diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e6c64a5f..23a29b457 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,27 +22,51 @@ jobs: include: - os: ubuntu-latest target: debug + compiler: gcc - os: ubuntu-latest target: release + compiler: gcc - os: macos-latest target: debug + compiler: clang - os: macos-latest target: release + compiler: clang steps: - uses: actions/checkout@v4 - name: Build (${{ matrix.target }}) - run: make ${{ matrix.target }} + run: make ${{ matrix.target }} CC=${{ matrix.compiler }} - # Tests build their own debug+ASan objects, so they only make sense after a - # debug build. Running `make test` after `make release` reuses the - # release-compiled src objects (no -DDEBUG), which omits DEBUG-only symbols - # like ray_check_null_invariant and fails to link. The release legs still - # verify the optimized build compiles + links; the debug legs run the tests. + # The embedding archive has its own .lib.o flags: binary-only builds + # do not exercise codec strict-FP overrides in that profile. + - name: Build static library + if: matrix.target == 'release' && matrix.compiler == 'gcc' + run: make -j2 lib CC=${{ matrix.compiler }} + + # Debug legs execute the sanitizer suite; release legs verify optimized + # artifacts. Runtime tests under release FP flags use the separate + # `make test-release` profile, not the debug suite below. - name: Test if: matrix.target == 'debug' - run: make test + run: make test CC=${{ matrix.compiler }} + + # The default Ubuntu compiler is gcc. Exercise the suite with a recent + # upstream Clang as well, so new -Werror diagnostics reach CI before users + # of rolling-release toolchains encounter them. + clang-current: + runs-on: ubuntu-latest + env: + RAY_MARCH: x86-64 + steps: + - uses: actions/checkout@v4 + - name: Install Clang 23 + run: | + wget -qO llvm.sh https://apt.llvm.org/llvm.sh + sudo bash llvm.sh 23 + - name: Test with Clang 23 + run: make test CC=clang-23 # The suite with every assert() compiled out (-DNDEBUG). Our own builds keep # asserts on, but CMake Release, distro packagers and `zig cc` define NDEBUG; @@ -148,15 +172,16 @@ jobs: # skipped required check can be treated as passed, silently opening the gate. # static-analysis is intentionally NOT in `needs` — it is advisory only. ci-success: - needs: [build-and-test, ndebug, fuzz-smoke, tsan] + needs: [build-and-test, clang-current, ndebug, fuzz-smoke, tsan] if: always() runs-on: ubuntu-latest steps: - name: Verify all required jobs passed run: | bt='${{ needs.build-and-test.result }}' + cl='${{ needs.clang-current.result }}' nd='${{ needs.ndebug.result }}' fz='${{ needs.fuzz-smoke.result }}' ts='${{ needs.tsan.result }}' - echo "build-and-test: $bt ndebug: $nd fuzz-smoke: $fz tsan: $ts" - [ "$bt" = "success" ] && [ "$nd" = "success" ] && [ "$fz" = "success" ] && [ "$ts" = "success" ] || exit 1 + echo "build-and-test: $bt clang-current: $cl ndebug: $nd fuzz-smoke: $fz tsan: $ts" + [ "$bt" = "success" ] && [ "$cl" = "success" ] && [ "$nd" = "success" ] && [ "$fz" = "success" ] && [ "$ts" = "success" ] || exit 1 diff --git a/.gitignore b/.gitignore index ef87b0142..9fe0426f9 100644 --- a/.gitignore +++ b/.gitignore @@ -53,6 +53,7 @@ compile_commands.json # Extra build flavours (see Makefile) rayforce.tsan rayforce.test.tsan +rayforce.test.rel # Fuzzing: grown corpus and crash artifacts stay local; only fuzz/seeds/ is committed fuzz/corpus/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cbbaf68d7..c510bdc0a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,6 +41,10 @@ See [RELEASE.md](RELEASE.md) for how releases are cut. ## Local build notes - Zero external dependencies; C17 toolchain only. +- `make` compiles with `clang` when `CC` is not set, so a machine without clang + fails at the first compile. `make CC=gcc` (or `CC=gcc` in the environment) + builds with gcc. The fuzz, TSan, coverage and `compdb` targets use clang + regardless of `CC`. - Debug builds enable AddressSanitizer + UndefinedBehaviorSanitizer; warnings are errors (`-Werror -Wall -Wextra`). A warning will fail CI, so fix them locally. - The version reported by a local build is derived from git tags (`0.0.0` on an @@ -96,6 +100,12 @@ The debug binaries load the ASan runtime DLL from `clang64\bin`, so keep it on Beyond the ASan/UBSan test run, the repo carries a stability toolset. These gate CI (fuzz smoke + TSan on every PR) and run deeper overnight. +Each PR is built with these compilers (`.github/workflows/ci.yml`): gcc for +the Ubuntu debug and release legs, clang for the macOS debug and release +legs, upstream Clang 23 from apt.llvm.org for the Ubuntu `clang-current` test +leg, and the Ubuntu runner's `clang` for the NDEBUG, fuzz-smoke and TSan +legs. + - **Fuzzing** (Linux + clang): coverage-guided targets under `fuzz/` cover the parser, numeric scanners, the binary wire/journal decoder, and the sandboxed evaluator, CSV, and journal-replay paths. `make fuzz-smoke` is the PR gate; diff --git a/Makefile b/Makefile index 2fbaff3ae..1402e6147 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,8 @@ -CC ?= clang +# GNU make predefines CC=cc, so ?= cannot select clang as the default. +# Keep command-line and environment overrides intact. +ifeq ($(origin CC),default) +CC = clang +endif # Some targets need clang specifically regardless of $(CC): the fuzzing # runtime (-fsanitize=fuzzer) and -MJ compilation-database fragments are # clang-only. Same precedent as `make coverage`, which pins CC=clang. @@ -25,12 +29,14 @@ VERSION_MAJOR := $(word 1,$(subst ., ,$(RAY_VERSION))) VERSION_MINOR := $(word 2,$(subst ., ,$(RAY_VERSION))) VERSION_PATCH := $(word 3,$(subst ., ,$(RAY_VERSION))) GIT_HASH := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown") -# The objects that embed GIT_HASH depend on a stamp rewritten only when the -# hash changes, so an incremental build after a new commit rebuilds them -# instead of keeping the previous hash (see GIT_HASH_OBJS below). -GIT_HASH_STAMP := build/.git-hash -$(shell mkdir -p build && { [ "$$(cat $(GIT_HASH_STAMP) 2>/dev/null)" = "$(GIT_HASH)" ] || echo "$(GIT_HASH)" > $(GIT_HASH_STAMP); }) BUILD_DATE := $(shell date -u +%Y-%m-%d) +# The objects that embed the build information (commit, version, build date) +# depend on a stamp rewritten only when one of them changes, so an incremental +# build after a new commit, a RAY_VERSION override or a new day rebuilds them +# instead of keeping the previous values (see BUILD_INFO_OBJS below). +BUILD_INFO := $(GIT_HASH) $(RAY_VERSION) $(BUILD_DATE) +BUILD_INFO_STAMP := build/.build-info +$(shell mkdir -p build && { [ "$$(cat $(BUILD_INFO_STAMP) 2>/dev/null)" = "$(BUILD_INFO)" ] || echo "$(BUILD_INFO)" > $(BUILD_INFO_STAMP); }) WARNS = -Wall -Wextra -Werror -Wstrict-prototypes -Wno-unused-parameter DEFS = -DRAYFORCE_GIT_COMMIT=\"$(GIT_HASH)\" -DRAYFORCE_BUILD_DATE=\"$(BUILD_DATE)\" \ @@ -58,6 +64,10 @@ DEBUG_CFLAGS = -fPIC $(WARNS) -std=$(STD) -g -O0 -march=$(RAY_MARCH) -DDEBUG \ RELEASE_CFLAGS = -fPIC $(WARNS) -std=$(STD) -O3 -march=$(RAY_MARCH) \ -funroll-loops -fomit-frame-pointer -fno-math-errno -falign-functions=64 \ -fassociative-math -ffp-contract=fast -fno-signed-zeros -fno-trapping-math +# -ffunction-sections/-fdata-sections: isolate code/data so static-library +# clients can discard unused sections with linker GC. Keep this library-only: +# the server keeps nearly all code live and gains little from these flags. +LIB_CFLAGS = $(RELEASE_CFLAGS) -ffunction-sections -fdata-sections # -falign-functions=64: start every function on a cache line. The default # 16-byte alignment makes hot leaf functions' cost depend on where unrelated # edits elsewhere in the same translation unit happen to push them — @@ -152,6 +162,15 @@ HARDENED_CFLAGS = -fPIC $(WARNS) -std=$(STD) -O3 -march=$(RAY_MARCH) -g \ # the whole suite that way. NDEBUG_CFLAGS = $(DEBUG_CFLAGS) -DNDEBUG +# Strict IEEE arithmetic for the ALP / ALP_RD codec (compressed-columns P5): +# its decode is a fixed expression (spec "ALP") and must give the same bits +# in every build profile, so reassociation, contraction and signed-zero +# folding are switched off for these objects only. Applied LAST on each +# pattern rule's command line, so it overrides the profile's fast-math flags. +STRICT_FP_CFLAGS := -fno-fast-math -fno-unsafe-math-optimizations -fno-associative-math \ + -fno-reciprocal-math -fsigned-zeros -ffp-contract=off +FP_STRICT_src/store/enc_alp := $(STRICT_FP_CFLAGS) + CFLAGS = $(DEBUG_CFLAGS) LDFLAGS = $(DEBUG_LDFLAGS) @@ -166,6 +185,7 @@ TEST_OBJ = $(TEST_SRC:.c=.o) # Per-flavour object lists (see the flavour CFLAGS block above). REL_LIB_OBJ = $(LIB_SRC:.c=.rel.o) +LIB_LIB_OBJ = $(LIB_SRC:.c=.lib.o) REL_MAIN_OBJ = $(MAIN_SRC:.c=.rel.o) FUZZ_LIB_OBJ = $(LIB_SRC:.c=.fuzz.o) TSAN_LIB_OBJ = $(LIB_SRC:.c=.tsan.o) @@ -176,48 +196,63 @@ HARD_MAIN_OBJ = $(MAIN_SRC:.c=.hard.o) NDEBUG_LIB_OBJ = $(LIB_SRC:.c=.ndebug.o) NDEBUG_MAIN_OBJ = $(MAIN_SRC:.c=.ndebug.o) NDEBUG_TEST_OBJ = $(TEST_SRC:.c=.ndebug.o) +RELT_LIB_OBJ = $(LIB_SRC:.c=.reltest.o) +RELT_TEST_OBJ = $(TEST_SRC:.c=.reltest.o) # Auto-generated header dependencies (one .d per .o, see DEPFLAGS). # The fragments are -included at the very END of this file — including # them here would let a .d's first rule (e.g. `foo.o: ...`) become the # default goal, so bare `make` would build one object instead of `debug`. DEPS = $(LIB_OBJ:.o=.d) $(MAIN_OBJ:.o=.d) $(TEST_OBJ:.o=.d) \ - $(REL_LIB_OBJ:.o=.d) $(REL_MAIN_OBJ:.o=.d) \ + $(REL_LIB_OBJ:.o=.d) $(REL_MAIN_OBJ:.o=.d) $(LIB_LIB_OBJ:.o=.d) \ $(FUZZ_LIB_OBJ:.o=.d) \ $(TSAN_LIB_OBJ:.o=.d) $(TSAN_MAIN_OBJ:.o=.d) $(TSAN_TEST_OBJ:.o=.d) \ $(HARD_LIB_OBJ:.o=.d) $(HARD_MAIN_OBJ:.o=.d) \ - $(NDEBUG_LIB_OBJ:.o=.d) $(NDEBUG_MAIN_OBJ:.o=.d) $(NDEBUG_TEST_OBJ:.o=.d) + $(NDEBUG_LIB_OBJ:.o=.d) $(NDEBUG_MAIN_OBJ:.o=.d) $(NDEBUG_TEST_OBJ:.o=.d) \ + $(RELT_LIB_OBJ:.o=.d) $(RELT_TEST_OBJ:.o=.d) # Default target (pinned so an -included .d fragment can't steal it). .DEFAULT_GOAL := default default: debug %.o: %.c - $(CC) -c $(CFLAGS) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + $(CC) -c $(CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< %.rel.o: %.c - $(CC) -c $(RELEASE_CFLAGS) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + $(CC) -c $(RELEASE_CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + +%.lib.o: %.c + $(CC) -c $(LIB_CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< %.fuzz.o: %.c - $(CLANG) -c $(FUZZ_CFLAGS) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + $(CLANG) -c $(FUZZ_CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< # TSan objects build with clang: gcc's -Werror=tsan rejects standalone # atomic_thread_fence (src/core/platform.h), which clang instruments fine. %.tsan.o: %.c - $(CLANG) -c $(TSAN_CFLAGS) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + $(CLANG) -c $(TSAN_CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< %.hard.o: %.c - $(CC) -c $(HARDENED_CFLAGS) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + $(CC) -c $(HARDENED_CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< %.ndebug.o: %.c - $(CC) -c $(NDEBUG_CFLAGS) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< - -# Sources that embed GIT_HASH (ray_git_commit, the REPL and crash banners, -# and the test that compares ray_git_commit against it), in every object -# flavour. -GIT_HASH_SRCS := src/core/types src/app/repl src/core/crash test/test_types -GIT_HASH_OBJS := $(foreach v,.o .rel.o .fuzz.o .tsan.o .hard.o .ndebug.o,$(addsuffix $(v),$(GIT_HASH_SRCS))) -$(GIT_HASH_OBJS): $(GIT_HASH_STAMP) + $(CC) -c $(NDEBUG_CFLAGS) $(FP_STRICT_$*) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + +# The C suite in the RELEASE FP profile (`make test-release`). Its own object +# flavour: the release flags plus -DDEBUG, because the suite calls test +# seams compiled only under DEBUG (platform.h, ipc.h, lang/internal.h); +# -DDEBUG changes no FP flag. The codec object gets the strict group as +# in every flavour; test sources are compiled with strict FP too, so their +# literals (e.g. -0.0) mean what they say. No sanitizers. +%.reltest.o: %.c + $(CC) -c $(RELEASE_CFLAGS) -DDEBUG $(FP_STRICT_$*) $(if $(filter test/%,$<),$(STRICT_FP_CFLAGS) -Itest) $(DEPFLAGS) $(DEFS) $(INCLUDES) -o $@ $< + +# Sources that embed the build information (ray_git_commit and the version +# accessors, the REPL and crash banners, .sys.build, and the test that compares +# ray_git_commit against GIT_HASH), in every object flavour. +BUILD_INFO_SRCS := src/core/types src/app/repl src/core/crash src/ops/system test/test_types +BUILD_INFO_OBJS := $(foreach v,.o .rel.o .lib.o .fuzz.o .tsan.o .hard.o .ndebug.o .reltest.o,$(addsuffix $(v),$(BUILD_INFO_SRCS))) +$(BUILD_INFO_OBJS): $(BUILD_INFO_STAMP) # Main binary for debug/test (some tests spawn ./$(TARGET) as a server). $(TARGET): $(LIB_OBJ) $(MAIN_OBJ) @@ -234,8 +269,9 @@ release: $(REL_LIB_OBJ) $(REL_MAIN_OBJ) $(CC) $(RELEASE_CFLAGS) -o $(TARGET) $(REL_LIB_OBJ) $(REL_MAIN_OBJ) $(LIBS) $(RELEASE_LDFLAGS) # Static library -lib: $(REL_LIB_OBJ) - $(AR) rc lib$(TARGET).a $(REL_LIB_OBJ) +lib: $(LIB_LIB_OBJ) + rm -f lib$(TARGET).a + $(AR) rc lib$(TARGET).a $(LIB_LIB_OBJ) # Release tarball: build the optimized binary and package it as # dist/rayforce---.tar.gz plus a SHA-256 checksum. @@ -279,6 +315,26 @@ test-ndebug: $(NDEBUG_LIB_OBJ) $(NDEBUG_MAIN_OBJ) $(NDEBUG_TEST_OBJ) $(CC) $(NDEBUG_CFLAGS) -o $(TARGET).test $(NDEBUG_LIB_OBJ) $(NDEBUG_TEST_OBJ) $(LIBS) $(DEBUG_LDFLAGS) -Itest RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test $(TEST_ARGS) +# The suite over the .reltest.o flavour (see its pattern rule). Does not +# relink ./$(TARGET): tests that spawn it get whatever build is on disk. +test-release: $(RELT_LIB_OBJ) $(RELT_TEST_OBJ) + $(CC) $(RELEASE_CFLAGS) -o $(TARGET).test.rel $(RELT_LIB_OBJ) $(RELT_TEST_OBJ) $(LIBS) $(RELEASE_LDFLAGS) + RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test.rel $(TEST_ARGS) + +# Multi-GiB generation-2 STR pool limits (spec "Large data"). Needs ~10 GiB +# of RAM and ~5 GiB of free space under /tmp. +test-large: CFLAGS = $(DEBUG_CFLAGS) +test-large: LDFLAGS = $(DEBUG_LDFLAGS) +test-large: $(LIB_OBJ) $(MAIN_OBJ) $(TEST_OBJ) + $(CC) $(CFLAGS) -o $(TARGET).test $(LIB_OBJ) $(TEST_OBJ) $(LIBS) $(LDFLAGS) -Itest + RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test -f large/ + +# Generation-2 wire structs compile to the same layout on wasm32 (no libc +# needed: test/wasm/stub supplies the three string.h declarations). +check-wasm32-layout: + clang --target=wasm32 -ffreestanding -fsyntax-only -std=c17 -Wall -Werror \ + -Itest/wasm/stub -Isrc -Iinclude test/wasm/layout_check.c + # ─── ThreadSanitizer ──────────────────────────────────────────────── # Data-race detection for the lock-free pool/heap paths, which the # default ASan build cannot see (ASan and TSan are mutually exclusive, @@ -464,12 +520,13 @@ cppcheck: .PHONY: tidy cppcheck clean: - -rm -f $(LIB_OBJ) $(MAIN_OBJ) $(TEST_OBJ) $(REL_LIB_OBJ) $(REL_MAIN_OBJ) + -rm -f $(LIB_OBJ) $(MAIN_OBJ) $(TEST_OBJ) $(REL_LIB_OBJ) $(REL_MAIN_OBJ) $(LIB_LIB_OBJ) -rm -f $(FUZZ_LIB_OBJ) $(TSAN_LIB_OBJ) $(TSAN_MAIN_OBJ) $(TSAN_TEST_OBJ) \ $(HARD_LIB_OBJ) $(HARD_MAIN_OBJ) \ - $(NDEBUG_LIB_OBJ) $(NDEBUG_MAIN_OBJ) $(NDEBUG_TEST_OBJ) + $(NDEBUG_LIB_OBJ) $(NDEBUG_MAIN_OBJ) $(NDEBUG_TEST_OBJ) \ + $(RELT_LIB_OBJ) $(RELT_TEST_OBJ) -rm -f $(DEPS) - -rm -f $(TARGET) $(TARGET).test lib$(TARGET).a + -rm -f $(TARGET) $(TARGET).test $(TARGET).test.rel lib$(TARGET).a -rm -f $(TARGET).tsan $(TARGET).test.tsan -rm -rf build build_release build_fuzz build_compdb dist # Test-generated fixtures (see test/rfl/system/*.rfl) — should not linger after a run. @@ -478,7 +535,7 @@ clean: -rm -f cov-*.profraw default.profraw coverage.profdata -rm -rf coverage_html -.PHONY: default debug release lib dist test test-ndebug coverage compdb tsan tsan-test hardened fuzz-smoke tidy cppcheck clean +.PHONY: check-wasm32-layout default debug release lib dist test test-ndebug test-release test-large coverage compdb tsan tsan-test hardened fuzz-smoke tidy cppcheck clean # Header dependencies last: .d fragments only add prerequisites to the # object targets above, and being last they can't hijack the default goal. diff --git a/README.md b/README.md index cdb89f803..f1af85953 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,9 @@ make test # run full test suite ./rayforce # start the Rayfall REPL ``` +`make` compiles with `clang` when `CC` is not set; `make CC=gcc` (or `CC=gcc` +in the environment) builds with gcc. + ## Rayfall REPL Rayforce ships with **Rayfall** — a Lisp-like query language with a rich set @@ -140,6 +143,45 @@ int main(void) { } ``` +## Embedding + +`make lib` builds the engine as a static library, `librayforce.a`, with no +dependencies beyond libc, libm and pthreads. The build compiles library +objects with `-ffunction-sections -fdata-sections` (the Makefile's +`LIB_CFLAGS` flavour, applied automatically to the `.lib.o` objects that go +into the archive), so no extra flags are needed at this step. + +To discard everything your code never reaches, pass `-Wl,--gc-sections` to +the linker on the final link, and `-s` to strip the result. A DAG-route +client, meaning one that builds and executes query plans through the +`ray_graph_*`, `ray_scan` and `ray_execute` C API and never calls +`ray_eval_str` or loads `.rfl` files, never touches the Rayfall parser, +compiler, REPL or IPC server, and section GC drops that whole surface +(mixing the two routes pulls the parser back in): + +```sh +make clean && make lib +cc -O2 -Iinclude -Isrc examples/analytics.c librayforce.a \ + -lm -lpthread -Wl,--gc-sections -s -o analytics +``` + +The command above is the Linux one. On macOS, use `-Wl,-dead_strip` in +place of `-Wl,--gc-sections` (the Makefile's platform block does the same +for its own release links). On MinGW, link the winsock libraries as well: +`-lws2_32 -lmswsock -lkernel32 -ladvapi32`, with the same section-GC flag +the toolchain accepts. + +A checkout at the current commit links `analytics.c` to a 3.47 MB +stripped binary, from a 10.22 MB archive; sizes move with the tree, so +this is just one measurement, not a bound. + +Memory follows consumed-argument conventions documented per function in +the headers: arguments marked `consumes` are released by the call, and +returns marked `borrowed` stay owned by the container. On error paths the +library releases the references it holds. Values are COW, managed with +`ray_retain`/`ray_release`; error objects are owned and freed with +`ray_error_free`. + ## How It Works **Build** — Construct a lazy DAG: scans, filters, joins, aggregations, window diff --git a/bench/cell_append/README.md b/bench/cell_append/README.md new file mode 100644 index 000000000..dc88b0b56 --- /dev/null +++ b/bench/cell_append/README.md @@ -0,0 +1,49 @@ +# Reserved-capacity append cost + +This POSIX C-API microbenchmark isolates an append that does **not** resize. +It allocates and touches the destination before timing, then validates every +value (or LIST slot) after timing. It is not a whole-engine or ingestion benchmark, +and does not measure the memory benefit or cost of natural capacity growth. + +Linux build/run example: + +```sh +make -j4 lib +clang -std=c17 -O3 -march=native -DNDEBUG -Iinclude \ + bench/cell_append/append.c librayforce.a -rdynamic -lpthread -lm -ldl \ + -o /tmp/cell-append +RAYFORCE_CORES=0 taskset -c 0 /tmp/cell-append vec 2000000 +``` + +Cases: `vec` (single I64 append), `raw` (raw append with count1), `list` +(repeated retained object), `bulk` (raw batches of4096). Choose an allowed CPU +instead of0 where necessary. `RAYFORCE_CORES=0` disables background helpers. +Build every compared archive with the same compiler/flags. Do not time alongside +builds or sanitizer tests. Run one discarded fresh process per variant/case, +then randomize five further fresh processes per variant/case and retain samples. +The project `make lib` optimized flags, not a debug/sanitizer archive, were used. + +## Local observation, 2026-10-21 + +Ubuntu24/x86-64, i7-6700, Clang18, one pinned logical CPU, shared host and +uncontrolled frequency governor. Medians of five fresh processes after warm-up; +2,000,000 elements, preallocated/pre-touched buffers, full validation outside timing: + +| Case | accepted646, ms | this change, ms | +|---|---:|---:| +| Single vector append |27.186|23.535| +| Single LIST append |15.343|12.065| +| Raw count1 |30.934|30.495| +| Raw batch4096 |0.919|0.869| + +The raw paths are deliberately unchanged; their overlapping sample ranges do +**not** establish an improvement. This is a workload-specific result, not a +no-regression or general speedup guarantee. A synthetic accepted646 tree with +only #925's production changes reversed was also compared: it showed that the +ordinary-path work added by that change was measurable even without resizing. +It is not an accepted historical release or an alternative proposed fix. + +A first experiment only moved arithmetic below the capacity branch. That helped +vector append but left LIST's enlarged register-save frame. Outlining the rare +geometry/allocation path removed that remaining common-path cost. The actual +allocation sizing policy and externally requested raw-count preflight remain. diff --git a/bench/cell_append/append.c b/bench/cell_append/append.c new file mode 100644 index 000000000..06ea0dd6f --- /dev/null +++ b/bench/cell_append/append.c @@ -0,0 +1,24 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +static double now(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return(double)t.tv_sec+1e-9*t.tv_nsec;} +int main(int argc,char**argv){ + if(argc!=3)return 1;const char*kind=argv[1];int64_t n=strtoll(argv[2],NULL,10);if(n<1||n>10000000)return 2; + ray_runtime_t*rt=ray_runtime_create(0,NULL);if(!rt)return 3; + int list=!strcmp(kind,"list"),raw=!strcmp(kind,"raw"),bulk=!strcmp(kind,"bulk"); + ray_t*v=list?ray_list_new(n):ray_vec_new(RAY_I64,n);if(!v||RAY_IS_ERR(v))return 4; + memset(ray_data(v),0,(size_t)n*8);int64_t seed=7;ray_t*item=list?ray_vec_from_raw(RAY_I64,&seed,1):NULL;if(list&&(!item||RAY_IS_ERR(item)))return 5; + int64_t block[4096];for(int i=0;i<4096;i++)block[i]=7; + double start=now(); + if(list){for(int64_t i=0;ilen!=n)return 6; + for(int64_t i=0;i report.txt + +Run on a parted database (one subdirectory per partition, each holding /): + + build/compress_estimate --db /path/to/parted --table hits --preds bench/compress_estimate/predicates.txt \ + --keep-index UserID > report.txt + +Report lines: `col` (per column: raw, encoded, ratio, index bytes), `pred` (parsed predicates), +`sym` (symfile FSST estimate, decompressed snapshot bytes, decode time), `group` (skip rates per +predicate group), `mix_fraction_of_vectors` (encoding mix, share of vectors per encoding, not of bytes), `breakdown` (whole table), `scenario` (sizes and the +combined-score factor at the size weight 0.1). + +The engine's index sites do not consult parted segment indexes, so on a parted root the +skip rates and index sizes describe what the files would allow, not what the engine uses today +(the program prints a `note` line in that case). + +## Per-query index use + +Which persisted indexes each ClickBench query actually consults (via `.idx.uses`), on a +splayed table (directly or through a `.current` generation; a parted root exits 2 with a warning): + + make release + bench/compress_estimate/index_use.sh /path/to/splayed hits [../ClickBench/rayforce/queries.rfl] + +Prints `query_no{column:count ...}`; `{}` means no index was consulted. `RAY_BIN` +overrides `./rayforce`. Note that `(count (select ...))` is fused by the engine and does not +reach the index sites, so it reports `{}` even with a matching index. diff --git a/bench/compress_estimate/RESULTS.md b/bench/compress_estimate/RESULTS.md new file mode 100644 index 000000000..9d85c5c9e --- /dev/null +++ b/bench/compress_estimate/RESULTS.md @@ -0,0 +1,4370 @@ +# Compressed-columns P0 measurements and gate decision + +## Machine and commit + +- build commit a8a3e5e6 (the commit the release binaries were built at; branch feat/compressed-columns, worktree compress-p0; RESULTS.md and estimator changes are in later commits) +- 8 cores (`nproc`), 62 GB RAM (`free -g`), kernel 6.8.0-100-generic +- Store: local 10M splayed ClickBench table, /skull/clickbench/rfsplayed, 9 999 505 rows, 105 columns, symfile at `/.sym` +- The 100M store was unavailable (user ruling); no remote machine was used. The submission's parted store (/skull/tmp/rayforce_tests/current) does not exist locally and was not run. +- Estimator runtime on the 10M store: 86 s, single run. + +Note on indexes: the store has no separate index files; HASH indexes are attached to the column files. Five columns carry one (WatchID, ClientEventTime, FUniqID, RefererHash, URLHash). UserID has none in this store (the estimator was run with `--keep-index UserID`, as the brief says, so that scenario treats UserID's index as kept). + +## Whole-table breakdown (10M) + +``` +breakdown rows=9999505 data=3599827376 index=1141598560 sym=1207249691 other=2312 total=5948677939 +scenario today bytes=5948677939 size_ratio=1.000 score_factor=1.0000 +scenario columns encoded bytes=3216322795 size_ratio=1.850 score_factor=0.9404 +scenario columns + sym fsst bytes=2673652592 size_ratio=2.225 score_factor=0.9231 +scenario columns + sym fsst + kept ix bytes=1532056784 size_ratio=3.883 score_factor=0.8731 +``` + +The estimator's "kept ix" scenario keeps only the UserID index (none exists). The measured index use below says RefererHash and URLHash must be kept, which adds 194 915 360 + 195 932 480 bytes: 1 922 904 624 bytes, ratio 3.094, score factor 0.8932 (3.094^-0.1; the factors above follow ratio^-0.1). + +## Per-type column ratios (sum of `col` lines; encoded includes null bitmaps and DICT) + +| type | columns | raw bytes | encoded bytes | ratio | index bytes | +|---|---|---|---|---|---| +| I16 | 48 | 959 955 456 | 140 403 592 | 6.84 | 132 096 | +| I32 | 19 | 759 963 520 | 128 670 000 | 5.91 | 52 288 | +| I64 | 6 | 479 976 576 | 260 169 848 | 1.84 | 1 034 508 992 | +| SYM (ids) | 28 | 1 119 945 456 | 152 978 952 | 7.32 | 0 | +| TIMESTAMP | 3 | 239 988 288 | 184 686 800 | 1.30 | 106 902 432 | +| DATE | 1 | 39 998 080 | 563 040 | 71.04 | 2 752 | +| **all** | 105 | 3 599 827 376 | 867 472 232 | **4.150** | 1 141 598 560 | + +Columns that barely compress (ratio below 1.5): WatchID 0.99, HID 1.03, RefererHash 1.03, URLHash 1.18, ClientEventTime 1.20, TIMESTAMP EventTime/LocalEventTime 1.35, RefererCategoryID 1.35, Referer 1.41, URL 1.47 (SYM id columns). Full `col` lines are in /tmp/ce_10m.txt (106 lines, not committed). + +## Encoding mix (fraction of vectors, not of bytes) + +``` +RAW 0.0370 CONST 0.3960 FOR_BP 0.1639 DELTA_BP 0.0001 RLE 0.3836 DICT 0.0194 +``` + +## Predicate groups (skip rates) + +`undecided_bytes` is the encoded bytes of the vectors undecided under the combined decision of all predicates of the group (the earlier run summed a running, per-predicate state). + +``` +group g_adv chunk_decided=0.0721 vector_decided=0.1840 undecided=0.7439 pred_bytes=793464 undecided_bytes=773448 +group g_mpm chunk_decided=0.0000 vector_decided=0.0725 undecided=0.9275 pred_bytes=1284168 undecided_bytes=1278504 +group g_sp chunk_decided=0.0000 vector_decided=0.0140 undecided=0.9860 pred_bytes=11463472 undecided_bytes=11462376 +group g_url chunk_decided=0.8296 vector_decided=0.1468 undecided=0.0236 pred_bytes=26816336 undecided_bytes=612656 +group g_ref chunk_decided=0.0000 vector_decided=0.0002 undecided=0.9998 pred_bytes=27909920 undecided_bytes=27905040 +group g_user chunk_decided=0.7013 vector_decided=0.2745 undecided=0.0243 pred_bytes=16247048 undecided_bytes=1085416 +group g_q37 chunk_decided=0.9279 vector_decided=0.0107 undecided=0.0614 pred_bytes=1765176 undecided_bytes=174096 +group g_q40 chunk_decided=0.9279 vector_decided=0.0107 undecided=0.0614 pred_bytes=82436744 undecided_bytes=5214784 +group g_q41 chunk_decided=0.9279 vector_decided=0.0107 undecided=0.0614 pred_bytes=69231040 undecided_bytes=5070064 +group g_q42 chunk_decided=0.9279 vector_decided=0.0107 undecided=0.0614 pred_bytes=1765176 undecided_bytes=174096 +``` + +All rows=9 999 505. The q37-q42 groups (CounterID == 62 plus a date range) are decided at chunk level for 92.8% of rows because the table is ordered by CounterID/EventDate. g_ref (Referer != 0) and g_sp/g_mpm/g_adv are mostly undecided: those predicates select a large share of rows. + +## Symfile + +``` +sym file=1207249691 fsst=664579488 ratio=1.82 snapshot=1274980311 decode_s=3.544 count=8466329 +``` + +FSST would shrink the symfile 1.82x. The decompressed snapshot is 1 274 980 311 bytes (1.056x the file); a single-thread decode of every block takes 3.544 s. + +## Per-query index use (actual consults via `.idx.uses`, 10M store) + +Queries 1-40 and 43: `{}`. Query 41: `{RefererHash:1}`. Query 42: `{URLHash:1}`. +Raw table is in /tmp/ce_iu_10m.tsv. `{}` means no index fast path was consulted; fused query shapes (for example `(count (select ...))`) never reach index sites and legitimately report `{}`. + +Parted tables never consult segment indexes. The benchmark submission uses a parted load, so segment indexes added by the converter to parted databases are never used by the submission as it runs today; the use counts above describe a splayed load only. + +## Extrapolation to 100M + +Method: linear in row count (x10.0 for 9 999 505 -> 99 997 497 rows). + +| item | 10M measured | x10.0 | spec 100M baseline | consistent? | +|---|---|---|---|---| +| column data raw | 3.60 GB | 36.0 GB | 36.0 GB | yes | +| column data encoded | 0.867 GB | 8.67 GB | 8.6 GB est. | yes (+1%) | +| ratio | 4.15x | | 4.1x | yes | +| HASH indexes | 1.14 GB | 11.4 GB | 11.7 GB | yes (-2.5%) | +| .sym | 1.207 GB | 12.1 GB (alt. 11.3 GB x 1.056 = 11.9 GB snapshot) | 11.3 GB | within 7% (symfile grows sub-linearly in distinct strings, not exactly linear; the 10M file is 1.07x of 1/10 of the 100M one) | + +Caveats: encoded size depends on chunk-level locality, so per-chunk behaviour is assumed unchanged at 10x rows (same data ordering, same chunk size; 100M column files are only more chunks). Index size is the hash table, close to linear in rows. The symfile and snapshot depend on distinct-string count, which is not guaranteed linear. Skip rates are ratios and do not extrapolate by row count; they are only valid if the 100M table has the same ordering. Decode time is extrapolated at 33-35 s only if per-block cost is flat. + +## Snapshot vs cold read, parallel decode, working set + +``` +sym file=1207249691 fsst=664579488 ratio=1.82 snapshot=1274980311 decode_s=3.570 sym_parallel_decode_s=0.667 threads=8 count=8466329 +``` + +- Cold read: could not be measured. `sudo -n tee /proc/sys/vm/drop_caches` failed (password required); not retried. Warm read of the symfile: 0.119 s for 1.2 GB. +- Decode of all blocks: 3.57 s single thread (about 360 MB/s), 0.667 s on 8 threads (5.4x; blocks are independent, work-stealing over 130 blocks; threads = online CPUs, no knob). +- 100M snapshot figure used throughout: 10x the measured 10M snapshot = 12.7 GB. The alternative 11.3 GB x 1.056 = 11.9 GB (spec symfile size times the measured snapshot/file ratio) differs by 7%; the 10x figure is used because it is the conservative one. Parallel decode at 100M, if per-block cost is flat and cores are 8: about 6.7 s (single-thread about 36 s). +- Benchmark working set, measured on the 10M splayed store with the release ./rayforce (`-t 8`, one process, `.db.splayed.get` once, all 43 queries once, script built like run.sh splits queries.rfl; 43 results, no errors): + - `/usr/bin/time -v`: Maximum resident set size 5 028 388 kB (4.8 GiB), wall 2.57 s, 0 major faults (page cache was warm). + - `/proc/PID/status` polled every 20 ms: peak RssAnon 3 053 956 kB (heap, 2.9 GiB) and peak RssFile 2 009 884 kB (mmapped column pages, evictable). Sampled peaks are lower bounds and need not coincide. + - The RssAnon peak includes today's symbol heap (offset table, atom array, touched atoms; the symfile itself is mmapped and counts in RssFile); it was not separated. + - Assumption: x10 for 100M, heap about 30.5 GB (not measured at 100M; heap does not necessarily scale linearly, e.g. hash-group state depends on distinct keys). File-backed column pages are counted as evictable page cache, not heap. + +## Re-run after the review fixes + +The estimator was changed and re-run on the same store: the FSST `lengths` slot is sized with RAW or FOR_BP only (plus the 8-byte child header), the VALUE_DICT charge now includes the side table (32 B) and a 32-aligned entry, and `undecided_bytes` comes from the final combined decisions. Changed: column encoded total 867 470 818 -> 867 472 232 (+1 414 B; I16 +702, I32 +384, I64 +216, TIMESTAMP +112; ratios unchanged to two decimals); symfile fsst 664 513 344 -> 664 579 488 (+66 144 B, +0.010%, ratio 1.82 unchanged); the three scenario byte counts moved by +1 414, +67 558 and +67 558 B, and no ratio or score factor changed at the printed precision (the keep-list scenario is 1 922 904 624 B, ratio 3.094). `undecided_bytes` fell for g_q37 and g_q42 (177 216 -> 174 096), g_q40 (6 069 864 -> 5 214 784) and g_q41 (5 910 280 -> 5 070 064); the other groups did not change. Index use re-run (`index_use.sh`, 43 queries): unchanged, only query 41 `{RefererHash:1}` and query 42 `{URLHash:1}`. Decode times vary run to run (single-thread 3.509 s, 8 threads 0.658 s). + +## Decisions + +- **P0 gate: PASS.** Column data is 4.15x smaller (3.60 GB -> 0.867 GB at 10M, in line with the spec's 4.1x at 100M), well above the 1.5x threshold; the whole-table breakdown and projection (1.85x columns only, 2.225x with sym FSST, 3.09x with index trimming) and per-query index use are reported. Caveat: 100M was not measured, only extrapolated. +- **PI input:** the keep list (RefererHash 194.9 MB, used by q41; URLHash 195.9 MB, used by q42) applies to splayed deployments only. On the parted load the submission uses, no segment index is consulted, so every converter-added index (all five, 1.14 GB at 10M, about 11.4 GB at 100M) is droppable. On a splayed load, WatchID (508.4 MB), FUniqID (135.2 MB) and ClientEventTime (106.9 MB) were never consulted: 750.5 MB of 1 141.6 MB at 10M (66%), about 7.5 GB at 100M. Only 2 of 43 queries consult any index, once each. Predicate group names are 0-based: g_qN is 1-based query N+1 (g_q37..g_q42 are queries 38..43), so g_q40 (RefererHash predicate) is query 41 and g_q41 (URLHash predicate) is query 42, matching the two index consults. +- **PS gate input:** the constraint that decides is memory headroom on 32 GB, not open latency. Open latency is small: parallel decode 0.667 s at 10M, about 6.7 s at 100M (single thread about 36 s). Memory: a full snapshot is a net heap addition of about 12.7 GB at 100M (minus the small offset table and atom array the engine already keeps, since the FILE symbol domain mmaps the symfile as page cache and materializes atoms lazily), on top of a heap extrapolated to about 30.5 GB (10M RssAnon peak 3.05 GB, x10 assumption). Today's symbol heap is not separated from that RssAnon peak. 30.5 + 12.7 is about 43 GB, far above 32 GB. The extrapolated heap leaves only about 1.5 GB headroom on 32 GB regardless of the PS choice. Encoded columns (8.67 GB) are file-backed and evictable so they do not count as heap. Recommendation: block cache (decode symbols on demand, bounded memory); the memory numbers strengthen it, and a full snapshot is not recommended on a 32 GB machine. PS steady state: by the spec's Bound rule a domain holds at most one decompressed snapshot (built at first open, never rebuilt for append flushes or conversions), so repeated appends and conversions do not grow it; only appended atoms add memory. + +## P1 measured sizes + +Release build, `bench/compress_estimate/p1_size.sh`: the 10M ClickBench splayed store (`.db.splayed.get`, 9 999 505 rows, 105 columns) re-saved with `{compress: true}` into a scratch directory, then per-column file sizes compared with the P0 estimator (`build/compress_estimate --db ... --keep-index UserID`, `col` lines: encoded bytes) on the same store. Size only, no timings. The scratch copy lives outside the repo and was removed after recording. + +Generations observed: 100 columns generation 2; WatchID, ClientEventTime, FUniqID, RefererHash and URLHash generation 0 and byte-identical to the source (588 420 000, 186 893 024, 215 227 840, 274 911 456, 275 928 576 B). This matches the expectation: a persisted HASH index keeps the column generation 0 until P4. + +| Group | Columns | gen-0 bytes | P1 bytes | P0 estimate | P1 / estimate | gen-0 / P1 | share of table column bytes | +|---|---|---|---|---|---|---|---| +| all generation-2 | 100 | 3 200 045 040 | 558 495 832 | 558 163 872 | 1.0006 | 5.73x | 67.5% | +| I16 | 48 | 960 087 552 | 140 403 584 | 140 403 592 | 1.0000 | 6.84x | 20.2% | +| I32 | 19 | 760 015 808 | 128 669 880 | 128 670 000 | 1.0000 | 5.91x | 16.0% | +| I64 | 2 | 159 997 696 | 17 323 136 | 17 323 128 | 1.0000 | 9.24x | 3.4% | +| SYM | 28 | 1 119 945 456 | 153 311 040 | 152 978 952 | 1.0022 | 7.31x | 23.6% | +| TIMESTAMP | 2 | 159 997 696 | 118 225 152 | 118 225 160 | 1.0000 | 1.35x | 3.4% | +| DATE | 1 | 40 000 832 | 563 040 | 563 040 | 1.0000 | 71.0x | 0.8% | + +The five largest per-column deltas (P1 minus estimate) are all small: UserAgentMinor +3 739 824 B (the whole SYM excess is 332 088 B net of savings elsewhere), Referer +832 320, SearchPhrase +166 624, OriginalURL +86 264, FlashMinor2 +73 304; every other column is within 16 B. + +Whole table (all files including `.sym` and `.d`, `du -sb`): generation 0 5 948 677 939 B, P1 3 307 128 731 B (1.80x). The `.sym` file is unchanged (1 207 249 691 B; symbol-file compression is not part of P1). The columns that stay generation 0 carry the inline HASH indexes (1.14 GB), so the 1.80x is the P1 floor before index policy (PI) and symfile work. + +Extrapolation to 100M (rows x10, same ordering and chunk behaviour assumed, `.sym` at the earlier 10x figure): gen-0 table about 59.5 GB, P1 table about 33.1 GB (generation-2 column data 5.6 GB, generation-0 indexed columns 15.4 GB, `.sym` 12.1 GB). Generation-2 columns alone: 32.0 GB -> 5.6 GB. + +## P1 gate decision + +**P1 size gate (size per P0): PASS.** Overall P1 / P0 estimate = 1.0006 (limit 1.10); the worst type with at least 1% of the table is SYM at 1.0022; generation-2 column data is 5.73x smaller than generation 0 (limit 1.5x). + +## PI index policy (10M store, release build, commit 2dcb78ae) + +Policy, fixed in the plan before measuring: converters stop persisting +auto-built HASH indexes; explicit `.idx.hash` is always honoured; parted +converters never auto-build segment HASH indexes; q41 / q42 stay unchanged +(identical results, warm within 5%), with an in-memory HASH built on first +use if needed. + +Stores: both converted from /skull/clickbench/hits_h.csv into +/home/hetoku/data/tmp/pi_bench (same filesystem), `conv_hash` by binary built +from detached copy of commit 2dcb78ae, `conv_nohash` by a second detached copy +of the same commit with the upgrade check returning 0 (measurement-only build, +not committed). Warm: 5 alternated rounds x 10 runs after a warm-up run in +each process. Cold: 5 runs, fresh process per run, page cache evicted before +each run by per-file POSIX_FADV_DONTNEED (dd iflag=nocache). Index use +verified with `.idx.uses`: conv_hash `{RefererHash:1}` / `{URLHash:1}`, +conv_nohash `{}` / `{}`. Result rows of q41 and q42 are identical across the +two stores (each store is also stable against itself). + +| query | warm hash ms | warm no-hash ms | warm ratio | cold hash ms | cold no-hash ms | cold ratio | +|---|---|---|---|---|---|---| +| q41 | 5.849 | 9.154 | 1.565 | 74.418 | 218.279 | 2.933 | +| q42 | 4.522 | 7.975 | 1.763 | 37.176 | 180.057 | 4.843 | + +Load (`.db.splayed.get`, cold): hash 3296.8 / 3301.1 ms (q41 / q42 runs), +no-hash 3272.1 / 3262.8 ms. + +| converter | wall s | peak RSS | store bytes | +|---|---|---|---| +| with upgrade | 16.57 | 5 356 888 kB | 5 948 945 203 | +| without upgrade | 14.74 | 4 492 028 kB | 4 807 577 107 | + +Per column (bytes with / without): WatchID 588 420 000 / 80 002 560, +ClientEventTime 186 893 024 / 80 002 560, FUniqID 215 227 840 / 80 002 560, +RefererHash 274 911 456 / 80 002 560, URLHash 275 928 576 / 80 002 560, +UserID 80 002 560 / 80 002 560 (no index in this store). + +Extrapolated to 100M (x 10.0): index bytes saved 11.4 GB, converter time saved 18.3 s. + +Informational (ruling C1), generation-2 store: `conv_gen2` = the no-hash +converter with `{compress: true}`; 25.97 s, peak RSS 4 492 372 kB, 2 074 724 107 +bytes (whole table); RefererHash 77 548 464 B, URLHash 68 057 128 B; both +queries consult no index (`{}`). q41 / q42 warm, alternated with the other two +stores (5 x 10 runs): hash 5.785 / 4.521 ms, no-hash 9.200 / 7.998 ms +(ratio 1.590 / 1.769), gen2 9.227 / 7.958 ms (ratio 1.595 / 1.760). A +generation-2 store therefore shows the same gap as the gen-0 no-hash store. +Parted loads never consult segment indexes (P0), so the submission path is +unaffected by PI; the driver measures splayed stores only. A resaved table +that already carries a HASH keeps it. + +**PI lazy build needed: yes** — q41 warm ratio 1.565, q42 warm ratio 1.763 (yes iff either exceeds 1.05). + +### PI index policy — gate (head 564368c6 vs dev) + +Script: `bench/compress_estimate/pi_gate.sh` (conversion, clause 1, measurement, +result identity) and `pi_gate.py` (tables and the gate line, printed from the +data, never typed). Head binary: release build of committed 564368c6 in a +detached copy; baseline: the dev release binary on a store its own converter +wrote (5 columns carry a persisted HASH: WatchID, ClientEventTime, FUniqID, +RefererHash, URLHash). Load kinds: splayed gen-0 (head store vs dev store), +splayed gen-2 (`{compress: true}`; dev has no generation 2, so the baseline +is the dev gen-0 store), parted (`.csv.parted`, 1 000 000 rows per +partition, head store vs dev store; both 4 807 844 987 B). All numbers come +from `.db.splayed.get` / `.db.parted.get` loads, release builds, 10M-row +ClickBench, all 43 queries. One fresh process per (kind, variant, query, round) +loads the store and runs the query 6 times (`timeit`, ms), head and baseline +alternated, order swapped every round, 5 rounds. First run = run 1 (fresh +process, warm page cache; median of rounds). 3-run total = runs 1..3 (median +of rounds). Warm = median of runs 2..6, best of the 5 rounds. A query is +"outside" when best-of-5 ratio > 1.05, the gap is at least 0.1 ms and the +median-of-rounds ratio is also > 1.05 (a 1 ms query moves 15% on jitter +alone); those over 1.05 but unconfirmed are listed as noise. Queries whose +best-of-5 was outside in the 5-round run (q25 gen-0; q20, q39 parted) were +re-measured with 15 rounds (confirm run replaces their rows): q25 1.056 +(gap 0.05 ms), q20 1.045, q39 1.048: within 5%. No cold run: the gate +asks for warm, first run and 3-run totals. Result text of every query is +identical head vs baseline on all three kinds (and head is stable against +itself). + +Converter (10M rows): gen-0 head 14.71 s, dev 16.23 s; store 4 807 577 107 B +(head) vs 5 948 945 203 B (dev) — byte count equal to Task 1's `nohash`; +gen-2 head 25.06 s, 2 074 724 107 B; parted head 27.38 s / dev 26.81 s, +equal size (parted never persisted hashes). +Clause 1: HASH columns on a fresh head conversion: gen-0 0, gen-2 0 +(dev gen-0: 5). + +q41 / q42 (the recorded deviation, ms head vs dev): splayed gen-0 warm +9.24 / 8.02 vs 5.87 / 4.66 (1.57x / 1.72x), first run 16.4 / 14.5 vs 13.5 / 11.0, +3-run 35.5 / 30.9 vs 25.7 / 20.5; gen-2 warm 1.57x / 1.73x (first run 86 / 82 +ms, decode); parted warm 17.6 / 13.4 vs 25.0 / 13.1 (0.70x / 1.03x), first run +39.1 / 24.4 vs 111.7 / 23.6: unchanged or better, parted never consults segment +indexes. Spec deviation: on splayed loads the lazy hash is built only after +accumulated scan work reaches its build cost, so q41/q42 run at scan speed. + +Findings other than the recorded q41/q42 deviation: +- splayed gen-2 first run is slower on every query (first-run total 7 740 ms + vs 2 586 ms, 3-run total 11 395 vs 6 228 ms, ratio 2.99 / 1.83): first + touch of a compressed column decodes it (e.g. q3 0.02 -> 18 ms); warm is + equal (1.005). Not index related; it is the cost of the compressed format + on the first query of a process. +- parted q16 (`group by UserID`) first run 145 ms vs 83 ms (1.73x, repeatable + in 15 rounds, 3-run 298 vs 233 ms); warm 1.03. Parted loads consult no + segment index, so this is not the index policy; not investigated here. +- q25 gen-0 and q20/q39 parted: noise (see above). + +``` +PI GATE: clause1 PASS ; clause2 splayed-gen0 FAIL (q41 1.6x, q42 1.7x warm; deviation recorded) ; clause2 splayed-gen2 FAIL (q41 1.6x, q42 1.7x warm; deviation recorded) ; clause2 parted PASS ; first run over 1.05x (informational): splayed-gen0 q41 q42; splayed-gen2 42 queries; parted q16 +``` + +Per-query tables (ms; ratio = head / baseline; ** = outside): +## splayed-gen0 (ms; head vs baseline; ratio = head/baseline) +| q | warm head | warm base | ratio | first head | first base | ratio | 3-run head | 3-run base | ratio | +|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.000 | 0.000 | 0.995 | 0.010 | 0.006 | 1.698 | 0.011 | 0.007 | 1.622 | +| q2 | 1.122 | 1.116 | 1.006 | 1.976 | 2.012 | 0.982 | 4.300 | 4.337 | 0.991 | +| q3 | 0.002 | 0.002 | 1.000 | 0.022 | 0.021 | 1.040 | 0.027 | 0.026 | 1.032 | +| q4 | 0.000 | 0.000 | 1.003 | 0.012 | 0.012 | 1.057 | 0.014 | 0.013 | 1.066 | +| q5 | 0.000 | 0.000 | 0.947 | 0.025 | 0.025 | 1.016 | 0.027 | 0.026 | 1.011 | +| q6 | 0.000 | 0.000 | 0.868 | 0.026 | 0.025 | 1.006 | 0.027 | 0.027 | 1.010 | +| q7 | 0.002 | 0.002 | 1.098 | 0.021 | 0.020 | 1.042 | 0.025 | 0.024 | 1.043 | +| q8 | 3.530 | 3.495 | 1.010 | 8.897 | 8.799 | 1.011 | 15.975 | 15.915 | 1.004 | +| q9 | 76.181 | 75.342 | 1.011 | 112.969 | 114.727 | 0.985 | 265.734 | 268.238 | 0.991 | +| q10 | 69.079 | 68.858 | 1.003 | 96.688 | 96.721 | 1.000 | 234.371 | 236.033 | 0.993 | +| q11 | 16.728 | 16.721 | 1.000 | 25.733 | 25.496 | 1.009 | 59.603 | 59.112 | 1.008 | +| q12 | 17.054 | 17.353 | 0.983 | 26.074 | 26.755 | 0.975 | 60.702 | 61.823 | 0.982 | +| q13 | 31.892 | 31.816 | 1.002 | 41.139 | 41.463 | 0.992 | 105.888 | 105.371 | 1.005 | +| q14 | 63.077 | 62.979 | 1.002 | 87.680 | 88.353 | 0.992 | 217.947 | 217.207 | 1.003 | +| q15 | 36.405 | 36.683 | 0.992 | 47.817 | 47.912 | 0.998 | 122.266 | 123.942 | 0.986 | +| q16 | 69.582 | 69.670 | 0.999 | 94.216 | 94.616 | 0.996 | 233.948 | 235.049 | 0.995 | +| q17 | 92.985 | 93.118 | 0.999 | 130.100 | 130.108 | 1.000 | 317.985 | 317.252 | 1.002 | +| q18 | 6.915 | 6.888 | 1.004 | 13.987 | 15.355 | 0.911 | 28.000 | 29.431 | 0.951 | +| q19 | 136.934 | 137.750 | 0.994 | 210.199 | 215.739 | 0.974 | 489.458 | 497.173 | 0.984 | +| q20 | 1.141 | 1.133 | 1.007 | 6.881 | 6.955 | 0.989 | 9.484 | 9.483 | 1.000 | +| q21 | 42.061 | 42.102 | 0.999 | 45.316 | 45.852 | 0.988 | 130.470 | 130.485 | 1.000 | +| q22 | 27.590 | 27.508 | 1.003 | 32.153 | 32.919 | 0.977 | 87.932 | 88.794 | 0.990 | +| q23 | 48.545 | 48.594 | 0.999 | 60.794 | 61.102 | 0.995 | 159.105 | 159.075 | 1.000 | +| q24 | 29.261 | 29.066 | 1.007 | 35.008 | 35.072 | 0.998 | 94.348 | 95.043 | 0.993 | +| q25 | 0.897 | 0.849 | 1.056 | 4.364 | 4.754 | 0.918 | 6.430 | 6.695 | 0.960 | +| q26 | 10.729 | 10.822 | 0.991 | 15.653 | 16.204 | 0.966 | 37.354 | 37.970 | 0.984 | +| q27 | 1.029 | 0.971 | 1.059 | 4.325 | 4.769 | 0.907 | 6.467 | 6.932 | 0.933 | +| q28 | 83.354 | 82.885 | 1.006 | 86.116 | 85.224 | 1.010 | 253.769 | 253.914 | 0.999 | +| q29 | 351.394 | 343.020 | 1.024 | 440.875 | 431.198 | 1.022 | 1153.210 | 1126.725 | 1.024 | +| q30 | 0.031 | 0.019 | 1.692 | 0.035 | 0.037 | 0.960 | 0.103 | 0.089 | 1.160 | +| q31 | 52.473 | 54.099 | 0.970 | 70.471 | 71.560 | 0.985 | 176.617 | 180.212 | 0.980 | +| q32 | 59.194 | 60.634 | 0.976 | 85.282 | 87.570 | 0.974 | 204.558 | 209.638 | 0.976 | +| q33 | 202.209 | 202.702 | 0.998 | 360.525 | 365.592 | 0.986 | 770.456 | 778.730 | 0.989 | +| q34 | 39.495 | 39.530 | 0.999 | 70.745 | 70.986 | 0.997 | 149.712 | 149.923 | 0.999 | +| q35 | 39.341 | 39.303 | 1.001 | 70.401 | 70.786 | 0.995 | 149.347 | 149.462 | 0.999 | +| q36 | 64.032 | 63.760 | 1.004 | 87.474 | 88.006 | 0.994 | 215.936 | 216.307 | 0.998 | +| q37 | 20.501 | 20.664 | 0.992 | 30.512 | 30.978 | 0.985 | 72.612 | 72.627 | 1.000 | +| q38 | 20.284 | 19.709 | 1.029 | 30.081 | 29.332 | 1.026 | 75.577 | 74.652 | 1.012 | +| q39 | 7.417 | 7.501 | 0.989 | 14.921 | 15.013 | 0.994 | 30.166 | 30.320 | 0.995 | +| q40 | 58.657 | 60.025 | 0.977 | 90.979 | 91.792 | 0.991 | 210.184 | 213.638 | 0.984 | +| q41 | 9.238 | 5.873 | 1.573 ** | 16.404 | 13.505 | 1.215 | 35.495 | 25.660 | 1.383 | +| q42 | 8.021 | 4.664 | 1.720 ** | 14.451 | 10.985 | 1.316 | 30.934 | 20.523 | 1.507 | +| q43 | 9.214 | 10.038 | 0.918 | 18.603 | 19.536 | 0.952 | 37.948 | 40.487 | 0.937 | +| total | 1807.6 | 1797.3 | 1.006 | 2590.0 | 2597.9 | 0.997 | 6254.5 | 6248.4 | 1.001 | +warm outside 1.05x (gap >= 0.1 ms): [('q41', 1.573), ('q42', 1.72)] +warm over 1.05x but not confirmed (gap < 0.1 ms or median-of-rounds ratio <= 1.05: noise): [('q7', 1.098), ('q25', 1.056), ('q27', 1.059), ('q30', 1.692)] +first run outside 1.05x (gap >= 0.1 ms): [('q41', 1.215), ('q42', 1.316)] +result text differs head vs baseline: stable-head diffs []; head unstable against itself (tie order) [] + +## splayed-gen2 (ms; head vs baseline; ratio = head/baseline) +| q | warm head | warm base | ratio | first head | first base | ratio | 3-run head | 3-run base | ratio | +|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.000 | 0.000 | 0.964 | 0.010 | 0.010 | 1.014 | 0.011 | 0.011 | 1.016 | +| q2 | 1.104 | 1.121 | 0.985 | 8.039 | 1.987 | 4.045 | 10.403 | 4.299 | 2.420 | +| q3 | 0.002 | 0.002 | 1.061 | 16.404 | 0.018 | 924.342 | 16.413 | 0.023 | 725.418 | +| q4 | 0.000 | 0.000 | 1.083 | 16.021 | 0.015 | 1040.824 | 16.024 | 0.017 | 970.616 | +| q5 | 0.001 | 0.000 | 1.333 | 16.420 | 0.025 | 667.112 | 16.424 | 0.026 | 631.219 | +| q6 | 0.000 | 0.000 | 1.080 | 15.530 | 0.025 | 630.336 | 15.533 | 0.026 | 594.766 | +| q7 | 0.001 | 0.002 | 0.894 | 6.240 | 0.020 | 310.868 | 6.244 | 0.024 | 256.419 | +| q8 | 3.512 | 3.523 | 0.997 | 14.850 | 9.006 | 1.649 | 21.999 | 16.224 | 1.356 | +| q9 | 75.863 | 75.058 | 1.011 | 133.561 | 113.886 | 1.173 | 287.482 | 266.015 | 1.081 | +| q10 | 68.559 | 68.151 | 1.006 | 137.883 | 96.636 | 1.427 | 275.705 | 235.166 | 1.172 | +| q11 | 16.757 | 16.706 | 1.003 | 49.883 | 25.638 | 1.946 | 83.839 | 59.410 | 1.411 | +| q12 | 17.157 | 17.336 | 0.990 | 56.519 | 26.398 | 2.141 | 91.613 | 61.785 | 1.483 | +| q13 | 31.921 | 31.887 | 1.001 | 56.916 | 41.234 | 1.380 | 122.126 | 106.666 | 1.145 | +| q14 | 62.836 | 63.276 | 0.993 | 117.868 | 88.924 | 1.325 | 246.660 | 217.423 | 1.134 | +| q15 | 36.555 | 36.344 | 1.006 | 71.562 | 47.824 | 1.496 | 145.571 | 122.149 | 1.192 | +| q16 | 69.706 | 69.872 | 0.998 | 109.395 | 94.294 | 1.160 | 249.223 | 234.507 | 1.063 | +| q17 | 92.708 | 92.969 | 0.997 | 160.109 | 130.087 | 1.231 | 346.961 | 316.677 | 1.096 | +| q18 | 6.924 | 6.847 | 1.011 | 38.133 | 15.057 | 2.533 | 52.550 | 28.966 | 1.814 | +| q19 | 137.279 | 137.730 | 0.997 | 258.030 | 209.278 | 1.233 | 536.660 | 490.246 | 1.095 | +| q20 | 1.143 | 1.166 | 0.980 | 22.558 | 6.741 | 3.347 | 25.155 | 9.359 | 2.688 | +| q21 | 41.928 | 42.038 | 0.997 | 61.725 | 46.995 | 1.313 | 145.674 | 133.471 | 1.091 | +| q22 | 27.498 | 27.541 | 0.998 | 78.190 | 32.041 | 2.440 | 133.508 | 87.356 | 1.528 | +| q23 | 48.661 | 48.790 | 0.997 | 122.894 | 60.647 | 2.026 | 220.996 | 158.771 | 1.392 | +| q24 | 29.021 | 29.044 | 0.999 | 1029.160 | 35.044 | 29.368 | 1087.650 | 93.295 | 11.658 | +| q25 | 0.888 | 0.967 | 0.918 | 1001.600 | 4.728 | 211.853 | 1003.839 | 6.622 | 151.589 | +| q26 | 10.745 | 10.842 | 0.991 | 1005.570 | 16.489 | 60.986 | 1027.331 | 38.339 | 26.796 | +| q27 | 0.896 | 0.961 | 0.932 | 995.396 | 4.739 | 210.045 | 997.483 | 6.682 | 149.277 | +| q28 | 82.987 | 82.819 | 1.002 | 108.232 | 85.585 | 1.265 | 275.128 | 251.898 | 1.092 | +| q29 | 351.880 | 343.977 | 1.023 | 458.004 | 430.144 | 1.065 | 1166.497 | 1123.256 | 1.038 | +| q30 | 0.019 | 0.019 | 1.000 | 10.440 | 0.036 | 286.173 | 10.513 | 0.100 | 104.953 | +| q31 | 52.867 | 54.150 | 0.976 | 122.678 | 71.107 | 1.725 | 230.587 | 180.355 | 1.279 | +| q32 | 59.079 | 60.640 | 0.974 | 146.874 | 86.700 | 1.694 | 266.680 | 210.969 | 1.264 | +| q33 | 201.737 | 202.704 | 0.995 | 406.545 | 365.183 | 1.113 | 814.983 | 775.678 | 1.051 | +| q34 | 39.386 | 39.291 | 1.002 | 86.553 | 70.668 | 1.225 | 165.755 | 149.809 | 1.106 | +| q35 | 39.354 | 39.354 | 1.000 | 86.359 | 70.292 | 1.229 | 165.070 | 149.801 | 1.102 | +| q36 | 63.575 | 63.701 | 0.998 | 99.095 | 87.737 | 1.129 | 227.293 | 215.882 | 1.053 | +| q37 | 20.657 | 20.713 | 0.997 | 74.320 | 30.524 | 2.435 | 118.112 | 72.365 | 1.632 | +| q38 | 19.702 | 19.614 | 1.005 | 76.263 | 29.939 | 2.547 | 118.735 | 75.052 | 1.582 | +| q39 | 7.483 | 7.486 | 1.000 | 62.670 | 14.878 | 4.212 | 78.000 | 30.122 | 2.589 | +| q40 | 58.813 | 59.841 | 0.983 | 169.767 | 91.258 | 1.860 | 288.556 | 212.414 | 1.358 | +| q41 | 9.114 | 5.794 | 1.573 ** | 86.463 | 13.239 | 6.531 | 105.528 | 25.505 | 4.138 | +| q42 | 7.955 | 4.600 | 1.729 ** | 81.636 | 11.268 | 7.245 | 97.989 | 20.789 | 4.713 | +| q43 | 9.256 | 10.101 | 0.916 | 63.617 | 19.562 | 3.252 | 82.567 | 40.387 | 2.044 | +| total | 1805.5 | 1797.0 | 1.005 | 7740.0 | 2585.9 | 2.993 | 11395.1 | 6227.9 | 1.830 | +warm outside 1.05x (gap >= 0.1 ms): [('q41', 1.573), ('q42', 1.729)] +warm over 1.05x but not confirmed (gap < 0.1 ms or median-of-rounds ratio <= 1.05: noise): [('q3', 1.061), ('q4', 1.083), ('q5', 1.333), ('q6', 1.08)] +first run outside 1.05x (gap >= 0.1 ms): [('q2', 4.045), ('q3', 924.342), ('q4', 1040.824), ('q5', 667.112), ('q6', 630.336), ('q7', 310.868), ('q8', 1.649), ('q9', 1.173), ('q10', 1.427), ('q11', 1.946), ('q12', 2.141), ('q13', 1.38), ('q14', 1.325), ('q15', 1.496), ('q16', 1.16), ('q17', 1.231), ('q18', 2.533), ('q19', 1.233), ('q20', 3.347), ('q21', 1.313), ('q22', 2.44), ('q23', 2.026), ('q24', 29.368), ('q25', 211.853), ('q26', 60.986), ('q27', 210.045), ('q28', 1.265), ('q29', 1.065), ('q30', 286.173), ('q31', 1.725), ('q32', 1.694), ('q33', 1.113), ('q34', 1.225), ('q35', 1.229), ('q36', 1.129), ('q37', 2.435), ('q38', 2.547), ('q39', 4.212), ('q40', 1.86), ('q41', 6.531), ('q42', 7.245), ('q43', 3.252)] +result text differs head vs baseline: stable-head diffs []; head unstable against itself (tie order) [] + +## parted (ms; head vs baseline; ratio = head/baseline) +| q | warm head | warm base | ratio | first head | first base | ratio | 3-run head | 3-run base | ratio | +|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.000 | 0.000 | 1.036 | 0.010 | 0.006 | 1.711 | 0.010 | 0.006 | 1.630 | +| q2 | 6.548 | 6.565 | 0.997 | 17.239 | 17.080 | 1.009 | 30.756 | 30.545 | 1.007 | +| q3 | 534.530 | 531.901 | 1.005 | 547.609 | 555.732 | 0.985 | 1630.568 | 1625.175 | 1.003 | +| q4 | 274.737 | 274.666 | 1.000 | 324.076 | 317.029 | 1.022 | 874.750 | 873.829 | 1.001 | +| q5 | 273.886 | 275.156 | 0.995 | 321.902 | 316.661 | 1.017 | 874.392 | 871.353 | 1.003 | +| q6 | 339.239 | 354.685 | 0.956 | 9589.120 | 9617.410 | 0.997 | 10274.543 | 10326.471 | 0.995 | +| q7 | 523.284 | 528.049 | 0.991 | 557.477 | 550.751 | 1.012 | 1608.479 | 1611.945 | 0.998 | +| q8 | 9.146 | 8.898 | 1.028 | 21.352 | 21.233 | 1.006 | 39.872 | 39.093 | 1.020 | +| q9 | 89.326 | 89.335 | 1.000 | 176.321 | 176.611 | 0.998 | 357.533 | 356.988 | 1.002 | +| q10 | 86.757 | 86.833 | 0.999 | 202.315 | 202.819 | 0.998 | 376.433 | 377.952 | 0.996 | +| q11 | 355.919 | 358.032 | 0.994 | 582.423 | 604.809 | 0.963 | 1297.609 | 1324.438 | 0.980 | +| q12 | 358.864 | 356.961 | 1.005 | 579.782 | 599.664 | 0.967 | 1297.504 | 1319.477 | 0.983 | +| q13 | 40.126 | 39.998 | 1.003 | 70.378 | 70.981 | 0.992 | 151.174 | 152.093 | 0.994 | +| q14 | 1126.650 | 1127.240 | 0.999 | 1415.890 | 1425.640 | 0.993 | 3682.500 | 3687.260 | 0.999 | +| q15 | 46.840 | 45.988 | 1.019 | 89.537 | 89.308 | 1.003 | 184.014 | 183.677 | 1.002 | +| q16 | 75.918 | 73.629 | 1.031 | 144.402 | 83.517 | 1.729 | 298.099 | 233.077 | 1.279 | +| q17 | 103.211 | 103.607 | 0.996 | 206.068 | 205.331 | 1.004 | 413.859 | 414.037 | 1.000 | +| q18 | 17.133 | 139.177 | 0.123 | 83.448 | 248.389 | 0.336 | 117.880 | 527.614 | 0.223 | +| q19 | 140.647 | 140.954 | 0.998 | 337.261 | 336.401 | 1.003 | 621.365 | 621.529 | 1.000 | +| q20 | 4.593 | 4.396 | 1.045 | 14.455 | 14.302 | 1.011 | 24.045 | 23.429 | 1.026 | +| q21 | 41.742 | 41.667 | 1.002 | 46.651 | 46.631 | 1.000 | 130.396 | 130.175 | 1.002 | +| q22 | 60.613 | 60.213 | 1.007 | 87.920 | 86.796 | 1.013 | 212.318 | 209.176 | 1.015 | +| q23 | 93.997 | 93.921 | 1.001 | 210.035 | 220.817 | 0.951 | 399.208 | 410.527 | 0.972 | +| q24 | 44.564 | 44.339 | 1.005 | 132.708 | 140.459 | 0.945 | 222.322 | 229.776 | 0.968 | +| q25 | 1063.330 | 1065.000 | 0.998 | 1324.740 | 1342.400 | 0.987 | 3459.250 | 3481.860 | 0.994 | +| q26 | 1120.870 | 1117.680 | 1.003 | 1471.470 | 1492.130 | 0.986 | 3729.920 | 3732.890 | 0.999 | +| q27 | 1079.460 | 1078.210 | 1.001 | 1337.470 | 1360.150 | 0.983 | 3507.540 | 3528.450 | 0.994 | +| q28 | 91.553 | 91.461 | 1.001 | 147.442 | 148.620 | 0.992 | 331.971 | 332.989 | 0.997 | +| q29 | 360.752 | 350.821 | 1.028 | 468.611 | 461.795 | 1.015 | 1196.195 | 1171.096 | 1.021 | +| q30 | 266.654 | 263.339 | 1.013 | 280.969 | 276.262 | 1.017 | 829.220 | 817.072 | 1.015 | +| q31 | 55.143 | 54.953 | 1.003 | 125.212 | 125.744 | 0.996 | 238.528 | 237.626 | 1.004 | +| q32 | 69.225 | 68.844 | 1.006 | 178.718 | 178.417 | 1.002 | 317.722 | 320.151 | 0.992 | +| q33 | 216.283 | 215.747 | 1.002 | 462.433 | 461.041 | 1.003 | 900.791 | 897.351 | 1.004 | +| q34 | 43.201 | 43.163 | 1.001 | 96.547 | 96.399 | 1.002 | 184.860 | 183.463 | 1.008 | +| q35 | 387.736 | 385.438 | 1.006 | 2286.520 | 2304.030 | 0.992 | 3063.081 | 3077.578 | 0.995 | +| q36 | 147.465 | 153.227 | 0.962 | 215.753 | 224.069 | 0.963 | 515.334 | 534.555 | 0.964 | +| q37 | 36.553 | 35.593 | 1.027 | 69.408 | 68.615 | 1.012 | 143.407 | 140.332 | 1.022 | +| q38 | 35.783 | 34.904 | 1.025 | 68.584 | 68.074 | 1.007 | 146.608 | 143.063 | 1.025 | +| q39 | 15.346 | 14.637 | 1.048 | 27.800 | 26.892 | 1.034 | 58.673 | 56.411 | 1.040 | +| q40 | 117.222 | 116.740 | 1.004 | 420.597 | 419.689 | 1.002 | 657.608 | 656.894 | 1.001 | +| q41 | 17.590 | 25.000 | 0.704 | 39.109 | 111.650 | 0.350 | 75.177 | 161.868 | 0.464 | +| q42 | 13.425 | 13.060 | 1.028 | 24.352 | 23.637 | 1.030 | 51.874 | 50.618 | 1.025 | +| q43 | 28.457 | 27.501 | 1.035 | 41.294 | 40.240 | 1.026 | 99.229 | 95.446 | 1.040 | +| total | 9814.3 | 9941.5 | 0.987 | 24845.4 | 25178.2 | 0.987 | 44626.6 | 45199.4 | 0.987 | +warm outside 1.05x (gap >= 0.1 ms): [] +warm over 1.05x but not confirmed (gap < 0.1 ms or median-of-rounds ratio <= 1.05: noise): [] +first run outside 1.05x (gap >= 0.1 ms): [('q16', 1.729)] +result text differs head vs baseline: stable-head diffs []; head unstable against itself (tie order) [] + + +## P2 range reads (10M store, release build, commit a184863c, base 80a28e49) + +Script: `bench/compress_estimate/p2_bench.sh` (prep, splayed, parted stages) +and `p2_summary.py` (tables and the gate lines, printed from p2.tsv). +Loads: splayed copies g0 / g2 written by `.db.splayed.set` from +/skull/clickbench/rfsplayed; parted conversions p0 / p2 of +/skull/clickbench/hits_h.csv (`.csv.parted`, 1M rows per partition); a ragged +copy of p0 (last partition 9 keeps only its first 40 columns: no AdvEngineID +and none of the columns after it; ResolutionWidth, index 20, stays, because +the parted loader takes a shorter partition only as a missing column tail). +One load kind on disk at a time under /home/hetoku/data/tmp/p2_bench. +Per query: 5 alternated rounds, each a fresh process running it 6 times: +first run = run 1, 3-run total = runs 1-3, warm = best round's median of +runs 2-6. Cold: 3 trials, page cache evicted per file (POSIX_FADV_DONTNEED; +the .sym is evicted with the store). Answers: each query's full result +(`.csv.write` for tables, the printed value otherwise) compared byte for byte; +queries without asc:/desc: compared with lines sorted; variant b run twice. +On disk: g0 5 948 677 939 B, g2 3 307 128 731 B (1.80x); p0 4 807 844 987 B, +p2 2 072 366 907 B (2.32x). Peak RSS over all 43 queries: g0 5 109 200 kB, +g2 8 101 948 kB, p0 14 864 816 kB, p2 15 743 720 kB. +Answers: identical on every arm (0 mismatches, 0 order differences). + +### Gate noise floor (A/A evidence, P2 gate) + +A/A = the base binary against itself under the gate protocol (five +alternated rounds, minimum-round warm). Measured on the 10M store: + +| class | queries | b/a | abs gap | round-median spread | +|---|---|---|---|---| +| statistics answers | splayed q1, q4, q5, q6, q7 (0.2-1.4 us) | 0.94-1.02 | <= 0.02 us | up to +36% (q6 0.43-0.56 us) | +| ~0.02 ms | q30 (18.7 us) | 1.009 | 0.16 us | 18.7-33.6 us | +| ~1 ms | q25, q27, q20, q2 (0.86-1.15 ms) | 1.002-1.041 | <= 35 us | up to 1.07 ms vs 0.86 min | +| >= 4 ms | parted q2, q8, q20, q39, q41, q42, q43, q18; splayed q3, q18, q39, q41, q42 | 0.984-1.011 | n/a | n/a | + +Gate rule (p2_summary.py): a per-query clause passes at ratio <= its bound +(1.05 warm, 1.10 first and cold), or when both medians are < 1 ms and the +gap is <= 0.05 ms (about 1.4x the largest sub-ms A/A gap, 35 us; it does not +hide the q25/q27 rows: on the old P2 gen-0 splayed arm q25 is 0.95 -> 1.03 +ms and q27 0.93 -> 1.08 ms, which fail because p2 crosses 1 ms, so the +sub-ms clause does not apply (the PI section's 15-round confirm of q25, +1.056 on a different head/dev pair, is a separate measurement and is not +evidence about this arm). Geometric means cover only queries whose base +median is >= 1 ms; the excluded queries are printed per column +(`below_1ms_excluded_from_warm_gmean`, `below_1ms_excluded_from_first_gmean`, +`below_1ms_excluded_from_cold_gmean`), because a +-6% ratio wobble on +0.2 us answers moves a gmean and means nothing. Above 4 ms A/A stays within ++-1.1%, so 1.05 keeps a 4x margin. + +Query classes are taken from the materialization the run measured (the +`mat` rows), not a fixed list: q5, q20, q36 do not materialize; splayed q18 +and q39, and parted q39, do. A SCAN_ONLY-list query that materializes stays +gated as scan-only (warm, first, cold) and fails `no_unexpected_materialization` +unless it is in P3_DEFERRALS for that arm; a missing `mat` row fails the +same field. The plan's pre-run SCAN_ONLY list is kept as a cross-check and +its disagreements are printed. Expected P3 deferrals are a data table +(`P3_DEFERRALS`) in p2_summary.py; the output has GATE (strict), GATE +(P3-exempt) and the exempt list with each exempted query's measured numbers. +Each deferral has a `max_ratio` per arm (about 1.5x its measured ratio, set +from the gate re-run below); above it the exemption lapses and the clause +fails. + +The 1.10 bound on first and cold is a per-query tolerance for cold and +first-run noise. The spec's "cold is faster" requirement is carried by the +aggregate: the cold geometric mean (queries with a cold base median >= 1 ms) +must be < 1.00. Geometric-mean filters use each column's own base median. + +### arm A: splayed g0 vs g2 (ms; ratio = g2/g0) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.995 | 0.01 | 0.01 | 0.991 | 0.01 | 0.01 | 0.990 | 0.01 | 0.01 | 1.018 | [] | same | +| q2 | 0.65 | 3.43 | 5.288 | 1.61 | 7.62 | 4.734 | 3.12 | 14.65 | 4.699 | 38.21 | 7.93 | 0.208 | [] | same | +| q3 | 3.79 | 0.00 | 0.001 | 5.52 | 0.04 | 0.006 | 13.17 | 0.04 | 0.003 | 94.54 | 0.04 | 0.000 | [] | same | +| q4 | 0.00 | 0.00 | 1.070 | 0.02 | 0.03 | 1.211 | 0.03 | 0.03 | 1.200 | 0.03 | 0.03 | 1.220 | [] | same | +| q5 | 0.00 | 0.00 | 1.259 | 0.03 | 0.03 | 0.897 | 0.04 | 0.03 | 0.915 | 0.03 | 0.03 | 0.994 | [] | same | +| q6 | 0.00 | 0.00 | 1.409 | 0.02 | 0.03 | 1.484 | 0.02 | 0.04 | 1.464 | 0.03 | 0.03 | 1.016 | [] | same | +| q7 | 0.00 | 0.00 | 1.119 | 0.02 | 0.03 | 1.660 | 0.02 | 0.04 | 1.571 | 0.02 | 0.04 | 1.770 | [] | same | +| q8 | 3.54 | 12.69 | 3.585 | 8.81 | 17.43 | 1.979 | 15.89 | 43.04 | 2.709 | 41.39 | 19.68 | 0.476 | [] | same | +| q9 | 75.13 | 75.28 | 1.002 | 112.55 | 131.21 | 1.166 | 265.23 | 287.73 | 1.085 | 665.44 | 156.55 | 0.235 | [RegionID UserID] | same | +| q10 | 68.60 | 77.23 | 1.126 | 97.17 | 136.21 | 1.402 | 237.51 | 297.81 | 1.254 | 403.47 | 164.59 | 0.408 | [RegionID UserID] | same | +| q11 | 16.31 | 16.45 | 1.009 | 25.01 | 50.49 | 2.019 | 57.76 | 83.48 | 1.445 | 246.75 | 67.57 | 0.274 | [UserID MobilePhoneModel] | same | +| q12 | 16.10 | 16.28 | 1.012 | 25.28 | 56.43 | 2.232 | 58.59 | 89.72 | 1.531 | 279.37 | 74.54 | 0.267 | [UserID MobilePhone MobilePhoneModel] | same | +| q13 | 32.34 | 32.22 | 0.996 | 41.48 | 55.37 | 1.335 | 106.90 | 120.18 | 1.124 | 113.55 | 64.37 | 0.567 | [SearchPhrase] | same | +| q14 | 63.27 | 63.16 | 0.998 | 88.81 | 117.31 | 1.321 | 219.49 | 247.11 | 1.126 | 304.71 | 141.66 | 0.465 | [UserID SearchPhrase] | same | +| q15 | 36.45 | 51.44 | 1.411 | 47.81 | 77.93 | 1.630 | 122.83 | 182.74 | 1.488 | 155.68 | 95.09 | 0.611 | [SearchPhrase] | same | +| q16 | 72.82 | 69.12 | 0.949 | 101.81 | 90.65 | 0.890 | 250.86 | 230.98 | 0.921 | 245.42 | 167.49 | 0.682 | [] | same | +| q17 | 95.90 | 123.10 | 1.284 | 133.37 | 166.22 | 1.246 | 329.94 | 413.65 | 1.254 | 458.42 | 294.68 | 0.643 | [] | same | +| q18 | 6.82 | 6.86 | 1.006 | 13.51 | 36.86 | 2.729 | 27.42 | 50.92 | 1.857 | 624.91 | 61.98 | 0.099 | [UserID SearchPhrase] | same | +| q19 | 141.17 | 166.63 | 1.180 | 212.97 | 255.88 | 1.201 | 501.27 | 596.17 | 1.189 | 674.52 | 479.71 | 0.711 | [EventTime] | same | +| q20 | 1.10 | 3.17 | 2.888 | 6.82 | 8.17 | 1.197 | 9.44 | 14.61 | 1.547 | 55.49 | 21.73 | 0.392 | [] | same | +| q21 | 42.22 | 41.99 | 0.995 | 45.28 | 51.21 | 1.131 | 132.45 | 136.48 | 1.030 | 77.39 | 92.90 | 1.200 | [URL] | same | +| q22 | 27.74 | 27.55 | 0.993 | 32.59 | 65.85 | 2.020 | 89.67 | 121.78 | 1.358 | 184.00 | 134.69 | 0.732 | [UserID URL SearchPhrase] | same | +| q23 | 48.86 | 49.01 | 1.003 | 60.44 | 98.66 | 1.633 | 159.04 | 197.23 | 1.240 | 413.08 | 206.37 | 0.500 | [Title UserID URL SearchPhrase] | same | +| q24 | 29.94 | 29.88 | 0.998 | 35.16 | 827.95 | 23.546 | 94.97 | 891.25 | 9.385 | 611.94 | 1463.61 | 2.392 | <100 columns> | same | +| q25 | 1.08 | 1.11 | 1.025 | 4.44 | 791.48 | 178.063 | 6.68 | 793.85 | 118.835 | 297.25 | 1446.28 | 4.866 | <100 columns> | same | +| q26 | 11.07 | 11.06 | 0.999 | 15.61 | 796.79 | 51.058 | 37.97 | 819.43 | 21.580 | 558.42 | 1455.72 | 2.607 | <100 columns> | same | +| q27 | 0.97 | 1.10 | 1.132 | 4.49 | 783.02 | 174.428 | 6.66 | 785.39 | 117.959 | 292.77 | 1443.96 | 4.932 | <100 columns> | same | +| q28 | 86.33 | 72.33 | 0.838 | 88.94 | 83.97 | 0.944 | 265.23 | 228.97 | 0.863 | 224.11 | 127.58 | 0.569 | [URL] | same | +| q29 | 350.58 | 350.90 | 1.001 | 440.03 | 443.62 | 1.008 | 1143.04 | 1153.56 | 1.009 | 510.18 | 491.90 | 0.964 | [Referer] | same | +| q30 | 0.02 | 0.02 | 0.992 | 2.77 | 9.49 | 3.419 | 2.84 | 9.53 | 3.355 | 53.19 | 12.57 | 0.236 | [ResolutionWidth] | same | +| q31 | 51.74 | 52.08 | 1.006 | 70.40 | 114.33 | 1.624 | 175.47 | 221.74 | 1.264 | 317.26 | 142.26 | 0.448 | [ClientIP IsRefresh ResolutionWidth SearchEngineID SearchPhrase] | same | +| q32 | 59.84 | 59.65 | 0.997 | 86.55 | 122.84 | 1.419 | 207.15 | 243.92 | 1.177 | 443.89 | 285.56 | 0.643 | [ClientIP IsRefresh ResolutionWidth SearchPhrase] | same | +| q33 | 207.66 | 231.81 | 1.116 | 371.55 | 394.89 | 1.063 | 799.40 | 867.71 | 1.085 | 598.50 | 593.67 | 0.992 | [] | same | +| q34 | 39.25 | 38.63 | 0.984 | 70.30 | 72.01 | 1.024 | 150.40 | 149.67 | 0.995 | 138.37 | 110.57 | 0.799 | [] | same | +| q35 | 39.25 | 38.75 | 0.987 | 69.84 | 71.72 | 1.027 | 150.67 | 149.17 | 0.990 | 138.13 | 109.70 | 0.794 | [] | same | +| q36 | 66.56 | 68.04 | 1.022 | 90.61 | 87.89 | 0.970 | 224.81 | 227.58 | 1.012 | 163.63 | 132.62 | 0.811 | [] | same | +| q37 | 16.61 | 16.58 | 0.998 | 27.20 | 47.29 | 1.739 | 60.68 | 80.94 | 1.334 | 41.97 | 92.43 | 2.202 | [EventDate URL IsRefresh DontCountHits] | same | +| q38 | 15.04 | 15.01 | 0.998 | 24.41 | 45.25 | 1.854 | 55.53 | 75.90 | 1.367 | 38.88 | 85.59 | 2.201 | [Title EventDate IsRefresh DontCountHits] | same | +| q39 | 7.10 | 7.19 | 1.012 | 14.61 | 38.87 | 2.661 | 30.02 | 53.81 | 1.792 | 42.55 | 88.72 | 2.085 | [EventDate URL IsRefresh IsLink IsDownload] | same | +| q40 | 59.01 | 58.54 | 0.992 | 90.51 | 132.40 | 1.463 | 212.86 | 252.34 | 1.185 | 117.68 | 236.73 | 2.012 | [EventDate CounterID URL Referer IsRefresh TraficSourceID SearchEngineID AdvEngineID] | same | +| q41 | 5.78 | 5.60 | 0.969 | 13.09 | 29.94 | 2.287 | 25.07 | 41.51 | 1.656 | 74.18 | 51.80 | 0.698 | [EventDate CounterID IsRefresh TraficSourceID] | same | +| q42 | 4.59 | 11.98 | 2.611 | 11.40 | 37.77 | 3.312 | 20.65 | 62.44 | 3.024 | 37.37 | 49.78 | 1.332 | [EventDate CounterID IsRefresh DontCountHits] | same | +| q43 | 9.02 | 9.02 | 0.999 | 18.35 | 48.99 | 2.670 | 37.45 | 67.55 | 1.804 | 39.91 | 151.26 | 3.790 | [EventTime EventDate CounterID IsRefresh DontCountHits] | same | + +``` +totals over all 43: warm 1814.3 vs 1914.9 (1.055); first run 2611.2 vs 6404.2 (2.453); 3-run 6308.3 vs 10304.7 (1.634) +answer_mismatches none +order_differences none +scan_only n=13 warm_gmean=0.730 warm_worst=5.288 first_gmean=1.007 first_worst=4.734 cold_gmean=0.394 cold_worst=2.085 +scan_only_materializing q18(P3-deferred) q39(P3-deferred) +worst5 warm [(5.288, 'q2'), (3.585, 'q8'), (1.284, 'q17'), (1.119, 'q7'), (1.116, 'q33')] +worst5 cold [(2.085, 'q39'), (1.77, 'q7'), (1.22, 'q4'), (1.018, 'q1'), (0.992, 'q33')] +worst5 first [(4.734, 'q2'), (2.729, 'q18'), (2.661, 'q39'), (1.979, 'q8'), (1.66, 'q7')] +worst5 materializing_warm [(2.888, 'q20'), (2.611, 'q42'), (1.411, 'q15'), (1.409, 'q6'), (1.259, 'q5')] +first_run_total_ratio 2.453 (PI after P1: 2.99) +pi_row q41 warm 0.969 first 2.287 3run 1.656 +pi_row q42 warm 2.611 first 3.312 3run 3.024 +``` + +### arm B: parted p0 vs p2 (ms; ratio = p2/p0) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.952 | 0.01 | 0.01 | 0.606 | 0.01 | 0.01 | 0.628 | 0.01 | 0.01 | 0.590 | [] | same | +| q2 | 6.58 | 9.83 | 1.494 | 17.03 | 18.16 | 1.066 | 30.48 | 37.95 | 1.245 | 47.81 | 17.94 | 0.375 | [] | same | +| q3 | 540.30 | 12.90 | 0.024 | 546.05 | 17.68 | 0.032 | 1632.34 | 43.60 | 0.027 | 564.14 | 19.39 | 0.034 | [] | same | +| q4 | 273.97 | 9.98 | 0.036 | 320.94 | 14.93 | 0.047 | 875.38 | 35.56 | 0.041 | 364.83 | 33.03 | 0.091 | [] | same | +| q5 | 274.29 | 0.00 | 0.000 | 323.55 | 0.03 | 0.000 | 878.66 | 0.03 | 0.000 | 365.09 | 0.04 | 0.000 | [] | same | +| q6 | 341.74 | 343.32 | 1.005 | 9648.46 | 9631.52 | 0.998 | 10333.93 | 10325.20 | 0.999 | 9688.53 | 9730.10 | 1.004 | [SearchPhrase] | same | +| q7 | 524.77 | 4.97 | 0.009 | 553.22 | 9.25 | 0.017 | 1610.32 | 19.56 | 0.012 | 574.75 | 9.61 | 0.017 | [] | same | +| q8 | 8.64 | 26.08 | 3.020 | 10.12 | 32.62 | 3.223 | 27.66 | 85.45 | 3.089 | 43.77 | 32.65 | 0.746 | [] | same | +| q9 | 85.40 | 83.24 | 0.975 | 151.93 | 174.92 | 1.151 | 324.13 | 346.82 | 1.070 | 390.50 | 194.38 | 0.498 | [RegionID UserID] | same | +| q10 | 78.88 | 85.98 | 1.090 | 157.68 | 184.35 | 1.169 | 316.28 | 362.88 | 1.147 | 447.95 | 208.92 | 0.466 | [RegionID UserID] | same | +| q11 | 357.41 | 348.47 | 0.975 | 576.50 | 1285.17 | 2.229 | 1290.19 | 1991.25 | 1.543 | 10386.90 | 2549.53 | 0.245 | <105 columns> | same | +| q12 | 353.55 | 348.32 | 0.985 | 571.92 | 1324.12 | 2.315 | 1286.72 | 2077.45 | 1.615 | 10332.90 | 2461.06 | 0.238 | <105 columns> | same | +| q13 | 40.30 | 40.08 | 0.994 | 70.48 | 82.55 | 1.171 | 151.85 | 168.81 | 1.112 | 154.95 | 93.44 | 0.603 | [SearchPhrase] | same | +| q14 | 1116.70 | 1118.73 | 1.002 | 1395.79 | 2425.98 | 1.738 | 3646.17 | 4776.23 | 1.310 | 9982.71 | 4084.80 | 0.409 | <105 columns> | same | +| q15 | 46.75 | 64.81 | 1.386 | 89.81 | 119.80 | 1.334 | 185.36 | 251.78 | 1.358 | 218.12 | 133.39 | 0.612 | [SearchPhrase] | same | +| q16 | 72.34 | 69.73 | 0.964 | 98.60 | 91.66 | 0.930 | 243.76 | 233.18 | 0.957 | 245.47 | 163.00 | 0.664 | [] | same | +| q17 | 95.53 | 123.20 | 1.290 | 133.67 | 168.75 | 1.262 | 326.62 | 416.80 | 1.276 | 458.69 | 289.93 | 0.632 | [] | same | +| q18 | 17.02 | 96.59 | 5.676 | 82.89 | 154.56 | 1.865 | 117.42 | 352.66 | 3.003 | 338.05 | 177.74 | 0.526 | [] | same | +| q19 | 141.05 | 231.04 | 1.638 | 335.78 | 417.38 | 1.243 | 621.69 | 879.86 | 1.415 | 758.07 | 555.79 | 0.733 | [EventTime] | same | +| q20 | 4.65 | 4.23 | 0.910 | 14.61 | 13.44 | 0.920 | 24.28 | 22.08 | 0.909 | 157.50 | 26.84 | 0.170 | [] | same | +| q21 | 41.94 | 41.78 | 0.996 | 46.90 | 56.37 | 1.202 | 131.78 | 140.89 | 1.069 | 89.56 | 100.97 | 1.128 | [URL] | same | +| q22 | 60.81 | 60.55 | 0.996 | 86.26 | 117.42 | 1.361 | 209.81 | 245.06 | 1.168 | 234.23 | 188.82 | 0.806 | [UserID URL SearchPhrase] | same | +| q23 | 93.79 | 93.43 | 0.996 | 207.73 | 975.62 | 4.696 | 396.18 | 1169.84 | 2.953 | 10458.40 | 2144.38 | 0.205 | <105 columns> | same | +| q24 | 44.83 | 43.79 | 0.977 | 129.40 | 914.32 | 7.066 | 222.10 | 1006.23 | 4.531 | 9603.40 | 1992.05 | 0.207 | <105 columns> | same | +| q25 | 1056.03 | 1052.35 | 0.997 | 1310.78 | 2493.40 | 1.902 | 3428.63 | 4669.08 | 1.362 | 9853.74 | 3924.10 | 0.398 | <105 columns> | same | +| q26 | 1113.89 | 1104.44 | 0.992 | 1459.83 | 2632.38 | 1.803 | 3690.92 | 4967.34 | 1.346 | 10048.50 | 4063.58 | 0.404 | <105 columns> | same | +| q27 | 1067.52 | 1064.85 | 0.997 | 1321.60 | 2538.17 | 1.921 | 3465.72 | 4763.56 | 1.374 | 9931.12 | 4025.96 | 0.405 | <105 columns> | same | +| q28 | 107.17 | 105.88 | 0.988 | 166.71 | 168.28 | 1.009 | 386.06 | 384.41 | 0.996 | 325.30 | 213.97 | 0.658 | [URL] | same | +| q29 | 356.74 | 356.98 | 1.001 | 467.90 | 478.22 | 1.022 | 1188.20 | 1196.51 | 1.007 | 551.13 | 518.06 | 0.940 | [Referer] | same | +| q30 | 267.51 | 266.83 | 0.997 | 276.80 | 287.61 | 1.039 | 830.20 | 829.11 | 0.999 | 285.37 | 287.75 | 1.008 | [ResolutionWidth] | same | +| q31 | 55.71 | 146.35 | 2.627 | 125.14 | 222.52 | 1.778 | 237.99 | 517.07 | 2.173 | 434.18 | 253.06 | 0.583 | [SearchPhrase] | same | +| q32 | 69.11 | 171.18 | 2.477 | 179.51 | 291.09 | 1.622 | 318.35 | 633.76 | 1.991 | 624.33 | 463.01 | 0.742 | [SearchPhrase] | same | +| q33 | 212.19 | 242.79 | 1.144 | 371.49 | 413.57 | 1.113 | 806.74 | 909.70 | 1.128 | 614.75 | 753.17 | 1.225 | [] | same | +| q34 | 43.19 | 46.34 | 1.073 | 95.59 | 97.05 | 1.015 | 183.40 | 191.10 | 1.042 | 180.01 | 145.04 | 0.806 | [] | same | +| q35 | 43.06 | 46.47 | 1.079 | 95.33 | 98.16 | 1.030 | 182.69 | 192.45 | 1.053 | 180.18 | 146.00 | 0.810 | [] | same | +| q36 | 144.81 | 181.98 | 1.257 | 214.66 | 252.28 | 1.175 | 513.86 | 623.38 | 1.213 | 300.37 | 269.32 | 0.897 | [] | same | +| q37 | 35.92 | 34.02 | 0.947 | 69.23 | 87.35 | 1.262 | 141.65 | 156.47 | 1.105 | 227.11 | 131.86 | 0.581 | [EventDate URL IsRefresh DontCountHits] | same | +| q38 | 34.90 | 32.80 | 0.940 | 67.34 | 89.53 | 1.329 | 142.75 | 154.88 | 1.085 | 230.93 | 130.62 | 0.566 | [Title EventDate IsRefresh DontCountHits] | same | +| q39 | 15.09 | 13.34 | 0.884 | 27.29 | 44.80 | 1.642 | 57.63 | 76.88 | 1.334 | 115.60 | 54.11 | 0.468 | [EventDate URL IsRefresh IsLink IsDownload] | same | +| q40 | 116.43 | 156.03 | 1.340 | 420.06 | 461.43 | 1.098 | 656.09 | 781.42 | 1.191 | 786.82 | 577.51 | 0.734 | [EventDate IsRefresh] | same | +| q41 | 17.58 | 22.25 | 1.266 | 39.07 | 63.86 | 1.635 | 75.49 | 112.03 | 1.484 | 268.00 | 227.34 | 0.848 | [EventDate CounterID IsRefresh TraficSourceID URLHash] | same | +| q42 | 13.15 | 22.57 | 1.716 | 24.11 | 57.65 | 2.391 | 50.87 | 105.34 | 2.071 | 193.49 | 173.00 | 0.894 | [EventDate CounterID IsRefresh WindowClientWidth WindowClientHeight DontCountHits] | same | +| q43 | 28.05 | 26.16 | 0.933 | 40.61 | 64.35 | 1.585 | 97.04 | 118.75 | 1.224 | 130.26 | 162.87 | 1.250 | [EventTime EventDate IsRefresh DontCountHits] | same | + +``` +totals over all 43: warm 9419.3 vs 8354.7 (0.887); first run 22342.4 vs 29072.3 (1.301); 3-run 41337.4 vs 46372.4 (1.122) +answer_mismatches none +order_differences none +scan_only n=13 warm_gmean=0.535 warm_worst=5.676 first_gmean=0.523 first_worst=3.223 cold_gmean=0.336 cold_worst=1.225 +scan_only_materializing q39(P3-deferred) +worst5 warm [(5.676, 'q18'), (3.02, 'q8'), (1.494, 'q2'), (1.29, 'q17'), (1.144, 'q33')] +worst5 cold [(1.225, 'q33'), (0.81, 'q35'), (0.806, 'q34'), (0.746, 'q8'), (0.664, 'q16')] +worst5 first [(3.223, 'q8'), (1.865, 'q18'), (1.642, 'q39'), (1.262, 'q17'), (1.113, 'q33')] +worst5 materializing_warm [(2.627, 'q31'), (2.477, 'q32'), (1.716, 'q42'), (1.638, 'q19'), (1.386, 'q15')] +pi_row q41 warm 1.266 first 1.635 3run 1.484 +pi_row q42 warm 1.716 first 2.391 3run 2.071 +``` + +### arm C0: splayed g0, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.916 | 0.01 | 0.01 | 0.999 | 0.01 | 0.01 | 0.997 | nan | nan | nan | | same | +| q2 | 1.11 | 0.64 | 0.576 | 2.03 | 1.61 | 0.793 | 4.33 | 3.10 | 0.716 | nan | nan | nan | | same | +| q3 | 3.78 | 3.79 | 1.001 | 5.65 | 5.75 | 1.019 | 13.27 | 13.42 | 1.011 | nan | nan | nan | | same | +| q4 | 0.00 | 0.00 | 1.046 | 0.02 | 0.03 | 1.189 | 0.02 | 0.03 | 1.184 | nan | nan | nan | | same | +| q5 | 0.00 | 0.00 | 1.010 | 0.03 | 0.02 | 0.884 | 0.03 | 0.02 | 0.902 | nan | nan | nan | | same | +| q6 | 0.00 | 0.00 | 1.070 | 0.03 | 0.02 | 0.824 | 0.03 | 0.02 | 0.831 | nan | nan | nan | | same | +| q7 | 0.00 | 0.00 | 1.036 | 0.02 | 0.02 | 1.033 | 0.02 | 0.02 | 1.046 | nan | nan | nan | | same | +| q8 | 3.49 | 3.56 | 1.021 | 8.86 | 8.94 | 1.009 | 16.05 | 16.18 | 1.008 | nan | nan | nan | | same | +| q9 | 75.90 | 75.33 | 0.992 | 115.44 | 113.47 | 0.983 | 267.67 | 264.46 | 0.988 | nan | nan | nan | | same | +| q10 | 69.23 | 69.67 | 1.006 | 97.35 | 104.22 | 1.071 | 239.68 | 245.66 | 1.025 | nan | nan | nan | | same | +| q11 | 16.20 | 16.26 | 1.003 | 24.96 | 25.29 | 1.013 | 57.96 | 58.09 | 1.002 | nan | nan | nan | | same | +| q12 | 16.40 | 16.10 | 0.982 | 25.93 | 25.66 | 0.989 | 59.87 | 58.54 | 0.978 | nan | nan | nan | | same | +| q13 | 31.90 | 32.30 | 1.013 | 41.01 | 41.32 | 1.008 | 106.01 | 105.76 | 0.998 | nan | nan | nan | | same | +| q14 | 62.72 | 63.05 | 1.005 | 90.23 | 90.11 | 0.999 | 224.77 | 220.95 | 0.983 | nan | nan | nan | | same | +| q15 | 36.37 | 36.63 | 1.007 | 48.16 | 48.24 | 1.002 | 123.53 | 125.32 | 1.015 | nan | nan | nan | | same | +| q16 | 69.87 | 72.59 | 1.039 | 94.14 | 97.87 | 1.040 | 234.21 | 245.34 | 1.048 | nan | nan | nan | | same | +| q17 | 93.27 | 95.00 | 1.019 | 128.92 | 134.41 | 1.043 | 320.07 | 327.26 | 1.022 | nan | nan | nan | | same | +| q18 | 6.90 | 6.88 | 0.997 | 13.92 | 13.82 | 0.993 | 27.97 | 27.68 | 0.989 | nan | nan | nan | | same | +| q19 | 139.60 | 141.25 | 1.012 | 208.89 | 210.19 | 1.006 | 488.93 | 499.67 | 1.022 | nan | nan | nan | | same | +| q20 | 1.12 | 1.15 | 1.023 | 6.89 | 6.84 | 0.993 | 9.42 | 9.40 | 0.997 | nan | nan | nan | | same | +| q21 | 41.92 | 42.34 | 1.010 | 45.19 | 46.08 | 1.020 | 129.17 | 132.85 | 1.028 | nan | nan | nan | | same | +| q22 | 27.61 | 27.72 | 1.004 | 31.83 | 32.36 | 1.017 | 87.77 | 89.04 | 1.015 | nan | nan | nan | | same | +| q23 | 48.75 | 48.76 | 1.000 | 60.27 | 60.32 | 1.001 | 158.26 | 158.27 | 1.000 | nan | nan | nan | | same | +| q24 | 29.28 | 29.90 | 1.021 | 34.23 | 35.97 | 1.051 | 93.17 | 97.15 | 1.043 | nan | nan | nan | | same | +| q25 | 0.95 | 1.03 | 1.078 | 4.32 | 4.39 | 1.016 | 6.38 | 6.65 | 1.041 | nan | nan | nan | | same | +| q26 | 10.74 | 11.08 | 1.032 | 15.21 | 15.42 | 1.014 | 36.81 | 37.63 | 1.022 | nan | nan | nan | | same | +| q27 | 0.93 | 1.08 | 1.170 | 4.34 | 4.44 | 1.023 | 6.33 | 6.63 | 1.048 | nan | nan | nan | | same | +| q28 | 82.56 | 86.36 | 1.046 | 85.19 | 89.28 | 1.048 | 251.59 | 263.23 | 1.046 | nan | nan | nan | | same | +| q29 | 353.78 | 350.44 | 0.991 | 444.64 | 440.71 | 0.991 | 1159.04 | 1147.23 | 0.990 | nan | nan | nan | | same | +| q30 | 0.03 | 0.02 | 0.588 | 2.94 | 2.91 | 0.990 | 3.01 | 2.98 | 0.990 | nan | nan | nan | | same | +| q31 | 52.98 | 51.90 | 0.980 | 71.08 | 70.10 | 0.986 | 178.14 | 174.78 | 0.981 | nan | nan | nan | | same | +| q32 | 59.52 | 60.00 | 1.008 | 85.27 | 88.10 | 1.033 | 205.17 | 207.93 | 1.013 | nan | nan | nan | | same | +| q33 | 202.05 | 208.10 | 1.030 | 362.74 | 373.46 | 1.030 | 775.96 | 798.94 | 1.030 | nan | nan | nan | | same | +| q34 | 39.47 | 39.18 | 0.993 | 70.30 | 71.42 | 1.016 | 150.12 | 150.65 | 1.004 | nan | nan | nan | | same | +| q35 | 39.09 | 39.03 | 0.998 | 70.14 | 69.35 | 0.989 | 148.37 | 148.54 | 1.001 | nan | nan | nan | | same | +| q36 | 64.05 | 66.85 | 1.044 | 89.41 | 90.80 | 1.016 | 218.76 | 227.06 | 1.038 | nan | nan | nan | | same | +| q37 | 17.19 | 16.59 | 0.965 | 27.80 | 27.04 | 0.973 | 62.33 | 60.18 | 0.965 | nan | nan | nan | | same | +| q38 | 15.83 | 15.02 | 0.949 | 25.25 | 24.27 | 0.961 | 57.70 | 55.04 | 0.954 | nan | nan | nan | | same | +| q39 | 7.48 | 7.10 | 0.949 | 14.77 | 14.33 | 0.970 | 29.91 | 29.13 | 0.974 | nan | nan | nan | | same | +| q40 | 59.09 | 58.96 | 0.998 | 89.70 | 90.02 | 1.004 | 209.60 | 209.05 | 0.997 | nan | nan | nan | | same | +| q41 | 5.86 | 5.62 | 0.960 | 13.34 | 13.24 | 0.992 | 25.16 | 25.24 | 1.003 | nan | nan | nan | | same | +| q42 | 4.71 | 4.46 | 0.947 | 11.25 | 11.00 | 0.978 | 20.96 | 20.42 | 0.974 | nan | nan | nan | | same | +| q43 | 9.30 | 8.99 | 0.967 | 18.86 | 18.72 | 0.992 | 38.44 | 37.47 | 0.975 | nan | nan | nan | | same | + +``` +totals over all 43: warm 1801.0 vs 1814.7 (1.008); first run 2590.5 vs 2621.6 (1.012); 3-run 6246.0 vs 6307.0 (1.010) +answer_mismatches none +order_differences none +gen0 warm_gmean=0.982 warm_worst=1.170 worst5 [(1.17, 'q27'), (1.078, 'q25'), (1.07, 'q6'), (1.046, 'q4'), (1.046, 'q28')] +``` + +### arm C1: parted p0, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.069 | 0.01 | 0.01 | 0.961 | 0.01 | 0.01 | 0.961 | nan | nan | nan | | same | +| q2 | 6.60 | 6.59 | 0.998 | 16.99 | 17.02 | 1.002 | 30.64 | 30.64 | 1.000 | nan | nan | nan | | same | +| q3 | 535.48 | 535.69 | 1.000 | 551.02 | 547.71 | 0.994 | 1633.60 | 1634.45 | 1.001 | nan | nan | nan | | same | +| q4 | 276.73 | 274.97 | 0.994 | 328.86 | 319.19 | 0.971 | 895.80 | 876.34 | 0.978 | nan | nan | nan | | same | +| q5 | 276.18 | 275.29 | 0.997 | 324.54 | 323.64 | 0.997 | 880.88 | 880.97 | 1.000 | nan | nan | nan | | same | +| q6 | 344.26 | 342.00 | 0.993 | 9689.67 | 9684.79 | 0.999 | 10384.85 | 10371.18 | 0.999 | nan | nan | nan | | same | +| q7 | 525.31 | 526.47 | 1.002 | 558.69 | 561.35 | 1.005 | 1616.75 | 1614.78 | 0.999 | nan | nan | nan | | same | +| q8 | 9.10 | 8.55 | 0.940 | 21.03 | 10.20 | 0.485 | 39.58 | 27.68 | 0.699 | nan | nan | nan | | same | +| q9 | 89.31 | 85.81 | 0.961 | 176.81 | 153.50 | 0.868 | 357.14 | 328.43 | 0.920 | nan | nan | nan | | same | +| q10 | 87.46 | 79.54 | 0.909 | 206.09 | 154.12 | 0.748 | 384.36 | 313.15 | 0.815 | nan | nan | nan | | same | +| q11 | 358.17 | 355.63 | 0.993 | 584.11 | 581.16 | 0.995 | 1304.84 | 1296.63 | 0.994 | nan | nan | nan | | same | +| q12 | 359.16 | 354.16 | 0.986 | 583.13 | 581.63 | 0.997 | 1303.94 | 1296.90 | 0.995 | nan | nan | nan | | same | +| q13 | 39.96 | 40.09 | 1.003 | 71.04 | 71.14 | 1.001 | 151.23 | 152.05 | 1.005 | nan | nan | nan | | same | +| q14 | 1128.22 | 1116.40 | 0.990 | 1422.55 | 1406.34 | 0.989 | 3701.36 | 3649.07 | 0.986 | nan | nan | nan | | same | +| q15 | 46.82 | 46.51 | 0.993 | 90.37 | 90.32 | 0.999 | 188.51 | 187.64 | 0.995 | nan | nan | nan | | same | +| q16 | 76.23 | 72.43 | 0.950 | 144.47 | 100.68 | 0.697 | 299.87 | 247.16 | 0.824 | nan | nan | nan | | same | +| q17 | 103.50 | 95.71 | 0.925 | 203.57 | 135.25 | 0.664 | 414.76 | 330.23 | 0.796 | nan | nan | nan | | same | +| q18 | 17.13 | 17.02 | 0.994 | 83.87 | 83.58 | 0.997 | 118.60 | 120.49 | 1.016 | nan | nan | nan | | same | +| q19 | 140.84 | 141.68 | 1.006 | 334.35 | 338.78 | 1.013 | 621.70 | 624.22 | 1.004 | nan | nan | nan | | same | +| q20 | 4.63 | 4.66 | 1.006 | 14.37 | 14.44 | 1.005 | 23.92 | 24.03 | 1.005 | nan | nan | nan | | same | +| q21 | 41.65 | 42.21 | 1.014 | 46.59 | 47.57 | 1.021 | 130.42 | 133.49 | 1.024 | nan | nan | nan | | same | +| q22 | 61.05 | 61.04 | 1.000 | 86.10 | 86.61 | 1.006 | 208.14 | 209.74 | 1.008 | nan | nan | nan | | same | +| q23 | 93.81 | 94.61 | 1.008 | 211.08 | 213.47 | 1.011 | 398.94 | 404.97 | 1.015 | nan | nan | nan | | same | +| q24 | 44.61 | 44.82 | 1.005 | 131.29 | 132.09 | 1.006 | 220.76 | 222.73 | 1.009 | nan | nan | nan | | same | +| q25 | 1073.31 | 1057.68 | 0.985 | 1333.96 | 1324.88 | 0.993 | 3491.04 | 3457.73 | 0.990 | nan | nan | nan | | same | +| q26 | 1126.64 | 1108.97 | 0.984 | 1479.28 | 1473.01 | 0.996 | 3739.92 | 3699.15 | 0.989 | nan | nan | nan | | same | +| q27 | 1081.98 | 1069.87 | 0.989 | 1342.24 | 1339.71 | 0.998 | 3515.27 | 3482.80 | 0.991 | nan | nan | nan | | same | +| q28 | 91.77 | 107.21 | 1.168 | 147.33 | 165.57 | 1.124 | 332.84 | 382.56 | 1.149 | nan | nan | nan | | same | +| q29 | 363.62 | 358.22 | 0.985 | 475.57 | 472.47 | 0.993 | 1205.25 | 1190.23 | 0.988 | nan | nan | nan | | same | +| q30 | 264.87 | 266.35 | 1.006 | 280.50 | 276.89 | 0.987 | 829.64 | 819.75 | 0.988 | nan | nan | nan | | same | +| q31 | 55.20 | 55.76 | 1.010 | 124.29 | 124.88 | 1.005 | 237.29 | 238.11 | 1.003 | nan | nan | nan | | same | +| q32 | 69.19 | 68.97 | 0.997 | 180.26 | 178.97 | 0.993 | 321.53 | 319.79 | 0.995 | nan | nan | nan | | same | +| q33 | 216.09 | 212.58 | 0.984 | 461.65 | 377.16 | 0.817 | 901.81 | 808.26 | 0.896 | nan | nan | nan | | same | +| q34 | 43.40 | 43.16 | 0.995 | 97.46 | 94.99 | 0.975 | 188.36 | 185.06 | 0.982 | nan | nan | nan | | same | +| q35 | 387.32 | 43.21 | 0.112 | 2322.52 | 96.04 | 0.041 | 3107.97 | 183.01 | 0.059 | nan | nan | nan | | same | +| q36 | 148.87 | 146.00 | 0.981 | 217.93 | 214.84 | 0.986 | 518.94 | 512.59 | 0.988 | nan | nan | nan | | same | +| q37 | 36.47 | 35.86 | 0.983 | 69.81 | 69.09 | 0.990 | 144.11 | 141.47 | 0.982 | nan | nan | nan | | same | +| q38 | 35.63 | 34.95 | 0.981 | 67.78 | 67.70 | 0.999 | 145.01 | 144.27 | 0.995 | nan | nan | nan | | same | +| q39 | 15.48 | 15.09 | 0.975 | 27.62 | 27.18 | 0.984 | 59.56 | 57.98 | 0.974 | nan | nan | nan | | same | +| q40 | 117.34 | 116.40 | 0.992 | 422.09 | 419.54 | 0.994 | 662.64 | 655.30 | 0.989 | nan | nan | nan | | same | +| q41 | 17.64 | 17.53 | 0.994 | 39.03 | 39.12 | 1.002 | 74.52 | 74.83 | 1.004 | nan | nan | nan | | same | +| q42 | 13.52 | 13.07 | 0.967 | 24.18 | 23.87 | 0.987 | 51.47 | 50.55 | 0.982 | nan | nan | nan | | same | +| q43 | 28.39 | 27.96 | 0.985 | 40.79 | 40.65 | 0.997 | 98.25 | 97.15 | 0.989 | nan | nan | nan | | same | + +``` +totals over all 43: warm 9853.0 vs 9420.7 (0.956); first run 25034.9 vs 22481.2 (0.898); 3-run 44936.0 vs 41477.6 (0.923) +answer_mismatches none +order_differences none +gen0 warm_gmean=0.943 warm_worst=1.168 worst5 [(1.168, 'q28'), (1.069, 'q1'), (1.014, 'q21'), (1.01, 'q31'), (1.008, 'q23')] +q16 first run base 144.5 ms, p2 100.7 ms (carry 2) +``` + +### arm R: parted ragged, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.963 | 0.01 | 0.01 | 0.977 | 0.01 | 0.01 | 0.978 | nan | nan | nan | | same | +| q2 | 7.73 | 8.78 | 1.136 | 18.17 | 18.60 | 1.024 | 33.95 | 36.45 | 1.074 | nan | nan | nan | | same | +| q3 | 578.33 | 274.39 | 0.474 | 592.51 | 286.43 | 0.483 | 1757.86 | 838.04 | 0.477 | nan | nan | nan | | same | +| q4 | 279.41 | 275.59 | 0.986 | 327.15 | 320.92 | 0.981 | 888.31 | 875.27 | 0.985 | nan | nan | nan | | same | +| q5 | 277.18 | 274.38 | 0.990 | 326.30 | 321.24 | 0.984 | 888.94 | 873.79 | 0.983 | nan | nan | nan | | same | +| q6 | 344.61 | 345.84 | 1.004 | 9719.35 | 9746.01 | 1.003 | 10417.85 | 10446.22 | 1.003 | nan | nan | nan | | same | +| q7 | 529.83 | 528.19 | 0.997 | 553.66 | 557.71 | 1.007 | 1612.25 | 1620.38 | 1.005 | nan | nan | nan | | same | +| q8 | 9.62 | 14.12 | 1.468 | 22.56 | 16.59 | 0.735 | 42.02 | 45.32 | 1.078 | nan | nan | nan | | same | +| q9 | 89.22 | 85.78 | 0.961 | 177.20 | 155.12 | 0.875 | 358.80 | 329.99 | 0.920 | nan | nan | nan | | same | +| q10 | 87.75 | 82.70 | 0.942 | 203.49 | 159.60 | 0.784 | 388.26 | 327.99 | 0.845 | nan | nan | nan | | same | +| q11 | 377.48 | 373.51 | 0.989 | 659.69 | 655.83 | 0.994 | 1418.56 | 1409.88 | 0.994 | nan | nan | nan | | same | +| q12 | 374.41 | 370.60 | 0.990 | 656.45 | 651.22 | 0.992 | 1410.51 | 1398.69 | 0.992 | nan | nan | nan | | same | +| q13 | 40.03 | 40.39 | 1.009 | 70.73 | 70.97 | 1.003 | 151.95 | 153.32 | 1.009 | nan | nan | nan | | same | +| q14 | 1187.45 | 1170.07 | 0.985 | 1535.19 | 1502.05 | 0.978 | 3926.25 | 3871.90 | 0.986 | nan | nan | nan | | same | +| q15 | 46.51 | 46.32 | 0.996 | 89.84 | 89.77 | 0.999 | 187.90 | 187.62 | 0.998 | nan | nan | nan | | same | +| q16 | 76.12 | 72.54 | 0.953 | 147.95 | 99.33 | 0.671 | 302.53 | 245.21 | 0.811 | nan | nan | nan | | same | +| q17 | 103.70 | 95.15 | 0.918 | 205.98 | 135.02 | 0.655 | 416.35 | 328.33 | 0.789 | nan | nan | nan | | same | +| q18 | 17.09 | 16.99 | 0.994 | 86.74 | 84.14 | 0.970 | 121.09 | 118.07 | 0.975 | nan | nan | nan | | same | +| q19 | 141.36 | 141.32 | 1.000 | 337.89 | 336.63 | 0.996 | 623.79 | 624.58 | 1.001 | nan | nan | nan | | same | +| q20 | 4.47 | 4.52 | 1.011 | 14.21 | 14.31 | 1.007 | 23.47 | 23.75 | 1.012 | nan | nan | nan | | same | +| q21 | 41.74 | 41.84 | 1.003 | 46.64 | 46.74 | 1.002 | 130.41 | 130.94 | 1.004 | nan | nan | nan | | same | +| q22 | 60.64 | 60.60 | 0.999 | 86.23 | 87.11 | 1.010 | 209.90 | 210.55 | 1.003 | nan | nan | nan | | same | +| q23 | 93.56 | 94.03 | 1.005 | 273.81 | 269.62 | 0.985 | 465.64 | 464.65 | 0.998 | nan | nan | nan | | same | +| q24 | 44.49 | 44.77 | 1.006 | 193.57 | 192.45 | 0.994 | 287.89 | 286.46 | 0.995 | nan | nan | nan | | same | +| q25 | 1122.11 | 1111.83 | 0.991 | 1439.10 | 1421.51 | 0.988 | 3707.26 | 3654.40 | 0.986 | nan | nan | nan | | same | +| q26 | 1182.70 | 1167.93 | 0.988 | 1595.74 | 1577.64 | 0.989 | 3975.71 | 3915.87 | 0.985 | nan | nan | nan | | same | +| q27 | 1137.22 | 1125.48 | 0.990 | 1451.73 | 1429.17 | 0.984 | 3740.65 | 3689.33 | 0.986 | nan | nan | nan | | same | +| q28 | 91.88 | 107.85 | 1.174 | 147.68 | 165.83 | 1.123 | 334.28 | 383.42 | 1.147 | nan | nan | nan | | same | +| q29 | 362.83 | 359.28 | 0.990 | 475.31 | 469.26 | 0.987 | 1205.11 | 1192.57 | 0.990 | nan | nan | nan | | same | +| q30 | 265.22 | 269.17 | 1.015 | 282.56 | 277.77 | 0.983 | 833.58 | 830.24 | 0.996 | nan | nan | nan | | same | +| q31 | 55.26 | 55.39 | 1.002 | 125.28 | 124.48 | 0.994 | 237.67 | 238.05 | 1.002 | nan | nan | nan | | same | +| q32 | 69.19 | 68.69 | 0.993 | 180.81 | 181.38 | 1.003 | 319.60 | 321.41 | 1.006 | nan | nan | nan | | same | +| q33 | 216.50 | 211.18 | 0.975 | 469.00 | 376.67 | 0.803 | 910.37 | 807.20 | 0.887 | nan | nan | nan | | same | +| q34 | 43.31 | 42.99 | 0.993 | 96.43 | 96.14 | 0.997 | 184.89 | 183.52 | 0.993 | nan | nan | nan | | same | +| q35 | 410.91 | 42.99 | 0.105 | 2413.37 | 96.23 | 0.040 | 3238.69 | 182.62 | 0.056 | nan | nan | nan | | same | +| q36 | 149.45 | 146.72 | 0.982 | 216.86 | 215.22 | 0.992 | 521.42 | 511.41 | 0.981 | nan | nan | nan | | same | +| q37 | 36.18 | 35.88 | 0.992 | 73.06 | 72.50 | 0.992 | 146.74 | 146.88 | 1.001 | nan | nan | nan | | same | +| q38 | 35.14 | 34.62 | 0.985 | 73.36 | 73.09 | 0.996 | 148.24 | 146.13 | 0.986 | nan | nan | nan | | same | +| q39 | 15.14 | 14.85 | 0.981 | 29.02 | 28.76 | 0.991 | 59.82 | 58.97 | 0.986 | nan | nan | nan | | same | +| q40 | 151.47 | 157.40 | 1.039 | 461.18 | 466.83 | 1.012 | 772.26 | 790.21 | 1.023 | nan | nan | nan | | same | +| q41 | 17.39 | 18.28 | 1.051 | 42.08 | 39.44 | 0.937 | 78.24 | 76.10 | 0.973 | nan | nan | nan | | same | +| q42 | 13.30 | 13.72 | 1.031 | 26.31 | 24.74 | 0.940 | 53.13 | 52.58 | 0.990 | nan | nan | nan | | same | +| q43 | 28.35 | 27.89 | 0.984 | 42.28 | 41.29 | 0.976 | 99.99 | 98.17 | 0.982 | nan | nan | nan | | same | + +``` +totals over all 43: warm 10216.3 vs 9474.6 (0.927); first run 25986.5 vs 22995.4 (0.885); 3-run 46632.1 vs 42126.5 (0.903) +answer_mismatches none +order_differences none +gen0 warm_gmean=0.940 warm_worst=1.468 worst5 [(1.468, 'q8'), (1.174, 'q28'), (1.136, 'q2'), (1.051, 'q41'), (1.039, 'q40')] +``` + +Splayed: scan-only warm gmean 0.730 (worst q2 5.288), first-run gmean 1.007 +(worst q2 4.734), cold gmean 0.394 (worst q39 2.085); all-43 totals warm +1.055, first run 2.453 (PI after P1: 2.99), 3-run 1.634. Parted: scan-only +warm gmean 0.535 (worst q18 5.676), first-run gmean 0.523 (worst q8 3.223), +cold gmean 0.336 (worst q33 1.225); all-43 totals warm 0.887, first run 1.301, +3-run 1.122. Generation 0 against the base binary: splayed warm gmean 0.982 +(worst q27 1.170), parted 0.943 (worst q28 1.168), ragged 0.940 (worst q8 +1.468); q16 parted first run 144.5 -> 100.7 ms (carry 2). +Encodings: the only key with DELTA vectors is UserID (splayed 97 of 9 766 +vectors delta_bp, 9 526 rle; parted 89). Decoded bytes per run over the plain +column (probe on the release library, gen 2): q16 UserID 1.052x splayed, +1.055x parted; q17 UserID and SearchPhrase 2.059x splayed, 2.058x parted; +q19 (splayed) the same 2.059x; +q2 AdvEngineID 0.928x splayed; q8 AdvEngineID 1.998x parted; q18 parted 1.0x +of both keys per run. +Materialized columns by class (gen 2): distinct counts q9 q10 (q6 parted); +file-domain SYM compares q11-q15, q31 q32, q37 q38; LIKE q21-q23; strlen q28 +q29; whole-row top-k gathers q24-q27 (104 columns splayed, 105 parted); q30 +sets ResolutionWidth; computed key q19 (EventTime); conjunction gathers +q37-q43; P3-deferred q18 (splayed) and q39. Not explained by these classes: +parted q11, q12, q14 and q23 materialize all 105 columns. + +Gate (failing clauses, worst five, ratio gen2/gen0 or p2/base): +- splayed warm (scan-only): q2 5.288, q8 3.585, q17 1.284, q7 1.119, q33 1.116 +- splayed cold: q39 2.085, q7 1.770, q4 1.220, q1 1.018, q33 0.992 +- splayed first: q2 4.734, q18 2.729, q39 2.661, q8 1.979, q7 1.660 +- splayed materializing warm: q20 2.888, q42 2.611, q15 1.411, q6 1.409, q5 1.259 +- parted warm (scan-only): q18 5.676, q8 3.020, q2 1.494, q17 1.290, q33 1.144 +- parted cold: q33 1.225 (only one over 1.10) +- parted first: q8 3.223, q18 1.865, q39 1.642, q17 1.262, q33 1.113 +- parted materializing warm: q31 2.627, q32 2.477, q42 1.716, q19 1.638, q15 1.386 +- gen0 splayed warm: q27 1.170, q25 1.078, q6 1.070, q4 1.046, q28 1.046 +- gen0 parted warm: q28 1.168, q1 1.069, q21 1.014, q31 1.010, q23 1.008 +- gen0 ragged warm: q8 1.468, q28 1.174, q2 1.136, q41 1.051, q40 1.039 + +Gate lines of this run as printed by the current p2_summary.py (noise floor, +measured classes, the first P3_DEFERRALS table; the first run's own printout +used an older clause set): + +``` +GATE (strict) splayed[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=FAIL first_total=PASS] parted[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=FAIL] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=PASS] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=PASS first=FAIL materializing_warm=FAIL no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=PASS] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (P3-exempt): FAIL +``` + + +## P2 gate (re-run) + +Re-run of the P2 gate after the gate fix tasks 17a-17h, on HEAD a09a54eb +(release build, sha256 4b72499b44ed) against the base 80a28e49 (release +build from `git archive`, sha256 c204703a62de). Method, loads, arms and +store sizes are as in "P2 range reads" above: `p2_bench.sh all` as +committed, 5 alternated rounds, 3 cold trials per query (fadvise eviction), +full answers compared; the ragged partition 9 keeps 40 columns. Raw data: +/home/hetoku/data/tmp/p2_rerun/p2.tsv (summary.txt beside it). The machine +was otherwise idle (19:13-21:05). + +Sizes are unchanged (g0 5 948 677 939 B, g2 3 307 128 731 B; p0 +4 807 844 987 B, p2 2 072 366 907 B). Peak RSS over all 43 queries: g0 +5 111 620 kB, g2 8 099 412 kB (x1.58; the q24-q27 whole-row top-k +gathers stay cached); p0 15 208 624 kB, p2 15 875 328 kB (x1.04). +Answers: identical on all five arms (0 mismatches, 0 order differences). + +### Gate lines + +``` +GATE (strict) splayed[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=FAIL first_total=PASS] parted[answers=PASS warm=FAIL cold=PASS first=FAIL materializing_warm=FAIL no_unexpected_materialization=FAIL] gen0-splayed[answers=PASS warm=PASS] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=PASS first=FAIL materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=FAIL cold=PASS first=FAIL materializing_warm=FAIL no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=PASS] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (P3-exempt): FAIL +``` + +**The P2 gate fails in both variants.** Generation 0 now passes on every +arm (splayed warm gmean 0.972, parted 0.772, ragged 0.759; q16 parted first +run 146.4 -> 100.8 ms), as do answers, no_unexpected_materialization, +splayed first_total (1.836 vs PI's 2.99) and both cold clauses with the +deferrals. The P3-exempt failures: + +| clause | query | a -> b (ms) | ratio | deferral | +|---|---|---|---|---| +| splayed warm (scan-only) | q33 | 203.29 -> 226.35 | 1.113 | none | +| splayed warm (scan-only) | q34 | 39.03 -> 41.10 | 1.053 | none | +| splayed first (scan-only) | q2 | 1.70 -> 5.49 | 3.219 | q2 has a warm deferral only | +| parted warm (scan-only) | q33 | 211.41 -> 227.61 | 1.077 | none | +| parted first (scan-only) | q8 | 8.33 -> 11.87 | 1.424 | q8 has a warm deferral only | +| parted materializing warm | q32 | 68.71 -> 73.86 | 1.075 | none | + +No other query fails a clause after the exemptions. Below the bound but +close: splayed q35 warm 1.048, parted q31 warm 1.033. Every failing ratio +reproduces in all five rounds: splayed q33 g0 203.3-205.3 against g2 +226.4-230.8 ms; q34 39.0-39.3 against 41.1-41.4 ms; q2 first run 1.64-1.82 +against 5.06-5.60 ms. + +### What the fixes moved (first gate run -> re-run, ratio gen2/gen0) + +- Splayed warm: q2 5.288 -> 1.086 (0.66 ms), q8 3.585 -> 1.424, q17 + 1.284 -> 1.016, q20 2.888 -> 0.633, q42 2.611 -> 1.664, q15 1.411 -> + 1.023, q19 1.180 -> 1.031. q33 1.116 -> 1.113 (unchanged). +- Parted warm: q18 5.676 -> 1.088, q8 3.020 -> 1.060, q2 1.494 -> 1.002, + q31 2.627 -> 1.033, q32 2.477 -> 1.075, q19 1.638 -> 1.027, q42 1.716 -> + 1.237, q36 1.257 -> 1.002. q33 1.144 -> 1.077. +- Parted q11, q12, q14 and q23 now gather only their own columns (2-4 + instead of 105); p0 warm q11 357 -> 24 ms, q14 1 117 -> 102 ms; their p2 + first runs are 1.10-1.28x p0 instead of 1.7-4.7x. +- First runs: splayed q24-q27 790-830 -> 450-484 ms (still 14-105x g0: the + whole-row top-k gather materializes 100 columns); all-43 first-run total + 2.453 -> 1.836. +- Generation 0 against the base: parted q28 1.168 -> 0.983, ragged q28 + 1.174 -> 0.990, ragged q8 1.468 -> 0.906, ragged q2 1.136 -> 0.976, + splayed q25 / q27 0.874 / 0.932, splayed q28 0.986. + +### Profiles of the worst failures + +Profiled on recreated splayed stores (deleted afterwards), the gate's p2 +binary, perf without call graphs. + +- **Splayed q33** (`by {WatchID ClientIP}`, count, sum, avg, `desc: c + take: 10`; 25 runs). g2 takes the fused radix pass that 17c admitted + for 32-byte records; g0 keeps the two-pass radix over the plain columns. + Radix samples: g0 96.1 K (agg_radix_group_fn 30.8%, scatter_fn 23.2%, + count_fn 6.9%); g2 107.9 K (agg_radix_group_fused_fn 36.9%, + agg_radix_chunk_fused 14.9%, agg_radix_stage_block 9.2%, + fused_totals_fn 1.1%), so +12% in the radix itself. Decode is small + (dec_fast_runs 2.3%), and memmove is about the same on both (12-14%). The + residual is the fused route's staging copy and a slower group pass over + chunk-major partitions, not decoding. Parted q33 (1.077) has the same + shape. +- **Splayed q2 first run** (`count where AdvEngineID != 0`; 1.6 -> 5.5 + ms; run 2 is 0.8 ms on both). CPU and page faults are about equal over + the process (g0 333.7 ms task-clock and 36 073 faults; g2 342.5 ms and + 35 675). The difference is one kernel hotspot (+4 951 samples over 60 + processes; the symbol is hidden by kptr_restrict) and dec_fast_runs + (+1 111). On g2 each pool worker creates its 32 MB buddy arena + (`madvise(MADV_HUGEPAGE)` on 8 arenas, seen in strace) on its first decode + and faults in fresh zeroed huge pages; g0's count reads the mapped plain + column in place and allocates nothing in the workers. This is a fixed + first-parallel-decode cost per process (about 4 ms), not per query. By + the same reading, parted q8's first run (+3.5 ms) is the same fixed + cost. This was inferred and not profiled separately. +- **Splayed q34** (`by URL`, count, `take: 10`): g2 adds the URL key decode + (dec_fast 9.7% of samples); agg_dense_partition_count_rows drops on g2, + and the net is +5%. + +### Remaining P3 deferrals (P3_DEFERRALS, max_ratio about 1.5x the re-run ratio, per arm) + +``` +q2/A/warm[run-level compute (count over RLE runs)]: 0.61 -> 0.66 ms (x1.086) EXEMPTED +q8/A/warm[run-level compute (group over RLE runs)]: 3.55 -> 5.05 ms (x1.424) EXEMPTED +q8/B/warm[run-level compute (group over RLE runs)]: 6.28 -> 6.66 ms (x1.060) EXEMPTED +q18/A/first[row-list gather (first-n keys published, P3 path 2)]: 13.46 -> 26.70 ms (x1.983) EXEMPTED +q18/B/warm[row-list gather (parted first-n compact build, P3)]: 17.06 -> 18.56 ms (x1.088) EXEMPTED +q39/A/first[selection gather (P3 path 2)]: 14.55 -> 34.94 ms (x2.402) EXEMPTED +q39/B/first[selection gather (P3 path 2)]: 27.30 -> 41.04 ms (x1.503) EXEMPTED +q39/A/cold[selection gather reads whole columns cold (P3)]: 38.04 -> 81.94 ms (x2.154) EXEMPTED +q42/A/warm[point gathers of the selected keys (P3)]: 4.52 -> 7.53 ms (x1.664) EXEMPTED +q42/B/warm[point gathers of the selected keys (P3)]: 13.21 -> 16.34 ms (x1.237) EXEMPTED +q24/A/rss[top-k output gather RSS]: arm peak-RSS 5111620 -> 8099412 kB (x1.58, max 2.4) not gated +q25/A/rss[top-k output gather RSS]: arm peak-RSS 5111620 -> 8099412 kB (x1.58, max 2.4) not gated +q26/A/rss[top-k output gather RSS]: arm peak-RSS 5111620 -> 8099412 kB (x1.58, max 2.4) not gated +q27/A/rss[top-k output gather RSS]: arm peak-RSS 5111620 -> 8099412 kB (x1.58, max 2.4) not gated +``` + +Removed because their clauses now pass: q2 parted warm, q18 splayed warm, +q18 parted first, q39 warm (both loads), q39 parted cold, and the parted +q24-q27 RSS rows (parted peak RSS x1.04). + +### Per-query tables (re-run) + +#### arm A: splayed g0 vs g2 (ms; ratio = g2/g0) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.000 | 0.01 | 0.01 | 0.949 | 0.01 | 0.01 | 0.947 | 0.01 | 0.01 | 1.599 | [] | same | +| q2 | 0.61 | 0.66 | 1.086 | 1.70 | 5.49 | 3.219 | 3.26 | 6.89 | 2.111 | 38.51 | 6.16 | 0.160 | [] | same | +| q3 | 3.79 | 0.00 | 0.001 | 5.74 | 0.04 | 0.007 | 13.40 | 0.05 | 0.004 | 94.24 | 0.04 | 0.000 | [] | same | +| q4 | 0.00 | 0.00 | 1.128 | 0.03 | 0.03 | 1.214 | 0.03 | 0.03 | 1.206 | 0.02 | 0.03 | 1.551 | [] | same | +| q5 | 0.00 | 0.00 | 1.303 | 0.03 | 0.03 | 1.030 | 0.03 | 0.03 | 1.033 | 0.03 | 0.03 | 0.989 | [] | same | +| q6 | 0.00 | 0.00 | 1.201 | 0.03 | 0.03 | 0.881 | 0.03 | 0.03 | 0.889 | 0.04 | 0.03 | 0.981 | [] | same | +| q7 | 0.00 | 0.00 | 1.103 | 0.02 | 0.04 | 1.766 | 0.02 | 0.04 | 1.652 | 0.02 | 0.04 | 1.680 | [] | same | +| q8 | 3.55 | 5.05 | 1.424 | 9.44 | 9.87 | 1.046 | 16.69 | 20.11 | 1.205 | 41.36 | 10.76 | 0.260 | [] | same | +| q9 | 75.06 | 74.98 | 0.999 | 114.34 | 125.02 | 1.093 | 266.42 | 278.85 | 1.047 | 698.31 | 155.01 | 0.222 | [RegionID UserID] | same | +| q10 | 68.90 | 72.07 | 1.046 | 104.68 | 120.58 | 1.152 | 242.78 | 267.98 | 1.104 | 427.77 | 158.53 | 0.371 | [RegionID UserID] | same | +| q11 | 16.12 | 16.04 | 0.995 | 25.11 | 40.65 | 1.619 | 57.67 | 73.03 | 1.266 | 255.95 | 61.36 | 0.240 | [UserID MobilePhoneModel] | same | +| q12 | 16.18 | 16.24 | 1.004 | 25.81 | 44.30 | 1.717 | 59.76 | 77.41 | 1.295 | 291.81 | 65.94 | 0.226 | [UserID MobilePhone MobilePhoneModel] | same | +| q13 | 32.01 | 32.08 | 1.002 | 41.77 | 48.69 | 1.166 | 106.63 | 113.51 | 1.065 | 112.69 | 63.89 | 0.567 | [SearchPhrase] | same | +| q14 | 62.67 | 63.03 | 1.006 | 88.97 | 105.38 | 1.184 | 217.83 | 236.32 | 1.085 | 315.91 | 140.80 | 0.446 | [UserID SearchPhrase] | same | +| q15 | 36.50 | 37.35 | 1.023 | 48.21 | 57.46 | 1.192 | 122.73 | 133.70 | 1.089 | 155.79 | 102.64 | 0.659 | [SearchPhrase] | same | +| q16 | 69.84 | 67.42 | 0.965 | 94.34 | 87.91 | 0.932 | 235.40 | 226.02 | 0.960 | 255.81 | 162.48 | 0.635 | [] | same | +| q17 | 92.86 | 94.32 | 1.016 | 128.91 | 124.79 | 0.968 | 316.31 | 316.21 | 1.000 | 474.95 | 254.52 | 0.536 | [] | same | +| q18 | 6.85 | 6.86 | 1.000 | 13.46 | 26.70 | 1.983 | 27.28 | 40.65 | 1.490 | 663.98 | 61.71 | 0.093 | [UserID SearchPhrase] | same | +| q19 | 138.42 | 142.69 | 1.031 | 210.43 | 211.84 | 1.007 | 490.20 | 502.86 | 1.026 | 674.62 | 439.78 | 0.652 | [EventTime] | same | +| q20 | 1.14 | 0.72 | 0.633 | 6.76 | 5.80 | 0.859 | 9.42 | 7.38 | 0.784 | 57.72 | 16.35 | 0.283 | [] | same | +| q21 | 41.72 | 41.77 | 1.001 | 45.25 | 53.08 | 1.173 | 130.18 | 137.60 | 1.057 | 77.09 | 92.35 | 1.198 | [URL] | same | +| q22 | 27.55 | 27.50 | 0.998 | 32.10 | 58.67 | 1.828 | 87.85 | 114.60 | 1.304 | 185.06 | 133.91 | 0.724 | [UserID URL SearchPhrase] | same | +| q23 | 48.77 | 48.92 | 1.003 | 60.42 | 92.66 | 1.534 | 159.54 | 192.46 | 1.206 | 492.28 | 204.24 | 0.415 | [Title UserID URL SearchPhrase] | same | +| q24 | 29.30 | 29.43 | 1.005 | 34.47 | 483.77 | 14.036 | 93.41 | 542.82 | 5.811 | 618.09 | 1229.60 | 1.989 | <100 columns> | same | +| q25 | 0.94 | 0.95 | 1.011 | 4.46 | 451.93 | 101.392 | 6.44 | 454.06 | 70.496 | 305.32 | 1206.99 | 3.953 | <100 columns> | same | +| q26 | 10.82 | 10.80 | 0.998 | 15.31 | 459.17 | 29.984 | 37.01 | 481.05 | 12.997 | 585.28 | 1227.12 | 2.097 | <100 columns> | same | +| q27 | 0.98 | 0.90 | 0.919 | 4.27 | 450.00 | 105.411 | 6.42 | 451.97 | 70.425 | 302.35 | 1207.00 | 3.992 | <100 columns> | same | +| q28 | 80.93 | 66.20 | 0.818 | 83.14 | 80.92 | 0.973 | 246.00 | 215.26 | 0.875 | 219.68 | 120.88 | 0.550 | [URL] | same | +| q29 | 349.56 | 349.14 | 0.999 | 436.06 | 445.20 | 1.021 | 1136.91 | 1146.86 | 1.009 | 512.71 | 492.02 | 0.960 | [Referer] | same | +| q30 | 0.02 | 0.03 | 1.709 | 2.81 | 5.36 | 1.904 | 2.88 | 5.43 | 1.884 | 56.07 | 11.36 | 0.203 | [ResolutionWidth] | same | +| q31 | 51.88 | 51.59 | 0.994 | 69.69 | 94.36 | 1.354 | 173.70 | 198.10 | 1.140 | 317.84 | 139.08 | 0.438 | [ClientIP IsRefresh ResolutionWidth SearchEngineID SearchPhrase] | same | +| q32 | 58.95 | 58.87 | 0.999 | 85.08 | 107.21 | 1.260 | 203.40 | 226.66 | 1.114 | 442.13 | 283.20 | 0.641 | [ClientIP IsRefresh ResolutionWidth SearchPhrase] | same | +| q33 | 203.29 | 226.35 | 1.113 | 365.04 | 373.20 | 1.022 | 776.52 | 833.91 | 1.074 | 593.34 | 566.05 | 0.954 | [] | same | +| q34 | 39.03 | 41.10 | 1.053 | 69.48 | 73.98 | 1.065 | 148.04 | 156.24 | 1.055 | 141.98 | 110.62 | 0.779 | [] | same | +| q35 | 39.29 | 41.17 | 1.048 | 69.90 | 73.94 | 1.058 | 151.71 | 157.04 | 1.035 | 138.49 | 110.54 | 0.798 | [] | same | +| q36 | 64.06 | 64.21 | 1.002 | 88.60 | 81.73 | 0.922 | 217.62 | 213.36 | 0.980 | 160.18 | 126.43 | 0.789 | [] | same | +| q37 | 16.56 | 16.54 | 0.999 | 27.10 | 44.94 | 1.659 | 60.88 | 78.54 | 1.290 | 43.66 | 87.74 | 2.010 | [EventDate URL IsRefresh DontCountHits] | same | +| q38 | 14.91 | 14.91 | 1.000 | 24.54 | 42.29 | 1.724 | 55.71 | 72.18 | 1.296 | 43.25 | 81.69 | 1.889 | [Title EventDate IsRefresh DontCountHits] | same | +| q39 | 7.16 | 7.23 | 1.010 | 14.55 | 34.94 | 2.402 | 28.97 | 49.55 | 1.710 | 38.04 | 81.94 | 2.154 | [EventDate URL IsRefresh IsLink IsDownload] | same | +| q40 | 58.91 | 58.46 | 0.992 | 90.61 | 127.01 | 1.402 | 210.68 | 245.31 | 1.164 | 118.32 | 229.58 | 1.940 | [EventDate CounterID URL Referer IsRefresh TraficSourceID SearchEngineID AdvEngineID] | same | +| q41 | 5.79 | 5.75 | 0.993 | 13.17 | 27.12 | 2.059 | 25.41 | 39.19 | 1.542 | 74.77 | 48.43 | 0.648 | [EventDate CounterID IsRefresh TraficSourceID] | same | +| q42 | 4.52 | 7.53 | 1.664 | 11.14 | 27.83 | 2.498 | 20.54 | 43.31 | 2.109 | 39.07 | 39.70 | 1.016 | [EventDate CounterID IsRefresh DontCountHits] | same | +| q43 | 8.95 | 8.90 | 0.994 | 18.32 | 41.98 | 2.291 | 37.10 | 60.29 | 1.625 | 41.87 | 146.39 | 3.497 | [EventTime EventDate CounterID IsRefresh DontCountHits] | same | + +``` +totals over all 43: warm 1788.4 vs 1807.8 (1.011); first run 2585.3 vs 4746.0 (1.836); 3-run 6202.8 vs 8416.9 (1.357) +answer_mismatches none +order_differences none +scan_only(gated) n=17; gmeans over base>=1ms (per column): warm n=11 0.512, first n=12 0.821, cold n=12 0.270; worst warm=1.424 +below_1ms_excluded_from_warm_gmean q1 q2 q4 q5 q6 q7 +below_1ms_excluded_from_first_gmean q1 q4 q5 q6 q7 +below_1ms_excluded_from_cold_gmean q1 q4 q5 q6 q7 +mat rows missing none +scan_only_list_but_materializing q18 q39 +measured_materializing q9(2 cols) q10(2 cols) q11(2 cols) q12(3 cols) q13(1 cols) q14(2 cols) q15(1 cols) q18(2 cols) q19(1 cols) q21(1 cols) q22(3 cols) q23(4 cols) q24(100 cols) q25(100 cols) q26(100 cols) q27(100 cols) q28(1 cols) q29(1 cols) q30(1 cols) q31(5 cols) q32(4 cols) q37(4 cols) q38(4 cols) q39(5 cols) q40(8 cols) q41(4 cols) q42(4 cols) q43(5 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q6(measured scan, list other) q18(measured materializing, list scan) q20(measured scan, list other) q36(measured scan, list other) q39(measured materializing, list scan) +worst5 warm [(1.424, 'q8'), (1.303, 'q5'), (1.201, 'q6'), (1.128, 'q4'), (1.113, 'q33')] +worst5 cold [(2.154, 'q39'), (1.68, 'q7'), (1.599, 'q1'), (1.551, 'q4'), (0.989, 'q5')] +worst5 first [(3.219, 'q2'), (2.402, 'q39'), (1.983, 'q18'), (1.766, 'q7'), (1.214, 'q4')] +worst5 materializing_warm [(1.709, 'q30'), (1.664, 'q42'), (1.046, 'q10'), (1.031, 'q19'), (1.023, 'q15')] +first_run_total_ratio 1.836 (PI after P1: 2.99) +pi_row q41 warm 0.993 first 2.059 3run 1.542 +pi_row q42 warm 1.664 first 2.498 3run 2.109 +``` + +#### arm B: parted p0 vs p2 (ms; ratio = p2/p0) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.939 | 0.01 | 0.01 | 1.021 | 0.01 | 0.01 | 1.013 | 0.01 | 0.01 | 1.641 | [] | same | +| q2 | 6.59 | 6.61 | 1.002 | 17.02 | 16.66 | 0.979 | 30.59 | 29.92 | 0.978 | 46.71 | 16.12 | 0.345 | [] | same | +| q3 | 526.01 | 5.80 | 0.011 | 546.45 | 10.36 | 0.019 | 1605.41 | 22.22 | 0.014 | 572.75 | 14.51 | 0.025 | [] | same | +| q4 | 273.95 | 7.40 | 0.027 | 324.65 | 12.19 | 0.038 | 875.53 | 27.25 | 0.031 | 364.44 | 31.48 | 0.086 | [] | same | +| q5 | 275.75 | 0.00 | 0.000 | 318.24 | 0.03 | 0.000 | 879.49 | 0.03 | 0.000 | 367.60 | 0.03 | 0.000 | [] | same | +| q6 | 340.90 | 340.28 | 0.998 | 9631.26 | 9644.03 | 1.001 | 10315.67 | 10322.85 | 1.001 | 9704.46 | 9738.85 | 1.004 | [SearchPhrase] | same | +| q7 | 528.29 | 2.55 | 0.005 | 552.67 | 6.78 | 0.012 | 1614.34 | 12.05 | 0.007 | 584.52 | 6.99 | 0.012 | [] | same | +| q8 | 6.28 | 6.66 | 1.060 | 8.33 | 11.87 | 1.424 | 21.43 | 25.28 | 1.179 | 40.91 | 12.13 | 0.297 | [] | same | +| q9 | 85.49 | 83.04 | 0.971 | 151.33 | 168.06 | 1.111 | 325.67 | 339.87 | 1.044 | 392.07 | 190.61 | 0.486 | [RegionID UserID] | same | +| q10 | 79.28 | 79.92 | 1.008 | 152.67 | 173.23 | 1.135 | 317.84 | 338.26 | 1.064 | 445.44 | 204.18 | 0.458 | [RegionID UserID] | same | +| q11 | 24.22 | 23.35 | 0.964 | 59.87 | 66.57 | 1.112 | 110.25 | 115.41 | 1.047 | 386.31 | 86.32 | 0.223 | [UserID MobilePhoneModel] | same | +| q12 | 26.76 | 25.89 | 0.968 | 61.73 | 71.87 | 1.164 | 115.70 | 123.51 | 1.067 | 442.56 | 91.15 | 0.206 | [UserID MobilePhone MobilePhoneModel] | same | +| q13 | 40.16 | 39.51 | 0.984 | 70.53 | 76.09 | 1.079 | 151.55 | 160.77 | 1.061 | 155.34 | 89.21 | 0.574 | [SearchPhrase] | same | +| q14 | 102.09 | 101.84 | 0.998 | 153.81 | 168.49 | 1.095 | 356.99 | 376.16 | 1.054 | 447.03 | 198.01 | 0.443 | [UserID SearchPhrase] | same | +| q15 | 46.66 | 46.36 | 0.994 | 89.59 | 87.05 | 0.972 | 185.61 | 181.49 | 0.978 | 212.99 | 104.60 | 0.491 | [SearchPhrase] | same | +| q16 | 72.51 | 67.96 | 0.937 | 98.04 | 88.21 | 0.900 | 244.76 | 225.69 | 0.922 | 249.61 | 151.20 | 0.606 | [] | same | +| q17 | 95.54 | 94.71 | 0.991 | 134.48 | 127.27 | 0.946 | 328.35 | 317.25 | 0.966 | 475.44 | 238.70 | 0.502 | [] | same | +| q18 | 17.06 | 18.56 | 1.088 | 83.65 | 33.74 | 0.403 | 118.10 | 71.25 | 0.603 | 338.42 | 60.62 | 0.179 | [] | same | +| q19 | 141.22 | 145.00 | 1.027 | 335.90 | 247.66 | 0.737 | 622.09 | 542.34 | 0.872 | 758.54 | 368.74 | 0.486 | [EventTime] | same | +| q20 | 4.64 | 1.58 | 0.341 | 14.10 | 12.11 | 0.859 | 23.72 | 15.78 | 0.665 | 157.26 | 22.40 | 0.142 | [] | same | +| q21 | 41.61 | 41.81 | 1.005 | 46.89 | 57.16 | 1.219 | 130.39 | 144.36 | 1.107 | 87.97 | 98.27 | 1.117 | [URL] | same | +| q22 | 60.42 | 60.33 | 0.998 | 86.10 | 111.74 | 1.298 | 208.76 | 235.71 | 1.129 | 231.42 | 181.49 | 0.784 | [UserID URL SearchPhrase] | same | +| q23 | 90.09 | 89.70 | 0.996 | 119.09 | 151.84 | 1.275 | 300.76 | 332.59 | 1.106 | 471.79 | 267.51 | 0.567 | [Title UserID URL SearchPhrase] | same | +| q24 | 44.58 | 43.67 | 0.980 | 136.70 | 611.73 | 4.475 | 225.91 | 703.59 | 3.114 | 9627.33 | 1710.92 | 0.178 | <105 columns> | same | +| q25 | 1055.56 | 1049.63 | 0.994 | 1324.40 | 1695.02 | 1.280 | 3459.65 | 3799.65 | 1.098 | 9637.01 | 2802.51 | 0.291 | <105 columns> | same | +| q26 | 1107.19 | 1099.57 | 0.993 | 1467.45 | 1841.83 | 1.255 | 3693.59 | 4043.28 | 1.095 | 9841.52 | 2960.88 | 0.301 | <105 columns> | same | +| q27 | 1070.09 | 1059.40 | 0.990 | 1337.34 | 1705.59 | 1.275 | 3481.39 | 3840.98 | 1.103 | 9685.41 | 2824.07 | 0.292 | <105 columns> | same | +| q28 | 90.95 | 87.22 | 0.959 | 146.37 | 148.83 | 1.017 | 328.87 | 326.29 | 0.992 | 306.51 | 187.99 | 0.613 | [URL] | same | +| q29 | 356.07 | 356.45 | 1.001 | 466.66 | 472.08 | 1.012 | 1185.18 | 1186.91 | 1.001 | 556.14 | 515.04 | 0.926 | [Referer] | same | +| q30 | 259.57 | 261.38 | 1.007 | 278.00 | 286.12 | 1.029 | 817.88 | 834.14 | 1.020 | 285.72 | 297.50 | 1.041 | [ResolutionWidth] | same | +| q31 | 54.99 | 56.81 | 1.033 | 125.08 | 104.90 | 0.839 | 236.97 | 223.06 | 0.941 | 425.79 | 140.07 | 0.329 | [SearchPhrase] | same | +| q32 | 68.71 | 73.86 | 1.075 | 178.93 | 132.71 | 0.742 | 317.34 | 282.16 | 0.889 | 617.89 | 297.80 | 0.482 | [SearchPhrase] | same | +| q33 | 211.41 | 227.61 | 1.077 | 372.78 | 390.88 | 1.049 | 807.99 | 847.37 | 1.049 | 612.81 | 613.61 | 1.001 | [] | same | +| q34 | 42.93 | 44.02 | 1.025 | 95.60 | 78.23 | 0.818 | 181.73 | 166.67 | 0.917 | 179.56 | 117.91 | 0.657 | [] | same | +| q35 | 42.87 | 44.05 | 1.028 | 95.81 | 78.05 | 0.815 | 182.40 | 167.37 | 0.918 | 180.97 | 116.55 | 0.644 | [] | same | +| q36 | 145.14 | 145.50 | 1.002 | 213.77 | 197.79 | 0.925 | 511.69 | 494.86 | 0.967 | 298.14 | 207.53 | 0.696 | [] | same | +| q37 | 35.93 | 34.19 | 0.952 | 71.33 | 83.84 | 1.175 | 143.19 | 153.65 | 1.073 | 224.38 | 127.33 | 0.567 | [EventDate URL IsRefresh DontCountHits] | same | +| q38 | 34.95 | 33.26 | 0.952 | 67.59 | 84.08 | 1.244 | 143.55 | 151.44 | 1.055 | 222.49 | 127.73 | 0.574 | [Title EventDate IsRefresh DontCountHits] | same | +| q39 | 15.03 | 13.32 | 0.886 | 27.30 | 41.04 | 1.503 | 57.34 | 73.05 | 1.274 | 116.25 | 49.94 | 0.430 | [EventDate URL IsRefresh IsLink IsDownload] | same | +| q40 | 116.16 | 116.46 | 1.003 | 423.77 | 364.75 | 0.861 | 658.30 | 601.00 | 0.913 | 788.41 | 457.05 | 0.580 | [EventDate IsRefresh] | same | +| q41 | 17.57 | 17.14 | 0.976 | 39.42 | 58.70 | 1.489 | 74.96 | 97.70 | 1.303 | 265.79 | 229.63 | 0.864 | [EventDate CounterID IsRefresh TraficSourceID URLHash] | same | +| q42 | 13.21 | 16.34 | 1.237 | 23.99 | 45.40 | 1.893 | 50.56 | 81.18 | 1.606 | 192.16 | 165.19 | 0.860 | [EventDate CounterID IsRefresh WindowClientWidth WindowClientHeight DontCountHits] | same | +| q43 | 27.80 | 25.74 | 0.926 | 40.92 | 63.19 | 1.544 | 97.11 | 117.60 | 1.211 | 128.79 | 157.31 | 1.221 | [EventTime EventDate IsRefresh DontCountHits] | same | + +``` +totals over all 43: warm 7696.2 vs 6094.5 (0.792); first run 19989.6 vs 19827.8 (0.992); 3-run 35538.6 vs 32152.0 (0.905) +answer_mismatches none +order_differences none +scan_only(gated) n=16; gmeans over base>=1ms (per column): warm n=15 0.159, first n=15 0.231, cold n=15 0.142; worst warm=1.088 +below_1ms_excluded_from_warm_gmean q1 +below_1ms_excluded_from_first_gmean q1 +below_1ms_excluded_from_cold_gmean q1 +mat rows missing none +scan_only_list_but_materializing q39 +measured_materializing q6(1 cols) q9(2 cols) q10(2 cols) q11(2 cols) q12(3 cols) q13(1 cols) q14(2 cols) q15(1 cols) q19(1 cols) q21(1 cols) q22(3 cols) q23(4 cols) q24(105 cols) q25(105 cols) q26(105 cols) q27(105 cols) q28(1 cols) q29(1 cols) q30(1 cols) q31(1 cols) q32(1 cols) q37(4 cols) q38(4 cols) q39(5 cols) q40(2 cols) q41(5 cols) q42(6 cols) q43(4 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q20(measured scan, list other) q36(measured scan, list other) q39(measured materializing, list scan) +worst5 warm [(1.088, 'q18'), (1.077, 'q33'), (1.06, 'q8'), (1.028, 'q35'), (1.025, 'q34')] +worst5 cold [(1.641, 'q1'), (1.001, 'q33'), (0.696, 'q36'), (0.657, 'q34'), (0.644, 'q35')] +worst5 first [(1.503, 'q39'), (1.424, 'q8'), (1.049, 'q33'), (1.021, 'q1'), (0.979, 'q2')] +worst5 materializing_warm [(1.237, 'q42'), (1.075, 'q32'), (1.033, 'q31'), (1.027, 'q19'), (1.008, 'q10')] +pi_row q41 warm 0.976 first 1.489 3run 1.303 +pi_row q42 warm 1.237 first 1.893 3run 1.606 +``` + +#### arm C0: splayed g0, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.058 | 0.01 | 0.01 | 1.820 | 0.01 | 0.01 | 1.765 | nan | nan | nan | | same | +| q2 | 1.11 | 0.63 | 0.567 | 2.01 | 1.67 | 0.833 | 4.32 | 3.11 | 0.719 | nan | nan | nan | | same | +| q3 | 3.78 | 3.79 | 1.003 | 5.73 | 5.83 | 1.017 | 13.35 | 13.49 | 1.010 | nan | nan | nan | | same | +| q4 | 0.00 | 0.00 | 1.063 | 0.02 | 0.02 | 1.170 | 0.02 | 0.03 | 1.160 | nan | nan | nan | | same | +| q5 | 0.00 | 0.00 | 1.087 | 0.02 | 0.03 | 1.258 | 0.02 | 0.03 | 1.268 | nan | nan | nan | | same | +| q6 | 0.00 | 0.00 | 1.052 | 0.02 | 0.03 | 1.196 | 0.02 | 0.03 | 1.195 | nan | nan | nan | | same | +| q7 | 0.00 | 0.00 | 0.995 | 0.02 | 0.02 | 1.123 | 0.02 | 0.02 | 1.089 | nan | nan | nan | | same | +| q8 | 3.49 | 3.53 | 1.012 | 9.08 | 8.80 | 0.969 | 16.27 | 16.07 | 0.988 | nan | nan | nan | | same | +| q9 | 75.71 | 75.25 | 0.994 | 113.89 | 112.32 | 0.986 | 268.58 | 262.98 | 0.979 | nan | nan | nan | | same | +| q10 | 69.02 | 69.16 | 1.002 | 97.58 | 97.05 | 0.995 | 237.44 | 238.34 | 1.004 | nan | nan | nan | | same | +| q11 | 16.13 | 16.17 | 1.002 | 25.15 | 25.09 | 0.998 | 57.83 | 57.83 | 1.000 | nan | nan | nan | | same | +| q12 | 16.47 | 16.30 | 0.990 | 25.73 | 25.77 | 1.001 | 59.09 | 59.34 | 1.004 | nan | nan | nan | | same | +| q13 | 31.93 | 32.19 | 1.008 | 41.16 | 41.85 | 1.017 | 105.01 | 106.02 | 1.010 | nan | nan | nan | | same | +| q14 | 62.81 | 62.57 | 0.996 | 87.56 | 89.78 | 1.025 | 216.46 | 218.50 | 1.009 | nan | nan | nan | | same | +| q15 | 36.45 | 36.37 | 0.998 | 48.39 | 48.17 | 0.996 | 125.50 | 125.06 | 0.997 | nan | nan | nan | | same | +| q16 | 69.63 | 70.03 | 1.006 | 93.90 | 95.05 | 1.012 | 236.61 | 235.36 | 0.995 | nan | nan | nan | | same | +| q17 | 92.95 | 93.00 | 1.001 | 129.64 | 130.41 | 1.006 | 320.42 | 317.92 | 0.992 | nan | nan | nan | | same | +| q18 | 6.91 | 6.89 | 0.997 | 14.45 | 14.63 | 1.013 | 28.35 | 28.40 | 1.002 | nan | nan | nan | | same | +| q19 | 137.54 | 136.75 | 0.994 | 210.31 | 207.22 | 0.985 | 490.43 | 491.09 | 1.001 | nan | nan | nan | | same | +| q20 | 1.16 | 1.13 | 0.977 | 6.78 | 6.87 | 1.013 | 9.36 | 9.79 | 1.045 | nan | nan | nan | | same | +| q21 | 41.86 | 41.77 | 0.998 | 45.19 | 45.25 | 1.001 | 129.10 | 130.72 | 1.013 | nan | nan | nan | | same | +| q22 | 27.52 | 27.57 | 1.002 | 32.13 | 32.00 | 0.996 | 87.65 | 87.56 | 0.999 | nan | nan | nan | | same | +| q23 | 48.78 | 48.88 | 1.002 | 60.45 | 60.51 | 1.001 | 159.52 | 159.40 | 0.999 | nan | nan | nan | | same | +| q24 | 29.18 | 29.57 | 1.013 | 34.34 | 34.87 | 1.015 | 92.88 | 94.20 | 1.014 | nan | nan | nan | | same | +| q25 | 1.03 | 0.90 | 0.874 | 4.42 | 4.44 | 1.004 | 6.46 | 6.62 | 1.024 | nan | nan | nan | | same | +| q26 | 10.75 | 10.81 | 1.005 | 15.36 | 15.38 | 1.001 | 37.22 | 37.40 | 1.005 | nan | nan | nan | | same | +| q27 | 0.96 | 0.89 | 0.932 | 4.39 | 4.36 | 0.993 | 6.42 | 6.25 | 0.974 | nan | nan | nan | | same | +| q28 | 82.86 | 81.72 | 0.986 | 85.43 | 86.03 | 1.007 | 251.42 | 249.28 | 0.991 | nan | nan | nan | | same | +| q29 | 353.72 | 348.33 | 0.985 | 443.88 | 438.75 | 0.988 | 1157.92 | 1140.94 | 0.985 | nan | nan | nan | | same | +| q30 | 0.02 | 0.02 | 0.996 | 3.04 | 3.04 | 0.999 | 3.12 | 3.11 | 0.998 | nan | nan | nan | | same | +| q31 | 52.87 | 51.52 | 0.975 | 70.78 | 69.53 | 0.982 | 177.98 | 173.27 | 0.974 | nan | nan | nan | | same | +| q32 | 59.35 | 59.38 | 1.000 | 88.91 | 86.25 | 0.970 | 208.12 | 205.19 | 0.986 | nan | nan | nan | | same | +| q33 | 202.16 | 201.70 | 0.998 | 364.33 | 365.65 | 1.004 | 784.03 | 776.80 | 0.991 | nan | nan | nan | | same | +| q34 | 39.27 | 39.08 | 0.995 | 70.43 | 69.85 | 0.992 | 149.04 | 150.74 | 1.011 | nan | nan | nan | | same | +| q35 | 39.36 | 39.26 | 0.998 | 70.41 | 70.55 | 1.002 | 149.31 | 149.38 | 1.000 | nan | nan | nan | | same | +| q36 | 63.98 | 64.20 | 1.003 | 86.95 | 88.00 | 1.012 | 215.52 | 218.22 | 1.012 | nan | nan | nan | | same | +| q37 | 17.06 | 16.61 | 0.973 | 27.52 | 27.27 | 0.991 | 61.92 | 60.38 | 0.975 | nan | nan | nan | | same | +| q38 | 15.99 | 14.90 | 0.932 | 25.23 | 24.68 | 0.978 | 58.10 | 55.08 | 0.948 | nan | nan | nan | | same | +| q39 | 7.40 | 7.08 | 0.956 | 14.65 | 14.59 | 0.996 | 29.92 | 29.00 | 0.969 | nan | nan | nan | | same | +| q40 | 59.06 | 58.41 | 0.989 | 90.37 | 90.25 | 0.999 | 210.38 | 211.54 | 1.006 | nan | nan | nan | | same | +| q41 | 5.82 | 5.66 | 0.972 | 13.42 | 13.49 | 1.005 | 25.68 | 25.27 | 0.984 | nan | nan | nan | | same | +| q42 | 4.60 | 4.47 | 0.971 | 11.08 | 11.18 | 1.009 | 20.72 | 20.45 | 0.987 | nan | nan | nan | | same | +| q43 | 9.27 | 8.99 | 0.969 | 18.92 | 18.66 | 0.986 | 38.18 | 37.35 | 0.978 | nan | nan | nan | | same | + +``` +totals over all 43: warm 1797.9 vs 1785.5 (0.993); first run 2593.1 vs 2585.2 (0.997); 3-run 6249.7 vs 6211.6 (0.994) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=36)=0.972 warm_worst=1.087 worst5 [(1.087, 'q5'), (1.063, 'q4'), (1.058, 'q1'), (1.052, 'q6'), (1.013, 'q24')] +``` + +#### arm C1: parted p0, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.090 | 0.01 | 0.01 | 1.125 | 0.01 | 0.01 | 1.111 | nan | nan | nan | | same | +| q2 | 6.62 | 6.59 | 0.996 | 17.18 | 17.15 | 0.998 | 30.46 | 30.56 | 1.003 | nan | nan | nan | | same | +| q3 | 534.35 | 528.84 | 0.990 | 554.47 | 547.36 | 0.987 | 1637.37 | 1611.73 | 0.984 | nan | nan | nan | | same | +| q4 | 273.69 | 277.05 | 1.012 | 323.52 | 321.92 | 0.995 | 880.75 | 875.73 | 0.994 | nan | nan | nan | | same | +| q5 | 274.70 | 274.50 | 0.999 | 325.77 | 324.56 | 0.996 | 882.26 | 880.37 | 0.998 | nan | nan | nan | | same | +| q6 | 344.40 | 337.23 | 0.979 | 9648.98 | 9655.06 | 1.001 | 10339.67 | 10350.37 | 1.001 | nan | nan | nan | | same | +| q7 | 525.73 | 528.95 | 1.006 | 551.41 | 554.90 | 1.006 | 1610.41 | 1620.07 | 1.006 | nan | nan | nan | | same | +| q8 | 9.16 | 6.29 | 0.687 | 21.57 | 8.00 | 0.371 | 39.84 | 20.79 | 0.522 | nan | nan | nan | | same | +| q9 | 89.55 | 85.31 | 0.953 | 176.83 | 151.68 | 0.858 | 359.03 | 323.14 | 0.900 | nan | nan | nan | | same | +| q10 | 86.64 | 78.62 | 0.907 | 204.89 | 153.82 | 0.751 | 383.09 | 313.25 | 0.818 | nan | nan | nan | | same | +| q11 | 357.31 | 23.88 | 0.067 | 574.30 | 59.12 | 0.103 | 1297.61 | 109.92 | 0.085 | nan | nan | nan | | same | +| q12 | 357.85 | 26.72 | 0.075 | 572.31 | 60.61 | 0.106 | 1293.21 | 114.46 | 0.089 | nan | nan | nan | | same | +| q13 | 40.19 | 40.15 | 0.999 | 70.24 | 69.98 | 0.996 | 150.94 | 150.99 | 1.000 | nan | nan | nan | | same | +| q14 | 1129.54 | 100.67 | 0.089 | 1397.99 | 154.03 | 0.110 | 3668.26 | 362.92 | 0.099 | nan | nan | nan | | same | +| q15 | 46.65 | 46.71 | 1.001 | 89.22 | 89.09 | 0.999 | 185.76 | 187.00 | 1.007 | nan | nan | nan | | same | +| q16 | 76.24 | 72.65 | 0.953 | 146.38 | 100.75 | 0.688 | 300.37 | 249.16 | 0.830 | nan | nan | nan | | same | +| q17 | 103.75 | 96.00 | 0.925 | 205.42 | 134.51 | 0.655 | 413.72 | 329.87 | 0.797 | nan | nan | nan | | same | +| q18 | 17.17 | 17.09 | 0.995 | 83.45 | 84.35 | 1.011 | 118.02 | 119.23 | 1.010 | nan | nan | nan | | same | +| q19 | 141.35 | 140.66 | 0.995 | 336.38 | 337.38 | 1.003 | 623.39 | 623.63 | 1.000 | nan | nan | nan | | same | +| q20 | 4.60 | 4.63 | 1.006 | 14.49 | 14.55 | 1.004 | 24.10 | 24.16 | 1.003 | nan | nan | nan | | same | +| q21 | 41.63 | 41.67 | 1.001 | 46.63 | 46.61 | 1.000 | 130.32 | 131.78 | 1.011 | nan | nan | nan | | same | +| q22 | 60.72 | 60.59 | 0.998 | 85.47 | 86.07 | 1.007 | 207.97 | 209.51 | 1.007 | nan | nan | nan | | same | +| q23 | 93.52 | 90.20 | 0.965 | 203.74 | 117.91 | 0.579 | 394.43 | 298.81 | 0.758 | nan | nan | nan | | same | +| q24 | 44.43 | 44.38 | 0.999 | 125.11 | 125.24 | 1.001 | 214.87 | 214.58 | 0.999 | nan | nan | nan | | same | +| q25 | 1069.78 | 1056.88 | 0.988 | 1324.12 | 1307.36 | 0.987 | 3469.64 | 3430.01 | 0.989 | nan | nan | nan | | same | +| q26 | 1122.13 | 1110.46 | 0.990 | 1471.87 | 1455.46 | 0.989 | 3728.19 | 3679.84 | 0.987 | nan | nan | nan | | same | +| q27 | 1081.82 | 1065.90 | 0.985 | 1331.94 | 1318.89 | 0.990 | 3500.73 | 3460.25 | 0.988 | nan | nan | nan | | same | +| q28 | 92.33 | 90.79 | 0.983 | 147.18 | 146.18 | 0.993 | 333.85 | 330.50 | 0.990 | nan | nan | nan | | same | +| q29 | 361.75 | 359.14 | 0.993 | 472.76 | 463.18 | 0.980 | 1201.24 | 1186.46 | 0.988 | nan | nan | nan | | same | +| q30 | 265.87 | 262.26 | 0.986 | 279.86 | 278.97 | 0.997 | 824.85 | 819.02 | 0.993 | nan | nan | nan | | same | +| q31 | 54.98 | 55.85 | 1.016 | 124.60 | 126.63 | 1.016 | 237.76 | 239.78 | 1.008 | nan | nan | nan | | same | +| q32 | 68.83 | 68.77 | 0.999 | 181.36 | 177.90 | 0.981 | 319.34 | 315.84 | 0.989 | nan | nan | nan | | same | +| q33 | 217.08 | 211.63 | 0.975 | 461.88 | 370.82 | 0.803 | 902.25 | 800.63 | 0.887 | nan | nan | nan | | same | +| q34 | 43.35 | 43.01 | 0.992 | 95.46 | 95.52 | 1.001 | 182.01 | 181.82 | 0.999 | nan | nan | nan | | same | +| q35 | 386.86 | 43.09 | 0.111 | 2293.99 | 95.82 | 0.042 | 3068.90 | 182.94 | 0.060 | nan | nan | nan | | same | +| q36 | 148.58 | 145.19 | 0.977 | 217.67 | 216.57 | 0.995 | 517.52 | 511.81 | 0.989 | nan | nan | nan | | same | +| q37 | 36.53 | 36.28 | 0.993 | 69.09 | 69.57 | 1.007 | 142.20 | 142.04 | 0.999 | nan | nan | nan | | same | +| q38 | 36.39 | 34.92 | 0.960 | 67.76 | 68.35 | 1.009 | 145.06 | 144.49 | 0.996 | nan | nan | nan | | same | +| q39 | 15.37 | 15.09 | 0.982 | 27.56 | 27.10 | 0.983 | 58.44 | 57.82 | 0.989 | nan | nan | nan | | same | +| q40 | 117.56 | 116.38 | 0.990 | 422.82 | 420.97 | 0.996 | 659.83 | 659.49 | 0.999 | nan | nan | nan | | same | +| q41 | 17.60 | 17.70 | 1.006 | 38.81 | 38.69 | 0.997 | 74.59 | 74.48 | 0.998 | nan | nan | nan | | same | +| q42 | 13.40 | 13.16 | 0.982 | 24.35 | 23.96 | 0.984 | 51.68 | 50.69 | 0.981 | nan | nan | nan | | same | +| q43 | 28.46 | 27.93 | 0.981 | 41.61 | 40.51 | 0.974 | 99.65 | 96.87 | 0.972 | nan | nan | nan | | same | + +``` +totals over all 43: warm 9838.5 vs 7703.8 (0.783); first run 24870.4 vs 19957.1 (0.802); 3-run 44703.6 vs 35516.8 (0.794) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=42)=0.772 warm_worst=1.090 worst5 [(1.09, 'q1'), (1.016, 'q31'), (1.012, 'q4'), (1.006, 'q7'), (1.006, 'q41')] +q16 first run base 146.4 ms, p2 100.7 ms (carry 2) +``` + +#### arm R: parted ragged, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.033 | 0.01 | 0.01 | 1.157 | 0.01 | 0.01 | 1.141 | nan | nan | nan | | same | +| q2 | 7.74 | 7.56 | 0.976 | 18.21 | 17.03 | 0.935 | 33.78 | 32.26 | 0.955 | nan | nan | nan | | same | +| q3 | 570.68 | 264.47 | 0.463 | 593.63 | 286.44 | 0.483 | 1753.58 | 827.68 | 0.472 | nan | nan | nan | | same | +| q4 | 274.36 | 273.91 | 0.998 | 323.51 | 320.98 | 0.992 | 876.45 | 880.59 | 1.005 | nan | nan | nan | | same | +| q5 | 275.33 | 273.71 | 0.994 | 324.77 | 321.02 | 0.988 | 883.16 | 877.90 | 0.994 | nan | nan | nan | | same | +| q6 | 340.49 | 339.03 | 0.996 | 9640.19 | 9661.39 | 1.002 | 10333.78 | 10353.71 | 1.002 | nan | nan | nan | | same | +| q7 | 522.08 | 523.52 | 1.003 | 551.47 | 559.12 | 1.014 | 1604.08 | 1621.32 | 1.011 | nan | nan | nan | | same | +| q8 | 9.65 | 8.74 | 0.906 | 22.43 | 10.20 | 0.455 | 41.75 | 27.89 | 0.668 | nan | nan | nan | | same | +| q9 | 89.46 | 85.23 | 0.953 | 177.06 | 153.64 | 0.868 | 357.59 | 327.12 | 0.915 | nan | nan | nan | | same | +| q10 | 86.66 | 79.39 | 0.916 | 203.33 | 155.38 | 0.764 | 380.75 | 315.48 | 0.829 | nan | nan | nan | | same | +| q11 | 372.93 | 23.61 | 0.063 | 644.72 | 57.90 | 0.090 | 1393.45 | 106.95 | 0.077 | nan | nan | nan | | same | +| q12 | 373.12 | 26.53 | 0.071 | 644.14 | 60.36 | 0.094 | 1389.89 | 114.68 | 0.083 | nan | nan | nan | | same | +| q13 | 39.85 | 40.12 | 1.007 | 69.70 | 70.43 | 1.010 | 151.89 | 152.43 | 1.004 | nan | nan | nan | | same | +| q14 | 1181.37 | 100.65 | 0.085 | 1503.10 | 154.65 | 0.103 | 3877.27 | 361.74 | 0.093 | nan | nan | nan | | same | +| q15 | 46.24 | 46.43 | 1.004 | 88.24 | 89.71 | 1.017 | 184.36 | 186.29 | 1.011 | nan | nan | nan | | same | +| q16 | 75.98 | 72.39 | 0.953 | 145.43 | 97.06 | 0.667 | 298.59 | 242.06 | 0.811 | nan | nan | nan | | same | +| q17 | 103.85 | 95.30 | 0.918 | 205.24 | 133.87 | 0.652 | 417.19 | 329.34 | 0.789 | nan | nan | nan | | same | +| q18 | 17.19 | 17.13 | 0.997 | 83.54 | 83.49 | 0.999 | 118.13 | 119.50 | 1.012 | nan | nan | nan | | same | +| q19 | 141.25 | 140.96 | 0.998 | 336.46 | 336.21 | 0.999 | 621.70 | 624.61 | 1.005 | nan | nan | nan | | same | +| q20 | 4.55 | 4.47 | 0.982 | 14.14 | 14.09 | 0.997 | 23.38 | 23.54 | 1.007 | nan | nan | nan | | same | +| q21 | 41.69 | 41.74 | 1.001 | 46.50 | 46.32 | 0.996 | 130.36 | 129.92 | 0.997 | nan | nan | nan | | same | +| q22 | 60.45 | 60.37 | 0.999 | 85.22 | 85.55 | 1.004 | 208.61 | 206.46 | 0.990 | nan | nan | nan | | same | +| q23 | 93.51 | 89.87 | 0.961 | 270.26 | 117.38 | 0.434 | 461.68 | 297.66 | 0.645 | nan | nan | nan | | same | +| q24 | 44.31 | 44.26 | 0.999 | 188.12 | 167.80 | 0.892 | 282.45 | 260.80 | 0.923 | nan | nan | nan | | same | +| q25 | 1119.49 | 1107.83 | 0.990 | 1416.34 | 1391.46 | 0.982 | 3658.41 | 3620.41 | 0.990 | nan | nan | nan | | same | +| q26 | 1171.45 | 1157.76 | 0.988 | 1579.79 | 1537.59 | 0.973 | 3938.50 | 3864.10 | 0.981 | nan | nan | nan | | same | +| q27 | 1130.19 | 1115.29 | 0.987 | 1437.34 | 1394.53 | 0.970 | 3709.24 | 3636.16 | 0.980 | nan | nan | nan | | same | +| q28 | 91.64 | 90.70 | 0.990 | 149.64 | 145.44 | 0.972 | 335.88 | 329.34 | 0.981 | nan | nan | nan | | same | +| q29 | 362.11 | 356.39 | 0.984 | 469.82 | 469.73 | 1.000 | 1199.84 | 1187.90 | 0.990 | nan | nan | nan | | same | +| q30 | 263.74 | 260.65 | 0.988 | 279.10 | 276.54 | 0.991 | 820.49 | 825.98 | 1.007 | nan | nan | nan | | same | +| q31 | 55.11 | 54.93 | 0.997 | 124.07 | 124.85 | 1.006 | 236.20 | 239.57 | 1.014 | nan | nan | nan | | same | +| q32 | 68.55 | 68.69 | 1.002 | 179.32 | 177.13 | 0.988 | 317.66 | 317.15 | 0.998 | nan | nan | nan | | same | +| q33 | 215.95 | 211.00 | 0.977 | 463.39 | 371.76 | 0.802 | 902.95 | 802.26 | 0.888 | nan | nan | nan | | same | +| q34 | 43.26 | 43.24 | 0.999 | 95.56 | 96.33 | 1.008 | 182.08 | 183.51 | 1.008 | nan | nan | nan | | same | +| q35 | 409.93 | 43.03 | 0.105 | 2395.54 | 95.91 | 0.040 | 3220.16 | 187.46 | 0.058 | nan | nan | nan | | same | +| q36 | 147.75 | 144.95 | 0.981 | 217.38 | 214.19 | 0.985 | 514.99 | 513.51 | 0.997 | nan | nan | nan | | same | +| q37 | 36.27 | 35.92 | 0.990 | 72.81 | 71.50 | 0.982 | 147.63 | 144.61 | 0.980 | nan | nan | nan | | same | +| q38 | 35.29 | 34.51 | 0.978 | 73.83 | 72.22 | 0.978 | 146.27 | 143.42 | 0.981 | nan | nan | nan | | same | +| q39 | 15.14 | 14.91 | 0.985 | 29.21 | 28.23 | 0.966 | 60.14 | 64.27 | 1.069 | nan | nan | nan | | same | +| q40 | 151.35 | 154.65 | 1.022 | 460.99 | 454.20 | 0.985 | 769.15 | 766.33 | 0.996 | nan | nan | nan | | same | +| q41 | 17.63 | 17.14 | 0.972 | 40.28 | 38.22 | 0.949 | 76.28 | 72.76 | 0.954 | nan | nan | nan | | same | +| q42 | 13.27 | 12.72 | 0.958 | 26.50 | 23.80 | 0.898 | 53.40 | 49.56 | 0.928 | nan | nan | nan | | same | +| q43 | 28.17 | 27.59 | 0.979 | 41.64 | 40.82 | 0.980 | 98.96 | 96.52 | 0.975 | nan | nan | nan | | same | + +``` +totals over all 43: warm 10149.0 vs 7611.3 (0.750); first run 25732.0 vs 20024.5 (0.778); 3-run 46212.1 vs 35464.8 (0.767) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=42)=0.759 warm_worst=1.033 worst5 [(1.033, 'q1'), (1.022, 'q40'), (1.007, 'q13'), (1.004, 'q15'), (1.003, 'q7')] +``` + + +## P2 gate (final) + +Final run of the P2 gate after the gate fix task 17i, on HEAD df637f04 +(release build, sha256 9e4c9efc37a6) against the base 80a28e49 (release +build from `git archive`, sha256 935f88522f32). Method, loads and arms are +as in "P2 range reads" above: `W=/home/hetoku/data/tmp/p2_final p2_bench.sh +all` as committed, all 43 queries on A, B, C0, C1 and R, 5 alternated +rounds, 3 cold trials per query (fadvise eviction), full answers compared; +the ragged partition 9 keeps 40 columns. Raw data: +/home/hetoku/data/tmp/p2_final/p2.tsv (summary.txt beside it). The machine +was otherwise idle (11:50-13:42). + +Sizes are unchanged (g0 5 948 677 939 B, g2 3 307 128 731 B; p0 +4 807 844 987 B, p2 2 072 366 907 B). Peak RSS over all 43 queries: g0 +5 120 428 kB, g2 8 102 144 kB (x1.58; the q24-q27 whole-row top-k gathers +stay cached); p0 15 253 952 kB, p2 15 812 084 kB (x1.04). Answers: +identical on all five arms (0 mismatches, 0 order differences). + +### Gate lines + +``` +GATE (strict) splayed[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=FAIL first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=FAIL materializing_warm=FAIL no_unexpected_materialization=FAIL] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=FAIL no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (P3-exempt): FAIL +P3-EXEMPT LIST q8/A/warm[run-level compute (group over RLE runs)]: 3.56 -> 5.06 ms (x1.422) EXEMPTED; q8/A/first[run-level compute (group over RLE runs, first run)]: 8.82 -> 10.21 ms (x1.157) EXEMPTED; q18/A/first[row-list gather (first-n keys published, P3 path 2)]: 13.48 -> 26.42 ms (x1.960) EXEMPTED; q39/A/first[selection gather (P3 path 2)]: 14.60 -> 31.46 ms (x2.155) EXEMPTED; q39/B/first[selection gather (P3 path 2)]: 27.64 -> 40.54 ms (x1.467) EXEMPTED; q39/A/cold[selection gather reads whole columns cold (P3)]: 38.31 -> 81.82 ms (x2.136) EXEMPTED; q42/A/warm[point gathers of the selected keys (P3)]: 4.52 -> 7.54 ms (x1.669) EXEMPTED; q42/B/warm[point gathers of the selected keys (P3)]: 13.12 -> 16.36 ms (x1.246) EXEMPTED; q24/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated; q25/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated; q26/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated; q27/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated +``` + +**The P2 gate fails in both variants.** Parted (arm B) now passes every +clause with the deferrals, as do generation 0 on parted and ragged, all +answers, every cold and first clause, no_unexpected_materialization and +splayed first_total (1.816 vs PI's 2.99). Three clauses fail after the +exemptions: + +| clause | query | a -> b (ms) | ratio | per-round range | deferral | +|---|---|---|---|---|---| +| splayed warm (scan-only) | q33 | 202.23 -> 212.53 | 1.051 | g0 202.2-203.8, g2 212.5-215.4 | none | +| splayed materializing warm | q10 | 69.01 -> 72.61 | 1.052 | g0 69.0-69.8, g2 72.6-74.7 | none | +| gen0-splayed warm (C0) | q25 | 0.898 -> 1.001 | 1.115 | base 0.90-1.09, p2 1.00-1.07 | none | + +No other clause fails. Close to a bound: splayed q25 materializing warm +1.049, splayed q35 first 1.036, parted q33 warm 1.030 and cold 1.038. + +- **Splayed q33** (`by {WatchID ClientIP}`): 1.113 on the re-run, 1.051 now + (17i measured 1.041-1.046). A separate alternated check after the run (7 + rounds, gate-min) gave 1.047, so it sits on the bound. What remains is + the fused phase 2 over chunk-major runs (17i report, concern 2). +- **Splayed q10** (`by RegionID`, sum AdvEngineID, count, avg + ResolutionWidth, count distinct UserID; materializes RegionID and UserID): + 1.046 on the re-run, 1.052 now. A 7-round alternated re-check gave g2/g0 + 1.036-1.072 in every round. Profile (25 runs in one process, perf without + call graphs): the two profiles match symbol for symbol (cdpg_buf_par_fn + 6 264 / 6 258 samples, agg_dense_partition_field 4 608 / 4 462) except + g2's `dec_fast_runs` at 1 753 samples (4.6%), the decode of the RLE-run + inputs. That is the whole gap: the same run-level decode cost as q8, + which P3's run-level compute removes. It has no deferral. +- **Gen-0 splayed q25** (`where SearchPhrase != "" asc: EventTime take: 10`, + the SearchPhrase column only): both medians are about 1 ms, and the gap of + 0.10 ms is above the 0.05 ms floor. The gate takes the best round: base's + round 3 is 0.898 ms against 1.00-1.09 in the others. The medians of the + rounds are 1.012 (base) and 1.029 (p2), 1.017. A 9-round alternated + re-check gave base 0.86-1.04 and p2 0.94-1.09 ms (best-round ratio 1.094, + median 1.009). The base often lands a fast round and p2 rarely does, so + this is the gate statistic on a 1 ms query rather than a measured + regression. On the re-run it was 0.874. + +### What moved since the re-run (ratio gen2/gen0) + +- Splayed: q2 first 3.219 -> 0.892, q33 warm 1.113 -> 1.051, q34 warm + 1.053 -> 0.983, q35 warm 1.048 -> 0.986, q2 warm 1.086 -> 1.049 (within + the bound), q8 first 1.046 -> 1.157 (17i concern 1, now deferred). +- Parted: q8 first 1.424 -> 1.065, q33 warm 1.077 -> 1.030, q32 warm + 1.075 -> 1.038, q8 warm 1.060 -> 1.038, q18 warm 1.088 -> 1.027. +- All-43 splayed first-run total 1.836 -> 1.816. + +### Generation-0 warm gmeans (base median >= 1 ms) + +| arm | n | gmean | worst | +|---|---|---|---| +| C0 splayed g0, base vs p2 | 35 | 0.977 | 1.115 (q25) | +| C1 parted p0, base vs p2 | 42 | 0.776 | 1.108 (q1, below 1 ms) | +| R parted ragged, base vs p2 | 42 | 0.763 | 1.047 (q30) | + +q16 parted first run: base 145.6 ms, p2 98.8 ms. + +### P3 deferrals (P3_DEFERRALS, max_ratio about 1.5x this run's ratio, per arm) + +``` +q8/A/warm[run-level compute (group over RLE runs)]: 3.56 -> 5.06 ms (x1.422) EXEMPTED +q8/A/first[run-level compute (group over RLE runs, first run)]: 8.82 -> 10.21 ms (x1.157) EXEMPTED +q18/A/first[row-list gather (first-n keys published, P3 path 2)]: 13.48 -> 26.42 ms (x1.960) EXEMPTED +q39/A/first[selection gather (P3 path 2)]: 14.60 -> 31.46 ms (x2.155) EXEMPTED +q39/B/first[selection gather (P3 path 2)]: 27.64 -> 40.54 ms (x1.467) EXEMPTED +q39/A/cold[selection gather reads whole columns cold (P3)]: 38.31 -> 81.82 ms (x2.136) EXEMPTED +q42/A/warm[point gathers of the selected keys (P3)]: 4.52 -> 7.54 ms (x1.669) EXEMPTED +q42/B/warm[point gathers of the selected keys (P3)]: 13.12 -> 16.36 ms (x1.246) EXEMPTED +q24/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated +q25/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated +q26/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated +q27/A/rss[top-k output gather RSS]: arm peak-RSS 5120428 -> 8102144 kB (x1.58, max 2.37) not gated +``` + +- Added by controller ruling: q8 splayed first. Its cause is the same + run-level compute as q8's warm deferral, and the first run carries the + warm gap (g0 8.8, g2 10.2 ms; run 2 onwards 3.6 against 5.1 ms). +- Removed because their clauses now pass: q2 splayed warm (1.049), q8 + parted warm (1.038), q18 parted warm (1.027). +- The reasons by class: + - run-level compute (q8): P3 computes over RLE runs instead of decoding + them; + - row-list gather (q18) and selection gather (q39): P3 path 2; + - point gathers of the selected keys (q42); + - top-k output gather RSS (q24-q27 splayed): not gated. + +### Per-query tables (final) + +#### arm A: splayed g0 vs g2 (ms; ratio = g2/g0) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.000 | 0.01 | 0.01 | 0.930 | 0.01 | 0.01 | 0.872 | 0.01 | 0.01 | 1.730 | [] | same | +| q2 | 0.62 | 0.65 | 1.049 | 1.66 | 1.48 | 0.892 | 3.21 | 2.94 | 0.916 | 38.47 | 3.47 | 0.090 | [] | same | +| q3 | 3.79 | 0.00 | 0.001 | 5.50 | 0.03 | 0.006 | 13.22 | 0.04 | 0.003 | 94.61 | 0.04 | 0.000 | [] | same | +| q4 | 0.00 | 0.00 | 1.013 | 0.02 | 0.03 | 1.247 | 0.03 | 0.03 | 1.236 | 0.03 | 0.03 | 1.218 | [] | same | +| q5 | 0.00 | 0.00 | 1.296 | 0.03 | 0.03 | 0.992 | 0.03 | 0.03 | 0.988 | 0.03 | 0.03 | 0.860 | [] | same | +| q6 | 0.00 | 0.00 | 1.275 | 0.03 | 0.03 | 1.025 | 0.03 | 0.03 | 1.028 | 0.03 | 0.03 | 1.106 | [] | same | +| q7 | 0.00 | 0.00 | 1.175 | 0.02 | 0.03 | 1.731 | 0.02 | 0.04 | 1.631 | 0.02 | 0.03 | 1.522 | [] | same | +| q8 | 3.56 | 5.06 | 1.422 | 8.82 | 10.21 | 1.157 | 16.03 | 20.54 | 1.282 | 41.27 | 10.92 | 0.264 | [] | same | +| q9 | 75.00 | 74.96 | 0.999 | 112.27 | 126.51 | 1.127 | 263.96 | 277.11 | 1.050 | 668.70 | 155.41 | 0.232 | [RegionID UserID] | same | +| q10 | 69.01 | 72.61 | 1.052 | 97.33 | 120.97 | 1.243 | 236.93 | 269.44 | 1.137 | 406.73 | 155.14 | 0.381 | [RegionID UserID] | same | +| q11 | 15.93 | 16.18 | 1.016 | 25.04 | 41.20 | 1.645 | 58.07 | 74.21 | 1.278 | 243.46 | 61.26 | 0.252 | [UserID MobilePhoneModel] | same | +| q12 | 16.22 | 16.38 | 1.010 | 25.42 | 44.56 | 1.753 | 58.98 | 78.87 | 1.337 | 279.43 | 65.47 | 0.234 | [UserID MobilePhone MobilePhoneModel] | same | +| q13 | 31.91 | 31.87 | 0.999 | 41.52 | 47.83 | 1.152 | 107.02 | 112.59 | 1.052 | 114.43 | 63.99 | 0.559 | [SearchPhrase] | same | +| q14 | 62.73 | 62.68 | 0.999 | 89.75 | 105.19 | 1.172 | 219.51 | 234.21 | 1.067 | 306.44 | 148.26 | 0.484 | [UserID SearchPhrase] | same | +| q15 | 36.44 | 37.51 | 1.030 | 47.56 | 57.26 | 1.204 | 122.41 | 133.13 | 1.088 | 155.16 | 101.38 | 0.653 | [SearchPhrase] | same | +| q16 | 69.87 | 63.35 | 0.907 | 96.81 | 88.63 | 0.915 | 236.84 | 218.40 | 0.922 | 241.35 | 166.52 | 0.690 | [] | same | +| q17 | 93.40 | 92.67 | 0.992 | 129.63 | 126.10 | 0.973 | 319.04 | 315.88 | 0.990 | 464.57 | 239.99 | 0.517 | [] | same | +| q18 | 6.84 | 6.87 | 1.004 | 13.48 | 26.42 | 1.960 | 27.55 | 40.27 | 1.461 | 619.26 | 61.93 | 0.100 | [UserID SearchPhrase] | same | +| q19 | 137.16 | 139.33 | 1.016 | 209.23 | 211.98 | 1.013 | 490.38 | 496.67 | 1.013 | 678.65 | 435.57 | 0.642 | [EventTime] | same | +| q20 | 1.16 | 0.73 | 0.631 | 6.92 | 6.12 | 0.885 | 9.50 | 7.73 | 0.813 | 55.12 | 16.65 | 0.302 | [] | same | +| q21 | 41.92 | 42.20 | 1.007 | 45.14 | 50.81 | 1.126 | 129.20 | 135.85 | 1.052 | 76.89 | 93.05 | 1.210 | [URL] | same | +| q22 | 27.53 | 27.56 | 1.001 | 32.48 | 55.17 | 1.699 | 87.56 | 110.69 | 1.264 | 185.74 | 133.34 | 0.718 | [UserID URL SearchPhrase] | same | +| q23 | 48.84 | 48.96 | 1.002 | 60.49 | 88.33 | 1.460 | 159.50 | 187.91 | 1.178 | 430.32 | 204.78 | 0.476 | [Title UserID URL SearchPhrase] | same | +| q24 | 29.48 | 29.38 | 0.997 | 34.61 | 475.67 | 13.744 | 94.09 | 534.77 | 5.684 | 608.60 | 1230.80 | 2.022 | <100 columns> | same | +| q25 | 0.91 | 0.95 | 1.049 | 4.44 | 449.39 | 101.239 | 6.54 | 451.57 | 69.055 | 299.04 | 1214.61 | 4.062 | <100 columns> | same | +| q26 | 10.84 | 10.91 | 1.006 | 15.29 | 449.39 | 29.384 | 37.20 | 472.07 | 12.688 | 574.14 | 1226.63 | 2.136 | <100 columns> | same | +| q27 | 1.00 | 0.96 | 0.957 | 4.30 | 448.34 | 104.187 | 6.38 | 450.45 | 70.637 | 296.98 | 1207.76 | 4.067 | <100 columns> | same | +| q28 | 81.50 | 67.00 | 0.822 | 83.78 | 79.21 | 0.946 | 247.87 | 213.48 | 0.861 | 219.28 | 121.39 | 0.554 | [URL] | same | +| q29 | 348.43 | 349.10 | 1.002 | 437.88 | 442.23 | 1.010 | 1134.78 | 1143.97 | 1.008 | 508.35 | 497.20 | 0.978 | [Referer] | same | +| q30 | 0.02 | 0.02 | 1.010 | 2.82 | 5.33 | 1.889 | 2.89 | 5.39 | 1.868 | 56.54 | 11.45 | 0.203 | [ResolutionWidth] | same | +| q31 | 51.39 | 51.61 | 1.004 | 69.47 | 93.84 | 1.351 | 172.05 | 199.21 | 1.158 | 318.81 | 139.14 | 0.436 | [ClientIP IsRefresh ResolutionWidth SearchEngineID SearchPhrase] | same | +| q32 | 59.27 | 59.28 | 1.000 | 86.52 | 106.58 | 1.232 | 205.99 | 226.04 | 1.097 | 440.77 | 281.46 | 0.639 | [ClientIP IsRefresh ResolutionWidth SearchPhrase] | same | +| q33 | 202.23 | 212.53 | 1.051 | 362.97 | 363.67 | 1.002 | 775.12 | 790.49 | 1.020 | 593.30 | 554.47 | 0.935 | [] | same | +| q34 | 39.36 | 38.68 | 0.983 | 71.49 | 71.60 | 1.002 | 153.17 | 151.87 | 0.992 | 138.09 | 109.68 | 0.794 | [] | same | +| q35 | 39.20 | 38.64 | 0.986 | 69.28 | 71.78 | 1.036 | 148.55 | 149.45 | 1.006 | 138.33 | 109.13 | 0.789 | [] | same | +| q36 | 64.23 | 61.05 | 0.950 | 88.88 | 83.83 | 0.943 | 220.31 | 210.88 | 0.957 | 160.40 | 124.22 | 0.774 | [] | same | +| q37 | 16.53 | 16.53 | 1.000 | 26.88 | 42.39 | 1.577 | 60.93 | 76.70 | 1.259 | 41.99 | 88.78 | 2.114 | [EventDate URL IsRefresh DontCountHits] | same | +| q38 | 14.99 | 14.81 | 0.988 | 24.40 | 40.00 | 1.639 | 55.10 | 70.58 | 1.281 | 39.18 | 81.85 | 2.089 | [Title EventDate IsRefresh DontCountHits] | same | +| q39 | 7.16 | 7.19 | 1.004 | 14.60 | 31.46 | 2.155 | 29.02 | 46.30 | 1.595 | 38.31 | 81.82 | 2.136 | [EventDate URL IsRefresh IsLink IsDownload] | same | +| q40 | 58.39 | 58.61 | 1.004 | 89.89 | 122.42 | 1.362 | 209.12 | 241.66 | 1.156 | 118.56 | 230.26 | 1.942 | [EventDate CounterID URL Referer IsRefresh TraficSourceID SearchEngineID AdvEngineID] | same | +| q41 | 5.84 | 5.69 | 0.975 | 13.48 | 27.31 | 2.026 | 25.59 | 39.16 | 1.530 | 74.93 | 49.16 | 0.656 | [EventDate CounterID IsRefresh TraficSourceID] | same | +| q42 | 4.52 | 7.54 | 1.669 | 10.95 | 28.10 | 2.566 | 20.51 | 43.41 | 2.117 | 37.43 | 40.84 | 1.091 | [EventDate CounterID IsRefresh DontCountHits] | same | +| q43 | 8.97 | 8.93 | 0.995 | 18.45 | 42.46 | 2.301 | 37.30 | 61.30 | 1.644 | 40.57 | 145.80 | 3.594 | [EventTime EventDate CounterID IsRefresh DontCountHits] | same | + +``` +totals over all 43: warm 1786.2 vs 1779.0 (0.996); first run 2579.5 vs 4683.9 (1.816); 3-run 6201.5 vs 8295.4 (1.338) +answer_mismatches none +order_differences none +scan_only(gated) n=17; gmeans over base>=1ms (per column): warm n=11 0.497, first n=12 0.725, cold n=12 0.259; worst warm=1.422 +below_1ms_excluded_from_warm_gmean q1 q2 q4 q5 q6 q7 +below_1ms_excluded_from_first_gmean q1 q4 q5 q6 q7 +below_1ms_excluded_from_cold_gmean q1 q4 q5 q6 q7 +mat rows missing none +scan_only_list_but_materializing q18 q39 +measured_materializing q9(2 cols) q10(2 cols) q11(2 cols) q12(3 cols) q13(1 cols) q14(2 cols) q15(1 cols) q18(2 cols) q19(1 cols) q21(1 cols) q22(3 cols) q23(4 cols) q24(100 cols) q25(100 cols) q26(100 cols) q27(100 cols) q28(1 cols) q29(1 cols) q30(1 cols) q31(5 cols) q32(4 cols) q37(4 cols) q38(4 cols) q39(5 cols) q40(8 cols) q41(4 cols) q42(4 cols) q43(5 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q6(measured scan, list other) q18(measured materializing, list scan) q20(measured scan, list other) q36(measured scan, list other) q39(measured materializing, list scan) +worst5 warm [(1.422, 'q8'), (1.296, 'q5'), (1.275, 'q6'), (1.175, 'q7'), (1.051, 'q33')] +worst5 cold [(2.136, 'q39'), (1.73, 'q1'), (1.522, 'q7'), (1.218, 'q4'), (1.106, 'q6')] +worst5 first [(2.155, 'q39'), (1.96, 'q18'), (1.731, 'q7'), (1.247, 'q4'), (1.157, 'q8')] +worst5 materializing_warm [(1.669, 'q42'), (1.052, 'q10'), (1.049, 'q25'), (1.03, 'q15'), (1.016, 'q19')] +first_run_total_ratio 1.816 (PI after P1: 2.99) +pi_row q41 warm 0.975 first 2.026 3run 1.530 +pi_row q42 warm 1.669 first 2.566 3run 2.117 +``` + +#### arm B: parted p0 vs p2 (ms; ratio = p2/p0) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.046 | 0.01 | 0.01 | 0.557 | 0.01 | 0.01 | 0.577 | 0.01 | 0.01 | 0.612 | [] | same | +| q2 | 6.59 | 6.69 | 1.015 | 17.00 | 16.51 | 0.971 | 30.70 | 30.22 | 0.984 | 46.54 | 16.19 | 0.348 | [] | same | +| q3 | 559.60 | 5.85 | 0.010 | 570.20 | 10.46 | 0.018 | 1688.32 | 22.34 | 0.013 | 579.80 | 15.03 | 0.026 | [] | same | +| q4 | 278.42 | 7.43 | 0.027 | 327.18 | 12.41 | 0.038 | 886.53 | 27.47 | 0.031 | 366.33 | 32.92 | 0.090 | [] | same | +| q5 | 278.19 | 0.00 | 0.000 | 321.37 | 0.03 | 0.000 | 882.25 | 0.03 | 0.000 | 368.48 | 0.03 | 0.000 | [] | same | +| q6 | 348.20 | 346.09 | 0.994 | 9629.99 | 9680.01 | 1.005 | 10322.71 | 10381.83 | 1.006 | 9719.79 | 9703.62 | 0.998 | [SearchPhrase] | same | +| q7 | 524.75 | 2.54 | 0.005 | 551.08 | 7.15 | 0.013 | 1621.75 | 12.38 | 0.008 | 579.96 | 7.18 | 0.012 | [] | same | +| q8 | 6.36 | 6.60 | 1.038 | 7.95 | 8.47 | 1.065 | 21.25 | 21.85 | 1.028 | 40.98 | 8.13 | 0.198 | [] | same | +| q9 | 85.32 | 82.99 | 0.973 | 152.39 | 165.67 | 1.087 | 324.30 | 334.45 | 1.031 | 396.40 | 190.15 | 0.480 | [RegionID UserID] | same | +| q10 | 78.87 | 80.44 | 1.020 | 153.43 | 177.51 | 1.157 | 314.92 | 341.65 | 1.085 | 452.06 | 208.39 | 0.461 | [RegionID UserID] | same | +| q11 | 24.59 | 23.26 | 0.946 | 59.64 | 66.98 | 1.123 | 109.30 | 114.49 | 1.048 | 396.02 | 87.32 | 0.220 | [UserID MobilePhoneModel] | same | +| q12 | 26.78 | 25.93 | 0.968 | 61.89 | 72.54 | 1.172 | 115.62 | 124.71 | 1.079 | 451.66 | 90.84 | 0.201 | [UserID MobilePhone MobilePhoneModel] | same | +| q13 | 40.31 | 39.79 | 0.987 | 72.27 | 75.83 | 1.049 | 153.47 | 157.25 | 1.025 | 155.92 | 92.98 | 0.596 | [SearchPhrase] | same | +| q14 | 101.44 | 101.48 | 1.000 | 155.23 | 170.28 | 1.097 | 362.84 | 379.75 | 1.047 | 448.10 | 203.88 | 0.455 | [UserID SearchPhrase] | same | +| q15 | 46.64 | 46.19 | 0.990 | 89.92 | 86.90 | 0.966 | 186.75 | 181.16 | 0.970 | 210.85 | 108.01 | 0.512 | [SearchPhrase] | same | +| q16 | 72.40 | 64.32 | 0.888 | 99.09 | 88.64 | 0.895 | 246.75 | 218.06 | 0.884 | 247.10 | 153.02 | 0.619 | [] | same | +| q17 | 95.91 | 93.16 | 0.971 | 134.02 | 127.05 | 0.948 | 326.26 | 314.97 | 0.965 | 460.21 | 243.60 | 0.529 | [] | same | +| q18 | 17.08 | 17.54 | 1.027 | 85.35 | 31.02 | 0.363 | 119.92 | 67.30 | 0.561 | 340.63 | 62.46 | 0.183 | [] | same | +| q19 | 141.90 | 144.65 | 1.019 | 340.37 | 245.69 | 0.722 | 630.90 | 537.47 | 0.852 | 756.81 | 374.25 | 0.495 | [EventTime] | same | +| q20 | 4.62 | 1.57 | 0.340 | 14.55 | 12.13 | 0.834 | 24.14 | 15.75 | 0.652 | 156.51 | 23.97 | 0.153 | [] | same | +| q21 | 41.83 | 41.82 | 1.000 | 46.92 | 57.12 | 1.217 | 131.86 | 143.22 | 1.086 | 87.51 | 99.66 | 1.139 | [URL] | same | +| q22 | 60.75 | 60.26 | 0.992 | 87.52 | 110.41 | 1.261 | 210.44 | 236.75 | 1.125 | 231.93 | 186.87 | 0.806 | [UserID URL SearchPhrase] | same | +| q23 | 90.56 | 90.05 | 0.994 | 118.41 | 150.42 | 1.270 | 300.24 | 336.41 | 1.120 | 476.54 | 272.73 | 0.572 | [Title UserID URL SearchPhrase] | same | +| q24 | 44.70 | 43.64 | 0.976 | 139.66 | 609.03 | 4.361 | 229.78 | 701.83 | 3.054 | 9299.80 | 1743.42 | 0.187 | <105 columns> | same | +| q25 | 1053.20 | 1045.10 | 0.992 | 1332.70 | 1693.05 | 1.270 | 3470.57 | 3809.47 | 1.098 | 9701.03 | 2850.10 | 0.294 | <105 columns> | same | +| q26 | 1104.94 | 1102.02 | 0.997 | 1475.42 | 1838.54 | 1.246 | 3701.58 | 4043.36 | 1.092 | 9846.98 | 2967.04 | 0.301 | <105 columns> | same | +| q27 | 1066.46 | 1057.73 | 0.992 | 1343.87 | 1695.61 | 1.262 | 3491.20 | 3822.35 | 1.095 | 9679.78 | 2831.98 | 0.293 | <105 columns> | same | +| q28 | 90.59 | 87.55 | 0.966 | 149.07 | 148.84 | 0.998 | 332.35 | 324.90 | 0.978 | 311.22 | 193.15 | 0.621 | [URL] | same | +| q29 | 355.79 | 356.29 | 1.001 | 471.44 | 472.34 | 1.002 | 1192.00 | 1195.56 | 1.003 | 553.17 | 514.18 | 0.930 | [Referer] | same | +| q30 | 277.62 | 276.13 | 0.995 | 287.03 | 293.39 | 1.022 | 863.06 | 860.62 | 0.997 | 297.33 | 295.00 | 0.992 | [ResolutionWidth] | same | +| q31 | 55.55 | 56.22 | 1.012 | 125.43 | 104.47 | 0.833 | 238.44 | 219.23 | 0.919 | 424.00 | 144.03 | 0.340 | [SearchPhrase] | same | +| q32 | 68.79 | 71.43 | 1.038 | 178.48 | 131.95 | 0.739 | 319.15 | 279.40 | 0.875 | 619.07 | 304.07 | 0.491 | [SearchPhrase] | same | +| q33 | 210.94 | 217.37 | 1.030 | 374.35 | 387.62 | 1.035 | 800.98 | 824.68 | 1.030 | 611.00 | 634.25 | 1.038 | [] | same | +| q34 | 43.29 | 43.57 | 1.006 | 96.17 | 75.39 | 0.784 | 183.16 | 163.55 | 0.893 | 183.36 | 119.91 | 0.654 | [] | same | +| q35 | 42.85 | 43.37 | 1.012 | 95.34 | 75.22 | 0.789 | 181.99 | 162.63 | 0.894 | 183.71 | 118.57 | 0.645 | [] | same | +| q36 | 145.78 | 144.73 | 0.993 | 214.28 | 199.54 | 0.931 | 511.12 | 494.71 | 0.968 | 303.01 | 208.74 | 0.689 | [] | same | +| q37 | 35.80 | 34.42 | 0.962 | 69.87 | 83.49 | 1.195 | 142.52 | 153.89 | 1.080 | 233.91 | 130.21 | 0.557 | [EventDate URL IsRefresh DontCountHits] | same | +| q38 | 34.68 | 33.22 | 0.958 | 67.96 | 84.22 | 1.239 | 143.92 | 153.88 | 1.069 | 222.92 | 126.51 | 0.568 | [Title EventDate IsRefresh DontCountHits] | same | +| q39 | 15.02 | 13.24 | 0.882 | 27.64 | 40.54 | 1.467 | 57.80 | 72.16 | 1.248 | 115.86 | 49.59 | 0.428 | [EventDate URL IsRefresh IsLink IsDownload] | same | +| q40 | 116.87 | 115.19 | 0.986 | 418.51 | 360.78 | 0.862 | 659.41 | 594.21 | 0.901 | 788.68 | 460.09 | 0.583 | [EventDate IsRefresh] | same | +| q41 | 17.64 | 17.17 | 0.973 | 39.44 | 59.16 | 1.500 | 75.11 | 98.49 | 1.311 | 256.05 | 236.74 | 0.925 | [EventDate CounterID IsRefresh TraficSourceID URLHash] | same | +| q42 | 13.12 | 16.36 | 1.246 | 23.92 | 45.45 | 1.900 | 50.78 | 81.80 | 1.611 | 191.69 | 171.50 | 0.895 | [EventDate CounterID IsRefresh WindowClientWidth WindowClientHeight DontCountHits] | same | +| q43 | 28.23 | 26.56 | 0.941 | 40.51 | 63.07 | 1.557 | 97.49 | 121.55 | 1.247 | 126.94 | 159.30 | 1.255 | [EventTime EventDate IsRefresh DontCountHits] | same | + +``` +totals over all 43: warm 7753.0 vs 6090.0 (0.786); first run 20066.9 vs 19834.9 (0.988); 3-run 35753.6 vs 32177.7 (0.900) +answer_mismatches none +order_differences none +scan_only(gated) n=16; gmeans over base>=1ms (per column): warm n=15 0.156, first n=15 0.223, cold n=15 0.141; worst warm=1.046 +below_1ms_excluded_from_warm_gmean q1 +below_1ms_excluded_from_first_gmean q1 +below_1ms_excluded_from_cold_gmean q1 +mat rows missing none +scan_only_list_but_materializing q39 +measured_materializing q6(1 cols) q9(2 cols) q10(2 cols) q11(2 cols) q12(3 cols) q13(1 cols) q14(2 cols) q15(1 cols) q19(1 cols) q21(1 cols) q22(3 cols) q23(4 cols) q24(105 cols) q25(105 cols) q26(105 cols) q27(105 cols) q28(1 cols) q29(1 cols) q30(1 cols) q31(1 cols) q32(1 cols) q37(4 cols) q38(4 cols) q39(5 cols) q40(2 cols) q41(5 cols) q42(6 cols) q43(4 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q20(measured scan, list other) q36(measured scan, list other) q39(measured materializing, list scan) +worst5 warm [(1.046, 'q1'), (1.038, 'q8'), (1.03, 'q33'), (1.027, 'q18'), (1.015, 'q2')] +worst5 cold [(1.038, 'q33'), (0.689, 'q36'), (0.654, 'q34'), (0.645, 'q35'), (0.619, 'q16')] +worst5 first [(1.467, 'q39'), (1.065, 'q8'), (1.035, 'q33'), (0.971, 'q2'), (0.948, 'q17')] +worst5 materializing_warm [(1.246, 'q42'), (1.038, 'q32'), (1.02, 'q10'), (1.019, 'q19'), (1.012, 'q31')] +pi_row q41 warm 0.973 first 1.500 3run 1.311 +pi_row q42 warm 1.246 first 1.900 3run 1.611 +``` + +#### arm C0: splayed g0, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.022 | 0.01 | 0.01 | 1.078 | 0.01 | 0.01 | 1.073 | nan | nan | nan | | same | +| q2 | 1.11 | 0.64 | 0.576 | 1.98 | 1.64 | 0.827 | 4.29 | 3.16 | 0.738 | nan | nan | nan | | same | +| q3 | 3.78 | 3.78 | 1.002 | 5.78 | 5.89 | 1.018 | 13.40 | 13.49 | 1.006 | nan | nan | nan | | same | +| q4 | 0.00 | 0.00 | 0.978 | 0.02 | 0.03 | 1.305 | 0.02 | 0.03 | 1.292 | nan | nan | nan | | same | +| q5 | 0.00 | 0.00 | 1.045 | 0.02 | 0.03 | 1.145 | 0.02 | 0.03 | 1.134 | nan | nan | nan | | same | +| q6 | 0.00 | 0.00 | 1.053 | 0.02 | 0.03 | 1.119 | 0.02 | 0.03 | 1.110 | nan | nan | nan | | same | +| q7 | 0.00 | 0.00 | 1.040 | 0.02 | 0.02 | 1.072 | 0.02 | 0.02 | 1.069 | nan | nan | nan | | same | +| q8 | 3.49 | 3.50 | 1.001 | 9.00 | 8.93 | 0.992 | 16.47 | 16.08 | 0.976 | nan | nan | nan | | same | +| q9 | 75.97 | 75.26 | 0.991 | 113.72 | 117.31 | 1.032 | 265.70 | 271.08 | 1.020 | nan | nan | nan | | same | +| q10 | 68.90 | 68.84 | 0.999 | 96.87 | 97.47 | 1.006 | 236.47 | 236.37 | 1.000 | nan | nan | nan | | same | +| q11 | 16.03 | 16.16 | 1.008 | 25.10 | 25.25 | 1.006 | 57.63 | 57.91 | 1.005 | nan | nan | nan | | same | +| q12 | 16.33 | 16.21 | 0.993 | 26.10 | 25.96 | 0.995 | 59.49 | 58.95 | 0.991 | nan | nan | nan | | same | +| q13 | 31.98 | 32.26 | 1.009 | 41.45 | 40.95 | 0.988 | 105.55 | 106.79 | 1.012 | nan | nan | nan | | same | +| q14 | 62.93 | 62.72 | 0.997 | 88.30 | 88.48 | 1.002 | 218.23 | 218.48 | 1.001 | nan | nan | nan | | same | +| q15 | 36.48 | 36.43 | 0.999 | 47.67 | 47.91 | 1.005 | 121.97 | 124.56 | 1.021 | nan | nan | nan | | same | +| q16 | 69.54 | 69.80 | 1.004 | 93.71 | 95.79 | 1.022 | 234.97 | 235.59 | 1.003 | nan | nan | nan | | same | +| q17 | 92.90 | 93.24 | 1.004 | 129.59 | 129.11 | 0.996 | 316.84 | 317.82 | 1.003 | nan | nan | nan | | same | +| q18 | 6.94 | 6.89 | 0.993 | 14.45 | 14.60 | 1.010 | 28.55 | 28.42 | 0.995 | nan | nan | nan | | same | +| q19 | 137.42 | 137.42 | 1.000 | 208.68 | 209.20 | 1.003 | 490.74 | 489.78 | 0.998 | nan | nan | nan | | same | +| q20 | 1.13 | 1.17 | 1.032 | 6.83 | 6.97 | 1.021 | 9.40 | 9.66 | 1.028 | nan | nan | nan | | same | +| q21 | 42.10 | 41.93 | 0.996 | 45.51 | 46.13 | 1.014 | 130.45 | 131.11 | 1.005 | nan | nan | nan | | same | +| q22 | 27.52 | 27.51 | 1.000 | 32.37 | 32.09 | 0.991 | 88.06 | 88.01 | 0.999 | nan | nan | nan | | same | +| q23 | 48.85 | 48.95 | 1.002 | 60.43 | 60.82 | 1.006 | 158.53 | 159.74 | 1.008 | nan | nan | nan | | same | +| q24 | 29.11 | 29.35 | 1.008 | 34.46 | 34.99 | 1.015 | 93.23 | 94.08 | 1.009 | nan | nan | nan | | same | +| q25 | 0.90 | 1.00 | 1.115 | 4.50 | 4.58 | 1.017 | 6.43 | 6.64 | 1.033 | nan | nan | nan | | same | +| q26 | 10.75 | 10.89 | 1.013 | 15.76 | 15.90 | 1.009 | 37.37 | 37.93 | 1.015 | nan | nan | nan | | same | +| q27 | 0.92 | 0.89 | 0.974 | 4.46 | 4.61 | 1.034 | 6.65 | 6.68 | 1.005 | nan | nan | nan | | same | +| q28 | 82.56 | 81.18 | 0.983 | 85.31 | 83.73 | 0.981 | 253.18 | 246.76 | 0.975 | nan | nan | nan | | same | +| q29 | 353.98 | 348.62 | 0.985 | 441.91 | 437.86 | 0.991 | 1155.87 | 1139.93 | 0.986 | nan | nan | nan | | same | +| q30 | 0.02 | 0.02 | 1.014 | 3.00 | 3.00 | 0.999 | 3.06 | 3.06 | 1.000 | nan | nan | nan | | same | +| q31 | 52.96 | 51.18 | 0.966 | 70.75 | 70.18 | 0.992 | 177.13 | 173.56 | 0.980 | nan | nan | nan | | same | +| q32 | 59.38 | 58.96 | 0.993 | 86.45 | 85.40 | 0.988 | 205.69 | 204.36 | 0.994 | nan | nan | nan | | same | +| q33 | 202.48 | 203.58 | 1.005 | 364.64 | 364.41 | 0.999 | 777.62 | 774.65 | 0.996 | nan | nan | nan | | same | +| q34 | 39.31 | 39.09 | 0.994 | 70.63 | 69.87 | 0.989 | 150.44 | 148.73 | 0.989 | nan | nan | nan | | same | +| q35 | 39.27 | 39.27 | 1.000 | 70.63 | 69.75 | 0.988 | 149.92 | 149.48 | 0.997 | nan | nan | nan | | same | +| q36 | 64.14 | 64.00 | 0.998 | 88.21 | 88.71 | 1.006 | 217.23 | 217.43 | 1.001 | nan | nan | nan | | same | +| q37 | 17.32 | 16.65 | 0.962 | 27.82 | 27.16 | 0.976 | 62.53 | 60.60 | 0.969 | nan | nan | nan | | same | +| q38 | 15.85 | 14.93 | 0.942 | 25.28 | 24.39 | 0.964 | 57.90 | 55.03 | 0.950 | nan | nan | nan | | same | +| q39 | 7.47 | 7.09 | 0.950 | 14.91 | 14.65 | 0.982 | 30.23 | 29.10 | 0.962 | nan | nan | nan | | same | +| q40 | 58.48 | 58.21 | 0.995 | 90.96 | 90.06 | 0.990 | 211.28 | 207.94 | 0.984 | nan | nan | nan | | same | +| q41 | 5.82 | 5.73 | 0.985 | 13.42 | 13.32 | 0.993 | 25.51 | 24.89 | 0.976 | nan | nan | nan | | same | +| q42 | 4.56 | 4.47 | 0.980 | 11.08 | 11.02 | 0.995 | 20.55 | 20.37 | 0.991 | nan | nan | nan | | same | +| q43 | 9.29 | 8.98 | 0.967 | 18.99 | 18.34 | 0.966 | 38.28 | 37.42 | 0.977 | nan | nan | nan | | same | + +``` +totals over all 43: warm 1798.0 vs 1786.8 (0.994); first run 2590.8 vs 2586.5 (0.998); 3-run 6236.9 vs 6205.7 (0.995) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=35)=0.977 warm_worst=1.115 worst5 [(1.115, 'q25'), (1.053, 'q6'), (1.045, 'q5'), (1.04, 'q7'), (1.032, 'q20')] +``` + +#### arm C1: parted p0, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.108 | 0.01 | 0.01 | 0.860 | 0.01 | 0.01 | 0.876 | nan | nan | nan | | same | +| q2 | 6.61 | 6.62 | 1.001 | 17.10 | 16.70 | 0.976 | 30.59 | 30.41 | 0.994 | nan | nan | nan | | same | +| q3 | 536.96 | 558.73 | 1.041 | 558.24 | 568.39 | 1.018 | 1637.52 | 1696.56 | 1.036 | nan | nan | nan | | same | +| q4 | 278.85 | 276.42 | 0.991 | 327.74 | 324.35 | 0.990 | 888.40 | 891.36 | 1.003 | nan | nan | nan | | same | +| q5 | 275.37 | 281.03 | 1.021 | 328.29 | 326.72 | 0.995 | 884.00 | 895.09 | 1.013 | nan | nan | nan | | same | +| q6 | 343.11 | 348.16 | 1.015 | 9698.42 | 9731.45 | 1.003 | 10403.65 | 10443.97 | 1.004 | nan | nan | nan | | same | +| q7 | 526.58 | 529.63 | 1.006 | 554.73 | 558.38 | 1.007 | 1616.05 | 1621.21 | 1.003 | nan | nan | nan | | same | +| q8 | 9.13 | 6.36 | 0.696 | 21.38 | 7.98 | 0.373 | 39.98 | 20.90 | 0.523 | nan | nan | nan | | same | +| q9 | 89.77 | 85.68 | 0.954 | 179.80 | 152.55 | 0.848 | 363.05 | 328.43 | 0.905 | nan | nan | nan | | same | +| q10 | 87.39 | 79.39 | 0.908 | 205.13 | 158.15 | 0.771 | 381.58 | 321.47 | 0.842 | nan | nan | nan | | same | +| q11 | 357.48 | 24.06 | 0.067 | 576.13 | 59.26 | 0.103 | 1304.50 | 110.45 | 0.085 | nan | nan | nan | | same | +| q12 | 357.24 | 26.78 | 0.075 | 572.06 | 60.89 | 0.106 | 1299.07 | 115.33 | 0.089 | nan | nan | nan | | same | +| q13 | 40.19 | 40.25 | 1.002 | 70.56 | 72.85 | 1.032 | 151.58 | 154.31 | 1.018 | nan | nan | nan | | same | +| q14 | 1133.32 | 102.95 | 0.091 | 1403.29 | 153.26 | 0.109 | 3678.46 | 366.48 | 0.100 | nan | nan | nan | | same | +| q15 | 46.67 | 46.53 | 0.997 | 89.81 | 90.20 | 1.004 | 185.20 | 185.52 | 1.002 | nan | nan | nan | | same | +| q16 | 76.44 | 72.57 | 0.949 | 145.56 | 98.79 | 0.679 | 302.96 | 244.82 | 0.808 | nan | nan | nan | | same | +| q17 | 103.63 | 95.54 | 0.922 | 204.53 | 133.73 | 0.654 | 413.35 | 326.89 | 0.791 | nan | nan | nan | | same | +| q18 | 17.21 | 17.09 | 0.993 | 84.12 | 83.53 | 0.993 | 119.39 | 117.59 | 0.985 | nan | nan | nan | | same | +| q19 | 141.87 | 141.45 | 0.997 | 334.42 | 335.92 | 1.004 | 622.65 | 622.25 | 0.999 | nan | nan | nan | | same | +| q20 | 4.61 | 4.68 | 1.014 | 14.34 | 14.44 | 1.007 | 23.89 | 24.02 | 1.005 | nan | nan | nan | | same | +| q21 | 41.90 | 41.74 | 0.996 | 48.45 | 46.94 | 0.969 | 136.53 | 132.31 | 0.969 | nan | nan | nan | | same | +| q22 | 60.68 | 60.77 | 1.001 | 85.82 | 86.91 | 1.013 | 209.57 | 208.71 | 0.996 | nan | nan | nan | | same | +| q23 | 93.79 | 90.61 | 0.966 | 206.67 | 117.78 | 0.570 | 395.79 | 299.80 | 0.757 | nan | nan | nan | | same | +| q24 | 44.48 | 44.41 | 0.998 | 127.02 | 127.19 | 1.001 | 215.96 | 217.93 | 1.009 | nan | nan | nan | | same | +| q25 | 1074.07 | 1052.47 | 0.980 | 1331.71 | 1328.17 | 0.997 | 3481.83 | 3441.38 | 0.988 | nan | nan | nan | | same | +| q26 | 1125.78 | 1106.85 | 0.983 | 1473.13 | 1466.61 | 0.996 | 3745.40 | 3705.24 | 0.989 | nan | nan | nan | | same | +| q27 | 1084.67 | 1065.58 | 0.982 | 1338.58 | 1326.23 | 0.991 | 3515.11 | 3478.92 | 0.990 | nan | nan | nan | | same | +| q28 | 92.14 | 91.33 | 0.991 | 147.79 | 147.94 | 1.001 | 336.72 | 331.77 | 0.985 | nan | nan | nan | | same | +| q29 | 362.16 | 357.81 | 0.988 | 471.83 | 469.18 | 0.994 | 1204.29 | 1189.85 | 0.988 | nan | nan | nan | | same | +| q30 | 267.68 | 277.81 | 1.038 | 284.43 | 286.33 | 1.007 | 830.87 | 857.70 | 1.032 | nan | nan | nan | | same | +| q31 | 55.42 | 55.62 | 1.004 | 124.75 | 124.97 | 1.002 | 237.74 | 239.72 | 1.008 | nan | nan | nan | | same | +| q32 | 68.90 | 69.00 | 1.001 | 179.08 | 178.04 | 0.994 | 320.00 | 321.12 | 1.004 | nan | nan | nan | | same | +| q33 | 217.16 | 211.97 | 0.976 | 468.10 | 372.87 | 0.797 | 909.83 | 805.93 | 0.886 | nan | nan | nan | | same | +| q34 | 43.57 | 43.12 | 0.990 | 96.72 | 95.36 | 0.986 | 184.03 | 182.53 | 0.992 | nan | nan | nan | | same | +| q35 | 390.54 | 43.40 | 0.111 | 2301.47 | 96.71 | 0.042 | 3083.73 | 184.33 | 0.060 | nan | nan | nan | | same | +| q36 | 147.42 | 145.49 | 0.987 | 216.52 | 216.25 | 0.999 | 520.36 | 514.19 | 0.988 | nan | nan | nan | | same | +| q37 | 36.76 | 36.10 | 0.982 | 69.49 | 69.32 | 0.998 | 144.55 | 142.21 | 0.984 | nan | nan | nan | | same | +| q38 | 35.90 | 35.26 | 0.982 | 68.57 | 67.62 | 0.986 | 146.53 | 143.13 | 0.977 | nan | nan | nan | | same | +| q39 | 15.41 | 15.13 | 0.982 | 27.72 | 27.41 | 0.989 | 58.55 | 57.99 | 0.990 | nan | nan | nan | | same | +| q40 | 117.80 | 117.17 | 0.995 | 419.75 | 421.61 | 1.004 | 658.80 | 660.14 | 1.002 | nan | nan | nan | | same | +| q41 | 17.73 | 17.63 | 0.994 | 38.83 | 38.89 | 1.002 | 75.22 | 74.57 | 0.991 | nan | nan | nan | | same | +| q42 | 13.44 | 13.12 | 0.977 | 24.02 | 23.87 | 0.994 | 51.51 | 51.09 | 0.992 | nan | nan | nan | | same | +| q43 | 28.72 | 28.28 | 0.985 | 41.00 | 41.17 | 1.004 | 99.03 | 98.66 | 0.996 | nan | nan | nan | | same | + +``` +totals over all 43: warm 9868.6 vs 7764.6 (0.787); first run 24977.1 vs 20124.9 (0.806); 3-run 44907.8 vs 35856.3 (0.798) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=42)=0.776 warm_worst=1.108 worst5 [(1.108, 'q1'), (1.041, 'q3'), (1.038, 'q30'), (1.021, 'q5'), (1.015, 'q6')] +q16 first run base 145.6 ms, p2 98.8 ms (carry 2) +``` + +#### arm R: parted ragged, base vs p2 binary (ms; ratio = p2/base) + +| q | warm_a | warm_b | wr | first_a | first_b | fr | 3run_a | 3run_b | tr | cold_a | cold_b | cr | materialized | answers | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.009 | 0.01 | 0.01 | 1.144 | 0.01 | 0.01 | 1.136 | nan | nan | nan | | same | +| q2 | 7.76 | 7.56 | 0.975 | 18.19 | 17.16 | 0.944 | 33.77 | 32.27 | 0.956 | nan | nan | nan | | same | +| q3 | 578.79 | 282.82 | 0.489 | 592.24 | 293.67 | 0.496 | 1755.26 | 860.58 | 0.490 | nan | nan | nan | | same | +| q4 | 275.04 | 275.99 | 1.003 | 323.09 | 322.98 | 1.000 | 875.03 | 882.94 | 1.009 | nan | nan | nan | | same | +| q5 | 273.95 | 278.98 | 1.018 | 328.18 | 324.35 | 0.988 | 882.66 | 884.92 | 1.003 | nan | nan | nan | | same | +| q6 | 342.84 | 346.64 | 1.011 | 9674.16 | 9722.34 | 1.005 | 10366.30 | 10413.12 | 1.005 | nan | nan | nan | | same | +| q7 | 524.12 | 525.43 | 1.003 | 555.39 | 554.24 | 0.998 | 1620.54 | 1608.67 | 0.993 | nan | nan | nan | | same | +| q8 | 9.61 | 8.75 | 0.911 | 22.56 | 10.28 | 0.456 | 41.90 | 27.87 | 0.665 | nan | nan | nan | | same | +| q9 | 89.12 | 85.58 | 0.960 | 180.49 | 152.64 | 0.846 | 359.73 | 323.84 | 0.900 | nan | nan | nan | | same | +| q10 | 87.41 | 79.47 | 0.909 | 203.34 | 153.84 | 0.757 | 380.81 | 316.04 | 0.830 | nan | nan | nan | | same | +| q11 | 373.77 | 23.68 | 0.063 | 644.06 | 57.46 | 0.089 | 1406.18 | 106.65 | 0.076 | nan | nan | nan | | same | +| q12 | 375.31 | 26.49 | 0.071 | 644.49 | 60.79 | 0.094 | 1399.42 | 114.96 | 0.082 | nan | nan | nan | | same | +| q13 | 39.86 | 39.96 | 1.003 | 69.53 | 70.83 | 1.019 | 150.09 | 152.82 | 1.018 | nan | nan | nan | | same | +| q14 | 1178.45 | 101.52 | 0.086 | 1501.43 | 153.94 | 0.103 | 3876.60 | 363.22 | 0.094 | nan | nan | nan | | same | +| q15 | 46.60 | 46.34 | 0.995 | 89.81 | 89.35 | 0.995 | 187.11 | 186.23 | 0.995 | nan | nan | nan | | same | +| q16 | 75.97 | 72.53 | 0.955 | 146.94 | 98.26 | 0.669 | 300.06 | 243.94 | 0.813 | nan | nan | nan | | same | +| q17 | 103.16 | 95.46 | 0.925 | 203.22 | 134.24 | 0.661 | 411.42 | 329.21 | 0.800 | nan | nan | nan | | same | +| q18 | 17.16 | 17.11 | 0.997 | 84.07 | 83.62 | 0.995 | 119.17 | 117.98 | 0.990 | nan | nan | nan | | same | +| q19 | 141.28 | 141.09 | 0.999 | 338.16 | 335.93 | 0.993 | 624.46 | 621.36 | 0.995 | nan | nan | nan | | same | +| q20 | 4.49 | 4.44 | 0.990 | 13.87 | 14.29 | 1.031 | 23.34 | 23.49 | 1.006 | nan | nan | nan | | same | +| q21 | 41.65 | 41.77 | 1.003 | 46.64 | 46.65 | 1.000 | 130.20 | 131.21 | 1.008 | nan | nan | nan | | same | +| q22 | 60.44 | 60.49 | 1.001 | 85.40 | 86.72 | 1.016 | 206.67 | 207.61 | 1.005 | nan | nan | nan | | same | +| q23 | 93.82 | 90.04 | 0.960 | 266.72 | 118.30 | 0.444 | 457.63 | 299.99 | 0.656 | nan | nan | nan | | same | +| q24 | 44.34 | 44.55 | 1.005 | 191.47 | 168.66 | 0.881 | 284.79 | 262.16 | 0.921 | nan | nan | nan | | same | +| q25 | 1119.36 | 1103.61 | 0.986 | 1422.38 | 1388.75 | 0.976 | 3677.66 | 3607.33 | 0.981 | nan | nan | nan | | same | +| q26 | 1178.30 | 1162.15 | 0.986 | 1575.60 | 1540.52 | 0.978 | 3943.13 | 3875.83 | 0.983 | nan | nan | nan | | same | +| q27 | 1127.49 | 1113.84 | 0.988 | 1441.46 | 1400.35 | 0.971 | 3718.50 | 3641.63 | 0.979 | nan | nan | nan | | same | +| q28 | 91.69 | 91.02 | 0.993 | 148.12 | 149.64 | 1.010 | 333.52 | 334.54 | 1.003 | nan | nan | nan | | same | +| q29 | 360.94 | 356.33 | 0.987 | 470.32 | 467.26 | 0.994 | 1205.90 | 1186.74 | 0.984 | nan | nan | nan | | same | +| q30 | 265.00 | 277.49 | 1.047 | 283.79 | 286.02 | 1.008 | 830.28 | 855.86 | 1.031 | nan | nan | nan | | same | +| q31 | 55.48 | 55.10 | 0.993 | 124.64 | 123.71 | 0.993 | 238.34 | 236.29 | 0.991 | nan | nan | nan | | same | +| q32 | 68.71 | 69.21 | 1.007 | 176.43 | 177.95 | 1.009 | 316.97 | 316.60 | 0.999 | nan | nan | nan | | same | +| q33 | 216.42 | 212.28 | 0.981 | 462.11 | 372.43 | 0.806 | 905.00 | 801.73 | 0.886 | nan | nan | nan | | same | +| q34 | 43.40 | 43.00 | 0.991 | 95.99 | 95.34 | 0.993 | 183.39 | 181.61 | 0.990 | nan | nan | nan | | same | +| q35 | 411.54 | 43.15 | 0.105 | 2397.56 | 95.23 | 0.040 | 3237.26 | 182.08 | 0.056 | nan | nan | nan | | same | +| q36 | 148.10 | 145.22 | 0.981 | 217.59 | 214.29 | 0.985 | 520.05 | 511.30 | 0.983 | nan | nan | nan | | same | +| q37 | 36.19 | 35.60 | 0.984 | 73.95 | 73.88 | 0.999 | 148.45 | 147.07 | 0.991 | nan | nan | nan | | same | +| q38 | 35.64 | 34.77 | 0.976 | 73.37 | 73.76 | 1.005 | 145.99 | 144.65 | 0.991 | nan | nan | nan | | same | +| q39 | 15.00 | 14.96 | 0.997 | 28.95 | 28.56 | 0.986 | 59.81 | 65.04 | 1.088 | nan | nan | nan | | same | +| q40 | 151.51 | 154.37 | 1.019 | 461.13 | 451.62 | 0.979 | 771.09 | 769.30 | 0.998 | nan | nan | nan | | same | +| q41 | 17.59 | 17.23 | 0.980 | 40.02 | 38.10 | 0.952 | 75.68 | 72.81 | 0.962 | nan | nan | nan | | same | +| q42 | 13.26 | 12.76 | 0.962 | 26.28 | 23.79 | 0.905 | 53.05 | 49.45 | 0.932 | nan | nan | nan | | same | +| q43 | 28.18 | 28.00 | 0.994 | 42.16 | 41.63 | 0.987 | 100.10 | 98.07 | 0.980 | nan | nan | nan | | same | + +``` +totals over all 43: warm 10168.7 vs 7666.8 (0.754); first run 25785.3 vs 20113.4 (0.780); 3-run 46357.3 vs 35589.0 (0.768) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=42)=0.763 warm_worst=1.047 worst5 [(1.047, 'q30'), (1.019, 'q40'), (1.018, 'q5'), (1.011, 'q6'), (1.009, 'q1')] +``` + +## P3 aware paths (10M store, release build, commit 7a603266) + +**The first run below (7a603266, "FAIL (pending)") is kept as history. +"Gate rerun (HEAD 2f949edc, after Task 14b)" at the end of this section +supersedes it and holds the verdict: P3 gate: PASS (Ruling 14-8).** + +The P3 gate (plan: compressed-columns P3, Task 14). The P2 driver ran +unchanged: `W=/home/hetoku/data/tmp/p3_bench p2_bench.sh all`, 07:14-08:55, +with HEAD 7a603266 (release, sha256 95039693ca59) against the base 80a28e49 +(release from `git archive`, sha256 f1075b366780). It ran all 43 queries +on arms A, B, C0, C1 and R, in 5 alternated rounds, with 3 cold trials per +query (fadvise eviction) and full answers compared; the ragged partition 9 +keeps 40 columns. The verdict is `p3_summary.py` (P2's `p2_summary.py` +unchanged, plus the P3 clauses). Raw data: +/home/hetoku/data/tmp/p3_bench/p2.tsv, with summary.txt beside it. Nothing +else heavy ran: the CI runner's listener was idle the whole time, no +Runner.Worker process appeared, and the load came from the driver alone. + +Sizes are unchanged (g0 5 948 677 939 B, g2 3 307 128 731 B; p0 +4 807 844 987 B, p2 2 072 366 907 B). Peak RSS over all 43 queries is now +lower on generation 2 than on generation 0: g0 5 120 100 kB against g2 +5 060 388 kB (x0.988; P2: x1.58), and p0 12 158 788 kB against p2 +11 963 400 kB (x0.984). + +### Gate lines + +``` +GATE (strict) splayed[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=FAIL warm=PASS q16_first=PASS] gen0-ragged[answers=FAIL warm=PASS] +P2 GATE (strict): FAIL +p3_unexpected_materializations A/q23:SearchPhrase B/q6:SearchPhrase B/q28:URL +rss A: 5120100 -> 5060388 kB (x0.988, bound 1.1) +rss B: 12158788 -> 11963400 kB (x0.984, bound 1.1) +P3GATE p2_strict=FAIL materialization=FAIL rss=PASS +P3 GATE: FAIL +``` + +**P3 gate (first run): FAIL (pending)**, superseded by the rerun below. +The controller ruled on each failing clause (rulings 14-1 to 14-7: fixed in +14b, or accepted). +Parted (arm B) passes every P2 clause on its own, with no exemption. + +### Failing clauses + +The profiles are `perf record -g` on the release binary, with the query run +5-30 times in one process; each line gives the top symbols as self samples, +g0 -> g2. + +| clause | query, arm | a -> b (ms) | ratio | owning path (diagnosis) | +|---|---|---|---|---| +| splayed warm (scan-only) | q13, A | 22.30 -> 31.54 | 1.414 | SYM-key group over the staged fused radix | +| splayed first | q13, A | 32.21 -> 40.57 | 1.260 | same | +| splayed warm | q15, A | 26.83 -> 35.98 | 1.341 | same (keys SearchEngineID, SearchPhrase) | +| splayed first | q15, A | 39.58 -> 49.43 | 1.249 | same | +| splayed warm | q29, A | 347.47 -> 425.13 | 1.224 | group by Referer: an extra min/max pass and a packed agg read | +| splayed first | q29, A | 434.76 -> 515.64 | 1.186 | same | +| splayed cold | q29, A | 500.27 -> 554.97 | 1.109 | same | +| splayed warm | q8, A | 3.59 -> 4.05 | 1.128 | run-level dense count; P3_DEFERRALS exempts it, the strict line does not | +| splayed materializing warm | q22, A | 18.04 -> 20.55 | 1.139 | SearchPhrase key decoded per morsel after the URL LIKE | +| gen0-splayed warm (C0) | q27 | 0.90 -> 1.00 | 1.110 | sub-ms gate statistic, not a regression (re-check below) | +| gen0-parted / gen0-ragged answers | q40, C1 and R | - | DIFF | tie order at the `take: 1010` boundary, not a wrong answer | +| materialization | q23, A | SearchPhrase | - | count-distinct group key, outside ALLOW | +| materialization | q6, B | SearchPhrase | - | parted `(at hits 'SearchPhrase)` takes the whole column | +| materialization | q28, B | URL | - | `strlen URL` in the per-partition group | + +- **q13 and q15, splayed.** Generation 2 did not slow down. Its time + stayed where the P2 gate had it (q13 31.87 -> 31.54 ms, q15 37.51 -> + 35.98 ms). Generation 0 sped up during P3 (C0: q13 0.709, q15 0.724; g0 + 31.91 -> 22.30 ms) and generation 2 did not follow. The profiles: + - g0 (q13): agg_radix_group_fn 3 081, agg_radix_scatter_fn 2 112, + rowsel_emit_segment 1 809, agg_radix_count_fn 1 267, + agg_sel_cursor_next 953; + - g2 (q13): agg_radix_group_fused_fn 3 342, agg_radix_stage_rows 1 834, + rowsel_emit_segment 1 812, dec_fast_runs 1 382, eval_runs 1 170; + - q15 matches, with ray_enccol_vview 869 in sixth place. + + Generation 0 groups over the selection with the plain radix. Generation + 2 stages the SYM key rows (`agg_radix_stage_rows`) and decodes the key per + morsel (dec_fast_runs, eval_runs and the view: about 18% of the samples). + The owning path is the group-by key read on generation 2: the staged fused + radix in agg_engine.c / group.c (Path 5 ids by range). +- **q22, splayed** (materializing: URL by LIKE). The P3 gain is the same as + for q13: g0 27.53 -> 18.04 ms, g2 27.56 -> 20.55 ms. The profiles: + - g0: like_rows_fn 7 865, memmem 3 573, rowsel_emit_segment 2 644, + dom_parse_strl_atoms 803, expr_eval_morsel 826; + - g2: like_rows_fn 7 700, memmem 3 651, rowsel_emit_segment 2 664, + eval_runs 1 736, dom_parse_strl_atoms 826, ray_enccol_vview 609. + + The extra eval_runs and view time is the SearchPhrase key and its + `!= ""` filter read by range. It is the same owner as q13. +- **q29, splayed** (`by: Referer`, `avg (strlen Referer)`). This one is a + generation-2 slowdown since P2: g2 349.10 -> 425.13 ms, with g0 + unchanged. P2 materialized Referer, and the group then read the flat + column. The profiles: + - g0: radix_phase1_body 21 124, radix_phase3_fn 10 568, + accum_from_entry_nullable 3 800, radix_phase2_fn 3 081, + exec_group_run 1 412; + - g2: radix_phase1_body 14 216, minmax_scan_body 11 631, + radix_phase3_fn 10 456, ght_pack_aggs_piece 7 256, + accum_from_entry_nullable 3 922. + + The DWARF call graph puts minmax_scan_body under exec_group_run -> + minmax_scan_fn -> group_sel_walk -> ray_col_walk -> minmax_piece, and + ght_pack_aggs_piece under radix_phase1_body. Generation 2 makes a range + pass over the key for its bounds, which generation 0 does not make, and it + packs the aggregate inputs piece by piece. The owning path is the + exec_group_run range-read setup (min/max key bounds by a column walk + instead of from the directory or the SYM bound), group.c. +- **q8, splayed** (watch item, was 1.17 after Task 3b). The profiles: + - g0: rowsel_emit_segment 1 315, dom_parse_strl_atoms 792, + expr_eval_morsel 679, expr_load_i64 389, agg_dense_sel_rows 294; + - g2: rowsel_emit_segment 1 252, dom_parse_strl_atoms 780, eval_runs 279, + ray_enccol_vview 263, agg_dense_runs_sel 194. + + What remains is the run view built for the filter and again for the dense + count (the triple-view structure ruled on at Task 3b). P3_DEFERRALS + exempts it (cap 2.13), but the strict line counts it. +- **Gen-0 q27 (C0)** (`asc: [EventTime SearchPhrase] take: 10`). Both + medians are about 1 ms, and the gap of 0.10 ms is above the 0.05 ms floor. + The gate statistic takes the best round: base 0.902 against p2 1.001. The + medians of the rounds are 0.983 and 1.039. A 9-round alternated re-check + on g0 gave a median of 1.031 ms for both binaries, and best rounds of 0.886 + and 0.918. This is the same sub-ms artifact as P2's gen-0 q25. Gen-0 q30 + at 1.773 passes on the floor (0.02 -> 0.03 ms). +- **q40, gen-0 parted and ragged** (base against p2, both p0). The whole + grouped result (354 662 rows) is byte-identical once sorted. 945 groups + have PageViews > 13, and 131 tie at 13. `desc: PageViews take: 1010` cuts + through that tie, so `take: -10` returns ten of the tied groups, and which + ten depends on tie order. The new binary now returns the same ten as + arms A, B and C0 (raw hash dd41af295a7d). The base returns a different + ten (2da5238161f2). The driver's sorted compare cannot tell a cut tie set + from a wrong answer, so it reports DIFF. At the P2 gate (df637f04) the + p2 binary still matched the base here. +- **Materializations outside ALLOW**: + - **A/q23 SearchPhrase**: taken directly by ray_select_impl, on the + count-distinct route (UserID by count_distinct_per_group_buf). This is + the same class as q10's RegionID: the group key of a group that has a + holistic aggregate. Parted q23 does not materialize it. Covering it + would widen ALLOW, which needs a ruling (D7). + - **B/q6 SearchPhrase**: `(count (distinct (at hits 'SearchPhrase)))`. + `ray_table_col_value` materializes the parted column for `at`, and + `enc_materialize_parted` fans out to every segment. Splayed `at` is + lazy and materializes nothing. The class is the eval-level column value + of a parted table (holistic distinct). The profile is the same on p0 + and p2 (sym_intern_nolock 12 815 / 12 690, ray_str_len 2 415 / 2 409), + and so is the time (warm 1.008). + - **B/q28 URL**: exec_strlen inside exec_group_per_partition + materializes each partition's URL (10 segments). The class is a row + expression (`strlen`) over a STR column in the per-partition group. No + ALLOW class covers it, and splayed q28 materializes nothing. The + profile is the same on p0 and p2 (strlen_sym_task 4 798 / 4 782, + agg_dense_sel_rows 1 965 / 2 071), and so is the time (0.964). + - The owning paths: parted `at` (eval / table column value) and the + per-partition group's expression inputs (exec_group_per_partition). + +### Materialization classes, traced + +The traces ran gdb on the release binary, with breakpoints on +`enc_materialize_single` and `enc_materialize_parted` printing the column +path and the backtrace, on generation-2 stores rebuilt after the run under +the same driver paths. + +| query | ALLOW entry | A (splayed) traced | B (parted) traced | class / outcome | +|---|---|---|---|---| +| q11 | UserID, MobilePhoneModel | both, try_count_distinct_v2_rewrite | none | count distinct (holistic): holds | +| q12 | UserID, MobilePhone, MobilePhoneModel | none | none | nested group: narrowed out of ALLOW | +| q14 | UserID, SearchPhrase | both, try_count_distinct_v2_rewrite | none | count distinct (holistic): holds | +| q22 | URL | URL, exec_like | URL, exec_like | LIKE: holds | +| q23 | Title, URL, UserID | Title and URL by exec_like, UserID by count_distinct_per_group_buf, plus SearchPhrase (ray_select_impl) | Title, URL by exec_like | LIKE and count distinct: hold; SearchPhrase is outside the entry (see above) | +| q24 | EventTime, URL | EventTime, ray_col_src_plain in ray_fused_topk_select | URL, exec_like | sort key (A); LIKE outside the fused predicate (B): both hold | +| q40 | URL, Referer, SearchEngineID, AdvEngineID, TraficSourceID | none | none | computed key Src: narrowed out of ALLOW | + +The other materializations take the classes ALLOW states: +- q9 and q10: count distinct (try_count_distinct_v2_rewrite, + count_distinct_per_group_buf); +- q19: `minute EventTime`, by bind_referenced_columns (A) and exec_extract + (B); +- q21: LIKE in ray_try_count_select_expr; +- q25-q27: sort keys in ray_fused_topk_select; +- q30: `set`, by ray_lazy_materialize. + +### Carries and watch list + +Each carry is printed with its P2 re-run ratio and today's: + +``` +carry q2/A/warm: P2 x1.086 -> P3 x0.606 +carry q8/A/warm: P2 x1.424 -> P3 x1.128 +carry q8/B/warm: P2 x1.060 -> P3 x0.356 +carry q18/A/first: P2 x1.983 -> P3 x0.487 +carry q18/B/warm: P2 x1.088 -> P3 x0.764 +carry q39/A/first: P2 x2.402 -> P3 x0.725 +carry q39/B/first: P2 x1.503 -> P3 x0.740 +carry q42/A/warm: P2 x1.664 -> P3 x1.012 +carry q42/B/warm: P2 x1.237 -> P3 x1.007 +``` + +Every carry is within its P2 clause bound except q8/A/warm (1.128 > 1.05). +The splayed rss carries (q24-q27) are x0.99 now. + +| watch item | number | +|---|---| +| q8 splayed warm (was 1.17) | 1.128 (first 0.997, cold 0.243); parted q8 warm 0.356 | +| q10 | splayed warm 1.024 (materializing, passes), first 1.176, cold 0.374; parted warm 1.007 | +| q26 splayed warm (was 1.058) | 1.044 | +| parted q42 (was 1.03-1.08) | warm 1.007, first 1.006, 3-run 1.074, cold 0.769 | +| arm R, gen-0 ragged | warm gmean 0.588 (n=42), worst 1.018 (q1, below 1 ms); answers all same except q40's tie order | +| parted nullable avg (parted q4) | p0 272.86 ms, p2 0.00 ms (answered without a decode); gen 0 base -> p2 0.974 (C1) and 0.991 (R) | +| URL first-touch, q24 | splayed first 1.377 (URL is not materialized on A, only the EventTime sort key); parted first 1.220 (URL by LIKE) | +| q24-q27 first run (reported, not gated) | splayed 1.377 / 3.064 / 1.371 / 4.306; parted 1.220 / 0.770 / 0.964 / 0.740 | +| SYM `in` later in a chain (ledger line 88) | still materializes, on splayed generation 2: `(and (== IsRefresh 0) (in MobilePhoneModel ['iPad 'iPhone]))` leaves MobilePhoneModel materialized (generic OP_IN in exec_node_inner); the integer `(in TraficSourceID [-1 6])` after `(== IsRefresh 0)` does the same, so the shape is wider than SYM; `in` first in the chain: 0 | +| parted `in` (Task 12) | 0 materializations: integer and SYM, first and later in the chain, also under a group | + +### Compared with the final P2 gate (same store, same driver) + +The ratios are generation-2 warm, P3 / P2; generation-0 times moved too, +so the gen2/gen0 ratio for each run is shown beside it. + +| q | A g2 warm P2 -> P3 (ms) | A P3/P2 | A g2/g0 P2 -> P3 | B p2 warm P2 -> P3 (ms) | B P3/P2 | B p2/p0 P2 -> P3 | +|---|---|---|---|---|---|---| +| q1 | 0.00 -> 0.00 | - | 1.000 -> 1.000 | 0.00 -> 0.00 | - | 1.046 -> 1.052 | +| q2 | 0.65 -> 0.39 | 0.600 | 1.049 -> 0.606 | 6.69 -> 6.43 | 0.961 | 1.015 -> 0.953 | +| q3 | 0.00 -> 0.00 | - | 0.001 -> 0.001 | 5.85 -> 0.00 | 0.000 | 0.010 -> 0.000 | +| q4 | 0.00 -> 0.00 | - | 1.013 -> 1.068 | 7.43 -> 0.00 | 0.000 | 0.027 -> 0.000 | +| q5 | 0.00 -> 0.00 | - | 1.296 -> 1.314 | 0.00 -> 0.00 | - | 0.000 -> 0.000 | +| q6 | 0.00 -> 0.00 | - | 1.275 -> 1.244 | 346.09 -> 342.61 | 0.990 | 0.994 -> 1.008 | +| q7 | 0.00 -> 0.00 | - | 1.175 -> 1.143 | 2.54 -> 0.00 | 0.000 | 0.005 -> 0.000 | +| q8 | 5.06 -> 4.05 | 0.800 | 1.422 -> 1.128 | 6.60 -> 2.25 | 0.341 | 1.038 -> 0.356 | +| q9 | 74.96 -> 75.25 | 1.004 | 0.999 -> 0.997 | 82.99 -> 83.23 | 1.003 | 0.973 -> 0.974 | +| q10 | 72.61 -> 71.13 | 0.980 | 1.052 -> 1.024 | 80.44 -> 79.37 | 0.987 | 1.020 -> 1.007 | +| q11 | 16.18 -> 11.70 | 0.723 | 1.016 -> 1.004 | 23.26 -> 16.14 | 0.694 | 0.946 -> 0.790 | +| q12 | 16.38 -> 11.68 | 0.713 | 1.010 -> 0.988 | 25.93 -> 17.95 | 0.692 | 0.968 -> 0.780 | +| q13 | 31.87 -> 31.54 | 0.990 | 0.999 -> 1.414 | 39.79 -> 37.92 | 0.953 | 0.987 -> 1.025 | +| q14 | 62.68 -> 53.37 | 0.851 | 0.999 -> 1.014 | 101.48 -> 85.77 | 0.845 | 1.000 -> 0.867 | +| q15 | 37.51 -> 35.98 | 0.959 | 1.030 -> 1.341 | 46.19 -> 44.84 | 0.971 | 0.990 -> 1.035 | +| q16 | 63.35 -> 60.88 | 0.961 | 0.907 -> 0.874 | 64.32 -> 61.44 | 0.955 | 0.888 -> 0.848 | +| q17 | 92.67 -> 90.22 | 0.974 | 0.992 -> 0.953 | 93.16 -> 90.11 | 0.967 | 0.971 -> 0.943 | +| q18 | 6.87 -> 5.01 | 0.729 | 1.004 -> 0.736 | 17.54 -> 13.18 | 0.751 | 1.027 -> 0.764 | +| q19 | 139.33 -> 138.35 | 0.993 | 1.016 -> 1.002 | 144.65 -> 145.35 | 1.005 | 1.019 -> 1.015 | +| q20 | 0.73 -> 0.59 | 0.808 | 0.631 -> 0.506 | 1.57 -> 1.48 | 0.943 | 0.340 -> 0.318 | +| q21 | 42.20 -> 41.98 | 0.995 | 1.007 -> 1.002 | 41.82 -> 41.76 | 0.999 | 1.000 -> 1.000 | +| q22 | 27.56 -> 20.55 | 0.746 | 1.001 -> 1.139 | 60.26 -> 58.55 | 0.972 | 0.992 -> 1.023 | +| q23 | 48.96 -> 39.39 | 0.805 | 1.002 -> 1.002 | 90.05 -> 89.69 | 0.996 | 0.994 -> 1.023 | +| q24 | 29.38 -> 27.75 | 0.945 | 0.997 -> 0.948 | 43.64 -> 43.06 | 0.987 | 0.976 -> 1.016 | +| q25 | 0.95 -> 0.95 | 1.000 | 1.049 -> 0.979 | 1045.10 -> 23.81 | 0.023 | 0.992 -> 0.858 | +| q26 | 10.91 -> 11.28 | 1.034 | 1.006 -> 1.044 | 1102.02 -> 76.64 | 0.070 | 0.997 -> 0.917 | +| q27 | 0.96 -> 0.81 | 0.844 | 0.957 -> 0.902 | 1057.73 -> 38.77 | 0.037 | 0.992 -> 0.753 | +| q28 | 67.00 -> 65.20 | 0.973 | 0.822 -> 0.814 | 87.55 -> 83.84 | 0.958 | 0.966 -> 0.964 | +| q29 | 349.10 -> 425.13 | 1.218 | 1.002 -> 1.224 | 356.29 -> 360.24 | 1.011 | 1.001 -> 0.999 | +| q30 | 0.02 -> 0.02 | - | 1.010 -> 1.027 | 276.13 -> 264.89 | 0.959 | 0.995 -> 1.001 | +| q31 | 51.61 -> 39.86 | 0.772 | 1.004 -> 0.939 | 56.22 -> 53.17 | 0.946 | 1.012 -> 1.019 | +| q32 | 59.28 -> 47.78 | 0.806 | 1.000 -> 0.962 | 71.43 -> 67.74 | 0.948 | 1.038 -> 1.032 | +| q33 | 212.53 -> 212.20 | 0.998 | 1.051 -> 1.044 | 217.37 -> 215.53 | 0.992 | 1.030 -> 1.009 | +| q34 | 38.68 -> 38.72 | 1.001 | 0.983 -> 0.990 | 43.57 -> 43.38 | 0.996 | 1.006 -> 0.998 | +| q35 | 38.64 -> 38.75 | 1.003 | 0.986 -> 0.985 | 43.37 -> 43.33 | 0.999 | 1.012 -> 1.004 | +| q36 | 61.05 -> 58.54 | 0.959 | 0.950 -> 0.917 | 144.73 -> 144.67 | 1.000 | 0.993 -> 0.994 | +| q37 | 16.53 -> 9.23 | 0.558 | 1.000 -> 0.549 | 34.42 -> 21.86 | 0.635 | 0.962 -> 0.603 | +| q38 | 14.81 -> 7.99 | 0.540 | 0.988 -> 0.529 | 33.22 -> 20.82 | 0.627 | 0.958 -> 0.579 | +| q39 | 7.19 -> 5.26 | 0.732 | 1.004 -> 0.731 | 13.24 -> 8.64 | 0.653 | 0.882 -> 0.567 | +| q40 | 58.61 -> 51.53 | 0.879 | 1.004 -> 0.876 | 115.19 -> 109.18 | 0.948 | 0.986 -> 0.929 | +| q41 | 5.69 -> 3.86 | 0.678 | 0.975 -> 0.672 | 17.17 -> 13.14 | 0.765 | 0.973 -> 0.743 | +| q42 | 7.54 -> 4.56 | 0.605 | 1.669 -> 1.012 | 16.36 -> 13.26 | 0.811 | 1.246 -> 1.007 | +| q43 | 8.93 -> 7.49 | 0.839 | 0.995 -> 0.834 | 26.56 -> 16.04 | 0.604 | 0.941 -> 0.563 | + +The warm-time gains since P2 are spread across the filtered and aggregate +queries. Splayed: +- q37 0.558, q38 0.540, q39 0.732, q41 0.678, q42 0.605; +- q18 0.729, q11 0.723, q12 0.713, q22 0.746, q31 0.772, q8 0.800. + +Parted: +- the top-k queries q25 0.023, q26 0.070, q27 0.037; +- the directory answers q3, q4, q7 (now 0.00 ms); +- q8 0.341, q37 0.635, q43 0.604. + +The one splayed query slower than at P2 is q29 (1.218). + +### Gate items (first run, superseded by the rerun below) + +**P3 gate (first run): FAIL (pending)**: +- the materialization counter is zero for filtered, rowsel-gather and + aggregate shapes: the unit gates pass (`aware/gate_materialization`, + planning included). On ClickBench, `p3_unexpected_materializations` + lists A/q23 SearchPhrase, B/q6 SearchPhrase and B/q28 URL: **FAIL**; +- decoded bytes are zero where statistics or codes answer, and exact + otherwise: `aware/gate_decoded_bytes`, `aware/filter_*`, + `aware/count_on_runs` and `aware/sum_*` pass; +- index row-list shapes materialize only the indexed column + (`aware/gather_index_rows`), and top-k only its sort keys + (`aware/topk_prune_cases`, `aware/gather_operators`, and the q24-q27 + traces above): pass; +- the cross-segment code tests pass (`aware/cross_segment_codes`, + `aware/str_key_domain`); +- the conformance battery passes (Task 13). The full suite at 7a603266 is + 5844 / 5844, with 0 UBSan runtime errors; +- the P2 gate's strict line: **FAIL**. The splayed warm, first, cold and + materializing-warm clauses fail (q13, q15, q29, q8, q22); gen-0 splayed + warm fails on q27, below 1 ms; gen-0 parted and ragged answers fail on + q40's tie order; +- RSS is within D3's bound: pass (x0.988 splayed, x0.984 parted). + +Benchmarks. Faster warm than generation 0: 23 of 43 splayed, 27 of 43 +parted. Faster cold: 37 of 43 splayed, 40 of 43 parted. Slower warm by +more than 5%: +- splayed q13 1.414, q15 1.341, q29 1.224, q22 1.139, q8 1.128 (profiles + above); +- the directory-answered q4-q7 (splayed) and q1 (parted), whose medians are + 0.00 ms on both sides. + +### Per-query tables (summary.txt) + +``` +## arm A: splayed g0 vs g2 (ms; ratio = g2/g0) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.000 0.01 0.01 0.561 0.01 0.01 0.589 0.01 0.01 1.552 [] same +q2 0.64 0.39 0.606 1.59 1.25 0.783 3.07 2.14 0.695 38.23 3.39 0.089 [] same +q3 3.78 0.00 0.001 5.50 0.04 0.007 13.23 0.05 0.004 94.34 0.04 0.000 [] same +q4 0.00 0.00 1.068 0.02 0.03 1.230 0.03 0.03 1.217 0.03 0.04 1.430 [] same +q5 0.00 0.00 1.314 0.03 0.03 1.027 0.03 0.03 1.031 0.03 0.03 0.906 [] same +q6 0.00 0.00 1.244 0.03 0.03 1.009 0.03 0.03 1.015 0.03 0.04 1.149 [] same +q7 0.00 0.00 1.143 0.02 0.04 1.982 0.02 0.04 1.838 0.02 0.04 2.002 [] same +q8 3.59 4.05 1.128 9.09 9.06 0.997 16.52 17.63 1.068 41.13 10.01 0.243 [] same +q9 75.49 75.25 0.997 118.27 126.46 1.069 268.82 280.19 1.042 608.63 154.72 0.254 [RegionID UserID] same +q10 69.50 71.13 1.024 99.27 116.77 1.176 239.28 268.10 1.120 410.25 153.27 0.374 [RegionID UserID] same +q11 11.65 11.70 1.004 22.01 35.94 1.633 45.58 59.77 1.311 239.53 57.82 0.241 [UserID MobilePhoneModel] same +q12 11.83 11.68 0.988 20.78 19.08 0.918 44.83 43.02 0.960 273.33 51.80 0.190 [] same +q13 22.30 31.54 1.414 32.21 40.57 1.260 77.34 103.98 1.344 102.35 58.79 0.574 [] same +q14 52.62 53.37 1.014 78.05 93.80 1.202 187.65 203.66 1.085 292.48 131.24 0.449 [UserID SearchPhrase] same +q15 26.83 35.98 1.341 39.58 49.43 1.249 93.29 124.05 1.330 142.31 99.58 0.700 [] same +q16 69.68 60.88 0.874 95.75 86.21 0.900 241.47 213.75 0.885 240.47 163.17 0.679 [] same +q17 94.68 90.22 0.953 130.42 124.13 0.952 323.63 306.21 0.946 465.76 246.13 0.528 [] same +q18 6.81 5.01 0.736 13.47 6.57 0.487 27.36 16.63 0.608 655.77 58.84 0.090 [] same +q19 138.04 138.35 1.002 210.39 207.39 0.986 493.70 493.87 1.000 679.95 448.07 0.659 [EventTime] same +q20 1.16 0.59 0.506 6.77 6.07 0.896 9.40 7.39 0.787 55.10 16.87 0.306 [] same +q21 41.90 41.98 1.002 45.36 50.92 1.123 131.15 136.09 1.038 77.37 93.28 1.206 [URL] same +q22 18.04 20.55 1.139 26.65 33.43 1.255 63.54 74.61 1.174 173.68 110.34 0.635 [URL] same +q23 39.30 39.39 1.002 55.12 85.60 1.553 134.14 165.62 1.235 415.93 245.74 0.591 [Title UserID URL SearchPhrase] same +q24 29.29 27.75 0.948 34.49 47.50 1.377 93.42 103.63 1.109 594.88 546.27 0.918 [EventTime] same +q25 0.97 0.95 0.979 4.40 13.48 3.064 6.47 15.43 2.386 294.72 244.45 0.829 [EventTime] same +q26 10.80 11.28 1.044 15.30 20.98 1.371 37.05 43.77 1.181 549.75 292.27 0.532 [SearchPhrase] same +q27 0.90 0.81 0.902 4.43 19.07 4.306 6.44 20.93 3.249 290.37 251.87 0.867 [EventTime SearchPhrase] same +q28 80.11 65.20 0.814 89.57 71.31 0.796 257.71 205.99 0.799 220.05 90.68 0.412 [] same +q29 347.47 425.13 1.224 434.76 515.64 1.186 1133.70 1365.76 1.205 500.27 554.97 1.109 [] same +q30 0.02 0.02 1.027 2.80 4.64 1.655 2.87 4.71 1.642 54.73 11.58 0.212 [ResolutionWidth] same +q31 42.44 39.86 0.939 62.70 57.37 0.915 147.53 138.16 0.936 306.03 110.14 0.360 [] same +q32 49.65 47.78 0.962 76.68 73.12 0.954 176.17 169.64 0.963 438.33 262.80 0.600 [] same +q33 203.22 212.20 1.044 364.70 363.27 0.996 774.13 796.00 1.028 609.63 554.47 0.910 [] same +q34 39.10 38.72 0.990 70.84 71.86 1.014 149.38 151.00 1.011 138.28 109.16 0.789 [] same +q35 39.34 38.75 0.985 69.84 72.08 1.032 149.47 154.96 1.037 137.79 110.02 0.798 [] same +q36 63.86 58.54 0.917 88.27 82.88 0.939 217.58 203.80 0.937 160.52 128.09 0.798 [] same +q37 16.80 9.23 0.549 27.15 19.12 0.704 60.74 38.97 0.642 42.04 22.35 0.532 [] same +q38 15.11 7.99 0.529 25.74 16.17 0.628 56.89 33.57 0.590 39.65 19.92 0.503 [] same +q39 7.20 5.26 0.731 14.76 10.70 0.725 29.36 22.28 0.759 38.41 18.45 0.480 [] same +q40 58.84 51.53 0.876 91.43 84.72 0.927 210.87 191.33 0.907 118.61 94.68 0.798 [] same +q41 5.75 3.86 0.672 13.54 10.15 0.750 25.52 18.19 0.712 74.21 40.16 0.541 [] same +q42 4.51 4.56 1.012 11.05 10.66 0.965 21.04 20.64 0.981 37.12 20.15 0.543 [] same +q43 8.98 7.49 0.834 18.54 17.59 0.949 37.20 33.51 0.901 40.77 26.63 0.653 [] same +totals over all 43: warm 1712.2 vs 1749.0 (1.021); first run 2531.4 vs 2675.2 (1.057); 3-run 6007.7 vs 6249.1 (1.040) +answer_mismatches none +order_differences none +scan_only(gated) n=30; gmeans over base>=1ms (per column): warm n=24 0.651, first n=25 0.738, cold n=25 0.357; worst warm=1.414 +below_1ms_excluded_from_warm_gmean q1 q2 q4 q5 q6 q7 +below_1ms_excluded_from_first_gmean q1 q4 q5 q6 q7 +below_1ms_excluded_from_cold_gmean q1 q4 q5 q6 q7 +mat rows missing none +scan_only_list_but_materializing none +measured_materializing q9(2 cols) q10(2 cols) q11(2 cols) q14(2 cols) q19(1 cols) q21(1 cols) q22(1 cols) q23(4 cols) q24(1 cols) q25(1 cols) q26(1 cols) q27(2 cols) q30(1 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q6(measured scan, list other) q12(measured scan, list other) q13(measured scan, list other) q15(measured scan, list other) q20(measured scan, list other) q28(measured scan, list other) q29(measured scan, list other) q31(measured scan, list other) q32(measured scan, list other) q36(measured scan, list other) q37(measured scan, list other) q38(measured scan, list other) q40(measured scan, list other) q41(measured scan, list other) q42(measured scan, list other) q43(measured scan, list other) +worst5 warm [(1.414, 'q13'), (1.341, 'q15'), (1.314, 'q5'), (1.244, 'q6'), (1.224, 'q29')] +worst5 cold [(2.002, 'q7'), (1.552, 'q1'), (1.43, 'q4'), (1.149, 'q6'), (1.109, 'q29')] +worst5 first [(1.982, 'q7'), (1.26, 'q13'), (1.249, 'q15'), (1.23, 'q4'), (1.186, 'q29')] +worst5 materializing_warm [(1.139, 'q22'), (1.044, 'q26'), (1.027, 'q30'), (1.024, 'q10'), (1.014, 'q14')] +first_run_total_ratio 1.057 (PI after P1: 2.99) +pi_row q41 warm 0.672 first 0.750 3run 0.712 +pi_row q42 warm 1.012 first 0.965 3run 0.981 + +## arm B: parted p0 vs p2 (ms; ratio = p2/p0) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.052 0.01 0.01 0.976 0.01 0.01 0.981 0.01 0.01 0.581 [] same +q2 6.75 6.43 0.953 16.81 16.35 0.973 30.37 29.32 0.965 45.63 16.32 0.358 [] same +q3 532.99 0.00 0.000 548.07 0.05 0.000 1628.48 0.06 0.000 574.17 0.05 0.000 [] same +q4 272.86 0.00 0.000 319.81 0.04 0.000 869.00 0.04 0.000 365.63 0.04 0.000 [] same +q5 273.15 0.00 0.000 319.23 0.03 0.000 868.18 0.03 0.000 361.11 0.03 0.000 [] same +q6 339.91 342.61 1.008 9704.33 9710.43 1.001 10384.72 10398.35 1.001 9764.99 9763.91 1.000 [SearchPhrase] same +q7 527.02 0.00 0.000 555.42 0.05 0.000 1610.10 0.05 0.000 573.31 0.05 0.000 [] same +q8 6.31 2.25 0.356 7.95 3.97 0.499 20.77 8.66 0.417 40.94 3.76 0.092 [] same +q9 85.50 83.23 0.974 154.75 164.19 1.061 330.08 334.28 1.013 392.26 190.25 0.485 [RegionID UserID] same +q10 78.79 79.37 1.007 153.99 167.29 1.086 313.14 337.93 1.079 440.67 196.62 0.446 [RegionID UserID] same +q11 20.44 16.14 0.790 38.30 29.69 0.775 81.69 65.14 0.797 338.89 56.00 0.165 [] same +q12 23.01 17.95 0.780 41.05 30.59 0.745 88.50 67.15 0.759 397.37 55.65 0.140 [] same +q13 36.99 37.92 1.025 69.20 52.30 0.756 143.21 130.20 0.909 137.12 69.88 0.510 [] same +q14 98.88 85.77 0.867 134.19 116.45 0.868 337.07 291.09 0.864 397.42 158.15 0.398 [] same +q15 43.31 44.84 1.035 88.47 64.58 0.730 175.92 160.28 0.911 194.91 86.78 0.445 [] same +q16 72.45 61.44 0.848 98.92 87.39 0.883 244.24 213.77 0.875 251.36 163.40 0.650 [] same +q17 95.57 90.11 0.943 136.37 125.13 0.918 331.74 312.21 0.941 475.64 240.24 0.505 [] same +q18 17.25 13.18 0.764 85.16 18.96 0.223 119.75 45.66 0.381 330.87 61.77 0.187 [] same +q19 143.26 145.35 1.015 340.74 244.55 0.718 629.70 539.07 0.856 745.55 373.40 0.501 [EventTime] same +q20 4.64 1.48 0.318 14.62 12.05 0.824 24.25 15.61 0.644 154.69 22.32 0.144 [] same +q21 41.76 41.76 1.000 46.70 56.18 1.203 131.20 140.11 1.068 87.68 99.23 1.132 [URL] same +q22 57.22 58.55 1.023 69.66 74.42 1.068 184.84 193.35 1.046 198.94 154.62 0.777 [URL] same +q23 87.67 89.69 1.023 102.12 114.66 1.123 277.49 299.63 1.080 443.42 279.65 0.631 [Title URL] same +q24 42.38 43.06 1.016 52.97 64.62 1.220 137.98 150.62 1.092 754.23 445.57 0.591 [URL] same +q25 27.76 23.81 0.858 47.76 36.77 0.770 103.20 85.00 0.824 570.34 250.53 0.439 [] same +q26 83.62 76.64 0.917 196.44 189.39 0.964 367.00 347.96 0.948 631.47 397.15 0.629 [] same +q27 51.50 38.77 0.753 71.21 52.68 0.740 175.70 131.67 0.749 612.33 263.97 0.431 [] same +q28 86.97 83.84 0.964 128.12 133.02 1.038 306.78 309.81 1.010 275.38 184.98 0.672 [URL] same +q29 360.55 360.24 0.999 470.82 452.51 0.961 1197.06 1186.56 0.991 541.74 500.62 0.924 [] same +q30 264.50 264.89 1.001 280.06 290.50 1.037 829.42 834.86 1.007 296.49 287.85 0.971 [ResolutionWidth] same +q31 52.18 53.17 1.019 124.44 78.79 0.633 237.38 188.76 0.795 388.58 117.48 0.302 [] same +q32 65.66 67.74 1.032 181.00 106.82 0.590 314.16 245.93 0.783 580.28 274.13 0.472 [] same +q33 213.58 215.53 1.009 376.52 385.70 1.024 808.07 830.19 1.027 612.29 637.07 1.040 [] same +q34 43.49 43.38 0.998 95.86 75.46 0.787 183.59 163.62 0.891 175.37 119.33 0.680 [] same +q35 43.14 43.33 1.004 96.24 75.96 0.789 184.67 166.80 0.903 177.87 119.13 0.670 [] same +q36 145.50 144.67 0.994 214.78 198.11 0.922 511.90 495.09 0.967 302.06 208.95 0.692 [] same +q37 36.25 21.86 0.603 70.06 37.17 0.531 142.85 83.19 0.582 230.61 83.01 0.360 [] same +q38 35.95 20.82 0.579 69.57 38.06 0.547 145.73 81.02 0.556 230.92 82.49 0.357 [] same +q39 15.22 8.64 0.567 27.59 20.42 0.740 59.01 37.75 0.640 122.33 26.11 0.213 [] same +q40 117.47 109.18 0.929 427.83 350.02 0.818 665.59 574.86 0.864 783.75 442.62 0.565 [] same +q41 17.68 13.14 0.743 39.28 26.75 0.681 74.72 54.43 0.728 263.31 176.16 0.669 [] same +q42 13.17 13.26 1.007 23.71 23.86 1.006 50.85 54.62 1.074 191.60 147.31 0.769 [] same +q43 28.49 16.04 0.563 41.11 27.63 0.672 98.10 60.97 0.621 135.74 35.19 0.259 [] same +totals over all 43: warm 4610.8 vs 2880.1 (0.625); first run 16081.3 vs 13753.6 (0.855); 3-run 25418.2 vs 19665.7 (0.774) +answer_mismatches none +order_differences none +scan_only(gated) n=33; gmeans over base>=1ms (per column): warm n=32 0.170, first n=32 0.241, cold n=32 0.140; worst warm=1.052 +below_1ms_excluded_from_warm_gmean q1 +below_1ms_excluded_from_first_gmean q1 +below_1ms_excluded_from_cold_gmean q1 +mat rows missing none +scan_only_list_but_materializing none +measured_materializing q6(1 cols) q9(2 cols) q10(2 cols) q19(1 cols) q21(1 cols) q22(1 cols) q23(2 cols) q24(1 cols) q28(1 cols) q30(1 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q11(measured scan, list other) q12(measured scan, list other) q13(measured scan, list other) q14(measured scan, list other) q15(measured scan, list other) q20(measured scan, list other) q25(measured scan, list other) q26(measured scan, list other) q27(measured scan, list other) q29(measured scan, list other) q31(measured scan, list other) q32(measured scan, list other) q36(measured scan, list other) q37(measured scan, list other) q38(measured scan, list other) q40(measured scan, list other) q41(measured scan, list other) q42(measured scan, list other) q43(measured scan, list other) +worst5 warm [(1.052, 'q1'), (1.035, 'q15'), (1.032, 'q32'), (1.025, 'q13'), (1.019, 'q31')] +worst5 cold [(1.04, 'q33'), (0.924, 'q29'), (0.769, 'q42'), (0.692, 'q36'), (0.68, 'q34')] +worst5 first [(1.024, 'q33'), (1.006, 'q42'), (0.976, 'q1'), (0.973, 'q2'), (0.964, 'q26')] +worst5 materializing_warm [(1.023, 'q23'), (1.023, 'q22'), (1.016, 'q24'), (1.015, 'q19'), (1.008, 'q6')] +pi_row q41 warm 0.743 first 0.681 3run 0.728 +pi_row q42 warm 1.007 first 1.006 3run 1.074 + +## arm C0: splayed g0, base vs p2 binary (ms; ratio = p2/base) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 0.989 0.01 0.01 1.009 0.01 0.01 1.006 nan nan nan same +q2 1.11 0.64 0.576 2.01 1.67 0.830 4.41 3.13 0.709 nan nan nan same +q3 3.78 3.79 1.002 5.83 5.85 1.004 13.68 13.47 0.985 nan nan nan same +q4 0.00 0.00 1.018 0.02 0.02 1.023 0.02 0.02 1.027 nan nan nan same +q5 0.00 0.00 1.014 0.03 0.03 1.153 0.03 0.03 1.141 nan nan nan same +q6 0.00 0.00 1.059 0.03 0.03 1.155 0.03 0.03 1.146 nan nan nan same +q7 0.00 0.00 1.005 0.02 0.02 1.025 0.02 0.02 1.029 nan nan nan same +q8 3.51 3.60 1.025 9.02 9.13 1.012 16.32 16.48 1.010 nan nan nan same +q9 75.82 75.11 0.991 114.42 117.44 1.026 272.55 268.70 0.986 nan nan nan same +q10 69.40 69.03 0.995 97.93 98.25 1.003 243.15 238.14 0.979 nan nan nan same +q11 16.16 11.56 0.715 25.50 22.21 0.871 58.57 45.94 0.784 nan nan nan same +q12 16.33 11.87 0.727 25.84 20.82 0.806 59.60 45.00 0.755 nan nan nan same +q13 31.95 22.65 0.709 41.14 32.17 0.782 105.35 77.59 0.737 nan nan nan same +q14 62.66 53.25 0.850 87.92 78.04 0.888 218.26 186.88 0.856 nan nan nan same +q15 36.58 26.48 0.724 48.60 39.72 0.817 126.01 93.49 0.742 nan nan nan same +q16 70.03 69.61 0.994 95.84 94.27 0.984 237.68 234.65 0.987 nan nan nan same +q17 93.33 93.28 0.999 129.64 130.37 1.006 322.60 317.00 0.983 nan nan nan same +q18 6.93 6.92 0.998 14.98 15.02 1.003 28.95 29.38 1.015 nan nan nan same +q19 137.39 138.02 1.005 208.71 212.28 1.017 489.99 492.37 1.005 nan nan nan same +q20 1.12 1.13 1.009 6.88 7.10 1.031 9.48 9.60 1.013 nan nan nan same +q21 41.75 42.02 1.006 45.48 46.24 1.017 130.68 132.69 1.015 nan nan nan same +q22 27.70 18.12 0.654 32.01 26.55 0.829 88.49 63.38 0.716 nan nan nan same +q23 48.89 39.22 0.802 60.72 55.16 0.908 158.90 134.07 0.844 nan nan nan same +q24 29.16 29.51 1.012 35.42 34.42 0.972 97.06 95.06 0.979 nan nan nan same +q25 0.94 0.91 0.967 4.48 4.50 1.004 6.40 6.49 1.015 nan nan nan same +q26 10.78 10.82 1.003 15.44 15.68 1.015 37.04 37.72 1.018 nan nan nan same +q27 0.90 1.00 1.110 4.48 4.46 0.995 6.46 6.60 1.023 nan nan nan same +q28 82.75 80.21 0.969 84.94 86.76 1.021 257.95 248.18 0.962 nan nan nan same +q29 356.59 345.68 0.969 450.96 436.37 0.968 1174.50 1138.82 0.970 nan nan nan same +q30 0.02 0.03 1.773 3.02 3.00 0.994 3.08 3.05 0.989 nan nan nan same +q31 52.72 42.10 0.799 71.65 61.02 0.852 178.12 146.52 0.823 nan nan nan same +q32 59.36 49.48 0.833 86.30 79.12 0.917 208.20 183.31 0.880 nan nan nan same +q33 202.80 204.42 1.008 369.58 361.75 0.979 782.89 785.95 1.004 nan nan nan same +q34 39.55 39.18 0.990 70.45 71.60 1.016 150.64 150.05 0.996 nan nan nan same +q35 39.46 39.25 0.995 70.49 69.75 0.989 157.26 148.98 0.947 nan nan nan same +q36 63.90 64.17 1.004 87.56 87.05 0.994 218.99 216.70 0.990 nan nan nan same +q37 17.20 16.61 0.966 27.95 27.24 0.974 62.51 60.64 0.970 nan nan nan same +q38 15.68 15.43 0.984 25.29 24.58 0.972 57.42 55.78 0.971 nan nan nan same +q39 7.48 7.19 0.961 14.74 14.65 0.994 30.15 29.20 0.968 nan nan nan same +q40 58.87 58.83 0.999 89.87 90.75 1.010 210.31 210.83 1.002 nan nan nan same +q41 5.81 5.76 0.993 13.31 13.49 1.014 25.25 25.26 1.001 nan nan nan same +q42 4.65 4.40 0.945 11.07 11.15 1.007 20.57 20.70 1.006 nan nan nan same +q43 9.31 9.06 0.973 18.82 18.38 0.977 40.33 37.58 0.932 nan nan nan same +totals over all 43: warm 1802.3 vs 1710.3 (0.949); first run 2608.4 vs 2528.1 (0.969); 3-run 6309.9 vs 6009.5 (0.952) +answer_mismatches none +order_differences none +gen0 warm_gmean(base>=1ms n=35)=0.910 warm_worst=1.773 worst5 [(1.773, 'q30'), (1.11, 'q27'), (1.059, 'q6'), (1.025, 'q8'), (1.018, 'q4')] + +## arm C1: parted p0, base vs p2 binary (ms; ratio = p2/base) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.168 0.01 0.01 1.659 0.01 0.01 1.628 nan nan nan same +q2 6.55 6.69 1.022 17.20 16.91 0.983 30.47 30.55 1.003 nan nan nan same +q3 531.18 534.29 1.006 558.45 548.30 0.982 1636.17 1622.64 0.992 nan nan nan same +q4 277.78 270.61 0.974 331.31 319.15 0.963 886.86 868.90 0.980 nan nan nan same +q5 277.98 273.13 0.983 328.60 321.27 0.978 892.74 869.66 0.974 nan nan nan same +q6 342.94 342.45 0.999 9721.68 9706.65 0.998 10414.78 10393.52 0.998 nan nan nan same +q7 527.64 523.20 0.992 555.78 551.49 0.992 1610.99 1613.99 1.002 nan nan nan same +q8 9.19 6.41 0.697 21.42 7.92 0.370 39.95 20.91 0.524 nan nan nan same +q9 88.90 85.11 0.957 179.93 151.86 0.844 360.03 324.32 0.901 nan nan nan same +q10 87.26 78.65 0.901 203.74 152.91 0.751 383.84 316.04 0.823 nan nan nan same +q11 358.46 20.23 0.056 596.91 38.22 0.064 1321.14 81.00 0.061 nan nan nan same +q12 361.36 22.66 0.063 592.09 40.32 0.068 1317.56 86.38 0.066 nan nan nan same +q13 40.07 36.80 0.918 69.60 70.25 1.009 150.93 145.26 0.962 nan nan nan same +q14 1135.50 98.14 0.086 1421.63 136.09 0.096 3706.61 337.04 0.091 nan nan nan same +q15 46.44 43.07 0.927 89.30 90.06 1.009 184.30 178.61 0.969 nan nan nan same +q16 76.32 72.72 0.953 147.98 97.44 0.659 305.43 244.71 0.801 nan nan nan same +q17 103.93 96.16 0.925 207.04 133.39 0.644 418.69 329.98 0.788 nan nan nan same +q18 17.23 17.11 0.993 84.69 83.96 0.991 120.69 118.09 0.978 nan nan nan same +q19 141.17 143.41 1.016 333.40 338.59 1.016 624.15 629.11 1.008 nan nan nan same +q20 4.63 4.67 1.007 14.45 14.35 0.993 24.05 23.90 0.994 nan nan nan same +q21 41.80 41.87 1.002 47.31 46.70 0.987 130.78 131.59 1.006 nan nan nan same +q22 60.42 57.13 0.945 85.91 69.22 0.806 209.53 184.53 0.881 nan nan nan same +q23 93.83 86.82 0.925 214.63 101.17 0.471 405.77 276.54 0.682 nan nan nan same +q24 44.54 42.46 0.953 135.14 52.17 0.386 225.82 139.81 0.619 nan nan nan same +q25 1074.76 27.44 0.026 1345.66 46.19 0.034 3501.16 101.40 0.029 nan nan nan same +q26 1131.50 83.50 0.074 1501.25 195.22 0.130 3763.66 363.50 0.097 nan nan nan same +q27 1086.70 51.36 0.047 1359.10 69.76 0.051 3542.68 174.50 0.049 nan nan nan same +q28 92.07 86.96 0.944 148.73 128.95 0.867 335.79 303.46 0.904 nan nan nan same +q29 363.91 358.75 0.986 473.12 467.32 0.988 1210.94 1194.90 0.987 nan nan nan same +q30 266.48 263.67 0.989 282.45 278.91 0.987 831.26 819.76 0.986 nan nan nan same +q31 55.79 51.86 0.930 122.18 123.21 1.008 236.81 234.04 0.988 nan nan nan same +q32 69.13 65.57 0.949 177.54 179.40 1.010 317.70 316.87 0.997 nan nan nan same +q33 218.46 213.21 0.976 462.22 371.26 0.803 912.23 813.09 0.891 nan nan nan same +q34 43.38 42.96 0.990 96.01 98.13 1.022 184.36 185.42 1.006 nan nan nan same +q35 389.48 42.94 0.110 2307.75 96.61 0.042 3084.96 185.00 0.060 nan nan nan same +q36 148.19 145.38 0.981 215.49 217.27 1.008 517.26 514.67 0.995 nan nan nan same +q37 36.67 36.12 0.985 69.54 68.33 0.982 145.21 141.25 0.973 nan nan nan same +q38 35.45 35.22 0.994 68.43 67.82 0.991 146.19 144.36 0.987 nan nan nan same +q39 15.38 15.10 0.982 27.27 27.13 0.995 58.31 58.22 0.998 nan nan nan same +q40 117.61 117.90 1.002 421.18 423.15 1.005 663.45 664.41 1.001 nan nan nan DIFF +q41 17.63 17.55 0.995 38.74 38.73 1.000 74.52 74.10 0.994 nan nan nan same +q42 13.47 13.19 0.980 24.37 23.80 0.977 51.46 51.13 0.994 nan nan nan same +q43 28.45 28.23 0.992 41.48 41.05 0.989 101.26 98.83 0.976 nan nan nan same +totals over all 43: warm 9879.7 vs 4600.7 (0.466); first run 25140.7 vs 16050.6 (0.638); 3-run 45080.5 vs 25406.0 (0.564) +answer_mismatches q40:DIFF +order_differences none +gen0 warm_gmean(base>=1ms n=42)=0.607 warm_worst=1.168 worst5 [(1.168, 'q1'), (1.022, 'q2'), (1.016, 'q19'), (1.007, 'q20'), (1.006, 'q3')] +q16 first run base 148.0 ms, p2 97.4 ms (carry 2) + +## arm R: parted ragged, base vs p2 binary (ms; ratio = p2/base) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.018 0.01 0.01 1.043 0.01 0.01 1.041 nan nan nan same +q2 7.81 7.58 0.970 18.24 17.47 0.958 33.82 32.90 0.973 nan nan nan same +q3 582.34 269.71 0.463 598.13 286.38 0.479 1769.76 830.03 0.469 nan nan nan same +q4 276.11 273.71 0.991 325.57 316.65 0.973 881.32 867.24 0.984 nan nan nan same +q5 277.60 271.26 0.977 325.52 323.44 0.994 884.05 863.94 0.977 nan nan nan same +q6 344.27 340.36 0.989 9731.98 9744.37 1.001 10453.01 10432.31 0.998 nan nan nan same +q7 526.78 523.55 0.994 552.98 552.63 0.999 1620.81 1604.75 0.990 nan nan nan same +q8 9.58 8.77 0.915 22.33 10.32 0.462 41.77 27.88 0.668 nan nan nan same +q9 89.20 85.31 0.956 178.64 154.91 0.867 361.46 330.29 0.914 nan nan nan same +q10 87.28 79.38 0.909 204.49 154.54 0.756 384.14 315.69 0.822 nan nan nan same +q11 379.16 19.95 0.053 663.10 36.74 0.055 1422.76 77.06 0.054 nan nan nan same +q12 376.05 22.56 0.060 661.86 39.83 0.060 1414.53 85.41 0.060 nan nan nan same +q13 39.96 36.74 0.919 71.42 70.54 0.988 152.46 144.43 0.947 nan nan nan same +q14 1191.29 100.21 0.084 1526.78 134.44 0.088 3921.24 337.68 0.086 nan nan nan same +q15 46.49 42.87 0.922 89.50 88.20 0.985 186.38 174.72 0.937 nan nan nan same +q16 76.22 72.72 0.954 145.99 103.06 0.706 301.88 250.89 0.831 nan nan nan same +q17 103.27 95.81 0.928 203.53 134.01 0.658 411.28 327.71 0.797 nan nan nan same +q18 17.02 16.99 0.998 83.65 83.54 0.999 118.48 118.08 0.997 nan nan nan same +q19 141.58 143.21 1.012 336.17 339.45 1.010 623.27 630.08 1.011 nan nan nan same +q20 4.46 4.47 1.001 14.34 14.27 0.995 23.55 23.62 1.003 nan nan nan same +q21 41.80 41.90 1.002 46.35 46.63 1.006 131.44 130.91 0.996 nan nan nan same +q22 60.24 56.86 0.944 85.16 69.43 0.815 206.76 184.57 0.893 nan nan nan same +q23 93.95 86.72 0.923 276.29 101.92 0.369 471.20 279.65 0.593 nan nan nan same +q24 44.44 42.61 0.959 196.59 51.75 0.263 293.39 136.94 0.467 nan nan nan same +q25 1130.54 27.65 0.024 1444.58 44.69 0.031 3720.06 100.78 0.027 nan nan nan same +q26 1186.13 83.17 0.070 1594.96 197.36 0.124 3975.01 365.39 0.092 nan nan nan same +q27 1142.81 51.62 0.045 1467.56 70.03 0.048 3752.06 175.32 0.047 nan nan nan same +q28 92.13 86.64 0.940 148.17 125.80 0.849 334.51 302.53 0.904 nan nan nan same +q29 364.79 358.93 0.984 474.70 471.02 0.992 1213.72 1201.51 0.990 nan nan nan same +q30 267.16 265.30 0.993 281.35 280.43 0.997 834.16 833.52 0.999 nan nan nan same +q31 55.26 51.89 0.939 125.77 122.81 0.976 237.51 236.77 0.997 nan nan nan same +q32 69.00 65.60 0.951 176.83 176.68 0.999 319.67 310.37 0.971 nan nan nan same +q33 217.79 213.02 0.978 469.57 381.03 0.811 917.57 813.04 0.886 nan nan nan same +q34 43.26 43.11 0.997 95.99 96.08 1.001 185.92 183.58 0.987 nan nan nan same +q35 412.19 43.17 0.105 2415.11 94.99 0.039 3246.49 183.31 0.056 nan nan nan same +q36 148.93 146.04 0.981 215.76 216.21 1.002 525.13 513.53 0.978 nan nan nan same +q37 36.36 33.02 0.908 72.94 66.21 0.908 147.72 133.17 0.901 nan nan nan same +q38 35.06 32.13 0.916 73.33 64.97 0.886 147.71 137.17 0.929 nan nan nan same +q39 15.21 12.51 0.823 29.11 24.68 0.848 60.02 49.91 0.832 nan nan nan same +q40 153.14 148.95 0.973 463.08 452.18 0.976 772.32 752.17 0.974 nan nan nan DIFF +q41 17.60 17.16 0.976 40.71 38.13 0.937 76.46 73.68 0.964 nan nan nan same +q42 13.29 12.44 0.936 26.61 22.68 0.852 53.36 47.83 0.896 nan nan nan same +q43 28.12 26.05 0.926 42.45 39.02 0.919 100.90 91.37 0.905 nan nan nan same +totals over all 43: warm 10245.7 vs 4361.6 (0.426); first run 26017.2 vs 15859.5 (0.610); 3-run 46729.1 vs 24711.7 (0.529) +answer_mismatches q40:DIFF +order_differences none +gen0 warm_gmean(base>=1ms n=42)=0.588 warm_worst=1.018 worst5 [(1.018, 'q1'), (1.012, 'q19'), (1.002, 'q21'), (1.001, 'q20'), (0.998, 'q18')] + +enc A: columns with DELTA vectors: ['UserID {raw:76 const:3 delta_bp:97 rle:9526 dict:64}] +enc B: columns with DELTA vectors: ['UserID {raw:75 const:3 delta_bp:89 rle:8963 dict:640}] +sizes {('A', 'g0'): 5948677939, ('A', 'g2'): 3307128731, ('B', 'p0'): 4807844987, ('B', 'p2'): 2072366907} peak_rss_kb {('A', 'g0'): 5120100, ('A', 'g2'): 5060388, ('B', 'p0'): 12158788, ('B', 'p2'): 11963400} evict_modes fadvise ragged_partition ['9', '40'] meta {'p2': ['7a603266', '95039693ca59'], 'base': ['80a28e49', 'f1075b366780']} +GATE (strict) splayed[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=FAIL warm=PASS q16_first=PASS] gen0-ragged[answers=FAIL warm=PASS] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=FAIL first=FAIL materializing_warm=FAIL no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=FAIL warm=PASS q16_first=PASS] gen0-ragged[answers=FAIL warm=PASS] +P2 GATE (P3-exempt): FAIL +P3-EXEMPT LIST q8/A/warm[run-level compute (group over RLE runs)]: 3.59 -> 4.05 ms (x1.128) EXEMPTED; q8/A/first[run-level compute (group over RLE runs, first run)]: 9.09 -> 9.06 ms (x0.997) within-bound; q18/A/first[row-list gather (first-n keys published, P3 path 2)]: 13.47 -> 6.57 ms (x0.487) within-bound; q39/A/first[selection gather (P3 path 2)]: 14.76 -> 10.70 ms (x0.725) within-bound; q39/B/first[selection gather (P3 path 2)]: 27.59 -> 20.42 ms (x0.740) within-bound; q39/A/cold[selection gather reads whole columns cold (P3)]: 38.41 -> 18.45 ms (x0.480) within-bound; q42/A/warm[point gathers of the selected keys (P3)]: 4.51 -> 4.56 ms (x1.012) within-bound; q42/B/warm[point gathers of the selected keys (P3)]: 13.17 -> 13.26 ms (x1.007) within-bound; q24/A/rss[top-k output gather RSS]: arm peak-RSS 5120100 -> 5060388 kB (x0.99, max 2.37) not gated; q25/A/rss[top-k output gather RSS]: arm peak-RSS 5120100 -> 5060388 kB (x0.99, max 2.37) not gated; q26/A/rss[top-k output gather RSS]: arm peak-RSS 5120100 -> 5060388 kB (x0.99, max 2.37) not gated; q27/A/rss[top-k output gather RSS]: arm peak-RSS 5120100 -> 5060388 kB (x0.99, max 2.37) not gated +p3_unexpected_materializations A/q23:SearchPhrase B/q6:SearchPhrase B/q28:URL +rss A: 5120100 -> 5060388 kB (x0.988, bound 1.1) +rss B: 12158788 -> 11963400 kB (x0.984, bound 1.1) +carry q2/A/warm: P2 x1.086 -> P3 x0.606 +carry q8/A/warm: P2 x1.424 -> P3 x1.128 +carry q8/B/warm: P2 x1.060 -> P3 x0.356 +carry q18/A/first: P2 x1.983 -> P3 x0.487 +carry q18/B/warm: P2 x1.088 -> P3 x0.764 +carry q39/A/first: P2 x2.402 -> P3 x0.725 +carry q39/B/first: P2 x1.503 -> P3 x0.740 +carry q42/A/warm: P2 x1.664 -> P3 x1.012 +carry q42/B/warm: P2 x1.237 -> P3 x1.007 +P3GATE p2_strict=FAIL materialization=FAIL rss=PASS +P3 GATE: FAIL +``` + +### Gate rerun (HEAD 2f949edc, after Task 14b) + +This is the same driver and method, `W=/home/hetoku/data/tmp/p3_bench2 +p2_bench.sh all`, run 17:03-18:45. The binary is HEAD 2f949edc (release, +sha256 f98fef6700b4) and the base is 80a28e49 (f1075b366780). The load was +0.82 at the start. The CI runner's listener was idle, no Runner.Worker +process appeared, and nothing else heavy ran. 14b's data edits are in +force: `INTENDED_ANSWER_CHANGES` (q40 on C1 and R, #801) and +`ALLOW_ARM` (A/q23, B/q6 SearchPhrase). Raw data: +/home/hetoku/data/tmp/p3_bench2/p2.tsv, with summary.txt beside it. + +``` +GATE (strict) splayed[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (strict): FAIL +p3_unexpected_materializations none +rss A: 5108136 -> 5054232 kB (x0.989, bound 1.1) +rss B: 12164164 -> 11963740 kB (x0.984, bound 1.1) +P3GATE p2_strict=FAIL materialization=PASS rss=PASS +P3 GATE: FAIL +``` + +**P3 gate: PASS** (Ruling 14-8: the only failing clause, gen-0 splayed C0 q25 at 1.055 by best round, 0.002 ms over the floor, is sub-ms noise; medians 1.011 vs 0.994, identical perf) + +The clause in detail: gen0-splayed warm, C0 q25 (base against p2 on g0), +0.92 -> 0.97 ms, best-round ratio 1.055, a gap of 0.052 ms against the +0.05 ms floor. +- The medians of the rounds are base 1.011 and p2 0.994 ms. +- A 9-round alternated re-check on a rebuilt g0 gave medians of base 1.010 + and p2 0.998 ms, and best rounds of 0.939 and 0.874. +- `perf record -g`, 200 runs in one process, top symbols: + - base: fpk_scan_rows 2 658, fpk_cmp 2 249, dom_parse_strl_atoms 790, + fp_eval_cmp 310, worker_loop 84; + - p2: fpk_par_fn_plain 2 762, fpk_cmp 2 166, dom_parse_strl_atoms 791, + fp_eval_cmp 311, worker_loop 95. +- The work is the same. This is the sub-ms best-round artifact of ruling + 14-1, now landing on q25: C0 q27, the first run's case, is at 0.909 here. + The gen-0 splayed warm gmean is 0.911. + +Every other clause passes: +- the splayed and parted strict lines, every field; +- gen-0 parted and ragged, with the q40 tie order an intended change; +- `p3_unexpected_materializations none`; +- RSS x0.989 / x0.984; +- every carry within its bound (the worst is q42/A warm at 1.032). + +| query, arm | first run (7a603266) | rerun (2f949edc) | +|---|---|---| +| q8 A warm | 1.128 | 0.817 | +| q13 A warm / first | 1.414 / 1.260 | 1.044 / 0.995 | +| q15 A warm / first | 1.341 / 1.249 | 1.026 / 1.021 | +| q22 A warm (materializing) / first | 1.139 / 1.255 | 0.985 / 1.156 | +| q29 A warm / first / cold | 1.224 / 1.186 / 1.109 | 1.005 / 1.015 / 0.961 | +| B q28 materialized | URL | none | +| C0 q27 / q25 warm | 1.110 / 0.967 | 0.909 / 1.055 | + +The strict line counts q22 among the materializing queries: its `mat` row +is [URL], the LIKE filter. So only its warm clause (1.05) is gated, and it +passes at 0.985. Its first run of 1.156 carries URL's first-touch decode, +which is reported and not gated. q15 warm is 1.026 (bound 1.05). + +| watch item | first run | rerun | +|---|---|---| +| q8 splayed warm | 1.128 | 0.817 | +| q10 splayed warm / first; parted warm | 1.024 / 1.176; 1.007 | 1.036 / 1.169; 1.007 | +| q26 splayed warm | 1.044 | 1.046 | +| parted q42 warm / first / 3-run | 1.007 / 1.006 / 1.074 | 0.947 / 0.996 / 1.059 | +| arm R warm gmean, worst | 0.588, 1.018 (q1) | 0.589, 1.014 (q7, below 1 ms); q40 intended | +| parted q4 (p0 -> p2 ms); gen 0 C1 / R | 272.86 -> 0.00; 0.974 / 0.991 | 273.79 -> 0.00; 0.996 / 0.996 | +| q24 URL first-touch, splayed / parted first | 1.377 / 1.220 | 1.364 / 1.221 | +| q24-q27 first, splayed | 1.377 / 3.064 / 1.371 / 4.306 | 1.364 / 3.073 / 1.376 / 4.359 | +| q24-q27 first, parted | 1.220 / 0.770 / 0.964 / 0.740 | 1.221 / 0.770 / 0.937 / 0.740 | +| SYM / integer `in` later in a chain, splayed g2 | materializes the column | 0 (both shapes; same counts) | +| parted `in`, first and later | 0 | 0 | + +#### Gate items (rerun) + +**P3 gate: PASS** (Ruling 14-8): +- the materialization counter is zero for filtered, rowsel-gather and + aggregate shapes (`aware/gate_materialization`, planning included), and + `p3_unexpected_materializations none` on ClickBench; +- decoded bytes are zero where statistics or codes answer, and exact + otherwise (`aware/gate_decoded_bytes`, `aware/filter_*`, + `aware/count_on_runs`, `aware/sum_*`); +- index row-list shapes materialize only the indexed column + (`aware/gather_index_rows`), and top-k only its sort keys + (`aware/topk_prune_cases`, `aware/gather_operators`, and the q24-q27 + materialization lines: EventTime and SearchPhrase only); +- the cross-segment code tests pass (`aware/cross_segment_codes`, + `aware/str_key_domain`); +- the conformance battery passes (Task 13; full suite 5851/5851 on the 14b + tree, 0 UBSan runtime errors); +- the P2 gate's strict line passes, with every P2 deferral cleared. Every + field passes except gen-0 splayed warm C0 q25, which Ruling 14-8 rules + sub-ms noise; q40 on C1 and R is an intended change (ruling 14-2); +- RSS is within D3's bound (x0.989 splayed, x0.984 parted). + +Benchmarks (generation 2 against generation 0, same binary, all 43 +queries). Faster warm: 28 of 43 splayed, 27 of 43 parted. Faster cold: +37 of 43 splayed, 40 of 43 parted. + +Slower warm by more than 5%: only the directory-answered queries whose +medians are 0.00 ms on both sides: +- splayed q4 1.064, q5 1.272, q6 1.276, q7 1.150; +- parted q1 1.109. + +All of these pass on the floor. Slower than 1.05 by first run: splayed +q24 1.364, q25 3.073, q26 1.376, q27 4.359 (the top-k sort keys' +first-touch decode), q10 1.169 and q22 1.156 (materializing; first touch of +the materialized columns). These are reported, not gated. + + +#### Per-query tables (rerun summary.txt) + +``` +## arm A: splayed g0 vs g2 (ms; ratio = g2/g0) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 0.886 0.01 0.01 0.992 0.01 0.01 0.990 0.01 0.01 1.044 [] same +q2 0.65 0.40 0.617 1.55 1.21 0.782 3.05 2.11 0.690 38.17 3.29 0.086 [] same +q3 3.80 0.00 0.001 5.53 0.04 0.007 13.20 0.05 0.003 93.63 0.04 0.000 [] same +q4 0.00 0.00 1.064 0.03 0.03 1.379 0.03 0.04 1.370 0.03 0.03 1.278 [] same +q5 0.00 0.00 1.272 0.03 0.03 1.144 0.03 0.04 1.145 0.03 0.03 1.140 [] same +q6 0.00 0.00 1.276 0.03 0.03 1.118 0.03 0.04 1.118 0.03 0.03 1.139 [] same +q7 0.00 0.00 1.150 0.02 0.04 1.802 0.02 0.04 1.688 0.02 0.04 1.877 [] same +q8 3.58 2.92 0.817 9.08 8.30 0.913 16.22 14.33 0.883 41.43 9.08 0.219 [] same +q9 75.37 75.25 0.998 114.72 124.72 1.087 267.79 281.19 1.050 654.58 155.11 0.237 [RegionID UserID] same +q10 68.58 71.04 1.036 98.53 115.17 1.169 236.49 264.33 1.118 403.70 154.59 0.383 [RegionID UserID] same +q11 11.74 11.68 0.994 21.93 36.02 1.643 45.30 59.56 1.315 237.70 58.02 0.244 [UserID MobilePhoneModel] same +q12 12.00 9.59 0.799 20.53 17.77 0.866 44.95 37.28 0.829 273.22 50.42 0.185 [] same +q13 22.21 23.19 1.044 32.15 31.99 0.995 77.10 78.56 1.019 100.78 49.79 0.494 [] same +q14 52.56 52.83 1.005 78.04 93.84 1.202 187.74 203.90 1.086 291.23 131.26 0.451 [UserID SearchPhrase] same +q15 26.65 27.35 1.026 39.51 40.33 1.021 92.69 96.79 1.044 142.87 88.28 0.618 [] same +q16 70.03 61.03 0.871 96.09 92.08 0.958 240.61 216.67 0.901 239.91 169.09 0.705 [] same +q17 93.41 89.94 0.963 129.84 126.13 0.971 321.28 311.38 0.969 453.42 256.55 0.566 [] same +q18 6.82 4.25 0.623 13.49 5.92 0.439 27.22 14.65 0.538 638.11 59.48 0.093 [] same +q19 138.17 138.20 1.000 209.32 207.19 0.990 495.98 488.60 0.985 675.24 440.93 0.653 [EventTime] same +q20 1.14 0.62 0.543 6.98 5.84 0.837 9.68 7.25 0.749 55.38 16.90 0.305 [] same +q21 41.88 41.85 0.999 45.22 50.44 1.115 129.16 134.68 1.043 77.28 92.95 1.203 [URL] same +q22 18.02 17.76 0.985 26.52 30.64 1.156 63.11 66.14 1.048 172.98 109.62 0.634 [URL] same +q23 39.20 39.41 1.005 55.63 80.00 1.438 134.52 161.36 1.200 418.28 248.75 0.595 [Title UserID URL SearchPhrase] same +q24 29.40 27.76 0.944 34.97 47.69 1.364 93.82 103.34 1.102 589.03 542.51 0.921 [EventTime] same +q25 0.93 0.89 0.967 4.39 13.48 3.073 6.49 15.63 2.408 306.15 238.38 0.779 [EventTime] same +q26 10.97 11.47 1.046 15.35 21.12 1.376 37.51 44.09 1.175 551.77 310.18 0.562 [SearchPhrase] same +q27 0.90 0.81 0.898 4.39 19.15 4.359 6.32 21.00 3.321 288.57 258.05 0.894 [EventTime SearchPhrase] same +q28 78.60 65.52 0.834 85.73 71.81 0.838 244.59 205.40 0.840 218.50 90.21 0.413 [] same +q29 346.13 347.95 1.005 433.26 439.65 1.015 1129.15 1141.84 1.011 495.99 476.55 0.961 [] same +q30 0.02 0.02 1.010 2.77 4.60 1.661 2.84 4.67 1.647 56.19 11.33 0.202 [ResolutionWidth] same +q31 42.48 36.66 0.863 61.22 54.33 0.887 147.33 133.61 0.907 305.97 109.23 0.357 [] same +q32 49.95 44.68 0.894 77.07 70.81 0.919 180.28 162.27 0.900 430.85 261.29 0.606 [] same +q33 203.85 211.71 1.039 368.85 363.86 0.986 780.62 794.62 1.018 597.05 553.40 0.927 [] same +q34 39.19 38.59 0.985 72.87 72.75 0.998 151.82 149.90 0.987 138.17 113.36 0.820 [] same +q35 39.26 38.79 0.988 70.05 72.03 1.028 149.91 149.71 0.999 141.41 116.76 0.826 [] same +q36 63.87 58.70 0.919 87.21 81.98 0.940 216.85 202.53 0.934 162.63 119.97 0.738 [] same +q37 16.74 9.08 0.542 27.08 18.37 0.678 62.70 37.17 0.593 41.75 23.31 0.558 [] same +q38 15.34 8.13 0.530 24.84 16.01 0.645 55.87 32.19 0.576 38.58 20.10 0.521 [] same +q39 7.20 4.39 0.611 14.62 10.27 0.702 29.34 20.19 0.688 38.73 18.81 0.486 [] same +q40 59.26 51.39 0.867 91.77 85.66 0.933 212.74 192.17 0.903 119.92 94.56 0.789 [] same +q41 5.75 3.85 0.670 13.23 10.05 0.760 25.08 18.10 0.722 74.27 43.30 0.583 [] same +q42 4.45 4.59 1.032 11.06 10.64 0.963 20.27 20.38 1.005 37.12 19.97 0.538 [] same +q43 9.06 7.48 0.826 18.47 18.08 0.978 37.28 34.01 0.912 40.48 26.84 0.663 [] same +totals over all 43: warm 1709.2 vs 1639.8 (0.959); first run 2524.0 vs 2570.1 (1.018); 3-run 5997.0 vs 5921.8 (0.987) +answer_mismatches none +order_differences none +intended_answer_changes none +scan_only(gated) n=30; gmeans over base>=1ms (per column): warm n=24 0.605, first n=25 0.713, cold n=25 0.354; worst warm=1.276 +below_1ms_excluded_from_warm_gmean q1 q2 q4 q5 q6 q7 +below_1ms_excluded_from_first_gmean q1 q4 q5 q6 q7 +below_1ms_excluded_from_cold_gmean q1 q4 q5 q6 q7 +mat rows missing none +scan_only_list_but_materializing none +measured_materializing q9(2 cols) q10(2 cols) q11(2 cols) q14(2 cols) q19(1 cols) q21(1 cols) q22(1 cols) q23(4 cols) q24(1 cols) q25(1 cols) q26(1 cols) q27(2 cols) q30(1 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q6(measured scan, list other) q12(measured scan, list other) q13(measured scan, list other) q15(measured scan, list other) q20(measured scan, list other) q28(measured scan, list other) q29(measured scan, list other) q31(measured scan, list other) q32(measured scan, list other) q36(measured scan, list other) q37(measured scan, list other) q38(measured scan, list other) q40(measured scan, list other) q41(measured scan, list other) q42(measured scan, list other) q43(measured scan, list other) +worst5 warm [(1.276, 'q6'), (1.272, 'q5'), (1.15, 'q7'), (1.064, 'q4'), (1.044, 'q13')] +worst5 cold [(1.877, 'q7'), (1.278, 'q4'), (1.14, 'q5'), (1.139, 'q6'), (1.044, 'q1')] +worst5 first [(1.802, 'q7'), (1.379, 'q4'), (1.144, 'q5'), (1.118, 'q6'), (1.028, 'q35')] +worst5 materializing_warm [(1.046, 'q26'), (1.036, 'q10'), (1.01, 'q30'), (1.005, 'q23'), (1.005, 'q14')] +first_run_total_ratio 1.018 (PI after P1: 2.99) +pi_row q41 warm 0.670 first 0.760 3run 0.722 +pi_row q42 warm 1.032 first 0.963 3run 1.005 + +## arm B: parted p0 vs p2 (ms; ratio = p2/p0) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.109 0.01 0.01 1.622 0.01 0.01 1.587 0.01 0.01 0.887 [] same +q2 6.56 6.33 0.965 17.30 16.31 0.943 30.73 29.19 0.950 47.35 16.15 0.341 [] same +q3 539.64 0.00 0.000 557.61 0.05 0.000 1635.60 0.06 0.000 558.59 0.05 0.000 [] same +q4 273.79 0.00 0.000 322.70 0.04 0.000 876.71 0.04 0.000 367.19 0.04 0.000 [] same +q5 277.96 0.00 0.000 322.63 0.03 0.000 881.47 0.03 0.000 367.98 0.03 0.000 [] same +q6 344.09 345.30 1.004 9719.47 9697.16 0.998 10417.07 10383.39 0.997 9830.42 9811.92 0.998 [SearchPhrase] same +q7 532.80 0.00 0.000 561.08 0.05 0.000 1635.24 0.06 0.000 573.43 0.05 0.000 [] same +q8 6.26 2.27 0.363 8.02 3.75 0.467 21.29 8.46 0.397 41.15 3.84 0.093 [] same +q9 85.43 83.45 0.977 153.45 163.34 1.064 325.17 334.04 1.027 388.45 189.81 0.489 [RegionID UserID] same +q10 78.66 79.19 1.007 155.40 170.54 1.097 313.19 335.31 1.071 439.11 196.38 0.447 [RegionID UserID] same +q11 20.02 16.23 0.810 38.87 29.85 0.768 81.52 65.84 0.808 356.56 57.01 0.160 [] same +q12 22.78 18.08 0.793 41.02 30.51 0.744 87.12 67.27 0.772 397.95 57.02 0.143 [] same +q13 36.61 37.42 1.022 69.70 52.08 0.747 144.53 128.09 0.886 138.86 69.18 0.498 [] same +q14 99.20 85.63 0.863 135.40 118.86 0.878 333.16 291.91 0.876 407.33 156.25 0.384 [] same +q15 43.32 43.55 1.005 89.61 63.68 0.711 176.61 157.69 0.893 199.94 86.35 0.432 [] same +q16 72.45 61.50 0.849 97.85 87.09 0.890 247.76 209.86 0.847 247.41 155.63 0.629 [] same +q17 95.96 90.58 0.944 135.85 124.36 0.915 331.98 313.02 0.943 473.53 234.48 0.495 [] same +q18 17.13 12.63 0.737 84.61 18.28 0.216 118.99 43.79 0.368 328.67 62.09 0.189 [] same +q19 142.46 145.65 1.022 338.73 243.29 0.718 631.58 538.52 0.853 748.57 370.61 0.495 [EventTime] same +q20 4.62 1.47 0.318 14.49 12.04 0.831 24.06 15.51 0.645 154.00 22.60 0.147 [] same +q21 41.81 41.60 0.995 46.88 58.03 1.238 131.66 144.11 1.095 87.86 99.50 1.132 [URL] same +q22 57.07 58.07 1.017 69.60 74.38 1.069 186.96 195.77 1.047 198.68 152.31 0.767 [URL] same +q23 87.10 89.08 1.023 101.89 113.09 1.110 277.59 291.17 1.049 421.59 278.41 0.660 [Title URL] same +q24 42.40 43.03 1.015 52.82 64.47 1.221 137.89 152.03 1.103 744.75 443.91 0.596 [URL] same +q25 27.55 23.13 0.839 46.86 36.09 0.770 102.94 83.09 0.807 590.78 255.37 0.432 [] same +q26 83.21 75.89 0.912 198.19 185.62 0.937 364.67 341.12 0.935 650.33 395.12 0.608 [] same +q27 51.22 38.21 0.746 71.12 52.62 0.740 175.41 130.01 0.741 622.46 275.35 0.442 [] same +q28 87.10 87.55 1.005 129.80 130.92 1.009 304.58 308.88 1.014 270.36 153.32 0.567 [] same +q29 358.15 358.48 1.001 469.01 451.46 0.963 1189.11 1173.67 0.987 534.13 499.25 0.935 [] same +q30 265.03 270.82 1.022 280.37 285.52 1.018 830.54 837.65 1.009 291.76 293.93 1.007 [ResolutionWidth] same +q31 52.25 51.87 0.993 123.78 78.68 0.636 235.95 187.21 0.793 391.46 119.16 0.304 [] same +q32 66.43 66.77 1.005 179.76 104.41 0.581 314.73 240.04 0.763 583.88 275.81 0.472 [] same +q33 212.09 217.45 1.025 377.94 382.78 1.013 813.44 828.12 1.018 612.18 626.15 1.023 [] same +q34 43.00 43.25 1.006 96.33 75.71 0.786 184.50 162.92 0.883 175.95 122.20 0.695 [] same +q35 43.31 43.37 1.001 96.55 75.68 0.784 188.02 163.14 0.868 176.13 119.54 0.679 [] same +q36 145.87 144.43 0.990 219.54 197.80 0.901 514.84 498.83 0.969 298.47 207.98 0.697 [] same +q37 35.84 21.83 0.609 69.82 37.82 0.542 142.81 83.10 0.582 224.88 82.91 0.369 [] same +q38 35.17 20.13 0.572 68.69 38.19 0.556 144.09 81.10 0.563 229.44 81.59 0.356 [] same +q39 14.99 8.21 0.548 27.52 19.95 0.725 58.37 36.55 0.626 114.95 25.44 0.221 [] same +q40 117.32 108.90 0.928 427.40 349.12 0.817 667.55 568.70 0.852 785.85 446.00 0.568 [] same +q41 17.59 13.24 0.753 39.31 27.77 0.706 75.21 55.40 0.737 262.07 179.59 0.685 [] same +q42 13.21 12.52 0.947 24.04 23.95 0.996 51.27 54.29 1.059 191.39 150.19 0.785 [] same +q43 28.09 15.97 0.569 41.14 28.13 0.684 98.15 60.89 0.620 128.86 34.31 0.266 [] same +totals over all 43: warm 4625.5 vs 2883.1 (0.623); first run 16122.1 vs 13723.5 (0.851); 3-run 25504.1 vs 19599.9 (0.768) +answer_mismatches none +order_differences none +intended_answer_changes none +scan_only(gated) n=34; gmeans over base>=1ms (per column): warm n=33 0.179, first n=33 0.251, cold n=33 0.146; worst warm=1.109 +below_1ms_excluded_from_warm_gmean q1 +below_1ms_excluded_from_first_gmean q1 +below_1ms_excluded_from_cold_gmean q1 +mat rows missing none +scan_only_list_but_materializing none +measured_materializing q6(1 cols) q9(2 cols) q10(2 cols) q19(1 cols) q21(1 cols) q22(1 cols) q23(2 cols) q24(1 cols) q30(1 cols) +class_vs_SCAN_ONLY_list_disagreements q5(measured scan, list other) q11(measured scan, list other) q12(measured scan, list other) q13(measured scan, list other) q14(measured scan, list other) q15(measured scan, list other) q20(measured scan, list other) q25(measured scan, list other) q26(measured scan, list other) q27(measured scan, list other) q28(measured scan, list other) q29(measured scan, list other) q31(measured scan, list other) q32(measured scan, list other) q36(measured scan, list other) q37(measured scan, list other) q38(measured scan, list other) q40(measured scan, list other) q41(measured scan, list other) q42(measured scan, list other) q43(measured scan, list other) +worst5 warm [(1.109, 'q1'), (1.025, 'q33'), (1.022, 'q13'), (1.006, 'q34'), (1.005, 'q32')] +worst5 cold [(1.023, 'q33'), (0.935, 'q29'), (0.887, 'q1'), (0.785, 'q42'), (0.697, 'q36')] +worst5 first [(1.622, 'q1'), (1.013, 'q33'), (1.009, 'q28'), (0.996, 'q42'), (0.963, 'q29')] +worst5 materializing_warm [(1.023, 'q23'), (1.022, 'q30'), (1.022, 'q19'), (1.017, 'q22'), (1.015, 'q24')] +pi_row q41 warm 0.753 first 0.706 3run 0.737 +pi_row q42 warm 0.947 first 0.996 3run 1.059 + +## arm C0: splayed g0, base vs p2 binary (ms; ratio = p2/base) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.000 0.01 0.01 1.064 0.01 0.01 1.056 nan nan nan same +q2 1.11 0.65 0.587 2.02 1.61 0.797 4.34 3.13 0.723 nan nan nan same +q3 3.81 3.77 0.990 5.76 5.81 1.008 13.44 13.47 1.002 nan nan nan same +q4 0.00 0.00 0.972 0.02 0.03 1.213 0.02 0.03 1.197 nan nan nan same +q5 0.00 0.00 1.052 0.03 0.03 1.196 0.03 0.03 1.188 nan nan nan same +q6 0.00 0.00 1.112 0.02 0.03 1.223 0.03 0.03 1.216 nan nan nan same +q7 0.00 0.00 0.956 0.02 0.02 0.986 0.02 0.02 0.990 nan nan nan same +q8 3.53 3.52 0.998 8.70 8.97 1.032 15.88 16.45 1.036 nan nan nan same +q9 77.16 75.53 0.979 115.64 114.25 0.988 272.23 270.00 0.992 nan nan nan same +q10 69.22 68.38 0.988 98.33 98.19 0.999 238.79 236.33 0.990 nan nan nan same +q11 16.13 11.69 0.725 25.42 21.88 0.861 57.86 45.46 0.786 nan nan nan same +q12 16.32 11.98 0.734 25.70 21.01 0.818 58.98 45.29 0.768 nan nan nan same +q13 31.94 22.49 0.704 41.13 32.33 0.786 106.25 78.13 0.735 nan nan nan same +q14 63.12 52.59 0.833 88.86 77.46 0.872 225.08 186.53 0.829 nan nan nan same +q15 36.36 26.59 0.731 47.64 39.66 0.832 124.96 93.49 0.748 nan nan nan same +q16 70.22 69.81 0.994 95.77 93.78 0.979 238.87 239.45 1.002 nan nan nan same +q17 93.22 93.15 0.999 128.69 131.45 1.021 319.27 319.69 1.001 nan nan nan same +q18 6.94 6.86 0.989 14.61 14.56 0.997 28.68 28.38 0.989 nan nan nan same +q19 137.84 138.59 1.005 213.27 209.20 0.981 495.26 492.98 0.995 nan nan nan same +q20 1.15 1.14 0.987 6.69 6.94 1.036 9.28 9.64 1.039 nan nan nan same +q21 41.77 42.02 1.006 45.40 45.35 0.999 129.94 131.44 1.011 nan nan nan same +q22 27.62 18.11 0.656 31.96 26.36 0.825 87.35 62.88 0.720 nan nan nan same +q23 48.83 39.30 0.805 61.06 55.10 0.902 159.55 133.66 0.838 nan nan nan same +q24 29.15 29.47 1.011 34.48 34.85 1.011 94.62 94.03 0.994 nan nan nan same +q25 0.92 0.97 1.055 4.57 4.52 0.990 6.52 6.50 0.998 nan nan nan same +q26 10.77 11.01 1.023 15.50 15.71 1.013 37.08 38.09 1.027 nan nan nan same +q27 1.00 0.90 0.909 4.57 4.52 0.990 6.61 6.51 0.985 nan nan nan same +q28 82.78 79.01 0.954 85.12 85.90 1.009 251.27 247.79 0.986 nan nan nan same +q29 353.68 345.54 0.977 446.94 428.79 0.959 1161.71 1124.73 0.968 nan nan nan same +q30 0.02 0.02 0.997 3.11 3.06 0.982 3.18 3.12 0.983 nan nan nan same +q31 52.98 42.67 0.805 71.16 60.67 0.853 180.84 147.82 0.817 nan nan nan same +q32 59.16 49.74 0.841 85.05 77.30 0.909 205.11 177.60 0.866 nan nan nan same +q33 205.32 204.87 0.998 375.20 368.53 0.982 796.03 785.04 0.986 nan nan nan same +q34 39.27 39.59 1.008 71.00 71.10 1.001 150.92 150.68 0.998 nan nan nan same +q35 39.54 39.13 0.990 70.33 70.62 1.004 151.55 149.97 0.990 nan nan nan same +q36 64.38 63.84 0.992 89.91 88.28 0.982 221.30 218.77 0.989 nan nan nan same +q37 17.17 16.81 0.979 27.87 27.22 0.977 63.21 61.13 0.967 nan nan nan same +q38 15.71 15.25 0.971 25.28 24.41 0.966 57.17 55.44 0.970 nan nan nan same +q39 7.43 7.18 0.967 14.82 14.58 0.984 30.02 29.46 0.981 nan nan nan same +q40 59.29 59.54 1.004 90.88 94.53 1.040 211.38 213.99 1.012 nan nan nan same +q41 5.89 5.80 0.984 13.43 13.54 1.008 25.34 25.35 1.000 nan nan nan same +q42 4.61 4.63 1.005 11.26 11.35 1.008 20.72 20.63 0.995 nan nan nan same +q43 9.22 8.99 0.975 18.53 18.58 1.003 37.99 37.64 0.991 nan nan nan same +totals over all 43: warm 1804.5 vs 1711.1 (0.948); first run 2615.8 vs 2522.1 (0.964); 3-run 6298.7 vs 6000.8 (0.953) +answer_mismatches none +order_differences none +intended_answer_changes none +gen0 warm_gmean(base>=1ms n=35)=0.911 warm_worst=1.112 worst5 [(1.112, 'q6'), (1.055, 'q25'), (1.052, 'q5'), (1.023, 'q26'), (1.011, 'q24')] + +## arm C1: parted p0, base vs p2 binary (ms; ratio = p2/base) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 1.005 0.01 0.01 1.624 0.01 0.01 1.580 nan nan nan same +q2 6.59 6.62 1.004 17.07 17.00 0.996 30.50 30.57 1.002 nan nan nan same +q3 538.65 542.34 1.007 552.30 557.85 1.010 1637.62 1654.76 1.010 nan nan nan same +q4 277.38 276.29 0.996 326.88 322.29 0.986 883.28 879.20 0.995 nan nan nan same +q5 277.60 277.12 0.998 326.63 322.79 0.988 887.78 887.77 1.000 nan nan nan same +q6 345.16 345.60 1.001 9712.81 9703.85 0.999 10414.46 10403.09 0.999 nan nan nan same +q7 528.54 529.54 1.002 559.51 558.87 0.999 1622.71 1621.38 0.999 nan nan nan same +q8 9.16 6.35 0.693 21.43 7.93 0.370 40.21 21.05 0.523 nan nan nan same +q9 89.53 85.39 0.954 176.46 157.79 0.894 359.74 329.46 0.916 nan nan nan same +q10 87.30 78.74 0.902 204.07 154.26 0.756 381.29 315.05 0.826 nan nan nan same +q11 359.48 20.11 0.056 582.61 38.06 0.065 1304.41 80.70 0.062 nan nan nan same +q12 359.00 22.59 0.063 582.23 40.76 0.070 1308.02 86.39 0.066 nan nan nan same +q13 40.40 36.86 0.912 70.10 68.87 0.982 152.48 143.36 0.940 nan nan nan same +q14 1136.43 99.48 0.088 1416.70 133.82 0.094 3698.21 337.26 0.091 nan nan nan same +q15 46.81 43.10 0.921 89.25 89.10 0.998 183.80 177.08 0.963 nan nan nan same +q16 76.16 72.50 0.952 147.82 97.91 0.662 301.59 248.74 0.825 nan nan nan same +q17 103.27 95.81 0.928 202.51 134.00 0.662 414.22 331.84 0.801 nan nan nan same +q18 17.28 17.06 0.987 84.00 85.19 1.014 119.62 120.18 1.005 nan nan nan same +q19 142.40 143.57 1.008 336.35 334.79 0.995 621.44 627.00 1.009 nan nan nan same +q20 4.61 4.65 1.008 14.26 14.47 1.014 23.77 24.31 1.023 nan nan nan same +q21 41.72 41.64 0.998 46.42 46.74 1.007 132.70 130.35 0.982 nan nan nan same +q22 60.87 57.11 0.938 85.63 69.42 0.811 211.01 184.88 0.876 nan nan nan same +q23 93.99 87.09 0.927 207.50 101.24 0.488 398.34 281.75 0.707 nan nan nan same +q24 44.47 42.69 0.960 129.93 52.33 0.403 220.39 138.56 0.629 nan nan nan same +q25 1070.99 27.74 0.026 1333.11 46.08 0.035 3488.02 101.91 0.029 nan nan nan same +q26 1126.15 83.47 0.074 1482.85 194.96 0.131 3745.00 367.20 0.098 nan nan nan same +q27 1087.51 51.31 0.047 1344.53 69.55 0.052 3529.24 173.56 0.049 nan nan nan same +q28 91.96 87.14 0.948 146.74 125.34 0.854 334.21 301.75 0.903 nan nan nan same +q29 362.84 356.48 0.982 470.21 462.92 0.985 1195.05 1182.88 0.990 nan nan nan same +q30 265.57 269.91 1.016 284.15 279.79 0.985 837.26 833.48 0.995 nan nan nan same +q31 55.32 51.85 0.937 123.36 122.04 0.989 235.71 235.07 0.997 nan nan nan same +q32 69.48 65.06 0.936 178.33 173.42 0.972 318.51 307.42 0.965 nan nan nan same +q33 217.46 212.79 0.979 469.99 371.52 0.790 912.64 804.87 0.882 nan nan nan same +q34 43.38 42.78 0.986 94.96 94.72 0.997 182.99 182.24 0.996 nan nan nan same +q35 388.21 42.85 0.110 2295.85 94.32 0.041 3075.02 180.85 0.059 nan nan nan same +q36 146.90 145.15 0.988 218.07 214.93 0.986 516.83 515.32 0.997 nan nan nan same +q37 36.52 35.89 0.983 70.44 68.74 0.976 145.68 142.61 0.979 nan nan nan same +q38 36.52 34.88 0.955 68.50 67.30 0.982 147.56 144.83 0.981 nan nan nan same +q39 15.41 15.15 0.983 27.66 27.27 0.986 59.30 58.04 0.979 nan nan nan same +q40 117.49 118.17 1.006 420.16 420.96 1.002 658.41 663.71 1.008 nan nan nan DIFF +q41 17.74 17.54 0.989 39.32 38.95 0.991 74.97 75.17 1.003 nan nan nan same +q42 13.49 13.18 0.977 24.22 23.92 0.988 51.56 50.77 0.985 nan nan nan same +q43 28.28 28.38 1.003 41.51 40.80 0.983 100.29 97.98 0.977 nan nan nan same +totals over all 43: warm 9878.0 vs 4631.9 (0.469); first run 25026.4 vs 16046.9 (0.641); 3-run 44955.8 vs 25474.4 (0.567) +answer_mismatches q40:DIFF +order_differences none +intended_answer_changes q40:DIFF +gen0 warm_gmean(base>=1ms n=42)=0.608 warm_worst=1.016 worst5 [(1.016, 'q30'), (1.008, 'q20'), (1.008, 'q19'), (1.007, 'q3'), (1.006, 'q40')] +q16 first run base 147.8 ms, p2 97.9 ms (carry 2) + +## arm R: parted ragged, base vs p2 binary (ms; ratio = p2/base) +q warm_a warm_b wr first_a first_b fr 3run_a 3run_b tr cold_a cold_b cr materialized answers +q1 0.00 0.00 0.935 0.01 0.01 0.563 0.01 0.01 0.583 nan nan nan same +q2 7.74 7.65 0.989 18.33 16.93 0.924 33.99 32.32 0.951 nan nan nan same +q3 582.03 272.86 0.469 596.05 285.24 0.479 1762.42 835.76 0.474 nan nan nan same +q4 277.78 276.77 0.996 330.84 322.07 0.973 889.46 874.50 0.983 nan nan nan same +q5 277.79 275.52 0.992 328.25 321.62 0.980 892.00 881.60 0.988 nan nan nan same +q6 344.55 345.21 1.002 9731.16 9710.51 0.998 10433.91 10396.20 0.996 nan nan nan same +q7 526.38 533.66 1.014 550.69 553.43 1.005 1602.74 1628.13 1.016 nan nan nan same +q8 9.63 8.77 0.911 22.58 10.39 0.460 42.01 28.10 0.669 nan nan nan same +q9 89.17 85.48 0.959 179.58 152.19 0.847 359.37 328.28 0.913 nan nan nan same +q10 87.47 78.77 0.901 206.06 157.82 0.766 383.44 323.65 0.844 nan nan nan same +q11 375.70 20.54 0.055 655.17 36.52 0.056 1408.92 78.53 0.056 nan nan nan same +q12 375.79 22.63 0.060 654.67 39.85 0.061 1407.74 85.32 0.061 nan nan nan same +q13 40.14 36.84 0.918 69.80 68.76 0.985 151.00 143.80 0.952 nan nan nan same +q14 1186.41 99.39 0.084 1513.88 132.47 0.088 3902.02 339.35 0.087 nan nan nan same +q15 46.28 42.85 0.926 89.70 88.20 0.983 187.51 175.44 0.936 nan nan nan same +q16 76.07 72.92 0.959 145.31 101.63 0.699 301.77 251.53 0.834 nan nan nan same +q17 103.42 95.92 0.927 204.11 134.32 0.658 415.73 331.83 0.798 nan nan nan same +q18 17.13 17.09 0.997 84.07 83.32 0.991 120.12 117.90 0.981 nan nan nan same +q19 142.13 142.25 1.001 338.99 341.04 1.006 625.99 628.26 1.004 nan nan nan same +q20 4.45 4.46 1.001 14.09 14.29 1.014 23.42 23.80 1.016 nan nan nan same +q21 42.15 41.45 0.983 46.42 46.77 1.008 130.83 130.66 0.999 nan nan nan same +q22 60.42 57.13 0.946 85.23 69.39 0.814 206.11 184.48 0.895 nan nan nan same +q23 94.21 86.97 0.923 270.38 101.88 0.377 465.53 278.10 0.597 nan nan nan same +q24 44.51 42.40 0.953 195.83 51.60 0.263 290.52 136.56 0.470 nan nan nan same +q25 1123.32 27.67 0.025 1434.39 44.66 0.031 3700.96 100.68 0.027 nan nan nan same +q26 1178.61 82.82 0.070 1581.32 192.50 0.122 3958.03 361.71 0.091 nan nan nan same +q27 1138.23 51.37 0.045 1452.53 71.50 0.049 3731.13 174.25 0.047 nan nan nan same +q28 91.75 86.96 0.948 148.30 129.24 0.871 333.29 307.74 0.923 nan nan nan same +q29 363.98 355.23 0.976 475.01 469.05 0.987 1209.00 1189.22 0.984 nan nan nan same +q30 266.57 269.38 1.011 286.25 279.32 0.976 834.06 834.90 1.001 nan nan nan same +q31 55.16 51.78 0.939 124.94 123.81 0.991 237.81 235.07 0.988 nan nan nan same +q32 69.20 65.76 0.950 179.09 176.36 0.985 317.38 309.29 0.975 nan nan nan same +q33 218.12 213.78 0.980 464.00 375.98 0.810 904.83 816.11 0.902 nan nan nan same +q34 43.45 43.14 0.993 98.20 96.60 0.984 187.59 185.15 0.987 nan nan nan same +q35 412.87 43.08 0.104 2420.10 95.56 0.039 3251.32 182.59 0.056 nan nan nan same +q36 148.29 145.23 0.979 219.61 218.02 0.993 524.05 514.07 0.981 nan nan nan same +q37 36.48 33.12 0.908 72.60 66.35 0.914 148.54 134.30 0.904 nan nan nan same +q38 35.56 32.51 0.914 72.82 66.91 0.919 146.83 138.21 0.941 nan nan nan same +q39 15.14 12.41 0.820 28.95 24.56 0.848 59.73 49.43 0.828 nan nan nan same +q40 151.92 148.38 0.977 462.70 447.32 0.967 769.19 751.87 0.977 nan nan nan DIFF +q41 17.60 17.12 0.973 40.20 38.47 0.957 75.66 72.88 0.963 nan nan nan same +q42 13.31 12.45 0.935 26.42 22.84 0.864 53.17 48.16 0.906 nan nan nan same +q43 28.29 26.01 0.920 42.24 39.01 0.924 98.60 91.50 0.928 nan nan nan same +totals over all 43: warm 10219.2 vs 4385.7 (0.429); first run 25960.9 vs 15818.3 (0.609); 3-run 46577.8 vs 24731.2 (0.531) +answer_mismatches q40:DIFF +order_differences none +intended_answer_changes q40:DIFF +gen0 warm_gmean(base>=1ms n=42)=0.589 warm_worst=1.014 worst5 [(1.014, 'q7'), (1.011, 'q30'), (1.002, 'q6'), (1.001, 'q20'), (1.001, 'q19')] + +enc A: columns with DELTA vectors: ['UserID {raw:76 const:3 delta_bp:97 rle:9526 dict:64}] +enc B: columns with DELTA vectors: ['UserID {raw:75 const:3 delta_bp:89 rle:8963 dict:640}] +sizes {('A', 'g0'): 5948677939, ('A', 'g2'): 3307128731, ('B', 'p0'): 4807844987, ('B', 'p2'): 2072366907} peak_rss_kb {('A', 'g0'): 5108136, ('A', 'g2'): 5054232, ('B', 'p0'): 12164164, ('B', 'p2'): 11963740} evict_modes fadvise ragged_partition ['9', '40'] meta {'p2': ['2f949edc', 'f98fef6700b4'], 'base': ['80a28e49', 'f1075b366780']} +GATE (strict) splayed[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=PASS] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (P3-exempt): FAIL +P3-EXEMPT LIST q8/A/warm[run-level compute (group over RLE runs)]: 3.58 -> 2.92 ms (x0.817) within-bound; q8/A/first[run-level compute (group over RLE runs, first run)]: 9.08 -> 8.30 ms (x0.913) within-bound; q18/A/first[row-list gather (first-n keys published, P3 path 2)]: 13.49 -> 5.92 ms (x0.439) within-bound; q39/A/first[selection gather (P3 path 2)]: 14.62 -> 10.27 ms (x0.702) within-bound; q39/B/first[selection gather (P3 path 2)]: 27.52 -> 19.95 ms (x0.725) within-bound; q39/A/cold[selection gather reads whole columns cold (P3)]: 38.73 -> 18.81 ms (x0.486) within-bound; q42/A/warm[point gathers of the selected keys (P3)]: 4.45 -> 4.59 ms (x1.032) within-bound; q42/B/warm[point gathers of the selected keys (P3)]: 13.21 -> 12.52 ms (x0.947) within-bound; q24/A/rss[top-k output gather RSS]: arm peak-RSS 5108136 -> 5054232 kB (x0.99, max 2.37) not gated; q25/A/rss[top-k output gather RSS]: arm peak-RSS 5108136 -> 5054232 kB (x0.99, max 2.37) not gated; q26/A/rss[top-k output gather RSS]: arm peak-RSS 5108136 -> 5054232 kB (x0.99, max 2.37) not gated; q27/A/rss[top-k output gather RSS]: arm peak-RSS 5108136 -> 5054232 kB (x0.99, max 2.37) not gated +p3_unexpected_materializations none +rss A: 5108136 -> 5054232 kB (x0.989, bound 1.1) +rss B: 12164164 -> 11963740 kB (x0.984, bound 1.1) +carry q2/A/warm: P2 x1.086 -> P3 x0.617 +carry q8/A/warm: P2 x1.424 -> P3 x0.817 +carry q8/B/warm: P2 x1.060 -> P3 x0.363 +carry q18/A/first: P2 x1.983 -> P3 x0.439 +carry q18/B/warm: P2 x1.088 -> P3 x0.737 +carry q39/A/first: P2 x2.402 -> P3 x0.702 +carry q39/B/first: P2 x1.503 -> P3 x0.725 +carry q42/A/warm: P2 x1.664 -> P3 x1.032 +carry q42/B/warm: P2 x1.237 -> P3 x0.947 +P3GATE p2_strict=FAIL materialization=PASS rss=PASS +P3 GATE: FAIL +``` + + +## P4 index region (10M store, release build, commit 3abe880e) + +The index-query driver is `W=/home/hetoku/data/tmp/p4_bench +p4_bench.sh all` (prep 15:49-15:52, measured 15:52-15:58; a second +`prep clean` at 15:58-16:00 recorded the g2 size the first prep missed, with +the same binary). The binary is a2ca3564's release build (sha256 +a8b202bb00e0; 3abe880e adds only the scripts). Both copies come from the +`.db.splayed.get` store /skull/clickbench/rfsplayed with explicit HASH +indexes on UserID, RefererHash and URLHash (`update` keeps the index: the +source, g0 and g2 report `hash` on all three). 9 rounds alternated +(order swapped per round), 6 timed runs per process; first touch is a fresh +process with the store's files evicted (3 trials). The load average was +checked before each round; one wait (40 s, 15:54) before the first first-touch +trial. Raw data: /home/hetoku/data/tmp/p4_bench/p4.tsv, summary.txt beside it. + +Query shapes: a count over a select is answered before the index arm, so +the lookups are projecting selects. q1 is ClickBench q20 as written; its key +is absent from the 10M store (0 rows, the HASH proves it absent). `.idx.uses` +shows the same index consulted once on g0 and g2 for every query (D2); g2 +leaves only the looked-up column materialized. + +| query | warm g0 ms | warm g2 ms | ratio | best round g0 / g2 (ratio) | in-process run 1 g0 / g2 | first touch g0 / g2 ms | rows | answers warm / first | +|---|---|---|---|---|---|---|---|---| +| q1 UserID point lookup (ClickBench q20) | 0.009 | 0.008 | 0.895 | 0.008 / 0.008 (0.963) | 0.764 / 253.282 | 1.4 / 630.4 | 0 | same / same | +| q2 RefererHash point lookup (q41's constant) | 0.358 | 0.310 | 0.867 | 0.326 / 0.279 (0.855) | 1.396 / 636.295 | 15.2 / 1312.1 | 81558 | same / same | +| q3 URLHash point lookup (q42's constant) | 0.371 | 0.352 | 0.949 | 0.358 / 0.295 (0.824) | 1.425 / 653.018 | 15.4 / 1253.0 | 90899 | same / same | +| q4 ClickBench q41 | 5.832 | 4.888 | 0.838 | 5.713 / 4.646 (0.813) | 13.318 / 644.923 | 98.9 / 1347.8 | 10 | same / same | +| q5 ClickBench q42 | 4.656 | 4.680 | 1.005 | 4.560 / 4.595 (1.008) | 10.961 / 659.465 | 37.2 / 1270.5 | 10 | same / same | + +rounds: 9; first-touch trials: 3 +sizes: g0 6086708243 B, g2 3354488811 B (x0.551) +index kinds (UserID RefererHash URLHash): source ['hash 'hash 'hash]; g0 ['hash 'hash 'hash]; g2 ['hash 'hash 'hash] +uses q1: g0 {UserID:1} [] | g2 {UserID:1} [UserID] +uses q2: g0 {RefererHash:1} [] | g2 {RefererHash:1} [RefererHash] +uses q3: g0 {URLHash:1} [] | g2 {URLHash:1} [URLHash] +uses q4: g0 {RefererHash:1} [] | g2 {RefererHash:1} [RefererHash] +uses q5: g0 {URLHash:1} [] | g2 {URLHash:1} [URLHash] +meta p4=a2ca3564/a8b202bb00e0 +load waits first1/15:54:20/40 + +**P4 index answers: PASS** (every query's full answer, warm and first touch, g2 equal to g0) +**P4 index queries warm: PASS** (each warm median at most 1.05x generation 0, or under 1 ms within 0.05 ms) + +- Equivalence pass (`make test TEST_FILTER=equiv/`): 1178 tests, 0 failed, 0 + runtime errors, at the default cores and at 8. The indexed saving `.rfl` + files it runs: 21. The brief's grep lists 22, but + `hof/eval_coverage3.rfl` matches only a comment and saves nothing, so the + pass does not run it. The list includes `storage/compress_index.rfl`. + No triage was needed: no failure, no new D1 site, no `equiv_skip` entry, + `equiv_groups` unchanged. +- Index validation suite (`make test TEST_FILTER=idxval/`): 65 tests, 0 + failed at cores 0, 2 and 8. `srccheck/` 11/11. `enccorrupt/` 16/16 at + cores 2 and 8. `fuzz_flips` gains an I64 HASH column saved by + `ray_col_save_gen` (a2ca3564): 300 of 300 flips confined to its index + region were rejected, and structural flips over all six bases were rejected + 1184 of 1200 times. Full suite: 5920/5920, 0 runtime errors. +- WASM golden run: not run (no emcc on this machine); wasm32 layout check PASS — SPEC DEVIATION. +- First touch (fresh process, cache evicted per file): generation 2 pays the + column decode and the region parse. This is reported, not gated (spec + "Benchmarks"). About 630 ms for UserID and 1.25-1.35 s for the + RefererHash and URLHash columns, against 1-100 ms on generation 0. + In-process run 1 (warm page cache) is 250-660 ms. A profile of q41's first + use attributes 47% to `ray_enc_index_validate` (32% in its sort for + distinctness) and 7% to the decode. + +**P4 gate (equivalence): PASS** +**P4 gate (index validation suite): PASS** +**P4 index answers: PASS** (every query's full answer, warm and first touch, g2 equal to g0) +**P4 index queries warm: PASS** (each warm median at most 1.05x generation 0, or under 1 ms within 0.05 ms) + +### D7: the P2/P3 driver rerun (no regression, I8) + +`W=/home/hetoku/data/tmp/p2_bench BASE=25eabaf2 p2_bench.sh prep`, then +`splayed` (16:04-16:35) and `parted` (16:35-17:36). The P4 binary is +3abe880e (release, sha256 a2d3151c0de3, same source as a2ca3564). The base +is 25eabaf2, the end of P3 (1e9feb84f335). The driver's previous data in +that directory (P2 gate, 2026-10-10) was moved to `old_p2gate_20261010/`. +Load was 1.00 at the start; no other heavy job ran (a light cron worker +was the only other process seen). `p3_summary.py` is unchanged, including +its ALLOW table. Raw data: /home/hetoku/data/tmp/p2_bench/p2.tsv and +summary.txt. + +``` +totals over all 43: warm 1707.3 vs 1647.7 (0.965); first run 2516.1 vs 3882.2 (1.543); 3-run 5989.7 vs 7241.1 (1.209) +answer_mismatches none +first_run_total_ratio 1.543 (PI after P1: 2.99) +pi_row q41 warm 0.814 first 47.001 3run 25.474 +pi_row q42 warm 1.005 first 58.635 3run 32.166 +totals over all 43: warm 4707.3 vs 2904.4 (0.617); first run 16199.4 vs 13738.1 (0.848); 3-run 25750.6 vs 19671.9 (0.764) +answer_mismatches none +pi_row q41 warm 0.792 first 0.688 3run 0.751 +pi_row q42 warm 0.954 first 0.997 3run 1.068 +totals over all 43: warm 1711.1 vs 1711.1 (1.000); first run 2524.3 vs 2531.3 (1.003); 3-run 6011.3 vs 6017.0 (1.001) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=34)=0.998 warm_worst=1.102 worst5 [(1.102, 'q1'), (1.089, 'q25'), (1.057, 'q7'), (1.022, 'q42'), (1.021, 'q5')] +totals over all 43: warm 4650.9 vs 4713.8 (1.014); first run 16076.3 vs 16160.0 (1.005); 3-run 25486.7 vs 25750.1 (1.010) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=42)=1.005 warm_worst=1.046 worst5 [(1.046, 'q5'), (1.045, 'q4'), (1.04, 'q26'), (1.028, 'q7'), (1.026, 'q6')] +totals over all 43: warm 4392.1 vs 4459.9 (1.015); first run 15853.2 vs 15930.9 (1.005); 3-run 24764.8 vs 24998.8 (1.009) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=42)=1.006 warm_worst=1.052 worst5 [(1.052, 'q5'), (1.049, 'q4'), (1.04, 'q30'), (1.036, 'q26'), (1.027, 'q6')] +sizes {('A', 'g0'): 5948677939, ('A', 'g2'): 3216455899, ('B', 'p0'): 4807844987, ('B', 'p2'): 2072366907} peak_rss_kb {('A', 'g0'): 5118136, ('A', 'g2'): 5970564, ('B', 'p0'): 12144580, ('B', 'p2'): 11965660} evict_modes fadvise ragged_partition ['9', '40'] meta {'p2': ['3abe880e', 'a2d3151c0de3'], 'base': ['25eabaf2', '1e9feb84f335']} +GATE (strict) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=PASS] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=PASS] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (P3-exempt): FAIL +p3_unexpected_materializations A/q41:RefererHash A/q42:URLHash +rss A: 5118136 -> 5970564 kB (x1.167, bound 1.1) +rss B: 12144580 -> 11965660 kB (x0.985, bound 1.1) +carry q2/A/warm: P2 x1.086 -> P3 x0.617 +carry q8/A/warm: P2 x1.424 -> P3 x0.831 +carry q8/B/warm: P2 x1.060 -> P3 x0.362 +carry q18/A/first: P2 x1.983 -> P3 x0.435 +carry q18/B/warm: P2 x1.088 -> P3 x0.736 +carry q39/A/first: P2 x2.402 -> P3 x0.690 +carry q39/B/first: P2 x1.503 -> P3 x0.735 +carry q42/A/warm: P2 x1.664 -> P3 x1.005 +carry q42/B/warm: P2 x1.237 -> P3 x0.954 +P3GATE p2_strict=FAIL materialization=FAIL rss=FAIL +P3 GATE: FAIL +``` + +**D7 no-regression rerun: FAIL by the letter, after Task 10b; every failing clause is ruled** (Rulings 10-1 to 10-7). Materialization and RSS PASS (Ruling 10-1); first index use fixed (Ruling 10-2; q2/q3 61-63 ms accepted, Ruling 10-6); splayed warm q33 1.068 accepted (Ruling 10-7, post-spec tuning); gen-0 C0 q25 1.111, q27 1.077 and gmean 1.001 (Ruling 10-4 extended) and gen-0 parted (Ruling 10-5) accepted. Answers PASS on every arm. The rerun is in "Task 10b" below. + +**P4 gate: PASS** (Rulings 10-1 to 10-7) + +Failing clauses, each profiled on the release binaries (`perf record -g`; +the top-5 tables are in the Task 10 report): + +1. **Materialization, A/q41 RefererHash, A/q42 URLHash**, and **RSS A x1.167**. + The source store carries a persisted HASH on RefererHash, URLHash and + WatchID. Up to P3, generation 2 wrote these indexed columns as + generation 0: a base-written g2 reports gen-0 HASH dicts on them. Under P4 + they are generation 2 with an index region. D2 sends q41 / q42 down + generation 0's index route: materialize, then probe the HASH. The + counters match gen 0 (`.idx.uses` {RefererHash:1} / {URLHash:1} on both). + The warm times are 0.814 and 1.005. The first runs are 647 / 657 ms + against 14 / 11 ms on g0 (47x / 59x; PI rows above). The RSS excess is + entirely q41 / q42: a 41-query run without them gives g0 5 080 248 kB + and g2 5 059 724 kB (x0.996). With all 43, the figures are 5 104 436 and + 5 965 972 kB. This is D2's stated cost ("one materialization per indexed + column"), not an answer change. The ALLOW table and the RSS bound + predate indexed generation-2 columns. +2. **Splayed warm (A), q33 1.082** (202.6 -> 219.3 ms; the P3 rerun gave 1.039). + The group runs on the P3 fused encoded path on g2: + `agg_radix_group_fused_fn`, `agg_radix_fused_fn` and + `agg_radix_stage_block_c`, against `agg_radix_group_fn` and + `agg_radix_scatter_fn` on g0. The key WatchID (10M distinct, HASH) is + now generation 2: enc raw:9702 dict:64. On P3 it was a generation-0 file. + On the same P4 binary, a P3-written g2 (WatchID gen 0) takes 213 ms and a + P4-written g2 takes 217.5 ms; the base binary on the P3-written g2 takes + 213 ms. About 2 points come from WatchID being encoded, and about 4 points + are P3's existing gap. Nothing in P4's code path runs here: no + materialization, no index use. +3. **Gen-0 splayed warm (C0), q25 1.089** (0.93 -> 1.01 ms, a gap of 0.08 ms + over the 0.05 ms floor). This is Ruling 14-8's class. A 4-pass recheck + of 41 runs gives medians of base 0.96-1.01 and p4 1.00-1.01, with equal + minimums. 3000 in-process iterations take 2947 vs 2957 ms (1.003), with + identical profiles (`fpk_par_fn_plain`, `fpk_cmp`, `fp_eval_cmp`). +4. **Gen-0 parted warm (C1 gmean 1.005; R gmean 1.006 and q5 1.052)**. + The worst queries are q4 `(avg (at hits 'UserID))` and q5 + `(count (distinct (at hits 'UserID)))`, at 278 -> 291 ms, plus q6, q7 and + q26 at +3-4%. The cost is parted `at`, the per-element + `parted_to_flat_vec` (`ray_alloc` / `ray_free` / `store_typed_elem`), + with identical profiles on both binaries. `perf stat` on q4 gives + 46.57 G instructions on both (within 0.003%) but cycles +3.9%. None + of these functions changed in P4: `git diff 25eabaf2` touches no file + under src/lang or src/mem, nor src/ops/collection.c (`parted_to_flat_vec`) + or src/store/part.c (the splay.c change is write-side). The cause is code or data + layout, not P4 logic. + +### Task 10b: first index use on generation 2, the D7 rerun (Rulings 10-1 to 10-5) + +The index-query driver was rerun in full on 5b8a8ff6 (release, sha256 +af0c122eecba): `W=/home/hetoku/data/tmp/p4_bench p4_bench.sh clean all` +(20:11-20:18, 9 rounds, 3 first-touch trials; two 20 s load waits). +ff68a997 changes the validator and the parse only (the stores the writer +produces are the same). + +| query | warm g0 ms | warm g2 ms | ratio | best round g0 / g2 (ratio) | in-process run 1 g0 / g2 | first touch g0 / g2 ms | rows | answers warm / first | +|---|---|---|---|---|---|---|---|---| +| q1 UserID point lookup (ClickBench q20) | 0.009 | 0.009 | 0.966 | 0.008 / 0.008 (0.947) | 0.740 / 45.347 | 1.3 / 293.2 | 0 | same / same | +| q2 RefererHash point lookup (q41's constant) | 0.342 | 0.327 | 0.957 | 0.318 / 0.263 (0.826) | 1.447 / 61.182 | 15.3 / 523.1 | 81558 | same / same | +| q3 URLHash point lookup (q42's constant) | 0.388 | 0.342 | 0.881 | 0.345 / 0.295 (0.856) | 1.441 / 63.202 | 15.3 / 494.6 | 90899 | same / same | +| q4 ClickBench q41 | 5.847 | 4.717 | 0.807 | 5.698 / 4.568 (0.802) | 13.276 / 70.473 | 74.7 / 553.7 | 10 | same / same | +| q5 ClickBench q42 | 4.615 | 4.677 | 1.013 | 4.505 / 4.566 (1.014) | 11.119 / 71.871 | 36.7 / 509.1 | 10 | same / same | + +meta p4=5b8a8ff6/af0c122eecba; sizes, kinds and `.idx.uses` as above. + +**P4 index answers: PASS** (every query's full answer, warm and first touch, g2 equal to g0) +**P4 index queries warm: PASS** (each warm median at most 1.05x generation 0, or under 1 ms within 0.05 ms) + +First index use (Ruling 10-2), in-process run 1 on g2: q1 253 -> 45 ms, +q2 636 -> 61 ms, q3 653 -> 63 ms; first touch 630 -> 293, 1312 -> 523 and +1253 -> 495 ms. The distinctness check moved into the reachability walk +(a sort only past a compare budget), and tables of 2^17 buckets or more are +checked and copied over the pool (the serial checks rerun on any doubt, so +verdicts and messages do not depend on the core count). The rest of a +first use is mostly the page faults of about 270 MB of fresh heap (the +decoded column and the four HASH children) on this 4-core machine. + +D7, the splayed stage only, on 5b8a8ff6 against BASE 25eabaf2: +`W=/home/hetoku/data/tmp/p2_bench BASE=25eabaf2 p2_bench.sh prep`, then +`splayed` (20:19-20:52). Task 10's data in that directory was moved, not +deleted, to `old_p4t10_20261015/`. The driver now records the memx rows +(arm A without queries 41 and 42, 5b8a8ff6). Splayed-only summary: +/home/hetoku/data/tmp/p2_bench/summary.txt. The gate lines below come from +the splayed rows joined with Task 10's parted rows (arms B, C1 and R, +binary 3abe880e; ff68a997 does not run on those arms, which hold no index +region): /home/hetoku/data/tmp/p4t10b/d7_merged.tsv. + +``` +totals over all 43: warm 1709.4 vs 1645.7 (0.963); first run 2522.3 vs 2705.8 (1.073); 3-run 5994.6 vs 6079.5 (1.014) +pi_row q41 warm 0.825 first 5.642 3run 3.388 +pi_row q42 warm 1.036 first 6.638 3run 4.102 +gen0 warm_gmean(base>=1ms n=34)=1.001 warm_worst=1.111 worst5 [(1.111, 'q25'), (1.077, 'q27'), (1.031, 'q30'), (1.02, 'q42'), (1.018, 'q20')] +GATE (strict) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=PASS] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (strict): FAIL +p3_unexpected_materializations none +rss A: 5111900 -> 5968704 kB (x1.168 over all 43, bound 1.1) +rss A without D2 q41,q42: 5084840 -> 5039312 kB (x0.991, bound 1.1, gated) +rss B: 12144580 -> 11965660 kB (x0.985 over all 43, bound 1.1) +P3GATE p2_strict=FAIL materialization=PASS rss=PASS +P3 GATE: FAIL +``` + +The strict line's failing clauses, by ruling: +- splayed warm: q33 1.068 (202.9 -> 216.6 ms) only (Ruling 10-7: accepted + with a PR note, post-spec tuning; analysis under Ruling 10-3). The gap is + phase 2 of the fused encoded group (`agg_radix_group_fused_fn`, +325 M + cycles a query, +19% on `agg_radix_group_fn`), reading each partition as + about 300 runs of about 7 records, one per chunk; the fused phase 1 is + about 55 M cycles cheaper than the two passes. Prefetching whole runs, + prefetching further ahead and gathering the runs first did not help; a + huge-page record buffer helps generation 0 (q33 205 -> 198 ms) and not + generation 2. Larger runs end the fused pass for q33 (212-215 ms) but + cost q15, q16, q17 and q36 6-16% on generation 2. Not closed: the fix + is phase 2's layout, more than a medium change. +- gen-0 splayed warm (C0), every failing clause (Ruling 10-4 extended: + the sub-ms class; 10b changes no gen-0 code; Task 10's C0 gmean was 0.998): + - q25 1.111 (0.91 -> 1.01 ms, a 0.10 ms gap over the 0.05 ms floor); + - q27 1.077 (0.91 -> 0.98 ms, a 0.07 ms gap); + - gmean (base >= 1 ms, n=34) 1.001 against the 1.00 bound. +- gen-0 parted and ragged warm (Task 10's parted stage; Ruling 10-5, + accepted). + + +## P5 float encodings (float store derived from the 10M splayed store, release build, commit f41e6c99) + +The tables below this paragraph are **before 8b** (Task 8, f41e6c99). The +Task 8b numbers (float decode speed) follow them, under "After Task 8b". + +Driver: `W=/home/hetoku/data/tmp/p5_bench bench/compress_estimate/p5_bench.sh` +(prep / enc / ident / warm / cold / savet 13:07-13:16; a second prep / ident / +wall pass 15:00-15:05 after the P2/P3 rerun, with full-precision answers). +Binary: f41e6c99 release (sha256 4980fe53bf93; the scripts are the only +change in this commit); BASE for the writer cost: 81c04acb (3073a046ace1). +The store: five F64 columns and one F32 computed from ResolutionWidth, +ClientIP, SendTiming, RegionID, EventTime of `/skull/clickbench/rfsplayed` +(9 999 505 rows), plus IsRefresh as the group key; g0 / g2 saved, measured, +deleted. 9 warm rounds alternated, 3 cold trials (per-file eviction), the +load average checked before each round (4 waits, logged). Raw data: +/home/hetoku/data/tmp/p5_bench/p5.tsv, summary.txt beside it. + +``` +| column | encoded B | raw B | ratio | mix | +|---|---|---|---|---| +| price | 8598264 | 79996040 | 9.30x | {const:331 rle:4571 dict:2570 alp:2294} | +| ratio | 17432608 | 79996040 | 4.59x | {raw:159 const:3 rle:9535 dict:64 alp_rd:5} | +| sendt | 1169256 | 79996040 | 68.42x | {const:9185 alp:581} | +| level | 11663056 | 79996040 | 6.86x | {const:3 rle:7290 dict:323 alp:2150} | +| ts | 34648152 | 79996040 | 2.31x | {raw:1 dict:64 alp:9701} | +| f32 | 8284320 | 39998020 | 4.83x | {const:331 rle:8923 dict:17 alp:495} | +| refresh | 1755280 | 19999010 | 11.39x | {const:5 for_bp:8347 rle:1414} | + +| column | type | vectors | ALP vecs | ALP exc / rows | ALP (e,f) | ALP_RD vecs | ALP_RD exc / rows | DICT vecs | DICT w/ RAW codes (last vec) | trailers | +|---|---|---|---|---|---|---|---|---|---|---| +| f32 | F32 | 9766 | 495 | 0 / 506880 (0.00%) | (4,1)x495 | 0 | - | 17 | 0 (0) | 0 | +| level | F64 | 9766 | 2150 | 0 / 2201600 (0.00%) | (0,0)x2150 | 0 | - | 323 | 0 (0) | 0 | +| price | F64 | 9766 | 2294 | 0 / 2349056 (0.00%) | (14,12)x2294 | 0 | - | 2570 | 0 (0) | 0 | +| ratio | F64 | 9766 | 0 | - | - | 5 | 92 / 5120 (1.80%) | 64 | 0 (0) | 0 | +| refresh | 3 | 9766 | 0 | - | - | 0 | - | 0 | 0 (0) | 0 | +| sendt | F64 | 9766 | 581 | 59851 / 594944 (10.06%) | (0,0)x581 | 0 | - | 0 | 0 (0) | 0 | +| ts | F64 | 9766 | 9701 | 0 / 9933824 (0.00%) | (0,0)x9701 | 0 | - | 64 | 0 (0) | 0 | + +store: g0 459997072 B, g2 83551112 B (x0.182); save g0 1384 ms, g2 50932 ms (prep, one run) + +| writer (O5) | save g0 ms | save g2 ms | g2 / g0 | runs | +|---|---|---|---|---| +| p5 | 1320 | 50596 | 38.323 | 3 | +| base | 1611 | 2436 | 1.512 | 3 | + +save g2 p5 / base: 20.766; save g0 p5 / base: 0.819 +g2 store bytes: p5 83551112, base 365338960; g0: p5 459997072, base 459997072 + +| query | warm g0 | warm g2 | ratio | first g0 | first g2 | cold g0 | cold g2 | ratio | answers | +|---|---|---|---|---|---|---|---|---|---| +| q0 | 0.00 | 11.93 | 24242.886 | 0.02 | 16.22 | 0.0 | 22.5 | 1055.678 | DIFF (g0 drifts against itself too) | +| q1 | 0.00 | 8.12 | 15735.291 | 0.02 | 11.99 | 0.0 | 12.6 | 752.185 | DIFF | +| q2 | 0.00 | 0.00 | 0.886 | 0.01 | 0.03 | 0.0 | 0.0 | 2.674 | same | +| q3 | 0.00 | 0.00 | 0.939 | 0.01 | 0.03 | 0.0 | 0.0 | 3.063 | same | +| q4 | 7.07 | 12.78 | 1.807 | 20.85 | 24.87 | 177.7 | 31.4 | 0.177 | same | +| q5 | 3.32 | 6.29 | 1.897 | 9.41 | 11.18 | 153.2 | 25.8 | 0.169 | same | +| q6 | 6.56 | 8.54 | 1.302 | 13.10 | 13.42 | 169.5 | 38.4 | 0.226 | same | +| q7 | 5.50 | 1.77 | 0.321 | 11.37 | 6.08 | 158.6 | 6.7 | 0.042 | same | +| q8 | 7.57 | 19.04 | 2.516 | 9.76 | 20.78 | 203.9 | 29.0 | 0.142 | same | +| q9 | 16.58 | 16.65 | 1.004 | 18.69 | 35.96 | 165.4 | 38.4 | 0.232 | same | + +| query | wall g0 ms/call | wall g2 ms/call | ratio | +|---|---|---|---| +| q0 | 2.96 | 12.09 | 4.084 | +| q1 | 2.98 | 8.23 | 2.766 | +| q2 | 0.00 | 0.00 | 2.000 | +| q3 | 0.00 | 0.00 | 0.333 | +| q4 | 7.07 | 12.93 | 1.829 | +| q5 | 3.32 | 6.35 | 1.911 | +| q6 | 6.59 | 8.41 | 1.276 | +| q7 | 5.58 | 1.80 | 0.323 | +| q8 | 7.74 | 18.53 | 2.394 | +| q9 | 16.86 | 16.86 | 1.000 | + +load waits: 4 (13:10:24/1.79, 15:03:22/2.26, 15:04:07/2.92, 15:04:37/1.77) + +**P5 float store, answers g2 = g0: FAIL** +**P5 float store, scan-only warm (no regression, <= 1.05 per query): FAIL** (worst 24242.886) +``` + +Which store each stage's numbers come from (before 8b): prep / enc / +warm / cold / savet ran on the first derived store (13:07-13:16); ident and +wall ran on a second store, derived and saved again by the same binary at +15:00 after the P2/P3 rerun (same derivation, same bytes: the sizes match). + +### After Task 8b: float decode speed + +Driver: `W=/home/hetoku/data/tmp/p5b_bench bench/compress_estimate/p5_bench.sh all` +(16:21-16:58), with the fixed summary (`fix(bench)` commit: the scan-only +ratio of a query comes from the wall stage when its timeit g0 median is +below 0.05 ms, wall times below 0.05 ms are floored, every query must be +present in every stage; fix round 1: a failed or unparsable run fails +its query, and where timeit and wall both exist the verdict takes the +larger ratio, a gap over 0.10 printed as CHECK). Binary: the 8b tree on 7d744e4c, release (sha256 +d6b3aefbbbee); BASE for the writer cost 81c04acb. One store for every +stage: `all` derives and saves it once (prep), then enc / ident / warm / +cold / wall / savet run on it, then clean deletes it. 9 warm rounds, 3 cold +trials, 5 wall rounds, alternated; 7 load waits, logged. Raw data: +/home/hetoku/data/tmp/p5b_bench/p5.tsv, summary.txt beside it. The store's +bytes and encodings are unchanged (83 551 112 B g2; the mix and vector +tables above hold). + +``` +| query | warm g0 | warm g2 | ratio | first g0 | first g2 | cold g0 | cold g2 | ratio | answers | +|---|---|---|---|---|---|---|---|---|---| +| q0 | 0.00 | 2.88 | 5825.818 | 0.02 | 7.30 | 0.0 | 19.2 | 1515.681 | DIFF (g0 drifts against itself too) | +| q1 | 0.00 | 1.94 | 3847.465 | 0.02 | 6.16 | 0.0 | 7.0 | 333.307 | DIFF | +| q2 | 0.00 | 0.00 | 0.940 | 0.01 | 0.03 | 0.0 | 0.0 | 3.398 | same | +| q3 | 0.00 | 0.00 | 1.234 | 0.01 | 0.04 | 0.0 | 0.0 | 2.622 | same | +| q4 | 7.07 | 6.82 | 0.965 | 20.93 | 19.81 | 162.0 | 29.5 | 0.182 | same | +| q5 | 3.26 | 2.25 | 0.690 | 9.44 | 7.02 | 152.9 | 25.8 | 0.169 | same | +| q6 | 6.58 | 6.37 | 0.968 | 13.03 | 11.73 | 153.0 | 37.7 | 0.247 | same | +| q7 | 5.47 | 1.15 | 0.210 | 11.22 | 5.93 | 152.6 | 6.1 | 0.040 | same | +| q8 | 7.56 | 8.74 | 1.157 | 9.76 | 10.41 | 188.5 | 23.7 | 0.126 | same | +| q9 | 16.68 | 16.72 | 1.003 | 18.74 | 27.10 | 149.6 | 33.8 | 0.226 | same | + +| query | wall g0 ms/call | wall g2 ms/call | ratio | rounds | +|---|---|---|---|---| +| q0 | 2.956 | 2.873 | 0.972 | 5 | +| q1 | 2.950 | 1.921 | 0.651 | 5 | +| q2 | 0.002 | 0.002 | 1.000 (floored) | 5 | +| q3 | 0.003 | 0.002 | 1.000 (floored) | 5 | +| q4 | 7.046 | 6.798 | 0.965 | 5 | +| q5 | 3.276 | 2.265 | 0.691 | 5 | +| q6 | 6.620 | 6.355 | 0.960 | 5 | +| q7 | 5.525 | 1.118 | 0.202 | 5 | +| q8 | 7.663 | 8.910 | 1.163 | 5 | +| q9 | 16.987 | 16.898 | 0.995 | 5 | + +| query | scan-only ratio g2 / g0 | source | +|---|---|---| +| q0 | 0.972 | wall | +| q1 | 0.651 | wall | +| q2 | 1.000 | wall (floored) | +| q3 | 1.000 | wall (floored) | +| q4 | 0.965 | max(timeit 0.965, wall 0.965) | +| q5 | 0.691 | max(timeit 0.690, wall 0.691) | +| q6 | 0.968 | max(timeit 0.968, wall 0.960) | +| q7 | 0.210 | max(timeit 0.210, wall 0.202) | +| q8 | 1.163 | max(timeit 1.157, wall 1.163) | +| q9 | 1.003 | max(timeit 1.003, wall 0.995) | + +load waits: 7 (16:22:07/1.63, 16:22:42/1.55, 16:23:32/2.51, 16:24:02/1.59, 16:24:54/1.82, 16:25:24/1.61, 16:26:05/2.13) + +**P5 float store, all 10 queries present (and no run failed) in warm, cold, wall and ident: PASS** +**P5 float store, answers g2 = g0: FAIL** +**P5 float store, scan-only warm (no regression, <= 1.05 per query): FAIL** (worst 1.163, q8, max(timeit 1.157, wall 1.163)) +``` + +Before 8b / after 8b, g2 / g0 (the scan-only source of each row; before 8b +q0 / q1 from the wall table, the rest timeit): + +| query | before 8b | after 8b | +|---|---|---| +| q0 `sum price` | 4.084 | 0.972 | +| q1 `avg sendt` | 2.766 | 0.651 | +| q4 `price > 12.5` | 1.807 | 0.965 | +| q5 `level == 213.0` | 1.897 | 0.690 | +| q6 `ratio < 0.25` | 1.302 | 0.968 | +| q7 `sendt in [0.5, 1.5)` | 0.321 | 0.210 | +| q8 group `sum price by refresh` | 2.516 | 1.163 (timeit 1.157, wall 1.163) | +| q9 top 10 by price | 1.004 | 1.003 | + +What changed (no byte on disk, no answer, no corruption verdict changes): +- **Float fast path** (`dec_fast_float`, enccol.c). Every float encoding + decodes straight into the destination at the element width; one + branch-free pass (or one check per run for CONST / RLE / DICT-over-RLE + codes) folds the NaN, statistics and null rules. Anything off declines + (a trailer, a width, an illegal child, a code outside the dictionary, a + flag that trips), and the reference `dec_floats` then decodes the vector + or names its first failing rule with its own error. DICT over FOR_BP and + over RLE codes, RLE runs filled in fixed 16-element stores. +- **ALP**: a FOR_BP ints child that `ray_enc_read` would accept whole is + unpacked and decoded in one pass in enc_alp.c (strict FP flags kept; FMA + count 0); integers inside [-2^51, 2^51) are converted by the exact + 1.5 * 2^52 trick, which gives (double)n's bits and vectorises, then + `alp_dec1`'s two multiplies in its order. +- **`ray_enc_unpack`** runs row-major over the lanes (contiguous, + vectorisable) instead of lane-major (gen-2 only). +- **Float filters**: the single-leaf selection emit (an RLE view's runs + straight to the selection, P3's integer path) now takes F64 leaves too + (`ray_enc_eval_cmp_runs_f64`), and `rowsel_emit_runs` writes a passing + run's indices in 16-index vector stores. + +Checks: the decoded bytes of all six float columns, written back as gen 0, +are identical to the g0 store's files (`cmp`). At one core the 18 sums / +filters / groups over the store give the same answers before and after +(the parallel sums drift run to run, #744). New test +`encfloat/fast_equals_reference`: every float encoding, F64 and F32, three +lengths, with and without nulls; the fast kernel must take each sound body +with the reference's exact bytes, and over every one-byte forgery of the +body (5 kinds) and statistics narrowed at either end, a body the kernel +takes is one `dec_floats` accepts, with the same bytes. A mutation (the +per-run statistics check removed) fails it. + +Under the fixed summary (fix round 1) q8 reads 1.163, the larger of its +timeit (1.157) and wall (1.163) ratios; it is still the only query over +1.05, and it is accepted as a recorded deviation (Ruling 8b-1). No row +prints CHECK. + +The writer is unchanged by 8b: save g2 p5 / base 20.446, save g0 p5 / base +0.709 (summary.txt of the 8b run). + +**The floor (q8).** q8 is the only query over 1.05. g0's group is +compute-bound in the dense aggregation (`sum_f64_update`, `count_update`, +`agg_dense_phaseA_fn`: 85% of its cycles). g2 runs the same aggregation +(and skips g0's `agg_key_bounds_raw`, 11%, by its statistics), and adds the +decode of price and refresh: about 20% of g2's cycles (`dec_fast_float` 10%, +mostly the RLE fill stores; `ray_enc_alp_read` 3.5%; the I16 key 3%; the +range-read dispatch 3%). Per cores: 1 core 21.6 / 24.4 ms (1.13), 4 cores +10.4 / 11.4 (1.09), 8 threads 7.66 / 8.91 (1.16). Only one decode per +vector runs (counted). The decode is about 0.9 cycles per row on one core; +with two threads per core it competes with the sibling's aggregation, which +g0 hides behind its memory latency. What is left is the materialization +itself: the price vectors are 47% RLE and 26% DICT over RLE codes (median 75 +runs per vector), and filling 8 KB per vector is store-bound. Getting q8 to +1.05 needs the group aggregation to consume runs without materializing them +(a run-aware dense sum), which is outside 8b. + +The `(timeit (sum v))` ~0 ms reading reproduces on dev 94a77eeb: `timeit` +releases a lazy result without materializing it inside the timed span. +Filed as #856. + +Reading the float-store table (before 8b): +- **Answers FAIL is #744, not P5.** q2-q9 are equal byte for byte. q0 + (`sum price`) and q1 (`avg sendt`) differ only in the last digits, and the + values are nondeterministic run to run. Eight runs each (full precision, + /home/hetoku/data/tmp/p5/recheck/drift744.txt): + - `sum price` gives 7 distinct values on g0 and 8 on g2, all within + 150873431.4403-.4406; + - `avg sendt` is stable on g0 in this sample (one other run gave + ...13067), and gives 7 distinct values on g2. + + This is the unordered parallel float fold that dev's #744 fixes. Gen 2's + `reduce_src_walk` needs the same chunk-ordered fold at the dev merge + (already carried). The first pass printed 6 digits and showed "same" for + all 10 queries; the driver now writes scalars through `.csv.write`. +- **Scan-only warm FAIL is real and goes to the controller.** `(timeit q)` on + a plain generation-0 vector reports a top-level reduction as ~0 ms (q0, q1, + 0.00 ms warm, 0.02 ms first). The `wall` table is the honest per-call cost + (process wall time over 100 calls). On it, g2 is 4.08x on q0, 2.77x on q1, + 1.8-1.9x on q4 / q5, 1.28x on q6 and 2.39x on q8. q7 is 0.32x (CONST / + statistics), and q2 / q3 / q9 are at parity or answered from statistics. + Profile (`perf record`, release binary, 150 calls per query): + - g2 time is in the decode: `dec_floats` 25-73%, `read_body`, `ray_enc_unpack`; + - the filters spend 6-16% in `ray_enc_eval_cmp_f64`; + - g0 is `reduce_range_raw` / `expr_eval_morsel` only. + + `dec_floats` decodes every float vector into a bits buffer, then runs a + scalar per-row loop over it: the bitmap, the NaN check, the statistics + bound check and the copy. The sums cannot use views (float sums decode, + bit-identical; Task 7). So every sum, avg, filter and group over a float + column pays a full decode of about 1 ns per row, on top of the scan. +- **O5, the writer cost.** Medians of 3 alternated rounds; the table holds + six float columns and one I16: + + | writer | g0 save | g2 save | + |---|---|---| + | f41e6c99 | 1.32 s | 50.6 s | + | BASE 81c04acb | 1.61 s | 2.44 s | + + So g2 saves 20.8x slower than at BASE, and the g2 store is 4.4x smaller + (83.6 MB against 365.3 MB). Per column, each float column takes 6.8-10.0 s + and the I16 0.92 s. Profile of one F64 column's save: + - 61% `alprd_best` → `alprd_plan_rb`: 16 `qsort` calls of 1024 `u16` per + vector, through glibc's merge sort with a comparison callback; + - 24% `enc_size` / `ray_enc_stats` (`ray_enc_lt`), the candidate sizing. + + The 16 ALP_RD trials run for every vector, even where ALP or DICT wins. + Sorting the left parts once at the widest split and reading every + narrower split from that sorted array (a prefix order) would remove 15 + of the 16 sorts. A counting pass would remove the sort altogether. + Post-spec tuning; recorded, not changed here. +- **O1, the ALP sampler.** + - sendt (SendTiming / 1000) trained (0,0), because most sampled rows of + chunk 0 are integers (0.0). Its 581 ALP vectors carry 59 851 exceptions + over 594 944 rows: 10.06%, about 600 KB of the column's 1.17 MB. + (3,0) would have none. + - price (14,12), level (0,0), ts (0,0) and the F32 column (4,1) have 0 + exceptions. + - ratio is 5 ALP_RD vectors at 1.80% exceptions; the rest of it is RLE. + + The sampler weakness seen in Tasks 2, 5 and 7 therefore shows on real data + whenever chunk 0 is mostly integral. Recommendation (post-spec): sample + from the non-CONST vectors of the chunk, or with an odd stride / offset. + Or re-train a vector whose exception rate passes a bound against its own + sample, and add the result to the candidates. The negative check in + `encfloat/first_chunk_training` (an alone-trained (e, f) outside the + chunk-0 candidates) depends on today's sampler. A comment there now says + so; re-derive it if the sampler is tuned. +- **The short float DICT tail.** 0 of 3 038 DICT vectors in the store have + RAW codes, and no column's last (145-row) vector is DICT. The case + (Task 6 Minor 4) did not occur on this data. +- #850 does not bear on these numbers. The derived values come from integer + columns by division in the engine (no `0.0` literal is parsed into data), + and ident compares two stores written by the same release binary. + +Step 1, the gate runs (logs under /home/hetoku/data/tmp/p5/): + +| run | result | runtime errors | +|---|---|---| +| debug `encfloat/`, default cores (2) | 35/35, 0 failed | 0 | +| debug `encfloat/`, `TEST_CORES=0` | 35/35 | 0 | +| debug `encfloat/`, `TEST_CORES=8` | 35/35 | 0 | +| debug full suite | 5964/5964 | 0 | +| debug `equiv/` | 1179/1179 | 0 | +| release FP profile `encfloat/` (incl. `sweep_bit_exact`) | 35/35 | - | +| release FP profile `encfmt/golden` | 4/4 | - | +| release FP profile `idxval/golden` | 3/3 | - | +| informational (O3), release FP profile `aware/` | 94/94 | - | +| informational (O3), release FP profile `idxval/` | 69/69 | - | + +- Sweep: 480 saves (2 widths x 6 shapes x 8 lengths x 5 forced encodings), + NaN payloads and both zeros included, bit-exact (`encfloat/sweep_bit_exact`), + in the debug build at cores 0 / 2 / 8 and in the release FP profile + (`make test-release`). The data is built in C with the zeros as bit + patterns (D10). +- Codec object flags. Every line ends with the strict group + `-fno-fast-math -fno-unsafe-math-optimizations -fno-associative-math + -fno-reciprocal-math -fsigned-zeros -ffp-contract=off`. The flags that + come before it: + - `enc_alp.o` (debug): `-g -O0 -march=native -DDEBUG -fsanitize=address,undefined ...`; + - `enc_alp.rel.o`: `-O3 -march=native -funroll-loops -fomit-frame-pointer + -fno-math-errno -falign-functions=64 -fassociative-math -ffp-contract=fast + -fno-signed-zeros -fno-trapping-math`; + - `enc_alp.hard.o`: `-O3 -march=native -g -fno-omit-frame-pointer + -DRAY_HARDENED -funroll-loops -fno-math-errno -fassociative-math + -ffp-contract=fast -fno-signed-zeros -fno-trapping-math -falign-functions=64`; + - `enc_alp.reltest.o`: the release flags plus `-DDEBUG`. + + The full lines are in `cl-*.txt` beside the logs. FMA instructions in + `enc_alp.rel.o`: 0 (and 0 in `enc_alp.hard.o`). +- Cross-binary check: the release and debug `./rayforce` write + byte-identical float column files. `cmp` gives same for price, ratio, + sendt, level and f32 on the 1M-row table, with mixes ALP (14,12) / DICT, + ALP_RD (3 647 exceptions), DICT, RLE / CONST, DICT. Each binary reads + each store with identical output: the four md5s are 1b4695e0. The + printed sums carry 6 digits. +- Informational, release FP profile (O3): `aware/` 94/94 and `idxval/` + 69/69. Nothing goes to the final-review watch. +- PR notes: + - D8: the ALP_RD exception code is 0, a spec clarification; + - the WASM golden run was not run (ruling; no float wire struct added); + - the P2 64 KB float scratch is unchanged. + +### P2/P3 driver rerun against BASE 81c04acb (I8) + +`W=/home/hetoku/data/tmp/p2_bench BASE=81c04acb p2_bench.sh prep` (13:25-13:28), +`splayed` (13:28-13:59), `parted` (13:59-15:00). P5 binary f41e6c99 +(4980fe53bf93), base 81c04acb (3073a046ace1). The previous data in that +directory (P4's final rerun) moved to `old_p4final_20261015/`. +`p3_summary.py` is unchanged. Raw data: +/home/hetoku/data/tmp/p2_bench/p2.tsv and summary.txt. + +``` +totals over all 43: warm 1705.9 vs 1644.7 (0.964); first run 2522.7 vs 2713.4 (1.076); 3-run 5996.4 vs 6092.4 (1.016) +answer_mismatches none +scan_only(gated) n=28; gmeans over base>=1ms (per column): warm n=22 0.588, first n=23 0.707, cold n=23 0.338; worst warm=1.241 +scan_only_list_but_materializing none +worst5 warm [(1.241, 'q5'), (1.179, 'q6'), (1.109, 'q7'), (1.068, 'q4'), (1.068, 'q33')] +totals over all 43: warm 4625.0 vs 2875.6 (0.622); first run 16086.7 vs 13743.0 (0.854); 3-run 25520.0 vs 19602.9 (0.768) +answer_mismatches none +scan_only(gated) n=34; gmeans over base>=1ms (per column): warm n=33 0.179, first n=33 0.251, cold n=33 0.144; worst warm=1.027 +scan_only_list_but_materializing none +worst5 warm [(1.027, 'q33'), (1.013, 'q15'), (1.007, 'q32'), (1.007, 'q29'), (1.007, 'q13')] +totals over all 43: warm 1706.1 vs 1705.8 (1.000); first run 2530.0 vs 2532.6 (1.001); 3-run 6001.3 vs 6031.9 (1.005) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=35)=0.998 warm_worst=1.073 worst5 [(1.073, 'q27'), (1.032, 'q7'), (1.024, 'q30'), (1.02, 'q1'), (1.019, 'q5')] +totals over all 43: warm 4635.3 vs 4636.9 (1.000); first run 16037.0 vs 16116.2 (1.005); 3-run 25492.0 vs 25536.2 (1.002) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=42)=0.999 warm_worst=1.036 worst5 [(1.036, 'q1'), (1.008, 'q33'), (1.008, 'q30'), (1.007, 'q19'), (1.007, 'q18')] +q16 first run base 97.9 ms, p2 99.1 ms (carry 2) +totals over all 43: warm 4387.9 vs 4390.5 (1.001); first run 15795.6 vs 15839.8 (1.003); 3-run 24713.9 vs 24767.2 (1.002) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=42)=0.999 warm_worst=1.014 worst5 [(1.014, 'q31'), (1.01, 'q4'), (1.009, 'q5'), (1.009, 'q30'), (1.009, 'q12')] +enc A: columns with DELTA vectors: ['UserID {raw:76 const:3 delta_bp:97 rle:9526 dict:64}] +enc B: columns with DELTA vectors: ['UserID {raw:75 const:3 delta_bp:89 rle:8963 dict:640}] +sizes {('A', 'g0'): 5948677939, ('A', 'g2'): 3216455899, ('B', 'p0'): 4807844987, ('B', 'p2'): 2072366907} peak_rss_kb {('A', 'g0'): 5112180, ('A', 'g2'): 5966708, ('B', 'p0'): 12160960, ('B', 'p2'): 11981660} evict_modes fadvise ragged_partition ['9', '40'] meta {'p2': ['f41e6c99', '4980fe53bf93'], 'base': ['81c04acb', '3073a046ace1']} +GATE (strict) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=FAIL] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=PASS q16_first=FAIL] gen0-ragged[answers=PASS warm=PASS] +P2 GATE (P3-exempt): FAIL +p3_unexpected_materializations none +rss A: 5112180 -> 5966708 kB (x1.167 over all 43, bound 1.1) +rss A without D2 q41,q42: 5070228 -> 5042840 kB (x0.995, bound 1.1, gated) +rss B: 12160960 -> 11981660 kB (x0.985 over all 43, bound 1.1) +P3GATE p2_strict=FAIL materialization=PASS rss=PASS +P3 GATE: FAIL +``` + +**P2/P3 rerun strict line: FAIL by the letter (`P2 GATE (strict): FAIL`, +`P3 GATE: FAIL` through `p2_strict`). Every failing clause is one P4 ruled, +at the same size.** Materialization PASS, RSS PASS, and answers PASS on +every arm. Sizes are byte-identical to P4's rerun (A g0 5 948 677 939, +g2 3 216 455 899; B p0 4 807 844 987, p2 2 072 366 907): the ClickBench +store has no float column. + +1. **Splayed warm (A), q33 1.068.** P4's rerun gave 1.068 too (Ruling + 10-7, post-spec tuning). q4-q7 above 1.05 are 0.00 ms rows under the + sub-ms floor. +2. **Gen-0 splayed warm (C0), q27 1.073**, from 0.92 to 0.98 ms, a gap of + 0.06 ms over the 0.05 ms floor (Ruling 14-8's class; P4 had q25 / q27). + Recheck: 12 alternated processes, 10 warm runs each, on a fresh g0 copy: + base 1.020 ms, P5 1.004 ms, ratio 0.985 + (/home/hetoku/data/tmp/p5/recheck/q27.txt). The gmean is 0.998. +3. **Gen-0 parted q16_first**: P5 99.1 ms against base 97.9 ms (1.013). The + clause requires P5 to be strictly below base, and P4 accepted the same + clause (Ruling 10-5). Gen-0 parted warm passes this time (gmean 0.999, + worst 1.036 for q1), and so does ragged (0.999, worst 1.014). + +**P5 gate (float round trip bit-exact, NaN payloads included): PASS** + +## P6 STR encodings (STR store derived from the 10M splayed store, release build, commit 00fc4a90) + +Driver: `W=/home/hetoku/data/tmp/p6/t8/bench bench/compress_estimate/p6_bench.sh` +with stages prep, enc, mat, ident, warm, cold, wall, o5, clean, savet and parted +(12:58-16:52; wall was rerun alone after a fix in the summary helper; parted was +rerun after the fix described under R2). Binary 00fc4a90, release build +(sha256 e658455568da). BASE for the writer cost and O5 is 9802ba80, the commit +P6 Task 1 started from (0e3c5aae6df3). The store holds the 25 columns that the +43 ClickBench queries read from `/skull/clickbench/rfsplayed` (9 999 505 +rows), with the five text columns (URL, Title, Referer, SearchPhrase, +MobilePhoneModel) cast SYM -> STR (`(as 'STR c)`; rulings R3 / D14). g0 and +g2 were saved by `.db.splayed.set`, measured and deleted. Protocol: 9 warm +rounds and 5 wall rounds, alternated; 3 cold trials with per-file eviction; +ident runs g0 twice; the load average was checked before each round (73 waits, +logged). The disk guard ran before each store (prep: the 5.76 GB estimate +plus 4 GB). Raw data: /home/hetoku/data/tmp/p6/t8/bench/p6.tsv, with +summary.txt beside it. `p6_dictcheck` (built from `make lib`) compares +every element of every STR column, and the runtime DICT of every all-STR_DICT +column against generation 0's persisted DICT (codes, first occurrences, +n_distinct). + +``` +meta {'p6': ['00fc4a90', 'e658455568da'], 'base': ['9802ba80', '0e3c5aae6df3']} +| column | all STR_DICT | gen-2 index | DICT equal (codes, first occurrences, n_distinct) | elements equal | vectors | STR_DICT vectors | n_distinct g0 | n_distinct g2 | +|---|---|---|---|---|---|---|---|---| +| URL | false | none | - | true | 9766 | 4928 | 2620031 | -1 | +| Title | false | none | - | true | 9766 | 3339 | 1602929 | -1 | +| Referer | false | none | - | true | 9766 | 6144 | 2718828 | -1 | +| MobilePhoneModel | false | none | - | true | 9766 | 9058 | 91 | -1 | +| SearchPhrase | false | none | - | true | 9766 | 770 | 834981 | -1 | + +| column | g0 file B | g2 encoded B | raw B (.idx.info) | g0 / g2 | mix | +|---|---|---|---|---|---| +| WatchID | 588420000 | 589031872 | 79996040 | 1.00x | {raw:9702 dict:64} | +| EventTime | 79998848 | 59112600 | 79996040 | 1.35x | {raw:1 for_bp:9237 rle:464 dict:64} | +| EventDate | 40000832 | 563040 | 39998020 | 71.04x | {const:9634 rle:132} | +| CounterID | 40000832 | 560760 | 39998020 | 71.33x | {const:9687 rle:79} | +| ClientIP | 40000832 | 10639528 | 39998020 | 3.76x | {raw:228 const:3 rle:9535} | +| RegionID | 40000832 | 8934824 | 39998020 | 4.48x | {const:3 for_bp:1508 rle:8255} | +| UserID | 79998848 | 16765104 | 79996040 | 4.77x | {raw:76 const:3 delta_bp:97 rle:9526 dict:64} | +| URL (STR) | 1073152224 | 432796192 | 718229513 | 2.48x | {str_dict:4928 fsst:4838} | +| Title (STR) | 1306275776 | 450776480 | 913412536 | 2.90x | {const:328 str_dict:3339 fsst:6099} | +| Referer (STR) | 1046435104 | 401683776 | 649408230 | 2.61x | {str_dict:6144 fsst:3622} | +| IsRefresh | 20001824 | 1755280 | 19999010 | 11.40x | {const:5 for_bp:8347 rle:1414} | +| ResolutionWidth | 20001824 | 5706328 | 19999010 | 3.51x | {raw:1 const:331 for_bp:839 rle:8592 dict:3} | +| MobilePhone | 20001824 | 1627680 | 19999010 | 12.29x | {const:300 for_bp:56 rle:9347 dict:63} | +| MobilePhoneModel (STR) | 200013952 | 1702864 | 159992268 | 117.46x | {const:708 str_dict:9058} | +| SearchEngineID | 20001824 | 6629840 | 19999010 | 3.02x | {raw:1 const:126 for_bp:2203 rle:6809 dict:627} | +| SearchPhrase (STR) | 284560672 | 45869184 | 241091612 | 6.20x | {const:137 str_dict:770 fsst:8859} | +| AdvEngineID | 20001824 | 1273424 | 19999010 | 15.71x | {const:2502 for_bp:309 rle:6718 dict:237} | +| IsLink | 20001824 | 695648 | 19999010 | 28.75x | {const:8684 for_bp:1057 rle:25} | +| IsDownload | 20001824 | 593104 | 19999010 | 33.72x | {const:9156 for_bp:78 rle:532} | +| DontCountHits | 20001824 | 722576 | 19999010 | 27.68x | {const:8240 for_bp:1092 rle:434} | +| TraficSourceID | 20001824 | 4427096 | 19999010 | 4.52x | {const:1 for_bp:7298 rle:29 dict:2438} | +| URLHash | 275928576 | 263989472 | 79996040 | 1.05x | {raw:3946 rle:5756 dict:64} | +| RefererHash | 274911456 | 272463680 | 79996040 | 1.01x | {raw:8563 rle:1139 dict:64} | +| WindowClientWidth | 20001824 | 12725264 | 19999010 | 1.57x | {raw:2 const:330 for_bp:7554 rle:1878 dict:2} | +| WindowClientHeight | 20001824 | 12540552 | 19999010 | 1.59x | {raw:17 const:329 for_bp:7474 rle:1945 dict:1} | + +store: g0 5589719419 B (estimate 5760421679), g2 2603586739 B (x0.466); save g0 50015 ms, g2 166550 ms (prep, one run) +BASE's generation-2 save of the same table (o5, RAW / CONST STR): 4933804739 B, save 38948 ms +disk: prep: scratch 8200847449 B, free 3113684992 B; o5: scratch 7560024346 B, free 4538294272 B; parted: scratch 6354252974 B, free 5729128448 B + +| writer (O2) | save g0 ms | save g2 ms | g2 / g0 | g0 B | g2 B | runs | +|---|---|---|---|---|---|---| +| p6 | 33866 | 167357 | 4.942 | 5589719419 | 2603586739 | 3 | +| base | 32858 | 37563 | 1.143 | 5589719419 | 4933804739 | 3 | + +save g2 p6 / base: 4.455; save g0 p6 / base: 1.031 + +| query | warm g0 | warm g2 | ratio | first g0 | first g2 | cold g0 | cold g2 | ratio | answers | g2 materializes | +|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.005 | 0.01 | 0.01 | 0.0 | 0.0 | 0.984 | same | scan | +| q2 | 0.67 | 0.47 | 0.695 | 1.67 | 1.25 | 38.3 | 3.6 | 0.094 | same | scan | +| q3 | 3.82 | 0.00 | 0.001 | 5.65 | 0.05 | 93.3 | 0.0 | 0.000 | same | scan | +| q4 | 0.00 | 0.00 | 1.078 | 0.03 | 0.04 | 0.0 | 0.0 | 1.656 | same | scan | +| q5 | 0.00 | 0.00 | 1.121 | 0.03 | 0.03 | 0.0 | 0.0 | 1.105 | same | scan | +| q6 | 0.00 | 0.00 | 1.208 | 0.03 | 0.03 | 0.0 | 0.0 | 1.117 | same | scan | +| q7 | 0.00 | 0.00 | 1.092 | 0.02 | 0.04 | 0.0 | 0.0 | 1.912 | same | scan | +| q8 | 3.58 | 2.97 | 0.827 | 9.07 | 8.25 | 41.0 | 9.7 | 0.237 | same | scan | +| q9 | 76.12 | 75.94 | 0.998 | 112.23 | 127.59 | 682.0 | 155.8 | 0.228 | same | mat: RegionID UserID | +| q10 | 69.67 | 72.55 | 1.041 | 97.15 | 118.00 | 430.2 | 154.0 | 0.358 | same | mat: RegionID UserID | +| q11 | 65.17 | 108.35 | 1.663 | 72.81 | 195.26 | 294.7 | 219.6 | 0.745 | same | mat: UserID MobilePhoneModel | +| q12 | 67.62 | 39.52 | 0.584 | 72.01 | 46.82 | 259.3 | 79.1 | 0.305 | same | scan | +| q13 | 79.33 | 379.73 | 4.787 | 95.70 | 464.32 | 170.5 | 485.0 | 2.845 | same | scan | +| q14 | 240.28 | 419.58 | 1.746 | 332.78 | 867.72 | 555.1 | 914.3 | 1.647 | same | mat: UserID SearchPhrase | +| q15 | 91.90 | 388.75 | 4.230 | 101.84 | 476.91 | 213.2 | 514.9 | 2.415 | same | scan | +| q16 | 70.49 | 61.50 | 0.873 | 95.97 | 86.79 | 243.0 | 166.6 | 0.685 | same | scan | +| q17 | 91.79 | 879.91 | 9.586 | 129.24 | 1016.16 | 443.4 | 1130.3 | 2.549 | same | scan | +| q18 | 6.97 | 790.27 | 113.340 | 13.70 | 909.88 | 660.2 | 956.7 | 1.449 | same | scan | +| q19 | 138.14 | 928.66 | 6.723 | 210.56 | 1104.83 | 681.0 | 1301.6 | 1.911 | same | mat: EventTime | +| q20 | 1.18 | 0.63 | 0.531 | 6.91 | 5.99 | 56.5 | 16.5 | 0.291 | same | scan | +| q21 | 107.05 | 110.36 | 1.031 | 110.67 | 1109.68 | 107.7 | 2393.6 | 22.228 | same | mat: URL | +| q22 | 177.62 | 246.90 | 1.390 | 179.98 | 1255.65 | 222.0 | 2573.1 | 11.589 | same | mat: URL | +| q23 | 286.56 | 299.81 | 1.046 | 291.98 | 3244.06 | 605.1 | 5828.5 | 9.632 | same | mat: UserID URL Title SearchPhrase | +| q24 | 75.93 | 240.19 | 3.163 | 80.54 | 441.17 | 177.3 | 1432.7 | 8.082 | same | mat: EventTime | +| q25 | 0.96 | 17.40 | 18.215 | 2.39 | 121.70 | 73.9 | 748.0 | 10.123 | same | mat: EventTime | +| q26 | 12.74 | 33.26 | 2.610 | 14.69 | 373.75 | 168.0 | 944.2 | 5.622 | same | mat: SearchPhrase | +| q27 | 0.96 | 9.34 | 9.711 | 2.45 | 371.33 | 77.6 | 1025.3 | 13.213 | same | mat: EventTime SearchPhrase | +| q28 | 110.67 | 97.52 | 0.881 | 113.94 | 1485.94 | 181.1 | 2062.4 | 11.388 | same | mat: URL | +| q29 | 2176.37 | 484.46 | 0.223 | 2405.44 | 1879.38 | 2406.0 | 2408.1 | 1.001 | same | mat: Referer | +| q30 | 0.02 | 0.02 | 0.982 | 2.92 | 4.64 | 53.4 | 11.4 | 0.213 | same | mat: ResolutionWidth | +| q31 | 112.12 | 305.35 | 2.723 | 127.08 | 355.91 | 305.1 | 417.5 | 1.368 | same | scan | +| q32 | 119.15 | 310.20 | 2.603 | 144.54 | 371.55 | 429.4 | 578.6 | 1.348 | same | scan | +| q33 | 207.14 | 222.23 | 1.073 | 373.12 | 377.26 | 601.2 | 609.6 | 1.014 | same | scan | +| q34 | 28.02 | 458.43 | 16.363 | 51.40 | 1679.74 | 130.6 | 2953.3 | 22.621 | same | mat: URL | +| q35 | 28.07 | 457.95 | 16.312 | 51.34 | 1671.40 | 130.3 | 2956.1 | 22.691 | same | mat: URL | +| q36 | 64.86 | 58.92 | 0.908 | 87.28 | 82.36 | 162.4 | 127.3 | 0.784 | same | scan | +| q37 | 20.64 | 166.28 | 8.057 | 31.23 | 280.43 | 49.3 | 597.9 | 12.118 | same | scan | +| q38 | 19.49 | 31.07 | 1.594 | 29.06 | 78.56 | 45.8 | 242.9 | 5.306 | same | scan | +| q39 | 7.40 | 272.87 | 36.861 | 14.73 | 341.85 | 44.0 | 644.8 | 14.664 | same | scan | +| q40 | 110.63 | 243.92 | 2.205 | 202.51 | 454.73 | 217.1 | 1085.3 | 4.998 | same | scan | +| q41 | 5.83 | 4.67 | 0.802 | 13.45 | 71.11 | 74.5 | 554.0 | 7.434 | same | mat: RefererHash | +| q42 | 4.49 | 4.81 | 1.073 | 10.93 | 73.18 | 37.3 | 564.2 | 15.123 | same | mat: URLHash | +| q43 | 9.07 | 7.65 | 0.844 | 18.74 | 17.22 | 41.4 | 26.6 | 0.642 | same | scan | + +| query | wall g0 ms/call | wall g2 ms/call | ratio | rounds | +|---|---|---|---|---| +| q1 | 0.082 | 0.002 | 0.610 (floored) | 5 | +| q2 | 0.497 | 0.437 | 0.879 | 5 | +| q3 | 3.880 | 0.006 | 0.013 (floored) | 5 | +| q4 | 2.993 | 0.001 | 0.017 (floored) | 5 | +| q5 | 41.611 | 41.571 | 0.999 | 5 | +| q6 | 67.178 | 251.079 | 3.738 | 5 | +| q7 | -0.018 | 0.005 | 1.000 (floored) | 5 | +| q8 | 3.748 | 2.999 | 0.800 | 5 | +| q9 | 77.914 | 76.971 | 0.988 | 5 | +| q10 | 70.698 | 72.982 | 1.032 | 5 | +| q11 | 64.874 | 108.749 | 1.676 | 5 | +| q12 | 68.136 | 40.187 | 0.590 | 5 | +| q13 | 79.998 | 380.515 | 4.757 | 5 | +| q14 | 242.437 | 418.591 | 1.727 | 5 | +| q15 | 91.187 | 388.036 | 4.255 | 5 | +| q16 | 71.271 | 62.909 | 0.883 | 5 | +| q17 | 94.228 | 877.738 | 9.315 | 5 | +| q18 | 7.147 | 792.773 | 110.924 | 5 | +| q19 | 138.300 | 927.711 | 6.708 | 5 | +| q20 | 1.026 | 0.622 | 0.606 | 5 | +| q21 | 108.276 | 111.336 | 1.028 | 5 | +| q22 | 179.730 | 246.767 | 1.373 | 5 | +| q23 | 287.759 | 299.688 | 1.041 | 5 | +| q24 | 76.877 | 239.782 | 3.119 | 5 | +| q25 | 1.041 | 17.641 | 16.946 | 5 | +| q26 | 12.845 | 33.331 | 2.595 | 5 | +| q27 | 0.847 | 9.583 | 11.314 | 5 | +| q28 | 112.467 | 98.102 | 0.872 | 5 | +| q29 | 2116.021 | 494.309 | 0.234 | 5 | +| q30 | 0.130 | 0.100 | 0.769 | 5 | +| q31 | 112.105 | 305.951 | 2.729 | 5 | +| q32 | 119.897 | 311.742 | 2.600 | 5 | +| q33 | 207.492 | 218.731 | 1.054 | 5 | +| q34 | 28.239 | 460.388 | 16.303 | 5 | +| q35 | 28.598 | 460.641 | 16.107 | 5 | +| q36 | 65.185 | 60.613 | 0.930 | 5 | +| q37 | 20.967 | 166.168 | 7.925 | 5 | +| q38 | 19.698 | 31.440 | 1.596 | 5 | +| q39 | 7.453 | 274.373 | 36.814 | 5 | +| q40 | 111.349 | 243.344 | 2.185 | 5 | +| q41 | 5.653 | 4.618 | 0.817 | 5 | +| q42 | 4.414 | 4.570 | 1.035 | 5 | +| q43 | 9.258 | 7.889 | 0.852 | 5 | + +| query | scan-only ratio g2 / g0 | source | g2 materializes | +|---|---|---|---| +| q1 | 0.610 | wall (floored) | scan | +| q2 | 0.879 | max(timeit 0.695, wall 0.879) CHECK | scan | +| q3 | 0.013 | max(timeit 0.001, wall 0.013) | scan | +| q4 | 0.017 | wall (floored) | scan | +| q5 | 0.999 | wall | scan | +| q6 | 3.738 | wall | scan | +| q7 | 1.000 | wall (floored) | scan | +| q8 | 0.827 | max(timeit 0.827, wall 0.800) | scan | +| q9 | 0.998 | max(timeit 0.998, wall 0.988) | mat: RegionID UserID | +| q10 | 1.041 | max(timeit 1.041, wall 1.032) | mat: RegionID UserID | +| q11 | 1.676 | max(timeit 1.663, wall 1.676) | mat: UserID MobilePhoneModel | +| q12 | 0.590 | max(timeit 0.584, wall 0.590) | scan | +| q13 | 4.787 | max(timeit 4.787, wall 4.757) | scan | +| q14 | 1.746 | max(timeit 1.746, wall 1.727) | mat: UserID SearchPhrase | +| q15 | 4.255 | max(timeit 4.230, wall 4.255) | scan | +| q16 | 0.883 | max(timeit 0.873, wall 0.883) | scan | +| q17 | 9.586 | max(timeit 9.586, wall 9.315) CHECK | scan | +| q18 | 113.340 | max(timeit 113.340, wall 110.924) CHECK | scan | +| q19 | 6.723 | max(timeit 6.723, wall 6.708) | mat: EventTime | +| q20 | 0.606 | max(timeit 0.531, wall 0.606) | scan | +| q21 | 1.031 | max(timeit 1.031, wall 1.028) | mat: URL | +| q22 | 1.390 | max(timeit 1.390, wall 1.373) | mat: URL | +| q23 | 1.046 | max(timeit 1.046, wall 1.041) | mat: UserID URL Title SearchPhrase | +| q24 | 3.163 | max(timeit 3.163, wall 3.119) | mat: EventTime | +| q25 | 18.215 | max(timeit 18.215, wall 16.946) CHECK | mat: EventTime | +| q26 | 2.610 | max(timeit 2.610, wall 2.595) | mat: SearchPhrase | +| q27 | 11.314 | max(timeit 9.711, wall 11.314) CHECK | mat: EventTime SearchPhrase | +| q28 | 0.881 | max(timeit 0.881, wall 0.872) | mat: URL | +| q29 | 0.234 | max(timeit 0.223, wall 0.234) | mat: Referer | +| q30 | 0.769 | wall | mat: ResolutionWidth | +| q31 | 2.729 | max(timeit 2.723, wall 2.729) | scan | +| q32 | 2.603 | max(timeit 2.603, wall 2.600) | scan | +| q33 | 1.073 | max(timeit 1.073, wall 1.054) | scan | +| q34 | 16.363 | max(timeit 16.363, wall 16.303) | mat: URL | +| q35 | 16.312 | max(timeit 16.312, wall 16.107) CHECK | mat: URL | +| q36 | 0.930 | max(timeit 0.908, wall 0.930) | scan | +| q37 | 8.057 | max(timeit 8.057, wall 7.925) CHECK | scan | +| q38 | 1.596 | max(timeit 1.594, wall 1.596) | scan | +| q39 | 36.861 | max(timeit 36.861, wall 36.814) | scan | +| q40 | 2.205 | max(timeit 2.205, wall 2.185) | scan | +| q41 | 0.817 | max(timeit 0.802, wall 0.817) | mat: RefererHash | +| q42 | 1.073 | max(timeit 1.073, wall 1.035) | mat: URLHash | +| q43 | 0.852 | max(timeit 0.844, wall 0.852) | scan | + +STR columns left materialized on g2 (mat stage): q11 MobilePhoneModel, q14 SearchPhrase, q21 URL, q22 URL, q23 URL+Title+SearchPhrase, q26 SearchPhrase, q27 SearchPhrase, q28 URL, q29 Referer, q34 URL, q35 URL + +| query | C: g0 base | C: g0 p6 | ratio | D: base on its gen-2 save | D: p6 on g2 | ratio | p6 g2 / p6 g0 (warm stage) | +|---|---|---|---|---|---|---|---| +| q6 | 0.00 | 0.00 | 0.978 | 0.00 | 0.00 | 0.980 | 1.208 | +| q11 | 64.89 | 64.65 | 0.996 | 99.39 | 108.75 | 1.094 | 1.663 | +| q12 | 67.26 | 68.79 | 1.023 | 66.95 | 39.46 | 0.589 | 0.584 | +| q13 | 79.67 | 79.55 | 0.998 | 194.99 | 382.34 | 1.961 | 4.787 | +| q14 | 240.06 | 240.64 | 1.002 | 406.00 | 417.12 | 1.027 | 1.746 | +| q15 | 91.04 | 93.41 | 1.026 | 201.34 | 385.46 | 1.914 | 4.230 | +| q17 | 91.62 | 92.14 | 1.006 | 419.44 | 878.90 | 2.095 | 9.586 | +| q18 | 6.99 | 7.06 | 1.010 | 333.81 | 792.39 | 2.374 | 113.340 | +| q19 | 138.37 | 137.06 | 0.990 | 470.49 | 924.82 | 1.966 | 6.723 | +| q22 | 177.88 | 176.88 | 0.994 | 175.74 | 244.84 | 1.393 | 1.390 | +| q23 | 286.20 | 287.85 | 1.006 | 294.34 | 300.94 | 1.022 | 1.046 | +| q29 | 1430.36 | 1951.79 | 1.365 | 521.54 | 483.36 | 0.927 | 0.223 | +| q34 | 27.91 | 27.87 | 0.999 | 481.41 | 457.39 | 0.950 | 16.363 | +| q35 | 28.08 | 28.12 | 1.002 | 480.96 | 457.78 | 0.952 | 16.312 | +| q37 | 20.62 | 20.82 | 1.009 | 78.13 | 164.24 | 2.102 | 8.057 | +| q38 | 19.53 | 19.58 | 1.002 | 48.19 | 30.81 | 0.639 | 1.594 | +| q39 | 7.33 | 7.37 | 1.006 | 19.10 | 275.11 | 14.403 | 36.861 | +| q40 | 111.14 | 111.80 | 1.006 | 141.96 | 241.79 | 1.703 | 2.205 | + +parted arm (R2): p0 4695311694 B, p2 1636295358 B; STR mixes: URL {str_dict:7368 fsst:2402}; Title {const:330 str_dict:3322 fsst:6118}; Referer {str_dict:6182 fsst:3588}; MobilePhoneModel {const:697 str_dict:8480 fsst:593}; SearchPhrase {const:142 str_dict:798 fsst:8830} + +| query | warm p0 | warm p2 | ratio | first p0 | first p2 | answers | p2 materializes | +|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.963 | 0.01 | 0.01 | same | scan | +| q2 | 6.74 | 6.57 | 0.974 | 16.78 | 16.29 | same | scan | +| q3 | 549.44 | 0.00 | 0.000 | 555.02 | 0.05 | same | scan | +| q4 | 282.41 | 0.00 | 0.000 | 323.86 | 0.05 | same | scan | +| q5 | 284.32 | 0.00 | 0.000 | 321.04 | 0.03 | same | scan | +| q6 | 359.46 | 359.07 | 0.999 | 634.55 | 843.89 | same | mat: SearchPhrase | +| q7 | 550.81 | 0.00 | 0.000 | 577.32 | 0.05 | same | scan | +| q8 | 6.38 | 2.31 | 0.363 | 7.76 | 3.75 | same | scan | +| q9 | 86.56 | 86.90 | 1.004 | 152.02 | 164.55 | same | mat: RegionID UserID | +| q10 | 79.67 | 80.30 | 1.008 | 156.87 | 172.77 | same | mat: RegionID UserID | +| q11 | 331.93 | 49.35 | 0.149 | 419.54 | 57.84 | same | scan | +| q12 | 335.42 | 50.20 | 0.150 | 424.04 | 57.53 | same | scan | +| q13 | 867.30 | 863.99 | 0.996 | 1129.19 | 1197.39 | same | mat: SearchPhrase | +| q14 | 638.31 | 543.20 | 0.851 | 862.04 | 635.15 | same | scan | +| q15 | 873.84 | 870.36 | 0.996 | 1120.00 | 1169.65 | same | mat: SearchPhrase | +| q16 | 72.86 | 61.84 | 0.849 | 98.14 | 88.55 | same | scan | +| q17 | 601.92 | 860.93 | 1.430 | 904.43 | 974.53 | same | scan | +| q18 | 590.18 | 777.66 | 1.318 | 897.57 | 860.40 | same | scan | +| q19 | 822.49 | 961.24 | 1.169 | 1376.85 | 1347.15 | same | mat: EventTime | +| q20 | 4.49 | 1.49 | 0.332 | 14.45 | 12.07 | same | scan | +| q21 | 109.98 | 110.78 | 1.007 | 114.93 | 717.45 | same | mat: URL | +| q22 | 490.31 | 349.75 | 0.713 | 658.44 | 966.95 | same | mat: URL | +| q23 | 590.45 | 519.93 | 0.881 | 765.13 | 2440.33 | same | mat: URL Title | +| q24 | 110.47 | 117.65 | 1.065 | 114.96 | 766.97 | same | mat: URL | +| q25 | 393.51 | 243.72 | 0.619 | 568.56 | 271.91 | same | scan | +| q26 | 490.89 | 414.98 | 0.845 | 675.11 | 495.52 | same | scan | +| q27 | 491.13 | 401.71 | 0.818 | 676.22 | 472.87 | same | scan | +| q28 | 746.99 | 756.54 | 1.013 | 1765.61 | 1346.74 | same | mat: URL | +| q29 | 1725.87 | 1726.94 | 1.001 | 2781.67 | 3779.16 | same | mat: Referer | +| q30 | 271.72 | 273.41 | 1.006 | 284.22 | 288.80 | same | mat: ResolutionWidth | +| q31 | 415.37 | 268.06 | 0.645 | 651.12 | 288.40 | same | scan | +| q32 | 433.31 | 284.48 | 0.657 | 706.45 | 322.32 | same | scan | +| q33 | 215.57 | 221.51 | 1.028 | 375.94 | 390.59 | same | scan | +| q34 | 1089.12 | 1107.09 | 1.016 | 2305.17 | 2912.90 | same | mat: URL | +| q35 | 1088.70 | 1107.31 | 1.017 | 2319.07 | 2913.25 | same | mat: URL | +| q36 | 150.03 | 151.86 | 1.012 | 221.85 | 198.53 | same | scan | +| q37 | 733.49 | 716.79 | 0.977 | 1739.18 | 2408.54 | same | mat: URL | +| q38 | 1045.51 | 1033.31 | 0.988 | 2440.77 | 3761.42 | same | mat: Title | +| q39 | 19.37 | 262.52 | 13.551 | 31.03 | 281.65 | same | scan | +| q40 | 204.29 | 239.08 | 1.170 | 350.89 | 387.78 | same | scan | +| q41 | 17.54 | 13.63 | 0.777 | 38.60 | 26.12 | same | scan | +| q42 | 13.05 | 13.46 | 1.031 | 23.63 | 24.83 | same | scan | +| q43 | 28.52 | 16.34 | 0.573 | 41.06 | 28.22 | same | scan | + +parted arm (R2), informational: all 43 queries present: yes; answers p2 = p0: yes + +load waits: 73 (13:13:49/1.65, 13:17:04/3.13, 13:17:34/1.95, 13:18:04/1.57, 13:21:17/4.00, 13:21:47/2.42, 13:22:17/1.64, 13:25:32/3.11, 13:26:02/1.88, 13:29:15/3.19) + +over 1.05 (scan-only line): q6 3.738, q11 1.676, q13 4.787, q14 1.746, q15 4.255, q17 9.586, q18 113.340, q19 6.723, q22 1.390, q24 3.163, q25 18.215, q26 2.610, q27 11.314, q31 2.729, q32 2.603, q33 1.073, q34 16.363, q35 16.312, q37 8.057, q38 1.596, q39 36.861, q40 2.205, q42 1.073 + +**P6 gate (STR round trip): PASS** (every STR column element-identical, 5 columns) +**P6 gate (DICT index equal to generation 0 on all-STR_DICT columns): FAIL** (not exercised: no all-STR_DICT column) +**P6 STR store, all 43 queries present (and no run failed) in warm, cold, wall and ident: PASS** +**P6 STR store, answers g2 = g0: PASS** +**P6 STR store, scan-only warm (no regression, <= 1.05 per query): FAIL** (worst 113.340, q18, max(timeit 113.340, wall 110.924) CHECK) +``` + +Reading the STR-store table: + +- **Round trip: PASS.** All five STR columns are element-identical between + g0 and g2 (`p6_dictcheck` compares every element), and all 43 answers are + byte-identical (raw hashes equal on every query; g0 is stable against + itself). The parted arm (R2, below) gives the same result. +- **DICT gate: FAIL, not exercised.** No STR column of the 10M store is + all STR_DICT, so no column carries a runtime DICT, and the second clause is + not measured on this data. The runtime DICT needs every vector to be + STR_DICT, so that every chunk carries code bounds (spec "STR dictionary + index"; `encw.c` writes chunk bounds only then). What breaks it, per column: + - MobilePhoneModel (91 distinct values): 9058 of 9766 vectors are STR_DICT, + and the other 708 are all-`""` vectors. The null rule (D4, the spec's + one-way rule) makes those CONST. + - Title and SearchPhrase: all-`""` CONST vectors (328 and 137), plus FSST. + - URL, Referer: FSST vectors (4838 and 3622) after chunk 0. + + So on real text data the runtime DICT is built only for columns with no + all-null vector, which almost every sparse text column has. Columns with + a non-STR_DICT vector carry no runtime DICT by design (spec "STR dictionary + index"); the DICT equality is covered by `encstr/dict_equals_gen0` (70 000 + rows, all STR_DICT). +- **Sizes.** g2 is 0.466 of g0 (2.60 GB against 5.59 GB) and 0.53 of BASE's + own generation-2 save, whose STR is RAW / CONST (4.93 GB). The STR + columns shrink 2.5-2.9x (URL, Title, Referer, all FSST / STR_DICT), 6.2x + (SearchPhrase) and 117x (MobilePhoneModel). +- **Writer cost (O2): 4.46x BASE.** The g2 save takes 167 s against 37.6 s + at BASE (medians of 3 alternated rounds). g0 saves are at parity (1.03). + This is the pre-flight's O2 item: the chunk plan FSST-encodes each vector + once to size it and again to write it. Post-spec, as P5's writer cost was. +- **Scan-only warm: FAIL (worst q18 113x), sent to the controller and not + tuned (the P5 Ruling 8b-1 precedent).** 23 queries are over 1.05. The + timeit and wall ratios agree everywhere (the gaps flagged CHECK are on + ratios far above 1.05). Two classes: + 1. **STR group-by keys** (q13 4.8x, q15 4.3x, q17 9.6x, q18 113x, q19 6.7x, + q34 / q35 16x, q37 8.1x, q38 1.6x, q39 37x, q40 2.2x). Gen 0 has a + persisted DICT on every STR column and groups on its codes; gen 2 has + no DICT on any column of this data (above). Profiles (`perf record`, + release, 8 calls after a warm-up; /home/hetoku/data/tmp/p6/t8/prof/): + - q18 g0: `agg_firstn_task` 21% (plus the load-time `col_validate_mapped`). + - q18 g2: the strdom route. `ray_fsst_expanded_len` 31% and + `ray_fsst_decode` 21% (a per-row FSST decode of SearchPhrase, which is + 8859 FSST vectors of 9766), then `sd_intern` 10%, `sd_rows` 9%, + `ray_enc_fsst_check` 9% and `dec_str` 9%. + - q34 g0: the dense partitioned aggregation over the DICT codes. + - q34 g2: URL is materialized (Ruling 7-1's shape), then grouped through + the string hash directory: `agg_key_directory_insert` 31%, + `ray_str_vec_get` 10%, and FSST decode 12%. + + The gap is the missing DICT, not the remap. Of the 770 STR_DICT + vectors of SearchPhrase, only those go through the per-dictionary remap + (Task 6); every FSST row is decoded and interned serially. + 2. **STR `!= ""` filters and sort keys** (q6 count distinct SearchPhrase + 3.7x; q24-q27 3.2-18x; q31 / q32 2.7x; q22 1.4x). Not profiled + separately: the store was deleted before this split was made. The + likely cause, inferred and not measured: an inequality on a FSST vector + has no code path (Task 5 evaluates on STR_DICT codes only), so gen 2 + decodes the FSST vectors that q18's profile shows to be costly, while + gen 0 reads plain descriptors. + - The other FAIL rows: q11 1.68 and q14 1.75 (STR count-distinct, which + materializes), q33 1.073 and q42 1.073 (non-STR, the P4 Ruling 10-7 class). + - The fix belongs to the controller's ruling. Candidates: a vector-scope + FSST fast decode (the 8b pattern); equality and inequality of a constant + on FSST vectors without decoding (compress the constant); building the + runtime DICT whenever the column's STR_DICT entries plus its decoded + non-dictionary vectors cover it (relaxing "every vector STR_DICT"). +- **O5, STR group-by against BASE** (5 alternated rounds; arm C: the BASE + and P6 binaries on g0; arm D: BASE on its own gen-2 save, RAW / CONST STR, + against P6 on g2): + - Arm C, gen 0: at parity (0.98-1.03) except q29 at 1.365 (see below). + - Arm D: P6's STR_DICT / FSST g2 is slower than BASE's RAW g2 on the STR + group-by and filter queries: q13 1.96, q15 1.91, q17 2.10, q18 2.37, + q19 1.97, q37 2.10, q39 14.4, q40 1.70, q22 1.39. It is faster where the + dictionary pays (q12 0.59, q38 0.64) and level on q14, q23, q29 and + q34 / q35. + + So the P3 carry ("gen-2 STR group-by ~3x BASE") is not closed on real + data. The remap helps STR_DICT vectors, but the FSST vectors that + dominate URL, Title and SearchPhrase cost more per row than BASE's RAW + cursor read. +- **q29, gen 0: 1.365x BASE on the STR store.** The cause is layout, not + P6 logic; it goes to the controller. On the STR g0 store, q29's per-group + `(strlen Referer)` runs `strlen_sym_task`, and `ray_sym_str` takes the + global spinlock `g_sym_lock` per element: 90-95% of the query. Bisected on + a 2M-row copy (median of 5 runs, ms): + + | binary | ms | + |---|---| + | BASE 9802ba80 | 255-281 | + | c8eb63b1 | 275-280 | + | 802fc803 | 230-237 | + | b08886cd | 378-424 | + | 6c20099b | 379-416 | + | 622a039b | 419-446 | + | 00fc4a90 | 374-418 | + + b08886cd touches only `src/store/enc*` (gen-2 code). Its new statics move + `.bss` by 0x20, which puts `g_sym_lock` on the same 64-byte line as `g_sym` + (0x9af900-0x9af93f; in 802fc803 they are on separate lines). Every + acquire of the lock then invalidates the line that every reader needs: + false sharing. The hot spot itself, a per-element global lock in parallel + SYM `strlen`, predates P6. On the SYM ClickBench store q29 is at parity + (C0 1.004, 346 ms), where the same query takes 1.4-2.2 s on the STR g0 + store. Recommendation: put `g_sym_lock` on its own cache line, and look + up the string once per symbol (not per element) in `strlen_sym_task`. Not + changed here. +- **Rulings 6-2 / 7-1 (materialization shapes).** + - `count s by s` with no filter (q34 / q35, URL) materializes URL on g2: + the 7-1 shape, measured at 16x warm, 1.7 s first run. + - The filtered `count s by s` queries (q13 SearchPhrase, q37 URL, q38 + Title) materialize nothing. + - Computed composite keys: q19's `(minute EventTime)` materializes + EventTime, a non-STR column, as at P3. q42's computed STR key `(if ... + Referer "")` and q43's `xbar` materialize nothing. + + The STR form of 6-2 did not show in the query set. STR columns left + materialized: q11 MobilePhoneModel and q14 SearchPhrase (count distinct); + q21-q23 and q28 (LIKE, strlen); q26 / q27 (sort keys); q29 Referer + (strlen); q34 / q35. All are in P3's allowed classes. +- **Parted STR arm (R2): run, not skipped.** Ten 1M-row partitions per + store, each derived from its own slice of the source: p0 4.70 GB, p2 1.64 + GB, one store at a time under the guard. All 43 queries present, answers + p2 = p0. Informational ratios: q39 13.6x; q17 1.43, q18 1.32, q19 1.17, + q40 1.17. Most other queries are at or under 1.0, because gen 0 has no + cross-segment DICT path either. The first attempt sliced the derived + table, and its STR slices kept the parent's pool. A gen-0 save writes + that pool tail, so each partition was 2.9 GB and the disk filled (`io`; the + partial store was deleted at once). That reproduces on dev 2129b8aa + (filed as #884, with a repro). +- **Disk.** Peak scratch was 8.20 GB at prep, with g0 and g2 present (3.11 + GB free). The low point was 2.88 GB free, during the failed first parted + attempt above. Every store was deleted after its stage. + +Step 1, the suites (logs under /home/hetoku/data/tmp/p6/t8/), all run +before any benchmark: + +| run | result | runtime errors | +|---|---|---| +| debug `make test` (full) | 6009/6009, 0 failed | 0 | +| debug `encstr/`, default cores | 40/40 | 0 | +| debug `encstr/`, `TEST_CORES=8` | 40/40 | 0 | +| debug `equiv/` | 1180/1180 | 0 | +| `make test-large` | 5/5 | 0 | +| release FP profile `encstr/` (`make test-release`) | 40/40 | - | +| informational (O3), release FP profile `aware/` | 95/95 | - | + +### P2/P3 driver rerun against BASE 9802ba80 (I8) + +`W=/home/hetoku/data/tmp/p6/t8/p2_bench BASE=9802ba80 p2_bench.sh prep`, +then `splayed` and `parted` (17:08-18:44), run after the STR stores were +deleted, with 11.97 GB free against the stage guard's 11.81 GB. The P6 +binary is 00fc4a90 (e658455568da), base 9802ba80 (0e3c5aae6df3). +`p3_summary.py` is unchanged. Raw data: /home/hetoku/data/tmp/p6/t8/p2_bench/p2.tsv +and summary.txt. + +``` +totals over all 43: warm 1711.3 vs 1648.7 (0.963); first run 2529.2 vs 2708.5 (1.071); 3-run 6023.0 vs 6084.9 (1.010) +answer_mismatches none +scan_only(gated) n=28; gmeans over base>=1ms (per column): warm n=22 0.582, first n=23 0.701, cold n=23 0.346; worst warm=1.166 +scan_only_list_but_materializing none +worst5 warm [(1.166, 'q6'), (1.12, 'q5'), (1.113, 'q4'), (1.094, 'q7'), (1.067, 'q33')] +totals over all 43: warm 4673.2 vs 2899.5 (0.620); first run 16262.2 vs 13906.6 (0.855); 3-run 25782.5 vs 19857.1 (0.770) +answer_mismatches none +scan_only(gated) n=34; gmeans over base>=1ms (per column): warm n=33 0.179, first n=33 0.253, cold n=33 0.146; worst warm=1.028 +scan_only_list_but_materializing none +worst5 warm [(1.028, 'q28'), (1.019, 'q33'), (1.017, 'q32'), (1.016, 'q15'), (1.012, 'q13')] +totals over all 43: warm 1709.9 vs 1714.1 (1.002); first run 2545.6 vs 2541.0 (0.998); 3-run 6033.7 vs 6028.7 (0.999) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=35)=0.998 warm_worst=1.175 worst5 [(1.175, 'q30'), (1.125, 'q25'), (1.05, 'q2'), (1.028, 'q7'), (1.024, 'q28')] +totals over all 43: warm 4666.4 vs 4678.5 (1.003); first run 16289.1 vs 16321.6 (1.002); 3-run 25806.8 vs 25863.6 (1.002) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=42)=1.000 warm_worst=1.024 worst5 [(1.024, 'q7'), (1.023, 'q2'), (1.013, 'q6'), (1.013, 'q12'), (1.011, 'q36')] +q16 first run base 98.7 ms, p2 99.0 ms (carry 2) +totals over all 43: warm 4429.0 vs 4443.3 (1.003); first run 16152.9 vs 16148.0 (1.000); 3-run 25222.4 vs 25195.7 (0.999) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=42)=1.001 warm_worst=1.085 worst5 [(1.085, 'q1'), (1.025, 'q14'), (1.024, 'q7'), (1.013, 'q11'), (1.011, 'q18')] +enc A: columns with DELTA vectors: ['UserID {raw:76 const:3 delta_bp:97 rle:9526 dict:64}] +enc B: columns with DELTA vectors: ['UserID {raw:75 const:3 delta_bp:89 rle:8963 dict:640}] +sizes {('A', 'g0'): 5948677939, ('A', 'g2'): 3216455899, ('B', 'p0'): 4807844987, ('B', 'p2'): 2072366907} peak_rss_kb {('A', 'g0'): 5120292, ('A', 'g2'): 5954800, ('B', 'p0'): 12146240, ('B', 'p2'): 11970140} evict_modes fadvise ragged_partition ['9', '40'] meta {'p2': ['00fc4a90', 'e658455568da'], 'base': ['9802ba80', '0e3c5aae6df3']} +GATE (strict) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=FAIL] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (strict): FAIL +GATE (P3-exempt) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[answers=PASS warm=PASS cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[answers=PASS warm=FAIL q16_first=FAIL] gen0-ragged[answers=PASS warm=FAIL] +P2 GATE (P3-exempt): FAIL +P3-EXEMPT LIST +p3_unexpected_materializations none +rss A: 5120292 -> 5954800 kB (x1.163 over all 43, bound 1.1) +rss A without D2 q41,q42: 5100968 -> 5063280 kB (x0.993, bound 1.1, gated) +rss B: 12146240 -> 11970140 kB (x0.986 over all 43, bound 1.1) +P3GATE p2_strict=FAIL materialization=PASS rss=PASS +P3 GATE: FAIL +``` + +**P2/P3 rerun strict line: FAIL by the letter** (`P2 GATE (strict): FAIL`; +`P3 GATE: FAIL` through `p2_strict`). Materialization PASS, RSS PASS +(x0.993 without D2, x0.986 parted), and answers PASS on every arm. Sizes are +byte-identical to P5's rerun: P6 does not change the SYM store's bytes. +Each failing clause: + +1. **Splayed warm (A): q33 1.067.** Ruling 10-7, accepted; P5 had 1.068. + q4-q7 above 1.05 are sub-ms rows inside the noise floor. +2. **Gen-0 splayed warm (C0): q25, 0.89 -> 1.00 ms (1.125).** The gap is + 0.11 ms against the 0.05 ms floor: Ruling 14-8's sub-ms class (P4: q25 / + q27; P5: q27). Gmean 0.998. +3. **Gen-0 parted q16_first: base 98.7 ms, P6 99.0 ms.** Ruling 10-5, + accepted. +4. **New: gen-0 parted warm (C1) and gen-0 ragged warm (R) FAIL on the + gmean clause only.** The gmeans are 1.0005 and 1.0005 (C1: 42 queries + with base >= 1 ms, worst 1.024 q7; R: worst 1.085 q1, which is sub-ms). + The bound is `<= 1.00`. P5's rerun had 0.999 for both. No query in + either arm is over 1.05 outside the floor. This is not covered by an + earlier ruling, so it goes to the controller. The size is noise (0.05%), + but it is reported, not waived. + +**P6 gate (STR round trip): PASS** (every STR column element-identical, 5 columns) +**P6 gate (DICT index equal to generation 0 on all-STR_DICT columns): FAIL** (not exercised: no all-STR_DICT column) +**P6 STR store, all 43 queries present (and no run failed) in warm, cold, wall and ident: PASS** +**P6 STR store, answers g2 = g0: PASS** +**P6 STR store, scan-only warm (no regression, <= 1.05 per query): FAIL** (worst 113.340, q18, max(timeit 113.340, wall 110.924) CHECK) + +## P6b persisted STR DICT (STR store derived from the 10M splayed store, release build, commit 29e54038) + +Driver: `W=/home/hetoku/data/tmp/p6b/t8/bench bench/compress_estimate/p6_bench.sh all`, +stages prep, enc, mat, ident, warm, cold, wall, o5, i8, clean, savet and +parted (12:26-15:40 on 2026-10-18). A first start at 12:24 was stopped in +prep by me before any store was written: the brief's `estimate_dict` used a +four-argument `+`, which the language rejects (`arity`), so the DICT +estimate was empty and the g2 guard would have been 3 GB instead of the +estimate plus 3 GB. The expression now nests binary `+`, and prep exits +when the estimate is empty or zero. Binary 29e54038, release build (sha256 +11b110c652ed). BASE is 9802ba80, as in P6 (sha256 e382892f42f5 here; P6's +section records 0e3c5aae6df3 for the same commit, a difference not +investigated). The store is P6's: the 25 columns the 43 queries read from +`/skull/clickbench/rfsplayed` (9 999 505 rows), the five text columns cast +SYM -> STR. Protocol unchanged from P6: 9 warm rounds and 5 wall rounds, +alternated; 3 cold trials with per-file eviction; ident runs g0 twice; 5 +rounds for o5 (arms C and D), i8 and parted; 3 savet rounds; the load average +checked before each round (66 waits, 12:36-15:36). Arm C now runs all 43 +queries on the STR g0 store (I8, D18); arm D keeps the 18 STR group-by +queries; the new `i8` stage runs BASE vs P6b on the SYM store read in place +from `/skull/clickbench/rfsplayed` (nothing copied, nothing written). +`p6_dictcheck` checks the persisted DICT of every STR column that generation +0 indexes: before materialization (the region through `ray_enccol_idict` and +the code tier `ray_enccol_idict_codes_vec`) and after it (the index attached +to the materialized root), against generation 0's DICT (codes, first +occurrences, n_distinct), along with every element. Raw data: +/home/hetoku/data/tmp/p6b/t8/bench/p6.tsv, summary.txt beside it; P6's +references in /home/hetoku/data/tmp/p6b/t8/p6-ref/. + +Disk. Free on / when the gate started: 11 949 789 184 B. Guards (need / +available, B): prep g0 10 055 388 975 / 12 003 774 464 (estimate 5 760 421 679 ++ 4 GB); prep g2 4 519 876 348 / 6 413 803 520 (DICT estimate 1 298 650 876 ++ 3 GB); o5 bg2 5 567 618 389 / 8 635 609 088 (0.9 size(g0) + 0.5 GB); savet +8 132 814 379 / at least 12 529 270 784 (six checks; estimate + DICT +estimate + 1 GB); parted p0 10 055 388 975 / 12 528 939 008; parted p2 +4 519 876 348 / 7 832 621 056. No guard refused and no post-save check +fired (0.5 GB after g2, 0.3 GB after bg2). Peak scratch was 9 499 516 822 B +at prep with g0 and g2 present, which is also the lowest free point +(2 511 122 432 B); o5 peak 8 858 734 871 B (3 701 592 064 B free); parted +peak 7 800 378 845 B (4 748 951 552 B free). Every store was deleted after +its stage. + +Step 1, the suites (logs under /home/hetoku/data/tmp/p6b/t8/), all run +before any benchmark: + +| run | result | runtime errors | +|---|---|---| +| debug `make test` (full) | 6035/6035, 0 failed | 0 | +| debug `encstr/`, default cores | 54/54 | 0 | +| debug `encstr/`, `TEST_CORES=8` | 54/54 | 0 | +| debug `idxval/` | 78/78 | 0 | +| debug `equiv/` | 1181/1181 | 0 | +| `make test-large` | 5/5 | 0 | +| release FP profile `encstr/` (`make test-release`) | 54/54 | - | + +summary.txt, as printed: + +``` +meta {'p6': ['29e54038', '11b110c652ed'], 'base': ['9802ba80', 'e382892f42f5']} +| column | g0 DICT | g2 kind (recorded) | region equal (codes, first occurrences, n_distinct) | root equal (after materialization) | elements equal | vectors | STR_DICT vectors | n_distinct g0 | n_distinct g2 | +|---|---|---|---|---|---|---|---|---|---| +| URL | true | dict | true | true | true | 9766 | 4928 | 2620031 | 2620031 | +| Title | true | dict | true | true | true | 9766 | 3339 | 1602929 | 1602929 | +| Referer | true | dict | true | true | true | 9766 | 6144 | 2718828 | 2718828 | +| MobilePhoneModel | true | dict | true | true | true | 9766 | 9058 | 91 | 91 | +| SearchPhrase | true | dict | true | true | true | 9766 | 770 | 834981 | 834981 | + +| column | g0 file B | g2 encoded B | raw B (.idx.info) | g0 / g2 | mix | +|---|---|---|---|---|---| +| WatchID | 588420000 | 589031872 | 79996040 | 1.00x | {raw:9702 dict:64} | +| EventTime | 79998848 | 59112600 | 79996040 | 1.35x | {raw:1 for_bp:9237 rle:464 dict:64} | +| EventDate | 40000832 | 563040 | 39998020 | 71.04x | {const:9634 rle:132} | +| CounterID | 40000832 | 560760 | 39998020 | 71.33x | {const:9687 rle:79} | +| ClientIP | 40000832 | 10639528 | 39998020 | 3.76x | {raw:228 const:3 rle:9535} | +| RegionID | 40000832 | 8934824 | 39998020 | 4.48x | {const:3 for_bp:1508 rle:8255} | +| UserID | 79998848 | 16765104 | 79996040 | 4.77x | {raw:76 const:3 delta_bp:97 rle:9526 dict:64} | +| URL (STR) | 1073152224 | 807061568 | 718229513 | 1.33x | {str_dict:4928 fsst:4838} | +| Title (STR) | 1306275776 | 777871520 | 913412536 | 1.68x | {const:328 str_dict:3339 fsst:6099} | +| Referer (STR) | 1046435104 | 856051552 | 649408230 | 1.22x | {str_dict:6144 fsst:3622} | +| IsRefresh | 20001824 | 1755280 | 19999010 | 11.40x | {const:5 for_bp:8347 rle:1414} | +| ResolutionWidth | 20001824 | 5706328 | 19999010 | 3.51x | {raw:1 const:331 for_bp:839 rle:8592 dict:3} | +| MobilePhone | 20001824 | 1627680 | 19999010 | 12.29x | {const:300 for_bp:56 rle:9347 dict:63} | +| MobilePhoneModel (STR) | 200013952 | 41702880 | 159992268 | 4.80x | {const:708 str_dict:9058} | +| SearchEngineID | 20001824 | 6629840 | 19999010 | 3.02x | {raw:1 const:126 for_bp:2203 rle:6809 dict:627} | +| SearchPhrase (STR) | 284560672 | 148787680 | 241091612 | 1.91x | {const:137 str_dict:770 fsst:8859} | +| AdvEngineID | 20001824 | 1273424 | 19999010 | 15.71x | {const:2502 for_bp:309 rle:6718 dict:237} | +| IsLink | 20001824 | 695648 | 19999010 | 28.75x | {const:8684 for_bp:1057 rle:25} | +| IsDownload | 20001824 | 593104 | 19999010 | 33.72x | {const:9156 for_bp:78 rle:532} | +| DontCountHits | 20001824 | 722576 | 19999010 | 27.68x | {const:8240 for_bp:1092 rle:434} | +| TraficSourceID | 20001824 | 4427096 | 19999010 | 4.52x | {const:1 for_bp:7298 rle:29 dict:2438} | +| URLHash | 275928576 | 263989472 | 79996040 | 1.05x | {raw:3946 rle:5756 dict:64} | +| RefererHash | 274911456 | 272463680 | 79996040 | 1.01x | {raw:8563 rle:1139 dict:64} | +| WindowClientWidth | 20001824 | 12725264 | 19999010 | 1.57x | {raw:2 const:330 for_bp:7554 rle:1878 dict:2} | +| WindowClientHeight | 20001824 | 12540552 | 19999010 | 1.59x | {raw:17 const:329 for_bp:7474 rle:1945 dict:1} | + +store: g0 5589719419 B (estimate 5760421679), g2 3902233443 B (x0.698); save g0 49672 ms, g2 175012 ms (prep, one run) + +| STR column | DICT region B | +|---|---| +| URL | 374265376 | +| Title | 327095040 | +| Referer | 454367776 | +| SearchPhrase | 102918496 | +| MobilePhoneModel | 40000000 | +| sum | 1298646688 | + +DICT region bytes: sum 1298646688 B (DICT estimate 1298650876 B); g2 3902233443 B, P6's g2 2603586739 B (/home/hetoku/data/tmp/p6b/t8/bench/../p6-ref/p6.tsv): g2 / P6's g2 1.499 +BASE's generation-2 save of the same table (o5, RAW / CONST STR): 4933804739 B, save 35079 ms +disk: prep: scratch 9499516822 B, free 2511122432 B; o5: scratch 8858734871 B, free 3701592064 B; parted: scratch 7800378845 B, free 4748951552 B + +| writer (O2) | save g0 ms | save g2 ms | g2 / g0 | g0 B | g2 B | runs | +|---|---|---|---|---|---|---| +| p6 | 33114 | 174017 | 5.255 | 5589719419 | 3902233443 | 3 | +| base | 34938 | 35469 | 1.015 | 5589719419 | 4933804739 | 3 | + +save g2 p6 / base: 4.906; save g0 p6 / base: 0.948 + +| query | warm g0 | warm g2 | ratio | first g0 | first g2 | cold g0 | cold g2 | ratio | answers | g2 materializes | +|---|---|---|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.043 | 0.01 | 0.01 | 0.0 | 0.0 | 0.806 | same | scan | +| q2 | 0.68 | 0.49 | 0.722 | 1.66 | 1.30 | 38.4 | 3.5 | 0.091 | same | scan | +| q3 | 3.82 | 0.00 | 0.001 | 5.62 | 0.05 | 94.3 | 0.0 | 0.000 | same | scan | +| q4 | 0.00 | 0.00 | 1.154 | 0.03 | 0.04 | 0.0 | 0.0 | 1.305 | same | scan | +| q5 | 0.00 | 0.00 | 1.138 | 0.03 | 0.04 | 0.0 | 0.0 | 1.426 | same | scan | +| q6 | 0.00 | 0.00 | 1.154 | 0.03 | 0.03 | 0.0 | 0.0 | 1.100 | same | scan | +| q7 | 0.00 | 0.00 | 1.064 | 0.02 | 0.04 | 0.0 | 0.0 | 2.074 | same | scan | +| q8 | 3.59 | 2.98 | 0.831 | 9.04 | 8.27 | 41.1 | 9.2 | 0.223 | same | scan | +| q9 | 76.27 | 75.57 | 0.991 | 111.80 | 128.52 | 650.7 | 155.5 | 0.239 | same | mat: RegionID UserID | +| q10 | 71.02 | 71.63 | 1.009 | 98.43 | 119.69 | 408.9 | 158.5 | 0.388 | same | mat: RegionID UserID | +| q11 | 64.52 | 13.29 | 0.206 | 71.97 | 71.11 | 293.0 | 166.3 | 0.568 | same | mat: UserID MobilePhoneModel | +| q12 | 67.38 | 37.41 | 0.555 | 70.52 | 45.70 | 253.2 | 148.1 | 0.585 | same | scan | +| q13 | 80.22 | 15.96 | 0.199 | 93.76 | 79.93 | 168.8 | 280.9 | 1.664 | same | scan | +| q14 | 240.66 | 162.68 | 0.676 | 337.31 | 569.88 | 556.8 | 828.6 | 1.488 | same | mat: UserID SearchPhrase | +| q15 | 93.42 | 26.51 | 0.284 | 102.53 | 87.90 | 213.3 | 322.2 | 1.511 | same | scan | +| q16 | 70.55 | 62.33 | 0.884 | 96.08 | 87.72 | 243.9 | 163.8 | 0.671 | same | scan | +| q17 | 91.98 | 86.45 | 0.940 | 128.72 | 167.08 | 469.2 | 435.5 | 0.928 | same | scan | +| q18 | 7.00 | 4.10 | 0.585 | 13.80 | 55.41 | 655.6 | 289.4 | 0.441 | same | scan | +| q19 | 138.36 | 133.28 | 0.963 | 209.81 | 250.28 | 672.4 | 642.4 | 0.955 | same | mat: EventTime | +| q20 | 1.16 | 0.59 | 0.511 | 6.89 | 5.89 | 55.4 | 16.7 | 0.301 | same | scan | +| q21 | 107.39 | 110.26 | 1.027 | 108.00 | 1325.76 | 112.0 | 3433.2 | 30.661 | same | mat: URL | +| q22 | 176.66 | 115.85 | 0.656 | 179.52 | 1393.03 | 218.4 | 3735.6 | 17.103 | same | mat: URL | +| q23 | 286.57 | 227.08 | 0.792 | 293.83 | 3469.69 | 591.9 | 7717.0 | 13.039 | same | mat: UserID URL Title SearchPhrase | +| q24 | 76.63 | 237.56 | 3.100 | 78.64 | 443.31 | 181.3 | 1455.5 | 8.028 | same | mat: EventTime | +| q25 | 0.96 | 10.45 | 10.900 | 2.39 | 152.07 | 77.3 | 975.0 | 12.611 | same | mat: EventTime | +| q26 | 12.77 | 21.04 | 1.647 | 14.62 | 410.69 | 169.2 | 1155.3 | 6.827 | same | mat: SearchPhrase | +| q27 | 0.96 | 9.20 | 9.564 | 2.38 | 416.43 | 78.7 | 1338.2 | 17.006 | same | mat: EventTime SearchPhrase | +| q28 | 111.48 | 45.84 | 0.411 | 114.03 | 1271.28 | 177.0 | 4058.6 | 22.927 | same | mat: URL | +| q29 | 1216.30 | 422.58 | 0.347 | 1380.18 | 1725.27 | 1412.7 | 4615.9 | 3.267 | same | mat: Referer | +| q30 | 0.02 | 0.02 | 0.998 | 2.76 | 4.62 | 56.2 | 11.3 | 0.202 | same | mat: ResolutionWidth | +| q31 | 112.68 | 179.90 | 1.597 | 129.09 | 276.01 | 306.7 | 536.5 | 1.749 | same | scan | +| q32 | 120.74 | 186.88 | 1.548 | 144.89 | 291.58 | 436.8 | 685.7 | 1.570 | same | scan | +| q33 | 204.33 | 220.13 | 1.077 | 362.62 | 379.30 | 609.9 | 621.1 | 1.018 | same | scan | +| q34 | 28.20 | 28.28 | 1.003 | 52.06 | 273.32 | 127.2 | 1172.3 | 9.217 | same | scan | +| q35 | 28.26 | 28.55 | 1.010 | 52.05 | 270.91 | 128.2 | 1172.8 | 9.146 | same | scan | +| q36 | 64.55 | 61.51 | 0.953 | 87.42 | 82.62 | 160.7 | 125.5 | 0.781 | same | scan | +| q37 | 20.72 | 9.43 | 0.455 | 30.99 | 238.44 | 48.0 | 1138.1 | 23.718 | same | scan | +| q38 | 19.28 | 8.00 | 0.415 | 28.98 | 169.19 | 45.0 | 875.7 | 19.455 | same | scan | +| q39 | 7.37 | 4.99 | 0.678 | 14.87 | 231.14 | 42.2 | 1130.1 | 26.754 | same | scan | +| q40 | 110.48 | 242.35 | 2.193 | 203.90 | 454.49 | 217.7 | 1124.7 | 5.166 | same | scan | +| q41 | 5.77 | 4.69 | 0.813 | 13.50 | 70.44 | 73.6 | 554.4 | 7.537 | same | mat: RefererHash | +| q42 | 4.50 | 4.69 | 1.042 | 11.23 | 71.91 | 37.1 | 547.4 | 14.753 | same | mat: URLHash | +| q43 | 9.10 | 7.70 | 0.847 | 18.76 | 17.23 | 40.1 | 26.0 | 0.648 | same | scan | + +| query | wall g0 ms/call | wall g2 ms/call | ratio | rounds | +|---|---|---|---|---| +| q1 | -0.036 | -0.002 | 1.000 (floored) | 5 | +| q2 | 0.602 | 0.429 | 0.713 | 5 | +| q3 | 3.743 | 0.006 | 0.013 (floored) | 5 | +| q4 | 3.051 | -0.001 | 0.016 (floored) | 5 | +| q5 | 41.437 | 41.365 | 0.998 | 5 | +| q6 | 67.486 | 67.201 | 0.996 | 5 | +| q7 | 0.020 | 0.003 | 1.000 (floored) | 5 | +| q8 | 3.474 | 2.991 | 0.861 | 5 | +| q9 | 76.340 | 77.184 | 1.011 | 5 | +| q10 | 70.960 | 73.579 | 1.037 | 5 | +| q11 | 64.631 | 13.532 | 0.209 | 5 | +| q12 | 67.869 | 37.919 | 0.559 | 5 | +| q13 | 80.184 | 16.247 | 0.203 | 5 | +| q14 | 242.749 | 163.739 | 0.675 | 5 | +| q15 | 91.397 | 26.459 | 0.289 | 5 | +| q16 | 72.331 | 62.850 | 0.869 | 5 | +| q17 | 93.005 | 86.669 | 0.932 | 5 | +| q18 | 7.225 | 4.195 | 0.581 | 5 | +| q19 | 138.986 | 134.751 | 0.970 | 5 | +| q20 | 1.119 | 0.630 | 0.563 | 5 | +| q21 | 108.707 | 112.661 | 1.036 | 5 | +| q22 | 177.400 | 116.411 | 0.656 | 5 | +| q23 | 289.195 | 226.806 | 0.784 | 5 | +| q24 | 77.510 | 239.579 | 3.091 | 5 | +| q25 | 0.731 | 10.498 | 14.361 | 5 | +| q26 | 12.890 | 21.297 | 1.652 | 5 | +| q27 | 1.140 | 9.116 | 7.996 | 5 | +| q28 | 111.603 | 46.901 | 0.420 | 5 | +| q29 | 1199.477 | 422.733 | 0.352 | 5 | +| q30 | 0.055 | 0.098 | 1.782 | 5 | +| q31 | 113.464 | 180.281 | 1.589 | 5 | +| q32 | 120.405 | 186.560 | 1.549 | 5 | +| q33 | 207.563 | 220.944 | 1.064 | 5 | +| q34 | 28.448 | 28.528 | 1.003 | 5 | +| q35 | 28.520 | 28.568 | 1.002 | 5 | +| q36 | 66.301 | 61.129 | 0.922 | 5 | +| q37 | 20.698 | 9.188 | 0.444 | 5 | +| q38 | 19.615 | 8.028 | 0.409 | 5 | +| q39 | 7.329 | 4.935 | 0.673 | 5 | +| q40 | 111.680 | 243.143 | 2.177 | 5 | +| q41 | 5.474 | 4.589 | 0.838 | 5 | +| q42 | 4.475 | 4.586 | 1.025 | 5 | +| q43 | 9.277 | 7.806 | 0.841 | 5 | + +| query | scan-only ratio g2 / g0 | source | g2 materializes | +|---|---|---|---| +| q1 | 1.000 | wall (floored) | scan | +| q2 | 0.722 | max(timeit 0.722, wall 0.713) | scan | +| q3 | 0.013 | max(timeit 0.001, wall 0.013) | scan | +| q4 | 0.016 | wall (floored) | scan | +| q5 | 0.998 | wall | scan | +| q6 | 0.996 | wall | scan | +| q7 | 1.000 | wall (floored) | scan | +| q8 | 0.861 | max(timeit 0.831, wall 0.861) | scan | +| q9 | 1.011 | max(timeit 0.991, wall 1.011) | mat: RegionID UserID | +| q10 | 1.037 | max(timeit 1.009, wall 1.037) | mat: RegionID UserID | +| q11 | 0.209 | max(timeit 0.206, wall 0.209) | mat: UserID MobilePhoneModel | +| q12 | 0.559 | max(timeit 0.555, wall 0.559) | scan | +| q13 | 0.203 | max(timeit 0.199, wall 0.203) | scan | +| q14 | 0.676 | max(timeit 0.676, wall 0.675) | mat: UserID SearchPhrase | +| q15 | 0.289 | max(timeit 0.284, wall 0.289) | scan | +| q16 | 0.884 | max(timeit 0.884, wall 0.869) | scan | +| q17 | 0.940 | max(timeit 0.940, wall 0.932) | scan | +| q18 | 0.585 | max(timeit 0.585, wall 0.581) | scan | +| q19 | 0.970 | max(timeit 0.963, wall 0.970) | mat: EventTime | +| q20 | 0.563 | max(timeit 0.511, wall 0.563) | scan | +| q21 | 1.036 | max(timeit 1.027, wall 1.036) | mat: URL | +| q22 | 0.656 | max(timeit 0.656, wall 0.656) | mat: URL | +| q23 | 0.792 | max(timeit 0.792, wall 0.784) | mat: UserID URL Title SearchPhrase | +| q24 | 3.100 | max(timeit 3.100, wall 3.091) | mat: EventTime | +| q25 | 14.361 | max(timeit 10.900, wall 14.361) CHECK | mat: EventTime | +| q26 | 1.652 | max(timeit 1.647, wall 1.652) | mat: SearchPhrase | +| q27 | 9.564 | max(timeit 9.564, wall 7.996) CHECK | mat: EventTime SearchPhrase | +| q28 | 0.420 | max(timeit 0.411, wall 0.420) | mat: URL | +| q29 | 0.352 | max(timeit 0.347, wall 0.352) | mat: Referer | +| q30 | 1.782 | wall | mat: ResolutionWidth | +| q31 | 1.597 | max(timeit 1.597, wall 1.589) | scan | +| q32 | 1.549 | max(timeit 1.548, wall 1.549) | scan | +| q33 | 1.077 | max(timeit 1.077, wall 1.064) | scan | +| q34 | 1.003 | max(timeit 1.003, wall 1.003) | scan | +| q35 | 1.010 | max(timeit 1.010, wall 1.002) | scan | +| q36 | 0.953 | max(timeit 0.953, wall 0.922) | scan | +| q37 | 0.455 | max(timeit 0.455, wall 0.444) | scan | +| q38 | 0.415 | max(timeit 0.415, wall 0.409) | scan | +| q39 | 0.678 | max(timeit 0.678, wall 0.673) | scan | +| q40 | 2.193 | max(timeit 2.193, wall 2.177) | scan | +| q41 | 0.838 | max(timeit 0.813, wall 0.838) | mat: RefererHash | +| q42 | 1.042 | max(timeit 1.042, wall 1.025) | mat: URLHash | +| q43 | 0.847 | max(timeit 0.847, wall 0.841) | scan | + +STR columns left materialized on g2 (mat stage): q11 MobilePhoneModel, q14 SearchPhrase, q21 URL, q22 URL, q23 URL+Title+SearchPhrase, q26 SearchPhrase, q27 SearchPhrase, q28 URL, q29 Referer + +| query | C: g0 base | C: g0 p6 | ratio | D: base on its gen-2 save | D: p6 on g2 | ratio | p6 g2 / p6 g0 (warm stage) | +|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 1.040 | nan | nan | nan | 1.043 | +| q2 | 0.64 | 0.67 | 1.046 | nan | nan | nan | 0.722 | +| q3 | 3.80 | 3.80 | 0.998 | nan | nan | nan | 0.001 | +| q4 | 0.00 | 0.00 | 1.061 | nan | nan | nan | 1.154 | +| q5 | 0.00 | 0.00 | 1.044 | nan | nan | nan | 1.138 | +| q6 | 0.00 | 0.00 | 1.066 | 0.00 | 0.00 | 1.030 | 1.154 | +| q7 | 0.00 | 0.00 | 0.925 | nan | nan | nan | 1.064 | +| q8 | 3.62 | 3.57 | 0.987 | nan | nan | nan | 0.831 | +| q9 | 77.50 | 75.94 | 0.980 | nan | nan | nan | 0.991 | +| q10 | 70.94 | 69.05 | 0.973 | nan | nan | nan | 1.009 | +| q11 | 64.72 | 64.01 | 0.989 | 101.64 | 13.67 | 0.135 | 0.206 | +| q12 | 68.01 | 67.60 | 0.994 | 67.78 | 37.12 | 0.548 | 0.555 | +| q13 | 80.76 | 80.10 | 0.992 | 194.81 | 15.93 | 0.082 | 0.199 | +| q14 | 242.65 | 240.74 | 0.992 | 413.44 | 163.27 | 0.395 | 0.676 | +| q15 | 91.85 | 90.99 | 0.991 | 201.99 | 26.45 | 0.131 | 0.284 | +| q16 | 71.25 | 70.58 | 0.991 | nan | nan | nan | 0.884 | +| q17 | 95.26 | 91.64 | 0.962 | 418.41 | 85.97 | 0.205 | 0.940 | +| q18 | 7.00 | 7.14 | 1.020 | 333.99 | 4.12 | 0.012 | 0.585 | +| q19 | 136.25 | 139.27 | 1.022 | 468.13 | 134.24 | 0.287 | 0.963 | +| q20 | 1.17 | 1.18 | 1.002 | nan | nan | nan | 0.511 | +| q21 | 106.68 | 107.54 | 1.008 | nan | nan | nan | 1.027 | +| q22 | 175.97 | 176.71 | 1.004 | 177.05 | 116.28 | 0.657 | 0.656 | +| q23 | 287.27 | 286.80 | 0.998 | 294.82 | 226.79 | 0.769 | 0.792 | +| q24 | 75.76 | 76.68 | 1.012 | nan | nan | nan | 3.100 | +| q25 | 0.96 | 0.97 | 1.007 | nan | nan | nan | 10.900 | +| q26 | 13.03 | 12.80 | 0.982 | nan | nan | nan | 1.647 | +| q27 | 0.94 | 0.95 | 1.003 | nan | nan | nan | 9.564 | +| q28 | 107.70 | 111.97 | 1.040 | nan | nan | nan | 0.411 | +| q29 | 1398.24 | 1144.08 | 0.818 | 522.00 | 421.62 | 0.808 | 0.347 | +| q30 | 0.02 | 0.03 | 1.433 | nan | nan | nan | 0.998 | +| q31 | 111.23 | 112.23 | 1.009 | nan | nan | nan | 1.597 | +| q32 | 121.12 | 119.82 | 0.989 | nan | nan | nan | 1.548 | +| q33 | 205.53 | 207.20 | 1.008 | nan | nan | nan | 1.077 | +| q34 | 28.37 | 28.30 | 0.997 | 485.11 | 28.10 | 0.058 | 1.003 | +| q35 | 28.35 | 28.14 | 0.992 | 483.09 | 28.30 | 0.059 | 1.010 | +| q36 | 64.57 | 65.13 | 1.009 | nan | nan | nan | 0.953 | +| q37 | 20.78 | 20.54 | 0.988 | 78.09 | 8.99 | 0.115 | 0.455 | +| q38 | 19.33 | 19.69 | 1.019 | 48.86 | 7.96 | 0.163 | 0.415 | +| q39 | 7.49 | 7.38 | 0.985 | 19.34 | 5.54 | 0.286 | 0.678 | +| q40 | 111.52 | 110.17 | 0.988 | 142.07 | 243.07 | 1.711 | 2.193 | +| q41 | 5.71 | 5.71 | 1.000 | nan | nan | nan | 0.813 | +| q42 | 4.49 | 4.46 | 0.993 | nan | nan | nan | 1.042 | +| q43 | 9.12 | 9.15 | 1.003 | nan | nan | nan | 0.847 | + +| query | i8: SYM store base | i8: SYM store p6 | ratio | +|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.951 | +| q2 | 0.66 | 0.66 | 1.004 | +| q3 | 3.81 | 3.81 | 0.999 | +| q4 | 0.00 | 0.00 | 0.931 | +| q5 | 0.00 | 0.00 | 1.139 | +| q6 | 0.00 | 0.00 | 1.216 | +| q7 | 0.00 | 0.00 | 0.960 | +| q8 | 3.58 | 3.66 | 1.021 | +| q9 | 77.51 | 78.44 | 1.012 | +| q10 | 69.62 | 69.17 | 0.994 | +| q11 | 12.32 | 12.31 | 0.999 | +| q12 | 12.75 | 12.83 | 1.006 | +| q13 | 22.90 | 22.58 | 0.986 | +| q14 | 53.61 | 54.17 | 1.010 | +| q15 | 27.02 | 27.09 | 1.003 | +| q16 | 71.47 | 70.50 | 0.986 | +| q17 | 95.75 | 95.34 | 0.996 | +| q18 | 6.98 | 6.93 | 0.992 | +| q19 | 139.58 | 139.65 | 1.000 | +| q20 | 1.21 | 1.19 | 0.982 | +| q21 | 42.38 | 42.33 | 0.999 | +| q22 | 18.11 | 18.14 | 1.002 | +| q23 | 39.62 | 39.41 | 0.995 | +| q24 | 29.60 | 29.66 | 1.002 | +| q25 | 1.02 | 1.02 | 1.006 | +| q26 | 10.86 | 10.87 | 1.001 | +| q27 | 0.94 | 1.05 | 1.117 | +| q28 | 78.99 | 82.25 | 1.041 | +| q29 | 346.28 | 351.30 | 1.015 | +| q30 | 0.02 | 0.03 | 1.735 | +| q31 | 42.45 | 42.69 | 1.006 | +| q32 | 49.95 | 50.43 | 1.009 | +| q33 | 205.59 | 204.45 | 0.994 | +| q34 | 39.70 | 39.32 | 0.990 | +| q35 | 40.50 | 39.31 | 0.971 | +| q36 | 65.45 | 66.48 | 1.016 | +| q37 | 20.16 | 20.23 | 1.003 | +| q38 | 20.00 | 19.71 | 0.986 | +| q39 | 7.29 | 7.28 | 0.999 | +| q40 | 59.88 | 59.72 | 0.997 | +| q41 | 5.91 | 5.80 | 0.981 | +| q42 | 4.73 | 4.69 | 0.992 | +| q43 | 9.15 | 9.18 | 1.003 | + +parted arm (R2): p0 4695311694 B, p2 3082331918 B; STR mixes: URL {str_dict:7368 fsst:2402}; Title {const:330 str_dict:3322 fsst:6118}; Referer {str_dict:6182 fsst:3588}; MobilePhoneModel {const:697 str_dict:8480 fsst:593}; SearchPhrase {const:142 str_dict:798 fsst:8830} + +| query | warm p0 | warm p2 | ratio | first p0 | first p2 | answers | p2 materializes | +|---|---|---|---|---|---|---|---| +| q1 | 0.00 | 0.00 | 0.960 | 0.01 | 0.01 | same | scan | +| q2 | 6.71 | 6.47 | 0.965 | 17.12 | 16.41 | same | scan | +| q3 | 548.99 | 0.00 | 0.000 | 559.05 | 0.08 | same | scan | +| q4 | 284.44 | 0.00 | 0.000 | 328.21 | 0.04 | same | scan | +| q5 | 283.20 | 0.00 | 0.000 | 323.18 | 0.03 | same | scan | +| q6 | 358.36 | 360.39 | 1.006 | 632.11 | 853.11 | same | mat: SearchPhrase | +| q7 | 548.43 | 0.00 | 0.000 | 567.65 | 0.05 | same | scan | +| q8 | 6.20 | 2.27 | 0.366 | 7.74 | 3.72 | same | scan | +| q9 | 86.05 | 84.99 | 0.988 | 152.84 | 163.54 | same | mat: RegionID UserID | +| q10 | 80.87 | 81.01 | 1.002 | 158.12 | 167.45 | same | mat: RegionID UserID | +| q11 | 334.69 | 39.42 | 0.118 | 429.15 | 48.78 | same | scan | +| q12 | 339.18 | 40.69 | 0.120 | 422.87 | 48.56 | same | scan | +| q13 | 868.51 | 155.99 | 0.180 | 1125.98 | 304.46 | same | scan | +| q14 | 643.29 | 315.58 | 0.491 | 854.99 | 425.55 | same | scan | +| q15 | 874.04 | 168.60 | 0.193 | 1131.74 | 324.48 | same | scan | +| q16 | 73.29 | 62.74 | 0.856 | 102.04 | 88.98 | same | scan | +| q17 | 601.03 | 235.61 | 0.392 | 911.19 | 373.68 | same | scan | +| q18 | 590.33 | 152.45 | 0.258 | 887.82 | 260.42 | same | scan | +| q19 | 822.68 | 334.63 | 0.407 | 1368.71 | 755.96 | same | mat: EventTime | +| q20 | 4.49 | 1.49 | 0.332 | 14.30 | 11.99 | same | scan | +| q21 | 110.21 | 111.04 | 1.008 | 112.04 | 764.05 | same | mat: URL | +| q22 | 494.65 | 129.29 | 0.261 | 668.43 | 822.72 | same | mat: URL | +| q23 | 593.29 | 291.48 | 0.491 | 760.07 | 2322.91 | same | mat: URL Title | +| q24 | 110.74 | 118.39 | 1.069 | 117.16 | 819.31 | same | mat: URL | +| q25 | 392.83 | 16.82 | 0.043 | 569.86 | 72.54 | same | scan | +| q26 | 497.17 | 186.92 | 0.376 | 674.91 | 296.24 | same | scan | +| q27 | 494.71 | 174.37 | 0.352 | 683.99 | 275.22 | same | scan | +| q28 | 747.13 | 66.49 | 0.089 | 1759.36 | 1026.15 | same | mat: URL | +| q29 | 1729.83 | 1064.03 | 0.615 | 2784.07 | 3149.35 | same | mat: Referer | +| q30 | 271.80 | 273.16 | 1.005 | 289.83 | 293.47 | same | mat: ResolutionWidth | +| q31 | 422.75 | 41.21 | 0.097 | 650.55 | 90.20 | same | scan | +| q32 | 434.90 | 56.33 | 0.130 | 706.87 | 118.46 | same | scan | +| q33 | 213.84 | 218.85 | 1.023 | 380.63 | 385.66 | same | scan | +| q34 | 1088.96 | 632.26 | 0.581 | 2275.28 | 1257.38 | same | scan | +| q35 | 1082.67 | 634.89 | 0.586 | 2286.26 | 1254.74 | same | scan | +| q36 | 149.65 | 147.06 | 0.983 | 216.41 | 200.24 | same | scan | +| q37 | 724.66 | 59.90 | 0.083 | 1715.76 | 281.07 | same | scan | +| q38 | 1045.23 | 36.87 | 0.035 | 2433.14 | 200.43 | same | scan | +| q39 | 19.28 | 23.86 | 1.238 | 31.20 | 73.68 | same | scan | +| q40 | 203.05 | 238.86 | 1.176 | 347.89 | 382.69 | same | scan | +| q41 | 17.47 | 13.59 | 0.778 | 39.02 | 26.07 | same | scan | +| q42 | 13.01 | 13.52 | 1.039 | 23.45 | 23.83 | same | scan | +| q43 | 28.01 | 15.73 | 0.562 | 41.29 | 28.33 | same | scan | + +parted arm (R2): all 43 queries present: yes; answers p2 = p0: yes; warm over 1.05 with p0 >= 1 ms: q24 1.069, q39 1.238, q40 1.176 + +load waits: 66 (12:36:46/2.30, 12:39:21/3.85, 12:39:51/2.40, 12:40:21/1.52, 12:42:57/4.13, 12:43:27/2.56, 12:43:57/1.71, 12:46:33/2.42, 12:49:09/2.83, 12:49:39/1.71) + +over 1.05 (scan-only line): q24 3.100, q25 14.361, q26 1.652, q27 9.564, q30 1.782, q31 1.597, q32 1.549, q33 1.077, q40 2.193 + +**P6 gate (STR round trip): PASS** (every STR column element-identical, 5 columns) +**P6b gate (persisted DICT equal to generation 0 on every STR column generation 0 indexes): PASS** +**P6 STR store, all 43 queries present (and no run failed) in warm, cold, wall and ident: PASS** +**P6 STR store, answers g2 = g0: PASS** +**P6 STR store, scan-only warm (no regression, <= 1.05 per query): FAIL** (worst 14.361, q25) +scan-only warm over 1.05 outside accepted clauses (q33 Ruling 10-7): q24 3.100, q25 14.361, q26 1.652, q27 9.564, q30 1.782, q31 1.597, q32 1.549, q40 2.193 +**Generation 0 on the STR store, P6b vs BASE (arm C, all 43, base >= 1 ms): every query <= 1.05: PASS** (gmean 0.9916 over 34 queries (Ruling 8-1: the gmean is reported, not gated), worst q28 1.040) +**Generation 0 on the SYM store, P6b vs BASE (i8, all 43, base >= 1 ms): every query <= 1.05: PASS** (gmean 0.9997 over 35 queries (Ruling 8-1: the gmean is reported, not gated), worst q28 1.041) +**Parted STR arm (R2): answers p2 = p0, all present, warm <= 1.05 per query with p0 >= 1 ms: FAIL** (over 1.05: q24 1.069, q39 1.238, q40 1.176) +``` + +Reading the table: + +- **P6 gate (STR round trip): PASS.** All five STR columns are + element-identical between g0 and g2. +- **P6b gate (persisted DICT): PASS.** Generation 0 indexes all five STR + columns, and generation 2 records a DICT on each. The region read before + materialization and the index on the materialized root both equal + generation 0's DICT: codes, first occurrences and n_distinct (2 620 031, + 1 602 929, 2 718 828, 91 and 834 981). +- **Sizes.** The DICT regions take 1 298 646 688 B, which is the estimate + less 4 188 B. g2 is 3 902 233 443 B: 1.499x P6's g2 (2 603 586 739 B), + larger by 1 298 646 704 B, which is the region bytes plus 16 B. That is + 0.698 of g0 and 0.791 of BASE's generation-2 save (4 933 804 739 B). + MobilePhoneModel's region is 40 000 000 B (4 B per row), against 1 702 864 B + of column body in P6. +- **Writer cost (O2).** The median g2 save is 174 017 ms against BASE's + 35 469 ms (4.906; P6 measured 4.455). The g0 save is 0.948 of BASE's. +- **Answers g2 = g0: PASS**, and all 43 queries are present in warm, cold, + wall and ident: **PASS**. No query differed in either generation, so no + in-memory check was needed. +- **Scan-only warm: FAIL by the letter** (worst q25 14.361). Outside q33 + (1.077, Ruling 10-7), eight queries are over 1.05: + - q24 3.100, q25 14.361, q26 1.652 and q27 9.564. The mat stage shows + their sort keys materialized on g2 (EventTime; SearchPhrase; EventTime + and SearchPhrase). This is the gen-2 top-k sort-key materialization + that Ruling 5-1 sent to the gate. + - q30 1.782 comes from the wall stage: 0.055 vs 0.098 ms per call; timeit + gives 0.998. ResolutionWidth materializes. + - q31 1.597, q32 1.549 and q40 2.193 materialize nothing. P6 measured + 2.729, 2.603 and 2.205 for them. + - Cleared since P6's gate: q6, q11, q13-q15, q17-q19, q22, q34, q35, + q37-q39 and q42. q18 went from 113.340 to 0.585, q34 / q35 from 16.3 + to 1.003 / 1.010, and q39 from 36.861 to 0.678. +- **Generation 0 against BASE, STR store (arm C, all 43): PASS.** 34 + queries have base >= 1 ms; their gmean is 0.9916 and the worst is q28 at + 1.040. q29 is 0.818 (1398 vs 1144 ms). Below 1 ms, q30 is 1.433 at + 0.02 ms, which the gate excludes. +- **Generation 0 against BASE, SYM store (i8): PASS.** 35 queries have base + >= 1 ms; their gmean is 0.9997 and the worst is q28 at 1.041. Ruling 8-1 + covers the gmeans, which are reported and not gated. +- **Arm D (18 STR group-by queries, BASE on its RAW / CONST STR g2 vs P6b + on g2).** P6b is faster on 16 of the 18, from q18 0.012 to q29 0.808. + q40 is slower at 1.711 (142 vs 243 ms), and q6 is 1.030 at 0.00 ms. P6 had nine of them over 1.3. +- **Parted STR arm (R2): FAIL by the letter (Ruling Q2).** All 43 queries + are present and the answers match (p2 = p0). Three queries with p0 >= 1 ms + are over 1.05: q24 1.069, q39 1.238 and q40 1.176. P6 measured q39 at + 13.551 and q40 at 1.170. +- **First-run and cold, informational.** The first run is slower on g2 + for the queries that read a STR column. For example q21 takes 1325.76 ms + against 108.00 ms, q23 3469.69 against 293.83, and q34 273.32 against + 52.06. Cold shows the same at 9x-31x for q21-q23, q28, q34, q35 and q37-q39. + Warm on those queries is at most 1.027 of g0. None of these is a gate line. +- **Materialization (Rulings 6-2 / 7-1).** The STR columns left + materialized on g2 are: q11 MobilePhoneModel and q14 SearchPhrase (count + distinct); q21-q23 and q28 (LIKE, strlen); q26 / q27 (sort keys); and q29 + Referer. `count s by s` (q34 / q35 URL, q13, q37, q38) no longer + materializes. + +### P2/P3 driver rerun against BASE 9802ba80 (I8), splayed arms only + +Ruling Q3: the gate started with 11 949 789 184 B free, at least the +11.81 GB the rerun needs. `W=/home/hetoku/data/tmp/p6b/t8/p2_bench +BASE=9802ba80 p2_bench.sh prep`, then `splayed` (arms A and C0), ran after +the STR stores were deleted. **The `parted` stage (arms B, C1 and R) was +not run.** It converts `/skull/clickbench/hits_h.csv`, which this task's +dispatch says not to touch. The P3 summary therefore reports parted +NOT-RUN, and its materialization and RSS clauses fail on the missing B rows +(`B/qN:no-mat-row`). That failure is an artifact of the skip, not a +measurement. Raw data: /home/hetoku/data/tmp/p6b/t8/p2_bench/p2.tsv and +summary.txt. + +``` +totals over all 43: warm 1712.0 vs 1649.9 (0.964); first run 2527.0 vs 2715.6 (1.075); 3-run 6027.6 vs 6097.3 (1.012) +answer_mismatches none +scan_only(gated) n=28; gmeans over base>=1ms (per column): warm n=22 0.590, first n=23 0.702, cold n=23 0.335; worst warm=1.213 +worst5 warm [(1.213, 'q7'), (1.143, 'q5'), (1.134, 'q6'), (1.102, 'q4'), (1.081, 'q1')] +totals over all 43: warm 1705.7 vs 1711.5 (1.003); first run 2545.0 vs 2550.5 (1.002); 3-run 6037.5 vs 6067.2 (1.005) +answer_mismatches none +gen0 warm_gmean(base>=1ms n=34)=0.998 warm_worst=1.080 worst5 [(1.08, 'q27'), (1.057, 'q6'), (1.051, 'q2'), (1.05, 'q30'), (1.031, 'q25')] +sizes {('A', 'g0'): 5948677939, ('A', 'g2'): 3216455899} peak_rss_kb {('A', 'g0'): 5117860, ('A', 'g2'): 5956804} evict_modes fadvise ragged_partition None meta {'p2': ['29e54038', '11b110c652ed'], 'base': ['9802ba80', 'e382892f42f5']} +GATE (strict) splayed[answers=PASS warm=FAIL cold=PASS first=PASS materializing_warm=PASS no_unexpected_materialization=PASS first_total=PASS] parted[NOT-RUN] gen0-splayed[answers=PASS warm=FAIL] gen0-parted[NOT-RUN] gen0-ragged[NOT-RUN] +P2 GATE (strict): FAIL +rss A without D2 q41,q42: 5088768 -> 5048936 kB (x0.992, bound 1.1, gated) +P3GATE p2_strict=FAIL materialization=FAIL rss=FAIL +P3 GATE: FAIL +``` + +Answers PASS on A and C0. The splayed warm clause (A) fails on sub-ms +rows: q4-q7 and q1 are 0.00 ms in both generations, the same class as in +P6's rerun. q33 is at 1.064 (Ruling 10-7). The gen-0 splayed warm clause +(C0) fails on q27 at 1.080 (0.90 vs 0.97 ms, sub-ms; Ruling 14-8's class); +the C0 gmean is 0.998. The A sizes are byte-identical to P6's rerun +(5 948 677 939 / 3 216 455 899): P6b does not change the SYM store's bytes. diff --git a/bench/compress_estimate/index_use.sh b/bench/compress_estimate/index_use.sh new file mode 100755 index 000000000..0322a92d7 --- /dev/null +++ b/bench/compress_estimate/index_use.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Per-query persisted-index use for the ClickBench queries. +# usage: index_use.sh DB TABLE [QUERIES] +# DB: splayed table dir (has .d, directly or via its .current generation). +# TABLE: table name (kept for symmetry with compress_estimate; unused). +# Output: one line per query, "query_nodict", the dict being what +# .idx.uses returned for that query ({} = no index consulted). +# Index sites never consult parted segment indexes, so a parted root is +# rejected (warning, exit 2) rather than reported as empty dicts. +set -euo pipefail +DB=${1:?usage: index_use.sh DB TABLE [QUERIES]} +QUERIES=${3:-../ClickBench/rayforce/queries.rfl} +BIN=${RAY_BIN:-./rayforce} +DB=${DB%/} +splayed=0 +if [ -f "$DB/.d" ]; then splayed=1 +elif [ -f "$DB/.current" ]; then + gen=$(tr -d '\n' < "$DB/.current") + [ -f "$DB/$gen/.d" ] && splayed=1 +fi +if [ "$splayed" != 1 ]; then + echo "warning: $DB is not a splayed table directory (no .d); index use is only meaningful on a splayed table" >&2 + exit 2 +fi +LOAD="(set hits (.db.splayed.get \"$DB/\"))" +n=0 +# one query per paren-balanced expression, as run.sh splits them +awk ' + /^[[:space:]]*$/ { next } + { q = q $0 "\n"; p = $0; gsub(/[^()]/, "", p) + for (i = 1; i <= length(p); i++) { c = substr(p, i, 1); if (c == "(") d++; else d-- } + if (d == 0) { printf "%s%c", q, 0; q = "" } } +' "$QUERIES" | while IFS= read -r -d '' q; do + n=$((n + 1)) + script=$(mktemp) + printf '(do %s null)\n(do (.idx.uses hits) null)\n(do %s null)\n(println (.idx.uses hits))\n' "$LOAD" "$q" > "$script" + out=$("$BIN" "$script" 2>&1 | tail -1) || out="error" + rm -f "$script" + printf '%d\t%s\n' "$n" "$out" +done diff --git a/bench/compress_estimate/main.c b/bench/compress_estimate/main.c new file mode 100644 index 000000000..c140c3608 --- /dev/null +++ b/bench/compress_estimate/main.c @@ -0,0 +1,481 @@ +/* Compressed-columns P0 estimator. + * + * Measures, for a splayed table or a parted database, the on-disk size + * breakdown (column data, inline indexes, symfile, other), the size of the + * column data under the generation-2 integer encodings (per-vector choice + * per the spec's selection rule, including null bitmaps, descriptors, + * chunk directory, headers and VALUE_DICT side data), the encoding mix, + * the chunk/vector skip rates of a predicate list, and an FSST estimate of + * the symfile with its decode time and decompressed-snapshot size. + * + * Build: make lib && cc -O2 -std=c17 -Wall -Wextra -Iinclude -Isrc \ + * bench/compress_estimate/main.c librayforce.a -lm -lpthread \ + * -o build/compress_estimate + */ +#define _POSIX_C_SOURCE 200809L +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "table/domain.h" +#include "store/splay.h" +#include "store/enc.h" +#include "store/fsst.h" +#include "lang/format.h" /* ray_type_name */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_PRED 256 + +static double now_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (double)t.tv_sec + (double)t.tv_nsec * 1e-9; } +static int64_t fsize(const char* p) { struct stat st; return stat(p, &st) == 0 ? (int64_t)st.st_size : 0; } +static void* xmalloc(size_t n) { void* p = malloc(n ? n : 1); if (!p) { fprintf(stderr, "out of memory\n"); exit(2); } return p; } +static void* xcalloc(size_t n, size_t m) { void* p = calloc(n ? n : 1, m ? m : 1); if (!p) { fprintf(stderr, "out of memory\n"); exit(2); } return p; } + +/* ---- predicates ---- */ +typedef struct { char group[32], col[64], op[4]; int nv; int64_t v[8]; bool sym_empty; } pred_t; +static pred_t g_pred[MAX_PRED]; static int g_npred; + +static int64_t parse_const(const char* s, bool* sym_empty) { + *sym_empty = strcmp(s, "\"\"") == 0; + if (*sym_empty) return 0; + int y, mo, d; + if (sscanf(s, "%d.%d.%d", &y, &mo, &d) == 3) { + /* days since 2000.01.01 (civil-from-days, proleptic Gregorian) */ + int yy = y - (mo <= 2); int era = (yy >= 0 ? yy : yy - 399) / 400; + unsigned yoe = (unsigned)(yy - era * 400); + unsigned doy = (153u * (unsigned)(mo + (mo > 2 ? -3 : 9)) + 2) / 5 + (unsigned)d - 1; + unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + int64_t days = (int64_t)era * 146097 + (int64_t)doe - 719468; /* since 1970 */ + return days - 10957; /* since 2000 */ + } + return strtoll(s, NULL, 10); +} + +static void load_preds(const char* path) { + FILE* f = fopen(path, "r"); if (!f) { perror(path); exit(2); } + char line[512]; + while (fgets(line, sizeof line, f) && g_npred < MAX_PRED) { + if (line[0] == '#' || line[0] == '\n') continue; + pred_t* p = &g_pred[g_npred]; + char vals[256]; + if (sscanf(line, "%31s %63s %3s %255s", p->group, p->col, p->op, vals) != 4) continue; + p->nv = 0; + for (char* t = strtok(vals, ","); t && p->nv < 8; t = strtok(NULL, ",")) + p->v[p->nv++] = parse_const(t, &p->sym_empty); + printf("pred\t%s\t%s\t%s", p->group, p->col, p->op); + for (int i = 0; i < p->nv; i++) printf("\t%lld", (long long)p->v[i]); + printf("\n"); + g_npred++; + } + fclose(f); +} + +/* Decision of one predicate over a range with logical min/max and nulls: + * 0 = no row passes, 1 = every row passes, 2 = undecided. Ranges with + * bitmap nulls are never decided (conservative, as zone_cmp_decision); + * SYM ranges decide only == / != / in (membership bounds). */ +static int decide(const pred_t* p, int64_t mn, int64_t mx, bool has_nulls, bool is_sym) { + if (has_nulls) return 2; + bool eq_all = mn == mx; + if (!strcmp(p->op, "==")) { int64_t c = p->v[0]; if (c < mn || c > mx) return 0; return eq_all && c == mn ? 1 : 2; } + if (!strcmp(p->op, "!=")) { int64_t c = p->v[0]; if (c < mn || c > mx) return 1; return eq_all && c == mn ? 0 : 2; } + if (!strcmp(p->op, "in")) { + bool any = false; + for (int i = 0; i < p->nv; i++) if (p->v[i] >= mn && p->v[i] <= mx) any = true; + if (!any) return 0; + if (eq_all) for (int i = 0; i < p->nv; i++) if (p->v[i] == mn) return 1; + return 2; + } + if (is_sym) return 2; + int64_t c = p->v[0]; + if (!strcmp(p->op, "<")) return mx < c ? 1 : mn >= c ? 0 : 2; + if (!strcmp(p->op, "<=")) return mx <= c ? 1 : mn > c ? 0 : 2; + if (!strcmp(p->op, ">")) return mn > c ? 1 : mx <= c ? 0 : 2; + if (!strcmp(p->op, ">=")) return mn >= c ? 1 : mx < c ? 0 : 2; + return 2; +} + +/* Per predicate: per-vector decisions at chunk level and vector level. */ +typedef struct { int8_t* chunk_dec; int8_t* vec_dec; int64_t nvec; int64_t* vec_rows; int64_t* vec_bytes; } pred_eval_t; +static pred_eval_t g_eval[MAX_PRED]; + +/* ---- totals ---- */ +static int64_t g_raw_data, g_enc_data, g_index_bytes, g_index_kept, g_other, g_rows; +static int64_t g_sym_raw, g_sym_fsst; +static int64_t g_enc_count[10]; + +static void report_col(const char* name, int8_t type, int64_t raw, int64_t enc, int64_t idx) { + printf("col\t%s\t%s\t%lld\t%lld\t%.2f\t%lld\n", name, ray_type_name(type), + (long long)raw, (long long)enc, enc ? (double)raw / (double)enc : 0.0, (long long)idx); +} + +/* Encode one column (one segment) and fill predicate evaluations for it. */ +static bool g_skipped[MAX_PRED]; +static int64_t estimate_column(ray_t* col, const char* name, int64_t vec_base, int64_t total_vecs) { + ray_enc_kind_t k; + if (!ray_enc_kind_of(col->type, col->attrs, &k)) { + for (int p = 0; p < g_npred; p++) + if (!strcmp(g_pred[p].col, name) && !g_skipped[p]) { + g_skipped[p] = true; + printf("pred_skipped\t%s\t%s\tcolumn type %s is not encodable\n", g_pred[p].group, name, ray_type_name(col->type)); + } + return -1; + } + const void* data = ray_data(col); + int64_t len = col->len; + int64_t n_chunks = (len + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + int64_t bytes = 32 + 64 + 64 * n_chunks; /* header, enc header, directory */ + ray_enc_input_t* in = xmalloc(sizeof *in); + int64_t dict_uses = 0; /* vectors that chose DICT */ + + /* VALUE_DICT from the first chunk (integer and temporal only). */ + ray_enc_dict_t dict = { NULL, 0 }; uint64_t* dv = NULL; uint32_t dn = 0; + if (k.is_signed && len > 0) { + int64_t m = len < RAY_ENC_CHUNK ? len : RAY_ENC_CHUNK; + uint64_t* first = xmalloc(sizeof(uint64_t) * (size_t)m); + for (int64_t s = 0; s < m; s += RAY_ENC_VEC) { + int n = (int)(m - s < RAY_ENC_VEC ? m - s : RAY_ENC_VEC); + ray_enc_load(data, col->type, col->attrs, s, n, in); + memcpy(first + s, in->bits, sizeof(uint64_t) * (size_t)n); + } + int tr = ray_enc_train_dict(first, m, k, &dv, &dn); + if (tr < 0) { fprintf(stderr, "out of memory training dictionary\n"); exit(1); } + if (tr == 1) { dict.v = dv; dict.n = dn; } + free(first); + } + + for (int64_t ch = 0; ch < n_chunks; ch++) { + int64_t c0 = ch * RAY_ENC_CHUNK, c1 = c0 + RAY_ENC_CHUNK < len ? c0 + RAY_ENC_CHUNK : len; + int64_t cmin = INT64_MAX, cmax = INT64_MIN; bool cnull = false; + bytes += 64 * 48; /* 64 descriptors */ + for (int64_t s = c0; s < c1; s += RAY_ENC_VEC) { + int n = (int)(c1 - s < RAY_ENC_VEC ? c1 - s : RAY_ENC_VEC); + ray_enc_load(data, col->type, col->attrs, s, n, in); + ray_enc_choice_t c = ray_enc_choose(in->bits, n, k, RAY_ENC_SLOT_TOP, 0, dict.n ? &dict : NULL); + int64_t vb = c.bytes + (in->bitmap && in->n_nulls ? 128 : 0); + bytes += vb; + g_enc_count[c.enc]++; + dict_uses += c.enc == RAY_ENC_DICT; + ray_enc_stats_t st; ray_enc_stats(in->bits, n, k, &st); + int64_t mn = ray_enc_logical(st.min, k), mx = ray_enc_logical(st.max, k); + bool vnull = in->bitmap && in->n_nulls > 0; + if (mn < cmin) cmin = mn; + if (mx > cmax) cmax = mx; + cnull |= vnull; + int64_t vi = vec_base + s / RAY_ENC_VEC; + for (int p = 0; p < g_npred; p++) { + if (strcmp(g_pred[p].col, name)) continue; + pred_eval_t* e = &g_eval[p]; + if (!e->vec_dec) { + e->nvec = total_vecs; + e->vec_dec = xcalloc((size_t)e->nvec, 1); e->chunk_dec = xcalloc((size_t)e->nvec, 1); + e->vec_rows = xcalloc((size_t)e->nvec, sizeof(int64_t)); e->vec_bytes = xcalloc((size_t)e->nvec, sizeof(int64_t)); + } + e->vec_dec[vi] = (int8_t)decide(&g_pred[p], mn, mx, vnull, col->type == RAY_SYM); + e->vec_rows[vi] = n; e->vec_bytes[vi] = vb; + } + } + for (int p = 0; p < g_npred; p++) { + if (strcmp(g_pred[p].col, name) || !g_eval[p].chunk_dec) continue; + int d = decide(&g_pred[p], cmin, cmax, cnull, col->type == RAY_SYM); + for (int64_t v = vec_base + c0 / RAY_ENC_VEC; v <= vec_base + (c1 - 1) / RAY_ENC_VEC; v++) + g_eval[p].chunk_dec[v] = (int8_t)d; + } + } + /* VALUE_DICT side data, charged only when a vector uses it: the side + * table (u32 n_entries, u32 reserved, one 24-byte entry record = 32 B), + * then the entry (u32 n, u32 reserved, n values, padded to 8) placed at + * a 32-aligned offset. */ + if (dict_uses) { + int64_t body = (16 + (int64_t)dn * k.T / 8 + 7) & ~(int64_t)7; + bytes += 32 + ((body + 31) & ~(int64_t)31); + } + if (dv) ray_free_raw(dv); + free(in); + return bytes; +} + +/* Index bytes of a column file: file size minus the payload (32-aligned). */ +static int64_t index_bytes(const char* path, ray_t* col) { + int64_t fs = fsize(path); + if (col->type == RAY_STR || col->type == RAY_LIST) return 0; /* not split in P0 */ + uint8_t esz = ray_sym_elem_size(col->type, col->attrs); + int64_t payload = 32 + col->len * esz; + int64_t region = (payload + 31) & ~(int64_t)31; + return fs > region ? fs - region : 0; +} + +static bool kept(const char* name, const char* keep) { + if (!keep) return false; + size_t n = strlen(name); + for (const char* p = keep; (p = strstr(p, name)); p += n) + if ((p == keep || p[-1] == ',') && (p[n] == ',' || p[n] == 0)) return true; + return false; +} + +/* Process one splayed directory (a table or one partition). */ +/* Resolve a splayed directory to its published generation (or itself). */ +static bool resolve_dir(const char* dir, char* out, size_t sz) { + return ray_splay_resolve_dir(dir, out, sz) == RAY_OK; +} + +static void process_splayed(const char* dir, const char* sym, const char* keep, int64_t vec_base, int64_t total_vecs) { + char rdir[1024]; + if (!resolve_dir(dir, rdir, sizeof rdir)) { fprintf(stderr, "cannot resolve %s\n", dir); exit(2); } + ray_t* t = ray_read_splayed(dir, sym); + if (!t || RAY_IS_ERR(t)) { fprintf(stderr, "cannot read %s\n", dir); exit(2); } + int64_t nc = ray_table_ncols(t); + for (int64_t c = 0; c < nc; c++) { + ray_t* col = ray_table_get_col_idx(t, c); + ray_t* nm = ray_sym_str(ray_table_col_name(t, c)); + char name[128]; snprintf(name, sizeof name, "%.*s", (int)ray_str_len(nm), ray_str_ptr(nm)); + char path[1280]; snprintf(path, sizeof path, "%s/%s", rdir, name); + int64_t fs = fsize(path), ib = index_bytes(path, col), raw = fs - ib; + int64_t enc = estimate_column(col, name, vec_base, total_vecs); + g_raw_data += raw; g_index_bytes += ib; if (kept(name, keep)) g_index_kept += ib; + g_enc_data += enc >= 0 ? enc : raw; /* unencodable types stay raw */ + report_col(name, col->type, raw, enc >= 0 ? enc : raw, ib); + } + g_rows += ray_table_nrows(t); + char p[1100]; snprintf(p, sizeof p, "%s/.d", rdir); g_other += fsize(p); + ray_release(t); +} + +/* ---- parallel decode of retained blocks ---- */ +typedef struct { + ray_fsst_table_t* t; uint8_t* arena; uint32_t* eoff; uint32_t* elen; uint32_t* l; int n; +} sym_blk_t; +typedef struct { sym_blk_t* blks; int nblk; int next; int bad; } sym_par_t; + +static void* sym_par_worker(void* a) { + sym_par_t* P = a; + size_t dcap = 1 << 16; uint8_t* dbuf = xmalloc(dcap); + for (;;) { + int b = __atomic_fetch_add(&P->next, 1, __ATOMIC_RELAXED); + if (b >= P->nblk) break; + sym_blk_t* k = &P->blks[b]; + for (int i = 0; i < k->n; i++) { + if ((size_t)k->l[i] > dcap) { while ((size_t)k->l[i] > dcap) dcap *= 2; free(dbuf); dbuf = xmalloc(dcap); } + int64_t d = ray_fsst_decode(k->t, k->arena + k->eoff[i], k->elen[i], dbuf, dcap); + if (d != (int64_t)k->l[i]) __atomic_store_n(&P->bad, 1, __ATOMIC_RELAXED); + } + } + free(dbuf); + return NULL; +} + +/* ---- symfile estimate ---- */ +/* The FSST `lengths` slot (U32) allows only RAW and FOR_BP: size one vector + * of lengths as the smaller of the two plus its 8-byte child header. */ +static int64_t fsst_lengths_bytes(const uint64_t* lv, int m) { + ray_enc_kind_t ku = { 32, false, false }; + uint64_t base; + int w = ray_enc_for_width(lv, m, ku, &base); + int64_t raw = ray_enc_size_raw(m, 32), fo = ray_enc_size_for(w); + return (raw < fo ? raw : fo) + 8; +} + +static void estimate_sym(const char* sym) { + ray_sym_domain_t* dom = ray_sym_domain_open(sym); + if (!dom) { printf("sym\tnone\n"); return; } + ray_sym_domain_raw_t r; + if (!ray_sym_domain_raw_pin(dom, &r)) { printf("sym\tno-raw\n"); ray_sym_domain_release(dom); return; } + int64_t raw_file = fsize(sym), snapshot = 8 * r.count, enc = 0; + double dec_s = 0; + const int64_t B = 65536; + const uint8_t** s = xmalloc(sizeof(uint8_t*) * (size_t)B); + uint32_t* l = xmalloc(sizeof(uint32_t) * (size_t)B); + uint32_t* elen = xmalloc(sizeof(uint32_t) * (size_t)B); + size_t* eoff = xmalloc(sizeof(size_t) * (size_t)B); + size_t cap = 1 << 22, dcap = 1 << 16; + uint8_t* arena = xmalloc(cap); + uint8_t* dbuf = xmalloc(dcap); + ray_fsst_table_t* t = xmalloc(sizeof *t); + ray_fsst_index_t* ix = xmalloc(sizeof *ix); + int64_t nblk_max = (r.count + B - 1) / B; + sym_blk_t* keep = xmalloc(sizeof(sym_blk_t) * (size_t)(nblk_max ? nblk_max : 1)); + int nkeep = 0; + for (int64_t b0 = 0; b0 < r.count; b0 += B) { + int64_t n = r.count - b0 < B ? r.count - b0 : B; + for (int64_t i = 0; i < n; i++) { + size_t len; const char* p = ray_sym_domain_raw_str(&r, b0 + i, &len); + s[i] = (const uint8_t*)p; l[i] = (uint32_t)len; snapshot += 4 + (int64_t)len; + } + if (ray_fsst_train(s, l, n, t) < 0) { fprintf(stderr, "fsst training out of memory\n"); exit(2); } + ray_fsst_index_build(t, ix); /* once per block */ + int64_t blk = ray_fsst_table_bytes(t); + /* encode into a block arena; lengths packed per 1024 as U32 vectors */ + size_t used = 0; + for (int64_t i = 0; i < n; i++) { + if (used + 2 * (size_t)l[i] > cap) { + while (used + 2 * (size_t)l[i] > cap) cap *= 2; + arena = realloc(arena, cap); if (!arena) { fprintf(stderr, "out of memory\n"); exit(2); } + } + int64_t e = ray_fsst_encode_ix(t, ix, s[i], l[i], arena + used); + eoff[i] = used; elen[i] = (uint32_t)e; used += (size_t)e; + } + blk += (int64_t)((used + 7) & ~(size_t)7) + 8; + for (int64_t v = 0; v < n; v += RAY_ENC_VEC) { + int m = (int)(n - v < RAY_ENC_VEC ? n - v : RAY_ENC_VEC); + uint64_t lv[RAY_ENC_VEC]; for (int i = 0; i < m; i++) lv[i] = elen[v + i]; + blk += fsst_lengths_bytes(lv, m); + } + enc += blk; + double t0 = now_s(); + for (int64_t i = 0; i < n; i++) { + if ((size_t)l[i] > dcap) { while ((size_t)l[i] > dcap) dcap *= 2; free(dbuf); dbuf = xmalloc(dcap); } + int64_t d = ray_fsst_decode(t, arena + eoff[i], elen[i], dbuf, dcap); + if (d != (int64_t)l[i] || memcmp(dbuf, s[i], l[i]) != 0) { fprintf(stderr, "fsst mismatch at %lld\n", (long long)(b0 + i)); exit(3); } + } + dec_s += now_s() - t0; + sym_blk_t* k = &keep[nkeep++]; + k->n = (int)n; + k->t = xmalloc(sizeof *t); memcpy(k->t, t, sizeof *t); + k->arena = xmalloc(used ? used : 1); memcpy(k->arena, arena, used); + k->eoff = xmalloc(sizeof(uint32_t) * (size_t)n); k->elen = xmalloc(sizeof(uint32_t) * (size_t)n); + k->l = xmalloc(sizeof(uint32_t) * (size_t)n); + for (int64_t i = 0; i < n; i++) { k->eoff[i] = (uint32_t)eoff[i]; k->elen[i] = elen[i]; k->l[i] = l[i]; } + } + /* parallel decode of every retained block on all online CPUs */ + long ncpu = sysconf(_SC_NPROCESSORS_ONLN); if (ncpu < 1) ncpu = 1; + sym_par_t P = { keep, nkeep, 0, 0 }; + pthread_t* th = xmalloc(sizeof(pthread_t) * (size_t)ncpu); + double tp = now_s(); + long started = 0; + for (long i = 0; i < ncpu; i++) { + if (pthread_create(&th[i], NULL, sym_par_worker, &P) != 0) break; + started++; + } + if (started < ncpu) { + fprintf(stderr, "warning: started %ld of %ld decode threads\n", started, ncpu); + sym_par_worker(&P); /* the caller drains whatever blocks remain */ + } + for (long i = 0; i < started; i++) pthread_join(th[i], NULL); + ncpu = started < ncpu ? started + 1 : ncpu; + double par_s = now_s() - tp; + if (P.bad) { fprintf(stderr, "parallel fsst decode length mismatch\n"); exit(3); } + for (int i = 0; i < nkeep; i++) { free(keep[i].t); free(keep[i].arena); free(keep[i].eoff); free(keep[i].elen); free(keep[i].l); } + free(keep); free(th); + printf("sym\tfile=%lld\tfsst=%lld\tratio=%.2f\tsnapshot=%lld\tdecode_s=%.3f\tsym_parallel_decode_s=%.3f\tthreads=%ld\tcount=%lld\n", + (long long)raw_file, (long long)enc, enc ? (double)raw_file / (double)enc : 0, + (long long)snapshot, dec_s, par_s, ncpu, (long long)r.count); + free(s); free(l); free(elen); free(eoff); free(arena); free(dbuf); free(t); free(ix); + ray_sym_domain_raw_unpin(dom); + ray_sym_domain_release(dom); + g_sym_raw = raw_file; g_sym_fsst = enc; +} + +static void report_groups(void) { + char seen[64][32]; int ns = 0; + for (int p = 0; p < g_npred; p++) { + bool dup = false; for (int i = 0; i < ns; i++) if (!strcmp(seen[i], g_pred[p].group)) dup = true; + if (dup || ns >= 64) continue; + strcpy(seen[ns++], g_pred[p].group); + int64_t nvec = 0; for (int q = 0; q < g_npred; q++) if (!strcmp(g_pred[q].group, g_pred[p].group) && g_eval[q].nvec) nvec = g_eval[q].nvec; + if (!nvec) { printf("group\t%s\tno-columns\n", g_pred[p].group); continue; } + int64_t rows = 0, chunk_dec = 0, vec_dec = 0, und = 0, bytes_all = 0, bytes_und = 0; + for (int64_t v = 0; v < nvec; v++) { + int cd = 1, vd = 1; int64_t vr = 0, vb = 0; /* AND of {0 none, 1 all, 2 undecided} */ + for (int q = 0; q < g_npred; q++) { + if (strcmp(g_pred[q].group, g_pred[p].group) || !g_eval[q].nvec) continue; + int c = g_eval[q].chunk_dec[v], d = g_eval[q].vec_dec[v]; + cd = (cd == 0 || c == 0) ? 0 : (cd == 2 || c == 2) ? 2 : 1; + vd = (vd == 0 || d == 0) ? 0 : (vd == 2 || d == 2) ? 2 : 1; + vr = g_eval[q].vec_rows[v]; + vb += g_eval[q].vec_bytes[v]; + } + bytes_all += vb; + if (vd == 2 && cd == 2) bytes_und += vb; /* final combined decisions */ + rows += vr; + if (cd != 2) chunk_dec += vr; else if (vd != 2) vec_dec += vr; else und += vr; + } + printf("group\t%s\trows=%lld\tchunk_decided=%.4f\tvector_decided=%.4f\tundecided=%.4f\tpred_bytes=%lld\tpred_bytes_undecided=%lld\n", + g_pred[p].group, (long long)rows, rows ? (double)chunk_dec / (double)rows : 0, + rows ? (double)vec_dec / (double)rows : 0, rows ? (double)und / (double)rows : 0, + (long long)bytes_all, (long long)bytes_und); + } +} + +int main(int argc, char** argv) { + const char *db = NULL, *table = NULL, *sym = NULL, *preds = NULL, *keep = NULL; + for (int i = 1; i + 1 < argc; i += 2) { + if (!strcmp(argv[i], "--db")) db = argv[i + 1]; + else if (!strcmp(argv[i], "--table")) table = argv[i + 1]; + else if (!strcmp(argv[i], "--sym")) sym = argv[i + 1]; + else if (!strcmp(argv[i], "--preds")) preds = argv[i + 1]; + else if (!strcmp(argv[i], "--keep-index")) keep = argv[i + 1]; + } + if (!db) { fprintf(stderr, "usage: compress_estimate --db DIR [--table NAME] [--sym PATH] [--preds FILE] [--keep-index COL,...]\n"); return 2; } + ray_heap_init(); (void)ray_sym_init(); + char symbuf[1024]; + if (!sym) { snprintf(symbuf, sizeof symbuf, "%s/.sym", db); sym = symbuf; } + if (preds) load_preds(preds); + printf("col\tname\ttype\traw\tencoded\tratio\tindex\n"); + + char rdb[1024], d0[1100]; + if (!resolve_dir(db, rdb, sizeof rdb)) snprintf(rdb, sizeof rdb, "%s", db); + snprintf(d0, sizeof d0, "%s/.d", rdb); + if (fsize(d0) > 0) { + ray_t* t = ray_read_splayed(db, sym); + if (!t || RAY_IS_ERR(t)) { fprintf(stderr, "cannot read %s\n", db); return 2; } + int64_t rows = ray_table_nrows(t); ray_release(t); + process_splayed(db, sym, keep, 0, (rows + RAY_ENC_VEC - 1) / RAY_ENC_VEC); + } else { + if (!table) { fprintf(stderr, "parted root needs --table\n"); return 2; } + printf("note\tparted root: the engine's index sites never consult parted segment indexes; " + "skip rates and index sizes show what the files allow, not what the engine uses today\n"); + /* partitions: subdirectories in name order, each /
/ */ + struct dirent** ents; int ne = scandir(db, &ents, NULL, alphasort); + if (ne < 0) { perror(db); return 2; } + int64_t total = 0, base = 0; + for (int pass = 0; pass < 2; pass++) { + for (int i = 0; i < ne; i++) { + if (ents[i]->d_name[0] == '.') continue; + char pd[1024]; snprintf(pd, sizeof pd, "%s/%s/%s", db, ents[i]->d_name, table); + char rpd[1024], pdd[1100]; + if (!resolve_dir(pd, rpd, sizeof rpd)) continue; + snprintf(pdd, sizeof pdd, "%s/.d", rpd); + if (fsize(pdd) <= 0) continue; + ray_t* t = ray_read_splayed(pd, sym); + if (!t || RAY_IS_ERR(t)) { fprintf(stderr, "cannot read %s\n", pd); return 2; } + int64_t r = ray_table_nrows(t); ray_release(t); + int64_t nv = (r + RAY_ENC_VEC - 1) / RAY_ENC_VEC; /* each partition owns its vector slots */ + if (pass == 0) total += nv; + else { process_splayed(pd, sym, keep, base, total); base += nv; } + } + } + for (int i = 0; i < ne; i++) free(ents[i]); + free(ents); + } + estimate_sym(sym); + report_groups(); + + static const char* encname[10] = { "RAW","CONST","FOR_BP","DELTA_BP","RLE","DICT","ALP","ALP_RD","STR_DICT","FSST" }; + int64_t nv = 0; for (int e = 0; e < 10; e++) nv += g_enc_count[e]; + for (int e = 0; e < 10; e++) if (g_enc_count[e]) printf("mix_fraction_of_vectors\t%s\t%.4f\n", encname[e], (double)g_enc_count[e] / (double)nv); + + int64_t before = g_raw_data + g_index_bytes + g_sym_raw + g_other; + struct { const char* name; int64_t size; } sc[4] = { + { "today", before }, + { "columns encoded", g_enc_data + g_index_bytes + g_sym_raw + g_other }, + { "columns + sym fsst", g_enc_data + g_index_bytes + g_sym_fsst + g_other }, + { "columns + sym fsst + kept ix",g_enc_data + g_index_kept + g_sym_fsst + g_other }, + }; + printf("breakdown\trows=%lld\tdata=%lld\tindex=%lld\tsym=%lld\tother=%lld\ttotal=%lld\n", + (long long)g_rows, (long long)g_raw_data, (long long)g_index_bytes, (long long)g_sym_raw, + (long long)g_other, (long long)before); + /* Combined-score factor from size alone: the size term of the site's + * combined score has weight 0.1, so factor = (after / before)^0.1. */ + for (int i = 0; i < 4; i++) + printf("scenario\t%s\tbytes=%lld\tsize_ratio=%.3f\tscore_factor=%.4f\n", sc[i].name, + (long long)sc[i].size, (double)before / (double)sc[i].size, pow((double)sc[i].size / (double)before, 0.1)); + ray_sym_destroy(); ray_heap_destroy(); + return 0; +} diff --git a/bench/compress_estimate/p1_size.rfl b/bench/compress_estimate/p1_size.rfl new file mode 100644 index 000000000..cd79945e4 --- /dev/null +++ b/bench/compress_estimate/p1_size.rfl @@ -0,0 +1,9 @@ +;; P1 size measurement: re-save a splayed store compressed. +;; Arguments after `--`: --src DIR (the generation-0 store), --out DIR (the +;; compressed copy). Defaults: the 10M ClickBench store and build/p1_size/hits under the cwd. +(set u (at (.sys.args) 'user)) +(set src (if (in 'src (key u)) (at u 'src) "/skull/clickbench/rfsplayed")) +(set out (if (in 'out (key u)) (at u 'out) "build/p1_size/hits")) +(set t (.db.splayed.get src)) +(.db.splayed.set out t {compress: true}) +(println (count (.db.splayed.get out))) diff --git a/bench/compress_estimate/p1_size.sh b/bench/compress_estimate/p1_size.sh new file mode 100755 index 000000000..f7acdaa8d --- /dev/null +++ b/bench/compress_estimate/p1_size.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# P1 size measurement: re-save a splayed store compressed and list per-column +# file sizes and generations next to the generation-0 originals. +# usage: p1_size.sh [SRC] [OUT] [RAYFORCE] +# SRC generation-0 splayed store (default /skull/clickbench/rfsplayed) +# OUT directory for the compressed copy, removed first +# (default /build/p1_size/hits) +# RAYFORCE release binary (default ./rayforce) +set -euo pipefail +SRC=${1:-/skull/clickbench/rfsplayed} +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +OUT=${2:-$HERE/../../build/p1_size/hits} +BIN=${3:-./rayforce} +rm -rf "$OUT" +"$BIN" "$HERE/p1_size.rfl" -- --src "$SRC" --out "$OUT" >&2 +cur() { if [ -f "$1/.current" ]; then echo "$1/$(cat "$1/.current")"; else echo "$1"; fi; } +S=$(cur "$SRC"); D=$(cur "$OUT") +printf 'column\tgen0_bytes\tp1_bytes\tp1_gen\n' +for f in "$S"/*; do + n=$(basename "$f"); [ -f "$D/$n" ] || continue + g=$(od -An -tu1 -j17 -N1 "$D/$n" | tr -d ' ') + printf '%s\t%s\t%s\t%s\n' "$n" "$(stat -c %s "$f")" "$(stat -c %s "$D/$n")" "$g" +done +printf 'sym\t%s\t%s\t-\n' "$(stat -c %s "$SRC/.sym")" "$(stat -c %s "$OUT/.sym")" diff --git a/bench/compress_estimate/p2_bench.sh b/bench/compress_estimate/p2_bench.sh new file mode 100755 index 000000000..d09f6ea45 --- /dev/null +++ b/bench/compress_estimate/p2_bench.sh @@ -0,0 +1,263 @@ +#!/usr/bin/env bash +# P2 gate (plan: compressed-columns P2, Task 17), 10M ClickBench, all 43 queries. +# Stages run one load kind at a time (disk: ~13-16 GB free): create, measure, delete. +# prep : HEAD's release build copied to $W/bin/p2; the pre-P2 base (BASE) +# built from `git archive` and copied to $W/bin/base +# splayed : g0 / g2 copies of the splayed store (.db.splayed.set {compress}) +# arm A g0 vs g2 (p2 binary); arm C0 g0, base vs p2 binary +# parted : p0 / p2 conversions of the CSV (.csv.parted, 1M rows per partition) +# arm B p0 vs p2 (p2 binary); arm C1 p0, base vs p2 binary; +# arm R p0 made ragged (the last partition without its column +# tail from AdvEngineID on), base vs p2 binary +# A measurement process loads the store and runs the query 6 times (timeit, ms): +# first = run 1 (fresh process, warm page cache), 3-run = runs 1..3, +# warm = median of runs 2..6. ROUNDS rounds, the two variants alternated +# (order swapped each round). Cold (arms A, B): the store's files evicted +# from the page cache per file (dd iflag=nocache: POSIX_FADV_DONTNEED, no +# privileged operation), then run 1 in a fresh process; the .sym is evicted +# with the store, so SYM queries' cold times include the domain faults. +# Answers: every query's full result is written (a table by .csv.write, any +# other value by println) and compared byte for byte, raw and with the lines +# sorted (header kept first). A query without an explicit order (no asc: / +# desc:) is compared sorted; a raw-only difference is reported as an order +# difference. Variant b runs twice to separate nondeterminism from a diff. +# Output: $W/p2.tsv ; the verdict is printed by p2_summary.py (never typed). +# usage: p2_bench.sh [-w WORKDIR] -s SCHEMA -q QUERIES prep | splayed | parted | all | verdict +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +W=${W:-$REPO/build/p2_bench} +SCHEMA= +QUERIES= +USAGE="usage: p2_bench.sh [-w WORKDIR] -s SCHEMA -q QUERIES \n -w WORKDIR scratch directory (default $REPO/build/p2_bench)\n -s SCHEMA the ClickBench rayforce schema.rfl\n -q QUERIES the ClickBench rayforce queries.rfl\n" +while getopts "w:s:q:" o; do + case $o in + w) W=$OPTARG ;; + s) SCHEMA=$OPTARG ;; + q) QUERIES=$OPTARG ;; + *) printf "%b" "$USAGE" >&2; exit 2 ;; + esac +done +shift $((OPTIND - 1)) +[ -n "$SCHEMA" ] || { printf "%b" "$USAGE" >&2; exit 2; } +[ -n "$QUERIES" ] || { printf "%b" "$USAGE" >&2; exit 2; } +SRC=/skull/clickbench/rfsplayed +CSV=/skull/clickbench/hits_h.csv +BASE=${BASE:-80a28e49} +ROUNDS=${ROUNDS:-5} +NQ=43 +OUT=$W/p2.tsv +P2=$W/bin/p2 +BB=$W/bin/base +mkdir -p "$W/g" "$W/bin" + +query_n() { + awk -v want="$1" ' + /^[[:space:]]*$/ { next } + { q = q $0 "\n"; p = $0; gsub(/[^()]/, "", p) + for (i = 1; i <= length(p); i++) { c = substr(p, i, 1); if (c == "(") d++; else d-- } + if (d == 0) { n++; if (n == want) { printf "%s", q; exit } q = "" } }' "$QUERIES" +} +QD=$W/g/q; mkdir -p "$QD" +for n in $(seq 1 $NQ); do query_n "$n" > "$QD/$n.rfl"; done +[ "$(cat "$QD/$NQ.rfl" | wc -c)" -gt 0 ] || { echo "queries.rfl has fewer than $NQ forms" >&2; exit 2; } + +guard() { # $1: GB free needed in $W + local avail; avail=$(df -B1 --output=avail "$W" | tail -1) + [ "$avail" -ge $(($1 * 1024 * 1024 * 1024)) ] || { echo "disk guard: need $1 GB in $W, have $avail" >&2; exit 2; } +} +rel_guard() { # a release build carries no sanitizer runtime + [ -x "$1" ] || { echo "$1 missing: run prep" >&2; exit 2; } + if grep -aq "__asan_init" "$1"; then echo "$1 is an ASan build" >&2; exit 2; fi +} +loadline() { # kind dir + if [ "$1" = parted ]; then printf '(set hits (.db.parted.get "%s" (quote hits)))\n' "$2" + else printf '(set hits (.db.splayed.get "%s/"))\n' "$2"; fi +} +evict() { # dir: per-file page-cache eviction, echoes the mode + sync + find "$1" -type f -exec dd if={} iflag=nocache count=0 status=none \; + echo fadvise +} +size() { printf 'size\t%s\t%s\t%s\n' "$1" "$2" "$(du -sb "$3" | cut -f1)" >> "$OUT"; } + +measure() { # arm kind dirA binA labA dirB binB labB + local arm=$1 kind=$2 round q v d b lab s r order + for round in $(seq 1 "$ROUNDS"); do + for q in $(seq 1 $NQ); do + if [ $((round % 2)) = 1 ]; then order="a b"; else order="b a"; fi + for v in $order; do + if [ "$v" = a ]; then d=$3; b=$4; lab=$5; else d=$6; b=$7; lab=$8; fi + s=$(mktemp -p "$W/g") + { loadline "$kind" "$d"; for i in 1 2 3 4 5 6; do printf '(println (timeit %s))\n' "$(cat "$QD/$q.rfl")"; done; } > "$s" + r=$("$b" "$s" 2>/dev/null | tail -6 | tr '\n' '\t') || true; rm -f "$s" + printf 'm\t%s\t%s\tq%s\t%s\t%s\n' "$arm" "$lab" "$q" "$round" "${r%$'\t'}" >> "$OUT" + done + done + echo "measure $arm round $round done" >&2 + done +} + +cold() { # arm kind dirA labA dirB labB (P2 binary) + local arm=$1 kind=$2 trial q v d lab s r mode + for q in $(seq 1 $NQ); do + for trial in 1 2 3; do + for v in a b; do + if [ "$v" = a ]; then d=$3; lab=$4; else d=$5; lab=$6; fi + mode=$(evict "$d") + s=$(mktemp -p "$W/g") + { loadline "$kind" "$d"; printf '(println (timeit %s))\n' "$(cat "$QD/$q.rfl")"; } > "$s" + r=$("$P2" "$s" 2>/dev/null | tail -1) || true; rm -f "$s" + printf 'c\t%s\t%s\tq%s\t%s\t%s\t%s\n' "$arm" "$lab" "$q" "$trial" "$r" "$mode" >> "$OUT" + done + done + done + echo "cold $arm done" >&2 +} + +mat() { # arm kind dir (generation 2, P2 binary): the columns each query leaves materialized + local arm=$1 q s m + for q in $(seq 1 $NQ); do + s=$(mktemp -p "$W/g") + { loadline "$2" "$3"; printf '(do %s null)\n' "$(cat "$QD/$q.rfl")" + printf '(println (at (cols hits) (where (raze (map (fn [c] (at (.idx.info hits c) (quote materialized))) (cols hits))))))\n'; } > "$s" + m=$("$P2" "$s" 2>/dev/null | tail -1) || true; rm -f "$s" + printf 'mat\t%s\tq%s\t%s\n' "$arm" "$q" "$m" >> "$OUT" + done +} + +enc() { # arm kind dir: every column's encoding mix (records which keys are DELTA) + local arm=$1 s + s=$(mktemp -p "$W/g") + { loadline "$2" "$3"; printf '(map (fn [c] (println (list c (at (.idx.info hits c) (quote enc))))) (cols hits))\nnull\n'; } > "$s" + "$P2" "$s" 2>/dev/null | while IFS= read -r line; do printf 'enc\t%s\t%s\n' "$arm" "$line" >> "$OUT"; done || true + rm -f "$s" +} + +mem() { # arm kind dirA labA dirB labB [skip]: peak RSS of one process running all 43 queries; + # with skip (query numbers), also of one running all but those (row memx) + local arm=$1 v d lab s q + for v in a b; do + if [ "$v" = a ]; then d=$3; lab=$4; else d=$5; lab=$6; fi + s=$(mktemp -p "$W/g") + { loadline "$2" "$d"; for q in $(seq 1 $NQ); do printf '(do %s null)\n' "$(cat "$QD/$q.rfl")"; done; } > "$s" + /usr/bin/time -f "%M" -o "$W/g/mem" "$P2" "$s" >/dev/null 2>&1 || true; rm -f "$s" + printf 'mem\t%s\t%s\t%s\n' "$arm" "$lab" "$(cat "$W/g/mem")" >> "$OUT" + [ -n "${7:-}" ] || continue + s=$(mktemp -p "$W/g") + { loadline "$2" "$d" + for q in $(seq 1 $NQ); do + case " $7 " in *" $q "*) continue ;; esac + printf '(do %s null)\n' "$(cat "$QD/$q.rfl")" + done; } > "$s" + /usr/bin/time -f "%M" -o "$W/g/mem" "$P2" "$s" >/dev/null 2>&1 || true; rm -f "$s" + printf 'memx\t%s\t%s\t%s\t%s\n' "$arm" "$lab" "$(cat "$W/g/mem")" "$(printf 'q%s,' $7 | sed 's/,$//')" >> "$OUT" + done +} + +answer() { # kind dir bin q file: the full result of query q written to file + local s c; s=$(mktemp -p "$W/g"); c=$(mktemp -p "$W/g" --suffix=.csv); rm -f "$c" + { loadline "$1" "$2"; printf '(set r %s)\n' "$(cat "$QD/$4.rfl")" + printf '(if (== (type r) (quote TABLE)) (.csv.write r "%s") (println r))\n' "$c"; } > "$s" + "$3" "$s" > "$5.stdout" 2>&1 || true; rm -f "$s" + if [ -f "$c" ]; then mv "$c" "$5"; else cp "$5.stdout" "$5"; fi + rm -f "$5.stdout" +} +h_raw() { md5sum < "$1" | cut -c1-12; } +h_sort() { { head -n 1 "$1"; tail -n +2 "$1" | LC_ALL=C sort; } | md5sum | cut -c1-12; } + +ident() { # arm kind dirA binA dirB binB: full answers of every query, a vs b, b twice + local arm=$1 q ord ad fa fb fb2 + ad=$W/ans/$arm; rm -rf "$ad"; mkdir -p "$ad" + for q in $(seq 1 $NQ); do + if grep -Eq '(asc|desc):' "$QD/$q.rfl"; then ord=ordered; else ord=unordered; fi + fa=$ad/q$q.a; fb=$ad/q$q.b; fb2=$ad/q$q.b2 + answer "$2" "$3" "$4" "$q" "$fa" + answer "$2" "$5" "$6" "$q" "$fb" + answer "$2" "$5" "$6" "$q" "$fb2" # separates nondeterminism from a real diff + printf 'ident\t%s\tq%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$arm" "$q" \ + "$(h_raw "$fa")" "$(h_raw "$fb")" "$(h_raw "$fb2")" \ + "$(h_sort "$fa")" "$(h_sort "$fb")" "$(h_sort "$fb2")" "$ord" >> "$OUT" + done + echo "ident $arm done" >&2 +} + +prep() { + ( cd "$REPO" && make release >/dev/null ) + cp "$REPO/rayforce" "$P2"; rel_guard "$P2" + rm -rf "$W/base_src"; mkdir -p "$W/base_src" + ( cd "$REPO" && git archive "$BASE" ) | tar -x -C "$W/base_src" + ( cd "$W/base_src" && make release >/dev/null ) + cp "$W/base_src/rayforce" "$BB"; rm -rf "$W/base_src"; rel_guard "$BB" + printf 'meta\tp2\t%s\t%s\n' "$(git -C "$REPO" rev-parse --short HEAD)" "$(sha256sum "$P2" | cut -c1-12)" >> "$OUT" + printf 'meta\tbase\t%s\t%s\n' "$BASE" "$(sha256sum "$BB" | cut -c1-12)" >> "$OUT" +} + +stage_splayed() { + rel_guard "$P2"; rel_guard "$BB"; guard 11 + rm -rf "$W/g0" "$W/g2" + local s; s=$(mktemp -p "$W/g") + printf '(set t (.db.splayed.get "%s"))\n(.db.splayed.set "%s/g0/" t {compress: false})\n(.db.splayed.set "%s/g2/" t {compress: true})\n' "$SRC" "$W" "$W" > "$s" + "$P2" "$s" >/dev/null; rm -f "$s" + size A g0 "$W/g0"; size A g2 "$W/g2" + enc A splayed "$W/g2" + mat A splayed "$W/g2" + measure A splayed "$W/g0" "$P2" g0 "$W/g2" "$P2" g2 + cold A splayed "$W/g0" g0 "$W/g2" g2 + mem A splayed "$W/g0" g0 "$W/g2" g2 "41 42" # memx: without p3_summary's D2 entries (index queries) + ident A splayed "$W/g0" "$P2" "$W/g2" "$P2" + measure C0 splayed "$W/g0" "$BB" base "$W/g0" "$P2" p2 + ident C0 splayed "$W/g0" "$BB" "$W/g0" "$P2" + rm -rf "$W/g0" "$W/g2" +} + +convert_parted() { # dir compress(true|false) + local s; s=$(mktemp -p "$W/g") + cat "$SCHEMA" > "$s" + printf '\n(do (.csv.parted {compress: %s} hit-types "%s" 1000000 "%s/" (quote hits)) null)\n' "$2" "$CSV" "$1" >> "$s" + "$P2" "$s" >/dev/null; rm -f "$s" +} + +make_ragged() { # dir: the last partition rewritten without its column tail from AdvEngineID on (generation 0) + # The parted loader associates columns by index and accepts a partition + # with fewer columns only as a missing tail (src/store/part.c), so the last + # partition keeps the columns before AdvEngineID (index 40 of 105; it lacks + # AdvEngineID, DontCountHits, IsLink, IsDownload, WindowClientWidth, + # RefererHash, URLHash and the rest; ResolutionWidth, index 20, stays). + local last s; last=$(find "$1" -mindepth 1 -maxdepth 1 -type d ! -name '.*' | sort -n | tail -1) + s=$(mktemp -p "$W/g") + printf '(set t (.db.splayed.get "%s/hits/" "%s/.sym"))\n(set cs (take (cols t) (first (where (== (cols t) %sAdvEngineID)))))\n(.db.splayed.set "%s/hits_r/" (table cs (map (fn [c] (at t c)) cs)) "%s/.sym" {compress: false})\n' \ + "$last" "$1" "'" "$last" "$1" > "$s" + "$BB" "$s" >/dev/null; rm -f "$s" # the base binary: plain column values, no lazy `at` + rm -rf "$last/hits"; mv "$last/hits_r" "$last/hits" + printf 'ragged\t%s\t%s\n' "$(basename "$last")" "$(ls "$last/hits" | grep -vc '^\.')" >> "$OUT" +} + +stage_parted() { + rel_guard "$P2"; rel_guard "$BB"; guard 11 + rm -rf "$W/p0" "$W/p2" + convert_parted "$W/p0" false + convert_parted "$W/p2" true + size B p0 "$W/p0"; size B p2 "$W/p2" + enc B parted "$W/p2" + mat B parted "$W/p2" + measure B parted "$W/p0" "$P2" p0 "$W/p2" "$P2" p2 + cold B parted "$W/p0" p0 "$W/p2" p2 + mem B parted "$W/p0" p0 "$W/p2" p2 + ident B parted "$W/p0" "$P2" "$W/p2" "$P2" + measure C1 parted "$W/p0" "$BB" base "$W/p0" "$P2" p2 + ident C1 parted "$W/p0" "$BB" "$W/p0" "$P2" + rm -rf "$W/p2" + make_ragged "$W/p0" + measure R parted "$W/p0" "$BB" base "$W/p0" "$P2" p2 + ident R parted "$W/p0" "$BB" "$W/p0" "$P2" + rm -rf "$W/p0" +} + +case "${1:?usage: p2_bench.sh prep|splayed|parted|all|verdict}" in + prep) prep ;; + splayed) stage_splayed ;; + parted) stage_parted ;; + all) rm -f "$OUT"; prep; stage_splayed; stage_parted ;; + verdict) python3 "$HERE/p2_summary.py" "$OUT" ;; +esac diff --git a/bench/compress_estimate/p2_summary.py b/bench/compress_estimate/p2_summary.py new file mode 100644 index 000000000..86bf29a45 --- /dev/null +++ b/bench/compress_estimate/p2_summary.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""P2 gate from p2.tsv (plan: compressed-columns P2, Task 17). Per-arm tables +and the GATE lines; every number comes from the file, nothing is typed.""" +import math, statistics, sys +from collections import defaultdict + +runs = defaultdict(list); cold = defaultdict(list); encs = defaultdict(list) +mat, mem, size, ident, meta, modes, ragged = {}, {}, {}, {}, {}, set(), None +bad_rows = [] +for line in open(sys.argv[1]): + f = line.rstrip("\n").split("\t") + k = f[0] + if k in ("m", "c"): + try: + if k == "m": runs[(f[1], f[2], f[3])].append([float(x) for x in f[5:11]]); assert len(f) == 11 + else: cold[(f[1], f[2], f[3])].append(float(f[5])); modes.add(f[6]) + except (ValueError, IndexError, AssertionError): + bad_rows.append("\t".join(f[:5])) + elif k == "mat": mat[(f[1], f[2])] = f[3].strip() + elif k == "enc": encs[f[1]].append(f[2]) + elif k == "mem": mem[(f[1], f[2])] = int(f[3]) + elif k == "size": size[(f[1], f[2])] = int(f[3]) + elif k == "ident": ident[(f[1], f[2])] = f[3:10] + elif k == "meta": meta[f[1]] = f[2:] + elif k == "ragged": ragged = f[1:] + +QS = [f"q{i}" for i in range(1, 44)] +# Cross-check only: the plan's pre-run "scan-only query" list. The class a +# query is gated in comes from the materialization the run measured (mat rows). +SCAN_ONLY = {"q1", "q2", "q3", "q4", "q7", "q8", "q16", "q17", "q18", "q33", "q34", "q35", "q39"} +# Noise floor (gate-triage.md G, RESULTS.md "Gate noise floor"): a clause passes +# at ratio <= bound, or when both medians are < 1 ms and the gap is <= 0.05 ms. +# Geometric means cover only queries whose base median is >= 1 ms. +FLOOR_MS, FLOOR_GAP_MS = 1.0, 0.05 +# P3 deferral table: (query, arms, metric, max_ratio, reason). metric is +# warm | first | cold | rss. Data only: the controller trims rows as the fix +# tasks land. +# GATE (P3-exempt) skips exactly these (query, arm, metric) clauses. +# Every P3 deferral cleared at the P3 gate (Ruling 14-8): see RESULTS.md, +# "P3 aware paths", subsection "Gate rerun (HEAD 2f949edc, after Task 14b)". +P3_DEFERRALS = [] +# Intended answer changes against the base binary (data only, ruling 14-2): +# (query, arm, reason). A DIFF listed here is not an answer failure on any +# GATE line; nothing else is ignored, and arms A, B and C0 still compare it. +INTENDED_ANSWER_CHANGES = [ + # #801: grouped take breaks ties on the earliest source row. q40's + # `take: 1010` cuts a 131-group tie at PageViews 13; HEAD returns the + # earliest-row tie set (= arms A, B, C0), the pre-fix base another. + ("q40", "C1", "#801 tie set at the take boundary"), + ("q40", "R", "#801 tie set at the take boundary"), +] +PI_SPLAYED_FIRST_TOTAL = 2.99 # RESULTS.md "PI index policy": gen-2 first-run total 7 740 vs 2 586 ms +ARMS = {"A": ("g0", "g2", "splayed g0 vs g2"), "B": ("p0", "p2", "parted p0 vs p2"), + "C0": ("base", "p2", "splayed g0, base vs p2 binary"), + "C1": ("base", "p2", "parted p0, base vs p2 binary"), + "R": ("base", "p2", "parted ragged, base vs p2 binary")} + +def gmean(xs): return math.exp(sum(math.log(x) for x in xs) / len(xs)) if xs else float("nan") +def stats(arm, v, q): + rs = runs.get((arm, v, q)) + if not rs: return None + warm = min(statistics.median(r[1:6]) for r in rs) # best round of the in-process medians + first = statistics.median(r[0] for r in rs) + three = statistics.median(sum(r[0:3]) for r in rs) + return warm, first, three +def ratio(a, b): return b / a if a > 0 else float("nan") + +def answer(arm, q): + """same | DIFF | noise (b differs from itself), and an order note.""" + if (arm, q) not in ident: return "?", "" + ra, rb, rb2, sa, sb, sb2, ordk = ident[(arm, q)] + if ordk == "ordered": + if ra == rb: return "same", "" + if sa == sb: return "same", "tie-order" # same rows, ties ordered differently + else: + if sa == sb: return "same", ("order" if ra != rb else "") + return ("noise" if sb != sb2 else "DIFF"), "" + +verdict_gate = {}; allraw = {}; verdict = {}; orders = defaultdict(list); worst = {} +for arm, (va, vb, title) in ARMS.items(): + if not any(k[0] == arm for k in runs): continue + print(f"## arm {arm}: {title} (ms; ratio = {vb}/{va})") + print("q\twarm_a\twarm_b\twr\tfirst_a\tfirst_b\tfr\t3run_a\t3run_b\ttr\tcold_a\tcold_b\tcr\tmaterialized\tanswers") + rows = {}; raw = {}; tot = [0.0] * 6; missing = [] + for q in QS: + sa, sb = stats(arm, va, q), stats(arm, vb, q) + if not sa or not sb: missing.append(q); continue + ca = statistics.median(cold[(arm, va, q)]) if cold.get((arm, va, q)) else float("nan") + cb = statistics.median(cold[(arm, vb, q)]) if cold.get((arm, vb, q)) else float("nan") + ans, note = answer(arm, q) + raw[q] = {0: (sa[0], sb[0]), 1: (sa[1], sb[1]), 3: (ca, cb)} + if note: orders[arm].append(f"{q}:{note}") + rows[q] = (ratio(sa[0], sb[0]), ratio(sa[1], sb[1]), ratio(sa[2], sb[2]), ratio(ca, cb), ans) + for i in range(3): tot[i] += sa[i]; tot[3 + i] += sb[i] + m = mat.get((arm, q), "") + print(f"{q}\t{sa[0]:.2f}\t{sb[0]:.2f}\t{rows[q][0]:.3f}\t{sa[1]:.2f}\t{sb[1]:.2f}\t{rows[q][1]:.3f}\t" + f"{sa[2]:.2f}\t{sb[2]:.2f}\t{rows[q][2]:.3f}\t{ca:.2f}\t{cb:.2f}\t{rows[q][3]:.3f}\t{m}\t" + f"{ans}{'/' + note if note else ''}") + print(f"totals over all 43: warm {tot[0]:.1f} vs {tot[3]:.1f} ({ratio(tot[0], tot[3]):.3f}); " + f"first run {tot[1]:.1f} vs {tot[4]:.1f} ({ratio(tot[1], tot[4]):.3f}); " + f"3-run {tot[2]:.1f} vs {tot[5]:.1f} ({ratio(tot[2], tot[5]):.3f})") + if missing: print("missing " + " ".join(missing)) + diffs = [q for q in rows if rows[q][4] != "same"] + print("answer_mismatches " + (" ".join(f"{q}:{rows[q][4]}" for q in diffs) if diffs else "none")) + print("order_differences " + (" ".join(orders[arm]) if orders[arm] else "none")) + def measured_scan(q): return mat.get((arm, q), "?") in ("[]", "") + scan = [q for q in QS if q in rows and measured_scan(q)] + other = [q for q in QS if q in rows and not measured_scan(q)] + disagree = [q for q in QS if q in rows and (q in SCAN_ONLY) != measured_scan(q)] + v = {} + intended = {q for q, a, _ in INTENDED_ANSWER_CHANGES if a == arm} + v["answers"] = not missing and all(rows[q][4] == "same" or (q in intended and rows[q][4] == "DIFF") for q in rows) + print("intended_answer_changes " + (" ".join(f"{q}:{rows[q][4]}" for q in sorted(intended) if q in rows) or "none")) + def top5(qs, i): return sorted(((round(rows[q][i], 3), q) for q in qs), reverse=True)[:5] + def clauses(qs, i, bound, metric): + """(query, passes) per query for ratio column i; a query below the + exempt table's metric is marked, the caller decides to skip it.""" + out = [] + for q in qs: + a_, b_ = raw[q][i] + ok = rows[q][i] <= bound or (a_ < FLOOR_MS and b_ < FLOOR_MS and abs(b_ - a_) <= FLOOR_GAP_MS) + out.append((q, ok)) + return out + def big(qs, i): return [rows[q][i] for q in qs if raw[q][i][0] >= FLOOR_MS] + if arm in ("A", "B"): + # gated as scan-only: measured scan-only, plus any SCAN_ONLY-list query + # that measured as materializing (it keeps its first and cold clauses) + gate = [q for q in QS if q in rows and (measured_scan(q) or q in SCAN_ONLY)] + other = [q for q in other if q not in gate] + unexpected = [q for q in gate if not measured_scan(q) and q in SCAN_ONLY and mat.get((arm, q)) is not None] + nomat = [q for q in rows if (arm, q) not in mat] + v["_unexpected"] = unexpected; v["_matmissing"] = nomat + v["_gate"] = gate + v["_g"] = {m: [(q, rows[q][i], raw[q][i][0]) for q in gate if not math.isnan(rows[q][i])] for m, i in (("warm", 0), ("first", 1), ("cold", 3))} + fails = {"warm": clauses(gate, 0, 1.05, "warm"), "first": clauses(gate, 1, 1.10, "first"), + "cold": [(q, ok) for q, ok in clauses(gate, 3, 1.10, "cold") if not math.isnan(rows[q][3])], + "materializing_warm": clauses(other, 0, 1.05, "warm")} + v["_clauses"] = fails + v["_cold_nan"] = any(math.isnan(rows[q][3]) for q in gate) + w, fr, c = big(gate, 0), big(gate, 1), big(gate, 3) + worst[arm] = {"warm": top5(gate, 0), "cold": top5(gate, 3), "first": top5(gate, 1), + "materializing_warm": top5(other, 0)} + print(f"scan_only(gated) n={len(gate)}; gmeans over base>=1ms (per column): warm n={len(w)} {gmean(w):.3f}, " + f"first n={len(fr)} {gmean(fr):.3f}, cold n={len(c)} {gmean(c):.3f}; worst warm={max([rows[q][0] for q in gate], default=float('nan')):.3f}") + for m, i in (("warm", 0), ("first", 1), ("cold", 3)): + sm = [q for q in gate if raw[q][i][0] < FLOOR_MS or math.isnan(raw[q][i][0])] + print(f"below_1ms_excluded_from_{m}_gmean " + (" ".join(sm) if sm else "none")) + print("mat rows missing " + (" ".join(nomat) if nomat else "none")) + print("scan_only_list_but_materializing " + (" ".join(unexpected) if unexpected else "none")) + print("measured_materializing " + (" ".join(f"{q}({len(mat.get((arm, q), '').strip('[]').split())} cols)" for q in QS if q in rows and not measured_scan(q)) if any(not measured_scan(q) for q in rows) else "none")) + print("class_vs_SCAN_ONLY_list_disagreements " + (" ".join(f"{q}(measured {'scan' if measured_scan(q) else 'materializing'}, list {'scan' if q in SCAN_ONLY else 'other'})" for q in disagree) if disagree else "none")) + for cl, lst in worst[arm].items(): print(f"worst5 {cl} {lst}") + if arm == "A": + ft = ratio(tot[1], tot[4]) + v["first_total"] = ft < PI_SPLAYED_FIRST_TOTAL + print(f"first_run_total_ratio {ft:.3f} (PI after P1: {PI_SPLAYED_FIRST_TOTAL})") + for q in ("q41", "q42"): + if q in rows: print(f"pi_row {q} warm {rows[q][0]:.3f} first {rows[q][1]:.3f} 3run {rows[q][2]:.3f}") + else: + w = big(list(rows), 0) + v["warm"] = len(rows) == 43 and all(ok for _, ok in clauses(list(rows), 0, 1.05, "warm")) and gmean(w) <= 1.00 + worst[arm] = {"warm": top5(list(rows), 0)} + print(f"gen0 warm_gmean(base>=1ms n={len(w)})={gmean(w):.3f} warm_worst={max([rows[q][0] for q in rows], default=float('nan')):.3f} " + f"worst5 {worst[arm]['warm']}") + if arm == "C1" and "q16" in rows: + s0, s1 = stats(arm, "base", "q16"), stats(arm, "p2", "q16") + v["q16_first"] = s1[1] < s0[1] + print(f"q16 first run base {s0[1]:.1f} ms, p2 {s1[1]:.1f} ms (carry 2)") + allraw[arm] = (rows, raw); verdict_gate[arm] = set(v.get('_gate', ())) + verdict[arm] = v + print() + +for arm, lines in encs.items(): + delta = [l for l in lines if "delta" in l] + print(f"enc {arm}: columns with DELTA vectors: {' '.join(delta) if delta else 'none'}") +if bad_rows: print("unparsed timing rows (query error?): " + "; ".join(bad_rows)) +print(f"sizes {size} peak_rss_kb {mem} evict_modes {','.join(sorted(modes))} ragged_partition {ragged} meta {meta}") + +COL = {"warm": 0, "first": 1, "cold": 3} +def exempt_ok(arm, q, m): + """The deferral for (q, arm, m) applies while its ratio stays <= max_ratio.""" + for dq, arms, dm, mx, _ in P3_DEFERRALS: + if dq == q and dm == m and arm in arms: + r = allraw[arm][0][q][COL[m]] if q in allraw[arm][0] else float("nan") + return r <= mx + return False +def deferred_any(arm, q): + return any(dq == q and arm in arms and dm != "rss" for dq, arms, dm, _, _ in P3_DEFERRALS) +def fields(arm, exempt): + v = dict(verdict.get(arm, {})) + cl = v.pop("_clauses", None); g = v.pop("_g", None); cn = v.pop("_cold_nan", False) + un = v.pop("_unexpected", []); nm = v.pop("_matmissing", []); v.pop("_gate", None) + if cl is None: return v + ex = (lambda q, m: exempt_ok(arm, q, m)) if exempt else (lambda q, m: False) + out = {"answers": v["answers"]} + for m in ("warm", "cold", "first"): + gm = gmean([r for q, r, base in g[m] if base >= FLOOR_MS and not ex(q, m)]) + out[m] = (all(ok for q, ok in cl[m] if not ex(q, m)) and gm <= (1.00 if m != "cold" else 0.9999) + and not (m == "cold" and cn)) + out["materializing_warm"] = all(ok for q, ok in cl["materializing_warm"] if not ex(q, "warm")) + out["no_unexpected_materialization"] = not nm and all(exempt and deferred_any(arm, q) for q in un) + if "first_total" in v: out["first_total"] = v["first_total"] + return out +def fmt(arm, exempt): + v = fields(arm, exempt) + return " ".join(f"{k}={'PASS' if ok else 'FAIL'}" for k, ok in v.items()) or "NOT-RUN" +for exempt, tag in ((False, "strict"), (True, "P3-exempt")): + print(f"GATE ({tag}) splayed[{fmt('A', exempt)}] parted[{fmt('B', exempt)}] gen0-splayed[{fmt('C0', exempt)}] " + f"gen0-parted[{fmt('C1', exempt)}] gen0-ragged[{fmt('R', exempt)}]") + ok = all(arm in verdict for arm in ARMS) and all(all(fields(a, exempt).values()) for a in ARMS if a in verdict) + print(f"P2 GATE ({tag}): " + ("PASS" if ok else "FAIL")) +parts = [] +for q, arms, m, mx, why in P3_DEFERRALS: + for arm in arms: + if arm not in allraw: continue + rows, raw = allraw[arm] + if m == "rss": + va, vb = ARMS[arm][0], ARMS[arm][1] + a_, b_ = mem.get((arm, va)), mem.get((arm, vb)) + r = ratio(a_, b_) if a_ and b_ else float("nan") + parts.append(f"{q}/{arm}/rss[{why}]: arm peak-RSS {a_} -> {b_} kB (x{r:.2f}, max {mx}) not gated" + + (" EXCEEDS-MAX" if r > mx else "")) + elif q in rows: + i = COL[m] + a_, b_ = raw[q][i]; r = rows[q][i] + bound = 1.05 if m == "warm" else 1.10 + gated = q in verdict_gate.get(arm, ()) or m == "warm" + if math.isnan(r): st = "no data (not gated)" + elif not gated: st = "not gated (materializing)" + elif r <= bound or (a_ < FLOOR_MS and b_ < FLOOR_MS and abs(b_ - a_) <= FLOOR_GAP_MS): st = "within-bound" + elif r <= mx: st = "EXEMPTED" + else: st = f"EXEMPTION-LAPSED (x{r:.3f} > max {mx})" + parts.append(f"{q}/{arm}/{m}[{why}]: {a_:.2f} -> {b_:.2f} ms (x{r:.3f}) {st}") +print("P3-EXEMPT LIST " + "; ".join(parts)) diff --git a/bench/compress_estimate/p3_summary.py b/bench/compress_estimate/p3_summary.py new file mode 100755 index 000000000..6a42afbee --- /dev/null +++ b/bench/compress_estimate/p3_summary.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""P3 gate (plan: compressed-columns P3, Task 14) from the P2 driver's TSV. +1. P2's summary, unchanged; its strict line must pass (no P3 exemption). +2. Materialization per query against the P3 expectations (arms A and B). +3. Peak RSS, generation 2 against generation 0 (open decision D3's bound), + judged without an arm's D2 index queries (ruling 10-1), all 43 beside it. +4. The P2 carries, each with its P2 re-run ratio and today's. +Every number comes from the file; nothing is typed.""" +import re, subprocess, sys, statistics +from collections import defaultdict +tsv = sys.argv[1] +here = sys.argv[0].rsplit("/", 1)[0] if "/" in sys.argv[0] else "." +p2 = subprocess.run([sys.executable, f"{here}/p2_summary.py", tsv], capture_output=True, text=True, check=True).stdout +print(p2, end="") +strict = re.search(r"^P2 GATE \(strict\): (PASS|FAIL)$", p2, re.M) + +mat, mem, memx, runs = {}, {}, {}, defaultdict(list) +for line in open(tsv): + f = line.rstrip("\n").split("\t") + if f[0] == "mat": mat[(f[1], f[2])] = f[3].strip() + elif f[0] == "mem": mem[(f[1], f[2])] = int(f[3]) + elif f[0] == "memx": memx[(f[1], f[2])] = (int(f[3]), frozenset(f[4].split(","))) + elif f[0] == "m" and len(f) == 11: + try: runs[(f[1], f[2], f[3])].append([float(x) for x in f[5:11]]) + except ValueError: pass + +# Columns a query may still materialize after P3, by class (spec: holistic +# aggregates and distinct counts, LIKE outside the fused paths, computed group +# keys, `set` of a column, top-k sort keys). Every other query: none. +# The entries once marked (confirm) were traced (gdb on enc_materialize_single / +# enc_materialize_parted, release build, commit 7a603266); the traced class is +# next to each, and RESULTS.md "P3 aware paths" has the frames. q12 and q40 +# materialized nothing on either arm and were narrowed out (ruling D7). +ALLOW = { + "q9": {"RegionID", "UserID"}, # count distinct (holistic) + "q10": {"RegionID", "UserID"}, # count distinct (holistic) + "q11": {"UserID", "MobilePhoneModel"}, # count distinct (holistic): traced, A only (key and argument) + "q14": {"UserID", "SearchPhrase"}, # count distinct (holistic): traced, A only + "q19": {"EventTime"}, # computed key (minute EventTime) + "q21": {"URL"}, # LIKE + "q22": {"URL"}, # LIKE: traced (exec_like), A and B + "q23": {"Title", "URL", "UserID"}, # LIKE (Title, URL), count distinct (UserID): traced + "q24": {"EventTime", "URL"}, # sort key (A, fused top-k); URL by LIKE outside the fused predicate (B): traced + "q25": {"EventTime"}, "q26": {"SearchPhrase"}, "q27": {"EventTime", "SearchPhrase"}, # sort keys + "q30": {"ResolutionWidth"}, # (set rw (at hits 'ResolutionWidth)) + "q43": {"EventTime"}, # computed key (xbar EventTime) +} +# Per-arm entries (ruling 14-3), outside the per-query table above. +ALLOW_ARM = { + ("A", "q23"): {"SearchPhrase"}, # the key of a count-distinct group (holistic), q10's RegionID class + ("B", "q6"): {"SearchPhrase"}, # count distinct (holistic); parted `at` reads the column eagerly (follow-up) +} +# D2: an indexed gen-2 column materializes on first index use (ruling 10-1). +D2 = { + ("A", "q41"): {"RefererHash"}, + ("A", "q42"): {"URLHash"}, +} +ALLOW_ARM.update(D2) +def cols(m): + if m.startswith("<"): return {"*many*"} + return set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", m)) +bad = [] +for arm in ("A", "B"): + for i in range(1, 44): + q = f"q{i}" + m = mat.get((arm, q)) + if m is None: bad.append(f"{arm}/{q}:no-mat-row"); continue + extra = cols(m) - ALLOW.get(q, set()) - ALLOW_ARM.get((arm, q), set()) + if extra: bad.append(f"{arm}/{q}:{'+'.join(sorted(extra))}") +print("p3_unexpected_materializations " + (" ".join(bad) if bad else "none")) + +RSS_BOUND = 1.10 # open decision D3 (recommended); the P2 re-run had splayed x1.58 +# The gate takes an arm's run without its D2 queries (ruling 10-1: their +# materialization is D2's stated cost); the 43-query figure is printed beside +# it. An arm with D2 entries needs the driver's memx rows over exactly them. +rss = {} +for arm, (a, b) in (("A", ("g0", "g2")), ("B", ("p0", "p2"))): + if (arm, a) in mem and (arm, b) in mem: + r43 = mem[(arm, b)] / mem[(arm, a)] + print(f"rss {arm}: {mem[(arm, a)]} -> {mem[(arm, b)]} kB (x{r43:.3f} over all 43, bound {RSS_BOUND})") + skip = frozenset(q for (ar, q) in D2 if ar == arm) + if not skip: + rss[arm] = r43 + continue + xa, xb = memx.get((arm, a)), memx.get((arm, b)) + if not xa or not xb or xa[1] != skip or xb[1] != skip: + print(f"rss {arm} without D2 {','.join(sorted(skip))}: no memx rows over exactly them") + rss[arm] = float("inf") + continue + rss[arm] = xb[0] / xa[0] + print(f"rss {arm} without D2 {','.join(sorted(skip))}: {xa[0]} -> {xb[0]} kB " + f"(x{rss[arm]:.3f}, bound {RSS_BOUND}, gated)") + +def ratio(arm, q, metric): + va, vb = {"A": ("g0", "g2"), "B": ("p0", "p2")}[arm] + ra, rb = runs.get((arm, va, q)), runs.get((arm, vb, q)) + if not ra or not rb: return float("nan") + if metric == "warm": a = min(statistics.median(r[1:6]) for r in ra); b = min(statistics.median(r[1:6]) for r in rb) + else: a = statistics.median(r[0] for r in ra); b = statistics.median(r[0] for r in rb) + return b / a if a > 0 else float("nan") +# The P2 carries (P2 re-run numbers, RESULTS.md "Remaining P3 deferrals"). +CARRIES = [("q2", "A", "warm", 1.086), ("q8", "A", "warm", 1.424), ("q8", "B", "warm", 1.060), + ("q18", "A", "first", 1.983), ("q18", "B", "warm", 1.088), ("q39", "A", "first", 2.402), + ("q39", "B", "first", 1.503), ("q42", "A", "warm", 1.664), ("q42", "B", "warm", 1.237)] +for q, arm, m, before in CARRIES: + print(f"carry {q}/{arm}/{m}: P2 x{before:.3f} -> P3 x{ratio(arm, q, m):.3f}") +ok_mat = not bad +ok_rss = all(r <= RSS_BOUND for r in rss.values()) and len(rss) == 2 +print(f"P3GATE p2_strict={'PASS' if strict and strict.group(1) == 'PASS' else 'FAIL'} " + f"materialization={'PASS' if ok_mat else 'FAIL'} rss={'PASS' if ok_rss else 'FAIL'}") +print("P3 GATE: " + ("PASS" if strict and strict.group(1) == "PASS" and ok_mat and ok_rss else "FAIL")) diff --git a/bench/compress_estimate/p4_bench.sh b/bench/compress_estimate/p4_bench.sh new file mode 100755 index 000000000..09f546bc4 --- /dev/null +++ b/bench/compress_estimate/p4_bench.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +# P4 gate (plan: compressed-columns P4, Task 10): index queries on the 10M +# store, generation 0 against generation 2, both carrying explicit HASH +# indexes on UserID, RefererHash and URLHash. Helpers are p2_bench.sh's. +# prep : HEAD's release build copied to $W/bin/p4; g0 / g2 copies of the +# splayed store with the three hashes (.db.splayed.set {compress}) +# warm : ROUNDS rounds, g0 / g2 alternated (order swapped each round); a +# process loads the store and runs the query 6 times (timeit, ms): +# run 1 materializes (generation 2) and builds nothing, runs 2..6 +# are the warm runs +# first : first index use, a fresh process with the store's files evicted +# from the page cache per file (dd iflag=nocache), 3 trials +# ident : every query's full answer, g0 against g2 (g2 twice), warm process +# and first-touch process (cache evicted), md5 raw and sorted +# uses : .idx.uses after each query, per variant (which index answered) +# clean : delete the copies +# kinds : the index kind of each copy's three columns (part of prep) +# all : prep warm first ident uses clean +# The load average is checked before every round and trial: below 1.5 or wait. +# Output: $W/p4.tsv ; the verdict is printed by p4_summary.py (never typed). +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +W=${W:-$REPO/build/p4_bench} +QUERIES= +USAGE="usage: p4_bench.sh [-w WORKDIR] -q QUERIES \n -w WORKDIR scratch directory (default $REPO/build/p4_bench)\n -q QUERIES the ClickBench rayforce queries.rfl\n" +while getopts "w:q:" o; do + case $o in + w) W=$OPTARG ;; + q) QUERIES=$OPTARG ;; + *) printf "%b" "$USAGE" >&2; exit 2 ;; + esac +done +shift $((OPTIND - 1)) +[ -n "$QUERIES" ] || { printf "%b" "$USAGE" >&2; exit 2; } +SRC=/skull/clickbench/rfsplayed +ROUNDS=${ROUNDS:-9} +OUT=$W/p4.tsv +BIN=$W/bin/p4 +mkdir -p "$W/g" "$W/bin" + +query_n() { # the n-th paren-balanced form of queries.rfl + awk -v want="$1" ' + /^[[:space:]]*$/ { next } + { q = q $0 "\n"; p = $0; gsub(/[^()]/, "", p) + for (i = 1; i <= length(p); i++) { c = substr(p, i, 1); if (c == "(") d++; else d-- } + if (d == 0) { n++; if (n == want) { printf "%s", q; exit } q = "" } }' "$QUERIES" +} +# q1: ClickBench q20 (the UserID point lookup, projecting: a count over a +# select is answered before the index arm). q2 / q3: the RefererHash / +# URLHash constants of q41 / q42 as bare projecting point lookups. q4 / q5: +# the whole q41 / q42 forms. +QD=$W/g/q; mkdir -p "$QD" +query_n 20 > "$QD/1.rfl" +grep -q '(== UserID 435090932899640449)' "$QD/1.rfl" || { echo "queries.rfl form 20 is not the UserID lookup" >&2; exit 2; } +printf '(select {RefererHash: RefererHash from: hits where: (== RefererHash 3594120000172545465)})\n' > "$QD/2.rfl" +printf '(select {URLHash: URLHash from: hits where: (== URLHash 2868770270353813622)})\n' > "$QD/3.rfl" +query_n 41 > "$QD/4.rfl"; query_n 42 > "$QD/5.rfl" +grep -q '3594120000172545465' "$QD/4.rfl" && grep -q '2868770270353813622' "$QD/5.rfl" \ + || { echo "queries.rfl forms 41 / 42 do not carry the hash constants" >&2; exit 2; } +NQ=5 + +guard() { # $1: GB free needed in $W + local avail; avail=$(df -B1 --output=avail "$W" | tail -1) + [ "$avail" -ge $(($1 * 1024 * 1024 * 1024)) ] || { echo "disk guard: need $1 GB in $W, have $avail" >&2; exit 2; } +} +rel_guard() { # a release build carries no sanitizer runtime + [ -x "$1" ] || { echo "$1 missing: run prep" >&2; exit 2; } + if grep -aq "__asan_init" "$1"; then echo "$1 is an ASan build" >&2; exit 2; fi +} +loadwait() { # wait until the 1-minute load average is below 1.5; logs waits + local t0; t0=$(date +%s) + until awk '{exit !($1 < 1.5)}' /proc/loadavg; do sleep 20; done + [ $(( $(date +%s) - t0 )) -lt 20 ] || printf 'loadwait\t%s\t%s\t%s\n' "$1" "$(date +%T)" "$(( $(date +%s) - t0 ))" >> "$OUT" +} +loadline() { printf '(set hits (.db.splayed.get "%s/"))\n' "$1"; } +evict() { # dir: per-file page-cache eviction + sync + find "$1" -type f -exec dd if={} iflag=nocache count=0 status=none \; +} +answer() { # dir q file: the full result of query q written to file; a result that is + # not a table (an error: every query here is a select) leaves file.err + local s c; s=$(mktemp -p "$W/g"); c=$(mktemp -p "$W/g" --suffix=.csv); rm -f "$c" + { loadline "$1"; printf '(set r %s)\n' "$(cat "$QD/$2.rfl")" + printf '(if (== (type r) (quote TABLE)) (.csv.write r "%s") (println r))\n' "$c"; } > "$s" + "$BIN" "$s" > "$3.stdout" 2>&1 || true; rm -f "$s" + rm -f "$3.err" + if [ -f "$c" ]; then mv "$c" "$3"; else cp "$3.stdout" "$3"; : > "$3.err"; fi + rm -f "$3.stdout" +} +# An error output hashes as ERR-: never equal to the other side's. +h_raw() { if [ -f "$1.err" ]; then echo "ERR-$(basename "$1")"; else md5sum < "$1" | cut -c1-12; fi; } +h_sort() { if [ -f "$1.err" ]; then echo "ERR-$(basename "$1")"; return; fi + { head -n 1 "$1"; tail -n +2 "$1" | LC_ALL=C sort; } | md5sum | cut -c1-12; } +rows() { echo $(( $(wc -l < "$1") - 1 )); } + +prep() { + guard 11 + ( cd "$REPO" && make release >/dev/null ) + cp "$REPO/rayforce" "$BIN"; rel_guard "$BIN" + printf 'meta\tp4\t%s\t%s\n' "$(git -C "$REPO" rev-parse --short HEAD)" "$(sha256sum "$BIN" | cut -c1-12)" >> "$OUT" + rm -rf "$W/g0" "$W/g2" + local s; s=$(mktemp -p "$W/g") + cat > "$s" <&1); rm -f "$s" + printf 'srckind\t%s\n' "$(printf '%s\n' "$o" | grep -m1 hash || true)" >> "$OUT" + for v in g0 g2; do printf 'size\t%s\t%s\n' "$v" "$(du -sb "$W/$v" | cut -f1)" >> "$OUT"; done + kinds +} + +kinds() { # the index kind each copy's columns carry once loaded (and materialized) + local v s o + for v in g0 g2; do + s=$(mktemp -p "$W/g") + { loadline "$W/$v"; printf "(println (map (fn [c] (at (.idx.info (at hits c)) 'kind)) ['UserID 'RefererHash 'URLHash]))\n"; } > "$s" + o=$("$BIN" "$s" 2>&1) || true; rm -f "$s" + printf 'kind\t%s\t%s\n' "$v" "$(printf '%s\n' "$o" | tail -1)" >> "$OUT" + done +} + +warm() { + rel_guard "$BIN" + local round q v order s r + for round in $(seq 1 "$ROUNDS"); do + loadwait "warm$round" + if [ $((round % 2)) = 1 ]; then order="g0 g2"; else order="g2 g0"; fi + for q in $(seq 1 $NQ); do + for v in $order; do + s=$(mktemp -p "$W/g") + { loadline "$W/$v"; for i in 1 2 3 4 5 6; do printf '(println (timeit %s))\n' "$(cat "$QD/$q.rfl")"; done; } > "$s" + r=$("$BIN" "$s" 2>/dev/null | tail -6 | tr '\n' '\t') || true; rm -f "$s" + printf 'm\t%s\tq%s\t%s\t%s\n' "$v" "$q" "$round" "${r%$'\t'}" >> "$OUT" + done + done + echo "warm round $round done $(date +%T)" >&2 + done +} + +first() { + rel_guard "$BIN" + local trial q v order s r + for trial in 1 2 3; do + loadwait "first$trial" + if [ $((trial % 2)) = 1 ]; then order="g0 g2"; else order="g2 g0"; fi + for q in $(seq 1 $NQ); do + for v in $order; do + evict "$W/$v" + s=$(mktemp -p "$W/g") + { loadline "$W/$v"; printf '(println (timeit %s))\n' "$(cat "$QD/$q.rfl")"; } > "$s" + r=$("$BIN" "$s" 2>/dev/null | tail -1) || true; rm -f "$s" + printf 'f\t%s\tq%s\t%s\t%s\n' "$v" "$q" "$trial" "$r" >> "$OUT" + done + done + echo "first trial $trial done $(date +%T)" >&2 + done +} + +ident() { # warm answers (g2 twice) and first-touch answers (cache evicted) + rel_guard "$BIN" + local q ad=$W/ans fa fb fb2 ord + rm -rf "$ad"; mkdir -p "$ad" + for q in $(seq 1 $NQ); do + if grep -Eq '(asc|desc):' "$QD/$q.rfl"; then ord=ordered; else ord=unordered; fi + fa=$ad/q$q.g0; fb=$ad/q$q.g2; fb2=$ad/q$q.g2b + answer "$W/g0" "$q" "$fa"; answer "$W/g2" "$q" "$fb"; answer "$W/g2" "$q" "$fb2" + printf 'ident\twarm\tq%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$q" \ + "$(h_raw "$fa")" "$(h_raw "$fb")" "$(h_raw "$fb2")" \ + "$(h_sort "$fa")" "$(h_sort "$fb")" "$(h_sort "$fb2")" "$ord" "$(rows "$fa")" >> "$OUT" + fa=$ad/q$q.g0f; fb=$ad/q$q.g2f + evict "$W/g0"; answer "$W/g0" "$q" "$fa" + evict "$W/g2"; answer "$W/g2" "$q" "$fb" + printf 'ident\tfirst\tq%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$q" \ + "$(h_raw "$fa")" "$(h_raw "$fb")" "$(h_raw "$fb")" \ + "$(h_sort "$fa")" "$(h_sort "$fb")" "$(h_sort "$fb")" "$ord" "$(rows "$fa")" >> "$OUT" + done + echo "ident done $(date +%T)" >&2 +} + +uses() { # which index each query consulted, and what it left materialized + rel_guard "$BIN" + local q v s + for q in $(seq 1 $NQ); do + for v in g0 g2; do + s=$(mktemp -p "$W/g") + { loadline "$W/$v"; printf '(do (.idx.uses hits) null)\n(do %s null)\n(println (.idx.uses hits))\n' "$(cat "$QD/$q.rfl")" + printf '(println (at (cols hits) (where (raze (map (fn [c] (at (.idx.info hits c) (quote materialized))) (cols hits))))))\n'; } > "$s" + printf 'uses\t%s\tq%s\t%s\n' "$v" "$q" "$("$BIN" "$s" 2>&1 | tail -2 | tr '\n' '\t' | sed 's/\t$//')" >> "$OUT" + rm -f "$s" + done + done +} + +clean() { rm -rf "$W/g0" "$W/g2" "$W/ans"; } + +[ $# -gt 0 ] || { echo "usage: p4_bench.sh prep|kinds|warm|first|ident|uses|clean|all ..." >&2; exit 2; } +for stage in "$@"; do # stages run in the order given + case "$stage" in + prep) prep ;; + kinds) kinds ;; + warm) warm ;; + first) first ;; + ident) ident ;; + uses) uses ;; + clean) clean ;; + all) rm -f "$OUT"; prep; warm; first; ident; uses; clean ;; + *) echo "unknown stage $stage" >&2; exit 2 ;; + esac +done diff --git a/bench/compress_estimate/p4_summary.py b/bench/compress_estimate/p4_summary.py new file mode 100644 index 000000000..60070e613 --- /dev/null +++ b/bench/compress_estimate/p4_summary.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""P4 gate summary from p4_bench.sh's TSV: the index queries, generation 2 +against generation 0 on the same release binary. +- warm: per process, the median of runs 2..6 (run 1 is the warm-up, where + generation 2 materializes the column and attaches its index); the table + gives the median over the rounds and the best round (P2's statistic). +- first: a fresh process with the store's files evicted from the page cache, + median of the trials; reported, not gated (spec "Benchmarks"). +- answers: every query's full answer, warm and first-touch, g0 against g2. +Gate: each warm median at most 1.05x generation 0, or, when both are below +1 ms, a gap of at most 0.05 ms (P2's noise floor, Ruling 14-8). Every number +comes from the file; nothing is typed.""" +import collections, statistics, sys +FLOOR_MS, FLOOR_GAP_MS, BOUND = 1.0, 0.05, 1.05 +runs = collections.defaultdict(list) # (v, q) -> [[t1..t6] per round] +firsts = collections.defaultdict(list) # (v, q) -> [t per trial] +sizes, kinds, ident, uses, meta, waits, srckind = {}, {}, {}, {}, {}, [], "" +for line in open(sys.argv[1]): + f = line.rstrip("\n").split("\t") + k = f[0] + if k == "size": sizes[f[1]] = int(f[2]) + elif k == "kind": kinds[f[1]] = f[2] if len(f) > 2 else "" + elif k == "srckind": srckind = f[1] if len(f) > 1 else "" + elif k == "meta": meta[f[1]] = f[2:] + elif k == "loadwait": waits.append(f[1:]) + elif k == "m" and len(f) == 10: + try: runs[(f[1], f[2])].append([float(x) for x in f[4:10]]) + except ValueError: pass + elif k == "f" and len(f) == 5: + try: firsts[(f[1], f[2])].append(float(f[4])) + except ValueError: pass + elif k == "ident": ident[(f[1], f[2])] = f[3:] + elif k == "uses": uses[(f[1], f[2])] = "\t".join(f[3:]) + +QS = [f"q{i}" for i in range(1, 6)] +NAMES = {"q1": "UserID point lookup (ClickBench q20)", "q2": "RefererHash point lookup (q41's constant)", + "q3": "URLHash point lookup (q42's constant)", "q4": "ClickBench q41", "q5": "ClickBench q42"} +def med(xs): return statistics.median(xs) if xs else float("nan") +def answers(mode, q): + r = ident.get((mode, q)) + if not r: return "?" + a, b, b2, sa, sb, sb2, order = r[:7] + if any(h.startswith("ERR") for h in (a, b, b2)): return "ERROR" # an error on either side + if b != b2 or sb != sb2: return "noise" + if a == b: return "same" + if sa == sb: return "order" if order == "ordered" else "same(sorted)" + return "DIFF" +ok_warm, ok_ans, missing = True, True, [] +print("| query | warm g0 ms | warm g2 ms | ratio | best round g0 / g2 (ratio) | in-process run 1 g0 / g2 | first touch g0 / g2 ms | rows | answers warm / first |") +print("|---|---|---|---|---|---|---|---|---|") +for q in QS: + r0, r2 = runs.get(("g0", q)), runs.get(("g2", q)) + if not r0 or not r2: missing.append(q); ok_warm = False; continue + m0 = [med(r[1:6]) for r in r0]; m2 = [med(r[1:6]) for r in r2] + w0, w2 = med(m0), med(m2); b0, b2 = min(m0), min(m2) + ratio = w2 / w0 if w0 > 0 else float("nan") + ok = ratio <= BOUND or (w0 < FLOOR_MS and w2 < FLOOR_MS and abs(w2 - w0) <= FLOOR_GAP_MS) + ok_warm &= ok + p0, p2 = med([r[0] for r in r0]), med([r[0] for r in r2]) + f0, f2 = med(firsts.get(("g0", q), [])), med(firsts.get(("g2", q), [])) + aw, af = answers("warm", q), answers("first", q) + ok_ans &= aw in ("same", "same(sorted)") and af in ("same", "same(sorted)") + nrows = ident.get(("warm", q), [""] * 8)[7] if len(ident.get(("warm", q), [])) > 7 else "?" + print(f"| {q} {NAMES[q]} | {w0:.3f} | {w2:.3f} | {ratio:.3f}{'' if ok else ' FAIL'} | {b0:.3f} / {b2:.3f} ({b2 / b0 if b0 > 0 else float('nan'):.3f}) " + f"| {p0:.3f} / {p2:.3f} | {f0:.1f} / {f2:.1f} | {nrows} | {aw} / {af} |") +print(f"\nrounds: {min((len(v) for v in runs.values()), default=0)}; first-touch trials: {min((len(v) for v in firsts.values()), default=0)}") +print(f"sizes: g0 {sizes.get('g0', 0)} B, g2 {sizes.get('g2', 0)} B (x{sizes.get('g2', 0) / sizes['g0'] if sizes.get('g0') else float('nan'):.3f})") +print(f"index kinds (UserID RefererHash URLHash): source {srckind}; g0 {kinds.get('g0', '?')}; g2 {kinds.get('g2', '?')}") +for q in QS: + print(f"uses {q}: g0 {uses.get(('g0', q), '?')} | g2 {uses.get(('g2', q), '?')}") +print("meta " + " ".join(f"{k}={'/'.join(v)}" for k, v in meta.items())) +print("load waits " + (" ".join("/".join(w) for w in waits) if waits else "none")) +if missing: print("missing " + " ".join(missing)) +print(f"\n**P4 index answers: {'PASS' if ok_ans and not missing else 'FAIL'}** (every query's full answer, warm and first touch, g2 equal to g0)") +print(f"**P4 index queries warm: {'PASS' if ok_warm else 'FAIL'}** (each warm median at most {BOUND}x generation 0, or under {FLOOR_MS:.0f} ms within {FLOOR_GAP_MS} ms)") diff --git a/bench/compress_estimate/p5_bench.sh b/bench/compress_estimate/p5_bench.sh new file mode 100755 index 000000000..8173cc88b --- /dev/null +++ b/bench/compress_estimate/p5_bench.sh @@ -0,0 +1,193 @@ +#!/usr/bin/env bash +# P5 measurement (plan: compressed-columns P5, Task 8, pre-flight D9). +# The ClickBench store has no float column, so the float store is derived +# from it: five F64 columns and one F32 computed from real integer columns +# of the 10M .db.splayed.get store, saved g0 / g2, measured, deleted. +# prep : release binary copied, store derived and saved (save times recorded); +# the TSV is started afresh, so a stale pass never mixes with this one +# enc : per-column encoding mix and sizes of g2; per-vector ALP / ALP_RD +# exception counts and DICT code children (p5_vecscan.py, O1) +# warm : every query, ROUNDS alternated rounds (order swapped), one process +# per round and variant: run 1 = first, runs 2..6 -> warm median +# cold : 3 trials per variant, the store's files evicted first (fadvise) +# ident: the full answer of every query, g0 vs g2 (g0 run twice, so float +# sum drift (#744) is told apart from a g2 difference); raw and sorted +# wall : per-call wall time of every query, g0 / g2, WALLS (5) alternated rounds +# savet: the writer cost (O5): SAVES alternated rounds of the g0 and g2 +# saves of the derived table, with this binary and with BASE's +# (`git archive`), each into a scratch store deleted after the round +# clean: delete the stores +# usage: p5_bench.sh [-w WORKDIR] prep | enc | warm | cold | ident | wall | savet | clean | all +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +W=${W:-$REPO/build/p5_bench} +USAGE="usage: p5_bench.sh [-w WORKDIR] \n -w WORKDIR scratch directory (default $REPO/build/p5_bench)\n" +while getopts "w:" o; do + case $o in + w) W=$OPTARG ;; + *) printf "%b" "$USAGE" >&2; exit 2 ;; + esac +done +shift $((OPTIND - 1)) +SRC=/skull/clickbench/rfsplayed +ROUNDS=${ROUNDS:-9} +SAVES=${SAVES:-3} +WALLS=${WALLS:-5} +BASE=${BASE:-81c04acb} +OUT=$W/p5.tsv +BIN=$W/bin/p5 +BB=$W/bin/base +mkdir -p "$W/g" "$W/bin" +QS=( + '(sum (at t (quote price)))' + '(avg (at t (quote sendt)))' + '(min (at t (quote ratio)))' + '(max (at t (quote f32)))' + '(count (select {from: t where: (> price 12.5)}))' + '(count (select {from: t where: (== level 213.0)}))' + '(count (select {from: t where: (< ratio 0.25)}))' + '(count (select {from: t where: (and (>= sendt 0.5) (< sendt 1.5))}))' + '(select {s: (sum price) c: (count price) from: t by: refresh})' + '(select {p: price from: t desc: price take: 10})' +) +guard() { local a; a=$(df -B1 --output=avail "$W" | tail -1) + [ "$a" -ge $(($1 * 1024 * 1024 * 1024)) ] || { echo "disk guard: need $1 GB in $W, have $a" >&2; exit 2; }; } +rel_guard() { [ -x "$1" ] || { echo "$1 missing: run prep" >&2; exit 2; } + if grep -aq "__asan_init" "$1"; then echo "$1 is an ASan build" >&2; exit 2; fi; } +calm() { while ! awk '{exit !($1 < 1.5)}' /proc/loadavg; do printf 'wait\t%s\t%s\n' "$(date +%T)" "$(cut -d' ' -f1 /proc/loadavg)" >> "$OUT"; sleep 30; done; } +evict() { sync; find "$1" -type f -exec dd if={} iflag=nocache count=0 status=none \; ; } +loadline() { printf '(set t (.db.splayed.get "%s/%s/"))\n' "$W" "$1"; } +derive() { # the derived float table, bound to t (pre-flight D9) + cat < "$s" + "$BIN" "$s" > "$3.err" 2>&1 || true; rm -f "$s" + # no csv: a FAIL marker, never the error text (the same error on g0 and + # g2 would hash the same and read as "same") + if [ -f "$c" ]; then mv "$c" "$3"; rm -f "$3.err"; else { echo FAIL; cat "$3.err"; } > "$3"; rm -f "$3.err"; fi +} +h_or_fail() { if [ "$(head -n 1 "$2")" = FAIL ]; then echo FAIL; else "$1" "$2"; fi; } +case "${1:?usage: p5_bench.sh prep|enc|warm|cold|ident|wall|savet|clean|all}" in +prep) + guard 4 + ( cd "$REPO" && make release >/dev/null ); cp "$REPO/rayforce" "$BIN"; rel_guard "$BIN" + : > "$OUT" + printf 'nq\t%s\n' "${#QS[@]}" >> "$OUT" + printf 'meta\tp5\t%s\t%s\n' "$(git -C "$REPO" rev-parse --short HEAD)" "$(sha256sum "$BIN" | cut -c1-12)" >> "$OUT" + rm -rf "$W/g0" "$W/g2" + s=$(mktemp -p "$W/g") + { derive; printf '(println (timeit (.db.splayed.set "%s/g0/" t {compress: false})))\n(println (timeit (.db.splayed.set "%s/g2/" t {compress: true})))\n' "$W" "$W"; } > "$s" + "$BIN" "$s" | tail -2 | paste -sd '\t' | awk '{printf "save\tg0\t%s\nsave\tg2\t%s\n", $1, $2}' >> "$OUT"; rm -f "$s" + for v in g0 g2; do printf 'size\t%s\t%s\n' "$v" "$(du -sb "$W/$v" | cut -f1)" >> "$OUT"; done + ;; +enc) + s=$(mktemp -p "$W/g") + { loadline g2; printf '(map (fn [c] (println (format "col\\t%%\\t%%\\t%%\\t%%" c (at (.idx.info t c) (quote encoded_bytes)) (at (.idx.info t c) (quote raw_bytes)) (at (.idx.info t c) (quote enc))))) (cols t))\nnull\n'; } > "$s" + "$BIN" "$s" | grep '^col' >> "$OUT"; rm -f "$s" + python3 "$HERE/p5_vecscan.py" "$W/g2" >> "$OUT" + ;; +warm) + rel_guard "$BIN" + for round in $(seq 1 "$ROUNDS"); do + calm + if [ $((round % 2)) = 1 ]; then order="g0 g2"; else order="g2 g0"; fi + for qn in "${!QS[@]}"; do q=${QS[$qn]} + for v in $order; do + s=$(mktemp -p "$W/g") + { loadline "$v"; for k in 1 2 3 4 5 6; do printf '(println (timeit %s))\n' "$q"; done; } > "$s" + # an erroring run (non-zero exit: a script stops at its first error) + # is a FAIL row, which the summary counts as a failure + if o=$("$BIN" "$s" 2>/dev/null); then r=$(printf '%s\n' "$o" | tail -6 | paste -sd '\t'); else r=FAIL; fi; rm -f "$s" + printf 'm\t%s\tq%s\t%s\t%s\n' "$v" "$qn" "$round" "$r" >> "$OUT" + done + done + echo "warm round $round done" >&2 + done + ;; +cold) + rel_guard "$BIN" + for qn in "${!QS[@]}"; do q=${QS[$qn]} + for trial in 1 2 3; do for v in g0 g2; do + calm; evict "$W/$v" + s=$(mktemp -p "$W/g") + { loadline "$v"; printf '(println (timeit %s))\n' "$q"; } > "$s" + if o=$("$BIN" "$s" 2>/dev/null); then r=$(printf '%s\n' "$o" | tail -1); else r=FAIL; fi; rm -f "$s" + printf 'c\t%s\tq%s\t%s\t%s\n' "$v" "$qn" "$trial" "$r" >> "$OUT" + done; done + done + ;; +ident) + for qn in "${!QS[@]}"; do q=${QS[$qn]} + a=$W/g/out_g0; b=$W/g/out_g2; a2=$W/g/out_g0b + answer g0 "$q" "$a"; answer g2 "$q" "$b"; answer g0 "$q" "$a2" + printf 'ident\tq%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$qn" "$(h_or_fail h_raw "$a")" "$(h_or_fail h_raw "$b")" "$(h_or_fail h_raw "$a2")" \ + "$(h_or_fail h_sort "$a")" "$(h_or_fail h_sort "$b")" "$(h_or_fail h_sort "$a2")" >> "$OUT" + printf 'answer\tq%s\tg0\t%s\n' "$qn" "$(head -c 300 "$a" | tr '\n\t' ' ')" >> "$OUT" + printf 'answer\tq%s\tg2\t%s\n' "$qn" "$(head -c 300 "$b" | tr '\n\t' ' ')" >> "$OUT" + done + ;; +savet) + rel_guard "$BIN"; guard 4 + if [ ! -x "$BB" ]; then + rm -rf "$W/base_src"; mkdir -p "$W/base_src" + ( cd "$REPO" && git archive "$BASE" ) | tar -x -C "$W/base_src" + ( cd "$W/base_src" && make release >/dev/null ) + cp "$W/base_src/rayforce" "$BB"; rm -rf "$W/base_src" + fi + rel_guard "$BB" + printf 'meta\tbase\t%s\t%s\n' "$BASE" "$(sha256sum "$BB" | cut -c1-12)" >> "$OUT" + for round in $(seq 1 "$SAVES"); do + if [ $((round % 2)) = 1 ]; then order="p5 base"; else order="base p5"; fi + for b in $order; do + if [ "$b" = p5 ]; then x=$BIN; else x=$BB; fi + calm; rm -rf "$W/s0" "$W/s2" + s=$(mktemp -p "$W/g") + { derive; printf '(println (timeit (.db.splayed.set "%s/s0/" t {compress: false})))\n(println (timeit (.db.splayed.set "%s/s2/" t {compress: true})))\n' "$W" "$W"; } > "$s" + r=$("$x" "$s" | tail -2 | paste -sd '\t'); rm -f "$s" + printf 'savet\t%s\t%s\t%s\t%s\t%s\n' "$b" "$round" "$r" "$(du -sb "$W/s0" | cut -f1)" "$(du -sb "$W/s2" | cut -f1)" >> "$OUT" + rm -rf "$W/s0" "$W/s2" + done + done + ;; +wall) # per-call wall time, (T(1 + K) - T(1)) / K over K top-level calls: (timeit q) on a + # plain generation-0 vector reports the reduction as ~0 ms (q0, q1), so the warm + # ratio of those queries is not a scan-to-scan ratio; this one is + rel_guard "$BIN"; K=100 + for round in $(seq 1 "$WALLS"); do + calm + if [ $((round % 2)) = 1 ]; then order="g0 g2"; else order="g2 g0"; fi + for qn in "${!QS[@]}"; do q=${QS[$qn]} + for v in $order; do + t=(); ok=1 + for n in 1 $((K + 1)); do + s=$(mktemp -p "$W/g") + { loadline "$v"; for k in $(seq 1 $n); do printf '(set r %s)\n' "$q"; done; } > "$s" + # an erroring run stops early and would time as fast: fail it, never time it + a=$(date +%s%N); "$BIN" "$s" >/dev/null 2>&1 || ok=0; b=$(date +%s%N); rm -f "$s" + t+=($(( (b - a) / 1000 ))) + done + if [ "$ok" = 1 ]; then w=$(awk -v a="${t[0]}" -v b="${t[1]}" -v k=$K 'BEGIN{printf "%.3f", (b - a) / k / 1000.0}'); else w=FAIL; fi + printf 'wall\t%s\tq%s\t%s\t%s\n' "$v" "$qn" "$round" "$w" >> "$OUT" + done + done + done + ;; +clean) rm -rf "$W/g0" "$W/g2" "$W/s0" "$W/s2" "$W/g" ;; +all) for st in prep enc ident warm cold wall savet clean; do "$0" -w "$W" "$st"; done ;; +esac diff --git a/bench/compress_estimate/p5_summary.py b/bench/compress_estimate/p5_summary.py new file mode 100755 index 000000000..71f467ac2 --- /dev/null +++ b/bench/compress_estimate/p5_summary.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""P5 float-store summary: per-column bytes and mix, store sizes, save +times, warm / first / cold medians g2 / g0, answer identity, and the +scan-only warm line (spec Benchmarks; pre-flight D9). Also the carried +items: the ALP / ALP_RD exception rates and the DICT vectors with RAW codes +per column (O1, the short DICT tail), and the writer cost against BASE (O5). +Every number comes from the TSV; nothing is typed.""" +import collections, statistics, sys +m = collections.defaultdict(list); c = collections.defaultdict(list); wall = collections.defaultdict(list) +cols, vecs, sizes, saves, ident, savet, meta, waits = [], [], {}, {}, {}, collections.defaultdict(list), {}, [] +nq = 10; bad_rows = [] +# A per-query ratio is taken from the `wall` stage when the timeit g0 median +# is below FLOOR ms ((timeit q) reports a top-level reduction on a plain +# vector as ~0 ms); a wall time below FLOOR is below the stage's resolution +# and is floored to it, so two sub-resolution times compare as 1.0. +FLOOR = 0.05 +XCHECK = 0.10 # the largest timeit / wall ratio gap printed without CHECK +def nums(xs): + try: return [float(x) for x in xs if x] + except ValueError: return None +for line in open(sys.argv[1]): + f = line.rstrip("\n").split("\t") + if f[0] == "col": cols.append(f[1:]) + elif f[0] == "vec": vecs.append(f[1:]) + elif f[0] == "size": sizes[f[1]] = int(f[2]) + elif f[0] == "save": saves[f[1]] = float(f[2]) + elif f[0] == "meta": meta[f[1]] = f[2:] + elif f[0] == "wait": waits.append(f[1:]) + elif f[0] == "ident": ident[f[1]] = f[2:] + elif f[0] == "savet" and len(f) >= 5 and f[3] and f[4]: + savet[(f[1], "g0")].append(float(f[3])); savet[(f[1], "g2")].append(float(f[4])) + if len(f) >= 7: savet[(f[1], "size_g0")].append(int(f[5])); savet[(f[1], "size_g2")].append(int(f[6])) + elif f[0] == "nq": nq = int(f[1]) + elif f[0] == "m": + t = nums(f[4:]) + if t is not None and len(t) == 6: m[(f[1], f[2], "first")].append(t[0]); m[(f[1], f[2], "warm")].append(statistics.median(t[1:])) + else: bad_rows.append(("warm", f[1], f[2], f[3])) + elif f[0] == "wall": + t = nums(f[4:5]) + if t: wall[(f[1], f[2])].append(t[0]) + else: bad_rows.append(("wall", f[1], f[2], f[3])) + elif f[0] == "c": + t = nums(f[4:5]) + if t: c[(f[1], f[2])].append(t[0]) + else: bad_rows.append(("cold", f[1], f[2], f[3])) +print(f"meta {meta}") +print("| column | encoded B | raw B | ratio | mix |\n|---|---|---|---|---|") +for name, e, r, mix in cols: print(f"| {name} | {e} | {r} | {int(r) / max(int(e), 1):.2f}x | {mix} |") +if vecs: + print("\n| column | type | vectors | ALP vecs | ALP exc / rows | ALP (e,f) | ALP_RD vecs | ALP_RD exc / rows | DICT vecs | DICT w/ RAW codes (last vec) | trailers |") + print("|---|---|---|---|---|---|---|---|---|---|---|") + for v in vecs: + name, ty, rows, nv, a, ar, ae, d, dr, de, dc, dcr, dcl, tr, ef = v + rate = lambda x, y: f"{int(x)} / {int(y)} ({100.0 * int(x) / int(y):.2f}%)" if int(y) else "-" + print(f"| {name} | {ty} | {nv} | {a} | {rate(ae, ar)} | {ef} | {d} | {rate(de, dr)} | {dc} | {dcr} ({dcl}) | {tr} |") +print(f"\nstore: g0 {sizes.get('g0', 0)} B, g2 {sizes.get('g2', 0)} B (x{sizes.get('g2', 0) / max(sizes.get('g0', 1), 1):.3f}); " + f"save g0 {saves.get('g0', 0):.0f} ms, g2 {saves.get('g2', 0):.0f} ms (prep, one run)\n") +if savet: + print("| writer (O5) | save g0 ms | save g2 ms | g2 / g0 | runs |\n|---|---|---|---|---|") + for b in ("p5", "base"): + if savet[(b, "g0")]: + s0 = statistics.median(savet[(b, "g0")]); s2 = statistics.median(savet[(b, "g2")]) + print(f"| {b} | {s0:.0f} | {s2:.0f} | {s2 / s0:.3f} | {len(savet[(b, 'g0')])} |") + if savet[("p5", "g2")] and savet[("base", "g2")]: + print(f"\nsave g2 p5 / base: {statistics.median(savet[('p5', 'g2')]) / statistics.median(savet[('base', 'g2')]):.3f}; " + f"save g0 p5 / base: {statistics.median(savet[('p5', 'g0')]) / statistics.median(savet[('base', 'g0')]):.3f}") + if savet[("base", "size_g2")]: + print(f"g2 store bytes: p5 {savet[('p5', 'size_g2')][0]}, base {savet[('base', 'size_g2')][0]}; " + f"g0: p5 {savet[('p5', 'size_g0')][0]}, base {savet[('base', 'size_g0')][0]}\n") +print("| query | warm g0 | warm g2 | ratio | first g0 | first g2 | cold g0 | cold g2 | ratio | answers |\n|---|---|---|---|---|---|---|---|---|---|") +want = [f"q{i}" for i in range(nq)] +missing = [] +for q in want: + for what, have in (("warm", m.get(("g0", q, "warm")) and m.get(("g2", q, "warm"))), + ("cold", c.get(("g0", q)) and c.get(("g2", q))), + ("wall", wall.get(("g0", q)) and wall.get(("g2", q))), + ("ident", q in ident)): + if not have: missing.append(f"{q}/{what}") +med = lambda xs: statistics.median(xs) if xs else float("nan") +ratio = lambda a, b: b / a if a > 0 else float("nan") +same = True; scan = {} +for q in want: + w0 = med(m.get(("g0", q, "warm"))); w2 = med(m.get(("g2", q, "warm"))) + f0 = med(m.get(("g0", q, "first"))); f2 = med(m.get(("g2", q, "first"))) + c0 = med(c.get(("g0", q))); c2 = med(c.get(("g2", q))) + i = ident.get(q) + if i is None: ok, how = False, "missing" + elif "FAIL" in i: ok, how = False, "FAIL (no answer)" + elif i[0] == i[1]: ok, how = True, "same" + elif i[3] == i[4]: ok, how = True, "same sorted" + elif i[0] != i[2] and i[3] != i[5]: ok, how = False, "DIFF (g0 drifts against itself too)" + else: ok, how = False, "DIFF" + same &= ok + print(f"| {q} | {w0:.2f} | {w2:.2f} | {ratio(w0, w2):.3f} | {f0:.2f} | {f2:.2f} | {c0:.1f} | {c2:.1f} | {ratio(c0, c2):.3f} | {how} |") + a = med(wall.get(("g0", q))); b = med(wall.get(("g2", q))) + if not (w0 >= FLOOR) and wall.get(("g0", q)) and wall.get(("g2", q)): + fl = a < FLOOR or b < FLOOR + scan[q] = (ratio(max(a, FLOOR), max(b, FLOOR)), "wall" + (" (floored)" if fl else "")) + elif w0 >= FLOOR: + rt = ratio(w0, w2) + if wall.get(("g0", q)) and wall.get(("g2", q)): + # both measures exist: the verdict takes the larger, and a gap + # over XCHECK is flagged (a timeit artifact on one store, #856, + # must not hide a regression the wall stage sees) + rw = ratio(max(a, FLOOR), max(b, FLOOR)) + big = max(rt, rw) if rt == rt and rw == rw else float("nan") + scan[q] = (big, f"max(timeit {rt:.3f}, wall {rw:.3f})" + (" CHECK" if not abs(rt - rw) <= XCHECK else "")) + else: + scan[q] = (rt, "timeit") + else: + scan[q] = (float("nan"), "none") +if wall: + print("\n| query | wall g0 ms/call | wall g2 ms/call | ratio | rounds |\n|---|---|---|---|---|") + for q in want: + a = med(wall.get(("g0", q))); b = med(wall.get(("g2", q))) + r = ratio(max(a, FLOOR), max(b, FLOOR)) if a < FLOOR or b < FLOOR else ratio(a, b) + print(f"| {q} | {a:.3f} | {b:.3f} | {r:.3f}{' (floored)' if a < FLOOR or b < FLOOR else ''} | {len(wall.get(('g2', q), []))} |") +print("\n| query | scan-only ratio g2 / g0 | source |\n|---|---|---|") +for q in want: print(f"| {q} | {scan[q][0]:.3f} | {scan[q][1]} |") +if waits: print(f"\nload waits: {len(waits)} ({', '.join(w[0] + '/' + w[1] for w in waits[:10])})") +if bad_rows: print(f"\nunparsed rows: {len(bad_rows)} ({', '.join('/'.join(r) for r in bad_rows[:10])})") +# a row that erred (FAIL) or does not parse is a failure of its query, +# even when other rounds of it succeeded +for st, v, q, rnd in bad_rows: missing.append(f"{q}/{st} ({v} round {rnd} failed)") +if missing: print(f"\nmissing or failed (query/stage): {', '.join(missing)}") +complete = not missing +worst = max((v[0] for v in scan.values()), default=float("nan")) +wq = max(scan, key=lambda q: scan[q][0] if scan[q][0] == scan[q][0] else float("inf")) if scan else "-" +scan_ok = complete and all(v[0] <= 1.05 for v in scan.values()) # a NaN ratio fails +print(f"\n**P5 float store, all {nq} queries present (and no run failed) in warm, cold, wall and ident: {'PASS' if complete else 'FAIL'}**") +print(f"**P5 float store, answers g2 = g0: {'PASS' if same and complete else 'FAIL'}**") +print(f"**P5 float store, scan-only warm (no regression, <= 1.05 per query): {'PASS' if scan_ok else 'FAIL'}** (worst {worst:.3f}, {wq}, {scan.get(wq, (0, '-'))[1]})") diff --git a/bench/compress_estimate/p5_vecscan.py b/bench/compress_estimate/p5_vecscan.py new file mode 100755 index 000000000..fd43187bd --- /dev/null +++ b/bench/compress_estimate/p5_vecscan.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""P5 Task 8, carried items O1 and the short float DICT tail: reads the +vector descriptors of every float column of a generation-2 splayed store +(spec "Format and codecs": directory at 96, 64 x 48-byte descriptors per +chunk, payload = null bitmap when n_nulls > 0, codec body, trailer) and +prints one `vec` line per column: + vec + + + +Reads headers only; nothing is decoded. usage: p5_vecscan.py """ +import collections, os, struct, sys + +ENC = {0: "raw", 1: "const", 2: "for_bp", 3: "delta_bp", 4: "rle", 5: "dict", 6: "alp", 7: "alp_rd"} +TYPES = {3: "I16", 6: "F32", 7: "F64"} # the ray_t type byte (offset 18); rows at 24 + + +def scan(path): + b = open(path, "rb").read() + if len(b) < 96 or b[32:36] != b"RENC": + return None + rows = struct.unpack_from(" 0 else 0 + if n_chunks: + off0 = struct.unpack_from(" 0 else 0 + s = collections.Counter(); efs = collections.Counter() + v_index = 0 + for c in range(n_chunks): + coff = struct.unpack_from("= n_vec_total: + break + d = coff + j * 48 + enc, _w, n_nulls, flags = struct.unpack_from(" 0 else 0) + s["n_vec"] += 1 + if flags & 2: + s["trailer"] += 1 + if enc == 6: + e, f, n_exc = struct.unpack_from(" STR, from the +# 10M .db.splayed.get store; saved g0 / g2, measured, deleted. Copied from +# p5_bench.sh (calm, guard, rel_guard, alternated rounds, per-file eviction, +# ident g0 twice, the wall stage for #856, completeness and FAIL rows). +# prep : release binary copied; the store's size and its DICT estimated, +# guarded (estimate + 4 GB), g0 saved and its size printed, guarded +# again (DICT estimate + 3 GB), g2 saved (save times recorded), at +# least 0.5 GB left after it; the DICT region bytes per STR column +# from the file header; p6_dictcheck built from `make lib` and run +# (dict / dictgate rows: the persisted DICT); the TSV started afresh +# enc : per-column encoding mix and sizes of g2 +# mat : the columns each query leaves materialized on g2 (Rulings 6-2 / 7-1) +# warm : every query, ROUNDS alternated rounds (order swapped), one process +# per round and variant: run 1 = first, runs 2..6 -> warm median +# cold : 3 trials per variant, the store's files evicted first (fadvise) +# ident: the full answer of every query, g0 vs g2 (g0 run twice); raw and sorted +# wall : per-call wall time, (T(1 + K) - T(1)) / K, WALLS alternated rounds; +# K per query from its warm g0 median (about 2 s of calls, 3..100) +# o5 : arm C base vs p6 binary on g0, all 43 queries (I8 on the STR +# store, D18); arm D the STR group-by queries (P3 carry), base binary +# on its own generation-2 save (bg2, RAW / CONST STR) vs the p6 binary +# on g2. bg2 is derived and saved by the base binary after g0 is +# deleted (one extra store at a time), at least 0.3 GB left after it +# i8 : base vs p6 binary on the SYM 10M store read in place from $SRC +# (no copy, no disk), all 43 queries (I8, D18) +# clean: delete the stores +# savet: the writer cost (O2): SAVES alternated rounds of the g0 and g2 +# saves, this binary and BASE's, each into a scratch store deleted +# after the round (run after clean: needs the room of g0 + g2) +# parted: R2, the parted STR arm: p0 / p2 built from the derived table, ten +# 1M-row partitions saved one by one, each store under the guard; +# a refusal is recorded as a `skip` row; warm / ident / mat on it +# usage: p6_bench.sh [-w WORKDIR] -q QUERIES prep | enc | mat | warm | cold | ident | wall | o5 | i8 | clean | savet | parted | all +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +W=${W:-$REPO/build/p6_bench} +QUERIES= +USAGE="usage: p6_bench.sh [-w WORKDIR] -q QUERIES \n -w WORKDIR scratch directory (default $REPO/build/p6_bench)\n -q QUERIES the ClickBench rayforce queries.rfl\n" +while getopts "w:q:" o; do + case $o in + w) W=$OPTARG ;; + q) QUERIES=$OPTARG ;; + *) printf "%b" "$USAGE" >&2; exit 2 ;; + esac +done +shift $((OPTIND - 1)) +[ -n "$QUERIES" ] || { printf "%b" "$USAGE" >&2; exit 2; } +SRC=/skull/clickbench/rfsplayed +ROUNDS=${ROUNDS:-9} +SAVES=${SAVES:-3} +WALLS=${WALLS:-5} +PROUNDS=${PROUNDS:-5} +BASE=${BASE:-9802ba80} +NQ=43 +OUT=$W/p6.tsv +BIN=$W/bin/p6 +BB=$W/bin/base +DC=$W/bin/p6_dictcheck +mkdir -p "$W/g" "$W/bin" +TEXT="URL Title Referer SearchPhrase MobilePhoneModel" +COLS="WatchID EventTime EventDate CounterID ClientIP RegionID UserID URL Title Referer IsRefresh ResolutionWidth + MobilePhone MobilePhoneModel SearchEngineID SearchPhrase AdvEngineID IsLink IsDownload DontCountHits + TraficSourceID URLHash RefererHash WindowClientWidth WindowClientHeight" +# the STR group-by queries (a STR key or a STR count-distinct): O5 +O5Q="6 11 12 13 14 15 17 18 19 22 23 29 34 35 37 38 39 40" +query_n() { + awk -v want="$1" ' + /^[[:space:]]*$/ { next } + { q = q $0 "\n"; p = $0; gsub(/[^()]/, "", p) + for (i = 1; i <= length(p); i++) { c = substr(p, i, 1); if (c == "(") d++; else d-- } + if (d == 0) { n++; if (n == want) { printf "%s", q; exit } q = "" } }' "$QUERIES" +} +QD=$W/g/q; mkdir -p "$QD" +for n in $(seq 1 $NQ); do query_n "$n" > "$QD/$n.rfl"; done +[ "$(wc -c < "$QD/$NQ.rfl")" -gt 0 ] || { echo "queries.rfl has fewer than $NQ forms" >&2; exit 2; } +Q() { cat "$QD/$1.rfl"; } +avail() { df -B1 --output=avail "$W" | tail -1; } +guard() { local a; a=$(avail) # $1: bytes needed in $W + printf 'disk\t%s\tneed\t%s\tavail\t%s\n' "${2:-guard}" "$1" "$a" >> "$OUT" + [ "$a" -ge "$1" ] || { echo "disk guard (${2:-guard}): need $1 B in $W, have $a" >&2; return 2; }; } +GB=$((1024 * 1024 * 1024)) +rel_guard() { [ -x "$1" ] || { echo "$1 missing: run prep" >&2; exit 2; } + if grep -aq "__asan_init" "$1"; then echo "$1 is an ASan build" >&2; exit 2; fi; } +calm() { while ! awk '{exit !($1 < 1.5)}' /proc/loadavg; do printf 'wait\t%s\t%s\n' "$(date +%T)" "$(cut -d' ' -f1 /proc/loadavg)" >> "$OUT"; sleep 30; done; } +evict() { sync; find "$1" -type f -exec dd if={} iflag=nocache count=0 status=none \; ; } +peak() { local u; u=$(du -sb "$W" | cut -f1); printf 'peak\t%s\t%s\t%s\n' "$1" "$u" "$(avail)" >> "$OUT"; } +loadline() { if [ "${2:-}" = parted ]; then printf '(set hits (.db.parted.get "%s/%s" (quote hits)))\n' "$W" "$1" + elif [ "${2:-}" = sym ]; then printf '(set hits (.db.splayed.get "%s/"))\n' "$1" + else printf '(set hits (.db.splayed.get "%s/%s/"))\n' "$W" "$1"; fi; } +sel() { # the select of the derived columns from table $1 + local c e="" + for c in $COLS; do + case " $TEXT " in *" $c "*) e="$e $c: (as 'STR $c)" ;; *) e="$e $c: $c" ;; esac + done + printf '(select {%s from: %s})' "$e" "$1" +} +derive() { # the derived STR table, bound to t (pre-flight D14, R3) + printf '(set h (.db.splayed.get "%s"))\n(set t %s)\n' "$SRC" "$(sel h)" +} +estimate() { # bytes: the numeric source files + per STR column 16 B descriptors, + # its pool (at most its string bytes) and the gen-0 DICT (8 B / row) + local s c num=0 str + for c in $COLS; do case " $TEXT " in *" $c "*) ;; *) num=$((num + $(stat -c %s "$SRC/$c"))) ;; esac; done + s=$(mktemp -p "$W/g") + { derive; printf '(println (sum (map (fn [c] (+ (* 24 (count t)) (sum (strlen (at t c))))) [%s])))\n' "$(printf "'%s " $TEXT)"; } > "$s" + str=$("$BIN" "$s" | tail -1); rm -f "$s" + echo $((num + str)) +} +estimate_dict() { # bytes: per text column 4 B / row + 12 B / distinct + the distinct strings' bytes + local s; s=$(mktemp -p "$W/g") + { printf '(set h (.db.splayed.get "%s"))\n' "$SRC" + printf '(println (sum (map (fn [c] (+ (+ (+ (* 4 (count h)) (* 12 (count (distinct (at h c))))) (sum (strlen (distinct (at h c))))) 1024)) [%s])))\n' "$(printf "'%s " $TEXT)"; } > "$s" + "$BIN" "$s" | tail -1; rm -f "$s" +} +h_raw() { md5sum < "$1" | cut -c1-12; } +h_sort() { { head -n 1 "$1"; tail -n +2 "$1" | LC_ALL=C sort; } | md5sum | cut -c1-12; } +answer() { # store q file [kind]: a table by .csv.write, a scalar as a one-cell + # table (println keeps 6 digits), anything else (a list) by println + local s c; s=$(mktemp -p "$W/g"); c=$W/g/ans.csv; rm -f "$c" + { loadline "$1" "${4:-}"; printf '(set r %s)\n(.csv.write (if (== (type r) (quote TABLE)) r (table [r] (list (enlist r)))) "%s")\n' "$(Q "$2")" "$c"; } > "$s" + "$BIN" "$s" > "$3.err" 2>&1 || true + if [ ! -f "$c" ]; then + { loadline "$1" "${4:-}"; printf '(set r %s)\n(println r)\n' "$(Q "$2")"; } > "$s" + if "$BIN" "$s" > "$3.out" 2>>"$3.err"; then mv "$3.out" "$c"; else rm -f "$3.out"; fi + fi + rm -f "$s" + # no answer: a FAIL marker with the error text after it (the hash is FAIL) + if [ -f "$c" ]; then mv "$c" "$3"; rm -f "$3.err"; else { echo FAIL; head -c 300 "$3.err"; } > "$3"; rm -f "$3.err"; fi +} +h_or_fail() { if [ "$(head -n 1 "$2")" = FAIL ]; then echo FAIL; else "$1" "$2"; fi; } +base_bin() { + [ -x "$BB" ] && return 0 + rm -rf "$W/base_src"; mkdir -p "$W/base_src" + ( cd "$REPO" && git archive "$BASE" ) | tar -x -C "$W/base_src" + ( cd "$W/base_src" && make release >/dev/null ) + cp "$W/base_src/rayforce" "$BB"; rm -rf "$W/base_src" + rel_guard "$BB" + printf 'meta\tbase\t%s\t%s\n' "$BASE" "$(sha256sum "$BB" | cut -c1-12)" >> "$OUT" +} +# warm rows: m */ + printf("dict\t%.*s\t%s\t%s\t%s\t%s\t%s\t%lld\t%lld\t%lld\t%lld\n", nl, np, + g0dict ? "true" : "false", d ? "dict" : "none", + g0dict ? (region_eq ? "true" : "false") : "-", g0dict ? (root_eq ? "true" : "false") : "-", + elems ? "true" : "false", (long long)nvec, (long long)nsd, nd0, nd2); + if (g0dict) { exercised++; if (!d || !region_eq || !root_eq) bad = 1; } + else if (d || k2 == RAY_IDX_DICT) bad = 1; /* a generation-2 DICT where generation 0 has none */ + if (!elems) bad = 1; + } + printf("dictgate\t%s\t%d\n", !exercised ? "not exercised" : bad ? "FAIL" : "PASS", exercised); + ray_release(t0); ray_release(t2); + ray_runtime_destroy(rt); + return 0; +} diff --git a/bench/compress_estimate/p6_summary.py b/bench/compress_estimate/p6_summary.py new file mode 100644 index 000000000..a86f9ef22 --- /dev/null +++ b/bench/compress_estimate/p6_summary.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""P6 STR-store summary (copied from p5_summary.py), rerun as the P6b gate: +per STR column round trip, encoding and the persisted DICT against +generation 0 (p6_dictcheck: the region before materialization, the root +after), the DICT region bytes per column and the store against P6's g2 +(from p6-ref/p6.tsv beside the TSV's directory, when present); per +column sizes and mix; store sizes, save times and the writer cost against +BASE (O2); warm / first / cold medians g2 / g0, answer identity, the wall +stage and the scan-only warm line (spec "Benchmarks", P5's wall / timeit +rule) over all 43 queries; the columns each query leaves materialized +(Rulings 6-2 / 7-1); generation 0 against BASE on the STR store (arm C, +all 43) and on the SYM store (i8), the STR group-by queries against BASE +on generation 2 (arm D, O5); the parted arm (R2, gated: Ruling Q2). Every +number comes from a TSV; nothing is typed. +usage: p6_summary.py []""" +import collections, math, os, statistics, sys +m = collections.defaultdict(list); c = collections.defaultdict(list); wall = collections.defaultdict(list) +cols, dicts, gate, sizes, saves, ident, meta, waits = [], [], None, {}, {}, {}, {}, [] +savet = collections.defaultdict(list); colsize = {}; est = None; matr = {}; pmat = {}; pident = {} +o5 = collections.defaultdict(list); pm = collections.defaultdict(list); pcols = []; skips = []; peaks = []; disks = [] +answers = {}; dictsize = {}; estd = None; i8 = collections.defaultdict(list); i8_bad = [] +nq = 43; bad_rows = []; o5_bad = []; pm_bad = [] +FLOOR = 0.05 # P5: below it the wall stage gives the ratio, floored to it +XCHECK = 0.10 # the largest timeit / wall ratio gap printed without CHECK +def nums(xs): + try: return [float(x) for x in xs if x] + except ValueError: return None +def six(dst, bad, f): + t = nums(f[4:]) + if t is not None and len(t) == 6: + dst[(f[1], f[2], "first")].append(t[0]); dst[(f[1], f[2], "warm")].append(statistics.median(t[1:])) + else: bad.append((f[0], f[1], f[2], f[3])) +for line in open(sys.argv[1], encoding="utf-8", errors="replace"): + f = line.rstrip("\n").split("\t") + k = f[0] + if k == "col": cols.append(f[1:]) + elif k == "dict": dicts.append(f[1:]) + elif k == "dictgate": gate = f[1] + elif k == "size": sizes[f[1]] = int(f[2]) + elif k == "est" and f[1] == "dict": estd = int(f[2]) + elif k == "est": est = int(f[2]) + elif k == "dictsize": dictsize[f[1]] = int(f[2]) + elif k == "colsize": colsize[(f[1], f[2])] = int(f[3]) + elif k == "save": saves[f[1]] = float(f[2]) if f[2] else float("nan") + elif k == "meta": meta[f[1]] = f[2:] + elif k == "wait": waits.append(f[1:]) + elif k == "ident": ident[f[1]] = f[2:] + elif k == "pident": pident[f[1]] = f[2:] + elif k == "answer": answers[(f[1], f[2], f[3])] = f[4] if len(f) > 4 else "" + elif k == "mat": matr[f[1]] = f[2] + elif k == "pmat": pmat[f[1]] = f[2] + elif k == "pcol": pcols.append(f[1:]) + elif k == "skip": skips.append(f[1:]) + elif k == "peak": peaks.append(f[1:]) + elif k == "disk": disks.append(f[1:]) + elif k == "savet" and len(f) >= 7 and f[3] and f[4]: + savet[(f[1], "g0")].append(float(f[3])); savet[(f[1], "g2")].append(float(f[4])) + savet[(f[1], "size_g0")].append(int(f[5])); savet[(f[1], "size_g2")].append(int(f[6])) + elif k == "nq": nq = int(f[1]) + elif k == "m": six(m, bad_rows, f) + elif k in ("o5c", "o5d"): + t = nums(f[4:]) + if t is not None and len(t) == 6: o5[(k, f[1], f[2])].append(statistics.median(t[1:])) + else: o5_bad.append((k, f[1], f[2], f[3])) + elif k == "i8": + t = nums(f[4:]) + if t is not None and len(t) == 6: i8[(f[1], f[2])].append(statistics.median(t[1:])) + else: i8_bad.append((k, f[1], f[2], f[3])) + elif k == "pm": six(pm, pm_bad, f) + elif k == "wall": + t = nums(f[4:5]) + if t: wall[(f[1], f[2])].append(t[0]) + else: bad_rows.append(("wall", f[1], f[2], f[3])) + elif k == "c": + t = nums(f[4:5]) + if t: c[(f[1], f[2])].append(t[0]) + else: bad_rows.append(("cold", f[1], f[2], f[3])) +med = lambda xs: statistics.median(xs) if xs else float("nan") +ratio = lambda a, b: b / a if a > 0 else float("nan") +print(f"meta {meta}") +# --- the STR columns: round trip and the persisted DICT (p6_dictcheck) --- +strcols = [d[0] for d in dicts] +print("| column | g0 DICT | g2 kind (recorded) | region equal (codes, first occurrences, n_distinct) | root equal (after materialization) | elements equal | vectors | STR_DICT vectors | n_distinct g0 | n_distinct g2 |") +print("|---|---|---|---|---|---|---|---|---|---|") +for d in dicts: print("| " + " | ".join(d + [""] * (10 - len(d))) + " |") +rt_ok = len(dicts) > 0 and all(len(d) > 5 and d[5] == "true" for d in dicts) +dict_ok = gate == "PASS" +# --- per column bytes and mix --- +print("\n| column | g0 file B | g2 encoded B | raw B (.idx.info) | g0 / g2 | mix |\n|---|---|---|---|---|---|") +for name, e, r, mix in cols: + g0b = colsize.get(("g0", name), 0) + print(f"| {name}{' (STR)' if name in strcols else ''} | {g0b} | {e} | {r} | {g0b / max(int(e), 1):.2f}x | {mix} |") +print(f"\nstore: g0 {sizes.get('g0', 0)} B (estimate {est}), g2 {sizes.get('g2', 0)} B (x{sizes.get('g2', 0) / max(sizes.get('g0', 1), 1):.3f}); " + f"save g0 {saves.get('g0', 0):.0f} ms, g2 {saves.get('g2', 0):.0f} ms (prep, one run)") +# --- the DICT region bytes (file header) and the store against P6's g2 --- +ref = sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(os.path.abspath(sys.argv[1])), "..", "p6-ref", "p6.tsv") +p6g2 = None +if os.path.exists(ref): + for line in open(ref, encoding="utf-8", errors="replace"): + f = line.rstrip("\n").split("\t") + if f[0] == "size" and f[1] == "g2": p6g2 = int(f[2]) +if dictsize: + print("\n| STR column | DICT region B |\n|---|---|") + for cn, b in dictsize.items(): print(f"| {cn} | {b} |") + print(f"| sum | {sum(dictsize.values())} |") + print(f"\nDICT region bytes: sum {sum(dictsize.values())} B (DICT estimate {estd} B); g2 {sizes.get('g2', 0)} B" + + (f", P6's g2 {p6g2} B ({ref}): g2 / P6's g2 {sizes.get('g2', 0) / p6g2:.3f}" if p6g2 else ", P6's g2: no reference TSV")) +if "bg2" in sizes: print(f"BASE's generation-2 save of the same table (o5, RAW / CONST STR): {sizes['bg2']} B, save {saves.get('bg2', 0):.0f} ms") +if peaks: print("disk: " + "; ".join(f"{p[0]}: scratch {int(p[1])} B, free {int(p[2])} B" for p in peaks)) +print() +if savet: + print("| writer (O2) | save g0 ms | save g2 ms | g2 / g0 | g0 B | g2 B | runs |\n|---|---|---|---|---|---|---|") + for b in ("p6", "base"): + if savet[(b, "g0")]: + s0 = med(savet[(b, "g0")]); s2 = med(savet[(b, "g2")]) + print(f"| {b} | {s0:.0f} | {s2:.0f} | {s2 / s0:.3f} | {savet[(b, 'size_g0')][0]} | {savet[(b, 'size_g2')][0]} | {len(savet[(b, 'g0')])} |") + if savet[("p6", "g2")] and savet[("base", "g2")]: + print(f"\nsave g2 p6 / base: {med(savet[('p6', 'g2')]) / med(savet[('base', 'g2')]):.3f}; " + f"save g0 p6 / base: {med(savet[('p6', 'g0')]) / med(savet[('base', 'g0')]):.3f}\n") +want = [f"q{i}" for i in range(1, nq + 1)] +def matcols(s): + s = (s or "").strip() + if s in ("", "[]"): return [] + return s.strip("[]").replace("'", "").split() +def mclass(q): + s = matr.get(q) + if s is None: return "?" + if s == "FAIL": return "FAIL" + mc = matcols(s) + return "scan" if not mc else "mat: " + " ".join(mc) +print("| query | warm g0 | warm g2 | ratio | first g0 | first g2 | cold g0 | cold g2 | ratio | answers | g2 materializes |\n|---|---|---|---|---|---|---|---|---|---|---|") +missing = [] +for q in want: + for what, have in (("warm", m.get(("g0", q, "warm")) and m.get(("g2", q, "warm"))), + ("cold", c.get(("g0", q)) and c.get(("g2", q))), + ("wall", wall.get(("g0", q)) and wall.get(("g2", q))), + ("ident", q in ident)): + if not have: missing.append(f"{q}/{what}") +def how_same(i): + if i is None: return False, "missing" + if "FAIL" in i[:3]: + if i[0] == i[1] == i[2] == "FAIL": return False, "error in both generations" + return False, "FAIL (no answer)" + if i[0] == i[1]: return True, "same" + if i[3] == i[4]: return True, "same sorted" + if i[0] != i[2] and i[3] != i[5]: return False, "DIFF (g0 drifts against itself too)" + return False, "DIFF" +same = True; scan = {}; both_err = [] +for q in want: + w0 = med(m.get(("g0", q, "warm"))); w2 = med(m.get(("g2", q, "warm"))) + f0 = med(m.get(("g0", q, "first"))); f2 = med(m.get(("g2", q, "first"))) + c0 = med(c.get(("g0", q))); c2 = med(c.get(("g2", q))) + ok, how = how_same(ident.get(q)) + if how == "error in both generations": + both_err.append(f"{q} ({answers.get(('ident', q, 'a'), '')[:120]})") + same &= ok + print(f"| {q} | {w0:.2f} | {w2:.2f} | {ratio(w0, w2):.3f} | {f0:.2f} | {f2:.2f} | {c0:.1f} | {c2:.1f} | {ratio(c0, c2):.3f} | {how} | {mclass(q)} |") + a = med(wall.get(("g0", q))); b = med(wall.get(("g2", q))) + if not (w0 >= FLOOR) and wall.get(("g0", q)) and wall.get(("g2", q)): + fl = a < FLOOR or b < FLOOR + scan[q] = (ratio(max(a, FLOOR), max(b, FLOOR)), "wall" + (" (floored)" if fl else "")) + elif w0 >= FLOOR: + rt = ratio(w0, w2) + if wall.get(("g0", q)) and wall.get(("g2", q)): + # both measures exist: the verdict takes the larger, and a gap + # over XCHECK is flagged (a timeit artifact on one store, #856, + # must not hide a regression the wall stage sees) + rw = ratio(max(a, FLOOR), max(b, FLOOR)) + big = max(rt, rw) if rt == rt and rw == rw else float("nan") + scan[q] = (big, f"max(timeit {rt:.3f}, wall {rw:.3f})" + (" CHECK" if not abs(rt - rw) <= XCHECK else "")) + else: + scan[q] = (rt, "timeit") + else: + scan[q] = (float("nan"), "none") +if wall: + print("\n| query | wall g0 ms/call | wall g2 ms/call | ratio | rounds |\n|---|---|---|---|---|") + for q in want: + a = med(wall.get(("g0", q))); b = med(wall.get(("g2", q))) + r = ratio(max(a, FLOOR), max(b, FLOOR)) if a < FLOOR or b < FLOOR else ratio(a, b) + print(f"| {q} | {a:.3f} | {b:.3f} | {r:.3f}{' (floored)' if a < FLOOR or b < FLOOR else ''} | {len(wall.get(('g2', q), []))} |") +print("\n| query | scan-only ratio g2 / g0 | source | g2 materializes |\n|---|---|---|---|") +for q in want: print(f"| {q} | {scan[q][0]:.3f} | {scan[q][1]} | {mclass(q)} |") +# --- Rulings 6-2 / 7-1: which queries leave a STR column materialized --- +strmat = {q: [x for x in matcols(matr.get(q)) if x in strcols] for q in want if matr.get(q) not in (None, "FAIL")} +print("\nSTR columns left materialized on g2 (mat stage): " + + (", ".join(f"{q} {'+'.join(v)}" for q, v in strmat.items() if v) or "none")) +# --- O5: STR group-by against BASE --- +def gen0_arm(get, labs): # every query base >= 1 ms gated at 1.05; the gmean over them reported + rs = {}; miss = [] + for q in want: + b = med(get(labs[0], q)); p = med(get(labs[1], q)) + if not (b == b and p == p): miss.append(q); continue + if b >= 1.0: rs[q] = p / b + over = [f"{q} {r:.3f}" for q, r in rs.items() if not r <= 1.05] + gm = math.exp(sum(math.log(r) for r in rs.values()) / len(rs)) if rs else float("nan") + wq = max(rs, key=rs.get) if rs else "-" + return rs, miss, over, gm, wq +if o5: + print("\n| query | C: g0 base | C: g0 p6 | ratio | D: base on its gen-2 save | D: p6 on g2 | ratio | p6 g2 / p6 g0 (warm stage) |\n|---|---|---|---|---|---|---|---|") + for q in sorted({k[2] for k in o5}, key=lambda q: int(q[1:])): + cb = med(o5.get(("o5c", "base", q))); cp = med(o5.get(("o5c", "p6", q))) + db = med(o5.get(("o5d", "base", q))); dp = med(o5.get(("o5d", "p6", q))) + w0 = med(m.get(("g0", q, "warm"))); w2 = med(m.get(("g2", q, "warm"))) + print(f"| {q} | {cb:.2f} | {cp:.2f} | {ratio(cb, cp):.3f} | {db:.2f} | {dp:.2f} | {ratio(db, dp):.3f} | {ratio(w0, w2):.3f} |") + if o5_bad: print(f"\no5 failed rows: {len(o5_bad)} ({', '.join('/'.join(r) for r in o5_bad[:12])})") +crs, cmiss, cover, cgm, cwq = gen0_arm(lambda lab, q: o5.get(("o5c", lab, q)), ("base", "p6")) +cmiss += [r[2] for r in o5_bad if r[0] == "o5c"] +c_ok = bool(crs) and not cmiss and not cover +if i8: + print("\n| query | i8: SYM store base | i8: SYM store p6 | ratio |\n|---|---|---|---|") + for q in want: + b = med(i8.get(("base", q))); p = med(i8.get(("p6", q))) + print(f"| {q} | {b:.2f} | {p:.2f} | {ratio(b, p):.3f} |") + if i8_bad: print(f"\ni8 failed rows: {len(i8_bad)} ({', '.join('/'.join(r) for r in i8_bad[:12])})") +irs, imiss, iover, igm, iwq = gen0_arm(lambda lab, q: i8.get((lab, q)), ("base", "p6")) +imiss += [r[2] for r in i8_bad] +i_ok = bool(irs) and not imiss and not iover +# --- R2: the parted arm --- +pskip = [s for s in skips if s[0] == "parted"] +if pskip: print(f"\nparted arm (R2): skipped ({'; '.join(' '.join(s[1:]) for s in pskip)})") +psame = False; pmiss = ["no parted rows"]; pover = [] +if pm or pident: + print(f"\nparted arm (R2): p0 {sizes.get('p0', 0)} B, p2 {sizes.get('p2', 0)} B; STR mixes: " + + "; ".join(f"{p[0]} {p[1]}" for p in pcols if p[0] in strcols)) + print("\n| query | warm p0 | warm p2 | ratio | first p0 | first p2 | answers | p2 materializes |\n|---|---|---|---|---|---|---|---|") + psame = True; pmiss = [] + for q in want: + w0 = med(pm.get(("p0", q, "warm"))); w2 = med(pm.get(("p2", q, "warm"))) + f0 = med(pm.get(("p0", q, "first"))); f2 = med(pm.get(("p2", q, "first"))) + ok, how = how_same(pident.get(q)); psame &= ok + if not (pm.get(("p0", q, "warm")) and pm.get(("p2", q, "warm"))): pmiss.append(q) + pmc = pmat.get(q); pmc = "?" if pmc is None else ("scan" if not matcols(pmc) else "mat: " + " ".join(matcols(pmc))) + print(f"| {q} | {w0:.2f} | {w2:.2f} | {ratio(w0, w2):.3f} | {f0:.2f} | {f2:.2f} | {how} | {pmc} |") + if w0 >= 1.0 and not ratio(w0, w2) <= 1.05: pover.append(f"{q} {ratio(w0, w2):.3f}") + for r in pm_bad: pmiss.append(f"{r[2]} ({r[1]} round {r[3]} failed)") + print(f"\nparted arm (R2): all {nq} queries present: {'yes' if not pmiss else 'no: ' + ', '.join(pmiss[:15])}; " + f"answers p2 = p0: {'yes' if psame else 'no'}; warm over 1.05 with p0 >= 1 ms: {', '.join(pover) or 'none'}") +if waits: print(f"\nload waits: {len(waits)} ({', '.join(w[0] + '/' + w[1] for w in waits[:10])})") +if bad_rows: print(f"\nunparsed rows: {len(bad_rows)} ({', '.join('/'.join(r) for r in bad_rows[:10])})") +for st, v, q, rnd in bad_rows: missing.append(f"{q}/{st} ({v} round {rnd} failed)") +if both_err: print(f"\nerroring identically in both generations (listed, never counted as passing): {'; '.join(both_err)}") +if missing: print(f"\nmissing or failed (query/stage): {', '.join(missing)}") +complete = not missing +worst = max((v[0] for v in scan.values()), default=float("nan")) +wq = max(scan, key=lambda q: scan[q][0] if scan[q][0] == scan[q][0] else float("inf")) if scan else "-" +over = [f"{q} {scan[q][0]:.3f}" for q in want if not scan[q][0] <= 1.05] +scan_ok = complete and not over # a NaN ratio fails +if over: print(f"\nover 1.05 (scan-only line): {', '.join(over)}") +print(f"\n**P6 gate (STR round trip): {'PASS' if rt_ok else 'FAIL'}** (every STR column element-identical, {len(dicts)} columns)") +note = " (not exercised: no STR column with a generation-0 DICT)" if gate == "not exercised" else "" +print(f"**P6b gate (persisted DICT equal to generation 0 on every STR column generation 0 indexes): {'PASS' if dict_ok else 'FAIL'}**{note}") +print(f"**P6 STR store, all {nq} queries present (and no run failed) in warm, cold, wall and ident: {'PASS' if complete else 'FAIL'}**") +print(f"**P6 STR store, answers g2 = g0: {'PASS' if same and complete else 'FAIL'}**") +print(f"**P6 STR store, scan-only warm (no regression, <= 1.05 per query): {'PASS' if scan_ok else 'FAIL'}** (worst {worst:.3f}, {wq})") +acc = {"q33": "Ruling 10-7"} +over_na = [o for o in over if o.split()[0] not in acc] +print(f"scan-only warm over 1.05 outside accepted clauses ({', '.join(f'{q} {r}' for q, r in acc.items())}): {', '.join(over_na) or 'none'}") +def g0line(what, rs, miss, ov, gm, wq): + ok = bool(rs) and not miss and not ov + tail = f"gmean {gm:.4f} over {len(rs)} queries (Ruling 8-1: the gmean is reported, not gated), worst {wq} {rs.get(wq, float('nan')):.3f}" + if ov: tail += f"; over 1.05: {', '.join(ov)}" + if miss: tail += f"; missing or failed: {', '.join(sorted(set(miss), key=lambda q: int(q[1:]) if q[1:].isdigit() else 0))}" + print(f"**{what}: every query <= 1.05: {'PASS' if ok else 'FAIL'}** ({tail})") +g0line(f"Generation 0 on the STR store, P6b vs BASE (arm C, all {nq}, base >= 1 ms)", crs, cmiss, cover, cgm, cwq) +g0line(f"Generation 0 on the SYM store, P6b vs BASE (i8, all {nq}, base >= 1 ms)", irs, imiss, iover, igm, iwq) +if pskip and not (pm or pident): + gd = [d for d in disks if d[0].startswith("parted")] + print(f"**Parted STR arm (R2): skipped (guard)** ({'; '.join(f'{d[0]}: need {d[2]} B, avail {d[4]} B' for d in gd)})") +else: + p_ok = psame and not pmiss and not pover + print(f"**Parted STR arm (R2): answers p2 = p0, all present, warm <= 1.05 per query with p0 >= 1 ms: {'PASS' if p_ok else 'FAIL'}**" + + (f" (over 1.05: {', '.join(pover)})" if pover else "") + (f" (missing: {', '.join(pmiss[:15])})" if pmiss else "")) diff --git a/bench/compress_estimate/pi_gate.py b/bench/compress_estimate/pi_gate.py new file mode 100644 index 000000000..caf4701e5 --- /dev/null +++ b/bench/compress_estimate/pi_gate.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""PI gate verdict from gate.tsv (written by pi_gate.sh). + +Prints per-kind tables (warm / first run / 3-run total, head vs baseline, all +43 queries) and ONE gate line computed from the data: + clause 1: no HASH index persisted by the head converter (every head store + measured carries 0 HASH columns) + clause 2: per load kind, warm head/baseline ratio <= 1.05 for every query + (and result identity). A query is outside when the best-of-5 ratio > 1.05 + AND the gap is at least NOISE_MS AND the median-of-5-rounds ratio + is also > 1.05 (a ~1 ms query's best-of-5 moves 15% on jitter + alone); the others over 1.05 are listed as noise, never hidden. +q41/q42 on a splayed kind are the recorded deviation (scan speed vs the +baseline's persisted HASH); any other query outside is flagged UNEXPECTED. +""" +import statistics, sys +from collections import defaultdict + +TOL = 1.05 +NOISE_MS = 0.1 +DEVIATION = {"q41", "q42"} +KINDS = ("gen0", "gen2", "parted") +NAME = {"gen0": "splayed-gen0", "gen2": "splayed-gen2", "parted": "parted"} + +runs = defaultdict(list) # (kind, variant, q) -> [[r1..r6], ...] +c1 = {} +ident = {} +meta = {} +# argv[1]: the full run; argv[2..]: confirmation runs (more rounds of a few +# queries); a confirmation run REPLACES the rows of the (kind, query) pairs it +# measured, it never adds to them. +files = sys.argv[1:] +replaced = set() +for fi, path in enumerate(files): + if fi: + for line in open(path): + f = line.rstrip("\n").split("\t") + if f[0] == "m": + replaced.add((f[1], f[3])) +for fi, path in enumerate(files): + for line in open(path): + f = line.rstrip("\n").split("\t") + if f[0] == "m": + if fi == 0 and (f[1], f[3]) in replaced: + continue + runs[(f[1], f[2], f[3])].append([float(x) for x in f[5:11]]) + elif f[0] == "clause1": + c1[f[1]] = int(f[3]) + elif f[0] == "ident": + ident[(f[1], f[2])] = f[3:6] + elif f[0] == "meta": + meta[f[1]] = f[2] + +wmed = {} + +def stats(kind, v, q): + rs = runs[(kind, v, q)] + per = [statistics.median(r[1:]) for r in rs] + warm = min(per) + wmed[(kind, v, q)] = statistics.median(per) + first = statistics.median(r[0] for r in rs) + three = statistics.median(sum(r[:3]) for r in rs) + return warm, first, three, len(rs) + +def r(a, b): + return a / b if b > 0 else 1.0 + +print("meta", meta) +print("clause1 HASH counts:", c1) +verdict = {} +firsts = {} +for kind in KINDS: + qs = sorted({k[2] for k in runs if k[0] == kind}, key=lambda s: int(s[1:])) + if not qs: + continue + print(f"\n## {NAME[kind]} (ms; head vs baseline; ratio = head/baseline)") + print("| q | warm head | warm base | ratio | first head | first base | ratio | 3-run head | 3-run base | ratio |") + print("|---|---|---|---|---|---|---|---|---|---|") + tot = [0.0] * 6 + outside, floor = [], [] + first_out = [] + for q in qs: + wh, fh, th, n = stats(kind, "h", q) + wd, fd, td, _ = stats(kind, "d", q) + for i, x in enumerate((wh, wd, fh, fd, th, td)): + tot[i] += x + rw, rf, rt = r(wh, wd), r(fh, fd), r(th, td) + mark = "" + rwm = r(wmed[(kind, "h", q)], wmed[(kind, "d", q)]) + if rw > TOL: + if wh - wd >= NOISE_MS and rwm > TOL: + outside.append((q, rw)); mark = " **" + else: + floor.append((q, rw)) + if rf > TOL and fh - fd >= NOISE_MS: + first_out.append((q, rf)) + print(f"| {q} | {wh:.3f} | {wd:.3f} | {rw:.3f}{mark} | {fh:.3f} | {fd:.3f} | {rf:.3f} | {th:.3f} | {td:.3f} | {rt:.3f} |") + print(f"| total | {tot[0]:.1f} | {tot[1]:.1f} | {r(tot[0], tot[1]):.3f} | {tot[2]:.1f} | {tot[3]:.1f} | {r(tot[2], tot[3]):.3f} | {tot[4]:.1f} | {tot[5]:.1f} | {r(tot[4], tot[5]):.3f} |") + print(f"warm outside {TOL}x (gap >= {NOISE_MS} ms): {[(q, round(x, 3)) for q, x in outside]}") + print(f"warm over {TOL}x but not confirmed (gap < {NOISE_MS} ms or median-of-rounds ratio <= {TOL}: noise): {[(q, round(x, 3)) for q, x in floor]}") + print(f"first run outside {TOL}x (gap >= {NOISE_MS} ms): {[(q, round(x, 3)) for q, x in first_out]}") + real, tie = [], [] + for q in qs: + i = ident.get((kind, q)) + if i and i[0] != i[1]: + (tie if i[0] != i[2] else real).append(q) + print(f"result text differs head vs baseline: stable-head diffs {real}; head unstable against itself (tie order) {tie}") + verdict[kind] = (outside, real) + firsts[kind] = first_out + +ok1 = bool(c1) and all(n == 0 for k, n in c1.items() if k.startswith("head_")) +parts = [] +for kind in KINDS: + if kind not in verdict: + continue + outside, real = verdict[kind] + exp = [(q, x) for q, x in outside if q in DEVIATION] + unexp = [(q, x) for q, x in outside if q not in DEVIATION] + if not outside and not real: + parts.append(f"clause2 {NAME[kind]} PASS") + continue + why = ", ".join(f"{q} {x:.1f}x" for q, x in exp) + if why: + why += " warm" + if real: + why += (", " if why else "") + "results differ " + " ".join(real) + if unexp: + why += (", " if why else "") + "UNEXPECTED " + ", ".join(f"{q} {x:.2f}x" for q, x in unexp) + tail = "; deviation recorded" if exp and not unexp and not real else "" + parts.append(f"clause2 {NAME[kind]} FAIL ({why}{tail})") +fo = [] +for kind in KINDS: + if kind in firsts: + fo.append(f"{NAME[kind]} " + (" ".join(q for q, _ in firsts[kind]) if len(firsts[kind]) < 10 else f"{len(firsts[kind])} queries") if firsts[kind] else f"{NAME[kind]} none") +print("\nPI GATE: clause1 " + ("PASS" if ok1 else "FAIL") + " ; " + " ; ".join(parts) + " ; first run over 1.05x (informational): " + "; ".join(fo)) diff --git a/bench/compress_estimate/pi_gate.sh b/bench/compress_estimate/pi_gate.sh new file mode 100755 index 000000000..f715f3d58 --- /dev/null +++ b/bench/compress_estimate/pi_gate.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +# PI gate (plan: compressed-columns PI, Task 5): re-measure after the index +# policy change, over ALL 43 ClickBench queries, per load kind. +# BIN_H : head binary (release, built from a committed tree) +# BIN_D : baseline binary (dev), run on a store ITS converter wrote +# (with the persisted HASH indexes) +# Load kinds: gen0 splayed generation 0 (head store vs dev store) +# gen2 splayed {compress:true} (head store vs the dev gen-0 store: +# dev has no generation 2) +# parted .csv.parted store (head store vs dev store) +# Per (kind, variant, query, round) one FRESH process loads the store through +# .db.splayed.get / .db.parted.get and runs the query 6 times (timeit, ms): +# first run = run 1 (fresh process, warm page cache) +# 3-run total= runs 1..3 (what the ClickBench harness records) +# warm = median of runs 2..6 in the process; best of 5 rounds, +# head and dev alternated (order swapped each round) +# Stores are converted, measured and deleted one at a time (disk guard). +# Output: $W/gate.tsv ; the verdict is printed by pi_gate.py (never typed). +# usage: BIN_H=... BIN_D=... pi_gate.sh [-w WORKDIR] -s SCHEMA -q QUERIES run|ident|all|verdict +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +W=${W:-$REPO/build/pi_bench} +SCHEMA= +QUERIES= +USAGE="usage: pi_gate.sh [-w WORKDIR] -s SCHEMA -q QUERIES \n -w WORKDIR scratch directory (default $REPO/build/pi_bench)\n -s SCHEMA the ClickBench rayforce schema.rfl\n -q QUERIES the ClickBench rayforce queries.rfl\n" +while getopts "w:s:q:" o; do + case $o in + w) W=$OPTARG ;; + s) SCHEMA=$OPTARG ;; + q) QUERIES=$OPTARG ;; + *) printf "%b" "$USAGE" >&2; exit 2 ;; + esac +done +shift $((OPTIND - 1)) +[ -n "$SCHEMA" ] || { printf "%b" "$USAGE" >&2; exit 2; } +[ -n "$QUERIES" ] || { printf "%b" "$USAGE" >&2; exit 2; } +CSV=/skull/clickbench/hits_h.csv +BIN_H=${BIN_H:?BIN_H} +BIN_D=${BIN_D:?BIN_D} +OUT=$W/gate.tsv +ROUNDS=${ROUNDS:-5} +NQ=43 +QS=${QS:-$(seq 1 43)} # confirmation runs: QS="16 20 39" ROUNDS=15 OUT_FILE=file.tsv +OUT=${OUT_FILE:-$OUT} +mkdir -p "$W/g" + +query_n() { + awk -v want="$1" ' + /^[[:space:]]*$/ { next } + { q = q $0 "\n"; p = $0; gsub(/[^()]/, "", p) + for (i = 1; i <= length(p); i++) { c = substr(p, i, 1); if (c == "(") d++; else d-- } + if (d == 0) { n++; if (n == want) { printf "%s", q; exit } q = "" } }' "$QUERIES" +} +# cache the 43 query texts once +QD=$W/g/q; mkdir -p "$QD" +for n in $(seq 1 $NQ); do query_n "$n" > "$QD/$n.rfl"; done + +guard() { # F8: >= 7 GB free before each conversion + local avail; avail=$(df -B1 --output=avail "$W" | tail -1) + [ "$avail" -ge $((7 * 1024 * 1024 * 1024)) ] || { echo "disk guard: $avail free" >&2; exit 2; } +} + +convert() { # bin kind dir + local bin=$1 kind=$2 dir=$3 s; guard + rm -rf "$dir"; s=$(mktemp -p "$W/g") + cat "$SCHEMA" > "$s" + case $kind in + gen0) printf '\n(do (.csv.splayed hit-types "%s" "%s") null)\n' "$CSV" "$dir" >> "$s" ;; + gen2) printf '\n(do (.csv.splayed {compress: true} hit-types "%s" "%s") null)\n' "$CSV" "$dir" >> "$s" ;; + parted) printf '\n(do (.csv.parted hit-types "%s" 1000000 "%s/" (quote hits)) null)\n' "$CSV" "$dir" >> "$s" ;; + esac + /usr/bin/time -f "%e %M" -o "$s.t" "$bin" "$s" >/dev/null + rm -f "$s" + echo "conv $kind $(basename "$bin") $(cat "$s.t") bytes=$(du -sb "$dir" | cut -f1)" >&2 + printf 'conv\t%s\t%s\t%s\t%s\n' "$kind" "$(basename "$dir")" "$(cut -d' ' -f1 "$s.t")" "$(du -sb "$dir" | cut -f1)" >> "$OUT" + rm -f "$s.t" +} + +loadline() { # kind dir + if [ "$1" = parted ]; then printf '(set hits (.db.parted.get "%s" (quote hits)))\n' "$2" + else printf '(set hits (.db.splayed.get "%s"))\n' "$2"; fi +} + +clause1() { # bin dir label : count of HASH-indexed columns of a splayed store + local s; s=$(mktemp -p "$W/g") + printf '(set t (.db.splayed.get "%s"))\n(println (sum (map (fn [c] (if (.idx.has? (at t c)) (if (== (at (.idx.info (at t c)) (quote kind)) (quote hash)) 1 0) 0)) (cols t))))\n' "$2" > "$s" + local n; n=$("$1" "$s" | tail -1); rm -f "$s" + printf 'clause1\t%s\t%s\t%s\n' "$3" "$(basename "$1")" "$n" >> "$OUT" + echo "clause1 $3: $n HASH columns" >&2 +} + +measure() { # kind dirH dirD + local kind=$1 dh=$2 dd=$3 round q v bin d s order + for round in $(seq 1 "$ROUNDS"); do + for q in $QS; do + if [ $((round % 2)) = 1 ]; then order="h d"; else order="d h"; fi + for v in $order; do + if [ $v = h ]; then bin=$BIN_H; d=$dh; else bin=$BIN_D; d=$dd; fi + s=$(mktemp -p "$W/g") + { loadline "$kind" "$d"; for i in 1 2 3 4 5 6; do printf '(println (timeit %s))\n' "$(cat "$QD/$q.rfl")"; done; } > "$s" + r=$("$bin" "$s" 2>&1 | tail -6 | tr '\n' '\t'); rm -f "$s" + printf 'm\t%s\t%s\tq%s\t%s\t%s\n' "$kind" "$v" "$q" "$round" "${r%$'\t'}" >> "$OUT" + done + done + echo "measure $kind round $round done" >&2 + done +} + +ident() { # kind dirH dirD : result text of every query, head vs baseline + local kind=$1 q s + for q in $QS; do + for v in h d; do + if [ $v = h ]; then bin=$BIN_H; d=$2; else bin=$BIN_D; d=$3; fi + s=$(mktemp -p "$W/g") + { loadline "$kind" "$d"; printf '(println %s)\n' "$(cat "$QD/$q.rfl")"; } > "$s" + "$bin" "$s" 2>&1 | md5sum | cut -c1-12 > "$W/g/id_$v"; rm -f "$s" + done + # repeat head once against itself to separate tie-order noise from a real diff + s=$(mktemp -p "$W/g") + { loadline "$kind" "$2"; printf '(println %s)\n' "$(cat "$QD/$q.rfl")"; } > "$s" + "$BIN_H" "$s" 2>&1 | md5sum | cut -c1-12 > "$W/g/id_h2"; rm -f "$s" + printf 'ident\t%s\tq%s\t%s\t%s\t%s\n' "$kind" "$q" "$(cat "$W/g/id_h")" "$(cat "$W/g/id_d")" "$(cat "$W/g/id_h2")" >> "$OUT" + done +} + +stage() { # kind: convert both, measure, delete head store (+ dev store unless kept) + local kind=$1 + case $kind in + gen0) + convert "$BIN_D" gen0 "$W/g/dev_gen0"; clause1 "$BIN_D" "$W/g/dev_gen0" dev_gen0 + convert "$BIN_H" gen0 "$W/g/head_gen0"; clause1 "$BIN_H" "$W/g/head_gen0" head_gen0 + measure gen0 "$W/g/head_gen0" "$W/g/dev_gen0"; ident gen0 "$W/g/head_gen0" "$W/g/dev_gen0" + rm -rf "$W/g/head_gen0" ;; + gen2) # dev gen-0 store is still on disk from the gen0 stage + convert "$BIN_H" gen2 "$W/g/head_gen2"; clause1 "$BIN_H" "$W/g/head_gen2" head_gen2 + measure gen2 "$W/g/head_gen2" "$W/g/dev_gen0"; ident gen2 "$W/g/head_gen2" "$W/g/dev_gen0" + rm -rf "$W/g/head_gen2" "$W/g/dev_gen0" ;; + parted) + convert "$BIN_D" parted "$W/g/dev_parted" + convert "$BIN_H" parted "$W/g/head_parted" + measure parted "$W/g/head_parted" "$W/g/dev_parted"; ident parted "$W/g/head_parted" "$W/g/dev_parted" + rm -rf "$W/g/head_parted" "$W/g/dev_parted" ;; + esac +} + +case "${1:?usage: pi_gate.sh run KIND|all|verdict}" in + run) stage "${2:?kind}" ;; + all) rm -f "$OUT"; printf 'meta\thead\t%s\n' "$(sha256sum "$BIN_H" | cut -c1-12)" >> "$OUT" + printf 'meta\tdev\t%s\n' "$(sha256sum "$BIN_D" | cut -c1-12)" >> "$OUT" + stage gen0; stage gen2; stage parted ;; + verdict) python3 "$HERE/pi_gate.py" "$OUT" ;; +esac diff --git a/bench/compress_estimate/pi_measure.sh b/bench/compress_estimate/pi_measure.sh new file mode 100755 index 000000000..492c7f12e --- /dev/null +++ b/bench/compress_estimate/pi_measure.sh @@ -0,0 +1,169 @@ +#!/usr/bin/env bash +# PI measurement (plan: compressed-columns PI, Task 1). +# conv : convert the 10M CSV twice (today's converter / upgrade disabled), +# recording wall time, peak RSS, store bytes and per-column bytes +# warm : q41, q42 on both stores, warm, alternated (5 rounds x 10 runs) +# gen2 : informational generation-2 store (no-hash converter, compress true) +# warm3 : q41, q42 on hash, nohash, gen2, alternated +# cold : q41, q42 on both stores, one fresh process per run, page cache +# evicted before each run, per file, with POSIX_FADV_DONTNEED +# through dd iflag=nocache (no privileged operation) +# Output: tab-separated lines appended to $W/pi.tsv. +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO=$(cd "$HERE/../.." && pwd) +W=${W:-$REPO/build/pi_bench} +SCHEMA= +QUERIES= +USAGE="usage: pi_measure.sh [-w WORKDIR] -s SCHEMA -q QUERIES \n -w WORKDIR scratch directory (default $REPO/build/pi_bench)\n -s SCHEMA the ClickBench rayforce schema.rfl\n -q QUERIES the ClickBench rayforce queries.rfl\n" +while getopts "w:s:q:" o; do + case $o in + w) W=$OPTARG ;; + s) SCHEMA=$OPTARG ;; + q) QUERIES=$OPTARG ;; + *) printf "%b" "$USAGE" >&2; exit 2 ;; + esac +done +shift $((OPTIND - 1)) +[ -n "$SCHEMA" ] || { printf "%b" "$USAGE" >&2; exit 2; } +[ -n "$QUERIES" ] || { printf "%b" "$USAGE" >&2; exit 2; } +CSV=/skull/clickbench/hits_h.csv +BIN_H=$W/rayforce_hash +BIN_N=$W/rayforce_nohash +OUT=$W/pi.tsv +mkdir -p "$W" + +query_n() { # print the n-th (1-based) paren-balanced expression of queries.rfl + awk -v want="$1" ' + /^[[:space:]]*$/ { next } + { q = q $0 "\n"; p = $0; gsub(/[^()]/, "", p) + for (i = 1; i <= length(p); i++) { c = substr(p, i, 1); if (c == "(") d++; else d-- } + if (d == 0) { n++; if (n == want) { printf "%s", q; exit } q = "" } }' "$QUERIES" +} + +evict() { # $1: store dir; per-file page-cache eviction, echoes the mode + sync + find "$1" -type f -exec dd if={} iflag=nocache count=0 status=none \; + echo fadvise +} + +case "${1:?usage: pi_measure.sh build|conv|warm|cold|gen2|warm3}" in +build) + avail=$(df -B1 --output=avail "$W" | tail -1) + [ "$avail" -ge $((13 * 1024 * 1024 * 1024)) ] || { echo "need 13 GB free in $W, have $avail" >&2; exit 2; } + # both binaries from detached copies of the same commit (HEAD): BIN_H as + # committed, BIN_N with the converter's hash upgrade check forced to 0. + # The BIN_N patch targets commit 2dcb78ae / trees before PI Task 3 (which + # removed ray_csv_hash_upgrade_check); on a later tree there is nothing to + # disable, the patch is skipped and BIN_N equals BIN_H. + SHA=$(git -C "$REPO" rev-parse --short HEAD) + T=${PI_TREES:-$W} + for t in h n; do + rm -rf "$T/pi-$t" + git -C "$REPO" worktree add --detach "$T/pi-$t" HEAD >/dev/null + done + python3 - "$T/pi-n/src/io/csv.c" <<'PY' +import sys +p = sys.argv[1] +s = open(p).read() +sig = "int ray_csv_hash_upgrade_check(int8_t type, int64_t len,\n const void* index_payload) {\n" +if s.count(sig) == 0: + print("pi_measure: no hash upgrade check in this tree (post PI Task 3): BIN_N not patched", file=sys.stderr) + sys.exit(0) +assert s.count(sig) == 1, "signature found more than once" +s = s.replace(sig, sig + " (void)type; (void)len; (void)index_payload;\n return 0; /* PI measurement only: upgrade disabled */\n") +open(p, "w").write(s) +PY + make -C "$T/pi-h" release >/dev/null && cp "$T/pi-h/rayforce" "$BIN_H" + make -C "$T/pi-n" release >/dev/null && cp "$T/pi-n/rayforce" "$BIN_N" + for t in h n; do git -C "$REPO" worktree remove --force "$T/pi-$t"; done + printf 'meta\tbuild\tsha\t%s\n' "$SHA" >> "$OUT" + echo "built $BIN_H $BIN_N from $SHA" + ;; +conv) + for v in hash nohash; do + bin=$BIN_H; [ "$v" = nohash ] && bin=$BIN_N + dir=$W/conv_$v + rm -rf "$dir" + s=$(mktemp) + cat "$SCHEMA" > "$s" + printf '\n(do (.csv.splayed hit-types "%s" "%s") null)\n' "$CSV" "$dir" >> "$s" + /usr/bin/time -f "%e %M" -o "$W/time_$v" "$bin" "$s" >/dev/null + rm -f "$s" + read -r secs rss_kb < "$W/time_$v" + printf 'conv\t%s\twall_s\t%s\n' "$v" "$secs" >> "$OUT" + printf 'conv\t%s\tpeak_rss_kb\t%s\n' "$v" "$rss_kb" >> "$OUT" + printf 'conv\t%s\tstore_bytes\t%s\n' "$v" "$(du -sb "$dir" | cut -f1)" >> "$OUT" + d=$dir; [ -f "$dir/.current" ] && d="$dir/$(cat "$dir/.current")" + for c in WatchID ClientEventTime FUniqID RefererHash URLHash UserID; do + printf 'conv\t%s\tbytes_%s\t%s\n' "$v" "$c" "$(stat -c %s "$d/$c")" >> "$OUT" + done + done + ;; +warm) + for qn in 41 42; do + q=$(query_n "$qn") + for round in 1 2 3 4 5; do + for v in hash nohash; do + s=$(mktemp) + printf '(set hits (.db.splayed.get "%s"))\n(do %s null)\n' "$W/conv_$v" "$q" > "$s" + for i in $(seq 1 10); do printf '(println (timeit %s))\n' "$q" >> "$s"; done + "$BIN_H" "$s" | while read -r ms; do printf 'warm\t%s\tq%s\t%s\n' "$v" "$qn" "$ms"; done >> "$OUT" + rm -f "$s" + done + done + done + ;; +cold) + for qn in 41 42; do + q=$(query_n "$qn") + for trial in 1 2 3 4 5; do + for v in hash nohash; do + mode=$(evict "$W/conv_$v") + s=$(mktemp) + printf '(println (timeit (set hits (.db.splayed.get "%s"))))\n(println (timeit %s))\n' "$W/conv_$v" "$q" > "$s" + mapfile -t r < <("$BIN_H" "$s") + rm -f "$s" + printf 'cold_load\t%s\tq%s\t%s\n' "$v" "$qn" "${r[0]}" >> "$OUT" + printf 'cold\t%s\tq%s\t%s\n' "$v" "$qn" "${r[1]}" >> "$OUT" + printf 'evict\t%s\tq%s\t%s\n' "$v" "$qn" "$mode" >> "$OUT" + done + done + done + ;; +gen2) + # informational (ruling C1): generation-2 store from the no-hash converter + avail=$(df -B1 --output=avail "$W" | tail -1) + [ "$avail" -ge $((4 * 1024 * 1024 * 1024)) ] || { echo "need 4 GB free for conv_gen2, have $avail" >&2; exit 2; } + dir=$W/conv_gen2 + rm -rf "$dir" + s=$(mktemp) + cat "$SCHEMA" > "$s" + printf '\n(do (.csv.splayed {compress: true} hit-types "%s" "%s") null)\n' "$CSV" "$dir" >> "$s" + /usr/bin/time -f "%e %M" -o "$W/time_gen2" "$BIN_N" "$s" >/dev/null + rm -f "$s" + read -r secs rss_kb < "$W/time_gen2" + printf 'conv\tgen2\twall_s\t%s\n' "$secs" >> "$OUT" + printf 'conv\tgen2\tpeak_rss_kb\t%s\n' "$rss_kb" >> "$OUT" + printf 'conv\tgen2\tstore_bytes\t%s\n' "$(du -sb "$dir" | cut -f1)" >> "$OUT" + d=$dir; [ -f "$dir/.current" ] && d="$dir/$(cat "$dir/.current")" + for c in WatchID ClientEventTime FUniqID RefererHash URLHash UserID; do + printf 'conv\tgen2\tbytes_%s\t%s\n' "$c" "$(stat -c %s "$d/$c")" >> "$OUT" + done + ;; +warm3) + # informational: q41/q42 on hash, nohash and gen2, alternated (kind warm3) + for qn in 41 42; do + q=$(query_n "$qn") + for round in 1 2 3 4 5; do + for v in hash nohash gen2; do + s=$(mktemp) + printf '(set hits (.db.splayed.get "%s"))\n(do %s null)\n' "$W/conv_$v" "$q" > "$s" + for i in $(seq 1 10); do printf '(println (timeit %s))\n' "$q" >> "$s"; done + "$BIN_H" "$s" | while read -r ms; do printf 'warm3\t%s\tq%s\t%s\n' "$v" "$qn" "$ms"; done >> "$OUT" + rm -f "$s" + done + done + done + ;; +esac diff --git a/bench/compress_estimate/pi_summary.py b/bench/compress_estimate/pi_summary.py new file mode 100644 index 000000000..da6d83f9c --- /dev/null +++ b/bench/compress_estimate/pi_summary.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Summarize pi.tsv: medians, ratios and the PI branch decision.""" +import statistics, sys +from collections import defaultdict + +rows = defaultdict(list) +conv = {} +for line in open(sys.argv[1]): + kind, variant, item, value = line.rstrip("\n").split("\t") + if kind == "conv": + conv[(variant, item)] = value + elif kind == "meta": + print(f"meta\t{item}\t{value}") + elif kind in ("warm", "warm3", "cold", "cold_load"): + rows[(kind, variant, item)].append(float(value)) + elif kind == "evict": + rows[("evict", variant, item)].append(value) + +lazy = "no" +for q in ("q41", "q42"): + if ("warm3", "gen2", q) in rows: + h = statistics.median(rows[("warm3", "hash", q)]) + for v in ("nohash", "gen2"): + m = statistics.median(rows[("warm3", v, q)]) + print(f"warm3\t{q}\t{v}_ms={m:.3f}\thash_ms={h:.3f}\tratio={m / h:.3f}\truns={len(rows[('warm3', v, q)])}") +for q in ("q41", "q42"): + for kind in ("warm", "cold", "cold_load"): + h = statistics.median(rows[(kind, "hash", q)]) + n = statistics.median(rows[(kind, "nohash", q)]) + print(f"{kind}\t{q}\thash_ms={h:.3f}\tnohash_ms={n:.3f}\tratio={n / h:.3f}\t" + f"runs={len(rows[(kind, 'hash', q)])}/{len(rows[(kind, 'nohash', q)])}") + if kind == "warm" and n / h > 1.05: + lazy = "yes" +modes = sorted({m for k, v in rows.items() if k[0] == "evict" for m in v}) +print("evict_modes\t" + ",".join(modes)) +for v in ("hash", "nohash", "gen2"): + if (v, "wall_s") not in conv: + continue + print(f"conv\t{v}\twall_s={conv[(v, 'wall_s')]}\tpeak_rss_kb={conv[(v, 'peak_rss_kb')]}\t" + f"store_bytes={conv[(v, 'store_bytes')]}") +for c in ("WatchID", "ClientEventTime", "FUniqID", "RefererHash", "URLHash", "UserID"): + print(f"col\t{c}\thash={conv[('hash', 'bytes_' + c)]}\tnohash={conv[('nohash', 'bytes_' + c)]}\tgen2={conv.get(('gen2', 'bytes_' + c), '-')}") +print(f"LAZY_BUILD_NEEDED\t{lazy}") diff --git a/bench/compress_estimate/predicates.txt b/bench/compress_estimate/predicates.txt new file mode 100644 index 000000000..ef82d1dd9 --- /dev/null +++ b/bench/compress_estimate/predicates.txt @@ -0,0 +1,29 @@ +# group column op value +g_adv AdvEngineID != 0 +g_mpm MobilePhoneModel != "" +g_sp SearchPhrase != "" +g_url URL != "" +g_ref Referer != "" +g_user UserID == 435090932899640449 +g_q37 CounterID == 62 +g_q37 EventDate >= 2013.07.01 +g_q37 EventDate <= 2013.07.31 +g_q37 DontCountHits == 0 +g_q37 IsRefresh == 0 +g_q40 CounterID == 62 +g_q40 EventDate >= 2013.07.01 +g_q40 EventDate <= 2013.07.31 +g_q40 IsRefresh == 0 +g_q40 TraficSourceID in -1,6 +g_q40 RefererHash == 3594120000172545465 +g_q41 CounterID == 62 +g_q41 EventDate >= 2013.07.01 +g_q41 EventDate <= 2013.07.31 +g_q41 IsRefresh == 0 +g_q41 DontCountHits == 0 +g_q41 URLHash == 2868770270353813622 +g_q42 CounterID == 62 +g_q42 EventDate >= 2013.07.14 +g_q42 EventDate <= 2013.07.15 +g_q42 IsRefresh == 0 +g_q42 DontCountHits == 0 diff --git a/bench/global_set/README.md b/bench/global_set/README.md new file mode 100644 index 000000000..920a3e4b4 --- /dev/null +++ b/bench/global_set/README.md @@ -0,0 +1,63 @@ +# Indexed global writes (#951) + +The change indexes symbol-to-slot lookup for writes only. The existing env +lock, global value epoch, slot order, user flags, and read path are preserved. +The fixed 1,024-slot binding table uses a 2,048-bucket index of slot-plus-one +values (4 KiB), with no per-value allocation. New names and misses use the +same index. Deletion already shifts slots; it rebuilds the small index under +the lock. Runtime initialization/destruction clears it with the env. + +## Reproduce + +The issue's compiled Rayfall loops are in `global_set.rfl`: + +```sh +make release -j4 +./rayforce -c 1 -f bench/global_set/global_set.rfl +``` + +To isolate lookup/refcount cost from Rayfall dispatch and value allocation: + +```sh +make lib -j4 +cc -O3 -Iinclude -Isrc bench/global_set/global_set.c librayforce.a \ + -lm -lpthread -o /tmp/global-set +RAYFORCE_CORES=1 /tmp/global-set 1000000 +``` + +The C program prebinds 512 user names, then measures same-symbol writes, +rotating-symbol writes, unchanged reads, and a dotted-write control. It uses +CPU time from C `clock()` and checks its read checksum. Run against both +baseline and candidate libraries on the same host. + +## Local results + +Measured on 2026-10-23 with optimized Clang builds, based on upstream +`d4899d91`. For the comparison, only the `env.c` object was replaced: all +other release objects and compiler flags were identical. The native program +reported 864 initial bindings. Five process runs per variant alternated +before/after order; the table gives medians in nanoseconds per operation. + +| Native operation | Before | Indexed writes | +|---|---:|---:| +| Same symbol, near end of env | 219.61 | 20.57 | +| Rotate over 512 symbols | 170.54 | 18.27 | +| Read control | 1.59 | 1.60 | +| Dotted-write control | 283.38 | 65.11 | + +The issue's one-million-iteration loops, medians of five samples in ms: + +| Rayfall loop | Before | Indexed writes | +|---|---:|---:| +| Local counter | 61.00 | 61.06 | +| Global counter | 175.25 | 80.31 | +| Local counter + global write | 193.09 | 82.22 | + +All loop checksums agree. These are observations, not hard performance tests. +Lock elision and per-slot value versions are separate changes and are not +needed for this lookup improvement. + +Focused sanitizer coverage includes randomized delete/reinsert/rebind, +runtime recreation, full-capacity rebinding and slot reuse, builtin user +flags, cached values (including exact dotted builtin names), environment +lookup, snapshot/replay, and persisted-symbol runtime initialization. diff --git a/bench/global_set/global_set.c b/bench/global_set/global_set.c new file mode 100644 index 000000000..de6db499b --- /dev/null +++ b/bench/global_set/global_set.c @@ -0,0 +1,52 @@ +/* #951: isolate binding lookup from allocation and Rayfall dispatch. + * Build against a release librayforce.a; see README.md. */ +#include +#include "lang/env.h" +#include +#include +#include +#include + +static double ns_per_op(clock_t begin, uint64_t n) { + return 1e9 * (double)(clock() - begin) / (double)CLOCKS_PER_SEC / (double)n; +} + +int main(int argc, char** argv) { + uint64_t n = argc > 1 ? strtoull(argv[1], NULL, 10) : UINT64_C(10000000); + if (!n) return 2; + ray_runtime_t* runtime = ray_runtime_create(0, NULL); + if (!runtime) return 2; + enum { NAMES = 512 }; + int64_t ids[NAMES]; + ray_t* value = ray_i64(7); + for (int i = 0; i < NAMES; i++) { + char name[48]; + int len = snprintf(name, sizeof(name), "global_set_bench_%d", i); + ids[i] = ray_sym_intern(name, (size_t)len); + if (ray_env_set(ids[i], value) != RAY_OK) return 2; + } + printf("bindings=%d iterations=%llu\n", ray_env_global_count(), (unsigned long long)n); + clock_t begin = clock(); + for (uint64_t i = 0; i < n; i++) + if (ray_env_set(ids[NAMES - 1], value) != RAY_OK) return 2; + printf("same-symbol-ns %.3f\n", ns_per_op(begin, n)); + begin = clock(); + for (uint64_t i = 0; i < n; i++) + if (ray_env_set(ids[i % NAMES], value) != RAY_OK) return 2; + printf("rotating-symbols-ns %.3f\n", ns_per_op(begin, n)); + volatile int64_t sum = 0; + begin = clock(); + for (uint64_t i = 0; i < n; i++) sum += ray_env_get_global(ids[i % NAMES])->i64; + printf("read-control-ns %.3f\n", ns_per_op(begin, n)); + int64_t dotted = ray_sym_intern("global_set_state.value", 22); + if (ray_env_set(dotted, value) != RAY_OK) return 2; + uint64_t ndot = n / 10 + 1; + begin = clock(); + for (uint64_t i = 0; i < ndot; i++) + if (ray_env_set(dotted, value) != RAY_OK) return 2; + printf("dotted-control-ns %.3f\n", ns_per_op(begin, ndot)); + printf("checksum=%lld\n", (long long)sum); + ray_release(value); + ray_runtime_destroy(runtime); + return sum == (int64_t)(7 * n) ? 0 : 2; +} diff --git a/bench/global_set/global_set.rfl b/bench/global_set/global_set.rfl new file mode 100644 index 000000000..a413a864d --- /dev/null +++ b/bench/global_set/global_set.rfl @@ -0,0 +1,12 @@ +;; Same loop shapes as #951, with five interleaved samples. +(set n 1000000) +(set x 0) +(set l_loop (fn [] (let i 0) (while (< i n) (let i (+ i 1))) i)) +(set g_loop (fn [] (set i 0) (while (< i n) (set i (+ i 1))) i)) +(set mix (fn [] (let i 0) (while (< i n) (set x i) (let i (+ i 1))) i)) +(l_loop) (g_loop) (mix) +(times [sample 5] + (println (list "local" (timeit (l_loop)))) + (println (list "global" (timeit (g_loop)))) + (println (list "mixed" (timeit (mix))))) +(println (list "checksums" (l_loop) (g_loop) (mix) x)) diff --git a/bench/global_set/rayfall-after.txt b/bench/global_set/rayfall-after.txt new file mode 100644 index 000000000..0d9d3d5ab --- /dev/null +++ b/bench/global_set/rayfall-after.txt @@ -0,0 +1,16 @@ +[local 61.1349] +[global 79.9146] +[mixed 81.9292] +[local 60.6894] +[global 79.9242] +[mixed 81.7657] +[local 60.7708] +[global 80.3111] +[mixed 82.4115] +[local 61.1454] +[global 80.9024] +[mixed 82.2222] +[local 61.0586] +[global 82.133] +[mixed 84.6347] +[checksums 1000000 1000000 1000000 999999] diff --git a/bench/global_set/rayfall-before.txt b/bench/global_set/rayfall-before.txt new file mode 100644 index 000000000..eae2c58af --- /dev/null +++ b/bench/global_set/rayfall-before.txt @@ -0,0 +1,16 @@ +[local 61.6782] +[global 172.492] +[mixed 198.514] +[local 60.9962] +[global 175.253] +[mixed 192.768] +[local 60.6798] +[global 173.945] +[mixed 192.59] +[local 60.8827] +[global 177.192] +[mixed 193.419] +[local 66.8172] +[global 177.524] +[mixed 193.093] +[checksums 1000000 1000000 1000000 999999] diff --git a/bench/global_set/results.json b/bench/global_set/results.json new file mode 100644 index 000000000..7a3402e2a --- /dev/null +++ b/bench/global_set/results.json @@ -0,0 +1,92 @@ +[ + { + "round": 0, + "version": "before", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 218.801\nrotating-symbols-ns 169.404\nread-control-ns 1.574\ndotted-control-ns 278.167\nchecksum=7000000\n", + "same-symbol-ns": 218.801, + "rotating-symbols-ns": 169.404, + "read-control-ns": 1.574, + "dotted-control-ns": 278.167 + }, + { + "round": 0, + "version": "after", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 18.126\nrotating-symbols-ns 18.160\nread-control-ns 1.594\ndotted-control-ns 64.269\nchecksum=7000000\n", + "same-symbol-ns": 18.126, + "rotating-symbols-ns": 18.16, + "read-control-ns": 1.594, + "dotted-control-ns": 64.269 + }, + { + "round": 1, + "version": "after", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 20.572\nrotating-symbols-ns 18.130\nread-control-ns 1.596\ndotted-control-ns 65.109\nchecksum=7000000\n", + "same-symbol-ns": 20.572, + "rotating-symbols-ns": 18.13, + "read-control-ns": 1.596, + "dotted-control-ns": 65.109 + }, + { + "round": 1, + "version": "before", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 225.420\nrotating-symbols-ns 170.536\nread-control-ns 1.611\ndotted-control-ns 284.237\nchecksum=7000000\n", + "same-symbol-ns": 225.42, + "rotating-symbols-ns": 170.536, + "read-control-ns": 1.611, + "dotted-control-ns": 284.237 + }, + { + "round": 2, + "version": "before", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 219.613\nrotating-symbols-ns 174.640\nread-control-ns 1.508\ndotted-control-ns 287.257\nchecksum=7000000\n", + "same-symbol-ns": 219.613, + "rotating-symbols-ns": 174.64, + "read-control-ns": 1.508, + "dotted-control-ns": 287.257 + }, + { + "round": 2, + "version": "after", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 24.651\nrotating-symbols-ns 18.575\nread-control-ns 1.502\ndotted-control-ns 65.479\nchecksum=7000000\n", + "same-symbol-ns": 24.651, + "rotating-symbols-ns": 18.575, + "read-control-ns": 1.502, + "dotted-control-ns": 65.479 + }, + { + "round": 3, + "version": "after", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 22.402\nrotating-symbols-ns 18.597\nread-control-ns 1.622\ndotted-control-ns 64.089\nchecksum=7000000\n", + "same-symbol-ns": 22.402, + "rotating-symbols-ns": 18.597, + "read-control-ns": 1.622, + "dotted-control-ns": 64.089 + }, + { + "round": 3, + "version": "before", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 240.902\nrotating-symbols-ns 168.516\nread-control-ns 1.599\ndotted-control-ns 277.287\nchecksum=7000000\n", + "same-symbol-ns": 240.902, + "rotating-symbols-ns": 168.516, + "read-control-ns": 1.599, + "dotted-control-ns": 277.287 + }, + { + "round": 4, + "version": "before", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 216.269\nrotating-symbols-ns 172.480\nread-control-ns 1.588\ndotted-control-ns 283.377\nchecksum=7000000\n", + "same-symbol-ns": 216.269, + "rotating-symbols-ns": 172.48, + "read-control-ns": 1.588, + "dotted-control-ns": 283.377 + }, + { + "round": 4, + "version": "after", + "stdout": "bindings=864 iterations=1000000\nsame-symbol-ns 18.273\nrotating-symbols-ns 18.274\nread-control-ns 1.620\ndotted-control-ns 65.189\nchecksum=7000000\n", + "same-symbol-ns": 18.273, + "rotating-symbols-ns": 18.274, + "read-control-ns": 1.62, + "dotted-control-ns": 65.189 + } +] \ No newline at end of file diff --git a/bench/join_identity/README.md b/bench/join_identity/README.md new file mode 100644 index 000000000..e2c38cb44 --- /dev/null +++ b/bench/join_identity/README.md @@ -0,0 +1,73 @@ +# Identity left-join gather + +The flat LEFT join executor retains left columns when the completed left +index mapping is exactly `[0, ..., left_rows - 1]`. It avoids allocating +and gathering unchanged columns and preserves their null bitmaps, string +pools and symbol domains. Updates retain the existing copy-on-write +semantics. Duplicate expansion and reordered output use the gather path; +FULL joins also keep that path because right-only rows change the left side. +Slice-valued left columns are gathered independently even with an identity +mapping: slice-header COW does not detach their parent. Other columns in the +same table can still be retained. + +## Standalone probe + +Build separate release binaries from the base and candidate, then run each +from this checkout: + +```sh +RAYFORCE_CORES=4 /path/to/base bench/join_identity/probe.rfl +RAYFORCE_CORES=4 /path/to/candidate bench/join_identity/probe.rfl +``` + +The probe builds one million rows with eight left columns and three unique +right keys. It measures one join, excluding input construction, and checks +the left row order, the last payload column, right payload sum and unmatched +null count. Each process prints `BENCH|milliseconds|valid|rows`. Compare fresh +processes in randomized order after discarded warm-ups, with identical build +flags and worker settings. Whole-process timing includes construction and +validation; use the printed join timing when comparing the executor itself. +The probe checks values; C ownership tests verify that sharing actually occurs. + +## Backtester measurement + +Matched local release builds based on `d7153e72`, Clang 23.1.3, default +`make release` flags; the candidate changes only `join.c`. Both variants +use the same projected backtester report. The workload has 100 instruments, +26,304 hourly steps, 2,630,400 bars and 705 fills, using xsmomf. The default +worker configuration is unchanged between variants. + +One discarded warm-up per variant, then three fresh processes each in +shuffled order (seed 22), without concurrent local compilation or tests: + +| Median | Base | Candidate | +|---|---:|---:| +| Post-run checks | 1146.46 ms | 1047.97 ms | +| Whole process | 4.137 s | 4.022 s | +| Peak RSS | 1608.2 MiB | 1590.1 MiB | + +These measurements include the slice fallback review correction. +Check ranges: base 1134.08–1163.55 ms, candidate 1043.04–1051.07 ms. +Process ranges: base 4.074–4.326 s, candidate 4.011–4.052 s. +This small experiment on a shared host is evidence for this workload, +not a general speedup guarantee. The backtester and its generated data are +external to this repository; the standalone probe above needs neither. + +## Regression coverage + +`test/test_join_buildside.c` checks pointer sharing, copy-on-write, null +metadata, string-pool lifetime after releasing the source, duplicate +expansion and a large order-preserving join. The large sharing fixture keeps +its build side below radix dispatch. +A separate equal-cardinality fixture takes the radix route and verifies +that output really is reordered, every left/right payload remains matched, +and reordered columns are gathered. The slice fixture mutates an owned +output and verifies the source slice, its parent and the original join +result retain their values, while an ordinary column still shares. +The slice regression fails on the original PR at the source-value assertion. +Deliberately removing the mapping guard fails the radix test at the +left/right payload-association assertion; restoring the guard passes. + +`test/rfl/join/join_identity.rfl` checks nulls, symbols, nested lists, +source/result update isolation, missing matches, duplicate expansion and +FULL joins. diff --git a/bench/join_identity/probe.rfl b/bench/join_identity/probe.rfl new file mode 100644 index 000000000..acc031d37 --- /dev/null +++ b/bench/join_identity/probe.rfl @@ -0,0 +1,15 @@ +;; One measured join per process; input construction is outside timeit. +(set n 1000000) +(set ids (til n)) +(set left (table [k a b c d e f g] + (list ids (+ ids 1) (+ ids 2) (+ ids 3) + (+ ids 4) (+ ids 5) (+ ids 6) (+ ids 7)))) +(set right (table [k mark] (list [0 500000 999999] [10 20 30]))) +(set elapsed_ms (timeit (set joined (left-join [k] left right)))) +(set valid (and (== (count joined) n) + (all (== (at joined 'k) ids)) + (all (== (at joined 'g) (+ ids 7))) + (== (sum (at joined 'mark)) 60) + (== (sum (map nil? (at joined 'mark))) (- n 3)))) +(if (not valid) (raise "identity-join: incorrect result")) +(println (format "BENCH|%|%|%" elapsed_ms (as 'I64 valid) (count joined))) diff --git a/bench/join_tiny_ht/.gitignore b/bench/join_tiny_ht/.gitignore new file mode 100644 index 000000000..2a27e17ac --- /dev/null +++ b/bench/join_tiny_ht/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +/results.json diff --git a/bench/join_tiny_ht/README.md b/bench/join_tiny_ht/README.md new file mode 100644 index 000000000..b4658ec7b --- /dev/null +++ b/bench/join_tiny_ht/README.md @@ -0,0 +1,53 @@ +# Tiny-build chained join probe + +A fixed-key version of the issue #599 shape: 200 inner joins of a 130,000-row, +773-instrument table against three unique composite keys. Each run verifies +101,400 output rows by an independent arithmetic oracle. This is a count check, +not a full answer-equivalence proof; correctness fixtures check exact pair IDs. + +Build baseline and candidate **release** binaries in separate worktrees and +preserve copies. `make test` overwrites the worktree CLI with a sanitizer build; +do not accidentally compare that binary against release. + +```sh +python3 bench/join_tiny_ht/compare.py /path/base-release /path/candidate-release \ + --cores 1 4 --trials 5 --output /tmp/join-tiny-results.json +``` + +The Unix-only, standard-library Python wrapper shuffles fresh processes, records +binary and probe SHA256s, and explicitly selects the existing steal scheduler. +`-c N` is the CLI's **total participants** (main included); this is not the +background-worker count used by positive `RAYFORCE_CORES`. The script clears that +environment override and tracing. There is no explicit warmup. Process user/sys +CPU and process wall time include startup/setup; `loop_ms` measures the join loop. +Avoid concurrent local builds/tests and report hardware, compiler, affinity and +noise/ranges when sharing measurements. The wrapper does not certify build flags +or exclusive machine idleness. + +This is a narrow workload, not a general join or compression benchmark, a pool +policy recommendation, or complete resolution of issue #599. User CPU is not an +instruction count: clocks, SMT, topology and waiting can change thread-seconds. +For causal analysis, measure instructions/cycles separately with helper-thread +inheritance and multiplexing checks. Do not mix instrumented timing with the +uninstrumented comparison. + +## What this optimization changes + +The minimum chained table has 256 heads (1 KiB). Its count and fill passes do +not hash a future left row merely to prefetch a head in that small table. Actual +current-row hashing, equality and output are unchanged. Capacity, not distinct +key count, selects the mode once per pass; the 128/129 right-row boundary has +256/512 heads. Both serial and pooled calls use the selected callback. Shared +inline bodies keep the semantics in one place while the two constant-mode +wrappers avoid a release per-row capacity-mode test in the inspected Clang build. +The larger-table prefetch and build-side prefetch remain. The head array's size +is not proof that the entire working set stays resident. + +Exact pair-ID fixtures separately cover duplicates, nulls and misses for inner, +left and full joins, the capacity boundary, and probe rows spanning a morsel. +The benchmark's row-count oracle does not replace those checks. Choose core +counts appropriate for the machine; requested counts do not prove which physical +helpers executed tasks. The example uses one and four total participants rather +than silently oversubscribing a four-core host. Retain any unfavorable larger, +radix or long-string controls when reporting the narrow gain. Callback +specialization can change code size/layout even on a retained-prefetch path. diff --git a/bench/join_tiny_ht/compare.py b/bench/join_tiny_ht/compare.py new file mode 100644 index 000000000..4289466ef --- /dev/null +++ b/bench/join_tiny_ht/compare.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Unix-only, stdlib benchmark. Does not build or modify either binary.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import random +import re +import resource +import statistics +import subprocess +import time + +parser = argparse.ArgumentParser() +parser.add_argument('baseline', type=Path) +parser.add_argument('candidate', type=Path) +parser.add_argument('--cores', type=int, nargs='+', default=[1, 8, 16]) +parser.add_argument('--trials', type=int, default=3) +parser.add_argument('--output', type=Path, default=Path(__file__).with_name('results.json')) +args = parser.parse_args() +if args.trials < 1 or any(c < 1 for c in args.cores): + parser.error('trials and total-participant core counts must be positive') +binaries = {name: path.resolve() for name, path in + [('baseline', args.baseline), ('candidate', args.candidate)]} +probe = Path(__file__).with_name('probe.rfl').resolve() +metadata = {name: {'path': str(path), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()} + for name, path in binaries.items()} +jobs = [(name, cores, trial) for name in binaries for cores in args.cores + for trial in range(args.trials)] +random.Random(599).shuffle(jobs) +env = os.environ.copy() +for name in ['RAYFORCE_CORES', 'RAY_POOL_TRACE']: + env.pop(name, None) +env['RAY_POOL_STEAL'] = '1' +rows = [] +for name, cores, trial in jobs: + before = resource.getrusage(resource.RUSAGE_CHILDREN) + start = time.monotonic() + proc = subprocess.run([str(binaries[name]), '-c', str(cores), str(probe)], + stdin=subprocess.DEVNULL, capture_output=True, + text=True, env=env, timeout=180) + wall = time.monotonic() - start + after = resource.getrusage(resource.RUSAGE_CHILDREN) + if proc.returncode: + raise RuntimeError(f'{name}, -c {cores}: {proc.stdout}\n{proc.stderr}') + if 'keys: ["INST0" "INST1" "INST2"]' not in proc.stdout: + raise RuntimeError(f'unexpected build keys: {proc.stdout}') + count = re.search(r'^result: (\d+)$', proc.stdout, re.M) + # 130000 rows cycling773 values: each of keys0/1/2 occurs169 times. + expected = 200 * sum(130000 // 773 + (i < 130000 % 773) for i in range(3)) + elapsed = re.search(r'^loop_ms: ([\d.e+-]+)$', proc.stdout, re.M) + if not count or int(count.group(1)) != expected or not elapsed: + raise RuntimeError(f'output/oracle mismatch: {proc.stdout}') + row = dict(binary=name, cores=cores, trial=trial, wall_s=wall, + user_s=after.ru_utime-before.ru_utime, + sys_s=after.ru_stime-before.ru_stime, + loop_ms=float(elapsed.group(1)), result=expected) + rows.append(row) + print(json.dumps(row), flush=True) +args.output.write_text(json.dumps(dict(binaries=metadata, + probe_sha256=hashlib.sha256(probe.read_bytes()).hexdigest(), + environment=dict(scheduler='steal', explicit_warmup=False), rows=rows), indent=2)) +for name in binaries: + for cores in args.cores: + group = [r for r in rows if r['binary'] == name and r['cores'] == cores] + print(name, cores, {key: statistics.median(r[key] for r in group) + for key in ['user_s', 'sys_s', 'wall_s', 'loop_ms']}) diff --git a/bench/join_tiny_ht/probe.rfl b/bench/join_tiny_ht/probe.rfl new file mode 100644 index 000000000..0e2b7b457 --- /dev/null +++ b/bench/join_tiny_ht/probe.rfl @@ -0,0 +1,10 @@ +;; Fixed-key version of the issue599 join shape; no explicit warmup. +(set N 130000) +(set syms (map (fn [i] (parse (format "INST%" i))) (til 773))) +(set t (table [venue instrument session message_id px] (list (take ['BFU] N) (take syms N) (take ['S1] N) (til N) (til N)))) +(set ks (select {from: t by: [venue instrument] n: (count px)})) +(set k3 (select {from: ks where: (in instrument ['INST0 'INST1 'INST2]) asc: instrument})) +(println "keys: %" (as 'STR (at k3 'instrument))) +(set n 0) +(println "loop_ms: %" (timeit (times 200 (set n (+ n (count (inner-join [venue instrument] t k3))))))) +(println "result: %" n) diff --git a/bench/minmax_query/README.md b/bench/minmax_query/README.md new file mode 100644 index 000000000..e7c38f296 --- /dev/null +++ b/bench/minmax_query/README.md @@ -0,0 +1,56 @@ +# Dyadic min/max query routes + +A MIN-focused synthetic, value-checked POSIX C probe for SELECT call classification and +avoidable per-row evaluator overhead. It is not ClickBench, a real workload +certification, or a general benchmark framework. + +## Build/run (Linux) + +Use the **same checkout's headers and static library**. Never combine an older +archive with newer struct definitions. The library build uses the project's +optimized library recipe, including its per-file floating-point flags. + +```sh +make -j4 lib CC=clang +clang -O3 -std=c17 -march=native -Iinclude bench/minmax_query/bench.c \ + librayforce.a -lm -lpthread -ldl -o /tmp/ray-minmax-query +RAYFORCE_CORES=0 /tmp/ray-minmax-query 1 200000 +RAYFORCE_CORES=3 /tmp/ray-minmax-query 1 200000 +``` + +Arguments are a case number and 1,000–10,000,000 rows, in multiples of 1,000. +`RAYFORCE_CORES` configures background helpers, **not total participants or +proof that those helpers ran**. The C runtime API does not interpret CLI `-c`. + +| Case | Timed expression | +|---|---| +| 0 | Direct language `min` over two table columns | +| 1 | SELECT dyadic `min x y` | +| 2 | SELECT `if (< x y) x y`, an equivalent **non-null I64** control | +| 3 | Genuine unary SELECT `min x` reduction | +| 4 | Grouped `sum (min x y)`, with 997 integer keys | + +Data creation/runtime initialization happen outside timing. Each fresh process +warms its case twice, then emits five `PRICE sample wall_ms process_cpu_ms` +records. Parsing and query construction are included in each evaluation; +payload checks and result release are outside the timed interval. Process CPU +includes all threads, not just the caller. Every warm/timed result must have +its exact I64 type, length and **every expected value**; success ends with +`VALIDATED 7`. Case 4 computes its oracle independently, not from another +engine route. Run multiple fresh processes in interleaved order and retain +all samples/ranges, including slow controls. + +Direct language MIN is still a boxed element-mapping implementation, **not a +raw SIMD MIN kernel**. The IF control is not a null-semantics oracle: language +dyadic MAX treats NULL as low, unlike graph MAX2's null propagation. These +positive-I64 measurements do not certify mixed/narrow types, NULLs, strings, +lexical shadows, file-backed sources, allocation failures or service latency. +Those require separate semantic tests. + +An unfixed SELECT that reduces only its first operand will fail the shape/value +checker; its short runtime is not a valid performance baseline. To study the +batching optimization, compare against an arity-correct but unbatched revision. +Record source/binary/compiler/flags, row count, worker settings and affinity. +For helper-free (`RAYFORCE_CORES=0`) controls, optional `taskset` affinity can reduce CPU +placement variance; do not mistake it for exclusive CPU isolation. Do not pin +multiple helpers to one CPU and call that a multicore throughput measurement. diff --git a/bench/minmax_query/bench.c b/bench/minmax_query/bench.c new file mode 100644 index 000000000..93e192571 --- /dev/null +++ b/bench/minmax_query/bench.c @@ -0,0 +1,37 @@ +#define _POSIX_C_SOURCE 200809L +#include "rayforce.h" +#include +#include +#include +#include +#include + +static uint64_t now(clockid_t c) { struct timespec t; if (clock_gettime(c,&t)) exit(9); return (uint64_t)t.tv_sec*1000000000ULL+(uint64_t)t.tv_nsec; } +static ray_t* eval(const char* s) { ray_t* v=ray_eval_str(s); if(!v || RAY_IS_ERR(v)) { const char* msg=ray_error_msg(); fprintf(stderr,"eval failed: %s: %s\n",s,msg ? msg : "no error message"); if(v)ray_error_free(v); exit(3); } return v; } +static void discard(const char* s) { ray_t* v=eval(s); ray_release(v); } +int main(int argc,char** argv) { + if(argc!=3) { fprintf(stderr,"usage: %s CASE(0..4) ROWS(1000..10000000, multiple of 1000)\n",argv[0]); return 2; } + char* end = NULL; + errno = 0; long choice = strtol(argv[1], &end, 10); + if(errno || end == argv[1] || *end || choice < 0 || choice > 4) return 2; + errno = 0; long long rows = strtoll(argv[2], &end, 10); + if(errno || end == argv[2] || *end || rows < 1000 || rows > 10000000 || rows % 1000) return 2; + int which = (int)choice; int64_t n = (int64_t)rows; + ray_runtime_t* rt=ray_runtime_create(0,NULL); if(!rt)return 3; + char setup[200]; snprintf(setup,sizeof(setup),"(set MX971 (%% (til %lld) 1000))",(long long)n); discard(setup); + discard("(set MY971 (- 999 MX971))"); + snprintf(setup,sizeof(setup),"(set MK971 (%% (til %lld) 997))",(long long)n); discard(setup); + discard("(set MB971 (table [x y k] (list MX971 MY971 MK971)))"); + const char* cases[]={"(min (at MB971 'x) (at MB971 'y))","(at (select {r: (min x y) from: MB971}) 'r)","(at (select {r: (if (< x y) x y) from: MB971}) 'r)","(at (select {r: (min x) from: MB971}) 'r)","(at (select {r: (sum (min x y)) from: MB971 by: k asc: k}) 'r)"}; + int64_t sums[997]={0}; for(int64_t i=0;itype!=RAY_I64 || ray_len(v)!=wantlen){fprintf(stderr,"shape kind=%d type=%d len=%lld expected=%lld\n",which,(int)v->type,(long long)ray_len(v),(long long)wantlen);exit(4);} + const int64_t* d=ray_data(v); + for(int64_t j=0;j=0)printf("PRICE %d %.9f %.9f\n",it,(double)(t1-t0)/1e6,(double)(c1-c0)/1e6); + } + puts("VALIDATED 7");ray_runtime_destroy(rt);return 0; +} diff --git a/bench/sorted_symbols/README.md b/bench/sorted_symbols/README.md new file mode 100644 index 000000000..62cec4d71 --- /dev/null +++ b/bench/sorted_symbols/README.md @@ -0,0 +1,322 @@ +# Already-sorted symbol keys + +Reproduce the sortedness-check contention in #933 without data files. The +script builds 2,630,400 rows ordered by `(timestamp, symbol)`, with 100 +lexically ordered symbols per timestamp. Symbol creation order differs from +lexical order. Construction and correctness checks are outside the timed +first `xasc`; start a fresh process for each observation. + +```sh +make -j8 release +RAYFORCE_CORES=4 ./rayforce bench/sorted_symbols/sorted_symbols.rfl +``` + +`RAYFORCE_CORES` requests secondary workers; zero is serial. Test 0, 1, 4 +and 16. Change `(set numeric 0)` to `(set numeric 1)` in a copy of the script +for the lexical integer-rank control. Discard one warm-up process and take +the median of three fresh processes per setting and key type. Output includes +the timed milliseconds, full key/row-count validation, and build identity. +The small reversed-input control verifies actual sorting outside timing. + +## Implementation + +The early sortedness scan compares adjacent rows, so timestamp ties often +require a symbol comparison on every row. Resolving those symbol IDs inside +parallel workers takes the shared runtime symbol lock repeatedly. Preparing +lexical ranks with `build_enum_rank` before dispatch replaces those lookups +with integer comparisons for large parallel table checks. First, an unranked +probe budgets one morsel (1024) of actual unequal-ID symbol comparisons, +rather than rows. Constant, low-transition, and bypassed secondary keys can +finish that probe without rank setup. A preceding key that already orders a +pair consumes no symbol budget. Early inversions still stop immediately. +Small tables and scans without secondary workers retain the serial scan. When ranks are unavailable because +of the density budget or allocation failure, the check keeps the string +comparator and scans serially; unavailable ranks never mean "not sorted". +Integer-only keys retain their existing parallel scan. Null and type +admissibility gates are unchanged. + +`ray_key_cols_sorted`, used by streaming parted ORDER BY, skips rank +preparation entirely. Symbol segments use the original equal-ID/string scan +serially, so constant segments need no string resolution and repeated small +segments do not repeatedly sort the domain. This also avoids shared-lock +contention. Table sorts retain any prepared ranks after workers join. The +real sort borrows them after a late inversion, including recursive single-key +sorts, so successful maps are not built twice. The caller frees them after +the real sort returns, or immediately on the already-sorted shortcut. Rank +storage remains sized through the maximum used intern ID; unavailable maps +may be retried by the real sort. +The serial fallback trades parallelism for bounded setup and no contention. +This change does not persist ordering ranks or change symbol representation. + +## Observed timings + +Measured on 2026-10-21 on a Ryzen AI 7 350, 16 logical CPUs, Linux, clang +optimized builds of upstream `64645998` and the patched source in the same +isolated build tree. Each cell is the median of three fresh processes after +one discarded warm-up. The machine was a shared desktop; small timing +differences are not decisive. + +| Secondary workers | Before symbols, ms | After symbols, ms | Before integers, ms | After integers, ms | +|---:|---:|---:|---:|---:| +| 0 | 52.036 | 21.773 | 21.254 | 22.069 | +| 1 | 85.375 | 17.608 | 16.648 | 16.925 | +| 4 | 291.224 | 14.876 | 14.113 | 14.165 | +| 16 | 1227.420 | 14.496 | 13.487 | 14.071 | + +Full reverse-sorted symbol input, reversed before timing and checked against +the same ascending expected output, measured 50.544/50.765 ms before/after +serially and 42.751/43.127 ms with four secondary workers. This is one +unsorted-input control, not an exhaustive regression study. + +## Sparse IDs and repeated partitions + +`work_count.c` counts symbol-domain string resolutions with the linker's +`--wrap` mechanism. It interns 70,000 unused names BEFORE the used symbol, +then checks an eight-row constant column and a 10,000-row constant column +twice each. The first exceeds the density budget; the second fits it. +The probe is serial and measures admission/work counts, not wall time. +Run from the repository root after `make release` (GNU-compatible linker): + +```sh +clang -O3 -Iinclude -Isrc bench/sorted_symbols/work_count.c \ + $(find src -name '*.rel.o' ! -path 'src/app/main.rel.o') \ + -lm -lpthread -Wl,--wrap=ray_sym_domain_str -o /tmp/symbol-work-count +/tmp/symbol-work-count +``` + +At the original PR head `f62ca12d`, both eight-row checks returned false; +both 10,000-row checks returned true but each performed 70,002 resolutions. +With the fallback/partition fix, all four return true with zero resolutions. +The same probe source was linked with the before/after sort objects; other +release objects were unchanged. This is a focused instrumented control. + +`parted_symbols.rfl` populates a database FILE symbol domain with 70,000 +padding names, writes two 10,000-row constant-symbol partitions, then times +50 ascending queries over the mounted table. Setup is outside timing. +It checks every result count and requires exactly 100 streaming partition +runs, so a flat fallback is an error. Run sequentially: the script uses and +removes `/tmp/rayforce_bench_rank_parts`. + +```sh +RAYFORCE_CORES=4 ./rayforce bench/sorted_symbols/parted_symbols.rfl +``` + +After one discarded warm-up, the median of three fresh processes was +232.272 ms on the original PR implementation and 1.766 ms after the fix, +for all 50 queries together. This reflects removal of repeated setup; +it is not a general query benchmark. The host was the same shared desktop. +The sparse eight-row streaming case is covered separately by +`test/rfl/sort/sorted_symbol_sparse_parted.rfl`, including exact streaming +counter deltas and full sequence checks in both budget regimes. It fails +on `f62ca12d` and passes after this fix. + +A fresh run of the original 2,630,400-row benchmark after the unsorted-input +fix retained the parallel speedup (three measurements after one warm-up). +The serial case now deliberately uses the original string scan, like +upstream, rather than preparing ranks without secondary workers: + +| Secondary workers | Symbols, ms | Integer ranks, ms | +|---:|---:|---:| +| 0 | 50.825 | 19.238 | +| 1 | 17.234 | 15.049 | +| 4 | 14.060 | 12.622 | +| 16 | 12.734 | 12.032 | + +## Unsorted and small table controls + +`unsorted_work.c` pads the runtime domain with 60,000 unused names before +creating the used keys. It exercises ascending and descending table sorts: +8-row unsorted input, 200,000-row input with an inversion at the first pair, +and 200,000-row input with an inversion at the last pair. Under the current +adaptive probe, that low-transition late inversion is discovered without +preparing ranks. A separate high-transition sorted-prefix C regression +exercises the rank handoff and borrowed lifetime after the budget is spent. It also checks the +large unsorted case without secondary workers. Every output key is checked. +The C regression additionally verifies stable row identities for these cases. + +For uninstrumented timing, build after `make release`: + +```sh +clang -O3 -march=native -std=c17 -Iinclude -Isrc \ + bench/sorted_symbols/unsorted_work.c \ + $(find src -name '*.rel.o' ! -path 'src/app/main.rel.o') \ + -lm -lpthread -o /tmp/unsorted-sort-time +/tmp/unsorted-sort-time +``` + +For string-resolution counts, add `-DCOUNT_RESOLUTIONS` and +`-Wl,--wrap=ray_sym_domain_str` to that command. Ignore timing from this +instrumented build. The probe initializes five total workers for the first +six cases, then one for the serial control. + +| Case (ascending) | Resolutions at eaff260a | At 8fcd0bc4 | +|---|---:|---:| +| Small | 60029 | 28 | +| Early inversion | 120006 | 60005 | +| Late inversion | 120006 | 60003 | +| Serial | 120006 | 60005 | + +Descending counts match the corresponding ascending cases. Early input +now pays for one real-sort rank build plus its two probe lookups; late input +prepares that map once and lends it to the real sort. Small input stays on +the comparison path without a dense LUT. Counts are measured over the entire +table sort, including its precheck, rather than just the precheck. + +The uninstrumented ascending medians in milliseconds at the unsorted-input +revision `8fcd0bc4` were: + +| Case | Upstream 64645998 | eaff260a | After unsorted fix | +|---|---:|---:|---:| +| Small | 0.022 | 2.155 | 0.025 | +| Early inversion | 3.030 | 5.131 | 3.161 | +| Late inversion | 3.191 | 5.023 | 3.072 | +| Serial | 2.919 | 4.883 | 3.032 | + +These are three fresh-process observations after one discarded warm-up per +build. Other release objects were identical; the upstream and eaff260a sort +objects were compiled separately with clang `-O3 -march=native -std=c17`. +The current sort object uses the release Makefile flags. Cases run in a fixed +order within each process, so the small ascending case includes first-sort +initialization and should not be compared with the later descending case. +Construction and validation are outside timing. The machine was a shared +desktop; these controls demonstrate removal of the extra work, not absence +of regressions for every input shape. Borrowed-rank ownership was checked +under ASan/UBSan with both serial and parallel sort tests. + +## Unbounded key-count regression + +The table caller stores key IDs, columns, rank pointers, rank scratch headers +and direction bytes in one checked, zeroed heap allocation. The sortedness +helper borrows the rank buffers directly and has no key-count-sized stack +arrays; the partition caller supplies no rank buffers at all. Allocation +failure returns an error before sorting, and the caller frees the block on +every exit, after releasing any prepared rank headers. + +`test/rfl/sort/sort_many_repeated_keys.rfl` checks `xasc` and `xdesc` on tiny +symbol and integer tables with 300,000 repeated key names. The C regression +`sort/sorted_many_repeated_keys` checks the query/partition helper directly +with a heap-backed 300,000-entry column list. These all-tie inputs force the +checks to visit every key. A reduced-stack sanitizer run verifies stack use +is independent of the user-supplied key count: + +```sh +(ulimit -s 2048; RAYFORCE_CORES=4 ./rayforce.test -f many_repeated_keys) +``` + +## Large constant and low-transition controls + +`constant_work.c` reproduces the additional review case with three total +participants, 70,000 unused names interned before the used keys, and 65,537 +rows. It checks ascending and descending sorts for a constant symbol key, +two long symbol runs, and a changing secondary symbol key bypassed by a +unique leading integer key. Every output key and row identity is validated. + +Build it like `unsorted_work.c`, substituting `constant_work.c`. By default +it reports uninstrumented sort time. Adding `-DCOUNT_RESOLUTIONS` and +`-Wl,--wrap=ray_sym_domain_str` asserts exact lookup counts: zero, two, and +zero for those three cases. The previous `73f7c0ea` source fails these work +assertions while still returning correct rows. + +| Shape, 65,537 rows | Upstream lookups | At 73f7c0ea | Adaptive probe | +|---|---:|---:|---:| +| Constant | 0 | 70003 | 0 | +| Two long runs | 2 | 70003 | 2 | +| Secondary key bypassed | 0 | 70003 | 0 | + +Counts agree in both directions. The larger raw ID prefix in the review's +process produced 70,422 lookups; this fresh process has 70,003 prefix IDs. +The underlying issue and repaired work counts are the same. + +Uninstrumented ascending medians over three processes after one warm-up: + +| Shape | Upstream, ms | At 73f7c0ea, ms | Adaptive probe, ms | +|---|---:|---:|---:| +| Constant | 0.080 | 3.771 | 0.091 | +| Two long runs | 0.069 | 2.440 | 0.084 | +| Secondary key bypassed | 0.625 | 3.252 | 0.530 | + +Other release objects were identical. The upstream and old sort objects +used clang `-O3 -march=native -std=c17`; the current object uses the release +Makefile flags. Inputs/validation are outside timing, cases run in fixed +order, and the host was shared. Submillisecond differences are not rankings. +The work-count checks, rather than the timings, pin the removal of setup. + +The adaptive probe leaves the worker comparator, heap buffer ownership, +sparse fallback, partition route, and borrowed-rank handoff unchanged. The +single-outlier late-inversion work control now makes 60,007 resolutions: +four probe lookups plus one 60,003-ID real-sort rank build. Early, small and +serial counts remain 60,005, 28 and 60,005. The updated C stability test has +1024 actual symbol comparisons in its sorted prefix, then a late inversion, +so ASan/UBSan still exercises the handoff instead of accidentally bypassing +it. Constant, two-run and bypassed-key C tests cover the newly cheap route. + +A contemporary dense-target control linked the `73f7c0ea` sort source with +matching release flags and otherwise identical objects. Three observations +after a warm-up, on the same shared host: + +| Secondary workers | 73f7c0ea symbols, ms | Adaptive symbols, ms | 73f7c0ea integers, ms | Adaptive integers, ms | +|---:|---:|---:|---:|---:| +| 4 | 19.881 | 20.554 | 18.036 | 16.930 | +| 16 | 21.416 | 20.914 | 19.399 | 18.585 | + +The parallel contention fix remains effective; small differences should not +be treated as a regression factor. Earlier measurements near 14 ms used a +different host load/CPU state, so this table compares the two revisions in +the current session instead of comparing only against historical timings. + +## Typed SYM-first scan control + +The comparison-budget probe shares the existing ascending SYM-first raw-i64 +scan with the worker for I64 and TIMESTAMP secondary keys. Rows within a +symbol run compare the secondary values directly, with no generic key/type +loop. The budget is polled only at symbol run boundaries; low-transition +inputs still finish without rank setup. This does not restore unconditional +row-count-based rank preparation or change the separate TIME-width repair. + +`typed_runs.c` reproduces the review recipe: 100 lexical symbols, 20,000 +contiguous rows each, with signed secondary values +`(i % 20000 - 10000) * 1000000`. It times whole `ray_xasc_fn` and checks +all output keys and both original source buffers outside timing. Symbol +creation order is the reverse of lexical order. Two arguments select total +participants and whether the secondary type is TIMESTAMP (1) or I64 (0). + +After `make release`, build from the repository root: + +```sh +clang -O3 -march=native -std=c17 -Iinclude -Isrc \ + bench/sorted_symbols/typed_runs.c \ + $(find src -name '*.rel.o' ! -path 'src/app/main.rel.o') \ + -lm -lpthread -o /tmp/typed-runs +taskset -c 0,1,2,3 /tmp/typed-runs 4 0 +taskset -c 0,1,2,3 /tmp/typed-runs 4 1 +``` + +Choose four CPUs available in the current affinity mask. The reported +comparison used CPUs 0–3, two discarded warm-up processes per case, then +12 fresh processes per case in randomized order (Python seed 937). There +were no concurrent local test/build jobs. The host/governor remained shared +and uncontrolled. Each variant replaced only the sort object, compiled with +matching release flags; all other release objects and the driver were +identical. The upstream reference is 64645998, rather than the reviewer's +later a587 reference; this is an independent reproduction on this host. + +| Secondary type | Total participants | Upstream median, ms | 43415820, ms | Typed probe, ms | +|---|---:|---:|---:|---:| +| I64 | 1 | 9.619 | 9.956 | 9.784 | +| I64 | 4 | 9.177 | 13.513 | 9.788 | +| TIMESTAMP | 1 | 9.654 | 9.980 | 9.825 | +| TIMESTAMP | 4 | 9.386 | 13.661 | 9.820 | + +The probe retains serial execution while deciding whether ranks are useful; +this fixes its generic per-cell dispatch overhead, rather than claiming the +same parallel strategy or identical latency as upstream. Four-participant +I64 ranges were 8.911–15.177 ms upstream, 13.307–14.724 ms on 43415820, +and 9.083–16.666 ms with the typed probe. These are workload controls, not +universal performance guarantees. + +The C regression `sort/sorted_sym_i64_probe` covers both secondary types, +negative/positive values, 100 low-transition runs, 2048 runs that spend the +budget, and a late secondary inversion. It verifies every row identity and +key after sorting. The high-transition inversion still exercises borrowed +rank lifetime; constant/work-count, sparse/streaming and reduced-stack +regressions remain separate controls. diff --git a/bench/sorted_symbols/constant_work.c b/bench/sorted_symbols/constant_work.c new file mode 100644 index 000000000..b18beda87 --- /dev/null +++ b/bench/sorted_symbols/constant_work.c @@ -0,0 +1,79 @@ +/* Default: sort time. COUNT_RESOLUTIONS: assert GNU ld --wrap work counts. */ +#define _POSIX_C_SOURCE 200809L +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "table/domain.h" +#include "lang/internal.h" +#include "core/pool.h" +#include +#include +#include +static _Atomic unsigned long long resolutions; +#ifdef COUNT_RESOLUTIONS +ray_t* __real_ray_sym_domain_str(ray_sym_domain_t*, int64_t); +ray_t* __wrap_ray_sym_domain_str(ray_sym_domain_t* dom, int64_t id) { + atomic_fetch_add_explicit(&resolutions, 1, memory_order_relaxed); + return __real_ray_sym_domain_str(dom, id); +} +#endif +static int probe(int kind, int desc, int64_t a, int64_t z) { + const int n = 65537; + ray_t* sym = ray_vec_new(RAY_SYM, n); + ray_t* time = ray_vec_new(RAY_I64, n); + ray_t* row = ray_vec_new(RAY_I64, n); + sym->len = time->len = row->len = n; + for (int i = 0; i < n; i++) { + int first = kind == 2 ? i % 2 == 0 : i < n / 2; + ((int64_t*)ray_data(sym))[i] = kind == 0 ? a : (first ? (desc ? z : a) : (desc ? a : z)); + ((int64_t*)ray_data(time))[i] = desc ? n - 1 - i : i; + ((int64_t*)ray_data(row))[i] = i; + } + int64_t sn = ray_sym_intern("s", 1), tn = ray_sym_intern("t", 1); + int64_t rn = ray_sym_intern("row", 3); + int64_t names[] = {tn, sn}; + ray_t* keys = ray_vec_from_raw(RAY_SYM, names + (kind == 2 ? 0 : 1), kind == 2 ? 2 : 1); + ray_t* table = ray_table_new(3); + table = ray_table_add_col(table, sn, sym); + table = ray_table_add_col(table, tn, time); + table = ray_table_add_col(table, rn, row); + atomic_store(&resolutions, 0); + struct timespec start, finish; + clock_gettime(CLOCK_MONOTONIC, &start); + ray_t* result = desc ? ray_xdesc_fn(table, keys) : ray_xasc_fn(table, keys); + clock_gettime(CLOCK_MONOTONIC, &finish); + unsigned long long calls = atomic_load(&resolutions); + double ms = (finish.tv_sec - start.tv_sec) * 1000.0 + (finish.tv_nsec - start.tv_nsec) / 1000000.0; + int valid = result && !RAY_IS_ERR(result) && ray_table_nrows(result) == n; + if (valid) { + ray_t* out_row = ray_table_get_col(result, rn); + ray_t* out_sym = ray_table_get_col(result, sn); + ray_t* out_time = ray_table_get_col(result, tn); + for (int i = 0; i < n; i++) { + valid &= ((int64_t*)ray_data(out_row))[i] == i; + valid &= ((int64_t*)ray_data(out_time))[i] == ((int64_t*)ray_data(time))[i]; + valid &= ray_read_sym(ray_data(out_sym), i, out_sym->type, out_sym->attrs) == ((int64_t*)ray_data(sym))[i]; + } + } + printf("case=%d|desc=%d|valid=%d|resolutions=%llu|ms=%.6f\n", kind, desc, valid, calls, ms); + ray_release(result); ray_release(table); ray_release(keys); + ray_release(sym); ray_release(time); ray_release(row); +#ifdef COUNT_RESOLUTIONS + valid &= calls == (kind == 1 ? 2u : 0u); +#endif + return valid; +} +int main(void) { + ray_heap_init(); ray_sym_init(); + for (int i = 0; i < 70000; i++) { + char name[40]; int n = snprintf(name, sizeof(name), "unused-constant-%d", i); + ray_sym_intern(name, n); + } + int64_t z = ray_sym_intern("used-z", 6), a = ray_sym_intern("used-a", 6); + ray_pool_init_total(3); + int valid = 1; + for (int desc = 0; desc < 2; desc++) + for (int kind = 0; kind < 3; kind++) valid &= probe(kind, desc, a, z); + ray_pool_destroy(); ray_sym_destroy(); ray_heap_destroy(); + return valid ? 0 : 1; +} diff --git a/bench/sorted_symbols/parted_symbols.rfl b/bench/sorted_symbols/parted_symbols.rfl new file mode 100644 index 000000000..d61e85160 --- /dev/null +++ b/bench/sorted_symbols/parted_symbols.rfl @@ -0,0 +1,18 @@ +;; Repeated 10k-row constant segments in a 70k-symbol FILE domain. +;; Populate the database FILE domain before writing the used symbol. Merely +;; interning unrelated runtime names would not give the file column high IDs. +(.sys.exec "rm -rf /tmp/rayforce_bench_rank_parts") +(set padding (as 'SYM (map (fn [i] (format "unused-rank-%" i)) (til 70000)))) +(.db.splayed.set "/tmp/rayforce_bench_rank_parts/2024.01.01/padding/" (table [s] (list padding))) +(set late (take [late-sorted-key] 10000)) +(.db.splayed.set "/tmp/rayforce_bench_rank_parts/2024.01.01/t/" (table [s seq] (list late (til 10000)))) +(.db.splayed.set "/tmp/rayforce_bench_rank_parts/2024.01.02/t/" (table [s seq] (list late (+ 10000 (til 10000))))) +(set parts (.db.parted.get "/tmp/rayforce_bench_rank_parts/" 't)) +(set repeats 50) +(set before (at (.sys.mem) 'sort-perpart-runs)) +(set elapsed_ms (timeit (set counts (map (fn [i] (count (select {from: parts asc: s}))) (til repeats))))) +(set streamed (- (at (.sys.mem) 'sort-perpart-runs) before)) +(set valid (and (all (== counts 20000)) (== streamed (* repeats 2)))) +(if (not valid) (raise "parted symbol benchmark did not stream correctly")) +(println (format "PARTED|%|checks=%|partitions=%" elapsed_ms repeats streamed)) +(.sys.exec "rm -rf /tmp/rayforce_bench_rank_parts") diff --git a/bench/sorted_symbols/sorted_symbols.rfl b/bench/sorted_symbols/sorted_symbols.rfl new file mode 100644 index 000000000..a5821ecd5 --- /dev/null +++ b/bench/sorted_symbols/sorted_symbols.rfl @@ -0,0 +1,19 @@ +;; One first xasc per process; set numeric to 1 for the integer control. +(set n 2630400) +(set numeric 0) +(set ids (til n)) +(set syms (asc (as 'SYM (map (fn [i] (format "s%" i)) (til 100))))) +(set ts (as 'TIMESTAMP (div ids 100))) +(set secondary (if numeric (% ids 100) (take syms n))) +(set b (table [ts sym] (list ts secondary))) +(set elapsed_ms (timeit (set sorted (xasc b [ts sym])))) +(set valid (and (== (count sorted) n) + (all (== (at sorted 'ts) ts)) + (all (== (at sorted 'sym) secondary)))) +;; A small reversed control verifies that xasc is doing real sorting. +(set control (xasc (reverse (take b 6)) [ts sym])) +(set valid (and valid (all (== (at control 'ts) (take ts 6))) + (all (== (at control 'sym) (take secondary 6))))) +(if (not valid) (raise "symbol-sort: incorrect result")) +(println (format "BENCH|%|%|%" elapsed_ms (as 'I64 valid) (count sorted))) +(println (format "META|%" (.sys.build))) diff --git a/bench/sorted_symbols/typed_runs.c b/bench/sorted_symbols/typed_runs.c new file mode 100644 index 000000000..7cfd49b51 --- /dev/null +++ b/bench/sorted_symbols/typed_runs.c @@ -0,0 +1,58 @@ +/* Whole-xasc typed-key control; construction/checks are outside timing. */ +#define _POSIX_C_SOURCE 200809L +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "lang/internal.h" +#include "core/pool.h" +#include +#include +#include +int main(int argc, char** argv) { + int participants = argc > 1 ? atoi(argv[1]) : 4; + int stamp = argc > 2 ? atoi(argv[2]) : 0; + if (participants < 1 || participants > 64 || (stamp != 0 && stamp != 1)) return 2; + ray_heap_init(); ray_sym_init(); + int64_t ids[100]; + for (int i = 99; i >= 0; i--) { + char name[32]; int n = snprintf(name, sizeof(name), "typed-%03d", i); + ids[i] = ray_sym_intern(name, (size_t)n); + } + const int64_t n = 2000000, run_rows = 20000; + ray_t* sym = ray_vec_new(RAY_SYM, n); + ray_t* time = ray_vec_new(stamp ? RAY_TIMESTAMP : RAY_I64, n); + sym->len = time->len = n; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(sym))[i] = ids[i / run_rows]; + ((int64_t*)ray_data(time))[i] = (i % run_rows - 10000) * 1000000; + } + int64_t sn = ray_sym_intern("s", 1), tn = ray_sym_intern("t", 1); + int64_t names[] = {sn, tn}; + ray_t* keys = ray_vec_from_raw(RAY_SYM, names, 2); + ray_t* table = ray_table_new(2); + table = ray_table_add_col(table, sn, sym); + table = ray_table_add_col(table, tn, time); + if (ray_pool_init_total((uint32_t)participants) != RAY_OK) return 2; + struct timespec start, finish; + clock_gettime(CLOCK_MONOTONIC, &start); + ray_t* result = ray_xasc_fn(table, keys); + clock_gettime(CLOCK_MONOTONIC, &finish); + double ms = (finish.tv_sec - start.tv_sec) * 1000.0 + (finish.tv_nsec - start.tv_nsec) / 1000000.0; + int valid = result && !RAY_IS_ERR(result) && ray_table_nrows(result) == n; + if (valid) { + ray_t* os = ray_table_get_col(result, sn); + ray_t* ot = ray_table_get_col(result, tn); + for (int64_t i = 0; i < n; i++) { + int64_t expected = (i % run_rows - 10000) * 1000000; + valid &= ray_read_sym(ray_data(os), i, os->type, os->attrs) == ids[i / run_rows]; + valid &= ((int64_t*)ray_data(ot))[i] == expected; + valid &= ((int64_t*)ray_data(sym))[i] == ids[i / run_rows]; + valid &= ((int64_t*)ray_data(time))[i] == expected; + } + } + printf("typed|participants=%d|timestamp=%d|valid=%d|ms=%.6f\n", participants, stamp, valid, ms); + ray_release(result); ray_release(table); ray_release(keys); + ray_release(sym); ray_release(time); + ray_pool_destroy(); ray_sym_destroy(); ray_heap_destroy(); + return valid ? 0 : 1; +} diff --git a/bench/sorted_symbols/unsorted_work.c b/bench/sorted_symbols/unsorted_work.c new file mode 100644 index 000000000..4556e3429 --- /dev/null +++ b/bench/sorted_symbols/unsorted_work.c @@ -0,0 +1,69 @@ +/* Default: elapsed sort time. COUNT_RESOLUTIONS: GNU ld --wrap work probe. */ +#define _POSIX_C_SOURCE 200809L +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "table/domain.h" +#include "ops/internal.h" +#include "lang/internal.h" +#include "core/pool.h" +#include +#include +#include +static _Atomic unsigned long long resolutions; +#ifdef COUNT_RESOLUTIONS +ray_t* __real_ray_sym_domain_str(ray_sym_domain_t*, int64_t); +ray_t* __wrap_ray_sym_domain_str(ray_sym_domain_t* dom, int64_t id) { + atomic_fetch_add_explicit(&resolutions, 1, memory_order_relaxed); + return __real_ray_sym_domain_str(dom, id); +} +#endif +static int probe(const char* label, int n, int late, int desc, int64_t a, int64_t z) { + ray_t* col = ray_vec_new(RAY_SYM, n); col->len = n; + int64_t* data = ray_data(col); + for (int i = 0; i < n; i++) data[i] = desc ? z : a; + /* Exactly one out-of-order value; early or beyond the leading probe. */ + data[late ? n - 2 : 0] = desc ? a : z; + int64_t name = ray_sym_intern("key", 3); + ray_t* keys = ray_alloc(0); keys->type = -RAY_SYM; keys->i64 = name; + ray_t* table = ray_table_new(1); + table = ray_table_add_col(table, name, col); + atomic_store(&resolutions, 0); + struct timespec start, finish; + clock_gettime(CLOCK_MONOTONIC, &start); + ray_t* result = desc ? ray_xdesc_fn(table, keys) : ray_xasc_fn(table, keys); + clock_gettime(CLOCK_MONOTONIC, &finish); + double ms = (finish.tv_sec - start.tv_sec) * 1000.0 + + (finish.tv_nsec - start.tv_nsec) / 1000000.0; + unsigned long long calls = atomic_load(&resolutions); + int valid = result && !RAY_IS_ERR(result) && ray_table_nrows(result) == n; + if (valid) { + ray_t* output = ray_table_get_col(result, name); + for (int i = 0; i < n; i++) { + int64_t expected = i == n - 1 ? (desc ? a : z) : (desc ? z : a); + if (ray_read_sym(ray_data(output), i, output->type, output->attrs) != expected) valid = 0; + } + } + printf("%s|desc=%d|valid=%d|resolutions=%llu|ms=%.6f\n", label, desc, valid, calls, ms); + ray_release(result); ray_release(table); ray_release(keys); ray_release(col); + return valid; +} +int main(void) { + ray_heap_init(); ray_sym_init(); + for (int i = 0; i < 60000; i++) { + char name[40]; int n = snprintf(name, sizeof(name), "unused-%d", i); + ray_sym_intern(name, n); + } + int64_t z = ray_sym_intern("used-z", 6), a = ray_sym_intern("used-a", 6); + int valid = 1; + ray_pool_init_total(5); + for (int desc = 0; desc < 2; desc++) { + valid &= probe("small", 8, 0, desc, a, z); + valid &= probe("early", 200000, 0, desc, a, z); + valid &= probe("late", 200000, 1, desc, a, z); + } + ray_pool_destroy(); ray_pool_init_total(1); + valid &= probe("serial", 200000, 0, 0, a, z); + ray_pool_destroy(); ray_sym_destroy(); ray_heap_destroy(); + return valid ? 0 : 1; +} diff --git a/bench/sorted_symbols/work_count.c b/bench/sorted_symbols/work_count.c new file mode 100644 index 000000000..908e23259 --- /dev/null +++ b/bench/sorted_symbols/work_count.c @@ -0,0 +1,32 @@ +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "table/domain.h" +#include "ops/internal.h" +#include +static unsigned long long resolutions; +ray_t* __real_ray_sym_domain_str(ray_sym_domain_t*, int64_t); +ray_t* __wrap_ray_sym_domain_str(ray_sym_domain_t* dom, int64_t id) { + resolutions++; + return __real_ray_sym_domain_str(dom, id); +} +int main(void) { + ray_heap_init(); ray_sym_init(); + for (int i = 0; i < 70000; i++) { + char name[40]; int n = snprintf(name, sizeof(name), "padding-%d", i); + ray_sym_intern(name, n); + } + int64_t id = ray_sym_intern("late-used-symbol", 16); + for (int n = 8; n <= 10000; n += 9992) { + ray_t* col = ray_vec_new(RAY_SYM, n); col->len = n; + for (int i = 0; i < n; i++) ((int64_t*)ray_data(col))[i] = id; + for (int repeat = 0; repeat < 2; repeat++) { + resolutions = 0; + int sorted = ray_key_cols_sorted(&col, 1, 0, n); + printf("rows=%d|repeat=%d|sorted=%d|resolutions=%llu\n", n, repeat, sorted, resolutions); + } + ray_release(col); + } + ray_sym_destroy(); ray_heap_destroy(); + return 0; +} diff --git a/bench/staged_strlen/.gitignore b/bench/staged_strlen/.gitignore new file mode 100644 index 000000000..9202c09b2 --- /dev/null +++ b/bench/staged_strlen/.gitignore @@ -0,0 +1,2 @@ +data/ +__pycache__/ diff --git a/bench/staged_strlen/README.md b/bench/staged_strlen/README.md new file mode 100644 index 000000000..7d3e498d2 --- /dev/null +++ b/bench/staged_strlen/README.md @@ -0,0 +1,40 @@ +# Staged grouped SYM strlen + +A narrow warm-query benchmark, not a complete engine performance gate. Requires +both binaries to support generation-2 columns (for example, dev744116d3 +and a descendant containing the staged-strlen optimization). Do not use a released gen0-only binary +as the gen2 baseline. + +The deterministic fixture has 10,000,000 rows, 997 I64 keys, and five nullable SYM +values, plus the other columns from the original six-column differential fixture. +It measures `avg(strlen(y)) by k asc k` on gen0/gen2 splayed tables. Empty symbols +are excluded from AVG's divisor. Setup writes under `bench/staged_strlen/data/`; +allow approximately 2 GiB of RAM and 1 GiB of disk. Data is retained for repeated +runs and ignored by git. Do not use this directory for application data. + +Build and preserve separate release binaries before running. From the repository +root, the optional Python 3 standard-library runner performs setup, shuffles +baseline/candidate and gen0/gen2 process order with seed 902512, and reports the +median of seven warm samples for each of three fresh processes: + +```sh +python3 bench/staged_strlen/compare.py /absolute/base /absolute/candidate --setup --cores 8 +``` + +No Python is required to execute the fixture manually: + +```sh +/absolute/base -c 8 bench/staged_strlen/setup.rfl +/absolute/base -c 8 bench/staged_strlen/gen0.rfl +/absolute/base -c 8 bench/staged_strlen/gen2.rfl +/absolute/candidate -c 8 bench/staged_strlen/gen0.rfl +/absolute/candidate -c 8 bench/staged_strlen/gen2.rfl +``` + +Each timed process loads its table and evaluates the query once before timing. +The checksum is only a rendered sanity check; use the regression/differential +suite for answer and type equivalence. Run without concurrent builds/tests, +record binary/compiler/CPU details, and do not interpret these as cold-read, +writer, high-cardinality, or general speedup measurements. The main CLI takes +`-c N` for total participants. `RAYFORCE_CORES` in the harness or embedding +runtime counts background workers, with the main thread additional. diff --git a/bench/staged_strlen/compare.py b/bench/staged_strlen/compare.py new file mode 100644 index 000000000..9fa1a123d --- /dev/null +++ b/bench/staged_strlen/compare.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Optional standard-library runner; execute after building two release binaries.""" +import argparse +import json +from pathlib import Path +import random +import re +import statistics +import subprocess + +parser = argparse.ArgumentParser(__doc__) +parser.add_argument("base", type=Path) +parser.add_argument("candidate", type=Path) +parser.add_argument("--cores", type=int, default=8) +parser.add_argument("--trials", type=int, default=3) +parser.add_argument("--setup", action="store_true") +args = parser.parse_args() +if args.cores < 1 or args.trials < 1: + parser.error("cores and trials must be positive") +root = Path(__file__).resolve().parents[2] +executables = {"base": args.base.resolve(), "candidate": args.candidate.resolve()} + +def run(executable, script): + return subprocess.run([str(executable), "-c", str(args.cores), str(script)], + cwd=root, stdin=subprocess.DEVNULL, text=True, + capture_output=True, check=True).stdout + +if args.setup: + print(run(executables["base"], root / "bench/staged_strlen/setup.rfl"), flush=True) +tasks = [(i, name, gen) for i in range(args.trials) + for name in executables for gen in (0, 2)] +random.Random(902512).shuffle(tasks) +results = [] +for trial, name, gen in tasks: + stdout = run(executables[name], root / f"bench/staged_strlen/gen{gen}.rfl") + checksum = re.search(r"^checksum: (.+)$", stdout, re.M) + times = re.search(r"^ms: \[(.+)\]$", stdout, re.M) + if not checksum or not times: + raise RuntimeError(f"unexpected output: {stdout!r}") + values = [float(v) for v in times.group(1).split()] + if len(values) != 7: + raise RuntimeError(f"expected seven timings, got {values!r}") + results.append(dict(trial=trial, binary=name, gen=gen, ms=values, + median_ms=statistics.median(values), checksum=checksum.group(1))) +# A rendered checksum is only a quick sanity check, not answer/bitwise equivalence. +if len({r["checksum"] for r in results}) != 1: + raise RuntimeError("checksums differ; investigate answers before comparing timings") +print(json.dumps(results, indent=2), flush=True) +for name in executables: + for gen in (0, 2): + medians = [r["median_ms"] for r in results if r["binary"] == name and r["gen"] == gen] + print(f"{name} gen{gen}: trial medians={medians}, median={statistics.median(medians):.3f} ms") diff --git a/bench/staged_strlen/gen0.rfl b/bench/staged_strlen/gen0.rfl new file mode 100644 index 000000000..3e6ae2222 --- /dev/null +++ b/bench/staged_strlen/gen0.rfl @@ -0,0 +1,4 @@ +(set X (.db.splayed.get "bench/staged_strlen/data/s0/" "bench/staged_strlen/data/s0.sym")) +(set result (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) +(println "checksum: %" (sum result)) +(println "ms: %" (list (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)))) diff --git a/bench/staged_strlen/gen2.rfl b/bench/staged_strlen/gen2.rfl new file mode 100644 index 000000000..0a5833b8c --- /dev/null +++ b/bench/staged_strlen/gen2.rfl @@ -0,0 +1,4 @@ +(set X (.db.splayed.get "bench/staged_strlen/data/s2/" "bench/staged_strlen/data/s2.sym")) +(set result (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) +(println "checksum: %" (sum result)) +(println "ms: %" (list (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)) (timeit (at (select {a: (avg (strlen y)) from: X by: k asc: k}) 'a)))) diff --git a/bench/staged_strlen/setup.rfl b/bench/staged_strlen/setup.rfl new file mode 100644 index 000000000..4db6f5d85 --- /dev/null +++ b/bench/staged_strlen/setup.rfl @@ -0,0 +1,7 @@ +;; Run from the repository root. Creates only this benchmark fixture. +(.sys.exec "mkdir -p bench/staged_strlen/data") +(set i (+ 0 (til 10000000))) +(set s (at ["" "alpha" "bb" "cccccc" "a longer repeated string"] (% i 5))) +(set T (table [i k v f s y] (list i (% i 997) (at [0N -7 1 99 1234] (% i 5)) (at [-0.0 0.0 0Nf 2.5 -3.25] (% i 5)) s (as 'SYM s)))) +(println "splayed gen0 writer_ms: %" (timeit (.db.splayed.set "bench/staged_strlen/data/s0/" T "bench/staged_strlen/data/s0.sym" {compress: false}))) +(println "splayed gen2 writer_ms: %" (timeit (.db.splayed.set "bench/staged_strlen/data/s2/" T "bench/staged_strlen/data/s2.sym" {compress: true}))) diff --git a/bench/time_key_width/README.md b/bench/time_key_width/README.md new file mode 100644 index 000000000..ed8b09967 --- /dev/null +++ b/bench/time_key_width/README.md @@ -0,0 +1,64 @@ +# `(SYM,TIME)` order-check cost + +This native **internal** helper benchmark measures `ray_key_cols_sorted`, not +whole-query or full-sort latency. It constructs2M already-ordered rows in100 +symbol groups before timing. TIME values use int32 cells; the I64 control uses +values outside int32 range. Result eligibility and both complete source buffers +are checked after timing. The pool is created before timing. + +```sh +make -j4 lib +clang -std=c17 -O3 -march=native -DNDEBUG -Iinclude -Isrc \ + bench/time_key_width/scan.c librayforce.a -rdynamic -lpthread -lm -ldl \ + -o /tmp/time-key-check +RAYFORCE_CORES=0 taskset -c 0 /tmp/time-key-check time asc +RAYFORCE_CORES=0 taskset -c 0 /tmp/time-key-check i64 asc +RAYFORCE_CORES=0 taskset -c 0 /tmp/time-key-check time desc +RAYFORCE_CORES=3 taskset -c 0,1,2,3 /tmp/time-key-check time asc +``` + +Choose allowed logical CPUs on your host. The environment counts **background +helpers**, not total participants; actual worker participation is not measured. +Use the same compiler/flags/base on both sides and no overlapping builds/tests. + +## Historical pre-#937 observation (`a9217925`) + +The reference is the **correct generic fallback** (remove TIME from the i64 +shortcut), not the old wrong-width kernel. Both reference and proposal include +accepted938's append changes. Ubuntu24/i7-6700/Clang18 project optimized flags; +one pinned logical CPU without helpers, first four allowed logical CPUs with3 +helpers. Shared host/governor not isolated. One discarded fresh process per +variant/case, then five randomized fresh processes: + +| TIME ascending,2M rows | correct generic, median ms | correct int32, median ms | +|---|---:|---:| +| no background helpers |16.086|3.775| +|3 background helpers |4.907|1.952| + +Do not interpret these as speedups over the old wrong answer or as full-sort +improvements. Descending still uses generic comparison; no new descending lane +is claimed. An initial five-sample I64 control was noisy (3.460/4.947ms, proposed +range3.422–7.998). A **16-fresh-process unchanged-code repeat** gave3.562/3.490ms +with overlapping ranges. Retain that limitation rather than claiming a universal +no-regression result. The tests check semantics, not a flaky wall-time threshold. + +## Integration with #937 + +The shared probe and worker now instantiate the same loop for TIME/int32 and +I64/TIMESTAMP/int64. The type choice remains outside rows; only unequal SYM +boundaries spend the rank-preparation comparison budget. The direct unranked +helper is serial after #937 even when background helpers are configured: do not +reuse the historical three-helper timings as current parallel performance. + +A new matched Clang18/current-dev-D715 common archive comparison replaced only +the immutable sort object. TIME ascending remains compared against a **correct +generic** reference, never the incorrect 64-bit read. One discarded warm process +per cell followed by eight randomized fresh processes: TIME ascending14.502→ +3.850ms; descending14.510→14.551ms with overlapping ranges. Both at zero helpers. +Whole-xasc I64 controls were22.643→22.939ms(1participant),22.552→22.914(4); +TIMESTAMP22.741→22.923 and22.578→22.827. All control ranges overlap; small +median increases remain disclosed rather than claiming universal neutrality. +There were108validated processes total(12warm/96measured). Output values and +source buffers were checked outside timing; requested participants do not prove +physical worker participation. This is a single-sort-TU/common-library study, +not a newly built whole-candidate release or an end-to-end ClickBench result. diff --git a/bench/time_key_width/scan.c b/bench/time_key_width/scan.c new file mode 100644 index 000000000..b97c52b61 --- /dev/null +++ b/bench/time_key_width/scan.c @@ -0,0 +1,17 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include "ops/internal.h" +#include "core/pool.h" +#include +#include +#include +#include +static double now(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec+t.tv_nsec*1e-9;} +int main(int argc,char**argv){ + if(argc!=3)return 2;int64_t n=2000000,per=n/100;int wide=!strcmp(argv[1],"i64"),desc=!strcmp(argv[2],"desc");ray_runtime_t*rt=ray_runtime_create(0,NULL);if(!rt)return 3;ray_pool_t*pool=ray_pool_get();unsigned configured=pool?ray_pool_total_workers(pool):1; + int64_t names[100];for(int i=0;i<100;i++){char s[32];int l=snprintf(s,sizeof s,"scan-sym-%04d",i);names[i]=ray_sym_intern(s,l);} + int64_t*ids=malloc((size_t)n*8);void*raw=malloc((size_t)n*(wide?8:4));if(!ids||!raw)return 4;for(int64_t i=0;ilen!=n)return 5; + double start=now();bool ordered=ray_key_cols_sorted(cols,2,(uint8_t)desc,n);double ms=(now()-start)*1000.0;if(!ordered||memcmp(ray_data(cols[0]),ids,(size_t)n*8)||memcmp(ray_data(cols[1]),raw,(size_t)n*(wide?8:4)))return 6; + printf("kind=%s direction=%s configured=%u n=%lld ms=%.9f valid=1\n",argv[1],argv[2],configured,(long long)n,ms);ray_release(cols[0]);ray_release(cols[1]);free(ids);free(raw);ray_runtime_destroy(rt);return 0; +} diff --git a/docs/docs/architecture/memory.md b/docs/docs/architecture/memory.md index 57d72c3ae..a7a3bdf89 100644 --- a/docs/docs/architecture/memory.md +++ b/docs/docs/architecture/memory.md @@ -89,7 +89,7 @@ Pools are normally backed by anonymous `mmap` — fast, lazy-committed by the ke The fallback is transparent to every `ray_alloc` caller. Pages never written stay as holes in the sparse backing file, so the over-allocate-and-trim alignment trick costs zero real disk space; only the pages you actually touch consume disk pages. On heap teardown the fd is closed and the tempfile is unlinked, so the swap directory doesn't accumulate orphans. - **Configurable swap directory.** The directory is resolved as `RAY_HEAP_SWAP` → `TMPDIR` → `/tmp`. `/tmp` is the default rather than the working directory, which may be read-only or shared. Trailing slash is added automatically. The chosen directory must exist and be writable by the running process. -- **Tempfile naming.** Format is `rayheap___.dat`. Files are opened `O_EXCL` so no clashes between concurrent processes; the counter is per-process atomic so no clashes within a process. +- **Tempfile naming.** Pools use `rayheap___.dat`, direct blocks `raydirect___.dat`. The pid keeps processes of one PID namespace apart, and the counter is a per-process atomic. Files are opened `O_EXCL`, so a name that already exists fails that allocation rather than sharing the file. - **POSIX only today.** The fallback path uses `open` / `ftruncate` / `mmap MAP_SHARED` / `munmap` / `unlink`. Windows pools currently take only the anonymous `VirtualAlloc` path. - **Distinct from block offloading.** Block offloading (see [Block Offloading](offloading.md)) streams pre-existing parted-table data through queries one segment at a time. The file-backed pool fallback handles fresh anonymous allocations that exceed RAM. Both let workloads exceed RAM, but at different layers and for different shapes of work. diff --git a/docs/docs/architecture/offloading.md b/docs/docs/architecture/offloading.md index 26e8f2ea0..020a128de 100644 --- a/docs/docs/architecture/offloading.md +++ b/docs/docs/architecture/offloading.md @@ -140,9 +140,32 @@ The following operations are safe for segment streaming. All other operations tr When adding new element-wise operations to Rayforce, they must be added to the `op_streamable()` whitelist in `exec.c` to participate in segment streaming. +## Per-Partition Sort, Take and Asof + +Three routes run a `select` over a parted table one partition at a time and merge the results, counted in `.sys.mem`: + +- **Sorted partitions** (`sort-perpart-runs`): `asc:` or `desc:` on bare columns, without `by:` or `take:`, when every partition is sorted on the keys and their key ranges follow each other; the partitions' results are concatenated. +- **Top-k** (`sort-perpart-runs`): `asc:`/`desc:` with a positive `take:`; each partition yields its own top `k`, and one more sort over those candidates gives the result. +- **Asof operands** (`asof-perpart-runs`): a `(select {from: parted …})` operand of `asof-join` without `by:`, `take:`, `asc:`, `desc:` or `nearest:` is joined day by day. + +On the two sort routes every output must be a bare column that no lambda parameter or `let` of its name hides. A `where:`, and on the asof route every projection too, runs on a partition only when the DAG streams it: the clause is compiled as a query expression and must pass the streamable-operations check above. What streams: + +- row-wise operations over the columns (the table above), `if`, `within` with constant or row-wise bounds; +- scalar constants: literals, and lambda parameters, `let`s and globals holding an atom; +- the set of `in`/`not-in` when it is a constant (a membership list, of any length); +- a call of a single-expression helper whose body is any of these in its parameters, named or written inline. + +What falls back to the flat path (the whole table in memory, the same answer): + +- a vector held by a lambda parameter, a `let` or a global, of any length (a mask, a projected vector), and anything computed to the table's or a partition's length (`til`, a helper returning a vector, a nested `select`); +- aggregates, scans and windows (`avg`, `sums`, `deltas`, `fills`), also inside a helper or through a chain of helpers; +- the set of `in`/`not-in` computed from columns; +- forms the compiler does not lower: `rand`, `eval`, the clock functions `date`, `time` and `timestamp`, a computed callee, a closure, a path into a dict or table (`c.lo`, `(at c 'lo)`), a lookup `(at d x)`, `sym-name`, a cast to `STR`, elementwise `min`/`max`, `bin`/`binr`, `find`, `map`/`pmap`; +- a clause that reads no column and is not one scalar constant. + ## Current Limitations -- **No streaming for aggregations, sorts, or joins** — these operations require seeing all data at once (or specialized merge logic). They fall back to loading all partitions into memory. This will be addressed in a future release with operator-aware merge functions. +- **Aggregations, joins and other sorts** need seeing all data at once or specialized merge logic. Outside the per-partition routes they fall back to loading all partitions into memory. - **Pruning requires literal constants** — the partition pruning pass only handles comparisons against literal values (e.g., `date > 2024.01.01`), not computed expressions (e.g., `date > (today - 30)`). - **Single partition column** — pruning works on the single partition key inferred from directory names. Multi-column partition keys are not supported. - **Thread-local memory pressure** — `ray_mem_pressure()` only reads the calling thread's heap statistics, not the global total across all worker threads. It is not currently used in the streaming hot path. diff --git a/docs/docs/architecture/pipeline.md b/docs/docs/architecture/pipeline.md index a2a8f438a..0ca8aba2d 100644 --- a/docs/docs/architecture/pipeline.md +++ b/docs/docs/architecture/pipeline.md @@ -47,7 +47,7 @@ Key design decisions: - **32-byte alignment** — nodes are allocated from a contiguous array in the `ray_graph_t`, keeping the DAG hot in L1 cache during optimization walks. - **At most 2 inputs** — binary operations use both; unary ops use `inputs[0]` only; sources have both NULL. - **Flags** — `OP_FLAG_DEAD` marks nodes removed by DCE. -- **est_rows** — populated by the type inference pass and used by filter reorder and join planning. +- **est_rows** — an advisory row-count estimate populated by type inference. It is not the selectivity key used by the current filter-reorder pass. ### ray_op_ext_t — Extended Node @@ -115,7 +115,11 @@ Pushes `OP_FILTER` nodes closer to data sources by walking the DAG up to four ti ### 7. Filter Reorder -When multiple filter predicates are chained, reorders them by estimated selectivity (most selective first). Uses the `est_rows` from type inference to estimate selectivity. More selective filters run first, reducing the number of rows processed by subsequent filters. +Splits and reorders only predicates whose complete resolved expression trees are proved invariant under an order-preserving restriction of the same default-source rows. Both the query front end's AND constructor and the optimizer apply this check before turning a conjunction into sequential filters. An aggregate or running expression cannot acquire an earlier conjunct's survivors as its input merely because that conjunct was cheaper. This is distinct from a final SELECT aggregate, which legitimately consumes the rows selected by WHERE. + +The proof checks scalar/row shapes, source identity and hidden operands, not merely whether a predicate contains a scan or produces a scalar. General captured row vectors are refused; fixed typed membership sets have a separate operand role. Unsupported shapes and the bounded analysis limits (4096 graph nodes, depth64) decline the optimization, not the language expression. An unproved predicate is a reorder barrier. Established input/default-table correspondence and the existing GROUP, pushed-filter and shared-consumer restrictions are still required; this expression proof alone does not justify arbitrary structural-input or no-compaction rewrites. It proves value invariance, not general exception or OOM ordering equivalence. + +Within an eligible run, static selectivity classes derived from opcode, operand type and constant presence dominate a coarse per-row cost score. Wide constant equality/membership is ranked ahead of neutral shapes; neutral predicates are ordered by cost. SYM equality remains neutral because the logical type alone does not reveal dictionary cardinality. These are static heuristics, not measured selectivities or an `est_rows`-based cost model. ### 8. Projection Pushdown @@ -165,7 +169,7 @@ Element-wise operation subtrees are compiled to flat bytecode at **execution tim - **Registers**: up to 16 slots (`EXPR_MAX_REGS`), each holding a typed lane — `REG_SCAN` (column slice), `REG_CONST` (broadcast scalar), or `REG_SCRATCH` (computed intermediate). - **Instructions**: up to 48 opcodes (`EXPR_MAX_INS`) covering arithmetic, comparisons, casts, and logical operations. - **Morsel evaluation**: the compiled program is evaluated one morsel at a time (1024 rows) in per-worker, arena-allocated scratch buffers. No full-length intermediate vectors are materialized. -- **Parallelism**: subtrees covering ≥ 65,536 rows (`RAY_PARALLEL_THRESHOLD`) are dispatched across worker threads, each thread processing its own morsel slice independently. +- **Parallelism**: eligible compiled subtrees can dispatch data-parallel ranges across worker threads, each processing its own morsel slice. A common minimum is 65,536 rows (`RAY_PARALLEL_THRESHOLD`); the chosen operator, available workers and dispatch-safety guards also determine whether work runs in parallel. This does not parallelize arbitrary Rayfall callbacks. - **Parted-segment aware**: for partitioned tables, column pointers are rebound per segment at evaluation time — zero-copy, no gather. **Null handling.** Nullable integer columns are sentinel-normalized at morsel load: `NULL_I32`/`NULL_I16` are widened to `NULL_I64` in `i64` lanes, or to `NaN` in `f64` lanes. Per-instruction null-aware kernel variants are selected at compile time (sentinel-checking `i64` arithmetic and comparisons, sentinel-mapping casts). F64 `NaN`-nulls propagate through arithmetic natively. Output vectors carry `RAY_ATTR_HAS_NULLS` conservatively. Null-free programs compile to the identical instruction stream as non-nullable inputs — no null checks on the fast path. @@ -199,10 +203,14 @@ This three-tier scheme means that fully-passing or fully-failing morsels (which ### Thread Pool -Rayforce uses a global thread pool (`ray_pool_t`) for parallel execution. Queries with more than `RAY_PARALLEL_THRESHOLD` (64 * 1024 = 65,536) elements are dispatched across worker threads. Each thread processes `RAY_DISPATCH_MORSELS` (8) morsels at a time to amortize scheduling overhead. +Rayforce uses a global thread pool (`ray_pool_t`) for eligible vector builtins and query operators. Many kernels use `RAY_PARALLEL_THRESHOLD` (64 * 1024 = 65,536) elements as a minimum and batch `RAY_DISPATCH_MORSELS` (8) morsels to amortize scheduling overhead. Eligibility and dispatch geometry are operator-specific; worker availability and safety guards (including avoiding nested dispatch) can keep work serial even above a size threshold. + +This is **kernel parallelism**, not automatic parallel evaluation of language functions. `map` and `pmap` currently invoke their callbacks sequentially on the caller's VM; `pmap` is an alias for `map`. A builtin or query inside a callback may itself use eligible parallel kernels. Increasing `-c` does not turn an interpreted parameter sweep into concurrent lambda calls. See [Higher-order functions](../language/math.md#pmap-f-x) and [Multiple Instances](../guides/instances.md). Each dispatch splits its tasks into one contiguous range per worker (the main thread included); a worker runs its range in order and, once it is empty, steals half of another worker's remaining range from the tail, so an idle thread never waits on a busy one and the rows a worker touches are sequential. Tasks of one dispatch may therefore run in any order and on any worker: operators place results by task index, and any early stop (a `take:` cutoff, a top-N bound) is derived from row positions or values, never from "the earlier tasks have run". The scheduler is selected once at pool creation (`RAY_POOL_STEAL`, default `1`; `0` restores the shared claim cursor for A/B comparison) and `RAY_POOL_TRACE=1` prints the own-versus-stolen task histogram per worker to stderr at pool destroy; see [REPL Reference](../language/repl.md#environment-variables). +The default pool has one thread per CPU of the process affinity mask (Linux; the online CPU count elsewhere), or per CPU of a cgroup CPU quota, rounded up, when that is smaller. Threads are not tied to CPUs: the scheduler places them within the mask. + ### Radix-Partitioned Hash Join Hash joins use adaptive radix partitioning to ensure each partition's hash table fits in L2 cache. The number of radix bits adapts between `RAY_JOIN_MIN_RADIX` (2, producing 4 partitions) and `RAY_JOIN_MAX_RADIX` (14, producing 16K partitions) based on input size, targeting a per-partition working set of `RAY_JOIN_L2_TARGET` (256 KB). diff --git a/docs/docs/c-api/core.md b/docs/docs/c-api/core.md index 603f9c4ba..353b5d2d1 100644 --- a/docs/docs/c-api/core.md +++ b/docs/docs/c-api/core.md @@ -1,7 +1,17 @@ # Core C API Reference !!! note "Headers" - Include `` for the bulk of the public API. A few internal helpers documented here live in their own headers — in particular `ray_cow` and the `ray_heap_init` / `ray_heap_destroy` lifecycle calls are declared in `"mem/heap.h"`, not in ``. Link against `librayforce.a` (static) or `librayforce.so` (shared). No external dependencies. + Include `` for the bulk of the public API. A few internal helpers documented here live in their own headers — in particular `ray_cow` and the `ray_heap_init` / `ray_heap_destroy` lifecycle calls are declared in `"mem/heap.h"`, not in ``. The Makefile builds the static archive `librayforce.a`; it does not provide a shared-library target. On Linux, link the archive with `-Wl,--gc-sections -lm -lpthread` so the linker can discard unused function and data sections. + +## Floating-point environment for compressed columns + +Generation-2 compressed F32/F64 I/O requires **default floating-point controls** on every calling/executing thread: round-to-nearest (`FE_TONEAREST`), masked FP exceptions, and gradual underflow (FTZ and DAZ disabled). Embedders must maintain those controls during calls. Rayforce does not silently change or normalize them; sticky exception status flags need not be clear and arithmetic may set them. Detected unsupported controls produce `fpenv` (`RAY_ERR_FPENV` in C), not a corruption error. Restore supported controls before retrying the same mapped column; an environment failure is transient, not permanently cached. + +The refusal applies conservatively to compressed float writes and whole-column materialization, including decoded-cache hits and non-ALP encodings. ALP range decoding also checks the executing thread. It does not change the file format or require every non-ALP range read to reject nondefault controls. + +Detection is deliberately limited: standard rounding is checked, plus SSE rounding, FTZ/DAZ and exception masks on supported x86 SSE builds. This is **not a complete portable FP-environment validator**: x87 trap masks are not checked, and on other native architectures only standard rounding is checked. WebAssembly has fixed nearest rounding. Maintaining other required controls remains the embedder's responsibility; passing a check is not proof that every control is supported. + +Use `ray_table_col` / `ray_table_col_idx` to obtain an owned `RAY_ERROR` on a failed materialization (free it with `ray_error_free`). The older `ray_table_get_col` / `ray_table_get_col_idx` getters collapse decode errors to `NULL`. Successful plain columns returned by these getters are borrowed from the table. Enum-returning save APIs report `RAY_ERR_FPENV`; reconstructing it with `ray_error(ray_err_code_str(err), NULL)` supplies the default explanation. ## Lifecycle diff --git a/docs/docs/c-api/dag.md b/docs/docs/c-api/dag.md index 798099e15..3cee93353 100644 --- a/docs/docs/c-api/dag.md +++ b/docs/docs/c-api/dag.md @@ -94,7 +94,7 @@ ray_op_t* price_f = ray_cast(g, ray_scan(g, "price"), RAY_F64); ## Binary Operations -Element-wise binary operations. All are fuseable into morsel passes. +Eligible element-wise binary operations can fuse into morsel passes. | Function | Opcode | Description | |---|---|---| @@ -117,6 +117,16 @@ Element-wise binary operations. All are fuseable into morsel passes. | `ray_min2(g, a, b)` | `OP_MIN2` | Element-wise minimum | | `ray_max2(g, a, b)` | `OP_MAX2` | Element-wise maximum | +Equality constructors can return `NULL` when a known SYM operand is paired +with a non-SYM/non-STR or unknown logical type. Symbol IDs are not numeric +comparison values. This is a **construction decline**, not an allocated +language error: query compilation can fall back to the evaluator, preserving +value-sensitive null behavior. Direct C callers must check the constructor +result before passing it to filters, optimization or execution. String literals +retain their text identity even when execution metadata uses SYM. Symbol/text +pairs are not rejected by this gate; their existing operand-shape checks still +apply at execution. + ### ray_if Ternary conditional: for each element, returns `then_val` where `cond` is true, `else_val` otherwise. diff --git a/docs/docs/data-types/index.md b/docs/docs/data-types/index.md index ac0d432d4..58cd2e345 100644 --- a/docs/docs/data-types/index.md +++ b/docs/docs/data-types/index.md @@ -13,17 +13,20 @@ All scalar types, their internal constants, storage sizes, and Rayfall literal s | **Short integer** | `RAY_I16` | 3 | 2 bytes | `0Nh` | Small integers | | **Integer** | `RAY_I32` | 4 | 4 bytes | `0Ni` | `42i` | | **Long integer** | `RAY_I64` | 5 | 8 bytes | `0Nl` | `42` | -| **Single float** | `RAY_F32` | 6 | 4 bytes | sentinel | — | +| **Single float** | `RAY_F32` | 6 | 4 bytes | `0Ne` | `1.5e` | | **Double float** | `RAY_F64` | 7 | 8 bytes | `0Nf` | `3.14` | | **Date** | `RAY_DATE` | 8 | 4 bytes | `0Nd` | `2024.01.15` | | **Time** | `RAY_TIME` | 9 | 4 bytes | `0Nt` | `09:30:00.000` | | **Timestamp** | `RAY_TIMESTAMP` | 10 | 8 bytes | `0Np` | `2024.01.15D09:30:00.000000000` | -| **GUID** | `RAY_GUID` | 11 | 16 bytes | all-zero GUID | UUID format | -| **Symbol** | `RAY_SYM` | 12 | Adaptive (8/16/32/64-bit) | none | `'AAPL`, `[AAPL GOOG]` | -| **String** | `RAY_STR` | 13 | 16 bytes per element | none | `"hello"` | +| **GUID** | `RAY_GUID` | 11 | 16 bytes | `0Ng` (the all-zero GUID) | `(as 'GUID "...")` | +| **Symbol** | `RAY_SYM` | 12 | Adaptive (8/16/32/64-bit) | `'` (empty symbol) | `'AAPL`, `[AAPL GOOG]` | +| **String** | `RAY_STR` | 13 | 16 bytes per element | `""` (empty string) | `"hello"` | +| **Timespan** | `RAY_TIMESPAN` | 16 | 8 bytes | `0Nn` | `1D`, `0D01:00:00.000000000` | + +TIMESPAN is a signed nanosecond duration. See [duration syntax, arithmetic, and migration](../guides/timespan.md). Internal tags 14 and 15 remain reserved. !!! note "Null handling" - Nulls are sentinel-encoded directly in the data array (`INT64_MIN` for `i64`, `NaN` for `f64`, the type-correct reserved value otherwise), not a separate bitmap; the `HAS_NULLS` attribute is a fast "may contain nulls" hint. Parseable null literals are `0Nh` (i16), `0Ni` (i32), `0Nl` (i64), `0Nf` (f64), `0Nd` (date), `0Nt` (time), and `0Np` (timestamp). `RAY_BOOL`, `RAY_U8`, `RAY_SYM`, and `RAY_STR` have no distinct null value. Use `nil?` to test for null. + Nulls are sentinel-encoded directly in the data array (`INT64_MIN` for `i64`, `NaN` for `f64`, the type-correct reserved value otherwise), not a separate bitmap; the `HAS_NULLS` attribute is a fast "may contain nulls" hint. Parseable null literals are `0Nh` (i16), `0Ni` (i32), `0Nl` (i64), `0Nf` (f64), `0Ne` (f32), `0Ng` (guid), `0Nd` (date), `0Nt` (time), `0Np` (timestamp), and `0Nn` (timespan). `RAY_BOOL` and `RAY_U8` have no null value. `RAY_SYM`'s null is the empty symbol `'` and `RAY_STR`'s is the empty string `""`: `(nil? ')` and `(nil? "")` are `true`. Use `nil?` to test for null. !!! note "Note" RAY_SYM and RAY_STR are both string types but serve different purposes. Symbols are dictionary-encoded (interned integers) — ideal for categorical data with repeated values like stock tickers or country codes. Strings are variable-length and stored inline or in a pool — ideal for free-form text. @@ -124,11 +127,11 @@ ray> (as 'DATE "2024.01.15") | From | To | Notes | |---|---|---| -| Any numeric | Any numeric | Widening is lossless; narrowing truncates | +| Any numeric | Any numeric | Widening is lossless; narrowing truncates; F64 → F32 saturates past the F32 range | | BOOL | I64, F64 | `true` → 1, `false` → 0 | | I64, F64 | BOOL | Non-zero → `true` | | Any scalar | STR | Formatted string representation | -| STR | I64, F64, DATE, TIME, TIMESTAMP | Parsed from standard format | +| STR | I64, F32, F64, DATE, TIME, TIMESTAMP | Parsed from standard format | | SYM | STR | Resolves interned string | | STR | SYM | Interns the string | | DATE | TIMESTAMP | Midnight on that date | @@ -140,7 +143,7 @@ Rayforce has three temporal types with different precision and epoch conventions ### RAY_DATE -Stored as a 32-bit signed integer counting **days since 2000.01.01**. This gives a range of roughly 5.8 million years in either direction. +Stored as a 32-bit signed integer counting **days since 2000.01.01**. This gives a range of roughly 5.8 million years in either direction. A result past that range keeps its low 32 bits, the same for an atom and for a vector cell. ```lisp ray> 2024.01.15 @@ -153,7 +156,7 @@ ray> (+ 2024.01.15 30) ### RAY_TIME -Stored as a 32-bit signed integer counting **milliseconds since midnight**. Range covers a full day (0 to 86,399,999 ms). +Stored as a 32-bit signed integer counting **milliseconds since midnight**. A time of day uses 0 to 86,399,999 ms, but values past 24 hours and negative values are valid, up to about ±596 hours (±2^31 ms). A result past that range keeps its low 32 bits, the same for an atom and for a vector cell: `(* 25 24:00:00.000)` is `-593:02:47.296`. ```lisp ray> 09:30:00.000 diff --git a/docs/docs/getting-started/quick-start.md b/docs/docs/getting-started/quick-start.md index 143da2053..e62a98409 100644 --- a/docs/docs/getting-started/quick-start.md +++ b/docs/docs/getting-started/quick-start.md @@ -6,7 +6,8 @@ Build Rayforce from source, start the Rayfall REPL, and run your first query in Rayforce is a pure C library with zero external dependencies. You need: -- A **C compiler** — GCC 7+ or Clang 6+ +- A **C compiler** — Clang 6+ or GCC 7+. `make` uses `clang` when `CC` is not set; + `make CC=gcc` (or `CC=gcc` in the environment) builds with GCC - **GNU Make** - **POSIX environment** (Linux, macOS, WSL) diff --git a/docs/docs/guides/analytics.md b/docs/docs/guides/analytics.md index 2f891f218..bd117dfc2 100644 --- a/docs/docs/guides/analytics.md +++ b/docs/docs/guides/analytics.md @@ -347,15 +347,16 @@ Null literals are type-suffixed: `0Nl` (i64), `0Nf` (f64), `0Nd` (date), `0Nt` ( - **Prefer `select` with `by:`** over manual group-then-map. The `select` pipeline fuses grouping and aggregation into a single pass, avoiding intermediate materialization. - **Use `xbar` for time bucketing** to bin timestamps into fixed intervals (e.g., 5-minute bars). This avoids materializing group keys and is faster than building date groups by hand. - - **Use `pmap` for embarrassingly parallel work.** It distributes a function across list elements using worker threads. Ideal for independent per-group transformations: + - **Express column work with vector builtins and queries.** Eligible kernels can use the morsel-driven pool; scheduling depends on the operator, input size and available workers. For example, squaring a vector does not require a callback per element: ```lisp - (pmap (fn [x] (* x x)) (list 1 2 3 4 5)) + (set x [1 2 3 4 5]) + (* x x) ; [1 4 9 16 25] ``` - ```text - (1 4 9 16 25) - ``` + This small example may run serially. See [Thread Pool](../architecture/pipeline.md#thread-pool) for the distinction between kernel parallelism and language evaluation. + + - **Do not use `pmap` as a parallel task scheduler.** It is currently a sequential alias for `map`, including for large inputs and expensive lambdas. Builtins inside a callback may use workers independently, but the callback invocations themselves remain sequential. For independent backtest configurations or other Rayfall task sweeps, use separate processes with an explicit per-process worker budget; see [Multiple Instances](instances.md). ## Next Steps diff --git a/docs/docs/guides/datalog-reference.md b/docs/docs/guides/datalog-reference.md index 27f1aad35..64adc0918 100644 --- a/docs/docs/guides/datalog-reference.md +++ b/docs/docs/guides/datalog-reference.md @@ -385,6 +385,8 @@ For advanced use cases, Rayforce provides a programmatic Datalog API that gives | `(dl-query prog 'pred)` | Retrieve the result table for a predicate | | `(dl-provenance prog 'pred)` | Reserved provenance hook; currently returns `domain: not available` | +A program handle owns its program and is released automatically when its binding is replaced or leaves scope. Call `(dl-free prog)` when you want to release it earlier; a later automatic release is safe. + ### Example ```lisp diff --git a/docs/docs/guides/errors.md b/docs/docs/guides/errors.md index f202861a0..0fc24529a 100644 --- a/docs/docs/guides/errors.md +++ b/docs/docs/guides/errors.md @@ -133,10 +133,10 @@ Any error you create with `raise`: ```text (raise "custom error message") -; error: domain +; error: domain: custom error message ``` -Internally, `raise` stores your value and triggers a domain error. The `try` handler receives the stored value. +Internally, `raise` stores your value and triggers a domain error. The `try` handler receives the stored value. When nothing catches it, the REPL, the script runner and a timer callback print the value after the code: a string as is, a table as `
`, anything else in the REPL's display form, cut with `..` when long. ### Access Errors (Restricted Mode) diff --git a/docs/docs/guides/indexes.md b/docs/docs/guides/indexes.md index 975f7bb1f..652e6ff05 100644 --- a/docs/docs/guides/indexes.md +++ b/docs/docs/guides/indexes.md @@ -24,6 +24,32 @@ Suited to "does this value exist in the column" / "which row(s) hold this value" **Wired today:** filter EQ (integer-family, null-free columns), filter IN, find. Float equality and null-bearing columns fall back to the scan. +### Hash indexes built after repeated lookups + +Converted tables persist chunk zones and string dictionaries, not hash +indexes. When an equality filter, or an `in` filter with a small set of +integers, meets an 8-byte integer or timestamp column whose chunk zone cannot +prune (values spread over the whole range in every chunk), the filter scans. +Narrower columns are never indexed this way: their index would cost more than +five times their data. A key outside the column's whole value range is +answered by the zone alone, without a scan. + +Once the same column has been scanned this way often enough to pay for an +index (about 320 lookups, since one build costs roughly as much as that many +scans), the engine builds a hash index for it in memory and reuses it for +later filters in the same process. Compressed columns are covered too: the +index is built from the decoded column. It is never written to disk and never +changes the table's column (`.idx.info` still reports its zone). Scans, +aggregates and range filters never count towards a build. + +The memory it holds is bounded by a quarter of the RAM the process may use +(physical memory, or the container's memory limit when that is smaller). The +least recently used index is dropped first; an index whose table is gone (a +reload, a dropped variable) is dropped on the next lookup; a column too large +for the bound is remembered and scanned without retrying. Build one +explicitly with `.idx.hash` to have it from the first lookup and to persist +it with the table. + ### Range queries / sorted access — `.idx.sort` Suited to "values between A and B", ordered-output queries, and distinct. Build cost O(n log n); space O(n) for the row-id permutation. The original column stays in original order — the sort lives in the permutation, not the values. @@ -121,7 +147,7 @@ Five things that bite first-time users. - **Mutation drops the index.** The quoted-symbol forms `(insert 'v val)` and `(alter 'v set i val)` / `(alter 'v concat vals)` mutate `v` in place and invalidate the attached structure. The mutator paths handle the drop transparently — there's no error, just a silently un-indexed column afterward. Rebuild explicitly after the write. The non-quoted form `(insert v val)` returns a fresh value and leaves the original (still indexed) untouched. - **Slices can't carry an index.** Internally, slicing a column produces a fresh slice header without `RAY_ATTR_HAS_INDEX`; `(.idx.*)` attach refuses to operate on a slice ("cannot index a slice; materialize first"). The Rayfall surface for slices today is C-API-only — this is mostly relevant when calling Rayforce from your own C code. - **One slot per column, one kind at a time.** Calling `.idx.hash` on a column that already has `.idx.zone` drops the zone first. Multiple coexisting kinds per column is a v2 feature. -- **No persistence for `.idx.*`.** The on-disk column format never carries an index; `ray_col_save` serializes a clean column. Rebuild after a load. HNSW handles can be persisted explicitly with `hnsw-save` / `hnsw-load`. +- **Persistence is explicit.** A splayed save (`.db.splayed.set`) persists the hash, sort and bloom indexes you built with `.idx.hash`, `.idx.sort` and `.idx.bloom`, and writes each numeric column's chunk zone and each string column's dictionary. A generation-2 (compressed) save persists the same indexes, so nothing needs rebuilding after a load. The CSV and Parquet converters add no hash index of their own. HNSW handles can be persisted explicitly with `hnsw-save` / `hnsw-load`. - **Type support.** `.idx.hash` accepts numeric/boolean columns **and `RAY_SYM`** (it indexes the symbol domain ids). `.idx.zone`, `.idx.sort`, and `.idx.bloom` are numeric/boolean only. `RAY_STR` is deferred for all kinds, and `RAY_SYM` is deferred for the non-hash kinds — an unsupported column is rejected with `error: nyi: : only numeric/sym vectors supported (got type N)`, because the string/sym pool pointers collide with the index aux bytes and the displacement sweep is pending. ## 8. Performance characteristics { #perf } diff --git a/docs/docs/guides/instances.md b/docs/docs/guides/instances.md new file mode 100644 index 000000000..eafdb74b5 --- /dev/null +++ b/docs/docs/guides/instances.md @@ -0,0 +1,72 @@ +# Running Several Instances + +Several rayforce processes can run on one machine. Each process sizes its thread pool and its memory for what it can see, and it does not know about the others. Give every instance its own share of CPUs and memory, its own port and journal, and keep each database written by one process at a time. + +## CPUs + +Choose the CPUs of each instance when you start it: `taskset -c LIST`, `docker run --cpuset-cpus=LIST`, or `CPUAffinity=` in a systemd unit. Every thread of the instance, and every program it starts with `.sys.exec`, stays within that list. + +On Linux an instance sizes its thread pool to its list: one thread per CPU of it, the main thread included. The operating system keeps the threads within the list and moves them between its CPUs as it sees fit; rayforce does not tie a thread to one CPU. On other platforms the pool has one thread per online CPU. + +```bash +taskset -c 0,2,4,6,24,26,28,30 rayforce -p 5001 & +taskset -c 8,10,12,14,32,34,36,38 rayforce -p 5002 & +``` + +**Choosing the lists.** Read the machine's layout from `lscpu -e` (columns `NODE`, `SOCKET`, `CORE`), or from `/sys/devices/system/cpu/cpuN/topology/thread_siblings_list` and `/sys/devices/system/node/nodeN/cpulist`. + +- Give each instance whole cores: both hardware threads of a core go to the same instance. Two instances on the two threads of one core slow each other down. +- Keep an instance on one NUMA node when its CPU count fits in one. +- CPU numbering does not follow the layout on every machine. On a two-socket machine that numbers sockets alternately (even CPUs on socket 0, odd on socket 1) with CPU `k` and `k+24` on one core, the ranges `0-7`, `8-15`, … `40-47` put every instance on both sockets, and the last three ranges on the hyperthreads of the first three. For six instances of 8 threads on that machine use `0,2,4,6,24,26,28,30`, `8,10,12,14,32,34,36,38`, `16,18,20,22,40,42,44,46`, `1,3,5,7,25,27,29,31`, `9,11,13,15,33,35,37,39` and `17,19,21,23,41,43,45,47`. + +**CPU quota.** `docker run --cpus=N` and systemd `CPUQuota=` limit CPU time, not CPUs: the instance may still run on every CPU. Its default pool then has one thread per CPU of the quota, rounded up. Give it `--cpuset-cpus` or `CPUAffinity=` as well to choose its CPUs. + +**Do not:** + +- start two instances on overlapping lists: they share those CPUs; +- start instances without a list and leave each at its default size: every instance takes every CPU; +- pass `-c` larger than the list: the threads take turns on its CPUs (rayforce prints a warning). + +`(.sys.info)` reports the CPUs of the instance (`cores`) and its pool size (`workers`); `taskset -p PID` shows its list. + +## Memory + +Each instance treats the machine's whole physical RAM, or the memory limit of its container or cgroup when one is set, as its own. It moves its working set to disk only when its own memory would pass that amount, so several busy instances without limits of their own can together exhaust RAM before any of them spills. Start every instance with `-m SIZE` and keep the sizes, plus room for the page cache, within RAM: + +```bash +taskset -c 0-11 rayforce -m 40G -p 5001 & +taskset -c 12-23 rayforce -m 40G -p 5002 & +``` + +`-m` also bounds the freed memory an idle instance keeps for reuse (a sixteenth of SIZE). + +Instances that read the same tables share the operating system's page cache, so the sum of their resident sizes overstates the memory in use. + +## Ports, journals and spill files + +- **Port:** each instance listens on its own `-p` port. A second instance on a busy port exits with an error. +- **Journal:** each instance needs its own journal base (`-l /path/instance1`). Two processes appending to one journal break its framing, and recovery stops at the first broken entry. Never run `.log.roll`, `.log.snapshot` or `.log.purge` on a journal another process writes. +- **Spill files:** names carry the process id and are removed as soon as they are mapped, so instances never share one. Point `RAY_HEAP_SWAP` at a disk with room for every instance that may spill at once. + +## Sharing a database + +**Readers.** Any number of instances can read the same splayed or partitioned tables. A reader sees either the whole previous version of a table or the whole new one, and a table it has already loaded stays valid when another process rewrites it. + +**One writer per database.** Only one process at a time may write a database: `.db.splayed.set`, a `.csv` or `.parquet` import into an existing root, or a live `insert` into a partitioned table followed by its rollover. All tables and partitions of a database share the root's symbol file. + +- When two processes write the same database, a write that races another one fails with a `corrupt` error. Nothing on disk is damaged. If the failing process holds tables it loaded from that database, its later reads and writes of the database fail until it drops them. +- Two processes that update one table by reading it, changing it and writing it back lose each other's updates; the last write wins. +- A partitioned reader fails while a new partition is being written, because the partition directory exists before its schema does. Write a new partition under a dot directory of the root, passing the root's symbol file, and rename it into place; dot directories are skipped when the partitions are listed: + +```lisp +(.db.splayed.set "/db/.stage/2026.10.02/t/" t "/db/.sym") +(.sys.exec "mv /db/.stage/2026.10.02 /db/2026.10.02") +``` + +**Files.** Never change table files in place: no `cp` over them, no `rsync --inplace`, no `truncate`, no editors. Instances that have the table open see the change at once, its stored statistics no longer match the data, and a shortened file crashes them with `SIGBUS`. Replace tables with `.db.splayed.set`, or write a new file and rename it over the old one. The same applies to files written with `write`, `write-bytes` and `hnsw-save`, which rewrite their target in place. + +**Versions.** All instances that share a database must run the same rayforce version; upgrade them together. + +## Interactive sessions + +The REPL rewrites `~/.rayforce_history` when it exits, so with several interactive sessions only the history of the last one to exit is kept. diff --git a/docs/docs/guides/memory.md b/docs/docs/guides/memory.md index 45cffe4df..425790711 100644 --- a/docs/docs/guides/memory.md +++ b/docs/docs/guides/memory.md @@ -14,7 +14,7 @@ For a deep dive into the allocator internals, see [Memory Model](../architecture ## 2. The `.sys.mem` Function -Call `(.sys.mem 0)` to get a snapshot of the current heap's allocation statistics. It returns a dictionary with the following fields: +Call `(.sys.mem)` to get a snapshot of the current heap's allocation statistics. It returns a dictionary with the following fields: | Field | Type | Description | |---|---|---| @@ -26,6 +26,12 @@ Call `(.sys.mem 0)` to get a snapshot of the current heap's allocation statistic | `sys-current` | i64 | Committed RAM: every anonymous mapping (buddy pools, sys allocations, swap-fallback pool) | | `sys-mapped` | i64 | File-backed bytes currently mapped (splayed columns, symbol file, parse buffers) | | `sys-mapped-peak` | i64 | High-water mark of `sys-mapped` | +| `anon-committed` | i64 | Anonymous RAM the heap has committed (pools, direct and sys blocks; spill excluded) | +| `anon-peak` | i64 | High-water mark of `anon-committed` | +| `anon-watermark` | i64 | Spill threshold: set by `-m SIZE`, see [section 8](#8-total-ram-and-out-of-core-spill) | + +It also returns diagnostic `*-perpart-runs` counters and the symbol-table size; +the [`.sys.mem` reference](../namespaces/sys.md#sys-mem) documents every key. ### Basic Usage @@ -86,7 +92,7 @@ tracing collector. ## 4. The `.sys.info` Function -Call `(.sys.info 0)` to see system-level information about the Rayforce runtime: +Call `(.sys.info)` to see system-level information about the Rayforce runtime: ```lisp (.sys.info) @@ -152,7 +158,7 @@ The progress bar is cleared automatically when the query completes and the resul ## 6. The `timeit` Function -Wrap any expression in `(timeit ...)` to measure its execution time. It evaluates the expression, discards the result, and **returns the elapsed time in milliseconds** as an f64 value. +Wrap any expression in `(timeit ...)` to measure its execution time. It evaluates the expression, discards the result, and **returns the elapsed time in milliseconds** as an f64 value. A deferred (lazy) result, such as a bare `(sum v)`, is forced inside the timed span, so the figure covers the computation, not the construction of its graph. ```lisp ;; Time a simple vector operation @@ -235,7 +241,8 @@ has committed, and when a new pool or large allocation would push that past the watermark — by default the smaller of total physical RAM and the container's cgroup memory limit (cgroup v2 `memory.max` / v1 `memory.limit_in_bytes`, including limits set on a parent slice), less a quarter of it (at least 3 GiB, -at most half) left to the page cache, or the `-m SIZE` flag when given — it +at most half) left to the page cache, or the `-m SIZE` flag when given +(reported as [`anon-watermark`](../namespaces/sys.md#sys-mem)) — it backs that allocation with a disk spill file **instead of** anonymous RAM. This never rejects work; it just routes the overflow to disk so it spills rather than getting OOM-killed. A query like `(til 10000000000)` (a 74 GiB vector) on a smaller machine now spills to disk and @@ -259,7 +266,8 @@ total-mem | 16777216000 ### Gauging headroom To see how close a workload is to spilling to disk, compare the anonymous -footprint the heap has committed (`anon-committed` from `(.sys.mem)`: pools, +footprint the heap has committed (`anon-committed` from +[`(.sys.mem)`](../namespaces/sys.md#sys-mem): pools, large blocks and the off-heap tables such as the symbol arenas) against the spill threshold (`anon-watermark`): @@ -276,6 +284,32 @@ spill threshold (`anon-watermark`): This shows the workload uses 29.4% of the RAM it may take before new memory starts going to spill files. +**No swap.** On Linux the heap locks the anonymous memory it maps under the +watermark — pools, large blocks, large off-heap tables — against swap-out +(`mlock2` with `MLOCK_ONFAULT`: a page is locked when it is first touched, +nothing is faulted in ahead), so the kernel never moves it to swap to make room +for page cache, and a query never waits for a swap-in. Memory past the +watermark and spill files are never locked, and the locked bytes stay within +the smaller of the watermark and half the RAM limit (the watermark alone is +half the limit on a small machine but up to three quarters on a large one, and +`-m` may set it past RAM). An empty pool kept for reuse is unlocked while it is +parked, and `(.sys.gc)` and the idle decay unlock the blocks the heap keeps +cached. + +`RLIMIT_MEMLOCK` bounds it too: the `rayforce` binary raises the soft limit to +the hard one at startup (an embedding keeps its host's limits, and children of +`.sys.exec` inherit the raised soft limit). A process with `CAP_IPC_LOCK` — root +outside a container — is past any limit; a user often has 8 or 64 MB, and a +container as little as 64 KB, root inside it too. What does not fit is left +unlocked, the heap works on as before, and `(.sys.mem)` counts it +(`lock-skipped`, `lock-failed`); `locked-bytes` shows the mapped bytes locked. +`RAY_HEAP_MLOCK=0` turns locking off (read once, at the first lock). The +bound follows the RAM limit read at startup: a cgroup limit lowered later is +not seen, and what was locked stays locked until it is freed. Each process +bounds only its own +locking: on a machine shared by several heavy rayforce processes, give each a +`-m` that adds up, or turn locking off. + A spill file is mapped shared. An embedding process that `fork()`s and keeps running rayforce code in the child shares the spilled blocks with the parent instead of getting its own copy, so the child must not write them; run the @@ -392,9 +426,9 @@ This tells you the join needed about 1 GB of temporary memory beyond what was al | Tool | What It Does | When to Use | |---|---|---| -| `(.sys.mem 0)` | Returns heap allocation statistics | Monitor memory usage, detect leaks | +| `(.sys.mem)` | Returns heap allocation statistics | Monitor memory usage, detect leaks | | `(.sys.gc)` | Flushes caches, releases pages | Between heavy queries, before benchmarks | -| `(.sys.info 0)` | Shows system and runtime info | Check total RAM, CPU count, OS details | +| `(.sys.info)` | Shows system and runtime info | Check total RAM, CPU count, OS details | | `(timeit expr)` | Measures execution time of one expression | Benchmark a specific operation | | `:timeit` | Toggles profiling for all REPL expressions | Interactive performance exploration | | Progress bar | Automatic during long queries | Visual feedback on query progress | diff --git a/docs/docs/guides/storage.md b/docs/docs/guides/storage.md index bee02b6e5..5eb259eef 100644 --- a/docs/docs/guides/storage.md +++ b/docs/docs/guides/storage.md @@ -69,7 +69,7 @@ ray_err_t ray_sym_save(const char* path); ray_err_t ray_sym_load(const char* path); ``` -The symbol file uses an append-only format: new symbols are appended on save, and loading merges them into the running table. File locking (`flock` on POSIX, `LockFileEx` on Windows) ensures safe concurrent access. +`ray_sym_save` writes the whole runtime table to a temporary file and renames it over the target, so a reader never sees a partial file; there is no merge with another writer's file, so one process writes a given file. Loading merges the file into the running table. In typical usage, you do not call these directly — the splayed and partitioned table functions handle symbol persistence automatically. @@ -127,7 +127,7 @@ trades/ Pass a `sym_path` to automatically save/load the symbol table alongside the data. Pass `NULL` if you manage symbols separately. -From Rayfall, use `(.db.splayed.set "/tmp/weather" t)` to save and `(.db.splayed.get "/tmp/weather")` to load — no C code required. +From Rayfall, use `(.db.splayed.set "/tmp/weather" t)` to save (add `{compress: true}` for compressed column files) and `(.db.splayed.get "/tmp/weather")` to load — no C code required. ## 5. Partitioned Tables { #partitioned-tables } @@ -380,6 +380,9 @@ decoding, and streaming grouped queries remain future work. Both `.parquet.splayed [types] path directory` and `.parquet.parted [types] path root table-name` return the imported row count. +An options dict in place of the type vector may add `compress: true` for +compressed (generation-2) column files; `.csv.splayed` and `.csv.parted` take +`{compress: true}` as a leading argument. The optional positional type vector has one entry per source column. It accepts matching native types, checked signed integer widths, and `SYM` for text. Raw integer dates/timestamps require explicit `UNIX_DATE` (days), `UNIX_SECONDS`, diff --git a/docs/docs/guides/timespan.md b/docs/docs/guides/timespan.md new file mode 100644 index 000000000..be10dbea3 --- /dev/null +++ b/docs/docs/guides/timespan.md @@ -0,0 +1,110 @@ +# Timespan + +TIMESPAN represents a signed 64-bit count of nanoseconds. It is a duration, +not a date or a time of day. One day is exactly 86,400 seconds; applying a +duration does not perform calendar or daylight-saving adjustments. + +## Literals and conversions + +```lisp +1D ; one day +0D01:00:00 ; one hour +-0D00:00:00.000000001 ; minus one nanosecond +0Nn ; null +0Wn ; maximum signed count +-0Wn ; negative maximum signed count +(as 'I64 1D) ; 86400000000000 +(as 'TIMESPAN 1000000000) ; 0D00:00:01.000000000 +(as 'TIMESPAN 01:00:00.000) ; 0D01:00:00.000000000 +(as 'TIMESPAN "1D01:00:00") ; 1D01:00:00.000000000 +``` + +The syntax is `[-]daysD[hh[:mm[:ss[.fraction]]]]`. Hours may exceed 23 +(`0D24:00:00` is `1D`); minute and second fields must be between 00 and 59. +Compact hour/minute/second forms are also accepted. The day field has at +most six digits. A fraction is padded or truncated to nine decimal places. The initial minus +sign negates the whole duration. Printing uses the full day/time form, +except for null and the signed endpoint spellings, so values read back with +their type and nanosecond precision. Integer arithmetic wraps in 64 bits; +`INT64_MIN` is reserved for null. Floating casts round to the nearest +integer count, with half counts rounded away from zero. + +Vectors use per-element duration syntax, for example `[1D 0Nn -1D]`. +`as 'TIMESPAN` also converts a vector element by element. TIME converts +milliseconds to nanoseconds exactly. Casting a timestamp to TIMESPAN +extracts its time of day; casting a timespan to I64 exposes its raw count. + +## Arithmetic and result types + +| Expression | Result | +|---|---| +| `timestamp - timestamp` | TIMESPAN | +| `timestamp + span`, `timestamp - span`, `span + timestamp` | TIMESTAMP | +| `span + span`, `span - span`, `neg span`, `abs span` | TIMESPAN | +| `span + integer`, `integer + span`, `span - integer` | TIMESPAN; integer counts nanoseconds | +| `span * integer`, `integer * span` | TIMESPAN | +| `span div integer`, `span div span` | TIMESPAN | +| `span / span`, `span / integer` | F64 | +| `span % integer` | TIMESPAN | +| `span % span`, `span * span` | Type error | +| Comparisons with another span or an integer count | BOOL | +| `sum spans` | TIMESPAN; skips nulls | +| `avg spans` | F64 nanoseconds; skips nulls | +| `min`, `max`, `first`, `last` | Preserve TIMESPAN | + +On empty or all-null duration vectors, `min` returns `0Wn` and `max` +returns `-0Wn`. + +F64 operands promote ordinary duration addition and multiplication to F64 +nanosecond arithmetic. F32 operands are rounded to an integer count for +these duration operations. Integer division preserves the left operand's +type: a span divided by a span is a duration containing the quotient count, +not a dimensionless integer. Division floors toward negative infinity. +For example, `(div -0D00:00:00.000000001 2)` is minus one nanosecond, and +`(% -0D00:00:00.000000001 1000000000)` is 999,999,999 nanoseconds. + +Nulls propagate through arithmetic. Integer division, remainder, and duration bucket widths of zero return a +typed null. F64 results retain the engine's existing +policy of converting non-finite results to `0Nf`. + +`xbar` accepts a TIMESPAN bucket width for timestamps: + +```lisp +(xbar 2024.01.15D12:34:56.000000000 0D01:00:00) +; 2024.01.15D12:00:00.000000000 +``` + +Scalar, vector and query column expressions use the same duration arithmetic. +Ordinary, encoded and partitioned storage preserve duration types and nulls. +Explicit CSV schemas accept TIMESPAN and CSV writes use its literal syntax. +Parquet duration and clock-time annotations are not remapped by this change. + +## Migrating timestamp differences + +Timestamp subtraction previously returned I64. It now returns TIMESPAN, +including in queries and updates. To retain the previous integer-count +behavior, explicitly cast the difference before further arithmetic: + +```lisp +(as 'I64 (- finish start)) +(div (as 'I64 (- finish start)) 1000000000) +``` + +For a typed period, `(div (- finish start) period)` returns a TIMESPAN +holding the quotient count. Cast that quotient to I64 when it represents a +bar index. Use an integer nanosecond width for remainder, because two +TIMESPAN operands are not admitted by `%`: + +```lisp +(as 'I64 (div (- finish start) period)) +(% (- finish start) (as 'I64 period)) +``` + +## Reference checks + +The installed q 5.0 binary (2026.07.23) was used to generate 65 scalar cases for +`test/rfl/temporal/timespan_operators.rfl`. The fixture checks both result +types and raw counts for parsing, endpoint spellings, mixed arithmetic, +division, remainder, comparisons, timestamp subtraction and aggregates. +These checks establish the tested duration behavior; the existing F64 +non-finite policy described above still applies. diff --git a/docs/docs/guides/types.md b/docs/docs/guides/types.md index 20973b75e..e5db5cc94 100644 --- a/docs/docs/guides/types.md +++ b/docs/docs/guides/types.md @@ -29,6 +29,7 @@ The `as` function performs explicit type conversion. It takes a type symbol and | `'i32` | 32-bit integer | Standard integer | | `'i64` | 64-bit integer | Long integer (default) | | `'u8` | unsigned 8-bit | Byte values | +| `'f32` | 32-bit float | Single precision; an f64 past its range saturates to ±3.40e+38 | | `'f64` | 64-bit float | Double precision (default) | | `'b8` | Boolean | true / false | | `'str` | String | Variable-length text | @@ -36,8 +37,20 @@ The `as` function performs explicit type conversion. It takes a type symbol and | `'date` | Date | Days since 2000-01-01 | | `'time` | Time | Milliseconds since midnight | | `'timestamp` | Timestamp | Nanoseconds since 2000-01-01T00:00:00 | +| `'timespan` | Duration | Signed count of nanoseconds | | `'guid` | GUID | 16-byte unique identifier | +F32 literals use a trailing lowercase `e`: `42e`, `1.5e`, or `-1.5e`. +Scientific notation keeps its exponent: `1e3` is F64, while `1e3e` is F32. +F32 vectors require a suffix on each non-null element: `[1e 2e 0Ne]`. +Finite values beyond the F32 range saturate just as casts do. F32 values +print with the suffix so parsing the output preserves the element type; +the configured display precision still controls decimal rounding. + +Casting F32 to STR instead produces plain numeric text without the literal +suffix (for example, `(as 'STR 1.5e)` returns `"1.5"`). It uses nine +significant digits so casting the string back to F32 preserves the value. + **Numeric casts:** ```lisp @@ -88,6 +101,11 @@ The `as` function performs explicit type conversion. It takes a type symbol and **Vector casts:** `as` maps element-wise over vectors. +Casting to `STR` produces a flat string vector from a vector or a LIST of +atoms. Each outer element must convert to one string atom. A nested vector or +LIST cell is rejected with a `type` error; this cast does not implicitly format +or flatten a whole inner collection into a string cell. + ```lisp ; Cast an integer vector to float (as 'f64 [1 2 3]) ; [1.0 2.0 3.0] @@ -187,7 +205,18 @@ Strings can be parsed into numeric, temporal, and symbol types with `as`. Conver ## 5. Null Semantics in Casting { #null-semantics } -Null values propagate through casts. A typed null in one type becomes a typed null in the target type. Invalid string parses raise a domain error. +Null values propagate through casts to nullable types. BOOL/B8 and U8 have +no null value: a numeric or temporal null casts to `true` for BOOL/B8 and +`0x00` for U8. The result is an ordinary non-null value, consistently for +atoms, vectors, lists, and query column casts. Empty strings cast to BOOL/B8 +as `false`. Invalid numeric string parses raise a domain error. + +```lisp +(as 'B8 0Nl) ; true +(as 'B8 [0 0Nl 1]) ; [false true true] +(as 'U8 0Nl) ; 0x00 +(nil? (as 'U8 0Nl)) ; false +``` ```text ; Casting a typed null produces a typed null @@ -208,11 +237,17 @@ Null values propagate through casts. A typed null in one type becomes a typed nu - `0Nl` — null i64 - `0Nh` — null i16 - `0Nf` — null f64 + - `0Ne` — null f32 + - `0Ng` — null guid (the all-zero GUID) - `0Nd` — null date - `0Nt` — null time - `0Np` — null timestamp + - `0Nn` — null timespan - `SYM` has no typed null literal (`0Ns` does not parse). + `SYM` has no `0N` literal (`0Ns` does not parse): its null is the empty + symbol, written `'`. `(nil? ')` is `true`, and it prints as `'`, so a + printed vector such as `[a ' b]` reads back as the same value. `STR`'s null + is the empty string `""`. Use `nil?` to test for null values: `(nil? 0Ni)` returns `true`. @@ -258,13 +293,25 @@ Rayforce has two string representations with different performance characteristi ## 7. Date/Time Types { #date-time } -Rayforce has three temporal types, all stored as integers internally: +Rayforce represents calendar points and clock times with DATE, TIME, and TIMESTAMP, and nanosecond durations with TIMESPAN. All use integer storage: | Type | Internal | Epoch | Literal Format | |---|---|---|---| | `date` | i32 | Days since 2000-01-01 | `2024.01.15` | | `time` | i32 | Milliseconds since midnight | `12:30:00.000` | | `timestamp` | i64 | Nanoseconds since 2000-01-01 midnight | `2024.01.15D12:30:00.000000000` | +| `timespan` | i64 | Nanoseconds of duration | `1D`, `0D01:00:00.000000000` | + +`date` and `time` are 32-bit counts (of days and of milliseconds). A `time` +is not limited to one day: `48:00:00.000` and negative values are valid, up to +about ±596 hours. A result past the 32-bit range keeps its low 32 bits, the +same for an atom and for a vector cell, so `(* 25 24:00:00.000)` is +`-593:02:47.296`. + +Subtracting two timestamps returns TIMESPAN. Cast the difference with +`as 'I64` when an integer nanosecond count is needed. A duration may be +added to a timestamp, scaled by an integer, or used as an `xbar` width. +See [Timespan](timespan.md) for operator result types and migration details. **Date arithmetic:** diff --git a/docs/docs/language/control-flow.md b/docs/docs/language/control-flow.md index 9602485fa..9837f4a94 100644 --- a/docs/docs/language/control-flow.md +++ b/docs/docs/language/control-flow.md @@ -18,6 +18,21 @@ Without an else branch, `if` returns `0`: 0 ``` +More condition/result pairs chain: conditions are tested in order, the +result paired with the first truthy one is evaluated, and an odd trailing +argument is the fallback. Conditions after the first truthy one, and every +other result, are never evaluated: + +```lisp +‣ (set classify (fn [x] (if (> x 100) "high" (> x 50) "mid" "low"))) +‣ (classify 60) +"mid" +‣ (if false 1 false 2) +0 +``` + +Inside a query (a projection, `where:`, a `by:` key), a chain with a fallback is evaluated row by row like the three-argument form, and a text literal in it becomes a symbol cell; a chain without a fallback is left to the evaluator. + ## Sequential Evaluation: do `do` evaluates expressions in order and returns the last result. `let` bindings inside `do` are scoped to that block: @@ -106,6 +121,21 @@ error. Like `while`, `times` pushes no scope of its own, so a `let` in the body binds in the enclosing frame; wrap the body in `do` when a fresh binding per pass is wanted. +To loop over positions, give `times` a `[name count]` binding instead of a bare +count. The name takes `0`, `1`, …, `count - 1`, one value per pass: + +```lisp +(times [i (count qty)] + (alter 'qty set i (+ (at qty i) (at delta i)))) +``` + +The index is bound like a `let`, in the enclosing frame, and keeps the last +index once the loop ends; a loop that runs no pass leaves it as it was. It is +set from the loop's own counter at the start of every pass, so a body that +rebinds the name changes it for the rest of that pass only, never the passes +that follow. The count follows the rules above: evaluated once, an integer, +nothing run when it is zero or less. + Reach for `times` when the number of passes is known up front and for `while` when it is not. Neither allocates a sequence, so neither pays for a range that exists only to be counted. diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index 06390f49b..76ed528f5 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -67,8 +67,8 @@ All comparison operators are **atomic** and return boolean results. | Function | Type | Description | Example | |---|---|---|---| -| `and` | binary | Logical AND | `(and true false)` → `false` | -| `or` | binary | Logical OR | `(or true false)` → `true` | +| `and` | binary | Logical AND; element-wise on vectors and lists, each element by its truthiness (lengths must match) | `(and true false)` → `false`, `(and [1 0 2] [1 1 0])` → `[true false false]` | +| `or` | binary | Logical OR; element-wise on vectors and lists (lengths must match) | `(or true false)` → `true` | | `not` | unary | Logical NOT; element-wise over a BOOL, numeric or temporal vector (zero and null are not true) | `(not true)` → `false`, `(not [1 0 0N])` → `[false true true]` | ## Aggregation @@ -129,7 +129,7 @@ Functions that take other functions as arguments. | Function | Type | Description | Example | |---|---|---|---| | `map` | variadic | Apply function to each element (returns a list) | `(map (fn [x] (* x 2)) [1 2 3])` → `(2 4 6)` | -| `pmap` | variadic | Parallel map (multi-threaded, returns a list) | `(pmap (fn [x] (* x x)) [1 2 3])` → `(1 4 9)` | +| `pmap` | variadic | Currently a sequential alias for `map` (returns a list) | `(pmap (fn [x] (* x x)) [1 2 3])` → `(1 4 9)` | | `filter` | binary | Keep elements where boolean mask is true | `(filter [1 2 3 4] (> [1 2 3 4] 2))` → `[3 4]` | | `fold` | variadic | Reduce with function and initial value | `(fold + 0 [1 2 3])` → `6` | | `fold-left` | variadic | Left-associative fold | `(fold-left - 10 [1 2 3])` → `4` | @@ -158,15 +158,15 @@ Query `concat` joins text row by row when every vector operand comes from a sour | `except` | binary | Set difference | `(except [1 2 3] [2])` → `[1 3]` | | `union` | binary | Set union | `(union [1 2] [2 3])` → `[1 2 3]` | | `sect` | binary | Set intersection | `(sect [1 2 3] [2 3 4])` → `[2 3]` | -| `take` | binary | Take first/last N elements | `(take [10 20 30] 2)` → `[10 20]` | +| `take` | binary | Take first/last N elements; past the length it cycles (`select … take:` stops at the table's length). A parted table handle (`.db.parted.get`) is taken as its flat table: the same rows `(at table (til n))` returns, cycling past the row count | `(take [10 20 30] 2)` → `[10 20]`; `(take [1 2 3] 5)` → `[1 2 3 1 2]` | | `drop` | binary | Drop first/last N elements | `(drop [10 20 30] 1)` → `[20 30]` | | `rotate` | binary | Rotate left by N positions; negative rotates right | `(rotate [1 2 3 4] 1)` → `[2 3 4 1]` | | `cut` | binary | Split at sorted 0-based indices | `(cut [1 2 3 4] [2])` → `([1 2] [3 4])` | | `cross` | binary | Cartesian product as pairs | `(cross [1 2] ['a 'b])` → `((1 'a) (1 'b) (2 'a) (2 'b))` | -| `at` | binary | Index a collection; vector keys batch dictionary lookups | `(at [10 20 30] 1)` → `20` | +| `at` | binary | Index a collection; vector keys batch dictionary lookups. A typed vector indexed by an integer vector keeps its type: a null or out-of-range index gives the type's null (`false`/`0x00` for BOOL/U8) | `(at [10 20 30] 1)` → `20`, `(at [10 20 30] [2 9])` → `[30 0Nl]` | | `find` | binary | Find index of value | `(find [10 20 30] 20)` → `1` | | `fill` | binary, atomic | Replace null values; the replacement is the first argument | `(fill 0 [1 0Nl 3])` → `[1 0 3]` | -| `reverse` | unary | Reverse order | `(reverse [1 2 3])` → `[3 2 1]` | +| `reverse` | unary | Reverse order; a table reverses its rows (columns and types kept), a dictionary its entries (keys and values together) | `(reverse [1 2 3])` → `[3 2 1]` | | `til` | unary | Range [0..n) | `(til 5)` → `[0 1 2 3 4]` | | `lag` | unary | Shift values one row back; first row is null/sentinel | `(lag [10 20 30])` → `[0Nl 10 20]` | | `lead` | unary | Shift values one row forward; last row is null/sentinel | `(lead [10 20 30])` → `[20 30 0Nl]` | @@ -231,7 +231,7 @@ The time-series vector functions above are lazy-aware DAG operations for vector | `xkey` | binary | Build a dict keyed by unique column value(s), with row dict values for remaining columns | `(xkey trades 'time)` | | `xgroup` | binary | Group rows by column value(s), returning dict key -> table slice | `(xgroup trades 'sym)` | | `fkeys` | unary | Inspect linked-column metadata as `column -> target table` | `(fkeys fact)` | -| `alter` | variadic, special | In-place mutation of table column | `(alter trades 'price (* price 1.1))` | +| `alter` | variadic, special | Amend a global binding in place and return its name: `(alter 'name set idx val)` writes `val` at an index or index vector, `(alter 'name concat vals)` appends, `(alter 'name remove idx)` drops list items. The target must be a global binding; a name bound by `let` or a parameter of the enclosing function raises `domain` | `(alter 'v set 0 99)` | | `del` | variadic, special | Delete columns or rows from table | `(del trades 'temp_col)` | | `modify` | variadic | Functional table update (returns new table) | `(modify trades 'price (fn [p] (* p 1.1)))` | @@ -294,7 +294,7 @@ These are **special forms** that bridge to the Rayforce DAG executor. Indices are *pre-insertion* positions in `[0, count]`; `idx == count` is equivalent to append. Vector positional inserts of a same-typed vector splice that vector in. List positional inserts always add the value as a single slot — use `concat` to splice. Multi-insert is stable on duplicate indices, preserving input order. Typed-null atoms (`0Nl`, `0Nf`, …) carry their null flag through — the inserted slot is marked null, not zero. -For a parted target, `rows` must match the physical data-column schema exactly in name and concrete vector type. Do **not** include the virtual `date` or `part` column. A list maps values in physical column order; a table or dictionary may reorder columns, but must contain every physical name exactly once. Atoms append one row. Equal-length vectors append a batch, and atom values alongside them broadcast across that batch. Generic `null` is accepted for sentinel-nullable columns; `SYM` and `STR` map it to their empty value because those types have no distinct null, while `BOOL` and `U8` reject it because they are non-nullable. +For a parted target, `rows` must match the physical data-column schema exactly in name and concrete vector type. Do **not** include the virtual `date` or `part` column. A list maps values in physical column order; a table or dictionary may reorder columns, but must contain every physical name exactly once. Atoms append one row. Equal-length vectors append a batch, and atom values alongside them broadcast across that batch. Generic `null` is accepted for sentinel-nullable columns; `SYM` and `STR` map it to their null, which is their empty value (`'` or `""`), while `BOOL` and `U8` reject it because they are non-nullable. The partition key must equal the current last key, which grows that live segment, or be strictly later, which starts a new live segment. Earlier keys — including an existing historical partition — are immutable and cannot be inserted into. Existing partition metadata must already be strictly increasing in logical key order; integer directory names are ordered by value (`1`, `2`, `10` — no zero-padding needed), so only two spellings of one value (`1` and `01`) violate this, and they are rejected as `corrupt`. Every historical physical segment must be present. A missing segment in the last partition can be repaired only by a non-empty same-key append; it blocks an empty insert or a move to a later key. `BOOL`/`U8` cannot be null-backfilled when that missing segment already represents existing rows, but a missing zero-row segment needs no backfill. @@ -384,7 +384,7 @@ Rayforce supports equi-joins, outer joins, anti-joins, and time-series-aware joi | `split` | binary | Split string by delimiter (returns a list) | `(split "a,b,c" ",")` → `("a" "b" "c")` | | `str-find` | binary | First byte index of a substring; returns `0Nl` when absent | `(str-find "banana" "na")` → `2` | | `str-join` | binary | Join strings or symbols with a delimiter | `(str-join ["a" "b"] ",")` → `"a,b"` | -| `strlen` | unary | Length of each string | `(strlen "hello")` → `5` | +| `strlen` | unary | Length of each string. `""` is the STR/SYM null: `strlen` maps it to a null length, `sum` and `avg` skip it, and the `avg` of an all-empty group is null. | `(strlen "hello")` → `5` | | `upper` | unary | Uppercase string or symbol atoms/vectors; lazy/DAG for vectors | `(upper ["ab" "Cd"])` → `["AB" "CD"]` | | `lower` | unary | Lowercase string or symbol atoms/vectors; lazy/DAG for vectors | `(lower 'AbC)` → `'abc` | | `trim` | unary | Strip leading/trailing whitespace; lazy/DAG for vectors | `(trim " abc ")` → `"abc"` | @@ -497,7 +497,7 @@ spills exactly as it did before. |---|---|---|---| | `set` | binary, special | Bind value to global variable | `(set x 42)` | | `let` | binary, special | Bind value to local variable | `(let y (+ x 1))` | -| `if` | variadic, special | Conditional (if/then/else) | `(if (> x 0) "pos" "neg")` | +| `if` | variadic, special | Conditional: condition/result pairs, optional final else | `(if (> x 0) "pos" "neg")` | | `do` | variadic, special | Sequential execution, returns last | `(do (set x 1) (set y 2) (+ x y))` | | `fn` | variadic, special | Create lambda function | `(fn [x] (* x x))` | | `try` | binary, special | Error handling (expr handler-or-fallback) | `(try (/ 1 0) (fn [e] 0))` | @@ -524,8 +524,8 @@ spills exactly as it did before. | `.sys.args` | nullary | Application arguments as a typed dict (`user` subdict for post-`--` args) | `(.sys.args)` | | `env` | unary | List all global environment bindings | `(env 0)` | | `.sys.build` | nullary | Build metadata: `version` + `build-date` | `(.sys.build)` | -| `.sys.mem` | variadic | Memory allocator statistics (alloc/peak/slab) | `(.sys.mem)` | -| `.sys.info` | variadic | System information (cores, page size, memory) | `(.sys.info)` | +| `.sys.mem` | nullary | Memory allocator statistics (alloc/peak/slab) | `(.sys.mem)` | +| `.sys.info` | nullary | System information (cores, page size, memory) | `(.sys.info)` | ## Serialization & Storage @@ -533,7 +533,7 @@ spills exactly as it did before. |---|---|---|---| | `ser` | unary | Serialize value to binary format | `(ser [1 2 3])` | | `de` | unary | Deserialize from binary format | `(de bytes)` | -| `.db.splayed.set` | variadic | Save table as splayed columns to directory | `(.db.splayed.set "db/trades" trades)` | +| `.db.splayed.set` | variadic | Save table as splayed columns to directory; optional `{compress: bool}` | `(.db.splayed.set "db/trades" trades)` | | `.db.splayed.get` | variadic | Load splayed table from directory | `(.db.splayed.get "db/trades")` | | `.db.parted.get` | variadic | Load partitioned table by name from root directory | `(.db.parted.get "db" 'trades)` | | `.db.parted.tables` | variadic | List table names under a parted root | `(.db.parted.tables "db")` | @@ -613,6 +613,8 @@ Low-level API for building and evaluating Datalog programs directly, bypassing t | `dl-query` | binary | Query a derived or base relation | `(dl-query prog 'edge)` | | `dl-provenance` | binary | Reserved provenance hook; currently returns `domain: not available` | `(dl-provenance prog 'rel)` | +A `dl-program` handle owns its program. Rebinding its symbol or leaving the handle's scope releases the program automatically; use `(dl-free prog)` to release it earlier. + ```lisp ; Low-level Datalog program (set prog (dl-program)) diff --git a/docs/docs/language/math.md b/docs/docs/language/math.md index 8136f7edc..d6f3e4b5d 100644 --- a/docs/docs/language/math.md +++ b/docs/docs/language/math.md @@ -237,16 +237,21 @@ Check if each element of a vector is within a range (inclusive). The second argu ### `(and a b)` — atomic -Logical AND. Works on booleans and boolean vectors. +Logical AND. On atoms it answers one boolean; on a vector or a list it +works element by element, each element by its truthiness, and returns a +boolean vector (a nested list keeps its shape). An atom broadcasts, and two +collections of different lengths are a `length` error. ```lisp (set x 5) (and (> x 0) (< x 10)) +(and [true false] (list true true)) ; [true false] +(and [1 0 2] true) ; [true false true] ``` ### `(or a b)` — atomic -Logical OR. +Logical OR, element by element on collections, as `and` is. ```lisp (set x 5) @@ -260,8 +265,12 @@ Logical NOT. Flips boolean values. ```lisp (not true) ; false (not [true false true]) ; [false true false] +(not (list 1 0)) ; [false true] ``` +Comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`) on a list also give a +boolean vector, element by element, as on a typed vector. + ## Aggregation Aggregation functions reduce a vector to a single scalar. They carry the `FN_AGGR` flag and are recognized by the `select`/`update` query planner for group-by operations. @@ -340,6 +349,14 @@ Median value. (med [1 3 5 7 9]) ; 5.0 ``` +For a TIMESPAN vector, the result is an F64 number of **nanoseconds**, +including fractional nanoseconds for an even-sized input. `SELECT` uses the +same result type; it does not round the median back into a duration. + +```lisp +(med [0D01:00:00 0D02:00:00]) ; 5400000000000.0 +``` + ### `(dev x)` — aggregate Population standard deviation. @@ -509,10 +526,14 @@ Take the first `n` elements from a vector, or repeat/cycle `x` to length `n`. ### `(reverse x)` -Reverse a vector. +Reverse a vector, a table's rows, or a dictionary's entries. A table keeps +its column names and types; a dictionary's keys and values move together. ```lisp (reverse [1 2 3]) ; [3 2 1] +(set t (table [a b] (list [1 2 3] ["x" "y" "z"]))) +(at (reverse t) 'a) ; [3 2 1] +(reverse (dict ['a 'b 'c] [10 20 30])) ; {c:30 b:20 a:10} ``` ### `(where x)` @@ -535,9 +556,13 @@ Find the index of the first occurrence of `val` in vector `x`. ### `(xbar x n)` Round each element down to the nearest multiple of `n` (bucketing). +A temporal `x` keeps its type. A null `x`, atom or element, gives the null of +the result type. ```lisp -(xbar [3 7 12 18] 5) ; [0 5 10 15] +(xbar [3 7 12 18] 5) ; [0 5 10 15] +(xbar [2000.01.10 0Nd] 7) ; [2000.01.08 0Nd] +(xbar 0Nd 7) ; 0Nd ``` ## Higher-order Functions @@ -610,12 +635,24 @@ Keep elements of `vec` where the boolean `mask` is true. ### `(pmap f x)` -Parallel map. Like `map` but distributes work across threads for large inputs. +Currently a **sequential alias for `map`**: it calls the function for each +input element in order on the calling thread's VM and returns the same list as +`map`. A larger input or a larger `-c` setting does not distribute these callback +invocations across workers. The name can signal intent, but does not currently +provide parallel lambda evaluation. ```lisp -(pmap (fn [x] (* x x)) (til 1000000)) +(pmap (fn [x] (* x x)) [1 2 3]) ; (1 4 9), evaluated sequentially ``` +Eligible vector builtins and query operators can use the morsel-driven thread +pool **inside** a callback; that is separate from scheduling callbacks in +parallel. Eligibility, input-size thresholds and worker availability depend on +the operator; a large vector alone is not a guarantee of parallel execution. +See [Thread Pool](../architecture/pipeline.md#thread-pool). For independent +Rayfall task sweeps today, use separate processes and budget their workers as +described in [Multiple Instances](../guides/instances.md). + ## Quick Reference Table | Category | Functions | diff --git a/docs/docs/language/repl.md b/docs/docs/language/repl.md index 6ed0ded87..ed5809764 100644 --- a/docs/docs/language/repl.md +++ b/docs/docs/language/repl.md @@ -17,7 +17,9 @@ The `rayforce` binary operates in three modes depending on how it is invoked: echo '(+ 1 2)' | ./rayforce ``` -Interactive mode is detected automatically when stdin is a terminal. On startup the REPL prints a banner with the version, CPU, memory, logical CPU count, and worker count, then shows the `‣` prompt. By default the pool includes every online logical CPU, including SMT threads. Use `-c N` to choose a total worker count explicitly. Individual operations may use fewer tasks when their workload or memory budget requires it. +Interactive mode is detected automatically when stdin is a terminal. On startup the REPL prints a banner with the version, CPU, memory, logical CPU count, and worker count, then shows the `‣` prompt. By default the pool includes every logical CPU the process may run on (all online CPUs, unless `taskset` or a cpuset narrowed them), including SMT threads. Use `-c N` to choose a total worker count explicitly: N must contain decimal digits only; `0` selects the automatic size, and `1..1023` sets the total count, including the main thread. Values outside this range are rejected before the pool starts. Individual operations may use fewer tasks when their workload or memory budget requires it. Use `-m SIZE` (`--mem`; a byte count or a `K`/`M`/`G`/`T` suffix) to set the RAM budget: anonymous memory past it spills to disk instead of risking the OOM killer. `(.sys.mem)` reports the effective value as [`anon-watermark`](../namespaces/sys.md#sys-mem). + +Under a cgroup CPU quota (`docker --cpus`, systemd `CPUQuota=`) the default pool has one thread per CPU of the quota, rounded up. A `-c` larger than the allowed CPUs prints a warning. See [Running Several Instances](../guides/instances.md) for choosing CPUs per instance. ### Environment Variables diff --git a/docs/docs/language/string.md b/docs/docs/language/string.md index 26747ea68..f5c2a2301 100644 --- a/docs/docs/language/string.md +++ b/docs/docs/language/string.md @@ -50,6 +50,8 @@ All string operations in Rayforce follow strict null propagation semantics: - Null propagation applies uniformly to both RAY_SYM and RAY_STR columns - Null state is carried through the execution pipeline per morsel (1024 elements) +`""` is the STR/SYM null: `strlen` maps it to a null length, `sum` and `avg` skip it, and the `avg` of an all-empty group is null. + In the C API DAG, null propagation is handled automatically per morsel. String transformation opcodes (STRLEN, UPPER/LOWER/TRIM, SUBSTR, REPLACE, CONCAT) propagate nulls: null input rows produce null output rows. CONCAT is null if any argument is null. ## String Functions diff --git a/docs/docs/language/syntax.md b/docs/docs/language/syntax.md index 4d4f5c8b9..2b3c36856 100644 --- a/docs/docs/language/syntax.md +++ b/docs/docs/language/syntax.md @@ -74,14 +74,24 @@ end of its month is normalized by the calendar rather than rejected, so ### Times Time-of-day literals in HH:MM:SS.mmm format. Stored as milliseconds since midnight (i32). +Values past 24 hours and negative values are valid; for the range, and what an +out-of-range result becomes, see [Date/Time types](../guides/types.md#date-time). ```lisp 09:30:00.000 ; 9:30 AM 14:15:30.500 ; 2:15:30.5 PM ``` -Hours must be `0`-`23`, minutes and seconds `0`-`59`; out-of-range -components are a parse error. +A time literal has two hour digits, `00`-`99`, and two digits each for +minutes and seconds. Minutes and seconds past `59` carry into the next unit, +the way a day past the end of its month does for dates, so `01:60:00.000` +parses as `02:00:00.000`. A leading `-` makes the time negative +(`-01:00:00.000`). The fractional part is optional (`09:30:00` is +`09:30:00.000`) and is a decimal fraction of a second: one to three digits are +padded (`09:30:00.5` is `09:30:00.500`), and digits past the third are +dropped. A timestamp literal, the string cast `(as 'time "...")` and the CSV +reader read it the same way. Times beyond `99:59:59.999` come from arithmetic +or from `(as 'TIME )`: `(as 'TIME 2147483647)` is `596:31:23.647`. ### Timestamps @@ -92,10 +102,13 @@ Full date+time with nanosecond precision. Stored as nanoseconds since 2000-01-01 2024.01.15D09:30:00.000000000 ; date + time (ns) ``` -The date and time parts follow the same range rules as above. Because the -value is a 64-bit nanosecond count from the epoch, timestamps only span -roughly ±292 years around 2000 (about 1708 to 2292); a year outside that -range is a parse error. +The date part follows the date rules above. The time part is stricter than a +time literal: hours `00`-`23` and minutes and seconds `00`-`59`, anything else +being a parse error; no leading `-`; and the fractional part is required, with +one to nine digits read as a decimal fraction (`.5` is half a second; digits +past the ninth are dropped). Because the value is a 64-bit nanosecond count +from the epoch, timestamps only span roughly ±292 years around 2000 (about +1708 to 2292); a year outside that range is a parse error. ### GUIDs @@ -118,13 +131,19 @@ sentinel for their type: 0Ni ; i32 null 0Nh ; i16 null 0Nf ; f64 null +0Ne ; f32 null +0Ng ; guid null (the all-zero GUID) 0Nd ; date null 0Nt ; time null 0Np ; timestamp null (nil? 0Nl) ; true ``` -Symbols have no typed null literal (there is no `0Ns`). +Symbols have no `0N` null literal (there is no `0Ns`). Their null is the +empty symbol, written as a lone quote `'`, and it works wherever a symbol +does: `(set s ')`, `(take ' 3)` is `[' ' ']`, `[a ' b]`, `{k: '}`. It prints as +`'` too, so a printed vector reads back as the same value. The symbol `null` +is an ordinary symbol, not the null. `nil?` is element-wise: given a vector or a list it returns a `B8` vector with one entry per element, so `(where (nil? v))` and `(sum (as 'I64 (nil? v)))` @@ -248,6 +267,12 @@ The single quote `'` prevents evaluation, creating a symbol atom. Useful for col `quote` returns its argument unevaluated. When the argument is a bare name, the result is a literal symbol — `(quote name)` is equal to the tick form `'name`. Such a literal symbol, when it names a from-table column, resolves to that column during query evaluation. This is how the dynamic-query idiom works: a query assembled as data evaluates `(quote name)` to the literal symbol `'name` during construction, and that symbol resolves to the column when the query runs (see [IPC](../storage/ipc.md)). Inside a query, the tick form `'name` and a bare `name` resolve the same way. +An inline `(quote name)` node written directly inside a query expression is +different: it keeps a literal symbol even when a column has that name (see +[Select](../queries/select.md)). In the dynamic-query idiom above, `quote` +was evaluated while constructing the query as data, before query evaluation. + + ## Comments Line comments start with a semicolon and extend to the end of the line: @@ -362,8 +387,8 @@ Every `.`-prefixed name is protected: `set`, `let`, lambda parameters, and `del` (raise "oops") ; throws an error (fn [e] "caught")) ; handler receives error → "caught" -; Unhandled raise: -; (raise "custom error") ; error: domain +; Unhandled raise: the error code, then the raised value +; (raise "custom error") ; error: domain: custom error ``` ## Lambdas & the VM @@ -492,7 +517,7 @@ ray_t* result = ray_execute(g, projected); 3. **SIP** (Sideways Information Passing) — propagate selection bitmaps backward through expand chains 4. **Factorize** — avoid materializing cross-products with factorized vectors 5. **Predicate pushdown** — move filters closer to data sources -6. **Filter reorder** — cheapest filters first +6. **Filter reorder** — rank eligible row-local filters by static selectivity and cost without crossing row-domain barriers 7. **Fusion** — merge adjacent operations into single morsel loops 8. **DCE** (Dead Code Elimination) — remove unused DAG nodes diff --git a/docs/docs/namespaces/csv.md b/docs/docs/namespaces/csv.md index 6ada89292..7cc384735 100644 --- a/docs/docs/namespaces/csv.md +++ b/docs/docs/namespaces/csv.md @@ -63,8 +63,9 @@ Signatures: - `(.csv.splayed "src.csv" "out_dir")` - `(.csv.splayed [types] "src.csv" "out_dir")` - `(.csv.splayed [names] [types] "src.csv" "out_dir")` +- `(.csv.splayed {compress: true} ...)` — any arrangement above may start with an options dict. `compress` true writes generation-2 (compressed) column files where eligible, false generation 0; absent inherits per file (generation 2 when the existing destination's current file is generation 2). Unknown keys, a non-bool value or a second options dict are a `domain` error. Linked and nested/list columns are always written uncompressed. A compressed string column persists its dictionary index, as a generation-0 one does. -Streams `src.csv` chunk-by-chunk through the parser into a splayed directory at `out_dir` (one column file per field, `.d` schema, and `.sym` symbol dictionary when needed). Returns the resulting splayed table loaded with `ray_read_splayed` — zero-copy mmap, so the bytes stay on disk. +Streams `src.csv` chunk-by-chunk through the parser into a splayed directory at `out_dir` (one column file per field, `.d` schema, and `.sym` symbol dictionary when needed). Returns the resulting splayed table loaded with `ray_read_splayed`: generation-0 columns are zero-copy mmap, so the bytes stay on disk; a compressed column decodes into heap memory the first time a query reads it. Use this when the CSV is too large to fit in memory but you want to query it like an in-memory table. @@ -84,6 +85,7 @@ Signatures (with optional rows-per-part): - `(.csv.parted [types] "src.csv" "db_root" 'tbl_name)` - `(.csv.parted [names] [types] "src.csv" "db_root" 'tbl_name)` - `(.csv.parted [...]types "src.csv" rows_per_part "db_root" 'tbl_name)` — pass a positive integer just before the db-root to override the default partition size. +- `(.csv.parted {compress: true} ...)` — any arrangement above may start with an options dict. `compress` true writes generation-2 (compressed) files where eligible, false generation 0; absent inherits per file (generation 2 when the existing destination file is generation 2). Unknown keys, a non-bool value or a second options dict are a `domain` error. Linked and nested/list columns are always written uncompressed. A compressed string column persists its dictionary index, as a generation-0 one does. Streams the CSV into `db_root//tbl_name/`. Returns the parted table loaded back from disk. A new root is staged at `.csv-partial` and published after the shared dictionary flush; staging from an import that failed after writing a partition is retained for diagnosis, and a retry into the same root fails with an `io` error naming the directory to remove. A failure before the first partition (an unreadable or empty source, a type vector that does not match) leaves nothing behind. Existing roots retain per-partition update behavior. Bulk writes require an external file and directory sync for durability. diff --git a/docs/docs/namespaces/db.md b/docs/docs/namespaces/db.md index 6fd39237d..8e92f6fbe 100644 --- a/docs/docs/namespaces/db.md +++ b/docs/docs/namespaces/db.md @@ -15,7 +15,7 @@ The `get` builtins memory-map every column file — load is constant-time regard | Function | Arity | Flags | Description | |---|---|---|---| | [`.db.splayed.set`](#db-splayed-set) | variadic | restricted | Save a table to a splayed directory. | -| [`.db.splayed.get`](#db-splayed-get) | variadic | — | Load a splayed table (columns mmap'd). | +| [`.db.splayed.get`](#db-splayed-get) | variadic | — | Load a splayed table (columns mmap'd; compressed columns decode on first read). | | [`.db.parted.get`](#db-parted-get) | variadic | — | Load a partitioned table by name from a db root. | | [`.db.parted.tables`](#db-parted-tables) | variadic | — | List the table names available under a parted db root. | | [`.db.parted.fill`](#db-parted-fill) | variadic | restricted | Fill missing tables across a parted db's partitions. | @@ -26,6 +26,14 @@ Signatures: - `(.db.splayed.set "dir" tbl)` — write columns to `dir/`; emit a `.sym` file in the same directory. - `(.db.splayed.set "dir" tbl "sym_path")` — write the symbol table to a custom location (typically a shared db-root `.sym`). +- `(.db.splayed.set "dir" tbl opts)` and `(.db.splayed.set "dir" tbl "sym_path" opts)` — the same with an options dict. + +`compress` (dict option, `{compress: true}` or `{compress: false}`): `true` writes generation-2 (compressed) column files where the column is eligible; `false` writes generation 0; when absent each file inherits: generation 2 when its source is an encoded column or the destination's current file is generation 2, else generation 0. Keys other than `compress` and `symfile`, and a non-bool `compress`, are a `domain` error, as is a second options dict. Linked and nested/list columns are always written uncompressed. A compressed file keeps its chunk zones and persists the column's hash, sort, bloom and dictionary index (`.idx.info` shows it), so a reload needs no rebuild. + +`symfile` (dict option, `{symfile: 'shared}` or `{symfile: 'column}`): `'shared`, the default, writes one symbol file for every `SYM` column; `'column` gives each `SYM` column its own, `..sym` next to the column file (in the generation being written), holding that column's vocabulary only. `.db.splayed.get` resolves a column over its own symbol file whenever it has one. `'column` together with an explicit `sym_path`, or for a partition of a parted table, is a `domain` error; so is any other value. + +Compressed F32/F64 writes and whole-column materialization require default FP controls (nearest rounding, masked exceptions, no FTZ/DAZ) on every calling/executing thread. Rayforce never silently normalizes the host's controls. Detected unsupported controls return `fpenv`; restore supported controls before retrying. Detection is not a complete portable validator: see [the compressed floating-point environment contract](../storage/index.md#compressed-floating-point-environment) for conservative refusal scope, platform-specific checks, and embedder responsibilities. + Returns `tbl` (retained), so the call can be threaded inside a larger expression. @@ -45,7 +53,7 @@ Signatures: - `(.db.splayed.get "dir")` — look for `dir/.sym` automatically. - `(.db.splayed.get "dir" "sym_path")` — use a custom symbol-table path (e.g. a shared db-root sym). -Returns a `table` with every column memory-mapped — zero allocation per row. +Returns a `table` with every column memory-mapped. Generation-0 columns are read in place — zero allocation per row; a compressed (generation-2) column decodes into heap memory the first time a query reads it. ```lisp (set loaded (.db.splayed.get "/tmp/weather")) diff --git a/docs/docs/namespaces/idx.md b/docs/docs/namespaces/idx.md index 3b7e7f2fc..4ea322906 100644 --- a/docs/docs/namespaces/idx.md +++ b/docs/docs/namespaces/idx.md @@ -19,7 +19,7 @@ Indexes are dropped automatically when the column is mutated (`alter set`, `upda | [`.idx.bloom`](#idx-bloom) | unary | — | Attach a Bloom filter. | | [`.idx.drop`](#idx-drop) | unary | — | Detach whatever index the vector carries. | | [`.idx.has?`](#idx-has-p) | unary | — | True if the vector carries any index. | -| [`.idx.info`](#idx-info) | unary | — | Dict describing the attached index. | +| [`.idx.info`](#idx-info) | variadic | — | Dict describing the attached index, or a table column's format. | ## `.idx.zone` { #idx-zone } @@ -72,6 +72,24 @@ Signature: `(.idx.info v)`. Returns a dict if the vector carries an index, or th ;; => {kind: 'bloom, length: 5, m_bits: 64, k: 4, n_keys: 5, ...} ``` +Signature: `(.idx.info table 'col)`. Describes a table column's on-disk format without decoding it. Returns a dict: + +| Key | Meaning | +|-----|---------| +| `gen` | `2` for a compressed column, `0` for a plain one (a ragged generation-0 parted table also reports `0`). | +| `enc` | Encoding name (`raw const for_bp delta_bp rle dict alp alp_rd str_dict fsst`) to vector count, nonzero counts only; empty for generation 0. | +| `encoded_bytes` | Bytes of the encoded column file (a parted column sums its segments). A synthetic stand-in segment (a ragged partition's absent column) adds nothing to `encoded_bytes` or the `enc` counts but does count in `raw_bytes`, and a plain parted segment counts its raw bytes. | +| `raw_bytes` | Bytes of the column as a plain vector (a string column includes its pool). | +| `materialized` | `true` once the plain column has been decoded and cached. | +| `index` | Generation 0: `.idx.info` of the attached index. Generation 2: the recorded index kind (`'none` when none); never materializes. | +| `segments` | Parted column only: the segment count. | + +```lisp +(set T (.db.splayed.get "trades/")) +(.idx.info T 'price) +;; => {gen: 2, enc: {alp: 196}, encoded_bytes: ..., raw_bytes: ..., materialized: false, index: 'none} +``` + ## See also - [Indexes Overview](../queries/indexes-overview.md) — when each kind helps and the query patterns it accelerates. diff --git a/docs/docs/namespaces/log.md b/docs/docs/namespaces/log.md index 9b44be8aa..fdea10bdf 100644 --- a/docs/docs/namespaces/log.md +++ b/docs/docs/namespaces/log.md @@ -13,8 +13,8 @@ The journal is intentionally minimal: there's no per-entry timestamp or transact |---|---|---|---| | [`.log.open`](#log-open) | variadic | restricted | Open a journal in async or sync mode. | | [`.log.write`](#log-write) | unary | — | Append a serialised expression to the open journal. | -| [`.log.sync`](#log-sync) | variadic | — | `fsync` the journal. | -| [`.log.snapshot`](#log-snapshot) | variadic | restricted | Write a snapshot of current state and roll to a fresh segment. | +| [`.log.sync`](#log-sync) | nullary | — | `fsync` the journal. | +| [`.log.snapshot`](#log-snapshot) | nullary | restricted | Write a snapshot of current state and roll to a fresh segment. | | [`.log.roll`](#log-roll) | nullary | restricted | Close the active segment and start a new one. | | [`.log.replay`](#log-replay) | unary | restricted | Replay a journal file; return entry count. | | [`.log.validate`](#log-validate) | unary | — | Scan a journal file; return `(chunks valid_bytes)`. | diff --git a/docs/docs/namespaces/mem.md b/docs/docs/namespaces/mem.md index f86d49a93..a2dfff4ee 100644 --- a/docs/docs/namespaces/mem.md +++ b/docs/docs/namespaces/mem.md @@ -30,7 +30,9 @@ allocator tuning. It is an in-memory size, not a serialized-wire size. Signature: `(.mem.ts expression)`. `.mem.ts` is a special form: it evaluates `expression` exactly once inside a -process-wide measurement scope. Secondary-worker allocations and worker busy +process-wide measurement scope. A deferred (lazy) result, such as a bare +`(sum v)`, is materialized inside the scope, so the time, allocation and worker +figures include its computation. Secondary-worker allocations and worker busy time are included. Result sizing and construction of the returned statistics dictionary happen after the time/allocation scope closes. diff --git a/docs/docs/namespaces/parquet.md b/docs/docs/namespaces/parquet.md index 46103ed2e..eafcf9069 100644 --- a/docs/docs/namespaces/parquet.md +++ b/docs/docs/namespaces/parquet.md @@ -83,7 +83,7 @@ Retaining batches increases memory use. ## `.parquet.splayed` { #parquet-splayed } Convert into a new native directory and return the row count. The optional -argument is a type vector or `{types: [...] rows: n strict: true}`. For example, +argument is a type vector or `{types: [...] rows: n strict: true compress: true}`. For example, a source containing an integer ID and text can be imported as: ```lisp @@ -109,3 +109,27 @@ output, and publish it without replacing an existing destination. Failed staging data is retained; existing staging directories are rejected. Imports do not support resume or append. Format or conversion failures return `parquet` errors; argument, I/O, allocation, and cancellation errors also propagate. + +The options dict also takes `compress`: `true` writes generation-2 +(compressed) column files where the column is eligible, `false` (or no +option, since the destination is always new) generation 0. A non-bool +`compress` or a second options dict is a `domain` error. Compressed files keep their chunk zones and persist the same indexes a generation-0 save does, because the import writes through the same splayed-table writer as `.db.splayed.set`. +For example: + +```lisp +(.parquet.splayed {compress: true} "events.parquet" "/tmp/events-native") +(.parquet.parted {compress: true rows: 262144} "events.parquet" "/tmp/events-db" 'events) +``` + +`.parquet.splayed` also takes `symfile`: `'shared` (the default) writes one +`.sym` for every `SYM` column; `'column` gives each `SYM` column a symbol file +of its own, `..sym` next to the column file, so a scan of one column +(`like`, a grouping that resolves its strings) reads that column's strings +only. A string that several columns hold is then stored once per column. +`.db.splayed.get` finds the per-column files by themselves. Any other value is +a `domain` error, and `.parquet.parted` refuses `'column`: every partition of a +parted table resolves over the one root `.sym`. + +```lisp +(.parquet.splayed {types: [I64 SYM SYM] symfile: 'column} "hits.parquet" "/tmp/hits") +``` diff --git a/docs/docs/namespaces/sys.md b/docs/docs/namespaces/sys.md index f1c8a1e87..a3d6fd7b6 100644 --- a/docs/docs/namespaces/sys.md +++ b/docs/docs/namespaces/sys.md @@ -11,9 +11,9 @@ Process-level introspection (build, memory, host info) and command-style operati |---|---|---|---| | [`.sys.args`](#sys-args) | variadic | — | Command-line arguments as a typed dict. | | [`.sys.build`](#sys-build) | nullary | — | Version + build date as a dict. | -| [`.sys.info`](#sys-info) | variadic | — | Host and process facts: cores, page size, total memory, pid, hostname. | -| [`.sys.mem`](#sys-mem) | variadic | — | Allocator statistics. | -| [`.sys.prof`](#sys-prof) | variadic | — | Last profiled query's per-step statistics as a table. | +| [`.sys.info`](#sys-info) | nullary | — | Host and process facts: cores, page size, total memory, pool size, pid, hostname. | +| [`.sys.mem`](#sys-mem) | nullary | — | Allocator statistics. | +| [`.sys.prof`](#sys-prof) | nullary | — | Last profiled query's per-step statistics as a table. | | [`.sys.querylog`](#sys-querylog) | variadic | — | Ambient per-query statistics ring as a table. | | [`.sys.querylog.enable`](#sys-querylog-enable) | variadic | restricted | Toggle query-statistics logging. | | [`.sys.gc`](#sys-gc) | variadic | — | Run allocator maintenance and return `0`. | @@ -39,7 +39,7 @@ Signature: `(.sys.args)`. Returns the process's command-line arguments as a dict | `source` | str | — | The file currently being evaluated: the innermost `load`, or the command-line script, by the path that was actually opened. Empty at the REPL, under a pipe, or in a hook or timer that runs outside any file. `file` is the script named on the command line (`$0`); `source` follows nested loads (`$BASH_SOURCE`). | | `user` | dict | after `--` | The application's own arguments. | -The top-level schema is **stable** — every launcher key is always present with its effective value (the default when the flag wasn't passed), so `(get (.sys.args) 'port)` never misses. Auth passwords (`-u` / `-U`) are deliberately **not** exposed. +The top-level schema is **stable** — every launcher key is always present with its effective value (the default when the flag wasn't passed), so `(get (.sys.args) 'port)` never misses. Auth passwords (`-u` / `-U`) and the RAM budget (`-m` / `--mem`) are deliberately **not** exposed; the effective budget is [`anon-watermark`](#sys-mem) in `(.sys.mem)`. ```lisp ;; load a sibling of the running file, whichever directory it was started from @@ -75,12 +75,15 @@ Signature: `(.sys.build)`. Returns a dict with `version` (string) and `build-dat ## `.sys.info` { #sys-info } -Signature: `(.sys.info)`. Returns `{cores: i64, page-size: i64, total-mem: i64, pid: i64, hostname: str}` on every platform (on Windows from `GetSystemInfo` / `GlobalMemoryStatusEx`). +Signature: `(.sys.info)`. Returns `{cores: i64, page-size: i64, total-mem: i64, workers: i64, pid: i64, hostname: str}` on every platform (on Windows from `GetSystemInfo` / `GlobalMemoryStatusEx`). + +- `cores`: the CPUs this process may run on. On Linux that is its affinity mask, which `taskset`, a cpuset or `docker --cpuset-cpus` may narrow below the machine's CPU count. +- `workers`: the threads of the execution pool, main included; before the pool exists, the size it will get. `.sys.info` does not create the pool (see [Running Several Instances](../guides/instances.md)). ```lisp (.sys.info) ;; => {cores: 10, page-size: 16384, total-mem: 68719476736, -;; pid: 48213, hostname: "tp-prod-01"} +;; workers: 10, pid: 48213, hostname: "tp-prod-01"} ``` `pid` and `hostname` describe *this process*, not the machine, and exist so an @@ -104,7 +107,8 @@ call — one unavailable field should not cost the caller the others. ## `.sys.mem` { #sys-mem } -Signature: `(.sys.mem)`. Returns the buddy allocator's running counters: +Signature: `(.sys.mem)`. Returns the allocator's running counters, the spill +watermark, a few diagnostic counters and the symbol-table size, all `i64`: | Key | Meaning | |---|---| @@ -116,19 +120,45 @@ Signature: `(.sys.mem)`. Returns the buddy allocator's running counters: | `sys-current` | **Committed RAM**: every anonymous mapping — the buddy pools (where all vectors live), sys allocations, and the swap-fallback pool. The true live-memory figure. | | `sys-mapped` | **File-backed** bytes currently mapped (splayed columns, the symbol file, CSV/script parse buffers). Page-cache, evictable, resident only on touch — kept separate from `sys-current` so a read-once column can't masquerade as live RAM. | | `sys-mapped-peak` | High-watermark of `sys-mapped`. | +| `anon-committed` | **Anonymous RAM** the heap has committed: buddy pools, direct blocks and sys blocks (off-heap tables such as the symbol arenas). Spill-file mappings are not counted. The figure checked against `anon-watermark`. | +| `anon-peak` | High-watermark of `anon-committed` since process start — the peak RAM the workload demanded, spill excluded. | +| `anon-watermark` | **Spill threshold** in bytes: a new pool, direct or sys block that would push `anon-committed` past it is mapped over a disk spill file instead of anonymous RAM. Set by `-m SIZE` / `--mem SIZE`; by default the RAM limit (physical RAM, or the cgroup memory limit when smaller) less a quarter of it, at least 3 GiB and at most half, left to the page cache. | +| `locked-bytes` | Bytes of the heap's mappings locked against swap-out (Linux): the mapped size, which is what `RLIMIT_MEMLOCK` counts, not the resident pages — a page is locked when it is first touched. At most the smaller of `anon-watermark` and half the RAM limit. | +| `lock-failed` | Times the kernel refused a lock, or a page release could not lock its range again, since start. | +| `lock-skipped` | Bytes, summed since start, that the heap mapped under the watermark but left unlocked: past the bound, past `RLIMIT_MEMLOCK`, or refused. The heap works on, unlocked. | +| `group-perpart-runs` | Diagnostic: results served by the streaming parted `by:` (GROUP) kernel — one per query, not per partition; a run that falls back to the flatten path is not counted. | +| `asof-perpart-runs` | Diagnostic: days processed by the streaming parted asof join — one per day in the union of both sides' partitions. | +| `sort-perpart-runs` | Diagnostic: partitions processed by the streaming parted `asc:` / `desc:` paths (ordered concat of pre-sorted partitions, or per-partition top-k). | +| `window-perpart-runs` | Diagnostic: segments processed by the streaming parted window path (the window's partition key includes the table's partition key). | +| `join-perpart-runs` | Diagnostic: segments processed by the broadcast-streaming join (one side parted, each segment joined against the whole other side). | +| `sym-count` | Entries in the global symbol table. | +| `sym-bytes` | Bytes held by the symbol table's string arena (every interned name). | Every mapping — buddy pool or file — is counted exactly once through the VM wrapper layer, so `sys-current` reflects the real committed footprint (a large -`til` shows up here, not as a flat few MB). There is **no enforced memory -ceiling**: the heap is out-of-core and spills to a file-backed mapping when -anonymous `mmap` is refused. Total physical RAM is reported separately by -[`.sys.info`](#sys-info) as `total-mem`; compare it against -`bytes-allocated + direct-bytes` to gauge how close a workload is to spilling. +`til` shows up here, not as a flat few MB). `anon-watermark` is a **spill +threshold, not a hard cap**: work past it is never rejected, it goes to a +file-backed spill mapping (as it does when anonymous `mmap` is refused) +instead of risking the OOM killer — see +[out-of-core spill](../guides/memory.md#8-total-ram-and-out-of-core-spill). +Compare `anon-committed` against `anon-watermark` to gauge how close a +workload is to spilling; total physical RAM is reported separately by +[`.sys.info`](#sys-info) as `total-mem`. + +The `*-perpart-runs` keys are monotonic diagnostic counters: a delta across a +query shows whether a parted table was streamed partition by partition +instead of flattened. `sym-count` / `sym-bytes` show whether a query left the +symbol table where it found it. ```lisp (.sys.mem) -;; => {alloc-count: 12345, bytes-allocated: 524288, peak-bytes: 2097152, -;; sys-current: 34754560, sys-mapped: 0, sys-mapped-peak: 0} +;; => {alloc-count: 786, bytes-allocated: 28672, direct-bytes: 0, +;; peak-bytes: 28672, slab-hits: 354, sys-current: 34836480, +;; sys-mapped: 0, sys-mapped-peak: 0, anon-committed: 34795520, +;; anon-peak: 34799616, anon-watermark: 50178081792, +;; group-perpart-runs: 0, asof-perpart-runs: 0, sort-perpart-runs: 0, +;; window-perpart-runs: 0, join-perpart-runs: 0, +;; sym-count: 424, sym-bytes: 30336} ``` ## `.sys.prof` { #sys-prof } diff --git a/docs/docs/queries/joins.md b/docs/docs/queries/joins.md index 2bd42f551..fc7d9776d 100644 --- a/docs/docs/queries/joins.md +++ b/docs/docs/queries/joins.md @@ -56,6 +56,13 @@ string key on the other side. The `left-join` function keeps all rows from the left table. Unmatched rows have null in the right-side columns. +When each left row produces exactly one output row in its original position, +the flat join executor retains ordinary left columns instead of copying them. +Slice-valued columns still use an independent gather because copying a slice +header does not detach its parent payload. +Subsequent updates use copy-on-write, preserving the source and result as +independent values. Duplicate matches still expand and gather the rows. + ### Signature `(left-join [keys] left right)` diff --git a/docs/docs/queries/select.md b/docs/docs/queries/select.md index 9009fb7c8..926599bbf 100644 --- a/docs/docs/queries/select.md +++ b/docs/docs/queries/select.md @@ -82,21 +82,46 @@ aggregate's argument a name that is a source column is always the source column, so `s: (sum s) mx: (max s)` takes the maximum of the rows, not of a sum. An aggregate cannot be aggregated again, through an alias or written out: `s: (sum price) mx: (max s)` and `mx: (max (sum price))` both raise -`domain`. And an output may not put a source column beside a per-group -value outside an aggregate: `f: (* price n)` with `n: (count price)` raises +`domain`. And an output may not mix a source column with a reference to an earlier +per-group alias outside an aggregate: `f: (* price n)` with `n: (count price)` raises `domain`; write `(* (sum price) n)` or whichever aggregate is meant. +The names `min` and `max` reduce only in their **one-argument** forms. +Their two-argument forms are element-wise expressions, as outside a query: +`r: (min x y)` preserves the input rows, and in a grouped select produces a +vector for each group. In contrast, `r: (min (sum x) (sum y))` compares two +per-group scalars; it is not a nested reduction. Genuine unary nesting such +as `r: (min (sum x))` still raises `domain` in a grouped select. + A literal symbol inside a select resolves to an earlier alias or a source column of that name, in that order; one naming neither stays a constant symbol. Arithmetic on a symbol — a literal or a symbol column — is a `type` error inside a select, as it is outside. +Equality (`==`) and inequality (`!=`) between a non-null symbol and a +non-null numeric or boolean value also raise `type`, rather than comparing +internal symbol IDs. Those IDs are not numeric values and can differ +between in-memory and file-backed symbol domains. Null operands retain the +ordinary comparison builtin's value-sensitive null rules; this is not a +blanket error based only on declared column types. + +To use a symbol that is also a column name as a constant, write it as +`(quote name)` or pass it in through a variable. `enlist` does not escape it: +its argument resolves first, so `(enlist 'price)` enlists the `price` column. + +```lisp +(set t (table [sym price] (list [AAPL GOOG price] [10 20 30]))) +(select {from: t x: (== sym 'price)}) ; error: type, compares SYM with the I64 column +(select {from: t x: (== sym (quote price))}) ; x: [false false true] +``` + ### Whole-column projections -A projection may be a whole-column verb — `distinct`, `asc`, `desc`, or -`reverse` — applied to a column. Unlike a per-row computed expression, these -consume the entire column and return a vector, so the result's row count can -differ from the source table (`distinct` in particular collapses duplicates): +A projection may be a whole-column verb — `distinct`, `asc`, `desc`, +`reverse`, or `where` — applied to a column. Unlike a per-row computed +expression, these consume the entire column and return a vector, so the +result's row count can differ from the source table (`distinct` in particular +collapses duplicates, `where` keeps the positions of the true rows): ```lisp (select {price: (distinct price) from: t}) @@ -109,10 +134,19 @@ differ from the source table (`distinct` in particular collapses duplicates): (select {price: (asc price) from: t}) ; ascending column ``` -A `where:` clause is applied first, so the verb only sees the surviving rows: +A `where:` clause is applied first, so the verb only sees the surviving rows. +The positions `where` returns count those rows, not the table's: ```lisp (select {price: (distinct price) from: t where: (> volume 400)}) + +(set m (table [k v] (list [1 1 2 2 2] [10 20 30 40 50]))) +(select {w: (where (> v 20)) from: m where: (> k 1)}) +; w +; - +; 0 +; 1 +; 2 ``` Because a whole-column verb changes the row count, it cannot be mixed with a @@ -143,6 +177,35 @@ Combine multiple conditions: ; GOOG 280 400 ``` +### Running functions under `where:` + +A running, moving or shift function in a projection (`sums`, `deltas`, +`msum`, `lag` and the rest) runs over the whole table, rows the `where:` +drops included, and the query then keeps the `where:` rows. An aggregate +nested inside such a function sees the whole table too; an aggregate on its +own sees the surviving rows: + +```lisp +(set r (table [name room score] (list ['Ann 'Bob 'Cid 'Dan] ['A 'B 'A 'B] [60 20 45 35]))) +(select {s: (sums score) from: r where: (== room 'A)}) ; s: [60 125] +(select {s: (avg score) from: r where: (== room 'A)}) ; s: [52.5] +(select {s: (sums (- score (avg score))) from: r where: (== room 'A)}) ; s: [20.0 5.0] +``` + +In the last query `avg` averages all four rows (40), the running sum of +`20 -20 5 -5` is `20 0 5 0`, and rows A keep `20` and `5`. A select used as +`from:` establishes its own input, so to run over the surviving rows only, +select them first: + +```lisp +(set a (select {from: r where: (== room 'A)})) +(select {s: (sums score) from: a}) ; s: [60 105] +(select {s: (sums (- score (avg score))) from: a}) ; s: [7.5 0.0] +``` + +The [whole-column verbs](#whole-column-projections) (`distinct`, `asc`, +`desc`, `reverse`, `where`) are different: they see the surviving rows only. + ### Group-by Aggregation The `by:` clause groups rows by one or more key columns. Aggregation functions are specified as additional key-value pairs in the query dict: @@ -184,6 +247,79 @@ Expressions over aggregates work with any number of keys and with binary aggrega (select {from: trades r2: (pow (pearson_corr price size) 2) by: {sym: sym}}) ``` +A `by:` name that reads no column — a lambda parameter or a `let` (which +hides a column of its name), or a global holding a vector — groups by the +values it holds, under its own name. It must hold one value per row of the +table; a key of any other length raises `length`, under a `where:` too (the +key meets the rows the filter keeps): + +```lisp +(set t (table [g x] (list [a a b b b c c c c c] (til 10)))) +(set K [1 1 1 1 1 2 2 2 2 2]) +(select {s: (sum x) by: K from: t}) ; K [1 2], s [10 35] +((fn [g] (select {s: (sum x) by: g from: t})) K) ; the same: g is K +(set K3 [1 2 3]) +(select {s: (sum x) by: K3 from: t}) ; error: length +``` + +### Aggregate sources + +What an aggregate reads depends on what its argument is. A column, or an +expression over columns, gives one value per row, and each group aggregates +its own rows. An argument that reads no column follows one of two rules, +depending on whether it is written as a value or computed. + +A vector written as a value — a literal, a global holding one, or a bound +value: a lambda parameter or a `let`, which hides a column of its name — +stands for a column: + +- a vector as long as the table is sliced per group, and filtered by + `where:` like any column (the table's rows before the filter); +- a one-element vector, like an atom, is spread over the rows: `(sum [7])` + and `(sum 7)` over ten rows are `70`; +- a vector of any other length raises a `length` error; +- `count` keeps a vector's own length: `(count [1 2 3])` is `3` in every + group; +- `count (distinct v)` of a bound vector counts the distinct values of the + whole collection, the same in every group, whatever its length or name. + A helper whose body reads a column, itself or through another helper, + reads the rows: `(count (distinct (f)))` with `f` = `(fn [] y)` counts + each group's values of `y`. + +```lisp +(set t (table [g x] (list [a a b b b c c c c c] (til 10)))) +(set W (* 10 (til 10))) +(select {s: (sum W) by: g from: t}) +; g s +; - --- +; a 10 +; b 90 +; c 350 +(select {s: (sum W) by: g from: t where: (> x 2)}) ; s [70 350] +(select {s: (sum [1 2 3]) by: g from: t}) ; error: length +((fn [v] (select {d: (count (distinct v)) by: g from: t})) [1 1 2 2 3 3 4 4 5 5]) +; d [5 5 5] +``` + +A computed argument that reads no column — `(til 5)`, `(at [1 2 3] 0)`, an +expression of constants, a call of a single-expression helper included — is +evaluated once for the whole query, not once per row or per group, so a side +effect in it runs once. A helper with several statements is not inlined and +runs once per group. A collection it +returns is aggregated as it stands, as outside a select, and gives the same +value in every group; a scalar stands for every row, as `1` does in +`(sum 1)`, which counts the rows: + +```lisp +(select {s: (sum (til 5)) by: g from: t}) ; s [10 10 10] +(select {s: (count (til 5)) by: g from: t}) ; s [5 5 5] +(select {s: (sum (at [1 2 3] 0)) by: g from: t}) ; s [2 3 5], the group sizes +``` + +The two rules answer differently for equal values: over the ten rows above, +`(sum (til 3))` is `3` while `(sum [0 1 2])` raises `length`, and +`(sum (take [7 8] 1))` is `7` while `(sum [7])` is `70`. + ### Filter + Group-by Filter first, then group by. Chain two `select` calls for correct results: @@ -227,6 +363,11 @@ Mix ascending and descending with separate clauses. Sort priority follows the or (select {from: t asc: sym desc: price}) ``` +The sort is stable: rows that tie on every sort key keep the order in which +they first appear in the source, and in a grouped select the group whose first +source row comes first wins a tie. A `take:` after the sort therefore returns +the same rows on every run, on in-memory, splayed and parted tables alike. + ### Limiting Rows with `take:` Limit the number of rows in the result. Positive values take from the beginning, negative from the end: @@ -427,4 +568,4 @@ To remove rows matching a predicate, use `select` with the inverse condition: | *delete rows* | `(select {from: t where: (not pred)})` | Remove matching rows via inverse filter | !!! note "Execution model" - All `select` and `update` queries compile to a lazy DAG. The optimizer applies predicate pushdown, filter reordering, operator fusion, and dead-code elimination before the fused morsel-driven executor processes data in 1024-element chunks. + Supported `select` and `update` expression shapes compile to a lazy DAG. The optimizer applies predicate pushdown, filter reordering, operator fusion, and dead-code elimination before the fused morsel-driven executor processes data in 1024-element chunks. Other expression shapes can use language-evaluator fallbacks to preserve their semantics; not every expression is fused. diff --git a/docs/docs/reference/all-functions.md b/docs/docs/reference/all-functions.md index 13accb781..e073ec148 100644 --- a/docs/docs/reference/all-functions.md +++ b/docs/docs/reference/all-functions.md @@ -153,9 +153,9 @@ Boolean logic operators. Work on scalars and vectors alike. | Function | Type | Flags | Description | Example | |---|---|---|---|---| -| `and` | binary | — | Logical AND | `(and true false)` → `false` | -| `or` | binary | — | Logical OR | `(or true false)` → `true` | -| `not` | unary | — | Logical NOT | `(not true)` → `false` | +| `and` | binary | — | Logical AND; element-wise on vectors and lists (lengths must match) | `(and true false)` → `false` | +| `or` | binary | — | Logical OR; element-wise on vectors and lists (lengths must match) | `(or true false)` → `true` | +| `not` | unary | — | Logical NOT; element-wise on vectors and lists | `(not true)` → `false` | ```lisp ; Combine filters with logic ops @@ -175,8 +175,8 @@ Aggregation functions reduce vectors to scalar values. Functions marked **aggr** | `any` | unary | aggr | True if any non-null numeric element is truthy; empty/all-null returns `false` | `(any [0 0 3])` → `true` | | `count` | unary | aggr | Count of elements | `(count [1 2 3])` → `3` | | `avg` | unary | aggr | Arithmetic mean | `(avg [1 2 3])` → `2.0` | -| `min` | unary aggr, or binary | aggr/atomic | Reduce one vector, or choose the element-wise minimum of two values | `(min [3 9 1] [2 10 4])` → `[2 9 1]` | -| `max` | unary aggr, or binary | aggr/atomic | Reduce one vector, or choose the element-wise maximum of two values | `(max [3 9 1] 5)` → `[5 9 5]` | +| `min` | unary aggr, or binary | aggr/atomic | Reduce one vector, or choose the element-wise minimum of two values, in their promoted type (null lowest) | `(min [3 9 1] [2 10 4])` → `[2 9 1]`, `(min 1 2.5)` → `1.0` | +| `max` | unary aggr, or binary | aggr/atomic | Reduce one vector, or choose the element-wise maximum of two values, in their promoted type (null lowest) | `(max [3 9 1] 5)` → `[5 9 5]`, `(max [2 0] true)` → `[2 1]` | | `first` | unary | — | First element of a vector | `(first [10 20 30])` → `10` | | `last` | unary | — | Last element of a vector | `(last [10 20 30])` → `30` | | `med` | unary | aggr | Median value (returns f64) | `(med [1 3 2])` → `2.0` | @@ -218,7 +218,7 @@ Functions that take other functions as arguments for mapping, folding, and filte | Function | Type | Flags | Description | Example | |---|---|---|---|---| | `map` | variadic | — | Apply function to each element (returns a list) | `(map (fn [x] (* x 2)) [1 2 3])` → `(2 4 6)` | -| `pmap` | variadic | — | Parallel map (multi-threaded, returns a list) | `(pmap (fn [x] (* x x)) [1 2 3])` → `(1 4 9)` | +| `pmap` | variadic | — | Currently a sequential alias for `map` (returns a list) | `(pmap (fn [x] (* x x)) [1 2 3])` → `(1 4 9)` | | `fold` | variadic | — | Reduce with function and initial value | `(fold + 0 [1 2 3])` → `6` | | `fold-left` | variadic | — | Left-associative fold | `(fold-left - 10 [1 2 3])` → `4` | | `fold-while` | variadic | — | Fold that stops when the accumulator fails pred | `(fold-while (fn [a] (< a 100)) + 0 (til 1000))` → `105` | @@ -236,7 +236,7 @@ Functions that take other functions as arguments for mapping, folding, and filte ; Transform each row with map (map (fn [x] (* x x)) [1 2 3 4]) ; (1 4 9 16) -; Parallel map for expensive computation +; pmap currently uses the same sequential callback loop as map (pmap (fn [t] (sum (til t))) [100 200 300]) ; Running sum with scan @@ -259,15 +259,15 @@ Query `concat` joins text row by row when an operand comes from a source column, | `except` | binary | — | Set difference (elements in A not in B) | `(except [1 2 3] [2])` → `[1 3]` | | `union` | binary | — | Set union (deduplicated) | `(union [1 2] [2 3])` → `[1 2 3]` | | `sect` | binary | — | Set intersection | `(sect [1 2 3] [2 3 4])` → `[2 3]` | -| `take` | binary | — | Take first N elements (negative N takes from end) | `(take [10 20 30] 2)` → `[10 20]` | +| `take` | binary | — | Take first N elements (negative N takes from end); past the length it cycles. A parted table handle (`.db.parted.get`) is taken as its flat table: the same rows `(at table (til n))` returns, cycling past the row count | `(take [10 20 30] 2)` → `[10 20]`; `(take [1 2 3] -5)` → `[2 3 1 2 3]` | | `drop` | binary | — | Drop first N elements (negative N drops from end) | `(drop [10 20 30] 1)` → `[20 30]` | | `rotate` | binary | — | Rotate left by N positions (negative rotates right) | `(rotate [1 2 3 4] 1)` → `[2 3 4 1]` | | `cut` | binary | — | Split a collection at sorted 0-based indices | `(cut [1 2 3 4] [2])` → `([1 2] [3 4])` | | `cross` | binary | — | Cartesian product as pairs | `(cross [1 2] ['a 'b])` → `((1 'a) (1 'b) (2 'a) (2 'b))` | -| `at` | binary | — | Index a collection; vector keys batch dictionary lookups | `(at [10 20 30] 1)` → `20` | +| `at` | binary | — | Index a collection; vector keys batch dictionary lookups. A typed vector indexed by an integer vector keeps its type: a null or out-of-range index gives the type's null (`false`/`0x00` for BOOL/U8) | `(at [10 20 30] 1)` → `20`, `(at [10 20 30] [2 9])` → `[30 0Nl]` | | `find` | binary | — | Find index of first occurrence | `(find [10 20 30] 20)` → `1` | | `fill` | binary | atomic | Replace null values; the replacement is the first argument | `(fill 0 [1 0Nl 3])` → `[1 0 3]` | -| `reverse` | unary | — | Reverse element order | `(reverse [1 2 3])` → `[3 2 1]` | +| `reverse` | unary | — | Reverse element order; a table reverses its rows (columns and types kept), a dictionary its entries (keys and values together) | `(reverse [1 2 3])` → `[3 2 1]` | | `til` | unary | — | Generate range [0..n) | `(til 5)` → `[0 1 2 3 4]` | | `lag` | unary | lazy/DAG | Shift values one row back; first row is null/sentinel | `(lag [10 20 30])` → `[0Nl 10 20]` | | `lead` | unary | lazy/DAG | Shift values one row forward; last row is null/sentinel | `(lead [10 20 30])` → `[20 30 0Nl]` | @@ -363,16 +363,16 @@ Special forms receive their arguments unevaluated. These are the core language p |---|---|---|---|---| | `set` | binary | special, restricted | Bind value to global variable | `(set x 42)` | | `let` | binary | special | Bind value to local variable (lexical scope) | `(let y (+ x 1))` | -| `if` | variadic | special | Conditional: (if cond then else) | `(if (> x 0) "pos" "neg")` | +| `if` | variadic | special | Conditional: (if c1 r1 c2 r2 ... else?) — first truthy condition wins | `(if (> x 0) "pos" "neg")` | | `do` | variadic | special | Sequential execution, returns last value | `(do (set x 1) (set y 2) (+ x y))` | | `while` | variadic | special | Iterate while cond is truthy; returns null | `(while (> n 0) (set n (- n 1)))` | -| `times` | variadic | special | Run body exactly n times (count evaluated once); returns null | `(times 5 (set n (+ n 1)))` | +| `times` | variadic | special | Run body exactly n times (count evaluated once); `(times [i n] ...)` binds `i` to 0..n-1, one per pass; returns null | `(times 5 (set n (+ n 1)))`, `(times [i 3] (println i))` | | `fn` | variadic | special | Create lambda function | `(fn [x y] (+ x y))` | | `try` | binary | special | Error handling: (try expr handler-fn-or-fallback-value) | `(try (/ 1 0) (fn [e] 0))` | | `raise` | unary | — | Throw an error with message | `(raise "bad input")` | | `return` | unary | — | Early return from function body | `(return 42)` | | `quote` | variadic | special | Return argument unevaluated; a bare name yields a literal symbol (`(quote x)` ≡ `'x`) | `(quote (+ 1 2))` → `(+ 1 2)` | -| `alter` | variadic | special | In-place mutation of table column | `(alter trades 'price (* price 1.1))` | +| `alter` | variadic | special | Amend a global binding in place and return its name: `(alter 'name set idx val)` writes `val` at an index or index vector, `(alter 'name concat vals)` appends, `(alter 'name remove idx)` drops list items. The target must be a global binding; a name bound by `let` or a parameter of the enclosing function raises `domain` | `(alter 'v set 0 99)` | | `del` | variadic | special, restricted | Delete columns or rows from table | `(del trades 'temp_col)` | ```lisp @@ -542,7 +542,7 @@ String functions are available as direct builtins. The transform functions are l | `split` | binary | — | Split string by delimiter into a list of strings | `(split "a,b,c" ",")` → `("a" "b" "c")` | | `str-find` | binary | parallel vector | First byte index of a substring; `0Nl` when absent | `(str-find "banana" "na")` → `2` | | `str-join` | binary | — | Join string/symbol atoms, vectors, or lists with a delimiter | `(str-join ["a" "b"] ",")` → `"a,b"` | -| `strlen` | unary | — | Length of each string | `(strlen "hello")` → `5` | +| `strlen` | unary | — | Length of each string. `""` is the STR/SYM null: `strlen` maps it to a null length, `sum` and `avg` skip it, and the `avg` of an all-empty group is null. | `(strlen "hello")` → `5` | | `upper` | unary | lazy/DAG | Uppercase string or symbol atoms/vectors | `(upper ["ab" "Cd"])` → `["AB" "CD"]` | | `lower` | unary | lazy/DAG | Lowercase string or symbol atoms/vectors | `(lower 'AbC)` → `'abc` | | `trim` | unary | lazy/DAG | Strip leading/trailing whitespace | `(trim " abc ")` → `"abc"` | @@ -661,11 +661,11 @@ System interaction, metaprogramming, diagnostics, and runtime inspection. | `.time.timer.set` | variadic | restricted | Schedule callback every `ms`, `num` times (0 = forever); returns id | `(.time.timer.set 1000 0 (fn [t] (println t)))` | | `.time.timer.del` | unary | restricted | Cancel a scheduled timer by id; returns null | `(.time.timer.del 0)` | | `.sys.build` | nullary | — | Build metadata dict with `version` + `build-date` | `(.sys.build)` | -| `.sys.mem` | variadic | — | Memory allocator statistics (alloc / peak / slab hits) | `(.sys.mem)` | -| `.sys.prof` | variadic | — | Last profiled query's per-step statistics as a table (opt-in via `:t`) | `(.sys.prof)` | +| `.sys.mem` | nullary | — | Memory allocator statistics (alloc / peak / slab hits) | `(.sys.mem)` | +| `.sys.prof` | nullary | — | Last profiled query's per-step statistics as a table (opt-in via `:t`) | `(.sys.prof)` | | `.sys.querylog` | variadic | — | Ambient per-query statistics ring as a table (opt-in via `-Q` / `.sys.querylog.enable`) | `(.sys.querylog)` | | `.sys.querylog.enable` | variadic | restricted | Toggle query-statistics logging; returns new state | `(.sys.querylog.enable 1)` | -| `.sys.info` | variadic | — | Host and process info (cores, page size, total memory, pid, hostname) | `(.sys.info)` | +| `.sys.info` | nullary | — | Host and process info (cores, page size, total memory, pid, hostname) | `(.sys.info)` | ```lisp ; Metaprogramming: parse and eval @@ -678,8 +678,8 @@ System interaction, metaprogramming, diagnostics, and runtime inspection. (println (format "%ms" (- (.time.now) t0))) ; System diagnostics -(.sys.info 0) ; OS, CPU cores, memory budget -(.sys.mem 0) ; heap usage statistics +(.sys.info) ; OS, CPU cores, memory budget +(.sys.mem) ; heap usage statistics ``` ## Serialization @@ -707,7 +707,7 @@ Persistent columnar storage — splayed (one file per column) and partitioned ta | Function | Type | Flags | Description | Example | |---|---|---|---|---| -| `.db.splayed.set` | variadic | restricted | Save table as splayed columns to a directory | `(.db.splayed.set "db/trades" trades)` | +| `.db.splayed.set` | variadic | restricted | Save table as splayed columns to a directory; optional `{compress: bool}` | `(.db.splayed.set "db/trades" trades)` | | `.db.splayed.get` | variadic | — | Load splayed table from a directory | `(.db.splayed.get "db/trades")` | | `.db.parted.get` | variadic | — | Load partitioned table from root directory | `(.db.parted.get "db" 'trades)` | | `.db.parted.tables` | variadic | — | List table names under a parted root (from the most recent partition) | `(.db.parted.tables "db")` | diff --git a/docs/docs/storage/index.md b/docs/docs/storage/index.md index e24bcb0a2..4e16dce3a 100644 --- a/docs/docs/storage/index.md +++ b/docs/docs/storage/index.md @@ -34,7 +34,7 @@ A string column file written by the current engine stores the content hash of ev |---|---| | `ray_col_save(vec, path)` | Write a vector to a column file. Handles slices, sentinel nulls, and string pools transparently. | | `ray_col_load(path)` | Read a column file into a heap-allocated vector. The file is read entirely into memory. | -| `ray_col_mmap(path)` | Memory-map a column file for zero-copy access. The returned vector points directly into the mapped file pages. Ideal for large datasets that exceed available RAM. | +| `ray_col_mmap(path)` | Memory-map a column file. A generation-0 file is zero-copy: the returned vector points directly into the mapped file pages. Ideal for large datasets that exceed available RAM. A compressed (generation-2) file is mapped too, but the column decodes into heap memory the first time it is read. | ```c // Save a vector @@ -50,7 +50,7 @@ ray_t* mapped = ray_col_mmap("db/trades/price"); ``` !!! note "Memory-mapped vectors" - Memory-mapped vectors have `mmod = 1` in their header, distinguishing them from heap-allocated vectors. The buddy allocator skips them during free. Slices of mmap'd vectors retain a reference to the parent mapping. + Memory-mapped generation-0 vectors have `mmod = 1` in their header, distinguishing them from heap-allocated vectors; a decoded compressed column is heap memory. The buddy allocator skips them during free. Slices of mmap'd vectors retain a reference to the parent mapping. ## Splayed Tables @@ -79,20 +79,27 @@ all columns into a fresh directory below `.generations/`. After the files are complete, it atomically replaces the small `.current` manifest. Readers follow that manifest, so they see either the previous complete generation or the new complete generation — never a mixture of columns from both. A failed write -before publication leaves the previous generation selected. Tables written by -older Rayforce versions remain readable; the first replacement upgrades the -directory to the generation layout. +before publication leaves the previous generation selected. A cancelled write +reports `cancel` and changes nothing: the previous generation stays selected, +and a cancelled first write leaves no table behind, while files that were +already in the directory before the write are kept. Superseded generations, +and what a failed first write created, are removed afterwards; a symbolic +link found among them is unlinked, never followed, so nothing outside the +table directory is touched. Tables written by older Rayforce versions remain +readable; the first replacement upgrades the directory to the generation +layout. The table, partition and CSV entry points follow the same publication protocol. Indexes are built in the new generation before it is published. The CSV and Parquet converters build each column's chunk zone or string dictionary from the rows as they are streamed and write it with the column, so a conversion -does not read its own output back; only integer columns whose zone qualifies -for a hash index are re-read, one column at a time, to build it. An index -that cannot be written (for example, the disk fills) is dropped and the column -is published without it. Writers to the -same table serialize on `.write.lock`; readers resolve the manifest once and -continue using that generation. The symbol vocabulary stays at its original +does not read its own output back. The converters add no hash index of their +own: a hash index is persisted only when the column carries one built with +`.idx.hash` when the table is saved (a table resaved from an older store keeps +a hash it already has), and a parted conversion builds none for its segments. +An index that cannot be written (for example, the disk fills) is dropped and the +column is published without it. Writers to the same table serialize on +`.write.lock`; readers resolve the manifest once and continue using that generation. The symbol vocabulary stays at its original location and grows append-only. Publication keeps only the selected generation and removes the others @@ -198,6 +205,10 @@ Mounting the same root again on the same thread reuses unchanged partitions whil The cache holds at most 1024 partition tables per thread. GC, symbol-domain opens and the next mount discard entries whose columns have no external references; heap abandonment, heap teardown and runtime shutdown clear the thread's entries. To release a dropped view's mappings and copied LIST values immediately, call `(.sys.gc)`. C callers can also use `ray_parted_cache_clear()` from `store/part.h` to clear their thread's cache. +### Partitions without a column (ragged tables) + +A partition may hold fewer columns than the first one, as long as the columns it has come first in the same order with the same names and types; a column it lacks is a NULL segment for that partition. Such a ragged table reads as the flat table with typed nulls in the missing rows, wherever its rows are read: a select over it (projections, `where:`, `asc:`/`desc:`, `take:`, `by:` and aggregates), `(at table 'col)`, the standalone `take` verb, printing and `show`, and `ser`, whose bytes equal those of the equivalent flat table. The partition-key column's row counts give the missing rows; `BOOL` and `U8`, which have no null, read as `false` and `0`. A parted column met away from its table (through `get` on a column value rather than a query) still contributes no rows for a partition that lacks it. + !!! warning "`update` over a partitioned table materializes in memory" `update` on a partitioned table flattens the whole table into memory first — the parted/`MAPCOMMON` columns cannot be mutated in place — so the result is an ordinary in-memory table. It is **not** written back to the store: re-reading the root returns the original values, and the returned table loses its parted / memory-mapped identity. @@ -211,7 +222,9 @@ The global symbol intern table maps strings to integer IDs. When saving data to ### Append-Only .sym Files -Symbol files use an append-only format. New symbols are appended to the end of the file without rewriting existing entries. This makes concurrent writes safe and enables incremental updates. +A table's symbol file, which `.db.splayed.set` and the importers write, is append-only: new symbols are appended to the end of the file without rewriting existing entries, so a symbol's position never changes and updates are incremental. One process writes a database at a time: a writer whose view of the file is out of date fails with `RAY_ERR_CORRUPT` instead of overwriting another writer's symbols (see [Running Several Instances](../guides/instances.md)). + +The C functions below work on the runtime's global symbol table instead. `ray_sym_save` writes the whole table to a temporary file and renames it over the target, and `ray_sym_load` merges a file into the running table. | Function | Description | |---|---| @@ -232,7 +245,7 @@ ray_sym_load("db/.sym"); ### Concurrency and Integrity - **File locking** — `flock()` on POSIX, `LockFileEx()` on Windows. Multiple processes can safely read the symbol file; writes acquire an exclusive lock. -- **Corruption detection** — symbol files include checksums. If a file is truncated or corrupted, `ray_sym_load()` returns `RAY_ERR_CORRUPT` and leaves the in-memory table unchanged. +- **Corruption detection** — symbol files carry no checksum. The loader checks the magic, the entry count and every entry's length; a truncated or malformed file makes `ray_sym_load()` return `RAY_ERR_CORRUPT`. - **Arena backing** — interned strings are allocated from a dedicated arena (`ray_arena_t`), making bulk allocation fast and ensuring all strings are freed together when the symbol table is destroyed. ## CSV Import and Export @@ -328,9 +341,19 @@ Writes a table as column files to a directory. A symbol table file is saved auto An optional third argument specifies a custom symbol table path: `(.db.splayed.set "/tmp/weather" t "/tmp/my_sym")`. Without it, a `sym` file is created in the table directory. +A trailing options dict selects the column file format: `(.db.splayed.set "/tmp/weather" t {compress: true})`, also after the symbol path. `true` writes generation-2 (compressed) files where eligible, `false` generation 0; when absent each file inherits (generation 2 when its source is an encoded column or the destination's current file is generation 2). Unknown keys or a non-bool value are a `domain` error. Linked, nested/list and explicitly indexed (hash, sort, bloom, part) columns are always written uncompressed. Compressed files keep their chunk zones but carry no persisted hash or dictionary index: a column that a generation-0 save would give one is written without it, and queries over it run without that accelerator. + +### Compressed floating-point environment + +Generation-2 compressed F32/F64 I/O requires **default floating-point controls** on every calling/executing thread: round-to-nearest (`FE_TONEAREST`), masked FP exceptions, and gradual underflow (FTZ and DAZ disabled). Embedders must maintain those controls during calls. Rayforce does not silently change or normalize them; sticky exception status flags need not be clear and arithmetic may set them. Detected unsupported controls produce `fpenv` (`RAY_ERR_FPENV` in C), not a corruption error. Restore supported controls before retrying the same mapped column; an environment failure is transient, not permanently cached. + +The refusal applies conservatively to compressed float writes and whole-column materialization, including decoded-cache hits and non-ALP encodings. ALP range decoding also checks the executing thread. It does not change the file format or require every non-ALP range read to reject nondefault controls. + +Detection is deliberately limited: standard rounding is checked, plus SSE rounding, FTZ/DAZ and exception masks on supported x86 SSE builds. This is **not a complete portable FP-environment validator**: x87 trap masks are not checked, and on other native architectures only standard rounding is checked. WebAssembly has fixed nearest rounding. Maintaining other required controls remains the embedder's responsibility; passing a check is not proof that every control is supported. + ### `.db.splayed.get` — Load a Splayed Table -Loads a splayed table from a directory. Columns are memory-mapped for zero-copy access. +Loads a splayed table from a directory. Columns are memory-mapped: generation-0 files for zero-copy access, while a compressed (generation-2) column decodes into heap memory the first time a query reads it. ```lisp (.db.splayed.get "/tmp/weather") @@ -391,7 +414,7 @@ For every table present in **any** partition, ensures **every** partition has it Symbol tables are persisted automatically when you use `.db.splayed.set`. A `.sym` file is written into the table directory containing all interned symbol strings. When loading with `.db.splayed.get` or `.db.parted.get`, the symbol table is loaded first so that symbol columns decode correctly. -At the C API level, `ray_sym_save(path)` and `ray_sym_load(path)` handle persistence directly. The format is append-only — new symbols are appended without rewriting existing entries, making concurrent access safe. +At the C API level, `ray_sym_save(path)` and `ray_sym_load(path)` handle persistence directly. `ray_sym_save` writes the whole runtime table to a temporary file and renames it over `path`; one process writes a given file. ## Working Example: Round-Trip @@ -425,3 +448,16 @@ A complete workflow: create a table, save it to disk, load it back, and verify t ``` The loaded table is fully functional — you can run `select`, `update`, joins, and aggregations on it just like an in-memory table. Symbol columns resolve correctly because the symbol table was saved and loaded alongside the data. + +## Duration column compatibility + +TIMESPAN uses the concrete type tag 16 and a signed 64-bit nanosecond +payload. Serialization, generation-0 and generation-2 splayed columns, +and partitioned columns preserve the tag and `0Nn` nulls. Tags 14 and 15 +remain internal selection and encoded-column tags. + +Readers built before TIMESPAN support reject the new tag, including when +it appears in a table schema. Upgrade readers before writing duration +columns to shared storage. Existing column tags and format generations +retain their meanings. Parquet logical time and duration mappings are +separate from this column format. diff --git a/include/rayforce.h b/include/rayforce.h index a683794e1..745412f6b 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -87,6 +87,8 @@ const char* ray_git_commit(void); #define RAY_SYM 12 /* Variable-length string column (inline + pool) */ #define RAY_STR 13 +/* Signed nanosecond duration; 14/15 belong to internal selection/encoded columns. */ +#define RAY_TIMESPAN 16 /* Compound types */ #define RAY_INDEX 97 /* Accelerator index attached to a vector (see ops/idxop.h) */ @@ -120,7 +122,8 @@ typedef enum { RAY_ERR_NAME, RAY_ERR_LIMIT, RAY_ERR_RESERVED, - RAY_ERR_VERSION + RAY_ERR_VERSION, + RAY_ERR_FPENV /* unsupported floating-point controls */ } ray_err_t; #define RAY_IS_ERR(p) ((p) != NULL && (uintptr_t)(p) > 31 && ((ray_t*)(p))->type == RAY_ERROR) @@ -254,7 +257,8 @@ extern ray_t __ray_null; extern ray_t __ray_oom; #define RAY_OOM_OBJ (&__ray_oom) -/* Error object creation (defined in core/runtime.c) */ +/* Error object creation (defined in core/runtime.c). With fmt == NULL, + * "fpenv" supplies a default explanatory message; other codes clear it. */ ray_t* ray_error(const char* code, const char* fmt, ...); const char* ray_err_code_str(ray_err_t e); ray_err_t ray_err_from_obj(ray_t* err); @@ -264,6 +268,10 @@ const char* ray_err_code(ray_t* err); * reference and want the block reclaimed must use this helper instead — * otherwise the error leaks until heap teardown. */ void ray_error_free(ray_t* err); +/* Thread-local message of the last error made on this thread (NULL when + * empty), and clearing it. */ +const char* ray_error_msg(void); +void ray_error_clear(void); /* ===== Accessor Macros ===== */ @@ -271,11 +279,14 @@ void ray_error_free(ray_t* err); #define ray_type(v) ((v)->type) #define ray_is_atom(v) ((v)->type < 0 || (v)->type >= RAY_LAMBDA) -#define ray_is_vec(v) ((v)->type >= RAY_BOOL && (v)->type <= RAY_STR) +static inline bool ray_is_vector_type(int8_t type) { + return (type >= RAY_BOOL && type <= RAY_STR) || type == RAY_TIMESPAN; +} +#define ray_is_vec(v) ray_is_vector_type((v)->type) #define ray_len(v) ((v)->len) /* Element type sizes indexed by type tag — covers all uint8_t values. - * Only types 1-14 (vectors) have non-zero entries. */ + * Only concrete vector types and LIST have non-zero entries. */ extern const uint8_t ray_type_sizes[256]; /* Out-of-line slice deref: keeps the hot path of ray_data_fn (a single @@ -519,6 +530,7 @@ ray_t* ray_sym(int64_t id); ray_t* ray_date(int64_t val); ray_t* ray_time(int64_t val); ray_t* ray_timestamp(int64_t val); +ray_t* ray_timespan(int64_t nanoseconds); /* Current UTC wall-clock time as a RAY_TIMESTAMP value (ns since 2000-01-01). * Shared "now as a timestamp" primitive — the single owner of the epoch * conversion; callers must not re-derive it. */ @@ -566,7 +578,8 @@ static inline bool ray_atom_is_null_fn(const union ray_t* x) { return f != f; } case RAY_I64: - case RAY_TIMESTAMP: return x->i64 == NULL_I64; + case RAY_TIMESTAMP: + case RAY_TIMESPAN: return x->i64 == NULL_I64; case RAY_I32: case RAY_DATE: case RAY_TIME: return x->i32 == NULL_I32; @@ -696,6 +709,7 @@ ray_err_t ray_env_set(int64_t sym_id, ray_t* val); * ray_table_ncols / ray_table_nrows -> 0 * ray_table_col_name -> -1 * ray_table_schema / ray_table_get_col* -> NULL + * ray_table_col / ray_table_col_idx -> NULL * ray_table_set_col_name / ray_table_set_col_idx -> no-op * ray_table_add_col -> typed "type" error * ray_table_validate_rectangular -> typed "type" error @@ -711,8 +725,19 @@ ray_err_t ray_env_set(int64_t sym_id, ray_t* val); ray_t* ray_table_new(int64_t ncols); ray_t* ray_table_add_col(ray_t* tbl, int64_t name_id, ray_t* col_vec); ray_t* ray_table_validate_rectangular(ray_t* tbl, const char* context); +/* Borrowed column, or NULL. NULL also covers an encoded column that fails + * to decode (corruption, OOM, cancel, fpenv): these two getters have no error + * channel, so a failed load reads as "no such column". Use ray_table_col / + * ray_table_col_idx below when the reason matters. */ ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id); ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx); +/* Plain column (borrowed; valid for the table's lifetime; retain to keep it + * longer), NULL when absent or `tbl` is not a table, or an owned RAY_ERROR + * when an encoded column fails to materialize (corruption, OOM, cancel, fpenv). + * Compressed float access requires the FP controls documented below under + * Runtime + Rayfall Eval API, including when a decoded cache exists. */ +ray_t* ray_table_col(ray_t* tbl, int64_t name_id); +ray_t* ray_table_col_idx(ray_t* tbl, int64_t idx); int64_t ray_table_col_name(ray_t* tbl, int64_t idx); void ray_table_set_col_name(ray_t* tbl, int64_t idx, int64_t name_id); void ray_table_set_col_idx(ray_t* tbl, int64_t idx, ray_t* col_vec); @@ -763,6 +788,22 @@ ray_t* ray_dict_remove(ray_t* d, ray_t* key_atom); /* COW; consumes * if (RAY_IS_ERR(result)) { ... } else { ...; ray_release(result); } * ray_runtime_destroy(rt); * + * Floating-point controls: generation-2 compressed F32/F64 I/O requires + * default FP controls on every calling/executing thread: round-to-nearest + * (FE_TONEAREST), masked FP exceptions, and gradual underflow (no FTZ/DAZ). + * Embedders must maintain these controls during calls; Rayforce never + * silently normalizes them. Sticky exception status flags need not be clear + * and computations may set them. Detected unsupported controls return + * RAY_ERR_FPENV ("fpenv"), not file corruption; retry is allowed after the + * controls are restored. Checks cover standard rounding, plus SSE rounding, + * FTZ/DAZ and exception masks on supported x86 SSE builds. They are not a + * complete portable FP-environment validator (notably, x87 trap masks are + * not checked). Elsewhere only standard rounding is checked; WebAssembly + * has fixed nearest rounding. Other controls remain the embedder's + * responsibility. This applies to compressed float writes and whole-column + * materialization even if a particular file uses a non-ALP encoding or has + * already been decoded; ALP range decoding also checks executing threads. + * * Single-runtime: only one ray_runtime_t may be live at a time in the * same process. Creating a second without destroying the first is * undefined. Symbols, env, and builtins are process-global; the diff --git a/mkdocs.yml b/mkdocs.yml index bfce5679a..df85bf0da 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -167,7 +167,9 @@ nav: - IPC Guide: docs/guides/ipc.md - Error Handling: docs/guides/errors.md - Memory & Monitoring: docs/guides/memory.md + - Running Several Instances: docs/guides/instances.md - Type Casting: docs/guides/types.md + - Timespan: docs/guides/timespan.md - Architecture: - Pipeline & Optimizer: docs/architecture/pipeline.md - Memory Model: docs/architecture/memory.md diff --git a/src/app/main.c b/src/app/main.c index 43d4dd5a4..57be5efb4 100644 --- a/src/app/main.c +++ b/src/app/main.c @@ -39,6 +39,7 @@ #include #include #include +#include #include #include @@ -82,10 +83,9 @@ static int64_t parse_size_arg(const char* s) { * password, a negative number) stays legal — refusing those would break * working command lines for no gain. * - * Keep this list in step with the flags handled in main's parse loop and - * with --help. (ray_build_sys_args in src/ops/system.c walks argv a - * second time for .sys.args; it only ever sees a command line that - * already passed this guard, so it cannot mis-pair.) + * Keep this list in step with the flags handled in main's parse loop, + * ray_build_sys_args in src/ops/system.c, and --help. The .sys.args + * builder walks argv again and must skip every flag's value too. * -------------------------------------------------------------------------- */ static const char* const k_known_flags[] = { "-i", "--interactive", "-p", "--port", "-c", "--cores", @@ -124,6 +124,11 @@ int main(int argc, char** argv) { ray_crash_install(); ray_expr_stats_init(); ray_idx_stats_init(); + /* The heap locks what it maps under the watermark against swap-out + * (heap_lock in mem/heap.c), within RLIMIT_MEMLOCK: the binary lets it + * have the hard limit, not only the soft one. Here and not in the + * runtime: an embedding's process limits are its host's to set. */ + ray_os_raise_memlock(); ray_runtime_t* rt = ray_runtime_create(argc, argv); if (!rt) { fprintf(stderr, "failed to create runtime\n"); return 1; } @@ -184,20 +189,41 @@ int main(int argc, char** argv) { port = (uint16_t)pv; } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--cores") == 0) { - const char* v = flag_value(argc, argv, &i, argv[i]); - if (!v) { ray_runtime_destroy(rt); return 2; } - n_cores = atoi(v); - if (n_cores < 0) n_cores = 0; + const char* flag = argv[i]; + const char* cv = flag_value(argc, argv, &i, flag); + if (!cv) { ray_runtime_destroy(rt); return 2; } + int64_t parsed; + if (!parse_sys_int_arg(cv, true, true, &parsed)) { + fprintf(stderr, "error: %s expects a worker count in 0..%u, got '%s'\n", + flag, (unsigned)(RAY_HEAP_ID_BITS - 1), cv); + ray_runtime_destroy(rt); + return 2; + } + n_cores = (int)parsed; } else if (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--timeit") == 0) { - const char* v = flag_value(argc, argv, &i, argv[i]); + const char* flag = argv[i]; + const char* v = flag_value(argc, argv, &i, flag); if (!v) { ray_runtime_destroy(rt); return 2; } - timeit_init = (atoi(v) != 0); + int64_t parsed; + if (!parse_sys_int_arg(v, false, false, &parsed)) { + fprintf(stderr, "error: %s expects an integer, got '%s'\n", flag, v); + ray_runtime_destroy(rt); + return 2; + } + timeit_init = (parsed != 0); } else if (strcmp(argv[i], "-Q") == 0 || strcmp(argv[i], "--querylog") == 0) { - const char* v = flag_value(argc, argv, &i, argv[i]); + const char* flag = argv[i]; + const char* v = flag_value(argc, argv, &i, flag); if (!v) { ray_runtime_destroy(rt); return 2; } - qlog_init = (atoi(v) != 0); + int64_t parsed; + if (!parse_sys_int_arg(v, false, false, &parsed)) { + fprintf(stderr, "error: %s expects an integer, got '%s'\n", flag, v); + ray_runtime_destroy(rt); + return 2; + } + qlog_init = (parsed != 0); } else if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "--file") == 0) { file = flag_value(argc, argv, &i, argv[i]); @@ -231,7 +257,7 @@ int main(int argc, char** argv) { " -f, --file FILE run script file (or pass as a positional arg)\n" " -p, --port PORT listen for IPC clients on PORT (all interfaces)\n" " --port HOST:PORT bind the listener to HOST only (e.g. 127.0.0.1:7701)\n" - " -c, --cores N total execution cores, main included (0 = auto)\n" + " -c, --cores N decimal digits; 0 = auto, 1..1023 includes main thread\n" " -t, --timeit N enable profiler at startup (N != 0)\n" " -Q, --querylog N enable query logging at startup (N != 0);\n" " read the ring with (.sys.querylog)\n" @@ -292,10 +318,20 @@ int main(int argc, char** argv) { * (file load, REPL eval, builtins). If -c wasn't given, leave the * pool to its lazy default on first use. */ if (n_cores >= 0) { + /* the CPUs this process may run on, or its CPU quota when smaller */ + uint32_t ncpu = ray_pool_default_total(); + if ((uint32_t)n_cores > ncpu) + fprintf(stderr, "warning: -c %d gives %d threads, more than the %u CPU%s this process " + "may use, and they take turns; use -c %u, or drop -c to size the pool " + "to the CPUs\n", + n_cores, n_cores, ncpu, ncpu == 1 ? "" : "s", ncpu); ray_err_t err = ray_pool_init_total((uint32_t)n_cores); - if (err != RAY_OK) - fprintf(stderr, "warning: ray_pool_init_total(%d) failed (%d)\n", + if (err != RAY_OK) { + fprintf(stderr, "error: ray_pool_init_total(%d) failed (%d)\n", n_cores, (int)err); + ray_runtime_destroy(rt); + return 2; + } } /* -t at startup flips the global profiler flag. The REPL reads diff --git a/src/app/repl.c b/src/app/repl.c index 9729d7186..b09009048 100644 --- a/src/app/repl.c +++ b/src/app/repl.c @@ -27,6 +27,7 @@ #define _GNU_SOURCE #endif +#include "store/enccol.h" /* ray_enccol_cache_trim at the statement boundary */ #include "lang/format.h" #include "app/repl.h" #include "app/term.h" @@ -396,11 +397,7 @@ static void print_banner(void) { char cpu[256]; get_cpu_name(cpu, sizeof(cpu)); int64_t mem_mb = get_total_mem_mb(); -#if defined(RAY_OS_WINDOWS) - int ncores = (int)ray_thread_count(); -#else - int ncores = (int)sysconf(_SC_NPROCESSORS_ONLN); -#endif + int ncores = (int)ray_cpu_set_count(); /* the CPUs this process may run on */ /* "Using" count reflects the actual worker-pool size, not ncores. * ray_pool_get() is a lazy initializer — callers might not have @@ -432,11 +429,21 @@ static void print_banner(void) { #define PIPE_BUF_SIZE 4096 +/* The detail printed after an error code: the error's own message, or else + * the value of an uncaught (raise x), which carries no message. `buf` + * holds the rendering; ray_raise_render bounds it to `cap`. */ +static const char* repl_error_detail(char* buf, size_t cap) { + const char* detail = ray_error_msg(); + if (detail) return detail; + return ray_raise_render(buf, cap) ? buf : NULL; +} + /* Format a rich error message with source snippet, carets, and stack trace. */ static void fmt_error_with_trace(FILE* fp, ray_t* err, ray_t* trace, bool use_color) { char err_code[8] = {0}; memcpy(err_code, err->sdata, err->slen < 7 ? err->slen : 7); - const char* detail = ray_error_msg(); + char raised[512]; + const char* detail = repl_error_detail(raised, sizeof(raised)); fprintf(fp, "\n"); if (use_color) fprintf(fp, "\033[1;31m"); @@ -556,7 +563,8 @@ static void repl_print_result(FILE* fp, ray_t* val, bool use_color) { memcpy(err_code, val->sdata, val->slen < 7 ? val->slen : 7); if (use_color) fprintf(fp, "\033[1;31m"); fprintf(fp, "error: %s", err_code); - const char* detail = ray_error_msg(); + char raised[512]; + const char* detail = repl_error_detail(raised, sizeof(raised)); if (detail) fprintf(fp, ": %s", detail); if (use_color) fprintf(fp, "\033[0m"); fprintf(fp, "\n"); @@ -836,6 +844,7 @@ static void eval_and_print(ray_term_t* term, const char* input, ray_t* nfo = ray_nfo_create(RAY_NFO_REPL_NAME, strlen(RAY_NFO_REPL_NAME), input, strlen(input)); ray_clear_error_trace(); + ray_raise_clear(); ray_t* parsed = ray_parse_with_nfo(input, nfo); if (profiling) ray_profile_tick("parse"); @@ -892,6 +901,7 @@ static void eval_and_print(ray_term_t* term, const char* input, } ray_heap_gc(); + ray_enccol_cache_trim(); ray_heap_relieve(); /* Statement boundary. Check BEFORE stamping: the clock still holds the * end of the previous statement, so what we measure is the gap between @@ -1481,6 +1491,7 @@ int ray_repl_run_file(const char* path) { ray_t* nfo = ray_nfo_create(path, strlen(path), buf, nread); ray_clear_error_trace(); + ray_raise_clear(); ray_t* parsed = ray_parse_with_nfo(buf, nfo); if (profiling) ray_profile_tick("parse"); @@ -1532,6 +1543,7 @@ int ray_repl_run_file(const char* path) { * exists to avoid. */ ray_heap_note_activity(); ray_heap_gc(); + ray_enccol_cache_trim(); /* The script's own temporaries — a load, say, before it hands over to a * server's poll loop — go back here under memory pressure, as after a * REPL statement. */ diff --git a/src/core/ipc.c b/src/core/ipc.c index 43041a970..a831540d9 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -25,6 +25,7 @@ #define _GNU_SOURCE #endif +#include "store/enccol.h" /* ray_enccol_cache_trim after a request */ #include "core/ipc.h" #include "core/mcast.h" #include "core/timer.h" @@ -480,6 +481,7 @@ static int conn_tx_drain_blocking(ray_poll_t* poll, ray_selector_t* sel, static void send_response(ray_sock_t fd, ray_t* result, size_t threshold) { + ray_serde_fail_clear(); int64_t ser_size = ray_serde_size(result); /* A result we cannot serialize must never leave the client waiting on @@ -490,8 +492,16 @@ static void send_response(ray_sock_t fd, ray_t* result, size_t threshold) * can put on the wire and we drop as before. */ ray_t* fallback = NULL; if (ser_size <= 0) { - fallback = ray_error("type", "result of type %s is not serializable over IPC", - result ? ray_type_name(result->type) : "null"); + const char* fcode = ray_serde_fail_code(); + if (fcode) { /* an encoded column failed to decode: say so */ + char code[8], msg[256]; + snprintf(code, sizeof code, "%s", fcode); + snprintf(msg, sizeof msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + fallback = ray_error(code, "%s", msg); + } else { + fallback = ray_error("type", "result of type %s is not serializable over IPC", + result ? ray_type_name(result->type) : "null"); + } result = fallback; ser_size = ray_serde_size(result); if (ser_size <= 0) { if (fallback) ray_error_free(fallback); return; } @@ -499,7 +509,22 @@ static void send_response(ray_sock_t fd, ray_t* result, size_t threshold) uint8_t* payload = (uint8_t*)ray_alloc_raw((size_t)ser_size); if (!payload) { if (fallback) ray_error_free(fallback); return; } - ray_ser_raw(payload, result); + int64_t wrote = ray_ser_raw(payload, result); + if (wrote != ser_size) { + /* The write phase disagrees with the size phase (an encoded column + * failed to decode): never send the frame, answer with an error. */ + ray_free_raw(payload); + if (fallback) { ray_error_free(fallback); return; } + fallback = ray_error("io", "result could not be serialized over IPC"); + result = fallback; + ser_size = ray_serde_size(result); + payload = ser_size > 0 ? (uint8_t*)ray_alloc_raw((size_t)ser_size) : NULL; + if (!payload || ray_ser_raw(payload, result) != ser_size) { + if (payload) ray_free_raw(payload); + ray_error_free(fallback); + return; + } + } uint8_t* send_buf = NULL; size_t send_len = 0; @@ -1172,6 +1197,7 @@ static ray_t* ipc_read_payload(ray_poll_t* poll, ray_selector_t* sel) * one between two requests. Stamping on frame arrival instead would * make the measured gap the request's own duration. */ ray_heap_note_activity(); + ray_enccol_cache_trim(); ray_heap_relieve(); return NULL; @@ -1331,7 +1357,11 @@ static ray_poll_frame_t* conn_frame_msg(ray_t* msg, uint8_t msgtype, if (err_out) *err_out = RAY_ERR_OOM; return NULL; } - ray_ser_raw(payload, msg); + if (ray_ser_raw(payload, msg) != ser_size) { + ray_free_raw(payload); + if (err_out) *err_out = RAY_ERR_IO; + return NULL; + } uint8_t* send_buf = NULL; size_t send_len = 0; diff --git a/src/core/morsel.c b/src/core/morsel.c index 6fff44f7f..963cc8604 100644 --- a/src/core/morsel.c +++ b/src/core/morsel.c @@ -48,6 +48,7 @@ void ray_morsel_init(ray_morsel_t* m, ray_t* vec) { /* One-time hint for mmap'd vectors */ if (vec->mmod == 1) { + /* generation-2 scans hint through ray_col_src_advise (store/colrange.c) */ ray_vm_advise_seq(ray_data(vec), (size_t)m->len * m->elem_size); } } diff --git a/src/core/numparse.c b/src/core/numparse.c index 6d4fa62f8..27863fd88 100644 --- a/src/core/numparse.c +++ b/src/core/numparse.c @@ -452,7 +452,20 @@ size_t ray_parse_f64(const char *src, size_t len, double *dst) { * fallback that produced ±Inf — to NULL_F64 (0Nf). Finite values * (including denormals and signed zero) pass through unchanged. The * fabs <= DBL_MAX test is false for both ±Inf and NaN. */ - double out = neg ? -val : val; + double out = val; + if (neg) { + /* Apply the sign through the bits, not through FP negation. The + * release flavour compiles with -fno-signed-zeros, under which the + * compiler may fold `neg ? -val : val` for val == 0.0 to a single + * constant and pick -0.0, so a plain "0" or "0.0" parsed to + * 0x8000000000000000 (#850). Flipping the sign bit through an + * integer is outside the FP model's reach and gives +0.0 for "0" + * and -0.0 for "-0" in every flavour. */ + uint64_t bits; + memcpy(&bits, &out, sizeof bits); + bits ^= UINT64_C(1) << 63; + memcpy(&out, &bits, sizeof out); + } *dst = (__builtin_fabs(out) <= DBL_MAX) ? out : NULL_F64; return i; } diff --git a/src/core/platform.c b/src/core/platform.c index 8606b9ec9..041b40373 100644 --- a/src/core/platform.c +++ b/src/core/platform.c @@ -62,9 +62,18 @@ uint64_t ray_vm_willneed_bytes(void) { #include /* EINTR — ray_os_cgroup_stat_flush */ #include #include /* getrusage: ray_io_counters */ +#include /* sched_getaffinity: ray_cpu_set_count */ +#include /* INT64_MAX: the cgroup quota */ #if !defined(RUSAGE_THREAD) #define RUSAGE_THREAD 1 #endif +#include /* SYS_mlock2: ray_vm_lock, past libc's mlock interceptors */ +#if !defined(MLOCK_ONFAULT) +#define MLOCK_ONFAULT 1 +#endif +#if !defined(MADV_DONTNEED_LOCKED) +#define MADV_DONTNEED_LOCKED 24 /* Linux 5.18 */ +#endif #endif #include "mem/sys.h" @@ -86,6 +95,11 @@ void ray_vm_free(void* ptr, size_t size) { } void* ray_vm_map_file(const char* path, size_t* out_size) { + return ray_vm_map_file_id(path, out_size, NULL); +} + +void* ray_vm_map_file_id(const char* path, size_t* out_size, ray_file_id_t* id) { + if (id) memset(id, 0, sizeof(*id)); int fd = open(path, O_RDONLY); if (fd < 0) return NULL; @@ -94,6 +108,18 @@ void* ray_vm_map_file(const char* path, size_t* out_size) { close(fd); return NULL; } + if (id) { + id->valid = true; + id->ino = (uint64_t)st.st_ino; + id->size = (uint64_t)st.st_size; +#if defined(RAY_OS_MACOS) + id->mtime_ns = (int64_t)st.st_mtimespec.tv_sec * 1000000000 + st.st_mtimespec.tv_nsec; + id->ctime_ns = (int64_t)st.st_ctimespec.tv_sec * 1000000000 + st.st_ctimespec.tv_nsec; +#else + id->mtime_ns = (int64_t)st.st_mtim.tv_sec * 1000000000 + st.st_mtim.tv_nsec; + id->ctime_ns = (int64_t)st.st_ctim.tv_sec * 1000000000 + st.st_ctim.tv_nsec; +#endif + } if (st.st_size <= 0) { close(fd); @@ -130,6 +156,18 @@ void* ray_vm_map_fd_ro(int fd, size_t size) { return p; } +/* A zeroed, writable private mapping with no file behind it, released by + * ray_vm_unmap_file: an in-memory image that the code mapping files takes + * as one of its own (a generated column). Counted in the file-mapping + * total, which ray_vm_unmap_file debits. NULL on failure. */ +void* ray_vm_map_anon(size_t size) { + if (size == 0) return NULL; + void* p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) return NULL; + ray_sys_track_file_add((int64_t)size); + return p; +} + void ray_vm_advise_seq(void* ptr, size_t size) { if (ptr) madvise(ptr, size, MADV_SEQUENTIAL); } @@ -147,6 +185,8 @@ static size_t vm_page_size(void) { return pg; } +size_t ray_vm_page_size(void) { return vm_page_size(); } + #if defined(RAY_OS_LINUX) /* A block device's queue attribute in KiB, -1 when it cannot be read. */ static long vm_queue_kb(const char* dev, const char* attr) { @@ -274,7 +314,9 @@ void ray_vm_release(void* ptr, size_t size) { #endif } -void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { +/* The range of free block blk whose pages may go: [*s, *e), empty if none. */ +static void vm_block_range(void* blk, size_t bsize, bool hugepage, + uintptr_t* s_out, uintptr_t* e_out) { if (!hugepage) { /* Release only whole pages strictly INSIDE the block, keeping its * first page resident: the buddy free-list links (fl_prev/fl_next @@ -291,9 +333,8 @@ void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { * NULL link (issue #240). Rounding inward to page-aligned bounds * makes the kernel's own rounding a no-op on every platform. */ size_t pg = vm_page_size(); - uintptr_t s = ((uintptr_t)blk + 32 + (pg - 1)) & ~(uintptr_t)(pg - 1); - uintptr_t e = ((uintptr_t)blk + bsize) & ~(uintptr_t)(pg - 1); - if (e > s) ray_vm_release((void*)s, e - s); + *s_out = ((uintptr_t)blk + 32 + (pg - 1)) & ~(uintptr_t)(pg - 1); + *e_out = ((uintptr_t)blk + bsize) & ~(uintptr_t)(pg - 1); return; } /* THP pool: release only the whole 2MB-aligned interior so a partial @@ -308,10 +349,62 @@ void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { * still release only whole 2MB regions, so no THP shatter. */ uintptr_t s = ((uintptr_t)blk + (2u << 20) - 1) & ~((uintptr_t)(2u << 20) - 1); if (s == (uintptr_t)blk) s += (2u << 20); - uintptr_t e = ((uintptr_t)blk + bsize) & ~((uintptr_t)(2u << 20) - 1); + *s_out = s; + *e_out = ((uintptr_t)blk + bsize) & ~((uintptr_t)(2u << 20) - 1); +} + +void ray_vm_release_block(void* blk, size_t bsize, bool hugepage) { + uintptr_t s, e; + vm_block_range(blk, bsize, hugepage, &s, &e); if (e > s) ray_vm_release((void*)s, e - s); } +#if defined(RAY_OS_LINUX) +/* 0 once MADV_DONTNEED_LOCKED (Linux 5.18) is known not to exist here. */ +static _Atomic(int) vm_dontneed_locked = 1; +#endif + +int ray_vm_release_locked(void* ptr, size_t size) { +#if defined(RAY_OS_LINUX) && defined(SYS_munlock) && defined(SYS_mlock2) + if (!ptr || size == 0) return 0; + /* MADV_DONTNEED refuses a locked range; MADV_DONTNEED_LOCKED does not, + * and the range stays locked. */ + if (atomic_load_explicit(&vm_dontneed_locked, memory_order_relaxed)) { + if (madvise(ptr, size, MADV_DONTNEED_LOCKED) == 0) return 0; + if (errno != EINVAL) return -1; + atomic_store_explicit(&vm_dontneed_locked, 0, memory_order_relaxed); + } + /* Before it: unlock, release, lock again — on fault, so nothing comes + * back in, and the kernel merges the range into its mapping again. */ + if (syscall(SYS_munlock, ptr, size) != 0) return -1; + madvise(ptr, size, MADV_DONTNEED); + return syscall(SYS_mlock2, ptr, size, MLOCK_ONFAULT) == 0 ? 0 : 1; +#else + ray_vm_release(ptr, size); + return 0; +#endif +} + +int ray_vm_release_block_locked(void* blk, size_t bsize, bool hugepage) { + uintptr_t s, e; + vm_block_range(blk, bsize, hugepage, &s, &e); + return e > s ? ray_vm_release_locked((void*)s, e - s) : 0; +} + +int ray_vm_release_block_any(void* blk, size_t bsize, bool hugepage) { + uintptr_t s, e; + vm_block_range(blk, bsize, hugepage, &s, &e); + if (e <= s) return 0; +#if defined(RAY_OS_LINUX) + if (madvise((void*)s, e - s, MADV_DONTNEED) == 0) return 0; + if (errno != EINVAL) return -1; + return ray_vm_release_locked((void*)s, e - s); /* a locked range */ +#else + ray_vm_release((void*)s, e - s); + return 0; +#endif +} + void* ray_vm_alloc_aligned(size_t size, size_t alignment) { size_t total = size + alignment; void* mem = mmap(NULL, total, PROT_READ | PROT_WRITE, @@ -346,6 +439,67 @@ bool ray_vm_hugepage(void* ptr, size_t size) { #endif } +/* Linux: mlock2(MLOCK_ONFAULT) — only the pages faulted in are locked, as + * they are faulted. Called as a raw system call: sanitizer runtimes + * intercept mlock() and make it a no-op, and an old libc has no mlock2 + * wrapper. Elsewhere nothing: plain mlock() would fault in and wire the + * whole range at once. */ +bool ray_vm_lock(void* ptr, size_t size) { +#if defined(RAY_OS_LINUX) && defined(SYS_mlock2) + if (!ptr || size == 0) return false; + return syscall(SYS_mlock2, ptr, size, MLOCK_ONFAULT) == 0; +#else + (void)ptr; (void)size; return false; +#endif +} + +void ray_vm_unlock(void* ptr, size_t size) { +#if defined(RAY_OS_LINUX) && defined(SYS_munlock) + if (ptr && size) (void)syscall(SYS_munlock, ptr, size); +#else + (void)ptr; (void)size; +#endif +} + +bool ray_os_has_ipc_lock(void) { +#if defined(RAY_OS_LINUX) + FILE* f = fopen("/proc/self/status", "r"); + if (!f) return false; + char line[256]; + unsigned long long eff = 0; + while (fgets(line, sizeof(line), f)) + if (strncmp(line, "CapEff:", 7) == 0) { eff = strtoull(line + 7, NULL, 16); break; } + fclose(f); + return (eff >> 14) & 1; /* CAP_IPC_LOCK */ +#else + return false; +#endif +} + +int64_t ray_vm_locked_bytes(void) { +#if defined(RAY_OS_LINUX) + FILE* f = fopen("/proc/self/status", "r"); + if (!f) return 0; + char line[256]; + int64_t kb = 0; + while (fgets(line, sizeof(line), f)) + if (strncmp(line, "VmLck:", 6) == 0) { kb = strtoll(line + 6, NULL, 10); break; } + fclose(f); + return kb * 1024; +#else + return 0; +#endif +} + +void ray_os_raise_memlock(void) { +#if defined(RAY_OS_LINUX) + struct rlimit rl; + if (getrlimit(RLIMIT_MEMLOCK, &rl) != 0 || rl.rlim_cur >= rl.rlim_max) return; + rl.rlim_cur = rl.rlim_max; + (void)setrlimit(RLIMIT_MEMLOCK, &rl); +#endif +} + /* -------------------------------------------------------------------------- * Threading * -------------------------------------------------------------------------- */ @@ -401,6 +555,37 @@ uint32_t ray_thread_count(void) { return (n > 0) ? (uint32_t)n : 1; } +/* The CPUs this process may run on: its affinity mask on Linux, which + * taskset, a cgroup cpuset or docker --cpuset-cpus may narrow below the + * online count; the online count elsewhere. The mask read is the calling + * thread's: the process's, unless an embedding application narrowed the + * thread that first uses the pool (whose workers then inherit it). */ +/* Test hook: a mask buffer below this many bytes fails as a kernel whose + * mask is wider than the buffer fails it (EINVAL); 0 = none. */ +static size_t g_cpu_set_test_min; +void ray_cpu_set_test_min_bytes(size_t n) { g_cpu_set_test_min = n; } + +uint32_t ray_cpu_set_count(void) { +#if defined(RAY_OS_LINUX) + /* A kernel built for more CPUs than a cpu_set_t holds (1024) rejects + * the fixed buffer with EINVAL however few CPUs the process may use: + * retry with a larger one. */ + for (size_t sz = sizeof(cpu_set_t); sz <= ((size_t)1 << 20); sz *= 2) { + cpu_set_t* set = (cpu_set_t*)ray_sys_alloc(sz); + if (!set) break; + memset(set, 0, sz); + int rc, err = EINVAL; + if (sz < g_cpu_set_test_min) rc = -1; + else { rc = sched_getaffinity(0, sz, set); err = errno; } + int n = rc == 0 ? CPU_COUNT_S(sz, set) : 0; + ray_sys_free(set); + if (rc == 0) { if (n > 0) return (uint32_t)n; break; } + if (err != EINVAL) break; + } +#endif + return ray_thread_count(); +} + /* Physical cores (SMT siblings collapsed). The worker pool's kernels are * memory-bound; two hyperthreads sharing one core's load/store machinery * only add contention (measured: the full ClickBench suite runs ~11% @@ -620,6 +805,200 @@ int64_t ray_os_cgroup_mem_limit(void) { return cgroup_mem_limit(NULL, 0); } +/* CPU quota (docker --cpus, systemd CPUQuota=): the CPU time a cgroup may + * use per period, as v2 cpu.max "QUOTA PERIOD" ("max" = none) or v1 + * cpu.cfs_quota_us (-1 = none) over cpu.cfs_period_us, in millicpus. A + * quota does not narrow the affinity mask, so a pool sized to the mask + * would run more threads than the quota lets run and be throttled. */ +static int64_t cgroup_cpu_read(const char* dir, bool v2) { + char path[640], buf[64]; + long long q = 0, per = 0; + if (v2) { + snprintf(path, sizeof(path), "%s/cpu.max", dir); + FILE* f = fopen(path, "r"); + if (!f) return 0; + buf[0] = 0; + if (!fgets(buf, sizeof(buf), f)) buf[0] = 0; + fclose(f); + if (strncmp(buf, "max", 3) == 0 || sscanf(buf, "%lld %lld", &q, &per) != 2) return 0; + } else { + snprintf(path, sizeof(path), "%s/cpu.cfs_quota_us", dir); + FILE* f = fopen(path, "r"); + if (!f) return 0; + if (fscanf(f, "%lld", &q) != 1) q = 0; + fclose(f); + snprintf(path, sizeof(path), "%s/cpu.cfs_period_us", dir); + f = fopen(path, "r"); + if (!f) return 0; + if (fscanf(f, "%lld", &per) != 1) per = 0; + fclose(f); + } + if (q <= 0 || per <= 0 || q > (long long)(INT64_MAX / 1000) - per) return 0; + return (int64_t)((q * 1000 + per - 1) / per); +} + +/* Test hook: a directory /proc/self/{cgroup,mountinfo} and the cgroup + * files of the quota reader are taken from (NULL: the real ones). */ +static const char* g_cg_test_root; +void ray_os_cgroup_test_root(const char* dir) { g_cg_test_root = dir; } + +static void cg_path(char* out, size_t n, const char* p) { + snprintf(out, n, "%s%s", g_cg_test_root ? g_cg_test_root : "", p); +} + +/* Smallest quota over `root`/`cgpath` and every ancestor up to `root`, as + * the memory limit walk above. */ +static int64_t cgroup_cpu_walk(const char* root, const char* cgpath, bool v2) { + char dir[512]; + if (snprintf(dir, sizeof(dir), "%s%s", root, cgpath) >= (int)sizeof(dir)) return 0; + size_t rootlen = strlen(root); + int64_t m = 0; + for (;;) { + int64_t v = cgroup_cpu_read(dir, v2); + if (v > 0 && (m == 0 || v < m)) m = v; + if (strlen(dir) <= rootlen) break; + char* slash = strrchr(dir, '/'); + if (!slash || (size_t)(slash - dir) < rootlen) break; + *slash = 0; + } + return m; +} + +/* True when the comma-separated list names `want`. */ +static bool cgroup_list_has(const char* list, const char* want) { + size_t wl = strlen(want); + while (*list) { + size_t n = strcspn(list, ","); + if (n == wl && strncmp(list, want, n) == 0) return true; + list += n; + if (*list == ',') list++; + } + return false; +} + +/* mountinfo escapes space, tab, newline and backslash as \ooo */ +static void cg_unescape(char* s) { + char* o = s; + for (char* p = s; *p; p++) { + if (p[0] == '\\' && p[1] >= '0' && p[1] <= '3' && p[2] >= '0' && p[2] <= '7' && + p[3] >= '0' && p[3] <= '7') { + *o++ = (char)((p[1] - '0') * 64 + (p[2] - '0') * 8 + (p[3] - '0')); + p += 3; + } else { + *o++ = *p; + } + } + *o = 0; +} + +/* One mount of a cgroup hierarchy from a /proc/self/mountinfo line: the + * v2 one (`ctrl` NULL), or the v1 one whose super options name `ctrl`. + * Its mount point, and the path in the hierarchy the mount shows (its + * root: "/" unless a subtree was mounted). The line is consumed. */ +static bool cgroup_mount_line(char* line, const char* ctrl, char** mnt, char** root) { + /* "ID PARENT MAJ:MIN ROOT MOUNTPOINT OPTS [OPTIONAL...] - FSTYPE SOURCE SUPEROPTS" */ + line[strcspn(line, "\n")] = 0; + char* sep = strstr(line, " - "); + if (!sep) return false; + *sep = 0; + char* f_root = NULL; char* f_mnt = NULL; + char* save = NULL; + int i = 0; + for (char* t = strtok_r(line, " ", &save); t; t = strtok_r(NULL, " ", &save), i++) { + if (i == 3) f_root = t; + else if (i == 4) { f_mnt = t; break; } + } + if (!f_root || !f_mnt) return false; + char* fstype = strtok_r(sep + 3, " ", &save); + char* source = fstype ? strtok_r(NULL, " ", &save) : NULL; + char* super = source ? strtok_r(NULL, " ", &save) : NULL; + if (!fstype) return false; + if (ctrl ? !(strcmp(fstype, "cgroup") == 0 && super && cgroup_list_has(super, ctrl)) + : strcmp(fstype, "cgroup2") != 0) + return false; + cg_unescape(f_root); + cg_unescape(f_mnt); + *mnt = f_mnt; + *root = f_root; + return true; +} + +/* The quota of a membership path `cgpath` ("" for the root) of the v2 + * hierarchy (`ctrl` NULL) or the v1 one carrying `ctrl`. Every mount of + * the hierarchy whose subtree holds the membership is a view of it: the + * membership is translated through the view's root to its directory under + * the mount point, and the cgroup and its ancestors visible there (up to + * the mount point) are read. The tightest quota of all views counts, as + * each shows a part of the same ancestry. Without mountinfo, or with no + * mount of the hierarchy listed, the conventional mounts. */ +static int64_t cgroup_cpu_member(const char* ctrl, const char* v1list, const char* cgpath) { + char path[600], base[600]; + cg_path(path, sizeof(path), "/proc/self/mountinfo"); + FILE* f = fopen(path, "r"); + bool listed = false; + int64_t m = 0; + if (f) { + char line[2048]; + while (fgets(line, sizeof(line), f)) { + char* mnt; char* root; + if (!cgroup_mount_line(line, ctrl, &mnt, &root)) continue; + listed = true; + const char* rel = cgpath; + if (strcmp(root, "/") != 0) { + size_t rl = strlen(root); + if (strncmp(cgpath, root, rl) != 0 || (cgpath[rl] != 0 && cgpath[rl] != '/')) + continue; /* the membership is outside this view */ + rel = cgpath + rl; + } + cg_path(base, sizeof(base), mnt); + int64_t v = cgroup_cpu_walk(base, rel, ctrl == NULL); + if (v > 0 && (m == 0 || v < m)) m = v; + } + fclose(f); + } + if (listed) return m; + if (!ctrl) { + cg_path(base, sizeof(base), "/sys/fs/cgroup"); + return cgroup_cpu_walk(base, cgpath, true); + } + /* v1 mounts the controller as the directory named by its list + * ("cpu,cpuacct"), usually with a "cpu" link to it */ + char dir[300]; + snprintf(dir, sizeof(dir), "/sys/fs/cgroup/%s", v1list); + cg_path(base, sizeof(base), dir); + int64_t v = cgroup_cpu_walk(base, cgpath, false); + if (!v) { + cg_path(base, sizeof(base), "/sys/fs/cgroup/cpu"); + v = cgroup_cpu_walk(base, cgpath, false); + } + return v; +} + +int64_t ray_os_cgroup_cpu_quota(void) { + char path[600]; + cg_path(path, sizeof(path), "/proc/self/cgroup"); + FILE* f = fopen(path, "r"); + if (!f) return 0; + int64_t m = 0; + char line[512]; + while (fgets(line, sizeof(line), f)) { + char* c1 = strchr(line, ':'); + char* c2 = c1 ? strchr(c1 + 1, ':') : NULL; + if (!c2) continue; + *c2 = 0; + const char* ctrls = c1 + 1; + char* cgpath = c2 + 1; + cgpath[strcspn(cgpath, "\n")] = 0; + if (strcmp(cgpath, "/") == 0) cgpath[0] = 0; + int64_t v = 0; + if (*ctrls == 0) v = cgroup_cpu_member(NULL, NULL, cgpath); + else if (cgroup_list_has(ctrls, "cpu")) v = cgroup_cpu_member("cpu", ctrls, cgpath); + if (v > 0 && (m == 0 || v < m)) m = v; + } + fclose(f); + return m; +} + bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return n && cgroup_mem_limit(buf, n) > 0 && buf[0]; @@ -638,6 +1017,8 @@ bool ray_os_cgroup_stat_flush(const char* cg) { } #else int64_t ray_os_cgroup_mem_limit(void) { return 0; } +int64_t ray_os_cgroup_cpu_quota(void) { return 0; } +void ray_os_cgroup_test_root(const char* dir) { (void)dir; } bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return false; } bool ray_os_cgroup_stat_flush(const char* cg) { (void)cg; return false; } #endif @@ -760,6 +1141,12 @@ void ray_vm_free(void* ptr, size_t size) { ray_sys_track_sub((int64_t)size); } +/* No file identity here: the record index never takes the shortcut. */ +void* ray_vm_map_file_id(const char* path, size_t* out_size, ray_file_id_t* id) { + if (id) memset(id, 0, sizeof(*id)); + return ray_vm_map_file(path, out_size); +} + void* ray_vm_map_file(const char* path, size_t* out_size) { HANDLE hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); @@ -821,6 +1208,22 @@ void* ray_vm_map_fd_ro(int fd, size_t size) { return p; } +/* A zeroed, writable view backed by the paging file, released by + * ray_vm_unmap_file (UnmapViewOfFile at the view's base): an in-memory + * image that the code mapping files takes as one of its own. Counted in + * the file-mapping total. NULL on failure. */ +void* ray_vm_map_anon(size_t size) { + if (size == 0) return NULL; + HANDLE hMap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, + (DWORD)((uint64_t)size >> 32), (DWORD)size, NULL); + if (!hMap) return NULL; + void* p = MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, size); + CloseHandle(hMap); + if (!p) return NULL; + ray_sys_track_file_add((int64_t)size); + return p; +} + void ray_vm_advise_seq(void* ptr, size_t size) { /* PrefetchVirtualMemory is Win8.1+. Best-effort; ignore failure. */ WIN32_MEMORY_RANGE_ENTRY entry; @@ -829,6 +1232,12 @@ void ray_vm_advise_seq(void* ptr, size_t size) { PrefetchVirtualMemory(GetCurrentProcess(), 1, &entry, 0); } +size_t ray_vm_page_size(void) { + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwPageSize ? (size_t)si.dwPageSize : 4096; +} + void ray_vm_advise_willneed(void* ptr, size_t size) { if (!ptr || !size) return; atomic_fetch_add_explicit(&vm_willneed_bytes, size, memory_order_relaxed); @@ -881,6 +1290,20 @@ void* ray_vm_alloc_aligned(size_t size, size_t alignment) { } bool ray_vm_hugepage(void* ptr, size_t size) { (void)ptr; (void)size; return false; } +bool ray_vm_lock(void* ptr, size_t size) { (void)ptr; (void)size; return false; } +void ray_vm_unlock(void* ptr, size_t size) { (void)ptr; (void)size; } +int ray_vm_release_locked(void* ptr, size_t size) { ray_vm_release(ptr, size); return 0; } +int ray_vm_release_block_locked(void* blk, size_t bsize, bool hugepage) { + ray_vm_release_block(blk, bsize, hugepage); + return 0; +} +int ray_vm_release_block_any(void* blk, size_t bsize, bool hugepage) { + ray_vm_release_block(blk, bsize, hugepage); + return 0; +} +bool ray_os_has_ipc_lock(void) { return false; } +int64_t ray_vm_locked_bytes(void) { return 0; } +void ray_os_raise_memlock(void) {} /* -------------------------------------------------------------------------- * Threading @@ -923,6 +1346,8 @@ uint32_t ray_thread_count(void) { GetSystemInfo(&si); return (uint32_t)si.dwNumberOfProcessors; } +uint32_t ray_cpu_set_count(void) { return ray_thread_count(); } +void ray_cpu_set_test_min_bytes(size_t n) { (void)n; } /* Windows: no cheap topology read here — fall back to the logical count * (the SMT-aware default sizing is a POSIX-side optimization). */ @@ -931,6 +1356,8 @@ uint32_t ray_physical_core_count(void) { } int64_t ray_os_cgroup_mem_limit(void) { return 0; } +int64_t ray_os_cgroup_cpu_quota(void) { return 0; } +void ray_os_cgroup_test_root(const char* dir) { (void)dir; } bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return false; } bool ray_os_cgroup_stat_flush(const char* cg) { (void)cg; return false; } @@ -1029,6 +1456,12 @@ void ray_vm_free(void* ptr, size_t size) { ray_sys_track_sub((int64_t)size); } +/* No file identity here: the record index never takes the shortcut. */ +void* ray_vm_map_file_id(const char* path, size_t* out_size, ray_file_id_t* id) { + if (id) memset(id, 0, sizeof(*id)); + return ray_vm_map_file(path, out_size); +} + void* ray_vm_map_file(const char* path, size_t* out_size) { int fd = open(path, O_RDONLY); if (fd < 0) return NULL; @@ -1064,8 +1497,24 @@ void* ray_vm_map_fd_ro(int fd, size_t size) { return p; } +/* A zeroed, writable private mapping with no file behind it, released by + * ray_vm_unmap_file: an in-memory image that the code mapping files takes + * as one of its own (a generated column). Counted in the file-mapping + * total, which ray_vm_unmap_file debits. NULL on failure. */ +void* ray_vm_map_anon(size_t size) { + if (size == 0) return NULL; + void* p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) return NULL; + ray_sys_track_file_add((int64_t)size); + return p; +} + /* madvise hints are advisory and have no analog on WASM — no-ops. */ void ray_vm_advise_seq(void* ptr, size_t size) { (void)ptr; (void)size; } +size_t ray_vm_page_size(void) { + long ps = sysconf(_SC_PAGESIZE); + return (ps > 0) ? (size_t)ps : 4096; +} void ray_vm_advise_willneed(void* ptr, size_t size) { if (ptr && size) atomic_fetch_add_explicit(&vm_willneed_bytes, size, memory_order_relaxed); } @@ -1090,6 +1539,20 @@ void* ray_vm_alloc_aligned(size_t size, size_t alignment) { } bool ray_vm_hugepage(void* ptr, size_t size) { (void)ptr; (void)size; return false; } +bool ray_vm_lock(void* ptr, size_t size) { (void)ptr; (void)size; return false; } +void ray_vm_unlock(void* ptr, size_t size) { (void)ptr; (void)size; } +int ray_vm_release_locked(void* ptr, size_t size) { ray_vm_release(ptr, size); return 0; } +int ray_vm_release_block_locked(void* blk, size_t bsize, bool hugepage) { + ray_vm_release_block(blk, bsize, hugepage); + return 0; +} +int ray_vm_release_block_any(void* blk, size_t bsize, bool hugepage) { + ray_vm_release_block(blk, bsize, hugepage); + return 0; +} +bool ray_os_has_ipc_lock(void) { return false; } +int64_t ray_vm_locked_bytes(void) { return 0; } +void ray_os_raise_memlock(void) {} /* Threading — return errors / 1. pool.c with n_workers==0 (the result of * thread_count==1 ⇒ ncpu-1 == 0) never invokes thread_create. */ @@ -1104,7 +1567,11 @@ ray_err_t ray_thread_join(ray_thread_t t) { } uint32_t ray_thread_count(void) { return 1; } +uint32_t ray_cpu_set_count(void) { return ray_thread_count(); } +void ray_cpu_set_test_min_bytes(size_t n) { (void)n; } int64_t ray_os_cgroup_mem_limit(void) { return 0; } +int64_t ray_os_cgroup_cpu_quota(void) { return 0; } +void ray_os_cgroup_test_root(const char* dir) { (void)dir; } bool ray_os_cgroup_mem_dir(char* buf, size_t n) { if (n) buf[0] = 0; return false; } bool ray_os_cgroup_stat_flush(const char* cg) { (void)cg; return false; } static uint64_t cache_llc_probe(void) { return 0; } diff --git a/src/core/platform.h b/src/core/platform.h index 0640524f0..bd35d0c25 100644 --- a/src/core/platform.h +++ b/src/core/platform.h @@ -153,9 +153,20 @@ typedef void (*ray_thread_fn)(void* arg); void* ray_vm_alloc(size_t size); void ray_vm_free(void* ptr, size_t size); void* ray_vm_map_file(const char* path, size_t* out_size); +/* The identity of a mapped file, read from the descriptor the mapping was + * made from (not the path, which may name another file by now): inode, + * size, modification and status-change times in ns. valid is false where + * the platform gives none (Windows, WASM). */ +typedef struct { bool valid; uint64_t ino, size; int64_t mtime_ns, ctime_ns; } ray_file_id_t; +void* ray_vm_map_file_id(const char* path, size_t* out_size, ray_file_id_t* id); void* ray_vm_map_fd_ro(int fd, size_t size); void ray_vm_unmap_file(void* ptr, size_t size); +/* Zeroed writable memory released by ray_vm_unmap_file (a generated file image). */ +void* ray_vm_map_anon(size_t size); void ray_vm_advise_seq(void* ptr, size_t size); +/* The host page size (sysconf / GetSystemInfo, read once; 4096 when the host + * does not say): what a madvise start must be aligned to. */ +size_t ray_vm_page_size(void); /* Ask the kernel to start reading [ptr, ptr+size) of a file mapping now, * asynchronously, so a later access finds it resident. Best effort. */ void ray_vm_advise_willneed(void* ptr, size_t size); @@ -193,6 +204,29 @@ void* ray_vm_alloc_aligned(size_t size, size_t alignment); * if the hint was issued (Linux THP); false where unsupported (macOS, WASM, * Windows). */ bool ray_vm_hugepage(void* ptr, size_t size); +/* Lock [ptr, ptr+size) of an anonymous mapping against swap-out, page by + * page as each is faulted in (Linux: mlock2 MLOCK_ONFAULT); munmap unlocks + * it. False where it cannot be — RLIMIT_MEMLOCK, a kernel before 4.4, a + * platform other than Linux — and nothing is locked then (errno says why). */ +bool ray_vm_lock(void* ptr, size_t size); +/* Unlock a range ray_vm_lock locked; its pages stay. */ +void ray_vm_unlock(void* ptr, size_t size); +/* ray_vm_release / ray_vm_release_block for a locked range, which + * MADV_DONTNEED refuses: MADV_DONTNEED_LOCKED (Linux 5.18), else unlock, + * release and lock again. 0: released, still locked; 1: released, left + * unlocked (the lock again failed); -1: nothing released. */ +int ray_vm_release_locked(void* ptr, size_t size); +int ray_vm_release_block_locked(void* blk, size_t bsize, bool hugepage); +/* For a block whose lock is not known: MADV_DONTNEED, and where that is + * refused for a lock, as ray_vm_release_block_locked. Same returns. */ +int ray_vm_release_block_any(void* blk, size_t bsize, bool hugepage); +/* Whether this process holds CAP_IPC_LOCK, past RLIMIT_MEMLOCK (Linux). */ +bool ray_os_has_ipc_lock(void); +/* Bytes of this process's locked mappings (VmLck); 0 where unknown. */ +int64_t ray_vm_locked_bytes(void); +/* Raise RLIMIT_MEMLOCK's soft limit to its hard limit (Linux; a no-op + * elsewhere, and where it already is). */ +void ray_os_raise_memlock(void); /* -------------------------------------------------------------------------- * Threading API @@ -200,6 +234,12 @@ bool ray_vm_hugepage(void* ptr, size_t size); ray_err_t ray_thread_create(ray_thread_t* t, ray_thread_fn fn, void* arg); ray_err_t ray_thread_join(ray_thread_t t); uint32_t ray_thread_count(void); +/* The CPUs this process may run on: the affinity mask on Linux (taskset, a + * cpuset or docker --cpuset-cpus narrow it), ray_thread_count elsewhere. */ +uint32_t ray_cpu_set_count(void); +/* Test hook: a mask buffer below n bytes fails as on a kernel with a wider + * mask (EINVAL), so the retry with a larger buffer is exercised; 0 = none. */ +void ray_cpu_set_test_min_bytes(size_t n); /* Physical cores (SMT siblings collapsed); falls back to the logical * count when topology is unavailable. */ uint32_t ray_physical_core_count(void); @@ -212,6 +252,13 @@ uint64_t ray_cache_llc_bytes(void); * the process's cgroup and its ancestors. 0 when none is set, or on * platforms without cgroups. */ int64_t ray_os_cgroup_mem_limit(void); +/* CPU quota of this process's cgroup (docker --cpus, systemd CPUQuota=), in + * millicpus: the smallest v2 cpu.max or v1 cfs quota over its period on the + * cgroup and its ancestors. 0 when none is set, or without cgroups. */ +int64_t ray_os_cgroup_cpu_quota(void); +/* Test hook: read /proc/self/{cgroup,mountinfo} and the cgroup files of the + * quota from under `dir` (NULL: the real ones). */ +void ray_os_cgroup_test_root(const char* dir); /* The directory of the cgroup that sets that limit, into buf[n]; false when * no limit is set, or on platforms without cgroups. */ bool ray_os_cgroup_mem_dir(char* buf, size_t n); diff --git a/src/core/pool.c b/src/core/pool.c index 2d4653cae..e34f15a19 100644 --- a/src/core/pool.c +++ b/src/core/pool.c @@ -32,6 +32,32 @@ #include #include +uint32_t ray_pool_default_total(void) { + uint32_t n = ray_cpu_set_count(); + int64_t q = ray_os_cgroup_cpu_quota(); /* millicpus, 0 = none */ + if (q > 0 && (q + 999) / 1000 < (int64_t)n) n = (uint32_t)((q + 999) / 1000); + return n > 0 ? n : 1; +} + +/* Spawned workers of a default pool. The RAYFORCE_CORES env var overrides + * the size — the test harness sets it (see the Makefile `test` target) so + * neither the in-process runtime nor the server children it spawns via + * .sys.exec each create a thread per CPU on a many-core box. An explicit + * positive -c uses ray_pool_init_total() with exact sizing and bypasses + * this entirely. Otherwise every CPU the process may run on (its affinity + * mask: every online CPU unless taskset or a cpuset narrowed it), or fewer + * under a cgroup CPU quota; individual operations may bound their task + * count to their workload or memory budget. */ +static uint32_t pool_default_workers(void) { + const char* env = getenv("RAYFORCE_CORES"); + if (env && *env) { + long v = strtol(env, NULL, 10); + return (v > 0) ? (uint32_t)v : 0; + } + uint32_t ncpu = ray_pool_default_total(); + return (ncpu > 1) ? ncpu - 1 : 0; +} + /* Per-worker query-statistics slab (see core/qstats.h). Zero-initialised; * disabled (mode == 0) until a profiling/progress consumer turns it on. */ ray_qstats_t g_qstats; @@ -569,23 +595,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, } if (auto_size) { - /* Auto-size to ncpu-1. The RAYFORCE_CORES env var overrides this - * default worker count — the test harness sets it (see the Makefile - * `test` target) so neither the in-process runtime nor the server - * children it spawns via .sys.exec each create ncpu-1 threads on a - * many-core box. An explicit positive -c uses ray_pool_init_total() - * with exact sizing and bypasses this entirely; a non-test run with - * the var unset keeps the historical ncpu-1 default. */ - const char* env = getenv("RAYFORCE_CORES"); - if (env && *env) { - long v = strtol(env, NULL, 10); - n_workers = (v > 0) ? (uint32_t)v : 0; - } else { - /* Default to every online logical CPU. Individual operations may - * bound their task count to their workload or memory budget. */ - uint32_t ncpu = ray_thread_count(); - n_workers = (ncpu > 1) ? ncpu - 1 : 0; - } + n_workers = pool_default_workers(); } pool->n_workers = n_workers; @@ -738,12 +748,20 @@ void ray_pool_free(ray_pool_t* pool) { memset(pool, 0, sizeof(*pool)); } +/* Read-ahead state for the dispatch about to start: a fresh generation, so + * the per-thread run state (active columns, probe misses, requested window) + * left by the previous dispatch is not taken for this one. Once per + * dispatch, not per round: the rounds of one dispatch walk one row space, + * and a thread's run continues across them. */ +static inline void pool_scan_dispatch_begin(ray_pool_t* pool) { + pool->scan_gen = atomic_fetch_add_explicit(&pool_scan_gens, 1, memory_order_relaxed) + 1; +} + /* Arm read-ahead for the window about to be published: the caller's * registration, requested per ticket when the window covers exactly its * rows (`total` elements, `grain` per ticket from `base`). */ static void pool_scan_begin(ray_pool_t* pool, int64_t total, uint64_t base, int64_t grain) { const ray_pool_scan_t* sc = (pool->scan_bytes && t_scan && t_scan->n) ? t_scan : NULL; - pool->scan_gen = atomic_fetch_add_explicit(&pool_scan_gens, 1, memory_order_relaxed) + 1; pool->scan = sc; pool->scan_auto = sc && pool->steal && grain > 0 && sc->rows == total; pool->scan_base = base; @@ -756,76 +774,62 @@ static inline void pool_scan_end(ray_pool_t* pool) { pool->scan_auto = false; } -/* -------------------------------------------------------------------------- - * ray_pool_dispatch - * -------------------------------------------------------------------------- */ - -/* M2: Caller (ray_execute) must reset pool->cancelled before dispatching. - * The cancelled flag is per-query state; failing to clear it causes all - * subsequent dispatches to skip task execution. */ -void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, - int64_t total_elems) { - if (total_elems <= 0) return; +/* Grow the ring towards n_tasks slots, up to MAX_RING_CAP. A dispatch that + * needs more than the ring holds afterwards (the ceiling, or a realloc that + * failed) runs its tasks in further rounds of task_cap each. + * + * conc-L6: Ring growth is safe without synchronization because dispatch is + * single-producer: only the main thread (the dispatch caller) writes + * tasks[] and task_cap, and only while the prior window is fully claimed + * (no task pending). Workers read tasks[]/task_cap only after acquiring + * the new task_limit (store-release), which orders the growth before any + * claim — so a late worker never reads a stale tasks pointer or task_cap. */ +/* Test hook (ray_pool_test_ring_fail): ring growth fails (as when its + * ray_sys_realloc returns NULL) and a round holds at most `cap` tasks, so a + * dispatch of more tasks runs in several rounds at test sizes; 0 off. */ +static _Atomic(uint32_t) g_pool_test_cap; +void ray_pool_test_ring_fail(uint32_t cap) { atomic_store_explicit(&g_pool_test_cap, cap, memory_order_relaxed); } + +/* Tasks one round may take: the ring, or the test hook's smaller cap. */ +static inline uint32_t pool_round_cap(const ray_pool_t* pool) { + uint32_t test_cap = atomic_load_explicit(&g_pool_test_cap, memory_order_relaxed); + return test_cap && test_cap < pool->task_cap ? test_cap : pool->task_cap; +} - /* Calculate number of tasks. - * Overflow guard: total_elems + grain - 1 could wrap for extreme values. */ - int64_t grain = TASK_GRAIN; - if (RAY_UNLIKELY(total_elems > INT64_MAX - grain + 1)) - total_elems = INT64_MAX - grain + 1; - uint32_t n_tasks = (uint32_t)((total_elems + grain - 1) / grain); - - /* conc-L6: Ring growth is safe without synchronization because dispatch is - * single-producer: only the main thread (the dispatch caller) writes - * tasks[] and task_cap, and only while the prior window is fully claimed - * (no task pending). Workers read tasks[]/task_cap only after acquiring - * the new task_limit (store-release), which orders the growth before any - * claim — so a late worker never reads a stale tasks pointer or task_cap. */ - if (n_tasks > pool->task_cap) { - uint32_t new_cap = pool->task_cap; - while (new_cap < n_tasks && new_cap < MAX_RING_CAP) new_cap *= 2; - if (new_cap > pool->task_cap) { - ray_pool_task_t* new_tasks = (ray_pool_task_t*)ray_sys_realloc( - pool->tasks, new_cap * sizeof(ray_pool_task_t)); - if (new_tasks) { - pool->tasks = new_tasks; - pool->task_cap = new_cap; - } +static void pool_ring_grow(ray_pool_t* pool, int64_t n_tasks) { + if (n_tasks <= (int64_t)pool->task_cap) return; + uint32_t new_cap = pool->task_cap; + while ((int64_t)new_cap < n_tasks && new_cap < MAX_RING_CAP) new_cap *= 2; + if (new_cap > pool->task_cap) { + ray_pool_task_t* new_tasks = + RAY_UNLIKELY(atomic_load_explicit(&g_pool_test_cap, memory_order_relaxed)) ? NULL /* the hook */ + : (ray_pool_task_t*)ray_sys_realloc(pool->tasks, new_cap * sizeof(ray_pool_task_t)); + if (new_tasks) { + pool->tasks = new_tasks; + pool->task_cap = new_cap; } } +} - /* Clamp n_tasks to task_cap to prevent ring overflow */ - if (n_tasks > pool->task_cap) { - n_tasks = pool->task_cap; - grain = (total_elems + n_tasks - 1) / n_tasks; - } - - /* Carve a fresh window [base, base+n_tasks) off the monotonic high-water - * mark. The prior dispatch is fully claimed, so task_claim == task_limit - * == base here (in steal mode: every slots[].range is head == tail and - * the cursors were advanced to base at publish); the window's slots - * never alias a still-live slot. */ - uint64_t base = atomic_load_explicit(&pool->task_limit, memory_order_relaxed); - - /* Fill task ring for tickets [base, base+n_tasks) */ - for (uint32_t i = 0; i < n_tasks; i++) { - int64_t start = (int64_t)i * grain; - int64_t end = start + grain; - if (end > total_elems) end = total_elems; - - uint32_t slot = (uint32_t)((base + i) & (pool->task_cap - 1)); - pool->tasks[slot].fn = fn; - pool->tasks[slot].ctx = ctx; - pool->tasks[slot].start = start; - pool->tasks[slot].end = end; - } +/* The window the next round fills: tickets [base, base+n_tasks), carved off + * the monotonic high-water mark. The prior round is fully claimed, so + * task_claim == task_limit == base here (in steal mode: every slots[].range + * is head == tail and the cursors were advanced to base at publish); the + * window's slots never alias a still-live slot. */ +static inline uint64_t pool_window_base(const ray_pool_t* pool) { + return atomic_load_explicit(&pool->task_limit, memory_order_relaxed); +} +/* Publish the window [base, base+n_tasks) whose ring slots the caller has + * filled, run it with the main thread as worker 0, and wait for it to + * drain. Read-ahead for the window is armed by the caller (pool_scan_begin) + * before this and disarmed here. */ +static void pool_run_window(ray_pool_t* pool, uint64_t base, uint32_t n_tasks, bool prog) { /* pending must be visible before the window opens; the task_limit * store-release publishes the ring fill AND pending to claimers. In * steal mode the range words are the publication (release each) and * the cursors only record the high-water mark. */ atomic_store_explicit(&pool->pending, n_tasks, memory_order_relaxed); - /* Scan read-ahead for this window, published with the ranges. */ - pool_scan_begin(pool, total_elems, base, grain); if (pool->steal) { atomic_store_explicit(&pool->task_claim, base + n_tasks, memory_order_relaxed); atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_relaxed); @@ -841,12 +845,6 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, /* Main thread enters atomic refcount mode during parallel dispatch */ ray_rc_sync = true; - /* Progress: when a callback is listening (PROGRESS bit armed), baseline the - * row counter for this dispatch so the main thread can pump a 0→100% bar - * from its claim/spin path. One relaxed load; skipped entirely otherwise. */ - const bool prog = ray_qstats_mode() & RAY_QS_PROGRESS; - if (prog) ray_progress_dispatch_begin((uint64_t)total_elems); - /* Wake worker threads — only as many as have something to claim. Main * participates as worker 0, so at most n_tasks-1 helpers can be useful; * signalling the whole pool woke threads that raced to an already-drained @@ -866,18 +864,7 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } else { uint64_t idx; while (pool_claim(pool, &idx)) { - if (RAY_UNLIKELY(atomic_load_explicit(&pool->cancelled, - memory_order_relaxed))) { - atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); - continue; - } - - ray_pool_task_t* t = &pool->tasks[idx & (pool->task_cap - 1)]; - int64_t _qs_t0; uint32_t _qs_m = ray_qstats_task_begin(&_qs_t0); - t->fn(t->ctx, 0, t->start, t->end); - ray_qstats_task_end(_qs_m, 0, t->end - t->start, _qs_t0); - - atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); + pool_exec(pool, 0, (uint32_t)idx); if (prog) ray_progress_pump(); } @@ -905,87 +892,120 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, pool_reclaim_worker_heaps(pool); } -/* One round of ray_pool_dispatch_n: tasks [first, first+n_tasks), each handed - * to fn as [i, i+1) with its ABSOLUTE index, n_tasks <= task_cap. */ -static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, - uint32_t first, uint32_t n_tasks) { - /* Carve a fresh window [base, base+n_tasks) off the monotonic high-water - * mark (the prior dispatch is fully claimed, so base == task_claim). */ - uint64_t base = atomic_load_explicit(&pool->task_limit, memory_order_relaxed); +/* One round of ray_pool_dispatch: tasks [first, first+n_tasks) of the + * element space, task i handed to fn as [i*grain, min((i+1)*grain, + * total_elems)), n_tasks <= task_cap. */ +static void dispatch_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, + int64_t total_elems, int64_t grain, int64_t first, + uint32_t n_tasks, bool prog) { + uint64_t base = pool_window_base(pool); - /* Fill task ring: one task per partition, tickets [base, base+n_tasks) */ + /* Fill task ring for tickets [base, base+n_tasks) */ for (uint32_t i = 0; i < n_tasks; i++) { + int64_t start = (first + (int64_t)i) * grain; + int64_t end = start + grain; + if (end > total_elems) end = total_elems; + uint32_t slot = (uint32_t)((base + i) & (pool->task_cap - 1)); pool->tasks[slot].fn = fn; pool->tasks[slot].ctx = ctx; - pool->tasks[slot].start = (int64_t)(first + i); - pool->tasks[slot].end = (int64_t)(first + i) + 1; + pool->tasks[slot].start = start; + pool->tasks[slot].end = end; } - atomic_store_explicit(&pool->pending, n_tasks, memory_order_relaxed); - pool_scan_begin(pool, -1, base, 0); /* tasks are not row ranges */ - if (pool->steal) { - atomic_store_explicit(&pool->task_claim, base + n_tasks, memory_order_relaxed); - atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_relaxed); - pool_publish_ranges(pool, base, n_tasks); - } else { - atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_release); - } + /* Scan read-ahead for this window, published with the ranges. Ticket + * base maps to task `first`, so the registration's ticket 0 is + * base - first (ticket arithmetic wraps as uint32 there). */ + pool_scan_begin(pool, total_elems, base - (uint64_t)first, grain); + pool_run_window(pool, base, n_tasks, prog); +} - atomic_store_explicit(&ray_parallel_flag, 1, memory_order_release); - ray_rc_sync = true; +/* -------------------------------------------------------------------------- + * ray_pool_dispatch + * -------------------------------------------------------------------------- */ - /* Progress: baseline this dispatch (one unit per task/partition). */ - const bool prog = ray_qstats_mode() & RAY_QS_PROGRESS; - if (prog) ray_progress_dispatch_begin((uint64_t)n_tasks); +/* M2: Caller (ray_execute) must reset pool->cancelled before dispatching. + * The cancelled flag is per-query state; failing to clear it causes all + * subsequent dispatches to skip task execution. + * + * Every task is exactly [i*grain, min((i+1)*grain, total_elems)) (grain + * TASK_GRAIN for ray_pool_dispatch): callers index per-task state by + * start / grain (fused WHERE rowsel builders, per-task histograms) and rely + * on grain-aligned starts. */ +static void pool_dispatch_at(ray_pool_t* pool, ray_pool_fn fn, void* ctx, + int64_t total_elems, int64_t grain) { + if (total_elems <= 0) return; - /* Wake worker threads — only as many as have something to claim. Main - * participates as worker 0, so at most n_tasks-1 helpers can be useful; - * signalling the whole pool woke threads that raced to an already-drained - * window and went straight back to sleep, which is pure overhead on any - * dispatch narrower than the machine (#599). Signalling FEWER is safe: - * completion is governed by the `pending` spin-wait below, never by the - * signal count, so an unsignalled worker simply stays asleep. */ - uint32_t wake = n_tasks > 0 ? n_tasks - 1 : 0; - if (wake > pool->n_workers) wake = pool->n_workers; - for (uint32_t i = 0; i < wake; i++) { - ray_sem_signal(&pool->work_ready); + /* Calculate number of tasks. + * Overflow guard: total_elems + grain - 1 could wrap for extreme values. */ + if (RAY_UNLIKELY(total_elems > INT64_MAX - grain + 1)) + total_elems = INT64_MAX - grain + 1; + int64_t n_tasks = (total_elems + grain - 1) / grain; + + pool_ring_grow(pool, n_tasks); + + /* Progress: when a callback is listening (PROGRESS bit armed), baseline the + * row counter for this dispatch so the main thread can pump a 0→100% bar + * from its claim/spin path. One relaxed load; skipped entirely otherwise. + * Baselined once for all rounds: the counter accumulates across them. */ + const bool prog = ray_qstats_mode() & RAY_QS_PROGRESS; + if (prog) ray_progress_dispatch_begin((uint64_t)total_elems); + pool_scan_dispatch_begin(pool); + + /* The ring holds task_cap tasks at a time (MAX_RING_CAP, or less when + * growing it failed). Anything past that runs in further rounds of the + * same grain: widening the grain to fit the ring instead moved task + * starts off the grain boundaries every caller indexes by (#792). + * A cancelled query runs no further round: every ticket of one would be + * skipped anyway, and the rounds left can number in the hundreds. */ + const uint32_t cap = pool_round_cap(pool); + for (int64_t first = 0; first < n_tasks; ) { + if (RAY_UNLIKELY(atomic_load_explicit(&pool->cancelled, memory_order_relaxed))) + break; + int64_t batch = n_tasks - first; + if (batch > (int64_t)cap) batch = cap; + dispatch_round(pool, fn, ctx, total_elems, grain, first, (uint32_t)batch, prog); + first += batch; } +} - /* Main thread participates as worker 0 */ - if (pool->steal) { - pool_main_run_steal(pool, prog); - } else { - uint64_t idx; - while (pool_claim(pool, &idx)) { - if (RAY_UNLIKELY(atomic_load_explicit(&pool->cancelled, - memory_order_relaxed))) { - atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); - continue; - } +void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, + int64_t total_elems) { + pool_dispatch_at(pool, fn, ctx, total_elems, TASK_GRAIN); +} - ray_pool_task_t* t = &pool->tasks[idx & (pool->task_cap - 1)]; - int64_t _qs_t0; uint32_t _qs_m = ray_qstats_task_begin(&_qs_t0); - t->fn(t->ctx, 0, t->start, t->end); - ray_qstats_task_end(_qs_m, 0, t->end - t->start, _qs_t0); +void ray_pool_dispatch_grain(ray_pool_t* pool, ray_pool_fn fn, void* ctx, + int64_t total_elems, int64_t grain) { + pool_dispatch_at(pool, fn, ctx, total_elems, grain); +} - atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); - if (prog) ray_progress_pump(); - } +void ray_pool_dispatch_geometry(ray_pool_t* pool, int64_t total_elems, int64_t grain, + uint32_t* n_tasks, int64_t* eff_grain) { + (void)pool; /* rounds keep the grain: the geometry is the arithmetic */ + *n_tasks = 0; *eff_grain = grain; + if (total_elems <= 0) return; + if (RAY_UNLIKELY(total_elems > INT64_MAX - grain + 1)) + total_elems = INT64_MAX - grain + 1; + *n_tasks = (uint32_t)((total_elems + grain - 1) / grain); +} - /* Spin-wait for workers to finish remaining tasks */ - unsigned spin_count = 0; - while (atomic_load_explicit(&pool->pending, memory_order_acquire) > 0) { - RAY_CPU_RELAX(); - if (++spin_count % 1024 == 0) { sched_yield(); if (prog) ray_progress_pump(); } - } +/* One round of ray_pool_dispatch_n: tasks [first, first+n_tasks), each handed + * to fn as [i, i+1) with its ABSOLUTE index, n_tasks <= task_cap. */ +static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, + uint32_t first, uint32_t n_tasks, bool prog) { + uint64_t base = pool_window_base(pool); + + /* Fill task ring: one task per partition, tickets [base, base+n_tasks) */ + for (uint32_t i = 0; i < n_tasks; i++) { + uint32_t slot = (uint32_t)((base + i) & (pool->task_cap - 1)); + pool->tasks[slot].fn = fn; + pool->tasks[slot].ctx = ctx; + pool->tasks[slot].start = (int64_t)(first + i); + pool->tasks[slot].end = (int64_t)(first + i) + 1; } - pool_scan_end(pool); - atomic_store_explicit(&ray_parallel_flag, 0, memory_order_release); - atomic_thread_fence(memory_order_seq_cst); - ray_rc_sync = false; - pool_reclaim_worker_heaps(pool); + pool_scan_begin(pool, -1, base, 0); /* tasks are not row ranges */ + pool_run_window(pool, base, n_tasks, prog); } /* -------------------------------------------------------------------------- @@ -996,28 +1016,25 @@ void ray_pool_dispatch_n(ray_pool_t* pool, ray_pool_fn fn, void* ctx, uint32_t n_tasks) { if (n_tasks == 0) return; - /* Grow ring if needed */ - if (n_tasks > pool->task_cap) { - uint32_t new_cap = pool->task_cap; - while (new_cap < n_tasks && new_cap < MAX_RING_CAP) new_cap *= 2; - if (new_cap > pool->task_cap) { - ray_pool_task_t* new_tasks = (ray_pool_task_t*)ray_sys_realloc( - pool->tasks, new_cap * sizeof(ray_pool_task_t)); - if (new_tasks) { - pool->tasks = new_tasks; - pool->task_cap = new_cap; - } - } - } + pool_ring_grow(pool, (int64_t)n_tasks); + + /* Progress: baseline this dispatch (one unit per task/partition), once + * for all of its rounds. */ + const bool prog = ray_qstats_mode() & RAY_QS_PROGRESS; + if (prog) ray_progress_dispatch_begin((uint64_t)n_tasks); + pool_scan_dispatch_begin(pool); /* The ring holds task_cap tasks at a time. Anything past that runs in * further rounds rather than being dropped: a window with more * partitions than the ring, or a join with more morsels, used to lose - * every task past the cap silently. */ + * every task past the cap silently. A cancelled query runs no further + * round (see ray_pool_dispatch). */ for (uint32_t first = 0; first < n_tasks; ) { + if (RAY_UNLIKELY(atomic_load_explicit(&pool->cancelled, memory_order_relaxed))) + break; uint32_t batch = n_tasks - first; if (batch > pool->task_cap) batch = pool->task_cap; - dispatch_n_round(pool, fn, ctx, first, batch); + dispatch_n_round(pool, fn, ctx, first, batch, prog); first += batch; } } @@ -1046,6 +1063,12 @@ static void pool_trace_arm(void) { if (!armed && g_pool.trace) { armed = true; atexit(pool_trace_atexit); } } +uint32_t ray_pool_size(void) { + if (atomic_load_explicit(&g_pool_init_state, memory_order_acquire) == 2) + return ray_pool_total_workers(&g_pool); + return pool_default_workers() + 1; +} + ray_pool_t* ray_pool_get(void) { uint32_t state = atomic_load_explicit(&g_pool_init_state, memory_order_acquire); if (state == 2) return &g_pool; diff --git a/src/core/pool.h b/src/core/pool.h index 7c11e3511..4420eeba5 100644 --- a/src/core/pool.h +++ b/src/core/pool.h @@ -160,18 +160,16 @@ struct ray_pool { /* Total workers = n_workers + 1 (main thread is worker 0) */ #define ray_pool_total_workers(p) ((p)->n_workers + 1) -/* Maximum number of tasks per ray_pool_dispatch call (ring capacity ceiling). - * Workloads that would require more tasks must either fall back to a serial - * path or be restructured — the dispatcher clamps n_tasks and re-derives a - * non-morsel-aligned grain, which breaks slot math in morsel-sensitive callers - * (e.g. exec_pred_to_selection). Value must stay in sync with MAX_RING_CAP - * in pool.c. */ +/* Task-ring capacity ceiling. A dispatch that needs more tasks than the ring + * holds (this ceiling, or a smaller ring that failed to grow) runs them in + * further rounds; the per-task ranges are unchanged, so ray_pool_dispatch's + * tasks always start on TASK_GRAIN boundaries. Value must stay in sync with + * MAX_RING_CAP in pool.c. */ #define RAY_POOL_MAX_TASKS (1u << 16) /* Initial task-ring capacity (power of 2). ray_pool_dispatch_n callers that - * must never trigger ring growth (its clamp-on-grow-failure silently DROPS - * tasks) cap their task count at this value — one shared constant instead of - * a hardcoded 1024 at every site. */ + * want their tasks in one round, with no ring growth, cap their task count at + * this value — one shared constant instead of a hardcoded 1024 at every site. */ #define RAY_POOL_INIT_TASKS 1024u /* True when a data-parallel dispatch is both worthwhile AND safe: a live @@ -199,15 +197,21 @@ void ray_pool_free(ray_pool_t* pool); * walks its own slice in order and then takes chunks cut from the END of * other workers' slices; with the shared cursor tasks start in index order * but still finish in any order). Callers may rely only on (a) each task - * running exactly once, (b) a task's identity — its [start, end) or index — - * which is what results must be placed by, and (c) everything being done - * when the dispatch returns. Anything that stops early ("first N", a - * cutoff, a bound) must be sound whatever the order: derive it from row - * positions or values, never from "the tasks before this one have run" - * (see ray_fused_take_select in fused_topk.c for the pattern). */ + * running at most once, and exactly once unless the dispatch was + * cancelled, (b) a task's identity — its [start, end) or index — which is + * what results must be placed by, and (c) everything that ran being done + * when the dispatch returns. A cancel (ray_request_interrupt, or the + * pool's cancelled flag) makes the dispatch skip every task that has not + * started and return normally; a task that has started runs to its end. + * A caller whose outputs need every task must check ray_interrupted() and + * the pool's cancelled flag after the dispatch before consuming them, and + * either give up or run the skipped tasks itself (see + * ray_sym_domain_intern_batch in table/domain.c). Anything that stops + * early ("first N", a cutoff, a bound) must be sound whatever the order: + * derive it from row positions or values, never from "the tasks before + * this one have run" (see ray_fused_take_select in fused_topk.c for the + * pattern). */ -/* Dispatch fn over [0, total_elems) partitioned into morsel-sized tasks. - * Blocks until all tasks complete. Main thread participates as worker 0. */ /* Register the columns the calling thread's next dispatches scan (NULL * clears); returns the previous registration so nested executions can * restore it. The registration must outlive those dispatches. */ @@ -241,7 +245,32 @@ bool ray_pool_scan_on(void); * a dispatch. */ void ray_pool_want(const void* p, size_t bytes); +/* Dispatch fn over [0, total_elems) partitioned into morsel-sized tasks. + * Blocks until all tasks complete. Main thread participates as worker 0. + * Contract: every task is one grain, [i*grain, min((i+1)*grain, total)) + * (TASK_GRAIN, RAY_DISPATCH_MORSELS morsels). When the tasks outnumber the + * ring (above RAY_POOL_MAX_TASKS, or a ring whose growth failed) they run + * in further rounds of the same grain (#792), so a caller keeping per-grain + * state may still walk its task grain by grain. */ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, int64_t total_elems); +/* ray_pool_dispatch at `grain` elements per task (a whole multiple of + * RAY_MORSEL_ELEMS), under the same clamp and contract. */ +void ray_pool_dispatch_grain(ray_pool_t* pool, ray_pool_fn fn, void* ctx, + int64_t total_elems, int64_t grain); +/* The task count and grain a dispatch of total_elems at `grain` takes (the + * default grain is RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS): rounds keep the + * grain, so *eff_grain == grain and *n_tasks is ceil(total / grain); a + * ray_pool_dispatch_grain at *eff_grain runs exactly *n_tasks tasks + * starting at multiples of *eff_grain: two passes that size per-task state + * from this agree. */ +void ray_pool_dispatch_geometry(ray_pool_t* pool, int64_t total_elems, int64_t grain, + uint32_t* n_tasks, int64_t* eff_grain); +/* Test hook (C tests only): ray_pool_dispatch's ring growth fails (its + * realloc returns NULL) and a round holds at most `cap` tasks, so the + * further rounds run at test sizes as they do above task_cap * TASK_GRAIN + * elements when the realloc fails, or above RAY_POOL_MAX_TASKS tasks; 0 off. + * Disarmed by ray_test_hooks_off. */ +void ray_pool_test_ring_fail(uint32_t cap); /* Dispatch exactly n_tasks tasks, each with range [i, i+1). * Used for partition-parallel workloads where each task is one partition. */ @@ -249,12 +278,20 @@ void ray_pool_dispatch_n(ray_pool_t* pool, ray_pool_fn fn, void* ctx, uint32_t n /* Global pool lifecycle (lazy singleton) */ ray_pool_t* ray_pool_get(void); +/* Threads of the global pool, main included: its size when it exists, else + * the size a default one would get (nothing is created). */ +uint32_t ray_pool_size(void); /* Public pool init/destroy (moved from rayforce.h) */ ray_err_t ray_pool_init(uint32_t n_workers); /* Initialize by total execution participants, including the main thread. * Pass 0 to auto-detect. Used by the CLI, where -c is a total-core count. */ ray_err_t ray_pool_init_total(uint32_t total_workers); + +/* The default pool size, main included: one thread per CPU the process may + * run on (ray_cpu_set_count), or per CPU of a cgroup CPU quota, rounded up, + * when that is smaller (docker --cpus, systemd CPUQuota=). */ +uint32_t ray_pool_default_total(void); void ray_pool_destroy(void); /* Call fn on the heap of every worker of the live singleton pool; nothing diff --git a/src/core/runtime.c b/src/core/runtime.c index a67d69b93..36f66f66c 100644 --- a/src/core/runtime.c +++ b/src/core/runtime.c @@ -26,6 +26,8 @@ #include "mem/heap.h" #include "mem/sys.h" #include "table/sym.h" +#include "ops/idxop.h" /* ray_idx_lazy_clear — the lazy hash cache */ +#include "ops/internal.h" /* ray_dict_cd_runtime_gone — the group-by DICT code stash */ #include "store/part.h" #include #include @@ -112,6 +114,7 @@ const char* ray_err_code_str(ray_err_t e) { * is capped at 7 bytes — the past-tense form would truncate. */ [RAY_ERR_RESERVED] = "reserve", [RAY_ERR_VERSION] = "version", + [RAY_ERR_FPENV] = "fpenv", }; if ((unsigned)e >= sizeof(codes)/sizeof(codes[0])) return "error"; return codes[e]; @@ -131,6 +134,7 @@ ray_err_t ray_err_from_obj(ray_t* err) { {"name", 4, RAY_ERR_NAME}, {"limit", 5, RAY_ERR_LIMIT}, {"reserve", 7, RAY_ERR_RESERVED}, {"version", 7, RAY_ERR_VERSION}, + {"fpenv", 5, RAY_ERR_FPENV}, }; for (int i = 0; i < (int)(sizeof(map)/sizeof(map[0])); i++) if (n == map[i].len && memcmp(s, map[i].s, n) == 0) return map[i].e; @@ -172,6 +176,13 @@ static ray_t* ray_verror(const char* code, const char* fmt, va_list ap) { } ray_t* ray_error(const char* code, const char* fmt, ...) { + /* Enum-only save wrappers reconstruct errors with fmt == NULL. Give + * this caller-environment error useful context without reusing stale TLS + * text or changing the message behavior of any other error code. This + * literal deliberately contains no printf conversions. */ + if (!fmt && code && strcmp(code, "fpenv") == 0) + fmt = "compressed floating-point I/O requires default FP controls " + "(FE_TONEAREST, masked exceptions, no FTZ/DAZ)"; if (fmt) { va_list ap; va_start(ap, fmt); @@ -405,7 +416,7 @@ uint8_t ray_obj_attrs(ray_t* v) { int64_t ray_vec_get_i64(ray_t* vec, int64_t idx) { if (!vec || idx < 0 || idx >= vec->len) return 0; - if (vec->type == RAY_I64 || vec->type == RAY_TIMESTAMP) { + if (vec->type == RAY_I64 || vec->type == RAY_TIMESPAN || vec->type == RAY_TIMESTAMP) { return ((const int64_t*)ray_data(vec))[idx]; } if (vec->type == RAY_I32 || vec->type == RAY_DATE || vec->type == RAY_TIME) { @@ -432,6 +443,10 @@ int64_t ray_vec_get_sym_id(ray_t* vec, int64_t idx) { void ray_runtime_destroy(ray_runtime_t* rt) { if (!rt) return; + /* The lazy hash cache holds column references: release them while the + * heap and the globals that share those columns are still alive. */ + ray_idx_lazy_clear(); + ray_lang_destroy(); /* Free VMs */ @@ -458,6 +473,12 @@ void ray_runtime_destroy(ray_runtime_t* rt) { g_ray_profile.n = 0; g_ray_profile_last.n = 0; + /* exec_group's DICT code stash (thread-local, for a later count- + * distinct) is heap memory: free this thread's before the heap goes and + * mark every other thread's stale, or the next runtime's first group-by + * frees a pointer into the dead heap (#865). */ + ray_dict_cd_runtime_gone(); + ray_parted_cache_clear(); ray_sym_destroy(); ray_heap_destroy(); diff --git a/src/core/runtime.h b/src/core/runtime.h index 135295825..eb06c1347 100644 --- a/src/core/runtime.h +++ b/src/core/runtime.h @@ -203,10 +203,6 @@ ray_t* ray_error(const char* code, const char* fmt, ...); const char* ray_err_code(ray_t* err); /* ray_error_free() is published in include/rayforce.h */ -/* Read VM error detail message (NULL if empty) */ -const char* ray_error_msg(void); - -/* Clear VM error detail */ -void ray_error_clear(void); +/* ray_error_msg / ray_error_clear: public, include/rayforce.h */ #endif /* RAY_RUNTIME_H */ diff --git a/src/core/timer.c b/src/core/timer.c index ae8c8bb40..925ba8e77 100644 --- a/src/core/timer.c +++ b/src/core/timer.c @@ -188,19 +188,27 @@ uint32_t ray_timers_fire_expired(ray_timers_t* t) { * releases both. The result (if any) is a new ref the caller * must release. */ ray_t* arg = make_i64(now); + /* A callback is a top-level evaluation of its own: a (raise x) + * left uncaught by the last REPL line must not be reported + * against this callback's error. */ + ray_raise_clear(); ray_t* result = call_fn1(timer->fn, arg); ray_release(arg); if (result) { if (RAY_IS_ERR(result)) { /* An error formats as its code alone; the message lives - * in the runtime's last-error slot. Print both, as the + * in the runtime's last-error slot, or, for an uncaught + * (raise x), x itself is pending. Print both, as the * REPL does, so a failing poll names its peer and cause. */ char code[8] = {0}; + char raised[512]; memcpy(code, result->sdata, result->slen < 7 ? result->slen : 7); const char* detail = ray_error_msg(); + if (!detail && ray_raise_render(raised, sizeof raised)) detail = raised; fprintf(stderr, "timer %lld: error: %s%s%s\n", (long long)timer->id, code, detail ? ": " : "", detail ? detail : ""); + ray_raise_clear(); ray_error_free(result); } else { ray_release(result); diff --git a/src/core/timespan.c b/src/core/timespan.c new file mode 100644 index 000000000..7de3a3aa6 --- /dev/null +++ b/src/core/timespan.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "core/timespan.h" +#include +#include +#include +#include +#include + +#define DAY_NS UINT64_C(86400000000000) + +static bool two_digits(const char** p, unsigned* out) { + const char* s = *p; + if (s[0] < '0' || s[0] > '9') return false; + if (s[1] < '0' || s[1] > '9') return false; + *out = (unsigned)(s[0] - '0') * 10 + (unsigned)(s[1] - '0'); + *p += 2; + return true; +} + +int ray_parse_timespan(const char* text, size_t* consumed, int64_t* value) { + const char* p = text; + bool negative = *p == '-'; + if (negative) p++; + if (p[0] == '0' && p[1] == 'N' && p[2] == 'n' && !negative) { + *value = INT64_MIN; *consumed = 3; return 1; + } + if (p[0] == '0' && p[1] == 'W' && p[2] == 'n') { + *value = negative ? -INT64_MAX : INT64_MAX; + *consumed = negative ? 4 : 3; return 1; + } + if (*p < '0' || *p > '9') return 0; + uint64_t days = 0; + unsigned day_digits = 0; + while (*p >= '0' && *p <= '9') { + if (++day_digits > 6) return 0; + days = days * 10 + (unsigned)(*p++ - '0'); + } + if (*p++ != 'D') return 0; + unsigned h = 0, m = 0, seconds = 0; + uint64_t fraction = 0; + const char* field = p; + unsigned digits = 0; + while (*p >= '0' && *p <= '9') { p++; if (++digits > 6) return 0; } + if (digits) { + if (*p == ':') { + if (digits != 2) return 0; + h = (unsigned)(field[0] - '0') * 10 + (unsigned)(field[1] - '0'); + p++; + if (!two_digits(&p, &m)) return 0; + if (*p == ':') { p++; if (!two_digits(&p, &seconds)) return 0; } + } else { + unsigned hour_digits = digits <= 2 ? digits : digits == 6 ? 2 : digits - 2; + for (unsigned i = 0; i < hour_digits; i++) h = h * 10 + (unsigned)(field[i] - '0'); + if (digits > 2) m = (unsigned)(field[hour_digits] - '0') * 10 + (unsigned)(field[hour_digits + 1] - '0'); + if (digits == 6) seconds = (unsigned)(field[4] - '0') * 10 + (unsigned)(field[5] - '0'); + } + if (m > 59 || seconds > 59) return 0; + if (*p == '.') { + p++; + if (*p < '0' || *p > '9') return 0; + unsigned n = 0; + while (*p >= '0' && *p <= '9') { + if (n < 9) { fraction = fraction * 10 + (unsigned)(*p - '0'); n++; } + p++; + } + while (n++ < 9) fraction *= 10; + } + } + uint64_t tail = ((uint64_t)h * 3600 + m * 60 + seconds) * UINT64_C(1000000000) + fraction; + uint64_t ns = days * DAY_NS + tail; + if (negative) ns = UINT64_C(0) - ns; + if (ns == (UINT64_C(1) << 63)) return 0; + memcpy(value, &ns, sizeof(ns)); + *consumed = (size_t)(p - text); + return 1; +} + +int ray_format_timespan(char* out, size_t size, int64_t value) { + if (value == INT64_MIN) return snprintf(out, size, "0Nn"); + if (value == INT64_MAX) return snprintf(out, size, "0Wn"); + if (value == -INT64_MAX) return snprintf(out, size, "-0Wn"); + uint64_t ns = value < 0 ? (uint64_t)-value : (uint64_t)value; + uint64_t days = ns / DAY_NS; + ns %= DAY_NS; + uint64_t seconds = ns / UINT64_C(1000000000); + return snprintf(out, size, "%s%" PRIu64 "D%02u:%02u:%02u.%09u", + value < 0 ? "-" : "", days, (unsigned)(seconds / 3600), + (unsigned)(seconds / 60 % 60), (unsigned)(seconds % 60), + (unsigned)(ns % UINT64_C(1000000000))); +} diff --git a/src/core/timespan.h b/src/core/timespan.h new file mode 100644 index 000000000..4f8a24470 --- /dev/null +++ b/src/core/timespan.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_TIMESPAN_H +#define RAY_TIMESPAN_H +#include +#include +/* Parse one duration prefix; consumed excludes the token delimiter. */ +int ray_parse_timespan(const char* text, size_t* consumed, int64_t* value); +int ray_format_timespan(char* out, size_t size, int64_t value); +#endif diff --git a/src/core/types.c b/src/core/types.c index 0599fcb24..7a4409dd3 100644 --- a/src/core/types.c +++ b/src/core/types.c @@ -23,8 +23,8 @@ #include "core/types.h" -/* Element sizes indexed by type tag. Only types 0-14 (vectors) have - * non-zero entries; remaining indices are zero (safe for non-vector types). */ +/* Element sizes indexed by type tag. Concrete vectors and LIST have + * non-zero entries; internal tag holes remain zero. */ const uint8_t ray_type_sizes[256] = { /* [RAY_LIST] = 0 */ 8, /* pointer-sized (ray_t*) */ /* [RAY_BOOL] = 1 */ 1, @@ -41,6 +41,7 @@ const uint8_t ray_type_sizes[256] = { /* [RAY_SYM] = 12 */ 8, /* W64 default; narrow widths use ray_sym_elem_size */ /* [RAY_STR] = 13 */ 16, /* sizeof(ray_str_t) */ /* [RAY_SEL] = 14 */ 0, /* variable-size layout, no elem_size */ + [RAY_TIMESPAN] = 8, }; /* ===== Semantic Version API ===== */ diff --git a/src/core/types.h b/src/core/types.h index 728f1d998..20c68f9a6 100644 --- a/src/core/types.h +++ b/src/core/types.h @@ -32,9 +32,10 @@ * Internal .c files can include either rayforce.h directly or types.h. */ #include +#include /* Number of types (positive range): must be > max type ID */ -#define RAY_TYPE_COUNT 15 +#define RAY_TYPE_COUNT 17 /* Type sizes lookup table (defined in types.c) */ extern const uint8_t ray_type_sizes[256]; @@ -67,6 +68,15 @@ static inline int16_t ray_cast_f64_to_i16_null(double v) { return (int16_t)v; } +/* F32 has no infinities either: a value past FLT_MAX saturates, as the + * integer narrowings above do. NaN (the float null) stays null. */ +static inline float ray_cast_f64_to_f32_null(double v) { + if (v != v) return NULL_F32; + if (v >= (double)FLT_MAX) return FLT_MAX; + if (v <= -(double)FLT_MAX) return -FLT_MAX; + return (float)v; +} + static inline uint8_t ray_cast_f64_to_u8_null(double v) { if (v != v || v <= 0.0) return 0; if (v >= (double)UINT8_MAX) return UINT8_MAX; @@ -74,7 +84,8 @@ static inline uint8_t ray_cast_f64_to_u8_null(double v) { } static inline uint8_t ray_cast_f64_to_bool_null(double v) { - return (v == v && v != 0.0) ? 1 : 0; + /* BOOL has no null: every non-zero value, including NaN, is true. */ + return v != 0.0 ? 1 : 0; } /* Two's-complement wraparound integer add/mul. Signed overflow is UB in C; diff --git a/src/io/csv.c b/src/io/csv.c index c7e4cf9f4..c907d2697 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -37,6 +37,7 @@ #define _GNU_SOURCE #endif +#include "core/timespan.h" #include "csv.h" #include "mem/heap.h" #include "mem/sys.h" @@ -46,7 +47,7 @@ #include "core/platform.h" /* ray_vm_map_fd_ro / ray_vm_unmap_file (tracked) */ #include "lang/format.h" #include "ops/hash.h" -#include "ops/idxop.h" /* ray_index_payload — shared hash-upgrade policy */ +#include "ops/idxop.h" /* ray_index_payload */ #include "store/col.h" #include "store/fileio.h" #include "store/splay.h" @@ -298,6 +299,19 @@ static void csv_cardinality_note(uint32_t* hashes, uint16_t* lens, non_null[col]++; } +static int64_t fast_timespan(const char* field, size_t len, bool* is_null) { + char text[128]; + size_t used = 0; + int64_t value = NULL_I64; + *is_null = true; + if (len >= sizeof(text)) return value; + memcpy(text, field, len); + text[len] = 0; + if (ray_parse_timespan(text, &used, &value) && used == len) + *is_null = value == NULL_I64; + return *is_null ? NULL_I64 : value; +} + static int8_t csv_resolve_inferred_type(csv_type_t t, uint16_t distinct, uint16_t non_null) { @@ -307,6 +321,7 @@ static int8_t csv_resolve_inferred_type(csv_type_t t, case CSV_TYPE_F64: return RAY_F64; case CSV_TYPE_DATE: return RAY_DATE; case CSV_TYPE_TIME: return RAY_TIME; + case CSV_TYPE_TIMESPAN: return RAY_TIMESPAN; case CSV_TYPE_TIMESTAMP: return RAY_TIMESTAMP; case CSV_TYPE_GUID: return RAY_GUID; case CSV_TYPE_STR: @@ -2225,6 +2240,7 @@ static void csv_parse_fn(void* arg, uint32_t worker_id, case CSV_TYPE_F64: ((double*)ctx->col_data[c])[row] = NULL_F64; break; case CSV_TYPE_DATE: ((int32_t*)ctx->col_data[c])[row] = NULL_I32; break; case CSV_TYPE_TIME: ((int32_t*)ctx->col_data[c])[row] = NULL_I32; break; + case CSV_TYPE_TIMESPAN: case CSV_TYPE_TIMESTAMP: ((int64_t*)ctx->col_data[c])[row] = NULL_I64; break; case CSV_TYPE_GUID: @@ -2320,6 +2336,13 @@ static void csv_parse_fn(void* arg, uint32_t worker_id, if (is_null) my_had_null[c] = true; break; } + case CSV_TYPE_TIMESPAN: { + bool is_null; + int64_t v = fast_timespan(fld, flen, &is_null); + ((int64_t*)ctx->col_data[c])[row] = is_null ? NULL_I64 : v; + if (is_null) my_had_null[c] = true; + break; + } case CSV_TYPE_TIMESTAMP: { bool is_null; int64_t v = fast_timestamp(fld, flen, &is_null); @@ -2412,6 +2435,7 @@ static bool csv_parse_serial(const char* buf, size_t buf_size, case CSV_TYPE_F64: ((double*)col_data[c])[row] = NULL_F64; break; case CSV_TYPE_DATE: ((int32_t*)col_data[c])[row] = NULL_I32; break; case CSV_TYPE_TIME: ((int32_t*)col_data[c])[row] = NULL_I32; break; + case CSV_TYPE_TIMESPAN: case CSV_TYPE_TIMESTAMP: ((int64_t*)col_data[c])[row] = NULL_I64; break; case CSV_TYPE_GUID: @@ -2505,6 +2529,13 @@ static bool csv_parse_serial(const char* buf, size_t buf_size, if (is_null) col_had_null[c] = true; break; } + case CSV_TYPE_TIMESPAN: { + bool is_null; + int64_t v = fast_timespan(fld, flen, &is_null); + ((int64_t*)col_data[c])[row] = is_null ? NULL_I64 : v; + if (is_null) col_had_null[c] = true; + break; + } case CSV_TYPE_TIMESTAMP: { bool is_null; int64_t v = fast_timestamp(fld, flen, &is_null); @@ -2557,125 +2588,6 @@ static bool csv_parse_serial(const char* buf, size_t buf_size, return true; } -/* Per-column elem size for the hash-attach cap. Mirrors the integer - * shapes accepted by ray_index_attach_hash (BOOL/U8/I16/I32/I64/DATE/ - * TIME/TIMESTAMP); returns 0 for floats and dict-backed types so the - * caller skips them. */ -static int csv_hash_elem_size(int8_t t) { - switch (t) { - case RAY_BOOL: case RAY_U8: return 1; - case RAY_I16: return 2; - case RAY_I32: case RAY_DATE: return 4; - case RAY_I64: case RAY_TIME: case RAY_TIMESTAMP: return 8; - default: return 0; - } -} - -/* Decide whether `v` is a good candidate for an auto-attached hash - * index, using only its (already-attached) chunk_zone as the entropy - * proxy. A column is "random-shaped" when each chunk's [min, max] - * covers more than half the global range — i.e. there's effectively - * no clustering, so the per-chunk zone-skip never excludes a chunk - * and the only way to accelerate `col == K` is by hashing. - * - * The memory cap rejects columns where the hash index (table+chain - * arrays — ~24 bytes/row at default load factor) would be much larger - * than the data itself. We use 5× the column's data bytes as the - * budget: this comfortably admits I32/I64 numeric IDs (where the - * index is 3–5× the data) while still excluding narrow types like - * BOOL/U8/I16 where the index would dwarf the column. - * - * Returns 1 to attach, 0 to skip. */ -/* Payload-level core of the hash-upgrade decision. Its only caller is the - * .csv.splayed / Parquet conversion path: the stream writer builds each - * column's chunk zone inline and, for integer columns whose zone passes this - * check, the column is re-read once to build the hash. Indexing is a - * CONVERSION-time decision, made once and persisted with the column files. - * A `.csv.read` into memory attaches nothing (it used to run this same - * heuristic over every column and throw the result away — 19.7 s of a 46 s - * 8 GB load), so there is no in-memory decision left for the on-disk one to - * match. It lives here because the heuristic is written against the - * chunk-zone payload the CSV type machinery defines. */ -int ray_csv_hash_upgrade_check(int8_t type, int64_t len, - const void* index_payload) { - const ray_index_t* ix = (const ray_index_t*)index_payload; - int esz = csv_hash_elem_size(type); - if (esz == 0) return 0; - if (!ix || ix->kind != RAY_IDX_CHUNK_ZONE || ix->u.chunk_zone.is_f64) - return 0; - uint32_t n_chunks = ix->u.chunk_zone.n_chunks; - if (n_chunks < 4) return 0; - const int64_t* mins = (const int64_t*)ray_data(ix->u.chunk_zone.mins); - const int64_t* maxs = (const int64_t*)ray_data(ix->u.chunk_zone.maxs); - - /* Whole-column [gmin, gmax] from the chunk extrema, ignoring empty - * chunks (mn > mx, set by the chunk_zone scan when a chunk is fully - * null). */ - int64_t gmin = INT64_MAX, gmax = INT64_MIN; - for (uint32_t g = 0; g < n_chunks; g++) { - if (mins[g] > maxs[g]) continue; - if (mins[g] < gmin) gmin = mins[g]; - if (maxs[g] > gmax) gmax = maxs[g]; - } - if (gmin == INT64_MAX || gmax == INT64_MIN) return 0; - /* Compute (gmax - gmin) in uint64 space — the signed subtraction - * overflows when the range spans the full I64 width (e.g. UserID - * hashing to both sign halves). Reinterpret as uint64 first; - * 2's-complement wrap gives the correct |gmax - gmin|. */ - uint64_t global_range = (uint64_t)gmax - (uint64_t)gmin; - if (global_range == 0) return 0; /* constant column — pointless */ - - /* Average per-chunk span / global range — selectivity proxy. - * Sum the per-chunk spans as doubles so the accumulation can't - * overflow when chunks span the full I64 width (uint64 sum - * across ~150 chunks each ~1.8e19 wide overflows; double has - * ~15 significant decimal digits, plenty for this coarse ratio). - * - * Threshold = 0.5. mean_ratio measures how much of the global - * value range an average chunk spans: it is the entropy/clustering - * signal that decides whether a hash index pays off. A value - * near 1.0 means each chunk already covers (almost) the whole - * range — the column is effectively uniformly random, chunk_zone - * min/max pruning is useless, so every point lookup degenerates - * to a full-column scan and a hash index is the only way to make - * it cheap. A small ratio means values are clustered, so - * chunk_zone already prunes most chunks and the index buys little. - * 0.5 is the natural random-vs-clustered separator: above it a - * chunk spans more than half the range (no useful zone pruning, - * index it); below it clustering gives the zone map real pruning - * power and the index's memory/build cost isn't justified. */ - double dgr = (double)global_range; - double span_sum = 0.0; - uint32_t n_eff = 0; - for (uint32_t g = 0; g < n_chunks; g++) { - if (mins[g] > maxs[g]) continue; - uint64_t span = (uint64_t)maxs[g] - (uint64_t)mins[g]; - span_sum += (double)span; - n_eff++; - } - if (n_eff < 4) return 0; - double mean_ratio = (span_sum / (double)n_eff) / dgr; - if (mean_ratio <= 0.5) return 0; - - /* Memory cap: ray_index_attach_hash allocates a power-of-two - * `cap = next_pow2(2*n)` int64 table plus an n-entry int64 - * chain. Skip when the index would cost more than 5× the - * column's payload — keeps narrow integer types (where the - * index dwarfs the data) out of the index set while admitting - * I32 / I64 numeric IDs. Done in int64 arithmetic (we cap n - * to anything that would overflow at the row counts we accept). */ - int64_t n = len; - if (n <= 0) return 0; - uint64_t cap = 8; - uint64_t want = (uint64_t)(2 * n); - while (cap < want) cap <<= 1; - uint64_t aux_bytes = cap * 8u + (uint64_t)n * 8u; - uint64_t data_bytes = (uint64_t)n * (uint64_t)esz; - if (aux_bytes > 5u * data_bytes) return 0; - - return 1; -} - /* -------------------------------------------------------------------------- * `INT` schema columns — auto narrowest integer width. * @@ -2880,6 +2792,7 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, case RAY_F64: parse_types[c] = CSV_TYPE_F64; break; case RAY_DATE: parse_types[c] = CSV_TYPE_DATE; break; case RAY_TIME: parse_types[c] = CSV_TYPE_TIME; break; + case RAY_TIMESPAN: parse_types[c] = CSV_TYPE_TIMESPAN; break; case RAY_TIMESTAMP: parse_types[c] = CSV_TYPE_TIMESTAMP; break; case RAY_GUID: parse_types[c] = CSV_TYPE_GUID; break; default: parse_types[c] = CSV_TYPE_STR; break; @@ -3278,7 +3191,7 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h for (int c = 0; c < ncols; c++) { int8_t t = col_types_in[c]; if (t < RAY_BOOL || - (t >= RAY_TYPE_COUNT && t != RAY_CSV_AUTO_TAG) || + ((t >= RAY_TYPE_COUNT || !ray_elem_size(t)) && t != RAY_CSV_AUTO_TAG) || t == RAY_TABLE) { scratch_free(row_offsets_hdr); ray_vm_unmap_file(buf, file_size); @@ -3346,6 +3259,7 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h case RAY_F64: parse_types[c] = CSV_TYPE_F64; break; case RAY_DATE: parse_types[c] = CSV_TYPE_DATE; break; case RAY_TIME: parse_types[c] = CSV_TYPE_TIME; break; + case RAY_TIMESPAN: parse_types[c] = CSV_TYPE_TIMESPAN; break; case RAY_TIMESTAMP: parse_types[c] = CSV_TYPE_TIMESTAMP; break; case RAY_GUID: parse_types[c] = CSV_TYPE_GUID; break; default: parse_types[c] = CSV_TYPE_STR; break; @@ -3554,13 +3468,9 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h /* ---- 11. Build table ---- */ { - /* No index attach at load time. Index policy lives at csv→splayed - * CONVERSION (store/splay.c: chunk-zone / dict, upgraded to a hash - * index by ray_csv_hash_upgrade_check) where the decision is made - * once and persisted. A `.csv.read` into memory used to pay for a - * chunk-zone AND a hash index on all 105 columns of an 8 GB file — - * 3.6 s + 16.1 s of a 46 s load — for indexes most in-memory reads - * never probe. Columns that need one can be indexed explicitly. */ + /* .csv.read attaches no index: indexes are a conversion-time + * decision (zones and dictionaries streamed with the columns by + * .csv.splayed / .parquet.splayed, index policy PI). */ ray_t* tbl = ray_table_new(ncols); if (!tbl || RAY_IS_ERR(tbl)) { @@ -3616,13 +3526,32 @@ ray_t* ray_read_csv_opts(const char* path, char delimiter, bool header, col_types_in, n_types, NULL, 0); } +/* Fault injection for the suite: RAY_CSV_SPLAYED_INJECT names where a + * .csv.splayed load is cancelled: "append" (from column 0's append task, + * mid-dispatch), "skip" (the last column's append task returns as a + * skipped ticket does) or "close" (before the column finish dispatch); + * debug builds only. "skip" raises no interrupt, which a real skip always + * comes with, so production never reaches it; it is kept because only it + * reaches the append done-count past the interrupt checks after it. */ +static bool csv_splayed_inject(const char* step) { +#if defined(DEBUG) + const char* e = getenv("RAY_CSV_SPLAYED_INJECT"); + return e && strcmp(e, step) == 0; +#else + (void)step; + return false; +#endif +} + /* Append task: column `start` of the chunk table into its writer. The - * first failure is kept (a later task cannot clear it). */ + * first failure is kept (a later task cannot clear it); `done` counts the + * columns appended, so a task a cancel skipped reads as not done. */ typedef struct { ray_col_stream_t* writers; ray_t* tbl; int ncols; _Atomic(ray_err_t) err; + _Atomic(int64_t) done; int64_t* col_ns; /* RAY_CSV_TRACE: per-column append time, or NULL */ } csv_splayed_append_ctx_t; @@ -3630,13 +3559,24 @@ static void csv_splayed_append_task(void* raw, uint32_t wid, int64_t start, int6 (void)wid; (void)end; csv_splayed_append_ctx_t* a = (csv_splayed_append_ctx_t*)raw; if (atomic_load_explicit(&a->err, memory_order_relaxed) != RAY_OK) return; - ray_t* col = ray_table_get_col_idx(a->tbl, (int64_t)start); + if (start == a->ncols - 1 && csv_splayed_inject("skip")) return; + ray_t* col = ray_table_col_idx(a->tbl, (int64_t)start); + if (col && RAY_IS_ERR(col)) { + ray_err_t ce = ray_err_from_obj(col); + ray_error_free(col); + ray_err_t ok = RAY_OK; + atomic_compare_exchange_strong_explicit(&a->err, &ok, ce, memory_order_relaxed, memory_order_relaxed); + return; + } int64_t tt0 = a->col_ns ? ray_profile_now_ns() : 0; ray_err_t e = ray_col_stream_append(&a->writers[start], col); if (a->col_ns) a->col_ns[start] += ray_profile_now_ns() - tt0; + if (start == 0 && csv_splayed_inject("append")) ray_request_interrupt(); if (e != RAY_OK) { ray_err_t ok = RAY_OK; atomic_compare_exchange_strong_explicit(&a->err, &ok, e, memory_order_relaxed, memory_order_relaxed); + } else { + atomic_fetch_add_explicit(&a->done, 1, memory_order_relaxed); } } @@ -3644,7 +3584,8 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool const int8_t* col_types_in, int32_t n_types, const int64_t* col_names_in, int32_t n_names, const char* dir, int64_t rows_per_chunk, - const char* sym_path) { + const char* sym_path, ray_compress_t mode, + const char* cur, ray_err_t cur_err) { if (ray_interrupted()) return RAY_ERR_CANCEL; if (!path || !dir || !sym_path) return RAY_ERR_DOMAIN; if (rows_per_chunk <= 0) rows_per_chunk = CSV_PART_ROWS_DEFAULT; @@ -3742,7 +3683,7 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool for (int c = 0; c < ncols; c++) { int8_t t = col_types_in[c]; if (t < RAY_BOOL || - (t >= RAY_TYPE_COUNT && t != RAY_CSV_AUTO_TAG) || + ((t >= RAY_TYPE_COUNT || !ray_elem_size(t)) && t != RAY_CSV_AUTO_TAG) || t == RAY_TABLE) { ray_vm_unmap_file(buf, file_size); return RAY_ERR_TYPE; @@ -3829,8 +3770,20 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool ray_col_stream_t writers[CSV_MAX_COLS]; memset(writers, 0, sizeof(writers)); for (int c = 0; c < ncols; c++) { - err = ray_col_stream_open(&writers[c], dir, col_name_ids[c], - resolved_types[c], sym_dom); + /* The column's generation (spec "Generation resolution"): only an + * inheriting column consults the destination's current generation, + * so only that one fails when it could not be resolved. */ + ray_t* na = ray_sym_str(col_name_ids[c]); + uint8_t gen = 0; + if (cur_err != RAY_OK && ray_col_resolve_type_needs_dest(mode, resolved_types[c])) + err = cur_err; + else + err = na ? ray_col_resolve_gen_type_err(mode, resolved_types[c], cur, + ray_str_ptr(na), ray_str_len(na), &gen) + : RAY_ERR_CORRUPT; + if (err == RAY_OK) + err = ray_col_stream_open(&writers[c], dir, col_name_ids[c], + resolved_types[c], sym_dom, gen); if (err == RAY_OK) err = ray_col_stream_index_begin(&writers[c], 0); if (err != RAY_OK) { for (int j = 0; j <= c; j++) ray_col_stream_abort(&writers[j]); @@ -3891,7 +3844,7 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool * encoded and written side by side. */ { csv_splayed_append_ctx_t actx = { .writers = writers, .tbl = tbl, - .ncols = ncols, .err = RAY_OK, + .ncols = ncols, .err = RAY_OK, .done = 0, .col_ns = trace ? tr_col_ns : NULL }; ray_pool_t* wpool = ray_pool_get(); if (ray_pool_par_dispatch_ok(wpool, ncols, 2)) @@ -3899,6 +3852,10 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool else for (int c = 0; c < ncols; c++) csv_splayed_append_task(&actx, 0, c, c + 1); err = actx.err; + /* A cancel skips the tasks not yet started and the dispatch + * returns normally: their columns miss this chunk (#716). */ + if (err == RAY_OK && atomic_load_explicit(&actx.done, memory_order_relaxed) != ncols) + err = RAY_ERR_CANCEL; } ray_release(tbl); int64_t tr_c3 = ray_profile_now_ns(); @@ -3919,6 +3876,10 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool if (cnt == 0) break; chunk_offset = next_offset; } + /* A cancel that lands during the last chunk's appends, once every one + * of them has started (or with the appends run in line), stops the + * load before the symfile flush and the column finish. */ + if (err == RAY_OK && ray_interrupted()) err = RAY_ERR_CANCEL; /* Flush the symfile BEFORE committing column files (writer_close * renames tmp → final): columns must never reference positions the @@ -3951,6 +3912,7 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool * zone finish, index region, header, fclose), then the renames run * serially in column order; a failed finish publishes nothing. */ memset(tr_col_ns, 0, sizeof(tr_col_ns)); + if (err == RAY_OK && csv_splayed_inject("close")) ray_request_interrupt(); if (err == RAY_OK) err = ray_col_stream_close_all(writers, ncols, false, trace ? tr_col_ns : NULL); else for (int c = 0; c < ncols; c++) ray_col_stream_abort(&writers[c]); int64_t tr_close_end = ray_profile_now_ns(); @@ -3964,27 +3926,15 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool } /* The domain was flushed before the closes and .d names columns through - * the global symbol table, so drop its tables before the hash re-read. */ + * the global symbol table, so drop its tables before .d is written. */ if (sym_dom) { ray_sym_domain_release(sym_dom); sym_dom = NULL; } int64_t tr_rel_end = ray_profile_now_ns(); if (trace) fprintf(stderr, "csv.splayed: domain_release=%.1fms\n", TR_MS(tr_rel_end - tr_close_end)); - /* Columns whose zone asked for a hash: the only files read back, before - * .d so an in-place first write never publishes a half-appended region. */ - memset(tr_col_ns, 0, sizeof(tr_col_ns)); - if (err == RAY_OK) ray_col_stream_hash_all(writers, ncols, trace ? tr_col_ns : NULL); - for (int c = 0; c < ncols; c++) - if (writers[c].index) { ray_release(writers[c].index); writers[c].index = NULL; } - int64_t tr_hash_end = ray_profile_now_ns(); - if (trace) { - for (int c = 0; c < ncols; c++) { - if (!tr_col_ns[c]) continue; - ray_t* na = ray_sym_str(col_name_ids[c]); - fprintf(stderr, "csv.splayed: hash col=%s type=%d task=%.1fms\n", - na ? ray_str_ptr(na) : "?", (int)resolved_types[c], TR_MS(tr_col_ns[c])); - } - fprintf(stderr, "csv.splayed: hash_phase=%.1fms\n", TR_MS(tr_hash_end - tr_rel_end)); - } + /* A cancel that landed in the finish phase stops the load here: + * without .d nothing is committed, and the caller's write finish + * removes what this load created. */ + if (err == RAY_OK && ray_interrupted()) err = RAY_ERR_CANCEL; /* .d LAST — the commit marker. All column files are renamed into * place by now and the symfile is flushed; a crash or error before @@ -4014,7 +3964,7 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool } } if (trace) fprintf(stderr, "csv.splayed: schema=%.1fms total=%.1fms\n", - TR_MS(ray_profile_now_ns() - tr_hash_end), TR_MS(ray_profile_now_ns() - tr_t0)); + TR_MS(ray_profile_now_ns() - tr_rel_end), TR_MS(ray_profile_now_ns() - tr_t0)); #undef TR_MS if (sym_dom) ray_sym_domain_release(sym_dom); @@ -4026,17 +3976,26 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool const int8_t* col_types_in, int32_t n_types, const int64_t* col_names_in, int32_t n_names, const char* dir, int64_t rows_per_chunk) { + return ray_csv_save_splayed_mode(path, delimiter, header, col_types_in, n_types, + col_names_in, n_names, dir, rows_per_chunk, + RAY_COMPRESS_ABSENT); +} + +ray_err_t ray_csv_save_splayed_mode(const char* path, char delimiter, bool header, + const int8_t* col_types_in, int32_t n_types, + const int64_t* col_names_in, int32_t n_names, + const char* dir, int64_t rows_per_chunk, ray_compress_t mode) { if (ray_interrupted()) return RAY_ERR_CANCEL; if (!path || !dir) return RAY_ERR_DOMAIN; char sym_path[1024]; int n = snprintf(sym_path, sizeof(sym_path), "%s/.sym", dir); if (n < 0 || (size_t)n >= sizeof(sym_path)) return RAY_ERR_RANGE; ray_splay_write_t write; - ray_err_t err = ray_splay_write_begin(dir, &write); + ray_err_t err = ray_splay_write_begin_mode(dir, mode, &write); if (err != RAY_OK) return err; err = csv_save_splayed_to_dir(path, delimiter, header, col_types_in, n_types, col_names_in, n_names, write.dir, - rows_per_chunk, sym_path); + rows_per_chunk, sym_path, mode, write.cur, write.cur_err); return ray_splay_write_finish(&write, err, false); } @@ -4044,7 +4003,8 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea const int8_t* col_types_in, int32_t n_types, const int64_t* col_names_in, int32_t n_names, const char* root, const char* table_name, - int64_t rows_per_part, bool staged) { + int64_t rows_per_part, bool staged, + ray_compress_t mode) { if (ray_interrupted()) return RAY_ERR_CANCEL; if (!path || !root || !table_name) return RAY_ERR_DOMAIN; if (rows_per_part <= 0) rows_per_part = CSV_PART_ROWS_DEFAULT; @@ -4142,7 +4102,7 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea for (int c = 0; c < ncols; c++) { int8_t t = col_types_in[c]; if (t < RAY_BOOL || - (t >= RAY_TYPE_COUNT && t != RAY_CSV_AUTO_TAG) || + ((t >= RAY_TYPE_COUNT || !ray_elem_size(t)) && t != RAY_CSV_AUTO_TAG) || t == RAY_TABLE) { ray_vm_unmap_file(buf, file_size); return RAY_ERR_TYPE; @@ -4236,7 +4196,8 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea /* Match Parquet parted output: build numeric zones while the bounded * decoded partition is resident, before serialization. */ for (int64_t c = 0; c < ray_table_ncols(tbl); c++) { - ray_t* col = ray_table_get_col_idx(tbl,c); + ray_t* col = ray_table_col_idx(tbl,c); + if (col && RAY_IS_ERR(col)) { err = ray_err_from_obj(col); ray_error_free(col); break; } if (col->type == RAY_STR || col->type == RAY_SYM || col->type == RAY_F32 || col->type == RAY_GUID) continue; ray_retain(col); ray_t* indexed = col->len >= 65536 ? ray_index_attach_chunk_zone(&col,16) : ray_index_attach_zone(&col); @@ -4270,8 +4231,8 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea err = RAY_ERR_RANGE; break; } - err = staged ? ray_splay_save_staged_bulk(tbl, leaf, root_sym) - : ray_splay_save_bulk(tbl, leaf, root_sym); + err = staged ? ray_splay_save_staged_bulk_mode(tbl, leaf, root_sym, mode) + : ray_splay_save_bulk_mode(tbl, leaf, root_sym, mode); ray_release(tbl); scratch_free(row_offsets_hdr); if (err != RAY_OK) { @@ -4316,6 +4277,16 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool const int64_t* col_names, int32_t n_names, const char* root, const char* table_name, int64_t rows_per_part) { + return ray_csv_save_parted_mode(path, delimiter, header, col_types, n_types, + col_names, n_names, root, table_name, + rows_per_part, RAY_COMPRESS_ABSENT); +} + +ray_err_t ray_csv_save_parted_mode(const char* path, char delimiter, bool header, + const int8_t* col_types, int32_t n_types, + const int64_t* col_names, int32_t n_names, + const char* root, const char* table_name, + int64_t rows_per_part, ray_compress_t mode) { if (!path || !root || !*root || !table_name || !*table_name || table_name[0] == '.' || strchr(table_name,'/') || strchr(table_name,'\\')) return RAY_ERR_DOMAIN; @@ -4326,7 +4297,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool struct stat st; if (stat(dest,&st) == 0) return csv_save_parted_impl(path,delimiter,header,col_types,n_types, - col_names,n_names,dest,table_name,rows_per_part,false); + col_names,n_names,dest,table_name,rows_per_part,false,mode); /* Fail on an unreadable input before claiming the staging directory: * failed staging is retained and blocks the root, which a mistyped * source path must not do. */ @@ -4348,7 +4319,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool if (mkdir(staging,0755) != 0) return RAY_ERR_IO; #endif ray_err_t err = csv_save_parted_impl(path,delimiter,header,col_types,n_types, - col_names,n_names,staging,table_name,rows_per_part,true); + col_names,n_names,staging,table_name,rows_per_part,true,mode); if (err != RAY_OK) { /* Failed staging is kept for diagnosis only when it holds a * partition. A failure before the first one (a type vector that @@ -4599,6 +4570,12 @@ static void csv_write_cell(csv_writer_t* w, const csv_col_info_t* ci, int64_t r) case RAY_TIME: csv_write_time(w, ((const int32_t*)d)[dr]); break; + case RAY_TIMESPAN: { + char text[64]; + int n = ray_format_timespan(text, sizeof(text), ((const int64_t*)d)[dr]); + if (n > 0 && n < (int)sizeof(text)) cw_write(w, text, (size_t)n); + break; + } case RAY_TIMESTAMP: csv_write_timestamp(w, ((const int64_t*)d)[dr]); break; @@ -4675,8 +4652,18 @@ ray_err_t ray_write_csv(ray_t* table, const char* path) { return RAY_ERR_OOM; } csv_col_info_t* ci = (csv_col_info_t*)ray_data(col_info_block); - for (int64_t c = 0; c < ncols; c++) - csv_col_info_init(&ci[c], ray_table_get_col_idx(table, c)); + for (int64_t c = 0; c < ncols; c++) { + ray_t* col = ray_table_col_idx(table, c); + if (col && RAY_IS_ERR(col)) { + ray_err_t ce = ray_err_from_obj(col); + ray_error_free(col); + ray_free(col_info_block); + fclose(fp); + remove(tmp_path); + return ce; + } + csv_col_info_init(&ci[c], col); + } /* Header row: column names */ for (int64_t c = 0; c < ncols; c++) { diff --git a/src/io/csv.h b/src/io/csv.h index 5b6cc343e..542fb4773 100644 --- a/src/io/csv.h +++ b/src/io/csv.h @@ -25,6 +25,7 @@ #define RAY_CSV_H #include +#include "store/col.h" /* -------------------------------------------------------------------------- * Column type tokens used during CSV parse and schema resolution. @@ -40,6 +41,7 @@ typedef enum { CSV_TYPE_DATE, CSV_TYPE_TIME, CSV_TYPE_TIMESTAMP, + CSV_TYPE_TIMESPAN, CSV_TYPE_GUID, /* Narrow-int parse types — selected only via explicit schema (never from * inference, so they do not appear in promote_csv_type). Each parses the @@ -83,16 +85,21 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool const int64_t* col_names, int32_t n_names, const char* root, const char* table_name, int64_t rows_per_part); +ray_err_t ray_csv_save_parted_mode(const char* path, char delimiter, bool header, + const int8_t* col_types, int32_t n_types, + const int64_t* col_names, int32_t n_names, + const char* root, const char* table_name, + int64_t rows_per_part, ray_compress_t mode); ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool header, const int8_t* col_types, int32_t n_types, const int64_t* col_names, int32_t n_names, const char* dir, int64_t rows_per_chunk); +/* The same with the call's compress option (ray_compress_t); the form above + * passes RAY_COMPRESS_ABSENT, so each column inherits the destination's. */ +ray_err_t ray_csv_save_splayed_mode(const char* path, char delimiter, bool header, + const int8_t* col_types, int32_t n_types, + const int64_t* col_names, int32_t n_names, + const char* dir, int64_t rows_per_chunk, ray_compress_t mode); ray_err_t ray_write_csv(ray_t* table, const char* path); -/* Hash-vs-chunk-zone index policy for a column, from its chunk-zone entropy - * (payload-level; see csv.c). Shared by the in-memory CSV load and the - * .csv.splayed store index builder so both make the same decision. */ -int ray_csv_hash_upgrade_check(int8_t type, int64_t len, - const void* index_payload); - #endif /* RAY_CSV_H */ diff --git a/src/io/parquet.c b/src/io/parquet.c index 8f41c281d..518b7f0fe 100644 --- a/src/io/parquet.c +++ b/src/io/parquet.c @@ -13,6 +13,7 @@ #include "core/profile.h" #include "core/runtime.h" /* ray_error_msg: a pool task's error message */ #include "mem/heap.h" +#include "table/table.h" #include "mem/sys.h" /* ray_sys_free: the grouped import's redo list */ #include "table/sym.h" #include "table/domain.h" @@ -27,6 +28,7 @@ #include "store/splay.h" #include "store/stream.h" #include "store/col.h" +#include "store/colrange.h" #include "store/fileio.h" #include "lang/eval.h" #include "lang/internal.h" @@ -303,6 +305,8 @@ struct ray_parquet { pq_interval* excluded; int64_t nexcluded, exclude_pos, group_rows, bloom_skipped, parallel_batches; bool failed, emitted, borrowed, filter_nulls; + uint8_t compress; /* the import's compress option (ray_compress_t; 0 = absent) */ + bool symcol; /* the import's symfile 'column option: a symbol file per column */ }; static bool pq_reserve(uint8_t** buf, size_t* cap, size_t n) { if (n > PQ_MAX_PAGE) return false; @@ -1411,6 +1415,8 @@ static ray_parquet_t* pq_group_reader(const ray_parquet_t* parent, int64_t group r->nselected = nselected; r->noutput = parent->noutput; r->filter_pos = parent->filter_pos; r->filter_lo = parent->filter_lo; r->filter_hi = parent->filter_hi; r->filter_nulls = parent->filter_nulls; + r->compress = parent->compress; + r->symcol = parent->symcol; r->text_pattern = parent->text_pattern; r->text_pos = parent->text_pos; r->selected = ray_alloc_raw((size_t)r->nselected*sizeof(*r->selected)); r->cursors = ray_calloc_raw((size_t)r->nselected*sizeof(*r->cursors)); @@ -1425,7 +1431,8 @@ static ray_pool_t* pq_group_pool(ray_parquet_t* r) { static ray_t* pq_append_table(ray_t** vectors, ray_t* batch, int64_t ncols) { int64_t nr = ray_table_nrows(batch); for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(batch,c); + ray_t* src = ray_table_col_idx(batch,c); + if (src && RAY_IS_ERR(src)) return src; if (src->type == RAY_STR) { for (int64_t i = 0; i < nr; i++) { size_t n; const char* p = ray_str_vec_get(src,i,&n); @@ -1606,16 +1613,35 @@ static ray_t* pq_import_types(ray_parquet_t* r, ray_t* types) { if (!keys || keys->type != RAY_SYM) return pq_error("import option keys must be symbols"); for (int64_t i = 0; i < keys->len; i++) { ray_t* key = ray_sym_vec_cell(keys,i); const char* k = key ? ray_str_ptr(key) : NULL; - if (!k || (strcmp(k,"types") && strcmp(k,"strict") && strcmp(k,"rows"))) return pq_error("unknown import option"); + if (!k || (strcmp(k,"types") && strcmp(k,"strict") && strcmp(k,"rows") && strcmp(k,"compress") && strcmp(k,"symfile"))) return pq_error("unknown import option"); } ray_t* err = pq_strict_option(r,types); ray_t* rows = pq_option(types,"rows"); + if (rows && RAY_IS_ERR(rows)) { /* the lookup itself failed */ + if (!err) err = rows; else ray_error_free(rows); + rows = NULL; + } if (!err && rows) { if (rows->type != -RAY_I64 || rows->i64 < 1 || rows->i64 > PQ_MAX_PART_ROWS) err = pq_error("partition rows must be 1..1048576"); else r->batch_rows = rows->i64; } if (rows) ray_release(rows); + ray_t* cmp = pq_option(types,"compress"); + if (cmp && RAY_IS_ERR(cmp)) { /* the lookup itself failed */ + if (!err) err = cmp; else ray_error_free(cmp); + cmp = NULL; + } + if (!err && cmp) { + if (cmp->type != -RAY_BOOL) err = ray_error("domain","parquet: compress must be true or false"); + else r->compress = cmp->b8 ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF; + } + if (cmp) ray_release(cmp); + if (!err) { + ray_symfile_t layout; + err = ray_symfile_opt_parse(types,&layout); + if (!err) r->symcol = layout == RAY_SYMFILE_COLUMN; + } ray_t* schema = pq_option(types,"types"); if (!err && schema && schema->type != RAY_SYM) err = pq_error("types must be a symbol vector"); if (!err) err = pq_import_types(r,schema); @@ -1657,7 +1683,7 @@ typedef struct { * shared vocabulary once after all workers join, before publishing the root. * Flushing it here rewrites the growing dictionary for every partition. */ static ray_err_t pq_save_partition(ray_parquet_t* r, ray_t* batch, const char* leaf, - const char* sym, bool durable) { + const char* sym, bool durable, ray_compress_t mode) { ray_sym_domain_t* domain = NULL; for (int64_t c = 0; c < r->ncols; c++) if (r->schema[c].import_domain) domain = r->schema[c].import_domain; /* No import domain means no SYM column, so the vocabulary is untouched. @@ -1666,7 +1692,8 @@ static ray_err_t pq_save_partition(ray_parquet_t* r, ray_t* batch, const char* l * the whole tree: write them as a bare staged save, without the writer * lock, generation handling or index pass that publishing a live table * needs. The spool then deletes exactly the files it wrote. */ - if (!domain) return durable ? ray_splay_save(batch,leaf,sym) : ray_splay_save_staged_bulk(batch,leaf,sym); + if (!domain) return durable ? ray_splay_save_mode(batch,leaf,sym,mode) + : ray_splay_save_staged_bulk_mode(batch,leaf,sym,mode); ray_err_t e = ray_mkdir_p(leaf); if (e != RAY_OK) return e; ray_t* schema = ray_vec_new(RAY_STR,r->ncols); if (!schema || RAY_IS_ERR(schema)) { if (schema) ray_release(schema); return RAY_ERR_OOM; } @@ -1675,9 +1702,19 @@ static ray_err_t pq_save_partition(ray_parquet_t* r, ray_t* batch, const char* l ray_t* name = ray_sym_str(r->schema[c].name); int n = snprintf(path,sizeof(path),"%s/%s",leaf,ray_str_ptr(name)); if (n < 0 || (size_t)n >= sizeof(path)) { e = RAY_ERR_RANGE; break; } - ray_t* col = ray_table_get_col_idx(batch,c); - e = col->type == RAY_SYM ? ray_col_save_sym_encoded(col,path,domain,durable) : - durable ? ray_col_save(col,path) : ray_col_save_bulk(col,path); + /* a decoded batch: plain columns, SYM over the import domain; the + * leaf is fresh, so there is no destination to inherit from */ + ray_t* col = ray_table_col_idx(batch,c); + if (col && RAY_IS_ERR(col)) { e = ray_err_from_obj(col); ray_error_free(col); break; } + ray_col_write_t cw; memset(&cw,0,sizeof cw); + ray_t* berr = ray_col_src_bind(col,&cw.src); + if (berr) { e = ray_err_from_obj(berr); ray_error_free(berr); break; } + cw.name = ray_str_ptr(name); + e = ray_col_resolve_gen_err(mode,col,NULL,ray_str_ptr(name),ray_str_len(name),&cw.gen); + cw.target_dom = col->type == RAY_SYM ? domain : NULL; + cw.durable = durable; + if (e == RAY_OK) e = ray_col_save_ctx(&cw,path); + ray_col_src_release(&cw.src); if (e != RAY_OK) break; ray_t* next = ray_str_vec_append(schema,ray_str_ptr(name),ray_str_len(name)); if (!next || RAY_IS_ERR(next)) { if (next) ray_release(next); e = RAY_ERR_OOM; break; } @@ -1698,7 +1735,8 @@ static ray_t* pq_write_reader(ray_parquet_t* r, const char* root, const char* ta if (!batch || RAY_IS_ERR(batch)) return batch; /* Native zones are built while the bounded decoded batch is resident. */ if (durable) for (int64_t c = 0; c < r->ncols; c++) { - ray_t* col = ray_table_get_col_idx(batch,c); + ray_t* col = ray_table_col_idx(batch,c); + if (col && RAY_IS_ERR(col)) { ray_release(batch); return col; } if (col->type == RAY_STR || col->type == RAY_SYM || col->type == RAY_F32) continue; ray_retain(col); ray_t* e = col->len >= PQ_BATCH ? ray_index_attach_chunk_zone(&col,16) : ray_index_attach_zone(&col); @@ -1710,7 +1748,8 @@ static ray_t* pq_write_reader(ray_parquet_t* r, const char* root, const char* ta /* All leaves are private staging output. Sync them together after * the workers finish, avoiding a directory fsync per column rename. */ ray_err_t e = n < 0 || (size_t)n >= sizeof(leaf) ? RAY_ERR_RANGE : - pq_save_partition(r,batch,leaf,sym,false); + pq_save_partition(r,batch,leaf,sym,false, + durable ? (ray_compress_t)r->compress : RAY_COMPRESS_OFF); ray_release(batch); if (e != RAY_OK) return ray_error(ray_err_code_str(e),"parquet: native partition write failed"); } @@ -1832,6 +1871,7 @@ ray_t* ray_parquet_parted_typed(const char* path, const char* root, const char* char staging[1100], sym[1200]; int64_t parts; ray_sym_domain_t* domain = NULL; err = pq_import_types(r,types); + if (!err && r->symcol) err = ray_error("domain","parquet: symfile 'column is supported by .parquet.splayed only"); if (!err) err = pq_stage(r,root,staging,sizeof(staging),true); if (err) goto done; /* Global runtime interning is not worker-safe. Decode symbols straight @@ -2165,7 +2205,9 @@ static void pq_write_direct_group(void* ptr, uint32_t worker, int64_t start, int ray_t* batch = ray_parquet_next(r); if (!batch) break; if (RAY_IS_ERR(batch)) { w->errors[task] = batch; break; } - ray_err_t err = ray_col_stream_append(&local,ray_table_get_col_idx(batch,0)); + ray_t* bcol = ray_table_col_idx(batch,0); + if (bcol && RAY_IS_ERR(bcol)) { w->errors[task] = bcol; ray_release(batch); break; } + ray_err_t err = ray_col_stream_append(&local,bcol); row += ray_table_nrows(batch); ray_release(batch); if (err != RAY_OK) { w->errors[task] = ray_error(ray_err_code_str(err),"parquet: direct column write failed"); break; } } @@ -2208,12 +2250,19 @@ static void pq_write_direct_group(void* ptr, uint32_t worker, int64_t start, int * entries to the symbol file every quarter second (and starts their * writeback), so the final flush writes only the tail and its sync finds * the rest on disk. */ -typedef struct { ray_sym_domain_t* dom; _Atomic(bool) stop; _Atomic(int) err; } pq_symflush_t; +typedef struct { + ray_sym_domain_t* dom; /* the first (the shared one, for the trace) */ + ray_sym_domain_t** doms; /* every symbol file's domain: one, or one a column (symfile 'column) */ + int64_t ndoms; + _Atomic(bool) stop; _Atomic(int) err; +} pq_symflush_t; static void pq_symflush_fn(void* arg) { pq_symflush_t* s = arg; while (!atomic_load_explicit(&s->stop,memory_order_acquire)) { - ray_err_t e = ray_sym_domain_flush_append(s->dom,false); - if (e != RAY_OK) { atomic_store_explicit(&s->err,(int)e,memory_order_release); return; } + for (int64_t i = 0; i < s->ndoms; i++) { + ray_err_t e = ray_sym_domain_flush_append(s->doms[i],false); + if (e != RAY_OK) { atomic_store_explicit(&s->err,(int)e,memory_order_release); return; } + } /* in slices, so the import's end does not wait out the interval */ for (int i = 0; i < 25 && !atomic_load_explicit(&s->stop,memory_order_acquire); i++) ray_sleep_ms(10); @@ -2896,13 +2945,25 @@ static void pq_sym_grouped(pq_direct_work* dw, ray_symgrp_t* g, ray_symimp_t* im * column by column (a pass is one column, or a few when the file has fewer * row groups than the pool has workers): one column file is written at a * time instead of all of them at once. Numeric and temporal columns go - * first and are closed as soon as their pass ends, their hash index built - * while the file is still in the page cache; symbol columns follow in + * first and are closed as soon as their pass ends; symbol columns follow in * passes of their own, smallest first, so the file domain only grows once * the other columns are done. With memory to spare one pass takes every - * column, and the columns close and are indexed together after it, as the + * column, and the columns close together after it, as the * row-group import does. Symbol columns close with the domain, after its * flush. */ +/* The entries of the import dictionaries of the symbol columns order[from, + * to), each dictionary counted once (one shared, or one a column under + * symfile 'column): the trace's seeding counts. */ +static int64_t pq_imp_count(ray_col_stream_t* writers, const int64_t* order, int64_t from, int64_t to) { + int64_t n = 0; + for (int64_t i = from; i < to; i++) { + ray_symimp_t* imp = ray_sym_domain_import(writers[order[i]].dom); + bool seen = false; + for (int64_t k = from; k < i && !seen; k++) seen = ray_sym_domain_import(writers[order[k]].dom) == imp; + if (imp && !seen) n += ray_symimp_count(imp); + } + return n; +} static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { int64_t chunks = r->ngroups*r->ncols; if (chunks > UINT32_MAX) return pq_error("too many column chunk tasks"); @@ -2923,7 +2984,10 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { ray_symgrp_t* sgrp = NULL; /* the grouped symbol import, or NULL */ ray_symimp_t* simp = NULL; ray_t* err = NULL; - pq_symflush_t symf = {NULL,false,(int)RAY_OK}; + pq_symflush_t symf = {NULL,NULL,0,false,(int)RAY_OK}; + ray_sym_domain_t** fdoms = NULL; /* symf.doms: the symbol columns' distinct domains */ + bool grouped = false; /* grouped symbol passes (sgrp, or one a column under symfile 'column) */ + ray_symgrp_order_t so = RAY_SYMGRP_ROWS; ray_thread_t sym_thread = 0; bool sym_running = false; if (!offsets || !nulls || !locks || !errors || !lo || !hi || !bytes || !vocab || !donly || !pick || !order) { err = ray_error("oom",NULL); goto done; } @@ -2954,7 +3018,7 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { /* The pass layout follows memory: physical RAM or the cgroup limit, * the page cache the output competes for (not the heap budget of -m). * Column by column pays off when the output does not fit it with room - * to spare: each column is written and indexed while it is hot, and + * to spare: each column is written while it is hot, and * only it is. With plenty of memory one pass over every column keeps * all the decode work overlapped with the symbol domain's commits and * wins. RAY_PQ_PASS_COLS forces columns per pass, symbol passes @@ -3087,23 +3151,27 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { } } if (mode == PQ_SYM_GROUPED && simp) { - ray_symgrp_order_t so = RAY_SYMGRP_ROWS; const char* e = getenv("RAY_PQ_SYM_ORDER"); if (e && !strcmp(e,"shards")) so = RAY_SYMGRP_SHARDS; else if (e && !strcmp(e,"freq")) so = RAY_SYMGRP_FREQ; else if (e && !strcmp(e,"rowsflat")) so = RAY_SYMGRP_ROWS_FLAT; - sgrp = ray_symgrp_new(simp,so); - if (!sgrp) { err = ray_error("oom",NULL); goto done; } + /* symfile 'column: every grouped column has a dictionary of its + * own, and its pass a grouped import over it (made by the pass) */ + if (!r->symcol) { + sgrp = ray_symgrp_new(simp,so); + if (!sgrp) { err = ray_error("oom",NULL); goto done; } + } + grouped = true; if (nd == r->ncols) nd = nnum; /* forced: every symbol column grouped */ } else nd = r->ncols; int64_t seeded = -1, seed0 = 0; /* the trace's: the dictionary's count after the seeding, and before */ if (seed) { int64_t ts = trace ? ray_profile_now_ns() : 0, entries = 0; int64_t bad_col; - seed0 = ray_symimp_count(simp); + seed0 = pq_imp_count(writers,order,nnum,r->ncols); const char* se = pq_seed_dicts(r,order,nnum,nd,&entries,&bad_col); if (se) { err = pq_col_error(r,se,bad_col); goto done; } - seeded = ray_symimp_count(simp); + seeded = pq_imp_count(writers,order,nnum,r->ncols); if (trace) fprintf(stderr,"parquet symseed: cols=%lld groups=%lld entries=%lld ms=%.1f\n",(long long)(nd-nnum), (long long)r->ngroups,(long long)entries,(double)(ray_profile_now_ns()-ts)/1e6); } @@ -3115,13 +3183,22 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { (int)ray_str_len(nm),ray_str_ptr(nm),(double)bytes[order[i]]/1048576.0,(long long)bytes[order[i]], (double)vocab[order[i]]/1048576.0,(long long)vocab[order[i]],(int)donly[order[i]],i < nd ? "direct" : "grouped"); } - if (!sgrp && nnum < r->ncols && writers[order[nnum]].dom) { + if (!grouped && nnum < r->ncols && writers[order[nnum]].dom) { symf.dom = writers[order[nnum]].dom; + fdoms = ray_alloc_raw((size_t)(r->ncols-nnum)*sizeof(*fdoms)); + if (!fdoms) { err = ray_error("oom",NULL); goto done; } + for (int64_t i = nnum; i < r->ncols; i++) { + ray_sym_domain_t* d = writers[order[i]].dom; + bool seen = false; + for (int64_t k = 0; k < symf.ndoms && !seen; k++) seen = fdoms[k] == d; + if (d && !seen) fdoms[symf.ndoms++] = d; + } + symf.doms = fdoms; if (ray_thread_create(&sym_thread,pq_symflush_fn,&symf) == RAY_OK) sym_running = true; } ray_symimp_stats_t ist; /* the import dictionary's counts, per pass */ if (trace && symf.dom) ray_sym_domain_import_stats(symf.dom,&ist); - bool all = !colwise && !sgrp; + bool all = !colwise && !grouped; for (int64_t p = 0; p < r->ncols && !err; p += work.npass) { int64_t wd = all ? r->ncols : p < nnum ? width : p < nd ? sym_width : 1; int64_t lim = all ? r->ncols : p < nnum ? nnum : p < nd ? nd : r->ncols; @@ -3129,7 +3206,16 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { work.npass = lim - p < wd ? lim - p : wd; int64_t tasks = r->ngroups*work.npass; int64_t t0 = trace ? ray_profile_now_ns() : 0, t1 = 0; - if (sgrp && p >= nd) { + ray_symgrp_t* pg = sgrp; /* the pass's grouped import */ + ray_symimp_t* pimp = simp; + if (grouped && p >= nd && r->symcol) { + /* symfile 'column: the column's own dictionary; one that has + * none (its file made without one) goes direct */ + pimp = ray_sym_domain_import(writers[work.pass[0]].dom); + pg = pimp ? ray_symgrp_new(pimp,so) : NULL; + if (pimp && !pg) { err = ray_error("oom",NULL); break; } + } + if (pg && p >= nd) { /* memory for the pass: what is left under the anon watermark */ int64_t wm = ray_heap_anon_watermark(); int64_t budget = wm > 0 ? wm - ray_heap_anon_committed() : (int64_t)1 << 30; @@ -3144,14 +3230,15 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { const char* e = getenv("RAY_PQ_SYM_GROUPS"); if (e && *e && strtol(e,NULL,10) > 0) groups = (int)strtol(e,NULL,10); else { - int64_t need = (ray_symgrp_entries(sgrp) + r->rows) * 24; + int64_t need = (ray_symgrp_entries(pg) + r->rows) * 24; while (groups < RAY_SYMGRP_MAX && need / groups > budget / 4) groups *= 2; } - pq_sym_grouped(&work,sgrp,simp,work.pass[0],groups,budget,workers,trace); + pq_sym_grouped(&work,pg,pimp,work.pass[0],groups,budget,workers,trace); } else if (tasks > 0) { if (ray_pool_par_dispatch_ok(pool,tasks,2)) ray_pool_dispatch_n(pool,pq_write_direct_group,&work,(uint32_t)tasks); else pq_write_direct_group(&work,0,0,tasks); } + if (pg && pg != sgrp) ray_symgrp_free(pg); /* a column's own (symfile 'column) */ /* errors[0] even with no tasks: a grouped pass over a file of no row * groups still runs its steps, and reports there */ for (int64_t t = 0; t < (tasks > 0 ? tasks : 1); t++) if (errors[t]) { @@ -3167,7 +3254,7 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { * leave out a PLAIN page): their positions are the workers' */ if (trace && seeded >= 0 && p < nd && p + work.npass >= nd) fprintf(stderr,"parquet symdirect: cols=%lld seeded=%lld seed_miss=%lld\n",(long long)(nd-nnum), - (long long)(seeded-seed0),(long long)(ray_symimp_count(simp)-seeded)); + (long long)(seeded-seed0),(long long)(pq_imp_count(writers,order,nnum,r->ncols)-seeded)); if (trace) t1 = ray_profile_now_ns(); for (int64_t i = 0; i < work.npass; i++) { int64_t c = work.pass[i]; @@ -3176,7 +3263,6 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { if (all || writers[c].type == RAY_SYM) continue; ray_err_t e = ray_col_stream_close(&writers[c],false); if (e != RAY_OK) { err = ray_error(ray_err_code_str(e),"parquet: column close failed"); break; } - ray_col_stream_hash_one(&writers[c]); } /* the workers' page and dictionary buffers grown past PQ_SPARE_MAX * for this pass's columns go with the pass */ @@ -3201,17 +3287,17 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { (double)ist.tab_bytes/1048576.0,(double)ist.off_bytes/1048576.0); } } - /* One pass: the columns finish side by side and their hash indexes are - * built in waves while the symbol file appender is still writing (its - * writeback can wait on the column data's); a symbol column's header - * takes the domain's final count, which no longer changes. The - * column-by-column passes have closed and indexed theirs already. */ + /* One pass: the columns finish side by side while the symbol file + * appender is still writing (its writeback can wait on the column + * data's); a symbol column's header takes the domain's final count, + * which no longer changes. The column-by-column passes have closed + * theirs already. No hash index is built: converters persist no + * auto-built hash (index policy), a column keeps its chunk zone. */ if (all && !err) { int64_t tc = trace ? ray_profile_now_ns() : 0; ray_err_t e = ray_col_stream_close_all(writers,r->ncols,false,NULL); if (e != RAY_OK) err = ray_error(ray_err_code_str(e),"parquet: column close failed"); - else ray_col_stream_hash_all(writers,r->ncols,NULL); - if (trace) fprintf(stderr,"parquet phase: close+hash=%.1fms\n",(double)(ray_profile_now_ns()-tc)/1e6); + if (trace) fprintf(stderr,"parquet phase: close=%.1fms\n",(double)(ray_profile_now_ns()-tc)/1e6); } if (sym_running) { atomic_store_explicit(&symf.stop,true,memory_order_release); @@ -3228,9 +3314,15 @@ static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { ray_free_raw(spare[i].page); ray_free_raw(spare[i].dict); ray_free_raw(spare[i].symbols); } ray_free_raw(spare); + ray_free_raw(fdoms); ray_symgrp_free(sgrp); return err; } +static void pq_release_doms(ray_sym_domain_t** doms, int64_t n) { + if (!doms) return; + for (int64_t c = 0; c < n; c++) if (doms[c]) ray_sym_domain_release(doms[c]); + ray_free_raw(doms); +} ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types) { #ifdef RAY_FUZZING return ray_error("restricted","Parquet imports disabled under fuzzing"); @@ -3243,27 +3335,46 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types char staging[1100], spool[1200], leaf[1500], file[1700]; ray_col_stream_t* writers = NULL; int64_t opened = 0, parts = 0; ray_err_t e = RAY_OK; ray_sym_domain_t* domain = NULL; + ray_sym_domain_t** cdoms = NULL; /* symfile 'column: column c's own domain, or NULL */ err = pq_import_types(r,types); if (err) goto done; err = pq_stage(r,dir,staging,sizeof(staging),false); if (err) goto done; writers = ray_calloc_raw((size_t)r->ncols*sizeof(*writers)); if (!writers) { err = ray_error("oom",NULL); goto done; } - for (int64_t c = 0; c < r->ncols; c++) if (r->schema[c].native_symbol && !domain) { - snprintf(file,sizeof(file),"%s/.sym",staging); - /* The direct import (no STR column) builds the symbol file with the - * import dictionary: strings go straight into the mapped file. */ - bool str_cols = false; - for (int64_t k = 0; k < r->ncols; k++) - if (!r->schema[k].native_symbol && r->schema[k].type == RAY_STR) str_cols = true; - if (!str_cols) domain = ray_sym_domain_create_import(file); - if (!domain) domain = ray_sym_domain_open_or_create(file); - if (!domain) { err = ray_error("oom",NULL); goto done; } - if (ray_sym_domain_intern(domain,"",0) != 0) { err = pq_error("cannot initialize native symbol domain"); goto done; } + if (r->symcol) { + cdoms = ray_calloc_raw((size_t)(r->ncols > 0 ? r->ncols : 1)*sizeof(*cdoms)); + if (!cdoms) { err = ray_error("oom",NULL); goto done; } + } + /* The direct import (no STR column) builds the symbol file with the + * import dictionary: strings go straight into the mapped file. */ + bool str_cols = false; + for (int64_t k = 0; k < r->ncols; k++) + if (!r->schema[k].native_symbol && r->schema[k].type == RAY_STR) str_cols = true; + for (int64_t c = 0; c < r->ncols; c++) if (r->schema[c].native_symbol && (cdoms || !domain)) { + /* shared: one symbol file, `.sym`; symfile 'column: each symbol + * column's own, `..sym` (ray_splay_col_sym_path) */ + ray_t* nm = ray_sym_str(r->schema[c].name); + if (!cdoms) snprintf(file,sizeof(file),"%s/.sym",staging); + else if (!nm || !ray_splay_col_sym_path(file,sizeof(file),staging,ray_str_ptr(nm),ray_str_len(nm))) { + err = pq_error("symbol file path is too long"); goto done; + } + ray_sym_domain_t* d = str_cols ? NULL : ray_sym_domain_create_import(file); + if (!d) d = ray_sym_domain_open_or_create(file); + if (!d) { err = ray_error("oom",NULL); goto done; } + if (cdoms) cdoms[c] = d; else domain = d; + if (ray_sym_domain_intern(d,"",0) != 0) { err = pq_error("cannot initialize native symbol domain"); goto done; } } for (int64_t c = 0; c < r->ncols; c++) { opened++; - e = ray_col_stream_open(&writers[c],staging,r->schema[c].name,r->schema[c].native_symbol ? RAY_SYM : (int8_t)r->schema[c].type,domain); + int8_t wt = r->schema[c].native_symbol ? RAY_SYM : (int8_t)r->schema[c].type; + /* the destination must not exist: nothing to inherit from */ + ray_t* nm = ray_sym_str(r->schema[c].name); + uint8_t gen = 0; + e = nm ? ray_col_resolve_gen_type_err((ray_compress_t)r->compress,wt,NULL, + ray_str_ptr(nm),ray_str_len(nm),&gen) : RAY_ERR_CORRUPT; + if (e == RAY_OK) e = ray_col_stream_open(&writers[c],staging,r->schema[c].name,wt, + cdoms && cdoms[c] ? cdoms[c] : domain,gen); if (e != RAY_OK) goto io_fail; } for (int64_t c = 0; c < r->ncols; c++) { @@ -3291,7 +3402,9 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types ray_t* batch = ray_read_splayed(leaf,NULL); if (!batch || RAY_IS_ERR(batch)) { err = batch ? batch : ray_error("oom",NULL); goto done; } for (int64_t c = 0; c < r->ncols; c++) { - e = ray_col_stream_append(&writers[c],ray_table_get_col_idx(batch,c)); + ray_t* bcol = ray_table_col_idx(batch,c); + if (bcol && RAY_IS_ERR(bcol)) { e = ray_err_from_obj(bcol); ray_error_free(bcol); break; } + e = ray_col_stream_append(&writers[c],bcol); if (e != RAY_OK) break; } ray_release(batch); @@ -3312,25 +3425,37 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types /* the direct import appended the symbols as they came: this writes * what is left and syncs the file */ if (domain) { e = ray_sym_domain_flush_append(domain,true); if (e != RAY_OK) goto io_fail; } + for (int64_t c = 0; cdoms && c < r->ncols; c++) + if (cdoms[c]) { e = ray_sym_domain_flush_append(cdoms[c],true); if (e != RAY_OK) goto io_fail; } if (trace) { fprintf(stderr,"parquet phase: sym flush=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } /* All columns are still under a private staging directory (the direct - * import has closed and indexed them already, but for the symbol - * columns of its column-by-column passes). Commit their final images - * together below, after the hash re-read of any column left. Every + * import has closed them already, but for the symbol columns of its + * column-by-column passes). Commit their final images together below. Every * column finishes as a pool task; the renames run serially after. */ e = ray_col_stream_close_all(writers,r->ncols,false,NULL); if (e != RAY_OK) goto io_fail; /* The persisted domain is flushed and every writer is closed (the zone * and dictionary indexes were built inline while streaming). Drop the - * ingestion hash tables and string arena before any hash re-read of the - * integer columns; reopening needs only the file-backed vocabulary. */ - if (domain) { - ray_sym_domain_release(domain); domain = NULL; + * ingestion hash tables and string arena before the schema is written; + * reopening needs only the file-backed vocabulary. */ + bool zsym = cdoms && r->compress == RAY_COMPRESS_ON; + if (domain || cdoms) { + if (domain) { ray_sym_domain_release(domain); domain = NULL; } + pq_release_doms(cdoms,r->ncols); cdoms = NULL; for (int64_t c = 0; c < opened; c++) writers[c].dom = NULL; } + /* symfile 'column under compress: each column's vocabulary, written + * whole, is coded (FSST) now that no domain holds it open */ + for (int64_t c = 0; zsym && c < r->ncols; c++) if (r->schema[c].native_symbol) { + ray_t* nm = ray_sym_str(r->schema[c].name); + if (!nm || !ray_splay_col_sym_path(file,sizeof(file),staging,ray_str_ptr(nm),ray_str_len(nm))) { + err = pq_error("symbol file path is too long"); goto done; + } + e = ray_sym_domain_compress(file); + if (e != RAY_OK) goto io_fail; + } + if (trace && zsym) { fprintf(stderr,"parquet phase: sym compress=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } if (trace) { fprintf(stderr,"parquet phase: close=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } - ray_col_stream_hash_all(writers,r->ncols,NULL); - if (trace) { fprintf(stderr,"parquet phase: hash=%.1fms\n",(double)(ray_profile_now_ns()-tp)/1e6); tp = ray_profile_now_ns(); } ray_t* schema = ray_vec_new(RAY_STR,r->ncols); if (!schema || RAY_IS_ERR(schema)) { err = schema ? schema : ray_error("oom",NULL); goto done; } for (int64_t c = 0; c < r->ncols; c++) { @@ -3361,7 +3486,8 @@ ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types err = ray_error(ray_err_code_str(e),"parquet: splayed write failed; staging directory retained"); done: for (int64_t c = 0; c < opened; c++) ray_col_stream_abort(&writers[c]); - ray_free_raw(writers); if (domain) ray_sym_domain_release(domain); ray_parquet_close(r); return err; + ray_free_raw(writers); if (domain) ray_sym_domain_release(domain); + pq_release_doms(cdoms,r ? r->ncols : 0); ray_parquet_close(r); return err; } ray_t* ray_parquet_splayed(const char* path, const char* dir) { @@ -3382,11 +3508,15 @@ ray_t* ray_parquet_read_fn(ray_t** args, int64_t n) { return p ? ray_parquet_read(p,n == 2 ? args[0] : NULL) : ray_error("type","parquet.read: path must be a nonempty string"); } ray_t* ray_parquet_splayed_fn(ray_t** args, int64_t n) { + if (n >= 2 && args[0] && args[0]->type == RAY_DICT && args[1] && args[1]->type == RAY_DICT) + return ray_error("domain","parquet: a second options dict"); if (n != 2 && n != 3) return ray_error("arity","parquet.splayed: [types] path directory"); const char* path = pq_path_arg(args[n-2]); const char* dir = pq_path_arg(args[n-1]); return path && dir ? ray_parquet_splayed_typed(path,dir,n == 3 ? args[0] : NULL) : ray_error("type","parquet.splayed: expected two paths"); } ray_t* ray_parquet_parted_fn(ray_t** args, int64_t n) { + if (n >= 2 && args[0] && args[0]->type == RAY_DICT && args[1] && args[1]->type == RAY_DICT) + return ray_error("domain","parquet: a second options dict"); if (n != 3 && n != 4) return ray_error("arity","parquet.parted: [types] path root table-name"); const char* p = pq_path_arg(args[n-3]); const char* root = pq_path_arg(args[n-2]); ray_t* name = args[n-1]->type == -RAY_SYM ? ray_sym_str(args[n-1]->i64) : args[n-1]; @@ -3437,7 +3567,7 @@ ray_t* ray_parquet_scan_fn(ray_t** args, int64_t n) { return ray_error("oom",NULL); } ray_retain(path); ((ray_t**)ray_data(vals))[0] = path; vals->len = 1; - if (n == 2) { ray_retain(args[0]); ((ray_t**)ray_data(vals))[1] = args[0]; vals->len = 2; } + if (n == 2) { ray_retain(args[0]); ((ray_t**)ray_data(vals))[1] = args[0]; vals->len = 2; } /* not-a-table */ return ray_dict_new(keys,vals); } static const char* pq_symbol_name(ray_t* x) { @@ -3583,12 +3713,17 @@ static bool pq_predicates(ray_parquet_t* r, ray_t* where, pq_predicate* predicat if (pos == r->noutput) return false; predicates[(*n)++] = (pq_predicate){pos,lo,hi}; return true; } -static void pq_filter_integers(ray_t* batch, const pq_predicate* predicates, int64_t n) { +/* Compacts the batch's columns in place, dropping rows that fail the integer + * predicates. Returns NULL or an owned error. */ +static ray_t* pq_filter_integers(ray_t* batch, const pq_predicate* predicates, int64_t n) { + ray_t* cols = ray_table_cols_inplace(batch); + if (!cols) return ray_error("type", "parquet: batch holds an encoded column"); + ray_t** cv = (ray_t**)ray_data(cols); int64_t rows = ray_table_nrows(batch), dst = 0, nc = ray_table_ncols(batch); for (int64_t i = 0; i < rows; i++) { bool keep = true; for (int64_t p = 0; p < n && keep; p++) { - ray_t* v = ray_table_get_col_idx(batch,predicates[p].pos); + ray_t* v = cv[predicates[p].pos]; int64_t x = v->type == RAY_I16 ? ((int16_t*)ray_data(v))[i] : v->type == RAY_I32 ? ((int32_t*)ray_data(v))[i] : ((int64_t*)ray_data(v))[i]; keep = ray_vec_is_null(v,i) ? predicates[p].lo == INT64_MIN : @@ -3596,22 +3731,27 @@ static void pq_filter_integers(ray_t* batch, const pq_predicate* predicates, int } if (!keep) continue; if (dst != i) for (int64_t c = 0; c < nc; c++) { - ray_t* v = ray_table_get_col_idx(batch,c); size_t size = ray_sym_elem_size(v->type,v->attrs); + ray_t* v = cv[c]; size_t size = ray_sym_elem_size(v->type,v->attrs); memcpy((uint8_t*)ray_data(v)+(size_t)dst*size,(uint8_t*)ray_data(v)+(size_t)i*size,size); } dst++; } - for (int64_t c = 0; c < nc; c++) ray_table_get_col_idx(batch,c)->len = dst; + for (int64_t c = 0; c < nc; c++) cv[c]->len = dst; + return NULL; } static ray_t* pq_accumulate(ray_parquet_t* r, pq_aggregate* aggs, int64_t n, const uint32_t* gids, const pq_predicate* predicates, int64_t np) { for (;;) { ray_t* batch = ray_parquet_next(r); if (!batch || RAY_IS_ERR(batch)) return batch; - if (np) pq_filter_integers(batch,predicates,np); + if (np) { + ray_t* fe = pq_filter_integers(batch,predicates,np); + if (fe) { ray_release(batch); return fe; } + } int64_t rows = ray_table_nrows(batch); for (int64_t a = 0; a < n; a++) { - ray_t* v = ray_table_get_col_idx(batch,aggs[a].pos); + ray_t* v = ray_table_col_idx(batch,aggs[a].pos); + if (v && RAY_IS_ERR(v)) { ray_release(batch); return v; } ray_valid_t valid = {ray_data(v),v->type,ray_vec_may_have_nulls(v)}; aggs[a].kernel->update_batch(aggs[a].state,aggs[a].kernel->state_size,gids,ray_data(v),&valid,rows,NULL); } diff --git a/src/lang/compile.c b/src/lang/compile.c index 3a54052d9..d58a494a1 100644 --- a/src/lang/compile.c +++ b/src/lang/compile.c @@ -148,7 +148,8 @@ static int32_t add_constant(compiler_t *c, ray_t *value) { if (v == value) return i; if (v->type == value->type && ray_is_atom(v)) { if (v->type == -RAY_I64 && v->i64 == value->i64) return i; - if (v->type == -RAY_F64 && v->f64 == value->f64) return i; + if (v->type == -RAY_F64 && + memcmp(&v->f64, &value->f64, sizeof v->f64) == 0) return i; if (v->type == -RAY_BOOL && v->b8 == value->b8) return i; if (v->type == -RAY_SYM && v->i64 == value->i64 && v->attrs == value->attrs) return i; @@ -283,310 +284,430 @@ static bool ast_refs_locals(compiler_t *c, ray_t *ast) { } if (ast->type == RAY_DICT) { /* slot[0]=keys, slot[1]=vals */ ray_t **slots = (ray_t**)ray_data(ast); - return ast_refs_locals(c, slots[0]) || ast_refs_locals(c, slots[1]); + return ast_refs_locals(c, slots[0]) || ast_refs_locals(c, slots[1]); /* not-a-table */ } return false; } -/* ── Compile a list (special form or function call) ── */ -static void compile_list(compiler_t *c, ray_t *ast) { - if (c->error) return; - EMIT_DBG(c, ast); - int64_t n = ray_len(ast); - if (n == 0) { c->error = true; return; } - ray_t **elems = (ray_t **)ray_data(ast); - ray_t *head = elems[0]; +/* Lower (if c1 r1 c2 r2 ... else?) — args are the forms after `if`, nargs + * >= 2. Each condition jumps past its result when false; the result + * jumps to the end of the chain. Recursing per pair keeps every end jump + * local to its own frame. No fallback: the chain yields 0, matching + * ray_cond_fn. */ +static void compile_if_chain(compiler_t *c, ray_t **args, int64_t nargs) { + if (nargs == 1) { compile_expr(c, args[0]); return; } + if (nargs == 0) { + ray_t *zero = ray_alloc(0); + zero->type = -RAY_I64; + zero->i64 = 0; + int32_t idx = add_constant(c, zero); + ray_release(zero); + emit_const(c, idx); + return; + } + compile_expr(c, args[0]); + /* Match ray_cond_fn: truthiness belongs to the materialized value, + * not to the non-NULL lazy handle that happens to contain it. */ + emit(c, OP_FORCE); + int32_t jmpf_pos = emit_jump(c, OP_JMPF); + compile_expr(c, args[1]); + int32_t jmp_pos = emit_jump(c, OP_JMP); + patch_jump(c, jmpf_pos); + compile_if_chain(c, args + 2, nargs - 2); + patch_jump(c, jmp_pos); +} - init_sf_syms(); +/* (set name value) — bind in the global env. Compile the value + * expression (so parameter/local slot references resolve in the + * current frame), then emit OP_STOREGLOBAL to bind the result by + * name. The value is left on the stack as the form's result. + * + * This previously emitted OP_CALLD on the whole form, which + * tree-walked the value against the global env and so could not + * see a compiled lambda's slot-bound parameters: `(fn [a] (set b a))` + * raised `name: 'a' undefined`. A non-symbol name aborts bytecode + * emission and falls back to the interpreter, which raises the + * proper `type` error via ray_set_fn. */ +static void compile_sf_set(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + ray_t *name_obj = elems[1]; + if (name_obj->type != -RAY_SYM) { c->error = true; return; } + compile_expr(c, elems[2]); + /* Match ray_set_fn: globals must never retain a single-use lazy + * DAG handle. Materializing one alias consumes its graph and + * would leave every other global read pointing at a spent handle. */ + emit(c, OP_FORCE); + int32_t idx = add_constant(c, name_obj); + if (idx < 256) { + emit(c, OP_STOREGLOBAL); + emit(c, (uint8_t)idx); + } else { + emit(c, OP_STOREGLOBAL_W); + emit(c, (uint8_t)(idx >> 8)); + emit(c, (uint8_t)(idx & 0xFF)); + } +} - /* A local (parameter, let or capture) named like a special form or a - * builtin is the callee, as it is on the tree walker, where the name - * resolves through the scope frames first. */ - bool head_local = head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && - find_local(c, head->i64) >= 0; +/* (let name value) — compile value, store in local slot. + * Reserved names (`.sys.*`, `.os.*`, `.csv.*`, `.ipc.*`) are + * refused here so a compiled lambda can't shadow a builtin + * through its local-slot table — the same guard + * ray_env_set_local enforces on the tree-walking path. + * Setting c->error aborts bytecode emission; call_lambda + * then falls back to the tree-walking interpreter which + * raises the proper `reserve` error via ray_let_fn. + * The five `.ipc.on.*` connection-hook names are exempt — + * they're user-settable, so a `let .ipc.on.open ...` in a + * compiled body must emit the same OP_STOREENV as any other + * local binding. Without this, the bytecode path would + * abort and silently fall back to the interpreter on every + * such write. */ +static void compile_sf_let(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + ray_t *name_obj = elems[1]; + if (name_obj->type != -RAY_SYM || + (ray_sym_is_reserved(name_obj->i64) && + !ray_sym_is_ipc_hook(name_obj->i64))) { + c->error = true; + return; + } + compile_expr(c, elems[2]); + /* Materialize a lazy value before binding — the interpreter's + * ray_let_fn does the same. A lazy handle is single-use + * (materialization consumes its deferred graph), so a local + * that aliased one would break on its SECOND read (e.g. + * `(let v (first xs)) (if (> v 0) v 0)`: the compare consumes + * the lazy, the branch then reloads a dead handle). */ + emit(c, OP_FORCE); + emit(c, OP_DUP); + int32_t slot = find_local(c, name_obj->i64); + if (slot < 0) slot = add_local(c, name_obj->i64); + if (slot < 0) { c->error = true; return; } + emit(c, OP_STOREENV); + emit(c, (uint8_t)slot); +} - /* Check for special forms by name (name ref = unflagged default) */ - if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local) { - int64_t sym_id = head->i64; +/* (do expr1 expr2 ...) */ +static void compile_sf_do(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + for (int64_t i = 1; i < n; i++) { + if (i > 1) emit(c, OP_POP); + compile_expr(c, elems[i]); + } +} - /* (set name value) — bind in the global env. Compile the value - * expression (so parameter/local slot references resolve in the - * current frame), then emit OP_STOREGLOBAL to bind the result by - * name. The value is left on the stack as the form's result. - * - * This previously emitted OP_CALLD on the whole form, which - * tree-walked the value against the global env and so could not - * see a compiled lambda's slot-bound parameters: `(fn [a] (set b a))` - * raised `name: 'a' undefined`. A non-symbol name aborts bytecode - * emission and falls back to the interpreter, which raises the - * proper `type` error via ray_set_fn. */ - if (sym_id == sf_set && n == 3) { - ray_t *name_obj = elems[1]; - if (name_obj->type != -RAY_SYM) { c->error = true; return; } - compile_expr(c, elems[2]); - /* Match ray_set_fn: globals must never retain a single-use lazy - * DAG handle. Materializing one alias consumes its graph and - * would leave every other global read pointing at a spent handle. */ - emit(c, OP_FORCE); - int32_t idx = add_constant(c, name_obj); - if (idx < 256) { - emit(c, OP_STOREGLOBAL); - emit(c, (uint8_t)idx); - } else { - emit(c, OP_STOREGLOBAL_W); - emit(c, (uint8_t)(idx >> 8)); - emit(c, (uint8_t)(idx & 0xFF)); - } - return; - } +/* (while cond body...) — the only backward branch the compiler + * emits. Body values are discarded (OP_POP each), and the form + * yields null however many times it iterated, matching + * ray_while_fn. No scope is pushed: `let` in the body writes this + * frame's local slot, so loop-carried state survives the pass + * exactly as it does on the tree-walking path. + * + * Compiling the body inline — rather than letting this fall through + * to the generic special-form path below — is what keeps `return` + * working inside a loop: it reaches the sf_return case and unwinds + * the lambda, instead of degrading to the tree walker's identity + * `return` (issue 588). */ +static void compile_sf_while(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + int32_t top = c->code_len; + compile_expr(c, elems[1]); + /* Truthiness belongs to the materialized value, not to the + * non-NULL lazy handle containing it — same rule as sf_if. */ + emit(c, OP_FORCE); + int32_t jmpf_pos = emit_jump(c, OP_JMPF); + for (int64_t i = 2; i < n; i++) { + compile_expr(c, elems[i]); + emit(c, OP_POP); + } + emit_jump_back(c, top); + patch_jump(c, jmpf_pos); + int32_t idx = add_constant(c, RAY_NULL_OBJ); + emit_const(c, idx); +} - /* (let name value) — compile value, store in local slot. - * Reserved names (`.sys.*`, `.os.*`, `.csv.*`, `.ipc.*`) are - * refused here so a compiled lambda can't shadow a builtin - * through its local-slot table — the same guard - * ray_env_set_local enforces on the tree-walking path. - * Setting c->error aborts bytecode emission; call_lambda - * then falls back to the tree-walking interpreter which - * raises the proper `reserve` error via ray_let_fn. - * The five `.ipc.on.*` connection-hook names are exempt — - * they're user-settable, so a `let .ipc.on.open ...` in a - * compiled body must emit the same OP_STOREENV as any other - * local binding. Without this, the bytecode path would - * abort and silently fall back to the interpreter on every - * such write. */ - if (sym_id == sf_let && n == 3) { - ray_t *name_obj = elems[1]; - if (name_obj->type != -RAY_SYM || - (ray_sym_is_reserved(name_obj->i64) && - !ray_sym_is_ipc_hook(name_obj->i64))) { - c->error = true; - return; - } - compile_expr(c, elems[2]); - /* Materialize a lazy value before binding — the interpreter's - * ray_let_fn does the same. A lazy handle is single-use - * (materialization consumes its deferred graph), so a local - * that aliased one would break on its SECOND read (e.g. - * `(let v (first xs)) (if (> v 0) v 0)`: the compare consumes - * the lazy, the branch then reloads a dead handle). */ - emit(c, OP_FORCE); - emit(c, OP_DUP); - int32_t slot = find_local(c, name_obj->i64); - if (slot < 0) slot = add_local(c, name_obj->i64); - if (slot < 0) { c->error = true; return; } - emit(c, OP_STOREENV); - emit(c, (uint8_t)slot); +/* (times n body...) — a counted loop, desugared onto the same + * backward branch `while` uses. + * + * The count is evaluated ONCE into a hidden local slot, so the + * bound is fixed on entry however the body mutates its source. + * ray_times_norm_fn type-checks it and clamps a negative bound to + * zero, which is what lets the per-pass test be a bare truthiness + * check on the counter: 0 is falsy (is_truthy), everything else is + * truthy, so the loop needs no comparison call and a negative bound + * cannot run away. + * + * Both helpers are pushed as constant-pool objects rather than + * resolved by name, so the loop's own arithmetic is invisible to + * user code and immune to an override of `-` or `>`. The counter's + * slot is likewise addressed by index, never by name, and its + * sym contains a space so no source token can collide with it — + * which is what keeps nested `times` counters apart. + * + * As with `while`, compiling the body inline is what keeps + * `return` unwinding the enclosing lambda from inside the loop. + * + * The indexed form, (times [i n] body...), keeps the normalized + * bound in a second hidden slot and stores bound - counter into + * i's slot at the top of each pass, so the index comes from the + * loop, never from i, and a body that rebinds i cannot steer it. */ +static void compile_sf_times(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + int64_t iname = -1; + ray_t *cexpr = elems[1]; + int32_t islot = -1, lslot = -1, idx_idx = -1; + if (ray_times_binding(elems[1], &iname, &cexpr)) { + if (ray_sym_is_reserved(iname) && !ray_sym_is_ipc_hook(iname)) { + c->error = true; return; } + ray_t *idx_fn = ray_fn_binary("times idx", RAY_FN_NONE, ray_times_idx_fn); + if (!idx_fn || RAY_IS_ERR(idx_fn)) { c->error = true; return; } + idx_idx = add_constant(c, idx_fn); + ray_release(idx_fn); + islot = find_local(c, iname); + if (islot < 0) islot = add_local(c, iname); + lslot = add_local(c, ray_sym_intern("times lim", 9)); + if (islot < 0 || lslot < 0 || c->error) { c->error = true; return; } + } + ray_t *norm_fn = ray_fn_unary("times norm", RAY_FN_NONE, ray_times_norm_fn); + ray_t *dec_fn = ray_fn_unary("times dec", RAY_FN_NONE, ray_times_dec_fn); + if (!norm_fn || RAY_IS_ERR(norm_fn) || !dec_fn || RAY_IS_ERR(dec_fn)) { + if (norm_fn && !RAY_IS_ERR(norm_fn)) ray_release(norm_fn); + if (dec_fn && !RAY_IS_ERR(dec_fn)) ray_release(dec_fn); + c->error = true; + return; + } + int32_t norm_idx = add_constant(c, norm_fn); + int32_t dec_idx = add_constant(c, dec_fn); + ray_release(norm_fn); + ray_release(dec_fn); + int32_t cslot = add_local(c, ray_sym_intern("times ctr", 9)); + if (cslot < 0 || c->error) { c->error = true; return; } + + /* counter = normalize(), and bound = counter if indexed */ + emit_const(c, norm_idx); + compile_expr(c, cexpr); + emit(c, OP_CALL1); + if (lslot >= 0) { + emit(c, OP_DUP); + emit(c, OP_STOREENV); + emit(c, (uint8_t)lslot); + } + emit(c, OP_STOREENV); + emit(c, (uint8_t)cslot); + + int32_t top = c->code_len; + emit(c, OP_LOADENV); + emit(c, (uint8_t)cslot); + int32_t jmpf_pos = emit_jump(c, OP_JMPF); + /* i = bound - counter */ + if (islot >= 0) { + emit_const(c, idx_idx); + emit(c, OP_LOADENV); + emit(c, (uint8_t)lslot); + emit(c, OP_LOADENV); + emit(c, (uint8_t)cslot); + emit(c, OP_CALL2); + emit(c, OP_STOREENV); + emit(c, (uint8_t)islot); + } + for (int64_t i = 2; i < n; i++) { + compile_expr(c, elems[i]); + emit(c, OP_POP); + } + /* counter = counter - 1 */ + emit_const(c, dec_idx); + emit(c, OP_LOADENV); + emit(c, (uint8_t)cslot); + emit(c, OP_CALL1); + emit(c, OP_STOREENV); + emit(c, (uint8_t)cslot); + emit_jump_back(c, top); + patch_jump(c, jmpf_pos); + int32_t null_idx = add_constant(c, RAY_NULL_OBJ); + emit_const(c, null_idx); +} - /* (if cond then else?) */ - if (sym_id == sf_if && n >= 3) { - compile_expr(c, elems[1]); - /* Match ray_cond_fn: truthiness belongs to the materialized value, - * not to the non-NULL lazy handle that happens to contain it. */ - emit(c, OP_FORCE); - int32_t jmpf_pos = emit_jump(c, OP_JMPF); - compile_expr(c, elems[2]); - if (n >= 4) { - int32_t jmp_pos = emit_jump(c, OP_JMP); - patch_jump(c, jmpf_pos); - compile_expr(c, elems[3]); - patch_jump(c, jmp_pos); - } else { - int32_t jmp_pos = emit_jump(c, OP_JMP); - patch_jump(c, jmpf_pos); - ray_t *zero = ray_alloc(0); - zero->type = -RAY_I64; - zero->i64 = 0; - int32_t idx = add_constant(c, zero); - ray_release(zero); - emit_const(c, idx); - patch_jump(c, jmp_pos); - } - return; - } +/* (fn [params] body...) — a closure template compiled once here + * and instantiated per evaluation (OP_MKCLOSURE); the dynamic + * eval below is the fallback when the literal cannot compile. */ +static void compile_sf_fn(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + if (compile_fn_template(c, ast)) return; + if (c->error) return; + /* The literal captures the window, which binds the locals it + * mentions and nothing a caller of this frame had in scope. */ + bool refs = ast_refs_locals(c, ast); + int32_t nsyms = refs ? c->n_locals : 0; + ray_t *syms = ray_alloc((size_t)(nsyms > 0 ? nsyms : 1) * sizeof(int64_t)); + if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } + syms->type = RAY_I64; + syms->len = nsyms; + int64_t *ids = (int64_t*)ray_data(syms); + for (int32_t i = 0; i < nsyms; i++) + ids[i] = c->locals[i].sym_id; + int32_t syms_idx = add_constant(c, syms); + ray_release(syms); + if (c->error) return; + emit_const(c, syms_idx); + emit(c, OP_SCOPE_EVAL); + int32_t idx = add_constant(c, ast); + emit_const(c, idx); + emit(c, OP_CALLD); + emit(c, 0); + emit_const(c, syms_idx); + emit(c, OP_SCOPE_END); +} - /* (do expr1 expr2 ...) */ - if (sym_id == sf_do && n >= 2) { - for (int64_t i = 1; i < n; i++) { - if (i > 1) emit(c, OP_POP); - compile_expr(c, elems[i]); - } - return; - } +/* (try body handler) — compile to OP_TRAP/OP_TRAP_END */ +static void compile_sf_try(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + /* Reserve a hidden local for err_val */ + int32_t err_slot = add_local(c, -1); + if (err_slot < 0) { c->error = true; return; } + + int32_t trap_pos = emit_jump(c, OP_TRAP); + c->trap_depth++; + compile_expr(c, elems[1]); /* body */ + c->trap_depth--; + emit(c, OP_TRAP_END); + int32_t jmp_pos = emit_jump(c, OP_JMP); + patch_jump(c, trap_pos); /* handler starts here */ + /* err_val is on stack (pushed by vm_error_cleanup). + * Stash it, compile handler fn, reload err_val, call. */ + emit(c, OP_STOREENV); + emit(c, (uint8_t)err_slot); + compile_expr(c, elems[2]); /* handler (fn or fallback value) */ + emit(c, OP_LOADENV); + emit(c, (uint8_t)err_slot); + emit(c, OP_TRYH); /* callable → call(err); else value */ + patch_jump(c, jmp_pos); /* end */ +} - /* (while cond body...) — the only backward branch the compiler - * emits. Body values are discarded (OP_POP each), and the form - * yields null however many times it iterated, matching - * ray_while_fn. No scope is pushed: `let` in the body writes this - * frame's local slot, so loop-carried state survives the pass - * exactly as it does on the tree-walking path. - * - * Compiling the body inline — rather than letting this fall through - * to the generic special-form path below — is what keeps `return` - * working inside a loop: it reaches the sf_return case and unwinds - * the lambda, instead of degrading to the tree walker's identity - * `return` (issue 588). */ - if (sym_id == sf_while && n >= 2) { - int32_t top = c->code_len; - compile_expr(c, elems[1]); - /* Truthiness belongs to the materialized value, not to the - * non-NULL lazy handle containing it — same rule as sf_if. */ - emit(c, OP_FORCE); - int32_t jmpf_pos = emit_jump(c, OP_JMPF); - for (int64_t i = 2; i < n; i++) { - compile_expr(c, elems[i]); - emit(c, OP_POP); - } - emit_jump_back(c, top); - patch_jump(c, jmpf_pos); - int32_t idx = add_constant(c, RAY_NULL_OBJ); - emit_const(c, idx); - return; - } +/* (return) | (return x) — early exit from enclosing compiled + * lambda. (return) pushes RAY_NULL_OBJ explicitly because + * OP_RET takes top-of-stack as the result; if (return) sits + * inside an outer expression that has already pushed values + * (e.g. (+ 1 (return))), relying on OP_RET's stack-empty + * fallback would return a stale value. */ +static void compile_sf_return(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n) { + if (n == 2) { + compile_expr(c, elems[1]); + } else { + int32_t idx = add_constant(c, RAY_NULL_OBJ); + emit_const(c, idx); + } + for (int32_t i = 0; i < c->trap_depth; i++) + emit(c, OP_TRAP_END); + emit(c, OP_RET); +} - /* (times n body...) — a counted loop, desugared onto the same - * backward branch `while` uses. - * - * The count is evaluated ONCE into a hidden local slot, so the - * bound is fixed on entry however the body mutates its source. - * ray_times_norm_fn type-checks it and clamps a negative bound to - * zero, which is what lets the per-pass test be a bare truthiness - * check on the counter: 0 is falsy (is_truthy), everything else is - * truthy, so the loop needs no comparison call and a negative bound - * cannot run away. - * - * Both helpers are pushed as constant-pool objects rather than - * resolved by name, so the loop's own arithmetic is invisible to - * user code and immune to an override of `-` or `>`. The counter's - * slot is likewise addressed by index, never by name, and its - * sym contains a space so no source token can collide with it — - * which is what keeps nested `times` counters apart. - * - * As with `while`, compiling the body inline is what keeps - * `return` unwinding the enclosing lambda from inside the loop. */ - if (sym_id == sf_times && n >= 2) { - ray_t *norm_fn = ray_fn_unary("times norm", RAY_FN_NONE, ray_times_norm_fn); - ray_t *dec_fn = ray_fn_unary("times dec", RAY_FN_NONE, ray_times_dec_fn); - if (!norm_fn || RAY_IS_ERR(norm_fn) || !dec_fn || RAY_IS_ERR(dec_fn)) { - if (norm_fn && !RAY_IS_ERR(norm_fn)) ray_release(norm_fn); - if (dec_fn && !RAY_IS_ERR(dec_fn)) ray_release(dec_fn); - c->error = true; - return; - } - int32_t norm_idx = add_constant(c, norm_fn); - int32_t dec_idx = add_constant(c, dec_fn); - ray_release(norm_fn); - ray_release(dec_fn); - int32_t cslot = add_local(c, ray_sym_intern("times ctr", 9)); - if (cslot < 0 || c->error) { c->error = true; return; } - - /* counter = normalize() */ - emit_const(c, norm_idx); - compile_expr(c, elems[1]); - emit(c, OP_CALL1); - emit(c, OP_STOREENV); - emit(c, (uint8_t)cslot); - - int32_t top = c->code_len; - emit(c, OP_LOADENV); - emit(c, (uint8_t)cslot); - int32_t jmpf_pos = emit_jump(c, OP_JMPF); - for (int64_t i = 2; i < n; i++) { - compile_expr(c, elems[i]); - emit(c, OP_POP); - } - /* counter = counter - 1 */ - emit_const(c, dec_idx); - emit(c, OP_LOADENV); - emit(c, (uint8_t)cslot); - emit(c, OP_CALL1); - emit(c, OP_STOREENV); - emit(c, (uint8_t)cslot); - emit_jump_back(c, top); - patch_jump(c, jmpf_pos); - int32_t null_idx = add_constant(c, RAY_NULL_OBJ); - emit_const(c, null_idx); - return; - } +/* Unrecognized special form: dynamic eval on the entire form. The + * special form re-evaluates its argument ASTs via the tree walker, + * which resolves names through scope frames + globals and cannot + * see this frame's local slots — so materialize the locals known + * at this point (plus self) into a scope frame around the eval, + * and sync any let-updates back into the slots afterwards. */ +static void compile_dyn_form(compiler_t *c, ray_t *ast) { + /* The window binds the locals the form mentions (none in the + * common globals-only case) and marks where the text's scope + * ends: a function the text calls, or a window of whoever called + * this frame, sees none of them (OP_SCOPE_EVAL). */ + bool refs = ast_refs_locals(c, ast); + int32_t nsyms = refs ? c->n_locals : 0; + ray_t *syms = ray_alloc((size_t)(nsyms > 0 ? nsyms : 1) * sizeof(int64_t)); + if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } + syms->type = RAY_I64; + syms->len = nsyms; + int64_t *ids = (int64_t*)ray_data(syms); + for (int32_t i = 0; i < nsyms; i++) + ids[i] = c->locals[i].sym_id; /* slot i <-> ids[i] */ + int32_t syms_idx = add_constant(c, syms); + ray_release(syms); + if (c->error) return; - /* (fn [params] body...) — a closure template compiled once here - * and instantiated per evaluation (OP_MKCLOSURE); the dynamic - * eval below is the fallback when the literal cannot compile. */ - if (sym_id == sf_fn && n >= 3) { - if (compile_fn_template(c, ast)) return; - if (c->error) return; - /* The literal captures the window, which binds the locals it - * mentions and nothing a caller of this frame had in scope. */ - bool refs = ast_refs_locals(c, ast); - int32_t nsyms = refs ? c->n_locals : 0; - ray_t *syms = ray_alloc((size_t)(nsyms > 0 ? nsyms : 1) * sizeof(int64_t)); - if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } - syms->type = RAY_I64; - syms->len = nsyms; - int64_t *ids = (int64_t*)ray_data(syms); - for (int32_t i = 0; i < nsyms; i++) - ids[i] = c->locals[i].sym_id; - int32_t syms_idx = add_constant(c, syms); - ray_release(syms); - if (c->error) return; - emit_const(c, syms_idx); - emit(c, OP_SCOPE_EVAL); - int32_t idx = add_constant(c, ast); - emit_const(c, idx); - emit(c, OP_CALLD); - emit(c, 0); - emit_const(c, syms_idx); - emit(c, OP_SCOPE_END); - return; - } + emit_const(c, syms_idx); + emit(c, OP_SCOPE_EVAL); + int32_t idx = add_constant(c, ast); + emit_const(c, idx); + emit(c, OP_CALLD); + emit(c, 0); + emit_const(c, syms_idx); + emit(c, OP_SCOPE_END); +} - /* (try body handler) — compile to OP_TRAP/OP_TRAP_END */ - if (sym_id == sf_try && n == 3) { - /* Reserve a hidden local for err_val */ - int32_t err_slot = add_local(c, -1); - if (err_slot < 0) { c->error = true; return; } - - int32_t trap_pos = emit_jump(c, OP_TRAP); - c->trap_depth++; - compile_expr(c, elems[1]); /* body */ - c->trap_depth--; - emit(c, OP_TRAP_END); - int32_t jmp_pos = emit_jump(c, OP_JMP); - patch_jump(c, trap_pos); /* handler starts here */ - /* err_val is on stack (pushed by vm_error_cleanup). - * Stash it, compile handler fn, reload err_val, call. */ - emit(c, OP_STOREENV); - emit(c, (uint8_t)err_slot); - compile_expr(c, elems[2]); /* handler (fn or fallback value) */ - emit(c, OP_LOADENV); - emit(c, (uint8_t)err_slot); - emit(c, OP_TRYH); /* callable → call(err); else value */ - patch_jump(c, jmp_pos); /* end */ - return; +/* compile_call's callee lookup: the value head names now, recorded in the + * dependency list when the code is cached against it. */ +static ray_t *call_head_fn(compiler_t *c, ray_t *head) { + ray_t *fn = c->dynamic_globals ? ray_env_get_global(head->i64) : ray_env_get_compiled(head->i64); + if (c->deps && !c->dynamic_globals) { + /* Only a builtin shapes the code (baked, a special form, the + * call opcode); any other value is called through OP_CALLF. */ + bool builtin = fn && (fn->type == RAY_UNARY || fn->type == RAY_BINARY || fn->type == RAY_VARY); + int64_t pair[2] = { head->i64, builtin ? (int64_t)(uintptr_t)fn : 0 }; + for (int k = 0; k < 2 && !c->error; k++) { + c->deps = ray_vec_append(c->deps, &pair[k]); + if (!c->deps || RAY_IS_ERR(c->deps)) { c->deps = NULL; c->error = true; } } + } + return fn; +} - /* (return) | (return x) — early exit from enclosing compiled - * lambda. (return) pushes RAY_NULL_OBJ explicitly because - * OP_RET takes top-of-stack as the result; if (return) sits - * inside an outer expression that has already pushed values - * (e.g. (+ 1 (return))), relying on OP_RET's stack-empty - * fallback would return a stale value. */ - if (sym_id == sf_return && (n == 1 || n == 2)) { - if (n == 2) { - compile_expr(c, elems[1]); - } else { - int32_t idx = add_constant(c, RAY_NULL_OBJ); - emit_const(c, idx); - } - for (int32_t i = 0; i < c->trap_depth; i++) - emit(c, OP_TRAP_END); - emit(c, OP_RET); - return; +/* The window an `eval` or `resolve` call runs in: every local of this + * frame. -1 with c->error set when it cannot be built. */ +static int32_t eval_window_syms(compiler_t *c) { + /* With no locals too: the window still marks where the text's + * scope ends, so a caller's window below it stays hidden. */ + ray_t *syms = ray_alloc((size_t)(c->n_locals > 0 ? c->n_locals : 1) * sizeof(int64_t)); + if (!syms || RAY_IS_ERR(syms)) { c->error = true; return -1; } + syms->type = RAY_I64; + syms->len = c->n_locals; + int64_t *ids = (int64_t*)ray_data(syms); + for (int32_t i = 0; i < c->n_locals; i++) ids[i] = c->locals[i].sym_id; + int32_t idx = add_constant(c, syms); + ray_release(syms); + return c->error ? -1 : idx; +} + +/* compile_call's call opcode, once the callee and the arguments are on + * the stack. */ +static void emit_call_op(compiler_t *c, ray_t *fn, bool baked, int64_t argc) { + bool emitted = false; + if (fn && !baked && c->dynamic_globals) { + /* A closure body resolved the callee above (OP_RESOLVE); while + * the name holds a builtin of the kind it holds now, the call + * takes the fast path, and the general call otherwise. */ + if (fn->type == RAY_UNARY && argc == 1) { emit(c, OP_CALL1R); emit(c, 1); emitted = true; } + else if (fn->type == RAY_BINARY && argc == 2) { emit(c, OP_CALL2R); emit(c, 2); emitted = true; } + else if (fn->type == RAY_VARY) { emit(c, OP_CALLNR); emit(c, (uint8_t)argc); emitted = true; } + } + if (!emitted && fn && (baked || fn->type == RAY_LAMBDA)) { + switch (fn->type) { + case RAY_UNARY: + if (argc == 1) { emit(c, OP_CALL1); emitted = true; } + break; + case RAY_BINARY: + if (argc == 2) { emit(c, OP_CALL2); emitted = true; } + break; + case RAY_VARY: + emit(c, OP_CALLN); + emit(c, (uint8_t)argc); + emitted = true; + break; + case RAY_LAMBDA: + emit(c, OP_CALLF); + emit(c, (uint8_t)argc); + emitted = true; + break; + default: + break; } } + if (!emitted) { + emit(c, OP_CALLF); + emit(c, (uint8_t)argc); + } +} +/* A function call: the arm of compile_list for everything that is not a + * special form it compiles inline. */ +static void compile_call(compiler_t *c, ray_t *ast, ray_t **elems, int64_t n, + ray_t *head, bool head_local) { /* Self-recursive call: emit OP_CALLS (lean frame reuse, no fn object) */ if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local && head->i64 == sf_self) { @@ -602,55 +723,13 @@ static void compile_list(compiler_t *c, ray_t *ast) { /* Look up head at compile time to determine call type */ ray_t *fn = NULL; if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local) { - fn = c->dynamic_globals ? ray_env_get_global(head->i64) : ray_env_get_compiled(head->i64); - if (c->deps && !c->dynamic_globals) { - /* Only a builtin shapes the code (baked, a special form, the - * call opcode); any other value is called through OP_CALLF. */ - bool builtin = fn && (fn->type == RAY_UNARY || fn->type == RAY_BINARY || fn->type == RAY_VARY); - int64_t pair[2] = { head->i64, builtin ? (int64_t)(uintptr_t)fn : 0 }; - for (int k = 0; k < 2 && !c->error; k++) { - c->deps = ray_vec_append(c->deps, &pair[k]); - if (!c->deps || RAY_IS_ERR(c->deps)) { c->deps = NULL; c->error = true; } - } - if (c->error) return; - } - } - - /* Unrecognized special form: dynamic eval on the entire form. The - * special form re-evaluates its argument ASTs via the tree walker, - * which resolves names through scope frames + globals and cannot - * see this frame's local slots — so materialize the locals known - * at this point (plus self) into a scope frame around the eval, - * and sync any let-updates back into the slots afterwards. */ - if (fn && (fn->attrs & RAY_FN_SPECIAL_FORM)) { - /* The window binds the locals the form mentions (none in the - * common globals-only case) and marks where the text's scope - * ends: a function the text calls, or a window of whoever called - * this frame, sees none of them (OP_SCOPE_EVAL). */ - bool refs = ast_refs_locals(c, ast); - int32_t nsyms = refs ? c->n_locals : 0; - ray_t *syms = ray_alloc((size_t)(nsyms > 0 ? nsyms : 1) * sizeof(int64_t)); - if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } - syms->type = RAY_I64; - syms->len = nsyms; - int64_t *ids = (int64_t*)ray_data(syms); - for (int32_t i = 0; i < nsyms; i++) - ids[i] = c->locals[i].sym_id; /* slot i <-> ids[i] */ - int32_t syms_idx = add_constant(c, syms); - ray_release(syms); + fn = call_head_fn(c, head); if (c->error) return; - - emit_const(c, syms_idx); - emit(c, OP_SCOPE_EVAL); - int32_t idx = add_constant(c, ast); - emit_const(c, idx); - emit(c, OP_CALLD); - emit(c, 0); - emit_const(c, syms_idx); - emit(c, OP_SCOPE_END); - return; } + /* An unrecognized special form: dynamic eval on the whole form. */ + if (fn && (fn->attrs & RAY_FN_SPECIAL_FORM)) { compile_dyn_form(c, ast); return; } + /* `eval` and `resolve` read names from text at run time: the tree * walker that serves them resolves through the scope frames, so the * call runs inside a window that binds this frame's locals, captures @@ -658,16 +737,7 @@ static void compile_list(compiler_t *c, ray_t *ast) { int32_t dyn_syms_idx = -1; if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local && (head->i64 == sf_eval || head->i64 == sf_resolve)) { - /* With no locals too: the window still marks where the text's - * scope ends, so a caller's window below it stays hidden. */ - ray_t *syms = ray_alloc((size_t)(c->n_locals > 0 ? c->n_locals : 1) * sizeof(int64_t)); - if (!syms || RAY_IS_ERR(syms)) { c->error = true; return; } - syms->type = RAY_I64; - syms->len = c->n_locals; - int64_t *ids = (int64_t*)ray_data(syms); - for (int32_t i = 0; i < c->n_locals; i++) ids[i] = c->locals[i].sym_id; - dyn_syms_idx = add_constant(c, syms); - ray_release(syms); + dyn_syms_idx = eval_window_syms(c); if (c->error) return; } @@ -699,47 +769,55 @@ static void compile_list(compiler_t *c, ray_t *ast) { emit(c, OP_SCOPE_EVAL); } - bool emitted = false; - if (fn && !baked && c->dynamic_globals) { - /* A closure body resolved the callee above (OP_RESOLVE); while - * the name holds a builtin of the kind it holds now, the call - * takes the fast path, and the general call otherwise. */ - if (fn->type == RAY_UNARY && argc == 1) { emit(c, OP_CALL1R); emit(c, 1); emitted = true; } - else if (fn->type == RAY_BINARY && argc == 2) { emit(c, OP_CALL2R); emit(c, 2); emitted = true; } - else if (fn->type == RAY_VARY) { emit(c, OP_CALLNR); emit(c, (uint8_t)argc); emitted = true; } - } - if (!emitted && fn && (baked || fn->type == RAY_LAMBDA)) { - switch (fn->type) { - case RAY_UNARY: - if (argc == 1) { emit(c, OP_CALL1); emitted = true; } - break; - case RAY_BINARY: - if (argc == 2) { emit(c, OP_CALL2); emitted = true; } - break; - case RAY_VARY: - emit(c, OP_CALLN); - emit(c, (uint8_t)argc); - emitted = true; - break; - case RAY_LAMBDA: - emit(c, OP_CALLF); - emit(c, (uint8_t)argc); - emitted = true; - break; - default: - break; - } - } - if (!emitted) { - emit(c, OP_CALLF); - emit(c, (uint8_t)argc); - } + emit_call_op(c, fn, baked, argc); if (dyn_syms_idx >= 0) { emit_const(c, dyn_syms_idx); emit(c, OP_SCOPE_END); } } +/* ── Compile a list (special form or function call) ── */ +/* compile_list dispatches each special form to a function of its own + * rather than compiling them all in one body. The arms recurse into + * compile_expr, and an unoptimized build gives a function one frame for + * every local of every arm: a single compile_list took 4.7 KB per level + * under ASan, so an if chain nested within the 2048-level depth guard + * overflowed an 8 MB stack. Split, each nesting level carries only the + * frame of the arm it passes through. */ +static void compile_list(compiler_t *c, ray_t *ast) { + if (c->error) return; + EMIT_DBG(c, ast); + int64_t n = ray_len(ast); + if (n == 0) { c->error = true; return; } + ray_t **elems = (ray_t **)ray_data(ast); + ray_t *head = elems[0]; + + init_sf_syms(); + + /* A local (parameter, let or capture) named like a special form or a + * builtin is the callee, as it is on the tree walker, where the name + * resolves through the scope frames first. */ + bool head_local = head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && + find_local(c, head->i64) >= 0; + + /* Check for special forms by name (name ref = unflagged default) */ + if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && !head_local) { + int64_t sym_id = head->i64; + + if (sym_id == sf_set && n == 3) { compile_sf_set(c, ast, elems, n); return; } + if (sym_id == sf_let && n == 3) { compile_sf_let(c, ast, elems, n); return; } + if (sym_id == sf_if && n >= 3) { compile_if_chain(c, elems + 1, n - 1); return; } + if (sym_id == sf_do && n >= 2) { compile_sf_do(c, ast, elems, n); return; } + if (sym_id == sf_while && n >= 2) { compile_sf_while(c, ast, elems, n); return; } + if (sym_id == sf_times && n >= 2) { compile_sf_times(c, ast, elems, n); return; } + if (sym_id == sf_fn && n >= 3) { compile_sf_fn(c, ast, elems, n); return; } + if (sym_id == sf_try && n == 3) { compile_sf_try(c, ast, elems, n); return; } + if (sym_id == sf_return && (n == 1 || n == 2)) { compile_sf_return(c, ast, elems, n); return; } + } + + compile_call(c, ast, elems, n, head, head_local); +} + /* ── Compile expression ── */ static void compile_expr_at(compiler_t *c, ray_t *ast); static void compile_expr(compiler_t *c, ray_t *ast) { @@ -940,7 +1018,7 @@ static bool ast_collect_syms_at(ray_t *ast, ray_t **out, bool *dynamic, int dept if (ast->type == RAY_DICT) { ray_t **slots = (ray_t**)ray_data(ast); return ast_collect_syms_at(slots[0], out, dynamic, depth + 1, weight, stop, nodes) && - ast_collect_syms_at(slots[1], out, dynamic, depth + 1, weight, stop, nodes); + ast_collect_syms_at(slots[1], out, dynamic, depth + 1, weight, stop, nodes); /* not-a-table */ } return true; } diff --git a/src/lang/env.c b/src/lang/env.c index 96917a3ed..5e4f23534 100644 --- a/src/lang/env.c +++ b/src/lang/env.c @@ -89,6 +89,10 @@ static inline void env_unlock(void) { } #define ENV_CAP 1024 +#define ENV_WRITE_INDEX_BITS 11 +#define ENV_WRITE_INDEX_CAP (1u << ENV_WRITE_INDEX_BITS) +_Static_assert(ENV_CAP < UINT16_MAX, "write index stores slot plus one"); +_Static_assert(ENV_WRITE_INDEX_CAP >= 2 * ENV_CAP, "write index needs empty buckets"); static struct { int64_t keys[ENV_CAP]; @@ -102,8 +106,33 @@ static struct { * preserved across snapshot/restore. */ uint8_t user[ENV_CAP]; int32_t count; + /* Writers hold env_lock. Zero is an empty bucket, otherwise slot + 1. + * Readers retain their existing validated hints and value-cache epochs. */ + uint16_t write_index[ENV_WRITE_INDEX_CAP]; } g_env; +/* Every name ever given a slot in g_env, as a one-hash Bloom filter. + * A dotted read (`d.k`) first looks the whole name up flat, and only the + * reserved builtins (`.sys.gc`, `.os.getenv`, ...) have dotted slots, so + * that lookup nearly always misses, and a miss scans every slot. A clear + * bit answers it at once. Bits are set under env_lock before the slot is + * published and only cleared by ray_env_init: a clear bit proves the name + * has no slot, and a collision only costs the scan. Plain names keep the + * scan, which their hint makes rare. */ +#define ENV_SLOT_FILTER_BITS 15 +static _Atomic uint64_t g_env_slot_filter[(1 << ENV_SLOT_FILTER_BITS) / 64]; +static inline uint32_t env_slot_filter_bit(int64_t sym_id) { + return (uint32_t)(((uint64_t)sym_id * UINT64_C(0x9E3779B97F4A7C15)) >> (64 - ENV_SLOT_FILTER_BITS)); +} +static inline void env_slot_filter_add(int64_t sym_id) { + uint32_t b = env_slot_filter_bit(sym_id); + atomic_fetch_or_explicit(&g_env_slot_filter[b / 64], UINT64_C(1) << (b % 64), memory_order_release); +} +static inline bool env_slot_filter_may_have(int64_t sym_id) { + uint32_t b = env_slot_filter_bit(sym_id); + return (atomic_load_explicit(&g_env_slot_filter[b / 64], memory_order_acquire) >> (b % 64)) & 1; +} + /* What a name compiled code resolves stays the same while neither moves: * the frame epoch (this thread's scope frames: a push, a pop, a binding, * a frame's kind or flags) and the global epoch (any global written). @@ -387,6 +416,8 @@ int64_t ray_sym_ipc_hook(int idx) { ray_err_t ray_env_init(void) { env_globals_moved(); memset(&g_env, 0, sizeof(g_env)); + for (size_t i = 0; i < sizeof(g_env_slot_filter) / sizeof(g_env_slot_filter[0]); i++) + atomic_store_explicit(&g_env_slot_filter[i], 0, memory_order_relaxed); __VM->scope_depth = 0; /* The IPC hook sym IDs are interned lazily on first probe via * `ipc_hook_syms_ensure`. We deliberately do NOT pre-intern here: @@ -458,6 +489,7 @@ static ray_t* env_global_lookup(int64_t sym_id) { int32_t i = hint[h].idx; int32_t n = g_env.count; if (hint[h].sym == sym_id && i < n && g_env.keys[i] == sym_id) return g_env.vals[i]; + if (ray_sym_is_dotted(sym_id) && !env_slot_filter_may_have(sym_id)) return NULL; for (i = 0; i < n; i++) { if (g_env.keys[i] != sym_id) continue; hint[h].sym = sym_id; @@ -517,6 +549,9 @@ ray_t* ray_env_get_local(int64_t sym_id) { return NULL; } +/* Borrowed lookup. A NULL for a dotted path into a table may also mean the + * column failed to load (the detail is in ray_error_msg()); ray_env_resolve + * returns that failure as an error instead. */ static ray_t* env_get_impl(int64_t sym_id, bool in_callee); ray_t* ray_env_get(int64_t sym_id) { return env_get_impl(sym_id, false); @@ -552,6 +587,12 @@ static ray_t* env_get_impl(int64_t sym_id, bool in_callee) { ray_t* v = env_lookup_flat_impl(segs[0], NULL, in_callee); for (int i = 1; v && i < n; i++) { v = ray_container_probe_sym(v, segs[i]); + if (v && RAY_IS_ERR(v)) { + /* A borrowed-ref API has no channel for the owned error: report + * "undefined"; ray_env_resolve (the evaluator's path) surfaces it. */ + ray_error_free(v); + return NULL; + } } return v; } @@ -658,7 +699,13 @@ static ray_t* env_resolve_impl(int64_t sym_id, uint8_t* rows, bool in_callee) { } next_fresh = (next != NULL); } - if (!next) next = ray_container_probe_sym(v, segs[i]); + if (!next) { + next = ray_container_probe_sym(v, segs[i]); + if (next && RAY_IS_ERR(next)) { /* a column that failed to load */ + if (fresh) ray_release(v); + return next; + } + } if (next) { if (fresh) ray_release(v); v = next; @@ -725,34 +772,57 @@ static ray_t* env_resolve_impl(int64_t sym_id, uint8_t* rows, bool in_callee) { * ray_del_fn's contract via ray_env_set(sym, NULL) and also covers the * cascade-up case in env_set_dotted where every dict in a dotted path was * emptied by the delete. */ +/* Index only write lookup. Keep lock acquisition, global value epochs, slot + * order, user flags, and the read path unchanged. At most half the buckets + * can be occupied because the binding table is still capped at ENV_CAP. */ +static uint32_t env_write_bucket(int64_t sym_id) { + uint32_t bucket = (uint32_t)(((uint64_t)sym_id * UINT64_C(0x9E3779B97F4A7C15)) + >> (64 - ENV_WRITE_INDEX_BITS)); + while (g_env.write_index[bucket]) { + int32_t slot = (int32_t)g_env.write_index[bucket] - 1; + if (g_env.keys[slot] == sym_id) break; + bucket = (bucket + 1) & (ENV_WRITE_INDEX_CAP - 1); + } + return bucket; +} + +/* Delete already compacts the ordered slot arrays. Rebuild the small index + * under the same lock so no shifted slot or probe-chain hole can survive. */ +static void env_write_index_rebuild(void) { + memset(g_env.write_index, 0, sizeof(g_env.write_index)); + for (int32_t i = 0; i < g_env.count; i++) + g_env.write_index[env_write_bucket(g_env.keys[i])] = (uint16_t)(i + 1); +} + static ray_err_t env_bind_global_impl(int64_t sym_id, ray_t* val, int is_user) { env_globals_moved(); env_lock(); - for (int32_t i = 0; i < g_env.count; i++) { - if (g_env.keys[i] == sym_id) { - if (val == NULL) { - if (g_env.vals[i]) ray_release(g_env.vals[i]); - for (int32_t j = i; j + 1 < g_env.count; j++) { - g_env.keys[j] = g_env.keys[j + 1]; - g_env.vals[j] = g_env.vals[j + 1]; - g_env.user[j] = g_env.user[j + 1]; - } - g_env.count--; - env_unlock(); - return RAY_OK; - } + uint32_t bucket = env_write_bucket(sym_id); + int32_t i = (int32_t)g_env.write_index[bucket] - 1; + if (i >= 0) { + if (val == NULL) { if (g_env.vals[i]) ray_release(g_env.vals[i]); - ray_retain(val); - g_env.vals[i] = val; - /* User write upgrades a builtin slot to user-defined, so a - * (set + 42) override survives snapshot/restore. A builtin - * re-bind (e.g. theoretical hot reload) leaves the existing - * flag alone — once user, always user, until the slot is - * deleted. */ - if (is_user) g_env.user[i] = 1; + for (int32_t j = i; j + 1 < g_env.count; j++) { + g_env.keys[j] = g_env.keys[j + 1]; + g_env.vals[j] = g_env.vals[j + 1]; + g_env.user[j] = g_env.user[j + 1]; + } + g_env.count--; + env_write_index_rebuild(); env_unlock(); return RAY_OK; } + if (g_env.vals[i]) ray_release(g_env.vals[i]); + ray_retain(val); + g_env.vals[i] = val; + /* User write upgrades a builtin slot to user-defined, so a + * (set + 42) override survives snapshot/restore. A builtin + * re-bind (e.g. theoretical hot reload) leaves the existing + * flag alone — once user, always user, until the slot is + * deleted. */ + if (is_user) g_env.user[i] = 1; + env_unlock(); + return RAY_OK; } if (val == NULL) { /* deleting an absent binding: no-op */ env_unlock(); @@ -762,10 +832,12 @@ static ray_err_t env_bind_global_impl(int64_t sym_id, ray_t* val, int is_user) { env_unlock(); return RAY_ERR_OOM; } + env_slot_filter_add(sym_id); g_env.keys[g_env.count] = sym_id; ray_retain(val); g_env.vals[g_env.count] = val; g_env.user[g_env.count] = is_user ? 1 : 0; + g_env.write_index[bucket] = (uint16_t)(g_env.count + 1); g_env.count++; env_unlock(); return RAY_OK; @@ -996,6 +1068,33 @@ ray_t* ray_env_get_global(int64_t sym_id) { return env_global_lookup(sym_id); } +/* True when `leaf` (what ray_env_get returned for the dotted `sym_id`) is + * reached through a chain of dicts that nothing else references: the global + * head and every dict below it held once, each dict's vals list held once. + * A write into the leaf is then seen through this name only, so it needs no + * copy and no rebuild of the chain. The leaf's own count is the caller's to + * check. A flat binding of the dotted name, a local shadowing the head, a + * table on the way or any shared level says no. */ +bool ray_env_dotted_sole(int64_t sym_id, ray_t* leaf) { + const int64_t* segs; + int n = ray_sym_segs(sym_id, &segs); + if (n < 2 || !leaf) return false; + if (env_lookup_flat_impl(sym_id, NULL, false)) return false; + + ray_t* v = env_global_lookup(segs[0]); + for (int i = 1; i < n; i++) { + if (!v || v->type != RAY_DICT || v->rc != 1 || v->mmod != 0 || + (v->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA))) + return false; + ray_t* vals = ray_dict_slots(v)[1]; + if (!vals || vals->type != RAY_LIST || vals->rc != 1 || vals->mmod != 0 || + (vals->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA))) + return false; + v = ray_dict_probe_sym_borrowed(v, segs[i]); + } + return v == leaf; +} + static ray_t* lookup_top_frame(int64_t sym_id) { if (__VM->scope_depth <= 0) return NULL; ray_scope_frame_t* f = &__VM->scope_stack[__VM->scope_depth - 1]; diff --git a/src/lang/env.h b/src/lang/env.h index 70e7e92e0..f97016bb8 100644 --- a/src/lang/env.h +++ b/src/lang/env.h @@ -46,6 +46,8 @@ ray_t* ray_env_get(int64_t sym_id); /* Borrowed flat global binding, ignoring local/query frames. */ ray_t* ray_env_get_global(int64_t sym_id); ray_t* ray_env_get_local(int64_t sym_id); +/* A dotted name's leaf sits under a global chain of dicts held only once. */ +bool ray_env_dotted_sole(int64_t sym_id, ray_t* leaf); /* User-facing binder. Refuses any name starting with `.` — that root is * reserved for system namespaces (.sys, .os, .io, .ipc, …) populated by diff --git a/src/lang/eval.c b/src/lang/eval.c index 3a939c5b1..64283aaf1 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -129,6 +129,7 @@ bool ray_interrupted(void) { return g_eval_interrupted != 0; } void ray_eval_request_interrupt(void) { ray_request_interrupt(); } void ray_eval_clear_interrupt(void) { ray_clear_interrupt(); } int ray_eval_is_interrupted(void) { return ray_interrupted(); } +int ray_eval_depth(void) { return __VM ? (int)__VM->eval_depth : 0; } ray_t* ray_eval_get_nfo(void) { return __VM ? __VM->nfo : NULL; } void ray_eval_set_nfo(ray_t* nfo) { if (__VM) __VM->nfo = nfo; } @@ -138,6 +139,56 @@ void ray_clear_error_trace(void) { if (__VM && __VM->trace) { ray_release(__VM->trace); __VM->trace = NULL; } } +/* A (raise x) value is consumed by `try`. An uncaught one stays in + * __VM->raise_val until the next raise; clearing it at every top-level + * boundary keeps a value from one evaluation from being reported against + * an error in a later one. */ +void ray_raise_clear(void) { + if (__VM && __VM->raise_val) { ray_release(__VM->raise_val); __VM->raise_val = NULL; } +} + +/* Render the pending uncaught raise value into buf (cap > 0, always + * NUL-terminated) for an error printer. Returns false when nothing is + * pending. Only error printers call this, so `raise` itself stays O(1), + * and the cost here is bounded: a string is copied up to cap, a table is + * summarised as "
" (as println does), and anything else is + * formatted in the REPL's display-limited mode. Text cut at cap ends in + * "..". */ +bool ray_raise_render(char* buf, size_t cap) { + if (!buf || cap == 0) return false; + buf[0] = '\0'; + ray_t* val = __VM ? __VM->raise_val : NULL; + if (!val) return false; + if (val->type == RAY_TABLE) { + snprintf(buf, cap, "
", + ray_table_nrows(val), ray_table_ncols(val)); + return true; + } + ray_t* text = NULL; + const char* p; + size_t n; + if (val->type == -RAY_STR) { + p = ray_str_ptr(val); + n = ray_str_len(val); + } else { + text = ray_fmt(val, 1); + if (!text || RAY_IS_ERR(text)) { if (text) ray_error_free(text); return false; } + p = ray_str_ptr(text); + n = ray_str_len(text); + } + if (n >= cap) { + /* Keep what fits, leaving room for ".." and the NUL. */ + n = cap > 3 ? cap - 3 : cap - 1; + memcpy(buf, p, n); + if (cap > 3) { buf[n++] = '.'; buf[n++] = '.'; } + } else { + memcpy(buf, p, n); + } + buf[n] = '\0'; + if (text) ray_release(text); + return true; +} + /* ══════════════════════════════════════════ * Restricted-mode check * ══════════════════════════════════════════ */ @@ -155,6 +206,42 @@ static inline ray_binary_fn unary_binary_overload(ray_unary_fn fn) { return NULL; } +/* A LIST whose elements are all atoms of one numeric or temporal type, as + * a vector of that type (the list is released); any other list as it is. */ +static ray_t* list_collapse_uniform(ray_t* list) { + if (!list || RAY_IS_ERR(list) || list->type != RAY_LIST || ray_len(list) == 0) + return list; + ray_t** e = (ray_t**)ray_data(list); + int8_t t = e[0] ? e[0]->type : 0; + switch (t) { + case -RAY_BOOL: case -RAY_U8: case -RAY_I16: case -RAY_I32: case -RAY_I64: + case -RAY_TIMESPAN: case -RAY_F32: case -RAY_F64: case -RAY_DATE: case -RAY_TIME: case -RAY_TIMESTAMP: + break; + default: + return list; + } + int64_t n = ray_len(list); + for (int64_t i = 1; i < n; i++) + if (!e[i] || e[i]->type != t) return list; + ray_t* vec = ray_vec_new((int8_t)-t, n); + if (!vec || RAY_IS_ERR(vec)) return list; + vec->len = n; + for (int64_t i = 0; i < n; i++) store_typed_elem(vec, i, e[i]); + ray_release(list); + return vec; +} + +/* (min a b) / (max a b) over collections. Two collections must have the + * same length, an error named for the call; and over a LIST the results, + * when they share one type, make a vector of it. */ +static ray_t* minmax_map(ray_binary_fn f2, ray_t* a, ray_t* b) { + if (is_collection(a) && is_collection(b) && ray_len(a) != ray_len(b)) + return ray_error("length", "%s: operand lengths must match, got %lld and %lld", + f2 == ray_min2_fn ? "min" : "max", + (long long)ray_len(a), (long long)ray_len(b)); + return list_collapse_uniform(atomic_map_binary(f2, a, b)); +} + static ray_t* materialize_owned_args(ray_t** args, int64_t n) { for (int64_t i = 0; i < n; i++) { if (!args[i] || !ray_is_lazy(args[i])) continue; @@ -176,6 +263,7 @@ static ray_t* materialize_owned_args(ray_t** args, int64_t n) { static int64_t numeric_atom_i64(ray_t* x) { switch (x->type) { case -RAY_I64: + case -RAY_TIMESPAN: case -RAY_TIMESTAMP: case -RAY_SYM: return x->i64; @@ -469,6 +557,7 @@ static ray_t* zero_atom_for_elem_type(ray_t* coll) { case RAY_F64: return make_f64(0.0); case RAY_DATE: return ray_date(0); case RAY_TIME: return ray_time(0); + case RAY_TIMESPAN: return ray_timespan(0); case RAY_TIMESTAMP: return ray_timestamp(0); case RAY_SYM: return ray_sym(0); case RAY_STR: return ray_str("", 0); @@ -754,6 +843,17 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, (right && !RAY_IS_ERR(right) && RAY_IS_PARTED(right->type))) return atomic_map_binary_parted(fn, dag_opcode, left, right); + bool duration_binary = fn == ray_add_fn || fn == ray_sub_fn || fn == ray_mul_fn || + fn == ray_div_fn || fn == ray_idiv_fn || fn == ray_mod_fn || fn == ray_xbar_fn || + fn == ray_eq_fn || fn == ray_neq_fn || fn == ray_lt_fn || fn == ray_lte_fn || + fn == ray_gt_fn || fn == ray_gte_fn; + if (duration_binary && left->type != RAY_LIST && right->type != RAY_LIST && + (ray_has_timespan(left) || ray_has_timespan(right) || + (fn == ray_sub_fn && + (left->type == RAY_TIMESTAMP || left->type == -RAY_TIMESTAMP) && + (right->type == RAY_TIMESTAMP || right->type == -RAY_TIMESTAMP)))) + return fn(left, right); + int left_coll = is_collection(left); int right_coll = is_collection(right); @@ -768,7 +868,7 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, * does NOT broadcast (only a true atom does — see the * !left_coll/!right_coll branch). */ if (ray_len(left) != ray_len(right)) { - const char* opn = ray_opcode_name(dag_opcode); + const char* opn = dag_opcode ? ray_opcode_name(dag_opcode) : NULL; return ray_error("length", "%s: operand lengths must match, got %lld and %lld", opn ? opn : "binary op", (long long)ray_len(left), (long long)ray_len(right)); @@ -789,14 +889,23 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, ray_t* ra = right_coll ? zero_atom_for_elem_type(right) : right; ray_t* probe = (la && ra && !RAY_IS_ERR(la) && !RAY_IS_ERR(ra)) ? fn(la, ra) : NULL; - if (left_coll && la) ray_release(la); - if (right_coll && ra) ray_release(ra); + /* The probe and the fabricated operands are ours. A failed + * probe — `(/ empty_DATE 2)`: ray_div_fn rejects the fabricated + * DATE — or a failed fabrication is freed and its message + * cleared; the empty result keeps its I64 fallback type. A + * caller's own operand (not fabricated) is not touched. */ + bool failed = (probe && RAY_IS_ERR(probe)) || + (left_coll && la && RAY_IS_ERR(la)) || + (right_coll && ra && RAY_IS_ERR(ra)); + if (left_coll && la) { if (RAY_IS_ERR(la)) ray_error_free(la); else ray_release(la); } + if (right_coll && ra) { if (RAY_IS_ERR(ra)) ray_error_free(ra); else ray_release(ra); } if (probe && !RAY_IS_ERR(probe) && probe->type < 0) { int8_t t = (int8_t)(-probe->type); ray_release(probe); return ray_vec_new(t, 0); } - if (probe && !RAY_IS_ERR(probe)) ray_release(probe); + if (probe) { if (RAY_IS_ERR(probe)) ray_error_free(probe); else ray_release(probe); } + if (failed) ray_error_clear(); return ray_vec_new(RAY_I64, 0); } @@ -835,7 +944,11 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, /* When LEFT is scalar broadcast to RIGHT vector, the output type follows * the RIGHT vector's element type for integer types, * unless float or temporal promotion is involved. */ - if (!e0_null && !e0_bool && !left_coll && right_coll && ray_is_vec(right) && out_type != RAY_F64) { + /* Not for the dyadic min/max: their result type is already the + * operands' promoted one (minmax_type), and narrowing it here would + * wrap a chosen scalar, (max 300 u8vec) giving 0x2c. */ + if (!e0_null && !e0_bool && !left_coll && right_coll && ray_is_vec(right) && out_type != RAY_F64 && + fn != ray_min2_fn && fn != ray_max2_fn) { int8_t vec_type = right->type; /* Only override for integer family: if probed type is wider int, downcast */ int out_is_int = (out_type == RAY_I64 || out_type == RAY_I32 || out_type == RAY_I16 || out_type == RAY_U8); @@ -1253,7 +1366,7 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, if (!force_boxed && (out_type == RAY_I64 || out_type == RAY_F64 || out_type == RAY_I32 || out_type == RAY_I16 || out_type == RAY_BOOL || out_type == RAY_U8 || - out_type == RAY_DATE || out_type == RAY_TIME || out_type == RAY_TIMESTAMP)) { + out_type == RAY_DATE || out_type == RAY_TIME || out_type == RAY_TIMESTAMP || out_type == RAY_TIMESPAN)) { ray_t* vec = ray_vec_new(out_type, len); if (RAY_IS_ERR(vec)) { ray_release(e0); return vec; } vec->len = len; @@ -1291,7 +1404,7 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, /* Coerce an integer atom to the scalar's integer type */ #define COERCE_TO_SCALAR(elem) do { \ if (scalar_int_type && ray_is_atom(elem) && elem->type != scalar_int_type && \ - elem->type != -RAY_F64 && is_numeric(elem)) { \ + elem->type != -RAY_F64 && elem->type != -RAY_BOOL && is_numeric(elem)) { \ int64_t _v = as_i64(elem); \ ray_t* _coerced = make_typed_int(scalar_int_type, _v); \ ray_release(elem); \ @@ -1337,7 +1450,22 @@ ray_t* atomic_map_binary_op(ray_binary_fn fn, uint16_t dag_opcode, ray_t* left, out[i] = elem; } #undef COERCE_TO_SCALAR - return result; + return ray_list_collapse_bool(result); +} + +ray_t* ray_list_collapse_bool(ray_t* list) { + if (!list || RAY_IS_ERR(list) || list->type != RAY_LIST) return list; + int64_t n = ray_len(list); + ray_t** e = (ray_t**)ray_data(list); + for (int64_t i = 0; i < n; i++) + if (!e[i] || e[i]->type != -RAY_BOOL) return list; + ray_t* vec = ray_vec_new(RAY_BOOL, n); + if (!vec || RAY_IS_ERR(vec)) return list; + uint8_t* d = (uint8_t*)ray_data(vec); + for (int64_t i = 0; i < n; i++) d[i] = e[i]->b8 ? 1 : 0; + vec->len = n; + ray_release(list); + return vec; } /* Map a unary function element-wise over a collection. @@ -1350,16 +1478,20 @@ ray_t* atomic_map_unary(ray_unary_fn fn, ray_t* arg) { if (len == 0) { /* Empty — fabricate a zero atom of the element type and run * `fn` to learn the output type; fall back to I64 if the - * probe can't resolve a typed atom. */ + * probe can't resolve a typed atom. The probe is ours: a + * failed one (or a failed fabricated operand) is freed and its + * message cleared, since only the type is wanted from it. */ ray_t* z = zero_atom_for_elem_type(arg); ray_t* probe = (z && !RAY_IS_ERR(z)) ? fn(z) : NULL; - if (z) ray_release(z); + bool failed = (z && RAY_IS_ERR(z)) || (probe && RAY_IS_ERR(probe)); + if (z) { if (RAY_IS_ERR(z)) ray_error_free(z); else ray_release(z); } if (probe && !RAY_IS_ERR(probe) && probe->type < 0) { int8_t t = (int8_t)(-probe->type); ray_release(probe); return ray_vec_new(t, 0); } - if (probe && !RAY_IS_ERR(probe)) ray_release(probe); + if (probe) { if (RAY_IS_ERR(probe)) ray_error_free(probe); else ray_release(probe); } + if (failed) ray_error_clear(); return ray_vec_new(RAY_I64, 0); } @@ -1375,7 +1507,7 @@ ray_t* atomic_map_unary(ray_unary_fn fn, ray_t* arg) { /* Try typed vector path for numeric/bool/temporal output */ if (out_type == RAY_I64 || out_type == RAY_F64 || out_type == RAY_I32 || out_type == RAY_I16 || out_type == RAY_BOOL || out_type == RAY_U8 || - out_type == RAY_DATE || out_type == RAY_TIME || out_type == RAY_TIMESTAMP) { + out_type == RAY_DATE || out_type == RAY_TIME || out_type == RAY_TIMESTAMP || out_type == RAY_TIMESPAN) { ray_t* vec = ray_vec_new(out_type, len); if (RAY_IS_ERR(vec)) { ray_release(e0); return vec; } vec->len = len; @@ -1515,7 +1647,7 @@ ray_t* call_fn2(ray_t* fn, ray_t* a, ray_t* b) { owned_b = true; } ray_t* out = (is_collection(la) || is_collection(lb)) - ? atomic_map_binary(f2, la, lb) : f2(la, lb); + ? minmax_map(f2, la, lb) : f2(la, lb); if (owned_a) ray_release(la); if (owned_b) ray_release(lb); return out; @@ -1930,7 +2062,8 @@ ray_t* ray_value_fn(ray_t* x) { ray_t* result = ray_list_new(ncols); if (!result || RAY_IS_ERR(result)) return result ? result : ray_error("oom", NULL); for (int64_t i = 0; i < ncols; i++) { - ray_t* c = ray_table_get_col_idx(x, i); + ray_t* c = ray_table_col_idx(x, i); + if (c && RAY_IS_ERR(c)) { ray_release(result); return c; } result = ray_list_append(result, c); if (RAY_IS_ERR(result)) return result; } @@ -1989,22 +2122,28 @@ ray_t* ray_let_fn(ray_t* name_obj, ray_t* val_expr) { return val; } -/* (if cond then else?) — conditional. Receives unevaluated args. */ +/* (if c1 r1 c2 r2 ... else?) — conditional chain. Receives unevaluated + * args. Conditions are tried in order and the result paired with the + * first truthy one is evaluated; an odd trailing arg is the fallback. No + * fallback: return 0. */ ray_t* ray_cond_fn(ray_t** args, int64_t n) { if (n < 2) return ray_error("domain", "if: expected at least 2 args (cond then), got %lld", (long long)n); - ray_t* cond = ray_eval(args[0]); - if (RAY_IS_ERR(cond)) return cond; - /* A vector condition tested whole: the expression may have needed - * row-by-row evaluation (see the opaque by: key). */ - if (!ray_is_atom(cond)) __VM->rows_cond++; - /* Materialize lazy handles before testing truthiness */ - if (ray_is_lazy(cond)) - cond = ray_lazy_materialize(cond); - if (RAY_IS_ERR(cond)) return cond; - int truthy = is_truthy(cond); - ray_release(cond); - if (truthy) return ray_eval(args[1]); - if (n >= 3) return ray_eval(args[2]); + int64_t i = 0; + for (; i + 1 < n; i += 2) { + ray_t* cond = ray_eval(args[i]); + if (RAY_IS_ERR(cond)) return cond; + /* A vector condition tested whole: the expression may have needed + * row-by-row evaluation (see the opaque by: key). */ + if (!ray_is_atom(cond)) __VM->rows_cond++; + /* Materialize lazy handles before testing truthiness */ + if (ray_is_lazy(cond)) + cond = ray_lazy_materialize(cond); + if (RAY_IS_ERR(cond)) return cond; + int truthy = is_truthy(cond); + ray_release(cond); + if (truthy) return ray_eval(args[i + 1]); + } + if (i < n) return ray_eval(args[i]); /* No else branch: return 0 */ return make_i64(0); } @@ -2106,9 +2245,35 @@ ray_t* ray_times_dec_fn(ray_t* x) { return make_i64(as_i64(x) - 1); } +/* The index of the pass about to run, from the normalized bound and the + * passes still to go (counter > 0 when this is called). */ +ray_t* ray_times_idx_fn(ray_t* lim, ray_t* ctr) { + return make_i64(as_i64(lim) - as_i64(ctr)); +} + +/* If `ast` is the binding of an indexed `times`, as the parser builds it + * from [name count], fill the name's sym and the count expression. */ +bool ray_times_binding(ray_t* ast, int64_t* name, ray_t** count) { + if (!ast || ast->type != RAY_LIST || ast->len != 3) return false; + ray_t** e = (ray_t**)ray_data(ast); + if (!e[0] || e[0]->type != -RAY_SYM || (e[0]->attrs & ATTR_QUOTED) || + e[0]->i64 != ray_sym_intern(RAY_TIMES_BIND, sizeof(RAY_TIMES_BIND) - 1)) + return false; + if (!e[1] || e[1]->type != -RAY_SYM) return false; + *name = e[1]->i64; + *count = e[2]; + return true; +} + /* (times n body...) — evaluate the body exactly n times. Receives * unevaluated args. Always returns null, like `while`. * + * (times [i n] body...) also binds i to 0, 1, ..., n-1, one per pass. + * The name is bound like a `let`, in the current frame, and stays bound + * after the loop to the last index (untouched when no pass runs). The + * index is assigned at the top of each pass from the loop's own counter, + * so a body that rebinds i changes it for the rest of that pass only. + * * `n` is evaluated ONCE, up front: the count is a bound fixed on entry, * so a body that mutates whatever produced it cannot change how many * passes remain. A count of zero or less runs the body zero times @@ -2122,7 +2287,12 @@ ray_t* ray_times_dec_fn(ray_t* x) { * The compiled form is emitted by the bytecode compiler — see compile.c. */ ray_t* ray_times_fn(ray_t** args, int64_t n) { if (n < 1) return ray_error("domain", "times: expected at least 1 arg (count), got %lld", (long long)n); - ray_t* cnt = ray_eval(args[0]); + int64_t name = -1; + ray_t* cexpr = args[0]; + if (ray_times_binding(args[0], &name, &cexpr) && + ray_sym_is_reserved(name) && !ray_sym_is_ipc_hook(name)) + return ray_error(ray_err_code_str(RAY_ERR_RESERVED), NULL); + ray_t* cnt = ray_eval(cexpr); if (RAY_IS_ERR(cnt)) return cnt; if (ray_is_lazy(cnt)) cnt = ray_lazy_materialize(cnt); @@ -2133,6 +2303,13 @@ ray_t* ray_times_fn(ray_t** args, int64_t n) { ray_release(cnt); if (bad) return err; for (int64_t r = 0; r < reps; r++) { + if (name >= 0) { + ray_t* idx = make_i64(r); + if (RAY_IS_ERR(idx)) return idx; + ray_err_t e = ray_env_set_local_rows(name, idx, 0); + ray_release(idx); + if (e != RAY_OK) return ray_error(ray_err_code_str(e), NULL); + } for (int64_t i = 1; i < n; i++) { ray_t* val = ray_eval(args[i]); if (RAY_IS_ERR(val)) return val; @@ -3303,7 +3480,7 @@ op_callf: { } } result = (is_collection(fn_args[0]) || is_collection(fn_args[1])) - ? atomic_map_binary(binary, fn_args[0], fn_args[1]) + ? minmax_map(binary, fn_args[0], fn_args[1]) : binary(fn_args[0], fn_args[1]); ray_release(fn_args[0]); ray_release(fn_args[1]); @@ -4451,6 +4628,7 @@ static void ray_register_builtins(void) { register_vary("del", RAY_FN_SPECIAL_FORM | RAY_FN_RESTRICTED, ray_del_fn); register_vary(".sys.build", RAY_FN_NONE, ray_internals_fn); register_vary(".sys.mem", RAY_FN_NONE, ray_memstat_fn); + register_unary(".idx.uses", RAY_FN_NONE, ray_idx_uses_fn); register_vary(".sys.prof", RAY_FN_NONE, ray_prof_fn); register_vary(".sys.querylog", RAY_FN_NONE, ray_qlog_fn); register_vary(".sys.querylog.enable", RAY_FN_RESTRICTED, ray_qlog_enable_fn); @@ -4501,7 +4679,7 @@ static void ray_register_builtins(void) { register_unary (".idx.bloom", RAY_FN_NONE, ray_idx_bloom_fn); register_unary (".idx.drop", RAY_FN_NONE, ray_idx_drop_fn); register_unary (".idx.has?", RAY_FN_NONE, ray_idx_has_fn); - register_unary (".idx.info", RAY_FN_NONE, ray_idx_info_fn); + register_vary (".idx.info", RAY_FN_NONE, ray_idx_info_vary_fn); /* Semantic attributes (see src/ops/idxop.c: (.attr.*) family) */ register_binary(".attr.set", RAY_FN_NONE, ray_attr_set_fn); @@ -4808,7 +4986,7 @@ ray_t* ray_eval(ray_t* obj) { if (!right || RAY_IS_ERR(right)) { ray_release(left); ret = right ? right : ray_error("type", NULL); goto out; } } ret = (is_collection(left) || is_collection(right)) - ? atomic_map_binary(fn2, left, right) : fn2(left, right); + ? minmax_map(fn2, left, right) : fn2(left, right); ray_release(left); ray_release(right); goto out; @@ -5071,6 +5249,7 @@ ray_t* ray_eval(ray_t* obj) { ray_t* ray_eval_str(const char* source) { ray_clear_error_trace(); + ray_raise_clear(); ray_t* nfo = ray_nfo_create(RAY_NFO_REPL_NAME, strlen(RAY_NFO_REPL_NAME), source, strlen(source)); ray_t* parsed = ray_parse_with_nfo(source, nfo); if (RAY_IS_ERR(parsed)) { ray_release(nfo); return parsed; } diff --git a/src/lang/eval.h b/src/lang/eval.h index 655063ee5..9704dfe8e 100644 --- a/src/lang/eval.h +++ b/src/lang/eval.h @@ -46,6 +46,11 @@ #define ATTR_QUOTED 0x20 /* -RAY_SYM atom with this flag SET = quoted/literal symbol; CLEAR (default) = name reference, resolved at eval. */ +/* Head of the list the parser makes from the [name count] binding of an + * indexed `times`: (RAY_TIMES_BIND name count). The space keeps any + * source token from spelling it. */ +#define RAY_TIMES_BIND "times bind" + /* Internal eval flag for RAY_LIST values carried as nested IPC arguments. * The evaluator still runs callable lists normally; this only makes a * non-callable list head fall back to returning the list as data. */ @@ -140,18 +145,24 @@ enum { */ #define LAMBDA_SLOTS 10 +/* The slots that hold no reference, and the last one that does. The free + * walk in mem/heap.c drops slots 0 .. LAMBDA_SLOT_CAPROWS but n_locals. */ +#define LAMBDA_SLOT_NLOCALS 4 +#define LAMBDA_SLOT_CAPROWS 8 +#define LAMBDA_SLOT_CAPQ 9 + #define RAY_FN_COMPILED 0x40 /* lambda has been compiled to bytecode */ #define LAMBDA_PARAMS(lam) (((ray_t**)ray_data(lam))[0]) -#define LAMBDA_BODY(lam) (((ray_t**)ray_data(lam))[1]) +#define LAMBDA_BODY(lam) (((ray_t**)ray_data(lam))[1]) /* not-a-table */ #define LAMBDA_BC(lam) (((ray_t**)ray_data(lam))[2]) #define LAMBDA_CONSTS(lam) (((ray_t**)ray_data(lam))[3]) -#define LAMBDA_NLOCALS(lam) (*((int32_t*)&((ray_t**)ray_data(lam))[4])) +#define LAMBDA_NLOCALS(lam) (*((int32_t*)&((ray_t**)ray_data(lam))[LAMBDA_SLOT_NLOCALS])) #define LAMBDA_NFO(lam) (((ray_t**)ray_data(lam))[5]) #define LAMBDA_DBG(lam) (((ray_t**)ray_data(lam))[6]) #define LAMBDA_CLOSURE(lam) (((ray_t**)ray_data(lam))[7]) -#define LAMBDA_CAPROWS(lam) (((ray_t**)ray_data(lam))[8]) -#define LAMBDA_CAPQ(lam) (*((uint32_t*)&((ray_t**)ray_data(lam))[9])) +#define LAMBDA_CAPROWS(lam) (((ray_t**)ray_data(lam))[LAMBDA_SLOT_CAPROWS]) +#define LAMBDA_CAPQ(lam) (*((uint32_t*)&((ray_t**)ray_data(lam))[LAMBDA_SLOT_CAPQ])) #define LAMBDA_IS_COMPILED(lam) ((lam)->attrs & RAY_FN_COMPILED) @@ -244,6 +255,8 @@ void ray_lang_print(FILE* fp, ray_t* val); void ray_eval_request_interrupt(void); void ray_eval_clear_interrupt(void); int ray_eval_is_interrupted(void); +/* Depth of the evaluation in progress on this thread: 0 between statements. */ +int ray_eval_depth(void); /* Return the current eval context's nfo (source location) object, or NULL. */ ray_t* ray_eval_get_nfo(void); @@ -254,6 +267,13 @@ void ray_eval_set_nfo(ray_t* nfo); ray_t* ray_get_error_trace(void); void ray_clear_error_trace(void); +/* Pending uncaught (raise x) value. ray_raise_clear drops it — call at each + * top-level evaluation boundary (ray_eval_str does). ray_raise_render + * writes a bounded rendering into buf for an error printer; false when no + * raise is pending. */ +void ray_raise_clear(void); +bool ray_raise_render(char* buf, size_t cap); + /* Restricted mode: when true, builtins with RAY_FN_RESTRICTED are blocked. */ void ray_eval_set_restricted(bool on); bool ray_eval_get_restricted(void); @@ -420,6 +440,8 @@ ray_t* ray_while_fn(ray_t** args, int64_t n); ray_t* ray_times_fn(ray_t** args, int64_t n); ray_t* ray_times_norm_fn(ray_t* x); ray_t* ray_times_dec_fn(ray_t* x); +ray_t* ray_times_idx_fn(ray_t* lim, ray_t* ctr); +bool ray_times_binding(ray_t* ast, int64_t* name, ray_t** count); ray_t* ray_fn(ray_t** args, int64_t n); ray_t* ray_raise_fn(ray_t* val); ray_t* ray_try_fn(ray_t* expr, ray_t* handler_expr); diff --git a/src/lang/format.c b/src/lang/format.c index 6c054f6d1..98d59e5f5 100644 --- a/src/lang/format.c +++ b/src/lang/format.c @@ -21,8 +21,11 @@ * SOFTWARE. */ +#include "ops/colgather.h" /* fmt_enc_window: the shown rows of an encoded column */ +#include "core/timespan.h" #include "lang/format.h" #include "lang/env.h" +#include "table/table.h" #include "table/sym.h" #include "lang/eval.h" #include "ops/ops.h" /* RAY_LAZY, ray_lazy_materialize */ @@ -52,6 +55,8 @@ typedef struct { * appended (mode 2) */ bool io_err; /* err was a failed write to sink */ bool flushed; /* some output already reached sink */ + char cause_code[16]; /* code of the error that stopped a column from loading */ + char cause_msg[192]; /* its detail (names the column file) */ } fmt_buf_t; #define FMT_SINK_FLUSH ((int64_t)1 << 20) @@ -71,6 +76,8 @@ static void fmt_init(fmt_buf_t* b) { b->sink = NULL; b->io_err = false; b->flushed = false; + b->cause_code[0] = '\0'; + b->cause_msg[0] = '\0'; b->block = ray_alloc(256); if (!b->block) { /* ray_alloc returns NULL (never an error object) on failure */ b->err = true; b->err_msg = "cannot allocate the initial output buffer"; @@ -184,7 +191,9 @@ static void fmt_putn(fmt_buf_t* b, const char* s, int64_t n) { static ray_t* fmt_to_str(fmt_buf_t* b) { if (b->err) { - ray_t* e = ray_error("format", "%s", b->err_msg ? b->err_msg : "output buffer error"); + ray_t* e = b->cause_code[0] + ? ray_error(b->cause_code, "%s: %s", b->err_msg, b->cause_msg) + : ray_error("format", "%s", b->err_msg ? b->err_msg : "output buffer error"); fmt_destroy(b); return e; } @@ -223,6 +232,7 @@ const char* ray_type_name(int8_t type) { case RAY_F64: return type < 0 ? "f64" : "F64"; case RAY_DATE: return type < 0 ? "date" : "DATE"; case RAY_TIME: return type < 0 ? "time" : "TIME"; + case RAY_TIMESPAN: return type < 0 ? "timespan" : "TIMESPAN"; case RAY_TIMESTAMP: return type < 0 ? "timestamp" : "TIMESTAMP"; case RAY_SYM: return type < 0 ? "sym" : "SYM"; case RAY_STR: return type < 0 ? "str" : "STR"; @@ -301,6 +311,7 @@ static void fmt_f64(fmt_buf_t* b, double val) { static void fmt_f32(fmt_buf_t* b, float val) { fmt_f64(b, (double)val); + fmt_putc(b, 'e'); } static void fmt_guid(fmt_buf_t* b, const uint8_t* bytes) { @@ -388,6 +399,12 @@ static void fmt_time(fmt_buf_t* b, int32_t val) { fmt_printf(b, "%02d:%02d:%02d.%03d", h, m, s, ms); } +static void fmt_timespan(fmt_buf_t* b, int64_t ns) { + char text[64]; + int n = ray_format_timespan(text, sizeof(text), ns); + if (n > 0 && n < (int)sizeof(text)) fmt_putn(b, text, n); +} + static void fmt_timestamp(fmt_buf_t* b, int64_t val) { int y, mo, d, h, mi, s, ns; ts_to_parts(val, &y, &mo, &d, &h, &mi, &s, &ns); @@ -409,7 +426,7 @@ static void fmt_obj(fmt_buf_t* b, ray_t* obj, int mode); /* ===== Null literal display (type → "0Nx" string) ===== */ -static const char* null_literal(int8_t type) { +const char* ray_fmt_null_literal(int8_t type) { switch (type) { case RAY_BOOL: return "0Nb"; case RAY_U8: return "0Nu"; @@ -420,9 +437,12 @@ static const char* null_literal(int8_t type) { case RAY_F32: return "0Ne"; case RAY_DATE: return "0Nd"; case RAY_TIME: return "0Nt"; + case RAY_TIMESPAN: return "0Nn"; case RAY_TIMESTAMP: return "0Np"; - /* SYM/STR have no separate null literal: their canonical empty/null values - * render as ' / "" on their ordinary formatting paths. */ + /* SYM's null is the empty symbol, written ' (as fmt_sym_atom renders + * it); `null` would read back as the symbol `null`. STR's null is "", + * which its callers write on the ordinary string path. */ + case RAY_SYM: return "'"; case RAY_GUID: return "0Ng"; default: return "null"; } @@ -435,7 +455,7 @@ static void fmt_raw_elem(fmt_buf_t* b, ray_t* vec, int64_t idx) { * distinct null (empty and null are the same value), so it renders * as "" via the RAY_STR case below rather than a 0Nc literal. */ if (vec->type != RAY_STR && ray_vec_is_null(vec, idx)) { - fmt_puts(b, null_literal(vec->type)); + fmt_puts(b, ray_fmt_null_literal(vec->type)); return; } @@ -450,6 +470,7 @@ static void fmt_raw_elem(fmt_buf_t* b, ray_t* vec, int64_t idx) { case RAY_F64: fmt_f64(b, ((double*)ray_data(vec))[idx]); break; case RAY_DATE: fmt_date(b, ((int32_t*)ray_data(vec))[idx]); break; case RAY_TIME: fmt_time(b, ((int32_t*)ray_data(vec))[idx]); break; + case RAY_TIMESPAN: fmt_timespan(b, ((int64_t*)ray_data(vec))[idx]); break; case RAY_TIMESTAMP: fmt_timestamp(b, ((int64_t*)ray_data(vec))[idx]); break; case RAY_SYM: /* cell-data: resolve through the column's domain */ @@ -520,6 +541,22 @@ static void fmt_list(fmt_buf_t* b, ray_t* list, int mode) { int64_t len = ray_len(list); if (len == 0) { fmt_puts(b, "()"); return; } + /* The binding of an indexed `times`, (RAY_TIMES_BIND name count) as the + * parser builds it from [name count]: print it as it was written, so a + * quoted loop reads back and round-trips. */ + { + int64_t bname = -1; + ray_t* bcount = NULL; + if (ray_times_binding(list, &bname, &bcount)) { + fmt_putc(b, '['); + fmt_obj(b, ((ray_t**)ray_data(list))[1], mode); /* not-a-table */ + fmt_putc(b, ' '); + fmt_obj(b, bcount, mode); + fmt_putc(b, ']'); + return; + } + } + /* Historical display equivalence: a homogeneous-atom list renders as a * vector [..] in the round-trippable / cell modes (0 and 2), which the * test suite and value-equality (fmt_eq, mode 0) rely on. REPL display @@ -593,7 +630,7 @@ static void fmt_dict_key(fmt_buf_t* b, ray_t* keys, int64_t i, int mode) { const char* sp = ray_str_vec_get(keys, i, &slen); k_atom = ray_str(sp ? sp : "", sp ? slen : 0); k_owned = true; - } else if (keys->type == RAY_I64 || keys->type == RAY_TIMESTAMP) { + } else if (keys->type == RAY_I64 || keys->type == RAY_TIMESPAN || keys->type == RAY_TIMESTAMP) { k_atom_storage.type = (int8_t)-keys->type; k_atom_storage.i64 = ((int64_t*)ray_data(keys))[i]; k_atom = &k_atom_storage; @@ -658,7 +695,7 @@ static void fmt_dict_val(fmt_buf_t* b, ray_t* vals, int64_t i, int mode) { v_storage.i32 = ((int32_t*)ray_data(vals))[i]; v_atom = &v_storage; break; case RAY_I64: - case RAY_TIMESTAMP: v_storage.type = (int8_t)-vals->type; + case RAY_TIMESPAN: case RAY_TIMESTAMP: v_storage.type = (int8_t)-vals->type; v_storage.i64 = ((int64_t*)ray_data(vals))[i]; v_atom = &v_storage; break; case RAY_F32: v_storage.type = -RAY_F32; @@ -801,6 +838,180 @@ static void fmt_centered(fmt_buf_t* b, const char* s, int32_t slen, int32_t widt for (int32_t i = 0; i < right; i++) fmt_putc(b, ' '); } +/* ===== Parted table cells ===== + * + * A parted table's columns hold no cells of their own: a parted column + * (RAY_PARTED_BASE + type) is an array of per-partition segments, and the + * partition-key column (RAY_MAPCOMMON) one key per partition with that + * partition's row count. Every table format reads their cells in place, + * as the flat column they stand for prints them, without building it. A + * NULL segment — a partition without the column (ragged, see store/part.c) + * — spans that partition's rows, from the table's partition-key counts, + * and prints the column's typed null, as the flat column with nulls does. + * + * fmt_col_t walks one column: a cursor over its partitions, so reading the + * rows in order costs one step per row (a jump back restarts it). */ +typedef struct { + ray_t* col; /* the table column (any kind) */ + int8_t type; /* element type of the flat column */ + const int64_t* cnt; /* per-partition row counts, NULL if none */ + int64_t ncnt; + int64_t s; /* cursor: current partition */ + int64_t start; /* cursor: its first row */ +} fmt_col_t; + +enum { FMT_CELL_OUT, FMT_CELL_MISSING, FMT_CELL_AT }; + +static bool fmt_col_is_parted(ray_t* col) { + return col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON); +} + +static int8_t fmt_col_type(ray_t* col) { + if (!col) return 0; + if (RAY_IS_PARTED(col->type)) return (int8_t)RAY_PARTED_BASETYPE(col->type); + if (col->type == RAY_MAPCOMMON) { + ray_t* keys = ((ray_t**)ray_data(col))[0]; + return keys ? keys->type : 0; + } + return col->type; +} + +/* The per-partition row counts of a parted table: its partition-key + * column's counts vector, or NULL. */ +static ray_t* fmt_part_counts(ray_t* tbl) { + int64_t ncols = ray_table_ncols(tbl); + for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t m; /* metadata first: MAPCOMMON is plain, nothing decodes */ + if (!ray_table_col_meta_idx(tbl, c, &m) || m.type != RAY_MAPCOMMON) continue; + ray_t* col = ray_table_col_idx(tbl, c); + if (col && !RAY_IS_ERR(col) && col->type == RAY_MAPCOMMON) { + ray_t* rc = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + return rc && !RAY_IS_ERR(rc) ? rc : NULL; + } + } + return NULL; +} + +static void fmt_col_init(fmt_col_t* c, ray_t* col, ray_t* counts) { + c->col = col; + c->type = fmt_col_type(col); + c->cnt = NULL; + c->ncnt = 0; + c->s = 0; + c->start = 0; + if (col && col->type == RAY_MAPCOMMON) counts = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + if (counts && !RAY_IS_ERR(counts)) { + c->cnt = (const int64_t*)ray_data(counts); + c->ncnt = counts->len; + } +} + +static int64_t fmt_col_nparts(const fmt_col_t* c) { + if (RAY_IS_PARTED(c->col->type)) return c->col->len; + ray_t* keys = ((ray_t**)ray_data(c->col))[0]; + if (!keys) return 0; + return c->ncnt < keys->len ? c->ncnt : keys->len; +} + +/* Rows of partition p: its segment's length, else the partition's count. */ +static int64_t fmt_col_part_rows(const fmt_col_t* c, int64_t p) { + if (RAY_IS_PARTED(c->col->type)) { + ray_t* seg = ((ray_t**)ray_data(c->col))[p]; + if (seg && !RAY_IS_ERR(seg)) return seg->len; + } + return p < c->ncnt ? c->cnt[p] : 0; +} + +/* Resolve row ri to the vector and index holding its cell (FMT_CELL_AT), + * a missing segment's null (FMT_CELL_MISSING), or no such row. */ +static int fmt_col_cell(fmt_col_t* c, int64_t ri, ray_t** vec, int64_t* at) { + ray_t* col = c->col; + if (!col || ri < 0) return FMT_CELL_OUT; + if (!fmt_col_is_parted(col)) { + if (ri >= ray_len(col)) return FMT_CELL_OUT; + *vec = col; *at = ri; + return FMT_CELL_AT; + } + if (ri < c->start) { c->s = 0; c->start = 0; } + int64_t np = fmt_col_nparts(c); + while (c->s < np) { + int64_t n = fmt_col_part_rows(c, c->s); + if (ri - c->start < n) break; + c->start += n; + c->s++; + } + if (c->s >= np) return FMT_CELL_OUT; + if (col->type == RAY_MAPCOMMON) { + *vec = ((ray_t**)ray_data(col))[0]; + *at = c->s; + return FMT_CELL_AT; + } + ray_t* seg = ((ray_t**)ray_data(col))[c->s]; + if (!seg || RAY_IS_ERR(seg)) return FMT_CELL_MISSING; + *vec = seg; + *at = ri - c->start; + return FMT_CELL_AT; +} + +/* A missing segment's cell, as fmt_raw_elem prints a null of the type: + * its null literal, "" for STR, null for a LIST cell; B8/U8 have no null + * (the flat column holds 0 there, as ser writes it). */ +static void fmt_missing_cell(fmt_buf_t* b, int8_t type) { + switch (type) { + case RAY_BOOL: fmt_bool(b, 0); return; + case RAY_U8: fmt_u8(b, 0); return; + case RAY_STR: fmt_puts(b, "\"\""); return; + default: fmt_puts(b, ray_fmt_null_literal(type)); return; + } +} + +/* Write row ri's cell; false when the column has no such row. */ +static bool fmt_col_write(fmt_buf_t* b, fmt_col_t* c, int64_t ri) { + ray_t* v = NULL; + int64_t at = 0; + switch (fmt_col_cell(c, ri, &v, &at)) { + case FMT_CELL_AT: fmt_raw_elem(b, v, at); return true; + case FMT_CELL_MISSING: fmt_missing_cell(b, c->type); return true; + default: return false; + } +} + +/* Row ri's element of a parted LIST column (a missing segment's is null). */ +static ray_t* fmt_col_elem(fmt_col_t* c, int64_t ri) { + ray_t* v = NULL; + int64_t at = 0; + if (fmt_col_cell(c, ri, &v, &at) != FMT_CELL_AT) return RAY_NULL_OBJ; + return ((ray_t**)ray_data(v))[at]; +} + +/* A parted column of `nrows` rows in compact mode (0), exactly as fmt_obj + * writes the flat column: fmt_vector unlimited, or fmt_list for LIST. */ +static void fmt_col_compact(fmt_buf_t* b, fmt_col_t* c, int64_t nrows) { + if (c->type != RAY_LIST) { + if (nrows == 0) { fmt_puts(b, "[]"); return; } + fmt_putc(b, '['); + for (int64_t ri = 0; ri < nrows && !b->err; ri++) { + if (ri > 0) fmt_putc(b, ' '); + if (!fmt_col_write(b, c, ri)) fmt_missing_cell(b, c->type); + } + fmt_putc(b, ']'); + return; + } + if (nrows == 0) { fmt_puts(b, "()"); return; } + ray_t* first = fmt_col_elem(c, 0); + bool homogeneous = first && !RAY_IS_ERR(first) && ray_is_atom(first); + for (int64_t ri = 1; homogeneous && ri < nrows; ri++) { + ray_t* e = fmt_col_elem(c, ri); + if (!e || RAY_IS_ERR(e) || e->type != first->type) homogeneous = false; + } + fmt_puts(b, homogeneous ? "[" : "(list "); + for (int64_t ri = 0; ri < nrows && !b->err; ri++) { + if (ri > 0) fmt_putc(b, ' '); + fmt_obj(b, fmt_col_elem(c, ri), 0); + } + fmt_putc(b, homogeneous ? ']' : ')'); +} + /* The REPL display (mode 1) pre-formats at most FMT_TABLE_MAX_WIDTH x * FMT_TABLE_MAX_HEIGHT cells on the stack; mode 2 without a sink pre-formats * the whole table on the heap, and show streams it (fmt_table_stream). */ @@ -815,11 +1026,10 @@ typedef struct { * each column's display width over every cell; the second writes the rows, * which the sink flushes as the buffer fills. Memory is O(columns), unlike * the pre-formatted cell grid of the REPL display. */ -static void fmt_stream_cell(fmt_buf_t* tmp, ray_t* col, int64_t ri, +static void fmt_stream_cell(fmt_buf_t* tmp, fmt_col_t* col, int64_t ri, const char** s, int32_t* len) { - if (!col || ri >= ray_len(col)) { *s = "NA"; *len = 2; return; } tmp->len = 0; - fmt_raw_elem(tmp, col, ri); + if (!fmt_col_write(tmp, col, ri)) { *s = "NA"; *len = 2; return; } *s = tmp->buf; *len = tmp->len; /* whole cell: tmp grows, unlike the REPL's fixed grid */ } @@ -839,6 +1049,51 @@ static void fmt_stream_rule(fmt_buf_t* b, const int32_t* w, int64_t n, * value in 10k rows wrote 100 MB of spaces). */ #define FMT_SHOW_PAD_MAX 256 +/* Column ci as a plain vector. A column that fails to materialize sets the + * builder's error (the thread-local message keeps the detail) and yields NULL; + * callers stop on b->err. */ +static ray_t* fmt_col_idx(fmt_buf_t* b, ray_t* tbl, int64_t ci) { + ray_t* c = ray_table_col_idx(tbl, ci); + if (c && RAY_IS_ERR(c)) { + const char* code = ray_err_code(c); + const char* msg = ray_error_msg(); + snprintf(b->cause_code, sizeof b->cause_code, "%s", code ? code : "format"); + snprintf(b->cause_msg, sizeof b->cause_msg, "%s", msg ? msg : ""); + ray_error_free(c); + b->err = true; b->err_msg = "column failed to load"; + return NULL; + } + return c; +} + +/* The shown rows of an encoded column ci: the first `half` rows and the + * last `height - half`, gathered by range into a vector of `height` rows, + * so a display of a compressed table reads what it shows instead of + * decoding every column whole. NULL when the slot is plain or a slice, or + * every row is shown (the caller takes the column); NULL with b->err set on + * a failed read. */ +static ray_t* fmt_enc_window(fmt_buf_t* b, ray_t* tbl, int64_t ci, int64_t nrows, + int64_t height, int64_t half) { + if (height >= nrows) return NULL; + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(tbl, ci)); + if (!enc) return NULL; + int64_t ids[FMT_TABLE_MAX_HEIGHT]; + if (height > FMT_TABLE_MAX_HEIGHT) return NULL; + for (int64_t r = 0; r < height; r++) ids[r] = r < half ? r : nrows - height + r; + ray_t* out = NULL; + ray_t* err = ray_col_gather_enc(enc, NULL, true, ids, height, &out); + if (err) { + const char* code = ray_err_code(err); + const char* msg = ray_error_msg(); + snprintf(b->cause_code, sizeof b->cause_code, "%s", code ? code : "format"); + snprintf(b->cause_msg, sizeof b->cause_msg, "%s", msg ? msg : ""); + ray_error_free(err); + b->err = true; b->err_msg = "column failed to load"; + return NULL; + } + return out; +} + static void fmt_table_stream(fmt_buf_t* b, ray_t* tbl) { int64_t ncols = ray_table_ncols(tbl); int64_t nrows = ray_table_nrows(tbl); @@ -847,20 +1102,26 @@ static void fmt_table_stream(fmt_buf_t* b, ray_t* tbl) { ray_t* wblk = ray_alloc((size_t)ncols * sizeof(int32_t)); ray_t* nblk = ray_alloc((size_t)ncols * sizeof(ray_t*)); if (nblk) memset(ray_data(nblk), 0, (size_t)ncols * sizeof(ray_t*)); + ray_t* cblk = ray_alloc((size_t)ncols * sizeof(fmt_col_t)); /* cursors over borrowed plain columns */ fmt_buf_t tmp; fmt_init(&tmp); - if (!wblk || !nblk || tmp.err) { + if (!wblk || !nblk || !cblk || tmp.err) { b->err = true; b->err_msg = "out of memory formatting a table"; goto done; } - int32_t* widths = (int32_t*)ray_data(wblk); - ray_t** names = (ray_t**)ray_data(nblk); + int32_t* widths = (int32_t*)ray_data(wblk); + ray_t** names = (ray_t**)ray_data(nblk); + fmt_col_t* cols = (fmt_col_t*)ray_data(cblk); + ray_t* counts = fmt_part_counts(tbl); for (int64_t ci = 0; ci < ncols; ci++) { ray_t* nm = ray_sym_str(ray_table_col_name(tbl, ci)); names[ci] = (nm && !RAY_IS_ERR(nm)) ? nm : NULL; - ray_t* col = ray_table_get_col_idx(tbl, ci); - const char* tname = ray_type_name(col ? col->type : 0); + ray_t* plain = fmt_col_idx(b, tbl, ci); + if (b->err) goto done; + fmt_col_t* col = &cols[ci]; + fmt_col_init(col, plain, counts); + const char* tname = ray_type_name(col->type); int32_t w = names[ci] ? fmt_utf8_width(ray_str_ptr(names[ci]), (int32_t)ray_str_len(names[ci])) : 1; if ((int32_t)strlen(tname) > w) w = (int32_t)strlen(tname); int32_t cell_w = 0; @@ -895,8 +1156,7 @@ static void fmt_table_stream(fmt_buf_t* b, ray_t* tbl) { fmt_putc(b, '\n'); fmt_puts(b, G_V); for (int64_t ci = 0; ci < ncols; ci++) { - ray_t* col = ray_table_get_col_idx(tbl, ci); - const char* tname = ray_type_name(col ? col->type : 0); + const char* tname = ray_type_name(cols[ci].type); fmt_centered(b, tname, (int32_t)strlen(tname), widths[ci]); fmt_puts(b, G_V); } @@ -907,7 +1167,7 @@ static void fmt_table_stream(fmt_buf_t* b, ray_t* tbl) { fmt_puts(b, G_V); for (int64_t ci = 0; ci < ncols; ci++) { const char* cs; int32_t cl; - fmt_stream_cell(&tmp, ray_table_get_col_idx(tbl, ci), ri, &cs, &cl); + fmt_stream_cell(&tmp, &cols[ci], ri, &cs, &cl); if (tmp.err) { b->err = true; b->err_msg = "out of memory formatting a table"; goto done; } fmt_putc(b, ' '); fmt_putn(b, cs, cl); @@ -935,6 +1195,7 @@ static void fmt_table_stream(fmt_buf_t* b, ray_t* tbl) { ray_free(nblk); } if (wblk) ray_free(wblk); + if (cblk) ray_free(cblk); fmt_destroy(&tmp); } @@ -942,6 +1203,8 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { int64_t ncols = ray_table_ncols(tbl); int64_t nrows = ray_table_nrows(tbl); + ray_t* part_counts = fmt_part_counts(tbl); /* NULL unless parted */ + /* Compact mode: round-trippable (table [names] (list col1 col2 ...)) */ if (mode == 0) { fmt_puts(b, "(table ["); @@ -957,8 +1220,13 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { fmt_puts(b, "] (list "); for (int64_t i = 0; i < ncols; i++) { if (i > 0) fmt_putc(b, ' '); - ray_t* col = ray_table_get_col_idx(tbl, i); - if (col) { + ray_t* col = fmt_col_idx(b, tbl, i); + if (b->err) return; + if (fmt_col_is_parted(col)) { + fmt_col_t cur; + fmt_col_init(&cur, col, part_counts); + fmt_col_compact(b, &cur, nrows); + } else if (col) { fmt_obj(b, col, mode); } } @@ -1066,8 +1334,20 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { } /* Column type */ - ray_t* col_vec = ray_table_get_col_idx(tbl, ci); - const char* tname = ray_type_name(col_vec ? col_vec->type : 0); + ray_t* col_win = fmt_enc_window(b, tbl, ci, nrows, table_height, table_height / 2); + ray_t* col_vec = col_win ? col_win : b->err ? NULL : fmt_col_idx(b, tbl, ci); + if (b->err) { + for (int64_t k = 0; k <= ci; k++) if (name_refs[k]) ray_release(name_refs[k]); + if (heap_alloc) { + ray_free(heap_widths_blk); ray_free(heap_names_blk); ray_free(heap_nlen_blk); + ray_free(heap_types_blk); ray_free(heap_tlen_blk); ray_free(heap_refs_blk); + ray_free(heap_cells_blk); + } + return; + } + fmt_col_t cur; + fmt_col_init(&cur, col_vec, part_counts); + const char* tname = ray_type_name(cur.type); col_types[ci] = tname; col_type_lens[ci] = (int32_t)strlen(tname); @@ -1076,25 +1356,27 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { int32_t max_w = fmt_utf8_width(col_names[ci], col_name_lens[ci]); if (col_type_lens[ci] > max_w) max_w = col_type_lens[ci]; - int64_t col_len = col_vec ? ray_len(col_vec) : 0; + /* A parted column spans the table's rows (a NULL segment's too). */ + int64_t col_len = !col_vec ? 0 + : (RAY_IS_PARTED(col_vec->type) || col_vec->type == RAY_MAPCOMMON) + ? nrows : ray_len(col_vec); /* Format first half (head rows) */ int64_t half = table_height / 2; for (int64_t ri = 0; ri < half; ri++) { fmt_cell_t* cell = &cells[ci * table_height + ri]; - if (ri < col_len) { - fmt_buf_t tmp; - fmt_init(&tmp); - fmt_raw_elem(&tmp, col_vec, ri); + fmt_buf_t tmp; + fmt_init(&tmp); + if (ri < col_len && fmt_col_write(&tmp, &cur, ri)) { int32_t clen = tmp.len < FMT_CELL_BUF_SIZE - 1 ? tmp.len : FMT_CELL_BUF_SIZE - 1; if (clen > 0) memcpy(cell->str, tmp.buf, (size_t)clen); cell->str[clen] = '\0'; cell->len = clen; - fmt_destroy(&tmp); } else { memcpy(cell->str, "NA", 3); cell->len = 2; } + fmt_destroy(&tmp); int32_t cell_dw = fmt_utf8_width(cell->str, cell->len); if (cell_dw > max_w) max_w = cell_dw; } @@ -1108,22 +1390,22 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { } else { src_idx = col_len - table_height + ri; } - if (src_idx >= 0 && src_idx < col_len) { - fmt_buf_t tmp; - fmt_init(&tmp); - fmt_raw_elem(&tmp, col_vec, src_idx); + fmt_buf_t tmp; + fmt_init(&tmp); + if (src_idx >= 0 && src_idx < col_len && fmt_col_write(&tmp, &cur, src_idx)) { int32_t clen = tmp.len < FMT_CELL_BUF_SIZE - 1 ? tmp.len : FMT_CELL_BUF_SIZE - 1; if (clen > 0) memcpy(cell->str, tmp.buf, (size_t)clen); cell->str[clen] = '\0'; cell->len = clen; - fmt_destroy(&tmp); } else { memcpy(cell->str, "NA", 3); cell->len = 2; } + fmt_destroy(&tmp); int32_t cell_dw = fmt_utf8_width(cell->str, cell->len); if (cell_dw > max_w) max_w = cell_dw; } + if (col_win) ray_release(col_win); col_widths[ci] = max_w + 2; /* +2 for padding (1 space each side) */ } @@ -1305,7 +1587,7 @@ static void fmt_obj(fmt_buf_t* b, ray_t* obj, int mode) { /* STR/SYM use their empty literals as canonical null spellings, so * retain those parseable representations instead of inventing 0Nc/0Ns. */ if (-type != RAY_STR && -type != RAY_SYM && RAY_ATOM_IS_NULL(obj)) { - fmt_puts(b, null_literal(-type)); + fmt_puts(b, ray_fmt_null_literal(-type)); return; } /* Atom: type is negated */ @@ -1320,6 +1602,7 @@ static void fmt_obj(fmt_buf_t* b, ray_t* obj, int mode) { case RAY_F64: fmt_f64(b, obj->f64); break; case RAY_DATE: fmt_date(b, obj->i32); break; case RAY_TIME: fmt_time(b, obj->i32); break; + case RAY_TIMESPAN: fmt_timespan(b, obj->i64); break; case RAY_TIMESTAMP: fmt_timestamp(b, obj->i64); break; case RAY_SYM: fmt_sym(b, obj->i64); break; case RAY_STR: fmt_str_atom(b, obj, mode > 0); break; @@ -1464,8 +1747,14 @@ void ray_fmt_pp_print(FILE* fp, ray_t* obj) { /* Write obj to fp in full (show): no row, column or width limits, and * streamed, so memory stays bounded whatever the size of obj. RAY_ERR_IO if - * fp fails, RAY_ERR_OOM if a scratch buffer cannot be allocated. */ -ray_err_t ray_fmt_write(FILE* fp, ray_t* obj) { + * fp fails, RAY_ERR_OOM if a scratch buffer cannot be allocated. A column + * that fails to load is reported with its own code: *cause (when non-NULL) + * receives an owned error carrying its code and message, and the matching + * ray_err_t is returned. Output flushed before the failure stays written + * (a table's columns are all loaded before its first byte, so only values + * formatted ahead of it in the same call are affected). */ +ray_err_t ray_fmt_write(FILE* fp, ray_t* obj, ray_t** cause) { + if (cause) *cause = NULL; fmt_buf_t b; fmt_init(&b); if (b.err) return RAY_ERR_OOM; @@ -1473,6 +1762,11 @@ ray_err_t ray_fmt_write(FILE* fp, ray_t* obj) { fmt_obj(&b, obj, 2); if (!b.err && b.len > 0 && fwrite(b.buf, 1, (size_t)b.len, fp) != (size_t)b.len) b.io_err = b.err = true; + if (b.err && b.cause_code[0] && cause) { + *cause = ray_error(b.cause_code, "%s: %s", b.err_msg, b.cause_msg); + fmt_destroy(&b); + return ray_err_from_obj(*cause); + } ray_err_t e = !b.err ? RAY_OK : b.io_err ? RAY_ERR_IO : RAY_ERR_OOM; /* Out of memory after part of the output was written: end that part * with a marker, and report it as written so the caller does not print diff --git a/src/lang/format.h b/src/lang/format.h index 26461165c..b4f8f2f0a 100644 --- a/src/lang/format.h +++ b/src/lang/format.h @@ -52,8 +52,15 @@ void ray_fmt_print(FILE* fp, ray_t* obj, int mode); /* Write obj to fp in full, without display limits, streaming so memory * stays bounded (show). RAY_ERR_IO if fp fails or if memory ran out after * part of the output was written (the part ends with an error marker); - * RAY_ERR_OOM if memory ran out before anything was written. */ -ray_err_t ray_fmt_write(FILE* fp, ray_t* obj); + * RAY_ERR_OOM if memory ran out before anything was written. A column that + * fails to load yields its own code and an owned error in *cause (free with + * ray_error_free); *cause is NULL otherwise. */ +ray_err_t ray_fmt_write(FILE* fp, ray_t* obj, ray_t** cause); + +/* The printed null of a vector or atom of `type` (a positive type tag): + * 0Nl, 0Ne, 0Ng, ... The one table every printer uses, so a null reads + * back the same way whichever printer wrote it. */ +const char* ray_fmt_null_literal(int8_t type); /* Display settings */ void ray_fmt_set_precision(int digits); diff --git a/src/lang/internal.h b/src/lang/internal.h index f85fc1085..c0777bc94 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -105,7 +105,7 @@ static inline int8_t ray_null_class(int8_t t) { if (t < 0) t = (int8_t)-t; switch (t) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: - case RAY_F64: case RAY_F32: + case RAY_F64: case RAY_F32: case RAY_TIMESPAN: return RAY_I64; default: return t; @@ -203,18 +203,6 @@ static inline int8_t promote_int_type(ray_t* a, ray_t* b) { return -RAY_I64; } -/* Promote integer type following right-operand's type (integer-promotion convention for sub) */ -static inline int8_t promote_int_type_right(ray_t* a, ray_t* b) { - (void)a; - int8_t bt = b->type; - if (bt == -RAY_I32 || bt == -RAY_I16 || bt == -RAY_U8 || bt == -RAY_I64) - return bt; - int8_t at = a->type; - if (at == -RAY_I32 || at == -RAY_I16 || at == -RAY_U8 || at == -RAY_I64) - return at; - return -RAY_I64; -} - /* Create a result atom of the given type from an int64_t value */ static inline ray_t* make_typed_int(int8_t atom_type, int64_t val) { switch (atom_type) { @@ -340,6 +328,7 @@ static inline ray_t* collection_elem(ray_t* coll, int64_t i, int *allocated) { case RAY_U8: return ray_u8(((uint8_t*)d)[i]); case RAY_DATE: return ray_date((int64_t)((int32_t*)d)[i]); case RAY_TIME: return ray_time((int64_t)((int32_t*)d)[i]); + case RAY_TIMESPAN: return ray_timespan(((int64_t*)d)[i]); case RAY_TIMESTAMP: return ray_timestamp(((int64_t*)d)[i]); case RAY_GUID: { const uint8_t* gd = ((uint8_t*)d) + i * 16; @@ -408,6 +397,7 @@ static inline int store_typed_elem(ray_t* vec, int64_t i, ray_t* elem) { case RAY_U8: ((uint8_t*)ray_data(vec))[i] = (uint8_t)elem_as_i64(elem); return 0; case RAY_DATE: ((int32_t*)ray_data(vec))[i] = (int32_t)elem_as_i64(elem); return 0; case RAY_TIME: ((int32_t*)ray_data(vec))[i] = (int32_t)elem_as_i64(elem); return 0; + case RAY_TIMESPAN: ((int64_t*)ray_data(vec))[i] = elem_as_i64(elem); return 0; case RAY_TIMESTAMP: ((int64_t*)ray_data(vec))[i] = elem_as_i64(elem); return 0; /* SYM atoms are runtime-domain by design. Runtime-domain target: * the id is written raw (today's behavior). FILE-domain target @@ -645,8 +635,11 @@ ray_t* ray_mem_ts_fn(ray_t** args, int64_t n); ray_t* ray_gc_fn(ray_t** args, int64_t n); /* Ceiling for growing a read that has no size to go on — an endless stream * has no EOF to reach, and growing to meet it takes the process down. A - * quarter of the heap's remaining anon headroom; 0 means "no bound known", - * which callers treat as permissive. Shared by `read`/`read-bytes` and by + * quarter of the heap's remaining anon headroom, and at least 64 MB: at or + * past the watermark there is none to take a quarter of. The callers bound + * the peak of a grow (3 x the buffer) by it, so past the watermark what they + * read stays within ~32 MB. 0 means "no bound known" — RAM unknown — which + * callers treat as permissive. Shared by `read`/`read-bytes` and by * .sys.exec's output capture, which face the same problem. */ int64_t ray_unsized_read_budget(void); @@ -758,6 +751,34 @@ ray_t* ray_select_fn(ray_t** args, int64_t n); /* Chunk length of the per-distinct-symbol key evaluation over a FILE * domain (ops/query.c derived_key_str_chunks); 0 restores the default. */ void ray_derived_key_chunk_set_for_test(int64_t rows); +/* Rows a key over an encoded column is evaluated by at a time (ops/query.c + * key_eval_by_range): a positive multiple of RAY_MORSEL_ELEMS; 0 restores + * the default. */ +void ray_key_range_rows_set_for_test(int64_t rows); +/* Bits kept of the derived-key grouping's key hash (ops/query.c dkh_hash), + * so distinct keys collide; 0 restores the full 64 bits. */ +void ray_derived_key_hash_bits_set_for_test(int bits); +/* The two-pass grouping under a having cut (ops/query.c dk2_run): out[0] + * its runs; of the last run, out[1] the groups emitted, out[2] the + * candidate hashes, out[3] the groups made for colliding keys, out[4] + * whether the key slices went into H's counts. */ +void ray_derived_key_two_pass_stats_for_test(int64_t out[5]); +/* The exact top-N-by-count grouping (ops/query.c select_topk_hh): the row + * count it starts at (INT64_MAX: off), the counters of a worker's summary, + * the bits of the key hash kept, the memory gate (1 open, -1 shut, 0 the + * budget); each 0 restores the default. The stats: + * out[0] answers, out[1] fallbacks after its passes, out[2] shapes left to + * a dense plan; of the last run out[3] the route (1 answered, 2 fell back, + * 3 dense, 4 saturated), out[4] E_eff, out[5] T, out[6] candidate hashes, + * out[7] the groups of pass B; out[8] shapes the memory gate left to the + * grouping (route 5); out[9] the bytes of one pass B table (0: no pass B). + * The pass B budget hook replaces the tables' budget (all workers). */ +void ray_group_topk_min_rows_set_for_test(int64_t rows); +void ray_group_topk_counters_set_for_test(int64_t m); +void ray_group_topk_hash_bits_set_for_test(int bits); +void ray_group_topk_mem_gate_set_for_test(int mode); +void ray_group_topk_ex_budget_set_for_test(int64_t bytes); +void ray_group_topk_stats_for_test(int64_t out[10]); #endif ray_t* ray_window_fn(ray_t** args, int64_t n); ray_t* ray_try_count_select_expr(ray_t* expr, int* handled); @@ -798,6 +819,11 @@ ray_t* ray_graph_shortest_path_fn(ray_t** args, int64_t n); ray_t* ray_graph_expand_fn(ray_t** args, int64_t n); ray_t* ray_graph_var_expand_fn(ray_t** args, int64_t n); +/* A LIST whose every element is a BOOL atom as a B8 vector (the list is + * released); any other list is returned as it is: an atomic op over a + * LIST yields a vector when its results are uniform booleans. */ +ray_t* ray_list_collapse_bool(ray_t* list); + /* Convenience wrapper: atomic_map_binary with no DAG opcode */ static inline ray_t* atomic_map_binary(ray_binary_fn fn, ray_t* left, ray_t* right) { return atomic_map_binary_op(fn, 0, left, right); diff --git a/src/lang/parse.c b/src/lang/parse.c index 94c16b0f4..b2b02ec3d 100644 --- a/src/lang/parse.c +++ b/src/lang/parse.c @@ -21,6 +21,7 @@ * SOFTWARE. */ +#include "core/timespan.h" #include "lang/parse.h" #include "lang/nfo.h" #include "lang/env.h" @@ -179,14 +180,17 @@ static const char* try_parse_time(const char* start, int32_t *ms_out) { if (!(c[0] >= '0' && c[0] <= '9' && c[1] >= '0' && c[1] <= '9')) return NULL; int ss = (c[0] - '0') * 10 + (c[1] - '0'); c += 2; - /* .mmm (milliseconds) */ + /* .fff: a decimal fraction of a second, as in a timestamp literal and + * the CSV reader. Fewer than three digits are padded (.5 is 500 ms); + * digits past the third are dropped. */ int ms = 0; if (*c == '.') { c++; if (!(*c >= '0' && *c <= '9')) return NULL; - ms = (*c - '0'); c++; - if (*c >= '0' && *c <= '9') { ms = ms * 10 + (*c - '0'); c++; } - if (*c >= '0' && *c <= '9') { ms = ms * 10 + (*c - '0'); c++; } + int nd = 0; + for (; *c >= '0' && *c <= '9'; c++) + if (nd < 3) { ms = ms * 10 + (*c - '0'); nd++; } + for (; nd < 3; nd++) ms *= 10; } *ms_out = sign * (int32_t)((hh * 3600 + mm * 60 + ss) * 1000 + ms); @@ -199,6 +203,11 @@ static ray_t* parse_number(ray_parser_t *p) { int is_neg = 0; if (*p->pos == '-') { is_neg = 1; p->pos++; } + if (p->pos[0] == '0' && p->pos[1] == 'W' && p->pos[2] == 'n') { + p->pos += 3; + return ray_timespan(is_neg ? -INT64_MAX : INT64_MAX); + } + /* Hex literal: 0x.. */ if (p->pos[0] == '0' && p->pos[1] == 'x') { p->pos += 2; @@ -209,7 +218,7 @@ static ray_t* parse_number(ray_parser_t *p) { return ray_u8((uint8_t)v); } - /* Null literal: 0N{h,i,d,t,p,l,f,s} or bare 0N (defaults to i64 null). */ + /* Null literal: 0N{h,i,d,t,p,l,f,e,g} or bare 0N (defaults to i64 null). */ if (!is_neg && p->pos[0] == '0' && p->pos[1] == 'N') { switch (p->pos[2]) { case 'h': p->pos += 3; return ray_typed_null(-RAY_I16); @@ -217,8 +226,11 @@ static ray_t* parse_number(ray_parser_t *p) { case 'd': p->pos += 3; return ray_typed_null(-RAY_DATE); case 't': p->pos += 3; return ray_typed_null(-RAY_TIME); case 'p': p->pos += 3; return ray_typed_null(-RAY_TIMESTAMP); + case 'n': p->pos += 3; return ray_typed_null(-RAY_TIMESPAN); case 'l': p->pos += 3; return ray_typed_null(-RAY_I64); case 'f': p->pos += 3; return ray_typed_null(-RAY_F64); + case 'e': p->pos += 3; return ray_typed_null(-RAY_F32); + case 'g': p->pos += 3; return ray_typed_null(-RAY_GUID); /* SYM has no typed null and no `0Ns` literal. The empty symbol * (sym 0) is written `'` (parse_symbol below). */ } @@ -236,6 +248,15 @@ static ray_t* parse_number(ray_parser_t *p) { const char *dstart = p->pos; while (*p->pos >= '0' && *p->pos <= '9') p->pos++; int ndigits = (int)(p->pos - dstart); + if (*p->pos == 'D') { + size_t consumed; + int64_t ns; + if (!ray_parse_timespan(start, &consumed, &ns)) + return ray_error("domain", "parse: invalid or out-of-range timespan"); + p->pos = start + consumed; + return ray_timespan(ns); + } + /* Date/Timestamp: YYYY.MM.DD or YYYY.MM.DDDhh:mm:ss.nnnnnnnnn */ if (ndigits == 4 && !is_neg && *p->pos == '.' && @@ -335,19 +356,26 @@ plain_number:; while (*p->pos >= '0' && *p->pos <= '9') p->pos++; } if (*p->pos == 'e' || *p->pos == 'E') { - is_float = 1; - p->pos++; - if (*p->pos == '+' || *p->pos == '-') p->pos++; - while (*p->pos >= '0' && *p->pos <= '9') p->pos++; + /* A trailing lowercase e is the F32 suffix; an exponent must + * have digits (optionally after a sign). */ + const char *exp = p->pos + 1; + if (*exp == '+' || *exp == '-') exp++; + if (*exp >= '0' && *exp <= '9') { + is_float = 1; + p->pos = exp; + while (*p->pos >= '0' && *p->pos <= '9') p->pos++; + } } size_t span = (size_t)(p->pos - start); - if (is_float) { + int is_f32 = (*p->pos == 'e'); + if (is_f32) p->pos++; + if (is_float || is_f32) { double v = 0.0; if (ray_parse_f64(start, span, &v) == 0) return ray_error("parse", NULL); - return ray_f64(v); + return is_f32 ? ray_f32(ray_cast_f64_to_f32_null(v)) : ray_f64(v); } /* Integer parse — overflow signalled by `n == 0` (digits present but @@ -607,7 +635,7 @@ static ray_t* parse_vector(ray_parser_t *p) { return vec; } switch (vec_type) { - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(vec); for (int32_t i = 0; i < count; i++) d[i] = elems[i]->i64; break; @@ -617,6 +645,19 @@ static ray_t* parse_vector(ray_parser_t *p) { for (int32_t i = 0; i < count; i++) d[i] = elems[i]->f64; break; } + case RAY_F32: { + /* F32 atoms keep their value in the f64 slot (ray_f32). */ + float* d = (float*)ray_data(vec); + for (int32_t i = 0; i < count; i++) d[i] = (float)elems[i]->f64; + break; + } + case RAY_GUID: { + /* A GUID atom's 16 bytes live in its obj U8 buffer. */ + uint8_t* d = (uint8_t*)ray_data(vec); + for (int32_t i = 0; i < count; i++) + memcpy(d + (size_t)i * 16, ray_data(elems[i]->obj), 16); + break; + } case RAY_I32: case RAY_DATE: case RAY_TIME: { int32_t* d = (int32_t*)ray_data(vec); for (int32_t i = 0; i < count; i++) d[i] = elems[i]->i32; @@ -810,6 +851,52 @@ static ray_t* parse_dict(ray_parser_t *p) { } /* ── List (s-expression): (fn arg1 arg2 ...) ── */ +/* ── times binding: the [name count] after a `times` head ── + * + * Not a vector literal: the count is an expression, so `[i (count qty)]` + * or `[i 5]` would mix element types, and a bare name in it would read + * as a symbol literal rather than a reference. It parses instead into + * the list (RAY_TIMES_BIND name count), whose head is a symbol no source + * token can spell (it contains a space), so it is told apart from a + * count expression however it was reached (see ray_times_binding). */ +static ray_t* parse_times_binding(ray_parser_t *p) { + int32_t sl = p->line, sc = p->col; + advance(p, 1); /* skip [ */ + ray_t* list = ray_list_new(3); + if (RAY_IS_ERR(list)) return list; + ray_t* marker = ray_sym(ray_sym_intern(RAY_TIMES_BIND, sizeof(RAY_TIMES_BIND) - 1)); + if (RAY_IS_ERR(marker)) { ray_release(list); return marker; } + list = ray_list_append(list, marker); + ray_release(marker); + if (RAY_IS_ERR(list)) return list; + + for (int i = 0; i < 2; i++) { + skip_ws_and_comments(p); + if (*p->pos == ']') { + ray_release(list); + return ray_error("parse", "times: binding must be [name count]"); + } + ray_t* elem = parse_expr(p); + if (RAY_IS_ERR(elem)) { ray_release(list); return elem; } + if (i == 0 && (elem->type != -RAY_SYM || (elem->attrs & ATTR_QUOTED))) { + ray_release(elem); + ray_release(list); + return ray_error("parse", "times: binding must be [name count], with a name first"); + } + list = ray_list_append(list, elem); + ray_release(elem); + if (RAY_IS_ERR(list)) return list; + } + skip_ws_and_comments(p); + if (*p->pos != ']') { + ray_release(list); + return ray_error("parse", "times: binding must be [name count]"); + } + advance(p, 1); /* skip ] */ + nfo_record(p, list, sl, sc); + return list; +} + static ray_t* parse_list(ray_parser_t *p) { advance(p, 1); /* skip ( */ ray_t* list = ray_list_new(4); @@ -817,7 +904,19 @@ static ray_t* parse_list(ray_parser_t *p) { skip_ws_and_comments(p); while (*p->pos && *p->pos != ')') { - ray_t* elem = parse_expr(p); + ray_t* elem; + /* (times [i n] body...): a bracket right after a `times` head is + * the index binding, not a vector literal. */ + if (list->len == 1 && *p->pos == '[') { + ray_t* head = ((ray_t**)ray_data(list))[0]; + if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && + head->i64 == ray_sym_intern("times", 5)) + elem = parse_times_binding(p); + else + elem = parse_expr(p); + } else { + elem = parse_expr(p); + } if (RAY_IS_ERR(elem)) { ray_release(list); return elem; } list = ray_list_append(list, elem); ray_release(elem); diff --git a/src/mem/cow.c b/src/mem/cow.c index a10c88bbf..d5813c47d 100644 --- a/src/mem/cow.c +++ b/src/mem/cow.c @@ -33,11 +33,6 @@ RAY_TLS bool ray_rc_sync = false; * ray_retain * -------------------------------------------------------------------------- */ -#ifdef DEBUG -/* Debug stale-pointer detector — see src/mem/heap.c (issue #240). */ -extern void ray_dfd_check_live(const void* p, const char* who); -#endif - void ray_retain(ray_t* v) { if (!v || RAY_IS_ERR(v)) return; if (v->attrs & RAY_ATTR_ARENA) return; @@ -55,22 +50,7 @@ void ray_retain(ray_t* v) { * -------------------------------------------------------------------------- */ void ray_release(ray_t* v) { - if (!v || RAY_IS_ERR(v)) return; - if (v->attrs & RAY_ATTR_ARENA) return; -#ifdef DEBUG - ray_dfd_check_live(v, "ray_release (stale release of freed block)"); -#endif - uint32_t prev; - if (RAY_LIKELY(!ray_rc_sync)) { - prev = v->rc--; - } else { - prev = ray_atomic_dec(&v->rc); - } - if (prev == 1) { - if (RAY_UNLIKELY(ray_rc_sync)) - ray_atomic_fence_acquire(); - ray_free(v); - } + if (ray_release_last(v)) ray_free_last_ref(v); } /* -------------------------------------------------------------------------- diff --git a/src/mem/cow.h b/src/mem/cow.h index b42643b2c..23f2f3128 100644 --- a/src/mem/cow.h +++ b/src/mem/cow.h @@ -34,10 +34,39 @@ #include #include "core/platform.h" +#include "heap.h" /* Thread-local flag: plain (false) vs atomic (true) refcount ops. * Default is false (fast single-threaded path). * The thread pool sets true before parallel dispatch. */ extern RAY_TLS bool ray_rc_sync; +#ifdef DEBUG +/* Debug stale-pointer detector — see src/mem/heap.c (issue #240). */ +void ray_dfd_check_live(const void* p, const char* who); +#endif + +/* Drop one reference to v. True when that was the last one: the caller + * now owns the block and must free it. ray_release is this plus + * ray_free_last_ref; the free walk in heap.c drops a dying container's + * children through it directly, so it frees them without nesting a + * ray_free per level. */ +RAY_INLINE bool ray_release_last(ray_t* v) { + if (!v || RAY_IS_ERR(v)) return false; + if (v->attrs & RAY_ATTR_ARENA) return false; +#ifdef DEBUG + ray_dfd_check_live(v, "ray_release (stale release of freed block)"); +#endif + uint32_t prev; + if (RAY_LIKELY(!ray_rc_sync)) { + prev = v->rc--; + } else { + prev = ray_atomic_dec(&v->rc); + } + if (prev != 1) return false; + if (RAY_UNLIKELY(ray_rc_sync)) + ray_atomic_fence_acquire(); + return true; +} + #endif /* RAY_COW_H */ diff --git a/src/mem/heap.c b/src/mem/heap.c index 0b20ed13d..d5c0d81bf 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -40,7 +40,9 @@ #include "store/hnsw.h" #include "store/csr.h" #include "store/part.h" +#include "ops/datalog.h" #include "ops/idxop.h" +#include "store/enccol.h" #include #include /* getenv */ #include /* snprintf */ @@ -50,6 +52,9 @@ #include /* O_* modes */ #include #include +#if defined(RAY_OS_LINUX) +#include /* RLIMIT_MEMLOCK — heap_lock */ +#endif /* File-backed spill (a pool or direct block mapped over a preallocated temp * file when the anonymous mapping is refused) is POSIX-only. Windows pools @@ -418,6 +423,237 @@ static bool heap_anon_would_exceed(size_t bytes) { return cur + (int64_t)bytes > wm; } +/* Locking the heap against swap. Anonymous memory the heap maps under the + * watermark — pools, direct blocks, large sys blocks — is locked against + * swap-out (ray_vm_lock: mlock2 MLOCK_ONFAULT, so a page is locked as it is + * faulted in and nothing is faulted in ahead): on a machine with swap and + * the default swappiness the kernel otherwise moves it to swap to make room + * for page cache — the mapped columns a query reads — and the next touch of + * that memory waits for a swap-in, at disk speed, wherever it falls in a + * query. Memory past the watermark, spill files, and a process with no + * known RAM budget are never locked. + * + * The bound: the bytes locked (g_locked, the mappings' sizes — what the + * kernel charges to RLIMIT_MEMLOCK too) stay within the smaller of the + * watermark and half the RAM limit (heap_lock_bound). The watermark alone + * is not enough: it is half the limit on a small machine but three quarters + * of it on a large one, and -m may set it past physical RAM — locked, the + * OOM killer would replace the swap. The bound is checked and taken with + * one atomic add, so threads mapping at once cannot overshoot it together. + * A bound lowered later (ray_heap_set_anon_watermark) is met at the next + * boundary, which unlocks pools until the locked bytes fit (heap_lock_trim). + * + * Dead memory is not kept locked where it would stay: a pool parked at a + * boundary is unlocked, and the direct-block cache's blocks are unlocked by + * (.sys.gc) and the idle decay (heap_unlock_idle); either is locked again + * when it comes back into service — taken from the cache, unparked for an + * allocation, or put back by the decay, a release or a merge + * (heap_relock_pools). A free block in a locked pool stays locked until its + * pages go (pass 5, the decay), which keeps the pool one locked mapping. + * + * Best effort: RLIMIT_MEMLOCK — 8 or 64 MB for a user, as little as 64 KB + * in a container, unlimited for root outside one (CAP_IPC_LOCK) — bounds it + * too, checked here before the system call: a lock refused by the kernel is + * not tried again until the locked bytes fall or the limit changes, since + * each mlock2 takes the mapping lock and walks every mapping of the process. + * What is left unlocked is counted (ray_heap_lock_skipped), refusals too + * (ray_heap_lock_failures). RAY_HEAP_MLOCK=0 turns locking off, read at + * the first lock. The RAM limit is the one read at startup: a cgroup limit + * lowered later is not seen. Linux + * only: plain mlock elsewhere would fault in and wire a whole pool at once. */ +#if defined(RAY_OS_LINUX) +static _Atomic(int64_t) g_locked = 0; +static _Atomic(int64_t) g_lock_failed = 0; +static _Atomic(int64_t) g_lock_skipped = 0; +static _Atomic(int64_t) g_lock_refused_at = -1; /* g_locked at a refusal, -1: none */ +static _Atomic(int64_t) g_lock_refused_lim = -1; /* RLIMIT_MEMLOCK then */ +static _Atomic(int) g_lock_cap = -1; /* CAP_IPC_LOCK: -1 not asked yet */ + +/* The most the heap locks: the smaller of the watermark and half the RAM + * limit; 0 — nothing — where the RAM limit is not known (no runtime), and + * the default watermark with it. */ +/* Whether to lock: RAY_HEAP_MLOCK=0 turns it off, read at the first lock + * rather than per mapping (a worker's, racing .sys.setenv). */ +static _Atomic(int) g_lock_on = -1; +static bool heap_lock_enabled(void) { + int on = atomic_load_explicit(&g_lock_on, memory_order_relaxed); + if (on < 0) { + const char* env = getenv("RAY_HEAP_MLOCK"); + on = (env && env[0] == '0') ? 0 : 1; + int unset = -1; + if (!atomic_compare_exchange_strong_explicit(&g_lock_on, &unset, on, + memory_order_relaxed, + memory_order_relaxed)) + on = unset; + } + return on != 0; +} + +static int64_t heap_lock_bound(void) { + int64_t lim = ray_sys_ram_limit(); + if (lim <= 0) return 0; + int64_t wm = heap_anon_watermark(); + return wm < lim / 2 ? wm : lim / 2; +} + +static void heap_lock_skip(size_t size) { + atomic_fetch_add_explicit(&g_lock_skipped, (int64_t)size, memory_order_relaxed); +} +#endif + +/* Lock anonymous mapping [p, p+size), mapped under the watermark; true if + * it is locked now (the caller keeps that, for heap_unlocked). */ +static bool heap_lock(void* p, size_t size) { +#if defined(RAY_OS_LINUX) + if (!heap_lock_enabled()) return false; + int64_t bound = heap_lock_bound(); + if (bound <= 0) return false; + struct rlimit rl; + int64_t soft = INT64_MAX; + if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && rl.rlim_cur != RLIM_INFINITY) + soft = (int64_t)rl.rlim_cur; + int cap = atomic_load_explicit(&g_lock_cap, memory_order_relaxed); + if (cap < 0) { + cap = ray_os_has_ipc_lock() ? 1 : 0; + atomic_store_explicit(&g_lock_cap, cap, memory_order_relaxed); + } + int64_t cur = atomic_load_explicit(&g_locked, memory_order_relaxed); + int64_t refused = atomic_load_explicit(&g_lock_refused_at, memory_order_relaxed); + if (refused >= 0 && cur >= refused + && atomic_load_explicit(&g_lock_refused_lim, memory_order_relaxed) == soft) { + heap_lock_skip(size); + return false; + } + if (!cap && cur + (int64_t)size > soft) { heap_lock_skip(size); return false; } + if (atomic_fetch_add_explicit(&g_locked, (int64_t)size, memory_order_relaxed) + + (int64_t)size > bound) { + atomic_fetch_sub_explicit(&g_locked, (int64_t)size, memory_order_relaxed); + heap_lock_skip(size); + return false; + } + if (!ray_vm_lock(p, size)) { + int err = errno; + int64_t now = atomic_fetch_sub_explicit(&g_locked, (int64_t)size, + memory_order_relaxed) - (int64_t)size; + atomic_fetch_add_explicit(&g_lock_failed, 1, memory_order_relaxed); + heap_lock_skip(size); + if (err == ENOMEM || err == EPERM || err == EAGAIN || err == ENOSYS) { + atomic_store_explicit(&g_lock_refused_lim, soft, memory_order_relaxed); + atomic_store_explicit(&g_lock_refused_at, err == ENOSYS ? 0 : now, + memory_order_relaxed); + } + return false; + } + return true; +#else + (void)p; (void)size; + return false; +#endif +} + +/* A mapping heap_lock locked is unmapped (munmap unlocks it) or unlocked: + * take it off the books. */ +static void heap_unlocked(size_t size) { +#if defined(RAY_OS_LINUX) + atomic_fetch_sub_explicit(&g_locked, (int64_t)size, memory_order_relaxed); +#else + (void)size; +#endif +} + +/* Unlock a locked mapping that stays mapped. */ +static void heap_unlock(void* p, size_t size) { + ray_vm_unlock(p, size); + heap_unlocked(size); +} + +/* Hand back the pages of free block blk (bsize bytes) of h's pool pidx (-1: + * a pool h does not track). A locked pool's go through + * ray_vm_release_block_locked, the lock kept; where that fails part way — + * the range unlocked, or not released — the pool is unlocked whole, which + * merges its mapping back into one rather than leaving it split, counted, + * and the pages released plainly. */ +static void heap_release_block(ray_heap_t* h, int pidx, ray_t* blk, size_t bsize) { + if (pidx < 0) { /* a pool h does not track: its lock unknown */ + (void)ray_vm_release_block_any(blk, bsize, false); + return; + } + ray_pool_entry_t* pe = &h->pools[pidx]; + bool hp = pe->hugepage != 0; + if (!pe->locked) { ray_vm_release_block(blk, bsize, hp); return; } + int r = ray_vm_release_block_locked(blk, bsize, hp); + if (r == 0) return; +#if defined(RAY_OS_LINUX) + atomic_fetch_add_explicit(&g_lock_failed, 1, memory_order_relaxed); +#endif + heap_unlock(pe->base, BSIZEOF(pe->pool_order)); + pe->locked = 0; + if (r < 0) ray_vm_release_block(blk, bsize, hp); +} + +static void direct_cache_unlock_all(void); + +/* A bound lowered under what is locked (a watermark set lower, by -m or an + * embedding): unlock h's pools, the last mapped first, until the locked + * bytes fit again. Called at the boundary and by the idle decay. */ +static void heap_lock_trim(ray_heap_t* h) { +#if defined(RAY_OS_LINUX) + /* No known RAM budget: nothing is bound, so nothing is over it (bytes a + * gone runtime's leaked heap left locked are not). */ + if (ray_sys_ram_limit() <= 0) return; + int64_t bound = heap_lock_bound(); + if (atomic_load_explicit(&g_locked, memory_order_relaxed) <= bound) return; + /* The cache's blocks first: dead memory. What live direct and sys + * blocks hold stays locked until they are freed — the heap keeps no list + * of them to unlock. */ + direct_cache_unlock_all(); + for (uint32_t p = h->pool_count; p-- > 0; ) { + if (atomic_load_explicit(&g_locked, memory_order_relaxed) <= bound) return; + ray_pool_entry_t* pe = &h->pools[p]; + if (!pe->locked) continue; + heap_unlock(pe->base, BSIZEOF(pe->pool_order)); + pe->locked = 0; + } +#else + (void)h; +#endif +} + +bool ray_heap_set_lock(bool on) { +#if defined(RAY_OS_LINUX) + bool was = heap_lock_enabled(); + atomic_store_explicit(&g_lock_on, on ? 1 : 0, memory_order_relaxed); + return was; +#else + (void)on; + return false; +#endif +} + +int64_t ray_heap_locked_bytes(void) { +#if defined(RAY_OS_LINUX) + return atomic_load_explicit(&g_locked, memory_order_relaxed); +#else + return 0; +#endif +} + +int64_t ray_heap_lock_failures(void) { +#if defined(RAY_OS_LINUX) + return atomic_load_explicit(&g_lock_failed, memory_order_relaxed); +#else + return 0; +#endif +} + +int64_t ray_heap_lock_skipped(void) { +#if defined(RAY_OS_LINUX) + return atomic_load_explicit(&g_lock_skipped, memory_order_relaxed); +#else + return 0; +#endif +} + /* A boundary far from the watermark visits the heaps for the spill pools * alone (ray_heap_relieve) — to park the empty ones, discard their pages and * age them — so at most this often: a stream of small statements (a @@ -446,6 +682,34 @@ void ray_heap_set_anon_watermark(int64_t bytes) { atomic_store_explicit(&g_far_visit_ms, INT64_MIN / 2, memory_order_relaxed); } +static size_t direct_cache_bytes_now(void); + +/* Committed anonymous bytes the calling thread can allocate again without + * committing more: the free blocks on its heap's freelists that lie in + * anonymous pools (a spill pool's are not RAM), and the blocks the direct + * cache holds, which it gives up under watermark pressure. Walks the + * freelists: for a planner sizing a working set, not for hot paths. */ +int64_t ray_heap_anon_reusable(void) { + int64_t bytes = (int64_t)direct_cache_bytes_now(); + ray_heap_t* h = ray_tl_heap; + if (!h) return bytes; + bool backed = false; + for (uint32_t i = 0; i < h->pool_count; i++) + if (h->pools[i].backed) { backed = true; break; } + for (int ord = RAY_ORDER_MIN; ord <= RAY_HEAP_MAX_ORDER; ord++) { + if (!(h->avail & (1ULL << ord))) continue; + ray_fl_head_t* fh = &h->freelist[ord]; + for (ray_t* blk = fh->fl_next; blk != (ray_t*)fh; blk = blk->fl_next) { + if (backed) { + int pi = heap_find_pool(h, blk); + if (pi < 0 || h->pools[pi].backed) continue; + } + bytes += (int64_t)BSIZEOF(ord); + } + } + return bytes; +} + ray_heap_t* ray_heap_registry[RAY_HEAP_REGISTRY_SIZE]; /* Serializes registry slot writes (register / unregister) and the @@ -530,7 +794,7 @@ uint8_t ray_order_for_size(size_t data_size) { * -------------------------------------------------------------------------- */ static bool heap_add_pool(ray_heap_t* h, uint8_t order); -static bool heap_unpark(ray_heap_t* h, bool spill); +static bool heap_unpark(ray_heap_t* h, bool spill, bool relock); static void heap_unpark_all(ray_heap_t* h); static bool heap_make_room(size_t bytes); static int64_t heap_decay_threshold_ms(void); @@ -813,6 +1077,8 @@ static bool heap_add_pool(ray_heap_t* h, uint8_t order) { .swap_fd = swap_fd, .swap_path = swap_path, /* NULL when not backed */ }; + if (swap_fd < 0 && !over) /* under the watermark: locked against swap-out */ + h->pools[h->pool_count].locked = heap_lock(mem, pool_size) ? 1 : 0; h->pool_count++; if (swap_fd < 0) /* anonymous pool: counts toward the RAM watermark */ @@ -919,7 +1185,10 @@ static bool ray_atom_owns_obj(const ray_t* v) { return false; } -static void ray_release_owned_refs(ray_t* v) { +/* Forced inline: ray_free_node has two inlined copies (the per-node free + * and the free walk's leaf child), and a leaf free must not pay a call + * here to learn it owns nothing. */ +RAY_INLINE void ray_release_owned_refs(ray_t* v) { if (!v || RAY_IS_ERR(v)) return; if (ray_is_atom(v)) { @@ -944,6 +1213,10 @@ static void ray_release_owned_refs(ray_t* v) { ray_graph_free(g); RAY_LAZY_GRAPH(v) = NULL; } + if (v->attrs & RAY_LAZY_COLREF) { /* a column reference holds its table */ + ray_t** tp = (ray_t**)ray_data(v); + if (*tp) { ray_release(*tp); *tp = NULL; } + } return; } /* I64 atom tagged as an HNSW handle owns a ray_hnsw_t — free it @@ -966,6 +1239,15 @@ static void ray_release_owned_refs(ray_t* v) { v->attrs &= (uint8_t)~RAY_ATTR_GRAPH; return; } + /* I64 atom tagged as a Datalog program owns the program block. The + * explicit dl-free path clears the tag and pointer after early + * release, so scope cleanup does not free the program a second time. */ + if (v->type == -RAY_I64 && (v->attrs & RAY_ATTR_DLPROG)) { + dl_program_free((dl_program_t*)(uintptr_t)v->i64); + v->i64 = 0; + v->attrs &= (uint8_t)~RAY_ATTR_DLPROG; + return; + } if (ray_atom_owns_obj(v) && v->obj && !RAY_IS_ERR(v->obj)) ray_release(v->obj); return; @@ -987,6 +1269,11 @@ static void ray_release_owned_refs(ray_t* v) { return; } + if (v->type == RAY_ENCCOL) { + ray_enccol_payload_release(v); + return; + } + /* Vector with attached index: aux[0..7] holds an owning ref to the * index ray_t. Bytes 8-15 are NOT displaced into the index for a * STR or SYM parent — attach_finalize leaves the pool or domain @@ -1043,7 +1330,7 @@ static void ray_release_owned_refs(ray_t* v) { if (v->type == RAY_TABLE || v->type == RAY_DICT) { ray_t** slots = (ray_t**)ray_data(v); if (slots[0] && !RAY_IS_ERR(slots[0])) ray_release(slots[0]); - if (slots[1] && !RAY_IS_ERR(slots[1])) ray_release(slots[1]); + if (slots[1] && !RAY_IS_ERR(slots[1])) ray_release(slots[1]); /* plain-table */ return; } @@ -1072,8 +1359,15 @@ bool ray_retain_owned_refs(ray_t* v) { if (LAMBDA_CAPROWS(v)) ray_retain(LAMBDA_CAPROWS(v)); return true; } - /* Lazy handles own their graph uniquely — no retain on copy */ - if (v->type == RAY_LAZY) return true; + /* Lazy handles own their graph uniquely — no retain on copy; a + * column reference shares its table */ + if (v->type == RAY_LAZY) { + if (v->attrs & RAY_LAZY_COLREF) { + ray_t* t = *(ray_t**)ray_data(v); + if (t) ray_retain(t); + } + return true; + } /* HNSW handle owns its ray_hnsw_t uniquely. Deep-clone the index * so the copy is an independent owner with the same semantics as * the source. On clone-OOM, detach the copy (so caller can free @@ -1103,6 +1397,13 @@ bool ray_retain_owned_refs(ray_t* v) { v->attrs &= (uint8_t)~RAY_ATTR_GRAPH; return true; } + /* Datalog program handles follow the graph handle policy: the + * shallow block copy is not a second owner, so detach its pointer. */ + if (v->type == -RAY_I64 && (v->attrs & RAY_ATTR_DLPROG)) { + v->i64 = 0; + v->attrs &= (uint8_t)~RAY_ATTR_DLPROG; + return true; + } if (ray_atom_owns_obj(v) && v->obj && !RAY_IS_ERR(v->obj)) ray_retain(v->obj); return true; @@ -1121,6 +1422,11 @@ bool ray_retain_owned_refs(ray_t* v) { return true; } + if (v->type == RAY_ENCCOL) { + ray_enccol_payload_retain(v); + return true; + } + if (v->attrs & RAY_ATTR_HAS_INDEX) { /* Mirror ray_release_owned_refs: a mmap-resident passenger index * (mmod==1) is owned by the column's mapping, not refcounted here, @@ -1163,7 +1469,7 @@ bool ray_retain_owned_refs(ray_t* v) { if (v->type == RAY_TABLE || v->type == RAY_DICT) { ray_t** slots = (ray_t**)ray_data(v); if (slots[0] && !RAY_IS_ERR(slots[0])) ray_retain(slots[0]); - if (slots[1] && !RAY_IS_ERR(slots[1])) ray_retain(slots[1]); + if (slots[1] && !RAY_IS_ERR(slots[1])) ray_retain(slots[1]); /* plain-table */ return true; } @@ -1194,6 +1500,7 @@ static void ray_detach_owned_refs(ray_t* v) { if (v->type == RAY_LAZY) { RAY_LAZY_GRAPH(v) = NULL; RAY_LAZY_OP(v) = NULL; + if (v->attrs & RAY_LAZY_COLREF) *(ray_t**)ray_data(v) = NULL; return; } /* HNSW handle: ownership has been transferred elsewhere; stop the @@ -1210,6 +1517,13 @@ static void ray_detach_owned_refs(ray_t* v) { v->attrs &= (uint8_t)~RAY_ATTR_GRAPH; return; } + /* Datalog program ownership moved with the memcpy; keep the old + * block's finalizer from freeing the program now owned by new_v. */ + if (v->type == -RAY_I64 && (v->attrs & RAY_ATTR_DLPROG)) { + v->i64 = 0; + v->attrs &= (uint8_t)~RAY_ATTR_DLPROG; + return; + } if (ray_atom_owns_obj(v)) v->obj = NULL; return; } @@ -1237,6 +1551,11 @@ static void ray_detach_owned_refs(ray_t* v) { return; } + if (v->type == RAY_ENCCOL) { + ray_enccol_payload_detach(v); + return; + } + if (v->attrs & RAY_ATTR_HAS_INDEX) { v->index = NULL; v->_idx_pad = NULL; @@ -1275,7 +1594,7 @@ static void ray_detach_owned_refs(ray_t* v) { if (v->type == RAY_TABLE || v->type == RAY_DICT) { ray_t** slots = (ray_t**)ray_data(v); slots[0] = NULL; - slots[1] = NULL; + slots[1] = NULL; /* plain-table */ v->len = 0; return; } @@ -1369,6 +1688,7 @@ typedef struct ray_direct_cache_node { struct ray_direct_cache_node* next; struct ray_direct_cache_node* prev; size_t map_size; + int locked; /* the block is locked against swap-out (heap_lock) */ } ray_direct_cache_node_t; _Static_assert(sizeof(ray_direct_cache_node_t) <= RAY_DIRECT_HDR, "cached links must fit in the dead direct-allocation prefix"); @@ -1399,6 +1719,13 @@ static size_t direct_cache_budget(void) { return b; } +static size_t direct_cache_bytes_now(void) { + direct_cache_lock(); + size_t b = g_direct_cache_bytes; + direct_cache_unlock(); + return b; +} + /* Caller holds the lock. Ownership transfers from the cache to the caller. */ static void direct_cache_unlink(ray_direct_cache_node_t* node) { if (node->prev) node->prev->next = node->next; @@ -1413,6 +1740,7 @@ static void direct_cache_release(ray_direct_cache_node_t* node) { while (node) { ray_direct_cache_node_t* next = node->next; size_t bytes = node->map_size; + if (node->locked) heap_unlocked(bytes); atomic_fetch_sub_explicit(&g_anon_committed, (int64_t)bytes, memory_order_relaxed); ray_vm_free(node, bytes); node = next; @@ -1421,7 +1749,7 @@ static void direct_cache_release(ray_direct_cache_node_t* node) { /* Best fitting cached block within the existing waste bound. Exact matches * stop the search; similar-sized analytical scratch is the common case. */ -static void* direct_cache_take(size_t need, size_t* out_size) { +static void* direct_cache_take(size_t need, size_t* out_size, bool* out_locked) { direct_cache_lock(); size_t slack = need / 4; if (slack < (2u << 20)) slack = (2u << 20); @@ -1435,6 +1763,7 @@ static void* direct_cache_take(size_t need, size_t* out_size) { } if (best) { *out_size = best->map_size; + *out_locked = best->locked != 0; direct_cache_unlink(best); } direct_cache_unlock(); @@ -1443,7 +1772,7 @@ static void* direct_cache_take(size_t need, size_t* out_size) { /* Recently freed blocks replace the oldest cached blocks within the unchanged * byte budget. The caller has already removed this block from live statistics. */ -static bool direct_cache_put(void* base, size_t map_size) { +static bool direct_cache_put(void* base, size_t map_size, bool locked) { size_t budget = direct_cache_budget(); if (map_size > budget) return false; ray_direct_cache_node_t* evicted = NULL; @@ -1456,6 +1785,7 @@ static bool direct_cache_put(void* base, size_t map_size) { } ray_direct_cache_node_t* node = base; node->map_size = map_size; + node->locked = locked; node->next = NULL; node->prev = g_direct_cache_tail; if (g_direct_cache_tail) g_direct_cache_tail->next = node; @@ -1482,6 +1812,49 @@ void ray_heap_direct_cache_drain(void) { direct_cache_drain(); } +static void direct_cache_unlock_all(void); + +void ray_heap_unlock_idle(void) { + direct_cache_unlock_all(); +} + +/* Unlock the blocks the direct-block cache keeps: dead memory, kept for its + * pages rather than its lock. They stay cached. Detached under the lock, + * unlocked outside it — an munlock can take milliseconds, as an munmap — and + * put back as the oldest; whatever that leaves past the budget (blocks put + * meanwhile) is evicted as a put would. */ +static void direct_cache_unlock_all(void) { + direct_cache_lock(); + ray_direct_cache_node_t* head = g_direct_cache_head; + ray_direct_cache_node_t* tail = g_direct_cache_tail; + size_t bytes = g_direct_cache_bytes; + g_direct_cache_head = g_direct_cache_tail = NULL; + g_direct_cache_bytes = 0; + direct_cache_unlock(); + if (!head) return; + for (ray_direct_cache_node_t* node = head; node; node = node->next) + if (node->locked) { + heap_unlock(node, node->map_size); + node->locked = 0; + } + size_t budget = direct_cache_budget(); + ray_direct_cache_node_t* evicted = NULL; + direct_cache_lock(); + tail->next = g_direct_cache_head; + if (g_direct_cache_head) g_direct_cache_head->prev = tail; + else g_direct_cache_tail = tail; + g_direct_cache_head = head; + g_direct_cache_bytes += bytes; + while (g_direct_cache_bytes > budget && g_direct_cache_head) { + ray_direct_cache_node_t* old = g_direct_cache_head; + direct_cache_unlink(old); + old->next = evicted; + evicted = old; + } + direct_cache_unlock(); + direct_cache_release(evicted); +} + /* Bytes a drain would hand back now. */ static int64_t direct_cache_bytes(void) { direct_cache_lock(); @@ -1504,9 +1877,13 @@ static ray_t* heap_alloc_direct(ray_heap_t* h, size_t data_size) { * pages — no mmap, no watermark commit (the block never left the * committed totals while cached), no kernel page-zeroing on fault. */ size_t cached_size = 0; - base = direct_cache_take(map_size, &cached_size); + bool locked = false; + base = direct_cache_take(map_size, &cached_size, &locked); if (base) { map_size = cached_size; + /* Unlocked while cached (ray_heap_unlock_idle): back in service it + * is locked again, under the watermark and within the bound. */ + if (!locked && !heap_anon_would_exceed(0)) locked = heap_lock(base, map_size); } else { /* If keeping this in anonymous RAM would push our footprint past the * watermark (default: physical RAM), back it with a disk file from the @@ -1527,6 +1904,8 @@ static ray_t* heap_alloc_direct(ray_heap_t* h, size_t data_size) { if (!base && force_file) base = ray_vm_alloc(map_size); if (!base) return NULL; } + if (swap_fd < 0 && !force_file) /* under the watermark */ + locked = heap_lock(base, map_size); if (swap_fd < 0) /* anonymous: counts toward the RAM watermark */ heap_anon_commit((int64_t)map_size, true, true); if (force_file || swap_fd >= 0) @@ -1536,6 +1915,7 @@ static ray_t* heap_alloc_direct(ray_heap_t* h, size_t data_size) { ray_direct_hdr_t* hdr = (ray_direct_hdr_t*)base; hdr->map_size = map_size; hdr->swap_fd = swap_fd; + hdr->locked = locked; hdr->swap_path = swap_path; ray_t* v = (ray_t*)((char*)base + RAY_DIRECT_HDR); @@ -1627,7 +2007,7 @@ ray_t* ray_alloc(size_t data_size) { /* Then a pool the heap parked (heap_park_empty_pools), an * anonymous one first. */ if (candidates == 0 && h->parked - && (heap_unpark(h, false) || heap_unpark(h, true))) + && (heap_unpark(h, false, true) || heap_unpark(h, true, true))) candidates = h->avail & (UINT64_MAX << order); if (candidates == 0) { if (!heap_add_pool(h, order)) return NULL; @@ -1747,98 +2127,13 @@ void ray_file_map_release(ray_file_map_t* m) { ray_sys_free(m); } -void ray_free(ray_t* v) { - if (!v || RAY_IS_ERR(v)) return; - if (v->attrs & RAY_ATTR_ARENA) return; /* arena-owned, bulk-freed */ -#ifdef DEBUG - if (dfd_contains(v)) dfd_report("ray_free (double free)", v); -#endif - - /* Guard: keep rc=1 while releasing children so buddy coalescing - * won't merge this block prematurely (it checks buddy_rc==0). */ - ray_atomic_store(&v->rc, 1); - - /* A mapped block owning a shared region takes its descriptor now: aux - * lives inside the region it describes. */ - ray_file_map_t* owned_map = (v->mmod == 3) ? v->file_map : NULL; - - /* A mapped string column reaches its own reference through its pool, - * which is the cheap path and needs no lock — but only while that - * pointer still leads to the mapped pool. Read it before the children - * go, since releasing the pool may be what drops it. */ - ray_file_map_t* col_map = NULL; - if (v->mmod == 1 && v->type == RAY_STR && - v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->mmod == 3) - col_map = v->str_pool->file_map; - - ray_release_owned_refs(v); - +/* Return the block of a dying v to wherever it came from, once its owned + * references are gone. The tail of the per-node free below, and all the + * free walk needs: the walk only takes heap blocks (mmod 0), for which the + * mapped-block arms of ray_free_node have nothing to do. */ +RAY_INLINE void ray_free_block(ray_t* v) { ray_heap_t* h = ray_tl_heap; - if (owned_map) { - ray_file_map_release(owned_map); - if (h) RAY_STAT(h->stats.free_count++); - return; - } - - /* File-mapped: munmap */ - if (v->mmod == 1) { - if (v->type == RAY_TABLE || v->type == RAY_DICT || v->type == RAY_LIST) return; - /* A column mapped by the store registered its region and holds one - * of its references. Looking that up by address rather than through - * str_pool is the point: a mutated column's pool pointer no longer - * leads anywhere useful, while its address is what the region was - * registered under. The descriptor also carries the true mapped - * length, so nothing has to re-derive it from a header that the - * children release may already have taken away. */ - /* col_map is the answer whenever the pool pointer still led to the - * region, which is every column that was not mutated. Only one - * that had its pool swapped — str_pool_cow deep-copies a mapped - * pool before appending — has to ask the registry, and only a - * string column was ever registered. So the lock stays off the - * ordinary free entirely, and a mutated column pays it once. */ - /* A column loaded with an inline index registered its region too - * (col.c): the index may have been detached since, and only the - * descriptor still knows the mapped length. */ - ray_file_map_t* m = col_map; - if (!m) m = ray_file_map_lookup(v); - if (m) { - ray_file_map_release(m); - if (h) RAY_STAT(h->stats.free_count++); - return; - } - if (v->type > 0 && v->type < RAY_TYPE_COUNT) { - uint8_t esz = ray_sym_elem_size(v->type, v->attrs); - size_t data_size = 32 + (size_t)v->len * esz; - if (v->type == RAY_STR) { - size_t pool_len = 0; - if (v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->len > 0) - pool_len = (size_t)v->str_pool->len; - data_size += 32 + pool_len; - } - /* Inline index region: a mmap-resident (passenger) index extends the - * mapping past the payload by its 32-aligned inline region. Derive - * that size from the index itself (ray_index_inline_size) rather than - * stashing it in aux — str_pool occupies _idx_pad on STR columns, and - * the payload size above already accounts for descriptors + pool. - * Heap-resident indexes (RAY_MARK_MMAP clear) keep the payload-only - * formula. */ - if ((v->attrs & RAY_ATTR_HAS_INDEX) && v->index && !RAY_IS_ERR(v->index)) { - ray_index_t* ix = ray_index_payload(v->index); - if (ix->markers & RAY_MARK_MMAP) { - int64_t region_off = ((int64_t)data_size + 31) & ~(int64_t)31; - data_size = (size_t)(region_off + ray_index_inline_size(ix)); - } - } - size_t mapped_size = (data_size + 4095) & ~(size_t)4095; - ray_vm_unmap_file(v, mapped_size); - } else { - ray_vm_unmap_file(v, 4096); - } - if (h) RAY_STAT(h->stats.free_count++); - return; - } - /* Legacy mmod==2 guard */ if (v->mmod == 2) return; @@ -1850,6 +2145,7 @@ void ray_free(ray_t* v) { ray_direct_hdr_t* hdr = (ray_direct_hdr_t*)base; size_t map_size = hdr->map_size; int swap_fd = hdr->swap_fd; + bool locked = hdr->locked != 0; char* swap_path = hdr->swap_path; mem_trace_note_free(map_size); if (h) RAY_STAT(h->stats.free_count++); @@ -1867,12 +2163,13 @@ void ray_free(ray_t* v) { #else (void)swap_fd; (void)swap_path; #endif - if (direct_cache_put(base, map_size)) { + if (direct_cache_put(base, map_size, locked)) { /* Stashed for reuse: pages stay resident, so the block keeps * its committed-RAM and watermark accounting; only the live * stats above dropped. Eviction (direct_cache_drain) performs * the deferred un-commit + munmap. */ } else { + if (locked) heap_unlocked(map_size); atomic_fetch_sub_explicit(&g_anon_committed, (int64_t)map_size, memory_order_relaxed); ray_vm_free(base, map_size); /* munmap + committed-RAM counter -= */ @@ -1971,6 +2268,217 @@ void ray_free(ray_t* v) { RAY_STAT(h->stats.free_count++); } +/* The one-node free: v's owned references through ray_release_owned_refs, + * then its block. Everything except the containers ray_free_walks accepts + * comes through here. */ +RAY_INLINE void ray_free_node(ray_t* v) { +#ifdef DEBUG + if (dfd_contains(v)) dfd_report("ray_free (double free)", v); +#endif + + /* Guard: keep rc=1 while releasing children so buddy coalescing + * won't merge this block prematurely (it checks buddy_rc==0). */ + ray_atomic_store(&v->rc, 1); + + /* A mapped block owning a shared region takes its descriptor now: aux + * lives inside the region it describes. */ + ray_file_map_t* owned_map = (v->mmod == 3) ? v->file_map : NULL; + + /* A mapped string column reaches its own reference through its pool, + * which is the cheap path and needs no lock — but only while that + * pointer still leads to the mapped pool. Read it before the children + * go, since releasing the pool may be what drops it. */ + ray_file_map_t* col_map = NULL; + if (v->mmod == 1 && v->type == RAY_STR && + v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->mmod == 3) + col_map = v->str_pool->file_map; + + ray_release_owned_refs(v); + + ray_heap_t* h = ray_tl_heap; + + if (owned_map) { + ray_file_map_release(owned_map); + if (h) RAY_STAT(h->stats.free_count++); + return; + } + + /* File-mapped: munmap */ + if (v->mmod == 1) { + if (v->type == RAY_TABLE || v->type == RAY_DICT || v->type == RAY_LIST) return; + /* A column mapped by the store registered its region and holds one + * of its references. Looking that up by address rather than through + * str_pool is the point: a mutated column's pool pointer no longer + * leads anywhere useful, while its address is what the region was + * registered under. The descriptor also carries the true mapped + * length, so nothing has to re-derive it from a header that the + * children release may already have taken away. */ + /* col_map is the answer whenever the pool pointer still led to the + * region, which is every column that was not mutated. Only one + * that had its pool swapped — str_pool_cow deep-copies a mapped + * pool before appending — has to ask the registry, and only a + * string column was ever registered. So the lock stays off the + * ordinary free entirely, and a mutated column pays it once. */ + /* A column loaded with an inline index registered its region too + * (col.c): the index may have been detached since, and only the + * descriptor still knows the mapped length. */ + ray_file_map_t* m = col_map; + if (!m) m = ray_file_map_lookup(v); + if (m) { + ray_file_map_release(m); + if (h) RAY_STAT(h->stats.free_count++); + return; + } + if (v->type > 0 && v->type < RAY_TYPE_COUNT) { + uint8_t esz = ray_sym_elem_size(v->type, v->attrs); + size_t data_size = 32 + (size_t)v->len * esz; + if (v->type == RAY_STR) { + size_t pool_len = 0; + if (v->str_pool && !RAY_IS_ERR(v->str_pool) && v->str_pool->len > 0) + pool_len = (size_t)v->str_pool->len; + data_size += 32 + pool_len; + } + /* Inline index region: a mmap-resident (passenger) index extends the + * mapping past the payload by its 32-aligned inline region. Derive + * that size from the index itself (ray_index_inline_size) rather than + * stashing it in aux — str_pool occupies _idx_pad on STR columns, and + * the payload size above already accounts for descriptors + pool. + * Heap-resident indexes (RAY_MARK_MMAP clear) keep the payload-only + * formula. */ + if ((v->attrs & RAY_ATTR_HAS_INDEX) && v->index && !RAY_IS_ERR(v->index)) { + ray_index_t* ix = ray_index_payload(v->index); + if (ix->markers & RAY_MARK_MMAP) { + int64_t region_off = ((int64_t)data_size + 31) & ~(int64_t)31; + data_size = (size_t)(region_off + ray_index_inline_size(ix)); + } + } + size_t mapped_size = (data_size + 4095) & ~(size_t)4095; + ray_vm_unmap_file(v, mapped_size); + } else { + ray_vm_unmap_file(v, 4096); + } + if (h) RAY_STAT(h->stats.free_count++); + return; + } + + ray_free_block(v); +} + +/* -------------------------------------------------------------------------- + * The free walk: nested containers without C recursion + * + * Releasing a container drops each child through ray_release, and a child + * whose count reaches zero is freed through ray_free, which drops ITS + * children — one ray_free / ray_release_owned_refs / ray_release chain of + * C frames per level of nesting. A parse tree a few thousand levels deep + * (a nested fn literal built for eval) overflowed an 8 MB stack under + * ASan, and a list nested a million deep overflows it in any build. + * + * The kinds that nest without bound — lists, dicts, tables and lambdas — + * are freed by one loop instead. A dying container is its own stack frame: + * to descend into a child the walk parks the parent, writing into the + * parent's aux bytes the container to resume after it (slice_parent) and + * the next slot to release (slice_offset). Nothing reads those bytes + * again: the parent's count has reached zero so no one else holds it, its + * rc stays 1 so a buddy free does not coalesce it, and freeing a heap block + * (ray_free_block) reads its order and pool, or a direct block's header, + * never its aux. The walk takes no memory and no stack beyond its own + * frame, whatever the depth — nothing to run out of inside a free. + * + * The order is the recursive one: children in slot order, each subtree + * freed whole before the next sibling, a container's block after all of + * its children. Every other kind is still freed per node; a container it + * owns (a slice's parent, say) starts a walk of its own, so C frames grow + * only where the nesting alternates through such a kind, never along a + * chain of containers. + * -------------------------------------------------------------------------- */ + +/* The containers the walk frees. Heap blocks only: a mapped or borrowed + * one keeps the per-node path and its mmod arms. A slice owns just its + * parent, and an index bit sends ray_release_owned_refs down its own arm + * first, so both stay per-node too. */ +RAY_INLINE bool ray_free_walks(const ray_t* v) { + if (v->type == RAY_LAMBDA) return v->mmod == 0; + if (v->type != RAY_LIST && v->type != RAY_DICT && v->type != RAY_TABLE) + return false; + return v->mmod == 0 && !(v->attrs & (RAY_ATTR_SLICE | RAY_ATTR_HAS_INDEX)); +} + +/* How many leading data slots of a walked container are owned references: + * the ones ray_release_owned_refs drops for its kind. */ +_Static_assert(LAMBDA_SLOT_CAPQ == LAMBDA_SLOTS - 1 && + LAMBDA_SLOT_CAPROWS == LAMBDA_SLOT_CAPQ - 1 && + LAMBDA_SLOT_NLOCALS < LAMBDA_SLOT_CAPROWS, + "the free walk drops lambda slots 0..CAPROWS except NLOCALS, " + "the references ray_release_owned_refs drops"); + +RAY_INLINE int64_t ray_free_walk_width(const ray_t* v) { + if (v->type == RAY_LIST) return v->len; + if (v->type == RAY_LAMBDA) return LAMBDA_SLOT_CAPROWS + 1; /* NLOCALS cleared */ + return 2; /* dict / table: keys, values */ +} + +/* Claim v for the walk, as ray_free_node claims a block. */ +RAY_INLINE void ray_free_walk_enter(ray_t* v) { +#ifdef DEBUG + if (dfd_contains(v)) dfd_report("ray_free (double free)", v); +#endif + /* rc=1 while the children go, so buddy coalescing skips the block. */ + ray_atomic_store(&v->rc, 1); + /* A lambda's n_locals slot is not a reference. The lambda is dying, + * so clear it and let the loop take slots 0..CAPROWS as one run. */ + if (v->type == RAY_LAMBDA) ((ray_t**)ray_data(v))[LAMBDA_SLOT_NLOCALS] = NULL; +} + +static void ray_free_walk(ray_t* v) { + ray_t* up = NULL; /* parked container to resume once v is done */ + int64_t i = 0; /* v's next slot to release */ + ray_free_walk_enter(v); + for (;;) { + ray_t** slots = (ray_t**)ray_data(v); + int64_t n = ray_free_walk_width(v); + ray_t* down = NULL; + while (i < n) { + ray_t* c = slots[i++]; + if (!ray_release_last(c)) continue; + if (!ray_free_walks(c)) { ray_free_node(c); continue; } + /* A container with no slots has nothing to park the walk for. */ + if (ray_free_walk_width(c) == 0) { + ray_free_walk_enter(c); + ray_free_block(c); + continue; + } + down = c; + break; + } + if (down) { + v->slice_parent = up; + v->slice_offset = i; + up = v; + v = down; + i = 0; + ray_free_walk_enter(v); + continue; + } + ray_free_block(v); + if (!up) return; + v = up; + up = v->slice_parent; + i = v->slice_offset; + } +} + +void ray_free_last_ref(ray_t* v) { + if (ray_free_walks(v)) ray_free_walk(v); + else ray_free_node(v); +} + +void ray_free(ray_t* v) { + if (!v || RAY_IS_ERR(v)) return; + if (v->attrs & RAY_ATTR_ARENA) return; /* arena-owned, bulk-freed */ + ray_free_last_ref(v); +} + /* -------------------------------------------------------------------------- * Raw buffer allocator: malloc/calloc/realloc/free for plain byte buffers that * are NOT ray_t values, backed by the buddy heap (no libc malloc). The block @@ -2060,6 +2568,8 @@ ray_t* ray_alloc_copy(ray_t* v) { if (v->type == RAY_MAPCOMMON) n_ptrs = 2; if (n_ptrs < 0) return ray_error("oom", NULL); data_size = (size_t)n_ptrs * sizeof(ray_t*); + } else if (v->type == RAY_ENCCOL) { + data_size = sizeof(void*); /* the payload pointer; payload is refcounted */ } else if (v->type == RAY_LIST) { /* RAY_LIST has type==0, which the generic branch below (t <= 0) * would route to data_size=0, silently producing a header-only copy @@ -2259,13 +2769,15 @@ static void* heap_sys_map_file(size_t size) { } #endif -void* ray_heap_sys_map(size_t size, bool* spilled) { +void* ray_heap_sys_map(size_t size, bool* spilled, bool* locked) { *spilled = false; + *locked = false; void* p = NULL; bool big = size >= RAY_SYS_SPILL_MIN; /* could spill, so ray_heap_relieve counts it */ #if RAY_HEAP_FILE_SPILL bool to_file = big && heap_anon_would_exceed(size) && heap_make_room(size); if (!to_file) p = ray_vm_alloc(size); + if (p && big) *locked = heap_lock(p, size); /* under the watermark: to_file is false */ if (!p && big) { p = heap_sys_map_file(size); if (p) { *spilled = true; heap_anon_spilled(); return p; } @@ -2283,8 +2795,9 @@ void* ray_heap_sys_map(size_t size, bool* spilled) { return p; } -void ray_heap_sys_unmap(void* p, size_t size, bool spilled) { +void ray_heap_sys_unmap(void* p, size_t size, bool spilled, bool locked) { if (!p) return; + if (locked) heap_unlocked(size); #if RAY_HEAP_FILE_SPILL if (spilled) { munmap(p, size); @@ -2463,6 +2976,7 @@ void ray_heap_destroy(void) { ray_pool_hdr_t* hdr = (ray_pool_hdr_t*)h->pools[i].base; dfd_purge_range((uintptr_t)h->pools[i].base, (uintptr_t)h->pools[i].base + BSIZEOF(h->pools[i].pool_order)); + if (h->pools[i].locked) heap_unlocked(BSIZEOF(h->pools[i].pool_order)); ray_vm_free(hdr->vm_base, BSIZEOF(h->pools[i].pool_order)); if (h->pools[i].backed) { atomic_fetch_sub_explicit(&g_spill_pools, 1, memory_order_relaxed); @@ -2661,6 +3175,7 @@ static int64_t heap_pool_unmap(ray_heap_t* h, uint32_t p) { if (pe->parked) h->parked--; dfd_purge_range(pb, pb + BSIZEOF(po)); + if (pe->locked) heap_unlocked(BSIZEOF(po)); ray_vm_free(((ray_pool_hdr_t*)pb)->vm_base, BSIZEOF(po)); /* File-backed pools also need their fd closed and tempfile * unlinked, mirroring the heap_destroy path. Unmapping drops the @@ -2733,12 +3248,21 @@ static void heap_park_empty_pools(ray_heap_t* h, unsigned mode, uint32_t now) { h->pools[p].parked = 1; ((ray_pool_hdr_t*)h->pools[p].base)->parked_ms = now; h->parked++; + /* An empty pool is dead memory: kept for its pages, not its lock + * (heap_lock). Taken back, it is locked again (heap_unpark). */ + if (h->pools[p].locked) { + heap_unlock(h->pools[p].base, BSIZEOF(h->pools[p].pool_order)); + h->pools[p].locked = 0; + h->pools[p].relock = 1; + } } } /* Put one parked pool's blocks back on the freelists — a spill one if - * `spill`, else an anonymous one; false if h has none. */ -static bool heap_unpark(ray_heap_t* h, bool spill) { + * `spill`, else an anonymous one; false if h has none. With `relock` — + * taken back for an allocation — an anonymous pool is locked again as it + * was before it was parked, if the footprint is under the watermark. */ +static bool heap_unpark(ray_heap_t* h, bool spill, bool relock) { for (uint32_t p = h->pool_count; p-- > 0; ) { ray_pool_entry_t* pe = &h->pools[p]; if (!pe->parked || pe->backed != spill) continue; @@ -2748,13 +3272,31 @@ static bool heap_unpark(ray_heap_t* h, bool spill) { pe->parked = 0; pe->discarded = 0; /* its pages are in use again */ h->parked--; + if (relock && pe->relock) { + pe->relock = 0; + if (!heap_anon_would_exceed(0)) + pe->locked = heap_lock(pe->base, BSIZEOF(pe->pool_order)) ? 1 : 0; + } return true; } return false; } static void heap_unpark_all(ray_heap_t* h) { - while (h->parked && (heap_unpark(h, false) || heap_unpark(h, true))) {} + while (h->parked && (heap_unpark(h, false, false) || heap_unpark(h, true, false))) {} +} + +/* Lock again the pools heap_unpark_all put back in service unlocked — after + * the caller is done handing their pages back, which a locked range makes + * dearer before Linux 5.18 — under the watermark, within the bound. */ +static void heap_relock_pools(ray_heap_t* h) { + for (uint32_t p = 0; p < h->pool_count; p++) { + ray_pool_entry_t* pe = &h->pools[p]; + if (!pe->relock || pe->parked) continue; + pe->relock = 0; + if (!pe->backed && !pe->locked && !heap_anon_would_exceed(0)) + pe->locked = heap_lock(pe->base, BSIZEOF(pe->pool_order)) ? 1 : 0; + } } /* An abandoned heap is visited by no boundary (heap_each_quiescent), so its @@ -2893,9 +3435,7 @@ void ray_heap_gc(void) { } else if (blk->attrs == RAY_FREE_AGE_RELEASE) { size_t bsize = BSIZEOF(ord); int rpidx = heap_find_pool(gh, blk); - bool hp = (rpidx >= 0) ? (gh->pools[rpidx].hugepage != 0) - : false; - ray_vm_release_block(blk, bsize, hp); + heap_release_block(gh, rpidx, blk, bsize); blk->attrs = RAY_FREE_AGE_RELEASE + 1; /* released */ if (++p5_released >= RAY_P5_RELEASE_BUDGET) break; } @@ -2922,8 +3462,7 @@ static int64_t heap_release_free_pages(ray_heap_t* h) { int pidx = heap_find_pool(h, blk); blk->attrs = RAY_FREE_AGE_RELEASE + 1; if (pidx >= 0 && h->pools[pidx].backed) continue; - bool hp = (pidx >= 0) ? (h->pools[pidx].hugepage != 0) : false; - ray_vm_release_block(blk, BSIZEOF(ord), hp); + heap_release_block(h, pidx, blk, BSIZEOF(ord)); released++; } } @@ -3053,6 +3592,7 @@ void ray_heap_release_pages(void) { if (!h) return; heap_unpark_all(h); (void)heap_release_free_pages(h); + heap_relock_pools(h); } /* -------------------------------------------------------------------------- @@ -3173,7 +3713,9 @@ static void heap_decay_sweep(ray_heap_t* h, void* ctx) { heap_flush_slabs(h); heap_unpark_all(h); (void)heap_reclaim_empty_pools(h, RAY_RECLAIM_SPILL); + heap_lock_trim(h); *(int64_t*)ctx += heap_release_free_pages(h); + heap_relock_pools(h); } int64_t ray_heap_decay(void) { @@ -3187,6 +3729,7 @@ int64_t ray_heap_decay(void) { int64_t released = 0; heap_each_quiescent(heap_decay_sweep, &released); + ray_heap_unlock_idle(); return released; } @@ -3235,6 +3778,7 @@ typedef struct { int64_t released; uint32_t now; bool near, act, dropped; } reli * keeps its slab cache. */ static void heap_relieve_visit(ray_heap_t* h, void* ctx) { relieve_visit_t* v = ctx; + heap_lock_trim(h); if (v->near) { heap_drain_foreign(h); heap_flush_slabs(h); @@ -3516,6 +4060,7 @@ void ray_heap_merge(ray_heap_t* src) { } } src->pool_count = 0; + heap_relock_pools(dst); /* src's parked pools, unparked above */ } /* -------------------------------------------------------------------------- @@ -3749,6 +4294,7 @@ size_t ray_shallow_bytes(const ray_t* v) { } if (v->attrs & RAY_ATTR_SLICE) return n; if (v->type == RAY_INDEX) return index_own_bytes(v); + if (v->type == RAY_ENCCOL) return block_own_bytes(v) + ray_enccol_own_bytes((ray_t*)v); if (v->attrs & RAY_ATTR_HAS_INDEX) n += index_own_bytes(v->index); if (v->type == RAY_STR && v->str_pool && !RAY_IS_ERR(v->str_pool)) n += block_own_bytes(v->str_pool); @@ -3814,6 +4360,12 @@ static size_t retained_walk(const ray_t* v, ptrset_t* seen) { for (int i = 0; i < k; i++) n += retained_walk(kids[i], seen); return n; } + if (v->type == RAY_ENCCOL) { + ray_t* kids[2]; + int nk = ray_enccol_children((ray_t*)v, kids); + for (int i = 0; i < nk; i++) n += retained_walk(kids[i], seen); + return n; + } if ((v->attrs & RAY_ATTR_HAS_INDEX) && v->index && !RAY_IS_ERR(v->index) && v->index->mmod != 1) n += retained_walk(v->index, seen); @@ -3830,7 +4382,7 @@ static size_t retained_walk(const ray_t* v, ptrset_t* seen) { if (v->type == RAY_MAPCOMMON || v->type == RAY_TABLE || v->type == RAY_DICT) { ray_t** slots = (ray_t**)ray_data((ray_t*)v); n += retained_walk(slots[0], seen); - n += retained_walk(slots[1], seen); + n += retained_walk(slots[1], seen); /* plain-table */ } return n; } diff --git a/src/mem/heap.h b/src/mem/heap.h index 20fab3804..ff8eb1964 100644 --- a/src/mem/heap.h +++ b/src/mem/heap.h @@ -58,6 +58,7 @@ * Bit 0x08 vectors: RAY_ATTR_HAS_INDEX (index ray_t* in aux[0..7]) * Bit 0x10 vectors: RAY_ATTR_SLICE * Bit 0x20 -RAY_SYM: ATTR_QUOTED (quoted/literal symbol; default = name reference) + * Bit 0x20 -RAY_I64 atoms: RAY_ATTR_DLPROG (Datalog program handle in .i64) * Bit 0x20 vectors: RAY_ATTR_SORTED (non-descending order marker) * Bit 0x40 vectors: RAY_ATTR_HAS_NULLS (sentinel-encoded; payload is truth; * a slice inherits its parent's bit) @@ -103,8 +104,8 @@ * integer or an arithmetic copy (which drops attrs) is rejected with a type * error instead of being reinterpreted as a pointer — see dl_unwrap_program. * Reuses 0x20 (RAY_ATTR_SORTED on vectors / ATTR_QUOTED on -RAY_SYM); the - * -RAY_I64 type tag disambiguates, and no free-path or generic check reads - * 0x20 on a -RAY_I64 atom. User must (dl-free h). */ + * -RAY_I64 type tag disambiguates. The heap finalizer frees the program when + * its owning atom is released; users may call (dl-free h) for early release. */ #define RAY_ATTR_DLPROG 0x20 /* Vector is a linked column. The 8 bytes of the aux union at offset @@ -136,6 +137,11 @@ /* ===== Internal Allocator Variants ===== */ +/* ray_free for a block whose last reference was just dropped: v is not + * NULL, not an error and not arena-owned, the checks ray_release_last + * already made. ray_release frees through it. */ +void ray_free_last_ref(ray_t* v); + ray_t* ray_alloc_copy(ray_t* v); ray_t* ray_scratch_alloc(size_t data_size); ray_t* ray_scratch_realloc(ray_t* v, size_t new_data_size); @@ -338,7 +344,7 @@ int64_t ray_heap_spill_discard_count(void); typedef struct { size_t map_size; /* total mmap'd bytes */ int swap_fd; /* -1 = anonymous (ray_vm_free); >=0 = file-backed spill */ - int _pad0; + int locked; /* locked against swap-out (heap_lock) */ char* swap_path; /* spill file to unlink+free on release; NULL if anon */ char _pad1[RAY_DIRECT_HDR - sizeof(size_t) - 2 * sizeof(int) - sizeof(char*)]; } ray_direct_hdr_t; @@ -388,16 +394,35 @@ int64_t ray_heap_anon_peak(void); * to the default, ray_sys_ram_limit() less the page-cache room). */ int64_t ray_heap_anon_watermark(void); void ray_heap_set_anon_watermark(int64_t bytes); +/* Locking against swap-out (heap_lock in heap.c): the bytes of the heap's + * mappings locked now; the times the kernel refused a lock, or a release + * could not lock a range again; and the bytes left unlocked — past the + * bound, past RLIMIT_MEMLOCK, or refused. All 0 where nothing is locked + * (not Linux, RAY_HEAP_MLOCK=0). */ +/* Locking on or off (RAY_HEAP_MLOCK=0 sets it off at the first lock); the + * setter, for tests, returns what it was. */ +bool ray_heap_set_lock(bool on); +int64_t ray_heap_locked_bytes(void); +int64_t ray_heap_lock_failures(void); +int64_t ray_heap_lock_skipped(void); /* The RAM a query may plan for (sizing gates, cache budgets): the watermark * when one was set (-m), else ray_sys_ram_limit(). Unlike the default * watermark it does not leave the page-cache room, which decides where new * memory goes, not how much a query may hold. */ int64_t ray_heap_mem_budget(void); +/* Committed anonymous bytes the calling thread's heap can reuse without + * committing more (free blocks in its anonymous pools, the direct-block + * cache): what a working-set planner adds back to the watermark's room. */ +int64_t ray_heap_anon_reusable(void); /* Release every block held by the direct-allocation reuse cache back to * the kernel (their committed-RAM accounting drops with them). The cache * self-drains under watermark pressure; this is for tests and explicit * memory trimming. */ void ray_heap_direct_cache_drain(void); +/* Unlock what the heap keeps locked but no longer uses: the direct-block + * cache's blocks (they stay cached). (.sys.gc) and the idle decay call it; + * an empty pool is unlocked when it is parked. */ +void ray_heap_unlock_idle(void); /* -------------------------------------------------------------------------- * Pool header: first min-block (64B) of each self-aligned pool. @@ -475,6 +500,9 @@ typedef struct { uint8_t discarded : 1; /* parked spill pool whose pages were discarded * since it was last in use * (heap_spill_pools_discard) */ + uint8_t locked : 1; /* locked against swap-out (heap_lock) */ + uint8_t relock : 1; /* unlocked while parked; to be locked again + * once in service (heap_relock_pools) */ } ray_pool_entry_t; /* -------------------------------------------------------------------------- diff --git a/src/mem/sys.c b/src/mem/sys.c index c1788b192..d75253bb3 100644 --- a/src/mem/sys.c +++ b/src/mem/sys.c @@ -36,9 +36,10 @@ typedef struct { size_t map_size; /* total mmap'd bytes (header + user, page-rounded) */ size_t usr_size; /* user-requested bytes (for realloc memcpy) */ bool spilled; /* mapped over a spill file (ray_heap_sys_map) */ + bool locked; /* locked against swap-out (ray_heap_sys_map) */ /* Padding sized so the struct totals SYS_HDR_SIZE on both 32-bit * (WASM, size_t=4) and 64-bit (Linux/macOS, size_t=8). */ - char _pad[SYS_HDR_SIZE - 2 * sizeof(size_t) - sizeof(bool)]; + char _pad[SYS_HDR_SIZE - 2 * sizeof(size_t) - 2 * sizeof(bool)]; } sys_hdr_t; _Static_assert(sizeof(sys_hdr_t) == SYS_HDR_SIZE, "sys_hdr_t must be 32 bytes"); @@ -86,21 +87,22 @@ void* ray_sys_alloc(size_t size) { if (size == 0) size = 1; if (size > SIZE_MAX - SYS_HDR_SIZE) return NULL; size_t total = page_round(SYS_HDR_SIZE + size); - bool spilled = false; - void* p = ray_heap_sys_map(total, &spilled); + bool spilled = false, locked = false; + void* p = ray_heap_sys_map(total, &spilled, &locked); if (!p) return NULL; sys_hdr_t* hdr = (sys_hdr_t*)p; hdr->map_size = total; hdr->usr_size = size; hdr->spilled = spilled; + hdr->locked = locked; return (char*)p + SYS_HDR_SIZE; } void ray_sys_free(void* ptr) { if (!ptr) return; sys_hdr_t* hdr = (sys_hdr_t*)((char*)ptr - SYS_HDR_SIZE); - ray_heap_sys_unmap(hdr, hdr->map_size, hdr->spilled); + ray_heap_sys_unmap(hdr, hdr->map_size, hdr->spilled, hdr->locked); } /* L5: ray_sys_realloc(ptr, 0) frees ptr and returns NULL, matching the diff --git a/src/mem/sys.h b/src/mem/sys.h index 6436c40ec..55f470c69 100644 --- a/src/mem/sys.h +++ b/src/mem/sys.h @@ -52,8 +52,8 @@ void* ray_sys_alloc(size_t size); void* ray_sys_realloc(void* ptr, size_t new_size); void ray_sys_free(void* ptr); char* ray_sys_strdup(const char* s); -void* ray_heap_sys_map(size_t size, bool* spilled); -void ray_heap_sys_unmap(void* p, size_t size, bool spilled); +void* ray_heap_sys_map(size_t size, bool* spilled, bool* locked); +void ray_heap_sys_unmap(void* p, size_t size, bool spilled, bool locked); /* -------------------------------------------------------------------------- * Global memory accounting. Two counters give the true runtime picture: diff --git a/src/ops/agg.c b/src/ops/agg.c index fe7d7f9d4..6815735c0 100644 --- a/src/ops/agg.c +++ b/src/ops/agg.c @@ -25,6 +25,9 @@ #include "ops/ops.h" #include "ops/internal.h" #include "ops/idxop.h" /* RAY_IDX_CHUNK_ZONE fast path for min/max */ +#include "ops/colbind.h" /* ray_col_bind_declines: column-reference lazies */ +#include "store/enccol.h" /* directory twins of the zone answers */ +#include "store/encw.h" /* ray_encw_type_summable */ #include "mem/heap.h" #include /* qsort (introselect fallback) */ @@ -94,7 +97,7 @@ static void nth_element_dbl(double* a, int64_t lo, int64_t hi, int64_t k) { static int agg_parted_numeric_base(int8_t t) { return t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || t == RAY_F32 || t == RAY_F64 || - t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_TIMESPAN; } static int64_t agg_read_i64(ray_t* v, int64_t i) { @@ -107,7 +110,7 @@ static int64_t agg_read_i64(ray_t* v, int64_t i) { case RAY_DATE: case RAY_TIME: return ((int32_t*)d)[i]; case RAY_I64: - case RAY_TIMESTAMP: return ((int64_t*)d)[i]; + case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((int64_t*)d)[i]; default: return 0; } } @@ -120,6 +123,7 @@ static ray_t* agg_atom_i64_for_type(int8_t t, int64_t v) { case RAY_I32: return ray_i32((int32_t)v); case RAY_DATE: return ray_date(v); case RAY_TIME: return ray_time(v); + case RAY_TIMESPAN: return ray_timespan(v); case RAY_TIMESTAMP: return ray_timestamp(v); default: return ray_i64(v); } @@ -160,6 +164,7 @@ static ray_t* agg_parted_sum(ray_t* x) { for (int64_t i = 0; i < seg->len; i++) if (!has_nulls || !ray_vec_is_null(seg, i)) sum = wrap_add_i64(sum, agg_read_i64(seg, i)); } + if (base == RAY_TIMESPAN) return ray_timespan(sum); if (base == RAY_TIME) return ray_time(sum); return make_i64(sum); } @@ -197,7 +202,7 @@ static ray_t* agg_parted_avg(ray_t* x) { static ray_t* agg_parted_prod(ray_t* x) { int8_t base = (int8_t)RAY_PARTED_BASETYPE(x->type); if (!agg_parted_numeric_base(base) || - base == RAY_DATE || base == RAY_TIME || base == RAY_TIMESTAMP) { + base == RAY_DATE || base == RAY_TIME || base == RAY_TIMESTAMP || base == RAY_TIMESPAN) { return ray_error("type", "prod expects a numeric parted column, got %s", ray_type_name(base)); } ray_t** segs = (ray_t**)ray_data(x); @@ -260,7 +265,8 @@ static ray_t* agg_parted_minmax(ray_t* x, int want_max) { } } } - if (!found) return ray_typed_null(-base); + if (!found) return base == RAY_TIMESPAN + ? ray_timespan(want_max ? -INT64_MAX : INT64_MAX) : ray_typed_null(-base); if (base == RAY_F64) return make_f64(best_f); if (base == RAY_F32) return ray_f32((float)best_f); return agg_atom_i64_for_type(base, best_i); @@ -466,8 +472,196 @@ bool ray_zone_int_sum128(ray_t* x, int64_t* hi_out, uint64_t* lo_out, int64_t* n return true; } +/* (at tbl 'col) of an encoded slot is a column-reference lazy + * (collection.c). The builtins below answer it as they answer the column: + * on its bound source (ray_reduce_src: the directory, or range reads), with + * the column's type-error messages, and with the out type the vector path + * gives (ray_min_op / ray_max_op: F32 answers F64). first / last read row + * 0 / len - 1 itself for the types they read with collection_elem (SYM, + * STR, GUID: by forcing the column). *done false: not a column reference, + * or an op the source does not serve (the caller appends it: the lazy is + * promoted to its OP_SCAN graph). */ +static ray_t* colref_answer(ray_t* x, uint16_t op, bool* done) { + *done = false; + ray_t* tbl; int64_t sym; + if (!ray_lazy_colref_get(x, &tbl, &sym) || ray_col_bind_declines(tbl, sym)) return NULL; + ray_col_src_t src; + ray_t* r = ray_table_col_src(tbl, sym, &src); + if (r) { *done = true; return r; } + if (!src.obj) return NULL; + int8_t t = src.type; + bool edge = op == OP_FIRST || op == OP_LAST; + switch (op) { + case OP_SUM: + if (!agg_type_admitted(OP_SUM, t)) r = ray_error("type", "sum expects a numeric or time-duration vector, got %s", ray_type_name(t)); + break; + case OP_AVG: + if (!agg_type_admitted(OP_AVG, t)) r = ray_error("type", "avg expects a numeric or temporal vector, got %s", ray_type_name(t)); + break; + case OP_PROD: + if (!agg_type_admitted(OP_PROD, t)) r = ray_error("type", "prod expects a numeric vector, got %s", ray_type_name(t)); + break; + case OP_ALL: case OP_ANY: + if (!agg_numeric_flat_type(t)) r = ray_error("type", op == OP_ALL ? "all expects a numeric vector, got %s" + : "any expects a numeric vector, got %s", ray_type_name(t)); + break; + default: break; + } + bool elem_type = t == RAY_SYM || t == RAY_I32 || t == RAY_I16 || t == RAY_GUID || t == RAY_STR || + t == RAY_BOOL || t == RAY_U8 || t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_TIMESPAN; + if (!r) { + if (op == OP_COUNT) { + r = make_i64(src.len); + } else if (edge && elem_type) { + r = ray_reduce_src_elem(&src, op == OP_LAST); + if (!r) { /* SYM / STR / GUID: the column's own element */ + ray_col_src_release(&src); + ray_retain(x); /* materialize consumes one reference */ + ray_t* v = ray_lazy_materialize(x); + *done = true; + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + r = op == OP_LAST ? ray_last_fn(v) : ray_first_fn(v); + ray_release(v); + return r; + } + } else { + int8_t out = 0; + if (op == OP_MIN || op == OP_MAX) out = t == RAY_F32 ? RAY_F64 : t; /* ray_min_op */ + else if (op == OP_SUM || op == OP_PROD) out = (t == RAY_F64 || t == RAY_F32) ? RAY_F64 : RAY_I64; + else if (op == OP_AVG) out = RAY_F64; + r = ray_reduce_src(&src, op, out); + } + } + ray_col_src_release(&src); + *done = r != NULL; + return r; +} + +/* The lazy branch of an aggregate builtin: a column reference answered in + * place, any other lazy extended by the op. */ +#define AGG_LAZY(x, op) do { \ + bool done_; \ + ray_t* r_ = colref_answer((x), (op), &done_); \ + if (done_) return r_; \ + return ray_lazy_append((x), (op)); \ +} while (0) + +/* ---- Directory twins of the CHUNK_ZONE answers (P2) ---- + * A single-file generation-2 column whose recorded index is CHUNK_ZONE is + * materialized with the chunk zone enc_synth_chunk_zone builds from its + * directory (enccol.c): aggs [sum_lo | non-null rows | sum_hi] for the + * summable types, mins / maxs with absent chunks at the empty extrema. + * These read the same entries and return what ray_sum_fn, ray_avg_fn, + * ray_min_fn and ray_max_fn return from that zone. */ +/* A single-file, stored (not synthetic) generation-2 column: it has a + * directory whether or not it records an index. */ +static ray_enccol_t* dir_col(ray_t* encv) { + if (!encv || encv->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e = ray_enccol_of(encv); + if (!e || e->kind != RAY_ENCCOL_SINGLE || e->synthetic) return NULL; + return e; +} + +/* The same, recording CHUNK_ZONE: generation 0 answers from the zone only + * where one is recorded (finding C3), and planning-time answers + * (select_agg_dir_answer) keep that gate so they never widen. */ +static ray_enccol_t* zone_dir_col(ray_t* encv) { + ray_enccol_t* e = dir_col(encv); + return e && e->hdr.index_kind == RAY_IDX_CHUNK_ZONE ? e : NULL; +} + +/* Whether the directory of a column of type t answers opcode: the types and + * operations the zone's aggs would. */ +static bool dir_op_ok(int8_t t, uint16_t opcode) { + bool int_sum_type = t == RAY_I64 || t == RAY_I32 || t == RAY_I16 || t == RAY_U8; /* ray_sum_fn / ray_avg_fn */ + if (opcode == OP_SUM || opcode == OP_AVG) return int_sum_type && ray_encw_type_summable(t); + if (opcode == OP_MIN || opcode == OP_MAX) return ray_zone_acc_supported(t); /* enc_attach_index */ + return false; +} + +static ray_t* dir_answer(ray_enccol_t* e, uint16_t opcode) { + if (!e) return NULL; + int8_t t = e->type; + bool fl = t == RAY_F32 || t == RAY_F64; + bool have_aggs = !fl && ray_encw_type_summable(t); /* zone_aggs: the summable, non-float types */ + if (!dir_op_ok(t, opcode)) return NULL; + /* the directory carries the high words (3 * n): the exact total */ + ray_enc_col_totals_t z; + ray_enccol_dir_totals(e, &z); + /* a chunk with non-null rows but no statistics is read, not skipped */ + if ((opcode == OP_MIN || opcode == OP_MAX) && z.mm_partial) return NULL; + switch (opcode) { + case OP_SUM: + return make_i64((int64_t)z.sum_wrapped); /* ray_zone_int_sum */ + case OP_AVG: + if (z.nonnull == 0) return ray_typed_null(-RAY_F64); + return make_f64(ray_i128_to_f64(z.sum_hi, z.sum_lo) / (double)z.nonnull); /* ray_zone_int_sum128 */ + default: { + bool mx = opcode == OP_MAX; + if (fl) { + /* absent chunks sit at +/-inf and never win */ + double m = mx ? z.max_f : z.min_f; + if (m == (mx ? -INFINITY : INFINITY)) return ray_typed_null(-RAY_F64); + return make_f64(m); + } + int64_t m = mx ? z.max_i : z.min_i; + if (t == RAY_TIMESPAN) + return ray_timespan(z.nonnull ? m : (mx ? -INT64_MAX : INT64_MAX)); + /* all-null by the non-null counts when the directory has sums */ + if (have_aggs ? z.nonnull == 0 : m == (mx ? INT64_MIN : INT64_MAX)) return ray_typed_null(-t); + switch (t) { + case RAY_BOOL: return ray_bool((bool)m); + case RAY_U8: return ray_u8((uint8_t)m); + case RAY_I16: return ray_i16((int16_t)m); + case RAY_I32: return ray_i32((int32_t)m); + case RAY_DATE: return ray_date((int32_t)m); + case RAY_TIME: return ray_time(m); + case RAY_TIMESPAN: return ray_timespan(m); + case RAY_TIMESTAMP: return ray_timestamp(m); + default: return ray_i64(m); + } + } + } +} + +ray_t* ray_zone_dir_answer(ray_t* encv, uint16_t opcode) { return dir_answer(zone_dir_col(encv), opcode); } +ray_t* ray_dir_answer(ray_t* encv, uint16_t opcode) { return dir_answer(dir_col(encv), opcode); } + +bool ray_dir_seg_totals(ray_t* segv, uint16_t opcode, void* totals_out) { + ray_enc_col_totals_t* out = totals_out; + ray_enccol_t* e = dir_col(segv); + if (!e || !dir_op_ok(e->type, opcode) || e->type == RAY_F32 || e->type == RAY_F64) return false; + ray_enccol_dir_totals(e, out); + if ((opcode == OP_MIN || opcode == OP_MAX) && out->mm_partial) return false; + return true; +} + +bool ray_zone_dir_int_sum128(ray_t* encv, int64_t* hi, uint64_t* lo, int64_t* nn) { + ray_enccol_t* e = zone_dir_col(encv); + if (!e) return false; + int8_t t = e->type; + /* ray_zone_int_sum128 answers the integer types whose zone has aggs */ + if (!(t == RAY_I64 || t == RAY_I32 || t == RAY_I16 || t == RAY_U8) || !ray_encw_type_summable(t)) + return false; + ray_enc_col_totals_t z; + ray_enccol_dir_totals(e, &z); + *hi = z.sum_hi; *lo = z.sum_lo; *nn = z.nonnull; + return true; +} + ray_t* ray_sum_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_SUM); + if (x->type == RAY_TIMESPAN) { + ray_t* counts = ray_vec_from_raw(RAY_I64, ray_data(x), x->len); + if (RAY_IS_ERR(counts)) return counts; + counts->attrs |= x->attrs & RAY_ATTR_HAS_NULLS; + ray_t* result = ray_sum_fn(counts); + ray_release(counts); + if (ray_is_lazy(result)) result = ray_lazy_materialize(result); + if (!RAY_IS_ERR(result)) result->type = -RAY_TIMESPAN; + return result; + } + + if (ray_is_lazy(x)) AGG_LAZY(x, OP_SUM); if (RAY_IS_PARTED(x->type)) return agg_parted_sum(x); if (ray_is_atom(x)) { /* u8/i16 scalar sum promotes to i64 */ @@ -547,7 +741,7 @@ ray_t* ray_sum_fn(ray_t* x) { } ray_t* ray_prod_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_PROD); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_PROD); if (RAY_IS_PARTED(x->type)) return agg_parted_prod(x); if (ray_is_atom(x)) { ray_retain(x); return x; } if (ray_is_vec(x)) { @@ -585,7 +779,7 @@ ray_t* ray_prod_fn(ray_t* x) { } ray_t* ray_all_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_ALL); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_ALL); if (RAY_IS_PARTED(x->type)) return agg_parted_truth(x, 1); if (ray_is_atom(x)) { if (!is_numeric(x)) return ray_error("type", "all expects numeric values, got %s", ray_type_name(x->type)); @@ -597,7 +791,7 @@ ray_t* ray_all_fn(ray_t* x) { } ray_t* ray_any_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_ANY); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_ANY); if (RAY_IS_PARTED(x->type)) return agg_parted_truth(x, 0); if (ray_is_atom(x)) { if (!is_numeric(x)) return ray_error("type", "any expects numeric values, got %s", ray_type_name(x->type)); @@ -609,7 +803,7 @@ ray_t* ray_any_fn(ray_t* x) { } ray_t* ray_count_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_COUNT); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_COUNT); if (x->type == RAY_TABLE) return make_i64(ray_table_nrows(x)); if (x->type == RAY_DICT) return make_i64(ray_dict_len(x)); /* String atom: count = string length */ @@ -626,7 +820,18 @@ ray_t* ray_count_fn(ray_t* x) { } ray_t* ray_avg_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_AVG); + if (x->type == -RAY_TIMESPAN) + return RAY_ATOM_IS_NULL(x) ? ray_typed_null(-RAY_F64) : ray_f64((double)x->i64); + if (x->type == RAY_TIMESPAN) { + ray_t* counts = ray_vec_from_raw(RAY_I64, ray_data(x), x->len); + if (RAY_IS_ERR(counts)) return counts; + counts->attrs |= x->attrs & RAY_ATTR_HAS_NULLS; + ray_t* result = ray_avg_fn(counts); + ray_release(counts); + return result; + } + + if (ray_is_lazy(x)) AGG_LAZY(x, OP_AVG); if (RAY_IS_PARTED(x->type)) return agg_parted_avg(x); if (ray_is_atom(x)) { if (RAY_ATOM_IS_NULL(x)) return ray_typed_null(-RAY_F64); @@ -665,10 +870,17 @@ ray_t* ray_avg_fn(ray_t* x) { } ray_t* ray_min_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_MIN); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_MIN); if (RAY_IS_PARTED(x->type)) return agg_parted_minmax(x, 0); if (ray_is_atom(x)) { ray_retain(x); return x; } if (ray_is_vec(x)) { + if (x->type == RAY_TIMESPAN) { + const int64_t* d = ray_data(x); + int64_t best = INT64_MAX; + for (int64_t i = 0; i < x->len; i++) + if (d[i] != NULL_I64 && d[i] < best) best = d[i]; + return ray_timespan(best); + } /* Per-chunk zone index fast path: O(n_chunks) instead of O(n_rows). * Only valid when the index was built for the column's current len * (mutation paths call ray_index_drop). */ @@ -702,6 +914,7 @@ ray_t* ray_min_fn(ray_t* x) { case RAY_I32: return ray_i32((int32_t)mn); case RAY_DATE: return ray_date((int32_t)mn); case RAY_TIME: return ray_time(mn); + case RAY_TIMESPAN: return ray_timespan(mn); case RAY_TIMESTAMP: return ray_timestamp(mn); default: return ray_i64(mn); } @@ -728,10 +941,17 @@ ray_t* ray_min_fn(ray_t* x) { } ray_t* ray_max_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_MAX); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_MAX); if (RAY_IS_PARTED(x->type)) return agg_parted_minmax(x, 1); if (ray_is_atom(x)) { ray_retain(x); return x; } if (ray_is_vec(x)) { + if (x->type == RAY_TIMESPAN) { + const int64_t* d = ray_data(x); + int64_t best = -INT64_MAX; + for (int64_t i = 0; i < x->len; i++) + if (d[i] != NULL_I64 && d[i] > best) best = d[i]; + return ray_timespan(best); + } if (ray_index_kind(x) == RAY_IDX_CHUNK_ZONE) { ray_index_t* ix = ray_index_payload(x->index); if (ix->built_for_len == x->len && ix->u.chunk_zone.maxs) { @@ -761,6 +981,7 @@ ray_t* ray_max_fn(ray_t* x) { case RAY_I32: return ray_i32((int32_t)mx); case RAY_DATE: return ray_date((int32_t)mx); case RAY_TIME: return ray_time(mx); + case RAY_TIMESPAN: return ray_timespan(mx); case RAY_TIMESTAMP: return ray_timestamp(mx); default: return ray_i64(mx); } @@ -787,7 +1008,7 @@ ray_t* ray_max_fn(ray_t* x) { } ray_t* ray_first_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_FIRST); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_FIRST); /* String first: return first char */ if (ray_is_atom(x) && (-x->type) == RAY_STR) { size_t slen = ray_str_len(x); @@ -812,7 +1033,7 @@ ray_t* ray_first_fn(ray_t* x) { if (x->type == RAY_SYM || x->type == RAY_I32 || x->type == RAY_I16 || x->type == RAY_GUID || x->type == RAY_STR || x->type == RAY_BOOL || x->type == RAY_U8 || x->type == RAY_DATE || x->type == RAY_TIME || - x->type == RAY_TIMESTAMP) { + x->type == RAY_TIMESTAMP || x->type == RAY_TIMESPAN) { int alloc = 0; return collection_elem(x, 0, &alloc); } @@ -826,7 +1047,7 @@ ray_t* ray_first_fn(ray_t* x) { } ray_t* ray_last_fn(ray_t* x) { - if (ray_is_lazy(x)) return ray_lazy_append(x, OP_LAST); + if (ray_is_lazy(x)) AGG_LAZY(x, OP_LAST); /* String last: return last char */ if (ray_is_atom(x) && (-x->type) == RAY_STR) { size_t slen = ray_str_len(x); @@ -850,7 +1071,7 @@ ray_t* ray_last_fn(ray_t* x) { if (x->type == RAY_SYM || x->type == RAY_I32 || x->type == RAY_I16 || x->type == RAY_GUID || x->type == RAY_STR || x->type == RAY_BOOL || x->type == RAY_U8 || x->type == RAY_DATE || x->type == RAY_TIME || - x->type == RAY_TIMESTAMP) { + x->type == RAY_TIMESTAMP || x->type == RAY_TIMESPAN) { int alloc = 0; return collection_elem(x, ray_len(x) - 1, &alloc); } @@ -897,7 +1118,7 @@ static ray_t* vec_to_f64_scratch(ray_t* x, double** out_vals) { * raw counts (result F64), per the canonical admission table. */ int32_t* d = (int32_t*)ray_data(x); for (int64_t i = 0; i < len; i++) { if (!ray_vec_is_null(x, i)) vals[cnt++] = (double)d[i]; } - } else if (x->type == RAY_TIMESTAMP) { + } else if (x->type == RAY_TIMESTAMP || x->type == RAY_TIMESPAN) { int64_t* d = (int64_t*)ray_data(x); for (int64_t i = 0; i < len; i++) { if (!ray_vec_is_null(x, i)) vals[cnt++] = (double)d[i]; } } else { diff --git a/src/ops/agg_acc.h b/src/ops/agg_acc.h index eb60c43e7..d2d4e5110 100644 --- a/src/ops/agg_acc.h +++ b/src/ops/agg_acc.h @@ -24,7 +24,7 @@ typedef struct { static inline bool ray_valid_at(const ray_valid_t* v, int64_t row) { if (!v->has_nulls) return true; switch (v->type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)v->base)[row] != NULL_I64; case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)v->base)[row] != NULL_I32; @@ -82,6 +82,10 @@ typedef struct { /* Release heap state owned by a per-group state slab. NULL for ACC_STREAMING. * The engine calls this on every init'd state once it won't be used again. */ void (*destroy)(void* state); + /* update_shared is an unconditional atomic add: every row writes, so the + * extrema sample (agg_shared_sample) cannot favour it, and only a plan too + * wide for per-worker slabs (dense_plan_t.wide) runs it. */ + bool shared_add; } agg_vtable_t; #endif /* RAY_OPS_AGG_ACC_H */ diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index 6a66a1de9..edb318c46 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -1,25 +1,53 @@ /* src/ops/agg_engine.c — v2 aggregation engine. */ +#if defined(__APPLE__) +# define _DARWIN_C_SOURCE +#elif !defined(_WIN32) +# define _GNU_SOURCE /* pread, pwrite, O_CLOEXEC: the radix spill file */ +#endif #include "ops/agg_engine.h" #include "ops/agg_registry.h" #include "ops/ops.h" #include "ops/hash.h" /* ray_hash_bytes — wide (STR) group-key hashing */ #include "ops/internal.h" /* col_vec_new, col_esz */ +#include "ops/colbind.h" +#include "ops/colgather.h" /* generation-2 compact gathers */ #include "ops/rowsel.h" /* ray_rowsel_meta, ray_rowsel_to_indices */ #include "lang/internal.h" /* sym_domain_rep */ #include "table/domain.h" +#include "table/table.h" #include "table/sym.h" /* ray_read_sym */ #include "store/col.h" /* ray_col_cold — sampled-row read-ahead */ #include "core/pool.h" /* ray_pool_want — a column asked for whole */ #include "core/platform.h" /* ray_cache_llc_bytes — replicated slab bound */ +#include "store/enc.h" /* RAY_ENC_CHUNK: directory statistics per chunk */ +#include "store/enccol.h" /* ray_enc_chunk_stat_t */ +#include "store/enceval.h" /* ray_enc_runs: COUNT groups on key runs */ #include #include #include +/* The radix spill file (agg_radix_spill_t) is POSIX pread/pwrite; Windows + * keeps the re-scanned waves only, as its heap keeps anonymous pools only. */ +#if defined(RAY_OS_WINDOWS) +# define AGG_RADIX_FILE_SPILL 0 +#else +# define AGG_RADIX_FILE_SPILL 1 +# include +# include +# include +#endif + /* Radix output address: high 32 bits partition, low 32 bits local group. */ typedef struct { int64_t idx; } agg_radix_order_t; bool ray_agg_engine_v2 = true; /* knob; default on */ bool ray_agg_tablestack = true; /* knob; default on */ +int64_t ray_agg_radix_wave_bytes = 0; /* knob; 0 = heap-derived wave bound, <0 = off */ +int ray_agg_radix_spill = 0; /* knob; 0 = by bytes, 1 = never, 2 = always, 3..6 = always with a fault */ +static bool agg_force_smallhash; /* test hook (agg_test_force_smallhash) */ +static bool agg_no_wide_dense; /* test hook (agg_test_no_wide_dense) */ +void agg_test_force_smallhash(bool on) { agg_force_smallhash = on; } +void agg_test_no_wide_dense(bool on) { agg_no_wide_dense = on; } static _Thread_local agg_route_stats_t route_stats; void agg_route_reset(void) { memset(&route_stats, 0, sizeof(route_stats)); } @@ -48,7 +76,6 @@ void agg_route_reason(agg_v2_reason_t reason) { } /* Read element `row` of an integer/temporal/SYM column widened to int64. */ -static inline int64_t agg_read_key_i64(ray_t* col, const void* data, int64_t row); /* Dense direct-index serial grouping; defined below agg_run_one. */ static int agg_group_keys_dense(ray_t** key_cols, int64_t nrows, const dense_plan_t* dp, agg_groups_t* out); @@ -66,11 +93,20 @@ static bool agg_indexed_supported(uint16_t op, int8_t t) { bool scalar = number || t == RAY_GUID || t == RAY_SYM || t == RAY_STR; if (op == OP_FIRST || op == OP_LAST) return scalar || t == RAY_LIST; if (op == OP_MIN || op == OP_MAX) return t == RAY_GUID || t == RAY_STR || t == RAY_SYM; - if (op == OP_MEDIAN || op == OP_QUANTILE) return number; + if (op == OP_MEDIAN || op == OP_QUANTILE) return number || t == RAY_TIMESPAN; if (op == OP_MODE || op == OP_TOP_N || op == OP_BOT_N) return scalar; return false; } +/* A column's metadata as the v2 engine routes it: under an in-place concat + * group (g->grp_seg_stream) a parted column reads as its base type, since + * its sources are read from the segments; otherwise unchanged. */ +static bool agg_col_meta(ray_graph_t* g, ray_t* tbl, int64_t sym, ray_col_meta_t* m) { + if (!ray_table_col_meta(tbl, sym, m)) return false; + if (g->grp_seg_stream && RAY_IS_PARTED(m->type)) m->type = (int8_t)RAY_PARTED_BASETYPE(m->type); + return true; +} + agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { if (!g || !op || !tbl) return AGG_V2_SHAPE; ray_op_ext_t* ext = find_ext(g, op->id); @@ -103,8 +139,10 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { if (ext->n_keys == 1 && op_node(g, ext->keys[0]) && op_node(g, ext->keys[0])->opcode == OP_SCAN) { ray_op_ext_t* ke = find_ext(g, ext->keys[0]); if (ke && ke->sym == ray_sym_intern("_src", 4)) { - ray_t* cnt = ray_table_get_col(tbl, ray_sym_intern("_count", 6)); - if (cnt && cnt->type == RAY_I64) return AGG_V2_SHAPE; + ray_col_meta_t cm; + /* agg_col_meta: a parted _count (an in-place concat's probe) is + * its base I64, so the shortcut keeps the group as over the flatten */ + if (agg_col_meta(g, tbl, ray_sym_intern("_count", 6), &cm) && cm.type == RAY_I64) return AGG_V2_SHAPE; } } @@ -113,9 +151,9 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { ray_op_t* key = op_node(g, ext->keys[k]); if (!key || key->opcode != OP_SCAN) return AGG_V2_KEY_EXPRESSION; ray_op_ext_t* kext = find_ext(g, key->id); - ray_t* kc = kext ? ray_table_get_col(tbl, kext->sym) : NULL; - if (!kc) return AGG_V2_SHAPE; - switch (kc->type) { + ray_col_meta_t km; + if (!kext || !agg_col_meta(g, tbl, kext->sym, &km)) return AGG_V2_SHAPE; + switch (km.type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_SYM: @@ -135,14 +173,15 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { bool floating = false, indexed = false; for (uint32_t k = 0; k < ext->n_keys; k++) { ray_op_ext_t* ke = find_ext(g, ext->keys[k]); - ray_t* col = ray_table_get_col(tbl, ke->sym); - if (col->type == RAY_F32 || col->type == RAY_F64) floating = true; - if (col->type == RAY_STR || col->type == RAY_GUID || col->type == RAY_LIST) indexed = true; + ray_col_meta_t cm; + if (!agg_col_meta(g, tbl, ke->sym, &cm)) continue; /* present: the key loop above checked */ + if (cm.type == RAY_F32 || cm.type == RAY_F64) floating = true; + if (cm.type == RAY_STR || cm.type == RAY_GUID || cm.type == RAY_LIST) indexed = true; } for (uint32_t a = 0; a < ext->n_aggs; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); - ray_t* col = ie ? ray_table_get_col(tbl, ie->sym) : NULL; - if (col && agg_indexed_supported(ext->agg_ops[a], col->type)) indexed = true; + ray_col_meta_t cm; + if (ie && agg_col_meta(g, tbl, ie->sym, &cm) && agg_indexed_supported(ext->agg_ops[a], cm.type)) indexed = true; } if (floating && !indexed) return AGG_V2_PARALLEL_WIDE; } @@ -155,9 +194,10 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { ray_op_t* in = op_node(g, ext->agg_ins[a]); if (!in || in->opcode != OP_SCAN) return AGG_V2_AGG_EXPRESSION; ray_op_ext_t* ie = find_ext(g, in->id); - ray_t* ic = ie ? ray_table_get_col(tbl, ie->sym) : NULL; - if (ic && agg_indexed_supported(ext->agg_ops[a], ic->type)) continue; - const agg_vtable_t* vt = ic ? agg_resolve(ext->agg_ops[a], ic->type) : NULL; + ray_col_meta_t im; + bool ih = ie && agg_col_meta(g, tbl, ie->sym, &im); + if (ih && agg_indexed_supported(ext->agg_ops[a], im.type)) continue; + const agg_vtable_t* vt = ih ? agg_resolve(ext->agg_ops[a], im.type) : NULL; if (!vt) return AGG_V2_AGG_TYPE; if (vt->kind != ACC_STREAMING) return AGG_V2_BUFFERED; continue; /* admitted */ @@ -167,11 +207,11 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { ray_op_t* xin = op_node(g, ext->agg_ins[a]); ray_op_t* yin = op_node(g, ext->agg_ins2[a]); if (!xin || xin->opcode != OP_SCAN || !yin || yin->opcode != OP_SCAN) return AGG_V2_AGG_EXPRESSION; ray_op_ext_t* xe = find_ext(g, xin->id); ray_op_ext_t* ye = find_ext(g, yin->id); - ray_t* xc = xe ? ray_table_get_col(tbl, xe->sym) : NULL; - ray_t* yc = ye ? ray_table_get_col(tbl, ye->sym) : NULL; - if (!xc || !yc) return AGG_V2_SHAPE; - if (!agg_resolve(ext->agg_ops[a], xc->type)) return AGG_V2_AGG_TYPE; - if (!agg_resolve(ext->agg_ops[a], yc->type)) return AGG_V2_AGG_TYPE; + ray_col_meta_t xm, ym; + if (!xe || !ye || !agg_col_meta(g, tbl, xe->sym, &xm) + || !agg_col_meta(g, tbl, ye->sym, &ym)) return AGG_V2_SHAPE; + if (!agg_resolve(ext->agg_ops[a], xm.type)) return AGG_V2_AGG_TYPE; + if (!agg_resolve(ext->agg_ops[a], ym.type)) return AGG_V2_AGG_TYPE; continue; /* admitted */ } if (ext->agg_ops[a] == OP_COUNT) { @@ -182,10 +222,10 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { ray_op_t* in = op_node(g, ext->agg_ins[a]); if (!in || in->opcode != OP_SCAN) return AGG_V2_AGG_EXPRESSION; ray_op_ext_t* ie = find_ext(g, in->id); - ray_t* ic = (ie) ? ray_table_get_col(tbl, ie->sym) : NULL; - if (!ic) return AGG_V2_SHAPE; - if (agg_indexed_supported(ext->agg_ops[a], ic->type)) continue; - const agg_vtable_t* vt = agg_resolve(ext->agg_ops[a], ic->type); + ray_col_meta_t im; + if (!ie || !agg_col_meta(g, tbl, ie->sym, &im)) return AGG_V2_SHAPE; + if (agg_indexed_supported(ext->agg_ops[a], im.type)) continue; + const agg_vtable_t* vt = agg_resolve(ext->agg_ops[a], im.type); if (!vt) return AGG_V2_AGG_TYPE; if (vt->kind != ACC_STREAMING) return AGG_V2_BUFFERED; /* The streaming 64-bit integer avg packs its 128-bit high word with @@ -193,8 +233,8 @@ agg_v2_reason_t agg_v2_admission(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { * group has fewer than 2^32 rows; the narrower kernels keep a plain * int64 sum, exact below 2^31 rows. A table that large keeps the * legacy engines, whose accumulators carry a full high word. */ - if (ext->agg_ops[a] == OP_AVG && ic->type != RAY_F64 && ic->type != RAY_F32 && - ray_table_nrows(tbl) >= ((int64_t)1 << ((ic->type == RAY_I64 || ic->type == RAY_TIMESTAMP) ? 32 : 31))) + if (ext->agg_ops[a] == OP_AVG && im.type != RAY_F64 && im.type != RAY_F32 && + ray_table_nrows(tbl) >= ((int64_t)1 << ((im.type == RAY_I64 || im.type == RAY_TIMESTAMP) ? 32 : 31))) return AGG_V2_AGG_TYPE; } return AGG_V2_ADMITTED; @@ -263,12 +303,341 @@ static bool agg_dense_range(dense_plan_t* dp, uint32_t k, int64_t mn, int64_t mx return true; } +/* ── Range reads: generation-2 sources ─────────────────────────────────── + * A strategy's sources are its keys, then its aggregate inputs, then the + * y-sides of binary aggregates (n_keys + 2 * n_aggs). A plain source (a + * generation-0 column, a published materialization) is read in place + * through its row-0 pointer. A staged source (generation 2) is read by + * range: the task body runs over pieces of its rows (R-WALK) or over runs + * of ascending rows (R-SPARSE), and reads every column at row - base + * through a view. A plain context runs today's loop over its whole-column + * view (base 0) and never calls the walk. */ +typedef struct { + ray_col_src_t* const* srcs; /* [n_src] staged sources; NULL: read in place (or COUNT) */ + const void* const* plain; /* [n_src] row-0 pointers; NULL for staged sources and COUNT */ + const uint8_t* esz; /* [n_src] element widths (keys: the column's SYM width) */ + const int8_t* key_types; /* [n_keys] */ + const uint8_t* key_attrs; /* [n_keys] the plain columns' (stand-ins') attrs */ + uint32_t n_src, n_keys, n_aggs; + ray_scan_fail_t* fail; + bool staged; /* some source is staged */ +} agg_rr_t; + +/* What a task body reads rows through: element 0 of every pointer is row + * `base`. The whole-column view has base 0; a piece's view is positioned + * at the piece's first row and carries the pieces' SYM widths. */ +typedef struct { + const void* const* key_data; /* [n_keys] */ + const uint8_t* key_attrs; /* [n_keys] SYM widths of key_data */ + const void* const* val_data; /* [n_aggs]; NULL: no input (COUNT) */ + const void* const* val2_data; /* [n_aggs] y-sides of binary aggregates */ + int64_t base; +} agg_view_t; + +static inline agg_view_t agg_view_whole(const agg_rr_t* rr) { + return (agg_view_t){ .key_data = rr->plain, .key_attrs = rr->key_attrs, + .val_data = rr->plain + rr->n_keys, + .val2_data = rr->plain + rr->n_keys + rr->n_aggs, .base = 0 }; +} + +/* Key k of view v at absolute row r. */ +static inline int64_t agg_vkey(const agg_view_t* v, const int8_t* key_types, uint32_t k, int64_t r) { + return agg_read_key_i64_raw(key_types[k], v->key_attrs[k], v->key_data[k], r - v->base); +} + +/* A body over rows [start, end) (or over indices [start, end) of an index + * list, for the R-SPARSE driver) read through view v. */ +typedef void (*agg_body_fn)(void* ctx, const agg_view_t* v, uint32_t wid, int64_t start, int64_t end); + +/* The view of row b: staged sources from their pieces or views (ptr/kat + * already filled for them), the others offset from their row-0 pointers. */ +static void agg_view_set(const agg_rr_t* rr, int64_t b, const void** ptr, uint8_t* kat, + agg_view_t* v) { + for (uint32_t i = 0; i < rr->n_src; i++) + if (!rr->srcs[i]) ptr[i] = rr->plain[i] ? (const char*)rr->plain[i] + (size_t)b * rr->esz[i] : NULL; + for (uint32_t k = 0; k < rr->n_keys; k++) + if (!rr->srcs[k] || rr->key_types[k] != RAY_SYM) kat[k] = rr->key_attrs[k]; + v->key_data = ptr; + v->key_attrs = kat; + v->val_data = ptr + rr->n_keys; + v->val2_data = ptr + rr->n_keys + rr->n_aggs; + v->base = b; +} + +typedef struct { + void* ctx; + agg_body_fn body; + const agg_rr_t* rr; +} agg_piece_ctx_t; + +static void agg_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + agg_piece_ctx_t* pc = (agg_piece_ctx_t*)ctx; + const agg_rr_t* rr = pc->rr; + uint32_t ns = rr->n_src ? rr->n_src : 1, nk = rr->n_keys ? rr->n_keys : 1; + const void* ptr[ns]; + uint8_t kat[nk]; + for (uint32_t i = 0; i < rr->n_src; i++) + if (rr->srcs[i]) ptr[i] = p[i].data; + for (uint32_t k = 0; k < rr->n_keys; k++) + if (rr->srcs[k]) kat[k] = p[k].attrs; + agg_view_t v; + agg_view_set(rr, b, ptr, kat, &v); + pc->body(pc->ctx, &v, wid, b, e); +} + +/* R-WALK of rows [start, end) of a staged context. A range error is noted + * keyed by `key` (the task's first row or position) and false returned; a + * task below a noted failure still runs (it may fail lower). */ +static bool agg_walk(const agg_rr_t* rr, void* ctx, agg_body_fn body, + uint32_t wid, int64_t start, int64_t end, int64_t key) { + if (ray_scan_fail_skip(rr->fail, key)) return false; + agg_piece_ctx_t pc = { ctx, body, rr }; + ray_t* err = ray_col_walk(rr->srcs, rr->plain, rr->n_src, start, end, false, &pc, wid, agg_piece); + if (!err) return true; + ray_scan_fail_note(rr->fail, key, err); + return false; +} + +/* One cursor per staged source, created by a task at its start and freed + * at its end (R-SPARSE: each touched vector is decoded once per task). Up + * to AGG_CURS_STACK cursors live in the set, on the task's stack, and the + * first AGG_CURS_LENT encoded sources decode into fixed vectors lent from + * the set, so a worker's first decode takes nothing from its heap (a fresh + * worker heap maps and faults in a whole pool on its first allocation: + * ClickBench q8 on partitions, first run). Two, not one per cursor: the + * set's frame is probed page by page on every task's first entry, and + * eight lent vectors (128 KB) measured q8's generation-0 first run 3% + * slower. Declared without an initializer (the fixed vectors are not to + * be zeroed): set cur = NULL before any path that may free it. */ +enum { AGG_CURS_STACK = 8, AGG_CURS_LENT = 2 }; +typedef struct { + ray_col_cursor_t st[AGG_CURS_STACK]; + ray_col_fixed_t fx[AGG_CURS_LENT]; + ray_col_cursor_t* cur; +} agg_curs_t; + +static bool agg_curs_init(agg_curs_t* cs, const agg_rr_t* rr) { + cs->cur = rr->n_src <= AGG_CURS_STACK ? cs->st + : ray_calloc_raw((size_t)rr->n_src * sizeof(ray_col_cursor_t)); + if (!cs->cur) return false; + uint32_t lent = 0; + for (uint32_t i = 0; i < rr->n_src; i++) { + if (!rr->srcs[i]) continue; + if (lent < AGG_CURS_LENT && ray_col_src_encoded(rr->srcs[i])) + ray_col_cursor_init_lent(&cs->cur[i], rr->srcs[i], &cs->fx[lent++]); + else + ray_col_cursor_init(&cs->cur[i], rr->srcs[i]); + } + return true; +} + +static void agg_curs_free(agg_curs_t* cs, const agg_rr_t* rr) { + if (!cs->cur) return; + for (uint32_t i = 0; i < rr->n_src; i++) + if (rr->srcs[i]) ray_col_cursor_free(&cs->cur[i]); + if (cs->cur != cs->st) ray_free_raw(cs->cur); + cs->cur = NULL; +} + +/* agg_walk through the task's cursors cs (agg_curs_init), which persist + * across its calls: a task walking consecutive blocks decodes the vector + * one block ends inside once, not once per block. */ +static bool agg_walk_cs(const agg_rr_t* rr, agg_curs_t* cs, void* ctx, agg_body_fn body, + uint32_t wid, int64_t start, int64_t end, int64_t key) { + if (ray_scan_fail_skip(rr->fail, key)) return false; + agg_piece_ctx_t pc = { ctx, body, rr }; + ray_t* err = ray_col_walk_cur(rr->srcs, rr->plain, rr->n_src, cs->cur, start, end, &pc, wid, agg_piece); + if (!err) return true; + ray_scan_fail_note(rr->fail, key, err); + return false; +} + +/* Point reads of a staged key or input (ray_col_src_points_i64's + * contract: the ascending rows[0, n) of one vector, 1 / 0 / -1). A SYM + * source's rows are its ids (ray_col_src_gather_points: each checked + * against the domain bound, id 0 the in-band null served as itself), so + * an id key costs no vector decode either. SYM has no null bitmap; a + * flagged row would be one, and declines (the cursor reads it). */ +static inline int agg_src_points(ray_col_src_t* s, const int64_t* rows, int64_t n, int64_t* out, ray_t** err) { + if (s->type != RAY_SYM) return ray_col_src_points_i64(s, rows, n, out, err); + *err = NULL; + if (n < 1 || n > RAY_COL_POINT_ROWS) return 0; + uint8_t nul[RAY_COL_POINT_ROWS]; + int pr = ray_col_src_gather_points(s, rows, n, out, nul, err); + if (pr > 0) for (int64_t q = 0; q < n; q++) if (nul[q]) return 0; + return pr; +} + +/* R-SPARSE over the ascending rows idx[i0, i1) through the task's cursors: + * the rows every staged source's current view covers form one run, handed + * to body as the index range [ib, ie) with a view positioned at idx[ib]. + * Point reads (open decision D2): the first AGG_CURS_LENT integer and SYM sources + * read a vector holding few of the rows (D2, per codec; none + * decoded yet) by point reads into a vector-sized buffer of the walk, at + * the rows' own offsets: a sparse view, valid for exactly those rows, + * which are every row of idx[i0, i1) inside the vector, so no run reads + * another. A declined vector is read through the cursor. + * NULL or an owned error (body is not called again after an error). */ +static ray_t* agg_idx_walk(const agg_rr_t* rr, agg_curs_t* cs, const int64_t* idx, + int64_t i0, int64_t i1, void* ctx, agg_body_fn body, uint32_t wid) { + uint32_t ns = rr->n_src ? rr->n_src : 1, nk = rr->n_keys ? rr->n_keys : 1; + const void* ptr[ns]; + uint8_t kat[nk]; + /* the sparse views: their sources, vectors [lo, hi) and buffers */ + _Alignas(64) int64_t spb[AGG_CURS_LENT][RAY_MORSEL_ELEMS]; + int64_t sp_lo[AGG_CURS_LENT], sp_hi[AGG_CURS_LENT]; + uint32_t sp_src[AGG_CURS_LENT], nsp = 0; + for (uint32_t s = 0; s < rr->n_src && nsp < AGG_CURS_LENT; s++) { + ray_col_src_t* src = rr->srcs[s]; + if (!src || !ray_col_src_encoded(src)) continue; + switch (src->type) { + case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_SYM: + sp_src[nsp] = s; sp_lo[nsp] = sp_hi[nsp] = -1; nsp++; break; + default: break; + } + } + for (int64_t i = i0; i < i1; ) { + int64_t b = idx[i], e = INT64_MAX; + for (uint32_t s = 0, sp = 0; s < rr->n_src; s++) { + if (!rr->srcs[s]) continue; + int slot = -1; + if (sp < nsp && sp_src[sp] == s) slot = (int)sp++; + if (slot >= 0) { + ray_col_cursor_t* c = &cs->cur[s]; + bool covered = c->have && b >= c->v.start && b < c->v.start + c->v.n; + int64_t vlo, vhi; + if (!covered && !(b >= sp_lo[slot] && b < sp_hi[slot]) && + ray_col_src_vec_span(rr->srcs[s], b, &vlo, &vhi)) { + int64_t j = i + 1; + while (j < i1 && j - i <= RAY_COL_POINT_ROWS && idx[j] < vhi) j++; + if (j - i <= RAY_COL_POINT_ROWS) { + int64_t x[RAY_COL_POINT_ROWS]; + ray_t* err = NULL; + int pr = agg_src_points(rr->srcs[s], idx + i, j - i, x, &err); + if (pr < 0) return err; + if (pr > 0) { + uint8_t esz = ray_sym_elem_size(rr->srcs[s]->type, rr->srcs[s]->attrs); + char* d = (char*)spb[slot]; + for (int64_t q = 0; q < j - i; q++) { + size_t at = (size_t)(idx[i + q] - vlo) * esz; + switch (esz) { + case 1: d[at] = (char)x[q]; break; + case 2: { int16_t y = (int16_t)x[q]; memcpy(d + at, &y, 2); break; } + case 4: { int32_t y = (int32_t)x[q]; memcpy(d + at, &y, 4); break; } + default: memcpy(d + at, &x[q], 8); break; + } + } + sp_lo[slot] = vlo; sp_hi[slot] = vhi; + } + } + } + if (!covered && b >= sp_lo[slot] && b < sp_hi[slot]) { + uint8_t esz = ray_sym_elem_size(rr->srcs[s]->type, rr->srcs[s]->attrs); + ptr[s] = (const char*)spb[slot] + (size_t)(b - sp_lo[slot]) * esz; + if (s < rr->n_keys) kat[s] = rr->srcs[s]->attrs; + if (sp_hi[slot] < e) e = sp_hi[slot]; + continue; + } + } + const ray_col_range_t* v; + ray_t* err = ray_col_cursor_at(&cs->cur[s], b, &v); + if (err) return err; + ptr[s] = (const char*)v->data + (size_t)(b - v->start) * ray_sym_elem_size(v->type, v->attrs); + if (s < rr->n_keys) kat[s] = v->attrs; + if (v->start + v->n < e) e = v->start + v->n; + } + int64_t j = i + 1; + while (j < i1 && idx[j] < e) j++; + agg_view_t view; + agg_view_set(rr, b, ptr, kat, &view); + body(ctx, &view, wid, i, j); + i = j; + } + return NULL; +} + +/* Single-row reads for the samplers (strided, sparse): in place, or + * from a staged source's packed vector (a point read, no vector decode), + * else through its cursor. *err is set on a range error. */ +static inline int64_t agg_key_at(const agg_rr_t* rr, agg_curs_t* cs, uint32_t k, int64_t r, ray_t** err) { + if (!rr->srcs[k]) return agg_read_key_i64_raw(rr->key_types[k], rr->key_attrs[k], rr->plain[k], r); + int64_t x; + int pr = rr->srcs[k]->type == RAY_SYM ? agg_src_points(rr->srcs[k], &r, 1, &x, err) + : ray_col_src_point_i64(rr->srcs[k], r, &x, err); + if (pr) return pr > 0 ? x : 0; + const ray_col_range_t* v; + if ((*err = ray_col_cursor_at(&cs->cur[k], r, &v)) != NULL) return 0; + return agg_read_key_i64_raw(rr->key_types[k], v->attrs, v->data, r - v->start); +} +static inline const void* agg_elem_at(const agg_rr_t* rr, agg_curs_t* cs, uint32_t i, int64_t r, ray_t** err) { + if (!rr->srcs[i]) return rr->plain[i] ? (const char*)rr->plain[i] + (size_t)r * rr->esz[i] : NULL; + const ray_col_range_t* v; + if ((*err = ray_col_cursor_at(&cs->cur[i], r, &v)) != NULL) return NULL; + return (const char*)v->data + (size_t)(r - v->start) * rr->esz[i]; +} + +/* A zero-length column of a staged source's type standing in for it where + * a strategy reads the column's type, SYM width, domain and nullability + * (plans, layouts, emits); NULL on OOM. Its data is never read. */ +static ray_t* agg_src_standin(const ray_col_src_t* s) { + /* a parted SYM source's own width is not authoritative (segments may + * differ): the stand-in takes the widest segment's, which plans and + * emits size their slots and output by */ + uint8_t w = s->parted ? parted_sym_width(s->obj) : (s->attrs & RAY_SYM_W_MASK); + ray_t* v = s->type == RAY_SYM ? ray_sym_vec_new(w, 0) + : ray_vec_new(s->type, 0); + if (!v || RAY_IS_ERR(v)) { + if (v) ray_error_free(v); + return NULL; + } + if (s->type == RAY_SYM && s->dom && s->dom != ray_sym_runtime_domain()) { + ray_sym_domain_retain(s->dom); + v->sym_domain = s->dom; + } + if (s->may_null && s->type != RAY_SYM) v->attrs |= RAY_ATTR_HAS_NULLS; + v->len = 0; + return v; +} + +/* The keys of one group run: bound once by exec_group_v2_run_inner. A + * staged key's column is a stand-in (agg_src_standin). */ +typedef struct { + agg_rr_t rr; /* keys only (n_aggs 0) */ + ray_col_src_t** srcs; /* [n] staged keys' sources */ + const void** plain; /* [n] */ + int8_t* types; + uint8_t* attrs; + uint8_t* esz; + ray_scan_fail_t fail; +} agg_keyset_t; + +/* R-RANDOM: every staged key takes its plain column (a generation-2 key + * decodes once, through its once-state), for a strategy that reads keys at + * stored rows or whole. NULL or an owned error. */ +static ray_t* agg_keys_unstage(ray_t** key_cols, agg_keyset_t* ks) { + for (uint32_t k = 0; k < ks->rr.n_keys; k++) { + if (!ks->srcs[k]) continue; + ray_t* plain = NULL; + ray_t* err = ray_col_src_plain(ks->srcs[k], &plain); /* random: unstage: v2 whole-column strategy */ + if (err) return err; + if (!plain) return ray_error("domain", "group key: no column"); + key_cols[k] = plain; /* borrowed: valid while the source is bound */ + ks->plain[k] = ray_data(plain); + ks->attrs[k] = plain->attrs; + ks->esz[k] = ray_sym_elem_size(plain->type, plain->attrs); + ks->srcs[k] = NULL; + } + ks->rr.staged = false; + return NULL; +} + /* Hoist type and null handling out of range scans so native integer * reductions can vectorize, including nullable temporal keys. */ -static void agg_key_bounds(ray_t* key, int64_t start, int64_t end, bool nullable, - int64_t null, int64_t* lo, int64_t* hi) { +static void agg_key_bounds_raw(int8_t type, uint8_t attrs, const void* data, + int64_t start, int64_t end, bool nullable, + int64_t null, int64_t* lo, int64_t* hi) { int64_t mn = INT64_MAX, mx = INT64_MIN; - const void* data = ray_data(key); #define KEY_BOUNDS(T) do { \ const T* p = data; \ if (nullable) { \ @@ -287,13 +656,13 @@ static void agg_key_bounds(ray_t* key, int64_t start, int64_t end, bool nullable } \ } \ } while (0) - switch (key->type) { - case RAY_I64: case RAY_TIMESTAMP: KEY_BOUNDS(int64_t); break; + switch (type) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: KEY_BOUNDS(int64_t); break; case RAY_I32: case RAY_DATE: case RAY_TIME: KEY_BOUNDS(int32_t); break; case RAY_I16: KEY_BOUNDS(int16_t); break; case RAY_U8: case RAY_BOOL: KEY_BOUNDS(uint8_t); break; case RAY_SYM: - switch (key->attrs & RAY_SYM_W_MASK) { + switch (attrs & RAY_SYM_W_MASK) { case RAY_SYM_W8: KEY_BOUNDS(uint8_t); break; case RAY_SYM_W16: KEY_BOUNDS(uint16_t); break; case RAY_SYM_W32: KEY_BOUNDS(uint32_t); break; @@ -304,6 +673,10 @@ static void agg_key_bounds(ray_t* key, int64_t start, int64_t end, bool nullable #undef KEY_BOUNDS *lo = mn; *hi = mx; } +static void agg_key_bounds(ray_t* key, int64_t start, int64_t end, bool nullable, + int64_t null, int64_t* lo, int64_t* hi) { + agg_key_bounds_raw(key->type, key->attrs, ray_data(key), start, end, nullable, null, lo, hi); +} typedef struct { ray_t* key; @@ -333,6 +706,137 @@ static void agg_key_bounds_fn(void* raw, uint32_t wid, int64_t start, int64_t en c->bounds[task * 2 + 1] = hi; } } + +/* A staged key's prescan: one task per scanned span (a chunk without + * directory statistics, or the whole key when it has no directory), each + * span read by pieces (R-WALK) into its task's bounds. */ +typedef struct { + const agg_rr_t* rr; /* the key alone */ + bool nullable; + int64_t null; + const int64_t* spans; /* [tasks][2] row ranges */ + int64_t* bounds; /* [tasks][2] */ +} agg_key_scan_ctx_t; +typedef struct { const agg_key_scan_ctx_t* c; int64_t lo, hi; } agg_key_scan_task_t; +static void agg_key_scan_piece(void* raw, const agg_view_t* v, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_key_scan_task_t* t = raw; + int64_t lo, hi; + agg_key_bounds_raw(t->c->rr->key_types[0], v->key_attrs[0], v->key_data[0], + 0, end - start, t->c->nullable, t->c->null, &lo, &hi); + if (lo < t->lo) t->lo = lo; + if (hi > t->hi) t->hi = hi; +} +static void agg_key_scan_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + agg_key_scan_ctx_t* c = raw; + for (int64_t task = start; task < end; task++) { + agg_key_scan_task_t t = { c, INT64_MAX, INT64_MIN }; + (void)agg_walk(c->rr, &t, agg_key_scan_piece, wid, c->spans[task * 2], c->spans[task * 2 + 1], + c->spans[task * 2]); + c->bounds[task * 2] = t.lo; c->bounds[task * 2 + 1] = t.hi; + } +} + +/* One chunk of a parted key (ray_col_src_parted_chunks): folded from its + * segment's statistics as agg_key_bounds_staged folds a directory's, or + * appended to the spans to scan (counted only while spans is NULL). */ +typedef struct { + int8_t type; + int64_t mn, mx; + int64_t* spans; + int64_t n; +} agg_bounds_fold_t; +static void agg_bounds_chunk(void* raw, int64_t lo, int64_t hi, const ray_enc_chunk_stat_t* st) { + agg_bounds_fold_t* f = raw; + if (st) { + if (f->type == RAY_SYM && st->null_count > 0 && f->mn > 0) f->mn = 0; + if ((int64_t)st->null_count >= st->rows) return; /* all null */ + if (st->has_minmax) { + if (st->min < f->mn) f->mn = st->min; + if (st->max > f->mx) f->mx = st->max; + return; + } + } + if (f->spans) { f->spans[f->n * 2] = lo; f->spans[f->n * 2 + 1] = hi; } + f->n++; +} + +/* Bounds of a staged key from its directory: per chunk min / max, all-null + * chunks skipped (a SYM chunk with nulls also spans id 0, the null symbol); + * chunks without statistics, and keys without a directory, are scanned by + * pieces. A parted key folds its encoded segments' chunks the same way + * (ray_col_src_parted_chunks) and scans its plain ones. NULL or an owned + * error. */ +static ray_t* agg_key_bounds_staged(const agg_rr_t* krr, uint32_t k, int64_t rows, bool nullable, + int64_t null, int64_t* lo, int64_t* hi) { + ray_col_src_t* src = krr->srcs[k]; + int64_t mn = INT64_MAX, mx = INT64_MIN; + int64_t nch = (rows + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + ray_enc_chunk_stat_t st; + bool dir = nch > 0 && ray_col_src_chunk_stat(src, 0, &st); + ray_t* hdr = NULL; + int64_t* spans; + int64_t* bounds; + int64_t n = 0; + agg_bounds_fold_t pf = { krr->key_types[k], INT64_MAX, INT64_MIN, NULL, 0 }; + ray_t* perr = NULL; + if (src->parted && ray_col_src_encoded(src) && ray_col_src_parted_chunks(src, &pf, agg_bounds_chunk, &perr)) { + /* the parted directory: count the chunks to scan, then list them */ + int64_t ns = pf.n; + spans = (int64_t*)scratch_alloc(&hdr, (size_t)(ns > 0 ? ns : 1) * 4 * sizeof(int64_t)); + if (!spans) return ray_error("oom", NULL); + bounds = spans + (ns > 0 ? ns : 1) * 2; + pf = (agg_bounds_fold_t){ krr->key_types[k], INT64_MAX, INT64_MIN, spans, 0 }; + (void)ray_col_src_parted_chunks(src, &pf, agg_bounds_chunk, &perr); + mn = pf.mn; mx = pf.mx; n = pf.n; + nch = 0; + } else { + if (perr) return perr; + spans = (int64_t*)scratch_alloc(&hdr, (size_t)(nch > 0 ? nch : 1) * 4 * sizeof(int64_t)); + if (!spans) return ray_error("oom", NULL); + bounds = spans + (nch > 0 ? nch : 1) * 2; + } + for (int64_t ch = 0; ch < nch; ch++) { + int64_t b = ch * RAY_ENC_CHUNK, e = b + RAY_ENC_CHUNK < rows ? b + RAY_ENC_CHUNK : rows; + if (dir) { + (void)ray_col_src_chunk_stat(src, ch, &st); + if (krr->key_types[k] == RAY_SYM && st.null_count > 0 && mn > 0) mn = 0; + if ((int64_t)st.null_count >= st.rows) continue; /* all null */ + if (st.has_minmax) { + if (st.min < mn) mn = st.min; + if (st.max > mx) mx = st.max; + continue; + } + } + spans[n * 2] = b; spans[n * 2 + 1] = e; n++; + } + ray_t* err = NULL; + if (n > 0) { + ray_col_src_t* one_src[1] = { src }; + const void* one_plain[1] = { NULL }; + uint8_t one_esz[1] = { krr->esz[k] }; + ray_scan_fail_t fail; + ray_scan_fail_init(&fail); + agg_rr_t rr = { .srcs = one_src, .plain = one_plain, .esz = one_esz, + .key_types = krr->key_types + k, .key_attrs = krr->key_attrs + k, + .n_src = 1, .n_keys = 1, .n_aggs = 0, .fail = &fail, .staged = true }; + agg_key_scan_ctx_t c = { &rr, nullable, null, spans, bounds }; + ray_col_src_advise(src, 0, rows); + ray_pool_t* pool = ray_pool_get(); + bool par = pool && n > 1 && rows >= RAY_PARALLEL_THRESHOLD; + if (par) ray_pool_dispatch_n(pool, agg_key_scan_fn, &c, (uint32_t)n); + else agg_key_scan_fn(&c, 0, 0, n); + err = ray_scan_fail_finish(&fail, par ? pool : NULL); + for (int64_t t = 0; !err && t < n; t++) { + if (bounds[t * 2] < mn) mn = bounds[t * 2]; + if (bounds[t * 2 + 1] > mx) mx = bounds[t * 2 + 1]; + } + } + scratch_free(hdr); + *lo = mn; *hi = mx; + return err; +} + static void agg_key_bounds_parallel(ray_t* key, int64_t rows, bool nullable, int64_t null, int64_t* lo, int64_t* hi) { ray_pool_t* pool = ray_pool_get(); @@ -369,44 +873,56 @@ static void agg_key_bounds_parallel(ray_t* key, int64_t rows, bool nullable, * bounded (AGG_COMPACT_MAX_RANGE codes) are compacted. */ enum { AGG_COMPACT_MAX_RANGE = 1 << 22, /* largest per-key remap table (codes) */ AGG_COMPACT_TRY_SLOTS = 1 << 16 }; /* raw products above this try compaction */ -#define AGG_COMPACT_BITMAP_BUDGET ((size_t)32 << 20) /* transient per-task bitmaps */ typedef struct { - ray_t** key_cols; + const agg_rr_t* krr; /* the keys; staged ones are read by pieces */ const dense_plan_t* dp; const bool* candidate; uint32_t n_keys; int64_t rows; uint32_t tasks; uint64_t** task_bits; /* [tasks][n_keys] private bitmaps, NULL when not a candidate */ + int64_t task; /* the task its pieces belong to (agg_compact_mark_fn) */ } agg_compact_ctx_t; -static void agg_compact_mark_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { +static void agg_compact_mark_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t begin, int64_t limit) { (void)wid; + agg_compact_ctx_t* c = raw; + for (uint32_t k = 0; k < c->n_keys; k++) { + if (!c->candidate[k]) continue; + uint64_t* bits = c->task_bits[(size_t)c->task * c->n_keys + k]; + int64_t mn = c->dp->mins[k]; + bool nullable = c->dp->nullable[k]; + int64_t null = c->dp->nulls[k]; + const int8_t kt = c->krr->key_types[k]; /* hoisted: the bitmap stores */ + const uint8_t ka = v->key_attrs[k]; /* would reload them per row */ + const void* kd = v->key_data[k]; + const int64_t base = v->base; + for (int64_t r = begin; r < limit; r++) { + int64_t val = agg_read_key_i64_raw(kt, ka, kd, r - base); + if (nullable && val == null) continue; + uint64_t code = (uint64_t)(val - mn); + bits[code >> 6] |= UINT64_C(1) << (code & 63); + } + } +} + +static void agg_compact_mark_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { agg_compact_ctx_t* c = raw; for (int64_t task = start; task < end; task++) { int64_t begin = c->rows / c->tasks * task; int64_t limit = task + 1 == c->tasks ? c->rows : c->rows / c->tasks * (task + 1); - for (uint32_t k = 0; k < c->n_keys; k++) { - if (!c->candidate[k]) continue; - uint64_t* bits = c->task_bits[(size_t)task * c->n_keys + k]; - ray_t* kc = c->key_cols[k]; - const void* d = ray_data(kc); - int64_t mn = c->dp->mins[k]; - bool nullable = c->dp->nullable[k]; - int64_t null = c->dp->nulls[k]; - for (int64_t r = begin; r < limit; r++) { - int64_t v = agg_read_key_i64(kc, d, r); - if (nullable && v == null) continue; - uint64_t code = (uint64_t)(v - mn); - bits[code >> 6] |= UINT64_C(1) << (code & 63); - } - } + agg_compact_ctx_t tc = *c; /* no atomics: a per-task copy names the task */ + tc.task = task; + if (!c->krr->staged) { + agg_view_t whole = agg_view_whole(c->krr); + agg_compact_mark_rows(&tc, &whole, wid, begin, limit); + } else (void)agg_walk(c->krr, &tc, agg_compact_mark_rows, wid, begin, limit, begin); } } -static bool agg_dense_plan_compact(ray_t** key_cols, uint32_t n_keys, int64_t nrows, - int64_t dense_limit, dense_plan_t* out) { +static bool agg_dense_plan_compact(const agg_rr_t* krr, uint32_t n_keys, int64_t nrows, + int64_t dense_limit, dense_plan_t* out, ray_t** err) { bool candidate[16]; bool any = false; for (uint32_t k = 0; k < n_keys; k++) { @@ -415,6 +931,27 @@ static bool agg_dense_plan_compact(ray_t** key_cols, uint32_t n_keys, int64_t nr any |= candidate[k]; } if (!any) return false; + /* The keys that are not candidates keep their ranges, and a candidate + * compacts to at least one slot: when those ranges alone overflow the + * limit no marking can make the plan fit (the check below would + * fail), so the keys are not read. */ + { + int64_t fixed = 1; + for (uint32_t k = 0; k < n_keys; k++) { + if (candidate[k]) continue; + if (out->ranges[k] <= 0 || fixed > dense_limit / out->ranges[k]) return false; + fixed *= out->ranges[k]; + } + } + /* Only the candidates are read: the others' staged sources leave the + * walk (agg_compact_mark_rows never reads them). */ + ray_col_src_t* msrc[16]; + agg_rr_t mrr = *krr; + if (krr->staged && krr->n_src <= 16) { + for (uint32_t i = 0; i < krr->n_src; i++) msrc[i] = i < n_keys && !candidate[i] ? NULL : krr->srcs[i]; + mrr.srcs = msrc; + krr = &mrr; + } ray_pool_t* pool = ray_pool_get(); uint32_t tasks = pool && nrows >= RAY_PARALLEL_THRESHOLD ? ray_pool_total_workers(pool) : 1; if ((int64_t)tasks > nrows) tasks = (uint32_t)nrows; @@ -436,10 +973,15 @@ static bool agg_dense_plan_compact(ray_t** key_cols, uint32_t n_keys, int64_t nr cursor += (out->ranges[k] - out->nullable[k] + 63) / 64; } } - agg_compact_ctx_t c = { .key_cols = key_cols, .dp = out, .candidate = candidate, + agg_compact_ctx_t c = { .krr = krr, .dp = out, .candidate = candidate, .n_keys = n_keys, .rows = nrows, .tasks = tasks, .task_bits = task_bits }; + if (krr->staged) ray_scan_fail_init(krr->fail); if (tasks > 1) ray_pool_dispatch_n(pool, agg_compact_mark_fn, &c, tasks); else agg_compact_mark_fn(&c, 0, 0, 1); + if (krr->staged && (*err = ray_scan_fail_finish(krr->fail, tasks > 1 ? pool : NULL)) != NULL) { + ray_free_raw(bits); ray_free_raw(task_bits); + return false; + } /* Reduce task bitmaps into task 0, count used codes, re-check the product. */ int64_t used[16]; int64_t total = 1; @@ -546,7 +1088,7 @@ enum { AGG_EST_SAMPLE = AGG_EST_SAMPLE_ROWS, AGG_EST_PREFETCH = 16, * one more value), a SYM's code. */ static inline int64_t agg_est_read(const void* d, int8_t t, uint8_t attrs, int64_t r) { switch (t) { - case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)d)[r]; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)d)[r]; case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)d)[r]; case RAY_I16: return ((const int16_t*)d)[r]; case RAY_U8: case RAY_BOOL: return ((const uint8_t*)d)[r]; @@ -814,13 +1356,96 @@ int64_t agg_group_card_estimate(ray_t** key_cols, uint32_t n_keys, int64_t nrows return total; } -bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, - const agg_vtable_t** vts, uint32_t n_aggs, - int64_t nrows, dense_plan_t* out) { - (void)vts; (void)n_aggs; /* agg kind no longer gates dense eligibility */ +/* The bytes the calling heap can take before the anonymous watermark: the + * room under it, with the committed blocks the heap can reuse added back. + * 0 when the watermark (the RAM) is unknown. */ +static int64_t agg_dense_wide_room(void) { + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return 0; + int64_t room = wm - ray_heap_anon_committed() + ray_heap_anon_reusable(); + return room > 0 ? room : 0; +} + +/* Whether a shared slab of this plan holds u32 counters (4 bytes a slot): every + * aggregate is COUNT, so one counter per slot serves them all, and the input + * has at most UINT32_MAX rows, so no slot's count can pass UINT32_MAX. With + * more rows the slab keeps the 8-byte count states. */ +static bool agg_count32_slab(const agg_vtable_t** vts, uint32_t n_aggs, int64_t rows) { + if (n_aggs == 0 || rows > (int64_t)UINT32_MAX) return false; + const agg_vtable_t* cnt = agg_resolve(OP_COUNT, RAY_I64); + for (uint32_t a = 0; a < n_aggs; a++) if (vts[a] != cnt) return false; + return true; +} + +/* A wide plan spans at most this many slots per input row: a slab much larger + * than the input is mostly empty, and the radix routes answer from the rows. */ +#define AGG_WIDE_RANGE_PER_ROW 16 + +/* The most slots a wide dense plan (a range past the row count) may span: one + * four-byte counter per slot must fit the room, and a slot is a uint32. */ +static int64_t agg_dense_wide_slots(void) { + int64_t s = agg_dense_wide_room() / 4; + return s < (int64_t)UINT32_MAX ? s : (int64_t)UINT32_MAX; +} + +/* Whether the single key has many groups: of 1024 rows spread over the table, + * at least a quarter hold distinct keys. A wide dense plan pays for its + * whole range, so a key with a few groups spread over a wide range (which + * the table stack and the hash routes answer from their own few entries) + * does not take it. *err is set on a failed range read. */ +static bool agg_wide_populated(ray_t* key_col, const agg_rr_t* rr, int64_t nrows, ray_t** err) { + enum { SAMPLES = 1024, CAP = 2048 }; + *err = NULL; + if (nrows < SAMPLES) return false; + int64_t seen[CAP]; + bool used[CAP]; + memset(used, 0, sizeof used); + agg_curs_t cs; cs.cur = NULL; + if (rr->staged && !agg_curs_init(&cs, rr)) { *err = ray_error("oom", NULL); return false; } + int64_t step = nrows / SAMPLES, distinct = 0; + if (!rr->staged && ray_col_cold(key_col)) + for (int i = 0; i < SAMPLES; i++) + ray_col_want_row(key_col, i * step + (int64_t)(ray_hash_i64(i) % (uint64_t)step)); + for (int i = 0; i < SAMPLES && !*err; i++) { + int64_t v = agg_key_at(rr, &cs, 0, i * step + (int64_t)(ray_hash_i64(i) % (uint64_t)step), err); + if (*err) break; + uint32_t at = ray_hash_i64(v) & (CAP - 1); + while (used[at] && seen[at] != v) at = (at + 1) & (CAP - 1); + if (!used[at]) { used[at] = true; seen[at] = v; distinct++; } + } + agg_curs_free(&cs, rr); + return !*err && distinct * 4 >= SAMPLES; +} + +/* Whether a single-key plan of total_slots runs as the one shared slab of a + * wide plan: every aggregate updates a shared state, the slab and its + * occupancy bits fit three quarters of the room under the anonymous + * watermark, and the key shows many groups (agg_wide_populated). The + * caller checks the plan's shape (pool, rows, streaming states, no group + * limit, one key). *err is set on a failed range read. */ +static bool agg_wide_shared_fits(const agg_vtable_t** vts, uint32_t n_aggs, size_t block, + int64_t total_slots, int64_t eff_n, ray_t* key_col, + const agg_rr_t* rr, int64_t nrows, ray_t** err) { + *err = NULL; + if (agg_no_wide_dense) return false; + for (uint32_t a = 0; a < n_aggs; a++) + if (vts[a]->update_shared == NULL) return false; + size_t slot_bytes = agg_count32_slab(vts, n_aggs, eff_n) ? sizeof(uint32_t) : block; + double need = (double)total_slots * (double)slot_bytes + (double)total_slots / 8; + if (need > (double)agg_dense_wide_room() / 4 * 3) return false; + return agg_wide_populated(key_col, rr, nrows, err); +} + +/* agg_dense_plan over keys bound for range reads: krr's staged keys (their + * key_cols are stand-ins) take their bounds from the directory or by + * pieces. False with *err set: a range error. */ +static bool agg_dense_plan_src(ray_t** key_cols, const agg_rr_t* krr, uint32_t n_keys, bool allow_wide, + int64_t nrows, dense_plan_t* out, ray_t** err) { + *err = NULL; out->ok = false; out->n_keys = n_keys; out->compacted = false; + out->wide = false; memset(out->remap, 0, sizeof(out->remap)); memset(out->inverse, 0, sizeof(out->inverse)); /* Dense direct-index routing self-limits to <=16 keys: dense_plan_t's @@ -873,7 +1498,10 @@ bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, } int64_t mn, mx; - agg_key_bounds_parallel(kc, nrows, out->nullable[k], out->nulls[k], &mn, &mx); + if (krr && krr->srcs[k]) { + if ((*err = agg_key_bounds_staged(krr, k, nrows, out->nullable[k], out->nulls[k], &mn, &mx)) != NULL) + return false; + } else agg_key_bounds_parallel(kc, nrows, out->nullable[k], out->nulls[k], &mn, &mx); if (!agg_dense_range(out, k, mn, mx)) return false; } @@ -888,6 +1516,17 @@ bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, if (total > dense_limit / rng) overflow = true; else total *= rng; } + /* One key whose range passes the row count: a slab the size of the range + * is admitted when it is at most AGG_WIDE_RANGE_PER_ROW slots per row and + * fits the room under the memory watermark (agg_dense_wide_slots). Its + * answer is the same; only the shared strategy runs it (the caller drops + * the plan otherwise). */ + if (overflow && n_keys == 1 && allow_wide && out->ranges[0] <= AGG_WIDE_RANGE_PER_ROW * nrows && + out->ranges[0] <= agg_dense_wide_slots()) { + overflow = false; + out->wide = true; + total = out->ranges[0]; + } if (overflow || (n_keys >= 2 && total > AGG_COMPACT_TRY_SLOTS)) { /* Raw ranges multiply out too far — or far enough past a * cache-resident slab that sparse keys would waste it (a W16 SYM key @@ -895,7 +1534,8 @@ bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, * they use and retry the packing over the compacted ranges. Keys * whose every code is used keep their raw range. */ bool compacted_ok = n_keys >= 2 && - agg_dense_plan_compact(key_cols, n_keys, nrows, dense_limit, out); + agg_dense_plan_compact(krr, n_keys, nrows, dense_limit, out, err); + if (*err) return false; if (overflow && !compacted_ok) return false; total = 1; for (uint32_t k = 0; k < n_keys; k++) { @@ -915,6 +1555,47 @@ bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, return true; } +/* The keys of plain columns, as a keys-only source set (nothing staged). */ +static agg_rr_t agg_keys_plain_rr(ray_t** key_cols, uint32_t n_keys, ray_t** hdr, + ray_scan_fail_t* fail) { + agg_rr_t rr = { .n_src = n_keys, .n_keys = n_keys, .fail = fail }; + size_t nk = n_keys ? n_keys : 1; + void* blk = scratch_calloc(hdr, nk * (2 * sizeof(void*) + 3)); + if (!blk) { rr.n_src = rr.n_keys = 0; return rr; } + ray_col_src_t** srcs = (ray_col_src_t**)blk; + const void** plain = (const void**)(srcs + nk); + uint8_t* esz = (uint8_t*)(plain + nk); + int8_t* types = (int8_t*)(esz + nk); + uint8_t* attrs = (uint8_t*)(types + nk); + for (uint32_t k = 0; k < n_keys; k++) { + plain[k] = ray_data(key_cols[k]); + types[k] = key_cols[k]->type; + attrs[k] = key_cols[k]->attrs; + esz[k] = ray_sym_elem_size(key_cols[k]->type, key_cols[k]->attrs); + } + rr.srcs = srcs; rr.plain = plain; rr.esz = esz; rr.key_types = types; rr.key_attrs = attrs; + return rr; +} + +bool agg_dense_plan(ray_t** key_cols, uint32_t n_keys, + const agg_vtable_t** vts, uint32_t n_aggs, + int64_t nrows, dense_plan_t* out) { + (void)vts; (void)n_aggs; /* agg kind no longer gates dense eligibility */ + out->ok = false; /* a failed carve leaves a plan agg_dense_plan_free takes */ + out->compacted = false; + memset(out->remap, 0, sizeof(out->remap)); + memset(out->inverse, 0, sizeof(out->inverse)); + ray_t* hdr = NULL; + ray_scan_fail_t fail; + ray_scan_fail_init(&fail); + agg_rr_t krr = agg_keys_plain_rr(key_cols, n_keys, &hdr, &fail); + ray_t* err = NULL; + bool ok = krr.n_keys == n_keys && agg_dense_plan_src(key_cols, &krr, n_keys, false, nrows, out, &err); + if (err) ray_error_free(err); /* plain keys read in place: no range errors */ + scratch_free(hdr); + return ok; +} + /* Per-op result-column-name suffix, mirroring emit_agg_columns (group.c). * Returns "" / 0 for ops without a suffix. */ static const char* agg_name_suffix(uint16_t agg_op, size_t* slen_out) { @@ -1017,7 +1698,7 @@ static bool key_null_in_range(const ray_t* v, int64_t start, int64_t end) { switch (v->type) { case RAY_F64: { const double* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] != d[i]); break; } case RAY_F32: { const float* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] != d[i]); break; } - case RAY_I64: case RAY_TIMESTAMP: { const int64_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I64); break; } + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { const int64_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I64); break; } case RAY_I32: case RAY_DATE: case RAY_TIME: { const int32_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I32); break; } case RAY_I16: { const int16_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[i] == NULL_I16); break; } case RAY_GUID: { const uint64_t* d = p; for (int64_t i = s; i < e; i++) any |= (d[2 * i] == 0 && d[2 * i + 1] == 0); break; } @@ -1044,7 +1725,7 @@ static void key_null_scan_fn(void* raw, uint32_t wid, int64_t start, int64_t end void ray_group_key_settle_nulls(ray_t* kc) { if (!kc || RAY_IS_ERR(kc) || !(kc->attrs & RAY_ATTR_HAS_NULLS)) return; switch (kc->type) { - case RAY_F64: case RAY_F32: case RAY_I64: case RAY_TIMESTAMP: + case RAY_F64: case RAY_F32: case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: case RAY_GUID: break; default: return; } @@ -1101,7 +1782,7 @@ ray_t* ray_group_gather(ray_t* src_col, const int64_t* first_row, int64_t n) { switch (src_col->type) { case RAY_F64: GATHER_NULL(double, NULL_F64); break; case RAY_F32: GATHER_NULL(float, NULL_F32); break; - case RAY_I64: case RAY_TIMESTAMP: GATHER_NULL(int64_t, NULL_I64); break; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: GATHER_NULL(int64_t, NULL_I64); break; case RAY_I32: case RAY_DATE: case RAY_TIME: GATHER_NULL(int32_t, NULL_I32); break; case RAY_I16: GATHER_NULL(int16_t, NULL_I16); break; default: break; /* SYM/GUID use zero payloads; BOOL/U8 have no null. */ @@ -1273,36 +1954,37 @@ static int64_t agg_sel_cursor_next(agg_sel_cursor_t* c, int64_t* rows) { return n; } -/* Gather one chunk's value column (native esz) into a small dense buffer. +/* Gather one chunk's value column (native esz) into a small dense buffer: + * rows[i] read at rows[i] - base (src is the view's pointer at row base). * COUNT (val_data == NULL) needs no gather — returns without touching dst. */ static inline void agg_sel_gather_vals(void* dst, const void* src, uint8_t esz, - const int64_t* rows, int64_t n) { + const int64_t* rows, int64_t n, int64_t base) { if (!src || esz == 0) return; const char* s = (const char*)src; switch (esz) { case 8: { int64_t* dd = (int64_t*)dst; const int64_t* ss = (const int64_t*)s; - for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i]]; + for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i] - base]; break; } case 4: { int32_t* dd = (int32_t*)dst; const int32_t* ss = (const int32_t*)s; - for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i]]; + for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i] - base]; break; } case 2: { int16_t* dd = (int16_t*)dst; const int16_t* ss = (const int16_t*)s; - for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i]]; + for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i] - base]; break; } case 1: { uint8_t* dd = (uint8_t*)dst; const uint8_t* ss = (const uint8_t*)s; - for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i]]; + for (int64_t i = 0; i < n; i++) dd[i] = ss[rows[i] - base]; break; } default: { /* general gather, correct for any element width */ char* dd = (char*)dst; - for (int64_t i = 0; i < n; i++) memcpy(dd + i * esz, s + rows[i] * esz, esz); + for (int64_t i = 0; i < n; i++) memcpy(dd + i * esz, s + (rows[i] - base) * esz, esz); break; } } @@ -1310,51 +1992,144 @@ static inline void agg_sel_gather_vals(void* dst, const void* src, uint8_t esz, /* Per-dispatch descriptor tables, sized from ext->n_keys / ext->n_aggs. * One carve; 8-byte arrays first, then narrower. Replaces the fixed - * [16] blocks that used to cap the engine at 16 keys/aggs. */ + * [16] blocks that used to cap the engine at 16 keys/aggs. + * + * key_data, val_data and val2_data are one array (the sources' row-0 + * pointers, NULL for a staged source and for COUNT), key_srcs, val_srcs + * and val2_srcs another (the staged sources), key_esz, val_esz and + * val2_esz a third: rr reads them as flat [n_keys + 2 * n_aggs] arrays. + * val_id / val2_id name each input whether staged or plain (its row-0 + * pointer, or its source; NULL: no input): the layouts and the phases that + * read no column test presence and identity on them. */ typedef struct { - ray_t* hdr; - const void** key_data; - const void** val_data; const void** val2_data; - int64_t* agg_syms; - int8_t* val_types; int8_t* val2_types; - bool* val_hasnull; bool* val2_hasnull; - uint8_t* val_esz; uint8_t* val2_esz; + ray_t* hdr; + const void** key_data; + const void** val_data; const void** val2_data; + ray_col_src_t** key_srcs; + ray_col_src_t** val_srcs; ray_col_src_t** val2_srcs; + const void** val_id; const void** val2_id; + int64_t* agg_syms; + uint8_t* key_esz; + int8_t* key_types; uint8_t* key_attrs; + int8_t* val_types; int8_t* val2_types; + bool* val_hasnull; bool* val2_hasnull; + uint8_t* val_esz; uint8_t* val2_esz; + bool staged; /* some key or input is read by range */ + agg_rr_t rr; + agg_view_t whole; + ray_scan_fail_t fail; /* the strategy's dispatches (R-FAIL) */ } agg_desc_t; +/* A value column: bound, decisions from the source; the payload pointer is + * captured only when the column can be read in place (ray_col_src_ready: + * generation 0, or a published materialization). Otherwise *plain stays + * NULL and the strategies read the source by range. Absent leaves *src + * NULL; a failed bind sets *err. The agg shapes admitted before this + * point never name a partition key or a sliced parted column, so a source + * that does not bind is an error here, not a fall back to raw reads. */ +static bool agg_desc_value(ray_graph_t* g, ray_t* tbl, int64_t sym, const void** plain, + ray_col_src_t** src, ray_t** err) { + *plain = NULL; *src = NULL; + if (ray_col_bind_declines(tbl, sym)) { + *err = ray_error("nyi", "aggregate input is not a bindable column"); + return false; + } + *src = ray_graph_bind_col(g, tbl, sym, err); + if (!*src) return *err == NULL; + ray_t* ready = ray_col_src_ready(*src); /* ready-only: never decodes */ + if (ready && !RAY_IS_PARTED(ready->type)) *plain = ray_data(ready); + return true; +} + +/* False with *err NULL: out of memory; false with an owned *err: a column + * bind failed (the caller returns it). A key whose column is a stand-in + * (its source is bound and not ready as that column: exec_group_v2_run_inner) + * and an input that is not ready are staged: read by range. */ static bool agg_desc_init(agg_desc_t* d, ray_graph_t* g, ray_op_ext_t* ext, - ray_t* tbl, ray_t** key_cols) { + ray_t* tbl, ray_t** key_cols, ray_t** err) { + *err = NULL; uint32_t nk = ext->n_keys, na = ext->n_aggs; - size_t n8 = (size_t)nk + 3u * na; /* key_data,val_data,val2_data,agg_syms */ - size_t n1 = 6u * na; /* types/hasnull/esz pairs */ - d->key_data = (const void**)scratch_alloc(&d->hdr, n8 * 8 + n1); + uint32_t ns = nk + 2u * na; + size_t n8 = 2u * (size_t)ns + 3u * na; /* plain, srcs, ids, agg_syms */ + size_t n1 = 3u * (size_t)nk + 6u * na; /* esz, key types/attrs, val types/hasnull */ + d->key_data = (const void**)scratch_calloc(&d->hdr, n8 * 8 + n1 + 1); if (!d->key_data) return false; d->val_data = d->key_data + nk; d->val2_data = d->val_data + na; - d->agg_syms = (int64_t*)(d->val2_data + na); - d->val_types = (int8_t*)(d->agg_syms + na); + d->key_srcs = (ray_col_src_t**)(d->val2_data + na); + d->val_srcs = d->key_srcs + nk; + d->val2_srcs = d->val_srcs + na; + d->val_id = (const void**)(d->val2_srcs + na); + d->val2_id = d->val_id + na; + d->agg_syms = (int64_t*)(d->val2_id + na); + d->key_esz = (uint8_t*)(d->agg_syms + na); + d->val_esz = d->key_esz + nk; + d->val2_esz = d->val_esz + na; + d->key_types = (int8_t*)(d->val2_esz + na); + d->key_attrs = (uint8_t*)(d->key_types + nk); + d->val_types = (int8_t*)(d->key_attrs + nk); d->val2_types = d->val_types + na; d->val_hasnull = (bool*)(d->val2_types + na); d->val2_hasnull = d->val_hasnull + na; - d->val_esz = (uint8_t*)(d->val2_hasnull + na); - d->val2_esz = d->val_esz + na; - for (uint32_t k = 0; k < nk; k++) d->key_data[k] = ray_data(key_cols[k]); + d->staged = false; + for (uint32_t k = 0; k < nk; k++) { + ray_t* kc = key_cols[k]; + d->key_types[k] = kc->type; + d->key_attrs[k] = kc->attrs; + d->key_esz[k] = ray_sym_elem_size(kc->type, kc->attrs); + d->key_data[k] = ray_data(kc); + ray_op_ext_t* kext = find_ext(g, ext->keys[k]); + if (!kext || ray_col_bind_declines(tbl, kext->sym)) continue; /* today's column */ + ray_col_src_t* ks = ray_graph_bind_col(g, tbl, kext->sym, err); + if (*err) goto fail; + if (ks && ray_col_src_ready(ks) != kc) { /* kc is the stand-in */ + d->key_srcs[k] = ks; + d->key_data[k] = NULL; + d->staged = true; + } + } for (uint32_t a = 0; a < na; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); d->agg_syms[a] = ie ? ie->sym : 0; - ray_t* vc = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_get_col(tbl, ie->sym) : NULL; - d->val_data[a] = vc ? ray_data(vc) : NULL; - d->val_types[a] = vc ? vc->type : RAY_I64; - d->val_hasnull[a] = vc ? ray_vec_may_have_nulls(vc) : false; - d->val_esz[a] = vc ? col_esz(vc) : 0; + const void* vp = NULL; + ray_col_src_t* vs = NULL; + if (ext->agg_ops[a] != OP_COUNT && ie && + !agg_desc_value(g, tbl, ie->sym, &vp, &vs, err)) goto fail; + d->val_data[a] = vp; + d->val_srcs[a] = vs && !vp ? vs : NULL; + d->val_types[a] = vs ? vs->type : RAY_I64; + d->val_hasnull[a] = vs ? vs->may_null : false; + d->val_esz[a] = vs ? ray_col_src_esz(vs) : 0; + d->val_id[a] = vp ? vp : (const void*)vs; + d->staged |= d->val_srcs[a] != NULL; /* Binary agg (pearson): resolve the y-side column from agg_ins2[a]. */ - ray_t* vc2 = (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) - ? ray_table_get_col(tbl, find_ext(g, ext->agg_ins2[a])->sym) : NULL; - d->val2_data[a] = vc2 ? ray_data(vc2) : NULL; - d->val2_types[a] = vc2 ? vc2->type : RAY_I64; - d->val2_hasnull[a] = vc2 ? ray_vec_may_have_nulls(vc2) : false; - d->val2_esz[a] = vc2 ? col_esz(vc2) : 0; - } + const void* vp2 = NULL; + ray_col_src_t* vs2 = NULL; + if (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE && + !agg_desc_value(g, tbl, find_ext(g, ext->agg_ins2[a])->sym, &vp2, &vs2, err)) goto fail; + d->val2_data[a] = vp2; + d->val2_srcs[a] = vs2 && !vp2 ? vs2 : NULL; + d->val2_types[a] = vs2 ? vs2->type : RAY_I64; + d->val2_hasnull[a] = vs2 ? vs2->may_null : false; + d->val2_esz[a] = vs2 ? ray_col_src_esz(vs2) : 0; + d->val2_id[a] = vp2 ? vp2 : (const void*)vs2; + d->staged |= d->val2_srcs[a] != NULL; + } + ray_scan_fail_init(&d->fail); + d->rr = (agg_rr_t){ .srcs = d->key_srcs, .plain = d->key_data, .esz = d->key_esz, + .key_types = d->key_types, .key_attrs = d->key_attrs, + .n_src = ns, .n_keys = nk, .n_aggs = na, .fail = &d->fail, .staged = d->staged }; + d->whole = agg_view_whole(&d->rr); return true; +fail: + scratch_free(d->hdr); d->hdr = NULL; + return false; +} + +/* One read-ahead hint per staged source over the rows a strategy reads. */ +static void agg_desc_advise(const agg_desc_t* d, int64_t nrows) { + for (uint32_t i = 0; d->staged && i < d->rr.n_src; i++) + if (d->rr.srcs[i]) ray_col_src_advise(d->rr.srcs[i], 0, nrows); } static void agg_desc_free(agg_desc_t* d) { scratch_free(d->hdr); d->hdr = NULL; } @@ -1378,8 +2153,9 @@ static bool agg_vo_init(agg_vo_t* vo, ray_graph_t* g, ray_op_ext_t* ext, ray_t* vo->block = 0; for (uint32_t a = 0; a < na; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); - ray_t* vc = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_get_col(tbl, ie->sym) : NULL; - int8_t in_type = vc ? vc->type : RAY_I64; + ray_col_meta_t vm; + bool vh = ext->agg_ops[a] != OP_COUNT && ie && agg_col_meta(g, tbl, ie->sym, &vm); + int8_t in_type = vh ? vm.type : RAY_I64; vo->vts[a] = agg_resolve(ext->agg_ops[a], in_type); vo->off[a] = vo->block; vo->block += vo->vts[a]->state_size; @@ -1430,32 +2206,37 @@ static void agg_sel_scratch_free(agg_sel_scratch_t* sc) { /* Accumulate one decoded chunk (rows[], gid[] indexed [0,n)) into `states` for * every aggregate, gathering each agg's input values for this chunk's ORIGINAL * rows into the reused scratch buffers first. `states` points at agg 0's slot 0 - * (i.e. states_base + off applied per agg by the kernel via off[a]). Returns 0, - * or -1 on scratch OOM (sets sc->oom). */ -static int agg_sel_accum_chunk(const agg_valdesc_t* vd, agg_sel_scratch_t* sc, + * (i.e. states_base + off applied per agg by the kernel via off[a]). The + * values come from view v (rows read at rows[i] - v->base: the whole columns, + * or a run of rows inside the staged sources' views). Returns 0, or -1 on + * scratch OOM (sets sc->oom). shared: the kernels' update_shared (atomic) in + * place of update_batch, for a slab several tasks update at once. */ +static int agg_sel_accum_chunk(const agg_valdesc_t* vd, const agg_view_t* v, agg_sel_scratch_t* sc, char* states, const uint32_t* gid, - const int64_t* rows, int64_t n) { + const int64_t* rows, int64_t n, bool shared) { for (uint32_t a = 0; a < vd->n_aggs; a++) { const agg_vtable_t* vt = vd->vts[a]; if (vt->update_batch2) { /* binary agg (pearson) */ uint8_t ez = vd->val_esz[a], ez2 = vd->val2_esz[a]; if (!sc->gv[a]) { sc->gv[a] = ray_alloc_raw((size_t)AGG_SEL_CHUNK * (ez ? ez : 1)); if (!sc->gv[a]) { sc->oom = 1; return -1; } } if (!sc->gy[a]) { sc->gy[a] = ray_alloc_raw((size_t)AGG_SEL_CHUNK * (ez2 ? ez2 : 1)); if (!sc->gy[a]) { sc->oom = 1; return -1; } } - agg_sel_gather_vals(sc->gv[a], vd->val_data[a], ez, rows, n); - agg_sel_gather_vals(sc->gy[a], vd->val2_data[a], ez2, rows, n); + agg_sel_gather_vals(sc->gv[a], v->val_data[a], ez, rows, n, v->base); + agg_sel_gather_vals(sc->gy[a], v->val2_data[a], ez2, rows, n, v->base); ray_valid_t vx = { sc->gv[a], vd->val_types[a], vd->val_hasnull[a] }; ray_valid_t vy = { sc->gy[a], vd->val2_types[a], vd->val2_hasnull[a] }; vt->update_batch2(states + vd->off[a], vd->block, gid, sc->gv[a], sc->gy[a], &vx, &vy, n, NULL); - } else if (vd->val_data[a]) { /* unary agg over a column */ + } else if (v->val_data[a]) { /* unary agg over a column */ uint8_t ez = vd->val_esz[a]; if (!sc->gv[a]) { sc->gv[a] = ray_alloc_raw((size_t)AGG_SEL_CHUNK * (ez ? ez : 1)); if (!sc->gv[a]) { sc->oom = 1; return -1; } } - agg_sel_gather_vals(sc->gv[a], vd->val_data[a], ez, rows, n); + agg_sel_gather_vals(sc->gv[a], v->val_data[a], ez, rows, n, v->base); ray_valid_t valid = { sc->gv[a], vd->val_types[a], vd->val_hasnull[a] }; - vt->update_batch(states + vd->off[a], vd->block, gid, sc->gv[a], &valid, n, NULL); + if (shared) vt->update_shared(states + vd->off[a], vd->block, gid, sc->gv[a], &valid, n); + else vt->update_batch(states + vd->off[a], vd->block, gid, sc->gv[a], &valid, n, NULL); } else { /* COUNT (no value gather) */ ray_valid_t valid = { NULL, vd->val_types[a], false }; - vt->update_batch(states + vd->off[a], vd->block, gid, NULL, &valid, n, NULL); + if (shared) vt->update_shared(states + vd->off[a], vd->block, gid, NULL, &valid, n); + else vt->update_batch(states + vd->off[a], vd->block, gid, NULL, &valid, n, NULL); } } return 0; @@ -1472,8 +2253,7 @@ static int agg_sel_accum_chunk(const agg_valdesc_t* vd, agg_sel_scratch_t* sc, * the same dense direct-index bound as agg_dense_plan and take v2's unbounded * hash/radix path; the fixed [16] mins/ranges/strides are only read at <=16. */ typedef struct { - ray_t** key_cols; - const void** key_data; + const agg_rr_t* krr; /* the keys: plain ones read in place, staged by R-SPARSE */ const bool* nullable; const int64_t* nulls; uint32_t n_keys; @@ -1481,45 +2261,582 @@ typedef struct { const int64_t* sel_prefix; int64_t n_sel; uint32_t tasks; + const int64_t* spans; /* [tasks][2] selected-ordinal ranges; NULL: n_sel split evenly */ int64_t* task_bounds; /* [tasks][2][n_keys]: min row, max row per key */ } agg_sel_bounds_ctx_t; +/* The min/max of every key over rows[ib, ie) of a chunk. */ +typedef struct { const agg_sel_bounds_ctx_t* c; const int64_t* rows; int64_t* mins; int64_t* maxs; } agg_sel_bounds_run_t; +/* One out-of-line copy, compiled as before, when it was also the staged + * walk's body (address taken): the plain pass keeps its instance (the + * staged pass reads key by key, agg_sel_bounds_staged). noipa is + * GCC-only (clang rejects the attribute). */ +#if defined(__GNUC__) && !defined(__clang__) +#define AGG_ONE_COPY __attribute__((noipa)) +#else +#define AGG_ONE_COPY __attribute__((noinline)) +#endif +AGG_ONE_COPY static void agg_sel_bounds_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t ib, int64_t ie) { + (void)wid; + agg_sel_bounds_run_t* t = raw; + const agg_sel_bounds_ctx_t* c = t->c; + const int64_t* rows = t->rows; + const int64_t base = v->base; + for (uint32_t k = 0; k < c->n_keys; k++) { + int64_t mn = t->mins[k], mx = t->maxs[k]; + const bool nullable = c->nullable[k]; + const int64_t null = c->nulls[k]; + const void* kd = v->key_data[k]; + /* the key's width switched once per run, not per row */ +#define SEL_BOUNDS_LOOP(LD) for (int64_t i = ib; i < ie; i++) { \ + int64_t val = (LD); \ + if (nullable && val == null) continue; \ + if (val < mn) mn = val; \ + if (val > mx) mx = val; \ + } + switch (c->krr->key_types[k]) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: SEL_BOUNDS_LOOP(((const int64_t*)kd)[rows[i] - base]); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: SEL_BOUNDS_LOOP(((const int32_t*)kd)[rows[i] - base]); break; + case RAY_I16: SEL_BOUNDS_LOOP(((const int16_t*)kd)[rows[i] - base]); break; + case RAY_U8: case RAY_BOOL: SEL_BOUNDS_LOOP(((const uint8_t*)kd)[rows[i] - base]); break; + default: SEL_BOUNDS_LOOP(agg_vkey(v, c->krr->key_types, k, rows[i])); break; + } +#undef SEL_BOUNDS_LOOP + t->mins[k] = mn; t->maxs[k] = mx; + } +} + +/* The min/max of key k over rows[ib, ie), element 0 of data being row + * `base` (the SEL_BOUNDS_LOOP fold of agg_sel_bounds_rows, for one key). */ +static void agg_sel_bounds_fold(const agg_sel_bounds_ctx_t* c, uint32_t k, uint8_t attrs, const void* kd, + int64_t base, const int64_t* rows, int64_t ib, int64_t ie, + int64_t* mnp, int64_t* mxp) { + int64_t mn = *mnp, mx = *mxp; + const bool nullable = c->nullable[k]; + const int64_t null = c->nulls[k]; +#define SEL_BOUNDS_LOOP(LD) for (int64_t i = ib; i < ie; i++) { \ + int64_t val = (LD); \ + if (nullable && val == null) continue; \ + if (val < mn) mn = val; \ + if (val > mx) mx = val; \ + } + switch (c->krr->key_types[k]) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: SEL_BOUNDS_LOOP(((const int64_t*)kd)[rows[i] - base]); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: SEL_BOUNDS_LOOP(((const int32_t*)kd)[rows[i] - base]); break; + case RAY_I16: SEL_BOUNDS_LOOP(((const int16_t*)kd)[rows[i] - base]); break; + case RAY_U8: case RAY_BOOL: SEL_BOUNDS_LOOP(((const uint8_t*)kd)[rows[i] - base]); break; + default: SEL_BOUNDS_LOOP(agg_read_key_i64_raw(c->krr->key_types[k], attrs, kd, rows[i] - base)); break; + } +#undef SEL_BOUNDS_LOOP + *mnp = mn; *mxp = mx; +} + +/* Run r's logical value of a CONST / RLE view (ray_enc_runs' value), + * inlined for the merges below, which walk a view's runs against sorted + * rows directly (one compare per run that holds none of them). */ +static inline int64_t agg_run_value(const ray_enc_vview_t* v, uint32_t r) { + const ray_enc_kind_t k = v->k; + uint64_t b; + switch (k.T) { + case 8: b = v->run_vals.b[r]; break; + case 16: b = v->run_vals.h[r]; break; + case 32: b = v->run_vals.s[r]; break; + default: return (int64_t)v->run_vals.q[r]; + } + const uint64_t m = (1ull << k.T) - 1; + return k.is_signed && (b >> (k.T - 1)) & 1 ? (int64_t)(b | ~m) : (int64_t)b; +} +/* The first run of v ending after local row x. */ +static inline uint32_t agg_run_at(const ray_enc_vview_t* v, int64_t x) { + uint32_t l = 0, h = v->n_runs; + while (l < h) { uint32_t mid = l + (h - l) / 2; if ((int64_t)v->run_ends.h[mid] <= x) l = mid + 1; else h = mid; } + return l; +} + +/* The bounds over a run view: the runs holding some of the ascending rows + * rows[i, j) (inside the view's vector, row 0 at vlo) fold their value, a + * null skipped as the per-row fold skips it. */ +static void agg_sel_bounds_runs(const ray_enc_vview_t* v, const int64_t* rows, int64_t i, int64_t j, int64_t vlo, + bool nullable, int64_t null, int64_t* mnp, int64_t* mxp) { + int64_t mn = *mnp, mx = *mxp; + for (uint32_t r = agg_run_at(v, rows[i] - vlo); r < v->n_runs && i < j; r++) { + const int64_t e = vlo + v->run_ends.h[r]; + if (rows[i] >= e) continue; /* none of the rows in this run */ + const int64_t x = agg_run_value(v, r); + if (!(nullable && x == null)) { if (x < mn) mn = x; if (x > mx) mx = x; } + int64_t h = j; /* past the run's rows */ + while (i < h) { int64_t mid = i + (h - i) / 2; if (rows[mid] < e) i = mid + 1; else h = mid; } + } + *mnp = mn; *mxp = mx; +} + +/* agg_sel_bounds_rows of a staged context over the ascending rows[0, cn), + * key by key: a plain key in place; a staged key's CONST / RLE vector + * (ray_col_src_runview) on its runs (P3 Task 3b: no vector decoded); a + * vector holding at most RAY_COL_POINT_ROWS of the rows point-read (open + * decision D2: no vector decoded), any other vector, or one whose read + * declines, through the key's cursor view. A point-served value is never + * null and lies inside its vector's statistics, so nests inside its + * chunk's (the guard's rule); a run view under the guard checks its run + * values against the chunk's statistics. NULL or an owned error. */ +static __attribute__((noinline)) ray_t* agg_sel_bounds_staged(agg_sel_bounds_run_t* t, agg_curs_t* cs, int64_t cn) { + const agg_sel_bounds_ctx_t* c = t->c; + const agg_rr_t* krr = c->krr; + const int64_t* rows = t->rows; + ray_enc_vview_t view; /* a key vector's runs: on the task's stack */ + for (uint32_t k = 0; k < c->n_keys; k++) { + ray_col_src_t* src = krr->srcs[k]; + if (!src) { + agg_sel_bounds_fold(c, k, krr->key_attrs[k], krr->plain[k], 0, rows, 0, cn, &t->mins[k], &t->maxs[k]); + continue; + } + const bool point = krr->key_types[k] != RAY_SYM && ray_col_src_encoded(src); + const bool runs = ray_col_src_encoded(src) && krr->key_types[k] != RAY_F32 && krr->key_types[k] != RAY_F64; + for (int64_t i = 0; i < cn; ) { + int64_t vlo, vhi; + if (runs) { + /* a CONST / RLE vector: the runs holding the rows fold their + * values, nothing decoded */ + ray_t* err = NULL; + int vr = ray_col_src_runview(src, rows[i], &view, &vlo, &vhi, &err); + if (vr < 0) return err; + if (vr > 0) { + int64_t j = i + 1; + while (j < cn && rows[j] < vhi) j++; + agg_sel_bounds_runs(&view, rows, i, j, vlo, c->nullable[k], c->nulls[k], &t->mins[k], &t->maxs[k]); + i = j; + continue; + } + } + if (point && ray_col_src_vec_span(src, rows[i], &vlo, &vhi)) { + int64_t j = i + 1; + while (j < cn && j - i <= RAY_COL_POINT_ROWS && rows[j] < vhi) j++; + if (j - i <= RAY_COL_POINT_ROWS) { + int64_t x[RAY_COL_POINT_ROWS]; + ray_t* err = NULL; + int pr = ray_col_src_points_i64(src, rows + i, j - i, x, &err); + if (pr < 0) return err; + if (pr > 0) { /* else declined: the cursor reads the vector */ + for (int64_t q = 0; q < j - i; q++) { + if (x[q] < t->mins[k]) t->mins[k] = x[q]; + if (x[q] > t->maxs[k]) t->maxs[k] = x[q]; + } + i = j; + continue; + } + } + } + const ray_col_range_t* v; + ray_t* err = ray_col_cursor_at(&cs->cur[k], rows[i], &v); + if (err) return err; + int64_t end = v->start + v->n, j = i + 1; + while (j < cn && rows[j] < end) j++; + agg_sel_bounds_fold(c, k, v->attrs, v->data, v->start, rows, i, j, &t->mins[k], &t->maxs[k]); + i = j; + } + } + return NULL; +} + /* One task's min/max over its slice of selected-row space. */ static void agg_sel_bounds_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; agg_sel_bounds_ctx_t* c = raw; + const agg_rr_t* krr = c->krr; int64_t rows[AGG_SEL_CHUNK]; + agg_view_t whole = agg_view_whole(krr); for (int64_t task = start; task < end; task++) { int64_t* mins = c->task_bounds + (2 * (size_t)task) * c->n_keys; int64_t* maxs = mins + c->n_keys; for (uint32_t k = 0; k < c->n_keys; k++) { mins[k] = INT64_MAX; maxs[k] = INT64_MIN; } - int64_t begin = c->n_sel / c->tasks * task; - int64_t limit = task + 1 == c->tasks ? c->n_sel : c->n_sel / c->tasks * (task + 1); + int64_t begin = c->spans ? c->spans[2 * task] : c->n_sel / c->tasks * task; + int64_t limit = c->spans ? c->spans[2 * task + 1] + : task + 1 == c->tasks ? c->n_sel : c->n_sel / c->tasks * (task + 1); agg_sel_cursor_t cur; agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, begin, limit); + agg_sel_bounds_run_t t = { c, rows, mins, maxs }; + agg_curs_t cs; cs.cur = NULL; + if (krr->staged) { + if (ray_scan_fail_skip(krr->fail, begin)) continue; + if (!agg_curs_init(&cs, krr)) { ray_scan_fail_note(krr->fail, begin, ray_error("oom", NULL)); continue; } + } int64_t cn; while ((cn = agg_sel_cursor_next(&cur, rows)) > 0) { - for (uint32_t k = 0; k < c->n_keys; k++) { - ray_t* kc = c->key_cols[k]; const void* d = c->key_data[k]; - int64_t mn = mins[k], mx = maxs[k]; - for (int64_t i = 0; i < cn; i++) { - int64_t v = agg_read_key_i64(kc, d, rows[i]); - if (c->nullable[k] && v == c->nulls[k]) continue; - if (v < mn) mn = v; - if (v > mx) mx = v; - } - mins[k] = mn; maxs[k] = mx; + if (!krr->staged) { agg_sel_bounds_rows(&t, &whole, wid, 0, cn); continue; } + ray_t* err = agg_sel_bounds_staged(&t, &cs, cn); + if (err) { ray_scan_fail_note(krr->fail, begin, err); break; } + } + agg_curs_free(&cs, krr); + } +} + +/* The chunks of state 2 scanned by their selected rows (one task each), + * folded into mins / maxs and marked 3. False on a range error or cancel. */ +static bool agg_sel_bounds_round(const agg_sel_bounds_ctx_t* bc, uint8_t* state, int64_t nch, int64_t spc, + int64_t* spans, int64_t* tb, int64_t* mins, int64_t* maxs) { + const uint32_t nsegs = ray_rowsel_meta(bc->sel)->n_segs; + int64_t n = 0, rows = 0; + for (int64_t ch = 0; ch < nch; ch++) { + if (state[ch] != 2) continue; + int64_t se = (ch + 1) * spc < (int64_t)nsegs ? (ch + 1) * spc : (int64_t)nsegs; + spans[2 * n] = bc->sel_prefix[ch * spc]; + spans[2 * n + 1] = bc->sel_prefix[se]; + rows += spans[2 * n + 1] - spans[2 * n]; + state[ch] = 3; + n++; + for (uint32_t k = 0; k < bc->n_keys; k++) /* clipped to the source's rows */ + ray_col_src_advise(bc->krr->srcs[k], ch * RAY_ENC_CHUNK, (ch + 1) * RAY_ENC_CHUNK); + } + if (n == 0) return true; + agg_sel_bounds_ctx_t c = *bc; + c.tasks = (uint32_t)n; c.spans = spans; c.task_bounds = tb; + ray_pool_t* pool = ray_pool_get(); + bool par = pool && n > 1 && rows >= RAY_PARALLEL_THRESHOLD; + ray_scan_fail_init(bc->krr->fail); + if (par) ray_pool_dispatch_n(pool, agg_sel_bounds_fn, &c, (uint32_t)n); + else agg_sel_bounds_fn(&c, 0, 0, n); + ray_t* err = ray_scan_fail_finish(bc->krr->fail, par ? pool : NULL); + if (err) { ray_error_free(err); return false; } + for (int64_t t = 0; t < n; t++) + for (uint32_t k = 0; k < bc->n_keys; k++) { + int64_t mn = tb[(2 * (size_t)t) * bc->n_keys + k], mx = tb[(2 * (size_t)t + 1) * bc->n_keys + k]; + if (mn < mins[k]) mins[k] = mn; + if (mx > maxs[k]) maxs[k] = mx; + } + return true; +} + +/* The selected rows' key bounds of staged keys, exactly the full scan's + * (so the plan, its route and its emit order are generation 0's), reading + * only the chunks that can move them. A chunk's directory min / max bound + * its rows, so a chunk with no nulls whose statistics lie inside the bounds + * found so far cannot change them: round 1 scans the selected rows of each + * key's chunks holding the lowest minimum and the highest maximum and of + * every chunk without statistics or with nulls; round 2 the chunks whose + * statistics still reach outside. Bounds only widen as chunks are read, so + * no chunk skipped after round 2 could move them. False (the caller scans + * every selected row) unless every key is a single-file staged non-SYM + * source with a directory; also on a scan error or cancel, so that the full + * scan reports the lowest failure. */ +static bool agg_sel_bounds_dir(const agg_sel_bounds_ctx_t* bc, int64_t* mins, int64_t* maxs) { + const agg_rr_t* krr = bc->krr; + const uint32_t nk = bc->n_keys; + const ray_rowsel_t* m = ray_rowsel_meta(bc->sel); + const int64_t nrows = m->nrows, nch = (nrows + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + const int64_t spc = RAY_ENC_CHUNK / RAY_MORSEL_ELEMS; /* selection segments per chunk */ + ray_enc_chunk_stat_t st; + if (nch < 1) return false; + for (uint32_t k = 0; k < nk; k++) + if (!krr->srcs[k] || krr->key_types[k] == RAY_SYM || krr->srcs[k]->len != nrows || + !ray_col_src_chunk_stat(krr->srcs[k], 0, &st)) + return false; + ray_t* hdr; + int64_t* spans = (int64_t*)scratch_alloc(&hdr, (size_t)nch * (2 + 2 * nk) * sizeof(int64_t) + (size_t)nch); + if (!spans) return false; + int64_t* tb = spans + 2 * nch; + uint8_t* state = (uint8_t*)(tb + 2 * (size_t)nch * nk); /* 0 no selected row, 1 skippable, 2 to scan, 3 scanned */ + int64_t lo_ch[16], hi_ch[16], lo_v[16], hi_v[16]; + for (uint32_t k = 0; k < nk; k++) { lo_ch[k] = hi_ch[k] = -1; lo_v[k] = INT64_MAX; hi_v[k] = INT64_MIN; } + for (int64_t ch = 0; ch < nch; ch++) { + int64_t se = (ch + 1) * spc < (int64_t)m->n_segs ? (ch + 1) * spc : (int64_t)m->n_segs; + state[ch] = bc->sel_prefix[se] > bc->sel_prefix[ch * spc]; + for (uint32_t k = 0; k < nk && state[ch]; k++) { + (void)ray_col_src_chunk_stat(krr->srcs[k], ch, &st); + /* Conservative: a chunk with nulls is always scanned. Its + * statistics bound only its non-null rows, which is all the + * scan folds when the plan holds the key nullable (the usual + * case: the column's null count makes it so); scanning keeps + * the bounds exact without relying on that, and such chunks + * are few. */ + if (!st.has_minmax || st.null_count) { state[ch] = 2; continue; } + if (st.min < lo_v[k]) { lo_v[k] = st.min; lo_ch[k] = ch; } + if (st.max > hi_v[k]) { hi_v[k] = st.max; hi_ch[k] = ch; } + } + } + for (uint32_t k = 0; k < nk; k++) { + if (lo_ch[k] >= 0) state[lo_ch[k]] = 2; + if (hi_ch[k] >= 0) state[hi_ch[k]] = 2; + mins[k] = INT64_MAX; maxs[k] = INT64_MIN; + } + bool ok = agg_sel_bounds_round(bc, state, nch, spc, spans, tb, mins, maxs); + for (int64_t ch = 0; ok && ch < nch; ch++) { + if (state[ch] != 1) continue; + for (uint32_t k = 0; k < nk; k++) { + (void)ray_col_src_chunk_stat(krr->srcs[k], ch, &st); + if (st.min < mins[k] || st.max > maxs[k]) { state[ch] = 2; break; } + } + } + if (ok) ok = agg_sel_bounds_round(bc, state, nch, spc, spans, tb, mins, maxs); + scratch_free(hdr); + return ok; +} + +/* Every selected row's key bounds, scanned (bc->tasks tasks over the + * selection). False on OOM (no *err) or a range error (*err owned, the + * lowest failure). */ +static bool agg_sel_bounds_scan(agg_sel_bounds_ctx_t* bc, int64_t* mins, int64_t* maxs, ray_t** err) { + const agg_rr_t* krr = bc->krr; + const uint32_t nk = bc->n_keys, tasks = bc->tasks; + for (uint32_t k = 0; k < nk; k++) { mins[k] = INT64_MAX; maxs[k] = INT64_MIN; } + ray_t* tb_hdr; + bc->task_bounds = (int64_t*)scratch_alloc(&tb_hdr, 2u * (size_t)tasks * nk * sizeof(int64_t)); + if (!bc->task_bounds) return false; + if (krr->staged) { + ray_scan_fail_init(krr->fail); + for (uint32_t k = 0; k < nk; k++) + if (krr->srcs[k]) ray_col_src_advise(krr->srcs[k], 0, ray_rowsel_meta(bc->sel)->nrows); + } + ray_pool_t* pool = ray_pool_get(); + if (tasks > 1) ray_pool_dispatch_n(pool, agg_sel_bounds_fn, bc, tasks); + else agg_sel_bounds_fn(bc, 0, 0, 1); + if (krr->staged && (*err = ray_scan_fail_finish(krr->fail, tasks > 1 ? pool : NULL)) != NULL) { + scratch_free(tb_hdr); + bc->task_bounds = NULL; + return false; + } + for (uint32_t t = 0; t < tasks; t++) + for (uint32_t k = 0; k < nk; k++) { + int64_t mn = bc->task_bounds[(2 * (size_t)t) * nk + k]; + int64_t mx = bc->task_bounds[(2 * (size_t)t + 1) * nk + k]; + if (mn < mins[k]) mins[k] = mn; + if (mx > maxs[k]) maxs[k] = mx; + } + scratch_free(tb_hdr); + bc->task_bounds = NULL; + return true; +} + +/* A subset of a bounds context's keys as a context of its own: the same + * selection, the keys' sources (pointers, never copies) and plain + * pointers, no aggregate input. */ +typedef struct { + agg_rr_t rr; + ray_col_src_t* srcs[16]; + const void* plain[16]; + uint8_t esz[16], attrs[16]; + int8_t types[16]; + bool nullable[16]; + int64_t nulls[16]; +} agg_sel_keys_t; +static void agg_sel_keys(const agg_sel_bounds_ctx_t* bc, const uint32_t* ks, uint32_t n, + agg_sel_keys_t* o, agg_sel_bounds_ctx_t* sub) { + const agg_rr_t* krr = bc->krr; + bool staged = false; + for (uint32_t i = 0; i < n; i++) { + const uint32_t k = ks[i]; + o->srcs[i] = krr->srcs[k]; + o->plain[i] = krr->plain[k]; + o->esz[i] = krr->esz[k]; + o->attrs[i] = krr->key_attrs[k]; + o->types[i] = krr->key_types[k]; + o->nullable[i] = bc->nullable[k]; + o->nulls[i] = bc->nulls[k]; + staged |= o->srcs[i] != NULL; + } + o->rr = (agg_rr_t){ .srcs = o->srcs, .plain = o->plain, .esz = o->esz, .key_types = o->types, + .key_attrs = o->attrs, .n_src = n, .n_keys = n, .n_aggs = 0, + .fail = krr->fail, .staged = staged }; + *sub = *bc; + sub->krr = &o->rr; sub->nullable = o->nullable; sub->nulls = o->nulls; sub->n_keys = n; + sub->spans = NULL; sub->task_bounds = NULL; +} + +/* The selected rows' exact key bounds of a staged context whose keys are + * read two ways, without scanning what cannot change the plan. The keys + * agg_sel_bounds_dir cannot prune (plain, SYM, parted, without a + * directory) are scanned first. When their ranges alone exceed the dense + * limit (or one has no range), the plan is impossible whatever the other + * keys hold (every range is at least 1): 2, nothing more read. Otherwise + * the single-file generation-2 non-SYM keys take the directory path, as a + * key set of their own: 1, mins / maxs exact for every key, so the plan, + * its route and its emit order are the full scan's. 0: not such a key + * set (every key one way), or a scan error or cancel (the caller's full + * scan then reports the lowest failure). */ +static int agg_sel_bounds_split(const agg_sel_bounds_ctx_t* bc, int64_t* mins, int64_t* maxs) { + const agg_rr_t* krr = bc->krr; + const uint32_t nk = bc->n_keys; + const int64_t nrows = ray_rowsel_meta(bc->sel)->nrows; + uint32_t dk[16], ok[16], nd = 0, no = 0; + ray_enc_chunk_stat_t st; + for (uint32_t k = 0; k < nk; k++) { + if (krr->srcs[k] && krr->key_types[k] != RAY_SYM && krr->srcs[k]->len == nrows && + ray_col_src_chunk_stat(krr->srcs[k], 0, &st)) dk[nd++] = k; + else ok[no++] = k; + } + if (nd == 0 || no == 0) return 0; + agg_sel_keys_t ko, kd; + agg_sel_bounds_ctx_t co, cd; + int64_t mn[16], mx[16]; + agg_sel_keys(bc, ok, no, &ko, &co); + ray_t* err = NULL; + if (!agg_sel_bounds_scan(&co, mn, mx, &err)) { if (err) ray_error_free(err); return 0; } + const int64_t limit = bc->n_sel < (int64_t)UINT32_MAX ? bc->n_sel : (int64_t)UINT32_MAX; + int64_t total = 1; + for (uint32_t i = 0; i < no; i++) { /* agg_dense_range's ranges */ + int64_t rng; + if (mx[i] < mn[i]) { + if (!co.nullable[i]) return 2; + rng = 1; + } else { + uint64_t span = (uint64_t)mx[i] - (uint64_t)mn[i]; + if (span >= (uint64_t)INT64_MAX - (uint64_t)co.nullable[i]) return 2; + rng = (int64_t)span + 1 + co.nullable[i]; + } + if (total > limit / rng) return 2; + total *= rng; + } + for (uint32_t i = 0; i < no; i++) { mins[ok[i]] = mn[i]; maxs[ok[i]] = mx[i]; } + agg_sel_keys(bc, dk, nd, &kd, &cd); + if (!agg_sel_bounds_dir(&cd, mn, mx)) return 0; + for (uint32_t i = 0; i < nd; i++) { mins[dk[i]] = mn[i]; maxs[dk[i]] = mx[i]; } + return 1; +} + +/* A probe that can only prove the dense plan impossible, for staged keys: + * the key values of AGG_SEL_PROBE_ROWS evenly spaced selected rows (in + * place or by point reads; a declined read skips its row, so nothing is + * decoded) bound the selected rows' exact ranges from + * below, so when their ranges already exceed the dense limit (as + * agg_sel_bounds_split judges them, nullability included) the exact + * bounds do too, and the scan of every selected row is skipped: the + * plan, the route and the emit order stay those of the exact bounds. + * True: impossible. False: undecided (a read error or OOM included; the + * exact scan reports it). */ +#define AGG_SEL_PROBE_ROWS (RAY_MORSEL_ELEMS / 16) +/* True when the key ranges mn / mx (a subset of the selected rows' values) + * already exceed the dense limit, as agg_sel_bounds_split judges them + * (agg_dense_range's ranges, nullability included). */ +static bool agg_sel_ranges_exceed(const agg_sel_bounds_ctx_t* bc, const int64_t* mn, const int64_t* mx) { + const int64_t limit = bc->n_sel < (int64_t)UINT32_MAX ? bc->n_sel : (int64_t)UINT32_MAX; + int64_t total = 1; + for (uint32_t k = 0; k < bc->n_keys; k++) { + if (mx[k] < mn[k]) continue; /* no value seen: at least 1 */ + uint64_t span = (uint64_t)mx[k] - (uint64_t)mn[k]; + if (span >= (uint64_t)INT64_MAX - (uint64_t)bc->nullable[k]) return true; + int64_t rng = (int64_t)span + 1 + bc->nullable[k]; + if (total > limit / rng) return true; + total *= rng; + } + return false; +} +static _Atomic(uint64_t) g_sel_probe_hits; /* test hook: plans the probe proved impossible */ +uint64_t ray_agg_test_sel_probe_hits(void) { return atomic_load_explicit(&g_sel_probe_hits, memory_order_relaxed); } +static bool agg_sel_bounds_impossible(const agg_sel_bounds_ctx_t* bc) { + const agg_rr_t* krr = bc->krr; + const uint32_t nk = bc->n_keys; + if (nk < 1 || nk > 16 || bc->n_sel < 2) return false; + int64_t mn[16], mx[16]; + for (uint32_t k = 0; k < nk; k++) { mn[k] = INT64_MAX; mx[k] = INT64_MIN; } + const int64_t np = bc->n_sel < AGG_SEL_PROBE_ROWS ? bc->n_sel : AGG_SEL_PROBE_ROWS; + bool ok = true; + for (int64_t i = 0; i < np && ok; i++) { + int64_t o = bc->n_sel / np * i, row; + agg_sel_cursor_t cur; + agg_sel_cursor_init(&cur, bc->sel, bc->sel_prefix, o, o + 1); + if (agg_sel_cursor_next(&cur, &row) != 1) { ok = false; break; } + for (uint32_t k = 0; k < nk; k++) { + /* in place, or a point read; a declined one skips the row for + * this key (fewer rows only weaken the bound: nothing decodes) */ + int64_t x; + if (!krr->srcs[k]) x = agg_read_key_i64_raw(krr->key_types[k], krr->key_attrs[k], krr->plain[k], row); + else { + ray_t* err = NULL; + int pr = krr->srcs[k]->type == RAY_SYM ? agg_src_points(krr->srcs[k], &row, 1, &x, &err) + : ray_col_src_point_i64(krr->srcs[k], row, &x, &err); + if (pr < 0) { ray_error_free(err); ok = false; break; } + if (pr == 0) continue; + } + if (bc->nullable[k] && x == bc->nulls[k]) continue; + if (x < mn[k]) mn[k] = x; + if (x > mx[k]) mx[k] = x; + } + } + if (!ok) return false; + if (agg_sel_ranges_exceed(bc, mn, mx)) return true; + /* Undecided: the selected rows of the chunks holding each SYM key's + * lowest minimum and highest maximum in the directory (its membership + * bounds; a SYM key has no directory route to its exact bounds) are + * scanned too. The statistics only choose the chunks; the bound is + * still the values read, so it stays a subset of the exact scan's + * whatever they say. A key whose extremes are a few rare values (SYM + * ids interned early) is proved here, where evenly spaced rows miss + * them. */ + const ray_rowsel_t* m = ray_rowsel_meta(bc->sel); + const int64_t nrows = m->nrows, nch = (nrows + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + const int64_t spc = RAY_ENC_CHUNK / RAY_MORSEL_ELEMS; /* selection segments per chunk */ + if (nch < 2) return false; /* one chunk: the exact scan */ + /* the SYM keys with a directory (the others' exact bounds take the + * directory, agg_sel_bounds_dir / _split, which reads these chunks + * anyway); none (every generation-0 key): nothing allocated */ + uint32_t sk[16], nsk = 0; + ray_enc_chunk_stat_t st; + for (uint32_t k = 0; k < nk; k++) + if (krr->srcs[k] && krr->key_types[k] == RAY_SYM && krr->srcs[k]->len == nrows && + ray_col_src_chunk_stat(krr->srcs[k], 0, &st)) sk[nsk++] = k; + if (nsk == 0) return false; + ray_t* hdr; + int64_t* spans = (int64_t*)scratch_alloc(&hdr, (size_t)nch * (2 + 2 * nk) * sizeof(int64_t) + (size_t)nch); + if (!spans) return false; + int64_t* tb = spans + 2 * nch; + uint8_t* state = (uint8_t*)(tb + 2 * (size_t)nch * nk); + memset(state, 0, (size_t)nch); + int64_t probe_rows = 0; /* selected rows of the marked chunks */ + uint32_t nread = 0; + for (uint32_t i = 0; i < nsk; i++) { + const uint32_t k = sk[i]; + int64_t lo_ch = -1, hi_ch = -1, lo_v = INT64_MAX, hi_v = INT64_MIN; + for (int64_t ch = 0; ch < nch; ch++) { + int64_t se = (ch + 1) * spc < (int64_t)m->n_segs ? (ch + 1) * spc : (int64_t)m->n_segs; + if (bc->sel_prefix[se] == bc->sel_prefix[ch * spc]) continue; /* no selected row */ + if (!ray_col_src_chunk_stat(krr->srcs[k], ch, &st) || !st.has_minmax) continue; + if (st.min < lo_v) { lo_v = st.min; lo_ch = ch; } + if (st.max > hi_v) { hi_v = st.max; hi_ch = ch; } + } + if (lo_ch < 0) continue; + sk[nread++] = k; + const int64_t mk[2] = { lo_ch, hi_ch }; + for (int e = 0; e < 2; e++) { + const int64_t ch = mk[e]; + if (state[ch] == 2) continue; + state[ch] = 2; + int64_t se = (ch + 1) * spc < (int64_t)m->n_segs ? (ch + 1) * spc : (int64_t)m->n_segs; + probe_rows += bc->sel_prefix[se] - bc->sel_prefix[ch * spc]; + } + } + /* The probe reads the marked chunks' selected rows; undecided, the + * exact scan then reads every selected row again, so a miss costs + * probe_rows / n_sel more. At most a quarter of the selected rows + * keeps a miss under a quarter of the exact scan, while a hit saves + * the other three quarters and more (q13: 2 of 153 chunks). Those + * keys alone are read (a key set of their own, agg_sel_keys). */ + bool proved = false; + if (nread > 0 && probe_rows * 4 <= bc->n_sel) { + agg_sel_keys_t ko; + agg_sel_bounds_ctx_t co; + agg_sel_keys(bc, sk, nread, &ko, &co); + int64_t cm[16], cx[16]; + for (uint32_t i = 0; i < nread; i++) { cm[i] = INT64_MAX; cx[i] = INT64_MIN; } + if (agg_sel_bounds_round(&co, state, nch, spc, spans, tb, cm, cx)) { + int64_t am[16], ax[16]; + for (uint32_t k = 0; k < nk; k++) { am[k] = mn[k]; ax[k] = mx[k]; } + for (uint32_t i = 0; i < nread; i++) { + if (cm[i] < am[sk[i]]) am[sk[i]] = cm[i]; + if (cx[i] > ax[sk[i]]) ax[sk[i]] = cx[i]; } + proved = agg_sel_ranges_exceed(bc, am, ax); } } + scratch_free(hdr); + return proved; } -static bool agg_dense_plan_sel(ray_t** key_cols, uint32_t n_keys, int64_t n_sel, +static bool agg_dense_plan_sel(ray_t** key_cols, const agg_rr_t* krr, uint32_t n_keys, int64_t n_sel, ray_t* sel, const int64_t* sel_prefix, - dense_plan_t* out) { + dense_plan_t* out, ray_t** err) { + *err = NULL; out->ok = false; out->n_keys = n_keys; out->compacted = false; + out->wide = false; memset(out->remap, 0, sizeof(out->remap)); memset(out->inverse, 0, sizeof(out->inverse)); if (n_keys < 1 || n_keys > 16) return false; @@ -1542,34 +2859,34 @@ static bool agg_dense_plan_sel(ray_t** key_cols, uint32_t n_keys, int64_t n_sel, * The pass is split across the pool: a serial walk of a 10M-row selection * cost ~13 ms on every filtered group-by regardless of core count. */ ray_t* pre_hdr; - void* pre = scratch_alloc(&pre_hdr, 3u * (size_t)n_keys * 8); /* mins,maxs,key_data */ + void* pre = scratch_alloc(&pre_hdr, 2u * (size_t)n_keys * 8); /* mins,maxs */ if (!pre) return false; int64_t* mins = (int64_t*)pre; int64_t* maxs = mins + n_keys; - const void** key_data = (const void**)(maxs + n_keys); for (uint32_t k = 0; k < n_keys; k++) { mins[k] = INT64_MAX; maxs[k] = INT64_MIN; } - for (uint32_t k = 0; k < n_keys; k++) key_data[k] = ray_data(key_cols[k]); ray_pool_t* pool = ray_pool_get(); uint32_t tasks = pool && n_sel >= RAY_PARALLEL_THRESHOLD ? ray_pool_total_workers(pool) * 4 : 1; if (tasks > RAY_POOL_INIT_TASKS) tasks = RAY_POOL_INIT_TASKS; if ((int64_t)tasks > n_sel) tasks = (uint32_t)n_sel; - agg_sel_bounds_ctx_t bc = { .key_cols = key_cols, .key_data = key_data, + agg_sel_bounds_ctx_t bc = { .krr = krr, .nullable = out->nullable, .nulls = out->nulls, .n_keys = n_keys, .sel = sel, .sel_prefix = sel_prefix, .n_sel = n_sel, .tasks = tasks }; - ray_t* tb_hdr; - bc.task_bounds = (int64_t*)scratch_alloc(&tb_hdr, 2u * (size_t)tasks * n_keys * sizeof(int64_t)); - if (!bc.task_bounds) { scratch_free(pre_hdr); return false; } - if (tasks > 1) ray_pool_dispatch_n(pool, agg_sel_bounds_fn, &bc, tasks); - else agg_sel_bounds_fn(&bc, 0, 0, 1); - for (uint32_t t = 0; t < tasks; t++) - for (uint32_t k = 0; k < n_keys; k++) { - int64_t mn = bc.task_bounds[(2 * (size_t)t) * n_keys + k]; - int64_t mx = bc.task_bounds[(2 * (size_t)t + 1) * n_keys + k]; - if (mn < mins[k]) mins[k] = mn; - if (mx > maxs[k]) maxs[k] = mx; - } - scratch_free(tb_hdr); + /* staged: the directory prunes what it can (every key, or the keys it + * serves after the others, agg_sel_bounds_split); else every selected + * row is scanned */ + if (krr->staged && agg_sel_bounds_impossible(&bc)) { + atomic_fetch_add_explicit(&g_sel_probe_hits, 1, memory_order_relaxed); + scratch_free(pre_hdr); + return false; + } + int split = krr->staged ? agg_sel_bounds_split(&bc, mins, maxs) : 0; + if (split == 2) { scratch_free(pre_hdr); return false; } /* dense is impossible */ + if (split == 0 && (!krr->staged || !agg_sel_bounds_dir(&bc, mins, maxs)) && + !agg_sel_bounds_scan(&bc, mins, maxs, err)) { + scratch_free(pre_hdr); + return false; + } for (uint32_t k = 0; k < n_keys; k++) { if (!agg_dense_range(out, k, mins[k], maxs[k])) { scratch_free(pre_hdr); return false; } } @@ -1618,6 +2935,17 @@ static inline uint64_t agg_tuple_hash(ray_t** key_cols, const void** key_data, return h; } +/* agg_tuple_hash of a group's stored key words (the same FNV-1a + fmix64): + * a staged small hash keys its groups by words, never by first rows. */ +static inline uint64_t agg_words_hash(const int64_t* w, uint32_t n_keys) { + uint64_t h = 1469598103934665603ULL; + for (uint32_t k = 0; k < n_keys; k++) { h ^= (uint64_t)w[k]; h *= 1099511628211ULL; } + h ^= h >> 33; h *= 0xff51afd7ed558ccdULL; + h ^= h >> 33; h *= 0xc4ceb9fe1a85ec53ULL; + h ^= h >> 33; + return h; +} + /* All keys at row ra equal all keys at row rb? n_keys is uint32_t (unbounded), * same contract as agg_tuple_hash above. */ static inline int agg_tuple_eq(ray_t** key_cols, const void** key_data, @@ -1664,6 +2992,9 @@ typedef struct { agg_valdesc_t vd; int64_t task_rows; uint32_t n_tasks; + const agg_rr_t* rr; /* sources; staged ones are read by range */ + const agg_view_t* whole; + bool runs; /* COUNT only over one staged key: its run views add to the slots */ } agg_dense_ctx_t; /* Each task owns a slice of one query allocation. Only the bitmap is @@ -1876,7 +3207,7 @@ bool agg_group_values_f64(const agg_vtable_t* vt, const char* states, int64_t n, int64_t param, double* out) { int8_t t = vt->out_type; switch (t) { - case RAY_F64: case RAY_F32: case RAY_I64: case RAY_TIMESTAMP: + case RAY_F64: case RAY_F32: case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: case RAY_U8: case RAY_BOOL: break; default: return false; @@ -1897,7 +3228,7 @@ bool agg_group_values_f64(const agg_vtable_t* vt, const char* states, switch (t) { case RAY_F64: v = ((const double*)ray_data(cell))[0]; break; case RAY_F32: v = ((const float*)ray_data(cell))[0]; break; - case RAY_I64: case RAY_TIMESTAMP: v = (double)((const int64_t*)ray_data(cell))[0]; break; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: v = (double)((const int64_t*)ray_data(cell))[0]; break; case RAY_I32: case RAY_DATE: case RAY_TIME: v = (double)((const int32_t*)ray_data(cell))[0]; break; case RAY_I16: v = (double)((const int16_t*)ray_data(cell))[0]; break; default: v = (double)((const uint8_t*)ray_data(cell))[0]; break; @@ -1930,14 +3261,15 @@ static void agg_dense_emit_fn(void* raw, uint32_t wid, int64_t start, int64_t en /* Compute the dense slot for row r via mixed-radix packing. `compacted` * is loop-invariant (dp->compacted); callers pass it from a local so the * raw form stays branch-free. */ -static inline int64_t agg_dense_slot(const agg_dense_ctx_t* c, int64_t r, bool compacted) { +static inline int64_t agg_dense_slot(const agg_dense_ctx_t* c, const agg_view_t* v, int64_t r, bool compacted) { int64_t slot = 0; + const int64_t i = r - v->base; if (compacted) { for (uint32_t k = 0; k < c->n_keys; k++) - slot += agg_dense_component(c->dp, k, agg_read_key_i64(c->key_cols[k], c->key_data[k], r)) * c->dp->strides[k]; + slot += agg_dense_component(c->dp, k, agg_read_key_i64_raw(c->key_cols[k]->type, v->key_attrs[k], v->key_data[k], i)) * c->dp->strides[k]; } else { for (uint32_t k = 0; k < c->n_keys; k++) - slot += agg_dense_component_raw(c->dp, k, agg_read_key_i64(c->key_cols[k], c->key_data[k], r)) * c->dp->strides[k]; + slot += agg_dense_component_raw(c->dp, k, agg_read_key_i64_raw(c->key_cols[k]->type, v->key_attrs[k], v->key_data[k], i)) * c->dp->strides[k]; } return slot; } @@ -1950,46 +3282,82 @@ static inline bool agg_dense_first(agg_dense_local_t* loc, int64_t slot) { return true; } -/* Phase A: per-worker dense accumulate over chunk [start,end). */ -static void agg_dense_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { +/* Phase A, sel mode: the slots and the accumulation of one run of selected + * rows rows[ib, ie) read through view v. */ +typedef struct { + agg_dense_ctx_t* c; + agg_dense_local_t* loc; + const int64_t* rows; + uint32_t* gid; + agg_sel_scratch_t* sc; +} agg_dense_sel_run_t; +static void agg_dense_sel_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t ib, int64_t ie) { + (void)wid; + agg_dense_sel_run_t* t = raw; + agg_dense_ctx_t* c = t->c; + agg_dense_local_t* loc = t->loc; + if (loc->oom) return; + /* Locals: the init calls below would otherwise reload every field. */ + const int64_t* rows = t->rows; + uint32_t* gid = t->gid; + int64_t* fr = loc->first_row; + char* states = loc->states; + const bool compacted = c->dp->compacted; + for (int64_t i = ib; i < ie; i++) { + int64_t r = rows[i]; + int64_t slot = agg_dense_slot(c, v, r, compacted); /* provably in [0,total_slots) */ + gid[i - ib] = (uint32_t)slot; + if (agg_dense_first(loc, slot)) { + for (uint32_t a = 0; a < c->n_aggs; a++) + c->vts[a]->init(states + (size_t)slot * c->block + c->off[a]); + fr[slot] = r; + } + if (r < fr[slot]) fr[slot] = r; + } + if (agg_sel_accum_chunk(&c->vd, v, t->sc, states, gid, rows + ib, ie - ib, false) != 0) + loc->oom = 1; +} + +/* Phase A, sel mode: chunk-iterate the SELECTED rows in [start,end) + * (selected-row space). Decode each chunk's ORIGINAL rows, compute dense + * slots, gather agg values per chunk into reused scratch, and batch-update. + * No full index array, no full compact column. Staged sources are read by + * R-SPARSE through this task's cursors. */ +static void agg_dense_phaseA_sel(agg_dense_ctx_t* c, uint32_t wid, int64_t start, int64_t end) { + agg_dense_local_t* loc = &c->locals[wid]; + if (loc->oom || end <= start) return; + int64_t rows[AGG_SEL_CHUNK]; + uint32_t gid[AGG_SEL_CHUNK]; + agg_sel_scratch_t sc; + if (!agg_sel_scratch_init(&sc, c->n_aggs)) { loc->oom = 1; return; } + const agg_rr_t* rr = c->rr; + agg_curs_t cs; cs.cur = NULL; + if (rr->staged) { + if (ray_scan_fail_skip(rr->fail, start)) { agg_sel_scratch_free(&sc); return; } + if (!agg_curs_init(&cs, rr)) { loc->oom = 1; agg_sel_scratch_free(&sc); return; } + } + agg_sel_cursor_t cur; + agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, start, end); + agg_dense_sel_run_t t = { c, loc, rows, gid, &sc }; + int64_t cn; + while (!loc->oom && (cn = agg_sel_cursor_next(&cur, rows)) > 0) { + if (!rr->staged) { agg_dense_sel_rows(&t, c->whole, wid, 0, cn); continue; } + ray_t* err = agg_idx_walk(rr, &cs, rows, 0, cn, &t, agg_dense_sel_rows, wid); + if (err) { ray_scan_fail_note(rr->fail, start, err); break; } + } + agg_curs_free(&cs, rr); + agg_sel_scratch_free(&sc); +} + +/* Phase A: per-worker dense accumulate over chunk [start,end) (at most + * 8192 rows) read through view v: the whole columns, or one piece. */ +static void agg_dense_phaseA_fn(void* vctx, const agg_view_t* v, uint32_t wid, int64_t start, int64_t end) { agg_dense_ctx_t* c = vctx; agg_dense_local_t* loc = &c->locals[wid]; if (loc->oom) return; int64_t n = end - start; if (n <= 0) return; - - /* ── Sel mode: chunk-iterate the SELECTED rows in [start,end) (selected-row - * space). Decode each chunk's ORIGINAL rows, compute dense slots, gather - * agg values per chunk into reused scratch, and batch-update. No full - * index array, no full compact column. */ - if (c->sel) { - int64_t rows[AGG_SEL_CHUNK]; - uint32_t gid[AGG_SEL_CHUNK]; - agg_sel_scratch_t sc; - if (!agg_sel_scratch_init(&sc, c->n_aggs)) { loc->oom = 1; return; } - agg_sel_cursor_t cur; - agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, start, end); - int64_t cn; - const bool compacted = c->dp->compacted; - while ((cn = agg_sel_cursor_next(&cur, rows)) > 0) { - for (int64_t i = 0; i < cn; i++) { - int64_t r = rows[i]; - int64_t slot = agg_dense_slot(c, r, compacted); /* provably in [0,total_slots) */ - gid[i] = (uint32_t)slot; - if (agg_dense_first(loc, slot)) { - for (uint32_t a = 0; a < c->n_aggs; a++) - c->vts[a]->init(loc->states + (size_t)slot * c->block + c->off[a]); - loc->first_row[slot] = r; - } - if (r < loc->first_row[slot]) loc->first_row[slot] = r; - } - if (agg_sel_accum_chunk(&c->vd, &sc, loc->states, gid, rows, cn) != 0) { - loc->oom = 1; agg_sel_scratch_free(&sc); return; - } - } - agg_sel_scratch_free(&sc); - return; - } + const int64_t kbase = v->base; uint32_t cgid[8192]; @@ -2001,18 +3369,19 @@ static void agg_dense_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t * this is the dominant cost of a low-card group-by (a 7-group count was * ~70% here). Multi-key keeps the generic composite path. */ if (c->n_keys == 1) { - const void* kd = c->key_data[0]; + const void* kd = v->key_data[0]; int64_t kmin = c->dp->mins[0]; - int64_t kstride = c->dp->strides[0]; - bool nullable = c->dp->nullable[0]; + bool nullable = c->dp->nullable[0]; /* one key: its stride is 1 */ int64_t null = c->dp->nulls[0], null_slot = c->dp->ranges[0] - 1; int64_t* fr = loc->first_row; uint32_t* cg = cgid; - #define DENSE_SLOT1_LAZY(LD) \ + /* Only the nullable instance tests for the null (a ragged + * partition's null segment makes the key nullable); the slot is + * v - kmin, a single key's stride being 1. */ + #define DENSE_SLOT1_LAZY(LD, SLOT) \ for (int64_t r = start; r < end; r++) { \ int64_t v = (int64_t)(LD); \ - int64_t slot = nullable && v == null ? null_slot \ - : (v - kmin) * kstride; \ + int64_t slot = (SLOT); \ cg[r - start] = (uint32_t)slot; \ if (agg_dense_first(loc, slot)) { \ for (uint32_t a = 0; a < c->n_aggs; a++) \ @@ -2033,24 +3402,25 @@ static void agg_dense_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t if (loc->eager) { \ if (!nullable) { DENSE_SLOT1_EAGER(LD, v - kmin); } \ else { DENSE_SLOT1_EAGER(LD, v == null ? null_slot : v - kmin); } \ - } else { DENSE_SLOT1_LAZY(LD); } \ + } else if (!nullable) { DENSE_SLOT1_LAZY(LD, v - kmin); } \ + else { DENSE_SLOT1_LAZY(LD, v == null ? null_slot : v - kmin); } \ } while (0) switch (c->key_cols[0]->type) { - case RAY_I64: case RAY_TIMESTAMP: DENSE_SLOT1(((const int64_t*)kd)[r]); break; - case RAY_I32: case RAY_DATE: case RAY_TIME: DENSE_SLOT1(((const int32_t*)kd)[r]); break; - case RAY_I16: DENSE_SLOT1(((const int16_t*)kd)[r]); break; - case RAY_U8: case RAY_BOOL: DENSE_SLOT1(((const uint8_t*)kd)[r]); break; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: DENSE_SLOT1(((const int64_t*)kd)[r - kbase]); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: DENSE_SLOT1(((const int32_t*)kd)[r - kbase]); break; + case RAY_I16: DENSE_SLOT1(((const int16_t*)kd)[r - kbase]); break; + case RAY_U8: case RAY_BOOL: DENSE_SLOT1(((const uint8_t*)kd)[r - kbase]); break; case RAY_SYM: - switch (c->key_cols[0]->attrs & RAY_SYM_W_MASK) { - case RAY_SYM_W8: DENSE_SLOT1(((const uint8_t*)kd)[r]); break; - case RAY_SYM_W16: DENSE_SLOT1(((const uint16_t*)kd)[r]); break; - case RAY_SYM_W32: DENSE_SLOT1(((const uint32_t*)kd)[r]); break; - default: DENSE_SLOT1(((const int64_t*)kd)[r]); break; /* W64 */ + switch (v->key_attrs[0] & RAY_SYM_W_MASK) { + case RAY_SYM_W8: DENSE_SLOT1(((const uint8_t*)kd)[r - kbase]); break; + case RAY_SYM_W16: DENSE_SLOT1(((const uint16_t*)kd)[r - kbase]); break; + case RAY_SYM_W32: DENSE_SLOT1(((const uint32_t*)kd)[r - kbase]); break; + default: DENSE_SLOT1(((const int64_t*)kd)[r - kbase]); break; /* W64 */ } break; default: for (int64_t r = start; r < end; r++) { - int64_t slot = agg_dense_slot(c, r, false); /* single key: never compacted */ + int64_t slot = agg_dense_slot(c, v, r, false); /* single key: never compacted */ cg[r - start] = (uint32_t)slot; if (r < fr[slot]) fr[slot] = r; } @@ -2061,7 +3431,7 @@ static void agg_dense_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t } else { #define DENSE_SLOT_MULTI(COMPACTED) \ for (int64_t r = start; r < end; r++) { \ - int64_t slot = agg_dense_slot(c, r, COMPACTED); /* provably in [0,total_slots) */ \ + int64_t slot = agg_dense_slot(c, v, r, COMPACTED); /* provably in [0,total_slots) */ \ cgid[r - start] = (uint32_t)slot; \ if (agg_dense_first(loc, slot)) { \ for (uint32_t a = 0; a < c->n_aggs; a++) \ @@ -2076,47 +3446,252 @@ static void agg_dense_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t for (uint32_t a = 0; a < c->n_aggs; a++) { if (c->vts[a]->update_batch2) { /* binary agg (pearson) */ - const void* vx = (const char*)c->val_data[a] + (size_t)start * c->val_esz[a]; - const void* vy = (const char*)c->val2_data[a] + (size_t)start * c->val2_esz[a]; + const void* vx = (const char*)v->val_data[a] + (size_t)(start - kbase) * c->val_esz[a]; + const void* vy = (const char*)v->val2_data[a] + (size_t)(start - kbase) * c->val2_esz[a]; ray_valid_t valid_x = { vx, c->val_types[a], c->val_hasnull[a] }; ray_valid_t valid_y = { vy, c->val2_types[a], c->val2_hasnull[a] }; c->vts[a]->update_batch2(loc->states + c->off[a], c->block, cgid, vx, vy, &valid_x, &valid_y, n, NULL); } else { - const void* vals = (c->val_data[a]) - ? (const void*)((const char*)c->val_data[a] + (size_t)start * c->val_esz[a]) + const void* vals = (v->val_data[a]) + ? (const void*)((const char*)v->val_data[a] + (size_t)(start - kbase) * c->val_esz[a]) : NULL; ray_valid_t valid = { vals, c->val_types[a], - c->val_data[a] ? c->val_hasnull[a] : false }; + v->val_data[a] ? c->val_hasnull[a] : false }; c->vts[a]->update_batch(loc->states + c->off[a], c->block, cgid, vals, &valid, n, NULL); } } } -/* One slab per logical task, independent of the physical worker executing it. - * A large pool can run a memory-bounded number of dense tasks safely. */ -static void agg_dense_task_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; - agg_dense_ctx_t* c = raw; - int64_t chunk = c->task_rows / c->n_tasks; - for (int64_t task = start; task < end; task++) { - agg_dense_local_t* loc = &c->locals[task]; - /* Storage was allocated once by the coordinator. Initialize each - * slab on its consuming task, without another pool dispatch. */ - agg_dense_local_init(loc, loc->slots, c->block); - if (loc->eager) for (int64_t s = 0; s < loc->slots; s++) { +/* Phase A on the key's runs (ctx->runs: every aggregate COUNT, one + * staged key). A CONST / RLE key vector without bitmap nulls + * (ray_col_src_runview) adds each run's rows to its slot: the run's length + * inside the task's rows, or the number of the selection's rows inside the + * run; the slot is the per-row body's (agg_dense_component_raw: one key, + * never compacted), the first row the run's first counted row. Every + * other vector is read and counted per row by the bodies above, as before + * (D6). A slot outside the slab is `corrupt` (an internal plan check). + * Exact for any rows a task holds: nothing + * depends on the task cut. */ +typedef struct { + agg_dense_ctx_t* c; + agg_dense_local_t* loc; + int64_t vlo; /* source row of the view's row 0 */ + int64_t r0, r1; /* dense rows [r0, r1); idx == NULL */ + const uint16_t* idx; /* else rows ibase + idx[ii, ni), ascending */ + int64_t ibase, ii, ni; + bool bad; /* a run value outside the plan */ +} agg_dense_runs_t; + +static inline void agg_dense_run_add(agg_dense_runs_t* t, int64_t value, int64_t first, int64_t cnt) { + const agg_dense_ctx_t* c = t->c; + agg_dense_local_t* loc = t->loc; + const int64_t slot = agg_dense_component_raw(c->dp, 0, value); + if (slot < 0 || slot >= loc->slots) { t->bad = true; return; } + int64_t* fr = loc->first_row; + char* st = loc->states + (size_t)slot * c->block; + if (loc->eager) { if (first < fr[slot]) fr[slot] = first; } + else if (agg_dense_first(loc, slot)) { + for (uint32_t a = 0; a < c->n_aggs; a++) c->vts[a]->init(st + c->off[a]); + fr[slot] = first; + } else if (first < fr[slot]) fr[slot] = first; + for (uint32_t a = 0; a < c->n_aggs; a++) { /* COUNT's state: one int64_t count */ + int64_t n; memcpy(&n, st + c->off[a], sizeof n); + n += cnt; + memcpy(st + c->off[a], &n, sizeof n); + } +} +/* ray_enc_runs callback: the run's rows inside dense rows [r0, r1) */ +static void agg_dense_run_rows(void* raw, int64_t value, int32_t lo, int32_t hi) { + agg_dense_runs_t* t = raw; + int64_t a = t->vlo + lo, b = t->vlo + hi; + if (a < t->r0) a = t->r0; + if (b > t->r1) b = t->r1; + if (a < b) agg_dense_run_add(t, value, a, b - a); +} +/* The selection's rows ibase + idx[ii, ni) inside the view's vector, + * merged with its runs: each run holding some adds their count. */ +static void agg_dense_runs_idx(agg_dense_runs_t* t, const ray_enc_vview_t* v) { + const uint16_t* idx = t->idx; + const int64_t ni = t->ni, off = t->vlo - t->ibase; /* local run end e <=> index e + off */ + int64_t i = t->ii; + for (uint32_t r = agg_run_at(v, idx[i] - off); r < v->n_runs && i < ni && !t->bad; r++) { + const int64_t e = (int64_t)v->run_ends.h[r] + off; + if (idx[i] >= e) continue; /* none of the rows in this run */ + const int64_t f = i; + while (i < ni && idx[i] < e) i++; + agg_dense_run_add(t, agg_run_value(v, r), t->ibase + idx[f], i - f); + } + t->ii = i; +} +static ray_t* agg_dense_runs_bad(void) { + return ray_error("corrupt", "group: a key run outside its dense plan"); +} + +/* Sel mode on runs: the task's selected rows [start, end) segment by + * segment (ALL: a dense row range; MIX: the segment's indices). */ +static __attribute__((noinline)) void agg_dense_runs_sel(agg_dense_ctx_t* c, uint32_t wid, int64_t start, int64_t end) { + agg_dense_local_t* loc = &c->locals[wid]; + if (loc->oom || end <= start) return; + const agg_rr_t* rr = c->rr; + ray_col_src_t* src = rr->srcs[0]; + if (ray_scan_fail_skip(rr->fail, start)) return; + int64_t rows[AGG_SEL_CHUNK]; + uint32_t gid[AGG_SEL_CHUNK]; + agg_sel_scratch_t sc; + if (!agg_sel_scratch_init(&sc, c->n_aggs)) { loc->oom = 1; return; } + agg_curs_t cs; cs.cur = NULL; + if (!agg_curs_init(&cs, rr)) { loc->oom = 1; agg_sel_scratch_free(&sc); return; } + agg_dense_sel_run_t pr = { c, loc, rows, gid, &sc }; + agg_dense_runs_t t = { .c = c, .loc = loc }; + ray_enc_vview_t view; /* the task's key view: on its stack */ + int64_t vlo = -1, vhi = -1, nb = 0; /* the view's (or declined) rows; buffered rows */ + int vr = 0; + bool stop = false; /* cancelled */ + ray_t* err = NULL; + const ray_rowsel_t* m = ray_rowsel_meta(c->sel); + const uint8_t* flags = ray_rowsel_flags(c->sel); + const uint32_t* offs = ray_rowsel_offsets(c->sel); + const uint16_t* idx = ray_rowsel_idx(c->sel); + const int64_t* pre = c->sel_prefix; + uint32_t s = 0, hs = m->n_segs; /* the segment holding selected row `start` */ + while (s < hs) { uint32_t mid = s + (hs - s) / 2; if (pre[mid + 1] <= start) s = mid + 1; else hs = mid; } + for (; s < m->n_segs && pre[s] < end && !err && !stop && !loc->oom; s++) { + if (flags[s] == RAY_SEL_NONE) continue; + const int64_t seg_sel = pre[s + 1] - pre[s]; + const int64_t p0 = start > pre[s] ? start - pre[s] : 0; + const int64_t p1 = end - pre[s] < seg_sel ? end - pre[s] : seg_sel; + const int64_t base = (int64_t)s * RAY_MORSEL_ELEMS; + const bool all = flags[s] == RAY_SEL_ALL; + const uint16_t* si = idx + offs[s]; + for (int64_t q = p0; q < p1 && !err; ) { + const int64_t r = all ? base + q : base + si[q]; + if (r < vlo || r >= vhi) { + if ((stop = agg_cancelled())) break; + vr = ray_col_src_runview(src, r, &view, &vlo, &vhi, &err); + if (vr < 0) break; + } + /* the positions [q, qe) of this segment inside [vlo, vhi) */ + int64_t qe; + if (all) qe = vhi - base < p1 ? vhi - base : p1; + else { qe = q + 1; while (qe < p1 && base + si[qe] < vhi) qe++; } + if (vr > 0) { + t.vlo = vlo; + if (all) { t.idx = NULL; t.r0 = base + q; t.r1 = base + qe; } + else { t.idx = si; t.ibase = base; t.ii = q; t.ni = qe; } + if (all) (void)ray_enc_runs(&view, &t, agg_dense_run_rows); + else agg_dense_runs_idx(&t, &view); + if (t.bad) { err = agg_dense_runs_bad(); break; } + } else { + for (int64_t i = q; i < qe && !err; i++) { + rows[nb++] = all ? base + i : base + si[i]; + if (nb == AGG_SEL_CHUNK) { err = agg_idx_walk(rr, &cs, rows, 0, nb, &pr, agg_dense_sel_rows, wid); nb = 0; } + } + } + q = qe; + } + } + if (nb > 0) { /* the lower rows' read reports first */ + ray_t* ferr = loc->oom ? NULL : agg_idx_walk(rr, &cs, rows, 0, nb, &pr, agg_dense_sel_rows, wid); + if (ferr) { if (err) ray_error_free(err); err = ferr; } + } + if (err) ray_scan_fail_note(rr->fail, start, err); + agg_curs_free(&cs, rr); + agg_sel_scratch_free(&sc); +} + +/* Row mode on runs: rows [begin, limit), a key run view at a time; a + * declined vector (or plain segment) is walked by the per-row body. */ +static __attribute__((noinline)) void agg_dense_runs_rows(agg_dense_ctx_t* c, uint32_t task, int64_t begin, int64_t limit) { + const agg_rr_t* rr = c->rr; + if (ray_scan_fail_skip(rr->fail, begin)) return; + agg_curs_t cs; + if (!agg_curs_init(&cs, rr)) { ray_scan_fail_note(rr->fail, begin, ray_error("oom", NULL)); return; } + agg_dense_runs_t t = { .c = c, .loc = &c->locals[task] }; + ray_enc_vview_t view; /* the task's key view: on its stack */ + for (int64_t r = begin; r < limit && !agg_cancelled() && !c->locals[task].oom; ) { + int64_t vlo, vhi; + ray_t* err = NULL; + int vr = ray_col_src_runview(rr->srcs[0], r, &view, &vlo, &vhi, &err); + if (vr < 0) { ray_scan_fail_note(rr->fail, begin, err); break; } + const int64_t re = vhi < limit ? vhi : limit; + if (vr > 0) { + t.vlo = vlo; t.idx = NULL; t.r0 = r; t.r1 = re; + (void)ray_enc_runs(&view, &t, agg_dense_run_rows); + if (t.bad) { ray_scan_fail_note(rr->fail, begin, agg_dense_runs_bad()); break; } + } else { + bool ok = true; + for (int64_t b = r; b < re && ok; b += 8192) + ok = agg_walk_cs(rr, &cs, c, agg_dense_phaseA_fn, task, b, re - b < 8192 ? re : b + 8192, begin); + if (!ok) break; + } + r = re; + } + agg_curs_free(&cs, rr); +} + +/* One slab per logical task, independent of the physical worker executing it. + * A large pool can run a memory-bounded number of dense tasks safely. Each + * 8192-row sub-block runs over the whole columns, or by pieces when a source + * is staged (whatever the block's alignment, through the task's cursors; a + * range error stops the task). */ +static void agg_dense_task_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_dense_ctx_t* c = raw; + int64_t chunk = c->task_rows / c->n_tasks; + for (int64_t task = start; task < end; task++) { + agg_dense_local_t* loc = &c->locals[task]; + /* Storage was allocated once by the coordinator. Initialize each + * slab on its consuming task, without another pool dispatch. */ + agg_dense_local_init(loc, loc->slots, c->block); + if (loc->eager) for (int64_t s = 0; s < loc->slots; s++) { loc->first_row[s] = INT64_MAX; for (uint32_t a = 0; a < c->n_aggs; a++) c->vts[a]->init(loc->states + (size_t)s * c->block + c->off[a]); } int64_t begin = chunk * task; int64_t limit = task + 1 == c->n_tasks ? c->task_rows : chunk * (task + 1); - if (c->sel) agg_dense_phaseA_fn(c, (uint32_t)task, begin, limit); - else for (int64_t row = begin; row < limit && !agg_cancelled(); row += 8192) { - ray_pool_scan_at(c->task_rows, row, limit); - agg_dense_phaseA_fn(c, (uint32_t)task, row, limit - row < 8192 ? limit : row + 8192); + if (c->sel) agg_dense_phaseA_sel(c, (uint32_t)task, begin, limit); + else if (!c->rr->staged) + for (int64_t row = begin; row < limit && !agg_cancelled(); row += 8192) { + ray_pool_scan_at(c->task_rows, row, limit); + agg_dense_phaseA_fn(c, c->whole, (uint32_t)task, row, limit - row < 8192 ? limit : row + 8192); + } + else { + agg_curs_t cs; + if (!agg_curs_init(&cs, c->rr)) ray_scan_fail_note(c->rr->fail, begin, ray_error("oom", NULL)); + else { + for (int64_t row = begin; row < limit && !agg_cancelled(); row += 8192) + if (!agg_walk_cs(c->rr, &cs, c, agg_dense_phaseA_fn, (uint32_t)task, row, + limit - row < 8192 ? limit : row + 8192, begin)) break; + agg_curs_free(&cs, c->rr); + } + } + if (loc->eager) for (int64_t s = 0; s < loc->slots; s++) + if (loc->first_row[s] != INT64_MAX) + loc->occupied[s / 64] |= UINT64_C(1) << (s % 64); + } +} + +/* agg_dense_task_fn for ctx->runs (the slab's set-up and occupancy as + * there), its own instance so the plain one keeps its code. */ +static void agg_dense_task_runs_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_dense_ctx_t* c = raw; + int64_t chunk = c->task_rows / c->n_tasks; + for (int64_t task = start; task < end; task++) { + agg_dense_local_t* loc = &c->locals[task]; + agg_dense_local_init(loc, loc->slots, c->block); + if (loc->eager) for (int64_t s = 0; s < loc->slots; s++) { + loc->first_row[s] = INT64_MAX; + for (uint32_t a = 0; a < c->n_aggs; a++) + c->vts[a]->init(loc->states + (size_t)s * c->block + c->off[a]); } + int64_t begin = chunk * task; + int64_t limit = task + 1 == c->n_tasks ? c->task_rows : chunk * (task + 1); + if (c->sel) agg_dense_runs_sel(c, (uint32_t)task, begin, limit); + else agg_dense_runs_rows(c, (uint32_t)task, begin, limit); if (loc->eager) for (int64_t s = 0; s < loc->slots; s++) if (loc->first_row[s] != INT64_MAX) loc->occupied[s / 64] |= UINT64_C(1) << (s % 64); @@ -2240,13 +3815,190 @@ static int64_t agg_slots_topn_select(ray_pool_t* pool, const agg_vtable_t* vt, return kept; } -/* Shared output stage. Takes ownership of states/first, borrows the - * prepared aggregate layout and descriptors. */ +/* Lean top-N emit over a shared dense slab. The slab's occupancy bitmap is + * walked in disjoint word ranges, one task each, in chunks of LEAN_CHUNK + * slots: a chunk's filter-aggregate values feed a bounded candidate set per + * task, the union of the sets gives the N-th value (the threshold), and a + * second walk keeps the slots that pass agg_topn_mark. Only the kept slots + * are stored, so the emit allocates O(N) (plus ties) instead of one entry per + * group; the kept set and its slot order are those of the generic path + * (agg_slots_topn_select over every occupied slot). The filter aggregate is + * read from the states, or from a count-only slab of u32 counters. */ +enum { LEAN_CHUNK = 4096, LEAN_CAND_BUDGET = 8 << 20 }; +typedef struct { + const agg_vtable_t* vt; + const char* states; + size_t block, off; + int64_t param; + const uint32_t* cnt32; +} agg_lean_src_t; + +typedef struct { + const agg_lean_src_t* src; + const uint64_t* occ; + int64_t words; + const ray_group_emit_filter_t* ef; + uint32_t tasks; + int pass; /* 0: candidates and group counts; 1: the kept slots */ + int64_t cap; + double* cand; /* [tasks][3 * cap]: the task's pool (2 * cap), then scratch */ + int64_t* pool_n; + int64_t* groups; + bool have_thr; + double thr; + int64_t** kept; + int64_t* kept_n; + int64_t* kept_cap; + _Atomic(int) fail; +} agg_lean_ctx_t; + +static bool agg_lean_vals(const agg_lean_src_t* s, const int64_t* slots, int64_t n, double* out) { + if (s->cnt32) { + for (int64_t i = 0; i < n; i++) out[i] = (double)s->cnt32[slots[i]]; + return true; + } + return agg_group_values_f64(s->vt, s->states, s->block, s->off, slots, n, s->param, out); +} + +/* The next chunk of occupied slots of words [*w, w1); *bits holds the rest of + * word *w (consumed bits cleared). */ +static int64_t agg_lean_chunk(const uint64_t* occ, int64_t* w, uint64_t* bits, int64_t w1, int64_t* slots) { + int64_t n = 0; + for (;;) { + while (*bits) { + if (n == LEAN_CHUNK) return n; + slots[n++] = *w * 64 + __builtin_ctzll(*bits); + *bits &= *bits - 1; + } + if (++*w >= w1) return n; + *bits = occ[*w]; + } +} + +static void agg_lean_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_lean_ctx_t* c = raw; + const ray_group_emit_filter_t* ef = c->ef; + int64_t slots[LEAN_CHUNK]; + double vals[LEAN_CHUNK]; + uint8_t keep[LEAN_CHUNK]; + for (int64_t t = start; t < end; t++) { + int64_t w0 = c->words / c->tasks * t; + int64_t w1 = t + 1 == (int64_t)c->tasks ? c->words : c->words / c->tasks * (t + 1); + if (w0 >= w1) continue; + int64_t w = w0; + uint64_t bits = c->occ[w]; + for (;;) { + int64_t n = agg_lean_chunk(c->occ, &w, &bits, w1, slots); + if (n == 0) break; + if (!agg_lean_vals(c->src, slots, n, vals)) { + atomic_store_explicit(&c->fail, 1, memory_order_relaxed); + return; + } + if (c->pass == 0) { + c->groups[t] += n; + if (c->cap > 0) { + double* pool = c->cand + (size_t)t * 3 * c->cap; + double* tmp = pool + 2 * c->cap; + int64_t hn; + agg_topn_candidates(vals, n, c->cap, ef->desc, tmp, &hn); + memcpy(pool + c->pool_n[t], tmp, (size_t)hn * sizeof(double)); + c->pool_n[t] += hn; + if (c->pool_n[t] > c->cap) { + agg_topn_candidates(pool, c->pool_n[t], c->cap, ef->desc, tmp, &hn); + memcpy(pool, tmp, (size_t)hn * sizeof(double)); + c->pool_n[t] = hn; + } + } + } else { + int64_t k = agg_topn_mark(vals, n, ef, c->have_thr, c->thr, keep); + if (c->kept_n[t] + k > c->kept_cap[t]) { + int64_t nc = c->kept_cap[t] ? c->kept_cap[t] * 2 : 64; + while (nc < c->kept_n[t] + k) nc *= 2; + int64_t* p = ray_realloc_raw(c->kept[t], (size_t)nc * sizeof(int64_t)); + if (!p) { atomic_store_explicit(&c->fail, 1, memory_order_relaxed); return; } + c->kept[t] = p; c->kept_cap[t] = nc; + } + for (int64_t i = 0; i < n; i++) + if (keep[i]) c->kept[t][c->kept_n[t]++] = slots[i]; + } + } + } +} + +/* The kept slots among the occupied ones, ascending, in *out (the caller + * frees it); their count, or -1 when the filter aggregate has no scalar order + * or memory ran out. */ +static int64_t agg_dense_lean_select(ray_pool_t* pool, const agg_lean_src_t* src, + const uint64_t* occ, int64_t total_slots, const ray_group_emit_filter_t* ef, + int64_t** out, bool* have_thr, double* thr) { + *out = NULL; *have_thr = false; *thr = 0; + int64_t words = (total_slots + 63) / 64; + int64_t cap = ef->top_count_take > 0 ? ef->top_count_take : 0; + uint32_t tasks = pool && total_slots >= RAY_PARALLEL_THRESHOLD ? ray_pool_total_workers(pool) * 4 : 1; + if (tasks > RAY_POOL_INIT_TASKS) tasks = RAY_POOL_INIT_TASKS; + if ((int64_t)tasks > words) tasks = (uint32_t)words; + if (cap > 0 && (int64_t)tasks * 3 * cap > LEAN_CAND_BUDGET) { + int64_t fit = LEAN_CAND_BUDGET / (3 * cap); + if (fit < tasks) tasks = fit < 1 ? 1 : (uint32_t)fit; + } + if (tasks < 1) tasks = 1; + size_t per = cap > 0 ? (size_t)cap : 1; + double* cand = ray_alloc_raw((size_t)tasks * 3 * per * sizeof(double)); + double* all = ray_alloc_raw((size_t)tasks * per * sizeof(double)); + int64_t* meta = ray_calloc_raw((size_t)tasks * 4 * sizeof(int64_t)); + int64_t** kept = ray_calloc_raw((size_t)tasks * sizeof(int64_t*)); + int64_t result = -1; + if (cand && all && meta && kept) { + agg_lean_ctx_t c = { .src = src, .occ = occ, .words = words, .ef = ef, .tasks = tasks, + .cap = cap, .cand = cand, .pool_n = meta, .groups = meta + tasks, + .kept = kept, .kept_n = meta + 2 * tasks, .kept_cap = meta + 3 * tasks }; + atomic_init(&c.fail, 0); + if (tasks > 1) ray_pool_dispatch_n(pool, agg_lean_fn, &c, tasks); + else agg_lean_fn(&c, 0, 0, 1); + if (!atomic_load_explicit(&c.fail, memory_order_relaxed)) { + int64_t total = 0, nc = 0; + for (uint32_t t = 0; t < tasks; t++) { + total += c.groups[t]; + memcpy(all + nc, cand + (size_t)t * 3 * per, (size_t)c.pool_n[t] * sizeof(double)); + nc += c.pool_n[t]; + } + if (cap > 0) c.have_thr = agg_topn_union_threshold(all, nc, total, ef, &c.thr); + *have_thr = c.have_thr; *thr = c.thr; + c.pass = 1; + if (tasks > 1) ray_pool_dispatch_n(pool, agg_lean_fn, &c, tasks); + else agg_lean_fn(&c, 0, 0, 1); + if (!atomic_load_explicit(&c.fail, memory_order_relaxed)) { + int64_t n = 0; + for (uint32_t t = 0; t < tasks; t++) n += c.kept_n[t]; + int64_t* o = ray_alloc_raw((size_t)(n > 0 ? n : 1) * sizeof(int64_t)); + if (o) { + int64_t at = 0; + for (uint32_t t = 0; t < tasks; t++) { + if (c.kept_n[t]) memcpy(o + at, c.kept[t], (size_t)c.kept_n[t] * sizeof(int64_t)); + at += c.kept_n[t]; + } + *out = o; + result = n; + } + } + } + for (uint32_t t = 0; t < tasks; t++) ray_free_raw(kept[t]); + } + ray_free_raw(cand); ray_free_raw(all); ray_free_raw(meta); ray_free_raw(kept); + return result; +} + +/* Shared output stage. Takes ownership of states/first/occ (occ: a bitmap of + * the occupied slots that stands in for first; first is then NULL), borrows the + * prepared aggregate layout and descriptors. u32c: gstates is a count-only slab + * of u32 counters, one per slot, standing for every (COUNT) aggregate. */ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t* ext, ray_pool_t* pool, const agg_vo_t* vo, const agg_desc_t* d, - int64_t total_slots, char* gstates, int64_t* gfirst, + int64_t total_slots, char* gstates, int64_t* gfirst, const uint64_t* occ, const dense_plan_t* key_plan, int64_t key_part_slots, uint32_t key_bits, - const ray_group_emit_filter_t* ef, int64_t group_limit) { + const ray_group_emit_filter_t* ef, int64_t group_limit, const dense_plan_t* slot_plan, + bool u32c, int64_t* pre_slots, int64_t pre_n) { uint32_t n_keys = ext->n_keys, n_aggs = ext->n_aggs; const agg_vtable_t** vts = vo->vts; const size_t* off = vo->off; @@ -2257,20 +4009,47 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t * (the natural build order) rather than sorting by first_row. gfirst[s] is * still the gather index (any member row) for the key columns. */ int64_t ng = 0; - for (int64_t s = 0; s < total_slots; s++) if (gfirst[s] != INT64_MAX) ng++; + int64_t* occupied_slot = NULL; + int64_t* first_row_ordered = NULL; + /* A slab with an occupancy bitmap under a top-N filter keeps only the + * groups the filter keeps (agg_dense_lean_select): no entry per group. */ + if (occ && ef && key_plan && group_limit <= 0) { + agg_lean_src_t src = { .vt = vts[ef->agg_index], .states = gstates, .block = block, + .off = off[ef->agg_index], .param = ext->agg_k ? ext->agg_k[ef->agg_index] : 0, + .cnt32 = u32c ? (const uint32_t*)gstates : NULL }; + bool lean_thr; double lean_thrv; + int64_t kept = pre_n >= 0 ? pre_n : agg_dense_lean_select(pool, &src, occ, total_slots, ef, &occupied_slot, &lean_thr, &lean_thrv); + if (pre_n >= 0) occupied_slot = pre_slots; + if (kept >= 0) { + ng = kept; + route_stats.topn_native = true; + route_stats.topn_kept = kept; + route_stats.dense_emit_slots = (uint64_t)kept; + ray_profile_tick("dense: selected top-N groups from the slab"); + goto emit; + } + if (u32c) { + agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); + ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); + return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); + } + } + if (occ) for (int64_t w = 0; w < (total_slots + 63) / 64; w++) ng += __builtin_popcountll(occ[w]); + else for (int64_t s = 0; s < total_slots; s++) if (gfirst[s] != INT64_MAX) ng++; + route_stats.dense_emit_slots = (uint64_t)ng; ray_profile_tick("dense: freed slabs and counted groups"); - int64_t* occupied_slot = ray_alloc_raw((size_t)(ng > 0 ? ng : 1) * sizeof(int64_t)); - int64_t* first_row_ordered = key_plan ? NULL : ray_alloc_raw((size_t)(ng > 0 ? ng : 1) * sizeof(int64_t)); + occupied_slot = ray_alloc_raw((size_t)(ng > 0 ? ng : 1) * sizeof(int64_t)); + first_row_ordered = key_plan ? NULL : ray_alloc_raw((size_t)(ng > 0 ? ng : 1) * sizeof(int64_t)); if (!occupied_slot || (!key_plan && !first_row_ordered)) { ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); - ray_free_raw(gstates); ray_free_raw(gfirst); + ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } { int64_t i = 0; for (int64_t s = 0; s < total_slots; s++) - if (gfirst[s] != INT64_MAX) { + if (occ ? (occ[s >> 6] >> (s & 63)) & 1 : gfirst[s] != INT64_MAX) { if (first_row_ordered) first_row_ordered[i] = gfirst[s]; occupied_slot[i] = s; i++; } @@ -2289,7 +4068,7 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t ray_free_raw(hkey); ray_free_raw(hslot); ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); - ray_free_raw(gstates); ray_free_raw(gfirst); + ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); return ray_error("oom", NULL); } { @@ -2362,26 +4141,33 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t ray_profile_tick("dense: selected top-N groups"); } +emit: + ; ray_t* result = ray_table_new(n_keys + n_aggs); if (!result || RAY_IS_ERR(result)) { agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); - ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); + ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); return result ? result : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } for (uint32_t k = 0; k < n_keys; k++) { - ray_t* kc = key_plan ? col_vec_new(key_cols[k], ng) - : ray_group_gather(key_cols[k], first_row_ordered, ng); + /* A staged key is never gathered at first rows (random reads): its + * value is rebuilt from the group's slot, the inverse of + * agg_dense_slot (agg_dense_code: null slot, compaction). */ + const dense_plan_t* kp = key_plan ? key_plan : d->key_srcs[k] ? slot_plan : NULL; + ray_t* kc = kp ? col_vec_new(key_cols[k], ng) + : ray_group_gather(key_cols[k], first_row_ordered, ng); if (!kc || RAY_IS_ERR(kc)) { agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); - ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); + ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); ray_release(result); return kc ? kc : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } - if (key_plan) { + if (kp) { kc->len = ng; if (ray_vec_may_have_nulls(key_cols[k])) kc->attrs |= RAY_ATTR_HAS_NULLS; if (kc->type == RAY_SYM) ray_sym_vec_adopt_domain(kc, sym_domain_rep(key_cols[k])); - agg_dense_key_emit_t emit = {key_plan, occupied_slot, key_part_slots, key_bits, kc, k}; + agg_dense_key_emit_t emit = {kp, occupied_slot, key_plan ? key_part_slots : 0, + key_plan ? key_bits : 0, kc, k}; ray_pool_dispatch(pool, agg_dense_key_emit, &emit, ng); ray_group_key_settle_nulls(kc); } @@ -2390,6 +4176,20 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t } for (uint32_t a = 0; a < n_aggs; a++) { + if (u32c) { /* the slab's counters are the count column */ + ray_t* cnt_out = ray_vec_new(RAY_I64, ng); + if (!cnt_out || RAY_IS_ERR(cnt_out)) { + ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); + ray_release(result); return cnt_out ? cnt_out : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); + } + cnt_out->len = ng; + const uint32_t* cnt = (const uint32_t*)gstates; + int64_t* dst = (int64_t*)ray_data(cnt_out); + for (int64_t i = 0; i < ng; i++) dst[i] = cnt[occupied_slot[i]]; + result = ray_table_add_col(result, agg_result_col_name(agg_syms[a], ext->agg_ops[a]), cnt_out); + ray_release(cnt_out); + continue; + } /* Buffered top_n/bot_n produce a LIST cell per group (a native vector); * median and all streaming aggs produce a scalar out_type cell. */ bool is_list = (vts[a]->out_type == RAY_LIST); @@ -2397,7 +4197,7 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t : ray_vec_new(vts[a]->out_type, ng); if (!out || RAY_IS_ERR(out)) { agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); - ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); + ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); ray_release(result); return out ? out : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } out->len = ng; @@ -2422,7 +4222,7 @@ static ray_t* agg_dense_finish(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t /* Finalize is done reading the global slab → destroy its buffered per-group * state exactly once before freeing the slab. */ agg_dense_slab_destroy_states(gstates, total_slots, vts, off, block, n_aggs); - ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); + ray_free_raw(occupied_slot); ray_free_raw(first_row_ordered); ray_free_raw(gstates); ray_free_raw(gfirst); ray_free_raw((void*)occ); if (result && !RAY_IS_ERR(result) && agg_cancelled()) { ray_release(result); return ray_error("cancel", NULL); } return result; } @@ -2458,19 +4258,65 @@ typedef struct { char* states; int64_t* first; _Atomic(bool) failed; + const agg_rr_t* rr; /* sources; staged ones are read by range */ + const agg_view_t* whole; + /* The staged sources each pass reads (rr's otherwise): the histogram + * the keys, the scatter the inputs, so each decodes once. */ + const agg_rr_t* count_rr; + const agg_rr_t* scatter_rr; } agg_dense_partition_ctx_t; -/* Slots and partition counts of input positions [begin, limit). */ -static void agg_dense_partition_count_rows(agg_dense_partition_ctx_t* c, uint64_t* count, +/* One source task of the histogram / scatter passes: its count row, and + * its write cursors (persisting across the pieces of the task). */ +typedef struct { + agg_dense_partition_ctx_t* c; + uint64_t* count; + uint64_t* cursor; +} agg_part_task_t; + +/* Run body over input positions [begin, limit) of a source task: the + * whole columns, pieces of the rows (R-WALK), or runs of the selected rows + * (R-SPARSE through the task's cursors). */ +static void agg_dense_partition_run(agg_dense_partition_ctx_t* c, const agg_rr_t* rr, agg_part_task_t* t, + agg_body_fn body, uint32_t wid, int64_t begin, int64_t limit) { + if (!rr->staged) { + if (begin >= limit) return; + /* These passes are the first reads of the keys and the aggregate + * inputs: keep the rows past each block requested from storage + * (scan read-ahead), from the input row the block starts at — + * selected rows come in order. */ + const int64_t* sel = c->selected_rows; + int64_t stop = sel ? sel[limit - 1] + 1 : limit; + for (int64_t b = begin; b < limit; b += 8192) { + ray_pool_scan_at(c->in_rows, sel ? sel[b] : b, stop); + body(t, c->whole, wid, b, limit - b > 8192 ? b + 8192 : limit); + } + return; + } + if (!c->selected_rows) { (void)agg_walk(rr, t, body, wid, begin, limit, begin); return; } + if (ray_scan_fail_skip(rr->fail, begin)) return; + agg_curs_t cs; + if (!agg_curs_init(&cs, rr)) { ray_scan_fail_note(rr->fail, begin, ray_error("oom", NULL)); return; } + ray_t* err = agg_idx_walk(rr, &cs, c->selected_rows, begin, limit, t, body, wid); + agg_curs_free(&cs, rr); + if (err) ray_scan_fail_note(rr->fail, begin, err); +} + +static void agg_dense_partition_count_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t begin, int64_t limit) { - const void* data = ray_data(c->key); + (void)wid; + agg_part_task_t* t = raw; + agg_dense_partition_ctx_t* c = t->c; + uint64_t* count = t->count; + const int64_t kbase = v->base; + const void* data = v->key_data[0]; if (c->plan->n_keys > 1) { #define PART_SLOT_MULTI(COMPONENT) \ for (int64_t r = begin; r < limit; r++) { \ - int64_t source = c->selected_rows ? c->selected_rows[r] : r; \ + int64_t source = (c->selected_rows ? c->selected_rows[r] : r) - kbase; \ int64_t slot = 0; \ for (uint32_t k = 0; k < c->plan->n_keys; k++) \ - slot += COMPONENT(c->plan, k, agg_read_key_i64(c->keys[k], c->key_data[k], source)) * c->plan->strides[k]; \ + slot += COMPONENT(c->plan, k, agg_read_key_i64_raw(c->keys[k]->type, v->key_attrs[k], v->key_data[k], source)) * c->plan->strides[k]; \ c->gids[r] = (uint32_t)slot; \ count[slot & (c->parts - 1)]++; \ } @@ -2482,18 +4328,18 @@ static void agg_dense_partition_count_rows(agg_dense_partition_ctx_t* c, uint64_ #define PART_COUNT(T) do { \ const T* p = data; \ for (int64_t r = begin; r < limit; r++) { \ - uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, (int64_t)p[c->selected_rows ? c->selected_rows[r] : r]); \ + uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, (int64_t)p[(c->selected_rows ? c->selected_rows[r] : r) - kbase]); \ c->gids[r] = slot; \ count[slot & (c->parts - 1)]++; \ } \ } while (0) switch (c->key->type) { - case RAY_I64: case RAY_TIMESTAMP: PART_COUNT(int64_t); break; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: PART_COUNT(int64_t); break; case RAY_I32: case RAY_DATE: case RAY_TIME: PART_COUNT(int32_t); break; case RAY_I16: PART_COUNT(int16_t); break; case RAY_U8: case RAY_BOOL: PART_COUNT(uint8_t); break; case RAY_SYM: - switch (c->key->attrs & RAY_SYM_W_MASK) { + switch (v->key_attrs[0] & RAY_SYM_W_MASK) { case RAY_SYM_W8: PART_COUNT(uint8_t); break; case RAY_SYM_W16: PART_COUNT(uint16_t); break; case RAY_SYM_W32: PART_COUNT(uint32_t); break; @@ -2505,28 +4351,19 @@ static void agg_dense_partition_count_rows(agg_dense_partition_ctx_t* c, uint64_ } static void agg_dense_partition_count(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; agg_dense_partition_ctx_t* c = raw; for (int64_t task = start; task < end; task++) { int64_t begin = c->rows / c->sources * task; int64_t limit = task + 1 == c->sources ? c->rows : c->rows / c->sources * (task + 1); - uint64_t* count = c->counts + task * c->parts; - if (begin >= limit) continue; - /* This pass is the first read of the keys: keep the rows past each - * block requested from storage (scan read-ahead), from the input - * row the block starts at — selected rows come in order. */ - const int64_t* sel = c->selected_rows; - int64_t stop = sel ? sel[limit - 1] + 1 : limit; - for (int64_t b = begin; b < limit; b += 8192) { - ray_pool_scan_at(c->in_rows, sel ? sel[b] : b, stop); - agg_dense_partition_count_rows(c, count, b, limit - b > 8192 ? b + 8192 : limit); - } + agg_part_task_t t = { c, c->counts + task * c->parts, NULL }; + agg_dense_partition_run(c, c->count_rr, &t, agg_dense_partition_count_rows, wid, begin, limit); } } /* Resolve native widths outside the row loop. A runtime-sized memcpy per - * value dominated scatter for eight-byte inputs and mixed aggregates. */ -static void agg_dense_partition_field(agg_dense_partition_ctx_t* c, const void* data, + * value dominated scatter for eight-byte inputs and mixed aggregates. + * `data` is the view's pointer at row `base`. */ +static void agg_dense_partition_field(agg_dense_partition_ctx_t* c, const void* data, int64_t base, uint8_t width, size_t field, const uint64_t* starts, int64_t begin, int64_t end) { uint64_t cursor[RAY_POOL_INIT_TASKS / 2]; assert(c->parts <= RAY_POOL_INIT_TASKS / 2); @@ -2535,7 +4372,7 @@ static void agg_dense_partition_field(agg_dense_partition_ctx_t* c, const void* for (int64_t r = begin; r < end; r++) { \ uint32_t part = c->gids[r] & (c->parts - 1); \ memcpy(c->payload + cursor[part]++ * c->record_size + field, \ - (const char*)data + (size_t)(c->selected_rows ? c->selected_rows[r] : r) * (W), (W)); \ + (const char*)data + (size_t)((c->selected_rows ? c->selected_rows[r] : r) - base) * (W), (W)); \ } \ } while (0) switch (width) { @@ -2547,18 +4384,23 @@ static void agg_dense_partition_field(agg_dense_partition_ctx_t* c, const void* #undef SCATTER_FIELD } -/* Records of input positions [begin, limit), written at `cursor`. */ -static void agg_dense_partition_scatter_rows(agg_dense_partition_ctx_t* c, uint64_t* cursor, +static void agg_dense_partition_scatter_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t begin, int64_t limit) { + (void)wid; + agg_part_task_t* t = raw; + agg_dense_partition_ctx_t* c = t->c; + uint64_t* cursor = t->cursor; + const int64_t base = v->base; const agg_valdesc_t* vd = &c->values; if (vd->n_aggs == 1 && vd->val_data[0] && !vd->val2_data[0]) { + const char* vals = v->val_data[0]; #define SCATTER_UNARY(W) do { \ for (int64_t r = begin; r < limit; r++) { \ uint32_t slot = c->gids[r]; \ uint32_t gid = slot >> c->bits, part = slot & (c->parts - 1); \ char* dst = c->payload + cursor[part]++ * (4 + (W)); \ memcpy(dst, &gid, 4); \ - memcpy(dst + 4, (const char*)vd->val_data[0] + (size_t)(c->selected_rows ? c->selected_rows[r] : r) * (W), (W)); \ + memcpy(dst + 4, vals + (size_t)((c->selected_rows ? c->selected_rows[r] : r) - base) * (W), (W)); \ } \ } while (0) switch (vd->val_esz[0]) { @@ -2587,12 +4429,12 @@ static void agg_dense_partition_scatter_rows(agg_dense_partition_ctx_t* c, uint6 } size_t emitted = sizeof(uint32_t); for (uint32_t a = 0; a < vd->n_aggs; a++) { - if (vd->val_data[a] && c->value_offsets[a] >= emitted) { - agg_dense_partition_field(c, vd->val_data[a], vd->val_esz[a], c->value_offsets[a], chunk_starts, chunk, chunk_end); + if (v->val_data[a] && c->value_offsets[a] >= emitted) { + agg_dense_partition_field(c, v->val_data[a], base, vd->val_esz[a], c->value_offsets[a], chunk_starts, chunk, chunk_end); emitted = c->value_offsets[a] + vd->val_esz[a]; } - if (vd->val2_data[a] && c->value2_offsets[a] >= emitted) { - agg_dense_partition_field(c, vd->val2_data[a], vd->val2_esz[a], c->value2_offsets[a], chunk_starts, chunk, chunk_end); + if (v->val2_data[a] && c->value2_offsets[a] >= emitted) { + agg_dense_partition_field(c, v->val2_data[a], base, vd->val2_esz[a], c->value2_offsets[a], chunk_starts, chunk, chunk_end); emitted = c->value2_offsets[a] + vd->val2_esz[a]; } } @@ -2600,7 +4442,6 @@ static void agg_dense_partition_scatter_rows(agg_dense_partition_ctx_t* c, uint6 } static void agg_dense_partition_scatter(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; agg_dense_partition_ctx_t* c = raw; for (int64_t task = start; task < end; task++) { int64_t begin = c->rows / c->sources * task; @@ -2609,15 +4450,8 @@ static void agg_dense_partition_scatter(void* raw, uint32_t wid, int64_t start, uint64_t cursor[RAY_POOL_INIT_TASKS / 2]; assert(c->parts <= RAY_POOL_INIT_TASKS / 2); memcpy(cursor, starts, c->parts * sizeof(*cursor)); - if (begin >= limit) continue; - /* The first read of the aggregate inputs: keep the rows past each - * block requested, as in the count pass. */ - const int64_t* sel = c->selected_rows; - int64_t stop = sel ? sel[limit - 1] + 1 : limit; - for (int64_t b = begin; b < limit; b += 8192) { - ray_pool_scan_at(c->in_rows, sel ? sel[b] : b, stop); - agg_dense_partition_scatter_rows(c, cursor, b, limit - b > 8192 ? b + 8192 : limit); - } + agg_part_task_t t = { c, NULL, cursor }; + agg_dense_partition_run(c, c->scatter_rr, &t, agg_dense_partition_scatter_rows, wid, begin, limit); } } @@ -2720,15 +4554,17 @@ static void agg_dense_partition_merge(void* raw, uint32_t wid, int64_t start, in static size_t agg_partition_record(const agg_desc_t* d, uint32_t n, size_t* x_offsets, size_t* y_offsets) { size_t bytes = sizeof(uint32_t); + /* An input's identity: its plain pointer, or its staged source (one + * source per column and table: ray_graph_bind_col deduplicates). */ for (uint32_t f = 0; f < 2 * n; f++) { uint32_t a = f / 2; - const void* data = f % 2 ? d->val2_data[a] : d->val_data[a]; + const void* data = f % 2 ? d->val2_id[a] : d->val_id[a]; uint8_t width = f % 2 ? d->val2_esz[a] : d->val_esz[a]; size_t offset = bytes; bool found = false; for (uint32_t prev = 0; data && prev < f; prev++) { uint32_t b = prev / 2; - const void* other = prev % 2 ? d->val2_data[b] : d->val_data[b]; + const void* other = prev % 2 ? d->val2_id[b] : d->val_id[b]; uint8_t size = prev % 2 ? d->val2_esz[b] : d->val_esz[b]; if (other == data && size == width) { if (x_offsets) offset = prev % 2 ? y_offsets[b] : x_offsets[b]; @@ -2754,8 +4590,9 @@ static uint32_t agg_dense_partition_parts(uint32_t sources, int64_t slots) { static ray_t* agg_dense_partitioned(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t* ext, ray_pool_t* pool, const dense_plan_t* plan, int64_t rows, - const agg_vo_t* vo, const agg_desc_t* d, ray_t* selection, + const agg_vo_t* vo, agg_desc_t* d, ray_t* selection, const ray_group_emit_filter_t* ef) { + ray_t* ferr = NULL; /* R-FAIL: a range error of a staged source */ uint32_t workers = ray_pool_total_workers(pool); uint32_t sources = workers; if (sources > RAY_POOL_INIT_TASKS / 2) sources = RAY_POOL_INIT_TASKS / 2; @@ -2766,13 +4603,32 @@ static ray_t* agg_dense_partitioned(ray_t** key_cols, int64_t* key_syms, ray_op_ int64_t slots = part_slots * parts; agg_dense_partition_ctx_t c = { .key = key_cols[0], .keys = key_cols, .key_data = d->key_data, + .rr = &d->rr, .whole = &d->whole, .plan = plan, .rows = rows, .part_slots = part_slots, .in_rows = selection ? ray_rowsel_meta(selection)->nrows : rows, .sources = sources, .parts = parts, .bits = bits, .failed = false, .values = { .n_aggs = ext->n_aggs, .vts = vo->vts, .off = vo->off, .block = vo->block, - .val_data = d->val_data, .val_types = d->val_types, .val_hasnull = d->val_hasnull, .val_esz = d->val_esz, - .val2_data = d->val2_data, .val2_types = d->val2_types, .val2_hasnull = d->val2_hasnull, .val2_esz = d->val2_esz } + .val_data = d->val_id, .val_types = d->val_types, .val_hasnull = d->val_hasnull, .val_esz = d->val_esz, + .val2_data = d->val2_id, .val2_types = d->val2_types, .val2_hasnull = d->val2_hasnull, .val2_esz = d->val2_esz } }; + /* Per-pass source sets: a staged source leaves the pass that does not + * read it (its slot then reads as an absent input). */ + ray_col_src_t** pass_srcs = NULL; + agg_rr_t count_rr = d->rr, scatter_rr = d->rr; + c.count_rr = c.scatter_rr = &d->rr; + if (d->staged) { + uint32_t ns = d->rr.n_src, nk = d->rr.n_keys; + pass_srcs = ray_alloc_raw((size_t)2 * (ns ? ns : 1) * sizeof(*pass_srcs)); + if (!pass_srcs) goto failed; + for (uint32_t i = 0; i < ns; i++) { + pass_srcs[i] = i < nk ? d->rr.srcs[i] : NULL; + pass_srcs[ns + i] = i < nk ? NULL : d->rr.srcs[i]; + } + count_rr.srcs = pass_srcs; + scatter_rr.srcs = pass_srcs + ns; + c.count_rr = &count_rr; + c.scatter_rr = &scatter_rr; + } if (selection) { c.selection_indices = ray_rowsel_to_indices(selection); if (!c.selection_indices || RAY_IS_ERR(c.selection_indices)) goto failed; @@ -2788,7 +4644,9 @@ static ray_t* agg_dense_partitioned(ray_t** key_cols, int64_t* key_syms, ray_op_ c.tasks = ray_alloc_raw((size_t)(parts + split_budget) * sizeof(*c.tasks)); if (!c.counts || !c.gids || !c.tasks || !c.payload) goto failed; c.starts = c.counts + (size_t)sources * parts; + agg_desc_advise(d, selection ? ray_rowsel_meta(selection)->nrows : rows); ray_pool_dispatch_n(pool, agg_dense_partition_count, &c, sources); + if (d->staged && (ferr = ray_scan_fail_finish(&d->fail, pool)) != NULL) goto failed; if (agg_cancelled()) goto failed; uint64_t offset = 0; for (uint32_t part = 0; part < parts; part++) { @@ -2817,6 +4675,7 @@ static ray_t* agg_dense_partitioned(ray_t** key_cols, int64_t* key_syms, ray_op_ if (!c.states || !c.first) goto failed; ray_profile_tick("dense partition: histogram"); ray_pool_dispatch_n(pool, agg_dense_partition_scatter, &c, sources); + if (d->staged && (ferr = ray_scan_fail_finish(&d->fail, pool)) != NULL) goto failed; if (agg_cancelled()) goto failed; ray_profile_tick("dense partition: scattered rows"); ray_pool_dispatch_n(pool, agg_dense_partition_reduce, &c, c.n_tasks); @@ -2827,14 +4686,16 @@ static ray_t* agg_dense_partitioned(ray_t** key_cols, int64_t* key_syms, ray_op_ ray_profile_tick("dense partition: merged split partitions"); ray_free_raw(c.counts); ray_free_raw(c.gids); ray_free_raw(c.tasks); ray_free_raw(c.payload); ray_free_raw(c.value_offsets); ray_release(c.selection_indices); + ray_free_raw(pass_srcs); route_stats.dense_strategy = AGG_DENSE_PARTITIONED; route_stats.dense_tasks = c.n_tasks; route_stats.dense_local_slots = slots + extra_slots; - return agg_dense_finish(key_cols, key_syms, ext, pool, vo, d, slots, c.states, c.first, plan, part_slots, bits, ef, 0); + return agg_dense_finish(key_cols, key_syms, ext, pool, vo, d, slots, c.states, c.first, NULL, plan, part_slots, bits, ef, 0, plan, false, NULL, -1); failed: ray_free_raw(c.counts); ray_free_raw(c.gids); ray_free_raw(c.tasks); ray_free_raw(c.payload); ray_free_raw(c.value_offsets); ray_release(c.selection_indices); ray_free_raw(c.states); ray_free_raw(c.first); - return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); + ray_free_raw(pass_srcs); + return ferr ? ferr : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } typedef struct { @@ -2844,10 +4705,52 @@ typedef struct { const agg_desc_t* desc; uint32_t n_aggs; char* states; + uint32_t* cnt32; /* the count-only slab (agg_count32_slab), else NULL */ + int64_t slots; + /* A probe pass (agg_dense_cut_ties) reads the keys again and records, for + * each slot of pslots (ascending) whose bit is set in probe, the first row + * that holds it in pfirst; it updates no counter. */ + const uint64_t* probe; + const int64_t* pslots; + int64_t pn; + int64_t* pfirst; + ray_t* sel; /* the selection (selected-row space), else NULL */ + const int64_t* sel_prefix; + const agg_valdesc_t* vd; _Atomic(uint64_t)* occupied; - int64_t* first; } agg_dense_shared_ctx_t; +static inline void agg_probe_note(const agg_dense_shared_ctx_t* c, uint32_t slot, int64_t row) { + if (!((c->probe[slot >> 6] >> (slot & 63)) & 1)) return; + int64_t lo = 0, hi = c->pn - 1; + while (lo < hi) { + int64_t mid = (lo + hi) / 2; + if (c->pslots[mid] < (int64_t)slot) lo = mid + 1; else hi = mid; + } + int64_t seen = __atomic_load_n(&c->pfirst[lo], __ATOMIC_RELAXED); + while (row < seen && + !__atomic_compare_exchange_n(&c->pfirst[lo], &seen, row, true, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) {} +} + +static void agg_dense_shared_zero(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_dense_shared_ctx_t* c = raw; + memset(c->cnt32 + start, 0, (size_t)(end - start) * sizeof(uint32_t)); +} + +/* The count-only slab keeps no bit per row: a slot is occupied when its + * counter is not zero. */ +static void agg_dense_shared_cnt_occupied(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_dense_shared_ctx_t* c = raw; + for (int64_t w = start; w < end; w++) { + uint64_t m = 0; + for (int64_t b = 0; b < 64 && w * 64 + b < c->slots; b++) + if (c->cnt32[w * 64 + b]) m |= UINT64_C(1) << b; + atomic_store_explicit(&c->occupied[w], m, memory_order_relaxed); + } +} + static void agg_dense_shared_init(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; agg_dense_shared_ctx_t* c = raw; @@ -2857,83 +4760,261 @@ static void agg_dense_shared_init(void* raw, uint32_t wid, int64_t start, int64_ vo->vts[a]->init(c->states + (size_t)s * vo->block + vo->off[a]); } -static void agg_dense_shared_rows(void* raw, uint32_t wid, int64_t start, int64_t end) { +/* Rows [start, end) (at most 8192) read through view v. */ +static void agg_dense_shared_block(void* raw, const agg_view_t* v, uint32_t wid, int64_t begin, int64_t end) { (void)wid; agg_dense_shared_ctx_t* c = raw; const agg_vo_t* vo = c->layout; const agg_desc_t* d = c->desc; - const void* data = ray_data(c->key); + const void* data = v->key_data[0]; + const int64_t base = v->base; uint32_t gids[8192]; - for (int64_t begin = start; begin < end && !agg_cancelled(); begin += 8192) { - int64_t n = end - begin < 8192 ? end - begin : 8192; - #define SHARED_GIDS(T) do { \ - const T* p = data; \ - for (int64_t i = 0; i < n; i++) { \ - uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, (int64_t)p[begin + i]); \ - gids[i] = slot; \ - uint64_t bit = UINT64_C(1) << (slot % 64); \ - _Atomic(uint64_t)* word = &c->occupied[slot / 64]; \ - if (!(atomic_load_explicit(word, memory_order_relaxed) & bit)) \ - atomic_fetch_or_explicit(word, bit, memory_order_relaxed); \ - } \ - } while (0) - switch (c->key->type) { - case RAY_I64: case RAY_TIMESTAMP: SHARED_GIDS(int64_t); break; - case RAY_I32: case RAY_DATE: case RAY_TIME: SHARED_GIDS(int32_t); break; - case RAY_I16: SHARED_GIDS(int16_t); break; - case RAY_U8: case RAY_BOOL: SHARED_GIDS(uint8_t); break; - case RAY_SYM: - switch (c->key->attrs & RAY_SYM_W_MASK) { - case RAY_SYM_W8: SHARED_GIDS(uint8_t); break; - case RAY_SYM_W16: SHARED_GIDS(uint16_t); break; - case RAY_SYM_W32: SHARED_GIDS(uint32_t); break; - default: SHARED_GIDS(int64_t); break; - } - break; - } - #undef SHARED_GIDS - for (uint32_t a = 0; a < c->n_aggs; a++) { - const void* vals = (const char*)d->val_data[a] + (size_t)begin * d->val_esz[a]; - ray_valid_t valid = {vals, d->val_types[a], d->val_hasnull[a]}; - vo->vts[a]->update_shared(c->states + vo->off[a], vo->block, gids, vals, &valid, n); - } + int64_t n = end - begin; + uint32_t* cnt32 = c->cnt32; + const uint64_t* probe = c->probe; + #define SHARED_GIDS(T) do { \ + const T* p = (const T*)data + (begin - base); \ + for (int64_t i = 0; i < n; i++) { \ + uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, (int64_t)p[i]); \ + gids[i] = slot; \ + if (probe) { agg_probe_note(c, slot, begin + i); continue; } \ + if (cnt32) { __atomic_fetch_add(&cnt32[slot], 1, __ATOMIC_RELAXED); continue; } \ + uint64_t bit = UINT64_C(1) << (slot % 64); \ + _Atomic(uint64_t)* word = &c->occupied[slot / 64]; \ + if (!(atomic_load_explicit(word, memory_order_relaxed) & bit)) \ + atomic_fetch_or_explicit(word, bit, memory_order_relaxed); \ + } \ + } while (0) + switch (c->key->type) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: SHARED_GIDS(int64_t); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: SHARED_GIDS(int32_t); break; + case RAY_I16: SHARED_GIDS(int16_t); break; + case RAY_U8: case RAY_BOOL: SHARED_GIDS(uint8_t); break; + case RAY_SYM: + switch (v->key_attrs[0] & RAY_SYM_W_MASK) { + case RAY_SYM_W8: SHARED_GIDS(uint8_t); break; + case RAY_SYM_W16: SHARED_GIDS(uint16_t); break; + case RAY_SYM_W32: SHARED_GIDS(uint32_t); break; + default: SHARED_GIDS(int64_t); break; + } + break; + } + #undef SHARED_GIDS + if (cnt32 || probe) return; + for (uint32_t a = 0; a < c->n_aggs; a++) { + const void* vals = v->val_data[a] /* NULL: COUNT reads no input */ + ? (const char*)v->val_data[a] + (size_t)(begin - base) * d->val_esz[a] : NULL; + ray_valid_t valid = {vals, d->val_types[a], d->val_hasnull[a]}; + vo->vts[a]->update_shared(c->states + vo->off[a], vo->block, gids, vals, &valid, n); } } -static void agg_dense_shared_occupied(void* raw, uint32_t wid, int64_t start, int64_t end) { +/* A run of selected rows rows[ib, ie) read through view v: their slots, then + * the counters or the shared kernels. */ +typedef struct { + agg_dense_shared_ctx_t* c; + const int64_t* rows; + uint32_t* gid; + agg_sel_scratch_t* sc; + int oom; +} agg_dense_shared_sel_t; +static void agg_dense_shared_sel_run(void* raw, const agg_view_t* v, uint32_t wid, int64_t ib, int64_t ie) { (void)wid; + agg_dense_shared_sel_t* t = raw; + agg_dense_shared_ctx_t* c = t->c; + for (int64_t i = ib; i < ie; i++) { + int64_t r = t->rows[i]; + int64_t k = agg_read_key_i64_raw(c->key->type, v->key_attrs[0], v->key_data[0], r - v->base); + uint32_t slot = (uint32_t)agg_dense_component_raw(c->plan, 0, k); + t->gid[i - ib] = slot; + if (c->probe) { agg_probe_note(c, slot, r); continue; } + if (c->cnt32) { __atomic_fetch_add(&c->cnt32[slot], 1, __ATOMIC_RELAXED); continue; } + uint64_t bit = UINT64_C(1) << (slot % 64); + _Atomic(uint64_t)* word = &c->occupied[slot / 64]; + if (!(atomic_load_explicit(word, memory_order_relaxed) & bit)) + atomic_fetch_or_explicit(word, bit, memory_order_relaxed); + } + if (c->cnt32 || c->probe) return; + if (agg_sel_accum_chunk(c->vd, v, t->sc, c->states, t->gid, t->rows + ib, ie - ib, true) != 0) t->oom = 1; +} + +/* Selected-row space [start, end): chunks of selected rows are decoded to + * their original rows and read through the key sources (R-SPARSE for staged + * ones). */ +static void agg_dense_shared_sel_rows(agg_dense_shared_ctx_t* c, uint32_t wid, int64_t start, int64_t end) { + const agg_desc_t* d = c->desc; + int64_t rows[AGG_SEL_CHUNK]; + uint32_t gid[AGG_SEL_CHUNK]; + agg_sel_scratch_t sc; + if (!agg_sel_scratch_init(&sc, c->n_aggs)) { ray_scan_fail_note(d->rr.fail, start, ray_error("oom", NULL)); return; } + agg_curs_t cs; cs.cur = NULL; + if (d->staged && !agg_curs_init(&cs, &d->rr)) { + ray_scan_fail_note(d->rr.fail, start, ray_error("oom", NULL)); + agg_sel_scratch_free(&sc); + return; + } + agg_sel_cursor_t cur; + agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, start, end); + agg_dense_shared_sel_t t = { c, rows, gid, &sc, 0 }; + int64_t cn; + while (!t.oom && !agg_cancelled() && (cn = agg_sel_cursor_next(&cur, rows)) > 0) { + if (!d->staged) { agg_dense_shared_sel_run(&t, &d->whole, wid, 0, cn); continue; } + ray_t* err = agg_idx_walk(&d->rr, &cs, rows, 0, cn, &t, agg_dense_shared_sel_run, wid); + if (err) { ray_scan_fail_note(d->rr.fail, start, err); break; } + } + if (t.oom) ray_scan_fail_note(d->rr.fail, start, ray_error("oom", NULL)); + agg_curs_free(&cs, &d->rr); + agg_sel_scratch_free(&sc); +} + +static void agg_dense_shared_rows(void* raw, uint32_t wid, int64_t start, int64_t end) { agg_dense_shared_ctx_t* c = raw; - for (int64_t s = start; s < end; s++) - c->first[s] = atomic_load_explicit(&c->occupied[s / 64], memory_order_relaxed) - & (UINT64_C(1) << (s % 64)) ? 0 : INT64_MAX; + if (c->sel) { agg_dense_shared_sel_rows(c, wid, start, end); return; } + const agg_desc_t* d = c->desc; + agg_curs_t cs; cs.cur = NULL; + if (d->staged && !agg_curs_init(&cs, &d->rr)) { ray_scan_fail_note(d->rr.fail, start, ray_error("oom", NULL)); return; } + for (int64_t begin = start; begin < end && !agg_cancelled(); begin += 8192) { + int64_t limit = end - begin < 8192 ? end : begin + 8192; + if (!d->staged) agg_dense_shared_block(c, &d->whole, wid, begin, limit); + else if (!agg_walk_cs(&d->rr, &cs, c, agg_dense_shared_block, wid, begin, limit, start)) break; + } + agg_curs_free(&cs, &d->rr); +} + +typedef struct { int64_t first, slot; bool strict; } agg_tie_t; +static int agg_tie_cmp(const void* a, const void* b) { + int64_t x = ((const agg_tie_t*)a)->first, y = ((const agg_tie_t*)b)->first; + return x < y ? -1 : x > y; +} +static int agg_dbl_cmp(const void* a, const void* b) { + double x = *(const double*)a, y = *(const double*)b; + return x < y ? -1 : x > y; +} + +/* The kept groups of a top-N cut (the threshold's ties included) as the radix + * route answers it: of the groups tied at the threshold only the ones with the + * smallest first rows stay, so N groups remain, and the kept groups come in + * first-row order, which the sort downstream keeps for equal values. The + * first rows come from one more pass over the keys (a probe pass) that notes + * them for the kept slots only. Kept values that are all different need + * neither, and the slot order stands. False with *err set on failure. */ +static bool agg_dense_cut_ties(ray_pool_t* pool, agg_dense_shared_ctx_t* c, agg_desc_t* d, const agg_lean_src_t* src, + const ray_group_emit_filter_t* ef, bool have_thr, double thr, int64_t rows, + int64_t* slots, int64_t* n_io, ray_t** err) { + int64_t n = *n_io; + *err = NULL; + if (n <= 1) return true; + double* vals = ray_alloc_raw((size_t)n * sizeof(double)); + double* sorted = ray_alloc_raw((size_t)n * sizeof(double)); + uint64_t* bm = ray_calloc_raw(((size_t)c->slots + 63) / 64 * sizeof(uint64_t)); + int64_t* first = ray_alloc_raw((size_t)n * sizeof(int64_t)); + agg_tie_t* ties = ray_alloc_raw((size_t)n * sizeof(agg_tie_t)); + bool ok = false; + if (!vals || !sorted || !bm || !first || !ties) { *err = ray_error("oom", NULL); goto done; } + ok = true; + if (!agg_lean_vals(src, slots, n, vals)) goto done; + memcpy(sorted, vals, (size_t)n * sizeof(double)); + qsort(sorted, (size_t)n, sizeof(double), agg_dbl_cmp); + bool distinct = true; + for (int64_t i = 1; i < n && distinct; i++) distinct = sorted[i] != sorted[i - 1]; + if (distinct) goto done; + for (int64_t i = 0; i < n; i++) { + bm[slots[i] >> 6] |= UINT64_C(1) << (slots[i] & 63); + first[i] = INT64_MAX; + } + c->probe = bm; c->pslots = slots; c->pn = n; c->pfirst = first; + ray_pool_dispatch(pool, agg_dense_shared_rows, c, rows); + c->probe = NULL; + if (d->staged && (*err = ray_scan_fail_finish(&d->fail, pool)) != NULL) { ok = false; goto done; } + if (agg_cancelled()) { *err = ray_error("cancel", NULL); ok = false; goto done; } + int64_t nstrict = 0; + for (int64_t i = 0; i < n; i++) { + ties[i].first = first[i]; ties[i].slot = slots[i]; + ties[i].strict = !have_thr || (ef->desc ? vals[i] > thr : vals[i] < thr); + nstrict += ties[i].strict; + } + int64_t room = have_thr ? ef->top_count_take - nstrict : n; + qsort(ties, (size_t)n, sizeof(agg_tie_t), agg_tie_cmp); + int64_t w = 0, tied = 0; + for (int64_t i = 0; i < n; i++) { + if (!ties[i].strict && tied++ >= room) continue; + slots[w++] = ties[i].slot; + } + *n_io = w; +done: + ray_free_raw(vals); ray_free_raw(sorted); ray_free_raw(bm); ray_free_raw(first); ray_free_raw(ties); + return ok; } static ray_t* agg_dense_shared(ray_t** key_cols, int64_t* key_syms, ray_op_ext_t* ext, - ray_pool_t* pool, const dense_plan_t* plan, int64_t rows, - const agg_vo_t* vo, const agg_desc_t* d, const ray_group_emit_filter_t* ef) { + ray_pool_t* pool, const dense_plan_t* plan, int64_t rows, ray_t* sel, const int64_t* sel_prefix, + const agg_vo_t* vo, agg_desc_t* d, const ray_group_emit_filter_t* ef) { + ray_t* ferr = NULL; /* R-FAIL: a range error of a staged source */ int64_t slots = plan->total_slots; - agg_dense_shared_ctx_t c = {.key = key_cols[0], .plan = plan, .layout = vo, .desc = d, .n_aggs = ext->n_aggs}; - c.states = ray_alloc_raw((size_t)slots * vo->block); - c.first = ray_alloc_raw((size_t)slots * sizeof(int64_t)); + agg_valdesc_t vd = { .n_aggs = ext->n_aggs, .vts = vo->vts, .off = vo->off, .block = vo->block, + .val_data = d->val_data, .val_types = d->val_types, .val_hasnull = d->val_hasnull, .val_esz = d->val_esz, + .val2_data = d->val2_data, .val2_types = d->val2_types, .val2_hasnull = d->val2_hasnull, .val2_esz = d->val2_esz }; + agg_dense_shared_ctx_t c = {.key = key_cols[0], .plan = plan, .layout = vo, .desc = d, .n_aggs = ext->n_aggs, .slots = slots, + .sel = sel, .sel_prefix = sel_prefix, .vd = &vd}; /* rows: the selected rows with a selection */ + bool u32c = plan->wide && agg_count32_slab(vo->vts, ext->n_aggs, rows); + c.states = ray_alloc_raw((size_t)slots * (u32c ? sizeof(uint32_t) : vo->block)); + if (u32c) c.cnt32 = (uint32_t*)c.states; c.occupied = ray_alloc_raw(((size_t)slots + 63) / 64 * sizeof(*c.occupied)); - if (!c.states || !c.first || !c.occupied) goto failed; + if (!c.states || !c.occupied) goto failed; for (int64_t w = 0; w < (slots + 63) / 64; w++) atomic_init(&c.occupied[w], 0); - ray_pool_dispatch(pool, agg_dense_shared_init, &c, slots); + ray_pool_dispatch(pool, u32c ? agg_dense_shared_zero : agg_dense_shared_init, &c, slots); ray_profile_tick("dense shared: initialized states"); + agg_desc_advise(d, rows); ray_pool_dispatch(pool, agg_dense_shared_rows, &c, rows); + if (d->staged && (ferr = ray_scan_fail_finish(&d->fail, pool)) != NULL) goto failed; if (agg_cancelled()) goto failed; ray_profile_tick("dense shared: reduced rows"); - ray_pool_dispatch(pool, agg_dense_shared_occupied, &c, slots); - if (agg_cancelled()) goto failed; - ray_profile_tick("dense shared: collected occupancy"); - ray_free_raw(c.occupied); + if (u32c) ray_pool_dispatch(pool, agg_dense_shared_cnt_occupied, &c, (slots + 63) / 64); route_stats.dense_strategy = AGG_DENSE_SHARED; route_stats.dense_tasks = ray_pool_total_workers(pool); route_stats.dense_local_slots = slots; - return agg_dense_finish(key_cols, key_syms, ext, pool, vo, d, slots, c.states, c.first, plan, slots, 0, ef, 0); + route_stats.dense_count32 = u32c; + int64_t* pre = NULL; + int64_t pre_n = -1; + if (ef && ef->top_count_take > 0) { + agg_lean_src_t src = { .vt = vo->vts[ef->agg_index], .states = c.states, .block = vo->block, + .off = vo->off[ef->agg_index], .param = ext->agg_k ? ext->agg_k[ef->agg_index] : 0, + .cnt32 = u32c ? c.cnt32 : NULL }; + bool have_thr; + double thr; + int64_t k = agg_dense_lean_select(pool, &src, (const uint64_t*)c.occupied, slots, ef, &pre, &have_thr, &thr); + if (k >= 0) { + if (!agg_dense_cut_ties(pool, &c, d, &src, ef, have_thr, thr, rows, pre, &k, &ferr)) { + ray_free_raw(pre); + goto failed; + } + pre_n = k; + } else if (u32c) { + goto failed; + } + } + return agg_dense_finish(key_cols, key_syms, ext, pool, vo, d, slots, c.states, NULL, (const uint64_t*)c.occupied, plan, slots, 0, ef, 0, plan, u32c, pre, pre_n); failed: - ray_free_raw(c.states); ray_free_raw(c.first); ray_free_raw(c.occupied); - return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); + ray_free_raw(c.states); ray_free_raw(c.occupied); + return ferr ? ferr : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); +} + +/* The dense phase A may count on the key's runs (agg_dense_runs_*): one + * staged generation-2 integer or SYM key, a raw-range plan, every + * aggregate COUNT (D6: the count adds a run's rows; any other aggregate + * needs its rows' values). */ +static bool agg_dense_runs_ok(const agg_rr_t* rr, const dense_plan_t* dp, const agg_vtable_t** vts, + uint32_t n_keys, uint32_t n_aggs) { + if (n_keys != 1 || !rr->staged || !rr->srcs[0] || !ray_col_src_encoded(rr->srcs[0]) || dp->compacted) return false; + switch (rr->key_types[0]) { + case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_SYM: break; + default: return false; + } + const agg_vtable_t* cnt = agg_resolve(OP_COUNT, RAY_I64); + for (uint32_t a = 0; a < n_aggs; a++) + if (vts[a] != cnt || vts[a]->state_size != sizeof(int64_t)) return false; + return true; } static ray_t* exec_group_v2_parallel_dense( @@ -2951,7 +5032,11 @@ static ray_t* exec_group_v2_parallel_dense( const agg_vtable_t** vts = vo.vts; size_t* off = vo.off; size_t block = vo.block; agg_desc_t d; - if (!agg_desc_init(&d, g, ext, tbl, key_cols)) { agg_vo_free(&vo); return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } + ray_t* derr = NULL; + if (!agg_desc_init(&d, g, ext, tbl, key_cols, &derr)) { + agg_vo_free(&vo); + return derr ? derr : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); + } const void** key_data = d.key_data; const void** val_data = d.val_data; const int8_t* val_types = d.val_types; const bool* val_hasnull = d.val_hasnull; const uint8_t* val_esz = d.val_esz; @@ -2959,7 +5044,7 @@ static ray_t* exec_group_v2_parallel_dense( const bool* val2_hasnull = d.val2_hasnull; const uint8_t* val2_esz = d.val2_esz; if (strategy == AGG_DENSE_SHARED) { - ray_t* result = agg_dense_shared(key_cols, key_syms, ext, pool, dp, nrows, &vo, &d, efp); + ray_t* result = agg_dense_shared(key_cols, key_syms, ext, pool, dp, sel ? n_sel : nrows, sel, sel_prefix, &vo, &d, efp); agg_vo_free(&vo); agg_desc_free(&d); return result; } @@ -2983,7 +5068,12 @@ static ray_t* exec_group_v2_parallel_dense( if (!locals) { agg_vo_free(&vo); agg_desc_free(&d); return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } memset(locals, 0, metadata_bytes); char* cursor = (char*)(((uintptr_t)locals + metadata_bytes + 63) & ~(uintptr_t)63); - for (uint32_t w = 0; w < nw; w++) { + /* The eager-initialization samples read a staged key through cursors + * (R-SPARSE: strided single rows, ascending). */ + agg_curs_t scs; scs.cur = NULL; + ray_t* serr = NULL; + if (d.staged && !sel && n_keys == 1 && !agg_curs_init(&scs, &d.rr)) serr = ray_error("oom", NULL); + for (uint32_t w = 0; w < nw && !serr; w++) { locals[w].slots = total_slots; /* Eager initialization amortizes when a task processes at least * two rows per possible slot. It preserves a tight row loop for @@ -2996,9 +5086,12 @@ static ray_t* exec_group_v2_parallel_dense( int64_t begin = nrows / nw * w; int64_t end = w + 1 == nw ? nrows : nrows / nw * (w + 1); int64_t low = total_slots, high = 0; - for (int64_t sample = 0; sample < 64; sample++) { + for (int64_t sample = 0; sample < 64 && !serr; sample++) { int64_t row = begin + (end - begin - 1) * sample / 63; - int64_t slot = agg_dense_component(dp, 0, agg_read_key_i64(key_cols[0], key_data[0], row)); + int64_t key = d.key_srcs[0] ? agg_key_at(&d.rr, &scs, 0, row, &serr) + : agg_read_key_i64(key_cols[0], key_data[0], row); + if (serr) break; /* key is 0: never a slot (a remap would read past it) */ + int64_t slot = agg_dense_component(dp, 0, key); if (slot < low) low = slot; if (slot > high) high = slot; } @@ -3009,6 +5102,8 @@ static ray_t* exec_group_v2_parallel_dense( locals[w].states = cursor; cursor += (bytes + 63) & ~(size_t)63; } + agg_curs_free(&scs, &d.rr); + if (serr) { ray_free_raw(locals); agg_vo_free(&vo); agg_desc_free(&d); return serr; } agg_dense_merge_ctx_t merge_ctx = { .locals = locals, .slots = total_slots, .vts = vts, .off = off, .block = block, .n_aggs = n_aggs, .nw = nw }; ray_profile_tick("dense: allocated slabs"); @@ -3024,19 +5119,23 @@ static ray_t* exec_group_v2_parallel_dense( .vd = { .n_aggs = n_aggs, .vts = vts, .off = off, .block = block, .val_data = val_data, .val_types = val_types, .val_hasnull = val_hasnull, .val_esz = val_esz, .val2_data = val2_data, .val2_types = val2_types, .val2_hasnull = val2_hasnull, .val2_esz = val2_esz }, + .rr = &d.rr, .whole = &d.whole, + .runs = agg_dense_runs_ok(&d.rr, dp, vts, n_keys, n_aggs), }; /* Sel mode dispatches over the SELECTED-row space [0,n_sel); each worker * range maps to a segment span via sel_prefix. Non-sel dispatches over rows. */ - ray_pool_dispatch_n(pool, agg_dense_task_fn, &ctx, nw); + agg_desc_advise(&d, nrows); + ray_pool_dispatch_n(pool, ctx.runs ? agg_dense_task_runs_fn : agg_dense_task_fn, &ctx, nw); ray_profile_tick("dense: accumulated rows"); + ray_t* ferr = d.staged ? ray_scan_fail_finish(&d.fail, pool) : NULL; for (uint32_t w = 0; w < nw; w++) - if (locals[w].oom || agg_cancelled()) { + if (ferr || locals[w].oom || agg_cancelled()) { for (uint32_t i = 0; i < nw; i++) agg_dense_local_destroy_states(&locals[i], vts, off, block, n_aggs); ray_free_raw(locals); agg_vo_free(&vo); agg_desc_free(&d); - return ray_error(agg_cancelled() ? "cancel" : "oom", NULL); + return ferr ? ferr : ray_error(agg_cancelled() ? "cancel" : "oom", NULL); } /* dispatch_n has joined every task. If cancellation skipped a task, the @@ -3073,7 +5172,7 @@ static ray_t* exec_group_v2_parallel_dense( ray_free_raw(locals); ray_t* result = agg_dense_finish(key_cols, key_syms, ext, pool, &vo, &d, - total_slots, gstates, gfirst, NULL, 0, 0, efp, group_limit); + total_slots, gstates, gfirst, NULL, NULL, 0, 0, efp, group_limit, dp, false, NULL, -1); agg_vo_free(&vo); agg_desc_free(&d); return result; } @@ -3099,37 +5198,67 @@ static ray_t* exec_group_v2_parallel_dense( /* Per-worker (and global merge) GROWABLE small-hash group table: open-addressing * hash on the tuple-hash → local gid; AoS per-group state blocks of `block` * bytes. Sized to cardinality (not N) and grown by rehash on load-factor. */ +/* A key column of `ng` rows from key words at w[g * stride]: the type, SYM + * width and domain of `like` (the key column or its stand-in). A word + * equal to the type's null sentinel is a null row and sets HAS_NULLS (so + * does a nullable `like`, as ray_group_gather would); BOOL and U8 are never + * null. Caller owns the column. */ +static ray_t* agg_keycol_from_words(ray_t* like, const int64_t* w, size_t stride, int64_t ng) { + ray_t* out = col_vec_new(like, ng); + if (!out || RAY_IS_ERR(out)) return out; + if (out->type == RAY_SYM) ray_sym_vec_adopt_domain(out, sym_domain_rep(like)); + out->len = ng; + bool nulls = ray_vec_may_have_nulls(like); + int64_t null = like->type == RAY_SYM ? 0 : agg_key_null(like->type); + bool nullable_type = like->type != RAY_BOOL && like->type != RAY_U8; + void* dst = ray_data(out); + for (int64_t g = 0; g < ng; g++) { + int64_t v = w[(size_t)g * stride]; + if (nullable_type && v == null) nulls = true; + write_col_i64(dst, g, v, out->type, out->attrs); + } + if (nulls) out->attrs |= RAY_ATTR_HAS_NULLS; + return out; +} + typedef struct { int32_t* ht; /* [htcap] slot -> local gid, -1 empty */ int64_t htcap; uint64_t htmask; int64_t* first_row; /* [cap] representative (MIN) row idx per local group */ char* states; /* [cap*block] AoS group state */ + int64_t* gkey; /* staged keys: [cap * n_keys] key words per group; else NULL */ + uint32_t n_keys; /* words per gkey entry (0: first-row compares) */ int64_t ng, cap; size_t block; int oom; } agg_sh_t; -static int agg_sh_init(agg_sh_t* sh, int64_t cap, size_t block) { +/* n_words > 0: the table keys its groups by stored key words (staged keys, + * read by range, have no row to compare at later). */ +static int agg_sh_init(agg_sh_t* sh, int64_t cap, size_t block, uint32_t n_words) { if (cap < 1) cap = 1; int64_t htcap = 2; while (htcap < cap * 2) htcap <<= 1; /* <0.5 load at full cap */ sh->ng = 0; sh->cap = cap; sh->block = block; sh->oom = 0; sh->htcap = htcap; sh->htmask = (uint64_t)htcap - 1; + sh->n_keys = n_words; sh->ht = ray_alloc_raw((size_t)htcap * sizeof(int32_t)); sh->first_row = ray_alloc_raw((size_t)cap * sizeof(int64_t)); sh->states = ray_alloc_raw((size_t)cap * block); - if (!sh->ht || !sh->first_row || !sh->states) { sh->oom = 1; return -1; } + sh->gkey = n_words ? ray_alloc_raw((size_t)cap * n_words * sizeof(int64_t)) : NULL; + if (!sh->ht || !sh->first_row || !sh->states || (n_words && !sh->gkey)) { sh->oom = 1; return -1; } for (int64_t i = 0; i < htcap; i++) sh->ht[i] = -1; return 0; } static void agg_sh_destroy(agg_sh_t* sh) { - ray_free_raw(sh->ht); ray_free_raw(sh->first_row); ray_free_raw(sh->states); - sh->ht = NULL; sh->first_row = NULL; sh->states = NULL; + ray_free_raw(sh->ht); ray_free_raw(sh->first_row); ray_free_raw(sh->states); ray_free_raw(sh->gkey); + sh->ht = NULL; sh->first_row = NULL; sh->states = NULL; sh->gkey = NULL; } -/* Grow capacity (states + first_row) when ng would exceed cap. Doubles cap. */ +/* Grow capacity (states + first_row, and the key words) when ng would exceed + * cap. Doubles cap. */ static int agg_sh_grow_cap(agg_sh_t* sh) { int64_t nc = sh->cap * 2; int64_t* nfr = ray_realloc_raw(sh->first_row, (size_t)nc * sizeof(int64_t)); @@ -3138,14 +5267,19 @@ static int agg_sh_grow_cap(agg_sh_t* sh) { char* nst = ray_realloc_raw(sh->states, (size_t)nc * sh->block); if (!nst) { sh->oom = 1; return -1; } sh->states = nst; + if (sh->n_keys) { + int64_t* ngk = ray_realloc_raw(sh->gkey, (size_t)nc * sh->n_keys * sizeof(int64_t)); + if (!ngk) { sh->oom = 1; return -1; } + sh->gkey = ngk; + } sh->cap = nc; return 0; } /* Rehash the hash table to a larger htcap (keeps load factor low). The gid set * is unchanged; we recompute each group's slot from its representative row's - * tuple hash. n_keys is uint32_t (unbounded), same contract as - * agg_tuple_hash. */ + * tuple hash, or from its stored key words (never reading a column). + * n_keys is uint32_t (unbounded), same contract as agg_tuple_hash. */ static int agg_sh_grow_ht(agg_sh_t* sh, ray_t** key_cols, const void** key_data, uint32_t n_keys) { int64_t nc = sh->htcap * 2; @@ -3154,7 +5288,8 @@ static int agg_sh_grow_ht(agg_sh_t* sh, ray_t** key_cols, const void** key_data, uint64_t nmask = (uint64_t)nc - 1; for (int64_t i = 0; i < nc; i++) nht[i] = -1; for (int64_t g = 0; g < sh->ng; g++) { - uint64_t h = agg_tuple_hash(key_cols, key_data, n_keys, sh->first_row[g]); + uint64_t h = sh->n_keys ? agg_words_hash(&sh->gkey[(size_t)g * sh->n_keys], sh->n_keys) + : agg_tuple_hash(key_cols, key_data, n_keys, sh->first_row[g]); uint64_t slot = h & nmask; while (nht[slot] >= 0) slot = (slot + 1) & nmask; nht[slot] = (int32_t)g; @@ -3187,6 +5322,8 @@ typedef struct { ray_t* sel; const int64_t* sel_prefix; agg_valdesc_t vd; + const agg_rr_t* rr; /* sources; staged ones are read by range */ + const agg_view_t* whole; } agg_sh_ctx_t; /* Probe-or-insert key tuple at row r in sh; returns gid (>=0) or -1 on oom. @@ -3222,13 +5359,109 @@ static inline int32_t agg_sh_find_or_insert( } } +/* Probe-or-insert by key words w[0, sh->n_keys) (a staged table; `r` the + * candidate's first row, kept as the MIN). Keys reaching the small hash + * are integer, temporal, BOOL, U8 or SYM, so a widened word identifies its + * value exactly. Returns gid (>=0) or -1 on oom. */ +static int32_t agg_sh_find_or_insert_words( + agg_sh_t* sh, const int64_t* w, const agg_vtable_t** vts, const size_t* off, + uint32_t n_aggs, int64_t r) { + uint32_t nk = sh->n_keys; + uint64_t h = agg_words_hash(w, nk); + uint64_t slot = h & sh->htmask; + for (;;) { + int32_t gp = sh->ht[slot]; + if (gp < 0) { /* new group */ + if (sh->ng == sh->cap && agg_sh_grow_cap(sh) != 0) return -1; + if ((sh->ng + 1) * 2 > sh->htcap) { + if (agg_sh_grow_ht(sh, NULL, NULL, 0) != 0) return -1; + slot = h & sh->htmask; + while (sh->ht[slot] >= 0) slot = (slot + 1) & sh->htmask; + } + int32_t g = (int32_t)sh->ng; + sh->ht[slot] = g; + sh->first_row[g] = r; + memcpy(&sh->gkey[(size_t)g * nk], w, (size_t)nk * sizeof(int64_t)); + for (uint32_t a = 0; a < n_aggs; a++) + vts[a]->init(sh->states + (size_t)g * sh->block + off[a]); + sh->ng++; + return g; + } + if (memcmp(&sh->gkey[(size_t)gp * nk], w, (size_t)nk * sizeof(int64_t)) == 0) { + if (r < sh->first_row[gp]) sh->first_row[gp] = r; /* MIN representative */ + return gp; + } + slot = (slot + 1) & sh->htmask; + } +} + +/* Group id of row r read through view v: by first-row compares over whole + * columns, by key words over pieces. */ +static inline int32_t agg_sh_gid(agg_sh_ctx_t* c, agg_sh_t* sh, const agg_view_t* v, int64_t r) { + if (!sh->n_keys) + return agg_sh_find_or_insert(sh, c->key_cols, c->key_data, c->n_keys, + c->vts, c->off, c->n_aggs, r); + uint32_t nk = c->n_keys; + int64_t w[nk]; + for (uint32_t k = 0; k < nk; k++) w[k] = agg_vkey(v, c->rr->key_types, k, r); + return agg_sh_find_or_insert_words(sh, w, c->vts, c->off, c->n_aggs, r); +} + +/* Phase A body: rows [start, end) (at most AGG_SH_CHUNK) through view v. */ +static void agg_sh_rows(void* vctx, const agg_view_t* v, uint32_t wid, int64_t cs, int64_t ce) { + agg_sh_ctx_t* c = (agg_sh_ctx_t*)vctx; + agg_sh_t* sh = &c->locals[wid]; + if (sh->oom) return; + uint32_t gid[AGG_SH_CHUNK]; + int64_t n = ce - cs; + const int64_t base = v->base; + for (int64_t r = cs; r < ce; r++) { + int32_t g = agg_sh_gid(c, sh, v, r); + if (g < 0) { sh->oom = 1; return; } + gid[r - cs] = (uint32_t)g; + } + for (uint32_t a = 0; a < c->n_aggs; a++) { + if (c->vts[a]->update_batch2) { /* binary agg (pearson) */ + const void* vx = (const char*)v->val_data[a] + (size_t)(cs - base) * c->val_esz[a]; + const void* vy = (const char*)v->val2_data[a] + (size_t)(cs - base) * c->val2_esz[a]; + ray_valid_t valid_x = { vx, c->val_types[a], c->val_hasnull[a] }; + ray_valid_t valid_y = { vy, c->val2_types[a], c->val2_hasnull[a] }; + c->vts[a]->update_batch2(sh->states + c->off[a], c->block, gid, + vx, vy, &valid_x, &valid_y, n, NULL); + } else { + const void* vals = (v->val_data[a]) + ? (const void*)((const char*)v->val_data[a] + (size_t)(cs - base) * c->val_esz[a]) + : NULL; + ray_valid_t valid = { vals, c->val_types[a], + v->val_data[a] ? c->val_hasnull[a] : false }; + c->vts[a]->update_batch(sh->states + c->off[a], c->block, + gid, vals, &valid, n, NULL); + } + } +} + +/* Phase A, sel mode: one run rows[ib, ie) of a selected chunk. */ +typedef struct { agg_sh_ctx_t* c; agg_sh_t* sh; const int64_t* rows; uint32_t* gid; agg_sel_scratch_t* sc; } agg_sh_sel_run_t; +static void agg_sh_sel_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t ib, int64_t ie) { + (void)wid; + agg_sh_sel_run_t* t = raw; + if (t->sh->oom) return; + for (int64_t i = ib; i < ie; i++) { + int32_t g = agg_sh_gid(t->c, t->sh, v, t->rows[i]); + if (g < 0) { t->sh->oom = 1; return; } + t->gid[i - ib] = (uint32_t)g; + } + if (agg_sel_accum_chunk(&t->c->vd, v, t->sc, t->sh->states, t->gid, t->rows + ib, ie - ib, false) != 0) + t->sh->oom = 1; +} + /* Phase A: per-worker small-hash group + accumulate over chunk [start,end), * processed in fixed-size sub-chunks so the gid buffer is O(CHUNK), not O(N). */ static void agg_sh_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { agg_sh_ctx_t* c = (agg_sh_ctx_t*)vctx; agg_sh_t* sh = &c->locals[wid]; if (sh->oom) return; - uint32_t gid[AGG_SH_CHUNK]; + const agg_rr_t* rr = c->rr; /* ── Sel mode: chunk-iterate the SELECTED rows in [start,end) (selected-row * space), decoding ORIGINAL rows, probing the per-worker hash, gathering @@ -3238,56 +5471,40 @@ static void agg_sh_phaseA_fn(void* vctx, uint32_t wid, int64_t start, int64_t en uint32_t sgid[AGG_SEL_CHUNK]; agg_sel_scratch_t sc; if (!agg_sel_scratch_init(&sc, c->n_aggs)) { sh->oom = 1; return; } + agg_curs_t cs; cs.cur = NULL; + if (rr->staged) { + if (ray_scan_fail_skip(rr->fail, start)) { agg_sel_scratch_free(&sc); return; } + if (!agg_curs_init(&cs, rr)) { sh->oom = 1; agg_sel_scratch_free(&sc); return; } + } agg_sel_cursor_t cur; agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, start, end); + agg_sh_sel_run_t t = { c, sh, rows, sgid, &sc }; int64_t cn; - while ((cn = agg_sel_cursor_next(&cur, rows)) > 0) { - for (int64_t i = 0; i < cn; i++) { - int32_t g = agg_sh_find_or_insert(sh, c->key_cols, c->key_data, c->n_keys, - c->vts, c->off, c->n_aggs, rows[i]); - if (g < 0) { sh->oom = 1; agg_sel_scratch_free(&sc); return; } - sgid[i] = (uint32_t)g; - } - if (agg_sel_accum_chunk(&c->vd, &sc, sh->states, sgid, rows, cn) != 0) { - sh->oom = 1; agg_sel_scratch_free(&sc); return; - } + while (!sh->oom && (cn = agg_sel_cursor_next(&cur, rows)) > 0) { + if (!rr->staged) { agg_sh_sel_rows(&t, c->whole, wid, 0, cn); continue; } + ray_t* err = agg_idx_walk(rr, &cs, rows, 0, cn, &t, agg_sh_sel_rows, wid); + if (err) { ray_scan_fail_note(rr->fail, start, err); break; } } + agg_curs_free(&cs, rr); agg_sel_scratch_free(&sc); return; } - for (int64_t cs = start; cs < end; cs += AGG_SH_CHUNK) { + agg_curs_t tc; tc.cur = NULL; + if (rr->staged && !agg_curs_init(&tc, rr)) { sh->oom = 1; return; } + for (int64_t cs = start; cs < end && !sh->oom; cs += AGG_SH_CHUNK) { int64_t ce = cs + AGG_SH_CHUNK; if (ce > end) ce = end; - int64_t n = ce - cs; - for (int64_t r = cs; r < ce; r++) { - int32_t g = agg_sh_find_or_insert(sh, c->key_cols, c->key_data, c->n_keys, - c->vts, c->off, c->n_aggs, r); - if (g < 0) { sh->oom = 1; return; } - gid[r - cs] = (uint32_t)g; - } - for (uint32_t a = 0; a < c->n_aggs; a++) { - if (c->vts[a]->update_batch2) { /* binary agg (pearson) */ - const void* vx = (const char*)c->val_data[a] + (size_t)cs * c->val_esz[a]; - const void* vy = (const char*)c->val2_data[a] + (size_t)cs * c->val2_esz[a]; - ray_valid_t valid_x = { vx, c->val_types[a], c->val_hasnull[a] }; - ray_valid_t valid_y = { vy, c->val2_types[a], c->val2_hasnull[a] }; - c->vts[a]->update_batch2(sh->states + c->off[a], c->block, gid, - vx, vy, &valid_x, &valid_y, n, NULL); - } else { - const void* vals = (c->val_data[a]) - ? (const void*)((const char*)c->val_data[a] + (size_t)cs * c->val_esz[a]) - : NULL; - ray_valid_t valid = { vals, c->val_types[a], - c->val_data[a] ? c->val_hasnull[a] : false }; - c->vts[a]->update_batch(sh->states + c->off[a], c->block, - gid, vals, &valid, n, NULL); - } - } + if (!rr->staged) agg_sh_rows(c, c->whole, wid, cs, ce); + else if (!agg_walk_cs(rr, &tc, c, agg_sh_rows, wid, cs, ce, start)) break; } + agg_curs_free(&tc, rr); } /* Parallel small-hash fallback. Precondition: int/SYM keys and streaming - * accumulators. Hashes start at one group and grow from observed cardinality. */ + * accumulators. Hashes start at one group and grow from observed cardinality. + * With staged keys every table keys its groups by key words: the merge + * inserts a local group by its words and the emit writes the keys from + * them, so no column is read at a stored row. */ static ray_t* exec_group_v2_parallel_smallhash( ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t nrows, ray_t** key_cols, int64_t* key_syms, @@ -3300,19 +5517,23 @@ static ray_t* exec_group_v2_parallel_smallhash( uint32_t nw = ray_pool_total_workers(pool); agg_desc_t d; - if (!agg_desc_init(&d, g, ext, tbl, key_cols)) return ray_error("oom", NULL); + ray_t* derr = NULL; + if (!agg_desc_init(&d, g, ext, tbl, key_cols, &derr)) return derr ? derr : ray_error("oom", NULL); const void** key_data = d.key_data; const void** val_data = d.val_data; const int8_t* val_types = d.val_types; const bool* val_hasnull = d.val_hasnull; const uint8_t* val_esz = d.val_esz; const void** val2_data = d.val2_data; const int8_t* val2_types = d.val2_types; const bool* val2_hasnull = d.val2_hasnull; const uint8_t* val2_esz = d.val2_esz; const int64_t* agg_syms = d.agg_syms; + bool words = false; + for (uint32_t k = 0; k < n_keys; k++) words |= d.key_srcs[k] != NULL; + uint32_t n_words = words ? n_keys : 0; agg_sh_t* locals = ray_calloc_raw((size_t)((size_t)nw) * (sizeof(agg_sh_t))); if (!locals) { agg_desc_free(&d); return ray_error("oom", NULL); } int alloc_oom = 0; for (uint32_t w = 0; w < nw; w++) - if (agg_sh_init(&locals[w], 1, block) != 0) { alloc_oom = 1; break; } + if (agg_sh_init(&locals[w], 1, block, n_words) != 0) { alloc_oom = 1; break; } if (alloc_oom) { for (uint32_t w = 0; w < nw; w++) agg_sh_destroy(&locals[w]); ray_free_raw(locals); @@ -3332,15 +5553,18 @@ static ray_t* exec_group_v2_parallel_smallhash( .vd = { .n_aggs = n_aggs, .vts = vts, .off = off, .block = block, .val_data = val_data, .val_types = val_types, .val_hasnull = val_hasnull, .val_esz = val_esz, .val2_data = val2_data, .val2_types = val2_types, .val2_hasnull = val2_hasnull, .val2_esz = val2_esz }, + .rr = &d.rr, .whole = &d.whole, }; + agg_desc_advise(&d, nrows); ray_pool_dispatch(pool, agg_sh_phaseA_fn, &ctx, sel ? n_sel : nrows); + ray_t* ferr = d.staged ? ray_scan_fail_finish(&d.fail, pool) : NULL; for (uint32_t w = 0; w < nw; w++) - if (locals[w].oom) { + if (ferr || locals[w].oom) { for (uint32_t i = 0; i < nw; i++) agg_sh_destroy(&locals[i]); ray_free_raw(locals); agg_desc_free(&d); - return ray_error("oom", NULL); + return ferr ? ferr : ray_error("oom", NULL); } /* ── Phase B: merge per-worker hashes into a global hash (serial). ── @@ -3348,7 +5572,7 @@ static ray_t* exec_group_v2_parallel_smallhash( int64_t gcap = 0; for (uint32_t w = 0; w < nw; w++) gcap += locals[w].ng; agg_sh_t gt = {0}; - if (agg_sh_init(>, gcap, block) != 0) { + if (agg_sh_init(>, gcap, block, n_words) != 0) { agg_sh_destroy(>); for (uint32_t i = 0; i < nw; i++) agg_sh_destroy(&locals[i]); ray_free_raw(locals); @@ -3359,8 +5583,9 @@ static ray_t* exec_group_v2_parallel_smallhash( agg_sh_t* loc = &locals[w]; for (int64_t lg = 0; lg < loc->ng; lg++) { int64_t fr = loc->first_row[lg]; - int32_t gg = agg_sh_find_or_insert(>, key_cols, key_data, n_keys, - vts, off, n_aggs, fr); + int32_t gg = n_words + ? agg_sh_find_or_insert_words(>, &loc->gkey[(size_t)lg * n_words], vts, off, n_aggs, fr) + : agg_sh_find_or_insert(>, key_cols, key_data, n_keys, vts, off, n_aggs, fr); if (gg < 0) { agg_sh_destroy(>); for (uint32_t i = 0; i < nw; i++) agg_sh_destroy(&locals[i]); @@ -3379,14 +5604,16 @@ static ray_t* exec_group_v2_parallel_smallhash( /* ── Phase C: emit key + agg columns in build order (unspecified order). ── * gt.first_row[g] is the representative row for the scattered key gather — - * trivially cheap for the few groups this path handles. */ + * trivially cheap for the few groups this path handles; a word-keyed + * table writes its keys from the words. */ ray_t* result = ray_table_new(n_keys + n_aggs); if (!result || RAY_IS_ERR(result)) { agg_sh_destroy(>); agg_desc_free(&d); return result ? result : ray_error("oom", NULL); } for (uint32_t k = 0; k < n_keys; k++) { - ray_t* kc = ray_group_gather(key_cols[k], gt.first_row, ng); + ray_t* kc = n_words ? agg_keycol_from_words(key_cols[k], gt.gkey + k, n_words, ng) + : ray_group_gather(key_cols[k], gt.first_row, ng); if (!kc || RAY_IS_ERR(kc)) { agg_sh_destroy(>); agg_desc_free(&d); ray_release(result); return kc ? kc : ray_error("oom", NULL); @@ -3482,6 +5709,12 @@ static uint32_t agg_radix_part_count(uint32_t nworkers, int64_t nrows) { * worker a chunk, so mid-size inputs count and scatter on the whole pool. */ #define AGG_RADIX_CHUNK_FLOOR_ROWS 4096 #define AGG_RADIX_CHUNKS_PER_WORKER 4 +/* The fused pass's chunks (generation 2) hold this many records per + * partition on average: smaller chunks keep the staged records in cache, + * fewer records per (chunk, partition) run make phase 2's reads scatter. */ +#define AGG_RADIX_RUN_ROWS 8 +/* Phase 2 of a fused context prefetches the run this many chunks ahead. */ +#define AGG_RADIX_RUN_AHEAD 4 /* Count-matrix budget: chunks are reduced (never below one per worker) so * n_chunks × n_parts × 4 bytes stays under this. */ #define AGG_RADIX_COUNT_BUDGET ((size_t)64 << 20) @@ -3590,6 +5823,49 @@ static void agg_key_emit_fn(void* vctx, uint32_t wid, int64_t start, int64_t end agg_key_emit_range((const agg_key_emit_ctx_t*)vctx, start, end); } +/* A record field of a compact fused context (agg_radix_ctx_t.cf): where + * the scatter takes it from. A staged source's field is copied into the + * task's staged row at soff; a plain source's (a column read in place) is + * read by the scatter at its row, as the two passes' scatter reads it. */ +enum { AGG_CF_STAGED, AGG_CF_KEY_I64, AGG_CF_KEY_I32, AGG_CF_KEY_I16, AGG_CF_KEY_U8, + AGG_CF_KEY_U16, AGG_CF_KEY_U32, AGG_CF_VAL }; +typedef struct { + const char* plain; /* plain fields: the column's row 0 */ + uint32_t off; /* the field's offset in the record */ + uint32_t soff; /* staged fields: the offset in the staged row */ + uint32_t agg; /* inputs: the aggregate whose input this is */ + uint8_t y; /* inputs: 1 for the y side of a binary aggregate */ + uint8_t w; /* bytes in the record (keys: 8) */ + uint8_t esz; /* plain fields: the column's element width */ + uint8_t kind; /* AGG_CF_* */ +} agg_radix_cf_t; + +/* Spill of the later waves of a reduced radix run (agg_radix_spill_*). One + * unlinked file in the heap's spill directory; each worker fills one buffer + * per wave and appends it whole when full — a block of n records followed + * by their n uint32 payload slots inside the wave — at a file offset taken + * from one shared tail, so every write is a large sequential pwrite. A wave + * is read back block by block (pread) straight into the payload slots, then + * reduced like any other wave. Written once, read once, unlinked at once. */ +typedef struct { int64_t off; uint32_t n; uint32_t wave; } agg_radix_blk_t; +typedef struct { char* buf; uint32_t n; } agg_radix_sbuf_t; +typedef struct agg_radix_spill_s { + int fd; + uint32_t n_waves; + uint32_t bcap; /* records per buffer */ + size_t rec; + const int64_t* wave_base; /* [n_waves] first record of each wave */ + agg_radix_sbuf_t* bufs; /* [nw * n_waves]; wave 0's unused */ + char* rbuf; /* [nw] read-back buffers */ + size_t rstride; /* bytes per buffer, 8-aligned */ + agg_radix_blk_t* blks; + int64_t blk_cap; + const int64_t* wave_blks; /* indices into blks of the wave read back */ + _Atomic(int64_t) n_blks; + _Atomic(int64_t) tail; + _Atomic(int) err; +} agg_radix_spill_t; + typedef struct { ray_t** key_cols; const void** key_data; @@ -3637,6 +5913,55 @@ typedef struct { * the decoded original row. */ ray_t* sel; const int64_t* sel_prefix; + const agg_rr_t* rr; /* sources; staged ones are read by range */ + const agg_view_t* whole; + /* Chunk-major payload (a staged context whose sources decode; chunks + * sized by exec_group_v2_parallel_radix): a task reads its chunk once, + * staging its records, and scatters them inside the chunk's own record + * range [chunk start, chunk end). cnt then holds each (chunk, + * partition)'s offset inside that range, runs the same transposed with + * the lengths, part_start the partition totals' prefix; pid is unused. + * A partition's records are its chunks' runs in chunk order: the global + * layout's sequence, so phase 2 groups the same records in the same + * order (agg_radix_group_fused_fn). */ + uint32_t fused_tasks; /* fused: tasks of consecutive chunks */ + const agg_rr_t* count_rr; /* two passes: the sources pass 1 reads (the + * keys; rr's other staged sources dropped) */ + uint32_t* runs; /* fused: [n_parts][n_chunks] (offset inside the + * chunk, length) of each partition's run, the + * count matrix transposed for phase 2 */ + /* Compact staging (fused, not sel mode): a task stages only the staged + * sources' fields (srec bytes a row: keys widened, inputs at their + * widths) and the scatter builds each record from them, the plain + * columns read in place and the position. cf[f] is field f in the + * record's order: the keys (cf[k] is key k's), then the inputs present, + * each aggregate's x then its y (n_cf in all). Not compact: a task + * stages whole records. */ + bool compact; + size_t srec; + uint32_t n_cf; + const agg_radix_cf_t* cf; + /* Waves (agg_radix_wave_plan): the payload holds the records of the + * partitions [wave_lo, wave_hi) only, partition p's slots starting at + * record part_start[p] - pay_base; phase 2 runs partition part_lo + task. + * One pass over every partition is wave 0 = [0, n_parts), base 0. */ + uint32_t wave_lo, wave_hi; + uint32_t part_lo; + int64_t pay_base; + /* Top-N candidates (agg_radix_part_compact): a finished partition with + * more than cmp_cap groups keeps only its cmp_cap best by the filter + * aggregate, ties to the smaller first row. 0 = keep every group. */ + int64_t cmp_cap; + const agg_vtable_t* cmp_vt; + size_t cmp_off; + int64_t cmp_param; + uint8_t cmp_desc; + _Atomic(int64_t) cmp_parts; /* partitions reduced (route stats) */ + /* Spilled waves (agg_radix_spill_scatter_fn): wave_of[p] is partition + * p's wave; wave 0 scatters into the payload, the later waves into + * per-(worker, wave) buffers written to the spill file. */ + const uint16_t* wave_of; + struct agg_radix_spill_s* spill; } agg_radix_ctx_t; /* Avalanche finalizer shared by the radix scatter (partition selection) and @@ -3652,12 +5977,74 @@ static inline uint64_t agg_radix_fmix64(uint64_t h) { return h; } +/* agg_read_key_i64 for the plain radix loops, the column's attrs read only + * by a SYM key (agg_read_key_i64 passes them to the raw reader up front, + * and the scatter loop then loads them for every key of every row). */ +RAY_INLINE int64_t agg_radix_key_at(const ray_t* col, const void* data, int64_t row) { + switch (col->type) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)data)[row]; + case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)data)[row]; + case RAY_I16: return ((const int16_t*)data)[row]; + case RAY_U8: case RAY_BOOL: return ((const uint8_t*)data)[row]; + case RAY_SYM: return (int64_t)ray_read_sym(data, row, RAY_SYM, col->attrs); + default: return 0; /* the gate admits only the above */ + } +} + +/* Pack the payload record of ORIGINAL row r at input position `pos` of a + * plain context (whole columns). */ +RAY_INLINE void agg_radix_put(const agg_radix_ctx_t* c, char* rec, int64_t r, int64_t pos) { + uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; + int64_t* kdst = (int64_t*)rec; + for (uint32_t k = 0; k < n_keys; k++) + kdst[k] = agg_radix_key_at(c->key_cols[k], c->key_data[k], r); + int64_t input_order = pos; + for (uint32_t a = 0; a < n_aggs; a++) { + if (c->val_data[a]) { + uint8_t ez = c->val_esz[a]; + memcpy(rec + c->val_off[a], (const char*)c->val_data[a] + (size_t)r * ez, ez); + } + if (c->val2_data[a]) { + uint8_t ez2 = c->val2_esz[a]; + memcpy(rec + c->val2_off[a], (const char*)c->val2_data[a] + (size_t)r * ez2, ez2); + } + } + if (c->needs_row) + memcpy(rec + c->row_off, &input_order, sizeof(input_order)); +} + +/* agg_radix_put of a staged context: row r read through view v (keys at + * r - base with the pieces' SYM widths, inputs from the pieces). */ +RAY_INLINE void agg_radix_put_view(const agg_radix_ctx_t* c, const agg_view_t* v, char* rec, + int64_t r, int64_t pos) { + uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; + const int64_t i = r - v->base; + int64_t* kdst = (int64_t*)rec; + for (uint32_t k = 0; k < n_keys; k++) + kdst[k] = agg_read_key_i64_raw(c->key_cols[k]->type, v->key_attrs[k], v->key_data[k], i); + int64_t input_order = pos; + for (uint32_t a = 0; a < n_aggs; a++) { + if (v->val_data[a]) { + uint8_t ez = c->val_esz[a]; + memcpy(rec + c->val_off[a], (const char*)v->val_data[a] + (size_t)i * ez, ez); + } + if (v->val2_data[a]) { + uint8_t ez2 = c->val2_esz[a]; + memcpy(rec + c->val2_off[a], (const char*)v->val2_data[a] + (size_t)i * ez2, ez2); + } + } + if (c->needs_row) + memcpy(rec + c->row_off, &input_order, sizeof(input_order)); +} + /* Visit one ORIGINAL row r at input position `pos`. * * Pass 1 (scatter == false) hashes the key tuple, records the partition in * pid[pos] and counts the row in its partition's cell of this chunk's count * row. Pass 2 (scatter == true) reads the partition back from pid[pos] and - * writes the packed record at the chunk's next slot of that partition. + * writes the packed record at the chunk's next slot of that partition; in a + * wave (`wave`) only a partition of [wave_lo, wave_hi) is written, at its + * slot less pay_base. * * Storing the partition id (2 bytes per row, freed after pass 2) instead of * re-hashing in pass 2 measured 15-25% faster for phase 1: the destination @@ -3665,12 +6052,12 @@ static inline uint64_t agg_radix_fmix64(uint64_t h) { * scattered stores issue back to back, and the keys go straight from the * column into the record with no staging row. */ RAY_INLINE void agg_radix_visit(agg_radix_ctx_t* c, uint32_t* cur, - int64_t r, int64_t pos, bool scatter) { - uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; + int64_t r, int64_t pos, bool scatter, bool wave) { + uint32_t n_keys = c->n_keys; if (!scatter) { uint64_t h = 1469598103934665603ULL; for (uint32_t k = 0; k < n_keys; k++) { - int64_t v = agg_read_key_i64(c->key_cols[k], c->key_data[k], r); + int64_t v = agg_radix_key_at(c->key_cols[k], c->key_data[k], r); h ^= (uint64_t)v; h *= 1099511628211ULL; } h = agg_radix_fmix64(h); @@ -3680,31 +6067,390 @@ RAY_INLINE void agg_radix_visit(agg_radix_ctx_t* c, uint32_t* cur, return; } uint32_t p = c->pid[pos]; - char* rec = c->pay + (size_t)(c->part_start[p] + cur[p]++) * c->rec; + if (wave && (p < c->wave_lo || p >= c->wave_hi)) return; + agg_radix_put(c, c->pay + (size_t)(c->part_start[p] - c->pay_base + cur[p]++) * c->rec, r, pos); +} + +/* agg_radix_visit of a staged context: row r read through view v (keys at + * r - base with the pieces' SYM widths, inputs from the pieces). The plain + * loops keep the column form above (its whole-column pointers are the + * context's; their loads stay as they were in the hot loop). */ +RAY_INLINE void agg_radix_visit_view(agg_radix_ctx_t* c, const agg_view_t* v, uint32_t* cur, + int64_t r, int64_t pos, bool scatter, bool wave) { + uint32_t n_keys = c->n_keys; + if (!scatter) { + const int64_t i = r - v->base; + uint64_t h = 1469598103934665603ULL; + for (uint32_t k = 0; k < n_keys; k++) { + int64_t val = agg_read_key_i64_raw(c->key_cols[k]->type, v->key_attrs[k], v->key_data[k], i); + h ^= (uint64_t)val; h *= 1099511628211ULL; + } + h = agg_radix_fmix64(h); + uint32_t p = (uint32_t)(h & (c->n_parts - 1)); + c->pid[pos] = (uint16_t)p; + cur[p]++; + return; + } + uint32_t p = c->pid[pos]; + if (wave && (p < c->wave_lo || p >= c->wave_hi)) return; + agg_radix_put_view(c, v, c->pay + (size_t)(c->part_start[p] - c->pay_base + cur[p]++) * c->rec, r, pos); +} + +/* The fused pass's visit of row r at position pos through view v: the + * hash picks the partition (recorded in the task's pid and counted, as + * pass 1 does) and the packed record is written at the position's slot of + * the task's staging buffer (as pass 2 writes it), so every source is read + * once. stage and spid are indexed by pos - pos0, the chunk's first + * position. */ +RAY_INLINE void agg_radix_stage_view(agg_radix_ctx_t* c, const agg_view_t* v, uint32_t* cur, + char* stage, uint16_t* spid, int64_t pos0, int64_t r, int64_t pos) { + uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; + const int64_t i = r - v->base; + char* rec = stage + (size_t)(pos - pos0) * c->rec; int64_t* kdst = (int64_t*)rec; - for (uint32_t k = 0; k < n_keys; k++) - kdst[k] = agg_read_key_i64(c->key_cols[k], c->key_data[k], r); - int64_t input_order = pos; + uint64_t h = 1469598103934665603ULL; + for (uint32_t k = 0; k < n_keys; k++) { + int64_t val = agg_read_key_i64_raw(c->key_cols[k]->type, v->key_attrs[k], v->key_data[k], i); + kdst[k] = val; + h ^= (uint64_t)val; h *= 1099511628211ULL; + } + h = agg_radix_fmix64(h); + uint32_t p = (uint32_t)(h & (c->n_parts - 1)); + spid[pos - pos0] = (uint16_t)p; + cur[p]++; for (uint32_t a = 0; a < n_aggs; a++) { - if (c->val_data[a]) { + if (v->val_data[a]) { uint8_t ez = c->val_esz[a]; - memcpy(rec + c->val_off[a], (const char*)c->val_data[a] + (size_t)r * ez, ez); + memcpy(rec + c->val_off[a], (const char*)v->val_data[a] + (size_t)i * ez, ez); } - if (c->val2_data[a]) { + if (v->val2_data[a]) { uint8_t ez2 = c->val2_esz[a]; - memcpy(rec + c->val2_off[a], (const char*)c->val2_data[a] + (size_t)r * ez2, ez2); + memcpy(rec + c->val2_off[a], (const char*)v->val2_data[a] + (size_t)i * ez2, ez2); } } - if (c->needs_row) + if (c->needs_row) { + int64_t input_order = pos; memcpy(rec + c->row_off, &input_order, sizeof(input_order)); + } +} + +/* One chunk's pass over a piece or a run, through view v: rows [b, e) + * (positions pos0 + (r - b)), or the selected rows rows[ib, ie) at + * positions pos0 + ib. */ +typedef struct { + agg_radix_ctx_t* c; + uint32_t* cur; + const int64_t* rows; /* sel mode: the chunk's decoded rows */ + int64_t pos0; +} agg_radix_run_t; +RAY_INLINE void agg_radix_run_rows(void* raw, const agg_view_t* v, int64_t b, int64_t e, + bool scatter, bool wave) { + agg_radix_run_t* t = raw; + if (t->rows) { + for (int64_t i = b; i < e; i++) + agg_radix_visit_view(t->c, v, t->cur, t->rows[i], t->pos0 + i, scatter, wave); + return; + } + for (int64_t r = b; r < e; r++) agg_radix_visit_view(t->c, v, t->cur, r, r, scatter, wave); +} +static void agg_radix_count_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t b, int64_t e) { + (void)wid; agg_radix_run_rows(raw, v, b, e, false, false); +} +static void agg_radix_scatter_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t b, int64_t e) { + (void)wid; agg_radix_run_rows(raw, v, b, e, true, false); +} +static void agg_radix_wave_scatter_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t b, int64_t e) { + (void)wid; agg_radix_run_rows(raw, v, b, e, true, true); +} + +/* The fused pass's body: rows [b, e) of a piece (each row its own + * position), or the selected rows rows[b, e) at positions pos0 + i, staged + * into the task's buffers. */ +typedef struct { + agg_radix_ctx_t* c; + uint32_t* cur; + const int64_t* rows; /* sel mode: the run's decoded rows */ + int64_t pos0; /* sel mode: position of rows[0]; else 0 */ + int64_t chunk0; /* the chunk's first position */ + char* stage; + uint16_t* spid; +} agg_radix_stage_t; +/* Rows [b, e) of a piece staged a field at a time (the type switches out + * of the row loops), in blocks of at most RAY_ENC_VEC rows: each key into + * its record slot and the running hash, then the partitions and counts, + * the inputs at their widths, the positions. The same records, ids and + * counts as agg_radix_stage_view row by row. */ +static void agg_radix_stage_block(agg_radix_stage_t* t, const agg_view_t* v, int64_t b, int64_t e) { + agg_radix_ctx_t* c = t->c; + const size_t rec = c->rec; + const int64_t i0 = b - v->base; + const int64_t n = e - b; + char* out = t->stage + (size_t)(b - t->chunk0) * rec; + uint16_t* spid = t->spid + (b - t->chunk0); + uint64_t h[RAY_ENC_VEC]; + for (int64_t i = 0; i < n; i++) h[i] = 1469598103934665603ULL; + for (uint32_t k = 0; k < c->n_keys; k++) { + const void* kd = v->key_data[k]; + char* kp = out + (size_t)k * 8; + #define STAGE_KEY(T) do { const T* src = (const T*)kd + i0; \ + for (int64_t i = 0; i < n; i++) { \ + int64_t val = (int64_t)src[i]; \ + memcpy(kp + (size_t)i * rec, &val, 8); \ + h[i] = (h[i] ^ (uint64_t)val) * 1099511628211ULL; \ + } } while (0) + switch (c->key_cols[k]->type) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: STAGE_KEY(int64_t); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: STAGE_KEY(int32_t); break; + case RAY_I16: STAGE_KEY(int16_t); break; + case RAY_U8: case RAY_BOOL: STAGE_KEY(uint8_t); break; + case RAY_SYM: + switch (v->key_attrs[k] & RAY_SYM_W_MASK) { + case RAY_SYM_W8: STAGE_KEY(uint8_t); break; + case RAY_SYM_W16: STAGE_KEY(uint16_t); break; + case RAY_SYM_W32: STAGE_KEY(uint32_t); break; + default: STAGE_KEY(int64_t); break; + } + break; + default: for (int64_t i = 0; i < n; i++) { memset(kp + (size_t)i * rec, 0, 8); h[i] *= 1099511628211ULL; } + } + #undef STAGE_KEY + } + const uint32_t mask = c->n_parts - 1; + uint32_t* cur = t->cur; + for (int64_t i = 0; i < n; i++) { + uint32_t p = (uint32_t)(agg_radix_fmix64(h[i]) & mask); + spid[i] = (uint16_t)p; + cur[p]++; + } + #define STAGE_FIELD(src, off, ez) do { \ + const char* sp = (const char*)(src) + (size_t)i0 * (ez); \ + char* dp = out + (off); \ + switch (ez) { \ + case 1: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * rec, sp + i, 1); break; \ + case 2: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * rec, sp + 2 * i, 2); break; \ + case 4: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * rec, sp + 4 * i, 4); break; \ + case 8: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * rec, sp + 8 * i, 8); break; \ + default: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * rec, sp + (size_t)i * (ez), (ez)); \ + } } while (0) + for (uint32_t a = 0; a < c->n_aggs; a++) { + if (v->val_data[a]) STAGE_FIELD(v->val_data[a], c->val_off[a], c->val_esz[a]); + if (v->val2_data[a]) STAGE_FIELD(v->val2_data[a], c->val2_off[a], c->val2_esz[a]); + } + #undef STAGE_FIELD + if (c->needs_row) { + char* rp = out + c->row_off; + for (int64_t i = 0; i < n; i++) { int64_t pos = b + i; memcpy(rp + (size_t)i * rec, &pos, 8); } + } +} +static void agg_radix_stage_block_c(agg_radix_stage_t* t, const agg_view_t* v, int64_t b, int64_t e); +static void agg_radix_stage_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t b, int64_t e) { + (void)wid; + agg_radix_stage_t* t = raw; + if (t->rows) { + for (int64_t i = b; i < e; i++) + agg_radix_stage_view(t->c, v, t->cur, t->stage, t->spid, t->chunk0, t->rows[i], t->pos0 + i); + return; + } + if (t->c->compact) { + for (int64_t r = b; r < e; r += RAY_ENC_VEC) + agg_radix_stage_block_c(t, v, r, e - r < RAY_ENC_VEC ? e : r + RAY_ENC_VEC); + return; + } + for (int64_t r = b; r < e; r += RAY_ENC_VEC) + agg_radix_stage_block(t, v, r, e - r < RAY_ENC_VEC ? e : r + RAY_ENC_VEC); +} + +/* Copy n records of `rec` bytes from the staging buffer to their slots: + * the chunk's partition runs, starting at wcur (offsets inside the chunk's + * record range at dst). Fixed record sizes copy with constant widths. */ +static void agg_radix_stage_scatter(char* dst, const char* stage, const uint16_t* spid, + uint32_t* wcur, int64_t n, size_t rec) { + #define STAGE_COPY(W) for (int64_t i = 0; i < n; i++) \ + memcpy(dst + (size_t)wcur[spid[i]]++ * (W), stage + (size_t)i * (W), (W)) + switch (rec) { + case 16: STAGE_COPY(16); break; + case 24: STAGE_COPY(24); break; + case 32: STAGE_COPY(32); break; + case 40: STAGE_COPY(40); break; + case 48: STAGE_COPY(48); break; + default: /* records are 8-aligned: word copies, no call */ + for (int64_t i = 0; i < n; i++) { + char* d = dst + (size_t)wcur[spid[i]]++ * rec; + const char* s = stage + (size_t)i * rec; + for (size_t w = 0; w < rec; w += 8) memcpy(d + w, s + w, 8); + } + break; + } + #undef STAGE_COPY +} + +/* agg_radix_stage_block of a compact context: rows [b, e) of a piece, + * hashed over every key (plain ones read in place through the view), the + * staged sources' fields copied into the staged rows (srec bytes each), + * the partitions and counts recorded. The plain fields and the positions + * are left to agg_radix_scatter_compact. */ +static void agg_radix_stage_block_c(agg_radix_stage_t* t, const agg_view_t* v, int64_t b, int64_t e) { + agg_radix_ctx_t* c = t->c; + const size_t srec = c->srec; + const int64_t i0 = b - v->base; + const int64_t n = e - b; + char* out = t->stage + (size_t)(b - t->chunk0) * srec; + uint16_t* spid = t->spid + (b - t->chunk0); + uint64_t h[RAY_ENC_VEC]; + for (int64_t i = 0; i < n; i++) h[i] = 1469598103934665603ULL; + for (uint32_t k = 0; k < c->n_keys; k++) { + const void* kd = v->key_data[k]; + const agg_radix_cf_t* f = &c->cf[k]; + char* kp = out + f->soff; + if (f->kind == AGG_CF_STAGED) { + #define STAGE_KEY(T) do { const T* src = (const T*)kd + i0; \ + for (int64_t i = 0; i < n; i++) { \ + int64_t val = (int64_t)src[i]; \ + memcpy(kp + (size_t)i * srec, &val, 8); \ + h[i] = (h[i] ^ (uint64_t)val) * 1099511628211ULL; \ + } } while (0) + switch (c->key_cols[k]->type) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: STAGE_KEY(int64_t); break; + case RAY_I32: case RAY_DATE: case RAY_TIME: STAGE_KEY(int32_t); break; + case RAY_I16: STAGE_KEY(int16_t); break; + case RAY_U8: case RAY_BOOL: STAGE_KEY(uint8_t); break; + case RAY_SYM: + switch (v->key_attrs[k] & RAY_SYM_W_MASK) { + case RAY_SYM_W8: STAGE_KEY(uint8_t); break; + case RAY_SYM_W16: STAGE_KEY(uint16_t); break; + case RAY_SYM_W32: STAGE_KEY(uint32_t); break; + default: STAGE_KEY(int64_t); break; + } + break; + default: for (int64_t i = 0; i < n; i++) { memset(kp + (size_t)i * srec, 0, 8); h[i] *= 1099511628211ULL; } + } + #undef STAGE_KEY + continue; + } + #define HASH_KEY(T) do { const T* src = (const T*)kd + i0; \ + for (int64_t i = 0; i < n; i++) \ + h[i] = (h[i] ^ (uint64_t)(int64_t)src[i]) * 1099511628211ULL; } while (0) + switch (f->kind) { + case AGG_CF_KEY_I64: HASH_KEY(int64_t); break; + case AGG_CF_KEY_I32: HASH_KEY(int32_t); break; + case AGG_CF_KEY_I16: HASH_KEY(int16_t); break; + case AGG_CF_KEY_U8: HASH_KEY(uint8_t); break; + case AGG_CF_KEY_U16: HASH_KEY(uint16_t); break; + case AGG_CF_KEY_U32: HASH_KEY(uint32_t); break; + default: for (int64_t i = 0; i < n; i++) h[i] *= 1099511628211ULL; + } + #undef HASH_KEY + } + const uint32_t mask = c->n_parts - 1; + uint32_t* cur = t->cur; + for (int64_t i = 0; i < n; i++) { + uint32_t p = (uint32_t)(agg_radix_fmix64(h[i]) & mask); + spid[i] = (uint16_t)p; + cur[p]++; + } + /* the staged inputs: each field names its aggregate and side */ + for (uint32_t fi = c->n_keys; fi < c->n_cf; fi++) { + const agg_radix_cf_t* f = &c->cf[fi]; + if (f->kind != AGG_CF_STAGED) continue; + const void* vd = f->y ? v->val2_data[f->agg] : v->val_data[f->agg]; + const char* sp = (const char*)vd + (size_t)i0 * f->w; + char* dp = out + f->soff; + switch (f->w) { + case 1: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * srec, sp + i, 1); break; + case 2: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * srec, sp + 2 * i, 2); break; + case 4: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * srec, sp + 4 * i, 4); break; + case 8: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * srec, sp + 8 * i, 8); break; + default: for (int64_t i = 0; i < n; i++) memcpy(dp + (size_t)i * srec, sp + (size_t)i * f->w, f->w); + } + } +} + +/* The scatter of a compact chunk: n staged rows (positions pos0 ..) to + * their slots at wcur (offsets inside the chunk's record range at dst), + * each record built as the two passes' scatter builds it: the staged + * fields from the staged row, the plain ones read in place at the row, + * the position. */ +static void agg_radix_scatter_compact(const agg_radix_ctx_t* c, char* dst, const char* stage, + const uint16_t* spid, uint32_t* wcur, int64_t pos0, int64_t n) { + const size_t rec = c->rec, srec = c->srec; + const uint32_t nf = c->n_cf; + const agg_radix_cf_t* cf = c->cf; + const size_t row_off = c->row_off; + const bool needs_row = c->needs_row; + for (int64_t i = 0; i < n; i++) { + char* d = dst + (size_t)wcur[spid[i]]++ * rec; + const char* sr = stage + (size_t)i * srec; + const int64_t r = pos0 + i; + for (uint32_t fi = 0; fi < nf; fi++) { + const agg_radix_cf_t* f = &cf[fi]; + int64_t kv; + switch (f->kind) { + case AGG_CF_STAGED: + switch (f->w) { + case 1: memcpy(d + f->off, sr + f->soff, 1); break; + case 2: memcpy(d + f->off, sr + f->soff, 2); break; + case 4: memcpy(d + f->off, sr + f->soff, 4); break; + case 8: memcpy(d + f->off, sr + f->soff, 8); break; + default: memcpy(d + f->off, sr + f->soff, f->w); + } + continue; + case AGG_CF_KEY_I64: kv = ((const int64_t*)f->plain)[r]; break; + case AGG_CF_KEY_I32: kv = ((const int32_t*)f->plain)[r]; break; + case AGG_CF_KEY_I16: kv = ((const int16_t*)f->plain)[r]; break; + case AGG_CF_KEY_U8: kv = ((const uint8_t*)f->plain)[r]; break; + case AGG_CF_KEY_U16: kv = ((const uint16_t*)f->plain)[r]; break; + case AGG_CF_KEY_U32: kv = ((const uint32_t*)f->plain)[r]; break; + default: + memcpy(d + f->off, f->plain + (size_t)r * f->esz, f->esz); + continue; + } + memcpy(d + f->off, &kv, 8); + } + if (needs_row) memcpy(d + row_off, &r, sizeof r); + } } -/* Run one pass over chunk `ch`: input positions [start,end) in chunk order - * (selected-row ordinals in sel mode, decoded to original rows). RAY_INLINE - * and `scatter` constant at both call sites, so the count and the scatter - * loops specialize. A chunk's count row doubles as its pass-2 write cursors - * and is touched only by the task running that chunk. */ -RAY_INLINE void agg_radix_chunk_pass(agg_radix_ctx_t* c, int64_t ch, bool scatter) { +/* The staged form of one pass over chunk ch (out of line: the plain loops + * below stay as compact as they were): pieces of the chunk's rows (R-WALK), + * or runs of its selected rows (R-SPARSE), through the task's cursors cs + * (the chunks of one task are consecutive); a range error is noted keyed + * by the chunk's first position. A wave's scatter (`wave`) writes only the + * records of its partitions. */ +static void agg_radix_chunk_staged(agg_radix_ctx_t* c, int64_t ch, uint32_t wid, bool scatter, bool wave, + agg_curs_t* cs) { + int64_t start = ch * c->chunk_rows; + int64_t end = start + c->chunk_rows; + if (end > c->n_in) end = c->n_in; + uint32_t* cur = c->cnt + (size_t)ch * c->n_parts; + if (!scatter) memset(cur, 0, (size_t)c->n_parts * sizeof(uint32_t)); + const agg_rr_t* rr = scatter ? c->rr : c->count_rr; /* pass 1 hashes the keys only */ + agg_body_fn body = !scatter ? agg_radix_count_rows + : wave ? agg_radix_wave_scatter_rows : agg_radix_scatter_rows; + if (!c->sel) { + agg_radix_run_t t = { c, cur, NULL, 0 }; + (void)agg_walk_cs(rr, cs, &t, body, wid, start, end, start); + return; + } + if (ray_scan_fail_skip(rr->fail, start)) return; + int64_t rows[AGG_SEL_CHUNK]; + agg_sel_cursor_t sc; + agg_sel_cursor_init(&sc, c->sel, c->sel_prefix, start, end); + int64_t pos = start, cn; + while ((cn = agg_sel_cursor_next(&sc, rows)) > 0) { + agg_radix_run_t t = { c, cur, rows, pos }; + ray_t* err = agg_idx_walk(rr, cs, rows, 0, cn, &t, body, wid); + if (err) { ray_scan_fail_note(rr->fail, start, err); break; } + pos += cn; + } +} + +/* Run one pass over chunk `ch` of a plain context (whole columns): input + * positions [start,end) in chunk order (selected-row ordinals in sel mode, + * decoded to original rows). RAY_INLINE and `scatter` constant at every + * call site, so the count and the scatter loops specialize. A chunk's + * count row doubles as its pass-2 write cursors and is touched only by the + * task running that chunk. A staged context runs agg_radix_chunk_staged. */ +RAY_INLINE void agg_radix_chunk_pass(agg_radix_ctx_t* c, int64_t ch, bool scatter, bool wave) { int64_t start = ch * c->chunk_rows; int64_t end = start + c->chunk_rows; if (end > c->n_in) end = c->n_in; @@ -3718,7 +6464,7 @@ RAY_INLINE void agg_radix_chunk_pass(agg_radix_ctx_t* c, int64_t ch, bool scatte int64_t cn; while ((cn = agg_sel_cursor_next(&sc, rows)) > 0) for (int64_t i = 0; i < cn; i++) - agg_radix_visit(c, cur, rows[i], pos++, scatter); + agg_radix_visit(c, cur, rows[i], pos++, scatter, wave); return; } /* Keep the next rows requested from storage, block by block (scan @@ -3728,52 +6474,462 @@ RAY_INLINE void agg_radix_chunk_pass(agg_radix_ctx_t* c, int64_t ch, bool scatte int64_t e = end - b > 8192 ? b + 8192 : end; ray_pool_scan_at(c->n_in, b, end); for (int64_t r = b; r < e; r++) - agg_radix_visit(c, cur, r, r, scatter); + agg_radix_visit(c, cur, r, r, scatter, wave); + } +} + +/* One cursor set per task call (staged sources), over its consecutive chunks; + * on OOM the first chunk's failure is noted and the call does nothing. */ +static bool agg_radix_task_curs(agg_radix_ctx_t* c, int64_t ch0, agg_curs_t* cs) { + cs->cur = NULL; + if (!c->rr->staged || agg_curs_init(cs, c->rr)) return true; + ray_scan_fail_note(c->rr->fail, ch0 * c->chunk_rows, ray_error("oom", NULL)); + return false; +} + +/* One task call of a pass over its consecutive chunks [start,end). One + * body, two instances per pass (`staged` constant): the plain instance is + * the whole-column chunk loop and never builds or touches a cursor set, so + * its codegen is the pre-range-read one; the staged instance holds one + * cursor set across its chunks. The dispatch picks the instance from the + * context (agg_radix_count_fn or _count_staged_fn, and likewise for the + * scatter). */ +RAY_INLINE void agg_radix_pass_body(agg_radix_ctx_t* c, uint32_t wid, int64_t start, int64_t end, + bool scatter, bool wave, const bool staged) { + if (!staged) { + for (int64_t ch = start; ch < end; ch++) + agg_radix_chunk_pass(c, ch, scatter, wave); + return; + } + agg_curs_t cs; + if (!agg_radix_task_curs(c, start, &cs)) return; + for (int64_t ch = start; ch < end; ch++) + agg_radix_chunk_staged(c, ch, wid, scatter, wave, &cs); + agg_curs_free(&cs, c->rr); +} + +/* Phase 1, pass 1: count each chunk's rows per partition. */ +static void agg_radix_count_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_pass_body((agg_radix_ctx_t*)vctx, wid, start, end, false, false, false); +} +static void agg_radix_count_staged_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_pass_body((agg_radix_ctx_t*)vctx, wid, start, end, false, false, true); +} + +/* Phase 1, prefix: for a band of partitions, turn every chunk's count into + * its offset inside the partition (exclusive scan down the chunks, so chunk + * order — ascending input order — is the slot order) and store the + * partition's total in part_start[p + 1] for the caller's scan. */ +static void agg_radix_prefix_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; + for (int64_t band = start; band < end; band++) { + uint32_t p0 = (uint32_t)band * AGG_RADIX_PREFIX_BAND; + uint32_t np = c->n_parts - p0; + if (np > AGG_RADIX_PREFIX_BAND) np = AGG_RADIX_PREFIX_BAND; + uint64_t run[AGG_RADIX_PREFIX_BAND] = {0}; + for (uint32_t ch = 0; ch < c->n_chunks; ch++) { + uint32_t* row = c->cnt + (size_t)ch * c->n_parts + p0; + for (uint32_t j = 0; j < np; j++) { + uint32_t n = row[j]; + row[j] = (uint32_t)run[j]; + run[j] += n; + } + } + for (uint32_t j = 0; j < np; j++) { + /* Offsets are uint32 and phase 2 indexes a partition's rows with + * 32-bit gids: a partition past that bound takes the fallback. */ + if (run[j] > UINT32_MAX) + atomic_store_explicit(&c->part_overflow, 1, memory_order_relaxed); + c->part_start[p0 + j + 1] = (int64_t)run[j]; + } + } +} + +/* Phase 1, pass 2: write each chunk's packed records at their exact slots. */ +static void agg_radix_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_pass_body((agg_radix_ctx_t*)vctx, wid, start, end, true, false, false); +} +static void agg_radix_scatter_staged_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_pass_body((agg_radix_ctx_t*)vctx, wid, start, end, true, false, true); +} + +/* Pass 2 of one wave: the same walk, writing only the records of the + * partitions [wave_lo, wave_hi). Each partition belongs to one wave, so its + * chunk cursors advance exactly as in the one-pass scatter and its records + * land in the same order. */ +static void agg_radix_wave_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_pass_body((agg_radix_ctx_t*)vctx, wid, start, end, true, true, false); +} +static void agg_radix_wave_scatter_staged_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_pass_body((agg_radix_ctx_t*)vctx, wid, start, end, true, true, true); +} + +/* The fused pass over chunk ch (a staged context, chunk-major payload): + * the chunk is read once (pieces, or runs of its selected rows) into the + * task's staging buffers, its count row becomes the chunk-local exclusive + * prefix (each partition's offset inside the chunk's record range), and + * the staged records are scattered there. A range error is noted keyed by + * the chunk's first position, and the chunk is not scattered. */ +static void agg_radix_chunk_fused(agg_radix_ctx_t* c, int64_t ch, uint32_t wid, agg_curs_t* cs, + char* stage, uint16_t* spid, uint32_t* wcur) { + const agg_rr_t* rr = c->rr; + int64_t start = ch * c->chunk_rows; + int64_t end = start + c->chunk_rows; + if (end > c->n_in) end = c->n_in; + uint32_t* cur = c->cnt + (size_t)ch * c->n_parts; + memset(cur, 0, (size_t)c->n_parts * sizeof(uint32_t)); + agg_radix_stage_t t = { c, cur, NULL, 0, start, stage, spid }; + if (!c->sel) { + if (!agg_walk_cs(rr, cs, &t, agg_radix_stage_rows, wid, start, end, start)) return; + } else { + if (ray_scan_fail_skip(rr->fail, start)) return; + int64_t rows[AGG_SEL_CHUNK]; + agg_sel_cursor_t sc; + agg_sel_cursor_init(&sc, c->sel, c->sel_prefix, start, end); + int64_t pos = start, cn; + while ((cn = agg_sel_cursor_next(&sc, rows)) > 0) { + t.rows = rows; t.pos0 = pos; + ray_t* err = agg_idx_walk(rr, cs, rows, 0, cn, &t, agg_radix_stage_rows, wid); + if (err) { ray_scan_fail_note(rr->fail, start, err); return; } + pos += cn; + } + } + uint32_t run = 0; + for (uint32_t p = 0; p < c->n_parts; p++) { + uint32_t n = cur[p]; + cur[p] = wcur[p] = run; + run += n; + } + if (c->compact) + agg_radix_scatter_compact(c, c->pay + (size_t)start * c->rec, stage, spid, wcur, start, end - start); + else + agg_radix_stage_scatter(c->pay + (size_t)start * c->rec, stage, spid, wcur, end - start, c->rec); +} + +/* Phase 1 of a fused context: one task call's consecutive chunks (a few + * tasks per worker, so a vector a chunk boundary cuts is decoded once per + * task, not per chunk) through one cursor set and one set of staging + * buffers (a chunk's records, its + * partition ids, the partitions' write cursors), allocated by the call + * and freed by it; on OOM the first chunk's failure is noted. */ +static void agg_radix_fused_fn(void* vctx, uint32_t wid, int64_t g0, int64_t g1) { + agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; + /* tasks g0..g1 of fused_tasks, each a run of consecutive chunks */ + int64_t start = (int64_t)((uint64_t)g0 * c->n_chunks / c->fused_tasks); + int64_t end = (int64_t)((uint64_t)g1 * c->n_chunks / c->fused_tasks); + if (start >= end) return; + agg_curs_t cs; + if (!agg_radix_task_curs(c, start, &cs)) return; + char* stage = ray_alloc_raw((size_t)c->chunk_rows * (c->compact ? (c->srec ? c->srec : 1) : c->rec)); + uint16_t* spid = ray_alloc_raw((size_t)c->chunk_rows * sizeof(uint16_t)); + uint32_t* wcur = ray_alloc_raw((size_t)c->n_parts * sizeof(uint32_t)); + if (!stage || !spid || !wcur) + ray_scan_fail_note(c->rr->fail, start * c->chunk_rows, ray_error("oom", NULL)); + else + for (int64_t ch = start; ch < end; ch++) + agg_radix_chunk_fused(c, ch, wid, &cs, stage, spid, wcur); + ray_free_raw(stage); ray_free_raw(spid); ray_free_raw(wcur); + agg_curs_free(&cs, c->rr); +} + +/* A fused context's partition totals, for a band of partitions: the sum of + * every chunk's run length (the next partition's offset, or the chunk's + * row count for the last), stored in part_start[p + 1] for the caller's + * scan (as agg_radix_prefix_fn stores them); each run's offset and length + * also go to the partition's row of runs, which phase 2 reads in order. */ +static void agg_radix_fused_totals_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; + for (int64_t band = start; band < end; band++) { + uint32_t p0 = (uint32_t)band * AGG_RADIX_PREFIX_BAND; + uint32_t np = c->n_parts - p0; + if (np > AGG_RADIX_PREFIX_BAND) np = AGG_RADIX_PREFIX_BAND; + uint64_t run[AGG_RADIX_PREFIX_BAND] = {0}; + for (uint32_t ch = 0; ch < c->n_chunks; ch++) { + const uint32_t* row = c->cnt + (size_t)ch * c->n_parts; + int64_t cs = (int64_t)ch * c->chunk_rows; + int64_t clen = (cs + c->chunk_rows < c->n_in ? cs + c->chunk_rows : c->n_in) - cs; + for (uint32_t j = 0; j < np; j++) { + uint32_t p = p0 + j; + uint64_t next = p + 1 < c->n_parts ? row[p + 1] : (uint64_t)clen; + uint32_t* rp = c->runs + ((size_t)p * c->n_chunks + ch) * 2; + rp[0] = row[p]; + rp[1] = (uint32_t)(next - row[p]); + run[j] += next - row[p]; + } + } + for (uint32_t j = 0; j < np; j++) { + if (run[j] > UINT32_MAX) + atomic_store_explicit(&c->part_overflow, 1, memory_order_relaxed); + c->part_start[p0 + j + 1] = (int64_t)run[j]; + } + } +} + +/* Reduce a finished partition to the groups a top-N emit can select. + * + * agg_radix_select_topn keeps every group strictly beyond the threshold T + * (the N-th value, N = take) and, of the groups AT T, the N with the + * smallest first row; it emits them in first-row order. Rank the groups by + * (value in the keep direction, then smaller first row) — a total order, + * first rows being distinct. The kept set is a prefix of that order no + * longer than 2N - 1: fewer than N groups lie strictly beyond T, then come + * the tied ones by first row. Every group of that prefix ranks below 2N + * inside its own partition too (only prefix members rank ahead of it), so a + * partition that keeps its 2N best (cmp_cap) loses no kept group, and the + * union of the survivors still holds the N best values, so the selection + * over the survivors finds the same T, the same strict groups and the same + * tied ones: the emitted rows are byte-identical. States are copied as they + * are (streaming accumulators, no destroy hook) and so are their keys and + * first rows. On an allocation failure the partition keeps every group, + * which is the unreduced, equally valid input of the same selection. */ +static void agg_radix_part_compact(agg_radix_ctx_t* c, char** states, + int64_t** first_row, int64_t** gkeys, int64_t* ngp) { + int64_t ng = *ngp, cap = c->cmp_cap; + if (cap <= 0 || ng <= cap) return; + uint32_t n_keys = c->n_keys; + size_t kw = (size_t)(n_keys ? n_keys : 1); + double* vals = ray_alloc_raw((size_t)ng * sizeof(double)); + int64_t* heap = ray_alloc_raw((size_t)cap * sizeof(int64_t)); + if (!vals || !heap || + !agg_group_values_f64(c->cmp_vt, *states, c->block, c->cmp_off, NULL, ng, + c->cmp_param, vals)) { + ray_free_raw(vals); ray_free_raw(heap); + return; + } + const int64_t* fr = *first_row; + uint8_t desc = c->cmp_desc; + /* i ranks after j: worse value, or the same value seen later. */ + #define CMP_AFTER(i, j) ((desc ? vals[i] < vals[j] : vals[i] > vals[j]) || \ + (vals[i] == vals[j] && fr[i] > fr[j])) + int64_t hn = 0; + for (int64_t gg = 0; gg < ng; gg++) { /* root = the last kept */ + if (hn < cap) { + int64_t j = hn++; + heap[j] = gg; + while (j > 0) { + int64_t par = (j - 1) / 2; + if (!CMP_AFTER(heap[j], heap[par])) break; + int64_t t = heap[par]; heap[par] = heap[j]; heap[j] = t; j = par; + } + } else if (CMP_AFTER(heap[0], gg)) { + heap[0] = gg; + for (int64_t j = 0;;) { + int64_t l = 2 * j + 1, r = l + 1, m = j; + if (l < cap && CMP_AFTER(heap[l], heap[m])) m = l; + if (r < cap && CMP_AFTER(heap[r], heap[m])) m = r; + if (m == j) break; + int64_t t = heap[m]; heap[m] = heap[j]; heap[j] = t; j = m; + } + } + } + #undef CMP_AFTER + ray_free_raw(vals); + char* ns = ray_alloc_raw((size_t)cap * c->block); + int64_t* nk = ray_alloc_raw((size_t)cap * kw * sizeof(int64_t)); + int64_t* nf = ray_alloc_raw((size_t)cap * sizeof(int64_t)); + if (!ns || !nk || !nf) { + ray_free_raw(ns); ray_free_raw(nk); ray_free_raw(nf); ray_free_raw(heap); + return; + } + for (int64_t i = 0; i < cap; i++) { + int64_t gg = heap[i]; + memcpy(ns + (size_t)i * c->block, *states + (size_t)gg * c->block, c->block); + memcpy(nk + (size_t)i * kw, *gkeys + (size_t)gg * kw, kw * sizeof(int64_t)); + nf[i] = fr[gg]; + } + ray_free_raw(heap); + ray_free_raw(*states); ray_free_raw(*gkeys); ray_free_raw(*first_row); + *states = ns; *gkeys = nk; *first_row = nf; *ngp = cap; + atomic_fetch_add_explicit(&c->cmp_parts, 1, memory_order_relaxed); +} + +#if AGG_RADIX_FILE_SPILL +static bool agg_spill_pwrite(int fd, const char* p, size_t n, int64_t off) { + while (n) { + ssize_t w = pwrite(fd, p, n, (off_t)off); + if (w < 0 && errno == EINTR) continue; + if (w <= 0) return false; + p += w; off += w; n -= (size_t)w; + } + return true; +} +static bool agg_spill_pread(int fd, char* p, size_t n, int64_t off) { + while (n) { + ssize_t r = pread(fd, p, n, (off_t)off); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) return false; + p += r; off += r; n -= (size_t)r; } + return true; +} +#endif + +/* The spill file: unlinked as soon as it is open, in the heap's spill + * directory (RAY_HEAP_SWAP, else TMPDIR, else /tmp — as heap_swap_dir). */ +static int agg_radix_spill_open(void) { +#if AGG_RADIX_FILE_SPILL + static _Atomic(uint64_t) ctr = 0; + const char* d = getenv("RAY_HEAP_SWAP"); + if (!(d && *d)) d = getenv("TMPDIR"); + if (!(d && *d) || strlen(d) > 400) d = "/tmp"; + size_t dl = strlen(d); + char path[512]; + snprintf(path, sizeof path, "%s%sraygroup_%d_%llu.dat", d, d[dl - 1] == '/' ? "" : "/", + (int)getpid(), + (unsigned long long)atomic_fetch_add_explicit(&ctr, 1, memory_order_relaxed)); + int fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600); + if (fd >= 0) unlink(path); + return fd; +#else + return -1; +#endif +} + +/* Append a full (or the last) buffer of one wave as one block. */ +static void agg_radix_spill_flush(agg_radix_spill_t* s, agg_radix_sbuf_t* b, uint32_t wave) { + if (!b->n) return; +#if AGG_RADIX_FILE_SPILL + size_t rb = (size_t)b->n * s->rec, sb = (size_t)b->n * sizeof(uint32_t); + int64_t bi = atomic_fetch_add_explicit(&s->n_blks, 1, memory_order_relaxed); + int64_t off = atomic_fetch_add_explicit(&s->tail, (int64_t)(rb + sb), memory_order_relaxed); + if (bi >= s->blk_cap || ray_agg_radix_spill == 4 || + !agg_spill_pwrite(s->fd, b->buf, rb, off) || + !agg_spill_pwrite(s->fd, b->buf + (size_t)s->bcap * s->rec, sb, off + (int64_t)rb)) + atomic_store_explicit(&s->err, 1, memory_order_relaxed); + else + s->blks[bi] = (agg_radix_blk_t){ off, b->n, wave }; +#else + (void)wave; + atomic_store_explicit(&s->err, 1, memory_order_relaxed); +#endif + b->n = 0; +} + +/* Where a spilled run scatters input position pos: wave 0 to its payload + * slot, a later wave to the next record of this worker's buffer, with the + * slot it will take when read back stored beside it (a full buffer is + * flushed first). The chunk cursors advance for every partition exactly as + * in the one-pass scatter, so every record's slot is the one-pass slot less + * its wave base. */ +RAY_INLINE char* agg_radix_spill_dst(agg_radix_ctx_t* c, uint32_t* cur, + agg_radix_sbuf_t* wb, int64_t pos) { + agg_radix_spill_t* s = c->spill; + uint32_t p = c->pid[pos]; + uint32_t w = c->wave_of[p]; + int64_t slot = c->part_start[p] - s->wave_base[w] + cur[p]++; + if (w == 0) return c->pay + (size_t)slot * c->rec; + agg_radix_sbuf_t* b = &wb[w]; + if (b->n == s->bcap) agg_radix_spill_flush(s, b, w); + ((uint32_t*)(void*)(b->buf + (size_t)s->bcap * c->rec))[b->n] = (uint32_t)slot; + return b->buf + (size_t)b->n++ * c->rec; } -/* Phase 1, pass 1: count each chunk's rows per partition. */ -static void agg_radix_count_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - (void)wid; - for (int64_t ch = start; ch < end; ch++) - agg_radix_chunk_pass((agg_radix_ctx_t*)vctx, ch, false); +/* The spilled scatter of a plain context (whole columns). */ +static void agg_radix_spill_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; + agg_radix_sbuf_t* wb = c->spill->bufs + (size_t)wid * c->spill->n_waves; + for (int64_t ch = start; ch < end; ch++) { + int64_t cs = ch * c->chunk_rows, ce = cs + c->chunk_rows; + if (ce > c->n_in) ce = c->n_in; + uint32_t* cur = c->cnt + (size_t)ch * c->n_parts; + if (c->sel) { + int64_t rows[AGG_SEL_CHUNK]; + agg_sel_cursor_t sc; + agg_sel_cursor_init(&sc, c->sel, c->sel_prefix, cs, ce); + int64_t pos = cs, cn; + while ((cn = agg_sel_cursor_next(&sc, rows)) > 0) + for (int64_t i = 0; i < cn; i++, pos++) + agg_radix_put(c, agg_radix_spill_dst(c, cur, wb, pos), rows[i], pos); + continue; + } + for (int64_t b = cs; b < ce; b += 8192) { + int64_t e = ce - b > 8192 ? b + 8192 : ce; + ray_pool_scan_at(c->n_in, b, ce); + for (int64_t r = b; r < e; r++) + agg_radix_put(c, agg_radix_spill_dst(c, cur, wb, r), r, r); + } + } } -/* Phase 1, prefix: for a band of partitions, turn every chunk's count into - * its offset inside the partition (exclusive scan down the chunks, so chunk - * order — ascending input order — is the slot order) and store the - * partition's total in part_start[p + 1] for the caller's scan. */ -static void agg_radix_prefix_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { +/* The spilled scatter of a staged context: rows read through views, as + * agg_radix_chunk_staged reads them; a range error is noted keyed by the + * chunk's first position and leaves the chunk unscattered. */ +typedef struct { + agg_radix_ctx_t* c; + uint32_t* cur; + const int64_t* rows; /* sel mode: the chunk's decoded rows */ + int64_t pos0; + agg_radix_sbuf_t* wb; +} agg_radix_spill_rows_t; +static void agg_radix_spill_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t b, int64_t e) { (void)wid; + agg_radix_spill_rows_t* t = raw; + if (t->rows) { + for (int64_t i = b; i < e; i++) { + int64_t pos = t->pos0 + i; + agg_radix_put_view(t->c, v, agg_radix_spill_dst(t->c, t->cur, t->wb, pos), t->rows[i], pos); + } + return; + } + for (int64_t r = b; r < e; r++) + agg_radix_put_view(t->c, v, agg_radix_spill_dst(t->c, t->cur, t->wb, r), r, r); +} +static void agg_radix_spill_scatter_staged_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; - for (int64_t band = start; band < end; band++) { - uint32_t p0 = (uint32_t)band * AGG_RADIX_PREFIX_BAND; - uint32_t np = c->n_parts - p0; - if (np > AGG_RADIX_PREFIX_BAND) np = AGG_RADIX_PREFIX_BAND; - uint64_t run[AGG_RADIX_PREFIX_BAND] = {0}; - for (uint32_t ch = 0; ch < c->n_chunks; ch++) { - uint32_t* row = c->cnt + (size_t)ch * c->n_parts + p0; - for (uint32_t j = 0; j < np; j++) { - uint32_t n = row[j]; - row[j] = (uint32_t)run[j]; - run[j] += n; - } + const agg_rr_t* rr = c->rr; + agg_radix_sbuf_t* wb = c->spill->bufs + (size_t)wid * c->spill->n_waves; + agg_curs_t curs; + if (!agg_radix_task_curs(c, start, &curs)) return; + for (int64_t ch = start; ch < end; ch++) { + int64_t cs = ch * c->chunk_rows, ce = cs + c->chunk_rows; + if (ce > c->n_in) ce = c->n_in; + uint32_t* cur = c->cnt + (size_t)ch * c->n_parts; + if (!c->sel) { + agg_radix_spill_rows_t t = { c, cur, NULL, 0, wb }; + (void)agg_walk_cs(rr, &curs, &t, agg_radix_spill_rows, wid, cs, ce, cs); + continue; } - for (uint32_t j = 0; j < np; j++) { - /* Offsets are uint32 and phase 2 indexes a partition's rows with - * 32-bit gids: a partition past that bound takes the fallback. */ - if (run[j] > UINT32_MAX) - atomic_store_explicit(&c->part_overflow, 1, memory_order_relaxed); - c->part_start[p0 + j + 1] = (int64_t)run[j]; + if (ray_scan_fail_skip(rr->fail, cs)) continue; + int64_t rows[AGG_SEL_CHUNK]; + agg_sel_cursor_t sc; + agg_sel_cursor_init(&sc, c->sel, c->sel_prefix, cs, ce); + int64_t pos = cs, cn; + while ((cn = agg_sel_cursor_next(&sc, rows)) > 0) { + agg_radix_spill_rows_t t = { c, cur, rows, pos, wb }; + ray_t* err = agg_idx_walk(rr, &curs, rows, 0, cn, &t, agg_radix_spill_rows, wid); + if (err) { ray_scan_fail_note(rr->fail, cs, err); break; } + pos += cn; } } + agg_curs_free(&curs, rr); } -/* Phase 1, pass 2: write each chunk's packed records at their exact slots. */ -static void agg_radix_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - (void)wid; - for (int64_t ch = start; ch < end; ch++) - agg_radix_chunk_pass((agg_radix_ctx_t*)vctx, ch, true); +/* Read the blocks of one wave back into their payload slots. */ +static void agg_radix_readback_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; + agg_radix_spill_t* s = c->spill; +#if AGG_RADIX_FILE_SPILL + char* rb = s->rbuf + (size_t)wid * s->rstride; + for (int64_t i = start; i < end; i++) { + const agg_radix_blk_t* bk = &s->blks[s->wave_blks[i]]; + size_t rbytes = (size_t)bk->n * c->rec; + if (ray_agg_radix_spill == 5) /* test fault: the pool is cancelled mid read-back */ + atomic_store_explicit(&ray_pool_get()->cancelled, 1, memory_order_relaxed); + if (ray_agg_radix_spill == 3 || + !agg_spill_pread(s->fd, rb, rbytes + (size_t)bk->n * sizeof(uint32_t), bk->off)) { + atomic_store_explicit(&s->err, 1, memory_order_relaxed); + continue; + } + const uint32_t* slots = (const uint32_t*)(const void*)(rb + rbytes); + for (uint32_t j = 0; j < bk->n; j++) + memcpy(c->pay + (size_t)slots[j] * c->rec, rb + (size_t)j * c->rec, c->rec); + } +#else + (void)wid; (void)start; (void)end; + atomic_store_explicit(&s->err, 1, memory_order_relaxed); +#endif } /* Phase 2: group + accumulate one partition by walking its packed payload @@ -3782,15 +6938,19 @@ static void agg_radix_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_ * contiguous packed keys at the head of each record (no scattered key-column * re-reads), and each agg's dense value buffer is gathered straight from the * records in the same sequential pass. Keys are disjoint from other - * partitions so the partition-local open-addressing hash suffices. */ + * partitions so the partition-local open-addressing hash suffices. Under a + * top-N emit (cmp_cap) the finished partition is cut to its candidates + * (agg_radix_part_compact) before it is published. */ static void agg_radix_group_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { (void)wid; agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; size_t key_bytes = (size_t)n_keys * 8; for (int64_t pi = start; pi < end; pi++) { - uint32_t p = (uint32_t)pi; + uint32_t p = c->part_lo + (uint32_t)pi; agg_radix_part_t* pr = &c->parts[p]; + if (ray_agg_radix_spill == 6 && c->pay_base > 0) /* test fault: cancelled in a later wave */ + atomic_store_explicit(&ray_pool_get()->cancelled, 1, memory_order_relaxed); /* Rows hashing to p: its contiguous slot range, in input order. */ int64_t total = c->part_start[p + 1] - c->part_start[p]; @@ -3845,7 +7005,7 @@ static void agg_radix_group_fn(void* vctx, uint32_t wid, int64_t start, int64_t int64_t ng = 0, ri = 0; { - const char* rec = c->pay + (size_t)c->part_start[p] * c->rec; + const char* rec = c->pay + (size_t)(c->part_start[p] - c->pay_base) * c->rec; for (int64_t i = 0; i < total; i++, rec += c->rec) { const int64_t* keys = (const int64_t*)rec; int64_t r = 0; @@ -3944,6 +7104,198 @@ static void agg_radix_group_fn(void* vctx, uint32_t wid, int64_t start, int64_t for (uint32_t a = 0; a < n_aggs; a++) { ray_free_raw(gv[a]); ray_free_raw(gy[a]); } ray_free_raw(gv); ray_free_raw(gy); ray_free_raw(gid); + if (c->cmp_cap > 0) agg_radix_part_compact(c, &states, &first_row, &gkeys, &ng); + pr->states = states; pr->first_row = first_row; pr->keys = gkeys; pr->ng = ng; + continue; + oom: + ray_free_raw(ht); ray_free_raw(ht_salt); ray_free_raw(first_row); ray_free_raw(states); ray_free_raw(keyp); ray_free_raw(gid); ray_free_raw(gkeys); + for (uint32_t a = 0; a < n_aggs; a++) { ray_free_raw(gv[a]); ray_free_raw(gy[a]); } + ray_free_raw(gv); ray_free_raw(gy); + pr->oom = 1; return; + } +} + +/* Phase 2 of a fused context: agg_radix_group_fn over each partition's + * chunk runs in chunk order (the same records in the same order as the + * global layout). A copy rather than a shared body: one always-inline + * body over a run table (the global layout one run per partition) + * measured q16 1.3% slower on generation 0 (73.8 against 72.8 ms) and 3% + * slower on generation 2. The two must group the same records in the + * same order: scanrange/v2_radix_record_order compares their answers + * byte for byte. Under a top-N emit (cmp_cap) a finished partition is cut to + * its candidates, as agg_radix_group_fn cuts it. */ +static void agg_radix_group_fused_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_radix_ctx_t* c = (agg_radix_ctx_t*)vctx; + uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; + size_t key_bytes = (size_t)n_keys * 8; + for (int64_t pi = start; pi < end; pi++) { + uint32_t p = (uint32_t)pi; + agg_radix_part_t* pr = &c->parts[p]; + + /* Rows hashing to p: its contiguous slot range, in input order. */ + int64_t total = c->part_start[p + 1] - c->part_start[p]; + if (total == 0) continue; + + /* Open-addressing hash sized to next_pow2(2*total). */ + int64_t htcap = 16; + while (htcap < total * 2) htcap <<= 1; + uint64_t htmask = (uint64_t)htcap - 1; + int32_t* ht = ray_alloc_raw((size_t)htcap * sizeof(int32_t)); + uint8_t* ht_salt = ray_alloc_raw((size_t)htcap); /* parallel salt fingerprint per slot */ + /* Group-state arrays sized to the distinct-group count (grow-on- + * demand) instead of `total` rows. gid/gv/gy stay row-sized. */ + int64_t gcap = total < 256 ? total : 256; + if (gcap < 16) gcap = 16; + /* first_row is only populated when a row-dependent agg needs it. */ + int64_t* first_row = c->needs_row ? ray_alloc_raw((size_t)gcap * sizeof(int64_t)) : NULL; + char* states = ray_alloc_raw((size_t)gcap * c->block); + const int64_t** keyp = ray_alloc_raw((size_t)gcap * sizeof(int64_t*)); /* gid -> packed keys */ + uint32_t* gid = ray_alloc_raw((size_t)total * sizeof(uint32_t));/* row i -> local gid */ + /* Persist each group's packed keys (build order) so Phase 3 emits the + * key columns by sequential un-pack rather than scattered gather. */ + int64_t* gkeys = ray_alloc_raw((size_t)gcap * (size_t)(n_keys ? n_keys : 1) * sizeof(int64_t)); + if (!ht || !ht_salt || (c->needs_row && !first_row) || !states || !keyp || !gid || !gkeys) { + ray_free_raw(ht); ray_free_raw(ht_salt); ray_free_raw(first_row); ray_free_raw(states); ray_free_raw(keyp); ray_free_raw(gid); ray_free_raw(gkeys); + pr->oom = 1; return; + } + for (int64_t i = 0; i < htcap; i++) ht[i] = -1; + + /* Per-agg dense value buffers, gathered contiguously from the records. + * gv/gy are per-partition scratch (this worker only) — carved here, not + * the shared descriptor, so per-invocation allocation is correct. */ + char** gv = ray_calloc_raw((size_t)(n_aggs ? n_aggs : 1) * sizeof(char*)); + char** gy = ray_calloc_raw((size_t)(n_aggs ? n_aggs : 1) * sizeof(char*)); + if (!gv || !gy) { + ray_free_raw(gv); ray_free_raw(gy); + ray_free_raw(ht); ray_free_raw(ht_salt); ray_free_raw(first_row); ray_free_raw(states); ray_free_raw(keyp); ray_free_raw(gid); ray_free_raw(gkeys); + pr->oom = 1; return; + } + for (uint32_t a = 0; a < n_aggs; a++) { + if (c->val_data[a]) { + uint8_t ez = c->val_esz[a]; + gv[a] = ray_alloc_raw((size_t)total * (ez ? ez : 1)); + if (!gv[a]) goto oom; + } + if (c->val2_data[a]) { + uint8_t ez2 = c->val2_esz[a]; + gy[a] = ray_alloc_raw((size_t)total * (ez2 ? ez2 : 1)); + if (!gy[a]) goto oom; + } + } + + int64_t ng = 0, ri = 0; + /* The records of p: one run per chunk, in chunk order. */ + for (uint32_t seg = 0; seg < c->n_chunks; seg++) { + const uint32_t* rp = c->runs + ((size_t)p * c->n_chunks + seg) * 2; + const char* rec = c->pay + (size_t)((int64_t)seg * c->chunk_rows + rp[0]) * c->rec; + const int64_t run_ = rp[1]; + /* the runs lie in different chunks: fetch a few runs ahead */ + if (seg + AGG_RADIX_RUN_AHEAD < c->n_chunks) { + const uint32_t* np = rp + 2 * AGG_RADIX_RUN_AHEAD; + const char* nr = c->pay + (size_t)((int64_t)(seg + AGG_RADIX_RUN_AHEAD) * c->chunk_rows + np[0]) * c->rec; + __builtin_prefetch(nr); + __builtin_prefetch(nr + 64); + } + for (int64_t i = 0; i < run_; i++, rec += c->rec) { + const int64_t* keys = (const int64_t*)rec; + int64_t r = 0; + if (c->needs_row) memcpy(&r, rec + c->row_off, sizeof(r)); + /* Gather this row's agg values into the dense per-agg buffers + * (sequential record read → sequential dense write). */ + for (uint32_t a = 0; a < n_aggs; a++) { + if (gv[a]) { uint8_t ez = c->val_esz[a]; + memcpy(gv[a] + (size_t)ri * ez, rec + c->val_off[a], ez); } + if (gy[a]) { uint8_t ez2 = c->val2_esz[a]; + memcpy(gy[a] + (size_t)ri * ez2, rec + c->val2_off[a], ez2); } + } + /* Hash the contiguous packed keys (same FNV-1a as the scatter). + * The scatter consumed the LOW log2(n_parts) bits of this hash + * to pick the partition, so within this partition those bits + * are constant across every record — the slot index must come + * from the bits above them or the open-addressing table + * collapses to 2^(htbits - partbits) usable slots and probing + * degrades to O(ng^2) linear chains (ClickBench q17: 65% of + * the query inside this probe loop at 4096 partitions). */ + uint64_t h = 1469598103934665603ULL; + for (uint32_t k = 0; k < n_keys; k++) { h ^= (uint64_t)keys[k]; h *= 1099511628211ULL; } + h = agg_radix_fmix64(h); + uint64_t slot = (h >> c->part_bits) & htmask; + /* Salt = top 8 bits of the hash (independent of the low-bit slot + * index). Compared first on probe to skip ~255/256 full memcmps. */ + uint8_t salt = (uint8_t)(h >> 56); + int32_t gg; + for (;;) { + int32_t gp = ht[slot]; + if (gp < 0) { /* new group */ + if ((int64_t)ng >= gcap) { /* grow group-state arrays (sized to distinct groups, not rows) */ + int64_t ncap = gcap * 2; + /* Assign each realloc result back before the next so + * a mid-sequence failure leaves only valid pointers + * for the oom: cleanup (realloc frees the old block + * on success, so the pre-realloc pointer must never + * survive into cleanup). */ + void* ns = ray_realloc_raw(states, (size_t)ncap * c->block); + if (!ns) goto oom; + states = ns; + void* nk = ray_realloc_raw((void*)keyp, (size_t)ncap * sizeof(int64_t*)); + if (!nk) goto oom; + keyp = nk; + void* ngk = ray_realloc_raw(gkeys, (size_t)ncap * (size_t)(n_keys ? n_keys : 1) * sizeof(int64_t)); + if (!ngk) goto oom; + gkeys = ngk; + if (c->needs_row) { + void* nf = ray_realloc_raw(first_row, (size_t)ncap * sizeof(int64_t)); + if (!nf) goto oom; + first_row = nf; + } + gcap = ncap; + } + gg = (int32_t)ng; + ht[slot] = gg; + ht_salt[slot] = salt; + if (c->needs_row) first_row[gg] = r; + keyp[gg] = keys; + for (uint32_t k = 0; k < n_keys; k++) + gkeys[(size_t)gg * n_keys + k] = keys[k]; + for (uint32_t a = 0; a < n_aggs; a++) + c->vts[a]->init(states + (size_t)gg * c->block + c->off[a]); + ng++; + break; + } + if (ht_salt[slot] == salt && memcmp(keys, keyp[gp], key_bytes) == 0) { + gg = gp; /* salt-gated key compare */ + if (c->needs_row && r < first_row[gg]) first_row[gg] = r; /* MIN */ + break; + } + slot = (slot + 1) & htmask; + } + gid[ri] = (uint32_t)gg; + ri++; + } + } + ray_free_raw(ht); ray_free_raw(ht_salt); ray_free_raw(keyp); + + /* Batch-accumulate each agg over the partition's dense value buffers. */ + for (uint32_t a = 0; a < n_aggs; a++) { + if (c->vts[a]->update_batch2) { /* binary agg (pearson) */ + ray_valid_t vx = { gv[a], c->val_types[a], c->val_hasnull[a] }; + ray_valid_t vy = { gy[a], c->val2_types[a], c->val2_hasnull[a] }; + c->vts[a]->update_batch2(states + c->off[a], c->block, gid, + gv[a], gy[a], &vx, &vy, total, NULL); + } else if (c->val_data[a]) { /* unary agg over a column */ + ray_valid_t valid = { gv[a], c->val_types[a], c->val_hasnull[a] }; + c->vts[a]->update_batch(states + c->off[a], c->block, gid, gv[a], &valid, total, NULL); + } else { /* COUNT (no value column) */ + ray_valid_t valid = { NULL, c->val_types[a], false }; + c->vts[a]->update_batch(states + c->off[a], c->block, gid, NULL, &valid, total, NULL); + } + } + + for (uint32_t a = 0; a < n_aggs; a++) { ray_free_raw(gv[a]); ray_free_raw(gy[a]); } + ray_free_raw(gv); ray_free_raw(gy); + ray_free_raw(gid); + if (c->cmp_cap > 0) agg_radix_part_compact(c, &states, &first_row, &gkeys, &ng); pr->states = states; pr->first_row = first_row; pr->keys = gkeys; pr->ng = ng; continue; oom: @@ -4751,6 +8103,293 @@ static ray_t* agg_parts_emit(ray_op_ext_t* ext, agg_desc_t* d, return result; } +/* Survivors per partition for a top-N emit (agg_radix_part_compact), or 0 + * when the emit keeps every group or selects with semantics the reduction + * does not cover: a bounded first-seen emit, a minimum-count bound (it is + * applied before the tie cut, so the kept groups are no longer a prefix of + * the rank order), an aggregate without a scalar order, accumulators with a + * destroy hook, or a take so large that the survivors are no small share of + * the input. */ +static int64_t agg_radix_cmp_cap(const ray_group_emit_filter_t* efp, int64_t group_limit, + const agg_vtable_t** vts, uint32_t n_aggs, + uint32_t n_parts, int64_t n_in) { + if (ray_agg_radix_wave_bytes < 0 || + !efp || group_limit != 0 || efp->top_count_take <= 0 || + efp->min_count_exclusive > 0 || efp->agg_index >= n_aggs) + return 0; + switch (vts[efp->agg_index]->out_type) { + case RAY_F64: case RAY_F32: case RAY_I64: case RAY_TIMESTAMP: + case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: + case RAY_U8: case RAY_BOOL: break; + default: return 0; + } + for (uint32_t a = 0; a < n_aggs; a++) + if (vts[a]->destroy) return 0; + if (efp->top_count_take > INT32_MAX) return 0; + int64_t cap = 2 * efp->top_count_take; + if ((double)cap * n_parts > (double)n_in / 2) return 0; + return cap; +} + +/* Bound on the waves a heap-derived plan may cut: every wave re-reads the + * partition ids and the input rows, so past this many the passes cost more + * than the memory they save. */ +#define AGG_RADIX_MAX_WAVES 64 + +/* Cut the partitions into runs of consecutive partitions holding at most + * `target` records each (a partition larger than that is a run of its own). + * Returns the run count; cut[w] .. cut[w + 1] are run w's partitions and + * *max_wave its largest record count. */ +static uint32_t agg_radix_wave_cut(const int64_t* part_start, uint32_t n_parts, + int64_t target, uint32_t* cut, int64_t* max_wave) { + uint32_t k = 0, lo = 0; + int64_t mx = 0; + while (lo < n_parts) { + uint32_t hi = lo + 1; + while (hi < n_parts && part_start[hi + 1] - part_start[lo] <= target) hi++; + cut[k++] = lo; + if (part_start[hi] - part_start[lo] > mx) mx = part_start[hi] - part_start[lo]; + lo = hi; + } + cut[k] = n_parts; + *max_wave = mx; + return k; +} + +/* Split the payload into waves of whole partitions when it would not fit the + * memory left under the heap's anonymous watermark. Only a reduced (top-N) + * run benefits: its finished partitions shrink to their candidates, so the + * largest wave's payload is what stays resident, not the whole input's. + * + * The room is what the watermark leaves above the committed memory, less + * `reserve`: the candidates' bound, the tables of the partitions in flight + * (one per worker, each a few bytes per row of the largest partition) and + * the spill buffers when the later waves may go to a file. The payload of + * one wave gets the rest. Waves are cut greedily on the exact partition + * sizes; a heap-derived plan never cuts more than AGG_RADIX_MAX_WAVES (the + * target doubles until it fits — a greedy cut can need up to twice the + * waves the record count suggests). The test knob fixes the target and + * cuts as many waves as it asks for. One wave = the one-pass scatter. */ +static uint32_t agg_radix_wave_plan(const int64_t* part_start, uint32_t n_parts, + size_t rec, int64_t cmp_cap, int64_t reserve, + uint32_t* cut, int64_t* max_wave) { + int64_t total = part_start[n_parts]; + cut[0] = 0; cut[1] = n_parts; + *max_wave = total; + if (cmp_cap <= 0 || total <= 0) return 1; + if (ray_agg_radix_wave_bytes > 0) { + int64_t target = ray_agg_radix_wave_bytes / (int64_t)rec; + if (target < 1) target = 1; + if (total <= target) return 1; + return agg_radix_wave_cut(part_start, n_parts, target, cut, max_wave); + } + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return 1; /* unknown RAM: one pass, as before */ + int64_t room = wm - ray_heap_anon_committed() - reserve; + int64_t target = room > 0 ? room / (int64_t)rec : 0; + if (total <= target) return 1; + int64_t least = (total + AGG_RADIX_MAX_WAVES - 1) / AGG_RADIX_MAX_WAVES; + if (target < least) target = least; + for (;;) { + uint32_t k = agg_radix_wave_cut(part_start, n_parts, target, cut, max_wave); + if (k <= AGG_RADIX_MAX_WAVES) return k; + target *= 2; + } +} + +/* Before the count pass: whether agg_radix_wave_plan may split a top-N run + * of n_in records into waves — the test knob's bound is below the payload, + * or the room under the heap's anonymous watermark is, less the plan's + * reserve estimated with partitions of even size (the plan has the exact + * sizes). */ +static bool agg_radix_may_wave(int64_t n_in, uint32_t n_parts, size_t rec, size_t block, + uint32_t n_keys, uint32_t nw, int64_t cmp_cap) { + if (cmp_cap <= 0 || n_in <= 0) return false; + if (ray_agg_radix_wave_bytes > 0) { + int64_t target = ray_agg_radix_wave_bytes / (int64_t)rec; + return n_in > (target < 1 ? 1 : target); + } + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return false; + size_t kb = 8 * (size_t)(n_keys ? n_keys : 1); + double per_row = (double)(20 + 4 + rec + 2 * (block + kb + 24)); + double reserve = (double)cmp_cap * n_parts * (double)(block + kb + 8) + + (double)nw * ((double)n_in / n_parts) * per_row; + double room = (double)(wm - ray_heap_anon_committed()) - reserve; + return (double)n_in * (double)rec > room; +} + +/* Whether a radix dispatch must not be followed by the next: the pool was + * cancelled, or (a staged context) a range read failed. */ +static bool agg_radix_stopped(const agg_radix_ctx_t* c, ray_pool_t* pool) { + return pool_cancelled(pool) || (c->rr->staged && ray_scan_failed(c->rr->fail)); +} + +/* Count pass + prefix again: the partition ids and every chunk's write + * cursors back to where the first scatter found them (part_start comes out + * the same). A spilled run whose file failed re-scans its remaining waves + * from here. A staged context counts through its key sources (count_rr); + * a range error is noted in its failure envelope. */ +static void agg_radix_recount(agg_radix_ctx_t* c, ray_pool_t* pool) { + ray_pool_dispatch_n(pool, c->rr->staged ? agg_radix_count_staged_fn : agg_radix_count_fn, + c, c->n_chunks); + uint32_t n_bands = (c->n_parts + AGG_RADIX_PREFIX_BAND - 1) / AGG_RADIX_PREFIX_BAND; + if (n_bands > 1 && (uint64_t)c->n_chunks * c->n_parts >= ((uint64_t)1 << 16)) + ray_pool_dispatch_n(pool, agg_radix_prefix_fn, c, n_bands); + else + agg_radix_prefix_fn(c, 0, 0, n_bands); + for (uint32_t p = 0; p < c->n_parts; p++) c->part_start[p + 1] += c->part_start[p]; +} + +/* Bytes of a column object that a re-scan would read from its file again: + * a mapped plain column's payload, a generation-2 column's encoded file + * (none for an in-memory stand-in), a parted column's segments; 0 for an + * in-memory column. Never decodes. */ +static int64_t agg_col_file_bytes(const ray_t* col) { + if (!col || RAY_IS_ERR(col)) return 0; + if (col->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of((ray_t*)col); + if (!e) return 0; + if (e->kind == RAY_ENCCOL_SINGLE) return e->synthetic ? 0 : (int64_t)e->size; + return agg_col_file_bytes(e->wrapper); + } + if (RAY_IS_PARTED(col->type)) { + int64_t b = 0; + ray_t* const* segs = (ray_t* const*)ray_data((ray_t*)col); + for (int64_t s = 0; s < col->len; s++) b += agg_col_file_bytes(segs[s]); + return b; + } + if (!ray_is_vec(col)) return 0; + const ray_t* base = (col->attrs & RAY_ATTR_SLICE) && col->slice_parent ? col->slice_parent : col; + return base->mmod == 1 ? col->len * (int64_t)col_esz(col) : 0; +} + +/* Re-scan or spill the later waves? A re-scan reads the input columns once + * more per extra wave — from the page cache when they stay there, from their + * files when they do not; a spill writes the later waves' records (with + * their 4-byte slots) once and reads them back once. With in-memory input + * a re-scan moves no bytes to or from a device, so it always wins; with + * file-backed input the cheaper of the two worst cases is taken, which caps + * the re-scanned waves at about 2 * payload / input (four to five for a + * near-unique two-key count). */ +static bool agg_radix_spill_wanted(int64_t file_bytes, uint32_t n_waves, + int64_t spilled_recs, size_t rec, int64_t max_wave) { + if (!AGG_RADIX_FILE_SPILL || n_waves <= 1 || max_wave > (int64_t)UINT32_MAX || + ray_agg_radix_spill == 1) + return false; + if (ray_agg_radix_spill >= 2) return true; + double spill = 2.0 * (double)spilled_recs * (double)(rec + sizeof(uint32_t)); + double rescan = (double)(n_waves - 1) * (double)file_bytes; + return file_bytes > 0 && spill < rescan; +} + +/* Run a split radix with its later waves spilled: one scatter pass writes + * wave 0 into the payload and the rest to the file, wave 0 is reduced, then + * each later wave is read back into the payload and reduced. Returns the + * first wave still to run by re-scan: n_waves when every wave was served, + * 0 when the spill could not be set up (nothing scattered yet), or the wave + * at which the file failed (the cursors are restored by agg_radix_recount). + * `buf_bytes` is the share of the plan's reserve for the write and read-back + * buffers: a buffer is never smaller than AGG_RADIX_SPILL_MIN_BUF (smaller + * writes would be small random I/O), so when the workers' buffers of that + * size for every wave exceed it, nothing is scattered and the caller + * re-scans (returns 0). */ +#define AGG_RADIX_SPILL_MIN_BUF ((int64_t)64 << 10) +static uint32_t agg_radix_spill_run(agg_radix_ctx_t* c, ray_pool_t* pool, uint32_t nw, + const uint32_t* cut, uint32_t n_waves, int64_t buf_bytes, + bool* cancelled, int* oom, uint64_t* bytes) { + uint32_t n_parts = c->n_parts; + size_t ent = c->rec + sizeof(uint32_t); + int64_t per = buf_bytes / ((int64_t)nw * (n_waves + 1)); + if (per > ((int64_t)1 << 20)) per = (int64_t)1 << 20; + if (per < AGG_RADIX_SPILL_MIN_BUF) per = AGG_RADIX_SPILL_MIN_BUF; + uint32_t bcap = (uint32_t)(per / (int64_t)ent); + if (bcap < 1) bcap = 1; + size_t stride = ((size_t)bcap * ent + 7) & ~(size_t)7; /* records stay 8-aligned */ + if ((double)nw * n_waves * (double)stride > (double)buf_bytes) return 0; + route_stats.radix_spill_buf = (uint64_t)nw * n_waves * stride; + int64_t spilled = c->part_start[n_parts] - c->part_start[cut[1]]; + agg_radix_spill_t sp = { .fd = -1, .n_waves = n_waves, .bcap = bcap, .rec = c->rec }; + atomic_init(&sp.n_blks, 0); atomic_init(&sp.tail, 0); atomic_init(&sp.err, 0); + sp.blk_cap = spilled / bcap + (int64_t)nw * n_waves + 1; + uint16_t* wave_of = ray_alloc_raw((size_t)n_parts * sizeof(uint16_t)); + int64_t* wave_base = ray_alloc_raw((size_t)n_waves * sizeof(int64_t)); + sp.bufs = ray_calloc_raw((size_t)nw * n_waves * sizeof(agg_radix_sbuf_t)); + sp.rstride = stride; + char* bufmem = ray_alloc_raw((size_t)nw * (n_waves - 1) * stride); + sp.rbuf = ray_alloc_raw((size_t)nw * stride); + sp.blks = ray_alloc_raw((size_t)sp.blk_cap * sizeof(agg_radix_blk_t)); + int64_t* wave_blks = ray_alloc_raw((size_t)sp.blk_cap * sizeof(int64_t)); + sp.fd = (wave_of && wave_base && sp.bufs && bufmem && sp.rbuf && sp.blks && wave_blks) + ? agg_radix_spill_open() : -1; + if (sp.fd < 0) { + ray_free_raw(wave_of); ray_free_raw(wave_base); ray_free_raw(sp.bufs); + ray_free_raw(bufmem); ray_free_raw(sp.rbuf); ray_free_raw(sp.blks); ray_free_raw(wave_blks); + return 0; + } + for (uint32_t w = 0; w < n_waves; w++) { + wave_base[w] = c->part_start[cut[w]]; + for (uint32_t p = cut[w]; p < cut[w + 1]; p++) wave_of[p] = (uint16_t)w; + } + for (uint32_t t = 0; t < nw; t++) + for (uint32_t w = 1; w < n_waves; w++) + sp.bufs[(size_t)t * n_waves + w].buf = + bufmem + ((size_t)t * (n_waves - 1) + (w - 1)) * stride; + sp.wave_base = wave_base; + sp.wave_blks = wave_blks; + // cppcheck-suppress autoVariables // sp outlives every dispatch that reads it; c->spill is reset before return + c->spill = &sp; c->wave_of = wave_of; + + uint32_t next = n_waves; + ray_pool_dispatch_n(pool, c->rr->staged ? agg_radix_spill_scatter_staged_fn + : agg_radix_spill_scatter_fn, c, c->n_chunks); + *cancelled = agg_radix_stopped(c, pool); + for (uint32_t t = 0; t < nw && !*cancelled; t++) + for (uint32_t w = 1; w < n_waves; w++) + agg_radix_spill_flush(&sp, &sp.bufs[(size_t)t * n_waves + w], w); + ray_free_raw(bufmem); bufmem = NULL; + ray_profile_tick("radix: spilled later waves"); + for (uint32_t w = 0; w < n_waves && !*cancelled && !*oom; w++) { + uint32_t lo = cut[w], hi = cut[w + 1]; + if (w > 0) { + if (atomic_load_explicit(&sp.err, memory_order_relaxed)) { + agg_radix_recount(c, pool); /* the file failed: re-scan from here */ + *cancelled = agg_radix_stopped(c, pool); + next = w; + break; + } + int64_t nb = 0, total = atomic_load_explicit(&sp.n_blks, memory_order_relaxed); + for (int64_t i = 0; i < total; i++) + if (sp.blks[i].wave == w) wave_blks[nb++] = i; + if (nb > 0) ray_pool_dispatch_n(pool, agg_radix_readback_fn, c, (uint32_t)nb); + *cancelled = agg_radix_stopped(c, pool); + if (*cancelled) break; + if (atomic_load_explicit(&sp.err, memory_order_relaxed)) { + agg_radix_recount(c, pool); + *cancelled = agg_radix_stopped(c, pool); + next = w; + break; + } + } + if (c->part_start[hi] == c->part_start[lo]) continue; + c->part_lo = lo; + c->pay_base = c->part_start[lo]; + ray_pool_dispatch_n(pool, agg_radix_group_fn, c, hi - lo); + *cancelled = agg_radix_stopped(c, pool); + for (uint32_t p = lo; p < hi && !*cancelled; p++) + if (c->parts[p].oom) { *oom = 1; break; } + ray_profile_tick("radix: wave reduced"); + } + *bytes = (uint64_t)atomic_load_explicit(&sp.tail, memory_order_relaxed); +#if AGG_RADIX_FILE_SPILL + close(sp.fd); +#endif + c->spill = NULL; c->wave_of = NULL; c->part_lo = 0; c->pay_base = 0; + ray_free_raw(wave_of); ray_free_raw(wave_base); ray_free_raw(sp.bufs); + ray_free_raw(sp.rbuf); ray_free_raw(sp.blks); ray_free_raw(wave_blks); + return next; +} + static ray_t* exec_group_v2_parallel_radix( ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t nrows, ray_t** key_cols, int64_t* key_syms, @@ -4763,11 +8402,14 @@ static ray_t* exec_group_v2_parallel_radix( uint32_t nw = ray_pool_total_workers(pool); agg_desc_t d; - if (!agg_desc_init(&d, g, ext, tbl, key_cols)) return ray_error("oom", NULL); + ray_t* derr = NULL; + if (!agg_desc_init(&d, g, ext, tbl, key_cols, &derr)) return derr ? derr : ray_error("oom", NULL); const void** key_data = d.key_data; - const void** val_data = d.val_data; const int8_t* val_types = d.val_types; + /* Phase 1 reads the inputs through views; the layout and phase 2 test + * their presence on the identities (staged or plain). */ + const void** val_data = d.val_id; const int8_t* val_types = d.val_types; const bool* val_hasnull = d.val_hasnull; const uint8_t* val_esz = d.val_esz; - const void** val2_data = d.val2_data; const int8_t* val2_types = d.val2_types; + const void** val2_data = d.val2_id; const int8_t* val2_types = d.val2_types; const bool* val2_hasnull = d.val2_hasnull; const uint8_t* val2_esz = d.val2_esz; /* Every group records its earliest source row so emitted order does not @@ -4779,16 +8421,66 @@ static ray_t* exec_group_v2_parallel_radix( * only phases 1-2 read them, freed once phase 2 joins. */ ray_t* off_hdr; size_t* val_off = (size_t*)scratch_calloc(&off_hdr, - 2u * (size_t)(n_aggs ? n_aggs : 1) * sizeof(size_t)); + 2u * (size_t)(n_aggs ? n_aggs : 1) * sizeof(size_t) + + ((size_t)n_keys + 2u * n_aggs) * sizeof(agg_radix_cf_t)); if (!val_off) { agg_desc_free(&d); return ray_error("oom", NULL); } size_t* val2_off = val_off + n_aggs; + agg_radix_cf_t* cf = (agg_radix_cf_t*)(val_off + 2u * (n_aggs ? n_aggs : 1)); size_t rec_cur = (size_t)n_keys * 8; for (uint32_t a = 0; a < n_aggs; a++) { if (val_data[a]) { val_off[a] = rec_cur; rec_cur += val_esz[a]; } if (val2_data[a]) { val2_off[a] = rec_cur; rec_cur += val2_esz[a]; } } - size_t row_off = rec_cur; if (needs_row) rec_cur += 8; - size_t rec = (rec_cur + 7u) & ~(size_t)7u; /* 8-align records */ + size_t row_off = rec_cur; if (needs_row) rec_cur += 8; + size_t rec = (rec_cur + 7u) & ~(size_t)7u; /* 8-align records */ + /* The compact staging of a fused pass (not sel mode: the scatter reads + * the plain columns at the chunk's own rows): the record's fields in + * the record's order (the keys, then each aggregate's x and y, as + * val_off / val2_off lay them out), a staged source's in the staged + * row, a plain one read in place. Field j walks source i: the keys + * are sources 0 .. n_keys, aggregate a's x n_keys + a, its y + * n_keys + n_aggs + a. */ + bool compact = d.staged && !sel; + size_t srec = 0; + uint32_t n_cf = 0; + for (uint32_t j = 0; compact && j < n_keys + 2u * n_aggs; j++) { + bool key = j < n_keys; + uint32_t a = key ? 0 : (j - n_keys) / 2; + bool y = !key && ((j - n_keys) & 1); + uint32_t i = key ? j : y ? n_keys + n_aggs + a : n_keys + a; + if (!key && !(y ? val2_data[a] : val_data[a])) continue; /* no input (COUNT) */ + agg_radix_cf_t* f = &cf[n_cf++]; + memset(f, 0, sizeof *f); + f->agg = a; + f->y = y; + f->off = (uint32_t)(key ? (size_t)i * 8 : y ? val2_off[a] : val_off[a]); + f->w = key ? 8 : y ? val2_esz[a] : val_esz[a]; + if (d.rr.srcs[i]) { + f->kind = AGG_CF_STAGED; + f->soff = (uint32_t)srec; + srec += f->w; + continue; + } + f->plain = d.rr.plain[i]; + f->esz = d.rr.esz[i]; + if (!f->plain) { compact = false; break; } + if (!key) { f->kind = AGG_CF_VAL; continue; } + switch (d.rr.key_types[i]) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: f->kind = AGG_CF_KEY_I64; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: f->kind = AGG_CF_KEY_I32; break; + case RAY_I16: f->kind = AGG_CF_KEY_I16; break; + case RAY_U8: case RAY_BOOL: f->kind = AGG_CF_KEY_U8; break; + case RAY_SYM: + switch (d.rr.key_attrs[i] & RAY_SYM_W_MASK) { + case RAY_SYM_W8: f->kind = AGG_CF_KEY_U8; break; + case RAY_SYM_W16: f->kind = AGG_CF_KEY_U16; break; + case RAY_SYM_W32: f->kind = AGG_CF_KEY_U32; break; + default: f->kind = AGG_CF_KEY_I64; break; + } + break; + default: compact = false; break; /* the gate admits only the above */ + } + } int64_t n_in = sel ? n_sel : nrows; if (n_in < 0) n_in = 0; @@ -4813,18 +8505,82 @@ static ray_t* exec_group_v2_parallel_radix( if (want < 1) want = 1; int64_t chunk_rows = (int64_t)(((uint64_t)n_in + want - 1) / want); if (chunk_rows < 1) chunk_rows = 1; + /* Sources that decode (generation 2) are read once: the fused pass + * stages each chunk in its task (agg_radix_fused_fn). Its chunks are + * small, so the staged records stay in the task's cache while they are + * scattered: AGG_RADIX_RUN_ROWS records per partition on average (a + * partition's runs, one per chunk, stay worth reading in phase 2), at + * least one block. The workers' staging buffers must fit the + * last-level cache together (the table stack's bound), and the chunks + * the count matrix; otherwise the two passes read the sources twice + * (staging that spills costs more than the second decode). */ + bool fused = false; + if (d.staged) { + for (uint32_t i = 0; i < d.rr.n_src && !fused; i++) + fused = d.rr.srcs[i] && ray_col_src_encoded(d.rr.srcs[i]); + int64_t want_rows = (int64_t)n_parts * AGG_RADIX_RUN_ROWS; + if (want_rows < RAY_COL_BLOCK_ROWS) want_rows = RAY_COL_BLOCK_ROWS; + uint64_t llc_bytes = ray_cache_llc_bytes(); + double cache_budget = (llc_bytes ? (double)llc_bytes : 32.0 * 1048576.0) * 0.75; + /* a worker's staging: a chunk's staged rows (compact: the staged + * sources' fields, srec bytes; else whole records, rec) and + * partition ids (2 bytes a row), and the partitions' write cursors */ + double per_worker = cache_budget / (double)nw - (double)n_parts * sizeof(uint32_t); + double staged_row = (double)(compact ? srec : rec) + sizeof(uint16_t); + int64_t cap = per_worker > 0 ? (int64_t)(per_worker / staged_row) : 0; + /* Staging over its share keeps the fused pass on smaller chunks: + * the largest block multiple under the cap, while that still holds + * half the records a run wants (4 a partition on average; q17's + * two keys: 3 of 4 blocks, decoded once). Below half the short + * runs cost more than the second decode (TS2m: 40-byte records + * over 8192 partitions, a quarter). */ + if (fused) { + int64_t target = chunk_rows > want_rows ? want_rows : chunk_rows; + if (target > cap) { + int64_t capped = cap / RAY_COL_BLOCK_ROWS * RAY_COL_BLOCK_ROWS; + if (capped >= RAY_COL_BLOCK_ROWS && 2 * capped >= want_rows) target = capped; + else fused = false; + } + if (fused) chunk_rows = target; + } + /* the count matrix and the runs (twice its size) live together + * until the runs are written */ + uint64_t nch = ((uint64_t)n_in + (uint64_t)chunk_rows - 1) / (uint64_t)chunk_rows; + if (fused && nch * n_parts * 3 * sizeof(uint32_t) > AGG_RADIX_COUNT_BUDGET) { + fused = false; + chunk_rows = (int64_t)(((uint64_t)n_in + want - 1) / want); /* the two passes' chunks */ + if (chunk_rows < 1) chunk_rows = 1; + } + } + /* A top-N emit keeps only its partitions' candidates (cmp_cap). When + * the whole payload may not fit the wave bound (agg_radix_may_wave), + * the two passes run instead of the fused pass: their partition-major + * payload splits into waves of whole partitions, while the fused pass's + * chunk-major payload holds every record at once. */ + int64_t cmp_cap = needs_row + ? agg_radix_cmp_cap(efp, group_limit, vts, n_aggs, n_parts, n_in) : 0; + if (fused && agg_radix_may_wave(n_in, n_parts, rec, block, n_keys, nw, cmp_cap)) { + fused = false; + chunk_rows = (int64_t)(((uint64_t)n_in + want - 1) / want); /* the two passes' chunks */ + if (chunk_rows < 1) chunk_rows = 1; + } uint32_t n_chunks = (uint32_t)((n_in + chunk_rows - 1) / chunk_rows); /* O(1) allocations whatever the worker count: the count matrix and the - * partition ids live until pass 2 ends, the payload until phase 2 ends. */ + * partition ids live until the last scatter pass ends (fused: no ids; + * the count matrix until its runs are transposed, the runs until phase + * 2 ends), the payload until phase 2 ends. The fused payload holds the + * whole input; the two passes size theirs once the partition sizes are + * known: the whole input, or the largest wave. */ agg_radix_part_t* parts = ray_calloc_raw((size_t)n_parts * sizeof(agg_radix_part_t)); uint32_t* cnt = ray_alloc_raw((size_t)(n_chunks ? n_chunks : 1) * n_parts * sizeof(uint32_t)); int64_t* part_start = ray_alloc_raw(((size_t)n_parts + 1) * sizeof(int64_t)); - uint16_t* pid = ray_alloc_raw((size_t)(n_in ? n_in : 1) * sizeof(uint16_t)); - char* pay = ray_alloc_raw((size_t)(n_in ? n_in : 1) * rec); - if (!parts || !cnt || !part_start || !pid || !pay) { + uint16_t* pid = fused ? NULL : ray_alloc_raw((size_t)(n_in ? n_in : 1) * sizeof(uint16_t)); + uint32_t* wave_cut = fused ? NULL : ray_alloc_raw(((size_t)n_parts + 1) * sizeof(uint32_t)); + char* pay = fused ? ray_alloc_raw((size_t)(n_in ? n_in : 1) * rec) : NULL; + if (!parts || !cnt || !part_start || (fused ? !pay : (!pid || !wave_cut))) { ray_free_raw(parts); ray_free_raw(cnt); ray_free_raw(part_start); - ray_free_raw(pid); ray_free_raw(pay); + ray_free_raw(pid); ray_free_raw(wave_cut); ray_free_raw(pay); scratch_free(off_hdr); agg_desc_free(&d); return exec_group_v2_parallel_smallhash(g, op, tbl, nrows, key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel); @@ -4844,15 +8600,98 @@ static ray_t* exec_group_v2_parallel_radix( .rec = rec, .row_off = row_off, .needs_row = needs_row, .sel = sel, .sel_prefix = sel_prefix, .val_off = val_off, .val2_off = val2_off, + .wave_lo = 0, .wave_hi = n_parts, .part_lo = 0, .pay_base = 0, + .cmp_cap = cmp_cap, + .cmp_vt = cmp_cap ? vts[efp->agg_index] : NULL, + .cmp_off = cmp_cap ? off[efp->agg_index] : 0, + .cmp_param = cmp_cap && ext->agg_k ? ext->agg_k[efp->agg_index] : 0, + .cmp_desc = cmp_cap ? efp->desc : 0, + .rr = &d.rr, .whole = &d.whole, + .compact = fused && compact, .srec = srec, .n_cf = n_cf, .cf = cf, }; + route_stats.radix_phase1 = !fused ? AGG_RADIX_P1_TWO_PASS + : ctx.compact ? AGG_RADIX_P1_FUSED_COMPACT : AGG_RADIX_P1_FUSED_RECORDS; atomic_init(&ctx.part_overflow, 0); + atomic_init(&ctx.cmp_parts, 0); + agg_desc_advise(&d, nrows); + /* Pass 1 of the two passes reads the keys alone: an input is read once + * by each scatter. */ + agg_rr_t count_rr = d.rr; + ray_col_src_t** count_srcs = NULL; + ctx.count_rr = &d.rr; + if (d.staged && !fused) { + count_srcs = ray_alloc_raw((size_t)(d.rr.n_src ? d.rr.n_src : 1) * sizeof(*count_srcs)); + if (count_srcs) { + for (uint32_t i = 0; i < d.rr.n_src; i++) count_srcs[i] = i < n_keys ? d.rr.srcs[i] : NULL; + count_rr.srcs = count_srcs; + ctx.count_rr = &count_rr; + } + } + + if (fused) { + /* One pass: each chunk counted and scattered inside its own record + * range, then the partition totals. */ + uint32_t n_bands = (n_parts + AGG_RADIX_PREFIX_BAND - 1) / AGG_RADIX_PREFIX_BAND; + route_stats.radix_waves = 1; + ctx.runs = ray_alloc_raw((size_t)n_chunks * n_parts * 2 * sizeof(uint32_t)); + if (!ctx.runs) { + ray_free_raw(parts); ray_free_raw(cnt); ray_free_raw(part_start); ray_free_raw(pay); + scratch_free(off_hdr); agg_desc_free(&d); + return exec_group_v2_parallel_smallhash(g, op, tbl, nrows, + key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel); + } + ctx.fused_tasks = nw * AGG_RADIX_CHUNKS_PER_WORKER; + if (ctx.fused_tasks > n_chunks) ctx.fused_tasks = n_chunks; + if (ctx.fused_tasks < 1) ctx.fused_tasks = 1; + ray_pool_dispatch_n(pool, agg_radix_fused_fn, &ctx, ctx.fused_tasks); + ray_t* ferr = ray_scan_fail_finish(&d.fail, pool); + bool cancelled = pool_cancelled(pool) || ferr; + if (!cancelled) { + if (n_bands > 1 && (uint64_t)n_chunks * n_parts >= ((uint64_t)1 << 16)) + ray_pool_dispatch_n(pool, agg_radix_fused_totals_fn, &ctx, n_bands); + else + agg_radix_fused_totals_fn(&ctx, 0, 0, n_bands); + cancelled = pool_cancelled(pool); + } + ray_free_raw(cnt); ctx.cnt = cnt = NULL; /* phase 2 reads the runs */ + int oom = atomic_load_explicit(&ctx.part_overflow, memory_order_relaxed); + if (!cancelled && !oom) + for (uint32_t p = 0; p < n_parts; p++) part_start[p + 1] += part_start[p]; + ray_profile_tick("radix: scattered rows"); + if (!cancelled && !oom) + ray_pool_dispatch_n(pool, agg_radix_group_fused_fn, &ctx, n_parts); + if (!cancelled && !oom) { + cancelled = pool_cancelled(pool); + for (uint32_t p = 0; p < n_parts; p++) + if (parts[p].oom) { oom = 1; break; } + } + route_stats.radix_compacted = + (uint64_t)atomic_load_explicit(&ctx.cmp_parts, memory_order_relaxed); + ray_profile_tick("radix: reduced partitions"); + scratch_free(off_hdr); + ray_free_raw(ctx.runs); ctx.runs = NULL; + ray_free_raw(pay); ctx.pay = NULL; + ray_free_raw(part_start); ctx.part_start = NULL; + if (cancelled || oom) { + agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); + ray_free_raw(parts); + agg_desc_free(&d); + if (ferr) return ferr; + if (cancelled) return ray_error("cancel", NULL); + return exec_group_v2_parallel_smallhash(g, op, tbl, nrows, + key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel); + } + return agg_parts_emit(ext, &d, parts, n_parts, pool, nw, key_cols, key_syms, + vts, off, block, sel ? n_sel : nrows, group_limit, efp); + } /* Phase 1, pass 1: per-(chunk, partition) counts. Sel mode chunks the * selected-row space [0,n_sel); each chunk decodes its selected rows to * ORIGINAL indices. A cancelled dispatch skips chunks and leaves their * count rows and ids unset, so nothing past it may run. */ - ray_pool_dispatch_n(pool, agg_radix_count_fn, &ctx, n_chunks); - bool cancelled = pool_cancelled(pool); + ray_pool_dispatch_n(pool, ctx.rr->staged ? agg_radix_count_staged_fn : agg_radix_count_fn, &ctx, n_chunks); + ray_t* ferr = d.staged ? ray_scan_fail_finish(&d.fail, pool) : NULL; + bool cancelled = pool_cancelled(pool) || ferr; if (!cancelled) { uint32_t n_bands = (n_parts + AGG_RADIX_PREFIX_BAND - 1) / AGG_RADIX_PREFIX_BAND; if (n_bands > 1 && (uint64_t)n_chunks * n_parts >= ((uint64_t)1 << 16)) @@ -4862,24 +8701,139 @@ static ray_t* exec_group_v2_parallel_radix( cancelled = pool_cancelled(pool); } int oom = atomic_load_explicit(&ctx.part_overflow, memory_order_relaxed); + uint32_t n_waves = 1; + bool no_pay = false; + int64_t file_bytes = 0, buf_bytes = 0; + bool spill_chosen = false; if (!cancelled && !oom) { for (uint32_t p = 0; p < n_parts; p++) part_start[p + 1] += part_start[p]; - /* Pass 2: every record to its exact slot. */ - ray_pool_dispatch_n(pool, agg_radix_scatter_fn, &ctx, n_chunks); - cancelled = pool_cancelled(pool); + int64_t max_wave = n_in; + /* Held beside one wave's payload: the candidates, the tables of the + * partitions in flight (one per worker; per row of the largest + * partition its hash slots, gid and value columns, and per group + * — at most a row each, doubling capacity — its state, keys, key + * pointer, first row and the reduction's value) and, with + * file-backed input, the spill buffers. */ + int64_t max_part = 0; + for (uint32_t p = 0; p < n_parts; p++) + if (part_start[p + 1] - part_start[p] > max_part) + max_part = part_start[p + 1] - part_start[p]; + size_t kb = 8 * (size_t)(n_keys ? n_keys : 1); + int64_t per_row = (int64_t)(20 + 4 + rec + 2 * (block + kb + 24)); + int64_t reserve = cmp_cap * (int64_t)n_parts * (int64_t)(block + kb + 8) + + (int64_t)nw * max_part * per_row; + /* The bytes a re-scan reads again: each key's and input's object as + * the scan reads it (a staged source's bound object, else the plain + * column read in place; an input read from an in-memory + * materialization of an encoded column reads no file). Never + * decodes. */ + for (uint32_t k = 0; k < n_keys; k++) + file_bytes += agg_col_file_bytes(d.key_srcs[k] ? d.key_srcs[k]->obj : key_cols[k]); + for (uint32_t a = 0; a < n_aggs; a++) { + ray_t* vc = NULL; + if (d.val_srcs[a]) { + vc = d.val_srcs[a]->obj; + } else if (d.val_data[a] && d.agg_syms[a]) { + ray_t* slot = ray_table_slot(tbl, d.agg_syms[a]); + vc = slot && slot->type != RAY_ENCCOL ? slot : NULL; + } + bool dup = false; + for (uint32_t k = 0; k < n_keys && vc; k++) + if ((d.key_srcs[k] ? d.key_srcs[k]->obj : key_cols[k]) == vc) dup = true; + if (!dup) file_bytes += agg_col_file_bytes(vc); + } + n_waves = agg_radix_wave_plan(part_start, n_parts, rec, cmp_cap, reserve, + wave_cut, &max_wave); + /* A split that would spill (by the cost rule, or the test knob) is + * planned again with room for the write buffers (at most 1 MB per + * worker and wave, at most an eighth of the room, none once the + * watermark is passed). If the larger reserve changes the plan so + * that the spill no longer pays, the plan without buffers stands: a + * re-scan needs none, and its waves are not multiplied for nothing. */ + if (n_waves > 1 && (file_bytes > 0 || ray_agg_radix_spill >= 2) && + agg_radix_spill_wanted(file_bytes, n_waves, + part_start[n_parts] - part_start[wave_cut[1]], rec, max_wave)) { + int64_t wm = ray_heap_anon_watermark(); + int64_t room = wm > 0 ? wm - ray_heap_anon_committed() : -1; + int64_t bb = (int64_t)nw * (AGG_RADIX_MAX_WAVES + 1) << 20; + if (wm > 0 && bb > (room > 0 ? room / 8 : 0)) bb = room > 0 ? room / 8 : 0; + uint32_t w2 = bb > 0 + ? agg_radix_wave_plan(part_start, n_parts, rec, cmp_cap, reserve + bb, + wave_cut, &max_wave) + : 0; + if (w2 > 1 && agg_radix_spill_wanted(file_bytes, w2, + part_start[n_parts] - part_start[wave_cut[1]], rec, max_wave)) { + n_waves = w2; buf_bytes = bb; spill_chosen = true; + } else if (w2) { + n_waves = agg_radix_wave_plan(part_start, n_parts, rec, cmp_cap, reserve, + wave_cut, &max_wave); + } + } + pay = ray_alloc_raw((size_t)(max_wave > 0 ? max_wave : 1) * rec); + ctx.pay = pay; + if (!pay) no_pay = true; } + route_stats.radix_waves = n_waves; + if (!cancelled && !oom && !no_pay && n_waves == 1) { + /* Pass 2: every record to its exact slot. */ + ray_pool_dispatch_n(pool, ctx.rr->staged ? agg_radix_scatter_staged_fn : agg_radix_scatter_fn, + &ctx, n_chunks); + cancelled = agg_radix_stopped(&ctx, pool); + ray_free_raw(cnt); cnt = ctx.cnt = NULL; + ray_free_raw(pid); pid = ctx.pid = NULL; + ray_free_raw(count_srcs); count_srcs = NULL; ctx.count_rr = NULL; + ray_profile_tick("radix: scattered rows"); + + /* Phase 2: per-partition group+accumulate. */ + if (!cancelled) + ray_pool_dispatch_n(pool, agg_radix_group_fn, &ctx, n_parts); + if (!cancelled) { + cancelled = pool_cancelled(pool); + for (uint32_t p = 0; p < n_parts; p++) + if (parts[p].oom) { oom = 1; break; } + } + } else if (!cancelled && !oom && !no_pay) { + /* Waves: scatter the records of a run of partitions, reduce those + * partitions to their top-N candidates, reuse the payload for the + * next run. The later waves come from the spill file when that + * moves fewer bytes (agg_radix_spill_wanted); otherwise, or from the + * wave at which the file failed, every wave re-reads the input (its + * rows in place or, staged, by range; the partition ids + * sequentially); no wave writes outside its payload. */ + uint32_t next = 0; + if (spill_chosen) { + uint64_t sb = 0; + next = agg_radix_spill_run(&ctx, pool, nw, wave_cut, n_waves, buf_bytes, + &cancelled, &oom, &sb); + route_stats.radix_spill_bytes = sb; + } + for (uint32_t w = next; w < n_waves && !cancelled && !oom; w++) { + uint32_t lo = wave_cut[w], hi = wave_cut[w + 1]; + if (part_start[hi] == part_start[lo]) continue; /* only empty partitions */ + ctx.wave_lo = lo; ctx.wave_hi = hi; ctx.part_lo = lo; + ctx.pay_base = part_start[lo]; + ray_pool_dispatch_n(pool, ctx.rr->staged ? agg_radix_wave_scatter_staged_fn + : agg_radix_wave_scatter_fn, &ctx, n_chunks); + cancelled = agg_radix_stopped(&ctx, pool); + if (cancelled) break; + ray_pool_dispatch_n(pool, agg_radix_group_fn, &ctx, hi - lo); + cancelled = pool_cancelled(pool); + for (uint32_t p = lo; p < hi && !cancelled; p++) + if (parts[p].oom) { oom = 1; break; } + ray_profile_tick("radix: wave reduced"); + } + ctx.wave_lo = 0; ctx.wave_hi = n_parts; ctx.part_lo = 0; ctx.pay_base = 0; + } + /* A range read that failed in a scatter is the query's error. */ + if (!ferr && d.staged && ray_scan_failed(&d.fail)) ferr = ray_scan_fail_finish(&d.fail, pool); + if (ferr) cancelled = true; ray_free_raw(cnt); ctx.cnt = NULL; ray_free_raw(pid); ctx.pid = NULL; - ray_profile_tick("radix: scattered rows"); - - /* Phase 2: per-partition group+accumulate. */ - if (!cancelled && !oom) - ray_pool_dispatch_n(pool, agg_radix_group_fn, &ctx, n_parts); - if (!cancelled && !oom) { - cancelled = pool_cancelled(pool); - for (uint32_t p = 0; p < n_parts; p++) - if (parts[p].oom) { oom = 1; break; } - } + ray_free_raw(count_srcs); ctx.count_rr = NULL; + ray_free_raw(wave_cut); + route_stats.radix_compacted = + (uint64_t)atomic_load_explicit(&ctx.cmp_parts, memory_order_relaxed); + if (no_pay) oom = 1; ray_profile_tick("radix: reduced partitions"); @@ -4893,6 +8847,7 @@ static ray_t* exec_group_v2_parallel_radix( agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); ray_free_raw(parts); agg_desc_free(&d); + if (ferr) return ferr; if (cancelled) return ray_error("cancel", NULL); return exec_group_v2_parallel_smallhash(g, op, tbl, nrows, key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel); @@ -5046,6 +9001,8 @@ typedef struct { int64_t merge_cand; /* total entries + scattered rows (phase 2 sizing) */ ray_t* sel; const int64_t* sel_prefix; + const agg_rr_t* rr; /* sources; staged ones are read by range */ + const agg_view_t* whole; } agg_ts_ctx_t; /* Same FNV-1a + fmix64 as the radix scatter; bit 0 forced on so 0 can mark @@ -5173,42 +9130,71 @@ static bool agg_ts_reserve(agg_ts_ctx_t* c, agg_ts_task_t* ts, int64_t n) { return true; } -/* Visit one chunk of rows of a task: original rows `rows[i]` (or pos0 + i - * when rows == NULL) at logical input positions pos0 + i. */ -static void agg_ts_chunk(agg_ts_ctx_t* c, agg_ts_task_t* ts, - const int64_t* rows, int64_t pos0, int64_t n, - agg_sel_scratch_t* sc, uint32_t* gid, int64_t* keys) { +/* One chunk of a task, probed and accumulated through a view: indices + * [ib, ie) of the chunk, original rows rows[i] (or pos0 + i when rows == + * NULL) at logical input positions pos0 + i. The chunk's table room was + * reserved (or the task switched to scatter) for the whole chunk first, so + * its pieces see the same table and the same switch point as one call. */ +typedef struct { + agg_ts_ctx_t* c; + agg_ts_task_t* ts; + const int64_t* rows; + int64_t pos0; + agg_sel_scratch_t* sc; + uint32_t* gid; + int64_t* keys; +} agg_ts_run_t; + +static void agg_ts_idx_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t ib, int64_t ie) { + (void)wid; + agg_ts_run_t* run = raw; + agg_ts_ctx_t* c = run->c; + agg_ts_task_t* ts = run->ts; + const int64_t* rows = run->rows; + const int64_t pos0 = run->pos0, base = v->base; + int64_t* keys = run->keys; + uint32_t* gid = run->gid; uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; - if (!ts->scatter && !agg_ts_reserve(c, ts, n)) { ts->oom = 1; return; } + if (ts->oom) return; + /* The entry and record stores below are byte copies, which may alias + * any field: the keys' read parameters are hoisted into locals (a + * single key's into registers). */ + uint32_t nkv = n_keys ? n_keys : 1; + int8_t kt[nkv]; uint8_t ka[nkv]; const void* kd[nkv]; + for (uint32_t k = 0; k < n_keys; k++) { + kt[k] = c->key_cols[k]->type; ka[k] = v->key_attrs[k]; kd[k] = v->key_data[k]; + } + const int8_t kt0 = kt[0]; + const uint8_t ka0 = ka[0]; + const void* kd0 = kd[0]; + #define AGG_TS_KEYS(r) do { \ + if (n_keys == 1) keys[0] = agg_read_key_i64_raw(kt0, ka0, kd0, (r) - base); \ + else for (uint32_t k = 0; k < n_keys; k++) \ + keys[k] = agg_read_key_i64_raw(kt[k], ka[k], kd[k], (r) - base); \ + } while (0) if (ts->scatter) { - if (!ts->buckets) { - ts->buckets = ray_calloc_raw((size_t)c->n_parts * sizeof(agg_ts_bucket_t)); - if (!ts->buckets) { ts->oom = 1; return; } - } uint32_t pshift = 64 - c->part_bits; - for (int64_t i = 0; i < n; i++) { + for (int64_t i = ib; i < ie; i++) { int64_t r = rows ? rows[i] : pos0 + i; - for (uint32_t k = 0; k < n_keys; k++) - keys[k] = agg_read_key_i64(c->key_cols[k], c->key_data[k], r); + AGG_TS_KEYS(r); uint64_t h = agg_ts_hash(keys, n_keys); char* rec = agg_ts_bucket_push(&ts->buckets[h >> pshift], c->rec); if (!rec) { ts->oom = 1; return; } memcpy(rec, keys, (size_t)n_keys * sizeof(int64_t)); for (uint32_t a = 0; a < n_aggs; a++) { - if (c->val_data[a]) { + if (v->val_data[a]) { uint8_t ez = c->val_esz[a]; - memcpy(rec + c->val_off[a], (const char*)c->val_data[a] + (size_t)r * ez, ez); + memcpy(rec + c->val_off[a], (const char*)v->val_data[a] + (size_t)(r - base) * ez, ez); } - if (c->val2_data[a]) { + if (v->val2_data[a]) { uint8_t ez2 = c->val2_esz[a]; - memcpy(rec + c->val2_off[a], (const char*)c->val2_data[a] + (size_t)r * ez2, ez2); + memcpy(rec + c->val2_off[a], (const char*)v->val2_data[a] + (size_t)(r - base) * ez2, ez2); } } int64_t pos = pos0 + i; memcpy(rec + c->row_off, &pos, sizeof(pos)); } - ts->rows += n; ts->scattered += n; return; } @@ -5216,10 +9202,9 @@ static void agg_ts_chunk(agg_ts_ctx_t* c, agg_ts_task_t* ts, uint64_t mask = (uint64_t)t->cap - 1; uint32_t shift = 64 - t->bits; size_t estride = c->estride, key_bytes = (size_t)n_keys * sizeof(int64_t); - for (int64_t i = 0; i < n; i++) { + for (int64_t i = ib; i < ie; i++) { int64_t r = rows ? rows[i] : pos0 + i; - for (uint32_t k = 0; k < n_keys; k++) - keys[k] = agg_read_key_i64(c->key_cols[k], c->key_data[k], r); + AGG_TS_KEYS(r); uint64_t h = agg_ts_hash(keys, n_keys); uint8_t tag = agg_ts_tag(h); uint64_t slot = h >> shift; @@ -5245,21 +9230,23 @@ static void agg_ts_chunk(agg_ts_ctx_t* c, agg_ts_task_t* ts, } slot = (slot + 1) & mask; } - gid[i] = (uint32_t)slot; + gid[i - ib] = (uint32_t)slot; } + int64_t n = ie - ib; if (rows) { - if (agg_sel_accum_chunk(&c->vd, sc, t->ent, gid, rows, n) != 0) { ts->oom = 1; return; } + if (agg_sel_accum_chunk(&c->vd, v, run->sc, t->ent, gid, rows + ib, n, false) != 0) { ts->oom = 1; return; } } else { + int64_t at = pos0 + ib - base; for (uint32_t a = 0; a < n_aggs; a++) { char* states = t->ent + c->ent_off[a]; if (c->vts[a]->update_batch2) { - const void* vx = (const char*)c->val_data[a] + (size_t)pos0 * c->val_esz[a]; - const void* vy = (const char*)c->val2_data[a] + (size_t)pos0 * c->val2_esz[a]; + const void* vx = (const char*)v->val_data[a] + (size_t)at * c->val_esz[a]; + const void* vy = (const char*)v->val2_data[a] + (size_t)at * c->val2_esz[a]; ray_valid_t valid_x = { vx, c->val_types[a], c->val_hasnull[a] }; ray_valid_t valid_y = { vy, c->val2_types[a], c->val2_hasnull[a] }; c->vts[a]->update_batch2(states, estride, gid, vx, vy, &valid_x, &valid_y, n, NULL); - } else if (c->val_data[a]) { - const void* vals = (const char*)c->val_data[a] + (size_t)pos0 * c->val_esz[a]; + } else if (v->val_data[a]) { + const void* vals = (const char*)v->val_data[a] + (size_t)at * c->val_esz[a]; ray_valid_t valid = { vals, c->val_types[a], c->val_hasnull[a] }; c->vts[a]->update_batch(states, estride, gid, vals, &valid, n, NULL); } else { @@ -5268,13 +9255,47 @@ static void agg_ts_chunk(agg_ts_ctx_t* c, agg_ts_task_t* ts, } } } - t->rows += n; ts->rows += n; + #undef AGG_TS_KEYS +} + +/* A piece of rows [b, e) of a contiguous chunk, as chunk indices. */ +static void agg_ts_range_rows(void* raw, const agg_view_t* v, uint32_t wid, int64_t b, int64_t e) { + agg_ts_run_t* run = raw; + agg_ts_idx_rows(raw, v, wid, b - run->pos0, e - run->pos0); +} + +/* Visit one chunk of rows of a task: original rows `rows[i]` (or pos0 + i + * when rows == NULL) at logical input positions pos0 + i. Staged sources + * are read by pieces of the chunk (through the task's cursors `cs` when + * given), or by runs of its selected rows through them. False on a range + * error (noted keyed by `key`). */ +static bool agg_ts_chunk(agg_ts_ctx_t* c, agg_ts_task_t* ts, + const int64_t* rows, int64_t pos0, int64_t n, + agg_sel_scratch_t* sc, uint32_t* gid, int64_t* keys, + uint32_t wid, agg_curs_t* cs, int64_t key) { + const agg_rr_t* rr = c->rr; + if (!ts->scatter && !agg_ts_reserve(c, ts, n)) { ts->oom = 1; return true; } + if (ts->scatter && !ts->buckets) { + ts->buckets = ray_calloc_raw((size_t)c->n_parts * sizeof(agg_ts_bucket_t)); + if (!ts->buckets) { ts->oom = 1; return true; } + } + agg_ts_run_t run = { c, ts, rows, pos0, sc, gid, keys }; + if (!rr->staged) agg_ts_idx_rows(&run, c->whole, wid, 0, n); + else if (rows) { + ray_t* err = agg_idx_walk(rr, cs, rows, 0, n, &run, agg_ts_idx_rows, wid); + if (err) { ray_scan_fail_note(rr->fail, key, err); return false; } + } else if (cs ? !agg_walk_cs(rr, cs, &run, agg_ts_range_rows, wid, pos0, pos0 + n, key) + : !agg_walk(rr, &run, agg_ts_range_rows, wid, pos0, pos0 + n, key)) return false; + if (ts->oom) return true; + if (ts->scatter) { ts->rows += n; ts->scattered += n; } + else { ts->top->rows += n; ts->rows += n; } + return true; } /* Phase 1: one task = one contiguous range of logical input positions. */ static void agg_ts_phase1_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - (void)wid; agg_ts_ctx_t* c = (agg_ts_ctx_t*)vctx; + const agg_rr_t* rr = c->rr; ray_t* kb_hdr = NULL; int64_t* keys = (int64_t*)scratch_alloc(&kb_hdr, (size_t)(c->n_keys ? c->n_keys : 1) * sizeof(int64_t)); @@ -5289,23 +9310,30 @@ static void agg_ts_phase1_fn(void* vctx, uint32_t wid, int64_t start, int64_t en int64_t lo = ti * c->task_rows; int64_t hi = lo + c->task_rows; if (hi > c->n_in) hi = c->n_in; + if (rr->staged && ray_scan_fail_skip(rr->fail, lo)) continue; if (c->sel) { int64_t rows[AGG_SEL_CHUNK]; agg_sel_scratch_t sc; if (!agg_sel_scratch_init(&sc, c->n_aggs)) { ts->oom = 1; continue; } + agg_curs_t cs; cs.cur = NULL; + if (rr->staged && !agg_curs_init(&cs, rr)) { ts->oom = 1; agg_sel_scratch_free(&sc); continue; } agg_sel_cursor_t cur; agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, lo, hi); int64_t pos = lo, cn; while (!ts->oom && (cn = agg_sel_cursor_next(&cur, rows)) > 0) { - agg_ts_chunk(c, ts, rows, pos, cn, &sc, gid, keys); + if (!agg_ts_chunk(c, ts, rows, pos, cn, &sc, gid, keys, wid, &cs, lo)) break; pos += cn; } + agg_curs_free(&cs, rr); agg_sel_scratch_free(&sc); } else { + agg_curs_t tc; tc.cur = NULL; + if (rr->staged && !agg_curs_init(&tc, rr)) { ts->oom = 1; continue; } for (int64_t cs = lo; cs < hi && !ts->oom; cs += AGG_TS_CHUNK) { int64_t ce = cs + AGG_TS_CHUNK; if (ce > hi) ce = hi; - agg_ts_chunk(c, ts, NULL, cs, ce - cs, NULL, gid, keys); + if (!agg_ts_chunk(c, ts, NULL, cs, ce - cs, NULL, gid, keys, wid, rr->staged ? &tc : NULL, lo)) break; } + agg_curs_free(&tc, rr); } for (agg_ts_table_t* tab = ts->top; tab; tab = tab->prev) ts->entries += tab->ng; } @@ -5574,8 +9602,7 @@ static void agg_ts_merge_fn(void* vctx, uint32_t wid, int64_t start, int64_t end #define AGG_TS_PRE_SAMPLE2 1024 #define AGG_TS_PRE_DECLINE_X 1.5 typedef struct { - ray_t** key_cols; - const void** key_data; + const agg_rr_t* rr; /* the keys are its first n_keys sources */ uint32_t n_keys; int64_t n_in; int64_t step; @@ -5590,6 +9617,7 @@ typedef struct { static void agg_ts_sample_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { (void)wid; agg_ts_sample_ctx_t* c = (agg_ts_sample_ctx_t*)vctx; + const agg_rr_t* rr = c->rr; uint32_t n_keys = c->n_keys; for (int64_t t = start; t < end; t++) { uint64_t* hs = c->hs + (size_t)t * AGG_TS_SAMPLE_SETCAP; @@ -5597,7 +9625,12 @@ static void agg_ts_sample_fn(void* vctx, uint32_t wid, int64_t start, int64_t en int64_t* keys = c->keys + (size_t)t * (n_keys ? n_keys : 1); int64_t rows[AGG_SEL_CHUNK]; int64_t n = 0; - for (int64_t j = 0; j < AGG_TS_SAMPLE_PER; j++) { + /* staged keys: strided single rows, ascending, through this task's + * cursors (R-SPARSE) */ + agg_curs_t cs; cs.cur = NULL; + ray_t* err = NULL; + if (rr->staged && !agg_curs_init(&cs, rr)) err = ray_error("oom", NULL); + for (int64_t j = 0; j < AGG_TS_SAMPLE_PER && !err; j++) { int64_t i = t * AGG_TS_SAMPLE_PER + j; int64_t pos = i * c->step + (int64_t)(ray_hash_i64(i) % (uint64_t)c->step); int64_t r = pos; @@ -5607,8 +9640,74 @@ static void agg_ts_sample_fn(void* vctx, uint32_t wid, int64_t start, int64_t en if (agg_sel_cursor_next(&cur, rows) != 1) continue; r = rows[0]; } - for (uint32_t k = 0; k < n_keys; k++) - keys[k] = agg_read_key_i64(c->key_cols[k], c->key_data[k], r); + for (uint32_t k = 0; k < n_keys && !err; k++) + keys[k] = agg_key_at(rr, &cs, k, r, &err); + if (err) break; + uint64_t h = agg_ts_hash(keys, n_keys); + uint64_t at = h & (AGG_TS_SAMPLE_SETCAP - 1); + while (hs[at] && hs[at] != h) at = (at + 1) & (AGG_TS_SAMPLE_SETCAP - 1); + if (!hs[at]) hs[at] = h; + cnt[at]++; + n++; + } + agg_curs_free(&cs, rr); + if (err) ray_scan_fail_note(rr->fail, t, err); + c->n[t] = n; + } +} + +/* agg_ts_sample_fn over staged keys: the same rows (the slice's selected + * rows ascending), each key read a vector at a time: the slice's rows in + * one vector point-read together (ray_col_src_points_i64: the body read + * once, not once per row), a declined vector through the cursor. Its own + * instance: the plain sampler keeps its code. */ +static void agg_ts_sample_staged_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_ts_sample_ctx_t* c = (agg_ts_sample_ctx_t*)vctx; + const agg_rr_t* rr = c->rr; + const uint32_t n_keys = c->n_keys; + for (int64_t t = start; t < end; t++) { + uint64_t* hs = c->hs + (size_t)t * AGG_TS_SAMPLE_SETCAP; + uint16_t* cnt = c->cnt + (size_t)t * AGG_TS_SAMPLE_SETCAP; + int64_t rows[AGG_TS_SAMPLE_PER], one[AGG_SEL_CHUNK]; + int64_t nr = 0; + for (int64_t j = 0; j < AGG_TS_SAMPLE_PER; j++) { + int64_t i = t * AGG_TS_SAMPLE_PER + j; + int64_t pos = i * c->step + (int64_t)(ray_hash_i64(i) % (uint64_t)c->step); + int64_t r = pos; + if (c->sel) { + agg_sel_cursor_t cur; + agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, pos, pos + 1); + if (agg_sel_cursor_next(&cur, one) != 1) continue; + r = one[0]; + } + rows[nr++] = r; + } + agg_curs_t cs; cs.cur = NULL; + ray_t* err = NULL; + /* the slice's tuples, key-major: kv[k * nr + a] (the task's one scratch) */ + int64_t* kv = (int64_t*)ray_alloc_raw((size_t)(nr ? nr : 1) * (n_keys ? n_keys : 1) * sizeof(int64_t)); + if (!kv || !agg_curs_init(&cs, rr)) err = ray_error("oom", NULL); + for (uint32_t k = 0; k < n_keys && !err; k++) { + int64_t* vals = kv + (size_t)k * nr; + ray_col_src_t* src = rr->srcs[k]; + for (int64_t a = 0; a < nr && !err; ) { + int64_t vlo, vhi, b = a + 1; + if (src && ray_col_src_vec_span(src, rows[a], &vlo, &vhi)) { + while (b < nr && b - a < RAY_COL_POINT_ROWS && rows[b] < vhi) b++; + int pr = agg_src_points(src, rows + a, b - a, vals + a, &err); + if (pr < 0) break; + if (pr > 0) { a = b; continue; } + } + vals[a] = agg_key_at(rr, &cs, k, rows[a], &err); /* in place, or the cursor */ + a++; + } + } + agg_curs_free(&cs, rr); + int64_t n = 0; + int64_t* keys = c->keys + (size_t)t * (n_keys ? n_keys : 1); + for (int64_t a = 0; a < nr && !err; a++) { + for (uint32_t k = 0; k < n_keys; k++) keys[k] = kv[(size_t)k * nr + a]; uint64_t h = agg_ts_hash(keys, n_keys); uint64_t at = h & (AGG_TS_SAMPLE_SETCAP - 1); while (hs[at] && hs[at] != h) at = (at + 1) & (AGG_TS_SAMPLE_SETCAP - 1); @@ -5616,6 +9715,8 @@ static void agg_ts_sample_fn(void* vctx, uint32_t wid, int64_t start, int64_t en cnt[at]++; n++; } + ray_free_raw(kv); + if (err) ray_scan_fail_note(rr->fail, t, err); c->n[t] = n; } } @@ -5644,9 +9745,13 @@ static inline bool agg_ts_sel_row_at(const uint8_t* flags, const uint32_t* offse return true; } -static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t nrows, - ray_t* sel, const int64_t* sel_prefix, int64_t n_sel) { +/* krr: the keys (staged ones read through cursors, scattered single rows); + * a range error sets *err (the caller returns it). */ +static bool agg_ts_precheck_declines(const agg_rr_t* krr, ray_t** key_cols, uint32_t n_keys, int64_t nrows, + ray_t* sel, const int64_t* sel_prefix, int64_t n_sel, + ray_t** err) { (void)sel_prefix; + *err = NULL; enum { PRECAP = AGG_TS_PRE_SAMPLE2 * 4 }; int64_t n_in = sel ? n_sel : nrows; if (n_in < AGG_TS_SAMPLE) return false; @@ -5656,16 +9761,14 @@ static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t size_t nk = n_keys ? n_keys : 1; uint64_t phs[PRECAP]; int64_t pkeys[16]; - const void* pdata[16]; ray_t* pk_hdr = NULL; int64_t* keys = pkeys; - const void** key_data = pdata; if (nk > 16) { - keys = (int64_t*)scratch_alloc(&pk_hdr, nk * (sizeof(int64_t) + sizeof(void*))); + keys = (int64_t*)scratch_alloc(&pk_hdr, nk * sizeof(int64_t)); if (!keys) return false; - key_data = (const void**)(keys + nk); } - for (uint32_t k = 0; k < n_keys; k++) key_data[k] = ray_data(key_cols[k]); + agg_curs_t cs; cs.cur = NULL; + if (krr->staged && !agg_curs_init(&cs, krr)) { scratch_free(pk_hdr); return false; } memset(phs, 0, sizeof(phs)); /* Stride AGG_TS_PRE_SAMPLE2 positions over the ORIGINAL rows (a selected * row is taken at or after each position); stage 1 visits every other @@ -5676,7 +9779,7 @@ static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t const int64_t ratio = AGG_TS_PRE_SAMPLE2 / AGG_TS_PRE_SAMPLE; int64_t pstep = nrows / AGG_TS_PRE_SAMPLE2; if (pstep < 1) pstep = 1; - if (!sel) + if (!sel && !krr->staged) /* staged keys are read by range instead */ for (uint32_t k = 0; k < n_keys; k++) if (ray_col_cold(key_cols[k])) for (int64_t i = 0; i < AGG_TS_PRE_SAMPLE2; i++) { @@ -5693,8 +9796,9 @@ static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t if (pos >= nrows) break; int64_t r = pos; if (sel && !agg_ts_sel_row_at(sflags, soffsets, sidx, pos, jit >> 32, &r)) continue; - for (uint32_t k = 0; k < n_keys; k++) - keys[k] = agg_read_key_i64(key_cols[k], key_data[k], r); + for (uint32_t k = 0; k < n_keys && !*err; k++) + keys[k] = agg_key_at(krr, &cs, k, r, err); + if (*err) { agg_curs_free(&cs, krr); scratch_free(pk_hdr); return false; } uint64_t h = agg_ts_hash(keys, n_keys); uint64_t at = h & (PRECAP - 1); while (phs[at] && phs[at] != h) at = (at + 1) & (PRECAP - 1); @@ -5713,6 +9817,7 @@ static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t double birthday = repeats > 0 ? (double)n * (double)n / (2.0 * (double)repeats) : 9.2e18; declined = birthday >= AGG_TS_PRE_DECLINE_X * (double)AGG_TS_GATE_GROUPS; } + agg_curs_free(&cs, krr); scratch_free(pk_hdr); return declined; } @@ -5734,10 +9839,11 @@ static bool agg_ts_precheck_declines(ray_t** key_cols, uint32_t n_keys, int64_t * whose key was seen once — the mass of keys the sample never saw — for * the caller's gate. Returns a value past INT64_MAX/2 when the sample is * all-distinct. */ -static double agg_ts_estimate(ray_pool_t* pool, ray_t** key_cols, const void** key_data, +static double agg_ts_estimate(ray_pool_t* pool, const agg_rr_t* rr, ray_t** key_cols, uint32_t n_keys, int64_t nrows, ray_t* sel, const int64_t* sel_prefix, int64_t n_sel, - int* unseen_pct) { + int* unseen_pct, ray_t** err) { + *err = NULL; enum { CAP = 16384, PRECAP = AGG_TS_PRE_SAMPLE * 4 }; int64_t n_in = sel ? n_sel : nrows; *unseen_pct = 0; @@ -5757,21 +9863,28 @@ static double agg_ts_estimate(ray_pool_t* pool, ray_t** key_cols, const void** k uint64_t* ghs = (uint64_t*)(ns + AGG_TS_SAMPLE_TASKS); uint16_t* gcnt = (uint16_t*)(ghs + CAP); agg_ts_sample_ctx_t ctx = { - .key_cols = key_cols, .key_data = key_data, .n_keys = n_keys, + .rr = rr, .n_keys = n_keys, .n_in = n_in, .step = n_in / AGG_TS_SAMPLE, .sel = sel, .sel_prefix = sel_prefix, .hs = hs, .cnt = cnt, .keys = keys, .n = ns, }; - if (!sel) + /* A cold mapped key: ask for the sampled rows' pages first (the + * staged sources of generation 2 are read by range instead). */ + if (!sel && !rr->staged) for (uint32_t k = 0; k < n_keys; k++) if (ray_col_cold(key_cols[k])) for (int64_t i = 0; i < AGG_TS_SAMPLE; i++) ray_col_want_row(key_cols[k], i * ctx.step + (int64_t)(ray_hash_i64(i) % (uint64_t)ctx.step)); - if (ray_pool_par_dispatch_ok(pool, AGG_TS_SAMPLE, 1)) - ray_pool_dispatch_n(pool, agg_ts_sample_fn, &ctx, AGG_TS_SAMPLE_TASKS); + bool par = ray_pool_par_dispatch_ok(pool, AGG_TS_SAMPLE, 1); + if (par) + ray_pool_dispatch_n(pool, rr->staged ? agg_ts_sample_staged_fn : agg_ts_sample_fn, &ctx, AGG_TS_SAMPLE_TASKS); else - agg_ts_sample_fn(&ctx, 0, 0, AGG_TS_SAMPLE_TASKS); + (rr->staged ? agg_ts_sample_staged_fn : agg_ts_sample_fn)(&ctx, 0, 0, AGG_TS_SAMPLE_TASKS); + if (rr->staged && (*err = ray_scan_fail_finish(rr->fail, par ? pool : NULL)) != NULL) { + scratch_free(hdr); + return (double)n_in; + } /* Merge the slices' counts into one set. */ int64_t d = 0, n = 0; for (int t = 0; t < AGG_TS_SAMPLE_TASKS; t++) { @@ -5803,7 +9916,7 @@ static double agg_ts_estimate(ray_pool_t* pool, ray_t** key_cols, const void** k * estimate says the radix scatter is the better fit; see the header. */ static ray_t* exec_group_v2_parallel_tablestack( ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t nrows, - ray_t** key_cols, int64_t* key_syms, + ray_t** key_cols, int64_t* key_syms, const agg_rr_t* krr, const agg_vtable_t** vts, const size_t* off, size_t block, ray_t* sel, const int64_t* sel_prefix, int64_t n_sel, int64_t group_limit, const ray_group_emit_filter_t* efp) { @@ -5814,13 +9927,16 @@ static ray_t* exec_group_v2_parallel_tablestack( /* Near-unique keys (the common radix shape) decline here, before any * allocation: the radix path then runs exactly as it always has. */ - if (agg_ts_precheck_declines(key_cols, n_keys, nrows, sel, sel_prefix, n_sel)) { + ray_t* perr = NULL; + if (agg_ts_precheck_declines(krr, key_cols, n_keys, nrows, sel, sel_prefix, n_sel, &perr)) { ray_profile_tick("tablestack: gate declined"); return NULL; } + if (perr) return perr; agg_desc_t d; - if (!agg_desc_init(&d, g, ext, tbl, key_cols)) return ray_error("oom", NULL); + ray_t* derr = NULL; + if (!agg_desc_init(&d, g, ext, tbl, key_cols, &derr)) return derr ? derr : ray_error("oom", NULL); int64_t n_in = sel ? n_sel : nrows; if (n_in < 0) n_in = 0; @@ -5839,8 +9955,9 @@ static ray_t* exec_group_v2_parallel_tablestack( size_t state_off = AGG_TS_KEY_OFF + (size_t)n_keys * sizeof(int64_t); size_t estride = (state_off + block + 7u) & ~(size_t)7u; int unseen_pct = 0; - double est = agg_ts_estimate(pool, key_cols, d.key_data, n_keys, nrows, - sel, sel_prefix, n_sel, &unseen_pct); + double est = agg_ts_estimate(pool, &d.rr, key_cols, n_keys, nrows, + sel, sel_prefix, n_sel, &unseen_pct, &derr); + if (derr) { agg_desc_free(&d); return derr; } uint32_t init_bits = AGG_TS_MIN_BITS; while (init_bits < AGG_TS_MAX_BITS && (double)((int64_t)1 << init_bits) * 0.75 < est * 1.25) init_bits++; @@ -5875,8 +9992,8 @@ static ray_t* exec_group_v2_parallel_tablestack( size_t* ent_off = val2_off + (n_aggs ? n_aggs : 1); size_t rec_cur = (size_t)n_keys * 8; for (uint32_t a = 0; a < n_aggs; a++) { - if (d.val_data[a]) { val_off[a] = rec_cur; rec_cur += d.val_esz[a]; } - if (d.val2_data[a]) { val2_off[a] = rec_cur; rec_cur += d.val2_esz[a]; } + if (d.val_id[a]) { val_off[a] = rec_cur; rec_cur += d.val_esz[a]; } + if (d.val2_id[a]) { val2_off[a] = rec_cur; rec_cur += d.val2_esz[a]; } } size_t row_off = rec_cur; rec_cur += 8; size_t rec = (rec_cur + 7u) & ~(size_t)7u; @@ -5910,11 +10027,11 @@ static ray_t* exec_group_v2_parallel_tablestack( agg_ts_ctx_t ctx = { .key_cols = key_cols, .key_data = d.key_data, .n_keys = n_keys, .vts = vts, .off = off, .block = block, .n_aggs = n_aggs, - .val_data = d.val_data, .val_types = d.val_types, .val_hasnull = d.val_hasnull, .val_esz = d.val_esz, - .val2_data = d.val2_data, .val2_types = d.val2_types, .val2_hasnull = d.val2_hasnull, .val2_esz = d.val2_esz, + .val_data = d.val_id, .val_types = d.val_types, .val_hasnull = d.val_hasnull, .val_esz = d.val_esz, + .val2_data = d.val2_id, .val2_types = d.val2_types, .val2_hasnull = d.val2_hasnull, .val2_esz = d.val2_esz, .vd = { .n_aggs = n_aggs, .vts = vts, .off = ent_off, .block = estride, - .val_data = d.val_data, .val_types = d.val_types, .val_hasnull = d.val_hasnull, .val_esz = d.val_esz, - .val2_data = d.val2_data, .val2_types = d.val2_types, .val2_hasnull = d.val2_hasnull, .val2_esz = d.val2_esz }, + .val_data = d.val_id, .val_types = d.val_types, .val_hasnull = d.val_hasnull, .val_esz = d.val_esz, + .val2_data = d.val2_id, .val2_types = d.val2_types, .val2_hasnull = d.val2_hasnull, .val2_esz = d.val2_esz }, .ent_off = ent_off, .estride = estride, .state_off = state_off, .rec = rec, .row_off = row_off, .val_off = val_off, .val2_off = val2_off, .n_parts = n_parts, .part_bits = (uint32_t)__builtin_ctz(n_parts), @@ -5922,10 +10039,13 @@ static ray_t* exec_group_v2_parallel_tablestack( .n_in = n_in, .task_rows = task_rows, .n_tasks = n_tasks, .tasks = tasks, .parts = parts, .sel = sel, .sel_prefix = sel_prefix, + .rr = &d.rr, .whole = &d.whole, }; + agg_desc_advise(&d, nrows); ray_pool_dispatch_n(pool, agg_ts_phase1_fn, &ctx, n_tasks); - bool cancelled = pool_cancelled(pool); + ray_t* ferr = d.staged ? ray_scan_fail_finish(&d.fail, pool) : NULL; + bool cancelled = pool_cancelled(pool) || ferr; int oom = 0; uint32_t scatter_tasks = 0; uint64_t tables = 0; int64_t cand = 0; for (uint32_t t = 0; t < n_tasks; t++) { @@ -5954,6 +10074,7 @@ static ray_t* exec_group_v2_parallel_tablestack( agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); ray_free_raw(parts); agg_desc_free(&d); + if (ferr) return ferr; if (cancelled) return ray_error("cancel", NULL); return exec_group_v2_parallel_smallhash(g, op, tbl, nrows, key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel); @@ -6209,8 +10330,8 @@ static void agg_index_stream_reduce(void* raw, uint32_t wid, int64_t start, int6 } while (at < stop) { int64_t n = stop - at < AGG_SEL_CHUNK ? stop - at : AGG_SEL_CHUNK; - if (ex) agg_sel_gather_vals(x, ray_data(c->x), ex, c->rows + at, n); - if (ey) agg_sel_gather_vals(y, ray_data(c->y), ey, c->rows + at, n); + if (ex) agg_sel_gather_vals(x, ray_data(c->x), ex, c->rows + at, n, 0); + if (ey) agg_sel_gather_vals(y, ray_data(c->y), ey, c->rows + at, n, 0); if (c->y) c->vt->update_batch2(state, c->vt->state_size, gids, x, y, &vx, &vy, n, NULL); else c->vt->update_batch(state, c->vt->state_size, gids, x, &vx, n, NULL); at += n; @@ -6282,7 +10403,7 @@ static int64_t agg_index_winner(void* raw, const int64_t* rows, int64_t count) { case RAY_I16: INDEX_FIRST_VALID(int16_t, value != NULL_I16); case RAY_I32: case RAY_DATE: case RAY_TIME: INDEX_FIRST_VALID(int32_t, value != NULL_I32); - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: INDEX_FIRST_VALID(int64_t, value != NULL_I64); case RAY_F32: INDEX_FIRST_VALID(float, value == value); case RAY_F64: INDEX_FIRST_VALID(double, value == value); @@ -6432,7 +10553,8 @@ static ray_t* agg_indexed_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (agg_cancelled()) { ray_release(result); result = ray_error("cancel", NULL); goto done; } uint16_t kind = ext->agg_ops[a]; ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); - ray_t* src = ie ? ray_table_get_col(tbl, ie->sym) : NULL; + ray_t* src = ie ? ray_table_col(tbl, ie->sym) : NULL; + if (src && RAY_IS_ERR(src)) { ray_release(result); result = src; goto done; } int64_t param = ext->agg_k ? ext->agg_k[a] : 0; ray_t* col = NULL; /* The kernels below read src at every row, group by group, so at @@ -6472,8 +10594,10 @@ static ray_t* agg_indexed_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } } else if (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) { ray_op_ext_t* ye = find_ext(g, ext->agg_ins2[a]); + ray_t* ycol = ray_table_col(tbl, ye->sym); + if (ycol && RAY_IS_ERR(ycol)) { ray_release(result); result = ycol; goto done; } col = agg_index_streaming(agg_resolve(kind, src->type), src, - ray_table_get_col(tbl, ye->sym), &groups, rows, offsets, nrows, param); + ycol, &groups, rows, offsets, nrows, param); } else if (kind == OP_COUNT) { col = ray_vec_new(RAY_I64, ng); if (col && !RAY_IS_ERR(col)) { col->len = ng; memcpy(ray_data(col), counts, (size_t)ng * sizeof(int64_t)); } @@ -6498,27 +10622,33 @@ static ray_t* agg_indexed_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * Predominantly changing states use owned partitions instead of contended CAS. * The sample is query-local and never supplies an answer to execution. */ static bool agg_shared_sample(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl, - ray_t** keys, const agg_vo_t* vo, int64_t rows) { + ray_t** keys, const agg_vo_t* vo, int64_t rows, ray_t** err) { + *err = NULL; if (!ext->n_aggs) return true; if (rows < 1024) return false; enum { SAMPLES = 1024, CAP = 2048 }; agg_desc_t d; - if (!agg_desc_init(&d, g, ext, tbl, keys)) return false; + if (!agg_desc_init(&d, g, ext, tbl, keys, err)) return false; /* *err: failed bind; else OOM = not shared */ char* states = ray_alloc_raw((SAMPLES + 1) * vo->block); if (!states) { agg_desc_free(&d); return false; } + /* Staged sources: strided single rows, ascending, through cursors + * (R-SPARSE). */ + agg_curs_t cs; cs.cur = NULL; + if (d.staged && !agg_curs_init(&cs, &d.rr)) { ray_free_raw(states); agg_desc_free(&d); return false; } char* previous = states + SAMPLES * vo->block; int16_t map[CAP]; int64_t values[SAMPLES]; memset(map, -1, sizeof(map)); uint32_t gid = 0; int groups = 0, unchanged = 0; int64_t step = rows / SAMPLES; - if (ray_col_cold(keys[0])) + if (!d.staged && ray_col_cold(keys[0])) for (int i = 0; i < SAMPLES; i++) ray_col_want_row(keys[0], i * step + (int64_t)(ray_hash_i64(i) % (uint64_t)step)); - for (int i = 0; i < SAMPLES; i++) { + for (int i = 0; i < SAMPLES && !*err; i++) { uint64_t jitter = ray_hash_i64(i); int64_t row = i * step + jitter % step; - int64_t value = agg_read_key_i64(keys[0], ray_data(keys[0]), row); + int64_t value = agg_key_at(&d.rr, &cs, 0, row, err); + if (*err) break; uint32_t at = ray_hash_i64(value) & (CAP - 1); while (map[at] >= 0 && values[map[at]] != value) at = (at + 1) & (CAP - 1); if (map[at] < 0) { @@ -6528,15 +10658,16 @@ static bool agg_shared_sample(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl, } char* state = states + map[at] * vo->block; memcpy(previous, state, vo->block); - for (uint32_t a = 0; a < ext->n_aggs; a++) { - const void* input = d.val_data[a] ? (const char*)d.val_data[a] + (size_t)row * d.val_esz[a] : NULL; + for (uint32_t a = 0; a < ext->n_aggs && !*err; a++) { + const void* input = agg_elem_at(&d.rr, &cs, ext->n_keys + a, row, err); ray_valid_t valid = {input, d.val_types[a], d.val_hasnull[a]}; - vo->vts[a]->update_shared(state + vo->off[a], vo->block, &gid, input, &valid, 1); + if (!*err) vo->vts[a]->update_shared(state + vo->off[a], vo->block, &gid, input, &valid, 1); } unchanged += memcmp(previous, state, vo->block) == 0; } + agg_curs_free(&cs, &d.rr); ray_free_raw(states); agg_desc_free(&d); - return unchanged >= SAMPLES / 4; + return !*err && unchanged >= SAMPLES / 4; } /* Core of exec_group_v2: resolution + strategy dispatch over (tbl, nrows). @@ -6563,6 +10694,45 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit, const ray_group_emit_filter_t* efp); +/* A segment-streamed table (g->grp_seg_stream) holding a parted column. */ +static bool agg_seg_parted(ray_graph_t* g, ray_t* tbl) { + if (!g->grp_seg_stream) return false; + int64_t nc = ray_table_ncols(tbl); + for (int64_t c = 0; c < nc; c++) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && RAY_IS_PARTED(m.type)) return true; + } + return false; +} + +/* R-RANDOM over a segment-streamed table: a strategy that reads keys or + * inputs at stored rows or whole runs over a flat copy of the table, each + * parted column copied from its segments by range (parted_flatten_fixed, + * the concat fallback's own copy), released when the run returns. */ +static ray_t* agg_seg_flat_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, + int64_t nrows, ray_t* sel, + const int64_t* sel_prefix, int64_t n_sel, + int64_t group_limit, + const ray_group_emit_filter_t* efp) { + int64_t nc = ray_table_ncols(tbl); + int64_t fx_ncnt = 0; + const int64_t* fx_cnt = parted_table_counts(tbl, &fx_ncnt); + ray_t* flat = ray_table_new(nc > 0 ? nc : 1); + for (int64_t c = 0; c < nc && flat && !RAY_IS_ERR(flat); c++) { + ray_t* slot = ray_table_slot_idx(tbl, c); + ray_col_meta_t m; + ray_t* v = ray_col_meta_of(slot, &m) && RAY_IS_PARTED(m.type) ? parted_flatten_fixed_c(slot, nrows, fx_cnt, fx_ncnt) : slot; + if (!v || RAY_IS_ERR(v)) { ray_release(flat); return v ? v : ray_error("oom", NULL); } + flat = ray_table_add_col(flat, ray_table_col_name(tbl, c), v); + if (v != slot) ray_release(v); + } + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); + ray_t* r = exec_group_v2_run_inner(g, op, flat, nrows, sel, sel_prefix, n_sel, group_limit, efp); + ray_graph_unbind_table(g, flat); + ray_release(flat); + return r; +} + /* Trim a full group result to the emit filter's keep set (the same decision * the native selections make, over the finished aggregate column). Row * order is preserved. Consumes `result`; a failure keeps the full result, @@ -6575,7 +10745,8 @@ ray_t* agg_emit_filter_trim(ray_t* result, uint32_t n_keys, uint32_t n_aggs, if (agg_ops && (ef->agg_op ? ef->agg_op : OP_COUNT) != agg_ops[ef->agg_index]) return result; int64_t nrows = ray_table_nrows(result); if (nrows <= 0) return result; - ray_t* vcol = ray_table_get_col_idx(result, (int64_t)n_keys + ef->agg_index); + ray_t* vcol = ray_table_col_idx(result, (int64_t)n_keys + ef->agg_index); + if (vcol && RAY_IS_ERR(vcol)) { ray_error_free(vcol); return result; } /* the sort+take downstream re-reads it */ if (!vcol || (vcol->type != RAY_I64 && vcol->type != RAY_F64)) return result; double* vals = ray_alloc_raw((size_t)nrows * sizeof(double)); uint8_t* keep = ray_alloc_raw((size_t)nrows); @@ -6614,7 +10785,7 @@ ray_t* agg_emit_filter_trim(ray_t* result, uint32_t n_keys, uint32_t n_aggs, * exists and holds the operation the filter names (count when unset). The * filter stays armed while the matched select's whole `from:` evaluates, so * grouped selects nested inside see it too; for them this is false. */ -static bool agg_emit_filter_targets(const ray_group_emit_filter_t* ef, const ray_op_ext_t* ext) { +bool agg_emit_filter_targets(const ray_group_emit_filter_t* ef, const ray_op_ext_t* ext) { return ef && ef->enabled && ext && ef->agg_index < ext->n_aggs && (ef->agg_op ? ef->agg_op : OP_COUNT) == ext->agg_ops[ef->agg_index]; } @@ -6662,8 +10833,6 @@ static ray_t* exec_group_v2_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * spent — when the N keys are not found within a bounded prefix, or when the * N groups hold a large share of the rows (sampled before the parallel pass, * counted exactly in it), where aggregating everything costs about the same. */ -#define AGG_FIRSTN_MAX 1024 /* largest take: N the pre-pass serves */ -#define AGG_FIRSTN_PROBE_ROWS 65536 /* prefix budget for the serial scan, at least */ #define AGG_FIRSTN_SAMPLES 4096 /* evenly spaced rows for the share estimate */ #define AGG_FIRSTN_SHARE 64 /* full run once the N groups hold 1/64 of the rows */ @@ -6717,10 +10886,12 @@ static inline int64_t agg_firstn_probe(agg_firstn_set_t* s, const int64_t* kv, /* Fold key column `col` rows [b, b+n) into the running hashes h[0..n). The * widening matches agg_read_key_i64 (signed types sign-extend, SYM and U8/BOOL * zero-extend), so the folded hash equals agg_firstn_hash of the read tuple. */ -static void agg_firstn_hash_block(uint64_t* h, ray_t* col, const void* data, +/* Always inlined: the per-task hash pass is the pre-pass's hot loop, and a + * second caller (the pick) must not turn it into a call. */ +static inline __attribute__((always_inline)) void agg_firstn_hash_block(uint64_t* h, ray_t* col, const void* data, int64_t b, int64_t n) { switch (col->type) { - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { const int64_t* d = (const int64_t*)data + b; for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], d[i]); break; @@ -6769,6 +10940,61 @@ static void agg_firstn_hash_block(uint64_t* h, ray_t* col, const void* data, break; } } +/* agg_firstn_hash_block over a type and SYM width instead of a column: + * the staged passes' instance (a view's width is per piece), kept apart so + * the plain passes keep their code. */ +static inline __attribute__((always_inline)) void agg_firstn_hash_raw(uint64_t* h, int8_t type, uint8_t attrs, + const void* data, int64_t b, int64_t n) { + switch (type) { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { + const int64_t* d = (const int64_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], d[i]); + break; + } + case RAY_I32: case RAY_DATE: case RAY_TIME: { + const int32_t* d = (const int32_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], (int64_t)d[i]); + break; + } + case RAY_I16: { + const int16_t* d = (const int16_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], (int64_t)d[i]); + break; + } + case RAY_U8: case RAY_BOOL: { + const uint8_t* d = (const uint8_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], (int64_t)d[i]); + break; + } + case RAY_SYM: + switch (attrs & RAY_SYM_W_MASK) { + case RAY_SYM_W8: { + const uint8_t* d = (const uint8_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], (int64_t)d[i]); + break; + } + case RAY_SYM_W16: { + const uint16_t* d = (const uint16_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], (int64_t)d[i]); + break; + } + case RAY_SYM_W32: { + const uint32_t* d = (const uint32_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], (int64_t)d[i]); + break; + } + default: { + const int64_t* d = (const int64_t*)data + b; + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], d[i]); + break; + } + } + break; + default: /* admission keeps every other type out */ + for (int64_t i = 0; i < n; i++) AGG_FIRSTN_MIX(h[i], agg_read_key_i64_raw(type, attrs, data, b + i)); + break; + } +} #define AGG_FIRSTN_LOCAL 1024 /* matches a task keeps before spilling */ @@ -6784,6 +11010,10 @@ typedef struct { int64_t* local; /* tasks * AGG_FIRSTN_LOCAL: the first matches */ int64_t* out; /* write pass: the final row list */ int64_t* kvs; /* tasks * n_keys: each task's probe tuple */ + const agg_rr_t* rr; /* staged keys (agg_firstn_task_staged); NULL: plain */ + const int64_t* mem_v; /* staged: n_keys member sets of 1 << mem_bits slots */ + const uint8_t* mem_used; + uint32_t mem_bits; } agg_firstn_ctx_t; /* One task: the selected rows of its morsel segments whose key tuple is in @@ -6833,6 +11063,381 @@ static void agg_firstn_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { for (int64_t t = start; t < end; t++) agg_firstn_task((agg_firstn_ctx_t*)raw, (uint32_t)t); } +/* ---- The passes over staged keys (generation 2, single file or parted): + * the keys are read through the key set's sources, never unstaged. Rows + * are read in order through task-held cursors (each touched vector decoded + * once per task); the share sample point-reads its rows. Separate + * instances: the plain passes above keep their code. ---- */ + +/* Key k at row r through the cursor set: in place for a plain key, else + * from its cursor's view. *err set on a range error. */ +static inline int64_t agg_firstn_key_cur(const agg_rr_t* rr, agg_curs_t* cs, uint32_t k, int64_t r, ray_t** err) { + if (!rr->srcs[k]) return agg_read_key_i64_raw(rr->key_types[k], rr->key_attrs[k], rr->plain[k], r); + const ray_col_range_t* v; + if ((*err = ray_col_cursor_at(&cs->cur[k], r, &v)) != NULL) return 0; + return agg_read_key_i64_raw(rr->key_types[k], v->attrs, v->data, r - v->start); +} + +/* Pass 1 over staged keys: the first group_limit distinct tuples from the + * first selected row, within the row budget, through one cursor set. NULL + * or an owned error. */ +static ray_t* agg_firstn_seen_staged(const agg_rr_t* rr, agg_firstn_set_t* set, ray_t* sel, + int64_t nrows, int64_t n_segs, int64_t group_limit, int64_t* kv) { + agg_curs_t cs; + if (!agg_curs_init(&cs, rr)) return ray_error("oom", NULL); + const uint8_t* fl = sel ? ray_rowsel_flags(sel) : NULL; + const uint32_t* of = sel ? ray_rowsel_offsets(sel) : NULL; + const uint16_t* ix = sel ? ray_rowsel_idx(sel) : NULL; + int64_t budget = group_limit * 64 > AGG_FIRSTN_PROBE_ROWS ? group_limit * 64 : AGG_FIRSTN_PROBE_ROWS; + int64_t scanned = 0; + ray_t* err = NULL; + for (int64_t seg = 0; seg < n_segs && set->n < group_limit && scanned < budget && !err; seg++) { + if (fl && fl[seg] == RAY_SEL_NONE) continue; + int64_t b = seg * RAY_MORSEL_ELEMS; + int64_t len = nrows - b < RAY_MORSEL_ELEMS ? nrows - b : RAY_MORSEL_ELEMS; + bool mix = fl && fl[seg] == RAY_SEL_MIX; + int64_t j_end = mix ? (int64_t)of[seg + 1] : len; + for (int64_t j = mix ? (int64_t)of[seg] : 0; + j < j_end && set->n < group_limit && scanned < budget; j++, scanned++) { + int64_t row = b + (mix ? (int64_t)ix[j] : j); + for (uint32_t k = 0; k < rr->n_keys && !err; k++) kv[k] = agg_firstn_key_cur(rr, &cs, k, row, &err); + if (err) break; + agg_firstn_probe(set, kv, agg_firstn_hash(kv, rr->n_keys), true); + } + } + agg_curs_free(&cs, rr); + return err; +} + +/* The share sample over staged keys: the plain sample's rows, each key + * point-read (agg_key_at: no vector decoded; SYM ids too) or, declined (RAW, + * DELTA_BP, nulls), read through a cursor, which decodes the sampled + * vector. The rows are split across pool tasks when the pass-2 dispatch + * is (each task its own cursors), so declined reads do not decode serially; + * a range error is noted keyed by the task's first sample row. */ +typedef struct { + const agg_rr_t* rr; + agg_firstn_set_t* set; + int64_t step, samples; + uint32_t tasks; + int64_t* hits; /* [tasks] */ + int64_t* kvs; /* [tasks * n_keys] */ +} agg_firstn_share_t; + +static void agg_firstn_share_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_firstn_share_t* c = (agg_firstn_share_t*)raw; + const agg_rr_t* rr = c->rr; + for (int64_t t = start; t < end; t++) { + int64_t i0 = c->samples * t / c->tasks, i1 = c->samples * (t + 1) / c->tasks; + int64_t key = i0 * c->step, hits = 0; + int64_t* kv = c->kvs + t * rr->n_keys; + c->hits[t] = 0; + if (i0 >= i1 || ray_scan_fail_skip(rr->fail, key)) continue; + agg_curs_t cs; + if (!agg_curs_init(&cs, rr)) { ray_scan_fail_note(rr->fail, key, ray_error("oom", NULL)); continue; } + ray_t* err = NULL; + for (int64_t i = i0; i < i1 && !err; i++) { + for (uint32_t k = 0; k < rr->n_keys && !err; k++) kv[k] = agg_key_at(rr, &cs, k, i * c->step, &err); + if (!err && agg_firstn_probe(c->set, kv, agg_firstn_hash(kv, rr->n_keys), false) >= 0) hits++; + } + agg_curs_free(&cs, rr); + if (err) ray_scan_fail_note(rr->fail, key, err); + c->hits[t] = hits; + } +} + +/* NULL or an owned error; *hits the sampled rows in the set. */ +static ray_t* agg_firstn_share_staged(const agg_rr_t* rr, agg_firstn_set_t* set, int64_t nrows, + int64_t samples, ray_pool_t* pool, bool par, int64_t* hits) { + uint32_t tasks = par ? ray_pool_total_workers(pool) : 1; + if ((int64_t)tasks > samples) tasks = (uint32_t)(samples > 0 ? samples : 1); + ray_t* hdr = NULL; + int64_t* buf = (int64_t*)scratch_alloc(&hdr, (size_t)tasks * (1 + rr->n_keys) * sizeof(int64_t)); + if (!buf) return ray_error("oom", NULL); + agg_firstn_share_t c = { .rr = rr, .set = set, .step = nrows / samples, .samples = samples, + .tasks = tasks, .hits = buf, .kvs = buf + tasks }; + ray_scan_fail_init(rr->fail); + if (tasks > 1) ray_pool_dispatch_n(pool, agg_firstn_share_fn, &c, tasks); + else agg_firstn_share_fn(&c, 0, 0, 1); + ray_t* err = ray_scan_fail_finish(rr->fail, tasks > 1 ? pool : NULL); + *hits = 0; + for (uint32_t t = 0; t < tasks; t++) *hits += buf[t]; + scratch_free(hdr); + return err; +} + +/* One piece of a staged pass-2 segment: rows [b, e) of every key (a piece + * ends at the nearest view end), hashed a key at a time, then the + * segment's selected rows inside it probed. */ +typedef struct { + agg_firstn_ctx_t* c; + uint64_t* hb; /* RAY_MORSEL_ELEMS */ + int64_t* kv; + int64_t* out; + int64_t out_cap, n; + int64_t seg_b; /* the segment's first row */ + const uint16_t* ix; /* MIX: selected indices [j, j_end) of the segment */ + int64_t j, j_end; +} agg_firstn_piece_t; + +static void agg_firstn_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + agg_firstn_piece_t* t = (agg_firstn_piece_t*)ctx; + const agg_rr_t* rr = t->c->rr; + agg_firstn_set_t* set = t->c->set; + const uint32_t nk = rr->n_keys; + const void* kd[nk]; + uint8_t ka[nk]; + const int64_t n = e - b; + for (int64_t i = 0; i < n; i++) t->hb[i] = AGG_FIRSTN_SEED; + for (uint32_t k = 0; k < nk; k++) { + kd[k] = rr->srcs[k] ? p[k].data : (const char*)rr->plain[k] + (size_t)b * rr->esz[k]; + ka[k] = rr->srcs[k] ? p[k].attrs : rr->key_attrs[k]; + agg_firstn_hash_raw(t->hb, rr->key_types[k], ka[k], kd[k], 0, n); + } + const uint32_t bshift = 64 - set->bbits; + for (int64_t q = t->ix ? t->j : 0; q < (t->ix ? t->j_end : n); q++) { + int64_t i; + if (t->ix) { + int64_t r = t->seg_b + (int64_t)t->ix[q]; + if (r >= e) break; /* the next piece's */ + i = r - b; + t->j = q + 1; + } else { + i = q; + } + uint64_t hv = AGG_FIRSTN_FINAL(t->hb[i]); + uint64_t bit = hv >> bshift; + if (!((set->bloom[bit >> 6] >> (bit & 63)) & 1)) continue; + for (uint32_t k = 0; k < nk; k++) t->kv[k] = agg_read_key_i64_raw(rr->key_types[k], ka[k], kd[k], i); + if (agg_firstn_probe(set, t->kv, hv, false) < 0) continue; + if (t->n < t->out_cap) t->out[t->n] = b + i; + t->n++; + } +} + +/* Lane i of a view's run lanes at width T. */ +static inline uint64_t agg_vv_lane(const ray_enc_lanes_t* l, int T, uint32_t i) { + switch (T) { + case 8: return l->b[i]; + case 16: return l->h[i]; + case 32: return l->s[i]; + default: return l->q[i]; + } +} + +/* Each key's member values (the distinct values key k takes among the N + * groups' tuples), an exact open-addressing set: pass 2 on runs skips a + * run whose value no group holds without reading the other key. */ +static inline uint32_t agg_firstn_mslot(int64_t x, uint32_t bits) { + return (uint32_t)(((uint64_t)x * 0x9E3779B97F4A7C15ULL) >> (64 - bits)); +} +static inline bool agg_firstn_member(const agg_firstn_ctx_t* c, uint32_t k, int64_t x) { + const uint32_t cap = 1u << c->mem_bits, mask = cap - 1; + const int64_t* v = c->mem_v + (size_t)k * cap; + const uint8_t* u = c->mem_used + (size_t)k * cap; + for (uint32_t i = agg_firstn_mslot(x, c->mem_bits);; i = (i + 1) & mask) { + if (!u[i]) return false; + if (v[i] == x) return true; + } +} + +/* Key k's vector at segment `seg` when it is a run view (RLE or CONST, not a float, + * without a null bitmap: SYM nulls are in-band ids), read by + * ray_col_src_vview, which makes every check the decode would: 1, 0 not + * one (read the vector otherwise), -1 with *err. The descriptor's + * encoding is looked at first, so no other codec builds a view. */ +static int agg_firstn_runview(const agg_rr_t* rr, uint32_t k, int64_t seg, int64_t len, + ray_enc_vview_t* vv, ray_t** err) { + ray_col_src_t* src = rr->srcs[k]; + if (!src || !ray_col_src_encoded(src) || ray_enccol_decoded_peek(src->obj)) return 0; + ray_enccol_t* e = ray_enccol_of(src->obj); + if (e->kind != RAY_ENCCOL_SINGLE) return 0; + /* a float view's run values are bit patterns: compared as integers they + * would split -0.0 from +0.0, so a float key is read by its values */ + if (e->type == RAY_F32 || e->type == RAY_F64) return 0; + uint8_t enc = ray_enccol_descs(e, seg / RAY_ENC_VECS_PER_CHUNK)[seg % RAY_ENC_VECS_PER_CHUNK].encoding; + if (enc != RAY_ENC_RLE && enc != RAY_ENC_CONST) return 0; + int r = ray_col_src_vview(src, seg, vv, err); + if (r <= 0) return r; + if ((vv->enc != RAY_ENC_RLE && vv->enc != RAY_ENC_CONST) || vv->n != len || + vv->nullmap || (vv->n_nulls && rr->key_types[k] != RAY_SYM)) return 0; + return 1; +} + +/* A key's reader inside one segment: its runs (a run view, the current + * run tracked) or its values (the cursor's decoded view, or in place). */ +typedef struct { + bool runs; + ray_enc_vview_t* vv; + uint32_t ri; /* runs: the current run */ + const void* data; /* values: element 0 is the segment's row 0 */ + uint8_t attrs; +} agg_firstn_kr_t; + +static inline int64_t agg_firstn_run_val(const ray_enc_vview_t* vv, uint32_t r) { + return ray_enc_logical(agg_vv_lane(&vv->run_vals, vv->k.T, r), vv->k); +} + +/* The other key's reader at segment row 0, made on first use. */ +static ray_t* agg_firstn_kr_open(const agg_rr_t* rr, agg_curs_t* cs, uint32_t k, int64_t seg, int64_t len, + ray_enc_vview_t* vv, agg_firstn_kr_t* kr) { + const int64_t b = seg * RAY_MORSEL_ELEMS; + ray_t* err = NULL; + kr->vv = vv; kr->ri = 0; + int r = agg_firstn_runview(rr, k, seg, len, vv, &err); + if (r < 0) return err; + kr->runs = r > 0; + if (kr->runs) return NULL; + if (!rr->srcs[k]) { + kr->data = (const char*)rr->plain[k] + (size_t)b * rr->esz[k]; + kr->attrs = rr->key_attrs[k]; + return NULL; + } + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(&cs->cur[k], b, &v)) != NULL) return err; + kr->data = NULL; /* the segment across views (a published materialization + * read from an earlier row): the caller walks it */ + if (v->start > b || v->start + v->n < b + len) return NULL; + kr->data = (const char*)v->data + (size_t)(b - v->start) * ray_sym_elem_size(v->type, v->attrs); + kr->attrs = v->attrs; + return NULL; +} + +/* Pass 2 of segment `seg` (one vector: single-file vectors are morsel + * aligned) driven by a key whose vector is a run view: a run whose value + * no group holds (agg_firstn_member) is skipped whole, and only a member + * run reads the other key, by its runs (a member sub-span probed once) + * or by its values (each row probed). Nothing is decoded but the other + * key's vector, and only when a member run needs it. A row matches when + * its whole tuple is in the set (agg_firstn_probe), as in the plain pass; + * matches go out in row order. 1 served, 0 no key is a run view (the + * caller walks the segment), -1 with *err. */ +/* One or two keys (the driving key and the other one), their views on + * the task's stack (vv[AGG_CURS_LENT]). */ +_Static_assert(AGG_CURS_LENT >= 2, "agg_firstn_runs keeps two run views"); +static int agg_firstn_runs(agg_firstn_piece_t* t, agg_curs_t* cs, ray_enc_vview_t* vv, int64_t seg, int64_t len, + ray_t** err) { + const agg_firstn_ctx_t* c = t->c; + const agg_rr_t* rr = c->rr; + agg_firstn_set_t* set = c->set; + const uint32_t nk = rr->n_keys; + uint32_t dk = 0; + int r = 0; + for (; dk < nk; dk++) { + r = agg_firstn_runview(rr, dk, seg, len, &vv[0], err); + if (r != 0) break; + } + if (r <= 0) return r; /* -1, or no key on runs */ + const uint32_t ok = nk == 2 ? 1 - dk : 0; /* the other key */ + agg_firstn_kr_t o = { .runs = false }; + bool o_open = false; + const ray_enc_vview_t* dv = &vv[0]; + const int64_t b = seg * RAY_MORSEL_ELEMS; + int64_t q = t->ix ? t->j : 0; + int64_t p = 0; + for (uint32_t ri = 0; ri < dv->n_runs && p < len; ri++) { + const int64_t e = dv->run_ends.h[ri]; + const int64_t dval = agg_firstn_run_val(dv, ri); + /* the run's rows of interest: [p, e), or its selected rows */ + int64_t q1 = q; + if (t->ix) while (q1 < t->j_end && t->ix[q1] < e) q1++; + bool any = t->ix ? q1 > q : true; + if (!any || !agg_firstn_member(c, dk, dval)) { p = e; q = q1; continue; } + t->kv[dk] = dval; + if (nk == 1) { + if (agg_firstn_probe(set, t->kv, agg_firstn_hash(t->kv, 1), false) >= 0) { + if (t->ix) for (int64_t z = q; z < q1; z++) { if (t->n < t->out_cap) t->out[t->n] = b + t->ix[z]; t->n++; } + else for (int64_t z = p; z < e; z++) { if (t->n < t->out_cap) t->out[t->n] = b + z; t->n++; } + } + p = e; q = q1; + continue; + } + if (!o_open) { + if ((*err = agg_firstn_kr_open(rr, cs, ok, seg, len, &vv[1], &o)) != NULL) return -1; + if (!o.runs && !o.data) return 0; /* nothing emitted yet: the caller walks the segment */ + o_open = true; + } + /* the run's rows, in order: every row, or the selected ones */ + for (int64_t z = t->ix ? q : p; z < (t->ix ? q1 : e); ) { + const int64_t row = t->ix ? t->ix[z] : z; + int64_t span_end; /* rows [row, span_end) share the other key's value */ + int64_t oval; + if (o.runs) { + while (o.vv->run_ends.h[o.ri] <= row) o.ri++; + oval = agg_firstn_run_val(o.vv, o.ri); + span_end = o.vv->run_ends.h[o.ri] < e ? o.vv->run_ends.h[o.ri] : e; + } else { + oval = agg_read_key_i64_raw(rr->key_types[ok], o.attrs, o.data, row); + span_end = row + 1; + } + int64_t z1 = z + 1; /* the indices the span covers */ + if (t->ix) while (z1 < q1 && t->ix[z1] < span_end) z1++; + else z1 = span_end; + if (agg_firstn_member(c, ok, oval)) { + t->kv[ok] = oval; + if (agg_firstn_probe(set, t->kv, agg_firstn_hash(t->kv, 2), false) >= 0) + for (int64_t w = z; w < z1; w++) { + if (t->n < t->out_cap) t->out[t->n] = b + (t->ix ? t->ix[w] : w); + t->n++; + } + } + z = z1; + } + p = e; q = q1; + } + if (t->ix && q < t->j_end) /* a selected row past the segment */ + { *err = ray_error("corrupt", "first-n: selection row %lld past its segment", (long long)(b + t->ix[q])); return -1; } + if (t->ix) t->j = t->j_end; + return 1; +} + +/* agg_firstn_task over staged keys: its segments walked through one cursor + * set (ray_col_walk_cur), a range error noted keyed by its first row. With + * one or two keys, a segment driven by a key on runs is served on runs + * (agg_firstn_runs, the views on the task's stack). */ +static void agg_firstn_task_staged(agg_firstn_ctx_t* c, uint32_t t) { + int64_t s0 = (int64_t)c->n_segs * t / c->tasks; + int64_t s1 = (int64_t)c->n_segs * (t + 1) / c->tasks; + const agg_rr_t* rr = c->rr; + const uint8_t* fl = c->sel ? ray_rowsel_flags(c->sel) : NULL; + const uint32_t* of = c->sel ? ray_rowsel_offsets(c->sel) : NULL; + uint64_t hb[RAY_MORSEL_ELEMS]; + ray_enc_vview_t vv[AGG_CURS_LENT]; /* agg_firstn_runs' views, never zeroed */ + agg_firstn_piece_t pc = { .c = c, .hb = hb, .kv = c->kvs + (int64_t)t * c->n_keys, + .out = c->out ? c->out + c->counts[t] : c->local + (int64_t)t * AGG_FIRSTN_LOCAL, + .out_cap = c->out ? INT64_MAX : AGG_FIRSTN_LOCAL, .n = 0 }; + const int64_t key = s0 * RAY_MORSEL_ELEMS; + agg_curs_t cs; cs.cur = NULL; + if (s0 < s1 && !ray_scan_fail_skip(rr->fail, key)) { + if (!agg_curs_init(&cs, rr)) ray_scan_fail_note(rr->fail, key, ray_error("oom", NULL)); + for (int64_t seg = s0; cs.cur && seg < s1; seg++) { + if (fl && fl[seg] == RAY_SEL_NONE) continue; + int64_t b = seg * RAY_MORSEL_ELEMS; + int64_t len = c->nrows - b < RAY_MORSEL_ELEMS ? c->nrows - b : RAY_MORSEL_ELEMS; + bool mix = fl && fl[seg] == RAY_SEL_MIX; + pc.seg_b = b; + pc.ix = mix ? ray_rowsel_idx(c->sel) : NULL; + pc.j = mix ? (int64_t)of[seg] : 0; + pc.j_end = mix ? (int64_t)of[seg + 1] : 0; + ray_t* err = NULL; + int ru = rr->n_keys <= 2 ? agg_firstn_runs(&pc, &cs, vv, seg, len, &err) : 0; + if (ru < 0) { ray_scan_fail_note(rr->fail, key, err); break; } + if (ru > 0) continue; + err = ray_col_walk_cur(rr->srcs, rr->plain, rr->n_src, cs.cur, b, b + len, &pc, 0, agg_firstn_piece); + if (err) { ray_scan_fail_note(rr->fail, key, err); break; } + } + agg_curs_free(&cs, rr); + } + if (!c->out) c->counts[t] = pc.n; +} + +static void agg_firstn_fn_staged(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + for (int64_t t = start; t < end; t++) agg_firstn_task_staged((agg_firstn_ctx_t*)raw, (uint32_t)t); +} + static bool agg_firstn_admitted(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl, ray_t** key_cols) { for (uint32_t k = 0; k < ext->n_keys; k++) @@ -6851,10 +11456,10 @@ static bool agg_firstn_admitted(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl, if (!has_in) { if (aop == OP_COUNT) continue; return false; } ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); if (!ie || ie->base.opcode != OP_SCAN) return false; - ray_t* col = ray_table_get_col(tbl, ie->sym); - if (!col) return false; + ray_col_meta_t cm; + if (!agg_col_meta(g, tbl, ie->sym, &cm)) return false; if (aop == OP_COUNT) continue; - switch (col->type) { + switch (cm.type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: break; default: return false; /* floats: the fold order shows in the value */ @@ -6863,21 +11468,67 @@ static bool agg_firstn_admitted(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl, return true; } +/* Map the rows of a group result (key columns okc, sub_rows rows) to the + * set's ranks: perm[rank] = row. Rows of groups outside the set are skipped, + * or fail the pick (-1) when `strict` (every row must be a set group). The + * key columns are hashed a block at a time; only bloom hits read the tuple + * and probe. Returns the number of set groups found, -1 on a mismatch. Kept + * out of line: the pre-pass's serial probe loop stays small. */ +static __attribute__((noinline)) int64_t agg_firstn_pick( + agg_firstn_set_t* set, ray_t** okc, uint32_t n_keys, int64_t sub_rows, + uint32_t bbits, bool strict, int64_t* perm, int64_t* kv, bool* identity) { + uint64_t hb[1024]; + const void* okd[16]; + for (uint32_t k = 0; k < n_keys; k++) okd[k] = ray_data(okc[k]); + uint32_t bshift = 64 - bbits; + int64_t found = 0; + for (int64_t b0 = 0; b0 < sub_rows; b0 += 1024) { + int64_t len = sub_rows - b0 < 1024 ? sub_rows - b0 : 1024; + for (int64_t i = 0; i < len; i++) hb[i] = AGG_FIRSTN_SEED; + for (uint32_t k = 0; k < n_keys; k++) agg_firstn_hash_block(hb, okc[k], okd[k], b0, len); + for (int64_t i = 0; i < len; i++) { + int64_t r = b0 + i; + uint64_t hv = AGG_FIRSTN_FINAL(hb[i]); + uint64_t bit = hv >> bshift; + int64_t rk = -1; + if ((set->bloom[bit >> 6] >> (bit & 63)) & 1) { + for (uint32_t k = 0; k < n_keys; k++) kv[k] = agg_read_key_i64(okc[k], okd[k], r); + rk = agg_firstn_probe(set, kv, hv, false); + } + if (rk < 0) { if (strict) return -1; continue; } + if (perm[rk] >= 0) return -1; + perm[rk] = r; + found++; + if (rk != r) *identity = false; + } + } + return found; +} + /* The first `group_limit` groups in first-seen order, an error, or NULL when * the shape or the data is not one the pre-pass serves (the caller then runs * the full aggregation). */ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t nrows, - ray_t** key_cols, ray_t* sel, int64_t n_sel, - int64_t group_limit) { + ray_t** key_cols, agg_keyset_t* ks, ray_t* sel, const int64_t* sel_prefix, + int64_t n_sel, int64_t group_limit, + bool allow_heavy, bool* heavy_out) { ray_op_ext_t* ext = find_ext(g, op->id); ray_pool_t* pool = ray_pool_get(); int64_t eff_n = sel ? n_sel : nrows; + /* A segment-streamed table (an unordered take over generation-2 parted + * keys, group_seg_stream_ok) runs the passes over its parted sources; + * every decline then runs the whole group over its flat copy, the only + * full run its unordered take has. */ + const bool seg = group_limit > 0 && agg_seg_parted(g, tbl); /* Only where the full run would take the parallel first-seen routes. */ if (!ray_agg_first_n || firstn_nested || !pool || eff_n < RAY_PARALLEL_THRESHOLD || - group_limit <= 0 || group_limit > AGG_FIRSTN_MAX || !ext) - return NULL; - if (sel && ray_rowsel_meta(sel)->nrows != nrows) return NULL; - if (!agg_firstn_admitted(g, ext, tbl, key_cols)) return NULL; + group_limit <= 0 || group_limit > AGG_FIRSTN_MAX || !ext || + (sel && ray_rowsel_meta(sel)->nrows != nrows) || !agg_firstn_admitted(g, ext, tbl, key_cols)) + return seg ? agg_seg_flat_run(g, op, tbl, nrows, sel, sel_prefix, n_sel, group_limit, NULL) : NULL; + /* Staged keys (generation 2) are read through their sources at rows, by + * the staged instances of the passes; nothing is unstaged. A declined + * pre-pass leaves the full run on the staged keys. */ + const agg_rr_t* krr = ks->rr.staged ? &ks->rr : NULL; uint32_t n_keys = ext->n_keys; uint32_t bits = 4; @@ -6899,6 +11550,8 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t int64_t* perm = NULL; ray_t* compact = NULL; ray_t* sub = NULL; + int64_t* mem_v = NULL; + uint8_t* mem_used = NULL; if (!kv || !set.keys || !set.rank || !set.bloom) { res = ray_error("oom", NULL); goto done; } memset(set.rank, 0xFF, (size_t)cap * sizeof(int32_t)); const void** key_data = (const void**)(kv + n_keys); @@ -6906,7 +11559,11 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t uint32_t n_segs = (uint32_t)((nrows + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS); /* 1. the first N distinct tuples, serially from the first selected row */ - { + if (krr) { + ray_t* e1 = agg_firstn_seen_staged(krr, &set, sel, nrows, n_segs, group_limit, kv); + if (e1) { res = e1; goto done; } + if (set.n < group_limit) goto done; /* few groups or long runs: full run */ + } else { const uint8_t* fl = sel ? ray_rowsel_flags(sel) : NULL; const uint32_t* of = sel ? ray_rowsel_offsets(sel) : NULL; const uint16_t* ix = sel ? ray_rowsel_idx(sel) : NULL; @@ -6934,9 +11591,33 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t uint64_t bit = agg_firstn_hash(set.keys + i * n_keys, n_keys) >> (64 - bbits); set.bloom[bit >> 6] |= (uint64_t)1 << (bit & 63); } + if (krr) { + /* the staged pass's per-key member sets (agg_firstn_member): at + * most N values each, in as many slots as the set has */ + mem_v = ray_alloc_raw((size_t)cap * n_keys * sizeof(int64_t)); + mem_used = ray_calloc_raw((size_t)cap * n_keys); + if (!mem_v || !mem_used) { res = ray_error("oom", NULL); goto done; } + for (int64_t i = 0; i < cap; i++) { + if (set.rank[i] < 0) continue; + for (uint32_t k = 0; k < n_keys; k++) { + int64_t x = set.keys[i * n_keys + k]; + int64_t* v = mem_v + (size_t)k * cap; + uint8_t* u = mem_used + (size_t)k * cap; + uint32_t h = agg_firstn_mslot(x, bits); + while (u[h] && v[h] != x) h = (h + 1) & (uint32_t)(cap - 1); + u[h] = 1; v[h] = x; + } + } + } /* the share of rows the N groups hold, from evenly spaced source rows */ - { + if (krr) { + int64_t samples = nrows < AGG_FIRSTN_SAMPLES ? nrows : AGG_FIRSTN_SAMPLES, hits = 0; + ray_t* e1 = agg_firstn_share_staged(krr, &set, nrows, samples, pool, + ray_pool_par_dispatch_ok(pool, eff_n, RAY_PARALLEL_THRESHOLD), &hits); + if (e1) { res = e1; goto done; } + if (hits * AGG_FIRSTN_SHARE > samples) goto heavy; + } else { int64_t samples = nrows < AGG_FIRSTN_SAMPLES ? nrows : AGG_FIRSTN_SAMPLES; int64_t step = nrows / samples, hits = 0; for (uint32_t k = 0; k < n_keys; k++) @@ -6947,7 +11628,7 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t kv[k] = agg_read_key_i64(key_cols[k], key_data[k], i * step); if (agg_firstn_probe(&set, kv, agg_firstn_hash(kv, n_keys), false) >= 0) hits++; } - if (hits * AGG_FIRSTN_SHARE > samples) goto done; + if (hits * AGG_FIRSTN_SHARE > samples) goto heavy; } /* 2. the selected rows of those groups, in row order: each task keeps its @@ -6966,9 +11647,14 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t if (!counts || !local || !kvs) { res = ray_error("oom", NULL); goto done; } agg_firstn_ctx_t c = { .set = &set, .key_cols = key_cols, .key_data = key_data, .n_keys = n_keys, .nrows = nrows, .sel = sel, .n_segs = n_segs, - .tasks = tasks, .counts = counts, .local = local, .out = NULL, .kvs = kvs }; - if (tasks > 1) ray_pool_dispatch_n(pool, agg_firstn_fn, &c, tasks); + .tasks = tasks, .counts = counts, .local = local, .out = NULL, .kvs = kvs, .rr = krr, + .mem_v = mem_v, .mem_used = mem_used, .mem_bits = bits }; + ray_pool_fn pass2 = krr ? agg_firstn_fn_staged : agg_firstn_fn; + if (krr) ray_scan_fail_init(krr->fail); + if (tasks > 1) ray_pool_dispatch_n(pool, pass2, &c, tasks); + else if (krr) agg_firstn_fn_staged(&c, 0, 0, 1); else agg_firstn_fn(&c, 0, 0, 1); + if (krr && (res = ray_scan_fail_finish(krr->fail, tasks > 1 ? pool : NULL)) != NULL) goto done; if (agg_cancelled()) { res = ray_error("cancel", NULL); goto done; } int64_t m = 0; bool spilled = false; @@ -6976,15 +11662,18 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t if (counts[t] > AGG_FIRSTN_LOCAL) spilled = true; m += counts[t]; } - if (m * (AGG_FIRSTN_SHARE / 2) > eff_n) goto done; /* the sample missed a heavy group */ + if (m * (AGG_FIRSTN_SHARE / 2) > eff_n) goto heavy; /* the sample missed a heavy group */ idx = ray_alloc_raw((size_t)(m > 0 ? m : 1) * sizeof(int64_t)); if (!idx) { res = ray_error("oom", NULL); goto done; } if (spilled) { int64_t off = 0; for (uint32_t t = 0; t < tasks; t++) { int64_t ct = counts[t]; counts[t] = off; off += ct; } c.out = idx; - if (tasks > 1) ray_pool_dispatch_n(pool, agg_firstn_fn, &c, tasks); + if (krr) ray_scan_fail_init(krr->fail); + if (tasks > 1) ray_pool_dispatch_n(pool, pass2, &c, tasks); + else if (krr) agg_firstn_fn_staged(&c, 0, 0, 1); else agg_firstn_fn(&c, 0, 0, 1); + if (krr && (res = ray_scan_fail_finish(krr->fail, tasks > 1 ? pool : NULL)) != NULL) goto done; if (agg_cancelled()) { res = ray_error("cancel", NULL); goto done; } } else { int64_t off = 0; @@ -7004,28 +11693,45 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t firstn_nested = true; sub = exec_group_v2_run(g, op, compact, m, NULL, NULL, 0, set.n, NULL); firstn_nested = false; + goto pick; + +heavy: + /* The N groups hold a large share of the rows: aggregating only them + * costs about what aggregating everything does. The bounded full run + * is the answer when it stays on a dense route (the task-local slabs + * select the N smallest first rows); the caller asks again with + * allow_heavy only when it would leave them for radix. Then run the + * unbounded group (dense routes allowed) and pick the N groups of the + * set from its result. */ + if (!allow_heavy) { if (heavy_out) *heavy_out = true; goto done; } + firstn_nested = true; + sub = exec_group_v2_run(g, op, tbl, nrows, sel, sel_prefix, n_sel, 0, NULL); + firstn_nested = false; + +pick: if (!sub || RAY_IS_ERR(sub)) { res = sub ? sub : ray_error("oom", NULL); sub = NULL; goto done; } /* 3. first-seen order: the rank of every emitted group in the set. The - * bounded emit already yields it; any other order is put right here. */ - if (sub->type != RAY_TABLE || ray_table_nrows(sub) != set.n || + * bounded emit already yields it; any other order is put right here; + * the unbounded run's other groups are dropped. */ + int64_t sub_rows = sub->type == RAY_TABLE ? ray_table_nrows(sub) : -1; + if (sub->type != RAY_TABLE || sub_rows < set.n || (compact && sub_rows != set.n) || ray_table_ncols(sub) < (int64_t)n_keys) goto done; /* unexpected shape: full run */ perm = ray_alloc_raw((size_t)set.n * sizeof(int64_t)); if (!perm) { res = ray_error("oom", NULL); goto done; } for (int64_t r = 0; r < set.n; r++) perm[r] = -1; - bool identity = true; - for (int64_t r = 0; r < set.n; r++) { - for (uint32_t k = 0; k < n_keys; k++) { - ray_t* oc = ray_table_get_col_idx(sub, k); - if (!oc || oc->type != key_cols[k]->type) goto done; - kv[k] = agg_read_key_i64(oc, ray_data(oc), r); - } - int64_t rk = agg_firstn_probe(&set, kv, agg_firstn_hash(kv, n_keys), false); - if (rk < 0 || perm[rk] >= 0) goto done; - perm[rk] = r; - if (rk != r) identity = false; + bool identity = sub_rows == set.n; + ray_t* okc[16]; + if (n_keys > 16) goto done; + for (uint32_t k = 0; k < n_keys; k++) { + okc[k] = ray_table_col_idx(sub, k); + if (okc[k] && RAY_IS_ERR(okc[k])) { res = okc[k]; goto done; } + if (!okc[k] || okc[k]->type != key_cols[k]->type) goto done; } + int64_t found = agg_firstn_pick(&set, okc, n_keys, sub_rows, bbits, compact != NULL, + perm, kv, &identity); + if (found != set.n) goto done; if (identity) { res = sub; sub = NULL; } else { ray_t* pv = ray_vec_new(RAY_I64, set.n); @@ -7042,14 +11748,28 @@ static ray_t* agg_first_n_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t } done: - if (sub) ray_release(sub); - if (compact) ray_release(compact); + if (sub) { ray_graph_unbind_table(g, sub); ray_release(sub); } + if (compact) { ray_graph_unbind_table(g, compact); ray_release(compact); } ray_free_raw(perm); ray_free_raw(idx); ray_free_raw(local); ray_free_raw(kvs); ray_free_raw(counts); ray_free_raw(set.keys); ray_free_raw(set.rank); ray_free_raw(set.bloom); + ray_free_raw(mem_v); ray_free_raw(mem_used); if (kv_hdr) scratch_free(kv_hdr); + if (!res && seg) return agg_seg_flat_run(g, op, tbl, nrows, sel, sel_prefix, n_sel, group_limit, NULL); return res; } +/* Bind the group keys (R-BIND) and run the strategies over them. A key + * that is a partition key or a slice keeps ray_table_col; a bound key that + * is not ready (generation 2, not materialized) is staged: its column is a + * stand-in carrying the type, SYM width, domain and nullability, and the + * strategies read it by range. */ +static ray_t* exec_group_v2_run_keys(ray_graph_t* g, ray_op_t* op, ray_t* tbl, + int64_t nrows, ray_t* sel, + const int64_t* sel_prefix, int64_t n_sel, + int64_t group_limit, + const ray_group_emit_filter_t* efp, ray_op_ext_t* ext, + ray_t** key_cols, int64_t* key_syms, agg_keyset_t* ks); + static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t nrows, ray_t* sel, const int64_t* sel_prefix, int64_t n_sel, @@ -7061,27 +11781,77 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, route_stats.dense_plan_available = false; route_stats.dense_worker_budget = false; route_stats.dense_tasks = 0; + route_stats.radix_waves = 0; + route_stats.radix_compacted = 0; + route_stats.radix_spill_bytes = 0; + route_stats.radix_spill_buf = 0; ray_op_ext_t* ext = find_ext(g, op->id); /* efp was already gated on this node by exec_group_v2_run; the compact * fallback recursion re-enters through that wrapper too. */ - /* Exact-size carve for the per-key column pointers + syms (one block, both - * 8-byte): unbounded key count, freed at every exit of this function - * (parallel branches free it beside agg_vo_free; the serial tail frees it - * after the key-emit loop; the compact-fallback macro frees it too). */ + /* Exact-size carve for the per-key columns, syms, sources and read + * tables: unbounded key count, freed (with the stand-ins) when the + * strategies return. */ + uint32_t nk = ext->n_keys; + size_t nkc = nk ? nk : 1; ray_t* kc_hdr; - ray_t** key_cols = (ray_t**)scratch_alloc(&kc_hdr, - (size_t)ext->n_keys * (sizeof(ray_t*) + sizeof(int64_t))); + ray_t** key_cols = (ray_t**)scratch_calloc(&kc_hdr, nkc * (5 * sizeof(void*) + 3)); if (!key_cols) return ray_error("oom", NULL); - int64_t* key_syms = (int64_t*)(key_cols + ext->n_keys); - for (uint32_t k = 0; k < ext->n_keys; k++) { + int64_t* key_syms = (int64_t*)(key_cols + nkc); + ray_t** standins = (ray_t**)(key_syms + nkc); + agg_keyset_t ks; + ks.srcs = (ray_col_src_t**)(standins + nkc); + ks.plain = (const void**)(ks.srcs + nkc); + ks.esz = (uint8_t*)(ks.plain + nkc); + ks.types = (int8_t*)(ks.esz + nkc); + ks.attrs = (uint8_t*)(ks.types + nkc); + ray_t* result = NULL; + bool staged = false; + for (uint32_t k = 0; k < nk; k++) { ray_op_ext_t* kext = find_ext(g, ext->keys[k]); - key_cols[k] = ray_table_get_col(tbl, kext->sym); key_syms[k] = kext->sym; + ray_col_src_t* src = NULL; + if (!ray_col_bind_declines(tbl, kext->sym)) { + ray_t* berr = NULL; + src = ray_graph_bind_col(g, tbl, kext->sym, &berr); /* no decode */ + if (berr) { result = berr; goto out; } + } + ray_t* ready = src ? ray_col_src_ready(src) : NULL; /* never decodes */ + if (ready && !RAY_IS_PARTED(ready->type)) key_cols[k] = ready; + else if (src) { + if (!(standins[k] = agg_src_standin(src))) { result = ray_error("oom", NULL); goto out; } + key_cols[k] = standins[k]; + ks.srcs[k] = src; + staged = true; + } else { + key_cols[k] = ray_table_col(tbl, kext->sym); /* today's column */ + if (key_cols[k] && RAY_IS_ERR(key_cols[k])) { result = key_cols[k]; key_cols[k] = NULL; goto out; } + } + ks.types[k] = key_cols[k]->type; + ks.attrs[k] = key_cols[k]->attrs; + ks.esz[k] = ray_sym_elem_size(key_cols[k]->type, key_cols[k]->attrs); + ks.plain[k] = ks.srcs[k] ? NULL : ray_data(key_cols[k]); if (key_cols[k]->type != RAY_SYM && ray_vec_may_have_nulls(key_cols[k])) route_stats.nullable_key = true; } + ray_scan_fail_init(&ks.fail); + ks.rr = (agg_rr_t){ .srcs = ks.srcs, .plain = ks.plain, .esz = ks.esz, + .key_types = ks.types, .key_attrs = ks.attrs, + .n_src = nk, .n_keys = nk, .n_aggs = 0, .fail = &ks.fail, .staged = staged }; + result = exec_group_v2_run_keys(g, op, tbl, nrows, sel, sel_prefix, n_sel, group_limit, efp, + ext, key_cols, key_syms, &ks); +out: + for (uint32_t k = 0; k < nk; k++) if (standins[k]) ray_release(standins[k]); + scratch_free(kc_hdr); + return result; +} +static ray_t* exec_group_v2_run_keys(ray_graph_t* g, ray_op_t* op, ray_t* tbl, + int64_t nrows, ray_t* sel, + const int64_t* sel_prefix, int64_t n_sel, + int64_t group_limit, + const ray_group_emit_filter_t* efp, ray_op_ext_t* ext, + ray_t** key_cols, int64_t* key_syms, agg_keyset_t* ks) { bool indexed = false; for (uint32_t k = 0; k < ext->n_keys; k++) { int8_t t = key_cols[k]->type; @@ -7089,33 +11859,40 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } for (uint32_t a = 0; a < ext->n_aggs; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); - ray_t* col = ie ? ray_table_get_col(tbl, ie->sym) : NULL; - if (col && agg_indexed_supported(ext->agg_ops[a], col->type)) indexed = true; + ray_col_meta_t cm; + if (ie && agg_col_meta(g, tbl, ie->sym, &cm) && agg_indexed_supported(ext->agg_ops[a], cm.type)) indexed = true; } if (indexed) { if (sel) { ray_t* idx = ray_rowsel_to_indices(sel); - if (!idx || RAY_IS_ERR(idx)) { scratch_free(kc_hdr); return idx ? idx : ray_error("oom", NULL); } + if (!idx || RAY_IS_ERR(idx)) { return idx ? idx : ray_error("oom", NULL); } ray_t* compact = agg_build_compact(g, op, tbl, ray_data(idx), n_sel); ray_t* result = compact && !RAY_IS_ERR(compact) ? exec_group_v2_run(g, op, compact, n_sel, NULL, NULL, 0, group_limit, efp) : compact; - if (compact && !RAY_IS_ERR(compact)) ray_release(compact); - ray_release(idx); scratch_free(kc_hdr); return result; + if (compact && !RAY_IS_ERR(compact)) { ray_graph_unbind_table(g, compact); ray_release(compact); } + ray_release(idx); return result; } + /* random: indexed / serial whole-column strategy */ + if (agg_seg_parted(g, tbl)) + return agg_seg_flat_run(g, op, tbl, nrows, sel, sel_prefix, n_sel, group_limit, efp); agg_route_record(AGG_ROUTE_V2_INDEXED); + ray_t* uerr = agg_keys_unstage(key_cols, ks); + if (uerr) return uerr; ray_t* result = agg_indexed_run(g, op, tbl, key_cols, key_syms, nrows); - scratch_free(kc_hdr); return result; + return result; } /* Unordered take: N — find the N groups first, aggregate only them. */ + bool firstn_heavy = false; /* the N groups hold a large share: see agg_first_n_run */ if (group_limit > 0 && !efp) { - ray_t* fr = agg_first_n_run(g, op, tbl, nrows, key_cols, sel, n_sel, group_limit); - if (fr) { scratch_free(kc_hdr); return fr; } + ray_t* fr = agg_first_n_run(g, op, tbl, nrows, key_cols, ks, sel, sel_prefix, n_sel, + group_limit, false, &firstn_heavy); + if (fr) { return fr; } } /* Precompute AoS state layout for the admitted aggregates. */ agg_vo_t vo; - if (!agg_vo_init(&vo, g, ext, tbl)) { scratch_free(kc_hdr); return ray_error("oom", NULL); } + if (!agg_vo_init(&vo, g, ext, tbl)) { return ray_error("oom", NULL); } const agg_vtable_t** vts = vo.vts; size_t* off = vo.off; size_t block = vo.block; /* Dense plan (low-card int/SYM keys + streaming aggs → direct index, no @@ -7125,9 +11902,10 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * for high-selectivity filters, and it can pull a sparse-but-low-card selected * key set into the dense path that the full-table range would have rejected. */ dense_plan_t dp; - bool dense = sel ? agg_dense_plan_sel(key_cols, ext->n_keys, n_sel, sel, sel_prefix, &dp) - : agg_dense_plan(key_cols, ext->n_keys, vts, ext->n_aggs, nrows, &dp); - route_stats.dense_plan_available = dense; + ray_t* plan_err = NULL; + bool dense = sel ? agg_dense_plan_sel(key_cols, &ks->rr, ext->n_keys, n_sel, sel, sel_prefix, &dp, &plan_err) + : agg_dense_plan_src(key_cols, &ks->rr, ext->n_keys, true, nrows, &dp, &plan_err); + if (plan_err) { agg_vo_free(&vo); agg_dense_plan_free(&dp); return plan_err; } /* Compact-fallback helper for the non-chunked shapes (hash-fallback keys, * and the serial path): gather selected rows into a compact table once and @@ -7135,7 +11913,7 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, #define AGG_RUN_COMPACT_FALLBACK() \ do { \ agg_vo_free(&vo); /* not needed by the compact recursion */ \ - agg_dense_plan_free(&dp); scratch_free(kc_hdr); /* key_cols dead: the recursion rebuilds them */ \ + agg_dense_plan_free(&dp); /* the recursion binds its own keys */ \ ray_t* idxb = ray_rowsel_to_indices(sel); \ if (!idxb) return ray_error("oom", NULL); \ ray_t* compact = agg_build_compact(g, op, tbl, (int64_t*)ray_data(idxb), n_sel); \ @@ -7145,7 +11923,7 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } \ ray_t* r = exec_group_v2_run(g, op, compact, n_sel, NULL, NULL, 0, \ group_limit, efp); \ - ray_release(compact); ray_release(idxb); \ + ray_graph_unbind_table(g, compact); ray_release(compact); ray_release(idxb); \ return r; \ } while (0) @@ -7163,6 +11941,38 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (vts[a]->kind != ACC_STREAMING) all_streaming = false; ray_pool_t* pool = ray_pool_get(); + /* A single-key plan within the row count whose per-worker slabs could + * never fit the dense budget (a quarter of the watermark, or the scatter + * payload when that is less) is a wide plan too: only the one shared slab + * can run it, and the per-worker budget check below must not be the one + * that sends it to the radix route. */ + if (dp.ok && !dp.wide && ext->n_keys == 1 && pool && eff_n >= RAY_PARALLEL_THRESHOLD) { + double budget = (double)eff_n * 2 * (8.0 * (ext->n_keys + ext->n_aggs + 1)); + int64_t wmb = ray_heap_mem_budget(); + if (wmb > 0 && budget > (double)wmb / 4) budget = (double)wmb / 4; + if ((double)dp.total_slots * (double)(block + sizeof(int64_t) + 1) > budget) dp.wide = true; + } + /* A wide plan (one key, range past the row count) runs only as the shared + * strategy: one state slab of the range plus its occupancy bits, which + * must fit three quarters of the room under the anonymous watermark (the + * rest is the emit's), and whose key shows many groups in a sample + * (agg_wide_populated). Any other shape, or too little room, drops the + * plan and the grouping takes the route it took before. */ + if (dp.wide) { + bool shared = pool && eff_n >= RAY_PARALLEL_THRESHOLD && all_streaming && + group_limit <= 0 && ext->n_keys == 1; + ray_t* werr = NULL; + bool fits = shared && agg_wide_shared_fits(vts, ext->n_aggs, block, dp.total_slots, eff_n, + key_cols[0], &ks->rr, nrows, &werr); + if (werr) { agg_vo_free(&vo); agg_dense_plan_free(&dp); return werr; } + if (!fits) { + agg_dense_plan_free(&dp); + dp.ok = false; + dp.wide = false; + } + } + dense = dense && dp.ok; + route_stats.dense_plan_available = dense; if (pool && eff_n >= RAY_PARALLEL_THRESHOLD && all_streaming) { /* A parallel dense plan owns one slot slab per worker. Admit it only * when the aggregate slot count across all workers remains O(input); @@ -7194,15 +12004,23 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } /* A bounded group emit selects first-seen groups. Dense slot order * cannot satisfy that contract; retain radix's bounded selection. */ - bool shared_plan = dp.ok && group_limit <= 0 && !sel && ext->n_keys == 1 && dp.total_slots >= 4096; + bool shared_plan = dp.ok && group_limit <= 0 && (dp.wide || !sel) && ext->n_keys == 1 && dp.total_slots >= 4096; for (uint32_t a = 0; a < ext->n_aggs && shared_plan; a++) - shared_plan = vts[a]->update_shared != NULL; - if (shared_plan && slab_bytes <= dense_budget && agg_shared_sample(g, ext, tbl, key_cols, &vo, nrows)) { + shared_plan = vts[a]->update_shared != NULL && + (dp.wide || !vts[a]->shared_add); /* an atomic add in the shared slab serves wide plans only */ + ray_t* serr = NULL; + bool shared_ok = shared_plan && (dp.wide || (slab_bytes <= dense_budget && + agg_shared_sample(g, ext, tbl, key_cols, &vo, nrows, &serr))); + if (serr) { /* a failed column bind */ + agg_vo_free(&vo); agg_dense_plan_free(&dp); + return serr; + } + if (shared_ok) { route_stats.dense_worker_budget = false; agg_route_record(AGG_ROUTE_V2_DENSE); ray_t* result = exec_group_v2_parallel_dense(g, op, tbl, key_cols, key_syms, ext, nrows, pool, &dp, dense_workers, AGG_DENSE_SHARED, sel, sel_prefix, n_sel, efp, 0); - agg_vo_free(&vo); agg_dense_plan_free(&dp); scratch_free(kc_hdr); + agg_vo_free(&vo); agg_dense_plan_free(&dp); return result; } /* Partition ownership amortizes scatter through concurrent reducers. @@ -7217,9 +12035,13 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * occupy one field in the payload, including mixed binary uses. */ agg_desc_t payload; double record_size = (double)SIZE_MAX; - if (agg_desc_init(&payload, g, ext, tbl, key_cols)) { + ray_t* perr = NULL; + if (agg_desc_init(&payload, g, ext, tbl, key_cols, &perr)) { record_size = agg_partition_record(&payload, ext->n_aggs, NULL, NULL); agg_desc_free(&payload); + } else if (perr) { /* a failed column bind */ + agg_vo_free(&vo); agg_dense_plan_free(&dp); + return perr; } double bytes = 2.0 * part_slots * parts * (block + sizeof(int64_t)) + (double)eff_n * (sizeof(uint32_t) + record_size + (sel ? sizeof(int64_t) : 0)) @@ -7251,7 +12073,7 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, agg_route_record(AGG_ROUTE_V2_DENSE); ray_t* result = exec_group_v2_parallel_dense(g, op, tbl, key_cols, key_syms, ext, nrows, pool, &dp, dense_workers, AGG_DENSE_PARTITIONED, sel, sel_prefix, n_sel, efp, 0); - agg_vo_free(&vo); agg_dense_plan_free(&dp); scratch_free(kc_hdr); + agg_vo_free(&vo); agg_dense_plan_free(&dp); return result; } } @@ -7271,9 +12093,12 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * exceeds one scatter payload. This affects strategy only, never values; * selections keep their existing exact selected-range planning. */ if (dense_par_ok && !sel && ext->n_keys == 1) { - const void* data = ray_data(key_cols[0]); + /* a staged key: strided single rows through a cursor (R-SPARSE) */ + agg_curs_t tcs; tcs.cur = NULL; + ray_t* terr = NULL; + if (ks->rr.staged && !agg_curs_init(&tcs, &ks->rr)) terr = ray_error("oom", NULL); double touched_slots = 0; - if (ray_col_cold(key_cols[0])) + if (!ks->rr.staged && ray_col_cold(key_cols[0])) for (uint32_t w = 0; w < dense_workers; w++) { int64_t start = nrows / dense_workers * w; int64_t end = w + 1 == dense_workers ? nrows : nrows / dense_workers * (w + 1); @@ -7282,23 +12107,44 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_col_want_row(key_cols[0], start + i * ((end - start - 1) / (samples > 1 ? samples - 1 : 1))); } - for (uint32_t w = 0; w < dense_workers; w++) { + for (uint32_t w = 0; w < dense_workers && !terr; w++) { int64_t start = nrows / dense_workers * w; int64_t end = w + 1 == dense_workers ? nrows : nrows / dense_workers * (w + 1); int64_t samples = end - start < 1024 ? end - start : 1024; int64_t lo = INT64_MAX, hi = INT64_MIN; - for (int64_t i = 0; i < samples; i++) { + for (int64_t i = 0; i < samples && !terr; i++) { int64_t r = start + i * ((end - start - 1) / (samples > 1 ? samples - 1 : 1)); - int64_t v = agg_read_key_i64(key_cols[0], data, r); + int64_t v = agg_key_at(&ks->rr, &tcs, 0, r, &terr); if (dp.nullable[0] && v == dp.nulls[0]) continue; if (v < lo) lo = v; if (v > hi) hi = v; } if (lo <= hi) touched_slots += (double)((uint64_t)hi - (uint64_t)lo) + 1; } + agg_curs_free(&tcs, &ks->rr); + if (terr) { agg_vo_free(&vo); agg_dense_plan_free(&dp); return terr; } if (touched_slots * (block + sizeof(int64_t) + 1) > scatter_budget / 2) dense_par_ok = false; } + /* No per-worker or partitioned dense plan fits the budget: a single + * key still runs as the one shared slab of a wide plan, as when its + * slab alone passes the budget, rather than scattered by radix. */ + if (dp.ok && !dp.wide && !dense_par_ok && ext->n_keys == 1 && group_limit <= 0) { + ray_t* werr = NULL; + bool fits = agg_wide_shared_fits(vts, ext->n_aggs, block, dp.total_slots, eff_n, + key_cols[0], &ks->rr, nrows, &werr); + if (werr) { agg_vo_free(&vo); agg_dense_plan_free(&dp); return werr; } + if (fits) { + dp.wide = true; + route_stats.dense_worker_budget = false; + ray_profile_tick("group: wide shared after the worker budget"); + agg_route_record(AGG_ROUTE_V2_DENSE); + ray_t* result = exec_group_v2_parallel_dense(g, op, tbl, key_cols, key_syms, ext, + nrows, pool, &dp, ray_pool_total_workers(pool), AGG_DENSE_SHARED, sel, sel_prefix, n_sel, efp, 0); + agg_vo_free(&vo); agg_dense_plan_free(&dp); + return result; + } + } route_stats.dense_worker_budget = dp.ok && !dense_par_ok; if (route_stats.nullable_key) ray_profile_tick("group: nullable key"); if (route_stats.dense_worker_budget) ray_profile_tick("group: dense worker budget exceeded"); @@ -7336,15 +12182,30 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, agg_route_record(AGG_ROUTE_V2_DENSE); ray_t* r = exec_group_v2_parallel_dense(g, op, tbl, key_cols, key_syms, ext, nrows, pool, &dp, dense_workers, AGG_DENSE_TASK_LOCAL, sel, sel_prefix, n_sel, efp, group_limit); - agg_vo_free(&vo); agg_dense_plan_free(&dp); scratch_free(kc_hdr); return r; + agg_vo_free(&vo); agg_dense_plan_free(&dp); return r; + } + if (keys_intsym && firstn_heavy && dp.ok) { + /* A dense plan exists but the bounded emit leaves the dense + * routes here (partition ownership and the shared slab take no + * limit): the unbounded group keeps them, and the N groups are + * picked from it. Without a dense plan both runs are radix and + * the bounded one selects the N groups itself. */ + ray_t* fr = agg_first_n_run(g, op, tbl, nrows, key_cols, ks, sel, sel_prefix, n_sel, + group_limit, true, NULL); + if (fr) { agg_vo_free(&vo); agg_dense_plan_free(&dp); return fr; } } if (keys_intsym) { /* Sparse ranges and excessive dense worker traffic: pre-aggregate * per task and scatter only the all-distinct tails (table stack); * the radix scatter remains available behind the knob. */ + if (agg_force_smallhash) { + ray_t* r = exec_group_v2_parallel_smallhash(g, op, tbl, nrows, + key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel); + agg_vo_free(&vo); agg_dense_plan_free(&dp); return r; + } ray_t* r = ray_agg_tablestack ? exec_group_v2_parallel_tablestack(g, op, tbl, nrows, - key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel, + key_cols, key_syms, &ks->rr, vts, off, block, sel, sel_prefix, n_sel, group_limit, efp) : NULL; if (!r) { /* declined by its sample gate (or disabled) */ @@ -7353,13 +12214,20 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel, group_limit, efp); } - agg_vo_free(&vo); agg_dense_plan_free(&dp); scratch_free(kc_hdr); return r; + agg_vo_free(&vo); agg_dense_plan_free(&dp); return r; } /* Hash fallback (F64 / STR keys): not a chunked strategy — compact. */ if (sel) AGG_RUN_COMPACT_FALLBACK(); + /* random: indexed / serial whole-column strategy */ + if (agg_seg_parted(g, tbl)) { + agg_vo_free(&vo); agg_dense_plan_free(&dp); + return agg_seg_flat_run(g, op, tbl, nrows, sel, sel_prefix, n_sel, group_limit, efp); + } agg_route_record(AGG_ROUTE_V2_INDEXED); + ray_t* uerr = agg_keys_unstage(key_cols, ks); + if (uerr) { agg_vo_free(&vo); agg_dense_plan_free(&dp); return uerr; } { ray_t* r = agg_indexed_run(g, op, tbl, key_cols, key_syms, nrows); - agg_vo_free(&vo); agg_dense_plan_free(&dp); scratch_free(kc_hdr); return r; } + agg_vo_free(&vo); agg_dense_plan_free(&dp); return r; } } /* Serial path does not consult the vts/off tables (per-agg vt is re-resolved @@ -7370,22 +12238,29 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * count is below the parallel threshold here → small; not a perf blocker). */ if (sel) AGG_RUN_COMPACT_FALLBACK(); + /* random: indexed / serial whole-column strategy */ + if (agg_seg_parted(g, tbl)) { + agg_dense_plan_free(&dp); + return agg_seg_flat_run(g, op, tbl, nrows, sel, sel_prefix, n_sel, group_limit, efp); + } agg_route_record(dense ? AGG_ROUTE_V2_SERIAL_DENSE : AGG_ROUTE_V2_SERIAL_HASH); + ray_t* uerr = agg_keys_unstage(key_cols, ks); + if (uerr) { agg_dense_plan_free(&dp); return uerr; } agg_groups_t groups = {0}; int grp_rc = dense ? agg_group_keys_dense(key_cols, nrows, &dp, &groups) : agg_group_keys(key_cols, ext->n_keys, nrows, &groups); - if (grp_rc != 0) { agg_dense_plan_free(&dp); scratch_free(kc_hdr); return ray_error("oom", NULL); } + if (grp_rc != 0) { agg_dense_plan_free(&dp); return ray_error("oom", NULL); } ray_t* result = ray_table_new(ext->n_keys + ext->n_aggs); - if (!result || RAY_IS_ERR(result)) { agg_dense_plan_free(&dp); scratch_free(kc_hdr); agg_groups_free(&groups); return ray_error("oom", NULL); } + if (!result || RAY_IS_ERR(result)) { agg_dense_plan_free(&dp); agg_groups_free(&groups); return ray_error("oom", NULL); } for (uint32_t k = 0; k < ext->n_keys; k++) { ray_t* kc = ray_group_gather(key_cols[k], groups.first_row, groups.ngroups); - if (!kc || RAY_IS_ERR(kc)) { agg_dense_plan_free(&dp); scratch_free(kc_hdr); agg_groups_free(&groups); ray_release(result); return kc ? kc : ray_error("oom", NULL); } + if (!kc || RAY_IS_ERR(kc)) { agg_dense_plan_free(&dp); agg_groups_free(&groups); ray_release(result); return kc ? kc : ray_error("oom", NULL); } result = ray_table_add_col(result, key_syms[k], kc); ray_release(kc); } - agg_dense_plan_free(&dp); scratch_free(kc_hdr); /* key_cols/key_syms done — agg loop below reads neither */ + agg_dense_plan_free(&dp); /* key_cols/key_syms done — agg loop below reads neither */ for (uint32_t a = 0; a < ext->n_aggs; a++) { ray_op_ext_t* ie = find_ext(g, ext->agg_ins[a]); @@ -7393,12 +12268,15 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* col; if (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) { /* binary agg (pearson) */ ray_op_ext_t* ye = find_ext(g, ext->agg_ins2[a]); - ray_t* x_col = ray_table_get_col(tbl, ie->sym); - ray_t* y_col = ray_table_get_col(tbl, ye->sym); + ray_t* x_col = ray_table_col(tbl, ie->sym); + if (x_col && RAY_IS_ERR(x_col)) { agg_groups_free(&groups); ray_release(result); return x_col; } + ray_t* y_col = ray_table_col(tbl, ye->sym); + if (y_col && RAY_IS_ERR(y_col)) { agg_groups_free(&groups); ray_release(result); return y_col; } const agg_vtable_t* vt = agg_resolve(ext->agg_ops[a], x_col->type); col = agg_run_one_bin(vt, x_col, y_col, groups.gids, nrows, groups.ngroups, kparam); } else { - ray_t* val_col = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_get_col(tbl, ie->sym) : NULL; + ray_t* val_col = (ext->agg_ops[a] != OP_COUNT && ie) ? ray_table_col(tbl, ie->sym) : NULL; + if (val_col && RAY_IS_ERR(val_col)) { agg_groups_free(&groups); ray_release(result); return val_col; } int8_t in_type = val_col ? val_col->type : RAY_I64; const agg_vtable_t* vt = agg_resolve(ext->agg_ops[a], in_type); col = agg_run_one(vt, val_col, groups.gids, nrows, groups.ngroups, kparam); @@ -7465,9 +12343,31 @@ static ray_t* agg_build_compact(ray_graph_t* g, ray_op_t* op, ray_t* tbl, return compact ? compact : ray_error("oom", NULL); } for (uint32_t i = 0; i < n_want; i++) { - ray_t* src = ray_table_get_col(tbl, want[i]); + /* A parted column only on a segment-streamed table, from its + * first-N pre-pass over generation-2 keys (an in-place concat group + * runs no selection, group_seg_stream_ok): gathered by range like + * an encoded one, a plain parted wrapper from its segments. */ + ray_t* gcol = NULL; + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc(tbl, want[i])); + ray_col_meta_t pm; + if (!enc && g->grp_seg_stream && ray_table_col_meta(tbl, want[i], &pm) && RAY_IS_PARTED(pm.type)) + enc = ray_table_slot(tbl, want[i]); + if (enc) { + /* generation 2 (or a parted column): the survivors' vectors, + * decoded or point-read by range (idx ascending); the gather's + * result is as fresh as gather_by_idx's */ + ray_t* err = ray_col_gather_enc(enc, NULL, true, idx, n_sel, &gcol); + if (err) { ray_release(compact); scratch_free(want_hdr); return err; } + compact = ray_table_add_col(compact, want[i], gcol); + ray_release(gcol); + if (!compact || RAY_IS_ERR(compact)) { scratch_free(want_hdr); return compact ? compact : ray_error("oom", NULL); } + continue; + } + ray_t* src = ray_table_col(tbl, want[i]); + if (src && RAY_IS_ERR(src)) { ray_release(compact); scratch_free(want_hdr); return src; } if (!src) { ray_release(compact); scratch_free(want_hdr); return ray_error("nyi", NULL); } - ray_t* gcol = gather_by_idx(src, idx, n_sel); /* fresh, no alias */ + assert(!RAY_IS_PARTED(src->type)); + gcol = gather_by_idx(src, idx, n_sel); /* fresh, no alias */ if (!gcol || RAY_IS_ERR(gcol)) { ray_release(compact); scratch_free(want_hdr); return gcol ? gcol : ray_error("oom", NULL); @@ -7539,18 +12439,6 @@ ray_t* exec_group_v2(ray_graph_t* g, ray_op_t* op, ray_t* tbl, return result; } -/* Read element `row` of an integer/temporal/SYM column widened to int64. */ -static inline int64_t agg_read_key_i64(ray_t* col, const void* data, int64_t row) { - switch (col->type) { - case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)data)[row]; - case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)data)[row]; - case RAY_I16: return ((const int16_t*)data)[row]; - case RAY_U8: case RAY_BOOL: return ((const uint8_t*)data)[row]; - case RAY_SYM: return (int64_t)ray_read_sym(data, row, col->type, col->attrs); - default: return 0; /* gate guarantees only the above reach here */ - } -} - ray_t* agg_run_one(const agg_vtable_t* vt, ray_t* val_col, const uint32_t* gids, int64_t nrows, int64_t ngroups, int64_t kparam) { @@ -7730,6 +12618,24 @@ static uint64_t agg_list_key_hash(ray_t* value, const ray_group_sym_view_t* view for (int64_t i = 0; i < value->len; i++) hash = ray_hash_combine(hash, agg_list_key_hash(children[i], view)); return hash; } + /* TABLE / DICT cells compare in atom_eq (the fallthrough of + * agg_list_key_eq). Hashing their names and columns only spreads the + * buckets: the fallback hash (type and length) puts every table of one + * length in one bucket, a linear scan per row. */ + if (value->type == RAY_TABLE) { + int64_t nc = ray_table_ncols(value); + uint64_t hash = ray_hash_i64(nc); + for (int64_t c = 0; c < nc; c++) { + hash = ray_hash_combine(hash, ray_hash_i64(ray_table_col_name(value, c))); + ray_t* col = ray_table_col_idx(value, c); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); col = NULL; } /* hashes as absent */ + hash = ray_hash_combine(hash, agg_list_key_hash(col, view)); + } + return hash; + } + if (value->type == RAY_DICT) + return ray_hash_combine(agg_list_key_hash(ray_dict_keys(value), view), + agg_list_key_hash(ray_dict_vals(value), view)); if (value->type == RAY_SYM || value->type == RAY_STR) { uint64_t hash = ray_hash_i64(value->type); for (int64_t i = 0; i < value->len; i++) { @@ -8160,7 +13066,8 @@ ray_t* agg_select_distinct(ray_t* tbl, ray_t** key_cols, const int64_t* key_syms for (int j = 0; j < keep_n; j++) if (keep_syms[j] == cn) { req = true; break; } if (!req) continue; } - ray_t* sc = ray_table_get_col_idx(tbl, c); + ray_t* sc = ray_table_col_idx(tbl, c); + if (sc && RAY_IS_ERR(sc)) { agg_groups_free(&groups); ray_release(result); return sc; } if (!sc) continue; ray_t* dc = agg_gather_col_at(sc, groups.first_row, groups.ngroups); if (!dc || RAY_IS_ERR(dc)) { diff --git a/src/ops/agg_engine.h b/src/ops/agg_engine.h index 4814e15c4..9490f33ef 100644 --- a/src/ops/agg_engine.h +++ b/src/ops/agg_engine.h @@ -5,6 +5,7 @@ #include #include "ops/internal.h" /* ray_graph_t, ray_op_t, ray_op_ext_t, find_ext */ #include "ops/agg_acc.h" /* agg_vtable_t */ +#include "table/sym.h" /* ray_read_sym */ /* Test/feature knob: route OP_GROUP through the v2 engine when it can handle * the query (see agg_v2_can_handle). Enabled by default. */ @@ -19,6 +20,52 @@ extern bool ray_agg_first_n; * all-distinct tails; off = the former radix scatter of every row. */ extern bool ray_agg_tablestack; +/* Test knob: payload bytes one radix wave may hold when a top-N (`desc: AGG + * take: N`) grouping is split into waves (agg_radix_wave_plan). 0 = derive + * the bound from the heap's anonymous watermark; tests lower it to split + * small inputs; negative = neither waves nor the per-partition top-N + * reduction (the one-pass radix the reduction must reproduce). */ +extern int64_t ray_agg_radix_wave_bytes; +/* Test knob: how the later waves of a split run get their records. 0 = by + * bytes moved (agg_radix_spill_wanted), 1 = always re-scan the input, + * 2 = always spill to a file when there is more than one wave; 3..6 spill + * like 2 and inject a fault: 3 = every read-back fails, 4 = every write + * fails, 5 = the pool is cancelled during the first read-back, 6 = the pool + * is cancelled when a later wave is reduced. */ +extern int ray_agg_radix_spill; + +/* Unordered take: N first-N limits, shared by the pre-pass (agg_first_n_run) + * and the parted group's first-key scan (group.c). */ +#define AGG_FIRSTN_MAX 1024 /* largest take: N the pre-pass serves */ +#define AGG_FIRSTN_PROBE_ROWS 65536 /* prefix budget for the serial scan, at least */ + +/* The group's transient-state budget: the dense compaction's per-task + * bitmaps (agg_engine.c) and the null fills a ragged parted group builds + * for one query (group.c, grp_synth_plain) stay within it. */ +#define AGG_COMPACT_BITMAP_BUDGET ((size_t)32 << 20) + +/* Read element `i` of integer/temporal/SYM data of `type` widened to int64; + * a SYM element's width comes from `attrs` (a column's, or a range piece's). */ +static inline int64_t agg_read_key_i64_raw(int8_t type, uint8_t attrs, const void* data, int64_t i) { + switch (type) { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)data)[i]; + case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)data)[i]; + case RAY_I16: return ((const int16_t*)data)[i]; + case RAY_U8: case RAY_BOOL: return ((const uint8_t*)data)[i]; + case RAY_SYM: return (int64_t)ray_read_sym(data, i, RAY_SYM, attrs); + default: return 0; /* gate guarantees only the above reach here */ + } +} +/* Read element `row` of an integer/temporal/SYM column widened to int64. */ +static inline int64_t agg_read_key_i64(ray_t* col, const void* data, int64_t row) { + return agg_read_key_i64_raw(col->type, col->attrs, data, row); +} +/* The key types agg_read_key_i64 reads. */ +static inline bool agg_key_i64_type(int8_t t) { + return t == RAY_I64 || t == RAY_TIMESPAN || t == RAY_TIMESTAMP || t == RAY_I32 || t == RAY_DATE || t == RAY_TIME || + t == RAY_I16 || t == RAY_U8 || t == RAY_BOOL || t == RAY_SYM; +} + /* Admission is pure: inspecting a plan must not change execution diagnostics. */ typedef enum { AGG_V2_ADMITTED, @@ -80,12 +127,33 @@ typedef struct { uint32_t ts_tasks; /* last table-stack run: phase-1 tasks */ uint32_t ts_scatter_tasks; /* ...of which switched to raw scatter */ uint64_t ts_tables; /* ...tables created across all tasks */ + uint32_t radix_waves; /* last radix run: payload waves (1 = one pass) */ + uint64_t radix_compacted; /* ...partitions reduced to their top-N candidates */ + uint64_t radix_spill_bytes; /* ...bytes written to (and read back from) its spill file */ + uint64_t radix_spill_buf; /* ...bytes of its write and read-back buffers */ + bool dense_count32; /* last shared dense run: the slab held u32 counters (count only) */ + uint64_t dense_emit_slots; /* last dense finish: slot entries its emit allocated */ + uint8_t radix_phase1; /* last radix run's phase 1: AGG_RADIX_P1_* */ } agg_route_stats_t; +/* Phase 1 of a radix run: plain or staged two passes, the fused pass + * staging whole records (sel mode), or the fused pass staging only the + * sources it decodes (plain columns read in place by its scatter). */ +enum { AGG_RADIX_P1_TWO_PASS = 1, AGG_RADIX_P1_FUSED_RECORDS, AGG_RADIX_P1_FUSED_COMPACT }; void agg_route_reset(void); void agg_route_note_key_domain(void); agg_route_stats_t agg_route_stats(void); void agg_route_record(agg_route_t route); void agg_route_reason(agg_v2_reason_t reason); +/* Test hook (C tests only): the parallel int/SYM-key strategies run the + * small hash (their allocation-failure fallback) in place of the table + * stack and the radix scatter. Disarmed by ray_test_hooks_off. */ +void agg_test_force_smallhash(bool on); +/* Test hook: a plan wider than the row count is dropped, so the grouping + * takes the radix / table-stack routes. Disarmed by ray_test_hooks_off. */ +void agg_test_no_wide_dense(bool on); +/* Test hook: dense plans over a selection that the row probe proved + * impossible (agg_sel_bounds_impossible) since process start. */ +uint64_t ray_agg_test_sel_probe_hits(void); /* True iff the v2 engine fully supports this group node over this table. * Conservative: any uncertainty → false → caller uses the existing engine. */ @@ -116,6 +184,9 @@ bool agg_group_values_f64(const agg_vtable_t* vt, const char* states, /* Trim a finished group result to the emit filter's kept superset (row order * preserved; consumes `result`). Used by routes that emit every group. */ +/* True when the armed emit filter names this group node's slot (the + * operation it names, count when unset): the one routing and trim test. */ +bool agg_emit_filter_targets(const ray_group_emit_filter_t* ef, const ray_op_ext_t* ext); ray_t* agg_emit_filter_trim(ray_t* result, uint32_t n_keys, uint32_t n_aggs, const uint16_t* agg_ops, const ray_group_emit_filter_t* ef); @@ -200,6 +271,7 @@ typedef struct { int32_t* remap[16]; int64_t* inverse[16]; bool compacted; /* any remap set: hot loops select the remap form once */ + bool wide; /* one key whose range exceeds the row count: only the shared strategy may run it (agg_dense_wide_slots) */ } dense_plan_t; /* Release a plan's compaction tables (no-op for raw-range plans). */ diff --git a/src/ops/agg_stream.c b/src/ops/agg_stream.c index 083b5a3c9..6fbaf41c2 100644 --- a/src/ops/agg_stream.c +++ b/src/ops/agg_stream.c @@ -70,6 +70,21 @@ static void sum_i64_update(void* base, size_t stride, const uint32_t* gids, }); } +#if ATOMIC_LLONG_LOCK_FREE == 2 +/* Concurrent form of sum_i64_update: one relaxed wrapping add per live row. */ +static void sum_i64_shared(void* base, size_t stride, const uint32_t* gids, + const void* vals, const ray_valid_t* valid, int64_t n) { + const int64_t* d = (const int64_t*)vals; + AGG_UPDATE_LOOP(valid, n, { + __atomic_fetch_add(&((sum_i64_state*)((char*)base + (size_t)gids[i]*stride))->sum, + d[i], __ATOMIC_RELAXED); + }); +} +#define SUM_I64_SHARED .update_shared = sum_i64_shared, .shared_add = true, +#else +#define SUM_I64_SHARED +#endif + static void sum_i64_merge(void* dst, const void* src, acc_arena_t* a) { (void)a; ((sum_i64_state*)dst)->sum = (int64_t)((uint64_t)((sum_i64_state*)dst)->sum @@ -85,6 +100,7 @@ static const agg_vtable_t SUM_I64 = { .state_size = sizeof(sum_i64_state), .kind = ACC_STREAMING, .out_type = RAY_I64, .init = sum_i64_init, .update_batch = sum_i64_update, .merge = sum_i64_merge, .finalize = sum_i64_final, .finalize_value = sum_i64_final_value, + SUM_I64_SHARED }; /* ---- count (type-agnostic over live rows) ---------------------------- */ @@ -97,6 +113,19 @@ static void count_update(void* base, size_t stride, const uint32_t* gids, for (int64_t i = 0; i < n; i++) ((count_state*)((char*)base + (size_t)gids[i]*stride))->n++; } +#if ATOMIC_LLONG_LOCK_FREE == 2 +/* Concurrent form of count_update: one relaxed add per row. */ +static void count_shared(void* base, size_t stride, const uint32_t* gids, + const void* vals, const ray_valid_t* valid, int64_t n) { + (void)vals; (void)valid; + for (int64_t i = 0; i < n; i++) + __atomic_fetch_add(&((count_state*)((char*)base + (size_t)gids[i]*stride))->n, + 1, __ATOMIC_RELAXED); +} +#define COUNT_SHARED .update_shared = count_shared, +#else +#define COUNT_SHARED +#endif static void count_merge(void* d, const void* s, acc_arena_t* a) { (void)a; ((count_state*)d)->n += ((const count_state*)s)->n; } @@ -108,7 +137,35 @@ static const agg_vtable_t COUNT_ANY = { .state_size = sizeof(count_state), .kind = ACC_STREAMING, .out_type = RAY_I64, .init = count_init, .update_batch = count_update, .merge = count_merge, .finalize = count_final, .finalize_value = count_final_value, -}; + COUNT_SHARED + .shared_add = true, +}; + +/* ---- non-null count (internal OP_COUNT_NN) ---------------------------- + * The per-partition AVG/VAR divisor of a nullable column: the AVG state's + * count without its sum, read straight from the column (no materialized + * not-null indicator). One kernel per nullable native representation. */ +#define COUNT_NN_KERNEL(SFX, T) \ +static void count_nn_##SFX##_update(void* base, size_t stride, \ + const uint32_t* gids, const void* vals, \ + const ray_valid_t* valid, int64_t n, \ + acc_arena_t* a) { \ + (void)a; const T* d = (const T*)vals; \ + AGG_UPDATE_LOOP(valid, n, { \ + ((count_state*)((char*)base + (size_t)gids[i]*stride))->n++; \ + }); \ +} \ +static const agg_vtable_t COUNT_NN_##SFX = { \ + .state_size = sizeof(count_state), .kind = ACC_STREAMING, .out_type = RAY_I64, \ + .init = count_init, .update_batch = count_nn_##SFX##_update, \ + .merge = count_merge, .finalize = count_final, .finalize_value = count_final_value, \ +}; +COUNT_NN_KERNEL(F64, double) +COUNT_NN_KERNEL(F32, float) +COUNT_NN_KERNEL(I64, int64_t) +COUNT_NN_KERNEL(I32, int32_t) +COUNT_NN_KERNEL(I16, int16_t) +#undef COUNT_NN_KERNEL /* ---- min / max I64 (empty group → typed null) ------------------------ */ typedef struct { int64_t v; int64_t cnt; } ext_i64_state; @@ -575,7 +632,7 @@ static inline double pearson_read_f64(const ray_valid_t* v, int64_t i) { switch (v->type) { case RAY_F32: return ((const float*)v->base)[i]; case RAY_F64: return ((const double*)v->base)[i]; - case RAY_I64: case RAY_TIMESTAMP: return (double)((const int64_t*)v->base)[i]; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: return (double)((const int64_t*)v->base)[i]; case RAY_I32: case RAY_DATE: case RAY_TIME: return (double)((const int32_t*)v->base)[i]; case RAY_I16: return (double)((const int16_t*)v->base)[i]; @@ -678,7 +735,7 @@ static inline int truth_read(const ray_valid_t* v, int64_t i) { switch (v->type) { case RAY_F32: return ((const float*)v->base)[i] != 0.0f; case RAY_F64: return ((const double*)v->base)[i] != 0.0; - case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)v->base)[i] != 0; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)v->base)[i] != 0; case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)v->base)[i] != 0; case RAY_I16: return ((const int16_t*)v->base)[i] != 0; @@ -1846,7 +1903,56 @@ static const agg_vtable_t PROD_F64 = { .merge = prod_f64_merge, .finalize = prod_f64_final, .finalize_value = prod_f64_final_value, }; +static ray_t* sum_timespan_final(const void* s, acc_arena_t* a, int64_t param) { + (void)a; (void)param; + return ray_timespan(((const sum_i64_state*)s)->sum); +} +static bool ext_timespan_value(const void* s, void* dst) { + *(int64_t*)dst = ((const ext_i64_state*)s)->v; + return false; +} +static ray_t* ext_timespan_final(const void* s, acc_arena_t* a, int64_t param) { + (void)a; (void)param; + return ray_timespan(((const ext_i64_state*)s)->v); +} +static const agg_vtable_t SUM_TIMESPAN = { + .state_size = sizeof(sum_i64_state), .kind = ACC_STREAMING, .out_type = RAY_TIMESPAN, + .init = sum_i64_init, .update_batch = sum_i64_update, + .merge = sum_i64_merge, .finalize = sum_timespan_final, .finalize_value = sum_i64_final_value, +}; +static const agg_vtable_t MIN_TIMESPAN = { + .state_size = sizeof(ext_i64_state), .kind = ACC_STREAMING, .out_type = RAY_TIMESPAN, + .init = min_i64_init, .update_batch = min_timestamp_native_update, + .merge = min_i64_merge, .finalize = ext_timespan_final, .finalize_value = ext_timespan_value, +}; +static void max_timespan_init(void* s) { + max_i64_init(s); + ((ext_i64_state*)s)->v = -INT64_MAX; +} +static const agg_vtable_t MAX_TIMESPAN = { + .state_size = sizeof(ext_i64_state), .kind = ACC_STREAMING, .out_type = RAY_TIMESPAN, + .init = max_timespan_init, .update_batch = max_timestamp_native_update, + .merge = max_i64_merge, .finalize = ext_timespan_final, .finalize_value = ext_timespan_value, +}; + const agg_vtable_t* agg_resolve(uint16_t agg_kind, int8_t in_type) { + if (in_type == RAY_TIMESPAN) { + if (agg_kind == OP_SUM) return &SUM_TIMESPAN; + if (agg_kind == OP_MIN) return &MIN_TIMESPAN; + if (agg_kind == OP_MAX) return &MAX_TIMESPAN; + return agg_resolve(agg_kind, RAY_I64); + } + + if (agg_kind == OP_COUNT_NN) { + switch (in_type) { + case RAY_F64: return &COUNT_NN_F64; + case RAY_F32: return &COUNT_NN_F32; + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: return &COUNT_NN_I64; + case RAY_I32: case RAY_DATE: case RAY_TIME: return &COUNT_NN_I32; + case RAY_I16: return &COUNT_NN_I16; + default: return NULL; + } + } if (agg_kind == OP_PROD && in_type == RAY_BOOL) return &PROD_BOOL; if (agg_kind == OP_PROD && in_type == RAY_U8) return &PROD_U8; if (agg_kind == OP_PROD && in_type == RAY_I16) return &PROD_I16; diff --git a/src/ops/arith.c b/src/ops/arith.c index 9be671efd..6b2d58097 100644 --- a/src/ops/arith.c +++ b/src/ops/arith.c @@ -69,6 +69,7 @@ static ray_t* ray_f64_unary_math_fn(ray_t* x, ray_unary_fn self, } ray_t* ray_add_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_ADD, a, b); if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_add_fn, OP_ADD, a, b); /* Vector fast path — only when at least one operand is a typed vector */ @@ -147,6 +148,10 @@ ray_t* ray_add_fn(ray_t* a, ray_t* b) { } ray_t* ray_sub_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b) || + ((a->type == -RAY_TIMESTAMP || a->type == RAY_TIMESTAMP) && + (b->type == -RAY_TIMESTAMP || b->type == RAY_TIMESTAMP))) + return ray_timespan_binary(OP_SUB, a, b); if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_sub_fn, OP_SUB, a, b); @@ -224,13 +229,14 @@ ray_t* ray_sub_fn(ray_t* a, ray_t* b) { if (both_f32_atoms(a, b)) return ray_f32((float)r); return make_f64(r); } - int8_t rt = promote_int_type_right(a, b); + int8_t rt = promote_int_type(a, b); /* uint64 wrap on overflow (defined), like ray_add_fn / the vector kernel. */ int64_t la = as_i64(a), lb = as_i64(b); return make_typed_int(rt, (int64_t)((uint64_t)la - (uint64_t)lb)); } ray_t* ray_mul_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_MUL, a, b); if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_mul_fn, OP_MUL, a, b); @@ -267,6 +273,7 @@ ray_t* ray_mul_fn(ray_t* a, ray_t* b) { } ray_t* ray_div_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_DIV, a, b); if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_div_fn, OP_DIV, a, b); if (!is_numeric(a) || !is_numeric(b)) @@ -281,6 +288,7 @@ ray_t* ray_div_fn(ray_t* a, ray_t* b) { } ray_t* ray_idiv_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_IDIV, a, b); if (!is_numeric(a) || !is_numeric(b)) return ray_error("type", "cannot div %s by %s", ray_type_name(a->type), ray_type_name(b->type)); @@ -312,6 +320,7 @@ ray_t* ray_idiv_fn(ray_t* a, ray_t* b) { } ray_t* ray_mod_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_MOD, a, b); if ((a && RAY_IS_PARTED(a->type)) || (b && RAY_IS_PARTED(b->type))) return atomic_map_binary_op(ray_mod_fn, OP_MOD, a, b); /* Temporal % numeric → temporal (same type as left operand) */ @@ -390,6 +399,11 @@ ray_t* ray_mod_fn(ray_t* a, ray_t* b) { } ray_t* ray_neg_fn(ray_t* x) { + if (ray_has_timespan(x)) { + if (is_collection(x)) return atomic_map_unary(ray_neg_fn, x); + if (RAY_ATOM_IS_NULL(x)) return ray_typed_null(-RAY_TIMESPAN); + return ray_timespan(-x->i64); + } if (RAY_ATOM_IS_NULL(x)) { ray_retain(x); return x; } if (x->type == -RAY_F64) return make_f64(-x->f64); if (x->type == -RAY_F32) return ray_f32((float)-x->f64); @@ -448,6 +462,11 @@ ray_t* ray_ceil_fn(ray_t* x) { * convention as `neg`). Stops `(abs -32768h) → -32768h` (negative * result from abs!) and `(abs INT_MIN)` UB simultaneously. */ ray_t* ray_abs_fn(ray_t* x) { + if (ray_has_timespan(x)) { + if (is_collection(x)) return atomic_map_unary(ray_abs_fn, x); + if (RAY_ATOM_IS_NULL(x)) return ray_typed_null(-RAY_TIMESPAN); + return ray_timespan(x->i64 < 0 ? -x->i64 : x->i64); + } if (RAY_ATOM_IS_NULL(x)) { ray_retain(x); return x; } if (x->type == -RAY_F64) return make_f64(fabs(x->f64)); if (x->type == -RAY_F32) return ray_f32(fabsf((float)x->f64)); diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 57c5fe104..906361697 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -24,10 +24,13 @@ /** I/O builtins, type casting, and misc builtins extracted from eval.c. */ +#include "table/domain.h" /* symbols a print must resolve */ +#include "core/timespan.h" #include #include #include "lang/eval.h" #include "lang/internal.h" +#include "table/table.h" #include "ops/idxop.h" /* ray_index_carry_append: keep a hash index across concat */ #include "lang/env.h" #include "core/platform.h" /* ray_vm_map_fd_ro / ray_vm_unmap_file (tracked) */ @@ -46,6 +49,7 @@ static inline double clear_neg_zero(double v) { return v; } #include "ops/hash.h" +#include "store/col.h" #include "store/part.h" #include "store/splay.h" #include "table/sym.h" @@ -72,23 +76,6 @@ static inline double clear_neg_zero(double v) { * I/O builtins: println, show, format, read-csv, write-csv, as, type * ══════════════════════════════════════════ */ -/* Helper: return the null literal string for a typed null atom (e.g. "0Ni" for I32). */ -static const char* null_literal_str(int8_t type) { - switch (-type) { - case RAY_I16: return "0Nh"; - case RAY_I32: return "0Ni"; - case RAY_I64: return "0Nl"; - case RAY_F32: return "0Ne"; - case RAY_F64: return "0Nf"; - case RAY_DATE: return "0Nd"; - case RAY_TIME: return "0Nt"; - case RAY_TIMESTAMP: return "0Np"; - /* SYM/STR use their empty literal as the canonical null spelling; - * callers keep them on their ordinary formatting paths. */ - default: return "null"; - } -} - /* Helper: print a ray_t value to a file handle */ void ray_lang_print(FILE* fp, ray_t* val) { if (!val || RAY_IS_ERR(val)) { fprintf(fp, "error"); return; } @@ -107,7 +94,7 @@ void ray_lang_print(FILE* fp, ray_t* val) { /* STR/SYM use their empty literals as canonical null spellings. */ if (val->type != -RAY_STR && val->type != -RAY_SYM && RAY_ATOM_IS_NULL(val)) { - fprintf(fp, "%s", null_literal_str(val->type)); + fprintf(fp, "%s", ray_fmt_null_literal(-val->type)); return; } switch (val->type) { @@ -171,8 +158,11 @@ void ray_lang_print(FILE* fp, ray_t* val) { /* Helper: format string with % placeholders, substituting args. * Returns a heap-allocated char* (caller must ray_free_raw) and sets *out_len. - * If fmt has no %, returns NULL (caller falls back to plain print). */ -static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t nargs, int64_t arg_start, size_t* out_len) { + * If fmt has no %, returns NULL (caller falls back to plain print). When an + * argument fails to format (a table column that fails to load), returns NULL + * with *err set to the owned error object; otherwise *err stays NULL. */ +static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t nargs, int64_t arg_start, size_t* out_len, ray_t** err) { + *err = NULL; /* Quick scan: any % in fmt? */ int has_pct = 0; for (size_t i = 0; i < flen; i++) if (fmt[i] == '%') { has_pct = 1; break; } @@ -203,7 +193,7 @@ static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t tlen = snprintf(tmp, sizeof(tmp), "error"); } else if (a->type != -RAY_STR && a->type != -RAY_SYM && RAY_ATOM_IS_NULL(a)) { - tlen = snprintf(tmp, sizeof(tmp), "%s", null_literal_str(a->type)); + tlen = snprintf(tmp, sizeof(tmp), "%s", ray_fmt_null_literal(-a->type)); } else if (a->type == -RAY_I64) { tlen = snprintf(tmp, sizeof(tmp), "%" PRId64, a->i64); } else if (a->type == -RAY_F64) { @@ -248,6 +238,12 @@ static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t if (a_owned) ray_release(a_owned); continue; } + if (formatted && RAY_IS_ERR(formatted)) { + if (a_owned) ray_release(a_owned); + ray_free_raw(buf); + *err = formatted; + return NULL; + } if (formatted) ray_release(formatted); tlen = snprintf(tmp, sizeof(tmp), "", a->type); } @@ -265,6 +261,11 @@ static char* fmt_interpolate(const char* fmt, size_t flen, ray_t** args, int64_t return buf; } +static ray_t* print_end(FILE* out) { + fflush(out); + return RAY_NULL_OBJ; +} + /* (println val1 val2 ...) — print values to stdout, newline at end. * If first arg is a string with % placeholders, substitutes remaining args. */ ray_t* ray_println_fn(ray_t** args, int64_t n) { @@ -278,7 +279,9 @@ ray_t* ray_println_fn(ray_t** args, int64_t n) { const char* fmt = ray_str_ptr(args[0]); size_t flen = ray_str_len(args[0]); size_t out_len = 0; - char* result = fmt_interpolate(fmt, flen, args, n, 1, &out_len); + ray_t* ferr; + char* result = fmt_interpolate(fmt, flen, args, n, 1, &out_len, &ferr); + if (ferr) return ferr; if (result) { fwrite(result, 1, out_len, stdout); fputc('\n', stdout); @@ -288,13 +291,13 @@ ray_t* ray_println_fn(ray_t** args, int64_t n) { } } + FILE* out = stdout; for (int64_t i = 0; i < n; i++) { - if (i > 0) fputc(' ', stdout); - ray_lang_print(stdout, args[i]); + if (i > 0) fputc(' ', out); + ray_lang_print(out, args[i]); } - fputc('\n', stdout); - fflush(stdout); - return RAY_NULL_OBJ; + fputc('\n', out); + return print_end(out); } /* (print val1 val2 ...) — like println but without trailing newline */ @@ -306,7 +309,9 @@ ray_t* ray_print_fn(ray_t** args, int64_t n) { const char* fmt = ray_str_ptr(args[0]); size_t flen = ray_str_len(args[0]); size_t out_len = 0; - char* result = fmt_interpolate(fmt, flen, args, n, 1, &out_len); + ray_t* ferr; + char* result = fmt_interpolate(fmt, flen, args, n, 1, &out_len, &ferr); + if (ferr) return ferr; if (result) { fwrite(result, 1, out_len, stdout); fflush(stdout); @@ -315,38 +320,44 @@ ray_t* ray_print_fn(ray_t** args, int64_t n) { } } + FILE* out = stdout; for (int64_t i = 0; i < n; i++) { - if (i > 0) fputc(' ', stdout); - ray_lang_print(stdout, args[i]); + if (i > 0) fputc(' ', out); + ray_lang_print(out, args[i]); } - fflush(stdout); - return RAY_NULL_OBJ; + return print_end(out); } /* (show val1 val2 ...) — print values to stdout using ray_fmt, newline at end */ ray_t* ray_show_fn(ray_t** args, int64_t n) { /* args are pre-materialized by eval — see ray_println_fn. */ + FILE* out = stdout; for (int64_t i = 0; i < n; i++) { - if (!args[i] || RAY_IS_ERR(args[i])) { fprintf(stdout, "error"); continue; } + if (!args[i] || RAY_IS_ERR(args[i])) { fprintf(out, "error"); continue; } /* show prints the whole value, streamed; the display limits belong * to the REPL and to print. */ - ray_err_t e = ray_fmt_write(stdout, args[i]); + ray_t* cause; + ray_err_t e = ray_fmt_write(out, args[i], &cause); + if (cause) { /* a column failed to load: report it, output already written stays */ + ray_t* r = print_end(out); + if (r && RAY_IS_ERR(r)) { ray_error_free(cause); return r; } + return cause; + } if (e == RAY_OK || e == RAY_ERR_IO) continue; /* written, partly written, or stdout failed */ /* out of memory before any output: fall back to the bounded REPL display */ ray_t* formatted = ray_fmt(args[i], 1); if (formatted && !RAY_IS_ERR(formatted)) { const char* sp = ray_str_ptr(formatted); size_t sl = ray_str_len(formatted); - fwrite(sp, 1, sl, stdout); + fwrite(sp, 1, sl, out); ray_release(formatted); } else { - if (formatted) ray_release(formatted); - ray_lang_print(stdout, args[i]); + if (formatted) ray_error_free(formatted); + ray_lang_print(out, args[i]); } } - fputc('\n', stdout); - fflush(stdout); - return RAY_NULL_OBJ; + fputc('\n', out); + return print_end(out); } /* (format "hello % world %" a b) — string formatting with % placeholders */ @@ -357,7 +368,9 @@ ray_t* ray_format_fn(ray_t** args, int64_t n) { const char* fmt = ray_str_ptr(args[0]); size_t flen = ray_str_len(args[0]); size_t out_len = 0; - char* result = fmt_interpolate(fmt, flen, args, n, 1, &out_len); + ray_t* ferr; + char* result = fmt_interpolate(fmt, flen, args, n, 1, &out_len, &ferr); + if (ferr) return ferr; if (result) { ray_t* s = ray_str(result, out_len); ray_free_raw(result); @@ -416,11 +429,16 @@ ray_t* ray_resolve_fn(ray_t** args, int64_t n) { if (RAY_IS_ERR(result)) { ray_release(tbl); return result; } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); int64_t col_name = ray_table_col_name(tbl, c); + ray_col_meta_t cm; + if (!ray_table_col_meta_idx(tbl, c, &cm)) continue; + /* Only an I64 column is read; any other is carried over still encoded. */ + ray_t* col = (cm.type == RAY_I64) ? ray_table_col_idx(tbl, c) : ray_table_get_col_enc_idx(tbl, c); + if (!col) col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) { ray_release(result); ray_release(tbl); return col; } if (!col) continue; - if (col->type == RAY_I64) { + if (cm.type == RAY_I64) { /* Try to resolve: convert to SYM only if ALL positive values * are valid sym IDs. This avoids converting entity-ID columns * where values are plain integers that happen to collide with @@ -475,6 +493,12 @@ ray_t* ray_timeit_fn(ray_t** args, int64_t n) { if (n < 1) return ray_error("arity", "timeit: expects 1 argument, got %lld", (long long)n); int64_t t0 = ray_profile_now_ns(); ray_t* result = ray_eval(args[0]); + /* Reductions such as (sum v) return a lazy handle whose work only runs + * on materialization. Force it inside the timed span, or timeit reports + * the cost of building the graph rather than of the computation (#856). + * ray_lazy_materialize consumes the handle and returns an owned value or + * an error. */ + if (ray_is_lazy(result)) result = ray_lazy_materialize(result); int64_t t1 = ray_profile_now_ns(); /* Propagate errors instead of swallowing them — otherwise a failing * expression silently reports a timing as if it had succeeded. */ @@ -526,6 +550,7 @@ static int8_t resolve_type_name(int64_t sym_id) { else if (len == 3 && memcmp(name, "F32", 3) == 0) result = RAY_F32; else if (len == 4 && memcmp(name, "DATE", 4) == 0) result = RAY_DATE; else if (len == 4 && memcmp(name, "TIME", 4) == 0) result = RAY_TIME; + else if (len == 8 && memcmp(name, "TIMESPAN", 8) == 0) result = RAY_TIMESPAN; else if (len == 9 && memcmp(name, "TIMESTAMP", 9) == 0) result = RAY_TIMESTAMP; else if (len == 4 && memcmp(name, "GUID", 4) == 0) result = RAY_GUID; ray_release(s); @@ -628,6 +653,14 @@ static const char* csv_default_sym_path(const char* dir, char* buf, size_t bufsz } ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) { + ray_compress_t mode = RAY_COMPRESS_ABSENT; + if (n >= 1 && args[0] && args[0]->type == RAY_DICT) { + if (n >= 2 && args[1] && args[1]->type == RAY_DICT) + return ray_error("domain", "csv.splayed: a second options dict"); + ray_t* oerr = ray_compress_opt_parse(args[0], true, &mode); + if (oerr) return oerr; + args++; n--; + } if (n < 2 || n > 4) return ray_error("arity", "csv.splayed: expects 2 to 4 arguments, got %lld", (long long)n); char dir[1024]; @@ -681,10 +714,10 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) { } } - ray_err_t err = ray_csv_save_splayed_named_opts(path, 0, header, - types_arg, ncols, - names_arg, ncols, - dir, 0); + ray_err_t err = ray_csv_save_splayed_mode(path, 0, header, + types_arg, ncols, + names_arg, ncols, + dir, 0, mode); if (err != RAY_OK) return ray_error(ray_err_code_str(err), NULL); char sym_path[1024]; @@ -696,6 +729,14 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) { } ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) { + ray_compress_t mode = RAY_COMPRESS_ABSENT; + if (n >= 1 && args[0] && args[0]->type == RAY_DICT) { + if (n >= 2 && args[1] && args[1]->type == RAY_DICT) + return ray_error("domain", "csv.parted: a second options dict"); + ray_t* oerr = ray_compress_opt_parse(args[0], true, &mode); + if (oerr) return oerr; + args++; n--; + } if (n < 3 || n > 6) return ray_error("arity", "csv.parted: expects 3 to 6 arguments, got %lld", (long long)n); char root[1024]; @@ -774,10 +815,10 @@ ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) { return ray_error("io", "csv.parted: %s is left from an earlier failed import; remove it to retry", staging); - ray_err_t err = ray_csv_save_parted_named_opts(path, 0, header, - types_arg, ncols, - names_arg, ncols, - root, table_name, rows_per_part); + ray_err_t err = ray_csv_save_parted_mode(path, 0, header, + types_arg, ncols, + names_arg, ncols, + root, table_name, rows_per_part, mode); if (err != RAY_OK) { struct stat st; if (stat(dest, &st) != 0 && stat(staging, &st) == 0) @@ -866,7 +907,7 @@ static ray_t* cast_vec_copy_nulls(ray_t* vec, ray_t* val) { if (ray_vec_is_null(val, j)) d[j] = NULL_F64; break; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(vec); for (int64_t j = 0; j < vec->len; j++) if (ray_vec_is_null(val, j)) d[j] = NULL_I64; @@ -972,7 +1013,7 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, * in_type); each leaf is a tight typed loop the compiler vectorizes. */ #define CL(R, W, EXPR) do { CAST_LOOP_RANGE(R, W, EXPR, lo, hi); return true; } while (0) switch (out_type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: switch (in_type) { case RAY_BOOL: CL(uint8_t, int64_t, _v ? 1 : 0); case RAY_U8: CL(uint8_t, int64_t, (int64_t)_v); @@ -980,6 +1021,7 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, case RAY_I32: case RAY_DATE: case RAY_TIME: CL(int32_t, int64_t, (int64_t)_v); case RAY_F64: CL(double, int64_t, ray_cast_f64_to_i64_null(_v)); + case RAY_F32: CL(float, int64_t, ray_cast_f64_to_i64_null((double)_v)); } break; case RAY_I32: case RAY_DATE: case RAY_TIME: @@ -987,9 +1029,10 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, case RAY_BOOL: CL(uint8_t, int32_t, _v ? 1 : 0); case RAY_U8: CL(uint8_t, int32_t, (int32_t)_v); case RAY_I16: CL(int16_t, int32_t, (int32_t)_v); - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: CL(int64_t, int32_t, (int32_t)_v); case RAY_F64: CL(double, int32_t, ray_cast_f64_to_i32_null(_v)); + case RAY_F32: CL(float, int32_t, ray_cast_f64_to_i32_null((double)_v)); } break; case RAY_I16: @@ -998,9 +1041,10 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, case RAY_U8: CL(uint8_t, int16_t, (int16_t)_v); case RAY_I32: case RAY_DATE: case RAY_TIME: CL(int32_t, int16_t, (int16_t)_v); - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: CL(int64_t, int16_t, (int16_t)_v); case RAY_F64: CL(double, int16_t, ray_cast_f64_to_i16_null(_v)); + case RAY_F32: CL(float, int16_t, ray_cast_f64_to_i16_null((double)_v)); } break; case RAY_U8: @@ -1009,9 +1053,10 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, case RAY_I16: CL(int16_t, uint8_t, (uint8_t)_v); case RAY_I32: case RAY_DATE: case RAY_TIME: CL(int32_t, uint8_t, (uint8_t)_v); - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: CL(int64_t, uint8_t, (uint8_t)_v); case RAY_F64: CL(double, uint8_t, ray_cast_f64_to_u8_null(_v)); + case RAY_F32: CL(float, uint8_t, ray_cast_f64_to_u8_null((double)_v)); } break; case RAY_F64: @@ -1021,8 +1066,21 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, case RAY_I16: CL(int16_t, double, (double)_v); case RAY_I32: case RAY_DATE: case RAY_TIME: CL(int32_t, double, (double)_v); - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: CL(int64_t, double, (double)_v); + case RAY_F32: CL(float, double, (double)_v); + } + break; + case RAY_F32: + switch (in_type) { + case RAY_BOOL: CL(uint8_t, float, _v ? 1.0f : 0.0f); + case RAY_U8: CL(uint8_t, float, (float)_v); + case RAY_I16: CL(int16_t, float, (float)_v); + case RAY_I32: case RAY_DATE: case RAY_TIME: + CL(int32_t, float, (float)_v); + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: + CL(int64_t, float, (float)_v); + case RAY_F64: CL(double, float, ray_cast_f64_to_f32_null(_v)); } break; case RAY_BOOL: @@ -1031,9 +1089,10 @@ static bool cast_range_worker(const void* _src_p, void* _dst_p, case RAY_I16: CL(int16_t, uint8_t, _v != 0 ? 1 : 0); case RAY_I32: case RAY_DATE: case RAY_TIME: CL(int32_t, uint8_t, _v != 0 ? 1 : 0); - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: CL(int64_t, uint8_t, _v != 0 ? 1 : 0); case RAY_F64: CL(double, uint8_t, ray_cast_f64_to_bool_null(_v)); + case RAY_F32: CL(float, uint8_t, ray_cast_f64_to_bool_null((double)_v)); } break; } @@ -1213,7 +1272,7 @@ static void cast_mark_output_sentinels(ray_t* vec, int8_t out_type, int64_t n) { if (d[i] != d[i]) { vec->attrs |= RAY_ATTR_HAS_NULLS; return; } return; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { const int64_t* d = (const int64_t*)out; for (int64_t i = 0; i < n; i++) if (d[i] == NULL_I64) { vec->attrs |= RAY_ATTR_HAS_NULLS; return; } @@ -1239,7 +1298,8 @@ static ray_t* cast_vec_numeric(ray_t* type_sym, ray_t* val, int8_t out_type) { /* Fast path: typed numeric vec → numeric vec, no list/string. */ if (ray_is_vec(val) && val->type != RAY_STR && val->type != RAY_SYM && - val->type != RAY_GUID && out_type != RAY_SYM) { + val->type != RAY_GUID && out_type != RAY_SYM && + val->type != RAY_TIMESPAN && out_type != RAY_TIMESPAN) { ray_t* fast = cast_vec_numeric_fast(val, vec, out_type); /* Three return states (helper does NOT release `vec`): * - vec on success @@ -1298,13 +1358,14 @@ static ray_t* cast_vec_numeric(ray_t* type_sym, ray_t* val, int8_t out_type) { if (alloc) ray_release(elem); if (RAY_IS_ERR(cast)) { ray_release(vec); return cast; } switch (out_type) { - case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: ((int64_t*)out)[i] = cast->i64; break; case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)out)[i] = cast->i32; break; case RAY_I16: ((int16_t*)out)[i] = cast->i16; break; case RAY_U8: ((uint8_t*)out)[i] = cast->u8; break; case RAY_F64: ((double*)out)[i] = cast->f64; break; + case RAY_F32: ((float*)out)[i] = (float)cast->f64; break; case RAY_BOOL: ((bool*)out)[i] = cast->b8; break; default: break; } @@ -1325,9 +1386,101 @@ static ray_t* cast_vec_numeric(ray_t* type_sym, ray_t* val, int8_t out_type) { return vec; } +/* STR has already been resolved. Successful scalar formatting produces + * atoms by construction; the flat collection kernel needs no kind check. */ +static inline __attribute__((always_inline)) +ray_t* cast_str_atom(ray_t* val) { + if (val->type == -RAY_STR) { ray_retain(val); return val; } + if (val->type == -RAY_SYM) { + ray_t* sym_str = ray_sym_str(val->i64); + return sym_str ? sym_str : ray_str("", 0); + } + if (val->type == -RAY_I64) { + char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%lld", (long long)val->i64); + return ray_str(buf, (size_t)n2); + } + if (val->type == -RAY_I32) { + char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%d", (int)val->i32); + return ray_str(buf, (size_t)n2); + } + if (val->type == -RAY_I16) { + char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%d", (int)val->i16); + return ray_str(buf, (size_t)n2); + } + if (val->type == -RAY_F64) { + double fv = val->f64; + fv = clear_neg_zero(fv); + char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%g", fv); + return ray_str(buf, (size_t)n2); + } + if (val->type == -RAY_F32) { + /* Data conversion uses plain decimal text, independent of the + * literal printer and its configured display precision. */ + double fv = clear_neg_zero((double)(float)val->f64); + char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%.9g", fv); + return ray_str(buf, (size_t)n2); + } + if (val->type == -RAY_BOOL) { + return val->b8 ? ray_str("true", 4) : ray_str("false", 5); + } + /* Fallback: use ray_fmt for any other atom type */ + if (ray_is_atom(val)) { + ray_t* formatted = ray_fmt(val, 0); + if (formatted && !RAY_IS_ERR(formatted)) return formatted; + if (formatted) ray_release(formatted); + } + return ray_error("type", "as: cannot cast %s to str", ray_type_name(val->type)); +} + +/* Choose the collection contract once. A boxed flat-vector element can + * only produce a string atom on success; LIST children may recurse to vectors. + * Keep the collection loop outside scalar dispatch's register frame. */ +static inline __attribute__((always_inline)) +ray_t* cast_str_cells(ray_t* type_sym, ray_t* val, bool may_nest) { + int64_t n2 = val->len; + ray_t* vec = ray_vec_new(RAY_STR, n2); + if (!vec || RAY_IS_ERR(vec)) return vec ? vec : ray_error("oom", NULL); + for (int64_t i = 0; i < n2; i++) { + int alloc = 0; + ray_t* elem = collection_elem(val, i, &alloc); + if (RAY_IS_ERR(elem)) { ray_release(vec); return elem; } + ray_t* cast = may_nest ? ray_cast_fn(type_sym, elem) + : RAY_ATOM_IS_NULL(elem) ? ray_str("", 0) + : cast_str_atom(elem); + if (alloc) ray_release(elem); + if (RAY_IS_ERR(cast)) { ray_release(vec); return cast; } + if (!cast) { ray_release(vec); return ray_error("oom", NULL); } + /* Each output cell needs a string atom. A nested input can + * recursively produce a STR vector, not an atom to inspect. */ + if (may_nest && cast->type != -RAY_STR) { + ray_release(cast); + ray_release(vec); + return ray_error("type", "as: STR vector elements must cast to string atoms"); + } + const char* sp = ray_str_ptr(cast); + size_t slen = ray_str_len(cast); + vec = ray_str_vec_append(vec, sp ? sp : "", sp ? slen : 0); + ray_release(cast); + if (RAY_IS_ERR(vec)) return vec; + } + ray_t* result = cast_vec_copy_nulls(vec, val); + if (RAY_IS_ERR(result)) return result; + return vec; +} + +static __attribute__((noinline)) +ray_t* cast_str_flat(ray_t* type_sym, ray_t* val) { + return cast_str_cells(type_sym, val, false); +} + +static __attribute__((noinline)) +ray_t* cast_str_list(ray_t* type_sym, ray_t* val) { + return cast_str_cells(type_sym, val, true); +} + ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (type_sym->type != -RAY_SYM) return ray_error("type", "as: target type must be sym, got %s", ray_type_name(type_sym->type)); - /* Null propagation: casting a typed null atom produces a typed null of target type */ + /* Nullable targets preserve nulls; BOOL/U8 produce ordinary values. */ if (ray_is_atom(val) && RAY_ATOM_IS_NULL(val)) { ray_t* s2 = ray_sym_str(type_sym->i64); if (!s2) return ray_error("domain", NULL); @@ -1339,14 +1492,23 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { else if (cast_match(tn, tl, "I16") || cast_match(tn, tl, "i16")) tt = -RAY_I16; else if (cast_match(tn, tl, "U8") || cast_match(tn, tl, "u8")) tt = -RAY_U8; else if (cast_match(tn, tl, "F64") || cast_match(tn, tl, "f64")) tt = -RAY_F64; + else if (cast_match(tn, tl, "F32") || cast_match(tn, tl, "f32")) tt = -RAY_F32; else if (cast_match(tn, tl, "BOOL") || cast_match(tn, tl, "bool") || cast_match(tn, tl, "B8") || cast_match(tn, tl, "b8")) tt = -RAY_BOOL; else if (cast_match(tn, tl, "SYMBOL") || cast_match(tn, tl, "symbol") || cast_match(tn, tl, "sym")) tt = -RAY_SYM; else if (cast_match(tn, tl, "DATE") || cast_match(tn, tl, "date")) tt = -RAY_DATE; else if (cast_match(tn, tl, "TIME") || cast_match(tn, tl, "time")) tt = -RAY_TIME; + else if (cast_match(tn, tl, "TIMESPAN") || cast_match(tn, tl, "timespan")) tt = -RAY_TIMESPAN; else if (cast_match(tn, tl, "TIMESTAMP") || cast_match(tn, tl, "timestamp")) tt = -RAY_TIMESTAMP; else if (cast_match(tn, tl, "GUID") || cast_match(tn, tl, "guid")) tt = -RAY_GUID; else if (cast_match(tn, tl, "STR") || cast_match(tn, tl, "str")) { ray_release(s2); return ray_str("", 0); } ray_release(s2); + if (tt == -RAY_U8) return ray_u8(0); + if (tt == -RAY_BOOL) { + /* Numeric and temporal null sentinels are non-zero. Empty + * text and zero-payload internal nulls convert to false. */ + return make_bool((val->type <= -RAY_I16 && val->type >= -RAY_TIMESTAMP) || + val->type == -RAY_TIMESPAN); + } if (tt) return ray_typed_null(tt); return ray_error("domain", "as: unknown target type name"); } @@ -1355,11 +1517,49 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { const char* tname = ray_str_ptr(s); size_t tlen = ray_str_len(s); + if (cast_match(tname, tlen, "TIMESPAN") || cast_match(tname, tlen, "timespan")) { + ray_release(s); + if (val->type == -RAY_TIMESPAN) { ray_retain(val); return val; } + if (val->type == -RAY_TIME) return ray_timespan((int64_t)val->i32 * INT64_C(1000000)); + if (val->type == -RAY_TIMESTAMP) { + int64_t ns = val->i64 % INT64_C(86400000000000); + return ray_timespan(ns < 0 ? ns + INT64_C(86400000000000) : ns); + } + if (val->type == -RAY_F64 || val->type == -RAY_F32) + return ray_timespan(ray_cast_f64_to_i64_null(round(val->f64))); + if (is_numeric(val)) return ray_timespan(as_i64(val)); + if (val->type == -RAY_STR) { + size_t used = 0; + int64_t ns; + if (!ray_parse_timespan(ray_str_ptr(val), &used, &ns) || used != ray_str_len(val)) + return ray_error("domain", "as: invalid duration string"); + return ray_timespan(ns); + } + if (ray_is_vec(val) || val->type == RAY_LIST) + return cast_vec_numeric(type_sym, val, RAY_TIMESPAN); + return ray_error("type", "as: cannot convert %s to TIMESPAN", ray_type_name(val->type)); + } + if (val->type == -RAY_TIMESPAN && + (cast_match(tname, tlen, "I64") || cast_match(tname, tlen, "i64") || + cast_match(tname, tlen, "I32") || cast_match(tname, tlen, "i32") || + cast_match(tname, tlen, "I16") || cast_match(tname, tlen, "i16") || + cast_match(tname, tlen, "U8") || cast_match(tname, tlen, "u8") || + cast_match(tname, tlen, "F64") || cast_match(tname, tlen, "f64") || + cast_match(tname, tlen, "F32") || cast_match(tname, tlen, "f32") || + cast_match(tname, tlen, "B8") || cast_match(tname, tlen, "b8") || + cast_match(tname, tlen, "BOOL"))) { + ray_release(s); + ray_t* count = ray_i64(val->i64); + if (RAY_IS_ERR(count)) return count; + ray_t* result = ray_cast_fn(type_sym, count); + ray_release(count); + return result; + } /* Cast to I64 / i64 */ if (cast_match(tname, tlen, "I64") || cast_match(tname, tlen, "i64")) { ray_release(s); if (val->type == -RAY_I64) { ray_retain(val); return val; } - if (val->type == -RAY_F64) return make_i64(ray_cast_f64_to_i64_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return make_i64(ray_cast_f64_to_i64_null(val->f64)); if (val->type == -RAY_BOOL) return make_i64(val->b8 ? 1 : 0); if (val->type == -RAY_I32 || val->type == -RAY_DATE || val->type == -RAY_TIME) return make_i64(val->i32); @@ -1399,7 +1599,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_U8) return ray_i32((int32_t)val->u8); if (val->type == -RAY_I16) return ray_i32(val->i16); if (val->type == -RAY_I64) return ray_i32((int32_t)val->i64); - if (val->type == -RAY_F64) return ray_i32(ray_cast_f64_to_i32_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return ray_i32(ray_cast_f64_to_i32_null(val->f64)); if (val->type == -RAY_DATE || val->type == -RAY_TIME) return ray_i32(val->i32); if (val->type == -RAY_TIMESTAMP) return ray_i32((int32_t)val->i64); if (val->type == -RAY_STR) { @@ -1435,7 +1635,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_U8) return ray_i16((int16_t)val->u8); if (val->type == -RAY_I32) return ray_i16((int16_t)val->i32); if (val->type == -RAY_I64) return ray_i16((int16_t)val->i64); - if (val->type == -RAY_F64) return ray_i16(ray_cast_f64_to_i16_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return ray_i16(ray_cast_f64_to_i16_null(val->f64)); if (val->type == -RAY_DATE || val->type == -RAY_TIME) return ray_i16((int16_t)val->i32); if (val->type == -RAY_TIMESTAMP) return ray_i16((int16_t)val->i64); if (val->type == -RAY_STR) { @@ -1467,6 +1667,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (cast_match(tname, tlen, "F64") || cast_match(tname, tlen, "f64")) { ray_release(s); if (val->type == -RAY_F64) { ray_retain(val); return val; } + if (val->type == -RAY_F32) return make_f64(val->f64); if (val->type == -RAY_BOOL) return make_f64(val->b8 ? 1.0 : 0.0); if (val->type == -RAY_I64) return make_f64((double)val->i64); if (val->type == -RAY_I32) return make_f64((double)val->i32); @@ -1495,6 +1696,37 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { return cast_vec_numeric(type_sym, val, RAY_F64); return ray_error("type", "as: cannot cast %s to f64", ray_type_name(val->type)); } + /* Cast to F32 / f32. A value past the F32 range saturates and a + * non-finite parse is the null, as for F64 (ray_cast_f64_to_f32_null). */ + if (cast_match(tname, tlen, "F32") || cast_match(tname, tlen, "f32")) { + ray_release(s); + if (val->type == -RAY_F32) { ray_retain(val); return val; } + if (val->type == -RAY_F64) return ray_f32(ray_cast_f64_to_f32_null(val->f64)); + if (val->type == -RAY_BOOL) return ray_f32(val->b8 ? 1.0f : 0.0f); + if (val->type == -RAY_I64) return ray_f32((float)val->i64); + if (val->type == -RAY_I32) return ray_f32((float)val->i32); + if (val->type == -RAY_I16) return ray_f32((float)val->i16); + if (val->type == -RAY_U8) return ray_f32((float)val->u8); + /* Temporal atoms cast through their storage, as for F64 and as the + * vector and query casts already do. */ + if (val->type == -RAY_DATE || val->type == -RAY_TIME) return ray_f32((float)val->i32); + if (val->type == -RAY_TIMESTAMP) return ray_f32((float)val->i64); + if (val->type == -RAY_STR) { + const char* sp = ray_str_ptr(val); + if (!sp) return ray_error("domain", "as: cannot parse empty str as f32"); + char* end; + errno = 0; + double v = strtod(sp, &end); + if (end == sp) return ray_error("domain", "as: cannot parse str as f32"); + if (*end != '\0') + return ray_error("domain", "as: cannot parse str as f32, unexpected trailing characters"); + /* Non-finite parses are the null, as make_f64 does for F64. */ + return ray_f32(isfinite(v) ? ray_cast_f64_to_f32_null(v) : NULL_F32); + } + if (ray_is_vec(val) || val->type == RAY_LIST) + return cast_vec_numeric(type_sym, val, RAY_F32); + return ray_error("type", "as: cannot cast %s to f32", ray_type_name(val->type)); + } /* Cast to B8/BOOL/b8 */ if (cast_match(tname, tlen, "BOOL") || cast_match(tname, tlen, "B8") || cast_match(tname, tlen, "b8")) { ray_release(s); @@ -1503,7 +1735,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_I32) return make_bool(val->i32 != 0 ? 1 : 0); if (val->type == -RAY_I16) return make_bool(val->i16 != 0 ? 1 : 0); if (val->type == -RAY_U8) return make_bool(val->u8 != 0 ? 1 : 0); - if (val->type == -RAY_F64) return make_bool(val->f64 != 0.0 ? 1 : 0); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return make_bool(val->f64 != 0.0 ? 1 : 0); if (val->type == -RAY_DATE) return make_bool(val->i32 != 0 ? 1 : 0); if (val->type == -RAY_TIME) return make_bool(val->i32 != 0 ? 1 : 0); if (val->type == -RAY_TIMESTAMP) return make_bool(val->i64 != 0 ? 1 : 0); @@ -1516,61 +1748,9 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { /* Cast to STR/str */ if (cast_match(tname, tlen, "STR") || cast_match(tname, tlen, "str")) { ray_release(s); - if (val->type == -RAY_STR) { ray_retain(val); return val; } - if (val->type == -RAY_SYM) { - ray_t* sym_str = ray_sym_str(val->i64); - return sym_str ? sym_str : ray_str("", 0); - } - if (val->type == -RAY_I64) { - char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%lld", (long long)val->i64); - return ray_str(buf, (size_t)n2); - } - if (val->type == -RAY_I32) { - char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%d", (int)val->i32); - return ray_str(buf, (size_t)n2); - } - if (val->type == -RAY_I16) { - char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%d", (int)val->i16); - return ray_str(buf, (size_t)n2); - } - if (val->type == -RAY_F64) { - double fv = val->f64; - fv = clear_neg_zero(fv); - char buf[32]; int n2 = snprintf(buf, sizeof(buf), "%g", fv); - return ray_str(buf, (size_t)n2); - } - if (val->type == -RAY_BOOL) { - return val->b8 ? ray_str("true", 4) : ray_str("false", 5); - } - /* Fallback: use ray_fmt for any other atom type */ - if (ray_is_atom(val)) { - ray_t* formatted = ray_fmt(val, 0); - if (formatted && !RAY_IS_ERR(formatted)) return formatted; - if (formatted) ray_release(formatted); - } - /* Vector/list -> STR vector: cast each element to string */ - if (ray_is_vec(val) || val->type == RAY_LIST) { - int64_t n2 = val->len; - ray_t* vec = ray_vec_new(RAY_STR, n2); - if (!vec || RAY_IS_ERR(vec)) return vec ? vec : ray_error("oom", NULL); - for (int64_t i = 0; i < n2; i++) { - int alloc = 0; - ray_t* elem = collection_elem(val, i, &alloc); - if (RAY_IS_ERR(elem)) { ray_release(vec); return elem; } - ray_t* cast = ray_cast_fn(type_sym, elem); - if (alloc) ray_release(elem); - if (RAY_IS_ERR(cast)) { ray_release(vec); return cast; } - const char* sp = ray_str_ptr(cast); - size_t slen = ray_str_len(cast); - vec = ray_str_vec_append(vec, sp ? sp : "", sp ? slen : 0); - ray_release(cast); - if (RAY_IS_ERR(vec)) return vec; - } - ray_t* result = cast_vec_copy_nulls(vec, val); - if (RAY_IS_ERR(result)) return result; - return vec; - } - return ray_error("type", "as: cannot cast %s to str", ray_type_name(val->type)); + if (val->type == RAY_LIST) return cast_str_list(type_sym, val); + if (ray_is_vec(val)) return cast_str_flat(type_sym, val); + return cast_str_atom(val); } /* Cast to SYMBOL/sym */ if (cast_match(tname, tlen, "SYMBOL") || cast_match(tname, tlen, "sym") || cast_match(tname, tlen, "symbol")) { @@ -1594,6 +1774,10 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { fv = clear_neg_zero(fv); n2 = snprintf(buf, sizeof(buf), "%.17g", fv); } + else if (val->type == -RAY_F32) { + double fv = clear_neg_zero((double)(float)val->f64); + n2 = snprintf(buf, sizeof(buf), "%.9g", fv); + } else n2 = snprintf(buf, sizeof(buf), "%lld", (long long)as_i64(val)); if (n2 > 0) { int64_t id = ray_sym_intern(buf, (size_t)n2); @@ -1626,7 +1810,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_I16) return ray_date((int64_t)val->i16); if (val->type == -RAY_I32) return ray_date((int64_t)val->i32); if (val->type == -RAY_I64) return ray_date(val->i64); - if (val->type == -RAY_F64) return ray_date(ray_cast_f64_to_i32_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return ray_date(ray_cast_f64_to_i32_null(val->f64)); if (val->type == -RAY_TIME) return ray_date((int64_t)val->i32); if (val->type == -RAY_TIMESTAMP) return ray_date(ts_days_floor(val->i64)); if (val->type == -RAY_STR) { @@ -1690,7 +1874,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_I16) return ray_time((int64_t)val->i16); if (val->type == -RAY_I32) return ray_time((int64_t)val->i32); if (val->type == -RAY_I64) return ray_time(val->i64); - if (val->type == -RAY_F64) return ray_time(ray_cast_f64_to_i32_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return ray_time(ray_cast_f64_to_i32_null(val->f64)); if (val->type == -RAY_DATE) return ray_time((int64_t)val->i32); if (val->type == -RAY_TIMESTAMP) /* TIMESTAMP is ns since epoch; TIME stores ms-of-day. Use @@ -1768,7 +1952,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_I16) return ray_timestamp((int64_t)val->i16); if (val->type == -RAY_I32) return ray_timestamp((int64_t)val->i32); if (val->type == -RAY_I64) return ray_timestamp(val->i64); - if (val->type == -RAY_F64) return ray_timestamp(ray_cast_f64_to_i64_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return ray_timestamp(ray_cast_f64_to_i64_null(val->f64)); if (val->type == -RAY_TIME) return ray_timestamp((int64_t)val->i32); if (val->type == -RAY_DATE) { int64_t days = val->i32; @@ -1968,7 +2152,7 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (val->type == -RAY_I16) return ray_u8((uint8_t)val->i16); if (val->type == -RAY_I32) return ray_u8((uint8_t)val->i32); if (val->type == -RAY_I64) return ray_u8((uint8_t)val->i64); - if (val->type == -RAY_F64) return ray_u8(ray_cast_f64_to_u8_null(val->f64)); + if (val->type == -RAY_F64 || val->type == -RAY_F32) return ray_u8(ray_cast_f64_to_u8_null(val->f64)); if (val->type == -RAY_STR) { const char* sp = ray_str_ptr(val); char* end; errno = 0; @@ -2000,7 +2184,8 @@ ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val) { if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(val, c); - ray_t* col_val = ray_table_get_col_idx(val, c); + ray_t* col_val = ray_table_col_idx(val, c); + if (col_val && RAY_IS_ERR(col_val)) { ray_release(keys); ray_release(vals); return col_val; } keys = ray_vec_append(keys, &col_name); if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } vals = ray_list_append(vals, col_val); @@ -2065,13 +2250,22 @@ ray_t* ray_type_fn(ray_t* val) { * watermark — so ray_heap_set_anon_watermark still steers this and no new * knob is introduced. * - * Returns 0 for "no bound known", which callers treat as permissive. */ + * Never less than RAY_UNSIZED_READ_FLOOR: at or past the watermark there is + * no headroom to take a quarter of, and the 0 that used to come back there + * meant "no bound" to the callers — the guard was off exactly when memory + * was short. The floor keeps the bound monotonic too: a little headroom + * does not bound tighter than none. + * + * Returns 0 for "no bound known" (RAM unknown), which callers treat as + * permissive. */ +#define RAY_UNSIZED_READ_FLOOR (INT64_C(64) << 20) + int64_t ray_unsized_read_budget(void) { int64_t wm = ray_heap_anon_watermark(); if (wm <= 0) return 0; /* RAM unknown → permissive */ int64_t avail = wm - ray_heap_anon_committed(); - if (avail <= 0) return 0; - return avail / 4; + int64_t budget = avail > 0 ? avail / 4 : 0; + return budget < RAY_UNSIZED_READ_FLOOR ? RAY_UNSIZED_READ_FLOOR : budget; } static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { @@ -2125,11 +2319,13 @@ static ray_t* read_file_bytes(ray_t* path_obj, const char* op) { * the hint", so a file that grew is read whole instead of truncated. */ int64_t cap = hint > 0 ? (int64_t)hint + 1 : 4096; - /* No ceiling on the hinted path. A reported size is a finite claim the - * filesystem backs, and a large file allocating through the heap and - * spilling to disk is the behaviour that was already correct — the - * budget below exists to terminate an *endless* stream, which is not a - * situation a hint can describe. */ + /* No ceiling on the hinted allocation. A reported size is a finite + * claim the filesystem backs, and a large file allocating through the + * heap and spilling to disk is the behaviour that was already correct — + * the budget below exists to terminate an *endless* stream, which is not + * a situation a hint can describe. A file that grows past its hint + * while it is read (len reaches cap = hint + 1) does grow through the + * loop below, though, and meets the same budget there. */ const int64_t budget = ray_unsized_read_budget(); ray_t* result = ray_vec_new(RAY_U8, cap); @@ -2356,13 +2552,15 @@ ray_t* ray_enlist_fn(ray_t** args, int64_t n) { bool homogeneous = true; bool has_float = (atype == -RAY_F64); bool has_int = (atype == -RAY_I64); + bool all_numeric = has_float || has_int; for (int64_t i = 1; i < n; i++) { if (args[i]->type != atype) homogeneous = false; if (args[i]->type == -RAY_F64) has_float = true; - if (args[i]->type == -RAY_I64) has_int = true; + else if (args[i]->type == -RAY_I64) has_int = true; + else all_numeric = false; } - /* Mixed int/float -> promote to f64 */ - if (!homogeneous && has_float && has_int) { + /* Only I64/F64 atoms have the payloads used by this promotion. */ + if (!homogeneous && has_float && has_int && all_numeric) { ray_t* vec = ray_vec_new(RAY_F64, n); if (RAY_IS_ERR(vec)) return vec; double* d = (double*)ray_data(vec); @@ -2385,7 +2583,7 @@ ray_t* ray_enlist_fn(ray_t** args, int64_t n) { ray_t* vec = ray_vec_new(vtype, n); if (RAY_IS_ERR(vec)) return vec; switch (vtype) { - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(vec); for (int64_t i = 0; i < n; i++) d[i] = args[i]->i64; break; @@ -2584,17 +2782,16 @@ static void where_emit_fn(void* ctxp, uint32_t wid, int64_t start, int64_t end) ray_t* ray_where_fn(ray_t* x) { if (!ray_is_vec(x) || x->type != RAY_BOOL) - return ray_error("type", "where: argument must be a b8 vector, got %s", ray_type_name(x->type)); + return ray_error("type", "where: argument must be a B8 vector, got %s%s", + ray_type_name(x->type), ray_is_atom(x) ? " atom" : ""); const uint8_t* data = (const uint8_t*)ray_data(x); int64_t n = x->len; ray_pool_t* pool = ray_pool_get(); if (ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) { /* One task per chunk (ray_pool_dispatch_n). Chunk count is capped - * at 1024 — the pool's INITIAL ring capacity — so dispatch_n never - * needs to grow the ring (its clamp-on-grow-failure silently DROPS - * tasks, which here would mean uninitialized prefix entries and - * out-of-bounds emit offsets). 1024 tasks is ample granularity. */ + * at 1024 — the pool's INITIAL ring capacity — so dispatch_n runs in + * one window with no ring growth; 1024 tasks is ample granularity. */ int64_t chunk_rows = WHERE_CHUNK_ROWS; while ((n + chunk_rows - 1) / chunk_rows > RAY_POOL_INIT_TASKS) chunk_rows *= 2; int64_t n_chunks = (n + chunk_rows - 1) / chunk_rows; @@ -2782,11 +2979,29 @@ uint64_t ray_atom_hash(ray_t* a) { h = ray_hash_combine(h, ray_atom_hash(elems[i])); return h; } + case RAY_TABLE: { + /* atom_eq: same names in order, equal columns. Hashing them + * only spreads the buckets: the default arm's type and length + * would put every table of one length in one bucket. */ + int64_t nc = ray_table_ncols(a); + uint64_t h = ray_hash_i64(nc); + for (int64_t c = 0; c < nc; c++) { + h = ray_hash_combine(h, ray_hash_i64(ray_table_col_name(a, c))); + ray_t* col = ray_table_col_idx(a, c); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); col = NULL; } /* hashes as absent */ + h = ray_hash_combine(h, ray_atom_hash(col)); + } + return h; + } + case RAY_DICT: + return ray_hash_combine(ray_atom_hash(ray_dict_keys(a)), + ray_atom_hash(ray_dict_vals(a))); default: /* Vec or unknown atom kind: fold type tag and length. Two - * structurally-equal lists never reach here (RAY_LIST branch - * above) so we can't accidentally produce different hashes - * for atom_eq-equal pairs. */ + * structurally-equal lists, tables or dicts never reach here + * (RAY_LIST / RAY_TABLE / RAY_DICT arms above) so we can't + * accidentally produce different hashes for atom_eq-equal + * pairs. */ return ray_hash_i64(((int64_t)a->type << 32) ^ (int64_t)a->len); } } @@ -3359,7 +3574,7 @@ ray_t* ray_group_indices_fn(ray_t* x) { * agree with the bitmap. */ void* base = ray_data(keys_vec); switch (key_type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)base)[g] = NULL_I64; break; case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)base)[g] = NULL_I32; break; @@ -3543,7 +3758,7 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { if (RAY_IS_ERR(result)) return result; /* Copy atom value as first element */ switch (b->type) { - case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: ((int64_t*)ray_data(result))[0] = a->i64; break; case RAY_F64: ((double*)ray_data(result))[0] = a->f64; break; @@ -3594,7 +3809,7 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { memcpy(ray_data(result), ray_data(a), (size_t)(na * esz)); } switch (a->type) { - case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: ((int64_t*)ray_data(result))[na] = b->i64; break; case RAY_F64: ((double*)ray_data(result))[na] = b->f64; break; @@ -3627,7 +3842,7 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { if (RAY_IS_ERR(result)) return result; result->len = 2; switch (vtype) { - case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: case RAY_SYM: ((int64_t*)ray_data(result))[0] = a->i64; ((int64_t*)ray_data(result))[1] = b->i64; break; @@ -3719,12 +3934,14 @@ ray_t* ray_concat_fn(ray_t* a, ray_t* b) { if (RAY_IS_ERR(result)) return result; for (int64_t c = 0; c < ncols_a; c++) { int64_t col_name_a = ray_table_col_name(a, c); - ray_t* acol = ray_table_get_col_idx(a, c); + ray_t* acol = ray_table_col_idx(a, c); + if (acol && RAY_IS_ERR(acol)) { ray_release(result); return acol; } /* Find matching column in b by name */ ray_t* bcol = NULL; for (int64_t j = 0; j < ncols_b; j++) { if (ray_table_col_name(b, j) == col_name_a) { - bcol = ray_table_get_col_idx(b, j); + bcol = ray_table_col_idx(b, j); + if (bcol && RAY_IS_ERR(bcol)) { ray_release(result); return bcol; } break; } } @@ -3875,8 +4092,8 @@ ray_t* ray_ungroup_fn(ray_t* x) { /* Locate the nested (RAY_LIST) columns. */ bool any_nested = false; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(x, c); - if (col && !RAY_IS_ERR(col) && col->type == RAY_LIST) { any_nested = true; break; } + ray_col_meta_t cm; + if (ray_table_col_meta_idx(x, c, &cm) && cm.type == RAY_LIST) { any_nested = true; break; } } /* No nested column → identity. */ if (!any_nested) { ray_retain(x); return x; } @@ -3891,8 +4108,11 @@ ray_t* ray_ungroup_fn(ray_t* x) { for (int64_t i = 0; i < nrows; i++) { int64_t n_i = -1; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(x, c); - if (!col || RAY_IS_ERR(col) || col->type != RAY_LIST) continue; + ray_col_meta_t cm; + if (!ray_table_col_meta_idx(x, c, &cm) || cm.type != RAY_LIST) continue; + ray_t* col = ray_table_col_idx(x, c); + if (col && RAY_IS_ERR(col)) { ray_free_raw(counts); return col; } + if (!col) continue; ray_t* cell = ray_list_get(col, i); /* A valid nested cell is either an atom (length 1) or a typed * NON-LIST vector (length cell->len). Anything else — NULL @@ -3927,10 +4147,11 @@ ray_t* ray_ungroup_fn(ray_t* x) { if (!out || RAY_IS_ERR(out)) { ray_free_raw(counts); ray_release(idx); return out ? out : ray_error("oom", NULL); } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(x, c); + ray_t* col = ray_table_col_idx(x, c); + if (col && RAY_IS_ERR(col)) { ray_release(out); ray_release(idx); ray_free_raw(counts); return col; } int64_t name = ray_table_col_name(x, c); ray_t* newcol; - if (col && !RAY_IS_ERR(col) && col->type == RAY_LIST) { + if (col && col->type == RAY_LIST) { /* Nested: raze the per-row cells in row order. */ newcol = ray_raze_fn(col); /* raze of an empty/all-empty list yields an empty LIST — leave @@ -3942,7 +4163,7 @@ ray_t* ray_ungroup_fn(ray_t* x) { ray_release(newcol); ray_release(out); ray_release(idx); ray_free_raw(counts); return ray_error("length", "ungroup: razed column length mismatch, got %lld, expected %lld", (long long)ray_len(newcol), (long long)total); } - } else if (col && !RAY_IS_ERR(col)) { + } else if (col) { /* Flat: gather row i repeated n_i times. */ newcol = gather_by_idx(col, idxd, total); } else { diff --git a/src/ops/cdfuse.c b/src/ops/cdfuse.c index c341e8ffd..a6055f168 100644 --- a/src/ops/cdfuse.c +++ b/src/ops/cdfuse.c @@ -58,6 +58,9 @@ #include "ops/hll.h" /* ray_count_distinct_approx — the gate's group count check */ #include "table/sym.h" /* RAY_IS_SYM */ #include "store/col.h" /* ray_col_cold — sampled-row read-ahead */ +#include "store/colrange.h" /* an encoded column read by range */ +#include "ops/rowsel.h" /* ray_rowsel_* — the bounded kernel's selection */ +#include "core/platform.h" /* ray_vm_advise_willneed */ /* Peak-footprint estimate used by the admission gate below: 32B/row for * phase 1's records plus up to 24B per (partition, key) pair in phase 2, @@ -255,12 +258,10 @@ typedef struct { cdf_part_t* parts; uint32_t nw, n_parts, part_bits; _Atomic(int) oom; - /* Partitions actually processed. ray_pool_dispatch_n CLAMPS its task - * count to the ring capacity when the growth realloc fails (see - * RAY_POOL_INIT_TASKS in core/pool.h) and a cancelled pool skips claimed - * tasks — either way the tail partitions never run, keep ng == 0, and - * their groups would silently vanish from the result. The wrapper - * compares this against n_parts and declines (NULL) on mismatch. */ + /* Partitions actually processed. A cancelled pool skips its tasks, so + * the partitions left keep ng == 0 and their groups would silently + * vanish from the result. The wrapper compares this against n_parts + * and declines (NULL) on mismatch. */ _Atomic(int64_t) done; } cdf_p2_ctx_t; @@ -888,3 +889,1144 @@ bool ray_cd_two_pass_preferred(ray_t** K_cols, int n_K, ray_t* X_col, return true; return t_est < nrows - nrows / 4; } + +/* ══════════════════════════════════════════ + * Bounded grouped count-distinct + * ══════════════════════════════════════════ + * + * The per-group slices (count_distinct_per_group_buf, query.c) take a row + * map (8 B a row), a row index ordered by group (8 B a row) and a hash table + * per group sized by its rows, and gather the values through the index: on a + * 100M-row table that is 1.6 GB of row-sized scratch read at random, which a + * small machine spills to disk and rewrites several times over. The global + * hash past 50 K groups scatters 16 B a row besides the row map. + * + * Here the K and X columns are read in order, a chunk at a time. Phase A + * (a task per run of CDB_TASK_ROWS rows) maps each row to its group, hashes + * the (group, value) pair, drops a pair the task saw a moment ago and sorts + * the rest by partition (the hash's top bits) into the chunk's record + * buffer. Phase B (a task per partition) adds the chunk's records of its + * partition to that partition's set — open addressing over (value, group+1) + * slots, 6 to 12 bytes each. The sets hold each distinct pair once; the + * record buffer, the staging and the per-worker counts are a few tens of MB + * whatever the row count. The input is read once, the sets are written in + * place: no structure grows with the rows. + * + * The sets are what grows with the distinct pairs. A set grows when phase + * B fills it to load 3/4 (its task stops there; the main thread gives it a + * block sized by the share of new pairs among the records so far, and phase + * B goes on), so a set holds what its pairs need, not its raw records. The + * sets are sized against a budget — three quarters of the room under the + * anon watermark, counting the blocks the heap can reuse, and no less than + * a sixteenth of the watermark or a quarter of the slices' row buffers — + * and when growing them would pass it, the partitions at the top of the + * round's range are freed and left to a further round, which reads the + * input again and keeps only their pairs. Partitions are disjoint in + * pairs, so a partition is counted in exactly one round; how many + * partitions a round takes is set from the bytes per partition the previous + * one ended with. The first trim projects the round's sets over the rows + * left: past CDB_MAX_ROUNDS budgets' worth the budget rises to a third of + * that (up to the slices' row buffers), rather than re-reading the input + * once a partition. + * + * Every set block is allocated and freed by the calling thread (phase B + * only fills blocks the main thread handed it), so nothing is freed into a + * worker's foreign list. */ + +#define CDB_TASK_ROWS 32768 /* rows per phase-A task (at most), a multiple of RAY_MORSEL_ELEMS */ +#define CDB_TASK_ROWS_MIN 4096 /* the fewest, under a small budget */ +#define CDB_MAX_ROUNDS 3 /* passes over the input before the sets may pass the budget */ +#define CDB_CACHE 256 /* recent-pair cache entries per task */ +#define CDB_SET_MIN_BYTES 1024 /* first block of a partition set */ +#define CDB_MAX_PARTS 1024u +#define CDB_LOCAL_CNT (INT64_C(4) << 20) /* per-worker count cells before atomics */ +#define CDB_MIN_BUDGET (INT64_C(4) << 20) /* and a sixteenth of the watermark */ +#define CDB_RA_BYTES (INT64_C(48) << 20) /* input requested ahead of the scan */ +#define CDB_SKEW 4 /* workers' shares of the rows a dominant group holds */ +#define CDB_SAMPLE_ROWS (INT64_C(1) << 26) /* rows from which the route samples */ + +typedef struct { int64_t x; uint32_t g; uint32_t h; } cdb_rec_t; +typedef struct { int64_t x; uint64_t g; } cdb_recent_t; + +typedef struct { + const void* data; /* NULL: every row reads `fill`, unless `src` */ + int64_t lo, n; /* global rows [lo, lo + n) */ + int8_t type; + uint8_t attrs, esz; + bool cold; + int64_t fill; + ray_col_src_t* src; /* an encoded column read by range (its cdb_col_t's own) */ +} cdb_seg_t; + +typedef struct { + cdb_seg_t* seg; + int64_t nseg, rows; + bool narrow; /* every cell is a 32-bit pattern (see cdb_col_open) */ + bool bound; /* own is bound: a single-file encoded column */ + ray_col_src_t own; +} cdb_col_t; + +typedef struct { + void* blk; /* cap values, then cap tags (group + 1, 0 = empty) */ + void* old; /* the previous slots, rehashed into blk by phase B */ + uint64_t cap, ocap; + uint64_t bytes; /* blk's buddy block: a power of two, header included */ + uint64_t obytes; /* old's */ + int64_t n; + /* phase B over one chunk: the records of the partition (inc), those + * taken (seen) and the new pairs among them (added), and where it + * stopped when the set filled (task rt, record ri) */ + int64_t inc, seen, added, ri; + uint32_t rt; + bool fresh; /* blk not initialised yet */ + bool full; /* stopped at load 3/4: to grow and go on */ +} cdb_set_t; + +typedef struct { + cdb_col_t key, val; + const int64_t* row_gid; + const int64_t* kkeys; /* key -> group + 1 */ + const uint32_t* ktag; + uint64_t kmask; + int64_t n_groups, nrows; + const uint8_t* sel_flg; + const uint32_t* sel_offs; + const uint16_t* sel_idx; + int64_t sel_nsegs; + const int64_t* sel_pre; /* a row map over the kept rows: rank of each segment's first kept row */ + uint64_t vmask; + uint32_t P, pshift, lo, hi, T, T_c; + int64_t S; /* rows per phase-A task */ + int64_t chunk_r0; + cdb_rec_t* recs; /* [T * S] */ + cdb_rec_t* stage; /* [W * S] */ + uint16_t* spart; /* [W * S] */ + const uint32_t* plist; /* phase B: the partitions of its tasks */ + int64_t* toff; /* [T * (P + 1)] */ + cdb_set_t* sets; /* [P] */ + int var; /* slot layout, see CDB_SET_FNS */ + int64_t* cnt; /* [W * n_groups], or [n_groups] when shared */ + bool cnt_shared; + bool one_group; /* no key: every row is group 0 */ + ray_scan_fail_t fail; /* a range read's failure (encoded columns) */ + _Atomic(int64_t) done; +} cdb_ctx_t; + +/* A slot of a set of `cap` slots from 32 hash bits (multiply-shift): any + * capacity, so a set fills its buddy block (cdb_set_bytes). */ +static inline uint64_t cdb_slot(uint32_t h, uint64_t cap) { + return ((uint64_t)h * cap) >> 32; +} + +static inline uint64_t cdb_hash(int64_t x, uint64_t g) { + return cdf_fmix64((uint64_t)x * 0x9E3779B97F4A7C15ULL + g * 0xC2B2AE3D27D4EB4FULL); +} + +static bool cdb_type_ok(int8_t t, bool is_val) { + switch (t) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_SYM: + return true; + case RAY_F64: + return is_val; + default: + return false; + } +} + +/* A cell as a key: integers widened with their sign, SYM ids and BOOL/U8 + * without, F64 through canon_f64_key — what the other count-distinct + * kernels key a value by, nulls included (the sentinels are ordinary + * integers, a SYM null is id 0, every NaN folds to one). */ +static inline int64_t cdb_cell(const void* d, int64_t r, int8_t t, uint8_t attrs) { + if (t == RAY_F64) return canon_f64_key(((const double*)d)[r]); + return read_col_i64(d, r, t, attrs); +} + +/* What the rows of a partition without the column read as: the type's + * null, keyed as a stored one (BOOL/U8 have none: 0, as parted_fill_nulls + * writes). */ +static int64_t cdb_null_cell(int8_t t) { + switch (t) { + case RAY_I16: return NULL_I16; + case RAY_I32: case RAY_DATE: case RAY_TIME: return NULL_I32; + case RAY_I64: case RAY_TIMESTAMP: return NULL_I64; + case RAY_F64: return canon_f64_key(NULL_F64); + default: return 0; + } +} + +static void cdb_col_close(cdb_col_t* c) { + ray_free_raw(c->seg); + c->seg = NULL; + if (c->bound) ray_col_src_release(&c->own); + c->bound = false; +} + +/* The segments of a flat, parted or MAPCOMMON column. `narrow`: the low 32 + * bits of every cell identify it — the signed family (I16, I32, DATE, TIME) + * whose cells are 32-bit integers widened, or the unsigned one (BOOL, U8, + * SYM) while every cell is below 2^32 — so a set stores 4 bytes a value. + * 1 when served, 0 when not (a type, a segment of another type), -1 when + * memory ran out. */ +static int cdb_col_open(cdb_col_t* c, ray_t* col, ray_t* tbl, bool is_val, ray_t** err) { + memset(c, 0, sizeof(*c)); + *err = NULL; + if (!col || RAY_IS_ERR(col)) return 0; + int8_t base; + int64_t n; + if (col->type == RAY_ENCCOL) { + /* a single-file generation-2 column, read a vector at a time by + * the tasks (never decoded whole); a parted one is not served */ + ray_col_meta_t m; + if (!ray_col_meta_of(col, &m) || RAY_IS_PARTED(m.type) || !cdb_type_ok(m.type, is_val)) return 0; + ray_t* be = ray_col_src_bind(col, &c->own); + if (be) { *err = be; return -1; } + c->bound = true; + base = c->own.type; + n = 1; + c->seg = (cdb_seg_t*)ray_calloc_raw(sizeof(cdb_seg_t)); + if (!c->seg) { cdb_col_close(c); *err = ray_error("oom", NULL); return -1; } + c->seg[0].n = c->own.len; + c->seg[0].type = base; + c->seg[0].attrs = c->own.attrs; + c->seg[0].esz = ray_col_src_esz(&c->own); + c->seg[0].src = &c->own; + } else if (col->type == RAY_MAPCOMMON) { + ray_t** mp = (ray_t**)ray_data(col); + ray_t* kv = mp[0]; + ray_t* rc = mp[1]; + if (!kv || !rc || RAY_IS_ERR(kv) || RAY_IS_ERR(rc) || rc->type != RAY_I64 || + !ray_is_vec(kv) || kv->len < rc->len || !cdb_type_ok(kv->type, is_val)) + return 0; + base = kv->type; + n = rc->len; + c->seg = (cdb_seg_t*)ray_calloc_raw((size_t)(n > 0 ? n : 1) * sizeof(cdb_seg_t)); + if (!c->seg) { *err = ray_error("oom", NULL); return -1; } + const int64_t* counts = (const int64_t*)ray_data(rc); + for (int64_t p = 0; p < n; p++) { + c->seg[p].n = counts[p] > 0 ? counts[p] : 0; + c->seg[p].type = base; + c->seg[p].fill = cdb_cell(ray_data(kv), p, kv->type, kv->attrs); + } + } else if (RAY_IS_PARTED(col->type)) { + base = (int8_t)RAY_PARTED_BASETYPE(col->type); + if (!cdb_type_ok(base, is_val)) return 0; + ray_t** segs = (ray_t**)ray_data(col); + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); + n = col->len; + c->seg = (cdb_seg_t*)ray_calloc_raw((size_t)(n > 0 ? n : 1) * sizeof(cdb_seg_t)); + if (!c->seg) { *err = ray_error("oom", NULL); return -1; } + for (int64_t s = 0; s < n; s++) { + ray_t* sg = segs[s]; + cdb_seg_t* d = &c->seg[s]; + d->type = base; + if (sg && !RAY_IS_ERR(sg)) { + if (sg->type != base || !ray_is_vec(sg)) { cdb_col_close(c); return 0; } + d->data = sg->len > 0 ? ray_data(sg) : NULL; + d->n = sg->len; + d->attrs = sg->attrs; + d->esz = ray_sym_elem_size(base, sg->attrs); + d->cold = d->data && ray_col_cold(sg); + if (!d->data) d->fill = 0; /* no rows */ + } else { + d->n = parted_seg_rows(segs, s, cnt, ncnt); + d->fill = cdb_null_cell(base); + } + } + } else { + if (!ray_is_vec(col) || !cdb_type_ok(col->type, is_val)) return 0; + base = col->type; + n = 1; + c->seg = (cdb_seg_t*)ray_calloc_raw(sizeof(cdb_seg_t)); + if (!c->seg) { *err = ray_error("oom", NULL); return -1; } + c->seg[0].data = col->len > 0 ? ray_data(col) : NULL; + c->seg[0].n = col->len; + c->seg[0].type = base; + c->seg[0].attrs = col->attrs; + c->seg[0].esz = ray_sym_elem_size(base, col->attrs); + c->seg[0].cold = c->seg[0].data && ray_col_cold(col); + } + c->nseg = n; + int64_t lo = 0; + for (int64_t s = 0; s < n; s++) { c->seg[s].lo = lo; lo += c->seg[s].n; } + c->rows = lo; + switch (base) { + case RAY_I16: case RAY_I32: case RAY_DATE: case RAY_TIME: + c->narrow = true; + break; + case RAY_BOOL: case RAY_U8: case RAY_SYM: + c->narrow = true; + for (int64_t s = 0; s < n && c->narrow; s++) { + const cdb_seg_t* d = &c->seg[s]; + if (d->data || d->src ? d->esz > 4 : (uint64_t)d->fill > UINT32_MAX) c->narrow = false; + } + break; + default: + c->narrow = false; + } + return 1; +} + +bool ray_cd_bounded_col_ok(ray_t* col, bool is_val) { + if (!col || RAY_IS_ERR(col)) return false; + if (col->type == RAY_ENCCOL) { /* from metadata: a single-file encoded column */ + ray_col_meta_t m; + return ray_col_meta_of(col, &m) && !RAY_IS_PARTED(m.type) && cdb_type_ok(m.type, is_val); + } + if (col->type == RAY_MAPCOMMON) { + ray_t* kv = ((ray_t**)ray_data(col))[0]; + return kv && !RAY_IS_ERR(kv) && ray_is_vec(kv) && cdb_type_ok(kv->type, is_val); + } + if (RAY_IS_PARTED(col->type)) + return cdb_type_ok((int8_t)RAY_PARTED_BASETYPE(col->type), is_val); + return ray_is_vec(col) && cdb_type_ok(col->type, is_val); +} + +/* The segment holding global row r (r < rows). */ +static int64_t cdb_seek(const cdb_col_t* c, int64_t r) { + int64_t a = 0, b = c->nseg - 1; + while (a < b) { + int64_t m = (a + b + 1) / 2; + if (c->seg[m].lo <= r) a = m; else b = m - 1; + } + return a; +} + +/* Cells [off, off + m) of a plain run of `type` at element size esz. */ +static void cdb_cells(const void* data, int8_t type, uint8_t esz, int64_t off, int64_t m, int64_t* out) { + if (type == RAY_F64) { + const double* d = (const double*)data + off; + for (int64_t i = 0; i < m; i++) out[i] = canon_f64_key(d[i]); + } else if (esz == 8) { + memcpy(out, (const int64_t*)data + off, (size_t)m * sizeof(int64_t)); + } else if (esz == 4) { + if (type == RAY_SYM) { + const uint32_t* d = (const uint32_t*)data + off; + for (int64_t i = 0; i < m; i++) out[i] = d[i]; + } else { + const int32_t* d = (const int32_t*)data + off; + for (int64_t i = 0; i < m; i++) out[i] = d[i]; + } + } else if (esz == 2) { + if (type == RAY_SYM) { + const uint16_t* d = (const uint16_t*)data + off; + for (int64_t i = 0; i < m; i++) out[i] = d[i]; + } else { + const int16_t* d = (const int16_t*)data + off; + for (int64_t i = 0; i < m; i++) out[i] = d[i]; + } + } else { + const uint8_t* d = (const uint8_t*)data + off; + for (int64_t i = 0; i < m; i++) out[i] = d[i]; + } +} + +/* Cells of rows [r, r + n) into out[], from segment *si on; an encoded + * segment through the caller's cursor (one per task, so a vector is + * decoded once a task). NULL or an owned error (a range read's). */ +static ray_t* cdb_decode(const cdb_col_t* c, int64_t* si, int64_t r, int64_t n, int64_t* out, + ray_col_cursor_t* cur) { + int64_t s = *si; + while (n > 0) { + while (r >= c->seg[s].lo + c->seg[s].n) s++; + const cdb_seg_t* g = &c->seg[s]; + int64_t off = r - g->lo, m = g->n - off; + if (m > n) m = n; + if (g->src) { + const ray_col_range_t* v; + ray_t* err = ray_col_cursor_at(cur, off, &v); + if (err) return err; + int64_t vm = v->start + v->n - off; + if (vm < m) m = vm; + cdb_cells(v->data, v->type, ray_sym_elem_size(v->type, v->attrs), off - v->start, m, out); + } else if (!g->data) { + for (int64_t i = 0; i < m; i++) out[i] = g->fill; + } else { + cdb_cells(g->data, g->type, g->esz, off, m, out); + } + out += m; r += m; n -= m; + } + *si = s; + return NULL; +} + +/* Ask for the cold segments' bytes of rows [r0, r1). */ +static void cdb_want(const cdb_col_t* c, int64_t r0, int64_t r1) { + if (r0 >= r1) return; + for (int64_t s = cdb_seek(c, r0); s < c->nseg && c->seg[s].lo < r1; s++) { + const cdb_seg_t* g = &c->seg[s]; + if (!g->cold || !g->data) continue; + int64_t a = r0 > g->lo ? r0 - g->lo : 0; + int64_t b = r1 < g->lo + g->n ? r1 - g->lo : g->n; + if (b > a) + ray_vm_advise_willneed((char*)g->data + (size_t)a * g->esz, + (size_t)(b - a) * g->esz); + } +} + +/* Ask for rows [r0, r1) of the columns the kernel reads — with a + * selection, only the runs of morsels it keeps rows of. */ +static void cdb_want_rows(const cdb_ctx_t* c, int64_t r0, int64_t r1) { + if (!c->sel_flg) { + if (!c->row_gid && !c->one_group) cdb_want(&c->key, r0, r1); + cdb_want(&c->val, r0, r1); + return; + } + int64_t m = r0 / RAY_MORSEL_ELEMS, m_end = (r1 + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS; + while (m < m_end) { + while (m < m_end && (m >= c->sel_nsegs || c->sel_flg[m] == RAY_SEL_NONE)) m++; + int64_t run = m; + while (m < m_end && m < c->sel_nsegs && c->sel_flg[m] != RAY_SEL_NONE) m++; + if (m > run) { + int64_t a = run * RAY_MORSEL_ELEMS > r0 ? run * RAY_MORSEL_ELEMS : r0; + int64_t b = m * RAY_MORSEL_ELEMS < r1 ? m * RAY_MORSEL_ELEMS : r1; + if (!c->row_gid && !c->one_group) cdb_want(&c->key, a, b); + cdb_want(&c->val, a, b); + } + } +} + +static inline int64_t cdb_gid(const cdb_ctx_t* c, int64_t k) { + uint64_t h = (uint64_t)k * 0x9E3779B97F4A7C15ULL; + h ^= h >> 33; + uint64_t s = h & c->kmask; + for (;;) { + uint32_t t = c->ktag[s]; + if (!t) return -1; + if (c->kkeys[s] == k) return (int64_t)t - 1; + s = (s + 1) & c->kmask; + } +} + +/* Phase A: task t of the chunk takes rows [chunk_r0 + t*S, +S), keeps the + * pairs whose partition is in [lo, hi) and lays them out in its region of + * the record buffer partition by partition (toff[t][p] .. toff[t][p+1]). */ +static void cdb_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + cdb_ctx_t* c = (cdb_ctx_t*)vctx; + int64_t kbuf[RAY_MORSEL_ELEMS], xbuf[RAY_MORSEL_ELEMS]; + uint32_t hist[CDB_MAX_PARTS]; + cdb_recent_t recent[CDB_CACHE]; + static const int64_t zero_gid[RAY_MORSEL_ELEMS]; /* one_group: every row's group */ + const uint32_t P = c->P, lo = c->lo, hi = c->hi, pshift = c->pshift; + const uint64_t vmask = c->vmask, ng = (uint64_t)c->n_groups; + /* the encoded columns' cursors, on this task's stack */ + ray_col_fixed_t kfix, xfix; + ray_col_cursor_t kcur, xcur; + const bool kenc = c->key.bound, xenc = c->val.bound; + if (kenc) ray_col_cursor_init_lent(&kcur, &c->key.own, &kfix); + if (xenc) ray_col_cursor_init_lent(&xcur, &c->val.own, &xfix); + for (int64_t t = start; t < end; t++) { + int64_t r0 = c->chunk_r0 + t * c->S; + int64_t r1 = r0 + c->S; + if (r1 > c->nrows) r1 = c->nrows; + if ((kenc || xenc) && ray_scan_failed(&c->fail)) { /* the round is abandoned */ + atomic_fetch_add_explicit(&c->done, 1, memory_order_relaxed); + continue; + } + ray_t* rerr = NULL; + cdb_rec_t* st = c->stage + (size_t)wid * c->S; + uint16_t* sp = c->spart + (size_t)wid * c->S; + memset(hist, 0, (size_t)P * sizeof(uint32_t)); + memset(recent, 0, sizeof(recent)); + int64_t ns = 0; + int64_t ksi = c->row_gid || c->one_group ? 0 : cdb_seek(&c->key, r0); + int64_t xsi = cdb_seek(&c->val, r0); + int64_t klast = 0, glast = -2; + for (int64_t m0 = r0; m0 < r1 && !rerr; m0 += RAY_MORSEL_ELEMS) { + int64_t mn = r1 - m0 < RAY_MORSEL_ELEMS ? r1 - m0 : RAY_MORSEL_ELEMS; + const uint16_t* idx = NULL; + int64_t ni = mn; + if (c->sel_flg) { + int64_t seg = m0 / RAY_MORSEL_ELEMS; + uint8_t f = seg < c->sel_nsegs ? c->sel_flg[seg] : RAY_SEL_NONE; + if (f == RAY_SEL_NONE) continue; + if (f != RAY_SEL_ALL) { + idx = c->sel_idx + c->sel_offs[seg]; + ni = c->sel_offs[seg + 1] - c->sel_offs[seg]; + } + } + const int64_t* gb; + if (c->one_group) { + gb = zero_gid; + } else if (c->row_gid) { + gb = c->sel_pre ? c->row_gid + c->sel_pre[m0 / RAY_MORSEL_ELEMS] : c->row_gid + m0; + } else { + if ((rerr = cdb_decode(&c->key, &ksi, m0, mn, kbuf, kenc ? &kcur : NULL)) != NULL) break; + for (int64_t i = 0; i < mn; i++) { + int64_t k = kbuf[i]; + if (k != klast || glast == -2) { klast = k; glast = cdb_gid(c, k); } + kbuf[i] = glast; + } + gb = kbuf; + } + if ((rerr = cdb_decode(&c->val, &xsi, m0, mn, xbuf, xenc ? &xcur : NULL)) != NULL) break; + for (int64_t j = 0; j < ni; j++) { + int64_t i = idx ? idx[j] : j; + uint64_t g = (uint64_t)(c->sel_pre ? gb[j] : gb[i]); + if (g >= ng) continue; /* no group (negative too) */ + g++; + int64_t x = (int64_t)((uint64_t)xbuf[i] & vmask); + uint64_t h = cdb_hash(x, g); + uint32_t p = (uint32_t)(h >> pshift); + if (p < lo || p >= hi) continue; + cdb_recent_t* e = &recent[(h >> 32) & (CDB_CACHE - 1)]; + if (e->g == g && e->x == x) continue; + e->g = g; e->x = x; + st[ns].x = x; st[ns].g = (uint32_t)g; st[ns].h = (uint32_t)h; + sp[ns] = (uint16_t)p; + hist[p]++; + ns++; + } + } + if (rerr) { + ray_scan_fail_note(&c->fail, r0, rerr); + atomic_fetch_add_explicit(&c->done, 1, memory_order_relaxed); + continue; + } + int64_t* to = c->toff + (size_t)t * (P + 1); + int64_t base = t * c->S; + for (uint32_t p = 0; p < P; p++) { + to[p] = base; + uint32_t k = hist[p]; + hist[p] = (uint32_t)(base - t * c->S); + base += k; + } + to[P] = base; + cdb_rec_t* region = c->recs + t * c->S; + for (int64_t i = 0; i < ns; i++) region[hist[sp[i]]++] = st[i]; + atomic_fetch_add_explicit(&c->done, 1, memory_order_relaxed); + } + if (kenc) ray_col_cursor_free(&kcur); + if (xenc) ray_col_cursor_free(&xcur); +} + +/* Slot layouts: values of VT, tags of GT — 4-byte values for a narrow + * column, 2-byte tags below 65535 groups. Rehash fills a fresh block + * (from the old one when it grew), insert adds a run of records (the main + * thread sized the block for all of them at load <= 3/4), count adds each + * occupied slot to its group's count. */ +#define CDB_SET_FNS(SFX, VT, GT) \ +static void cdb_rehash_##SFX(cdb_set_t* s) { \ + VT* nx = (VT*)s->blk; \ + GT* ng = (GT*)((char*)s->blk + s->cap * sizeof(VT)); \ + memset(ng, 0, s->cap * sizeof(GT)); \ + if (!s->old) return; \ + const VT* ox = (const VT*)s->old; \ + const GT* og = (const GT*)((const char*)s->old + s->ocap * sizeof(VT)); \ + uint64_t cap = s->cap; \ + for (uint64_t i = 0; i < s->ocap; i++) { \ + GT g = og[i]; \ + if (!g) continue; \ + uint64_t slot = cdb_slot((uint32_t)cdb_hash((int64_t)ox[i], g), cap); \ + while (ng[slot]) if (++slot == cap) slot = 0; \ + ng[slot] = g; \ + nx[slot] = ox[i]; \ + } \ +} \ +static int64_t cdb_insert_##SFX(cdb_set_t* s, const cdb_rec_t* r, int64_t n) { \ + VT* xs = (VT*)s->blk; \ + GT* gs = (GT*)((char*)s->blk + s->cap * sizeof(VT)); \ + uint64_t cap = s->cap; \ + int64_t have = s->n; \ + int64_t room = (int64_t)(cap * 3 / 4); /* load the set may reach */ \ + int64_t i = 0; \ + for (; i < n; i++) { \ + if (i + 8 < n) { \ + uint64_t ps = cdb_slot(r[i + 8].h, cap); \ + __builtin_prefetch(&gs[ps]); \ + __builtin_prefetch(&xs[ps]); \ + } \ + GT g = (GT)r[i].g; \ + VT x = (VT)r[i].x; \ + uint64_t slot = cdb_slot(r[i].h, cap); \ + for (;;) { \ + GT cur = gs[slot]; \ + if (!cur) break; \ + if (cur == g && xs[slot] == x) break; \ + if (++slot == cap) slot = 0; \ + } \ + if (gs[slot]) continue; /* seen before */ \ + if (have >= room) break; /* full: grow, then go on */ \ + gs[slot] = g; \ + xs[slot] = x; \ + have++; \ + } \ + s->n = have; \ + return i; \ +} \ +static void cdb_count_##SFX(const cdb_set_t* s, int64_t* cnt, bool shared) { \ + const GT* gs = (const GT*)((const char*)s->blk + s->cap * sizeof(VT)); \ + if (shared) { \ + for (uint64_t i = 0; i < s->cap; i++) \ + if (gs[i]) __atomic_fetch_add(&cnt[gs[i] - 1], 1, __ATOMIC_RELAXED); \ + } else { \ + for (uint64_t i = 0; i < s->cap; i++) \ + if (gs[i]) cnt[gs[i] - 1]++; \ + } \ +} + +CDB_SET_FNS(v8g4, int64_t, uint32_t) +CDB_SET_FNS(v8g2, int64_t, uint16_t) +CDB_SET_FNS(v4g4, uint32_t, uint32_t) +CDB_SET_FNS(v4g2, uint32_t, uint16_t) +#undef CDB_SET_FNS + +static void cdb_rehash(int var, cdb_set_t* s) { + switch (var) { + case 0: cdb_rehash_v8g4(s); break; + case 1: cdb_rehash_v8g2(s); break; + case 2: cdb_rehash_v4g4(s); break; + default: cdb_rehash_v4g2(s); break; + } +} +static int64_t cdb_insert(int var, cdb_set_t* s, const cdb_rec_t* r, int64_t n) { + switch (var) { + case 0: return cdb_insert_v8g4(s, r, n); + case 1: return cdb_insert_v8g2(s, r, n); + case 2: return cdb_insert_v4g4(s, r, n); + default: return cdb_insert_v4g2(s, r, n); + } +} +static void cdb_count(int var, const cdb_set_t* s, int64_t* cnt, bool shared) { + switch (var) { + case 0: cdb_count_v8g4(s, cnt, shared); break; + case 1: cdb_count_v8g2(s, cnt, shared); break; + case 2: cdb_count_v4g4(s, cnt, shared); break; + default: cdb_count_v4g2(s, cnt, shared); break; + } +} + +/* Phase B: task i adds the chunk's records of partition plist[i] to its + * set, from where it stopped last, until they are all in or the set reaches + * load 3/4 (`full`: the main thread grows it and dispatches it again). */ +static void cdb_insert_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + cdb_ctx_t* c = (cdb_ctx_t*)vctx; + for (int64_t i = start; i < end; i++) { + uint32_t p = c->plist[i]; + cdb_set_t* s = &c->sets[p]; + if (s->fresh) { cdb_rehash(c->var, s); s->fresh = false; } + s->full = false; + int64_t before = s->n; + for (uint32_t t = s->rt; t < c->T_c; t++, s->ri = 0) { + const int64_t* to = c->toff + (size_t)t * (c->P + 1); + int64_t n = to[p + 1] - to[p] - s->ri; + if (n <= 0) continue; + int64_t took = cdb_insert(c->var, s, c->recs + to[p] + s->ri, n); + s->seen += took; + if (took < n) { s->rt = t; s->ri += took; s->full = true; break; } + } + if (!s->full) { s->rt = c->T_c; s->ri = 0; } + s->added += s->n - before; + atomic_fetch_add_explicit(&c->done, 1, memory_order_relaxed); + } +} + +/* End of a round: each finished partition's pairs, counted per group. */ +static void cdb_count_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + cdb_ctx_t* c = (cdb_ctx_t*)vctx; + int64_t* cnt = c->cnt_shared ? c->cnt : c->cnt + (size_t)wid * (size_t)c->n_groups; + for (int64_t i = start; i < end; i++) { + const cdb_set_t* s = &c->sets[c->lo + (uint32_t)i]; + if (s->blk) cdb_count(c->var, s, cnt, c->cnt_shared); + atomic_fetch_add_explicit(&c->done, 1, memory_order_relaxed); + } +} + +/* Run fn over n tasks: on the pool, or here. False when tasks were + * skipped (a cancel). */ +static bool cdb_run(ray_pool_t* pool, bool par, ray_pool_fn fn, cdb_ctx_t* c, uint32_t n) { + if (n == 0) return true; + atomic_store_explicit(&c->done, 0, memory_order_relaxed); + if (par) ray_pool_dispatch_n(pool, fn, c, n); + else fn(c, 0, 0, n); + if (atomic_load_explicit(&c->done, memory_order_relaxed) != (int64_t)n) return false; + if (ray_interrupted()) return false; + if (pool && atomic_load_explicit(&pool->cancelled, memory_order_relaxed)) return false; + return true; +} + +static void cdb_free_set(cdb_set_t* s) { + ray_free_raw(s->blk); + ray_free_raw(s->old); + memset(s, 0, sizeof(*s)); +} + +/* What the anon watermark leaves: the room under it, the committed blocks + * the calling heap can reuse added back (a heap keeps the pools a query + * freed; counted as taken they made a repeat of the same query look short of + * memory). INT64_MAX when the RAM is unknown. */ +static int64_t cdb_room(void) { + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return INT64_MAX; + return wm - ray_heap_anon_committed() + ray_heap_anon_reusable(); +} + +/* The bytes the kernel may give its sets: three quarters of the room, and + * when that is less, a sixteenth of the watermark or a quarter of the + * slices' row buffers (`demand`), whichever is less, CDB_MIN_BUDGET at + * least — a room used up by other work does not shrink the sets to nothing + * (one round a partition). */ +static int64_t cdb_budget(int64_t demand) { + int64_t room = cdb_room(); + if (room == INT64_MAX) return INT64_MAX; + int64_t b = room / 4 * 3; + int64_t floor = ray_heap_anon_watermark() / 16; + if (floor > demand / 4) floor = demand / 4; + if (floor < CDB_MIN_BUDGET) floor = CDB_MIN_BUDGET; + return b > floor ? b : floor; +} + +/* Up to `cap` row indices spread evenly over the rows `sel` keeps; *pop + * receives how many it keeps. Returns the count. */ +static int64_t cdb_sel_sample(ray_t* sel, int64_t nrows, int64_t* out, int64_t cap, int64_t* pop) { + ray_rowsel_t* sm = ray_rowsel_meta(sel); + const uint8_t* flg = ray_rowsel_flags(sel); + const uint32_t* offs = ray_rowsel_offsets(sel); + const uint16_t* idx = ray_rowsel_idx(sel); + int64_t total = sm->total_pass; + *pop = total; + if (total <= 0) return 0; + int64_t step = total / cap + (total % cap != 0); + int64_t j = 0, next = 0, n = 0; /* j: kept rows before this morsel */ + for (int64_t m = 0; m < (int64_t)sm->n_segs && n < cap; m++) { + int64_t lo = m * RAY_MORSEL_ELEMS, hi = lo + RAY_MORSEL_ELEMS; + if (hi > nrows) hi = nrows; + if (flg[m] == RAY_SEL_NONE) continue; + int64_t k = flg[m] == RAY_SEL_ALL ? hi - lo : (int64_t)(offs[m + 1] - offs[m]); + while (next < j + k && n < cap) { + int64_t at = next - j; + out[n++] = lo + (flg[m] == RAY_SEL_ALL ? at : idx[offs[m] + at]); + next += step; + } + j += k; + } + return n; +} + +/* A partition both parted columns have rows in, the largest: the sample the + * route reads them through. -1 when there is none. */ +static int64_t cdb_parted_rep(ray_t* key, ray_t* val) { + ray_t** ks = (ray_t**)ray_data(key); + ray_t** vs = (ray_t**)ray_data(val); + int64_t best = -1, rows = 0; + for (int64_t s = 0; s < key->len && s < val->len; s++) { + ray_t* a = ks[s]; + ray_t* b = vs[s]; + if (!a || !b || RAY_IS_ERR(a) || RAY_IS_ERR(b) || a->len != b->len) continue; + if (a->len > rows) { rows = a->len; best = s; } + } + return best; +} + +bool ray_cd_bounded_preferred(ray_t* tbl, ray_t* key, ray_t* val, ray_t* sel, + int64_t nrows, int64_t n_groups) { + if (nrows <= 0 || n_groups <= 0) return false; + bool kp = key && (RAY_IS_PARTED(key->type) || key->type == RAY_MAPCOMMON); + bool vp = val && (RAY_IS_PARTED(val->type) || val->type == RAY_MAPCOMMON); + bool ke = key && key->type == RAY_ENCCOL, ve = val && val->type == RAY_ENCCOL; /* decoded whole by the slices */ + /* Memory first: the slices' row buffers — row map and index, 16 B a + * row, or row map and scattered pairs past 50 K groups, 24 — and the + * flat copies they make of parted columns, 8 B a row each, against half + * of the room under the anon watermark. Past it they spill, and the + * gathers over them and the inputs turn into rewrites of the spill + * files: the bounded kernel, whatever the data. */ + int64_t wm = ray_heap_anon_watermark(); + if (wm > 0) { + double need = (double)nrows * ((n_groups <= 50000 ? 16.0 : 24.0) + (kp || ke ? 8 : 0) + (vp || ve ? 8 : 0)); + /* the reusable blocks (a freelist walk) only when the room without + * them is short */ + if (need > (double)(wm - ray_heap_anon_committed()) / 2 && + need > (double)cdb_room() / 2) return true; + } + if (n_groups > 50000 || nrows < CDB_MIN_ROWS || !key || !val) return false; + /* In memory both fit; the slices dedup each group in cache but serially + * over a group, the bounded kernel spreads every pair over the workers + * but holds the distinct pairs in sets read at random. The bounded + * kernel where one group holds more than CDB_SKEW workers' shares of the + * rows (1.4x to 4x faster on 48 workers over 100 M rows, 3 groups or + * 9 K with one of 18%) or the pairs dedup to a quarter of the rows + * (6.5x, 2 K values a group); the slices for even groups of nearly + * distinct pairs (1.6x faster there: 100 M rows, 9 K groups, 95 M + * pairs). A column read from storage is read here in order where the + * slices gather it at the rows of each group. Sampled estimates + * (agg_group_card_sample) — over the rows a selection keeps, and over + * one partition of a parted pair — from CDB_SAMPLE_ROWS rows: the + * sample's scattered reads take some 6 ms, a quarter of a 10 M-row count + * the slices finish in 25 ms. */ + ray_t* cols[2] = { key, val }; + int64_t srows = nrows, scale_num = 1, scale_den = 1; + if (kp || vp) { + if (!(RAY_IS_PARTED(key->type) && RAY_IS_PARTED(val->type))) return false; + int64_t r = cdb_parted_rep(key, val); + if (r < 0) return false; + cols[0] = ((ray_t**)ray_data(key))[r]; + cols[1] = ((ray_t**)ray_data(val))[r]; + srows = cols[0]->len; + scale_num = nrows; + scale_den = srows > 0 ? srows : 1; + sel = NULL; /* a selection is over the whole table's rows */ + } + /* an encoded column is not in memory as values either: it is read in + * order, a vector at a time, where the slices would decode it whole */ + if (cols[0]->type == RAY_ENCCOL || cols[1]->type == RAY_ENCCOL) return true; + if (ray_col_cold(cols[0]) || ray_col_cold(cols[1])) return true; + if (nrows < CDB_SAMPLE_ROWS) return false; + int64_t kmax = 0, pairs = 0; + bool ok; + if (sel) { + int64_t cap = AGG_EST_SAMPLE_ROWS * 2, pop = 0; + int64_t* rows = (int64_t*)ray_alloc_raw((size_t)cap * sizeof(int64_t)); + if (!rows) return false; + int64_t n = cdb_sel_sample(sel, nrows, rows, cap, &pop); + ok = n > 0 && agg_group_card_sample(cols, 2, 1, rows, n, pop, NULL, NULL, &kmax, &pairs); + ray_free_raw(rows); + if (!ok) return false; + nrows = pop; + } else { + ok = agg_group_card_sample(cols, 2, 1, NULL, srows, 0, NULL, NULL, &kmax, &pairs); + if (!ok) return false; + kmax = (int64_t)((double)kmax * scale_num / scale_den); + pairs = (int64_t)((double)pairs * scale_num / scale_den); + } + ray_pool_t* pool = ray_pool_get(); + int64_t workers = pool ? ray_pool_total_workers(pool) : 1; + if (workers > 1 && kmax > nrows / workers * CDB_SKEW) return true; + return pairs <= nrows / 4; +} + +/* The bytes of the buddy block that holds `n` pairs at load 3/4: twice + * `prev` at least (a power of two, header included). */ +static uint64_t cdb_block_for(uint64_t prev, uint64_t n, size_t sb) { + uint64_t nb = prev ? prev * 2 : CDB_SET_MIN_BYTES; + while ((nb - 32) / sb * 3 < n * 4) nb <<= 1; + return nb; +} + +/* The pairs to size a full set for: its pairs, and the share of its records + * so far that were new over the records it has left (a quarter over); for a + * set without a block, the pairs a partition ended the last round with. */ +static uint64_t cdb_want_pairs(const cdb_set_t* s, int64_t expect) { + if (!s->blk) return expect > 0 ? (uint64_t)expect : 0; + double rate = (double)(s->added + 1) / (double)(s->seen + 1); + return (uint64_t)s->n + (uint64_t)(rate * (double)(s->inc - s->seen) * 1.25) + 16; +} + +/* ray_cd_bounded's body; one_group: no key, every row is group 0 of 1. */ +static ray_t* cdb_bounded_run(ray_t* tbl, ray_t* key_col, ray_t* grp_keys, + const int64_t* row_gid, int64_t n_groups, + ray_t* val_col, ray_t* sel, int64_t nrows, bool one_group); + +ray_t* ray_cd_bounded(ray_t* tbl, ray_t* key_col, ray_t* grp_keys, + const int64_t* row_gid, int64_t n_groups, + ray_t* val_col, ray_t* sel, int64_t nrows) { + return cdb_bounded_run(tbl, key_col, grp_keys, row_gid, n_groups, val_col, sel, nrows, false); +} + +ray_t* ray_cd_bounded_all(ray_t* val_col, int64_t nrows) { + ray_t* r = cdb_bounded_run(NULL, NULL, NULL, NULL, 1, val_col, NULL, nrows, true); + if (!r || RAY_IS_ERR(r)) return r; + int64_t cnt = r->len > 0 ? ((const int64_t*)ray_data(r))[0] : 0; + ray_release(r); + return ray_i64(cnt); +} + +static ray_t* cdb_bounded_run(ray_t* tbl, ray_t* key_col, ray_t* grp_keys, + const int64_t* row_gid, int64_t n_groups, + ray_t* val_col, ray_t* sel, int64_t nrows, bool one_group) { + if (n_groups < 0 || nrows < 0) return NULL; + if (n_groups >= (int64_t)UINT32_MAX - 1) return NULL; + if (!row_gid && !one_group && (!grp_keys || RAY_IS_ERR(grp_keys) || !ray_is_vec(grp_keys) || + !cdb_type_ok(grp_keys->type, false) || grp_keys->len < n_groups)) + return NULL; + + cdb_ctx_t c; + memset(&c, 0, sizeof(c)); + ray_scan_fail_init(&c.fail); + c.one_group = one_group; + ray_t* oerr = NULL; + int rc = cdb_col_open(&c.val, val_col, tbl, true, &oerr); + if (rc <= 0) return oerr; + if (c.val.rows < nrows) { cdb_col_close(&c.val); return NULL; } + if (!row_gid && !one_group) { + rc = cdb_col_open(&c.key, key_col, tbl, false, &oerr); + if (rc <= 0) { cdb_col_close(&c.val); return oerr; } + if (c.key.rows < nrows) { cdb_col_close(&c.key); cdb_col_close(&c.val); return NULL; } + } + + ray_t* out = ray_vec_new(RAY_I64, n_groups); + if (!out || RAY_IS_ERR(out)) { + cdb_col_close(&c.key); cdb_col_close(&c.val); + return out ? out : ray_error("oom", NULL); + } + out->len = n_groups; + int64_t* odata = (int64_t*)ray_data(out); + if (n_groups > 0) memset(odata, 0, (size_t)n_groups * sizeof(int64_t)); + if (n_groups == 0 || nrows == 0) { + cdb_col_close(&c.key); cdb_col_close(&c.val); + return out; + } + + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, nrows, 2 * CDB_TASK_ROWS); + uint32_t W = par ? ray_pool_total_workers(pool) : 1; + uint32_t P = 256; + while (P < CDB_MAX_PARTS && P < 8 * W) P <<= 1; + uint32_t T = par ? 2 * W : 1; + if (T > 512) T = 512; + /* The record buffer and the staging (18 B a row of a task, T and W + * tasks' worth) within a quarter of the budget: shorter tasks, then + * fewer of them, down to one a worker. */ + int64_t budget_cap = (int64_t)((double)(sel ? ray_rowsel_meta(sel)->total_pass : nrows) * (n_groups <= 50000 ? 16.0 : 24.0)); + int64_t budget = cdb_budget(budget_cap); + int64_t S = CDB_TASK_ROWS; + while ((int64_t)(T + W) * S * 18 > budget / 4 && S > CDB_TASK_ROWS_MIN) S /= 2; + while ((int64_t)(T + W) * S * 18 > budget / 4 && T > W) T--; + int64_t chunk_rows = (int64_t)T * S; + + c.row_gid = row_gid; + c.n_groups = n_groups; + c.nrows = nrows; + c.vmask = c.val.narrow ? UINT32_MAX : UINT64_MAX; + c.P = P; + c.pshift = 64 - (uint32_t)__builtin_ctz(P); + c.T = T; + c.S = S; + c.var = (c.val.narrow ? 2 : 0) + (n_groups < 65535 ? 1 : 0); + size_t sb = (c.val.narrow ? 4 : 8) + (n_groups < 65535 ? 2 : 4); /* bytes a slot */ + if (sel) { + ray_rowsel_t* sm = ray_rowsel_meta(sel); + c.sel_flg = ray_rowsel_flags(sel); + c.sel_offs = ray_rowsel_offsets(sel); + c.sel_idx = ray_rowsel_idx(sel); + c.sel_nsegs = sm->n_segs; + } + + /* Working buffers: all sized by the workers, partitions and groups. */ + ray_t* err = NULL; + void *khdr = NULL; + uint32_t* plist = NULL; + int64_t* selpre = NULL; + uint64_t kcap = 16; + bool by_key = !row_gid && !one_group; /* rows map to groups through the key table */ + if (by_key) while (kcap < (uint64_t)n_groups * 2) kcap <<= 1; + bool cnt_shared = (int64_t)W * n_groups > CDB_LOCAL_CNT; + size_t cnt_cells = cnt_shared ? (size_t)n_groups : (size_t)W * (size_t)n_groups; + c.cnt_shared = cnt_shared; + c.recs = (cdb_rec_t*)ray_alloc_raw((size_t)chunk_rows * sizeof(cdb_rec_t)); + c.stage = (cdb_rec_t*)ray_alloc_raw((size_t)W * (size_t)S * sizeof(cdb_rec_t)); + c.spart = (uint16_t*)ray_alloc_raw((size_t)W * (size_t)S * sizeof(uint16_t)); + c.toff = (int64_t*)ray_alloc_raw((size_t)T * (P + 1) * sizeof(int64_t)); + c.sets = (cdb_set_t*)ray_calloc_raw((size_t)P * sizeof(cdb_set_t)); + c.cnt = (int64_t*)ray_calloc_raw(cnt_cells * sizeof(int64_t)); + plist = (uint32_t*)ray_alloc_raw((size_t)P * sizeof(uint32_t)); + if (by_key) khdr = ray_calloc_raw((size_t)kcap * (sizeof(int64_t) + sizeof(uint32_t))); + if (!c.recs || !c.stage || !c.spart || !c.toff || !c.sets || !c.cnt || !plist || + (by_key && !khdr)) { + err = ray_error("oom", NULL); + goto done; + } + c.plist = plist; + if (row_gid && c.sel_flg) { + /* a row map over the kept rows: rank of the first kept row of each segment */ + selpre = (int64_t*)ray_alloc_raw((size_t)(c.sel_nsegs + 1) * sizeof(int64_t)); + if (!selpre) { err = ray_error("oom", NULL); goto done; } + int64_t run = 0; + for (int64_t s = 0; s < c.sel_nsegs; s++) { + selpre[s] = run; + if (c.sel_flg[s] == RAY_SEL_ALL) { + int64_t lo = s * RAY_MORSEL_ELEMS; + run += nrows - lo < RAY_MORSEL_ELEMS ? nrows - lo : RAY_MORSEL_ELEMS; + } else if (c.sel_flg[s] != RAY_SEL_NONE) { + run += c.sel_offs[s + 1] - c.sel_offs[s]; + } + } + selpre[c.sel_nsegs] = run; + c.sel_pre = selpre; + } + if (by_key) { + int64_t* kk = (int64_t*)khdr; + uint32_t* kt = (uint32_t*)(kk + kcap); + uint64_t kmask = kcap - 1; + const void* gd = ray_data(grp_keys); + for (int64_t gi = 0; gi < n_groups; gi++) { + int64_t k = read_col_i64(gd, gi, grp_keys->type, grp_keys->attrs); + uint64_t h = (uint64_t)k * 0x9E3779B97F4A7C15ULL; + h ^= h >> 33; + uint64_t s = h & kmask; + while (kt[s] && kk[s] != k) s = (s + 1) & kmask; + if (!kt[s]) { kt[s] = (uint32_t)(gi + 1); kk[s] = k; } /* a repeat keeps the first */ + } + c.kkeys = kk; + c.ktag = kt; + c.kmask = kmask; + } + + int64_t overhead = (int64_t)chunk_rows * (int64_t)sizeof(cdb_rec_t) + + (int64_t)W * S * (int64_t)(sizeof(cdb_rec_t) + 2) + + (int64_t)cnt_cells * 8 + (int64_t)kcap * 12; + if (budget != INT64_MAX) { + int64_t floor = budget / 4; /* the sets keep three quarters at least */ + budget = budget - overhead > floor ? budget - overhead : floor; + } + /* Past CDB_MAX_ROUNDS rounds' worth of pairs the sets may pass the + * budget, up to what the slices would have taken; the first trim + * projects the round's sets over the rows left. */ + bool projected = budget == INT64_MAX; + bool want = ray_pool_scan_on() && nrows > 0; + int64_t ra_rows = CDB_RA_BYTES / 12; + if (ra_rows < 2 * chunk_rows) ra_rows = 2 * chunk_rows; + + uint32_t lo = 0, hi = P; + int64_t expect = 0; /* pairs a partition ended the last round with */ + while (lo < P) { + c.lo = lo; + c.hi = hi; + int64_t live = 0; /* bytes of the round's set blocks */ + int64_t ra_hi = 0; + for (int64_t r0 = 0; r0 < nrows; r0 += chunk_rows) { + int64_t r1 = r0 + chunk_rows < nrows ? r0 + chunk_rows : nrows; + if (want) { + int64_t ra = r1 + ra_rows < nrows ? r1 + ra_rows : nrows; + if (ra > ra_hi) { + cdb_want_rows(&c, ra_hi > r0 ? ra_hi : r0, ra); + ra_hi = ra; + } + } + c.chunk_r0 = r0; + c.T_c = (uint32_t)((r1 - r0 + S - 1) / S); + bool ran = cdb_run(pool, par, cdb_scatter_fn, &c, c.T_c); + if (ray_scan_failed(&c.fail)) { err = ray_scan_fail_finish(&c.fail, NULL); goto done; } + if (!ran) { + err = ray_error("cancel", "interrupted"); + goto done; + } + /* The partitions with records in this chunk; a set without a + * block gets one first. */ + uint32_t np = 0; + for (uint32_t p = lo; p < c.hi; p++) { + cdb_set_t* s = &c.sets[p]; + int64_t inc = 0; + for (uint32_t t = 0; t < c.T_c; t++) { + const int64_t* to = c.toff + (size_t)t * (P + 1); + inc += to[p + 1] - to[p]; + } + s->inc = inc; s->seen = s->added = 0; s->rt = 0; s->ri = 0; + s->full = inc > 0 && !s->blk; + if (inc > 0) plist[np++] = p; + } + /* Phase B, then the sets that filled grow and go on. A set grows + * to twice its block at least, and to the pairs its records so + * far promise for the rest of them. Growth that would pass the + * budget frees the round's top partitions instead (a later round + * counts them). */ + while (np > 0) { + int64_t grow = 0; + for (uint32_t i = 0; i < np; i++) { + cdb_set_t* s = &c.sets[plist[i]]; + if (s->full) grow += (int64_t)cdb_block_for(s->bytes, cdb_want_pairs(s, expect), sb); + } + if (live + grow > budget && c.hi - lo > 1) { + if (!projected) { + /* the sets this round is heading for, over the rows left */ + double rows_in = (double)r1; + double total = (double)(live + grow) * ((double)nrows / rows_in); + if (total > (double)budget * CDB_MAX_ROUNDS) { + int64_t nb = (int64_t)(total / CDB_MAX_ROUNDS); + if (nb > budget_cap) nb = budget_cap; + if (nb > budget) budget = nb; + } + projected = true; + } + bool trimmed = false; + while (live + grow > budget && c.hi - lo > 1) { + uint32_t p = c.hi - 1; + cdb_set_t* s = &c.sets[p]; + if (s->full) grow -= (int64_t)cdb_block_for(s->bytes, cdb_want_pairs(s, expect), sb); + live -= (int64_t)s->bytes; + cdb_free_set(s); + c.hi--; + trimmed = true; + } + if (trimmed) { + uint32_t k = 0; + for (uint32_t i = 0; i < np; i++) if (plist[i] < c.hi) plist[k++] = plist[i]; + np = k; + ray_profile_tick("count-distinct: partitions left to the next round"); + } + } + for (uint32_t i = 0; i < np; i++) { + cdb_set_t* s = &c.sets[plist[i]]; + if (!s->full) continue; + uint64_t nb = cdb_block_for(s->bytes, cdb_want_pairs(s, expect), sb); + uint64_t nc = (nb - 32) / sb; + if (nc > UINT32_MAX) { err = ray_error("oom", NULL); goto done; } + void* blk = ray_alloc_raw((size_t)(nb - 32)); + if (!blk) { err = ray_error("oom", NULL); goto done; } + s->old = s->blk; s->ocap = s->cap; s->obytes = s->bytes; + s->blk = blk; s->cap = nc; s->bytes = nb; + s->fresh = true; + live += (int64_t)nb; + } + if (np == 0) break; + bool ok = cdb_run(pool, par, cdb_insert_fn, &c, np); + uint32_t k = 0; + for (uint32_t i = 0; i < np; i++) { + cdb_set_t* s = &c.sets[plist[i]]; + if (s->old) { + ray_free_raw(s->old); + live -= (int64_t)s->obytes; + s->old = NULL; s->ocap = 0; s->obytes = 0; + } + if (s->full) plist[k++] = plist[i]; + } + np = k; + if (!ok) { err = ray_error("cancel", "interrupted"); goto done; } + } + } + hi = c.hi; + if (!cdb_run(pool, par, cdb_count_fn, &c, hi - lo)) { + err = ray_error("cancel", "interrupted"); + goto done; + } + int64_t pairs = 0; + for (uint32_t p = lo; p < hi; p++) { pairs += c.sets[p].n; cdb_free_set(&c.sets[p]); } + ray_profile_tick("count-distinct: bounded round"); + /* the next round: as many partitions as the budget holds at the + * bytes a partition took in this one */ + int64_t per = live / (int64_t)(hi - lo); + expect = pairs / (int64_t)(hi - lo); + lo = hi; + if (lo >= P) break; + int64_t take = per > 0 ? budget / 8 * 7 / per : (int64_t)P; + if (take < 1) take = 1; + hi = (int64_t)lo + take < (int64_t)P ? lo + (uint32_t)take : P; + } + + if (cnt_shared) { + memcpy(odata, c.cnt, (size_t)n_groups * sizeof(int64_t)); + } else { + for (uint32_t w = 0; w < W; w++) { + const int64_t* wc = c.cnt + (size_t)w * (size_t)n_groups; + for (int64_t g = 0; g < n_groups; g++) odata[g] += wc[g]; + } + } + +done: + if (c.sets) for (uint32_t p = 0; p < P; p++) cdb_free_set(&c.sets[p]); + ray_free_raw(c.sets); + ray_free_raw(c.recs); + ray_free_raw(c.stage); + ray_free_raw(c.spart); + ray_free_raw(c.toff); + ray_free_raw(c.cnt); + ray_free_raw(plist); + ray_free_raw(selpre); + ray_free_raw(khdr); + cdb_col_close(&c.key); + cdb_col_close(&c.val); + if (err) { ray_release(out); return err; } + return out; +} diff --git a/src/ops/cdfuse.h b/src/ops/cdfuse.h index b6bf83440..3c168bd6a 100644 --- a/src/ops/cdfuse.h +++ b/src/ops/cdfuse.h @@ -63,4 +63,56 @@ bool ray_cd_two_pass_preferred(ray_t** K_cols, int n_K, ray_t* X_col, const int64_t* rows, int64_t nrows, int64_t population, int64_t workers); +/* Grouped count-distinct in bounded memory (the post-group scatter of a + * select whose `(count (distinct X))` sits beside a group by K). One + * sequential pass over the K and X columns per round: each row's group id + * comes from K through a table of the n_groups result keys `grp_keys` + * (rows whose key is not among them are skipped), or from `row_gid` when + * the caller has the row map already (then `key_col` and `grp_keys` are + * unused, and the map carries the selection as -1 — or, with `sel` given + * too, holds one id for each row `sel` keeps, in order: sel->total_pass + * ids, not nrows). The (group, value) + * pairs are hash-partitioned and deduplicated chunk by chunk into + * partition-local sets; when the sets would outgrow the memory budget (a + * share of what the anon watermark leaves), the partitions past it are + * dropped and counted by a further pass over the input instead — up to + * about CDB_MAX_ROUNDS passes, past which the sets may pass the budget. No + * per-row index, no per-group slices. + * + * key_col/val_col: flat vectors, parted columns (a missing partition's rows + * read as nulls, sized by the partition counts of `tbl`) or MAPCOMMON. Key + * types: BOOL U8 I16 I32 I64 DATE TIME TIMESTAMP SYM; value types the same + * and F64. `sel` is a rowsel over the nrows rows or NULL. A null value is + * one distinct value, as on every other count-distinct path. + * + * Returns an I64 vector of n_groups counts (group i of grp_keys / row_gid + * id i), an error (oom, cancel), or NULL when a column is not served (a type + * it does not read, fewer rows than nrows). */ +ray_t* ray_cd_bounded(ray_t* tbl, ray_t* key_col, ray_t* grp_keys, + const int64_t* row_gid, int64_t n_groups, + ray_t* val_col, ray_t* sel, int64_t nrows); + +/* The count of distinct values of val_col's first nrows rows, in bounded + * memory: ray_cd_bounded over one group (every row in it). An I64 atom, an + * error, or NULL when the column is not served. */ +ray_t* ray_cd_bounded_all(ray_t* val_col, int64_t nrows); + +/* Whether ray_cd_bounded serves `col` as a key (is_val false) or a value: + * a flat, parted or MAPCOMMON column, or a single-file encoded one (a + * RAY_ENCCOL slot, read by range, never decoded whole) from its metadata. */ +bool ray_cd_bounded_col_ok(ray_t* col, bool is_val); + +/* Whether the scatter of a count-distinct of `val` over nrows rows of `tbl` + * (those `sel` keeps, when given) into n_groups groups of `key` takes + * ray_cd_bounded rather than the per-group slices (or the global hash past + * 50 K groups): when the slices' row buffers and the flat copies of parted + * columns would not fit half of the room under the anon watermark; else, + * from CDB_MIN_ROWS rows up to 50 K groups, for a column not resident, and + * from 64 M rows for a dominant group or pairs that dedup to a quarter of + * the rows (sampled; over one partition of a parted pair). key/val NULL (a + * composite key, a row map built anyway): memory alone. */ +#define CDB_MIN_ROWS 65536 +bool ray_cd_bounded_preferred(ray_t* tbl, ray_t* key, ray_t* val, ray_t* sel, + int64_t nrows, int64_t n_groups); + #endif /* RAY_OPS_CDFUSE_H */ diff --git a/src/ops/cmp.c b/src/ops/cmp.c index fbbe083de..e5c9ff335 100644 --- a/src/ops/cmp.c +++ b/src/ops/cmp.c @@ -84,6 +84,7 @@ static inline int both_int_atoms(const ray_t* a, const ray_t* b) { /* Comparison */ ray_t* ray_gt_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_GT, a, b); { int c; if (char_str_cmp(a, b, &c) == 0) return make_bool(c > 0 ? 1 : 0); } if (a->type == -RAY_SYM && b->type == -RAY_SYM) return make_bool(sym_atom_cmp(a, b) > 0 ? 1 : 0); @@ -107,6 +108,7 @@ ray_t* ray_gt_fn(ray_t* a, ray_t* b) { } ray_t* ray_lt_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_LT, a, b); { int c; if (char_str_cmp(a, b, &c) == 0) return make_bool(c < 0 ? 1 : 0); } if (a->type == -RAY_SYM && b->type == -RAY_SYM) return make_bool(sym_atom_cmp(a, b) < 0 ? 1 : 0); @@ -129,6 +131,7 @@ ray_t* ray_lt_fn(ray_t* a, ray_t* b) { } ray_t* ray_gte_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_GE, a, b); { int c; if (char_str_cmp(a, b, &c) == 0) return make_bool(c >= 0 ? 1 : 0); } if (a->type == -RAY_SYM && b->type == -RAY_SYM) return make_bool(sym_atom_cmp(a, b) >= 0 ? 1 : 0); @@ -152,6 +155,7 @@ ray_t* ray_gte_fn(ray_t* a, ray_t* b) { } ray_t* ray_lte_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_LE, a, b); { int c; if (char_str_cmp(a, b, &c) == 0) return make_bool(c <= 0 ? 1 : 0); } if (a->type == -RAY_SYM && b->type == -RAY_SYM) return make_bool(sym_atom_cmp(a, b) <= 0 ? 1 : 0); @@ -174,28 +178,65 @@ ray_t* ray_lte_fn(ray_t* a, ray_t* b) { return make_bool(as_f64(a) <= as_f64(b) ? 1 : 0); } -/* Elementwise dyadic overloads for the aggregate names `min` and `max`. - * Their vectorization is supplied by the evaluator, just like comparisons. */ -ray_t* ray_min2_fn(ray_t* a, ray_t* b) { - ray_t* cmp = ray_lte_fn(a, b); - if (!cmp || RAY_IS_ERR(cmp)) return cmp ? cmp : ray_error("oom", NULL); - ray_t* out = cmp->b8 ? a : b; - ray_retain(out); - ray_release(cmp); - return out; +/* Rank of a numeric atom type in the promotion order min/max use, or -1. */ +static int minmax_rank(int8_t t) { + switch (t) { + case -RAY_BOOL: return 0; + case -RAY_U8: return 1; + case -RAY_I16: return 2; + case -RAY_I32: return 3; + case -RAY_I64: return 4; + case -RAY_F32: return 5; + case -RAY_F64: return 6; + default: return -1; + } } -ray_t* ray_max2_fn(ray_t* a, ray_t* b) { - ray_t* cmp = ray_gte_fn(a, b); +/* The atom type the result of (min a b) / (max a b) takes: the wider of + * two numeric types (BOOL < U8 < I16 < I32 < I64 < F32 < F64), or + * TIMESTAMP for a DATE against a TIMESTAMP, so an integer against a float + * is a float and a boolean against an integer an integer. 0 when the + * types already agree or no promotion applies. */ +static int8_t minmax_type(ray_t* a, ray_t* b) { + if (a->type == b->type) return 0; + int ra = minmax_rank(a->type), rb = minmax_rank(b->type); + if (ra >= 0 && rb >= 0) return ra > rb ? a->type : b->type; + if ((a->type == -RAY_DATE && b->type == -RAY_TIMESTAMP) || + (a->type == -RAY_TIMESTAMP && b->type == -RAY_DATE)) + return -RAY_TIMESTAMP; + return 0; +} + +/* `x` as an atom of type `t` (from minmax_type); a null stays null. */ +static ray_t* minmax_promote(ray_t* x, int8_t t) { + if (RAY_ATOM_IS_NULL(x)) return ray_typed_null(t); + if (t == -RAY_TIMESTAMP) return ray_timestamp(temporal_as_ns(x)); + if (t == -RAY_F64) return make_f64(as_f64(x)); + if (t == -RAY_F32) return ray_f32((float)as_f64(x)); + int64_t v = x->type == -RAY_BOOL ? (int64_t)(x->b8 != 0) : as_i64(x); + return make_typed_int(t, v); +} + +/* Elementwise dyadic overloads for the aggregate names `min` and `max`. + * Their vectorization is supplied by the evaluator, just like comparisons. + * The result takes the promoted type of the two operands (minmax_type), + * whichever of them is chosen. */ +static ray_t* minmax_pick(ray_t* a, ray_t* b, ray_t* cmp) { if (!cmp || RAY_IS_ERR(cmp)) return cmp ? cmp : ray_error("oom", NULL); ray_t* out = cmp->b8 ? a : b; - ray_retain(out); ray_release(cmp); + int8_t t = minmax_type(a, b); + if (t && out->type != t) return minmax_promote(out, t); + ray_retain(out); return out; } +ray_t* ray_min2_fn(ray_t* a, ray_t* b) { return minmax_pick(a, b, ray_lte_fn(a, b)); } +ray_t* ray_max2_fn(ray_t* a, ray_t* b) { return minmax_pick(a, b, ray_gte_fn(a, b)); } + ray_t* ray_eq_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_EQ, a, b); /* Handle null forms (RAY_NULL_OBJ, typed null atoms) */ RAY_ASSERT_VALUE(a); RAY_ASSERT_VALUE(b); int na = RAY_ATOM_IS_NULL(a), nb = RAY_ATOM_IS_NULL(b); @@ -218,6 +259,7 @@ ray_t* ray_eq_fn(ray_t* a, ray_t* b) { } ray_t* ray_neq_fn(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) return ray_timespan_binary(OP_NE, a, b); /* Handle null forms (RAY_NULL_OBJ, typed null atoms) */ RAY_ASSERT_VALUE(a); RAY_ASSERT_VALUE(b); int na = RAY_ATOM_IS_NULL(a), nb = RAY_ATOM_IS_NULL(b); @@ -267,27 +309,74 @@ ray_t* ray_neq_fn(ray_t* a, ray_t* b) { return r; \ } while(0) +/* and/or with a collection operand that is not a BOOL vector — a LIST, or + * a numeric or temporal vector: element by element, never one truth value + * for the whole collection. Each pair goes back + * through `fn`, so a nested list recurses, and a result whose elements + * are all booleans is a B8 vector. An atom broadcasts; two collections + * must have the same length. */ +static ray_t* logic_map(ray_binary_fn fn, const char* name, ray_t* a, ray_t* b) { + int ac = is_collection(a), bc = is_collection(b); + if (ac && bc && ray_len(a) != ray_len(b)) + return ray_error("length", "%s: operand lengths must match, got %lld and %lld", + name, (long long)ray_len(a), (long long)ray_len(b)); + int64_t n = ac ? ray_len(a) : ray_len(b); + ray_t* out = ray_list_new(n > 0 ? n : 1); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + for (int64_t i = 0; i < n; i++) { + int la = 0, lb = 0; + ray_t* ea = ac ? collection_elem(a, i, &la) : a; + ray_t* eb = bc ? collection_elem(b, i, &lb) : b; + ray_t* r = (RAY_IS_ERR(ea) || RAY_IS_ERR(eb)) + ? ray_error("type", NULL) : fn(ea, eb); + if (la) ray_release(ea); + if (lb) ray_release(eb); + if (!r || RAY_IS_ERR(r)) { ray_release(out); return r ? r : ray_error("oom", NULL); } + out = ray_list_append(out, r); + ray_release(r); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + } + if (n == 0) { ray_release(out); return ray_vec_new(RAY_BOOL, 0); } + return ray_list_collapse_bool(out); +} + +static inline bool is_bool_vec(ray_t* x) { + return ray_is_vec(x) && x->type == RAY_BOOL; +} + ray_t* ray_and_fn(ray_t* a, ray_t* b) { /* Element-wise for bool vectors */ - if (ray_is_vec(a) && a->type == RAY_BOOL && ray_is_vec(b) && b->type == RAY_BOOL) + if (is_bool_vec(a) && is_bool_vec(b)) { + if (a->len != b->len) + return ray_error("length", "and: operand lengths must match, got %lld and %lld", + (long long)a->len, (long long)b->len); BOOL_VEC_BINOP(a, b, &); + } /* Scalar broadcast: vec and scalar */ - if (ray_is_vec(a) && a->type == RAY_BOOL && ray_is_atom(b)) + if (is_bool_vec(a) && ray_is_atom(b)) BOOL_VEC_SCALAR_L(a, is_truthy(b), &&); - if (ray_is_atom(a) && ray_is_vec(b) && b->type == RAY_BOOL) + if (ray_is_atom(a) && is_bool_vec(b)) BOOL_VEC_SCALAR_L(b, is_truthy(a), &&); + if (is_collection(a) || is_collection(b)) + return logic_map(ray_and_fn, "and", a, b); return make_bool((is_truthy(a) && is_truthy(b)) ? 1 : 0); } ray_t* ray_or_fn(ray_t* a, ray_t* b) { /* Element-wise for bool vectors */ - if (ray_is_vec(a) && a->type == RAY_BOOL && ray_is_vec(b) && b->type == RAY_BOOL) + if (is_bool_vec(a) && is_bool_vec(b)) { + if (a->len != b->len) + return ray_error("length", "or: operand lengths must match, got %lld and %lld", + (long long)a->len, (long long)b->len); BOOL_VEC_BINOP(a, b, |); + } /* Scalar broadcast */ - if (ray_is_vec(a) && a->type == RAY_BOOL && ray_is_atom(b)) + if (is_bool_vec(a) && ray_is_atom(b)) BOOL_VEC_SCALAR_L(a, is_truthy(b), ||); - if (ray_is_atom(a) && ray_is_vec(b) && b->type == RAY_BOOL) + if (ray_is_atom(a) && is_bool_vec(b)) BOOL_VEC_SCALAR_L(b, is_truthy(a), ||); + if (is_collection(a) || is_collection(b)) + return logic_map(ray_or_fn, "or", a, b); return make_bool((is_truthy(a) || is_truthy(b)) ? 1 : 0); } @@ -401,5 +490,22 @@ ray_t* ray_not_fn(ray_t* x) { r->len = n; return r; } + /* A LIST, element by element: a nested list recurses, and all-boolean + * results make a B8 vector. */ + if (is_list(x)) { + int64_t n = ray_len(x); + if (n == 0) return ray_vec_new(RAY_BOOL, 0); + ray_t* out = ray_list_new(n); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + ray_t** e = (ray_t**)ray_data(x); + for (int64_t i = 0; i < n; i++) { + ray_t* r = ray_not_fn(e[i]); + if (!r || RAY_IS_ERR(r)) { ray_release(out); return r ? r : ray_error("oom", NULL); } + out = ray_list_append(out, r); + ray_release(r); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + } + return ray_list_collapse_bool(out); + } return make_bool(is_truthy(x) ? 0 : 1); } diff --git a/src/ops/colbind.c b/src/ops/colbind.c new file mode 100644 index 000000000..2aeeaf5ee --- /dev/null +++ b/src/ops/colbind.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "ops/colbind.h" +#include "table/table.h" +#include +#include + +static _Atomic int64_t g_bind_fail_at; /* test hook: fail the nth allocation */ +void ray_graph_bind_test_fail_alloc(int64_t nth) { atomic_store(&g_bind_fail_at, nth); } +static bool bind_alloc_fails(void) { + int64_t v = atomic_load(&g_bind_fail_at); + while (v > 0) + if (atomic_compare_exchange_weak(&g_bind_fail_at, &v, v - 1)) return v == 1; + return false; +} + +typedef struct { ray_t* tbl; int64_t sym; ray_col_src_t src; } colbind_ent_t; + +typedef struct ray_col_binds_s { + colbind_ent_t** e; /* one allocation per entry: stable addresses */ + uint32_t n, cap; +} ray_col_binds_t; + +ray_col_src_t* ray_graph_bind_col(ray_graph_t* g, ray_t* tbl, int64_t sym, ray_t** err) { + *err = NULL; + if (!g || !tbl) return NULL; + ray_col_binds_t* b = g->binds; + /* A hit must still describe the column the table holds now: a table + * released and reallocated at the same address (a temporary sub-table) + * or a column replaced in place must not return the old binding. */ + ray_t* cur = NULL; + bool cur_set = false; + for (uint32_t i = 0; b && i < b->n; i++) { + if (b->e[i]->tbl != tbl || b->e[i]->sym != sym) continue; + if (!cur_set) { + cur = ray_table_slot(tbl, sym); /* no decode */ + cur_set = true; + } + if (b->e[i]->src.obj == cur) return &b->e[i]->src; + } + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, sym, &m)) return NULL; /* absent */ + if (bind_alloc_fails()) { *err = ray_error("oom", "column bind"); return NULL; } + if (!b) { + b = ray_calloc_raw(sizeof *b); + if (!b) { *err = ray_error("oom", "column bind"); return NULL; } + g->binds = b; + } + if (b->n == b->cap) { + uint32_t nc = b->cap ? b->cap * 2 : 8; + colbind_ent_t** ne = ray_realloc_raw(b->e, nc * sizeof *ne); + if (!ne) { *err = ray_error("oom", "column bind"); return NULL; } + b->e = ne; b->cap = nc; + } + colbind_ent_t* x = ray_calloc_raw(sizeof *x); + if (!x) { *err = ray_error("oom", "column bind"); return NULL; } + ray_t* e = ray_table_col_src(tbl, sym, &x->src); /* no decode */ + if (e || !x->src.obj) { ray_free_raw(x); *err = e; return NULL; } + x->tbl = tbl; x->sym = sym; + b->e[b->n++] = x; + return &x->src; +} + +bool ray_col_bind_declines(ray_t* tbl, int64_t sym) { + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, sym, &m)) return false; + if (m.type == RAY_MAPCOMMON) return true; + if (m.enc) return (m.enc->attrs & RAY_ATTR_SLICE) != 0; + return RAY_IS_PARTED(m.type) && (m.attrs & RAY_ATTR_SLICE) != 0; +} + +void ray_graph_binds_free(ray_graph_t* g) { + ray_col_binds_t* b = g ? g->binds : NULL; + if (!b) return; + for (uint32_t i = 0; i < b->n; i++) { ray_col_src_release(&b->e[i]->src); ray_free_raw(b->e[i]); } + ray_free_raw(b->e); + ray_free_raw(b); + g->binds = NULL; +} + +static _Atomic uint64_t g_unbound; +uint64_t ray_graph_binds_dropped(void) { return atomic_load(&g_unbound); } + +void ray_graph_unbind_table(ray_graph_t* g, ray_t* tbl) { + ray_col_binds_t* b = g ? g->binds : NULL; + if (!b || !tbl) return; + uint32_t w = 0; + for (uint32_t i = 0; i < b->n; i++) { + if (b->e[i]->tbl == tbl) { + ray_col_src_release(&b->e[i]->src); + ray_free_raw(b->e[i]); + atomic_fetch_add(&g_unbound, 1); + } else { + b->e[w++] = b->e[i]; + } + } + b->n = w; +} + +uint32_t ray_graph_binds_count(const ray_graph_t* g) { + return (g && g->binds) ? g->binds->n : 0; +} diff --git a/src/ops/colbind.h b/src/ops/colbind.h new file mode 100644 index 000000000..a2c740a69 --- /dev/null +++ b/src/ops/colbind.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_COLBIND_H +#define RAY_COLBIND_H + +#include "ops/ops.h" +#include "store/colrange.h" + +/* Bind column `sym` of `tbl` for this execution (deduplicated per table + * and name; no decode). A cached entry is returned only while it is still + * the column object the table holds, so a table released and reallocated at + * the same address, or a column replaced in place, never hits a stale entry. + * The entries of a temporary table (a sub-table, a compacted copy) are + * dropped with ray_graph_unbind_table before it is released. NULL with *err NULL when absent; NULL with an + * owned *err on failure (OOM). Binds are made on the thread executing the + * graph, before any pool dispatch that reads them; the returned source is + * borrowed from the graph and valid until ray_graph_free. `tbl` must + * outlive the graph: the dedup key is its raw pointer. */ +ray_col_src_t* ray_graph_bind_col(ray_graph_t* g, ray_t* tbl, int64_t sym, ray_t** err); +void ray_graph_binds_free(ray_graph_t* g); +/* Release and remove every entry keyed by `tbl`; borrowed sources of that + * table must no longer be in use. */ +void ray_graph_unbind_table(ray_graph_t* g, ray_t* tbl); +uint32_t ray_graph_binds_count(const ray_graph_t* g); /* tests */ +uint64_t ray_graph_binds_dropped(void); /* tests: entries removed by unbind, process-wide */ +void ray_graph_bind_test_fail_alloc(int64_t nth); /* tests: fail the nth bind (0 = off) */ + +/* True when the column is present but its shape is not a bindable source + * (a partition key column, a slice of a parted or encoded column): a + * compile site declines these as a shape, the way it declined them before + * the bind stage existed, instead of treating the bind's error as a failure. */ +bool ray_col_bind_declines(ray_t* tbl, int64_t sym); + +#endif /* RAY_COLBIND_H */ diff --git a/src/ops/colgather.c b/src/ops/colgather.c new file mode 100644 index 000000000..3069e9744 --- /dev/null +++ b/src/ops/colgather.c @@ -0,0 +1,724 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "ops/colgather.h" +#include "ops/internal.h" /* parted_sym_width */ +#include "ops/rowsel.h" +#include "core/pool.h" /* the parallel selection gather */ +#include "table/domain.h" /* ray_sym_domain_retain */ +#include "table/sym.h" +#include "vec/str.h" +#include "vec/vec.h" /* ray_str_pool_reserve, ray_raw_is_null */ +#include +#include +#include + +static _Atomic(uint64_t) g_par_gathers; /* test hook: parallel selection gathers */ +uint64_t ray_col_test_gather_par(void) { return atomic_load_explicit(&g_par_gathers, memory_order_relaxed); } + +/* The result under construction: the output vector (len set, cells filled + * by position) and, for STR, the pool built for it (a RAY_U8 block grown + * as ray_str_vec_append grows one, attached at the finish). A parallel + * gather gives each task its own accumulator over the one shared output: + * the task writes only its own output positions and its own pool, and + * notes a null in `nulls` instead of the output's attrs, which only the + * finish sets (after the join). */ +typedef struct { + ray_t* out; + ray_t* pool; + uint8_t ow; /* SYM: the output's width class */ + bool nulls; /* a null was written: HAS_NULLS at the finish */ +} gather_acc_t; + +static ray_t* acc_open(gather_acc_t* a, const ray_col_src_t* src, int64_t n) { + memset(a, 0, sizeof *a); + if (src->type == RAY_LIST) return ray_error("nyi", "gather: LIST source"); + if (src->type == RAY_SYM) + /* a parted source's own width is not authoritative (segments may + * differ): the widest segment's, as agg_src_standin sizes it */ + a->ow = src->parted ? parted_sym_width(src->obj) : (uint8_t)(src->attrs & RAY_SYM_W_MASK); + ray_t* v = src->type == RAY_SYM ? ray_sym_vec_new(a->ow, n > 0 ? n : 1) : ray_vec_new(src->type, n > 0 ? n : 1); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + v->len = n; + a->out = v; + return NULL; +} + +/* The partial result, its pool and nothing else: the domain is retained + * only at the finish. */ +static void acc_abort(gather_acc_t* a) { + if (a->out) ray_release(a->out); + if (a->pool) ray_release(a->pool); + a->out = a->pool = NULL; +} + +/* Copy len bytes into the result's pool: their offset in *off. The pool + * is created and grown as ray_str_vec_append's (ray_str_pool_reserve); + * `range` when it would cross UINT32_MAX, as for any STR pool. */ +static ray_t* acc_pool_put(gather_acc_t* a, const char* p, uint32_t len, uint32_t* off) { + int64_t at; + ray_err_t pe = ray_str_pool_reserve(&a->pool, len, &at); + if (pe == RAY_ERR_RANGE) + return ray_error("range", "gather: STR pool exceeds %lld bytes", (long long)UINT32_MAX); + if (pe != RAY_OK) return ray_error("oom", NULL); + memcpy((char*)ray_data(a->pool) + at, p, len); + a->pool->len = at + (int64_t)len; + *off = (uint32_t)at; + return NULL; +} + +/* The type's null sentinel at output position pos, as ray_vec_set_null + * writes it for the fixed-width types a view can carry nulls in; the + * HAS_NULLS bit waits for the finish (a.nulls). */ +static void acc_null(gather_acc_t* a, int64_t pos) { + void* p = ray_data(a->out); + switch (a->out->type) { + case RAY_F64: ((double*)p)[pos] = NULL_F64; break; + case RAY_F32: ((float*)p)[pos] = NULL_F32; break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)p)[pos] = NULL_I64; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)p)[pos] = NULL_I32; break; + case RAY_I16: ((int16_t*)p)[pos] = NULL_I16; break; + case RAY_GUID: memset((uint8_t*)p + pos * 16, 0, 16); break; + default: return; /* not nullable (BOOL, U8): as ray_vec_set_null */ + } + a->nulls = true; +} + +/* Elements [i, i + cnt) of view `v` to output positions [pos, pos + cnt), + * as generation 0's gather leaves them: STR descriptors rebuilt over the + * result's pool (as ray_str_vec_append builds them), SYM ids written as + * logical values at the output width, nulls under the view's may_null as + * ray_vec_set_null writes them (SYM and STR nulls are in-band and always + * tested, as ray_vec_may_have_nulls has it). */ +static ray_t* acc_put(gather_acc_t* a, const ray_col_range_t* v, int64_t i, int64_t pos, int64_t cnt) { + ray_t* o = a->out; + if (v->type == RAY_STR) { + const ray_str_t* sv = (const ray_str_t*)v->data; + ray_str_t* d = (ray_str_t*)ray_data(o); + for (int64_t k = 0; k < cnt; k++) { + const ray_str_t* s = &sv[i + k]; + ray_str_t e; + memset(&e, 0, sizeof e); + e.len = s->len; + if (s->len == 0) { + a->nulls = true; + } else if (ray_str_is_inline(s)) { + memcpy(e.data, s->data, s->len); + } else { + /* the view's pool lives until the next read: copy now */ + const char* p = v->str_pool + s->pool_off; + uint32_t off; + ray_t* err = acc_pool_put(a, p, s->len, &off); + if (err) return err; + memcpy(e.prefix, p, 4); + e.pool_off = off; + /* a nonzero cached hash is the content hash (every builder + * and loader keeps it so, col.c / enccol.c): reused, else + * computed as ray_str_vec_append computes it */ + e.hash32 = s->hash32; + e.hash32 = ray_str_t_hash32(&e, (const char*)ray_data(a->pool)); + } + d[pos + k] = e; + } + return NULL; + } + if (v->type == RAY_SYM) { + uint8_t vw = v->attrs & RAY_SYM_W_MASK; + void* d = ray_data(o); + if (vw == a->ow) { + uint8_t esz = ray_sym_elem_size(RAY_SYM, v->attrs); + memcpy((char*)d + (size_t)pos * esz, (const char*)v->data + (size_t)i * esz, (size_t)cnt * esz); + } + uint64_t lim = a->ow == RAY_SYM_W8 ? UINT8_MAX : a->ow == RAY_SYM_W16 ? UINT16_MAX + : a->ow == RAY_SYM_W32 ? UINT32_MAX : UINT64_MAX; + for (int64_t k = 0; k < cnt; k++) { + uint64_t id = (uint64_t)ray_read_sym(v->data, i + k, RAY_SYM, v->attrs); + if (id == 0) a->nulls = true; + if (vw == a->ow) continue; + if (id > lim) /* the width scan said every segment fits */ + return ray_error("corrupt", "gather: symbol id %llu above its width class", (unsigned long long)id); + ray_write_sym(d, pos + k, id, RAY_SYM, o->attrs); + } + return NULL; + } + uint8_t esz = ray_sym_elem_size(v->type, v->attrs); + memcpy((char*)ray_data(o) + (size_t)pos * esz, (const char*)v->data + (size_t)i * esz, (size_t)cnt * esz); + if (v->may_null) + for (int64_t k = 0; k < cnt; k++) + if (ray_raw_is_null(v->type, v->attrs, v->data, i + k)) acc_null(a, pos + k); + return NULL; +} + +/* A partial vector: view elements base + li[q] (li16 or li64, whichever is + * not NULL), q in [0, cnt), to output positions [pos, pos + cnt). A + * fixed-width view (SYM at the output's width included) is copied by one + * width-specialised loop, then its nulls are rewritten as acc_put rewrites + * them; STR and widened SYM go element by element through acc_put. */ +#define ACC_LIST_COPY(IX) do { \ + switch (esz) { \ + case 1: for (int64_t q = 0; q < cnt; q++) d[q] = sd[(IX)]; break; \ + case 2: for (int64_t q = 0; q < cnt; q++) memcpy(d + q * 2, sd + (IX) * 2, 2); break; \ + case 4: for (int64_t q = 0; q < cnt; q++) memcpy(d + q * 4, sd + (IX) * 4, 4); break; \ + case 8: for (int64_t q = 0; q < cnt; q++) memcpy(d + q * 8, sd + (IX) * 8, 8); break; \ + default: for (int64_t q = 0; q < cnt; q++) memcpy(d + q * esz, sd + (IX) * esz, esz); break; \ + } \ + } while (0) +static ray_t* acc_put_list(gather_acc_t* a, const ray_col_range_t* v, int64_t base, const uint16_t* li16, + const int64_t* li64, int64_t cnt, int64_t pos) { + if (v->type == RAY_STR || (v->type == RAY_SYM && (v->attrs & RAY_SYM_W_MASK) != a->ow)) { + for (int64_t q = 0; q < cnt; q++) { + ray_t* err = acc_put(a, v, base + (li16 ? (int64_t)li16[q] : li64[q]), pos + q, 1); + if (err) return err; + } + return NULL; + } + uint8_t esz = ray_sym_elem_size(v->type, v->attrs); + const char* sd = (const char*)v->data; + char* d = (char*)ray_data(a->out) + (size_t)pos * esz; + if (li16) ACC_LIST_COPY(base + (int64_t)li16[q]); + else ACC_LIST_COPY(base + li64[q]); + if (v->type == RAY_SYM) { + for (int64_t q = 0; q < cnt && !a->nulls; q++) + if (ray_read_sym(ray_data(a->out), pos + q, RAY_SYM, a->out->attrs) == 0) a->nulls = true; + } else if (v->may_null) { + for (int64_t q = 0; q < cnt; q++) { + int64_t r = base + (li16 ? (int64_t)li16[q] : li64[q]); + if (ray_raw_is_null(v->type, v->attrs, v->data, r)) acc_null(a, pos + q); + } + } + return NULL; +} +#undef ACC_LIST_COPY + +/* Point reads (open decision D2, per codec in Task 10b): a vector holding + * few enough of the requested rows for its codec (the measured crossovers + * at enccol.c's batched point reads: RAY_ENC_VEC / 32 FOR_BP, / 16 RLE, + * CONST, DICT and any vector with a null bitmap, / 128 a RAW vector whose + * chunk is not yet validated) serves them through + * ray_col_src_gather_points (the body read once, then one lane unpacked, + * one code looked up or one run found per row) instead of being decoded + * whole; callers hand it at most RAY_COL_POINT_ROWS rows and it declines + * past the codec's limit. SYM ids come back as ids, bitmap nulls as + * flags. A declined read (DELTA_BP, a viewed RAW vector, a plain or + * materialized source) leaves the vector to the cursor, which decodes it. */ +#define GATHER_POINT_ROWS RAY_COL_POINT_ROWS + +/* The source's values can be point-read: an encoded integer, temporal or + * SYM column. */ +static bool gather_point_src(const ray_col_src_t* src) { + if (!ray_col_src_encoded(src)) return false; + switch (src->type) { + case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: return true; + default: return false; + } +} + +/* A point-served value at output position pos: a bitmap null as acc_null + * writes it; a SYM id written at the output width (checked against it, as + * acc_put checks a widened id), id 0 noted as the null it is. */ +static inline ray_t* acc_point(gather_acc_t* a, int64_t pos, int64_t x, bool null) { + if (null) { acc_null(a, pos); return NULL; } + void* d = ray_data(a->out); + if (a->out->type == RAY_SYM) { + uint64_t lim = a->ow == RAY_SYM_W8 ? UINT8_MAX : a->ow == RAY_SYM_W16 ? UINT16_MAX + : a->ow == RAY_SYM_W32 ? UINT32_MAX : UINT64_MAX; + if ((uint64_t)x > lim) + return ray_error("corrupt", "gather: symbol id %llu above its width class", (unsigned long long)x); + if (x == 0) a->nulls = true; + } + switch (ray_sym_elem_size(a->out->type, a->out->attrs)) { + case 1: ((uint8_t*)d)[pos] = (uint8_t)x; break; + case 2: ((int16_t*)d)[pos] = (int16_t)x; break; + case 4: ((int32_t*)d)[pos] = (int32_t)x; break; + default: ((int64_t*)d)[pos] = x; break; + } + return NULL; +} + +static ray_t* acc_finish(gather_acc_t* a, const ray_col_src_t* src, ray_t** out) { + ray_t* o = a->out; + if (a->pool) { o->str_pool = a->pool; a->pool = NULL; } /* the result's own pool */ + if (a->nulls) o->attrs |= RAY_ATTR_HAS_NULLS; + if (src->type == RAY_SYM && src->dom && src->dom != ray_sym_runtime_domain()) { + ray_sym_domain_retain(src->dom); /* the agg_src_standin pattern */ + o->sym_domain = src->dom; + } + a->out = NULL; + *out = o; + return NULL; +} + +/* Positions 0..n) ordered by ids[pos], stable (repeated ids keep their + * input order): an LSD radix sort, 11-bit digits over the bits of + * max_id. Ids are checked to lie in [0, max_id] by the caller. */ +#define GATHER_RADIX_BITS 11 +static ray_t* gather_order(const int64_t* ids, int64_t n, int64_t max_id, int64_t** out) { + int64_t* ord = (int64_t*)ray_alloc_raw((size_t)n * sizeof(int64_t)); + int64_t* tmp = (int64_t*)ray_alloc_raw((size_t)n * sizeof(int64_t)); + if (!ord || !tmp) { ray_free_raw(ord); ray_free_raw(tmp); return ray_error("oom", "gather order"); } + for (int64_t k = 0; k < n; k++) ord[k] = k; + int bits = 0; + while (bits < 63 && ((uint64_t)max_id >> bits) != 0) bits++; + int64_t cnt[1 << GATHER_RADIX_BITS]; + for (int sh = 0; sh < bits; sh += GATHER_RADIX_BITS) { + memset(cnt, 0, sizeof cnt); + for (int64_t k = 0; k < n; k++) cnt[((uint64_t)ids[k] >> sh) & ((1u << GATHER_RADIX_BITS) - 1)]++; + int64_t sum = 0; + for (int d = 0; d < (1 << GATHER_RADIX_BITS); d++) { int64_t c = cnt[d]; cnt[d] = sum; sum += c; } + for (int64_t k = 0; k < n; k++) { + int64_t p = ord[k]; + tmp[cnt[((uint64_t)ids[p] >> sh) & ((1u << GATHER_RADIX_BITS) - 1)]++] = p; + } + int64_t* sw = ord; ord = tmp; tmp = sw; + } + ray_free_raw(tmp); + *out = ord; + return NULL; +} + +/* ray_col_gather_rows' work: decode-order positions [k0, k1) (ord NULL: + * the ids in order, positions themselves) through one cursor. */ +static ray_t* grows_range(ray_col_src_t* src, const int64_t* ids, const int64_t* ord, int64_t k0, int64_t k1, + gather_acc_t* a, ray_col_cursor_t* cur, bool point) { + ray_t* err = NULL; + const int64_t n = k1; + for (int64_t k = k0; k < n && !err; ) { + int64_t pos = ord ? ord[k] : k, r = ids[pos]; + int64_t vlo, vhi; + if (point && ray_col_src_vec_span(src, r, &vlo, &vhi)) { + /* the ids inside r's vector, in decode order: few are point-read */ + int64_t j = k + 1; + while (j < n && j - k <= GATHER_POINT_ROWS && ids[ord ? ord[j] : j] < vhi) j++; + if (j - k <= GATHER_POINT_ROWS) { + int64_t rows[GATHER_POINT_ROWS], x[GATHER_POINT_ROWS]; + uint8_t nul[GATHER_POINT_ROWS]; + const int64_t* rp = ids + k; /* in order: the ids themselves */ + if (ord) { for (int64_t q = k; q < j; q++) rows[q - k] = ids[ord[q]]; rp = rows; } + int pr = ray_col_src_gather_points(src, rp, j - k, x, nul, &err); + if (pr < 0) break; + if (pr > 0) { /* every row of the vector served */ + for (int64_t q = k; q < j && !err; q++) err = acc_point(a, ord ? ord[q] : q, x[q - k], nul[q - k]); + k = j; + continue; + } /* declined: the cursor reads the vector */ + } + } + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(cur, r, &v)) != NULL) break; + int64_t end = v->start + v->n; + if (!ord) { /* in order: the view's ids are one copy */ + int64_t j = k + 1; + bool run = true; /* every step +1: one run, no repeats */ + for (; j < n && ids[j] < end; j++) run = run && ids[j] == ids[j - 1] + 1; + err = run ? acc_put(a, v, ids[k] - v->start, k, j - k) + : acc_put_list(a, v, -v->start, NULL, ids + k, j - k, k); + k = j; + continue; + } + for (; k < n && !err; k++) { + pos = ord[k]; + r = ids[pos]; + if (r >= end) break; + err = acc_put(a, v, r - v->start, pos, 1); + } + } + return err; +} + +static ray_t* grows_par(ray_col_src_t* src, const int64_t* ids, int64_t n, ray_pool_t* pool, gather_acc_t* a, bool point); + +ray_t* ray_col_gather_rows(ray_col_src_t* src, const int64_t* ids, int64_t n, ray_t** out) { + *out = NULL; + if (n < 0) return ray_error("range", "gather: %lld rows", (long long)n); + bool sorted = true; + for (int64_t k = 0; k < n; k++) { + if (ids[k] < 0 || ids[k] >= src->len) + return ray_error("range", "gather: row %lld of %lld", (long long)ids[k], (long long)src->len); + if (k && ids[k] < ids[k - 1]) sorted = false; + } + gather_acc_t a; + ray_t* err = acc_open(&a, src, n); + if (err) return err; + const bool point = gather_point_src(src); + /* ascending ids, many of them: pool tasks over position ranges, each + * with its own cursor, writing its own output positions */ + ray_pool_t* pool = ray_pool_get(); + if (sorted && ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) { + err = grows_par(src, ids, n, pool, &a, point); + if (err) { acc_abort(&a); return err; } + return acc_finish(&a, src, out); + } + /* the decode schedule: positions in id order, so the cursor keeps its + * view while the ids stay inside it and each touched vector (segment + * local for a parted source) is range-read once; each value still goes + * to its own output position */ + int64_t* ord = NULL; + if (!sorted && (err = gather_order(ids, n, src->len - 1, &ord)) != NULL) { acc_abort(&a); return err; } + ray_col_fixed_t fixed; /* the decode vector on the stack (P2 17i) */ + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, src, &fixed); + err = grows_range(src, ids, ord, 0, n, &a, &cur, point); + ray_col_cursor_free(&cur); + ray_free_raw(ord); + if (err) { acc_abort(&a); return err; } + return acc_finish(&a, src, out); +} + +/* ray_col_gather_sel's work: segments [s0, s1) of the selection, the + * first written at output position pos, through one task's cursor. */ +typedef struct { + ray_col_src_t* src; + const uint8_t* flags; /* NULL: every segment ALL */ + const uint32_t* offs; + const uint16_t* idx; + bool point; /* gather_point_src: few-row segments are point-read */ + int64_t end; /* the last segment ends here: the source end, or a span's */ +} gsel_in_t; + +/* The first segment in [s, s1) whose flag is not RAY_SEL_NONE (0), else + * s1: eight flags per load, so a sparse selection's long runs of empty + * segments cost a load per eight (every column's gather walks them). */ +_Static_assert(RAY_SEL_NONE == 0, "gsel_next skips empty segments as zero bytes"); +static inline int64_t gsel_next(const uint8_t* flags, int64_t s, int64_t s1) { +#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + for (; s + 8 <= s1; s += 8) { + uint64_t w; + memcpy(&w, flags + s, 8); + if (w) return s + (__builtin_ctzll(w) >> 3); /* little-endian: the lowest set byte */ + } +#endif + while (s < s1 && flags[s] == RAY_SEL_NONE) s++; + return s; +} + +static ray_t* gsel_range(const gsel_in_t* in, gather_acc_t* a, ray_col_cursor_t* cur, + int64_t s0, int64_t s1, int64_t pos) { + ray_col_src_t* src = in->src; + ray_t* err = NULL; + for (int64_t s = s0; s < s1 && !err; s++) { + if (in->flags && (s = gsel_next(in->flags, s, s1)) >= s1) break; /* the vectors are never read */ + uint8_t f = in->flags ? in->flags[s] : RAY_SEL_ALL; + int64_t lo = s * RAY_MORSEL_ELEMS; + int64_t hi = lo + RAY_MORSEL_ELEMS < in->end ? lo + RAY_MORSEL_ELEMS : in->end; + if (f == RAY_SEL_ALL) { + /* a segment may span two views (a parted segment boundary) */ + for (int64_t r = lo; r < hi && !err; ) { + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(cur, r, &v)) != NULL) break; + int64_t end = v->start + v->n < hi ? v->start + v->n : hi; + err = acc_put(a, v, r - v->start, pos, end - r); + pos += end - r; + r = end; + } + continue; + } + uint32_t k0 = in->offs[s], k1 = in->offs[s + 1]; + for (uint32_t k = k0; k < k1; k++) + if (in->idx[k] >= hi - lo) + return ray_error("corrupt", "gather: selection row %lld past its segment", (long long)(lo + in->idx[k])); + uint32_t k = k0; + if (in->point && k1 - k0 <= GATHER_POINT_ROWS) { + /* few rows: point reads of each vector they fall in (a parted + * segment boundary may split them; the segment's rows bound + * each vector's share), a declined vector left to the cursor */ + int64_t rows[GATHER_POINT_ROWS], x[GATHER_POINT_ROWS]; + uint8_t nul[GATHER_POINT_ROWS]; + while (k < k1 && !err) { + int64_t vlo, vhi; + if (!ray_col_src_vec_span(src, lo + in->idx[k], &vlo, &vhi)) break; + uint32_t j = k; + for (; j < k1 && lo + in->idx[j] < vhi; j++) rows[j - k] = lo + in->idx[j]; + int pr = ray_col_src_gather_points(src, rows, j - k, x, nul, &err); + if (pr <= 0) break; + for (uint32_t q = k; q < j && !err; q++) err = acc_point(a, pos++, x[q - k], nul[q - k]); + k = j; + } + if (err) break; + } + while (k < k1 && !err) { + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(cur, lo + in->idx[k], &v)) != NULL) break; + int64_t end = v->start + v->n; + uint32_t j = k + 1; + /* a rowsel's indices ascend inside a segment (engine-built), + * so a view's run never starts before the view */ + while (j < k1 && lo + in->idx[j] < end) { assert(in->idx[j] > in->idx[j - 1]); j++; } + err = acc_put_list(a, v, lo - v->start, in->idx + k, NULL, j - k, pos); + pos += j - k; + k = j; + } + } + return err; +} + +/* The parallel form: task t gathers segments [t * spt, (t + 1) * spt) at + * output position pos0[t] (the selection's own counts, summed before the + * dispatch) into its own accumulator over the shared output; failures go + * to the envelope keyed by the task's first row. */ +typedef struct { + gsel_in_t in; + int64_t s_base; /* task t starts at segment s_base + t * spt */ + int64_t nseg, spt; + const int64_t* pos0; + gather_acc_t* acc; + ray_scan_fail_t fail; +} gsel_par_t; + +static void gsel_task(void* ctxp, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + gsel_par_t* c = (gsel_par_t*)ctxp; + for (int64_t t = start; t < end; t++) { + int64_t s0 = c->s_base + t * c->spt, s1 = s0 + c->spt < c->nseg ? s0 + c->spt : c->nseg; + int64_t key = s0 * RAY_MORSEL_ELEMS; + if (ray_scan_fail_skip(&c->fail, key)) continue; + ray_col_fixed_t fixed; /* the task's decode vector on its stack */ + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, c->in.src, &fixed); + ray_t* err = gsel_range(&c->in, &c->acc[t], &cur, s0, s1, c->pos0[t]); + ray_col_cursor_free(&cur); + if (err) ray_scan_fail_note(&c->fail, key, err); + } +} + +/* Task pools appended in task order (row order) into one pool: each task's + * pooled descriptors (output positions [pos0[t], pos0[t + 1])) move by the + * bytes before them. `range` when the whole would pass UINT32_MAX. */ +static ray_t* gsel_merge_pools(gather_acc_t* acc, int64_t ntask, const int64_t* pos0, gather_acc_t* a) { + int64_t total = 0, first = -1, users = 0; + for (int64_t t = 0; t < ntask; t++) + if (acc[t].pool) { total += acc[t].pool->len; users++; if (first < 0) first = t; } + if (!users) return NULL; + /* one pool: adopted as is (nothing before it, nothing to move) */ + if (users == 1) { a->pool = acc[first].pool; acc[first].pool = NULL; return NULL; } + int64_t at; + ray_err_t pe = ray_str_pool_reserve(&a->pool, (size_t)total, &at); + if (pe == RAY_ERR_RANGE) + return ray_error("range", "gather: STR pool exceeds %lld bytes", (long long)UINT32_MAX); + if (pe != RAY_OK) return ray_error("oom", NULL); + ray_str_t* d = (ray_str_t*)ray_data(a->out); + int64_t b = at; + for (int64_t t = 0; t < ntask; t++) { + if (!acc[t].pool) continue; + memcpy((char*)ray_data(a->pool) + b, ray_data(acc[t].pool), (size_t)acc[t].pool->len); + if (b) + for (int64_t p = pos0[t]; p < pos0[t + 1]; p++) + if (d[p].len && !ray_str_is_inline(&d[p])) d[p].pool_off += (uint32_t)b; + b += acc[t].pool->len; + ray_release(acc[t].pool); + acc[t].pool = NULL; + } + a->pool->len = b; + return NULL; +} + +/* The parallel row-list gather (ascending ids): task t gathers positions + * [n t / T, n (t + 1) / T) into its own accumulator over the shared + * output, failures noted keyed by the task's first id, STR pools merged in + * position order as the selection gather merges them. */ +typedef struct { + ray_col_src_t* src; + const int64_t* ids; + const int64_t* pos0; /* [tasks + 1] */ + gather_acc_t* acc; + bool point; + ray_scan_fail_t fail; +} grows_par_t; + +static void grows_task(void* ctxp, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + grows_par_t* c = (grows_par_t*)ctxp; + for (int64_t t = start; t < end; t++) { + int64_t k0 = c->pos0[t], k1 = c->pos0[t + 1]; + if (k0 >= k1) continue; + int64_t key = c->ids[k0]; + if (ray_scan_fail_skip(&c->fail, key)) continue; + ray_col_fixed_t fixed; /* the task's decode vector on its stack */ + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, c->src, &fixed); + ray_t* err = grows_range(c->src, c->ids, NULL, k0, k1, &c->acc[t], &cur, c->point); + ray_col_cursor_free(&cur); + if (err) ray_scan_fail_note(&c->fail, key, err); + } +} + +static ray_t* grows_par(ray_col_src_t* src, const int64_t* ids, int64_t n, ray_pool_t* pool, gather_acc_t* a, bool point) { + int64_t ntask = (int64_t)ray_pool_total_workers(pool) * 4; + if (ntask > (int64_t)RAY_POOL_INIT_TASKS) ntask = RAY_POOL_INIT_TASKS; + int64_t* pos0 = (int64_t*)ray_alloc_raw((size_t)(ntask + 1) * sizeof(int64_t)); + gather_acc_t* acc = (gather_acc_t*)ray_calloc_raw((size_t)ntask * sizeof(gather_acc_t)); + if (!pos0 || !acc) { ray_free_raw(pos0); ray_free_raw(acc); return ray_error("oom", "gather tasks"); } + for (int64_t t = 0; t <= ntask; t++) pos0[t] = n * t / ntask; + grows_par_t c = { .src = src, .ids = ids, .pos0 = pos0, .acc = acc, .point = point }; + for (int64_t t = 0; t < ntask; t++) { acc[t].out = a->out; acc[t].ow = a->ow; } + ray_scan_fail_init(&c.fail); + ray_pool_dispatch_n(pool, grows_task, &c, (uint32_t)ntask); + ray_t* err = ray_scan_fail_finish(&c.fail, pool); + for (int64_t t = 0; t < ntask; t++) a->nulls |= acc[t].nulls; + if (!err) err = gsel_merge_pools(acc, ntask, pos0, a); + for (int64_t t = 0; t < ntask; t++) if (acc[t].pool) ray_release(acc[t].pool); + ray_free_raw(pos0); + ray_free_raw(acc); + return err; +} + +ray_t* ray_col_gather_sel(ray_col_src_t* src, ray_t* sel, ray_t** out) { + *out = NULL; + ray_rowsel_t* m = sel ? ray_rowsel_meta(sel) : NULL; + if (m && m->nrows != src->len) + return ray_error("length", "gather: selection of %lld rows over %lld", (long long)m->nrows, (long long)src->len); + int64_t n = m ? m->total_pass : src->len; + gather_acc_t a; + ray_t* err = acc_open(&a, src, n); + if (err) return err; + int64_t nseg = m ? (int64_t)m->n_segs : (src->len + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS; + gsel_in_t in = { .src = src, .flags = sel ? ray_rowsel_flags(sel) : NULL, + .offs = sel ? ray_rowsel_offsets(sel) : NULL, .idx = sel ? ray_rowsel_idx(sel) : NULL, + .point = gather_point_src(src), .end = src->len }; + /* the tasks: the pool's grain of segments each, at most the ring's + * initial capacity of them; one runs here when the pool cannot help */ + ray_pool_t* pool = ray_pool_get(); + int64_t spt = RAY_DISPATCH_MORSELS; + while ((nseg + spt - 1) / spt > (int64_t)RAY_POOL_INIT_TASKS) spt *= 2; + int64_t ntask = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD) ? (nseg + spt - 1) / spt : 1; + if (ntask <= 1) { ntask = 1; spt = nseg; } + /* each task's first output position, from the selection's counts: + * checked against total_pass before anything is written */ + int64_t pos0_one[2]; + int64_t* pos0 = ntask > 1 ? (int64_t*)ray_alloc_raw((size_t)(ntask + 1) * sizeof(int64_t)) : pos0_one; + gather_acc_t* acc = ntask > 1 ? (gather_acc_t*)ray_calloc_raw((size_t)ntask * sizeof(gather_acc_t)) : NULL; + if (!pos0 || (ntask > 1 && !acc)) { + if (pos0 != pos0_one) ray_free_raw(pos0); + ray_free_raw(acc); + acc_abort(&a); + return ray_error("oom", "gather tasks"); + } + int64_t cum = 0; + /* task by task, the empty segments skipped eight at a time (a + * division or a test per segment cost more than a sparse gather: + * every column's gather walks every segment) */ + for (int64_t t = 0; t < ntask && !err; t++) { + pos0[t] = cum; + const int64_t s1 = (t + 1) * spt < nseg ? (t + 1) * spt : nseg; + for (int64_t s = t * spt; s < s1 && !err; s++) { + if (in.flags && (s = gsel_next(in.flags, s, s1)) >= s1) break; + uint8_t f = in.flags ? in.flags[s] : RAY_SEL_ALL; + int64_t lo = s * RAY_MORSEL_ELEMS; + int64_t hi = lo + RAY_MORSEL_ELEMS < src->len ? lo + RAY_MORSEL_ELEMS : src->len; + /* the rows this segment adds, checked before any is written */ + int64_t add = f == RAY_SEL_ALL ? hi - lo : (int64_t)in.offs[s + 1] - (int64_t)in.offs[s]; + if (add < 0 || add > n - cum) + err = ray_error("corrupt", "gather: selection holds more rows than its %lld", (long long)n); + else + cum += add; + } + } + pos0[ntask] = cum; + if (!err && cum != n) + err = ray_error("corrupt", "gather: selection holds %lld rows, says %lld", (long long)cum, (long long)n); + if (!err && ntask == 1) { + ray_col_fixed_t fixed; /* the decode vector on the stack (P2 17i) */ + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, src, &fixed); + err = gsel_range(&in, &a, &cur, 0, nseg, 0); + ray_col_cursor_free(&cur); + } else if (!err) { + gsel_par_t c = { .in = in, .nseg = nseg, .spt = spt, .pos0 = pos0, .acc = acc }; + for (int64_t t = 0; t < ntask; t++) { acc[t].out = a.out; acc[t].ow = a.ow; } + ray_scan_fail_init(&c.fail); + atomic_fetch_add_explicit(&g_par_gathers, 1, memory_order_relaxed); + ray_pool_dispatch_n(pool, gsel_task, &c, (uint32_t)ntask); + err = ray_scan_fail_finish(&c.fail, pool); + for (int64_t t = 0; t < ntask; t++) a.nulls |= acc[t].nulls; + if (!err) err = gsel_merge_pools(acc, ntask, pos0, &a); + for (int64_t t = 0; t < ntask; t++) if (acc[t].pool) ray_release(acc[t].pool); + } + if (pos0 != pos0_one) ray_free_raw(pos0); + ray_free_raw(acc); + if (err) { acc_abort(&a); return err; } + return acc_finish(&a, src, out); +} + +ray_t* ray_col_gather_span(ray_col_src_t* src, int64_t lo, int64_t hi, ray_t** out) { + *out = NULL; + if (lo < 0 || hi < lo || hi > src->len || lo % RAY_MORSEL_ELEMS) + return ray_error("range", "gather: rows [%lld, %lld) of %lld", (long long)lo, (long long)hi, (long long)src->len); + const int64_t n = hi - lo; + gather_acc_t a; + ray_t* err = acc_open(&a, src, n); + if (err) return err; + /* every row of every vector is read: no point reads */ + gsel_in_t in = { .src = src, .end = hi }; + const int64_t s_lo = lo / RAY_MORSEL_ELEMS, s_hi = (hi + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS; + const int64_t nseg = s_hi - s_lo; + ray_pool_t* pool = ray_pool_get(); + int64_t spt = RAY_DISPATCH_MORSELS; + while ((nseg + spt - 1) / spt > (int64_t)RAY_POOL_INIT_TASKS) spt *= 2; + int64_t ntask = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD) ? (nseg + spt - 1) / spt : 1; + if (ntask <= 1) { + ray_col_fixed_t fixed; /* the decode vector on the stack */ + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, src, &fixed); + err = gsel_range(&in, &a, &cur, s_lo, s_hi, 0); + ray_col_cursor_free(&cur); + } else { + /* task t: segments [s_lo + t * spt, + spt), at output position + * their first row less lo */ + int64_t* pos0 = (int64_t*)ray_alloc_raw((size_t)(ntask + 1) * sizeof(int64_t)); + gather_acc_t* acc = (gather_acc_t*)ray_calloc_raw((size_t)ntask * sizeof(gather_acc_t)); + if (!pos0 || !acc) { + ray_free_raw(pos0); + ray_free_raw(acc); + acc_abort(&a); + return ray_error("oom", "gather tasks"); + } + for (int64_t t = 0; t < ntask; t++) pos0[t] = (s_lo + t * spt) * RAY_MORSEL_ELEMS - lo; + pos0[ntask] = n; + gsel_par_t c = { .in = in, .s_base = s_lo, .nseg = s_hi, .spt = spt, .pos0 = pos0, .acc = acc }; + for (int64_t t = 0; t < ntask; t++) { acc[t].out = a.out; acc[t].ow = a.ow; } + ray_scan_fail_init(&c.fail); + ray_pool_dispatch_n(pool, gsel_task, &c, (uint32_t)ntask); + err = ray_scan_fail_finish(&c.fail, pool); + for (int64_t t = 0; t < ntask; t++) a.nulls |= acc[t].nulls; + if (!err) err = gsel_merge_pools(acc, ntask, pos0, &a); + for (int64_t t = 0; t < ntask; t++) if (acc[t].pool) ray_release(acc[t].pool); + ray_free_raw(pos0); + ray_free_raw(acc); + } + if (err) { acc_abort(&a); return err; } + return acc_finish(&a, src, out); +} + +ray_t* ray_col_gather_slot(ray_t* enc) { + return (enc && enc->type == RAY_ENCCOL && !(enc->attrs & RAY_ATTR_SLICE)) ? enc : NULL; +} + +ray_t* ray_col_gather_enc(ray_t* enc, ray_t* sel, bool by_rows, const int64_t* ids, int64_t n, ray_t** out) { + *out = NULL; + ray_col_src_t s; + ray_t* err = ray_col_src_bind(enc, &s); + if (err) return err; + err = by_rows ? ray_col_gather_rows(&s, ids, n, out) : ray_col_gather_sel(&s, sel, out); + ray_col_src_release(&s); + return err; +} diff --git a/src/ops/colgather.h b/src/ops/colgather.h new file mode 100644 index 000000000..226a1f2ae --- /dev/null +++ b/src/ops/colgather.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_COLGATHER_H +#define RAY_COLGATHER_H + +/* + * Gathers from a bound column source (generation 0 or 2, single file or + * parted) under the spec's gather output contract: the result is a new + * plain vector that owns everything it references. A STR result holds one + * pool built for it (each pooled value is copied out of the read's view + * before the next read reuses the scratch); a SYM result retains the + * source's domain at the widest contributing width class, ids widened as + * logical values; HAS_NULLS and null payloads are left as generation 0's + * gather leaves them (the type's canonical sentinel). A LIST source is + * `nyi` (lists are never encoded; callers keep their LIST code). On any + * error the partial result, its pool and its domain are released and + * nothing is published. + */ + +#include "store/colrange.h" + +/* Rows of `src` kept by rowsel `sel` (NULL: every row), in row order, as a + * new plain vector. Only vectors whose segment is not RAY_SEL_NONE are + * read. A large selection is gathered by pool tasks over consecutive + * segments; a failure is the lowest-row one (the scan-fail envelope), a + * cancelled dispatch `cancel`. NULL with *out set, or an owned error. */ +ray_t* ray_col_gather_sel(ray_col_src_t* src, ray_t* sel, ray_t** out); +/* Rows [lo, hi) of `src` (lo a multiple of RAY_MORSEL_ELEMS), in row + * order, as a new plain vector: every vector the span touches is read once, + * by pool tasks over consecutive segments for a large span (the lowest-row + * failure, a cancelled dispatch `cancel`). For a consumer that walks a + * column in pieces it evaluates whole, so that only one piece is decoded + * at a time. NULL with *out set, or an owned error. */ +ray_t* ray_col_gather_span(ray_col_src_t* src, int64_t lo, int64_t hi, ray_t** out); +/* The operators' entry for one table slot. ray_col_gather_slot: the + * RAY_ENCCOL a row gather reads by range (slot from ray_table_get_col_enc / + * _idx), or NULL for none or a slice of an encoded column, which a source + * does not bind: the caller keeps its plain gather. ray_col_gather_enc: + * that slot bound, gathered under `sel` (by_rows false) or at ids[0..n) + * (by_rows true), released. NULL with *out set, or an owned error. */ +ray_t* ray_col_gather_slot(ray_t* enc); +ray_t* ray_col_gather_enc(ray_t* enc, ray_t* sel, bool by_rows, const int64_t* ids, int64_t n, ray_t** out); +/* Test hook: selection gathers run as several pool tasks since process + * start (a selection of at least RAY_PARALLEL_THRESHOLD rows with a + * pool: each task gathers its segments into the output range the + * selection's counts give it, STR pools appended in row order). */ +uint64_t ray_col_test_gather_par(void); +/* Rows ids[0..n) of `src`, in that order, repeats included, as a new plain + * vector. Ids are bucketed by vector; each touched vector is range-read + * once and its values scattered to their output positions, or, holding at + * most its codec's point-read limit of the ids, point-read (an encoded + * integer or SYM source, nulls included; ray_col_gather_sel's few-row + * segments likewise). */ +ray_t* ray_col_gather_rows(ray_col_src_t* src, const int64_t* ids, int64_t n, ray_t** out); + +#endif /* RAY_COLGATHER_H */ diff --git a/src/ops/collection.c b/src/ops/collection.c index c6fa46eff..a49ded854 100644 --- a/src/ops/collection.c +++ b/src/ops/collection.c @@ -23,6 +23,7 @@ /* Collection / higher-order builtins — extracted from eval.c */ +#include "ops/colgather.h" /* take_table_enc: a window of an encoded column */ #include "lang/internal.h" #include "lang/env.h" #include "core/types.h" @@ -31,6 +32,7 @@ #include "ops/internal.h" /* col_propagate_str_pool */ #include "ops/idxop.h" #include "ops/ops.h" +#include "store/enccol.h" /* ray_enccol_is_parted: (at tbl 'col) on an encoded slot */ #include #include #include @@ -82,7 +84,7 @@ typedef struct hashset_t { enum { HS_NUM_NONE = 0, HS_NUM_INT = 1, HS_NUM_FLT = 2 }; static inline int hs_num_class(int8_t t) { switch (t) { - case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_TIMESPAN: case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: return HS_NUM_INT; case RAY_F32: case RAY_F64: return HS_NUM_FLT; @@ -98,7 +100,7 @@ static inline double hs_cell_f64(int8_t t, const void* data, int64_t i) { case RAY_U8: return (double)((const uint8_t*)data)[i]; case RAY_I16: return (double)((const int16_t*)data)[i]; case RAY_I32: return (double)((const int32_t*)data)[i]; - case RAY_I64: return (double)((const int64_t*)data)[i]; + case RAY_TIMESPAN: case RAY_I64: return (double)((const int64_t*)data)[i]; case RAY_F32: return (double)((const float*)data)[i]; default: return ((const double*)data)[i]; } @@ -134,6 +136,7 @@ static uint64_t hs_hash_row(ray_t* src, int64_t i, int8_t t, void* data, case RAY_F32: return ray_hash_f64((double)((const float*)data)[i]); case RAY_DATE: return ray_hash_i64((int64_t)((const int32_t*)data)[i]); case RAY_TIME: return ray_hash_i64((int64_t)((const int32_t*)data)[i]); + case RAY_TIMESPAN: return ray_hash_i64(((const int64_t*)data)[i]); case RAY_TIMESTAMP: return ray_hash_i64(((const int64_t*)data)[i]); case RAY_SYM: { /* Hashes the raw cell id, i.e. the BUILD side's id space. @@ -156,11 +159,12 @@ static uint64_t hs_hash_row(ray_t* src, int64_t i, int8_t t, void* data, if (!e || RAY_ATOM_IS_NULL(e)) return 0; /* Numeric coercion: hash as f64 so distinct numeric types * holding the same value collide (atom_eq does the same). */ - if (is_numeric(e)) return ray_hash_f64(as_f64(e)); + if (is_numeric(e) || e->type == -RAY_TIMESPAN) return ray_hash_f64(as_f64(e)); switch (e->type) { case -RAY_SYM: return ray_hash_i64(e->i64); case -RAY_DATE: case -RAY_TIME: return ray_hash_i64((int64_t)e->i32); + case -RAY_TIMESPAN: return ray_hash_i64(e->i64); case -RAY_TIMESTAMP: return ray_hash_i64(e->i64); case -RAY_GUID: { const uint8_t* g = e->obj @@ -194,6 +198,7 @@ static int hs_eq_rows(ray_t* a_src, int64_t ai, int8_t at, void* a_data, case RAY_F32: return ((const float*)a_data)[ai] == ((const float*)b_data)[bi]; case RAY_DATE: case RAY_TIME: return ((const int32_t*)a_data)[ai] == ((const int32_t*)b_data)[bi]; + case RAY_TIMESPAN: return ((const int64_t*)a_data)[ai] == ((const int64_t*)b_data)[bi]; case RAY_TIMESTAMP: return ((const int64_t*)a_data)[ai] == ((const int64_t*)b_data)[bi]; case RAY_SYM: { /* Raw index equality is only meaningful within ONE id @@ -554,6 +559,26 @@ static bool find_needle_side_ok(ray_t* hay, ray_t* nd) { * Higher-order functions * ══════════════════════════════════════════ */ +/* The i-th element of `coll`, a LIST or a typed vector, for one call of an + * iterator's function. A typed vector's element is boxed here, one at a + * time, and *owned tells the caller to release it after the call; a LIST's + * slot is lent. Boxing the whole vector up front (unbox_vec_arg) kept every + * atom alive for the whole walk, about ten times the vector's memory (#823). + * A vector type collection_elem cannot box comes back as an error. */ +static inline ray_t* iter_elem(ray_t* coll, int64_t i, int* owned) { + ray_t* e = collection_elem(coll, i, owned); + if (!e) { *owned = 0; return ray_error("oom", NULL); } + return e; +} + +/* An owned reference to the i-th element of `coll`, to seed an accumulator. */ +static ray_t* iter_elem_owned(ray_t* coll, int64_t i) { + int owned = 0; + ray_t* e = iter_elem(coll, i, &owned); + if (!owned && !RAY_IS_ERR(e)) ray_retain(e); + return e; +} + /* (map fn val vec) — apply binary fn(val, elem) to each element of vec. * Also supports (map fn vec) for unary mapping. */ ray_t* ray_map_fn(ray_t** args, int64_t n) { @@ -562,63 +587,48 @@ ray_t* ray_map_fn(ray_t** args, int64_t n) { if (ray_is_lazy(args[i])) args[i] = ray_lazy_materialize(args[i]); ray_t* fn = args[0]; - ray_t* _bx = NULL; + ray_t* val = NULL; + ray_t* coll; if (n == 2) { /* Unary map: (map fn vec) */ - ray_t* vec = unbox_vec_arg(args[1], &_bx); - if (RAY_IS_ERR(vec)) return vec; - if (!is_list(vec)) { if (_bx) ray_release(_bx); return ray_error("type", "map: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - ray_t* result = ray_alloc(len * sizeof(ray_t*)); - if (!result) { if (_bx) ray_release(_bx); return ray_error("oom", NULL); } - result->type = RAY_LIST; - result->len = len; - ray_t** out = (ray_t**)ray_data(result); - ray_t** elems = (ray_t**)ray_data(vec); - for (int64_t i = 0; i < len; i++) { - out[i] = call_fn1(fn, elems[i]); - /* Materialise a lazy result (e.g. the lambda returned - * (count (distinct x)) — distinct/count of a vec is lazy). A LIST - * of unforced lazy nodes breaks every downstream consumer that - * doesn't force per element (sum, ==, +). */ - if (ray_is_lazy(out[i])) out[i] = ray_lazy_materialize(out[i]); - if (RAY_IS_ERR(out[i])) { - for (int64_t j = 0; j < i; j++) ray_release(out[j]); - result->len = 0; ray_release(result); if (_bx) ray_release(_bx); - return out[i]; - } - } - if (_bx) ray_release(_bx); - return result; + coll = args[1]; + if (RAY_IS_ERR(coll)) return coll; + if (!is_collection(coll)) return ray_error("type", "map: vec arg must be a list, got %s", ray_type_name(coll->type)); + } else { + /* Binary map: (map fn val vec) — apply fn(val, elem) */ + val = args[1]; + coll = args[2]; + if (RAY_IS_ERR(coll)) return coll; + /* If vec is scalar, just call fn(val, vec) once */ + if (!is_collection(coll)) return call_fn2(fn, val, coll); } - /* Binary map: (map fn val vec) — apply fn(val, elem) */ - ray_t* val = args[1]; - ray_t* vec = unbox_vec_arg(args[2], &_bx); - if (RAY_IS_ERR(vec)) return vec; - /* If vec is scalar, just call fn(val, vec) once */ - if (!is_list(vec)) { - if (_bx) ray_release(_bx); - return call_fn2(fn, val, args[2]); - } - int64_t len = ray_len(vec); + int64_t len = ray_len(coll); ray_t* result = ray_alloc(len * sizeof(ray_t*)); - if (!result) { if (_bx) ray_release(_bx); return ray_error("oom", NULL); } + if (!result) return ray_error("oom", NULL); result->type = RAY_LIST; result->len = len; ray_t** out = (ray_t**)ray_data(result); - ray_t** elems = (ray_t**)ray_data(vec); for (int64_t i = 0; i < len; i++) { - out[i] = call_fn2(fn, val, elems[i]); + int owned = 0; + ray_t* elem = iter_elem(coll, i, &owned); + if (RAY_IS_ERR(elem)) out[i] = elem; + else if (n == 2) out[i] = call_fn1(fn, elem); + else out[i] = call_fn2(fn, val, elem); + if (owned) ray_release(elem); + /* Materialise a lazy result (e.g. the lambda returned + * (count (distinct x)) — distinct/count of a vec is lazy). A LIST + * of unforced lazy nodes breaks every downstream consumer that + * doesn't force per element (sum, ==, +). */ if (ray_is_lazy(out[i])) out[i] = ray_lazy_materialize(out[i]); if (RAY_IS_ERR(out[i])) { + ray_t* err = out[i]; for (int64_t j = 0; j < i; j++) ray_release(out[j]); - result->len = 0; ray_release(result); if (_bx) ray_release(_bx); - return out[i]; + result->len = 0; ray_release(result); + return err; } } - if (_bx) ray_release(_bx); return result; } @@ -637,49 +647,38 @@ ray_t* ray_fold_fn(ray_t** args, int64_t n) { if (ray_is_lazy(args[i])) args[i] = ray_lazy_materialize(args[i]); ray_t* fn = args[0]; - ray_t* vec; + ray_t* coll = args[n == 2 ? 1 : 2]; + if (RAY_IS_ERR(coll)) return coll; + if (!is_collection(coll)) return ray_error("type", "fold: vec arg must be a list, got %s", ray_type_name(coll->type)); + int64_t len = ray_len(coll); ray_t* acc; - ray_t* _bx = NULL; + int64_t start; if (n == 2) { /* (fold fn vec) — use first element as initial value */ - vec = unbox_vec_arg(args[1], &_bx); - if (RAY_IS_ERR(vec)) return vec; - if (!is_list(vec)) { if (_bx) ray_release(_bx); return ray_error("type", "fold: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - if (len == 0) { if (_bx) ray_release(_bx); return ray_error("domain", "fold: empty list has no initial value, got %lld", (long long)len); } - ray_t** elems = (ray_t**)ray_data(vec); - ray_retain(elems[0]); - acc = elems[0]; - for (int64_t i = 1; i < len; i++) { - ray_t* next = call_fn2(fn, acc, elems[i]); - ray_release(acc); - if (RAY_IS_ERR(next)) { if (_bx) ray_release(_bx); return next; } - acc = next; - } - if (_bx) ray_release(_bx); - return acc; - } - - /* (fold fn init vec) */ - ray_retain(args[1]); - acc = args[1]; - vec = unbox_vec_arg(args[2], &_bx); - if (RAY_IS_ERR(vec)) { ray_release(acc); return vec; } - if (!is_list(vec)) { ray_release(acc); if (_bx) ray_release(_bx); return ray_error("type", "fold: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - ray_t** elems = (ray_t**)ray_data(vec); - for (int64_t i = 0; i < len; i++) { - ray_t* next = call_fn2(fn, acc, elems[i]); + if (len == 0) return ray_error("domain", "fold: empty list has no initial value, got %lld", (long long)len); + acc = iter_elem_owned(coll, 0); + if (RAY_IS_ERR(acc)) return acc; + start = 1; + } else { + /* (fold fn init vec) */ + ray_retain(args[1]); + acc = args[1]; + start = 0; + } + for (int64_t i = start; i < len; i++) { + int owned = 0; + ray_t* elem = iter_elem(coll, i, &owned); + ray_t* next = RAY_IS_ERR(elem) ? elem : call_fn2(fn, acc, elem); + if (owned) ray_release(elem); ray_release(acc); - if (RAY_IS_ERR(next)) { if (_bx) ray_release(_bx); return next; } + if (RAY_IS_ERR(next)) return next; acc = next; } - if (_bx) ray_release(_bx); return acc; } /* Typed prefix-scan kernels for the native arithmetic operators. The - * generic scan below unboxes the vector into a LIST and drives the full + * generic scan below boxes each element and drives the full * call machinery per element — and, worse, RETURNS a LIST of boxed * atoms, so every downstream vector op on the running sums degrades to * the boxed paths too (the q28 20-row moving average spent ~13ms on @@ -740,16 +739,18 @@ static ray_t* scan_typed_arith(ray_t* fn, ray_t* vec) { /* (prior fn vec) — pairwise combinator over adjacent elements: * out[i] = (fn v[i] v[i-1]) for i >= 1, out[0] = (fn v[0] v[0]) — the * self-pair start matches the concat/take shift idiom it replaces - * (prev[0] = v[0]), so a comparison's first slot compares equal → false. + * (prev[0] = v[0]). * The six comparison operators over null-free * numeric/temporal typed vectors (plus ==//= over SYM, where adjacent - * same-vector ids compare directly) run one fused pass returning a BOOL + * same-vector ids, including null id0, compare directly) run one fused pass returning a BOOL * vector — no shifted copy, no boxing. Everything else falls to the * generic per-pair application returning a LIST, mirroring scan. */ static ray_t* prior_typed_cmp(ray_t* fn, ray_t* vec) { if (fn->type != RAY_BINARY || !vec || !ray_is_vec(vec) || vec->len <= 0) return NULL; - if (ray_vec_may_have_nulls(vec)) return NULL; + /* SYM EQ/NE compare canonical same-vector ids, including null id0; + * nullable numeric comparisons still need the generic atom path. */ + if (vec->type != RAY_SYM && ray_vec_may_have_nulls(vec)) return NULL; ray_binary_fn bf = (ray_binary_fn)(uintptr_t)fn->i64; int op; /* 0:< 1:> 2:<= 3:>= 4:== 5:!= */ if (bf == ray_lt_fn) op = 0; @@ -770,7 +771,8 @@ static ray_t* prior_typed_cmp(ray_t* fn, ray_t* vec) { } int64_t n = vec->len; ray_t* out = ray_vec_new(RAY_BOOL, n); - if (!out || RAY_IS_ERR(out)) { if (out) ray_release(out); return NULL; } + /* Allocation failure after admission must not switch BOOL to LIST. */ + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); out->len = n; uint8_t* restrict o = (uint8_t*)ray_data(out); #define PRIOR_CMP_LOOP(READ) \ @@ -877,38 +879,30 @@ ray_t* ray_scan_fn(ray_t** args, int64_t n) { ray_t* fast = scan_typed_arith(fn, args[1]); if (fast) return fast; } - ray_t* _bx = NULL; - ray_t* vec = unbox_vec_arg(args[1], &_bx); - if (RAY_IS_ERR(vec)) return vec; - if (!is_list(vec)) { if (_bx) ray_release(_bx); return ray_error("type", "scan: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - if (len == 0) { - if (_bx) ray_release(_bx); - ray_t* result = ray_alloc(0); - if (!result) return ray_error("oom", NULL); - result->type = RAY_LIST; - result->len = 0; - return result; - } + ray_t* coll = args[1]; + if (RAY_IS_ERR(coll)) return coll; + if (!is_collection(coll)) return ray_error("type", "scan: vec arg must be a list, got %s", ray_type_name(coll->type)); + int64_t len = ray_len(coll); ray_t* result = ray_alloc(len * sizeof(ray_t*)); - if (!result) { if (_bx) ray_release(_bx); return ray_error("oom", NULL); } + if (!result) return ray_error("oom", NULL); result->type = RAY_LIST; - result->len = len; + result->len = 0; + if (len == 0) return result; ray_t** out = (ray_t**)ray_data(result); - ray_t** elems = (ray_t**)ray_data(vec); - ray_retain(elems[0]); - out[0] = elems[0]; + out[0] = iter_elem_owned(coll, 0); + if (RAY_IS_ERR(out[0])) { ray_t* err = out[0]; ray_release(result); return err; } + result->len = 1; for (int64_t i = 1; i < len; i++) { - out[i] = call_fn2(fn, out[i - 1], elems[i]); - if (RAY_IS_ERR(out[i])) { - for (int64_t j = 0; j < i; j++) ray_release(out[j]); - result->len = 0; ray_release(result); if (_bx) ray_release(_bx); - return out[i]; - } + int owned = 0; + ray_t* elem = iter_elem(coll, i, &owned); + ray_t* next = RAY_IS_ERR(elem) ? elem : call_fn2(fn, out[i - 1], elem); + if (owned) ray_release(elem); + if (RAY_IS_ERR(next)) { ray_release(result); return next; } + out[i] = next; + result->len = i + 1; } - if (_bx) ray_release(_bx); return result; } @@ -926,7 +920,8 @@ ray_t* ray_filter_fn(ray_t* vec, ray_t* mask) { if (RAY_IS_ERR(result)) return result; for (int64_t c = 0; c < ncols; c++) { int64_t cn = ray_table_col_name(vec, c); - ray_t* src_col = ray_table_get_col_idx(vec, c); + ray_t* src_col = ray_table_col_idx(vec, c); + if (src_col && RAY_IS_ERR(src_col)) { ray_release(result); return src_col; } ray_t* filtered = ray_filter_fn(src_col, mask); if (RAY_IS_ERR(filtered)) { ray_release(result); return filtered; } result = ray_table_add_col(result, cn, filtered); @@ -1072,8 +1067,46 @@ ray_t* ray_apply_fn(ray_t** args, int64_t n) { * Collection operations * ══════════════════════════════════════════ */ +/* atom_eq for a column of a table / dict cell. A SYM column is read at + * its storage width (the vector branch reads 8 bytes a cell) and compared + * by text across domains; a STR column by content (a descriptor holds a + * pool offset and a cached hash). Other columns take atom_eq. */ +static int atom_eq_cell_col(ray_t* a, ray_t* b) { + if (a->type != b->type || a->len != b->len || + (a->type != RAY_SYM && a->type != RAY_STR)) + return atom_eq(a, b); + if (a->type == RAY_STR) { + for (int64_t i = 0; i < a->len; i++) { + size_t la = 0, lb = 0; + const char* sa = ray_str_vec_get(a, i, &la); + const char* sb = ray_str_vec_get(b, i, &lb); + if (la != lb || (la && memcmp(sa, sb, la) != 0)) return 0; + } + return 1; + } + bool same_dom = ray_sym_vec_domain(a) == ray_sym_vec_domain(b); + for (int64_t i = 0; i < a->len; i++) { + if (same_dom) { + if (ray_read_sym(ray_data(a), i, RAY_SYM, a->attrs) != + ray_read_sym(ray_data(b), i, RAY_SYM, b->attrs)) return 0; + } else if (ray_str_cmp(ray_sym_vec_cell(a, i), ray_sym_vec_cell(b, i)) != 0) { + return 0; + } + } + return 1; +} + /* Helper: compare two atoms for equality (value-based) */ int atom_eq(ray_t* a, ray_t* b) { + if (ray_has_timespan(a) || ray_has_timespan(b)) { + if (ray_timespan_binary_type(OP_EQ, a->type, b->type) <= 0) return 0; + ray_t* result = ray_timespan_binary(OP_EQ, a, b); + if (RAY_IS_ERR(result)) return 0; + int equal = result->b8; + ray_release(result); + return equal; + } + int a_null = RAY_ATOM_IS_NULL(a); int b_null = RAY_ATOM_IS_NULL(b); /* Two nulls are equal where two values of their types can be: the same @@ -1099,6 +1132,7 @@ int atom_eq(ray_t* a, ray_t* b) { case -RAY_SYM: return a->i64 == b->i64; case -RAY_DATE: case -RAY_TIME: return a->i32 == b->i32; + case -RAY_TIMESPAN: case -RAY_TIMESTAMP: return a->i64 == b->i64; case -RAY_GUID: { @@ -1128,6 +1162,34 @@ int atom_eq(ray_t* a, ray_t* b) { } return 1; } + case RAY_TABLE: { + /* Same column names in order and equal columns. The vector branch + * below compares len * elem_size bytes, zero for a table, so every + * pair of same-length tables compared equal (one group for all). */ + int64_t nc = ray_table_ncols(a); + if (nc != ray_table_ncols(b) || ray_table_nrows(a) != ray_table_nrows(b)) + return 0; + for (int64_t c = 0; c < nc; c++) { + if (ray_table_col_name(a, c) != ray_table_col_name(b, c)) return 0; + ray_t* ca = ray_table_col_idx(a, c); + ray_t* cb = ray_table_col_idx(b, c); + bool ea = ca && RAY_IS_ERR(ca), eb = cb && RAY_IS_ERR(cb); + if (ea) ray_error_free(ca); + if (eb) ray_error_free(cb); + if (ea || eb) return 0; /* a column that cannot be read compares unequal */ + if (!ca || !cb) { if (ca != cb) return 0; continue; } + if (!atom_eq_cell_col(ca, cb)) return 0; + } + return 1; + } + case RAY_DICT: { + /* Equal keys and equal values, position by position (the vector + * branch saw every pair of same-length dicts as equal too). */ + ray_t* ka = ray_dict_keys(a); ray_t* kb = ray_dict_keys(b); + ray_t* va = ray_dict_vals(a); ray_t* vb = ray_dict_vals(b); + if (!ka || !kb || !va || !vb) return ka == kb && va == vb; + return atom_eq_cell_col(ka, kb) && atom_eq_cell_col(va, vb); + } default: /* Vector equality: same type and length, element-wise comparison */ if (a->type > 0 && a->type == b->type && a->len == b->len) { @@ -1161,6 +1223,7 @@ ray_t* distinct_vec_eager(ray_t* x) { ray_t* ids = ray_index_distinct_ids(x, &count); if (ids) { ray_idx_hits[IDX_SITE_DISTINCT]++; + ray_idx_note_use(x); ray_t* result = gather_by_idx(x, (int64_t*)ray_data(ids), count); ray_release(ids); return result; @@ -1259,18 +1322,19 @@ ray_t* distinct_vec_eager(ray_t* x) { return result; } -static ray_t* parted_to_flat_vec(ray_t* x) { +/* `cnt`/`ncnt` are the partition row counts of the column's table (NULL + * when the column is met on its own): a NULL segment, a partition without + * the column, then yields its rows as the type's null. */ +static ray_t* parted_to_flat_vec_c(ray_t* x, const int64_t* cnt, int64_t ncnt) { if (!x || !RAY_IS_PARTED(x->type)) return ray_error("type", NULL); int8_t base = (int8_t)RAY_PARTED_BASETYPE(x->type); ray_t** segs = (ray_t**)ray_data(x); - int64_t total = 0; - for (int64_t s = 0; s < x->len; s++) - if (segs[s]) total += segs[s]->len; + int64_t total = parted_rows_counted(x, cnt, ncnt); /* RAY_LIST: share (retain) elements — ray_vec_new rejects type 0 and * the per-cell copy below has no notion of nested elements. */ if (base == RAY_LIST) - return parted_flatten_list(segs, x->len, total); + return parted_flatten_list_c(segs, x->len, cnt, ncnt); ray_t* out = ray_vec_new(base, base == RAY_STR ? 0 : total); if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); @@ -1279,7 +1343,20 @@ static ray_t* parted_to_flat_vec(ray_t* x) { int64_t pos = 0; for (int64_t s = 0; s < x->len; s++) { ray_t* seg = segs[s]; - if (!seg) continue; + if (!seg) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + if (base == RAY_STR) { + for (int64_t i = 0; i < n; i++) { + out = ray_str_vec_append(out, "", 0); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + ray_vec_set_null(out, pos++, true); + } + } else { + parted_fill_nulls(out, pos, n); + pos += n; + } + continue; + } for (int64_t i = 0; i < seg->len; i++) { if (base == RAY_STR) { size_t slen = 0; @@ -1303,6 +1380,10 @@ static ray_t* parted_to_flat_vec(ray_t* x) { return out; } +static ray_t* parted_to_flat_vec(ray_t* x) { + return parted_to_flat_vec_c(x, NULL, 0); +} + /* (distinct x) — remove duplicates. Dispatches on type: * table → deduplicate rows (via DAG GROUP with zero aggs) * vector → remove duplicate elements, preserving first occurrence @@ -1528,6 +1609,7 @@ ray_t* ray_in_fn(ray_t* val, ray_t* vec) { bool miss = false; if (ray_index_find_vec(vec, val, pos, &miss)) { ray_idx_hits[IDX_SITE_IN]++; + ray_idx_note_use(vec); ray_t* result = ray_vec_new(RAY_BOOL, vlen); if (RAY_IS_ERR(result)) { ray_free_raw(pos); return result; } result->len = vlen; @@ -1999,6 +2081,133 @@ ray_t* ray_sect_fn(ray_t* vec1, ray_t* vec2) { return result; } +/* Rows [start, start+count) of the parted or MAPCOMMON column `col` of the + * table `tbl` (.db.parted.get) as a flat vector, reading only those rows + * (0 <= start, start + count <= the table's rows). The table's partition + * counts give the rows a NULL segment (a partition without the column) + * spans; they come back as the type's null. */ +static ray_t* parted_col_window(ray_t* tbl, ray_t* col, int64_t start, int64_t count) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); + int8_t base = col->type == RAY_MAPCOMMON + ? RAY_SYM : (int8_t)RAY_PARTED_BASETYPE(col->type); + + /* MAPCOMMON, STR and LIST go through the row-index gathers. */ + if (col->type == RAY_MAPCOMMON || base == RAY_STR || base == RAY_LIST) { + int64_t one = 0; + int64_t* idx = count > 0 ? (int64_t*)ray_alloc_raw((size_t)count * sizeof(int64_t)) : &one; + if (!idx) return ray_error("oom", NULL); + for (int64_t i = 0; i < count; i++) idx[i] = start + i; + ray_t** segs = (ray_t**)ray_data(col); + ray_t* out = col->type == RAY_MAPCOMMON + ? materialize_mapcommon_gather(col, idx, count) + : base == RAY_STR + ? parted_gather_str_rows_c(segs, col->len, idx, count, cnt, ncnt) + : parted_gather_list_rows_c(segs, col->len, idx, count, cnt, ncnt); + if (idx != &one) ray_free_raw(idx); + return out ? out : ray_error("oom", NULL); + } + + ray_t** segs = (ray_t**)ray_data(col); + uint8_t ba = (base == RAY_SYM) ? parted_sym_max_attrs(segs, col->len) : 0; + ray_t* out = typed_vec_new(base, ba, count); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + out->len = count; + int64_t end = start + count, seg_start = 0; + for (int64_t s = 0; s < col->len && seg_start < end; s++) { + int64_t rows = parted_seg_rows(segs, s, cnt, ncnt); + int64_t lo = start > seg_start ? start : seg_start; + int64_t hi = end < seg_start + rows ? end : seg_start + rows; + if (lo < hi) { + int64_t dst = lo - start, src = lo - seg_start, n = hi - lo; + if (!segs[s] || RAY_IS_ERR(segs[s])) { + parted_fill_nulls(out, dst, n); + } else { + parted_copy_cells(ray_data(out), base, ba, dst, segs[s], src, n); + if (ray_vec_may_have_nulls(segs[s])) + for (int64_t i = 0; i < n; i++) + if (ray_vec_is_null(segs[s], src + i)) + ray_vec_set_null(out, dst + i, true); + } + } + seg_start += rows; + } + /* raw SYM cell ids copied from the segments — adopt their domain */ + if (base == RAY_SYM) { + ray_t* rep = sym_domain_rep(col); + if (rep) ray_sym_vec_adopt_domain(out, rep); + } + return out; +} + +/* take over one column of the table `tbl`. A parted or MAPCOMMON column + * (.db.parted.get) is not a dense vector: materialize only the rows the + * count selects — the head or tail window, or a range — and, when the + * count wraps past the row count, all rows, then take from those as for a + * flat column (#855). `n_obj` was validated by ray_take_fn. */ +#define TAKE_ENC_WINDOW_MAX (INT64_C(1) << 20) + +/* (take tbl n) of an encoded column: only the rows taken are read, by + * range, so a window of a compressed column does not decode it whole. NULL + * when the slot is plain, a slice, or the take wraps past the end (the + * caller takes the plain column). */ +static ray_t* take_table_enc(ray_t* tbl, int64_t i, ray_t* n_obj) { + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(tbl, i)); + if (!enc) return NULL; + int64_t nrows = ray_table_nrows(tbl), start, count; + if (ray_is_vec(n_obj)) { + const int64_t* r = (const int64_t*)ray_data(n_obj); + start = r[0]; + if (start < 0) start = nrows + start; + if (start < 0) start = 0; + count = start >= nrows ? 0 : r[1] < nrows - start ? r[1] : nrows - start; + if (start >= nrows) start = 0; + } else { + int64_t n = as_i64(n_obj); + int64_t abs_n = n < 0 ? -n : n; + if (abs_n > nrows) return NULL; + start = n >= 0 ? 0 : nrows - abs_n; + count = abs_n; + } + /* A row gather holds 8 bytes of row id a row: past a window of this + * size the take is most of the column anyway, and decoding it is cheaper. */ + if (count > TAKE_ENC_WINDOW_MAX) return NULL; + int64_t one = 0; + int64_t* ids = count > 0 ? (int64_t*)ray_alloc_raw((size_t)count * sizeof(int64_t)) : &one; + if (!ids) return ray_error("oom", NULL); + for (int64_t k = 0; k < count; k++) ids[k] = start + k; + ray_t* out = NULL; + ray_t* err = ray_col_gather_enc(enc, NULL, true, ids, count, &out); + if (ids != &one) ray_free_raw(ids); + if (err) return err; + return out ? out : ray_error("oom", NULL); +} + +static ray_t* take_table_col(ray_t* tbl, ray_t* col, ray_t* n_obj) { + if (!col || !(RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) + return ray_take_fn(col, n_obj); + int64_t nrows = ray_table_nrows(tbl); + if (ray_is_vec(n_obj)) { + /* range take [start amount], clamped as for a typed vector */ + const int64_t* r = (const int64_t*)ray_data(n_obj); + int64_t start = r[0], amount = r[1]; + if (start < 0) start = nrows + start; + if (start < 0) start = 0; + if (start >= nrows) return parted_col_window(tbl, col, 0, 0); + int64_t count = amount < nrows - start ? amount : nrows - start; + return parted_col_window(tbl, col, start, count); + } + int64_t n = as_i64(n_obj); + int64_t abs_n = n < 0 ? -n : n; + if (abs_n <= nrows) + return parted_col_window(tbl, col, n >= 0 ? 0 : nrows - abs_n, abs_n); + ray_t* all = parted_col_window(tbl, col, 0, nrows); + if (!all || RAY_IS_ERR(all)) return all ? all : ray_error("oom", NULL); + ray_t* out = ray_take_fn(all, n_obj); + ray_release(all); + return out; +} + /* (take vec n) — first n elements (positive) or last |n| elements (negative) */ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { if (ray_is_lazy(vec)) vec = ray_lazy_materialize(vec); @@ -2021,9 +2230,13 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { ray_t* result = ray_table_new(ncols); if (RAY_IS_ERR(result)) return result; for (int64_t i = 0; i < ncols; i++) { - ray_t* col = ray_table_get_col_idx(vec, i); int64_t name_id = ray_table_col_name(vec, i); - ray_t* taken = ray_take_fn(col, n_obj); + ray_t* taken = take_table_enc(vec, i, n_obj); + if (!taken) { + ray_t* col = ray_table_col_idx(vec, i); + if (col && RAY_IS_ERR(col)) { ray_release(result); return col; } + taken = take_table_col(vec, col, n_obj); + } if (RAY_IS_ERR(taken)) { ray_release(result); return taken; } result = ray_table_add_col(result, name_id, taken); ray_release(taken); @@ -2206,9 +2419,13 @@ ray_t* ray_take_fn(ray_t* vec, ray_t* n_obj) { ray_t* result = ray_table_new(ncols); if (RAY_IS_ERR(result)) return result; for (int64_t i = 0; i < ncols; i++) { - ray_t* col = ray_table_get_col_idx(vec, i); int64_t name_id = ray_table_col_name(vec, i); - ray_t* taken = ray_take_fn(col, n_obj); + ray_t* taken = take_table_enc(vec, i, n_obj); + if (!taken) { + ray_t* col = ray_table_col_idx(vec, i); + if (col && RAY_IS_ERR(col)) { ray_release(result); return col; } + taken = take_table_col(vec, col, n_obj); + } if (RAY_IS_ERR(taken)) { ray_release(result); return taken; } result = ray_table_add_col(result, name_id, taken); ray_release(taken); @@ -2567,7 +2784,110 @@ ray_t* ray_cross_fn(ray_t* a, ray_t* b) { return out; } +/* An encoded slot whose promoted scan equals today's `at` value: a + * single-file column (OP_SCAN materializes it exactly as ray_table_col + * does), or a parted one of a numeric / temporal base type (OP_SCAN's + * flatten and parted_to_flat_vec then build the same vector). Forcing the + * reference itself always reads ray_table_col_value. */ +static bool at_lazy_ok(ray_t* enc) { + ray_col_meta_t m; + if (!ray_col_meta_of(enc, &m)) return false; + int8_t b = RAY_IS_PARTED(m.type) ? (int8_t)RAY_PARTED_BASETYPE(m.type) : m.type; + if (!ray_enccol_is_parted(enc)) return true; + switch (b) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_F32: case RAY_F64: return true; + default: return false; + } +} + +/* The value (at tbl 'col) returns eagerly: the column, a parted one + * flattened, MAPCOMMON materialized. An owned value or error. */ +ray_t* ray_table_col_value(ray_t* tbl, int64_t sym) { + ray_t* col = ray_table_col(tbl, sym); + if (col && RAY_IS_ERR(col)) return col; + if (!col) return ray_error("domain", "at: unknown table column"); + if (RAY_IS_PARTED(col->type)) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); + return parted_to_flat_vec_c(col, cnt, ncnt); + } + if (col->type == RAY_MAPCOMMON) return materialize_mapcommon(col); + ray_retain(col); + return col; +} + /* (at vec idx) or (at table 'col) — index into vector or table */ +/* Row j of an integer index vector as a row id into a vec of vlen rows, + * or -1 when it is null or out of range. */ +static int64_t at_row(ray_t* idx, const void* ids, int64_t j, int64_t vlen, bool nulls) { + if (nulls && ray_vec_is_null(idx, j)) return -1; + int64_t k; + switch (idx->type) { + case RAY_I64: k = ((const int64_t*)ids)[j]; break; + case RAY_I32: k = ((const int32_t*)ids)[j]; break; + case RAY_I16: k = ((const int16_t*)ids)[j]; break; + default: k = ((const uint8_t*)ids)[j]; break; + } + return k >= 0 && k < vlen ? k : -1; +} + +/* (at vec idx) for a typed vec and an integer index vector — see the + * caller in ray_at_fn. The valid row ids are gathered; an invalid one + * reads row 0 (nothing, from an empty vec) and is then set to the type's + * null, or to zero for BOOL and U8, which have none. */ +static ray_t* at_gather_typed(ray_t* vec, ray_t* idx) { + int64_t n = ray_len(idx); + int64_t vlen = ray_len(vec); + bool nulls = ray_vec_may_have_nulls(idx); + const void* ids = ray_data(idx); + + /* The common case: I64 row ids, all valid — gather straight from them. */ + int64_t nbad = 0; + for (int64_t j = 0; j < n; j++) + if (at_row(idx, ids, j, vlen, nulls) < 0) nbad++; + if (idx->type == RAY_I64 && nbad == 0) + return gather_by_idx(vec, (int64_t*)ids, n); + + ray_t* out; + if (vlen > 0) { + ray_t* rows = ray_vec_new(RAY_I64, n); + if (!rows || RAY_IS_ERR(rows)) return rows ? rows : ray_error("oom", NULL); + rows->len = n; + int64_t* r = (int64_t*)ray_data(rows); + for (int64_t j = 0; j < n; j++) { + int64_t k = at_row(idx, ids, j, vlen, nulls); + r[j] = k < 0 ? 0 : k; + } + out = gather_by_idx(vec, r, n); + ray_release(rows); + } else if (vec->type == RAY_SYM) { + out = ray_sym_vec_new(vec->attrs & RAY_SYM_W_MASK, n); + if (out && !RAY_IS_ERR(out)) { + ray_sym_vec_adopt_domain(out, vec); + out->len = n; + memset(ray_data(out), 0, (size_t)n * RAY_SYM_ELEM(vec->attrs & RAY_SYM_W_MASK)); + } + } else { + out = ray_vec_new(vec->type, n); + if (out && !RAY_IS_ERR(out)) { + out->len = n; + memset(ray_data(out), 0, (size_t)n * ray_type_sizes[vec->type]); + } + } + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + if (nbad == 0) return out; + + bool nullable = vec->type != RAY_BOOL && vec->type != RAY_U8; + uint8_t* bytes = (uint8_t*)ray_data(out); + for (int64_t j = 0; j < n; j++) { + if (at_row(idx, ids, j, vlen, nulls) >= 0) continue; + if (nullable) ray_vec_set_null(out, j, true); + else bytes[j] = 0; + } + return out; +} + ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { if (ray_is_lazy(vec)) vec = ray_lazy_materialize(vec); /* Table column access by symbol key — return the typed vector directly. @@ -2576,12 +2896,11 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { * direct `(at table 'col)` must materialize it so downstream `(at col i)` / * count / formatting see a dense vector instead of failing with `type`. */ if (vec->type == RAY_TABLE && idx->type == -RAY_SYM) { - ray_t* col = ray_table_get_col(vec, idx->i64); - if (!col) return ray_error("domain", "at: unknown table column"); - if (RAY_IS_PARTED(col->type)) return parted_to_flat_vec(col); - if (col->type == RAY_MAPCOMMON) return materialize_mapcommon(col); - ray_retain(col); - return col; + /* An encoded slot stays a column reference: an aggregate over it + * reduces on the bound source; forcing it reads the column below. */ + ray_t* enc = ray_table_get_col_enc(vec, idx->i64); + if (enc && at_lazy_ok(enc)) return ray_lazy_colref(vec, idx->i64); + return ray_table_col_value(vec, idx->i64); } /* Table row access by integer index: (at table 0) → {col1: val1, col2: val2} */ @@ -2601,7 +2920,8 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { int64_t key_id = ray_table_col_name(vec, c); keys = ray_vec_append(keys, &key_id); if (RAY_IS_ERR(keys)) { ray_release(vals); return keys; } - ray_t* col = ray_table_get_col_idx(vec, c); + ray_t* col = ray_table_col_idx(vec, c); + if (col && RAY_IS_ERR(col)) { ray_release(keys); ray_release(vals); return col; } int alloc = 0; ray_t* val = collection_elem(col, row, &alloc); if (RAY_IS_ERR(val)) { ray_release(keys); ray_release(vals); return val; } @@ -2629,10 +2949,26 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { ray_t* result = ray_table_new(ncols); if (!result || RAY_IS_ERR(result)) return result ? result : ray_error("oom", NULL); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(vec, c); + ray_t* col = ray_table_col_idx(vec, c); + if (col && RAY_IS_ERR(col)) { ray_release(result); return col; } int64_t name = ray_table_col_name(vec, c); if (!col) continue; - ray_t* gathered = gather_by_idx(col, ids, nidx); + /* Parted and MAPCOMMON columns (.db.parted.get) are not dense + * vectors: flatten them the way the symbol arm does, then gather. */ + ray_t* flat = NULL; + if (RAY_IS_PARTED(col->type)) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(vec, &ncnt); + flat = parted_to_flat_vec_c(col, cnt, ncnt); + } else if (col->type == RAY_MAPCOMMON) { + flat = materialize_mapcommon(col); + } + if (flat && RAY_IS_ERR(flat)) { + ray_release(result); + return flat; + } + ray_t* gathered = gather_by_idx(flat ? flat : col, ids, nidx); + if (flat) ray_release(flat); if (!gathered || RAY_IS_ERR(gathered)) { ray_release(result); return gathered ? gathered : ray_error("oom", NULL); @@ -2739,24 +3075,15 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { return ray_str(&s[i], 1); } - /* Typed vector index: keep the result typed when every row id is valid. - * The generic path below remains responsible for out-of-range/null row ids, - * because it preserves the scalar `at` rule of producing typed null atoms. */ - if (ray_is_vec(vec) && idx->type == RAY_I64 && ray_is_vec(idx)) { - int64_t idxlen = ray_len(idx); - int64_t vlen = ray_len(vec); - int64_t* ids = (int64_t*)ray_data(idx); - bool idx_has_nulls = ray_vec_may_have_nulls(idx); - bool valid = true; - for (int64_t j = 0; j < idxlen; j++) { - if ((idx_has_nulls && ray_vec_is_null(idx, j)) || - ids[j] < 0 || ids[j] >= vlen) { - valid = false; - break; - } - } - if (valid) return gather_by_idx(vec, ids, idxlen); - } + /* Typed vector indexed by an integer vector: the result has the + * source's type, whatever the index holds. A null or out-of-range + * index gives the type's null there, as the scalar `at` gives a typed + * null atom; BOOL and U8 have no null and give false / 0x00. Only a + * nested index (a LIST of index vectors) takes the generic path. */ + if (ray_is_vec(vec) && ray_is_vec(idx) && + (idx->type == RAY_I64 || idx->type == RAY_I32 || + idx->type == RAY_I16 || idx->type == RAY_U8)) + return at_gather_typed(vec, idx); /* Vector index: (at vec [i j k]) → vector of values */ if (is_collection(idx) && idx->type != -RAY_SYM) { @@ -2780,6 +3107,8 @@ ray_t* ray_at_fn(ray_t* vec, ray_t* idx) { ray_t* sub_idx = idx_elem; ray_t* val = ray_at_fn(vec, sub_idx); if (alloc) ray_release(idx_elem); + /* a list holds values, never a lazy column scan */ + if (val && !RAY_IS_ERR(val) && ray_is_lazy(val)) val = ray_lazy_materialize(val); if (RAY_IS_ERR(val)) { result->len = j; ray_release(result); @@ -2856,6 +3185,7 @@ ray_t* ray_find_fn(ray_t* vec, ray_t* val) { ray_idx_consults[IDX_SITE_FIND]++; if (ray_index_find_vec(vec, val, out, &any_null)) { ray_idx_hits[IDX_SITE_FIND]++; + ray_idx_note_use(vec); done = true; } } @@ -2906,6 +3236,7 @@ ray_t* ray_find_fn(ray_t* vec, ray_t* val) { int64_t row = ray_index_find_atom(vec, val); if (row >= -1) { /* -2 means not eligible — fall through */ ray_idx_hits[IDX_SITE_FIND]++; + ray_idx_note_use(vec); if (row < 0) return ray_typed_null(-RAY_I64); return make_i64(row); @@ -3753,6 +4084,7 @@ static bool ts_cell_equal(ray_t* x, int64_t a, int64_t b) { case RAY_TIME: return ((const int32_t*)d)[a] == ((const int32_t*)d)[b]; case RAY_I64: + case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)d)[a] == ((const int64_t*)d)[b]; case RAY_F32: @@ -4338,7 +4670,8 @@ ray_t* ray_fills_fn(ray_t* x) { if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(x, c); + ray_t* col = ray_table_col_idx(x, c); + if (col && RAY_IS_ERR(col)) { ray_release(out); return col; } ray_t* filled = fills_vec_eager(col); if (!filled || RAY_IS_ERR(filled)) { ray_release(out); @@ -4418,7 +4751,7 @@ ray_t* ray_mdev_fn(ray_t* n, ray_t* x) { return ts_moving_fn(n, x, OP_MDEV); } -/* (reverse vec) — reverse a vector */ +/* (reverse x) — reverse a vector, table's rows, or dictionary's entries */ ray_t* ray_reverse_fn(ray_t* x) { if (!x || RAY_IS_ERR(x)) return x; @@ -4427,6 +4760,28 @@ ray_t* ray_reverse_fn(ray_t* x) { if (ray_is_atom(x)) { ray_retain(x); return x; } + if (x->type == RAY_TABLE) { + int64_t nrows = ray_table_nrows(x); + ray_t* ids = ray_vec_new(RAY_I64, nrows); + if (!ids || RAY_IS_ERR(ids)) return ids ? ids : ray_error("oom", NULL); + ids->len = nrows; + int64_t* rows = (int64_t*)ray_data(ids); + for (int64_t i = 0; i < nrows; i++) rows[i] = nrows - 1 - i; + ray_t* result = ray_at_fn(x, ids); + ray_release(ids); + return result; + } + + if (x->type == RAY_DICT) { + ray_t* keys = ray_dict_keys(x); + ray_t* vals = ray_dict_vals(x); + if (!keys || !vals) return ray_error("domain", "reverse: malformed dictionary"); + ray_t* nk = ray_is_vec(keys) ? reverse_vec_eager(keys) : ray_reverse_fn(keys); + if (!nk || RAY_IS_ERR(nk)) return nk ? nk : ray_error("oom", NULL); + ray_t* nv = ray_is_vec(vals) ? reverse_vec_eager(vals) : ray_reverse_fn(vals); + return ray_dict_new(nk, nv); + } + /* Typed vector path: start a fresh lazy chain. The DAG executor will * call reverse_vec_eager() when the chain is materialised. */ if (ray_is_vec(x)) { @@ -4647,13 +5002,11 @@ ray_t* ray_fold_left_fn(ray_t** args, int64_t n) { * BEFORE the first element, so a predicate that is false at the start * returns `init` untouched and touches nothing. * - * Deliberately unlike ray_fold_fn in one respect: that routes its - * collection through unbox_vec_arg -> to_boxed_list, boxing every element - * up front. For a primitive whose whole purpose is to stop early, paying - * for the tail it never reaches is exactly the cost being removed here - * (issue 588), so elements are pulled one at a time via collection_elem — - * the same way map_iterate walks its input. Stopping at element three of - * a million costs three boxed atoms, not a million. */ + * Elements are pulled one at a time via collection_elem, as ray_fold_fn + * does, never boxed up front: for a primitive whose whole purpose is to + * stop early, paying for the tail it never reaches would defeat it + * (issue 588). Stopping at element three of a million costs three boxed + * atoms, not a million. */ ray_t* ray_fold_while_fn(ray_t** args, int64_t n) { if (n != 4) return ray_error("domain", "fold-while: requires exactly 4 args (pred, fn, init, coll), got %lld", (long long)n); for (int64_t i = 0; i < n; i++) @@ -4694,45 +5047,33 @@ ray_t* ray_fold_right_fn(ray_t** args, int64_t n) { if (ray_is_lazy(args[i])) args[i] = ray_lazy_materialize(args[i]); ray_t* fn = args[0]; - ray_t* _bx = NULL; + ray_t* coll = args[n == 2 ? 1 : 2]; + if (RAY_IS_ERR(coll)) return coll; + if (!is_collection(coll)) return ray_error("type", "fold-right: vec arg must be a list, got %s", ray_type_name(coll->type)); + int64_t len = ray_len(coll); ray_t* acc; - ray_t* vec; - + int64_t start; if (n == 2) { /* (fold-right fn vec) — use last element as initial value */ - vec = unbox_vec_arg(args[1], &_bx); - if (RAY_IS_ERR(vec)) return vec; - if (!is_list(vec)) { if (_bx) ray_release(_bx); return ray_error("type", "fold-right: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - if (len == 0) { if (_bx) ray_release(_bx); return ray_error("domain", "fold-right: empty list has no initial value, got %lld", (long long)len); } - ray_t** elems = (ray_t**)ray_data(vec); - ray_retain(elems[len - 1]); - acc = elems[len - 1]; - for (int64_t i = len - 2; i >= 0; i--) { - ray_t* next = call_fn2(fn, elems[i], acc); - ray_release(acc); - if (RAY_IS_ERR(next)) { if (_bx) ray_release(_bx); return next; } - acc = next; - } - if (_bx) ray_release(_bx); - return acc; - } - - /* (fold-right fn init coll) */ - ray_retain(args[1]); - acc = args[1]; - vec = unbox_vec_arg(args[2], &_bx); - if (RAY_IS_ERR(vec)) { ray_release(acc); return vec; } - if (!is_list(vec)) { ray_release(acc); if (_bx) ray_release(_bx); return ray_error("type", "fold-right: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - ray_t** elems = (ray_t**)ray_data(vec); - for (int64_t i = len - 1; i >= 0; i--) { - ray_t* next = call_fn2(fn, elems[i], acc); + if (len == 0) return ray_error("domain", "fold-right: empty list has no initial value, got %lld", (long long)len); + acc = iter_elem_owned(coll, len - 1); + if (RAY_IS_ERR(acc)) return acc; + start = len - 2; + } else { + /* (fold-right fn init coll) */ + ray_retain(args[1]); + acc = args[1]; + start = len - 1; + } + for (int64_t i = start; i >= 0; i--) { + int owned = 0; + ray_t* elem = iter_elem(coll, i, &owned); + ray_t* next = RAY_IS_ERR(elem) ? elem : call_fn2(fn, elem, acc); + if (owned) ray_release(elem); ray_release(acc); - if (RAY_IS_ERR(next)) { if (_bx) ray_release(_bx); return next; } + if (RAY_IS_ERR(next)) return next; acc = next; } - if (_bx) ray_release(_bx); return acc; } @@ -4748,37 +5089,33 @@ ray_t* ray_scan_right_fn(ray_t** args, int64_t n) { if (ray_is_lazy(args[i])) args[i] = ray_lazy_materialize(args[i]); ray_t* fn = args[0]; - ray_t* _bx = NULL; - ray_t* vec = unbox_vec_arg(args[1], &_bx); - if (RAY_IS_ERR(vec)) return vec; - if (!is_list(vec)) { if (_bx) ray_release(_bx); return ray_error("type", "scan-right: vec arg must be a list, got %s", ray_type_name(vec->type)); } - int64_t len = ray_len(vec); - if (len == 0) { - if (_bx) ray_release(_bx); - ray_t* result = ray_alloc(0); - if (!result) return ray_error("oom", NULL); - result->type = RAY_LIST; - result->len = 0; - return result; - } + ray_t* coll = args[1]; + if (RAY_IS_ERR(coll)) return coll; + if (!is_collection(coll)) return ray_error("type", "scan-right: vec arg must be a list, got %s", ray_type_name(coll->type)); + int64_t len = ray_len(coll); ray_t* result = ray_alloc(len * sizeof(ray_t*)); - if (!result) { if (_bx) ray_release(_bx); return ray_error("oom", NULL); } + if (!result) return ray_error("oom", NULL); result->type = RAY_LIST; - result->len = len; + result->len = 0; + if (len == 0) return result; ray_t** out = (ray_t**)ray_data(result); - ray_t** elems = (ray_t**)ray_data(vec); - ray_retain(elems[len - 1]); - out[len - 1] = elems[len - 1]; + /* Filled from the end, so the error path releases the tail by hand. */ + out[len - 1] = iter_elem_owned(coll, len - 1); + if (RAY_IS_ERR(out[len - 1])) { ray_t* err = out[len - 1]; ray_release(result); return err; } for (int64_t i = len - 2; i >= 0; i--) { - out[i] = call_fn2(fn, elems[i], out[i + 1]); - if (RAY_IS_ERR(out[i])) { + int owned = 0; + ray_t* elem = iter_elem(coll, i, &owned); + ray_t* next = RAY_IS_ERR(elem) ? elem : call_fn2(fn, elem, out[i + 1]); + if (owned) ray_release(elem); + if (RAY_IS_ERR(next)) { for (int64_t j = i + 1; j < len; j++) ray_release(out[j]); - result->len = 0; ray_release(result); if (_bx) ray_release(_bx); - return out[i]; + ray_release(result); + return next; } + out[i] = next; } - if (_bx) ray_release(_bx); + result->len = len; return result; } diff --git a/src/ops/datalog.c b/src/ops/datalog.c index 7d885056b..6ec1cb211 100644 --- a/src/ops/datalog.c +++ b/src/ops/datalog.c @@ -55,6 +55,18 @@ dl_program_t* dl_program_new(void) { return prog; } +/* Keep the first error an evaluation step failed with (the rest are + * disposed of); dl_eval's callers report it instead of a generic failure. */ +static void dl_keep_err(dl_program_t* prog, ray_t* e) { + if (!e) return; + /* Program-shape errors (type, domain) keep the generic domain report; + * what is kept is a column that failed to materialize and the like. */ + const char* code = RAY_IS_ERR(e) ? ray_err_code(e) : ""; + bool shape = strcmp(code, "type") == 0 || strcmp(code, "domain") == 0; + if (!prog->first_err && !shape) prog->first_err = e; + else ray_error_free(e); +} + /* Recover the ray_t header from a dl_program_t pointer for ray_free. */ static inline ray_t* dl_prog_block(dl_program_t* prog) { return (ray_t*)((char*)prog - 32); /* ray_data is at offset 32 */ @@ -74,6 +86,7 @@ void dl_program_free(dl_program_t* prog) { } for (int i = 0; i < prog->n_rules; i++) dl_rule_free_exprs(&prog->rules[i]); + if (prog->first_err) ray_error_free(prog->first_err); ray_free(dl_prog_block(prog)); } @@ -96,6 +109,19 @@ static int64_t dl_col_sym(const char* rel_name, int col_idx) { return ray_sym_intern(buf, strlen(buf)); } +/* Best-effort borrow of the first `n` plain columns of `tbl` into cols[] + * (one fetch per call, for loops that would otherwise fetch per row). An + * absent column or one that fails to materialize leaves NULL (the failure + * stays cached in the slot); callers treat NULL as a missing column. */ +static void dl_cols_borrow(ray_t* tbl, int64_t n, ray_t** cols) { + for (int64_t c = 0; c < n; c++) { + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); col = NULL; } + cols[c] = col; + } +} + + int dl_add_edb(dl_program_t* prog, const char* name, ray_t* table, int arity) { if (!prog || !name || !table || prog->n_rels >= DL_MAX_RELS) return -1; @@ -123,7 +149,7 @@ int dl_add_edb(dl_program_t* prog, const char* name, ray_t* table, int arity) { ray_t* new_tbl = ray_table_new(arity); for (int c = 0; c < arity; c++) { - ray_t* col = ray_table_get_col_idx(table, c); + ray_t* col = ray_table_slot_idx(table, c); if (!col) { ray_release(new_tbl); return -1; } new_tbl = ray_table_add_col(new_tbl, rel->col_names[c], col); if (RAY_IS_ERR(new_tbl)) return -1; @@ -188,8 +214,8 @@ static void dl_idb_align_head_const_types(dl_program_t* prog, const dl_rule_t* r bool any_change = false; int8_t desired[DL_MAX_ARITY]; for (int c = 0; c < rel->arity; c++) { - ray_t* col = ray_table_get_col_idx(rel->table, c); - int8_t cur = col ? col->type : RAY_I64; + ray_col_meta_t m; + int8_t cur = ray_table_col_meta_idx(rel->table, c, &m) ? m.type : RAY_I64; int8_t want = rule->head_const_types[c]; if (want == 0) { desired[c] = cur; @@ -760,8 +786,9 @@ static ray_t* dl_eval_expr(dl_expr_t* expr, ray_t* accum, } case DL_EXPR_VAR: { int ci = var_col[expr->var_idx]; - ray_t* src = ray_table_get_col_idx(accum, ci); + ray_t* src = ray_table_col_idx(accum, ci); if (!src) return NULL; + if (RAY_IS_ERR(src)) return src; if (src->type != RAY_I64 && src->type != RAY_F64) return NULL; size_t elem = (src->type == RAY_F64) ? sizeof(double) : sizeof(int64_t); ray_t* dst = ray_vec_new(src->type, nrows); @@ -774,6 +801,14 @@ static ray_t* dl_eval_expr(dl_expr_t* expr, ray_t* accum, case DL_EXPR_BINOP: { ray_t* lv = dl_eval_expr(expr->left, accum, var_col, nrows); ray_t* rv = dl_eval_expr(expr->right, accum, var_col, nrows); + /* A column that failed to materialize comes back as an owned error: + * hand it up (the other operand, if any, is disposed of here). */ + if ((lv && RAY_IS_ERR(lv)) || (rv && RAY_IS_ERR(rv))) { + ray_t* e = (lv && RAY_IS_ERR(lv)) ? lv : rv; + ray_t* o = (e == lv) ? rv : lv; + if (o) { if (RAY_IS_ERR(o)) ray_error_free(o); else ray_release(o); } + return e; + } if (!lv || !rv) { if (lv) ray_release(lv); if (rv) ray_release(rv); @@ -845,7 +880,7 @@ static ray_t* dl_table_add_computed_col(ray_t* tbl, ray_t* new_col, const char* int64_t ncols = ray_table_ncols(tbl); ray_t* out = ray_table_new((int)(ncols + 1)); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); if (col) out = ray_table_add_col(out, ray_table_col_name(tbl, c), col); } @@ -871,8 +906,15 @@ static ray_t* dl_builtin_before(ray_t* tbl, int s_col, int t_col) { int64_t nrows = ray_table_nrows(tbl); int64_t ncols = ray_table_ncols(tbl); - int64_t* sd = (int64_t*)ray_data(ray_table_get_col_idx(tbl, s_col)); - int64_t* t_data = (int64_t*)ray_data(ray_table_get_col_idx(tbl, t_col)); + ray_t* s_vec = ray_table_col_idx(tbl, s_col); + ray_t* t_vec = ray_table_col_idx(tbl, t_col); + if (s_vec && RAY_IS_ERR(s_vec)) { + if (t_vec && RAY_IS_ERR(t_vec)) ray_error_free(t_vec); + return s_vec; + } + if (t_vec && RAY_IS_ERR(t_vec)) return t_vec; + int64_t* sd = (int64_t*)ray_data(s_vec); + int64_t* t_data = (int64_t*)ray_data(t_vec); int64_t count = 0; for (int64_t r = 0; r < nrows; r++) @@ -882,8 +924,9 @@ static ray_t* dl_builtin_before(ray_t* tbl, int s_col, int t_col) { ray_t* out = ray_table_new((int)ncols); for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(tbl, c); + ray_t* src = ray_table_col_idx(tbl, c); if (!src) continue; + if (RAY_IS_ERR(src)) { ray_release(out); return src; } ray_t* dst = ray_vec_new(src->type, count); if (!dst || RAY_IS_ERR(dst)) continue; dst->len = count; @@ -906,8 +949,15 @@ static ray_t* dl_builtin_duration_since(ray_t* tbl, int t1_col, int t2_col, const char* out_name) { if (!tbl || RAY_IS_ERR(tbl)) return tbl; int64_t nrows = ray_table_nrows(tbl); - int64_t* t1 = (int64_t*)ray_data(ray_table_get_col_idx(tbl, t1_col)); - int64_t* t2 = (int64_t*)ray_data(ray_table_get_col_idx(tbl, t2_col)); + ray_t* t1_vec = ray_table_col_idx(tbl, t1_col); + ray_t* t2_vec = ray_table_col_idx(tbl, t2_col); + if (t1_vec && RAY_IS_ERR(t1_vec)) { + if (t2_vec && RAY_IS_ERR(t2_vec)) ray_error_free(t2_vec); + return t1_vec; + } + if (t2_vec && RAY_IS_ERR(t2_vec)) return t2_vec; + int64_t* t1 = (int64_t*)ray_data(t1_vec); + int64_t* t2 = (int64_t*)ray_data(t2_vec); ray_t* col = ray_vec_new(RAY_I64, nrows); if (!col || RAY_IS_ERR(col)) { ray_retain(tbl); return tbl; } @@ -925,7 +975,9 @@ static ray_t* dl_builtin_duration_since(ray_t* tbl, int t1_col, int t2_col, static ray_t* dl_builtin_abs(ray_t* tbl, int x_col, const char* out_name) { if (!tbl || RAY_IS_ERR(tbl)) return tbl; int64_t nrows = ray_table_nrows(tbl); - int64_t* xd = (int64_t*)ray_data(ray_table_get_col_idx(tbl, x_col)); + ray_t* x_vec = ray_table_col_idx(tbl, x_col); + if (x_vec && RAY_IS_ERR(x_vec)) return x_vec; + int64_t* xd = (int64_t*)ray_data(x_vec); ray_t* col = ray_vec_new(RAY_I64, nrows); if (!col || RAY_IS_ERR(col)) { ray_retain(tbl); return tbl; } @@ -950,9 +1002,9 @@ static ray_t* dl_join_tables(ray_t* left, ray_t* right, int64_t rnc = ray_table_ncols(right); ray_t* empty = ray_table_new((int)(lnc + rnc)); for (int64_t c = 0; c < lnc; c++) { - ray_t* col = ray_table_get_col_idx(left, c); - if (!col) continue; - ray_t* ec = ray_vec_new(col->type, 0); + ray_col_meta_t m; + if (!ray_table_col_meta_idx(left, c, &m)) continue; + ray_t* ec = ray_vec_new(m.type, 0); if (ec && !RAY_IS_ERR(ec)) { empty = ray_table_add_col(empty, ray_table_col_name(left, c), ec); ray_release(ec); @@ -970,7 +1022,7 @@ static ray_t* dl_join_tables(ray_t* left, ray_t* right, int64_t rnc = ray_table_ncols(right); ray_t* ltbl = ray_table_new((int)lnc); for (int64_t c = 0; c < lnc; c++) { - ray_t* col = ray_table_get_col_idx(left, c); + ray_t* col = ray_table_slot_idx(left, c); if (!col) continue; char name[32]; snprintf(name, sizeof(name), "L%d", (int)c); int64_t sym = ray_sym_intern(name, strlen(name)); @@ -978,7 +1030,7 @@ static ray_t* dl_join_tables(ray_t* left, ray_t* right, } ray_t* rtbl = ray_table_new((int)rnc); for (int64_t c = 0; c < rnc; c++) { - ray_t* col = ray_table_get_col_idx(right, c); + ray_t* col = ray_table_slot_idx(right, c); if (!col) continue; char name[32]; snprintf(name, sizeof(name), "R%d", (int)c); int64_t sym = ray_sym_intern(name, strlen(name)); @@ -1023,14 +1075,14 @@ static ray_t* dl_antijoin_tables(ray_t* left, ray_t* right, int64_t rnc = ray_table_ncols(right); ray_t* ltbl = ray_table_new((int)lnc); for (int64_t c = 0; c < lnc; c++) { - ray_t* col = ray_table_get_col_idx(left, c); + ray_t* col = ray_table_slot_idx(left, c); if (!col) continue; char name[32]; snprintf(name, sizeof(name), "L%d", (int)c); ltbl = ray_table_add_col(ltbl, ray_sym_intern(name, strlen(name)), col); } ray_t* rtbl = ray_table_new((int)rnc); for (int64_t c = 0; c < rnc; c++) { - ray_t* col = ray_table_get_col_idx(right, c); + ray_t* col = ray_table_slot_idx(right, c); if (!col) continue; char name[32]; snprintf(name, sizeof(name), "R%d", (int)c); rtbl = ray_table_add_col(rtbl, ray_sym_intern(name, strlen(name)), col); @@ -1143,7 +1195,8 @@ static ray_t* dl_table_take_mask(ray_t* tbl, const uint8_t* keep, int64_t count) if (!out) return ray_error("memory", "dl_table_take_mask: table_new"); if (RAY_IS_ERR(out)) return out; for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(tbl, c); + ray_t* src = ray_table_col_idx(tbl, c); + if (src && RAY_IS_ERR(src)) { ray_release(out); return src; } if (!src) { ray_release(out); return ray_error("domain", "dl_table_take_mask: missing source column"); } ray_t* dst = (src->type == RAY_SYM) ? ray_sym_vec_new(src->attrs & RAY_SYM_W_MASK, count) @@ -1207,7 +1260,8 @@ static ray_t* dl_filter_eq(ray_t* tbl, int col_idx, int64_t value, if (!tbl || RAY_IS_ERR(tbl)) { if (tbl) ray_retain(tbl); return tbl; } if (ray_table_nrows(tbl) == 0) { ray_retain(tbl); return tbl; } - ray_t* col = ray_table_get_col_idx(tbl, col_idx); + ray_t* col = ray_table_col_idx(tbl, col_idx); + if (col && RAY_IS_ERR(col)) return col; if (!col) { ray_retain(tbl); return tbl; } /* Non-numeric, non-sym keys: not supported by this filter — raise a * type error rather than silently passing every row through. */ @@ -1265,8 +1319,13 @@ static ray_t* dl_filter_col_eq(ray_t* tbl, int c1, int c2) { if (!tbl || RAY_IS_ERR(tbl)) { if (tbl) ray_retain(tbl); return tbl; } int64_t nrows = ray_table_nrows(tbl); if (nrows == 0) { ray_retain(tbl); return tbl; } - ray_t* a = ray_table_get_col_idx(tbl, c1); - ray_t* b = ray_table_get_col_idx(tbl, c2); + ray_t* a = ray_table_col_idx(tbl, c1); + ray_t* b = ray_table_col_idx(tbl, c2); + if ((a && RAY_IS_ERR(a)) || (b && RAY_IS_ERR(b))) { + ray_t* e = (a && RAY_IS_ERR(a)) ? a : b; + if (e == a && b && RAY_IS_ERR(b)) ray_error_free(b); + return e; + } if (!a || !b) return ray_error("domain", "datalog: repeated-variable filter on missing column"); if ((a->type != RAY_I64 && a->type != RAY_SYM) || (b->type != RAY_I64 && b->type != RAY_SYM)) return ray_error("type", "datalog: repeated variable over unsupported column type %s", @@ -1311,8 +1370,8 @@ static ray_t* dl_filter_repeated_vars(ray_t* tbl, const dl_body_t* body) { * Correctness note: this must be a real, heap-allocated vec — not a view * onto rule-local scratch — so that the IDB relation table can outlive the * per-iteration scratch that built it. Cross-IDB reads at subsequent - * strata borrow from this column via ray_table_get_col_idx. */ -/* width_template: when type == RAY_SYM, this column is consulted for its + * strata borrow from this column via the table accessors. */ +/* width_template: when type == RAY_SYM, this column's metadata is consulted for its * SYM attrs/width so the broadcast matches the IDB relation's existing * adaptive width (otherwise ray_vec_new would default to W64 and a * later table_union would hit a ray_vec_concat width mismatch). Pass @@ -1320,7 +1379,7 @@ static ray_t* dl_filter_repeated_vars(ray_t* tbl, const dl_body_t* body) { * here rather than a uint8_t hint avoids the W8=0 sentinel ambiguity * of an "a zero hint means default" convention. */ static ray_t* dl_broadcast_const_col(int64_t nrows, int8_t type, int64_t val, - const ray_t* width_template) { + const ray_col_meta_t* width_template) { if (type != RAY_I64 && type != RAY_SYM && type != RAY_F64) { return ray_error("type", "datalog: broadcast const column expects i64/sym/f64, got %s", ray_type_name(type)); } @@ -1372,18 +1431,20 @@ static ray_t* dl_project(ray_t* tbl, const int* col_indices, int n_out, for (int c = 0; c < n_out; c++) { int src_idx = col_indices[c]; if (src_idx >= 0) { - ray_t* src = ray_table_get_col_idx(tbl, src_idx); + ray_t* src = ray_table_col_idx(tbl, src_idx); + if (src && RAY_IS_ERR(src)) { ray_release(out); return src; } if (!src) { if (empty_accum && head_rel && head_rel->table) { - ray_t* hcol = ray_table_get_col_idx(head_rel->table, c); - int8_t htype = hcol ? hcol->type : RAY_I64; + ray_col_meta_t hm; + bool hcol = ray_table_col_meta_idx(head_rel->table, c, &hm); + int8_t htype = hcol ? hm.type : RAY_I64; /* For SYM columns, preserve the head-relation's * adaptive-width attrs — ray_vec_new(RAY_SYM, …) would * force W64 and a later table_union onto a narrower * head-rel column would hit the column-count check, * or worse, produce a width-mismatched merge. */ ray_t* ecol = (htype == RAY_SYM && hcol) - ? ray_sym_vec_new(hcol->attrs & RAY_SYM_W_MASK, 0) + ? ray_sym_vec_new(hm.attrs & RAY_SYM_W_MASK, 0) : ray_vec_new(htype, 0); if (!ecol) { ray_release(out); @@ -1466,9 +1527,11 @@ static ray_t* dl_project(ray_t* tbl, const int* col_indices, int n_out, * (from a prior aligned rule), match its width so * table_union's ray_vec_concat doesn't reject a W64 vs * narrow mismatch. */ - const ray_t* width_tpl = NULL; - if (ctype == RAY_SYM && head_rel && head_rel->table) - width_tpl = ray_table_get_col_idx(head_rel->table, c); + ray_col_meta_t width_m; + const ray_col_meta_t* width_tpl = NULL; + if (ctype == RAY_SYM && head_rel && head_rel->table && + ray_table_col_meta_idx(head_rel->table, c, &width_m)) + width_tpl = &width_m; ray_t* bcast = dl_broadcast_const_col(nrows, ctype, head_consts[c], width_tpl); if (!bcast || RAY_IS_ERR(bcast)) { ray_release(out); @@ -1542,7 +1605,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(filtered)) { - ray_error_free(filtered); + dl_keep_err(prog, filtered); if (accum) ray_release(accum); prog->eval_err = true; return NULL; @@ -1554,7 +1617,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, body_tbl = dl_filter_repeated_vars(body_tbl, body); if (!body_tbl) { if (accum) ray_release(accum); prog->eval_err = true; return NULL; } if (RAY_IS_ERR(body_tbl)) { - ray_error_free(body_tbl); + dl_keep_err(prog, body_tbl); if (accum) ray_release(accum); prog->eval_err = true; return NULL; @@ -1643,7 +1706,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, ray_t* one_val = ray_vec_new(RAY_I64, 1); if (!one_val) { prog->eval_err = true; return NULL; } if (RAY_IS_ERR(one_val)) { - ray_error_free(one_val); + dl_keep_err(prog, one_val); prog->eval_err = true; return NULL; } @@ -1656,7 +1719,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(accum)) { - ray_error_free(accum); + dl_keep_err(prog, accum); ray_release(one_val); prog->eval_err = true; return NULL; @@ -1672,7 +1735,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(accum_unit)) { - ray_error_free(accum_unit); + dl_keep_err(prog, accum_unit); ray_release(accum); prog->eval_err = true; return NULL; @@ -1711,7 +1774,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(filtered)) { - ray_error_free(filtered); + dl_keep_err(prog, filtered); ray_release(accum); prog->eval_err = true; return NULL; @@ -1723,7 +1786,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, neg_tbl = dl_filter_repeated_vars(neg_tbl, body); if (!neg_tbl) { ray_release(accum); prog->eval_err = true; return NULL; } if (RAY_IS_ERR(neg_tbl)) { - ray_error_free(neg_tbl); + dl_keep_err(prog, neg_tbl); ray_release(accum); prog->eval_err = true; return NULL; @@ -1769,7 +1832,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(new_col)) { - ray_error_free(new_col); + dl_keep_err(prog, new_col); ray_release(accum); prog->eval_err = true; return NULL; @@ -1783,7 +1846,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, ray_release(accum); if (!new_accum) { prog->eval_err = true; return NULL; } if (RAY_IS_ERR(new_accum)) { - ray_error_free(new_accum); + dl_keep_err(prog, new_accum); prog->eval_err = true; return NULL; } @@ -1923,7 +1986,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(group_tbl)) { - ray_error_free(group_tbl); + dl_keep_err(prog, group_tbl); ray_release(accum); prog->eval_err = true; return NULL; @@ -1995,11 +2058,11 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, * correct result type. */ bool is_float = is_avg; if (need_value_col) { - ray_t* vc0 = ray_table_get_col_idx(src_table, body->agg_value_col); - if (vc0) { - if (vc0->type == RAY_F64) { + ray_col_meta_t vc0; + if (ray_table_col_meta_idx(src_table, body->agg_value_col, &vc0)) { + if (vc0.type == RAY_F64) { is_float = true; - } else if (vc0->type != RAY_I64) { + } else if (vc0.type != RAY_I64) { /* Non-numeric source: reject regardless of row count. */ ray_release(accum); prog->eval_err = true; @@ -2017,7 +2080,14 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, case DL_AGG_AVG: if (src_nrows > 0) { ray_t* val_col = - ray_table_get_col_idx(src_table, body->agg_value_col); + ray_table_col_idx(src_table, body->agg_value_col); + if (val_col && RAY_IS_ERR(val_col)) { + /* the failure stays cached in the slot */ + dl_keep_err(prog, val_col); + ray_release(accum); + prog->eval_err = true; + return NULL; + } if (!val_col) { ray_release(accum); return NULL; @@ -2097,7 +2167,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(new_col)) { - ray_error_free(new_col); + dl_keep_err(prog, new_col); ray_release(accum); prog->eval_err = true; return NULL; @@ -2131,6 +2201,11 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, int t_col = var_col[body->vars[2]]; ray_t* filtered = dl_builtin_before(accum, s_col, t_col); ray_release(accum); + if (!filtered || RAY_IS_ERR(filtered)) { + if (filtered) dl_keep_err(prog, filtered); + prog->eval_err = true; + return NULL; + } accum = filtered; break; } @@ -2143,6 +2218,11 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, snprintf(colname, sizeof(colname), "_d%d", d_var); ray_t* result = dl_builtin_duration_since(accum, t1_col, t2_col, colname); ray_release(accum); + if (!result || RAY_IS_ERR(result)) { + if (result) dl_keep_err(prog, result); + prog->eval_err = true; + return NULL; + } accum = result; var_bound[d_var] = true; var_col[d_var] = new_idx; @@ -2156,6 +2236,11 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, snprintf(colname, sizeof(colname), "_abs%d", y_var); ray_t* result = dl_builtin_abs(accum, x_col, colname); ray_release(accum); + if (!result || RAY_IS_ERR(result)) { + if (result) dl_keep_err(prog, result); + prog->eval_err = true; + return NULL; + } accum = result; var_bound[y_var] = true; var_col[y_var] = new_idx; @@ -2184,7 +2269,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(lhs_evaled)) { - ray_error_free(lhs_evaled); + dl_keep_err(prog, lhs_evaled); prog->eval_err = true; ray_release(accum); return NULL; @@ -2192,8 +2277,9 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, lhs_src = lhs_evaled; } else { int lhs_col = var_col[body->cmp_lhs]; - lhs_src = ray_table_get_col_idx(accum, lhs_col); - if (!lhs_src) { + lhs_src = ray_table_col_idx(accum, lhs_col); + if (!lhs_src || RAY_IS_ERR(lhs_src)) { + if (lhs_src) dl_keep_err(prog, lhs_src); prog->eval_err = true; ray_release(accum); return NULL; @@ -2209,7 +2295,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(rhs_evaled)) { - ray_error_free(rhs_evaled); + dl_keep_err(prog, rhs_evaled); if (lhs_evaled) ray_release(lhs_evaled); prog->eval_err = true; ray_release(accum); @@ -2218,8 +2304,9 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, rhs_src = rhs_evaled; } else if (body->cmp_rhs != DL_CONST) { int rhs_col = var_col[body->cmp_rhs]; - rhs_src = ray_table_get_col_idx(accum, rhs_col); - if (!rhs_src) { + rhs_src = ray_table_col_idx(accum, rhs_col); + if (!rhs_src || RAY_IS_ERR(rhs_src)) { + if (rhs_src) dl_keep_err(prog, rhs_src); if (lhs_evaled) ray_release(lhs_evaled); prog->eval_err = true; ray_release(accum); @@ -2318,15 +2405,16 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, int64_t ncols = ray_table_ncols(accum); ray_t* out = ray_table_new((int)ncols); if (!out || RAY_IS_ERR(out)) { - if (out && RAY_IS_ERR(out)) ray_error_free(out); + if (out && RAY_IS_ERR(out)) dl_keep_err(prog, out); ray_free(mask_block); ray_release(accum); prog->eval_err = true; return NULL; } for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(accum, c); - if (!src) { + ray_t* src = ray_table_col_idx(accum, c); + if (!src || RAY_IS_ERR(src)) { + if (src) dl_keep_err(prog, src); ray_release(out); ray_free(mask_block); ray_release(accum); prog->eval_err = true; @@ -2342,7 +2430,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(dst)) { - ray_error_free(dst); + dl_keep_err(prog, dst); ray_release(out); ray_free(mask_block); ray_release(accum); prog->eval_err = true; @@ -2370,7 +2458,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, return NULL; } if (RAY_IS_ERR(next)) { - ray_error_free(next); + dl_keep_err(prog, next); ray_release(out); ray_free(mask_block); ray_release(accum); prog->eval_err = true; @@ -2424,7 +2512,7 @@ ray_op_t* dl_compile_rule(dl_program_t* prog, dl_rule_t* rule, * output via the const_table/execute chain. */ if (!projected) return NULL; if (RAY_IS_ERR(projected)) { - ray_error_free(projected); + dl_keep_err(prog, projected); prog->eval_err = true; return NULL; } @@ -2464,7 +2552,7 @@ static ray_t* table_rename_cols(ray_t* tbl, dl_rel_t* target_rel) { /* Build new table with correct column names sharing the same column data */ ray_t* out = ray_table_new(arity); for (int c = 0; c < arity; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); if (col) out = ray_table_add_col(out, target_rel->col_names[c], col); } @@ -2477,7 +2565,7 @@ static ray_t* canonicalize(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); ray_t* out = ray_table_new(nc); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); if (!col) continue; char buf[16]; snprintf(buf, sizeof(buf), "c%d", (int)c); @@ -2493,7 +2581,7 @@ static ray_t* restore_names(ray_t* tbl, ray_t* src) { int64_t nc = ray_table_ncols(tbl); ray_t* out = ray_table_new(nc); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); if (col) out = ray_table_add_col(out, ray_table_col_name(src, c), col); } @@ -2543,8 +2631,14 @@ static ray_t* table_union(ray_t* a, ray_t* b) { if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("memory", "table_union: table_new"); for (int64_t c = 0; c < ncols; c++) { - ray_t* col_a = ray_table_get_col_idx(a, c); - ray_t* col_b = ray_table_get_col_idx(b, c); + ray_t* col_a = ray_table_col_idx(a, c); + ray_t* col_b = ray_table_col_idx(b, c); + if ((col_a && RAY_IS_ERR(col_a)) || (col_b && RAY_IS_ERR(col_b))) { + ray_t* e = (col_a && RAY_IS_ERR(col_a)) ? col_a : col_b; + if (e == col_a && col_b && RAY_IS_ERR(col_b)) ray_error_free(col_b); + ray_release(out); + return e; + } if (!col_a || !col_b) { /* Silently dropping a column would produce a schema-incomplete * result that the caller mistakes for a successful union. */ @@ -2717,15 +2811,26 @@ typedef struct { int64_t ncols; } dl_rowset_t; -static bool dl_rowset_init(dl_rowset_t* rs, ray_t* ref) { +static bool dl_rowset_init(dl_program_t* prog, dl_rowset_t* rs, ray_t* ref) { int64_t ncols = ray_table_ncols(ref); int64_t nrows = ray_table_nrows(ref); rs->ncols = ncols; rs->ref_cols = (int64_t**)ray_calloc_raw(sizeof(int64_t*) * (size_t)ncols); if (!rs->ref_cols) return false; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(ref, c); - rs->ref_cols[c] = col ? (int64_t*)ray_data(col) : NULL; + ray_t* col = ray_table_col_idx(ref, c); + if (col && RAY_IS_ERR(col)) { + dl_keep_err(prog, col); /* the rule's marking is skipped */ + ray_free_raw(rs->ref_cols); + rs->ref_cols = NULL; + return false; + } + if (!col) { /* the hash reads every column of every row */ + ray_free_raw(rs->ref_cols); + rs->ref_cols = NULL; + return false; + } + rs->ref_cols[c] = (int64_t*)ray_data(col); } int64_t cap = 16; while (cap < (nrows > 0 ? nrows * 2 : 16)) cap *= 2; @@ -2795,6 +2900,9 @@ static void dl_build_source_prov(dl_program_t* prog, dl_rel_t* rel, int64_t* buf = (int64_t*)ray_data(buf_block); int64_t buf_len = 0; + ray_t* head_cols[DL_MAX_ARITY] = {0}; + dl_cols_borrow(rel->table, rel->arity < DL_MAX_ARITY ? rel->arity : DL_MAX_ARITY, head_cols); + for (int64_t row = 0; row < nrows; row++) { off[row] = buf_len; if (pd[row] < 0) continue; @@ -2809,7 +2917,7 @@ static void dl_build_source_prov(dl_program_t* prog, dl_rel_t* rel, for (int h = 0; h < rule->head_arity; h++) { int v = rule->head_vars[h]; if (v == DL_CONST) continue; - ray_t* col = ray_table_get_col_idx(rel->table, h); + ray_t* col = h < DL_MAX_ARITY ? head_cols[h] : NULL; if (!col) continue; var_vals[v] = ((int64_t*)ray_data(col))[row]; var_set[v] = true; @@ -2824,11 +2932,13 @@ static void dl_build_source_prov(dl_program_t* prog, dl_rel_t* rel, if (bri < 0) continue; dl_rel_t* brel = &prog->rels[bri]; int64_t bnrows = ray_table_nrows(brel->table); + ray_t* bcols[DL_MAX_ARITY] = {0}; + dl_cols_borrow(brel->table, body->arity < DL_MAX_ARITY ? body->arity : DL_MAX_ARITY, bcols); for (int64_t br = 0; br < bnrows; br++) { bool match = true; for (int c = 0; c < body->arity; c++) { - ray_t* bcol = ray_table_get_col_idx(brel->table, c); + ray_t* bcol = c < DL_MAX_ARITY ? bcols[c] : NULL; if (!bcol) { match = false; break; } int v = body->vars[c]; if (v == DL_CONST) { @@ -2935,21 +3045,28 @@ static void dl_build_provenance(dl_program_t* prog) { * hashset over `derived` once and probe per row of rel — * was O(nrows × derived_rows × ncols), now O(nrows + derived_rows). */ dl_rowset_t rs; - if (dl_rowset_init(&rs, derived)) { + if (dl_rowset_init(prog, &rs, derived)) { int64_t ncols_t = ray_table_ncols(rel->table); int64_t** tbl_cols = (int64_t**)ray_calloc_raw(sizeof(int64_t*) * (size_t)ncols_t); - if (tbl_cols) { - for (int64_t c = 0; c < ncols_t; c++) { - ray_t* col = ray_table_get_col_idx(rel->table, c); - tbl_cols[c] = col ? (int64_t*)ray_data(col) : NULL; - } + /* every column must be readable: the probe reads each + * row's cell of every column. A column that fails to + * materialize skips this rule's marking and is kept as the + * program's error. */ + bool cols_ok = tbl_cols != NULL; + for (int64_t c = 0; cols_ok && c < ncols_t; c++) { + ray_t* col = ray_table_col_idx(rel->table, c); + if (col && RAY_IS_ERR(col)) { dl_keep_err(prog, col); col = NULL; } + if (!col) cols_ok = false; + else tbl_cols[c] = (int64_t*)ray_data(col); + } + if (cols_ok) { for (int64_t row = 0; row < nrows; row++) { if (pd[row] >= 0) continue; if (dl_rowset_contains(&rs, tbl_cols, row)) pd[row] = r; } - ray_free_raw(tbl_cols); } + ray_free_raw(tbl_cols); dl_rowset_destroy(&rs); } ray_release(derived); @@ -3069,8 +3186,8 @@ int dl_eval(dl_program_t* prog) { * non-i64 columns (e.g. RAY_SYM from head-constant slots). */ prev_tables[rel_idx] = ray_table_new(rel->arity); for (int c = 0; c < rel->arity && c < DL_MAX_ARITY; c++) { - ray_t* src = ray_table_get_col_idx(rel->table, c); - int8_t ctype = src ? src->type : RAY_I64; + ray_col_meta_t sm; + int8_t ctype = ray_table_col_meta_idx(rel->table, c, &sm) ? sm.type : RAY_I64; ray_t* empty_col = ray_vec_new(ctype, 0); if (empty_col && !RAY_IS_ERR(empty_col)) { prev_tables[rel_idx] = ray_table_add_col( @@ -3348,6 +3465,22 @@ ray_t* ray_datoms_fn(ray_t** args, int64_t n) { return tbl; } +/* Borrow the three plain datoms columns (e, a, v) of `db`. Returns NULL, or + * the owned error of the first column that failed to materialize. */ +static ray_t* dl_datoms_cols(ray_t* db, ray_t** e, ray_t** a, ray_t** v) { + *e = ray_table_col_idx(db, 0); + *a = ray_table_col_idx(db, 1); + *v = ray_table_col_idx(db, 2); + ray_t* err = NULL; + ray_t** cols[3] = { e, a, v }; + for (int i = 0; i < 3; i++) { + if (!*cols[i] || !RAY_IS_ERR(*cols[i])) continue; + if (err) ray_error_free(*cols[i]); + else err = *cols[i]; + } + return err; +} + /* (assert-fact db entity attr value) — append a triple to the datoms table */ ray_t* ray_assert_fact_fn(ray_t** args, int64_t n) { if (n != 4) return ray_error("arity", "assert-fact expects 4 arguments: db entity attr value"); @@ -3385,10 +3518,13 @@ ray_t* ray_assert_fact_fn(ray_t** args, int64_t n) { if (RAY_IS_ERR(result)) return result; for (int64_t c = 0; c < ncols; c++) { - ray_t* old_col = ray_table_get_col_idx(db, c); + ray_t* old_col = ray_table_col_idx(db, c); + if (old_col && RAY_IS_ERR(old_col)) { ray_release(result); return old_col; } int64_t col_name = ray_table_col_name(db, c); - /* Clone the column via retain + COW on append */ + /* Clone the column via retain + COW on append. A slot holding an + * encoded column reaches the append with two references (the table's + * cache and ours), so the cached materialization is copied. */ ray_retain(old_col); ray_t* new_col = old_col; @@ -3447,9 +3583,9 @@ ray_t* ray_retract_fact_fn(ray_t** args, int64_t n) { return ray_error("type", "retract-fact: value must be an integer or symbol"); /* Get existing columns */ - ray_t* e_col = ray_table_get_col_idx(db, 0); - ray_t* a_col = ray_table_get_col_idx(db, 1); - ray_t* v_col = ray_table_get_col_idx(db, 2); + ray_t *e_col, *a_col, *v_col; + ray_t* col_err = dl_datoms_cols(db, &e_col, &a_col, &v_col); + if (col_err) return col_err; int64_t nrows = ray_len(e_col); int64_t* e_data = (int64_t*)ray_data(e_col); @@ -3502,9 +3638,9 @@ ray_t* ray_scan_eav_fn(ray_t** args, int64_t n) { if (db->type != RAY_TABLE || ray_table_ncols(db) != 3) return ray_error("type", "scan-eav: first arg must be a datoms table"); - ray_t* e_col = ray_table_get_col_idx(db, 0); - ray_t* a_col = ray_table_get_col_idx(db, 1); - ray_t* v_col = ray_table_get_col_idx(db, 2); + ray_t *e_col, *a_col, *v_col; + ray_t* col_err = dl_datoms_cols(db, &e_col, &a_col, &v_col); + if (col_err) return col_err; int64_t nrows = ray_table_nrows(db); if (n == 2) { @@ -3620,9 +3756,9 @@ ray_t* ray_pull_fn(ray_t** args, int64_t n) { } int64_t entity_id = entity->i64; - ray_t* e_col = ray_table_get_col_idx(db, 0); - ray_t* a_col = ray_table_get_col_idx(db, 1); - ray_t* v_col = ray_table_get_col_idx(db, 2); + ray_t *e_col, *a_col, *v_col; + ray_t* col_err = dl_datoms_cols(db, &e_col, &a_col, &v_col); + if (col_err) return col_err; int64_t nrows = ray_table_nrows(db); const int64_t* e_data = (const int64_t*)ray_data(e_col); @@ -4414,9 +4550,21 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { int64_t nrows_db = ray_table_nrows(db); ray_t* eav_tbl = ray_table_new(3); for (int c = 0; c < 3; c++) { - ray_t* col = ray_table_get_col_idx(db, c); + /* A SYM column is read (converted to I64 ids); any other column + * goes into the EAV table as it is, encoded or not. */ + ray_col_meta_t cm; + if (!ray_table_col_meta_idx(db, c, &cm)) continue; + ray_t* col = (cm.type == RAY_SYM) ? ray_table_col_idx(db, c) + : ray_table_slot_idx(db, c); if (!col) continue; - if (col->type == RAY_SYM) { + if (RAY_IS_ERR(col)) { + ray_release(eav_tbl); + dl_rule_free_exprs(&qrule); + dl_program_free(prog); + ray_release(db); + return col; + } + if (cm.type == RAY_SYM) { /* Convert SYM -> I64. The I64 ids flow into datalog's * runtime-id world (literal compares, joins with parsed * constants), so each cell must be re-expressed as a @@ -4552,8 +4700,18 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { return ray_error("memory", "query: failed to create env-backed EDB table"); } for (int c = 0; c < pred_arity; c++) { - ray_t* col = ray_table_get_col_idx(env_val, c); + ray_col_meta_t cm; + bool have_col = ray_table_col_meta_idx(env_val, c, &cm); + ray_t* col = !have_col ? NULL + : (cm.type == RAY_SYM) ? ray_table_col_idx(env_val, c) + : ray_table_slot_idx(env_val, c); ray_t* next_clean; + if (col && RAY_IS_ERR(col)) { + ray_release(clean); + dl_program_free(prog); + ray_release(db); + return col; + } if (!col) { /* Silently skipping would build `clean` with fewer than * pred_arity columns yet still register it via dl_add_edb @@ -4563,7 +4721,7 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { ray_release(db); return ray_error("schema", "query: env-backed EDB table missing expected column"); } - if (col->type == RAY_SYM) { + if (cm.type == RAY_SYM) { ray_t* i64col = ray_vec_new(RAY_I64, nrows_env); if (!i64col) { ray_release(clean); @@ -4667,10 +4825,15 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { strncpy(prev, p, sizeof(prev) - 1); prev[sizeof(prev) - 1] = '\0'; } + ray_t* first = prog->first_err; + prog->first_err = NULL; dl_program_free(prog); ray_release(db); - if (ray_interrupted()) + if (ray_interrupted()) { + if (first) ray_error_free(first); return ray_error("cancel", "interrupted"); + } + if (first) return first; /* the failing column's own error */ if (prev[0]) { return ray_error("domain", "query: evaluation failed: %s", prev); } @@ -4690,8 +4853,9 @@ ray_t* ray_query_fn(ray_t** args, int64_t n) { int64_t ncols = ray_table_ncols(raw); ray_t* result = ray_table_new(n_find_vars); for (int i = 0; i < n_find_vars && i < (int)ncols; i++) { - ray_t* col = ray_table_get_col_idx(raw, i); + ray_t* col = ray_table_col_idx(raw, i); if (!col) continue; + if (RAY_IS_ERR(col)) { ray_release(result); dl_program_free(prog); ray_release(db); return col; } ray_t* clean = dl_untag_i64_col(col); /* returns retained col when nothing is tagged */ if (!clean || RAY_IS_ERR(clean)) { ray_release(result); dl_program_free(prog); ray_release(db); return clean ? clean : ray_error("memory", "query: untag"); } @@ -4789,6 +4953,7 @@ ray_t* ray_dl_eval_fn(ray_t* x) { int rc = dl_eval(prog); if (rc == 0) return ray_bool(true); if (ray_interrupted()) return ray_error("cancel", "interrupted"); + if (prog->first_err) { ray_t* e = prog->first_err; prog->first_err = NULL; return e; } return ray_error("domain", "dl-eval: evaluation failed"); } @@ -4829,9 +4994,8 @@ ray_t* ray_dl_provenance_fn(ray_t* prog_obj, ray_t* pred_obj) { } /* (dl-free prog) — free a dl-program handle created by (dl-program). - * The handle wraps a raw dl_program_t* with no automatic finalizer, so - * without an explicit free the program block and all relation tables it - * owns leak. On free we clear RAY_ATTR_DLPROG and zero the pointer, so a + * The heap finalizer frees an owning handle on release; this builtin allows + * early release. On free we clear RAY_ATTR_DLPROG and zero the pointer, so a * second call is an idempotent no-op (returns false) rather than a * double-free. A tagged pointer that isn't an i64 is a type error, and a * plain/forged integer (RAY_ATTR_DLPROG absent, non-zero value) is rejected diff --git a/src/ops/datalog.h b/src/ops/datalog.h index 81cce7db8..264aae9ea 100644 --- a/src/ops/datalog.h +++ b/src/ops/datalog.h @@ -220,6 +220,7 @@ typedef struct { int strata_sizes[DL_MAX_STRATA]; /* number of predicates per stratum */ int n_strata; uint32_t flags; /* DL_FLAG_* bitmask */ + ray_t* first_err; /* first owned error behind eval_err, or NULL */ bool eval_err; /* set by compile/eval on unrecoverable failure (distinct from "rule diff --git a/src/ops/dump.c b/src/ops/dump.c index 63cf8f2e1..1c60cd2d3 100644 --- a/src/ops/dump.c +++ b/src/ops/dump.c @@ -289,6 +289,10 @@ static void dump_node(FILE* f, ray_graph_t* g, ray_op_t* node, int depth) { /* agg inputs */ for (uint32_t i = 0; i < ext->n_aggs; i++) dump_node(f, g, op_node(g, ext->agg_ins[i]), depth + 1); + if (ext->agg_ins2) + for (uint32_t i = 0; i < ext->n_aggs; i++) + if (ext->agg_ins2[i] != RAY_OP_NONE) + dump_node(f, g, op_node(g, ext->agg_ins2[i]), depth + 1); } /* Also recurse into standard inputs */ for (uint32_t i = 0; i < node->arity && i < 2; i++) diff --git a/src/ops/exec.c b/src/ops/exec.c index d4f354709..0ec84f7c0 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -22,9 +22,16 @@ */ #include "ops/internal.h" +#include "ops/colgather.h" /* ray_col_gather_slot: the refinement over encoded columns */ +#include "ops/colbind.h" +#include "ops/cdfuse.h" /* ray_cd_bounded_all: count distinct of an encoded scan */ #include "lang/internal.h" /* sym_domain_rep (sym-domain Phase 2) */ #include "lang/format.h" /* ray_type_name (error context) */ #include "ops/rowsel.h" +#include "store/enccol.h" +#include "store/enceval.h" +#include "store/encidx.h" /* ray_enc_idx_kind_has_region */ +#include "table/table.h" #include "ops/fused_group.h" #include "ops/idxop.h" #include "ops/hash.h" @@ -630,7 +637,12 @@ ray_t* broadcast_scalar(ray_t* atom, int64_t nrows) { /* OP_IN worker — process [start, end) of the BOOL output buffer. * Disjoint slices, no synchronization. */ typedef struct { - ray_t* col; + ray_t* col; /* NULL for a range-read source (cd set) */ + /* Range-read view: element i of the column is cd[i - cd_base], with SYM + * width class cattrs. NULL for a plain column, read at ray_data(col). */ + const void* cd; + int64_t cd_base; + uint8_t cattrs; const double* svf; const int64_t* svi; int64_t sv_len; @@ -705,47 +717,52 @@ static inline int in_set_has_f(const in_worker_ctx_t* c, double v) { return 0; } -static void exec_in_worker(void* vctx, uint32_t worker_id, - int64_t start, int64_t end) { - (void)worker_id; - in_worker_ctx_t* c = (in_worker_ctx_t*)vctx; +/* The worker body, specialized on `rng` (a range-read view in cd, else + * the plain column): exec_in_worker instantiates it twice, so the plain + * path compiles to loops with no view offset or view null test. */ +RAY_INLINE void exec_in_body(const in_worker_ctx_t* c, int64_t start, int64_t end, + const bool rng) { ray_t* col = c->col; - const void* cd = c->col_is_atom ? NULL : ray_data(col); + const void* cd = c->col_is_atom ? NULL : (rng ? c->cd : ray_data(col)); + const int64_t cd_base = rng ? c->cd_base : 0; int8_t ct = c->ct; - uint8_t cattrs = c->col_is_atom ? 0 : col->attrs; + uint8_t cattrs = c->col_is_atom ? 0 : (rng ? c->cattrs : col->attrs); /* Output index is relative to ob_base so a fused-selection caller can * point ob at a morsel-local scratch (ob_base = morsel start) while the * column is still read at the absolute row index i: element i writes * ob[i - ob_base], which lands at scratch[0..n). Full-vec callers set - * ob_base = 0, leaving the plain ob[i]. */ + * ob_base = 0, leaving the plain ob[i]. A range-read view is indexed + * the same way: element i is cd[i - cd_base]. */ uint8_t* ob = c->ob; int64_t ob_base = c->ob_base; int64_t sv_len = c->sv_len; int negate = c->negate ? 1 : 0; #define IN_READ_I64(dst, idx) do { \ + int64_t _ix = (idx) - cd_base; \ switch (ct) { \ - case RAY_BOOL: case RAY_U8: (dst) = ((const uint8_t*)cd)[idx]; break; \ - case RAY_I16: (dst) = ((const int16_t*)cd)[idx]; break; \ + case RAY_BOOL: case RAY_U8: (dst) = ((const uint8_t*)cd)[_ix]; break; \ + case RAY_I16: (dst) = ((const int16_t*)cd)[_ix]; break; \ case RAY_I32: case RAY_DATE: case RAY_TIME: \ - (dst) = ((const int32_t*)cd)[idx]; break; \ + (dst) = ((const int32_t*)cd)[_ix]; break; \ case RAY_I64: case RAY_TIMESTAMP: \ - (dst) = ((const int64_t*)cd)[idx]; break; \ - case RAY_SYM: (dst) = ray_read_sym(cd, (idx), ct, cattrs); break; \ + (dst) = ((const int64_t*)cd)[_ix]; break; \ + case RAY_SYM: (dst) = ray_read_sym(cd, _ix, ct, cattrs); break; \ default: (dst) = 0; break; \ } \ } while (0) #define IN_READ_F64(dst, idx) do { \ + int64_t _ix = (idx) - cd_base; \ switch (ct) { \ - case RAY_BOOL: case RAY_U8: (dst) = (double)((const uint8_t*)cd)[idx]; break; \ - case RAY_I16: (dst) = (double)((const int16_t*)cd)[idx]; break; \ + case RAY_BOOL: case RAY_U8: (dst) = (double)((const uint8_t*)cd)[_ix]; break; \ + case RAY_I16: (dst) = (double)((const int16_t*)cd)[_ix]; break; \ case RAY_I32: case RAY_DATE: case RAY_TIME: \ - (dst) = (double)((const int32_t*)cd)[idx]; break; \ + (dst) = (double)((const int32_t*)cd)[_ix]; break; \ case RAY_I64: case RAY_TIMESTAMP: \ - (dst) = (double)((const int64_t*)cd)[idx]; break; \ - case RAY_F32: (dst) = (double)((const float*)cd)[idx]; break; \ - case RAY_F64: (dst) = ((const double*)cd)[idx]; break; \ + (dst) = (double)((const int64_t*)cd)[_ix]; break; \ + case RAY_F32: (dst) = (double)((const float*)cd)[_ix]; break; \ + case RAY_F64: (dst) = ((const double*)cd)[_ix]; break; \ default: (dst) = 0.0; break; \ } \ } while (0) @@ -754,6 +771,8 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, * the per-element null check is a single ray_vec_is_null call when * nulls are present, or eliminated entirely when they are not. */ bool vec_has_nulls = c->col_has_nulls && !c->col_is_atom; + #define IN_IS_NULL(i) (rng ? ray_raw_is_null(ct, cattrs, cd, (i) - cd_base) \ + : ray_vec_is_null(col, (i))) /* ---- SIMD-friendly fast path ----------------------------------------- * Common case: non-atom fixed-width INTEGER column, integer set (not @@ -775,19 +794,19 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, if (w == RAY_SYM_W8) { const uint8_t* dp = (const uint8_t*)cd; for (int64_t i = start; i < end; i++) - ob[i - ob_base] = (uint8_t)(lut[dp[i]] ^ neg); + ob[i - ob_base] = (uint8_t)(lut[dp[i - cd_base]] ^ neg); } else if (w == RAY_SYM_W16) { const uint16_t* dp = (const uint16_t*)cd; for (int64_t i = start; i < end; i++) - ob[i - ob_base] = (uint8_t)(lut[dp[i]] ^ neg); + ob[i - ob_base] = (uint8_t)(lut[dp[i - cd_base]] ^ neg); } else if (w == RAY_SYM_W32) { const uint32_t* dp = (const uint32_t*)cd; for (int64_t i = start; i < end; i++) - ob[i - ob_base] = (uint8_t)(lut[dp[i]] ^ neg); + ob[i - ob_base] = (uint8_t)(lut[dp[i - cd_base]] ^ neg); } else { const int64_t* dp = (const int64_t*)cd; for (int64_t i = start; i < end; i++) - ob[i - ob_base] = (uint8_t)(lut[dp[i]] ^ neg); + ob[i - ob_base] = (uint8_t)(lut[dp[i - cd_base]] ^ neg); } return; } @@ -814,7 +833,7 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, if ((HASNULL) && vec_has_nulls) { \ CTYPE sent = (CTYPE)(SENT); \ for (int64_t i = start; i < end; i++) { \ - CTYPE v = dp[i]; \ + CTYPE v = dp[i - cd_base]; \ uint8_t f = (uint8_t)((v==t0)|(v==t1)|(v==t2)|(v==t3)| \ (v==t4)|(v==t5)|(v==t6)|(v==t7)); \ uint8_t isn = (uint8_t)(v == sent); \ @@ -822,7 +841,7 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, } \ } else { \ for (int64_t i = start; i < end; i++) { \ - CTYPE v = dp[i]; \ + CTYPE v = dp[i - cd_base]; \ uint8_t f = (uint8_t)((v==t0)|(v==t1)|(v==t2)|(v==t3)| \ (v==t4)|(v==t5)|(v==t6)|(v==t7)); \ ob[i - ob_base] = (uint8_t)(f ^ neg); \ @@ -843,7 +862,7 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, IN_FAST(int32_t, (sj >= INT32_MIN && sj <= INT32_MAX), NULL_I32, 1); break; - case RAY_I64: case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_I64: case RAY_TIMESTAMP: IN_FAST(int64_t, 1, NULL_I64, 1); /* all i64 fit */ break; default: break; /* SYM / unsupported → generic below */ @@ -857,7 +876,7 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, for (int64_t i = start; i < end; i++) ob[i - ob_base] = 0; } else if (vec_has_nulls) { for (int64_t i = start; i < end; i++) { - if (ray_vec_is_null(col, i)) { ob[i - ob_base] = 0; continue; } + if (IN_IS_NULL(i)) { ob[i - ob_base] = 0; continue; } double cv; if (c->col_is_atom) cv = (ct == RAY_F64) ? col->f64 : (double)col->i64; else IN_READ_F64(cv, i); @@ -876,7 +895,7 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, for (int64_t i = start; i < end; i++) ob[i - ob_base] = 0; } else if (vec_has_nulls) { for (int64_t i = start; i < end; i++) { - if (ray_vec_is_null(col, i)) { ob[i - ob_base] = 0; continue; } + if (IN_IS_NULL(i)) { ob[i - ob_base] = 0; continue; } int64_t cv; if (c->col_is_atom) cv = col->i64; else IN_READ_I64(cv, i); @@ -893,6 +912,22 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, } #undef IN_READ_I64 #undef IN_READ_F64 + #undef IN_IS_NULL +} + +/* The range-read instance, out of line so the plain instance keeps the + * worker's own code layout. */ +static __attribute__((noinline)) void exec_in_worker_rng(const in_worker_ctx_t* c, + int64_t start, int64_t end) { + exec_in_body(c, start, end, true); +} + +static void exec_in_worker(void* vctx, uint32_t worker_id, + int64_t start, int64_t end) { + (void)worker_id; + const in_worker_ctx_t* c = (const in_worker_ctx_t*)vctx; + if (c->cd) { exec_in_worker_rng(c, start, end); return; } + exec_in_body(c, start, end, false); } /* ============================================================================ @@ -928,18 +963,23 @@ static void exec_in_worker(void* vctx, uint32_t worker_id, * the bool path can surface nyi/oom while the fused path falls back. */ typedef enum { IN_CTX_UNSUPPORTED = 0, IN_CTX_OK = 1, IN_CTX_OOM = 2 } in_ctx_status_t; -static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, - double* svf_stack, int64_t* svi_stack, - in_worker_ctx_t* out_ctx, - ray_t** sv_hdr_out, - ray_t** lut_hdr_out) { +/* The body shared by in_build_worker_ctx (a column vector or atom) and + * in_build_worker_ctx_meta (a bound source read by range), over the + * column's description: `atom` is the column when it is an atom (else + * NULL), ct its element type, may_null its null flag, and dom (SYM) the + * domain its raw ids resolve over. out_ctx->col is left NULL. */ +static in_ctx_status_t in_build_ctx_core(ray_t* atom, int8_t ct, bool may_null, + struct ray_sym_domain_s* dom, + ray_t* set, bool negate, + double* svf_stack, int64_t* svi_stack, + in_worker_ctx_t* out_ctx, + ray_t** sv_hdr_out, + ray_t** lut_hdr_out) { *sv_hdr_out = NULL; *lut_hdr_out = NULL; int64_t set_len = ray_is_atom(set) ? 1 : set->len; - int8_t ct = ray_is_atom(col) ? (int8_t)(-col->type) : col->type; int8_t st = ray_is_atom(set) ? (int8_t)(-set->type) : set->type; - if (RAY_IS_PARTED(ct)) ct = (int8_t)RAY_PARTED_BASETYPE(ct); if (RAY_IS_PARTED(st)) st = (int8_t)RAY_PARTED_BASETYPE(st); if (ct == RAY_STR || st == RAY_STR) return IN_CTX_UNSUPPORTED; @@ -988,8 +1028,8 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, * context. Also skip null elements when building the probe * buffer so a non-null col row doesn't accidentally match the * sentinel value of a null set element. */ - bool col_has_nulls = !ray_is_atom(col) && ray_vec_may_have_nulls(col); - bool col_atom_null = ray_is_atom(col) && RAY_ATOM_IS_NULL(col); + bool col_has_nulls = !atom && may_null; + bool col_atom_null = atom && RAY_ATOM_IS_NULL(atom); bool set_has_nulls = !ray_is_atom(set) && ray_vec_may_have_nulls(set); #define READ_I64(dst, vec, type, idx) do { \ @@ -1046,10 +1086,8 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, struct ray_sym_domain_s* in_col_dom = NULL; /* non-NULL ⇒ translate */ struct ray_sym_domain_s* in_set_dom = NULL; if (col_class == 2 && set_class == 2 && set_len > 0) { - ray_t* col_rep = ray_is_atom(col) ? NULL : sym_domain_rep(col); ray_t* set_rep = ray_is_atom(set) ? NULL : sym_domain_rep(set); - struct ray_sym_domain_s* cd = - col_rep ? ray_sym_vec_domain(col_rep) : ray_sym_runtime_domain(); + struct ray_sym_domain_s* cd = (!atom && dom) ? dom : ray_sym_runtime_domain(); struct ray_sym_domain_s* sd = set_rep ? ray_sym_vec_domain(set_rep) : ray_sym_runtime_domain(); if (cd != sd) { in_col_dom = cd; in_set_dom = sd; } @@ -1109,10 +1147,8 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, * verdict is one flag per domain position). O(D) build, then the * worker does one byte load per row regardless of set size. */ const uint8_t* symlut = NULL; - if (!ray_is_atom(col) && col_class == 2 && !use_double && sv_len > 0) { - ray_t* col_rep2 = sym_domain_rep(col); - struct ray_sym_domain_s* cdom = col_rep2 - ? ray_sym_vec_domain(col_rep2) : ray_sym_runtime_domain(); + if (!atom && col_class == 2 && !use_double && sv_len > 0) { + struct ray_sym_domain_s* cdom = dom ? dom : ray_sym_runtime_domain(); int64_t d = ray_sym_domain_count(cdom); if (d > 0 && d <= (int64_t)1 << 22) { ray_t* lh = ray_alloc(d); @@ -1138,7 +1174,7 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, const uint64_t* htf = NULL; int64_t ht_mask = 0; bool ht_has_min = false; - if (!ray_is_atom(col) && !symlut && sv_len > IN_SIMD_SET) { + if (!atom && !symlut && sv_len > IN_SIMD_SET) { int64_t cap = 16; while (cap < sv_len * 2) cap <<= 1; ray_t* hh = ray_alloc((size_t)cap * sizeof(int64_t)); @@ -1172,14 +1208,14 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, } *out_ctx = (in_worker_ctx_t){ - .col = col, + .col = atom, .svf = svf, .svi = svi, .sv_len = sv_len, .symlut = symlut, .hti = hti, .htf = htf, .ht_mask = ht_mask, .ht_has_min = ht_has_min, .ob = NULL, .ob_base = 0, .ct = ct, .col_has_nulls = col_has_nulls, .col_atom_null = col_atom_null, - .col_is_atom = ray_is_atom(col), + .col_is_atom = atom != NULL, .use_double = use_double, .negate = negate, }; @@ -1187,6 +1223,45 @@ static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, return IN_CTX_OK; } +static in_ctx_status_t in_build_worker_ctx(ray_t* col, ray_t* set, bool negate, + double* svf_stack, int64_t* svi_stack, + in_worker_ctx_t* out_ctx, + ray_t** sv_hdr_out, + ray_t** lut_hdr_out) { + bool atom = ray_is_atom(col); + int8_t ct = atom ? (int8_t)(-col->type) : col->type; + if (RAY_IS_PARTED(ct)) ct = (int8_t)RAY_PARTED_BASETYPE(ct); + struct ray_sym_domain_s* dom = NULL; + if (!atom && ct == RAY_SYM) { + ray_t* rep = sym_domain_rep(col); + dom = rep ? ray_sym_vec_domain(rep) : ray_sym_runtime_domain(); + } + in_ctx_status_t st = in_build_ctx_core(atom ? col : NULL, ct, + !atom && ray_vec_may_have_nulls(col), dom, + set, negate, svf_stack, svi_stack, + out_ctx, sv_hdr_out, lut_hdr_out); + if (st == IN_CTX_OK) out_ctx->col = col; + return st; +} + +/* The context for a bound source read by range (exec_in_to_selection's + * generation-2 path): the column described by its type, persisted attrs, + * null flag and SYM domain. ctx.col stays NULL; each fill sets cd / + * cd_base / cattrs to its range view. */ +static in_ctx_status_t in_build_worker_ctx_meta(int8_t ct, uint8_t attrs, bool may_null, + struct ray_sym_domain_s* dom, + ray_t* set, bool negate, + double* svf_stack, int64_t* svi_stack, + in_worker_ctx_t* out_ctx, + ray_t** sv_hdr_out, + ray_t** lut_hdr_out) { + in_ctx_status_t st = in_build_ctx_core(NULL, ct, may_null, dom, set, negate, + svf_stack, svi_stack, out_ctx, + sv_hdr_out, lut_hdr_out); + if (st == IN_CTX_OK) out_ctx->cattrs = attrs; + return st; +} + /* Public entry for the typed membership kernel — the eval-level `in` * routes typed vec/set shapes here so a bare (in vec set) gets the same * verdict-LUT / SIMD / pool-parallel treatment as the fused WHERE path @@ -1229,7 +1304,30 @@ ray_t* ray_in_vec_exec(ray_t* col, ray_t* set, bool negate) { return out; } -static ray_t* flatten_parted_col(ray_t* col); +static ray_t* flatten_parted_col(ray_t* col, ray_t* tbl); +static ray_t* flatten_parted_table(ray_t* tbl, ray_t* counts_src); +static int64_t parted_table_rows(ray_t* tbl, ray_t* counts_src, ray_t** err_out); +static ray_t* parted_result_validate(ray_t* tbl, ray_t* counts_src); + +/* Debug builds check that a parted column flattened out of a table has the + * table's row count, its MAPCOMMON total (#724: a short flat column was read + * past its end). Release builds compile the check out. */ +#if defined(DEBUG) && !defined(NDEBUG) +#include +static int64_t dbg_mapcommon_rows(ray_t* tbl) { + if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return -1; + for (int64_t c = 0; c < ray_table_ncols(tbl); c++) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && m.type == RAY_MAPCOMMON) return m.len; + } + return -1; +} +#define PARTED_FLAT_DCHECK(tbl, flat) \ + assert(!(flat) || RAY_IS_ERR(flat) || dbg_mapcommon_rows(tbl) < 0 || \ + (flat)->len == dbg_mapcommon_rows(tbl)) +#else +#define PARTED_FLAT_DCHECK(tbl, flat) ((void)0) +#endif /* General membership fallback: the typed `in` kernel bails on guid operands * (16-byte cells it can't compare) and on string columns (variable-length @@ -1237,11 +1335,12 @@ static ray_t* flatten_parted_col(ray_t* col); * guid- and string-aware hashset. `col` is a materialized column vector, so * ray_in_fn returns a fresh RAY_BOOL vector we own and may invert in place * for not-in. */ -static ray_t* exec_in_general_fallback(ray_t* col, ray_t* set, bool negate) { +static ray_t* exec_in_general_fallback(ray_t* col, ray_t* set, bool negate, + ray_t* tbl) { ray_t* input = col; bool owns_input = false; if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) { - input = flatten_parted_col(col); + input = flatten_parted_col(col, tbl); if (!input || RAY_IS_ERR(input)) return input ? input : ray_error("oom", NULL); owns_input = true; } @@ -1353,7 +1452,7 @@ static ray_t* exec_in(ray_graph_t* g, ray_op_t* op, ray_t* col, ray_t* set) { &in_ctx, &sv_hdr, &lut_hdr); if (st == IN_CTX_UNSUPPORTED) { if (in_has_general_fallback(col, set)) - return exec_in_general_fallback(col, set, negate); + return exec_in_general_fallback(col, set, negate, g ? g->table : NULL); return ray_error("nyi", "OP_IN on RAY_STR not yet implemented"); } if (st == IN_CTX_OOM) @@ -1380,20 +1479,549 @@ static ray_t* exec_in(ray_graph_t* g, ray_op_t* op, ray_t* col, ray_t* set) { return out; } -/* Fused `in`/`not-in` → row selection. Decodes a root OP_IN/OP_NOT_IN of the - * shape (SCAN flat-col) IN (CONST set) against g->table, builds the same probe - * buffer + worker context as exec_in, then drives the per-task rowsel builders - * — each morsel runs exec_in_worker into a morsel-local scratch (ob_base = - * morsel start) and streams the verdict via rowsel_emit_segment. Bit-identical - * to exec_in's bool output (null rows → 0 → not-selected); only the sink - * differs. Returns NULL+all_pass=0 for any unsupported shape so the caller - * falls back to exec_node→ray_rowsel_from_pred unchanged. */ -static int idx_filter_in_decode(ray_graph_t* g, ray_op_t* pred_op, - ray_t** out_col, ray_t** out_set_lit); +/* Fused `in`/`not-in` → row selection (exec_in_to_selection). Binds the + * column of a root OP_IN/OP_NOT_IN of the shape (SCAN flat-col) IN (CONST + * set) against g->table (a generation-2 column is read by range, never + * decoded whole), builds the same probe buffer + worker context as exec_in, + * then drives the per-task rowsel builders — each morsel runs exec_in_worker + * into a morsel-local scratch (ob_base = morsel start) and streams the + * verdict via rowsel_emit_segment. Bit-identical to exec_in's bool output + * (null rows → 0 → not-selected); only the sink differs. Returns + * NULL+all_pass=0 for any unsupported shape so the caller falls back to + * exec_node→ray_rowsel_from_pred unchanged. */ +static int idx_filter_in_decode(ray_graph_t* g, ray_op_t* pred_op, unsigned want, + ray_t** out_col, ray_t** out_set_lit, ray_col_meta_t* out_meta); + +/* What a filter-index consult needs from a column, decided from metadata so + * an encoded column without it is never decoded to find that out: any index + * (IDXW_INDEX), a sorted attribute (IDXW_SORTED), or neither (the caller + * reads the column's values). */ +enum { IDXW_NONE = 0, IDXW_INDEX = 1, IDXW_SORTED = 2 }; + +static bool idx_want_ok(const ray_col_meta_t* m, unsigned want) { + if (!want) return true; + return ((want & IDXW_INDEX) && m->index_kind != RAY_IDX_NONE) || + ((want & IDXW_SORTED) && (m->attrs & RAY_ATTR_SORTED)); +} + +/* Metadata admits the lazy in-memory hash (ray_idx_lazy_hash): an 8-byte + * integer or timestamp column, no nulls, a chunk zone the hash may replace. The column's own + * shape test runs on the decoded vector after this. */ +static bool idx_lazy_meta_ok(const ray_col_meta_t* m) { + if (m->index_kind != RAY_IDX_CHUNK_ZONE) return false; + /* the lazy cost test admits 8-byte columns only */ + if (m->type != RAY_I64 && m->type != RAY_TIMESTAMP) return false; + return m->null_count >= 0 ? m->null_count == 0 : !(m->attrs & RAY_ATTR_HAS_NULLS); +} + +/* The (kind, op, type) pairs the generation-0 single-compare block consults + * a persisted region index for, decided from metadata (cmp_op, key_i and + * is_float as idx_filter_decode reconciled them with the column): + * BLOOM EQ, integer key (the definite-absent probe, step 2); + * HASH / PART EQ, integer key, a nonzero SYM key or a column without + * HAS_NULLS (ray_vec_may_have_nulls of the materialization, + * whose attrs are the persisted ones; step 3); + * SORT every compare but NE (the range probe, step 4). + * Any other shape consults no region index on generation 0. */ +static bool idx_enc_cmp_uses_index(const ray_col_meta_t* m, uint16_t cmp_op, int64_t key_i, int is_float) { + switch (m->index_kind) { + case RAY_IDX_BLOOM: return cmp_op == OP_EQ && !is_float; + case RAY_IDX_HASH: + case RAY_IDX_PART: + if (cmp_op != OP_EQ || is_float) return false; + if (m->type == RAY_SYM) return key_i != 0; + return m->type != RAY_STR && !(m->attrs & RAY_ATTR_HAS_NULLS); + case RAY_IDX_SORT: return cmp_op != OP_NE; + default: return false; + } +} + +/* The generation-0 `in` block's region-index pairs: HASH or PART over a + * non-float column (the IN probe, step 5). */ +static bool idx_enc_in_uses_index(const ray_col_meta_t* m) { + return (m->index_kind == RAY_IDX_HASH || m->index_kind == RAY_IDX_PART) && + m->type != RAY_F32 && m->type != RAY_F64; +} + +/* An unpublished generation-2 column is consulted from its directory (P3's + * encoded route) unless the shape uses its recorded region index (`uses`, + * from idx_enc_cmp_uses_index / idx_enc_in_uses_index): then a recorded + * HASH, SORT, BLOOM or PART answers as on generation 0, from the index its + * materialization attaches (the "index an executor chose to use" exception + * of spec "Instrumentation"). Every other shape materializes nothing, and + * a malformed region fails only an index-using query. */ +static bool idx_enc_from_dir(const ray_col_meta_t* m, bool uses) { + return m->enc && !ray_enccol_decoded_peek(m->enc) && + !(uses && ray_enc_idx_kind_has_region(m->index_kind)); +} + +/* Materialize a region-kind generation-2 column for its index (called only + * for a shape that uses it): NULL when the column is plain, published, or + * materialized now; an owned error otherwise (spec "Accessors": an error + * never reads as "no index"). */ +static ray_t* idx_enc_index_ready(ray_graph_t* g, const ray_col_meta_t* m, int64_t sym) { + if (!m->enc || !ray_enc_idx_kind_has_region(m->index_kind) || ray_enccol_decoded_peek(m->enc)) return NULL; + ray_t* c = ray_table_col(g->table, sym); + return (c && RAY_IS_ERR(c)) ? c : NULL; +} + +/* A lazy-hash failure is best effort (the scan answers), except an + * interrupted build: that is the query's cancellation, handed back. */ +static ray_t* idx_lazy_err(ray_t* le) { + if (!le) return NULL; + if (strcmp(ray_err_code(le), "cancel") == 0) return le; + ray_error_free(le); + return NULL; +} + +/* An `in` set that is a point lookup for the lazy hash: an integer-family + * vector no larger than an eighth of the rows (the dense cutoff the hash + * equality probe applies to one key's rows). */ +static bool idx_lazy_set_ok_len(int64_t len, const ray_t* set) { + if (!set || RAY_IS_ERR(set) || ray_is_atom(set)) return false; + switch (set->type) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: break; + default: return false; + } + return set->len <= (len >> 3); +} +static bool idx_lazy_set_ok(const ray_t* col, const ray_t* set) { + return idx_lazy_set_ok_len(col->len, set); +} + +/* The plain column for a decode that declines (the scan fallback re-reads the + * column through the accessors and reports a failure with its message). A + * region-kind generation-2 column's failure never reaches here: the arms + * materialize it first (idx_enc_index_ready) and return that error. */ +static ray_t* idx_decode_col(ray_t* tbl, int64_t sym) { + ray_t* col = ray_table_col(tbl, sym); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); return NULL; } + return col; +} + +/* ---- STR equality / inequality as a selection (P6, spec Path 1) ---- + * + * (== s "c") / (!= s "c") over a generation-2 STR column, single file or + * parted. Byte equality, nulls included: "" is the in-band null, so a "" + * constant selects the null rows under ==, and a null row passes != of a + * non-empty constant. Per segment the constant is looked up once in the + * column's STR_DICT entry (its code, -1 absent, -2 no entry). A vector is + * decided whole when the constant is non-empty and its code lies outside + * the chunk's or the vector's code bounds (membership bounds over the + * non-null rows: "" is never inside them, D4); a STR_DICT vector otherwise + * compares its codes as a view; any other vector, a plain or materialized + * segment and a synthetic all-null one are read by range and compared on + * bytes. A segment recording a persisted DICT (P6b), materialized or not, + * compares its codes by range instead, with no bounds: its constant is + * looked up once in the DICT's entries ("" is an entry like any other, so + * the null rows are selected exactly). */ +typedef struct { + ray_col_src_t src; /* parted: the segment's own source, bound here */ + ray_col_src_t* rs; /* the source its rows are read from by range */ + ray_enccol_t* e; /* single-file encoded, not materialized: codes and bounds; else NULL */ + int64_t code; /* the constant's code in e's entry: >= 0, -1 absent, -2 no entry */ + ray_enccol_t* de; /* single-file encoded with a persisted DICT (materialized or not); else NULL */ + int64_t dcode; /* the constant's DICT code: >= 0, -1 absent (-2, no DICT: de stays NULL) */ + bool bound; +} str_seg_sel_t; + +typedef struct { + str_seg_sel_t* segs; + const int64_t* off; /* segment i: rows [off[i], off[i + 1]) */ + int64_t n_segs; + const char* cs; + uint32_t clen; + bool ne; + const char* cname; /* the column's name (error texts), cname_len bytes */ + int cname_len; + ray_scan_fail_t* fail; + /* an installed selection the result is ANDed with (a later conjunct), or NULL */ + const uint8_t* wflags; + const uint32_t* woff; + const uint16_t* widx; +} str_sel_ctx_t; + +/* Rows [lr, lr + n) of segment s (segment-local rows) into out; false + * with the failure noted under `key` (the rest of out is the caller's). */ +static bool str_seg_fill(const str_sel_ctx_t* x, str_seg_sel_t* s, ray_col_scratch_t* sc, int64_t key, + int64_t lr, int64_t n, uint8_t* out) { + const uint8_t miss = (uint8_t)x->ne; /* a row that does not equal c */ + int64_t at = 0; + while (at < n) { + const int64_t row = lr + at; + uint8_t* o = out + at; + if (s->de) { + /* the persisted DICT (spec path 1, P6b): codes by range, no bounds */ + const int64_t v = row / RAY_ENC_VEC; + int64_t piece = (v + 1) * RAY_ENC_VEC - row; + if (piece > n - at) piece = n - at; + if (s->dcode < 0) { memset(o, miss, (size_t)piece); at += piece; continue; } + const int32_t* cd = NULL; + ray_t* err = ray_enccol_idict_codes(s->de, row, piece, &cd); + if (err) { ray_scan_fail_note(x->fail, key, err); return false; } + const int32_t cc = (int32_t)s->dcode; + for (int64_t k = 0; k < piece; k++) o[k] = (uint8_t)((cd[k] == cc) ^ x->ne); + at += piece; + continue; + } + if (s->e) { + const int64_t v = row / RAY_ENC_VEC; + int64_t piece = (v + 1) * RAY_ENC_VEC - row; + if (piece > n - at) piece = n - at; + const int64_t c = v / RAY_ENC_VECS_PER_CHUNK; + const int j = (int)(v % RAY_ENC_VECS_PER_CHUNK); + ray_t* err = NULL; + int64_t lo, hi; + bool decided = false; + if (x->clen > 0 && s->code >= -1) { /* "" is never inside the bounds */ + if (ray_enccol_code_bounds(s->e, c, -1, &lo, &hi)) + decided = s->code < lo || s->code > hi; + if (!decided && ray_enccol_code_bounds(s->e, c, j, &lo, &hi)) + decided = s->code < lo || s->code > hi; + } + if (decided) { memset(o, miss, (size_t)piece); at += piece; continue; } + if (s->code >= -1) { + const ray_enc_desc_t* d = ray_enccol_descs(s->e, c); + if (d[j].encoding == RAY_ENC_STR_DICT) { + ray_enc_vview_t vv; /* on this task's stack */ + int vr = ray_enccol_vview(s->e, v, &vv, &err); + if (vr < 0) { ray_scan_fail_note(x->fail, key, err); return false; } + if (vr > 0 && vv.enc == RAY_ENC_STR_DICT) { + const int64_t k0 = row - v * RAY_ENC_VEC; + if (k0 + piece > vv.n) { + ray_scan_fail_note(x->fail, key, ray_error("corrupt", + "column %s: STR selection: vector %lld holds %d rows", s->e->path, (long long)v, vv.n)); + return false; + } + const uint32_t* cd = vv.codes + k0; + if (s->code < 0) memset(o, miss, (size_t)piece); /* absent: no row equals c */ + else { + const uint32_t cc = (uint32_t)s->code; + for (int64_t k = 0; k < piece; k++) o[k] = (uint8_t)((cd[k] == cc) ^ x->ne); + } + at += piece; + continue; + } + /* declined: the range read decodes or reports it */ + } + } + } + ray_col_range_t rv; + ray_t* err = ray_col_range(s->rs, row, n - at, sc, &rv); + if (!err && rv.n <= 0) + err = s->e ? ray_error("range", "column %s: STR selection: empty range read at row %lld", s->e->path, (long long)row) + : ray_error("range", "column %.*s: STR selection: empty range read at row %lld", + x->cname_len, x->cname, (long long)row); + if (err) { ray_scan_fail_note(x->fail, key, err); return false; } + const ray_str_t* sd = (const ray_str_t*)rv.data; + const uint32_t cl = x->clen; + for (int64_t k = 0; k < rv.n; k++) { + const uint32_t len = sd[k].len; + const bool eq = len == cl && (len == 0 || memcmp(ray_str_t_ptr(&sd[k], rv.str_pool), x->cs, len) == 0); + o[k] = (uint8_t)(eq ^ x->ne); + } + at += rv.n; + } + return true; +} + +/* One morsel [start, start + n) (pred_sel_drive fills morsel by morsel): + * each piece inside one segment at segment-local rows; under an installed + * selection a morsel it drops is not read and a mixed one keeps only its + * own rows. A failure is noted keyed by the morsel's first row and the + * morsel passes no row. */ +static void str_sel_fill(void* vctx, ray_col_scratch_t* sc, int64_t start, int64_t n, uint8_t* out) { + const str_sel_ctx_t* x = (const str_sel_ctx_t*)vctx; + const int64_t ms = start / RAY_MORSEL_ELEMS; + if (x->wflags && x->wflags[ms] == RAY_SEL_NONE) { memset(out, 0, (size_t)n); return; } + if (ray_scan_fail_skip(x->fail, start)) { memset(out, 0, (size_t)n); return; } + int64_t r = start; + const int64_t end = start + n; + while (r < end) { + int64_t lo = 0, hi = x->n_segs - 1; /* the last i with off[i] <= r */ + while (lo < hi) { int64_t mid = lo + (hi - lo + 1) / 2; if (x->off[mid] <= r) lo = mid; else hi = mid - 1; } + int64_t e = x->off[lo + 1] < end ? x->off[lo + 1] : end; + if (!str_seg_fill(x, &x->segs[lo], sc, start, r - x->off[lo], e - r, out + (r - start))) { + memset(out, 0, (size_t)n); + return; + } + r = e; + } + if (x->wflags && x->wflags[ms] == RAY_SEL_MIX) { + uint8_t keep[RAY_MORSEL_ELEMS]; + memset(keep, 0, sizeof keep); + for (uint32_t j = x->woff[ms]; j < x->woff[ms + 1]; j++) + if (x->widx[j] < n) keep[x->widx[j]] = 1; + for (int64_t i = 0; i < n; i++) out[i] &= keep[i]; + } +} + +static _Atomic(uint64_t) g_str_sel_runs[2]; /* test hook: [0] first conjunct, [1] refinement */ +uint64_t ray_exec_test_str_sel(int within) { return atomic_load(&g_str_sel_runs[within ? 1 : 0]); } + +/* A segment's codes path: a single-file, non-synthetic encoded column + * without a published materialization (read by range otherwise). */ +static ray_enccol_t* str_sel_codes_col(ray_t* o) { + if (!o || o->type != RAY_ENCCOL || ray_enccol_decoded_peek(o)) return NULL; + ray_enccol_t* e = ray_enccol_of(o); + return e && e->kind == RAY_ENCCOL_SINGLE && !e->synthetic ? e : NULL; +} + +/* A segment's persisted DICT (P6b): a single-file, non-synthetic encoded + * column recording one, materialized or not (the codes read the mapping). */ +static ray_enccol_t* str_sel_dict_col(ray_t* o) { + if (!o || o->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e = ray_enccol_of(o); + return ray_enccol_has_idict(e) ? e : NULL; +} + +static ray_t* str_sel_run(ray_graph_t* g, ray_op_t* pred, int64_t nrows, ray_t* within, bool* all_pass) { + *all_pass = false; + if (!g || !g->table || !pred || nrows <= 0) return NULL; + if ((pred->opcode != OP_EQ && pred->opcode != OP_NE) || pred->arity != 2) return NULL; + ray_op_t* lhs = op_child(g, pred, 0); + ray_op_t* rhs = op_child(g, pred, 1); + if (!lhs || !rhs) return NULL; + if (lhs->opcode == OP_CONST && rhs->opcode == OP_SCAN) { ray_op_t* t = lhs; lhs = rhs; rhs = t; } + if (lhs->opcode != OP_SCAN || rhs->opcode != OP_CONST) return NULL; + ray_op_ext_t* le = find_ext(g, lhs->id); + ray_op_ext_t* re = find_ext(g, rhs->id); + if (!le || !re || !re->literal || re->literal->type != -RAY_STR) return NULL; + uint16_t stored_table_id = 0; + memcpy(&stored_table_id, le->base.pad, sizeof(uint16_t)); + if (stored_table_id != 0) return NULL; /* default table only */ + ray_col_meta_t m; + /* generation 2 only: a generation-0 column keeps its path */ + if (!ray_table_col_meta(g->table, le->sym, &m) || !m.enc) return NULL; + const bool parted = RAY_IS_PARTED(m.type); + if ((parted ? RAY_PARTED_BASETYPE(m.type) : m.type) != RAY_STR) return NULL; + if (within) { + ray_rowsel_t* wm = ray_rowsel_meta(within); + if (!wm || wm->nrows != nrows) return NULL; + } + if (ray_col_bind_declines(g->table, le->sym)) return NULL; + ray_t* berr = NULL; + ray_col_src_t* src = ray_graph_bind_col(g, g->table, le->sym, &berr); + if (berr) return berr; + if (!src || src->type != RAY_STR || src->len != nrows || src->parted != parted) return NULL; + + str_sel_ctx_t x = { .cs = ray_str_ptr(re->literal), .clen = (uint32_t)ray_str_len(re->literal), + .ne = pred->opcode == OP_NE }; + int64_t one_off[2] = { 0, nrows }; + str_seg_sel_t one; + ray_t* ret = NULL; + bool any_codes = false; + ray_t* cn = ray_sym_str(le->sym); /* arena-owned: the release at out is a no-op */ + x.cname = cn && !RAY_IS_ERR(cn) ? ray_str_ptr(cn) : "?"; + x.cname_len = cn && !RAY_IS_ERR(cn) ? (int)ray_str_len(cn) : 1; + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + x.fail = &fail; + + if (!parted) { + ray_enccol_t* de = str_sel_dict_col(src->obj); + int64_t dc = -2; + if (de && (ret = ray_enccol_idict_code(de, x.cs, x.clen, &dc)) != NULL) goto out; + if (dc >= -1) { /* -2: no DICT after all, the route below */ + one = (str_seg_sel_t){ .rs = src, .de = de, .code = -2, .dcode = dc }; + } else { + ray_enccol_t* e = str_sel_codes_col(src->obj); + if (!e) goto decline; /* materialized: read in place on its path */ + one = (str_seg_sel_t){ .rs = src, .e = e, .code = -2 }; + if ((ret = ray_enccol_strdict_code(e, x.cs, x.clen, &one.code)) != NULL) goto out; + } + x.segs = &one; x.off = one_off; x.n_segs = 1; + ray_col_src_advise(src, 0, nrows); + } else { + int64_t ns = 0; ray_t** segv = NULL; const int64_t* off = NULL; + if (!ray_col_src_parted_segs(src, &ns, &segv, &off, &berr)) { ret = berr; goto out; } + if (ns <= 0 || off[ns] != nrows) goto decline; + x.segs = (str_seg_sel_t*)ray_calloc_raw((size_t)ns * sizeof(str_seg_sel_t)); + if (!x.segs) goto decline; + x.off = off; x.n_segs = ns; + for (int64_t i = 0; i < ns; i++) { + str_seg_sel_t* s = &x.segs[i]; + if (off[i + 1] == off[i]) continue; /* empty: never filled */ + ray_t* be = ray_col_src_bind(segv[i], &s->src); + if (be) { ray_error_free(be); goto decline; } + s->bound = true; + if (s->src.parted || s->src.type != RAY_STR || s->src.len != off[i + 1] - off[i]) goto decline; + s->rs = &s->src; + s->code = -2; + ray_enccol_t* de = str_sel_dict_col(segv[i]); + int64_t dc = -2; + if (de && (ret = ray_enccol_idict_code(de, x.cs, x.clen, &dc)) != NULL) goto out; + if (dc >= -1) { /* -2: no DICT after all, the route below */ + s->de = de; s->dcode = dc; + any_codes = true; + continue; + } + s->e = str_sel_codes_col(segv[i]); + if (s->e && (ret = ray_enccol_strdict_code(s->e, x.cs, x.clen, &s->code)) != NULL) goto out; + any_codes |= s->e != NULL; + } + /* no encoded segment (a generation-0 store whose ragged partitions + * stand in as synthetic segments): its path is unchanged */ + if (!any_codes) goto decline; + for (int64_t i = 0; i < ns; i++) + if (x.segs[i].bound) ray_col_src_advise(&x.segs[i].src, 0, x.segs[i].src.len); + } + if (within) { + x.wflags = ray_rowsel_flags(within); + x.woff = ray_rowsel_offsets(within); + x.widx = ray_rowsel_idx(within); + } + ret = pred_sel_drive(nrows, str_sel_fill, &x, &fail, all_pass); + if ((ret && !RAY_IS_ERR(ret)) || (!ret && *all_pass)) atomic_fetch_add(&g_str_sel_runs[within ? 1 : 0], 1); + goto out; +decline: + ret = NULL; +out: + if (parted && x.segs) { + for (int64_t i = 0; i < x.n_segs; i++) + if (x.segs[i].bound) ray_col_src_release(&x.segs[i].src); + ray_free_raw(x.segs); + } + if (cn && !RAY_IS_ERR(cn)) ray_release(cn); + else if (cn) ray_error_free(cn); + return ret; +} + +ray_t* exec_str_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, bool* all_pass) { + return str_sel_run(g, pred, nrows, NULL, all_pass); +} + +ray_t* exec_str_refine_selection(ray_graph_t* g, ray_op_t* pred, ray_t* sel, bool* all_pass) { + *all_pass = false; + if (!sel) return NULL; + ray_rowsel_t* m = ray_rowsel_meta(sel); + return m ? str_sel_run(g, pred, m->nrows, sel, all_pass) : NULL; +} + +static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, unsigned want, + ray_t** out_col, uint16_t* out_cmp_op, + int64_t* out_key_i, double* out_key_f, + int* out_is_float, ray_col_meta_t* out_meta); + +/* The scanned column of a conjunct idx_filter_decode accepted. */ +static int64_t idx_conj_sym(ray_graph_t* g, ray_op_t* pred) { + ray_op_t* l = op_child(g, pred, 0); + ray_op_ext_t* x = l ? find_ext(g, l->id) : NULL; + return x ? x->sym : -1; +} + +/* The eq+range conjunction's one null rule, for the metadata pass and the + * decode loop alike: a generation-2 column (m->enc, published or not) by its + * exact directory null count, a text column always (ray_vec_may_have_nulls), + * a plain column by ray_vec_may_have_nulls on its vector (borrowed from the + * table: reading it decodes nothing). */ +static bool idx_conj_may_null(ray_graph_t* g, const ray_col_meta_t* m, int64_t sym) { + if (m->type == RAY_SYM || m->type == RAY_STR) return true; + if (m->enc) return m->null_count != 0; + ray_t* c = g->table ? idx_decode_col(g->table, sym) : NULL; + return !c || ray_vec_may_have_nulls(c); +} + +/* The eq+range conjunction's decode loop decided from metadata: no float + * literal, one equality on a hash-eligible column, and ordered compares on + * one other null-free column. Lets a generation-2 equality column probe + * its lazy hash only for a shape that would use it. */ +static bool idx_eqrange_meta_ok(ray_graph_t* g, ray_op_t** conj, int ncj) { + int64_t eq_sym = -1, rg_sym = -1; + for (int ci = 0; ci < ncj; ci++) { + uint16_t cop = 0; ray_col_meta_t cm; + int64_t ki = 0; double kf = 0.0; int isf = 0; + if (!idx_filter_decode(g, conj[ci], IDXW_NONE, NULL, &cop, &ki, &kf, &isf, &cm) || isf) + return false; + int64_t sym = idx_conj_sym(g, conj[ci]); + if (sym < 0) return false; + if (cop == OP_EQ && eq_sym < 0 && + (cm.index_kind == RAY_IDX_HASH || idx_lazy_meta_ok(&cm)) && + (cm.type == RAY_SYM ? ki != 0 : !idx_conj_may_null(g, &cm, sym))) { + eq_sym = sym; + } else if (cop == OP_GE || cop == OP_GT || cop == OP_LE || cop == OP_LT) { + if (idx_conj_may_null(g, &cm, sym)) return false; + if (rg_sym < 0) rg_sym = sym; + else if (rg_sym != sym) return false; + } else return false; + } + return eq_sym >= 0 && rg_sym >= 0 && rg_sym != eq_sym; +} + +/* The single-compare consult on a generation-2 column without a published + * materialization (finding C1), from its directory: the zone class (recorded + * ZONE), an EQ key outside the chunk zone's range, then the PI lazy HASH, + * which materializes the column only when the accumulated probes pay for + * the build. Only a column idx_enc_from_dir admits comes here: recorded + * kind none, ZONE or CHUNK_ZONE, or a recorded HASH, SORT, BLOOM or PART + * under a shape that does not use it (idx_enc_cmp_uses_index); a shape + * that uses it is materialized and answered by the generation-0 block from + * its index. + * 1: every row passes; 2: *sel is the selection; 0: undecided (the fused + * scan answers, by range); -1: *err owned. Mirrors the generation-0 steps + * of the OP_FILTER arm: the same counters in the same order, the same null + * and float conditions (m->null_count is exact for generation 2). */ +static int idx_filter_enc_consult(ray_t* enc, const ray_col_meta_t* m, uint16_t cmp_op, + int64_t key_i, double key_f, int is_float, + int64_t nrows, ray_t** sel, ray_t** err) { + *sel = NULL; *err = NULL; + if (m->index_kind == RAY_IDX_ZONE) ray_idx_consults[IDX_SITE_FILTER_ZONE]++; + switch (ray_enc_zone_class(enc, cmp_op, key_i, key_f)) { + case RAY_ZONE_ALL: + ray_idx_hits[IDX_SITE_FILTER_ZONE]++; + ray_idx_note_use_enc(enc); + return 1; + case RAY_ZONE_NONE: + ray_idx_hits[IDX_SITE_FILTER_ZONE]++; + ray_idx_note_use_enc(enc); + *sel = ray_index_empty_rowsel(nrows); + return *sel ? 2 : 0; + default: break; + } + if (cmp_op != OP_EQ || is_float || m->type == RAY_SYM || m->null_count != 0) return 0; + if (ray_enc_zone_excludes(enc, key_i)) { + ray_idx_consults[IDX_SITE_FILTER_ZONE]++; + *sel = ray_index_empty_rowsel(nrows); + if (*sel) { ray_idx_hits[IDX_SITE_FILTER_ZONE]++; ray_idx_note_use_enc(enc); return 2; } + } + ray_t* lazy = NULL; + ray_t* le = idx_lazy_err(ray_idx_lazy_hash_enc(enc, &lazy)); + if (le) { *err = le; return -1; } + if (!lazy) return 0; + ray_idx_consults[IDX_SITE_FILTER_HASH]++; + *sel = ray_index_hash_eq_rowsel(lazy, key_i); + if (*sel) { ray_idx_hits[IDX_SITE_FILTER_HASH]++; ray_idx_note_use(lazy); } + ray_release(lazy); + return *sel ? 2 : 0; +} + +/* The IN consult's twin: every element outside the chunk zone's range, then + * the lazy HASH for a small integer set. */ +static int idx_filter_enc_in_consult(ray_t* enc, const ray_col_meta_t* m, ray_t* set, + int64_t nrows, ray_t** sel, ray_t** err) { + *sel = NULL; *err = NULL; + if (m->type == RAY_F32 || m->type == RAY_F64 || m->null_count != 0) return 0; + if (ray_enc_zone_excludes_set(enc, set)) { + ray_idx_consults[IDX_SITE_FILTER_ZONE]++; + *sel = ray_index_empty_rowsel(nrows); + if (*sel) { ray_idx_hits[IDX_SITE_FILTER_ZONE]++; ray_idx_note_use_enc(enc); return 2; } + } + if (!idx_lazy_set_ok_len(m->len, set)) return 0; + ray_t* lazy = NULL; + ray_t* le = idx_lazy_err(ray_idx_lazy_hash_enc(enc, &lazy)); + if (le) { *err = le; return -1; } + if (!lazy) return 0; + ray_idx_consults[IDX_SITE_IN]++; + *sel = ray_index_in_rowsel(lazy, set); + if (*sel) { ray_idx_hits[IDX_SITE_IN]++; ray_idx_note_use(lazy); } + ray_release(lazy); + return *sel ? 2 : 0; +} typedef struct { in_worker_ctx_t* ic; } in_sel_fill_ctx_t; -static void in_sel_fill(void* vctx, int64_t start, int64_t n, uint8_t* out) { +static void in_sel_fill(void* vctx, ray_col_scratch_t* sc, int64_t start, int64_t n, uint8_t* out) { + (void)sc; in_sel_fill_ctx_t* c = (in_sel_fill_ctx_t*)vctx; in_worker_ctx_t local = *c->ic; /* per-call copy: morsel-local sink */ local.ob = out; /* element i writes out[i - start] */ @@ -1401,19 +2029,404 @@ static void in_sel_fill(void* vctx, int64_t start, int64_t n, uint8_t* out) { exec_in_worker(&local, 0, start, start + n); } +/* The range-reading fill: rows [start, start + n) of the bound source, + * one range view at a time (a view ends at a generation-2 vector + * boundary), each through exec_in_worker with cd / cd_base at the view. + * A failed read is noted keyed by the morsel's first row (a global row: + * the lowest failure wins) and the rest of the morsel is not-selected. + * Today a morsel is exactly one generation-2 vector (both RAY_MORSEL_ELEMS = + * RAY_ENC_VEC rows, both aligned at row 0), so the loop runs once; it stays + * general for a source whose views end inside a morsel: each view is read + * at its own offset (cd_base = ob_base = start + at), and the failure key + * stays the morsel's first row, the key every view of the morsel shares. */ +typedef struct { + in_worker_ctx_t* ic; + ray_col_src_t* src; + ray_scan_fail_t* fail; + int64_t key_base; /* added to failure keys: a parted segment's first row */ + /* Membership bounds (integer and SYM columns): the probe values, sorted + * ascending and distinct (keys == NULL: no bounds, every morsel read), + * and whether "" (SYM id 0) is one of them. */ + const int64_t* keys; + int nkeys; + bool has_zero; + bool negate; + bool sym_zero_fails; /* SYM: id-0 rows fail both in and not in, as in the kernel */ + /* The float twin (a float column or set: the kernel compares doubles + * with ==, so -0.0 matches +0.0 and a NaN matches nothing): the probe + * as doubles, sorted, NaN dropped (fkeys == NULL: no float bounds); + * col_float: the statistics are F32 / F64 bit patterns, else integer + * values widened to double (monotone, so a value's double stays inside + * the widened [min, max]). */ + const double* fkeys; + int nfkeys; + bool col_float; +} in_sel_rfill_ctx_t; + +/* The membership rule over a range from its statistics (min / max over its + * non-null values, SYM ids nonzero; nn its null rows): when no probe value + * lies in [min, max], `in` passes no row (a null row passes neither) and + * `not in` passes every row, but only without nulls (a null row is not + * selected by `not in` here). A SYM "" member is decided by the null + * count: any id-0 row leaves the range undecided. 1 / 0 / -1. */ +static int in_bounds_decide(const in_sel_rfill_ctx_t* c, int64_t mn, int64_t mx, bool has_mm, int64_t nn) { + if (!has_mm || mn > mx) return -1; + if (c->has_zero && nn > 0) return -1; + int lo = 0, hi = c->nkeys; + while (lo < hi) { int mid = lo + (hi - lo) / 2; if (c->keys[mid] < mn) lo = mid + 1; else hi = mid; } + if (lo < c->nkeys && c->keys[lo] <= mx) return -1; + if (!c->negate) return 0; + return nn == 0 ? 1 : -1; +} + +/* in_bounds_decide over double bounds (the float twin's probe). A NaN + * bound is undecided; -0.0 and +0.0 compare equal, as in the kernel. */ +static int in_bounds_decide_f(const in_sel_rfill_ctx_t* c, double mn, double mx, bool has_mm, int64_t nn) { + if (!has_mm || !(mn <= mx)) return -1; + int lo = 0, hi = c->nfkeys; + while (lo < hi) { int mid = lo + (hi - lo) / 2; if (c->fkeys[mid] < mn) lo = mid + 1; else hi = mid; } + if (lo < c->nfkeys && c->fkeys[lo] <= mx) return -1; + if (!c->negate) return 0; + return nn == 0 ? 1 : -1; +} +static inline double in_stat_f(const in_sel_rfill_ctx_t* c, int64_t v) { + if (!c->col_float) return (double)v; + double d; memcpy(&d, &v, 8); + return d; +} + +/* Morsel [start, start + n) answered without a range read: from the chunk's + * directory, then the vector's descriptor, then the vector's view + * (ray_enc_eval_in on ids / values, inverted for `not in` with null rows + * cleared). 1 answered into out, 0 read it, -1 an owned *err (the view's + * validation, as the decode would report it). */ +static int in_sel_bounds(const in_sel_rfill_ctx_t* c, int64_t start, int64_t n, uint8_t* out, ray_t** err) { + if (c->fkeys) { /* floats: bounds only, no view evaluator */ + int d = -1; + if ((start >> 16) == ((start + n - 1) >> 16)) { + ray_enc_chunk_stat_t st; + if (ray_col_src_chunk_stat(c->src, start >> 16, &st)) + d = in_bounds_decide_f(c, in_stat_f(c, st.min), in_stat_f(c, st.max), st.has_minmax, + (int64_t)st.null_count); + } + if (d < 0 && start / RAY_ENC_VEC == (start + n - 1) / RAY_ENC_VEC) { + int64_t mn, mx; uint32_t nn; + if (ray_col_src_vec_stat(c->src, start / RAY_ENC_VEC, &mn, &mx, &nn)) + d = in_bounds_decide_f(c, in_stat_f(c, mn), in_stat_f(c, mx), true, nn); + } + if (d >= 0) { memset(out, d, (size_t)n); return 1; } + return 0; + } + if (!c->keys) return 0; + int d = -1; + if ((start >> 16) == ((start + n - 1) >> 16)) { + ray_enc_chunk_stat_t st; + if (ray_col_src_chunk_stat(c->src, start >> 16, &st)) + d = in_bounds_decide(c, st.min, st.max, st.has_minmax, (int64_t)st.null_count); + } + if (d < 0 && start / RAY_ENC_VEC == (start + n - 1) / RAY_ENC_VEC) { + int64_t mn, mx; uint32_t nn; + if (ray_col_src_vec_stat(c->src, start / RAY_ENC_VEC, &mn, &mx, &nn)) + d = in_bounds_decide(c, mn, mx, true, nn); + } + if (d >= 0) { memset(out, d, (size_t)n); return 1; } + if (start % RAY_ENC_VEC) return 0; + ray_enc_vview_t v; /* on this task's stack */ + int vr = ray_col_src_vview(c->src, start / RAY_ENC_VEC, &v, err); + if (vr <= 0 || v.n != n) return vr < 0 ? -1 : 0; + if (!ray_enc_eval_in(&v, c->keys, c->nkeys, 0, out)) return 0; + if (c->negate) { + for (int64_t i = 0; i < n; i++) out[i] ^= 1; + ray_enc_mask_nulls(&v, 0, out); + } + if (v.type == RAY_SYM && c->sym_zero_fails && v.n_nulls > 0) { + uint8_t zero[RAY_ENC_VEC]; /* the view's id-0 rows */ + const int64_t z = 0; + if (!ray_enc_eval_in(&v, &z, 1, 0, zero)) return 0; + for (int64_t i = 0; i < n; i++) out[i] &= (uint8_t)(zero[i] ^ 1); + } + return 1; +} + +static int in_key_cmp(const void* a, const void* b) { + int64_t x = *(const int64_t*)a, y = *(const int64_t*)b; + return (x > y) - (x < y); +} + +static int in_fkey_cmp(const void* a, const void* b) { + double x = *(const double*)a, y = *(const double*)b; + return (x > y) - (x < y); +} + +static void in_sel_rfill(void* vctx, ray_col_scratch_t* sc, int64_t start, int64_t n, uint8_t* out) { + in_sel_rfill_ctx_t* c = (in_sel_rfill_ctx_t*)vctx; + const int64_t key = c->key_base + start; + if (ray_scan_fail_skip(c->fail, key)) { memset(out, 0, (size_t)n); return; } + ray_t* berr = NULL; + int b = in_sel_bounds(c, start, n, out, &berr); + if (b > 0) return; + if (b < 0) { ray_scan_fail_note(c->fail, key, berr); memset(out, 0, (size_t)n); return; } + int64_t at = 0; + while (at < n) { + ray_col_range_t v; + ray_t* e = ray_col_range(c->src, start + at, n - at, sc, &v); + if (!e && v.n <= 0) + e = ray_error("range", "in selection: empty range read at row %lld", (long long)(start + at)); + if (e) { + ray_scan_fail_note(c->fail, key, e); + memset(out + at, 0, (size_t)(n - at)); + return; + } + in_worker_ctx_t local = *c->ic; + local.ob = out + at; local.ob_base = start + at; + local.cd = v.data; local.cd_base = start + at; + local.cattrs = v.attrs; + exec_in_worker(&local, 0, start + at, start + at + v.n); + at += v.n; + } +} + +/* The range-reading fill's context over bound source `src` with probe ic: + * the membership bounds, the probe values sorted once (integer and SYM + * columns as int64; a float column or set as doubles), in kstack / fstack + * when they hold 32 values or fewer. A failed allocation leaves those + * bounds off (every morsel read). in_rfill_free releases them. */ +static void in_rfill_setup(in_sel_rfill_ctx_t* f, in_worker_ctx_t* ic, ray_col_src_t* src, + ray_scan_fail_t* fail, bool negate, int64_t* kstack, double* fstack) { + *f = (in_sel_rfill_ctx_t){ .ic = ic, .src = src, .fail = fail, .negate = negate }; + if (!ic->use_double && ic->sv_len <= INT32_MAX) { + int64_t* keys = ic->sv_len <= 32 ? kstack : (int64_t*)ray_alloc_raw((size_t)ic->sv_len * sizeof(int64_t)); + if (keys) { + if (ic->sv_len) memcpy(keys, ic->svi, (size_t)ic->sv_len * sizeof(int64_t)); + qsort(keys, (size_t)ic->sv_len, sizeof(int64_t), in_key_cmp); + int64_t nk = 0; + for (int64_t j = 0; j < ic->sv_len; j++) + if (nk == 0 || keys[nk - 1] != keys[j]) keys[nk++] = keys[j]; + f->keys = keys; + f->nkeys = (int)nk; + f->has_zero = src->type == RAY_SYM && nk > 0 && keys[0] == 0; + /* a SYM view's id-0 rows answer as the kernel's: 0 under the + * verdict LUT and the null-checked loop (null rows fail both + * in and not in, #739), (0 in set) ^ negate under the + * unchecked loop */ + f->sym_zero_fails = ic->symlut || ic->col_has_nulls; + } + } + if (ic->use_double && ic->sv_len <= INT32_MAX) { + double* fkeys = ic->sv_len <= 32 ? fstack : (double*)ray_alloc_raw((size_t)ic->sv_len * sizeof(double)); + if (fkeys) { + int64_t nk = 0; + for (int64_t j = 0; j < ic->sv_len; j++) + if (ic->svf[j] == ic->svf[j]) fkeys[nk++] = ic->svf[j]; /* a NaN member matches nothing */ + qsort(fkeys, (size_t)nk, sizeof(double), in_fkey_cmp); + f->fkeys = fkeys; + f->nfkeys = (int)nk; + f->col_float = src->type == RAY_F32 || src->type == RAY_F64; + } + } +} + +static void in_rfill_free(in_sel_rfill_ctx_t* f, int64_t* kstack, double* fstack) { + if (f->keys && f->keys != kstack) ray_free_raw((void*)f->keys); + if (f->fkeys && f->fkeys != fstack) ray_free_raw((void*)f->fkeys); + f->keys = NULL; f->fkeys = NULL; +} + +/* One segment of a parted `in` selection: its own bound source and probe + * (a SYM segment translates the set into its own domain, an integer DICT + * segment's views decide on its own dictionary), read in place when ready + * (a plain segment, or a published materialization) and by range + * otherwise. */ +typedef struct { + ray_col_src_t src; + bool bound, ready; + in_worker_ctx_t ic; + ray_t* sv_hdr; + ray_t* lut_hdr; + double svf_stack[32]; + int64_t svi_stack[32]; + int64_t kstack[32]; + double fstack[32]; + in_sel_fill_ctx_t f; + in_sel_rfill_ctx_t rf; +} in_seg_sel_t; + +typedef struct { + in_seg_sel_t* segs; + const int64_t* off; /* segment i: rows [off[i], off[i + 1]) */ + int64_t n_segs; + /* An installed selection the result is ANDed with (a later conjunct), + * or NULL: its morsel flags, offsets and ids. */ + const uint8_t* wflags; + const uint32_t* woff; + const uint16_t* widx; +} in_sel_parted_ctx_t; + +/* Rows [start, start + n) of a parted table (one morsel: pred_sel_drive + * fills morsel by morsel): each piece inside one segment goes to that + * segment's fill at segment-local rows (a morsel straddling a segment + * boundary is cut there). Under an installed selection a morsel it drops + * is not read, and a mixed one keeps only its own rows. */ +static void in_sel_parted_fill(void* vctx, ray_col_scratch_t* sc, int64_t start, int64_t n, uint8_t* out) { + const in_sel_parted_ctx_t* c = (const in_sel_parted_ctx_t*)vctx; + const int64_t ms = start / RAY_MORSEL_ELEMS; + if (c->wflags && c->wflags[ms] == RAY_SEL_NONE) { memset(out, 0, (size_t)n); return; } + int64_t r = start; + const int64_t end = start + n; + while (r < end) { + int64_t lo = 0, hi = c->n_segs - 1; /* the last i with off[i] <= r: never empty */ + while (lo < hi) { int64_t mid = lo + (hi - lo + 1) / 2; if (c->off[mid] <= r) lo = mid; else hi = mid - 1; } + in_seg_sel_t* s = &c->segs[lo]; + int64_t e = c->off[lo + 1] < end ? c->off[lo + 1] : end; + if (s->ready) in_sel_fill(&s->f, sc, r - c->off[lo], e - r, out + (r - start)); + else in_sel_rfill(&s->rf, sc, r - c->off[lo], e - r, out + (r - start)); + r = e; + } + if (c->wflags && c->wflags[ms] == RAY_SEL_MIX) { + uint8_t keep[RAY_MORSEL_ELEMS]; + memset(keep, 0, sizeof keep); + for (uint32_t j = c->woff[ms]; j < c->woff[ms + 1]; j++) + if (c->widx[j] < n) keep[c->widx[j]] = 1; + for (int64_t i = 0; i < n; i++) out[i] &= keep[i]; + } +} + +static void in_seg_sel_free(in_seg_sel_t* segs, int64_t n) { + for (int64_t i = 0; i < n; i++) { + in_seg_sel_t* s = &segs[i]; + if (!s->ready) in_rfill_free(&s->rf, s->kstack, s->fstack); + if (s->sv_hdr) ray_free(s->sv_hdr); + if (s->lut_hdr) ray_free(s->lut_hdr); + if (s->bound) ray_col_src_release(&s->src); + } + ray_free_raw(segs); +} + +/* exec_in_to_selection over a generation-2 parted column (src, bound over + * the RAY_ENCCOL parted object): the segments evaluated each by its own + * source and probe, as the single-file path reads one, into one selection + * over the table's rows; the column is never materialized. A generation-0 + * parted wrapper is not taken (its route is unchanged). With `within` (a + * selection over the same rows, borrowed) the result is its AND with that + * one. NULL (the caller's fallback) for a shape a segment declines (STR, + * GUID), an owned error, or the selection. */ +static ray_t* in_sel_parted(ray_col_src_t* src, ray_t* set_lit, bool negate, int64_t nrows, ray_t* within, + bool* all_pass) { + *all_pass = false; + if (!src->obj || src->obj->type != RAY_ENCCOL) return NULL; + int64_t ns = 0; ray_t** segv = NULL; const int64_t* off = NULL; ray_t* err = NULL; + if (!ray_col_src_parted_segs(src, &ns, &segv, &off, &err)) return err; + if (ns <= 0 || off[ns] != nrows) return NULL; + in_seg_sel_t* segs = (in_seg_sel_t*)ray_calloc_raw((size_t)ns * sizeof(in_seg_sel_t)); + if (!segs) return NULL; + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + for (int64_t i = 0; i < ns; i++) { + in_seg_sel_t* s = &segs[i]; + if (off[i + 1] == off[i]) { s->ready = true; continue; } /* empty: never filled */ + ray_t* be = ray_col_src_bind(segv[i], &s->src); + if (be) { ray_error_free(be); in_seg_sel_free(segs, ns); return NULL; } + s->bound = true; + if (s->src.parted || s->src.len != off[i + 1] - off[i]) { in_seg_sel_free(segs, ns); return NULL; } + ray_t* col = ray_col_src_ready(&s->src); + in_ctx_status_t st; + if (col) { + if (ray_is_atom(col) || RAY_IS_PARTED(col->type)) { in_seg_sel_free(segs, ns); return NULL; } + s->ready = true; + st = in_build_worker_ctx(col, set_lit, negate, s->svf_stack, s->svi_stack, &s->ic, &s->sv_hdr, &s->lut_hdr); + s->f.ic = &s->ic; + } else { + st = in_build_worker_ctx_meta(s->src.type, s->src.attrs, s->src.may_null, s->src.dom, set_lit, negate, + s->svf_stack, s->svi_stack, &s->ic, &s->sv_hdr, &s->lut_hdr); + if (st == IN_CTX_OK) { + in_rfill_setup(&s->rf, &s->ic, &s->src, &fail, negate, s->kstack, s->fstack); + s->rf.key_base = off[i]; + ray_col_src_advise(&s->src, 0, s->src.len); + } + } + if (st != IN_CTX_OK) { s->ready = true; in_seg_sel_free(segs, ns); return NULL; } /* STR / GUID / OOM */ + } + in_sel_parted_ctx_t pc = { segs, off, ns, NULL, NULL, NULL }; + if (within) { + ray_rowsel_t* wm = ray_rowsel_meta(within); + if (!wm || wm->nrows != nrows) { in_seg_sel_free(segs, ns); return NULL; } + pc.wflags = ray_rowsel_flags(within); + pc.woff = ray_rowsel_offsets(within); + pc.widx = ray_rowsel_idx(within); + } + ray_t* sel = pred_sel_drive(nrows, in_sel_parted_fill, &pc, &fail, all_pass); + in_seg_sel_free(segs, ns); + return sel; +} + +/* A later `in` conjunct over a single-file generation-2 column read by + * range (exec_in_to_selection's range fill), ANDed with the installed + * selection `within` inside the fill (in_sel_parted_fill over one + * segment: a morsel `within` drops is not read). NULL when the column is + * read in place (a published materialization: the bool path, as before) + * or the shape declines (STR, GUID, OOM); an owned error, or the + * selection. */ +static _Atomic(uint64_t) g_in_single_within; /* test hook */ +uint64_t ray_exec_test_in_single_within(void) { return atomic_load(&g_in_single_within); } +static ray_t* in_sel_single_within(ray_col_src_t* src, ray_t* set_lit, bool negate, int64_t nrows, + ray_t* within, bool* all_pass) { + *all_pass = false; + if (ray_col_src_ready(src)) return NULL; + ray_rowsel_t* wm = ray_rowsel_meta(within); + if (!wm || wm->nrows != nrows) return NULL; + in_seg_sel_t* seg = (in_seg_sel_t*)ray_calloc_raw(sizeof(in_seg_sel_t)); + if (!seg) return NULL; + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + if (in_build_worker_ctx_meta(src->type, src->attrs, src->may_null, src->dom, set_lit, negate, + seg->svf_stack, seg->svi_stack, &seg->ic, &seg->sv_hdr, &seg->lut_hdr) != IN_CTX_OK) { + seg->ready = true; /* nothing set up to free but the headers */ + in_seg_sel_free(seg, 1); + return NULL; + } + in_rfill_setup(&seg->rf, &seg->ic, src, &fail, negate, seg->kstack, seg->fstack); + ray_col_src_advise(src, 0, nrows); + const int64_t off[2] = { 0, nrows }; + in_sel_parted_ctx_t pc = { seg, off, 1, ray_rowsel_flags(within), ray_rowsel_offsets(within), + ray_rowsel_idx(within) }; + ray_t* sel = pred_sel_drive(nrows, in_sel_parted_fill, &pc, &fail, all_pass); + in_seg_sel_free(seg, 1); /* src is the graph's: not bound here */ + if ((sel && !RAY_IS_ERR(sel)) || (!sel && *all_pass)) atomic_fetch_add(&g_in_single_within, 1); + return sel; +} + +/* A parted `in` / `not in` filter's selection, for a FILTER that already + * holds one (a later conjunct): the generation-2 route above, or NULL when + * it is not taken (any other column keeps the bool path). */ +static ray_t* exec_in_parted_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, ray_t* within, + bool* all_pass); + ray_t* exec_in_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, bool* all_pass) { *all_pass = false; if (pred->opcode != OP_IN && pred->opcode != OP_NOT_IN) return NULL; - - ray_t* col = NULL; - ray_t* set_lit = NULL; - /* idx_filter_in_decode matches OP_IN of shape (SCAN flat-col) IN (CONST - * set) and rejects parted/MAPCOMMON columns + non-CONST sets. OP_NOT_IN - * isn't a decode shape (the shared decode is IN-only), so `not-in` falls - * back to the bool path here — still correct, just unfused. */ - if (!idx_filter_in_decode(g, pred, &col, &set_lit)) return NULL; - if (ray_is_atom(col) || col->len != nrows) return NULL; + if (pred->arity != 2) return NULL; + + /* Shape: (SCAN flat-col) IN / NOT-IN (CONST set) over the default + * table. The column is bound, never decoded: a plain column (or a + * generation-2 one whose materialization is published) is read in + * place, a generation-2 one by range. */ + ray_op_t* lhs = op_child(g, pred, 0); + ray_op_t* rhs = op_child(g, pred, 1); + if (!lhs || lhs->opcode != OP_SCAN || !rhs || rhs->opcode != OP_CONST) return NULL; + ray_op_ext_t* le = find_ext(g, lhs->id); + ray_op_ext_t* re = find_ext(g, rhs->id); + if (!le || !re || !re->literal) return NULL; + uint16_t stored_table_id = 0; + memcpy(&stored_table_id, le->base.pad, sizeof(uint16_t)); + if (stored_table_id != 0 || !g->table) return NULL; /* default table only, as idx_filter_in_decode */ + ray_col_meta_t m; + if (!ray_table_col_meta(g->table, le->sym, &m) || m.type == RAY_MAPCOMMON) return NULL; + if (RAY_IS_PARTED(m.type)) return exec_in_parted_selection(g, pred, nrows, NULL, all_pass); + if (ray_col_bind_declines(g->table, le->sym)) return NULL; + ray_t* berr = NULL; + ray_col_src_t* src = ray_graph_bind_col(g, g->table, le->sym, &berr); + if (berr) return berr; + if (!src || src->parted || src->len != nrows) return NULL; + ray_t* set_lit = re->literal; bool negate = (pred->opcode == OP_NOT_IN); double svf_stack[32]; @@ -1421,22 +2434,68 @@ ray_t* exec_in_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, in_worker_ctx_t ic; ray_t* sv_hdr = NULL; ray_t* lut_hdr = NULL; - if (in_build_worker_ctx(col, set_lit, negate, svf_stack, svi_stack, - &ic, &sv_hdr, &lut_hdr) != IN_CTX_OK) - return NULL; /* STR / OOM → bool-path fallback */ - - in_sel_fill_ctx_t fctx = { &ic }; - ray_t* sel = pred_sel_drive(nrows, in_sel_fill, &fctx, all_pass); + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + ray_t* sel; + ray_t* col = ray_col_src_ready(src); + if (col) { + if (ray_is_atom(col) || RAY_IS_PARTED(col->type)) return NULL; + if (in_build_worker_ctx(col, set_lit, negate, svf_stack, svi_stack, + &ic, &sv_hdr, &lut_hdr) != IN_CTX_OK) + return NULL; /* STR / OOM → bool-path fallback */ + in_sel_fill_ctx_t fctx = { &ic }; + sel = pred_sel_drive(nrows, in_sel_fill, &fctx, &fail, all_pass); + } else { + if (in_build_worker_ctx_meta(src->type, src->attrs, src->may_null, src->dom, + set_lit, negate, svf_stack, svi_stack, + &ic, &sv_hdr, &lut_hdr) != IN_CTX_OK) + return NULL; /* STR / GUID / OOM → bool-path fallback */ + ray_col_src_advise(src, 0, nrows); + in_sel_rfill_ctx_t fctx; + int64_t kstack[32]; + double fstack[32]; + in_rfill_setup(&fctx, &ic, src, &fail, negate, kstack, fstack); + sel = pred_sel_drive(nrows, in_sel_rfill, &fctx, &fail, all_pass); + in_rfill_free(&fctx, kstack, fstack); + } if (sv_hdr) ray_free(sv_hdr); if (lut_hdr) ray_free(lut_hdr); return sel; } -static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, +static ray_t* exec_in_parted_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, ray_t* within, + bool* all_pass) { + *all_pass = false; + if (!g || !g->table || !pred || nrows <= 0) return NULL; + if ((pred->opcode != OP_IN && pred->opcode != OP_NOT_IN) || pred->arity != 2) return NULL; + ray_op_t* lhs = op_child(g, pred, 0); + ray_op_t* rhs = op_child(g, pred, 1); + if (!lhs || lhs->opcode != OP_SCAN || !rhs || rhs->opcode != OP_CONST) return NULL; + ray_op_ext_t* le = find_ext(g, lhs->id); + ray_op_ext_t* re = find_ext(g, rhs->id); + if (!le || !re || !re->literal) return NULL; + uint16_t stored_table_id = 0; + memcpy(&stored_table_id, le->base.pad, sizeof(uint16_t)); + if (stored_table_id != 0) return NULL; + ray_col_meta_t m; + /* generation 2 only: a generation-0 column is never bound here; a + * single-file one only as a later conjunct (within: the first one + * takes exec_in_to_selection's range fill) */ + if (!ray_table_col_meta(g->table, le->sym, &m) || !m.enc) return NULL; + if (!RAY_IS_PARTED(m.type) && (!within || m.type == RAY_MAPCOMMON)) return NULL; + if (ray_col_bind_declines(g->table, le->sym)) return NULL; + ray_t* berr = NULL; + ray_col_src_t* src = ray_graph_bind_col(g, g->table, le->sym, &berr); + if (berr) return berr; + if (!src || src->len != nrows) return NULL; + if (!src->parted) return in_sel_single_within(src, re->literal, pred->opcode == OP_NOT_IN, nrows, within, all_pass); + return in_sel_parted(src, re->literal, pred->opcode == OP_NOT_IN, nrows, within, all_pass); +} + +static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, unsigned want, ray_t** out_col, uint16_t* out_cmp_op, int64_t* out_key_i, double* out_key_f, - int* out_is_float); + int* out_is_float, ray_col_meta_t* out_meta); /* ---- Slice-group fusion probe (FILTER(in/eq on c) + GROUP(by c)) ---- * @@ -1467,13 +2526,13 @@ bool ray_slice_group_probe(ray_graph_t* g, ray_op_t* root, ray_t* by_col) { ray_t* eq_atom = NULL; /* owned (built for the eq shape) */ if (pred->opcode == OP_IN) { /* NOT_IN also decodes — reject it */ ray_t* c = NULL; ray_t* set = NULL; - if (idx_filter_in_decode(g, pred, &c, &set) && c == by_col) + if (idx_filter_in_decode(g, pred, IDXW_INDEX, &c, &set, NULL) && c == by_col) keys = set; } if (!keys) { ray_t* c = NULL; uint16_t cop = 0; int64_t ki = 0; double kf = 0.0; int isf = 0; - if (idx_filter_decode(g, pred, &c, &cop, &ki, &kf, &isf) && + if (idx_filter_decode(g, pred, IDXW_INDEX, &c, &cop, &ki, &kf, &isf, NULL) && c == by_col && cop == OP_EQ && !isf) { eq_atom = ray_sym(ki); if (!eq_atom || RAY_IS_ERR(eq_atom)) { @@ -1492,6 +2551,7 @@ bool ray_slice_group_probe(ray_graph_t* g, ray_op_t* root, ray_t* by_col) { if (eq_atom) ray_release(eq_atom); if (k < 0) return false; ray_idx_hits[IDX_SITE_GROUP_SLICE]++; + ray_idx_note_use(by_col); g->sg_col = by_col; ray_retain(by_col); g->sg_slices_hdr = shdr; /* NULL when k == 0 */ @@ -1541,10 +2601,10 @@ static int idx_flatten_and(ray_graph_t* g, ray_op_t* op, return n; } -static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, +static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, unsigned want, ray_t** out_col, uint16_t* out_cmp_op, int64_t* out_key_i, double* out_key_f, - int* out_is_float) { + int* out_is_float, ray_col_meta_t* out_meta) { if (!pred_op || pred_op->arity != 2) return 0; uint16_t opc = pred_op->opcode; if (opc != OP_EQ && opc != OP_NE && @@ -1563,9 +2623,10 @@ static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, if (stored_table_id != 0) return 0; /* non-default table — skip */ ray_t* tbl = g->table; if (!tbl) return 0; - ray_t* col = ray_table_get_col(tbl, lext->sym); - if (!col || RAY_IS_ERR(col)) return 0; - if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return 0; + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, lext->sym, &m)) return 0; + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON) return 0; + if (!idx_want_ok(&m, want)) return 0; ray_t* cv = rext->literal; if (!cv) return 0; @@ -1592,7 +2653,7 @@ static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, * cross-type predicate would otherwise compare against the zero-filled * key slot — e.g. (> f 100) on an F64 column decoded key_f=0.0 and * misclassified ALL/NONE. */ - int col_is_float = (col->type == RAY_F32 || col->type == RAY_F64); + int col_is_float = (m.type == RAY_F32 || m.type == RAY_F64); if (col_is_float && !is_float) { /* Integer literal vs float column: coerce, but only when the * value round-trips exactly through double. Doubles have a @@ -1608,7 +2669,12 @@ static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, return 0; } - *out_col = col; + if (out_meta) *out_meta = m; + if (out_col) { + ray_t* col = idx_decode_col(tbl, lext->sym); + if (!col) return 0; + *out_col = col; + } *out_cmp_op = opc; *out_key_i = key_i; *out_key_f = key_f; @@ -1621,11 +2687,12 @@ static int idx_filter_decode(ray_graph_t* g, ray_op_t* pred_op, * Same column eligibility as idx_filter_decode: default table, not parted, * not MAPCOMMON. * - * On success, *out_col is the column vec and *out_set_lit is the CONST + * On success, *out_col (when non-NULL; NULL decodes nothing) is the column + * vec, *out_meta (when non-NULL) its metadata, and *out_set_lit is the CONST * literal vec (borrowed from the ext, valid for the lifetime of the graph). * Returns 1 on success, 0 if the shape is not matched. */ -static int idx_filter_in_decode(ray_graph_t* g, ray_op_t* pred_op, - ray_t** out_col, ray_t** out_set_lit) { +static int idx_filter_in_decode(ray_graph_t* g, ray_op_t* pred_op, unsigned want, + ray_t** out_col, ray_t** out_set_lit, ray_col_meta_t* out_meta) { if (!pred_op || pred_op->arity != 2) return 0; if (pred_op->opcode != OP_IN) return 0; @@ -1644,11 +2711,16 @@ static int idx_filter_in_decode(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl = g->table; if (!tbl) return 0; - ray_t* col = ray_table_get_col(tbl, lext->sym); - if (!col || RAY_IS_ERR(col)) return 0; - if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return 0; - - *out_col = col; + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, lext->sym, &m)) return 0; + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON) return 0; + if (!idx_want_ok(&m, want)) return 0; + if (out_meta) *out_meta = m; + if (out_col) { + ray_t* col = idx_decode_col(tbl, lext->sym); + if (!col) return 0; + *out_col = col; + } *out_set_lit = rext->literal; return 1; } @@ -1742,7 +2814,11 @@ static ray_t* exec_pushed_group_filter(ray_graph_t* g, ray_op_t* filter_op) { * scan or literal. Only scalar expression nodes (OP_SCAN/OP_CONST and the * element-wise range OP_ROUND..OP_IDIV) are admitted in the walk; any other * opcode, an oversized graph, or overflow returns -1 — callers must treat - * that as "unknown" and skip the optimisation. */ + * that as "unknown" and skip the optimisation. So does a constant holding + * several values: a vector of the table's length stands for a column, row + * aligned with the table, and the compacted survivors would read it from + * its first cell on (one of another length is the group's length error, + * which measures it against the table). */ /* Opcodes handled by the elementwise case of exec_node_inner — must * match its case labels (ROUND sits at 9, outside NEG..CAST; IDIV at * 49, outside ADD..MAX2; extra unary math starts at 137). */ @@ -1790,7 +2866,12 @@ static int collect_scan_syms(ray_graph_t* g, const uint32_t* roots, int nroots, } continue; } - if (node->opcode == OP_CONST) continue; + if (node->opcode == OP_CONST) { + ray_op_ext_t* cx = find_ext(g, nid); + ray_t* lit = cx ? cx->literal : NULL; + if (lit && !ray_is_atom(lit) && ray_len(lit) != 1) return -1; + continue; + } /* Admit only scalar element-wise expression nodes. */ if (!op_is_elementwise(node->opcode)) return -1; @@ -1811,6 +2892,101 @@ static int collect_scan_syms(ray_graph_t* g, const uint32_t* roots, int nroots, return n; } +/* Is `filter` chained (it reads another FILTER, as a split `and` does) + * over the default table's rows, with a term whose verdicts survive a + * subset of those rows (ray_expr_subset_invariant)? A term reading other + * rows (an aggregate, a running function) answers false. */ +static bool filter_chain_subset_invariant(ray_graph_t* g, ray_op_t* filter) { + ray_op_t* in = op_child(g, filter, 0); + ray_op_t* term = op_child(g, filter, 1); + if (!in || in->opcode != OP_FILTER || !term) return false; + return filter_input_default_domain(g, in->id) && + ray_expr_subset_invariant(g, term->id); +} + +/* The sparse refinement's keep set for a membership test the element-wise + * walk declines: `in` / `not in` of one generation-2 column (not SYM: its + * ids resolve over the file's domain, which exec_in does not translate) + * against a constant set. The refinement then gathers that column's + * survivors by range and runs exec_in over them, instead of evaluating + * the test over every row, which reads the column whole. Generation 0 + * keeps the full-width path (0: not admitted). */ +static ray_t* scan_table_of(ray_graph_t* g, ray_op_ext_t* ext); +static _Atomic(uint64_t) g_refine_in; +uint64_t ray_exec_test_refine_in(void) { return atomic_load(&g_refine_in); } +static int refine_in_keep(ray_graph_t* g, ray_op_t* pred, ray_t* tbl, int64_t* keep) { + if (!pred || (pred->opcode != OP_IN && pred->opcode != OP_NOT_IN)) return 0; + ray_op_t* c0 = op_child(g, pred, 0); + ray_op_t* c1 = op_child(g, pred, 1); + if (!c0 || !c1 || c0->opcode != OP_SCAN || c1->opcode != OP_CONST) return 0; + ray_op_ext_t* x = find_ext(g, c0->id); + if (!x || scan_table_of(g, x) != tbl) return 0; + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, x->sym, &m) || !m.enc) return 0; + int8_t bt = RAY_IS_PARTED(m.type) ? (int8_t)RAY_PARTED_BASETYPE(m.type) : m.type; + if (bt == RAY_SYM || bt == RAY_LIST) return 0; + keep[0] = x->sym; + atomic_fetch_add(&g_refine_in, 1); + return 1; +} + +/* Does a GROUP read a constant of several values as rows: a vector + * literal under its key or aggregate inputs, as one or as an operand of an + * element-wise node? Such a vector stands for a column of the table it was + * written against, so compacting the table under a where: would leave it + * longer than the survivors. An operand of any other node (the set of an + * `in`, say) is no row input and does not count. */ +static bool group_reads_vector_const(ray_graph_t* g, ray_op_ext_t* gx) { + if (!gx) return false; + uint32_t nc = g->node_count; + if (nc > 4096) return true; + bool visited[4096]; + memset(visited, 0, nc * sizeof(bool)); + uint32_t stack[64]; + bool rows[64]; + int sp = 0; + for (uint8_t k = 0; k < gx->n_keys; k++) { + if (sp >= 64) return true; + stack[sp] = gx->keys[k]; rows[sp++] = true; + } + for (uint8_t a = 0; a < gx->n_aggs; a++) { + uint32_t ins[2] = { gx->agg_ins ? gx->agg_ins[a] : RAY_OP_NONE, + gx->agg_ins2 ? gx->agg_ins2[a] : RAY_OP_NONE }; + for (int i = 0; i < 2; i++) { + if (ins[i] == RAY_OP_NONE) continue; + if (sp >= 64) return true; + stack[sp] = ins[i]; rows[sp++] = true; + } + } + while (sp > 0) { + sp--; + uint32_t nid = stack[sp]; + bool as_rows = rows[sp]; + if (nid >= nc) return true; + ray_op_t* node = &g->nodes[nid]; + if (node->flags & OP_FLAG_DEAD) continue; + if (node->opcode == OP_CONST) { + ray_op_ext_t* cx = find_ext(g, nid); + ray_t* lit = cx ? cx->literal : NULL; + if (as_rows && lit && !ray_is_atom(lit) && ray_len(lit) != 1) return true; + continue; + } + if (visited[nid]) continue; + visited[nid] = true; + bool child_rows = op_is_elementwise(node->opcode); + ray_op_ext_t* nx = find_ext(g, nid); + uint32_t kids[3] = { node->arity > 0 ? node->in_id[0] : RAY_OP_NONE, + node->arity > 1 ? node->in_id[1] : RAY_OP_NONE, + nx && nx->third_in != 0 ? nx->third_in : RAY_OP_NONE }; + for (int i = 0; i < 3; i++) { + if (kids[i] == RAY_OP_NONE) continue; + if (sp >= 64) return true; + stack[sp] = kids[i]; rows[sp++] = child_rows; + } + } + return false; +} + /* collect_scan_syms over a GROUP's key + agg-input subtrees. */ static int group_input_scan_syms(ray_graph_t* g, ray_op_ext_t* gx, int64_t* syms, int max, bool* has_expr) { @@ -1977,14 +3153,19 @@ static ray_t* exec_elementwise_tree(ray_graph_t* g, ray_op_t* root) { * runs compiled. */ if (n != root && g->table && nr > 0) { ray_expr_t ex; - if (expr_compile(g, g->table, n, &ex)) { + ray_t* cerr = NULL; + if (expr_compile(g, g->table, n, &ex, &cerr)) { ray_t* vec = expr_eval_full(&ex, nr); if (vec && !RAY_IS_ERR(vec)) { vals[e.id] = vec; state[e.id] = EW_DONE; continue; } + if (expr_eval_err_fatal(vec)) { result = vec; goto done; } ray_error_free(vec); /* fall through to per-node eval */ + } else if (cerr) { /* a failed column bind is the query's error */ + result = cerr; + goto done; } } @@ -2250,6 +3431,281 @@ ray_t* exec_node(ray_graph_t* g, ray_op_t* op) { return _prof_result; } +/* Release a table an operator consumed (a selection-compacted copy, a + * child's result) after unbinding it: kernels compiled over it bound its + * columns on `g`, and each bind retains its column until ray_graph_free, so + * a released temporary would stay alive for the rest of the graph. The + * query table itself keeps its binds. */ +static void exec_release_tmp(ray_graph_t* g, ray_t* t) { + if (t && !RAY_IS_ERR(t) && t->type == RAY_TABLE && t != g->table) + ray_graph_unbind_table(g, t); + ray_release(t); +} + +/* The table an OP_SCAN reads: pad[0..1] holds table_id + 1, 0 = g->table. */ +static ray_t* scan_table_of(ray_graph_t* g, ray_op_ext_t* ext) { + uint16_t stored_table_id = 0; + memcpy(&stored_table_id, ext->base.pad, sizeof(uint16_t)); + if (stored_table_id > 0 && g->tables && (stored_table_id - 1) < g->n_tables) + return g->tables[stored_table_id - 1]; + return g->table; +} + +/* A chained filter's refinement over a generation-2 predicate column: the + * predicate is evaluated on the segments the selection keeps, through the + * fused path's encoded leaves (views and vector statistics), and ANDed with + * the selection (exec_pred_refine_selection), so no predicate value is + * gathered. input (the selection replaced), an owned error (input + * released), or NULL: not such a predicate, or unsupported (the caller's + * gather runs). Out of line: exec_node_inner keeps its code. */ +static __attribute__((noinline)) ray_t* exec_filter_refine_enc(ray_graph_t* g, ray_op_t* op, ray_t* input) { + ray_op_t* pred_root = op_child(g, op, 1); + int64_t ks[32]; + bool has_expr = false; + uint32_t roots[1] = { pred_root->id }; + int nks = collect_scan_syms(g, roots, 1, ks, 32, &has_expr); + bool enc = false; + for (int i = 0; i < nks && !enc; i++) + enc = ray_col_gather_slot(ray_table_get_col_enc(input, ks[i])) != NULL; + if (!enc) return NULL; + bool ap = false; + ray_t* rs = exec_pred_refine_selection(g, pred_root, g->selection, &ap); + if (rs && RAY_IS_ERR(rs)) { ray_release(input); return rs; } + if (!rs && !ap) return NULL; + ray_release(g->selection); + g->selection = rs; /* NULL: every row passes */ + return input; +} + +/* ---- Chunk pruning of a conjunctive row filter over generation 2 ---- + * + * The optimizer splits `where: (and a b c)` into a chain of filters, each + * one predicate, and the first to run reads its column over every row: + * the per-morsel zone decision of one predicate never sees the others, so + * an equality on a hash column decodes the column whole although a + * conjunct on the table's sort column (CounterID == 62) excludes almost + * every chunk. Before the chain runs, its outermost filter decides every + * comparison or `in` conjunct of the chain on a single-file generation-2 + * numeric or temporal column from the directory statistics of each 64K-row + * chunk, then from the descriptors of the vectors of a chunk some conjunct + * left undecided, and installs the rows no conjunct excludes as the + * selection: every filter of the chain then runs as a chained filter over + * those rows (exec_filter_refine_enc reads only the vectors it keeps). A + * conjunct whose column carries a recorded HASH / SORT / PART / BLOOM index + * its shape would use (the index route of the first filter) leaves the + * chain alone, as does a pruning that keeps more than half of the rows. + * Generation 0 is never pruned here. */ +_Static_assert(RAY_ENC_VEC == RAY_MORSEL_ELEMS, "a selection segment is one encoded vector"); +_Static_assert(RAY_ENC_CHUNK == RAY_ENC_VEC * RAY_ENC_VECS_PER_CHUNK, "chunk geometry"); + +#define ZP_MAX_CONJ 16 +#define ZP_MAX_SET 64 + +typedef struct { + ray_col_src_t* src; /* borrowed from the graph's binds */ + const ray_enccol_t* e; + uint16_t op; /* OP_EQ .. OP_GE, or OP_IN */ + bool is_f; /* F32 / F64 column, key_f */ + int64_t key_i; + double key_f; + int64_t set[ZP_MAX_SET]; + int nset; +} zp_conj_t; + +static _Atomic(uint64_t) g_zp_calls, g_zp_segs; /* test hook */ +void ray_exec_test_zone_prune(uint64_t* calls, uint64_t* pruned_segs) { + *calls = atomic_load_explicit(&g_zp_calls, memory_order_relaxed); + *pruned_segs = atomic_load_explicit(&g_zp_segs, memory_order_relaxed); +} + +/* A literal comparable with a column of type ct as its raw logical value: + * an integer-family literal for an integer column, the same temporal type + * for a temporal column (another temporal literal is converted by the + * kernel), any non-null float or integer literal for a float column. */ +static bool zp_lit_ok(int8_t ct, int8_t lt) { + bool lint = lt == RAY_BOOL || lt == RAY_U8 || lt == RAY_I16 || lt == RAY_I32 || lt == RAY_I64; + switch (ct) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: return lint; + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: return lt == ct; + case RAY_F32: case RAY_F64: return lint || lt == RAY_F32 || lt == RAY_F64; + default: return false; + } +} + +/* One conjunct of the chain as a zp_conj_t: 1 accepted, 0 not a pruning + * conjunct (it stays a filter of the chain), -1 a conjunct whose recorded + * region index the chain's index route would use (no pruning), -2 an owned + * *err (a failed bind). */ +static int zp_conj_of(ray_graph_t* g, ray_op_t* p, zp_conj_t* out, ray_t** err) { + *err = NULL; + ray_col_meta_t m; + uint16_t op = 0; int64_t ki = 0; double kf = 0.0; int isf = 0; + ray_t* set = NULL; + bool is_in = false; + if (idx_filter_decode(g, p, IDXW_NONE, NULL, &op, &ki, &kf, &isf, &m)) { + if (m.enc && idx_enc_cmp_uses_index(&m, op, ki, isf) && ray_enc_idx_kind_has_region(m.index_kind)) + return -1; + } else if (idx_filter_in_decode(g, p, IDXW_NONE, NULL, &set, &m)) { + if (m.enc && idx_enc_in_uses_index(&m) && ray_enc_idx_kind_has_region(m.index_kind)) return -1; + is_in = true; + } else return 0; + if (!m.enc) return 0; + const ray_enccol_t* e = ray_enccol_of(m.enc); + if (!e || e->kind != RAY_ENCCOL_SINGLE || e->synthetic) return 0; + bool is_f = m.type == RAY_F32 || m.type == RAY_F64; + if (!zone_dir_type(m.type) && !is_f) return 0; + ray_op_t* rhs = op_child(g, p, 1); + ray_op_ext_t* rx = rhs ? find_ext(g, rhs->id) : NULL; + ray_t* lit = rx ? rx->literal : NULL; + if (!lit) return 0; + out->op = is_in ? OP_IN : op; + out->is_f = is_f; + out->key_i = ki; out->key_f = kf; out->nset = 0; + if (is_in) { + if (is_f || ray_is_atom(lit) || !zp_lit_ok(m.type, lit->type) || lit->len > ZP_MAX_SET) return 0; + for (int64_t i = 0; i < lit->len; i++) { + if (ray_vec_is_null(lit, i)) return 0; /* a null member: left to the filter */ + out->set[out->nset++] = read_col_i64(ray_data(lit), i, lit->type, lit->attrs); + } + } else { + if (!ray_is_atom(lit) || RAY_ATOM_IS_NULL(lit) || !zp_lit_ok(m.type, (int8_t)-lit->type)) return 0; + if (is_f && kf != kf) return 0; + } + int64_t sym = idx_conj_sym(g, p); + if (sym < 0) return 0; + ray_col_src_t* src = ray_graph_bind_col(g, g->table, sym, err); + if (*err) return -2; + if (!src || src->obj != m.enc) return 0; + out->src = src; + out->e = e; + return 1; +} + +/* One conjunct over extrema [mn, mx] (has_mm: present) of `rows` rows with + * nn nulls: 1 every row passes, 0 none does, -1 undecided. */ +static int zp_decide(const zp_conj_t* c, int64_t mn, int64_t mx, bool has_mm, int64_t nn, int64_t rows) { + bool all_null = nn == rows; + if (c->op == OP_IN) { + if (all_null || !has_mm || mn > mx) return -1; + for (int i = 0; i < c->nset; i++) + if (c->set[i] >= mn && c->set[i] <= mx) return -1; + return 0; /* a null row is in no set */ + } + if (c->is_f) { + double fmn, fmx; + memcpy(&fmn, &mn, 8); memcpy(&fmx, &mx, 8); + return zone_cmp_core_f64(fmn, fmx, has_mm, nn > 0, all_null, c->op, c->key_f); + } + return zone_cmp_core(mn, mx, has_mm, nn > 0, all_null, c->op, c->key_i); +} + +/* The chain under `top` (its outermost filter) prunes its rows: installs + * g->selection (NULL return), or leaves it NULL (no pruning); an owned + * error otherwise. */ +static __attribute__((noinline)) ray_t* exec_filter_chain_prune(ray_graph_t* g, ray_op_t* top) { + if (!g->table || g->table->type != RAY_TABLE || !filter_input_default_domain(g, top->id)) return NULL; + ray_op_t* conj[ZP_MAX_CONJ]; + int ncj = 0; + for (ray_op_t* f = top; f && f->opcode == OP_FILTER; f = op_child(g, f, 0)) { + if (f->arity != 2 || !ray_expr_subset_invariant(g, f->in_id[1])) return NULL; + ray_op_t* p = op_child(g, f, 1); + if (!p) return NULL; + ray_op_t* parts[ZP_MAX_CONJ]; + int np = idx_flatten_and(g, p, parts, ZP_MAX_CONJ); + if (np == 0) { parts[0] = p; np = 1; } + for (int i = 0; i < np; i++) { + if (ncj >= ZP_MAX_CONJ) return NULL; + conj[ncj++] = parts[i]; + } + } + if (ncj < 2) return NULL; /* one predicate: its own zone decision prunes it */ + const int64_t nrows = ray_table_nrows(g->table); + if (nrows < RAY_ENC_CHUNK) return NULL; + zp_conj_t zc[ZP_MAX_CONJ]; + int nz = 0; + for (int i = 0; i < ncj; i++) { + ray_t* err = NULL; + int rc = zp_conj_of(g, conj[i], &zc[nz], &err); + if (rc == -2) return err; + if (rc == -1) return NULL; + if (rc == 1 && zc[nz].e->len == nrows) nz++; + } + if (nz == 0) return NULL; + const int64_t n_segs = (nrows + RAY_ENC_VEC - 1) / RAY_ENC_VEC; + const int64_t n_chunks = (nrows + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + ray_t* hdr = NULL; + uint8_t* keep = (uint8_t*)scratch_alloc(&hdr, (size_t)n_segs); + if (!keep) return NULL; /* OOM: the chain runs unpruned */ + int64_t kept = 0; + for (int64_t ch = 0; ch < n_chunks; ch++) { + const int64_t s0 = ch * RAY_ENC_VECS_PER_CHUNK; + const int64_t s1 = s0 + RAY_ENC_VECS_PER_CHUNK < n_segs ? s0 + RAY_ENC_VECS_PER_CHUNK : n_segs; + bool dead = false; + int mixed[ZP_MAX_CONJ], nmixed = 0; + for (int k = 0; k < nz && !dead; k++) { + ray_enc_chunk_stat_t st; + ray_enccol_chunk_stat(zc[k].e, ch, &st); + int d = zp_decide(&zc[k], st.min, st.max, st.has_minmax, (int64_t)st.null_count, st.rows); + if (d == 0) dead = true; + else if (d < 0) mixed[nmixed++] = k; + } + for (int64_t s = s0; s < s1; s++) { + bool sdead = dead; + const int64_t rows = (s + 1) * RAY_ENC_VEC <= nrows ? RAY_ENC_VEC : nrows - s * RAY_ENC_VEC; + for (int j = 0; j < nmixed && !sdead; j++) { + int64_t mn, mx; uint32_t nn; + if (ray_col_src_vec_stat(zc[mixed[j]].src, s, &mn, &mx, &nn) && + zp_decide(&zc[mixed[j]], mn, mx, true, (int64_t)nn, rows) == 0) + sdead = true; + } + keep[s] = !sdead; + if (!sdead) kept += rows; + } + } + ray_t* sel = NULL; + if (kept * 2 <= nrows) { + int64_t pruned = 0; + sel = ray_rowsel_new(nrows, kept, 0); + if (sel) { + uint8_t* fl = ray_rowsel_flags(sel); + uint32_t* off = ray_rowsel_offsets(sel); + for (int64_t s = 0; s < n_segs; s++) { + fl[s] = keep[s] ? RAY_SEL_ALL : RAY_SEL_NONE; + off[s] = 0; + pruned += !keep[s]; + } + off[n_segs] = 0; + atomic_fetch_add_explicit(&g_zp_calls, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&g_zp_segs, (uint64_t)pruned, memory_order_relaxed); + } + } + scratch_free(hdr); + g->selection = sel; + return NULL; +} + +/* A whole-vector reader (running, moving, order, distinct) reads every row of + * its input, rows a lazy selection drops included. Producers evaluated under a + * selection may leave those rows unwritten (par_binary_fn skips NONE blocks, + * the SYM like kernel skips dropped rows, `if` zero-fills them), so the input + * is evaluated with the selection cleared and comes back at full length, as + * the group path does for a declined input (group.c). As for an `if` branch + * (pivot.c), the input gets a memo of its own: a shared node's value depends + * on the rows it was computed over, so neither domain may serve the other's. + * A selection the input installs (a FILTER child) is the input's to drop. */ +static ray_t* exec_node_all_rows(ray_graph_t* g, ray_op_t* child) { + ray_t* saved = g->selection; + if (!saved) return exec_node(g, child); + g->selection = NULL; + ray_exec_memo_save_t memo_save; + ray_exec_memo_push(g, child, &memo_save); + ray_t* v = exec_node(g, child); + ray_exec_memo_pop(g, &memo_save); + if (g->selection) ray_release(g->selection); + g->selection = saved; + return v; +} + static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (!op) return ray_error("nyi", NULL); @@ -2258,57 +3714,22 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_op_ext_t* ext = find_ext(g, op->id); if (!ext) return ray_error("nyi", NULL); - /* Resolve table: pad[0..1] stores table_id+1 (0 = default g->table) */ - uint16_t stored_table_id = 0; - memcpy(&stored_table_id, ext->base.pad, sizeof(uint16_t)); - ray_t* scan_tbl; - if (stored_table_id > 0 && g->tables && (stored_table_id - 1) < g->n_tables) { - scan_tbl = g->tables[stored_table_id - 1]; - } else { - scan_tbl = g->table; - } + ray_t* scan_tbl = scan_table_of(g, ext); if (!scan_tbl) return ray_error("schema", NULL); - ray_t* col = ray_table_get_col(scan_tbl, ext->sym); + ray_t* col = ray_table_col(scan_tbl, ext->sym); if (!col) return ray_error("schema", NULL); + if (RAY_IS_ERR(col)) return col; /* a failed decode keeps its own code and message */ if (col->type == RAY_MAPCOMMON) return materialize_mapcommon(col); if (RAY_IS_PARTED(col->type)) { - /* Concat parted segments into flat vector (cold path) */ - int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); - ray_t** sps = (ray_t**)ray_data(col); - int64_t total = ray_parted_nrows(col); - - /* RAY_STR: deep-copy to handle multi-pool segments */ - if (base == RAY_STR) - return parted_flatten_str(sps, col->len, total); - /* RAY_LIST: share (retain) elements — byte-copy would - * alias them without a refcount (issue #355). */ - if (base == RAY_LIST) - return parted_flatten_list(sps, col->len, total); - - uint8_t sba = (base == RAY_SYM) - ? parted_sym_max_attrs(sps, col->len) : 0; - ray_t* flat = typed_vec_new(base, sba, total); - if (!flat || RAY_IS_ERR(flat)) - return flat ? flat : ray_error("oom", NULL); - flat->len = total; - ray_t** segs = sps; - int64_t off = 0; - uint8_t seg_nulls = 0; - for (int64_t s = 0; s < col->len; s++) { - if (!segs[s] || segs[s]->len <= 0) continue; - parted_copy_cells(ray_data(flat), base, sba, off, - segs[s], 0, segs[s]->len); - seg_nulls |= segs[s]->attrs & RAY_ATTR_HAS_NULLS; - off += segs[s]->len; + /* Concat parted segments into a flat vector (cold path); + * the table's partition counts give a missing segment its + * rows as typed nulls (ragged parted table). */ + { + ray_t* f = flatten_parted_col(col, scan_tbl); + PARTED_FLAT_DCHECK(scan_tbl, f); + return f; } - /* Null propagation: propagate HAS_NULLS across segments. */ - flat->attrs |= seg_nulls; - /* Raw-copied SYM cell ids resolve over the partitions' - * shared domain (first SYM segment is the rep). */ - if (flat->type == RAY_SYM) - ray_sym_vec_adopt_domain(flat, sym_domain_rep(col)); - return flat; } ray_retain(col); return col; @@ -2350,9 +3771,14 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t nr = ray_table_nrows(g->table); if (nr > 0) { ray_expr_t ex; - if (expr_compile(g, g->table, op, &ex)) { + ray_t* cerr = NULL; + if (expr_compile(g, g->table, op, &ex, &cerr)) { ray_t* vec = expr_eval_full(&ex, nr); if (vec && !RAY_IS_ERR(vec)) return vec; + if (expr_eval_err_fatal(vec)) return vec; /* a range read failed */ + if (vec) ray_error_free(vec); /* oom: per-node eval */ + } else if (cerr) { + return cerr; } } } @@ -2368,7 +3794,33 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { case OP_MIN: case OP_MAX: case OP_COUNT: case OP_AVG: case OP_FIRST: case OP_LAST: case OP_STDDEV: case OP_STDDEV_POP: case OP_VAR: case OP_VAR_POP: { - ray_t* input = exec_node(g, op_child(g, op, 0)); + /* A reduction of an encoded column's scan, no selection: reduce + * the bound source (directory answer or range reads) instead of + * materializing it. A table without an encoded slot never + * enters (sm.enc is NULL). With a selection installed the + * reduction must read only the selected rows (exec_reduction's + * selection branch); no language shape reaches this arm with one + * today (a select with a where takes the group path), so that + * case keeps the plain path rather than going untested. */ + ray_op_t* child = op_child(g, op, 0); + if (child && child->opcode == OP_SCAN && !g->selection) { + ray_op_ext_t* se = find_ext(g, child->id); + ray_t* scan_tbl = se ? scan_table_of(g, se) : NULL; + ray_col_meta_t sm; + if (scan_tbl && ray_table_col_meta(scan_tbl, se->sym, &sm) && sm.enc && + !ray_col_bind_declines(scan_tbl, se->sym)) { + ray_t* berr = NULL; + ray_col_src_t* src = ray_graph_bind_col(g, scan_tbl, se->sym, &berr); + if (berr) return berr; + if (src) { + if (src->type > 0 && !agg_type_admitted(op->opcode, src->type)) + return ray_error("type", "aggregate: element type not admitted for this aggregation, got %s", ray_type_name(src->type)); + ray_t* r = exec_reduction_src(g, op, src); + if (r) return r; /* NULL: type not served, plain path below */ + } + } + } + ray_t* input = exec_node(g, child); if (!input || RAY_IS_ERR(input)) return input; /* Compact lazy selection before reducing — filters may have * set g->selection without materializing a compacted table. */ @@ -2396,11 +3848,37 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } } ray_t* result = exec_reduction(g, op, input); - if (own_input) ray_release(input); + if (own_input) exec_release_tmp(g, input); return result; } case OP_COUNT_DISTINCT: { + /* The scan of a single-file encoded column not decoded yet + * whose whole decode would not stay cached + * (ray_enccol_decode_kept), no selection: counted in bounded + * memory reading the column by range (ray_cd_bounded_all) + * instead of decoding it whole and scattering every row. + * Integer, temporal and SYM columns; any other keeps the plain + * path. */ + ray_op_t* cchild = op_child(g, op, 0); + if (cchild && cchild->opcode == OP_SCAN && !g->selection) { + ray_op_ext_t* se = find_ext(g, cchild->id); + ray_t* scan_tbl = se ? scan_table_of(g, se) : NULL; + ray_col_meta_t sm; + if (scan_tbl && ray_table_col_meta(scan_tbl, se->sym, &sm) && sm.enc && + !RAY_IS_PARTED(sm.type) && !ray_enccol_decoded_peek(sm.enc) && + !ray_enccol_decode_kept(sm.enc) && !ray_col_bind_declines(scan_tbl, se->sym)) { + switch (sm.type) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_SYM: { + ray_t* r = sm.len > 0 ? ray_cd_bounded_all(sm.enc, sm.len) : ray_i64(0); + if (r) return r; /* NULL: not served, plain path below */ + break; + } + default: break; + } + } + } ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; ray_t* result = exec_count_distinct(g, op, input); @@ -2409,7 +3887,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } case OP_DISTINCT: { - ray_t* input = exec_node(g, op_child(g, op, 0)); + ray_t* input = exec_node_all_rows(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; if (!ray_is_vec(input)) { ray_release(input); @@ -2421,7 +3899,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } case OP_ASC: { - ray_t* input = exec_node(g, op_child(g, op, 0)); + ray_t* input = exec_node_all_rows(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; if (!ray_is_vec(input)) { ray_release(input); @@ -2433,7 +3911,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } case OP_DESC: { - ray_t* input = exec_node(g, op_child(g, op, 0)); + ray_t* input = exec_node_all_rows(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; if (!ray_is_vec(input)) { ray_release(input); @@ -2445,7 +3923,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } case OP_REVERSE: { - ray_t* input = exec_node(g, op_child(g, op, 0)); + ray_t* input = exec_node_all_rows(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; if (!ray_is_vec(input)) { ray_release(input); @@ -2461,7 +3939,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { case OP_MAXS: case OP_PRDS: case OP_DIFFER: case OP_MSUM: case OP_MAVG: case OP_MMIN: case OP_MMAX: case OP_MCOUNT: case OP_MVAR: case OP_MDEV: { - ray_t* input = exec_node(g, op_child(g, op, 0)); + ray_t* input = exec_node_all_rows(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; if (!ray_is_vec(input)) { ray_release(input); @@ -2530,6 +4008,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { return result; } + /* The outermost filter of a chain prunes the chain's rows from + * its conjuncts' chunk statistics (generation 2) before the + * first one runs. */ + if (tl_filter_depth == 1 && !g->selection) { + ray_t* perr = exec_filter_chain_prune(g, op); + if (perr) return perr; + } ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; /* A verified physically-sorted column remains routable even when @@ -2542,8 +4027,8 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t ski = 0; double skf = 0.0; int sisf = 0; - if (idx_filter_decode(g, op_child(g, op, 1), &scol, &sop, - &ski, &skf, &sisf) && + if (idx_filter_decode(g, op_child(g, op, 1), IDXW_SORTED, + &scol, &sop, &ski, &skf, &sisf, NULL) && sop != OP_NE && ray_attr_is_sorted(scol)) { ray_idx_consults[IDX_SITE_FILTER_RANGE]++; ray_t* ssel = ray_sorted_range_rowsel(scol, sop, ski, skf, @@ -2576,25 +4061,105 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { * pre-existing selection (the entry shape downstream * group-by / sort already expects). */ if (input->type == RAY_TABLE && !g->selection) { + /* A symbol missing from the column's domain selects no rows, + * indexed or not. Decided from the domain alone: a generation-2 + * column is never decoded to learn that. */ + { + uint16_t pc = 0; int64_t pk = 0; double pf = 0.0; int pif = 0; + ray_col_meta_t pm; + if (idx_filter_decode(g, op_child(g, op, 1), IDXW_NONE, NULL, &pc, + &pk, &pf, &pif, &pm) && + pm.type == RAY_SYM && pc == OP_EQ && !pif && pk != 0) { + ray_op_t* sl = op_child(g, op_child(g, op, 1), 0); + ray_op_ext_t* sx = sl ? find_ext(g, sl->id) : NULL; + struct ray_sym_domain_s* dom = NULL; + if (pm.enc) { + ray_enccol_t* ee = ray_enccol_of(pm.enc); + if (ee) dom = ee->dom; + } else if (sx) { + ray_t* pcol = ray_table_col(g->table, sx->sym); + if (pcol && RAY_IS_ERR(pcol)) ray_error_free(pcol); + else if (pcol) dom = ray_sym_vec_domain(pcol); + } + ray_t* ps = dom ? ray_sym_str(pk) : NULL; + if (ps && ray_sym_domain_find(dom, ray_str_ptr(ps), ray_str_len(ps)) < 0) { + ray_t* empty = ray_index_empty_rowsel(ray_table_nrows(input)); + if (empty) { g->selection = empty; return input; } + } + } + } ray_t* col = NULL; uint16_t cmp_op = 0; int64_t key_i = 0; double key_f = 0.0; int is_float = 0; - if (idx_filter_decode(g, op_child(g, op, 1), &col, &cmp_op, - &key_i, &key_f, &is_float)) { + /* A generation-2 column without a published materialization + * is consulted from its directory (finding C1) and never + * decoded here, unless the shape uses its recorded HASH / + * SORT / BLOOM / PART (idx_enc_cmp_uses_index): that column + * is materialized now (its failure is the query's) and, like + * a published one, takes the block below on its + * materialization, which carries the attached index. */ + ray_col_meta_t fm; + bool enc_done = false; + bool fm_ok = idx_filter_decode(g, op_child(g, op, 1), IDXW_INDEX, NULL, &cmp_op, + &key_i, &key_f, &is_float, &fm); + bool fm_uses = fm_ok && fm.enc && idx_enc_cmp_uses_index(&fm, cmp_op, key_i, is_float); + /* An equality on a recorded HASH not yet materialized probes + * the region where it is mapped (ray_enc_hash_eq_rowsel): + * the column is not decoded and the region not copied. A + * declined probe (a dense key) materializes as below. */ + if (fm_uses && fm.index_kind == RAY_IDX_HASH && cmp_op == OP_EQ && !is_float && + !ray_enccol_decoded_peek(fm.enc)) { + int64_t hk = key_i; + bool hk_ok = true; + if (fm.type == RAY_SYM) { /* global intern id -> the column's domain id */ + ray_enccol_t* he = ray_enccol_of(fm.enc); + ray_t* hs = he && he->dom ? ray_sym_str(key_i) : NULL; + hk = hs ? ray_sym_domain_find(he->dom, ray_str_ptr(hs), ray_str_len(hs)) : -1; + hk_ok = hk > 0; + } + if (hk_ok) { + ray_idx_consults[IDX_SITE_FILTER_HASH]++; + ray_t* hsel = NULL; ray_t* herr = NULL; + int hrc = ray_enc_hash_eq_rowsel(fm.enc, hk, &hsel, &herr); + if (hrc < 0) { ray_release(input); return herr; } + if (hrc == 1) { + ray_idx_hits[IDX_SITE_FILTER_HASH]++; + ray_idx_note_use_enc(fm.enc); + g->selection = hsel; + return input; + } + } + } + if (fm_ok && idx_enc_from_dir(&fm, fm_uses)) { + enc_done = true; + ray_t* esel = NULL; ray_t* eerr = NULL; + int rc = idx_filter_enc_consult(fm.enc, &fm, cmp_op, key_i, key_f, is_float, + ray_table_nrows(input), &esel, &eerr); + if (rc < 0) { ray_release(input); return eerr; } + if (rc == 1) return input; + if (rc == 2) { g->selection = esel; return input; } + } else if (fm_uses) { + ray_t* merr = idx_enc_index_ready(g, &fm, idx_conj_sym(g, op_child(g, op, 1))); + if (merr) { ray_release(input); return merr; } + } + if (!enc_done && idx_filter_decode(g, op_child(g, op, 1), IDXW_INDEX, &col, &cmp_op, + &key_i, &key_f, &is_float, NULL)) { /* 1. Zone index: O(1) all/none short-circuit. */ if (ray_index_kind(col) == RAY_IDX_ZONE) ray_idx_consults[IDX_SITE_FILTER_ZONE]++; switch (ray_index_zone_class(col, cmp_op, key_i, key_f)) { case RAY_ZONE_ALL: ray_idx_hits[IDX_SITE_FILTER_ZONE]++; + ray_idx_note_use(col); /* All rows pass — mirror the lazy path: leave * g->selection NULL (no filter) and return the * table. Same ownership as the hash path below. */ return input; case RAY_ZONE_NONE: { ray_idx_hits[IDX_SITE_FILTER_ZONE]++; + ray_idx_note_use(col); int64_t nrows = ray_table_nrows(input); ray_t* empty = ray_index_empty_rowsel(nrows); if (empty) { g->selection = empty; return input; } @@ -2612,6 +4177,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* empty = ray_index_empty_rowsel(nrows); if (empty) { ray_idx_hits[IDX_SITE_FILTER_BLOOM]++; + ray_idx_note_use(col); g->selection = empty; return input; } @@ -2653,6 +4219,30 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } if (!sym_probe_skip) { ray_idx_kind_t eq_kind = ray_index_kind(col); + /* No persisted hash: an unprunable integer zone + * gets the lazy in-memory one (built on this first + * point lookup, reused after). The indexed copy + * has the table column's rows. */ + /* A key outside the chunk zone's whole range + * matches nothing: answered here, nothing built. */ + if (eq_kind != RAY_IDX_HASH && eq_kind != RAY_IDX_PART && + ray_idx_zone_excludes(col, key_i)) { + ray_idx_consults[IDX_SITE_FILTER_ZONE]++; + ray_t* empty = ray_index_empty_rowsel(ray_table_nrows(input)); + if (empty) { + ray_idx_hits[IDX_SITE_FILTER_ZONE]++; + ray_idx_note_use(col); + g->selection = empty; + return input; + } + } + ray_t* lazy_col = NULL; + if (eq_kind != RAY_IDX_HASH && eq_kind != RAY_IDX_PART) { + ray_t* le = idx_lazy_err(ray_idx_lazy_hash(col, &lazy_col)); + if (le) { ray_release(input); return le; } + if (lazy_col) eq_kind = RAY_IDX_HASH; + } + ray_t* probe_col = lazy_col ? lazy_col : col; if (eq_kind == RAY_IDX_HASH || eq_kind == RAY_IDX_PART) { idx_site_t site = eq_kind == RAY_IDX_HASH @@ -2660,14 +4250,17 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { : IDX_SITE_FILTER_PART; ray_idx_consults[site]++; ray_t* sel = eq_kind == RAY_IDX_HASH - ? ray_index_hash_eq_rowsel(col, key_i) - : ray_index_part_eq_rowsel(col, key_i); + ? ray_index_hash_eq_rowsel(probe_col, key_i) + : ray_index_part_eq_rowsel(probe_col, key_i); if (sel) { ray_idx_hits[site]++; + ray_idx_note_use(probe_col); + if (lazy_col) ray_release(lazy_col); g->selection = sel; return input; } } + if (lazy_col) ray_release(lazy_col); /* sel == NULL: ineligible (wrong/stale index kind, * key out of range) or OOM — fall through to scan. */ } @@ -2686,6 +4279,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { (bool)is_float); if (sel) { ray_idx_hits[IDX_SITE_FILTER_RANGE]++; + ray_idx_note_use(col); g->selection = sel; return input; } @@ -2710,20 +4304,61 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t eq_key = 0; int64_t lo = INT64_MIN, hi = INT64_MAX; bool shape_ok = (ncj >= 2); + /* Metadata first: a conjunct list without an equality on a + * hash-indexed column decodes nothing. */ + bool has_hash_eq = false; + ray_t* eq_enc = NULL; + ray_t* eq_lazy = NULL; + for (int ci = 0; ci < ncj && shape_ok && !has_hash_eq; ci++) { + uint16_t cop = 0; ray_col_meta_t cm; + int64_t ki = 0; double kf = 0.0; int isf = 0; + has_hash_eq = idx_filter_decode(g, conj[ci], IDXW_NONE, NULL, &cop, + &ki, &kf, &isf, &cm) && + cop == OP_EQ && (cm.index_kind == RAY_IDX_HASH || + idx_lazy_meta_ok(&cm)); + if (has_hash_eq && cm.enc && !ray_enccol_decoded_peek(cm.enc) && + cm.index_kind != RAY_IDX_HASH) + eq_enc = cm.enc; + /* a recorded HASH materializes for its index only + * when the whole shape is the one the decode below + * takes (else nothing is decoded); its failure is + * the query's, and the decode loop reads it */ + if (has_hash_eq && cm.enc && cm.index_kind == RAY_IDX_HASH && + !ray_enccol_decoded_peek(cm.enc)) { + if (!idx_eqrange_meta_ok(g, conj, ncj)) { shape_ok = false; break; } + ray_t* merr = idx_enc_index_ready(g, &cm, idx_conj_sym(g, conj[ci])); + if (merr) { ray_release(input); return merr; } + } + } + shape_ok = shape_ok && has_hash_eq; + /* Finding C1: a generation-2 equality column is probed + * (and its lazy HASH built, materializing it) before any + * conjunct column is decoded, once the metadata shows + * the shape the decode below accepts; while the probe is + * still pending the scan answers and nothing is decoded. */ + if (shape_ok && eq_enc) { + if (!idx_eqrange_meta_ok(g, conj, ncj)) shape_ok = false; + else { + ray_t* le = idx_lazy_err(ray_idx_lazy_hash_enc(eq_enc, &eq_lazy)); + if (le) { ray_release(input); return le; } + if (!eq_lazy) shape_ok = false; + } + } for (int ci = 0; ci < ncj && shape_ok; ci++) { - ray_t* c = NULL; uint16_t cop = 0; + ray_t* c = NULL; uint16_t cop = 0; ray_col_meta_t dm; int64_t ki = 0; double kf = 0.0; int isf = 0; - if (!idx_filter_decode(g, conj[ci], &c, &cop, - &ki, &kf, &isf) || isf) { + if (!idx_filter_decode(g, conj[ci], IDXW_NONE, &c, &cop, + &ki, &kf, &isf, &dm) || isf) { shape_ok = false; break; } + bool c_nulls = idx_conj_may_null(g, &dm, idx_conj_sym(g, conj[ci])); if (cop == OP_EQ && !eq_col && - ray_index_kind(c) == RAY_IDX_HASH && - (c->type == RAY_SYM ? ki != 0 : !ray_vec_may_have_nulls(c))) { + (ray_index_kind(c) == RAY_IDX_HASH || ray_idx_lazy_hash_wanted(c)) && + (c->type == RAY_SYM ? ki != 0 : !c_nulls)) { eq_col = c; eq_key = ki; } else if (cop == OP_GE || cop == OP_GT || cop == OP_LE || cop == OP_LT) { - if (ray_vec_may_have_nulls(c)) { shape_ok = false; break; } + if (c_nulls) { shape_ok = false; break; } if (!rg_col) rg_col = c; else if (rg_col != c) { shape_ok = false; break; } if (cop == OP_GE) { if (ki > lo) lo = ki; } @@ -2732,6 +4367,18 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { else { if (ki == INT64_MIN) { lo = 1; hi = 0; } else if (ki - 1 < hi) hi = ki - 1; } } else { shape_ok = false; break; } } + /* The equality column without a persisted hash probes + * its lazy one, built only now that the whole shape + * matched (a generation-2 one was probed above, and its + * build published the materialization the decode read); + * the range column stays the table's. */ + if (shape_ok && eq_col && rg_col && rg_col != eq_col && !eq_lazy && + ray_index_kind(eq_col) != RAY_IDX_HASH) { + ray_t* le = idx_lazy_err(ray_idx_lazy_hash(eq_col, &eq_lazy)); + if (le) { ray_release(input); return le; } + if (!eq_lazy) shape_ok = false; + } + if (eq_lazy) eq_col = eq_lazy; if (shape_ok && eq_col && rg_col && rg_col != eq_col) { ray_idx_consults[IDX_SITE_FILTER_EQRANGE]++; /* SYM eq: global intern id -> this column's domain @@ -2758,6 +4405,8 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* sel = ray_index_rowsel_from_ids(nrows, NULL, 0); if (sel) { ray_idx_hits[IDX_SITE_FILTER_EQRANGE]++; + ray_idx_note_use(eq_col); + if (eq_lazy) ray_release(eq_lazy); g->selection = sel; return input; } @@ -2791,6 +4440,8 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { nrows, ray_idx_rows_from(grows, startp), a - startp); if (sel) { ray_idx_hits[IDX_SITE_FILTER_EQRANGE]++; + ray_idx_note_use(eq_col); + if (eq_lazy) ray_release(eq_lazy); g->selection = sel; return input; } @@ -2799,6 +4450,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } /* hit < 0 (stale/ineligible index): fall through */ } + if (eq_lazy) ray_release(eq_lazy); } /* 5. Hash/part-index IN probe: @@ -2808,21 +4460,70 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { { ray_t* in_col = NULL; ray_t* in_set_lit = NULL; - if (idx_filter_in_decode(g, op_child(g, op, 1), &in_col, &in_set_lit)) { + /* generation 2 without a published materialization: + * from the directory, never decoded here, unless the + * `in` uses its recorded HASH / PART + * (idx_enc_in_uses_index): that column materializes now + * (its failure the query's) and takes the block below on + * its index */ + ray_col_meta_t im; + bool in_enc_done = false; + bool im_ok = idx_filter_in_decode(g, op_child(g, op, 1), IDXW_INDEX, NULL, &in_set_lit, &im); + bool im_uses = im_ok && im.enc && idx_enc_in_uses_index(&im); + if (im_ok && idx_enc_from_dir(&im, im_uses)) { + in_enc_done = true; + ray_t* isel = NULL; ray_t* ierr = NULL; + int rc = idx_filter_enc_in_consult(im.enc, &im, in_set_lit, + ray_table_nrows(input), &isel, &ierr); + if (rc < 0) { ray_release(input); return ierr; } + if (rc == 2) { g->selection = isel; return input; } + } else if (im_uses) { + ray_t* merr = idx_enc_index_ready(g, &im, idx_conj_sym(g, op_child(g, op, 1))); + if (merr) { ray_release(input); return merr; } + } + if (!in_enc_done && + idx_filter_in_decode(g, op_child(g, op, 1), IDXW_INDEX, &in_col, &in_set_lit, NULL)) { bool in_col_is_float = (in_col->type == RAY_F32 || in_col->type == RAY_F64); ray_idx_kind_t in_kind = ray_index_kind(in_col); + /* No persisted index: a small integer set on an + * unprunable zone probes the lazy in-memory hash. */ + if (in_kind != RAY_IDX_HASH && in_kind != RAY_IDX_PART && + !in_col_is_float && !ray_vec_may_have_nulls(in_col) && + ray_idx_zone_excludes_set(in_col, in_set_lit)) { + /* every element outside the zone's range */ + ray_idx_consults[IDX_SITE_FILTER_ZONE]++; + ray_t* empty = ray_index_empty_rowsel(ray_table_nrows(input)); + if (empty) { + ray_idx_hits[IDX_SITE_FILTER_ZONE]++; + ray_idx_note_use(in_col); + g->selection = empty; + return input; + } + } + ray_t* in_lazy = NULL; + if (in_kind != RAY_IDX_HASH && in_kind != RAY_IDX_PART && + !in_col_is_float && !ray_vec_may_have_nulls(in_col) && + idx_lazy_set_ok(in_col, in_set_lit)) { + ray_t* le = idx_lazy_err(ray_idx_lazy_hash(in_col, &in_lazy)); + if (le) { ray_release(input); return le; } + if (in_lazy) in_kind = RAY_IDX_HASH; + } + ray_t* in_probe = in_lazy ? in_lazy : in_col; if ((in_kind == RAY_IDX_HASH || in_kind == RAY_IDX_PART) && !in_col_is_float) { ray_idx_consults[IDX_SITE_IN]++; - ray_t* sel = ray_index_in_rowsel(in_col, in_set_lit); + ray_t* sel = ray_index_in_rowsel(in_probe, in_set_lit); if (sel) { ray_idx_hits[IDX_SITE_IN]++; + ray_idx_note_use(in_probe); + if (in_lazy) ray_release(in_lazy); g->selection = sel; return input; } /* NULL: guard fired, ineligible, or OOM — fall through. */ } + if (in_lazy) ray_release(in_lazy); } } @@ -2830,14 +4531,18 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { * expr-evaluable BOOL subtree, stream its per-morsel bools * straight into a rowsel — skipping both the full BOOL vec and * the second BOOL→rowsel scan. Any unsupported shape (parted, - * >RAY_POOL_MAX_TASKS, OOM) returns NULL+all_pass=false, - * falling through to the bool path. */ + * OOM) returns NULL+all_pass=false, falling through to the + * bool path. */ ray_op_t* pred_root = op_child(g, op, 1); { int64_t fnrows = ray_table_nrows(input); bool all_pass = false; ray_t* fsel = exec_pred_to_selection(g, pred_root, fnrows, &all_pass); + if (fsel && RAY_IS_ERR(fsel)) { /* a failed bind or range read, an oom, a cancel */ + ray_release(input); + return fsel; + } if (fsel || all_pass) { g->selection = fsel; /* NULL when all rows pass */ return input; @@ -2856,6 +4561,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { * survivors — O(survivors). Any ineligibility (non-scalar * predicate shape, OOM, unexpected result) falls through to * the full-width path unchanged. */ + /* Over a generation-2 predicate column the refinement reads no + * gathered values (exec_filter_refine_enc); generation 0 keeps + * the gather below. */ + if (input->type == RAY_TABLE && g->selection && input == g->table) { + ray_t* rs = exec_filter_refine_enc(g, op, input); + if (rs) return rs; /* input (refined), or an owned error */ + } if (input->type == RAY_TABLE && g->selection) { ray_rowsel_t* smeta = ray_rowsel_meta(g->selection); int64_t fr_nrows = ray_table_nrows(input); @@ -2867,6 +4579,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { uint32_t roots[1] = { pred_root->id }; int nkeep = collect_scan_syms(g, roots, 1, keep, 32, &has_expr); + if (nkeep <= 0) nkeep = refine_in_keep(g, pred_root, input, keep); if (nkeep > 0) { ray_t* sub = sel_compact(g, input, g->selection, keep, nkeep); @@ -2920,6 +4633,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } if (pv && !RAY_IS_ERR(pv)) ray_release(pv); else if (pv) ray_error_free(pv); + ray_graph_unbind_table(g, sub); ray_release(sub); if (done_refine) return input; } else if (sub && sub != input) { @@ -2931,6 +4645,23 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } } + /* A later `in` conjunct over a generation-2 column (parted: + * segment by segment; single-file: by range) read over the + * morsels the installed selection keeps, ANDed with it + * (exec_in_parted_selection), instead of a bool vector over the + * column read whole. */ + if (input->type == RAY_TABLE && g->selection && input == g->table) { + bool in_all = false; + ray_t* isel = exec_in_parted_selection(g, op_child(g, op, 1), ray_table_nrows(input), + g->selection, &in_all); + if (isel && RAY_IS_ERR(isel)) { ray_release(input); return isel; } + if (isel || in_all) { + ray_rowsel_release(g->selection); + g->selection = isel; /* NULL: every row passes both */ + return input; + } + } + ray_t* pred = exec_node(g, op_child(g, op, 1)); if (!pred || RAY_IS_ERR(pred)) { ray_release(input); return pred; } @@ -2999,14 +4730,34 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { /* Compact lazy selection before sort (needs dense data) */ if (g->selection && tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, tbl, g->selection, NULL, 0); + /* sel_compact's alloc fallback hands back the table itself: + * sorting it would answer from rows the selection dropped */ + if (compacted && !RAY_IS_ERR(compacted) && + ray_table_nrows(compacted) != ray_rowsel_meta(g->selection)->total_pass) { + ray_release(compacted); + compacted = ray_error("oom", NULL); + } ray_release(input); ray_release(g->selection); g->selection = NULL; input = compacted; tbl = compacted; } + /* An all-pass where: leaves no selection and hands over the + * source itself; a parted source still has segmented columns, + * which the sort cannot gather. Sort a flattened copy, as the + * partial-where path above does. */ + if (!g->selection && tbl && tbl->type == RAY_TABLE) { + ray_t* flat = flatten_parted_table(tbl, g->table); + if (flat) { + ray_release(input); + if (RAY_IS_ERR(flat)) return flat; + input = flat; + tbl = flat; + } + } ray_t* result = exec_sort(g, op, tbl, 0); - ray_release(input); + exec_release_tmp(g, input); return result; } @@ -3072,7 +4823,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (g->sg_col) { ray_t* serr = ray_group_slice_hint_settle(g, op, tbl, 0); if (serr) { - if (owned_tbl) ray_release(owned_tbl); + if (owned_tbl) { ray_graph_unbind_table(g, owned_tbl); ray_release(owned_tbl); } return serr; } } @@ -3121,7 +4872,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { keep, nkeep); if (compacted && !RAY_IS_ERR(compacted) && compacted != tbl) { - if (owned_tbl) ray_release(owned_tbl); + if (owned_tbl) { ray_graph_unbind_table(g, owned_tbl); ray_release(owned_tbl); } owned_tbl = compacted; tbl = compacted; ray_release(g->selection); @@ -3142,7 +4893,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { * downstream ops (SORT etc.) don't try to sel_compact the * aggregated output with a mismatched-length bitmap. */ ray_t* result = exec_group(g, op, tbl, 0); - if (owned_tbl) ray_release(owned_tbl); + if (owned_tbl) { ray_graph_unbind_table(g, owned_tbl); ray_release(owned_tbl); } if (g->selection) { ray_release(g->selection); g->selection = NULL; @@ -3162,7 +4913,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { tbl = compacted; } ray_t* result = exec_pivot(g, op, tbl); - if (owned_tbl) ray_release(owned_tbl); + if (owned_tbl) { ray_graph_unbind_table(g, owned_tbl); ray_release(owned_tbl); } return result; } @@ -3180,7 +4931,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { left = compacted; } ray_t* result = exec_join(g, op, left, right); - ray_release(left); + exec_release_tmp(g, left); ray_release(right); return result; } @@ -3198,7 +4949,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { left = compacted; } ray_t* result = exec_antijoin(g, op, left, right); - ray_release(left); + exec_release_tmp(g, left); ray_release(right); return result; } @@ -3216,7 +4967,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { left = compacted; } ray_t* result = exec_window_join(g, op, left, right); - ray_release(left); + exec_release_tmp(g, left); ray_release(right); return result; } @@ -3236,7 +4987,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { wdf = compacted; } ray_t* result = exec_window(g, op, wdf); - ray_release(input); + exec_release_tmp(g, input); return result; } @@ -3252,17 +5003,43 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* sort_input = exec_node(g, op_child(g, child_op, 0)); if (!sort_input || RAY_IS_ERR(sort_input)) return sort_input; ray_t* tbl = (sort_input->type == RAY_TABLE) ? sort_input : g->table; - /* Compact lazy selection before sort */ + /* Under a lazy selection, the keys first and only the + * winners' rows of the other columns (late + * materialization); else compact the table and sort */ + if (g->selection && tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { + ray_t* late = exec_sort_head_sel(g, child_op, tbl, g->selection, n); + if (late) { + ray_release(sort_input); /* owned: see OP_SORT */ + ray_release(g->selection); + g->selection = NULL; + return late; + } + } if (g->selection && tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { ray_t* compacted = sel_compact(g, tbl, g->selection, NULL, 0); + if (compacted && !RAY_IS_ERR(compacted) && /* the alloc fallback: see OP_SORT */ + ray_table_nrows(compacted) != ray_rowsel_meta(g->selection)->total_pass) { + ray_release(compacted); + compacted = ray_error("oom", NULL); + } ray_release(sort_input); /* owned: see OP_SORT */ ray_release(g->selection); g->selection = NULL; sort_input = compacted; tbl = compacted; } + /* All-pass where: over a parted source: see OP_SORT */ + if (!g->selection && tbl && tbl->type == RAY_TABLE) { + ray_t* flat = flatten_parted_table(tbl, g->table); + if (flat) { + ray_release(sort_input); + if (RAY_IS_ERR(flat)) return flat; + sort_input = flat; + tbl = flat; + } + } ray_t* result = exec_sort(g, child_op, tbl, n); - ray_release(sort_input); + exec_release_tmp(g, sort_input); /* Top-level statement GC catches intermediates. */ return result; } @@ -3289,7 +5066,8 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (res) { owned_tbl = res; tbl = res; } /* NULL → lazy path; g->selection installed, tbl unchanged */ } else if (g->selection && tbl->type == RAY_TABLE && - group_has_keys(g, child_op)) { + group_has_keys(g, child_op) && + !group_reads_vector_const(g, find_ext(g, child_op->id))) { /* A keyless group (an all-aggregate select) is one row * whatever the limit, and its aggregates read the * selection themselves: compacting a no-match where: @@ -3298,9 +5076,9 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int needs = 0; int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && !RAY_IS_PARTED(col->type) - && col->type != RAY_MAPCOMMON) { + ray_col_meta_t cm; + if (ray_table_col_meta_idx(tbl, c, &cm) && !RAY_IS_PARTED(cm.type) + && cm.type != RAY_MAPCOMMON) { needs = 1; break; } } @@ -3314,11 +5092,17 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } } input = exec_group(g, child_op, tbl, n); - if (owned_tbl) ray_release(owned_tbl); + if (owned_tbl) { ray_graph_unbind_table(g, owned_tbl); ray_release(owned_tbl); } if (g->selection) { ray_release(g->selection); g->selection = NULL; } + } else if (child_op && child_op->opcode == OP_FILTER && n >= 0 && + filter_chain_subset_invariant(g, child_op)) { + /* The chain narrows the inner filters' selection and the + * head below gathers the first N rows it keeps. A negative + * N keeps the filter head's empty result. */ + input = exec_node(g, child_op); } else if (child_op && child_op->opcode == OP_FILTER) { /* HEAD(FILTER): early-termination filter — gather only * the first N matching rows instead of all matches. */ @@ -3351,7 +5135,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* result = exec_filter_head(ftbl, pred, n); ray_release(pred); - ray_release(filter_input); + exec_release_tmp(g, filter_input); /* Top-level statement GC catches intermediates. */ return result; } else { @@ -3359,7 +5143,11 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } if (!input || RAY_IS_ERR(input)) return input; if (g->selection && input->type == RAY_TABLE) { - ray_t* compacted = sel_compact(g, input, g->selection, NULL, 0); + /* only the first n rows the selection keeps */ + ray_t* hsel = (n >= 0 && n < ray_rowsel_meta(g->selection)->total_pass) + ? ray_rowsel_head(g->selection, n) : NULL; + ray_t* compacted = sel_compact(g, input, hsel ? hsel : g->selection, NULL, 0); + if (hsel) ray_rowsel_release(hsel); ray_release(input); ray_release(g->selection); g->selection = NULL; @@ -3372,8 +5160,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (n > nrows) n = nrows; ray_t* result = ray_table_new(ncols); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = ray_table_col_idx(input, c); int64_t name_id = ray_table_col_name(input, c); + if (col && RAY_IS_ERR(col)) { + ray_release(result); + ray_release(input); + return col; + } if (!col) continue; if (col->type == RAY_MAPCOMMON) { ray_t* mc_head = materialize_mapcommon_head(col, n); @@ -3388,10 +5181,12 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); ray_t** sp = (ray_t**)ray_data(col); ray_t* head_vec; + int64_t hcn = 0; + const int64_t* hcnt = parted_table_counts(input, &hcn); if (base == RAY_STR) { - head_vec = parted_head_str(sp, col->len, n); + head_vec = parted_head_str_c(sp, col->len, n, hcnt, hcn); } else if (base == RAY_LIST) { - head_vec = parted_head_list(sp, col->len, n); + head_vec = parted_head_list_c(sp, col->len, n, hcnt, hcn); } else { uint8_t ba = (base == RAY_SYM) ? parted_sym_max_attrs(sp, col->len) : 0; @@ -3403,9 +5198,15 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t dst_off = 0; uint8_t seg_nulls = 0; for (int64_t s = 0; s < col->len && remaining > 0; s++) { - if (!segs[s]) continue; - int64_t take = segs[s]->len; + int64_t take = parted_seg_rows(segs, s, hcnt, hcn); if (take > remaining) take = remaining; + if (!segs[s]) { + /* a partition without the column */ + parted_fill_nulls(head_vec, dst_off, take); + dst_off += take; + remaining -= take; + continue; + } parted_copy_cells(ray_data(head_vec), base, ba, dst_off, segs[s], 0, take); @@ -3496,8 +5297,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t skip = nrows - n; ray_t* result = ray_table_new(ncols); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = ray_table_col_idx(input, c); int64_t name_id = ray_table_col_name(input, c); + if (col && RAY_IS_ERR(col)) { + ray_release(result); + ray_release(input); + return col; + } if (!col) continue; if (col->type == RAY_MAPCOMMON) { /* Materialize last N rows from MAPCOMMON partitions */ @@ -3536,10 +5342,12 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); ray_t** tsp = (ray_t**)ray_data(col); ray_t* tail_vec; + int64_t tcn = 0; + const int64_t* tcnt = parted_table_counts(input, &tcn); if (base == RAY_STR) { - tail_vec = parted_tail_str(tsp, col->len, n); + tail_vec = parted_tail_str_c(tsp, col->len, n, tcnt, tcn); } else if (base == RAY_LIST) { - tail_vec = parted_tail_list(tsp, col->len, n); + tail_vec = parted_tail_list_c(tsp, col->len, n, tcnt, tcn); } else { uint8_t tba = (base == RAY_SYM) ? parted_sym_max_attrs(tsp, col->len) : 0; @@ -3551,10 +5359,15 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t dst = n; uint8_t seg_nulls = 0; for (int64_t s = col->len - 1; s >= 0 && remaining > 0; s--) { - if (!segs[s]) continue; - int64_t take = segs[s]->len; + int64_t take = parted_seg_rows(segs, s, tcnt, tcn); if (take > remaining) take = remaining; dst -= take; + if (!segs[s]) { + /* a partition without the column */ + parted_fill_nulls(tail_vec, dst, take); + remaining -= take; + continue; + } parted_copy_cells(ray_data(tail_vec), base, tba, dst, segs[s], segs[s]->len - take, take); @@ -3734,7 +5547,7 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_op_ext_t* col_ext = find_ext(g, columns[c]); if (!col_ext) continue; int64_t name_id = col_ext->sym; - ray_t* src_col = ray_table_get_col(input, name_id); + ray_t* src_col = ray_table_slot(input, name_id); if (src_col) { ray_retain(src_col); result = ray_table_add_col(result, name_id, src_col); @@ -3792,9 +5605,9 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { int64_t broadcast_len = nr_in; bool has_collection = false; for (int64_t c = 0; c < rc; c++) { - ray_t* cv = ray_table_get_col_idx(result, c); - if (!cv || cv->type < 0) continue; - int64_t len = ray_parted_nrows(cv); + ray_col_meta_t lm; /* metadata: an encoded column stays encoded */ + if (!ray_table_col_meta_idx(result, c, &lm) || lm.type < 0) continue; + int64_t len = lm.len; /* a parted column: its rows across segments */ if (len == 1) continue; if (!has_collection) broadcast_len = len; has_collection = true; @@ -3802,9 +5615,9 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { bool has_full = false; if (nr_in != 1) { for (int64_t c = 0; c < rc; c++) { - ray_t* cv = ray_table_get_col_idx(result, c); + ray_col_meta_t cm; /* a parted column counts its rows across segments */ - if (cv && cv->type > 0 && ray_parted_nrows(cv) == nr_in) { has_full = true; break; } + if (ray_table_col_meta_idx(result, c, &cm) && cm.type > 0 && cm.len == nr_in) { has_full = true; break; } } } else { /* On a one-row input a scalar and a row column have the @@ -3834,12 +5647,20 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } /* A LIST here is an atom enlist has no vector for (F32). */ for (int64_t c = 0; broadcast_len != 1 && has_full && c < rc; c++) { - ray_t* cv = ray_table_get_col_idx(result, c); - if (!cv || cv->type < 0 || RAY_IS_PARTED(cv->type) || - cv->type == RAY_MAPCOMMON || cv->len != 1) continue; + ray_col_meta_t cm; + if (!ray_table_col_meta_idx(result, c, &cm) || cm.type < 0 || + RAY_IS_PARTED(cm.type) || cm.type == RAY_MAPCOMMON || + cm.len != 1) continue; /* One input row does not turn a row-aligned expression * into a scalar. Only constants/reductions may expand. */ if (nr_in == 1 && !op_tree_is_scalar(g, columns[c])) continue; + ray_t* cv = ray_table_col_idx(result, c); + if (cv && RAY_IS_ERR(cv)) { + ray_release(result); + g->table = saved_table; + ray_release(input); + return cv; + } ray_t* n_obj = make_i64(broadcast_len); ray_t* wide = n_obj ? ray_take_fn(cv, n_obj) : ray_error("oom", NULL); if (n_obj) ray_release(n_obj); @@ -3853,22 +5674,29 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_release(wide); } /* Length-changing constant projections must not silently - * truncate or pad the other columns during materialization. */ - ray_t* shape_err = ray_table_validate_rectangular(result, "select"); + * truncate or pad the other columns during materialization. + * A parted column with missing segments (ragged parted + * table) is measured through the source's partition counts, + * which the generic check does not know. */ + ray_t* shape_err = parted_result_validate(result, input); if (shape_err) { ray_release(result); g->table = saved_table; ray_release(input); return shape_err; } - if (g->selection && ray_table_nrows(result) != nr_in) { - ray_t* err = ray_error("length", - "select: collection projection has %lld rows; where requires %lld input-aligned rows", - (long long)ray_table_nrows(result), (long long)nr_in); - ray_release(result); - g->table = saved_table; - ray_release(input); - return err; + if (g->selection) { + ray_t* rows_err = NULL; + int64_t proj_rows = parted_table_rows(result, input, &rows_err); + if (rows_err || proj_rows != nr_in) { + ray_t* err = rows_err ? rows_err : ray_error("length", + "select: collection projection has %lld rows; where requires %lld input-aligned rows", + (long long)proj_rows, (long long)nr_in); + ray_release(result); + g->table = saved_table; + ray_release(input); + return err; + } } } @@ -4037,8 +5865,14 @@ ray_t* ray_result_merge(ray_t* accum, ray_t* partial) { ray_t* merged = ray_table_new(ncols); for (int64_t c = 0; c < ncols; c++) { int64_t name_id = ray_table_col_name(accum, c); - ray_t* a_col = ray_table_get_col_idx(accum, c); - ray_t* p_col = ray_table_get_col_idx(partial, c); + ray_t* a_col = ray_table_col_idx(accum, c); + ray_t* p_col = ray_table_col_idx(partial, c); + if ((a_col && RAY_IS_ERR(a_col)) || (p_col && RAY_IS_ERR(p_col))) { + bool a_bad = a_col && RAY_IS_ERR(a_col); + if (a_bad && p_col && RAY_IS_ERR(p_col)) ray_error_free(p_col); + ray_release(merged); + return a_bad ? a_col : p_col; + } if (!a_col || !p_col) { ray_release(merged); return ray_error("schema", NULL); @@ -4064,7 +5898,8 @@ ray_t* ray_result_merge(ray_t* accum, ray_t* partial) { } /* Build a flat table containing one segment's columns from a parted table. - * For each parted column, extracts segs[seg_idx] as a flat vector. + * For each parted column, extracts segs[seg_idx] without decoding it (a + * generation-2 segment stays a RAY_ENCCOL until an operator needs it). * MAPCOMMON columns are materialized for segment seg_idx: the partition key * value is broadcast to fill seg_rows elements. * Non-parted columns are retained as-is. */ @@ -4073,24 +5908,31 @@ ray_t* build_segment_table(ray_t* parted_tbl, int32_t seg_idx) { ray_t* seg_tbl = ray_table_new(ncols); if (!seg_tbl || RAY_IS_ERR(seg_tbl)) return seg_tbl; - /* Find segment row count from first parted column */ + /* The segment's row count: the partition-key counts, else the first + * parted column's segment (a ragged table may lack a column in this + * partition; its counts still give the rows). */ int64_t seg_rows = 0; - for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(parted_tbl, c); - if (col && RAY_IS_PARTED(col->type)) { - ray_t** segs = (ray_t**)ray_data(col); - if (seg_idx < col->len && segs[seg_idx]) - seg_rows = segs[seg_idx]->len; - break; + { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(parted_tbl, &ncnt); + if (cnt && seg_idx < ncnt) seg_rows = cnt[seg_idx]; + else for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(parted_tbl, c, &m) && RAY_IS_PARTED(m.type)) { + ray_t* seg = seg_idx < m.n_segs ? ray_table_parted_seg_idx(parted_tbl, c, seg_idx) : NULL; + if (seg) seg_rows = ray_table_col_nrows(seg); + break; + } } } for (int64_t c = 0; c < ncols; c++) { int64_t name_id = ray_table_col_name(parted_tbl, c); - ray_t* col = ray_table_get_col_idx(parted_tbl, c); - if (!col) continue; + ray_col_meta_t m; + if (!ray_table_col_meta_idx(parted_tbl, c, &m)) continue; - if (col->type == RAY_MAPCOMMON) { + if (m.type == RAY_MAPCOMMON) { + ray_t* col = ray_table_col_idx(parted_tbl, c); /* MAPCOMMON: plain */ /* Materialize partition key for this segment: broadcast key * value across seg_rows elements. */ if (col->len < 2) { @@ -4133,15 +5975,61 @@ ray_t* build_segment_table(ray_t* parted_tbl, int32_t seg_idx) { if (flat->type == RAY_SYM) ray_sym_vec_adopt_domain(flat, kv); seg_tbl = ray_table_add_col(seg_tbl, name_id, flat); ray_release(flat); - } else if (RAY_IS_PARTED(col->type)) { - ray_t** segs = (ray_t**)ray_data(col); - if (seg_idx >= col->len || !segs[seg_idx]) { + } else if (RAY_IS_PARTED(m.type)) { + if (seg_idx >= m.n_segs) { ray_release(seg_tbl); return ray_error("schema", NULL); } - ray_retain(segs[seg_idx]); - seg_tbl = ray_table_add_col(seg_tbl, name_id, segs[seg_idx]); - ray_release(segs[seg_idx]); + ray_t* seg = ray_table_parted_seg_idx(parted_tbl, c, seg_idx); + if (!seg) { + /* A partition without this column (a ragged parted table + * built elsewhere than ray_read_parted, whose missing + * segments are lazy all-null segments): its rows are the + * type's null. */ + int8_t base = (int8_t)RAY_PARTED_BASETYPE(m.type); + ray_t* nulls; + if (base == RAY_STR) { + nulls = ray_vec_new(RAY_STR, seg_rows); + for (int64_t r = 0; nulls && !RAY_IS_ERR(nulls) && r < seg_rows; r++) { + nulls = ray_str_vec_append(nulls, "", 0); + if (nulls && !RAY_IS_ERR(nulls)) ray_vec_set_null(nulls, r, true); + } + } else if (base == RAY_LIST) { + nulls = ray_list_new(seg_rows); + if (nulls && !RAY_IS_ERR(nulls)) { + ray_t** d = (ray_t**)ray_data(nulls); + for (int64_t r = 0; r < seg_rows; r++) { ray_retain(RAY_NULL_OBJ); d[r] = RAY_NULL_OBJ; } + nulls->len = seg_rows; + } + } else { + nulls = typed_vec_new(base, 0, seg_rows); + if (nulls && !RAY_IS_ERR(nulls)) { + nulls->len = seg_rows; + parted_fill_nulls(nulls, 0, seg_rows); + /* the domain of the first present segment */ + for (int64_t s = 0; base == RAY_SYM && s < m.n_segs; s++) { + ray_t* rep = ray_table_parted_seg_idx(parted_tbl, c, s); + if (!rep) continue; + if (rep->type == RAY_ENCCOL) ray_enccol_adopt_domain(nulls, rep); + else ray_sym_vec_adopt_domain(nulls, rep); + break; + } + } + } + if (!nulls || RAY_IS_ERR(nulls)) { + ray_release(seg_tbl); + return nulls ? nulls : ray_error("oom", NULL); + } + seg_tbl = ray_table_add_col(seg_tbl, name_id, nulls); + ray_release(nulls); + continue; + } + if (ray_table_col_nrows(seg) != seg_rows) { /* segments of one partition align */ + ray_release(seg_tbl); + return ray_error("length", "parted table: segment %d of column %lld has %lld rows, expected %lld", + (int)seg_idx, (long long)c, (long long)ray_table_col_nrows(seg), (long long)seg_rows); + } + seg_tbl = ray_table_add_col(seg_tbl, name_id, seg); /* encoded or plain, not decoded */ } else { /* Non-parted, non-MAPCOMMON column in a parted table: * streaming should have been rejected by ray_execute(). @@ -4153,37 +6041,41 @@ ray_t* build_segment_table(ray_t* parted_tbl, int32_t seg_idx) { return seg_tbl; } -/* Is this opcode safe for segment streaming with concatenation merge? - * Only element-wise, scan, filter, project, and alias ops produce - * results that can be correctly concatenated across segments. - * Everything else (joins, aggregations, sorts, graph ops, etc.) - * requires specialized merge or global state. */ -static bool op_streamable(uint16_t opc) { +/* Resolved pointwise layouts shared by streaming admission and the stricter + * row-subset proof. This is NOT op_is_elementwise's executor-dispatch set. */ +enum { EXPR_NONE, EXPR_UNARY, EXPR_BINARY, EXPR_THIRD, EXPR_CONCAT, EXPR_SET }; +static unsigned pointwise_layout(uint16_t opc) { switch (opc) { - /* Data access (OP_CONST excluded: vector constants have total-row - * length and produce length mismatches with per-segment data. - * Scalar constants are checked separately in dag_can_stream.) */ - case OP_SCAN: - /* Element-wise unary */ case OP_NEG: case OP_ABS: case OP_NOT: case OP_SQRT: case OP_LOG: case OP_EXP: case OP_CEIL: case OP_FLOOR: case OP_ROUND: case OP_SIN: case OP_ASIN: case OP_COS: case OP_ACOS: case OP_TAN: case OP_ATAN: case OP_RECIPROCAL: case OP_SIGNUM: case OP_ISNULL: case OP_CAST: - /* Element-wise binary */ - case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV: case OP_MOD: - case OP_POW: - case OP_EQ: case OP_NE: case OP_LT: case OP_LE: - case OP_GT: case OP_GE: case OP_AND: case OP_OR: - case OP_MIN2: case OP_MAX2: case OP_IF: case OP_IN: case OP_NOT_IN: - /* String element-wise */ - case OP_LIKE: case OP_ILIKE: case OP_UPPER: case OP_LOWER: - case OP_STRLEN: case OP_SUBSTR: case OP_REPLACE: case OP_TRIM: - case OP_CONCAT: case OP_STR_FIND: - /* Temporal element-wise */ + case OP_UPPER: case OP_LOWER: case OP_STRLEN: case OP_TRIM: case OP_EXTRACT: case OP_DATE_TRUNC: - /* Structure */ - case OP_FILTER: case OP_SELECT: case OP_ALIAS: + return EXPR_UNARY; + case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV: case OP_MOD: + case OP_POW: case OP_EQ: case OP_NE: case OP_LT: case OP_LE: + case OP_GT: case OP_GE: case OP_AND: case OP_OR: case OP_MIN2: case OP_MAX2: + case OP_LIKE: case OP_ILIKE: case OP_STR_FIND: + return EXPR_BINARY; + case OP_IF: case OP_SUBSTR: case OP_REPLACE: + return EXPR_THIRD; + case OP_CONCAT: + return EXPR_CONCAT; + case OP_IN: case OP_NOT_IN: + return EXPR_SET; + default: + return EXPR_NONE; + } +} + +/* Streaming keeps its historical structural permissions and root/constant + * policies. Sharing the classification does not widen its admission. */ +static bool op_streamable(uint16_t opc) { + if (pointwise_layout(opc)) return true; + switch (opc) { + case OP_SCAN: case OP_FILTER: case OP_SELECT: case OP_ALIAS: case OP_MATERIALIZE: return true; default: @@ -4191,6 +6083,120 @@ static bool op_streamable(uint16_t opc) { } } +/* A bounded rewrite-safety proof, not an execution validator for arbitrary + * malformed graphs. Shapes: 0 unproved, 1 scalar, 2 default-source rows. + * Set literals are checked on their edge and NEVER cached as value shapes. */ +#define SUBSET_NODE_LIMIT 4096 +#define SUBSET_DEPTH_LIMIT 64 +typedef struct { + ray_graph_t* g; + uint8_t state[SUBSET_NODE_LIMIT]; /* 0 unseen, 1 active, 2 done */ + uint8_t shape[SUBSET_NODE_LIMIT]; +} subset_proof_t; + +static bool subset_data_atom(ray_t* v) { + return v && v->type <= -RAY_BOOL && v->type >= -RAY_STR; +} + +static ray_op_t* subset_node(subset_proof_t* p, uint32_t id) { + if (id >= p->g->node_count) return NULL; + ray_op_t* n = &p->g->nodes[id]; + if (n->id != id || (n->flags & (OP_FLAG_DEAD | OP_FLAG_INVALID_SCAN))) return NULL; + return n; +} + +static ray_op_ext_t* subset_ext(subset_proof_t* p, ray_op_t* n) { + ray_op_ext_t* e = find_ext(p->g, n->id); + return e && e->base.opcode == n->opcode && e->base.arity == n->arity ? e : NULL; +} + +static bool subset_set(subset_proof_t* p, uint32_t id) { + ray_op_t* n = subset_node(p, id); + if (!n || n->opcode != OP_CONST || n->arity != 0) return false; + ray_op_ext_t* e = subset_ext(p, n); + /* Flat typed vectors only: excludes LIST, callable, lazy and table values. + * No data reads or mutation; the held literal is fixed during the rewrite. */ + return e && e->literal && ray_is_vec(e->literal) && e->literal->len >= 0; +} + +static uint8_t subset_visit(subset_proof_t* p, uint32_t id, unsigned depth) { + if (depth >= SUBSET_DEPTH_LIMIT) return 0; + ray_op_t* n = subset_node(p, id); + if (!n || p->state[id] == 1) return 0; + if (p->state[id] == 2) return p->shape[id]; + p->state[id] = 1; + uint8_t shape = 0; + if (n->opcode == OP_CONST || n->opcode == OP_SCAN) { + ray_op_ext_t* e = subset_ext(p, n); + if (n->arity != 0 || !e) return 0; + if (n->opcode == OP_CONST) { + if (!subset_data_atom(e->literal)) return 0; + shape = 1; + } else { + uint16_t source; + memcpy(&source, e->base.pad, sizeof(source)); + if (source != 0) return 0; + shape = 2; + } + } else { + unsigned layout = pointwise_layout(n->opcode); + if (!layout || n->arity != (layout == EXPR_UNARY ? 1 : 2)) return 0; + ray_op_ext_t* e = NULL; + if (layout == EXPR_THIRD || layout == EXPR_CONCAT || + n->opcode == OP_EXTRACT || n->opcode == OP_DATE_TRUNC) { + e = subset_ext(p, n); + if (!e) return 0; + } + /* Tail allocation capacity is not recorded: do not silently omit + * hidden arguments or read an unverifiable variadic tail. */ + if (layout == EXPR_CONCAT && e->sym != 2) return 0; + if (n->opcode == OP_EXTRACT && + (e->sym < RAY_EXTRACT_YEAR || e->sym > RAY_EXTRACT_EPOCH)) return 0; + if (n->opcode == OP_DATE_TRUNC && + e->sym != RAY_EXTRACT_DAY && e->sym != RAY_EXTRACT_SECOND) return 0; + if (n->opcode == OP_CAST && + (n->out_type < RAY_BOOL || n->out_type > RAY_STR)) return 0; + uint8_t a = subset_visit(p, n->in_id[0], depth + 1); + if (!a) return 0; + /* These special executors own row shape through their first input; + * do not infer row output merely from a parameter/unchosen branch. */ + if ((layout == EXPR_THIRD || n->opcode == OP_LIKE || + n->opcode == OP_ILIKE || n->opcode == OP_STR_FIND) && a != 2) return 0; + shape = a; + if (layout == EXPR_SET) { + /* Atom-left IN returns a one-cell vector, not scalar broadcast. */ + if (a != 2 || !subset_set(p, n->in_id[1])) return 0; + } else if (n->arity == 2) { + uint8_t b = subset_visit(p, n->in_id[1], depth + 1); + if (!b) return 0; + if ((n->opcode == OP_LIKE || n->opcode == OP_ILIKE || + n->opcode == OP_STR_FIND || n->opcode == OP_REPLACE) && b != 1) return 0; + if (b == 2) shape = 2; + } + if (layout == EXPR_THIRD) { + uint8_t c = subset_visit(p, e->third_in, depth + 1); /* ID zero is valid */ + if (!c || (n->opcode == OP_REPLACE && c != 1)) return 0; + if (c == 2) shape = 2; + } + /* Numeric primitive scalar dispatch is established. Decline other + * scan-free compositions unless their atom return is explicit. */ + if (shape == 1 && !op_is_elementwise(n->opcode) && + n->opcode != OP_UPPER && n->opcode != OP_LOWER && + n->opcode != OP_TRIM && n->opcode != OP_STRLEN && + n->opcode != OP_EXTRACT && n->opcode != OP_DATE_TRUNC) return 0; + } + p->state[id] = 2; + return p->shape[id] = shape; +} + +bool ray_expr_subset_invariant(ray_graph_t* g, uint32_t root_id) { + if (!g || !g->nodes || !g->node_count || g->node_count > SUBSET_NODE_LIMIT || + g->node_count > g->node_cap || g->ext_count > g->ext_cap || + (g->ext_count && !g->ext_nodes)) return false; + subset_proof_t p = { .g = g }; + return subset_visit(&p, root_id, 0) != 0; +} + /* Walk the root's input subtree to check if it reaches a default-table * OP_SCAN. Returns true if found, false otherwise. Also rejects the * subtree (sets *ok = false) on vector constants or secondary-table scans. @@ -4274,7 +6280,7 @@ static bool subtree_has_default_scan(ray_graph_t* g, ray_op_t* op, bool* ok, * DAGs that never scan the default table (e.g. a bare OP_CONST behind * passthrough ops) are rejected to avoid duplicating table-independent * results across partitions. */ -static bool dag_can_stream(ray_graph_t* g, ray_op_t* root) { +bool dag_can_stream(ray_graph_t* g, ray_op_t* root) { uint32_t n_words = (g->node_count + 63) / 64; uint64_t stack_buf[16]; /* covers DAGs up to 1024 nodes */ ray_t* visited_hdr = NULL; @@ -4365,7 +6371,8 @@ static const ray_pool_scan_t* exec_scan_columns(ray_graph_t* g, ray_pool_scan_t* ray_t* tbl = (tid > 0 && g->tables && (uint32_t)(tid - 1) < g->n_tables) ? g->tables[tid - 1] : g->table; if (!tbl || tbl->type != RAY_TABLE) continue; - exec_scan_add_col(s, ray_table_get_col(tbl, ext->sym)); + if (!ray_table_get_col_enc(tbl, ext->sym)) /* generation 2 reads by range */ + exec_scan_add_col(s, ray_table_col(tbl, ext->sym)); /* a plain slot: no decode, no error */ } return s->rows >= 0 ? s : NULL; } @@ -4411,17 +6418,21 @@ ray_t* ray_execute(ray_graph_t* g, ray_op_t* root) { /* Flatten one parted/mapcommon column into a dense vector (mirrors the * OP_SCAN cold-path flatten at the top of this file). Returns an owned * flat vector or a RAY_ERR. Precondition: col is RAY_MAPCOMMON or - * RAY_IS_PARTED. */ -static ray_t* flatten_parted_col(ray_t* col) { + * RAY_IS_PARTED. `tbl` is the column's table, or NULL: its partition + * counts give a NULL segment (a partition without the column, see + * store/part.c) its rows, filled with the type's null. */ +static ray_t* flatten_parted_col(ray_t* col, ray_t* tbl) { if (col->type == RAY_MAPCOMMON) return materialize_mapcommon(col); int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); ray_t** segs = (ray_t**)ray_data(col); - int64_t total = ray_parted_nrows(col); + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); if (base == RAY_STR) - return parted_flatten_str(segs, col->len, total); + return parted_flatten_str_c(segs, col->len, cnt, ncnt); if (base == RAY_LIST) - return parted_flatten_list(segs, col->len, total); + return parted_flatten_list_c(segs, col->len, cnt, ncnt); + int64_t total = parted_rows_counted(col, cnt, ncnt); uint8_t sba = (base == RAY_SYM) ? parted_sym_max_attrs(segs, col->len) : 0; ray_t* flat = typed_vec_new(base, sba, total); if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); @@ -4429,7 +6440,13 @@ static ray_t* flatten_parted_col(ray_t* col) { int64_t off = 0; uint8_t seg_nulls = 0; for (int64_t s = 0; s < col->len; s++) { - if (!segs[s] || segs[s]->len <= 0) continue; + if (!segs[s] || RAY_IS_ERR(segs[s])) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + parted_fill_nulls(flat, off, n); + off += n; + continue; + } + if (segs[s]->len <= 0) continue; parted_copy_cells(ray_data(flat), base, sba, off, segs[s], 0, segs[s]->len); seg_nulls |= segs[s]->attrs & RAY_ATTR_HAS_NULLS; @@ -4445,7 +6462,127 @@ static ray_t* flatten_parted_col(ray_t* col) { return flat; } +/* The keep-set a select published for this ray_execute's filter + * finalization (__VM->filt_keep: the columns its group reads), + * or none (keep every column). Depth-gated so a nested subquery's own + * finalization does not consume it. */ +static void exec_filt_keep(const int64_t** keep, int* keep_n) { + *keep = NULL; *keep_n = 0; + if (__VM && __VM->filt_keep && __VM->filt_keep_n > 0 + && __VM->eval_depth == __VM->filt_depth) { + *keep = __VM->filt_keep; *keep_n = __VM->filt_keep_n; + } +} + +/* The partition-count source for `tbl`: itself when it carries the + * partition-key column, else `counts_src` (the source table a projection + * of parted columns was taken from, whose partitions it shares). */ +static ray_t* parted_counts_table(ray_t* tbl, ray_t* counts_src) { + int64_t n = 0; + if (parted_table_counts(tbl, &n)) return tbl; + return counts_src; +} + +/* Rows of column c of `tbl`, a parted one counted through the partition + * counts; reads metadata only, except a parted column (its segments). + * -1 with *err set when the column fails to load. */ +static int64_t parted_col_rows(ray_t* tbl, int64_t c, const int64_t* cnt, int64_t ncnt, ray_t** err) { + *err = NULL; + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m)) return -2; /* no column */ + if (!RAY_IS_PARTED(m.type) || m.enc) return m.len; /* an encoded parted column has every segment */ + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) { *err = col; return -1; } + if (!col) return -2; + return parted_rows_counted(col, cnt, ncnt); +} + +/* ray_table_validate_rectangular for a result that may hold parted columns + * with missing segments: every column must span the rows the partition + * counts (of `tbl`, else `counts_src`) give a parted column. */ +static ray_t* parted_result_validate(ray_t* tbl, ray_t* counts_src) { + int64_t ncols = ray_table_ncols(tbl); + bool any_parted = false; + for (int64_t c = 0; c < ncols && !any_parted; c++) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && RAY_IS_PARTED(m.type)) any_parted = true; + } + if (!any_parted) return ray_table_validate_rectangular(tbl, "select"); + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(parted_counts_table(tbl, counts_src), &ncnt); + int64_t want = -1; + for (int64_t c = 0; c < ncols; c++) { + ray_t* err = NULL; + int64_t n = parted_col_rows(tbl, c, cnt, ncnt, &err); + if (err) return err; + if (n < 0) continue; + if (want < 0) want = n; + else if (n != want) + return ray_error("domain", "select: ragged columns (column %lld has %lld rows, expected %lld)", + (long long)c, (long long)n, (long long)want); + } + return NULL; +} + +/* Rows of a table whose first column may be a parted column with missing + * segments: counted through the partition counts. */ +static int64_t parted_table_rows(ray_t* tbl, ray_t* counts_src, ray_t** err_out) { + ray_col_meta_t m; + if (ray_table_ncols(tbl) <= 0 || !ray_table_col_meta_idx(tbl, 0, &m) || !RAY_IS_PARTED(m.type)) + return ray_table_nrows(tbl); + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(parted_counts_table(tbl, counts_src), &ncnt); + ray_t* err = NULL; + int64_t n = parted_col_rows(tbl, 0, cnt, ncnt, &err); + if (err) { *err_out = err; return -1; } /* the column's own load error, owned by the caller */ + return n; +} + +/* A flattened copy of `tbl` when any column is parted / mapcommon, built + * without mutating the (possibly stored) source; NULL when every column is + * already dense. Returns an owned table or a RAY_ERR. A ragged table (a + * partition without some column) flattens to the table's row count in + * every column, the missing rows as typed nulls; the counts come from + * `tbl`, or from `counts_src` when `tbl` is a projection without the + * partition-key column. Only the parted columns are read (an encoded one + * through its materialization); the others are carried as they are. */ +static ray_t* flatten_parted_table(ray_t* tbl, ray_t* counts_src) { + int64_t ncols = ray_table_ncols(tbl); + ray_t* ctbl = parted_counts_table(tbl, counts_src); + bool any_parted = false; + for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON)) { + any_parted = true; break; + } + } + if (!any_parted) return NULL; + ray_t* out = ray_table_new(ncols); + for (int64_t c = 0; out && !RAY_IS_ERR(out) && c < ncols; c++) { + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m)) continue; + int64_t name = ray_table_col_name(tbl, c); + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON) { + ray_t* col = ray_table_col_idx(tbl, c); + if (!col || RAY_IS_ERR(col)) { ray_release(out); return col ? col : ray_error("oom", NULL); } + ray_t* flat = flatten_parted_col(col, ctbl); + PARTED_FLAT_DCHECK(ctbl, flat); + if (!flat || RAY_IS_ERR(flat)) { + ray_release(out); + return flat ? flat : ray_error("oom", NULL); + } + out = ray_table_add_col(out, name, flat); + ray_release(flat); + } else { + ray_t* slot = ray_table_slot_idx(tbl, c); /* encoded or plain, not decoded */ + if (slot) out = ray_table_add_col(out, name, slot); + } + } + return out ? out : ray_error("oom", NULL); +} + static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cancel) { + ray_enc_note_exec_start(); if (!g || !root) return ray_error("nyi", NULL); /* Lazy-init the global thread pool on first call */ @@ -4465,15 +6602,36 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance int32_t seg_count = 0; if (g->table) { bool has_flat = false; + /* Every parted and MAPCOMMON column covers the same rows: a + * flattened column is sized by its own row count and consumers + * index up to the table's, so a shorter one (#724) is refused here + * rather than read past its end. A missing (NULL) segment of a + * hand-built wrapper counts its partition's rows, from the + * partition-key counts: the segment table and every flatten fill + * them with the type's null (ray_read_parted builds none). */ + int64_t parted_rows = -1; + int64_t pncnt = 0; + const int64_t* pcnt = parted_table_counts(g->table, &pncnt); for (int64_t c = 0; c < ray_table_ncols(g->table); c++) { - ray_t* col = ray_table_get_col_idx(g->table, c); - if (!col) continue; - if (RAY_IS_PARTED(col->type)) { + ray_col_meta_t m; + if (!ray_table_col_meta_idx(g->table, c, &m)) continue; + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON) { + int64_t rows = m.len; + if (RAY_IS_PARTED(m.type) && !m.enc && pcnt) { + ray_t* pc = ray_table_col_idx(g->table, c); /* a plain wrapper: no decode */ + if (pc && !RAY_IS_ERR(pc)) rows = parted_rows_counted(pc, pcnt, pncnt); + } + if (parted_rows < 0) parted_rows = rows; + else if (rows != parted_rows) + return ray_error("length", "parted table: column %lld has %lld rows, expected %lld", + (long long)c, (long long)rows, (long long)parted_rows); + } + if (RAY_IS_PARTED(m.type)) { if (seg_count == 0) - seg_count = (int32_t)col->len; - else if ((int32_t)col->len != seg_count) + seg_count = (int32_t)m.n_segs; + else if ((int32_t)m.n_segs != seg_count) return ray_error("schema", NULL); - } else if (col->type != RAY_MAPCOMMON) { + } else if (m.type != RAY_MAPCOMMON) { has_flat = true; } } @@ -4491,15 +6649,11 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance if (memo_armed) exec_memo_end(g); if (g->selection && result && !RAY_IS_ERR(result) && result->type == RAY_TABLE) { - /* Projection-aware compaction: a select publishes the keys-only - * keep-set of its distinct downstream via __VM->filt_keep before - * this ray_execute; gather only those columns. Depth-gated so a - * nested subquery's own finalization does not consume it. */ + /* Projection-aware compaction: a select publishes the columns + * its group reads via __VM->filt_keep before this + * ray_execute; gather only those columns. */ const int64_t* keep = NULL; int keep_n = 0; - if (__VM && __VM->filt_keep && __VM->filt_keep_n > 0 - && __VM->eval_depth == __VM->filt_depth) { - keep = __VM->filt_keep; keep_n = __VM->filt_keep_n; - } + exec_filt_keep(&keep, &keep_n); ray_t* compacted = sel_compact(g, result, g->selection, keep, keep_n); ray_release(result); ray_release(g->selection); @@ -4517,18 +6671,30 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance int64_t ncols = ray_table_ncols(result); bool any_parted = false; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(result, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(result, c, &m) + && (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON)) { any_parted = true; break; } } if (any_parted) { + ray_t* ctbl = parted_counts_table(result, g->table); + /* the same keep-set as the partial filter's sel_compact */ + const int64_t* keep = NULL; int keep_n = 0; + exec_filt_keep(&keep, &keep_n); ray_t* out = ray_table_new(ncols); for (int64_t c = 0; out && !RAY_IS_ERR(out) && c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(result, c); int64_t name = ray_table_col_name(result, c); + if (keep_n > 0) { + bool kept = false; + for (int j = 0; j < keep_n && !kept; j++) kept = keep[j] == name; + if (!kept) continue; + } + ray_t* col = ray_table_col_idx(result, c); + if (col && RAY_IS_ERR(col)) { ray_release(out); ray_release(result); return col; } if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) { - ray_t* flat = flatten_parted_col(col); + ray_t* flat = flatten_parted_col(col, ctbl); + PARTED_FLAT_DCHECK(ctbl, flat); if (!flat || RAY_IS_ERR(flat)) { ray_release(out); ray_release(result); return flat ? flat : ray_error("oom", NULL); @@ -4599,7 +6765,9 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance /* Compact lazy selection for this segment */ if (g->selection && partial && !RAY_IS_ERR(partial) && partial->type == RAY_TABLE) { - ray_t* compacted = sel_compact(g, partial, g->selection, NULL, 0); + const int64_t* keep = NULL; int keep_n = 0; + exec_filt_keep(&keep, &keep_n); + ray_t* compacted = sel_compact(g, partial, g->selection, keep, keep_n); ray_release(partial); ray_release(g->selection); g->selection = NULL; @@ -4607,6 +6775,7 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance } g->table = saved_table; + ray_graph_unbind_table(g, seg_tbl); ray_release(seg_tbl); if (!partial || RAY_IS_ERR(partial)) { @@ -4638,14 +6807,15 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance if (empty_tbl && !RAY_IS_ERR(empty_tbl)) { for (int64_t c = 0; c < ncols; c++) { int64_t name_id = ray_table_col_name(saved_table, c); - ray_t* col = ray_table_get_col_idx(saved_table, c); - if (!col) continue; - int8_t base = col->type; - if (col->type == RAY_MAPCOMMON) { + ray_col_meta_t m; + if (!ray_table_col_meta_idx(saved_table, c, &m)) continue; + int8_t base = m.type; + if (m.type == RAY_MAPCOMMON) { + ray_t* col = ray_table_col_idx(saved_table, c); ray_t** mc = (ray_t**)ray_data(col); base = mc[0] ? mc[0]->type : RAY_I64; - } else if (RAY_IS_PARTED(col->type)) { - base = (int8_t)RAY_PARTED_BASETYPE(col->type); + } else if (RAY_IS_PARTED(m.type)) { + base = (int8_t)RAY_PARTED_BASETYPE(m.type); } ray_t* ecol = ray_vec_new(base, 0); if (!ecol || RAY_IS_ERR(ecol)) { @@ -4669,6 +6839,7 @@ static ray_t* ray_execute_inner(ray_graph_t* g, ray_op_t* root, bool reset_cance g->selection = NULL; } g->table = saved_table; + ray_graph_unbind_table(g, empty_tbl); ray_release(empty_tbl); } } diff --git a/src/ops/expr.c b/src/ops/expr.c index 8940e9c93..f04ee6fd9 100644 --- a/src/ops/expr.c +++ b/src/ops/expr.c @@ -25,7 +25,11 @@ #include "lang/internal.h" /* sym_domain_rep (sym-domain Phase 2) */ #include "lang/format.h" /* ray_type_name */ #include "ops/rowsel.h" +#include "table/table.h" /* ray_table_col_meta */ +#include "ops/colbind.h" #include "ops/idxop.h" /* RAY_IDX_CHUNK_ZONE per-morsel zone-skip */ +#include "store/enccol.h" /* ray_enccol_seg: encoded parted segments */ +#include "store/enceval.h" /* encoded leaves: ray_enc_eval_cmp(_f64), ray_enc_const_decision(_f64) */ #include #include @@ -137,6 +141,11 @@ static bool eval_const_numeric_expr(ray_graph_t* g, ray_op_t* op, if (op->opcode == OP_CONST) { ray_op_ext_t* ext = find_ext(g, op->id); if (!ext || !ext->literal) return false; + /* A null constant has no numeric value: atom_to_numeric would hand + * back its sentinel (INT64_MIN for 0Nl) and the SUM/AVG linear and + * affine folds would sum it per row. Decline, as expr_compile does, + * so the null-aware path evaluates it. */ + if (RAY_ATOM_IS_NULL(ext->literal)) return false; return atom_to_numeric(ext->literal, out_f, out_i, out_is_f64); } @@ -260,15 +269,11 @@ static bool const_expr_to_i64(ray_graph_t* g, ray_op_t* op, int64_t* out) { int64_t c_i = 0; bool c_is_f64 = false; if (!eval_const_numeric_expr(g, op, &c_f, &c_i, &c_is_f64)) return false; - if (!c_is_f64) { - *out = c_i; - return true; - } - if (!isfinite(c_f)) return false; - double ip = 0.0; - if (modf(c_f, &ip) != 0.0) return false; - if (ip > (double)INT64_MAX || ip < (double)INT64_MIN) return false; - *out = (int64_t)ip; + /* A FLOAT constant, even a whole-number one (2.0), makes the expression + * F64, but the linear plan sums integer terms and emits SUM as I64. + * Decline it so the expression is evaluated with its F64 type. */ + if (c_is_f64) return false; + *out = c_i; return true; } @@ -382,7 +387,8 @@ static bool parse_linear_i64_expr(ray_graph_t* g, ray_op_t* op, linear_expr_i64_ /* Detect SUM/AVG integer-linear inputs for scalar aggregate fast path. * Example: (v1 + 1) * 2, v1 + v2 + 1 */ bool try_linear_sumavg_input_i64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, - agg_linear_t* out_plan) { + agg_linear_t* out_plan, ray_t** err) { + *err = NULL; if (!g || !tbl || !input_op || !out_plan) return false; linear_expr_i64_t lin; if (!parse_linear_i64_expr(g, input_op, &lin)) return false; @@ -390,16 +396,30 @@ bool try_linear_sumavg_input_i64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, memset(out_plan, 0, sizeof(*out_plan)); out_plan->n_terms = lin.n_terms; out_plan->bias_i64 = lin.bias_i64; + /* Every decision first, from the bound sources; the plain columns are + * requested only once the plan is certain (a decline decodes nothing). */ + ray_col_src_t* srcs[AGG_LINEAR_MAX_TERMS]; for (uint8_t i = 0; i < lin.n_terms; i++) { - ray_t* col = ray_table_get_col(tbl, lin.syms[i]); - if (!col || !type_is_linear_i64_col(col->type)) return false; + if (ray_col_bind_declines(tbl, lin.syms[i])) return false; + srcs[i] = ray_graph_bind_col(g, tbl, lin.syms[i], err); + if (!srcs[i]) return false; + if (srcs[i]->parted || !type_is_linear_i64_col(srcs[i]->type)) return false; /* scalar_sum_linear_i64_fn reads slots raw via scalar_i64_at; * any nullable term would poison the sum with NULL_I{16,32,64} * sentinels. Refuse the fast plan and let the caller fall back * to the generic masked path. */ - if (ray_vec_may_have_nulls(col)) return false; + if (srcs[i]->may_null) return false; + /* the plan reads whole-column pointers: an encoded term not yet + * materialized declines (a shape decline, *err NULL), and the + * scalar route evaluates the expression by range reads instead */ + if (!ray_col_src_base(srcs[i])) return false; + } + for (uint8_t i = 0; i < lin.n_terms; i++) { + ray_t* col = NULL; + *err = ray_col_src_plain(srcs[i], &col); /* ready-only */ + if (*err) return false; out_plan->term_ptrs[i] = ray_data(col); - out_plan->term_types[i] = col->type; + out_plan->term_types[i] = srcs[i]->type; out_plan->coeff_i64[i] = lin.coeff_i64[i]; } out_plan->enabled = true; @@ -413,7 +433,8 @@ bool try_linear_sumavg_input_i64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, * The fused read promotes each side to double exactly like expr's * promote(), so the accumulated sum is bit-compatible. */ bool try_prod_sumavg_input_f64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, - agg_prod_t* out) { + agg_prod_t* out, ray_t** err) { + *err = NULL; if (!g || !tbl || !input_op || !out) return false; if (input_op->opcode != OP_MUL || input_op->arity != 2) return false; ray_op_t* lhs = op_child(g, input_op, 0); @@ -423,29 +444,73 @@ bool try_prod_sumavg_input_f64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, ray_op_ext_t* lx = find_ext(g, lhs->id); ray_op_ext_t* rx = find_ext(g, rhs->id); if (!lx || !rx) return false; - ray_t* ca = ray_table_get_col(tbl, lx->sym); - ray_t* cb = ray_table_get_col(tbl, rx->sym); - if (!ca || !cb || RAY_IS_ERR(ca) || RAY_IS_ERR(cb)) return false; - if (RAY_IS_PARTED(ca->type) || ca->type == RAY_MAPCOMMON) return false; - if (RAY_IS_PARTED(cb->type) || cb->type == RAY_MAPCOMMON) return false; - if (ray_vec_may_have_nulls(ca) || ray_vec_may_have_nulls(cb)) + if (ray_col_bind_declines(tbl, lx->sym) || ray_col_bind_declines(tbl, rx->sym)) return false; + ray_col_src_t* sa = ray_graph_bind_col(g, tbl, lx->sym, err); + if (!sa) return false; + ray_col_src_t* sb = ray_graph_bind_col(g, tbl, rx->sym, err); + if (!sb) return false; + if (sa->parted || sb->parted) return false; + if (sa->may_null || sb->may_null) + return false; + /* whole-column pointers only: an encoded side not yet materialized + * declines (the input is evaluated by range reads instead) */ + if (!ray_col_src_base(sa) || !ray_col_src_base(sb)) return false; #define PROD_OK_T(t) ((t) == RAY_F64 || (t) == RAY_I64 || (t) == RAY_I32 || \ (t) == RAY_I16 || (t) == RAY_U8 || (t) == RAY_BOOL) - if (!PROD_OK_T(ca->type) || !PROD_OK_T(cb->type)) return false; + if (!PROD_OK_T(sa->type) || !PROD_OK_T(sb->type)) return false; #undef PROD_OK_T - if (ca->type != RAY_F64 && cb->type != RAY_F64) return false; - + if (sa->type != RAY_F64 && sb->type != RAY_F64) return false; + + ray_t* ca = NULL; + ray_t* cb = NULL; + *err = ray_col_src_plain(sa, &ca); /* ready-only */ + if (*err) return false; + *err = ray_col_src_plain(sb, &cb); /* ready-only */ + if (*err) return false; out->enabled = true; - out->pa = ray_data(ca); out->ta = ca->type; out->aa = ca->attrs; - out->pb = ray_data(cb); out->tb = cb->type; out->ab = cb->attrs; + out->pa = ray_data(ca); out->ta = sa->type; out->aa = sa->attrs; + out->pb = ray_data(cb); out->tb = sb->type; out->ab = sb->attrs; return true; } -/* Detect SUM/AVG affine inputs of form (scan +/- const) and return scan vector - * plus the additive bias so we can adjust results from (sum,count) directly. */ +/* The affine plan's column object: the ready plain column (generation 0, + * or a published materialization), else the bound source's own object (a + * RAY_ENCCOL), which the caller binds and reads by range. Never decodes. */ +static ray_t* affine_base_obj(ray_col_src_t* src) { + ray_t* ready = ray_col_src_ready(src); + return ready ? ready : src->obj; +} + +/* A delayed F64 bias is equivalent to per-row F64 addition only when every + * addition and the entire reduction are exact. Bound this from the type and + * row count, without reading the column. I64 has no useful type-wide bound: + * casting a value above 2^53 can discard bits before the addition. */ +static bool affine_int_f64_bias_exact(int8_t bt, double bias, int64_t nrows, + bool may_null) { + if (may_null || nrows <= 0 || !isfinite(bias) || trunc(bias) != bias) + return false; + long double max_abs; + switch (bt) { + case RAY_I32: max_abs = 2147483648.0L; break; + case RAY_I16: max_abs = 32768.0L; break; + case RAY_U8: max_abs = 255.0L; break; + case RAY_BOOL: max_abs = 1.0L; break; + default: return false; + } + return ((max_abs + fabsl((long double)bias)) * (long double)nrows) <= + 9007199254740992.0L; +} + +/* Detect SUM/AVG affine inputs of form (scan +/- const) and return the scan's + * column object (a plain vector, or a RAY_ENCCOL the caller binds: see + * affine_base_obj) plus the additive bias so we can adjust results from + * (sum,count) directly. f64_bias_ok: the caller emits a FLOAT bias over an + * integer column as F64 (agg_affine_t.f64). */ bool try_affine_sumavg_input(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, - ray_t** out_vec, agg_affine_t* out_affine) { + bool f64_bias_ok, + ray_t** out_vec, agg_affine_t* out_affine, ray_t** err) { + *err = NULL; if (!g || !tbl || !input_op || !out_vec || !out_affine) return false; if (input_op->opcode != OP_ADD && input_op->opcode != OP_SUB) return false; if (input_op->arity != 2 || !op_child(g, input_op, 0) || !op_child(g, input_op, 1)) return false; @@ -491,11 +556,15 @@ bool try_affine_sumavg_input(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, ray_op_ext_t* base_ext = find_ext(g, base_op->id); if (!base_ext || base_ext->base.opcode != OP_SCAN) return false; - ray_t* base_vec = ray_table_get_col(tbl, base_ext->sym); - if (!base_vec) return false; + if (ray_col_bind_declines(tbl, base_ext->sym)) return false; + ray_col_src_t* base_src = ray_graph_bind_col(g, tbl, base_ext->sym, err); + if (!base_src) return false; + if (base_src->parted) return false; /* a parted wrapper matches no arm below */ - int8_t bt = base_vec->type; + int8_t bt = base_src->type; + ray_t* base_vec = NULL; if (bt == RAY_F64) { + base_vec = affine_base_obj(base_src); out_affine->enabled = true; out_affine->bias_f64 = (double)sign * (c_is_f64 ? c_f : (double)c_i); out_affine->bias_i64 = (int64_t)out_affine->bias_f64; @@ -506,16 +575,22 @@ bool try_affine_sumavg_input(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, if (bt == RAY_I64 || bt == RAY_TIMESTAMP || bt == RAY_I32 || bt == RAY_I16 || bt == RAY_U8 || bt == RAY_BOOL || RAY_IS_SYM(bt)) { - int64_t c = 0; + /* A FLOAT bias needs per-row F64 casts/additions. Delay it only + * when type and row-count bounds prove those operations, plus the + * reduction, exact; otherwise evaluate the expression as written. */ if (c_is_f64) { - if (!isfinite(c_f)) return false; - double ip = 0.0; - if (modf(c_f, &ip) != 0.0) return false; - if (ip > (double)INT64_MAX || ip < (double)INT64_MIN) return false; - c = (int64_t)ip; - } else { - c = c_i; + if (!f64_bias_ok || !affine_int_f64_bias_exact(bt, c_f, + base_src->len, base_src->may_null)) return false; + base_vec = affine_base_obj(base_src); + out_affine->enabled = true; + out_affine->f64 = true; + out_affine->bias_f64 = (double)sign * c_f; + out_affine->bias_i64 = 0; + *out_vec = base_vec; + return true; } + int64_t c = c_i; + base_vec = affine_base_obj(base_src); out_affine->enabled = true; out_affine->bias_i64 = sign > 0 ? c : -c; out_affine->bias_f64 = (double)out_affine->bias_i64; @@ -680,10 +755,58 @@ static bool expr_null_capable(uint8_t op, int8_t dt, int8_t t1) { return false; } +/* The null SYM literal (', the SYM null "": id 0 in every domain). */ +static bool expr_lit_null_sym(const ray_t* lit) { + return lit && lit->type == -RAY_SYM && RAY_ATOM_IS_NULL(lit); +} + +/* The bytes of a STR literal constant node ("" included) or of a SYM one + * (the null SYM as ""), or false. */ +static bool expr_sym_lit_bytes(ray_graph_t* g, ray_op_t* n, const char** s, size_t* len) { + if (!n || n->opcode != OP_CONST) return false; + ray_op_ext_t* ext = find_ext(g, n->id); + ray_t* lit = ext ? ext->literal : NULL; + if (!lit) return false; + if (lit->type == -RAY_STR) { *s = ray_str_ptr(lit); *len = ray_str_len(lit); return true; } /* "" included */ + if (expr_lit_null_sym(lit)) { *s = ""; *len = 0; return true; } + if (lit->type == -RAY_SYM) { + ray_t* str = ray_sym_str(lit->i64); /* borrowed from the intern table */ + if (!str) return false; + *s = ray_str_ptr(str); *len = ray_str_len(str); + return true; + } + return false; +} +/* `n` is a SYM / STR literal an EQ / NE against `col` may compare on the + * column's file-domain ids. The null SYM literal only against a + * generation-2 column (its id 0, decided by ids on the encoded route, + * spec "SYM ids decide equality"); generation 0 keeps its fallback for it, + * unchanged. */ +static bool expr_sym_lit(ray_graph_t* g, ray_t* tbl, ray_op_t* n, ray_op_t* col) { + const char* s; size_t len; + if (!expr_sym_lit_bytes(g, n, &s, &len)) return false; + ray_op_ext_t* ext = find_ext(g, n->id); + if (!expr_lit_null_sym(ext->literal)) return true; + ray_op_ext_t* ce = col && col->opcode == OP_SCAN ? find_ext(g, col->id) : NULL; + ray_col_meta_t cm; + return ce && ray_table_col_meta(tbl, ce->sym, &cm) && cm.enc != NULL; +} +/* A STR / SYM literal as an id of a file-domain source: "" is id 0 in + * every domain; a string absent from the domain is the impossible id -1 + * (EQ all-false; NE true for every row, id 0 included, as null != c). */ +static bool expr_sym_lit_in(ray_graph_t* g, ray_op_t* n, const ray_col_src_t* src, int64_t* id) { + const char* s; size_t len; + if (!expr_sym_lit_bytes(g, n, &s, &len)) return false; + int64_t x = len == 0 ? 0 : ray_col_src_sym_find(src, s, len); + *id = x < 0 ? -1 : x; + return true; +} + /* Compile expression DAG into flat instruction array. * Returns true on success. Only compiles element-wise subtrees. */ -bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { +bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out, ray_t** err) { memset(out, 0, sizeof(*out)); + *err = NULL; if (ray_expr_disable) return false; /* uncounted: test knob */ if (!root || !g || !tbl) EXPR_BAIL(EXPR_BAIL_ROOT); if (root->opcode == OP_SCAN || root->opcode == OP_CONST) EXPR_BAIL(EXPR_BAIL_ROOT); @@ -697,14 +820,32 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { /* Issue #533: which nodes may skip the SYM null proof. A null SYM is * id 0, below every real intern id, and the fallback ranks a null SYM * below everything in all six comparisons (null == null, null != x, - * null < x hold; null == x, x < null do not). Raw id equality compares - * preserve this; ordered compares bail below to lexical LUTs. A SYM - * column whose every consumer is EQ..GE against a non-null constant (a - * null literal bails at OP_CONST) or another SYM scan needs no O(n) + * null < x hold; null == x, x < null do not). Raw id equality compares + * preserve this; ordered compares bail below to lexical LUTs. A SYM + * column whose every consumer in this subtree is EQ..GE against a + * constant (a null literal bails at OP_CONST, except "" and the null + * SYM, id 0, read only by an EQ / NE on file-domain ids: null == null + * holds, as the fallback ranks it) or another SYM scan needs no O(n) * ray_vec_has_nulls walk. Any other consumer — ISNULL, CAST, * arithmetic — reads the lane as a value and keeps the proof. */ uint8_t sym_cmp_safe[nc]; memset(sym_cmp_safe, 1, nc * sizeof(uint8_t)); + /* Which nodes are consumed only by EQ / NE against a STR constant + * ("" included: id 0) or a SYM one (the null SYM, id 0, only for a + * generation-2 column: expr_sym_lit): a file-domain SYM column + * read so compares on its own + * ids once the constant is translated into its domain (below, at the + * compare). An ordered consumer keeps EXPR_BAIL_SYM_DOMAIN: ids are + * never ordered (#738 / #768). */ + uint8_t sym_eq_only[nc]; + memset(sym_eq_only, 1, nc * sizeof(uint8_t)); + /* Per register: the bound file-domain SYM source of a scan register + * admitted by sym_eq_only; a STR constant absent from the global + * intern table (usable only once re-translated into such a domain). */ + ray_col_src_t* fd_src[EXPR_MAX_REGS]; + bool const_unres[EXPR_MAX_REGS]; + memset(fd_src, 0, sizeof fd_src); + memset(const_unres, 0, sizeof const_unres); { uint8_t seen[nc]; uint32_t stk[nc]; @@ -713,7 +854,11 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { if (root->id < nc) { seen[root->id] = 1; stk[ssp++] = root->id; } while (ssp > 0) { ray_op_t* n = &g->nodes[stk[--ssp]]; + int8_t type = n->out_type; + if (RAY_IS_PARTED(type)) type = (int8_t)RAY_PARTED_BASETYPE(type); + if (type == RAY_TIMESPAN) EXPR_BAIL(EXPR_BAIL_ROOT); bool cmp = n->arity == 2 && n->opcode >= OP_EQ && n->opcode <= OP_GE; + bool eqne = n->arity == 2 && (n->opcode == OP_EQ || n->opcode == OP_NE); for (int i = 0; i < n->arity; i++) { ray_op_t* ch = op_child(g, n, i); if (!ch || ch->id >= nc) continue; @@ -723,14 +868,16 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { if (other && other->opcode == OP_CONST) safe = true; else if (other && other->opcode == OP_SCAN) { ray_op_ext_t* oe = find_ext(g, other->id); - ray_t* oc = oe ? ray_table_get_col(tbl, oe->sym) : NULL; - if (oc && (RAY_IS_PARTED(oc->type) - ? RAY_PARTED_BASETYPE(oc->type) == RAY_SYM - : oc->type == RAY_SYM)) + ray_col_meta_t om; + bool oh = oe && ray_table_col_meta(tbl, oe->sym, &om); + if (oh && (RAY_IS_PARTED(om.type) + ? RAY_PARTED_BASETYPE(om.type) == RAY_SYM + : om.type == RAY_SYM)) safe = true; } } if (!safe) sym_cmp_safe[ch->id] = 0; + if (!(eqne && expr_sym_lit(g, tbl, op_child(g, n, 1 - i), ch))) sym_eq_only[ch->id] = 0; if (!seen[ch->id]) { seen[ch->id] = 1; stk[ssp++] = ch->id; } } } @@ -766,16 +913,18 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { if (node->opcode == OP_SCAN) { ray_op_ext_t* ext = find_ext(g, node->id); if (!ext) EXPR_BAIL(EXPR_BAIL_OTHER); - ray_t* col = ray_table_get_col(tbl, ext->sym); - if (!col) EXPR_BAIL(EXPR_BAIL_OTHER); - if (col->type == RAY_MAPCOMMON) EXPR_BAIL(EXPR_BAIL_MAPCOMMON); - /* Bail on the ELEMENT type: a parted wrapper carries - * RAY_PARTED_BASE + base and would sail past checks on - * col->type — a parted GUID column then zero-filled - * every lane and matched everything. */ - int8_t elem = RAY_IS_PARTED(col->type) - ? (int8_t)RAY_PARTED_BASETYPE(col->type) - : col->type; + ray_col_meta_t cm; + if (!ray_table_col_meta(tbl, ext->sym, &cm)) EXPR_BAIL(EXPR_BAIL_OTHER); + if (ray_col_bind_declines(tbl, ext->sym)) + EXPR_BAIL(cm.type == RAY_MAPCOMMON ? EXPR_BAIL_MAPCOMMON : EXPR_BAIL_SLICE); + ray_col_src_t* src = ray_graph_bind_col(g, tbl, ext->sym, err); + if (*err) return false; /* a failed bind is an error, not a bail */ + if (!src) EXPR_BAIL(EXPR_BAIL_OTHER); + /* Bail on the ELEMENT type: a parted source reports its base + * type in src->type (the wrapper type would sail past checks + * — a parted GUID column then zero-filled every lane and + * matched everything). */ + int8_t elem = src->type; if (elem == RAY_STR) EXPR_BAIL(EXPR_BAIL_STR); /* RAY_STR needs string comparison path */ /* GUID cells are 16-byte blobs the fused program has no * loads or compares for — without this bail the compiled @@ -790,14 +939,17 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { if (!((elem >= RAY_BOOL && elem <= RAY_TIMESTAMP) || elem == RAY_SYM)) EXPR_BAIL(EXPR_BAIL_OTHER); - if (col->attrs & RAY_ATTR_SLICE) EXPR_BAIL(EXPR_BAIL_SLICE); + /* An encoded source is never a slice (a slice of a parted or + * encoded column does not bind: ray_col_bind_declines). */ + if (src->obj->type != RAY_ENCCOL && (src->obj->attrs & RAY_ATTR_SLICE)) + EXPR_BAIL(EXPR_BAIL_SLICE); /* Length-1 columns used as scalar broadcasts are handled by the * fallback's exec_elementwise_binary (which has vec/scalar routing). * The fused evaluator reads exactly nrows elements from every scan * column — a length-1 column paired with nrows>1 would overread. */ - if (!RAY_IS_PARTED(col->type)) { + if (!src->parted) { int64_t nrows = ray_table_nrows(tbl); - if (col->len != nrows) EXPR_BAIL(EXPR_BAIL_OTHER); /* length-mismatch (scalar broadcast) */ + if (src->len != nrows) EXPR_BAIL(EXPR_BAIL_OTHER); /* length-mismatch (scalar broadcast) */ } /* sym-domain Phase 2: the fused program loads SYM cells * as raw i64s and resolves STR literals via the GLOBAL @@ -805,66 +957,112 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { * runtime-domain columns. FILE-domain columns bail to * the non-fused executor, which is domain-aware. No-op * pre-flip (every domain is the runtime singleton). */ - { - ray_t* sym_rep = sym_domain_rep(col); - if (sym_rep && ray_sym_vec_domain(sym_rep) != - ray_sym_runtime_domain()) + if (elem == RAY_SYM && src->dom != ray_sym_runtime_domain()) { + if (node->id >= nc || !sym_eq_only[node->id]) EXPR_BAIL(EXPR_BAIL_SYM_DOMAIN); + fd_src[r] = src; /* EQ / NE on ids: constants re-translated */ } /* Determine whether any lane in this column may be null. - * For parted columns the wrapper attrs may not reflect - * individual segments — scan all segments. SYM columns - * consumed only by null-safe comparisons skip the proof - * (see sym_cmp_safe above): their raw-id lanes already - * give the null-aware answers, so they compile as + * A generation-2 source answers from its directory. A + * generation-0 source keeps the per-segment scan (the + * wrapper attrs of a parted column may not reflect + * individual segments; SYM / STR report may_null always). + * SYM columns consumed only by null-safe comparisons skip + * the proof (see sym_cmp_safe above): their raw-id lanes + * already give the null-aware answers, so they compile as * non-nullable whether or not id 0 is present. */ bool need_proof = !(elem == RAY_SYM && node->id < nc && sym_cmp_safe[node->id]); - bool col_nulls = need_proof && ray_vec_has_nulls(col); - if (need_proof && RAY_IS_PARTED(col->type)) { - ray_t** segs = (ray_t**)ray_data(col); - for (int64_t s = 0; s < col->len; s++) - if (segs[s] && ray_vec_has_nulls(segs[s])) - col_nulls = true; + bool enc_src = src->obj->type == RAY_ENCCOL; + bool col_nulls = false; + if (need_proof && enc_src) col_nulls = src->may_null; + else if (need_proof && !src->may_null) col_nulls = false; + else if (need_proof) { + ray_t* c0 = src->obj; + col_nulls = ray_vec_has_nulls(c0); + if (RAY_IS_PARTED(c0->type)) { + ray_t** segs = (ray_t**)ray_data(c0); + for (int64_t s = 0; s < c0->len; s++) + if (segs[s] && ray_vec_has_nulls(segs[s])) + col_nulls = true; + } } /* Nullable SYM read as a value is out of scope: sym ids are * indistinguishable from the null sentinel (id 0) in raw * integer lanes. */ - if (col_nulls && (col->type == RAY_SYM || - (RAY_IS_PARTED(col->type) && - RAY_PARTED_BASETYPE(col->type) == RAY_SYM))) + if (col_nulls && elem == RAY_SYM) EXPR_BAIL(EXPR_BAIL_NULLS); + /* Past every gate. A source whose plain vector is ready + * (generation 0, or a published materialization) keeps + * today's capture; a generation-2 single-file source is + * range-read per morsel (expr_eval_morsel), never + * materialized here. An encoded parted source without a + * published materialization keeps is_parted over the + * RAY_ENCCOL itself: expr_eval_full_parted binds each + * encoded segment and reads it by range. */ + ray_t* ready = ray_col_src_ready(src); + bool enc = !src->parted && !ready; + bool enc_parted = src->parted && !ready; out->regs[r].kind = REG_SCAN; - if (RAY_IS_PARTED(col->type)) { - int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); - out->regs[r].col_type = base; - out->regs[r].data = NULL; /* resolved per-segment */ - out->regs[r].is_parted = true; - out->regs[r].col_obj = NULL; /* parted: per-segment, no zone-skip */ - out->regs[r].parted_col = col; - out->regs[r].type = (base == RAY_F64 || base == RAY_F32) - ? RAY_F64 : RAY_I64; - out->regs[r].nullable = col_nulls; - out->regs[r].null_src = col_nulls; - out->has_parted = true; - } else { - out->regs[r].col_type = col->type; - out->regs[r].col_attrs = col->attrs; - out->regs[r].data = ray_data(col); + out->regs[r].src = src; + out->regs[r].enc = enc; + if (enc) { + out->regs[r].col_type = src->type; + out->regs[r].col_attrs = src->attrs; + out->regs[r].data = NULL; out->regs[r].is_parted = false; - out->regs[r].col_obj = col; + out->regs[r].col_obj = NULL; out->regs[r].parted_col = NULL; - out->regs[r].type = (col->type == RAY_F64 || col->type == RAY_F32) + out->regs[r].type = (src->type == RAY_F64 || src->type == RAY_F32) ? RAY_F64 : RAY_I64; out->regs[r].nullable = col_nulls; out->regs[r].null_src = col_nulls; + } else { + ray_t* col = NULL; + if (enc_parted) col = src->obj; /* segments read by expr_eval_full_parted */ + else { + *err = ray_col_src_plain(src, &col); /* ready-only */ + if (*err) return false; + } + if (src->parted) { + int8_t base = elem; + out->regs[r].col_type = base; + out->regs[r].data = NULL; /* resolved per-segment */ + out->regs[r].is_parted = true; + out->regs[r].col_obj = NULL; /* parted: per-segment, no zone-skip */ + out->regs[r].parted_col = col; + out->regs[r].type = (base == RAY_F64 || base == RAY_F32) + ? RAY_F64 : RAY_I64; + out->regs[r].nullable = col_nulls; + out->regs[r].null_src = col_nulls; + out->has_parted = true; + } else { + out->regs[r].col_type = col->type; + out->regs[r].col_attrs = col->attrs; + out->regs[r].data = ray_data(col); + out->regs[r].is_parted = false; + out->regs[r].col_obj = col; + out->regs[r].parted_col = NULL; + out->regs[r].type = (col->type == RAY_F64 || col->type == RAY_F32) + ? RAY_F64 : RAY_I64; + out->regs[r].nullable = col_nulls; + out->regs[r].null_src = col_nulls; + } } } else if (node->opcode == OP_CONST) { ray_op_ext_t* ext = find_ext(g, node->id); if (!ext || !ext->literal) EXPR_BAIL(EXPR_BAIL_CONST); - if (RAY_ATOM_IS_NULL(ext->literal)) EXPR_BAIL(EXPR_BAIL_CONST); /* null constants need the null-aware path */ double cf; int64_t ci; bool is_f64; - if (!atom_to_numeric(ext->literal, &cf, &ci, &is_f64)) { + if (RAY_ATOM_IS_NULL(ext->literal)) { + /* null constants need the null-aware path, except "" + * and the null SYM: id 0 of a file-domain SYM compare, + * which reads its own re-translation (the check after + * the walk bails any other reader) */ + if (ext->literal->type != -RAY_STR && !expr_lit_null_sym(ext->literal)) + EXPR_BAIL(EXPR_BAIL_CONST); + const_unres[r] = true; + ci = 0; cf = 0; is_f64 = false; + } else if (!atom_to_numeric(ext->literal, &cf, &ci, &is_f64)) { /* Try resolving string constant to symbol intern ID — * enables fused evaluation of SYM column comparisons * (e.g. id2 = 'id080' compiles to integer EQ). */ @@ -872,7 +1070,10 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { const char* s = ray_str_ptr(ext->literal); size_t slen = ray_str_len(ext->literal); int64_t sid = ray_sym_find(s, slen); - if (sid < 0) EXPR_BAIL(EXPR_BAIL_CONST); + /* absent from the intern table: only a file-domain + * compare may read it, which re-translates it (the + * check after the walk bails any other reader) */ + if (sid < 0) { const_unres[r] = true; sid = -1; } ci = sid; cf = (double)sid; is_f64 = false; @@ -891,6 +1092,14 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { * the typed executor until the VM has a real F32 lane. */ if (node->out_type == RAY_F32) EXPR_BAIL(EXPR_BAIL_OTHER); + /* Narrow `%` results retain their type in the typed executor. + * Only the I64 lane can express the U8 divisor's zero rule + * without changing the result width. F64 uses its own lane. */ + if (node->opcode == OP_MOD && node->arity >= 2 && + node->out_type != RAY_I64 && node->out_type != RAY_F64 && + op_child(g, node, 1) && + op_child(g, node, 1)->out_type == RAY_U8) + EXPR_BAIL(EXPR_BAIL_NULL_SHAPE); if (!op_child(g, node, 0)) EXPR_BAIL(EXPR_BAIL_OTHER); uint8_t s1 = node_reg[node->in_id[0]]; if (s1 == 0xFF) EXPR_BAIL(EXPR_BAIL_OTHER); @@ -968,6 +1177,28 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { } } #undef EXPR_PROMOTE + /* EQ / NE of a file-domain SYM scan with a constant: the + * constant in the column's domain, in a register of this + * instruction's own (a shared constant register may feed a + * runtime-domain compare elsewhere). */ + if ((op == OP_EQ || op == OP_NE) && s2 != 0xFF && + (fd_src[s1] || fd_src[s2])) { + bool left = fd_src[s1] != NULL; + ray_op_t* cn = op_child(g, node, left ? 1 : 0); + uint8_t cs = left ? s2 : s1; + if (out->regs[cs].kind != REG_CONST) EXPR_BAIL(EXPR_BAIL_SYM_DOMAIN); + int64_t fid; + if (!expr_sym_lit_in(g, cn, left ? fd_src[s1] : fd_src[s2], &fid)) + EXPR_BAIL(EXPR_BAIL_CONST); + uint8_t nr = out->n_regs; + if (nr >= EXPR_MAX_REGS) EXPR_BAIL(EXPR_BAIL_REGS); + out->regs[nr].kind = REG_CONST; + out->regs[nr].type = RAY_I64; + out->regs[nr].const_i64 = fid; + out->regs[nr].const_f64 = (double)fid; + out->n_regs++; + if (left) s2 = nr; else s1 = nr; + } r = out->n_regs; /* re-read after possible CAST inserts */ if (r >= EXPR_MAX_REGS) EXPR_BAIL(EXPR_BAIL_REGS); @@ -1042,6 +1273,9 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { out->ins[out->n_ins++] = (expr_ins_t){ .opcode = (uint8_t)op, .dst = r, .src1 = s1, .src2 = s2, .null_aware = ins_null_aware ? 1 : 0, + .u8_mod_zero = (op == OP_MOD && ot == RAY_I64 && + op_child(g, node, 1) && + op_child(g, node, 1)->out_type == RAY_U8), }; } else { EXPR_BAIL(EXPR_BAIL_OTHER); @@ -1053,6 +1287,12 @@ bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out) { } if (out->n_regs == 0 || out->n_ins == 0) EXPR_BAIL(EXPR_BAIL_OTHER); + /* a STR constant the intern table lacks is read only through its + * file-domain re-translations */ + for (uint8_t i = 0; i < out->n_ins; i++) + if (const_unres[out->ins[i].src1] || + (out->ins[i].src2 != 0xFF && const_unres[out->ins[i].src2])) + EXPR_BAIL(EXPR_BAIL_CONST); out->out_reg = out->n_regs - 1; out->out_type = out->regs[out->out_reg].type; @@ -1192,7 +1432,8 @@ static void expr_load_f64(double* dst, const void* data, int8_t col_type, * AND/OR on I64-dst: task derivation forces BOOL dst for AND/OR since Task 6, * so these I64-dst cases are unreachable for null_aware programs; left plain. */ -static void expr_exec_binary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* dp, +static void expr_exec_binary(uint8_t opcode, uint8_t null_aware, uint8_t u8_mod_zero, + int8_t dt, void* dp, int8_t t1, const void* ap, int8_t t2, const void* bp, int64_t n) { (void)t2; @@ -1287,7 +1528,8 @@ static void expr_exec_binary(uint8_t opcode, uint8_t null_aware, int8_t dt, void break; case OP_MOD: for (int64_t j=0;jobj); +} + +/* Encoded register r's rows [start, start + n) inside one chunk of a + * synthetic stand-in whose every row is null: fill dst with what the decode + * and expr_load_* would give (the widened null, or the raw sentinel for a + * register compiled null-free) and return true, reading no payload. False: + * not such a chunk, or a type this does not cover (the range read runs). */ +static bool expr_enc_null_fill(const ray_expr_t* expr, uint8_t r, int64_t start, int64_t n, void* dst) { + const __typeof__(expr->regs[0])* rg = &expr->regs[r]; + if ((start >> 16) != ((start + n - 1) >> 16) || !expr_src_synthetic(rg->src)) return false; + int8_t ct = rg->col_type, rt = rg->type; + int64_t raw; + switch (ct) { + case RAY_I64: case RAY_TIMESTAMP: raw = NULL_I64; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: raw = NULL_I32; break; + case RAY_I16: raw = NULL_I16; break; + case RAY_F64: case RAY_F32: raw = 0; break; + default: return false; + } + ray_enc_chunk_stat_t st; + if (!ray_col_src_chunk_stat(rg->src, start >> 16, &st) || st.rows <= 0 || + (int64_t)st.null_count != st.rows) return false; + bool fl = ct == RAY_F64 || ct == RAY_F32; + if (rt == RAY_F64) { + double v = fl || rg->nullable ? NULL_F64 : (double)raw; + for (int64_t j = 0; j < n; j++) ((double*)dst)[j] = v; + return true; + } + if (rt != RAY_I64 || fl) return false; + int64_t v = rg->nullable ? NULL_I64 : raw; + for (int64_t j = 0; j < n; j++) ((int64_t*)dst)[j] = v; + return true; +} + +/* Load register r for morsel rows [start, start + n) into *rptr: a scan + * register's values (in place when its native type matches, else + * converted into scratch[r]; an encoded one by range, at most one vector + * per read), a constant broadcast into scratch[r], or scratch[r] for a + * scratch register. NULL, or an owned error when a range read fails. */ +RAY_INLINE ray_t* expr_load_reg(const ray_expr_t* expr, uint8_t r, void** scratch, + ray_col_scratch_t* rsc, int64_t start, int64_t n, void** rptr) { + int8_t rt = expr->regs[r].type; + int8_t ct = expr->regs[r].col_type; + switch (expr->regs[r].kind) { + case REG_SCAN: { + /* Direct pointer if native type matches, else convert. + * Nullable F64/I64 columns may take the direct path: their + * sentinels (NaN / NULL_I64) are already canonical in place. + * Narrow types always go through expr_load_* for sentinel + * normalization. */ + uint8_t ca = expr->regs[r].col_attrs; + bool hn = expr->regs[r].nullable; + bool direct = (rt == RAY_F64 && ct == RAY_F64) || + (rt == RAY_I64 && (ct == RAY_I64 || ct == RAY_TIMESTAMP)) || + (rt == RAY_I64 && ct == RAY_SYM && (ca & RAY_SYM_W_MASK) == RAY_SYM_W64); + if (expr->regs[r].enc) { + /* generation 2: at most one vector per range read; a + * morsel that straddles a vector boundary is assembled + * piece by piece into this register's scratch */ + int64_t at = 0; + *rptr = scratch[r]; + /* a morsel inside an all-null directory chunk (a ragged + * partition's synthetic segment) loads as the nulls the + * decode would give, without decoding */ + if (expr_enc_null_fill(expr, r, start, n, scratch[r])) return NULL; + /* a narrow integer register over one whole vector is + * widened straight from the packed values into the + * register (no range scratch, no expr_load pass) */ + if (!direct && (rt == RAY_I64 || rt == RAY_F64) && + (ct == RAY_BOOL || ct == RAY_U8 || ct == RAY_I16 || ct == RAY_I32 || + ct == RAY_DATE || ct == RAY_TIME)) { + ray_t* e = ray_col_range_wide(expr->regs[r].src, start, n, &rsc[r], rt, scratch[r], &at); + if (e) return e; + } + while (at < n) { + ray_col_range_t v; + ray_t* e = ray_col_range(expr->regs[r].src, start + at, n - at, &rsc[r], &v); + if (e) return e; + if (v.n <= 0) return ray_error("corrupt", "fused scan: short range read"); + if (at == 0 && v.n == n && direct) { *rptr = (void*)v.data; break; } + if (direct) + memcpy((char*)scratch[r] + at * 8, v.data, (size_t)v.n * 8); + else if (rt == RAY_F64) + expr_load_f64((double*)scratch[r] + at, v.data, ct, v.attrs, hn, 0, v.n); + else + expr_load_i64((int64_t*)scratch[r] + at, v.data, ct, v.attrs, hn, 0, v.n); + at += v.n; + } + } else if (direct) { + *rptr = (char*)expr->regs[r].data + (size_t)start * 8; + } else { + *rptr = scratch[r]; + if (rt == RAY_F64) + expr_load_f64(scratch[r], expr->regs[r].data, ct, ca, hn, start, n); + else + expr_load_i64(scratch[r], expr->regs[r].data, ct, ca, hn, start, n); + } + } + break; + case REG_CONST: + *rptr = scratch[r]; + if (rt == RAY_F64) { + double v = expr->regs[r].const_f64; + double* d = (double*)scratch[r]; + for (int64_t j = 0; j < n; j++) d[j] = v; + } else { + int64_t v = expr->regs[r].const_i64; + int64_t* d = (int64_t*)scratch[r]; + for (int64_t j = 0; j < n; j++) d[j] = v; + } + break; + default: /* REG_SCRATCH */ + *rptr = scratch[r]; + break; + } + return NULL; +} + +static int expr_leaf_on_view(const ray_expr_t* expr, const expr_enc_plan_t* p, uint8_t i, + ray_enc_vview_t* vbuf, void** scratch, void** rptrs, + int64_t start, int64_t n, ray_t** err); + /* Evaluate compiled expression for morsel [start, end). * scratch: array of EXPR_MAX_REGS buffers, each EXPR_MORSEL*8 bytes. - * Returns pointer to output data (morsel-relative indexing). */ -static void* expr_eval_morsel(const ray_expr_t* expr, void** scratch, - int64_t start, int64_t end) { + * rsc: one range scratch per register index, NULL when no register is + * encoded. plan (NULL: none, every register is loaded): the encoded + * leaves, answered on the vector's view (vbuf) where it has one; a + * register the plan does not load is loaded only when a leaf falls back + * to its kernel. Returns pointer to output data (morsel-relative + * indexing); NULL with an owned *err when a range read fails. Kept one + * copy (noclone) and the kernels' only caller, so the compiler inlines + * them here as it always has (generation 0's codegen). */ +/* noclone is GCC-only (clang rejects the attribute) */ +#if defined(__GNUC__) && !defined(__clang__) +#define EXPR_ONE_COPY __attribute__((noinline, noclone)) +#else +#define EXPR_ONE_COPY __attribute__((noinline)) +#endif +EXPR_ONE_COPY static void* expr_eval_morsel(const ray_expr_t* expr, const expr_enc_plan_t* plan, ray_enc_vview_t* vbuf, + void** scratch, ray_col_scratch_t* rsc, int64_t start, int64_t end, + ray_t** err) { int64_t n = end - start; if (n <= 0) return NULL; void* rptrs[EXPR_MAX_REGS]; + bool loaded[EXPR_MAX_REGS]; for (uint8_t r = 0; r < expr->n_regs; r++) { - int8_t rt = expr->regs[r].type; - int8_t ct = expr->regs[r].col_type; - switch (expr->regs[r].kind) { - case REG_SCAN: { - /* Direct pointer if native type matches, else convert. - * Nullable F64/I64 columns may take the direct path: their - * sentinels (NaN / NULL_I64) are already canonical in place. - * Narrow types always go through expr_load_* for sentinel - * normalization. */ - uint8_t ca = expr->regs[r].col_attrs; - if (rt == RAY_F64 && ct == RAY_F64) { - rptrs[r] = (double*)expr->regs[r].data + start; - } else if (rt == RAY_I64 && (ct == RAY_I64 || ct == RAY_TIMESTAMP)) { - rptrs[r] = (int64_t*)expr->regs[r].data + start; - } else if (rt == RAY_I64 && ct == RAY_SYM && - (ca & RAY_SYM_W_MASK) == RAY_SYM_W64) { - rptrs[r] = (int64_t*)expr->regs[r].data + start; - } else { - rptrs[r] = scratch[r]; - bool hn = expr->regs[r].nullable; - if (rt == RAY_F64) - expr_load_f64(scratch[r], expr->regs[r].data, ct, ca, hn, start, n); - else - expr_load_i64(scratch[r], expr->regs[r].data, ct, ca, hn, start, n); - } - } - break; - case REG_CONST: - rptrs[r] = scratch[r]; - if (rt == RAY_F64) { - double v = expr->regs[r].const_f64; - double* d = (double*)scratch[r]; - for (int64_t j = 0; j < n; j++) d[j] = v; - } else { - int64_t v = expr->regs[r].const_i64; - int64_t* d = (int64_t*)scratch[r]; - for (int64_t j = 0; j < n; j++) d[j] = v; - } - break; - default: /* REG_SCRATCH */ - rptrs[r] = scratch[r]; - break; - } + if (plan && !plan->load_reg[r]) { rptrs[r] = scratch[r]; loaded[r] = false; continue; } + loaded[r] = true; + ray_t* e = expr_load_reg(expr, r, scratch, rsc, start, n, &rptrs[r]); + if (e) { *err = e; return NULL; } } for (uint8_t i = 0; i < expr->n_ins; i++) { const expr_ins_t* ins = &expr->ins[i]; + if (plan && plan->leaf_of_ins[i] >= 0) { + int lv = expr_leaf_on_view(expr, plan, i, vbuf, scratch, rptrs, start, n, err); + if (lv < 0) return NULL; + if (lv > 0) continue; + /* no view or no evaluator: load the register (once) and run the kernel */ + uint8_t lr = plan->leaf[plan->leaf_of_ins[i]].reg; + if (!loaded[lr]) { + ray_t* e = expr_load_reg(expr, lr, scratch, rsc, start, n, &rptrs[lr]); + if (e) { *err = e; return NULL; } + loaded[lr] = true; + } + } int8_t dt = expr->regs[ins->dst].type; if (ins->src2 != 0xFF) { - expr_exec_binary(ins->opcode, ins->null_aware, dt, rptrs[ins->dst], + expr_exec_binary(ins->opcode, ins->null_aware, ins->u8_mod_zero, + dt, rptrs[ins->dst], expr->regs[ins->src1].type, rptrs[ins->src1], expr->regs[ins->src2].type, rptrs[ins->src2], n); } else { @@ -1901,38 +2261,93 @@ static int zone_cmp_decision(const ray_index_t* ix, int64_t ch, uint16_t cmp_op, int64_t cval) { const int64_t* mins = (const int64_t*)ray_data(ix->u.chunk_zone.mins); const int64_t* maxs = (const int64_t*)ray_data(ix->u.chunk_zone.maxs); - int64_t cmin = mins[ch], cmax = maxs[ch]; - if (cmin > cmax) return ZT_MIXED; /* all-null chunk: leave to kernel */ const uint8_t* nb = (const uint8_t*)ray_data(ix->u.chunk_zone.null_bits); bool has_nulls = (nb[ch >> 3] >> (ch & 7)) & 1u; + int d = zone_cmp_core(mins[ch], maxs[ch], true, has_nulls, false, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; +} + +/* (null cmp_op cval) for a chunk of a synthetic stand-in whose every row is + * null: every lane loads as NULL_I64, which both the null-aware and the + * plain i64 kernels rank below every value, so null == c, null > c and + * null >= c fail and null != c, null < c and null <= c pass. The constant + * is never the null (expr_zone_decide leaves a null constant to the + * kernel). */ +static int zone_all_null_decision(uint16_t cmp_op) { switch (cmp_op) { - case OP_EQ: - if (cval < cmin || cval > cmax) return 0; - if (!has_nulls && cmin == cmax) return 1; - break; - case OP_NE: - if (!has_nulls && (cval < cmin || cval > cmax)) return 1; - if (!has_nulls && cmin == cmax && cval == cmin) return 0; - break; - case OP_LT: - if (!has_nulls && cmin >= cval) return 0; - if (!has_nulls && cmax < cval) return 1; - break; - case OP_LE: - if (!has_nulls && cmin > cval) return 0; - if (!has_nulls && cmax <= cval) return 1; - break; - case OP_GT: - if (cmax <= cval) return 0; - if (!has_nulls && cmin > cval) return 1; - break; - case OP_GE: - if (cmax < cval) return 0; - if (!has_nulls && cmin >= cval) return 1; - break; - default: break; + case OP_EQ: case OP_GT: case OP_GE: return 0; + case OP_NE: case OP_LT: case OP_LE: return 1; + default: return ZT_MIXED; } - return ZT_MIXED; +} + +/* Directory-statistics twin of zone_cmp_decision for a generation-2 + * register: chunk ch of its bound source (a single file, or the encoded + * segment a parted register is rebound to; the morsel rows are the + * source's own). Undecided when the source has no directory. */ +_Static_assert(RAY_ENC_CHUNK == 1 << 16, "the directory gate reads 64K-row chunks"); +static int zone_dir_decision(const ray_col_src_t* src, int64_t ch, uint16_t cmp_op, int64_t cval) { + ray_enc_chunk_stat_t st; + if (!ray_col_src_chunk_stat(src, ch, &st)) return ZT_MIXED; + bool all_null = (int64_t)st.null_count == st.rows; + if (all_null && st.rows > 0 && expr_src_synthetic(src)) return zone_all_null_decision(cmp_op); + int d = zone_cmp_core(st.min, st.max, st.has_minmax, st.null_count > 0, all_null, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; +} + +/* The same over vector v of the register's source, from its descriptor: + * for a morsel inside one vector of a chunk its directory left undecided. + * Answer-only (the morsel is filled, never read), so no consumer guard. */ +static int zone_vec_decision(const ray_col_src_t* src, int64_t v, uint16_t cmp_op, int64_t cval) { + int64_t mn, mx; uint32_t nn; + if (!ray_col_src_vec_stat(src, v, &mn, &mx, &nn)) return ZT_MIXED; + int d = zone_cmp_core(mn, mx, true, nn > 0, false, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; +} + +/* The SYM arm of the two decisions above (zone_sym_decision): EQ / NE of + * a SYM register against an id of its domain (-1: absent, decided without + * statistics). A chunk whose every row is id 0 is decided from its + * directory only for a synthetic stand-in, as zone_dir_decision does; a + * saved one is left to its vectors, whose views validate it. */ +static int zone_sym_dir_decision(const ray_col_src_t* src, int64_t ch, uint16_t cmp_op, int64_t cval) { + if (cval < 0) return zone_sym_decision(0, 0, false, 0, 1, cmp_op, cval); + ray_enc_chunk_stat_t st; + if (!ray_col_src_chunk_stat(src, ch, &st)) return ZT_MIXED; + if ((int64_t)st.null_count == st.rows && !expr_src_synthetic(src)) return ZT_MIXED; + int d = zone_sym_decision(st.min, st.max, st.has_minmax, (int64_t)st.null_count, st.rows, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; +} +static int zone_sym_vec_decision(const ray_col_src_t* src, int64_t v, uint16_t cmp_op, int64_t cval) { + int64_t mn, mx; uint32_t nn; + if (!ray_col_src_vec_stat(src, v, &mn, &mx, &nn)) return ZT_MIXED; + int64_t rows = src->len - v * RAY_ENC_VEC; /* the last vector may be short */ + if (rows > RAY_ENC_VEC) rows = RAY_ENC_VEC; + int d = zone_sym_decision(mn, mx, true, nn, rows, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; +} + +/* The float arm of the two decisions above: an F32 / F64 register against + * an F64 constant, from the double extrema (bit patterns) of the chunk's + * directory and then of the vector's descriptor. A chunk whose every row + * is null is left to the kernel (zone_cmp_core_f64), synthetic or not. */ +static inline bool zone_f64_type(int8_t t) { return t == RAY_F32 || t == RAY_F64; } +static int zone_dir_decision_f64(const ray_col_src_t* src, int64_t ch, uint16_t cmp_op, double cval) { + ray_enc_chunk_stat_t st; + if (!ray_col_src_chunk_stat(src, ch, &st)) return ZT_MIXED; + double mn, mx; + memcpy(&mn, &st.min, 8); memcpy(&mx, &st.max, 8); + int d = zone_cmp_core_f64(mn, mx, st.has_minmax, st.null_count > 0, + (int64_t)st.null_count == st.rows, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; +} +static int zone_vec_decision_f64(const ray_col_src_t* src, int64_t v, uint16_t cmp_op, double cval) { + int64_t bmn, bmx; uint32_t nn; + if (!ray_col_src_vec_stat(src, v, &bmn, &bmx, &nn)) return ZT_MIXED; + double mn, mx; + memcpy(&mn, &bmn, 8); memcpy(&mx, &bmx, 8); + int d = zone_cmp_core_f64(mn, mx, true, nn > 0, false, cmp_op, cval); + return d < 0 ? ZT_MIXED : d; } /* Does `col` carry a fresh, integer/temporal chunk-zone index? */ @@ -1950,7 +2365,10 @@ static inline const ray_index_t* zone_fresh_index(const ray_t* col) { static bool expr_zone_eligible(const ray_expr_t* expr) { if (expr->out_type != RAY_BOOL) return false; for (uint8_t r = 0; r < expr->n_regs; r++) - if (expr->regs[r].kind == REG_SCAN && zone_fresh_index(expr->regs[r].col_obj)) + if (expr->regs[r].kind == REG_SCAN && + (expr->regs[r].enc ? zone_dir_type(expr->regs[r].col_type) || zone_f64_type(expr->regs[r].col_type) || + expr->regs[r].col_type == RAY_SYM + : zone_fresh_index(expr->regs[r].col_obj) != NULL)) return true; return false; } @@ -1965,23 +2383,63 @@ static int expr_zone_decide(const ray_expr_t* expr, int64_t ms, int64_t me) { const expr_ins_t* in = &expr->ins[i]; uint16_t op = in->opcode; if (op >= OP_EQ && op <= OP_GE && in->src2 != 0xFF) { - const ray_t* col = NULL; int64_t cval = 0; uint16_t cmp = op; + const ray_t* col = NULL; int src_reg = -1; int64_t cval = 0; uint16_t cmp = op; uint8_t a = in->src1, b = in->src2; if (expr->regs[a].kind == REG_SCAN && expr->regs[b].kind == REG_CONST && expr->regs[b].type == RAY_I64) { - col = expr->regs[a].col_obj; cval = expr->regs[b].const_i64; + col = expr->regs[a].col_obj; src_reg = a; cval = expr->regs[b].const_i64; } else if (expr->regs[b].kind == REG_SCAN && expr->regs[a].kind == REG_CONST && expr->regs[a].type == RAY_I64) { - col = expr->regs[b].col_obj; cval = expr->regs[a].const_i64; + col = expr->regs[b].col_obj; src_reg = b; cval = expr->regs[a].const_i64; cmp = zone_swap_op(op); } int d = ZT_MIXED; - const ray_index_t* ix = zone_fresh_index(col); - if (ix) { - uint8_t log2 = ix->u.chunk_zone.chunk_log2; - int64_t s_ch = ms >> log2, e_ch = (me - 1) >> log2; - if (s_ch == e_ch && (uint32_t)s_ch < ix->u.chunk_zone.n_chunks) - d = zone_cmp_decision(ix, s_ch, cmp, cval); + /* the float arm: an encoded F32 / F64 register against an F64 + * constant (generation-0 float registers have no zone: their + * chunk-zone index is never is_f64-admitted). A NaN constant + * (the null) is left to the kernel. */ + int fr = -1; double fc = 0; uint16_t fcmp = op; + if (expr->regs[a].kind == REG_SCAN && expr->regs[a].enc && zone_f64_type(expr->regs[a].col_type) && + expr->regs[a].type == RAY_F64 && expr->regs[b].kind == REG_CONST && expr->regs[b].type == RAY_F64) { + fr = a; fc = expr->regs[b].const_f64; + } else if (expr->regs[b].kind == REG_SCAN && expr->regs[b].enc && zone_f64_type(expr->regs[b].col_type) && + expr->regs[b].type == RAY_F64 && expr->regs[a].kind == REG_CONST && expr->regs[a].type == RAY_F64) { + fr = b; fc = expr->regs[a].const_f64; fcmp = zone_swap_op(op); + } + if (fr >= 0 && fc == fc) { + if ((ms >> 16) == ((me - 1) >> 16)) + d = zone_dir_decision_f64(expr->regs[fr].src, ms >> 16, fcmp, fc); + if (d == ZT_MIXED && ms / RAY_ENC_VEC == (me - 1) / RAY_ENC_VEC) + d = zone_vec_decision_f64(expr->regs[fr].src, ms / RAY_ENC_VEC, fcmp, fc); + } + /* A null constant is left to the kernel, before any arm: no + * extrema rule covers it. Unreachable today (the compiler bails + * a null constant, EXPR_BAIL_CONST), it guards every arm if that + * bail is ever relaxed. */ + if (src_reg >= 0 && cval == NULL_I64) { src_reg = -1; col = NULL; } + if (src_reg >= 0 && expr->regs[src_reg].enc && expr->regs[src_reg].col_type == RAY_SYM) { + /* SYM: the membership rule on ids, EQ / NE only */ + const ray_col_src_t* ss = expr->regs[src_reg].src; + if ((ms >> 16) == ((me - 1) >> 16)) + d = zone_sym_dir_decision(ss, ms >> 16, cmp, cval); + if (d == ZT_MIXED && ms / RAY_ENC_VEC == (me - 1) / RAY_ENC_VEC) + d = zone_sym_vec_decision(ss, ms / RAY_ENC_VEC, cmp, cval); + } else if (src_reg >= 0 && expr->regs[src_reg].enc) { + /* generation 2: the directory's chunk of 64K rows, then the + * descriptor of the vector the morsel lies in */ + if (zone_dir_type(expr->regs[src_reg].col_type) && (ms >> 16) == ((me - 1) >> 16)) + d = zone_dir_decision(expr->regs[src_reg].src, ms >> 16, cmp, cval); + if (d == ZT_MIXED && zone_dir_type(expr->regs[src_reg].col_type) && + ms / RAY_ENC_VEC == (me - 1) / RAY_ENC_VEC) + d = zone_vec_decision(expr->regs[src_reg].src, ms / RAY_ENC_VEC, cmp, cval); + } else { + const ray_index_t* ix = zone_fresh_index(col); + if (ix) { + uint8_t log2 = ix->u.chunk_zone.chunk_log2; + int64_t s_ch = ms >> log2, e_ch = (me - 1) >> log2; + if (s_ch == e_ch && (uint32_t)s_ch < ix->u.chunk_zone.n_chunks) + d = zone_cmp_decision(ix, s_ch, cmp, cval); + } } tri[in->dst] = d; } else if (op == OP_AND && in->src2 != 0xFF) { @@ -1996,6 +2454,173 @@ static int expr_zone_decide(const ray_expr_t* expr, int64_t ms, int64_t me) { return (res == 0 || res == 1) ? res : -1; } +/* ── Encoded leaves of a fused BOOL program ────────────────────────────── + * + * A comparison of an encoded single-file scan register with a constant of + * the same lane type is a leaf: per morsel (one vector) it is answered on + * the vector's view (store/enceval.h: CONST one test, RLE one per run, + * FOR_BP on the packed residuals, DICT a code interval) with the null mask, + * and its register is never decoded unless some non-leaf instruction reads + * it as a value, or the vector has no view. An integer column against a + * float constant is not a leaf (the F64 lanes compare in double: no + * constant is narrowed), nor is an ordered compare on SYM (#738). */ + +/* The lane value the register load gives a null row: the canonical + * sentinel for a nullable register, else the raw in-band sentinel widened + * (expr_load_i64 without has_nulls). F64 lanes: NaN either way. */ +static int64_t leaf_null_lane_i64(int8_t ct, bool nullable) { + if (nullable) return NULL_I64; + switch (ct) { + case RAY_I32: case RAY_DATE: case RAY_TIME: return (int64_t)NULL_I32; + case RAY_I16: return (int64_t)NULL_I16; + default: return NULL_I64; + } +} + +/* One-lane null_result of a leaf: run the leaf's own kernel, through the + * morsel evaluator, on one row whose scan lane holds a null row's value + * against the constant (a three-register program of two constants). */ +static uint8_t leaf_null_result(const ray_expr_t* expr, const expr_ins_t* in, uint8_t scan_reg) { + uint8_t other = in->src1 == scan_reg ? in->src2 : in->src1; + ray_expr_t one; + memset(&one, 0, sizeof one); + one.n_regs = 3; one.n_ins = 1; one.n_scratch = 1; one.out_reg = 2; one.out_type = RAY_BOOL; + one.regs[0].kind = REG_CONST; one.regs[0].type = expr->regs[scan_reg].type; /* RAY_I64 or RAY_F64 lanes */ + one.regs[0].const_i64 = leaf_null_lane_i64(expr->regs[scan_reg].col_type, expr->regs[scan_reg].nullable); + one.regs[0].const_f64 = NULL_F64; + one.regs[1].kind = REG_CONST; one.regs[1].type = expr->regs[other].type; + one.regs[1].const_i64 = expr->regs[other].const_i64; one.regs[1].const_f64 = expr->regs[other].const_f64; + one.regs[2].kind = REG_SCRATCH; one.regs[2].type = RAY_BOOL; + one.ins[0] = (expr_ins_t){ .opcode = in->opcode, .dst = 2, .src1 = in->src1 == scan_reg ? 0 : 1, + .src2 = in->src1 == scan_reg ? 1 : 0, .null_aware = in->null_aware }; + int64_t lanes[3] = { 0, 0, 0 }; + void* sc[3] = { &lanes[0], &lanes[1], &lanes[2] }; + ray_t* err = NULL; + const uint8_t* out = (const uint8_t*)expr_eval_morsel(&one, NULL, NULL, sc, NULL, 0, 1, &err); + if (err) ray_error_free(err); /* constants only: no read */ + return out ? out[0] : 0; +} + +/* Can encoded scan register r against a constant of its own lane type be + * a leaf? I64 lanes over an integer, temporal or SYM column (SYM under + * EQ / NE only), F64 lanes over an F32 / F64 column. */ +static bool leaf_reg_ok(const ray_expr_t* expr, uint8_t r, uint16_t op) { + int8_t ct = expr->regs[r].col_type; + if (expr->regs[r].type == RAY_F64) return zone_f64_type(ct); + if (expr->regs[r].type != RAY_I64) return false; + if (ct == RAY_SYM) return op == OP_EQ || op == OP_NE; /* never order ids (#738) */ + return zone_dir_type(ct); +} + +/* The plan of an expression, or NULL when no register is encoded (a + * generation-0 program: nothing to plan). */ +static const expr_enc_plan_t* expr_enc_plan_build(const ray_expr_t* expr, expr_enc_plan_t* p) { + bool any = false; + for (uint8_t r = 0; r < expr->n_regs; r++) any |= expr->regs[r].kind == REG_SCAN && expr->regs[r].enc; + if (!any) return NULL; + memset(p, 0, sizeof *p); + memset(p->leaf_of_ins, -1, sizeof p->leaf_of_ins); + for (uint8_t r = 0; r < expr->n_regs; r++) + p->load_reg[r] = !(expr->regs[r].kind == REG_SCAN && expr->regs[r].enc); + if (expr->out_type != RAY_BOOL) { + for (uint8_t r = 0; r < expr->n_regs; r++) p->load_reg[r] = true; + return p; + } + for (uint8_t i = 0; i < expr->n_ins; i++) { + const expr_ins_t* in = &expr->ins[i]; + uint8_t a = in->src1, b = in->src2; + bool ea = expr->regs[a].kind == REG_SCAN && expr->regs[a].enc; + bool eb = b != 0xFF && expr->regs[b].kind == REG_SCAN && expr->regs[b].enc; + int sreg = -1, creg = -1; + if (in->opcode >= OP_EQ && in->opcode <= OP_GE && b != 0xFF) { + if (ea && expr->regs[b].kind == REG_CONST && expr->regs[b].type == expr->regs[a].type) { sreg = a; creg = b; } + else if (eb && expr->regs[a].kind == REG_CONST && expr->regs[a].type == expr->regs[b].type) { sreg = b; creg = a; } + } + uint16_t op = sreg == a ? in->opcode : zone_swap_op(in->opcode); + if (sreg >= 0 && !leaf_reg_ok(expr, (uint8_t)sreg, op)) sreg = -1; + if (sreg >= 0) { + expr_enc_leaf_t* l = &p->leaf[p->n_leaves]; + l->ins = i; l->reg = (uint8_t)sreg; l->op = op; + l->is_f64 = expr->regs[sreg].type == RAY_F64; + l->ci = expr->regs[creg].const_i64; l->cf = expr->regs[creg].const_f64; + l->null_result = leaf_null_result(expr, in, (uint8_t)sreg); + p->leaf_of_ins[i] = (int8_t)p->n_leaves++; + } else { + if (ea) p->load_reg[a] = true; /* read as a value */ + if (eb) p->load_reg[b] = true; + } + } + return p; +} + +/* Leaf instruction i over morsel [ms, ms + n) (one vector: + * RAY_MORSEL_ELEMS == RAY_ENC_VEC), on the vector's view: 1 answered into + * the instruction's register (a CONST decision, or the encoded evaluator + * with the null mask), 0 no view or no evaluator (the caller loads the + * register and runs the kernel), -1 an owned *err (the view's validation, + * as the decode would report it). */ +_Static_assert(RAY_MORSEL_ELEMS == RAY_ENC_VEC, "a fused morsel is one vector"); +static int expr_leaf_on_view(const ray_expr_t* expr, const expr_enc_plan_t* p, uint8_t i, + ray_enc_vview_t* vbuf, void** scratch, void** rptrs, + int64_t ms, int64_t n, ray_t** err) { + const expr_ins_t* in = &expr->ins[i]; + const expr_enc_leaf_t* l = &p->leaf[p->leaf_of_ins[i]]; + if (ms % RAY_ENC_VEC) return 0; + int vr = ray_col_src_vview(expr->regs[l->reg].src, ms / RAY_ENC_VEC, vbuf, err); + if (vr <= 0) return vr; + if (n != vbuf->n) return 0; + uint8_t* out = (uint8_t*)scratch[in->dst]; + int cd = l->is_f64 ? ray_enc_const_decision_f64(vbuf, l->op, l->cf, l->null_result) + : ray_enc_const_decision(vbuf, l->op, l->ci, l->null_result); + if (cd >= 0) memset(out, cd, (size_t)n); + else if (!(l->is_f64 ? ray_enc_eval_cmp_f64(vbuf, l->op, l->cf, l->null_result, out) + : ray_enc_eval_cmp(vbuf, l->op, l->ci, l->null_result, out))) return 0; + rptrs[in->dst] = out; + return 1; +} + +static _Atomic(int64_t) g_expr_leaf_runs; /* test hook */ +int64_t ray_expr_test_leaf_runs(void) { return atomic_load_explicit(&g_expr_leaf_runs, memory_order_relaxed); } + +/* A program that is one leaf: its only instruction is the leaf and its + * output (a selection is the leaf's answer itself). */ +static bool expr_single_leaf(const ray_expr_t* expr, const expr_enc_plan_t* p) { + return p && p->n_leaves == 1 && expr->n_ins == 1 && p->leaf_of_ins[0] == 0 && + expr->ins[0].dst == expr->out_reg; +} + +/* A single-leaf program's selection segment for morsel [ms, ms + n) (one + * vector), emitted from the vector's view: a CONST decision as one + * uniform segment, an RLE view without bitmap nulls from its runs + * (ray_enc_eval_cmp_runs: no per-row bools to scan), any other view + * through the encoded evaluator's bools (out, a morsel buffer). The + * segment is the one rowsel_emit_segment makes of expr_leaf_on_view's + * bools. 1 emitted, 0 no view or no evaluator (the caller's morsel + * evaluation, nothing emitted), -1 an owned *err. */ +static int expr_leaf_emit(const ray_expr_t* expr, const expr_enc_plan_t* p, ray_enc_vview_t* vbuf, + rowsel_builder_t* sb, uint32_t lseg, uint8_t* out, int64_t ms, int64_t n, + ray_t** err) { + const expr_enc_leaf_t* l = &p->leaf[0]; + if (ms % RAY_ENC_VEC) return 0; + int vr = ray_col_src_vview(expr->regs[l->reg].src, ms / RAY_ENC_VEC, vbuf, err); + if (vr <= 0) return vr; + if (n != vbuf->n) return 0; + int cd = l->is_f64 ? ray_enc_const_decision_f64(vbuf, l->op, l->cf, l->null_result) + : ray_enc_const_decision(vbuf, l->op, l->ci, l->null_result); + if (cd >= 0) { rowsel_emit_uniform(sb, lseg, (uint8_t)cd, n); return 1; } + uint8_t pass[RAY_ENC_VEC]; + if (l->is_f64 ? ray_enc_eval_cmp_runs_f64(vbuf, l->op, l->cf, pass) + : ray_enc_eval_cmp_runs(vbuf, l->op, l->ci, pass)) { + rowsel_emit_runs(sb, lseg, vbuf->run_ends.h, pass, vbuf->n_runs, n); + atomic_fetch_add_explicit(&g_expr_leaf_runs, 1, memory_order_relaxed); + return 1; + } + if (!(l->is_f64 ? ray_enc_eval_cmp_f64(vbuf, l->op, l->cf, l->null_result, out) + : ray_enc_eval_cmp(vbuf, l->op, l->ci, l->null_result, out))) return 0; + rowsel_emit_segment(sb, lseg, out, n); + return 1; +} + /* Context for parallel full-vector expression evaluation. * * Two output modes: @@ -2014,27 +2639,53 @@ typedef struct { int8_t out_type; rowsel_builder_t* sel_builders; /* NULL = normal bool/vec output */ uint32_t n_sel_builders; /* slot count (fused mode only) */ + ray_scan_fail_t* fail; /* range-read failures, keyed by task start */ + int64_t key_base; /* added to every failure key: a parted + * segment's first row, so keys are global */ + const expr_enc_plan_t* plan; /* encoded leaves (NULL or none: every + * register is loaded, generation 0's loop) */ } expr_full_ctx_t; -static void expr_full_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { +static _Atomic(int64_t) g_expr_zone_skips; /* test hook */ +int64_t ray_expr_test_zone_skips(void) { return atomic_load_explicit(&g_expr_zone_skips, memory_order_relaxed); } + +static void expr_full_block(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { (void)worker_id; expr_full_ctx_t* c = (expr_full_ctx_t*)ctx; const ray_expr_t* expr = c->expr; uint8_t esz = ray_elem_size(c->out_type); + /* a lower task already failed: this one cannot change the answer (the + * coordinator discards the output; a skipped selection builder stays + * all-NONE) */ + int64_t key = c->key_base + start; + if (ray_scan_fail_skip(c->fail, key)) return; /* Per-worker scratch buffers (heap-allocated via arena, morsel-sized) */ ray_t* scratch_hdr = NULL; /* one morsel buffer per register the expression uses */ char* scratch_mem = (char*)scratch_alloc(&scratch_hdr, (size_t)(expr->n_regs ? expr->n_regs : 1) * EXPR_MORSEL * 8); - if (!scratch_mem) return; + if (!scratch_mem) { ray_scan_fail_note(c->fail, key, ray_error("oom", "fused expression scratch")); return; } void* scratch[EXPR_MAX_REGS]; for (uint8_t r = 0; r < expr->n_regs; r++) scratch[r] = scratch_mem + (size_t)r * EXPR_MORSEL * 8; + /* range scratch, one per register index, only when a register is + * read by range */ + ray_col_scratch_t rsc_arr[EXPR_MAX_REGS]; + ray_col_scratch_t* rsc = NULL; + for (uint8_t r = 0; r < expr->n_regs; r++) + if (expr->regs[r].kind == REG_SCAN && expr->regs[r].enc) { rsc = rsc_arr; break; } + if (rsc) for (uint8_t r = 0; r < expr->n_regs; r++) ray_col_scratch_init(&rsc[r]); + bool failed = false; /* Chunk-zone skip is only possible for a BOOL predicate over a zone- * indexed column; compute the gate once, not per morsel. */ bool zone = expr_zone_eligible(expr); + int64_t skips = 0; + /* encoded leaves: one vector view on this task's stack (never the heap) */ + const expr_enc_plan_t* plan = c->plan && c->plan->n_leaves ? c->plan : NULL; + ray_enc_vview_t vbuf; + const bool leaf1 = expr_single_leaf(expr, plan); /* Fused selection-output mode: resolve this task's builder + its first * global segment once. Task boundaries are morsel-aligned because @@ -2059,6 +2710,7 @@ static void expr_full_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t e if (zone) { int d = expr_zone_decide(expr, ms, me); if (d >= 0) { /* whole morsel decided from extrema — skip the read */ + skips++; if (sb) { /* Emit a uniform ALL (d=1) / NONE (d=0) segment: memset a * scratch bool buffer (unused on this branch — no eval ran) @@ -2072,7 +2724,19 @@ static void expr_full_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t e continue; } } - void* result = expr_eval_morsel(expr, scratch, ms, me); + if (sb && leaf1 && !failed) { + ray_t* err = NULL; + uint32_t lseg = (uint32_t)(ms / RAY_MORSEL_ELEMS) - local_base_seg; + int lr = expr_leaf_emit(expr, plan, &vbuf, sb, lseg, (uint8_t*)scratch[0], ms, me - ms, &err); + if (lr > 0) continue; + if (lr < 0) { ray_scan_fail_note(c->fail, key, err); failed = true; } + } + void* result = NULL; + if (!failed) { + ray_t* err = NULL; + result = expr_eval_morsel(expr, plan, plan ? &vbuf : NULL, scratch, rsc, ms, me, &err); + if (err) { ray_scan_fail_note(c->fail, key, err); failed = true; result = NULL; } + } if (sb) { /* Selection mode: emit this morsel's bools (or, on the rare * eval-NULL internal error, a none-pass segment so the builder's @@ -2084,7 +2748,23 @@ static void expr_full_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t e memcpy((char*)c->out_data + ms * esz, result, (size_t)(me - ms) * esz); } } + if (rsc) for (uint8_t r = 0; r < expr->n_regs; r++) ray_col_scratch_free(&rsc[r]); scratch_free(scratch_hdr); + if (skips) atomic_fetch_add_explicit(&g_expr_zone_skips, skips, memory_order_relaxed); +} + +/* A dispatched task of expr_eval_full: in fused selection mode one rowsel + * builder per TASK_GRAIN block (see pred_sel_worker: a clamped dispatch + * hands out tasks of several blocks). */ +static void expr_full_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + const expr_full_ctx_t* c = (const expr_full_ctx_t*)ctx; + const int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; + if (!c->sel_builders || c->n_sel_builders <= 1 || end - start <= grain) { + expr_full_block(ctx, worker_id, start, end); + return; + } + for (int64_t b = start; b < end; b += grain) + expr_full_block(ctx, worker_id, b, b + grain < end ? b + grain : end); } /* Post-pass for the fused unary path: |INT64_MIN| and -INT64_MIN don't fit in @@ -2126,9 +2806,32 @@ static void expr_flag_output_nulls(const ray_expr_t* expr, ray_t* out, int64_t n else if (expr->out_type == RAY_F64) mark_f64_nonfinite_as_null(out, 0, nrows); } +/* Test hook: the parted evaluator runs every segment instead of stopping + * at the first failing one, so the global failure keys alone must pick the + * lowest failure. */ +static bool g_expr_test_parted_all_segs; +void ray_expr_test_parted_all_segments(bool on) { g_expr_test_parted_all_segs = on; } + +/* Segment s of a parted register's object: a plain segment vector, a + * RAY_ENCCOL (generation 2 or synthetic), or NULL for a missing segment. */ +static ray_t* expr_seg(ray_t* parted_col, int64_t s) { + if (parted_col->type == RAY_ENCCOL) return ray_enccol_seg(parted_col, s); + return ((ray_t**)ray_data(parted_col))[s]; /* not-a-table: a parted wrapper */ +} +static int64_t expr_nsegs(ray_t* parted_col) { + return parted_col->type == RAY_ENCCOL ? ray_enccol_of(parted_col)->wrapper->len : parted_col->len; +} + /* Evaluate compiled expression over parted (segmented) columns. - * Iterates segments as outer loop, rebinds data pointers per segment, - * then dispatches the existing morsel evaluator per segment. Zero copy. */ + * Iterates segments as outer loop, rebinds every parted register to the + * segment, then dispatches the existing morsel evaluator per segment. A + * plain segment (or an encoded one whose materialization is published) is + * read in place; an encoded segment (generation 2, or the synthetic null + * segment of a ragged partition) is bound as its own source and read by + * range, never materialized. Failure keys are global rows (the segment's + * first row plus the task start), so the lowest failure in row order is + * the answer; segments run in order, and the first failing one or a + * cancel ends the loop (a cancel is answered by ray_scan_fail_finish). */ static ray_t* expr_eval_full_parted(const ray_expr_t* expr, int64_t nrows) { ray_t* out = ray_vec_new(expr->out_type, nrows); if (!out || RAY_IS_ERR(out)) { @@ -2146,55 +2849,96 @@ static ray_t* expr_eval_full_parted(const ray_expr_t* expr, int64_t nrows) { } if (!ref_parted) { ray_release(out); return ray_error("nyi", NULL); } - int64_t n_segs = ref_parted->len; + int64_t n_segs = expr_nsegs(ref_parted); uint8_t esz = ray_elem_size(expr->out_type); ray_pool_t* pool = ray_pool_get(); int64_t global_off = 0; + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + bool dispatched = false; for (int64_t s = 0; s < n_segs; s++) { /* Determine segment length from any non-NULL parted register */ int64_t seg_len = 0; for (uint8_t r = 0; r < expr->n_regs; r++) { if (expr->regs[r].is_parted) { - ray_t** segs = (ray_t**)ray_data(expr->regs[r].parted_col); - if (segs[s]) { seg_len = segs[s]->len; break; } + ray_t* seg = expr_seg(expr->regs[r].parted_col, s); + if (seg) { seg_len = ray_table_col_nrows(seg); break; } } } if (seg_len <= 0) continue; - /* Stack-copy expr, rebind parted registers to this segment's data */ + /* Stack-copy expr, rebind parted registers to this segment */ ray_expr_t seg_expr = *expr; + ray_col_src_t seg_src[EXPR_MAX_REGS]; /* bound in place, released below */ + uint8_t n_seg_src = 0; bool seg_ok = true; for (uint8_t r = 0; r < seg_expr.n_regs; r++) { - if (seg_expr.regs[r].is_parted) { - ray_t** segs = (ray_t**)ray_data(seg_expr.regs[r].parted_col); - if (!segs[s]) { seg_ok = false; break; } - seg_expr.regs[r].data = ray_data(segs[s]); + if (!seg_expr.regs[r].is_parted) continue; + ray_t* seg = expr_seg(seg_expr.regs[r].parted_col, s); + if (!seg) { seg_ok = false; break; } + /* every register reads the same rows: a segment of another + * length is a malformed table, never clipped */ + int64_t rl = ray_table_col_nrows(seg); + if (rl != seg_len) { + ray_scan_fail_note(&fail, global_off, + ray_error("length", "parted expression: segment %lld has %lld rows, expected %lld", + (long long)s, (long long)rl, (long long)seg_len)); + seg_ok = false; break; + } + ray_t* segp = seg; + if (seg->type == RAY_ENCCOL) { + ray_t* pk = ray_enccol_decoded_peek(seg); /* published: read it in place */ + if (pk) segp = pk; + } + seg_expr.regs[r].is_parted = false; + if (segp->type == RAY_ENCCOL) { + ray_t* be = ray_col_src_bind(seg, &seg_src[n_seg_src]); + if (be) { ray_scan_fail_note(&fail, global_off, be); seg_ok = false; break; } + seg_expr.regs[r].src = &seg_src[n_seg_src++]; + seg_expr.regs[r].enc = true; + seg_expr.regs[r].data = NULL; + seg_expr.regs[r].col_attrs = seg_expr.regs[r].src->attrs; + ray_col_src_advise(seg_expr.regs[r].src, 0, seg_len); + } else { + seg_expr.regs[r].enc = false; + seg_expr.regs[r].data = ray_data(segp); /* SYM index width is PER SEGMENT (partitions saved at * different vocabulary sizes legitimately differ) — the * compile-time reg carries no width for parted scans. */ - seg_expr.regs[r].col_attrs = segs[s]->attrs; + seg_expr.regs[r].col_attrs = segp->attrs; } } - if (!seg_ok) { + if (seg_ok) { + /* the segment's leaves: its registers are encoded only after + * the rebinding, and read this segment's own descriptors */ + expr_enc_plan_t plan; + expr_full_ctx_t ctx = { + .expr = &seg_expr, + .out_data = (char*)ray_data(out) + global_off * esz, + .out_type = expr->out_type, + .fail = &fail, + .key_base = global_off, + .plan = expr_enc_plan_build(&seg_expr, &plan), + }; + if (pool && seg_len >= RAY_PARALLEL_THRESHOLD) { + ray_pool_dispatch(pool, expr_full_fn, &ctx, seg_len); + dispatched = true; + } else + expr_full_fn(&ctx, 0, 0, seg_len); + } else if (!ray_scan_failed(&fail)) { memset((char*)ray_data(out) + global_off * esz, 0, (size_t)seg_len * esz); - global_off += seg_len; - continue; } - - expr_full_ctx_t ctx = { - .expr = &seg_expr, - .out_data = (char*)ray_data(out) + global_off * esz, - .out_type = expr->out_type, - }; - if (pool && seg_len >= RAY_PARALLEL_THRESHOLD) - ray_pool_dispatch(pool, expr_full_fn, &ctx, seg_len); - else - expr_full_fn(&ctx, 0, 0, seg_len); - + for (uint8_t i = 0; i < n_seg_src; i++) ray_col_src_release(&seg_src[i]); global_off += seg_len; + /* the lowest failing segment ends the loop; so does a cancel, which + * a later inline segment's failure could otherwise overtake */ + if (ray_scan_failed(&fail) && !g_expr_test_parted_all_segs) break; + if (ray_interrupted() || (pool && atomic_load_explicit(&pool->cancelled, memory_order_acquire))) + break; } + ray_t* ferr = ray_scan_fail_finish(&fail, dispatched ? pool : NULL); + if (ferr) { ray_release(out); return ferr; } expr_flag_output_nulls(expr, out, nrows); return out; } @@ -2209,20 +2953,46 @@ ray_t* expr_eval_full(const ray_expr_t* expr, int64_t nrows) { if (!out || RAY_IS_ERR(out)) return out; out->len = nrows; + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + expr_enc_plan_t plan; expr_full_ctx_t ctx = { - .expr = expr, .out_data = ray_data(out), .out_type = expr->out_type, + .expr = expr, .out_data = ray_data(out), .out_type = expr->out_type, .fail = &fail, + .plan = expr_enc_plan_build(expr, &plan), }; + for (uint8_t r = 0; r < expr->n_regs; r++) + if (expr->regs[r].kind == REG_SCAN && expr->regs[r].enc) + ray_col_src_advise(expr->regs[r].src, 0, nrows); ray_pool_t* pool = ray_pool_get(); - if (pool && nrows >= RAY_PARALLEL_THRESHOLD) + bool par = pool && nrows >= RAY_PARALLEL_THRESHOLD; + if (par) ray_pool_dispatch(pool, expr_full_fn, &ctx, nrows); else expr_full_fn(&ctx, 0, 0, nrows); + ray_t* ferr = ray_scan_fail_finish(&fail, par ? pool : NULL); + if (ferr) { ray_release(out); return ferr; } expr_flag_output_nulls(expr, out, nrows); return out; } +/* Run the morsel evaluator of a BOOL program over [start, end) (at most + * EXPR_MORSEL rows, any alignment) into out[0 .. end - start). */ +void ray_expr_test_eval_range(const ray_expr_t* expr, int64_t start, int64_t end, + uint8_t* out, ray_t** err) { + *err = NULL; + ray_t* hdr = NULL; + char* mem = (char*)scratch_alloc(&hdr, (size_t)(expr->n_regs ? expr->n_regs : 1) * EXPR_MORSEL * 8); + if (!mem) { *err = ray_error("oom", NULL); return; } + void* scratch[EXPR_MAX_REGS]; + ray_col_scratch_t rsc[EXPR_MAX_REGS]; + for (uint8_t r = 0; r < expr->n_regs; r++) { scratch[r] = mem + (size_t)r * EXPR_MORSEL * 8; ray_col_scratch_init(&rsc[r]); } + void* res = expr_eval_morsel(expr, NULL, NULL, scratch, rsc, start, end, err); + if (res && !*err) memcpy(out, res, (size_t)(end - start)); + for (uint8_t r = 0; r < expr->n_regs; r++) ray_col_scratch_free(&rsc[r]); + scratch_free(hdr); +} + /* ============================================================================ * Fused predicate → row selection * @@ -2244,11 +3014,10 @@ ray_t* expr_eval_full(const ray_expr_t* expr, int64_t nrows) { /* Allocate + init one rowsel builder per dispatched grain task (parallel) or a * single builder over all segments (serial). ray_pool_dispatch carves task i * as [i*grain, min((i+1)*grain, nrows)); grain is morsel-aligned so each task - * owns a contiguous run of whole segments. On return *parallel and *n_builders - * describe the dispatch geometry. Returns NULL when the table needs more tasks - * than the ring holds (pool clamps n_tasks to RAY_POOL_MAX_TASKS and re-derives - * a non-morsel-aligned grain, which would trip the worker's `start % grain == 0` - * assert) or on OOM — caller falls back to the bool path. */ + * owns a contiguous run of whole segments; tasks past the ring run in further + * rounds of the same grain, so one builder per task holds for any table. On + * return *parallel and *n_builders describe the dispatch geometry. Returns + * NULL on OOM — caller falls back to the bool path. */ static rowsel_builder_t* pred_sel_builders_alloc(int64_t nrows, ray_pool_t* pool, bool* parallel, uint32_t* n_builders_out) { @@ -2257,7 +3026,6 @@ static rowsel_builder_t* pred_sel_builders_alloc(int64_t nrows, ray_pool_t* pool bool par = (pool && nrows >= RAY_PARALLEL_THRESHOLD); uint32_t n_builders = par ? (uint32_t)((nrows + grain - 1) / grain) : 1u; - if (par && n_builders > RAY_POOL_MAX_TASKS) return NULL; rowsel_builder_t* builders = (rowsel_builder_t*)ray_alloc_raw((size_t)n_builders * sizeof(rowsel_builder_t)); @@ -2312,16 +3080,25 @@ typedef struct { void* fill_ctx; rowsel_builder_t* sel_builders; uint32_t n_sel_builders; + ray_scan_fail_t* fail; /* NULL: the fill cannot fail */ } pred_sel_drive_ctx_t; -static void pred_sel_worker(void* vctx, uint32_t worker_id, - int64_t start, int64_t end) { +static void pred_sel_block(void* vctx, uint32_t worker_id, + int64_t start, int64_t end) { (void)worker_id; pred_sel_drive_ctx_t* c = (pred_sel_drive_ctx_t*)vctx; + /* a lower task already failed: this one cannot change the answer (a + * skipped builder stays all-NONE; the coordinator discards it) */ + if (c->fail && ray_scan_fail_skip(c->fail, start)) return; ray_t* scratch_hdr = NULL; uint8_t* scratch = (uint8_t*)scratch_alloc(&scratch_hdr, RAY_MORSEL_ELEMS); - if (!scratch) return; + if (!scratch) { + if (c->fail) ray_scan_fail_note(c->fail, start, ray_error("oom", "selection scratch")); + return; + } + ray_col_scratch_t sc; /* this task's range scratch */ + ray_col_scratch_init(&sc); const int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; _Static_assert((RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS) % RAY_MORSEL_ELEMS == 0, @@ -2334,15 +3111,29 @@ static void pred_sel_worker(void* vctx, uint32_t worker_id, for (int64_t ms = start; ms < end; ms += RAY_MORSEL_ELEMS) { int64_t me = (ms + RAY_MORSEL_ELEMS < end) ? ms + RAY_MORSEL_ELEMS : end; - c->fill(c->fill_ctx, ms, me - ms, scratch); + c->fill(c->fill_ctx, &sc, ms, me - ms, scratch); uint32_t lseg = (uint32_t)(ms / RAY_MORSEL_ELEMS) - local_base_seg; rowsel_emit_segment(sb, lseg, scratch, me - ms); } + ray_col_scratch_free(&sc); scratch_free(scratch_hdr); } +/* A dispatched task of the fused selection: one rowsel builder per + * TASK_GRAIN block. ray_pool_dispatch keeps task starts at multiples of + * the grain it was asked for, but a clamped dispatch (a ring that cannot + * grow) hands out wider tasks: those run block by block, each into its own + * builder. */ +static void pred_sel_worker(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { + const pred_sel_drive_ctx_t* c = (const pred_sel_drive_ctx_t*)vctx; + const int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; + if (c->n_sel_builders <= 1 || end - start <= grain) { pred_sel_block(vctx, worker_id, start, end); return; } + for (int64_t b = start; b < end; b += grain) + pred_sel_block(vctx, worker_id, b, b + grain < end ? b + grain : end); +} + ray_t* pred_sel_drive(int64_t nrows, pred_sel_fill_fn fill, void* fill_ctx, - bool* all_pass) { + ray_scan_fail_t* fail, bool* all_pass) { *all_pass = false; if (nrows <= 0) { *all_pass = true; return NULL; } @@ -2358,13 +3149,22 @@ ray_t* pred_sel_drive(int64_t nrows, pred_sel_fill_fn fill, void* fill_ctx, .fill_ctx = fill_ctx, .sel_builders = builders, .n_sel_builders = n_builders, + .fail = fail, }; if (parallel) ray_pool_dispatch(pool, pred_sel_worker, &ctx, nrows); else pred_sel_worker(&ctx, 0, 0, nrows); - return pred_sel_builders_finish(builders, n_builders, nrows, all_pass); + bool ap = false; + ray_t* block = pred_sel_builders_finish(builders, n_builders, nrows, &ap); + ray_t* ferr = fail ? ray_scan_fail_finish(fail, parallel ? pool : NULL) : NULL; + if (ferr) { + if (block) ray_rowsel_release(block); + return ferr; + } + *all_pass = ap; + return block; } ray_t* exec_pred_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, @@ -2379,11 +3179,17 @@ ray_t* exec_pred_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, * bool fallback: its 4 input-shape paths + dict-LUT pipeline don't reduce * to a clean per-morsel fill. `between` desugars to >=/<= AND and so * already rides the expr path below.) */ + if (pred->opcode == OP_EQ || pred->opcode == OP_NE) { + /* a generation-2 STR column against a STR constant (codes, code bounds) */ + ray_t* ss = exec_str_to_selection(g, pred, nrows, all_pass); + if (ss || *all_pass) return ss; /* answered, or an error */ + } if (pred->opcode == OP_IN || pred->opcode == OP_NOT_IN) return exec_in_to_selection(g, pred, nrows, all_pass); ray_expr_t ex; - if (!expr_compile(g, g->table, pred, &ex)) return NULL; + ray_t* cerr = NULL; + if (!expr_compile(g, g->table, pred, &ex, &cerr)) return cerr; /* NULL: unsupported */ if (ex.out_type != RAY_BOOL || ex.has_parted) return NULL; ray_pool_t* pool = ray_pool_get(); @@ -2393,19 +3199,199 @@ ray_t* exec_pred_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, pred_sel_builders_alloc(nrows, pool, ¶llel, &n_builders); if (!builders) return NULL; + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + expr_enc_plan_t plan; expr_full_ctx_t ctx = { .expr = &ex, .out_data = NULL, .out_type = ex.out_type, .sel_builders = builders, .n_sel_builders = n_builders, + .fail = &fail, + .plan = expr_enc_plan_build(&ex, &plan), }; + for (uint8_t r = 0; r < ex.n_regs; r++) + if (ex.regs[r].kind == REG_SCAN && ex.regs[r].enc) + ray_col_src_advise(ex.regs[r].src, 0, nrows); if (parallel) ray_pool_dispatch(pool, expr_full_fn, &ctx, nrows); else expr_full_fn(&ctx, 0, 0, nrows); - return pred_sel_builders_finish(builders, n_builders, nrows, all_pass); + bool ap = false; + ray_t* block = pred_sel_builders_finish(builders, n_builders, nrows, &ap); + ray_t* ferr = ray_scan_fail_finish(&fail, parallel ? pool : NULL); + if (ferr) { + if (block) ray_rowsel_release(block); + return ferr; + } + *all_pass = ap; + return block; +} + +/* exec_pred_to_selection restricted to an existing selection: a chained + * filter's refinement over generation-2 columns. Only the segments `sel` + * keeps are evaluated, through the same encoded leaves and zone decisions + * as the fused selection path (vectors read as views, decided by their + * statistics, never decoded where a leaf serves them); each segment's + * bools are ANDed with the selection's own rows and emitted. Its own + * instance: expr_full_fn, generation 0's loop, keeps its code. */ +/* One MIX segment of the refinement: the selection's rows ix[0, cnt) that + * pass (res NULL: every one), appended to the builder as + * rowsel_emit_segment would classify the ANDed bools, without scanning + * the segment's n bools. */ +static ray_t* refine_emit_mix(rowsel_builder_t* b, uint32_t seg, const uint16_t* ix, uint32_t cnt, + const uint8_t* res, int64_t n) { + b->seg_off[seg] = b->idx_len; + b->seg_flags[seg] = RAY_SEL_NONE; + b->seg_off[seg + 1] = b->idx_len; + if (b->idx_len + cnt > b->idx_cap) { + uint32_t newcap = b->idx_cap ? b->idx_cap : 8u; + while (newcap < b->idx_len + cnt) newcap *= 2u; + uint16_t* ni = (uint16_t*)ray_realloc_raw(b->idx, (size_t)newcap * sizeof(uint16_t)); + if (!ni) return ray_error("oom", "refinement selection"); + b->idx = ni; + b->idx_cap = newcap; + } + uint32_t pc = 0; + for (uint32_t k = 0; k < cnt; k++) { + if (ix[k] >= n) /* as gsel_range reports it */ + return ray_error("corrupt", "refinement: selection row %u past its segment", (unsigned)ix[k]); + if (!res || res[ix[k]]) b->idx[b->idx_len + pc++] = ix[k]; + } + b->total_pass += pc; + if (pc == 0) b->seg_flags[seg] = RAY_SEL_NONE; + else if ((int64_t)pc == n) b->seg_flags[seg] = RAY_SEL_ALL; /* ALL contributes nothing to idx[] */ + else { b->seg_flags[seg] = RAY_SEL_MIX; b->idx_len += pc; } + b->seg_off[seg + 1] = b->idx_len; + return NULL; +} + +typedef struct { + const ray_expr_t* expr; + const expr_enc_plan_t* plan; + const uint8_t* flags; + const uint32_t* offs; + const uint16_t* idx; + rowsel_builder_t* sel_builders; /* one per task */ + uint32_t n_sel_builders; + int64_t nrows, n_segs; + ray_scan_fail_t* fail; +} expr_refine_ctx_t; + +static void expr_refine_task(expr_refine_ctx_t* c, uint32_t t) { + const ray_expr_t* expr = c->expr; + const int64_t s0 = c->n_segs * t / c->n_sel_builders, s1 = c->n_segs * (t + 1) / c->n_sel_builders; + const int64_t start = s0 * RAY_MORSEL_ELEMS; + const int64_t end = s1 * RAY_MORSEL_ELEMS < c->nrows ? s1 * RAY_MORSEL_ELEMS : c->nrows; + rowsel_builder_t* sb = &c->sel_builders[t]; + const uint32_t base_seg = (uint32_t)s0; + if (s0 >= s1) return; + if (ray_scan_fail_skip(c->fail, start)) { + for (int64_t seg = s0; seg < s1; seg++) { /* the builder still covers its segments */ + const uint32_t ls = (uint32_t)(seg - s0); + sb->seg_off[ls] = sb->idx_len; sb->seg_flags[ls] = RAY_SEL_NONE; sb->seg_off[ls + 1] = sb->idx_len; + } + return; + } + ray_t* scratch_hdr = NULL; + char* scratch_mem = (char*)scratch_alloc(&scratch_hdr, + (size_t)(expr->n_regs ? expr->n_regs : 1) * EXPR_MORSEL * 8); + bool failed = false; + if (!scratch_mem) { ray_scan_fail_note(c->fail, start, ray_error("oom", "fused expression scratch")); failed = true; } + void* scratch[EXPR_MAX_REGS]; + for (uint8_t r = 0; r < expr->n_regs && scratch_mem; r++) scratch[r] = scratch_mem + (size_t)r * EXPR_MORSEL * 8; + ray_col_scratch_t rsc_arr[EXPR_MAX_REGS]; + ray_col_scratch_t* rsc = NULL; + for (uint8_t r = 0; r < expr->n_regs; r++) + if (expr->regs[r].kind == REG_SCAN && expr->regs[r].enc) { rsc = rsc_arr; break; } + if (rsc) for (uint8_t r = 0; r < expr->n_regs; r++) ray_col_scratch_init(&rsc[r]); + const expr_enc_plan_t* plan = c->plan && c->plan->n_leaves ? c->plan : NULL; + ray_enc_vview_t vbuf; + for (int64_t ms = start; ms < end; ms += EXPR_MORSEL) { + int64_t me = ms + EXPR_MORSEL < end ? ms + EXPR_MORSEL : end; + const int64_t n = me - ms; + const uint32_t seg = (uint32_t)(ms / RAY_MORSEL_ELEMS); + const uint8_t f = c->flags[seg]; + if (f == RAY_SEL_NONE || failed) { + /* rowsel_emit_segment's NONE outcome without scanning n bools */ + const uint32_t ls = seg - base_seg; + sb->seg_off[ls] = sb->idx_len; + sb->seg_flags[ls] = RAY_SEL_NONE; + sb->seg_off[ls + 1] = sb->idx_len; + continue; + } + const uint8_t* res = NULL; + /* the leaves decide whole vectors on their views; a failed or empty + * evaluation passes no row (as expr_full_fn emits it) */ + ray_t* err = NULL; + res = (const uint8_t*)expr_eval_morsel(expr, plan, plan ? &vbuf : NULL, scratch, rsc, ms, me, &err); + if (err) { ray_scan_fail_note(c->fail, start, err); failed = true; res = NULL; } + const uint32_t ls = seg - base_seg; + if (!res) { + sb->seg_off[ls] = sb->idx_len; + sb->seg_flags[ls] = RAY_SEL_NONE; + sb->seg_off[ls + 1] = sb->idx_len; + continue; + } + if (f == RAY_SEL_MIX) { + if ((err = refine_emit_mix(sb, ls, c->idx + c->offs[seg], c->offs[seg + 1] - c->offs[seg], res, n)) != NULL) { + ray_scan_fail_note(c->fail, start, err); + failed = true; + } + continue; + } + rowsel_emit_segment(sb, ls, res, n); + } + if (rsc) for (uint8_t r = 0; r < expr->n_regs; r++) ray_col_scratch_free(&rsc[r]); + scratch_free(scratch_hdr); +} + +static void expr_refine_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + (void)worker_id; + for (int64_t t = start; t < end; t++) expr_refine_task((expr_refine_ctx_t*)ctx, (uint32_t)t); +} + +ray_t* exec_pred_refine_selection(ray_graph_t* g, ray_op_t* pred, ray_t* sel, bool* all_pass) { + *all_pass = false; + if (!g || !g->table || !pred || !sel) return NULL; + ray_rowsel_t* m = ray_rowsel_meta(sel); + const int64_t nrows = m->nrows; + if (nrows <= 0 || nrows != ray_table_nrows(g->table)) return NULL; + if (pred->opcode == OP_EQ || pred->opcode == OP_NE) { + ray_t* ss = exec_str_refine_selection(g, pred, sel, all_pass); + if (ss || *all_pass) return ss; /* answered, or an error */ + } + ray_expr_t ex; + ray_t* cerr = NULL; + if (!expr_compile(g, g->table, pred, &ex, &cerr)) return cerr; /* NULL: unsupported */ + if (ex.out_type != RAY_BOOL || ex.has_parted) return NULL; + /* tasks over contiguous segment ranges, one builder each: four per + * worker (as the first-n pass splits its segments), so a sparse + * selection allocates few builders */ + ray_pool_t* pool = ray_pool_get(); + const int64_t n_segs = (nrows + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS; + const bool parallel = ray_pool_par_dispatch_ok(pool, nrows, RAY_PARALLEL_THRESHOLD); + int64_t ntask = parallel ? (int64_t)ray_pool_total_workers(pool) * 4 : 1; + if (ntask > n_segs) ntask = n_segs; + const uint32_t n_builders = (uint32_t)(ntask > 0 ? ntask : 1); + rowsel_builder_t* builders = (rowsel_builder_t*)ray_alloc_raw((size_t)n_builders * sizeof(rowsel_builder_t)); + if (!builders) return NULL; + for (uint32_t t = 0; t < n_builders; t++) + rowsel_builder_init(&builders[t], (uint32_t)(n_segs * (t + 1) / n_builders - n_segs * t / n_builders)); + ray_scan_fail_t fail; ray_scan_fail_init(&fail); + expr_enc_plan_t plan; + expr_refine_ctx_t ctx = { .expr = &ex, .plan = expr_enc_plan_build(&ex, &plan), + .flags = ray_rowsel_flags(sel), .offs = ray_rowsel_offsets(sel), .idx = ray_rowsel_idx(sel), + .sel_builders = builders, .n_sel_builders = n_builders, .nrows = nrows, .n_segs = n_segs, .fail = &fail }; + if (n_builders > 1) ray_pool_dispatch_n(pool, expr_refine_fn, &ctx, n_builders); + else expr_refine_fn(&ctx, 0, 0, 1); + bool ap = false; + ray_t* block = pred_sel_builders_finish(builders, n_builders, nrows, &ap); + ray_t* ferr = ray_scan_fail_finish(&fail, parallel ? pool : NULL); + if (ferr) { if (block) ray_rowsel_release(block); return ferr; } + *all_pass = ap; + return block; } /* ============================================================================ @@ -2595,6 +3581,20 @@ static bool ew_unary_math_type_admitted(uint16_t opcode, int8_t t) { } ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { + if (input && !RAY_IS_ERR(input) && (ray_has_timespan(input) || op->out_type == RAY_TIMESPAN)) { + if (op->opcode == OP_CAST) { + const char* name = ray_type_name(op->out_type); + ray_t* target = ray_sym(ray_sym_intern(name, strlen(name))); + if (RAY_IS_ERR(target)) return target; + ray_t* result = ray_cast_fn(target, input); + ray_release(target); + return result; + } + if (op->opcode == OP_NEG) return ray_neg_fn(input); + if (op->opcode == OP_ABS) return ray_abs_fn(input); + if (op->opcode != OP_ISNULL) return ray_error("type", "unsupported duration unary operation"); + } + (void)g; if (!input || RAY_IS_ERR(input)) return input; if (!ray_is_vec(input)) return ray_error("type", "expr eval: unary op expects a vector, got %s", ray_type_name(input->type)); @@ -2650,8 +3650,9 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { int64_t n = m.morsel_len; float* dst = (float*)ray_data(result) + out_off; if (in_type == RAY_F64) { + /* Saturate past the F32 range, as the `as` builtin does. */ const double* src = (const double*)m.morsel_ptr; - for (int64_t i = 0; i < n; i++) dst[i] = (float)src[i]; + for (int64_t i = 0; i < n; i++) dst[i] = ray_cast_f64_to_f32_null(src[i]); } else if (in_type == RAY_F32) { memcpy(dst, m.morsel_ptr, (size_t)n * sizeof(float)); } else if (in_type == RAY_I64 || in_type == RAY_TIMESTAMP) { @@ -2849,14 +3850,13 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { } } else if (in_type == RAY_I64 && out_type == RAY_BOOL && opc == OP_CAST) { { - /* (as 'BOOL i64_col) — truthy semantics; NULL_I64 = INT64_MIN - * sentinel is non-zero but logically missing, so skip it. */ + /* BOOL has no null; its integer null sentinel is non-zero. */ while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; int64_t* src = (int64_t*)m.morsel_ptr; uint8_t* dst = (uint8_t*)((char*)ray_data(result) + out_off); for (int64_t i = 0; i < n; i++) - dst[i] = (src[i] != 0 && src[i] != NULL_I64) ? 1 : 0; + dst[i] = src[i] != 0 ? 1 : 0; out_off += n; } } @@ -2914,9 +3914,8 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { if (out_type == RAY_I32) ((int32_t*)dst)[i] = (int32_t)v; else if (out_type == RAY_I16) ((int16_t*)dst)[i] = (int16_t)v; else if (out_type == RAY_U8) ((uint8_t*)dst)[i] = (uint8_t)v; - else /* BOOL: a null is not true, as in the I64 and F64 arms */ - ((uint8_t*)dst)[i] = v != 0 && !(it == RAY_I32 && v == NULL_I32) && - !(it == RAY_I16 && v == NULL_I16); + else /* BOOL: a non-zero null sentinel also becomes true. */ + ((uint8_t*)dst)[i] = v != 0; } out_off += n; } @@ -3046,9 +4045,7 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { double* src = (double*)m.morsel_ptr; uint8_t* dst = (uint8_t*)((char*)ray_data(result) + out_off); if (ot == RAY_BOOL) - /* NaN (NULL_F64 sentinel) is "missing"; IEEE - * `NaN != 0.0` is true so add an explicit - * `src[i] == src[i]` to filter NaN to false. */ + /* Non-zero values, including NaN, become true. */ for (int64_t i = 0; i < n; i++) dst[i] = ray_cast_f64_to_bool_null(src[i]); else @@ -3061,7 +4058,8 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { /* Propagate null bitmap from input to result. OP_ISNULL never reaches * here — it is handled and returned before the typed dispatch above. */ - if (vec_may_have_nulls(input)) + if (vec_may_have_nulls(input) && + !(opc == OP_CAST && (out_type == RAY_BOOL || out_type == RAY_U8))) propagate_nulls(input, result, len); /* OP_NEG/OP_ABS over i64: |INT64_MIN| and -INT64_MIN don't fit — surface @@ -3334,9 +4332,8 @@ static void binary_range(ray_op_t* op, int8_t out_type, /* SYM index scratch — needed ONLY by narrow-width (W8/W16) or cross-domain * SYM columns. Allocated lazily on the heap (freed at `done:`) rather than - * as a stack VLA: the pool can hand a worker a morsel far larger than a page - * (grain is total/task_cap once the ring saturates), so an n-sized stack - * array would overflow the worker stack. Non-SYM ops (the common case) + * as a stack VLA: a caller can hand a worker a range far larger than a + * page, so an n-sized stack array would overflow the worker stack. Non-SYM ops (the common case) * allocate nothing. */ int64_t* lsym_buf = NULL; int64_t* rsym_buf = NULL; @@ -3532,7 +4529,31 @@ static void binary_range(ray_op_t* op, int8_t out_type, case OP_MUL: for(int64_t i=0;iattrs, (uint8_t)RAY_ATTR_HAS_NULLS, + __ATOMIC_RELAXED); + } else if (idiv_i64_inline_gate) { /* Gate rides inside the divide loop: each element is read * once, range-checked in-register, and divided by the * vectorizable double kernel. If any element (or a null, @@ -3608,7 +4629,9 @@ static void binary_range(ray_op_t* op, int8_t out_type, for(int64_t i=0;iri?li:ri;}break; default: for(int64_t i=0;inodes[op->in_id[0]].out_type; + int8_t right_type = g->nodes[op->in_id[1]].out_type; + if (ray_has_timespan(lhs) || ray_has_timespan(rhs) || + left_type == RAY_TIMESPAN || right_type == RAY_TIMESPAN || + (op->opcode == OP_SUB && left_type == RAY_TIMESTAMP && right_type == RAY_TIMESTAMP)) { + /* Constant payloads are integers; the graph carries their temporal types. */ + ray_t left_atom, right_atom; + if (ray_is_atom(lhs) && (left_type == RAY_TIMESPAN || left_type == RAY_TIMESTAMP)) { + left_atom = *lhs; left_atom.type = -left_type; lhs = &left_atom; + } + if (ray_is_atom(rhs) && (right_type == RAY_TIMESPAN || right_type == RAY_TIMESTAMP)) { + right_atom = *rhs; right_atom.type = -right_type; rhs = &right_atom; + } + return ray_timespan_binary(op->opcode, lhs, rhs); + } bool l_scalar = ray_is_atom(lhs) || (lhs->type > 0 && lhs->len == 1); bool r_scalar = ray_is_atom(rhs) || (rhs->type > 0 && rhs->len == 1); @@ -4038,8 +5076,29 @@ ray_t* exec_elementwise_binary(ray_graph_t* g, ray_op_t* op, ray_t* lhs, ray_t* const int32_t* b = (const int32_t*)ray_data(rhs); for (int64_t i = 0; i < len; i++) if (b[i] == 0) ray_vec_set_null(result, i, true); + } else if (rt == RAY_I16 && !(opc == OP_IDIV && + (result->type == RAY_I64 || result->type == RAY_TIMESTAMP))) { + const int16_t* b = (const int16_t*)ray_data(rhs); + for (int64_t i = 0; i < len; i++) + if (b[i] == 0) ray_vec_set_null(result, i, true); + } else if ((rt == RAY_U8 && opc != OP_MOD) || rt == RAY_BOOL) { + /* `%` by a U8 divisor is unsigned byte modulo: 0, no null */ + const uint8_t* b = (const uint8_t*)ray_data(rhs); + for (int64_t i = 0; i < len; i++) + if (b[i] == 0) ray_vec_set_null(result, i, true); + } else if (rt == RAY_F64 && result->type != RAY_F64) { + /* An F64 result already holds NULL_F64 there; an integer + * one (div of floats) holds 0. */ + const double* b = (const double*)ray_data(rhs); + for (int64_t i = 0; i < len; i++) + if (b[i] == 0.0) ray_vec_set_null(result, i, true); + } else if (rt == RAY_F32 && result->type != RAY_F32 && + result->type != RAY_F64) { + const float* b = (const float*)ray_data(rhs); + for (int64_t i = 0; i < len; i++) + if (b[i] == 0.0f) ray_vec_set_null(result, i, true); } - /* F64 div-by-zero produces NaN which is handled by propagate_nulls */ + /* A U8 / BOOL result has no null (ray_vec_set_null declines). */ } else { /* Scalar divisor: check for zero using the correct type */ bool is_zero = false; @@ -4048,6 +5107,9 @@ ray_t* exec_elementwise_binary(ray_graph_t* g, ray_op_t* op, ray_t* lhs, ray_t* is_zero = (r_f64_val == 0.0); else is_zero = (r_i64_val == 0); + /* rt: an atom or a length-one vector alike */ + if (opc == OP_MOD && rt == RAY_U8) + is_zero = false; /* unsigned byte modulo: 0, no null */ if (is_zero) { for (int64_t i = 0; i < len; i++) ray_vec_set_null(result, i, true); diff --git a/src/ops/filter.c b/src/ops/filter.c index 090f89a86..f8a8c825c 100644 --- a/src/ops/filter.c +++ b/src/ops/filter.c @@ -24,6 +24,7 @@ #include "ops/internal.h" #include "ops/rowsel.h" #include "lang/internal.h" /* sym_domain_rep (sym-domain Phase 2) */ +#include "ops/colgather.h" /* ============================================================================ * Filter execution — extracted from exec.c @@ -32,7 +33,8 @@ /* Gather from a parted column using global row indices (sorted ascending). * Walks match_idx with an advancing segment cursor — O(count + n_segs). */ static void parted_gather_col(ray_t* parted_col, const int64_t* match_idx, - int64_t count, ray_t* dst_col) { + int64_t count, ray_t* dst_col, + const int64_t* cnt, int64_t ncnt) { int64_t n_segs = parted_col->len; if (n_segs == 0) return; /* zero-length VLA is UB in C17 */ ray_t** segs = (ray_t**)ray_data(parted_col); @@ -44,11 +46,12 @@ static void parted_gather_col(ray_t* parted_col, const int64_t* match_idx, char* dst = (char*)ray_data(dst_col); memset(dst, 0, (size_t)count * esz); - /* Build prefix-sum segment end table */ + /* Build prefix-sum segment end table (a NULL segment spans its + * partition's rows, from the table's partition counts) */ int64_t seg_ends[n_segs]; int64_t cumul = 0; for (int64_t i = 0; i < n_segs; i++) { - cumul += segs[i] ? segs[i]->len : 0; + cumul += parted_seg_rows(segs, i, cnt, ncnt); seg_ends[i] = cumul; } @@ -57,8 +60,10 @@ static void parted_gather_col(ray_t* parted_col, const int64_t* match_idx, for (int64_t i = 0; i < count; i++) { int64_t row = match_idx[i]; while (seg < n_segs - 1 && row >= seg_ends[seg]) seg++; - if (!segs[seg]) - continue; /* NULL segment — zero-fill from vec_new */ + if (!segs[seg]) { + parted_fill_nulls(dst_col, i, 1); /* a missing segment's row */ + continue; + } int64_t seg_start = (seg > 0) ? seg_ends[seg - 1] : 0; int64_t local_row = row - seg_start; parted_copy_cells(dst, base, out_attrs, i, segs[seg], local_row, 1); @@ -135,9 +140,13 @@ static ray_t* exec_filter_vec(ray_t* input, ray_t* pred, int64_t pass_count) { return result; } -/* Filter a parted column by boolean predicate (sequential). */ +/* Filter a parted column by boolean predicate (sequential). `cnt`/`ncnt` + * are the table's partition counts: a NULL segment (a partition without + * the column) spans that many predicate rows, and those it passes come out + * as the type's null. */ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, - int64_t pass_count) { + int64_t pass_count, + const int64_t* cnt, int64_t ncnt) { int8_t base = (int8_t)RAY_PARTED_BASETYPE(parted_col->type); ray_t** segs = (ray_t**)ray_data(parted_col); int64_t n_segs = parted_col->len; @@ -146,7 +155,7 @@ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, /* RAY_LIST: share (retain) elements — the byte-copy path below would * alias them without a refcount and double-free on release. */ if (base == RAY_LIST) - return parted_filter_list(segs, n_segs, pred_data, pass_count); + return parted_filter_list_c(segs, n_segs, pred_data, pass_count, cnt, ncnt); /* RAY_STR: deep-copy to handle multi-pool segments */ if (base == RAY_STR) { @@ -154,7 +163,17 @@ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, if (!result || RAY_IS_ERR(result)) return result; int64_t pred_off = 0; for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s]) continue; + if (!segs[s]) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + for (int64_t i = 0; i < n; i++) { + if (!pred_data[pred_off + i]) continue; + result = ray_str_vec_append(result, "", 0); + if (RAY_IS_ERR(result)) return result; + ray_vec_set_null(result, result->len - 1, true); + } + pred_off += n; + continue; + } int64_t seg_len = segs[s]->len; const char* pool_base = segs[s]->str_pool ? (const char*)ray_data(segs[s]->str_pool) : NULL; @@ -179,7 +198,16 @@ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, int64_t pred_off = 0; for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s]) continue; + if (!segs[s]) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + for (int64_t i = 0; i < n; i++) { + if (!pred_data[pred_off + i]) continue; + parted_fill_nulls(result, out_idx, 1); + out_idx++; + } + pred_off += n; + continue; + } int64_t seg_len = segs[s]->len; char* dst = (char*)ray_data(result); bool seg_has_nulls = ray_vec_may_have_nulls(segs[s]); @@ -214,28 +242,57 @@ static ray_t* exec_filter_parted_vec(ray_t* parted_col, ray_t* pred, /* Sequential table filter fallback (small tables or alloc failure). */ static ray_t* exec_filter_seq(ray_t* input, ray_t* pred, int64_t ncols, int64_t pass_count) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(input, &ncnt); ray_t* tbl = ray_table_new(ncols); if (!tbl || RAY_IS_ERR(tbl)) return tbl; + /* Generation-2 slots gather under the predicate's selection, built + * once on the first such slot (NULL when every row passes). */ + ray_t* sel = NULL; + bool sel_built = false; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); - if (!col || RAY_IS_ERR(col)) continue; int64_t name_id = ray_table_col_name(input, c); + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(input, c)); + if (enc) { + if (!sel_built) { + if (pred->len != ray_table_nrows(input)) { + int64_t il = ray_table_nrows(input), pl = pred->len; + ray_release(tbl); + return ray_error("length", "filter: predicate length must match input, got %lld and %lld", + (long long)il, (long long)pl); + } + sel = ray_rowsel_from_pred(pred); + sel_built = true; + if (!sel && pass_count != pred->len) { ray_release(tbl); return ray_error("oom", NULL); } + } + ray_t* gc = NULL; + ray_t* ge = ray_col_gather_enc(enc, sel, false, NULL, 0, &gc); + if (ge) { if (sel) ray_rowsel_release(sel); ray_release(tbl); return ge; } + tbl = ray_table_add_col(tbl, name_id, gc); + ray_release(gc); + if (!tbl || RAY_IS_ERR(tbl)) { if (sel) ray_rowsel_release(sel); return tbl ? tbl : ray_error("oom", NULL); } + continue; + } + ray_t* col = ray_table_col_idx(input, c); + if (col && RAY_IS_ERR(col)) { if (sel) ray_rowsel_release(sel); ray_release(tbl); return col; } + if (!col) continue; if (col->type == RAY_MAPCOMMON) { ray_t* mc_filt = materialize_mapcommon_filter(col, pred, pass_count); - if (!mc_filt || RAY_IS_ERR(mc_filt)) { ray_release(tbl); return mc_filt; } + if (!mc_filt || RAY_IS_ERR(mc_filt)) { if (sel) ray_rowsel_release(sel); ray_release(tbl); return mc_filt; } tbl = ray_table_add_col(tbl, name_id, mc_filt); ray_release(mc_filt); continue; } ray_t* filtered; if (RAY_IS_PARTED(col->type)) - filtered = exec_filter_parted_vec(col, pred, pass_count); + filtered = exec_filter_parted_vec(col, pred, pass_count, cnt, ncnt); else filtered = exec_filter_vec(col, pred, pass_count); - if (!filtered || RAY_IS_ERR(filtered)) { ray_release(tbl); return filtered; } + if (!filtered || RAY_IS_ERR(filtered)) { if (sel) ray_rowsel_release(sel); ray_release(tbl); return filtered; } tbl = ray_table_add_col(tbl, name_id, filtered); ray_release(filtered); } + if (sel) ray_rowsel_release(sel); return tbl; } @@ -344,6 +401,8 @@ ray_t* ray_where_mask_coerce(ray_t* pred, int64_t tn, const char* label) { } ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(input, &ncnt); /* ragged partitions */ (void)g; (void)op; if (!input || RAY_IS_ERR(input)) return input; @@ -478,11 +537,37 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { ray_t* new_cols[ncols]; int64_t col_names[ncols]; + ray_t* src_cols[ncols]; /* borrowed: the plain columns read below */ + bool has_parted_cols = false; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); col_names[c] = ray_table_col_name(input, c); - if (!col || RAY_IS_ERR(col)) { new_cols[c] = NULL; continue; } + /* A generation-2 slot gathers at match_idx (ascending, so its + * bucketing is one pass) into its finished column; src_cols[c] + * stays NULL, so every pass below skips it. */ + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(input, c)); + if (enc) { + src_cols[c] = NULL; + ray_t* ge = ray_col_gather_enc(enc, NULL, true, match_idx, pass_count, &new_cols[c]); + if (ge) { + for (int64_t k = 0; k < c; k++) + if (new_cols[k]) ray_release(new_cols[k]); + scratch_free(idx_hdr); + ray_release(tbl); + return ge; + } + continue; + } + ray_t* col = ray_table_col_idx(input, c); + src_cols[c] = col; + if (col && RAY_IS_ERR(col)) { + for (int64_t k = 0; k < c; k++) + if (new_cols[k]) ray_release(new_cols[k]); + scratch_free(idx_hdr); + ray_release(tbl); + return col; + } + if (!col) { new_cols[c] = NULL; continue; } if (col->type == RAY_MAPCOMMON) { /* Materialize MAPCOMMON through filter predicate */ new_cols[c] = materialize_mapcommon_filter(col, pred, pass_count); @@ -521,7 +606,7 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { * here and skipped there. */ for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = src_cols[c]; if (!col) continue; if (col->type == RAY_LIST) { ray_t** d = (ray_t**)ray_data(new_cols[c]); @@ -533,9 +618,9 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { } } else if (parted_base_is_list(col)) { ray_release(new_cols[c]); - new_cols[c] = parted_gather_list_rows((ray_t**)ray_data(col), - col->len, match_idx, - pass_count); + new_cols[c] = parted_gather_list_rows_c((ray_t**)ray_data(col), + col->len, match_idx, + pass_count, cnt, ncnt); if (new_cols[c] && RAY_IS_ERR(new_cols[c])) { ray_error_free(new_cols[c]); new_cols[c] = NULL; @@ -547,7 +632,7 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { /* Parted-aware gather: use parted_gather_col for parted columns, * sequential flat gather for non-parted columns */ for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = src_cols[c]; if (!col || !new_cols[c]) continue; if (col->type == RAY_MAPCOMMON) continue; /* already materialized */ if (col->type == RAY_LIST || parted_base_is_list(col)) @@ -557,10 +642,12 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { if (pbase == RAY_STR) { ray_t** psegs = (ray_t**)ray_data(col); ray_release(new_cols[c]); - new_cols[c] = parted_gather_str_rows(psegs, col->len, - match_idx, pass_count); + new_cols[c] = parted_gather_str_rows_c(psegs, col->len, + match_idx, pass_count, + cnt, ncnt); } else { - parted_gather_col(col, match_idx, pass_count, new_cols[c]); + parted_gather_col(col, match_idx, pass_count, new_cols[c], + cnt, ncnt); } } else { uint8_t esz = col_esz(col); @@ -575,7 +662,8 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { multi_gather_ctx_t mgctx = { .idx = match_idx, .ncols = 0 }; for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = src_cols[c]; + if (!col) continue; /* generation 2: gathered above */ if (col && col->type == RAY_MAPCOMMON) continue; /* already materialized */ if (col && col->type == RAY_LIST) continue; /* gathered above with retain */ int64_t ci = mgctx.ncols; @@ -593,7 +681,7 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { } else { /* Sequential gather with index */ for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = src_cols[c]; if (!col || !new_cols[c]) continue; if (col->type == RAY_LIST) continue; /* gathered above with retain */ uint8_t esz = col_esz(col); @@ -612,7 +700,7 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { * singleton). */ for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(input, c); + ray_t* col = src_cols[c]; if (!col) continue; if (col->type == RAY_LIST || parted_base_is_list(col)) continue; /* elements gathered+retained; no str-pool to touch */ @@ -624,6 +712,12 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { } } else { col_propagate_str_pool(new_cols[c], col); + /* the flat gathers above copy values only (parted columns carry + * their null bits in parted_gather_col / _str_rows); SYM and STR + * nulls travel in the copied cell, so only a HAS_NULLS column of + * another type takes the pass (#784) */ + if (col->type != RAY_SYM && col->type != RAY_STR && ray_vec_may_have_nulls(col)) + col_propagate_nulls_gather(new_cols[c], col, match_idx, pass_count); } if (new_cols[c]->type == RAY_SYM) ray_sym_vec_adopt_domain(new_cols[c], sym_domain_rep(col)); @@ -648,6 +742,8 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { * number of matches far exceeds the limit. * ============================================================================ */ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(input, &ncnt); /* ragged partitions */ if (!input || RAY_IS_ERR(input)) return input; if (!pred || RAY_IS_ERR(pred)) return pred; /* Over a table the predicate goes through the one where: rule @@ -717,8 +813,20 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { if (!tbl || RAY_IS_ERR(tbl)) { scratch_free(idx_hdr); return tbl; } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(input, c); int64_t name_id = ray_table_col_name(input, c); + /* a generation-2 slot: the head's rows, gathered by range */ + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(input, c)); + if (enc) { + ray_t* gc = NULL; + ray_t* ge = ray_col_gather_enc(enc, NULL, true, match_idx, found, &gc); + if (ge) { scratch_free(idx_hdr); ray_release(tbl); return ge; } + tbl = ray_table_add_col(tbl, name_id, gc); + ray_release(gc); + if (!tbl || RAY_IS_ERR(tbl)) { scratch_free(idx_hdr); return tbl ? tbl : ray_error("oom", NULL); } + continue; + } + ray_t* col = ray_table_col_idx(input, c); + if (col && RAY_IS_ERR(col)) { scratch_free(idx_hdr); ray_release(tbl); return col; } if (!col) continue; if (col->type == RAY_MAPCOMMON) { ray_t* mc = materialize_mapcommon_gather(col, match_idx, found); @@ -748,8 +856,8 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { if (out_type == RAY_LIST) { ray_t* lcol; if (RAY_IS_PARTED(col->type)) { - lcol = parted_gather_list_rows((ray_t**)ray_data(col), - col->len, match_idx, found); + lcol = parted_gather_list_rows_c((ray_t**)ray_data(col), + col->len, match_idx, found, cnt, ncnt); } else { lcol = ray_list_new(found); if (lcol && !RAY_IS_ERR(lcol)) { @@ -782,30 +890,23 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { if (out_type == RAY_STR) { /* Deep-copy STR to handle multi-pool segments */ ray_release(new_col); - new_col = parted_gather_str_rows(segs, n_segs, match_idx, found); + new_col = parted_gather_str_rows_c(segs, n_segs, match_idx, found, + cnt, ncnt); } else { - /* Non-STR parted gather */ - int64_t seg_start = 0; - int64_t cur_seg = 0; - int64_t cur_seg_end = (n_segs > 0 && segs[0]) ? segs[0]->len : 0; - for (int64_t j = 0; j < found; j++) { - int64_t r = match_idx[j]; - while (cur_seg < n_segs - 1 && r >= cur_seg_end) { - seg_start = cur_seg_end; - cur_seg++; - cur_seg_end += segs[cur_seg] ? segs[cur_seg]->len : 0; - } - if (!segs[cur_seg]) - continue; /* NULL segment — zero-fill from memset */ - parted_copy_cells(dst, out_type, out_attrs, j, - segs[cur_seg], r - seg_start, 1); - } + /* Non-STR parted gather: the shared helper spans a NULL + * segment over its partition's rows and carries each + * present segment's null cells over. */ + parted_gather_col(col, match_idx, found, new_col, cnt, ncnt); } } else { char* src = (char*)ray_data(col); for (int64_t j = 0; j < found; j++) memcpy(dst + j * esz, src + match_idx[j] * esz, esz); col_propagate_str_pool(new_col, col); + /* a null bitmap only where HAS_NULLS says so; SYM and STR + * nulls travel in the copied cell (#784) */ + if (col->type != RAY_SYM && col->type != RAY_STR && ray_vec_may_have_nulls(col)) + col_propagate_nulls_gather(new_col, col, match_idx, found); } /* SYM gather copied cell ids verbatim — resolve over the source * column's domain (flat → col itself; parted → first SYM seg). */ @@ -877,6 +978,11 @@ static inline bool sel_compact_keep(int64_t nm, const int64_t* keep_syms, int ke ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, const int64_t* keep_syms, int keep_n) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); /* ragged partitions */ + /* A projection of parted columns carries no partition-key column: the + * counts come from the graph's source table, whose partitions it shares. */ + if (!cnt && g && g->table) cnt = parted_table_counts(g->table, &ncnt); (void)g; if (!tbl || RAY_IS_ERR(tbl) || !sel) return tbl; @@ -884,7 +990,21 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, * keep_syms (order preserved); NULL/0 => materialize all columns. */ bool use_keep = (keep_syms != NULL && keep_n > 0); + /* The table's rows: through the partition counts when its first column + * is a parted column with missing segments (ragged parted table). */ int64_t nrows = ray_table_nrows(tbl); + { + ray_col_meta_t fm; /* metadata first: an encoded column stays encoded */ + bool parted = ray_table_ncols(tbl) > 0 && ray_table_col_meta_idx(tbl, 0, &fm) && + RAY_IS_PARTED(fm.type); + /* an encoded parted column has every segment (lazy all-null ones + * for a ragged partition): its rows are its length */ + if (parted && fm.enc) { parted = false; nrows = fm.len; } + ray_t* first = parted ? ray_table_col_idx(tbl, 0) : NULL; + if (first && RAY_IS_ERR(first)) return first; + if (first && RAY_IS_PARTED(first->type)) + nrows = parted_rows_counted(first, cnt, ncnt); + } ray_rowsel_t* meta = ray_rowsel_meta(sel); /* Defensive: the selection must have been built for a table @@ -913,17 +1033,19 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, if (use_keep && !sel_compact_keep(ray_table_col_name(tbl, c), keep_syms, keep_n)) continue; - ray_t* col = ray_table_get_col_idx(tbl, c); - if (!col) continue; - if (col->type == RAY_MAPCOMMON) { + ray_col_meta_t cm; + if (!ray_table_col_meta_idx(tbl, c, &cm)) continue; + if (cm.type == RAY_MAPCOMMON) { + ray_t* col = ray_table_col_idx(tbl, c); + if (!col || RAY_IS_ERR(col)) { ray_release(empty); return col; } ray_t* mc = materialize_mapcommon_head(col, 0); if (!mc || RAY_IS_ERR(mc)) { ray_release(empty); return mc; } empty = ray_table_add_col(empty, ray_table_col_name(tbl, c), mc); ray_release(mc); continue; } - int8_t ct = RAY_IS_PARTED(col->type) - ? (int8_t)RAY_PARTED_BASETYPE(col->type) : col->type; + int8_t ct = RAY_IS_PARTED(cm.type) + ? (int8_t)RAY_PARTED_BASETYPE(cm.type) : cm.type; /* RAY_LIST == 0; ray_vec_new rejects type <= 0, so a LIST * column needs ray_list_new — otherwise the empty result * silently drops it and the 0-row schema loses a column. */ @@ -1015,16 +1137,42 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, if (ncols > 256) { scratch_free(idx_hdr); return ray_error("limit", "table exceeds 256 columns"); } ray_t* new_cols[ncols]; + ray_t* src_cols[ncols]; /* borrowed: the plain kept columns */ int64_t col_names[ncols]; bool has_parted = false; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); col_names[c] = ray_table_col_name(tbl, c); + src_cols[c] = NULL; if (use_keep && !sel_compact_keep(col_names[c], keep_syms, keep_n)) { new_cols[c] = NULL; continue; } - if (!col || RAY_IS_ERR(col)) { new_cols[c] = NULL; continue; } + /* A generation-2 slot (single file or parted) gathers under the + * selection into its finished column; src_cols[c] stays NULL, so + * the batch gather, the LIST and parted passes and the fix-ups + * below skip it. */ + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(tbl, c)); + if (enc) { + ray_t* ge = ray_col_gather_enc(enc, sel, false, NULL, 0, &new_cols[c]); + if (ge) { + for (int64_t k = 0; k < c; k++) + if (new_cols[k]) ray_release(new_cols[k]); + scratch_free(idx_hdr); + ray_release(out); + return ge; + } + continue; + } + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) { + for (int64_t k = 0; k < c; k++) + if (new_cols[k]) ray_release(new_cols[k]); + scratch_free(idx_hdr); + ray_release(out); + return col; + } + if (!col) { new_cols[c] = NULL; continue; } + src_cols[c] = col; if (col->type == RAY_MAPCOMMON) { ray_t** mc_ptrs = (ray_t**)ray_data(col); ray_t* kv = mc_ptrs[0]; @@ -1083,13 +1231,13 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, * #355). */ for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = src_cols[c]; if (!col) continue; if (parted_base_is_list(col)) { ray_release(new_cols[c]); - new_cols[c] = parted_gather_list_rows((ray_t**)ray_data(col), + new_cols[c] = parted_gather_list_rows_c((ray_t**)ray_data(col), col->len, match_idx, - pass_count); + pass_count, cnt, ncnt); if (new_cols[c] && RAY_IS_ERR(new_cols[c])) { ray_error_free(new_cols[c]); new_cols[c] = NULL; @@ -1108,7 +1256,7 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, if (has_parted) { for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = src_cols[c]; if (!col || !new_cols[c]) continue; if (col->type == RAY_LIST || parted_base_is_list(col)) continue; /* gathered above with retain */ @@ -1117,10 +1265,12 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, if (pbase == RAY_STR) { ray_t** psegs = (ray_t**)ray_data(col); ray_release(new_cols[c]); - new_cols[c] = parted_gather_str_rows(psegs, col->len, - match_idx, pass_count); + new_cols[c] = parted_gather_str_rows_c(psegs, col->len, + match_idx, pass_count, + cnt, ncnt); } else { - parted_gather_col(col, match_idx, pass_count, new_cols[c]); + parted_gather_col(col, match_idx, pass_count, new_cols[c], + cnt, ncnt); } } else { uint8_t esz = col_esz(col); @@ -1137,7 +1287,8 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, multi_gather_ctx_t mgctx = { .idx = match_idx, .ncols = 0 }; for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = src_cols[c]; + if (!col) continue; /* generation 2: gathered above */ if (col->type == RAY_LIST) continue; /* gathered above with retain */ /* RAY_MAPCOMMON is not skipped here: the pre-alloc loop above already * materialized it to a flat new_cols[c], so col_esz returns 0 and the @@ -1157,7 +1308,7 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, ray_pool_dispatch(pool, multi_gather_fn, &mgctx, pass_count); } else { for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = src_cols[c]; if (!col || !new_cols[c]) continue; if (col->type == RAY_LIST) continue; /* gathered above with retain */ uint8_t esz = col_esz(col); @@ -1170,7 +1321,7 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* scol = ray_table_get_col_idx(tbl, c); + ray_t* scol = src_cols[c]; if (scol && (scol->type == RAY_LIST || parted_base_is_list(scol))) { /* LIST elements already gathered+retained; no str-pool / null * bitmap to propagate. */ @@ -1188,7 +1339,7 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, /* SYM gathers above copied cell ids verbatim — resolve over the * source column's domain (flat → scol; parted → first SYM seg; * MAPCOMMON → keys vec, all via sym_domain_rep). */ - if (new_cols[c]->type == RAY_SYM) + if (scol && new_cols[c]->type == RAY_SYM) /* a gathered slot (scol NULL) holds its domain */ ray_sym_vec_adopt_domain(new_cols[c], sym_domain_rep(scol)); out = ray_table_add_col(out, col_names[c], new_cols[c]); ray_release(new_cols[c]); diff --git a/src/ops/fused_pred.c b/src/ops/fused_pred.c index 94d30219d..b94e7a847 100644 --- a/src/ops/fused_pred.c +++ b/src/ops/fused_pred.c @@ -34,16 +34,26 @@ * fused_group.h (ray_fused_group_supported). */ +#include "ops/colbind.h" #include "vec/vec.h" #include "ops/fused_group.h" /* ray_fused_group_supported decl */ #include "ops/fused_pred.h" #include "table/domain.h" /* sym-domain resolution */ +#include "table/table.h" /* ray_table_col_meta */ #include "ops/idxop.h" /* RAY_IDX_CHUNK_ZONE chunk-skip in fp_eval_cmp */ #include "lang/eval.h" /* ATTR_QUOTED */ +#include "store/enc.h" /* RAY_ENC_VEC: the range-read vector */ +#include "store/enccol.h" /* ray_enc_chunk_stat_t: the directory gate */ +#include "store/enceval.h" /* encoded leaves: ray_enc_eval_cmp */ +#include "vec/str.h" /* ray_str_t_ptr: STR through a view */ +#include #include #include +/* FP_EQ..FP_GE are 0..5 and OP_EQ..OP_GE 25..30 in the same order. */ +static inline uint16_t cmp_op_of(fp_op_t op) { return (uint16_t)(OP_EQ + (int)(op - FP_EQ)); } + /* Recognise a 2-character comparison operator: ==, !=, <=, >=. Returns * the FP_* code or -1 on miss. */ static int fp_op_from_2char(const char* op, size_t len) { @@ -103,21 +113,16 @@ static int fp_atom_col_compatible(int8_t atom_type, int8_t col_type) { } } -/* Numeric, temporal, STR and GUID comparisons have an explicit typed leg - * with null-as-minimum ordering. SYM equality uses domain codes. IN keeps - * its stricter null-free admission because it uses a different evaluator. */ -static int fp_col_supported_op(const ray_t* col, int eq_or_ne) { - if (!col) return 0; - if (col->type >= RAY_BOOL && col->type <= RAY_TIMESTAMP) return 1; - if (col->type == RAY_GUID || col->type == RAY_STR) return 1; - if (eq_or_ne && col->type == RAY_SYM) return 1; - return !ray_vec_has_nulls(col); -} - -/* Strict form — no nullable column at all. Used by the shape whose - * evaluator arm is not an equality compare (IN). */ -static int fp_col_supported(const ray_t* col) { - return col && !ray_vec_has_nulls(col); +/* Planning-time admission by metadata (the bound-source forms are + * fp_src_supported_op / fp_src_supported below): numeric, temporal, STR and + * GUID comparisons have an explicit typed leg with null-as-minimum + * ordering, SYM equality uses domain codes, anything else needs a null-free + * column from ray_table_col_has_nulls, never a decode. */ +static int fp_meta_supported_op(ray_t* tbl, int64_t sym, const ray_col_meta_t* m, int eq_or_ne) { + if (m->type >= RAY_BOOL && m->type <= RAY_TIMESTAMP) return 1; + if (m->type == RAY_GUID || m->type == RAY_STR) return 1; + if (eq_or_ne && m->type == RAY_SYM) return 1; + return !ray_table_col_has_nulls(tbl, sym); } static int fp_expr_const_str(ray_t* expr) { @@ -167,10 +172,10 @@ static int fp_check_simple_cmp(ray_t* expr, ray_t* tbl) { * compile agree — divergence here means the executor returns * `nyi` on shapes the planner thought were ok. */ if (tbl) { - ray_t* col = ray_table_get_col(tbl, lhs->i64); - if (!col) return -1; - if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return -1; - int8_t ct = col->type; + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, lhs->i64, &m)) return -1; + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON) return -1; + int8_t ct = m.type; int is_ord = (code >= 2); /* LT/LE/GT/GE */ if (is_ord && ct == RAY_SYM) return -1; /* Dict-encoded STR: EQ/NE only, compared on the int32 code vector @@ -179,7 +184,7 @@ static int fp_check_simple_cmp(ray_t* expr, ray_t* tbl) { * are meaningless on first-occurrence codes, so reject them. */ int is_dict_str = (ct == RAY_STR && !is_ord && rhs->type == -RAY_STR - && ray_index_kind(col) == RAY_IDX_DICT); + && m.index_kind == RAY_IDX_DICT); /* Only types with a matching typed comparison implementation. */ if (!is_dict_str && ct != RAY_SYM && ct != RAY_BOOL && ct != RAY_U8 @@ -187,7 +192,7 @@ static int fp_check_simple_cmp(ray_t* expr, ray_t* tbl) { && ct != RAY_DATE && ct != RAY_TIME && ct != RAY_TIMESTAMP && ct != RAY_F32 && ct != RAY_F64 && ct != RAY_STR && ct != RAY_GUID) return -1; - if (!fp_col_supported_op(col, code == 0 || code == 1)) return -1; + if (!fp_meta_supported_op(tbl, lhs->i64, &m, code == 0 || code == 1)) return -1; if (!is_dict_str && !fp_atom_col_compatible(rhs->type, ct)) return -1; } return code; @@ -207,12 +212,12 @@ static int fp_check_like(ray_t* expr, ray_t* tbl) { return 0; if (!fp_expr_const_str(elems[2])) return 0; if (tbl) { - ray_t* col = ray_table_get_col(tbl, lhs->i64); + ray_col_meta_t m; /* A null text cell is the empty string on every like path (the * kernel and this evaluator both match the pattern against ""), * so a nullable column is admitted. */ - if (!col) return 0; - if (col->type != RAY_STR && col->type != RAY_SYM) return 0; + if (!ray_table_col_meta(tbl, lhs->i64, &m)) return 0; + if (m.type != RAY_STR && m.type != RAY_SYM) return 0; } return 1; } @@ -241,10 +246,10 @@ static int fp_check_in(ray_t* expr, ray_t* tbl) { if (ray_len(rhs) > 16) return 0; if (!fp_int_family(rhs->type)) return 0; if (tbl) { - ray_t* col = ray_table_get_col(tbl, lhs->i64); - if (!col || !fp_col_supported(col)) return 0; - if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return 0; - if (!fp_int_family(col->type)) return 0; + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, lhs->i64, &m) || ray_table_col_has_nulls(tbl, lhs->i64)) return 0; + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON) return 0; + if (!fp_int_family(m.type)) return 0; } return 1; } @@ -254,7 +259,41 @@ static int fp_check_in(ray_t* expr, ray_t* tbl) { * pred = simple_cmp | (and simple_cmp simple_cmp …) * simple_cmp = (op col const) where op ∈ {==, !=, <, <=, >, >=} * ordering ops require col to be a numeric/temporal (non-SYM) column. - * AND fan-in is bounded by FP_PRED_MAX_CHILDREN (defined in fused_pred.h). */ + * AND fan-in is bounded by FP_PRED_MAX_CHILDREN (defined in fused_pred.h). + * + * A nested `and` is the flat `and` of its leaves: fp_compile_pred_dag + * walks nested OP_AND nodes into one child list, so (and (and a b) c) runs + * as (and a b c). The leaf cap counts across the nesting. */ + +static int fp_is_and(ray_t* expr) { + if (!expr || expr->type != RAY_LIST || ray_len(expr) < 2) return 0; + ray_t** elems = (ray_t**)ray_data(expr); + if (!elems[0] || elems[0]->type != -RAY_SYM) return 0; + ray_t* head_sym = ray_sym_str(elems[0]->i64); + return head_sym && ray_str_len(head_sym) == 3 && + memcmp(ray_str_ptr(head_sym), "and", 3) == 0; +} + +/* Add the leaves of `(and …)` to *n_leaves; 0 once a leaf is not a fused + * comparison or the leaves pass the cap. Every level holds a leaf or an + * `and`, so FP_PRED_MAX_CHILDREN also bounds the depth. */ +static int fp_and_leaves_supported(ray_t* expr, ray_t* tbl, int* n_leaves, int depth) { + if (depth > FP_PRED_MAX_CHILDREN) return 0; + int64_t n = ray_len(expr); + ray_t** elems = (ray_t**)ray_data(expr); + for (int64_t i = 1; i < n; i++) { + ray_t* leaf = elems[i]; + if (fp_is_and(leaf)) { + if (!fp_and_leaves_supported(leaf, tbl, n_leaves, depth + 1)) return 0; + continue; + } + if (++*n_leaves > FP_PRED_MAX_CHILDREN) return 0; + if (fp_check_simple_cmp(leaf, tbl) < 0 + && !fp_check_like(leaf, tbl) + && !fp_check_in(leaf, tbl)) return 0; + } + return 1; +} int ray_fused_group_supported(ray_t* expr, ray_t* tbl) { if (!expr || expr->type != RAY_LIST) return 0; @@ -263,21 +302,9 @@ int ray_fused_group_supported(ray_t* expr, ray_t* tbl) { ray_t** elems = (ray_t**)ray_data(expr); if (!elems[0] || elems[0]->type != -RAY_SYM) return 0; - /* Detect (and …). */ - ray_t* head_sym = ray_sym_str(elems[0]->i64); - if (head_sym) { - size_t hlen = ray_str_len(head_sym); - const char* hstr = ray_str_ptr(head_sym); - if (hlen == 3 && memcmp(hstr, "and", 3) == 0) { - int64_t k = n - 1; - if (k < 1 || k > FP_PRED_MAX_CHILDREN) return 0; - for (int64_t i = 0; i < k; i++) { - if (fp_check_simple_cmp(elems[i + 1], tbl) < 0 - && !fp_check_like(elems[i + 1], tbl) - && !fp_check_in(elems[i + 1], tbl)) return 0; - } - return 1; - } + if (fp_is_and(expr)) { + int n_leaves = 0; + return fp_and_leaves_supported(expr, tbl, &n_leaves, 0); } /* Fall through: single simple cmp. */ return (fp_check_simple_cmp(expr, tbl) >= 0 || @@ -319,12 +346,20 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, if (p->typed_compare) { for (int64_t r = start; r < end; r++) { - bool an = ray_vec_is_null(p->col_obj, r), bn = p->constant_null; + bool an = p->col_obj ? ray_vec_is_null(p->col_obj, r) + : ray_raw_is_null(ct, p->col_attrs, p->col_base, r); + bool bn = p->constant_null; int cmp; if (an || bn) cmp = an == bn ? 0 : an ? -1 : 1; else if (ct == RAY_STR) { size_t len = 0, clen = ray_str_len(p->literal); - const char* str = ray_str_vec_get(p->col_obj, r, &len); + const char* str; + if (p->col_obj) str = ray_str_vec_get(p->col_obj, r, &len); + else { + const ray_str_t* sd = &((const ray_str_t*)p->col_base)[r]; + len = sd->len; + str = len ? ray_str_t_ptr(sd, p->col_pool) : ""; + } size_t common = len < clen ? len : clen; cmp = common ? memcmp(str, ray_str_ptr(p->literal), common) : 0; if (!cmp) cmp = (len > clen) - (len < clen); @@ -388,34 +423,8 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, if (cmin <= cmax) { /* skip empty (all-null) chunks */ const uint8_t* nb = (const uint8_t*)ray_data(ix->u.chunk_zone.null_bits); bool has_nulls = (nb[s_ch >> 3] >> (s_ch & 7)) & 1u; - int decision = -1; /* 0=all-fail, 1=all-pass, -1=mixed */ - switch (op) { - case FP_EQ: - if (cval < cmin || cval > cmax) decision = 0; - else if (!has_nulls && cmin == cmax) decision = 1; - break; - case FP_NE: - if (!has_nulls && (cval < cmin || cval > cmax)) decision = 1; - else if (!has_nulls && cmin == cmax && cval == cmin) decision = 0; - break; - case FP_LT: - if (!has_nulls && cmin >= cval) decision = 0; - else if (!has_nulls && cmax < cval) decision = 1; - break; - case FP_LE: - if (!has_nulls && cmin > cval) decision = 0; - else if (!has_nulls && cmax <= cval) decision = 1; - break; - case FP_GT: - if (cmax <= cval) decision = 0; - else if (!has_nulls && cmin > cval) decision = 1; - break; - case FP_GE: - if (cmax < cval) decision = 0; - else if (!has_nulls && cmin >= cval) decision = 1; - break; - default: break; - } + /* 0=all-fail, 1=all-pass, -1=mixed */ + int decision = zone_cmp_core(cmin, cmax, true, has_nulls, false, cmp_op_of(op), cval); if (decision >= 0) { memset(bits, (uint8_t)decision, (size_t)n); return; @@ -443,7 +452,7 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, * positions through the column's domain (sym-domain Phase 2). * The LUT is sized by that domain's count at compile. */ struct ray_sym_domain_s* like_dom = - sym_strings ? NULL : ray_sym_vec_domain(p->col_obj); + sym_strings ? NULL : p->like_dom ? p->like_dom : ray_sym_vec_domain(p->col_obj); int use_simple = p->pat_compiled.shape != RAY_GLOB_SHAPE_NONE; for (int64_t r = 0; r < n; r++) { uint64_t sid = (uint64_t)read_by_esz(base, start + r, esz_l); @@ -485,7 +494,13 @@ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, int use_simple = p->pat_compiled.shape != RAY_GLOB_SHAPE_NONE; for (int64_t r = 0; r < n; r++) { size_t sl = 0; - const char* sp = ray_str_vec_get(p->col_obj, start + r, &sl); + const char* sp; + if (p->col_obj) sp = ray_str_vec_get(p->col_obj, start + r, &sl); + else { + const ray_str_t* sd = &((const ray_str_t*)p->col_base)[start + r]; + sl = sd->len; + sp = sl ? ray_str_t_ptr(sd, p->col_pool) : ""; + } if (!sp) sp = ""; bits[r] = use_simple ? (uint8_t)ray_glob_match_compiled(&p->pat_compiled, sp, sl) @@ -625,7 +640,8 @@ static inline uint8_t fp_eval_cmp_one(const fp_cmp_t* p, int64_t row) { } else { ray_t* s = p->like_sym_strings ? p->like_sym_strings[sid] - : ray_sym_domain_str(ray_sym_vec_domain(p->col_obj), (int64_t)sid); + : ray_sym_domain_str(p->like_dom ? p->like_dom : ray_sym_vec_domain(p->col_obj), + (int64_t)sid); if (s) { sp = ray_str_ptr(s); sl = ray_str_len(s); } } uint8_t match = 0; @@ -641,7 +657,13 @@ static inline uint8_t fp_eval_cmp_one(const fp_cmp_t* p, int64_t row) { } if (p->col_type == RAY_STR) { size_t sl = 0; - const char* sp = ray_str_vec_get(p->col_obj, row, &sl); + const char* sp; + if (p->col_obj) sp = ray_str_vec_get(p->col_obj, row, &sl); + else { + const ray_str_t* sd = &((const ray_str_t*)p->col_base)[row]; + sl = sd->len; + sp = sl ? ray_str_t_ptr(sd, p->col_pool) : ""; + } if (!sp) sp = ""; return (p->pat_compiled.shape != RAY_GLOB_SHAPE_NONE) ? (uint8_t)ray_glob_match_compiled(&p->pat_compiled, sp, sl) @@ -695,6 +717,7 @@ void fp_eval_pred(const fp_pred_t* p, int64_t start, int64_t end, uint8_t* bits) { int64_t n = end - start; + for (uint8_t i = 0; i < p->n_children; i++) assert(!p->children[i].enc); if (p->n_children == 0) { memset(bits, 1, (size_t)n); return; @@ -716,32 +739,219 @@ void fp_eval_pred(const fp_pred_t* p, int64_t start, int64_t end, } } -/* Resolve a constant string to its dict code in a RAY_IDX_DICT column. - * Codes are assigned by first-occurrence (not sorted), so there is no - * persisted string->code map; scan the n_distinct first-occurrence rows - * and compare the string at each. One-time per-query compile cost. - * Returns the code, or -1 when the string is absent from the dict. */ -static int64_t fp_dict_str_code(ray_t* col, const ray_index_t* dix, - const char* s, size_t slen) { - int64_t nd = dix->u.dict.n_distinct; - if (nd <= 0 || !dix->u.dict.first_occ || RAY_IS_ERR(dix->u.dict.first_occ)) - return -1; - const int32_t* focc = (const int32_t*)ray_data(dix->u.dict.first_occ); - for (int64_t c = 0; c < nd; c++) { - size_t l = 0; - const char* p = ray_str_vec_get(col, focc[c], &l); - if (!p) continue; - if (l == slen && (slen == 0 || memcmp(p, s, slen) == 0)) - return c; +void fp_scratch_init(fp_scratch_t* s) { + for (int i = 0; i < FP_PRED_MAX_CHILDREN; i++) ray_col_scratch_init(&s->sc[i]); +} +void fp_scratch_free(fp_scratch_t* s) { + for (int i = 0; i < FP_PRED_MAX_CHILDREN; i++) ray_col_scratch_free(&s->sc[i]); +} + +/* An encoded child whose answer needs no column read: a fold, or a SYM + * constant absent from the domain (fp_eval_cmp memsets both). */ +static bool fp_reads_nothing(const fp_cmp_t* c) { + return c->fold || (c->col_type == RAY_SYM && !c->cval_in_dict); +} + +/* A child answered on its vector's view (store/enceval.h): a plain + * integer / temporal compare, or SYM equality with a constant of the + * domain. A non-typed child has no nulls (fp_src_supported_op), and SYM + * nulls are in band, so no null mask is applied. */ +static bool fp_view_leaf(const fp_cmp_t* c) { + if (c->typed_compare || c->fold != FP_FOLD_NONE || c->op > FP_GE) return false; + if (c->col_type == RAY_SYM) return (c->op == FP_EQ || c->op == FP_NE) && c->cval_in_dict; + return zone_dir_type(c->col_type); +} + +/* Rebind an encoded child to the view of [start, start + n) (one vector), + * shifted so that row `start` is index 0: rows are passed as [0, n). The + * directory gate decides a whole range from its chunk's statistics first, + * then from its vector's descriptor (*decided 0 / 1, nothing read); a + * materialization another consumer + * published meanwhile is read in place, never decoded again. Otherwise a + * leaf (fp_view_leaf) is evaluated on the vector's view into dst[0, n) + * (*decided 2, nothing decoded); a vector without a view is read by + * range. */ +static ray_t* fp_bind_view(const fp_cmp_t* c, int64_t start, int64_t n, + ray_col_scratch_t* sc, ray_enc_vview_t* vb, uint8_t* dst, + fp_cmp_t* out, int* decided) { + *out = *c; + *decided = -1; + if (c->idict) { + /* the persisted DICT's codes (P6b), in the mapping: no decode, and + * never a zone decision (codes are membership values, D6) */ + const int32_t* cd = NULL; + ray_t* e = ray_enccol_idict_codes(c->idict, start, n, &cd); + if (e) return e; + out->col_base = cd; /* rows are view-relative, as for a range read */ + out->col_obj = NULL; + return NULL; } - return -1; + if (!c->typed_compare && zone_dir_type(c->col_type) && c->op <= FP_GE && + (start / RAY_ENC_CHUNK) == ((start + n - 1) / RAY_ENC_CHUNK)) { + ray_enc_chunk_stat_t st; + if (ray_col_src_chunk_stat(c->src, start / RAY_ENC_CHUNK, &st)) { + int d = zone_cmp_core(st.min, st.max, st.has_minmax, st.null_count > 0, + (int64_t)st.null_count == st.rows, cmp_op_of(c->op), c->cval); + if (d >= 0) { *decided = d; return NULL; } + } + /* then the vector's descriptor (the window lies in one vector); + * answer-only, the window is filled, so no consumer guard */ + int64_t mn, mx; uint32_t nn; + if (start / RAY_ENC_VEC == (start + n - 1) / RAY_ENC_VEC && + ray_col_src_vec_stat(c->src, start / RAY_ENC_VEC, &mn, &mx, &nn)) { + int d = zone_cmp_core(mn, mx, true, nn > 0, false, cmp_op_of(c->op), c->cval); + if (d >= 0) { *decided = d; return NULL; } + } + } + ray_t* rd = ray_col_src_ready(c->src); + if (rd && !RAY_IS_PARTED(rd->type)) { + ray_t* own = (rd->attrs & RAY_ATTR_SLICE) ? rd->slice_parent : rd; + out->col_attrs = rd->attrs; + out->col_esz = ray_sym_elem_size(rd->type, rd->attrs); + out->col_base = (const char*)ray_data(rd) + (size_t)start * out->col_esz; + out->col_pool = (rd->type == RAY_STR && own->str_pool && !RAY_IS_ERR(own->str_pool)) + ? (const char*)ray_data(own->str_pool) : NULL; + out->col_obj = NULL; /* rows are view-relative */ + return NULL; + } + if (!rd && fp_view_leaf(c)) { + ray_t* verr = NULL; + int vr = ray_col_src_vview(c->src, start / RAY_ENC_VEC, vb, &verr); + if (vr < 0) return verr; + int64_t off = start % RAY_ENC_VEC; + /* a bitmap with nulls cannot occur here (a non-typed child is + * null-free); were it present, the range read answers exactly */ + if (vr > 0 && !vb->nullmap && off + n <= vb->n) { + uint8_t whole[RAY_ENC_VEC]; /* a window inside the vector */ + uint8_t* o = off == 0 && n == vb->n ? dst : whole; + if (ray_enc_eval_cmp(vb, cmp_op_of(c->op), c->cval, 0, o)) { + if (o != dst) memcpy(dst, whole + off, (size_t)n); + *decided = 2; + return NULL; + } + } + } + ray_col_range_t v; + ray_t* e = ray_col_range(c->src, start, n, sc, &v); + if (e) return e; + if (v.n != n) return ray_error("range", "fused predicate: morsel crosses a vector boundary"); + out->col_base = v.data; + out->col_pool = v.str_pool; + out->col_obj = NULL; + out->col_attrs = v.attrs; + out->col_esz = ray_sym_elem_size(v.type, v.attrs); + return NULL; +} + +ray_t* fp_eval_pred_rs(const fp_pred_t* p, int64_t start, int64_t end, + uint8_t* bits, fp_scratch_t* s) { + int64_t n = end - start; + assert(n <= RAY_MORSEL_ELEMS); + bool any_enc = false; + for (uint8_t i = 0; i < p->n_children; i++) any_enc |= p->children[i].enc; + if (!any_enc) { fp_eval_pred(p, start, end, bits); return NULL; } + /* encoded children read one vector per call: split at vector boundaries */ + int64_t cut = ((start / RAY_ENC_VEC) + 1) * RAY_ENC_VEC; + if (cut < end) { + ray_t* e = fp_eval_pred_rs(p, start, cut, bits, s); + return e ? e : fp_eval_pred_rs(p, cut, end, bits + (cut - start), s); + } + /* Children AND into bits; once no row of the window passes, the rest + * would only AND zeros, so they are not evaluated (nor their vectors + * decoded). */ + uint8_t tmp[RAY_MORSEL_ELEMS]; + for (uint8_t i = 0; i < p->n_children; i++) { + const fp_cmp_t* c = &p->children[i]; + uint8_t* dst = i == 0 ? bits : tmp; + if (c->enc && !fp_reads_nothing(c)) { + fp_cmp_t local; int decided; + ray_t* e = fp_bind_view(c, start, n, &s->sc[i], &s->vb, dst, &local, &decided); + if (e) return e; + if (decided == 0 || decided == 1) memset(dst, decided, (size_t)n); + else if (decided < 0) fp_eval_cmp(&local, 0, n, dst); /* 2: written on the view */ + } else if (c->enc) { + fp_eval_cmp(c, 0, n, dst); /* reads no column */ + } else { + fp_eval_cmp(c, start, end, dst); + } + uint8_t any = 0; + if (i == 0) for (int64_t r = 0; r < n; r++) any |= bits[r]; + else for (int64_t r = 0; r < n; r++) { + /* Each non-error branch writes n bytes through dst == tmp: + * memset, fp_eval_cmp, or fp_bind_view's decided==2 view. */ + // cppcheck-suppress legacyUninitvar + bits[r] &= tmp[r]; + any |= bits[r]; + } + if (!any) break; /* the window is decided: all fail */ + } + return NULL; +} + +/* Nullability of a bound source. Generation 0 keeps the exact payload + * test; an encoded source answers from its directory null counts (exact), + * never a decode. */ +static int fp_src_has_nulls(const ray_col_src_t* s) { + if (s->obj->type != RAY_ENCCOL && ray_is_vec(s->obj)) return ray_vec_has_nulls(s->obj); + return s->may_null; +} + +/* Numeric, temporal, STR and GUID comparisons have an explicit typed leg + * with null-as-minimum ordering. SYM equality uses domain codes. Any other + * form needs a null-free source; IN keeps that stricter admission + * (fp_src_supported) because it uses a different evaluator. */ +static int fp_src_supported_op(const ray_col_src_t* s, int eq_or_ne) { + if (s->type >= RAY_BOOL && s->type <= RAY_TIMESTAMP) return 1; + if (s->type == RAY_GUID || s->type == RAY_STR) return 1; + if (eq_or_ne && s->type == RAY_SYM) return 1; + return !fp_src_has_nulls(s); +} + +static int fp_src_supported(const ray_col_src_t* s) { + return !fp_src_has_nulls(s); +} + +/* The step that captures a payload pointer asks for the plain column. Both + * callers hold a ready source (fp_bind_fields only when out->enc is false; + * the STR dictionary leg only for a generation-0 column), so it never decodes. */ +static int fp_src_plain(ray_col_src_t* s, ray_t** col, ray_t** err) { + ray_t* e = ray_col_src_plain(s, col); /* ready-only */ + if (e) { *err = e; return -1; } + return 0; +} + +/* The column fields of a compiled child: today's pointers for a ready + * source; the source's metadata and no pointer for an encoded one (a view + * is bound per morsel by fp_bind_view). */ +static int fp_bind_fields(ray_col_src_t* src, fp_cmp_t* out, ray_t** err) { + if (out->enc) { + out->col_type = src->type; + out->col_attrs = src->attrs; + out->col_esz = ray_sym_elem_size(src->type, src->attrs); + out->col_base = NULL; + out->col_obj = NULL; + out->col_len = src->len; + return 0; + } + ray_t* col = NULL; + if (fp_src_plain(src, &col, err) != 0) return -1; /* ready-only */ + out->col_type = col->type; + out->col_attrs = col->attrs; + out->col_esz = ray_sym_elem_size(col->type, col->attrs); + out->col_base = ray_data(col); + out->col_obj = col; + out->col_len = col->len; + ray_t* own = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; + out->col_pool = (col->type == RAY_STR && own->str_pool && !RAY_IS_ERR(own->str_pool)) + ? (const char*)ray_data(own->str_pool) : NULL; + return 0; } /* Compile predicate DAG node (a comparison with OP_SCAN lhs and OP_CONST * rhs) against `tbl`. Returns 0 on success, -1 if the shape can't be * handled (caller should bail and let the unfused path run). */ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, - fp_cmp_t* out) + fp_cmp_t* out, ray_t** err) { if (!pred_op || pred_op->arity != 2) return -1; out->fold = FP_FOLD_NONE; @@ -766,20 +976,24 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, ray_op_ext_t* rext = find_ext(g, rhs->id); if (!lext || !rext || !rext->literal) return -1; - ray_t* col = ray_table_get_col(tbl, lext->sym); - if (!col) return -1; - if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return -1; + /* Bind without decoding: every decision below reads the bound source; + * the plain column is requested only where a payload pointer is + * captured (R-READ: a decline takes the unfused scan path). */ + ray_t* berr = NULL; + if (ray_col_bind_declines(tbl, lext->sym)) return -1; + ray_col_src_t* src = ray_graph_bind_col(g, tbl, lext->sym, &berr); + if (berr) { *err = berr; return -1; } + if (!src) return -1; + if (src->parted) return -1; + out->src = src; + out->enc = ray_col_src_ready(src) == NULL; /* a generation-2 single-file column */ + out->col_pool = NULL; if (out->op == FP_IN) { - if (!fp_col_supported(col) || !fp_int_family(col->type)) return -1; + if (!fp_src_supported(src) || !fp_int_family(src->type)) return -1; ray_t* sv = rext->literal; if (!sv || !ray_is_vec(sv) || !fp_int_family(sv->type)) return -1; if (ray_len(sv) > 16) return -1; - out->col_type = col->type; - out->col_attrs = col->attrs; - out->col_esz = ray_sym_elem_size(col->type, col->attrs); - out->col_base = ray_data(col); - out->col_obj = col; - out->col_len = col->len; + if (fp_bind_fields(src, out, err) != 0) return -1; int8_t st = sv->type; int64_t nsv = ray_len(sv); int64_t out_n = 0; @@ -806,29 +1020,25 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, /* A nullable text column is admitted: a null cell is the empty * string on every like path, matched against the pattern once * here (like_empty_match). */ - if (col->type != RAY_STR && col->type != RAY_SYM) return -1; + if (src->type != RAY_STR && src->type != RAY_SYM) return -1; ray_t* cv_like = rext->literal; if (!cv_like || cv_like->type != -RAY_STR) return -1; - out->col_type = col->type; - out->col_attrs = col->attrs; - out->col_esz = ray_sym_elem_size(col->type, col->attrs); - out->col_base = ray_data(col); - out->col_obj = col; - out->col_len = col->len; + if (fp_bind_fields(src, out, err) != 0) return -1; out->pat_str = ray_str_ptr(cv_like); out->pat_len = ray_str_len(cv_like); out->pat_compiled = ray_glob_compile(out->pat_str, out->pat_len); out->like_empty_match = (out->pat_compiled.shape != RAY_GLOB_SHAPE_NONE) ? (uint8_t)ray_glob_match_compiled(&out->pat_compiled, "", 0) : (uint8_t)ray_glob_match("", 0, out->pat_str, out->pat_len); - if (col->type == RAY_SYM) { + if (src->type == RAY_SYM) { /* Cell ids are positions in the COLUMN's domain. Runtime * domain: borrow the global string snapshot (lock-free per * row). FILE domain: size the LUT by the domain's count and - * resolve lazily via ray_sym_domain_str at eval (col_obj - * carries the domain). Pre-flip this is always the runtime - * branch — exact no-op. */ - if (ray_sym_vec_domain(col) == ray_sym_runtime_domain()) { + * resolve lazily via ray_sym_domain_str at eval over like_dom, + * the source's domain (an encoded child has no col_obj). + * Pre-flip this is always the runtime branch — exact no-op. */ + out->like_dom = src->dom; + if (src->dom == ray_sym_runtime_domain()) { ray_t** sym_strings = NULL; uint32_t sym_count = 0; ray_sym_strings_borrow(&sym_strings, &sym_count); @@ -839,14 +1049,13 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, out->like_lut_count = sym_count; out->like_sym_strings = sym_strings; } else { - int64_t dn = ray_sym_domain_count(ray_sym_vec_domain(col)); + int64_t dn = ray_sym_domain_count(src->dom); if (dn <= 0 || dn > UINT32_MAX) return -1; uint8_t* lut = (uint8_t*)scratch_calloc(&out->aux_hdr, (size_t)dn); if (!lut) return -1; out->like_lut = lut; out->like_lut_count = (uint32_t)dn; - out->like_sym_strings = NULL; /* resolve via col_obj's domain */ - out->like_dom = ray_sym_vec_domain(col); + out->like_sym_strings = NULL; /* resolve via like_dom */ out->like_raw_ok = ray_sym_domain_raw_pin(out->like_dom, &out->like_raw) ? 1 : 0; } } @@ -856,57 +1065,72 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, /* Dict-encoded STR EQ/NE: drive the comparison on the column's int32 * dict-code vector (like a W32 SYM). Resolve the constant string to - * its code once; absent ⇒ EQ all-false / NE all-true via fold. */ - if (col->type == RAY_STR && (out->op == FP_EQ || out->op == FP_NE) - && ray_index_kind(col) == RAY_IDX_DICT) { - if (!fp_col_supported_op(col, 1)) return -1; + * its code once; absent => EQ all-false / NE all-true via fold. A + * source without a dictionary (-2) takes the typed leg below. */ + if (src->type == RAY_STR && (out->op == FP_EQ || out->op == FP_NE) + && rext->literal && rext->literal->type == -RAY_STR) { ray_t* cv_str = rext->literal; - if (!cv_str || cv_str->type != -RAY_STR) return -1; - ray_index_t* dix = ray_index_payload(col->index); - ray_t* codes = dix->u.dict.codes; - if (!codes || RAY_IS_ERR(codes) || codes->len != col->len) return -1; - int64_t code = fp_dict_str_code(col, dix, - ray_str_ptr(cv_str), ray_str_len(cv_str)); - out->col_type = RAY_I32; /* compare codes as int32 */ - out->col_attrs = 0; - out->col_esz = 4; - out->col_base = ray_data(codes); - out->col_obj = codes; - out->col_len = col->len; - out->cval = (code >= 0) ? code : 0; - out->cval_in_dict = (code >= 0) ? 1 : 0; - if (code < 0) - out->fold = (out->op == FP_EQ) ? FP_FOLD_FALSE : FP_FOLD_TRUE; - return 0; + int64_t code = ray_col_src_dict_code(src, ray_str_ptr(cv_str), ray_str_len(cv_str)); + if (code != -2) { /* never for an encoded source (no dictionary) */ + ray_t* col = NULL; + if (fp_src_plain(src, &col, err) != 0) return -1; + ray_index_t* dix = ray_index_payload(col->index); + ray_t* codes = dix->u.dict.codes; + if (!codes || RAY_IS_ERR(codes) || codes->len != col->len) return -1; + out->col_type = RAY_I32; /* compare codes as int32 */ + out->col_attrs = 0; + out->col_esz = 4; + out->col_base = ray_data(codes); + out->col_obj = codes; + out->col_len = col->len; + out->cval = (code >= 0) ? code : 0; + out->cval_in_dict = (code >= 0) ? 1 : 0; + if (code < 0) + out->fold = (out->op == FP_EQ) ? FP_FOLD_FALSE : FP_FOLD_TRUE; + return 0; + } + /* a generation-2 single-file column with a persisted DICT (P6b), + * materialized or not: its codes, read from the mapping by range + * (fp_bind_view); "" is an entry, so the null rows compare exactly */ + ray_enccol_t* de = (src->obj && src->obj->type == RAY_ENCCOL) ? ray_enccol_of(src->obj) : NULL; + int64_t dc = -2; + if (ray_enccol_has_idict(de)) { + ray_t* ce = ray_enccol_idict_code(de, ray_str_ptr(cv_str), ray_str_len(cv_str), &dc); + if (ce) { *err = ce; return -1; } + } + if (dc >= -1) { /* -2: no DICT after all, the typed leg below */ + out->col_type = RAY_I32; out->col_attrs = 0; out->col_esz = 4; + out->col_base = NULL; out->col_obj = NULL; out->col_len = src->len; + out->typed_compare = 0; + out->enc = true; out->idict = de; + out->cval = dc >= 0 ? dc : 0; + out->cval_in_dict = dc >= 0; + if (dc < 0) out->fold = (out->op == FP_EQ) ? FP_FOLD_FALSE : FP_FOLD_TRUE; + return 0; + } } /* Ordering ops on SYM are meaningless (dict ID order != string order). */ - if (col->type == RAY_SYM && (out->op == FP_LT || out->op == FP_LE || + if (src->type == RAY_SYM && (out->op == FP_LT || out->op == FP_LE || out->op == FP_GT || out->op == FP_GE)) return -1; /* Admission and execution share the typed comparison/null contract. */ - if (!fp_col_supported_op(col, out->op == FP_EQ || out->op == FP_NE)) + if (!fp_src_supported_op(src, out->op == FP_EQ || out->op == FP_NE)) return -1; ray_t* cv = rext->literal; /* Atom type ↔ column class compatibility — block mixed-temporal * forms like `(== date_col timestamp_const)` whose raw-unit * comparison is meaningless. */ - if (!fp_atom_col_compatible(cv->type, col->type)) return -1; - - out->col_type = col->type; - out->col_attrs = col->attrs; - out->col_esz = ray_sym_elem_size(col->type, col->attrs); - out->col_base = ray_data(col); - out->col_obj = col; - out->col_len = col->len; + if (!fp_atom_col_compatible(cv->type, src->type)) return -1; + if (fp_bind_fields(src, out, err) != 0) return -1; out->literal = cv; out->constant_null = RAY_ATOM_IS_NULL(cv); - out->float_compare = col->type == RAY_F32 || col->type == RAY_F64 || cv->type == -RAY_F32 || cv->type == -RAY_F64; - out->typed_compare = col->type == RAY_STR || col->type == RAY_GUID || - (col->type != RAY_SYM && (out->float_compare || out->constant_null || ray_vec_may_have_nulls(col))); - if (col->type == RAY_STR || col->type == RAY_GUID) return 0; + out->float_compare = src->type == RAY_F32 || src->type == RAY_F64 || cv->type == -RAY_F32 || cv->type == -RAY_F64; + out->typed_compare = src->type == RAY_STR || src->type == RAY_GUID || + (src->type != RAY_SYM && (out->float_compare || out->constant_null || src->may_null)); + if (src->type == RAY_STR || src->type == RAY_GUID) return 0; if (out->col_type == RAY_SYM) { /* The constant must be expressed in the COLUMN's domain — cells @@ -915,18 +1139,18 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, * all-true fold via cval_in_dict). Exact no-op while the column * is runtime-domain: a runtime atom's id IS the cell-id space. */ if (cv->type == -RAY_SYM) { - if (ray_sym_vec_domain(col) == ray_sym_runtime_domain()) { + if (src->dom == ray_sym_runtime_domain()) { out->cval = cv->i64; out->cval_in_dict = 1; } else { ray_t* cs = ray_sym_str(cv->i64); /* atom: runtime id */ - int64_t did = cs ? ray_sym_vec_lookup(col, ray_str_ptr(cs), - ray_str_len(cs)) : -1; + int64_t did = cs ? ray_col_src_sym_find(src, ray_str_ptr(cs), + ray_str_len(cs)) : -1; out->cval = (did >= 0) ? did : 0; out->cval_in_dict = (did >= 0) ? 1 : 0; } } else if (cv->type == -RAY_STR) { - int64_t did = ray_sym_vec_lookup(col, ray_str_ptr(cv), ray_str_len(cv)); + int64_t did = ray_col_src_sym_find(src, ray_str_ptr(cv), ray_str_len(cv)); out->cval = (did >= 0) ? did : 0; out->cval_in_dict = (did >= 0) ? 1 : 0; } else { @@ -1005,18 +1229,18 @@ static int fp_compile_cmp(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, * OP_AND node. Returns 0 on success, -1 if a leaf can't be compiled or * the fan-in exceeds FP_PRED_MAX_CHILDREN. */ static int fp_compile_pred_dag(ray_graph_t* g, ray_op_t* node, ray_t* tbl, - fp_pred_t* out) + fp_pred_t* out, ray_t** err) { if (!node) return -1; if (node->opcode == OP_AND) { - if (fp_compile_pred_dag(g, op_child(g, node, 0), tbl, out) != 0) return -1; - if (fp_compile_pred_dag(g, op_child(g, node, 1), tbl, out) != 0) return -1; + if (fp_compile_pred_dag(g, op_child(g, node, 0), tbl, out, err) != 0) return -1; + if (fp_compile_pred_dag(g, op_child(g, node, 1), tbl, out, err) != 0) return -1; return 0; } if (out->n_children >= FP_PRED_MAX_CHILDREN) return -1; fp_cmp_t tmp; memset(&tmp, 0, sizeof(tmp)); - if (fp_compile_cmp(g, node, tbl, &tmp) != 0) { + if (fp_compile_cmp(g, node, tbl, &tmp, err) != 0) { if (tmp.aux_hdr) scratch_free(tmp.aux_hdr); return -1; } @@ -1049,14 +1273,15 @@ static void fp_pred_order_children(fp_pred_t* p) { } int fp_compile_pred(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, - fp_pred_t* out) + fp_pred_t* out, ray_t** err) { + *err = NULL; memset(out, 0, sizeof(*out)); out->n_children = 0; /* No predicate → const-true. fp_eval_pred memsets bits to 1 * when n_children == 0, so the worker treats every row as a hit. */ if (!pred_op) return 0; - int rc = fp_compile_pred_dag(g, pred_op, tbl, out); + int rc = fp_compile_pred_dag(g, pred_op, tbl, out, err); if (rc == 0 && out->n_children > 1) fp_pred_order_children(out); return rc; diff --git a/src/ops/fused_pred.h b/src/ops/fused_pred.h index be2fea7fc..92d3e79ab 100644 --- a/src/ops/fused_pred.h +++ b/src/ops/fused_pred.h @@ -24,6 +24,8 @@ #ifndef RAY_OPS_FUSED_PRED_H #define RAY_OPS_FUSED_PRED_H +#include "store/colrange.h" +#include "store/enccol.h" /* ray_enc_vview_t */ #include "rayforce.h" #include "ops/internal.h" #include "ops/glob.h" @@ -86,6 +88,19 @@ typedef struct { * LUT does not cover (the same rule as the bare like kernel). */ uint8_t like_empty_match; struct ray_sym_domain_s* like_dom; + /* The bound source (borrowed from the graph). enc: a generation-2 + * single-file column without a published materialization, or an + * idict child (materialized or not); col_base + * and col_obj are NULL at compile and a view is bound per morsel + * (fp_eval_pred_rs). col_pool: STR, the base of the pooled ray_str_t + * offsets col_base's descriptors point into. */ + ray_col_src_t* src; + bool enc; + const char* col_pool; + /* P6b: a STR == / != child over a generation-2 column's persisted DICT: + * col_type RAY_I32, cval its code; fp_bind_view reads the codes by range + * (never a zone decision: DICT codes are membership values) */ + struct ray_enccol_s* idict; } fp_cmp_t; typedef struct { @@ -97,14 +112,34 @@ typedef struct { * bits[0..end-start). */ void fp_eval_cmp(const fp_cmp_t* p, int64_t start, int64_t end, uint8_t* bits); -/* Evaluate the full (possibly ANDed) predicate; AND of children into bits[]. */ +/* Evaluate the full (possibly ANDed) predicate; AND of children into bits[]. + * No child may be encoded (fp_eval_pred_rs reads those). */ void fp_eval_pred(const fp_pred_t* p, int64_t start, int64_t end, uint8_t* bits); +/* Per-task range-read scratch, one per child, and one vector view for the + * encoded leaves (about 21 KB: the task holds it on its stack). Allocate + * it per task, free it inside the same task (a scratch holds its column + * until freed). */ +typedef struct { + ray_col_scratch_t sc[FP_PRED_MAX_CHILDREN]; + ray_enc_vview_t vb; +} fp_scratch_t; +void fp_scratch_init(fp_scratch_t* s); +void fp_scratch_free(fp_scratch_t* s); +/* fp_eval_pred over [start, end) (end - start <= RAY_MORSEL_ELEMS) with + * range reads for encoded children. NULL or an owned error. */ +ray_t* fp_eval_pred_rs(const fp_pred_t* p, int64_t start, int64_t end, + uint8_t* bits, fp_scratch_t* s); + /* Walk an OP_AND tree of leaf comparisons and populate fp_pred_t. - * Returns 0 on success, -1 if any leaf can't be compiled or fan-in - * exceeds FP_PRED_MAX_CHILDREN. */ + * Returns 0 on success; -1 with *err NULL when a leaf is not supported + * (a decline: the caller takes the unfused path) or the fan-in exceeds + * FP_PRED_MAX_CHILDREN; -1 with an owned *err when binding or the plain + * request failed (OOM, a corrupt column): the caller returns that error. + * Call fp_pred_cleanup before releasing the graph (like_dom is borrowed + * from a bound source). */ int fp_compile_pred(ray_graph_t* g, ray_op_t* pred_op, ray_t* tbl, - fp_pred_t* out); + fp_pred_t* out, ray_t** err); void fp_pred_cleanup(fp_pred_t* p); diff --git a/src/ops/fused_topk.c b/src/ops/fused_topk.c index 581835bb6..ac0a43332 100644 --- a/src/ops/fused_topk.c +++ b/src/ops/fused_topk.c @@ -45,6 +45,8 @@ #include "ops/fused_pred.h" #include "ops/fused_group.h" /* ray_fused_group_supported */ #include "ops/internal.h" +#include "ops/colbind.h" +#include "ops/colgather.h" /* generation-2 output gathers */ #include "lang/internal.h" #include "core/pool.h" #include "ops/idxop.h" /* chunk-zone extrema: skip chunks that cannot enter the top-K */ @@ -68,6 +70,39 @@ int ray_fused_topk_supported(ray_t* where_expr, ray_t* tbl) { * ──────────────────────────────────────────────────────────────────── */ #define FPK_MAX_KEYS 16 +_Static_assert(RAY_ENC_CHUNK == (1 << 16), "the directory zone is one chunk per 1 << 16 rows"); +_Static_assert(RAY_MORSEL_ELEMS == RAY_ENC_VEC, "a top-k morsel touches at most two key vectors"); + +/* Test hook: how often a fused select compiled its predicate (ran) and how + * often it declined to the unfused path. */ +static _Atomic uint64_t g_fpk_ran, g_fpk_declined; +static void fpk_count(int declined) { + atomic_fetch_add_explicit(declined ? &g_fpk_declined : &g_fpk_ran, 1, memory_order_relaxed); +} +void ray_fused_topk_counters(uint64_t* ran, uint64_t* declined) { + *ran = atomic_load(&g_fpk_ran); + *declined = atomic_load(&g_fpk_declined); +} +void ray_fused_topk_counters_reset(void) { atomic_store(&g_fpk_ran, 0); atomic_store(&g_fpk_declined, 0); } + +/* Test hook: pruning events of the last ray_fused_topk_select (reset at + * its entry): chunk-slot prunes (per task fragment, so a chunk split + * across tasks counts once per task: dispatch geometry, not distinct + * chunks) and pruned morsels. */ +static _Atomic uint64_t g_fpk_pruned_chunks, g_fpk_pruned_vecs; +void ray_fused_topk_test_pruned(uint64_t* chunks, uint64_t* vectors) { + *chunks = atomic_load(&g_fpk_pruned_chunks); + *vectors = atomic_load(&g_fpk_pruned_vecs); +} + +/* Per-range statistics class of a generation-2 first key. */ +enum { FPK_STATS = 0, FPK_ALL_NULL = 1, FPK_NO_STATS = 2 }; + +/* The first-key types whose ranges are pruned: their statistics are + * signed logical_T values, ordered as fpk_key_i64 reads the key. */ +static inline bool fpk_prunable_type(int8_t t) { + return t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; +} typedef struct { int8_t type; @@ -98,9 +133,18 @@ typedef struct { } fpk_keyspec_t; static void fpk_unpin_keys(fpk_keyspec_t* keys, uint32_t n) { for (uint32_t i = 0; i < n; i++) - if (keys[i].raw_ok) { ray_sym_domain_raw_unpin(ray_sym_vec_domain(keys[i].col)); keys[i].raw_ok = 0; } + if (keys[i].raw_ok) { ray_sym_domain_raw_unpin(keys[i].raw.dom); keys[i].raw_ok = 0; } } +/* A single-file generation-2 first key: the zone arrays of fpk_par_ctx_t + * come from its directory, zstat[c] is chunk c's FPK_* class, and the + * vectors of a surviving chunk are pruned from their descriptors (src, e). */ +typedef struct fpk_dir_s { + const uint8_t* zstat; + ray_enccol_t* e; + const ray_col_src_t* src; +} fpk_dir_t; + typedef struct { fp_pred_t pred; fpk_keyspec_t keys[FPK_MAX_KEYS]; @@ -150,12 +194,54 @@ typedef struct { * of the data. NULL when there is no zone index. */ const uint32_t* zorder; int64_t nrows; + /* range-read failures of the predicate scan, keyed by the morsel's + * first row: the lowest wins. Held by pointer (the envelope lives on + * the coordinator's stack): embedding it here put a few hundred bytes + * between the hot read-only fields and moved the top-k loop's layout. */ + ray_scan_fail_t* fail; + /* A generation-2 first key's directory pruning (fpk_dir_t), NULL on the + * chunk-zone path. By pointer, in the padding before `bound`: the + * fields the plain instance reads keep their offsets (and its code). */ + const struct fpk_dir_s* zdir; /* written by every worker with a full heap: own cache line, away from * the read-only zone pointers above */ _Alignas(64) _Atomic(int64_t) bound; _Atomic(uint8_t) bound_set; + /* Range-read keys (fpk_rk_t), NULL when every key is read in place: + * last, so the fields above keep their offsets. */ + const struct fpk_rk_s* rk; } fpk_par_ctx_t; +/* ---- Range-read sort keys ---- + * + * A sort key that is a generation-2 column without a published + * materialization is not decoded whole for the top-k: each task reads the + * key vectors of the morsels whose rows pass the predicate through a + * cursor, and the heaps carry the key values of the rows they hold, so a + * compare never reads a row outside the vector being scanned. Entry e + * (worker w's slot s is e = w * k + s) holds row rows[e] and key j's value + * kv[e * n_keys + j] (integers and SYM ids widened to int64, floats as the + * bits of their double) with its null flag kn[e * n_keys + j]. The order + * is fpk_cmp's: nulls where sort_nulls_first puts them, then the values, + * then the row. A candidate's later keys are read only when its earlier + * ones tie the heap's worst. */ +typedef struct fpk_rk_s { + int64_t* rows; + int64_t* kv; + uint8_t* kn; + ray_col_src_t* srcs[FPK_MAX_KEYS]; /* borrowed binds */ + struct ray_sym_domain_s* dom[FPK_MAX_KEYS]; /* SYM keys */ +} fpk_rk_t; + +/* One task's key cursors and the candidate row it compares. */ +typedef struct { + ray_col_cursor_t cur[FPK_MAX_KEYS]; + int64_t cv[FPK_MAX_KEYS]; + uint8_t cn[FPK_MAX_KEYS]; + uint32_t have; /* bit j: key j of crow is in cv / cn */ + int64_t crow; +} fpk_rk_task_t; + static inline int64_t fpk_key_i64(const fpk_keyspec_t* ks, int64_t row) { switch (ks->esz) { case 1: return (int64_t)((const uint8_t*)ks->base)[row]; @@ -194,6 +280,61 @@ static inline bool fpk_chunk_pruned(const fpk_par_ctx_t* c, int64_t g) { return c->zdesc ? c->zmax[g] < b : c->zmin[g] > b; } +/* The statistics rule of a generation-2 range (a chunk or a vector) of + * class `cls`: it cannot hold a row that beats the bound. Nulls sort first + * ascending and last descending (sort_nulls_first), and the bound is always + * a non-null key, so: with statistics, ascending prunes only a range + * without nulls and descending judges a range by its non-null extrema; + * an all-null range is pruned only descending; a range without statistics + * never. Strict: a range whose extremum ties the bound may hold a row that + * wins on a later key or on the row order. */ +static inline bool fpk_stat_prunes(const fpk_par_ctx_t* c, uint8_t cls, bool has_nulls, + int64_t mn, int64_t mx) { + if (!atomic_load_explicit(&c->bound_set, memory_order_acquire)) return false; + if (cls == FPK_NO_STATS) return false; + if (cls == FPK_ALL_NULL) return c->zdesc; + if (!c->zdesc && has_nulls) return false; + int64_t b = atomic_load_explicit(&c->bound, memory_order_relaxed); + return c->zdesc ? mx < b : mn > b; +} + +/* fpk_chunk_pruned for the directory arrays (zdir set). */ +static inline bool fpk_dir_chunk_pruned(const fpk_par_ctx_t* c, int64_t g) { + if (g < 0 || g >= (int64_t)c->zn) return false; + bool has_nulls = (c->znull[g >> 3] >> (g & 7)) & 1; + return fpk_stat_prunes(c, c->zdir->zstat[g], has_nulls, c->zmin[g], c->zmax[g]); +} + +/* Vector v of the first key cannot hold a row that beats the bound (its + * descriptor; ray_col_src_vec_stat declines an all-null vector and one + * without statistics alike, and the descriptor's null count tells them + * apart). */ +static bool fpk_one_vec_pruned(const fpk_par_ctx_t* c, int64_t v) { + int64_t vrows = c->nrows - v * RAY_ENC_VEC; + if (vrows > RAY_ENC_VEC) vrows = RAY_ENC_VEC; + int64_t mn = 0, mx = 0; + uint32_t nn = 0; + uint8_t cls = FPK_STATS; + if (!ray_col_src_vec_stat(c->zdir->src, v, &mn, &mx, &nn)) { + const ray_enc_desc_t* d = ray_enccol_descs(c->zdir->e, v / RAY_ENC_VECS_PER_CHUNK); + cls = d[v % RAY_ENC_VECS_PER_CHUNK].n_nulls == vrows ? FPK_ALL_NULL : FPK_NO_STATS; + } + return fpk_stat_prunes(c, cls, nn > 0, mn, mx); +} + +/* No row of the morsel [row, mend) can beat the bound: every vector it + * touches says so. Task starts stay on the dispatch grain (a multiple of + * the vector, pool_geometry), so a morsel touches one vector today; the + * loop guards a grain off the vector grid. Statistics bound every row of + * their vector, so a partial morsel is pruned as exactly as a whole one. */ +static bool fpk_vec_pruned(const fpk_par_ctx_t* c, int64_t row, int64_t mend) { + if (!atomic_load_explicit(&c->bound_set, memory_order_relaxed)) return false; + int64_t v0 = row / RAY_ENC_VEC, v1 = (mend - 1) / RAY_ENC_VEC; + for (int64_t v = v0; v <= v1; v++) + if (!fpk_one_vec_pruned(c, v)) return false; + return true; +} + /* Chunk `a` is more promising than chunk `b` for the first key's * direction: null chunks lead when nulls sort ahead, then the smaller * minimum (asc) or the larger maximum (desc); ties keep chunk order. */ @@ -383,23 +524,234 @@ static inline void fpk_heapify(const fpk_par_ctx_t* c, int64_t* heap, int32_t n) fpk_sift_down(c, heap, n, i); } +/* fpk_cmp's SYM arm over two ids of a range-read key: 0 when they tie + * (or a string cannot be resolved, as fpk_cmp continues past it). */ +static int fpk_rk_sym_cmp(const fpk_par_ctx_t* c, uint32_t j, uint32_t ia, uint32_t ib) { + if (ia == ib) return 0; + const fpk_keyspec_t* ks = &c->keys[j]; + if (ks->raw_ok && (int64_t)ia < ks->raw.count && (int64_t)ib < ks->raw.count) { + /* off the mapped vocabulary, as fpk_cmp: no atom is made per compare */ + size_t la, lb; + const char* pa = ray_sym_domain_raw_str(&ks->raw, (int64_t)ia, &la); + const char* pb = ray_sym_domain_raw_str(&ks->raw, (int64_t)ib, &lb); + size_t ml = la < lb ? la : lb; + int cmp = ml ? memcmp(pa, pb, ml) : 0; + return cmp ? cmp : (la < lb ? -1 : (la > lb ? 1 : 0)); + } + ray_t* sa; + ray_t* sb; + if (ks->dom_runtime) { + if (ia >= c->sym_count || ib >= c->sym_count) return 0; + sa = c->sym_strings[ia]; + sb = c->sym_strings[ib]; + } else { + sa = ray_sym_domain_str(c->rk->dom[j], (int64_t)ia); + sb = ray_sym_domain_str(c->rk->dom[j], (int64_t)ib); + } + if (!sa || !sb) return 0; + return ray_str_cmp(sa, sb); +} + +/* Key j of two entries' values: fpk_cmp's sense ("a is worse" > 0). */ +static inline int fpk_rk_key_cmp(const fpk_par_ctx_t* c, uint32_t j, int64_t va, uint8_t na, + int64_t vb, uint8_t nb) { + const fpk_keyspec_t* ks = &c->keys[j]; + if (ks->has_nulls) { + if (na && nb) return 0; + if (na) return ks->nulls_first ? -1 : 1; + if (nb) return ks->nulls_first ? 1 : -1; + } + int cmp; + if (ks->type == RAY_SYM) { + cmp = fpk_rk_sym_cmp(c, j, (uint32_t)va, (uint32_t)vb); + } else if (ks->type == RAY_F32 || ks->type == RAY_F64) { + double da, db; + memcpy(&da, &va, 8); memcpy(&db, &vb, 8); + cmp = (da > db) - (da < db); + } else { + cmp = (va > vb) - (va < vb); + } + return ks->desc ? -cmp : cmp; +} + +/* Entries ea and eb in fpk_cmp's order. */ +static int fpk_rk_ent_cmp(const fpk_par_ctx_t* c, int64_t ea, int64_t eb) { + if (ea == eb) return 0; + const fpk_rk_t* rk = c->rk; + const uint32_t nk = c->n_keys; + for (uint32_t j = 0; j < nk; j++) { + int cmp = fpk_rk_key_cmp(c, j, rk->kv[ea * nk + j], rk->kn[ea * nk + j], + rk->kv[eb * nk + j], rk->kn[eb * nk + j]); + if (cmp) return cmp; + } + int64_t ra = rk->rows[ea], rb = rk->rows[eb]; + return (ra > rb) - (ra < rb); +} + +/* Key j of the task's candidate row, read through its cursor (the vector + * the row lies in; a later key of the same morsel reuses its decode). */ +static ray_t* fpk_rk_load(const fpk_par_ctx_t* c, fpk_rk_task_t* t, uint32_t j) { + if ((t->have >> j) & 1u) return NULL; + const ray_col_range_t* v = NULL; + ray_t* err = ray_col_cursor_at(&t->cur[j], t->crow, &v); + if (err) return err; + const int64_t i = t->crow - v->start; + const fpk_keyspec_t* ks = &c->keys[j]; + int64_t x; + switch (ks->type) { + case RAY_SYM: x = ray_read_sym(v->data, i, RAY_SYM, v->attrs); break; + case RAY_BOOL: case RAY_U8: x = ((const uint8_t*)v->data)[i]; break; + case RAY_I16: x = ((const int16_t*)v->data)[i]; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: x = ((const int32_t*)v->data)[i]; break; + case RAY_F32: { double d = ((const float*)v->data)[i]; memcpy(&x, &d, 8); break; } + case RAY_F64: memcpy(&x, (const double*)v->data + i, 8); break; + default: x = ((const int64_t*)v->data)[i]; break; /* I64, TIMESTAMP */ + } + t->cv[j] = x; + t->cn[j] = ks->has_nulls && ray_raw_is_null(ks->type, v->attrs, v->data, i); + t->have |= 1u << j; + return NULL; +} + +/* The candidate against entry e: *cmp in fpk_cmp's sense, reading the + * candidate's keys only as far as they tie. */ +static ray_t* fpk_rk_cand_cmp(const fpk_par_ctx_t* c, fpk_rk_task_t* t, int64_t e, int* cmp) { + const fpk_rk_t* rk = c->rk; + const uint32_t nk = c->n_keys; + for (uint32_t j = 0; j < nk; j++) { + ray_t* err = fpk_rk_load(c, t, j); + if (err) return err; + int d = fpk_rk_key_cmp(c, j, t->cv[j], t->cn[j], rk->kv[e * nk + j], rk->kn[e * nk + j]); + if (d) { *cmp = d; return NULL; } + } + int64_t rb = rk->rows[e]; + *cmp = (t->crow > rb) - (t->crow < rb); + return NULL; +} + +/* The candidate, every key read, into entry e. */ +static ray_t* fpk_rk_store(const fpk_par_ctx_t* c, fpk_rk_task_t* t, int64_t e) { + const fpk_rk_t* rk = c->rk; + const uint32_t nk = c->n_keys; + for (uint32_t j = 0; j < nk; j++) { + ray_t* err = fpk_rk_load(c, t, j); + if (err) return err; + rk->kv[e * nk + j] = t->cv[j]; + rk->kn[e * nk + j] = t->cn[j]; + } + rk->rows[e] = t->crow; + return NULL; +} + +static void fpk_rk_sift_down(const fpk_par_ctx_t* c, int64_t* heap, int32_t n, int32_t i) { + for (;;) { + int32_t worst = i; + int32_t l = 2 * i + 1, r = 2 * i + 2; + if (l < n && fpk_rk_ent_cmp(c, heap[l], heap[worst]) > 0) worst = l; + if (r < n && fpk_rk_ent_cmp(c, heap[r], heap[worst]) > 0) worst = r; + if (worst == i) return; + int64_t ti = heap[i]; heap[i] = heap[worst]; heap[worst] = ti; + i = worst; + } +} + +static void fpk_rk_heapify(const fpk_par_ctx_t* c, int64_t* heap, int32_t n) { + for (int32_t i = n / 2 - 1; i >= 0; i--) + fpk_rk_sift_down(c, heap, n, i); +} + +/* fpk_publish_bound from entry e's stored first key. */ +static void fpk_rk_publish_bound(fpk_par_ctx_t* c, int64_t e) { + if (!c->zmin) return; + const uint32_t nk = c->n_keys; + if (c->rk->kn[e * nk]) return; + int64_t v = c->rk->kv[e * nk]; + int64_t cur = atomic_load_explicit(&c->bound, memory_order_relaxed); + bool set = atomic_load_explicit(&c->bound_set, memory_order_relaxed); + for (;;) { + bool better = !set || (c->zdesc ? v > cur : v < cur); + if (!better) return; + if (atomic_compare_exchange_weak_explicit(&c->bound, &cur, v, + memory_order_relaxed, memory_order_relaxed)) { + atomic_store_explicit(&c->bound_set, 1, memory_order_release); + return; + } + set = true; + } +} + +/* The passing rows of one morsel into the task's heap (entries ebase + + * [0, k)): NULL, or an owned error of a key read. */ +static ray_t* fpk_rk_insert(fpk_par_ctx_t* c, fpk_rk_task_t* t, int64_t* hidx, int32_t* hnp, int32_t k, + int64_t ebase, int64_t row, int64_t mlen, const uint8_t* bits) { + int32_t hn = *hnp; + ray_t* err = NULL; + for (int64_t r = 0; r < mlen && !err; r++) { + if (!bits[r]) continue; + t->crow = row + r; + t->have = 0; + if (hn < k) { + int64_t e = ebase + hn; + if ((err = fpk_rk_store(c, t, e)) != NULL) break; + hidx[hn++] = e; + if (hn == k) fpk_rk_heapify(c, hidx, k); + } else { + int cmp = 0; + if ((err = fpk_rk_cand_cmp(c, t, hidx[0], &cmp)) != NULL) break; + if (cmp >= 0) continue; + if ((err = fpk_rk_store(c, t, hidx[0])) != NULL) break; + fpk_rk_sift_down(c, hidx, k, 0); + } + } + *hnp = hn; + return err; +} + /* Scan physical rows [row, end): eval predicate per morsel, heap-insert * the passing rows. `*hnp` is the worker's heap fill on entry and exit. * `chunk` >= 0 is the zone chunk the rows belong to: the bound may tighten * while the chunk is being scanned (another worker's heap filled, or this * one's), so it is re-tested before every morsel — one relaxed load and a - * compare — and the rest of the chunk is abandoned once it cannot beat it. */ -static inline void fpk_scan_rows(fpk_par_ctx_t* c, int64_t* hidx, int32_t* hnp, - int32_t k, int64_t row, int64_t end, int64_t chunk) { + * compare — and the rest of the chunk is abandoned once it cannot beat it. + * Encoded predicate children read by range through the task's scratch `fs`; + * a failed read is noted under the morsel's first row and ends this call's + * rows (one ascending run within a chunk: the rest are higher keys), as + * does a failure noted below them. The task's other chunk slots may lie + * lower and are still scanned (fpk_par_fn). + * `zv` (constant per instance, with `rs`): the zone arrays are a + * generation-2 first key's directory; each morsel is first tested on the + * descriptors of the key vectors it touches and skipped, predicate unread, + * when it cannot beat the bound (counted in *npv). */ +RAY_INLINE void fpk_scan_rows(fpk_par_ctx_t* c, fp_scratch_t* fs, int64_t* hidx, int32_t* hnp, + int32_t k, int64_t row, int64_t end, int64_t chunk, const bool rs, + const bool zv, uint64_t* npv, fpk_rk_task_t* rt, int64_t ebase) { int32_t hn = *hnp; while (row < end) { - if (chunk >= 0 && fpk_chunk_pruned(c, chunk)) break; + if (zv) { + if (chunk >= 0 && fpk_dir_chunk_pruned(c, chunk)) break; + } else if (chunk >= 0 && fpk_chunk_pruned(c, chunk)) { + break; + } + if (rs && ray_scan_fail_skip(c->fail, row)) break; int64_t mend = row + RAY_MORSEL_ELEMS; if (mend > end) mend = end; + if (zv && fpk_vec_pruned(c, row, mend)) { (*npv)++; row = mend; continue; } int64_t mlen = mend - row; uint8_t bits[RAY_MORSEL_ELEMS]; - fp_eval_pred(&c->pred, row, mend, bits); + if (rs) { + ray_t* pe = fp_eval_pred_rs(&c->pred, row, mend, bits, fs); + if (pe) { ray_scan_fail_note(c->fail, row, pe); break; } + } else { + fp_eval_pred(&c->pred, row, mend, bits); /* no child is read by range */ + } + if (rt) { /* range-read keys (rs is set) */ + ray_t* ke = fpk_rk_insert(c, rt, hidx, &hn, k, ebase, row, mlen, bits); + if (ke) { ray_scan_fail_note(c->fail, row, ke); break; } + if (hn == k) fpk_rk_publish_bound(c, hidx[0]); + row = mend; + continue; + } for (int64_t r = 0; r < mlen; r++) { if (!bits[r]) continue; int64_t src_row = row + r; @@ -421,17 +773,35 @@ static inline void fpk_scan_rows(fpk_par_ctx_t* c, int64_t* hidx, int32_t* hnp, *hnp = hn; } -/* Worker fn: [start, end) is a range of physical rows, or — with a zone - * order — of virtual rows whose chunk slots map to physical chunks. */ -static void fpk_par_fn(void* raw, uint32_t worker_id, int64_t start, int64_t end) { +/* Worker body: [start, end) is a range of physical rows, or — with a zone + * order — of virtual rows whose chunk slots map to physical chunks. The + * range-read scratch lives and dies with the task. `rs` (some predicate + * child is read by range) is constant per instance: the plain one keeps + * the generation-0 loop, with no scratch and no failure envelope. `zv`: + * the directory zone arrays of a generation-2 first key (fpk_scan_rows). */ +RAY_INLINE void fpk_par_body(void* raw, uint32_t worker_id, int64_t start, int64_t end, + const bool rs, const bool zv, const bool rk) { fpk_par_ctx_t* c = (fpk_par_ctx_t*)raw; if (atomic_load_explicit(&c->oom, memory_order_relaxed)) return; int32_t k = (int32_t)c->k; int64_t* hidx = &c->heap_idx[(size_t)worker_id * (size_t)k]; int32_t hn = c->heap_n[worker_id]; + fp_scratch_t fs; + if (rs) fp_scratch_init(&fs); + fpk_rk_task_t rkt; + fpk_rk_task_t* rt = NULL; + const int64_t ebase = (int64_t)worker_id * k; + if (rk) { + for (uint32_t j = 0; j < c->n_keys; j++) ray_col_cursor_init(&rkt.cur[j], c->rk->srcs[j]); + rt = &rkt; + } + /* pruned here (zv), added once per task: npc counts chunk-slot prunes + * (a chunk split across tasks counts once per task; one abandoned + * mid-scan is not counted), npv pruned morsels */ + uint64_t npc = 0, npv = 0; if (!c->zmin) { - fpk_scan_rows(c, hidx, &hn, k, start, end, -1); + fpk_scan_rows(c, &fs, hidx, &hn, k, start, end, -1, rs, zv, &npv, rt, ebase); } else { int64_t span = (int64_t)1 << c->zlog2; int64_t v = start; @@ -441,18 +811,50 @@ static void fpk_par_fn(void* raw, uint32_t worker_id, int64_t start, int64_t end int64_t send = sbeg + span; if (send > end) send = end; int64_t g = c->zorder ? (int64_t)c->zorder[slot] : slot; - if (!fpk_chunk_pruned(c, g)) { + if (!(zv ? fpk_dir_chunk_pruned(c, g) : fpk_chunk_pruned(c, g))) { int64_t p0 = (g << c->zlog2) + (v - sbeg); int64_t p1 = (g << c->zlog2) + (send - sbeg); if (p1 > c->nrows) p1 = c->nrows; - if (p0 < p1) fpk_scan_rows(c, hidx, &hn, k, p0, p1, g); + if (p0 < p1) fpk_scan_rows(c, &fs, hidx, &hn, k, p0, p1, g, rs, zv, &npv, rt, ebase); + } else if (zv) { + npc++; } v = send; } } + if (rs) fp_scratch_free(&fs); + if (rk) for (uint32_t j = 0; j < c->n_keys; j++) ray_col_cursor_free(&rkt.cur[j]); + if (zv && (npc | npv)) { + atomic_fetch_add_explicit(&g_fpk_pruned_chunks, npc, memory_order_relaxed); + atomic_fetch_add_explicit(&g_fpk_pruned_vecs, npv, memory_order_relaxed); + } c->heap_n[worker_id] = hn; } +static void fpk_par_fn_plain(void* raw, uint32_t worker_id, int64_t start, int64_t end) { + fpk_par_body(raw, worker_id, start, end, false, false, false); +} + +static void fpk_par_fn(void* raw, uint32_t worker_id, int64_t start, int64_t end) { + fpk_par_body(raw, worker_id, start, end, true, false, false); +} + +/* A generation-2 first key: its directory and descriptors prune (the + * predicate may still have no encoded child; fp_eval_pred_rs reads those + * in place). */ +static void fpk_par_fn_dir(void* raw, uint32_t worker_id, int64_t start, int64_t end) { + fpk_par_body(raw, worker_id, start, end, true, true, false); +} + +/* Range-read keys (fpk_rk_t), with or without a generation-2 first key's + * directory pruning. */ +static void fpk_par_fn_rk(void* raw, uint32_t worker_id, int64_t start, int64_t end) { + fpk_par_body(raw, worker_id, start, end, true, false, true); +} +static void fpk_par_fn_rk_dir(void* raw, uint32_t worker_id, int64_t start, int64_t end) { + fpk_par_body(raw, worker_id, start, end, true, true, true); +} + /* Insertion sort over K entries so output rows match full-sort + take order. */ static void fpk_sort_final(const fpk_par_ctx_t* c, int64_t* idx, int32_t n) { for (int32_t i = 1; i < n; i++) { @@ -479,59 +881,104 @@ ray_t* ray_fused_topk_select(ray_t* tbl, if (!tbl || tbl->type != RAY_TABLE || k <= 0 || n_out == 0) return NULL; if (k > FPK_MAX_K) return NULL; if (n_sort_keys == 0 || n_sort_keys > FPK_MAX_KEYS) return NULL; + atomic_store(&g_fpk_pruned_chunks, 0); + atomic_store(&g_fpk_pruned_vecs, 0); int64_t nrows = ray_table_nrows(tbl); if (nrows <= 0 || k >= nrows) return NULL; - for (uint32_t c = 0; c < n_out; c++) { - ray_t* col = ray_table_get_col(tbl, out_col_syms[c]); - if (!col) return NULL; - int8_t ot = col->type; - if (RAY_IS_PARTED(ot) || ot == RAY_MAPCOMMON) return NULL; - if (!ray_is_vec(col)) - return NULL; + for (uint32_t c = 0; c < n_out; c++) { /* a gate: metadata, no bind */ + ray_col_meta_t om; + if (!ray_table_col_meta(tbl, out_col_syms[c], &om)) return NULL; + if (RAY_IS_PARTED(om.type) || om.type == RAY_MAPCOMMON) return NULL; + if (om.type < RAY_BOOL || om.type > RAY_STR) return NULL; /* not a vector */ } - /* Resolve sort-key columns + decide if any need the SYM dict snapshot. */ + /* The graph owns the column binds: it is made before the sort keys are + * resolved and freed after the output is built. */ + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return NULL; + + /* Resolve sort-key columns + decide if any need the SYM dict snapshot. + * Sort keys are materialized (spec "Top-k"): the plain column is + * requested here; a failed bind or plain request is returned. */ fpk_par_ctx_t ctx; memset(&ctx, 0, sizeof(ctx)); int sym_needed = 0; + ray_col_src_t* ksrc0 = NULL; /* the first key's bound source */ + /* Range-read keys (fpk_rk_t): some key is a generation-2 column whose + * materialization is not published, and every key is a fixed-width + * scalar (not STR or GUID). Decided from metadata, before any key is + * requested plain. */ + fpk_rk_t rk; + memset(&rk, 0, sizeof(rk)); + bool use_rk = false, rk_ok = true; + for (uint32_t i = 0; i < n_sort_keys; i++) { + ray_col_meta_t km; + if (!ray_table_col_meta(tbl, sort_key_syms[i], &km)) { rk_ok = false; break; } + if (km.type == RAY_STR || km.type == RAY_GUID) rk_ok = false; + if (km.enc && !RAY_IS_PARTED(km.type) && !ray_enccol_decoded_peek(km.enc)) use_rk = true; + } + use_rk = use_rk && rk_ok; for (uint32_t i = 0; i < n_sort_keys; i++) { - ray_t* col = ray_table_get_col(tbl, sort_key_syms[i]); - if (!col) { fpk_unpin_keys(ctx.keys, i); return NULL; } - int8_t kt = col->type; - if (RAY_IS_PARTED(kt) || kt == RAY_MAPCOMMON) { fpk_unpin_keys(ctx.keys, i); return NULL; } + ray_col_meta_t km; + if (!ray_table_col_meta(tbl, sort_key_syms[i], &km)) { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return NULL; } + if (RAY_IS_PARTED(km.type) || km.type == RAY_MAPCOMMON || ray_col_bind_declines(tbl, sort_key_syms[i])) + { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return NULL; } + ray_t* berr = NULL; + ray_col_src_t* ksrc = ray_graph_bind_col(g, tbl, sort_key_syms[i], &berr); + if (berr) { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return berr; } + if (!ksrc) { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return NULL; } + int8_t kt = ksrc->type; + if (ksrc->parted || kt == RAY_MAPCOMMON) { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return NULL; } if (kt != RAY_SYM && kt != RAY_STR && kt != RAY_BOOL && kt != RAY_U8 && kt != RAY_I16 && kt != RAY_I32 && kt != RAY_I64 && kt != RAY_DATE && kt != RAY_TIME && kt != RAY_TIMESTAMP && kt != RAY_F32 && kt != RAY_F64 && kt != RAY_GUID) - { fpk_unpin_keys(ctx.keys, i); return NULL; } + { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return NULL; } + ray_t* col = NULL; + if (use_rk && (kt == RAY_STR || kt == RAY_GUID)) { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return NULL; } + if (!use_rk) { + ray_t* perr = ray_col_src_plain(ksrc, &col); /* random: top-k sort key */ + if (perr) { fpk_unpin_keys(ctx.keys, i); ray_graph_free(g); return perr; } + } + if (i == 0) ksrc0 = ksrc; + rk.srcs[i] = ksrc; + rk.dom[i] = ksrc->dom; ctx.keys[i].type = kt; - ctx.keys[i].attrs = col->attrs; - ctx.keys[i].esz = ray_sym_elem_size(kt, col->attrs); + ctx.keys[i].attrs = col ? col->attrs : ksrc->attrs; + ctx.keys[i].esz = ray_sym_elem_size(kt, ctx.keys[i].attrs); ctx.keys[i].desc = sort_descs[i]; - ctx.keys[i].has_nulls = ray_vec_may_have_nulls(col) ? 1 : 0; + ctx.keys[i].has_nulls = ksrc->may_null ? 1 : 0; ctx.keys[i].nulls_first = sort_nulls_first(sort_descs[i]); ctx.keys[i].dom_runtime = (kt == RAY_SYM && - ray_sym_vec_domain(col) == ray_sym_runtime_domain()) ? 1 : 0; + ksrc->dom == ray_sym_runtime_domain()) ? 1 : 0; ctx.keys[i].sym = sort_key_syms[i]; - ctx.keys[i].base = ray_data(col); + ctx.keys[i].base = col ? ray_data(col) : NULL; ctx.keys[i].col = col; ctx.keys[i].raw_ok = 0; if (ctx.keys[i].dom_runtime) sym_needed = 1; else if (kt == RAY_SYM) - ctx.keys[i].raw_ok = ray_sym_domain_raw_pin(ray_sym_vec_domain(col), &ctx.keys[i].raw) ? 1 : 0; + ctx.keys[i].raw_ok = ray_sym_domain_raw_pin(ksrc->dom, &ctx.keys[i].raw) ? 1 : 0; } ctx.n_keys = n_sort_keys; ctx.k = k; ctx.tbl = tbl; ctx.nrows = nrows; - { + /* A single-file generation-2 first key prunes from its directory and + * descriptors (built before the dispatch); its materialization's + * synthesized chunk zone is not used. */ + ray_enccol_t* kenc = NULL; + if (ray_col_src_encoded(ksrc0) && !ksrc0->parted && fpk_prunable_type(ctx.keys[0].type)) { + ray_enccol_t* e = ray_enccol_of(ksrc0->obj); + if (e->kind == RAY_ENCCOL_SINGLE && !e->synthetic && e->len == nrows && + e->n_chunks * RAY_ENC_CHUNK >= nrows) + kenc = e; + } + if (!kenc && ctx.keys[0].col) { ray_t* kc = ctx.keys[0].col; int8_t kt = ctx.keys[0].type; - if ((kt == RAY_I16 || kt == RAY_I32 || kt == RAY_I64 || kt == RAY_DATE || - kt == RAY_TIME || kt == RAY_TIMESTAMP) && - ray_index_kind(kc) == RAY_IDX_CHUNK_ZONE) { + if (fpk_prunable_type(kt) && ray_index_kind(kc) == RAY_IDX_CHUNK_ZONE) { ray_index_t* zx = ray_index_payload(kc->index); if (zx->built_for_len == kc->len && !zx->u.chunk_zone.is_f64 && zx->u.chunk_zone.mins && zx->u.chunk_zone.maxs && zx->u.chunk_zone.null_bits) { @@ -551,24 +998,28 @@ ray_t* ray_fused_topk_select(ray_t* tbl, /* Compile the predicate via a temp graph just for the WHERE clause. No * where: is a predicate with no children — every row passes — and the * heap does the whole sort-and-take in one pass. */ - ray_graph_t* g = ray_graph_new(tbl); - if (!g) { fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } if (where_expr) { ray_op_t* pred_dag = compile_expr_dag(g, where_expr); if (!pred_dag) { ray_graph_free(g); fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } - if (fp_compile_pred(g, pred_dag, tbl, &ctx.pred) != 0) { + ray_t* cerr = NULL; + if (fp_compile_pred(g, pred_dag, tbl, &ctx.pred, &cerr) != 0) { fp_pred_cleanup(&ctx.pred); ray_graph_free(g); fpk_unpin_keys(ctx.keys, n_sort_keys); - return NULL; + if (!cerr) fpk_count(1); + return cerr; /* NULL: a decline; else the bind failure */ } + fpk_count(0); } if (sym_needed) { ray_sym_strings_borrow(&ctx.sym_strings, &ctx.sym_count); - if (!ctx.sym_strings) { ray_graph_free(g); fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } + if (!ctx.sym_strings) { fp_pred_cleanup(&ctx.pred); ray_graph_free(g); fpk_unpin_keys(ctx.keys, n_sort_keys); return NULL; } } atomic_store_explicit(&ctx.oom, 0, memory_order_relaxed); + ray_scan_fail_t fail; + ctx.fail = &fail; + ray_scan_fail_init(ctx.fail); /* Allocate per-worker heaps. */ ray_pool_t* pool = ray_pool_get(); @@ -579,7 +1030,18 @@ ray_t* ray_fused_topk_select(ray_t* tbl, (size_t)nw * (size_t)k * sizeof(int64_t)); ctx.heap_n = (int32_t*)scratch_calloc(&hn_hdr, (size_t)nw * sizeof(int32_t)); - if (!ctx.heap_idx || !ctx.heap_n) { + ray_t *rkr_hdr = NULL, *rkv_hdr = NULL, *rkn_hdr = NULL; + if (use_rk) { + size_t ne = (size_t)nw * (size_t)k; + rk.rows = (int64_t*)scratch_alloc(&rkr_hdr, ne * sizeof(int64_t)); + rk.kv = (int64_t*)scratch_alloc(&rkv_hdr, ne * n_sort_keys * sizeof(int64_t)); + rk.kn = (uint8_t*)scratch_alloc(&rkn_hdr, ne * n_sort_keys); + ctx.rk = &rk; + } + if (!ctx.heap_idx || !ctx.heap_n || (use_rk && (!rk.rows || !rk.kv || !rk.kn))) { + if (rkr_hdr) scratch_free(rkr_hdr); + if (rkv_hdr) scratch_free(rkv_hdr); + if (rkn_hdr) scratch_free(rkn_hdr); if (idx_hdr) scratch_free(idx_hdr); if (hn_hdr) scratch_free(hn_hdr); fp_pred_cleanup(&ctx.pred); @@ -593,19 +1055,81 @@ ray_t* ray_fused_topk_select(ray_t* tbl, * to the physical chunks and pruning still applies). */ int64_t span_rows = nrows; ray_t* zord_hdr = NULL; + /* A generation-2 first key: the zone arrays from its directory, sized + * by the chunk count (structure, not statistics: answer-only). An all-null chunk gets its null bit and an empty + * range, as the chunk-zone builder writes. On OOM nothing is pruned. */ + ray_t *zmin_hdr = NULL, *zmax_hdr = NULL, *znb_hdr = NULL, *zstat_hdr = NULL; + fpk_dir_t zdir = { NULL, kenc, ksrc0 }; + if (kenc) { + int64_t nc = kenc->n_chunks; + int64_t* mins = (int64_t*)scratch_alloc(&zmin_hdr, (size_t)nc * sizeof(int64_t)); + int64_t* maxs = (int64_t*)scratch_alloc(&zmax_hdr, (size_t)nc * sizeof(int64_t)); + uint8_t* nb = (uint8_t*)scratch_calloc(&znb_hdr, (size_t)(nc + 7) / 8); + uint8_t* zst = (uint8_t*)scratch_alloc(&zstat_hdr, (size_t)nc); + if (mins && maxs && nb && zst) { + for (int64_t c = 0; c < nc; c++) { + ray_enc_chunk_stat_t st; + ray_enccol_chunk_stat(kenc, c, &st); + bool all_null = (int64_t)st.null_count == st.rows; + if (st.null_count) nb[c >> 3] |= (uint8_t)(1u << (c & 7)); + if (all_null || !st.has_minmax) { mins[c] = INT64_MAX; maxs[c] = INT64_MIN; } + else { mins[c] = st.min; maxs[c] = st.max; } + zst[c] = all_null ? FPK_ALL_NULL : st.has_minmax ? FPK_STATS : FPK_NO_STATS; + } + ctx.zmin = mins; ctx.zmax = maxs; ctx.znull = nb; + zdir.zstat = zst; + ctx.zdir = &zdir; + ctx.zn = (uint32_t)nc; ctx.zlog2 = 16; /* RAY_ENC_CHUNK rows */ + ctx.zdesc = ctx.keys[0].desc; + ctx.znulls_better = ctx.keys[0].nulls_first; + } + } if (ctx.zmin) { span_rows = (int64_t)ctx.zn << ctx.zlog2; uint32_t* ord = (uint32_t*)scratch_alloc(&zord_hdr, (size_t)ctx.zn * sizeof(uint32_t)); - if (ord) { + if (ord && ctx.zdir) { + /* chunks with statistics best first, then the rest in source order */ + uint32_t n = 0; + for (uint32_t g = 0; g < ctx.zn; g++) if (zdir.zstat[g] == FPK_STATS) ord[n++] = g; + fpk_order_chunks(&ctx, ord, n); + for (uint32_t g = 0; g < ctx.zn; g++) if (zdir.zstat[g] != FPK_STATS) ord[n++] = g; + ctx.zorder = ord; + } else if (ord) { for (uint32_t g = 0; g < ctx.zn; g++) ord[g] = g; fpk_order_chunks(&ctx, ord, ctx.zn); ctx.zorder = ord; } } - if (pool) ray_pool_dispatch(pool, fpk_par_fn, &ctx, span_rows); - else fpk_par_fn(&ctx, 0, 0, span_rows); + bool rs = false; + for (uint8_t i = 0; i < ctx.pred.n_children; i++) rs |= ctx.pred.children[i].enc; + void (*par_fn)(void*, uint32_t, int64_t, int64_t) = + use_rk ? (ctx.zdir ? fpk_par_fn_rk_dir : fpk_par_fn_rk) : + ctx.zdir ? fpk_par_fn_dir : rs ? fpk_par_fn : fpk_par_fn_plain; + if (pool) ray_pool_dispatch(pool, par_fn, &ctx, span_rows); + else par_fn(&ctx, 0, 0, span_rows); if (zord_hdr) { scratch_free(zord_hdr); ctx.zorder = NULL; } + if (zmin_hdr) scratch_free(zmin_hdr); + if (zmax_hdr) scratch_free(zmax_hdr); + if (znb_hdr) scratch_free(znb_hdr); + if (zstat_hdr) scratch_free(zstat_hdr); + ctx.zmin = ctx.zmax = NULL; ctx.znull = NULL; ctx.zdir = NULL; + + /* A failed range read (or a cancelled dispatch: skipped tasks noted + * nothing) is the query's error, never a partial top-k. */ + ray_t* ferr = ray_scan_fail_finish(ctx.fail, pool); + if (ferr || atomic_load_explicit(&ctx.oom, memory_order_relaxed)) { + if (rkr_hdr) scratch_free(rkr_hdr); + if (rkv_hdr) scratch_free(rkv_hdr); + if (rkn_hdr) scratch_free(rkn_hdr); + } + if (ferr) { + scratch_free(idx_hdr); scratch_free(hn_hdr); + fp_pred_cleanup(&ctx.pred); + ray_graph_free(g); + fpk_unpin_keys(ctx.keys, n_sort_keys); + return ferr; + } if (atomic_load_explicit(&ctx.oom, memory_order_relaxed)) { scratch_free(idx_hdr); scratch_free(hn_hdr); @@ -620,6 +1144,36 @@ ray_t* ray_fused_topk_select(ray_t* tbl, * enforced at function entry. */ int64_t global_idx[FPK_MAX_K]; int32_t global_n = 0; + if (use_rk) { + /* every worker's entries into one K-heap of entry ids, sorted, then + * their rows */ + for (uint32_t w = 0; w < nw; w++) { + int32_t hn = ctx.heap_n[w]; + int64_t* hidx = &ctx.heap_idx[(size_t)w * (size_t)k]; + for (int32_t i = 0; i < hn; i++) { + if (global_n < (int32_t)k) { + // cppcheck-suppress objectIndex // heap_idx is an nw*k scratch buffer and hn <= k; cppcheck misreads ray_data's inline payload as a scalar + global_idx[global_n++] = hidx[i]; + if (global_n == (int32_t)k) fpk_rk_heapify(&ctx, global_idx, global_n); + // cppcheck-suppress objectIndex // same nw*k buffer as above + } else if (fpk_rk_ent_cmp(&ctx, hidx[i], global_idx[0]) < 0) { + // cppcheck-suppress objectIndex // same nw*k buffer as above + global_idx[0] = hidx[i]; + fpk_rk_sift_down(&ctx, global_idx, global_n, 0); + } + } + } + for (int32_t i = 1; i < global_n; i++) { /* fpk_sort_final over entries */ + int64_t v = global_idx[i]; + int32_t j = i - 1; + while (j >= 0 && fpk_rk_ent_cmp(&ctx, global_idx[j], v) > 0) { global_idx[j + 1] = global_idx[j]; j--; } + global_idx[j + 1] = v; + } + for (int32_t i = 0; i < global_n; i++) global_idx[i] = rk.rows[global_idx[i]]; + scratch_free(rkr_hdr); scratch_free(rkv_hdr); scratch_free(rkn_hdr); + ctx.rk = NULL; + nw = 0; /* the loop below has nothing to merge */ + } for (uint32_t w = 0; w < nw; w++) { int32_t hn = ctx.heap_n[w]; int64_t* hidx = &ctx.heap_idx[(size_t)w * (size_t)k]; @@ -642,7 +1196,7 @@ ray_t* ray_fused_topk_select(ray_t* tbl, scratch_free(idx_hdr); scratch_free(hn_hdr); - fpk_sort_final(&ctx, global_idx, global_n); + if (!use_rk) fpk_sort_final(&ctx, global_idx, global_n); fpk_unpin_keys(ctx.keys, n_sort_keys); /* no more compares past here */ /* Materialize n_out output columns by gathering rows[global_idx]. */ @@ -650,24 +1204,37 @@ ray_t* ray_fused_topk_select(ray_t* tbl, if (!result || RAY_IS_ERR(result)) { fp_pred_cleanup(&ctx.pred); ray_graph_free(g); - return result ? result : ray_error("oom", NULL); + if (result) ray_error_free(result); + return NULL; /* decline: the unfused path runs (as before) */ } int build_ok = 1; + ray_t* gerr = NULL; /* a failed bind or plain request: returned */ for (uint32_t c = 0; c < n_out; c++) { int64_t cs = out_col_syms[c]; int64_t alias = out_alias_syms ? out_alias_syms[c] : cs; - ray_t* src = ray_table_get_col(tbl, cs); - if (!src) { build_ok = 0; break; } - ray_t* col = gather_by_idx(src, global_idx, global_n); + ray_col_src_t* ssrc = ray_graph_bind_col(g, tbl, cs, &gerr); + if (gerr) { build_ok = 0; break; } + if (!ssrc) { build_ok = 0; break; } + ray_t* col = NULL; + if (ray_col_src_encoded(ssrc)) { + /* generation 2: the output rows' vectors, decoded by range */ + gerr = ray_col_gather_rows(ssrc, global_idx, global_n, &col); + if (gerr) { build_ok = 0; break; } + } else { + ray_t* src = NULL; + gerr = ray_col_src_plain(ssrc, &src); /* ready-only */ + if (gerr) { build_ok = 0; break; } + col = gather_by_idx(src, global_idx, global_n); + } if (!col || RAY_IS_ERR(col)) { build_ok = 0; break; } result = ray_table_add_col(result, alias, col); ray_release(col); } + fp_pred_cleanup(&ctx.pred); /* before the graph: like_dom is borrowed from a bind */ ray_graph_free(g); - fp_pred_cleanup(&ctx.pred); if (!build_ok) { ray_release(result); - return ray_error("schema", NULL); + return gerr; /* NULL: decline, the unfused path runs (as before) */ } return result; } @@ -697,6 +1264,7 @@ typedef struct { int64_t* rows; /* [nw * k] per-worker row ids, in scan order */ int32_t* rows_n; /* [nw] */ _Atomic(int64_t) cutoff; /* forward: rows >= cutoff are out; backward: rows <= cutoff */ + ray_scan_fail_t fail; /* range-read failures, keyed by the chunk's first row */ } ftk_ctx_t; static inline bool ftk_beyond(const ftk_ctx_t* c, int64_t row) { @@ -756,7 +1324,13 @@ static void ftk_task_fn(void* raw, uint32_t worker_id, int64_t start, int64_t en if (lo < 0) lo = 0; } if (ftk_beyond(c, c->from_end ? hi - 1 : lo)) return; + if (ray_scan_fail_skip(&c->fail, lo)) return; + /* Encoded predicate children read by range through the task's scratch; + * a failed read is noted under the chunk's first row and ends the task. */ + fp_scratch_t fs; + fp_scratch_init(&fs); + ray_t* pe = NULL; uint8_t bits[RAY_MORSEL_ELEMS]; bool more = true; /* false: list full, rest of chunk is farther */ if (!c->from_end) { @@ -764,7 +1338,7 @@ static void ftk_task_fn(void* raw, uint32_t worker_id, int64_t start, int64_t en if (ftk_beyond(c, row)) break; int64_t mend = row + RAY_MORSEL_ELEMS; if (mend > hi) mend = hi; - fp_eval_pred(&c->pred, row, mend, bits); + if ((pe = fp_eval_pred_rs(&c->pred, row, mend, bits, &fs))) break; for (int64_t r = 0; r < mend - row && more; r++) if (bits[r]) more = ftk_push(c, my, &n, row + r); row = mend; @@ -774,13 +1348,15 @@ static void ftk_task_fn(void* raw, uint32_t worker_id, int64_t start, int64_t en if (ftk_beyond(c, mend - 1)) break; int64_t row = mend - RAY_MORSEL_ELEMS; if (row < lo) row = lo; - fp_eval_pred(&c->pred, row, mend, bits); + if ((pe = fp_eval_pred_rs(&c->pred, row, mend, bits, &fs))) break; for (int64_t r = mend - row - 1; r >= 0 && more; r--) if (bits[r]) more = ftk_push(c, my, &n, row + r); mend = row; } } + fp_scratch_free(&fs); c->rows_n[worker_id] = n; + if (pe) { ray_scan_fail_note(&c->fail, lo, pe); return; } if (n >= k) ftk_publish(c, my[k - 1]); } @@ -799,12 +1375,11 @@ ray_t* ray_fused_take_select(ray_t* tbl, int64_t nrows = ray_table_nrows(tbl); if (nrows <= 0 || k >= nrows) return NULL; - for (uint32_t c = 0; c < n_out; c++) { - ray_t* col = ray_table_get_col(tbl, out_col_syms[c]); - if (!col) return NULL; - int8_t ot = col->type; - if (RAY_IS_PARTED(ot) || ot == RAY_MAPCOMMON) return NULL; - if (!ray_is_vec(col)) return NULL; + for (uint32_t c = 0; c < n_out; c++) { /* a gate: metadata, no bind */ + ray_col_meta_t om; + if (!ray_table_col_meta(tbl, out_col_syms[c], &om)) return NULL; + if (RAY_IS_PARTED(om.type) || om.type == RAY_MAPCOMMON) return NULL; + if (om.type < RAY_BOOL || om.type > RAY_STR) return NULL; /* not a vector */ } ftk_ctx_t ctx; @@ -813,16 +1388,20 @@ ray_t* ray_fused_take_select(ray_t* tbl, ctx.k = k; ctx.from_end = from_end; atomic_store_explicit(&ctx.cutoff, from_end ? -1 : INT64_MAX, memory_order_relaxed); + ray_scan_fail_init(&ctx.fail); ray_graph_t* g = ray_graph_new(tbl); if (!g) return NULL; ray_op_t* pred_dag = compile_expr_dag(g, where_expr); if (!pred_dag) { ray_graph_free(g); return NULL; } - if (fp_compile_pred(g, pred_dag, tbl, &ctx.pred) != 0) { + ray_t* cerr = NULL; + if (fp_compile_pred(g, pred_dag, tbl, &ctx.pred, &cerr) != 0) { fp_pred_cleanup(&ctx.pred); ray_graph_free(g); - return NULL; + if (!cerr) fpk_count(1); + return cerr; /* NULL: a decline; else the bind failure */ } + fpk_count(0); ray_pool_t* pool = ray_pool_get(); uint32_t nw = pool ? ray_pool_total_workers(pool) : 1; @@ -839,10 +1418,20 @@ ray_t* ray_fused_take_select(ray_t* tbl, } int64_t n_chunks = (nrows + FTK_CHUNK_ROWS - 1) / FTK_CHUNK_ROWS; - if (ray_pool_par_dispatch_ok(pool, n_chunks, 2)) + bool par = ray_pool_par_dispatch_ok(pool, n_chunks, 2); + if (par) ray_pool_dispatch_n(pool, ftk_task_fn, &ctx, (uint32_t)n_chunks); else for (int64_t t = 0; t < n_chunks; t++) ftk_task_fn(&ctx, 0, t, t + 1); + /* A failed range read (or a cancelled dispatch: skipped tasks noted + * nothing) is the query's error, never a partial take. */ + ray_t* ferr = ray_scan_fail_finish(&ctx.fail, par ? pool : NULL); + if (ferr) { + scratch_free(rows_hdr); scratch_free(n_hdr); + fp_pred_cleanup(&ctx.pred); + ray_graph_free(g); + return ferr; + } /* Merge: each list is in scan order; pick the row nearest the scanned * end across lists k times, then present in table order. */ @@ -881,24 +1470,37 @@ ray_t* ray_fused_take_select(ray_t* tbl, if (!result || RAY_IS_ERR(result)) { fp_pred_cleanup(&ctx.pred); ray_graph_free(g); - return result ? result : ray_error("oom", NULL); + if (result) ray_error_free(result); + return NULL; /* decline: the unfused path runs (as before) */ } int build_ok = 1; + ray_t* gerr = NULL; /* a failed bind or plain request: returned */ for (uint32_t c = 0; c < n_out; c++) { int64_t cs = out_col_syms[c]; int64_t alias = out_alias_syms ? out_alias_syms[c] : cs; - ray_t* src = ray_table_get_col(tbl, cs); - if (!src) { build_ok = 0; break; } - ray_t* col = gather_by_idx(src, out, out_n); + ray_col_src_t* ssrc = ray_graph_bind_col(g, tbl, cs, &gerr); + if (gerr) { build_ok = 0; break; } + if (!ssrc) { build_ok = 0; break; } + ray_t* col = NULL; + if (ray_col_src_encoded(ssrc)) { + /* generation 2: the output rows' vectors, decoded by range */ + gerr = ray_col_gather_rows(ssrc, out, out_n, &col); + if (gerr) { build_ok = 0; break; } + } else { + ray_t* src = NULL; + gerr = ray_col_src_plain(ssrc, &src); /* ready-only */ + if (gerr) { build_ok = 0; break; } + col = gather_by_idx(src, out, out_n); + } if (!col || RAY_IS_ERR(col)) { build_ok = 0; break; } result = ray_table_add_col(result, alias, col); ray_release(col); } + fp_pred_cleanup(&ctx.pred); /* before the graph: like_dom is borrowed from a bind */ ray_graph_free(g); - fp_pred_cleanup(&ctx.pred); if (!build_ok) { ray_release(result); - return ray_error("schema", NULL); + return gerr; /* NULL: decline, the unfused path runs (as before) */ } return result; } diff --git a/src/ops/fused_topk.h b/src/ops/fused_topk.h index 4b164ae4a..8c059c513 100644 --- a/src/ops/fused_topk.h +++ b/src/ops/fused_topk.h @@ -81,7 +81,8 @@ int ray_fused_topk_supported(ray_t* where_expr, ray_t* tbl); * serves `asc: key take: K` when the key column carries RAY_ATTR_SORTED * and no nulls (the first K passing rows are then the K smallest, ties in * table order — what the stable sort returns). - * Returns NULL on a shape the path does not take (caller falls back). */ + * Returns NULL on a shape the path does not take (caller falls back), or an + * owned error only when binding a column failed (the query's error). */ ray_t* ray_fused_take_select(ray_t* tbl, ray_t* where_expr, int64_t k, @@ -99,4 +100,12 @@ ray_t* ray_fused_topk_select(ray_t* tbl, const int64_t* out_alias_syms, uint32_t n_out); +/* Test hooks: predicates compiled by the fused selects / declined. */ +void ray_fused_topk_counters(uint64_t* ran, uint64_t* declined); +void ray_fused_topk_counters_reset(void); +/* Test hook: pruning of the last ray_fused_topk_select on a generation-2 + * first key: chunk-slot prunes (one per task fragment of a chunk, so they + * follow the dispatch geometry, not distinct chunks) and pruned morsels. */ +void ray_fused_topk_test_pruned(uint64_t* chunks, uint64_t* vectors); + #endif /* RAY_OPS_FUSED_TOPK_H */ diff --git a/src/ops/graph.c b/src/ops/graph.c index d39eda74c..0a2e42de5 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -21,9 +21,11 @@ * SOFTWARE. */ +#include "ops/colbind.h" #include "graph.h" #include "internal.h" /* EXT_TRAIL, graph_alloc_ext_node_ex */ #include "store/csr.h" +#include "table/table.h" /* ray_table_col_meta */ #include "store/hnsw.h" #include @@ -140,6 +142,7 @@ ray_graph_t* ray_graph_new(ray_t* tbl) { void ray_graph_free(ray_graph_t* g) { if (!g) return; + ray_graph_binds_free(g); if (g->compile_err) { ray_error_free(g->compile_err); g->compile_err = NULL; } /* errors are not refcounted */ /* Unconsumed slice-group hint (error paths / shapes that never @@ -211,6 +214,14 @@ void ray_graph_free(ray_graph_t* g) { * the base type and the wrapper stays where it belongs, on the column. The * executor decides how to read a parted column from the column itself, never * from the node. */ +/* Estimated rows as the graph has always recorded them: a parted wrapper's + * len (its segment count), MAPCOMMON's len (2), else the row count. */ +static uint32_t scan_est_rows(const ray_col_meta_t* m) { + if (RAY_IS_PARTED(m->type)) return (uint32_t)m->n_segs; + if (m->type == RAY_MAPCOMMON) return 2; + return (uint32_t)m->len; +} + static int8_t scan_out_type(int8_t col_type) { return RAY_IS_PARTED(col_type) ? (int8_t)RAY_PARTED_BASETYPE(col_type) : col_type; @@ -229,10 +240,10 @@ ray_op_t* ray_scan(ray_graph_t* g, const char* col_name) { /* Infer output type from the bound table */ if (g->table) { - ray_t* col = ray_table_get_col(g->table, sym_id); - if (col) { - ext->base.out_type = scan_out_type(col->type); - ext->base.est_rows = (uint32_t)col->len; + ray_col_meta_t m; + if (ray_table_col_meta(g->table, sym_id, &m)) { + ext->base.out_type = scan_out_type(m.type); + ext->base.est_rows = scan_est_rows(&m); } } @@ -410,7 +421,8 @@ static ray_op_t* make_binary(ray_graph_t* g, uint16_t opcode, ray_op_t* a, ray_o n->arity = 2; n->in_id[0] = a->id; n->in_id[1] = b->id; - n->out_type = out_type; + int8_t span_out = ray_timespan_binary_type(opcode, a->out_type, b->out_type); + n->out_type = span_out > 0 ? span_out : out_type; n->est_rows = est; return n; } @@ -499,8 +511,9 @@ static int8_t cmp_temporal_type(ray_graph_t* g, ray_op_t* x) { /* A date-partitioned table's key scans as MAPCOMMON over DATE values. */ if (t == RAY_MAPCOMMON && x->opcode == OP_SCAN && g->table) { ray_op_ext_t* ext = find_ext(g, x->id); - ray_t* col = ext ? ray_table_get_col(g->table, ext->sym) : NULL; - if (col && col->type == RAY_MAPCOMMON && col->attrs == RAY_MC_DATE) + ray_col_meta_t m; + if (ext && ray_table_col_meta(g->table, ext->sym, &m) + && m.type == RAY_MAPCOMMON && m.attrs == RAY_MC_DATE) return RAY_DATE; } return 0; @@ -559,7 +572,26 @@ static uint16_t cmp_flip(uint16_t opcode) { } } +/* Called only for an otherwise mismatched SYM pair. String literals carry + * SYM execution metadata but must keep their existing text admission path. */ +static int cmp_is_symbol_value(ray_graph_t* g, ray_op_t* x) { + if (x->opcode != OP_CONST) return 1; + ray_op_ext_t* ext = find_ext(g, x->id); + return !ext || !ext->literal || ext->literal->type != -RAY_STR; +} + static ray_op_t* make_cmp(ray_graph_t* g, uint16_t opcode, ray_op_t* a, ray_op_t* b) { + int8_t a_type = a->out_type, b_type = b->out_type; + if (RAY_IS_PARTED(a_type)) a_type = (int8_t)RAY_PARTED_BASETYPE(a_type); + if (RAY_IS_PARTED(b_type)) b_type = (int8_t)RAY_PARTED_BASETYPE(b_type); + /* Symbol IDs are not numeric values. Let the evaluator apply its + * value-sensitive builtin/null rules to unsupported equality pairs. */ + if ((opcode == OP_EQ || opcode == OP_NE) && + ((a_type == RAY_SYM && b_type != RAY_SYM && b_type != RAY_STR && + cmp_is_symbol_value(g, a)) || + (b_type == RAY_SYM && a_type != RAY_SYM && a_type != RAY_STR && + cmp_is_symbol_value(g, b)))) + return NULL; int8_t ta = cmp_temporal_type(g, a); int8_t tb = cmp_temporal_type(g, b); if (!ta || !tb || ta == tb) return make_binary(g, opcode, a, b, RAY_BOOL); @@ -619,8 +651,8 @@ static bool if_branch_is_list_scan(ray_graph_t* g, ray_op_t* b) { if (!b || b->opcode != OP_SCAN || !g->table) return false; ray_op_ext_t* ext = find_ext(g, b->id); if (!ext) return false; - ray_t* col = ray_table_get_col(g->table, ext->sym); - return col && col->type == RAY_LIST; + ray_col_meta_t m; + return ray_table_col_meta(g->table, ext->sym, &m) && m.type == RAY_LIST; } /* Is node `id` a bare null atom literal (`0N`, `0Nf`, `0Ni`, ...)? */ @@ -817,7 +849,13 @@ ray_op_t* ray_concat(ray_graph_t* g, ray_op_t** args, int n) { * Reduction ops * -------------------------------------------------------------------------- */ -ray_op_t* ray_sum(ray_graph_t* g, ray_op_t* a) { return make_unary(g, OP_SUM, a, (a->out_type == RAY_F64 || a->out_type == RAY_F32) ? RAY_F64 : RAY_I64); } +ray_op_t* ray_sum(ray_graph_t* g, ray_op_t* a) { + int8_t type = a->out_type; + if (RAY_IS_PARTED(type)) type = (int8_t)RAY_PARTED_BASETYPE(type); + int8_t out = type == RAY_F64 || type == RAY_F32 ? RAY_F64 + : type == RAY_TIMESPAN ? RAY_TIMESPAN : RAY_I64; + return make_unary(g, OP_SUM, a, out); +} ray_op_t* ray_prod(ray_graph_t* g, ray_op_t* a) { return make_unary(g, OP_PROD, a, (a->out_type == RAY_F64 || a->out_type == RAY_F32) ? RAY_F64 : RAY_I64); } ray_op_t* ray_all(ray_graph_t* g, ray_op_t* a) { return make_unary(g, OP_ALL, a, RAY_BOOL); } ray_op_t* ray_any(ray_graph_t* g, ray_op_t* a) { return make_unary(g, OP_ANY, a, RAY_BOOL); } @@ -1470,10 +1508,10 @@ ray_op_t* ray_scan_table(ray_graph_t* g, uint16_t table_id, const char* col_name /* Infer output type from the specified table */ ray_t* tbl = g->tables[table_id]; if (tbl) { - ray_t* col = ray_table_get_col(tbl, sym_id); - if (col) { - ext->base.out_type = scan_out_type(col->type); - ext->base.est_rows = (uint32_t)col->len; + ray_col_meta_t m; + if (ray_table_col_meta(tbl, sym_id, &m)) { + ext->base.out_type = scan_out_type(m.type); + ext->base.est_rows = scan_est_rows(&m); } } @@ -1942,7 +1980,59 @@ ray_t* ray_lazy_wrap(ray_graph_t* g, ray_op_t* op) { return h; } +/* ---- Column-reference lazies ---- */ + +typedef struct { ray_t* tbl; int64_t sym; } lazy_colref_t; + +ray_t* ray_lazy_colref(ray_t* tbl, int64_t sym) { + ray_t* h = ray_alloc(sizeof(lazy_colref_t)); + if (!h) return ray_error("oom", NULL); + h->type = RAY_LAZY; + h->attrs = RAY_LAZY_COLREF; + RAY_LAZY_GRAPH(h) = NULL; + RAY_LAZY_OP(h) = NULL; + lazy_colref_t* c = (lazy_colref_t*)ray_data(h); + c->tbl = tbl; + c->sym = sym; + ray_retain(tbl); + return h; +} + +bool ray_lazy_colref_get(ray_t* lazy, ray_t** tbl, int64_t* sym) { + if (!ray_is_lazy(lazy) || !(lazy->attrs & RAY_LAZY_COLREF)) return false; + lazy_colref_t* c = (lazy_colref_t*)ray_data(lazy); + if (!c->tbl) return false; + *tbl = c->tbl; + *sym = c->sym; + return true; +} + +ray_t* ray_lazy_promote(ray_t* lazy) { + ray_t* tbl; int64_t sym; + if (!ray_lazy_colref_get(lazy, &tbl, &sym)) return NULL; + ray_t* nm = ray_sym_str(sym); /* borrowed */ + size_t nl = (nm && !RAY_IS_ERR(nm)) ? ray_str_len(nm) : 0; + char nb[256]; + if (nl == 0 || nl >= sizeof nb || memchr(ray_str_ptr(nm), '\0', nl)) + return ray_error("domain", "lazy column: name not scannable"); + memcpy(nb, ray_str_ptr(nm), nl); + nb[nl] = '\0'; /* ray_scan interns strlen(name) bytes */ + ray_graph_t* g = ray_graph_new(tbl); /* retains tbl */ + if (!g) return ray_error("oom", NULL); + ray_op_t* sc = ray_scan(g, nb); + if (!sc) { ray_graph_free(g); return ray_error("oom", NULL); } + lazy_colref_t* c = (lazy_colref_t*)ray_data(lazy); + c->tbl = NULL; + lazy->attrs &= (uint8_t)~RAY_LAZY_COLREF; + RAY_LAZY_GRAPH(lazy) = g; + RAY_LAZY_OP(lazy) = sc; + ray_release(tbl); /* the graph holds its own */ + return NULL; +} + ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode) { + ray_t* perr = ray_lazy_promote(lazy); + if (perr) return perr; ray_graph_t* g = RAY_LAZY_GRAPH(lazy); ray_op_t* prev = RAY_LAZY_OP(lazy); if (!g || !prev) @@ -2012,6 +2102,8 @@ ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode) { } ray_t* ray_lazy_append_param(ray_t* lazy, uint16_t opcode, int64_t param) { + ray_t* perr = ray_lazy_promote(lazy); + if (perr) return perr; ray_graph_t* g = RAY_LAZY_GRAPH(lazy); ray_op_t* prev = RAY_LAZY_OP(lazy); if (!g || !prev) @@ -2046,6 +2138,14 @@ ray_t* ray_lazy_append_param(ray_t* lazy, uint16_t opcode, int64_t param) { ray_t* ray_lazy_materialize(ray_t* val) { if (!ray_is_lazy(val)) return val; + /* A column reference forces to what (at tbl 'col) returned eagerly. */ + ray_t* ctbl; int64_t csym; + if (ray_lazy_colref_get(val, &ctbl, &csym)) { + ray_t* r = ray_table_col_value(ctbl, csym); + ray_release(val); + return r; + } + ray_graph_t* g = RAY_LAZY_GRAPH(val); ray_op_t* op = RAY_LAZY_OP(val); if (!g || !op) { diff --git a/src/ops/graph_builtin.c b/src/ops/graph_builtin.c index 26d27f725..d8585dfb0 100644 --- a/src/ops/graph_builtin.c +++ b/src/ops/graph_builtin.c @@ -168,8 +168,10 @@ ray_t* ray_graph_build_fn(ray_t** args, int64_t n) { if (weight_sym < 0) return ray_error("type", "graph.build: weight column name must be sym or str, got %s", ray_type_name(args[3]->type)); } - ray_t* src_col = ray_table_get_col(tbl, src_sym); - ray_t* dst_col = ray_table_get_col(tbl, dst_sym); + ray_t* src_col = ray_table_col(tbl, src_sym); + if (src_col && RAY_IS_ERR(src_col)) return src_col; + ray_t* dst_col = ray_table_col(tbl, dst_sym); + if (dst_col && RAY_IS_ERR(dst_col)) return dst_col; if (!src_col || !dst_col) return ray_error("name", NULL); if (!ray_is_vec(src_col) || !ray_is_vec(dst_col)) return ray_error("type", "graph.build: src and dst columns must be vectors, got %s and %s", ray_type_name(src_col->type), ray_type_name(dst_col->type)); if (src_col->len != dst_col->len) return ray_error("length", "graph.build: src and dst columns must have equal length, got %lld and %lld", (long long)src_col->len, (long long)dst_col->len); @@ -209,14 +211,20 @@ ray_t* ray_graph_build_fn(ray_t** args, int64_t n) { n_nodes, n_nodes, true); if (!rel) { ray_release(edges); - return ray_error("oom", NULL); + /* The build gives up on an interrupt (csr.c); report that, not oom. */ + return ray_interrupted() ? ray_error("cancel", "interrupted") + : ray_error("oom", NULL); } /* Optional: attach a weight column. Algorithms that need edge weights * (dijkstra, mst, …) look the column up by sym ID via rel->fwd.props. * The column is referenced by its original name in the user's table. */ if (weight_sym >= 0) { - ray_t* w_col = ray_table_get_col(tbl, weight_sym); + ray_t* w_col = ray_table_col(tbl, weight_sym); + if (w_col && RAY_IS_ERR(w_col)) { + ray_rel_free(rel); ray_release(edges); + return w_col; + } if (!w_col || !ray_is_vec(w_col)) { ray_rel_free(rel); ray_release(edges); return ray_error("name", NULL); diff --git a/src/ops/group.c b/src/ops/group.c index e2c5d5e4c..2a92a27b5 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -22,6 +22,7 @@ */ #include "ops/internal.h" +#include "ops/colbind.h" #include "ops/hash.h" #include "ops/rowsel.h" #include "ops/hll.h" /* approximate count-distinct via HyperLogLog */ @@ -31,6 +32,11 @@ #include "ops/agg_engine.h" /* v2 agg engine routing gate (ray_agg_engine_v2) */ #include "vec/str.h" /* ray_str_t SSO hash/eq for wide STR group keys */ #include "ops/idxop.h" /* RAY_IDX_DICT: group on persisted string codes */ +#include "ops/strdom.h" /* query-wide string domain: generation-2 STR keys */ +#include "store/enccol.h" /* encoded-slot segments, decoded peek */ +#include "store/enceval.h" /* ray_enc_vec_sum: a selected vector's sum from its encoding */ +#include "store/encw.h" /* ray_encw_type_summable: the types whose directory has sums */ +#include "store/part.h" /* ray_null_fill: a ragged stand-in's plain nulls */ #include "core/runtime.h" /* __VM — per-thread group-key cardinality hint */ #include "core/profile.h" @@ -52,7 +58,7 @@ static inline bool group_fp_type(int8_t t) { * unknown type (0: a linear plan without a source vector) is treated as * 64-bit. */ static inline bool group_avg_needs_hi(int8_t t, int64_t nrows) { - return t == RAY_I64 || t == RAY_TIMESTAMP || t == RAY_SYM || t == 0 || + return t == RAY_I64 || t == RAY_TIMESPAN || t == RAY_TIMESTAMP || t == RAY_SYM || t == 0 || nrows >= ((int64_t)1 << 31); } @@ -101,35 +107,49 @@ static inline double group_fp_at(const void* data, int8_t t, int64_t row) { * encoding agg_entry_is_null and the y-side pair-skip can see in an F64 * slot; a raw (double)sentinel cast would read as a huge finite value. * FP cells go through group_fp_at directly: their nulls are NaN already. */ -static inline double group_pack_i64_as_f64(ray_t* col, int64_t row) { - int64_t v = read_col_i64(ray_data(col), row, col->type, col->attrs); - ray_t* src = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; - if (src && ray_vec_may_have_nulls(src)) { - int64_t sent = agg_int_null_sentinel_for(col->type); +/* The cell at `row` of a raw element array of type t (SYM width from + * attrs); may_null is the column's nullability. */ +static inline double group_pack_i64_as_f64_at(const void* data, int64_t row, int8_t t, + uint8_t attrs, bool may_null) { + int64_t v = read_col_i64(data, row, t, attrs); + if (may_null) { + int64_t sent = agg_int_null_sentinel_for(t); if (sent != 0 && v == sent) return (double)NAN; } return (double)v; } +static inline double group_pack_i64_as_f64(ray_t* col, int64_t row) { + ray_t* src = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; + return group_pack_i64_as_f64_at(ray_data(col), row, col->type, col->attrs, + src && ray_vec_may_have_nulls(src)); +} /* Pack the y-side cell of an int×int binary agg (entry keeps i64 slots). * Declared nulls canonicalize to NULL_I64 regardless of the source width so * the accumulator's pair-skip needs no per-agg y-side sentinel plumbing. */ -static inline int64_t group_pack_y_i64(ray_t* col, int64_t row) { - int64_t v = read_col_i64(ray_data(col), row, col->type, col->attrs); - ray_t* src = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; - if (src && ray_vec_may_have_nulls(src)) { - int64_t sent = agg_int_null_sentinel_for(col->type); +static inline int64_t group_pack_y_i64_at(const void* data, int64_t row, int8_t t, + uint8_t attrs, bool may_null) { + int64_t v = read_col_i64(data, row, t, attrs); + if (may_null) { + int64_t sent = agg_int_null_sentinel_for(t); if (sent != 0 && v == sent) return NULL_I64; } return v; } +static inline int64_t group_pack_y_i64(ray_t* col, int64_t row) { + ray_t* src = (col->attrs & RAY_ATTR_SLICE) ? col->slice_parent : col; + return group_pack_y_i64_at(ray_data(col), row, col->type, col->attrs, + src && ray_vec_may_have_nulls(src)); +} -/* Monotonic count of exec_group_per_partition entries (the streaming parted - * GROUP kernel). Bumped ONCE at the kernel entry — O(1) per query, never - * per-row, so it does not violate the "instrumentation never costs O(data)" - * rule. Counts every entry regardless of success/cancel/NULL-return. Atomic - * because group exec may run on worker threads. Surfaced via - * ray_group_perpart_runs() and (.sys.mem)'s "group-perpart-runs" entry. */ +/* Monotonic count of results served by exec_group_per_partition (the + * streaming parted GROUP kernel). Bumped ONCE per result — O(1) per query, + * never per-row, so it does not violate the "instrumentation never costs + * O(data)" rule. A run that bails (error, cancel, NULL return) is not + * counted: the caller then answers from the concat path, and a test pinning + * the route must see the difference. Atomic because group exec may run on + * worker threads. Surfaced via ray_group_perpart_runs() and (.sys.mem)'s + * "group-perpart-runs" entry. */ static _Atomic(int64_t) ray_group_perpart_runs_ctr = 0; int64_t ray_group_perpart_runs(void) { @@ -137,6 +157,49 @@ int64_t ray_group_perpart_runs(void) { memory_order_relaxed); } +/* Monotonic count of exec_group_per_partition runs that returned their + * merged result (the concat fallback's NULL and errors excluded). Test + * hook, O(1) per query. */ +static _Atomic(int64_t) ray_group_perpart_done_ctr = 0; + +int64_t ray_group_perpart_done(void) { + return atomic_load_explicit(&ray_group_perpart_done_ctr, memory_order_relaxed); +} + +/* Monotonic count of the per-partition non-null count slots built as a SUM + * of a not-null indicator (one per nullable AVG/VAR/DEV input per + * partition); a null-free input keeps the row count and adds none. Test + * hook, O(1) per slot. */ +static _Atomic(int64_t) ray_group_perpart_nn_ctr = 0; + +int64_t ray_group_perpart_nn_slots(void) { + return atomic_load_explicit(&ray_group_perpart_nn_ctr, memory_order_relaxed); +} + +/* Per-partition unordered takes answered from grp_first_keys_scan's keys. */ +static _Atomic(int64_t) ray_group_firstkeys_runs_ctr = 0; +int64_t ray_group_firstkeys_runs(void) { + return atomic_load_explicit(&ray_group_firstkeys_runs_ctr, memory_order_relaxed); +} + +/* Entries of exec_group_parted's in-place concat (group_seg_stream_ok). */ +static _Atomic(int64_t) ray_group_segstream_runs_ctr = 0; +int64_t ray_group_segstream_runs(void) { + return atomic_load_explicit(&ray_group_segstream_runs_ctr, memory_order_relaxed); +} + +/* Bytes of null fill built for ragged partitions' stand-ins (grp_synth_plain). */ +static _Atomic(int64_t) ray_group_null_fill_bytes_ctr = 0; +int64_t ray_group_null_fill_bytes(void) { + return atomic_load_explicit(&ray_group_null_fill_bytes_ctr, memory_order_relaxed); +} + +/* Rows of staged keys the direct-array prescan walked (minmax_piece). */ +static _Atomic(int64_t) ray_group_minmax_staged_rows_ctr = 0; +int64_t ray_group_test_minmax_staged_rows(void) { + return atomic_load_explicit(&ray_group_minmax_staged_rows_ctr, memory_order_relaxed); +} + /* ============================================================================ * Reduction execution * ============================================================================ */ @@ -189,6 +252,7 @@ static inline bool sym_lex_lt(struct ray_sym_domain_s* dom, a < raw.count && b < raw.count) { pa = ray_sym_domain_raw_str(&raw, a, &la); pb = ray_sym_domain_raw_str(&raw, b, &lb); + if (!pa || !pb) return a < b; /* corrupt file: reported by the evaluation */ } else { ray_t* sa = ray_sym_domain_str(dom, a); ray_t* sb = ray_sym_domain_str(dom, b); @@ -582,11 +646,18 @@ static ray_t* agg_wide_reduce(ray_t* input, uint16_t op, REDUCE_SYM_EXTREME(input, base, start, end, acc, idx, dom, 1, 1, WANT_MIN); \ } while (0) -static void reduce_range(ray_t* input, int64_t start, int64_t end, - reduce_acc_t* acc, bool has_nulls, - const int64_t* idx, uint16_t opcode) { - void* base = ray_data(input); - switch (input->type) { +/* The reduction kernel over raw elements: `base` is row 0 of a column of + * `type`. `input` is read only by the SYM arm (cell width, domain) and by + * the BOOL / U8 bitmap null test, which never runs: those types are + * non-nullable. A raw caller (ray_reduce_src) passes input NULL and never + * a SYM column. */ +static void reduce_range_raw(int8_t type, uint8_t attrs, const void* cbase, + struct ray_sym_domain_s* dom, ray_t* input, + int64_t start, int64_t end, reduce_acc_t* acc, + bool has_nulls, const int64_t* idx, uint16_t opcode) { + (void)attrs; + void* base = (void*)cbase; /* the loops only read */ + switch (type) { case RAY_BOOL: case RAY_U8: DISPATCH_BITMAP_I_OPCODE(uint8_t, input, base, start, end, acc, has_nulls, idx, opcode); break; @@ -596,7 +667,7 @@ static void reduce_range(ray_t* input, int64_t start, int64_t end, case RAY_I32: case RAY_DATE: case RAY_TIME: DISPATCH_I_OPCODE(int32_t, NULL_I32, base, start, end, acc, has_nulls, idx, opcode); break; - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: DISPATCH_I_OPCODE(int64_t, NULL_I64, base, start, end, acc, has_nulls, idx, opcode); break; case RAY_F32: @@ -610,7 +681,6 @@ static void reduce_range(ray_t* input, int64_t start, int64_t end, * order is by string content (matches asc/desc), not by intern * id. Same 4-way dispatch to eliminate the per-element * null/idx branches. */ - struct ray_sym_domain_s* dom = ray_sym_vec_domain(input); if (opcode == OP_MIN) DISPATCH_SYM_EXTREME(input, base, start, end, acc, has_nulls, idx, dom, 1); @@ -623,6 +693,14 @@ static void reduce_range(ray_t* input, int64_t start, int64_t end, } } +static void reduce_range(ray_t* input, int64_t start, int64_t end, + reduce_acc_t* acc, bool has_nulls, + const int64_t* idx, uint16_t opcode) { + reduce_range_raw(input->type, input->attrs, ray_data(input), + input->type == RAY_SYM ? ray_sym_vec_domain(input) : NULL, input, + start, end, acc, has_nulls, idx, opcode); +} + /* Keyless reductions over a pooled input run in chunks whose shape depends * only on the row count: one partial per chunk, folded in chunk order. The * association order of a float sum, the zero a min/max keeps among equal @@ -894,7 +972,7 @@ static void cd_hist_fn(void* ctx, uint32_t worker_id, uint64_t p = (h ^ (h >> 33)) & p_mask; hist[p]++; } - } else if (in_type == RAY_I64 || in_type == RAY_TIMESTAMP) { + } else if (in_type == RAY_I64 || in_type == RAY_TIMESPAN || in_type == RAY_TIMESTAMP) { const int64_t* d = (const int64_t*)base; for (int64_t i = start; i < end; i++) { int64_t val = d[i]; @@ -993,7 +1071,7 @@ static void cd_scatter_fn(void* ctx, uint32_t worker_id, uint64_t p = (h ^ (h >> 33)) & p_mask; out[cur[p]++] = val; } - } else if (in_type == RAY_I64 || in_type == RAY_TIMESTAMP) { + } else if (in_type == RAY_I64 || in_type == RAY_TIMESPAN || in_type == RAY_TIMESTAMP) { const int64_t* d = (const int64_t*)base; SCATTER_BODY(d[i]) } else if (in_type == RAY_I32 || in_type == RAY_DATE || in_type == RAY_TIME) { @@ -1159,7 +1237,7 @@ ray_t* exec_count_distinct(ray_graph_t* g, ray_op_t* op, ray_t* input) { switch (in_type) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: - case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: break; case RAY_STR: @@ -1216,10 +1294,10 @@ ray_t* exec_count_distinct(ray_graph_t* g, ray_op_t* op, ray_t* input) { if (grain <= 0) grain = 8192; int64_t n_tasks_64 = (len + grain - 1) / grain; if (n_tasks_64 <= 0) n_tasks_64 = 1; - /* MAX_RING_CAP guards against pathological len; if we'd exceed it, - * fall back to the sequential kernel — the cap is high enough that - * this only fires on absurd inputs. */ - if (n_tasks_64 > (1u << 16)) { + /* Tasks past the ring run in further rounds; the only bound on the task + * count is the uint32 ray_pool_dispatch_n takes (a vector that long + * cannot exist, so the sequential kernel below is a formality). */ + if (n_tasks_64 > UINT32_MAX) { int64_t cnt = cd_seq_count(in_type, input->attrs, base, len); if (cnt < 0) return ray_error("oom", NULL); return ray_i64(cnt); @@ -1388,7 +1466,7 @@ static void dv_scatter_fn(void* ctx, uint32_t worker_id, out[c] = val; rid[c] = i; } - } else if (x->type == RAY_I64 || x->type == RAY_TIMESTAMP) { + } else if (x->type == RAY_I64 || x->type == RAY_TIMESPAN || x->type == RAY_TIMESTAMP) { const int64_t* d = (const int64_t*)base; DV_SCATTER_BODY(d[i]) } else if (x->type == RAY_I32 || x->type == RAY_DATE || x->type == RAY_TIME) { @@ -1471,7 +1549,7 @@ ray_t* distinct_radix_first_ids(ray_t* input) { switch (in_type) { case RAY_I16: case RAY_I32: case RAY_I64: - case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: break; case RAY_F64: /* The kernel canonicalizes every NaN to one value. The eager @@ -1497,7 +1575,7 @@ ray_t* distinct_radix_first_ids(ray_t* input) { int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; if (grain <= 0) grain = 8192; int64_t n_tasks_64 = (len + grain - 1) / grain; - if (n_tasks_64 <= 0 || n_tasks_64 > (1u << 16)) return NULL; + if (n_tasks_64 <= 0 || n_tasks_64 > UINT32_MAX) return NULL; /* dispatch_n takes a uint32 */ uint32_t n_tasks = (uint32_t)n_tasks_64; void* base = ray_data(input); @@ -1669,15 +1747,16 @@ typedef struct { uint64_t p_mask; /* P - 1, P = number of partitions */ /* Pass 1 outputs / pass 2 inputs. Per-task counters: each worker * writes to its own slice of hist[task_id * P] / cursor[task_id * P] - * so there's no atomic contention. task_id is derived from `start` - * via the dispatch grain (matches ray_pool_dispatch's tasking). + * so there's no atomic contention. task_id is start / grain, both + * passes dispatched at the one geometry ray_pool_dispatch_geometry + * returned. * * Earlier comment claimed P=64 atomic-cursor contention was * negligible — it isn't. Q11's parallel speedup was 1.2× (not 28×) * because the per-row atomic_fetch_add on cursor[h & p_mask] in * cdpg_scat_fn serialised through the partition cache lines. */ - int64_t grain; /* task grain (matches pool dispatch) */ - int64_t n_tasks; /* number of tasks in the dispatch */ + int64_t grain; /* task grain (ray_pool_dispatch_geometry) */ + int64_t n_tasks; /* number of tasks in each dispatch */ int64_t* hist; /* [n_tasks * P] — per-task counts */ int64_t* cursor; /* [n_tasks * P] — per-task scat cursor */ int64_t* part_off; /* P + 1, prefix offsets */ @@ -1709,7 +1788,7 @@ static void cdpg_hist_fn(void* ctx_, uint32_t worker_id, * scat_fn computes the SAME task_id and reads cursor[task_id*P+p] * we wrote here. No atomics: each task owns its row. */ int64_t task_id = start / x->grain; - int64_t* my_hist = &x->hist[task_id * (p_mask + 1)]; + int64_t* my_hist = &x->hist[task_id * (int64_t)(p_mask + 1)]; for (int64_t r = start; r < end; r++) { int64_t gid = x->row_gid[r]; if (gid < 0 || gid >= x->n_groups) continue; @@ -1730,7 +1809,7 @@ static void cdpg_scat_fn(void* ctx_, uint32_t worker_id, * orchestrator from per-task hist counts so writes are guaranteed * non-overlapping across tasks within the same partition. */ int64_t task_id = start / x->grain; - int64_t* my_cur = &x->cursor[task_id * (p_mask + 1)]; + int64_t* my_cur = &x->cursor[task_id * (int64_t)(p_mask + 1)]; for (int64_t r = start; r < end; r++) { int64_t gid = x->row_gid[r]; if (gid < 0 || gid >= x->n_groups) continue; @@ -1833,16 +1912,15 @@ static ray_t* count_distinct_per_group_parallel( if (P > 256) return NULL; - /* Match ray_pool_dispatch's task layout so task_id derived from - * `start / grain` inside the worker fn matches the row range the - * dispatch hands out. Mirrors pool.c's TASK_GRAIN (8 morsels of - * 1024 rows each) and MAX_RING_CAP (65536) clamping logic. */ - int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; - int64_t n_tasks = (n_rows + grain - 1) / grain; - if (n_tasks > 65536) { - n_tasks = 65536; - grain = (n_rows + n_tasks - 1) / n_tasks; - } + /* Counters per dispatch task, sized from the geometry the pool takes + * (its clamp included), computed once: both passes dispatch at that + * grain, which then needs no further clamp (a ring never shrinks), so + * `start / grain` names the same task in each. */ + uint32_t geo_tasks; + int64_t grain; + ray_pool_dispatch_geometry(pool, n_rows, (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS, + &geo_tasks, &grain); + int64_t n_tasks = geo_tasks; ctx.grain = grain; ctx.n_tasks = n_tasks; @@ -1851,7 +1929,7 @@ static ray_t* count_distinct_per_group_parallel( ctx.hist = (int64_t*)scratch_calloc(&hist_hdr, (size_t)n_tasks * (size_t)P * sizeof(int64_t)); if (!ctx.hist) { return NULL; } - ray_pool_dispatch(pool, cdpg_hist_fn, &ctx, n_rows); + ray_pool_dispatch_grain(pool, cdpg_hist_fn, &ctx, n_rows, grain); /* Compute global per-partition totals + prefix offsets, then per-task * scatter cursors. Layout invariant: tasks within a partition write @@ -1897,7 +1975,7 @@ static ray_t* count_distinct_per_group_parallel( return NULL; } if (total > 0) - ray_pool_dispatch(pool, cdpg_scat_fn, &ctx, n_rows); + ray_pool_dispatch_grain(pool, cdpg_scat_fn, &ctx, n_rows, grain); /* Pass 3: per-partition dedup; partition is keyed on gid via * CDPG_PART_HASH so each gid is owned by exactly one task — odata @@ -2018,7 +2096,7 @@ ray_t* ray_count_distinct_per_group(ray_t* src, const int64_t* row_gid, switch (in_type) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: - case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: break; default: @@ -2254,7 +2332,7 @@ static inline double med_read_as_f64(const void* base, int8_t t, int64_t row) { case RAY_I32: { int32_t v; memcpy(&v, (const char*)base + (size_t)row * 4, 4); return (double)v; } case RAY_DATE: case RAY_TIME: { int32_t v; memcpy(&v, (const char*)base + (size_t)row * 4, 4); return (double)v; } - case RAY_TIMESTAMP: { int64_t v; memcpy(&v, (const char*)base + (size_t)row * 8, 8); return (double)v; } + case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t v; memcpy(&v, (const char*)base + (size_t)row * 8, 8); return (double)v; } case RAY_I16: { int16_t v; memcpy(&v, (const char*)base + (size_t)row * 2, 2); return (double)v; } case RAY_BOOL: case RAY_U8: return (double)((const uint8_t*)base)[row]; default: return 0.0; @@ -2271,7 +2349,7 @@ static inline bool med_is_null(const void* base, int8_t t, int64_t row) { case RAY_I32: return ((const int32_t*)base)[row] == NULL_I32; case RAY_DATE: case RAY_TIME: return ((const int32_t*)base)[row] == NULL_I32; - case RAY_TIMESTAMP: return ((const int64_t*)base)[row] == NULL_I64; + case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)base)[row] == NULL_I64; case RAY_I16: return ((const int16_t*)base)[row] == NULL_I16; case RAY_BOOL: case RAY_U8: return false; /* non-nullable */ default: return false; @@ -2581,7 +2659,7 @@ static ray_t* rank_per_group_buf(ray_t* src, int8_t t = src->type; if (t != RAY_F64 && t != RAY_F32 && t != RAY_I64 && t != RAY_I32 && t != RAY_I16 && t != RAY_U8 && t != RAY_BOOL && t != RAY_DATE && - t != RAY_TIME && t != RAY_TIMESTAMP) return NULL; + t != RAY_TIME && t != RAY_TIMESTAMP && t != RAY_TIMESPAN) return NULL; if (use_quantile && (!__builtin_isfinite(q) || q < 0.0 || q > 1.0)) return ray_error("domain", "quantile: probability out of range"); @@ -2694,7 +2772,7 @@ static inline uint64_t mode_scalar_key(ray_t* src, int64_t row) { case RAY_SYM: return (uint64_t)ray_read_sym(base, row, src->type, src->attrs); case RAY_I64: - case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t v; memcpy(&v, (const char*)base + (size_t)row * 8, 8); return (uint64_t)v; @@ -3113,7 +3191,7 @@ ray_t* ray_mode_per_group_buf(ray_t* src, const int64_t* rows, if (!src || RAY_IS_ERR(src) || ng < 0) return NULL; switch (src->type) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: - case RAY_F32: case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_F32: case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_GUID: case RAY_SYM: case RAY_STR: break; default: return NULL; } @@ -3204,7 +3282,7 @@ static inline double topk_read_f64(const void* base, int64_t row) { /* Read src element as int64 for integer source types. */ static inline int64_t topk_read_i64(const void* base, int8_t t, int64_t row) { switch (t) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t v; memcpy(&v, (const char*)base + (size_t)row * 8, 8); return v; } case RAY_I32: case RAY_DATE: case RAY_TIME: { int32_t v; memcpy(&v, (const char*)base + (size_t)row * 4, 4); return (int64_t)v; } @@ -3434,7 +3512,7 @@ static void topk_rows_sift(ray_t* src, int64_t* heap, int64_t n, int64_t root, b case RAY_BOOL: case RAY_U8: TOPK_SIFT_NATIVE(uint8_t); case RAY_I16: TOPK_SIFT_NATIVE(int16_t); case RAY_I32: case RAY_DATE: case RAY_TIME: TOPK_SIFT_NATIVE(int32_t); - case RAY_I64: case RAY_TIMESTAMP: TOPK_SIFT_NATIVE(int64_t); + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: TOPK_SIFT_NATIVE(int64_t); case RAY_F32: TOPK_SIFT_NATIVE(float); case RAY_F64: TOPK_SIFT_NATIVE(double); default: break; @@ -3679,7 +3757,7 @@ static void topk_chunks_run(void* raw, uint32_t wid, int64_t start, int64_t end) case RAY_I16: TOPK_SCAN_NATIVE(int16_t, value != NULL_I16); break; case RAY_I32: case RAY_DATE: case RAY_TIME: TOPK_SCAN_NATIVE(int32_t, value != NULL_I32); break; - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: TOPK_SCAN_NATIVE(int64_t, value != NULL_I64); break; case RAY_F32: TOPK_SCAN_NATIVE(float, value == value); break; case RAY_F64: TOPK_SCAN_NATIVE(double, value == value); break; @@ -3788,7 +3866,7 @@ static void topk_select_count(void* raw, uint32_t wid, int64_t start, int64_t en case RAY_BOOL: case RAY_U8: TOPK_SELECT_COUNT(uint8_t); case RAY_I16: TOPK_SELECT_COUNT(int16_t); case RAY_I32: case RAY_DATE: case RAY_TIME: TOPK_SELECT_COUNT(int32_t); - case RAY_I64: case RAY_TIMESTAMP: TOPK_SELECT_COUNT(int64_t); + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: TOPK_SELECT_COUNT(int64_t); case RAY_F32: TOPK_SELECT_COUNT(float); case RAY_F64: TOPK_SELECT_COUNT(double); default: break; @@ -3833,7 +3911,7 @@ static void topk_select_scatter(void* raw, uint32_t wid, int64_t start, int64_t case RAY_BOOL: case RAY_U8: TOPK_SELECT_SCATTER(uint8_t); case RAY_I16: TOPK_SELECT_SCATTER(int16_t); case RAY_I32: case RAY_DATE: case RAY_TIME: TOPK_SELECT_SCATTER(int32_t); - case RAY_I64: case RAY_TIMESTAMP: TOPK_SELECT_SCATTER(int64_t); + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: TOPK_SELECT_SCATTER(int64_t); case RAY_F32: TOPK_SELECT_SCATTER(float); case RAY_F64: TOPK_SELECT_SCATTER(double); default: break; @@ -4154,7 +4232,8 @@ static ray_t* reduction_i64_result(int64_t val, int8_t out_type, ray_t* src) { case RAY_BOOL: return ray_bool((bool)val); case RAY_DATE: return ray_date((int32_t)val); case RAY_TIME: return ray_time(val); - case RAY_TIMESTAMP: return ray_timestamp(val); + case RAY_TIMESPAN: return ray_timespan(val); + case RAY_TIMESTAMP: return ray_timestamp(val); case RAY_I32: return ray_i32((int32_t)val); case RAY_I16: return ray_i16((int16_t)val); case RAY_U8: return ray_u8((uint8_t)val); @@ -4163,9 +4242,9 @@ static ray_t* reduction_i64_result(int64_t val, int8_t out_type, ray_t* src) { } } -static ray_t* reduction_extreme_result(ray_op_t* op, int8_t in_type, bool found, +static ray_t* reduction_extreme_result(int8_t op_out_type, int8_t in_type, bool found, double fval, int64_t ival, ray_t* src) { - int8_t out_type = op->out_type ? op->out_type : in_type; + int8_t out_type = op_out_type ? op_out_type : in_type; if (!found) return ray_typed_null(-out_type); /* Single-null float model: min/max of finite inputs is finite, but guard * against an ±Inf init sentinel surfacing as a value. */ @@ -4174,7 +4253,53 @@ static ray_t* reduction_extreme_result(ray_op_t* op, int8_t in_type, bool found, return reduction_i64_result(ival, out_type, out_type == RAY_SYM ? src : NULL); } +/* The result of reduction `opcode` (op_out_type: the op's out type, 0 for + * the input's) from the merged accumulator over scan_n rows of in_type. + * `input` is read only for SYM results (the domain of the cell id). */ +static ray_t* reduce_result(uint16_t opcode, int8_t op_out_type, int8_t in_type, + const reduce_acc_t* m, int64_t scan_n, ray_t* input) { + bool fp = in_type == RAY_F64 || in_type == RAY_F32; + ray_t* sym_src = in_type == RAY_SYM ? input : NULL; + switch (opcode) { + case OP_SUM: return fp ? ray_f64(ray_f64_fin(m->sum_f)) : (in_type == RAY_TIME ? ray_time(m->sum_i) : ray_i64(m->sum_i)); + case OP_PROD: return fp ? ray_f64(ray_f64_fin(m->prod_f)) : ray_i64(m->prod_i); + case OP_ALL: return ray_bool(m->zero_count == 0); + case OP_ANY: return ray_bool(m->cnt > m->zero_count); + case OP_MIN: return reduction_extreme_result(op_out_type, in_type, m->cnt > 0, m->min_f, m->min_i, input); + case OP_MAX: return reduction_extreme_result(op_out_type, in_type, m->cnt > 0, m->max_f, m->max_i, input); + /* COUNT returns total length including nulls — matches ray_count_fn's + * "count all elements" semantics, not SQL's COUNT(col) non-null count. */ + case OP_COUNT: return ray_i64(scan_n); + case OP_AVG: return m->cnt > 0 ? ray_f64(ray_f64_fin(fp ? m->sum_f / m->cnt : ray_i128_to_f64(m->sum_hi, (uint64_t)m->sum_i) / m->cnt)) : ray_typed_null(-RAY_F64); + case OP_FIRST: return m->has_first ? (group_fp_type(in_type) ? ray_f64(m->first_f) : reduction_i64_result(m->first_i, in_type, sym_src)) : ray_typed_null(-(op_out_type ? op_out_type : in_type)); + case OP_LAST: return m->has_first ? (group_fp_type(in_type) ? ray_f64(m->last_f) : reduction_i64_result(m->last_i, in_type, sym_src)) : ray_typed_null(-(op_out_type ? op_out_type : in_type)); + case OP_VAR: case OP_VAR_POP: + case OP_STDDEV: case OP_STDDEV_POP: { + bool insufficient = (opcode == OP_VAR || opcode == OP_STDDEV) ? m->cnt <= 1 : m->cnt <= 0; + if (insufficient) return ray_typed_null(-RAY_F64); + double mean, var_pop; + if (fp) { mean = m->sum_f / m->cnt; var_pop = m->sum_sq_f / m->cnt - mean * mean; } + else { mean = m->sum_d / m->cnt; var_pop = (double)m->sum_sq_i / m->cnt - mean * mean; } + if (var_pop < 0) var_pop = 0; + double val; + if (opcode == OP_VAR_POP) val = var_pop; + else if (opcode == OP_VAR) val = var_pop * m->cnt / (m->cnt - 1); + else if (opcode == OP_STDDEV_POP) val = sqrt(var_pop); + else val = sqrt(var_pop * m->cnt / (m->cnt - 1)); + return ray_f64(ray_f64_fin(val)); + } + default: return ray_error("nyi", NULL); + } +} + ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { + if (input && input->type == RAY_TIMESPAN) { + if (op->opcode == OP_SUM) return ray_sum_fn(input); + if (op->opcode == OP_AVG) return ray_avg_fn(input); + if (op->opcode == OP_MIN) return ray_min_fn(input); + if (op->opcode == OP_MAX) return ray_max_fn(input); + } + if (!input || RAY_IS_ERR(input)) return input; /* TABLE input: COUNT returns row count, others need a column */ @@ -4341,36 +4466,273 @@ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input) { } if (sel_idx_block) ray_release(sel_idx_block); - switch (op->opcode) { - case OP_SUM: return (in_type == RAY_F64 || in_type == RAY_F32) ? ray_f64(ray_f64_fin(acc.sum_f)) : (in_type == RAY_TIME ? ray_time(acc.sum_i) : ray_i64(acc.sum_i)); - case OP_PROD: return (in_type == RAY_F64 || in_type == RAY_F32) ? ray_f64(ray_f64_fin(acc.prod_f)) : ray_i64(acc.prod_i); - case OP_ALL: return ray_bool(acc.zero_count == 0); - case OP_ANY: return ray_bool(acc.cnt > acc.zero_count); - case OP_MIN: return reduction_extreme_result(op, in_type, acc.cnt > 0, acc.min_f, acc.min_i, input); - case OP_MAX: return reduction_extreme_result(op, in_type, acc.cnt > 0, acc.max_f, acc.max_i, input); - /* COUNT returns total length including nulls — matches ray_count_fn's - * "count all elements" semantics, not SQL's COUNT(col) non-null count. */ - case OP_COUNT: return ray_i64(scan_n); - case OP_AVG: return acc.cnt > 0 ? ray_f64(ray_f64_fin((in_type == RAY_F64 || in_type == RAY_F32) ? acc.sum_f / acc.cnt : ray_i128_to_f64(acc.sum_hi, (uint64_t)acc.sum_i) / acc.cnt)) : ray_typed_null(-RAY_F64); - case OP_FIRST: return acc.has_first ? (group_fp_type(in_type) ? ray_f64(acc.first_f) : reduction_i64_result(acc.first_i, in_type, in_type == RAY_SYM ? input : NULL)) : ray_typed_null(-(op->out_type ? op->out_type : in_type)); - case OP_LAST: return acc.has_first ? (group_fp_type(in_type) ? ray_f64(acc.last_f) : reduction_i64_result(acc.last_i, in_type, in_type == RAY_SYM ? input : NULL)) : ray_typed_null(-(op->out_type ? op->out_type : in_type)); - case OP_VAR: case OP_VAR_POP: - case OP_STDDEV: case OP_STDDEV_POP: { - bool insufficient = (op->opcode == OP_VAR || op->opcode == OP_STDDEV) ? acc.cnt <= 1 : acc.cnt <= 0; - if (insufficient) return ray_typed_null(-RAY_F64); - double mean, var_pop; - if (in_type == RAY_F64 || in_type == RAY_F32) { mean = acc.sum_f / acc.cnt; var_pop = acc.sum_sq_f / acc.cnt - mean * mean; } - else { mean = acc.sum_d / acc.cnt; var_pop = (double)acc.sum_sq_i / acc.cnt - mean * mean; } - if (var_pop < 0) var_pop = 0; - double val; - if (op->opcode == OP_VAR_POP) val = var_pop; - else if (op->opcode == OP_VAR) val = var_pop * acc.cnt / (acc.cnt - 1); - else if (op->opcode == OP_STDDEV_POP) val = sqrt(var_pop); - else val = sqrt(var_pop * acc.cnt / (acc.cnt - 1)); - return ray_f64(ray_f64_fin(val)); + return reduce_result(op->opcode, op->out_type, in_type, &acc, scan_n, input); +} + +/* ---- Reductions over a bound encoded source (P2) ---- + * The answer exec_reduction gives over the source's materialization, read + * by range: the rows fall into the chunks exec_reduction folds + * (red_chunk_rows: their shape depends on the row count only), each chunk + * walked piece by piece (R-WALK) into its own partial, and the partials + * folded in chunk order. REDUCE_LOOP_I / _F accumulate every row straight + * into the accumulator's fields (no per-call partial), so the pieces of a + * chunk add in the same order as one call over the chunk: float sums, + * squares and products are the same bits as the plain loop's, at any + * worker count (#744). */ + +typedef struct { + ray_col_src_t* src; + const void* base; /* the source read in place, or NULL (by range) */ + reduce_acc_t* parts; /* [red_n_chunks(n)] one partial per chunk */ + bool has_nulls; + uint16_t opcode; + int64_t lo; /* first row of the walked range (a parted segment's) */ + int64_t n; /* rows walked */ + int64_t rows; /* red_chunk_rows(n) */ + ray_scan_fail_t fail; +} par_reduce_src_ctx_t; + +typedef struct { const par_reduce_src_ctx_t* c; reduce_acc_t* acc; } reduce_piece_ctx_t; + +static void reduce_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + reduce_piece_ctx_t* x = (reduce_piece_ctx_t*)ctx; + reduce_range_raw(x->c->src->type, p[0].attrs, p[0].data, NULL, NULL, 0, e - b, + x->acc, x->c->has_nulls, NULL, x->c->opcode); +} + +/* Chunk k of the walked rows into c->parts[k]. */ +static void red_src_chunk_run(par_reduce_src_ctx_t* c, uint32_t wid, int64_t k) { + reduce_acc_t* acc = &c->parts[k]; + reduce_acc_init(acc); + int64_t start = k * c->rows; + int64_t end = c->n - start > c->rows ? start + c->rows : c->n; + if (ray_scan_fail_skip(&c->fail, start)) return; + ray_col_src_t* srcs[1] = { c->src }; + const void* plain[1] = { c->base }; + reduce_piece_ctx_t x = { c, acc }; + ray_t* err = ray_col_walk(srcs, plain, 1, c->lo + start, c->lo + end, false, &x, wid, reduce_piece); + if (err) ray_scan_fail_note(&c->fail, start, err); +} + +static void par_reduce_src_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + par_reduce_src_ctx_t* c = (par_reduce_src_ctx_t*)ctx; + for (int64_t k = start; k < end; k++) red_src_chunk_run(c, wid, k); +} + +static bool reduce_src_type(int8_t t) { + return t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_F32 || t == RAY_F64; +} + +/* The atom exec_reduction's first / last short-circuit builds from row i + * of view v. */ +static ray_t* src_row_value(int8_t t, const ray_col_range_t* v, int64_t i) { + if (t == RAY_F64) return ray_f64(((const double*)v->data)[i]); + if (t == RAY_F32) return ray_f64((double)((const float*)v->data)[i]); + return reduction_i64_result(read_col_i64(v->data, i, t, v->attrs), t, NULL); +} + +/* First (last) value of a served source. skip_nulls: the first (last) + * non-null row, exec_reduction's short-circuit (a typed null when there is + * none); else row 0 (len - 1) itself, ray_first_fn / ray_last_fn's + * collection_elem (a null row is a typed null). Nulls are told by the + * sentinel only when the source may hold nulls, as the vector's HAS_NULLS + * gates them. Last reads blocks of RAY_MORSEL_ELEMS rows backwards, each + * forwards view by view, so every vector is decoded once. An owned atom or + * error. */ +static ray_t* reduce_src_edge(ray_col_src_t* src, bool last, bool skip_nulls) { + int8_t t = src->type; + int64_t len = src->len; + bool mn = src->may_null; + if (len <= 0) return ray_typed_null(-t); + ray_col_cursor_t cur; + ray_col_cursor_init(&cur, src); + const ray_col_range_t* v; + ray_t* out = NULL; + if (!skip_nulls) { + int64_t r = last ? len - 1 : 0; + out = ray_col_cursor_at(&cur, r, &v); + if (!out) { + int64_t i = r - v->start; + out = (mn && ray_raw_is_null(t, v->attrs, v->data, i)) ? ray_typed_null(-t) : src_row_value(t, v, i); + } + } else if (!last) { + for (int64_t r = 0; r < len && !out; ) { + if ((out = ray_col_cursor_at(&cur, r, &v)) != NULL) break; + int64_t ve = v->start + v->n; + for (; r < ve; r++) + if (!mn || !ray_raw_is_null(t, v->attrs, v->data, r - v->start)) { + out = src_row_value(t, v, r - v->start); + break; + } } - default: return ray_error("nyi", NULL); + } else { + for (int64_t hi = len; hi > 0 && !out; ) { + int64_t lo = ((hi - 1) / RAY_MORSEL_ELEMS) * RAY_MORSEL_ELEMS; + ray_t* found = NULL; + for (int64_t r = lo; r < hi; ) { + ray_t* err = ray_col_cursor_at(&cur, r, &v); + if (err) { if (found) ray_release(found); found = err; break; } + int64_t ve = v->start + v->n < hi ? v->start + v->n : hi; + for (int64_t q = ve - 1; q >= r; q--) + if (!mn || !ray_raw_is_null(t, v->attrs, v->data, q - v->start)) { + if (found) ray_release(found); + found = src_row_value(t, v, q - v->start); + break; + } + r = ve; + } + out = found; + hi = lo; + } + } + ray_col_cursor_free(&cur); + return out ? out : ray_typed_null(-t); +} + +/* Reduce rows [lo, lo + n) of the source by range reads into *out + * (overwritten): the chunks of exec_reduction, folded in chunk order (see + * red_chunk_rows), so the result is the same at any worker count. NULL or + * an owned error. */ +static ray_t* reduce_src_walk(ray_col_src_t* src, int64_t lo, int64_t n, uint16_t opcode, reduce_acc_t* out) { + int8_t t = src->type; + reduce_acc_init(out); + if (n <= 0) return NULL; + int64_t n_chunks = red_n_chunks(n); + ray_t* parts_hdr; + reduce_acc_t* parts = (reduce_acc_t*)scratch_calloc(&parts_hdr, (size_t)n_chunks * sizeof(reduce_acc_t)); + if (!parts) return ray_error("oom", NULL); + par_reduce_src_ctx_t ctx = { .src = src, .base = ray_col_src_base(src), .parts = parts, + .has_nulls = src->may_null, .opcode = opcode, .lo = lo, + .n = n, .rows = red_chunk_rows(n) }; + ray_scan_fail_init(&ctx.fail); + ray_col_src_advise(src, lo, lo + n); + ray_pool_t* pool = ray_pool_get(); + bool par = n_chunks > 1 && ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + if (par) ray_pool_dispatch_n(pool, par_reduce_src_fn, &ctx, (uint32_t)n_chunks); + else par_reduce_src_fn(&ctx, 0, 0, n_chunks); + ray_t* err = ray_scan_fail_finish(&ctx.fail, par ? pool : NULL); + if (err) { scratch_free(parts_hdr); return err; } + *out = parts[0]; + for (int64_t k = 1; k < n_chunks; k++) reduce_merge(out, &parts[k], t, NULL, opcode); + scratch_free(parts_hdr); + return NULL; +} + +/* A parted source's integer or temporal SUM / AVG / MIN / MAX into *merged: + * every single-file stored generation-2 segment from its directory totals + * (what reduce_range would accumulate over its rows), every synthetic + * all-null segment as no rows, and each run of other segments by range + * reads; folded in segment order. *done false when the source has no + * segment table to walk (the caller reads the whole source). NULL or an + * owned error. */ +static ray_t* reduce_src_parted(ray_col_src_t* src, uint16_t opcode, reduce_acc_t* merged, bool* done) { + int8_t t = src->type; + int64_t n; + ray_t** segs; + const int64_t* off; + ray_t* err = NULL; + if (!ray_col_src_parted_segs(src, &n, &segs, &off, &err)) return err; + int64_t run = -1; /* first row of the pending plain run */ + for (int64_t i = 0; i <= n; i++) { + ray_enc_col_totals_t z; + bool dir = false, empty = false; + if (i < n) { + ray_t* sg = segs[i]; + int64_t sl = off[i + 1] - off[i]; + ray_enccol_t* e = sg && sg->type == RAY_ENCCOL ? ray_enccol_of(sg) : NULL; + if (sl <= 0) empty = true; + else if (e && e->kind == RAY_ENCCOL_SINGLE && e->len == sl && e->type == t) { + /* a nullable stand-in is all null: no rows, no extremes; a BOOL / U8 one is + * non-null zeros (ray_null_fill) and is read like a plain segment */ + if (e->synthetic) empty = t != RAY_BOOL && t != RAY_U8; + else dir = ray_dir_seg_totals(sg, opcode, &z); + } + } + if (i < n && !dir && !empty) { if (run < 0) run = off[i]; continue; } + if (run >= 0) { /* flush the plain run before this segment */ + reduce_acc_t acc; + if ((err = reduce_src_walk(src, run, off[i] - run, opcode, &acc)) != NULL) return err; + reduce_merge(merged, &acc, t, NULL, opcode); + run = -1; + } + if (dir) { + reduce_acc_t acc; + reduce_acc_init(&acc); + acc.sum_i = (int64_t)z.sum_wrapped; + acc.sum_hi = z.sum_hi; + acc.cnt = z.nonnull; + if (z.nonnull > 0) { acc.min_i = z.min_i; acc.max_i = z.max_i; } + reduce_merge(merged, &acc, t, NULL, opcode); + } + } + *done = true; + return NULL; +} + +ray_t* ray_reduce_src(ray_col_src_t* src, uint16_t opcode, int8_t out_type) { + int8_t t = src->type; + int64_t len = src->len; + if (opcode == OP_COUNT) return ray_i64(len); /* the length, whatever the type */ + if (!reduce_src_type(t)) return NULL; + switch (opcode) { + case OP_SUM: case OP_PROD: case OP_ALL: case OP_ANY: case OP_MIN: case OP_MAX: + case OP_AVG: case OP_FIRST: case OP_LAST: + case OP_VAR: case OP_VAR_POP: case OP_STDDEV: case OP_STDDEV_POP: break; + default: return NULL; + } + /* BOOL / U8 nulls would be a bitmap the raw kernel cannot read; the + * producers reject them, this keeps the plain path if one appears. */ + if ((t == RAY_BOOL || t == RAY_U8) && src->may_null) return NULL; + /* Finding C3: generation 0 answers a CHUNK_ZONE column's sum / avg / + * min / max from its zone; the directory gives the same numbers. For + * an integer type they are exec_reduction's too. A float extreme is + * taken only where exec_reduction would build the same atom: an F64 + * result (F32 under an F64 out type) that is finite (exec_reduction + * maps an infinite extreme to null, the zone does not). */ + bool fl = t == RAY_F32 || t == RAY_F64; + bool mm_ok = t == RAY_F32 ? out_type == RAY_F64 : (out_type == 0 || out_type == t); + bool dir_ok = opcode == OP_SUM || opcode == OP_AVG || + ((opcode == OP_MIN || opcode == OP_MAX) && mm_ok); + ray_t* dir = dir_ok ? ray_dir_answer(src->obj, opcode) : NULL; + if (dir && fl && dir->type == -RAY_F64 && !RAY_ATOM_IS_NULL(dir) && !(fabs(dir->f64) <= DBL_MAX)) { + ray_release(dir); + dir = NULL; + } + if (dir) return dir; + if (opcode == OP_FIRST || opcode == OP_LAST) + return reduce_src_edge(src, opcode == OP_LAST, true); + reduce_acc_t merged; + reduce_acc_init(&merged); + ray_t* err; + if (dir_ok && !fl && src->parted && ray_col_src_encoded(src)) { + /* integer and temporal SUM / AVG / MIN / MAX of a parted source: + * each encoded segment from its directory, the rest by range reads */ + bool done = false; + err = reduce_src_parted(src, opcode, &merged, &done); + if (err) return err; + if (!done) err = reduce_src_walk(src, 0, len, opcode, &merged); + } else { + err = reduce_src_walk(src, 0, len, opcode, &merged); } + if (err) return err; + return reduce_result(opcode, out_type, t, &merged, len, NULL); +} + +ray_t* exec_reduction_src(ray_graph_t* g, ray_op_t* op, ray_col_src_t* src) { + (void)g; + return ray_reduce_src(src, op->opcode, op->out_type); +} + +/* ray_first_fn / ray_last_fn of a bound source whose type they read with + * collection_elem: row 0 (len - 1) itself, nulls included. */ +ray_t* ray_reduce_src_elem(ray_col_src_t* src, bool last) { + int8_t t = src->type; + if (!(t == RAY_I32 || t == RAY_I16 || t == RAY_BOOL || t == RAY_U8 || + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP)) return NULL; + if ((t == RAY_BOOL || t == RAY_U8) && src->may_null) return NULL; + return reduce_src_edge(src, last, false); } /* ============================================================================ @@ -4539,7 +4901,7 @@ bool ght_compute_layout(ght_layout_t* out, uint32_t n_keys, uint32_t n_aggs, switch (key_types[k]) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: case RAY_SYM: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: break; default: packed = false; @@ -4973,7 +5335,8 @@ static inline uint64_t ght_hash_lanes(const int64_t* lane, uint32_t lanes) { } /* Gather one key column's lanes for a batch of rows. Semantically - * `dst[j] = read_col_i64(data, rows[j], type, attrs)` for every j — the type + * `dst[j] = read_col_i64(data, rows[j] - base, type, attrs)` for every j + * (`data` holds row `base` first: a piece of a range read, else 0) — the type * (and, for SYM, the stored-id-width) dispatch is hoisted OUT of the row loop, * which is the whole point: read_col_i64's switch lowers to a jump table, so * the row-major builder pays one indirect jump per key per row and mispredicts @@ -4982,35 +5345,35 @@ static inline uint64_t ght_hash_lanes(const int64_t* lane, uint32_t lanes) { * MUST stay bit-identical to read_col_i64 (ops/internal.h) — narrow signed * types sign-extend, SYM ids zero-extend. */ static inline void group_keys_gather(int64_t* dst, const void* data, - const int64_t* rows, uint32_t m, + const int64_t* rows, int64_t base, uint32_t m, int8_t type, uint8_t attrs) { switch (type) { - case RAY_I64: case RAY_TIMESTAMP: - for (uint32_t j = 0; j < m; j++) dst[j] = ((const int64_t*)data)[rows[j]]; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: + for (uint32_t j = 0; j < m; j++) dst[j] = ((const int64_t*)data)[rows[j] - base]; return; case RAY_SYM: switch (attrs & RAY_SYM_W_MASK) { case RAY_SYM_W8: - for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint8_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint8_t*)data)[rows[j] - base]; return; case RAY_SYM_W16: - for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint16_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint16_t*)data)[rows[j] - base]; return; case RAY_SYM_W32: - for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint32_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint32_t*)data)[rows[j] - base]; return; default: - for (uint32_t j = 0; j < m; j++) dst[j] = ((const int64_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = ((const int64_t*)data)[rows[j] - base]; return; } case RAY_I32: case RAY_DATE: case RAY_TIME: - for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const int32_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const int32_t*)data)[rows[j] - base]; return; case RAY_I16: - for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const int16_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const int16_t*)data)[rows[j] - base]; return; default: /* RAY_BOOL, RAY_U8 */ - for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint8_t*)data)[rows[j]]; + for (uint32_t j = 0; j < m; j++) dst[j] = (int64_t)((const uint8_t*)data)[rows[j] - base]; return; } } @@ -5023,7 +5386,7 @@ static inline void group_keys_gather_seq(int64_t* dst, const void* data, int64_t row0, uint32_t m, int8_t type, uint8_t attrs) { switch (type) { - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* p = (const int64_t*)data + row0; for (uint32_t j = 0; j < m; j++) dst[j] = p[j]; return; @@ -5895,22 +6258,331 @@ static inline bool group_rowsel_pass(ray_t* sel, int64_t row) { return false; } -void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, - uint8_t* key_attrs, ray_t** key_vecs, ray_t** agg_vecs, - ray_t** agg_vecs2, - uint8_t* agg_strlen, - ray_t* rowsel, - int64_t start, int64_t end, - const int64_t* match_idx) { +/* ---- Range reads of the fat-entry builders (radix phase 1, its v2 + * sibling, the holistic reprobe, the serial fallback; R-WALK / R-SPARSE) ---- + * + * A builder context carries a grp_rr_t. A plain one (staged false) reads + * whole columns and leaves the rest unused, so a table with no encoded slot + * runs today's loops. A staged one runs its body once per piece of a walk + * over its sources: the keys, then the inputs, then the y-sides + * (n_keys + 2 * n_aggs; NULL for a source the entries do not read: COUNT, a + * holistic input, a missing y-side). The keys of a group-by with a wide key + * (STR, GUID, LIST) are plain and stay unwalked (keys_walked false): their + * arms store and compare source rows, so they read the whole columns. */ +typedef struct { + ray_col_src_t** srcs; + const void** plain; /* [n_src] a plain source's base, NULL for a staged one */ + uint32_t n_src; + uint32_t n_keys, n_aggs; + const int8_t* key_types; + ray_scan_fail_t* fail; + bool staged; + bool keys_walked; +} grp_rr_t; + +/* What a builder body reads rows through: the whole columns in a plain + * context (bases 0), one piece in a staged one. Keys are read at + * row - key_base, inputs at row - row_base; rows stay absolute everywhere + * else (selection, entry row ids, FIRST/LAST order). */ +typedef struct { + void* const* key_data; + const uint8_t* key_attrs; /* the pieces' SYM widths when walked */ + int64_t key_base; + bool key_raw; /* null tests read the key pieces' sentinels */ + const void* const* agg_ptrs; /* [n_aggs] input pieces at row_base; NULL: the + * inputs are read whole through agg_vecs */ + const void* const* agg_ptrs2; /* y-sides */ + const uint8_t* agg_attrs; /* the input pieces' SYM widths */ + const uint8_t* agg_attrs2; + int64_t row_base; +} grp_view_t; + +static inline grp_view_t grp_view_whole(void* const* key_data, const uint8_t* key_attrs) { + return (grp_view_t){ .key_data = key_data, .key_attrs = key_attrs }; +} + +/* Key k (type t) is null at `row`: from the piece's sentinel when the keys + * are walked, else from the column (ray_vec_is_null). */ +static inline bool grp_key_null(ray_t* kv, const grp_view_t* v, uint32_t k, int8_t t, int64_t row) { + return v->key_raw ? ray_raw_is_null(t, v->key_attrs[k], v->key_data[k], row - v->key_base) + : ray_vec_is_null(kv, row); +} + +static inline int64_t sym_strlen_raw(const void* data, int64_t row, uint8_t attrs, + struct ray_sym_domain_s* dom); + +/* Pack one row's aggregate input values into an entry's value slots: the + * one packer of every fat-entry builder. Slot indices come from the layout + * (agg_val_slot), never a running counter: holistic aggs and the valueless + * OP_COUNT carry -1 and pack nothing. agg_vecs may be NULL (pure-COUNT + * layouts). In a staged view the cells come from the pieces at + * row - row_base with the pieces' SYM widths; agg_vecs[a] (the input or its + * stand-in) gives the type, nullability and SYM domain. */ +static void ght_pack_aggs_piece(const ght_layout_t* ly, ray_t* const* agg_vecs, + ray_t* const* agg_vecs2, const uint8_t* agg_strlen, + const grp_view_t* v, int64_t* ev, int64_t row); + +/* The plain arm stays inline in every builder's row loop (today's code); + * the piece arm is out of line. */ +RAY_INLINE void ght_pack_aggs(const ght_layout_t* ly, ray_t* const* agg_vecs, + ray_t* const* agg_vecs2, const uint8_t* agg_strlen, + const grp_view_t* v, int64_t* ev, int64_t row) { + const uint8_t* const aflags = ly->agg_flags; + uint16_t na = ly->n_aggs; + if (!v->agg_ptrs) { /* plain: whole columns at `row` */ + for (uint32_t a = 0; a < na; a++) { + uint8_t af = aflags[a]; + int8_t vs = ly->agg_val_slot[a]; + if (vs < 0) continue; + uint8_t vi = (uint8_t)vs; + ray_t* ac = agg_vecs ? agg_vecs[a] : NULL; + if (!ac) continue; + if (agg_strlen && agg_strlen[a]) + ev[vi] = group_strlen_at(ac, row); + else if (af & GHT_AF_F64) { + double d = group_fp_type(ac->type) + ? group_fp_at(ray_data(ac), ac->type, row) + : group_pack_i64_as_f64(ac, row); + memcpy(&ev[vi], &d, sizeof(d)); + } + else + ev[vi] = read_col_i64(ray_data(ac), row, ac->type, ac->attrs); + vi++; + /* Binary aggregator: the y-side value in the next slot. + * Non-F64 pairs keep i64 slots (group_pack_y_i64 + * canonicalizes nulls). */ + if ((af & GHT_AF_BINARY) && agg_vecs2 && agg_vecs2[a]) { + ray_t* ay = agg_vecs2[a]; + if (af & GHT_AF_F64) { + double d = group_fp_type(ay->type) + ? group_fp_at(ray_data(ay), ay->type, row) + : group_pack_i64_as_f64(ay, row); + memcpy(&ev[vi], &d, sizeof(d)); + } + else + ev[vi] = group_pack_y_i64(ay, row); + vi++; + } + } + return; + } + ght_pack_aggs_piece(ly, agg_vecs, agg_vecs2, agg_strlen, v, ev, row); +} + +static void ght_pack_aggs_piece(const ght_layout_t* ly, ray_t* const* agg_vecs, + ray_t* const* agg_vecs2, const uint8_t* agg_strlen, + const grp_view_t* v, int64_t* ev, int64_t row) { + const uint8_t* const aflags = ly->agg_flags; + uint16_t na = ly->n_aggs; + const int64_t r = row - v->row_base; + for (uint32_t a = 0; a < na; a++) { + uint8_t af = aflags[a]; + int8_t vs = ly->agg_val_slot[a]; + if (vs < 0) continue; + uint8_t vi = (uint8_t)vs; + ray_t* ac = agg_vecs ? agg_vecs[a] : NULL; + if (!ac) continue; + const void* xd = v->agg_ptrs[a]; + if (agg_strlen && agg_strlen[a]) + ev[vi] = ac->type == RAY_STR ? (int64_t)((const ray_str_t*)xd)[r].len + : sym_strlen_raw(xd, r, v->agg_attrs[a], ray_sym_vec_domain(ac)); + else if (af & GHT_AF_F64) { + double d = group_fp_type(ac->type) + ? group_fp_at(xd, ac->type, r) + : group_pack_i64_as_f64_at(xd, r, ac->type, v->agg_attrs[a], + ray_vec_may_have_nulls(ac)); + memcpy(&ev[vi], &d, sizeof(d)); + } + else + ev[vi] = read_col_i64(xd, r, ac->type, v->agg_attrs[a]); + vi++; + if ((af & GHT_AF_BINARY) && agg_vecs2 && agg_vecs2[a]) { + ray_t* ay = agg_vecs2[a]; + const void* yd = v->agg_ptrs2[a]; + if (af & GHT_AF_F64) { + double d = group_fp_type(ay->type) ? group_fp_at(yd, ay->type, r) + : group_pack_i64_as_f64_at(yd, r, ay->type, v->agg_attrs2[a], + ray_vec_may_have_nulls(ay)); + memcpy(&ev[vi], &d, sizeof(d)); + } + else + ev[vi] = group_pack_y_i64_at(yd, r, ay->type, v->agg_attrs2[a], + ray_vec_may_have_nulls(ay)); + vi++; + } + } +} + +static ray_t* group_sel_walk(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + ray_t* rowsel, int64_t start, int64_t end, + void* ctx, uint32_t wid, ray_col_piece_fn fn); + +/* R-SPARSE over the ascending rows idx[i0, i1): one cursor per staged + * source for the call (each touched vector is decoded once). Rows that + * every source's current view covers form one run, handed to fn as the + * index range [ib, ie) with each piece positioned at row b = idx[ib]. + * NULL or an owned error (fn is not called again after an error). */ +typedef void (*group_idx_piece_fn)(void* ctx, uint32_t wid, int64_t ib, int64_t ie, + int64_t b, const ray_col_piece_t* p); +static ray_t* group_idx_walk(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + const int64_t* idx, int64_t i0, int64_t i1, + void* ctx, uint32_t wid, group_idx_piece_fn fn) { + if (i0 >= i1) return NULL; + enum { IDX_WALK_STACK = 16 }; + ray_col_cursor_t cst[IDX_WALK_STACK]; + ray_col_piece_t pst[IDX_WALK_STACK]; + ray_col_cursor_t* cur = cst; + ray_col_piece_t* pc = pst; + if (n > IDX_WALK_STACK) { + cur = ray_calloc_raw((size_t)n * sizeof *cur); + pc = ray_calloc_raw((size_t)n * sizeof *pc); + if (!cur || !pc) { ray_free_raw(cur); ray_free_raw(pc); return ray_error("oom", "scan walk"); } + } + for (uint32_t s = 0; s < n; s++) { + pc[s] = (ray_col_piece_t){ 0 }; + if (!srcs[s]) continue; + pc[s].attrs = srcs[s]->attrs; + pc[s].may_null = srcs[s]->may_null; + pc[s].dom = srcs[s]->dom; + if (!plain[s]) ray_col_cursor_init(&cur[s], srcs[s]); + } + ray_t* err = NULL; + for (int64_t i = i0; i < i1 && !err; ) { + int64_t b = idx[i], e = INT64_MAX; + for (uint32_t s = 0; s < n; s++) { + ray_col_src_t* src = srcs[s]; + if (!src) continue; + if (plain[s]) { pc[s].data = (const char*)plain[s] + (size_t)b * ray_col_src_esz(src); continue; } + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(&cur[s], b, &v)) != NULL) break; + uint8_t vesz = ray_sym_elem_size(v->type, v->attrs); + pc[s].data = (const char*)v->data + (size_t)(b - v->start) * vesz; + pc[s].attrs = v->attrs; pc[s].may_null = v->may_null; + pc[s].str_pool = v->str_pool; pc[s].dom = v->dom; + if (v->start + v->n < e) e = v->start + v->n; + } + if (err) break; + int64_t j = i + 1; + while (j < i1 && idx[j] < e) j++; + fn(ctx, wid, i, j, b, pc); + i = j; + } + for (uint32_t s = 0; s < n; s++) + if (srcs[s] && !plain[s]) ray_col_cursor_free(&cur[s]); + if (cur != cst) { ray_free_raw(cur); ray_free_raw(pc); } + return err; +} + +/* A builder body over rows [start, end) (indices into match_idx when the + * context has one) read through view v. */ +typedef void (*grp_body_fn)(void* ctx, const grp_view_t* v, uint32_t wid, int64_t start, int64_t end); +typedef struct { + void* ctx; + grp_body_fn body; + const grp_rr_t* rr; + const grp_view_t* whole; /* the context's whole-column view (unwalked keys) */ +} grp_piece_ctx_t; + +/* The view of one piece positioned at row b; the arrays live in the caller. */ +static void grp_view_bind(const grp_piece_ctx_t* pc, int64_t b, const ray_col_piece_t* p, + void** kd, uint8_t* kat, const void** ap, const void** ap2, + uint8_t* at, uint8_t* at2, grp_view_t* v) { + const grp_rr_t* rr = pc->rr; + uint32_t nk = rr->n_keys, na = rr->n_aggs; + *v = *pc->whole; + if (rr->keys_walked) { + for (uint32_t k = 0; k < nk; k++) { + kd[k] = (void*)p[k].data; + kat[k] = rr->key_types[k] == RAY_SYM ? p[k].attrs : pc->whole->key_attrs[k]; + } + v->key_data = kd; + v->key_attrs = kat; + v->key_base = b; + v->key_raw = true; + } + for (uint32_t a = 0; a < na; a++) { + ap[a] = p[nk + a].data; /* NULL for an input without a source */ + at[a] = p[nk + a].attrs; + ap2[a] = p[nk + na + a].data; + at2[a] = p[nk + na + a].attrs; + } + v->agg_ptrs = ap; + v->agg_ptrs2 = ap2; + v->agg_attrs = at; + v->agg_attrs2 = at2; + v->row_base = b; +} + +#define GRP_PIECE_VIEW(pc, b, p, v) \ + uint32_t nk_ = (pc)->rr->n_keys ? (pc)->rr->n_keys : 1; \ + uint32_t na_ = (pc)->rr->n_aggs ? (pc)->rr->n_aggs : 1; \ + void* kd_[nk_]; uint8_t kat_[nk_]; \ + const void* ap_[na_]; const void* ap2_[na_]; uint8_t at_[na_]; uint8_t at2_[na_]; \ + grp_view_t v; \ + grp_view_bind((pc), (b), (p), kd_, kat_, ap_, ap2_, at_, at2_, &v) + +static void grp_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + grp_piece_ctx_t* pc = (grp_piece_ctx_t*)ctx; + GRP_PIECE_VIEW(pc, b, p, v); + pc->body(pc->ctx, &v, wid, b, e); +} + +static void grp_idx_piece(void* ctx, uint32_t wid, int64_t ib, int64_t ie, int64_t b, + const ray_col_piece_t* p) { + grp_piece_ctx_t* pc = (grp_piece_ctx_t*)ctx; + GRP_PIECE_VIEW(pc, b, p, v); + pc->body(pc->ctx, &v, wid, ib, ie); +} +#undef GRP_PIECE_VIEW + +/* The driver of every builder: a plain context runs `body` over [start, + * end) through its whole-column view, exactly today's loop; a staged one + * by pieces (R-WALK, morsels a selection rejects whole are not read; or + * R-SPARSE over the ascending rows idx[start, end)). A range error is + * noted keyed by the task's first row (R-FAIL). */ +static void grp_run(void* ctx, grp_body_fn body, const grp_view_t* whole, const grp_rr_t* rr, + ray_t* rowsel, const int64_t* idx, uint32_t wid, int64_t start, int64_t end) { + if (!rr->staged) { body(ctx, whole, wid, start, end); return; } + if (ray_scan_fail_skip(rr->fail, start)) return; + grp_piece_ctx_t pc = { ctx, body, rr, whole }; + ray_t* err = idx ? group_idx_walk(rr->srcs, rr->plain, rr->n_src, idx, start, end, &pc, wid, grp_idx_piece) + : group_sel_walk(rr->srcs, rr->plain, rr->n_src, rowsel, start, end, &pc, wid, grp_piece); + if (err) ray_scan_fail_note(rr->fail, start, err); +} + +/* The serial builder's context (group_rows_range). */ +typedef struct { + group_ht_t* ht; + void** key_data; + int8_t* key_types; + ray_t** key_vecs; + ray_t** agg_vecs; + ray_t** agg_vecs2; + uint8_t* agg_strlen; + ray_t* rowsel; + const int64_t* match_idx; + grp_rr_t rr; +} group_rows_ctx_t; + +static void group_rows_body(void* vctx, const grp_view_t* v, uint32_t wid, + int64_t start, int64_t end) { + (void)wid; + group_rows_ctx_t* c = (group_rows_ctx_t*)vctx; + group_ht_t* ht = c->ht; + int8_t* key_types = c->key_types; + ray_t** key_vecs = c->key_vecs; + ray_t* rowsel = c->rowsel; + const int64_t* match_idx = c->match_idx; + void* const* key_data = v->key_data; + const uint8_t* key_attrs = v->key_attrs; + const int64_t kb = v->key_base; /* keys are read at row - kb */ const ght_layout_t* ly = &ht->layout; uint16_t nk = ly->n_keys; - uint16_t na = ly->n_aggs; /* Hoisted per-key / per-agg flag bases + scalar shape guards (cut-3 * register-promotion doctrine): the common int/sym-key numeric path has * both guards 0, so the wide/inline/holistic per-slot branches short- * circuit on a register test without touching the flag arrays. */ const uint8_t* const kflags = ly->key_flags; - const uint8_t* const aflags = ly->agg_flags; uint8_t wide_any = ly->any_wide_key; uint32_t mask = ht->ht_cap - 1; /* Stack buffer for one entry: hash + (nk+1) key slots + nv agg_vals @@ -5939,7 +6611,7 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, /* Wire the HT's key_data + key_pool tables so probe/rehash can * resolve wide keys (GUID bytes / STR descriptors) via the source columns. */ - if (wide_any) { group_ht_set_key_data(ht, key_data); group_ht_set_key_pool(ht, key_vecs); } + if (wide_any) { group_ht_set_key_data(ht, c->key_data); group_ht_set_key_pool(ht, key_vecs); } for (int64_t i = start; i < end; i++) { /* Cancellation checkpoint every 65536 rows — ~150 polls on a @@ -5951,8 +6623,9 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, uint64_t h = 0; int64_t* ek = (int64_t*)(ebuf + 8); if (ly->any_inline_str) { - h = inline_build_keys(ly, key_types, key_data, key_attrs, ht->key_pool, - key_vecs, any_nullable, row, ebuf + 8); + /* inline STR: a wide-key layout, whose keys are whole columns */ + h = inline_build_keys(ly, key_types, c->key_data, key_attrs, + ht->key_pool, key_vecs, any_nullable, row, ebuf + 8); } else { /* Non-inline keys are 8 B each, so the null-mask words start at ek[nk] * (== ebuf+8+key_off[nk]); write bit k into word k>>6 in place. */ @@ -5967,11 +6640,11 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, * stay in lockstep with hash_keys_inline (rehash/merge/lookup). */ for (uint32_t k = 0; k < nk; k++) { if (__builtin_expect(any_nullable && ray_key_may_be_null(key_vecs[k]) - && ray_vec_is_null(key_vecs[k], row), 0)) { + && grp_key_null(key_vecs[k], v, k, key_types[k], row), 0)) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); ek[k] = 0; } else { - ek[k] = read_col_i64(key_data[k], row, key_types[k], key_attrs[k]); + ek[k] = read_col_i64(key_data[k], row - kb, key_types[k], key_attrs[k]); } } h = ght_hash_lanes(ek, (uint32_t)nk + null_words); @@ -5980,7 +6653,7 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, int8_t t = key_types[k]; uint64_t kh; bool is_null = any_nullable && ray_key_may_be_null(key_vecs[k]) - && ray_vec_is_null(key_vecs[k], row); + && grp_key_null(key_vecs[k], v, k, t, row); if (is_null) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); ek[k] = 0; /* canonical null value — real 0 differs via null mask */ @@ -5989,15 +6662,15 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, /* Wide key: store source row index, hash the actual bytes * (GUID fixed / STR SSO via pool). */ ek[k] = row; - kh = wide_key_hash_at(ly, k, key_data, ht->key_pool, row); + kh = wide_key_hash_at(ly, k, c->key_data, ht->key_pool, row); } else if (t == RAY_F64) { /* -0.0 -> +0.0 before BOTH the store and the hash. */ - int64_t kv = group_key_f64_bits(key_data[k], row); + int64_t kv = group_key_f64_bits(key_data[k], row - kb); double dv; memcpy(&dv, &kv, 8); ek[k] = kv; kh = ray_hash_f64(dv); } else { - int64_t kv = read_col_i64(key_data[k], row, t, key_attrs[k]); + int64_t kv = read_col_i64(key_data[k], row - kb, t, key_attrs[k]); ek[k] = kv; kh = ray_hash_i64(kv); } @@ -6008,43 +6681,8 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, } *(uint64_t*)ebuf = h; - int64_t* ev = (int64_t*)(ebuf + 8 + (size_t)ly->key_region); - for (uint32_t a = 0; a < na; a++) { - uint8_t af = aflags[a]; - /* Destination slot comes from the layout, never a running counter: - * aggs that reserve no value slot (holistic OP_MEDIAN &c., and - * valueless OP_COUNT) carry agg_val_slot == -1, and a running - * counter would silently shift every later agg's slot. */ - int8_t vs = ly->agg_val_slot[a]; - if (vs < 0) continue; - uint8_t vi = (uint8_t)vs; - ray_t* ac = agg_vecs[a]; - if (!ac) continue; - if (agg_strlen && agg_strlen[a]) - ev[vi] = group_strlen_at(ac, row); - else if (af & GHT_AF_F64) { - double v = group_fp_type(ac->type) - ? group_fp_at(ray_data(ac), ac->type, row) - : group_pack_i64_as_f64(ac, row); - memcpy(&ev[vi], &v, sizeof(v)); - } - else - ev[vi] = read_col_i64(ray_data(ac), row, ac->type, ac->attrs); - vi++; - /* Binary aggregator: pack y after x in the same entry. */ - if ((af & GHT_AF_BINARY) && agg_vecs2 && agg_vecs2[a]) { - ray_t* ay = agg_vecs2[a]; - if (af & GHT_AF_F64) { - double v = group_fp_type(ay->type) - ? group_fp_at(ray_data(ay), ay->type, row) - : group_pack_i64_as_f64(ay, row); - memcpy(&ev[vi], &v, sizeof(v)); - } - else - ev[vi] = group_pack_y_i64(ay, row); - vi++; - } - } + ght_pack_aggs(ly, c->agg_vecs, c->agg_vecs2, c->agg_strlen, v, + (int64_t*)(ebuf + 8 + (size_t)ly->key_region), row); /* Tail slot: source row index for FIRST/LAST tie-breaking. Same * layout as the radix path's entries so accum_from_entry can read * it from the same offset. */ @@ -6055,6 +6693,22 @@ void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, scratch_free(ebuf_hdr); /* NULL (inline ebuf) → no-op */ } +void group_rows_range(group_ht_t* ht, void** key_data, int8_t* key_types, + uint8_t* key_attrs, ray_t** key_vecs, ray_t** agg_vecs, + ray_t** agg_vecs2, + uint8_t* agg_strlen, + ray_t* rowsel, + int64_t start, int64_t end, + const int64_t* match_idx) { + group_rows_ctx_t c = { + .ht = ht, .key_data = key_data, .key_types = key_types, .key_vecs = key_vecs, + .agg_vecs = agg_vecs, .agg_vecs2 = agg_vecs2, .agg_strlen = agg_strlen, + .rowsel = rowsel, .match_idx = match_idx, + }; + grp_view_t v = grp_view_whole(key_data, key_attrs); + group_rows_body(&c, &v, 0, start, end); +} + /* ============================================================================ * Radix-partitioned parallel group-by * @@ -6084,6 +6738,7 @@ static inline uint32_t group_radix_part(uint64_t hash, uint32_t n_parts) { typedef struct { int64_t value; + int64_t first; /* the group's earliest source row: the tie-break */ uint32_t part; uint32_t gid; } group_topn_item_t; @@ -6094,61 +6749,58 @@ typedef struct { * its cost is O(total groups) — tens of millions of rows on a high-cardinality * 100M-row group-by, and it ran on one thread. * - * `TOPN_BETTER(desc, a, b)` is the single ordering predicate: for `desc` a - * larger value is better, otherwise a smaller one. The heap keeps the WORST - * retained item at the root (min-heap when desc), so the invariant is - * "parent is not better than child" and a swap is needed exactly when the - * parent IS better. */ + * `TOPN_BETTER(desc, a, b)` orders two values: for `desc` a larger value is + * better, otherwise a smaller one. `TOPN_ITEM_BETTER` orders two items and + * is the ONLY predicate the heap uses: the better value, and between equal + * values the smaller earliest source row (`first`). That is the tie rule of + * the answer itself: phase 3 emits groups by earliest source row and the + * final sort is stable, so of the groups tied at the cut the take keeps the + * ones seen first. Groups have distinct earliest rows, so this is a strict + * total order. The heap keeps the WORST retained item at the root, so the + * invariant is "parent is not better than child" and a swap is needed + * exactly when the parent IS better. */ #define TOPN_BETTER(desc_dir, a, b) ((desc_dir) ? ((a) > (b)) : ((a) < (b))) +#define TOPN_ITEM_BETTER(desc_dir, a, b) (TOPN_BETTER(desc_dir, (a).value, (b).value) || \ + ((a).value == (b).value && (a).first < (b).first)) /* Push one candidate into a bounded "best k" heap; returns the new count. - * Replacement is on STRICT improvement: an item that merely TIES the root is - * rejected and the heap is left byte-for-byte unchanged. + * Replacement is on strict improvement under TOPN_ITEM_BETTER. Because that + * order is total, the heap retains exactly the k best items it was shown, + * whatever order they came in: the (partition, gid) push order, which + * depends on how phase 1's workers claimed morsels, on phase 2's fold and on + * the partition count, cannot change the retained set. (A value-only order + * left ties to that push order, and the answer changed between runs and + * core counts: #801.) * - * That is NOT the same as "the earliest of equal values wins" — with k=2, - * desc, pushing 5,5,7 evicts the FIRST 5, because sift-down may promote - * either equal child to the root. What holds is only that the outcome is a - * deterministic function of the push sequence, which is all the callers need. - * - * WHY THE PARALLEL PRE-PASS RETAINS THE SAME SET AS ONE SERIAL SCAN. Let H - * be the global heap of the serial scan and H_p a partition's local heap. - * When H_p is full it holds the k best of what that partition has shown so - * far; H at the same point holds the k best of a SUPERSET of those items, so - * H's root is never worse than H_p's. An item H_p rejects is therefore not - * strictly better than H's root either — H would reject it too, leaving H - * unchanged. So the pre-pass elides only pushes that are provably no-ops, - * and feeding H the survivors alone reproduces its exact trajectory. - * - * TWO CONDITIONS CARRY THAT ARGUMENT. Do not "optimise" either away: - * (1) the per-partition cap is k_take ITSELF, never k_take/n_parts or any - * other share. (It may be smaller only when the partition holds fewer - * than k_take groups — then the heap drops nothing at all.) With a - * smaller cap H_p's root could be BETTER than H's, and H_p would drop - * an item the serial scan keeps. - * (2) the merge feeds candidates in the serial scan's order: partitions - * ascending, and gid ascending within a partition. Ties are - * order-sensitive (see the 5,5,7 trace above), so topn_scan_fn sorts - * its survivors back into gid order for exactly this reason. */ + * WHY THE PARALLEL PRE-PASS RETAINS THE SAME SET AS ONE SCAN. Each + * partition's own k best contain every item of the global k best that lives + * in it, so the union of the per-partition survivors contains the global k + * best, and the heap fed that union retains exactly them. This needs the + * per-partition cap to be k_take ITSELF, never k_take/n_parts or any other + * share (it may be smaller only when the partition holds fewer than k_take + * groups, so that it drops nothing): with a smaller cap a partition could + * drop an item of the global k best. Do not "optimise" it away. */ static inline int64_t topn_heap_push(group_topn_item_t* h, int64_t hn, int64_t k, uint8_t desc_dir, int64_t v, - uint32_t part, uint32_t gid) { + int64_t first, uint32_t part, uint32_t gid) { + group_topn_item_t it = {v, first, part, gid}; if (hn < k) { int64_t j = hn++; - h[j] = (group_topn_item_t){v, part, gid}; + h[j] = it; while (j > 0) { /* sift up */ int64_t pr = (j - 1) >> 1; - if (!TOPN_BETTER(desc_dir, h[pr].value, h[j].value)) break; + if (!TOPN_ITEM_BETTER(desc_dir, h[pr], h[j])) break; group_topn_item_t t = h[pr]; h[pr] = h[j]; h[j] = t; j = pr; } return hn; } - if (!TOPN_BETTER(desc_dir, v, h[0].value)) return hn; - h[0] = (group_topn_item_t){v, part, gid}; + if (!TOPN_ITEM_BETTER(desc_dir, it, h[0])) return hn; + h[0] = it; for (int64_t j = 0;;) { /* sift down */ int64_t l = j * 2 + 1, r = l + 1, m = j; - if (l < hn && TOPN_BETTER(desc_dir, h[m].value, h[l].value)) m = l; - if (r < hn && TOPN_BETTER(desc_dir, h[m].value, h[r].value)) m = r; + if (l < hn && TOPN_ITEM_BETTER(desc_dir, h[m], h[l])) m = l; + if (r < hn && TOPN_ITEM_BETTER(desc_dir, h[m], h[r])) m = r; if (m == j) break; group_topn_item_t t = h[m]; h[m] = h[j]; h[j] = t; j = m; @@ -6156,12 +6808,6 @@ static inline int64_t topn_heap_push(group_topn_item_t* h, int64_t hn, return hn; } -static int topn_gid_cmp(const void* a, const void* b) { - uint32_t ga = ((const group_topn_item_t*)a)->gid; - uint32_t gb = ((const group_topn_item_t*)b)->gid; - return ga < gb ? -1 : (ga > gb ? 1 : 0); -} - static int topn_part_gid_cmp(const void* a, const void* b) { const group_topn_item_t* x = (const group_topn_item_t*)a; const group_topn_item_t* y = (const group_topn_item_t*)b; @@ -6169,18 +6815,58 @@ static int topn_part_gid_cmp(const void* a, const void* b) { return x->gid < y->gid ? -1 : (x->gid > y->gid ? 1 : 0); } +/* The (value, earliest row) item of group gi of partition p. `nn_off` is + * the in-row offset of the ordering agg's non-null count when its result is + * null for an all-null group (MIN/MAX over a nullable column), else 0. Such + * a group's slot holds the accumulator's init sentinel (MIN's INT64_MAX would + * rank it above every value), so it is ranked as the null instead: INT64_MIN, + * below every value, i.e. last under desc: and first under asc:, where the + * stable sort puts nulls (#808). INT64_MIN is the I64 null itself, never a + * value, and narrower types widen into the slot above it. + * + * `bias` is the constant of an affine SUM (`(sum (+ x c))` aggregates x and + * phase 3 adds c once per non-null x, wrapping as the I64 sum does), else 0: + * the group is ranked by that final value, not by the column's sum (#813). + * `bias_off` is the in-row offset of the count it multiplies: the slot's + * non-null count in a nullable layout, else the group's row count at row + 0, + * the same count phase 3 uses (#814). */ +static inline int64_t topn_group_push(group_topn_item_t* h, int64_t hn, + int64_t k, uint8_t desc_dir, + const group_ht_t* ph, uint16_t order_off, + uint16_t nn_off, int64_t bias, + uint16_t bias_off, uint32_t p, uint32_t gi) { + const char* row = ph->rows + (size_t)gi * ph->layout.row_stride; + int64_t v, first; + memcpy(&v, row + order_off, 8); + if (bias) { + int64_t cnt; + memcpy(&cnt, row + bias_off, 8); + v = wrap_add_i64(v, wrap_mul_i64(bias, cnt)); + } + if (nn_off) { + int64_t nn; + memcpy(&nn, row + nn_off, 8); + if (nn == 0) v = INT64_MIN; + } + memcpy(&first, row + ph->layout.off_group_first, 8); + return topn_heap_push(h, hn, k, desc_dir, v, first, p, gi); +} + /* Parallel pre-pass: reduce each partition to its OWN top-k. The global * top-k is a subset of the union of those, so the serial merge that follows - * only walks the survivors. Each worker sorts its survivors back into gid - * order and the merge walks partitions in ascending order, so the merge sees - * candidates in the same (partition, gid) sequence the single-threaded scan - * did — the retained set, and therefore the emitted rows, are identical. */ + * only walks the survivors. The heap's order is total, so the survivors' + * order within a partition and the order the merge walks them in do not + * matter: the retained set, and therefore the emitted rows, are those of a + * single scan. */ typedef struct { group_ht_t* part_hts; group_topn_item_t* items; /* [item_off[n_parts]] staging */ const uint32_t* item_off; /* [n_parts + 1] per-partition capacity */ uint32_t* item_cnt; /* [n_parts] survivors produced */ uint16_t order_off; /* in-row byte offset of the ordering agg */ + uint16_t nn_off; /* its non-null count, 0 = never null */ + int64_t bias; /* affine SUM constant, 0 = none */ + uint16_t bias_off; /* the count it multiplies */ uint8_t desc_dir; } topn_scan_ctx_t; @@ -6190,18 +6876,14 @@ static void topn_scan_fn(void* vctx, uint32_t worker_id, int64_t start, topn_scan_ctx_t* c = (topn_scan_ctx_t*)vctx; for (int64_t pi = start; pi < end; pi++) { uint32_t p = (uint32_t)pi; - group_ht_t* ph = &c->part_hts[p]; + const group_ht_t* ph = &c->part_hts[p]; uint32_t gc = ph->grp_count; - uint16_t rs = ph->layout.row_stride; group_topn_item_t* h = c->items + c->item_off[p]; int64_t cap = (int64_t)(c->item_off[p + 1] - c->item_off[p]); int64_t hn = 0; - for (uint32_t gi = 0; gi < gc; gi++) { - int64_t v = *(const int64_t*)(const void*) - (ph->rows + (size_t)gi * rs + c->order_off); - hn = topn_heap_push(h, hn, cap, c->desc_dir, v, p, gi); - } - if (hn > 1) qsort(h, (size_t)hn, sizeof(*h), topn_gid_cmp); + for (uint32_t gi = 0; gi < gc; gi++) + hn = topn_group_push(h, hn, cap, c->desc_dir, ph, c->order_off, + c->nn_off, c->bias, c->bias_off, p, gi); c->item_cnt[p] = (uint32_t)hn; } } @@ -6210,12 +6892,10 @@ static void topn_scan_fn(void* vctx, uint32_t worker_id, int64_t start, * the END of the phase-2 task that BUILT the partition, while its rows are * still in that core's L2/L3 instead of being re-read from DRAM afterwards. * - * It is arithmetically the same scan — same shared topn_heap_push, the same - * per-partition cap (`cap` is k_take ITSELF, condition (1) of the proof above, - * here as a uniform stride because grp_count is unknown at allocation time), - * and the same sort back into gid order so the merge still sees candidates - * partitions-ascending / gid-ascending (condition (2)). Fusion moves only - * WHERE the scan runs, never what it retains. + * It is arithmetically the same scan: the same shared topn_heap_push and the + * same per-partition cap (`cap` is k_take ITSELF, as the proof above needs, + * here as a uniform stride because grp_count is unknown at allocation time). + * Fusion moves only WHERE the scan runs, never what it retains. * * `items == NULL` means fusion is off and the standalone topn_scan_fn pre-pass * (or the serial scan) runs instead. `item_cnt` is calloc'd by the driver and @@ -6227,22 +6907,21 @@ typedef struct { uint32_t* item_cnt; /* [n_parts] survivors per partition */ uint32_t cap; /* per-partition capacity = k_take */ uint16_t order_off; /* in-row byte offset of the ordering agg */ + uint16_t nn_off; /* its non-null count, 0 = never null */ + int64_t bias; /* affine SUM constant, 0 = none */ + uint16_t bias_off; /* the count it multiplies */ uint8_t desc_dir; } topn_fuse_t; static inline void topn_fuse_partition(const topn_fuse_t* f, group_ht_t* ph, uint32_t p) { uint32_t gc = ph->grp_count; - uint16_t rs = ph->layout.row_stride; group_topn_item_t* h = f->items + (size_t)p * f->cap; int64_t cap = (int64_t)f->cap; int64_t hn = 0; - for (uint32_t gi = 0; gi < gc; gi++) { - int64_t v = *(const int64_t*)(const void*) - (ph->rows + (size_t)gi * rs + f->order_off); - hn = topn_heap_push(h, hn, cap, f->desc_dir, v, p, gi); - } - if (hn > 1) qsort(h, (size_t)hn, sizeof(*h), topn_gid_cmp); + for (uint32_t gi = 0; gi < gc; gi++) + hn = topn_group_push(h, hn, cap, f->desc_dir, ph, f->order_off, + f->nn_off, f->bias, f->bias_off, p, gi); f->item_cnt[p] = (uint32_t)hn; } @@ -6355,6 +7034,7 @@ typedef struct { * the payload buffers. Growing 1->2->4->... instead re-copies the whole * scattered payload ~2x (28% of ClickBench q16 in memmove). */ uint32_t buf_prime; + grp_rr_t rr; /* range reads (grp_run) */ } radix_phase1_ctx_t; /* Pack one row's aggregate input values into the entry staging slots. @@ -6362,53 +7042,18 @@ typedef struct { * two cannot drift; slot indices come from the layout (agg_val_slot), never * a running counter. */ static inline void radix_phase1_pack_aggs(const radix_phase1_ctx_t* c, + const grp_view_t* v, const ght_layout_t* ly, int64_t* agg_vals, int64_t row) { - const uint8_t* const aflags = ly->agg_flags; - uint16_t na = ly->n_aggs; - for (uint32_t a = 0; a < na; a++) { - uint8_t af = aflags[a]; - /* Destination slot from the layout (see group_rows_range): aggs - * with no value slot — holistic OP_MEDIAN &c. and valueless - * OP_COUNT — carry agg_val_slot == -1 and pack nothing. */ - int8_t vs = ly->agg_val_slot[a]; - if (vs < 0) continue; - uint8_t vi = (uint8_t)vs; - ray_t* ac = c->agg_vecs[a]; - if (!ac) continue; - if (c->agg_strlen && c->agg_strlen[a]) - agg_vals[vi] = group_strlen_at(ac, row); - else if (af & GHT_AF_F64) { - double v = group_fp_type(ac->type) - ? group_fp_at(ray_data(ac), ac->type, row) - : group_pack_i64_as_f64(ac, row); - memcpy(&agg_vals[vi], &v, sizeof(v)); - } - else - agg_vals[vi] = read_col_i64(ray_data(ac), row, ac->type, ac->attrs); - vi++; - /* Binary aggregator: read y-side value into the next slot. - * Cast non-F64 inputs through read_col_i64 — pearson_corr's - * finalize reads both slots as F64 doubles regardless of - * input type (i64 will be reinterpreted; for now we only - * support F64 inputs cleanly — i64 path is a perf followup). */ - if ((af & GHT_AF_BINARY) && c->agg_vecs2 && c->agg_vecs2[a]) { - ray_t* ay = c->agg_vecs2[a]; - if (af & GHT_AF_F64) { - double v = group_fp_type(ay->type) - ? group_fp_at(ray_data(ay), ay->type, row) - : group_pack_i64_as_f64(ay, row); - memcpy(&agg_vals[vi], &v, sizeof(v)); - } - else - agg_vals[vi] = group_pack_y_i64(ay, row); - vi++; - } - } + ght_pack_aggs(ly, c->agg_vecs, c->agg_vecs2, c->agg_strlen, v, agg_vals, row); } -static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { +static void radix_phase1_body(void* ctx, const grp_view_t* v, uint32_t worker_id, + int64_t start, int64_t end) { radix_phase1_ctx_t* c = (radix_phase1_ctx_t*)ctx; + void* const* key_data = v->key_data; + const uint8_t* key_attrs = v->key_attrs; + const int64_t kb = v->key_base; /* keys are read at row - kb */ const ght_layout_t* ly = &c->layout; radix_buf_t* my_bufs = &c->bufs[(size_t)worker_id * c->n_parts]; uint16_t nk = ly->n_keys; @@ -6481,17 +7126,17 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ if (m == 0) continue; for (uint32_t k = 0; k < nk; k++) { if (contiguous) - group_keys_gather_seq(stage[k], c->key_data[k], rowbuf[0], m, - c->key_types[k], c->key_attrs[k]); + group_keys_gather_seq(stage[k], key_data[k], rowbuf[0] - kb, m, + c->key_types[k], key_attrs[k]); else - group_keys_gather(stage[k], c->key_data[k], rowbuf, m, - c->key_types[k], c->key_attrs[k]); + group_keys_gather(stage[k], key_data[k], rowbuf, kb, m, + c->key_types[k], key_attrs[k]); } for (uint32_t j = 0; j < m; j++) { int64_t row = rowbuf[j]; for (uint32_t k = 0; k < nk; k++) keys[k] = stage[k][j]; uint64_t h = ght_hash_lanes(keys, nk); - radix_phase1_pack_aggs(c, ly, agg_vals, row); + radix_phase1_pack_aggs(c, v, ly, agg_vals, row); uint32_t part = group_radix_part(h, c->n_parts); radix_buf_push(&my_bufs[part], estride, h, keys, agg_vals, nv, row, ly->key_region, c->buf_prime); @@ -6510,7 +7155,8 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, row)) continue; uint64_t h = 0; if (inline_str) { - h = inline_build_keys(ly, c->key_types, c->key_data, c->key_attrs, + /* inline STR: a wide-key layout, whose keys are whole columns */ + h = inline_build_keys(ly, c->key_types, c->key_data, key_attrs, c->key_pool, c->key_vecs, nullable, row, keybuf); } else { @@ -6528,12 +7174,12 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ * key shape. */ for (uint32_t k = 0; k < nk; k++) { if (__builtin_expect(nullable && ray_key_may_be_null(c->key_vecs[k]) - && ray_vec_is_null(c->key_vecs[k], row), 0)) { + && grp_key_null(c->key_vecs[k], v, k, c->key_types[k], row), 0)) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); keys[k] = 0; } else { - keys[k] = read_col_i64(c->key_data[k], row, c->key_types[k], - c->key_attrs[k]); + keys[k] = read_col_i64(key_data[k], row - kb, c->key_types[k], + key_attrs[k]); } } h = ght_hash_lanes(keys, (uint32_t)nk + null_words); @@ -6542,7 +7188,7 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ int8_t t = c->key_types[k]; uint64_t kh; bool is_null = nullable && ray_key_may_be_null(c->key_vecs[k]) - && ray_vec_is_null(c->key_vecs[k], row); + && grp_key_null(c->key_vecs[k], v, k, t, row); if (is_null) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); keys[k] = 0; @@ -6552,12 +7198,12 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ kh = wide_key_hash_at(ly, k, c->key_data, c->key_pool, row); } else if (t == RAY_F64) { /* -0.0 -> +0.0 before BOTH the store and the hash. */ - int64_t kv = group_key_f64_bits(c->key_data[k], row); + int64_t kv = group_key_f64_bits(key_data[k], row - kb); double dv; memcpy(&dv, &kv, 8); keys[k] = kv; kh = ray_hash_f64(dv); } else { - int64_t kv = read_col_i64(c->key_data[k], row, t, c->key_attrs[k]); + int64_t kv = read_col_i64(key_data[k], row - kb, t, key_attrs[k]); keys[k] = kv; kh = ray_hash_i64(kv); } @@ -6567,7 +7213,7 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ } } - radix_phase1_pack_aggs(c, ly, agg_vals, row); + radix_phase1_pack_aggs(c, v, ly, agg_vals, row); uint32_t part = group_radix_part(h, c->n_parts); radix_buf_push(&my_bufs[part], estride, h, @@ -6577,6 +7223,13 @@ static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ scratch_free(stage_hdr); /* NULL (inline staging) → no-op */ } +static void radix_phase1_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + radix_phase1_ctx_t* c = (radix_phase1_ctx_t*)ctx; + grp_view_t v = grp_view_whole(c->key_data, c->key_attrs); + grp_run(c, radix_phase1_body, &v, &c->rr, c->match_idx ? NULL : c->rowsel, NULL, + worker_id, start, end); +} + /* Process pre-partitioned fat entries into an HT with prefetch batching. * Two-phase prefetch: (1) prefetch HT slots, (2) prefetch group rows. */ static void group_rows_indirect(group_ht_t* ht, const int8_t* key_types, @@ -6615,8 +7268,21 @@ typedef struct { ray_t* vec; } agg_out_t; -/* Aliases for shared parallel null helpers from internal.h */ -#define grp_set_null par_set_null +/* Radix outputs are fresh, unsliced vectors. Workers own disjoint slots, + * but all read attrs through ray_data(); even an atomic HAS_NULLS update + * races with those plain header reads. Write only payload here and derive + * the flag with grp_finalize_nulls after the dispatch joins. */ +static inline void grp_set_null(ray_t* vec, int64_t idx) { + void* p = vec->data; + switch (vec->type) { + case RAY_F64: ((double*)p)[idx] = NULL_F64; break; + case RAY_F32: ((float*)p)[idx] = NULL_F32; break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)p)[idx] = NULL_I64; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)p)[idx] = NULL_I32; break; + case RAY_I16: ((int16_t*)p)[idx] = NULL_I16; break; + default: break; + } +} #define grp_finalize_nulls par_finalize_nulls typedef struct { @@ -6695,7 +7361,7 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ case RAY_F32: { float v = NULL_F32; memcpy(dst + doff, &v, 4); break; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t v = NULL_I64; memcpy(dst + doff, &v, 8); break; } case RAY_I32: case RAY_DATE: case RAY_TIME: { @@ -6711,7 +7377,7 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ * width — the same payload * ray_vec_set_null_checked writes on the serial * emit path. The HAS_NULLS bit these three need - * (par_set_null does not write it for them) is + * (not derived by the numeric sentinel rescan) is * seeded from the source column BEFORE the * dispatch, so no worker touches attrs here. */ memset(dst + doff, 0, esz); @@ -6760,7 +7426,8 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ case OP_SUM: v = sf ? ROW_RD_F64(row, ly->off_sum, s) : (double)ROW_RD_I64(row, ly->off_sum, s); - if (ao->affine) v += ao->bias_f64 * cnt; + /* `(sum (+ x c))`: c once per non-null x (#814) */ + if (ao->affine) v += ao->bias_f64 * nn; break; case OP_PROD: if (nn == 0) { v = NULL_F64; grp_set_null(ao->vec, di); break; } @@ -6856,7 +7523,7 @@ static void radix_phase3_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ switch (op) { case OP_SUM: v = ROW_RD_I64(row, ly->off_sum, s); - if (ao->affine) v = wrap_add_i64(v, wrap_mul_i64(ao->bias_i64, cnt)); + if (ao->affine) v = wrap_add_i64(v, wrap_mul_i64(ao->bias_i64, nn)); break; case OP_PROD: if (nn == 0) { v = int_null; grp_set_null(ao->vec, di); break; } @@ -7072,6 +7739,7 @@ typedef struct { uint32_t ht_grow_cap; /* slot-count ceiling for HT growth — * see group_ht_t.grow_cap */ _Atomic(int) oom; + grp_rr_t rr; /* range reads (grp_run; R-SPARSE over match_idx) */ } radix_v2_phase1_ctx_t; /* Pack one row's aggregate input values into the entry's agg-value slots. @@ -7080,46 +7748,29 @@ typedef struct { * running counter. Mirrors radix_phase1_pack_aggs, but tolerates a NULL * agg_vecs table (pure-COUNT layouts carry none). */ static inline void radix_v2_pack_aggs(const radix_v2_phase1_ctx_t* c, + const grp_view_t* v, const ght_layout_t* ly, int64_t* ev, int64_t row) { - const uint8_t* const aflags = ly->agg_flags; - uint16_t na = ly->n_aggs; - for (uint32_t a = 0; a < na; a++) { - uint8_t af = aflags[a]; - int8_t vs = ly->agg_val_slot[a]; - if (vs < 0) continue; /* holistic / valueless OP_COUNT */ - uint8_t vi = (uint8_t)vs; - ray_t* ac = c->agg_vecs ? c->agg_vecs[a] : NULL; - if (!ac) continue; - if (c->agg_strlen && c->agg_strlen[a]) - ev[vi] = group_strlen_at(ac, row); - else if (af & GHT_AF_F64) { - double v = group_fp_type(ac->type) - ? group_fp_at(ray_data(ac), ac->type, row) - : group_pack_i64_as_f64(ac, row); - memcpy(&ev[vi], &v, sizeof(v)); - } - else - ev[vi] = read_col_i64(ray_data(ac), row, ac->type, ac->attrs); - vi++; - if ((af & GHT_AF_BINARY) && c->agg_vecs2 && c->agg_vecs2[a]) { - ray_t* ay = c->agg_vecs2[a]; - if (af & GHT_AF_F64) { - double v = group_fp_type(ay->type) - ? group_fp_at(ray_data(ay), ay->type, row) - : group_pack_i64_as_f64(ay, row); - memcpy(&ev[vi], &v, sizeof(v)); - } - else - ev[vi] = group_pack_y_i64(ay, row); - vi++; - } - } + ght_pack_aggs(ly, c->agg_vecs, c->agg_vecs2, c->agg_strlen, v, ev, row); } -static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, - int64_t start, int64_t end) { - radix_v2_phase1_ctx_t* c = (radix_v2_phase1_ctx_t*)ctx; +/* One task's phase-1 state, shared by its pieces: the worker's partition + * HTs and their live probe masks, the entry staging, and the + * partition-major path's counting-sort histogram (NULL: row-major). */ +typedef struct { + radix_v2_phase1_ctx_t* c; + group_ht_t* my_hts; + uint32_t* masks; + char* ebuf; + const void** kpool; + uint32_t* hist; +} radix_v2_task_t; + +static void radix_v2_phase1_body(void* ctx, const grp_view_t* v, uint32_t worker_id, + int64_t start, int64_t end) { + (void)worker_id; + radix_v2_task_t* tk = (radix_v2_task_t*)ctx; + radix_v2_phase1_ctx_t* c = tk->c; if (atomic_load_explicit(&c->oom, memory_order_relaxed)) return; const ght_layout_t* ly = &c->layout; uint16_t nk = ly->n_keys; @@ -7128,32 +7779,13 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, uint8_t inline_str = ly->any_inline_str; uint8_t nullable = c->nullable_mask; const int64_t* match_idx = c->match_idx; - - group_ht_t* my_hts = &c->wpart_hts[(size_t)worker_id * c->n_parts]; - uint32_t masks[c->n_parts]; - /* A worker may be called for several morsels. Its partition HTs persist - * across calls, so restore each live probe mask instead of treating every - * invocation as first use. */ - for (uint32_t p = 0; p < c->n_parts; p++) - masks[p] = my_hts[p].slots ? my_hts[p].ht_cap - 1 : 0; - - /* Stack-resident transient entry + per-key str-pool table, same layout as - * group_rows_range. ≤8 keys/aggs stay on the stack (byte-identical); - * wider layouts carve one per-worker heap block ONCE (never per row — - * unbounded-slots cut 4): ebuf(entry_stride) | kpool(n_keys ptrs). */ - char ebuf_stk[8 + 9 * 8 + 8 * 8 + 8]; - const void* kpool_stk[8]; - char* ebuf = ebuf_stk; - const void** kpool = kpool_stk; - ray_t* v2_stage_hdr = NULL; - if (ly->entry_stride > sizeof(ebuf_stk) || nk > 8) { - char* blk = (char*)scratch_alloc(&v2_stage_hdr, - (size_t)ly->entry_stride + (size_t)nk * sizeof(void*)); - if (!blk) { atomic_store_explicit(&c->oom, 1, memory_order_relaxed); return; } - ebuf = blk; - kpool = (const void**)(blk + ly->entry_stride); - } - derive_key_pool(ly, c->key_vecs, kpool); + group_ht_t* my_hts = tk->my_hts; + uint32_t* masks = tk->masks; + char* ebuf = tk->ebuf; + const void** kpool = tk->kpool; + void* const* key_data = v->key_data; + const uint8_t* key_attrs = v->key_attrs; + const int64_t kb = v->key_base; /* keys are read at row - kb */ /* Partition-major fast path (spec Part A): stage a morsel of rows * (hash + partition, no HT access), counting-sort the morsel's @@ -7174,11 +7806,7 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, * * NOTE: "hashing is identical" is load-bearing and is enforced by the * v2_packed branch in the staging loop — see the comment there. */ - if (!wide_any && !inline_str && !nullable && ly->null_words == 0 && - (ly->need_flags & ~(uint32_t)(GHT_NEED_SUM | GHT_NEED_SUM128)) == 0 && - !(ly->agg_flags_any & (GHT_AF_FIRST | GHT_AF_LAST | GHT_AF_BINARY | - GHT_AF_HOLISTIC)) && - nk >= 1 && nk <= 2 && ly->entry_stride <= 64) { + if (tk->hist) { enum { V2M = 1024, V2MPF = 8 }; /* Morsel staging: hashes, key values, source rows, partition ids, * partition-order permutation, and the counting-sort histogram. @@ -7188,7 +7816,8 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, * morder stays uint16_t — it indexes morsel slots, always <=1024. * hist is sized n_parts (not n_parts+1: sparse scheme below writes * counts directly into hist[p], no running-offset slot needed) and - * is scratch_calloc'd ONCE per dispatch call so it starts zeroed; + * is scratch_calloc'd ONCE per dispatch call (radix_v2_phase1_fn, + * shared by the task's pieces) so it starts zeroed; * each morsel only touches (and only re-zeroes) the partitions it * actually hit, tracked via plist, keeping the per-morsel counting * sort O(morsel size) instead of O(n_parts) — at 100M rows @@ -7201,14 +7830,7 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, uint32_t mpart[V2M]; uint16_t morder[V2M]; uint32_t plist[V2M]; - ray_t* hist_hdr = NULL; - uint32_t* hist = (uint32_t*)scratch_calloc(&hist_hdr, - (size_t)c->n_parts * sizeof(uint32_t)); - if (!hist) { - atomic_store_explicit(&c->oom, 1, memory_order_relaxed); - scratch_free(v2_stage_hdr); - return; - } + uint32_t* hist = tk->hist; int64_t i = start; while (i < end) { @@ -7229,13 +7851,13 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, * (v2_packed never holds with an F64 key — F64 is off * the packed whitelist — but stage the same bits the * generic builder would either way.) */ - int64_t kv = group_key_f64_bits(c->key_data[k], row); + int64_t kv = group_key_f64_bits(key_data[k], row - kb); double dv; memcpy(&dv, &kv, 8); mk[(size_t)mn * nk + k] = kv; if (!v2_packed) kh = ray_hash_f64(dv); } else { - int64_t kv = read_col_i64(c->key_data[k], row, t, - c->key_attrs[k]); + int64_t kv = read_col_i64(key_data[k], row - kb, t, + key_attrs[k]); mk[(size_t)mn * nk + k] = kv; if (!v2_packed) kh = ray_hash_i64(kv); } @@ -7318,7 +7940,7 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, * stay the same size; the source row is mrow[j] and the reads * are identical to the row-major builder's. */ if (ly->need_flags) - radix_v2_pack_aggs(c, ly, + radix_v2_pack_aggs(c, v, ly, (int64_t*)(ebuf + 8 + (size_t)ly->key_region), mrow[j]); memcpy(ebuf + ly->entry_stride - 8, &mrow[j], 8); masks[p] = group_probe_entry(&my_hts[p], ebuf, @@ -7330,8 +7952,6 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, } } v2_morsel_done: - scratch_free(hist_hdr); - scratch_free(v2_stage_hdr); return; } @@ -7343,7 +7963,8 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, uint64_t h = 0; int64_t* ek = (int64_t*)(ebuf + 8); if (inline_str) { - h = inline_build_keys(ly, c->key_types, c->key_data, c->key_attrs, + /* inline STR: a wide-key layout, whose keys are whole columns */ + h = inline_build_keys(ly, c->key_types, c->key_data, key_attrs, kpool, c->key_vecs, nullable, row, ebuf + 8); } else { int64_t* nullw = ek + nk; /* null-mask words at key_off[nk]==nk*8 */ @@ -7357,11 +7978,11 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, * stay in lockstep with hash_keys_inline (rehash/merge/lookup). */ for (uint32_t k = 0; k < nk; k++) { if (__builtin_expect(nullable && ray_key_may_be_null(c->key_vecs[k]) - && ray_vec_is_null(c->key_vecs[k], row), 0)) { + && grp_key_null(c->key_vecs[k], v, k, c->key_types[k], row), 0)) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); ek[k] = 0; } else { - ek[k] = read_col_i64(c->key_data[k], row, c->key_types[k], c->key_attrs[k]); + ek[k] = read_col_i64(key_data[k], row - kb, c->key_types[k], key_attrs[k]); } } h = ght_hash_lanes(ek, (uint32_t)nk + null_words); @@ -7370,7 +7991,7 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, int8_t t = c->key_types[k]; uint64_t kh; bool is_null = nullable && ray_key_may_be_null(c->key_vecs[k]) - && ray_vec_is_null(c->key_vecs[k], row); + && grp_key_null(c->key_vecs[k], v, k, t, row); if (is_null) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); ek[k] = 0; @@ -7380,12 +8001,12 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, kh = wide_key_hash_at(ly, k, c->key_data, kpool, row); } else if (t == RAY_F64) { /* -0.0 -> +0.0 before BOTH the store and the hash. */ - int64_t kv = group_key_f64_bits(c->key_data[k], row); + int64_t kv = group_key_f64_bits(key_data[k], row - kb); double dv; memcpy(&dv, &kv, 8); ek[k] = kv; kh = ray_hash_f64(dv); } else { - int64_t kv = read_col_i64(c->key_data[k], row, t, c->key_attrs[k]); + int64_t kv = read_col_i64(key_data[k], row - kb, t, key_attrs[k]); ek[k] = kv; kh = ray_hash_i64(kv); } @@ -7400,7 +8021,7 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, * skips every agg slot; packing here would be a wasted column * read per row (a measurable regression on q15-class queries). */ if (ly->need_flags) - radix_v2_pack_aggs(c, ly, + radix_v2_pack_aggs(c, v, ly, (int64_t*)(ebuf + 8 + (size_t)ly->key_region), row); memcpy(ebuf + ly->entry_stride - 8, &row, 8); uint32_t p = group_radix_part(h, c->n_parts); @@ -7428,9 +8049,68 @@ static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, } masks[p] = new_mask; } +} + +static void radix_v2_phase1_fn(void* ctx, uint32_t worker_id, + int64_t start, int64_t end) { + radix_v2_phase1_ctx_t* c = (radix_v2_phase1_ctx_t*)ctx; + if (atomic_load_explicit(&c->oom, memory_order_relaxed)) return; + const ght_layout_t* ly = &c->layout; + uint16_t nk = ly->n_keys; + uint8_t wide_any = ly->any_wide_key; + uint8_t inline_str = ly->any_inline_str; + uint8_t nullable = c->nullable_mask; + + group_ht_t* my_hts = &c->wpart_hts[(size_t)worker_id * c->n_parts]; + uint32_t masks[c->n_parts]; + /* A worker may be called for several morsels. Its partition HTs persist + * across calls, so restore each live probe mask instead of treating every + * invocation as first use. */ + for (uint32_t p = 0; p < c->n_parts; p++) + masks[p] = my_hts[p].slots ? my_hts[p].ht_cap - 1 : 0; + + /* Stack-resident transient entry + per-key str-pool table, same layout as + * group_rows_range. ≤8 keys/aggs stay on the stack (byte-identical); + * wider layouts carve one per-worker heap block ONCE (never per row — + * unbounded-slots cut 4): ebuf(entry_stride) | kpool(n_keys ptrs). */ + char ebuf_stk[8 + 9 * 8 + 8 * 8 + 8]; + const void* kpool_stk[8]; + char* ebuf = ebuf_stk; + const void** kpool = kpool_stk; + ray_t* v2_stage_hdr = NULL; + if (ly->entry_stride > sizeof(ebuf_stk) || nk > 8) { + char* blk = (char*)scratch_alloc(&v2_stage_hdr, + (size_t)ly->entry_stride + (size_t)nk * sizeof(void*)); + if (!blk) { atomic_store_explicit(&c->oom, 1, memory_order_relaxed); return; } + ebuf = blk; + kpool = (const void**)(blk + ly->entry_stride); + } + derive_key_pool(ly, c->key_vecs, kpool); + + /* The partition-major path of radix_v2_phase1_body takes this shape. */ + ray_t* hist_hdr = NULL; + uint32_t* hist = NULL; + if (!wide_any && !inline_str && !nullable && ly->null_words == 0 && + (ly->need_flags & ~(uint32_t)(GHT_NEED_SUM | GHT_NEED_SUM128)) == 0 && + !(ly->agg_flags_any & (GHT_AF_FIRST | GHT_AF_LAST | GHT_AF_BINARY | + GHT_AF_HOLISTIC)) && + nk >= 1 && nk <= 2 && ly->entry_stride <= 64) { + hist = (uint32_t*)scratch_calloc(&hist_hdr, (size_t)c->n_parts * sizeof(uint32_t)); + if (!hist) { + atomic_store_explicit(&c->oom, 1, memory_order_relaxed); + scratch_free(v2_stage_hdr); + return; + } + } + radix_v2_task_t tk = { c, my_hts, masks, ebuf, kpool, hist }; + grp_view_t v = grp_view_whole(c->key_data, c->key_attrs); + grp_run(&tk, radix_v2_phase1_body, &v, &c->rr, c->match_idx ? NULL : c->rowsel, + c->rr.staged ? c->match_idx : NULL, worker_id, start, end); + scratch_free(hist_hdr); scratch_free(v2_stage_hdr); /* NULL (inline staging) → no-op */ } + typedef struct { group_ht_t* wpart_hts; /* [n_workers * n_parts] — input */ group_ht_t* part_hts; /* [n_parts] — output */ @@ -7501,6 +8181,28 @@ static void radix_v2_phase2_fn(void* ctx, uint32_t worker_id, * Parallel direct-array accumulation for low-cardinality single integer key * ============================================================================ */ +/* R-WALK of [start, end) over n sources (ray_col_walk), skipping the + * morsels a selection rejects whole: those rows are never read, so a range + * error there never surfaces. NULL or an owned error. */ +static ray_t* group_sel_walk(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + ray_t* rowsel, int64_t start, int64_t end, + void* ctx, uint32_t wid, ray_col_piece_fn fn) { + const uint8_t* flags = rowsel ? ray_rowsel_flags(rowsel) : NULL; + if (!flags) return ray_col_walk(srcs, plain, n, start, end, false, ctx, wid, fn); + const int64_t M = RAY_MORSEL_ELEMS; + for (int64_t r = start; r < end; ) { + while (r < end && flags[r / M] == RAY_SEL_NONE) r = (r / M + 1) * M; + if (r >= end) break; + int64_t q = r; + while (q < end && flags[q / M] != RAY_SEL_NONE) q = (q / M + 1) * M; + if (q > end) q = end; + ray_t* err = ray_col_walk(srcs, plain, n, r, q, false, ctx, wid, fn); + if (err) return err; + r = q; + } + return NULL; +} + /* Parallel min/max scan for direct-array key range detection */ typedef struct { const void* key_data; @@ -7515,11 +8217,20 @@ typedef struct { * contributing row count, direct-array state would be superlinear. */ int64_t span_budget; _Atomic(int)* abort_flag; + /* Range reads (R-WALK). src NULL: key_data is the whole column (row + * base 0). A staged key (generation 2) is read by pieces: key_data and + * key_attrs then describe the piece starting at row_base. scan_chunk: + * NULL scans every row; else only the directory chunks marked 1 (the + * others' bounds came from their statistics). */ + int64_t row_base; + ray_col_src_t* src; + const uint8_t* scan_chunk; + ray_scan_fail_t* fail; } minmax_ctx_t; -static void minmax_scan_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - minmax_ctx_t* c = (minmax_ctx_t*)ctx; +static void minmax_scan_body(minmax_ctx_t* c, uint32_t worker_id, int64_t start, int64_t end) { uint32_t wid = worker_id % c->n_workers; + const int64_t rb = c->row_base; const int64_t* match_idx = c->match_idx; int64_t kmin = INT64_MAX, kmax = INT64_MIN; int8_t t = c->key_type; @@ -7540,7 +8251,7 @@ static void minmax_scan_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t memory_order_relaxed)) \ goto minmax_done; \ if (kmax >= kmin && \ - (uint64_t)(kmax - kmin) > (uint64_t)span_budget) { \ + (uint64_t)kmax - (uint64_t)kmin > (uint64_t)span_budget) { \ atomic_store_explicit(c->abort_flag, 1, \ memory_order_relaxed); \ goto minmax_done; \ @@ -7548,14 +8259,14 @@ static void minmax_scan_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t } \ int64_t r = match_idx ? match_idx[i] : i; \ if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, r)) continue; \ - int64_t v = (int64_t)CAST kd[r]; \ + int64_t v = (int64_t)CAST kd[r - rb]; \ if (t == RAY_SYM && v == 0) continue; \ if (v < kmin) kmin = v; \ if (v > kmax) kmax = v; \ } \ } while (0) - if (t == RAY_I64 || t == RAY_TIMESTAMP) + if (t == RAY_I64 || t == RAY_TIMESPAN || t == RAY_TIMESTAMP) MINMAX_SEG_LOOP(int64_t, ); else if (RAY_IS_SYM(t)) { uint8_t w = c->key_attrs & RAY_SYM_W_MASK; @@ -7579,6 +8290,57 @@ static void minmax_scan_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t if (kmax > c->per_worker_max[wid]) c->per_worker_max[wid] = kmax; } +/* One piece of a staged key: the body over [b, e) with the piece's base + * and SYM width. */ +static void minmax_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + minmax_ctx_t* c = (minmax_ctx_t*)ctx; + if (atomic_load_explicit(c->abort_flag, memory_order_relaxed)) return; + minmax_ctx_t local = *c; + local.key_data = p[0].data; + local.key_attrs = p[0].attrs; + local.row_base = b; + minmax_scan_body(&local, wid, b, e); + atomic_fetch_add_explicit(&ray_group_minmax_staged_rows_ctr, e - b, memory_order_relaxed); + /* A piece is at most one vector, and the body's batched span check + * runs on the piece's own bounds, which start empty: it never fires + * inside a piece. The worker's bounds so far (the body merged them) + * decide instead, as the plain scan's check does over the same rows. */ + const uint32_t w = wid % c->n_workers; + const int64_t mn = c->per_worker_min[w], mx = c->per_worker_max[w]; + if (mx >= mn && (uint64_t)mx - (uint64_t)mn > (uint64_t)c->span_budget) + atomic_store_explicit(c->abort_flag, 1, memory_order_relaxed); +} + +static void minmax_scan_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + minmax_ctx_t* c = (minmax_ctx_t*)ctx; + if (!c->src) { minmax_scan_body(c, worker_id, start, end); return; } + if (ray_scan_fail_skip(c->fail, start)) return; + ray_col_src_t* const srcs[1] = { c->src }; + const void* const plain[1] = { NULL }; + ray_t* err = NULL; + for (int64_t lo = start; lo < end && !err; ) { + int64_t hi = end; + if (c->scan_chunk) { + /* the run of chunks to scan from lo, clipped to the task */ + int64_t ch = lo / RAY_ENC_CHUNK; + if (!c->scan_chunk[ch]) { lo = (ch + 1) * RAY_ENC_CHUNK; continue; } + int64_t q = ch + 1; + while (q * RAY_ENC_CHUNK < end && c->scan_chunk[q]) q++; + if (q * RAY_ENC_CHUNK < hi) hi = q * RAY_ENC_CHUNK; + } + /* eight vectors at a time, so an abort (minmax_piece) stops the + * walk, and its decodes, within eight vectors of the worker */ + const int64_t step = (int64_t)RAY_ENC_VEC * 8; + const int64_t ce = (lo / step + 1) * step; + if (ce < hi) hi = ce; + if (atomic_load_explicit(c->abort_flag, memory_order_relaxed)) break; + err = group_sel_walk(srcs, plain, 1, c->match_idx ? NULL : c->rowsel, + lo, hi, c, worker_id, minmax_piece); + lo = hi; + } + if (err) ray_scan_fail_note(c->fail, start, err); +} + typedef union { double f; int64_t i; } da_val_t; typedef struct { @@ -7600,6 +8362,11 @@ typedef struct { * aggs needs null tracking (no HAS_NULLS columns). */ int64_t* first_row; /* min row index seen per slot (FIRST) [n_slots] */ int64_t* last_row; /* max row index seen per slot (LAST) [n_slots] */ + int64_t* sl_null; /* per-(group, agg) rows of length 0 under an + * AVG(strlen) fusion [n_slots * n_aggs]: the empty + * string is the STR/SYM null, so the emit divides + * by the non-null rows (nn_count, else count) + * minus these. NULL without an AVG(strlen). */ /* Binary-aggregator co-moments (PEARSON/COV/WAVG/WSUM): the y-side of * the pair. [n_slots * n_aggs]. x-side reuses sum (Σx) + sumsq_f64 * (Σx²). Allocated only when DA_NEED_PAIR is set. */ @@ -7616,6 +8383,7 @@ typedef struct { ray_t* _h_nn_count; ray_t* _h_first_row; ray_t* _h_last_row; + ray_t* _h_sl_null; ray_t* _h_sum_y; ray_t* _h_sumsq_y; ray_t* _h_sumxy; @@ -7631,6 +8399,7 @@ static inline void da_accum_free(da_accum_t* a) { scratch_free(a->_h_nn_count); scratch_free(a->_h_first_row); scratch_free(a->_h_last_row); + scratch_free(a->_h_sl_null); scratch_free(a->_h_sum_y); scratch_free(a->_h_sumsq_y); scratch_free(a->_h_sumxy); @@ -7669,10 +8438,12 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* /* agg_col == NULL means a fused input. The accumulator family * follows the FUSION, not the expression's out_type: a fused * product accumulates F64; the linear i64 plan accumulates i64 - * even when its compiled expression promotes to F64. */ + * (it takes no FLOAT constant, const_expr_to_i64). */ bool is_f64 = agg_col ? group_fp_type(agg_col->type) : (prod && prod[a].enabled); + /* `(sum (+ x c))` with a FLOAT c over an integer x is F64 */ + bool f64_bias = affine && affine[a].enabled && affine[a].f64; int8_t out_type; switch (agg_op) { case OP_AVG: @@ -7696,7 +8467,8 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* * from the aggregation input op when the vector is absent. */ int8_t src_t = agg_col ? agg_col->type : (op_node(g, ext->agg_ins[a]) ? op_node(g, ext->agg_ins[a])->out_type : 0); - out_type = is_f64 ? RAY_F64 : (src_t == RAY_TIME ? RAY_TIME : RAY_I64); + out_type = is_f64 || f64_bias ? RAY_F64 + : (src_t == RAY_TIME ? RAY_TIME : RAY_I64); break; } case OP_PROD: @@ -7729,9 +8501,12 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* double v; switch (agg_op) { case OP_SUM: - v = is_f64 ? sum_f64[idx] : (double)sum_i64[idx]; + v = is_f64 ? sum_f64[idx] + : sum_hi64 ? ray_i128_to_f64(sum_hi64[idx], (uint64_t)sum_i64[idx]) + : (double)sum_i64[idx]; + /* `(sum (+ x c))`: c once per non-null x (#814) */ if (affine && affine[a].enabled) - v += affine[a].bias_f64 * counts[gi]; + v += affine[a].bias_f64 * nn; break; case OP_PROD: if (nn == 0) { v = NULL_F64; ray_vec_set_null(new_col, gi, true); break; } @@ -7739,6 +8514,14 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* break; case OP_AVG: if (nn == 0) { v = NULL_F64; ray_vec_set_null(new_col, gi, true); break; } + if (f64_bias) { + /* the sum of the F64 values over their count, + * as the builtin avg divides it */ + v = sum_hi64 ? ray_i128_to_f64(sum_hi64[idx], (uint64_t)sum_i64[idx]) + : (double)sum_i64[idx]; + v = (v + affine[a].bias_f64 * nn) / nn; + break; + } v = is_f64 ? sum_f64[idx] / nn : sum_hi64 ? ray_i128_to_f64(sum_hi64[idx], (uint64_t)sum_i64[idx]) / nn : (double)sum_i64[idx] / nn; @@ -7822,7 +8605,7 @@ static void emit_agg_columns(ray_t** result, ray_graph_t* g, const ray_op_ext_t* case OP_SUM: v = sum_i64[idx]; if (affine && affine[a].enabled) - v = wrap_add_i64(v, wrap_mul_i64(affine[a].bias_i64, counts[gi])); + v = wrap_add_i64(v, wrap_mul_i64(affine[a].bias_i64, nn)); break; case OP_PROD: if (nn == 0) { v = int_null; ray_vec_set_null(new_col, gi, true); break; } @@ -7949,8 +8732,37 @@ typedef struct { * entry off the mapping instead of pinning (and checking null) per row. */ ray_sym_domain_raw_t* agg_raw; uint8_t* agg_raw_ok; + /* Range reads (R-WALK). A plain context (staged false) reads whole + * columns: row_base 0, srcs/plain/piece_attrs/fail unused. A staged + * one (some key or input is generation 2) runs each task through + * ray_col_walk over n_src sources, the keys first, then the inputs, + * then the binary aggregates' y-sides: key_ptrs / agg_ptrs / agg_ptrs2 + * then address row row_base of the piece, and piece_attrs[i] is source + * i's SYM width there. Rows stay absolute (selection, FIRST/LAST, + * fused-product terms); only the piece reads subtract row_base. */ + int64_t row_base; + ray_col_src_t** srcs; /* [n_src]; NULL: nothing read (COUNT, fused, absent) */ + const void** plain; /* [n_src]: a ready source's base, NULL for a staged one */ + uint32_t n_src; + const uint8_t* piece_attrs; + ray_scan_fail_t* fail; + bool staged; + /* Per-agg STR descriptors of a strlen fusion's column, resolved once + * (slice offset applied); NULL for other aggs. Always set. */ + const ray_str_t** agg_str; + /* The one SUM/AVG(strlen) agg when every other agg is a COUNT, the key + * is single and all_sum holds (da_accum_strlen_fn); -1 otherwise. */ + int32_t sl_agg; } da_ctx_t; +/* SYM attrs (width) of agg input a: the piece's when staged. `staged` is + * a compile-time constant in every caller: the plain instances fold the + * piece test away. */ +static inline uint8_t da_agg_attrs(const da_ctx_t* c, uint32_t a, const bool staged) { + if (staged && c->piece_attrs) return c->piece_attrs[c->n_keys + a]; + return c->agg_cols[a] ? c->agg_cols[a]->attrs : 0; +} + typedef struct { uint8_t* used; int64_t* keys; @@ -8204,6 +9016,8 @@ static inline int da_key_is_unsigned(int8_t t) { } /* Composite GID from multi-key. Planning bounds total_slots to INT32_MAX. */ +/* `r` is the row within the key pieces (r - row_base; the absolute row for + * a plain context). */ static inline int32_t da_composite_gid(da_ctx_t* c, int64_t r) { int32_t gid = 0; for (uint32_t k = 0; k < c->n_keys; k++) { @@ -8246,6 +9060,14 @@ static inline void da_read_val(const void* ptr, int8_t type, uint8_t attrs, } } +/* The length of FILE-domain entry `sid` from the pinned index's length + * bytes (the string bytes stay unread below 255 bytes); an entry the symfile + * cannot give counts 0, the corrupt flag having been raised by the read. */ +static inline int64_t raw_len_or0(const ray_sym_domain_raw_t* raw, int64_t sid) { + int64_t l = ray_sym_domain_raw_len(raw, sid); + return l < 0 ? 0 : l; +} + static inline int64_t group_strlen_at(const ray_t* col, int64_t row) { if (!col || ray_vec_is_null((ray_t*)col, row)) return 0; if (col->type == RAY_STR) { @@ -8257,8 +9079,8 @@ static inline int64_t group_strlen_at(const ray_t* col, int64_t row) { } /* SYM cell: resolve through the COLUMN's domain (sym-domain Phase 2) * — sym_elem resolves via the global table, wrong for FILE-domain - * columns. A FILE domain's entries carry their length as a u32 - * prefix in the mapping: read it off the published snapshot (one + * columns. A FILE domain's index carries each length as a byte (the + * record header past 254): read it off the published snapshot (one * acquire load) instead of materialising an atom per symbol under * the domain lock; positions past the mapped prefix and other domains * resolve as before. */ @@ -8266,8 +9088,8 @@ static inline int64_t group_strlen_at(const ray_t* col, int64_t row) { int64_t sid = ray_read_sym(ray_data((ray_t*)col), row, col->type, col->attrs); ray_sym_domain_raw_t raw; if (ray_sym_domain_raw_pin(ray_sym_vec_domain((ray_t*)col), &raw) && sid >= 0 && sid < raw.count) { - size_t sl; - (void)ray_sym_domain_raw_str(&raw, sid, &sl); + int64_t sl; + sl = raw_len_or0(&raw, sid); return (int64_t)sl; } } @@ -8275,6 +9097,22 @@ static inline int64_t group_strlen_at(const ray_t* col, int64_t row) { return s ? (int64_t)ray_str_len(s) : 0; } +/* group_strlen_at's SYM arm on a raw id array: element `row` of `data` + * (width from attrs), resolved over `dom`. Id 0 is the null (length 0). */ +static inline int64_t sym_strlen_raw(const void* data, int64_t row, uint8_t attrs, + struct ray_sym_domain_s* dom) { + int64_t sid = ray_read_sym(data, row, RAY_SYM, attrs); + if (sid == 0) return 0; + ray_sym_domain_raw_t raw; + if (ray_sym_domain_raw_pin(dom, &raw) && sid > 0 && sid < raw.count) { + int64_t sl; + sl = raw_len_or0(&raw, sid); + return (int64_t)sl; + } + ray_t* s = ray_sym_domain_str(dom, sid); + return s ? (int64_t)ray_str_len(s) : 0; +} + static inline int64_t group_strlen_at_cached(const ray_t* col, int64_t row, ray_t** sym_strings, uint32_t sym_count) { @@ -8300,23 +9138,63 @@ static inline int64_t group_strlen_at_cached(const ray_t* col, int64_t row, return group_strlen_at(col, row); } +/* SUM/AVG(strlen scan): *out_vec is the STR / SYM column, plain when it is + * ready, else (an encoded SYM column) its RAY_ENCCOL, which the caller binds + * and reads by range. An encoded STR column is read through its plain + * column (R-RANDOM), materialized here, so every route reads what it reads + * at generation 0: declining left the input to the expression path, whose + * strlen makes an empty string a null that AVG skips, where the scalar and + * direct-array routes count it as length 0. A failed bind or + * materialization leaves an owned *err. */ static bool try_strlen_sumavg_input(ray_graph_t* g, ray_t* tbl, - ray_op_t* input_op, ray_t** out_vec) { + ray_op_t* input_op, ray_t** out_vec, ray_t** err) { + *err = NULL; if (!g || !tbl || !input_op || !out_vec) return false; if (input_op->opcode != OP_STRLEN || input_op->arity != 1 || !op_child(g, input_op, 0)) return false; ray_op_t* child = op_child(g, input_op, 0); ray_op_ext_t* child_ext = find_ext(g, child->id); if (!child_ext || child_ext->base.opcode != OP_SCAN) return false; - ray_t* col = ray_table_get_col(tbl, child_ext->sym); - if (!col || (col->type != RAY_STR && col->type != RAY_SYM)) return false; + ray_t* col; + if (ray_col_bind_declines(tbl, child_ext->sym)) { + col = ray_table_col(tbl, child_ext->sym); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); return false; } + } else { + ray_col_src_t* src = ray_graph_bind_col(g, tbl, child_ext->sym, err); + if (!src || src->parted) return false; + col = ray_col_src_ready(src); + if (!col && src->type == RAY_SYM) col = src->obj; /* staged */ + if (!col && src->type == RAY_STR) { + ray_t* e = ray_col_src_plain(src, &col); /* random: STR strlen */ + if (e) { *err = e; return false; } + } + } + if (!col) return false; + if (col->type != RAY_ENCCOL && col->type != RAY_STR && col->type != RAY_SYM) return false; *out_vec = col; return true; } /* Materialize a scalar (atom or len-1 vector) into a full-length vector so * group-aggregation loops can read row-wise without out-of-bounds access. */ +static ray_t* materialize_broadcast_input_fill(ray_t* src, int64_t nrows); + +/* The fill copies the source's null payload (sentinel / NaN / empty) into + * every row, but every aggregation loop gates its null skip on HAS_NULLS: + * without the attr a broadcast 0Nl was summed as INT64_MIN per row. Mark the + * result nullable when the source is a null atom or a nullable vector. BOOL + * and U8 vectors have no null representation, so they never carry the attr. */ static ray_t* materialize_broadcast_input(ray_t* src, int64_t nrows) { + ray_t* out = materialize_broadcast_input_fill(src, nrows); + if (!out || RAY_IS_ERR(out) || nrows == 0) return out; + if (out->type == RAY_BOOL || out->type == RAY_U8) return out; + bool src_null = ray_is_atom(src) ? RAY_ATOM_IS_NULL(src) + : (src->attrs & RAY_ATTR_HAS_NULLS) != 0; + if (src_null) out->attrs |= RAY_ATTR_HAS_NULLS; + return out; +} + +static ray_t* materialize_broadcast_input_fill(ray_t* src, int64_t nrows) { if (!src || RAY_IS_ERR(src) || nrows < 0) return NULL; /* A STR atom has no fixed-width payload to copy: the switch below has no * case for it, and the NULL surfaced as "oom". */ @@ -8469,13 +9347,19 @@ static bool group_materialize_prod_slots(agg_prod_t* prod, ray_t** agg_vecs, /* ---- Scalar aggregate (n_keys==0): one flat scan, no GID, no hash ---- */ typedef struct scalar_ctx_s scalar_ctx_t; -typedef void (*scalar_range_fn_t)(scalar_ctx_t* c, da_accum_t* acc, - int64_t start, int64_t end); +/* A range kernel: rows [start, end) into the context's current chunk + * accumulator (c->acc); worker_id is the walk's worker (decode scratch). */ +typedef void (*scalar_range_fn_t)(void* ctx, uint32_t worker_id, int64_t start, int64_t end); struct scalar_ctx_s { void** agg_ptrs; int8_t* agg_types; ray_t** agg_cols; uint8_t* agg_strlen; + ray_t** sym_strings; /* borrowed sym snapshot for strlen-on-SYM aggs */ + uint32_t sym_count; + const ray_str_t** agg_str; /* strlen-on-STR: descriptors resolved once */ + const ray_sym_domain_raw_t* agg_raw; /* strlen-on-SYM: pinned vocabulary per agg (agg_raw_ok) */ + const uint8_t* agg_raw_ok; uint16_t* agg_ops; agg_linear_t* agg_linear; agg_prod_t* agg_prod; /* fused SUM/AVG(a*b) slots (may be NULL) */ @@ -8489,6 +9373,21 @@ struct scalar_ctx_s { * silently alias past that many aggregates. */ const bool* agg_int_null_has; int64_t* agg_int_null_sentinel; + /* Range reads (R-WALK). A plain context (staged false) reads whole + * columns: row_base 0, srcs/plain/piece_attrs/fail unused. A staged + * one (some input is generation 2) runs each task through + * ray_col_walk: agg_ptrs[a] then address row row_base of the piece, + * and piece_attrs[a] is the piece's SYM width. */ + int64_t row_base; + ray_col_src_t** srcs; /* per input; NULL: no column read (COUNT, fused, absent) */ + const void** plain; /* per input: a ready source's base, NULL for a staged one */ + const uint8_t* piece_attrs; + ray_scan_fail_t* fail; + bool staged; + /* Chunk route (sc_rows): per input, the earlier input reading the same + * column, whose piece it shares (one decode per vector); NULL, or an + * input's own index, for none. */ + const uint32_t* alias; /* One set of 1-slot accumulators per chunk of the scan (chunk shape: * red_chunk_rows). Chunk k's arrays live in the k-th block of * acc_words words, each at the word offset below; count is word 0, so @@ -8499,6 +9398,7 @@ struct scalar_ctx_s { int64_t n_scan; int64_t chunk_rows; scalar_range_fn_t range_fn; + da_accum_t* acc; /* the chunk being scanned (scalar_red_chunk_run) */ }; /* Aim acc's 1-slot arrays at chunk k's block. */ @@ -8514,6 +9414,56 @@ static void scalar_chunk_acc(const scalar_ctx_t* c, int64_t k, da_accum_t* acc) if (c->off_nn) acc->nn_count = blk + c->off_nn; } +/* SYM attrs (width) of input a in this context: the piece's when staged. */ +static inline uint8_t scalar_attrs(const scalar_ctx_t* c, uint32_t a) { + if (c->piece_attrs) return c->piece_attrs[a]; + return c->agg_cols[a] ? c->agg_cols[a]->attrs : 0; +} + +/* The domain SYM input a's ids resolve over (the bound source's when the + * context is staged; the plain column's otherwise). */ +static inline struct ray_sym_domain_s* scalar_sym_dom(const scalar_ctx_t* c, uint32_t a) { + if (c->srcs && c->srcs[a] && c->srcs[a]->dom) return c->srcs[a]->dom; + return ray_sym_vec_domain(c->agg_cols[a]); +} + +typedef void (*scalar_body_fn)(scalar_ctx_t*, uint32_t, int64_t, int64_t); +typedef struct { + scalar_ctx_t* c; + scalar_body_fn body; +} scalar_piece_ctx_t; + +/* One piece [b, e): a copy of the context whose pointers address row b. */ +static void scalar_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + scalar_piece_ctx_t* pc = (scalar_piece_ctx_t*)ctx; + scalar_ctx_t local = *pc->c; + uint32_t n = local.n_aggs ? local.n_aggs : 1; + void* ptrs[n]; + uint8_t attrs[n]; + for (uint32_t a = 0; a < local.n_aggs; a++) { + uint32_t q = local.alias ? local.alias[a] : a; + ptrs[a] = (void*)p[q].data; /* NULL for an input without a source */ + attrs[a] = p[q].attrs; + } + local.row_base = b; + local.agg_ptrs = ptrs; + local.piece_attrs = attrs; + pc->body(&local, wid, b, e); +} + +/* R-WALK driver: a plain context runs `body` as today; a staged one by + * pieces, and a range error is noted keyed by the task's first row. + * Morsels a selection rejects whole are not read. */ +static void scalar_run_staged(scalar_ctx_t* c, uint32_t wid, int64_t start, int64_t end, + scalar_body_fn body) { + if (!c->staged) { body(c, wid, start, end); return; } + if (ray_scan_fail_skip(c->fail, start)) return; + scalar_piece_ctx_t pc = { c, body }; + ray_t* err = group_sel_walk((ray_col_src_t* const*)c->srcs, c->plain, c->n_aggs, c->rowsel, + start, end, &pc, wid, scalar_piece); + if (err) ray_scan_fail_note(c->fail, start, err); +} + static inline int64_t scalar_i64_at(const void* ptr, int8_t type, int64_t r) { return read_col_i64(ptr, r, type, 0); /* attrs=0: agg columns are numeric, never SYM */ } @@ -8566,32 +9516,158 @@ static inline void group_i128_sum_i64_range(const int64_t* restrict x, int64_t n /* Tight SIMD-friendly loop for single SUM/AVG on i64 (no mask). * Note: the int64 sum wraps (SUM's contract); an integer AVG also carries * the high word (acc->sum_hi) so it divides the exact 128-bit total. */ -static void scalar_sum_i64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { - const int64_t* restrict data = (const int64_t*)c->agg_ptrs[0]; +static void scalar_sum_i64_body(scalar_ctx_t* c, uint32_t worker_id, int64_t start, int64_t end) { + da_accum_t* acc = c->acc; + const int64_t* restrict data = (const int64_t*)c->agg_ptrs[0] + (start - c->row_base); + int64_t n = end - start; if (acc->sum_hi) { - group_i128_sum_i64_range(data + start, end - start, - &acc->sum_hi[0], (uint64_t*)&acc->sum[0].i); + group_i128_sum_i64_range(data, n, &acc->sum_hi[0], (uint64_t*)&acc->sum[0].i); } else { int64_t sum = 0; - for (int64_t r = start; r < end; r++) + for (int64_t r = 0; r < n; r++) sum = wrap_add_i64(sum, data[r]); acc->sum[0].i = wrap_add_i64(acc->sum[0].i, sum); } - acc->count[0] += end - start; + acc->count[0] += n; +} + +static void scalar_sum_i64_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + scalar_run_staged((scalar_ctx_t*)ctx, worker_id, start, end, scalar_sum_i64_body); } -/* Tight SIMD-friendly loop for single SUM/AVG on f64 (no mask) */ -static void scalar_sum_f64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { - const double* restrict data = (const double*)c->agg_ptrs[0]; - double sum = 0.0; - for (int64_t r = start; r < end; r++) - sum += data[r]; - acc->sum[0].f += sum; +/* Tight loop for single SUM/AVG on f64 (no mask), by explicit lanes: row r + * adds into lane r mod SC_F64_LANES, each lane in row order, and the task's + * partial is the lanes combined in one fixed order. The answer therefore + * depends only on the rows each task covers, never on how a task's rows are + * cut into pieces: a staged task reads zero-copy pieces with its lanes + * carried across them and gives generation 0's bits for the same task. + * + * The release build reassociates float math (-fassociative-math), so every + * intermediate the order depends on is pinned with SC_F64_PIN: an empty asm + * that claims to read and write the value, which no compiler may move an + * addition across. GCC-compatible compilers (gcc, clang, emscripten) pin + * on every target: in a vector register on x86 and aarch64, through memory + * elsewhere. Other compilers get no pin: the guarantee there rests on the + * compiler not reassociating (MSVC's default /fp:precise does not). */ +#define SC_F64_LANES 8 +#if defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) +#define SC_F64_PIN(v) __asm__("" : "+x"(v)) +#elif defined(__GNUC__) && defined(__aarch64__) +#define SC_F64_PIN(v) __asm__("" : "+w"(v)) +#elif defined(__GNUC__) +#define SC_F64_PIN(v) __asm__("" : "+m"(v)) +#else +#define SC_F64_PIN(v) ((void)0) +#endif +typedef struct { double l[SC_F64_LANES]; } sc_f64_lanes_t; + +/* Rows [row0, row0 + n) at d into the lanes. */ +static void sc_f64_lanes_add(sc_f64_lanes_t* restrict s, const double* restrict d, int64_t row0, int64_t n) { + int64_t i = 0; + for (; i < n && ((row0 + i) & (SC_F64_LANES - 1)); i++) { + double v = s->l[(row0 + i) & (SC_F64_LANES - 1)] + d[i]; + SC_F64_PIN(v); + s->l[(row0 + i) & (SC_F64_LANES - 1)] = v; + } +#if defined(__GNUC__) && defined(__AVX__) + /* two 4-lane vectors: lanes {0..3} {4..7}, each lane still one + * row-order chain (a vector add is lane-wise): the same bits as the + * 2-lane and scalar forms below */ + typedef double sc_v4d __attribute__((vector_size(32))); + sc_v4d v0, v1; + memcpy(&v0, &s->l[0], 32); memcpy(&v1, &s->l[4], 32); + SC_F64_PIN(v0); SC_F64_PIN(v1); /* the head's last adds stay folded in */ + for (; i + SC_F64_LANES <= n; i += SC_F64_LANES) { + sc_v4d x0, x1; + memcpy(&x0, d + i, 32); memcpy(&x1, d + i + 4, 32); + v0 += x0; v1 += x1; + SC_F64_PIN(v0); SC_F64_PIN(v1); + } + memcpy(&s->l[0], &v0, 32); memcpy(&s->l[4], &v1, 32); +#elif defined(__GNUC__) + /* four 2-lane vectors: lanes {0,1} {2,3} {4,5} {6,7}, each lane still + * one row-order chain (a vector add is lane-wise) */ + typedef double sc_v2d __attribute__((vector_size(16))); + sc_v2d v0, v1, v2, v3; + memcpy(&v0, &s->l[0], 16); memcpy(&v1, &s->l[2], 16); + memcpy(&v2, &s->l[4], 16); memcpy(&v3, &s->l[6], 16); + SC_F64_PIN(v0); SC_F64_PIN(v1); SC_F64_PIN(v2); SC_F64_PIN(v3); + for (; i + SC_F64_LANES <= n; i += SC_F64_LANES) { + sc_v2d x0, x1, x2, x3; + memcpy(&x0, d + i, 16); memcpy(&x1, d + i + 2, 16); + memcpy(&x2, d + i + 4, 16); memcpy(&x3, d + i + 6, 16); + v0 += x0; v1 += x1; v2 += x2; v3 += x3; + SC_F64_PIN(v0); SC_F64_PIN(v1); SC_F64_PIN(v2); SC_F64_PIN(v3); + } + memcpy(&s->l[0], &v0, 16); memcpy(&s->l[2], &v1, 16); + memcpy(&s->l[4], &v2, 16); memcpy(&s->l[6], &v3, 16); +#else + for (; i + SC_F64_LANES <= n; i += SC_F64_LANES) + for (int l = 0; l < SC_F64_LANES; l++) { double v = s->l[l] + d[i + l]; SC_F64_PIN(v); s->l[l] = v; } +#endif + for (; i < n; i++) { + double v = s->l[(row0 + i) & (SC_F64_LANES - 1)] + d[i]; + SC_F64_PIN(v); + s->l[(row0 + i) & (SC_F64_LANES - 1)] = v; + } +} + +static double sc_f64_lanes_total(const sc_f64_lanes_t* s) { + double a = s->l[0] + s->l[1]; SC_F64_PIN(a); + double b = s->l[2] + s->l[3]; SC_F64_PIN(b); + double c = s->l[4] + s->l[5]; SC_F64_PIN(c); + double d = s->l[6] + s->l[7]; SC_F64_PIN(d); + double ab = a + b; SC_F64_PIN(ab); + double cd = c + d; SC_F64_PIN(cd); + return ab + cd; +} + +static void scalar_f64_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sc_f64_lanes_add((sc_f64_lanes_t*)ctx, (const double*)p[0].data, b, e - b); +} + +/* Test hook (internal.h): rows [0, n) of d summed as one block at row0 and + * as the pieces cut at cuts[] (ascending, inside (0, n)) through the staged + * piece function; both totals out. The engine's tasks and pieces start + * 1024-aligned, so only this hook reaches an unaligned piece start. */ +void ray_group_test_f64_lanes(const double* d, int64_t row0, int64_t n, const int64_t* cuts, + int ncuts, double* whole, double* cut) { + sc_f64_lanes_t a = { { 0 } }, b = { { 0 } }; + sc_f64_lanes_add(&a, d, row0, n); + *whole = sc_f64_lanes_total(&a); + int64_t lo = 0; + for (int k = 0; k <= ncuts; k++) { + int64_t hi = k < ncuts ? cuts[k] : n; + ray_col_piece_t p = { .data = d + lo }; + scalar_f64_piece(&b, 0, row0 + lo, row0 + hi, &p); + lo = hi; + } + *cut = sc_f64_lanes_total(&b); +} + +static void scalar_sum_f64_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + scalar_ctx_t* c = (scalar_ctx_t*)ctx; + da_accum_t* acc = c->acc; + sc_f64_lanes_t lanes = { { 0 } }; + if (!c->staged) { + sc_f64_lanes_add(&lanes, (const double*)c->agg_ptrs[0] + start, start, end - start); + } else { + if (ray_scan_fail_skip(c->fail, start)) return; + ray_t* err = ray_col_walk(c->srcs, c->plain, 1, start, end, false, &lanes, worker_id, scalar_f64_piece); + if (err) { ray_scan_fail_note(c->fail, start, err); return; } + } + acc->sum[0].f += sc_f64_lanes_total(&lanes); acc->count[0] += end - start; } -/* Tight loop for single SUM/AVG on integer linear expression (no mask). */ -static void scalar_sum_linear_i64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { +/* Tight loop for single SUM/AVG on integer linear expression (no mask). + * Its terms are whole-column pointers read at absolute rows: the plan + * declines a term that is not ready (try_linear_sumavg_input_i64), and as + * the only input it never runs in a staged context. */ +static void scalar_sum_linear_i64_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + scalar_ctx_t* c = (scalar_ctx_t*)ctx; + da_accum_t* acc = c->acc; const agg_linear_t* lin = &c->agg_linear[0]; int64_t n = end - start; @@ -8605,7 +9681,7 @@ static void scalar_sum_linear_i64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t s bool bare = lin->n_terms == 1 && lin->coeff_i64[0] == 1 && lin->bias_i64 == 0 && lin->term_ptrs[0]; int8_t t0 = lin->term_types[0]; - if (bare && (t0 == RAY_I64 || t0 == RAY_TIMESTAMP)) { + if (bare && (t0 == RAY_I64 || t0 == RAY_TIMESPAN || t0 == RAY_TIMESTAMP)) { group_i128_sum_i64_range((const int64_t*)lin->term_ptrs[0] + start, n, &acc->sum_hi[0], (uint64_t*)&acc->sum[0].i); } else if (bare && t0 != RAY_SYM) { @@ -8649,6 +9725,99 @@ static void scalar_sum_linear_i64_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t s acc->count[0] += n; } +/* An input the scalar route reads by pieces when it is staged: a fixed-width + * type and a streaming op that scalar_accum_row (or a tight kernel) computes + * from the values alone. A count of any type reads no values (it counts + * rows, nulls included, as on generation 0), so it never needs the column. + * Anything else (holistic and row-gathered aggregates, wide types) reads its + * plain column (R-RANDOM). */ +static bool scalar_stageable(int8_t t, uint16_t op) { + if (op == OP_COUNT) return true; + switch (t) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F32: case RAY_F64: case RAY_SYM: + break; + default: + return false; + } + switch (op) { + case OP_SUM: case OP_AVG: case OP_MIN: case OP_MAX: + case OP_FIRST: case OP_LAST: case OP_PROD: case OP_ALL: case OP_ANY: + case OP_VAR: case OP_VAR_POP: case OP_STDDEV: case OP_STDDEV_POP: + return !agg_needs_row_gather(t, op); + default: + return false; + } +} + +/* Take `plain` (a source's plain column, borrowed) into a caller's slot: + * retained and owned. NULL or an owned error. */ +static ray_t* group_own_plain(ray_t* plain, ray_t** vec, uint8_t* owned) { + if (!plain) return ray_error("domain", "aggregate input: no column"); + ray_retain(plain); + *vec = plain; + *owned = 1; + return NULL; +} + +/* A staged input's plain column for a site that reads whole columns: the + * source's materialization (a generation-2 column decodes once, through + * its once-state), retained and owned by the caller's slot. Callers: the + * scalar route's inputs outside scalar_stageable (holistic and row-gathered + * aggregates, wide types). */ +static ray_t* agg_unstage(ray_col_src_t* src, ray_t** vec, uint8_t* owned) { + ray_t* plain = NULL; + ray_t* err = ray_col_src_plain(src, &plain); /* random: unstage: scalar holistic or wide input */ + return err ? err : group_own_plain(plain, vec, owned); +} + +/* A zero-length column of a staged source's type standing in for it where + * a route reads the column's type, SYM width and domain (layouts, emits); + * NULL on OOM. */ +static ray_t* group_src_standin(const ray_col_src_t* s) { + ray_t* v = s->type == RAY_SYM ? ray_sym_vec_new(s->attrs & RAY_SYM_W_MASK, 0) + : ray_vec_new(s->type, 0); + if (!v || RAY_IS_ERR(v)) { + if (v) ray_error_free(v); + return NULL; + } + if (s->type == RAY_SYM && s->obj->type == RAY_ENCCOL) ray_enccol_adopt_domain(v, s->obj); + v->len = 0; + return v; +} + +/* The columns emit_agg_columns reads (type, SYM domain): agg_vecs, with a + * zero-length column of the source's type standing in for each staged + * input (a SYM one with its width and domain). NULL on OOM; release with + * scalar_emit_vecs_free. */ +static ray_t** scalar_emit_vecs(ray_t** hdr, ray_t** agg_vecs, ray_col_src_t** agg_srcs, uint32_t n_aggs) { + *hdr = NULL; + bool any = false; + for (uint32_t a = 0; a < n_aggs && !any; a++) any = !agg_vecs[a] && agg_srcs[a]; + if (!any) return agg_vecs; + ray_t** ev = (ray_t**)scratch_calloc(hdr, (size_t)(n_aggs ? n_aggs : 1) * sizeof(ray_t*)); + if (!ev) return NULL; + for (uint32_t a = 0; a < n_aggs; a++) { + ev[a] = agg_vecs[a]; + if (agg_vecs[a] || !agg_srcs[a]) continue; + ray_t* v = group_src_standin(agg_srcs[a]); + if (!v) { + for (uint32_t j = 0; j < a; j++) if (!agg_vecs[j] && ev[j]) ray_release(ev[j]); + scratch_free(*hdr); + *hdr = NULL; + return NULL; + } + ev[a] = v; + } + return ev; +} + +static void scalar_emit_vecs_free(ray_t* hdr, ray_t** ev, ray_t** agg_vecs, uint32_t n_aggs) { + if (ev == agg_vecs) return; + for (uint32_t a = 0; a < n_aggs; a++) if (!agg_vecs[a] && ev[a]) ray_release(ev[a]); + scratch_free(hdr); +} + /* Generic scalar accumulation: handles all ops, all types, mask */ /* Inner scalar accumulation for a single row */ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) { @@ -8679,11 +9848,34 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) } else { if (!c->agg_ptrs[a]) continue; if (c->agg_strlen && c->agg_strlen[a]) { - iv = group_strlen_at(c->agg_cols[a], r); + if (!c->agg_cols[a]) { + /* Encoded SYM: read the current piece, not a whole column. */ + iv = sym_strlen_raw(c->agg_ptrs[a], r - c->row_base, + scalar_attrs(c, a), scalar_sym_dom(c, a)); + } else { + /* STR: the descriptor's length (a null is the empty + * string, length 0); SYM: a FILE-domain id from the pinned + * mapping, else through the borrowed snapshot. */ + if (c->agg_str[a]) { + iv = (int64_t)c->agg_str[a][r].len; + } else if (c->agg_raw_ok[a]) { /* a pinned SYM column */ + const ray_t* scol = c->agg_cols[a]; + int64_t sid = ray_read_sym(ray_data((ray_t*)scol), r, RAY_SYM, scol->attrs); + if (sid > 0 && sid < c->agg_raw[a].count) { + int64_t sl; + sl = raw_len_or0(&c->agg_raw[a], sid); + iv = (int64_t)sl; + } else { + iv = group_strlen_at_cached(scol, r, c->sym_strings, c->sym_count); + } + } else { + iv = group_strlen_at_cached(c->agg_cols[a], r, c->sym_strings, c->sym_count); + } + } fv = (double)iv; } else { - uint8_t attrs = c->agg_cols[a] ? c->agg_cols[a]->attrs : 0; - da_read_val(c->agg_ptrs[a], c->agg_types[a], attrs, r, &fv, &iv); + da_read_val(c->agg_ptrs[a], c->agg_types[a], scalar_attrs(c, a), + r - c->row_base, &fv, &iv); } } uint16_t op = c->agg_ops[a]; @@ -8749,7 +9941,7 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) else if (c->agg_types[a] == RAY_SYM && !int_null) { /* Lex compare for SYM; INT64_MAX = "not seen yet". */ if (acc->min_val[a].i == INT64_MAX || - sym_lex_lt(ray_sym_vec_domain(c->agg_cols[a]), iv, acc->min_val[a].i)) + sym_lex_lt(scalar_sym_dom(c, a), iv, acc->min_val[a].i)) acc->min_val[a].i = iv; } else if (!int_null) { if (iv < acc->min_val[a].i) acc->min_val[a].i = iv; } @@ -8758,7 +9950,7 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) if (is_f) { if (fv == fv && fv > acc->max_val[a].f) acc->max_val[a].f = fv; } else if (c->agg_types[a] == RAY_SYM && !int_null) { if (acc->max_val[a].i == INT64_MIN || - sym_lex_gt(ray_sym_vec_domain(c->agg_cols[a]), iv, acc->max_val[a].i)) + sym_lex_gt(scalar_sym_dom(c, a), iv, acc->max_val[a].i)) acc->max_val[a].i = iv; } else if (!int_null) { if (iv > acc->max_val[a].i) acc->max_val[a].i = iv; } @@ -8767,8 +9959,9 @@ static inline void scalar_accum_row(scalar_ctx_t* c, da_accum_t* acc, int64_t r) } } -static void scalar_accum_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { - const int64_t* match_idx = c->match_idx; +static void scalar_accum_body(scalar_ctx_t* c, uint32_t worker_id, int64_t start, int64_t end) { + da_accum_t* acc = c->acc; + const int64_t* match_idx = c->match_idx; /* NULL whenever staged */ for (int64_t i = start; i < end; i++) { int64_t r = match_idx ? match_idx[i] : i; @@ -8777,34 +9970,352 @@ static void scalar_accum_fn(scalar_ctx_t* c, da_accum_t* acc, int64_t start, int } } -/* Chunk k of the keyless scan into its own accumulators. Below the - * parallel threshold the scan is one chunk taken in one pass; above it each - * chunk is walked RED_BLOCK rows at a time, with scan read-ahead. */ -static void scalar_chunk_run(scalar_ctx_t* c, int64_t k) { - da_accum_t acc; - scalar_chunk_acc(c, k, &acc); - for (uint32_t a = 0; a < c->n_aggs; a++) { - bool fp = group_fp_type(c->agg_types[a]); - if (acc.min_val) { - if (fp) acc.min_val[a].f = DBL_MAX; else acc.min_val[a].i = INT64_MAX; - } - if (acc.max_val) { - if (fp) acc.max_val[a].f = -DBL_MAX; else acc.max_val[a].i = INT64_MIN; +static void scalar_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + scalar_run_staged((scalar_ctx_t*)ctx, worker_id, start, end, scalar_accum_body); +} + +/* ---- The scalar route by storage chunks (P3: statistics under a selection) ---- + * When every input has a rule here, a staged context walks each task's + * rows chunk by chunk (scalar_chunk_fn). A task (RAY_COL_BLOCK_ROWS rows, + * or any cut) need not hold a whole chunk, so every task holding part of a + * chunk decides the chunk level alike and the one holding its first row + * folds it; a whole-chunk task would leave the last workers a chunk each + * (measured 4% on a selection that decodes). Each chunk is answered at the coarsest level its + * selection allows, input by input: + * 1. every row selected: the chunk's directory statistics; + * 2. otherwise, or for an input the directory cannot answer, each fully + * selected vector from its view (sums) or its descriptor (extremes); + * 3. every other vector (partly selected, or no rule) through the piece + * driver and scalar_accum_row, reading only the inputs left. + * What lands in da_accum_t is what scalar_accum_row adds over the same + * rows: sum (low word, wrapping) and sum_hi with carry, nn_count by the + * non-null rows, min / max folded with its strict compares, count[0] by + * the selected rows. Statistics only answer, never size anything. */ +enum { SC_RULE_NONE = 0, SC_RULE_COUNT, SC_RULE_SUM, SC_RULE_MM, SC_RULE_FMM }; + +/* The rule of an input: COUNT reads nothing (ray_count_fn: the selected + * rows); integer SUM / AVG over the summable types; integer and temporal + * MIN / MAX (never SYM: ids are not ordered, #738); float MIN / MAX (D4). + * Float SUM / AVG / VAR / STDDEV, DATE / TIMESTAMP AVG and the rest keep + * the block dispatch, so their accumulation order is generation 0's. */ +static uint8_t scalar_chunk_rule(int8_t t, uint16_t op) { + if (op == OP_COUNT) return SC_RULE_COUNT; + bool isum = t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || + t == RAY_I64 || t == RAY_TIME; + if (op == OP_SUM || op == OP_AVG) return isum ? SC_RULE_SUM : SC_RULE_NONE; + if (op == OP_MIN || op == OP_MAX) { + if (isum || t == RAY_DATE || t == RAY_TIMESTAMP) return SC_RULE_MM; + if (t == RAY_F32 || t == RAY_F64) return SC_RULE_FMM; + } + return SC_RULE_NONE; +} + +/* A directory chunk: rows [lo, hi), chunk `chunk` of the columns. */ +typedef struct { + int64_t lo, hi; + int64_t chunk; +} sc_unit_t; + +typedef struct { + scalar_ctx_t* c; + const uint8_t* rule; /* per input */ + int64_t nrows; +} sc_chunk_ctx_t; + +/* Selected rows of [lo, hi): whole segments by their flags, MIX ones by + * their sorted local positions. */ +static int64_t sc_sel_rows(ray_t* sel, int64_t lo, int64_t hi) { + if (!sel) return hi - lo; + const int64_t M = RAY_MORSEL_ELEMS; + const uint8_t* flags = ray_rowsel_flags(sel); + const uint32_t* off = ray_rowsel_offsets(sel); + const uint16_t* idx = ray_rowsel_idx(sel); + int64_t n = 0; + for (int64_t sg = lo / M; sg * M < hi; sg++) { + int64_t a = sg * M > lo ? sg * M : lo, b = (sg + 1) * M < hi ? (sg + 1) * M : hi; + uint8_t f = flags[sg]; + if (f == RAY_SEL_ALL) { n += b - a; continue; } + if (f == RAY_SEL_NONE) continue; + uint32_t i0 = off[sg], i1 = off[sg + 1]; + if (a == sg * M && b == (sg + 1) * M) { n += i1 - i0; continue; } + /* first positions >= a and >= b, local to the segment */ + uint16_t la = (uint16_t)(a - sg * M); + uint32_t x = i0, y = i1; + while (x < y) { uint32_t m = x + ((y - x) >> 1); if (idx[m] < la) x = m + 1; else y = m; } + uint32_t pa = x; + y = i1; + if (b - sg * M < M) { + uint16_t lb = (uint16_t)(b - sg * M); + while (x < y) { uint32_t m = x + ((y - x) >> 1); if (idx[m] < lb) x = m + 1; else y = m; } + } else { + x = i1; + } + n += x - pa; + } + return n; +} + +/* Input a's column when it is a stored single-file generation-2 one + * holding unit u, *obj its object; NULL for a plain or synthetic one, read + * by rows (a ragged partition's stand-in holds what its rows hold: all + * null, or BOOL / U8 zeros, ray_null_fill). */ +static ray_enccol_t* sc_unit_col(const sc_chunk_ctx_t* cc, uint32_t a, const sc_unit_t* u, ray_t** obj) { + const ray_col_src_t* s = cc->c->srcs[a]; + ray_t* o = s->obj; + if (!o || o->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e = ray_enccol_of(o); + if (!e || e->kind != RAY_ENCCOL_SINGLE || e->synthetic || e->type != s->type || + e->len != cc->nrows || u->chunk >= e->n_chunks) return NULL; + *obj = o; + return e; +} + +/* Fold `rows` fully selected rows of input a from their statistics: the + * null count, the extremes when has_mm (logical values; a float's bits), + * the exact sum when has_sum; acc NULL only decides. False: the rows are + * read instead (no rule, + * no extremes for non-null rows, a non-finite float extreme, nulls in a + * BOOL / U8 input whose kernel counts every row). */ +static bool sc_fold(scalar_ctx_t* c, da_accum_t* acc, uint32_t a, uint8_t rule, int64_t rows, + int64_t n_nulls, bool has_mm, int64_t mn, int64_t mx, + bool has_sum, int64_t s_hi, uint64_t s_lo) { + int8_t t = c->agg_types[a]; + if (n_nulls < 0 || n_nulls > rows || ((t == RAY_BOOL || t == RAY_U8) && n_nulls)) return false; + int64_t nn = rows - n_nulls; + bool is_min = c->agg_ops[a] == OP_MIN; + if (rule == SC_RULE_SUM) { + if (!has_sum) return false; + if (!acc) return true; + if (acc->sum_hi) ray_i128_add128(&acc->sum_hi[a], (uint64_t*)&acc->sum[a].i, s_hi, s_lo); + else acc->sum[a].i = wrap_add_i64(acc->sum[a].i, (int64_t)s_lo); + } else if (nn > 0) { + if (!has_mm) return false; /* non-null rows without extremes are read */ + if (rule == SC_RULE_FMM) { + double x; + int64_t b = is_min ? mn : mx; + memcpy(&x, &b, sizeof x); + if (!(fabs(x) <= DBL_MAX)) return false; /* finite only (D4) */ + if (!acc) return true; + if (is_min) { if (x < acc->min_val[a].f) acc->min_val[a].f = x; } + else { if (x > acc->max_val[a].f) acc->max_val[a].f = x; } + } else { + if (!acc) return true; + if (is_min) { if (mn < acc->min_val[a].i) acc->min_val[a].i = mn; } + else { if (mx > acc->max_val[a].i) acc->max_val[a].i = mx; } + } + } + if (acc && acc->nn_count) acc->nn_count[a] += nn; + return true; +} + +/* Input a over unit u, every row selected, from the chunk's directory + * (acc NULL: whether it would). */ +static bool sc_chunk_answer(const sc_chunk_ctx_t* cc, da_accum_t* acc, uint32_t a, const sc_unit_t* u) { + ray_t* obj; + const ray_col_src_t* s = cc->c->srcs[a]; + ray_enc_chunk_stat_t st; + if (!sc_unit_col(cc, a, u, &obj) || !ray_col_src_chunk_stat(s, u->chunk, &st) || + st.rows != u->hi - u->lo) return false; + return sc_fold(cc->c, acc, a, cc->rule[a], st.rows, st.null_count, st.has_minmax, st.min, st.max, + ray_encw_type_summable(s->type), st.sum_hi, st.sum_lo); +} + +/* Input a over vector j of unit u (vlen rows, every one selected, inside + * one task): a sum from the vector's view (on the caller's stack), extremes + * from its descriptor statistics. An error of the view or the descriptors + * declines: the read of the vector reports it as its decode would. */ +static bool sc_vec_answer(const sc_chunk_ctx_t* cc, da_accum_t* acc, uint32_t a, const sc_unit_t* u, + int64_t j, int64_t vlen, ray_enc_vview_t* vv) { + ray_t* obj; + const ray_col_src_t* s = cc->c->srcs[a]; + ray_enccol_t* e = sc_unit_col(cc, a, u, &obj); + if (!e) return false; + int64_t v = u->chunk * RAY_ENC_VECS_PER_CHUNK + j; + ray_t* err = NULL; + if (cc->rule[a] == SC_RULE_SUM) { + /* only the encodings with a sum rule build a view: a DICT view would + * check every code against its dictionary and then decode as well */ + const ray_enc_desc_t* d = &ray_enccol_descs(e, u->chunk)[j]; + if (!(d->encoding == RAY_ENC_CONST || d->encoding == RAY_ENC_FOR_BP || + (d->encoding == RAY_ENC_RLE && d->n_nulls == 0))) return false; + int rc = ray_col_src_vview(s, v, vv, &err); /* 0 for a materialized column: read in place */ + if (rc < 0) { ray_error_free(err); return false; } + int64_t hi, nn; uint64_t lo; + if (rc == 0 || vv->n != vlen || !ray_enc_vec_sum(vv, &hi, &lo, &nn)) return false; + return sc_fold(cc->c, acc, a, SC_RULE_SUM, vlen, vlen - nn, false, 0, 0, true, hi, lo); + } + int64_t mn, mx; uint32_t nnul; + /* false also for a vector without statistics (all null among them): read */ + if (!ray_col_src_vec_stat(s, v, &mn, &mx, &nnul)) return false; + return sc_fold(cc->c, acc, a, cc->rule[a], vlen, nnul, true, mn, mx, false, 0, 0); +} + +/* Rows [lo, hi) of the inputs marked in `need` through the piece driver: + * the others read nothing (scalar_accum_row skips an input without data). */ +static void sc_rows(scalar_ctx_t* c, uint32_t wid, int64_t lo, int64_t hi, const bool* need) { + uint32_t n = c->n_aggs ? c->n_aggs : 1; + ray_col_src_t* srcs[n]; + const void* plain[n]; + uint32_t alias[n]; + for (uint32_t a = 0; a < c->n_aggs; a++) { + srcs[a] = need[a] ? c->srcs[a] : NULL; + plain[a] = need[a] ? c->plain[a] : NULL; + alias[a] = a; + /* an input over a column an earlier one reads shares its piece */ + for (uint32_t q = 0; q < a && srcs[a]; q++) + if (srcs[q] && srcs[q]->obj == srcs[a]->obj && alias[q] == q) { + alias[a] = q; + srcs[a] = NULL; + plain[a] = NULL; + } + } + scalar_ctx_t local = *c; + local.srcs = srcs; + local.plain = plain; + local.alias = alias; + scalar_run_staged(&local, wid, lo, hi, scalar_accum_body); +} + +/* Rows [plo, phi) of unit u (one task's share of the chunk). Every share + * makes the chunk-level decision the same way from the chunk's selection + * and statistics; the share holding the chunk's first row folds them. */ +static void sc_unit_run(const sc_chunk_ctx_t* cc, uint32_t wid, const sc_unit_t* u, + int64_t plo, int64_t phi, ray_enc_vview_t* vv) { + scalar_ctx_t* c = cc->c; + da_accum_t* acc = c->acc; + if (ray_scan_fail_skip(c->fail, plo)) return; + int64_t sel = sc_sel_rows(c->rowsel, u->lo, u->hi); + if (sel == 0) return; + bool owner = plo == u->lo; + uint32_t n = c->n_aggs ? c->n_aggs : 1; + bool need[n], vneed[n], run_need[n], vdefer[n]; + for (uint32_t a = 0; a < n; a++) need[a] = vneed[a] = run_need[a] = vdefer[a] = false; + bool any = false; + for (uint32_t a = 0; a < c->n_aggs; a++) { + need[a] = cc->rule[a] != SC_RULE_COUNT && + !(sel == u->hi - u->lo && sc_chunk_answer(cc, owner ? acc : NULL, a, u)); + any |= need[a]; + } + if (!any) { if (owner) acc->count[0] += sel; return; } + for (uint32_t a = 0; a < c->n_aggs; a++) + if (need[a] && !c->plain[a]) ray_col_src_advise(c->srcs[a], plo, phi); + /* Consecutive vectors read by rows with the same inputs form one run + * (one piece walk). */ + int64_t run_lo = -1, run_hi = -1; + /* The chunk's vectors (its own grid, not the task's cut): one wholly + * inside [plo, phi) and wholly selected may answer from its statistics; + * the part of a vector the task holds at either edge is read by rows. */ + for (int64_t j = (plo - u->lo) / RAY_ENC_VEC; u->lo + j * RAY_ENC_VEC < phi; j++) { + int64_t vs = u->lo + j * RAY_ENC_VEC; + int64_t ve = vs + RAY_ENC_VEC < u->hi ? vs + RAY_ENC_VEC : u->hi; + int64_t vlo = vs > plo ? vs : plo, vhi = ve < phi ? ve : phi; + bool whole = vlo == vs && vhi == ve; + int64_t vsel = sc_sel_rows(c->rowsel, vlo, vhi); + if (vsel == 0) continue; + /* Folds keep row order: a float extreme from statistics is decided + * here and folded only after the pending run's rows (a -0.0 / +0.0 + * tie keeps the first row's zero, as the kernel's strict compares + * do). Sums and integer extremes are order-free and fold at once. */ + bool vany = false; + for (uint32_t a = 0; a < c->n_aggs; a++) { + bool stat_ok = need[a] && whole && vsel == ve - vs; + bool defer = stat_ok && cc->rule[a] == SC_RULE_FMM; + vneed[a] = need[a] && !(stat_ok && sc_vec_answer(cc, defer ? NULL : acc, a, u, j, ve - vs, vv)); + vdefer[a] = defer && !vneed[a]; + vany |= vneed[a]; + } + bool same = run_lo >= 0; + for (uint32_t a = 0; a < c->n_aggs && same; a++) same = vneed[a] == run_need[a]; + if (run_lo >= 0 && (!vany || !same)) { sc_rows(c, wid, run_lo, run_hi, run_need); run_lo = -1; } + for (uint32_t a = 0; a < c->n_aggs; a++) + if (vdefer[a]) (void)sc_vec_answer(cc, acc, a, u, j, ve - vs, vv); + if (!vany) { acc->count[0] += vsel; continue; } + if (run_lo < 0) { + run_lo = vlo; + for (uint32_t a = 0; a < c->n_aggs; a++) run_need[a] = vneed[a]; + } + run_hi = vhi; + } + if (run_lo >= 0) sc_rows(c, wid, run_lo, run_hi, run_need); +} + +/* A task's rows [start, end), chunk by chunk. The pool's grain is + * RAY_COL_BLOCK_ROWS, but ray_pool_dispatch re-derives an unaligned one when + * it clamps to its ring (beyond RAY_POOL_MAX_TASKS tasks, or a ring that + * cannot grow), so nothing here depends on the cut: a chunk is decided alike + * by every task holding part of it and folded by the one holding its first + * row, and a vector answers from statistics only inside one task. */ +static void scalar_chunk_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + const sc_chunk_ctx_t* cc = (const sc_chunk_ctx_t*)ctx; + ray_enc_vview_t vv; /* one view, on this task's stack */ + for (int64_t ch = start / RAY_ENC_CHUNK; ch * RAY_ENC_CHUNK < end; ch++) { + sc_unit_t u = { .lo = ch * RAY_ENC_CHUNK, .chunk = ch }; + u.hi = u.lo + RAY_ENC_CHUNK < cc->nrows ? u.lo + RAY_ENC_CHUNK : cc->nrows; + sc_unit_run(cc, wid, &u, start > u.lo ? start : u.lo, end < u.hi ? end : u.hi, &vv); + } +} + +static _Atomic(int64_t) g_scalar_test_grain; /* ray_group_test_scalar_grain */ +void ray_group_test_scalar_grain(int64_t rows) { atomic_store_explicit(&g_scalar_test_grain, rows, memory_order_relaxed); } + +/* Whether the scalar route's staged inputs share the chunk grid of their + * row space. A parted source never reaches this route (parted groups run + * per partition, each partition a single-file table), and one that did + * takes the block dispatch. */ +static bool sc_chunk_grid_ok(ray_col_src_t** srcs, const uint8_t* rule, uint32_t n_aggs, int64_t nrows) { + for (uint32_t a = 0; a < n_aggs; a++) + if (rule[a] != SC_RULE_COUNT && srcs[a] && (srcs[a]->parted || srcs[a]->len != nrows)) return false; + return nrows > 0; +} + +/* Chunk k of the keyless scan into its own accumulators (chunk shape: + * red_chunk_rows, a function of the row count alone), folded in chunk order + * by the caller: float sums associate the same way at any worker count and + * every run, and FIRST / LAST / PROD take each chunk's value in row order + * (#744). Below the parallel threshold the scan is one chunk taken in one + * pass; above it each chunk is walked RED_BLOCK rows at a time, with scan + * read-ahead for a plain input. A staged kernel walks its pieces + * (scalar_run_staged); the storage-chunk route (cc non-NULL) answers each + * chunk's rows by statistics or reads them (scalar_chunk_fn), the test + * grain cutting them further. */ +static void scalar_red_chunk_run(scalar_ctx_t* c, const sc_chunk_ctx_t* cc, uint32_t wid, int64_t k) { + da_accum_t acc; + scalar_chunk_acc(c, k, &acc); + for (uint32_t a = 0; a < c->n_aggs; a++) { + bool fp = group_fp_type(c->agg_types[a]); + if (acc.min_val) { + if (fp) acc.min_val[a].f = DBL_MAX; else acc.min_val[a].i = INT64_MAX; + } + if (acc.max_val) { + if (fp) acc.max_val[a].f = -DBL_MAX; else acc.max_val[a].i = INT64_MIN; } } + scalar_ctx_t local = *c; + local.acc = &acc; int64_t lo = k * c->chunk_rows; int64_t hi = c->n_scan - lo > c->chunk_rows ? lo + c->chunk_rows : c->n_scan; + if (cc) { + sc_chunk_ctx_t lcc = *cc; + lcc.c = &local; + int64_t tg = atomic_load_explicit(&g_scalar_test_grain, memory_order_relaxed); + int64_t step = tg > 0 ? tg : hi - lo; + for (int64_t b = lo; b < hi; b += step) + scalar_chunk_fn(&lcc, wid, b, hi - b > step ? b + step : hi); + return; + } int64_t step = c->n_scan < RAY_PARALLEL_THRESHOLD ? hi - lo : RED_BLOCK; for (int64_t b = lo; b < hi; b += step) { int64_t e = hi - b > step ? b + step : hi; - if (!c->match_idx) ray_pool_scan_at(c->n_scan, b, hi); - c->range_fn(c, &acc, b, e); + if (!c->match_idx && !c->staged) ray_pool_scan_at(c->n_scan, b, hi); + c->range_fn(&local, wid, b, e); } } -static void scalar_chunk_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - (void)worker_id; - for (int64_t k = start; k < end; k++) scalar_chunk_run((scalar_ctx_t*)ctx, k); +typedef struct { scalar_ctx_t* c; const sc_chunk_ctx_t* cc; } scalar_red_ctx_t; + +static void scalar_red_chunk_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + scalar_red_ctx_t* x = (scalar_red_ctx_t*)ctx; + for (int64_t k = start; k < end; k++) scalar_red_chunk_run(x->c, x->cc, wid, k); } /* Inner DA accumulation for a single row — shared by single-key and multi-key paths. @@ -8813,21 +10324,31 @@ static void scalar_chunk_fn(void* ctx, uint32_t worker_id, int64_t start, int64_ * across all rows). */ /* strlen of agg column a at row r. STR: the descriptor's length (a null * is the empty string, length 0). SYM: null is id 0; a FILE-domain entry's - * length is the u32 prefix in the pinned mapping; anything else resolves + * length is its index length byte in the pinned mapping; anything else resolves * as group_strlen_at_cached does. */ -static inline int64_t da_strlen_at(const da_ctx_t* c, uint32_t a, int64_t r) { +RAY_INLINE int64_t da_strlen_at(const da_ctx_t* c, uint32_t a, int64_t r, int64_t rr, + const bool staged) { const ray_t* col = c->agg_cols[a]; - if (col->type == RAY_STR) { - const ray_str_t* elems; const char* pool; (void)pool; - str_resolve(col, &elems, &pool); - return (int64_t)elems[r].len; + if (staged && c->piece_attrs && col->type == RAY_SYM) { + /* staged context: the id from the piece (row rr); agg_cols[a] is + * the column or its stand-in, carrying the domain */ + int64_t sid = ray_read_sym(c->agg_ptrs[a], rr, RAY_SYM, da_agg_attrs(c, a, staged)); + if (sid == 0) return 0; + if (c->agg_raw_ok && c->agg_raw_ok[a] && sid > 0 && sid < c->agg_raw[a].count) { + int64_t sl; + sl = raw_len_or0(&c->agg_raw[a], sid); + return (int64_t)sl; + } + return sym_strlen_raw(c->agg_ptrs[a], rr, da_agg_attrs(c, a, staged), ray_sym_vec_domain((ray_t*)col)); } + /* STR: descriptors resolved once at setup (every strlen-on-STR agg). */ + if (col->type == RAY_STR) return (int64_t)c->agg_str[a][r].len; if (col->type == RAY_SYM) { int64_t sid = ray_read_sym(ray_data((ray_t*)col), r, RAY_SYM, col->attrs); if (sid == 0) return 0; if (c->agg_raw_ok && c->agg_raw_ok[a] && sid > 0 && sid < c->agg_raw[a].count) { - size_t sl; - (void)ray_sym_domain_raw_str(&c->agg_raw[a], sid, &sl); + int64_t sl; + sl = raw_len_or0(&c->agg_raw[a], sid); return (int64_t)sl; } } @@ -8852,7 +10373,11 @@ static inline bool da_sym_lex_lt(const da_ctx_t* c, uint32_t a_idx, int64_t x, i return sym_lex_lt(ray_sym_vec_domain(c->agg_cols[a_idx]), x, y); } -static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64_t r) { +/* Row r (absolute: selection, FIRST/LAST order, fused-product terms) is + * read from the input pieces at rr = r - row_base. `staged` is constant + * per instance (see da_accum_body). */ +RAY_INLINE void da_accum_row_body(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64_t r, int64_t rr, + const bool staged) { uint8_t n_aggs = c->n_aggs; acc->count[gid]++; size_t base = (size_t)gid * n_aggs; @@ -8874,11 +10399,16 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 } if (!c->agg_ptrs[a]) continue; if (c->agg_strlen && c->agg_strlen[a]) { - acc->sum[idx].i = wrap_add_i64(acc->sum[idx].i, da_strlen_at(c, a, r)); + /* Length 0 is the empty string, the STR/SYM null: it adds + * nothing to the sum; an AVG keeps it out of the divisor + * through sl_null (exec_strlen maps it to null). */ + int64_t len = da_strlen_at(c, a, r, rr, staged); + acc->sum[idx].i = wrap_add_i64(acc->sum[idx].i, len); if (nn) nn[idx]++; + if (RAY_UNLIKELY(len == 0) && acc->sl_null) acc->sl_null[idx]++; } else if (f64m & ((uint64_t)1 << a)) { /* NaN payload = null, skip from sum. */ - double v = group_fp_at(c->agg_ptrs[a], c->agg_types[a], r); + double v = group_fp_at(c->agg_ptrs[a], c->agg_types[a], rr); if (RAY_LIKELY(v == v)) { acc->sum[idx].f += v; if (nn) nn[idx]++; } } else { /* NULL_I* sentinel = null, skip from sum. Only paid when @@ -8886,8 +10416,7 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 * INT_MIN value in a HAS_NULLS column is indistinguishable * from a null and is dropped — this is the standard cost of * sentinel-based null encoding for integers. */ - uint8_t v_attrs = c->agg_cols[a] ? c->agg_cols[a]->attrs : 0; - int64_t v = read_col_i64(c->agg_ptrs[a], r, c->agg_types[a], v_attrs); + int64_t v = read_col_i64(c->agg_ptrs[a], rr, c->agg_types[a], da_agg_attrs(c, a, staged)); if (RAY_LIKELY(!((inm >> a) & 1) || v != c->agg_int_null_sentinel[a])) { if (acc->sum_hi) ray_i128_add(&acc->sum_hi[idx], (uint64_t*)&acc->sum[idx].i, v); else acc->sum[idx].i = wrap_add_i64(acc->sum[idx].i, v); @@ -8926,11 +10455,14 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 fv = prod_val_f64(&c->agg_prod[a], r); iv = (int64_t)fv; } else if (c->agg_strlen && c->agg_strlen[a]) { - iv = da_strlen_at(c, a, r); - fv = (double)iv; + /* SUM/AVG(strlen) only: as the SUM/AVG fast path above. */ + int64_t len = da_strlen_at(c, a, r, rr, staged); + acc->sum[idx].i = wrap_add_i64(acc->sum[idx].i, len); + if (nn) nn[idx]++; + if (RAY_UNLIKELY(len == 0) && acc->sl_null) acc->sl_null[idx]++; + continue; } else { - uint8_t attrs = c->agg_cols[a] ? c->agg_cols[a]->attrs : 0; - da_read_val(c->agg_ptrs[a], c->agg_types[a], attrs, r, &fv, &iv); + da_read_val(c->agg_ptrs[a], c->agg_types[a], da_agg_attrs(c, a, staged), rr, &fv, &iv); } uint16_t op = c->agg_ops[a]; bool is_f = group_fp_type(c->agg_types[a]); @@ -8967,7 +10499,7 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 * finalises PEARSON/COV/WAVG/WSUM from (Σx,Σx²,Σy,Σy²,Σxy,n). */ double xv = is_f ? fv : (double)iv; double yv; int64_t yi; - da_read_val(c->agg_ptrs2[a], c->agg_types2[a], 0, r, &yv, &yi); + da_read_val(c->agg_ptrs2[a], c->agg_types2[a], 0, rr, &yv, &yi); bool y_is_f = group_fp_type(c->agg_types2[a]); double yval = y_is_f ? yv : (double)yi; bool y_null = y_is_f ? !(yval == yval) : false; @@ -9047,17 +10579,182 @@ static inline void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64 if (last_advanced) acc->last_row[gid] = r; } -static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { - da_ctx_t* c = (da_ctx_t*)ctx; +/* Off the hot loop: an id past the pinned mapping / snapshot. */ +static int64_t __attribute__((noinline, cold)) +da_sid_len_slow(const da_ctx_t* c, uint32_t a, int64_t r) { + return group_strlen_at_cached(c->agg_cols[a], r, c->sym_strings, c->sym_count); +} + +static int64_t __attribute__((noinline, cold)) +da_sid_len_piece_slow(const da_ctx_t* c, uint32_t a, int64_t rr) { + return sym_strlen_raw(c->agg_ptrs[a], rr, da_agg_attrs(c, a, true), + ray_sym_vec_domain((ray_t*)c->agg_cols[a])); +} + +/* strlen of SYM id sid (cell r of agg a): raw is the pinned FILE mapping or + * NULL, rt the runtime domain with the borrowed snapshot — both decided by + * the caller once. Same answer as da_strlen_at. */ +RAY_INLINE int64_t da_sid_len(const da_ctx_t* c, uint32_t a, int64_t sid, + const ray_sym_domain_raw_t* raw, bool rt, int64_t r, + int64_t rr, const bool staged) { + if (sid == 0) return 0; + if (raw && sid > 0 && sid < raw->count) { + int64_t sl; + sl = raw_len_or0(raw, sid); + return (int64_t)sl; + } + if (rt && sid > 0 && (uint64_t)sid < c->sym_count) { + ray_t* atom = c->sym_strings[sid]; + return atom ? (int64_t)ray_str_len(atom) : 0; + } + return staged ? da_sid_len_piece_slow(c, a, rr) : da_sid_len_slow(c, a, r); +} + +/* One SUM/AVG(strlen) beside COUNTs, one key, no row selection + * (c->sl_agg >= 0). Per block of rows the lengths are read first by a loop + * of the column's own kind — STR descriptors, or SYM ids at their width — + * and then folded by a loop of the key's width, so neither loop carries the + * other's dispatch nor da_accum_row's per-agg one. Keeps the state the + * SUM/AVG fast path keeps for it: count, the length sum, nn when allocated, + * sl_null for an AVG (COUNT emits from count alone). */ +#define DA_SL_BLK 512 +/* The two wrappers instantiate this with a constant mode. Piece pointers + * address row_base; lengths are consumed synchronously before the walk advances. */ +RAY_INLINE void da_accum_strlen_body(da_ctx_t* c, da_accum_t* acc, + int64_t start, int64_t end, const bool staged) { + const uint32_t sa = (uint32_t)c->sl_agg; + const size_t n_aggs = c->n_aggs; + int64_t* restrict count = acc->count; + da_val_t* restrict sum = acc->sum; + int64_t* nn = acc->nn_count; + int64_t* sln = acc->sl_null; + const int64_t kmin = c->key_mins[0]; + const bool ksym = c->key_types[0] == RAY_SYM; + const bool da_pf = c->n_slots >= 4096; + const ray_t* col = c->agg_cols[sa]; + const int64_t rb = staged ? c->row_base : 0; + /* Staged admission is SYM only; STR retains its whole-column descriptors. */ + const ray_str_t* desc = staged ? NULL : c->agg_str[sa]; + const void* ids = desc ? NULL : (staged ? c->agg_ptrs[sa] : ray_data((ray_t*)col)); + const uint8_t sw = (staged ? da_agg_attrs(c, sa, true) : col->attrs) & RAY_SYM_W_MASK; + const ray_sym_domain_raw_t* raw = + (!desc && c->agg_raw_ok && c->agg_raw_ok[sa]) ? &c->agg_raw[sa] : NULL; + const bool rt = !staged && !desc && c->sym_strings && + ray_sym_vec_domain((ray_t*)col) == ray_sym_runtime_domain(); + int64_t lens[DA_SL_BLK]; + #define DA_SL_SYM(T) \ + do { \ + const T* sp = (const T*)ids; \ + for (int64_t j = 0; j < n; j++) \ + lens[j] = da_sid_len(c, sa, (int64_t)sp[b0 + j - rb], raw, rt, \ + b0 + j, b0 + j - rb, staged); \ + } while (0) + #define DA_SL_PF_DIST 8 + #define DA_SL_FOLD(KTYPE, KCAST) \ + do { \ + const KTYPE* kp = (const KTYPE*)c->key_ptrs[0]; \ + for (int64_t j = 0; j < n; j++) { \ + int64_t r = b0 + j; \ + if (da_pf && RAY_LIKELY(r + DA_SL_PF_DIST < end)) { \ + int64_t pfk = (int64_t)KCAST kp[r + DA_SL_PF_DIST - rb]; \ + if (ksym && pfk == 0) pfk = kmin; \ + __builtin_prefetch(&count[(int32_t)(pfk - kmin)], 1, 1); \ + __builtin_prefetch(&sum[(size_t)(int32_t)(pfk - kmin) * n_aggs], 1, 1); \ + } \ + int64_t kv = (int64_t)KCAST kp[r - rb]; \ + if (ksym && kv == 0) kv = kmin; \ + int32_t gid = (int32_t)(kv - kmin); \ + count[gid]++; \ + size_t idx = (size_t)gid * n_aggs + sa; \ + int64_t len = lens[j]; \ + sum[idx].i = wrap_add_i64(sum[idx].i, len); \ + if (nn) nn[idx]++; \ + if (RAY_UNLIKELY(len == 0) && sln) sln[idx]++; \ + } \ + } while (0) + for (int64_t b0 = start; b0 < end; b0 += DA_SL_BLK) { + int64_t n = end - b0 < DA_SL_BLK ? end - b0 : DA_SL_BLK; + if (desc) { + for (int64_t j = 0; j < n; j++) lens[j] = (int64_t)desc[b0 + j].len; + } else { + switch (sw) { + case RAY_SYM_W8: DA_SL_SYM(uint8_t); break; + case RAY_SYM_W16: DA_SL_SYM(uint16_t); break; + case RAY_SYM_W32: DA_SL_SYM(uint32_t); break; + default: DA_SL_SYM(int64_t); break; + } + } + /* Key widths as da_accum_fn's single-key loop (sign-extend signed). */ + if (da_key_is_unsigned(c->key_types[0])) { + switch (c->key_esz[0]) { + case 1: DA_SL_FOLD(uint8_t, ); break; + case 2: DA_SL_FOLD(uint16_t, ); break; + case 4: DA_SL_FOLD(uint32_t, (int64_t)); break; + default: DA_SL_FOLD(int64_t, ); break; + } + } else { + switch (c->key_esz[0]) { + case 1: DA_SL_FOLD(int8_t, ); break; + case 2: DA_SL_FOLD(int16_t, ); break; + case 4: DA_SL_FOLD(int32_t, (int64_t)); break; + default: DA_SL_FOLD(int64_t, ); break; + } + } + } + #undef DA_SL_FOLD + #undef DA_SL_PF_DIST + #undef DA_SL_SYM +} +#undef DA_SL_BLK + +static void __attribute__((noinline)) +da_accum_strlen_fn(da_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { + da_accum_strlen_body(c, acc, start, end, false); +} + +static void __attribute__((noinline)) +da_accum_strlen_staged_fn(da_ctx_t* c, da_accum_t* acc, int64_t start, int64_t end) { + da_accum_strlen_body(c, acc, start, end, true); +} + +/* The row step, out of line once per instance (as before range reads): + * the plain one reads whole columns with no piece widths. */ +static void da_accum_row_plain(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64_t r, int64_t rr) { + da_accum_row_body(c, acc, gid, r, rr, false); +} + +static void da_accum_row_staged(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64_t r, int64_t rr) { + da_accum_row_body(c, acc, gid, r, rr, true); +} + +RAY_INLINE void da_accum_row(da_ctx_t* c, da_accum_t* acc, int32_t gid, int64_t r, int64_t rr, + const bool staged) { + if (staged) da_accum_row_staged(c, acc, gid, r, rr); + else da_accum_row_plain(c, acc, gid, r, rr); +} + +/* One body, two instances: da_accum_plain (whole columns: rb folds to 0 + * and the piece widths drop out, the pre-range-read codegen) and + * da_accum_staged (a piece of the R-WALK, rows read at r - row_base). */ +RAY_INLINE void da_accum_body(da_ctx_t* c, uint32_t worker_id, int64_t start, int64_t end, + const bool staged) { da_accum_t* acc = &c->accums[worker_id]; + const int64_t rb = staged ? c->row_base : 0; /* pieces: rows are read at r - rb */ uint8_t n_aggs = c->n_aggs; uint8_t n_keys = c->n_keys; const int64_t* match_idx = c->match_idx; + if (c->sl_agg >= 0) { + if (staged) da_accum_strlen_staged_fn(c, acc, start, end); + else da_accum_strlen_fn(c, acc, start, end); + return; + } + /* Fast path: single key — avoid composite GID loop overhead. * Templated by key element size: the entire loop is stamped out per width * so the compiler generates direct movzbl/movzwl/movl/movq — zero dispatch. */ #define DA_PF_DIST 8 + /* The prefetch row stays below `end`, the piece end when staged. */ #define DA_SINGLE_KEY_LOOP(KTYPE, KCAST) \ do { \ const KTYPE* kp = (const KTYPE*)c->key_ptrs[0]; \ @@ -9068,15 +10765,15 @@ static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t en if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, r)) continue; \ if (da_pf && RAY_LIKELY(i + DA_PF_DIST < end)) { \ int64_t pf_r = match_idx ? match_idx[i + DA_PF_DIST] : (i + DA_PF_DIST); \ - int64_t pfk = (int64_t)KCAST kp[pf_r]; \ + int64_t pfk = (int64_t)KCAST kp[pf_r - rb]; \ if (c->key_types[0] == RAY_SYM && pfk == 0) pfk = kmin; \ __builtin_prefetch(&acc->count[(int32_t)(pfk - kmin)], 1, 1); \ if (acc->sum) __builtin_prefetch( \ &acc->sum[(size_t)(int32_t)(pfk - kmin) * n_aggs], 1, 1); \ } \ - int64_t kv = (int64_t)KCAST kp[r]; \ + int64_t kv = (int64_t)KCAST kp[r - rb]; \ if (c->key_types[0] == RAY_SYM && kv == 0) kv = kmin; \ - da_accum_row(c, acc, (int32_t)(kv - kmin), r); \ + da_accum_row(c, acc, (int32_t)(kv - kmin), r, r - rb, staged); \ } \ } while (0) @@ -9113,11 +10810,11 @@ static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t en if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, r)) continue; \ if (_da_pf && RAY_LIKELY(i + DA_PF_DIST < end)) { \ int64_t pf_r = match_idx ? match_idx[i + DA_PF_DIST] : (i + DA_PF_DIST); \ - int32_t pf_gid = GID_FN(pf_r); \ + int32_t pf_gid = GID_FN(pf_r - rb); \ __builtin_prefetch(&acc->count[pf_gid], 1, 1); \ if (acc->sum) __builtin_prefetch(&acc->sum[(size_t)pf_gid * n_aggs], 1, 1); \ } \ - da_accum_row(c, acc, GID_FN(r), r); \ + da_accum_row(c, acc, GID_FN(r - rb), r, r - rb, staged); \ } \ } while (0) @@ -9182,6 +10879,68 @@ static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t en #undef DA_PF_DIST } +static void da_accum_plain(da_ctx_t* c, uint32_t worker_id, int64_t start, int64_t end) { + da_accum_body(c, worker_id, start, end, false); +} + +static void da_accum_staged(da_ctx_t* c, uint32_t worker_id, int64_t start, int64_t end) { + da_accum_body(c, worker_id, start, end, true); +} + +typedef void (*da_body_fn)(da_ctx_t*, uint32_t, int64_t, int64_t); +typedef struct { + da_ctx_t* c; + da_body_fn body; +} da_piece_ctx_t; + +/* One piece [b, e): a copy of the context whose key and input pointers + * address row b, with the pieces' SYM widths. */ +static void da_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + da_piece_ctx_t* pc = (da_piece_ctx_t*)ctx; + da_ctx_t local = *pc->c; + uint32_t nk = local.n_keys, na = local.n_aggs; + void* kp[nk ? nk : 1]; + uint8_t kat[nk ? nk : 1], kesz[nk ? nk : 1]; + void* ap[na ? na : 1]; + void* ap2[na ? na : 1]; + uint8_t attrs[local.n_src ? local.n_src : 1]; + for (uint32_t i = 0; i < local.n_src; i++) attrs[i] = p[i].attrs; + for (uint32_t k = 0; k < nk; k++) { + kp[k] = (void*)p[k].data; + kat[k] = local.key_types[k] == RAY_SYM ? p[k].attrs : local.key_attrs[k]; + kesz[k] = ray_sym_elem_size(local.key_types[k], kat[k]); + } + for (uint32_t a = 0; a < na; a++) { + ap[a] = (void*)p[nk + a].data; /* NULL for an input without a source */ + ap2[a] = (void*)p[nk + na + a].data; + } + local.row_base = b; + local.key_ptrs = kp; + local.key_attrs = kat; + local.key_esz = kesz; + local.agg_ptrs = ap; + local.agg_ptrs2 = ap2; + local.piece_attrs = attrs; + pc->body(&local, wid, b, e); +} + +/* R-WALK driver: a plain context runs `body` over [start, end) as today; a + * staged one by pieces (morsels a selection rejects whole are not read), + * and a range error is noted keyed by the task's first row. */ +static void da_run_staged(da_ctx_t* c, uint32_t wid, int64_t start, int64_t end, da_body_fn body) { + if (!c->staged) { body(c, wid, start, end); return; } + if (ray_scan_fail_skip(c->fail, start)) return; + da_piece_ctx_t pc = { c, body }; + ray_t* err = group_sel_walk(c->srcs, c->plain, c->n_src, c->rowsel, start, end, &pc, wid, da_piece); + if (err) ray_scan_fail_note(c->fail, start, err); +} + +static void da_accum_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + da_ctx_t* c = (da_ctx_t*)ctx; + if (!c->staged) { da_accum_plain(c, worker_id, start, end); return; } + da_run_staged(c, worker_id, start, end, da_accum_staged); +} + /* ---- slot-partitioned accumulate -------------------------------------- * For a pool with more workers than the per-worker slot budget allows. * Pass 1 (nw tasks, contiguous row ranges in order): each row's group is @@ -9229,7 +10988,7 @@ static void da_part_scatter_fn(void* raw, uint32_t wid, int64_t task, int64_t ta for (int64_t i = start; i < end; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, r)) continue; - uint32_t t = (uint32_t)da_composite_gid(c, r) / p->span; + uint32_t t = (uint32_t)da_composite_gid(c, r) / p->span; /* plain context only */ if (!da_bucket_push(&mine[t], (int32_t)r)) { atomic_store_explicit(&p->oom, 1, memory_order_relaxed); return; @@ -9247,7 +11006,7 @@ static void da_part_drain_fn(void* raw, uint32_t wid, int64_t start, int64_t end const da_bucket_t* b = &p->buckets[(size_t)w * p->k + t]; for (int64_t j = 0; j < b->len; j++) { int64_t r = b->data[j]; - da_accum_row(c, acc, da_composite_gid(c, r), r); + da_accum_row(c, acc, da_composite_gid(c, r), r, r, false); } } } @@ -9393,6 +11152,10 @@ static void da_merge_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { for (uint32_t a = 0; a < n_aggs; a++) merged->nn_count[base + a] += wa->nn_count[base + a]; } + if (merged->sl_null && wa->sl_null) { + for (uint32_t a = 0; a < n_aggs; a++) + merged->sl_null[base + a] += wa->sl_null[base + a]; + } merged->count[s] += wa->count[s]; } } @@ -9463,16 +11226,18 @@ typedef struct { int64_t* row_gid; /* output [nrows] */ const int64_t* match_idx; ray_t* rowsel; /* non-NULL when selection carried as rowsel */ + grp_rr_t rr; /* range reads (grp_run) */ } reprobe_ctx_t; /* Resolve one source row to the flat partition-local group id. The caller * owns reusable key staging so a scan performs no per-row allocation. */ -static inline int64_t reprobe_flat_gid(const reprobe_ctx_t* c, int64_t row, - int64_t* ek_buf, char* keybuf) { +static inline int64_t reprobe_flat_gid(const reprobe_ctx_t* c, const grp_view_t* v, + int64_t row, int64_t* ek_buf, char* keybuf) { uint32_t nk = c->n_keys; int8_t* key_types = c->key_types; - void** key_data = c->key_data; - uint8_t* key_attrs = c->key_attrs; + void* const* key_data = v->key_data; + const uint8_t* key_attrs = v->key_attrs; + const int64_t kb = v->key_base; /* keys are read at row - kb */ ray_t** key_vecs = c->key_vecs; uint8_t nullable = c->nullable_mask; const uint8_t* const kflags = c->layout->key_flags; @@ -9481,7 +11246,8 @@ static inline int64_t reprobe_flat_gid(const reprobe_ctx_t* c, int64_t row, const int64_t* lookup_keys; if (c->layout->any_inline_str) { - h = inline_build_keys(c->layout, key_types, key_data, key_attrs, + /* inline STR: a wide-key layout, whose keys are whole columns */ + h = inline_build_keys(c->layout, key_types, c->key_data, key_attrs, c->key_pool, key_vecs, nullable, row, keybuf); lookup_keys = (const int64_t*)keybuf; } else { @@ -9496,11 +11262,11 @@ static inline int64_t reprobe_flat_gid(const reprobe_ctx_t* c, int64_t row, * stay in lockstep with hash_keys_inline (rehash/merge/lookup). */ for (uint32_t k = 0; k < nk; k++) { if (__builtin_expect(nullable && ray_key_may_be_null(key_vecs[k]) - && ray_vec_is_null(key_vecs[k], row), 0)) { + && grp_key_null(key_vecs[k], v, k, key_types[k], row), 0)) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); ek_buf[k] = 0; } else { - ek_buf[k] = read_col_i64(key_data[k], row, key_types[k], key_attrs[k]); + ek_buf[k] = read_col_i64(key_data[k], row - kb, key_types[k], key_attrs[k]); } } h = ght_hash_lanes(ek_buf, (uint32_t)nk + null_words); @@ -9509,23 +11275,23 @@ static inline int64_t reprobe_flat_gid(const reprobe_ctx_t* c, int64_t row, int8_t t = key_types[k]; uint64_t kh; bool is_null = nullable && ray_key_may_be_null(key_vecs[k]) - && ray_vec_is_null(key_vecs[k], row); + && grp_key_null(key_vecs[k], v, k, t, row); if (is_null) { nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); ek_buf[k] = 0; kh = ray_hash_i64(0); } else if (wide_any && (kflags[k] & GHT_KEYF_WIDE)) { ek_buf[k] = row; - kh = wide_key_hash_at(c->layout, k, key_data, c->key_pool, row); + kh = wide_key_hash_at(c->layout, k, c->key_data, c->key_pool, row); } else if (t == RAY_F64) { /* -0.0 -> +0.0 before BOTH the store and the hash — the * reprobe MUST derive the same bits phase 1 stored. */ - int64_t kv = group_key_f64_bits(key_data[k], row); + int64_t kv = group_key_f64_bits(key_data[k], row - kb); double dv; memcpy(&dv, &kv, 8); ek_buf[k] = kv; kh = ray_hash_f64(dv); } else { - int64_t kv = read_col_i64(key_data[k], row, t, key_attrs[k]); + int64_t kv = read_col_i64(key_data[k], row - kb, t, key_attrs[k]); ek_buf[k] = kv; kh = ray_hash_i64(kv); } @@ -9544,8 +11310,8 @@ static inline int64_t reprobe_flat_gid(const reprobe_ctx_t* c, int64_t row, return (int64_t)c->part_offsets[part] + local; } -static void reprobe_rows_fn(void* vctx, uint32_t worker_id, - int64_t start, int64_t end) { +static void reprobe_rows_body(void* vctx, const grp_view_t* v, uint32_t worker_id, + int64_t start, int64_t end) { (void)worker_id; reprobe_ctx_t* c = (reprobe_ctx_t*)vctx; /* Key lookup staging: ≤8 keys stay on the stack (ek_buf: 8 keys + 1 null @@ -9575,7 +11341,7 @@ static void reprobe_rows_fn(void* vctx, uint32_t worker_id, c->row_gid[row] = -1; continue; } - int64_t flat = reprobe_flat_gid(c, row, ek_buf, keybuf); + int64_t flat = reprobe_flat_gid(c, v, row, ek_buf, keybuf); if (flat < 0) { c->row_gid[row] = -1; } else { @@ -9586,6 +11352,15 @@ static void reprobe_rows_fn(void* vctx, uint32_t worker_id, scratch_free(rp_stage_hdr); /* NULL (inline staging) → no-op */ } +/* Rows a selection rejects in whole morsels are skipped unread: the caller + * pre-fills row_gid with -1. */ +static void reprobe_rows_fn(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { + reprobe_ctx_t* c = (reprobe_ctx_t*)vctx; + grp_view_t v = grp_view_whole(c->key_data, c->key_attrs); + grp_run(c, reprobe_rows_body, &v, &c->rr, c->match_idx ? NULL : c->rowsel, NULL, + worker_id, start, end); +} + /* Histogram + scatter for idx_buf construction. Identical pattern to * query.c's idxbuf_hist_fn / idxbuf_scat_fn — duplicated here to avoid * pulling a query.c-internal helper through internal.h. @@ -9746,15 +11521,303 @@ static int group_expr_src_syms(ray_graph_t* g, uint32_t root_id, * g->selection, so this materialization is unfiltered regardless of whether a * pushed-down WHERE is active (the per-partition sub-group applies the * filter, not the key materialization). */ + +/* Partition p's segment of column sym bound as a source (never decodes): + * NULL with s->obj NULL when the segment is missing, or an owned error. */ +static ray_t* grp_seg_bind(ray_t* tbl, int64_t sym, int64_t p, ray_col_src_t* s) { + memset(s, 0, sizeof *s); + ray_t* seg = ray_table_parted_seg(tbl, sym, p); /* borrowed */ + return seg ? ray_col_src_bind(seg, s) : NULL; +} + +/* Rows [lo, hi) of a bound segment source read by range (zero copy for a + * plain or already materialized segment, one vector at a time for an + * encoded one): fn(ctx, piece data, piece attrs, n) per piece. NULL, or an + * owned error. */ +typedef void (*grp_seg_fn)(void* ctx, const void* data, uint8_t attrs, int64_t n); +typedef struct { void* ctx; grp_seg_fn fn; } grp_seg_walk_t; +static void grp_seg_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + grp_seg_walk_t* w = (grp_seg_walk_t*)ctx; + w->fn(w->ctx, p[0].data, p[0].attrs, e - b); +} +static ray_t* grp_seg_read(ray_col_src_t* s, int64_t lo, int64_t hi, void* ctx, grp_seg_fn fn) { + if (hi > s->len) hi = s->len; + if (lo >= hi) return NULL; + const void* plain[1] = { ray_col_src_base(s) }; /* in place when ready */ + ray_col_src_t* srcs[1] = { s }; + grp_seg_walk_t w = { ctx, fn }; + return ray_col_walk(srcs, plain, 1, lo, hi, false, &w, 0, grp_seg_piece); +} + +/* parted_flatten_fixed's copy of one piece into the flat vector. */ +typedef struct { void* out; int8_t base; uint8_t out_attrs; } grp_flat_t; +static void grp_flat_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + grp_flat_t* f = (grp_flat_t*)ctx; + uint8_t esz = ray_sym_elem_size(f->base, f->out_attrs); + if (f->base != RAY_SYM || ((p[0].attrs ^ f->out_attrs) & RAY_SYM_W_MASK) == 0) { + memcpy((char*)f->out + (size_t)b * esz, p[0].data, (size_t)(e - b) * esz); + return; + } + /* a narrower segment: ids are positions in the shared domain, widened verbatim */ + for (int64_t i = 0; i < e - b; i++) + ray_write_sym(f->out, b + i, (uint64_t)ray_read_sym(p[0].data, i, RAY_SYM, p[0].attrs), + RAY_SYM, f->out_attrs); +} + +/* parted_flatten_fixed on the pool: task i walks its own slice of the + * rows (one cursor set, so a vector a slice starts inside decodes once a + * slice) into the shared flat vector; a range error is noted keyed by the + * slice's first row. */ +typedef struct { + ray_col_src_t* src; + grp_flat_t* f; + int64_t n, slice; + ray_scan_fail_t* fail; +} grp_flat_par_t; +/* Rows [lo, hi) of the source into the flat vector: a whole vector of an + * encoded segment decoded straight into place (ray_col_range_into), any + * other rows through one cursor (decoding into its lent vector) and + * copied. NULL or an owned error. */ +static ray_t* grp_flat_rows(ray_col_src_t* src, grp_flat_t* f, uint32_t wid, int64_t lo, int64_t hi) { + const uint8_t esz = ray_sym_elem_size(f->base, f->out_attrs); + ray_col_fixed_t fixed; + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, src, &fixed); + ray_t* err = NULL; + for (int64_t r = lo; r < hi && !err; ) { + int64_t got = 0; + err = ray_col_range_into(src, r, hi - r, &cur.sc, f->out_attrs, (char*)f->out + (size_t)r * esz, &got); + if (err) break; + if (got) { r += got; continue; } + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(&cur, r, &v)) != NULL) break; + int64_t e = v->start + v->n < hi ? v->start + v->n : hi; + ray_col_piece_t p = { .data = (const char*)v->data + (size_t)(r - v->start) * ray_sym_elem_size(v->type, v->attrs), + .attrs = v->attrs }; + grp_flat_piece(f, wid, r, e, &p); + r = e; + } + ray_col_cursor_free(&cur); + return err; +} + +static void grp_flat_par_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + (void)end; + grp_flat_par_t* c = (grp_flat_par_t*)ctx; + int64_t lo = start * c->slice, hi = lo + c->slice < c->n ? lo + c->slice : c->n; + if (lo >= hi || ray_scan_fail_skip(c->fail, lo)) return; + ray_t* err = grp_flat_rows(c->src, c->f, wid, lo, hi); + if (err) ray_scan_fail_note(c->fail, lo, err); +} + +/* Over a parted column's segment headers (never decodes): the widest SYM + * width and whether any segment holds nulls. */ +static void parted_seg_scan(ray_t* col, int64_t n_segs, uint8_t* width, bool* nulls) { + *width = 0; + *nulls = false; + for (int64_t i = 0; i < n_segs; i++) { + ray_t* sg = col->type == RAY_ENCCOL ? ray_enccol_seg(col, i) : ((ray_t**)ray_data(col))[i]; + if (!sg) continue; + ray_col_meta_t sm; + ray_col_meta_of(sg, &sm); + if ((sm.attrs & RAY_SYM_W_MASK) > *width) *width = sm.attrs & RAY_SYM_W_MASK; + if (sg->type == RAY_ENCCOL ? (sm.null_count >= 0 ? sm.null_count > 0 : (sm.attrs & RAY_ATTR_HAS_NULLS) != 0) + : (sg->attrs & RAY_ATTR_HAS_NULLS) != 0) + *nulls = true; + } +} + +uint8_t parted_sym_width(ray_t* col) { + ray_col_meta_t m; + if (!ray_col_meta_of(col, &m) || !RAY_IS_PARTED(m.type) || RAY_PARTED_BASETYPE(m.type) != RAY_SYM) return 0; + uint8_t w; + bool nulls; + parted_seg_scan(col, m.n_segs, &w, &nulls); + return w; +} + +static _Atomic(int64_t) g_flat_copies; /* test hook: parted_flatten_fixed calls */ +int64_t ray_group_test_flat_copies(void) { return atomic_load_explicit(&g_flat_copies, memory_order_relaxed); } + +/* A hand-built plain wrapper with missing (NULL) segments: each missing + * one spans its partition's rows from the partition-key counts (`cnt`, + * `ncnt`; none: no rows), as the type's null. ray_read_parted never builds + * one (a ragged partition's absent column is a lazy all-null segment). */ +static ray_t* parted_flatten_fixed_gaps(ray_t* col, int64_t total, const int64_t* cnt, int64_t ncnt) { + int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); + ray_t** segs = (ray_t**)ray_data(col); + uint8_t sba = base == RAY_SYM ? parted_sym_max_attrs(segs, col->len) : 0; + int64_t rows = parted_rows_counted(col, cnt, ncnt); + if (rows > total) rows = total; + ray_t* flat = typed_vec_new(base, sba, total > 0 ? total : 1); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); + flat->len = total; + int64_t off = 0; + uint8_t nulls = 0; + for (int64_t s = 0; s < col->len && off < total; s++) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + if (n > total - off) n = total - off; + if (!segs[s]) { parted_fill_nulls(flat, off, n); if (n > 0) nulls = RAY_ATTR_HAS_NULLS; off += n; continue; } + if (n > 0) parted_copy_cells(ray_data(flat), base, sba, off, segs[s], 0, n); + nulls |= segs[s]->attrs & RAY_ATTR_HAS_NULLS; + off += n; + } + if (off < total) parted_fill_nulls(flat, off, total - off); + flat->attrs |= nulls; + if (base == RAY_SYM) ray_sym_vec_adopt_domain(flat, sym_domain_rep(col)); + return flat; +} + +ray_t* parted_flatten_fixed_c(ray_t* col, int64_t total, const int64_t* cnt, int64_t ncnt) { + if (col && col->type != RAY_ENCCOL && RAY_IS_PARTED(col->type)) { + ray_t** segs = (ray_t**)ray_data(col); + for (int64_t s = 0; s < col->len; s++) + if (!segs[s]) { + atomic_fetch_add_explicit(&g_flat_copies, 1, memory_order_relaxed); + return parted_flatten_fixed_gaps(col, total, cnt, ncnt); + } + } + return parted_flatten_fixed(col, total); +} + +ray_t* parted_flatten_fixed(ray_t* col, int64_t total) { + atomic_fetch_add_explicit(&g_flat_copies, 1, memory_order_relaxed); + ray_col_meta_t m; + if (!ray_col_meta_of(col, &m) || !RAY_IS_PARTED(m.type)) return ray_error("type", "flatten: not a parted column"); + int8_t base = (int8_t)RAY_PARTED_BASETYPE(m.type); + uint8_t w; + bool any_null; + parted_seg_scan(col, m.n_segs, &w, &any_null); + if (base != RAY_SYM) w = 0; + uint8_t nulls = any_null ? RAY_ATTR_HAS_NULLS : 0; + ray_t* flat = typed_vec_new(base, w, total > 0 ? total : 1); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); + ray_col_src_t s; + ray_t* err = ray_col_src_bind(col, &s); + if (err) { ray_release(flat); return err; } + /* segment cells are copied id-preserving — all partitions resolve over + * the root symfile's domain (PARTED contract): the first segment's */ + if (base == RAY_SYM && s.dom && s.dom != ray_sym_runtime_domain()) { + ray_sym_domain_retain(s.dom); + flat->sym_domain = s.dom; + } + int64_t n = s.len < total ? s.len : total; + grp_flat_t f = { ray_data(flat), base, w }; + const void* plain[1] = { NULL }; /* a parted source reads through its cursor */ + ray_col_src_t* srcs[1] = { &s }; + /* A flatten that decodes runs on the pool: an encoded or synthetic + * segment with no published materialization (ray_col_src_ready is + * NULL; a plain source is its own ready column). Plain segments, or a + * materialization read in place, stay one serial memcpy (in parallel, + * the fresh output's page faults contend: q18 over generation 0, +6%). */ + ray_pool_t* pool = ray_pool_get(); + if (!ray_col_src_ready(&s) && ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) { + /* a few block-aligned slices a worker, so claiming balances uneven + * segments; a cancelled dispatch skips slices: finish says `cancel` */ + uint64_t nt = (uint64_t)ray_pool_total_workers(pool) * 4; + if (nt > RAY_POOL_INIT_TASKS) nt = RAY_POOL_INIT_TASKS; + int64_t slice = (int64_t)(((uint64_t)n + nt - 1) / nt); + slice = (slice + RAY_COL_BLOCK_ROWS - 1) / RAY_COL_BLOCK_ROWS * RAY_COL_BLOCK_ROWS; + ray_scan_fail_t fail; + ray_scan_fail_init(&fail); + grp_flat_par_t pc = { .src = &s, .f = &f, .n = n, .slice = slice, .fail = &fail }; + ray_pool_dispatch_n(pool, grp_flat_par_fn, &pc, (uint32_t)((n + slice - 1) / slice)); + err = ray_scan_fail_finish(&fail, pool); + } else + err = n > 0 ? ray_col_walk(srcs, plain, 1, 0, n, false, &f, 0, grp_flat_piece) : NULL; + ray_col_src_release(&s); + if (err) { ray_release(flat); return err; } + flat->len = total; + flat->attrs |= nulls; + return flat; +} + +/* The cardinality sample's folds over a segment's pieces: the SYM presence + * bitmap, the integer value span. The null sentinel (`null`) is one group + * of its own, not the low end of the value range: taking it as lo would + * turn a nullable low-cardinality key into a span of ~2^63 (I64) or ~2^31 + * (I32) and force the concat path. The span is over the non-null values, + * `has_null` noting a null. */ +typedef struct { + uint64_t* bits; + uint32_t sym_n; + int64_t null; + int64_t lo, hi; + bool any, has_null; +} grp_card_t; +static void grp_card_sym(void* ctx, const void* data, uint8_t attrs, int64_t n) { + grp_card_t* c = (grp_card_t*)ctx; + for (int64_t r = 0; r < n; r++) { + uint32_t id = (uint32_t)ray_read_sym(data, r, RAY_SYM, attrs); + if (id < c->sym_n) c->bits[id / 64] |= 1ULL << (id % 64); + } +} +#define GRP_CARD_FOLD(NAME, T) \ +static void NAME(void* ctx, const void* data, uint8_t attrs, int64_t n) { \ + (void)attrs; \ + grp_card_t* c = (grp_card_t*)ctx; \ + const T* v = (const T*)data; \ + int64_t lo = c->any ? c->lo : INT64_MAX, hi = c->any ? c->hi : INT64_MIN; \ + bool hn = c->has_null; \ + for (int64_t r = 0; r < n; r++) { \ + int64_t x = (int64_t)v[r]; \ + if (x == c->null) { hn = true; continue; } \ + if (x < lo) lo = x; \ + if (x > hi) hi = x; \ + } \ + c->has_null = hn; \ + if (lo <= hi) { c->lo = lo; c->hi = hi; c->any = true; } \ +} +GRP_CARD_FOLD(grp_card_i64, int64_t) +GRP_CARD_FOLD(grp_card_i32, int32_t) +GRP_CARD_FOLD(grp_card_i16, int16_t) +#undef GRP_CARD_FOLD + +/* The integer value span of a generation-2 segment from its directory, + * without decoding: every chunk's statistics (over its non-null values), + * a chunk with nulls noting one, so the span is the scan's. False when a + * chunk has no statistics (the caller scans). It only picks the route; + * nothing is sized from it. */ +static bool grp_card_dir(const ray_col_src_t* s, grp_card_t* c) { + ray_enc_chunk_stat_t st; + int64_t nch = (s->len + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + if (nch <= 0 || !ray_col_src_chunk_stat(s, 0, &st)) return false; + int64_t lo = INT64_MAX, hi = INT64_MIN; + bool hn = false; + for (int64_t ch = 0; ch < nch; ch++) { + (void)ray_col_src_chunk_stat(s, ch, &st); + if (st.null_count > 0) hn = true; + if ((int64_t)st.null_count >= st.rows) continue; + if (!st.has_minmax) return false; + if (st.min < lo) lo = st.min; + if (st.max > hi) hi = st.max; + } + c->has_null = hn; + c->any = lo <= hi; + if (c->any) { c->lo = lo; c->hi = hi; } + return true; +} + +/* The first owned error among `n` column lookups (the others are disposed + * of), or NULL when none failed. */ +static ray_t* group_first_err(ray_t** c, int n) { + ray_t* e = NULL; + for (int i = 0; i < n; i++) { + if (!c[i] || !RAY_IS_ERR(c[i])) continue; + if (!e) e = c[i]; else ray_error_free(c[i]); + } + return e; +} + static ray_t* group_eval_part_expr(ray_graph_t* g, ray_t* parted_tbl, const int64_t* src_syms, int n_src, uint32_t root, int32_t p) { ray_t* sub = ray_table_new(n_src > 0 ? (int64_t)n_src : 1); if (!sub || RAY_IS_ERR(sub)) return NULL; for (int j = 0; j < n_src; j++) { - ray_t* pcol = ray_table_get_col(parted_tbl, src_syms[j]); - if (!pcol || !RAY_IS_PARTED(pcol->type)) { ray_release(sub); return NULL; } - ray_t* seg = ((ray_t**)ray_data(pcol))[p]; + ray_t* seg = ray_table_parted_seg(parted_tbl, src_syms[j], p); if (!seg) { ray_release(sub); return NULL; } ray_retain(seg); sub = ray_table_add_col(sub, src_syms[j], seg); @@ -9773,6 +11836,163 @@ static ray_t* group_eval_part_expr(ray_graph_t* g, ray_t* parted_tbl, return vec; } +static int g_group_test_route; /* defined with ray_group_test_route below */ + +/* A ragged partition's synthetic all-null segment `sg` (ray_read_parted's + * stand-in for a column the partition lacks) as a plain vector: its + * published materialization, or, known all null, ray_null_fill's vector + * (what its decode gives, never a decode). The fill is transient, rows x + * width per query, so it is built only while it fits in *budget, the + * bytes of fill this query may still build (GRP_NULL_FILL_BUDGET), which it + * then spends. NULL: not a synthetic segment, a type without a fixed width, + * or over the budget (the caller reads sg as it is, by range: the piece walk + * decodes one vector at a time into its scratch); else an owned vector or + * error. */ +#define GRP_NULL_FILL_BUDGET ((int64_t)AGG_COMPACT_BITMAP_BUDGET) +static int64_t grp_synth_fill_bytes(ray_t* sg) { + if (!sg || sg->type != RAY_ENCCOL || !ray_enccol_is_synthetic(sg) || ray_enccol_is_parted(sg)) return -1; + if (ray_enccol_decoded_peek(sg)) return 0; + ray_col_meta_t sm; + if (!ray_col_meta_of(sg, &sm)) return -1; + switch (sm.type) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F32: case RAY_F64: case RAY_SYM: + break; + default: + return -1; + } + return sm.len * (int64_t)ray_sym_elem_size(sm.type, RAY_SYM_W8); +} +static ray_t* grp_synth_plain(ray_t* sg, int64_t* budget) { + int64_t bytes = grp_synth_fill_bytes(sg); + if (bytes < 0 || bytes > *budget) return NULL; + ray_t* pk = ray_enccol_decoded_peek(sg); + if (pk) { ray_retain(pk); return pk; } + ray_col_meta_t sm; + if (!ray_col_meta_of(sg, &sm)) return NULL; + ray_t* f; + if (sm.type == RAY_SYM) { + /* a SYM stand-in's domain: the db's, the one every partition resolves over */ + ray_col_src_t ss; + ray_t* be = ray_col_src_bind(sg, &ss); + if (be) return be; + f = ray_null_fill(sm.type, sm.len, ss.dom && ss.dom != ray_sym_runtime_domain() ? ss.dom : NULL); + ray_col_src_release(&ss); + } else { + f = ray_null_fill(sm.type, sm.len, NULL); + } + if (f && !RAY_IS_ERR(f)) { + *budget -= bytes; + atomic_fetch_add_explicit(&ray_group_null_fill_bytes_ctr, bytes, memory_order_relaxed); + } + return f; +} + +/* A generation-0 ragged column (a RAY_ENCCOL_PARTED whose only encoded + * segments are synthetic stand-ins) as a plain parted wrapper for the + * in-place group: the plain segments as they are, each stand-in as + * grp_synth_plain's vector. The group then reads every segment in place on + * the plain loops, as a column with no ragged partition does. *budget is + * the query's remaining fill budget, shared by its columns. NULL: not such + * a column, a stand-in of a type grp_synth_plain leaves, or fills over the + * budget (the slot is grouped as it is, by the piece walk); else an owned + * wrapper or error. */ +static ray_t* grp_ragged_plain(ray_t* slot, int64_t* budget) { + if (!slot || slot->type != RAY_ENCCOL || !ray_enccol_is_parted(slot) || + !ray_enccol_is_synthetic(slot)) return NULL; + ray_col_meta_t m; + if (!ray_col_meta_of(slot, &m) || !RAY_IS_PARTED(m.type)) return NULL; + int64_t ns = m.n_segs, need = 0; + for (int64_t i = 0; i < ns; i++) { /* every stand-in fits, or none is filled */ + ray_t* sg = ray_enccol_seg(slot, i); + if (!sg || sg->type != RAY_ENCCOL) continue; + int64_t b = grp_synth_fill_bytes(sg); + if (b < 0) return NULL; + need += b; + } + if (need > *budget) return NULL; + ray_t* w = ray_alloc((size_t)(ns > 0 ? ns : 1) * sizeof(ray_t*)); + if (!w || RAY_IS_ERR(w)) return w ? w : ray_error("oom", NULL); + w->type = m.type; + w->len = ns; + w->attrs = 0; + memset(w->aux, 0, 16); + ray_t** segs = (ray_t**)ray_data(w); + memset(segs, 0, (size_t)(ns > 0 ? ns : 1) * sizeof(ray_t*)); + for (int64_t i = 0; i < ns; i++) { + ray_t* sg = ray_enccol_seg(slot, i); + if (!sg) continue; + if (sg->type != RAY_ENCCOL) { ray_retain(sg); segs[i] = sg; continue; } + ray_t* f = grp_synth_plain(sg, budget); + if (!f || RAY_IS_ERR(f)) { ray_release(w); return f; } /* NULL: the slot as it is */ + segs[i] = f; + } + return w; +} + +/* The in-place concat's eligibility: v2 groups the parted columns from + * their segments (every source staged, R-WALK through every SCAN site). + * Every key a scan of a parted fixed-width integer, temporal or SYM column; + * every aggregate a streaming one over a scan of a parted number column + * (or a count), with no second input and no parameter; no selection (v2's + * compact prologue would gather the parted sources); an unordered take + * only over a generation-2 key (v2's first-N pre-pass reads the keys at + * rows through their parted sources and gathers its groups' rows by range, + * any decline running the group over its flat copy; a generation-0 table + * keeps the flat copy, as before); and v2 admits the shape over the base + * types. */ +/* A hand-built plain parted wrapper with a missing (NULL) segment: its + * partition's rows come from the partition-key counts, which the segment + * stream does not read (ray_read_parted builds no such wrapper). */ +static bool grp_plain_seg_gap(ray_t* parted_tbl, int64_t sym) { + ray_t* slot = ray_table_slot(parted_tbl, sym); + if (!slot || slot->type == RAY_ENCCOL || !RAY_IS_PARTED(slot->type)) return false; + ray_t** segs = (ray_t**)ray_data(slot); + for (int64_t s = 0; s < slot->len; s++) if (!segs[s]) return true; + return false; +} + +static bool group_seg_stream_ok(ray_graph_t* g, ray_op_t* op, ray_op_ext_t* ext, + ray_t* parted_tbl, int64_t group_limit) { + if (!ray_agg_engine_v2 || g_group_test_route >= 1 || g->selection || g->sg_col || + ext->n_keys == 0 || group_limit < 0) + return false; + for (uint32_t i = 0; i < ext->n_keys + ext->n_aggs; i++) { + ray_op_ext_t* e2 = find_ext(g, i < ext->n_keys ? ext->keys[i] : ext->agg_ins[i - ext->n_keys]); + if (e2 && e2->base.opcode == OP_SCAN && grp_plain_seg_gap(parted_tbl, e2->sym)) return false; + } + bool firstn = group_limit > 0 && !ray_group_emit_filter_active().enabled; + bool enc_key = false; + for (uint32_t k = 0; k < ext->n_keys; k++) { + ray_op_ext_t* ke = find_ext(g, ext->keys[k]); + ray_col_meta_t m; + if (!ke || ke->base.opcode != OP_SCAN || !ray_table_col_meta(parted_tbl, ke->sym, &m) || + !RAY_IS_PARTED(m.type)) return false; + if (!agg_key_i64_type((int8_t)RAY_PARTED_BASETYPE(m.type))) return false; + enc_key |= ray_table_get_col_enc(parted_tbl, ke->sym) != NULL; + } + if (firstn && !enc_key) return false; + for (uint32_t a = 0; a < ext->n_aggs; a++) { + uint16_t aop = ext->agg_ops[a]; + if (aop != OP_SUM && aop != OP_COUNT && aop != OP_MIN && aop != OP_MAX && aop != OP_AVG && + aop != OP_FIRST && aop != OP_LAST && aop != OP_VAR && aop != OP_VAR_POP && + aop != OP_STDDEV && aop != OP_STDDEV_POP) return false; + if ((ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) || (ext->agg_k && ext->agg_k[a])) return false; + ray_op_ext_t* ae = find_ext(g, ext->agg_ins[a]); + if (aop == OP_COUNT && (!ae || ae->base.opcode != OP_SCAN)) continue; + ray_col_meta_t m; + if (!ae || ae->base.opcode != OP_SCAN || !ray_table_col_meta(parted_tbl, ae->sym, &m) || + !RAY_IS_PARTED(m.type)) return false; + int8_t b = (int8_t)RAY_PARTED_BASETYPE(m.type); + if (!((b >= RAY_BOOL && b <= RAY_TIMESTAMP) || b == RAY_F32 || b == RAY_F64)) return false; + } + bool saved = g->grp_seg_stream; + g->grp_seg_stream = true; + bool ok = agg_v2_admission(g, op, parted_tbl) == AGG_V2_ADMITTED; + g->grp_seg_stream = saved; + return ok; +} + /* -------------------------------------------------------------------------- * exec_group_parted — dispatch per-partition or concat-fallback * -------------------------------------------------------------------------- */ @@ -9791,10 +12011,10 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, int32_t n_parts = 0; int64_t total_rows = 0; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(parted_tbl, c); - if (col && RAY_IS_PARTED(col->type)) { - n_parts = (int32_t)col->len; - total_rows = ray_parted_nrows(col); + ray_col_meta_t m; + if (ray_table_col_meta_idx(parted_tbl, c, &m) && RAY_IS_PARTED(m.type)) { + n_parts = (int32_t)m.n_segs; + total_rows = m.len; break; } } @@ -9860,8 +12080,9 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, * Returns 0 if the column is missing or MAPCOMMON (expression sources * must be plain PARTED so segment[p] can be borrowed directly). */ #define GP_BORROW_ADD(sym) do { \ - ray_t* _pc = ray_table_get_col(parted_tbl, (sym)); \ - if (!_pc || !RAY_IS_PARTED(_pc->type)) { can_partition = 0; break; } \ + ray_col_meta_t _pm; \ + if (!ray_table_col_meta(parted_tbl, (sym), &_pm) || \ + !RAY_IS_PARTED(_pm.type)) { can_partition = 0; break; } \ int _dup = 0; \ for (int _i = 0; _i < n_borrow; _i++) \ if (borrow_syms[_i] == (sym)) { _dup = 1; break; } \ @@ -9874,8 +12095,8 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, key_syms[k] = ke->sym; key_is_expr[k] = 0; /* MAPCOMMON scan keys are reconstructed post-merge, not borrowed. */ - ray_t* pc = ray_table_get_col(parted_tbl, ke->sym); - if (pc && pc->type == RAY_MAPCOMMON) continue; + ray_col_meta_t pm; + if (ray_table_col_meta(parted_tbl, ke->sym, &pm) && pm.type == RAY_MAPCOMMON) continue; GP_BORROW_ADD(ke->sym); } else { /* Expression key: admit only pure row-local scalar exprs and @@ -9887,7 +12108,7 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, int64_t synth = ray_sym_intern(nbuf, (size_t)nl); /* A real column shadowing the synthetic name would be borrowed * over the materialized value — decline. */ - if (ray_table_get_col(parted_tbl, synth)) { can_partition = 0; break; } + { ray_col_meta_t sm_; if (ray_table_col_meta(parted_tbl, synth, &sm_)) { can_partition = 0; break; } } for (int s = 0; s < ns && can_partition; s++) GP_BORROW_ADD(esrc[s]); key_syms[k] = synth; key_is_expr[k] = 1; @@ -9923,7 +12144,7 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, char nbuf[24]; int nl = snprintf(nbuf, sizeof(nbuf), "_gpa%u", (unsigned)a); int64_t synth = ray_sym_intern(nbuf, (size_t)nl); - if (ray_table_get_col(parted_tbl, synth)) { can_partition = 0; break; } + { ray_col_meta_t sm_; if (ray_table_col_meta(parted_tbl, synth, &sm_)) { can_partition = 0; break; } } for (int s = 0; s < ns && can_partition; s++) GP_BORROW_ADD(esrc[s]); agg_syms[a] = synth; agg_is_expr[a] = 1; @@ -9938,20 +12159,31 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, * concat path, which applies g->selection over the flattened table. */ if (g->selection && n_borrow == 0) can_partition = 0; - /* Cardinality gate: estimate groups from first partition. - * Per-partition only wins when #groups << partition_size. */ + /* Cardinality gate: estimate groups from a sample partition. + * Per-partition only wins when #groups << partition_size. The sample is + * the first partition holding more than one row: a pruned source keeps a + * one-row stand-in for its pruned partitions (query.c, partition + * pruning), usually first, and a one-row sample always estimates one + * group whatever the data. */ if (can_partition) { int64_t rows_per_part = total_rows / n_parts; int64_t est_groups = 1; + int32_t sp = 0; + if (n_borrow > 0) { + for (int32_t p = 0; p < n_parts; p++) { + ray_t* sg = ray_table_parted_seg(parted_tbl, borrow_syms[0], p); + if (sg && sg->len > 1) { sp = p; break; } + } + } for (uint32_t k = 0; k < n_keys; k++) { if (key_is_expr[k]) { - /* Expression key: materialize partition 0 and estimate its + /* Expression key: materialize the sample and estimate its * distinct group count via HyperLogLog. A range-based proxy * (as used for integer scan keys below) would badly over-count * bucketed keys — xbar values are spaced N apart, so hi-lo * spans the whole domain range, not the bucket count. */ ray_t* v0 = group_eval_part_expr(g, parted_tbl, borrow_syms, - n_borrow, ext->keys[k], 0); + n_borrow, ext->keys[k], sp); if (!v0) { est_groups = rows_per_part; break; } ray_t* cd = ray_count_distinct_approx(v0); ray_release(v0); @@ -9962,63 +12194,85 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, int64_t card = cd->i64; ray_release(cd); if (card < 1) card = 1; + if (card > rows_per_part / est_groups) { est_groups = rows_per_part; break; } est_groups *= card; if (est_groups > rows_per_part) { est_groups = rows_per_part; break; } continue; } - ray_t* pcol = ray_table_get_col(parted_tbl, key_syms[k]); - if (!pcol) { est_groups = rows_per_part; break; } + ray_col_meta_t pcm; + if (!ray_table_col_meta(parted_tbl, key_syms[k], &pcm)) { est_groups = rows_per_part; break; } /* MAPCOMMON key: constant per partition — excluded from * per-partition sub-GROUP-BY, contributes 0 to cardinality. */ - if (pcol->type == RAY_MAPCOMMON) { continue; } - if (!RAY_IS_PARTED(pcol->type)) { est_groups = rows_per_part; break; } - ray_t* seg0 = ((ray_t**)ray_data(pcol))[0]; - if (!seg0 || seg0->len <= 0) { est_groups = rows_per_part; break; } - int8_t bt = RAY_PARTED_BASETYPE(pcol->type); + if (pcm.type == RAY_MAPCOMMON) { continue; } + if (!RAY_IS_PARTED(pcm.type)) { est_groups = rows_per_part; break; } + /* segment sp read by range: a plain segment in place, an encoded + * one a vector at a time (never materialized) */ + ray_col_src_t ss; + ray_t* serr = grp_seg_bind(parted_tbl, key_syms[k], sp, &ss); + if (serr) { + scratch_free(key_syms_hdr); scratch_free(agg_syms_hdr); + scratch_free(key_is_expr_hdr); scratch_free(agg_is_expr_hdr); + scratch_free(borrow_hdr); scratch_free(esrc_hdr); + return serr; + } + if (!ss.obj || ss.len <= 0) { ray_col_src_release(&ss); est_groups = rows_per_part; break; } + int8_t bt = RAY_PARTED_BASETYPE(pcm.type); int64_t card; + grp_card_t cc = { .bits = NULL }; + ray_t* bits_hdr = NULL; if (RAY_IS_SYM(bt)) { - /* seg0's cell ids are positions in ITS domain — size the - * presence bitmap by that domain's count, not the global - * intern count (a FILE-domain position can exceed the - * global count → OOB). Identical value pre-flip. */ - int64_t dom_n = ray_sym_domain_count(ray_sym_vec_domain(seg0)); - uint32_t sym_n = (dom_n > 0 && dom_n <= UINT32_MAX) ? (uint32_t)dom_n : 0; - if (sym_n == 0 || sym_n > 4194304) { est_groups = rows_per_part; break; } - size_t bwords = ((size_t)sym_n + 63) / 64; - ray_t* bits_hdr = NULL; - uint64_t* bits = (uint64_t*)scratch_calloc(&bits_hdr, bwords * 8); - if (!bits) { est_groups = rows_per_part; break; } - for (int64_t r = 0; r < seg0->len; r++) { - uint32_t id = (uint32_t)ray_read_sym(ray_data(seg0), r, seg0->type, seg0->attrs); - bits[id / 64] |= 1ULL << (id % 64); - } + /* the segment's cell ids are positions in ITS domain — size + * the presence bitmap by that domain's count, not the global + * intern count (a FILE-domain position can exceed the global + * count → OOB). Identical value pre-flip. */ + int64_t dom_n = ray_sym_domain_count(ss.dom); + cc.sym_n = (dom_n > 0 && dom_n <= UINT32_MAX) ? (uint32_t)dom_n : 0; + if (cc.sym_n == 0 || cc.sym_n > 4194304) { ray_col_src_release(&ss); est_groups = rows_per_part; break; } + size_t bwords = ((size_t)cc.sym_n + 63) / 64; + cc.bits = (uint64_t*)scratch_calloc(&bits_hdr, bwords * 8); + if (!cc.bits) { ray_col_src_release(&ss); est_groups = rows_per_part; break; } + serr = grp_seg_read(&ss, 0, ss.len, &cc, grp_card_sym); card = 0; for (size_t i = 0; i < bwords; i++) - card += __builtin_popcountll(bits[i]); + card += __builtin_popcountll(cc.bits[i]); scratch_free(bits_hdr); - } else if (bt == RAY_I64) { - const int64_t* v = (const int64_t*)ray_data(seg0); - int64_t lo = v[0], hi = v[0]; - for (int64_t r = 1; r < seg0->len; r++) { - if (v[r] < lo) lo = v[r]; - if (v[r] > hi) hi = v[r]; - } - card = hi - lo + 1; - } else if (bt == RAY_I32) { - const int32_t* v = (const int32_t*)ray_data(seg0); - int32_t lo = v[0], hi = v[0]; - for (int64_t r = 1; r < seg0->len; r++) { - if (v[r] < lo) lo = v[r]; - if (v[r] > hi) hi = v[r]; + } else if (bt == RAY_I64 || bt == RAY_TIMESPAN || bt == RAY_TIMESTAMP || + bt == RAY_I32 || bt == RAY_DATE || bt == RAY_TIME || + bt == RAY_I16) { + /* Range proxy for every integer-like key, by width, over + * the non-null values, plus one group when a null shows + * (grp_card_t). */ + bool w64 = bt == RAY_I64 || bt == RAY_TIMESPAN || bt == RAY_TIMESTAMP; + cc.null = w64 ? NULL_I64 : bt == RAY_I16 ? NULL_I16 : NULL_I32; + if (!grp_card_dir(&ss, &cc)) + serr = grp_seg_read(&ss, 0, ss.len, &cc, + w64 ? grp_card_i64 : bt == RAY_I16 ? grp_card_i16 : grp_card_i32); + if (!cc.any) { + card = 1; /* all null */ + } else { + /* Unsigned span: hi - lo can still exceed INT64_MAX + * for a full-range I64 key. A span past the partition + * size already saturates the estimate, so cap it. */ + uint64_t span = (uint64_t)cc.hi - (uint64_t)cc.lo; + card = span < (uint64_t)rows_per_part + ? (int64_t)span + 1 : rows_per_part + 1; + if (cc.has_null) card++; } - card = (int64_t)(hi - lo + 1); } else { - card = seg0->len; + card = ss.len; } + ray_col_src_release(&ss); + if (serr) { + scratch_free(key_syms_hdr); scratch_free(agg_syms_hdr); + scratch_free(key_is_expr_hdr); scratch_free(agg_is_expr_hdr); + scratch_free(borrow_hdr); scratch_free(esrc_hdr); + return serr; + } + if (card > rows_per_part / est_groups) { est_groups = rows_per_part; break; } est_groups *= card; if (est_groups > rows_per_part) { est_groups = rows_per_part; break; } } - /* Post-filter cap: est_groups is estimated from partition 0's + /* Post-filter cap: est_groups is estimated from the sample's * UNFILTERED rows, but a pushed-down WHERE lets a partition yield at * most one group per SURVIVING row. Without this cap a selective * filter over a genuinely low-cardinality group-by would be judged @@ -10071,6 +12325,37 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, scratch_free(esrc_hdr); /* ---- Concat fallback ---- */ + /* In place: the parted columns grouped from their segments, no flatten. + * The table holds the slot objects themselves (plain parted wrappers or + * RAY_ENCCOL_PARTED), unread. */ + if (group_seg_stream_ok(g, op, ext, parted_tbl, group_limit)) { + ray_t* in_place = ray_table_new((int64_t)n_keys + (int64_t)n_aggs); + if (!in_place || RAY_IS_ERR(in_place)) return in_place ? in_place : ray_error("oom", NULL); + int64_t fill_budget = GRP_NULL_FILL_BUDGET; + for (uint32_t i = 0; i < n_keys + n_aggs; i++) { + ray_op_ext_t* e2 = find_ext(g, i < n_keys ? ext->keys[i] : ext->agg_ins[i - n_keys]); + if (!e2 || e2->base.opcode != OP_SCAN) continue; /* a count without input */ + ray_col_meta_t dm; + if (ray_table_col_meta(in_place, e2->sym, &dm)) continue; /* already added */ + ray_t* slot = ray_table_slot(parted_tbl, e2->sym); + ray_t* plain = grp_ragged_plain(slot, &fill_budget); + if (plain && RAY_IS_ERR(plain)) { ray_release(in_place); return plain; } + in_place = ray_table_add_col(in_place, e2->sym, plain ? plain : slot); + if (plain) ray_release(plain); + if (!in_place || RAY_IS_ERR(in_place)) return in_place ? in_place : ray_error("oom", NULL); + } + atomic_fetch_add_explicit(&ray_group_segstream_runs_ctr, 1, memory_order_relaxed); + ray_t* saved = g->table; + bool saved_stream = g->grp_seg_stream; + g->table = in_place; + g->grp_seg_stream = true; + ray_t* result = exec_group(g, op, in_place, group_limit); + g->grp_seg_stream = saved_stream; + g->table = saved; + ray_graph_unbind_table(g, in_place); /* its binds die with it */ + ray_release(in_place); + return result; + } /* ---- Concat-only-needed-columns fallback ---- * Used when query has AVG or expression keys/aggs. * Only concatenates the columns actually referenced by the GROUP BY. */ @@ -10082,9 +12367,10 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, * of the key over flat_tbl fails "by: column not found" (the former * collector silently dropped expression-key sources). A distinct * source column can never exceed the table's column count, and each - * slot may reference several, so bound the union at n_keys+n_aggs+ncols - * (min 1); the dedup keeps the live count ≤ ncols. */ - int64_t needed_max = (int64_t)n_keys + (int64_t)n_aggs + ncols; + * slot may reference several, so bound the union at + * n_keys+2*n_aggs+ncols (min 1; an agg has up to two inputs); the + * dedup keeps the live count ≤ ncols. */ + int64_t needed_max = (int64_t)n_keys + 2 * (int64_t)n_aggs + ncols; if (needed_max < 1) needed_max = 1; ray_t* needed_hdr = NULL; int64_t* needed = (int64_t*)scratch_alloc(&needed_hdr, @@ -10119,8 +12405,16 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, } } } - for (uint32_t a = 0; !copy_all && a < n_aggs; a++) { - ray_op_ext_t* ae = find_ext(g, ext->agg_ins[a]); + /* Both inputs of every agg: agg_ins2 carries the second operand of a + * binary agg (wsum/wavg/cov/scov/pearson_corr) — a column referenced + * only there must be carried into flat_tbl too. */ + for (uint32_t s2 = 0; !copy_all && s2 < 2 * n_aggs; s2++) { + uint32_t a = s2 >> 1; + uint32_t in_id = (s2 & 1) + ? (ext->agg_ins2 ? ext->agg_ins2[a] : RAY_OP_NONE) + : ext->agg_ins[a]; + if (in_id == RAY_OP_NONE) continue; + ray_op_ext_t* ae = find_ext(g, in_id); if (ae && ae->base.opcode == OP_SCAN) { int dup = 0; for (int i = 0; i < n_needed; i++) @@ -10129,7 +12423,7 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, } else { /* Expression agg input — carry its source columns; unknown * subtrees copy everything (safe). */ - int ns = group_expr_src_syms(g, ext->agg_ins[a], c_esrc, (int)esrc_max); + int ns = group_expr_src_syms(g, in_id, c_esrc, (int)esrc_max); if (ns < 0) { copy_all = 1; break; } for (int s = 0; s < ns; s++) { int dup = 0; @@ -10148,14 +12442,31 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, int64_t cols_to_iter = n_needed > 0 ? (int64_t)n_needed : ncols; for (int64_t ci = 0; ci < cols_to_iter; ci++) { - ray_t* col; - int64_t name_id; - if (n_needed > 0) { - col = ray_table_get_col(parted_tbl, needed[ci]); - name_id = needed[ci]; - } else { - col = ray_table_get_col_idx(parted_tbl, ci); - name_id = ray_table_col_name(parted_tbl, ci); + int64_t name_id = n_needed > 0 ? needed[ci] : ray_table_col_name(parted_tbl, ci); + /* A parted fixed-width column is copied from its segments by + * range (an encoded segment is never materialized); the others + * take their plain column. */ + ray_col_meta_t fm; + if (ray_table_col_meta(parted_tbl, name_id, &fm) && RAY_IS_PARTED(fm.type) && + RAY_PARTED_BASETYPE(fm.type) != RAY_STR && RAY_PARTED_BASETYPE(fm.type) != RAY_LIST) { + int64_t fx_ncnt = 0; + const int64_t* fx_cnt = parted_table_counts(parted_tbl, &fx_ncnt); + ray_t* flat = parted_flatten_fixed_c(ray_table_slot(parted_tbl, name_id), total_rows, fx_cnt, fx_ncnt); + if (!flat || RAY_IS_ERR(flat)) { + ray_release(flat_tbl); + scratch_free(needed_hdr); + return flat ? flat : ray_error("oom", NULL); + } + flat_tbl = ray_table_add_col(flat_tbl, name_id, flat); + ray_release(flat); + continue; + } + ray_t* col = n_needed > 0 ? ray_table_col(parted_tbl, needed[ci]) + : ray_table_col_idx(parted_tbl, ci); + if (col && RAY_IS_ERR(col)) { + ray_release(flat_tbl); + scratch_free(needed_hdr); + return col; } if (!col) continue; if (col->type == RAY_MAPCOMMON) { @@ -10176,41 +12487,12 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, int8_t base_type = (int8_t)RAY_PARTED_BASETYPE(col->type); ray_t** segs = (ray_t**)ray_data(col); - ray_t* flat; - - if (base_type == RAY_STR) { - flat = parted_flatten_str(segs, col->len, total_rows); - } else if (base_type == RAY_LIST) { - flat = parted_flatten_list(segs, col->len, total_rows); - } else { - uint8_t base_attrs = (base_type == RAY_SYM) - ? parted_sym_max_attrs(segs, col->len) : 0; - flat = typed_vec_new(base_type, base_attrs, total_rows); - if (!flat || RAY_IS_ERR(flat)) { - ray_release(flat_tbl); - scratch_free(needed_hdr); - return flat ? flat : ray_error("oom", NULL); - } - /* segment cells are copied id-preserving — all partitions - * resolve over the root symfile's domain (PARTED - * contract); adopt it from the first SYM segment. */ - if (base_type == RAY_SYM) - ray_sym_vec_adopt_domain(flat, sym_domain_rep(col)); - flat->len = total_rows; - - int64_t offset = 0; - uint8_t seg_nulls = 0; - for (int32_t p = 0; p < n_parts; p++) { - ray_t* seg = segs[p]; - if (!seg || seg->len <= 0) continue; - parted_copy_cells(ray_data(flat), base_type, base_attrs, - offset, seg, 0, seg->len); - seg_nulls |= seg->attrs & RAY_ATTR_HAS_NULLS; - offset += seg->len; - } - /* Null propagation: propagate HAS_NULLS across segments. */ - flat->attrs |= seg_nulls; - } + /* A partition without the column (ragged parted table) spans + * its rows, from the partition-key counts, as typed nulls. */ + int64_t rg_ncnt = 0; + const int64_t* rg_cnt = parted_table_counts(parted_tbl, &rg_ncnt); + ray_t* flat = base_type == RAY_STR ? parted_flatten_str_c(segs, col->len, rg_cnt, rg_ncnt) + : parted_flatten_list_c(segs, col->len, rg_cnt, rg_ncnt); if (!flat || RAY_IS_ERR(flat)) { ray_release(flat_tbl); scratch_free(needed_hdr); @@ -10223,8 +12505,9 @@ static ray_t* exec_group_parted(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, ray_t* saved = g->table; g->table = flat_tbl; - ray_t* result = exec_group(g, op, flat_tbl, 0); + ray_t* result = exec_group(g, op, flat_tbl, group_limit); g->table = saved; + ray_graph_unbind_table(g, flat_tbl); /* before its address can be reused */ ray_release(flat_tbl); scratch_free(needed_hdr); return result; @@ -10280,14 +12563,58 @@ static ray_t* dict_codes_to_str(const ray_t* codes_col, ray_t* src_col, return out; } +/* An I32 DICT-code result column mapped back to strings through a + * generation-2 column's persisted entries (P6b): the bytes are read in + * place (no decode) and copied into the output once. */ +static ray_t* dict_entries_to_str(const ray_t* codes_col, const ray_enc_idict_t* d) { + int64_t n = codes_col->len; + if (codes_col->type != RAY_I32) + return ray_error("type", "group: DICT key emitted as %s", ray_type_name(codes_col->type)); + const int32_t* cd = (const int32_t*)ray_data((ray_t*)codes_col); + if (n <= 0) return ray_vec_new(RAY_STR, 1); + const char** ptrs = (const char**)ray_alloc_raw((size_t)n * sizeof(const char*)); + uint32_t* lens = (uint32_t*)ray_alloc_raw((size_t)n * sizeof(uint32_t)); + if (!ptrs || !lens) { + if (ptrs) ray_free_raw(ptrs); + if (lens) ray_free_raw(lens); + return ray_error("oom", NULL); + } + for (int64_t i = 0; i < n; i++) { + int32_t c = cd[i]; + if (c < 0 || c >= d->n_distinct) { ptrs[i] = ""; lens[i] = 0; continue; } + ray_enc_sdict_entry(d->ent, (uint32_t)c, &ptrs[i], &lens[i]); + } + ray_t* out = ray_str_vec_from_parts(ptrs, lens, NULL, n); + ray_free_raw(ptrs); + ray_free_raw(lens); + return out; +} + /* Thread-local stash of the result group dict codes so the * count-distinct path can build row_gid by remapping dict codes (cheap int) * instead of re-hashing strings. */ static _Thread_local ray_dict_cd_t tl_dict_cd; +/* The stash is heap memory of the runtime that made it. A thread's stash + * outliving its runtime (the heap destroyed and made again) is dropped, never + * freed (#865): each stash records the runtime epoch, which teardown bumps + * (ray_dict_cd_runtime_gone), so a stale one is forgotten on any thread. */ +static _Atomic(uint64_t) g_dict_cd_epoch; +static _Thread_local uint64_t tl_dict_cd_epoch; +static void ray_dict_cd_forget_stale(void) { + if (tl_dict_cd.result_codes && + tl_dict_cd_epoch != atomic_load_explicit(&g_dict_cd_epoch, memory_order_acquire)) + memset(&tl_dict_cd, 0, sizeof(tl_dict_cd)); /* its heap is gone */ +} +void ray_dict_cd_runtime_gone(void) { + ray_dict_cd_clear(); /* this thread's: still freeable */ + atomic_fetch_add_explicit(&g_dict_cd_epoch, 1, memory_order_acq_rel); +} static void ray_dict_cd_stash(ray_t* codes_col, int64_t n_groups, int64_t key_sym, const ray_t* tbl, int64_t n_distinct) { + ray_dict_cd_forget_stale(); if (tl_dict_cd.result_codes) { ray_free_raw(tl_dict_cd.result_codes); tl_dict_cd.result_codes = NULL; } tl_dict_cd.valid = 0; + tl_dict_cd_epoch = atomic_load_explicit(&g_dict_cd_epoch, memory_order_acquire); if (!codes_col || n_groups <= 0) return; int32_t* rc = ray_alloc_raw((size_t)n_groups * sizeof(int32_t)); if (!rc) return; @@ -10299,8 +12626,9 @@ static void ray_dict_cd_stash(ray_t* codes_col, int64_t n_groups, int64_t key_sy tl_dict_cd.n_distinct = n_distinct; tl_dict_cd.valid = 1; } -ray_dict_cd_t ray_dict_cd_get(void) { return tl_dict_cd; } +ray_dict_cd_t ray_dict_cd_get(void) { ray_dict_cd_forget_stale(); return tl_dict_cd; } void ray_dict_cd_clear(void) { + ray_dict_cd_forget_stale(); if (tl_dict_cd.result_codes) ray_free_raw(tl_dict_cd.result_codes); memset(&tl_dict_cd, 0, sizeof(tl_dict_cd)); } @@ -10337,9 +12665,186 @@ static int64_t ray_grp_card_lookup(int64_t sym) { return 0; } +/* A generation-2 STR key (its source a RAY_ENCCOL: single file, or a parted + * column with an encoded segment) groups on query-wide string-domain ids + * (strdom.c) read by range, never materializing the column: the key's + * column is swapped for the ids, as a DICT key's for its codes, and the + * groups' ids map back to strings. A generation-0 STR key keeps its route. + * The swap (string-domain ids, or a generation-2 key's persisted DICT codes) + * is safe only when nothing but the key itself reads the column: no other + * key's expression and no aggregate input may read it, at any depth of the + * expression. The one exception is a plain COUNT of the key column (a bare + * scan, no second input): COUNT is the group size, it reads no values + * (nulls and "" rows included), so it answers the same over ids or codes. */ +static bool strdom_key_ok(ray_graph_t* g, const ray_op_ext_t* ext, int64_t sym) { + int64_t syms[64]; + for (uint32_t k = 0; k < ext->n_keys; k++) { + ray_op_ext_t* ke = find_ext(g, ext->keys[k]); + if (ke && ke->base.opcode == OP_SCAN) continue; /* a scan key: swapped alike */ + int n = group_expr_src_syms(g, ext->keys[k], syms, 64); + if (n < 0) return false; + for (int i = 0; i < n; i++) if (syms[i] == sym) return false; + } + for (uint32_t a = 0; a < ext->n_aggs; a++) { + if (ext->agg_ops[a] == OP_COUNT && + (!ext->agg_ins2 || ext->agg_ins2[a] == RAY_OP_NONE)) { + ray_op_t* ain = op_node(g, ext->agg_ins[a]); + ray_op_ext_t* ae = ain ? find_ext(g, ain->id) : NULL; + if (ae && ae->base.opcode == OP_SCAN && ae->sym == sym) continue; /* the group size */ + } + for (int w = 0; w < 2; w++) { + uint32_t in = w ? (ext->agg_ins2 ? ext->agg_ins2[a] : RAY_OP_NONE) : ext->agg_ins[a]; + if (in == RAY_OP_NONE) continue; + int n = group_expr_src_syms(g, in, syms, 64); + if (n < 0) return false; + for (int i = 0; i < n; i++) if (syms[i] == sym) return false; + } + } + return true; +} + +/* The id column of STR key `sym` of tbl over a new domain *dom, ids + * first-occurrence over the rows `sel` selects (NULL: every row): an I64 + * vector, or for a parted column a parted wrapper of I64 segments, one per + * source segment (a missing segment stays missing), the ids written into + * them directly. NULL with *dom and *out owned, or an owned error. */ +static ray_t* strdom_key_col(ray_t* tbl, int64_t sym, ray_t* sel, ray_strdom_t** dom, ray_t** out) { + *dom = NULL; *out = NULL; + ray_col_src_t src; + ray_t* err = ray_table_col_src(tbl, sym, &src); + if (err) return err; + if (!src.obj) return ray_error("domain", "group: key column not found"); + ray_t* ids = NULL; + ray_t* dst_hdr = NULL; + int64_t one_off[2] = { 0, src.len }; + int64_t* one_dst[1]; + int64_t ns = 1; const int64_t* off = one_off; int64_t** dst = one_dst; + if (!src.parted) { + ids = ray_vec_new(RAY_I64, src.len > 0 ? src.len : 1); + if (!ids || RAY_IS_ERR(ids)) { err = ids ? ids : ray_error("oom", NULL); ids = NULL; } + else { ids->len = src.len; one_dst[0] = (int64_t*)ray_data(ids); } + } else { + ray_t** segs = NULL; + if (!ray_col_src_parted_segs(&src, &ns, &segs, &off, &err)) + err = err ? err : ray_error("type", "group: STR key not parted"); + if (!err) { + dst = (int64_t**)scratch_calloc(&dst_hdr, (size_t)(ns > 0 ? ns : 1) * sizeof(int64_t*)); + ids = ray_alloc((size_t)(ns > 0 ? ns : 1) * sizeof(ray_t*)); + if (!dst || !ids || RAY_IS_ERR(ids)) { + err = ids && RAY_IS_ERR(ids) ? ids : ray_error("oom", NULL); + if (ids && !RAY_IS_ERR(ids)) ray_release(ids); /* len 0: no segments yet */ + ids = NULL; + } + } + if (!err) { + ids->type = RAY_PARTED_BASE + RAY_I64; + ids->len = 0; + ids->attrs = 0; + memset(ids->aux, 0, 16); + ray_t** wseg = (ray_t**)ray_data(ids); + memset(wseg, 0, (size_t)(ns > 0 ? ns : 1) * sizeof(ray_t*)); + for (int64_t i = 0; i < ns; i++) { + /* a segment of rows gets ids (one not yet opened may read + * NULL here); a missing one holds none */ + if (segs[i] || off[i + 1] > off[i]) { + int64_t n = off[i + 1] - off[i]; + ray_t* v = ray_vec_new(RAY_I64, n > 0 ? n : 1); + if (!v || RAY_IS_ERR(v)) { err = v ? v : ray_error("oom", NULL); break; } + v->len = n; + wseg[i] = v; + dst[i] = (int64_t*)ray_data(v); + } + ids->len = i + 1; + } + } + } + if (!err) err = ray_strdom_build_parts(&src, sel, ns, off, dst, dom); + scratch_free(dst_hdr); + ray_col_src_release(&src); + if (err) { + if (ids) ray_release(ids); + ray_strdom_free(*dom); *dom = NULL; + return err; + } + *out = ids; + return NULL; +} + +/* A group result's key column of domain ids as the domain's strings. */ +static ray_t* strdom_key_emit(const ray_strdom_t* dom, ray_t* ids_col, ray_t** out) { + *out = NULL; + int64_t n = ids_col->len; + if (ids_col->type == RAY_I64) return ray_strdom_emit(dom, (const int64_t*)ray_data(ids_col), n, out); + if (ids_col->type != RAY_I32 && ids_col->type != RAY_I16 && ids_col->type != RAY_U8) + return ray_error("type", "group: string-domain key emitted as %s", ray_type_name(ids_col->type)); + int64_t* w = (int64_t*)ray_alloc_raw((size_t)(n > 0 ? n : 1) * sizeof(int64_t)); + if (!w) return ray_error("oom", NULL); + const void* d = ray_data(ids_col); + for (int64_t i = 0; i < n; i++) + w[i] = ids_col->type == RAY_I32 ? ((const int32_t*)d)[i] + : ids_col->type == RAY_I16 ? ((const int16_t*)d)[i] : ((const uint8_t*)d)[i]; + ray_t* err = ray_strdom_emit(dom, w, n, out); + ray_free_raw(w); + return err; +} + /* exec_group wrapper: when a plain STR scan key carries a RAY_IDX_DICT, group on * its int32 codes (cheap integer path) instead of the 16-byte descriptors, then - * map codes -> strings on the small result. Falls through otherwise. */ + * map codes -> strings on the small result; a generation-2 STR scan key groups + * on its string-domain ids likewise (strdom_key_col). Falls through otherwise. */ +/* The length error for an aggregate input that carries none of the rows + * but holds several values (`(sum [1 2 3])` over ten rows, a global vector + * of another length): the aggregation loops read an input row by row, so + * such a vector was read past its end. A vector of the table's length + * stands for a column (sliced per group, filtered by where:), and one value + * (an atom or a one-element vector) is spread over the rows; anything else + * is an error. COUNT reads no value of its input. Cold: only a constant + * collection ever gets here. */ +static __attribute__((noinline, cold)) ray_t* group_const_input_check(ray_graph_t* g, uint32_t id, + ray_t* tbl, int64_t nrows) { + ray_op_t* in = op_node(g, id); + if (!in) return NULL; + ray_op_ext_t* x = find_ext(g, in->id); + ray_t* v = NULL; + bool owned = false; + if (in->opcode == OP_CONST) { + v = x ? x->literal : NULL; + } else { + ray_t* saved = g->table; + g->table = tbl; + v = exec_node(g, in); + g->table = saved; + if (!v || RAY_IS_ERR(v)) return v; + owned = true; + } + ray_t* err = NULL; + if (v && !ray_is_atom(v) && (ray_is_vec(v) || v->type == RAY_LIST) && + v->len != 1 && v->len != nrows) + err = ray_error("length", "aggregate input has %lld values for %lld rows", + (long long)v->len, (long long)nrows); + if (owned) ray_release(v); + return err; +} + +static ray_t* group_const_inputs_check(ray_graph_t* g, ray_op_ext_t* ext, ray_t* tbl) { + int64_t nrows = ray_table_nrows(tbl); + /* Over no rows nothing of an input is read: `(sum [1 2])` over an + * empty table is the sum of no values, as `(sum (til 3))` is. */ + if (nrows == 0) return NULL; + for (uint32_t a = 0; a < ext->n_aggs; a++) { + if (ext->agg_ops[a] == OP_COUNT) continue; + uint32_t ids[2] = { ext->agg_ins[a], + ext->agg_ins2 ? ext->agg_ins2[a] : RAY_OP_NONE }; + for (int k = 0; k < 2; k++) { + if (ids[k] == RAY_OP_NONE) continue; + if (!op_tree_is_scalar(g, ids[k]) || op_tree_is_atom(g, ids[k])) continue; + ray_t* err = group_const_input_check(g, ids[k], tbl, nrows); + if (err) return err; + } + } + return NULL; +} + ray_t* exec_group(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) { ray_dict_cd_clear(); /* Save the outer group-key cardinality hint and publish a fresh empty one @@ -10364,38 +12869,100 @@ ray_t* exec_group(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) ray_t* wrap_hdr = NULL; ray_t** key_col = NULL; /* source STR column per dict'd key (for output) */ int64_t* dict_sym = NULL; + ray_strdom_t** sdom = NULL; /* string domain per generation-2 STR key (owned) */ + ray_t** sd_col = NULL; /* its id column (owned) */ + ray_t** dc_vec = NULL; /* a generation-2 DICT key's code vector (borrowed) */ + const ray_enc_idict_t** dc_d = NULL; /* its persisted DICT */ + uint32_t sd_n = 0; /* entries of sdom / sd_col */ + bool sd_any = false; /* a key was swapped for string-domain ids or DICT codes */ if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) { result = exec_group_run(g, op, tbl, group_limit); goto grp_done; } ray_op_ext_t* ext = find_ext(g, op->id); + if (ext && (result = group_const_inputs_check(g, ext, tbl))) goto grp_done; if (!ext || ext->n_keys == 0) { result = exec_group_run(g, op, tbl, group_limit); goto grp_done; } uint32_t nk = ext->n_keys; key_col = (ray_t**)scratch_alloc(&wrap_hdr, - (size_t)nk * (sizeof(ray_t*) + sizeof(int64_t))); + (size_t)nk * (5 * sizeof(void*) + sizeof(int64_t))); if (!key_col) { result = exec_group_run(g, op, tbl, group_limit); goto grp_done; } - dict_sym = (int64_t*)(key_col + nk); - for (uint32_t k = 0; k < nk; k++) key_col[k] = NULL; + sd_col = key_col + nk; + sdom = (ray_strdom_t**)(sd_col + nk); + dc_vec = (ray_t**)(sdom + nk); + dc_d = (const ray_enc_idict_t**)(dc_vec + nk); + dict_sym = (int64_t*)(dc_d + nk); + for (uint32_t k = 0; k < nk; k++) { + key_col[k] = NULL; sd_col[k] = NULL; sdom[k] = NULL; dc_vec[k] = NULL; dc_d[k] = NULL; + } + sd_n = nk; bool any = false; for (uint32_t k = 0; k < nk; k++) { ray_op_t* key_op = op_node(g, ext->keys[k]); ray_op_ext_t* ke = key_op ? find_ext(g, key_op->id) : NULL; if (!ke || ke->base.opcode != OP_SCAN) continue; int64_t sym = ke->sym; - ray_t* col = ray_table_get_col(tbl, sym); - if (!col || col->type != RAY_STR) continue; - if (ray_index_kind(col) != RAY_IDX_DICT) continue; - /* Skip if any non-COUNT agg reads this key column as strings. */ - bool unsafe = false; - for (uint32_t a = 0; a < ext->n_aggs; a++) { - if (ext->agg_ops[a] == OP_COUNT) continue; - ray_op_t* ain = op_node(g, ext->agg_ins[a]); - ray_op_ext_t* ae = ain ? find_ext(g, ain->id) : NULL; - if (ae && ae->base.opcode == OP_SCAN && ae->sym == sym) { unsafe = true; break; } + ray_col_meta_t km; + if (!ray_table_col_meta(tbl, sym, &km)) continue; + /* a single-file generation-2 STR key with a persisted DICT: its + * codes, as generation 0 groups on its DICT codes (spec "5. Group-by + * inputs", P6b), admitted by the swap rule (strdom_key_ok: nothing + * but the key and a plain COUNT of it reads the column, at any + * expression depth); a repeated key is swapped by the first + * occurrence's codes. Declined, the column is read as strings. */ + if (km.enc && !RAY_IS_PARTED(km.type) && km.type == RAY_STR && km.index_kind == RAY_IDX_DICT) { + bool dup = false; + for (uint32_t j = 0; j < k; j++) + if ((dc_vec[j] || sd_col[j] || key_col[j]) && dict_sym[j] == sym) dup = true; + if (dup) continue; + if (strdom_key_ok(g, ext, sym)) { + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(tbl, sym)); + const ray_enc_idict_t* d = NULL; + ray_t* derr = e ? ray_enccol_idict(e, &d) : NULL; + ray_t* cv = NULL; + if (!derr && d) derr = ray_enccol_idict_codes_vec(e, &cv); + if (derr) { result = derr; goto grp_done; } + if (d && cv) { + dc_vec[k] = cv; dc_d[k] = d; dict_sym[k] = sym; + any = true; sd_any = true; + continue; + } + } + } + /* a generation-2 STR key: query-wide domain ids */ + if (km.enc && + (RAY_IS_PARTED(km.type) ? RAY_PARTED_BASETYPE(km.type) : km.type) == RAY_STR) { + bool dup = false; + for (uint32_t j = 0; j < k; j++) if (sd_col[j] && dict_sym[j] == sym) dup = true; + if (dup || !strdom_key_ok(g, ext, sym)) continue; + /* The ids are first-occurrence over the rows generation 0 + * orders this key's groups by. A single-file column as long as + * a saved generation-0 STR column carrying its DICT index + * (RAY_DICT_MIN_ROWS, up to int32 codes): generation 0 groups on + * those codes (above), first-occurrence over the whole column, + * so every row. Otherwise (shorter, or parted, whose segments + * group as STR): the selected rows. */ + bool whole = !RAY_IS_PARTED(km.type) && km.len >= RAY_DICT_MIN_ROWS && km.len <= INT32_MAX; + ray_t* serr = strdom_key_col(tbl, sym, whole ? NULL : g->selection, &sdom[k], &sd_col[k]); + if (serr) { result = serr; goto grp_done; } + dict_sym[k] = sym; + any = true; + sd_any = true; + continue; } - if (unsafe) continue; + if (km.type != RAY_STR || + km.index_kind != RAY_IDX_DICT) continue; + ray_t* dix_blk; + ray_t* ierr = ray_table_col_index(tbl, sym, &dix_blk); + if (ierr) { result = ierr; goto grp_done; } + if (!dix_blk) continue; + ray_t* col = ray_table_col(tbl, sym); /* cached: the index read above decoded it */ + if (!col || RAY_IS_ERR(col)) { result = col ? col : ray_error("oom", NULL); goto grp_done; } + /* The swap rule of the generation-2 arms: nothing but the key and a + * plain count of it may read the column, at any depth (an aggregate + * over (strlen s) would read the I32 codes as strings). */ + if (!strdom_key_ok(g, ext, sym)) continue; key_col[k] = col; dict_sym[k] = sym; any = true; @@ -10408,9 +12975,17 @@ ray_t* exec_group(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) if (!sub || RAY_IS_ERR(sub)) { result = exec_group_run(g, op, tbl, group_limit); goto grp_done; } for (int64_t c = 0; c < ncols; c++) { int64_t name = ray_table_col_name(tbl, c); - ray_t* use = ray_table_get_col_idx(tbl, c); + ray_t* use = ray_table_slot_idx(tbl, c); /* pass encoded slots on undecoded */ for (uint32_t k = 0; k < nk; k++) - if (key_col[k] && dict_sym[k] == name) { + if (dc_vec[k] && dict_sym[k] == name) { + use = dc_vec[k]; + ray_grp_card_add(name, dc_d[k]->n_distinct); + break; + } else if (sd_col[k] && dict_sym[k] == name) { + use = sd_col[k]; + ray_grp_card_add(name, ray_strdom_count(sdom[k])); + break; + } else if (key_col[k] && dict_sym[k] == name) { const ray_index_t* dix = ray_index_payload(key_col[k]->index); use = dix->u.dict.codes; /* Record the dict's distinct-count so exec_group_v2's DA @@ -10424,11 +12999,68 @@ ray_t* exec_group(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) result = exec_group_run(g, op, sub, group_limit); ray_release(sub); + /* A group's result is a table (or an error): a swapped key's ids are + * mapped back below, never returned as the key. */ + if (sd_any && result && !RAY_IS_ERR(result) && result->type != RAY_TABLE) { + ray_release(result); + result = ray_error("nyi", "group: a swapped STR key without a table result"); + goto grp_done; + } if (result && !RAY_IS_ERR(result) && result->type == RAY_TABLE) { for (uint32_t k = 0; k < nk; k++) { + /* the string-domain keys: every scan key of a swapped column + * (a key repeated holds the same ids) */ + int64_t sd = -1, dc = -1; + if (!key_col[k]) { + ray_op_ext_t* ke = find_ext(g, ext->keys[k]); + for (uint32_t j = 0; ke && ke->base.opcode == OP_SCAN && j < nk; j++) + if (dc_vec[j] && dict_sym[j] == ke->sym) { dc = j; break; } + else if (sd_col[j] && dict_sym[j] == ke->sym) { sd = j; break; } + } + if (dc >= 0) { + /* a generation-2 DICT key (every scan key of the column): + * its codes through the persisted entries */ + ray_t* codes_col = ray_table_col_idx(result, k); + if (!codes_col || RAY_IS_ERR(codes_col)) { + ray_release(result); + result = codes_col ? codes_col : ray_error("domain", "group: key column missing"); + break; + } + if (nk == 1 && codes_col->type == RAY_I32) + ray_dict_cd_stash(codes_col, ray_table_nrows(result), dict_sym[dc], tbl, + dc_d[dc]->n_distinct); + ray_t* str_col = dict_entries_to_str(codes_col, dc_d[dc]); + if (!str_col || RAY_IS_ERR(str_col)) { + ray_release(result); + result = str_col ? str_col : ray_error("oom", NULL); + break; + } + ray_table_set_col_idx(result, k, str_col); + ray_release(str_col); + continue; + } + if (sd >= 0) { + ray_t* ids_col = ray_table_col_idx(result, k); + if (!ids_col || RAY_IS_ERR(ids_col)) { + ray_release(result); + result = ids_col ? ids_col : ray_error("domain", "group: key column missing"); + break; + } + ray_t* str_col = NULL; + ray_t* eerr = strdom_key_emit(sdom[sd], ids_col, &str_col); + if (eerr) { ray_release(result); result = eerr; break; } + ray_table_set_col_idx(result, k, str_col); + ray_release(str_col); + continue; + } if (!key_col[k]) continue; - ray_t* codes_col = ray_table_get_col_idx(result, k); + ray_t* codes_col = ray_table_col_idx(result, k); + if (codes_col && RAY_IS_ERR(codes_col)) { + ray_release(result); + result = codes_col; + break; + } if (codes_col && codes_col->type == RAY_I32) { /* Stash the result group codes (single-key only) so * the count-distinct can build row_gid from dict codes instead @@ -10448,6 +13080,10 @@ ray_t* exec_group(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) } } grp_done: + for (uint32_t k = 0; k < sd_n; k++) { + if (sd_col[k]) ray_release(sd_col[k]); + ray_strdom_free(sdom[k]); + } scratch_free(wrap_hdr); /* NULL on early bails → no-op */ if (gvm) { gvm->grp_card_n = sv_grp_n; @@ -10535,7 +13171,7 @@ static inline double sg_prod_range(const agg_prod_t* p, int64_t r0, int64_t n, a2 += x[j + 2] * y[j + 2]; a3 += x[j + 3] * y[j + 3]; } for (; j < n; j++) a0 += x[j] * y[j]; - } else if (ta == RAY_F64 && (tb == RAY_I64 || tb == RAY_TIMESTAMP)) { + } else if (ta == RAY_F64 && (tb == RAY_I64 || tb == RAY_TIMESPAN || tb == RAY_TIMESTAMP)) { const double* restrict x = (const double*)pa + r0; const int64_t* restrict y = (const int64_t*)pb + r0; uint64_t s0 = 0; @@ -10715,7 +13351,7 @@ static void sg_accum_fn(void* raw, uint32_t wid, int64_t tstart, int64_t tend) { bool need_sq = c->partial_sumsq && (op == OP_STDDEV || op == OP_STDDEV_POP || op == OP_VAR || op == OP_VAR_POP); - if (contig && (t == RAY_I64 || t == RAY_TIMESTAMP)) { + if (contig && (t == RAY_I64 || t == RAY_TIMESPAN || t == RAY_TIMESTAMP)) { const int64_t* restrict x = (const int64_t*)p + r0; if (c->partials_hi) { /* exact 128-bit total, still a vectorized stream */ @@ -10815,7 +13451,12 @@ static ray_t* sg_hint_to_selection(ray_graph_t* g, ray_t* tbl) { static bool sg_shape_eligible(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit, ray_t** agg_vecs, ray_t** agg_vecs2, - agg_prod_t* prod) { + agg_prod_t* prod, ray_t** err) { + *err = NULL; + /* Admission reads metadata only; the input columns are fetched (and an + * encoded one decoded) once every aggregate has been admitted. */ + int64_t agg_syms[16], agg_syms2[16]; + for (int i = 0; i < 16; i++) agg_syms[i] = agg_syms2[i] = -1; /* group_limit is a HEAD(GROUP) HINT, not a semantic: this kernel computes * every group and the caller's HEAD trims the result, so a positive limit * is simply ignored here (staying eligible keeps where+by+take shapes on @@ -10830,8 +13471,14 @@ static bool sg_shape_eligible(ray_graph_t* g, ray_op_t* op, ray_t* tbl, /* The single group key must be the bare scan of the probed column. */ ray_op_ext_t* ke = find_ext(g, ext->keys[0]); if (!ke || ke->base.opcode != OP_SCAN) return false; - ray_t* key_col = ray_table_get_col(tbl, ke->sym); - if (!key_col || key_col != g->sg_col) return false; + { + /* sg_col is the plain (decoded) key column the probe found the index + * on; an encoded slot is identified by its slot object or by its + * cached decode, neither of which decodes here. */ + ray_t* slot = ray_table_get_col_enc(tbl, ke->sym); + ray_t* key_col = slot ? ray_enccol_decoded_peek(slot) : ray_table_col(tbl, ke->sym); + if (!key_col || RAY_IS_ERR(key_col) || key_col != g->sg_col) return false; + } for (uint32_t a = 0; a < ext->n_aggs; a++) { uint16_t aop = ext->agg_ops[a]; @@ -10845,40 +13492,55 @@ static bool sg_shape_eligible(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_op_t* in = op_node(g, ext->agg_ins[a]); if (!in) return false; if (!pair && (aop == OP_SUM || aop == OP_AVG) && - try_prod_sumavg_input_f64(g, tbl, in, &prod[a])) + try_prod_sumavg_input_f64(g, tbl, in, &prod[a], err)) continue; + if (*err) return false; /* a failed bind is the caller's error */ ray_op_ext_t* ae = find_ext(g, in->id); if (!ae || ae->base.opcode != OP_SCAN) return false; - ray_t* col = ray_table_get_col(tbl, ae->sym); - if (!col || ray_is_atom(col)) return false; - if (ray_vec_has_nulls(col)) return false; - if (!agg_type_admitted(aop, col->type)) return false; - switch (col->type) { + ray_col_meta_t am; + if (!ray_table_col_meta(tbl, ae->sym, &am) || am.type < 0) return false; + if (ray_table_col_has_nulls(tbl, ae->sym)) return false; + if (!agg_type_admitted(aop, am.type)) return false; + switch (am.type) { case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: case RAY_TIME: case RAY_F32: case RAY_F64: break; default: return false; } - agg_vecs[a] = col; + agg_syms[a] = ae->sym; if (pair) { if (!ext->agg_ins2 || ext->agg_ins2[a] == RAY_OP_NONE) return false; ray_op_t* in2 = op_node(g, ext->agg_ins2[a]); if (!in2) return false; ray_op_ext_t* ae2 = find_ext(g, in2->id); if (!ae2 || ae2->base.opcode != OP_SCAN) return false; - ray_t* col2 = ray_table_get_col(tbl, ae2->sym); - if (!col2 || ray_is_atom(col2)) return false; - if (ray_vec_has_nulls(col2)) return false; - if (!agg_type_admitted(aop, col2->type)) return false; - switch (col2->type) { + ray_col_meta_t am2; + if (!ray_table_col_meta(tbl, ae2->sym, &am2) || am2.type < 0) return false; + if (ray_table_col_has_nulls(tbl, ae2->sym)) return false; + if (!agg_type_admitted(aop, am2.type)) return false; + switch (am2.type) { case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: case RAY_F32: case RAY_F64: break; default: return false; } - agg_vecs2[a] = col2; + agg_syms2[a] = ae2->sym; } else if (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) { return false; } } + for (uint32_t a = 0; a < ext->n_aggs; a++) { + if (agg_syms[a] >= 0) { + ray_t* col = ray_table_col(tbl, agg_syms[a]); + if (col && RAY_IS_ERR(col)) { *err = col; return false; } + if (!col) return false; + agg_vecs[a] = col; + } + if (agg_syms2[a] >= 0) { + ray_t* col2 = ray_table_col(tbl, agg_syms2[a]); + if (col2 && RAY_IS_ERR(col2)) { *err = col2; return false; } + if (!col2) return false; + agg_vecs2[a] = col2; + } + } return true; } @@ -10895,8 +13557,10 @@ ray_t* ray_group_slice_hint_settle(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* agg_vecs2[16] = {0}; agg_prod_t prod[16]; memset(prod, 0, sizeof(prod)); - if (sg_shape_eligible(g, op, tbl, group_limit, agg_vecs, agg_vecs2, prod)) + ray_t* serr = NULL; + if (sg_shape_eligible(g, op, tbl, group_limit, agg_vecs, agg_vecs2, prod, &serr)) return NULL; /* kernel will consume it */ + if (serr) return serr; /* a failed column bind */ return sg_hint_to_selection(g, tbl); /* fold; NULL on success */ } @@ -10906,11 +13570,13 @@ static ray_t* exec_group_slices(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* agg_vecs2[16] = {0}; agg_prod_t prod[16]; memset(prod, 0, sizeof(prod)); - if (!sg_shape_eligible(g, op, tbl, group_limit, agg_vecs, agg_vecs2, prod)) - return NULL; + ray_t* serr = NULL; + if (!sg_shape_eligible(g, op, tbl, group_limit, agg_vecs, agg_vecs2, prod, &serr)) + return serr; /* NULL: not this shape; else a failed column bind */ ray_op_ext_t* ext = find_ext(g, op->id); ray_op_ext_t* ke = find_ext(g, ext->keys[0]); - ray_t* key_col = ray_table_get_col(tbl, ke->sym); + ray_t* key_col = ray_table_col(tbl, ke->sym); /* cached: sg_shape_eligible matched its decode */ + if (!key_col || RAY_IS_ERR(key_col)) return key_col ? key_col : ray_error("oom", NULL); uint32_t n_aggs = ext->n_aggs; int64_t K = g->sg_nslices; @@ -11153,9 +13819,42 @@ static ray_t* exec_group_slices(ray_graph_t* g, ray_op_t* op, ray_t* tbl, return result; } +/* The rows of a constant aggregate input, or NULL when it has none to give + * here: one value (an atom, a one-element vector) spread over the rows, or + * a vector of the table's length, which stands for a column. The legacy + * engine broadcasts the same way; given rows, the constant is grouped as a + * column is, so `(sum 1)` orders its groups as `(sum v)` and `(count v)` + * do. */ +static ray_t* group_const_input_rows(ray_graph_t* g, ray_op_t* in, int64_t nrows) { + ray_op_ext_t* x = find_ext(g, in->id); + ray_t* lit = x ? x->literal : NULL; + if (!lit || RAY_IS_ERR(lit)) return NULL; + if (ray_is_atom(lit) || (ray_is_vec(lit) && lit->len == 1)) + return materialize_broadcast_input(lit, nrows); + if (ray_is_vec(lit) && lit->len == nrows) { ray_retain(lit); return lit; } + return NULL; +} + +static bool group_const_input_spreads(ray_graph_t* g, ray_op_t* in, int64_t nrows) { + ray_op_ext_t* x = find_ext(g, in->id); + ray_t* lit = x ? x->literal : NULL; + if (!lit || RAY_IS_ERR(lit)) return false; + return ray_is_atom(lit) || (ray_is_vec(lit) && (lit->len == 1 || lit->len == nrows)); +} + /* v2 bridge for expression agg inputs — see the call site in * exec_group_run. Returns the v2 result (or an error), or NULL when the * shape is ineligible and the caller should continue on the legacy path. */ +/* Does the expression `in` read an encoded column of `tbl` (or columns it + * cannot name)? */ +static bool grp_expr_reads_enc(ray_graph_t* g, ray_t* tbl, ray_op_t* in) { + int64_t syms[64]; + int n = group_expr_src_syms(g, in->id, syms, 64); + if (n < 0) return true; + for (int i = 0; i < n; i++) if (ray_table_get_col_enc(tbl, syms[i])) return true; + return false; +} + static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) { if (!tbl || tbl->type != RAY_TABLE) return NULL; @@ -11166,8 +13865,9 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * every index loop below is uint32_t. */ if (!ext || ext->n_keys < 1 || ext->n_aggs < 1) return NULL; - /* At least one agg input must be a compiled-expression node; scans, - * COUNT and binary/holistic second inputs pass through untouched. */ + /* At least one agg input must be a compiled-expression node or a + * constant with rows to give (group_const_input_rows); scans, COUNT + * and binary/holistic second inputs pass through untouched. */ int64_t nrows = ray_table_nrows(tbl); if (nrows <= 0) return NULL; uint32_t na = ext->n_aggs, nkk = ext->n_keys; @@ -11176,7 +13876,8 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (ext->agg_ops[a] == OP_COUNT) continue; ray_op_t* in = op_node(g, ext->agg_ins[a]); if (!in) return NULL; - if (in->opcode == OP_SCAN || in->opcode == OP_CONST) continue; + if (in->opcode == OP_SCAN) continue; + if (in->opcode == OP_CONST && !group_const_input_spreads(g, in, nrows)) continue; any_expr = true; } if (!any_expr) return NULL; @@ -11188,19 +13889,32 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, char names[na][16]; for (uint32_t a = 0; a < na; a++) synth[a] = NULL; ray_t* sub = NULL; + ray_t* cerr = NULL; /* a failed column bind: returned instead of the legacy path */ bool ok = true; for (uint32_t a = 0; a < na && ok; a++) { if (ext->agg_ops[a] == OP_COUNT) continue; ray_op_t* in = op_node(g, ext->agg_ins[a]); - if (in->opcode == OP_SCAN || in->opcode == OP_CONST) continue; + if (in->opcode == OP_SCAN) continue; + if (in->opcode == OP_CONST && !group_const_input_spreads(g, in, nrows)) continue; snprintf(names[a], sizeof(names[a]), "_e%u", (unsigned)a); - if (ray_table_get_col(tbl, ray_sym_intern(names[a], strlen(names[a])))) { + ray_col_meta_t shm; + if (ray_table_col_meta(tbl, ray_sym_intern(names[a], strlen(names[a])), &shm)) { ok = false; break; /* user column shadows the synthetic name */ } ray_expr_t ex; ray_t* v; - if (expr_compile(g, tbl, in, &ex)) { + if (in->opcode == OP_CONST) { + v = group_const_input_rows(g, in, nrows); + } else if (expr_compile(g, tbl, in, &ex, &cerr)) { v = expr_eval_full(&ex, nrows); + if (expr_eval_err_fatal(v)) { cerr = v; ok = false; break; } /* a range read failed */ + } else if (cerr || in->opcode == OP_STRLEN || grp_expr_reads_enc(g, tbl, in)) { + /* a failed column bind (the query's error); a strlen, which the + * legacy path aggregates inline (try_strlen_sumavg_input: a null + * cell as length 0, as the keyless select does); or an input + * over an encoded column: the executor would materialize the + * column, the legacy path reads it by range */ + ok = false; break; } else { /* An input the element-wise compiler declines — an `if`, say: * `(sum (if (== st 'bad) 1 0))` used to drop the whole group onto @@ -11216,7 +13930,7 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } if (!v || RAY_IS_ERR(v) || !ray_is_vec(v) || v->len != nrows) { if (v && !RAY_IS_ERR(v)) ray_release(v); - else if (v) ray_release(v); + else if (v) ray_error_free(v); ok = false; break; } synth[a] = v; @@ -11226,8 +13940,8 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, sub = ray_table_new(ncols + na); if (!sub || RAY_IS_ERR(sub)) { ok = false; } for (int64_t c = 0; c < ncols && ok; c++) { - sub = ray_table_add_col(sub, ray_table_col_name(tbl, c), - ray_table_get_col_idx(tbl, c)); + ray_t* pc = ray_table_slot_idx(tbl, c); /* encoded slots pass undecoded */ + sub = ray_table_add_col(sub, ray_table_col_name(tbl, c), pc); if (!sub || RAY_IS_ERR(sub)) ok = false; } for (uint32_t a = 0; a < na && ok; a++) { @@ -11283,7 +13997,8 @@ static ray_t* exec_group_v2_exprs(ray_graph_t* g, ray_op_t* op, ray_t* tbl, result = exec_group_v2(g, op2, sub, group_limit); for (uint32_t a = 0; a < na; a++) if (synth[a]) ray_release(synth[a]); - if (sub) ray_release(sub); + if (sub) { ray_graph_unbind_table(g, sub); ray_release(sub); } + if (cerr) return cerr; return result; /* NULL → legacy path */ } @@ -11329,6 +14044,16 @@ typedef struct { ray_t* match_idx_block; ray_t* vla_hdr; ray_group_emit_filter_t emit_filter; + /* Range reads. staged: the key or some input is generation 2 and not + * materialized. key_src / agg_src[a] are then the staged sources (NULL + * for a plain one, read in place at its absolute row); the parallel + * fill walks the key (R-WALK), the serial passes read every staged + * source through its cursor (R-SPARSE: rows ascend within a pass). + * key_vecs / agg_vecs hold a zero-length stand-in (type, SYM width and + * domain) for each staged column. */ + bool staged; + ray_col_src_t* key_src; + ray_col_src_t** agg_src; } sp_dyn_ctx_t; /* Parallel dense-count fill for the legacy sparse-dynamic path: each worker @@ -11347,22 +14072,24 @@ typedef struct { const int64_t* match_idx; ray_t* rowsel; _Atomic(int) fail; + /* Range reads (R-WALK): src NULL reads key_data as the whole column; a + * staged key (key_data NULL) by pieces. Range errors go to scan_fail. */ + ray_col_src_t* src; + ray_scan_fail_t* scan_fail; } sp_dyn_pcount_ctx_t; -static void sp_dyn_pcount_fn(void* vctx, uint32_t wid, int64_t start, - int64_t end) { - sp_dyn_pcount_ctx_t* c = (sp_dyn_pcount_ctx_t*)vctx; +/* Rows [start, end), the key read from kd (its row rb) at width esz. */ +RAY_INLINE void sp_dyn_pcount_body(sp_dyn_pcount_ctx_t* c, const void* kd, uint8_t esz, int64_t rb, + uint32_t wid, int64_t start, int64_t end) { if (atomic_load_explicit(&c->fail, memory_order_relaxed)) return; uint32_t* my = c->counts + (size_t)(wid % c->n_workers) * c->stride; const int64_t* match_idx = c->match_idx; const uint64_t bound = c->bound; - const uint8_t esz = c->key_esz; - const void* kd = c->key_data; for (int64_t i = start; i < end; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && c->rowsel && !group_rowsel_pass(c->rowsel, r)) continue; - int64_t key = read_by_esz(kd, r, esz); + int64_t key = read_by_esz(kd, r - rb, esz); if ((uint64_t)key >= bound) { /* negative wraps huge — caught too */ atomic_store_explicit(&c->fail, 1, memory_order_relaxed); return; @@ -11371,8 +14098,53 @@ static void sp_dyn_pcount_fn(void* vctx, uint32_t wid, int64_t start, } } +static void sp_dyn_pcount_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + sp_dyn_pcount_ctx_t* c = (sp_dyn_pcount_ctx_t*)ctx; + sp_dyn_pcount_body(c, p[0].data, ray_sym_elem_size(c->src->type, p[0].attrs), b, wid, b, e); +} + +static void sp_dyn_pcount_fn(void* vctx, uint32_t wid, int64_t start, + int64_t end) { + sp_dyn_pcount_ctx_t* c = (sp_dyn_pcount_ctx_t*)vctx; + if (!c->src) { sp_dyn_pcount_body(c, c->key_data, c->key_esz, 0, wid, start, end); return; } + if (atomic_load_explicit(&c->fail, memory_order_relaxed)) return; + if (ray_scan_fail_skip(c->scan_fail, start)) return; + ray_col_src_t* const srcs[1] = { c->src }; + const void* const plain[1] = { NULL }; + ray_t* err = group_sel_walk(srcs, plain, 1, c->match_idx ? NULL : c->rowsel, + start, end, c, wid, sp_dyn_pcount_piece); + if (err) ray_scan_fail_note(c->scan_fail, start, err); +} + +/* R-SPARSE reads of row r through a staged source's cursor: the view + * covering r, NULL with *err set (the first error kept) on failure. */ +static inline const ray_col_range_t* sp_cur_view(ray_col_cursor_t* cur, int64_t r, ray_t** err) { + const ray_col_range_t* v = NULL; + ray_t* e = ray_col_cursor_at(cur, r, &v); + if (e) { if (!*err) *err = e; else ray_error_free(e); return NULL; } + return v; +} +static inline int64_t sp_cur_key(ray_col_cursor_t* cur, int64_t r, ray_t** err) { + const ray_col_range_t* v = sp_cur_view(cur, r, err); + return v ? read_by_esz(v->data, r - v->start, ray_sym_elem_size(v->type, v->attrs)) : 0; +} +static inline double sp_cur_f64(ray_col_cursor_t* cur, int64_t r, int8_t t, ray_t** err) { + const ray_col_range_t* v = sp_cur_view(cur, r, err); + return v ? group_fp_at(v->data, t, r - v->start) : 0.0; +} +static inline int64_t sp_cur_i64(ray_col_cursor_t* cur, int64_t r, int8_t t, ray_t** err) { + const ray_col_range_t* v = sp_cur_view(cur, r, err); + return v ? read_col_i64(v->data, r - v->start, t, v->attrs) : 0; +} +static inline int64_t sp_cur_strlen(ray_col_cursor_t* cur, int64_t r, ray_t** err) { + const ray_col_range_t* v = sp_cur_view(cur, r, err); + return v ? sym_strlen_raw(v->data, r - v->start, v->attrs, v->dom ? v->dom : cur->src->dom) : 0; +} + +/* sp_cur: a staged context's cursors (the key's first, then one per input; + * a plain source's slot unused); NULL for a plain context. */ static ray_t* __attribute__((noinline)) -exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { +exec_group_sp_dyn_emit_run(const sp_dyn_ctx_t* c, ray_col_cursor_t* sp_cur) { ray_graph_t* g = c->g; ray_op_ext_t* ext = c->ext; void** key_data = c->key_data; @@ -11400,6 +14172,8 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { ray_t* match_idx_block = c->match_idx_block; ray_t* vla_hdr = c->vla_hdr; ray_group_emit_filter_t emit_filter = c->emit_filter; + ray_col_src_t* const* agg_src = c->agg_src; + ray_t* sp_err = NULL; /* a staged range read's error: the answer */ uint64_t cap = key_esz == 1 ? 256u : key_esz == 2 ? (1u << 16) @@ -11468,6 +14242,8 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { if (raw) { uint32_t* pc = (uint32_t*)(void*) (((uintptr_t)raw + pc_line - 1) & ~(uintptr_t)(pc_line - 1)); + ray_scan_fail_t pfail; + ray_scan_fail_init(&pfail); sp_dyn_pcount_ctx_t pctx = { .key_data = key_data[0], .key_esz = key_esz, @@ -11478,10 +14254,17 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { .match_idx = match_idx, .rowsel = rowsel, .fail = 0, + .src = c->key_src, + .scan_fail = &pfail, }; + if (c->key_src) ray_col_src_advise(c->key_src, 0, n_scan); ray_pool_dispatch(dp, sp_dyn_pcount_fn, &pctx, n_scan); - if (!atomic_load_explicit(&pctx.fail, + /* R-FAIL: a staged key's range error is the answer */ + if (c->key_src) sp_err = ray_scan_fail_finish(&pfail, dp); + if (sp_err) { + dyn_ok = false; + } else if (!atomic_load_explicit(&pctx.fail, memory_order_relaxed)) { /* Grow range_count to the bound, then merge * worker arrays with saturation. */ @@ -11518,10 +14301,25 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { } } +/* Row reads of the passes below. DYN_ST (defined at each pass) 0: whole + * columns at the absolute row, exactly the plain code; 1: a staged source + * through its cursor (R-SPARSE, rows ascending), its error kept in sp_err. */ +#define DYN_KEY(r) ((DYN_ST && c->key_src) ? sp_cur_key(&sp_cur[0], (r), &sp_err) \ + : read_by_esz(key_data[0], (r), key_esz)) +#define DYN_HAS(a) (agg_ptrs[a] || (DYN_ST && agg_src[a])) +#define DYN_STRLEN(a, r) ((DYN_ST && agg_src[a]) ? sp_cur_strlen(&sp_cur[1 + (a)], (r), &sp_err) \ + : group_strlen_at_cached(agg_vecs[a], (r), strlen_sym_strings, strlen_sym_count)) +#define DYN_F64(a, r) ((DYN_ST && agg_src[a]) ? sp_cur_f64(&sp_cur[1 + (a)], (r), agg_types[a], &sp_err) \ + : group_fp_at(agg_ptrs[a], agg_types[a], (r))) +#define DYN_I64(a, r) ((DYN_ST && agg_src[a]) ? sp_cur_i64(&sp_cur[1 + (a)], (r), agg_types[a], &sp_err) \ + : read_col_i64(agg_ptrs[a], (r), agg_types[a], 0)) +#define DYN_FAILED (DYN_ST && sp_err) + #define DYN_DENSE_ACCUM_ROW(row_expr) \ do { \ int64_t dyn_row = (row_expr); \ - int64_t key = read_by_esz(key_data[0], dyn_row, key_esz); \ + int64_t key = DYN_KEY(dyn_row); \ + if (DYN_FAILED) { dyn_ok = false; goto dyn_dense_done; } \ if (key < 0 || (uint64_t)key >= max_dense_cap) { \ dyn_ok = false; \ goto dyn_dense_done; \ @@ -11573,57 +14371,76 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { if (range_sum) { \ da_val_t* sums = &range_sum[(size_t)off * n_aggs]; \ for (uint32_t a = 0; a < n_aggs; a++) { \ - if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; \ + if (ext->agg_ops[a] == OP_COUNT || !DYN_HAS(a)) continue; \ if (agg_strlen[a]) \ - sums[a].i = wrap_add_i64( \ - sums[a].i, \ - group_strlen_at_cached( \ - agg_vecs[a], dyn_row, strlen_sym_strings, strlen_sym_count)); \ + sums[a].i = wrap_add_i64(sums[a].i, DYN_STRLEN(a, dyn_row)); \ else if (agg_f64_mask & ((uint64_t)1 << a)) \ - sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], dyn_row); \ + sums[a].f += DYN_F64(a, dyn_row); \ else if (range_sum_hi) \ ray_i128_add(&range_sum_hi[(size_t)off * n_aggs + a], \ - (uint64_t*)&sums[a].i, \ - read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0)); \ + (uint64_t*)&sums[a].i, DYN_I64(a, dyn_row)); \ else \ - sums[a].i = wrap_add_i64( \ - sums[a].i, \ - read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0)); \ + sums[a].i = wrap_add_i64(sums[a].i, DYN_I64(a, dyn_row)); \ } \ + if (DYN_FAILED) { dyn_ok = false; goto dyn_dense_done; } \ } \ } while (0) +/* One pass of DYN_DENSE_ACCUM_ROW over the rows (the selection's segments + * ascending), reading through the DYN_* accessors defined at its use. */ +#define DYN_DENSE_ACCUM_PASS() \ + if (dyn_ok && match_idx) { \ + for (int64_t i = 0; i < n_scan; i++) \ + DYN_DENSE_ACCUM_ROW(match_idx[i]); \ + } else if (dyn_ok && rowsel) { \ + ray_rowsel_t* m = ray_rowsel_meta(rowsel); \ + const uint8_t* flags = ray_rowsel_flags(rowsel); \ + const uint32_t* offs = ray_rowsel_offsets(rowsel); \ + const uint16_t* idx = ray_rowsel_idx(rowsel); \ + uint32_t nseg = (uint32_t)((m->nrows + RAY_MORSEL_ELEMS - 1) / \ + RAY_MORSEL_ELEMS); \ + for (uint32_t seg = 0; seg < nseg; seg++) { \ + int64_t base = (int64_t)seg * RAY_MORSEL_ELEMS; \ + if (flags[seg] == RAY_SEL_NONE) continue; \ + if (flags[seg] == RAY_SEL_ALL) { \ + int64_t end = base + RAY_MORSEL_ELEMS; \ + if (end > m->nrows) end = m->nrows; \ + for (int64_t r = base; r < end; r++) \ + DYN_DENSE_ACCUM_ROW(r); \ + } else { \ + for (uint32_t p = offs[seg]; p < offs[seg + 1]; p++) \ + DYN_DENSE_ACCUM_ROW(base + idx[p]); \ + } \ + } \ + } else if (dyn_ok) { \ + for (int64_t r = 0; r < n_scan; r++) \ + DYN_DENSE_ACCUM_ROW(r); \ + } + + if (dyn_par_done) { /* counts merged by the parallel fill above */ - } else if (dyn_ok && match_idx) { - for (int64_t i = 0; i < n_scan; i++) - DYN_DENSE_ACCUM_ROW(match_idx[i]); - } else if (dyn_ok && rowsel) { - ray_rowsel_t* m = ray_rowsel_meta(rowsel); - const uint8_t* flags = ray_rowsel_flags(rowsel); - const uint32_t* offs = ray_rowsel_offsets(rowsel); - const uint16_t* idx = ray_rowsel_idx(rowsel); - uint32_t nseg = (uint32_t)((m->nrows + RAY_MORSEL_ELEMS - 1) / - RAY_MORSEL_ELEMS); - for (uint32_t seg = 0; seg < nseg; seg++) { - int64_t base = (int64_t)seg * RAY_MORSEL_ELEMS; - if (flags[seg] == RAY_SEL_NONE) continue; - if (flags[seg] == RAY_SEL_ALL) { - int64_t end = base + RAY_MORSEL_ELEMS; - if (end > m->nrows) end = m->nrows; - for (int64_t r = base; r < end; r++) - DYN_DENSE_ACCUM_ROW(r); - } else { - for (uint32_t p = offs[seg]; p < offs[seg + 1]; p++) - DYN_DENSE_ACCUM_ROW(base + idx[p]); - } - } - } else if (dyn_ok) { - for (int64_t r = 0; r < n_scan; r++) - DYN_DENSE_ACCUM_ROW(r); + } else if (!sp_cur) { +#define DYN_ST 0 + DYN_DENSE_ACCUM_PASS() +#undef DYN_ST + } else { +#define DYN_ST 1 + DYN_DENSE_ACCUM_PASS() +#undef DYN_ST } dyn_dense_done: +#undef DYN_DENSE_ACCUM_PASS #undef DYN_DENSE_ACCUM_ROW + if (sp_err) { /* R-FAIL: the range error is the answer */ + scratch_free(range_sum_hdr); scratch_free(range_hi_hdr); scratch_free(cnt_hdr); + for (uint32_t a = 0; a < n_aggs; a++) + if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); + for (uint32_t k = 0; k < n_keys; k++) + if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); + return sp_err; + } if (dyn_ok && have_dyn_key) { uint32_t total_groups = 0; @@ -11723,58 +14540,77 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { #define DYN_DENSE_SUM_ROW(row_expr) \ do { \ int64_t dyn_row = (row_expr); \ - int64_t key = read_by_esz(key_data[0], dyn_row, key_esz); \ + int64_t key = DYN_KEY(dyn_row); \ + if (DYN_FAILED) goto dyn_sum_done; \ if (key < 0 || (uint64_t)key > max_seen) break; \ uint32_t marker = range_count[(uint64_t)key]; \ if (!marker) break; \ da_val_t* sums = &dense_sum[(size_t)(marker - 1u) * n_aggs]; \ for (uint32_t a = 0; a < n_aggs; a++) { \ - if (ext->agg_ops[a] == OP_COUNT || !agg_ptrs[a]) continue; \ + if (ext->agg_ops[a] == OP_COUNT || !DYN_HAS(a)) continue; \ if (agg_strlen[a]) \ - sums[a].i = wrap_add_i64( \ - sums[a].i, \ - group_strlen_at_cached( \ - agg_vecs[a], dyn_row, strlen_sym_strings, strlen_sym_count)); \ + sums[a].i = wrap_add_i64(sums[a].i, DYN_STRLEN(a, dyn_row)); \ else if (agg_f64_mask & ((uint64_t)1 << a)) \ - sums[a].f += group_fp_at(agg_ptrs[a], agg_types[a], dyn_row); \ + sums[a].f += DYN_F64(a, dyn_row); \ else if (dense_sum_hi) \ ray_i128_add(&dense_sum_hi[(size_t)(marker - 1u) * n_aggs + a], \ - (uint64_t*)&sums[a].i, \ - read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0)); \ + (uint64_t*)&sums[a].i, DYN_I64(a, dyn_row)); \ else \ - sums[a].i = wrap_add_i64( \ - sums[a].i, \ - read_col_i64(agg_ptrs[a], dyn_row, agg_types[a], 0)); \ + sums[a].i = wrap_add_i64(sums[a].i, DYN_I64(a, dyn_row)); \ } \ + if (DYN_FAILED) goto dyn_sum_done; \ } while (0) - if (match_idx) { - for (int64_t i = 0; i < n_scan; i++) - DYN_DENSE_SUM_ROW(match_idx[i]); - } else if (rowsel) { - ray_rowsel_t* m = ray_rowsel_meta(rowsel); - const uint8_t* flags = ray_rowsel_flags(rowsel); - const uint32_t* offs = ray_rowsel_offsets(rowsel); - const uint16_t* idx = ray_rowsel_idx(rowsel); - uint32_t nseg = (uint32_t)((m->nrows + RAY_MORSEL_ELEMS - 1) / - RAY_MORSEL_ELEMS); - for (uint32_t seg = 0; seg < nseg; seg++) { - int64_t base = (int64_t)seg * RAY_MORSEL_ELEMS; - if (flags[seg] == RAY_SEL_NONE) continue; - if (flags[seg] == RAY_SEL_ALL) { - int64_t end = base + RAY_MORSEL_ELEMS; - if (end > m->nrows) end = m->nrows; - for (int64_t r = base; r < end; r++) - DYN_DENSE_SUM_ROW(r); - } else { - for (uint32_t p = offs[seg]; p < offs[seg + 1]; p++) - DYN_DENSE_SUM_ROW(base + idx[p]); - } - } +#define DYN_DENSE_SUM_PASS() \ + if (match_idx) { \ + for (int64_t i = 0; i < n_scan; i++) \ + DYN_DENSE_SUM_ROW(match_idx[i]); \ + } else if (rowsel) { \ + ray_rowsel_t* m = ray_rowsel_meta(rowsel); \ + const uint8_t* flags = ray_rowsel_flags(rowsel); \ + const uint32_t* offs = ray_rowsel_offsets(rowsel); \ + const uint16_t* idx = ray_rowsel_idx(rowsel); \ + uint32_t nseg = (uint32_t)((m->nrows + RAY_MORSEL_ELEMS - 1) / \ + RAY_MORSEL_ELEMS); \ + for (uint32_t seg = 0; seg < nseg; seg++) { \ + int64_t base = (int64_t)seg * RAY_MORSEL_ELEMS; \ + if (flags[seg] == RAY_SEL_NONE) continue; \ + if (flags[seg] == RAY_SEL_ALL) { \ + int64_t end = base + RAY_MORSEL_ELEMS; \ + if (end > m->nrows) end = m->nrows; \ + for (int64_t r = base; r < end; r++) \ + DYN_DENSE_SUM_ROW(r); \ + } else { \ + for (uint32_t p = offs[seg]; p < offs[seg + 1]; p++) \ + DYN_DENSE_SUM_ROW(base + idx[p]); \ + } \ + } \ + } else { \ + for (int64_t r = 0; r < n_scan; r++) \ + DYN_DENSE_SUM_ROW(r); \ + } + if (!sp_cur) { +#define DYN_ST 0 + DYN_DENSE_SUM_PASS() +#undef DYN_ST } else { - for (int64_t r = 0; r < n_scan; r++) - DYN_DENSE_SUM_ROW(r); +#define DYN_ST 1 + DYN_DENSE_SUM_PASS() +#undef DYN_ST } + dyn_sum_done: +#undef DYN_DENSE_SUM_PASS #undef DYN_DENSE_SUM_ROW + if (sp_err) { /* R-FAIL: the range error is the answer */ + scratch_free(_h_sum); scratch_free(_h_sum_hi); scratch_free(_h_cnt); + scratch_free(range_sum_hdr); scratch_free(range_hi_hdr); scratch_free(cnt_hdr); + ray_release(key_col); ray_release(result); + for (uint32_t a = 0; a < n_aggs; a++) + if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); + for (uint32_t k = 0; k < n_keys; k++) + if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); + return sp_err; + } } ray_op_ext_t* key_ext = find_ext(g, ext->keys[0]); @@ -11808,6 +14644,231 @@ exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { * resources are untouched — caller continues on the next sp path. */ return NULL; } +#undef DYN_KEY +#undef DYN_HAS +#undef DYN_STRLEN +#undef DYN_F64 +#undef DYN_I64 +#undef DYN_FAILED + +/* A staged context reads each staged source through its own cursor for + * the serial passes; they are freed when the route returns. */ +static ray_t* exec_group_sp_dyn_emit(const sp_dyn_ctx_t* c) { + if (!c->staged) return exec_group_sp_dyn_emit_run(c, NULL); + uint32_t n = 1 + c->n_aggs; + ray_col_cursor_t cur[n]; + ray_col_cursor_init(&cur[0], c->key_src); + for (uint32_t a = 0; a < c->n_aggs; a++) ray_col_cursor_init(&cur[1 + a], c->agg_src[a]); + ray_t* r = exec_group_sp_dyn_emit_run(c, cur); + for (uint32_t i = 0; i < n; i++) ray_col_cursor_free(&cur[i]); + return r; +} + +/* ---- Range reads of the single-key sparse paths (R-WALK) ---------------- + * exec_group_run's single-key sparse paths (the emit-filter key-range + * scatter and the sparse i64 table, reached past the dense count) run each + * pass of a staged context by pieces, serially and in row order, so the + * sums fold exactly as the plain loops fold them. srcs[0] is the key's + * source and srcs[1 + a] each staged input's; a plain key or input has a + * NULL slot and is read in place at its absolute row (key_plain, + * agg_ptrs[a]). A COUNT input has no slot: it is never read. Staged SYM + * and STR inputs are not eligible (sp_eligible), so a strlen input is + * always plain. */ +enum { SPW_MINMAX, SPW_RANGE, SPW_MARKER, SPW_HT_COUNT, SPW_HT_SUM, SPW_HEAVY }; +typedef struct { + int pass; + ray_op_ext_t* ext; + uint32_t n_aggs; + int8_t key_type; + const void* key_plain; /* a plain key's base (srcs[0] NULL) */ + uint8_t key_esz; /* its width */ + void* const* agg_ptrs; /* plain inputs' bases; NULL for a staged one */ + const int8_t* agg_types; + const uint8_t* agg_strlen; + ray_t* const* agg_vecs; + ray_t** strlen_sym_strings; + uint32_t strlen_sym_count; + uint64_t agg_f64_mask; + ray_col_src_t** srcs; /* [1 + n_aggs] */ + ray_t* rowsel; + /* the pass's state */ + bool have_key; /* SPW_MINMAX: bounds of the keys read */ + int64_t min_key, max_key; + uint32_t* range_count; /* SPW_RANGE counts, SPW_MARKER markers */ + da_val_t* sums; /* SPW_RANGE: the range sums (NULL: none); MARKER / HEAVY: dense */ + int64_t* sums_hi; /* their high words (integer AVG), or NULL */ + sparse_i64_ht_t* ht; /* HT_COUNT / HT_SUM: the table; HEAVY: the heavy hitters */ + bool need_sum; + bool stop; /* sparse_i64_touch failed: the caller falls back */ +} sp_walk_ctx_t; + +/* Row r's inputs folded into sums (and hi, when not NULL), the staged ones + * read from the piece positioned at row b. Inlined into each pass's row + * loop (sp_walk_rows), as generation 0's loop is into exec_group_run. */ +static inline __attribute__((always_inline)) void sp_walk_sums(const sp_walk_ctx_t* c, const ray_col_piece_t* p, + int64_t b, int64_t r, da_val_t* sums, int64_t* hi) { + for (uint32_t a = 0; a < c->n_aggs; a++) { + if (c->ext->agg_ops[a] == OP_COUNT) continue; + const void* d; + int64_t rr; + if (c->srcs[1 + a]) { d = p[1 + a].data; rr = r - b; } + else if (c->agg_ptrs[a]) { d = c->agg_ptrs[a]; rr = r; } + else continue; + if (c->agg_strlen[a]) + sums[a].i = wrap_add_i64(sums[a].i, group_strlen_at_cached(c->agg_vecs[a], r, + c->strlen_sym_strings, c->strlen_sym_count)); + else if (c->agg_f64_mask & ((uint64_t)1 << a)) + sums[a].f += group_fp_at(d, c->agg_types[a], rr); + else if (hi) + ray_i128_add(&hi[a], (uint64_t*)&sums[a].i, read_col_i64(d, rr, c->agg_types[a], 0)); + else + sums[a].i = wrap_add_i64(sums[a].i, read_col_i64(d, rr, c->agg_types[a], 0)); + } +} + +/* One pass over the rows [b, e) of a piece, `pass` and the key width + * `kesz` constants of each inlined copy (sp_walk_piece switches on them + * once per piece): no per-row pass switch or width read, the pass's state + * held in locals. The key is read at r - kb. */ +static inline __attribute__((always_inline)) void sp_walk_rows(sp_walk_ctx_t* c, const ray_col_piece_t* p, + int64_t b, int64_t e, const void* kd, int64_t kb, + const int pass, const uint8_t kesz) { + const uint32_t n = c->n_aggs; + ray_t* const rowsel = c->rowsel; + uint32_t* const rc = c->range_count; + da_val_t* const sums = c->sums; + int64_t* const sums_hi = c->sums_hi; + sparse_i64_ht_t* const ht = c->ht; + const uint64_t min_key = (uint64_t)c->min_key; + const bool ns = pass == SPW_HT_SUM && c->need_sum; + bool have = c->have_key; + int64_t mn = c->min_key, mx = c->max_key; + for (int64_t r = b; r < e; r++) { + if (rowsel && !group_rowsel_pass(rowsel, r)) continue; + const int64_t key = read_by_esz(kd, r - kb, kesz); + if (pass == SPW_MINMAX) { + if (!have) { mn = mx = key; have = true; } + else if (key < mn) mn = key; + else if (key > mx) mx = key; + } else if (pass == SPW_RANGE) { + uint64_t off = (uint64_t)key - min_key; + if (rc[off] != UINT32_MAX) rc[off]++; + if (sums) sp_walk_sums(c, p, b, r, &sums[(size_t)off * n], sums_hi ? &sums_hi[(size_t)off * n] : NULL); + } else if (pass == SPW_MARKER) { + uint32_t marker = rc[(uint64_t)key - min_key]; + if (!marker) continue; + size_t gi = (size_t)(marker - 1u) * n; + sp_walk_sums(c, p, b, r, &sums[gi], sums_hi ? &sums_hi[gi] : NULL); + } else if (pass == SPW_HT_COUNT || pass == SPW_HT_SUM) { + int32_t slot; + if (!sparse_i64_touch(ht, key, (uint8_t)n, ns, &slot)) { c->stop = true; return; } + ht->counts[slot]++; + if (ns) sp_walk_sums(c, p, b, r, &ht->sums[(size_t)slot * n], + ht->sums_hi ? &ht->sums_hi[(size_t)slot * n] : NULL); + } else { /* SPW_HEAVY */ + int32_t hs = sparse_i64_find_slot(ht, key); + if (!ht->used[hs] || ht->keys[hs] != key) continue; + size_t gi = (size_t)(uint32_t)ht->counts[hs] * n; + sp_walk_sums(c, p, b, r, &sums[gi], sums_hi ? &sums_hi[gi] : NULL); + } + } + if (pass == SPW_MINMAX) { c->have_key = have; c->min_key = mn; c->max_key = mx; } +} + +static void sp_walk_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sp_walk_ctx_t* c = (sp_walk_ctx_t*)ctx; + if (c->stop) return; + const bool ks = c->srcs[0] != NULL; + const void* kd = ks ? p[0].data : c->key_plain; + const int64_t kb = ks ? b : 0; /* the key is read at r - kb */ + const uint8_t kesz = ks ? ray_sym_elem_size(c->key_type, p[0].attrs) : c->key_esz; +#define SPW_WIDTHS(P) do { switch (kesz) { \ + case 1: sp_walk_rows(c, p, b, e, kd, kb, (P), 1); break; \ + case 2: sp_walk_rows(c, p, b, e, kd, kb, (P), 2); break; \ + case 4: sp_walk_rows(c, p, b, e, kd, kb, (P), 4); break; \ + default: sp_walk_rows(c, p, b, e, kd, kb, (P), 8); break; } } while (0) + switch (c->pass) { + case SPW_MINMAX: SPW_WIDTHS(SPW_MINMAX); break; + case SPW_RANGE: SPW_WIDTHS(SPW_RANGE); break; + case SPW_MARKER: SPW_WIDTHS(SPW_MARKER); break; + case SPW_HT_COUNT: SPW_WIDTHS(SPW_HT_COUNT); break; + case SPW_HT_SUM: SPW_WIDTHS(SPW_HT_SUM); break; + default: SPW_WIDTHS(SPW_HEAVY); break; + } +#undef SPW_WIDTHS +} + +/* One pass over rows [lo, hi) by pieces (the selection's rejected morsels + * skipped), polling for cancellation between blocks. A pass that reads no + * input (the bounds, the counts, a range scatter without sums) walks the + * key alone; a pass whose sources are all plain runs as one piece. NULL, + * or the range error keyed by the failing block's first row, or `cancel`. */ +static ray_t* __attribute__((noinline)) +sp_walk_run(sp_walk_ctx_t* c, int pass, int64_t lo, int64_t hi) { + c->pass = pass; + c->stop = false; + bool key_only = pass == SPW_MINMAX || pass == SPW_HT_COUNT || + (pass == SPW_RANGE && !c->sums) || (pass == SPW_HT_SUM && !c->need_sum); + uint32_t n = key_only ? 1 : 1 + c->n_aggs; + bool any = false; + for (uint32_t i = 0; i < n; i++) any |= c->srcs[i] != NULL; + const void* plain[1 + 64] = { 0 }; /* sp_eligible caps n_aggs at 64; plain slots are NULL */ + ray_col_piece_t none[1 + 64]; + memset(none, 0, sizeof none); + ray_scan_fail_t fail; + ray_scan_fail_init(&fail); + for (int64_t s = lo; s < hi && !c->stop; s += 65536) { + if (ray_interrupted()) break; /* ray_scan_fail_finish: `cancel` */ + int64_t q = hi - s > 65536 ? s + 65536 : hi; + if (!any) { sp_walk_piece(c, 0, s, q, none); continue; } + ray_t* err = group_sel_walk(c->srcs, plain, n, c->rowsel, s, q, c, 0, sp_walk_piece); + if (err) { ray_scan_fail_note(&fail, s, err); break; } + } + return ray_scan_fail_finish(&fail, NULL); +} + +/* The key range of the emit-filter scatter, read unsigned (read_by_esz) as + * that scatter reads it. Without a selection a staged key's chunks fold + * their directory bounds where those are exact for the unsigned read (no + * null, and a non-negative minimum or a 64-bit key); every other chunk is + * scanned by range. A selection scans the selected rows. NULL or the + * pass's error. */ +static ray_t* sp_walk_key_range(sp_walk_ctx_t* c, int64_t n_scan) { + c->have_key = false; + ray_col_src_t* src = c->srcs[0]; + ray_enc_chunk_stat_t st; + int64_t nch = (n_scan + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + if (c->rowsel || !src || src->len != n_scan || nch == 0 || !ray_col_src_chunk_stat(src, 0, &st)) + return sp_walk_run(c, SPW_MINMAX, 0, n_scan); + bool have = false; + int64_t mn = 0, mx = 0; + uint8_t esz = ray_sym_elem_size(c->key_type, src->attrs); + for (int64_t ch = 0; ch < nch; ch++) { + (void)ray_col_src_chunk_stat(src, ch, &st); + if (st.has_minmax && st.null_count == 0 && (esz == 8 || st.min >= 0)) { + if (!have || st.min < mn) mn = st.min; + if (!have || st.max > mx) mx = st.max; + have = true; + continue; + } + int64_t lo = ch * RAY_ENC_CHUNK, hi = lo + RAY_ENC_CHUNK < n_scan ? lo + RAY_ENC_CHUNK : n_scan; + ray_t* err = sp_walk_run(c, SPW_MINMAX, lo, hi); /* folds into have_key / min_key / max_key */ + if (err) return err; + } + if (have) { + if (!c->have_key || mn < c->min_key) c->min_key = mn; + if (!c->have_key || mx > c->max_key) c->max_key = mx; + c->have_key = true; + } + return NULL; +} + +/* Route test hook (ray_group_test_route, internal.h). */ +static int g_group_test_route; +void ray_group_test_route(int route) { g_group_test_route = route; } +static int g_group_test_fail_scalar_alloc; +void ray_group_test_fail_scalar_alloc(int fail) { g_group_test_fail_scalar_alloc = fail; } /* The error for a by: key that is no value: a function or null. Out of * line and cold: exec_group_run is hot, and the error is rare. */ @@ -11839,19 +14900,26 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * ray_slice_group_probe): aggregate the key slices directly, or * fold them into the selection the skipped filter would have * produced and continue on the generic paths. */ + if (g->sg_col && g_group_test_route >= 3) { + ray_t* err = sg_hint_to_selection(g, tbl); + if (err) return err; + } if (g->sg_col) { ray_t* sgr = exec_group_slices(g, op, tbl, group_limit); - if (sgr) { agg_route_record(AGG_ROUTE_SLICES); sg_hint_release(g); return sgr; } + if (sgr && !RAY_IS_ERR(sgr)) agg_route_record(AGG_ROUTE_SLICES); + if (sgr) { sg_hint_release(g); return sgr; } ray_t* err = sg_hint_to_selection(g, tbl); if (err) return err; } - /* Parted dispatch: detect parted input columns */ - { + /* Parted dispatch: detect parted input columns (not under an in-place + * concat group, whose parted columns are read from their segments) */ + if (!g->grp_seg_stream) { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) { + ray_col_meta_t pm; + if (ray_table_col_meta_idx(tbl, c, &pm) && + (RAY_IS_PARTED(pm.type) || pm.type == RAY_MAPCOMMON)) { agg_route_record(AGG_ROUTE_PARTED); return exec_group_parted(g, op, tbl, group_limit); } @@ -11869,7 +14937,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * the dense finishes select the kept groups natively and every other * route trims its full result (exec_group_v2), so an armed filter never * routes a shape v2 admits onto the ladder. */ - agg_v2_reason_t admission = !ray_agg_engine_v2 ? AGG_V2_DISABLED + agg_v2_reason_t admission = !ray_agg_engine_v2 || g_group_test_route >= 1 ? AGG_V2_DISABLED : group_limit < 0 ? AGG_V2_SHAPE : agg_v2_admission(g, op, tbl); agg_route_reason(admission); @@ -11894,6 +14962,51 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (r) return r; } + /* OP_COUNT_NN (internal, see exec_group_per_partition) is served by the + * v2 kernels only. A group bound for the legacy engine is re-planned + * with each such slot as SUM over a not-null indicator of the same input + * (SUM over BOOL emits I64), so the op is valid whichever route the group + * takes and no caller has to predict it. Node creation may realloc + * g->nodes: work on ids, build the pointer arrays after the last new + * node, and return straight away (`op` itself may dangle). */ + for (uint32_t a = 0; a < ext->n_aggs; a++) { + if (ext->agg_ops[a] != OP_COUNT_NN) continue; + uint32_t na = ext->n_aggs, nk = ext->n_keys; + uint16_t ops2[na]; + uint32_t in_ids[na]; + for (uint32_t i = 0; i < na; i++) { + ops2[i] = ext->agg_ops[i]; + in_ids[i] = ext->agg_ins[i]; + } + for (uint32_t i = 0; i < na; i++) { + if (ops2[i] != OP_COUNT_NN) continue; + ray_op_t* isn = ray_isnull(g, op_node(g, in_ids[i])); + ray_op_t* nn = isn ? ray_not(g, isn) : NULL; + if (!nn) return ray_error("oom", NULL); + ops2[i] = OP_SUM; + in_ids[i] = nn->id; + } + bool has2 = false, hask = false; + ray_op_t* keys[nk > 0 ? nk : 1]; + ray_op_t* ins[na]; + ray_op_t* ins2[na]; + for (uint32_t k = 0; k < nk; k++) + keys[k] = op_node(g, ext->keys[k]); + for (uint32_t i = 0; i < na; i++) { + ins[i] = op_node(g, in_ids[i]); + ins2[i] = (ext->agg_ins2 && ext->agg_ins2[i] != RAY_OP_NONE) + ? op_node(g, ext->agg_ins2[i]) : NULL; + if (ins2[i]) has2 = true; + if (ext->agg_k && ext->agg_k[i]) hask = true; + } + ray_op_t* op2 = (has2 || hask) + ? ray_group_build(g, keys, nk, ops2, ins, has2 ? ins2 : NULL, + hask ? ext->agg_k : NULL, na) + : ray_group(g, keys, nk, ops2, ins, na); + if (!op2) return ray_error("oom", NULL); + return exec_group_run(g, op2, tbl, group_limit); + } + agg_route_record(AGG_ROUTE_LEGACY); int64_t nrows = ray_table_nrows(tbl); uint32_t n_keys = ext->n_keys; @@ -11919,10 +15032,11 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * not just the presence of a _count column. */ if (g->selection && n_keys == 1 && n_aggs > 0 && nrows > 0) { int64_t cnt_sym_probe = ray_sym_intern("_count", 6); - ray_t* cnt_col_probe = ray_table_get_col(tbl, cnt_sym_probe); + ray_col_meta_t cnt_probe_m; + bool cnt_probe_ok = ray_table_col_meta(tbl, cnt_sym_probe, &cnt_probe_m); ray_op_ext_t* key_ext_probe = find_ext(g, ext->keys[0]); int64_t src_sym_probe = ray_sym_intern("_src", 4); - if (cnt_col_probe && cnt_col_probe->type == RAY_I64 && + if (cnt_probe_ok && cnt_probe_m.type == RAY_I64 && key_ext_probe && key_ext_probe->base.opcode == OP_SCAN && key_ext_probe->sym == src_sym_probe) { /* Reject on ANY agg whose semantics depend on the @@ -11962,8 +15076,8 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } if (!g->selection && n_keys == 1 && n_aggs > 0 && nrows > 0) { int64_t cnt_sym = ray_sym_intern("_count", 6); - ray_t* cnt_col = ray_table_get_col(tbl, cnt_sym); - if (cnt_col && cnt_col->type == RAY_I64) { + ray_col_meta_t cnt_m; + if (ray_table_col_meta(tbl, cnt_sym, &cnt_m) && cnt_m.type == RAY_I64) { ray_op_ext_t* key_ext = find_ext(g, ext->keys[0]); int64_t src_sym = ray_sym_intern("_src", 4); if (key_ext && key_ext->base.opcode == OP_SCAN && @@ -11985,8 +15099,11 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (all_compat) { /* The factorized table already has one row per group. * Build result with _src key + agg columns from _count. */ - ray_t* src_col = ray_table_get_col(tbl, src_sym); - if (src_col) { + ray_t* src_col = ray_table_col(tbl, src_sym); + if (src_col && RAY_IS_ERR(src_col)) return src_col; + ray_t* cnt_col = ray_table_col(tbl, cnt_sym); /* the result holds plain columns */ + if (cnt_col && RAY_IS_ERR(cnt_col)) return cnt_col; + if (src_col && cnt_col) { int64_t out_nkeys = 1; int64_t out_ncols = out_nkeys + n_aggs; ray_t* result = ray_table_new((int64_t)out_ncols); @@ -12056,11 +15173,39 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * used to consult the dict known-cardinality map for the DA-reject. */ int64_t key_scan_sym[vla_keys]; for (uint32_t k = 0; k < vla_keys; k++) key_scan_sym[k] = -1; + /* Bound sources of the scan keys (R-BIND): key_srcs[k] set with + * key_vecs[k] NULL is a generation-2 key not materialized (staged), read + * by range on the direct-array routes; every other route takes its plain + * column (group_unstage). The sources are the graph's (borrowed). */ + ray_col_src_t* key_srcs[vla_keys]; + memset(key_srcs, 0, vla_keys * sizeof(ray_col_src_t*)); + /* Sources this function binds for plain keys of a staged direct-array + * context, released with the inputs' own sources (AGG_OWN_SRC_RELEASE). */ + ray_col_src_t key_own_src[vla_keys]; + memset(key_own_src, 0, vla_keys * sizeof(ray_col_src_t)); for (uint32_t k = 0; k < n_keys; k++) { ray_op_t* key_op = op_node(g, ext->keys[k]); ray_op_ext_t* key_ext = find_ext(g, key_op->id); if (key_ext && key_ext->base.opcode == OP_SCAN) { - key_vecs[k] = ray_table_get_col(tbl, key_ext->sym); + ray_t* kerr = NULL; + if (ray_col_bind_declines(tbl, key_ext->sym)) { + key_vecs[k] = ray_table_col(tbl, key_ext->sym); /* today's path (partition key, slice) */ + if (key_vecs[k] && RAY_IS_ERR(key_vecs[k])) { kerr = key_vecs[k]; key_vecs[k] = NULL; } + } else { + ray_col_src_t* src = ray_graph_bind_col(g, tbl, key_ext->sym, &kerr); /* no decode */ + if (src && !kerr) { + ray_t* ready = ray_col_src_ready(src); + if (ready && !RAY_IS_PARTED(ready->type)) key_vecs[k] = ready; + else if (RAY_IS_PARTED(src->obj->type)) key_vecs[k] = src->obj; /* plain parted wrapper: + * never here (exec_group_parted) */ + else key_srcs[k] = src; /* staged */ + } + } + if (kerr) { + for (uint32_t j = 0; j < k; j++) + if (key_owned[j] && key_vecs[j]) ray_release(key_vecs[j]); + return kerr; + } key_scan_sym[k] = key_ext->sym; } else { /* Expression key (CASE WHEN etc) — evaluate against current tbl */ @@ -12105,9 +15250,15 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } key_vecs[k] = vec; key_owned[k] = 1; + } else if (vec) { + /* The key's own error (a column that cannot materialize, + * say), not "not found". */ + for (uint32_t j = 0; j < k; j++) + if (key_owned[j] && key_vecs[j]) ray_release(key_vecs[j]); + return vec; } } - if (!key_vecs[k]) { + if (!key_vecs[k] && !key_srcs[k]) { for (uint32_t j = 0; j < k; j++) if (key_owned[j] && key_vecs[j]) ray_release(key_vecs[j]); return ray_error("domain", "by: column not found in table"); @@ -12133,7 +15284,8 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * `cleanup:` label). */ uint32_t vla_aggs = n_aggs > 0 ? n_aggs : 1; ray_t* vla_hdr = NULL; - size_t vla_bytes = (size_t)vla_aggs * (2 * sizeof(ray_t*) + size_t vla_bytes = (size_t)vla_aggs * (2 * sizeof(ray_t*) + 2 * sizeof(ray_col_src_t*) + + 2 * sizeof(ray_col_src_t) + sizeof(agg_affine_t) + sizeof(agg_linear_t) + sizeof(agg_prod_t) + 3 * sizeof(uint8_t)); uint8_t* vla_blk = (uint8_t*)scratch_calloc(&vla_hdr, vla_bytes); @@ -12144,13 +15296,48 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } ray_t** agg_vecs = (ray_t**)vla_blk; ray_t** agg_vecs2 = agg_vecs + vla_aggs; - agg_affine_t* agg_affine = (agg_affine_t*)(agg_vecs2 + vla_aggs); + /* Bound sources of the inputs (R-BIND). agg_srcs[a] set with + * agg_vecs[a] NULL: a generation-2 input not materialized (staged), read + * by range on the scalar route; every other route receives its plain + * column at da_path. agg_own_src: sources this function binds (an + * encoded affine / strlen base, a plain input of a staged context), + * released at its exits (AGG_OWN_SRC_RELEASE). */ + ray_col_src_t** agg_srcs = (ray_col_src_t**)(agg_vecs2 + vla_aggs); + /* The binary aggregates' second inputs, bound the same way: agg_srcs2[a] + * set with agg_vecs2[a] NULL is a staged y-side. */ + ray_col_src_t** agg_srcs2 = agg_srcs + vla_aggs; + ray_col_src_t* agg_own_src = (ray_col_src_t*)(agg_srcs2 + vla_aggs); + /* plain y-sides bound in a staged direct-array context */ + ray_col_src_t* agg_own_src2 = agg_own_src + vla_aggs; + agg_affine_t* agg_affine = (agg_affine_t*)(agg_own_src2 + vla_aggs); agg_linear_t* agg_linear = (agg_linear_t*)(agg_affine + vla_aggs); agg_prod_t* agg_prod = (agg_prod_t*)(agg_linear + vla_aggs); uint8_t* agg_owned = (uint8_t*)(agg_prod + vla_aggs); uint8_t* agg_owned2 = agg_owned + vla_aggs; uint8_t* agg_strlen = agg_owned2 + vla_aggs; + #define AGG_OWN_SRC_RELEASE() do { \ + for (uint32_t s_ = 0; s_ < vla_aggs; s_++) { \ + if (agg_own_src[s_].obj) ray_col_src_release(&agg_own_src[s_]); \ + if (agg_own_src2[s_].obj) ray_col_src_release(&agg_own_src2[s_]); \ + } \ + for (uint32_t s_ = 0; s_ < vla_keys; s_++) \ + if (key_own_src[s_].obj) ray_col_src_release(&key_own_src[s_]); \ + } while (0) + + /* Binary aggregators (OP_PEARSON_CORR) carry cross-term row slots + * (off_sum_y / off_sumsq_y / off_sumxy) and a y-side input that the + * scalar da_accum_t path neither allocates nor reads — mirror the + * DA-path guard below and fall through to the HT path which computes + * them. Without this the Pearson slot accumulates nothing and emit + * falls to its integer default, returning 0. */ + bool sc_has_binary = false; + for (uint32_t a = 0; a < n_aggs; a++) + if (agg_is_binary_agg(ext->agg_ops[a])) { sc_has_binary = true; break; } + /* The scalar route is the one that emits a FLOAT affine bias over an + * integer column as F64 (emit_agg_columns); the others decline it. */ + bool sc_route = n_keys == 0 && nrows > 0 && !sc_has_binary; + ray_t* rerr = NULL; /* a failed column bind in the planners below */ for (uint32_t a = 0; a < n_aggs; a++) { ray_op_t* agg_input_op = op_node(g, ext->agg_ins[a]); ray_op_ext_t* agg_ext = find_ext(g, agg_input_op->id); @@ -12158,47 +15345,86 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, /* SUM/AVG(scan +/- const): aggregate base scan and apply bias at emit. */ uint16_t agg_kind = ext->agg_ops[a]; if ((agg_kind == OP_SUM || agg_kind == OP_AVG) && - try_affine_sumavg_input(g, tbl, agg_input_op, &agg_vecs[a], &agg_affine[a])) { + try_affine_sumavg_input(g, tbl, agg_input_op, sc_route, + &agg_vecs[a], &agg_affine[a], &rerr)) { + if (agg_vecs[a] && agg_vecs[a]->type == RAY_ENCCOL) { /* staged base */ + rerr = ray_col_src_bind(agg_vecs[a], &agg_own_src[a]); + agg_vecs[a] = NULL; + if (rerr) goto resolve_fail; + agg_srcs[a] = &agg_own_src[a]; + } continue; } + if (rerr) goto resolve_fail; if ((agg_kind == OP_SUM || agg_kind == OP_AVG) && - try_strlen_sumavg_input(g, tbl, agg_input_op, &agg_vecs[a])) { + try_strlen_sumavg_input(g, tbl, agg_input_op, &agg_vecs[a], &rerr)) { agg_strlen[a] = 1; + if (agg_vecs[a] && agg_vecs[a]->type == RAY_ENCCOL) { /* staged SYM */ + rerr = ray_col_src_bind(agg_vecs[a], &agg_own_src[a]); + agg_vecs[a] = NULL; + if (rerr) goto resolve_fail; + agg_srcs[a] = &agg_own_src[a]; + } continue; } + if (rerr) goto resolve_fail; /* SUM/AVG(integer-linear expr): scalar path can aggregate directly * without materializing the expression vector. */ if (n_keys == 0 && nrows > 0 && (agg_kind == OP_SUM || agg_kind == OP_AVG) && - try_linear_sumavg_input_i64(g, tbl, agg_input_op, &agg_linear[a])) { + try_linear_sumavg_input_i64(g, tbl, agg_input_op, &agg_linear[a], &rerr)) { continue; } + if (rerr) goto resolve_fail; /* SUM/AVG(a * b) float product: the scalar and DA accumulators * multiply per row; paths without the fused read (radix sp / HT) * materialize on entry via group_materialize_prod_slots. */ if ((agg_kind == OP_SUM || agg_kind == OP_AVG) && nrows > 0 && - try_prod_sumavg_input_f64(g, tbl, agg_input_op, &agg_prod[a])) { + try_prod_sumavg_input_f64(g, tbl, agg_input_op, &agg_prod[a], &rerr)) { continue; } + if (rerr) goto resolve_fail; if (agg_ext && agg_ext->base.opcode == OP_SCAN) { - agg_vecs[a] = ray_table_get_col(tbl, agg_ext->sym); + if (ray_col_bind_declines(tbl, agg_ext->sym)) { + agg_vecs[a] = ray_table_col(tbl, agg_ext->sym); /* today's path (partition key, slice) */ + if (agg_vecs[a] && RAY_IS_ERR(agg_vecs[a])) { + rerr = agg_vecs[a]; + agg_vecs[a] = NULL; + goto resolve_fail; + } + } else { + ray_col_src_t* src = ray_graph_bind_col(g, tbl, agg_ext->sym, &rerr); /* no decode */ + if (rerr) goto resolve_fail; + agg_srcs[a] = src; + ray_t* ready = src ? ray_col_src_ready(src) : NULL; + agg_vecs[a] = (ready && !RAY_IS_PARTED(ready->type)) ? ready : NULL; /* NULL: staged */ + if (src && !agg_vecs[a] && RAY_IS_PARTED(src->obj->type)) { + /* a plain parted wrapper (never reaches this route: + * exec_group_parted takes parted tables) */ + agg_vecs[a] = src->obj; + agg_srcs[a] = NULL; + } + } } else if (agg_ext && agg_ext->base.opcode == OP_CONST && agg_ext->literal) { agg_vecs[a] = agg_ext->literal; } else { /* Expression node (ADD/MUL etc) — try compiled expression first */ ray_expr_t agg_expr; - if (expr_compile(g, tbl, agg_input_op, &agg_expr)) { + if (expr_compile(g, tbl, agg_input_op, &agg_expr, &rerr)) { ray_t* vec = expr_eval_full(&agg_expr, nrows); if (vec && !RAY_IS_ERR(vec)) { agg_vecs[a] = vec; agg_owned[a] = 1; goto resolve_ins2; } - if (vec && RAY_IS_ERR(vec)) ray_release(vec); + if (expr_eval_err_fatal(vec)) { rerr = vec; goto resolve_fail; } + if (vec && RAY_IS_ERR(vec)) ray_error_free(vec); + } else if (rerr) { + goto resolve_fail; } /* Fallback: full recursive evaluation */ ray_t* saved_table = g->table; @@ -12210,6 +15436,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { if (agg_owned[i] && agg_vecs[i]) ray_release(agg_vecs[i]); if (agg_owned2[i] && agg_vecs2[i]) ray_release(agg_vecs2[i]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); scratch_free(vla_hdr); return vec; } @@ -12227,21 +15454,40 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_op_t* agg_input_op2 = op_node(g, ext->agg_ins2[a]); ray_op_ext_t* agg_ext2 = find_ext(g, agg_input_op2->id); if (agg_ext2 && agg_ext2->base.opcode == OP_SCAN) { - agg_vecs2[a] = ray_table_get_col(tbl, agg_ext2->sym); + if (ray_col_bind_declines(tbl, agg_ext2->sym)) { + agg_vecs2[a] = ray_table_col(tbl, agg_ext2->sym); /* today's path (partition key, slice) */ + if (agg_vecs2[a] && RAY_IS_ERR(agg_vecs2[a])) { + rerr = agg_vecs2[a]; + agg_vecs2[a] = NULL; + goto resolve_fail; + } + } else { + ray_col_src_t* src = ray_graph_bind_col(g, tbl, agg_ext2->sym, &rerr); /* no decode */ + if (rerr) goto resolve_fail; + ray_t* ready = src ? ray_col_src_ready(src) : NULL; + if (ready && !RAY_IS_PARTED(ready->type)) agg_vecs2[a] = ready; + else if (src && RAY_IS_PARTED(src->obj->type)) agg_vecs2[a] = src->obj; /* never here */ + else agg_srcs2[a] = src; /* staged (or absent: NULL) */ + } } else if (agg_ext2 && agg_ext2->base.opcode == OP_CONST && agg_ext2->literal) { agg_vecs2[a] = agg_ext2->literal; } else { ray_expr_t agg_expr2; int compiled2 = 0; - if (expr_compile(g, tbl, agg_input_op2, &agg_expr2)) { + if (expr_compile(g, tbl, agg_input_op2, &agg_expr2, &rerr)) { ray_t* vec = expr_eval_full(&agg_expr2, nrows); if (vec && !RAY_IS_ERR(vec)) { agg_vecs2[a] = vec; agg_owned2[a] = 1; compiled2 = 1; + } else if (expr_eval_err_fatal(vec)) { + rerr = vec; + goto resolve_fail; } else if (vec) { - ray_release(vec); + ray_error_free(vec); } + } else if (rerr) { + goto resolve_fail; } if (!compiled2) { ray_t* saved_table = g->table; @@ -12254,6 +15500,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { if (agg_owned[i] && agg_vecs[i]) ray_release(agg_vecs[i]); if (agg_owned2[i] && agg_vecs2[i]) ray_release(agg_vecs2[i]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); scratch_free(vla_hdr); return vec; } @@ -12266,6 +15513,20 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } } + if (0) { + resolve_fail: + for (uint32_t i = 0; i < n_aggs; i++) { + if (agg_owned[i] && agg_vecs[i]) ray_release(agg_vecs[i]); + if (agg_owned2[i] && agg_vecs2[i]) ray_release(agg_vecs2[i]); + } + for (uint32_t k = 0; k < n_keys; k++) + if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); + if (match_idx_block) ray_release(match_idx_block); + scratch_free(vla_hdr); + return rerr; + } + /* Normalize scalar agg inputs to full-length vectors. * Constants and scalar sub-expressions (len=1) must be broadcast to nrows * before row-wise aggregation loops. */ @@ -12286,6 +15547,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, for (uint32_t k = 0; k < n_keys; k++) { if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); } + AGG_OWN_SRC_RELEASE(); scratch_free(vla_hdr); return bcast && RAY_IS_ERR(bcast) ? bcast : ray_error("oom", NULL); } @@ -12294,6 +15556,31 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, agg_vecs[a] = bcast; agg_owned[a] = 1; } + /* Same for the second input of a binary agg (wsum/wavg/cov/scov/ + * pearson_corr): a literal or constant-folded operand is an atom, and + * the pair loops index it per row. */ + for (uint32_t a = 0; a < n_aggs; a++) { + if (!agg_vecs2[a] || RAY_IS_ERR(agg_vecs2[a])) continue; + bool needs_broadcast = ray_is_atom(agg_vecs2[a]) || + (agg_vecs2[a]->type > 0 && agg_vecs2[a]->len == 1 && nrows > 1); + if (!needs_broadcast) continue; + + ray_t* bcast = materialize_broadcast_input(agg_vecs2[a], nrows); + if (!bcast || RAY_IS_ERR(bcast)) { + for (uint32_t i = 0; i < n_aggs; i++) { + { if (agg_owned[i] && agg_vecs[i]) ray_release(agg_vecs[i]); if (agg_owned2[i] && agg_vecs2[i]) ray_release(agg_vecs2[i]); } + } + for (uint32_t k = 0; k < n_keys; k++) { + if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + } + scratch_free(vla_hdr); + return bcast && RAY_IS_ERR(bcast) ? bcast : ray_error("oom", NULL); + } + + if (agg_owned2[a]) ray_release(agg_vecs2[a]); + agg_vecs2[a] = bcast; + agg_owned2[a] = 1; + } /* Pre-compute key metadata. VLA sized to vla_keys (== max(n_keys,1)), * matching key_vecs above: the width guard is retired (unbounded-slots @@ -12307,6 +15594,10 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, key_data[k] = ray_data(key_vecs[k]); key_types[k] = key_vecs[k]->type; key_attrs[k] = key_vecs[k]->attrs; + } else if (key_srcs[k]) { + key_data[k] = NULL; /* staged: read by range */ + key_types[k] = key_srcs[k]->type; + key_attrs[k] = key_srcs[k]->attrs; } else { key_data[k] = NULL; key_types[k] = 0; @@ -12346,17 +15637,18 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ext->agg_ops[emit_filter.agg_index] == OP_MAX); /* ---- Scalar aggregate fast path (n_keys == 0): flat vector scan ---- */ - /* Binary aggregators (OP_PEARSON_CORR) carry cross-term row slots - * (off_sum_y / off_sumsq_y / off_sumxy) and a y-side input that the - * scalar da_accum_t path neither allocates nor reads — mirror the - * DA-path guard below and fall through to the HT path which computes - * them. Without this the Pearson slot accumulates nothing and emit - * falls to its integer default, returning 0. */ - bool sc_has_binary = false; - for (uint32_t a = 0; a < n_aggs; a++) - if (agg_is_binary_agg(ext->agg_ops[a])) { sc_has_binary = true; break; } - if (n_keys == 0 && nrows > 0 && !sc_has_binary) { + if (sc_route) { + /* Staged inputs this route cannot read by pieces take their plain + * column (R-RANDOM: holistic and row-gathered aggregates, wide + * types, any op outside the streaming set). */ + for (uint32_t a = 0; a < n_aggs; a++) { + if (agg_vecs[a] || !agg_srcs[a] || scalar_stageable(agg_srcs[a]->type, ext->agg_ops[a])) + continue; + ray_t* uerr = agg_unstage(agg_srcs[a], &agg_vecs[a], &agg_owned[a]); + if (uerr) { rerr = uerr; goto resolve_fail; } + } uint8_t need_flags = DA_NEED_COUNT; + bool has_first_last = false; /* the storage-chunk route reads no FIRST / LAST */ for (uint32_t a = 0; a < n_aggs; a++) { uint16_t aop = ext->agg_ops[a]; if (aop == OP_SUM || aop == OP_PROD || aop == OP_AVG || aop == OP_ALL || aop == OP_ANY || aop == OP_FIRST || aop == OP_LAST) @@ -12365,12 +15657,13 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { need_flags |= DA_NEED_SUM; need_flags |= DA_NEED_SUMSQ; } else if (aop == OP_MIN) need_flags |= DA_NEED_MIN; else if (aop == OP_MAX) need_flags |= DA_NEED_MAX; + if (aop == OP_FIRST || aop == OP_LAST) has_first_last = true; } /* Keyless path serves unbounded n_aggs — VLAs here scale with the query, * so carve exactly (8-byte arrays first). */ ray_t* sc_vla_hdr = NULL; - size_t sc_vla_bytes = (size_t)vla_aggs * (sizeof(void*) + sizeof(int64_t) + size_t sc_vla_bytes = (size_t)vla_aggs * (4 * sizeof(void*) + sizeof(int64_t) + sizeof(int8_t) + sizeof(bool)); uint8_t* sc_blk = (uint8_t*)scratch_alloc(&sc_vla_hdr, sc_vla_bytes); if (!sc_blk) { @@ -12378,11 +15671,15 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("oom", NULL); } void* *agg_ptrs = (void**)sc_blk; - int64_t *sc_int_null_sentinel = (int64_t*)(agg_ptrs + vla_aggs); + ray_col_src_t** sc_srcs = (ray_col_src_t**)(agg_ptrs + vla_aggs); /* staged only */ + const void** sc_plain = (const void**)(sc_srcs + vla_aggs); /* staged only */ + const ray_str_t** sc_agg_str = (const ray_str_t**)(sc_plain + vla_aggs); + int64_t *sc_int_null_sentinel = (int64_t*)(sc_agg_str + vla_aggs); int8_t *agg_types = (int8_t*)(sc_int_null_sentinel + vla_aggs); /* Per-element flag, not a bitmask: this path's n_aggs is VLA-sized * with no fixed cap, so a fixed-width bitmask would silently alias @@ -12391,6 +15688,9 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, bool sc_any_nullable = false; /* Integer AVG divides the exact 128-bit sum: carry high words. */ bool sc_need_sum128 = false; + bool sc_has_f64_affine = false; + /* Some input is read by range (a staged source, agg_ptrs NULL). */ + bool sc_staged = false; for (uint32_t a = 0; a < n_aggs; a++) { if (agg_prod[a].enabled) { /* Fused product: F64 accumulate, no source vec. */ @@ -12400,20 +15700,32 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, sc_int_null_has[a] = false; continue; } - if (agg_vecs[a]) { - agg_ptrs[a] = ray_data(agg_vecs[a]); - agg_types[a] = agg_vecs[a]->type; - sc_int_null_sentinel[a] = agg_int_null_sentinel_for(agg_vecs[a]->type); + /* A staged input: type and nullability from its bound source */ + ray_col_src_t* ssrc = (!agg_vecs[a] && agg_srcs[a]) ? agg_srcs[a] : NULL; + if (agg_vecs[a] || ssrc) { + int8_t t = ssrc ? ssrc->type : agg_vecs[a]->type; + /* text always may hold nulls, as ray_vec_may_have_nulls + * answers for the plain column */ + bool may_null = ssrc ? (ssrc->may_null || t == RAY_SYM || t == RAY_STR) + : ray_vec_may_have_nulls(agg_vecs[a]); + agg_ptrs[a] = ssrc ? NULL : ray_data(agg_vecs[a]); /* NULL: staged, read by pieces */ + agg_types[a] = t; + sc_int_null_sentinel[a] = agg_int_null_sentinel_for(t); + if (ssrc && ext->agg_ops[a] != OP_COUNT) sc_staged = true; /* Only flag int-null for storage types whose sentinel is * meaningful. BOOL/U8 are non-nullable; SYM zero is the * canonical empty value and must be skipped by aggregates. - * F64 has its own NaN path. */ - int8_t t = agg_vecs[a]->type; - bool is_sentinel_typed = (t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || - t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_SYM); - sc_int_null_has[a] = is_sentinel_typed && ray_vec_may_have_nulls(agg_vecs[a]); - if (ray_vec_may_have_nulls(agg_vecs[a]) && - (group_fp_type(agg_vecs[a]->type) || is_sentinel_typed)) + * F64 has its own NaN path. A strlen fusion reads lengths: + * its null is length 0 (the empty string, the STR/SYM null + * that exec_strlen maps to null), already the STR/SYM + * sentinel. Only an AVG needs it — a SUM adds 0 either way. */ + bool is_sentinel_typed = agg_strlen[a] + ? ext->agg_ops[a] == OP_AVG + : (t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_SYM); + sc_int_null_has[a] = is_sentinel_typed && may_null; + if (may_null && + (group_fp_type(t) || is_sentinel_typed)) sc_any_nullable = true; } else { agg_ptrs[a] = NULL; @@ -12424,10 +15736,17 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (ext->agg_ops[a] == OP_AVG && !group_fp_type(agg_types[a]) && !agg_strlen[a] && group_avg_needs_hi(agg_types[a], nrows)) sc_need_sum128 = true; + /* An F64 sum of integers does not wrap: emit it from the + * exact 128-bit total. */ + if (agg_affine[a].f64) { + sc_need_sum128 = true; + sc_has_f64_affine = true; + } } if (!match_idx && !rowsel && !sc_any_nullable && n_aggs > 1) { ray_t* base_col = NULL; + ray_col_src_t* base_src = NULL; /* a staged base: read through its source */ const void* base_ptr = NULL; int8_t base_type = 0; int64_t base_len = 0; @@ -12451,7 +15770,18 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, slot_ptr = agg_ptrs[a]; slot_type = agg_vecs[a]->type; slot_len = agg_vecs[a]->len; - if (!base_col) base_col = agg_vecs[a]; + if (!base_col && !base_src) base_col = agg_vecs[a]; + } else if (!agg_vecs[a] && agg_srcs[a]) { + /* staged: slots compare by the bound object (one + * column bound twice, as two affine bases, is one) */ + if (!agg_type_admitted(OP_SUM, agg_srcs[a]->type)) { + one_base_input = false; + break; + } + slot_ptr = agg_srcs[a]->obj; + slot_type = agg_srcs[a]->type; + slot_len = agg_srcs[a]->len; + if (!base_col && !base_src) base_src = agg_srcs[a]; } else if (agg_linear[a].enabled && agg_linear[a].n_terms == 1 && agg_linear[a].coeff_i64[0] == 1 && @@ -12485,21 +15815,31 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * and let the parallel scan below carry the high word. */ int64_t zone_hi = 0, zone_nn = 0; uint64_t zone_lo = 0; bool zone_128 = false; - if (one_base_input && base_col && sc_need_sum128 && + if (one_base_input && (base_col || base_src) && sc_need_sum128 && !group_fp_type(base_type)) { - zone_128 = ray_zone_int_sum128(base_col, &zone_hi, &zone_lo, &zone_nn) + /* a staged base: the directory twin of the same total */ + zone_128 = (base_src ? ray_zone_dir_int_sum128(base_src->obj, &zone_hi, &zone_lo, &zone_nn) + : ray_zone_int_sum128(base_col, &zone_hi, &zone_lo, &zone_nn)) && zone_nn == nrows; if (!zone_128) one_base_input = false; } - if (one_base_input && base_col) { + if (one_base_input && (base_col || base_src)) { + /* A staged base sums through its source: the directory + * where ray_sum_fn answers from the zone, else exactly + * ray_sum_fn's DAG reduction (float sums bit-identical). + * NULL: a type the source does not serve, no shortcut. */ ray_t* base_sum_obj = zone_128 ? ray_i64((int64_t)zone_lo) - : ray_sum_fn(base_col); + : base_src ? ray_reduce_src(base_src, OP_SUM, + group_fp_type(base_type) ? RAY_F64 : RAY_I64) + : ray_sum_fn(base_col); + if (!base_sum_obj && base_src) goto one_base_done; if (!base_sum_obj || RAY_IS_ERR(base_sum_obj)) { scratch_free(sc_vla_hdr); for (uint32_t a = 0; a < n_aggs; a++) { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) ray_release(match_idx_block); scratch_free(vla_hdr); return base_sum_obj ? base_sum_obj : ray_error("oom", NULL); @@ -12512,6 +15852,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) ray_release(match_idx_block); scratch_free(vla_hdr); return base_sum_obj ? base_sum_obj : ray_error("oom", NULL); @@ -12552,7 +15893,11 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, counts[0] = nrows; ray_t* result = ray_table_new(n_aggs); - if (!result || RAY_IS_ERR(result)) { + ray_t* sv_hdr = NULL; + ray_t** emit_vecs = (result && !RAY_IS_ERR(result)) + ? scalar_emit_vecs(&sv_hdr, agg_vecs, agg_srcs, n_aggs) : NULL; + if (!result || RAY_IS_ERR(result) || !emit_vecs) { + if (result && !RAY_IS_ERR(result)) { ray_release(result); result = NULL; } scratch_free(sum_hdr); scratch_free(cnt_hdr); ray_release(base_sum_obj); @@ -12561,32 +15906,82 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) ray_release(match_idx_block); scratch_free(vla_hdr); return result ? result : ray_error("oom", NULL); } - emit_agg_columns(&result, g, ext, agg_vecs, 1, n_aggs, + emit_agg_columns(&result, g, ext, emit_vecs, 1, n_aggs, sums_f64, sums_i64, sums_hi, NULL, NULL, NULL, NULL, counts, agg_affine, agg_prod, NULL, NULL, NULL, NULL, NULL); + scalar_emit_vecs_free(sv_hdr, emit_vecs, agg_vecs, n_aggs); scratch_free(sum_hdr); scratch_free(cnt_hdr); ray_release(base_sum_obj); scratch_free(sc_vla_hdr); - for (uint32_t a = 0; a < n_aggs; a++) - { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } - for (uint32_t k = 0; k < n_keys; k++) - if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); - if (match_idx_block) ray_release(match_idx_block); - scratch_free(vla_hdr); - return result; + for (uint32_t a = 0; a < n_aggs; a++) + { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } + for (uint32_t k = 0; k < n_keys; k++) + if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); + if (match_idx_block) ray_release(match_idx_block); + scratch_free(vla_hdr); + return result; + } + scratch_free(sum_hdr); + scratch_free(cnt_hdr); + } + ray_release(base_sum_obj); + } + } + one_base_done:; + + /* The chunk route (scalar_chunk_fn): a staged context, no row list + * and no FIRST / LAST, a selection over exactly these rows, and a + * statistics rule for every input (a plain column beside the staged + * ones is read by rows). */ + uint8_t sc_rule[vla_aggs]; + bool sc_chunk_route = sc_staged && !match_idx && !has_first_last && + (!rowsel || ray_rowsel_meta(rowsel)->nrows == nrows); + for (uint32_t a = 0; a < n_aggs; a++) { + sc_rule[a] = SC_RULE_NONE; + if (!sc_chunk_route) continue; + uint16_t aop = ext->agg_ops[a]; + if (aop != OP_COUNT && (agg_prod[a].enabled || agg_linear[a].enabled || agg_strlen[a] || + (!agg_vecs[a] && !agg_srcs[a]))) { sc_chunk_route = false; continue; } + sc_rule[a] = scalar_chunk_rule(agg_types[a], aop); + if (sc_rule[a] == SC_RULE_NONE) sc_chunk_route = false; + } + + /* A staged context reads every input through a source (R-WALK): + * plain inputs are bound beside the staged ones, COUNT reads none. */ + ray_scan_fail_t sc_fail; + ray_scan_fail_init(&sc_fail); + if (sc_staged) { + for (uint32_t a = 0; a < n_aggs; a++) { + sc_srcs[a] = NULL; + sc_plain[a] = NULL; + if (agg_prod[a].enabled || ext->agg_ops[a] == OP_COUNT) { agg_ptrs[a] = NULL; continue; } + if (!agg_vecs[a] && !agg_srcs[a]) continue; /* linear plan / absent */ + if (agg_srcs[a]) { + sc_srcs[a] = agg_srcs[a]; + } else { + ray_t* berr = ray_col_src_bind(agg_vecs[a], &agg_own_src[a]); + if (berr) { + scratch_free(sc_vla_hdr); + rerr = berr; + goto resolve_fail; } - scratch_free(sum_hdr); - scratch_free(cnt_hdr); + sc_srcs[a] = &agg_own_src[a]; } - ray_release(base_sum_obj); + /* the source's in-place base: NULL for a staged source and + * for a plain parted wrapper (no single base), read by range */ + sc_plain[a] = ray_col_src_base(sc_srcs[a]); + /* the chunk route reads ahead only the chunks it reads by rows */ + if (!sc_plain[a] && !sc_chunk_route) ray_col_src_advise(sc_srcs[a], 0, nrows); } } @@ -12618,14 +16013,57 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, if (sc_any_nullable) { sc_off_nn = sc_words; sc_words += n_aggs; } size_t sc_bytes = ((sc_words * sizeof(int64_t)) + sc_line - 1) / sc_line * sc_line; ray_t* sc_hdr = NULL; - void* sc_raw = scratch_calloc(&sc_hdr, (size_t)sc_n * sc_bytes + sc_line); - if (!sc_raw) { scratch_free(sc_vla_hdr); goto da_path; } - + /* After the per-chunk blocks: one pinned vocabulary per aggregate. */ + const size_t sc_pin_off = (size_t)sc_n * sc_bytes + sc_line; + bool fail_scalar_alloc = g_group_test_fail_scalar_alloc != 0; + g_group_test_fail_scalar_alloc = 0; + void* sc_raw = fail_scalar_alloc ? NULL : scratch_calloc(&sc_hdr, sc_pin_off + + (size_t)n_aggs * (sizeof(ray_sym_domain_raw_t) + 1) + sc_line); + if (!sc_raw) { + scratch_free(sc_vla_hdr); + /* The fallback emit cannot apply an F64 affine bias. Report + * the allocation failure instead of returning an I64 sum with + * the bias silently dropped. */ + if (sc_has_f64_affine) { + rerr = ray_error("oom", NULL); + goto resolve_fail; + } + goto da_path; + } + ray_sym_domain_raw_t* sc_agg_raw = (ray_sym_domain_raw_t*)(void*) + (((uintptr_t)sc_raw + sc_pin_off + sc_line - 1) & ~(uintptr_t)(sc_line - 1)); + uint8_t* sc_agg_raw_ok = (uint8_t*)(sc_agg_raw + n_aggs); + + /* strlen-on-STR: resolve the descriptors once. strlen-on-SYM: + * pin each column's vocabulary once (a FILE-domain column reads its + * strings from the mapping) and borrow the sym snapshot once (as the + * DA path does) for runtime-domain ids — the uncached resolve takes + * the domain per row, and the workers contend on it. */ + ray_t** sc_sym_strings = NULL; + uint32_t sc_sym_count = 0; + for (uint32_t a = 0; a < n_aggs; a++) { + sc_agg_str[a] = NULL; + if (!agg_strlen[a] || !agg_vecs[a]) continue; + if (agg_vecs[a]->type == RAY_STR) { + const char* pool; (void)pool; + str_resolve(agg_vecs[a], &sc_agg_str[a], &pool); + } else if (agg_vecs[a]->type == RAY_SYM) { + sc_agg_raw_ok[a] = ray_sym_domain_raw_pin( + ray_sym_vec_domain(agg_vecs[a]), &sc_agg_raw[a]) ? 1 : 0; + if (!sc_sym_strings) + ray_sym_strings_borrow(&sc_sym_strings, &sc_sym_count); + } + } scalar_ctx_t sc_ctx = { .agg_ptrs = agg_ptrs, .agg_types = agg_types, .agg_cols = agg_vecs, .agg_strlen = agg_strlen, + .sym_strings = sc_sym_strings, + .sym_count = sc_sym_count, + .agg_str = sc_agg_str, + .agg_raw = sc_agg_raw, + .agg_raw_ok = sc_agg_raw_ok, .agg_ops = ext->agg_ops, .agg_linear = agg_linear, .agg_prod = agg_prod, @@ -12635,6 +16073,12 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, .rowsel = rowsel, .agg_int_null_has = sc_int_null_has, .agg_int_null_sentinel = sc_int_null_sentinel, + .row_base = 0, + .srcs = sc_staged ? sc_srcs : NULL, + .plain = sc_staged ? sc_plain : NULL, + .piece_attrs = NULL, + .fail = &sc_fail, + .staged = sc_staged, /* 8-byte words from the first line boundary of the carve */ .acc_base = (int64_t*)(void*)(((uintptr_t)sc_raw + sc_line - 1) & ~(uintptr_t)(sc_line - 1)), .acc_words = sc_bytes / sizeof(int64_t), @@ -12662,8 +16106,15 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, bool agg0_has_nulls = n_aggs > 0 && (sc_int_null_has[0] || (agg_vecs[0] && group_fp_type(agg_vecs[0]->type) && - ray_vec_may_have_nulls(agg_vecs[0]))); - if (n_aggs == 1 && !match_idx && !rowsel && agg_ptrs[0] != NULL && !agg0_has_nulls) { + ray_vec_may_have_nulls(agg_vecs[0])) || + (!agg_vecs[0] && agg_srcs[0] && group_fp_type(agg_srcs[0]->type) && + agg_srcs[0]->may_null)); + /* A strlen fusion reads lengths, never raw cells: keep it off the + * raw-cell sum loops even when SUM does not track nulls. */ + /* A staged single input takes the tight kernels through the piece + * walk (never a SYM one: SYM always may hold nulls). */ + if (n_aggs == 1 && !match_idx && !rowsel && (agg_ptrs[0] != NULL || sc_staged) && !agg0_has_nulls && + !agg_strlen[0]) { uint16_t op0 = ext->agg_ops[0]; int8_t t0 = agg_types[0]; if ((op0 == OP_SUM || op0 == OP_AVG) && @@ -12679,20 +16130,28 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, sc_ctx.range_fn = sc_fn; - if (sc_n > 1 && ray_pool_par_dispatch_ok(sc_pool, n_scan, RAY_PARALLEL_THRESHOLD)) { - ray_pool_dispatch_n(sc_pool, scalar_chunk_fn, &sc_ctx, (uint32_t)sc_n); - if (pool_cancelled(sc_pool)) { - scratch_free(sc_hdr); - scratch_free(sc_vla_hdr); - for (uint32_t a = 0; a < n_aggs; a++) - { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } - for (uint32_t k = 0; k < n_keys; k++) - if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); - if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); - return ray_error("cancel", NULL); - } - } else { - for (int64_t k = 0; k < sc_n; k++) scalar_chunk_run(&sc_ctx, k); + /* Every input with a statistics rule: the rows storage chunk by + * storage chunk (scalar_chunk_fn), else the block kernels; either + * way one accumulator set per scan chunk, folded in chunk order. */ + bool sc_by_chunk = sc_chunk_route && sc_chunk_grid_ok(sc_srcs, sc_rule, n_aggs, nrows); + sc_chunk_ctx_t sc_cc = { .c = &sc_ctx, .rule = sc_rule, .nrows = nrows }; + if (sc_chunk_route && !sc_by_chunk) /* the block dispatch reads ahead as it always did */ + for (uint32_t a = 0; a < n_aggs; a++) + if (sc_srcs[a] && !sc_plain[a]) ray_col_src_advise(sc_srcs[a], 0, nrows); + scalar_red_ctx_t sc_rc = { .c = &sc_ctx, .cc = sc_by_chunk ? &sc_cc : NULL }; + bool sc_par = sc_n > 1 && ray_pool_par_dispatch_ok(sc_pool, n_scan, RAY_PARALLEL_THRESHOLD) && + atomic_load_explicit(&g_scalar_test_grain, memory_order_relaxed) <= 0; + if (sc_par) ray_pool_dispatch_n(sc_pool, scalar_red_chunk_fn, &sc_rc, (uint32_t)sc_n); + else scalar_red_chunk_fn(&sc_rc, 0, 0, sc_n); + /* R-FAIL: a range error (or a cancelled staged dispatch) is the + * answer; the partial accumulators are discarded. */ + ray_t* sc_err = sc_staged ? ray_scan_fail_finish(&sc_fail, sc_par ? sc_pool : NULL) : NULL; + if (!sc_err && sc_par && pool_cancelled(sc_pool)) sc_err = ray_error("cancel", NULL); + if (sc_err) { + scratch_free(sc_hdr); + scratch_free(sc_vla_hdr); + rerr = sc_err; + goto resolve_fail; } /* Fold the chunks into chunk 0's accumulators, in chunk order */ @@ -12747,7 +16206,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } else if (agg_types[a] == RAY_SYM) { if (wa->min_val[a].i != INT64_MAX && (m->min_val[a].i == INT64_MAX || - sym_lex_lt(ray_sym_vec_domain(agg_vecs[a]), + sym_lex_lt(scalar_sym_dom(&sc_ctx, a), wa->min_val[a].i, m->min_val[a].i))) m->min_val[a].i = wa->min_val[a].i; } else { @@ -12764,7 +16223,7 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, } else if (agg_types[a] == RAY_SYM) { if (wa->max_val[a].i != INT64_MIN && (m->max_val[a].i == INT64_MIN || - sym_lex_gt(ray_sym_vec_domain(agg_vecs[a]), + sym_lex_gt(scalar_sym_dom(&sc_ctx, a), wa->max_val[a].i, m->max_val[a].i))) m->max_val[a].i = wa->max_val[a].i; } else { @@ -12782,23 +16241,29 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, /* Emit 1-row result with no key columns */ ray_t* result = ray_table_new(n_aggs); - if (!result || RAY_IS_ERR(result)) { + ray_t* sv_hdr = NULL; + ray_t** emit_vecs = (result && !RAY_IS_ERR(result)) + ? scalar_emit_vecs(&sv_hdr, agg_vecs, agg_srcs, n_aggs) : NULL; + if (!result || RAY_IS_ERR(result) || !emit_vecs) { + if (result && !RAY_IS_ERR(result)) { ray_release(result); result = NULL; } scratch_free(sc_hdr); scratch_free(sc_vla_hdr); for (uint32_t a = 0; a < n_aggs; a++) { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result ? result : ray_error("oom", NULL); } - emit_agg_columns(&result, g, ext, agg_vecs, 1, n_aggs, + emit_agg_columns(&result, g, ext, emit_vecs, 1, n_aggs, (double*)m->sum, (int64_t*)m->sum, m->sum_hi, (double*)m->min_val, (double*)m->max_val, (int64_t*)m->min_val, (int64_t*)m->max_val, m->count, agg_affine, agg_prod, m->sumsq_f64, m->nn_count, NULL, NULL, NULL); + scalar_emit_vecs_free(sv_hdr, emit_vecs, agg_vecs, n_aggs); /* Row-gathered min/max/first/last cannot be represented in * emit_agg_columns' fixed-width accumulator slots. Recompute those @@ -12906,11 +16371,29 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result; } da_path:; + /* The direct-array routes (DA, the sparse-dynamic count), the + * single-key sparse paths and the fat-entry routes at ht_path read + * staged keys and inputs by range. */ + /* Some key or input is staged (a generation-2 column not materialized). */ + bool grp_staged = false; + for (uint32_t k = 0; k < n_keys; k++) if (key_srcs[k]) grp_staged = true; + for (uint32_t a = 0; a < n_aggs; a++) + if ((!agg_vecs[a] && agg_srcs[a]) || (!agg_vecs2[a] && agg_srcs2[a])) grp_staged = true; + /* match_idx is never built here (a selection streams as the rowsel), + * so a staged context never has one. Every staged reader below relies + * on that (grp_run walks rows, or R-SPARSE over its own survivor list, + * never match_idx). */ + assert(!(grp_staged && match_idx) && "group: a staged context with a flattened selection"); + /* The single-key sparse paths' stand-ins for the staged key and inputs + * (bit a: input a), dropped again at ht_path. */ + bool sp_sv_key = false; + uint64_t sp_sv_agg = 0; /* ---- Direct-array fast path for low-cardinality integer keys ---- */ /* Supports multi-key via a composite index when its state remains O(input). */ { @@ -12919,7 +16402,7 @@ da_path:; * agg). Wider agg lists route to the hash (HT) path instead, which * carries per-agg arrays rather than a fixed-width bitmask. */ bool da_eligible = (n_scan > 0 && n_keys > 0 && n_keys <= 8 && - n_aggs <= 64); + n_aggs <= 64) && g_group_test_route < 2; /* Selection-sparse gate (restored from the pre-#326 routing): with a * bitmap rowsel and no flattened match_idx, both DA scans (min/max * prescan and accumulate) visit every input row and test the bitmap @@ -12958,7 +16441,18 @@ da_path:; * be accumulated as a real value — must stay on the HT path. */ if (agg_is_binary_agg(aop)) { ray_t* yv2 = (agg_vecs2 ? agg_vecs2[a] : NULL); - if (!yv2) { da_eligible = false; } + ray_col_src_t* ys = (!yv2 && agg_srcs2[a]) ? agg_srcs2[a] : NULL; /* staged */ + if (ys) { + /* the same gate on the source's type, length and nullability */ + int8_t t2 = ys->type; + bool y_fp = group_fp_type(t2); + bool y_int = (t2 == RAY_I16 || t2 == RAY_I32 || t2 == RAY_I64 || + t2 == RAY_DATE || t2 == RAY_TIME || t2 == RAY_TIMESTAMP || + t2 == RAY_BOOL || t2 == RAY_U8); + if (ys->len < n_scan || (!y_fp && !y_int) || (!y_fp && ys->may_null)) + da_eligible = false; + } + else if (!yv2) { da_eligible = false; } else if (yv2->len < n_scan) { /* Short y (e.g. an OP_CONST vector literal): da_accum_row * indexes y by absolute row — would read out of bounds. */ @@ -12987,9 +16481,12 @@ da_path:; if (agg_vecs[a] && agg_needs_row_gather(agg_vecs[a]->type, aop)) da_eligible = false; + if (!agg_vecs[a] && agg_srcs[a] && + agg_needs_row_gather(agg_srcs[a]->type, aop)) + da_eligible = false; } for (uint32_t k = 0; k < n_keys && da_eligible; k++) { - if (!key_data[k]) { da_eligible = false; break; } + if (!key_data[k] && !key_srcs[k]) { da_eligible = false; break; } int8_t t = key_types[k]; if (t != RAY_I64 && t != RAY_SYM && t != RAY_I32 && t != RAY_TIMESTAMP && t != RAY_DATE && t != RAY_TIME @@ -13003,6 +16500,8 @@ da_path:; ? key_vecs[k]->slice_parent : key_vecs[k]; if (t != RAY_SYM && ray_vec_may_have_nulls(src)) da_eligible = false; + } else if (t != RAY_SYM && key_srcs[k]->may_null) { + da_eligible = false; /* staged: the directory's null counts */ } } @@ -13038,8 +16537,17 @@ da_path:; bool da_fits = false; + /* A staged key's bounds come from its directory statistics where + * every chunk has them (no decode); under a selection those bound + * the selected rows too (a superset range). Should that superset + * not fit, the prescan runs again by range over the selected rows, + * so the route is the one generation 0 takes. */ + bool mm_dir_ok = true; + da_prescan: if (da_eligible) { da_fits = true; + bool mm_dir_wide = false; /* a directory superset was used */ + total_slots = 1; ray_pool_t* mm_pool = ray_pool_get(); uint32_t mm_n = (mm_pool && nrows >= RAY_PARALLEL_THRESHOLD) ? ray_pool_total_workers(mm_pool) : 1; @@ -13054,23 +16562,62 @@ da_path:; mm_mins[w] = INT64_MAX; mm_maxs[w] = INT64_MIN; } - minmax_ctx_t mm_ctx = { - .key_data = key_data[k], - .key_type = key_types[k], - .key_attrs = key_attrs[k], - .per_worker_min = mm_mins, - .per_worker_max = mm_maxs, - .n_workers = mm_n, - .match_idx = match_idx, - .rowsel = rowsel, - .span_budget = (int64_t)da_slot_budget, - .abort_flag = &mm_abort, - }; - if (mm_n > 1) { - ray_pool_dispatch(mm_pool, minmax_scan_fn, &mm_ctx, n_scan); - } else { - minmax_scan_fn(&mm_ctx, 0, 0, n_scan); + /* Staged key: fold the directory's chunk bounds; chunks + * without statistics (and not all null) are scanned. */ + ray_t* sc_hdr = NULL; + uint8_t* scan_chunk = NULL; + bool mm_scan = true; + if (key_srcs[k] && mm_dir_ok) { + ray_enc_chunk_stat_t st; + int64_t nch = (key_srcs[k]->len + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK; + if (nch > 0 && ray_col_src_chunk_stat(key_srcs[k], 0, &st)) { + scan_chunk = (uint8_t*)scratch_calloc(&sc_hdr, (size_t)nch); + if (!scan_chunk) { rerr = ray_error("oom", NULL); goto resolve_fail; } + int64_t dmin = INT64_MAX, dmax = INT64_MIN; + mm_scan = false; + for (int64_t ch = 0; ch < nch; ch++) { + (void)ray_col_src_chunk_stat(key_srcs[k], ch, &st); + if ((int64_t)st.null_count >= st.rows) continue; /* all null */ + if (!st.has_minmax) { scan_chunk[ch] = 1; mm_scan = true; continue; } + if (st.min < dmin) dmin = st.min; + if (st.max > dmax) dmax = st.max; + } + mm_mins[0] = dmin; + mm_maxs[0] = dmax; + if (rowsel) mm_dir_wide = true; + } } + ray_scan_fail_t mm_fail; + ray_scan_fail_init(&mm_fail); + if (mm_scan) { + minmax_ctx_t mm_ctx = { + .key_data = key_data[k], + .key_type = key_types[k], + .key_attrs = key_attrs[k], + .per_worker_min = mm_mins, + .per_worker_max = mm_maxs, + .n_workers = mm_n, + .match_idx = match_idx, + .rowsel = rowsel, + .span_budget = (int64_t)da_slot_budget, + .abort_flag = &mm_abort, + .row_base = 0, + .src = key_srcs[k], + .scan_chunk = scan_chunk, + .fail = &mm_fail, + }; + if (key_srcs[k]) ray_col_src_advise(key_srcs[k], 0, nrows); + if (mm_n > 1) { + ray_pool_dispatch(mm_pool, minmax_scan_fn, &mm_ctx, n_scan); + } else { + minmax_scan_fn(&mm_ctx, 0, 0, n_scan); + } + } + scratch_free(sc_hdr); + /* R-FAIL: a staged key's range error is the answer */ + ray_t* mm_err = key_srcs[k] && mm_scan + ? ray_scan_fail_finish(&mm_fail, mm_n > 1 ? mm_pool : NULL) : NULL; + if (mm_err) { rerr = mm_err; goto resolve_fail; } if (atomic_load_explicit(&mm_abort, memory_order_relaxed)) { da_fits = false; break; @@ -13104,6 +16651,10 @@ da_path:; } total_slots *= range; } + if (!da_fits && mm_dir_wide) { /* a superset did not fit: the exact range */ + mm_dir_ok = false; + goto da_prescan; + } } if (da_fits) { @@ -13165,6 +16716,8 @@ da_path:; * F64 with HAS_NULLS uses NaN-skip; sentinel-typed integers * with HAS_NULLS use sentinel-skip. */ bool da_any_nullable = false; + /* An AVG(strlen) slot counts its empty-string rows (sl_null). */ + bool da_strlen_avg = false; for (uint32_t a = 0; a < n_aggs; a++) { /* y-side plumbing for binary aggs (PEARSON/COV/WAVG/WSUM). * Eligibility (above) already rejected nullable-int and @@ -13172,7 +16725,11 @@ da_path:; * branch skips those PAIRS, so nn must be allocated or the * emitter would divide by the full group count. */ agg_ptrs2[a] = NULL; agg_types2[a] = 0; - if (agg_is_binary_agg(ext->agg_ops[a]) && agg_vecs2 && agg_vecs2[a]) { + if (agg_is_binary_agg(ext->agg_ops[a]) && !agg_vecs2[a] && agg_srcs2[a]) { + agg_types2[a] = agg_srcs2[a]->type; /* staged: read by pieces */ + if (group_fp_type(agg_types2[a]) && agg_srcs2[a]->may_null) + da_any_nullable = true; + } else if (agg_is_binary_agg(ext->agg_ops[a]) && agg_vecs2 && agg_vecs2[a]) { agg_ptrs2[a] = ray_data(agg_vecs2[a]); agg_types2[a] = agg_vecs2[a]->type; ray_t* ysrc = (agg_vecs2[a]->attrs & RAY_ATTR_SLICE) @@ -13189,22 +16746,31 @@ da_path:; da_int_null_sentinel[a] = 0; continue; } - if (agg_vecs[a]) { - agg_ptrs[a] = ray_data(agg_vecs[a]); - agg_types[a] = agg_vecs[a]->type; - if (group_fp_type(agg_vecs[a]->type)) + /* A staged input: type and nullability from its bound source + * (text always may hold nulls, as ray_vec_may_have_nulls + * answers for the plain column); read by pieces. */ + ray_col_src_t* ssrc = (!agg_vecs[a] && agg_srcs[a]) ? agg_srcs[a] : NULL; + if (agg_vecs[a] || ssrc) { + int8_t t = ssrc ? ssrc->type : agg_vecs[a]->type; + bool may_null = ssrc ? (ssrc->may_null || t == RAY_SYM || t == RAY_STR) + : ray_vec_may_have_nulls(agg_vecs[a]); + agg_ptrs[a] = ssrc ? NULL : ray_data(agg_vecs[a]); + agg_types[a] = t; + if (group_fp_type(t)) agg_f64_mask |= ((uint64_t)1 << a); - da_int_null_sentinel[a] = agg_int_null_sentinel_for(agg_vecs[a]->type); + da_int_null_sentinel[a] = agg_int_null_sentinel_for(t); /* Only set the int-null mask bit for storage types whose * sentinel is meaningful. BOOL/U8 are non-nullable; SYM - * zero is skipped by aggregates. F64 has its own NaN path. */ - int8_t t = agg_vecs[a]->type; - bool is_sentinel_typed = (t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || - t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_SYM); - if (is_sentinel_typed && ray_vec_may_have_nulls(agg_vecs[a])) + * zero is skipped by aggregates. F64 has its own NaN path. + * A strlen fusion reads lengths, not these cells: an + * AVG counts its nulls apart (sl_null), off the mask + * and the per-agg non-null counts. */ + bool is_sentinel_typed = !agg_strlen[a] && + (t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_SYM); + if (is_sentinel_typed && may_null) da_int_null_mask |= ((uint64_t)1 << a); - if (ray_vec_may_have_nulls(agg_vecs[a]) && - (group_fp_type(agg_vecs[a]->type) || is_sentinel_typed)) + if (may_null && (group_fp_type(t) || is_sentinel_typed)) da_any_nullable = true; } else { agg_ptrs[a] = NULL; @@ -13214,6 +16780,8 @@ da_path:; if (ext->agg_ops[a] == OP_AVG && !(agg_f64_mask & ((uint64_t)1 << a)) && !agg_strlen[a] && group_avg_needs_hi(agg_types[a], nrows)) da_need_sum128 = true; + if (agg_strlen[a] && ext->agg_ops[a] == OP_AVG) + da_strlen_avg = true; } ray_pool_t* da_pool = ray_pool_get(); @@ -13232,6 +16800,7 @@ da_path:; /* Nullable aggs add a per-(group, agg) non-null count array. * ~8 bytes per (group, agg). */ if (da_any_nullable) arrays_per_agg += 1; + if (da_strlen_avg) arrays_per_agg += 1; /* sl_null */ uint64_t cells_per_worker = (uint64_t)n_slots * ((uint64_t)arrays_per_agg * n_aggs + 1u); uint64_t max_workers = cells_per_worker @@ -13250,11 +16819,13 @@ da_path:; * budget those keep the serial scan in row order. */ da_n_workers = 1; } else if ((uint64_t)da_n_workers > max_workers) { - if (n_slots >= 2 * da_n_workers && nrows <= INT32_MAX) { + if (n_slots >= 2 * da_n_workers && nrows <= INT32_MAX && !grp_staged) { /* Partition the SLOTS instead: one pass buckets the row * ids by slot span, then one task per span drains its * buckets into the single accumulator set. Twice as - * many spans as workers evens out skewed groups. */ + * many spans as workers evens out skewed groups. Not + * for a staged context: the drain reads rows at random + * (bucketed), so it takes the ranged scan instead. */ da_part_tasks = 2 * da_n_workers; if (da_part_tasks > n_slots) da_part_tasks = n_slots; da_n_workers = 1; @@ -13325,6 +16896,11 @@ da_path:; &accums[w]._h_nn_count, total * sizeof(int64_t)); if (!accums[w].nn_count) { alloc_ok = false; break; } } + if (da_strlen_avg) { + accums[w].sl_null = (int64_t*)scratch_calloc( + &accums[w]._h_sl_null, total * sizeof(int64_t)); + if (!accums[w].sl_null) { alloc_ok = false; break; } + } if (da_has_first_last) { accums[w].first_row = (int64_t*)scratch_alloc( &accums[w]._h_first_row, n_slots * sizeof(int64_t)); @@ -13364,6 +16940,64 @@ da_path:; break; } } + /* The columns the merge and the emit read (type, SYM width and + * domain): a zero-length stand-in of the source's type for each + * staged key and input. */ + ray_t *da_kc_hdr = NULL, *da_ac_hdr = NULL; + ray_t** da_key_cols = scalar_emit_vecs(&da_kc_hdr, key_vecs, key_srcs, n_keys); + ray_t** da_agg_cols = da_key_cols ? scalar_emit_vecs(&da_ac_hdr, agg_vecs, agg_srcs, n_aggs) : NULL; + /* A staged context reads every key and input through a source + * (R-WALK): the keys, then the inputs, then the y-sides; plain + * ones are bound beside the staged ones, COUNT and fused-product + * slots read none. */ + uint32_t da_n_src = n_keys + 2u * n_aggs; + ray_col_src_t* da_srcs[da_n_src ? da_n_src : 1]; + const void* da_plain[da_n_src ? da_n_src : 1]; + ray_t* da_berr = da_agg_cols ? NULL : ray_error("oom", NULL); + if (grp_staged && !da_berr) { + for (uint32_t i = 0; i < da_n_src; i++) { da_srcs[i] = NULL; da_plain[i] = NULL; } + for (uint32_t k = 0; k < n_keys && !da_berr; k++) { + if (key_srcs[k]) { da_srcs[k] = key_srcs[k]; continue; } + da_berr = ray_col_src_bind(key_vecs[k], &key_own_src[k]); + da_srcs[k] = &key_own_src[k]; + da_plain[k] = key_data[k]; + } + for (uint32_t a = 0; a < n_aggs && !da_berr; a++) { + uint32_t i = n_keys + a; + if (!agg_prod[a].enabled && ext->agg_ops[a] != OP_COUNT && + (agg_vecs[a] || agg_srcs[a])) { + if (agg_srcs[a]) { + da_srcs[i] = agg_srcs[a]; + } else { + da_berr = ray_col_src_bind(agg_vecs[a], &agg_own_src[a]); + da_srcs[i] = &agg_own_src[a]; + } + da_plain[i] = agg_vecs[a] ? ray_data(agg_vecs[a]) : NULL; + } + if (agg_is_binary_agg(ext->agg_ops[a]) && !da_berr) { + uint32_t j = n_keys + n_aggs + a; + if (!agg_vecs2[a] && agg_srcs2[a]) { + da_srcs[j] = agg_srcs2[a]; /* staged */ + } else if (agg_ptrs2[a]) { + da_berr = ray_col_src_bind(agg_vecs2[a], &agg_own_src2[a]); + da_srcs[j] = &agg_own_src2[a]; + da_plain[j] = agg_ptrs2[a]; + } + } + } + for (uint32_t i = 0; i < da_n_src && !da_berr; i++) + if (da_srcs[i] && !da_plain[i]) ray_col_src_advise(da_srcs[i], 0, nrows); + } + if (da_berr) { + if (da_agg_cols) scalar_emit_vecs_free(da_ac_hdr, da_agg_cols, agg_vecs, n_aggs); + if (da_key_cols) scalar_emit_vecs_free(da_kc_hdr, da_key_cols, key_vecs, n_keys); + for (uint32_t w = 0; w < da_n_workers; w++) da_accum_free(&accums[w]); + scratch_free(accums_hdr); + rerr = da_berr; + goto resolve_fail; + } + ray_scan_fail_t da_fail; + ray_scan_fail_init(&da_fail); da_ctx_t da_ctx = { .accums = accums, .sym_strings = da_sym_strings, @@ -13380,7 +17014,7 @@ da_path:; .agg_ptrs2 = agg_ptrs2, .agg_types2 = agg_types2, .agg_types = agg_types, - .agg_cols = agg_vecs, + .agg_cols = da_agg_cols, .agg_strlen = agg_strlen, .agg_prod = agg_prod, .agg_ops = ext->agg_ops, @@ -13394,7 +17028,39 @@ da_path:; .match_idx = match_idx, .rowsel = rowsel, .da_n_scan = n_scan, + .row_base = 0, + .srcs = grp_staged ? da_srcs : NULL, + .plain = grp_staged ? da_plain : NULL, + .n_src = da_n_src, + .piece_attrs = NULL, + .fail = &da_fail, + .staged = grp_staged, }; + /* strlen-on-STR: resolve each column's descriptors once. */ + const ray_str_t* da_agg_str[vla_aggs]; + for (uint32_t a = 0; a < n_aggs; a++) { + da_agg_str[a] = NULL; + if (agg_strlen[a] && agg_vecs[a] && agg_vecs[a]->type == RAY_STR) { + const char* pool; (void)pool; + str_resolve(agg_vecs[a], &da_agg_str[a], &pool); + } + } + da_ctx.agg_str = da_agg_str; + da_ctx.sl_agg = -1; + if (all_sum && n_keys == 1 && !match_idx && !rowsel) { + int32_t one = -1; + bool sl_ok = true; + for (uint32_t a = 0; a < n_aggs && sl_ok; a++) { + if (agg_prod[a].enabled) sl_ok = false; + else if (agg_strlen[a] && da_agg_cols[a] && + (!grp_staged || (da_agg_cols[a]->type == RAY_SYM && + (ext->agg_ops[a] == OP_SUM || ext->agg_ops[a] == OP_AVG)))) { + if (one >= 0) sl_ok = false; else one = (int32_t)a; + } + else if (ext->agg_ops[a] != OP_COUNT) sl_ok = false; + } + if (sl_ok && one >= 0) da_ctx.sl_agg = one; + } /* Pin each SYM agg column's vocabulary once for the accumulate. */ ray_t* agg_raw_hdr = NULL; if (n_aggs > 0) { @@ -13404,9 +17070,9 @@ da_path:; da_ctx.agg_raw = (ray_sym_domain_raw_t*)rm; da_ctx.agg_raw_ok = (uint8_t*)(rm + (size_t)n_aggs * sizeof(ray_sym_domain_raw_t)); for (uint32_t a = 0; a < n_aggs; a++) - if (agg_vecs[a] && agg_vecs[a]->type == RAY_SYM) + if (da_agg_cols[a] && da_agg_cols[a]->type == RAY_SYM) da_ctx.agg_raw_ok[a] = ray_sym_domain_raw_pin( - ray_sym_vec_domain(agg_vecs[a]), &da_ctx.agg_raw[a]) ? 1 : 0; + ray_sym_vec_domain(da_agg_cols[a]), &da_ctx.agg_raw[a]) ? 1 : 0; } } @@ -13420,6 +17086,18 @@ da_path:; else da_accum_fn(&da_ctx, 0, 0, n_scan); if (agg_raw_hdr) scratch_free(agg_raw_hdr); + /* R-FAIL: a range error (or a cancelled staged dispatch) is the + * answer; the partial accumulators are discarded. */ + ray_t* da_err = grp_staged + ? ray_scan_fail_finish(&da_fail, da_n_workers > 1 ? da_pool : NULL) : NULL; + if (da_err) { + for (uint32_t w = 0; w < da_n_workers; w++) da_accum_free(&accums[w]); + scratch_free(accums_hdr); + scalar_emit_vecs_free(da_ac_hdr, da_agg_cols, agg_vecs, n_aggs); + scalar_emit_vecs_free(da_kc_hdr, da_key_cols, key_vecs, n_keys); + rerr = da_err; + goto resolve_fail; + } /* Merge target is always accums[0] */ da_accum_t* merged = &accums[0]; @@ -13499,7 +17177,7 @@ da_path:; * INT64_MAX is the "no value seen" seed. */ if (wa->min_val[i].i != INT64_MAX && (merged->min_val[i].i == INT64_MAX || - sym_lex_lt(ray_sym_vec_domain(agg_vecs[a]), + sym_lex_lt(ray_sym_vec_domain(da_agg_cols[a]), wa->min_val[i].i, merged->min_val[i].i))) merged->min_val[i].i = wa->min_val[i].i; } else { @@ -13519,7 +17197,7 @@ da_path:; * INT64_MIN is the "no value seen" seed. */ if (wa->max_val[i].i != INT64_MIN && (merged->max_val[i].i == INT64_MIN || - sym_lex_gt(ray_sym_vec_domain(agg_vecs[a]), + sym_lex_gt(ray_sym_vec_domain(da_agg_cols[a]), wa->max_val[i].i, merged->max_val[i].i))) merged->max_val[i].i = wa->max_val[i].i; } else { @@ -13532,6 +17210,10 @@ da_path:; for (size_t i = 0; i < total; i++) merged->nn_count[i] += wa->nn_count[i]; } + if (merged->sl_null && wa->sl_null) { + for (size_t i = 0; i < total; i++) + merged->sl_null[i] += wa->sl_null[i]; + } for (uint32_t s = 0; s < n_slots; s++) merged->count[s] += wa->count[s]; } @@ -13544,7 +17226,7 @@ da_path:; .n_aggs = n_aggs, .agg_types = agg_types, .agg_ops = ext->agg_ops, - .agg_cols = agg_vecs, + .agg_cols = da_agg_cols, }; ray_pool_dispatch(da_pool, da_merge_fn, &merge_ctx, (int64_t)n_slots); } else { @@ -13608,7 +17290,7 @@ da_path:; * INT64_MAX is the "no value seen" seed. */ if (wa->min_val[i].i != INT64_MAX && (merged->min_val[i].i == INT64_MAX || - sym_lex_lt(ray_sym_vec_domain(agg_vecs[a]), + sym_lex_lt(ray_sym_vec_domain(da_agg_cols[a]), wa->min_val[i].i, merged->min_val[i].i))) merged->min_val[i].i = wa->min_val[i].i; } else { @@ -13628,7 +17310,7 @@ da_path:; * INT64_MIN is the "no value seen" seed. */ if (wa->max_val[i].i != INT64_MIN && (merged->max_val[i].i == INT64_MIN || - sym_lex_gt(ray_sym_vec_domain(agg_vecs[a]), + sym_lex_gt(ray_sym_vec_domain(da_agg_cols[a]), wa->max_val[i].i, merged->max_val[i].i))) merged->max_val[i].i = wa->max_val[i].i; } else { @@ -13641,6 +17323,10 @@ da_path:; for (size_t i = 0; i < total; i++) merged->nn_count[i] += wa->nn_count[i]; } + if (merged->sl_null && wa->sl_null) { + for (size_t i = 0; i < total; i++) + merged->sl_null[i] += wa->sl_null[i]; + } for (uint32_t s = 0; s < n_slots; s++) merged->count[s] += wa->count[s]; } @@ -13678,17 +17364,20 @@ da_path:; ray_t* result = ray_table_new(total_cols); if (!result || RAY_IS_ERR(result)) { da_accum_free(&accums[0]); scratch_free(accums_hdr); + scalar_emit_vecs_free(da_ac_hdr, da_agg_cols, agg_vecs, n_aggs); + scalar_emit_vecs_free(da_kc_hdr, da_key_cols, key_vecs, n_keys); for (uint32_t a = 0; a < n_aggs; a++) { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result ? result : ray_error("oom", NULL); } /* Key columns — decompose composite slot back to per-key values */ for (uint32_t k = 0; k < n_keys; k++) { - ray_t* src_col = key_vecs[k]; + ray_t* src_col = da_key_cols[k]; /* the column or its stand-in */ if (!src_col) continue; ray_t* key_col = col_vec_new(src_col, (int64_t)grp_count); out_col_adopt_str_pool(key_col, src_col); @@ -13730,7 +17419,8 @@ da_path:; int64_t* dense_counts = grp_count ? (int64_t*)scratch_alloc(&_h_dcnt, grp_count * sizeof(int64_t)) : NULL; - int64_t* dense_nn_counts = (da_nn_count && grp_count) + int64_t* da_sl_null = merged->sl_null; /* NULL without an AVG(strlen) */ + int64_t* dense_nn_counts = ((da_nn_count || da_sl_null) && grp_count) ? (int64_t*)scratch_alloc(&_h_dnn, dense_total * sizeof(int64_t)) : NULL; @@ -13749,12 +17439,18 @@ da_path:; if (dense_sum_y) dense_sum_y[di] = da_sum_y[si]; if (dense_sumsq_y) dense_sumsq_y[di] = da_sumsq_y[si]; if (dense_sumxy) dense_sumxy[di] = da_sumxy[si]; - if (dense_nn_counts) dense_nn_counts[di] = da_nn_count[si]; + if (dense_nn_counts) { + /* An AVG(strlen) divides by its non-empty rows. */ + int64_t nnv = da_nn_count ? da_nn_count[si] : da_count[s]; + if (da_sl_null && agg_strlen[a] && ext->agg_ops[a] == OP_AVG) + nnv -= da_sl_null[si]; + dense_nn_counts[di] = nnv; + } } gi++; } - emit_agg_columns(&result, g, ext, agg_vecs, grp_count, n_aggs, + emit_agg_columns(&result, g, ext, da_agg_cols, grp_count, n_aggs, (double*)dense_sum, (int64_t*)dense_sum, dense_sum_hi, (double*)dense_min_val, (double*)dense_max_val, (int64_t*)dense_min_val, (int64_t*)dense_max_val, @@ -13769,20 +17465,26 @@ da_path:; scratch_free(_h_dshi); da_accum_free(&accums[0]); scratch_free(accums_hdr); + scalar_emit_vecs_free(da_ac_hdr, da_agg_cols, agg_vecs, n_aggs); + scalar_emit_vecs_free(da_kc_hdr, da_key_cols, key_vecs, n_keys); for (uint32_t a = 0; a < n_aggs; a++) { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result; } } + /* Staged columns stay staged for the sparse-dynamic count, the + * single-key sparse paths (sp_walk_run) and the fat-entry routes at + * ht_path. */ { /* n_aggs <= 64: same mask-width bound as da_eligible above — this * path's independent agg_f64_mask is also a uint64_t. Beyond 64 * aggs, fall through to the hash path. */ - bool sp_eligible = (nrows > 0 && n_keys == 1 && key_data[0] != NULL && + bool sp_eligible = (nrows > 0 && n_keys == 1 && (key_data[0] != NULL || key_srcs[0]) && n_aggs <= 64); int8_t kt = sp_eligible ? key_types[0] : 0; if (sp_eligible && kt != RAY_I64 && kt != RAY_I32 && kt != RAY_I16 && @@ -13794,6 +17496,8 @@ da_path:; ? key_vecs[0]->slice_parent : key_vecs[0]; if (kt != RAY_SYM && ray_vec_may_have_nulls(src)) sp_eligible = false; + } else if (sp_eligible && kt != RAY_SYM && key_srcs[0]->may_null) { + sp_eligible = false; /* staged: the directory's null counts */ } bool sp_need_sum = false; /* An integer AVG divides the exact 128-bit sum: the scatter arrays @@ -13811,13 +17515,16 @@ da_path:; * NULL_F64 sentinels. Fall back to slower paths that * mask nulls properly. (The multi-key radix HT at * accum_from_entry inherits the same nullable-agg gap.) */ + ray_col_src_t* ssrc = (!agg_vecs[a] && agg_srcs[a]) ? agg_srcs[a] : NULL; + int8_t at = agg_vecs[a] ? agg_vecs[a]->type : ssrc ? ssrc->type : 0; if (agg_vecs[a] && ray_vec_may_have_nulls(agg_vecs[a])) sp_eligible = false; + else if (ssrc && (ssrc->may_null || at == RAY_SYM || at == RAY_STR)) + sp_eligible = false; /* staged: as ray_vec_may_have_nulls */ else { sp_need_sum = true; - if (op == OP_AVG && !(agg_vecs[a] && group_fp_type(agg_vecs[a]->type)) && - !agg_strlen[a] && - group_avg_needs_hi(agg_vecs[a] ? agg_vecs[a]->type : 0, nrows)) + if (op == OP_AVG && !group_fp_type(at) && !agg_strlen[a] && + group_avg_needs_hi(at, nrows)) sp_need_sum128 = true; } } @@ -13836,12 +17543,14 @@ da_path:; * not a VLA bound. */ void* agg_ptrs[vla_aggs]; int8_t agg_types[vla_aggs]; + ray_col_src_t* sp_agg_src[vla_aggs]; /* staged inputs' sources */ uint64_t agg_f64_mask = 0; for (uint32_t a = 0; a < n_aggs; a++) { - if (agg_vecs[a]) { - agg_ptrs[a] = ray_data(agg_vecs[a]); - agg_types[a] = agg_vecs[a]->type; - if (group_fp_type(agg_vecs[a]->type)) + sp_agg_src[a] = (!agg_vecs[a] && agg_srcs[a]) ? agg_srcs[a] : NULL; + if (agg_vecs[a] || sp_agg_src[a]) { + agg_ptrs[a] = agg_vecs[a] ? ray_data(agg_vecs[a]) : NULL; /* NULL: staged */ + agg_types[a] = agg_vecs[a] ? agg_vecs[a]->type : sp_agg_src[a]->type; + if (group_fp_type(agg_types[a])) agg_f64_mask |= ((uint64_t)1 << a); } else { agg_ptrs[a] = NULL; @@ -13888,12 +17597,25 @@ da_path:; (emit_filter.min_count_exclusive > 0 || emit_filter.top_count_take > 0) && n_scan <= UINT32_MAX) { + /* Staged columns: stand-ins carry the type, SYM width and + * domain the emit reads. */ + ray_t *sp_kc_hdr = NULL, *sp_ac_hdr = NULL; + ray_t** sp_key_cols = scalar_emit_vecs(&sp_kc_hdr, key_vecs, key_srcs, n_keys); + ray_t** sp_agg_cols = sp_key_cols ? scalar_emit_vecs(&sp_ac_hdr, agg_vecs, agg_srcs, n_aggs) : NULL; + if (!sp_agg_cols) { + if (sp_key_cols) scalar_emit_vecs_free(sp_kc_hdr, sp_key_cols, key_vecs, n_keys); + rerr = ray_error("oom", NULL); + goto resolve_fail; + } + for (uint32_t a = 0; a < n_aggs; a++) + if (sp_agg_src[a]) ray_col_src_advise(sp_agg_src[a], 0, nrows); + if (key_srcs[0]) ray_col_src_advise(key_srcs[0], 0, nrows); sp_dyn_ctx_t sc = { .g = g, .ext = ext, .key_data = key_data, - .key_types = key_types, .key_vecs = key_vecs, + .key_types = key_types, .key_vecs = sp_key_cols, .key_owned = key_owned, .agg_ptrs = agg_ptrs, .agg_types = agg_types, .agg_strlen = agg_strlen, - .agg_vecs = agg_vecs, .agg_owned = agg_owned, + .agg_vecs = sp_agg_cols, .agg_owned = agg_owned, .agg_affine = agg_affine, .agg_prod = agg_prod, .strlen_sym_strings = strlen_sym_strings, .strlen_sym_count = strlen_sym_count, @@ -13902,10 +17624,54 @@ da_path:; .sp_need_sum = sp_need_sum, .sp_need_sum128 = sp_need_sum128, .match_idx = match_idx, .rowsel = rowsel, .match_idx_block = match_idx_block, - .vla_hdr = vla_hdr, .emit_filter = emit_filter, + /* freed here, after the inputs' own sources it holds */ + .vla_hdr = NULL, .emit_filter = emit_filter, + .staged = grp_staged, .key_src = key_srcs[0], .agg_src = sp_agg_src, }; ray_t* sp_r = exec_group_sp_dyn_emit(&sc); - if (sp_r) return sp_r; + scalar_emit_vecs_free(sp_ac_hdr, sp_agg_cols, agg_vecs, n_aggs); + scalar_emit_vecs_free(sp_kc_hdr, sp_key_cols, key_vecs, n_keys); + if (sp_r) { + /* the route released the keys and inputs it owned */ + AGG_OWN_SRC_RELEASE(); + scratch_free(vla_hdr); + return sp_r; + } + } + /* A staged context stays staged: the passes below read its key + * and inputs by pieces (sp_walk_run, R-WALK; COUNT inputs are + * not read), a plain one in place. Each staged column gets a + * zero-length stand-in (type, SYM width and domain) for the + * emit, owned like a materialization; ht_path drops them again, + * its builders reading the sources themselves. */ + ray_col_src_t* spw_srcs[1 + 64]; + sp_walk_ctx_t spw; + memset(&spw, 0, sizeof spw); + if (grp_staged) { + spw_srcs[0] = key_vecs[0] ? NULL : key_srcs[0]; + for (uint32_t a = 0; a < n_aggs; a++) + spw_srcs[1 + a] = ext->agg_ops[a] == OP_COUNT ? NULL : sp_agg_src[a]; + if (!key_vecs[0]) { + ray_t* sv = group_src_standin(key_srcs[0]); + if (!sv) { rerr = ray_error("oom", NULL); goto resolve_fail; } + key_vecs[0] = sv; key_owned[0] = 1; sp_sv_key = true; + } + for (uint32_t a = 0; a < n_aggs; a++) { + if (agg_vecs[a] || !agg_srcs[a]) continue; + ray_t* sv = group_src_standin(agg_srcs[a]); + if (!sv) { rerr = ray_error("oom", NULL); goto resolve_fail; } + agg_vecs[a] = sv; agg_owned[a] = 1; sp_sv_agg |= (uint64_t)1 << a; + } + for (uint32_t i = 0; i < 1 + n_aggs; i++) + if (spw_srcs[i]) ray_col_src_advise(spw_srcs[i], 0, nrows); + spw = (sp_walk_ctx_t){ + .ext = ext, .n_aggs = n_aggs, .key_type = key_types[0], + .key_plain = key_data[0], .key_esz = key_esz, + .agg_ptrs = agg_ptrs, .agg_types = agg_types, .agg_strlen = agg_strlen, + .agg_vecs = agg_vecs, .strlen_sym_strings = strlen_sym_strings, + .strlen_sym_count = strlen_sym_count, .agg_f64_mask = agg_f64_mask, + .srcs = spw_srcs, .rowsel = rowsel, .need_sum = sp_need_sum, + }; } if (use_emit_filter && @@ -13914,6 +17680,11 @@ da_path:; key_types[0] != RAY_SYM && n_scan <= UINT32_MAX) { bool have_key = false; int64_t min_key = 0, max_key = 0; + if (grp_staged) { /* directory bounds where exact, else by range */ + ray_t* werr = sp_walk_key_range(&spw, n_scan); + if (werr) { rerr = werr; goto resolve_fail; } + have_key = spw.have_key; min_key = spw.min_key; max_key = spw.max_key; + } else for (int64_t i = 0; i < n_scan; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && rowsel && !group_rowsel_pass(rowsel, r)) @@ -13960,6 +17731,16 @@ da_path:; } } + if (grp_staged) { + spw.min_key = min_key; spw.range_count = range_count; + spw.sums = range_sum; spw.sums_hi = range_sum_hi; + ray_t* werr = sp_walk_run(&spw, SPW_RANGE, 0, n_scan); + if (werr) { + scratch_free(range_sum_hdr); scratch_free(range_hi_hdr); + scratch_free(cnt_hdr); + rerr = werr; goto resolve_fail; + } + } else for (int64_t i = 0; i < n_scan; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && rowsel && !group_rowsel_pass(rowsel, r)) @@ -14014,6 +17795,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result ? result : ray_error("oom", NULL); } @@ -14031,6 +17813,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return key_col ? key_col : ray_error("oom", NULL); } @@ -14056,6 +17839,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("oom", NULL); } @@ -14084,7 +17868,18 @@ da_path:; gi++; } - if (sp_need_sum && !range_sum) { + if (sp_need_sum && !range_sum && grp_staged) { + spw.min_key = min_key; spw.range_count = range_count; + spw.sums = dense_sum; spw.sums_hi = dense_sum_hi; + ray_t* werr = sp_walk_run(&spw, SPW_MARKER, 0, n_scan); + if (werr) { + scratch_free(_h_sum); scratch_free(_h_sum_hi); scratch_free(_h_cnt); + scratch_free(range_sum_hdr); scratch_free(range_hi_hdr); + scratch_free(cnt_hdr); + ray_release(key_col); ray_release(result); + rerr = werr; goto resolve_fail; + } + } else if (sp_need_sum && !range_sum) { for (int64_t i = 0; i < n_scan; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && rowsel && !group_rowsel_pass(rowsel, r)) @@ -14139,6 +17934,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result; } @@ -14158,6 +17954,12 @@ da_path:; if (!sparse_i64_init(&sp_ht, (uint32_t)expected, n_aggs, false, false)) goto ht_path; + if (grp_staged) { + spw.ht = &sp_ht; + ray_t* werr = sp_walk_run(&spw, SPW_HT_COUNT, 0, n_scan); + if (werr) { sparse_i64_free(&sp_ht); rerr = werr; goto resolve_fail; } + if (spw.stop) sp_ok = false; + } else for (int64_t i = 0; i < n_scan; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && rowsel && !group_rowsel_pass(rowsel, r)) @@ -14178,6 +17980,12 @@ da_path:; sp_need_sum128)) goto ht_path; + if (grp_staged) { + spw.ht = &sp_ht; + ray_t* werr = sp_walk_run(&spw, SPW_HT_SUM, 0, n_scan); + if (werr) { sparse_i64_free(&sp_ht); rerr = werr; goto resolve_fail; } + if (spw.stop) sp_ok = false; + } else for (int64_t i = 0; i < n_scan; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && rowsel && !group_rowsel_pass(rowsel, r)) @@ -14240,6 +18048,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result ? result : ray_error("oom", NULL); } @@ -14256,6 +18065,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return key_col ? key_col : ray_error("oom", NULL); } @@ -14281,6 +18091,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("oom", NULL); } @@ -14301,6 +18112,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("oom", NULL); } @@ -14324,6 +18136,7 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("oom", NULL); } @@ -14341,7 +18154,17 @@ da_path:; } sparse_i64_free(&sp_ht); - if (use_emit_filter && sp_need_sum) { + if (use_emit_filter && sp_need_sum && grp_staged) { + spw.ht = &heavy_ht; + spw.sums = dense_sum; spw.sums_hi = dense_sum_hi; + ray_t* werr = sp_walk_run(&spw, SPW_HEAVY, 0, n_scan); + if (werr) { + scratch_free(_h_sum); scratch_free(_h_sum_hi); scratch_free(_h_cnt); + ray_release(key_col); ray_release(result); + sparse_i64_free(&heavy_ht); + rerr = werr; goto resolve_fail; + } + } else if (use_emit_filter && sp_need_sum) { for (int64_t i = 0; i < n_scan; i++) { int64_t r = match_idx ? match_idx[i] : i; if (!match_idx && rowsel && !group_rowsel_pass(rowsel, r)) @@ -14395,12 +18218,88 @@ da_path:; if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return result; } } ht_path:; + /* The single-key sparse paths fell back: their stand-ins go, the + * builders below read the staged sources. */ + if (sp_sv_key) { ray_release(key_vecs[0]); key_vecs[0] = NULL; key_owned[0] = 0; } + for (uint32_t a = 0; a < n_aggs && sp_sv_agg; a++) + if (sp_sv_agg & ((uint64_t)1 << a)) { ray_release(agg_vecs[a]); agg_vecs[a] = NULL; agg_owned[a] = 0; } + /* The fat-entry routes below (radix phase 1, its v2 sibling, the + * holistic reprobe, the serial fallback) read staged keys and inputs by + * range (R-WALK; R-SPARSE over the v2 survivor list). Random-access + * readers take their plain columns here (R-RANDOM): every key of a + * group-by with a wide key (STR, GUID, LIST), because equality compares + * every key at stored rows, and exactly the inputs of the holistic + * aggregates, whose per-group buffers gather stored rows. A + * generation-2 STR scan key reaches here only when exec_group's + * string-domain swap declined it (strdom_key_ok). */ + bool ht_wide = false; + for (uint32_t k = 0; k < n_keys; k++) + if (key_types[k] == RAY_STR || key_types[k] == RAY_GUID || key_types[k] == RAY_LIST) + ht_wide = true; + if (grp_staged) { + for (uint32_t k = 0; k < n_keys && ht_wide; k++) { + if (key_vecs[k] || !key_srcs[k]) continue; + ray_t* pv = NULL; + ray_t* uerr = ray_col_src_plain(key_srcs[k], &pv); /* random: wide key */ + if (!uerr) uerr = group_own_plain(pv, &key_vecs[k], &key_owned[k]); + if (uerr) { rerr = uerr; goto resolve_fail; } + key_srcs[k] = NULL; + key_data[k] = ray_data(key_vecs[k]); + key_types[k] = key_vecs[k]->type; + key_attrs[k] = key_vecs[k]->attrs; + } + for (uint32_t a = 0; a < n_aggs; a++) { + if (agg_vecs[a] || !agg_srcs[a]) continue; + uint16_t op = ext->agg_ops[a]; + if (op != OP_MEDIAN && op != OP_QUANTILE && op != OP_MODE && op != OP_TOP_N && + op != OP_BOT_N && !agg_needs_row_gather(agg_srcs[a]->type, op)) + continue; + ray_t* pv = NULL; + ray_t* uerr = ray_col_src_plain(agg_srcs[a], &pv); /* random: holistic aggregate */ + if (!uerr) uerr = group_own_plain(pv, &agg_vecs[a], &agg_owned[a]); + if (uerr) { rerr = uerr; goto resolve_fail; } + } + grp_staged = false; + for (uint32_t k = 0; k < n_keys; k++) if (key_srcs[k] && !key_vecs[k]) grp_staged = true; + for (uint32_t a = 0; a < n_aggs; a++) + if ((!agg_vecs[a] && agg_srcs[a]) || (!agg_vecs2[a] && agg_srcs2[a])) grp_staged = true; + } + /* A staged context: each staged column gets a zero-length stand-in + * (type, SYM width and domain, HAS_NULLS when the source may hold + * nulls), owned like a materialized one, so the layout, the + * nullability gates and the emits below read it as the column; the + * builders read the source (ht_srcs, keys then inputs then y-sides). */ + uint32_t ht_n_src = n_keys + 2u * n_aggs; + ray_t* ht_rr_hdr = NULL; + ray_col_src_t** ht_srcs = NULL; + const void** ht_plain = NULL; + if (grp_staged) { + char* blk = (char*)scratch_calloc(&ht_rr_hdr, (size_t)ht_n_src * 2 * sizeof(void*)); + if (!blk) { rerr = ray_error("oom", NULL); goto resolve_fail; } + ht_srcs = (ray_col_src_t**)(void*)blk; + ht_plain = (const void**)(void*)(blk + (size_t)ht_n_src * sizeof(void*)); + for (uint32_t i = 0; i < ht_n_src; i++) { + uint32_t k = i, a = i - n_keys, y = i - n_keys - n_aggs; + ray_col_src_t* src = i < n_keys ? (key_vecs[k] ? NULL : key_srcs[k]) + : i < n_keys + n_aggs ? (agg_vecs[a] ? NULL : agg_srcs[a]) + : (agg_vecs2[y] ? NULL : agg_srcs2[y]); + if (!src) continue; + ray_t* sv = group_src_standin(src); + if (!sv) { scratch_free(ht_rr_hdr); rerr = ray_error("oom", NULL); goto resolve_fail; } + if (src->may_null) sv->attrs |= RAY_ATTR_HAS_NULLS; + ht_srcs[i] = src; /* staged: ht_plain[i] stays NULL */ + if (i < n_keys) { key_vecs[k] = sv; key_owned[k] = 1; } + else if (i < n_keys + n_aggs) { agg_vecs[a] = sv; agg_owned[a] = 1; } + else { agg_vecs2[y] = sv; agg_owned2[y] = 1; } + } + } /* n_aggs > 8 guard RETIRED (unbounded-slots cut 4): the HT row-layout is * now layout-sized end to end (ght_layout_t agg metadata is unbounded, the * entry-staging buffers spill past 8), so this fallback — reached by the @@ -14416,6 +18315,8 @@ ht_path:; if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); + scratch_free(ht_rr_hdr); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("oom", NULL); } @@ -14458,10 +18359,13 @@ ht_path:; if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); + scratch_free(ht_rr_hdr); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); return ray_error("limit", "group: layout stride/slot budget exceeded (or OOM)"); } + /* Sequential fallback grows strictly from observed groups. */ uint32_t ht_cap = 2; @@ -14500,6 +18404,58 @@ ht_path:; ray_t* topn_fuse_cnt_hdr = NULL; topn_fuse_t topn_fuse = {0}; + /* The builders' range reads: the staged sources beside plain ones + * bound for the walk (a key or input without a graph source is bound + * into the route's own source), read in place. Only the inputs that + * own a value slot are read: COUNT and holistic inputs are not. */ + grp_rr_t ht_rr = { .n_keys = n_keys, .n_aggs = n_aggs, .key_types = key_types }; + ray_scan_fail_t ht_fail; + ray_scan_fail_init(&ht_fail); + if (grp_staged) { + ray_t* berr = NULL; + for (uint32_t k = 0; k < n_keys && !berr; k++) { + if (ht_wide) { ht_srcs[k] = NULL; continue; } /* plain, read whole */ + if (ht_srcs[k]) continue; /* staged */ + if (key_own_src[k].obj) ray_col_src_release(&key_own_src[k]); + berr = ray_col_src_bind(key_vecs[k], &key_own_src[k]); + ht_srcs[k] = &key_own_src[k]; + ht_plain[k] = key_data[k]; + } + for (uint32_t a = 0; a < n_aggs && !berr; a++) { + uint32_t i = n_keys + a, j = n_keys + n_aggs + a; + bool slot = ght_layout.agg_val_slot[a] >= 0; + if (!slot) ht_srcs[i] = NULL; + else if (!ht_srcs[i] && agg_vecs[a]) { + if (agg_srcs[a]) ht_srcs[i] = agg_srcs[a]; + else { + if (agg_own_src[a].obj) ray_col_src_release(&agg_own_src[a]); + berr = ray_col_src_bind(agg_vecs[a], &agg_own_src[a]); + ht_srcs[i] = &agg_own_src[a]; + } + ht_plain[i] = ray_data(agg_vecs[a]); + } + if (!slot || !(ght_layout.agg_flags[a] & GHT_AF_BINARY)) ht_srcs[j] = NULL; + else if (!ht_srcs[j] && agg_vecs2[a] && !berr) { + if (agg_own_src2[a].obj) ray_col_src_release(&agg_own_src2[a]); + berr = ray_col_src_bind(agg_vecs2[a], &agg_own_src2[a]); + ht_srcs[j] = &agg_own_src2[a]; + ht_plain[j] = ray_data(agg_vecs2[a]); + } + } + if (berr) { result = berr; goto cleanup; } + for (uint32_t i = 0; i < ht_n_src; i++) + if (ht_srcs[i] && !ht_plain[i]) ray_col_src_advise(ht_srcs[i], 0, nrows); + ht_rr.srcs = ht_srcs; + ht_rr.plain = ht_plain; + ht_rr.n_src = ht_n_src; + ht_rr.fail = &ht_fail; + ht_rr.staged = true; + ht_rr.keys_walked = !ht_wide; + /* The builders walk rows (or the v2 survivor list), never match_idx: + * a staged context has none (unstaged at da_path). */ + assert(!match_idx); + } + /* ---- top-N ordering-agg resolution, hoisted above the parallel section. * Phase 2 now runs each partition's top-k itself, while the partition is * cache-hot (topn_fuse_partition), so the in-row offset of the ordering @@ -14512,6 +18468,9 @@ ht_path:; * whole compaction is skipped, exactly as the in-place `goto * topn_compact_skip` did before. */ uint16_t topn_order_off = 0; /* default: COUNT at row + 0 */ + uint16_t topn_nn_off = 0; /* non-null count of a nullable MIN/MAX */ + int64_t topn_bias = 0; /* affine SUM constant (#813) */ + uint16_t topn_bias_off = 0; /* ...times this count: row + 0 or nn (#814) */ uint8_t topn_desc_dir = 0; bool topn_order_ok = false; if (use_topn_filter) { @@ -14529,6 +18488,21 @@ ht_path:; if (agg_slot < 0 || order_is_f64) topn_order_ok = false; else topn_order_off = (uint16_t)(ght_layout.off_sum + (uint16_t)agg_slot * 8u); + /* `(sum (+ x c))` aggregates x; phase 3 adds c once per + * non-null x (topn_bias_off below). An + * integer slot's affine constant is always an integer (a FLOAT + * one declines the rewrite off the scalar route, + * try_affine_sumavg_input), so the heap folds bias_i64 in + * exactly as the emit does. */ + if (agg_affine[ai].enabled) { + topn_bias = agg_affine[ai].bias_i64; + /* c is added once per non-null x: a nullable layout keeps + * the slot's non-null count, a null-free one has only the + * row count, which then equals it (#814) */ + if (ght_layout.off_nn) + topn_bias_off = (uint16_t)(ght_layout.off_nn + + (uint16_t)agg_slot * 8u); + } } else if (order_op == OP_MIN) { if (agg_slot < 0 || order_is_f64 || (ght_layout.agg_flags[ai] & GHT_AF_SYM)) topn_order_ok = false; @@ -14540,6 +18514,13 @@ ht_path:; else topn_order_off = (uint16_t)(ght_layout.off_max + (uint16_t)agg_slot * 8u); } + /* MIN and MAX of an all-null group are null (phase 3 emits them so + * when the slot's non-null count is 0); SUM is 0 and COUNT never + * null, and their slots already hold that value. off_nn is set + * only for a layout with a nullable agg (see topn_group_push). */ + if (topn_order_ok && (order_op == OP_MIN || order_op == OP_MAX) && + ght_layout.off_nn && agg_slot >= 0) + topn_nn_off = (uint16_t)(ght_layout.off_nn + (uint16_t)agg_slot * 8u); /* `.desc` is authoritative for every agg kind, COUNT included: every * arming site in query.c sets it (1 for desc:, 0 for asc:). It used * to be force-set to 1 for COUNT — that silently turned @@ -14555,8 +18536,8 @@ ht_path:; * and admits it only as a real reduction (<= an eighth of the groups). * Fusion has to commit before any group exists, so the same test is made * against the row count that bounds them: groups <= scattered rows, so - * n_parts * k_take <= radix_rows / 8 keeps the stash under 2 bytes per - * scattered row — against the >= 16 bytes per row phase 1's fat entries + * n_parts * k_take <= radix_rows / 8 keeps the stash (24-byte items) at + * most 3 bytes per scattered row — against the >= 16 bytes per row phase 1's fat entries * (or the v2 worker HTs) already hold, peak memory cannot move. Failing * that test, or a single worker/partition, or allocation failure, leaves * .items NULL and the unchanged post-phase-2 scan runs. */ @@ -14582,6 +18563,9 @@ ht_path:; topn_fuse.item_cnt = fcnt; topn_fuse.cap = (uint32_t)kt; topn_fuse.order_off = topn_order_off; + topn_fuse.nn_off = topn_nn_off; + topn_fuse.bias = topn_bias; + topn_fuse.bias_off = topn_bias_off; topn_fuse.desc_dir = topn_desc_dir; } else if (fcnt) { scratch_free(topn_fuse_cnt_hdr); @@ -14726,14 +18710,27 @@ ht_path:; .ht_init_block = v2_cap > 2 ? v2_cap / 2 : 1, .ht_grow_cap = v2_grow, .oom = 0, + .rr = ht_rr, }; /* By-value embed the layout, fixing its base pointers to v2p1's * own inline arrays (inline) / shared spill (wide); the master * ght_layout outlives this dispatch. */ ght_layout_copy(&v2p1.layout, &ght_layout); + ray_scan_fail_init(&ht_fail); ray_pool_dispatch(pool, radix_v2_phase1_fn, &v2p1, sel_match ? sel_n : n_scan); if (sel_match_block) ray_release(sel_match_block); + /* R-FAIL: a range error (or a cancelled staged dispatch) is the + * answer; the worker HTs are discarded. */ + ray_t* v2_ferr = ht_rr.staged ? ray_scan_fail_finish(&ht_fail, pool) : NULL; + if (v2_ferr) { + for (size_t i = 0; i < v2_n_w; i++) + group_ht_free(&wpart_hts[i]); + scratch_free(wpart_hdr); + scratch_free(v2_part_hdr); + result = v2_ferr; + goto cleanup; + } CHECK_CANCEL_GOTO(pool, cleanup); if (atomic_load_explicit(&v2p1.oom, memory_order_relaxed)) { for (size_t i = 0; i < v2_n_w; i++) @@ -14823,6 +18820,7 @@ v2_done:; .match_idx = match_idx, .buf_prime = (uint32_t)((uint64_t)(n_scan > 0 ? n_scan : 1) / ((uint64_t)n_total * radix_n_parts) * 5 / 4 + 8), + .rr = ht_rr, }; ght_layout_copy(&p1ctx.layout, &ght_layout); /* Wide-key str-pool table (n_keys slots): carve once (never per row); @@ -14834,8 +18832,14 @@ v2_done:; if (!p1ctx.key_pool) { result = ray_error("oom", NULL); goto cleanup; } derive_key_pool(&ght_layout, key_vecs, p1ctx.key_pool); } + ray_scan_fail_init(&ht_fail); ray_pool_dispatch(pool, radix_phase1_fn, &p1ctx, n_scan); scratch_free(p1_kp_hdr); + if (ht_rr.staged) { + /* R-FAIL: the scattered entries are discarded at cleanup */ + ray_t* p1_ferr = ray_scan_fail_finish(&ht_fail, pool); + if (p1_ferr) { result = p1_ferr; goto cleanup; } + } CHECK_CANCEL_GOTO(pool, cleanup); /* Check for OOM during phase 1 radix buffer growth */ @@ -14909,11 +18913,13 @@ v2_emit:; * total_grps is in the millions but N is much smaller. * * Implementation notes: - * - The bounded heap orders by count (the agg at COUNT slot, the - * first int64 in each row). Equal counts are stable: the - * first row seen wins. Final per-partition row order is - * preserved so apply_sort_take below can do the final - * arrange-by-agg deterministically. + * - The bounded heap orders by the ordering agg's int64 row slot + * (topn_order_off) in the take's direction, and equal values + * by the group's earliest source row, smaller first: of the + * groups tied at the cut it keeps the ones the stable sort + * would take (TOPN_ITEM_BETTER). Final per-partition row + * order is preserved so apply_sort_take below can do the + * final arrange-by-agg deterministically. * - We also handle the "fewer total rows than N" case — compact * becomes a no-op. * - Only fires when emit_filter.top_count_take > 0; existing @@ -14953,7 +18959,8 @@ v2_emit:; * topn_fuse, at a uniform k_take stride per partition. * 2. the standalone topn_scan_fn pre-pass, admitted when the * staging array is a real REDUCTION — at most an eighth of - * the groups, i.e. under 2 bytes per group against the + * the groups, i.e. at most 3 bytes per group (24-byte + * items) against the * >= 24-byte group rows already resident, so peak memory * cannot move. (Fusion could not make this test: it must * commit before any group exists, so it makes the @@ -14962,8 +18969,8 @@ v2_emit:; * allocation failure, or a staging array that would not * reduce. * - * All three feed the same heap in the same (partition asc, - * gid asc) order, so they retain the same set. */ + * All three feed the same heap, whose order is total, so they + * retain the same set. */ ray_t* stage_hdr = NULL; ray_t* item_hdr = NULL; const uint32_t* item_off = NULL; /* NULL => uniform stride */ @@ -15024,7 +19031,10 @@ v2_emit:; topn_scan_ctx_t sctx = { .part_hts = part_hts, .items = items_w, .item_off = off_w, .item_cnt = cnt_w, - .order_off = order_off, .desc_dir = desc_dir, + .order_off = order_off, + .nn_off = topn_nn_off, .bias = topn_bias, + .bias_off = topn_bias_off, + .desc_dir = desc_dir, }; ray_pool_dispatch_n(pool, topn_scan_fn, &sctx, radix_n_parts); @@ -15047,10 +19057,7 @@ v2_emit:; } } - /* Merge the per-partition survivors: partitions ascending, - * gid ascending within one — the serial scan's push order, - * which is what makes the retained set identical (condition - * (2) of the topn_heap_push proof). `item_off` is the + /* Merge the per-partition survivors. `item_off` is the * standalone pre-pass's packed layout; the fused stash uses a * uniform k_take stride instead. */ if (scanned) @@ -15061,23 +19068,21 @@ v2_emit:; uint32_t n = item_cnt[p]; for (uint32_t i = 0; i < n; i++) hn = topn_heap_push(heap, hn, k_take, desc_dir, - h[i].value, h[i].part, - h[i].gid); + h[i].value, h[i].first, + h[i].part, h[i].gid); } scratch_free(item_hdr); scratch_free(stage_hdr); if (!scanned) for (uint32_t p = 0; p < radix_n_parts; p++) { - group_ht_t* ph = &part_hts[p]; - uint16_t rs = ph->layout.row_stride; + const group_ht_t* ph = &part_hts[p]; uint32_t gc = ph->grp_count; - for (uint32_t gi = 0; gi < gc; gi++) { - int64_t v = *(const int64_t*)(const void*) - (ph->rows + (size_t)gi * rs + order_off); - hn = topn_heap_push(heap, hn, k_take, desc_dir, - v, p, gi); - } + for (uint32_t gi = 0; gi < gc; gi++) + hn = topn_group_push(heap, hn, k_take, desc_dir, + ph, order_off, topn_nn_off, + topn_bias, topn_bias_off, + p, gi); } if (hn > 0) { @@ -15284,11 +19289,12 @@ v2_emit:; result = ray_table_new(total_cols); if (!result || RAY_IS_ERR(result)) goto cleanup; - /* Pre-allocate key columns */ - ray_t* key_cols[n_keys]; - char* key_dsts[n_keys]; - int8_t key_out_types[n_keys]; - uint8_t key_esizes[n_keys]; + /* Pre-allocate key columns (vla_keys == max(n_keys,1): a keyless + * group reaches here too, and a zero-length VLA is UB). */ + ray_t* key_cols[vla_keys]; + char* key_dsts[vla_keys]; + int8_t key_out_types[vla_keys]; + uint8_t key_esizes[vla_keys]; for (uint32_t k = 0; k < n_keys; k++) { ray_t* src_col = key_vecs[k]; key_cols[k] = NULL; @@ -15323,9 +19329,9 @@ v2_emit:; new_col->len = (int64_t)total_grps; /* Seed HAS_NULLS from the source key column, exactly as the * gather-based emit does (agg_gather_key_col). radix_phase3_fn - * runs in parallel and par_set_null writes this bit for the - * sentinel types only, so setting it once here — serially, - * before the dispatch — keeps SYM/STR/GUID null keys flagged + * runs in parallel without changing headers; sentinel types + * are finalized after the dispatch. Seeding this bit serially + * before the dispatch keeps SYM/STR/GUID null keys flagged * without a worker ever storing into a shared attrs byte that * other workers read non-atomically via ray_data(). * @@ -15466,6 +19472,7 @@ v2_emit:; .row_gid = row_gid, .match_idx = match_idx, .rowsel = rowsel, + .rr = ht_rr, }; /* Wide-key str-pool table (n_keys slots): carve once here (never * per row); NULL when no wide keys — cut 4. */ @@ -15476,8 +19483,19 @@ v2_emit:; if (!rp.key_pool) { scratch_free(rg_hdr); result = ray_error("oom", NULL); goto cleanup; } derive_key_pool(&ght_layout, key_vecs, rp.key_pool); } + ray_scan_fail_init(&ht_fail); ray_pool_dispatch(pool, reprobe_rows_fn, &rp, n_scan); scratch_free(rp_kp_hdr); + ray_t* rp_ferr = ht_rr.staged ? ray_scan_fail_finish(&ht_fail, pool) : NULL; + if (rp_ferr) { + /* R-FAIL: the result under construction is discarded */ + scratch_free(rg_hdr); + for (uint32_t k = 0; k < n_keys; k++) if (key_cols[k]) ray_release(key_cols[k]); + for (uint32_t a = 0; a < n_aggs; a++) if (agg_cols[a]) ray_release(agg_cols[a]); + ray_release(result); + result = rp_ferr; + goto cleanup; + } /* Build idx_buf + offsets + grp_cnt via histogram/scatter. * @@ -15730,10 +19748,25 @@ sequential_fallback:; result = ray_error("oom", NULL); goto cleanup; } - group_rows_range(&single_ht, key_data, key_types, key_attrs, key_vecs, agg_vecs, - agg_vecs2, agg_strlen, rowsel, - 0, n_scan, match_idx); final_ht = &single_ht; + if (ht_rr.staged) { + /* the serial builder by pieces (worker 0) */ + group_rows_ctx_t grc = { + .ht = &single_ht, .key_data = key_data, .key_types = key_types, + .key_vecs = key_vecs, .agg_vecs = agg_vecs, .agg_vecs2 = agg_vecs2, + .agg_strlen = agg_strlen, .rowsel = rowsel, .match_idx = match_idx, + .rr = ht_rr, + }; + grp_view_t gv = grp_view_whole(key_data, key_attrs); + ray_scan_fail_init(&ht_fail); + grp_run(&grc, group_rows_body, &gv, &grc.rr, match_idx ? NULL : rowsel, NULL, 0, 0, n_scan); + ray_t* sq_ferr = ray_scan_fail_finish(&ht_fail, NULL); + if (sq_ferr) { result = sq_ferr; goto cleanup; } + } else { + group_rows_range(&single_ht, key_data, key_types, key_attrs, key_vecs, agg_vecs, + agg_vecs2, agg_strlen, rowsel, + 0, n_scan, match_idx); + } if (ray_interrupted()) { result = ray_error("cancel", "interrupted"); goto cleanup; } if (single_ht.oom) { result = ray_error("oom", NULL); goto cleanup; } @@ -15783,7 +19816,7 @@ sequential_fallback:; switch (kt) { case RAY_F64: ((double*)ray_data(new_col))[gi] = NULL_F64; break; - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)ray_data(new_col))[gi] = NULL_I64; break; case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)ray_data(new_col))[gi] = NULL_I32; break; @@ -15825,6 +19858,7 @@ sequential_fallback:; * Built lazily on first need and reused across all median slots. */ ray_t** med_out = NULL; ray_t* med_hdr = NULL; + ray_t* hol_err = NULL; /* the reprobe's range error or a cancel */ if (ly->agg_flags_any & GHT_AF_HOLISTIC) { med_out = (ray_t**)scratch_calloc(&med_hdr, (size_t)n_aggs * sizeof(ray_t*)); @@ -15849,100 +19883,47 @@ sequential_fallback:; uint8_t reprobe_nullable_s = 0; /* 0/1: any key may be null */ for (uint32_t k = 0; k < n_keys; k++) if (ray_key_may_be_null(key_vecs[k])) { reprobe_nullable_s = 1; break; } - /* Key lookup staging + per-key str-pool table: stack for ≤8 - * keys, one heap block for wider (carved once — cut 4). */ + /* Per-key str-pool table: stack for ≤8 keys, one heap + * block for wider (carved once — cut 4). */ const void* reprobe_pool_stk[8]; - int64_t ek_buf_stk[9]; - char keybuf_stk[136]; const void** reprobe_pool = reprobe_pool_stk; - int64_t* ek_buf = ek_buf_stk; - char* keybuf = keybuf_stk; ray_t* hol_stage_hdr = NULL; - if ((size_t)ly->key_region > sizeof(ek_buf_stk) || n_keys > 8) { - size_t kb = ly->key_region; - char* blk = (char*)scratch_alloc(&hol_stage_hdr, - kb + kb + (size_t)n_keys * sizeof(void*)); - if (!blk) { + if (n_keys > 8) { + reprobe_pool = (const void**)scratch_alloc(&hol_stage_hdr, + (size_t)n_keys * sizeof(void*)); + if (!reprobe_pool) { scratch_free(rg_hdr); scratch_free(cnt_hdr_s); scratch_free(off_hdr_s); scratch_free(pos_hdr_s); result = ray_error("oom", NULL); goto cleanup; } - keybuf = blk; - ek_buf = (int64_t*)(blk + kb); - reprobe_pool = (const void**)(blk + kb + kb); } derive_key_pool(ly, key_vecs, reprobe_pool); - for (int64_t i = 0; i < n_scan; i++) { + /* The reprobe (reprobe_rows_fn on the one HT, worker 0) + * honours the pushed WHERE itself: the holistic fill + * re-scans rows independently of the streaming + * accumulators, so rows a rowsel rejects map to no group + * (-1) — otherwise median/top would aggregate the + * unfiltered group, diverging from every other agg. */ + memset(row_gid, 0xff, (size_t)nrows * sizeof(int64_t)); + uint32_t srp_off0 = 0; + reprobe_ctx_t srp = { + .key_data = key_data, .key_types = key_types, .key_attrs = key_attrs, + .key_vecs = key_vecs, .n_keys = n_keys, + .nullable_mask = reprobe_nullable_s, .layout = ly, + .key_pool = reprobe_pool, .part_hts = final_ht, + .part_offsets = &srp_off0, .group_out = NULL, .n_parts = 1, + .row_gid = row_gid, .match_idx = match_idx, .rowsel = rowsel, + .rr = ht_rr, + }; + ray_scan_fail_init(&ht_fail); + reprobe_rows_fn(&srp, 0, 0, n_scan); + hol_err = ht_rr.staged ? ray_scan_fail_finish(&ht_fail, NULL) : NULL; + if (!hol_err && ray_interrupted()) hol_err = ray_error("cancel", "interrupted"); + for (int64_t i = 0; i < n_scan && !hol_err; i++) { int64_t row = match_idx ? match_idx[i] : i; - /* Holistic fill re-scans rows independently of the streaming - * grouping accumulators, so it must honor the pushed WHERE - * filter itself. When the selection is carried as a rowsel - * (match_idx == NULL, the default), skip rows that don't - * pass — otherwise median/top would aggregate filtered-out - * rows (the unfiltered group), diverging from every other - * agg which already respects the selection. */ if (!match_idx && !group_rowsel_pass(rowsel, row)) continue; - uint64_t h = 0; - const int64_t* lookup_keys; - if (ly->any_inline_str) { - h = inline_build_keys(ly, key_types, key_data, key_attrs, - reprobe_pool, key_vecs, reprobe_nullable_s, - row, keybuf); - lookup_keys = (const int64_t*)keybuf; - } else { - int64_t* nullw = ek_buf + n_keys; /* null-mask words at key_off[nk] */ - uint32_t null_words = ly->null_words; - for (uint32_t w = 0; w < null_words; w++) nullw[w] = 0; - if (ly->packed_key) { - /* Packed tuple (ly->packed_key): every key is a plain integer lane, so - * the wide/F64 arms of the generic loop below are dead and the whole - * key region — values plus null-mask words — avalanches in ONE - * ght_hash_lanes call instead of nk hashes plus nk-1 combines. MUST - * stay in lockstep with hash_keys_inline (rehash/merge/lookup). */ - for (uint32_t k = 0; k < n_keys; k++) { - if (__builtin_expect(reprobe_nullable_s && ray_key_may_be_null(key_vecs[k]) - && ray_vec_is_null(key_vecs[k], row), 0)) { - nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); - ek_buf[k] = 0; - } else { - ek_buf[k] = read_col_i64(key_data[k], row, key_types[k], key_attrs[k]); - } - } - h = ght_hash_lanes(ek_buf, (uint32_t)n_keys + null_words); - } else { - for (uint32_t k = 0; k < n_keys; k++) { - int8_t t = key_types[k]; - uint64_t kh; - bool is_null = reprobe_nullable_s && ray_key_may_be_null(key_vecs[k]) - && ray_vec_is_null(key_vecs[k], row); - if (is_null) { - nullw[k >> 6] |= (int64_t)((uint64_t)1 << (k & 63)); - ek_buf[k] = 0; - kh = ray_hash_i64(0); - } else if (ly->key_flags[k] & GHT_KEYF_WIDE) { - ek_buf[k] = row; - kh = wide_key_hash_at(ly, k, key_data, reprobe_pool, row); - } else if (t == RAY_F64) { - /* -0.0 -> +0.0 before BOTH the store and the hash - * — must match the builder that filled final_ht. */ - int64_t kv = group_key_f64_bits(key_data[k], row); - double dv; memcpy(&dv, &kv, 8); - ek_buf[k] = kv; - kh = ray_hash_f64(dv); - } else { - int64_t kv = read_col_i64(key_data[k], row, t, key_attrs[k]); - ek_buf[k] = kv; - kh = ray_hash_i64(kv); - } - h = (k == 0) ? kh : ray_hash_combine(h, kh); - } - h = ght_hash_null_words(h, nullw, null_words); - } - lookup_keys = ek_buf; - } - uint32_t gid = group_ht_lookup_gid(final_ht, h, lookup_keys, key_types); - row_gid[row] = (gid == UINT32_MAX) ? -1 : (int64_t)gid; - if (gid != UINT32_MAX) grp_cnt_s[gid]++; + int64_t gid = row_gid[row]; + if (gid >= 0) grp_cnt_s[gid]++; } int64_t total_s = 0; for (uint32_t gi = 0; gi < grp_count; gi++) { @@ -15951,7 +19932,7 @@ sequential_fallback:; total_s += grp_cnt_s[gi]; } ray_t* ix_hdr_s = NULL; - int64_t* idx_buf_s = (int64_t*)scratch_alloc(&ix_hdr_s, + int64_t* idx_buf_s = hol_err ? NULL : (int64_t*)scratch_alloc(&ix_hdr_s, (size_t)(total_s > 0 ? total_s : 1) * sizeof(int64_t)); if (idx_buf_s) { for (int64_t i = 0; i < n_scan; i++) { @@ -16005,6 +19986,12 @@ sequential_fallback:; scratch_free(pos_hdr_s); } } + if (hol_err) { + scratch_free(med_hdr); /* no column was filled */ + ray_release(result); + result = hol_err; + goto cleanup; + } /* Agg columns from inline accumulators */ for (uint32_t a = 0; a < n_aggs; a++) { @@ -16086,7 +20073,8 @@ sequential_fallback:; case OP_SUM: v = is_f64 ? ROW_RD_F64(row, ly->off_sum, s) : (double)ROW_RD_I64(row, ly->off_sum, s); - if (agg_affine[a].enabled) v += agg_affine[a].bias_f64 * cnt; + /* `(sum (+ x c))`: c once per non-null x (#814) */ + if (agg_affine[a].enabled) v += agg_affine[a].bias_f64 * nn; break; case OP_PROD: if (nn == 0) { v = NULL_F64; ray_vec_set_null(new_col, gi, true); break; } @@ -16174,7 +20162,7 @@ sequential_fallback:; case OP_SUM: v = ROW_RD_I64(row, ly->off_sum, s); if (agg_affine[a].enabled) - v = wrap_add_i64(v, wrap_mul_i64(agg_affine[a].bias_i64, cnt)); + v = wrap_add_i64(v, wrap_mul_i64(agg_affine[a].bias_i64, nn)); break; case OP_PROD: if (nn == 0) { v = int_null; ray_vec_set_null(new_col, gi, true); break; } @@ -16292,6 +20280,8 @@ sequential_fallback:; { if (agg_owned[a] && agg_vecs[a]) ray_release(agg_vecs[a]); if (agg_owned2[a] && agg_vecs2[a]) ray_release(agg_vecs2[a]); } for (uint32_t k = 0; k < n_keys; k++) if (key_owned[k] && key_vecs[k]) ray_release(key_vecs[k]); + AGG_OWN_SRC_RELEASE(); + scratch_free(ht_rr_hdr); if (match_idx_block) { ray_release(match_idx_block); } scratch_free(vla_hdr); /* No explicit GC — top-level statement runner (run_piped / repl) @@ -16301,6 +20291,7 @@ sequential_fallback:; return result; } +#undef AGG_OWN_SRC_RELEASE /* Smallest index i in a[0..n) with a[i] >= key (lower_bound over a SORTED * ascending int64 array). Used to slice the flattened global selection ids @@ -16316,6 +20307,292 @@ static inline int64_t grp_sorted_lower_bound(const int64_t* a, int64_t n, return lo; } +/* The first-seen key set of an unordered take over a parted table: up to + * `n` distinct key tuples, in first-seen order over the selected rows + * (sel_ids: sorted global row ids, or every row when NULL), read from the + * partitions in order. Keys are partition-key (MAPCOMMON) columns or plain + * scan columns of the types agg_read_key_i64 reads. True with the tuples + * (keys[i * n_keys + k], *n_found of them) when n were found, or when every + * row was read (all the groups); false when the scan passed its budget or a + * key is not such a column (the caller then carries first rows instead). + * A segment that fails to materialize is its error in *err. */ +typedef struct { + int64_t* keys; /* found tuples in first-seen order: n * n_keys */ + int64_t* slot; /* hash slot -> tuple index, -1 empty: cap */ + int64_t cap, n_found; + uint32_t n_keys; +} grp_keyset_t; + +static uint64_t grp_keyset_hash(const int64_t* kv, uint32_t n_keys) { + uint64_t h = 0x9E3779B97F4A7C15ULL; + for (uint32_t k = 0; k < n_keys; k++) { h = (h ^ (uint64_t)kv[k]) * 0x9E3779B97F4A7C15ULL; h ^= h >> 32; } + return h * 0xD6E8FEB86659FD93ULL; +} + +/* Index of tuple kv in the set, inserting it when `insert` (returns -1 for + * an absent tuple either way). */ +static int64_t grp_keyset_probe(grp_keyset_t* ks, const int64_t* kv, bool insert) { + for (int64_t i = (int64_t)(grp_keyset_hash(kv, ks->n_keys) & (uint64_t)(ks->cap - 1));; + i = (i + 1) & (ks->cap - 1)) { + int64_t t = ks->slot[i]; + if (t < 0) { + if (insert) { + memcpy(ks->keys + ks->n_found * ks->n_keys, kv, ks->n_keys * sizeof(int64_t)); + ks->slot[i] = ks->n_found++; + } + return -1; + } + if (memcmp(ks->keys + t * ks->n_keys, kv, ks->n_keys * sizeof(int64_t)) == 0) return t; + } +} + +static bool grp_first_keys_scan(ray_t* pt, const int64_t* key_syms, uint32_t n_keys, + int32_t n_parts, const int64_t* sel_ids, int64_t sel_total, + const int64_t* part_off, int64_t n, grp_keyset_t* ks, + ray_t** err) { + *err = NULL; + if (n_keys == 0 || n_keys > 16 || n > AGG_FIRSTN_MAX) return false; + ray_t* mcv[16]; + for (uint32_t k = 0; k < n_keys; k++) { + ray_col_meta_t m; + if (!ray_table_col_meta(pt, key_syms[k], &m)) return false; + mcv[k] = NULL; + if (m.type == RAY_MAPCOMMON) { + ray_t* mc = ray_table_col(pt, key_syms[k]); /* MAPCOMMON is plain */ + if (!mc || RAY_IS_ERR(mc)) return false; + mcv[k] = ((ray_t**)ray_data(mc))[0]; /* not-a-table */ + if (!mcv[k] || !agg_key_i64_type(mcv[k]->type) || mcv[k]->len < n_parts) return false; + } else if (!RAY_IS_PARTED(m.type) || !agg_key_i64_type((int8_t)RAY_PARTED_BASETYPE(m.type))) { + return false; + } + } + int64_t budget = n * 64 > AGG_FIRSTN_PROBE_ROWS ? n * 64 : AGG_FIRSTN_PROBE_ROWS; + int64_t scanned = 0; + int64_t kv[16]; + /* Each key's partition-p segment is bound as a source and read through + * a cursor: rows ascend within a partition, so each touched vector of an + * encoded segment decodes once and a plain segment is read in place. */ + ray_col_src_t src[16]; + ray_col_cursor_t cur[16]; + bool done = false, ok = true; + for (int32_t p = 0; p < n_parts && !done && ok; p++) { + int64_t len = -1; + for (uint32_t k = 0; k < n_keys; k++) { + memset(&src[k], 0, sizeof src[k]); + ray_col_cursor_init(&cur[k], &src[k]); + } + for (uint32_t k = 0; k < n_keys && ok; k++) { + if (mcv[k]) continue; + ray_t* berr = grp_seg_bind(pt, key_syms[k], p, &src[k]); + if (berr) { *err = berr; ok = false; break; } + if (!src[k].obj || !agg_key_i64_type(src[k].type)) { ok = false; break; } + if (len < 0) len = src[k].len; + else if (src[k].len != len) { ok = false; break; } + } + if (ok && len < 0) ok = false; /* no parted key: not this route */ + int64_t lo = 0, hi = ok ? len : 0; + if (ok && sel_ids) { /* this partition's selected rows */ + lo = grp_sorted_lower_bound(sel_ids, sel_total, part_off[p]); + hi = grp_sorted_lower_bound(sel_ids, sel_total, part_off[p + 1]); + } + for (int64_t j = lo; ok && j < hi; j++) { + if (scanned++ >= budget) { ok = false; break; } + int64_t r = sel_ids ? sel_ids[j] - part_off[p] : j; + for (uint32_t k = 0; k < n_keys && ok; k++) { + if (mcv[k]) { kv[k] = agg_read_key_i64(mcv[k], ray_data(mcv[k]), p); continue; } + const ray_col_range_t* v; + ray_t* cerr = ray_col_cursor_at(&cur[k], r, &v); + if (cerr) { *err = cerr; ok = false; break; } + kv[k] = agg_read_key_i64_raw(src[k].type, v->attrs, v->data, r - v->start); + } + if (!ok) break; + grp_keyset_probe(ks, kv, true); + if (ks->n_found >= n) { done = true; break; } + } + for (uint32_t k = 0; k < n_keys; k++) { + ray_col_cursor_free(&cur[k]); + if (src[k].obj) ray_col_src_release(&src[k]); + } + } + return ok; /* every row read (or n found): all the groups */ +} + +/* The rows of `result` (key columns 0..n_keys) whose key is in the set, + * ordered by first-seen rank: an owned table, NULL when a found key has no + * result row (the caller declines), or an owned error. */ +static ray_t* grp_keep_first_keys(ray_t* result, grp_keyset_t* ks) { + int64_t rows = ray_table_nrows(result); + ray_t* okc[16]; + for (uint32_t k = 0; k < ks->n_keys; k++) { + okc[k] = ray_table_col_idx(result, k); + if (okc[k] && RAY_IS_ERR(okc[k])) return okc[k]; + if (!okc[k] || !agg_key_i64_type(okc[k]->type)) return NULL; + } + ray_t* idx = ray_vec_new(RAY_I64, ks->n_found > 0 ? ks->n_found : 1); + if (!idx || RAY_IS_ERR(idx)) return idx ? idx : ray_error("oom", NULL); + int64_t* ix = (int64_t*)ray_data(idx); + for (int64_t i = 0; i < ks->n_found; i++) ix[i] = -1; + int64_t kv[16], found = 0; + for (int64_t r = 0; r < rows && found < ks->n_found; r++) { + for (uint32_t k = 0; k < ks->n_keys; k++) kv[k] = agg_read_key_i64(okc[k], ray_data(okc[k]), r); + int64_t t = grp_keyset_probe(ks, kv, false); + if (t >= 0 && ix[t] < 0) { ix[t] = r; found++; } + } + if (found != ks->n_found) { ray_release(idx); return NULL; } + idx->len = found; + ray_t* out = ray_at_fn(result, idx); + ray_release(idx); + return out ? out : ray_error("oom", NULL); +} + +/* The rows of `result` holding the `n` smallest values of its I64 column + * `ci` (distinct global first-row ids), ordered by that value: an owned + * table, or an owned error. A bounded max-heap keeps the selection + * O(rows log n). */ +static ray_t* grp_keep_first_rows(ray_t* result, int64_t ci, int64_t n) { + ray_t* col = ray_table_col_idx(result, ci); + if (!col) return ray_error("domain", "group: first-row slot missing"); + if (RAY_IS_ERR(col)) return col; + if (col->type != RAY_I64) return ray_error("type", "group: first-row slot is %s", ray_type_name(col->type)); + int64_t rows = col->len; + if (n > rows) n = rows; + const int64_t* v = (const int64_t*)ray_data(col); + ray_t* idx = ray_vec_new(RAY_I64, n > 0 ? n : 1); + if (!idx || RAY_IS_ERR(idx)) return idx ? idx : ray_error("oom", NULL); + int64_t* h = (int64_t*)ray_data(idx); /* max-heap of row indices by v */ + int64_t hn = 0; + for (int64_t r = 0; r < rows && n > 0; r++) { + if (hn < n) { + int64_t i = hn++; + h[i] = r; + while (i > 0 && v[h[(i - 1) / 2]] < v[h[i]]) { + int64_t pi = (i - 1) / 2, t = h[pi]; h[pi] = h[i]; h[i] = t; i = pi; + } + } else if (v[r] < v[h[0]]) { + h[0] = r; + for (int64_t i = 0;;) { + int64_t l = 2 * i + 1, rr = l + 1, m = i; + if (l < hn && v[h[l]] > v[h[m]]) m = l; + if (rr < hn && v[h[rr]] > v[h[m]]) m = rr; + if (m == i) break; + int64_t t = h[m]; h[m] = h[i]; h[i] = t; i = m; + } + } + } + /* heap order -> ascending: repeatedly move the max to the end */ + for (int64_t end = hn - 1; end > 0; end--) { + int64_t t = h[0]; h[0] = h[end]; h[end] = t; + for (int64_t i = 0;;) { + int64_t l = 2 * i + 1, rr = l + 1, m = i; + if (l < end && v[h[l]] > v[h[m]]) m = l; + if (rr < end && v[h[rr]] > v[h[m]]) m = rr; + if (m == i) break; + int64_t t2 = h[m]; h[m] = h[i]; h[i] = t2; i = m; + } + } + idx->len = hn; + ray_t* out = ray_at_fn(result, idx); + ray_release(idx); + return out ? out : ray_error("oom", NULL); +} + +/* Release a per-partition sub-table: its expression keys / agg inputs were + * evaluated on the outer graph (exec_node with g->table swapped), which + * bound the sub-table's columns there; drop those binds with it, or each + * would keep its partition's column alive until the graph is freed. */ +static void pp_release_sub(ray_graph_t* g, ray_t* sub) { + if (sub && !RAY_IS_ERR(sub)) ray_graph_unbind_table(g, sub); + ray_release(sub); +} + +/* Concatenate the merge input for a STR or LIST column: the running result's + * column then each partial's, in that order (NULL entries contribute no + * rows). A STR cell is a descriptor into its own vector's string pool and a + * LIST cell a counted pointer, so neither survives the raw cell copy the + * fixed-width columns take: the strings are copied into the output's pool + * and the LIST elements are retained. */ +static ray_t* pp_concat_varlen(int8_t type, ray_t** srcs, int64_t n_srcs, + int64_t total) { + return type == RAY_STR ? parted_flatten_str(srcs, n_srcs, total) + : parted_flatten_list(srcs, n_srcs, total); +} + +/* Every segment of the parted column `sym` holds no null: a generation-2 + * segment by its directory null count, a plain one by its HAS_NULLS flag. + * A missing segment, or an encoded one without a null count, counts as + * nullable. */ +static bool pp_input_null_free(ray_t* parted_tbl, int64_t sym, int32_t n_parts) { + for (int32_t p = 0; p < n_parts; p++) { + ray_t* seg = ray_table_parted_seg(parted_tbl, sym, p); + ray_col_meta_t m; + if (!seg || !ray_col_meta_of(seg, &m)) return false; + if (m.null_count >= 0) { if (m.null_count > 0) return false; continue; } + if (m.enc || ray_vec_may_have_nulls(seg)) return false; + } + return true; +} + +/* The per-partition expression input `op` (a node of g over the parted + * table) yields no null when its inputs hold none. A column scan is + * pp_input_null_free; strlen is null-free over a null-free input; a cast of + * a null-free integer to I64 or F64 is exact. Everything else counts as + * nullable: integer arithmetic surfaces an overflow as null, float + * arithmetic can make a NaN, a division a null. */ +static bool pp_expr_null_free(ray_graph_t* g, ray_op_t* op, ray_t* parted_tbl, + int32_t n_parts, int depth) { + if (!op || depth > 8) return false; + switch (op->opcode) { + case OP_SCAN: { + ray_op_ext_t* x = find_ext(g, op->id); + return x && pp_input_null_free(parted_tbl, x->sym, n_parts); + } + case OP_STRLEN: + return op->arity == 1 && + pp_expr_null_free(g, op_child(g, op, 0), parted_tbl, n_parts, depth + 1); + case OP_CAST: { + ray_op_t* in = op->arity == 1 ? op_child(g, op, 0) : NULL; + if (!in || (op->out_type != RAY_I64 && op->out_type != RAY_F64)) return false; + int8_t t = in->out_type; + if (t != RAY_BOOL && t != RAY_U8 && t != RAY_I16 && t != RAY_I32 && t != RAY_I64) + return false; + return pp_expr_null_free(g, in, parted_tbl, n_parts, depth + 1); + } + default: + return false; + } +} + +/* AVG counts all rows only when its input is known null-free. In + * particular strlen maps the empty STR/SYM value to null (#888). */ +static bool pp_avg_counts_rows(ray_graph_t* g, ray_op_ext_t* ext, uint32_t a, + const uint8_t* agg_is_expr, const int64_t* agg_syms, + ray_t* parted_tbl, int32_t n_parts) { + if (!agg_is_expr[a]) return pp_input_null_free(parted_tbl, agg_syms[a], n_parts); + return pp_expr_null_free(g, op_node(g, ext->agg_ins[a]), parted_tbl, n_parts, 0); +} + +/* SUM / AVG input a of the per-partition group that is (strlen c) of a + * borrowed generation-2 column scan: c's symbol, else -1. Its partitions are not + * evaluated into a column: each partition's group takes the expression + * over its borrowed segment and aggregates it inline, by range over a + * generation-2 segment, as the splayed group does (try_strlen_sumavg_input + * and the range reads), so the segment is never materialized. */ +static int64_t pp_strlen_scan_sym(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, uint32_t a, + const uint8_t* agg_is_expr, const int64_t* borrow_syms, int n_borrow) { + if (!agg_is_expr[a] || (ext->agg_ops[a] != OP_SUM && ext->agg_ops[a] != OP_AVG)) return -1; + ray_op_t* in = op_node(g, ext->agg_ins[a]); + if (!in || in->opcode != OP_STRLEN || in->arity != 1) return -1; + ray_op_t* c = op_child(g, in, 0); + ray_op_ext_t* ce = c && c->opcode == OP_SCAN ? find_ext(g, c->id) : NULL; + if (!ce) return -1; + /* generation 2 only: a generation-0 column keeps its route (the + * partition's plain strlen column, measured cheaper there) */ + ray_col_meta_t cm; + if (!ray_table_col_meta(parted_tbl, ce->sym, &cm) || !cm.enc) return -1; + for (int j = 0; j < n_borrow; j++) if (borrow_syms[j] == ce->sym) return ce->sym; + return -1; +} + /* -------------------------------------------------------------------------- * exec_group_per_partition — per-partition GROUP BY with merge * @@ -16323,8 +20600,9 @@ static inline int64_t grp_sorted_lower_bound(const int64_t* a, int64_t n, * then merges the small partial results via a second exec_group pass. * * Merge ops: SUM→SUM, COUNT→SUM, MIN→MIN, MAX→MAX, FIRST→FIRST, LAST→LAST. - * AVG: decomposed into SUM+COUNT per partition, merged, then divided. - * STDDEV/VAR: decomposed into SUM(x)+SUM(x²)+COUNT(x) per partition, + * AVG: decomposed into SUM+N per partition, merged, then divided, where N is + * the input's non-null count (a SUM of its not-null indicator). + * STDDEV/VAR: decomposed into SUM(x)+SUM(x²)+N per partition, * merged with SUM, then final variance/stddev computed from merged totals. * * Pushed-down WHERE (g->selection set): the global selection covers the parted @@ -16346,10 +20624,17 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, int n_borrow, int has_avg, int has_stddev, int64_t group_limit) { - /* Count every entry into the streaming per-partition kernel (O(1), see the - * ray_group_perpart_runs_ctr definition near the top of this file). */ - atomic_fetch_add_explicit(&ray_group_perpart_runs_ctr, 1, - memory_order_relaxed); + /* The top-N emit filter (`asc:/desc: take: N`) names groups of the + * whole result: a partition's partial must keep every group (a group's + * aggregate is merged over all partitions), and so must the merge. Disarm + * it for the partial and merge executions (restored in pp_cleanup) and + * trim the finished result once with the filter's own decision. */ + ray_group_emit_filter_t ef_saved = ray_group_emit_filter_get(); + ray_group_emit_filter_t ef_trim = ray_group_emit_filter_active(); + if (ef_saved.enabled) { + ray_group_emit_filter_t off = {0}; + ray_group_emit_filter_set(off); + } uint32_t n_keys = ext->n_keys; uint32_t n_aggs = ext->n_aggs; @@ -16367,13 +20652,15 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, else if (aop == OP_STDDEV || aop == OP_STDDEV_POP || aop == OP_VAR || aop == OP_VAR_POP) n_std++; } - uint32_t part_n_aggs_max = n_aggs + n_avg + 2 * n_std; + uint32_t part_n_aggs_max = n_aggs + n_avg + 2 * n_std + 1; /* + the first-row slot */ size_t key_n = n_keys ? n_keys : 1; /* min-1 guarded */ size_t agg_n = n_aggs ? n_aggs : 1; size_t pna_n = part_n_aggs_max ? part_n_aggs_max : 1; ray_t* ret = NULL; /* pp_cleanup return value (NULL on any early bail) */ + grp_keyset_t fks = { 0 }; /* first-seen keys of an unordered take (freed in pp_cleanup) */ + bool frow_by_keys = false; /* Pushed-down WHERE state (Part A). saved_sel is captured now and * g->selection cleared later (in the setup block below) so the setup's @@ -16404,6 +20691,8 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, uint16_t* std_orig_op = scratch_alloc(&std_orig_op_hdr, agg_n * sizeof(uint16_t)); uint8_t* std_sq_slot = scratch_alloc(&std_sq_slot_hdr, agg_n * sizeof(uint8_t)); uint8_t* std_cnt_slot = scratch_alloc(&std_cnt_slot_hdr, agg_n * sizeof(uint8_t)); + ray_t* cnt_nn_hdr = NULL; /* per count slot (AVG's, then STDDEV/VAR's): counts non-nulls */ + uint8_t* cnt_nn = scratch_alloc(&cnt_nn_hdr, agg_n * sizeof(uint8_t)); /* decomposed per-partition/merge slot carves (sized part_n_aggs_max) */ ray_t *part_ops_hdr = NULL, *merge_ops_hdr = NULL, *part_agg_syms_hdr = NULL, @@ -16417,11 +20706,15 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, ray_op_t** pagg_ins = scratch_alloc(&pagg_ins_hdr, pna_n * sizeof(ray_op_t*)); ray_op_t** magg_ins = scratch_alloc(&magg_ins_hdr, pna_n * sizeof(ray_op_t*)); int64_t* unique_agg = scratch_alloc(&unique_agg_hdr, pna_n * sizeof(int64_t)); + /* Merge-table column names, one per POSITION (keys then partial slots). */ + ray_t* mcol_names_hdr = NULL; + int64_t* mcol_names = scratch_alloc(&mcol_names_hdr, + (key_n + pna_n) * sizeof(int64_t)); if (!mc_sym_ids || !pk_syms || !pkeys || !mkeys || !avg_idx || !std_idx || - !std_orig_op || !std_sq_slot || !std_cnt_slot || !part_ops || + !std_orig_op || !std_sq_slot || !std_cnt_slot || !cnt_nn || !part_ops || !merge_ops || !part_agg_syms || !part_needs_sq || !agg_name_ids || - !pagg_ins || !magg_ins || !unique_agg) + !pagg_ins || !magg_ins || !unique_agg || !mcol_names) goto pp_cleanup; /* Identify MAPCOMMON vs PARTED keys. MAPCOMMON keys are constant @@ -16431,8 +20724,8 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, uint32_t n_part_keys = 0; for (uint32_t k = 0; k < n_keys; k++) { - ray_t* pcol = ray_table_get_col(parted_tbl, key_syms[k]); - if (pcol && pcol->type == RAY_MAPCOMMON) { + ray_col_meta_t pcm; + if (ray_table_col_meta(parted_tbl, key_syms[k], &pcm) && pcm.type == RAY_MAPCOMMON) { mc_sym_ids[n_mc_keys++] = key_syms[k]; } else { pk_syms[n_part_keys++] = key_syms[k]; @@ -16440,13 +20733,25 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, } /* LIMIT pushdown: when all GROUP BY keys are MAPCOMMON (n_part_keys==0), - * each partition produces exactly 1 group. Limit the partition loop. - * Disabled under a pushed-down WHERE: a filtered partition may yield 0 - * groups (all rows filtered out), breaking the "1 group per partition" - * assumption the limit relies on — the outer take/limit truncates the - * merged result instead. */ - if (group_limit > 0 && n_part_keys == 0 && group_limit < n_parts && !saved_sel) - n_parts = (int32_t)group_limit; + * each non-empty partition produces exactly 1 group. Limit the partition + * loop to the first group_limit non-empty partitions (the partition key's + * per-partition row counts say which). Disabled under a pushed-down + * WHERE: a filtered partition may yield 0 groups (all rows filtered out), + * breaking the "1 group per non-empty partition" assumption the limit + * relies on — the outer take/limit truncates the merged result instead. */ + if (group_limit > 0 && n_part_keys == 0 && n_mc_keys > 0 && + group_limit < n_parts && !saved_sel) { + ray_t* mc_col = ray_table_col(parted_tbl, mc_sym_ids[0]); /* MAPCOMMON is plain */ + ray_t* mc_cnt = (mc_col && !RAY_IS_ERR(mc_col) && mc_col->type == RAY_MAPCOMMON) + ? ((ray_t**)ray_data(mc_col))[1] : NULL; /* not-a-table */ + if (mc_cnt && mc_cnt->type == RAY_I64 && mc_cnt->len >= n_parts) { + const int64_t* cnt = (const int64_t*)ray_data(mc_cnt); + int64_t seen = 0; + for (int32_t p = 0; p < n_parts; p++) { + if (cnt[p] > 0 && ++seen == group_limit) { n_parts = p + 1; break; } + } + } + } /* Pushed-down WHERE setup (Part A): flatten the global selection once, * clear g->selection for the materialization phase, and precompute the @@ -16469,22 +20774,27 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, * len) or MAPCOMMON (counts[p]). All columns share partition * boundaries, so any one is authoritative. */ int64_t pncols = ray_table_ncols(parted_tbl); - ray_t* ref = NULL; + ray_t* ref = NULL; /* plain wrapper or MAPCOMMON slot */ + ray_t* ref_enc = NULL; /* encoded parted slot: segments read through it */ for (int64_t c = 0; c < pncols; c++) { - ray_t* col = ray_table_get_col_idx(parted_tbl, c); - if (col && (RAY_IS_PARTED(col->type) || - col->type == RAY_MAPCOMMON)) { ref = col; break; } + ray_col_meta_t rm; + if (!ray_table_col_meta_idx(parted_tbl, c, &rm) || + !(RAY_IS_PARTED(rm.type) || rm.type == RAY_MAPCOMMON)) continue; + ref_enc = ray_table_get_col_enc_idx(parted_tbl, c); + ref = ref_enc ? ref_enc : ray_table_col_idx(parted_tbl, c); /* plain slot: never fails */ + break; } if (!ref) goto pp_cleanup; - const int64_t* mc_counts = (ref->type == RAY_MAPCOMMON) - ? (const int64_t*)ray_data(((ray_t**)ray_data(ref))[1]) : NULL; - ray_t** ref_segs = (ref->type == RAY_MAPCOMMON) - ? NULL : (ray_t**)ray_data(ref); + const int64_t* mc_counts = (!ref_enc && ref->type == RAY_MAPCOMMON) + ? (const int64_t*)ray_data(((ray_t**)ray_data(ref))[1]) : NULL; /* not-a-table */ + ray_t** ref_segs = (ref_enc || mc_counts) ? NULL : (ray_t**)ray_data(ref); int64_t cum = 0, max_len = 0; for (int32_t p = 0; p < n_parts; p++) { part_off[p] = cum; + ray_t* ref_seg = ref_enc ? ray_enccol_seg(ref_enc, p) + : (ref_segs ? ref_segs[p] : NULL); int64_t len_p = mc_counts ? mc_counts[p] - : (ref_segs[p] ? ref_segs[p]->len : 0); + : (ref_seg ? ref_seg->len : 0); cum += len_p; if (len_p > max_len) max_len = len_p; } @@ -16498,6 +20808,11 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, /* Decomposition: AVG(x) → SUM(x) + COUNT(x). * STDDEV/VAR(x) → SUM(x) + SUM(x²) + COUNT(x). + * COUNT(x) here is the NON-NULL count (SUM skips null x, so the divisor + * must too). OP_COUNT is the group row count (nulls included), so it is + * used only for a partition whose segment cannot hold nulls; otherwise + * the slot is the internal OP_COUNT_NN (a plain column) or sums a + * not-null indicator (an expression input), chosen per partition below. * Build per-partition agg_ops with decomposed ops, then merge ops. * part_ops/merge_ops/avg_idx/std_idx/std_orig_op/std_sq_slot/std_cnt_slot * are carved above; n_avg/n_std are recounted here to fill them. */ @@ -16524,13 +20839,67 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, std_sq_slot[i] = part_n_aggs; part_ops[part_n_aggs++] = OP_SUM; /* SUM(x²) */ } - /* Append COUNT for each AVG column */ - for (uint32_t i = 0; i < n_avg; i++) - part_ops[part_n_aggs++] = OP_COUNT; - /* Append COUNT for each STDDEV/VAR column */ + /* Append the count of each AVG column, then of each STDDEV/VAR column. + * OP_COUNT counts rows, nulls included, while SUM(x) and SUM(x²) skip + * nulls (#767): an input that may hold a null counts its non-nulls, a + * SUM over its not-null indicator (built per partition below). An input + * that cannot hold one (a null-free column, an expression over null-free + * columns that yields none) keeps the row count. */ + for (uint32_t i = 0; i < n_avg; i++) { + uint32_t a = avg_idx[i]; + cnt_nn[i] = !pp_avg_counts_rows(g, ext, a, agg_is_expr, agg_syms, parted_tbl, n_parts); + part_ops[part_n_aggs++] = cnt_nn[i] ? OP_SUM : OP_COUNT; + } for (uint32_t i = 0; i < n_std; i++) { + uint32_t a = std_idx[i]; + cnt_nn[n_avg + i] = agg_is_expr[a] + ? !pp_expr_null_free(g, op_node(g, ext->agg_ins[a]), parted_tbl, n_parts, 0) + : !pp_input_null_free(parted_tbl, agg_syms[a], n_parts); std_cnt_slot[i] = part_n_aggs; - part_ops[part_n_aggs++] = OP_COUNT; + part_ops[part_n_aggs++] = cnt_nn[n_avg + i] ? OP_SUM : OP_COUNT; + } + + /* First-row slot: an unordered `take: N` (group_limit > 0) keeps the + * first N groups in first-seen order. Each partial carries the MIN of + * a hidden column of global row ids (partition offset + local row, over + * the rows the partition's selection keeps); the merge takes the MIN, + * and the finished result keeps the N groups with the smallest first + * row, in that order (the dense first-N path's rule). A group keyed + * only by the partition key needs none: the LIMIT pushdown above. */ + int64_t frow_sym = -1; + uint32_t frow_slot = 0; + if (group_limit > 0 && n_part_keys > 0) { + frow_sym = ray_sym_intern("_gprow", 6); + ray_col_meta_t fm_; + if (ray_table_col_meta(parted_tbl, frow_sym, &fm_)) goto pp_cleanup; /* a real column has the name */ + frow_slot = part_n_aggs; + part_ops[part_n_aggs++] = OP_MIN; + } + /* Cheaper when the first N distinct keys show up early in the scan + * order (or the whole input is short): read them up front and keep + * those groups of the merged result in that order; the hidden slot + * stays for the rest. */ + if (frow_sym >= 0 && group_limit <= AGG_FIRSTN_MAX) { + int64_t cap = 16; + while (cap < group_limit * 4) cap *= 2; + fks.n_keys = n_keys; + fks.cap = cap; + fks.keys = ray_alloc_raw((size_t)group_limit * n_keys * sizeof(int64_t)); + fks.slot = ray_alloc_raw((size_t)cap * sizeof(int64_t)); + if (fks.keys && fks.slot) { + for (int64_t i = 0; i < cap; i++) fks.slot[i] = -1; + bool any_expr = false; + for (uint32_t k = 0; k < n_keys; k++) any_expr |= key_is_expr[k] != 0; + ray_t* serr = NULL; + frow_by_keys = !any_expr && + grp_first_keys_scan(parted_tbl, key_syms, n_keys, n_parts, saved_sel ? sel_ids : NULL, + sel_total, part_off, group_limit, &fks, &serr); + if (serr) { ret = serr; goto pp_cleanup; } + } + if (frow_by_keys) { /* drop the hidden slot */ + part_n_aggs--; + frow_sym = -1; + } } /* Merge ops: SUM→SUM, COUNT→SUM, MIN→MIN, MAX→MAX, @@ -16560,6 +20929,23 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, /* COUNT slots for STDDEV/VAR */ for (uint32_t i = 0; i < n_std; i++) part_agg_syms[std_cnt_slot[i]] = agg_syms[std_idx[i]]; + if (frow_sym >= 0) part_agg_syms[frow_slot] = frow_sym; + /* Borrow the text source for a strlen SUM/AVG. A nullable AVG's + * auxiliary count scans the same source and counts non-null lengths. */ + for (uint32_t a = 0; a < n_aggs; a++) { + int64_t ls = pp_strlen_scan_sym(g, parted_tbl, ext, a, agg_is_expr, borrow_syms, n_borrow); + if (ls >= 0) part_agg_syms[a] = ls; + } + for (uint32_t i = 0; i < n_avg; i++) { + uint32_t a = avg_idx[i]; + int64_t ls = pp_strlen_scan_sym(g, parted_tbl, ext, a, agg_is_expr, borrow_syms, n_borrow); + if (ls >= 0 && cnt_nn[i]) { + uint32_t cs = n_aggs + n_std + i; + part_agg_syms[cs] = ls; + /* This slot sums the not-null indicator built below. */ + } + } + int64_t frow_base = 0; /* global row id of the partition's first row (no selection) */ /* ---- Batched incremental merge ---- * Process partitions in batches of MERGE_BATCH. After each batch: @@ -16573,6 +20959,21 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, * (agg_name_ids carved above, sized part_n_aggs_max). */ int agg_names_captured = 0; + /* The merge table holds ONLY the key columns (positions [0, n_keys)) and + * the partial slots (positions [n_keys, n_keys + part_n_aggs)), and the + * merge GROUP BY can only address them through name scans. Partial + * names come from the partition's group emit ("f_count", "f_sum", ...) + * and key names are user columns, so the two families can collide (a key + * column named "f_count" next to (count f) — the first-match scan then + * reads the key as the partial). Name every merge column after its + * position instead: no two coincide, and no user name enters the merge. */ + for (uint32_t c = 0; c < n_keys + part_n_aggs; c++) { + char nbuf[24]; + int nl = snprintf(nbuf, sizeof(nbuf), "_gm%u", (unsigned)c); + mcol_names[c] = ray_sym_intern(nbuf, (size_t)nl); + if (mcol_names[c] < 0) goto pp_cleanup; + } + ray_t* running = NULL; ray_t* merge_tbl = NULL; /* last merge table (for column name fixup) */ @@ -16616,6 +21017,7 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, * this batch). The reference partition is never skipped, so the * bp[ref_bi] type lookups below always resolve. */ int64_t sel_off = 0, sel_len = 0, sel_lo = 0, sel_cnt = -1; + int32_t src_p = p; /* the partition whose segments are read */ if (saved_sel) { sel_off = part_off[p]; sel_len = part_off[p + 1] - sel_off; @@ -16627,6 +21029,19 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, bp[bi] = NULL; continue; } + /* A whole-table aggregate answers one row whatever the + * where: keeps, and that row comes from the reference + * partial. Over a partition holding no rows the sub-group + * answers none (a 0-row input has no row to aggregate), so + * when every partition's survivors are skipped the select + * came back empty. Read the reference from a partition + * that has rows, under an empty selection: the same + * columns, no survivors, the one row of the empty answer. */ + if (sel_cnt == 0 && n_keys == 0 && sel_len == 0) { + for (int32_t q = 0; q < n_parts; q++) + if (part_off[q + 1] > part_off[q]) { src_p = q; break; } + sel_len = part_off[src_p + 1] - part_off[src_p]; + } } /* Build the per-partition sub-table. It carries (a) the borrow @@ -16640,21 +21055,21 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, * unchanged. (unique_agg's key/agg dedup is subsumed by * borrow_syms, which is already deduplicated.) */ (void)unique_agg; - ray_t* sub = ray_table_new((int64_t)(n_borrow + n_keys + n_aggs)); + ray_t* sub = ray_table_new((int64_t)(n_borrow + n_keys + n_aggs + 1)); if (!sub || RAY_IS_ERR(sub)) goto batch_fail; int64_t part_nrows = -1; + int64_t fill_budget = GRP_NULL_FILL_BUDGET; /* one sub-table's fills live at a time */ for (int j = 0; j < n_borrow; j++) { - ray_t* pcol = ray_table_get_col(parted_tbl, borrow_syms[j]); - if (!pcol || !RAY_IS_PARTED(pcol->type)) { - ray_release(sub); goto batch_fail; - } - ray_t* seg = ((ray_t**)ray_data(pcol))[p]; - if (!seg) { ray_release(sub); goto batch_fail; } + ray_t* seg = ray_table_parted_seg(parted_tbl, borrow_syms[j], src_p); + if (!seg) { pp_release_sub(g, sub); goto batch_fail; } if (part_nrows < 0) part_nrows = seg->len; - ray_retain(seg); - sub = ray_table_add_col(sub, borrow_syms[j], seg); - ray_release(seg); + /* a ragged partition's synthetic segment: its nulls in place */ + ray_t* fill = grp_synth_plain(seg, &fill_budget); + if (fill && RAY_IS_ERR(fill)) { ret = fill; pp_release_sub(g, sub); goto batch_fail; } + if (!fill) ray_retain(seg); + sub = ray_table_add_col(sub, borrow_syms[j], fill ? fill : seg); + ray_release(fill ? fill : seg); } /* Materialize expression keys / agg inputs over this partition. @@ -16671,29 +21086,53 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, g->table = saved; if (!v || RAY_IS_ERR(v) || !ray_is_vec(v) || (part_nrows >= 0 && v->len != part_nrows)) { - if (v && !RAY_IS_ERR(v)) ray_release(v); - ray_release(sub); goto batch_fail; + /* decline: the concat fallback re-evaluates the + * expression and reports its error */ + if (v && RAY_IS_ERR(v)) ray_error_free(v); + else if (v) ray_release(v); + pp_release_sub(g, sub); goto batch_fail; } sub = ray_table_add_col(sub, key_syms[k], v); ray_release(v); } for (uint32_t a = 0; a < n_aggs; a++) { if (!agg_is_expr[a]) continue; + if (pp_strlen_scan_sym(g, parted_tbl, ext, a, agg_is_expr, borrow_syms, n_borrow) >= 0) continue; /* below */ ray_t* saved = g->table; g->table = sub; ray_t* v = exec_node(g, op_node(g, ext->agg_ins[a])); g->table = saved; if (!v || RAY_IS_ERR(v) || !ray_is_vec(v) || (part_nrows >= 0 && v->len != part_nrows)) { - if (v && !RAY_IS_ERR(v)) ray_release(v); - ray_release(sub); goto batch_fail; + /* decline: the concat fallback re-evaluates the + * expression and reports its error */ + if (v && RAY_IS_ERR(v)) ray_error_free(v); + else if (v) ray_release(v); + pp_release_sub(g, sub); goto batch_fail; } sub = ray_table_add_col(sub, agg_syms[a], v); ray_release(v); } + if (frow_sym >= 0) { + int64_t base = saved_sel ? part_off[p] : frow_base; + int64_t nr = part_nrows > 0 ? part_nrows : 0; + ray_t* ids = ray_vec_new(RAY_I64, nr > 0 ? nr : 1); + if (!ids || RAY_IS_ERR(ids)) { + if (ids) ray_error_free(ids); + pp_release_sub(g, sub); goto batch_fail; + } + ids->len = nr; + int64_t* idv = (int64_t*)ray_data(ids); + for (int64_t r = 0; r < nr; r++) idv[r] = base + r; + frow_base += nr; + sub = ray_table_add_col(sub, frow_sym, ids); + ray_release(ids); + if (!sub || RAY_IS_ERR(sub)) { if (sub) ray_error_free(sub); goto batch_fail; } + } + ray_graph_t* pg = ray_graph_new(sub); - if (!pg) { ray_release(sub); goto batch_fail; } + if (!pg) { pp_release_sub(g, sub); goto batch_fail; } for (uint32_t k = 0; k < n_part_keys; k++) { ray_t* sym_atom = ray_sym_str(pk_syms[k]); @@ -16703,6 +21142,16 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, ray_t* sym_atom = ray_sym_str(part_agg_syms[a]); pagg_ins[a] = ray_scan(pg, ray_str_ptr(sym_atom)); } + /* (strlen c) inputs: the SUM slot's scan of c (set above) + * wrapped in the expression */ + for (uint32_t a = 0; a < n_aggs; a++) { + if (pp_strlen_scan_sym(g, parted_tbl, ext, a, agg_is_expr, borrow_syms, n_borrow) < 0) continue; + pagg_ins[a] = pagg_ins[a] ? ray_strlen(pg, pagg_ins[a]) : NULL; + if (!pagg_ins[a]) { ray_graph_free(pg); pp_release_sub(g, sub); goto batch_fail; } + } + /* strlen is null exactly when its STR/SYM source is null. + * The auxiliary count scans that source directly: its null + * predicate can run by range without decoding a strlen vector. */ for (uint32_t j = 0; j < n_std; j++) { uint8_t sq = std_sq_slot[j]; ray_op_t* x = pagg_ins[sq]; @@ -16713,6 +21162,37 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, ray_op_t* xf = (x->out_type == RAY_F64) ? x : ray_cast(pg, x, RAY_F64); pagg_ins[sq] = ray_mul(pg, xf, xf); } + /* SUM over TIME emits TIME (4 bytes) on both engines, while the + * readout below takes every non-F64 sum partial as I64 (and a + * clock-value sum overflows 32 bits within a few thousand rows): + * sum the AVG/VAR input of a TIME column as I64. */ + for (uint32_t j = 0; j < n_avg + n_std; j++) { + uint32_t a = j < n_avg ? avg_idx[j] : std_idx[j - n_avg]; + ray_op_t* x = pagg_ins[a]; + if (x && x->out_type == RAY_TIME) { + pagg_ins[a] = ray_cast(pg, x, RAY_I64); + if (!pagg_ins[a]) { ray_graph_free(pg); pp_release_sub(g, sub); goto batch_fail; } + } + } + /* The non-null count slots of nullable inputs (AVG's, then + * STDDEV/VAR's): SUM of the input's not-null indicator as I64. */ + for (uint32_t j = 0; j < n_avg + n_std; j++) { + if (!cnt_nn[j]) continue; + uint32_t cs = j < n_avg ? n_aggs + n_std + j : std_cnt_slot[j - n_avg]; + atomic_fetch_add_explicit(&ray_group_perpart_nn_ctr, 1, memory_order_relaxed); + ray_op_t* cx = pagg_ins[cs]; + /* A FILE-domain SYM is admitted by the range expression VM + * only as an equality operand, not as an integer value. + * Its null is the empty symbol: compare in its own domain. */ + uint32_t cxid = cx ? cx->id : RAY_OP_NONE; + ray_op_t* empty = cx && cx->out_type == RAY_SYM + ? ray_const_str(pg, "", 0) : NULL; + cx = cxid != RAY_OP_NONE ? op_node(pg, cxid) : NULL; + ray_op_t* nn = empty ? ray_ne(pg, cx, empty) + : ray_not(pg, ray_isnull(pg, cx)); + pagg_ins[cs] = nn ? ray_cast(pg, nn, RAY_I64) : NULL; + if (!pagg_ins[cs]) { ray_graph_free(pg); pp_release_sub(g, sub); goto batch_fail; } + } ray_op_t* proot = ray_group(pg, pkeys, n_part_keys, part_ops, pagg_ins, part_n_aggs); @@ -16728,21 +21208,38 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, * ray_graph_free(pg) releases pg->selection. */ if (saved_sel) { if (part_nrows >= 0 && part_nrows != sel_len) { - ray_graph_free(pg); ray_release(sub); goto batch_fail; + ray_graph_free(pg); pp_release_sub(g, sub); goto batch_fail; } for (int64_t j = 0; j < sel_cnt; j++) local_ids[j] = sel_ids[sel_lo + j] - sel_off; ray_t* lsel = ray_index_rowsel_from_ids(sel_len, local_ids, sel_cnt); - if (!lsel) { ray_graph_free(pg); ray_release(sub); goto batch_fail; } + if (!lsel) { ray_graph_free(pg); pp_release_sub(g, sub); goto batch_fail; } pg->selection = lsel; } bp[bi] = ray_execute(pg, proot); ray_graph_free(pg); - ray_release(sub); - - if (!bp[bi] || RAY_IS_ERR(bp[bi])) goto batch_fail; + pp_release_sub(g, sub); + + /* batch_fail releases bp[], which leaves an error object be */ + if (bp[bi] && RAY_IS_ERR(bp[bi])) { ray_error_free(bp[bi]); bp[bi] = NULL; } + if (!bp[bi]) goto batch_fail; + /* A zero-survivor partition is built only as the schema + * reference. Grouped on partition keys alone, its sub-group + * has no key and still answers one row (the aggregates of no + * rows), which the merge would key by this partition: keep + * its columns, drop the row. With no key at all that row is + * the empty-input answer of a whole-table aggregate: keep it. */ + if (sel_cnt == 0 && n_part_keys == 0 && n_mc_keys > 0) { + ray_t* zero = make_i64(0); + ray_t* empty = zero ? ray_take_fn(bp[bi], zero) : NULL; + if (zero) ray_release(zero); + ray_release(bp[bi]); + bp[bi] = empty; + if (bp[bi] && RAY_IS_ERR(bp[bi])) { ray_error_free(bp[bi]); bp[bi] = NULL; } + if (!bp[bi]) goto batch_fail; + } if (ref_bi < 0) ref_bi = bi; /* first built partial in this batch */ /* Capture agg column name IDs once (all partials share names) */ @@ -16765,7 +21262,10 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, merge_tbl = NULL; goto batch_fail; } - /* Key columns */ + /* Key columns. Read by position: running keeps key k at column k, + * a partial keeps its non-MAPCOMMON keys first, in key order (pk_pos + * counts them). */ + uint32_t pk_pos = 0; for (uint32_t k = 0; k < n_keys; k++) { /* Poll cancellation before allocating this column's flat vec * (each concat copy is O(total merged groups)). No live `flat` @@ -16781,17 +21281,40 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, /* Type reference for column allocation */ ray_t* tref = NULL; if (running) { - tref = ray_table_get_col(running, key_syms[k]); + tref = ray_table_col_idx(running, (int64_t)k); } else if (is_mc) { - ray_t* mc_col = ray_table_get_col(parted_tbl, key_syms[k]); - tref = ((ray_t**)ray_data(mc_col))[0]; + ray_t* mc_col = ray_table_col(parted_tbl, key_syms[k]); /* MAPCOMMON is plain */ + tref = ((ray_t**)ray_data(mc_col))[0]; /* not-a-table */ } else { /* ref_bi = first built partial (skipped zero-survivor * partitions leave bp[bi] NULL); always >= 0 here. */ - tref = ray_table_get_col(bp[ref_bi >= 0 ? ref_bi : 0], key_syms[k]); + tref = ray_table_col_idx(bp[ref_bi >= 0 ? ref_bi : 0], (int64_t)pk_pos); } + if (tref && RAY_IS_ERR(tref)) { ret = tref; goto batch_fail; } if (!tref) goto batch_fail; + /* STR / LIST key (an expression key yielding strings): each + * partial's cells point into that partial's own storage, so + * they are concatenated by value. */ + if (!is_mc && (tref->type == RAY_STR || tref->type == RAY_LIST)) { + ray_t* srcs[MERGE_BATCH + 1]; + int64_t ns = 0; + srcs[ns++] = running ? ray_table_col_idx(running, (int64_t)k) : NULL; + for (int32_t i = 0; i < batch_n; i++) + srcs[ns++] = bp[i] ? ray_table_col_idx(bp[i], (int64_t)pk_pos) : NULL; + for (int64_t s = 0; s < ns; s++) { + if (srcs[s] && RAY_IS_ERR(srcs[s])) { ret = srcs[s]; goto batch_fail; } + if (srcs[s] && srcs[s]->type != tref->type) goto batch_fail; + } + ray_t* flat = pp_concat_varlen(tref->type, srcs, ns, mrows); + if (!flat || RAY_IS_ERR(flat)) { ret = flat; goto batch_fail; } + merge_tbl = ray_table_add_col(merge_tbl, mcol_names[k], flat); + ray_release(flat); + if (!merge_tbl || RAY_IS_ERR(merge_tbl)) goto merge_add_fail; + pk_pos++; /* a STR/LIST key is never MAPCOMMON */ + continue; + } + /* Per-partition group outputs keep their partition's SYM index * width, so partials in one batch can legitimately differ — * size the merged flat at the max width and convert per @@ -16800,14 +21323,16 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, if (tref->type == RAY_SYM) { uint8_t w = tref->attrs & RAY_SYM_W_MASK; if (running) { - ray_t* rc = ray_table_get_col(running, key_syms[k]); + ray_t* rc = ray_table_col_idx(running, (int64_t)k); + if (rc && RAY_IS_ERR(rc)) { ret = rc; goto batch_fail; } if (rc && rc->type == RAY_SYM && (rc->attrs & RAY_SYM_W_MASK) > w) w = rc->attrs & RAY_SYM_W_MASK; } for (int32_t i = 0; i < batch_n; i++) { ray_t* pc = is_mc ? NULL - : ray_table_get_col(bp[i], key_syms[k]); + : ray_table_col_idx(bp[i], (int64_t)pk_pos); + if (pc && RAY_IS_ERR(pc)) { ret = pc; goto batch_fail; } if (pc && pc->type == RAY_SYM && (pc->attrs & RAY_SYM_W_MASK) > w) w = pc->attrs & RAY_SYM_W_MASK; @@ -16815,7 +21340,10 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, out_attrs = w; } ray_t* flat = typed_vec_new(tref->type, out_attrs, mrows); - if (!flat || RAY_IS_ERR(flat)) goto batch_fail; + if (!flat || RAY_IS_ERR(flat)) { + if (flat) ray_error_free(flat); + goto batch_fail; + } /* cell ids copied id-preserving from running/partial/MAPCOMMON * key vecs — all resolve over the same dictionary (PARTED * contract: one root symfile domain), represented by tref. */ @@ -16829,7 +21357,8 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, /* Copy from running result */ if (running) { - ray_t* rc = ray_table_get_col(running, key_syms[k]); + ray_t* rc = ray_table_col_idx(running, (int64_t)k); + if (rc && RAY_IS_ERR(rc)) { ray_release(flat); ret = rc; goto batch_fail; } if (rc && rc->len > 0) { parted_copy_cells(out, flat->type, out_attrs, 0, rc, 0, rc->len); @@ -16844,8 +21373,8 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, if (is_mc) { /* MAPCOMMON: replicate this partition's key value */ int32_t p = batch_start + i; - ray_t* mc_col = ray_table_get_col(parted_tbl, key_syms[k]); - ray_t* mc_kv = ((ray_t**)ray_data(mc_col))[0]; + ray_t* mc_col = ray_table_col(parted_tbl, key_syms[k]); /* MAPCOMMON is plain */ + ray_t* mc_kv = ((ray_t**)ray_data(mc_col))[0]; /* not-a-table */ for (int64_t r = 0; r < pnrows; r++) { /* O(groups) replicate: stride-poll cancellation. * `flat` is live and not yet added to merge_tbl — @@ -16861,7 +21390,8 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, src_nulls |= mc_kv->attrs & RAY_ATTR_HAS_NULLS; off += pnrows; } else { - ray_t* pc = ray_table_get_col(bp[i], key_syms[k]); + ray_t* pc = ray_table_col_idx(bp[i], (int64_t)pk_pos); + if (pc && RAY_IS_ERR(pc)) { ray_release(flat); ret = pc; goto batch_fail; } if (pc && pc->len > 0) { parted_copy_cells(out, flat->type, out_attrs, off, pc, 0, pc->len); @@ -16873,8 +21403,10 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, /* Null propagation: propagate HAS_NULLS from copied sources. */ flat->attrs |= src_nulls; - merge_tbl = ray_table_add_col(merge_tbl, key_syms[k], flat); + merge_tbl = ray_table_add_col(merge_tbl, mcol_names[k], flat); ray_release(flat); + if (!merge_tbl || RAY_IS_ERR(merge_tbl)) goto merge_add_fail; + if (!is_mc) pk_pos++; } /* Agg columns */ @@ -16886,19 +21418,40 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, goto batch_fail; } ray_t* tref = running - ? ray_table_get_col_idx(running, (int64_t)n_keys + a) - : ray_table_get_col_idx(bp[ref_bi >= 0 ? ref_bi : 0], - (int64_t)n_part_keys + a); + ? ray_table_col_idx(running, (int64_t)n_keys + a) + : ray_table_col_idx(bp[ref_bi >= 0 ? ref_bi : 0], + (int64_t)n_part_keys + a); + if (tref && RAY_IS_ERR(tref)) { ret = tref; goto batch_fail; } if (!tref) goto batch_fail; + /* STR / LIST partials (FIRST/LAST of strings): same as the keys. */ + if (tref->type == RAY_STR || tref->type == RAY_LIST) { + ray_t* srcs[MERGE_BATCH + 1]; + int64_t ns = 0; + srcs[ns++] = running ? ray_table_col_idx(running, (int64_t)n_keys + a) : NULL; + for (int32_t i = 0; i < batch_n; i++) + srcs[ns++] = bp[i] ? ray_table_col_idx(bp[i], (int64_t)n_part_keys + a) : NULL; + for (int64_t s = 0; s < ns; s++) { + if (srcs[s] && RAY_IS_ERR(srcs[s])) { ret = srcs[s]; goto batch_fail; } + if (srcs[s] && srcs[s]->type != tref->type) goto batch_fail; + } + ray_t* flat = pp_concat_varlen(tref->type, srcs, ns, mrows); + if (!flat || RAY_IS_ERR(flat)) { ret = flat; goto batch_fail; } + merge_tbl = ray_table_add_col(merge_tbl, mcol_names[n_keys + a], flat); + ray_release(flat); + if (!merge_tbl || RAY_IS_ERR(merge_tbl)) goto merge_add_fail; + continue; + } + /* SYM partials (FIRST/LAST/MIN/MAX) keep their partition's * index width — size at max width, convert per source. */ uint8_t out_attrs = tref->attrs; if (tref->type == RAY_SYM) { uint8_t w = tref->attrs & RAY_SYM_W_MASK; for (int32_t i = 0; i < batch_n; i++) { - ray_t* pc = ray_table_get_col_idx(bp[i], - (int64_t)n_part_keys + a); + ray_t* pc = ray_table_col_idx(bp[i], + (int64_t)n_part_keys + a); + if (pc && RAY_IS_ERR(pc)) { ret = pc; goto batch_fail; } if (pc && pc->type == RAY_SYM && (pc->attrs & RAY_SYM_W_MASK) > w) w = pc->attrs & RAY_SYM_W_MASK; @@ -16906,7 +21459,10 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, out_attrs = w; } ray_t* flat = typed_vec_new(tref->type, out_attrs, mrows); - if (!flat || RAY_IS_ERR(flat)) goto batch_fail; + if (!flat || RAY_IS_ERR(flat)) { + if (flat) ray_error_free(flat); + goto batch_fail; + } /* SYM FIRST/LAST/MIN/MAX partials carry raw cell ids — same * single-dictionary contract as the key flats above. */ if (flat->type == RAY_SYM) @@ -16917,7 +21473,8 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, uint8_t src_nulls = 0; if (running) { - ray_t* rc = ray_table_get_col_idx(running, (int64_t)n_keys + a); + ray_t* rc = ray_table_col_idx(running, (int64_t)n_keys + a); + if (rc && RAY_IS_ERR(rc)) { ray_release(flat); ret = rc; goto batch_fail; } if (rc && rc->len > 0) { parted_copy_cells(out, flat->type, out_attrs, 0, rc, 0, rc->len); @@ -16927,8 +21484,9 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, } for (int32_t i = 0; i < batch_n; i++) { - ray_t* pc = ray_table_get_col_idx(bp[i], - (int64_t)n_part_keys + a); + ray_t* pc = ray_table_col_idx(bp[i], + (int64_t)n_part_keys + a); + if (pc && RAY_IS_ERR(pc)) { ray_release(flat); ret = pc; goto batch_fail; } if (pc && pc->len > 0) { parted_copy_cells(out, flat->type, out_attrs, off, pc, 0, pc->len); @@ -16939,8 +21497,9 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, /* Null propagation: propagate HAS_NULLS from copied sources. */ flat->attrs |= src_nulls; - merge_tbl = ray_table_add_col(merge_tbl, agg_name_ids[a], flat); + merge_tbl = ray_table_add_col(merge_tbl, mcol_names[n_keys + a], flat); ray_release(flat); + if (!merge_tbl || RAY_IS_ERR(merge_tbl)) goto merge_add_fail; } /* Free batch partials */ @@ -16953,14 +21512,11 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, ray_graph_t* mg = ray_graph_new(merge_tbl); if (!mg) goto batch_fail; - for (uint32_t k = 0; k < n_keys; k++) { - ray_t* sym_atom = ray_sym_str(key_syms[k]); - mkeys[k] = ray_scan(mg, ray_str_ptr(sym_atom)); - } - - for (uint32_t a = 0; a < part_n_aggs; a++) { - ray_t* agg_name = ray_sym_str(agg_name_ids[a]); - magg_ins[a] = ray_scan(mg, ray_str_ptr(agg_name)); + for (uint32_t c = 0; c < n_keys + part_n_aggs; c++) { + ray_t* nm_atom = ray_sym_str(mcol_names[c]); + ray_op_t* sc = ray_scan(mg, ray_str_ptr(nm_atom)); + if (c < n_keys) mkeys[c] = sc; + else magg_ins[c - n_keys] = sc; } ray_op_t* mroot = ray_group(mg, mkeys, n_keys, @@ -16984,6 +21540,11 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, continue; +merge_add_fail: + /* ray_table_add_col consumed merge_tbl and handed back an error + * (ray_release is a no-op on one) or NULL. */ + if (merge_tbl) ray_error_free(merge_tbl); + merge_tbl = NULL; batch_fail: for (int32_t i = 0; i < batch_n; i++) if (bp[i]) ray_release(bp[i]); @@ -17003,11 +21564,39 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, goto pp_cleanup; } + /* First-seen keys read up front: keep their groups, in that order. */ + if (frow_by_keys) { + ray_t* kept = grp_keep_first_keys(result, &fks); + if (!kept || RAY_IS_ERR(kept)) { + ray_release(result); + if (merge_tbl) ray_release(merge_tbl); + ret = kept; /* NULL: the concat fallback */ + goto pp_cleanup; + } + ray_release(result); + result = kept; + atomic_fetch_add_explicit(&ray_group_firstkeys_runs_ctr, 1, memory_order_relaxed); + } + + /* First-row slot: keep the group_limit groups with the smallest first + * row, ordered by it (first-seen order). */ + if (frow_sym >= 0) { + ray_t* kept = grp_keep_first_rows(result, (int64_t)n_keys + frow_slot, group_limit); + if (!kept || RAY_IS_ERR(kept)) { + ray_release(result); + if (merge_tbl) ray_release(merge_tbl); + ret = kept; + goto pp_cleanup; + } + ray_release(result); + result = kept; + } + int64_t rncols = ray_table_ncols(result); /* AVG/STDDEV post-processing: build trimmed table (n_keys + n_aggs cols), * computing final AVG = SUM/COUNT and STDDEV/VAR from SUM, SUM_SQ, COUNT. */ - if (has_avg || has_stddev) { + if (has_avg || has_stddev || frow_sym >= 0) { /* drops the decomposed and hidden slots */ ray_t* trimmed = ray_table_new((int64_t)(n_keys + n_aggs)); if (!trimmed || RAY_IS_ERR(trimmed)) { ray_release(result); @@ -17036,8 +21625,16 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, int64_t sum_ci = c; /* AVG COUNT slots: after n_aggs + n_std SUM_SQ slots */ int64_t cnt_ci = (int64_t)n_keys + n_aggs + n_std + avg_i; - ray_t* sum_col = ray_table_get_col_idx(result, sum_ci); - ray_t* cnt_col = (cnt_ci < rncols) ? ray_table_get_col_idx(result, cnt_ci) : NULL; + ray_t* sum_col = ray_table_col_idx(result, sum_ci); + ray_t* cnt_col = (cnt_ci < rncols) ? ray_table_col_idx(result, cnt_ci) : NULL; + ray_t* rd[2] = { sum_col, cnt_col }; + ray_t* rd_err = group_first_err(rd, 2); + if (rd_err) { + ray_release(trimmed); ray_release(result); + if (merge_tbl) ray_release(merge_tbl); + ret = rd_err; + goto pp_cleanup; + } if (!sum_col || !cnt_col) { if (sum_col) { ray_retain(sum_col); @@ -17057,19 +21654,20 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, avg_col->len = nrows; double* out = (double*)ray_data(avg_col); - if (sum_col->type == RAY_F64) { - const double* sv = (const double*)ray_data(sum_col); - const int64_t* cv = (const int64_t*)ray_data(cnt_col); - for (int64_t r = 0; r < nrows; r++) - out[r] = cv[r] > 0 ? ray_f64_fin(sv[r] / (double)cv[r]) : 0.0; - } else { - const int64_t* sv = (const int64_t*)ray_data(sum_col); - const int64_t* cv = (const int64_t*)ray_data(cnt_col); - for (int64_t r = 0; r < nrows; r++) - out[r] = cv[r] > 0 ? ray_f64_fin((double)sv[r] / (double)cv[r]) : 0.0; + const int64_t* cv = (const int64_t*)ray_data(cnt_col); + bool sum_f64 = sum_col->type == RAY_F64; + const double* svf = (const double*)ray_data(sum_col); + const int64_t* svi = (const int64_t*)ray_data(sum_col); + for (int64_t r = 0; r < nrows; r++) { + /* a group whose every input is null averages to null */ + if (cv[r] <= 0) { out[r] = NULL_F64; ray_vec_set_null(avg_col, r, true); continue; } + double sv = sum_f64 ? svf[r] : (double)svi[r]; + out[r] = ray_f64_fin(sv / (double)cv[r]); } /* Single-null float model: flip HAS_NULLS for any avg - * canonicalized to NULL_F64 (overflow). */ + * canonicalized to NULL_F64 (overflow), and for the avg + * of no rows -- a whole-table aggregate whose where: kept + * none -- which is null, as over a flat table (was 0.0). */ grp_finalize_nulls(avg_col); trimmed = ray_table_add_col(trimmed, nm, avg_col); ray_release(avg_col); @@ -17081,9 +21679,17 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, int64_t sum_ci = c; int64_t sq_ci = (int64_t)n_keys + std_sq_slot[std_i]; int64_t cnt_ci = (int64_t)n_keys + std_cnt_slot[std_i]; - ray_t* sum_col = ray_table_get_col_idx(result, sum_ci); - ray_t* sq_col = (sq_ci < rncols) ? ray_table_get_col_idx(result, sq_ci) : NULL; - ray_t* cnt_col = (cnt_ci < rncols) ? ray_table_get_col_idx(result, cnt_ci) : NULL; + ray_t* sum_col = ray_table_col_idx(result, sum_ci); + ray_t* sq_col = (sq_ci < rncols) ? ray_table_col_idx(result, sq_ci) : NULL; + ray_t* cnt_col = (cnt_ci < rncols) ? ray_table_col_idx(result, cnt_ci) : NULL; + ray_t* rd[3] = { sum_col, sq_col, cnt_col }; + ray_t* rd_err = group_first_err(rd, 3); + if (rd_err) { + ray_release(trimmed); ray_release(result); + if (merge_tbl) ray_release(merge_tbl); + ret = rd_err; + goto pp_cleanup; + } if (!sum_col || !sq_col || !cnt_col) { if (sum_col) { ray_retain(sum_col); @@ -17145,7 +21751,7 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, trimmed = ray_table_add_col(trimmed, nm, out_col); ray_release(out_col); } else { - ray_t* col = ray_table_get_col_idx(result, c); + ray_t* col = ray_table_slot_idx(result, c); /* passed on undecoded */ if (col) { ray_retain(col); trimmed = ray_table_add_col(trimmed, nm, col); @@ -17178,8 +21784,20 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, if (merge_tbl) ray_release(merge_tbl); ret = result; + if (agg_emit_filter_targets(&ef_trim, ext)) + ret = agg_emit_filter_trim(ret, n_keys, n_aggs, ext->agg_ops, &ef_trim); + if (ret && !RAY_IS_ERR(ret)) + atomic_fetch_add_explicit(&ray_group_perpart_done_ctr, 1, memory_order_relaxed); + /* Count the result served (O(1); see ray_group_perpart_runs_ctr). A bail + * above returns NULL and the caller answers from the concat path, which a + * route check must not mistake for this kernel. */ + if (ret && !RAY_IS_ERR(ret)) + atomic_fetch_add_explicit(&ray_group_perpart_runs_ctr, 1, memory_order_relaxed); pp_cleanup: + if (ef_saved.enabled) ray_group_emit_filter_set(ef_saved); + ray_free_raw(fks.keys); + ray_free_raw(fks.slot); scratch_free(mc_sym_ids_hdr); scratch_free(pk_syms_hdr); scratch_free(pkeys_hdr); @@ -17189,6 +21807,7 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, scratch_free(std_orig_op_hdr); scratch_free(std_sq_slot_hdr); scratch_free(std_cnt_slot_hdr); + scratch_free(cnt_nn_hdr); scratch_free(part_ops_hdr); scratch_free(merge_ops_hdr); scratch_free(part_agg_syms_hdr); @@ -17197,6 +21816,7 @@ exec_group_per_partition(ray_graph_t* g, ray_t* parted_tbl, ray_op_ext_t* ext, scratch_free(pagg_ins_hdr); scratch_free(magg_ins_hdr); scratch_free(unique_agg_hdr); + scratch_free(mcol_names_hdr); /* Pushed-down WHERE cleanup: free the flattened-ids block and offset/ * local-id scratch, and restore the caller's global selection (needed by * the concat fallback when this path returns NULL). */ diff --git a/src/ops/hll.c b/src/ops/hll.c index 5e24eb5d1..29c80acec 100644 --- a/src/ops/hll.c +++ b/src/ops/hll.c @@ -580,12 +580,11 @@ int ray_count_distinct_approx_pg_buf(ray_t* src, }; ray_pool_t* pool = ray_pool_get(); if (pool && ray_pool_total_workers(pool) >= 2 && n_groups >= 4) { - /* dispatch_n issues exactly n_groups tasks of [i, i+1), but the - * task ring is hard-capped at 65536 so n_groups > 65536 would - * silently drop trailing groups. For high-cardinality grouping - * use element-based dispatch — each worker gets a range of - * groups, processes them serially, and reuses its stack sketch - * across the range. */ + /* dispatch_n issues exactly n_groups tasks of [i, i+1): one + * sketch set-up per task, which is fine while groups are few. + * For high-cardinality grouping use element-based dispatch + * instead — each task gets a range of groups, processes them + * serially, and reuses its stack sketch across the range. */ if (n_groups <= 65536) { ray_pool_dispatch_n(pool, cda_pg_buf_task, &ctx, (uint32_t)n_groups); } else { diff --git a/src/ops/idiom.c b/src/ops/idiom.c index 508fc0053..a74f20c66 100644 --- a/src/ops/idiom.c +++ b/src/ops/idiom.c @@ -24,6 +24,7 @@ #include "vec/vec.h" #include "idiom.h" #include "opt.h" +#include "table/table.h" /* ray_table_col_meta */ #include "mem/heap.h" #include @@ -86,11 +87,13 @@ static ray_op_t* rw_count_passthrough(ray_graph_t* g, ray_op_t* node) { return repl; } -static ray_t* scan_source_col(ray_graph_t* g, ray_op_t* src) { - if (!g || !src || src->opcode != OP_SCAN) return NULL; +/* The table and column a scan reads, by metadata (no decode). */ +static bool scan_source_meta(ray_graph_t* g, ray_op_t* src, ray_t** tbl_out, + int64_t* sym_out, ray_col_meta_t* m) { + if (!g || !src || src->opcode != OP_SCAN) return false; ray_op_ext_t* ext = find_ext(g, src->id); - if (!ext) return NULL; + if (!ext) return false; uint16_t stored_table_id = 0; memcpy(&stored_table_id, src->pad, sizeof(uint16_t)); @@ -104,8 +107,10 @@ static ray_t* scan_source_col(ray_graph_t* g, ray_op_t* src) { tbl = g->table; } - if (!tbl) return NULL; - return ray_table_get_col(tbl, ext->sym); + if (!tbl || !ray_table_col_meta(tbl, ext->sym, m)) return false; + *tbl_out = tbl; + *sym_out = ext->sym; + return true; } /* True only when the input vector to (asc …) is statically known to @@ -131,10 +136,10 @@ static bool pre_no_nulls_on_asc_input(ray_graph_t* g, ray_op_t* node) { } if (src->opcode == OP_SCAN) { - ray_t* col = scan_source_col(g, src); - if (!col) return false; - if (!ray_is_vec(col) && !RAY_IS_PARTED(col->type)) return false; - return !ray_vec_has_nulls(col); + ray_t* st; int64_t ss; ray_col_meta_t sm; + if (!scan_source_meta(g, src, &st, &ss, &sm)) return false; + if (!ray_is_vector_type(sm.type) && !RAY_IS_PARTED(sm.type)) return false; + return !ray_table_col_has_nulls(st, ss); } return false; diff --git a/src/ops/idxop.c b/src/ops/idxop.c index 995c0c4a1..832e90f06 100644 --- a/src/ops/idxop.c +++ b/src/ops/idxop.c @@ -27,12 +27,17 @@ #include "mem/cow.h" #include "vec/vec.h" #include "table/table.h" +#include "store/enccol.h" #include "table/sym.h" #include "lang/eval.h" #include "ops/ops.h" #include "ops/rowsel.h" +#include "ops/colgather.h" /* ray_enc_hash_eq_rowsel: the probe's rows read back */ +#include "store/encidx.h" /* the HASH region layout */ #include "ops/hash.h" /* ray_hash_bytes: STR hash-index key word */ #include "core/pool.h" /* parallel hash-index build */ +#include "lang/format.h" /* ray_type_name */ +#include #include #include #include @@ -43,11 +48,100 @@ uint64_t ray_idx_consults[IDX_SITE__N]; uint64_t ray_idx_hits[IDX_SITE__N]; +#define IDX_USE_SLOTS 512 +static struct { const void* key; _Atomic uint64_t n; } g_idx_use[IDX_USE_SLOTS]; +static atomic_flag g_idx_use_lock = ATOMIC_FLAG_INIT; +/* Counting is off until `.idx.uses` has been called once in the process, so + * a server that never asks pays one relaxed load per index use. */ +static atomic_bool g_idx_use_armed; + +static void idx_use_add(const void* key) { + uint32_t h = (uint32_t)(((uintptr_t)key >> 5) * 2654435761u) & (IDX_USE_SLOTS - 1); + while (atomic_flag_test_and_set_explicit(&g_idx_use_lock, memory_order_acquire)) { } + for (uint32_t i = 0; i < IDX_USE_SLOTS; i++) { + uint32_t s = (h + i) & (IDX_USE_SLOTS - 1); + if (g_idx_use[s].key == key || g_idx_use[s].key == NULL) { + g_idx_use[s].key = key; + atomic_fetch_add_explicit(&g_idx_use[s].n, 1, memory_order_relaxed); + break; + } + } /* table full: drop the count */ + atomic_flag_clear_explicit(&g_idx_use_lock, memory_order_release); +} + +void ray_idx_note_use(const ray_t* col) { + if (!atomic_load_explicit(&g_idx_use_armed, memory_order_relaxed)) return; + if (!col || RAY_IS_ERR(col) || !(col->attrs & RAY_ATTR_HAS_INDEX) || !col->index) return; + idx_use_add(col->index); +} + +/* A directory answer counts under the encoded payload (it has no index + * block until materialized), as the lazy cache keys it: every header copy + * of the column reports the same uses. */ +void ray_idx_note_use_enc(const ray_t* encv) { + if (!atomic_load_explicit(&g_idx_use_armed, memory_order_relaxed)) return; + if (encv && !RAY_IS_ERR(encv) && encv->type == RAY_ENCCOL) { + const ray_enccol_t* e = ray_enccol_of((ray_t*)encv); + if (e) idx_use_add(e); + } +} + +static const void* lazy_use_key(const ray_t* col); /* the lazy hash cache, below */ + +ray_t* ray_idx_uses_fn(ray_t* tbl) { + if (!tbl || tbl->type != RAY_TABLE) + return ray_error("type", ".idx.uses expects a table, got %s", tbl ? ray_type_name(tbl->type) : "null"); + atomic_store_explicit(&g_idx_use_armed, true, memory_order_relaxed); + /* Under the lock only copy the live (key, count) pairs out and reset; + * matching columns and building the result allocate, so they run after. */ + struct { const void* key; uint64_t n; } snap[IDX_USE_SLOTS]; + uint32_t ns = 0; + while (atomic_flag_test_and_set_explicit(&g_idx_use_lock, memory_order_acquire)) { } + for (uint32_t s = 0; s < IDX_USE_SLOTS; s++) + if (g_idx_use[s].key && g_idx_use[s].n) { + snap[ns].key = g_idx_use[s].key; + snap[ns].n = g_idx_use[s].n; + ns++; + } + memset(g_idx_use, 0, sizeof g_idx_use); /* reset */ + atomic_flag_clear_explicit(&g_idx_use_lock, memory_order_release); + + int64_t nc = ray_table_ncols(tbl); + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, nc); + if (RAY_IS_ERR(keys)) return keys; + ray_t* vals = ray_vec_new(RAY_I64, nc); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + for (int64_t c = 0; c < nc; c++) { + /* Never decode: an encoded column has no attached index until it is + * materialized, and the materialization carries any index it built. */ + ray_t* enc = ray_table_get_col_enc_idx(tbl, c); + ray_t* col = enc ? ray_enccol_decoded_peek(enc) : ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) continue; + if (!col && !enc) continue; + /* A lazy in-memory hash counts under the column it was built for, + * a directory answer under the encoded object. */ + const void* own = (col && (col->attrs & RAY_ATTR_HAS_INDEX)) ? (const void*)col->index : NULL; + const void* lazy = lazy_use_key(enc ? enc : col); + const void* dir = enc ? (const void*)ray_enccol_of(enc) : NULL; /* ray_idx_note_use_enc */ + if (!own && !lazy && !dir) continue; + int64_t cnt = 0; + for (uint32_t s = 0; s < ns; s++) + if (snap[s].key == own || snap[s].key == lazy || snap[s].key == dir) cnt += (int64_t)snap[s].n; + if (cnt == 0) continue; + int64_t name = ray_table_col_name(tbl, c); + keys = ray_vec_append(keys, &name); + if (RAY_IS_ERR(keys)) { ray_release(vals); return ray_error("oom", NULL); } + vals = ray_vec_append(vals, &cnt); + if (RAY_IS_ERR(vals)) { ray_release(keys); return ray_error("oom", NULL); } + } + return ray_dict_new(keys, vals); +} + static void idx_stats_dump(void) { static const char* names[IDX_SITE__N] = { "filter-zone", "filter-bloom", "filter-hash", "filter-part", "filter-range", "in", "find", "sort", "distinct", "asof", - "filter-eq-range", "group-slice", + "filter-eq-range", "group-slice", "asof-ordered", }; for (int i = 0; i < IDX_SITE__N; i++) if (ray_idx_consults[i] || ray_idx_hits[i]) @@ -55,6 +149,15 @@ static void idx_stats_dump(void) { names[i], (unsigned long long)ray_idx_consults[i], (unsigned long long)ray_idx_hits[i]); + uint64_t zpc = 0, zps = 0; + ray_exec_test_zone_prune(&zpc, &zps); + if (zpc) + fprintf(stderr, "zone_prune chains=%llu vectors=%llu\n", (unsigned long long)zpc, (unsigned long long)zps); + ray_enc_counters_t k; + ray_enc_counters_get(&k); + if (k.decoded_bytes || k.materialized) + fprintf(stderr, "enc_decode decoded_bytes=%llu materialized=%llu\n", + (unsigned long long)k.decoded_bytes, (unsigned long long)k.materialized); } void ray_idx_stats_init(void) { @@ -67,7 +170,7 @@ static int numeric_elem_size(int8_t t) { case RAY_BOOL: case RAY_U8: return 1; case RAY_I16: return 2; case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_F32: return 4; - case RAY_I64: case RAY_TIMESTAMP: case RAY_F64: return 8; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: return 8; default: return 0; } } @@ -161,7 +264,7 @@ static bool vec_is_ascending(const ray_t* v) { for (int64_t i = 1; i < n; i++) if (p[i] < p[i-1]) return false; return true; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* p = (const int64_t*)b; for (int64_t i = 1; i < n; i++) if (p[i] < p[i-1]) return false; return true; @@ -184,12 +287,7 @@ static bool vec_is_ascending(const ray_t* v) { /* 64-bit avalanche mix (splittable hash from Stafford / xxhash). */ static inline uint64_t mix64(uint64_t x) { - x ^= x >> 30; - x *= 0xbf58476d1ce4e5b9ULL; - x ^= x >> 27; - x *= 0x94d049bb133111ebULL; - x ^= x >> 31; - return x; + return ray_index_mix64(x); } /* Smallest power of two >= n, clamped to >= 1. */ @@ -572,7 +670,7 @@ static ray_err_t zone_scan(ray_t* v, ray_index_t* ix) { case RAY_DATE: case RAY_TIME: return zone_scan_int(v, ix, 4); /* TIME is 4-byte int32 */ case RAY_I64: - case RAY_TIMESTAMP: return zone_scan_int(v, ix, 8); + case RAY_TIMESPAN: case RAY_TIMESTAMP: return zone_scan_int(v, ix, 8); case RAY_F32: return zone_scan_float(v, ix, 4); case RAY_F64: return zone_scan_float(v, ix, 8); default: return RAY_ERR_NYI; @@ -687,7 +785,7 @@ static ray_err_t chunk_zone_scan(ray_t* v, ray_index_t* ix) { case RAY_DATE: case RAY_TIME: return chunk_zone_scan_int(v, ix, 4); /* TIME is 4-byte int32 */ case RAY_I64: - case RAY_TIMESTAMP: return chunk_zone_scan_int(v, ix, 8); + case RAY_TIMESPAN: case RAY_TIMESTAMP: return chunk_zone_scan_int(v, ix, 8); case RAY_F32: return chunk_zone_scan_float(v, ix, 4); case RAY_F64: return chunk_zone_scan_float(v, ix, 8); default: return RAY_ERR_NYI; @@ -1156,6 +1254,51 @@ ray_t* ray_index_attach_built(ray_t** vp, ray_t* idx) { return attach_finalize(v, idx); } +ray_t* ray_index_new_root(ray_idx_kind_t kind, int8_t parent_type, int64_t parent_len) { + return ray_index_alloc(kind, parent_type, parent_len); +} + +/* The one admission predicate for a heap-built root (generation-2 + * materialization, the validator and the writer share the matrix). */ +ray_t* ray_index_attach_persisted(ray_t** vp, ray_t* root) { + if (!root || RAY_IS_ERR(root) || root->type != RAY_INDEX) { + if (root && !RAY_IS_ERR(root)) ray_release(root); + return ray_error("type", "attach_persisted: not an index object"); + } + ray_index_t* ix = ray_index_payload(root); + ray_t* v = vp ? *vp : NULL; + if (!v || RAY_IS_ERR(v) || !ray_is_vec(v) || + (v->attrs & (RAY_ATTR_SLICE | RAY_ATTR_HAS_INDEX))) { + ray_release(root); + return ray_error("type", "attach_persisted: needs a fresh plain vector"); + } + if (!ray_index_kind_admits((ray_idx_kind_t)ix->kind, v->type) || + ix->parent_type != v->type || ix->built_for_len != v->len) { + int k = ix->kind; + ray_release(root); + return ray_error("corrupt", "index kind %d is not admitted on type %s", k, ray_type_name(v->type)); + } + v = ray_cow(v); + if (!v || RAY_IS_ERR(v)) { ray_release(root); return v ? v : ray_error("oom", NULL); } + *vp = v; + return attach_finalize(v, root); +} + +static bool idx_numeric_parent(int8_t t) { + return t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_F32 || t == RAY_F64 || t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; +} + +bool ray_index_kind_admits(ray_idx_kind_t kind, int8_t t) { + if (idx_numeric_parent(t)) + return kind == RAY_IDX_NONE || kind == RAY_IDX_HASH || kind == RAY_IDX_SORT || + kind == RAY_IDX_BLOOM || kind == RAY_IDX_PART || kind == RAY_IDX_ZONE || + kind == RAY_IDX_CHUNK_ZONE; + if (t == RAY_SYM) return kind == RAY_IDX_NONE || kind == RAY_IDX_HASH || kind == RAY_IDX_PART; + if (t == RAY_STR) return kind == RAY_IDX_NONE || kind == RAY_IDX_HASH || kind == RAY_IDX_DICT; + return false; +} + ray_t* ray_index_attach_dict(ray_t** vp) { ray_t* v = prepare_attach_ex(vp, "dict", true, false); if (RAY_IS_ERR(v)) return v; @@ -1200,12 +1343,8 @@ static ray_err_t dict_acc_rehash(ray_dict_acc_t* a) { return RAY_OK; } -ray_err_t ray_dict_acc_add(ray_dict_acc_t* a, ray_t* v) { - if (a->dead) return RAY_OK; - if (!v || RAY_IS_ERR(v) || v->type != RAY_STR) return RAY_ERR_TYPE; - int64_t n = v->len; - if (n <= 0) return RAY_OK; - if (a->n_rows + n > INT32_MAX) { a->dead = true; ray_dict_acc_free(a); return RAY_OK; } +/* Codes capacity for n more rows (the growth rule of ray_dict_acc_add). */ +static ray_err_t dict_acc_reserve(ray_dict_acc_t* a, int64_t n) { if (a->n_rows + n > a->cap_rows) { int64_t cap = a->cap_rows ? a->cap_rows : 65536; while (cap < a->n_rows + n) cap *= 2; @@ -1213,59 +1352,93 @@ ray_err_t ray_dict_acc_add(ray_dict_acc_t* a, ray_t* v) { if (!p) return RAY_ERR_OOM; a->codes = p; a->cap_rows = cap; } - for (int64_t i = 0; i < n; i++) { - if (RAY_UNLIKELY((i & 4095) == 0 && ray_interrupted())) return RAY_ERR_CANCEL; - size_t len; const char* p = ray_str_vec_get(v, i, &len); - uint64_t h = ray_hash_bytes(p, len); - uint64_t s = h & a->mask; - int32_t code = -1; - for (;;) { - uint32_t cp1 = a->slot[s]; - if (cp1 == 0) break; - int32_t c = (int32_t)cp1 - 1; - if (a->lens[c] == len && (len == 0 || memcmp(a->pool + a->offs[c], p, len) == 0)) { code = c; break; } - s = (s + 1) & a->mask; + return RAY_OK; +} + +/* One row of the accumulator: the code of (p, len), appended on first + * sight. `row` is the column row (first_occ). RAY_OK, or OOM. */ +static inline ray_err_t dict_acc_put(ray_dict_acc_t* a, const char* p, size_t len, int64_t row) { + uint64_t h = ray_hash_bytes(p, len); + uint64_t s = h & a->mask; + int32_t code = -1; + for (;;) { + uint32_t cp1 = a->slot[s]; + if (cp1 == 0) break; + int32_t c = (int32_t)cp1 - 1; + if (a->lens[c] == len && (len == 0 || memcmp(a->pool + a->offs[c], p, len) == 0)) { code = c; break; } + s = (s + 1) & a->mask; + } + if (code < 0) { + if (a->n_distinct == a->cap_distinct) { + int64_t cap = a->cap_distinct ? a->cap_distinct * 2 : 1024; + int32_t* f = (int32_t*)ray_realloc_raw(a->first_occ, (size_t)cap * sizeof(int32_t)); + uint64_t* o = f ? (uint64_t*)ray_realloc_raw(a->offs, (size_t)cap * sizeof(uint64_t)) : NULL; + uint32_t* l = o ? (uint32_t*)ray_realloc_raw(a->lens, (size_t)cap * sizeof(uint32_t)) : NULL; + if (f) a->first_occ = f; + if (o) a->offs = o; + if (l) a->lens = l; + if (!f || !o || !l) return RAY_ERR_OOM; /* grown parts stay owned by a */ + a->cap_distinct = cap; } - if (code < 0) { - if (a->n_distinct == a->cap_distinct) { - int64_t cap = a->cap_distinct ? a->cap_distinct * 2 : 1024; - int32_t* f = (int32_t*)ray_realloc_raw(a->first_occ, (size_t)cap * sizeof(int32_t)); - uint64_t* o = f ? (uint64_t*)ray_realloc_raw(a->offs, (size_t)cap * sizeof(uint64_t)) : NULL; - uint32_t* l = o ? (uint32_t*)ray_realloc_raw(a->lens, (size_t)cap * sizeof(uint32_t)) : NULL; - if (f) a->first_occ = f; - if (o) a->offs = o; - if (l) a->lens = l; - if (!f || !o || !l) return RAY_ERR_OOM; /* grown parts stay owned by a */ - a->cap_distinct = cap; - } - if (len > 0) { - if (a->pool_len + len > a->pool_cap) { - uint64_t cap = a->pool_cap ? a->pool_cap * 2 : 65536; - while (cap < a->pool_len + len) cap *= 2; - char* np = (char*)ray_realloc_raw(a->pool, (size_t)cap); - if (!np) return RAY_ERR_OOM; - a->pool = np; a->pool_cap = cap; - } - memcpy(a->pool + a->pool_len, p, len); - } - code = (int32_t)a->n_distinct++; - a->offs[code] = a->pool_len; a->lens[code] = (uint32_t)len; - a->pool_len += len; - a->first_occ[code] = (int32_t)(a->n_rows + i); - a->slot[s] = (uint32_t)code + 1; - if ((uint64_t)a->n_distinct * 2 > a->mask + 1) { - ray_err_t err = dict_acc_rehash(a); - if (err != RAY_OK) return err; + if (len > 0) { + if (a->pool_len + len > a->pool_cap) { + uint64_t cap = a->pool_cap ? a->pool_cap * 2 : 65536; + while (cap < a->pool_len + len) cap *= 2; + char* np = (char*)ray_realloc_raw(a->pool, (size_t)cap); + if (!np) return RAY_ERR_OOM; + a->pool = np; a->pool_cap = cap; } + memcpy(a->pool + a->pool_len, p, len); } - a->codes[a->n_rows + i] = code; + code = (int32_t)a->n_distinct++; + a->offs[code] = a->pool_len; a->lens[code] = (uint32_t)len; + a->pool_len += len; + a->first_occ[code] = (int32_t)row; + a->slot[s] = (uint32_t)code + 1; + if ((uint64_t)a->n_distinct * 2 > a->mask + 1) { + ray_err_t err = dict_acc_rehash(a); + if (err != RAY_OK) return err; + } + } + a->codes[row] = code; + return RAY_OK; +} + +ray_err_t ray_dict_acc_add(ray_dict_acc_t* a, ray_t* v) { + if (a->dead) return RAY_OK; + if (!v || RAY_IS_ERR(v) || v->type != RAY_STR) return RAY_ERR_TYPE; + int64_t n = v->len; + if (n <= 0) return RAY_OK; + if (a->n_rows + n > INT32_MAX) { a->dead = true; ray_dict_acc_free(a); return RAY_OK; } + ray_err_t e = dict_acc_reserve(a, n); + if (e != RAY_OK) return e; + for (int64_t i = 0; i < n; i++) { + if (RAY_UNLIKELY((i & 4095) == 0 && ray_interrupted())) return RAY_ERR_CANCEL; + size_t len; const char* p = ray_str_vec_get(v, i, &len); + if ((e = dict_acc_put(a, p, len, a->n_rows + i)) != RAY_OK) return e; + } + a->n_rows += n; + return RAY_OK; +} + +ray_err_t ray_dict_acc_add_raw(ray_dict_acc_t* a, const ray_str_t* d, const char* pool, int64_t n) { + if (a->dead) return RAY_OK; + if (n <= 0) return RAY_OK; + if (a->n_rows + n > INT32_MAX) { a->dead = true; ray_dict_acc_free(a); return RAY_OK; } + ray_err_t e = dict_acc_reserve(a, n); + if (e != RAY_OK) return e; + for (int64_t i = 0; i < n; i++) { + if (RAY_UNLIKELY((i & 4095) == 0 && ray_interrupted())) return RAY_ERR_CANCEL; + const uint32_t len = d[i].len; + const char* p = len ? ray_str_t_ptr(&d[i], pool) : ""; + if ((e = dict_acc_put(a, p, len, a->n_rows + i)) != RAY_OK) return e; } a->n_rows += n; return RAY_OK; } ray_t* ray_dict_acc_finish(ray_dict_acc_t* a, int64_t len) { - if (a->dead || len < 65536 || a->n_rows != len) { ray_dict_acc_free(a); return NULL; } + if (a->dead || len < RAY_DICT_MIN_ROWS || a->n_rows != len) { ray_dict_acc_free(a); return NULL; } ray_t* codes = ray_vec_new(RAY_I32, len); ray_t* first_occ = ray_vec_new(RAY_I32, a->n_distinct > 0 ? a->n_distinct : 1); ray_t* idx = ray_index_alloc(RAY_IDX_DICT, RAY_STR, len); @@ -2484,6 +2657,74 @@ ray_t* ray_index_attach_hash(ray_t** vp) { return ray_error("cancel", "interrupted"); } + +typedef struct { int64_t first, g; } hx_first_t; +static int hx_first_cmp(const void* a, const void* b) { + int64_t x = ((const hx_first_t*)a)->first, y = ((const hx_first_t*)b)->first; + return x < y ? -1 : x > y; +} + +bool ray_index_hash_legacy(const ray_index_t* ix, ray_t** table, ray_t** gkeys, + ray_t** offs, ray_t** rows) { + *table = *gkeys = *offs = *rows = NULL; + if (!ix || ix->kind != RAY_IDX_HASH) return false; + const ray_t *t = ix->u.hash.table, *gk = ix->u.hash.gkeys, *of = ix->u.hash.offs, *rw = ix->u.hash.rows; + if (!t || RAY_IS_ERR(t) || !gk || RAY_IS_ERR(gk) || !of || RAY_IS_ERR(of) || !rw || RAY_IS_ERR(rw)) + return false; + int64_t ng = ix->u.hash.n_groups, nk = ix->u.hash.n_keys; + uint64_t mask = ix->u.hash.mask; + if (t->type == RAY_I64 && of->type == RAY_I64 && rw->type == RAY_I64 && + !(ix->markers & RAY_MARK_HASH_HIGH)) { + /* the generation-1 layout already: shared */ + ray_retain((ray_t*)t); ray_retain((ray_t*)gk); ray_retain((ray_t*)of); ray_retain((ray_t*)rw); + *table = (ray_t*)t; *gkeys = (ray_t*)gk; *offs = (ray_t*)of; *rows = (ray_t*)rw; + return true; + } + /* Renumber the groups by first occurrence (the generation-1 builders' + * numbering: a group's rows ascend, so its first row is rows[offs[g]]), + * then lay the slot table out in that order under the low-bits rule. */ + ray_t* ord_hdr = NULL; + hx_first_t* ord = (hx_first_t*)scratch_alloc(&ord_hdr, (size_t)(ng > 0 ? ng : 1) * sizeof(hx_first_t)); + ray_t* nt = ray_vec_new(RAY_I64, (int64_t)(mask + 1)); + ray_t* ngk = ray_vec_new(RAY_I64, ng > 0 ? ng : 1); + ray_t* nof = ray_vec_new(RAY_I64, ng + 1); + ray_t* nrw = ray_vec_new(RAY_I64, nk > 0 ? nk : 1); + bool ok = ord && nt && !RAY_IS_ERR(nt) && ngk && !RAY_IS_ERR(ngk) && + nof && !RAY_IS_ERR(nof) && nrw && !RAY_IS_ERR(nrw); + if (ok) { + const int64_t* g0 = (const int64_t*)ray_data((ray_t*)gk); + for (int64_t g = 0; g < ng; g++) { + int64_t o = hx_get(of, g); + ord[g].first = o < hx_get(of, g + 1) ? hx_get(rw, o) : INT64_MAX; + ord[g].g = g; + } + if (ng > 1) qsort(ord, (size_t)ng, sizeof *ord, hx_first_cmp); + int64_t* td = (int64_t*)ray_data(nt); + int64_t* gd = (int64_t*)ray_data(ngk); + int64_t* od = (int64_t*)ray_data(nof); + int64_t* rd = (int64_t*)ray_data(nrw); + memset(td, 0, (size_t)(mask + 1) * sizeof(int64_t)); + int64_t at = 0; + for (int64_t i = 0; i < ng; i++) { + int64_t g = ord[i].g; + gd[i] = g0[g]; + od[i] = at; + for (int64_t r = hx_get(of, g); r < hx_get(of, g + 1); r++) rd[at++] = hx_get(rw, r); + uint64_t sl = mix64((uint64_t)gd[i]) & mask; + while (td[sl] != 0) sl = (sl + 1) & mask; + td[sl] = i + 1; + } + od[ng] = at; + nt->len = (int64_t)(mask + 1); ngk->len = ng; nof->len = ng + 1; nrw->len = nk; + } + scratch_free(ord_hdr); + if (ok) { *table = nt; *gkeys = ngk; *offs = nof; *rows = nrw; return true; } + ray_t* v[4] = { nt, ngk, nof, nrw }; + for (int i = 0; i < 4; i++) + if (v[i]) { if (RAY_IS_ERR(v[i])) ray_error_free(v[i]); else ray_release(v[i]); } + return false; +} + ray_err_t ray_index_hash_build_region(ray_t* v, ray_index_region_fn map, void* ctx, ray_hash_trace_t* tr) { if (!v || RAY_IS_ERR(v) || !map) return RAY_ERR_DOMAIN; @@ -2545,7 +2786,7 @@ static int hash_key_in_range(int8_t t, int64_t k) { case RAY_I32: case RAY_DATE: case RAY_TIME: return k >= INT32_MIN && k <= INT32_MAX; case RAY_I64: - case RAY_TIMESTAMP: return 1; + case RAY_TIMESPAN: case RAY_TIMESTAMP: return 1; case RAY_SYM: return k >= 0; /* domain id; non-neg guaranteed by resolve */ default: return 0; } @@ -2560,7 +2801,7 @@ static int64_t hash_col_read_i64(const uint8_t* base, int8_t t, int64_t i) { case RAY_I32: case RAY_DATE: case RAY_TIME: es = 4; break; /* TIME is 4-byte int32 */ case RAY_I64: - case RAY_TIMESTAMP: es = 8; break; + case RAY_TIMESPAN: case RAY_TIMESTAMP: es = 8; break; default: return 0; } switch (es) { @@ -2696,24 +2937,8 @@ static bool idx_fresh_nonull(ray_t* col, ray_idx_kind_t kind) { * Zone-index all/none classification * -------------------------------------------------------------------------- */ -/* Classify (col cmp_op key) using the zone index min/max for O(1) decision. - * Integer family (BOOL/U8/I16/I32/I64/DATE/TIME/TIMESTAMP) uses key_i and - * the zone's min_i/max_i; float family (F32/F64) uses key_f and min_f/max_f. - * NaN key_f → UNKNOWN immediately (NaN comparison is the null-aware kernel's - * business). Returns UNKNOWN when not eligible (no zone, stale, null-bearing, - * or unsupported type). */ -ray_zone_class_t ray_index_zone_class(ray_t* col, uint16_t cmp_op, - int64_t key_i, double key_f) { - if (!idx_fresh_nonull(col, RAY_IDX_ZONE)) return RAY_ZONE_UNKNOWN; - ray_index_t* ix = ray_index_payload(col->index); - - /* Dispatch to integer or float path based on column type. */ - bool is_float = (col->type == RAY_F32 || col->type == RAY_F64); - bool is_int = !is_float && (numeric_elem_size(col->type) > 0); - if (!is_float && !is_int) return RAY_ZONE_UNKNOWN; - - if (is_float && isnan(key_f)) return RAY_ZONE_UNKNOWN; - +/* One zone decision text for ray_index_zone_class and its directory twin + * ray_enc_zone_class. */ #define ZONE_CLASSIFY(mn, mx, key) do { \ switch (cmp_op) { \ case OP_EQ: \ @@ -2743,14 +2968,72 @@ ray_zone_class_t ray_index_zone_class(ray_t* col, uint16_t cmp_op, } \ } while (0) +/* Classify (col cmp_op key) using the zone index min/max for O(1) decision. + * Integer family (BOOL/U8/I16/I32/I64/DATE/TIME/TIMESTAMP) uses key_i and + * the zone's min_i/max_i; float family (F32/F64) uses key_f and min_f/max_f. + * NaN key_f → UNKNOWN immediately (NaN comparison is the null-aware kernel's + * business). Returns UNKNOWN when not eligible (no zone, stale, null-bearing, + * or unsupported type). */ +ray_zone_class_t ray_index_zone_class(ray_t* col, uint16_t cmp_op, + int64_t key_i, double key_f) { + if (!idx_fresh_nonull(col, RAY_IDX_ZONE)) return RAY_ZONE_UNKNOWN; + ray_index_t* ix = ray_index_payload(col->index); + + /* Dispatch to integer or float path based on column type. */ + bool is_float = (col->type == RAY_F32 || col->type == RAY_F64); + bool is_int = !is_float && (numeric_elem_size(col->type) > 0); + if (!is_float && !is_int) return RAY_ZONE_UNKNOWN; + + if (is_float && isnan(key_f)) return RAY_ZONE_UNKNOWN; + if (is_int) { ZONE_CLASSIFY(ix->u.zone.min_i, ix->u.zone.max_i, key_i); } else { ZONE_CLASSIFY(ix->u.zone.min_f, ix->u.zone.max_f, key_f); } -#undef ZONE_CLASSIFY + return RAY_ZONE_UNKNOWN; +} +/* ---- Directory twins (P2) ---- + * A single-file generation-2 column is answered from its directory, unless + * the shape uses its recorded HASH, SORT, BLOOM or PART: then from the + * index its materialization attaches (exec.c, idx_enc_from_dir and the + * idx_enc_*_uses_index pairs). The materialization synthesizes a ZONE / CHUNK_ZONE + * from the directory (enc_synth_zone / enc_synth_chunk_zone, + * src/store/enccol.c); these answer what the synthesized zone would, from + * the same entries, without decoding. */ +static ray_enccol_t* enc_zone_col(ray_t* encv, uint8_t kind) { + if (!encv || RAY_IS_ERR(encv) || encv->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e = ray_enccol_of(encv); + if (!e || e->kind != RAY_ENCCOL_SINGLE || e->hdr.index_kind != kind) return NULL; + return e; +} +static double enc_dbl(int64_t b) { double d; memcpy(&d, &b, 8); return d; } + +ray_zone_class_t ray_enc_zone_class(ray_t* encv, uint16_t cmp_op, int64_t key_i, double key_f) { + ray_enccol_t* e = enc_zone_col(encv, RAY_IDX_ZONE); + if (!e || e->null_count != 0) return RAY_ZONE_UNKNOWN; /* idx_fresh_nonull */ + bool is_float = (e->type == RAY_F32 || e->type == RAY_F64); + bool is_int = !is_float && (numeric_elem_size(e->type) > 0); + if (!is_float && !is_int) return RAY_ZONE_UNKNOWN; + if (is_float && isnan(key_f)) return RAY_ZONE_UNKNOWN; + /* enc_synth_zone: the chunks with statistics, first of ties; 0/0 when none */ + bool have = false; + int64_t mn = 0, mx = 0; + for (int64_t c = 0; c < e->n_chunks; c++) { + ray_enc_chunk_stat_t st; ray_enccol_chunk_stat(e, c, &st); + if (!st.has_minmax) continue; + bool lt = is_float ? enc_dbl(st.min) < enc_dbl(mn) : st.min < mn; + bool gt = is_float ? enc_dbl(st.max) > enc_dbl(mx) : st.max > mx; + if (!have || lt) mn = st.min; + if (!have || gt) mx = st.max; + have = true; + } + if (is_int) { ZONE_CLASSIFY(mn, mx, key_i); } + else { double fmn = enc_dbl(mn), fmx = enc_dbl(mx); ZONE_CLASSIFY(fmn, fmx, key_f); } return RAY_ZONE_UNKNOWN; } +#undef ZONE_CLASSIFY + /* qsort comparator: ascending int64 row ids, used by the rowsel * builder to put matches into per-segment order. */ static int hash_match_cmp_i64(const void* a, const void* b) { @@ -2862,6 +3145,61 @@ ray_t* ray_index_hash_eq_rowsel(ray_t* col, int64_t key) { return rowsel_from_sorted_rows(n, hx_rows(ix->u.hash.rows, hx_get(ofv, gid)), gsz); } +static _Atomic(uint64_t) g_enc_hash_probes; /* test hook */ +uint64_t ray_enc_hash_test_probes(void) { return atomic_load_explicit(&g_enc_hash_probes, memory_order_relaxed); } + +static int64_t ehp_at(const uint8_t* b, int64_t off, int64_t i) { + int64_t x; + memcpy(&x, b + off + i * 8, 8); + return x; +} + +/* An equality on a single-file generation-2 column with a recorded HASH: + * the stored region is probed where it is mapped, as the builder laid it + * out (ray_enc_index_write), and the group's rows become the selection. The + * region is the file we wrote; it is read as written, not re-validated. */ +int ray_enc_hash_eq_rowsel(ray_t* encv, int64_t key, ray_t** sel, ray_t** err) { + *sel = NULL; *err = NULL; + ray_enccol_t* e = ray_enccol_of(encv); + if (!e || e->kind != RAY_ENCCOL_SINGLE || e->synthetic || e->hdr.index_kind != RAY_IDX_HASH) return 0; + const int8_t t = e->type; + const int64_t len = e->len; + if (!hash_key_in_range(t, key) || (t == RAY_SYM && key == 0)) return 0; + if (t != RAY_SYM && numeric_elem_size(t) == 0) return 0; + const uint8_t* b = e->base + e->hdr.index_off; + ray_enc_idx_hash_t h; + memcpy(&h, b + 16, sizeof h); /* the root's kind arguments */ + /* the builder's canonical key word and home slot (hash_probe_setup; + * a region holds the low-bits home rule, ray_enc_index_write) */ + const int64_t kw = t == RAY_SYM ? key : (int64_t)hash_key_bits(numeric_elem_size(t), key); + uint64_t slot = mix64((uint64_t)kw) & h.mask; + int64_t gid = -1; + for (;;) { + int64_t gp1 = ehp_at(b, h.table, (int64_t)slot); + if (gp1 == 0) break; + if (ehp_at(b, h.gkeys, gp1 - 1) == kw) { gid = gp1 - 1; break; } + slot = (slot + 1) & h.mask; + } + if (gid < 0) { + *sel = rowsel_from_sorted_ids(len, NULL, 0); + if (!*sel) { *err = ray_error("oom", NULL); return -1; } + atomic_fetch_add_explicit(&g_enc_hash_probes, 1, memory_order_relaxed); + return 1; + } + const int64_t o0 = ehp_at(b, h.offs, gid), o1 = ehp_at(b, h.offs, gid + 1); + const int64_t gsz = o1 - o0; + if (gsz > 64 && gsz > (len >> 3)) return 0; /* dense: the scan answers */ + ray_t* ids_hdr = NULL; + int64_t* ids = (int64_t*)scratch_alloc(&ids_hdr, (size_t)gsz * sizeof(int64_t)); + if (!ids) { *err = ray_error("oom", NULL); return -1; } + memcpy(ids, b + h.rows + o0 * 8, (size_t)gsz * 8); + *sel = rowsel_from_sorted_ids(len, ids, gsz); + scratch_free(ids_hdr); + if (!*sel) { *err = ray_error("oom", NULL); return -1; } + atomic_fetch_add_explicit(&g_enc_hash_probes, 1, memory_order_relaxed); + return 1; +} + /* -------------------------------------------------------------------------- * Hash/part-index IN probe * @@ -2878,7 +3216,7 @@ static int64_t set_vec_read_i64(const uint8_t* base, int8_t t, int64_t i) { case RAY_I16: { int16_t v; memcpy(&v, base + i*2, 2); return (int64_t)v; } case RAY_I32: case RAY_DATE: case RAY_TIME: { int32_t v; memcpy(&v, base + i*4, 4); return (int64_t)v; } - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t v; memcpy(&v, base + i*8, 8); return v; } default: return 0; } @@ -3933,6 +4271,25 @@ static ray_t* dict_append_sym_sym(ray_t** keys, ray_t** vals, const char* k, con return *vals; } +static ray_t* dict_append_sym_bool(ray_t** keys, ray_t** vals, const char* k, bool b) { + int64_t kid = ray_sym_intern(k, strlen(k)); + *keys = ray_vec_append(*keys, &kid); + if (RAY_IS_ERR(*keys)) return *keys; + ray_t* bv = ray_bool(b ? 1 : 0); + *vals = ray_list_append(*vals, bv); + ray_release(bv); + return *vals; +} + +/* Appends `nested` (borrowed) under k. */ +static ray_t* dict_append_sym_obj(ray_t** keys, ray_t** vals, const char* k, ray_t* nested) { + int64_t kid = ray_sym_intern(k, strlen(k)); + *keys = ray_vec_append(*keys, &kid); + if (RAY_IS_ERR(*keys)) return *keys; + *vals = ray_list_append(*vals, nested); + return *vals; +} + ray_t* ray_index_info(ray_t* v) { if (!ray_index_has(v)) return RAY_NULL_OBJ; ray_index_t* ix = ray_index_payload(v->index); @@ -4072,6 +4429,104 @@ ray_t* ray_idx_info_fn(ray_t* v) { return ray_index_info(v); } +static const char* const k_enc_names[10] = { + "raw", "const", "for_bp", "delta_bp", "rle", "dict", "alp", "alp_rd", "str_dict", "fsst" +}; + +/* (.idx.info col) | (.idx.info table 'col): the column's format. Reads + * metadata and chunk descriptors only; nothing is decoded. */ +ray_t* ray_idx_info_vary_fn(ray_t** args, int64_t n) { + if (n == 1) { + ray_t* v = args[0]; + if (v && ray_is_lazy(v)) { /* a lazy column arrives unforced */ + ray_t* m = ray_lazy_materialize(v); + if (!m || RAY_IS_ERR(m)) return m; + ray_t* r = ray_idx_info_fn(m); + ray_release(m); + return r; + } + return ray_idx_info_fn(v); + } + if (n != 2) return ray_error("arity", ".idx.info: expected (col) or (table 'col)"); + ray_t* tbl = args[0]; + ray_t* nm = args[1]; + if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE || !nm || nm->type != -RAY_SYM) + return ray_error("type", ".idx.info: expected a table and a column name symbol"); + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, nm->i64, &m)) return ray_error("domain", ".idx.info: no such column"); + + ray_enccol_info_t ci; + memset(&ci, 0, sizeof ci); + bool gen2 = false; + ray_t* slot = ray_table_slot(tbl, nm->i64); + if (m.enc) { + ray_t* err = ray_enccol_info(m.enc, &ci); + if (err) return err; + gen2 = !ci.synthetic; + } else if (RAY_IS_PARTED(m.type)) { + ray_t** seg = (ray_t**)ray_data(slot); + for (int64_t i = 0; i < slot->len; i++) ci.raw_bytes += ray_enccol_plain_bytes(seg[i]); + ci.encoded_bytes = ci.raw_bytes; + } else { + ci.raw_bytes = ci.encoded_bytes = ray_enccol_plain_bytes(slot); + } + + ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 8); + if (RAY_IS_ERR(keys)) return keys; + ray_t* vals = ray_list_new(8); + if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } + ray_t* r; + r = dict_append_sym_i64(&keys, &vals, "gen", gen2 ? 2 : 0); + if (RAY_IS_ERR(r)) goto fail; + + ray_t* ek = ray_sym_vec_new(RAY_SYM_W64, 10); + ray_t* ev = RAY_IS_ERR(ek) ? ek : ray_list_new(10); + if (RAY_IS_ERR(ek) || RAY_IS_ERR(ev)) { + r = RAY_IS_ERR(ek) ? ek : ev; + if (!RAY_IS_ERR(ek)) ray_release(ek); + goto fail; + } + if (gen2) { + for (int k = 0; k < 10; k++) { + if (!ci.vectors[k]) continue; + r = dict_append_sym_i64(&ek, &ev, k_enc_names[k], ci.vectors[k]); + if (RAY_IS_ERR(r)) { if (!RAY_IS_ERR(ek)) ray_release(ek); if (!RAY_IS_ERR(ev)) ray_release(ev); goto fail; } + } + } + ray_t* ed = ray_dict_new(ek, ev); + if (RAY_IS_ERR(ed)) { r = ed; goto fail; } + r = dict_append_sym_obj(&keys, &vals, "enc", ed); + ray_release(ed); + if (RAY_IS_ERR(r)) goto fail; + + r = dict_append_sym_i64(&keys, &vals, "encoded_bytes", (int64_t)ci.encoded_bytes); + if (RAY_IS_ERR(r)) goto fail; + r = dict_append_sym_i64(&keys, &vals, "raw_bytes", (int64_t)ci.raw_bytes); + if (RAY_IS_ERR(r)) goto fail; + r = dict_append_sym_bool(&keys, &vals, "materialized", ci.materialized); + if (RAY_IS_ERR(r)) goto fail; + + if (gen2) { + r = dict_append_sym_sym(&keys, &vals, "index", kind_name((ray_idx_kind_t)m.index_kind)); + } else { + ray_t* ix = ray_idx_info_fn(m.enc ? RAY_NULL_OBJ : slot); /* synthetic: no index */ + if (RAY_IS_ERR(ix)) { r = ix; goto fail; } + r = dict_append_sym_obj(&keys, &vals, "index", ix); + if (ix != RAY_NULL_OBJ) ray_release(ix); + } + if (RAY_IS_ERR(r)) goto fail; + if (m.n_segs) { + r = dict_append_sym_i64(&keys, &vals, "segments", m.n_segs); + if (RAY_IS_ERR(r)) goto fail; + } + return ray_dict_new(keys, vals); + +fail: + if (!RAY_IS_ERR(keys)) ray_release(keys); + if (!RAY_IS_ERR(vals)) ray_release(vals); + return r; +} + /* -------------------------------------------------------------------------- * Semantic attributes — (.attr.*) family. See docs spec * 2026-06-01-column-attributes-design.md. @@ -4392,7 +4847,7 @@ int ray_index_hash_group(ray_t* col, int64_t key, static bool int_atom_key(const ray_t* a, int64_t* k) { switch (a->type) { case -RAY_I64: - case -RAY_TIMESTAMP: *k = a->i64; return true; + case -RAY_TIMESPAN: case -RAY_TIMESTAMP: *k = a->i64; return true; case -RAY_I32: case -RAY_DATE: case -RAY_TIME: *k = (int64_t)a->i32; return true; @@ -4598,3 +5053,442 @@ void ray_index_carry_append(ray_t* src, ray_t* dst) { ix->markers = sx->markers; attach_finalize(dst, idx); } + +/* ---- Lazy in-memory HASH (index policy) ---------------------------------- + * + * See idxop.h. The cache is a small fixed table under a spin lock: probes + * are rare (one per point-lookup filter), so the lock is never contended in + * practice. Allocation, the build and every release run outside it. */ + +/* A fresh integer chunk zone's whole-column [min, max] over its non-empty + * chunks, or false (no such zone, or every chunk empty). *nc_eff: the + * non-empty chunks. */ +static bool chunk_zone_extrema(const ray_t* col, int64_t* gmin, int64_t* gmax, uint32_t* nc_eff) { + if (!col || RAY_IS_ERR(col) || !ray_is_vec(col) || (col->attrs & RAY_ATTR_SLICE)) return false; + if (numeric_elem_size(col->type) == 0 || col->type == RAY_F32 || col->type == RAY_F64) return false; + if (ray_index_kind(col) != RAY_IDX_CHUNK_ZONE) return false; + const ray_index_t* ix = ray_index_payload(col->index); + if (ix->built_for_len != col->len || ix->u.chunk_zone.is_f64) return false; + uint32_t nc = ix->u.chunk_zone.n_chunks; + if (nc == 0 || !ix->u.chunk_zone.mins || !ix->u.chunk_zone.maxs) return false; + const int64_t* mins = (const int64_t*)ray_data(ix->u.chunk_zone.mins); + const int64_t* maxs = (const int64_t*)ray_data(ix->u.chunk_zone.maxs); + int64_t lo = INT64_MAX, hi = INT64_MIN; + uint32_t n_eff = 0; + for (uint32_t g = 0; g < nc; g++) { + if (mins[g] > maxs[g]) continue; /* all-null chunk */ + if (mins[g] < lo) lo = mins[g]; + if (maxs[g] > hi) hi = maxs[g]; + n_eff++; + } + if (n_eff == 0) return false; + *gmin = lo; *gmax = hi; + if (nc_eff) *nc_eff = n_eff; + return true; +} + +bool ray_idx_zone_excludes(const ray_t* col, int64_t key) { + int64_t lo, hi; + return chunk_zone_extrema(col, &lo, &hi, NULL) && (key < lo || key > hi); +} + +bool ray_idx_zone_excludes_set(const ray_t* col, const ray_t* set) { + int64_t lo, hi; + if (!set || RAY_IS_ERR(set) || ray_is_atom(set)) return false; + if (numeric_elem_size(set->type) == 0 || set->type == RAY_F32 || set->type == RAY_F64) return false; + if (!chunk_zone_extrema(col, &lo, &hi, NULL)) return false; + const uint8_t* sb = (const uint8_t*)ray_data((ray_t*)set); + for (int64_t i = 0; i < set->len; i++) { + int64_t v = set_vec_read_i64(sb, set->type, i); + if (v >= lo && v <= hi) return false; + } + return true; +} + +bool ray_idx_lazy_hash_wanted(const ray_t* col) { + int64_t gmin, gmax; + uint32_t n_eff = 0; + if (!chunk_zone_extrema(col, &gmin, &gmax, &n_eff)) return false; + const ray_index_t* ix = ray_index_payload(col->index); + uint32_t nc = ix->u.chunk_zone.n_chunks; + if (nc < 4 || n_eff < 4) return false; + const int64_t* mins = (const int64_t*)ray_data(ix->u.chunk_zone.mins); + const int64_t* maxs = (const int64_t*)ray_data(ix->u.chunk_zone.maxs); + uint64_t range = (uint64_t)gmax - (uint64_t)gmin; /* full I64 width: wraps correctly */ + if (range == 0) return false; + double span_sum = 0.0; + for (uint32_t g = 0; g < nc; g++) { + if (mins[g] > maxs[g]) continue; + span_sum += (double)((uint64_t)maxs[g] - (uint64_t)mins[g]); + } + if ((span_sum / (double)n_eff) / (double)range <= 0.5) return false; + int esz = numeric_elem_size(col->type); + uint64_t cap = 8, want = 2u * (uint64_t)col->len; + while (cap < want) cap <<= 1; + return cap * 8u + (uint64_t)col->len * 8u <= 5u * (uint64_t)col->len * (uint64_t)esz; +} + +/* chunk_zone_extrema over the directory of a CHUNK_ZONE generation-2 + * column: a chunk without statistics is the synthesized zone's empty chunk + * (INT64_MAX / INT64_MIN), which chunk_zone_extrema skips. */ +static bool enc_chunk_zone_extrema(ray_t* encv, int64_t* gmin, int64_t* gmax, + uint32_t* nc_eff, uint32_t* nc_all) { + ray_enccol_t* e = enc_zone_col(encv, RAY_IDX_CHUNK_ZONE); + if (!e || numeric_elem_size(e->type) == 0 || e->type == RAY_F32 || e->type == RAY_F64) return false; + if (e->n_chunks == 0) return false; + int64_t lo = INT64_MAX, hi = INT64_MIN; + uint32_t n_eff = 0; + for (int64_t c = 0; c < e->n_chunks; c++) { + ray_enc_chunk_stat_t st; ray_enccol_chunk_stat(e, c, &st); + if (!st.has_minmax) continue; + if (st.min < lo) lo = st.min; + if (st.max > hi) hi = st.max; + n_eff++; + } + if (n_eff == 0) return false; + *gmin = lo; *gmax = hi; + if (nc_eff) *nc_eff = n_eff; + if (nc_all) *nc_all = (uint32_t)e->n_chunks; + return true; +} + +bool ray_enc_zone_excludes(ray_t* encv, int64_t key) { + int64_t lo, hi; + return enc_chunk_zone_extrema(encv, &lo, &hi, NULL, NULL) && (key < lo || key > hi); +} + +bool ray_enc_zone_excludes_set(ray_t* encv, const ray_t* set) { + int64_t lo, hi; + if (!set || RAY_IS_ERR(set) || ray_is_atom(set)) return false; + if (numeric_elem_size(set->type) == 0 || set->type == RAY_F32 || set->type == RAY_F64) return false; + if (!enc_chunk_zone_extrema(encv, &lo, &hi, NULL, NULL)) return false; + const uint8_t* sb = (const uint8_t*)ray_data((ray_t*)set); + for (int64_t i = 0; i < set->len; i++) { + int64_t v = set_vec_read_i64(sb, set->type, i); + if (v >= lo && v <= hi) return false; + } + return true; +} + +bool ray_enc_lazy_hash_wanted(ray_t* encv) { + int64_t gmin, gmax; + uint32_t n_eff = 0, nc = 0; + if (!enc_chunk_zone_extrema(encv, &gmin, &gmax, &n_eff, &nc)) return false; + ray_enccol_t* e = ray_enccol_of(encv); + if (nc < 4 || n_eff < 4) return false; + uint64_t range = (uint64_t)gmax - (uint64_t)gmin; /* full I64 width: wraps correctly */ + if (range == 0) return false; + double span_sum = 0.0; + for (int64_t c = 0; c < e->n_chunks; c++) { + ray_enc_chunk_stat_t st; ray_enccol_chunk_stat(e, c, &st); + if (!st.has_minmax) continue; + span_sum += (double)((uint64_t)st.max - (uint64_t)st.min); + } + if ((span_sum / (double)n_eff) / (double)range <= 0.5) return false; + int esz = numeric_elem_size(e->type); + uint64_t cap = 8, want = 2u * (uint64_t)e->len; + while (cap < want) cap <<= 1; + return cap * 8u + (uint64_t)e->len * 8u <= 5u * (uint64_t)e->len * (uint64_t)esz; +} + +#define LAZY_SLOTS 64 +#define LAZY_HASH_BYTES_PER_ROW 58 /* the converters' hash-build figure, per row */ +/* An entry is built (hcol set), pending (hcol NULL: a wanted column whose + * probes are still answered by the scan; work = rows those scans read), or + * declined (over budget, or its build failed: later probes do not retry). + * Only a built entry holds bytes. + * + * A generation-2 column probed before it is materialized is a memo keyed by + * its encoded payload (enc, not referenced: enccol_free drops it through + * ray_idx_lazy_forget_enc, so a memo never keeps a dropped table's mapping + * alive); its key is then only a non-NULL slot marker, never dereferenced + * or compared. A build materializes the column, and the built entry is + * keyed by that materialization, as any plain column's. */ +typedef struct { + const ray_t* key; ray_t* col; ray_t* hcol; + const ray_enccol_t* enc; + int64_t bytes; int64_t work; uint64_t tick; bool declined; +} lazy_ent_t; +static lazy_ent_t g_lazy[LAZY_SLOTS]; +static int64_t g_lazy_bytes; +static uint64_t g_lazy_tick; +static atomic_flag g_lazy_lock = ATOMIC_FLAG_INIT; +static _Atomic(int) g_lazy_fail; /* test hook: 1 = next build "oom", 2 = "cancel" */ + +void ray_idx_lazy_test_fail_build(const char* code) { + atomic_store(&g_lazy_fail, !code ? 0 : strcmp(code, "cancel") == 0 ? 2 : 1); +} + +static void lazy_lock(void) { while (atomic_flag_test_and_set_explicit(&g_lazy_lock, memory_order_acquire)) RAY_CPU_RELAX(); } +static void lazy_unlock(void) { atomic_flag_clear_explicit(&g_lazy_lock, memory_order_release); } + +/* References taken out of the table under the lock, released after it. */ +typedef struct { ray_t* objs[2 * LAZY_SLOTS + 2]; int n; } lazy_drop_t; +static void lazy_take(lazy_drop_t* d, int i) { + g_lazy_bytes -= g_lazy[i].bytes; + if (g_lazy[i].hcol) d->objs[d->n++] = g_lazy[i].hcol; + if (g_lazy[i].col) d->objs[d->n++] = g_lazy[i].col; + memset(&g_lazy[i], 0, sizeof g_lazy[i]); +} +static void lazy_drop(lazy_drop_t* d) { + for (int i = 0; i < d->n; i++) ray_release(d->objs[i]); + d->n = 0; +} +/* The published materialization of an encoded payload, or NULL. */ +static const ray_t* lazy_enc_decoded(const ray_enccol_t* e) { + if (atomic_load_explicit(&e->once.state, memory_order_acquire) != RAY_ENC_ONCE_DONE) return NULL; + return e->decoded; +} +/* The entry for col (a plain vector or a RAY_ENCCOL header): keyed by col, + * a memo of col's encoded payload, or (an encoded header whose column is + * published) keyed by its materialization; a plain col also meets the memo + * of the payload it materializes. So a column's probes meet one entry + * whatever its materialization state, and whichever header copy probes. */ +static int lazy_find(const ray_t* col) { + const ray_enccol_t* ce = NULL; + const ray_t* cdec = NULL; + if (col->type == RAY_ENCCOL) { + ce = ray_enccol_of((ray_t*)col); + if (ce) cdec = lazy_enc_decoded(ce); + } + for (int i = 0; i < LAZY_SLOTS; i++) { + if (!g_lazy[i].key) continue; + const ray_enccol_t* me = g_lazy[i].enc; + if (me) { + if (me == ce || (!ce && lazy_enc_decoded(me) == col)) return i; + continue; + } + if (g_lazy[i].key == col || (cdec && g_lazy[i].key == cdec)) return i; + } + return -1; +} +/* Entries whose column only the cache still holds: its table is gone (a + * reload, a dropped variable), so nothing can probe it again. Taken into d, + * which keeps a dead table's copy and its mapped files (a pruned store + * generation) from living on until budget pressure. */ +static void lazy_sweep_locked(lazy_drop_t* d) { + for (int i = 0; i < LAZY_SLOTS; i++) + if (g_lazy[i].col && ray_atomic_load(&g_lazy[i].col->rc) == 1) lazy_take(d, i); +} +/* A free slot, else the least recently used memo (pending or declined: + * cheap to lose), else the least recently used built entry, emptied into d. */ +static int lazy_slot(lazy_drop_t* d) { + lazy_sweep_locked(d); + int lru_memo = -1, lru_built = -1; + for (int i = 0; i < LAZY_SLOTS; i++) { + if (!g_lazy[i].key) return i; + int* lru = g_lazy[i].hcol ? &lru_built : &lru_memo; + if (*lru < 0 || g_lazy[i].tick < g_lazy[*lru].tick) *lru = i; + } + int v = lru_memo >= 0 ? lru_memo : lru_built; + lazy_take(d, v); + return v; +} + +/* The key's rows, element type, shape test and plain column. A + * generation-2 key (its RAY_ENCCOL) answers the first three from its header + * and directory; lazy_plain materializes it, and runs only when a build fires. */ +static int64_t lazy_len(const ray_t* key) { return key->type == RAY_ENCCOL ? ray_enccol_of((ray_t*)key)->len : key->len; } +static int8_t lazy_type(const ray_t* key) { return key->type == RAY_ENCCOL ? ray_enccol_of((ray_t*)key)->type : key->type; } +static bool lazy_wanted(ray_t* key) { return key->type == RAY_ENCCOL ? ray_enc_lazy_hash_wanted(key) : ray_idx_lazy_hash_wanted(key); } +static ray_t* lazy_plain(ray_t* key) { return key->type == RAY_ENCCOL ? ray_enccol_materialize(key) : key; } + +/* Record col without an index: pending (this probe's scan counted as its + * first work) or declined. An entry another probe made meanwhile stands. */ +static void lazy_memo(ray_t* col, bool declined) { + lazy_drop_t d = { .n = 0 }; + lazy_lock(); + int i = lazy_find(col); + if (i >= 0) { + if (declined && !g_lazy[i].hcol) g_lazy[i].declined = true; + } else { + int s = lazy_slot(&d); + bool enc = col->type == RAY_ENCCOL; /* a payload memo, unreferenced */ + if (!enc) ray_retain(col); + g_lazy[s] = (lazy_ent_t){ .key = col, .col = enc ? NULL : col, + .enc = enc ? ray_enccol_of(col) : NULL, + .work = declined ? 0 : lazy_len(col), + .tick = ++g_lazy_tick, .declined = declined }; + } + lazy_unlock(); + lazy_drop(&d); +} +static void lazy_decline(ray_t* col) { lazy_memo(col, true); } + +ray_t* ray_idx_lazy_lookup(const ray_t* col) { + lazy_lock(); + int i = col ? lazy_find(col) : -1; + ray_t* r = i >= 0 ? g_lazy[i].hcol : NULL; + if (r) ray_retain(r); /* taken under the lock */ + lazy_unlock(); + return r; +} + +int64_t ray_idx_lazy_work(const ray_t* col) { + lazy_lock(); + int i = col ? lazy_find(col) : -1; + int64_t w = i < 0 || g_lazy[i].declined ? -1 : g_lazy[i].hcol ? 0 : g_lazy[i].work; + lazy_unlock(); + return w; +} + +/* The index block of col's cached copy, as a .idx.uses key (compared, + * never dereferenced), or NULL. */ +static const void* lazy_use_key(const ray_t* col) { + lazy_lock(); + int i = col ? lazy_find(col) : -1; + const void* k = i >= 0 && g_lazy[i].hcol ? (const void*)g_lazy[i].hcol->index : NULL; + lazy_unlock(); + return k; +} + +static ray_t* lazy_hash_keyed(ray_t* key, ray_t** out) { + lazy_drop_t dead = { .n = 0 }; + lazy_lock(); + lazy_sweep_locked(&dead); + int hit = lazy_find(key); + if (hit >= 0) { + lazy_ent_t* e = &g_lazy[hit]; + e->tick = ++g_lazy_tick; + if (e->hcol) { + ray_retain(e->hcol); + *out = e->hcol; + lazy_unlock(); + lazy_drop(&dead); + return NULL; + } + /* Pending: the scan answers until the rows earlier probes scanned + * pay for the build (RAY_IDX_LAZY_BUILD_PROBES). */ + if (e->declined || e->work < (int64_t)(RAY_IDX_LAZY_BUILD_PROBES - 1) * lazy_len(key)) { + if (!e->declined) e->work += lazy_len(key); /* this probe scans */ + lazy_unlock(); + lazy_drop(&dead); + return NULL; + } + lazy_unlock(); /* repeated enough: build now */ + lazy_drop(&dead); + } else { + lazy_unlock(); + lazy_drop(&dead); + /* The shape is decided from the zone's chunk extrema (O(chunks), + * nothing built), so a column it rejects is simply asked again. */ + if (!lazy_wanted(key)) return NULL; + } + int64_t budget = ray_sys_ram_limit() / 4; + if (budget <= 0) return NULL; /* no runtime: no budget, no cache */ + int64_t bytes = lazy_len(key) * (int64_t)(numeric_elem_size(lazy_type(key)) + LAZY_HASH_BYTES_PER_ROW); + if (bytes > budget) { lazy_decline(key); return NULL; } + if (hit < 0) { lazy_memo(key, false); return NULL; } /* first probe: the scan answers */ + ray_t* plain = lazy_plain(key); /* generation 2: the one materialization */ + if (!plain || RAY_IS_ERR(plain)) { + if (!plain) { lazy_decline(key); return ray_error("oom", "lazy hash"); } + if (strcmp(ray_err_code(plain), "cancel") != 0) lazy_decline(key); + return plain; + } + int fail = atomic_exchange(&g_lazy_fail, 0); + ray_t* h = fail == 2 ? ray_error("cancel", "interrupted") + : fail == 1 ? ray_error("oom", "lazy hash") + : attach_via(plain, ray_index_attach_hash); /* copy-on-write: plain is never modified */ + if (!h) { lazy_decline(key); return ray_error("oom", "lazy hash"); } + if (RAY_IS_ERR(h)) { + /* an interrupted build is the query's cancellation, not the column's */ + if (strcmp(ray_err_code(h), "cancel") != 0) lazy_decline(key); + return h; + } + if (ray_index_kind(h) != RAY_IDX_HASH) { ray_release(h); lazy_decline(key); return NULL; } + + lazy_drop_t d = { .n = 0 }; + lazy_lock(); + int i = lazy_find(key); + if (i >= 0 && g_lazy[i].hcol) { + /* Another probe built and published it first: use that one. */ + g_lazy[i].tick = ++g_lazy_tick; + ray_retain(g_lazy[i].hcol); + *out = g_lazy[i].hcol; + lazy_unlock(); + ray_release(h); + return NULL; + } + if (i >= 0) lazy_take(&d, i); /* its pending (or declined) memo */ + lazy_sweep_locked(&d); /* dead entries go before live ones */ + while (g_lazy_bytes + bytes > budget) { /* least recently used first */ + int lru = -1; + for (int k = 0; k < LAZY_SLOTS; k++) + if (g_lazy[k].hcol && (lru < 0 || g_lazy[k].tick < g_lazy[lru].tick)) lru = k; + if (lru < 0) break; + lazy_take(&d, lru); + } + int s = lazy_slot(&d); + ray_retain(plain); /* generation 2: keyed by its materialization */ + g_lazy[s] = (lazy_ent_t){ .key = plain, .col = plain, .hcol = h, .bytes = bytes, .tick = ++g_lazy_tick }; + g_lazy_bytes += bytes; + ray_retain(h); + *out = h; + lazy_unlock(); + lazy_drop(&d); + return NULL; +} + +ray_t* ray_idx_lazy_hash(ray_t* col, ray_t** out) { + *out = NULL; + if (!col || RAY_IS_ERR(col) || !ray_is_vec(col)) return NULL; + return lazy_hash_keyed(col, out); +} + +ray_t* ray_idx_lazy_hash_enc(ray_t* encv, ray_t** out) { + *out = NULL; + if (!encv || RAY_IS_ERR(encv) || encv->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e = ray_enccol_of(encv); + if (!e || e->kind != RAY_ENCCOL_SINGLE) return NULL; + return lazy_hash_keyed(encv, out); +} + +void ray_idx_lazy_forget(const ray_t* col) { + if (!col) return; + lazy_drop_t d = { .n = 0 }; + lazy_lock(); + int i = lazy_find(col); + if (i >= 0) lazy_take(&d, i); + lazy_unlock(); + lazy_drop(&d); +} + +void ray_idx_lazy_forget_enc(const ray_enccol_t* e) { + if (!e) return; + lazy_drop_t d = { .n = 0 }; + lazy_lock(); + for (int i = 0; i < LAZY_SLOTS; i++) if (g_lazy[i].enc == e) lazy_take(&d, i); + lazy_unlock(); + lazy_drop(&d); +} + +void ray_idx_lazy_clear(void) { + lazy_drop_t d = { .n = 0 }; + lazy_lock(); + for (int i = 0; i < LAZY_SLOTS; i++) if (g_lazy[i].key) lazy_take(&d, i); + lazy_unlock(); + lazy_drop(&d); +} + +int64_t ray_idx_lazy_count(void) { + int64_t n = 0; + lazy_lock(); + for (int i = 0; i < LAZY_SLOTS; i++) n += g_lazy[i].hcol != NULL; /* built entries */ + lazy_unlock(); + return n; +} + +int64_t ray_idx_lazy_entries(void) { + int64_t n = 0; + lazy_lock(); + for (int i = 0; i < LAZY_SLOTS; i++) n += g_lazy[i].key != NULL; + lazy_unlock(); + return n; +} + +int64_t ray_idx_lazy_bytes(void) { + lazy_lock(); + int64_t b = g_lazy_bytes; + lazy_unlock(); + return b; +} diff --git a/src/ops/idxop.h b/src/ops/idxop.h index 2244bf893..aa0181733 100644 --- a/src/ops/idxop.h +++ b/src/ops/idxop.h @@ -48,6 +48,7 @@ #include /* FILE: ray_index_inline_write_file */ #include #include "mem/heap.h" /* RAY_ATTR_HAS_INDEX */ +#include "vec/str.h" /* ray_str_t: ray_dict_acc_add_raw */ /* Maximum key columns a RAY_IDX_UKEY map covers. Chosen so the arm fits * the existing union (see the static assert below); a wider key simply gets @@ -253,18 +254,118 @@ static inline ray_index_t* ray_index_payload(ray_t* idx) { return (ray_index_t*)idx->data; } +/* The 64-bit mix every hash index uses (builder, probes, and the + * generation-2 validator). */ +static inline uint64_t ray_index_mix64(uint64_t x) { + x ^= x >> 30; x *= 0xbf58476d1ce4e5b9ULL; + x ^= x >> 27; x *= 0x94d049bb133111ebULL; + x ^= x >> 31; return x; +} + /* ── Routing observability: per-site consult/hit counters ── * Diagnostic, unsynchronized (same caveat as ray_expr_bail_counts). */ typedef enum { IDX_SITE_FILTER_ZONE = 0, IDX_SITE_FILTER_BLOOM, IDX_SITE_FILTER_HASH, IDX_SITE_FILTER_PART, IDX_SITE_FILTER_RANGE, IDX_SITE_IN, IDX_SITE_FIND, IDX_SITE_SORT, IDX_SITE_DISTINCT, IDX_SITE_ASOF, - IDX_SITE_FILTER_EQRANGE, IDX_SITE_GROUP_SLICE, IDX_SITE__N + IDX_SITE_FILTER_EQRANGE, IDX_SITE_GROUP_SLICE, IDX_SITE_ASOF_ORDERED, IDX_SITE__N } idx_site_t; extern uint64_t ray_idx_consults[IDX_SITE__N]; extern uint64_t ray_idx_hits[IDX_SITE__N]; void ray_idx_stats_init(void); /* atexit dump when RAY_IDX_STATS set */ +/* Per-index use attribution (diagnostic, for the index policy + * measurement). Counts one use of col->index; read and reset through the + * `.idx.uses` builtin. No-op for vectors without an index. */ +void ray_idx_note_use(const ray_t* col); +/* A consult answered from encv's directory (zone class or exclusion): counts + * under the RAY_ENCCOL object itself. */ +void ray_idx_note_use_enc(const ray_t* encv); +ray_t* ray_idx_uses_fn(ray_t* tbl); + +/* ===== Lazy in-memory HASH (index policy) ===== + * + * The converters persist a CHUNK_ZONE, not a HASH. Point lookups (equality + * or `in` filters) on an 8-byte integer or timestamp column whose zone cannot + * prune (the cost test admits no narrower type) build a HASH in memory once + * they have been repeated enough, and reuse it in the same process. + * The index lives in a process-wide cache keyed by the plain column object + * (generation 0: the table's column; generation 2: the encoded object's + * materialization), never in a table slot and never attached to the column, + * so no save can see it. An entry holds one reference to the column and an + * indexed heap copy (ray_idx_hash_fn, copy-on-write); an entry whose column + * only the cache still holds is dropped on the next probe. The bytes held stay + * within a quarter of ray_sys_ram_limit(); least recently used entries are + * evicted to make room. A column the budget or a failed build declines is + * remembered, so later probes do not retry it. + * + * The build waits for proven repetition: the scan answers a wanted column's + * probes, and the rows they read are counted in a pending entry, until that + * scan work pays for one build. Measured on 10M unclustered I64 rows (8 + * cores, release, page cache warm): the parallel in-memory build, column copy + * included, takes 615 ms (about 61 ns/row); the equality scan it replaces + * reads the mapped column in 1.9 ms (about 0.19 ns/row). 61 / 0.19 rounds + * to 320 full-column probes: the 320th probe builds, the first 319 scan. + * A cold scan costs more and pays sooner, so the warm ratio is the safe one. + * + * Threads: the cache takes its own lock, but its entries share column + * objects with the caller's tables, so a caller outside the pool's workers + * that probes while another thread uses the same objects must run with + * ray_rc_sync set (atomic reference counts), as for any shared object. */ +#define RAY_IDX_LAZY_BUILD_PROBES 320 + +/* The random-shape test the converters used: a fresh, integer CHUNK_ZONE of + * at least 4 non-empty chunks whose mean chunk span exceeds half the global + * range, and an index costing at most 5x the column's payload. */ +bool ray_idx_lazy_hash_wanted(const ray_t* col); +/* True when col's fresh integer chunk zone proves that no row equals key + * (key outside its whole-column [min, max]), or, for _set, no row equals any + * element of the integer vector set. The caller has ruled out nulls. */ +bool ray_idx_zone_excludes(const ray_t* col, int64_t key); +bool ray_idx_zone_excludes_set(const ray_t* col, const ray_t* set); +/* Directory twins for a single-file generation-2 column (encv a + * RAY_ENCCOL): the answer the zone its materialization would synthesize + * (enc_synth_zone / enc_synth_chunk_zone, src/store/enccol.c) gives, + * from the same directory entries, never decoding. UNKNOWN / false for a + * parted column, another recorded kind, or a type the zone does not cover. */ +bool ray_enc_zone_excludes(ray_t* encv, int64_t key); +bool ray_enc_zone_excludes_set(ray_t* encv, const ray_t* set); +bool ray_enc_lazy_hash_wanted(ray_t* encv); +/* For a probe on `col`: NULL with *out = a retained vector equal to col + * carrying a HASH (from the cache, or built now), or NULL with *out = NULL + * when no lazy index applies (not wanted, over budget, declined before, or + * still pending: the caller scans and this probe's work is counted); an + * owned error on failure to build (the caller falls back to its scan). */ +ray_t* ray_idx_lazy_hash(ray_t* col, ray_t** out); +/* ray_idx_lazy_hash for a single-file generation-2 column (encv its + * RAY_ENCCOL): the probes are counted on the encoded payload (any header + * copy), and the column is materialized only when the build fires; the + * built entry is keyed by that materialization, and *out is its indexed + * copy. ray_idx_lazy_hash / _lookup / _work on the published + * materialization meet the same entry. */ +ray_t* ray_idx_lazy_hash_enc(ray_t* encv, ray_t** out); +/* The cached indexed copy for col, retained (the caller releases it), or NULL. */ +ray_t* ray_idx_lazy_lookup(const ray_t* col); +/* Drop the entry of a column object that is going away (the generation-2 + * object frees its materialization). */ +void ray_idx_lazy_forget(const ray_t* col); +/* An encoded column's payload is freed: its memo (a probe count kept + * before the column was materialized) goes with it. */ +struct ray_enccol_s; +void ray_idx_lazy_forget_enc(const struct ray_enccol_s* e); +/* Tests: rows the scans of col's pending probes read (0 once built), or -1 + * when col has no entry or was declined. */ +int64_t ray_idx_lazy_work(const ray_t* col); +/* Test hook: the next lazy build fails with `code` ("oom" or "cancel"); + * NULL disarms. */ +void ray_idx_lazy_test_fail_build(const char* code); +/* Tests and runtime teardown: drop every entry; indexed entry count; every + * entry (built, pending, declined); bytes held. */ +void ray_idx_lazy_clear(void); +int64_t ray_idx_lazy_count(void); +int64_t ray_idx_lazy_entries(void); +int64_t ray_idx_lazy_bytes(void); + /* ===== Attach / Detach ===== */ /* Build an accelerator and attach. Numeric types are supported by every @@ -352,6 +453,27 @@ bool ray_zone_int_sum(ray_t* x, int64_t* sum_out, int64_t* nn_out); * metadata: true when the per-chunk high words are stored, or when no * partial sum can wrap int64 (then the wrapped sum is the exact one). */ bool ray_zone_int_sum128(ray_t* x, int64_t* hi_out, uint64_t* lo_out, int64_t* nn_out); +/* OP_SUM / OP_AVG / OP_MIN / OP_MAX of a single-file generation-2 column + * whose recorded index is CHUNK_ZONE, answered as ray_sum_fn / ray_avg_fn / + * ray_min_fn / ray_max_fn answer the generation-0 column from its + * CHUNK_ZONE (the zone the materialization would synthesize), from the + * directory; NULL when that zone path would not answer. */ +ray_t* ray_zone_dir_answer(ray_t* encv, uint16_t opcode); +/* ray_zone_int_sum128's twin for the same columns: the exact 128-bit sum + * and non-null count from the directory; false when the zone the + * materialization would synthesize carries no integer sums. */ +bool ray_zone_dir_int_sum128(ray_t* encv, int64_t* hi, uint64_t* lo, int64_t* nn); +/* ray_zone_dir_answer's answer for every single-file stored generation-2 + * column, with or without a recorded zone: the execution-time reduction + * (ray_reduce_src) takes it. Planning-time answers stay on + * ray_zone_dir_answer, so they do not widen past generation 0's. */ +ray_t* ray_dir_answer(ray_t* encv, uint16_t opcode); +/* The directory totals (a ray_enc_col_totals_t, store/enccol.h) of one + * parted segment for an integer or temporal SUM / AVG / MIN / MAX: true + * when the segment is a single-file stored generation-2 column the + * directory answers `opcode` for, false for a plain, synthetic or float + * segment (the caller reduces its rows). */ +bool ray_dir_seg_totals(ray_t* segv, uint16_t opcode, void* totals_out); /* Build a RAY_IDX_DICT (codes + distinct values) for STR vector `v` WITHOUT * attaching it — standalone RAY_INDEX object (caller releases / attaches). @@ -362,7 +484,7 @@ ray_t* ray_index_attach_dict(ray_t** vp); /* ===== Incremental STR dictionary ===== */ -typedef struct { +typedef struct ray_dict_acc_s { int32_t* codes; int64_t n_rows; int64_t cap_rows; int32_t* first_occ; int64_t n_distinct; int64_t cap_distinct; uint64_t* offs; /* per distinct: byte offset into pool */ @@ -378,13 +500,33 @@ ray_err_t ray_dict_acc_init(ray_dict_acc_t* a); * sets dead and returns RAY_OK; further adds are no-ops. A non-OK return * (OOM, CANCEL) leaves the accumulator partial: free/discard it. */ ray_err_t ray_dict_acc_add(ray_dict_acc_t* a, ray_t* v); +/* Appends n raw STR descriptors whose pooled bytes are relative to `pool` + * (ray_str_t_ptr): the same codes ray_dict_acc_add assigns to the same + * strings, with the same dead / error rules. */ +ray_err_t ray_dict_acc_add_raw(ray_dict_acc_t* a, const ray_str_t* d, const char* pool, int64_t n); +/* The fewest rows a saved generation-0 STR column carries its DICT index at. */ +#define RAY_DICT_MIN_ROWS 65536 /* The standalone RAY_IDX_DICT for a column of `len` rows, identical to - * ray_index_dict_compute; NULL when dead or len < 65536. Frees `a`. */ + * ray_index_dict_compute; NULL when dead or len < RAY_DICT_MIN_ROWS. Frees `a`. */ ray_t* ray_dict_acc_finish(ray_dict_acc_t* a, int64_t len); void ray_dict_acc_free(ray_dict_acc_t* a); /* Attach an already-built standalone RAY_INDEX object (zero-copy on rc=1). */ ray_t* ray_index_attach_built(ray_t** vp, ray_t* idx); +/* Attach a heap-built root to a fresh plain vector. Consumes `root` on + * success and on error; refuses (corrupt) a pair the matrix does not + * admit, a root whose parent_type or built_for_len disagree, a slice, or + * a vector already indexed. */ +ray_t* ray_index_attach_persisted(ray_t** vp, ray_t* root); +/* A zeroed RAY_INDEX block of `kind` for a parent (public wrapper of the + * allocator used by every builder). */ +ray_t* ray_index_new_root(ray_idx_kind_t kind, int8_t parent_type, int64_t parent_len); +/* Spec "Materialization" step 3 admission matrix: + * numeric and temporal types carry HASH, SORT, BLOOM, PART, ZONE, + * CHUNK_ZONE and a marker-only root; SYM carries HASH, PART and a + * marker-only root; STR carries HASH, DICT (persisted for generation 2 + * since P6b) and a marker-only root; GUID carries nothing. */ +bool ray_index_kind_admits(ray_idx_kind_t kind, int8_t parent_type); /* ── Inline on-disk index region (zero-copy mmap) ── * ray_index_inline_size: bytes the region occupies (32-aligned ray_t blocks). @@ -434,6 +576,15 @@ void ray_hash_trace_print(FILE* f, const char* what, const ray_hash_trace_t* t, * did: the mapped memory, if any, holds no complete region. `tr` (may be * NULL) collects the phases. */ typedef uint8_t* (*ray_index_region_fn)(void* ctx, int64_t bytes); +/* The arrays of HASH payload `ix` in the generation-1 layout a + * generation-2 index region stores: every array I64, the groups numbered by + * first occurrence (row order of their first rows), each group in the first + * free slot from mix64(key) & mask (the low-bits home rule): the bytes the + * generation-1 builders made. Shared (retained) when ix is that layout + * already; fresh otherwise. False on OOM (outputs NULL). */ +bool ray_index_hash_legacy(const ray_index_t* ix, ray_t** table, ray_t** gkeys, + ray_t** offs, ray_t** rows); + ray_err_t ray_index_hash_build_region(ray_t* v, ray_index_region_fn map, void* ctx, ray_hash_trace_t* tr); @@ -502,6 +653,10 @@ ray_t* ray_index_info(ray_t* v); typedef enum { RAY_ZONE_UNKNOWN = 0, RAY_ZONE_ALL = 1, RAY_ZONE_NONE = 2 } ray_zone_class_t; ray_zone_class_t ray_index_zone_class(ray_t* col, uint16_t cmp_op, int64_t key_i, double key_f); +/* Its directory twin for a generation-2 column recording ZONE (see + * ray_enc_zone_excludes): UNKNOWN unless encv is a single-file RAY_ENCCOL + * without nulls. */ +ray_zone_class_t ray_enc_zone_class(ray_t* encv, uint16_t cmp_op, int64_t key_i, double key_f); /* Build an all-NONE rowsel of `n` rows. Wraps rowsel_from_sorted_ids(n, NULL, 0). * Returns NULL on OOM; returns a valid zero-match rowsel on success. */ @@ -545,6 +700,20 @@ bool ray_index_bloom_absent(ray_t* col, int64_t key); * Floats are intentionally not supported — equality on F32/F64 * has NaN / -0 semantics the unfused compare kernel handles. */ ray_t* ray_index_hash_eq_rowsel(ray_t* col, int64_t key); +/* ray_index_hash_eq_rowsel for a single-file generation-2 column whose + * recorded HASH region is probed where it is mapped, without materializing + * the column or copying the region: the root's layout is checked against + * the region, every slot, group and offset the probe reads is bounded, and + * the group's rows are checked ascending, inside the column, and holding + * `key` (read back by range: a region that disagrees with the column is + * `corrupt`, naming it). `key` as for ray_index_hash_eq_rowsel (a SYM key + * a nonzero domain id). 1: *sel the selection (an empty one for an absent + * key); 0 declined (no such region, a key or type it does not cover, or a + * group dense enough for the scan, as ray_index_hash_eq_rowsel declines); + * -1: *err owned. */ +int ray_enc_hash_eq_rowsel(ray_t* encv, int64_t key, ray_t** sel, ray_t** err); +/* Test hook: probes ray_enc_hash_eq_rowsel answered since process start. */ +uint64_t ray_enc_hash_test_probes(void); /* Direct equality selection for a fresh part index. `key` is a numeric * value or a column-domain SYM id. Dense matches remain eligible because @@ -761,6 +930,7 @@ ray_t* ray_idx_bloom_fn(ray_t* v); /* (.idx.bloom v) -> v with bloom attached * ray_t* ray_idx_drop_fn (ray_t* v); /* (.idx.drop v) -> v with index removed */ ray_t* ray_idx_has_fn (ray_t* v); /* (.idx.has? v) -> 0b/1b */ ray_t* ray_idx_info_fn (ray_t* v); /* (.idx.info v) -> dict of metadata */ +ray_t* ray_idx_info_vary_fn(ray_t** args, int64_t n); /* (.idx.info col) | (.idx.info table 'col) */ ray_t* ray_attr_set_fn (ray_t* name, ray_t* v); /* (.attr.set 'name v) */ ray_t* ray_attr_get_fn (ray_t* v); /* (.attr.get v) -> sym vec */ diff --git a/src/ops/internal.h b/src/ops/internal.h index 3e8e74350..71d098339 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -36,6 +36,8 @@ #include "exec.h" #include "core/pool.h" #include "core/profile.h" +#include "core/runtime.h" /* ray_err_code — expr_eval_err_fatal */ +#include "store/colrange.h" #include "store/csr.h" #include "store/hnsw.h" #include "lftj.h" @@ -46,6 +48,13 @@ #include "vec/vec.h" #include #include +#include +#include + +/* Shared strict parser for launcher flags and .sys.args. When core_count is + * true, values are limited to the heap registry's total worker capacity. */ +int parse_sys_int_arg(const char* s, bool nonnegative, bool core_count, + int64_t* out); /* True if every leaf is constant or reduced to a scalar. */ bool op_tree_is_scalar(ray_graph_t* g, uint32_t id); @@ -183,7 +192,7 @@ static inline int64_t sym_intern_safe(const char* s, size_t len) { static inline int64_t read_col_i64(const void* data, int64_t row, int8_t type, uint8_t attrs) { switch (type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)data)[row]; case RAY_SYM: switch (attrs & RAY_SYM_W_MASK) { @@ -216,7 +225,7 @@ static inline int64_t read_col_i64(const void* data, int64_t row, static inline void write_col_i64(void* data, int64_t row, int64_t val, int8_t type, uint8_t attrs) { switch (type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)data)[row] = val; return; case RAY_SYM: ray_write_sym(data, row, (uint64_t)val, type, attrs); return; @@ -321,10 +330,18 @@ static inline void col_propagate_str_pool_parted(ray_t* dst, ray_t** segs, int64 static inline void col_propagate_nulls_gather(ray_t* dst, const ray_t* src, const int64_t* indices, int64_t count) { - bool src_has_nulls = ray_vec_may_have_nulls(src); + /* Two loops, the may-have-nulls test hoisted out: this runs once per + * row per gathered column, and with the test inside, inlined into a + * large caller (sel_compact), the loop lost its registers and cost ~8% + * on where-heavy group queries. */ + if (!ray_vec_may_have_nulls(src)) { + for (int64_t r = 0; r < count; r++) + if (indices[r] < 0) ray_vec_set_null(dst, r, true); + return; + } for (int64_t r = 0; r < count; r++) { - if (indices[r] < 0 || - (src_has_nulls && ray_vec_is_null((ray_t*)src, indices[r]))) + int64_t i = indices[r]; + if (i < 0 || ray_vec_is_null((ray_t*)src, i)) ray_vec_set_null(dst, r, true); } } @@ -357,6 +374,60 @@ static inline void col_propagate_nulls_filter(ray_t* dst, const ray_t* src, } } +/* ── Ragged parted tables ───────────────────────────────────────────────── + * A partition may lack a trailing column (store/part.c): that column's + * segment for it is NULL and stands for the partition's rows as typed + * nulls, which is how ser and the formatter read it. The partition's row + * count lives in the table's partition-key (MAPCOMMON) column, so every + * reader that flattens or gathers a parted column takes those counts and a + * NULL segment contributes its rows as nulls rather than none. Without + * counts (a column met away from its table) a NULL segment contributes no + * rows, as before. */ +static inline const int64_t* parted_table_counts(ray_t* tbl, int64_t* n_out) { + *n_out = 0; + if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return NULL; + int64_t nc = ray_table_ncols(tbl); + for (int64_t c = 0; c < nc; c++) { + /* metadata first: an encoded column stays encoded; MAPCOMMON is plain */ + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m) || m.type != RAY_MAPCOMMON) continue; + ray_t* col = ray_table_col_idx(tbl, c); + if (col && !RAY_IS_ERR(col) && col->type == RAY_MAPCOMMON) { + ray_t* rc = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + if (!rc || RAY_IS_ERR(rc)) return NULL; + *n_out = rc->len; + return (const int64_t*)ray_data(rc); + } + } + return NULL; +} + +/* Rows segment s stands for: its length, or a NULL segment's partition count. */ +static inline int64_t parted_seg_rows(ray_t** segs, int64_t s, + const int64_t* cnt, int64_t ncnt) { + if (segs[s] && !RAY_IS_ERR(segs[s])) return segs[s]->len; + return (cnt && s < ncnt) ? cnt[s] : 0; +} + +/* Rows of a parted column, NULL segments counted by the partition counts. */ +static inline int64_t parted_rows_counted(ray_t* col, const int64_t* cnt, int64_t ncnt) { + ray_t** segs = (ray_t**)ray_data(col); + int64_t total = 0; + for (int64_t s = 0; s < col->len; s++) total += parted_seg_rows(segs, s, cnt, ncnt); + return total; +} + +/* Rows [off, off+n) of a flat fixed-width or SYM vector (len already + * covering them) as the type's null; BOOL/U8 have none and get 0. */ +static inline void parted_fill_nulls(ray_t* flat, int64_t off, int64_t n) { + if (n <= 0) return; + if (flat->type == RAY_BOOL || flat->type == RAY_U8) { + memset((char*)ray_data(flat) + off, 0, (size_t)n); + return; + } + for (int64_t i = 0; i < n; i++) ray_vec_set_null(flat, off + i, true); +} + /* Append one string element from a parted segment, preserving nulls. */ static inline ray_t* parted_str_append_elem(ray_t* out, ray_t* seg, int64_t local_idx, @@ -376,10 +447,12 @@ static inline ray_t* parted_str_append_elem(ray_t* out, ray_t* seg, /* Deep-copy gather from parted RAY_STR segments by row index. * Resolves each string from its source segment's pool and appends * into the output vector's own pool. Safe for multi-pool segments. */ -static inline ray_t* parted_gather_str_rows(ray_t** segs, int64_t n_segs, - const int64_t* row_indices, - int64_t count) { - /* Build prefix-sum segment boundaries */ +static inline ray_t* parted_gather_str_rows_c(ray_t** segs, int64_t n_segs, + const int64_t* row_indices, + int64_t count, + const int64_t* cnt, int64_t ncnt) { + /* Build prefix-sum segment boundaries (a NULL segment spans its + * partition's rows) */ int64_t cumul = 0; int64_t stack_ends[64]; int64_t* seg_ends = (n_segs <= 64) ? stack_ends : NULL; @@ -389,7 +462,7 @@ static inline ray_t* parted_gather_str_rows(ray_t** segs, int64_t n_segs, if (!seg_ends) return ray_error("oom", NULL); } for (int64_t i = 0; i < n_segs; i++) { - cumul += (segs[i]) ? segs[i]->len : 0; + cumul += parted_seg_rows(segs, i, cnt, ncnt); seg_ends[i] = cumul; } @@ -417,61 +490,101 @@ static inline ray_t* parted_gather_str_rows(ray_t** segs, int64_t n_segs, return out; } -/* Deep-copy head (first n rows) from parted RAY_STR segments. */ -static inline ray_t* parted_head_str(ray_t** segs, int64_t n_segs, int64_t n) { +static inline ray_t* parted_gather_str_rows(ray_t** segs, int64_t n_segs, + const int64_t* row_indices, + int64_t count) { + return parted_gather_str_rows_c(segs, n_segs, row_indices, count, NULL, 0); +} + +/* First n rows from parted RAY_STR segments; a NULL segment's rows (its + * partition count) are null strings. */ +static inline ray_t* parted_head_str_c(ray_t** segs, int64_t n_segs, int64_t n, + const int64_t* cnt, int64_t ncnt) { ray_t* out = ray_vec_new(RAY_STR, n); if (!out || RAY_IS_ERR(out)) return out; int64_t remaining = n; for (int64_t s = 0; s < n_segs && remaining > 0; s++) { - if (!segs[s]) continue; - int64_t seg_len = segs[s]->len; - int64_t take = (seg_len > remaining) ? remaining : seg_len; - const char* pool_base = segs[s]->str_pool - ? (const char*)ray_data(segs[s]->str_pool) : NULL; - for (int64_t i = 0; i < take; i++) { - out = parted_str_append_elem(out, segs[s], i, pool_base); - if (RAY_IS_ERR(out)) return out; + int64_t seg_len = parted_seg_rows(segs, s, cnt, ncnt); + int64_t take = seg_len < remaining ? seg_len : remaining; + if (!segs[s] || RAY_IS_ERR(segs[s])) { + for (int64_t i = 0; i < take; i++) { + out = ray_str_vec_append(out, "", 0); + if (RAY_IS_ERR(out)) return out; + ray_vec_set_null(out, out->len - 1, true); + } + } else { + const char* pool_base = segs[s]->str_pool + ? (const char*)ray_data(segs[s]->str_pool) : NULL; + for (int64_t i = 0; i < take; i++) { + out = parted_str_append_elem(out, segs[s], i, pool_base); + if (RAY_IS_ERR(out)) return out; + } } remaining -= take; } return out; } +static inline ray_t* parted_head_str(ray_t** segs, int64_t n_segs, int64_t n) { + return parted_head_str_c(segs, n_segs, n, NULL, 0); +} -/* Deep-copy tail (last n rows) from parted RAY_STR segments. */ -static inline ray_t* parted_tail_str(ray_t** segs, int64_t n_segs, int64_t n) { - /* First pass: count total rows to find start offset */ +/* Last n rows from parted RAY_STR segments; a NULL segment's rows (its + * partition count) are null strings. */ +static inline ray_t* parted_tail_str_c(ray_t** segs, int64_t n_segs, int64_t n, + const int64_t* cnt, int64_t ncnt) { int64_t total = 0; - for (int64_t s = 0; s < n_segs; s++) - if (segs[s]) total += segs[s]->len; + for (int64_t s = 0; s < n_segs; s++) total += parted_seg_rows(segs, s, cnt, ncnt); int64_t skip = total - n; if (skip < 0) { skip = 0; n = total; } - ray_t* out = ray_vec_new(RAY_STR, n); if (!out || RAY_IS_ERR(out)) return out; int64_t skipped = 0; for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s]) continue; - int64_t seg_len = segs[s]->len; + int64_t seg_len = parted_seg_rows(segs, s, cnt, ncnt); int64_t seg_start = 0; if (skipped + seg_len <= skip) { skipped += seg_len; continue; } if (skipped < skip) { seg_start = skip - skipped; skipped = skip; } - const char* pool_base = segs[s]->str_pool - ? (const char*)ray_data(segs[s]->str_pool) : NULL; - for (int64_t i = seg_start; i < seg_len; i++) { - out = parted_str_append_elem(out, segs[s], i, pool_base); - if (RAY_IS_ERR(out)) return out; + if (!segs[s] || RAY_IS_ERR(segs[s])) { + for (int64_t i = seg_start; i < seg_len; i++) { + out = ray_str_vec_append(out, "", 0); + if (RAY_IS_ERR(out)) return out; + ray_vec_set_null(out, out->len - 1, true); + } + } else { + const char* pool_base = segs[s]->str_pool + ? (const char*)ray_data(segs[s]->str_pool) : NULL; + for (int64_t i = seg_start; i < seg_len; i++) { + out = parted_str_append_elem(out, segs[s], i, pool_base); + if (RAY_IS_ERR(out)) return out; + } } skipped += seg_len; } return out; } +static inline ray_t* parted_tail_str(ray_t** segs, int64_t n_segs, int64_t n) { + return parted_tail_str_c(segs, n_segs, n, NULL, 0); +} -/* Deep-copy flatten all rows from parted RAY_STR segments. */ -static inline ray_t* parted_flatten_str(ray_t** segs, int64_t n_segs, int64_t total) { +/* Deep-copy flatten all rows from parted RAY_STR segments; a NULL segment + * yields its partition's rows as null (empty) strings. */ +static inline ray_t* parted_flatten_str_c(ray_t** segs, int64_t n_segs, + const int64_t* cnt, int64_t ncnt) { + int64_t total = 0; + for (int64_t s = 0; s < n_segs; s++) total += parted_seg_rows(segs, s, cnt, ncnt); ray_t* out = ray_vec_new(RAY_STR, total); if (!out || RAY_IS_ERR(out)) return out; for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s] || segs[s]->len <= 0) continue; + if (!segs[s] || RAY_IS_ERR(segs[s])) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + for (int64_t i = 0; i < n; i++) { + out = ray_str_vec_append(out, "", 0); + if (RAY_IS_ERR(out)) return out; + ray_vec_set_null(out, out->len - 1, true); + } + continue; + } + if (segs[s]->len <= 0) continue; const char* pool_base = segs[s]->str_pool ? (const char*)ray_data(segs[s]->str_pool) : NULL; for (int64_t i = 0; i < segs[s]->len; i++) { @@ -482,6 +595,12 @@ static inline ray_t* parted_flatten_str(ray_t** segs, int64_t n_segs, int64_t to return out; } +/* Deep-copy flatten all rows from parted RAY_STR segments. */ +static inline ray_t* parted_flatten_str(ray_t** segs, int64_t n_segs, int64_t total) { + (void)total; /* a capacity hint; the segments give the exact count */ + return parted_flatten_str_c(segs, n_segs, NULL, 0); +} + /* ── LIST analogues of the parted STR helpers ──────────────────────────── * A LIST cell is a ray_t* — every copy below SHARES elements via * ray_retain, never byte-copies: a raw memcpy of the 8-byte pointers @@ -489,15 +608,25 @@ static inline ray_t* parted_flatten_str(ray_t** segs, int64_t n_segs, int64_t to * on release (issue #355). NULL segments contribute zero rows, matching * parted_gather_col's row numbering. */ -/* Flatten all rows from parted RAY_LIST segments. */ -static inline ray_t* parted_flatten_list(ray_t** segs, int64_t n_segs, - int64_t total) { +/* Flatten all rows from parted RAY_LIST segments; a NULL segment yields its + * partition's rows as the null object. */ +static inline ray_t* parted_flatten_list_c(ray_t** segs, int64_t n_segs, + const int64_t* cnt, int64_t ncnt) { + int64_t total = 0; + for (int64_t s = 0; s < n_segs; s++) total += parted_seg_rows(segs, s, cnt, ncnt); ray_t* out = ray_list_new(total); if (!out || RAY_IS_ERR(out)) return out; ray_t** dst = (ray_t**)ray_data(out); int64_t pos = 0; for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s]) continue; + if (!segs[s] || RAY_IS_ERR(segs[s])) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + for (int64_t i = 0; i < n && pos < total; i++) { + ray_retain(RAY_NULL_OBJ); + dst[pos++] = RAY_NULL_OBJ; + } + continue; + } ray_t** src = (ray_t**)ray_data(segs[s]); for (int64_t i = 0; i < segs[s]->len && pos < total; i++) { ray_t* e = src[i]; @@ -509,16 +638,32 @@ static inline ray_t* parted_flatten_list(ray_t** segs, int64_t n_segs, return out; } -/* First n rows from parted RAY_LIST segments. */ -static inline ray_t* parted_head_list(ray_t** segs, int64_t n_segs, int64_t n) { +/* Flatten all rows from parted RAY_LIST segments. */ +static inline ray_t* parted_flatten_list(ray_t** segs, int64_t n_segs, + int64_t total) { + (void)total; + return parted_flatten_list_c(segs, n_segs, NULL, 0); +} + +/* First n rows from parted RAY_LIST segments; a NULL segment's rows are the + * null object. */ +static inline ray_t* parted_head_list_c(ray_t** segs, int64_t n_segs, int64_t n, + const int64_t* cnt, int64_t ncnt) { ray_t* out = ray_list_new(n); if (!out || RAY_IS_ERR(out)) return out; ray_t** dst = (ray_t**)ray_data(out); int64_t pos = 0; for (int64_t s = 0; s < n_segs && pos < n; s++) { - if (!segs[s]) continue; + int64_t seg_len = parted_seg_rows(segs, s, cnt, ncnt); + if (!segs[s] || RAY_IS_ERR(segs[s])) { + for (int64_t i = 0; i < seg_len && pos < n; i++) { + ray_retain(RAY_NULL_OBJ); + dst[pos++] = RAY_NULL_OBJ; + } + continue; + } ray_t** src = (ray_t**)ray_data(segs[s]); - for (int64_t i = 0; i < segs[s]->len && pos < n; i++) { + for (int64_t i = 0; i < seg_len && pos < n; i++) { ray_t* e = src[i]; if (e) ray_retain(e); dst[pos++] = e; @@ -527,54 +672,72 @@ static inline ray_t* parted_head_list(ray_t** segs, int64_t n_segs, int64_t n) { out->len = pos; return out; } +static inline ray_t* parted_head_list(ray_t** segs, int64_t n_segs, int64_t n) { + return parted_head_list_c(segs, n_segs, n, NULL, 0); +} -/* Last n rows from parted RAY_LIST segments. */ -static inline ray_t* parted_tail_list(ray_t** segs, int64_t n_segs, int64_t n) { +/* Last n rows from parted RAY_LIST segments; a NULL segment's rows are the + * null object. */ +static inline ray_t* parted_tail_list_c(ray_t** segs, int64_t n_segs, int64_t n, + const int64_t* cnt, int64_t ncnt) { int64_t total = 0; - for (int64_t s = 0; s < n_segs; s++) - if (segs[s]) total += segs[s]->len; + for (int64_t s = 0; s < n_segs; s++) total += parted_seg_rows(segs, s, cnt, ncnt); int64_t skip = total - n; - if (skip < 0) skip = 0; - - ray_t* out = ray_list_new(total - skip); + if (skip < 0) { skip = 0; n = total; } + ray_t* out = ray_list_new(n); if (!out || RAY_IS_ERR(out)) return out; ray_t** dst = (ray_t**)ray_data(out); - int64_t pos = 0, seen = 0; - for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s]) continue; - ray_t** src = (ray_t**)ray_data(segs[s]); - for (int64_t i = 0; i < segs[s]->len; i++, seen++) { - if (seen < skip) continue; - ray_t* e = src[i]; - if (e) ray_retain(e); - dst[pos++] = e; + int64_t pos = 0, skipped = 0; + for (int64_t s = 0; s < n_segs && pos < n; s++) { + int64_t seg_len = parted_seg_rows(segs, s, cnt, ncnt); + int64_t seg_start = 0; + if (skipped + seg_len <= skip) { skipped += seg_len; continue; } + if (skipped < skip) { seg_start = skip - skipped; skipped = skip; } + if (!segs[s] || RAY_IS_ERR(segs[s])) { + for (int64_t i = seg_start; i < seg_len && pos < n; i++) { + ray_retain(RAY_NULL_OBJ); + dst[pos++] = RAY_NULL_OBJ; + } + } else { + ray_t** src = (ray_t**)ray_data(segs[s]); + for (int64_t i = seg_start; i < seg_len && pos < n; i++) { + ray_t* e = src[i]; + if (e) ray_retain(e); + dst[pos++] = e; + } } + skipped += seg_len; } out->len = pos; return out; } +static inline ray_t* parted_tail_list(ray_t** segs, int64_t n_segs, int64_t n) { + return parted_tail_list_c(segs, n_segs, n, NULL, 0); +} /* Gather rows (global row indices, sorted ascending) from parted RAY_LIST * segments — LIST counterpart of parted_gather_str_rows. */ -static inline ray_t* parted_gather_list_rows(ray_t** segs, int64_t n_segs, - const int64_t* idx, - int64_t count) { +static inline ray_t* parted_gather_list_rows_c(ray_t** segs, int64_t n_segs, + const int64_t* idx, int64_t count, + const int64_t* cnt, int64_t ncnt) { ray_t* out = ray_list_new(count); if (!out || RAY_IS_ERR(out)) return out; ray_t** dst = (ray_t**)ray_data(out); int64_t seg = 0; int64_t seg_start = 0; - int64_t seg_end = (n_segs > 0 && segs[0]) ? segs[0]->len : 0; + int64_t seg_end = n_segs > 0 ? parted_seg_rows(segs, 0, cnt, ncnt) : 0; for (int64_t j = 0; j < count; j++) { int64_t r = idx[j]; while (seg < n_segs - 1 && r >= seg_end) { seg_start = seg_end; seg++; - seg_end += segs[seg] ? segs[seg]->len : 0; + seg_end += parted_seg_rows(segs, seg, cnt, ncnt); } ray_t* e = NULL; if (segs[seg] && r >= seg_start && r - seg_start < segs[seg]->len) e = ((ray_t**)ray_data(segs[seg]))[r - seg_start]; + else if (!segs[seg] && r >= seg_start && r < seg_end) + e = RAY_NULL_OBJ; /* a missing segment's row */ if (e) ray_retain(e); dst[j] = e; } @@ -582,30 +745,50 @@ static inline ray_t* parted_gather_list_rows(ray_t** segs, int64_t n_segs, return out; } +static inline ray_t* parted_gather_list_rows(ray_t** segs, int64_t n_segs, + const int64_t* idx, + int64_t count) { + return parted_gather_list_rows_c(segs, n_segs, idx, count, NULL, 0); +} + /* Filter parted RAY_LIST segments by a boolean predicate over the column's - * global rows. */ -static inline ray_t* parted_filter_list(ray_t** segs, int64_t n_segs, - const uint8_t* pred, - int64_t pass_count) { + * global rows; a NULL segment spans its partition's rows, which pass as + * the null object. */ +static inline ray_t* parted_filter_list_c(ray_t** segs, int64_t n_segs, + const uint8_t* pred, int64_t pass_count, + const int64_t* cnt, int64_t ncnt) { ray_t* out = ray_list_new(pass_count); if (!out || RAY_IS_ERR(out)) return out; ray_t** dst = (ray_t**)ray_data(out); int64_t off = 0, pos = 0; for (int64_t s = 0; s < n_segs; s++) { - if (!segs[s]) continue; + int64_t seg_len = parted_seg_rows(segs, s, cnt, ncnt); + if (!segs[s] || RAY_IS_ERR(segs[s])) { + for (int64_t i = 0; i < seg_len && pos < pass_count; i++) { + if (!pred[off + i]) continue; + ray_retain(RAY_NULL_OBJ); + dst[pos++] = RAY_NULL_OBJ; + } + off += seg_len; + continue; + } ray_t** src = (ray_t**)ray_data(segs[s]); - for (int64_t i = 0; i < segs[s]->len; i++) { + for (int64_t i = 0; i < seg_len; i++) { if (!pred[off + i]) continue; if (pos >= pass_count) break; ray_t* e = src[i]; if (e) ray_retain(e); dst[pos++] = e; } - off += segs[s]->len; + off += seg_len; } out->len = pos; return out; } +static inline ray_t* parted_filter_list(ray_t** segs, int64_t n_segs, + const uint8_t* pred, int64_t pass_count) { + return parted_filter_list_c(segs, n_segs, pred, pass_count, NULL, 0); +} /* True for a parted column whose segments are RAY_LIST vectors — such a * column must go through the retaining LIST helpers above, never the @@ -777,6 +960,8 @@ static inline void sym_elem(const ray_t* input, int64_t i, typedef struct { bool enabled; + bool f64; /* a FLOAT bias over an integer column: SUM and AVG + * emit F64 from the integer sum (bias_i64 unused) */ double bias_f64; int64_t bias_i64; } agg_affine_t; @@ -847,6 +1032,7 @@ typedef struct { uint8_t src1; /* source 1 register */ uint8_t src2; /* source 2 register (0xFF for unary) */ uint8_t null_aware; /* 1 = use sentinel-checking kernel variant */ + uint8_t u8_mod_zero; /* U8 divisor: modulo by zero yields 0 */ } expr_ins_t; enum { REG_SCAN = 0, REG_CONST = 1, REG_SCRATCH = 2 }; @@ -867,16 +1053,43 @@ typedef struct { bool nullable; /* lanes may contain NULL_I64 / NaN */ bool null_src; /* that nullability traces to a nullable column * (else: only op-generated sentinels) */ + ray_col_src_t* src; /* bound source (REG_SCAN; borrowed from the graph) */ + bool enc; /* src is range-read per morsel (generation 2, + * single file, not materialized; or, rebound + * per segment, an encoded parted segment): + * data is NULL */ const void* data; /* column data pointer (REG_SCAN only) */ ray_t* col_obj; /* source column vec (REG_SCAN, non-parted) — * carries the chunk-zone index for zone-skip */ - ray_t* parted_col; /* parted wrapper (is_parted only) */ + ray_t* parted_col; /* parted wrapper, or a RAY_ENCCOL_PARTED without a + * published materialization (is_parted only): + * expr_eval_full_parted rebinds it per segment */ double const_f64; /* scalar value (REG_CONST) */ int64_t const_i64; /* scalar value (REG_CONST) */ } regs[EXPR_MAX_REGS]; expr_ins_t ins[EXPR_MAX_INS]; } ray_expr_t; +/* Encoded leaves of a fused BOOL program (expr.c, expr_enc_plan_build): a + * comparison of an encoded single-file scan register with a constant of + * the same lane type, evaluated on the vector's view instead of its + * decoded values. */ +typedef struct { + uint8_t ins; /* the compare instruction */ + uint8_t reg; /* its encoded scan register */ + uint16_t op; /* normalized: the column on the left */ + bool is_f64; /* F64 lanes: the scan register and the constant are both F64 */ + int64_t ci; /* the constant, I64 lanes */ + double cf; /* the constant, F64 lanes */ + uint8_t null_result; /* the leaf kernel's result on the lane's null sentinel */ +} expr_enc_leaf_t; +typedef struct { + uint8_t n_leaves; + int8_t leaf_of_ins[EXPR_MAX_INS]; + bool load_reg[EXPR_MAX_REGS]; /* some non-leaf instruction reads the register */ + expr_enc_leaf_t leaf[EXPR_MAX_INS]; +} expr_enc_plan_t; + /* ══════════════════════════════════════════ * Shared gather types — used by filter.c, exec.c (sort, join) * ══════════════════════════════════════════ */ @@ -917,6 +1130,109 @@ typedef struct { * is chosen by both. */ static inline uint8_t sort_nulls_first(uint8_t desc) { return (uint8_t)!desc; } +/* Column types whose directory statistics are ordered for the zone gate + * in P2: BOOL, U8, I16, I32, I64, DATE, TIME, TIMESTAMP. */ +static inline bool zone_dir_type(int8_t t) { + return t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; +} + +/* Three-valued decision of (col cmp_op cval) over a range from its + * non-null extrema: 1 all-pass, 0 all-fail, -1 undecided. Nulls rank + * below every value (zone_cmp_decision's rule). all_null ranges and + * ranges without extrema are undecided. */ +static inline int zone_cmp_core(int64_t cmin, int64_t cmax, bool has_minmax, bool has_nulls, + bool all_null, uint16_t cmp_op, int64_t cval) { + if (all_null || !has_minmax || cmin > cmax) return -1; /* leave to the kernel */ + switch (cmp_op) { + case OP_EQ: + if (cval < cmin || cval > cmax) return 0; + if (!has_nulls && cmin == cmax) return 1; + break; + case OP_NE: + if (!has_nulls && (cval < cmin || cval > cmax)) return 1; + if (!has_nulls && cmin == cmax && cval == cmin) return 0; + break; + case OP_LT: + if (!has_nulls && cmin >= cval) return 0; + if (!has_nulls && cmax < cval) return 1; + break; + case OP_LE: + if (!has_nulls && cmin > cval) return 0; + if (!has_nulls && cmax <= cval) return 1; + break; + case OP_GT: + if (cmax <= cval) return 0; + if (!has_nulls && cmin > cval) return 1; + break; + case OP_GE: + if (cmax < cval) return 0; + if (!has_nulls && cmin >= cval) return 1; + break; + default: break; + } + return -1; +} + +/* The SYM membership rule: (ids == c) or (ids != c) over a range whose + * statistics exclude id 0 ("", the in-band null): min / max over the + * nonzero ids (has_minmax false when every row is id 0), n_nulls the id-0 + * rows of `rows`. 1 all-pass, 0 all-fail, -1 undecided. c is an id of + * the column's domain, or -1 for a string absent from it (EQ all-fail, NE + * all-pass, without statistics). c == 0 is decided by the null count + * alone, a nonzero c by [min, max]. EQ / NE only: ids are never ordered + * (#738); any other operator is undecided. */ +static inline int zone_sym_decision(int64_t cmin, int64_t cmax, bool has_minmax, int64_t n_nulls, + int64_t rows, uint16_t op, int64_t c) { + if (op != OP_EQ && op != OP_NE) return -1; + int eq = -1; + if (c < 0) eq = 0; + else if (rows <= 0) eq = -1; + else if (c == 0) eq = n_nulls == 0 ? 0 : n_nulls == rows ? 1 : -1; + else if (n_nulls == rows) eq = 0; + else if (!has_minmax || cmin > cmax) eq = -1; + else if (c < cmin || c > cmax) eq = 0; + else if (cmin == cmax && n_nulls == 0) eq = 1; + if (eq < 0) return -1; + return op == OP_EQ ? eq : 1 - eq; +} + +/* zone_cmp_core over double extrema (F32 / F64 directory and descriptor + * statistics, NaN excluded as the null): the same table under the + * predicate comparator, where -0.0 == +0.0 as plain C comparison gives. */ +static inline int zone_cmp_core_f64(double cmin, double cmax, bool has_minmax, bool has_nulls, + bool all_null, uint16_t cmp_op, double cval) { + if (all_null || !has_minmax || !(cmin <= cmax) || cval != cval) return -1; /* leave to the kernel */ + switch (cmp_op) { + case OP_EQ: + if (cval < cmin || cval > cmax) return 0; + if (!has_nulls && cmin == cmax) return 1; + break; + case OP_NE: + if (!has_nulls && (cval < cmin || cval > cmax)) return 1; + if (!has_nulls && cmin == cmax && cval == cmin) return 0; + break; + case OP_LT: + if (!has_nulls && cmin >= cval) return 0; + if (!has_nulls && cmax < cval) return 1; + break; + case OP_LE: + if (!has_nulls && cmin > cval) return 0; + if (!has_nulls && cmax <= cval) return 1; + break; + case OP_GT: + if (cmax <= cval) return 0; + if (!has_nulls && cmin > cval) return 1; + break; + case OP_GE: + if (cmax < cval) return 0; + if (!has_nulls && cmin >= cval) return 1; + break; + default: break; + } + return -1; +} + typedef struct { ray_t** vecs; uint8_t* desc; @@ -1041,48 +1357,129 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, const int64_t* keep_syms, int keep_n); /* ── expr.c ── */ +/* The try_* planners and expr_compile return false for "not this shape". A + * failed column bind (or plain request) also returns false but leaves an + * owned error in *err (ray_error_free); *err is NULL otherwise. */ +/* try_affine_sumavg_input's *out_vec is the base scan's column object: the + * plain column when it is ready, else a RAY_ENCCOL the caller binds + * (ray_col_src_bind) and reads by range. try_linear_sumavg_input_i64 and + * try_prod_sumavg_input_f64 read whole-column pointers: an encoded term not + * yet materialized declines them (*err NULL). */ bool try_affine_sumavg_input(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, - ray_t** out_vec, agg_affine_t* out_affine); + bool f64_bias_ok, + ray_t** out_vec, agg_affine_t* out_affine, ray_t** err); bool try_linear_sumavg_input_i64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, - agg_linear_t* out_plan); + agg_linear_t* out_plan, ray_t** err); bool try_prod_sumavg_input_f64(ray_graph_t* g, ray_t* tbl, ray_op_t* input_op, - agg_prod_t* out); -bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out); + agg_prod_t* out, ray_t** err); +bool expr_compile(ray_graph_t* g, ray_t* tbl, ray_op_t* root, ray_expr_t* out, ray_t** err); ray_t* expr_eval_full(const ray_expr_t* expr, int64_t nrows); +/* A failed expr_eval_full result: NULL or oom keeps the caller's fallback; + * any other error (a range read's corrupt, a cancel) is the query's answer, + * since a fallback would re-read the same column and hide the path. */ +static inline bool expr_eval_err_fatal(ray_t* v) { + return v && RAY_IS_ERR(v) && strcmp(ray_err_code(v), "oom") != 0; +} +/* Test hook: run the morsel evaluator of a BOOL program over [start, end) + * (at most EXPR_MORSEL rows, any alignment) into out[0 .. end - start). */ +void ray_expr_test_eval_range(const ray_expr_t* expr, int64_t start, int64_t end, + uint8_t* out, ray_t** err); +/* Test hook: the parted evaluator runs every segment instead of stopping + * at the first failing one (false restores the stop). */ +void ray_expr_test_parted_all_segments(bool on); +/* Monotonic count of fused-expression morsels decided from statistics + * (zone or directory) without reading their rows. Tests. */ +int64_t ray_expr_test_zone_skips(void); +/* Test hook: selection segments a single-leaf program emitted from an RLE + * view's runs (expr_leaf_emit), never expanded to bools. */ +int64_t ray_expr_test_leaf_runs(void); + +/* exec.c test hook: membership tests the sparse filter refinement took + * (refine_in_keep) since process start. */ +uint64_t ray_exec_test_refine_in(void); +/* exec.c test hook: filter chains pruned from their conjuncts' chunk + * statistics before running (exec_filter_chain_prune), and the selection + * segments (vectors) they dropped, since process start. */ +void ray_exec_test_zone_prune(uint64_t* calls, uint64_t* pruned_segs); +/* exec.c test hook: later `in` conjuncts over a single-file generation-2 + * column answered by range (in_sel_single_within) since process start. */ +uint64_t ray_exec_test_in_single_within(void); +/* query.c test hook: counts the (count (select ... where )) fast + * path answered since process start. */ +uint64_t ray_query_test_count_fast(void); +/* query.c test hook: rows of data[0, n) of `type` (BOOL, U8, I16, I32, + * I64, DATE, TIME, TIMESTAMP) for which `x op rhs` holds, op 1..6 = == != + * < <= > >=; ref: through the reference widening compare instead of the + * native-width kernels. */ +int64_t ray_query_test_count_compare(int8_t type, const void* data, int64_t n, int64_t rhs, + int op, bool ref); /* Fused predicate→selection (skips the full BOOL vec). * * Compiles and evaluates `pred` in selection-output mode (per-task rowsel * builders dispatched over [0,nrows), then finished into one rowsel block). - * Handles the parted/non-BOOL guard and the - * large-table fallback (>RAY_POOL_MAX_TASKS tasks → non-morsel-aligned grain). + * Handles the parted/non-BOOL guard. * Returns: * - non-NULL rowsel block → the selection (caller installs / reads it). * - NULL with *all_pass=1 → every row passed (all-pass = "no selection"). - * - NULL with *all_pass=0 → disabled / unsupported / OOM — caller falls - * back to exec_node→ray_rowsel_from_pred unchanged. */ + * - NULL with *all_pass=0 → disabled / unsupported, or an OOM before the + * dispatch (builders, rowsel block) — caller falls + * back to exec_node→ray_rowsel_from_pred unchanged. + * - an owned error → a column bind or a range read failed, a task's + * fused or range scratch ran out of memory (oom), + * or the dispatch was cancelled; the caller + * returns it (no fallback). */ ray_t* exec_pred_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, bool* all_pass); +/* exec_pred_to_selection of `pred` ANDed with the existing selection `sel` + * (borrowed): only the segments sel keeps are evaluated, with the fused + * path's encoded leaves. The same tri-state return (a block, NULL with + * *all_pass, NULL unsupported) or an owned error. */ +ray_t* exec_pred_refine_selection(ray_graph_t* g, ray_op_t* pred, ray_t* sel, bool* all_pass); /* Per-morsel "fill this morsel's bool" callback used by pred_sel_drive. * Writes out[0..n) (1=selected, 0=not) for the kernel's verdict on global - * rows [start, start+n). Null rows must resolve to 0 (not-selected). */ -typedef void (*pred_sel_fill_fn)(void* ctx, int64_t start, int64_t n, - uint8_t* out); + * rows [start, start+n). Null rows must resolve to 0 (not-selected). `sc` + * is the calling task's range scratch: initialized at the task's start and + * freed at its end on the same thread, so a fill that range-reads one + * source keeps one decode buffer per task, not per morsel. */ +typedef void (*pred_sel_fill_fn)(void* ctx, ray_col_scratch_t* sc, int64_t start, + int64_t n, uint8_t* out); /* Generic selection-output driver: dispatch `fill` over [0,nrows) in the * per-task rowsel-builder model, stitch into one block. Same tri-state * return as exec_pred_to_selection (block / NULL+all_pass / NULL). Used by - * the standalone predicate kernels (exec_in_to_selection). */ + * the standalone predicate kernels (exec_in_to_selection). With `fail` + * (initialized by the caller, noted by the fill), the dispatch's verdict is + * ray_scan_fail_finish's: the lowest noted failure, else `cancel` for a + * cancelled dispatch, returned as an owned error (no block). */ ray_t* pred_sel_drive(int64_t nrows, pred_sel_fill_fn fill, void* fill_ctx, - bool* all_pass); + ray_scan_fail_t* fail, bool* all_pass); -/* `in` selection-output worker: a root OP_IN over a flat column + literal set, - * streaming membership bools straight into a rowsel. Same tri-state return as +/* `in` / `not-in` selection-output worker: a root OP_IN / OP_NOT_IN over a + * flat column + literal set, streaming membership bools straight into a + * rowsel (a generation-2 column is read by range). Same tri-state return as * exec_pred_to_selection; NULL+all_pass=0 for any unsupported shape (non-CONST - * set, parted/MAPCOMMON/STR column, or OP_NOT_IN) → bool-path fallback. */ + * set, parted/MAPCOMMON/STR/GUID column) → bool-path fallback; an owned + * error for a bind or range-read failure or a cancel. */ ray_t* exec_in_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, bool* all_pass); +/* (== s "c") / (!= s "c") on a STR column whose source is generation 2 + * (single file or parted with an encoded segment), as a rowsel. Byte + * equality, nulls included ("" is the in-band null). Per segment: one + * dictionary lookup; chunks and vectors decided from code bounds; STR_DICT + * vectors compared on codes; other vectors range-read and compared on + * bytes. Same tri-state as exec_pred_to_selection; NULL with *all_pass + * false for any other shape (generation 0, a published materialization of + * a single-file column, a SYM constant: their path is unchanged). */ +ray_t* exec_str_to_selection(ray_graph_t* g, ray_op_t* pred, int64_t nrows, bool* all_pass); +/* exec_str_to_selection ANDed with the installed selection `sel` + * (borrowed; a later conjunct, exec_pred_refine_selection): a morsel sel + * drops is not read. The same returns. */ +ray_t* exec_str_refine_selection(ray_graph_t* g, ray_op_t* pred, ray_t* sel, bool* all_pass); +/* Test hook: STR selections answered (within 0: a first conjunct; 1: a + * refinement) since process start. */ +uint64_t ray_exec_test_str_sel(int within); ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input); ray_t* exec_elementwise_binary(ray_graph_t* g, ray_op_t* op, ray_t* lhs, ray_t* rhs); ray_t* exec_sym_order(uint16_t opcode, ray_t* lhs, ray_t* rhs, @@ -1110,9 +1507,48 @@ int64_t* msd_radix_sort_run(ray_pool_t* pool, uint64_t* keys, int64_t* indices, int64_t n, uint8_t n_bytes, uint64_t** sorted_keys_out); void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end); +/* A double as a composite radix component: the bits read as an i64 with + * a negative value's low 63 bits flipped, so signed i64 order equals + * numeric order. The composite prescans take SIGNED min/max per key; the + * single-key encoding (bits ^ mask) is unsigned-ordered instead and would + * put every positive below every negative there. The encode subtracts the + * min and so only needs the same form on both sides. -0.0 reads as +0.0: + * the comparator holds the two equal, so a tie between them must not be + * split by sign here either (it was, above the comparator's row count). */ +static inline int64_t radix_f64_ord(double x) { + if (x == 0.0) x = 0.0; + uint64_t bits; + memcpy(&bits, &x, 8); + return (int64_t)(bits ^ (-(bits >> 63) >> 1)); +} + +/* A float null is NaN. Its bits would pack above every real number, so a + * null-bearing float key sorted one way below 64 rows (comparator: a null + * is the smallest value) and the other above (composite). Instead the + * prescans leave nulls out of the key's min/max, radix_key_bounds_finish + * reserves the slot below the minimum, and the encode maps a null there: + * first on ascending, last on descending, as the I64 sentinel INT64_MIN + * already is and as the comparator orders it. */ +static inline bool radix_f64_is_null(double x) { return x != x; } + +/* Final bounds of key `col` for the composite, once kmin/kmax hold the + * min/max over its non-null values. An F64 key that may hold nulls gets + * one slot below its minimum for them; a key with no non-null value at all + * (every row null) spans a single slot. */ +static inline void radix_key_bounds_finish(ray_t* col, int64_t* kmin, int64_t* kmax) { + if (col->type != RAY_F64) return; + if (*kmin > *kmax) { *kmin = 0; *kmax = 0; } + if (ray_vec_may_have_nulls(col)) *kmin = (int64_t)((uint64_t)*kmin - 1); +} void mk_prescan_fn(void* arg, uint32_t wid, int64_t start, int64_t end); uint32_t* build_enum_rank(ray_t* col, int64_t nrows, ray_t** hdr_out); ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit); +/* HEAD(SORT) of `limit` rows under the lazy selection `sel` (borrowed), + * late materialization: the keys compacted and top-k'd, then only the + * winners' rows gathered, the old route's answer row for row. NULL when + * the shape is not the top-k shortcut's (compact the table and sort). */ +ray_t* exec_sort_head_sel(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* sel, int64_t limit); +uint64_t ray_sort_test_late_heads(void); /* test hook: HEAD(SORT)s it answered */ /* ── join.c ── */ ray_t* exec_join(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ray_t* right_table); @@ -1123,6 +1559,38 @@ ray_t* exec_window_join(ray_graph_t* g, ray_op_t* op, /* ── group.c ── */ ray_t* exec_reduction(ray_graph_t* g, ray_op_t* op, ray_t* input); +/* Reduction `opcode` (out_type: the op's, 0 for the input's) over a bound + * encoded source without a selection: the result exec_reduction gives over + * its materialization, from directory statistics where agg.c answers a + * generation-0 CHUNK_ZONE column from its zone (ray_zone_dir_answer), + * else by range reads. NULL when the type or op is not served here (the + * caller takes the plain path); otherwise a result or an owned error. */ +ray_t* ray_reduce_src(ray_col_src_t* src, uint16_t opcode, int8_t out_type); +/* Test hook (C tests only): 0 normal routing; 1 skip the v2 aggregate + * engine (legacy ladder); 2 also skip the direct-array route (legacy + * radix); 3 also skip the slice-group probe. Disarmed by + * ray_test_hooks_off. */ +void ray_group_test_route(int route); +/* Fail the next scalar chunk-buffer allocation, then disarm automatically. */ +void ray_group_test_fail_scalar_alloc(int fail); +/* Test hook (C tests only): the scalar route's chunk walk (scalar_chunk_fn) + * runs serially in tasks of `rows` rows, any cut (as ray_pool_dispatch's + * grain after its ring clamp); 0 dispatches as usual. Disarmed by + * ray_test_hooks_off. */ +void ray_group_test_scalar_grain(int64_t rows); +/* Test hook (C tests only): the scalar route's F64 lane sum of d[0, n) at + * absolute row row0, as one block (*whole) and as pieces cut at cuts[] + * through the staged piece function (*cut). */ +void ray_group_test_f64_lanes(const double* d, int64_t row0, int64_t n, const int64_t* cuts, + int ncuts, double* whole, double* cut); +ray_t* exec_reduction_src(ray_graph_t* g, ray_op_t* op, ray_col_src_t* src); +/* ray_first_fn / ray_last_fn of a bound source for the types they read + * with collection_elem among those served here (I32, I16, BOOL, U8, DATE, + * TIME, TIMESTAMP): row 0 (len - 1) itself, a null row a typed null, read + * by range. NULL for any other type; else an atom or an owned error. */ +ray_t* ray_reduce_src_elem(ray_col_src_t* src, bool last); +/* (collection.c) The value (at tbl 'col) returns eagerly. */ +ray_t* ray_table_col_value(ray_t* tbl, int64_t sym); ray_t* exec_count_distinct(ray_graph_t* g, ray_op_t* op, ray_t* input); /* Parallel distinct for large fixed-width columns: radix-partitioned @@ -1181,6 +1649,45 @@ ray_t* exec_group(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t group_limit) /* Monotonic count of streaming parted-GROUP kernel (exec_group_per_partition) * entries. O(1) per query; surfaced via (.sys.mem)'s "group-perpart-runs". */ int64_t ray_group_perpart_runs(void); +/* Monotonic count of exec_group_per_partition runs that returned their + * result (not the concat fallback's NULL, not an error). Tests. */ +int64_t ray_group_perpart_done(void); +/* Per-partition non-null count slots built for nullable AVG/VAR/DEV inputs + * (test hook; a null-free input keeps the row count). */ +int64_t ray_group_perpart_nn_slots(void); + +/* Monotonic count of exec_group_parted's in-place concat groups (the + * parted columns grouped from their segments, no flatten). Tests. */ +int64_t ray_group_segstream_runs(void); +/* Monotonic bytes of null fill the parted group built for ragged + * partitions' stand-ins (bounded per query by the group's transient + * budget, AGG_COMPACT_BITMAP_BUDGET). Tests. */ +int64_t ray_group_null_fill_bytes(void); +/* Monotonic count of rows the direct-array key prescan walked over a + * staged (generation-2) key by range (minmax_piece). Tests. */ +int64_t ray_group_test_minmax_staged_rows(void); +/* Monotonic count of per-partition unordered takes answered from the + * first keys read up front (grp_first_keys_scan). Tests. */ +int64_t ray_group_firstkeys_runs(void); + +/* A parted fixed-width column (a plain parted wrapper or a RAY_ENCCOL_PARTED + * slot; base neither STR nor LIST) copied into one owned flat vector of + * `total` rows: segments read by range (in place when plain or already + * materialized, a vector at a time when encoded; never materialized), SYM + * cells at the widest segment's width over the first segment's domain, + * HAS_NULLS from the segments. An owned vector or error. */ +ray_t* parted_flatten_fixed(ray_t* col, int64_t total); +/* parted_flatten_fixed reading a hand-built plain wrapper's missing (NULL) + * segments as their partitions' rows of nulls (cnt / ncnt: the partition-key + * counts, parted_table_counts). */ +ray_t* parted_flatten_fixed_c(ray_t* col, int64_t total, const int64_t* cnt, int64_t ncnt); +/* Test hook: parted_flatten_fixed calls since process start (the flat + * copies of parted columns the group fallbacks make). */ +int64_t ray_group_test_flat_copies(void); +/* The widest SYM width class over a parted SYM column's segments (a plain + * parted wrapper or a RAY_ENCCOL_PARTED slot), read from their headers: the + * width a vector holding every segment's ids needs. 0 for anything else. */ +uint8_t parted_sym_width(ray_t* col); /* Monotonic count of streaming parted asof-join per-partition (day) runs * bumped once per partition processed by the streaming asof path in query.c. @@ -1216,6 +1723,22 @@ bool ray_key_cols_sorted(ray_t** key_cols, int64_t n_keys, uint8_t descending, * in exec.c; consumed by the streaming parted asof path in query.c. */ ray_t* build_segment_table(ray_t* parted_tbl, int32_t seg_idx); +/* May the DAG rooted at `root` run segment by segment with a concat merge: + * streamable ops only, scalar constants only, and a scan of the default + * table. Defined in exec.c; the parted per-segment sort/take and asof + * routes in query.c decide a clause's eligibility with it. */ +bool dag_can_stream(ray_graph_t* g, ray_op_t* root); +/* Value invariance under order-preserving restriction of the default rows: + * primitive scalars/row expressions only, with fixed membership-set edges. + * Caller must separately establish the input/default-table correspondence. + * Read-only and bounded; false declines a rewrite, not the language program. + * This does not prove structural-domain or exception-order equivalence. */ +bool ray_expr_subset_invariant(ray_graph_t* g, uint32_t root_id); +/* Does node `id` read the default table's rows, through filters, aliases + * and materializations only? Defined in opt.c; the correspondence + * ray_expr_subset_invariant leaves to its caller. */ +bool filter_input_default_domain(ray_graph_t* g, uint32_t id); + /* Ordered concat-merge of two partial partition-streamed results (tables: * per-column concat; vectors: direct concat). Returns an OWNED result. * Defined in exec.c; consumed by the streaming parted asof path in query.c. */ @@ -1247,6 +1770,9 @@ typedef struct { } ray_dict_cd_t; ray_dict_cd_t ray_dict_cd_get(void); void ray_dict_cd_clear(void); +/* Runtime teardown, before the heap goes: frees this thread's stash and + * makes every other thread's stale (dropped, never freed: #865). */ +void ray_dict_cd_runtime_gone(void); /* ── collection.c ── */ ray_t* distinct_vec_eager(ray_t* x); @@ -1502,12 +2028,15 @@ typedef struct { * on false *out carries no owned spill. On success *out owns its spill_hdr * (NULL when inline) and every base pointer aims at *out's own storage. */ /* Per-type integer null sentinel for an aggregation column. Returns 0 for - * non-nullable / non-integer types (BOOL, U8, SYM, F64) since 0 will never - * match a value flagged as null via HAS_NULLS. Shared by the group row-layout - * accumulators/finalizers and the pivot finalizer. */ + * the other types. For SYM that is the null itself (cell id 0, the empty + * symbol), and so it is for a strlen fusion over STR/SYM (length 0, the + * empty string): the row-layout accumulators skip those zeros. BOOL/U8 are + * non-nullable and F64 nulls are NaN, so 0 is never consulted for them. + * Shared by the group row-layout accumulators/finalizers and the pivot + * finalizer. */ static inline int64_t agg_int_null_sentinel_for(int8_t t) { switch (t) { - case RAY_I64: case RAY_TIMESTAMP: return NULL_I64; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: return NULL_I64; case RAY_I32: case RAY_DATE: case RAY_TIME: return (int64_t)NULL_I32; case RAY_I16: return (int64_t)NULL_I16; default: return 0; @@ -1706,14 +2235,14 @@ ray_t* broadcast_scalar(ray_t* atom, int64_t nrows); ray_t* exec_node(ray_graph_t* g, ray_op_t* op); /* ══════════════════════════════════════════ - * Thread-safe null bitmap helpers (parallel group/window) + * Parallel null-sentinel helpers (group/window) * ══════════════════════════════════════════ */ -/* Parallel-safe null marker. Writes the type-correct NULL_* sentinel - * into payload[idx] and atomically ORs HAS_NULLS into vec->attrs. - * Payload write needs no synchronisation — different threads call this - * with different idx, so each per-slot store is uncontended. attrs OR - * is atomic so the read-modify-write on the shared attrs byte is safe. +/* Write the type-correct NULL_* sentinel into a worker-owned payload slot. + * Workers must own disjoint slots and leave the shared header unchanged: + * even an atomic attrs OR races with ray_data()'s ordinary SLICE-bit read. + * The producer derives HAS_NULLS with par_finalize_nulls after workers join, + * before exposing the result to metadata consumers. * * BOOL/U8 are non-nullable (rejected at the producer surface). SYM/STR/GUID * don't appear in parallel aggregation/window output columns and are no-ops @@ -1723,20 +2252,17 @@ static inline void par_set_null(ray_t* vec, int64_t idx) { switch (vec->type) { case RAY_F64: ((double*)p)[idx] = NULL_F64; break; case RAY_F32: ((float*)p)[idx] = NULL_F32; break; - case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)p)[idx] = NULL_I64; break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)p)[idx] = NULL_I64; break; case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)p)[idx] = NULL_I32; break; case RAY_I16: ((int16_t*)p)[idx] = NULL_I16; break; default: return; } - __atomic_fetch_or(&vec->attrs, (uint8_t)RAY_ATTR_HAS_NULLS, - __ATOMIC_RELAXED); } -/* Scan payload after parallel execution and set RAY_ATTR_HAS_NULLS if - * any element carries the type-correct NULL_* sentinel. This catches - * the case where par_set_null's atomic OR raced with another thread's - * load before it took effect — the scan is the post-hoc authoritative - * check. No-op for non-sentinel types. */ +/* After workers join, derive RAY_ATTR_HAS_NULLS from type-correct NULL_* + * sentinels before publishing the output. This serial pass is not a repair + * for racing header accesses: workers must not write attrs in the first + * place. No-op for non-sentinel types. */ static inline void par_finalize_nulls(ray_t* vec) { int64_t n = vec->len; const void* p = ray_data(vec); @@ -1753,7 +2279,7 @@ static inline void par_finalize_nulls(ray_t* vec) { if (d[i] != d[i]) { vec->attrs |= RAY_ATTR_HAS_NULLS; return; } return; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* d = (const int64_t*)p; for (int64_t i = 0; i < n; i++) if (d[i] == NULL_I64) { vec->attrs |= RAY_ATTR_HAS_NULLS; return; } diff --git a/src/ops/join.c b/src/ops/join.c index 4906de103..2fc3fa169 100644 --- a/src/ops/join.c +++ b/src/ops/join.c @@ -962,6 +962,7 @@ static void join_radix_build_probe_fn(void* raw, uint32_t wid, int64_t task_star /* ht_heads is accessed atomically from multiple workers during join build. * Using _Atomic(uint32_t)* for C11-compliant atomic access. */ +#define JHT_MIN_CAP 256u #define JHT_EMPTY UINT32_MAX /* sentinel for empty HT slot/chain end */ typedef struct { @@ -1036,7 +1037,7 @@ typedef struct { } join_probe_ctx_t; /* Pass 2a: count matches per morsel */ -static void join_count_fn(void* raw, uint32_t wid, int64_t task_start, int64_t task_end) { +RAY_INLINE void join_count_rows(void* raw, uint32_t wid, int64_t task_start, int64_t task_end, bool prefetch_heads) { (void)wid; (void)task_end; join_probe_ctx_t* c = (join_probe_ctx_t*)raw; uint32_t tid = (uint32_t)task_start; @@ -1059,7 +1060,7 @@ static void join_count_fn(void* raw, uint32_t wid, int64_t task_start, int64_t t continue; } - if (l + 8 < row_end) { + if (prefetch_heads && l + 8 < row_end) { uint64_t pf_h = hash_row_keys(c->l_key_vecs, c->n_keys, l + 8, c->nullfree); __builtin_prefetch(&c->ht_heads[(uint32_t)(pf_h & ht_mask)], 0, 1); } @@ -1077,8 +1078,16 @@ static void join_count_fn(void* raw, uint32_t wid, int64_t task_start, int64_t t c->morsel_counts[tid] = count; } +/* Compile both modes from one body; select once per pass, not per row. */ +static void join_count_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + join_count_rows(raw, wid, start, end, true); +} +static void join_count_tiny_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + join_count_rows(raw, wid, start, end, false); +} + /* Pass 2b: fill match pairs using pre-computed offsets */ -static void join_fill_fn(void* raw, uint32_t wid, int64_t task_start, int64_t task_end) { +RAY_INLINE void join_fill_rows(void* raw, uint32_t wid, int64_t task_start, int64_t task_end, bool prefetch_heads) { (void)wid; (void)task_end; join_probe_ctx_t* c = (join_probe_ctx_t*)raw; uint32_t tid = (uint32_t)task_start; @@ -1108,7 +1117,7 @@ static void join_fill_fn(void* raw, uint32_t wid, int64_t task_start, int64_t ta continue; } - if (l + 8 < row_end) { + if (prefetch_heads && l + 8 < row_end) { uint64_t pf_h = hash_row_keys(c->l_key_vecs, c->n_keys, l + 8, c->nullfree); __builtin_prefetch(&c->ht_heads[(uint32_t)(pf_h & ht_mask)], 0, 1); } @@ -1133,14 +1142,22 @@ static void join_fill_fn(void* raw, uint32_t wid, int64_t task_start, int64_t ta } } +/* Compile both modes from one body; select once per pass, not per row. */ +static void join_fill_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + join_fill_rows(raw, wid, start, end, true); +} +static void join_fill_tiny_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + join_fill_rows(raw, wid, start, end, false); +} + /* Segment count of a parted table = length of any parted column's segs * array (mirrors build_segment_table's own read, exec.c:3377-3384, and * window.c's window_parted_seg_count). */ static int64_t join_parted_seg_count(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && RAY_IS_PARTED(col->type)) return col->len; + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && RAY_IS_PARTED(m.type)) return m.n_segs; } return 0; } @@ -1148,8 +1165,9 @@ static int64_t join_parted_seg_count(ray_t* tbl) { static bool join_table_has_parted_col(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) return true; + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && + (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON)) return true; } return false; } @@ -1209,10 +1227,22 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra for (uint32_t k = 0; k < n_keys; k++) { ray_op_ext_t* lk = find_ext(g, ext->join.left_keys[k]); ray_op_ext_t* rk = find_ext(g, ext->join.right_keys[k]); - if (lk && lk->base.opcode == OP_SCAN) - l_key_vecs[k] = ray_table_get_col(left_table, lk->sym); - if (rk && rk->base.opcode == OP_SCAN) - r_key_vecs[k] = ray_table_get_col(right_table, rk->sym); + if (lk && lk->base.opcode == OP_SCAN) { + l_key_vecs[k] = ray_table_col(left_table, lk->sym); + if (l_key_vecs[k] && RAY_IS_ERR(l_key_vecs[k])) { + ray_t* e = l_key_vecs[k]; + scratch_free(key_vecs_hdr); + return e; + } + } + if (rk && rk->base.opcode == OP_SCAN) { + r_key_vecs[k] = ray_table_col(right_table, rk->sym); + if (r_key_vecs[k] && RAY_IS_ERR(r_key_vecs[k])) { + ray_t* e = r_key_vecs[k]; + scratch_free(key_vecs_hdr); + return e; + } + } if (rk && rk->base.opcode == OP_CONST && rk->literal) r_key_vecs[k] = rk->literal; } @@ -1528,7 +1558,7 @@ static ray_t* exec_join_flat(ray_graph_t* g, ray_op_t* op, ray_t* left_table, ra chained_ht_fallback:; /* ── Chained HT path (small joins / radix OOM fallback) ────────── */ - uint64_t ht_cap64 = 256; + uint64_t ht_cap64 = JHT_MIN_CAP; uint64_t target = (uint64_t)right_rows * 2; while (ht_cap64 < target) ht_cap64 *= 2; if (ht_cap64 > UINT32_MAX) ht_cap64 = (uint64_t)1 << 31; @@ -1554,8 +1584,8 @@ chained_ht_fallback:; if (n_keys == 1 && join_type == 0 && l_key_vecs[0] && l_key_vecs[0]->type == RAY_I64 && right_rows > left_rows * 2) { int64_t cnt_sym = ray_sym_intern("_count", 6); - ray_t* cnt_col = ray_table_get_col(left_table, cnt_sym); - if (cnt_col) { /* left is factorized */ + ray_col_meta_t cnt_m; + if (ray_table_col_meta(left_table, cnt_sym, &cnt_m)) { /* left is factorized */ int64_t* lk = (int64_t*)ray_data(l_key_vecs[0]); int64_t lk_max = 0; for (int64_t i = 0; i < left_rows; i++) @@ -1666,12 +1696,16 @@ chained_ht_fallback:; .nullfree = keys_nullfree, }; + /* Minimum heads occupy only 1 KiB: choose no-lookahead callbacks here. + * Bodies share their implementation; constant modes remove the row-loop + * capacity decision instead of relying on compiler loop unswitching. */ + const ray_pool_fn count_probe = ht_cap > JHT_MIN_CAP ? join_count_fn : join_count_tiny_fn; /* 2a: Count matches per morsel */ if (pool && n_tasks > 1) - ray_pool_dispatch_n(pool, join_count_fn, &probe_ctx, n_tasks); + ray_pool_dispatch_n(pool, count_probe, &probe_ctx, n_tasks); else for (uint32_t t = 0; t < n_tasks; t++) - join_count_fn(&probe_ctx, 0, t, t + 1); + count_probe(&probe_ctx, 0, t, t + 1); /* Prefix sum → morsel_offsets (reuse counts array as offsets) */ pair_count = 0; @@ -1694,11 +1728,12 @@ chained_ht_fallback:; probe_ctx.r_idx = r_idx; if (pair_count > 0) { + const ray_pool_fn fill_probe = ht_cap > JHT_MIN_CAP ? join_fill_fn : join_fill_tiny_fn; if (pool && n_tasks > 1) - ray_pool_dispatch_n(pool, join_fill_fn, &probe_ctx, n_tasks); + ray_pool_dispatch_n(pool, fill_probe, &probe_ctx, n_tasks); else for (uint32_t t = 0; t < n_tasks; t++) - join_fill_fn(&probe_ctx, 0, t, t + 1); + fill_probe(&probe_ctx, 0, t, t + 1); } CHECK_CANCEL_GOTO(pool, join_cleanup); @@ -1748,6 +1783,17 @@ join_gather:; * indices), falling back to per-column gather for nullable RIGHT columns. */ int64_t left_ncols = ray_table_ncols(left_table); int64_t right_ncols = ray_table_ncols(right_table); + /* Share left columns only when the LEFT join's actual mapping preserves + * every left row in order. Cardinality alone is not sufficient: radix + * partitioning can reorder even a one-to-one join's output. + * Retained columns already carry their nulls, pools and symbol domains; + * do not rewrite metadata on these shared objects below. */ + bool left_identity = join_type == 1 && pair_count == left_rows; + if (left_identity) { + for (int64_t i = 0; i < pair_count; i++) { + if (l_idx[i] != i) { left_identity = false; break; } + } + } result = ray_table_new(left_ncols + right_ncols); if (!result || RAY_IS_ERR(result)) goto join_cleanup; @@ -1756,7 +1802,7 @@ join_gather:; * MGATHER_MAX_COLS and falls back to per-column gather otherwise, so * no column may be dropped here (a fixed [16] cap used to silently * truncate wide-table join results). */ - size_t out_slots = (size_t)(left_ncols * 2 + right_ncols * 3); + size_t out_slots = (size_t)(left_ncols * 3 + right_ncols * 3); { void* out_mem = scratch_alloc(&out_cols_hdr, (out_slots ? out_slots : 1) * sizeof(void*)); @@ -1773,16 +1819,33 @@ join_gather:; ray_t** r_out_cols = (ray_t**)(l_out_names + left_ncols); ray_t** r_src_cols = r_out_cols + right_ncols; int64_t* r_out_names = (int64_t*)(r_src_cols + right_ncols); + ray_t** l_src_cols = (ray_t**)(r_out_names + right_ncols); - /* Allocate all output columns upfront for batched gather */ + /* Allocate all output columns upfront for batched gather. Each source + * column is fetched once (borrowed plain object) and kept in + * l_src_cols / r_src_cols for the gather and propagate passes. */ int64_t l_out_count = 0; bool l_has_list = false; for (int64_t c = 0; c < left_ncols; c++) { - ray_t* col = ray_table_get_col_idx(left_table, c); + ray_t* col = ray_table_col_idx(left_table, c); if (!col) continue; - ray_t* new_col = col->type == RAY_LIST - ? join_gather_list_col(col, l_idx, pair_count) - : col_vec_new(col, pair_count); + if (RAY_IS_ERR(col)) { + for (int64_t i = 0; i < l_out_count; i++) ray_release(l_out_cols[i]); + ray_release(result); + result = col; + goto join_cleanup; + } + ray_t* new_col; + /* Slice COW copies only its header, leaving the parent shared. + * Preserve the old independent gather for this representation. */ + if (left_identity && !(col->attrs & RAY_ATTR_SLICE)) { + ray_retain(col); + new_col = col; + } else { + new_col = col->type == RAY_LIST + ? join_gather_list_col(col, l_idx, pair_count) + : col_vec_new(col, pair_count); + } if (!new_col || RAY_IS_ERR(new_col)) { ray_t* err = new_col ? new_col : ray_error("oom", NULL); for (int64_t i = 0; i < l_out_count; i++) ray_release(l_out_cols[i]); @@ -1791,8 +1854,9 @@ join_gather:; goto join_cleanup; } if (col->type == RAY_LIST) l_has_list = true; - else new_col->len = pair_count; + else if (new_col != col) new_col->len = pair_count; l_out_cols[l_out_count] = new_col; + l_src_cols[l_out_count] = col; l_out_names[l_out_count] = ray_table_col_name(left_table, c); l_out_count++; } @@ -1800,9 +1864,16 @@ join_gather:; int64_t r_out_count = 0; bool r_has_list = false; for (int64_t c = 0; c < right_ncols; c++) { - ray_t* col = ray_table_get_col_idx(right_table, c); + ray_t* col = ray_table_col_idx(right_table, c); int64_t name_id = ray_table_col_name(right_table, c); if (!col) continue; + if (RAY_IS_ERR(col)) { + for (int64_t i = 0; i < l_out_count; i++) ray_release(l_out_cols[i]); + for (int64_t i = 0; i < r_out_count; i++) ray_release(r_out_cols[i]); + ray_release(result); + result = col; + goto join_cleanup; + } bool is_key = false; for (uint32_t k = 0; k < n_keys; k++) { ray_op_ext_t* rk = find_ext(g, ext->join.right_keys[k]); @@ -1833,29 +1904,25 @@ join_gather:; if (pair_count > 0) { /* Left columns: multi_gather (non-nullable for INNER/LEFT) */ bool l_nullable = (join_type == 2); /* only FULL OUTER */ - if (!l_nullable && !l_has_list && + if (!left_identity && !l_nullable && !l_has_list && l_out_count > 1 && l_out_count <= MGATHER_MAX_COLS) { multi_gather_ctx_t mgctx = { .idx = l_idx, .ncols = l_out_count }; - int64_t si = 0; - for (int64_t c = 0; c < left_ncols && si < l_out_count; c++) { - ray_t* col = ray_table_get_col_idx(left_table, c); - if (!col) continue; + for (int64_t si = 0; si < l_out_count; si++) { + ray_t* col = l_src_cols[si]; mgctx.srcs[si] = (char*)ray_data(col); mgctx.dsts[si] = (char*)ray_data(l_out_cols[si]); mgctx.esz[si] = col_esz(col); - si++; } if (pool && pair_count > RAY_PARALLEL_THRESHOLD) ray_pool_dispatch(pool, multi_gather_fn, &mgctx, pair_count); else multi_gather_fn(&mgctx, 0, 0, pair_count); } else { - /* Fall back to per-column gather for nullable or single column */ - int64_t si = 0; - for (int64_t c = 0; c < left_ncols && si < l_out_count; c++) { - ray_t* col = ray_table_get_col_idx(left_table, c); - if (!col) continue; - if (col->type != RAY_LIST) { + /* Gather newly allocated columns, including slice fallbacks. + * Retained identity outputs already have their source values. */ + for (int64_t si = 0; si < l_out_count; si++) { + ray_t* col = l_src_cols[si]; + if (l_out_cols[si] != col && col->type != RAY_LIST) { gather_ctx_t gctx = { .idx = l_idx, .src_col = col, .dst_col = l_out_cols[si], .esz = col_esz(col), .nullable = l_nullable, @@ -1865,7 +1932,6 @@ join_gather:; else gather_fn(&gctx, 0, 0, pair_count); } - si++; } } @@ -1904,16 +1970,14 @@ join_gather:; * adopt that source's domain (sym-domain Phase 2; no-op while all * domains are the runtime singleton). */ { - int64_t si = 0; - for (int64_t c = 0; c < left_ncols && si < l_out_count; c++) { - ray_t* col = ray_table_get_col_idx(left_table, c); - if (!col) continue; + for (int64_t si = 0; si < l_out_count; si++) { + ray_t* col = l_src_cols[si]; + if (l_out_cols[si] == col) continue; /* retained, metadata intact */ col_propagate_str_pool(l_out_cols[si], col); if (col->type != RAY_LIST) col_propagate_nulls_gather(l_out_cols[si], col, l_idx, pair_count); if (l_out_cols[si]->type == RAY_SYM) ray_sym_vec_adopt_domain(l_out_cols[si], col); - si++; } } if (join_type == 2 && full_right_only_start >= 0) { @@ -2165,10 +2229,22 @@ static ray_t* exec_antijoin_flat(ray_graph_t* g, ray_op_t* op, for (uint32_t k = 0; k < n_keys; k++) { ray_op_ext_t* lk = find_ext(g, ext->join.left_keys[k]); ray_op_ext_t* rk = find_ext(g, ext->join.right_keys[k]); - if (lk && lk->base.opcode == OP_SCAN) - l_key_vecs[k] = ray_table_get_col(left_table, lk->sym); - if (rk && rk->base.opcode == OP_SCAN) - r_key_vecs[k] = ray_table_get_col(right_table, rk->sym); + if (lk && lk->base.opcode == OP_SCAN) { + l_key_vecs[k] = ray_table_col(left_table, lk->sym); + if (l_key_vecs[k] && RAY_IS_ERR(l_key_vecs[k])) { + ray_t* e = l_key_vecs[k]; + scratch_free(key_vecs_hdr); + return e; + } + } + if (rk && rk->base.opcode == OP_SCAN) { + r_key_vecs[k] = ray_table_col(right_table, rk->sym); + if (r_key_vecs[k] && RAY_IS_ERR(r_key_vecs[k])) { + ray_t* e = r_key_vecs[k]; + scratch_free(key_vecs_hdr); + return e; + } + } if (rk && rk->base.opcode == OP_CONST && rk->literal) r_key_vecs[k] = rk->literal; } @@ -2294,8 +2370,13 @@ static ray_t* exec_antijoin_flat(ray_graph_t* g, ray_op_t* op, } for (int64_t c = 0; c < left_ncols; c++) { - ray_t* col = ray_table_get_col_idx(left_table, c); + ray_t* col = ray_table_col_idx(left_table, c); if (!col) continue; + if (RAY_IS_ERR(col)) { + ray_release(result); + scratch_free(out_idx_hdr); + return col; + } ray_t* new_col = col->type == RAY_LIST ? join_gather_list_col(col, out_idx, out_count) : col_vec_new(col, out_count); @@ -2672,6 +2753,16 @@ static void asof_idx_match_fn(void* raw, uint32_t wid, } } +/* The two index variants of asof_hash_group_match (single key and + * multi-key) admit only a right side whose FIRST eq key carries a grouped + * HASH or PART index. Shared with the caller so it pays the exact text + * null proof (rt_no_nulls) only when one of those variants can use it. */ +static bool asof_rt_eq_indexed(uint32_t n_eq, ray_t* const* rt_eq) { + if (n_eq == 0) return false; + ray_idx_kind_t kind = ray_index_kind(rt_eq[0]); + return kind == RAY_IDX_HASH || kind == RAY_IDX_PART; +} + static bool asof_hash_group_match(uint32_t n_eq, ray_t* const* lt_eq, ray_t* const* rt_eq, const int64_t* const* eq_xlut, @@ -2802,9 +2893,7 @@ static bool asof_hash_group_match(uint32_t n_eq, * sequential memory and costs a fraction of the binary searches it * unlocks. No pass over the right table is needed: cost is * per-probed-key, not per-row. */ - if (ok && n_eq == 1 && rt_no_nulls && - (ray_index_kind(rt_eq[0]) == RAY_IDX_HASH || - ray_index_kind(rt_eq[0]) == RAY_IDX_PART)) { + if (ok && n_eq == 1 && rt_no_nulls && asof_rt_eq_indexed(n_eq, rt_eq)) { ray_idx_consults[IDX_SITE_ASOF]++; bool served = true; ray_t* gsl_hdr = NULL; @@ -2821,6 +2910,8 @@ static bool asof_hash_group_match(uint32_t n_eq, * with a shared bail flag. */ int64_t verify_rows = 0; bool idx_ordered = asof_index_ordered_by(rt_eq[0], rt_time_sym); + /* counts the route decision, not a served use (the variant may still bail) */ + if (idx_ordered) ray_idx_consults[IDX_SITE_ASOF_ORDERED]++; for (int32_t g = 0; g < n_groups && served; g++) { int hit = asof_index_group(rt_eq[0], gkeys[g], &gsl[g]); if (hit < 0) { served = false; break; } /* ineligible */ @@ -2836,6 +2927,7 @@ static bool asof_hash_group_match(uint32_t n_eq, } if (served) { ray_idx_hits[IDX_SITE_ASOF]++; + ray_idx_note_use(rt_eq[0]); asof_idx_match_ctx_t mctx = { .slices = gsl, .left_gid = left_gid, .lt_time = lt_time, .rt_time = rt_time, @@ -2866,8 +2958,7 @@ static bool asof_hash_group_match(uint32_t n_eq, * table anyway, the sequential full pass is cheaper per row, so bail * upfront on the (known!) slice-length sum. */ if (ok && n_eq >= 2 && rt_no_nulls && n_groups > 0 && - (ray_index_kind(rt_eq[0]) == RAY_IDX_HASH || - ray_index_kind(rt_eq[0]) == RAY_IDX_PART)) { + asof_rt_eq_indexed(n_eq, rt_eq)) { ray_idx_consults[IDX_SITE_ASOF]++; bool served = true; @@ -2934,6 +3025,8 @@ static bool asof_hash_group_match(uint32_t n_eq, * for the density bail. */ int64_t total_slice = 0; bool idx_ordered = asof_index_ordered_by(rt_eq[0], rt_time_sym); + /* counts the route decision, not a served use (the variant may still bail) */ + if (idx_ordered) ray_idx_consults[IDX_SITE_ASOF_ORDERED]++; for (int32_t f = 0; f < n_fk && served; f++) { int32_t rep = fk_head[f]; int hit = asof_index_group(rt_eq[0], @@ -2989,6 +3082,7 @@ static bool asof_hash_group_match(uint32_t n_eq, } if (sparse) { ray_idx_hits[IDX_SITE_ASOF]++; + ray_idx_note_use(rt_eq[0]); scratch_free(ftab_hdr); scratch_free(fhead_hdr); scratch_free(fnext_hdr); scratch_free(fgid_hdr); scratch_free(fsl_hdr); @@ -3004,6 +3098,7 @@ static bool asof_hash_group_match(uint32_t n_eq, if (served) { ray_idx_hits[IDX_SITE_ASOF]++; + ray_idx_note_use(rt_eq[0]); /* Left cursor structures — identical to the full-pass * cursor merge. */ memset(lcnt, 0, ((size_t)n_groups + 1) * 4); @@ -3445,8 +3540,16 @@ static ray_t* exec_window_join_flat(ray_graph_t* g, ray_op_t* op, /* Get time vectors — use int64 representation for comparison. * TIME uses 4-byte i32 (ms), TIMESTAMP uses 8-byte i64 (ns). * We expand to a temporary i64 array for uniform comparison. */ - ray_t* lt_time_vec = ray_table_get_col(left_table, time_sym); - ray_t* rt_time_vec = ray_table_get_col(right_table, time_sym); + ray_t* lt_time_vec = ray_table_col(left_table, time_sym); + ray_t* rt_time_vec = ray_table_col(right_table, time_sym); + if ((lt_time_vec && RAY_IS_ERR(lt_time_vec)) || + (rt_time_vec && RAY_IS_ERR(rt_time_vec))) { + ray_t* e = (lt_time_vec && RAY_IS_ERR(lt_time_vec)) ? lt_time_vec : rt_time_vec; + if (e == lt_time_vec && rt_time_vec && RAY_IS_ERR(rt_time_vec)) + ray_error_free(rt_time_vec); + scratch_free(eqbuf_hdr); + return e; + } if (!lt_time_vec || !rt_time_vec) { scratch_free(eqbuf_hdr); return ray_error("schema", NULL); @@ -3486,8 +3589,16 @@ static ray_t* exec_window_join_flat(ray_graph_t* g, ray_op_t* op, /* Get eq key vectors — stored as ray_t* for type-safe access. * lt_eq/rt_eq point into the eqbuf carve above (no separate alloc). */ for (uint32_t k = 0; k < n_eq; k++) { - ray_t* lv = ray_table_get_col(left_table, eq_syms[k]); - ray_t* rv = ray_table_get_col(right_table, eq_syms[k]); + ray_t* lv = ray_table_col(left_table, eq_syms[k]); + ray_t* rv = ray_table_col(right_table, eq_syms[k]); + if ((lv && RAY_IS_ERR(lv)) || (rv && RAY_IS_ERR(rv))) { + ray_t* e = (lv && RAY_IS_ERR(lv)) ? lv : rv; + if (e == lv && rv && RAY_IS_ERR(rv)) ray_error_free(rv); + if (lt_time_hdr) scratch_free(lt_time_hdr); + if (rt_time_hdr) scratch_free(rt_time_hdr); + scratch_free(eqbuf_hdr); + return e; + } if (!lv || !rv) { if (lt_time_hdr) scratch_free(lt_time_hdr); if (rt_time_hdr) scratch_free(rt_time_hdr); @@ -3618,10 +3729,27 @@ static ray_t* exec_window_join_flat(ray_graph_t* g, ray_op_t* op, * (no sorting of either side; a fresh CSR grouped index on a single eq * key answers groups with no right pass at all). Falls back to the * sort-merge when the per-group right-time monotonicity precondition - * fails. */ + * fails. + * + * rt_no_nulls feeds only the index variants. The O(1) attrs check + * settles every key it can; a SYM/STR key, which that check can never + * clear, is proven by a full payload scan — so take that scan only + * when the first key carries an index the variants accept, and only + * after every flag-readable key has passed. Without such an index + * rt_no_nulls stays false at no cost, as nothing would consume it. */ bool rt_no_nulls = !ray_vec_may_have_nulls(rt_time_vec); - for (uint32_t k = 0; k < n_eq && rt_no_nulls; k++) - if (ray_vec_may_have_nulls(rt_eq[k])) rt_no_nulls = false; + bool rt_text_keys = false; + for (uint32_t k = 0; k < n_eq && rt_no_nulls; k++) { + if (!ray_vec_may_have_nulls(rt_eq[k])) continue; + if (join_key_col_scanned(rt_eq[k])) rt_text_keys = true; + else rt_no_nulls = false; + } + if (rt_no_nulls && rt_text_keys) { + if (!asof_rt_eq_indexed(n_eq, rt_eq)) rt_no_nulls = false; + for (uint32_t k = 0; k < n_eq && rt_no_nulls; k++) + if (join_key_col_scanned(rt_eq[k]) && + !join_key_col_nullfree(rt_eq[k])) rt_no_nulls = false; + } if (asof_hash_group_match(n_eq, lt_eq, rt_eq, eq_xlut, eq_xn, lt_time, rt_time, lt_null, rt_null, left_n, right_n, @@ -3965,7 +4093,12 @@ build_output:; /* Gather left columns — iterate in original row order, preserve nulls */ for (int64_t c = 0; c < left_ncols; c++) { int64_t col_name = ray_table_col_name(left_table, c); - ray_t* src_col = ray_table_get_col_idx(left_table, c); + ray_t* src_col = ray_table_col_idx(left_table, c); + if (src_col && RAY_IS_ERR(src_col)) { + ray_release(out); + out = src_col; + goto window_output_cleanup; + } ray_t* dst_col = join_gather_col_serial(src_col, lidx, out_n); if (!dst_col || RAY_IS_ERR(dst_col)) { ray_release(out); @@ -3985,7 +4118,12 @@ build_output:; for (int64_t rc = 0; rc < right_out_count; rc++) { int64_t cidx = right_out_idx[rc]; int64_t col_name = ray_table_col_name(right_table, cidx); - ray_t* src_col = ray_table_get_col_idx(right_table, cidx); + ray_t* src_col = ray_table_col_idx(right_table, cidx); + if (src_col && RAY_IS_ERR(src_col)) { + ray_release(out); + out = src_col; + goto window_output_cleanup; + } ray_t* dst_col = join_gather_col_serial(src_col, ridx, out_n); if (!dst_col || RAY_IS_ERR(dst_col)) { ray_release(out); diff --git a/src/ops/journal.c b/src/ops/journal.c index 34074284c..177e75ca9 100644 --- a/src/ops/journal.c +++ b/src/ops/journal.c @@ -206,14 +206,16 @@ ray_t* ray_log_roll_fn(ray_t** args, int64_t n) { } ray_t* ray_log_snapshot_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".log.snapshot takes no arguments"); if (!ray_journal_is_open()) return ray_error("domain", ".log.snapshot: no journal open"); return err_to_ray(ray_journal_snapshot(), "io"); } ray_t* ray_log_sync_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".log.sync takes no arguments"); return err_to_ray(ray_journal_sync(), "io"); } diff --git a/src/ops/linkop.c b/src/ops/linkop.c index ac1af1611..952d97c62 100644 --- a/src/ops/linkop.c +++ b/src/ops/linkop.c @@ -64,8 +64,8 @@ ray_t* ray_link_attach(ray_t** vp, int64_t target_sym_id) { * non-parted dim). */ int64_t tcols = ray_table_ncols(target); for (int64_t c = 0; c < tcols; c++) { - ray_t* tcol = ray_table_get_col_idx(target, c); - if (tcol && RAY_IS_PARTED(tcol->type)) + ray_col_meta_t tm; + if (ray_table_col_meta_idx(target, c, &tm) && RAY_IS_PARTED(tm.type)) return ray_error("nyi", "link: target table has a parted column (%d); " "link targets must be non-parted (in-memory or splayed) tables", @@ -151,15 +151,16 @@ ray_t* ray_link_deref(ray_t* v, int64_t sym_id) { * list of segment pointers — straight-byte indexing is meaningless). */ int64_t tcols = ray_table_ncols(target_tab); for (int64_t c = 0; c < tcols; c++) { - ray_t* tcol = ray_table_get_col_idx(target_tab, c); - if (tcol && RAY_IS_PARTED(tcol->type)) + ray_col_meta_t tm; + if (ray_table_col_meta_idx(target_tab, c, &tm) && RAY_IS_PARTED(tm.type)) return ray_error("nyi", "link deref: target table has a parted column (%d); " "links to parted dim tables are not supported in v1", (int)c); } - ray_t* target_col = ray_table_get_col(target_tab, sym_id); + ray_t* target_col = ray_table_col(target_tab, sym_id); + if (target_col && RAY_IS_ERR(target_col)) return target_col; if (!target_col) return NULL; int64_t n = v->len; @@ -246,7 +247,7 @@ ray_t* ray_link_deref(ray_t* v, int64_t sym_id) { if (ray_vec_is_null(result, i)) d[i] = NULL_F64; break; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(result); for (int64_t i = 0; i < n; i++) if (ray_vec_is_null(result, i)) d[i] = NULL_I64; diff --git a/src/ops/ops.h b/src/ops/ops.h index 1c1955dcd..cf3fc68d3 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -34,6 +34,10 @@ extern "C" { /* ===== Internal Type Constants ===== */ #define RAY_SEL 14 /* selection bitmap (lazy filter) */ +/* Encoded (generation-2) column held by a table slot: payload is one + * pointer to a refcounted ray_enccol_t (src/store/enccol.h). Never seen + * outside the store layer, the table accessors and the aware paths. */ +#define RAY_ENCCOL 15 /* Lazy DAG handle (atom-only; stored inline in aux region) */ #define RAY_LAZY 104 @@ -57,6 +61,11 @@ static inline bool ray_is_lazy(ray_t* x) { ray_t* ray_lazy_materialize(ray_t* val); ray_t* ray_lazy_append_param(ray_t* lazy, uint16_t opcode, int64_t param); +bool ray_has_timespan(const ray_t* x); +int8_t ray_timespan_binary_type(uint16_t op, int8_t a, int8_t b); +ray_t* ray_timespan_binary(uint16_t op, ray_t* a, ray_t* b); +ray_t* ray_timespan_xbar(ray_t* values, ray_t* width); + /* ===== Cancel API ===== */ void ray_cancel(void); @@ -232,6 +241,11 @@ void ray_cancel_reset(void); #define OP_BOT_N 90 /* per-group smallest K values (bounded min-heap) */ #define OP_QUANTILE 91 /* exact quantile per group (literal probability) */ #define OP_MODE 145 /* most frequent non-null value per group */ +/* Internal aggregate, never compiled from Rayfall: the non-null count of its + * input (the per-partition AVG/VAR divisor). The v2 engine counts it in + * place (agg_stream.c); a group bound for the legacy engine is re-planned + * with the slot as SUM over a not-null indicator (exec_group_run). */ +#define OP_COUNT_NN 147 #define OP_ALL 131 /* truthy-all reduction (nulls skipped) */ #define OP_ANY 132 /* truthy-any reduction (nulls skipped) */ #define OP_COV 133 /* population covariance per group (binary input) */ @@ -262,7 +276,7 @@ static inline bool agg_type_admitted(uint16_t op, int8_t t) { * wrappers (e.g. RAY_MAPCOMMON) and out_type==0 to the runtime so a * plan-time guard never false-rejects a column it can't classify. */ bool nonnum = (t == RAY_SYM || t == RAY_STR || t == RAY_GUID); - bool temporal = (t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP); + bool temporal = (t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_TIMESPAN); switch (op) { /* sum: numeric + TIME (duration-like ms count). SYM/STR/GUID and the * absolute temporals DATE/TIMESTAMP are meaningless to sum → reject. */ @@ -516,6 +530,7 @@ typedef struct ray_graph { uint32_t ext_count; /* number of extended nodes */ uint32_t ext_cap; /* capacity of ext_nodes array */ ray_t* selection; /* RAY_SEL bitmap — lazy filter (NULL = all pass) */ + struct ray_col_binds_s* binds; /* sources bound by this execution (ops/colbind.c) */ /* Slice-group hint (FILTER(in/eq on c) + GROUP(by c) fusion). * Armed by ray_slice_group_probe (exec.c) INSTEAD of executing the @@ -605,6 +620,11 @@ typedef struct ray_graph { * retry, since the interpreter's `if` tests one truth value and would * write the then-branch to every row. */ bool if_refused; + + /* Set by exec_group_parted around an in-place concat group: the + * table's parted columns are grouped from their segments (no flatten); + * exec_group_run skips its parted dispatch. */ + bool grp_seg_stream; } ray_graph_t; /* ===== Morsel Iterator ===== */ @@ -969,6 +989,18 @@ ray_op_t* ray_graph_input_vec(ray_graph_t* g, ray_t* vec); ray_t* ray_lazy_wrap(ray_graph_t* g, ray_op_t* op); ray_t* ray_lazy_append(ray_t* lazy, uint16_t opcode); +/* Column-reference lazy: (at tbl 'col) of an encoded slot. A RAY_LAZY header + * with RAY_LAZY_COLREF in attrs and no graph (GRAPH / OP slots NULL); its + * data holds the retained table and the column sym. The aggregate builtins + * answer it on the bound source; ray_lazy_append / ray_lazy_materialize and + * every other reader of the lazy slots promote or force it first. */ +#define RAY_LAZY_COLREF 0x01 +ray_t* ray_lazy_colref(ray_t* tbl, int64_t sym); /* retains tbl */ +bool ray_lazy_colref_get(ray_t* lazy, ray_t** tbl, int64_t* sym); /* borrowed */ +/* Turn a column reference into the OP_SCAN graph it stands for, in place; + * a no-op for any other lazy. NULL or an owned error. */ +ray_t* ray_lazy_promote(ray_t* lazy); + /* Active query from-table during tree-walk evaluation of query expressions * (B3 Part 2). Set by bind_all_columns while a query's columns are mounted * in the local env, cleared/restored on scope pop. The evaluator consults diff --git a/src/ops/opt.c b/src/ops/opt.c index cfacce669..527d71355 100644 --- a/src/ops/opt.c +++ b/src/ops/opt.c @@ -28,6 +28,7 @@ #include "vec/vec.h" #include "opt.h" #include "idiom.h" +#include "table/table.h" /* ray_table_col_meta */ #include "core/profile.h" #include "mem/heap.h" #include @@ -37,6 +38,10 @@ /* Forward declaration — defined below, used by type inference and DCE passes. */ ray_op_ext_t* find_ext(ray_graph_t* g, uint32_t node_id); +/* Shared resolved-expression dependency proof (exec.c/internal.h). Keep + * the optimizer's local edge accessors rather than including internal.h. */ +bool ray_expr_subset_invariant(ray_graph_t* g, uint32_t root_id); + /* Shared 32-byte node allocator (graph.c). Forwarded by graph_alloc_node_opt; * node ids are realloc-stable so no pointer fixups are needed. */ ray_op_t* graph_alloc_node(ray_graph_t* g); @@ -161,6 +166,11 @@ static void pass_type_inference(ray_graph_t* g, ray_op_t* root) { for (uint32_t a = 0; a < ext->n_aggs; a++) if (op_node(g, ext->agg_ins[a]) && !visited[ext->agg_ins[a]] && sp < (int)stack_cap) stack[sp++] = ext->agg_ins[a]; + /* Second inputs of binary aggs (wsum/wavg/cov/pearson). */ + if (ext->agg_ins2) + for (uint32_t a = 0; a < ext->n_aggs; a++) + if (op_node(g, ext->agg_ins2[a]) && !visited[ext->agg_ins2[a]] && sp < (int)stack_cap) + stack[sp++] = ext->agg_ins2[a]; break; case OP_SORT: case OP_SELECT: @@ -480,17 +490,16 @@ static bool fold_binary_const(ray_graph_t* g, ray_op_t* node) { case OP_SUB: r = lv - rv; break; case OP_MUL: r = lv * rv; break; case OP_MOD: - if (rv == 0.0f) r = NULL_F32; - else { - r = fmodf(lv, rv); - if (r != 0.0f && ((r > 0.0f) != (rv > 0.0f))) r += rv; - } + if (rv == 0.0f) return false; /* 0Nf at run time */ + r = fmodf(lv, rv); + if (r != 0.0f && ((r > 0.0f) != (rv > 0.0f))) r += rv; break; case OP_MIN2: r = lv < rv ? lv : rv; break; case OP_MAX2: r = lv > rv ? lv : rv; break; default: return false; } - folded = ray_f32(isfinite(r) ? r : NULL_F32); + if (!isfinite(r)) return false; /* see the F64 arm */ + folded = ray_f32(r); break; } case RAY_F64: { @@ -501,8 +510,11 @@ static bool fold_binary_const(ray_graph_t* g, ray_op_t* node) { case OP_ADD: r = lv + rv; break; case OP_SUB: r = lv - rv; break; case OP_MUL: r = lv * rv; break; - case OP_DIV: r = lv / rv; break; /* IEEE 754: ±Inf or NaN */ - case OP_MOD: r = fmod(lv, rv); break; /* IEEE 754: NaN for rv==0 */ + case OP_DIV: r = lv / rv; break; + case OP_MOD: + r = fmod(lv, rv); + if (r != 0.0 && ((r > 0.0) != (rv > 0.0))) r += rv; + break; case OP_POW: if (!pow_atom_type_admitted(le->literal) || !pow_atom_type_admitted(re->literal)) @@ -513,6 +525,10 @@ static bool fold_binary_const(ray_graph_t* g, ray_op_t* node) { case OP_MAX2: r = fmax(lv, rv); break; /* NaN-propagating */ default: return false; } + /* A non-finite result (x/0, overflow) is 0Nf at run time; a + * folded constant would carry Inf/NaN without its null flag, + * so leave it to the kernels. */ + if (!isfinite(r)) return false; folded = ray_f64(r); break; } @@ -524,11 +540,17 @@ static bool fold_binary_const(ray_graph_t* g, ray_op_t* node) { case OP_ADD: r = (int64_t)((uint64_t)lv + (uint64_t)rv); break; case OP_SUB: r = (int64_t)((uint64_t)lv - (uint64_t)rv); break; case OP_MUL: r = (int64_t)((uint64_t)lv * (uint64_t)rv); break; + /* A zero divisor (or INT64_MIN / -1) is 0Nl at run time: + * leave it to the kernels rather than fold a 0. */ case OP_DIV: - r = (rv != 0 && !(lv == INT64_MIN && rv == -1)) ? lv / rv : 0; + if (rv == 0 || (lv == INT64_MIN && rv == -1)) return false; + r = lv / rv; + if (r * rv != lv && ((lv < 0) != (rv < 0))) r--; break; case OP_MOD: - r = (rv != 0 && !(lv == INT64_MIN && rv == -1)) ? lv % rv : 0; + if (rv == 0 || (lv == INT64_MIN && rv == -1)) return false; + r = lv % rv; + if (r != 0 && ((r ^ rv) < 0)) r += rv; break; case OP_MIN2: r = lv < rv ? lv : rv; break; case OP_MAX2: r = lv > rv ? lv : rv; break; @@ -566,10 +588,14 @@ static bool fold_binary_const(ray_graph_t* g, ray_op_t* node) { case OP_SUB: r = (int32_t)((uint32_t)lv - (uint32_t)rv); break; case OP_MUL: r = (int32_t)((uint32_t)lv * (uint32_t)rv); break; case OP_DIV: - r = (rv != 0 && !(lv == INT32_MIN && rv == -1)) ? lv / rv : 0; + if (rv == 0 || (lv == INT32_MIN && rv == -1)) return false; + r = lv / rv; + if (r * rv != lv && ((lv < 0) != (rv < 0))) r--; break; case OP_MOD: - r = (rv != 0 && !(lv == INT32_MIN && rv == -1)) ? lv % rv : 0; + if (rv == 0 || (lv == INT32_MIN && rv == -1)) return false; + r = lv % rv; + if (r != 0 && ((r ^ rv) < 0)) r += rv; break; case OP_MIN2: r = lv < rv ? lv : rv; break; case OP_MAX2: r = lv > rv ? lv : rv; break; @@ -778,6 +804,11 @@ static void pass_constant_fold(ray_graph_t* g, ray_op_t* root) { for (uint32_t a = 0; a < ext->n_aggs; a++) if (op_node(g, ext->agg_ins[a]) && !visited[ext->agg_ins[a]] && sp < (int)stack_cap) stack[sp++] = ext->agg_ins[a]; + /* Second inputs of binary aggs (wsum/wavg/cov/pearson). */ + if (ext->agg_ins2) + for (uint32_t a = 0; a < ext->n_aggs; a++) + if (op_node(g, ext->agg_ins2[a]) && !visited[ext->agg_ins2[a]] && sp < (int)stack_cap) + stack[sp++] = ext->agg_ins2[a]; break; case OP_SORT: case OP_SELECT: @@ -924,6 +955,13 @@ static void mark_live(ray_graph_t* g, ray_op_t* root, bool* live) { if (op_node(g, ext->agg_ins[a]) && !live[ext->agg_ins[a]] && sp < (int)stack_cap) stack[sp++] = ext->agg_ins[a]; } + /* Second inputs of binary aggs: an expression + * referenced only here must stay live. */ + if (ext->agg_ins2) + for (uint32_t a = 0; a < ext->n_aggs; a++) { + if (op_node(g, ext->agg_ins2[a]) && !live[ext->agg_ins2[a]] && sp < (int)stack_cap) + stack[sp++] = ext->agg_ins2[a]; + } break; case OP_SORT: case OP_SELECT: @@ -1599,11 +1637,44 @@ static int filter_rank_key(ray_graph_t* g, ray_op_t* pred) { return filter_selectivity_rank(g, pred) * 100 + filter_cost(g, pred); } -/* Split FILTER(AND(a, b), input) into FILTER(a, FILTER(b, input)). +/* A reorderable filter run must stay in the default table's row domain. + * Filters preserve schema; an unsafe predicate may be an immovable barrier + * inside this ancestry. Do not infer correspondence through a group, join, + * projection, order/position change, or a registered secondary scan. */ +bool filter_input_default_domain(ray_graph_t* g, uint32_t id) { + if (!g || !g->nodes) return false; + uint32_t budget = g->node_count; + while (budget--) { + if (id >= g->node_count) return false; + ray_op_t* n = &g->nodes[id]; + if (n->id != id || (n->flags & OP_FLAG_DEAD)) return false; + if (n->opcode == OP_FILTER) { + if (n->arity != 2 || n->in_id[1] >= g->node_count) return false; + id = n->in_id[0]; + } else if (n->opcode == OP_ALIAS || n->opcode == OP_MATERIALIZE) { + if (n->arity != 1) return false; + id = n->in_id[0]; + } else if (n->opcode == OP_SCAN) { + return ray_expr_subset_invariant(g, id); + } else if (n->opcode == OP_CONST) { + ray_op_ext_t* x = find_ext(g, id); + return n->arity == 0 && x && g->table && + g->table->type == RAY_TABLE && x->literal == g->table; + } else { + return false; + } + } + return false; /* cyclic or unproved ancestry */ +} + +/* Split FILTER(AND(a, b), input) into FILTER(b, FILTER(a, input)) only + * when both complete limbs preserve verdicts under a source-row subset. * Returns the new outer filter node, or the original if no split. */ static ray_op_t* split_and_filter(ray_graph_t* g, ray_op_t* filter_node) { if (!filter_node || filter_node->opcode != OP_FILTER) return filter_node; - if (filter_node->arity != 2) return filter_node; + if (filter_node->arity != 2 || + filter_node->in_id[0] >= g->node_count || + filter_node->in_id[1] >= g->node_count) return filter_node; ray_op_t* pred = op_child(g, filter_node, 1); if (!pred || pred->opcode != OP_AND || pred->arity != 2) return filter_node; @@ -1620,6 +1691,8 @@ static ray_op_t* split_and_filter(ray_graph_t* g, ray_op_t* filter_node) { * on an agg-output ref, row-count mismatch on a key ref). Left intact, the * single FILTER(AND, GROUP) is handled correctly by the HAVING fusion. */ if (input->opcode == OP_GROUP) return filter_node; + if (!filter_input_default_domain(g, input->id) || + !ray_expr_subset_invariant(g, pred->id)) return filter_node; /* Save IDs before potential realloc */ uint32_t filter_id = filter_node->id; @@ -1657,8 +1730,15 @@ static ray_op_t* split_and_filter(ray_graph_t* g, ray_op_t* filter_node) { static int collect_filter_chain(ray_graph_t* g, ray_op_t* top, ray_op_t** chain, int max) { int n = 0; ray_op_t* cur = top; + if (!top || !filter_input_default_domain(g, top->id)) return 0; while (cur && cur->opcode == OP_FILTER && !(cur->flags & OP_FLAG_PUSHED) && n < max) { + if ((cur->flags & OP_FLAG_DEAD) || cur->arity != 2 || + cur->in_id[0] >= g->node_count || + cur->in_id[1] >= g->node_count || + !ray_expr_subset_invariant(g, cur->in_id[1])) break; + /* Stop BEFORE the unsafe predicate: it is a domain barrier, not + * an expensive predicate that may be sorted across its neighbors. */ chain[n++] = cur; cur = op_child(g, cur, 0); } @@ -1834,6 +1914,12 @@ static bool pass_projection_pushdown(ray_graph_t* g, ray_op_t* root) { live[ext->agg_ins[a]] = true; if (qt < (int)nc) q[qt++] = ext->agg_ins[a]; } + if (ext->agg_ins2) + for (uint32_t a = 0; a < ext->n_aggs; a++) + if (op_node(g, ext->agg_ins2[a]) && !live[ext->agg_ins2[a]]) { + live[ext->agg_ins2[a]] = true; + if (qt < (int)nc) q[qt++] = ext->agg_ins2[a]; + } break; case OP_SORT: case OP_SELECT: @@ -1935,6 +2021,166 @@ static bool pass_projection_pushdown(ray_graph_t* g, ray_op_t* root) { * est_rows=1 to hint that most partitions can be skipped at execution time. * -------------------------------------------------------------------------- */ +/* Partitions whose key passes `key cmp_op lit` (`lit cmp_op key` when + * swapped) set their bit in `mask` (key_values->len bits, zeroed by the + * caller). False when the comparison cannot prune — a type-class mismatch, + * an unsupported literal, or an allocation failure — and every partition + * must then be kept. Shared by the partition-pruning pass and select's + * pre-fetch pruning of a parted source. */ +bool ray_part_prune_mask(ray_t* key_values, uint16_t cmp_op, bool swapped, + ray_t* lit, uint64_t* mask) { + int64_t n_parts = key_values->len; + /* Type-class check: partition keys and the literal must live in + * the same value namespace, otherwise comparisons are nonsense. + * - SYM keys are interned IDs; they can only be compared to + * SYM set elements. + * - int-family keys (I16/I32/I64/DATE/TIME/TIMESTAMP/BOOL/U8) + * compare only to other int-family values. + * - mixing the two is always wrong at the raw-bits level, + * so skip pruning (the executor filter still runs). */ + int8_t pkey_t = key_values->type; + int8_t lit_base = lit->type < 0 ? (int8_t)(-lit->type) : lit->type; + bool pkey_is_sym = (pkey_t == RAY_SYM); + bool lit_is_sym = (lit_base == RAY_SYM); + if (pkey_is_sym != lit_is_sym) return false; + /* Raw partition ids have no lexical ordering (#738). Let the + * domain-aware predicate executor select these rows instead. */ + if (pkey_is_sym && (cmp_op == OP_LT || cmp_op == OP_LE || + cmp_op == OP_GT || cmp_op == OP_GE)) + return false; + + /* OP_IN / OP_NOT_IN expects a literal vector const on the RHS. + * For the scalar ops, the const is a single atom or 1-elem vec. */ + bool is_in = (cmp_op == OP_IN); + bool is_nin = (cmp_op == OP_NOT_IN); + + /* For IN/NOT_IN the scan must be the LHS (col IN set), not + * swapped — we never pruned on `const IN col_set` anyway. */ + if ((is_in || is_nin) && swapped) return false; + + /* Extract constant(s) for comparison. Scalar ops take one + * value; IN ops take an array of values read from the vec + * literal. We normalize all values to int64_t (which covers + * I64, TIMESTAMP, SYM interned IDs, and sign-extended I32/ + * DATE/TIME). Atoms store the value in the header; vectors + * store it in data. */ + int64_t const_val = 0; /* for scalar ops */ + int64_t set_stack[32]; + int64_t* set_vals = set_stack; /* for IN/NOT_IN */ + int64_t set_len = 0; + ray_t* set_heap = NULL; + + int8_t lt = lit->type < 0 ? (int8_t)(-lit->type) : lit->type; + bool narrow32 = (lt == RAY_I32 || lt == RAY_DATE || lt == RAY_TIME); + bool wide64 = (lt == RAY_I64 || lt == RAY_TIMESTAMP || lt == RAY_SYM); + if (!narrow32 && !wide64) + return false; /* unsupported type for partition pruning */ + + if (is_in || is_nin) { + /* Literal must be a vector (ray_const_vec carries the vec + * pointer unchanged in ext->literal). */ + if (lit->type <= 0) return false; + set_len = lit->len; + if (set_len <= 0) { + /* Empty set: for IN no partition can match → mask stays 0 + * (the caller skips every segment). For + * NOT_IN every partition passes → set all bits. */ + if (is_nin) { + for (int64_t p = 0; p < n_parts; p++) + mask[p / 64] |= (1ULL << (p % 64)); + } + return true; + } + if (set_len > 32) { + set_heap = ray_alloc((size_t)set_len * sizeof(int64_t)); + if (!set_heap) return false; + set_vals = (int64_t*)ray_data(set_heap); + } + /* Read set elements — skip nulls in the literal so a null + * sentinel can never match a partition key. */ + int64_t next = 0; + bool set_has_nulls = ray_vec_may_have_nulls(lit); + for (int64_t i = 0; i < set_len; i++) { + if (set_has_nulls && ray_vec_is_null(lit, i)) continue; + if (narrow32) { + int32_t v32; + memcpy(&v32, (char*)ray_data(lit) + i * sizeof(int32_t), sizeof(int32_t)); + set_vals[next++] = v32; + } else { + int64_t v64; + memcpy(&v64, (char*)ray_data(lit) + i * sizeof(int64_t), sizeof(int64_t)); + set_vals[next++] = v64; + } + } + set_len = next; + /* Also handle the degenerate case where all set elements + * were null — treat like empty set. */ + if (set_len == 0) { + if (is_nin) { + for (int64_t p = 0; p < n_parts; p++) + mask[p / 64] |= (1ULL << (p % 64)); + } + if (set_heap) ray_free(set_heap); + return true; + } + } else { + /* Scalar const path (EQ/NE/LT/GT/LE/GE). */ + if (wide64) { + if (lit->type < 0) const_val = lit->i64; + else memcpy(&const_val, ray_data(lit), sizeof(int64_t)); + } else { + int32_t v32; + if (lit->type < 0) v32 = lit->i32; + else memcpy(&v32, ray_data(lit), sizeof(int32_t)); + const_val = v32; + } + } + + /* Effective comparison: if swapped, reverse direction + * (IN/NOT_IN are never swapped — gated above). */ + uint16_t eff_op = cmp_op; + if (swapped) { + if (cmp_op == OP_LT) eff_op = OP_GT; + else if (cmp_op == OP_GT) eff_op = OP_LT; + else if (cmp_op == OP_LE) eff_op = OP_GE; + else if (cmp_op == OP_GE) eff_op = OP_LE; + } + + for (int64_t p = 0; p < n_parts; p++) { + int64_t pkey = 0; + if (key_values->type == RAY_DATE || key_values->type == RAY_I32 || key_values->type == RAY_TIME) { + int32_t v32; + memcpy(&v32, (char*)ray_data(key_values) + p * sizeof(int32_t), sizeof(int32_t)); + pkey = v32; + } else { + memcpy(&pkey, (char*)ray_data(key_values) + p * sizeof(int64_t), sizeof(int64_t)); + } + + bool pass = false; + if (is_in || is_nin) { + bool found = false; + for (int64_t j = 0; j < set_len; j++) { + if (pkey == set_vals[j]) { found = true; break; } + } + pass = is_in ? found : !found; + } else { + switch (eff_op) { + case OP_EQ: pass = (pkey == const_val); break; + case OP_NE: pass = (pkey != const_val); break; + case OP_LT: pass = (pkey < const_val); break; + case OP_GT: pass = (pkey > const_val); break; + case OP_LE: pass = (pkey <= const_val); break; + case OP_GE: pass = (pkey >= const_val); break; + default: break; + } + } + if (pass) + mask[p / 64] |= (1ULL << (p % 64)); + } + if (set_heap) ray_free(set_heap); + return true; +} + static void pass_partition_pruning(ray_graph_t* g, ray_op_t* root) { if (!g || !root) return; (void)root; @@ -1981,8 +2227,11 @@ static void pass_partition_pruning(ray_graph_t* g, ray_op_t* root) { tbl = g->table; if (!tbl) continue; - ray_t* mc_col = ray_table_get_col(tbl, scan_ext->sym); - if (!mc_col || mc_col->type != RAY_MAPCOMMON) continue; + ray_col_meta_t mm; + if (!ray_table_col_meta(tbl, scan_ext->sym, &mm) || mm.type != RAY_MAPCOMMON) continue; + ray_t* mc_col = ray_table_col(tbl, scan_ext->sym); /* MAPCOMMON: plain slot, no decode */ + if (!mc_col) continue; + if (RAY_IS_ERR(mc_col)) { ray_error_free(mc_col); continue; } /* Extract constant value */ ray_op_ext_t* const_ext = find_ext(g, const_node->id); @@ -1997,164 +2246,14 @@ static void pass_partition_pruning(ray_graph_t* g, ray_op_t* root) { int64_t n_parts = key_values->len; if (n_parts <= 0) continue; - /* Type-class check: partition keys and the literal must live in - * the same value namespace, otherwise comparisons are nonsense. - * - SYM keys are interned IDs; they can only be compared to - * SYM set elements. - * - int-family keys (I16/I32/I64/DATE/TIME/TIMESTAMP/BOOL/U8) - * compare only to other int-family values. - * - mixing the two is always wrong at the raw-bits level, - * so skip pruning (the executor filter still runs). */ - int8_t pkey_t = key_values->type; - int8_t lit_base = lit->type < 0 ? (int8_t)(-lit->type) : lit->type; - bool pkey_is_sym = (pkey_t == RAY_SYM); - bool lit_is_sym = (lit_base == RAY_SYM); - if (pkey_is_sym != lit_is_sym) { - continue; - } - /* Raw partition ids have no lexical ordering (#738). Let the - * domain-aware predicate executor select these rows instead. */ - if (pkey_is_sym && (cmp_op == OP_LT || cmp_op == OP_LE || - cmp_op == OP_GT || cmp_op == OP_GE)) - continue; - /* Allocate seg_mask bitmap */ uint32_t n_words = (uint32_t)((n_parts + 63) / 64); uint64_t* mask = (uint64_t*)ray_calloc_raw(n_words * sizeof(uint64_t)); if (!mask) continue; - - /* OP_IN / OP_NOT_IN expects a literal vector const on the RHS. - * For the scalar ops, the const is a single atom or 1-elem vec. */ - bool is_in = (cmp_op == OP_IN); - bool is_nin = (cmp_op == OP_NOT_IN); - - /* For IN/NOT_IN the scan must be the LHS (col IN set), not - * swapped — we never pruned on `const IN col_set` anyway. */ - if ((is_in || is_nin) && swapped) { ray_free_raw(mask); continue; } - - /* Extract constant(s) for comparison. Scalar ops take one - * value; IN ops take an array of values read from the vec - * literal. We normalize all values to int64_t (which covers - * I64, TIMESTAMP, SYM interned IDs, and sign-extended I32/ - * DATE/TIME). Atoms store the value in the header; vectors - * store it in data. */ - int64_t const_val = 0; /* for scalar ops */ - int64_t set_stack[32]; - int64_t* set_vals = set_stack; /* for IN/NOT_IN */ - int64_t set_len = 0; - ray_t* set_heap = NULL; - - int8_t lt = lit->type < 0 ? (int8_t)(-lit->type) : lit->type; - bool narrow32 = (lt == RAY_I32 || lt == RAY_DATE || lt == RAY_TIME); - bool wide64 = (lt == RAY_I64 || lt == RAY_TIMESTAMP || lt == RAY_SYM); - if (!narrow32 && !wide64) { + if (!ray_part_prune_mask(key_values, cmp_op, swapped, lit, mask)) { ray_free_raw(mask); - continue; /* unsupported type for partition pruning */ - } - - if (is_in || is_nin) { - /* Literal must be a vector (ray_const_vec carries the vec - * pointer unchanged in ext->literal). */ - if (lit->type <= 0) { ray_free_raw(mask); continue; } - set_len = lit->len; - if (set_len <= 0) { - /* Empty set: for IN no partition can match → mask stays 0 - * and we attach it below (skipping all segments). For - * NOT_IN every partition passes → set all bits. */ - if (is_nin) { - for (int64_t p = 0; p < n_parts; p++) - mask[p / 64] |= (1ULL << (p % 64)); - } - goto attach_mask; - } - if (set_len > 32) { - set_heap = ray_alloc((size_t)set_len * sizeof(int64_t)); - if (!set_heap) { ray_free_raw(mask); continue; } - set_vals = (int64_t*)ray_data(set_heap); - } - /* Read set elements — skip nulls in the literal so a null - * sentinel can never match a partition key. */ - int64_t next = 0; - bool set_has_nulls = ray_vec_may_have_nulls(lit); - for (int64_t i = 0; i < set_len; i++) { - if (set_has_nulls && ray_vec_is_null(lit, i)) continue; - if (narrow32) { - int32_t v32; - memcpy(&v32, (char*)ray_data(lit) + i * sizeof(int32_t), sizeof(int32_t)); - set_vals[next++] = v32; - } else { - int64_t v64; - memcpy(&v64, (char*)ray_data(lit) + i * sizeof(int64_t), sizeof(int64_t)); - set_vals[next++] = v64; - } - } - set_len = next; - /* Also handle the degenerate case where all set elements - * were null — treat like empty set. */ - if (set_len == 0) { - if (is_nin) { - for (int64_t p = 0; p < n_parts; p++) - mask[p / 64] |= (1ULL << (p % 64)); - } - if (set_heap) ray_free(set_heap); - goto attach_mask; - } - } else { - /* Scalar const path (EQ/NE/LT/GT/LE/GE). */ - if (wide64) { - if (lit->type < 0) const_val = lit->i64; - else memcpy(&const_val, ray_data(lit), sizeof(int64_t)); - } else { - int32_t v32; - if (lit->type < 0) v32 = lit->i32; - else memcpy(&v32, ray_data(lit), sizeof(int32_t)); - const_val = v32; - } - } - - /* Effective comparison: if swapped, reverse direction - * (IN/NOT_IN are never swapped — gated above). */ - uint16_t eff_op = cmp_op; - if (swapped) { - if (cmp_op == OP_LT) eff_op = OP_GT; - else if (cmp_op == OP_GT) eff_op = OP_LT; - else if (cmp_op == OP_LE) eff_op = OP_GE; - else if (cmp_op == OP_GE) eff_op = OP_LE; - } - - for (int64_t p = 0; p < n_parts; p++) { - int64_t pkey = 0; - if (key_values->type == RAY_DATE || key_values->type == RAY_I32 || key_values->type == RAY_TIME) { - int32_t v32; - memcpy(&v32, (char*)ray_data(key_values) + p * sizeof(int32_t), sizeof(int32_t)); - pkey = v32; - } else { - memcpy(&pkey, (char*)ray_data(key_values) + p * sizeof(int64_t), sizeof(int64_t)); - } - - bool pass = false; - if (is_in || is_nin) { - bool found = false; - for (int64_t j = 0; j < set_len; j++) { - if (pkey == set_vals[j]) { found = true; break; } - } - pass = is_in ? found : !found; - } else { - switch (eff_op) { - case OP_EQ: pass = (pkey == const_val); break; - case OP_NE: pass = (pkey != const_val); break; - case OP_LT: pass = (pkey < const_val); break; - case OP_GT: pass = (pkey > const_val); break; - case OP_LE: pass = (pkey <= const_val); break; - case OP_GE: pass = (pkey >= const_val); break; - default: break; - } - } - if (pass) - mask[p / 64] |= (1ULL << (p % 64)); + continue; } - if (set_heap) ray_free(set_heap); - attach_mask:; /* Attach seg_mask to OP_SCAN nodes reading parted columns from same table. * When !any_active the mask is all-zeros — attach it anyway so the @@ -2173,8 +2272,8 @@ static void pass_partition_pruning(ray_graph_t* g, ray_op_t* root) { memcpy(&sn_tid, sn_ext->base.pad, sizeof(uint16_t)); if (sn_tid != stored_table_id) continue; - ray_t* sn_col = ray_table_get_col(tbl, sn_ext->sym); - if (!sn_col || !RAY_IS_PARTED(sn_col->type)) continue; + ray_col_meta_t sm; + if (!ray_table_col_meta(tbl, sn_ext->sym, &sm) || !RAY_IS_PARTED(sm.type)) continue; if (sn_ext->seg_mask) { /* AND with existing mask (conjunctive filters) */ diff --git a/src/ops/opt.h b/src/ops/opt.h index 5b2cb2a9e..225797d6b 100644 --- a/src/ops/opt.h +++ b/src/ops/opt.h @@ -32,5 +32,9 @@ void redirect_consumers(ray_graph_t* g, uint32_t old_id, ray_op_t* new_target, uint32_t skip_a, uint32_t skip_b); ray_op_ext_t* find_ext(ray_graph_t* g, uint32_t node_id); +/* Partition-key pruning bitmap for one comparison against a literal (see + * opt.c); false when the comparison cannot prune. */ +bool ray_part_prune_mask(ray_t* key_values, uint16_t cmp_op, + bool swapped, ray_t* lit, uint64_t* mask); #endif /* RAY_OPT_H */ diff --git a/src/ops/pivot.c b/src/ops/pivot.c index c75d18b80..f710bc391 100644 --- a/src/ops/pivot.c +++ b/src/ops/pivot.c @@ -27,6 +27,7 @@ #include "ops/hash.h" #include "ops/idxop.h" #include "ops/rowsel.h" +#include "ops/colbind.h" /* ray_graph_unbind_table */ #include "table/domain.h" /* raw vocabulary snapshot for if_sym_side_t */ #include "core/pool.h" #include "lang/format.h" /* ray_type_name (error context) */ @@ -266,6 +267,8 @@ static ray_t* if_eval_branch(ray_graph_t* g, ray_op_t* branch, } g->table = saved_table; g->selection = saved_sel; + /* the branch bound the sub-table's columns on g: drop them with it */ + if (sub != saved_table) ray_graph_unbind_table(g, sub); ray_release(sub); return value; } @@ -1829,8 +1832,8 @@ static inline uint64_t pivot_hash_null_words(uint64_t h, const int64_t* nullw, static int64_t pivot_parted_seg_count(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && RAY_IS_PARTED(col->type)) return col->len; + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && RAY_IS_PARTED(m.type)) return m.n_segs; } return 0; } @@ -1838,8 +1841,9 @@ static int64_t pivot_parted_seg_count(ray_t* tbl) { static bool pivot_table_has_parted_col(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && + (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON)) return true; } return false; @@ -1848,7 +1852,7 @@ static bool pivot_table_has_parted_col(ray_t* tbl) { ray_t* exec_pivot(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { if (!tbl || RAY_IS_ERR(tbl)) return tbl; - /* Parted-input guard: exec_pivot fetches columns via ray_table_get_col and + /* Parted-input guard: exec_pivot fetches columns via ray_table_col and * indexes them by row up to ray_table_nrows. A raw RAY_PARTED/MAPCOMMON * column (whose data is a tiny segs array, not nrows elements) would be * indexed out of bounds → OOB read / SIGSEGV. Flatten (concat all @@ -1917,18 +1921,25 @@ ray_t* exec_pivot(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { for (uint32_t i = 0; i < n_idx; i++) { ray_op_ext_t* ie = find_ext(g, ext->pivot.index_cols[i]); idx_vecs[i] = (ie && ie->base.opcode == OP_SCAN) - ? ray_table_get_col(tbl, ie->sym) : NULL; + ? ray_table_col(tbl, ie->sym) : NULL; + if (idx_vecs[i] && RAY_IS_ERR(idx_vecs[i])) { + ray_t* err = idx_vecs[i]; + scratch_free(key_hdr); + return err; + } if (!idx_vecs[i]) { scratch_free(key_hdr); return ray_error("domain", "pivot: index column not found"); } } ray_op_ext_t* pe = find_ext(g, ext->pivot.pivot_col); ray_t* pcol = (pe && pe->base.opcode == OP_SCAN) - ? ray_table_get_col(tbl, pe->sym) : NULL; + ? ray_table_col(tbl, pe->sym) : NULL; + if (pcol && RAY_IS_ERR(pcol)) { scratch_free(key_hdr); return pcol; } if (!pcol) { scratch_free(key_hdr); return ray_error("domain", "pivot: pivot column not found"); } ray_op_ext_t* ve = find_ext(g, ext->pivot.value_col); ray_t* vcol = (ve && ve->base.opcode == OP_SCAN) - ? ray_table_get_col(tbl, ve->sym) : NULL; + ? ray_table_col(tbl, ve->sym) : NULL; + if (vcol && RAY_IS_ERR(vcol)) { scratch_free(key_hdr); return vcol; } if (!vcol) { scratch_free(key_hdr); return ray_error("domain", "pivot: value column not found"); } if (nrows == 0) { scratch_free(key_hdr); return ray_table_new(0); } diff --git a/src/ops/query.c b/src/ops/query.c index 390eba172..1c29bf0ce 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -31,24 +31,30 @@ #include "lang/env.h" #include "ops/ops.h" #include "ops/internal.h" +#include "ops/colbind.h" /* ray_col_bind_declines — the count fast path binds */ #include "ops/hash.h" #include "ops/glob.h" /* ray_strpat — str-find in the derived-key program */ #include "ops/idxop.h" /* ray_index_kind / RAY_IDX_DICT — dict-code row_gid */ #include "ops/agg_engine.h" /* agg_select_distinct — dict-linked pure-distinct path */ #include "core/runtime.h" /* __VM — per-thread query/eval context */ #include "ops/rowsel.h" +#include "ops/opt.h" /* ray_part_prune_mask — select prunes partitions before fetch */ #include "store/col.h" /* ray_col_want_rows — group-gather read-ahead */ #include "core/pool.h" /* ray_pool_dispatch — the route gate's sampled gather */ #include "ops/fused_group.h" #include "ops/fused_topk.h" #include "ops/hll.h" #include "ops/cdfuse.h" /* ray_cd_fused — fused grouped count-distinct */ +#include "ops/colgather.h" /* ray_col_gather_span — a key evaluated piece by piece */ #include "ops/temporal.h" #include "core/profile.h" #include "table/sym.h" #include "table/domain.h" #include "table/dict.h" +#include "store/enccol.h" /* ray_enccol_adopt_domain — empty columns of encoded SYM */ +#include "store/enceval.h" /* ray_enc_count_cmp — the count fast path on views */ #include "mem/heap.h" +#include "mem/arena.h" /* the views of a compressed vocabulary (dk_chunk_views) */ #include #include @@ -194,6 +200,7 @@ static ray_t* groups_to_pair_list(ray_t* d) { case RAY_SYM: k = ray_sym(sym_cell_runtime_id(keys, i)); break; case RAY_I64: case RAY_TIMESTAMP: k = ray_i64(((int64_t*)base)[i]); break; + case RAY_TIMESPAN: k = ray_timespan(((int64_t*)base)[i]); break; case RAY_I32: case RAY_DATE: case RAY_TIME: k = ray_i32(((int32_t*)base)[i]); break; @@ -312,6 +319,64 @@ static bool dag_pow_type_admitted(int8_t t) { return dag_numeric_type_admitted(t); } +/* The arithmetic unary verbs' kernels read any fixed-width lane as a + * number, while their builtins (arith.c) take a narrower set: a DATE, + * TIME or TIMESTAMP column came back negated, square-rooted or rounded as + * its raw day / millisecond / nanosecond counts where `(neg dates)` + * raises `type` (#854), and SYM or GUID columns were read as interned ids + * or bytes. `neg`/`abs` also reject BOOL and U8, and the integer lanes of + * `ceil`/`floor`/`round` returned garbage where the builtin is the + * identity (round: the value as F64); compile_expr_dag lowers those to + * the operand and to a cast (dag_int_rounding below). An operand outside + * the builtin's set declines to the evaluator, which applies the builtin + * itself. */ +static bool dag_unary_arith_type_admitted(const char* name, size_t len, int8_t t) { + if (t <= 0) return true; /* unknown/uninferred: let executor validate */ + if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); + if (len == 3 && (memcmp(name, "neg", 3) == 0 || memcmp(name, "abs", 3) == 0)) + return t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_F32 || t == RAY_F64; + if ((len == 3 && (memcmp(name, "exp", 3) == 0 || memcmp(name, "log", 3) == 0)) || + (len == 4 && memcmp(name, "sqrt", 4) == 0)) + return dag_numeric_type_admitted(t); + if ((len == 4 && memcmp(name, "ceil", 4) == 0) || + (len == 5 && (memcmp(name, "floor", 5) == 0 || memcmp(name, "round", 5) == 0))) + return t == RAY_F32 || t == RAY_F64; + return true; +} + +/* `ceil`/`floor`/`round` of an integer operand (BOOL, U8, I16, I32, I64, + * as the builtins' is_numeric takes them): ceil and floor are the identity, + * type and nulls kept, and round is the value as F64, a null becoming 0Nf + * as `(as 'F64 x)` does. The DAG computes both without a kernel: the + * operand node itself, or a cast to F64. NULL for any other verb or + * operand type, which the regular admission then handles; a literal + * operand is left to it as well (the evaluator folds it, where a cast + * of an atom has no vector to run on). The identity is taken only over + * a column or an I64 operand: the fused kernels compute narrower integer + * arithmetic in I64 lanes and return it as I64 (`(neg i)` over I32), so + * `(floor (neg i))` would lose the I32 the builtin keeps. That case is + * left on the evaluator at its old cost (about 1.2 s over 10M rows, + * against 0.01 ms for the lowered forms). The thing to fix is the + * widening: once a fused result over a narrow integer column comes back + * in the column's own width, the identity holds for any integer operand + * and the OP_SCAN / I64 condition below can go. */ +static ray_op_t* dag_int_rounding(ray_graph_t* g, const char* name, size_t len, + ray_op_t* arg) { + int8_t t = arg->out_type; + if (t <= 0 || arg->opcode == OP_CONST) return NULL; + if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); + if (t != RAY_BOOL && t != RAY_U8 && t != RAY_I16 && + t != RAY_I32 && t != RAY_I64) + return NULL; + if ((len == 4 && memcmp(name, "ceil", 4) == 0) || + (len == 5 && memcmp(name, "floor", 5) == 0)) + return t == RAY_I64 || arg->opcode == OP_SCAN ? arg : NULL; + if (len == 5 && memcmp(name, "round", 5) == 0) + return ray_cast(g, arg, RAY_F64); + return NULL; +} + static bool dag_type_is_temporal(int8_t t) { if (t <= 0) return false; if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); @@ -348,11 +413,77 @@ static bool dag_arith_rejects_sym(const char* fname, size_t fname_len, return arith && (lt == RAY_SYM || rt == RAY_SYM); } +/* The value type of a DAG operand. A partitioned table's key scans as + * the RAY_MAPCOMMON wrapper, which names no value type: the plan-time type + * guards below matched none of their cases on it, so `(+ date 1)` over a + * DATE partition key ran as raw integer arithmetic and came back as I32 + * day counts (8768, not 2024.01.03), `(in (+ date 0) [2024.01.02])` then + * compared I32 cells against a DATE set and matched nothing, and + * `(+ sym_key 1)` added interned ids. The key vector carries the type. */ +static int8_t dag_operand_type(ray_graph_t* g, ray_op_t* x) { + if (x->out_type != RAY_MAPCOMMON || x->opcode != OP_SCAN || !g->table) + return x->out_type; + ray_op_ext_t* ext = find_ext(g, x->id); + ray_col_meta_t mm; /* metadata first; MAPCOMMON is plain */ + ray_t* col = ext && ray_table_col_meta(g->table, ext->sym, &mm) && mm.type == RAY_MAPCOMMON + ? ray_table_col(g->table, ext->sym) : NULL; + if (!col || RAY_IS_ERR(col) || col->type != RAY_MAPCOMMON || col->len < 1) return x->out_type; + ray_t* keys = ((ray_t**)ray_data(col))[0]; + return keys ? keys->type : x->out_type; +} + +/* Arithmetic with a temporal operand keeps its meaning only in the + * builtins (arith.c), which pick the result type (DATE + I64 is DATE, + * DATE - DATE is I32 days) or reject the pair outright. The DAG kernels + * see raw day / millisecond / nanosecond counts, so `(/ date 2)` and + * `(div date 2)` came back as F64 / I64 numbers where the builtins raise + * `cannot divide date by i64` and `cannot div date by i64`, and + * `(% date 2)` came back as I64 where the builtin keeps DATE. Every verb + * the DAG lowers declines a temporal operand, so the projection is left to + * the builtin through the evaluator: select's fallback applies it row by + * row, an ordinary update to the whole bound columns. The one exception + * is the modulo dag_temporal_mod admits. */ static bool dag_temporal_arith_needs_eval(const char* name, size_t len, int8_t left_type, int8_t right_type) { if (!dag_type_is_temporal(left_type) && !dag_type_is_temporal(right_type)) return false; - return len == 1 && (name[0] == '+' || name[0] == '-' || name[0] == '*'); + if (len == 1) + return name[0] == '+' || name[0] == '-' || name[0] == '*' || + name[0] == '/' || name[0] == '%'; + return len == 3 && (memcmp(name, "div", 3) == 0 || + memcmp(name, "pow", 3) == 0); +} + +/* `(% temporal n)` keeps the left operand's type (ray_mod_fn): the raw + * day / millisecond / nanosecond count is reduced by floor modulo, which + * takes the divisor's sign, and retagged; a null left cell is a typed + * null. The DAG's integer MOD kernel computes the same floor modulo on + * the raw counts (in I64 when either side is I64, so a DATE / TIME count + * by a wide divisor narrows as the builtin's store does) and keeps the + * null cells null, so the node only needs its result cast back to the left + * type, as the xbar lowering does. Admitted only where the kernel + * provably agrees: a temporal column (not a literal, not the partition + * key's MAPCOMMON wrapper) by a non-null, nonzero integer literal. + * Everything else stays with the builtin: a zero divisor, which the + * builtin nulls but the fused kernel writes as 0 over a column with no + * nulls (as it does for `(% i 0)`); a divisor column, which may hold such + * a zero; a null literal; a float divisor, which the builtin truncates to + * an integer first; and a temporal divisor, an error. */ +static bool const_op_i64(ray_graph_t* g, ray_op_t* op, int64_t* out); + +static ray_op_t* dag_temporal_mod(ray_graph_t* g, const char* name, size_t len, + ray_op_t* left, ray_op_t* right, + int8_t left_type) { + if (len != 1 || name[0] != '%') return NULL; + if (left->opcode == OP_CONST || left->out_type != left_type) return NULL; + if (!dag_type_is_temporal(left_type)) return NULL; + int64_t divisor = 0; + if (!const_op_i64(g, right, &divisor) || divisor == 0) return NULL; + int8_t lt = left_type; + if (RAY_IS_PARTED(lt)) lt = (int8_t)RAY_PARTED_BASETYPE(lt); + ray_op_t* m = ray_mod(g, left, right); + if (!m) return NULL; + return ray_cast(g, m, lt); } /* A comparison between a temporal and a float has no meaning — the eval @@ -379,12 +510,15 @@ static bool dag_cmp_rejects_temporal_float(const char* fname, size_t fname_len, * column by its bytes, so `(and x (> y 2))` kept rows a where: on `x` * alone rejects (#678). A literal keeps its scalar truth value, as a * where: scalar does. Sets compile_err and returns false on a bad operand. */ +static int8_t dag_operand_type(ray_graph_t* g, ray_op_t* x); + static bool dag_bool_operand_ok(ray_graph_t* g, ray_op_t* a, bool is_and) { - if (a->opcode == OP_CONST || a->out_type <= 0 || a->out_type == RAY_BOOL) + int8_t t = dag_operand_type(g, a); + if (a->opcode == OP_CONST || t <= 0 || t == RAY_BOOL) return true; if (!g->compile_err) g->compile_err = ray_error("type", "%s: operand must be boolean, got %s", - is_and ? "and" : "or", ray_type_name(a->out_type)); + is_and ? "and" : "or", ray_type_name(t)); return false; } @@ -565,13 +699,132 @@ static uint16_t resolve_agg_opcode(int64_t sym_id) { return 0; } +/* Column presence by name, from metadata: an encoded column stays encoded. */ +static bool tbl_has_col(ray_t* tbl, int64_t sym) { + ray_col_meta_t m; + return ray_table_col_meta(tbl, sym, &m); +} + +/* Column `sym` of `tbl` when it is a plain (generation-0 or in-memory) + * vector, NULL for an encoded one or none: the page-level read-ahead and + * sampling helpers read a column's memory directly, which an encoded column + * has only once materialized, and generation 2 reads by range instead. */ +static ray_t* tbl_plain_col(ray_t* tbl, int64_t sym) { + if (!tbl || tbl->type != RAY_TABLE || ray_table_get_col_enc(tbl, sym)) return NULL; + ray_t* c = ray_table_col(tbl, sym); /* a plain slot: no decode, no error */ + return c && !RAY_IS_ERR(c) ? c : NULL; +} + +/* The first present segment of a plain parted wrapper, or NULL. */ +static ray_t* tbl_parted_first_seg(ray_t* col) { + ray_t** segs = (ray_t**)ray_data(col); + for (int64_t i = 0; i < col->len; i++) + if (segs[i] && !RAY_IS_ERR(segs[i])) return segs[i]; + return NULL; +} + +/* ray_vec_may_have_nulls of a column without a decode: a plain slot is asked + * directly, a plain parted wrapper through its segments (the null flag lives + * on them, the wrapper's attrs are 0); an encoded one answers what its + * materialization would (the persisted attrs become the vector's, a parted + * one's are the OR of its segments', text always may hold nulls). */ +static bool tbl_col_may_have_nulls(ray_t* tbl, int64_t sym) { + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, sym, &m)) return false; + if (!m.enc) { + ray_t* col = ray_table_col(tbl, sym); + if (!col || RAY_IS_ERR(col) || !RAY_IS_PARTED(col->type)) + return ray_vec_may_have_nulls(col); + ray_t** segs = (ray_t**)ray_data(col); + for (int64_t i = 0; i < col->len; i++) + if (segs[i] && !RAY_IS_ERR(segs[i]) && ray_vec_may_have_nulls(segs[i])) return true; + return false; + } + int8_t bt = RAY_IS_PARTED(m.type) ? (int8_t)RAY_PARTED_BASETYPE(m.type) : m.type; + if (bt == RAY_SYM || bt == RAY_STR) return true; + return (m.attrs & RAY_ATTR_HAS_NULLS) != 0; +} + +/* An empty column shaped like a table column: what ray_group_gather(col, + * NULL, 0) returns. A plain slot is gathered as it is, a plain parted + * wrapper as its first segment (its base type and domain); an encoded one is + * built the same way from its metadata, without a decode, a parted one at its + * base type. */ +static ray_t* tbl_col_empty(ray_t* tbl, int64_t sym) { + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, sym, &m)) return NULL; + if (!m.enc) { /* plain: no decode */ + ray_t* col = ray_table_col(tbl, sym); + if (col && !RAY_IS_ERR(col) && RAY_IS_PARTED(col->type)) { + ray_t* seg = tbl_parted_first_seg(col); + if (!seg) return ray_error("nyi", "empty column of a parted column without segments"); + col = seg; + } + return ray_group_gather(col, NULL, 0); + } + if (RAY_IS_PARTED(m.type)) { + ray_t* seg = ray_enccol_seg(m.enc, 0); /* borrowed, encoded or plain */ + if (!seg) return ray_error("nyi", "empty column of a parted column without segments"); + if (seg->type != RAY_ENCCOL) return ray_group_gather(seg, NULL, 0); + ray_col_meta_t sm; + if (!ray_col_meta_of(seg, &sm)) return ray_error("schema", NULL); + m.type = sm.type; + m.attrs = sm.attrs; /* segment 0's SYM width */ + m.enc = seg; /* and its domain */ + } + if (m.type == RAY_LIST) return ray_list_new(0); + if (m.type == RAY_STR) { + const char* p0 = ""; uint32_t l0 = 0; + return ray_str_vec_from_parts(&p0, &l0, NULL, 0); + } + ray_t* out = m.type == RAY_SYM ? ray_sym_vec_new(m.attrs & RAY_SYM_W_MASK, 0) + : ray_vec_new(m.type, 0); + if (!out || RAY_IS_ERR(out)) return out; + if (m.type == RAY_SYM) ray_enccol_adopt_domain(out, m.enc); + out->len = 0; + if (tbl_col_may_have_nulls(tbl, sym)) out->attrs |= RAY_ATTR_HAS_NULLS; + return out; +} + +/* A column as a plain borrowed vector for a function that declines by + * returning NULL: a column that fails to materialize declines too, and the + * path the caller falls back to re-reads it through the accessors and + * reports the failure there. */ +static ray_t* tbl_col_or_null(ray_t* tbl, int64_t sym) { + ray_t* c = ray_table_col(tbl, sym); + if (c && RAY_IS_ERR(c)) { ray_error_free(c); return NULL; } + return c; +} +static ray_t* tbl_col_idx_or_null(ray_t* tbl, int64_t idx) { + ray_t* c = ray_table_col_idx(tbl, idx); + if (c && RAY_IS_ERR(c)) { ray_error_free(c); return NULL; } + return c; +} + +/* A generation-2 column's answer to agg `op` from its directory, exactly + * where the generation-0 column answers from its CHUNK_ZONE below + * (ray_zone_dir_answer, finding C3): COUNT, integer SUM / AVG, and MIN / + * MAX of non-float types (the is_f64 zone declines float extremes). NULL + * when that answer does not exist (the query runs at execution). */ +static ray_t* select_agg_dir_answer(const ray_col_meta_t* m, uint16_t op, int64_t nrows) { + bool fl = m->type == RAY_F32 || m->type == RAY_F64; + ray_t* atom = op == OP_COUNT ? ray_i64(nrows) + : (op == OP_SUM || op == OP_AVG || ((op == OP_MIN || op == OP_MAX) && !fl)) + ? ray_zone_dir_answer(m->enc, op) : NULL; + if (atom && (RAY_IS_ERR(atom) || !ray_is_atom(atom))) { + if (RAY_IS_ERR(atom)) ray_error_free(atom); else ray_release(atom); + return NULL; + } + return atom; +} + /* See the call site in ray_select_impl. NULL: some output is not answerable * from metadata (the caller plans the query as usual). */ static ray_t* select_aggs_from_metadata(ray_t* tbl, ray_t** dict_elems, int64_t dict_n, int64_t from_id) { int64_t nrows = ray_table_nrows(tbl); if (nrows <= 0) return NULL; /* empty tables keep the planner's answers */ - int64_t n_out = 0; + int64_t n_out = 0, n_enc = 0; for (int64_t i = 0; i + 1 < dict_n; i += 2) { if (dict_elems[i]->i64 == from_id) continue; ray_t* e = dict_elems[i + 1]; @@ -579,10 +832,24 @@ static ray_t* select_aggs_from_metadata(ray_t* tbl, ray_t** dict_elems, int64_t ray_t** el = (ray_t**)ray_data(e); if (el[0]->type != -RAY_SYM || (el[0]->attrs & ATTR_QUOTED)) return NULL; if (el[1]->type != -RAY_SYM || (el[1]->attrs & ATTR_QUOTED)) return NULL; - ray_t* col = ray_table_get_col(tbl, el[1]->i64); - if (!col || !ray_is_vec(col) || RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON || - (col->attrs & RAY_ATTR_SLICE) || col->len != nrows) + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, el[1]->i64, &m) || + m.type < RAY_BOOL || m.type > RAY_STR || RAY_IS_PARTED(m.type) || + m.type == RAY_MAPCOMMON || (m.attrs & RAY_ATTR_SLICE) || m.len != nrows) + return NULL; + if (m.enc) { /* generation 2: from the directory, no decode */ + ray_t* atom = select_agg_dir_answer(&m, resolve_agg_opcode(el[0]->i64), nrows); + if (!atom) return NULL; + ray_release(atom); + n_out++; + n_enc++; + continue; + } + ray_t* col = ray_table_col(tbl, el[1]->i64); /* plain slot: no decode */ + if (!col || RAY_IS_ERR(col)) { + if (col) ray_error_free(col); return NULL; + } uint16_t op = resolve_agg_opcode(el[0]->i64); bool int_col = col->type == RAY_I64 || col->type == RAY_I32 || col->type == RAY_I16 || col->type == RAY_U8; @@ -590,7 +857,7 @@ static ray_t* select_aggs_from_metadata(ray_t* tbl, ray_t** dict_elems, int64_t switch (op) { case OP_COUNT: break; case OP_MIN: case OP_MAX: { - if (ray_index_kind(col) != RAY_IDX_CHUNK_ZONE) return NULL; + if (m.index_kind != RAY_IDX_CHUNK_ZONE) return NULL; ray_index_t* ix = ray_index_payload(col->index); if (ix->built_for_len != col->len || ix->u.chunk_zone.is_f64 || !ix->u.chunk_zone.mins || !ix->u.chunk_zone.maxs) return NULL; @@ -614,13 +881,24 @@ static ray_t* select_aggs_from_metadata(ray_t* tbl, ray_t** dict_elems, int64_t int64_t kid = dict_elems[i]->i64; if (kid == from_id) continue; ray_t** el = (ray_t**)ray_data(dict_elems[i + 1]); - ray_t* col = ray_table_get_col(tbl, el[1]->i64); - uint16_t op = resolve_agg_opcode(el[0]->i64); - ray_t* atom = op == OP_COUNT ? ray_i64(nrows) - : op == OP_MIN ? ray_min_fn(col) - : op == OP_MAX ? ray_max_fn(col) - : op == OP_SUM ? ray_sum_fn(col) - : ray_avg_fn(col); + ray_col_meta_t m; + ray_t* atom = NULL; + if (n_enc > 0 && ray_table_col_meta(tbl, el[1]->i64, &m) && m.enc) { + atom = select_agg_dir_answer(&m, resolve_agg_opcode(el[0]->i64), nrows); + } else { + ray_t* col = ray_table_col(tbl, el[1]->i64); /* plain (checked above) */ + if (!col || RAY_IS_ERR(col)) { + if (col) ray_error_free(col); + ray_release(res); + return NULL; + } + uint16_t op = resolve_agg_opcode(el[0]->i64); + atom = op == OP_COUNT ? ray_i64(nrows) + : op == OP_MIN ? ray_min_fn(col) + : op == OP_MAX ? ray_max_fn(col) + : op == OP_SUM ? ray_sum_fn(col) + : ray_avg_fn(col); + } if (!atom || RAY_IS_ERR(atom) || !ray_is_atom(atom)) { if (atom && RAY_IS_ERR(atom)) ray_error_free(atom); else if (atom) ray_release(atom); ray_release(res); @@ -671,37 +949,20 @@ static bool quantile_literal_prob(ray_t* prob_expr, bool percentile, static bool group_keys_have_bool(ray_t* by_expr, ray_t* tbl) { if (!by_expr || !tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return true; if (by_expr->type == -RAY_SYM && !(by_expr->attrs & ATTR_QUOTED)) { - ray_t* c = ray_table_get_col(tbl, by_expr->i64); - return !c || c->type == RAY_BOOL; + ray_col_meta_t m; + return !ray_table_col_meta(tbl, by_expr->i64, &m) || m.type == RAY_BOOL; } if (ray_is_vec(by_expr) && by_expr->type == RAY_SYM) { const int64_t* ids = (const int64_t*)ray_data(by_expr); for (int64_t i = 0; i < ray_len(by_expr); i++) { - ray_t* c = ray_table_get_col(tbl, ids[i]); - if (!c || c->type == RAY_BOOL) return true; + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, ids[i], &m) || m.type == RAY_BOOL) return true; } return false; } return true; /* computed / unresolved key shapes: stay conservative */ } -/* True when `tbl` carries PARTED or MAPCOMMON columns (a parted store). The - * parted GROUP dispatch (exec_group_parted) treats a positive group_limit as - * "stop after group_limit partitions", which assumes every partition yields a - * group — an EMPTY partition breaks that and under-fills the answer. Rather - * than push a hint that path would mis-apply, grouped takes over parted inputs - * keep the post-execution take. */ -static bool table_is_parted(ray_t* tbl) { - if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return true; - int64_t nc = ray_table_ncols(tbl); - for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) - return true; - } - return false; -} - /* Apply sort (asc/desc) and take clauses to a materialized result table. * Used by eval-level paths that bypass the DAG (e.g., LIST/STR group keys). * Builds a temporary DAG for sorting (supports per-column direction flags) @@ -734,11 +995,12 @@ typedef struct { ray_t* result; ray_t* src; int64_t rows; int64_t added; } carry static int carry_one_sort_key(int64_t name, void* p) { carry_ctx_t* c = (carry_ctx_t*)p; - if (ray_table_get_col(c->result, name)) return 0; /* output already */ - ray_t* col = ray_table_get_col(c->src, name); - if (!col || col->type < 0 || RAY_IS_PARTED(col->type) || - col->type == RAY_MAPCOMMON || ray_len(col) != c->rows) + if (ray_table_has_col(c->result, name)) return 0; /* output already */ + ray_col_meta_t cm; /* metadata: the slot is carried, encoded or plain */ + if (!ray_table_col_meta(c->src, name, &cm) || cm.type < 0 || RAY_IS_PARTED(cm.type) || + cm.type == RAY_MAPCOMMON || cm.len != c->rows) return 0; /* not a row column */ + ray_t* col = ray_table_slot(c->src, name); ray_retain(col); ray_t* r = ray_table_add_col(c->result, name, col); ray_release(col); @@ -773,7 +1035,7 @@ static ray_t* select_fallback_drop_tail_cols(ray_t* tbl, int64_t n) { ray_t* out = ray_table_new(keep); for (int64_t c = 0; c < keep && out && !RAY_IS_ERR(out); c++) out = ray_table_add_col(out, ray_table_col_name(tbl, c), - ray_table_get_col_idx(tbl, c)); + ray_table_slot_idx(tbl, c)); /* encoded or plain, not decoded */ ray_release(tbl); return out ? out : ray_error("oom", NULL); } @@ -940,13 +1202,17 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, int has_list = 0; int64_t ncols = ray_table_ncols(result); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(result, c); - if (col && col->type == RAY_LIST) { has_list = 1; break; } + ray_col_meta_t m; + if (ray_table_col_meta_idx(result, c, &m) && m.type == RAY_LIST) { has_list = 1; break; } } if (!has_list) { ray_t* topk = NULL; if (n_keys == 1) { - ray_t* sort_col = ray_table_get_col(result, key_syms[0]); + ray_t* sort_col = ray_table_col(result, key_syms[0]); + if (sort_col && RAY_IS_ERR(sort_col)) { + ray_error_free(sort_col); + sort_col = NULL; /* the full path re-reads and reports */ + } if (sort_col) { topk = ray_topk_table(result, sort_col, key_descs[0], @@ -957,8 +1223,12 @@ static ray_t* apply_sort_take(ray_t* result, ray_t** dict_elems, int64_t dict_n, uint8_t nfs[TOPK_MAX_KEYS]; int ok = 1; for (uint32_t i = 0; i < n_keys; i++) { - key_cols[i] = ray_table_get_col(result, key_syms[i]); + key_cols[i] = ray_table_col(result, key_syms[i]); nfs[i] = sort_nulls_first(key_descs[i]); + if (key_cols[i] && RAY_IS_ERR(key_cols[i])) { + ray_error_free(key_cols[i]); + key_cols[i] = NULL; /* the full path re-reads and reports */ + } if (!key_cols[i]) { ok = 0; break; } } if (ok) { @@ -1334,7 +1604,7 @@ static ray_t* in_str_set_const(ray_graph_t* g, ray_t* set) { ray_t* v = g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(id) : ray_env_get_lexical_local(id); if (!v) { - if (g->table && g->table->type == RAY_TABLE && ray_table_get_col(g->table, id)) + if (g->table && g->table->type == RAY_TABLE && ray_table_has_col(g->table, id)) return NULL; v = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(id) : ray_env_get(id); } @@ -1380,12 +1650,33 @@ static bool in_set_names_global_value(ray_graph_t* g, ray_t* set) { if (g->cexpr_helper_depth > 0 ? ray_env_get_lexical_local_callee(id) : ray_env_get_lexical_local(id)) return false; - if (g->table && g->table->type == RAY_TABLE && ray_table_get_col(g->table, id)) + if (g->table && g->table->type == RAY_TABLE && ray_table_has_col(g->table, id)) return false; ray_t* v = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(id) : ray_env_get(id); return v && !ray_is_atom(v) && !ray_is_vec(v); } + +/* Lower the arguments of an if chain (c1 r1 c2 r2 ... else), nargs odd and + * >= 3, into nested OP_IF nodes. Node creation may realloc g->nodes: + * re-derive pointers from ids after compiling each arm. The arms are + * compiled under if_arm_depth, as the three-argument form's were. */ +static ray_op_t* compile_if_chain_dag(ray_graph_t* g, ray_t** a, int64_t nargs) { + if (nargs == 1) return compile_expr_dag(g, a[0]); + ray_op_t* c = compile_expr_dag(g, a[0]); + if (!c) return NULL; + uint32_t c_id = c->id; + g->if_arm_depth++; + ray_op_t* t = compile_expr_dag(g, a[1]); + uint32_t t_id = t ? t->id : 0; + ray_op_t* e = t ? compile_if_chain_dag(g, a + 2, nargs - 2) : NULL; + g->if_arm_depth--; + if (!t || !e) return NULL; + c = &g->nodes[c_id]; + t = &g->nodes[t_id]; + return ray_if(g, c, t, e); +} + ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (!expr) return NULL; @@ -1443,7 +1734,8 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { int nsegs = ray_sym_segs(expr->i64, &segs); if (nsegs < 2) return NULL; if (!g->table || g->table->type != RAY_TABLE) return NULL; - if (!ray_table_get_col(g->table, segs[0])) return NULL; + ray_col_meta_t hm; + if (!ray_table_col_meta(g->table, segs[0], &hm)) return NULL; ray_t* head_name = ray_sym_str(segs[0]); if (!head_name) return NULL; ray_op_t* op = ray_scan(g, ray_str_ptr(head_name)); @@ -1468,8 +1760,9 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { /* Column names on the bound table shadow global env — * matches eval-level name-resolution order. */ + ray_col_meta_t cm; if (g->table && g->table->type == RAY_TABLE && - ray_table_get_col(g->table, expr->i64)) + ray_table_col_meta(g->table, expr->i64, &cm)) return ray_scan(g, ray_str_ptr(s)); /* Global env: atom literals / typed vectors compile as * const nodes. Lambdas only make sense as call heads @@ -1528,8 +1821,9 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * a literal still never captures those. */ ray_op_t* alias = sel_alias_lookup(g, expr->i64); if (alias) return alias; + ray_col_meta_t lm; if (g->table && g->table->type == RAY_TABLE && - ray_table_get_col(g->table, expr->i64)) { + ray_table_col_meta(g->table, expr->i64, &lm)) { ray_t* s = ray_sym_str(expr->i64); if (s) return ray_scan(g, ray_str_ptr(s)); } @@ -1628,10 +1922,11 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * branch: local cexpr_env > table columns > globals. A * column named `f` isn't callable, but we still must honor * shadowing so the exec-time error is consistent. */ + ray_col_meta_t hcm; if (head->type == -RAY_SYM && !(head->attrs & ATTR_QUOTED) && cexpr_env_lookup(g, head->i64) == NULL && !(g->table && g->table->type == RAY_TABLE && - ray_table_get_col(g->table, head->i64))) { + ray_table_col_meta(g->table, head->i64, &hcm))) { ray_t* gv = g->cexpr_helper_depth > 0 ? ray_env_get_compiled(head->i64) : ray_env_get(head->i64); /* Not a closure: its captures are not in the planner's scope, @@ -1740,6 +2035,9 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * it to nanoseconds). */ int8_t col_t = col->out_type; if (RAY_IS_PARTED(col_t)) col_t = (int8_t)RAY_PARTED_BASETYPE(col_t); + int8_t bucket_type = bucket->out_type; + if (RAY_IS_PARTED(bucket_type)) bucket_type = (int8_t)RAY_PARTED_BASETYPE(bucket_type); + if (col_t == RAY_TIMESPAN || bucket_type == RAY_TIMESPAN) return NULL; int8_t temporal = dag_type_is_temporal(col_t) ? col_t : 0; if (temporal) { int8_t bt = bucket->out_type; @@ -1763,23 +2061,15 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { return ray_cast(g, r, temporal); } - /* (if cond then else) — 4 elements (fn + 3 args). Compiles - * to OP_IF which is supported by the element-wise fusion - * pipeline. */ + /* (if c1 r1 c2 r2 ... else) — condition/result pairs with a + * fallback. Pairs nest right to left into OP_IF, which the + * element-wise fusion pipeline serves: (if c1 r1 c2 r2 e) is + * OP_IF(c1, r1, OP_IF(c2, r2, e)). A chain with no fallback has + * no column value for the rows no condition takes (the evaluator + * yields 0), so it is left to the evaluator. */ if (fname_len == 2 && memcmp(fname, "if", 2) == 0) { - if (n != 4) return NULL; - ray_op_t* c = compile_expr_dag(g, elems[1]); - if (!c) return NULL; - uint32_t c_id = c->id; - g->if_arm_depth++; - ray_op_t* t = compile_expr_dag(g, elems[2]); - uint32_t t_id = t ? t->id : 0; - ray_op_t* e = t ? compile_expr_dag(g, elems[3]) : NULL; - g->if_arm_depth--; - if (!t || !e) return NULL; - c = &g->nodes[c_id]; - t = &g->nodes[t_id]; - return ray_if(g, c, t, e); + if (n < 4 || (n & 1)) return NULL; + return compile_if_chain_dag(g, elems + 1, n - 1); } /* (substr str start len) — 4 elements. */ @@ -2176,27 +2466,25 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { (!dag_bool_operand_ok(g, left, ctor == ray_and) || !dag_bool_operand_ok(g, right, ctor == ray_and))) return NULL; - if (dag_temporal_arith_needs_eval(fname, fname_len, - left->out_type, - right->out_type)) - return NULL; + int8_t lvt = dag_operand_type(g, left); + int8_t rvt = dag_operand_type(g, right); + if (dag_temporal_arith_needs_eval(fname, fname_len, lvt, rvt)) + return dag_temporal_mod(g, fname, fname_len, left, right, lvt); if (g->if_arm_depth == 0 && - dag_arith_rejects_sym(fname, fname_len, - left->out_type, right->out_type)) { + dag_arith_rejects_sym(fname, fname_len, lvt, rvt)) { if (!g->compile_err) g->compile_err = ray_error("type", "cannot %s %s and %s", dag_arith_verb(fname, fname_len), - ray_type_name((int8_t)-left->out_type), - ray_type_name((int8_t)-right->out_type)); + ray_type_name((int8_t)-lvt), + ray_type_name((int8_t)-rvt)); return NULL; } if (g->if_arm_depth == 0 && - dag_cmp_rejects_temporal_float(fname, fname_len, - left->out_type, right->out_type)) { + dag_cmp_rejects_temporal_float(fname, fname_len, lvt, rvt)) { if (!g->compile_err) g->compile_err = ray_error("type", "cannot compare %s and %s", - ray_type_name((int8_t)-left->out_type), - ray_type_name((int8_t)-right->out_type)); + ray_type_name((int8_t)-lvt), + ray_type_name((int8_t)-rvt)); return NULL; } if (fname_len == 3 && memcmp(fname, "pow", 3) == 0 && @@ -2214,9 +2502,18 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { if (uctor) { ray_op_t* arg = compile_expr_dag(g, elems[1]); if (!arg) return NULL; + /* The partition key's wrapper holds one value per + * partition, which the unary kernels read as the rows: + * `(neg date)` came back as dates. The evaluator applies + * the verb to the key's values, as over a flat column. */ + if (dag_operand_type(g, arg) != arg->out_type) return NULL; if (dag_unary_numeric_name(fname, fname_len) && !dag_numeric_type_admitted(arg->out_type)) return NULL; + ray_op_t* r = dag_int_rounding(g, fname, fname_len, arg); + if (r) return r; + if (!dag_unary_arith_type_admitted(fname, fname_len, arg->out_type)) + return NULL; return uctor(g, arg); } /* Aggregation functions return DAG agg nodes */ @@ -2230,7 +2527,8 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { * DAG path never silently aggregates raw symbol ids / string * bytes / date counts. Returning NULL routes the select to the * eval-level path, where the scalar builtin raises `type`. */ - if (arg->out_type > 0 && !agg_type_admitted(agg_op, arg->out_type)) + int8_t arg_t = dag_operand_type(g, arg); /* the partition key's values */ + if (arg_t > 0 && !agg_type_admitted(agg_op, arg_t)) return NULL; switch (agg_op) { case OP_SUM: return ray_sum(g, arg); @@ -2938,7 +3236,7 @@ static ray_t* query_inline_source_col(query_inline_scope_t* scope, ray_t* col) { do { int len = snprintf(name, sizeof name, "__query_source_%d", scope->next++); id = ray_sym_intern(name, len); - } while (ray_table_get_col(scope->table, id) || ray_env_get(id)); + } while (ray_table_has_col(scope->table, id) || ray_env_get(id)); if (!scope->owned) { ray_retain(scope->table); scope->owned = true; } scope->table = ray_table_add_col(scope->table, id, col); if (!scope->table || RAY_IS_ERR(scope->table)) return NULL; @@ -2961,10 +3259,11 @@ static ray_t* query_inline_walk(ray_t* expr, ray_t* tbl, ray_retain(bindings[i].expr); return bindings[i].expr; } - ray_t* source_col = named_body ? ray_table_get_col(tbl, expr->i64) : NULL; + /* slots: identity and a column carried as it is, never decoded */ + ray_t* source_col = named_body ? ray_table_slot(tbl, expr->i64) : NULL; if (source_col && scope && scope->globals_for_source) source_col = NULL; else if (source_col && scope && scope->table && !RAY_IS_ERR(scope->table) && - source_col != ray_table_get_col(scope->table, expr->i64)) + source_col != ray_table_slot(scope->table, expr->i64)) return query_inline_source_col(scope, source_col); if (named_body && !source_col) { /* A named helper's free name belongs to its global scope, not @@ -2993,7 +3292,7 @@ static ray_t* query_inline_walk(ray_t* expr, ray_t* tbl, ray_t* params = NULL, *body = NULL; bool named = false; if (es[0]->type == -RAY_SYM && !(es[0]->attrs & ATTR_QUOTED) && - !ray_table_get_col(tbl, es[0]->i64)) { + !ray_table_has_col(tbl, es[0]->i64)) { ray_t* fn = ray_env_get(es[0]->i64); /* A closure's body reads its captures; inlined, those names would * resolve to columns or globals instead. Never inline one, however @@ -3107,22 +3406,33 @@ ray_t* ray_query_helper_table(void) { } -/* Mount columns AND publish `tbl` as the active query table; returns the +/* Mount columns AND publish `tbl` as the active query table; `*err` is the + * owned error of a column that failed to materialize (else NULL). Returns the * previously-active table so the caller can restore it after the matching * ray_env_pop_scope (sub-selects nest, so save/restore is required). */ -static ray_t* bind_all_columns(ray_t* tbl) { +static ray_t* bind_all_columns(ray_t* tbl, ray_t** err) { ray_t* prev = g_active_query_table; g_active_query_table = tbl; + *err = NULL; int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { int64_t cn = ray_table_col_name(tbl, c); - ray_t* cv = ray_table_get_col_idx(tbl, c); + ray_t* cv = ray_table_col_idx(tbl, c); + if (cv && RAY_IS_ERR(cv)) { + /* A column that cannot materialize: the caller takes the error + * in place of its evaluation result, then restores the previous + * table and pops the scope as on any other error. */ + *err = cv; + break; + } if (cv) ray_env_set_query_local(cn, cv); } return prev; } static ray_t* group_key_eval(ray_t* v, ray_t* tbl); +static ray_t* bind_referenced_query(ray_t* tbl, ray_t* const* exprs, int64_t n, ray_t** err); +static ray_t* bind_referenced_columns(ray_t* tbl, ray_t* const* exprs, int64_t n); /* The column of an aggregate's argument expression over `tbl`: the * full-column evaluation the eval-level grouping slices per group @@ -3133,8 +3443,9 @@ static ray_t* group_key_eval(ray_t* v, ray_t* tbl); * Owned ref, or an error. */ static ray_t* select_eval_over_table(ray_t* expr, ray_t* tbl) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); - ray_t* v = group_key_eval(expr, tbl); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_referenced_query(tbl, &expr, 1, &bind_err_); /* decodes what expr reads */ + ray_t* v = bind_err_ ? bind_err_ : group_key_eval(expr, tbl); g_active_query_table = _aqt; ray_env_pop_scope(); if (!v) return ray_error("domain", "select by: failed to evaluate aggregation source"); @@ -3146,14 +3457,65 @@ static ray_t* select_eval_over_table(ray_t* expr, ray_t* tbl) { return v; } +static bool table_has_parted_columns(ray_t* tbl); +static ray_t* query_materialize_parted_col(ray_t* col, ray_t* tbl); +static int collect_col_refs_set(ray_t* expr, ray_t* tbl, + int64_t* out_syms, int max_out, int n); +static bool clause_runs_code_in(ray_t* v, ray_t* tbl, bool containers); + +/* `tbl` with the parted / MAPCOMMON columns `expr` reads flattened, every + * other column shared as it is. The evaluator's verbs take a segmented + * column only in part (a comparison does, arithmetic does not: `(+ date 1)` + * over the partition key raised `cannot add ? and i64`), so a where: the + * DAG declines is evaluated over plain vectors. Every segmented column is + * flattened when `expr` runs code whose reads it does not show (a helper + * the planner does not inline) or names more columns than are counted. + * Owned, or an error. */ +static ray_t* parted_flatten_expr_cols(ray_t* expr, ray_t* tbl) { + int64_t refs[256]; + int nref = collect_col_refs_set(expr, tbl, refs, 256, 0); + bool all = nref >= 256 || clause_runs_code_in(expr, tbl, false); + int64_t nc = ray_table_ncols(tbl); + ray_t* out = ray_table_new(nc); + for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { + int64_t cn = ray_table_col_name(tbl, c); + ray_col_meta_t m; + ray_t* slot = ray_table_slot_idx(tbl, c); /* encoded or plain, not decoded */ + if (!slot || !ray_table_col_meta_idx(tbl, c, &m)) continue; + bool want = all; + for (int r = 0; r < nref && !want; r++) want = refs[r] == cn; + if (!want || (!RAY_IS_PARTED(m.type) && m.type != RAY_MAPCOMMON)) { + out = ray_table_add_col(out, cn, slot); + continue; + } + ray_t* col = ray_table_col_idx(tbl, c); + if (!col || RAY_IS_ERR(col)) { ray_release(out); return col ? col : ray_error("oom", NULL); } + ray_t* v = query_materialize_parted_col(col, tbl); + if (!v || RAY_IS_ERR(v)) { ray_release(out); return v ? v : ray_error("oom", NULL); } + out = ray_table_add_col(out, cn, v); + ray_release(v); + } + return out ? out : ray_error("oom", NULL); +} + static ray_t* eval_where_mask(ray_t* where_expr, ray_t* tbl, const char* label) { - if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); - ray_t* mask = eval_query_expr(where_expr, tbl); + ray_t* etbl = tbl; + if (table_has_parted_columns(tbl)) { + etbl = parted_flatten_expr_cols(where_expr, tbl); + if (!etbl || RAY_IS_ERR(etbl)) return etbl ? etbl : ray_error("oom", NULL); + } + if (ray_env_push_query_scope() != RAY_OK) { + if (etbl != tbl) ray_release(etbl); + return ray_error("oom", NULL); + } + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_referenced_query(etbl, &where_expr, 1, &bind_err_); /* decodes what it reads */ + ray_t* mask = bind_err_ ? bind_err_ : eval_query_expr(where_expr, etbl); if (mask && !RAY_IS_ERR(mask)) mask = ray_lazy_materialize(mask); g_active_query_table = _aqt; ray_env_pop_scope(); + if (etbl != tbl) ray_release(etbl); if (!mask) return ray_error("domain", "%s: WHERE predicate evaluation failed", label); @@ -3219,14 +3581,14 @@ static int expr_refs_row_column(ray_t* expr, ray_t* tbl) { if (!expr) return 0; if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { if (ray_env_has_lexical_local(expr->i64)) return 0; - if (ray_table_get_col(tbl, expr->i64)) return 1; + if (tbl_has_col(tbl, expr->i64)) return 1; /* Dotted name whose head is a column is a row-aligned ref — * `Timestamp.ss` flows through row-by-row the same as plain * `Timestamp` would, so the scatter must treat it as one. */ if (ray_sym_is_dotted(expr->i64)) { const int64_t* segs; int nsegs = ray_sym_segs(expr->i64, &segs); - if (nsegs >= 1 && ray_table_get_col(tbl, segs[0])) return 1; + if (nsegs >= 1 && tbl_has_col(tbl, segs[0])) return 1; } return 0; } @@ -3249,6 +3611,14 @@ static int expr_refs_row_column(ray_t* expr, ray_t* tbl) { return 0; } +/* min/max overload on arity: only their unary calls reduce rows. Keep + * the name-only resolver for aggregate specifications and other signatures. */ +static uint16_t resolve_agg_call_opcode(int64_t sym_id, int64_t nargs) { + uint16_t op = resolve_agg_opcode(sym_id); + if ((op == OP_MIN || op == OP_MAX) && nargs != 1) return 0; + return op; +} + /* Check if an expression is an aggregation call (head is an agg function) */ static int is_agg_expr(ray_t* expr) { if (!expr || expr->type != RAY_LIST) return 0; @@ -3257,7 +3627,7 @@ static int is_agg_expr(ray_t* expr) { if (n < 2) return 0; ray_t** elems = (ray_t**)ray_data(expr); if (elems[0]->type != -RAY_SYM) return 0; - return resolve_agg_opcode(elems[0]->i64) != 0; + return resolve_agg_call_opcode(elems[0]->i64, n - 1) != 0; } /* True iff the expression contains an aggregation call anywhere in @@ -3455,7 +3825,7 @@ static ray_t* agg_arith_rewrite(ray_t* expr, ray_t* tbl, * (ts.yyyy) are column paths we cannot verify here — reject. * Globals (NS_HOUR etc.) resolve identically at post-eval. */ if (ray_sym_is_dotted(child->i64) || - ray_table_get_col(tbl, child->i64)) { *ok = 0; } + tbl_has_col(tbl, child->i64)) { *ok = 0; } else rep = child; } else { rep = child; /* call head / literal / quoted sym */ @@ -3524,7 +3894,7 @@ static int expr_contains_call_named(ray_t* expr, const char* name, size_t name_l return 0; } -static ray_t* query_materialize_parted_col(ray_t* col); +static ray_t* query_materialize_parted_col(ray_t* col, ray_t* tbl); static bool table_has_parted_columns(ray_t* tbl); static ray_t* query_materialize_parted_table(ray_t* tbl); @@ -3541,24 +3911,72 @@ static ray_t* query_materialize_parted_table(ray_t* tbl); static ray_t* select_fallback_passthrough_col(ray_t* expr, ray_t* tbl, int64_t nrows) { if (!expr || expr->type != -RAY_SYM || (expr->attrs & ATTR_QUOTED)) return NULL; if (ray_env_has_lexical_local(expr->i64)) return NULL; /* a formal shadows the column, as on the DAG */ - ray_t* col = ray_table_get_col(tbl, expr->i64); - if (!col || col->type < 0) return NULL; - if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON || - (col->attrs & RAY_ATTR_SLICE) || ray_len(col) != nrows) + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, expr->i64, &m) || m.type < 0) return NULL; + if (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON || + (m.attrs & RAY_ATTR_SLICE) || m.len != nrows) return NULL; + /* The slot object goes into the result table as it is: an encoded + * column stays encoded. */ + ray_t* col = ray_table_slot(tbl, expr->i64); + if (!col || RAY_IS_ERR(col)) return NULL; ray_retain(col); return col; } +/* Cold admission for a direct dyadic min/max output only. Inspect borrowed + * physical slots, never decode or trial-evaluate: the LANGUAGE builtin can + * consume these full I64 vectors (including NULL-low lanes) once instead of + * paying the fallback evaluator per row. Do not use this after helper + * expansion or in grouped/aggregate classification. */ +static int select_fallback_bulk_minmax(ray_t* expr, ray_t* tbl, int64_t nrows) { + if (!tbl || tbl->type != RAY_TABLE || nrows <= 0 || + !expr || expr->type != RAY_LIST || (expr->attrs & ATTR_QUOTED) || + ray_len(expr) != 3) return 0; + ray_t** args = (ray_t**)ray_data(expr); + ray_t* head = args[0]; + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return 0; + /* Reject unrelated verbs before any schema lookup. Keep the existing + * name-based reducer/alias classification unchanged. */ + ray_t* name = ray_sym_str(head->i64); + if (!name || ray_str_len(name) != 3 || + (memcmp(ray_str_ptr(name), "min", 3) != 0 && + memcmp(ray_str_ptr(name), "max", 3) != 0)) return 0; + if (ray_env_has_lexical_local(head->i64) || ray_table_slot(tbl, head->i64)) return 0; + ray_t* fn = ray_env_get(head->i64); + if (!fn || fn->type != RAY_UNARY) return 0; + ray_unary_fn native = (ray_unary_fn)(uintptr_t)fn->i64; + if (native != ray_min_fn && native != ray_max_fn) return 0; + int columns = 0; + for (int i = 1; i <= 2; i++) { + ray_t* arg = args[i]; + if (!arg) return 0; + if (arg->type == -RAY_I64) { + /* Opaque tagged handles are not ordinary numeric literals. */ + if (arg->attrs & (RAY_ATTR_GRAPH | RAY_ATTR_HNSW | RAY_ATTR_DLPROG)) return 0; + continue; + } + if (arg->type != -RAY_SYM || (arg->attrs & ATTR_QUOTED) || + ray_sym_is_dotted(arg->i64) || ray_env_has_lexical_local(arg->i64)) return 0; + ray_t* col = ray_table_slot(tbl, arg->i64); /* borrowed; never decodes */ + if (!col || col->type != RAY_I64 || (col->attrs & RAY_ATTR_SLICE) || + ray_len(col) != nrows) return 0; + columns++; + } + return columns != 0; +} + /* True when a projection's TOP-LEVEL call is a "whole-column verb": a - * collection builtin (distinct, asc, desc, reverse, enlist) that + * collection builtin (distinct, asc, desc, reverse, where, enlist) that * consumes an entire column vector and returns a vector. The DAG compiler * has no bucket for these — they are neither element-wise ops nor * scalar-reducing aggregations — so `compile_expr_dag` returns NULL and the * projection lands in the eval fallback. There the default per-row scatter * feeds the verb one scalar cell at a time: `distinct` errors ("argument must - * be a list") and `asc`/`desc`/`reverse` silently return the column untouched - * (reordering a 1-element slice is a no-op). Both are wrong; such a + * be a list"), `where` errors (it takes a B8 vector, and got one b8 cell: + * `(count (where (> i 2)))` never counted anything) and `asc`/`desc`/`reverse` + * silently return the column untouched (reordering a 1-element slice is a + * no-op). All are wrong; such a * projection must instead be evaluated once against the full column * (see eval_expr_whole_column). Matched on the top-level head only — * a whole-column verb nested under an element-wise op has ambiguous length @@ -3610,21 +4028,37 @@ static int is_whole_column_projection(ray_t* expr, ray_t* tbl) { * remain per-row constructors. Aggregate arguments are handled by * the fallback's existing one-value rule. */ if (ray_len(expr) != 2) return 0; - ray_t* value = ((ray_t**)ray_data(expr))[1]; + ray_t* value = ((ray_t**)ray_data(expr))[1]; /* not-a-table */ if (!ray_is_atom(value)) return 0; if (value->type == -RAY_SYM) { - if (ray_table_get_col(tbl, value->i64) && + if (ray_table_has_col(tbl, value->i64) && !ray_env_has_lexical_local(value->i64)) return 0; if (!(value->attrs & ATTR_QUOTED)) value = ray_env_get(value->i64); } return value && ray_is_atom(value); } return (l == 8 && memcmp(p, "distinct", 8) == 0) || + (l == 5 && memcmp(p, "where", 5) == 0) || (l == 7 && memcmp(p, "reverse", 7) == 0) || (l == 3 && memcmp(p, "asc", 3) == 0) || (l == 4 && memcmp(p, "desc", 4) == 0); } +static int collect_col_refs_walk(ray_t* expr, ray_t* tbl, int64_t* out_syms, + int max_out, int n, bool sym_vecs_data); +static bool clause_runs_code_in(ray_t* v, ray_t* tbl, bool containers); + +/* Does `expr` read no column of `tbl`: it names none (by name or by a + * quoted symbol, which a query resolves to the column), nor runs code (a + * lambda, a computed callee, text evaluated at run time) whose reads it + * does not show? Its value is then the same for every row. A symbol + * vector in it is a literal, whatever names it holds. */ +static bool expr_reads_no_column(ray_t* expr, ray_t* tbl) { + int64_t ref; + return collect_col_refs_walk(expr, tbl, &ref, 1, 0, true) == 0 && + !clause_runs_code_in(expr, tbl, false); +} + /* True when a grouped aggregate expression can be lowered to OP_GROUP. * `(count (distinct col))` is semantically an aggregate, but `distinct` * is not a row-aligned DAG input inside GROUP. Route it through the @@ -3651,18 +4085,30 @@ static bool agg_input_needs_group_eval(ray_t* arg, ray_t* tbl, bool collections) if (tbl && tbl->type == RAY_TABLE) { if (arg->type == -RAY_SYM) { bool local = !(arg->attrs & ATTR_QUOTED) && ray_env_has_lexical_local(arg->i64); - if (!local && ray_table_get_col(tbl, arg->i64)) return false; + if (!local && ray_table_has_col(tbl, arg->i64)) return false; if (!collections) return false; } else if (arg->type != RAY_LIST) { return collections && ray_is_vec(arg); + } else if (expr_contains_call_named(arg, "where", 5)) { + /* `where` keeps the positions it selects, not the rows: its + * result is no row-aligned input, so aggregate what it returns + * within each group. */ + return true; } else if (!expr_contains_call_named(arg, "concat", 6) && !query_expr_has_helper(arg)) { - if (!collections || expr_refs_row_column(arg, tbl)) return false; + if (expr_refs_row_column(arg, tbl)) return false; + if (!collections && !expr_reads_no_column(arg, tbl)) return false; } } bool lowered = false; bool constant = expr_is_constant_collection(arg, tbl, &lowered); if (constant && collections) return true; if (lowered) return false; + /* A source the planner cannot lower that reads no column (`(til 5)`) + * is one value whatever the row: aggregate it per group in the + * evaluator, as a constant collection is counted, not row by row. */ + if (tbl && tbl->type == RAY_TABLE && arg->type == RAY_LIST && + expr_reads_no_column(arg, tbl)) + return true; /* A helper the planner can neither lower nor expand (several * statements, a closure, recursion) runs per group in the evaluator, * where its argument keeps the group's rows. */ @@ -3851,7 +4297,7 @@ static int64_t key_col_read_i64(ray_t* col, int64_t row) { case RAY_DATE: case RAY_TIME: return ((const int32_t*)d)[row]; case RAY_I64: - case RAY_TIMESTAMP: return ((const int64_t*)d)[row]; + case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)d)[row]; default: return 0; } } @@ -3869,6 +4315,17 @@ static int8_t query_col_base_type(ray_t* col) { return col->type; } +/* query_col_base_type of a table column from metadata: an encoded slot + * reports its logical type, a parted one RAY_PARTED_BASE + base, so the base + * is taken from that; plain slots and MAPCOMMON (never encoded) are asked + * directly. */ +static int8_t tbl_col_base_type(ray_t* tbl, int64_t sym) { + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, sym, &m)) return 0; + if (m.enc) return RAY_IS_PARTED(m.type) ? (int8_t)RAY_PARTED_BASETYPE(m.type) : m.type; + return query_col_base_type(ray_table_col(tbl, sym)); /* plain: no decode */ +} + /* A scalar key type the streaming per-partition group kernel packs into an * 8-byte slot. STR/LIST/GUID keys route to the eval-level toy grouper (which * gathers materialized key columns by name) and MUST NOT be deferred over a @@ -3946,9 +4403,9 @@ static bool can_defer_single_key_where(ray_t* by_expr, ray_t* where_expr, RAY_ATOM_IS_NULL(atom)) return false; - ray_t* key_col = ray_table_get_col(tbl, by_expr->i64); - if (!key_col) return false; - int8_t kt = key_col->type; + ray_col_meta_t km; + if (!ray_table_col_meta(tbl, by_expr->i64, &km)) return false; + int8_t kt = km.type; if (!RAY_IS_PARTED(kt)) return false; if (RAY_IS_PARTED(kt)) kt = (int8_t)RAY_PARTED_BASETYPE(kt); return kt == RAY_SYM || kt == RAY_BOOL || kt == RAY_U8 || @@ -4132,7 +4589,7 @@ static bool match_group_desc_count_take(ray_t* tbl, ray_t** dict_elems, int64_t return false; } -/* True for `(fn arg ...)` where fn resolves to a RAY_UNARY marked +/* True for an actual unary `(fn arg)` call whose fn is RAY_UNARY marked * RAY_FN_AGGR — i.e. a builtin aggregator (sum/avg/min/max/count and * the non-whitelisted med/dev/var/stddev/etc). Used to route these * through the streaming-style per-group AGG branch rather than the @@ -4142,7 +4599,7 @@ static bool match_group_desc_count_take(ray_t* tbl, ray_t** dict_elems, int64_t static int is_aggr_unary_call(ray_t* expr) { if (!expr || expr->type != RAY_LIST) return 0; int64_t n = ray_len(expr); - if (n < 2) return 0; + if (n != 2) return 0; ray_t** elems = (ray_t**)ray_data(expr); if (elems[0]->type != -RAY_SYM) return 0; ray_t* fn_obj = ray_env_get(elems[0]->i64); @@ -4248,14 +4705,97 @@ static bool simplify_agg_idiom(ray_t* val_expr, ray_t* tbl, * null-free col of tbl. Mirrors idiom.c:pre_no_nulls_on_asc_input. */ if (!col_expr || col_expr->type != -RAY_SYM || (col_expr->attrs & ATTR_QUOTED)) return false; - ray_t* col = ray_table_get_col(tbl, col_expr->i64); - if (!col || ray_vec_has_nulls(col)) return false; + if (!tbl_has_col(tbl, col_expr->i64) || + ray_table_col_has_nulls(tbl, col_expr->i64)) return false; *op_out = is_first ? OP_MIN : OP_MAX; *arg_out = col_expr; return true; } +/* The column a count(distinct) operand reads directly: a bare name of a + * column of `tbl` that no lexical local (a parameter, a let) hides. NULL + * for any other operand, which the evaluator resolves. */ +static ray_t* count_distinct_src_col(ray_t* tbl, ray_t* inner) { + if (!tbl || !inner || inner->type != -RAY_SYM || (inner->attrs & ATTR_QUOTED)) + return NULL; + if (ray_env_get_lexical_local(inner->i64) || !tbl_has_col(tbl, inner->i64)) return NULL; + return ray_table_col(tbl, inner->i64); +} + +/* The RAY_ENCCOL slot of column `sym` when it is a single-file encoded + * column not decoded whose whole decode would not stay cached + * (ray_enccol_decode_kept), which the bounded count-distinct kernel reads + * by range; NULL for any other slot (read as before). */ +static ray_t* cd_enc_slot(ray_t* tbl, int64_t sym) { + ray_t* e = ray_table_get_col_enc(tbl, sym); + ray_col_meta_t m; + return e && ray_col_meta_of(e, &m) && !RAY_IS_PARTED(m.type) && + !ray_enccol_decoded_peek(e) && !ray_enccol_decode_kept(e) ? e : NULL; +} + +/* The column the bounded count-distinct kernel reads for a count(distinct) + * operand: count_distinct_src_col's, as its encoded slot when it has one + * (cd_enc_slot: nothing decoded). */ +static ray_t* cd_bounded_src_col(ray_t* tbl, ray_t* inner) { + if (tbl && inner && inner->type == -RAY_SYM && !(inner->attrs & ATTR_QUOTED) && + !ray_env_get_lexical_local(inner->i64) && tbl_has_col(tbl, inner->i64)) { + ray_t* e = cd_enc_slot(tbl, inner->i64); + if (e) return e; + } + return count_distinct_src_col(tbl, inner); +} + +/* Whether the column count_distinct_src_col resolves suits the bounded + * count-distinct kernel; one that fails to decode does not (the path that + * reads it reports the error). A single-file encoded column is answered + * from its metadata, without a decode (a damaged one is reported by the + * read that follows). */ +static bool cd_src_bounded_ok(ray_t* tbl, ray_t* inner) { + if (tbl && inner && inner->type == -RAY_SYM && !(inner->attrs & ATTR_QUOTED) && + !ray_env_get_lexical_local(inner->i64) && tbl_has_col(tbl, inner->i64)) { + ray_t* e = ray_table_get_col_enc(tbl, inner->i64); + ray_col_meta_t m; + if (e && ray_col_meta_of(e, &m) && !RAY_IS_PARTED(m.type)) return ray_cd_bounded_col_ok(e, true); + } + ray_t* c = count_distinct_src_col(tbl, inner); + if (c && RAY_IS_ERR(c)) { ray_error_free(c); return false; } + return ray_cd_bounded_col_ok(c, true); +} + +static bool sym_names_col(ray_t* tbl, int64_t s); +static ray_t* match_count_distinct(ray_t* expr); + +/* Every non-agg a count(distinct) of a column the bounded kernel reads by + * range (cd_enc_slot): the bounded kernel then counts them over the row + * map, where the slices or the global hash would decode the column whole. */ +static bool cd_nonaggs_by_range(ray_t** nonagg_exprs, int64_t n_nonaggs, ray_t* tbl) { + if (n_nonaggs <= 0) return false; + for (int64_t ni = 0; ni < n_nonaggs; ni++) { + ray_t* in = match_count_distinct(nonagg_exprs[ni]); + if (!in || in->type != -RAY_SYM || (in->attrs & ATTR_QUOTED) || + ray_env_get_lexical_local(in->i64) || !tbl_has_col(tbl, in->i64)) + return false; + ray_t* e = cd_enc_slot(tbl, in->i64); + if (!e || !ray_cd_bounded_col_ok(e, true)) return false; + } + return true; +} + +/* Does a count(distinct) operand the evaluator resolves read none of the + * table's rows, so that it stays a collection counted whole in every group: + * a name that reads no column (a lexical local, a global), or an expression + * the planner lowers to constants alone (bound vectors and literals). The + * planner inlines a helper, so one whose body reads a column, itself or + * through another helper, reads the rows; an operand the planner does not + * lower is taken to read them and is gathered per group. */ +static bool cd_operand_is_collection(ray_t* inner, ray_t* tbl) { + if (!inner) return false; + if (inner->type == -RAY_SYM && !(inner->attrs & ATTR_QUOTED)) + return !sym_names_col(tbl, inner->i64); + return expr_is_constant_collection(inner, tbl, NULL); +} + static ray_t* match_count_distinct(ray_t* expr) { if (!expr || expr->type != RAY_LIST) return NULL; int64_t n = ray_len(expr); @@ -4327,12 +4867,12 @@ static int collect_col_refs(ray_t* expr, ray_t* tbl, if (!expr || n >= max_out) return n; if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { int64_t want = -1; - if (ray_table_get_col(tbl, expr->i64)) { + if (tbl_has_col(tbl, expr->i64)) { want = expr->i64; } else if (ray_sym_is_dotted(expr->i64)) { const int64_t* segs; int nsegs = ray_sym_segs(expr->i64, &segs); - if (nsegs >= 1 && ray_table_get_col(tbl, segs[0])) want = segs[0]; + if (nsegs >= 1 && tbl_has_col(tbl, segs[0])) want = segs[0]; } if (want >= 0) { for (int i = 0; i < n; i++) if (out_syms[i] == want) return n; @@ -4384,7 +4924,7 @@ static bool derived_key_expr_ok(ray_t* e, ray_t* tbl, int64_t col_sym, int64_t* if (e->type == -RAY_SYM) { /* A symbol literal — unless it names a column of the table, which * the DAG compiler resolves to that column. */ - if (e->attrs & ATTR_QUOTED) return ray_table_get_col(tbl, e->i64) == NULL; + if (e->attrs & ATTR_QUOTED) return !tbl_has_col(tbl, e->i64); if (e->i64 == col_sym) return true; for (int i = 0; i < nbound; i++) if (bound[i] == e->i64) return true; return false; /* free name */ @@ -4460,10 +5000,11 @@ static ray_t* group_key_eval(ray_t* v, ray_t* tbl) { for (int ri = 0; ri < n_refs; ri++) materialized_refs[ri] = NULL; ray_t* col_vec = NULL; for (int ri = 0; ri < n_refs && !col_vec; ri++) { - ray_t* ref_col = ray_table_get_col(tbl, ref_syms[ri]); + ray_t* ref_col = ray_table_col(tbl, ref_syms[ri]); + if (ref_col && RAY_IS_ERR(ref_col)) { col_vec = ref_col; break; } if (ref_col && (RAY_IS_PARTED(ref_col->type) || ref_col->type == RAY_MAPCOMMON)) { - ray_t* flat = query_materialize_parted_col(ref_col); + ray_t* flat = query_materialize_parted_col(ref_col, tbl); if (!flat || RAY_IS_ERR(flat)) { col_vec = flat ? flat : ray_error("oom", NULL); break; @@ -4490,8 +5031,11 @@ static ray_t* group_key_eval(ray_t* v, ray_t* tbl) { } for (int ri = 0; ri < n_refs; ri++) { if (materialized_refs[ri]) { - ray_t* ref_col = ray_table_get_col(tbl, ref_syms[ri]); - if (ref_col) ray_env_set_query_local(ref_syms[ri], ref_col); + /* The first pass cached this decode and a cached success is + * returned as is, so the error branch is unreachable. */ + ray_t* ref_col = ray_table_col(tbl, ref_syms[ri]); + if (ref_col && RAY_IS_ERR(ref_col)) ray_error_free(ref_col); + else if (ref_col) ray_env_set_query_local(ref_syms[ri], ref_col); ray_release(materialized_refs[ri]); } } @@ -4499,171 +5043,1565 @@ static ray_t* group_key_eval(ray_t* v, ray_t* tbl) { return col_vec; } -#define DERIVED_KEY_MAX_DOMAIN (64LL * 1024 * 1024) -/* The distinct-symbol evaluation, in chunks and over STR. - * - * Feeding the DAG a SYM column whose ids live in a FILE domain makes every - * string step of the expression a permanent cost: substr/str-find intern - * each distinct result into the global runtime table (with the dotted - * split, about 1 KB per URL) and an `if` that keeps the column itself - * translates its cells into runtime ids too. Over a 20M-entry vocabulary - * that is tens of GB that never come back. +/* ---- A key over an encoded column, evaluated piece by piece ---- * - * Here the referenced column is presented to the same DAG as a STR column - * built from the vocabulary bytes, CHUNK rows at a time: every - * intermediate is then a chunk-sized STR vector that dies with the chunk, - * and only the FINAL key strings are interned — once per distinct value, - * into a domain of the key vector's own (released with the result; the - * global table never grows by a derived value; positions = first-seen - * order of the keys, the order unsorted groups come out in). Applies only when the - * expression's result over the SYM column is SYM (so the result has the - * type the caller expects). File prefixes use the raw snapshot, the - * runtime domain its borrowed atom array, and a private in-memory domain - * resolves its stable atoms through the tail path. Any other shape - * returns NULL and the caller takes the one-shot SYM evaluation. */ -/* Chunk length in distinct values: 256 dispatch rounds of morsels (2M - * rows). Enough rows for the pooled string ops to spread over the - * workers, while every chunk-scoped STR intermediate stays in the - * low hundreds of MB at URL-sized strings. */ -#define DERIVED_KEY_CHUNK ((int64_t)RAY_MORSEL_ELEMS * RAY_DISPATCH_MORSELS * 256) + * group_key_eval reads every column the key names whole: an encoded + * (generation 2) column is decoded into one vector of the table's rows + * first, 800 MB for a 100 M-row timestamp the key only reads to take its + * minute. A key the DAG lowers to row-wise operators alone (each output + * row a function of the same input row: arithmetic, comparisons, casts, + * temporal extracts, string forms, `if`) gives the same values evaluated + * over consecutive row ranges. When such a key scans an encoded column + * whose whole decode would not stay cached anyway (ray_enccol_decode_kept: + * past the statement-boundary budget), the encoded columns are read + * KEY_RANGE rows at a time (ray_col_gather_span), each range evaluated as + * its own table, and only the key vector is whole. Plain columns are + * sliced. A decode the cache keeps is read as before, so a repeated + * query reuses it. */ +#define KEY_RANGE_ROWS ((int64_t)RAY_MORSEL_ELEMS * RAY_DISPATCH_MORSELS * 128) /* 1 M rows */ +#define KEY_RANGE_MAX_COLS 16 #ifdef DEBUG -static int64_t g_derived_key_chunk_test = 0; -/* Test seam: a positive value replaces the chunk length until reset to 0, - * so a test can drive several chunks through a small vocabulary. */ -void ray_derived_key_chunk_set_for_test(int64_t rows) { - g_derived_key_chunk_test = rows > 0 ? rows : 0; +static int64_t g_key_range_rows_test = 0; +/* Test seam: a positive multiple of RAY_MORSEL_ELEMS replaces the range + * length until reset to 0, so a test drives several ranges through a small + * table. */ +void ray_key_range_rows_set_for_test(int64_t rows) { + g_key_range_rows_test = rows > 0 && rows % RAY_MORSEL_ELEMS == 0 ? rows : 0; } #endif -static int64_t derived_key_chunk_rows(void) { +static int64_t key_range_rows(void) { #ifdef DEBUG - if (g_derived_key_chunk_test > 0) return g_derived_key_chunk_test; + if (g_key_range_rows_test > 0) return g_key_range_rows_test; #endif - return DERIVED_KEY_CHUNK; + return KEY_RANGE_ROWS; +} + +static bool key_range_op_rowwise(uint16_t opc) { + switch (opc) { + case OP_NEG: case OP_ABS: case OP_NOT: case OP_SQRT: + case OP_LOG: case OP_EXP: case OP_CEIL: case OP_FLOOR: case OP_ROUND: + case OP_SIN: case OP_ASIN: case OP_COS: case OP_ACOS: + case OP_TAN: case OP_ATAN: case OP_RECIPROCAL: case OP_SIGNUM: + case OP_ISNULL: case OP_CAST: + case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV: case OP_MOD: + case OP_POW: + case OP_EQ: case OP_NE: case OP_LT: case OP_LE: + case OP_GT: case OP_GE: case OP_AND: case OP_OR: + case OP_MIN2: case OP_MAX2: case OP_IF: + case OP_LIKE: case OP_ILIKE: case OP_UPPER: case OP_LOWER: + case OP_STRLEN: case OP_SUBSTR: case OP_REPLACE: case OP_TRIM: + case OP_CONCAT: case OP_STR_FIND: + case OP_EXTRACT: case OP_DATE_TRUNC: + return true; + default: + return false; + } } -/* ---- chunk STR build: the entries at positions dv[lo, lo+n) as one STR - * vector over one pool. Lengths and byte pointers are read on the workers - * (the raw snapshot needs no lock); a position past the file prefix — a - * runtime-appended entry — is resolved through the domain on the calling - * thread. A serial prefix sum places the pooled rows, then the workers - * write the descriptors and copy the pooled bytes into disjoint ranges. */ typedef struct { - const void* dv; - uint8_t dattrs; - int64_t lo; - const ray_sym_domain_raw_t* raw; - const char** ptr; - uint32_t* len; - uint32_t* off; - ray_str_t* dst; - char* pool; - ray_t* const* rstr; /* runtime domain: the borrowed atom array */ - uint32_t rcnt; - atomic_int late; -} dk_chunk_ctx_t; - -static void dk_chunk_scan_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - (void)wid; - dk_chunk_ctx_t* c = (dk_chunk_ctx_t*)vctx; - int late = 0; - for (int64_t i = start; i < end; i++) { - int64_t pos = ray_read_sym(c->dv, c->lo + i, RAY_SYM, c->dattrs); - if (c->rstr) { - /* runtime domain: the atom array borrowed once per chunk (no - * lock — nothing interns into the global table while the chunk - * is read) */ - ray_t* a = (pos >= 0 && pos < (int64_t)c->rcnt) ? c->rstr[pos] : NULL; - if (a && ray_str_len(a) <= UINT32_MAX) { - c->ptr[i] = ray_str_ptr(a); - c->len[i] = (uint32_t)ray_str_len(a); - } else { - c->ptr[i] = NULL; - c->len[i] = UINT32_MAX; - late++; - } - } else if (pos >= 0 && pos < c->raw->count) { - size_t sl = 0; - c->ptr[i] = ray_sym_domain_raw_str(c->raw, pos, &sl); - c->len[i] = (uint32_t)sl; - } else { - c->ptr[i] = NULL; - c->len[i] = UINT32_MAX; - late++; + ray_t* tbl; + int64_t syms[KEY_RANGE_MAX_COLS]; + int n_syms; + bool reads_enc; /* a scanned column is encoded and not decoded */ +} key_range_plan_t; + +/* Every node under op row-wise, every constant one value, every scan a + * column of the plan's table read in place or by range. */ +static bool key_range_walk(ray_graph_t* g, ray_op_t* op, key_range_plan_t* p, int depth) { + if (!op || depth > 64) return false; + uint16_t opc = op->opcode; + ray_op_ext_t* ext = find_ext(g, op->id); + if (opc == OP_CONST) return ext && ext->literal && ray_is_atom(ext->literal); + if (opc == OP_SCAN) { + if (!ext) return false; + uint16_t tid = 0; + memcpy(&tid, ext->base.pad, sizeof tid); + if (tid != 0) return false; + ray_col_meta_t m; + if (!ray_table_col_meta(p->tbl, ext->sym, &m) || RAY_IS_PARTED(m.type) || + m.type == RAY_MAPCOMMON || m.type == RAY_LIST) + return false; + int i = 0; + while (i < p->n_syms && p->syms[i] != ext->sym) i++; + if (i == p->n_syms) { + if (p->n_syms >= KEY_RANGE_MAX_COLS) return false; + p->syms[p->n_syms++] = ext->sym; + if (m.enc && !ray_enccol_decoded_peek(m.enc) && !ray_enccol_decode_kept(m.enc)) + p->reads_enc = true; } + return true; } - if (late) atomic_fetch_add_explicit(&c->late, late, memory_order_relaxed); + if (!key_range_op_rowwise(opc)) return false; + for (uint8_t i = 0; i < op->arity && i < 2; i++) + if (op->in_id[i] != RAY_OP_NONE && !key_range_walk(g, op_child(g, op, i), p, depth + 1)) + return false; + if ((opc == OP_IF || opc == OP_SUBSTR || opc == OP_REPLACE) && ext && + ext->third_in != RAY_OP_NONE && + !key_range_walk(g, op_node(g, ext->third_in), p, depth + 1)) + return false; + if (opc == OP_CONCAT && ext) { + int n_args = (int)ext->sym; + uint32_t* trail = (uint32_t*)((char*)(ext + 1)); + for (int i = 2; i < n_args; i++) + if (!key_range_walk(g, op_node(g, trail[i - 2]), p, depth + 1)) return false; + } + return true; } -static void dk_chunk_fill_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - (void)wid; - const dk_chunk_ctx_t* c = (const dk_chunk_ctx_t*)vctx; - for (int64_t i = start; i < end; i++) { - ray_str_t* d = &c->dst[i]; - uint32_t l = c->len[i]; - memset(d, 0, sizeof(*d)); - d->len = l; - if (l == 0) continue; - if (l <= RAY_STR_INLINE_MAX) { - memcpy(d->data, c->ptr[i], l); +/* Whether key `v` over `tbl` compiles to a row-wise DAG (metadata only: + * nothing is read) and, when need_enc, scans an encoded column not decoded + * whose whole decode would not stay cached (ray_enccol_decode_kept). + * Fills the plan's columns. */ +static bool key_range_plan_ex(ray_t* v, ray_t* tbl, key_range_plan_t* p, bool need_enc) { + memset(p, 0, sizeof *p); + p->tbl = tbl; + if (!v || v->type != RAY_LIST || !tbl || tbl->type != RAY_TABLE) return false; + if (ray_table_nrows(tbl) <= 0) return false; + /* no such column, no compile: a plain table takes none of this */ + bool any = !need_enc; + for (int64_t c = 0, nc = ray_table_ncols(tbl); c < nc && !any; c++) { + ray_t* e = ray_table_get_col_enc_idx(tbl, c); + any = e && !ray_enccol_decoded_peek(e) && !ray_enccol_decode_kept(e); + } + if (!any) return false; + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return false; + ray_op_t* root = compile_expr_dag(g, v); + bool ok = root && key_range_walk(g, root, p, 0) && (p->reads_enc || !need_enc); + ray_graph_free(g); + return ok; +} + +/* Whether key `v` over `tbl` is evaluated by range (key_eval_by_range). */ +static bool key_range_plan(ray_t* v, ray_t* tbl, key_range_plan_t* p) { + return key_range_plan_ex(v, tbl, p, true); +} + +/* The plan's columns bound for range reads: an encoded column not decoded + * as a source (srcs[k], bound[k]), any other one whole (plain[k], + * borrowed). NULL, or an owned error with nothing left bound. */ +static ray_t* key_range_bind(const key_range_plan_t* p, ray_col_src_t* srcs, ray_t** plain, bool* bound) { + ray_t* err = NULL; + for (int k = 0; k < p->n_syms; k++) { plain[k] = NULL; bound[k] = false; } + for (int k = 0; k < p->n_syms && !err; k++) { + ray_t* enc = ray_table_get_col_enc(p->tbl, p->syms[k]); + if (enc && !ray_enccol_decoded_peek(enc)) { + err = ray_table_col_src(p->tbl, p->syms[k], &srcs[k]); + if (!err) bound[k] = true; } else { - memcpy(c->pool + c->off[i], c->ptr[i], l); - memcpy(d->prefix, c->ptr[i], 4); - d->pool_off = c->off[i]; + plain[k] = ray_table_col(p->tbl, p->syms[k]); /* plain, or already decoded */ + if (!plain[k]) err = ray_error("schema", NULL); + else if (RAY_IS_ERR(plain[k])) { err = plain[k]; plain[k] = NULL; } } } + if (err) + for (int k = 0; k < p->n_syms; k++) if (bound[k]) { ray_col_src_release(&srcs[k]); bound[k] = false; } + return err; } -/* The bytes of entries dv[lo, lo+n) as (ptr, len) views: read on the - * workers off the raw snapshot (FILE) or the borrowed atom array (the - * runtime domain), a position past either resolved through the domain on - * the calling thread. False on a length past UINT32_MAX. */ -static bool dk_chunk_views(const void* dv, uint8_t dattrs, int64_t lo, int64_t n, - const ray_sym_domain_raw_t* raw, struct ray_sym_domain_s* dom, - const char** ptr, uint32_t* len) { - dk_chunk_ctx_t c; - memset(&c, 0, sizeof(c)); - c.dv = dv; c.dattrs = dattrs; c.lo = lo; c.raw = raw; - c.ptr = ptr; - c.len = len; - if (dom == ray_sym_runtime_domain()) { - ray_t** rs = NULL; uint32_t rc = 0; - ray_sym_strings_borrow(&rs, &rc); - c.rstr = rs; c.rcnt = rc; - } - atomic_store_explicit(&c.late, 0, memory_order_relaxed); - ray_pool_t* pool = ray_pool_get(); - if (ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) - ray_pool_dispatch(pool, dk_chunk_scan_fn, &c, n); - else - dk_chunk_scan_fn(&c, 0, 0, n); - if (atomic_load_explicit(&c.late, memory_order_relaxed)) { - for (int64_t i = 0; i < n; i++) { - if (len[i] != UINT32_MAX) continue; - int64_t pos = ray_read_sym(dv, lo + i, RAY_SYM, dattrs); - ray_t* a = ray_sym_domain_str(dom, pos); - size_t sl = a ? ray_str_len(a) : 0; - if (sl > UINT32_MAX) return false; - ptr[i] = a ? ray_str_ptr(a) : ""; - len[i] = (uint32_t)sl; - } +static void key_range_unbind(const key_range_plan_t* p, ray_col_src_t* srcs, bool* bound) { + for (int k = 0; k < p->n_syms; k++) if (bound[k]) { ray_col_src_release(&srcs[k]); bound[k] = false; } +} + +/* Key `v` over rows [lo, hi) of the plan's table, its columns bound by + * key_range_bind: the owned result of group_key_eval over a table of those + * rows (a value or an owned error), or NULL when it declines. */ +static ray_t* key_range_piece(ray_t* v, const key_range_plan_t* p, ray_col_src_t* srcs, + ray_t* const* plain, const bool* bound, int64_t lo, int64_t hi) { + ray_t* err = NULL; + ray_t* ct = ray_table_new(p->n_syms); + if (!ct || RAY_IS_ERR(ct)) return ct ? ct : ray_error("oom", NULL); + for (int k = 0; k < p->n_syms && !err; k++) { + ray_t* piece = NULL; + if (bound[k]) err = ray_col_gather_span(&srcs[k], lo, hi, &piece); + else { + piece = ray_vec_slice(plain[k], lo, hi - lo); + if (!piece || RAY_IS_ERR(piece)) { err = piece ? piece : ray_error("oom", NULL); piece = NULL; } + } + if (err) break; + ray_t* nt = ray_table_add_col(ct, p->syms[k], piece); + ray_release(piece); + if (!nt || RAY_IS_ERR(nt)) { err = nt ? nt : ray_error("oom", NULL); ct = NULL; break; } + ct = nt; + } + if (err) { if (ct) ray_release(ct); return err; } + /* the range's columns are the query's locals while it runs, as + * bind_referenced_columns binds the whole ones */ + ray_t* r = NULL; + if (ray_env_push_query_scope() != RAY_OK) r = ray_error("oom", NULL); + else { + ray_t* prev = g_active_query_table; + g_active_query_table = ct; + for (int k = 0; k < p->n_syms; k++) { + ray_t* cv = ray_table_col(ct, p->syms[k]); + if (cv && !RAY_IS_ERR(cv)) ray_env_set_query_local(p->syms[k], cv); + } + r = group_key_eval(v, ct); + g_active_query_table = prev; + ray_env_pop_scope(); } - return true; + ray_release(ct); + return r; } -static ray_t* derived_key_chunk_strs(const void* dv, uint8_t dattrs, int64_t lo, int64_t n, - const ray_sym_domain_raw_t* raw, - struct ray_sym_domain_s* dom) { +/* The element types a key's ranges are joined in: fixed width, no domain. */ +static bool key_range_type_ok(int8_t t) { + switch (t) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_F32: case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + return true; + default: + return false; + } +} + +/* Key `v` over `tbl` evaluated by range (see above): an owned vector of + * the table's rows, an owned error (a range that fails to read, or the + * key's own), or NULL when the key is not evaluated this way (a shape the + * plan declines, a result type the ranges are not joined in): the caller + * then binds the columns and evaluates it whole. */ +static ray_t* key_eval_by_range(ray_t* v, ray_t* tbl) { + key_range_plan_t p; + if (!key_range_plan(v, tbl, &p)) return NULL; + const int64_t n = ray_table_nrows(tbl); + const int64_t step = key_range_rows(); + ray_col_src_t srcs[KEY_RANGE_MAX_COLS]; + ray_t* plain[KEY_RANGE_MAX_COLS]; + bool bound[KEY_RANGE_MAX_COLS]; + ray_t* err = key_range_bind(&p, srcs, plain, bound); + ray_t* out = NULL; + uint8_t nulls = 0; + bool declined = false; + for (int64_t lo = 0; lo < n && !err && !declined; lo += step) { + int64_t hi = lo + step < n ? lo + step : n; + ray_t* r = key_range_piece(v, &p, srcs, plain, bound, lo, hi); + if (!r) { declined = true; break; } + if (RAY_IS_ERR(r)) { err = r; break; } + if (!ray_is_vec(r) || (r->attrs & RAY_ATTR_SLICE) || ray_len(r) != hi - lo || + !key_range_type_ok(r->type) || (out && r->type != out->type)) { + ray_release(r); + declined = true; + break; + } + if (!out) { + out = ray_vec_new(r->type, n); + if (!out || RAY_IS_ERR(out)) { ray_release(r); err = out ? out : ray_error("oom", NULL); out = NULL; break; } + out->len = n; + } + size_t esz = ray_sym_elem_size(r->type, r->attrs); + memcpy((char*)ray_data(out) + (size_t)lo * esz, ray_data(r), (size_t)(hi - lo) * esz); + nulls |= r->attrs & RAY_ATTR_HAS_NULLS; + ray_release(r); + } + key_range_unbind(&p, srcs, bound); + if (err || declined || !out) { + if (out) ray_release(out); + return err; + } + out->attrs |= nulls; + return out; +} + +/* The slot a by-dict value renames ({k: col}) when it is an encoded column + * read by range (cd_enc_slot): the grouping then reads the slot under the + * new name, where evaluating the name decoded the column whole. NULL for + * any other value. */ +static ray_t* cd_enc_slot(ray_t* tbl, int64_t sym); +static ray_t* bydict_enc_rename(ray_t* v, ray_t* tbl) { + if (!v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED) || !tbl || tbl->type != RAY_TABLE) return NULL; + if (ray_env_get_lexical_local(v->i64) || !ray_table_has_col(tbl, v->i64)) return NULL; + return cd_enc_slot(tbl, v->i64); +} + +/* group_key_eval of a key for a caller that binds the columns it reads + * (bind_referenced_columns) only when the key is evaluated whole: by + * range when key_eval_by_range takes it, else bound and evaluated. The + * caller has pushed the query scope. */ +static ray_t* group_key_eval_bound(ray_t* v, ray_t* tbl) { + ray_t* r = key_eval_by_range(v, tbl); + if (r) return r; + r = bind_referenced_columns(tbl, &v, 1); + return r ? r : group_key_eval(v, tbl); +} + +/* ---- The top groups by count, exactly, in two passes -------------------- + * + * (select {from: T by: K c: (count x) desc: c take: N}) keeps N groups while + * the grouping holds every one of them: 56 M groups over 100 M rows, which + * past a 1 GB budget the radix route spills to disk wave by wave. For count + * outputs over fixed-width keys (integer, temporal and SYM columns, and + * row-wise computed keys of integer or temporal type over them): + * pass A: the 64-bit hash of every row's composite key enters a heavy- + * hitter summary of the worker that reads the row (Misra-Gries, the + * counter form of SpaceSaving): m counters; a full summary takes the + * median count d off every counter, drops those left at zero and adds d + * to its error E. A hash's row count is at least its estimate and at + * most its estimate plus E; a hash not in the summary has at most E rows. + * The summaries merge by summing (their errors add, as does a reduce of + * the merged one): every hash of more than E = sum(E_t) rows is in it, + * with E_t at most 2 N_t / m; + * candidates: the hashes whose estimate plus E reaches L, the N-th largest + * estimate. A hash left out has fewer than L rows, and E_eff, the + * largest bound of a hash left out (E when none is), covers it; + * pass B: the rows whose hash is a candidate are grouped exactly, by their + * key values (never by the hash), each group with its first row; + * the check: T, the N-th largest exact count, exceeds E_eff. A group whose + * hash is no candidate has at most E_eff < T rows, so it is neither in + * the top N nor tied at T: the groups taken in count-descending, first- + * row order are the grouping's cut (it emits groups in first-seen order + * and the sort is stable). When fewer than N groups are found the check + * holds only with E_eff = 0 (every group found). Otherwise — near-unique + * keys, where the summary saturates — the query takes the grouping. + * The dense route emits its groups in key order, not first-seen, so a shape + * whose key value ranges a dense plan could take (hh_dense_possible) is left + * to the grouping. The keys are read a range at a time (KEY_RANGE_ROWS: + * generation 2 by ray_col_gather_span, a computed key by key_range_piece) in + * both passes, so no key vector of the table's rows is built. And only a + * grouping that would outgrow the memory budget (hh_grouping_outgrows) takes + * the two passes: one that fits RAM is faster than reading the keys twice. */ +#define HH_MAX_KEYS 8 +#define HH_MAX_OUTS 8 +#define HH_MAX_TAKE 1024 +#define HH_MIN_ROWS ((int64_t)1 << 20) +#define HH_MAX_CAND ((int64_t)1 << 16) /* candidate hashes pass B takes */ +#define HH_CAND_PER_TAKE 64 /* and per row taken, at least 4096 */ +#define HH_BLK 256 /* rows hashed per block */ +#define HH_HIST 256 /* reduce: counts below this by histogram */ +#define HH_SUM_BUDGET ((size_t)256 << 20) /* every worker's pass A summary together */ +#ifdef DEBUG +static int64_t g_hh_min_rows_test = 0; +static int64_t g_hh_counters_test = 0; +static int g_hh_hash_bits_test = 0; +static int g_hh_mem_gate_test = 0; +static int64_t g_hh_ex_budget_test = 0; +static int64_t g_hh_stats[10]; +/* Test seams: the row count from which the shape is taken (a positive value + * replaces HH_MIN_ROWS; INT64_MAX turns the path off), the counters of a + * worker's summary (positive: replaces the sizing), the bits of the key hash + * kept (1..63: distinct keys collide), the memory gate (1: always past the + * budget, -1: never, 0: hh_grouping_outgrows), each 0 to restore. */ +void ray_group_topk_min_rows_set_for_test(int64_t rows) { g_hh_min_rows_test = rows > 0 ? rows : 0; } +void ray_group_topk_counters_set_for_test(int64_t m) { g_hh_counters_test = m > 0 ? m : 0; } +void ray_group_topk_hash_bits_set_for_test(int bits) { g_hh_hash_bits_test = bits > 0 && bits < 64 ? bits : 0; } +void ray_group_topk_mem_gate_set_for_test(int mode) { g_hh_mem_gate_test = mode > 0 ? 1 : mode < 0 ? -1 : 0; } +/* The pass B budget, all workers together (positive: replaces hh_ex_budget). */ +void ray_group_topk_ex_budget_set_for_test(int64_t bytes) { g_hh_ex_budget_test = bytes > 0 ? bytes : 0; } +/* out[0] answers, out[1] fallbacks after the passes, out[2] shapes left to a + * dense plan; of the last run, out[3] its route (1 answered, 2 fell back, + * 3 dense, 4 pass A saturated, 5 the grouping fits the budget), out[4] + * E_eff, out[5] T (-1: fewer than N groups or not reached), out[6] the + * candidate hashes, out[7] the groups pass B made; out[8] shapes left to the + * grouping by the memory gate; out[9] the bytes of a pass B table of the last + * run (0: no pass B). */ +void ray_group_topk_stats_for_test(int64_t out[10]) { memcpy(out, g_hh_stats, sizeof g_hh_stats); } +#define HH_STAT(i, v) (g_hh_stats[i] = (v)) +#else +#define HH_STAT(i, v) ((void)0) +#endif +static int64_t hh_min_rows(void) { +#ifdef DEBUG + if (g_hh_min_rows_test > 0) return g_hh_min_rows_test; +#endif + return HH_MIN_ROWS; +} +static int hh_hash_bits(void) { +#ifdef DEBUG + return g_hh_hash_bits_test; +#else + return 0; +#endif +} + +/* The memory gate: two passes only when the grouping would outgrow the + * budget a query plans for (ray_heap_mem_budget: the -m watermark, else the + * RAM limit). Its state is estimated as every row's key bytes and an 8-byte + * count, nrows * row_bytes; the radix route moves that at least twice + * (scattered, then grouped), so a grouping past a quarter of the budget + * spills waves to disk. Below that the grouping, in RAM, beats reading the + * keys twice. 100 M rows of 8 + 8 + 4 + 8 bytes (2.8 GB) take two passes + * under 11.2 GB and the grouping from there; an unknown budget keeps the + * grouping. */ +#define HH_MEM_SHARE 4 +static bool hh_grouping_outgrows(int64_t nrows, int64_t row_bytes) { +#ifdef DEBUG + if (g_hh_mem_gate_test) return g_hh_mem_gate_test > 0; +#endif + int64_t budget = ray_heap_mem_budget(); + if (budget <= 0) return false; + return (double)nrows * (double)row_bytes * HH_MEM_SHARE > (double)budget; +} + +typedef struct { const void* data; int8_t type; uint8_t attrs; } hh_piece_t; + +typedef struct { + bool computed; + int64_t name; /* output column */ + int64_t col; /* a column key: its column */ + ray_t* expr; /* a computed key (borrowed from the query) */ + ray_col_src_t src; /* column key, bound in place (never copied) */ + bool src_bound; + const void* base; /* column read in place, or NULL: by range */ + int8_t type; + uint8_t attrs; + key_range_plan_t plan; /* computed key: its columns */ + ray_col_src_t psrcs[KEY_RANGE_MAX_COLS]; + ray_t* pplain[KEY_RANGE_MAX_COLS]; + bool pbound[KEY_RANGE_MAX_COLS]; + bool plan_bound; + bool ctype_set; /* computed: type of its first range */ +} hh_key_t; + +/* A heavy-hitter summary: open addressing over the hash (0 is the empty + * slot), at most m entries in mask + 1 slots; c the estimate (at least the + * hash's rows less E), x a worker's E when the entry came in (the rows + * since then are c + E - x, exactly) or, merged, a lower bound of the + * hash's rows; tmp holds 2 m values. */ +typedef struct { + uint64_t* h; + int64_t* c; + int64_t* x; + int64_t* tmp; + uint64_t mask; + int64_t n, m, E; + bool merged; + int64_t mn[HH_MAX_KEYS], mx[HH_MAX_KEYS]; + bool nul[HH_MAX_KEYS]; +} hh_sum_t; + +/* Exact groups of pass B: key values (nk per slot), count, first row. */ +typedef struct { + uint64_t* h; + int64_t* kv; + int64_t* c; + int64_t* first; + uint64_t mask; + int64_t n, lim; + int nk; + bool full; +} hh_ex_t; + +typedef struct { + int nk; + int bits; + hh_piece_t pc[HH_MAX_KEYS]; + int64_t lo; /* table row of the pieces' first row */ + hh_sum_t* sums; + hh_ex_t* exs; + const uint64_t* cand; + uint64_t cmask; + uint32_t W; /* workers: sums[] / exs[] entries */ + int64_t K; + bool checked; /* pass A's saturation check ran */ + bool saturated; /* ... and stopped the pass */ +} hh_pass_t; + +static bool table_has_parted_columns(ray_t* tbl); + +static inline int64_t hh_null_of(int8_t t) { + switch (t) { + case RAY_I16: return NULL_I16; + case RAY_I32: case RAY_DATE: case RAY_TIME: return NULL_I32; + default: return NULL_I64; /* I64 / TIMESTAMP; never a BOOL, U8 or SYM value */ + } +} + +static bool hh_col_type_ok(int8_t t) { + switch (t) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_SYM: + return true; + default: + return false; + } +} + +/* A computed key's value type: fixed width, no domain, no float. */ +static bool hh_ctype_ok(int8_t t) { return t != RAY_SYM && hh_col_type_ok(t); } + +/* Values [b, b + n) of a piece as int64 (SYM: its codes). */ +static inline void hh_load(const hh_piece_t* p, int64_t b, int64_t n, int64_t* out) { + switch (p->type) { + case RAY_BOOL: case RAY_U8: { + const uint8_t* s = (const uint8_t*)p->data + b; + for (int64_t i = 0; i < n; i++) out[i] = s[i]; + break; + } + case RAY_I16: { + const int16_t* s = (const int16_t*)p->data + b; + for (int64_t i = 0; i < n; i++) out[i] = s[i]; + break; + } + case RAY_I32: case RAY_DATE: case RAY_TIME: { + const int32_t* s = (const int32_t*)p->data + b; + for (int64_t i = 0; i < n; i++) out[i] = s[i]; + break; + } + case RAY_SYM: + switch (p->attrs & RAY_SYM_W_MASK) { + case RAY_SYM_W8: { const uint8_t* s = (const uint8_t*)p->data + b; for (int64_t i = 0; i < n; i++) out[i] = s[i]; break; } + case RAY_SYM_W16: { const uint16_t* s = (const uint16_t*)p->data + b; for (int64_t i = 0; i < n; i++) out[i] = s[i]; break; } + case RAY_SYM_W32: { const uint32_t* s = (const uint32_t*)p->data + b; for (int64_t i = 0; i < n; i++) out[i] = s[i]; break; } + default: { const int64_t* s = (const int64_t*)p->data + b; for (int64_t i = 0; i < n; i++) out[i] = s[i]; break; } + } + break; + default: { + const int64_t* s = (const int64_t*)p->data + b; + for (int64_t i = 0; i < n; i++) out[i] = s[i]; + break; + } + } +} + +/* Keys and hashes of rows [b, b + n) of the pieces (n <= HH_BLK). */ +static inline void hh_hash_block(const hh_pass_t* c, int64_t b, int64_t n, + int64_t (*vals)[HH_BLK], uint64_t* hs) { + for (int k = 0; k < c->nk; k++) hh_load(&c->pc[k], b, n, vals[k]); + for (int64_t i = 0; i < n; i++) hs[i] = ray_hash_i64(vals[0][i]); + for (int k = 1; k < c->nk; k++) + for (int64_t i = 0; i < n; i++) hs[i] = ray_hash_combine(hs[i], (uint64_t)vals[k][i]); + uint64_t keep = c->bits ? ((uint64_t)1 << c->bits) - 1 : ~(uint64_t)0; + for (int64_t i = 0; i < n; i++) { + uint64_t h = hs[i] & keep; + hs[i] = h + (h == 0); /* 0 marks an empty slot */ + } +} + +/* The k-th smallest (0-based) of a[0..n): quickselect, three-way. */ +static int64_t hh_kth(int64_t* a, int64_t n, int64_t k) { + int64_t lo = 0, hi = n - 1; + while (lo < hi) { + int64_t x = a[lo], y = a[lo + (hi - lo) / 2], z = a[hi]; + int64_t p = x < y ? (y < z ? y : (x < z ? z : x)) : (x < z ? x : (y < z ? z : y)); + int64_t lt = lo, i = lo, gt = hi; + while (i <= gt) { + if (a[i] < p) { int64_t t = a[lt]; a[lt++] = a[i]; a[i++] = t; } + else if (a[i] > p) { int64_t t = a[gt]; a[gt--] = a[i]; a[i] = t; } + else i++; + } + if (k < lt) hi = lt - 1; + else if (k > gt) lo = gt + 1; + else return p; + } + return a[lo]; +} + +static inline void hh_sum_put(hh_sum_t* s, uint64_t h, int64_t cnt, int64_t x) { + uint64_t i = h & s->mask; + while (s->h[i]) i = (i + 1) & s->mask; + s->h[i] = h; + s->c[i] = cnt; + s->x[i] = x; + s->n++; +} + +/* Take the lower median count d off every counter: at least half of them + * reach zero and leave, at least half lose d (so the d's of all reduces sum + * to at most 2 N / m). */ +static void hh_sum_reduce(hh_sum_t* s) { + const uint64_t cap = s->mask + 1; + int64_t hist[HH_HIST]; + memset(hist, 0, sizeof hist); + for (uint64_t i = 0; i < cap; i++) + if (s->h[i]) hist[s->c[i] < HH_HIST ? s->c[i] : 0]++; + const int64_t need = (s->n + 1) / 2; + int64_t d = 0, cum = 0; + for (int64_t v = 1; v < HH_HIST && !d; v++) { + cum += hist[v]; + if (cum >= need) d = v; + } + if (!d) { + int64_t nb = 0; + for (uint64_t i = 0; i < cap; i++) + if (s->h[i] && s->c[i] >= HH_HIST) s->tmp[nb++] = s->c[i]; + d = hh_kth(s->tmp, nb, need - cum - 1); + } + /* the survivors (at most half) as triples in tmp, then put back */ + int64_t ns = 0; + for (uint64_t i = 0; i < cap; i++) + if (s->h[i] && s->c[i] > d) { + s->tmp[3 * ns] = (int64_t)s->h[i]; + s->tmp[3 * ns + 1] = s->c[i] - d; + s->tmp[3 * ns + 2] = s->x[i]; + ns++; + } + memset(s->h, 0, cap * sizeof(uint64_t)); + s->n = 0; + for (int64_t j = 0; j < ns; j++) + hh_sum_put(s, (uint64_t)s->tmp[3 * j], s->tmp[3 * j + 1], s->tmp[3 * j + 2]); + s->E += d; +} + +/* cnt rows of hash h; merged, lb more rows of it for certain. */ +static inline void hh_sum_add(hh_sum_t* s, uint64_t h, int64_t cnt, int64_t lb) { + uint64_t i = h & s->mask; + while (s->h[i] && s->h[i] != h) i = (i + 1) & s->mask; + if (s->h[i]) { + s->c[i] += cnt; + if (s->merged) s->x[i] += lb; + return; + } + if (s->n >= s->m) { hh_sum_reduce(s); hh_sum_put(s, h, cnt, s->merged ? lb : s->E); return; } + s->h[i] = h; + s->c[i] = cnt; + s->x[i] = s->merged ? lb : s->E; + s->n++; +} + +static bool hh_sum_init(hh_sum_t* s, int64_t m, bool merged) { + memset(s, 0, sizeof *s); + uint64_t cap = 64; + while (cap < (uint64_t)m * 2) cap <<= 1; + s->h = ray_calloc_raw(cap * sizeof(uint64_t)); + s->c = ray_alloc_raw(cap * sizeof(int64_t)); + s->x = ray_alloc_raw(cap * sizeof(int64_t)); + s->tmp = ray_alloc_raw((size_t)(m > 0 ? m : 1) * 2 * sizeof(int64_t)); + s->mask = cap - 1; + s->m = m; + s->merged = merged; + for (int k = 0; k < HH_MAX_KEYS; k++) { s->mn[k] = INT64_MAX; s->mx[k] = INT64_MIN; } + return s->h && s->c && s->x && s->tmp; +} + +static void hh_sum_free(hh_sum_t* s) { + ray_free_raw(s->h); ray_free_raw(s->c); ray_free_raw(s->x); ray_free_raw(s->tmp); + s->h = NULL; s->c = NULL; s->x = NULL; s->tmp = NULL; +} + +static inline bool hh_cand_has(const uint64_t* set, uint64_t mask, uint64_t h) { + uint64_t i = h & mask; + while (set[i]) { + if (set[i] == h) return true; + i = (i + 1) & mask; + } + return false; +} + +/* Count `cnt` rows of key `key` (first row `first`) into its exact group: + * the slot of the same hash AND the same key values. False when a new + * group would pass the table's limit. */ +static inline bool hh_ex_add(hh_ex_t* x, uint64_t h, const int64_t* key, int64_t cnt, int64_t first) { + const int nk = x->nk; + uint64_t i = h & x->mask; + while (x->h[i]) { + if (x->h[i] == h && memcmp(&x->kv[i * (uint64_t)nk], key, (size_t)nk * sizeof(int64_t)) == 0) { + x->c[i] += cnt; + if (first < x->first[i]) x->first[i] = first; + return true; + } + i = (i + 1) & x->mask; + } + if (x->n >= x->lim) return false; + x->h[i] = h; + memcpy(&x->kv[i * (uint64_t)nk], key, (size_t)nk * sizeof(int64_t)); + x->c[i] = cnt; + x->first[i] = first; + x->n++; + return true; +} + +/* Slots of a pass B table of lim groups (at most half full). */ +static uint64_t hh_ex_cap(int64_t lim) { + uint64_t cap = 64; + while (cap < (uint64_t)lim * 2) cap <<= 1; + return cap; +} + +/* The pass B tables' budget, all workers together: HH_SUM_BUDGET, at most + * an eighth of the memory budget. */ +static uint64_t hh_ex_budget(void) { +#ifdef DEBUG + if (g_hh_ex_budget_test > 0) return (uint64_t)g_hh_ex_budget_test; +#endif + uint64_t b = HH_SUM_BUDGET; + int64_t mb = ray_heap_mem_budget(); + if (mb > 0 && (uint64_t)mb / 8 < b) b = (uint64_t)mb / 8; + return b; +} + +static bool hh_ex_init(hh_ex_t* x, int nk, int64_t lim) { + memset(x, 0, sizeof *x); + uint64_t cap = hh_ex_cap(lim); + x->h = ray_calloc_raw(cap * sizeof(uint64_t)); + x->kv = ray_alloc_raw(cap * (uint64_t)nk * sizeof(int64_t)); + x->c = ray_alloc_raw(cap * sizeof(int64_t)); + x->first = ray_alloc_raw(cap * sizeof(int64_t)); + x->mask = cap - 1; + x->lim = lim; + x->nk = nk; + return x->h && x->kv && x->c && x->first; +} + +static void hh_ex_free(hh_ex_t* x) { + ray_free_raw(x->h); ray_free_raw(x->kv); ray_free_raw(x->c); ray_free_raw(x->first); + x->h = NULL; x->kv = NULL; x->c = NULL; x->first = NULL; +} + +static void hh_pass_a_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + hh_pass_t* c = (hh_pass_t*)ctx; + hh_sum_t* s = &c->sums[wid]; + int64_t vals[HH_MAX_KEYS][HH_BLK]; + uint64_t hs[HH_BLK]; + for (int64_t b = start; b < end; b += HH_BLK) { + int64_t n = end - b < HH_BLK ? end - b : HH_BLK; + hh_hash_block(c, b, n, vals, hs); + for (int k = 0; k < c->nk; k++) { + const int64_t nv = hh_null_of(c->pc[k].type); + int64_t mn = s->mn[k], mx = s->mx[k]; + bool nul = false; + for (int64_t i = 0; i < n; i++) { + int64_t v = vals[k][i]; + if (v == nv) { nul = true; continue; } + if (v < mn) mn = v; + if (v > mx) mx = v; + } + s->mn[k] = mn; s->mx[k] = mx; + s->nul[k] |= nul; + } + for (int64_t i = 0; i < n; i++) hh_sum_add(s, hs[i], 1, 0); + } +} + +static void hh_pass_b_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + hh_pass_t* c = (hh_pass_t*)ctx; + hh_ex_t* x = &c->exs[wid]; + if (x->full) return; + int64_t vals[HH_MAX_KEYS][HH_BLK]; + uint64_t hs[HH_BLK]; + int64_t key[HH_MAX_KEYS]; + for (int64_t b = start; b < end; b += HH_BLK) { + int64_t n = end - b < HH_BLK ? end - b : HH_BLK; + hh_hash_block(c, b, n, vals, hs); + for (int64_t i = 0; i < n; i++) { + if (!hh_cand_has(c->cand, c->cmask, hs[i])) continue; + for (int k = 0; k < c->nk; k++) key[k] = vals[k][i]; + if (!hh_ex_add(x, hs[i], key, 1, c->lo + b + i)) { x->full = true; return; } + } + } +} + +static void hh_run(hh_pass_t* c, int64_t n, ray_pool_fn fn) { + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) ray_pool_dispatch(pool, fn, c, n); + else fn(c, 0, 0, n); +} + +/* Whether a dense plan (agg_dense_plan_src) could take keys whose value + * ranges are rng[] over nrows rows: the product within the row count, one + * key of at most AGG_WIDE_RANGE_PER_ROW (16) slots per row, or several whose + * compaction (keys of at most 1 << 22 codes) could fit. Monotone: a range + * at least the plan's makes it say yes no less often. */ +static bool hh_dense_possible(int nk, const int64_t* rng, const bool* nul, int64_t nrows) { + const int64_t lim = nrows < (int64_t)UINT32_MAX ? nrows : (int64_t)UINT32_MAX; + int64_t total = 1; + bool over = false; + for (int k = 0; k < nk && !over; k++) { + if (rng[k] <= 0) return true; + if (total > lim / rng[k]) over = true; + else total *= rng[k]; + } + if (!over) return true; + if (nk == 1) return rng[0] / 16 <= nrows; + int64_t fixed = 1; + bool any = false; + for (int k = 0; k < nk; k++) { + int64_t raw = rng[k] - (nul[k] ? 1 : 0); + if (raw > 1 && raw <= ((int64_t)1 << 22)) { any = true; continue; } + if (fixed > lim / rng[k]) return false; + fixed *= rng[k]; + } + return any; +} + +/* The key pieces of rows [lo, hi): pc[k] and the vector it owns in own[k] + * (released by the caller, also on an error). An owned error (the caller + * declines), or NULL; *declined when a computed key's range is not of a + * type this path groups. */ +static ray_t* hh_pieces(hh_key_t* ks, int nk, int64_t lo, int64_t hi, hh_piece_t* pc, + ray_t** own, bool* declined) { + for (int k = 0; k < nk; k++) own[k] = NULL; + for (int k = 0; k < nk; k++) { + hh_key_t* q = &ks[k]; + if (!q->computed && q->base) { + pc[k].data = (const char*)q->base + (size_t)lo * ray_sym_elem_size(q->type, q->attrs); + pc[k].type = q->type; + pc[k].attrs = q->attrs; + continue; + } + ray_t* r = NULL; + if (!q->computed) { + ray_t* err = ray_col_gather_span(&q->src, lo, hi, &r); + if (err) return err; + } else { + r = key_range_piece(q->expr, &q->plan, q->psrcs, q->pplain, q->pbound, lo, hi); + if (!r) { *declined = true; return NULL; } + if (RAY_IS_ERR(r)) return r; + } + own[k] = r; + if (!ray_is_vec(r) || ray_len(r) != hi - lo || + (q->computed ? !hh_ctype_ok(r->type) || (q->ctype_set && r->type != q->type) + : r->type != q->type)) { + *declined = true; + return NULL; + } + if (q->computed && !q->ctype_set) { q->type = r->type; q->attrs = r->attrs; q->ctype_set = true; } + pc[k].data = ray_data(r); + pc[k].type = r->type; + pc[k].attrs = r->attrs; + } + return NULL; +} + +/* Pass A after an eighth of the rows: whether the summaries look saturated + * (near-unique keys), the sum over the workers of their N-th largest lower + * bound at most half the error so far. T would then end below E: the + * grouping answers, without the rest of the pass. A guess only — a wrong + * one costs the shortcut, never the answer. */ +static bool hh_saturated(hh_pass_t* c) { + int64_t Lsum = 0, Esum = 0; + for (uint32_t w = 0; w < c->W; w++) { + hh_sum_t* s = &c->sums[w]; + Esum += s->E; + if (s->n < c->K) continue; + int64_t j = 0; + for (uint64_t i = 0; i <= s->mask; i++) if (s->h[i]) s->tmp[j++] = s->c[i] + s->E - s->x[i]; + Lsum += hh_kth(s->tmp, j, j - c->K); + } + return Esum > 0 && 2 * Lsum <= Esum; +} + +/* One pass over the table's rows by range: the pieces of each range to fn + * on the workers. A range is KEY_RANGE_ROWS, or about a 64th of a smaller + * table (64 K rows at least), so the pieces a range reads stay in + * proportion to the table. False when a range fails to read, is + * interrupted or declines (*err: an owned error, when there is one). */ +static bool hh_pass(hh_key_t* ks, int nk, int64_t nrows, hh_pass_t* c, ray_pool_fn fn, ray_t** err) { + int64_t step = key_range_rows(); +#ifdef DEBUG + if (g_key_range_rows_test <= 0) +#endif + while (step > ((int64_t)64 << 10) && step / 2 >= nrows / 64) step /= 2; + *err = NULL; + for (int64_t lo = 0; lo < nrows; lo += step) { + if (ray_interrupted()) { *err = ray_error("cancel", "interrupted"); return false; } + int64_t hi = lo + step < nrows ? lo + step : nrows; + ray_t* own[HH_MAX_KEYS]; + bool declined = false; + *err = hh_pieces(ks, nk, lo, hi, c->pc, own, &declined); + bool ok = !*err && !declined; + if (ok) { + c->lo = lo; + hh_run(c, hi - lo, fn); + } + for (int k = 0; k < nk; k++) if (own[k]) ray_release(own[k]); + if (!ok) return false; + if (c->exs) + for (uint32_t w = 0; w < c->W; w++) if (c->exs[w].full) return false; + if (c->sums && !c->checked && hi >= nrows / 8 && hi < nrows) { + c->checked = true; + if (hh_saturated(c)) { c->saturated = true; return false; } + } + } + return true; +} + +/* The query's shape: false when it is not this path's, else fills ks (names, + * columns, expressions) and the outputs. */ +static bool hh_shape(ray_t* dict, ray_t* tbl, hh_key_t* ks, int* nk_out, + int64_t* outs, int* nout_out, int64_t* take_out) { + int64_t from_id = dict_key_id(dict, "from"), by_id = dict_key_id(dict, "by"); + int64_t take_id = dict_key_id(dict, "take"), desc_id = dict_key_id(dict, "desc"); + int64_t where_id = dict_key_id(dict, "where"), asc_id = dict_key_id(dict, "asc"); + int64_t nearest_id = dict_key_id(dict, "nearest"); + ray_t *by = NULL, *desc = NULL, *take = NULL; + int nout = 0, nk = 0; + bool ok = true; + DICT_VIEW_DECL(dv); + DICT_VIEW_OPEN(dict, dv); + if (DICT_VIEW_OVERFLOW(dv)) { DICT_VIEW_CLOSE(dv); return false; } + for (int64_t i = 0; i + 1 < dv_n && ok; i += 2) { + int64_t kid = dv[i]->i64; + ray_t* val = dv[i + 1]; + if (kid == from_id) continue; + if (kid == by_id) { by = val; continue; } + if (kid == desc_id) { desc = val; continue; } + if (kid == take_id) { take = val; continue; } + if (kid == where_id || kid == asc_id || kid == nearest_id) { ok = false; break; } + /* an output: (count col) of a column of the table */ + if (nout >= HH_MAX_OUTS || !val || val->type != RAY_LIST || ray_len(val) != 2) { ok = false; break; } + ray_t** e = (ray_t**)ray_data(val); + if (!e[0] || e[0]->type != -RAY_SYM || resolve_agg_opcode(e[0]->i64) != OP_COUNT || + !e[1] || e[1]->type != -RAY_SYM || (e[1]->attrs & ATTR_QUOTED) || + ray_env_get_lexical_local(e[1]->i64) || !ray_table_has_col(tbl, e[1]->i64)) { ok = false; break; } + outs[nout++] = kid; + } + if (ok && (!by || !desc || !take || nout == 0)) ok = false; + if (ok && (desc->type != -RAY_SYM || (desc->attrs & ATTR_QUOTED))) ok = false; + if (ok) { + bool named = false; + for (int o = 0; o < nout; o++) named |= outs[o] == desc->i64; + ok = named; + } + int64_t K = 0; + if (ok) { + if (take->type == -RAY_I64) K = take->i64; + else if (take->type == -RAY_I32) K = take->i32; + ok = K > 0 && K <= HH_MAX_TAKE; + } + /* the keys */ + if (ok) { + if (by->type == -RAY_SYM && !(by->attrs & ATTR_QUOTED)) { + ks[0].name = ks[0].col = by->i64; + nk = 1; + } else if (by->type == RAY_SYM && ray_len(by) >= 1 && ray_len(by) <= HH_MAX_KEYS) { + for (int64_t i = 0; i < ray_len(by); i++) { + ks[nk].name = ks[nk].col = ray_read_sym(ray_data(by), i, RAY_SYM, by->attrs); + nk++; + } + } else if (by->type == RAY_DICT) { + DICT_VIEW_DECL(bv); + DICT_VIEW_OPEN(by, bv); + if (DICT_VIEW_OVERFLOW(bv) || bv_n / 2 < 1 || bv_n / 2 > HH_MAX_KEYS) ok = false; + for (int64_t i = 0; i + 1 < bv_n && ok; i += 2) { + ray_t* k = bv[i]; + ray_t* v = bv[i + 1]; + if (!k || k->type != -RAY_SYM) { ok = false; break; } + /* a name of an input column other than {x: x} is the + * grouping's error to report ("alias shadows") */ + if (ray_table_has_col(tbl, k->i64) && !(v && v->type == -RAY_SYM && v->i64 == k->i64)) { + ok = false; + break; + } + ks[nk].name = k->i64; + if (v && v->type == -RAY_SYM && !(v->attrs & ATTR_QUOTED)) ks[nk].col = v->i64; + else if (v && v->type == RAY_LIST) { ks[nk].computed = true; ks[nk].expr = v; ks[nk].col = -1; } + else { ok = false; break; } + nk++; + } + DICT_VIEW_CLOSE(bv); + } else ok = false; + } + DICT_VIEW_CLOSE(dv); + if (!ok) return false; + for (int k = 0; k < nk; k++) { + hh_key_t* q = &ks[k]; + for (int j = 0; j < k; j++) if (ks[j].name == q->name) return false; + for (int o = 0; o < nout; o++) if (outs[o] == q->name) return false; + if (!q->computed) { + ray_col_meta_t m; + if (ray_env_get_lexical_local(q->col) || !ray_table_col_meta(tbl, q->col, &m) || + RAY_IS_PARTED(m.type) || !hh_col_type_ok(m.type)) + return false; + } else { + if (!key_range_plan_ex(q->expr, tbl, &q->plan, false)) return false; + /* its columns are the table's: no local, no other key's name */ + for (int s = 0; s < q->plan.n_syms; s++) { + int64_t sym = q->plan.syms[s]; + if (ray_env_get_lexical_local(sym)) return false; + for (int j = 0; j < nk; j++) + if (j != k && ks[j].name == sym && (ks[j].computed || ks[j].col != sym)) return false; + } + } + } + *nk_out = nk; + *nout_out = nout; + *take_out = K; + return true; +} + +/* The output column of key q at exact slots rows[0..n): a column key + * gathered at the groups' first rows, a computed key from its values. */ +static ray_t* hh_key_col(hh_key_t* q, int k, const hh_ex_t* g, const int64_t* slots, const int64_t* firsts, + int64_t n) { + if (!q->computed) { + ray_t* out = NULL; + ray_t* err = ray_col_gather_rows(&q->src, firsts, n, &out); + if (err) { if (out) ray_release(out); return err; } + return out; + } + ray_t* v = ray_vec_new(q->type, n); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + v->len = n; + const int64_t nv = hh_null_of(q->type); + bool nulls = false; + for (int64_t o = 0; o < n; o++) { + int64_t x = g->kv[slots[o] * g->nk + k]; + switch (q->type) { + case RAY_BOOL: case RAY_U8: ((uint8_t*)ray_data(v))[o] = (uint8_t)x; break; + case RAY_I16: ((int16_t*)ray_data(v))[o] = (int16_t)x; nulls |= x == nv; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)ray_data(v))[o] = (int32_t)x; nulls |= x == nv; break; + default: ((int64_t*)ray_data(v))[o] = x; nulls |= x == nv; break; + } + } + if (nulls) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} + +/* Group a precedes b in the answer: more rows, then the earlier first row. */ +static inline bool hh_before(const hh_ex_t* g, int64_t a, int64_t b) { + return g->c[a] != g->c[b] ? g->c[a] > g->c[b] : g->first[a] < g->first[b]; +} + +/* The top-N groups of the shape above, or NULL for the grouping to answer + * (another shape, a dense one, the check failing, any error). */ +static ray_t* select_topk_hh(ray_t* dict, ray_t* tbl) { + if (!dict || dict->type != RAY_DICT || !tbl || tbl->type != RAY_TABLE) return NULL; + const int64_t nrows = ray_table_nrows(tbl); + if (nrows < hh_min_rows() || table_has_parted_columns(tbl)) return NULL; + ray_t* khdr = NULL; + hh_key_t* ks = (hh_key_t*)scratch_calloc(&khdr, sizeof(hh_key_t) * HH_MAX_KEYS); + if (!ks) return NULL; + int64_t outs[HH_MAX_OUTS]; + int nk = 0, nout = 0; + int64_t K = 0; + if (!hh_shape(dict, tbl, ks, &nk, outs, &nout, &K)) { scratch_free(khdr); return NULL; } + + ray_pool_t* pool = ray_pool_get(); + const uint32_t W = pool ? ray_pool_total_workers(pool) : 1; + ray_t* shdr = NULL; + ray_t* xhdr = NULL; + hh_sum_t* sums = NULL; + hh_ex_t* exs = NULL; + hh_sum_t mg; + memset(&mg, 0, sizeof mg); + hh_ex_t gx; + memset(&gx, 0, sizeof gx); + uint64_t* cand = NULL; + ray_t* result = NULL; + ray_t* err = NULL; + int route = 2; + int64_t E_eff = 0, T = -1, n_cand = 0; + bool ok = true; + + /* bind the keys; column keys whose ranges are bounded by their type + * alone, small enough for a dense plan, are left to it unread */ + int64_t rng[HH_MAX_KEYS] = {0}; + bool nul[HH_MAX_KEYS] = {0}; + bool all_bounded = true; + for (int k = 0; k < nk && ok; k++) { + hh_key_t* q = &ks[k]; + nul[k] = false; + if (q->computed) { + ray_t* e = key_range_bind(&q->plan, q->psrcs, q->pplain, q->pbound); + if (e) { ray_error_free(e); ok = false; break; } /* an error declines */ + q->plan_bound = true; + all_bounded = false; + continue; + } + ray_t* e = ray_table_col_src(tbl, q->col, &q->src); + if (e) { ray_error_free(e); ok = false; break; } + q->src_bound = true; + q->type = q->src.type; + q->attrs = q->src.attrs; + q->base = ray_col_src_base(&q->src); + if (q->base) { + ray_t* rv = ray_col_src_ready(&q->src); + if (rv) { q->type = rv->type; q->attrs = rv->attrs; } + else q->base = NULL; + } + if (q->src.len != nrows || !hh_col_type_ok(q->type)) { ok = false; break; } + int64_t ub = INT64_MAX; + switch (q->type) { + case RAY_BOOL: ub = 2; break; + case RAY_U8: ub = 256; break; + case RAY_I16: ub = 65537; break; + case RAY_SYM: { + uint8_t w = q->attrs & RAY_SYM_W_MASK; + ub = w == RAY_SYM_W8 ? 256 : w == RAY_SYM_W16 ? 65536 : INT64_MAX; + int64_t dc = q->src.dom ? ray_sym_domain_count(q->src.dom) : 0; + if (dc > 0 && dc < ub) ub = dc; + break; + } + default: break; + } + if (ub == INT64_MAX) all_bounded = false; + rng[k] = ub; + } + if (ok && all_bounded && hh_dense_possible(nk, rng, nul, nrows)) { ok = false; route = 3; } + /* a grouping that fits the budget is left to it */ + if (ok) { + int64_t row_bytes = 8; /* the count */ + for (int k = 0; k < nk; k++) + row_bytes += ks[k].computed ? 8 : (int64_t)ray_sym_elem_size(ks[k].type, ks[k].attrs); + if (!hh_grouping_outgrows(nrows, row_bytes)) { ok = false; route = 5; } + } + + /* pass A: per-worker summaries of m counters (about N / 128, at most + * 1 M: E stays near 2 N / m; all of them within HH_SUM_BUDGET) */ + int64_t m = 0; + if (ok) { + uint64_t cap = 4096; + while (cap < (uint64_t)nrows / 64 && cap < ((uint64_t)1 << 21)) cap <<= 1; + while (cap > 4096 && (size_t)W * cap * 32 > HH_SUM_BUDGET) cap >>= 1; + m = (int64_t)(cap / 2); +#ifdef DEBUG + if (g_hh_counters_test > 0) m = g_hh_counters_test; +#endif + sums = (hh_sum_t*)scratch_calloc(&shdr, sizeof(hh_sum_t) * W); + ok = sums != NULL; + for (uint32_t w = 0; w < W && ok; w++) ok = hh_sum_init(&sums[w], m, false); + } + hh_pass_t pc; + memset(&pc, 0, sizeof pc); + pc.nk = nk; + pc.bits = hh_hash_bits(); + pc.sums = sums; + pc.W = W; + pc.K = K; + if (ok) ok = hh_pass(ks, nk, nrows, &pc, hh_pass_a_fn, &err); + if (pc.saturated) route = 4; + + /* the keys' value ranges: a dense plan's shape is left to it */ + if (ok) { + for (int k = 0; k < nk; k++) { + int64_t mn = INT64_MAX, mx = INT64_MIN; + for (uint32_t w = 0; w < W; w++) { + if (sums[w].mn[k] < mn) mn = sums[w].mn[k]; + if (sums[w].mx[k] > mx) mx = sums[w].mx[k]; + nul[k] |= sums[w].nul[k]; + } + int64_t span = mx < mn ? 0 : ((uint64_t)mx - (uint64_t)mn >= (uint64_t)INT64_MAX ? INT64_MAX : mx - mn + 1); + rng[k] = span == INT64_MAX ? span : span + (nul[k] ? 1 : 0); + } + if (hh_dense_possible(nk, rng, nul, nrows)) { ok = false; route = 3; } + } + + /* merge: sums of the workers' estimates, their errors added */ + int64_t E = 0; + if (ok) { + int64_t tot = 0; + for (uint32_t w = 0; w < W; w++) { + tot += sums[w].n; + E += sums[w].E; + ray_free_raw(sums[w].tmp); /* no reduce of a worker's summary from here */ + sums[w].tmp = NULL; + } + int64_t mm = tot < 2 * m ? tot : 2 * m; + ok = hh_sum_init(&mg, mm > 0 ? mm : 1, true); + for (uint32_t w = 0; w < W && ok; w++) { + hh_sum_t* s = &sums[w]; + for (uint64_t i = 0; i <= s->mask; i++) if (s->h[i]) hh_sum_add(&mg, s->h[i], s->c[i], s->c[i] + s->E - s->x[i]); + hh_sum_free(s); + } + E += mg.E; + } + /* candidates: estimate + E reaches L, the N-th largest lower bound (a + * hash's rows counted since its entry came in: at most its rows, so + * without a collision L <= T); a hash left out has at most its estimate + * + E < L rows, E_eff the largest such bound. Many candidates mean + * the N-th largest count is near the summary's floor (near-unique keys): + * T would not pass E_eff, and pass B is not run */ + int64_t L = 0; + if (ok) { + if (mg.n >= K) { + int64_t j = 0; + for (uint64_t i = 0; i <= mg.mask; i++) if (mg.h[i]) mg.tmp[j++] = mg.x[i]; + L = hh_kth(mg.tmp, j, j - K); + } + E_eff = E; + for (uint64_t i = 0; i <= mg.mask; i++) { + if (!mg.h[i]) continue; + int64_t ub = mg.c[i] + E; + if (ub >= L) n_cand++; + else if (ub > E_eff) E_eff = ub; + } + /* at most (estimate + E) / (E_eff + 1) groups of more than E_eff + * rows share a candidate hash: fewer than N in all, and T <= E_eff */ + int64_t reach = 0; + for (uint64_t i = 0; i <= mg.mask && reach < K; i++) + if (mg.h[i] && mg.c[i] + E >= L) reach += (mg.c[i] + E) / (E_eff + 1); + int64_t cand_lim = K * HH_CAND_PER_TAKE > 4096 ? K * HH_CAND_PER_TAKE : 4096; + if (n_cand > cand_lim || n_cand > HH_MAX_CAND || reach < K) ok = false; + } + uint64_t cmask = 0; + if (ok) { + uint64_t cap = 64; + while (cap < (uint64_t)n_cand * 2) cap <<= 1; + cand = ray_calloc_raw(cap * sizeof(uint64_t)); + ok = cand != NULL; + cmask = cap - 1; + for (uint64_t i = 0; ok && i <= mg.mask; i++) { + if (!mg.h[i] || mg.c[i] + E < L) continue; + uint64_t j = mg.h[i] & cmask; + while (cand[j]) j = (j + 1) & cmask; + cand[j] = mg.h[i]; + } + } + hh_sum_free(&mg); + + /* pass B: the candidates' rows grouped exactly, per worker, in tables of + * lim groups that all W of them, and the merged one, hold within the + * pass B budget's share each (hh_ex_budget). A worker meets at most + * n_cand groups (one per candidate hash, but for a collision, which + * fills the table and falls back): a lim below that is not tried */ + int64_t lim = n_cand * 4 > 4096 ? n_cand * 4 : 4096; + HH_STAT(9, 0); + if (ok) { + const uint64_t slot = (uint64_t)(24 + 8 * nk); + const uint64_t share = hh_ex_budget() / W; + uint64_t cap = 64; + while (cap * 2 * slot <= share) cap <<= 1; /* the largest table within the share */ + if ((uint64_t)lim * 2 > cap) lim = (int64_t)(cap / 2); + if (lim < n_cand || cap * slot > share) ok = false; + HH_STAT(9, ok ? (int64_t)(hh_ex_cap(lim) * slot) : 0); + } + if (ok) { + exs = (hh_ex_t*)scratch_calloc(&xhdr, sizeof(hh_ex_t) * W); + ok = exs != NULL; + for (uint32_t w = 0; w < W && ok; w++) ok = hh_ex_init(&exs[w], nk, lim); + } + if (ok) { + pc.sums = NULL; + pc.exs = exs; + pc.cand = cand; + pc.cmask = cmask; + ok = hh_pass(ks, nk, nrows, &pc, hh_pass_b_fn, &err); + } + if (ok) { + int64_t tot = 0; + for (uint32_t w = 0; w < W; w++) tot += exs[w].n; + ok = hh_ex_init(&gx, nk, tot < lim ? (tot > 0 ? tot : 1) : lim); + for (uint32_t w = 0; w < W && ok; w++) { + hh_ex_t* x = &exs[w]; + for (uint64_t i = 0; i <= x->mask && ok; i++) + if (x->h[i]) ok = hh_ex_add(&gx, x->h[i], &x->kv[i * (uint64_t)nk], x->c[i], x->first[i]); + hh_ex_free(x); + } + } + HH_STAT(6, n_cand); + HH_STAT(7, gx.n); + + /* the N first groups by (count desc, first row): a heap whose root is + * the last one kept, then sorted */ + ray_t* ihdr = NULL; + int64_t* top = NULL; + int64_t nt = 0; + if (ok) { + top = (int64_t*)scratch_alloc(&ihdr, (size_t)K * 2 * sizeof(int64_t)); + ok = top != NULL; + } + if (ok) { + for (uint64_t i = 0; i <= gx.mask; i++) { + if (!gx.h[i]) continue; + int64_t e = (int64_t)i; + if (nt < K) { + int64_t j = nt++; + while (j > 0 && hh_before(&gx, top[(j - 1) / 2], e)) { top[j] = top[(j - 1) / 2]; j = (j - 1) / 2; } + top[j] = e; + } else if (hh_before(&gx, e, top[0])) { + int64_t j = 0; + for (;;) { + int64_t l = 2 * j + 1, r = l + 1, w = j; + int64_t wv = e; + if (l < nt && hh_before(&gx, wv, top[l])) { w = l; wv = top[l]; } + if (r < nt && hh_before(&gx, wv, top[r])) { w = r; wv = top[r]; } + if (w == j) break; + top[j] = top[w]; + j = w; + } + top[j] = e; + } + } + for (int64_t a = 1; a < nt; a++) { /* insertion sort, nt <= HH_MAX_TAKE */ + int64_t e = top[a], j = a; + while (j > 0 && hh_before(&gx, e, top[j - 1])) { top[j] = top[j - 1]; j--; } + top[j] = e; + } + /* the check: every group of more than E_eff rows was counted */ + T = nt == K ? gx.c[top[K - 1]] : -1; + ok = nt == K ? T > E_eff : E_eff == 0; + } + HH_STAT(4, E_eff); + HH_STAT(5, T); + + /* the answer: the keys in by order, then the counts in output order */ + if (ok) { + int64_t* firsts = top + K; + for (int64_t o = 0; o < nt; o++) firsts[o] = gx.first[top[o]]; + ray_t* cols[HH_MAX_KEYS + 1]; + memset(cols, 0, sizeof cols); + for (int k = 0; k < nk && ok; k++) { + cols[k] = hh_key_col(&ks[k], k, &gx, top, firsts, nt); + if (!cols[k] || RAY_IS_ERR(cols[k])) { + if (cols[k]) ray_error_free(cols[k]); + cols[k] = NULL; + ok = false; + } + } + if (ok) { + cols[nk] = ray_vec_new(RAY_I64, nt); + if (!cols[nk] || RAY_IS_ERR(cols[nk])) { if (cols[nk]) ray_error_free(cols[nk]); cols[nk] = NULL; ok = false; } + else { + cols[nk]->len = nt; + for (int64_t o = 0; o < nt; o++) ((int64_t*)ray_data(cols[nk]))[o] = gx.c[top[o]]; + } + } + if (ok) { + result = ray_table_new(nk + nout); + for (int k = 0; k < nk && result && !RAY_IS_ERR(result); k++) + result = ray_table_add_col(result, ks[k].name, cols[k]); + for (int o = 0; o < nout && result && !RAY_IS_ERR(result); o++) + result = ray_table_add_col(result, outs[o], cols[nk]); + if (!result || RAY_IS_ERR(result)) { + if (result) ray_error_free(result); + result = NULL; + ok = false; + } + } + for (int k = 0; k <= nk; k++) if (cols[k]) ray_release(cols[k]); + } + if (ihdr) scratch_free(ihdr); + + if (result) { + route = 1; +#ifdef DEBUG + g_hh_stats[0]++; +#endif + } else if (route == 3) { +#ifdef DEBUG + g_hh_stats[2]++; +#endif + } else if (route == 5) { +#ifdef DEBUG + g_hh_stats[8]++; +#endif + } else { +#ifdef DEBUG + g_hh_stats[1]++; +#endif + } + HH_STAT(3, route); + hh_ex_free(&gx); + for (uint32_t w = 0; exs && w < W; w++) hh_ex_free(&exs[w]); + for (uint32_t w = 0; sums && w < W; w++) hh_sum_free(&sums[w]); + if (cand) ray_free_raw(cand); + /* an interrupt is the query's answer; any other error declines (the + * grouping reads the same columns and reports its own) */ + if (err && !result && ray_interrupted()) { result = err; err = NULL; } + if (err) ray_error_free(err); + for (int k = 0; k < nk; k++) { + if (ks[k].src_bound) ray_col_src_release(&ks[k].src); + if (ks[k].plan_bound) key_range_unbind(&ks[k].plan, ks[k].psrcs, ks[k].pbound); + } + scratch_free(shdr); + scratch_free(xhdr); + scratch_free(khdr); + return result; +} + + +#define DERIVED_KEY_MAX_DOMAIN (64LL * 1024 * 1024) +/* The distinct-symbol evaluation, in chunks and over STR. + * + * Feeding the DAG a SYM column whose ids live in a FILE domain makes every + * string step of the expression a permanent cost: substr/str-find intern + * each distinct result into the global runtime table (with the dotted + * split, about 1 KB per URL) and an `if` that keeps the column itself + * translates its cells into runtime ids too. Over a 20M-entry vocabulary + * that is tens of GB that never come back. + * + * Here the referenced column is presented to the same DAG as a STR column + * built from the vocabulary bytes, CHUNK rows at a time (or, when the key + * compiles to one, to a per-value program over the bytes): every + * intermediate then dies with the chunk. The keys are grouped by a hash + * of their bytes, compared byte for byte (dkh_build: no dictionary while + * grouping), and each group's key is interned once, into a domain of the + * key vector's own (released with the result; the global table never + * grows by a derived value; positions = first-seen order of the keys, the + * order unsorted groups come out in). Applies only when the + * expression's result over the SYM column is SYM (so the result has the + * type the caller expects). File prefixes use the raw snapshot, the + * runtime domain its borrowed atom array, and a private in-memory domain + * resolves its stable atoms through the tail path. Any other shape + * returns NULL and the caller takes the one-shot SYM evaluation. */ +/* Chunk length in distinct values: 256 dispatch rounds of morsels (2M + * rows) when the key runs as a DAG — enough rows for the pooled string ops + * to spread over the workers, while every chunk-scoped STR intermediate + * stays in the low hundreds of MB at URL-sized strings — and an eighth of + * that for the per-value program and the passes that read values only (a + * chunk's per-value arrays stay in the tens of MB and in cache reach). */ +#define DERIVED_KEY_CHUNK ((int64_t)RAY_MORSEL_ELEMS * RAY_DISPATCH_MORSELS * 256) +#ifdef DEBUG +static int64_t g_derived_key_chunk_test = 0; +/* Test seam: a positive value replaces the chunk length until reset to 0, + * so a test can drive several chunks through a small vocabulary. */ +void ray_derived_key_chunk_set_for_test(int64_t rows) { + g_derived_key_chunk_test = rows > 0 ? rows : 0; +} +#endif +static int64_t derived_key_chunk_rows(bool dag) { +#ifdef DEBUG + if (g_derived_key_chunk_test > 0) return g_derived_key_chunk_test; +#endif + return dag ? DERIVED_KEY_CHUNK : DERIVED_KEY_CHUNK / 8; +} +/* ---- chunk STR build: the entries at positions dv[lo, lo+n) as one STR + * vector over one pool. Lengths and byte pointers are read on the workers + * (the raw snapshot needs no lock); a position past the file prefix — a + * runtime-appended entry — is resolved through the domain on the calling + * thread. A serial prefix sum places the pooled rows, then the workers + * write the descriptors and copy the pooled bytes into disjoint ranges. */ +typedef struct { + const void* dv; + uint8_t dattrs; + int64_t lo; + const ray_sym_domain_raw_t* raw; + const char** ptr; + uint32_t* len; + uint32_t* off; + ray_str_t* dst; + char* pool; + ray_t* const* rstr; /* runtime domain: the borrowed atom array */ + uint32_t rcnt; + const uint8_t* want; /* NULL = every entry; else only where set */ + atomic_int late; +} dk_chunk_ctx_t; + +static void dk_chunk_scan_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + dk_chunk_ctx_t* c = (dk_chunk_ctx_t*)vctx; + int late = 0; + for (int64_t i = start; i < end; i++) { + if (c->want && !c->want[i]) { c->ptr[i] = ""; c->len[i] = 0; continue; } + int64_t pos = ray_read_sym(c->dv, c->lo + i, RAY_SYM, c->dattrs); + if (c->rstr) { + /* runtime domain: the atom array borrowed once per chunk (no + * lock — nothing interns into the global table while the chunk + * is read) */ + ray_t* a = (pos >= 0 && pos < (int64_t)c->rcnt) ? c->rstr[pos] : NULL; + if (a && ray_str_len(a) <= UINT32_MAX) { + c->ptr[i] = ray_str_ptr(a); + c->len[i] = (uint32_t)ray_str_len(a); + } else { + c->ptr[i] = NULL; + c->len[i] = UINT32_MAX; + late++; + } + } else if (pos >= 0 && pos < c->raw->count) { + size_t sl = 0; + c->ptr[i] = ray_sym_domain_raw_str(c->raw, pos, &sl); + c->len[i] = (uint32_t)sl; + } else { + c->ptr[i] = NULL; + c->len[i] = UINT32_MAX; + late++; + } + } + if (late) atomic_fetch_add_explicit(&c->late, late, memory_order_relaxed); +} + +static void dk_chunk_fill_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + const dk_chunk_ctx_t* c = (const dk_chunk_ctx_t*)vctx; + for (int64_t i = start; i < end; i++) { + ray_str_t* d = &c->dst[i]; + uint32_t l = c->len[i]; + memset(d, 0, sizeof(*d)); + d->len = l; + if (l == 0) continue; + if (l <= RAY_STR_INLINE_MAX) { + memcpy(d->data, c->ptr[i], l); + } else { + memcpy(c->pool + c->off[i], c->ptr[i], l); + memcpy(d->prefix, c->ptr[i], 4); + d->pool_off = c->off[i]; + } + } +} + +/* A compressed vocabulary's entries of a chunk, decoded into the places + * dk_chunk_views gave them. */ +static void dk_chunk_decode_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + dk_chunk_ctx_t* c = (dk_chunk_ctx_t*)vctx; + for (int64_t i = start; i < end; i++) { + if (c->len[i] == UINT32_MAX || (c->want && !c->want[i])) continue; + int64_t pos = ray_read_sym(c->dv, c->lo + i, RAY_SYM, c->dattrs); + ray_sym_domain_raw_decode(c->raw, pos, (char*)c->ptr[i]); + } +} + +/* The calling thread's buffer for the views of a compressed vocabulary. */ +static _Thread_local ray_arena_t* g_dk_zarena; + +/* The bytes of entries dv[lo, lo+n) as (ptr, len) views: read on the + * workers off the raw snapshot (FILE) or the borrowed atom array (the + * runtime domain), a position past either resolved through the domain on + * the calling thread. With `want`, only the entries it marks are read (the + * others come out as empty views, their bytes untouched). A compressed + * vocabulary's entries are decoded into a buffer of the calling thread + * that holds them until a later call with `fresh`. False on a length past + * UINT32_MAX or on OOM. */ +static bool dk_chunk_views(const void* dv, uint8_t dattrs, int64_t lo, int64_t n, + const ray_sym_domain_raw_t* raw, struct ray_sym_domain_s* dom, + const uint8_t* want, const char** ptr, uint32_t* len, bool fresh) { + dk_chunk_ctx_t c; + memset(&c, 0, sizeof(c)); + c.dv = dv; c.dattrs = dattrs; c.lo = lo; c.raw = raw; + c.ptr = ptr; + c.len = len; + c.want = want; + if (dom == ray_sym_runtime_domain()) { + ray_t** rs = NULL; uint32_t rc = 0; + ray_sym_strings_borrow(&rs, &rc); + c.rstr = rs; c.rcnt = rc; + } + atomic_store_explicit(&c.late, 0, memory_order_relaxed); + ray_pool_t* pool = ray_pool_get(); + if (raw && raw->z && !c.rstr) { + /* lengths from the index, places in the buffer, then the decode */ + if (!g_dk_zarena && !(g_dk_zarena = ray_arena_new((size_t)1 << 20))) return false; + if (fresh) ray_arena_reset(g_dk_zarena); + uint64_t total = 0; + int late = 0; + for (int64_t i = 0; i < n; i++) { + if (want && !want[i]) { ptr[i] = ""; len[i] = 0; continue; } + int64_t pos = ray_read_sym(dv, lo + i, RAY_SYM, dattrs); + int64_t l = pos >= 0 && pos < raw->count ? ray_sym_domain_raw_len(raw, pos) : -1; + if (l > UINT32_MAX) return false; + if (l < 0) { ptr[i] = NULL; len[i] = UINT32_MAX; late++; continue; } + len[i] = (uint32_t)l; + total += (uint64_t)l + 8; + } + char* at = total ? (char*)ray_arena_alloc_raw(g_dk_zarena, (size_t)total) : NULL; + if (total && !at) return false; + for (int64_t i = 0; i < n; i++) { + if (len[i] == UINT32_MAX || (want && !want[i])) continue; + ptr[i] = at; + at += (size_t)len[i] + 8; + } + if (ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(pool, dk_chunk_decode_fn, &c, n); + else + dk_chunk_decode_fn(&c, 0, 0, n); + if (late) atomic_store_explicit(&c.late, late, memory_order_relaxed); + } else if (ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) + ray_pool_dispatch(pool, dk_chunk_scan_fn, &c, n); + else + dk_chunk_scan_fn(&c, 0, 0, n); + if (atomic_load_explicit(&c.late, memory_order_relaxed)) { + for (int64_t i = 0; i < n; i++) { + if (len[i] != UINT32_MAX) continue; + int64_t pos = ray_read_sym(dv, lo + i, RAY_SYM, dattrs); + ray_t* a = ray_sym_domain_str(dom, pos); + size_t sl = a ? ray_str_len(a) : 0; + if (sl > UINT32_MAX) return false; + ptr[i] = a ? ray_str_ptr(a) : ""; + len[i] = (uint32_t)sl; + } + } + return true; +} + +/* The n views (ptr[i], len[i]) as one STR vector over one pool. */ +static ray_t* derived_key_chunk_strs(const char** ptr, uint32_t* len, int64_t n) { ray_t* aux_hdr = NULL; - size_t ptr_sz = (size_t)n * sizeof(const char*); - size_t u32_sz = (size_t)n * sizeof(uint32_t); - char* mem = (char*)scratch_alloc(&aux_hdr, ptr_sz + 2 * u32_sz); - if (!mem) return NULL; + uint32_t* off = (uint32_t*)scratch_alloc(&aux_hdr, (size_t)n * sizeof(uint32_t)); + if (!off) return NULL; dk_chunk_ctx_t c; memset(&c, 0, sizeof(c)); - c.ptr = (const char**)mem; - c.len = (uint32_t*)(mem + ptr_sz); - c.off = (uint32_t*)(mem + ptr_sz + u32_sz); - if (!dk_chunk_views(dv, dattrs, lo, n, raw, dom, c.ptr, c.len)) { scratch_free(aux_hdr); return NULL; } + c.ptr = ptr; + c.len = len; + c.off = off; ray_pool_t* pool = ray_pool_get(); bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); uint64_t total = 0; @@ -4691,316 +6629,6 @@ static ray_t* derived_key_chunk_strs(const void* dv, uint8_t dattrs, int64_t lo, return sv; } -/* ---- chunk result interning: each distinct key string of a chunk is - * interned once, all of them under one lock, in the order of their first - * row (the order the ids — and with them the group order — came out in - * when one serial pass did the dedupe), and its id spread over the rows - * that hold it. The hashes are the intern table's own (ray_hash_bytes). - * The dedupe runs on the workers: the rows are split into DK_NPART - * partitions by the top bits of their hash (a count and a stable scatter - * over row ranges), and each partition is deduped by one task in an - * open-addressing table of its own, rows in row order, so every string's - * representative is its first row. One serial pass over the rows then - * lists the representatives in row order for the batch intern. */ -#define DK_PART_BITS 6 -#define DK_NPART (1 << DK_PART_BITS) -/* A row as its partition's dedupe reads it: everything in one place, the - * partition's rows contiguous. */ -typedef struct dk_item_s { - const char* p; - uint32_t h; - uint32_t l; - int32_t row; - int32_t pad; -} dk_item_t; -typedef struct { - const char* const* sp; - const uint32_t* sl; - const uint32_t* hash; - int64_t n; - int64_t nt; /* row ranges of the count / scatter passes */ - int64_t* cnt; /* [nt][DK_NPART]: counts, then write cursors */ - struct dk_item_s* items; /* rows grouped by partition, row order within */ - const int64_t* pbase; /* [DK_NPART + 1]: partition starts in items */ - const int64_t* tbase; /* [DK_NPART + 1]: partition tables in tab */ - uint64_t* tab; /* hash << 32 | index in the partition; all ones = empty */ - int32_t* rep; /* first row holding the same string */ - int32_t* ord; /* at a representative row: its ordinal */ - const int64_t* did; /* id per ordinal */ - int64_t* out; - int64_t* rcnt; /* [nt]: representatives per row range, then their base */ - const char** dstr; /* the representatives' strings, lengths, hashes */ - size_t* dlen; - uint32_t* dhsh; -} dk_dedupe_ctx_t; - -static inline uint32_t dk_part_of(uint32_t h) { return h >> (32 - DK_PART_BITS); } - -static void dk_count_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { - (void)wid; - dk_dedupe_ctx_t* c = (dk_dedupe_ctx_t*)vctx; - for (int64_t t = t0; t < t1; t++) { - int64_t* k = c->cnt + t * DK_NPART; - memset(k, 0, DK_NPART * sizeof(int64_t)); - int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt; - for (int64_t i = lo; i < hi; i++) k[dk_part_of(c->hash[i])]++; - } -} - -static void dk_scatter_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { - (void)wid; - dk_dedupe_ctx_t* c = (dk_dedupe_ctx_t*)vctx; - for (int64_t t = t0; t < t1; t++) { - int64_t* k = c->cnt + t * DK_NPART; - int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt; - for (int64_t i = lo; i < hi; i++) { - uint32_t h = c->hash[i]; - dk_item_t* it = &c->items[k[dk_part_of(h)]++]; - it->p = c->sp[i]; - it->h = h; - it->l = c->sl[i]; - it->row = (int32_t)i; - it->pad = 0; - } - } -} - -static void dk_dedupe_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { - (void)wid; - dk_dedupe_ctx_t* c = (dk_dedupe_ctx_t*)vctx; - for (int64_t p = p0; p < p1; p++) { - int64_t lo = c->pbase[p], hi = c->pbase[p + 1]; - if (lo == hi) continue; - uint64_t* tab = c->tab + c->tbase[p]; - uint64_t mask = (uint64_t)(c->tbase[p + 1] - c->tbase[p]) - 1; - memset(tab, 0xff, (size_t)(mask + 1) * sizeof(uint64_t)); - const dk_item_t* items = c->items + lo; - for (int64_t k = 0; k < hi - lo; k++) { - const dk_item_t* it = &items[k]; - uint32_t h = it->h; - uint32_t l = it->l; - uint64_t s = ((uint64_t)h * 0x9E3779B97F4A7C15ull >> 32) & mask; - for (;;) { - uint64_t e = tab[s]; - if (e == UINT64_MAX) { - tab[s] = (uint64_t)h << 32 | (uint32_t)k; - c->rep[it->row] = it->row; - break; - } - const dk_item_t* rt = &items[(uint32_t)e]; - if ((uint32_t)(e >> 32) == h && rt->l == l && - (l == 0 || memcmp(rt->p, it->p, l) == 0)) { - c->rep[it->row] = rt->row; - break; - } - s = (s + 1) & mask; - } - } - } -} - -static void dk_reps_count_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { - (void)wid; - const dk_dedupe_ctx_t* c = (const dk_dedupe_ctx_t*)vctx; - for (int64_t t = t0; t < t1; t++) { - int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt, k = 0; - for (int64_t i = lo; i < hi; i++) k += c->rep[i] == (int32_t)i; - c->rcnt[t] = k; - } -} - -static void dk_reps_list_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { - (void)wid; - const dk_dedupe_ctx_t* c = (const dk_dedupe_ctx_t*)vctx; - for (int64_t t = t0; t < t1; t++) { - int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt, d = c->rcnt[t]; - for (int64_t i = lo; i < hi; i++) { - if (c->rep[i] != (int32_t)i) continue; - c->ord[i] = (int32_t)d; - c->dstr[d] = c->sp[i]; c->dlen[d] = c->sl[i]; c->dhsh[d] = c->hash[i]; - d++; - } - } -} - -static void dk_assign_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { - (void)wid; - const dk_dedupe_ctx_t* c = (const dk_dedupe_ctx_t*)vctx; - for (int64_t i = lo; i < hi; i++) c->out[i] = c->did[c->ord[c->rep[i]]]; -} - -/* Intern the n strings (sp[i], sl[i]) with hashes hash[i] into the key - * domain kdom; out[i] gets the position of string i. n stays below - * INT32_MAX (a chunk). The partitioned rows and their tables live only - * through the dedupe; the arrays the batch intern reads are sized by the - * distinct count. The domain is this execution's own and the - * representatives are handed over in first-row order, so a key's position - * is its first-seen rank — the order unsorted groups come out in, the same - * at every thread count. */ -static bool dk_intern_views(const char* const* sp, const uint32_t* sl, const uint32_t* hash, - int64_t n, struct ray_sym_domain_s* kdom, int64_t* out) { - if (n <= 0) return true; - ray_pool_t* pool = ray_pool_get(); - bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); - int64_t nt = 1; - if (par) { - nt = (int64_t)ray_pool_total_workers(pool) * 4; - if (nt > n / 4096) nt = n / 4096; - if (nt < 1) nt = 1; - } - size_t cnt_sz = (size_t)nt * DK_NPART * sizeof(int64_t); - size_t base_sz = (size_t)(DK_NPART + 1) * sizeof(int64_t); - size_t i32_sz = (size_t)n * sizeof(int32_t); - ray_t *hdr = NULL, *ihdr = NULL, *thdr = NULL, *dhdr = NULL; - char* mem = (char*)scratch_alloc(&hdr, cnt_sz + 2 * base_sz + 2 * i32_sz); - dk_item_t* items = (dk_item_t*)scratch_alloc(&ihdr, (size_t)n * sizeof(dk_item_t)); - if (!mem || !items) { scratch_free(hdr); scratch_free(ihdr); return false; } - int64_t* cnt = (int64_t*)mem; mem += cnt_sz; - int64_t* pbase = (int64_t*)mem; mem += base_sz; - int64_t* tbase = (int64_t*)mem; mem += base_sz; - int32_t* rep = (int32_t*)mem; mem += i32_sz; - int32_t* ord = (int32_t*)mem; - - dk_dedupe_ctx_t c = { - .sp = sp, .sl = sl, .hash = hash, .n = n, .nt = nt, .cnt = cnt, .items = items, - .pbase = pbase, .tbase = tbase, .rep = rep, .ord = ord, .out = out, - }; - if (par) ray_pool_dispatch_n(pool, dk_count_fn, &c, (uint32_t)nt); - else dk_count_fn(&c, 0, 0, nt); - /* partition starts, per-range write cursors, table extents (a power - * of two at least twice the partition's rows) */ - int64_t run = 0, tsz = 0; - for (int p = 0; p < DK_NPART; p++) { - pbase[p] = run; - tbase[p] = tsz; - int64_t pc = 0; - for (int64_t t = 0; t < nt; t++) { - int64_t k = cnt[t * DK_NPART + p]; - cnt[t * DK_NPART + p] = run + pc; - pc += k; - } - run += pc; - int64_t slots = 16; - while (slots < 2 * pc) slots <<= 1; - tsz += pc ? slots : 0; - } - pbase[DK_NPART] = run; - tbase[DK_NPART] = tsz; - c.tab = (uint64_t*)scratch_alloc(&thdr, (size_t)(tsz ? tsz : 1) * sizeof(uint64_t)); - if (!c.tab) { scratch_free(ihdr); scratch_free(hdr); return false; } - if (par) ray_pool_dispatch_n(pool, dk_scatter_fn, &c, (uint32_t)nt); - else dk_scatter_fn(&c, 0, 0, nt); - if (par) ray_pool_dispatch_n(pool, dk_dedupe_fn, &c, DK_NPART); - else dk_dedupe_fn(&c, 0, 0, DK_NPART); - ray_profile_tick("derived key: keys deduplicated"); - scratch_free(thdr); - scratch_free(ihdr); - - /* the representatives in row order: ordinals, then their strings — - * counted per row range on the workers, a prefix over the ranges, then - * numbered and listed per range (the count array is free by now) */ - c.rcnt = cnt; - if (par) ray_pool_dispatch_n(pool, dk_reps_count_fn, &c, (uint32_t)nt); - else dk_reps_count_fn(&c, 0, 0, nt); - int64_t nd = 0; - for (int64_t t = 0; t < nt; t++) { int64_t k = cnt[t]; cnt[t] = nd; nd += k; } - size_t dstr_sz = (size_t)nd * sizeof(const char*); - size_t dlen_sz = (size_t)nd * sizeof(size_t); - size_t did_sz = (size_t)nd * sizeof(int64_t); - char* dm = (char*)scratch_alloc(&dhdr, dstr_sz + dlen_sz + did_sz + (size_t)nd * sizeof(uint32_t)); - if (!dm) { scratch_free(hdr); return false; } - const char** dstr = (const char**)dm; dm += dstr_sz; - size_t* dlen = (size_t*)dm; dm += dlen_sz; - int64_t* did = (int64_t*)dm; dm += did_sz; - uint32_t* dhsh = (uint32_t*)dm; - c.dstr = dstr; c.dlen = dlen; c.dhsh = dhsh; - if (par) ray_pool_dispatch_n(pool, dk_reps_list_fn, &c, (uint32_t)nt); - else dk_reps_list_fn(&c, 0, 0, nt); - /* Key strings are values of this query, not names: they go into the - * key vector's own domain (released with it), never into the global - * table — a host extracted from millions of URLs costs one entry - * there for as long as the result lives, and nothing afterwards. */ - ray_profile_tick("derived key: representatives listed"); - bool ok = ray_sym_domain_intern_batch(kdom, nd, dstr, dlen, dhsh, did); - ray_profile_tick("derived key: key domain interned"); - if (ok) { - c.did = did; - if (par) ray_pool_dispatch(pool, dk_assign_fn, &c, n); - else dk_assign_fn(&c, 0, 0, n); - ray_profile_tick("derived key: keys interned"); - } - scratch_free(dhdr); - scratch_free(hdr); - return ok; -} - -/* The STR evaluation's key vector: its views and hashes (workers), then - * the view interning above. */ -typedef struct { - const ray_str_t* desc; - const char* pool; - const char** sp; - uint32_t* sl; - uint32_t* hash; -} dk_hash_ctx_t; - -static void dk_hash_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - (void)wid; - const dk_hash_ctx_t* c = (const dk_hash_ctx_t*)vctx; - for (int64_t i = start; i < end; i++) { - const ray_str_t* d = &c->desc[i]; - const char* p = ray_str_t_ptr(d, c->pool); - c->sp[i] = p; - c->sl[i] = d->len; - c->hash[i] = (uint32_t)ray_hash_bytes(p, d->len); - } -} - -static bool derived_key_intern_chunk(ray_t* kc, int64_t n, struct ray_sym_domain_s* kdom, - int64_t* out) { - dk_hash_ctx_t hc; - memset(&hc, 0, sizeof(hc)); - str_resolve(kc, &hc.desc, &hc.pool); - ray_t* hdr = NULL; - char* mem = (char*)scratch_alloc(&hdr, (size_t)n * (sizeof(const char*) + 2 * sizeof(uint32_t))); - if (!mem) return false; - hc.sp = (const char**)mem; - hc.sl = (uint32_t*)(mem + (size_t)n * sizeof(const char*)); - hc.hash = hc.sl + n; - ray_pool_t* rp = ray_pool_get(); - if (ray_pool_par_dispatch_ok(rp, n, RAY_PARALLEL_THRESHOLD)) - ray_pool_dispatch(rp, dk_hash_fn, &hc, n); - else - dk_hash_fn(&hc, 0, 0, n); - bool ok = dk_intern_views(hc.sp, hc.sl, hc.hash, n, kdom, out); - scratch_free(hdr); - return ok; -} - -/* A chunk result that is already SYM (a symbol-literal arm, say): its - * cells as strings through their own domain, interned into the key - * domain like any other key string. */ -static bool derived_key_intern_sym_cells(ray_t* kc, int64_t n, struct ray_sym_domain_s* kdom, - int64_t* out) { - ray_t* hdr = NULL; - char* mem = (char*)scratch_alloc(&hdr, (size_t)n * (sizeof(const char*) + 2 * sizeof(uint32_t))); - if (!mem) return false; - const char** sp = (const char**)mem; - uint32_t* sl = (uint32_t*)(mem + (size_t)n * sizeof(const char*)); - uint32_t* hash = sl + n; - for (int64_t i = 0; i < n; i++) { - ray_t* a = ray_sym_vec_cell(kc, i); - size_t l = a ? ray_str_len(a) : 0; - if (l > UINT32_MAX) { scratch_free(hdr); return false; } - sp[i] = a ? ray_str_ptr(a) : ""; - sl[i] = (uint32_t)l; - hash[i] = (uint32_t)ray_hash_bytes(sp[i], l); - } - bool ok = dk_intern_views(sp, sl, hash, n, kdom, out); - scratch_free(hdr); - return ok; -} - /* ---- the spread pass of derived_key_over_sym_domain: each row takes the * key of its symbol's slot (workers, disjoint ranges). */ typedef struct { @@ -5204,10 +6832,18 @@ static int dkp_compile(dkp_prog_t* P, ray_t* e, int64_t col, int64_t* bsym, int* return dkp_compile(P, el[3], col, bsym, breg, nb + 1); } if (DKP_IS("if")) { - if (n != 4) return -1; - int c = DKP_ARG(1), t = DKP_ARG(2), f = DKP_ARG(3); - if (c < 0 || t < 0 || f < 0 || DKP_K(c) != DKP_BOOL || DKP_K(t) != DKP_K(f)) return -1; - return dkp_emit(P, DKO_IF, DKP_K(t), c, t, f); + /* (if c1 r1 c2 r2 ... else): pairs nest right to left, as `cond` + * below; a chain without a fallback is left to the evaluator. */ + if (n < 4 || (n & 1)) return -1; + int acc = DKP_ARG(n - 1); + if (acc < 0) return -1; + for (int64_t i = n - 3; i >= 1; i -= 2) { + int c = DKP_ARG(i), t = DKP_ARG(i + 1); + if (c < 0 || t < 0 || DKP_K(c) != DKP_BOOL || DKP_K(t) != DKP_K(acc)) return -1; + acc = dkp_emit(P, DKO_IF, DKP_K(t), c, t, acc); + if (acc < 0) return -1; + } + return acc; } if (DKP_IS("cond")) { /* right to left into an if chain; the last clause is the else */ @@ -5432,168 +7068,1168 @@ static void dkp_run_batch(const dkp_prog_t* P, dkp_reg_t* R, const char* const* } } -/* Workers: each value's key, in place over its view, and the key's hash. - * regs holds one register file per worker. */ -typedef struct { - const dkp_prog_t* prog; - const char** sp; - uint32_t* sl; - uint32_t* hash; - dkp_reg_t* regs; -} dkp_run_ctx_t; +/* The key hash of the derived-key grouping: ray_hash_bytes, all 64 bits. */ +#ifdef DEBUG +static int g_derived_key_hash_bits_test = 0; +/* Test seam: a value in [1, 63] keeps only that many low bits of every key + * hash until reset to 0, so distinct keys share hashes and the byte + * compare alone keeps them apart. */ +void ray_derived_key_hash_bits_set_for_test(int bits) { + g_derived_key_hash_bits_test = bits > 0 && bits < 64 ? bits : 0; +} +#endif +static inline uint64_t dkh_hash(const char* p, uint32_t l) { + uint64_t h = ray_hash_bytes(p, l); +#ifdef DEBUG + if (g_derived_key_hash_bits_test) h &= ((uint64_t)1 << g_derived_key_hash_bits_test) - 1; +#endif + return h; +} + +/* Workers: each value's key as a view (of the value itself or of a + * literal) and the key's hash. regs holds one register file per worker. */ +typedef struct { + const dkp_prog_t* prog; + const char* const* sp; + const uint32_t* sl; + const char** kp; + uint32_t* kl; + uint64_t* kh; + dkp_reg_t* regs; +} dkp_run_ctx_t; + +static void dkp_run_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + const dkp_run_ctx_t* c = (const dkp_run_ctx_t*)vctx; + const dkp_prog_t* P = c->prog; + dkp_reg_t* R = c->regs + (size_t)wid * (size_t)P->n * DKP_BATCH; + const dkp_reg_t* res = R + (size_t)P->res * DKP_BATCH; + /* literals once: the batches run the other instructions only */ + for (int k = 0; k < P->n; k++) { + dkp_reg_t* o = R + (size_t)k * DKP_BATCH; + if (P->ins[k].op == DKO_LIT) + for (int t = 0; t < DKP_BATCH; t++) o[t].v = P->ins[k].imm; + else if (P->ins[k].op == DKO_LSTR) + for (int t = 0; t < DKP_BATCH; t++) { o[t].p = P->ins[k].sp; o[t].v = P->ins[k].sl; } + } + for (int64_t i = start; i < end; i += DKP_BATCH) { + int m = end - i < DKP_BATCH ? (int)(end - i) : DKP_BATCH; + dkp_run_batch(P, R, c->sp + i, c->sl + i, m); + for (int t = 0; t < m; t++) { + const char* p = res[t].v ? res[t].p : ""; + uint32_t l = (uint32_t)res[t].v; + c->kp[i + t] = p; + c->kl[i + t] = l; + c->kh[i + t] = dkh_hash(p, l); + } + } +} + +/* The chunk DAG's key vector (STR, or SYM for a symbol arm) as views and + * hashes (workers). */ +typedef struct { + ray_t* kc; + const ray_str_t* desc; + const char* pool; + const char** kp; + uint32_t* kl; + uint64_t* kh; + atomic_int bad; +} dk_kview_ctx_t; + +static void dk_kview_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + dk_kview_ctx_t* c = (dk_kview_ctx_t*)vctx; + for (int64_t i = start; i < end; i++) { + const char* p; size_t l; + if (c->desc) { + const ray_str_t* d = &c->desc[i]; + p = ray_str_t_ptr(d, c->pool); + l = d->len; + } else { + ray_t* a = ray_sym_vec_cell(c->kc, i); + p = a ? ray_str_ptr(a) : ""; + l = a ? ray_str_len(a) : 0; + } + if (l > UINT32_MAX) { atomic_store_explicit(&c->bad, 1, memory_order_relaxed); l = 0; } + if (!p) p = ""; + c->kp[i] = p; + c->kl[i] = (uint32_t)l; + c->kh[i] = dkh_hash(p, (uint32_t)l); + } +} + +/* The keys of the n values (sp[i], sl[i]) as views kp/kl and hashes kh: + * the per-value program on the workers when prog is set (regs: one + * register file per worker), the chunk DAG over a STR column of the values + * otherwise — the views then point into *kc, the DAG's key vector, which + * the caller releases once it is done with them. False on failure. */ +static bool dkh_keys_of(ray_t* by_expr, int64_t col, const dkp_prog_t* prog, dkp_reg_t* regs, + const char** sp, uint32_t* sl, int64_t n, + const char** kp, uint32_t* kl, uint64_t* kh, ray_t** kc_out) { + *kc_out = NULL; + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + if (prog) { + dkp_run_ctx_t rc = { .prog = prog, .sp = sp, .sl = sl, + .kp = kp, .kl = kl, .kh = kh, .regs = regs }; + if (par) ray_pool_dispatch(pool, dkp_run_fn, &rc, n); + else dkp_run_fn(&rc, 0, 0, n); + ray_profile_tick("derived key: program over values"); + return true; + } + ray_t* kc = NULL; + ray_t* sv = derived_key_chunk_strs(sp, sl, n); + if (!sv) return false; + ray_t* mini = ray_table_new(0); + if (mini && !RAY_IS_ERR(mini)) mini = ray_table_add_col(mini, col, sv); + ray_release(sv); + if (!mini || RAY_IS_ERR(mini)) { if (mini) ray_error_free(mini); return false; } + ray_graph_t* g2 = ray_graph_new(mini); + if (g2) { + ray_op_t* kop = compile_expr_dag(g2, by_expr); + if (kop) kop = ray_optimize(g2, kop); + if (kop) kc = ray_execute(g2, kop); + ray_graph_free(g2); + } + ray_release(mini); + if (kc && !RAY_IS_ERR(kc) && ray_is_lazy(kc)) kc = ray_lazy_materialize(kc); + if (!kc || RAY_IS_ERR(kc)) { if (kc) ray_error_free(kc); return false; } + if (!ray_is_vec(kc) || kc->len != n || (kc->type != RAY_STR && !RAY_IS_SYM(kc->type))) { + ray_release(kc); return false; + } + ray_profile_tick("derived key: chunk DAG"); + dk_kview_ctx_t vc; + memset(&vc, 0, sizeof(vc)); + vc.kc = kc; vc.kp = kp; vc.kl = kl; vc.kh = kh; + if (kc->type == RAY_STR) str_resolve(kc, &vc.desc, &vc.pool); + atomic_store_explicit(&vc.bad, 0, memory_order_relaxed); + /* a SYM key's cells resolve through its domain's atoms: serial */ + if (par && kc->type == RAY_STR) ray_pool_dispatch(pool, dk_kview_fn, &vc, n); + else dk_kview_fn(&vc, 0, 0, n); + if (atomic_load_explicit(&vc.bad, memory_order_relaxed)) { ray_release(kc); return false; } + *kc_out = kc; + return true; +} + +/* The type the one-shot SYM evaluation gives the key: the expression + * compiled (only) against the SYM column of distinct values. */ +static bool dk_key_is_sym(ray_t* by_expr, int64_t col_sym, ray_t* dom_vec) { + int8_t sym_out = 0; + ray_t* probe = ray_table_new(0); + /* add_col retains the column itself; the caller keeps its own ref. */ + if (probe && !RAY_IS_ERR(probe)) probe = ray_table_add_col(probe, col_sym, dom_vec); + if (!probe || RAY_IS_ERR(probe)) { if (probe) ray_error_free(probe); return false; } + ray_graph_t* gp = ray_graph_new(probe); + if (gp) { + ray_op_t* kop = compile_expr_dag(gp, by_expr); + /* A key that compiles to a constant — a literal, or a let whose + * body is one — evaluates to that literal: a string literal is + * typed SYM by the compiler but executes as the STR it is. The + * one-shot evaluation (and the row path behind it) keeps that + * type; this path would make it a symbol. */ + if (kop && kop->opcode != OP_CONST) sym_out = kop->out_type; + ray_graph_free(gp); + } + ray_release(probe); + return sym_out == RAY_SYM; +} + +/* ---- the distinct values grouped by their key --------------------------- + * The key of every distinct value of C is computed (the per-value program, + * or the chunk DAG over a STR column of the values) and the values are + * grouped by key without a dictionary: the key's 64-bit hash picks one of + * DKH_NPART partitions (its top bits) and a slot in that partition's + * open-addressing table; a slot holds the hash and a group, and a group + * holds a copy of its key's bytes (in the partition's byte arena, made when + * the group is created) and the index of its first value. A key joins a + * group only when hash, length and bytes all equal the group's; a key whose + * hash equals a group's but whose bytes do not (a collision) keeps probing + * and makes a group of its own. So the grouping is exact whatever the + * hashes do, and the bytes are compared once per distinct value, against a + * copy that stays in cache for the frequent keys. Nothing is interned. + * + * The values are taken in chunks: their views, their keys, a scatter by + * partition in value order, then one task per partition, which owns its + * table, groups and arena (nothing shared, nothing locked). Before the + * tasks run, the calling thread sizes every partition as if all its + * pending values made new groups (dkh_grow), so a chunk's partitions run in + * one dispatch; a task that still runs out of room stops where it is and + * resumes after the next sizing. Every buffer is allocated and freed on + * the calling thread. + * + * Optionally, per group: the row count (hn per value; 1 without it), the + * length-weighted row count, the min and max value (by bytes, the null + * value skipped, of equal values the one first in value order); per + * value its group code (local group << DKH_PART_BITS | + * partition). Groups are then ranked by their first value, the group of + * the empty key first (the position a key domain gives ""). */ +#define DKH_PART_BITS 8 +#define DKH_NPART (1 << DKH_PART_BITS) +#define DKH_MAX_LOCAL ((int64_t)1 << (32 - DKH_PART_BITS)) +enum { DKH_F_CNT = 1, DKH_F_LENW = 2, DKH_F_MIN = 4, DKH_F_MAX = 8 }; +/* group fields */ +enum { DKH_G_FIRST, DKH_G_KOFF, DKH_G_KLEN, DKH_G_CNT, DKH_G_LENW, + DKH_G_MN, DKH_G_MNP, DKH_G_MNL, DKH_G_MX, DKH_G_MXP, DKH_G_MXL, DKH_NG }; +static const uint8_t dkh_gsize[DKH_NG] = { 8, 8, 4, 8, 8, 8, sizeof(void*), 4, 8, sizeof(void*), 4 }; + +typedef struct { + /* table: hash and group + 1 per slot (0 = empty) */ + uint64_t* th; uint32_t* tg; int64_t tcap; ray_t *th_hdr, *tg_hdr; + /* groups */ + int64_t ng, gcap; + void* gf[DKH_NG]; ray_t* gh[DKH_NG]; + /* key bytes */ + char* kb; uint64_t kbn, kbcap; ray_t* kb_hdr; + /* this chunk's items [cur, end) of the item array */ + int64_t cur, end; + uint64_t ibytes; + int full; /* the task stopped for room */ + int64_t null_g; /* group of the null value, -1 */ + int64_t null_vi; /* the null value's index */ + int64_t empty_g; /* group of the empty key, -1 */ + /* replacement buffers, staged by the calling thread */ + uint64_t* nth; uint32_t* ntg; int64_t ntcap; ray_t *nth_hdr, *ntg_hdr; + void* ngf[DKH_NG]; ray_t* ngh[DKH_NG]; int64_t ngcap; + char* nkb; uint64_t nkbcap; ray_t* nkb_hdr; + bool grow; +} dkh_part_t; + +/* A value as its partition's task reads it: all it needs in one place, the + * partition's values contiguous (no gather by value index per value). A + * key of up to DKH_INLINE bytes is copied in, so the task compares it + * without reading the value's bytes, which lie wherever its symbol lies. */ +#define DKH_INLINE 24 +typedef struct dkh_item_s { + const char* p; /* the key */ + uint64_t h; + int64_t k; /* the value's row count */ + uint32_t l; + uint32_t i; /* chunk-relative value index */ + uint32_t vl; /* the value's length */ + uint32_t null; /* the value is the null symbol */ + char kb[DKH_INLINE];/* the key, when l <= DKH_INLINE */ +} dkh_item_t; +static inline const char* dkh_item_key(const dkh_item_t* it) { + return it->l <= DKH_INLINE ? it->kb : it->p; +} + +/* The bytes of a min / max candidate by its index when the vocabulary is a + * compressed file: its strings are decoded per read (domain.h), so a + * pointer to one does not last; the best value is kept by its index and + * decoded again for each comparison. `dv` NULL: the index is the position. */ +typedef struct { + const ray_sym_domain_raw_t* raw; + struct ray_sym_domain_s* dom; + const void* dv; + uint8_t dattrs; +} dkh_zr_t; + +static inline const dkh_zr_t* dkh_zr_set(dkh_zr_t* z, const ray_sym_domain_raw_t* raw, + struct ray_sym_domain_s* dom, const void* dv, + uint8_t dattrs) { + if (!raw || !raw->z) return NULL; + z->raw = raw; z->dom = dom; z->dv = dv; z->dattrs = dattrs; + return z; +} + +typedef struct { + /* inputs */ + ray_t* by_expr; + int64_t col; + ray_t* dvec; /* the distinct values (SYM) */ + const void* dv; + uint8_t dattrs; + struct ray_sym_domain_s* dom; + const ray_sym_domain_raw_t* raw; + int64_t du; + const int64_t* hn; /* rows per value, or NULL */ + unsigned flags; + bool want_codes; + /* chunk state */ + int64_t lo, n, nt; + const char** sp; uint32_t* sl; /* the values */ + const char** kp; uint32_t* kl; uint64_t* kh; /* their keys */ + dkh_item_t* items; + int64_t* tcnt; /* [nt][DKH_NPART] counts, then cursors */ + uint64_t* tbytes; /* [nt][DKH_NPART] key bytes */ + /* results */ + dkh_part_t part[DKH_NPART]; + uint32_t* codes; /* per value, when want_codes */ + int64_t G; + int64_t pbase[DKH_NPART + 1]; + uint32_t* rank; /* [pbase[p] + g]: the group's rank */ + uint32_t* order; /* [rank]: the group's code */ + /* ranking */ + uint64_t* bits; + const int64_t* wrank; + int64_t r_empty; /* rank of the empty key's group by its first value, -1 */ + ray_t* hdrs[8]; + dkh_zr_t zr; /* min / max of a compressed vocabulary: */ + const dkh_zr_t* zp; /* &zr then, else NULL */ +} dkh_t; + +static inline uint32_t dkh_part_of(uint64_t h) { return (uint32_t)(h >> (64 - DKH_PART_BITS)); } +static inline uint64_t dkh_slot(uint64_t h) { return (h * 0x9E3779B97F4A7C15ull) >> 29; } + +/* One value's min / max candidate against the best so far (bi < 0: none): + * by bytes, then length; of equal values the lower value index wins (the + * first in value order, as the row path keeps the first row). */ +static const char* dkh_zget(const dkh_zr_t* z, int64_t i, uint32_t* l) { + int64_t pos = z->dv ? ray_read_sym(z->dv, i, RAY_SYM, z->dattrs) : i; + if (pos >= 0 && pos < z->raw->count) { + size_t sl = 0; + const char* p = ray_sym_domain_raw_str(z->raw, pos, &sl); + *l = (uint32_t)sl; + return p ? p : ""; + } + ray_t* a = ray_sym_domain_str(z->dom, pos); + *l = a ? (uint32_t)ray_str_len(a) : 0; + return a ? ray_str_ptr(a) : ""; +} + +/* Value vi (bytes p, l; with `z`, p may be NULL: read by its index) into + * the best (*bi, *bp, *bl) so far; with `z` the best is kept by index only. */ +static inline void dkh_minmax(const dkh_zr_t* z, int64_t* bi, const char** bp, uint32_t* bl, + int64_t vi, const char* p, uint32_t l, bool is_max) { + if (*bi >= 0) { + const char* q = *bp; + uint32_t ql = *bl; + if (z) { + if (!p) p = dkh_zget(z, vi, &l); + q = dkh_zget(z, *bi, &ql); + } + uint32_t m = l < ql ? l : ql; + int cmp = m ? memcmp(p, q, m) : 0; + if (cmp == 0) cmp = (l > ql) - (l < ql); + if (cmp == 0 ? vi > *bi : (is_max ? cmp < 0 : cmp > 0)) return; + } + *bi = vi; *bp = z ? NULL : p; *bl = l; +} + +static void dkh_count_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dkh_t* c = (dkh_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t* k = c->tcnt + t * DKH_NPART; + uint64_t* b = c->tbytes + t * DKH_NPART; + memset(k, 0, DKH_NPART * sizeof(int64_t)); + memset(b, 0, DKH_NPART * sizeof(uint64_t)); + int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt; + for (int64_t i = lo; i < hi; i++) { + uint32_t p = dkh_part_of(c->kh[i]); + k[p]++; + b[p] += c->kl[i]; + } + } +} + +static void dkh_scatter_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dkh_t* c = (dkh_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t* k = c->tcnt + t * DKH_NPART; + int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt; + for (int64_t i = lo; i < hi; i++) { + uint64_t h = c->kh[i]; + dkh_item_t* it = &c->items[k[dkh_part_of(h)]++]; + it->p = c->kp[i]; + it->h = h; + it->k = c->hn ? c->hn[c->lo + i] : 1; + it->l = c->kl[i]; + it->i = (uint32_t)i; + it->vl = c->sl[i]; + it->null = ray_read_sym(c->dv, c->lo + i, RAY_SYM, c->dattrs) <= 0; + if (it->l <= DKH_INLINE) memcpy(it->kb, it->p, it->l); + } + } +} + +#define DKH_GF(P, f, T) ((T*)(P)->gf[f]) + +static void dkh_group_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dkh_t* c = (dkh_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + dkh_part_t* P = &c->part[p]; + if (P->cur >= P->end) continue; + int64_t* first = DKH_GF(P, DKH_G_FIRST, int64_t); + uint64_t* koff = DKH_GF(P, DKH_G_KOFF, uint64_t); + uint32_t* klen = DKH_GF(P, DKH_G_KLEN, uint32_t); + int64_t* cnt = DKH_GF(P, DKH_G_CNT, int64_t); + int64_t* lenw = DKH_GF(P, DKH_G_LENW, int64_t); + int64_t* mn = DKH_GF(P, DKH_G_MN, int64_t); + const char** mnp = DKH_GF(P, DKH_G_MNP, const char*); + uint32_t* mnl = DKH_GF(P, DKH_G_MNL, uint32_t); + int64_t* mx = DKH_GF(P, DKH_G_MX, int64_t); + const char** mxp = DKH_GF(P, DKH_G_MXP, const char*); + uint32_t* mxl = DKH_GF(P, DKH_G_MXL, uint32_t); + bool aggs = cnt || lenw || mn || mx; + /* the partition's state in locals for the loop, stored back after */ + uint64_t* th = P->th; + uint32_t* tg = P->tg; + char* kb = P->kb; + uint64_t kbn = P->kbn, kbcap = P->kbcap; + int64_t ng = P->ng, gcap = P->gcap, tcap = P->tcap; + int64_t cur = P->cur, end = P->end; + const dkh_item_t* items = c->items; + uint32_t* codes = c->codes; + const int64_t lo = c->lo; + uint64_t mask = (uint64_t)tcap - 1; + for (; cur < end; cur++) { + const dkh_item_t* it = &items[cur]; + uint64_t h = it->h; + uint32_t l = it->l; + uint64_t s = dkh_slot(h) & mask; + int64_t g = -1; + for (;;) { + uint32_t e = tg[s]; + if (!e) break; + if (th[s] == h) { + int64_t q = (int64_t)e - 1; + if (klen[q] == l && (l == 0 || memcmp(kb + koff[q], dkh_item_key(it), l) == 0)) { g = q; break; } + } + s = (s + 1) & mask; + } + int64_t vi = lo + it->i; + if (g < 0) { + if ((ng + 1) * 2 > tcap || ng >= gcap || kbn + l > kbcap) { + P->full = 1; + break; + } + g = ng++; + tg[s] = (uint32_t)(g + 1); + th[s] = h; + first[g] = vi; + koff[g] = kbn; + klen[g] = l; + if (l) memcpy(kb + kbn, dkh_item_key(it), l); + kbn += l; + if (l == 0) P->empty_g = g; + if (cnt) cnt[g] = 0; + if (lenw) lenw[g] = 0; + if (mn) mn[g] = -1; + if (mx) mx[g] = -1; + } + if (codes) codes[vi] = (uint32_t)((uint64_t)g << DKH_PART_BITS | (uint64_t)p); + if (!aggs) continue; + if (cnt) cnt[g] += it->k; + if (it->null) { P->null_g = g; P->null_vi = vi; continue; } + if (lenw) lenw[g] += it->k * (int64_t)it->vl; + if (mn) dkh_minmax(c->zp, &mn[g], &mnp[g], &mnl[g], vi, c->sp[it->i], it->vl, false); + if (mx) dkh_minmax(c->zp, &mx[g], &mxp[g], &mxl[g], vi, c->sp[it->i], it->vl, true); + } + P->kbn = kbn; + P->ng = ng; + P->cur = cur; + } +} + +/* Moves a partition into its staged buffers: the table rehashed, the + * groups and key bytes copied. */ +static void dkh_grow_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dkh_t* c = (dkh_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + dkh_part_t* P = &c->part[p]; + if (!P->grow) continue; + if (P->ntg) { + memset(P->ntg, 0, (size_t)P->ntcap * sizeof(uint32_t)); + uint64_t nm = (uint64_t)P->ntcap - 1; + for (int64_t s = 0; s < P->tcap; s++) { + uint32_t e = P->tg[s]; + if (!e) continue; + uint64_t h = P->th[s]; + uint64_t d = dkh_slot(h) & nm; + while (P->ntg[d]) d = (d + 1) & nm; + P->ntg[d] = e; + P->nth[d] = h; + } + } + for (int f = 0; f < DKH_NG; f++) + if (P->ngf[f] && P->gf[f] && P->ng) + memcpy(P->ngf[f], P->gf[f], (size_t)P->ng * dkh_gsize[f]); + if (P->nkb && P->kbn) memcpy(P->nkb, P->kb, (size_t)P->kbn); + } +} + +static bool dkh_field_on(const dkh_t* c, int f) { + switch (f) { + case DKH_G_FIRST: case DKH_G_KOFF: case DKH_G_KLEN: return true; + case DKH_G_CNT: return (c->flags & DKH_F_CNT) != 0; + case DKH_G_LENW: return (c->flags & DKH_F_LENW) != 0; + case DKH_G_MN: case DKH_G_MNP: case DKH_G_MNL: return (c->flags & DKH_F_MIN) != 0; + default: return (c->flags & DKH_F_MAX) != 0; + } +} + +/* Stage larger buffers for every partition whose pending items might not + * fit, move the content over on the workers, and free what was replaced. + * The share of pending values expected to make new groups is the share so + * far (a quarter before the first chunk), with half again for slack; the + * group arrays, the table (at half load) and the arena are sized for that + * and grown by half at least. A task that still runs out of room stops, + * and the next call sizes it again. False on OOM or past the code width. */ +static bool dkh_grow(dkh_t* c, bool par) { + ray_pool_t* pool = ray_pool_get(); + bool any = false, ok = true; + int64_t ng_all = 0; + for (int p = 0; p < DKH_NPART; p++) ng_all += c->part[p].ng; + double share = c->lo > 0 ? 1.5 * (double)ng_all / (double)c->lo : 0.25; + if (share > 1.0) share = 1.0; + for (int p = 0; p < DKH_NPART && ok; p++) { + dkh_part_t* P = &c->part[p]; + P->grow = false; + int64_t pend = P->end - P->cur; + if (pend <= 0) continue; + int64_t need_g = P->ng + (int64_t)((double)pend * share) + 16; + if (need_g > P->ng + pend) need_g = P->ng + pend; + if (need_g > DKH_MAX_LOCAL) need_g = DKH_MAX_LOCAL; + uint64_t need_b = P->kbn + (uint64_t)((double)P->ibytes * share) + 256; + if (need_b > P->kbn + P->ibytes) need_b = P->kbn + P->ibytes; + if (P->full) { /* room for the value it stopped at, at least */ + if (need_g < P->ng + 1) need_g = P->ng + 1; + uint64_t nb = P->kbn + c->items[P->cur].l; + if (need_b < nb) need_b = nb; + } + if (need_g > DKH_MAX_LOCAL) { ok = false; break; } /* past the code width */ + if (2 * need_g > P->tcap) { + int64_t cap = P->tcap ? P->tcap : 64; + while (cap < 2 * need_g) cap <<= 1; + P->nth = (uint64_t*)scratch_alloc(&P->nth_hdr, (size_t)cap * sizeof(uint64_t)); + P->ntg = (uint32_t*)scratch_alloc(&P->ntg_hdr, (size_t)cap * sizeof(uint32_t)); + if (!P->nth || !P->ntg) { ok = false; break; } + P->ntcap = cap; + } + if (need_g > P->gcap) { + int64_t cap = P->gcap + P->gcap / 2; + if (cap < need_g) cap = need_g; + if (cap > DKH_MAX_LOCAL) cap = DKH_MAX_LOCAL; + for (int f = 0; f < DKH_NG && ok; f++) { + if (!dkh_field_on(c, f)) continue; + P->ngf[f] = scratch_alloc(&P->ngh[f], (size_t)cap * dkh_gsize[f]); + if (!P->ngf[f]) ok = false; + } + P->ngcap = cap; + } + if (need_b > P->kbcap || P->kbcap == 0) { + uint64_t cap = P->kbcap + P->kbcap / 2; + if (cap < need_b) cap = need_b; + if (cap < 1024) cap = 1024; + P->nkb = (char*)scratch_alloc(&P->nkb_hdr, (size_t)cap); + if (!P->nkb) { ok = false; break; } + P->nkbcap = cap; + } + P->grow = P->ntg || P->ngcap || P->nkb; + any |= P->grow; + } + if (ok && any) { + if (par) ray_pool_dispatch_n(pool, dkh_grow_fn, c, DKH_NPART); + else dkh_grow_fn(c, 0, 0, DKH_NPART); + if (ray_interrupted()) ok = false; + } + /* swap in what moved (or drop what was staged, on failure) */ + for (int p = 0; p < DKH_NPART; p++) { + dkh_part_t* P = &c->part[p]; + if (ok && P->grow) { + if (P->ntg) { + scratch_free(P->th_hdr); scratch_free(P->tg_hdr); + P->th = P->nth; P->tg = P->ntg; P->tcap = P->ntcap; + P->th_hdr = P->nth_hdr; P->tg_hdr = P->ntg_hdr; + } + if (P->ngcap) { + for (int f = 0; f < DKH_NG; f++) { + if (!P->ngf[f]) continue; + scratch_free(P->gh[f]); + P->gf[f] = P->ngf[f]; P->gh[f] = P->ngh[f]; + } + P->gcap = P->ngcap; + } + if (P->nkb) { + scratch_free(P->kb_hdr); + P->kb = P->nkb; P->kbcap = P->nkbcap; P->kb_hdr = P->nkb_hdr; + } + P->full = 0; + } else { + scratch_free(P->nth_hdr); scratch_free(P->ntg_hdr); + for (int f = 0; f < DKH_NG; f++) scratch_free(P->ngh[f]); + scratch_free(P->nkb_hdr); + } + P->nth = NULL; P->ntg = NULL; P->ntcap = 0; P->nth_hdr = P->ntg_hdr = NULL; + memset(P->ngf, 0, sizeof(P->ngf)); memset(P->ngh, 0, sizeof(P->ngh)); P->ngcap = 0; + P->nkb = NULL; P->nkbcap = 0; P->nkb_hdr = NULL; + P->grow = false; + } + return ok; +} + +static void dkh_free(dkh_t* c) { + for (int p = 0; p < DKH_NPART; p++) { + dkh_part_t* P = &c->part[p]; + scratch_free(P->th_hdr); scratch_free(P->tg_hdr); + for (int f = 0; f < DKH_NG; f++) scratch_free(P->gh[f]); + scratch_free(P->kb_hdr); + } + for (int k = 0; k < 8; k++) scratch_free(c->hdrs[k]); +} + +/* Ranks: a bitmap of the groups' first values (set on the workers), a + * running popcount per word, the rank of each group, the group of the + * empty key moved first. */ +static void dkh_mark_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dkh_t* c = (dkh_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + const dkh_part_t* P = &c->part[p]; + const int64_t* first = DKH_GF(P, DKH_G_FIRST, int64_t); + for (int64_t g = 0; g < P->ng; g++) + atomic_fetch_or_explicit((_Atomic(uint64_t)*)&c->bits[first[g] >> 6], + (uint64_t)1 << (first[g] & 63), memory_order_relaxed); + } +} + +static inline int64_t dkh_first_rank(const dkh_t* c, int64_t v) { + int64_t w = v >> 6; + return c->wrank[w] + __builtin_popcountll(c->bits[w] & (((uint64_t)1 << (v & 63)) - 1)); +} + +static void dkh_rank_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dkh_t* c = (dkh_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + const dkh_part_t* P = &c->part[p]; + const int64_t* first = DKH_GF(P, DKH_G_FIRST, int64_t); + uint32_t* rk = c->rank + c->pbase[p]; + for (int64_t g = 0; g < P->ng; g++) { + int64_t r = dkh_first_rank(c, first[g]); + if (c->r_empty > 0) r = r == c->r_empty ? 0 : r + (r < c->r_empty); + rk[g] = (uint32_t)r; + c->order[r] = (uint32_t)((uint64_t)g << DKH_PART_BITS | (uint64_t)p); + } + } +} + +static inline uint32_t dkh_code_rank(const dkh_t* c, uint32_t code) { + return c->rank[c->pbase[code & (DKH_NPART - 1)] + (code >> DKH_PART_BITS)]; +} -static void dkp_run_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { - const dkp_run_ctx_t* c = (const dkp_run_ctx_t*)vctx; - const dkp_prog_t* P = c->prog; - dkp_reg_t* R = c->regs + (size_t)wid * (size_t)P->n * DKP_BATCH; - const dkp_reg_t* res = R + (size_t)P->res * DKP_BATCH; - /* literals once: the batches run the other instructions only */ - for (int k = 0; k < P->n; k++) { - dkp_reg_t* o = R + (size_t)k * DKP_BATCH; - if (P->ins[k].op == DKO_LIT) - for (int t = 0; t < DKP_BATCH; t++) o[t].v = P->ins[k].imm; - else if (P->ins[k].op == DKO_LSTR) - for (int t = 0; t < DKP_BATCH; t++) { o[t].p = P->ins[k].sp; o[t].v = P->ins[k].sl; } +/* Group the du distinct values of c->dvec by their key (see above). The + * caller fills the inputs and calls dkh_free afterwards, whatever this + * returns. */ +static bool dkh_build(dkh_t* c) { + int64_t du = c->du; + if (du <= 0 || du >= INT32_MAX) return false; + for (int p = 0; p < DKH_NPART; p++) { c->part[p].null_g = -1; c->part[p].empty_g = -1; } + c->dv = ray_data(c->dvec); + c->dattrs = c->dvec->attrs; + c->zp = dkh_zr_set(&c->zr, c->raw, c->dom, c->dv, c->dattrs); + ray_pool_t* pool = ray_pool_get(); + uint32_t nwork = ray_pool_par_dispatch_ok(pool, 2, 1) ? ray_pool_total_workers(pool) : 1; + + dkp_prog_t* prog = NULL; + ray_t* prog_hdr = NULL; + prog = (dkp_prog_t*)scratch_alloc(&prog_hdr, sizeof(dkp_prog_t)); + c->hdrs[0] = prog_hdr; + if (!prog) return false; + bool use_prog = dkp_build(prog, c->by_expr, c->col); + + const int64_t chunk = derived_key_chunk_rows(!use_prog); + int64_t cn = du < chunk ? du : chunk; + int64_t nt_max = (int64_t)nwork * 4; + if (nt_max < 1) nt_max = 1; + size_t per = 2 * sizeof(const char*) + 2 * sizeof(uint32_t) + sizeof(uint64_t) + sizeof(dkh_item_t); + char* mem = (char*)scratch_alloc(&c->hdrs[1], (size_t)cn * per); + char* tm = (char*)scratch_alloc(&c->hdrs[2], (size_t)nt_max * DKH_NPART * (sizeof(int64_t) + sizeof(uint64_t))); + dkp_reg_t* regs = NULL; + if (use_prog) + regs = (dkp_reg_t*)scratch_alloc(&c->hdrs[3], (size_t)nwork * (size_t)prog->n * DKP_BATCH * sizeof(dkp_reg_t)); + if (!mem || !tm || (use_prog && !regs)) return false; + c->items = (dkh_item_t*)mem; mem += (size_t)cn * sizeof(dkh_item_t); + c->sp = (const char**)mem; mem += (size_t)cn * sizeof(const char*); + c->kp = (const char**)mem; mem += (size_t)cn * sizeof(const char*); + c->kh = (uint64_t*)mem; mem += (size_t)cn * sizeof(uint64_t); + c->sl = (uint32_t*)mem; mem += (size_t)cn * sizeof(uint32_t); + c->kl = (uint32_t*)mem; + c->tcnt = (int64_t*)tm; + c->tbytes = (uint64_t*)(tm + (size_t)nt_max * DKH_NPART * sizeof(int64_t)); + if (c->want_codes) { + c->codes = (uint32_t*)scratch_alloc(&c->hdrs[4], (size_t)du * sizeof(uint32_t)); + if (!c->codes) return false; } - for (int64_t i = start; i < end; i += DKP_BATCH) { - int m = end - i < DKP_BATCH ? (int)(end - i) : DKP_BATCH; - dkp_run_batch(P, R, c->sp + i, c->sl + i, m); - for (int t = 0; t < m; t++) { - const char* p = res[t].v ? res[t].p : ""; - uint32_t l = (uint32_t)res[t].v; - c->sp[i + t] = p; - c->sl[i + t] = l; - c->hash[i + t] = (uint32_t)ray_hash_bytes(p, l); - } + + for (int64_t lo = 0; lo < du; lo += chunk) { + if (ray_interrupted()) return false; + int64_t n = du - lo < chunk ? du - lo : chunk; + c->lo = lo; c->n = n; + bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + if (!dk_chunk_views(c->dv, c->dattrs, lo, n, c->raw, c->dom, NULL, c->sp, c->sl, true)) return false; + ray_t* kc = NULL; + if (!dkh_keys_of(c->by_expr, c->col, use_prog ? prog : NULL, regs, c->sp, c->sl, n, + c->kp, c->kl, c->kh, &kc)) return false; + + /* scatter by partition, value order kept within each */ + int64_t nt = 1; + if (par) { + nt = nt_max; + if (nt > n / 4096) nt = n / 4096; + if (nt < 1) nt = 1; + } + c->nt = nt; + if (nt > 1) ray_pool_dispatch_n(pool, dkh_count_fn, c, (uint32_t)nt); + else dkh_count_fn(c, 0, 0, 1); + int64_t run = 0; + for (int p = 0; p < DKH_NPART; p++) { + dkh_part_t* P = &c->part[p]; + P->cur = run; + P->ibytes = 0; + for (int64_t t = 0; t < nt; t++) { + int64_t k = c->tcnt[t * DKH_NPART + p]; + P->ibytes += c->tbytes[t * DKH_NPART + p]; + c->tcnt[t * DKH_NPART + p] = run; + run += k; + } + P->end = run; + } + if (nt > 1) ray_pool_dispatch_n(pool, dkh_scatter_fn, c, (uint32_t)nt); + else dkh_scatter_fn(c, 0, 0, 1); + + /* the partitions, until every one has taken its items */ + bool ok = dkh_grow(c, par); + while (ok) { + if (par) ray_pool_dispatch_n(pool, dkh_group_fn, c, DKH_NPART); + else dkh_group_fn(c, 0, 0, DKH_NPART); + if (ray_interrupted()) { ok = false; break; } + bool pending = false; + for (int p = 0; p < DKH_NPART; p++) if (c->part[p].cur < c->part[p].end) pending = true; + if (!pending) break; + ok = dkh_grow(c, par); + } + if (kc) ray_release(kc); + if (!ok) return false; + ray_profile_tick("derived key: values grouped"); + } + + /* ranks by first value */ + int64_t G = 0; + for (int p = 0; p < DKH_NPART; p++) { c->pbase[p] = G; G += c->part[p].ng; } + c->pbase[DKH_NPART] = G; + c->G = G; + if (G <= 0 || G > du) return false; + int64_t nw = (du + 63) / 64; + c->bits = (uint64_t*)scratch_calloc(&c->hdrs[5], (size_t)nw * sizeof(uint64_t)); + int64_t* wrank = (int64_t*)scratch_alloc(&c->hdrs[6], (size_t)nw * sizeof(int64_t)); + char* rm = (char*)scratch_alloc(&c->hdrs[7], (size_t)G * 2 * sizeof(uint32_t)); + if (!c->bits || !wrank || !rm) return false; + c->rank = (uint32_t*)rm; + c->order = c->rank + G; + bool par = ray_pool_par_dispatch_ok(pool, G, RAY_PARALLEL_THRESHOLD); + if (par) ray_pool_dispatch_n(pool, dkh_mark_fn, c, DKH_NPART); + else dkh_mark_fn(c, 0, 0, DKH_NPART); + int64_t run = 0; + for (int64_t w = 0; w < nw; w++) { wrank[w] = run; run += __builtin_popcountll(c->bits[w]); } + c->wrank = wrank; + if (run != G) return false; + c->r_empty = -1; + for (int p = 0; p < DKH_NPART; p++) { + const dkh_part_t* P = &c->part[p]; + if (P->empty_g >= 0) + c->r_empty = dkh_first_rank(c, DKH_GF(P, DKH_G_FIRST, int64_t)[P->empty_g]); + } + if (par) ray_pool_dispatch_n(pool, dkh_rank_fn, c, DKH_NPART); + else dkh_rank_fn(c, 0, 0, DKH_NPART); + scratch_free(c->hdrs[5]); c->hdrs[5] = NULL; c->bits = NULL; + scratch_free(c->hdrs[6]); c->hdrs[6] = NULL; c->wrank = NULL; + /* the chunk buffers are done */ + scratch_free(c->hdrs[1]); c->hdrs[1] = NULL; + scratch_free(c->hdrs[2]); c->hdrs[2] = NULL; + scratch_free(c->hdrs[3]); c->hdrs[3] = NULL; + ray_profile_tick("derived key: groups ranked"); + return true; +} + +/* The key bytes of group `code`. */ +static inline const char* dkh_key(const dkh_t* c, uint32_t code, uint32_t* len) { + const dkh_part_t* P = &c->part[code & (DKH_NPART - 1)]; + uint32_t g = code >> DKH_PART_BITS; + *len = DKH_GF(P, DKH_G_KLEN, uint32_t)[g]; + return P->kb + DKH_GF(P, DKH_G_KOFF, uint64_t)[g]; +} + +/* The keys of groups order[0, n) (codes) into a fresh key domain, in that + * order — all distinct, so one batch appends them: position = order + * (after the domain's "" at 0). The domain hash is computed here, never + * the grouping's. */ +typedef struct { + const dkh_t* c; + const uint32_t* codes; + const char** strs; + size_t* lens; + uint32_t* h32; +} dkh_keys_ctx_t; + +static void dkh_keys_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)wid; + const dkh_keys_ctx_t* k = (const dkh_keys_ctx_t*)vctx; + for (int64_t r = lo; r < hi; r++) { + uint32_t l; + const char* p = dkh_key(k->c, k->codes[r], &l); + k->strs[r] = p; + k->lens[r] = l; + k->h32[r] = (uint32_t)ray_hash_bytes(p, l); } } -/* The keys of dv[lo, lo+n) through the program, interned into the key - * domain kdom as kd[0, n). */ -static bool dkp_chunk_keys(const dkp_prog_t* P, const void* dv, uint8_t dattrs, int64_t lo, - int64_t n, const ray_sym_domain_raw_t* raw, - struct ray_sym_domain_s* dom, struct ray_sym_domain_s* kdom, - int64_t* kd) { +static bool dkh_intern_keys(const dkh_t* c, const uint32_t* codes, int64_t n, + struct ray_sym_domain_s* kdom, int64_t* pos) { + if (n <= 0) return true; + ray_t* hdr = NULL; + char* mem = (char*)scratch_alloc(&hdr, (size_t)n * (sizeof(const char*) + sizeof(size_t) + sizeof(uint32_t))); + if (!mem) return false; + dkh_keys_ctx_t k = { .c = c, .codes = codes }; + k.strs = (const char**)mem; + k.lens = (size_t*)(mem + (size_t)n * sizeof(const char*)); + k.h32 = (uint32_t*)(mem + (size_t)n * (sizeof(const char*) + sizeof(size_t))); ray_pool_t* pool = ray_pool_get(); - bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); - uint32_t nwork = par ? ray_pool_total_workers(pool) : 1; - ray_t *hdr = NULL, *rhdr = NULL; - char* mem = (char*)scratch_alloc(&hdr, (size_t)n * (sizeof(const char*) + 2 * sizeof(uint32_t))); - dkp_reg_t* regs = (dkp_reg_t*)scratch_alloc(&rhdr, (size_t)nwork * (size_t)P->n * - DKP_BATCH * sizeof(dkp_reg_t)); - if (!mem || !regs) { scratch_free(hdr); scratch_free(rhdr); return false; } - dkp_run_ctx_t c = { .prog = P, .regs = regs }; - c.sp = (const char**)mem; - c.sl = (uint32_t*)(mem + (size_t)n * sizeof(const char*)); - c.hash = c.sl + n; - bool ok = dk_chunk_views(dv, dattrs, lo, n, raw, dom, c.sp, c.sl); - if (ok) { - if (par) ray_pool_dispatch(pool, dkp_run_fn, &c, n); - else dkp_run_fn(&c, 0, 0, n); - ray_profile_tick("derived key: program over values"); - ok = dk_intern_views(c.sp, c.sl, c.hash, n, kdom, kd); - } - scratch_free(rhdr); + if (ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD)) ray_pool_dispatch(pool, dkh_keys_fn, &k, n); + else dkh_keys_fn(&k, 0, 0, n); + bool ok = ray_sym_domain_intern_batch(kdom, n, k.strs, k.lens, k.h32, pos); scratch_free(hdr); + ray_profile_tick("derived key: key domain interned"); return ok; } +/* Per value: the key domain position of its group. */ +typedef struct { + const dkh_t* c; + const int64_t* kpos; + int64_t* out; +} dkh_spread_ctx_t; + +static void dkh_spread_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)wid; + const dkh_spread_ctx_t* s = (const dkh_spread_ctx_t*)vctx; + for (int64_t i = lo; i < hi; i++) s->out[i] = s->kpos[dkh_code_rank(s->c, s->c->codes[i])]; +} + +/* The key of each of the du values of dom_vec, as a SYM vector over a key + * domain of its own: the distinct values grouped by key (dkh_build), the + * groups' keys interned once each in first-seen order, every value given + * its group's position. Applies only when the expression's result over + * the SYM column is SYM (the type the caller expects). NULL otherwise. */ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom_vec, struct ray_sym_domain_s* dom, int64_t du) { if (!dom || du <= 0) return NULL; + if (!dk_key_is_sym(by_expr, col_sym, dom_vec)) return NULL; ray_sym_domain_raw_t raw = {0}; (void)ray_sym_domain_raw_pin(dom, &raw); - - /* The result type the SYM evaluation would give: compile (only) the - * expression against the SYM column. */ - int8_t sym_out = 0; - { - ray_t* probe = ray_table_new(0); - /* add_col retains the column itself; the caller keeps its own ref. */ - if (probe && !RAY_IS_ERR(probe)) probe = ray_table_add_col(probe, col_sym, dom_vec); - if (!probe || RAY_IS_ERR(probe)) { if (probe) ray_error_free(probe); goto unpin_null; } - ray_graph_t* gp = ray_graph_new(probe); - if (gp) { - ray_op_t* kop = compile_expr_dag(gp, by_expr); - /* A key that compiles to a constant — a literal, or a let whose - * body is one — evaluates to that literal: a string literal is - * typed SYM by the compiler but executes as the STR it is. The - * one-shot evaluation (and the row path behind it) keeps that - * type; this path would intern it into a symbol. */ - if (kop && kop->opcode != OP_CONST) sym_out = kop->out_type; - ray_graph_free(gp); - } - ray_release(probe); - } - if (sym_out != RAY_SYM) goto unpin_null; - - ray_t* key_dom = ray_vec_new(RAY_SYM, du); - if (!key_dom || RAY_IS_ERR(key_dom)) { if (key_dom) ray_error_free(key_dom); goto unpin_null; } - key_dom->len = du; - int64_t* kd = (int64_t*)ray_data(key_dom); - const void* dv = ray_data(dom_vec); - /* The key strings live in a domain of their own, owned by the key - * vector (and by every vector that adopts it): the query's derived - * values never enter the global table, and the whole dictionary goes - * when the last result column holding it does. Its positions are - * this execution's first-seen ranks of the keys (dk_intern_views). */ + ray_t* out = NULL; + ray_t* chdr = NULL; + dkh_t* c = (dkh_t*)scratch_calloc(&chdr, sizeof(dkh_t)); + if (!c) goto done; + c->by_expr = by_expr; c->col = col_sym; c->dvec = dom_vec; c->dom = dom; c->raw = &raw; + c->du = du; c->want_codes = true; + if (!dkh_build(c)) goto done; { + ray_t* key_dom = ray_vec_new(RAY_SYM, du); + if (!key_dom || RAY_IS_ERR(key_dom)) { if (key_dom) ray_error_free(key_dom); goto done; } + key_dom->len = du; + /* The key strings live in a domain of their own, owned by the key + * vector (and by every vector that adopts it): the query's derived + * values never enter the global table, and the whole dictionary + * goes when the last result column holding it does. */ struct ray_sym_domain_s* kdom = ray_sym_domain_new(); - if (!kdom) { ray_release(key_dom); goto unpin_null; } + if (!kdom) { ray_release(key_dom); goto done; } key_dom->sym_domain = kdom; /* the vector takes the ref */ + ray_t* phdr = NULL; + int64_t* kpos = (int64_t*)scratch_alloc(&phdr, (size_t)c->G * sizeof(int64_t)); + if (!kpos || !dkh_intern_keys(c, c->order, c->G, kdom, kpos)) { + scratch_free(phdr); ray_release(key_dom); goto done; + } + dkh_spread_ctx_t sc = { .c = c, .kpos = kpos, .out = (int64_t*)ray_data(key_dom) }; + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, du, RAY_PARALLEL_THRESHOLD)) ray_pool_dispatch(pool, dkh_spread_fn, &sc, du); + else dkh_spread_fn(&sc, 0, 0, du); + scratch_free(phdr); + ray_profile_tick("derived key: keys spread"); + out = key_dom; + } +done: + if (c) dkh_free(c); + scratch_free(chdr); + ray_sym_domain_raw_unpin(dom); + return out; +} + +/* ---- min / max of the kept groups, after the grouping: only the values + * of kept groups are read (their bytes off the mapping, in value order), + * scattered by their group's partition, and one task per partition + * compares its groups' values — the first of equal values kept, as the row + * path keeps it. oix[rank] is the group's output row (UINT32_MAX: not + * kept); mn/mx NULL when not wanted. */ +typedef struct { + const char* p; + uint32_t i; /* chunk-relative value index */ + uint32_t l; + uint32_t o; /* the group's output row */ + uint32_t pad; +} dkh_mm_item_t; +typedef struct { + const dkh_t* c; + const uint32_t* oix; + int64_t lo, n, nt; + uint8_t* want; + uint32_t* wo; /* per value: its group's output row */ + const char** sp; + uint32_t* sl; + int64_t* tcnt; /* [nt][DKH_NPART]: counts, then cursors */ + dkh_mm_item_t* items; /* the wanted values, by partition */ + int64_t pstart[DKH_NPART + 1]; + int64_t* mn; const char** mnp; uint32_t* mnl; + int64_t* mx; const char** mxp; uint32_t* mxl; +} dkh_mm_ctx_t; + +static void dkh_mm_want_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)wid; + dkh_mm_ctx_t* m = (dkh_mm_ctx_t*)vctx; + const dkh_t* c = m->c; + for (int64_t i = lo; i < hi; i++) { + int64_t vi = m->lo + i; + uint32_t o = m->oix[dkh_code_rank(c, c->codes[vi])]; + m->wo[i] = o; + m->want[i] = o != UINT32_MAX && ray_read_sym(c->dv, vi, RAY_SYM, c->dattrs) > 0; } - struct ray_sym_domain_s* kdom = key_dom->sym_domain; +} - /* The per-value program when the key compiles to one, the chunk DAG - * otherwise. */ - dkp_prog_t prog; - bool use_prog = dkp_build(&prog, by_expr, col_sym); +static void dkh_mm_count_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dkh_mm_ctx_t* m = (dkh_mm_ctx_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t* k = m->tcnt + t * DKH_NPART; + memset(k, 0, DKH_NPART * sizeof(int64_t)); + int64_t lo = m->n * t / m->nt, hi = m->n * (t + 1) / m->nt; + for (int64_t i = lo; i < hi; i++) + if (m->want[i]) k[m->c->codes[m->lo + i] & (DKH_NPART - 1)]++; + } +} - const int64_t chunk = derived_key_chunk_rows(); - for (int64_t lo = 0; lo < du; lo += chunk) { - int64_t n = du - lo < chunk ? du - lo : chunk; - if (use_prog) { - if (!dkp_chunk_keys(&prog, dv, dom_vec->attrs, lo, n, &raw, dom, kdom, kd + lo)) goto fail; - continue; +static void dkh_mm_scatter_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dkh_mm_ctx_t* m = (dkh_mm_ctx_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t* k = m->tcnt + t * DKH_NPART; + int64_t lo = m->n * t / m->nt, hi = m->n * (t + 1) / m->nt; + for (int64_t i = lo; i < hi; i++) { + if (!m->want[i]) continue; + dkh_mm_item_t* it = &m->items[k[m->c->codes[m->lo + i] & (DKH_NPART - 1)]++]; + it->p = m->sp[i]; + it->i = (uint32_t)i; + it->l = m->sl[i]; + it->o = m->wo[i]; + it->pad = 0; } - ray_t* sv = derived_key_chunk_strs(dv, dom_vec->attrs, lo, n, &raw, dom); - if (!sv) goto fail; - ray_t* mini = ray_table_new(0); - if (mini && !RAY_IS_ERR(mini)) mini = ray_table_add_col(mini, col_sym, sv); - ray_release(sv); - if (!mini || RAY_IS_ERR(mini)) { if (mini) ray_error_free(mini); goto fail; } - ray_t* kc = NULL; - ray_graph_t* g2 = ray_graph_new(mini); - if (g2) { - ray_op_t* kop = compile_expr_dag(g2, by_expr); - if (kop) kop = ray_optimize(g2, kop); - if (kop) kc = ray_execute(g2, kop); - ray_graph_free(g2); + } +} + +static void dkh_mm_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dkh_mm_ctx_t* m = (dkh_mm_ctx_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + for (int64_t j = m->pstart[p]; j < m->pstart[p + 1]; j++) { + const dkh_mm_item_t* it = &m->items[j]; + int64_t vi = m->lo + it->i; + uint32_t o = it->o; + if (m->mn) dkh_minmax(m->c->zp, &m->mn[o], &m->mnp[o], &m->mnl[o], vi, it->p, it->l, false); + if (m->mx) dkh_minmax(m->c->zp, &m->mx[o], &m->mxp[o], &m->mxl[o], vi, it->p, it->l, true); } - ray_release(mini); - if (kc && !RAY_IS_ERR(kc) && ray_is_lazy(kc)) kc = ray_lazy_materialize(kc); - if (!kc || RAY_IS_ERR(kc)) { if (kc) ray_error_free(kc); goto fail; } - if (!ray_is_vec(kc) || kc->len != n) { ray_release(kc); goto fail; } - ray_profile_tick("derived key: chunk DAG"); - if (kc->type == RAY_STR) { - if (!derived_key_intern_chunk(kc, n, kdom, kd + lo)) { ray_release(kc); goto fail; } - } else if (RAY_IS_SYM(kc->type)) { - /* The STR evaluation still produced symbols (e.g. a literal - * symbol branch): their strings, into the key domain. */ - if (!derived_key_intern_sym_cells(kc, n, kdom, kd + lo)) { ray_release(kc); goto fail; } - } else { - ray_release(kc); - goto fail; + } +} + +static bool dkh_kept_minmax_scatter(const dkh_t* c, const uint32_t* oix, + int64_t* mn, const char** mnp, uint32_t* mnl, + int64_t* mx, const char** mxp, uint32_t* mxl) { + if (!c->codes) return false; + ray_pool_t* pool = ray_pool_get(); + const int64_t chunk = derived_key_chunk_rows(false); + int64_t cn = c->du < chunk ? c->du : chunk; + int64_t nt_max = (int64_t)ray_pool_total_workers(pool) * 4; + if (nt_max < 1) nt_max = 1; + ray_t *hdr = NULL, *thdr = NULL; + char* mem = (char*)scratch_alloc(&hdr, (size_t)cn * (sizeof(dkh_mm_item_t) + sizeof(const char*) + + 2 * sizeof(uint32_t) + 1)); + int64_t* tcnt = (int64_t*)scratch_alloc(&thdr, (size_t)nt_max * DKH_NPART * sizeof(int64_t)); + if (!mem || !tcnt) { scratch_free(hdr); scratch_free(thdr); return false; } + dkh_mm_ctx_t m; + memset(&m, 0, sizeof(m)); + m.c = c; m.oix = oix; m.tcnt = tcnt; + m.mn = mn; m.mnp = mnp; m.mnl = mnl; m.mx = mx; m.mxp = mxp; m.mxl = mxl; + m.items = (dkh_mm_item_t*)mem; mem += (size_t)cn * sizeof(dkh_mm_item_t); + m.sp = (const char**)mem; mem += (size_t)cn * sizeof(const char*); + m.sl = (uint32_t*)mem; mem += (size_t)cn * sizeof(uint32_t); + m.wo = (uint32_t*)mem; mem += (size_t)cn * sizeof(uint32_t); + m.want = (uint8_t*)mem; + bool ok = true; + for (int64_t lo = 0; lo < c->du && ok; lo += chunk) { + if (ray_interrupted()) { ok = false; break; } + int64_t n = c->du - lo < chunk ? c->du - lo : chunk; + m.lo = lo; m.n = n; + bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + if (par) ray_pool_dispatch(pool, dkh_mm_want_fn, &m, n); + else dkh_mm_want_fn(&m, 0, 0, n); + if (!dk_chunk_views(c->dv, c->dattrs, lo, n, c->raw, c->dom, m.want, m.sp, m.sl, true)) { ok = false; break; } + int64_t nt = 1; + if (par) { + nt = nt_max; + if (nt > n / 4096) nt = n / 4096; + if (nt < 1) nt = 1; + } + m.nt = nt; + if (nt > 1) ray_pool_dispatch_n(pool, dkh_mm_count_fn, &m, (uint32_t)nt); + else dkh_mm_count_fn(&m, 0, 0, 1); + int64_t run = 0; + for (int p = 0; p < DKH_NPART; p++) { + m.pstart[p] = run; + for (int64_t t = 0; t < nt; t++) { + int64_t k = tcnt[t * DKH_NPART + p]; + tcnt[t * DKH_NPART + p] = run; + run += k; + } + } + m.pstart[DKH_NPART] = run; + if (nt > 1) ray_pool_dispatch_n(pool, dkh_mm_scatter_fn, &m, (uint32_t)nt); + else dkh_mm_scatter_fn(&m, 0, 0, 1); + if (par) ray_pool_dispatch_n(pool, dkh_mm_fn, &m, DKH_NPART); + else dkh_mm_fn(&m, 0, 0, DKH_NPART); + if (ray_interrupted()) ok = false; + } + scratch_free(hdr); + scratch_free(thdr); + ray_profile_tick("derived key: min/max of kept groups by partition"); + return ok; +} + +/* The same for few kept groups: every worker takes value ranges in value + * order and keeps a best per kept group of its own (no scatter, the + * values' bytes read in mapping order); the bests are merged per group + * afterwards. A value past the file prefix / the borrowed atom array is + * left to the calling thread. */ +typedef struct { + const dkh_t* c; + const uint32_t* oc; /* [pbase[p] + g]: the group's output row */ + int64_t K; + int64_t* mn; const char** mnp; uint32_t* mnl; /* [worker][K] */ + int64_t* mx; const char** mxp; uint32_t* mxl; + ray_t* const* rstr; + uint32_t rcnt; + atomic_int late; +} dkh_mmw_ctx_t; + +static inline uint32_t dkh_mmw_out(const dkh_mmw_ctx_t* m, int64_t vi) { + uint32_t code = m->c->codes[vi]; + return m->oc[m->c->pbase[code & (DKH_NPART - 1)] + (code >> DKH_PART_BITS)]; +} + +/* The bytes of value vi when a worker may read them; false = late. */ +static inline bool dkh_mmw_str(const dkh_mmw_ctx_t* m, int64_t pos, const char** p, uint32_t* l) { + if (m->rstr) { + ray_t* a = pos < (int64_t)m->rcnt ? m->rstr[pos] : NULL; + if (!a || ray_str_len(a) > UINT32_MAX) return false; + *p = ray_str_ptr(a); + *l = (uint32_t)ray_str_len(a); + return true; + } + if (pos >= m->c->raw->count) return false; + size_t sl = 0; + const char* s = ray_sym_domain_raw_str(m->c->raw, pos, &sl); + *p = s ? s : ""; + *l = (uint32_t)sl; + return true; +} + +static void dkh_mmw_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { + dkh_mmw_ctx_t* m = (dkh_mmw_ctx_t*)vctx; + const dkh_t* c = m->c; + size_t base = (size_t)wid * (size_t)m->K; + int late = 0; + for (int64_t vi = lo; vi < hi; vi++) { + uint32_t o = dkh_mmw_out(m, vi); + if (o == UINT32_MAX) continue; + int64_t pos = ray_read_sym(c->dv, vi, RAY_SYM, c->dattrs); + if (pos <= 0) continue; + const char* p; uint32_t l; + if (!dkh_mmw_str(m, pos, &p, &l)) { late++; continue; } + size_t s = base + o; + if (m->mn) dkh_minmax(c->zp, &m->mn[s], &m->mnp[s], &m->mnl[s], vi, p, l, false); + if (m->mx) dkh_minmax(c->zp, &m->mx[s], &m->mxp[s], &m->mxl[s], vi, p, l, true); + } + if (late) atomic_fetch_add_explicit(&m->late, late, memory_order_relaxed); +} + +static bool dkh_kept_minmax(const dkh_t* c, const uint32_t* oix, int64_t K, + int64_t* mn, const char** mnp, uint32_t* mnl, + int64_t* mx, const char** mxp, uint32_t* mxl) { + if (!c->codes) return false; + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, c->du, RAY_PARALLEL_THRESHOLD); + int64_t nw = par ? (int64_t)ray_pool_total_workers(pool) : 1; + if (K * nw > ((int64_t)1 << 20)) + return dkh_kept_minmax_scatter(c, oix, mn, mnp, mnl, mx, mxp, mxl); + ray_t *ohdr = NULL, *whdr = NULL; + uint32_t* oc = (uint32_t*)scratch_alloc(&ohdr, (size_t)c->G * sizeof(uint32_t)); + size_t per = sizeof(int64_t) + sizeof(const char*) + sizeof(uint32_t); + char* w = (char*)scratch_alloc(&whdr, (size_t)nw * (size_t)K * per * 2); + if (!oc || !w) { scratch_free(ohdr); scratch_free(whdr); return false; } + for (int64_t q = 0; q < c->G; q++) oc[q] = oix[c->rank[q]]; + dkh_mmw_ctx_t m; + memset(&m, 0, sizeof(m)); + m.c = c; m.oc = oc; m.K = K; + size_t nk = (size_t)nw * (size_t)K; + int64_t* wmn = (int64_t*)w; w += nk * sizeof(int64_t); + int64_t* wmx = (int64_t*)w; w += nk * sizeof(int64_t); + const char** wmnp = (const char**)w; w += nk * sizeof(const char*); + const char** wmxp = (const char**)w; w += nk * sizeof(const char*); + uint32_t* wmnl = (uint32_t*)w; w += nk * sizeof(uint32_t); + uint32_t* wmxl = (uint32_t*)w; + for (size_t s = 0; s < nk; s++) { wmn[s] = -1; wmx[s] = -1; } + if (mn) { m.mn = wmn; m.mnp = wmnp; m.mnl = wmnl; } + if (mx) { m.mx = wmx; m.mxp = wmxp; m.mxl = wmxl; } + if (c->dom == ray_sym_runtime_domain()) { + ray_t** rs = NULL; uint32_t rcnt = 0; + ray_sym_strings_borrow(&rs, &rcnt); + m.rstr = rs; m.rcnt = rcnt; + } + atomic_store_explicit(&m.late, 0, memory_order_relaxed); + if (par) ray_pool_dispatch(pool, dkh_mmw_fn, &m, c->du); + else dkh_mmw_fn(&m, 0, 0, c->du); + bool ok = !ray_interrupted(); + /* merge: per kept group, the best over the workers */ + for (int64_t o = 0; ok && o < K; o++) { + for (int64_t wk = 0; wk < nw; wk++) { + size_t s = (size_t)wk * (size_t)K + (size_t)o; + if (mn && wmn[s] >= 0) dkh_minmax(c->zp, &mn[o], &mnp[o], &mnl[o], wmn[s], wmnp[s], wmnl[s], false); + if (mx && wmx[s] >= 0) dkh_minmax(c->zp, &mx[o], &mxp[o], &mxl[o], wmx[s], wmxp[s], wmxl[s], true); + } + } + /* the values no worker could read, through the domain */ + if (ok && atomic_load_explicit(&m.late, memory_order_relaxed)) { + for (int64_t vi = 0; vi < c->du; vi++) { + uint32_t o = dkh_mmw_out(&m, vi); + if (o == UINT32_MAX) continue; + int64_t pos = ray_read_sym(c->dv, vi, RAY_SYM, c->dattrs); + if (pos <= 0) continue; + const char* p; uint32_t l; + if (dkh_mmw_str(&m, pos, &p, &l)) continue; + ray_t* a = ray_sym_domain_str(c->dom, pos); + size_t sl = a ? ray_str_len(a) : 0; + if (sl > UINT32_MAX) { ok = false; break; } + p = a ? ray_str_ptr(a) : ""; + l = (uint32_t)sl; + if (mn) dkh_minmax(c->zp, &mn[o], &mnp[o], &mnl[o], vi, p, l, false); + if (mx) dkh_minmax(c->zp, &mx[o], &mxp[o], &mxl[o], vi, p, l, true); } - ray_release(kc); } - ray_sym_domain_raw_unpin(dom); - return key_dom; -fail: - ray_release(key_dom); -unpin_null: - ray_sym_domain_raw_unpin(dom); - return NULL; + scratch_free(ohdr); + scratch_free(whdr); + ray_profile_tick("derived key: min/max of kept groups"); + return ok; } /* ---- aggregates over the vocabulary ------------------------------------- @@ -5604,8 +8240,15 @@ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom * its strlen sum the length-weighted count. So: one grouping of the rows by * C itself (the engine's fastest shape: a column key, a count) gives the * distinct values with their counts; the key expression runs once per - * distinct value (derived_key_str_chunks); and the aggregates are rewritten - * over that per-value table. Nothing per row is evaluated or accumulated + * distinct value and the values are grouped by key (dkh_build), each + * group's count, length-weighted count and min/max accumulated as its + * values join it. With a having cut armed by the enclosing select (a + * where over the count, dkv_having_count) that few groups can pass, the + * values are grouped in two passes instead (dk2_run: counts by key hash, + * then exact aggregates for the keys under the hashes that pass); with one + * that many can pass, min/max are found afterwards for the kept groups + * only. Only the output groups' keys are interned. + * Nothing per row is evaluated or accumulated * beyond the count histogram. count(C) counts null rows too, avg(strlen C) * divides by the non-null rows, min/max skip null — the row-wise rules. * Returns NULL for every shape it does not take (the caller runs the row @@ -5684,52 +8327,11 @@ static int dkv_agg_kind(ray_t* v, int64_t col) { #undef DKV_IS } -/* Per distinct value (workers): its non-null row count and its - * length-weighted row count, the length read off the pinned mapping. A - * position past the file prefix is marked (lenw = INT64_MIN) and resolved - * through the domain on the calling thread. */ -typedef struct { - const void* hc; - uint8_t attrs; - const int64_t* cnt; - int64_t* nn; - int64_t* lenw; - struct ray_sym_domain_s* dom; - ray_sym_domain_raw_t raw; - bool raw_ok; - ray_t* const* rstr; /* runtime domain: the borrowed atom array */ - uint32_t rcnt; - atomic_int late; -} dkv_len_ctx_t; - -static void dkv_len_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { - (void)wid; - dkv_len_ctx_t* c = (dkv_len_ctx_t*)vctx; - int late = 0; - for (int64_t i = lo; i < hi; i++) { - int64_t pos = ray_read_sym(c->hc, i, RAY_SYM, c->attrs); - c->nn[i] = pos > 0 ? c->cnt[i] : 0; - if (pos <= 0) { c->lenw[i] = 0; continue; } - if (c->rstr) { - ray_t* a = pos < (int64_t)c->rcnt ? c->rstr[pos] : NULL; - if (a) c->lenw[i] = c->cnt[i] * (int64_t)ray_str_len(a); - else { c->lenw[i] = INT64_MIN; late++; } - } else if (c->raw_ok && pos < c->raw.count) { - size_t l; (void)ray_sym_domain_raw_str(&c->raw, pos, &l); - c->lenw[i] = c->cnt[i] * (int64_t)l; - } else { - c->lenw[i] = INT64_MIN; - late++; - } - } - if (late) atomic_fetch_add_explicit(&c->late, late, memory_order_relaxed); -} - /* H (distinct values of C with their counts) in C's domain-position order. * The grouping that produced H emits in an order that depends on the core - * count; the key domain is filled in H's order, and the rewrite's output - * is put in key-position order, so it comes out the same at every core - * count (the first-seen order of the key values over the vocabulary). Positions are distinct, so the order is the + * count; the groups are ranked by their first value in H, so the output + * comes out the same at every core count (the first-seen order of the + * key values over the vocabulary). Positions are distinct, so the order is the * rank of each position among those present: a bitmap over the domain * (set on the workers), a running popcount per word, then a scatter on the * workers. Returns a new table, or NULL (H kept). */ @@ -5773,10 +8375,22 @@ static void dkv_order_scatter_fn(void* vctx, uint32_t wid, int64_t lo, int64_t h } static ray_t* dkv_order_by_position(ray_t* H, int64_t dom_count) { - ray_t* Hc = ray_table_get_col_idx(H, 0); - ray_t* Hn = ray_table_get_col_idx(H, 1); + ray_t* Hc = tbl_col_idx_or_null(H, 0); /* engine-built: never encoded */ + ray_t* Hn = tbl_col_idx_or_null(H, 1); int64_t du = ray_table_nrows(H); - if (dom_count <= 0 || du <= 1) return NULL; + if (!Hc || !Hn || dom_count <= 0 || du <= 1) return NULL; + /* A dense grouping emits its groups ascending by code already: keep H + * rather than hold a second copy of it. */ + { + const void* cd = ray_data(Hc); + int64_t prev = ray_read_sym(cd, 0, RAY_SYM, Hc->attrs), i = 1; + for (; i < du; i++) { + int64_t cur = ray_read_sym(cd, i, RAY_SYM, Hc->attrs); + if (cur <= prev) break; + prev = cur; + } + if (i == du) return NULL; + } int64_t nw = (dom_count + 63) / 64; ray_t *bh = NULL, *rh = NULL; uint64_t* bits = (uint64_t*)scratch_calloc(&bh, (size_t)nw * sizeof(uint64_t)); @@ -5824,6 +8438,884 @@ static ray_t* dkv_order_by_position(ray_t* H, int64_t dom_count) { return out; } +/* An enclosing select whose `where: (> c N)` reads a count output of this + * one arms the group emit filter for it (match_group_count_emit_filter): + * the groups that filter drops are dropped here as well, before a key or a + * min / max is made for them — the enclosing select still applies its + * where as written, so the answer is the same. N when the filter targets + * an output that counts C and this select has no sort or take; -1 + * otherwise. */ +static int64_t dkv_having_count(ray_t** dict_elems, int64_t dict_n, int64_t from_id, + int64_t by_id, int64_t where_id, int64_t take_id, + int64_t asc_id, int64_t desc_id, const int64_t* alias, + const int* kind, int n_aggs, bool plain) { + if (!plain) return -1; + ray_group_emit_filter_t ef = ray_group_emit_filter_active(); + if (!ef.enabled || ef.top_count_take > 0 || ef.min_count_exclusive <= 0) return -1; + if (ef.agg_op != 0 && ef.agg_op != OP_COUNT) return -1; + /* the filter names its output by its index among the select's + * aggregate outputs, counted as match_group_count_emit_filter counts */ + uint8_t ai = 0; + for (int64_t i = 0; i + 1 < dict_n; i += 2) { + int64_t kid = dict_elems[i]->i64; + if (kid == from_id || kid == where_id || kid == by_id || + kid == take_id || kid == asc_id || kid == desc_id) + continue; + if (!is_group_dag_agg_expr(dict_elems[i + 1], NULL)) continue; + if (ai == ef.agg_index) { + for (int a = 0; a < n_aggs; a++) + if (alias[a] == kid) return kind[a] == DKV_COUNT ? ef.min_count_exclusive : -1; + return -1; + } + ai++; + } + return -1; +} + +/* The output of K groups: kv, their key column (consumed), then the + * aggregates as written — per output row o, cnt[o] rows, nn[o] of them not + * null, lenw[o] the length-weighted count, mnpos[o] / mxpos[o] the position + * of the min / max value in C's domain (<= 0: none). NULL on failure. */ +static ray_t* dkv_emit(ray_t* by_expr, const int64_t* alias, const int* kind, int n_aggs, + ray_t* Hc, ray_t* kv, int64_t K, const int64_t* cnt, const int64_t* nn, + const int64_t* lenw, const int64_t* mnpos, const int64_t* mxpos) { + ray_t* cols[DKV_MAX_AGGS + 1]; + memset(cols, 0, sizeof(cols)); + cols[0] = kv; + bool ok = true; + for (int a = 0; a < n_aggs && ok; a++) { + int k = kind[a]; + ray_t* v; + if (k == DKV_MIN || k == DKV_MAX) v = ray_sym_vec_new(Hc->attrs & RAY_SYM_W_MASK, K); + else v = ray_vec_new(k == DKV_AVG_LEN ? RAY_F64 : RAY_I64, K); + if (!v || RAY_IS_ERR(v)) { if (v) ray_error_free(v); ok = false; break; } + v->len = K; + cols[a + 1] = v; + if (k == DKV_MIN || k == DKV_MAX) ray_sym_vec_adopt_domain(v, Hc); + bool nulls = false; + for (int64_t o = 0; o < K; o++) { + if (k == DKV_COUNT) { + ((int64_t*)ray_data(v))[o] = cnt[o]; + } else if (k == DKV_SUM_LEN) { + ((int64_t*)ray_data(v))[o] = lenw[o]; + } else if (k == DKV_AVG_LEN) { + double d = nn[o] ? ray_f64_fin((double)lenw[o] / (double)nn[o]) : NULL_F64; + if (d != d) nulls = true; + ((double*)ray_data(v))[o] = d; + } else { + int64_t pos = k == DKV_MIN ? mnpos[o] : mxpos[o]; + if (pos <= 0) { pos = 0; nulls = true; } + ray_write_sym(ray_data(v), o, (uint64_t)pos, RAY_SYM, v->attrs); + } + } + if (nulls) v->attrs |= RAY_ATTR_HAS_NULLS; + } + ray_t* O = NULL; + if (ok) { + /* the key column is named as the row path names a computed key */ + int64_t kname = derived_key_name(by_expr); + for (int a = 0; a < n_aggs; a++) + if (alias[a] == kname) { kname = ray_sym_intern("key", 3); break; } + O = ray_table_new(n_aggs + 1); + if (O && !RAY_IS_ERR(O)) O = ray_table_add_col(O, kname, cols[0]); + for (int a = 0; a < n_aggs && O && !RAY_IS_ERR(O); a++) + O = ray_table_add_col(O, alias[a], cols[a + 1]); + if (O && RAY_IS_ERR(O)) { ray_error_free(O); O = NULL; } + } + for (int a = 0; a <= n_aggs; a++) if (cols[a]) ray_release(cols[a]); + if (!ok || !O) { if (O) ray_release(O); return NULL; } + return O; +} + +/* ---- the derived-key grouping under a having cut, in two passes --------- + * With a count cut armed (dkv_having_count: only the groups of more than N + * rows are kept) at most rows / (N + 1) groups survive, while dkh_build + * holds every group's key bytes and aggregates — hundreds of MB over a + * URL-sized vocabulary — to keep a few dozen. So: + * pass A: every value's key and its 64-bit hash; the row counts summed by + * hash alone (one 16-byte slot per hash: the hash, the count and the + * first value — no key bytes, no other aggregate), in the partitioned + * chunk structure of dkh_build. Per value, the low 32 bits of its + * key's hash and, when the key is the per-value program's view of the + * value, where in the value it lies (dk2_sc_of: in the high half of the + * value's row count when H is ours alone, else in an array); + * candidates: the hashes whose count passes the cut. A key's count is at + * most its hash's, so no kept group is missed; + * pass B: the key of each candidate's first value, copied out, makes a + * group of its own. Then only the values whose low 32 bits are a + * candidate's are read again, their keys taken off their bytes by the + * slice (the program runs again only for a chunk with a value that + * has none, the chunk DAG for every chunk): a value whose key's bytes + * equal a group's adds to that group's exact aggregates (on the + * workers, an accumulator set per task). A value whose key is no + * group's (another key under a candidate's hash, or under its low 32 + * bits only) is marked, and the marked values are grouped afterwards on + * the calling thread, exactly, making the groups they need; + * the cut again, over the exact counts: every key past it is under a + * candidate hash, so it has a group, and every group's count is exact. + * The answer is dkh_build's: the kept groups ordered by their first value + * in C's position order (the smallest position among their values), the + * empty key first; min / max by bytes; the null value counted, not + * measured. */ +#define DK2_MAX_CAND ((int64_t)1 << 18) /* groups a cut may let through */ +#define DK2_STAGE_BYTES ((size_t)16 << 20) /* pass A tables moved per round */ +#ifdef DEBUG +static int64_t g_dk2_stats[5]; +/* Test seam: runs of the two-pass grouping, then of the last run the + * groups it emitted, its candidate hashes, the groups made for marked + * values, and whether the key slices went into H's counts. */ +void ray_derived_key_two_pass_stats_for_test(int64_t out[5]) { + memcpy(out, g_dk2_stats, sizeof(g_dk2_stats)); +} +#endif + +typedef struct { uint64_t h; uint32_t cnt; uint32_t f1; } dk2_slot_t; /* f1: first value + 1, 0 = empty */ +typedef struct { uint64_t h; uint32_t k; uint32_t i; } dk2_item_t; /* hash, rows, chunk-relative value */ +typedef struct { + dk2_slot_t* t; int64_t cap, ng; ray_t* hdr; + dk2_slot_t* nt; int64_t ncap; ray_t* nhdr; /* staged by the calling thread */ + int64_t cur, end; + int full; /* the task stopped for room */ +} dk2_part_t; +typedef struct { + int64_t cnt, lenw; + int64_t fpos; /* smallest position among the values */ + int64_t mn, mx; /* positions of the min / max value, -1 */ + const char* mnp; const char* mxp; + uint32_t mnl, mxl; +} dk2_acc_t; +typedef struct { uint64_t h, koff; uint32_t klen, pad; dk2_acc_t a; } dk2_grp_t; +typedef struct { uint32_t g1, h32; } dk2_ts_t; /* group + 1, its low 32 bits */ + +typedef struct { + /* inputs */ + ray_t* by_expr; + int64_t col; + const void* dv; + uint8_t dattrs; + struct ray_sym_domain_s* dom; + const ray_sym_domain_raw_t* raw; + int64_t du; + int64_t* hn; /* rows per value in the low 32 bits */ + uint32_t* h32; /* the values' low 32 hash bits */ + uint32_t* sc; /* the values' key slices (dk2_sc_of); NULL: hn's high half */ + atomic_int n_none; /* selected values of the chunk without a slice */ + const char* lit_p[DKP_MAX_INS]; /* the program's string literals */ + uint32_t lit_l[DKP_MAX_INS]; + int nlit; + int64_t having; + bool want_lenw, want_mn, want_mx; + const dkp_prog_t* prog; + dkp_reg_t* regs; + /* chunk state */ + int64_t lo, n, nt, m, at; + int mode; /* pass B selection: 0 a candidate's low bits, 1 marked */ + const char** sp; uint32_t* sl; + const char** kp; uint32_t* kl; uint64_t* kh; + dk2_item_t* items; + const char** wsp; uint32_t* wsl; uint32_t* wix; /* the selected values */ + uint8_t* want; + int64_t* tcnt; /* [nt][DKH_NPART] counts, then cursors */ + /* pass A */ + dk2_part_t part[DKH_NPART]; + /* pass B: the groups, their table (by low 32 bits) and key bytes */ + dk2_grp_t* grp; int64_t ng, gcap; ray_t* grp_hdr; + dk2_ts_t* tab; int64_t tcap; ray_t* tab_hdr; + char* kb; uint64_t kbn, kbcap; ray_t* kb_hdr; + int64_t ng0, nacc; + dk2_acc_t* acc; /* [task][ng0] */ + uint64_t* unres; /* per value: marked */ + atomic_int n_unres; + int64_t null_g, null_cnt; + dkh_zr_t zr; /* min / max of a compressed vocabulary, by position */ + const dkh_zr_t* zp; +} dk2_t; + +static inline uint32_t dk2_sc(const dk2_t* c, int64_t v) { + return c->sc ? c->sc[v] : (uint32_t)((uint64_t)c->hn[v] >> 32); +} +static inline int64_t dk2_cnt(const dk2_t* c, int64_t v) { return (int64_t)(uint32_t)c->hn[v]; } + +/* Where a value's key lies, so pass B reads it back without running the + * key again: off << 20 | length when the key's bytes are the value's bytes + * at off (off < DK2_SC_LIT) — a view the program returned, or the DAG's + * key found in the value —, DK2_SC_LIT << 20 | i for the program's string + * literal i, DK2_SC_NONE for any other key (whose value runs the key + * again). The bytes are compared or the pointer is the value's own, so a + * slice gives the key's bytes exactly. */ +#define DK2_SC_NONE UINT32_MAX +#define DK2_SC_LIT 4095u +#define DK2_SC_LEN (((uint32_t)1 << 20) - 1) +static inline uint32_t dk2_sc_of(const dk2_t* c, const char* v, uint32_t vl, const char* k, uint32_t kl) { + if (kl == 0) return 0; + if (kl >= DK2_SC_LEN) return DK2_SC_NONE; + uintptr_t vp = (uintptr_t)v, kp = (uintptr_t)k; + if (kp >= vp && kp + kl <= vp + vl && kp - vp < DK2_SC_LIT) + return (uint32_t)((kp - vp) << 20 | kl); + if (c->prog) { + for (int i = 0; i < c->nlit; i++) + if (c->lit_p[i] == k && c->lit_l[i] == kl) return DK2_SC_LIT << 20 | (uint32_t)i; + return DK2_SC_NONE; + } + if (kl > vl) return DK2_SC_NONE; + size_t lim = (size_t)vl < (size_t)DK2_SC_LIT - 1 + kl ? (size_t)vl : (size_t)DK2_SC_LIT - 1 + kl; + int64_t off = memcmp(v, k, kl) == 0 ? 0 : dkp_find_literal(v, lim, k, kl); + if (off == NULL_I64 || off < 0 || off >= (int64_t)DK2_SC_LIT) return DK2_SC_NONE; + return (uint32_t)((uint64_t)off << 20 | kl); +} + +/* The key bytes of slice sc (not DK2_SC_NONE) of value bytes v. */ +static inline const char* dk2_sc_key(const dk2_t* c, uint32_t sc, const char* v, uint32_t* kl) { + uint32_t off = sc >> 20, len = sc & DK2_SC_LEN; + if (off < DK2_SC_LIT) { *kl = len; return v + off; } + *kl = c->lit_l[len]; + return c->lit_p[len]; +} + +/* pass A slot: any table size (no power of two to double into) */ +static inline uint64_t dk2_aslot(uint64_t h, int64_t cap) { + return (uint64_t)(((unsigned __int128)(h * 0x9E3779B97F4A7C15ull) * (uint64_t)cap) >> 64); +} + +static void dk2_count_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t* k = c->tcnt + t * DKH_NPART; + memset(k, 0, DKH_NPART * sizeof(int64_t)); + int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt; + for (int64_t i = lo; i < hi; i++) k[dkh_part_of(c->kh[i])]++; + } +} + +static void dk2_scatter_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t* k = c->tcnt + t * DKH_NPART; + int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt; + for (int64_t i = lo; i < hi; i++) { + uint64_t h = c->kh[i]; + int64_t v = c->lo + i; + uint32_t cnt = (uint32_t)c->hn[v]; + dk2_item_t* it = &c->items[k[dkh_part_of(h)]++]; + it->h = h; + it->k = cnt; + it->i = (uint32_t)i; + c->h32[v] = (uint32_t)h; + uint32_t sc = dk2_sc_of(c, c->sp[i], c->sl[i], c->kp[i], c->kl[i]); + if (c->sc) c->sc[v] = sc; + else c->hn[v] = (int64_t)((uint64_t)sc << 32 | cnt); + } + } +} + +static void dk2_group_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + dk2_part_t* P = &c->part[p]; + if (P->cur >= P->end) continue; + dk2_slot_t* t = P->t; + const uint64_t cap = (uint64_t)P->cap; + int64_t ng = P->ng, cur = P->cur, end = P->end; + const dk2_item_t* items = c->items; + for (; cur < end; cur++) { + const dk2_item_t* it = &items[cur]; + uint64_t h = it->h; + uint64_t s = dk2_aslot(h, P->cap); + while (t[s].f1 && t[s].h != h) if (++s == cap) s = 0; + if (!t[s].f1) { + if ((uint64_t)(ng + 1) * 5 > cap * 4) { P->full = 1; break; } + t[s].h = h; + t[s].cnt = 0; + t[s].f1 = (uint32_t)(c->lo + it->i + 1); + ng++; + } + t[s].cnt += it->k; + } + P->ng = ng; + P->cur = cur; + } +} + +/* Moves the staged partitions' slots into their new tables. */ +static void dk2_move_fn(void* vctx, uint32_t wid, int64_t p0, int64_t p1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t p = p0; p < p1; p++) { + dk2_part_t* P = &c->part[p]; + if (!P->nt) continue; + memset(P->nt, 0, (size_t)P->ncap * sizeof(dk2_slot_t)); + const uint64_t ncap = (uint64_t)P->ncap; + for (int64_t s = 0; s < P->cap; s++) { + if (!P->t[s].f1) continue; + uint64_t d = dk2_aslot(P->t[s].h, P->ncap); + while (P->nt[d].f1) if (++d == ncap) d = 0; + P->nt[d] = P->t[s]; + } + } +} + +/* Sizes every partition whose pending items might not fit at load 4/5: + * the share of pending values expected to make new hashes is the share so + * far (a quarter before the first chunk) with half again for slack, and a + * table grows to load 3/5 of that, by half at least. The tables move a + * batch of DK2_STAGE_BYTES at a time, so old and new tables coexist for + * that batch only. False on OOM or interrupt. */ +static bool dk2_grow(dk2_t* c, bool par) { + ray_pool_t* pool = ray_pool_get(); + int64_t ng_all = 0; + for (int p = 0; p < DKH_NPART; p++) ng_all += c->part[p].ng; + double share = c->lo > 0 ? 1.5 * (double)ng_all / (double)c->lo : 0.25; + if (share > 1.0) share = 1.0; + bool ok = true; + size_t staged = 0; + for (int p = 0; p < DKH_NPART && ok; p++) { + dk2_part_t* P = &c->part[p]; + int64_t pend = P->end - P->cur; + if (pend > 0) { + int64_t need = P->ng + (int64_t)((double)pend * share) + 16; + if (need > P->ng + pend) need = P->ng + pend; + if (need < P->ng + 1) need = P->ng + 1; + if (need * 5 > P->cap * 4) { + int64_t ncap = need * 5 / 3; + if (ncap < P->cap + P->cap / 2) ncap = P->cap + P->cap / 2; + ncap += 64; + P->nt = (dk2_slot_t*)scratch_alloc(&P->nhdr, (size_t)ncap * sizeof(dk2_slot_t)); + if (!P->nt) { P->nhdr = NULL; ok = false; break; } + P->ncap = ncap; + staged += (size_t)ncap * sizeof(dk2_slot_t); + } + } + if (staged && (staged >= DK2_STAGE_BYTES || p == DKH_NPART - 1)) { + if (par) ray_pool_dispatch_n(pool, dk2_move_fn, c, DKH_NPART); + else dk2_move_fn(c, 0, 0, DKH_NPART); + for (int q = 0; q <= p; q++) { + dk2_part_t* Q = &c->part[q]; + if (!Q->nt) continue; + scratch_free(Q->hdr); + Q->t = Q->nt; Q->cap = Q->ncap; Q->hdr = Q->nhdr; + Q->nt = NULL; Q->ncap = 0; Q->nhdr = NULL; + } + staged = 0; + } + } + for (int p = 0; p < DKH_NPART; p++) { + dk2_part_t* P = &c->part[p]; + if (P->nt) { scratch_free(P->nhdr); P->nt = NULL; P->ncap = 0; P->nhdr = NULL; } + P->full = 0; + } + return ok && !ray_interrupted(); +} + +/* pass B table: slot of a hash's low 32 bits */ +static inline uint64_t dk2_tslot(uint32_t h32, int64_t tcap) { + return (((uint64_t)h32 * 0x9E3779B97F4A7C15ull) >> 32) & (uint64_t)(tcap - 1); +} + +/* Is h32 the low 32 bits of a group's hash? */ +static inline bool dk2_want(const dk2_t* c, uint32_t h32) { + const uint64_t mask = (uint64_t)c->tcap - 1; + for (uint64_t s = dk2_tslot(h32, c->tcap); c->tab[s].g1; s = (s + 1) & mask) + if (c->tab[s].h32 == h32) return true; + return false; +} + +/* The group of key (p, l), whose hash has low 32 bits h32, or -1: equal + * bytes are the same key, so the low bits pick the slots to compare. */ +static inline int64_t dk2_find(const dk2_t* c, uint32_t h32, const char* p, uint32_t l) { + const uint64_t mask = (uint64_t)c->tcap - 1; + for (uint64_t s = dk2_tslot(h32, c->tcap); c->tab[s].g1; s = (s + 1) & mask) { + if (c->tab[s].h32 != h32) continue; + const dk2_grp_t* g = &c->grp[c->tab[s].g1 - 1]; + if (g->klen == l && (l == 0 || memcmp(c->kb + g->koff, p, l) == 0)) return (int64_t)c->tab[s].g1 - 1; + } + return -1; +} + +static inline void dk2_acc_init(dk2_acc_t* a) { + memset(a, 0, sizeof(*a)); + a->fpos = INT64_MAX; + a->mn = -1; + a->mx = -1; +} + +/* A new group for key (p, l) with hash h (calling thread only); -1 on OOM. */ +static int64_t dk2_insert(dk2_t* c, uint64_t h, const char* p, uint32_t l) { + if ((c->ng + 1) * 2 > c->tcap) { + int64_t cap = c->tcap ? c->tcap * 2 : 64; + while ((c->ng + 1) * 2 > cap) cap *= 2; + ray_t* hdr = NULL; + dk2_ts_t* tab = (dk2_ts_t*)scratch_calloc(&hdr, (size_t)cap * sizeof(dk2_ts_t)); + if (!tab) return -1; + scratch_free(c->tab_hdr); + c->tab = tab; c->tcap = cap; c->tab_hdr = hdr; + for (int64_t g = 0; g < c->ng; g++) { + uint64_t s = dk2_tslot((uint32_t)c->grp[g].h, cap); + while (tab[s].g1) s = (s + 1) & (uint64_t)(cap - 1); + tab[s].g1 = (uint32_t)(g + 1); + tab[s].h32 = (uint32_t)c->grp[g].h; + } + } + if (c->ng >= c->gcap) { + int64_t cap = c->gcap ? c->gcap * 2 : 64; + dk2_grp_t* g = (dk2_grp_t*)scratch_realloc(&c->grp_hdr, (size_t)c->ng * sizeof(dk2_grp_t), + (size_t)cap * sizeof(dk2_grp_t)); + if (!g) return -1; + c->grp = g; c->gcap = cap; + } + if (c->kbn + l > c->kbcap) { + uint64_t cap = c->kbcap * 2; + if (cap < c->kbn + l) cap = c->kbn + l; + if (cap < 1024) cap = 1024; + char* kb = (char*)scratch_realloc(&c->kb_hdr, (size_t)c->kbn, (size_t)cap); + if (!kb) return -1; + c->kb = kb; c->kbcap = cap; + } + int64_t g = c->ng++; + dk2_grp_t* G = &c->grp[g]; + G->h = h; G->koff = c->kbn; G->klen = l; G->pad = 0; + dk2_acc_init(&G->a); + if (l) memcpy(c->kb + c->kbn, p, l); + c->kbn += l; + uint64_t s = dk2_tslot((uint32_t)h, c->tcap); + while (c->tab[s].g1) s = (s + 1) & (uint64_t)(c->tcap - 1); + c->tab[s].g1 = (uint32_t)(g + 1); + c->tab[s].h32 = (uint32_t)h; + return g; +} + +/* Value v (bytes p, l) into accumulator a of group g: rows always, the + * null value's rows noted, the others' lengths and bytes measured. */ +static inline void dk2_add(dk2_t* c, dk2_acc_t* a, int64_t g, int64_t v, const char* p, uint32_t l) { + int64_t k = dk2_cnt(c, v); + int64_t pos = ray_read_sym(c->dv, v, RAY_SYM, c->dattrs); + a->cnt += k; + if (pos < a->fpos) a->fpos = pos; + if (pos <= 0) { c->null_g = g; c->null_cnt = k; return; } /* the one null value */ + if (c->want_lenw) a->lenw += k * (int64_t)l; + if (c->want_mn) dkh_minmax(c->zp, &a->mn, &a->mnp, &a->mnl, pos, p, l, false); + if (c->want_mx) dkh_minmax(c->zp, &a->mx, &a->mxp, &a->mxl, pos, p, l, true); +} + +static void dk2_acc_merge(const dkh_zr_t* z, dk2_acc_t* a, const dk2_acc_t* b) { + a->cnt += b->cnt; + a->lenw += b->lenw; + if (b->fpos < a->fpos) a->fpos = b->fpos; + if (b->mn >= 0) dkh_minmax(z, &a->mn, &a->mnp, &a->mnl, b->mn, b->mnp, b->mnl, false); + if (b->mx >= 0) dkh_minmax(z, &a->mx, &a->mxp, &a->mxl, b->mx, b->mxp, b->mxl, true); +} + +/* pass B selection: per task, the chunk's values it takes and their count */ +static void dk2_mark_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt, k = 0; + for (int64_t i = lo; i < hi; i++) { + int64_t v = c->lo + i; + bool w = c->mode ? ((c->unres[v >> 6] >> (v & 63)) & 1) != 0 : dk2_want(c, c->h32[v]); + c->want[i] = w; + k += w; + } + c->tcnt[t] = k; + } +} + +static void dk2_compact_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + int64_t lo = c->n * t / c->nt, hi = c->n * (t + 1) / c->nt, j = c->tcnt[t]; + int none = 0; + for (int64_t i = lo; i < hi; i++) { + if (!c->want[i]) continue; + c->wsp[j] = c->sp[i]; + c->wsl[j] = c->sl[i]; + c->wix[j] = (uint32_t)i; + /* the key off the value, where pass A found it */ + uint32_t sc = dk2_sc(c, c->lo + i); + if (sc == DK2_SC_NONE) { c->kl[j] = UINT32_MAX; none++; } + else c->kp[j] = dk2_sc_key(c, sc, c->sp[i], &c->kl[j]); + j++; + } + if (none) atomic_fetch_add_explicit(&c->n_none, none, memory_order_relaxed); + } +} + +/* pass B on the workers: each task its share of the selected values, into + * its own accumulator set. */ +static void dk2_acc_fn(void* vctx, uint32_t wid, int64_t t0, int64_t t1) { + (void)wid; + dk2_t* c = (dk2_t*)vctx; + for (int64_t t = t0; t < t1; t++) { + dk2_acc_t* A = c->acc + t * c->ng0; + int64_t lo = c->m * t / c->at, hi = c->m * (t + 1) / c->at; + int marked = 0; + for (int64_t j = lo; j < hi; j++) { + int64_t v = c->lo + c->wix[j]; + int64_t g = dk2_find(c, c->h32[v], c->kp[j], c->kl[j]); + if (g < 0) { + /* another key under a candidate's low 32 bits */ + atomic_fetch_or_explicit((_Atomic(uint64_t)*)&c->unres[v >> 6], + (uint64_t)1 << (v & 63), memory_order_relaxed); + marked++; + continue; + } + dk2_add(c, &A[g], g, v, c->wsp[j], c->wsl[j]); + } + if (marked) atomic_fetch_add_explicit(&c->n_unres, marked, memory_order_relaxed); + } +} + +/* The selected values of chunk [lo, lo + n) (c->mode): marked, their bytes + * read, compacted (c->m of them) and their keys taken off the values by + * their slices; the keys of the values without one computed again (*kc as + * dkh_keys_of leaves it, *khdr the buffers of that). */ +static bool dk2_select(dk2_t* c, int64_t lo, int64_t n, int64_t nt_max, ray_t** kc, ray_t** khdr) { + *kc = NULL; + *khdr = NULL; + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + c->lo = lo; c->n = n; + int64_t nt = 1; + if (par) { + nt = nt_max; + if (nt > n / 4096) nt = n / 4096; + if (nt < 1) nt = 1; + } + c->nt = nt; + if (nt > 1) ray_pool_dispatch_n(pool, dk2_mark_fn, c, (uint32_t)nt); + else dk2_mark_fn(c, 0, 0, 1); + int64_t run = 0; + for (int64_t t = 0; t < nt; t++) { int64_t k = c->tcnt[t]; c->tcnt[t] = run; run += k; } + c->m = run; + if (run == 0) return true; + if (!dk_chunk_views(c->dv, c->dattrs, lo, n, c->raw, c->dom, c->want, c->sp, c->sl, true)) return false; + atomic_store_explicit(&c->n_none, 0, memory_order_relaxed); + if (nt > 1) ray_pool_dispatch_n(pool, dk2_compact_fn, c, (uint32_t)nt); + else dk2_compact_fn(c, 0, 0, 1); + int64_t np = atomic_load_explicit(&c->n_none, memory_order_relaxed); + if (np == 0) return true; + /* the values without a slice: their keys again, then into place */ + size_t per = 2 * sizeof(const char*) + 3 * sizeof(uint32_t) + sizeof(uint64_t); + char* m = (char*)scratch_alloc(khdr, (size_t)np * per); + if (!m) return false; + const char** psp = (const char**)m; m += (size_t)np * sizeof(const char*); + const char** pkp = (const char**)m; m += (size_t)np * sizeof(const char*); + uint64_t* pkh = (uint64_t*)m; m += (size_t)np * sizeof(uint64_t); + uint32_t* psl = (uint32_t*)m; m += (size_t)np * sizeof(uint32_t); + uint32_t* pkl = (uint32_t*)m; m += (size_t)np * sizeof(uint32_t); + uint32_t* pix = (uint32_t*)m; + int64_t q = 0; + for (int64_t j = 0; j < run && q < np; j++) + if (c->kl[j] == UINT32_MAX) { psp[q] = c->wsp[j]; psl[q] = c->wsl[j]; pix[q] = (uint32_t)j; q++; } + if (q != np) return false; + if (!dkh_keys_of(c->by_expr, c->col, c->prog, c->regs, psp, psl, np, pkp, pkl, pkh, kc)) return false; + for (int64_t k = 0; k < np; k++) { c->kp[pix[k]] = pkp[k]; c->kl[pix[k]] = pkl[k]; } + return true; +} + +typedef struct { int64_t key; int64_t g; } dk2_ord_t; +static int dk2_ord_cmp(const void* a, const void* b) { + int64_t x = ((const dk2_ord_t*)a)->key, y = ((const dk2_ord_t*)b)->key; + return (x > y) - (x < y); +} + +/* The grouping of H's du values (Hc, counts Hn) by key under the cut + * `having`, and its output (see above); NULL on failure. pack: H and Hn + * are ours alone, so Hn's high halves may hold the key slices (every count + * fits 32 bits: the caller checked the rows). */ +static ray_t* dk2_run(ray_t* by_expr, int64_t col, ray_t* Hc, ray_t* Hn, bool pack, + struct ray_sym_domain_s* dom, const ray_sym_domain_raw_t* raw, + int64_t having, const int64_t* alias, const int* kind, int n_aggs) { + int64_t du = ray_len(Hc); + if (du <= 0 || du >= INT32_MAX || having <= 0) return NULL; + ray_pool_t* pool = ray_pool_get(); + uint32_t nwork = ray_pool_par_dispatch_ok(pool, 2, 1) ? ray_pool_total_workers(pool) : 1; + ray_t *chdr = NULL, *prog_hdr = NULL, *regs_hdr = NULL, *mem_hdr = NULL, *tm_hdr = NULL; + ray_t *h32_hdr = NULL, *cand_hdr = NULL, *rep_hdr = NULL, *acc_hdr = NULL, *un_hdr = NULL; + ray_t *ord_hdr = NULL, *out_hdr = NULL, *sc_hdr = NULL, *khdr = NULL; + ray_t* kc = NULL; + ray_t* O = NULL; + dk2_t* c = (dk2_t*)scratch_calloc(&chdr, sizeof(dk2_t)); + if (!c) return NULL; + c->by_expr = by_expr; c->col = col; + c->dv = ray_data(Hc); c->dattrs = Hc->attrs; + c->dom = dom; c->raw = raw; c->du = du; + c->zp = dkh_zr_set(&c->zr, raw, dom, NULL, 0); + c->hn = (int64_t*)ray_data(Hn); + c->having = having; + c->null_g = -1; + for (int a = 0; a < n_aggs; a++) { + if (kind[a] == DKV_SUM_LEN || kind[a] == DKV_AVG_LEN) c->want_lenw = true; + if (kind[a] == DKV_MIN) c->want_mn = true; + if (kind[a] == DKV_MAX) c->want_mx = true; + } + atomic_store_explicit(&c->n_unres, 0, memory_order_relaxed); + + dkp_prog_t* prog = (dkp_prog_t*)scratch_alloc(&prog_hdr, sizeof(dkp_prog_t)); + if (!prog) goto done; + bool use_prog = dkp_build(prog, by_expr, col); + if (use_prog) { + c->prog = prog; + c->regs = (dkp_reg_t*)scratch_alloc(®s_hdr, (size_t)nwork * (size_t)prog->n * DKP_BATCH * sizeof(dkp_reg_t)); + if (!c->regs) goto done; + } + const int64_t chunk = derived_key_chunk_rows(!use_prog); + int64_t cn = du < chunk ? du : chunk; + int64_t nt_max = (int64_t)nwork * 4; + { + size_t per = 2 * sizeof(const char*) + 2 * sizeof(uint32_t) + sizeof(uint64_t) + + sizeof(dk2_item_t) + 1; + char* mem = (char*)scratch_alloc(&mem_hdr, (size_t)cn * per); + c->tcnt = (int64_t*)scratch_alloc(&tm_hdr, (size_t)nt_max * DKH_NPART * sizeof(int64_t)); + if (!mem || !c->tcnt) goto done; + c->items = (dk2_item_t*)mem; + c->wsp = (const char**)mem; /* pass B: the item array again */ + c->wsl = (uint32_t*)(mem + (size_t)cn * sizeof(const char*)); + c->wix = (uint32_t*)(mem + (size_t)cn * (sizeof(const char*) + sizeof(uint32_t))); + mem += (size_t)cn * sizeof(dk2_item_t); + c->sp = (const char**)mem; mem += (size_t)cn * sizeof(const char*); + c->kp = (const char**)mem; mem += (size_t)cn * sizeof(const char*); + c->kh = (uint64_t*)mem; mem += (size_t)cn * sizeof(uint64_t); + c->sl = (uint32_t*)mem; mem += (size_t)cn * sizeof(uint32_t); + c->kl = (uint32_t*)mem; mem += (size_t)cn * sizeof(uint32_t); + c->want = (uint8_t*)mem; + } + c->h32 = (uint32_t*)scratch_alloc(&h32_hdr, (size_t)du * sizeof(uint32_t)); + if (!c->h32) goto done; + if (!pack) { + c->sc = (uint32_t*)scratch_alloc(&sc_hdr, (size_t)du * sizeof(uint32_t)); + if (!c->sc) goto done; + } + if (use_prog) + for (int k = 0; k < prog->n; k++) + if (prog->ins[k].op == DKO_LSTR) { + c->lit_p[c->nlit] = prog->ins[k].sp; + c->lit_l[c->nlit] = prog->ins[k].sl; + c->nlit++; + } + + /* pass A: rows by hash */ + for (int64_t lo = 0; lo < du; lo += chunk) { + if (ray_interrupted()) goto done; + int64_t n = du - lo < chunk ? du - lo : chunk; + c->lo = lo; c->n = n; + bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); + if (!dk_chunk_views(c->dv, c->dattrs, lo, n, raw, dom, NULL, c->sp, c->sl, true)) goto done; + if (!dkh_keys_of(by_expr, col, c->prog, c->regs, c->sp, c->sl, n, c->kp, c->kl, c->kh, &kc)) goto done; + int64_t nt = 1; + if (par) { + nt = nt_max; + if (nt > n / 4096) nt = n / 4096; + if (nt < 1) nt = 1; + } + c->nt = nt; + if (nt > 1) ray_pool_dispatch_n(pool, dk2_count_fn, c, (uint32_t)nt); + else dk2_count_fn(c, 0, 0, 1); + int64_t run = 0; + for (int p = 0; p < DKH_NPART; p++) { + dk2_part_t* P = &c->part[p]; + P->cur = run; + for (int64_t t = 0; t < nt; t++) { + int64_t k = c->tcnt[t * DKH_NPART + p]; + c->tcnt[t * DKH_NPART + p] = run; + run += k; + } + P->end = run; + } + if (nt > 1) ray_pool_dispatch_n(pool, dk2_scatter_fn, c, (uint32_t)nt); + else dk2_scatter_fn(c, 0, 0, 1); + if (kc) { ray_release(kc); kc = NULL; } /* the slices are taken: hashes only from here */ + bool ok = dk2_grow(c, par); + while (ok) { + if (par) ray_pool_dispatch_n(pool, dk2_group_fn, c, DKH_NPART); + else dk2_group_fn(c, 0, 0, DKH_NPART); + if (ray_interrupted()) { ok = false; break; } + bool pending = false; + for (int p = 0; p < DKH_NPART; p++) if (c->part[p].cur < c->part[p].end) pending = true; + if (!pending) break; + ok = dk2_grow(c, par); + } + if (!ok) goto done; + } + ray_profile_tick("derived key: pass A, rows by hash"); + + /* the candidates: hash and first value of every hash past the cut */ + int64_t NC = 0; + for (int p = 0; p < DKH_NPART; p++) { + const dk2_part_t* P = &c->part[p]; + for (int64_t s = 0; s < P->cap; s++) + if (P->t[s].f1 && (int64_t)P->t[s].cnt > having) NC++; + } + uint64_t* ch = NULL; + uint32_t* cv = NULL; + if (NC > 0) { + char* m = (char*)scratch_alloc(&cand_hdr, (size_t)NC * (sizeof(uint64_t) + sizeof(uint32_t))); + if (!m) goto done; + ch = (uint64_t*)m; + cv = (uint32_t*)(m + (size_t)NC * sizeof(uint64_t)); + int64_t j = 0; + for (int p = 0; p < DKH_NPART; p++) { + const dk2_part_t* P = &c->part[p]; + for (int64_t s = 0; s < P->cap; s++) + if (P->t[s].f1 && (int64_t)P->t[s].cnt > having) { ch[j] = P->t[s].h; cv[j] = P->t[s].f1 - 1; j++; } + } + } + for (int p = 0; p < DKH_NPART; p++) { + scratch_free(c->part[p].hdr); + c->part[p].hdr = NULL; c->part[p].t = NULL; c->part[p].cap = 0; + } + ray_profile_tick("derived key: candidates"); + + if (NC > 0) { + /* pass B: a group per candidate, keyed by its first value's key */ + char* m = (char*)scratch_alloc(&rep_hdr, (size_t)NC * (2 * sizeof(const char*) + 2 * sizeof(uint32_t) + sizeof(uint64_t))); + if (!m) goto done; + const char** rsp = (const char**)m; m += (size_t)NC * sizeof(const char*); + const char** rkp = (const char**)m; m += (size_t)NC * sizeof(const char*); + uint64_t* rkh = (uint64_t*)m; m += (size_t)NC * sizeof(uint64_t); + uint32_t* rsl = (uint32_t*)m; m += (size_t)NC * sizeof(uint32_t); + uint32_t* rkl = (uint32_t*)m; + for (int64_t j = 0; j < NC; j++) + if (!dk_chunk_views(c->dv, c->dattrs, cv[j], 1, raw, dom, NULL, &rsp[j], &rsl[j], j == 0)) goto done; + if (!dkh_keys_of(by_expr, col, c->prog, c->regs, rsp, rsl, NC, rkp, rkl, rkh, &kc)) goto done; + for (int64_t j = 0; j < NC; j++) { + /* the same program over the same bytes: the same hash */ + if (rkh[j] != ch[j] || dk2_insert(c, rkh[j], rkp[j], rkl[j]) != j) goto done; + } + if (kc) { ray_release(kc); kc = NULL; } + scratch_free(rep_hdr); rep_hdr = NULL; + scratch_free(cand_hdr); cand_hdr = NULL; + c->ng0 = NC; + c->nacc = nwork; + if (c->nacc * NC > DK2_MAX_CAND) c->nacc = DK2_MAX_CAND / NC; + if (c->nacc < 1) c->nacc = 1; + c->acc = (dk2_acc_t*)scratch_alloc(&acc_hdr, (size_t)c->nacc * (size_t)NC * sizeof(dk2_acc_t)); + c->unres = (uint64_t*)scratch_calloc(&un_hdr, (size_t)((du + 63) / 64) * sizeof(uint64_t)); + if (!c->acc || !c->unres) goto done; + for (int64_t s = 0; s < c->nacc * NC; s++) dk2_acc_init(&c->acc[s]); + + /* the values under a candidate's low 32 bits, on the workers */ + c->mode = 0; + for (int64_t lo = 0; lo < du; lo += chunk) { + if (ray_interrupted()) goto done; + int64_t n = du - lo < chunk ? du - lo : chunk; + if (!dk2_select(c, lo, n, nt_max, &kc, &khdr)) goto done; + if (c->m > 0) { + bool par = ray_pool_par_dispatch_ok(pool, c->m, RAY_PARALLEL_THRESHOLD); + c->at = par ? c->nacc : 1; + if (c->at > 1) ray_pool_dispatch_n(pool, dk2_acc_fn, c, (uint32_t)c->at); + else dk2_acc_fn(c, 0, 0, 1); + } + if (kc) { ray_release(kc); kc = NULL; } + scratch_free(khdr); khdr = NULL; + } + for (int64_t g = 0; g < NC; g++) + for (int64_t t = 0; t < c->nacc; t++) dk2_acc_merge(c->zp, &c->grp[g].a, &c->acc[t * NC + g]); + scratch_free(acc_hdr); acc_hdr = NULL; c->acc = NULL; + ray_profile_tick("derived key: pass B, candidate keys"); + + /* the marked values: other keys under a candidate hash, grouped + * here exactly */ + if (atomic_load_explicit(&c->n_unres, memory_order_relaxed) > 0) { + c->mode = 1; + for (int64_t lo = 0; lo < du; lo += chunk) { + if (ray_interrupted()) goto done; + int64_t n = du - lo < chunk ? du - lo : chunk; + if (!dk2_select(c, lo, n, nt_max, &kc, &khdr)) goto done; + for (int64_t j = 0; j < c->m; j++) { + int64_t v = lo + c->wix[j]; + int64_t g = dk2_find(c, c->h32[v], c->kp[j], c->kl[j]); + if (g < 0) { + uint64_t h = dkh_hash(c->kp[j], c->kl[j]); + /* the same bytes: pass A's hash */ + if ((uint32_t)h != c->h32[v]) goto done; + g = dk2_insert(c, h, c->kp[j], c->kl[j]); + } + if (g < 0) goto done; + dk2_add(c, &c->grp[g].a, g, v, c->wsp[j], c->wsl[j]); + } + if (kc) { ray_release(kc); kc = NULL; } + scratch_free(khdr); khdr = NULL; + } + ray_profile_tick("derived key: pass B, colliding keys"); + } + } + + /* the cut over the exact counts; the kept groups by first value, the + * empty key first */ + { + int64_t K = 0; + for (int64_t g = 0; g < c->ng; g++) if (c->grp[g].a.cnt > having) K++; + dk2_ord_t* ord = (dk2_ord_t*)scratch_alloc(&ord_hdr, (size_t)(K ? K : 1) * sizeof(dk2_ord_t)); + size_t per = 5 * sizeof(int64_t) + sizeof(const char*) + sizeof(size_t) + sizeof(uint32_t); + char* m = (char*)scratch_alloc(&out_hdr, (size_t)(K ? K : 1) * per); + if (!ord || !m) goto done; + int64_t k = 0; + for (int64_t g = 0; g < c->ng; g++) { + if (c->grp[g].a.cnt <= having) continue; + ord[k].key = c->grp[g].klen == 0 ? -1 : c->grp[g].a.fpos; + ord[k].g = g; + k++; + } + if (K > 1) qsort(ord, (size_t)K, sizeof(dk2_ord_t), dk2_ord_cmp); + int64_t* ocnt = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + int64_t* onn = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + int64_t* olenw = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + int64_t* omn = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + int64_t* omx = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + const char** ks = (const char**)m; m += (size_t)K * sizeof(const char*); + size_t* kls = (size_t*)m; m += (size_t)K * sizeof(size_t); + uint32_t* kh32 = (uint32_t*)m; + for (int64_t o = 0; o < K; o++) { + const dk2_grp_t* G = &c->grp[ord[o].g]; + ocnt[o] = G->a.cnt; + onn[o] = G->a.cnt - (ord[o].g == c->null_g ? c->null_cnt : 0); + olenw[o] = G->a.lenw; + omn[o] = G->a.mn >= 0 ? G->a.mn : 0; + omx[o] = G->a.mx >= 0 ? G->a.mx : 0; + ks[o] = G->klen ? c->kb + G->koff : ""; /* no key bytes stored when every key is empty */ + kls[o] = G->klen; + kh32[o] = (uint32_t)ray_hash_bytes(ks[o], G->klen); + } + ray_t* kv = ray_vec_new(RAY_SYM, K); + if (!kv || RAY_IS_ERR(kv)) { if (kv) ray_error_free(kv); goto done; } + kv->len = K; + /* the key strings in a domain of the key vector's own (as + * derived_key_str_chunks) */ + struct ray_sym_domain_s* kdom = ray_sym_domain_new(); + if (!kdom) { ray_release(kv); goto done; } + kv->sym_domain = kdom; + if (K > 0 && !ray_sym_domain_intern_batch(kdom, K, ks, kls, kh32, (int64_t*)ray_data(kv))) { + ray_release(kv); goto done; + } + ray_profile_tick("derived key: key domain interned"); + O = dkv_emit(by_expr, alias, kind, n_aggs, Hc, kv, K, ocnt, onn, olenw, omn, omx); +#ifdef DEBUG + if (O) { + g_dk2_stats[0]++; + g_dk2_stats[1] = K; + g_dk2_stats[2] = c->ng0; + g_dk2_stats[3] = c->ng - c->ng0; + g_dk2_stats[4] = pack; + } +#endif + } +done: + if (kc) ray_release(kc); + scratch_free(khdr); + for (int p = 0; p < DKH_NPART; p++) { scratch_free(c->part[p].hdr); scratch_free(c->part[p].nhdr); } + scratch_free(c->grp_hdr); scratch_free(c->tab_hdr); scratch_free(c->kb_hdr); + scratch_free(ord_hdr); scratch_free(out_hdr); scratch_free(un_hdr); scratch_free(acc_hdr); + scratch_free(rep_hdr); scratch_free(cand_hdr); scratch_free(h32_hdr); scratch_free(sc_hdr); + scratch_free(tm_hdr); scratch_free(mem_hdr); scratch_free(regs_hdr); scratch_free(prog_hdr); + scratch_free(chdr); + return O; +} + static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_expr, ray_t** dict_elems, int64_t dict_n, int64_t from_id, int64_t by_id, int64_t where_id, @@ -5835,10 +9327,21 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex int64_t col = ref_syms[0]; int64_t bound[32]; if (!derived_key_expr_ok(by_expr, tbl, col, bound, 0)) return NULL; - ray_t* C = ray_table_get_col(tbl, col); int64_t nrows = ray_table_nrows(tbl); - if (!C || C->type != RAY_SYM || !ray_is_vec(C) || C->len != nrows || nrows < 65536) return NULL; - struct ray_sym_domain_s* dom = ray_sym_vec_domain(C); + /* A single-file encoded column answers type, rows and domain from its + * directory: decoding it here would hold the whole column in memory for + * a check, while the grouping below reads it by range. */ + struct ray_sym_domain_s* dom = NULL; + ray_t* E = ray_table_get_col_enc(tbl, col); + ray_enccol_t* e = E ? ray_enccol_of(E) : NULL; + if (e && e->kind == RAY_ENCCOL_SINGLE && e->type == RAY_SYM && e->dom) { + if (e->len != nrows || nrows < 65536) return NULL; + dom = e->dom; + } else { + ray_t* C = tbl_col_or_null(tbl, col); + if (!C || C->type != RAY_SYM || !ray_is_vec(C) || C->len != nrows || nrows < 65536) return NULL; + dom = ray_sym_vec_domain(C); + } if (!dom) return NULL; /* Every output is one of the decomposable aggregates over C; sort/take @@ -5869,216 +9372,249 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex } } - /* 1. the rows grouped by C itself: distinct values with their counts */ + /* 1. the rows grouped by C itself: distinct values with their counts. + * A filter that is a pure function of C alone (its only column, every + * head elementwise) passes or fails every row of a value together, so + * it runs over the distinct values after the grouping instead of over + * the rows before it: no row selection, one predicate per value. */ int64_t s_t = ray_sym_intern("__dkv_t", 7), s_cnt = ray_sym_intern("__dkv_cnt", 9); - int64_t s_s = ray_sym_intern("__dkv_s", 7), s_k = ray_sym_intern("__dkv_k", 7); - int64_t s_ref = ray_sym_intern("__dkv_ref", 9), s_nn = ray_sym_intern("__dkv_nn", 8); - int64_t s_lenw = ray_sym_intern("__dkv_lenw", 10); + bool where_on_values = false; + if (where_expr) { + int64_t wrefs[2], wbound[32]; + where_on_values = collect_col_refs(where_expr, tbl, wrefs, 2, 0) == 1 && wrefs[0] == col && + derived_key_expr_ok(where_expr, tbl, col, wbound, 0); + } ray_t* H = NULL; - { + for (int step = 0; step < (where_on_values ? 2 : 1); step++) { int64_t keys[4]; ray_t* vals[4]; int64_t n = 0; keys[n] = from_id; vals[n++] = ray_sym(s_t); - keys[n] = by_id; vals[n++] = ray_sym(col); - keys[n] = s_cnt; vals[n++] = dkv_call("count", ray_sym(col), NULL); - if (where_expr) { keys[n] = where_id; ray_retain(where_expr); vals[n++] = where_expr; } - for (int64_t i = 0; i < n; i++) if (!vals[i]) { for (int64_t j = 0; j < n; j++) if (vals[j]) ray_release(vals[j]); return NULL; } + if (step == 0) { + keys[n] = by_id; vals[n++] = ray_sym(col); + keys[n] = s_cnt; vals[n++] = dkv_call("count", ray_sym(col), NULL); + } + if (where_expr && (step == 1 || !where_on_values)) { + keys[n] = where_id; ray_retain(where_expr); vals[n++] = where_expr; + } + for (int64_t i = 0; i < n; i++) if (!vals[i]) { + for (int64_t j = 0; j < n; j++) if (vals[j]) ray_release(vals[j]); + if (H && !RAY_IS_ERR(H)) ray_release(H); + return NULL; + } ray_t* q = dkv_select(keys, vals, n); - if (!q) return NULL; - if (ray_env_push_query_scope() != RAY_OK) { ray_release(q); return NULL; } - ray_env_set_query_local(s_t, tbl); - H = ray_eval(q); + if (!q) { if (H && !RAY_IS_ERR(H)) ray_release(H); return NULL; } + if (ray_env_push_query_scope() != RAY_OK) { ray_release(q); if (H && !RAY_IS_ERR(H)) ray_release(H); return NULL; } + ray_t* src = step == 0 ? tbl : H; + ray_env_set_query_local(s_t, src); + ray_t* r = ray_eval(q); ray_env_pop_scope(); ray_release(q); + if (step == 1) ray_release(H); + H = r; + if (!H || RAY_IS_ERR(H) || H->type != RAY_TABLE) break; } if (!H || RAY_IS_ERR(H) || H->type != RAY_TABLE || ray_table_ncols(H) != 2) { if (H && !RAY_IS_ERR(H)) ray_release(H); else if (H) ray_error_free(H); return NULL; } - ray_t* Hc = ray_table_get_col_idx(H, 0); - ray_t* Hn = ray_table_get_col_idx(H, 1); + ray_t* Hc = tbl_col_idx_or_null(H, 0); /* engine-built: never encoded */ + ray_t* Hn = tbl_col_idx_or_null(H, 1); int64_t du = ray_table_nrows(H); if (!Hc || !Hn || Hc->type != RAY_SYM || Hn->type != RAY_I64 || du <= 0 || ray_sym_vec_domain(Hc) != dom) { ray_release(H); return NULL; } + bool plain = true; + for (int64_t i = 0; i + 1 < dict_n; i += 2) { + int64_t kid = dict_elems[i]->i64; + if (kid == take_id || kid == asc_id || kid == desc_id) plain = false; + } + int64_t having = dkv_having_count(dict_elems, dict_n, from_id, by_id, where_id, take_id, + asc_id, desc_id, alias, kind, n_aggs, plain); + /* A having cut that at most DK2_MAX_CAND groups can pass takes the + * two-pass grouping (dk2_run); its counts fit 32 bits there. */ + bool two_pass = false; + if (having > 0 && nrows < ((int64_t)1 << 32) && du < INT32_MAX) { + int64_t bound = nrows / (having + 1); + if (bound > DK2_MAX_CAND) { + const int64_t* hn = (const int64_t*)ray_data(Hn); + int64_t total = 0; + for (int64_t i = 0; i < du; i++) total += hn[i]; + bound = total / (having + 1); + } + two_pass = bound <= DK2_MAX_CAND; + } { ray_t* Ho = dkv_order_by_position(H, ray_sym_domain_count(dom)); if (Ho) { ray_release(H); H = Ho; - Hc = ray_table_get_col_idx(H, 0); - Hn = ray_table_get_col_idx(H, 1); + Hc = tbl_col_idx_or_null(H, 0); + Hn = tbl_col_idx_or_null(H, 1); } } ray_profile_tick("derived key: distinct values"); - /* 2. the key once per distinct value */ - ray_t* key_dom = derived_key_str_chunks(by_expr, col, Hc, dom, du); - if (!key_dom || RAY_IS_ERR(key_dom)) { if (key_dom) ray_error_free(key_dom); ray_release(H); return NULL; } - - /* 3. the per-value table: key, count, the value, its non-null count, - * its length-weighted count */ - ray_t* S = NULL; + if (two_pass) { + if (!dk_key_is_sym(by_expr, col, Hc)) { ray_release(H); return NULL; } + /* H and its counts ours alone: the counts' high halves take the + * key slices, no array of their own */ + bool pack = ray_atomic_load(&H->rc) == 1 && ray_atomic_load(&Hn->rc) == 1 && + !(Hn->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); + ray_sym_domain_raw_t raw = {0}; + (void)ray_sym_domain_raw_pin(dom, &raw); + ray_t* O2 = dk2_run(by_expr, col, Hc, Hn, pack, dom, &raw, having, alias, kind, n_aggs); + ray_sym_domain_raw_unpin(dom); + ray_release(H); + if (!O2) return NULL; + ray_profile_tick("derived key: output built"); + agg_route_note_key_domain(); + return O2; + } + /* 2. the distinct values grouped by key, with the aggregates per group + * (dkh_build) */ + bool want_min = false, want_max = false; + unsigned flags = having >= 0 ? DKH_F_CNT : 0; + for (int a = 0; a < n_aggs; a++) { + switch (kind[a]) { + case DKV_COUNT: flags |= DKH_F_CNT; break; + case DKV_MIN: want_min = true; break; + case DKV_MAX: want_max = true; break; + case DKV_SUM_LEN: flags |= DKH_F_LENW; break; + default: flags |= DKH_F_CNT | DKH_F_LENW; break; /* avg */ + } + } + /* With a having cut, min / max are found afterwards for the kept + * groups only; otherwise while grouping. */ + bool post_mm = having >= 0 && (want_min || want_max); + if (!post_mm) { + if (want_min) flags |= DKH_F_MIN; + if (want_max) flags |= DKH_F_MAX; + } + if (!dk_key_is_sym(by_expr, col, Hc)) { ray_release(H); return NULL; } + ray_sym_domain_raw_t raw = {0}; + (void)ray_sym_domain_raw_pin(dom, &raw); + ray_t *chdr = NULL, *khdr = NULL, *mhdr = NULL; + ray_t* O = NULL; + dkh_t* c = (dkh_t*)scratch_calloc(&chdr, sizeof(dkh_t)); + if (!c) goto vfail; + c->by_expr = by_expr; c->col = col; c->dvec = Hc; c->dom = dom; c->raw = &raw; c->du = du; + c->hn = (const int64_t*)ray_data(Hn); c->flags = flags; c->want_codes = post_mm; + if (!dkh_build(c)) goto vfail; + + /* 3. the kept groups in rank order: oix[rank] = output row, or none */ + int64_t G = c->G, K = 0; + uint32_t* oix = (uint32_t*)scratch_alloc(&khdr, (size_t)G * 2 * sizeof(uint32_t)); + if (!oix) goto vfail; + uint32_t* ko = oix + G; + for (int64_t r = 0; r < G; r++) { + uint32_t code = c->order[r]; + const dkh_part_t* P = &c->part[code & (DKH_NPART - 1)]; + bool keep = having < 0 || DKH_GF(P, DKH_G_CNT, int64_t)[code >> DKH_PART_BITS] > having; + oix[r] = keep ? (uint32_t)K : UINT32_MAX; + if (keep) ko[K++] = code; + } + ray_profile_tick("derived key: groups kept"); + + /* min / max per kept group: value index, bytes, length */ + int64_t *smn = NULL, *smx = NULL; + const char **smnp = NULL, **smxp = NULL; + uint32_t *smnl = NULL, *smxl = NULL; + if (post_mm && K > 0) { + size_t per = sizeof(int64_t) + sizeof(const char*) + sizeof(uint32_t); + char* m = (char*)scratch_alloc(&mhdr, (size_t)K * per * 2); + if (!m) goto vfail; + smn = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + smx = (int64_t*)m; m += (size_t)K * sizeof(int64_t); + smnp = (const char**)m; m += (size_t)K * sizeof(const char*); + smxp = (const char**)m; m += (size_t)K * sizeof(const char*); + smnl = (uint32_t*)m; m += (size_t)K * sizeof(uint32_t); + smxl = (uint32_t*)m; + for (int64_t o = 0; o < K; o++) { smn[o] = -1; smx[o] = -1; } + if (!dkh_kept_minmax(c, oix, K, want_min ? smn : NULL, smnp, smnl, + want_max ? smx : NULL, smxp, smxl)) goto vfail; + } + + /* 4. the output columns, key first, the aggregates as written */ { - ray_t* nn = ray_vec_new(RAY_I64, du); - ray_t* lenw = ray_vec_new(RAY_I64, du); - if (!nn || RAY_IS_ERR(nn) || !lenw || RAY_IS_ERR(lenw)) { - if (nn && !RAY_IS_ERR(nn)) ray_release(nn); - if (lenw && !RAY_IS_ERR(lenw)) ray_release(lenw); - ray_release(key_dom); ray_release(H); return NULL; - } - nn->len = du; lenw->len = du; - dkv_len_ctx_t lc = { - .hc = ray_data(Hc), .attrs = Hc->attrs, .cnt = (const int64_t*)ray_data(Hn), - .nn = (int64_t*)ray_data(nn), .lenw = (int64_t*)ray_data(lenw), .dom = dom, - }; - lc.raw_ok = ray_sym_domain_raw_pin(dom, &lc.raw); - if (dom == ray_sym_runtime_domain()) { - ray_t** rs = NULL; uint32_t rcnt = 0; - ray_sym_strings_borrow(&rs, &rcnt); - lc.rstr = rs; lc.rcnt = rcnt; - } - atomic_store_explicit(&lc.late, 0, memory_order_relaxed); - ray_pool_t* pool = ray_pool_get(); - if (ray_pool_par_dispatch_ok(pool, du, RAY_PARALLEL_THRESHOLD)) - ray_pool_dispatch(pool, dkv_len_fn, &lc, du); - else - dkv_len_fn(&lc, 0, 0, du); - if (atomic_load_explicit(&lc.late, memory_order_relaxed)) { - /* positions past the file prefix: resolved through the domain on - * the calling thread */ - for (int64_t i = 0; i < du; i++) { - if (lc.lenw[i] != INT64_MIN) continue; - int64_t pos = ray_read_sym(lc.hc, i, RAY_SYM, lc.attrs); - ray_t* a = ray_sym_domain_str(dom, pos); - lc.lenw[i] = lc.cnt[i] * (a ? (int64_t)ray_str_len(a) : 0); - } - } - S = ray_table_new(5); - if (S && !RAY_IS_ERR(S)) S = ray_table_add_col(S, s_k, key_dom); - if (S && !RAY_IS_ERR(S)) S = ray_table_add_col(S, s_cnt, Hn); - if (S && !RAY_IS_ERR(S)) S = ray_table_add_col(S, s_ref, Hc); - if (S && !RAY_IS_ERR(S)) S = ray_table_add_col(S, s_nn, nn); - if (S && !RAY_IS_ERR(S)) S = ray_table_add_col(S, s_lenw, lenw); - ray_release(nn); ray_release(lenw); - } - ray_release(key_dom); + int64_t null_cnt = 0; + for (int p = 0; p < DKH_NPART; p++) + if (c->part[p].null_g >= 0) null_cnt = c->hn[c->part[p].null_vi]; + ray_t* ahdr = NULL; + int64_t* av = (int64_t*)scratch_alloc(&ahdr, (size_t)(K ? K : 1) * 5 * sizeof(int64_t)); + if (!av) goto vfail; + int64_t *acnt = av, *ann = av + K, *alenw = av + 2 * K, *amn = av + 3 * K, *amx = av + 4 * K; + const void* hd = ray_data(Hc); + for (int64_t o = 0; o < K; o++) { + uint32_t code = ko[o]; + const dkh_part_t* P = &c->part[code & (DKH_NPART - 1)]; + uint32_t g = code >> DKH_PART_BITS; + acnt[o] = (flags & DKH_F_CNT) ? DKH_GF(P, DKH_G_CNT, int64_t)[g] : 0; + alenw[o] = (flags & DKH_F_LENW) ? DKH_GF(P, DKH_G_LENW, int64_t)[g] : 0; + ann[o] = acnt[o] - ((int64_t)g == P->null_g ? null_cnt : 0); + int64_t bi = -1; + if (want_min) bi = post_mm ? smn[o] : DKH_GF(P, DKH_G_MN, int64_t)[g]; + amn[o] = bi >= 0 ? ray_read_sym(hd, bi, RAY_SYM, Hc->attrs) : 0; + bi = -1; + if (want_max) bi = post_mm ? smx[o] : DKH_GF(P, DKH_G_MX, int64_t)[g]; + amx[o] = bi >= 0 ? ray_read_sym(hd, bi, RAY_SYM, Hc->attrs) : 0; + } + ray_t* kv = ray_vec_new(RAY_SYM, K); + if (!kv || RAY_IS_ERR(kv)) { if (kv) ray_error_free(kv); scratch_free(ahdr); goto vfail; } + kv->len = K; + struct ray_sym_domain_s* kdom = ray_sym_domain_new(); + bool ok = kdom != NULL; + if (ok) { + kv->sym_domain = kdom; /* the vector takes the ref */ + ok = dkh_intern_keys(c, ko, K, kdom, (int64_t*)ray_data(kv)); + } + if (!ok) { ray_release(kv); scratch_free(ahdr); goto vfail; } + O = dkv_emit(by_expr, alias, kind, n_aggs, Hc, kv, K, acnt, ann, alenw, amn, amx); + scratch_free(ahdr); + if (!O) goto vfail; + } + ray_profile_tick("derived key: output built"); + dkh_free(c); scratch_free(chdr); chdr = NULL; c = NULL; + scratch_free(khdr); khdr = NULL; + scratch_free(mhdr); mhdr = NULL; + ray_sym_domain_raw_unpin(dom); ray_release(H); - if (!S || RAY_IS_ERR(S)) { if (S) ray_error_free(S); return NULL; } - ray_profile_tick("derived key: per-value table"); - /* 4. the aggregates rewritten over the per-value table, sort/take as - * written */ - ray_t* R = NULL; - { - int64_t keys[DKV_MAX_AGGS + 8]; ray_t* vals[DKV_MAX_AGGS + 8]; int64_t n = 0; - bool bad = false; - for (int64_t i = 0; i + 1 < dict_n && !bad; i += 2) { + /* Unsorted output comes out in the order of the groups' first values in + * the vocabulary order of C (the key "" first), the same at every core + * count. A sort or take clause runs over that, as written. */ + if (!plain) { + int64_t s_s = ray_sym_intern("__dkv_s", 7); + int64_t keys[4]; ray_t* vals[4]; int64_t n = 0; + keys[n] = from_id; vals[n++] = ray_sym(s_s); + for (int64_t i = 0; i + 1 < dict_n && n < 4; i += 2) { int64_t kid = dict_elems[i]->i64; - ray_t* v = NULL; - if (kid == from_id) v = ray_sym(s_s); - else if (kid == by_id) v = ray_sym(s_k); - else if (kid == where_id) continue; - else if (kid == take_id || kid == asc_id || kid == desc_id) { v = dict_elems[i + 1]; ray_retain(v); } - else { - int k = 0; - for (int a = 0; a < n_aggs; a++) if (alias[a] == kid) k = kind[a]; - switch (k) { - case DKV_COUNT: v = dkv_call("sum", ray_sym(s_cnt), NULL); break; - case DKV_MIN: v = dkv_call("min", ray_sym(s_ref), NULL); break; - case DKV_MAX: v = dkv_call("max", ray_sym(s_ref), NULL); break; - case DKV_SUM_LEN: v = dkv_call("sum", ray_sym(s_lenw), NULL); break; - case DKV_AVG_LEN: v = dkv_call("/", dkv_call("sum", ray_sym(s_lenw), NULL), - dkv_call("sum", ray_sym(s_nn), NULL)); break; - default: v = NULL; - } + if (kid == take_id || kid == asc_id || kid == desc_id) { + keys[n] = kid; vals[n] = dict_elems[i + 1]; ray_retain(vals[n]); n++; } - if (!v) { bad = true; break; } - keys[n] = kid; vals[n++] = v; } - if (bad) { for (int64_t j = 0; j < n; j++) ray_release(vals[j]); ray_release(S); return NULL; } ray_t* q = dkv_select(keys, vals, n); - if (!q) { ray_release(S); return NULL; } - if (ray_env_push_query_scope() != RAY_OK) { ray_release(q); ray_release(S); return NULL; } - ray_env_set_query_local(s_s, S); - R = ray_eval(q); + if (!q) { ray_release(O); return NULL; } + if (ray_env_push_query_scope() != RAY_OK) { ray_release(q); ray_release(O); return NULL; } + ray_env_set_query_local(s_s, O); + ray_t* R = ray_eval(q); ray_env_pop_scope(); ray_release(q); - } - ray_release(S); - if (!R || RAY_IS_ERR(R)) { if (R) ray_error_free(R); return NULL; } - if (ray_is_lazy(R)) R = ray_lazy_materialize(R); - if (!R || RAY_IS_ERR(R) || R->type != RAY_TABLE || ray_table_ncols(R) == 0) { - if (R && !RAY_IS_ERR(R)) ray_release(R); else if (R) ray_error_free(R); - return NULL; - } - /* The engine emits a post-aggregate expression (the avg quotient) - * after the plain aggregates: put the outputs back in the order they - * were written, key first. */ - int64_t rc = ray_table_ncols(R); - if (rc != n_aggs + 1) { ray_release(R); return NULL; } - ray_t* O = ray_table_new(rc); - if (!O || RAY_IS_ERR(O)) { if (O) ray_error_free(O); ray_release(R); return NULL; } - O = ray_table_add_col(O, ray_table_col_name(R, 0), ray_table_get_col_idx(R, 0)); - for (int a = 0; a < n_aggs && O && !RAY_IS_ERR(O); a++) { - ray_t* col = ray_table_get_col(R, alias[a]); - if (!col) { ray_release(O); ray_release(R); return NULL; } - O = ray_table_add_col(O, alias[a], col); - } - ray_release(R); - if (!O || RAY_IS_ERR(O)) { if (O) ray_error_free(O); return NULL; } - /* the key column is named as the row path names a computed key */ - int64_t kname = derived_key_name(by_expr); - for (int64_t c = 1; c < rc; c++) - if (ray_table_col_name(O, c) == kname) { kname = ray_sym_intern("key", 3); break; } - ray_table_set_col_name(O, 0, kname); - /* Unsorted output comes out in the order of the key domain's positions - * — this execution's first-seen ranks over S, i.e. the vocabulary order - * of the values — whatever order the grouping over S emitted in (its - * strategy, and with it the order, depends on the core count). A sort - * or take clause fixes the order itself. */ - bool plain = true; - for (int64_t i = 0; i + 1 < dict_n; i += 2) { - int64_t kid = dict_elems[i]->i64; - if (kid == take_id || kid == asc_id || kid == desc_id) plain = false; - } - int64_t orows = ray_table_nrows(O); - ray_t* okey = ray_table_get_col_idx(O, 0); - if (plain && orows > 1 && okey && okey->type == RAY_SYM) { - struct ray_sym_domain_s* kdom = ray_sym_vec_domain(okey); - int64_t kn = ray_sym_domain_count(kdom); - ray_t *shdr = NULL, *ihdr = NULL; - int64_t* slot = (int64_t*)scratch_alloc(&shdr, (size_t)(kn > 0 ? kn : 1) * sizeof(int64_t)); - int64_t* idx = (int64_t*)scratch_alloc(&ihdr, (size_t)orows * sizeof(int64_t)); - bool ok = slot && idx; - if (ok) { - memset(slot, 0xff, (size_t)kn * sizeof(int64_t)); - const void* kd = ray_data(okey); - for (int64_t i = 0; i < orows && ok; i++) { - int64_t pos = ray_read_sym(kd, i, RAY_SYM, okey->attrs); - if (pos < 0 || pos >= kn || slot[pos] >= 0) ok = false; /* not a grouping by this key */ - else slot[pos] = i; - } - } - if (ok) { - int64_t m = 0; - for (int64_t pos = 0; pos < kn; pos++) if (slot[pos] >= 0) idx[m++] = slot[pos]; - ok = m == orows; - } - if (ok) { - ray_t* P = ray_table_new(rc); - for (int64_t c = 0; c < rc && P && !RAY_IS_ERR(P); c++) { - ray_t* src = ray_table_get_col_idx(O, c); - ray_t* g = src ? gather_by_idx(src, idx, orows) : NULL; - if (!g || RAY_IS_ERR(g)) { if (g) ray_error_free(g); ray_release(P); P = NULL; break; } - P = ray_table_add_col(P, ray_table_col_name(O, c), g); - ray_release(g); - } - if (P && !RAY_IS_ERR(P)) { ray_release(O); O = P; } - else if (P) ray_error_free(P); + ray_release(O); + if (R && !RAY_IS_ERR(R) && ray_is_lazy(R)) R = ray_lazy_materialize(R); + if (!R || RAY_IS_ERR(R) || R->type != RAY_TABLE) { + if (R && !RAY_IS_ERR(R)) ray_release(R); else if (R) ray_error_free(R); + return NULL; } - scratch_free(shdr); scratch_free(ihdr); + O = R; } agg_route_note_key_domain(); return O; +vfail: + if (c) dkh_free(c); + scratch_free(chdr); + scratch_free(khdr); + scratch_free(mhdr); + ray_sym_domain_raw_unpin(dom); + ray_release(H); + return NULL; } /* `sel` (a rowsel over tbl, or NULL): only the rows it selects decide @@ -6092,7 +9628,7 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl, ray_t* sel if (nref != 1) return NULL; int64_t bound[32]; if (!derived_key_expr_ok(by_expr, tbl, ref_syms[0], bound, 0)) return NULL; - ray_t* C = ray_table_get_col(tbl, ref_syms[0]); + ray_t* C = tbl_col_or_null(tbl, ref_syms[0]); int64_t nrows = ray_table_nrows(tbl); if (!C || C->type != RAY_SYM || !ray_is_vec(C) || C->len != nrows || nrows < 4096) return NULL; @@ -6316,8 +9852,14 @@ static ray_t* nonagg_eval_per_group_impl(ray_t* expr, ray_t* tbl, if (!col_syms) return ray_error("oom", NULL); int n_cols = collect_col_refs(expr, tbl, col_syms, (int)ncols_max, 0); ray_t** cols = (ray_t**)(col_syms + ncols_max); - for (int i = 0; i < n_cols; i++) - cols[i] = ray_table_get_col(tbl, col_syms[i]); + for (int i = 0; i < n_cols; i++) { + cols[i] = ray_table_col(tbl, col_syms[i]); + if (cols[i] && RAY_IS_ERR(cols[i])) { + ray_t* err = cols[i]; + scratch_free(refs_hdr); + return err; + } + } if (ray_env_push_query_scope() != RAY_OK) { scratch_free(refs_hdr); return ray_error("oom", NULL); } @@ -6600,7 +10142,7 @@ static bool query_expr_reads_rows_on(ray_t* expr, ray_t* tbl) { if (rows == 1) return true; if (rows == 0) return false; } - if (ray_table_get_col(tbl, expr->i64)) return true; + if (ray_table_has_col(tbl, expr->i64)) return true; if (!ray_sym_is_dotted(expr->i64)) return false; } else if (expr->type != RAY_LIST) return false; if (expr->type == RAY_LIST && expr->len == 3) { @@ -6634,7 +10176,7 @@ static bool query_expr_reads_rows_on(ray_t* expr, ray_t* tbl) { if (expr->type == RAY_LIST && expr->len >= 2) { ray_t** es = ray_data(expr); ray_t* fn = es[0]->type == -RAY_SYM && !(es[0]->attrs & ATTR_QUOTED) && - !ray_table_get_col(tbl, es[0]->i64) ? ray_env_get(es[0]->i64) : NULL; + !ray_table_has_col(tbl, es[0]->i64) ? ray_env_get(es[0]->i64) : NULL; if (fn && fn->type == RAY_LAMBDA) { /* The planner inlines what it can; a helper it cannot lower * yields row data when it was given row data. */ @@ -6683,8 +10225,8 @@ bool ray_query_expr_reads_rows(ray_t* expr) { ray_t* ray_query_helper_value(int64_t sym) { ray_t* src = ray_query_helper_table(); if (!src || src->type != RAY_TABLE) return NULL; - ray_t* col = ray_table_get_col(src, sym); - if (!col) return NULL; + ray_t* col = ray_table_col(src, sym); + if (!col || RAY_IS_ERR(col)) return col; /* Per-group evaluation: the group's rows of the column, as the * expression's own column references are bound. */ if (g_active_query_group_idx && src == g_active_query_table) @@ -6704,8 +10246,8 @@ ray_t* ray_query_helper_value(int64_t sym) { ray_t* ray_active_query_literal(int64_t sym) { ray_t* qt = g_active_query_table; if (!qt || qt->type != RAY_TABLE) return NULL; - ray_t* col = ray_table_get_col(qt, sym); - if (!col) return NULL; + ray_t* col = ray_table_col(qt, sym); + if (!col || RAY_IS_ERR(col)) return col; if (g_active_query_row < 0 || qt != g_active_query_row_tbl || g_active_query_row >= ray_len(col) || ray_env_query_scope_above(g_active_query_row_depth)) { @@ -6735,8 +10277,14 @@ static ray_t* eval_expr_per_row_impl(ray_t* expr, ray_t* tbl, int64_t nrows) { * back inside a list or a dict leaves as a plain string. */ ray_t** marked = cols + ncols_max; int n_marked = 0; - for (int i = 0; i < n_cols; i++) - cols[i] = ray_table_get_col(tbl, col_syms[i]); + for (int i = 0; i < n_cols; i++) { + cols[i] = ray_table_col(tbl, col_syms[i]); + if (cols[i] && RAY_IS_ERR(cols[i])) { + ray_t* err = cols[i]; + scratch_free(refs_hdr); + return err; + } + } if (ray_env_push_query_scope() != RAY_OK) { scratch_free(refs_hdr); return ray_error("oom", NULL); } @@ -6937,12 +10485,13 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { * eval_expr_per_row's scope save/restore, including on every error exit. */ static ray_t* eval_expr_whole_column_impl(ray_t* expr, ray_t* tbl) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_referenced_query(tbl, &expr, 1, &bind_err_); /* decodes what expr reads */ /* Whole columns here, even when a per-row evaluation of an outer select * is in progress (a nested select inside one of its outputs). */ int64_t _aqr = g_active_query_row; g_active_query_row = -1; - ray_t* result = ray_eval(expr); + ray_t* result = bind_err_ ? bind_err_ : ray_eval(expr); /* distinct/asc/desc/reverse return a lazy DAG chain (RAY_LAZY) — force it * to a concrete vector while the source columns it captured are still * bound in this scope. */ @@ -6963,6 +10512,36 @@ static ray_t* eval_expr_whole_column(ray_t* expr, ray_t* tbl) { return result; } +static bool update_expr_elementwise(ray_t* e, ray_t* tbl, bool meta_cols); + +/* A projection over no rows. The per-row pass evaluates nothing and + * leaves an empty LIST, where the builtin over the empty columns keeps its + * result type: `(% d 2)` over an empty DATE column is an empty DATE + * vector. An elementwise expression (atomic builtins over columns and + * literals, update_expr_elementwise) runs no lambda and no effect, so it + * is evaluated once over the empty columns and its result taken when that + * is an empty typed vector. Anything else, or a failure, which is + * swallowed whole, keeps the empty LIST. The check is select's + * (meta_cols): a name bound as a lexical local shadows the column of that + * name, so it is not a column and the probe never reads the column for it. */ +static ray_t* select_fallback_empty_col(ray_t* expr, ray_t* tbl) { + if (update_expr_elementwise(expr, tbl, true)) { + ray_t* col = eval_expr_whole_column_impl(expr, tbl); + if (col && !RAY_IS_ERR(col) && ray_is_vec(col) && ray_len(col) == 0) + return col; + if (col && RAY_IS_ERR(col)) { + ray_error_free(col); + if (__VM->raise_val) { ray_release(__VM->raise_val); __VM->raise_val = NULL; } + if (__VM->return_val) { ray_release(__VM->return_val); __VM->return_val = NULL; } + ray_clear_error_trace(); + ray_error_clear(); /* both the VM's and ray_error_msg()'s copy */ + } else if (col) { + ray_release(col); + } + } + return eval_expr_per_row_impl(expr, tbl, 0); +} + /* Zero groups still need the aggregate's column. Run the aggregate once over * an empty vector of the source's type so the empty column keeps the type a * non-empty result would have had; if that probe cannot run, an empty LIST @@ -7042,14 +10621,16 @@ static ray_t* aggr_unary_per_group_buf(ray_t* expr, ray_t* tbl, * or a full-table eval of the sub-expression. */ ray_t* src = NULL; if (col_expr->type == -RAY_SYM && !(col_expr->attrs & ATTR_QUOTED)) { - src = ray_table_get_col(tbl, col_expr->i64); + src = ray_table_col(tbl, col_expr->i64); + if (src && RAY_IS_ERR(src)) return src; if (src) ray_retain(src); } if (!src) { /* Bind table cols and eval — same pattern as the existing path. */ if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); - src = ray_eval(col_expr); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_all_columns(tbl, &bind_err_); + src = bind_err_ ? bind_err_ : ray_eval(col_expr); g_active_query_table = _aqt; ray_env_pop_scope(); if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("domain", "select by: failed to evaluate aggregation source"); @@ -7171,13 +10752,15 @@ static ray_t* aggr_med_per_group_buf(ray_t* expr, ray_t* tbl, ray_t* src = NULL; if (col_expr->type == -RAY_SYM && !(col_expr->attrs & ATTR_QUOTED)) { - src = ray_table_get_col(tbl, col_expr->i64); + src = ray_table_col(tbl, col_expr->i64); + if (src && RAY_IS_ERR(src)) return src; if (src) ray_retain(src); } if (!src) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); - src = ray_eval(col_expr); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_all_columns(tbl, &bind_err_); + src = bind_err_ ? bind_err_ : ray_eval(col_expr); g_active_query_table = _aqt; ray_env_pop_scope(); if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("domain", "select by: failed to evaluate median source column"); @@ -7473,7 +11056,9 @@ static bool slice_build(const int64_t* row_gid, int64_t nrows, ray_t* sel, return true; } -static ray_t* query_materialize_parted_col(ray_t* col) { +/* `tbl` is the column's table (or NULL): its partition counts give a NULL + * segment, a partition without the column, its rows as typed nulls. */ +static ray_t* query_materialize_parted_col(ray_t* col, ray_t* tbl) { if (!col) return NULL; if (col->type == RAY_MAPCOMMON) return materialize_mapcommon(col); if (!RAY_IS_PARTED(col->type)) { @@ -7483,9 +11068,11 @@ static ray_t* query_materialize_parted_col(ray_t* col) { int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); ray_t** segs = (ray_t**)ray_data(col); - int64_t total = ray_parted_nrows(col); - if (base == RAY_STR) return parted_flatten_str(segs, col->len, total); - if (base == RAY_LIST) return parted_flatten_list(segs, col->len, total); + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); + if (base == RAY_STR) return parted_flatten_str_c(segs, col->len, cnt, ncnt); + if (base == RAY_LIST) return parted_flatten_list_c(segs, col->len, cnt, ncnt); + int64_t total = parted_rows_counted(col, cnt, ncnt); uint8_t attrs = (base == RAY_SYM) ? parted_sym_max_attrs(segs, col->len) : 0; ray_t* flat = typed_vec_new(base, attrs, total); @@ -7496,7 +11083,13 @@ static ray_t* query_materialize_parted_col(ray_t* col) { uint8_t seg_nulls = 0; for (int64_t s = 0; s < col->len; s++) { ray_t* seg = segs[s]; - if (!seg || seg->len <= 0) continue; + if (!seg || RAY_IS_ERR(seg)) { + int64_t n = parted_seg_rows(segs, s, cnt, ncnt); + parted_fill_nulls(flat, off, n); + off += n; + continue; + } + if (seg->len <= 0) continue; parted_copy_cells(ray_data(flat), base, attrs, off, seg, 0, seg->len); seg_nulls |= seg->attrs & RAY_ATTR_HAS_NULLS; off += seg->len; @@ -7588,7 +11181,7 @@ static ray_t* try_count_distinct_v2_rewrite( } /* an alias naming another input column is rejected by the * by-dict materialization; let it report that */ - if (a->i64 != v->i64 && ray_table_get_col(tbl, a->i64)) { + if (a->i64 != v->i64 && ray_table_has_col(tbl, a->i64)) { DICT_VIEW_CLOSE(byv); return NULL; } @@ -7674,9 +11267,10 @@ static ray_t* try_count_distinct_v2_rewrite( * packed kernel. Its byte-width limit must not restrict this rewrite. */ ray_t* K_cols[15]; for (int j = 0; j < n_K; j++) { - K_cols[j] = ray_table_get_col(tbl, K_syms[j]); - if (!K_cols[j]) return NULL; - int8_t kct_j = K_cols[j]->type; + if (ray_env_get_lexical_local(K_syms[j])) return NULL; + ray_col_meta_t kmj; + if (!ray_table_col_meta(tbl, K_syms[j], &kmj)) return NULL; + int8_t kct_j = kmj.type; if (RAY_IS_PARTED(kct_j) || kct_j == RAY_MAPCOMMON) return NULL; int kct_ok_j = (kct_j == RAY_SYM || kct_j == RAY_BOOL || kct_j == RAY_U8 || kct_j == RAY_I16 || kct_j == RAY_I32 || kct_j == RAY_I64 || @@ -7684,9 +11278,10 @@ static ray_t* try_count_distinct_v2_rewrite( kct_j == RAY_STR || kct_j == RAY_GUID || kct_j == RAY_LIST); if (!kct_ok_j) return NULL; } - ray_t* X_col = ray_table_get_col(tbl, cd_X_sym); - if (!X_col) return NULL; - int8_t xct = X_col->type; + if (ray_env_get_lexical_local(cd_X_sym)) return NULL; + ray_col_meta_t xm; + if (!ray_table_col_meta(tbl, cd_X_sym, &xm)) return NULL; + int8_t xct = xm.type; if (RAY_IS_PARTED(xct) || xct == RAY_MAPCOMMON) return NULL; /* X gets the same per-type acceptability check as the K columns * (validated in the loop above). SYM is allowed — mk_compile packs @@ -7700,6 +11295,31 @@ static ray_t* try_count_distinct_v2_rewrite( if (where_expr && !ray_fused_group_supported(where_expr, tbl)) return NULL; + /* An encoded column whose whole decode would not stay cached + * (ray_enccol_decode_kept) is not decoded here: the fused kernel and + * the route's sample read whole columns. The select goes to the + * general path, whose bounded count reads the value (and a single key) + * by range (cd_bounded_scatter_ok). */ + bool enc_cols = false; + for (int j = 0; j <= n_K && !enc_cols; j++) { + ray_t* e = ray_table_get_col_enc(tbl, j < n_K ? K_syms[j] : cd_X_sym); + enc_cols = e && !ray_enccol_decoded_peek(e) && !ray_enccol_decode_kept(e); + } + if (enc_cols) return NULL; + + /* Every gate above is metadata, so a declined rewrite decodes nothing. + * A read declines on a failed decode; the general path re-reads the + * column and reports it. */ + ray_t* X_col = NULL; + if (!enc_cols) { + for (int j = 0; j < n_K; j++) { + K_cols[j] = tbl_col_or_null(tbl, K_syms[j]); + if (!K_cols[j]) return NULL; + } + X_col = tbl_col_or_null(tbl, cd_X_sym); + if (!X_col) return NULL; + } + /* === Fused single-pass kernel (spec Part B) === * Single narrow key, plain column cd-inner, no WHERE, flat columns: * ray_cd_fused replaces the two group-by passes below with one @@ -7713,7 +11333,7 @@ static ray_t* try_count_distinct_v2_rewrite( * dispatch (i.e. from a worker thread). ray_pool_par_dispatch_ok * carries exactly that check (n_workers > 0 && !ray_parallel_flag) * plus the row-count floor. */ - if (n_K == 1 && !where_expr) { + if (n_K == 1 && !where_expr && !enc_cols) { int64_t nrows = ray_table_nrows(tbl); if (ray_pool_par_dispatch_ok(ray_pool_get(), nrows, CDF_MIN_ROWS)) { ray_t* fr = ray_cd_fused(K_cols[0], X_col, nrows); @@ -7725,8 +11345,8 @@ static ray_t* try_count_distinct_v2_rewrite( * SYM over the source domain and renders as text), and * `_first` — an internal ordering artifact — is dropped by * building a fresh 2-column table. */ - ray_t* fk = ray_table_get_col_idx(fr, 0); - ray_t* fu = ray_table_get_col_idx(fr, 1); + ray_t* fk = tbl_col_idx_or_null(fr, 0); /* engine-built */ + ray_t* fu = tbl_col_idx_or_null(fr, 1); int64_t ng = fk ? fk->len : 0; ray_t* kv = col_vec_new(K_cols[0], ng > 0 ? ng : 1); if (!kv || RAY_IS_ERR(kv)) { @@ -7767,7 +11387,7 @@ static ray_t* try_count_distinct_v2_rewrite( * vector on the way there). The estimates the gate takes describe the * rows a `where:` keeps (query_cd_gate_where_rows): a filter that drops a * dominant key value hides the groups and the shares of what remains. */ - { + if (!enc_cols) { const int64_t n_table = ray_table_nrows(tbl); const int64_t* sel_rows = NULL; int64_t sel_nrows = n_table, sel_pop = 0; @@ -7927,6 +11547,34 @@ static ray_t* try_count_distinct_v2_rewrite( return apply_sort_take(result, dict_elems, dict_n, asc_id, desc_id, take_id, NULL); } +/* Whether the post-group scatter of a select can count every non-agg in + * bounded memory straight from the key column (ray_cd_bounded, cdfuse.c): + * each one a `(count (distinct col))` over a column the kernel reads, a + * single key it reads whose base type is the result key's, and the route + * taking it (ray_cd_bounded_preferred, decided on the first count's column). + * Then neither the row map nor the per-group slices are built. */ +static bool cd_bounded_scatter_ok(ray_t** nonagg_exprs, int64_t n_nonaggs, ray_t* tbl, + ray_t* key, ray_t* grp_key, ray_t* sel, int64_t nrows, + int64_t n_groups) { + if (n_nonaggs <= 0) return false; + if (!ray_cd_bounded_col_ok(key, false) || !grp_key || !ray_is_vec(grp_key)) return false; + ray_col_meta_t km; + int8_t kb = key->type == RAY_MAPCOMMON ? ((ray_t**)ray_data(key))[0]->type + : RAY_IS_PARTED(key->type) ? (int8_t)RAY_PARTED_BASETYPE(key->type) + : key->type == RAY_ENCCOL ? (ray_col_meta_of(key, &km) ? km.type : RAY_ENCCOL) + : key->type; + if (grp_key->type != kb || grp_key->len < n_groups) return false; + for (int64_t ni = 0; ni < n_nonaggs; ni++) { + ray_t* cd_inner = match_count_distinct(nonagg_exprs[ni]); + if (!cd_inner || cd_inner->type != -RAY_SYM || (cd_inner->attrs & ATTR_QUOTED)) + return false; + if (!cd_src_bounded_ok(tbl, cd_inner)) return false; + } + ray_t* first = cd_bounded_src_col(tbl, match_count_distinct(nonagg_exprs[0])); + if (first && RAY_IS_ERR(first)) { ray_error_free(first); return false; } + return ray_cd_bounded_preferred(tbl, key, first, sel, nrows, n_groups); +} + /* Per-group count(distinct) using the existing OP_COUNT_DISTINCT kernel. * Mirrors aggr_unary_per_group_buf but slices the source column once per * group and calls exec_count_distinct directly — bypasses the full @@ -7957,25 +11605,52 @@ static ray_t* count_distinct_per_group_buf(ray_t* inner_expr, ray_t* tbl, /* Resolve the source vector — either a direct column ref (zero copy) * or a full-table eval of the inner sub-expression. */ ray_t* src = NULL; - if (inner_expr && inner_expr->type == -RAY_SYM && - !(inner_expr->attrs & ATTR_QUOTED)) { - src = ray_table_get_col(tbl, inner_expr->i64); - if (src) ray_retain(src); - } + src = count_distinct_src_col(tbl, inner_expr); + if (src && RAY_IS_ERR(src)) return src; + if (src) ray_retain(src); if (!src) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); - src = ray_eval(inner_expr); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_all_columns(tbl, &bind_err_); + src = bind_err_ ? bind_err_ : ray_eval(inner_expr); g_active_query_table = _aqt; ray_env_pop_scope(); if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("domain", "select by: failed to evaluate count-distinct source"); + if (ray_is_lazy(src)) { + src = ray_lazy_materialize(src); + if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("oom", NULL); + } + /* An operand that reads none of the table's rows (a bound vector, a + * parameter named like a column) stays a collection: every group + * counts its distinct values, as `(count v)` counts it whole. */ + if (cd_operand_is_collection(inner_expr, tbl)) { + ray_t* d = ray_distinct_fn(src); + if (d && !RAY_IS_ERR(d) && ray_is_lazy(d)) d = ray_lazy_materialize(d); + ray_release(src); + if (!d || RAY_IS_ERR(d)) return d ? d : ray_error("oom", NULL); + int64_t nd = ray_len(d); + ray_release(d); + ray_t* out = ray_vec_new(RAY_I64, n_groups); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + out->len = n_groups; + for (int64_t gi = 0; gi < n_groups; gi++) ((int64_t*)ray_data(out))[gi] = nd; + return out; + } } if (src && !RAY_IS_ERR(src) && (RAY_IS_PARTED(src->type) || src->type == RAY_MAPCOMMON)) { - ray_t* flat = query_materialize_parted_col(src); + ray_t* flat = query_materialize_parted_col(src, tbl); ray_release(src); src = flat; if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("oom", NULL); } + /* The groups list rows of `tbl`: an operand of another length (a + * parameter, `(take y 2)`) has no cell for some of them. */ + if (!ray_is_atom(src) && ray_len(src) != ray_table_nrows(tbl)) { + int64_t sl = ray_len(src); + ray_release(src); + return ray_error("length", "count distinct: operand has %lld values for %lld rows", + (long long)sl, (long long)ray_table_nrows(tbl)); + } if (src->type == RAY_STR || src->type == RAY_GUID || src->type == RAY_LIST) { ray_t* wide = agg_count_distinct_indexed(src, idx_buf, offsets, grp_cnt, n_groups); @@ -8140,19 +11815,21 @@ static ray_t* count_distinct_per_group_groups(ray_t* inner_expr, ray_t* tbl, ray_t* src = NULL; if (inner_expr && inner_expr->type == -RAY_SYM && !(inner_expr->attrs & ATTR_QUOTED)) { - src = ray_table_get_col(tbl, inner_expr->i64); + src = ray_table_col(tbl, inner_expr->i64); + if (src && RAY_IS_ERR(src)) return src; if (src) ray_retain(src); } if (!src) { if (ray_env_push_query_scope() != RAY_OK) return ray_error("oom", NULL); - ray_t* _aqt = bind_all_columns(tbl); - src = ray_eval(inner_expr); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_all_columns(tbl, &bind_err_); + src = bind_err_ ? bind_err_ : ray_eval(inner_expr); g_active_query_table = _aqt; ray_env_pop_scope(); if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("domain", "select by: failed to evaluate count-distinct source"); } if (src && !RAY_IS_ERR(src) && (RAY_IS_PARTED(src->type) || src->type == RAY_MAPCOMMON)) { - ray_t* flat = query_materialize_parted_col(src); + ray_t* flat = query_materialize_parted_col(src, tbl); ray_release(src); src = flat; if (!src || RAY_IS_ERR(src)) return src ? src : ray_error("oom", NULL); @@ -8229,7 +11906,7 @@ static inline int64_t key_read_i64(const void* d, int64_t idx, case RAY_DATE: case RAY_TIME: return ((const int32_t*)d)[idx]; case RAY_I64: - case RAY_TIMESTAMP: return ((const int64_t*)d)[idx]; + case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)d)[idx]; /* F32/F64: the bits, with -0.0 canonicalised to +0.0 the way the * grouping reads its keys (group_key_f64_bits, #407). The group result * holds +0.0 for the merged zero group; a row carrying -0.0 read raw @@ -8452,6 +12129,8 @@ typedef struct { const uint32_t* sel_offs; const uint16_t* sel_idx; uint32_t sel_n_segs; + const int64_t* sel_pre; /* compact map: rank of each segment's first kept row */ + int64_t nrows; /* compact map: rows of the table */ } rgid_probe_mk_ctx_t; static inline uint64_t rgid_mk_hash_step(uint64_t h, int64_t v) { @@ -8522,13 +12201,37 @@ static void rgid_probe_mk_fn(void* ctx_, uint32_t worker_id, for (int64_t r = covered; r < end; r++) x->row_gid[r] = -1; } +/* The compact sibling of rgid_probe_mk_fn: tasks are segments [start, end) + * of the selection, and the gid of the j-th selected row lands in + * row_gid[j] (sel_pre[seg] is the rank of a segment's first kept row). */ +static void rgid_probe_mk_compact_fn(void* ctx_, uint32_t worker_id, + int64_t start, int64_t end) { + (void)worker_id; + const rgid_probe_mk_ctx_t* x = (const rgid_probe_mk_ctx_t*)ctx_; + for (int64_t seg = start; seg < end; seg++) { + uint8_t f = x->sel_flg[seg]; + if (f == RAY_SEL_NONE) continue; + int64_t base = seg * RAY_MORSEL_ELEMS; + int64_t* out = x->row_gid + x->sel_pre[seg]; + if (f == RAY_SEL_ALL) { + int64_t n = x->nrows - base < RAY_MORSEL_ELEMS ? x->nrows - base : RAY_MORSEL_ELEMS; + for (int64_t i = 0; i < n; i++) out[i] = rgid_mk_probe_row(x, base + i); + } else { + uint32_t off = x->sel_offs[seg]; + uint32_t cnt = x->sel_offs[seg + 1] - off; + for (uint32_t i = 0; i < cnt; i++) + out[i] = rgid_mk_probe_row(x, base + x->sel_idx[off + i]); + } + } +} + /* The base types the composite probe reads: KEY_READ's coverage less STR, * which the single-key scatter resolves through its own descriptor probe. */ static int rgid_mk_key_type_ok(int8_t bt) { switch (bt) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: case RAY_F32: case RAY_F64: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: case RAY_SYM: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: return 1; default: return 0; @@ -8545,9 +12248,9 @@ static int multikey_scatter_keys_ok(ray_t* by_expr, ray_t* tbl) { if (!by_expr || by_expr->type != RAY_SYM || ray_len(by_expr) < 2) return 0; const int64_t* ids = (const int64_t*)ray_data(by_expr); for (int64_t k = 0; k < ray_len(by_expr); k++) { - ray_t* col = ray_table_get_col(tbl, ids[k]); - if (!col || col->type == RAY_MAPCOMMON) return 0; - int8_t bt = col->type; + ray_col_meta_t km; /* metadata: the key's type, nothing decoded */ + if (!ray_table_col_meta(tbl, ids[k], &km) || km.type == RAY_MAPCOMMON) return 0; + int8_t bt = km.type; if (RAY_IS_PARTED(bt)) bt = (int8_t)RAY_PARTED_BASETYPE(bt); if (!rgid_mk_key_type_ok(bt)) return 0; } @@ -8558,10 +12261,11 @@ static int multikey_scatter_keys_ok(ray_t* by_expr, ray_t* tbl) { * `result`'s key columns, hashed; then every row of `tbl`'s key columns is * probed (in parallel when the input is large). Parted source keys are * flattened for the probe. Rows `selection` drops get -1. Returns NULL on - * success, else an owned error. */ + * success, else an owned error. `compact`: row_gid holds the selected rows + * only, in selection order (total_pass cells), not one per row. */ static ray_t* rgid_build_multikey(ray_t* tbl, ray_t* result, ray_t* by_expr, int64_t nrows, int64_t n_groups, - ray_t* selection, int64_t* row_gid) { + ray_t* selection, int64_t* row_gid, bool compact) { int nk = (int)ray_len(by_expr); const int64_t* ids = (const int64_t*)ray_data(by_expr); ray_t* err = NULL; @@ -8583,12 +12287,14 @@ static ray_t* rgid_build_multikey(ray_t* tbl, ray_t* result, ray_t* by_expr, if (!owned) { scratch_free(cols_hdr); return ray_error("oom", NULL); } for (int k = 0; k < nk && !err; k++) { - ray_t* orig = ray_table_get_col(tbl, ids[k]); - ray_t* g = ray_table_get_col(result, ids[k]); + ray_t* orig = ray_table_col(tbl, ids[k]); + if (orig && RAY_IS_ERR(orig)) { err = orig; break; } + ray_t* g = ray_table_col(result, ids[k]); + if (g && RAY_IS_ERR(g)) { err = g; break; } if (!orig || !g) { err = ray_error("domain", "select by: group key column not found"); break; } ray_t* sc = orig; if (RAY_IS_PARTED(sc->type) || sc->type == RAY_MAPCOMMON) { - sc = query_materialize_parted_col(sc); + sc = query_materialize_parted_col(sc, tbl); if (!sc || RAY_IS_ERR(sc)) { err = sc ? sc : ray_error("oom", NULL); break; } owned[k] = 1; } @@ -8651,7 +12357,33 @@ static ray_t* rgid_build_multikey(ray_t* tbl, ray_t* result, ray_t* by_expr, ctx.sel_n_segs = sm->n_segs; } ray_pool_t* pool = ray_pool_get(); - if (pool && nrows >= 200000 && ray_pool_total_workers(pool) >= 2) + ray_t* pre_hdr = NULL; + if (compact && selection) { + int64_t ns = (int64_t)ctx.sel_n_segs; + int64_t* pre = (int64_t*)scratch_alloc(&pre_hdr, (size_t)(ns + 1) * sizeof(int64_t)); + if (!pre) err = ray_error("oom", NULL); + else { + int64_t run = 0; + for (int64_t s = 0; s < ns; s++) { + pre[s] = run; + uint8_t f = ctx.sel_flg[s]; + if (f == RAY_SEL_ALL) { + int64_t lo = s * RAY_MORSEL_ELEMS; + run += (nrows - lo < RAY_MORSEL_ELEMS ? nrows - lo : RAY_MORSEL_ELEMS); + } else if (f != RAY_SEL_NONE) { + run += ctx.sel_offs[s + 1] - ctx.sel_offs[s]; + } + } + pre[ns] = run; + ctx.sel_pre = pre; + ctx.nrows = nrows; + if (pool && nrows >= 200000 && ray_pool_total_workers(pool) >= 2) + ray_pool_dispatch(pool, rgid_probe_mk_compact_fn, &ctx, ns); + else + rgid_probe_mk_compact_fn(&ctx, 0, 0, ns); + } + if (pre_hdr) scratch_free(pre_hdr); + } else if (pool && nrows >= 200000 && ray_pool_total_workers(pool) >= 2) ray_pool_dispatch(pool, rgid_probe_mk_fn, &ctx, nrows); else rgid_probe_mk_fn(&ctx, 0, 0, nrows); @@ -8686,7 +12418,7 @@ static int can_atom_broadcast(ray_t* a) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: case RAY_F32: case RAY_F64: case RAY_GUID: case RAY_STR: - case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: return 1; default: @@ -8757,7 +12489,7 @@ static ray_t* atom_broadcast_vec(ray_t* a, int64_t n) { break; } case RAY_I64: - case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t val = a->i64; int64_t* d = (int64_t*)dst; for (int64_t i = 0; i < n; i++) d[i] = val; @@ -8820,6 +12552,57 @@ static ray_t* atom_broadcast_vec(ray_t* a, int64_t n) { return v; } +/* A grouped output that is the same value for every group, decided from + * the AST alone: 1 for a self-evaluating literal (can_atom_broadcast), 2 + * for a call of an atomic builtin over such literals and such calls + * (`(+ 1 2)`), which yields an atom. A name that is a column, a lexical + * local or anything but an atomic builtin (lambdas, special forms, + * aggregates) is not constant: 0. The post-group scatter broadcasts a + * constant without reading the table, so a constant output does not need + * the flat table a row-dependent one does. */ +static int const_output_expr(ray_t* e, ray_t* tbl, int depth) { + if (can_atom_broadcast(e)) return 1; + if (!e || e->type != RAY_LIST || depth > 16) return 0; + int64_t n = ray_len(e); + if (n < 2) return 0; + ray_t** el = (ray_t**)ray_data(e); + ray_t* h = el[0]; + if (!h || h->type != -RAY_SYM || (h->attrs & ATTR_QUOTED)) return 0; + if (tbl_has_col(tbl, h->i64) || ray_env_has_lexical_local(h->i64)) return 0; + if (resolve_agg_opcode(h->i64)) return 0; + ray_t* fn = ray_env_get(h->i64); + if (!fn || (fn->type != RAY_UNARY && fn->type != RAY_BINARY && fn->type != RAY_VARY)) + return 0; + if (!(fn->attrs & (RAY_FN_ATOMIC | RAY_FN_LEFT_ATOMIC | RAY_FN_RIGHT_ATOMIC)) || + (fn->attrs & (RAY_FN_AGGR | RAY_FN_SPECIAL_FORM))) + return 0; + for (int64_t i = 1; i < n; i++) + if (!const_output_expr(el[i], tbl, depth + 1)) return 0; + return 2; +} + +/* The non-aggregate columns of a grouped select that has no group: an + * empty grouped aggregate keeps its result type, a literal its own type, + * and any other expression is an empty LIST. Consumes `result`; returns it + * extended, or an error. */ +static ray_t* grouped_nonagg_empty(ray_t* result, ray_t* tbl, ray_t* const* exprs, + const int64_t* names, int64_t n) { + for (int64_t ni = 0; ni < n; ni++) { + ray_t* expr = exprs[ni]; + ray_t* empty_list = match_count_distinct(expr) ? ray_vec_new(RAY_I64, 0) + : is_streaming_aggr_unary_call(expr, tbl) ? aggr_unary_per_group_buf(expr, tbl, NULL, NULL, NULL, 0) + : can_atom_broadcast(expr) ? atom_broadcast_vec(expr, 0) : ray_list_new(0); + if (!empty_list || RAY_IS_ERR(empty_list)) { + ray_release(result); + return empty_list ? empty_list : ray_error("oom", NULL); + } + result = ray_table_add_col(result, names[ni], empty_list); + ray_release(empty_list); + if (RAY_IS_ERR(result)) return result; + } + return result; +} + static ray_t* scalar_result_col(ray_t* value) { if (!value || RAY_IS_ERR(value)) return value ? value : ray_error("domain", "select: scalar aggregate produced no result"); @@ -8886,10 +12669,33 @@ static ray_t* eval_scalar_agg_outputs(ray_t** dict_elems, int64_t dict_n, /* Expand helpers first: a pure helper around such a verb is the * verb, and must not be fed one cell at a time either. */ ray_t* agg_src_expr = query_inline_helpers(agg_elems[1], tbl); - ray_t* src = (is_whole_column_projection(agg_src_expr, tbl) || - expr_is_constant_collection(agg_src_expr, tbl, NULL)) - ? eval_expr_whole_column_impl(agg_src_expr, tbl) - : eval_expr_per_row_impl(agg_src_expr, tbl, nrows); + ray_t* src = NULL; + bool column_free = false; + if (is_whole_column_projection(agg_src_expr, tbl) || + expr_is_constant_collection(agg_src_expr, tbl, NULL)) + src = eval_expr_whole_column_impl(agg_src_expr, tbl); + else if (expr_reads_no_column(agg_src_expr, tbl)) { + column_free = true; + /* A source that reads no column (`(til 5)`, which the planner + * does not lower) has one value whatever the row: a collection + * is aggregated as it stands, as outside a select; per row it + * would be counted once per row. A scalar keeps its per-row + * meaning (`(sum 1)` is the row count): the rows' cells, all + * this one value. Evaluated once either way, so an effect in + * it runs once. */ + src = eval_expr_whole_column_impl(agg_src_expr, tbl); + if (src && !RAY_IS_ERR(src) && ray_is_atom(src)) { + ray_t* cells = atom_broadcast_vec(src, nrows); + if (!cells) { + cells = ray_list_new(nrows); + for (int64_t r = 0; r < nrows && cells && !RAY_IS_ERR(cells); r++) + cells = ray_list_append(cells, src); + } + ray_release(src); + src = cells ? cells : ray_error("oom", NULL); + } + } + else src = eval_expr_per_row_impl(agg_src_expr, tbl, nrows); ray_release(agg_src_expr); if (!src || RAY_IS_ERR(src)) { ray_release(result); @@ -8906,6 +12712,18 @@ static ray_t* eval_scalar_agg_outputs(ray_t** dict_elems, int64_t dict_n, return agg_value ? agg_value : ray_error("domain", "select: scalar aggregate evaluation failed"); } + /* The aggregate of a column-free source is one value, a collection + * too: boxed as one cell, as each group takes it under by:. */ + if (column_free && !ray_is_atom(agg_value)) { + ray_t* box = ray_list_new(1); + if (box && !RAY_IS_ERR(box)) box = ray_list_append(box, agg_value); + ray_release(agg_value); + if (!box || RAY_IS_ERR(box)) { + ray_release(result); + return box ? box : ray_error("oom", NULL); + } + agg_value = box; + } ray_t* col = scalar_result_col(agg_value); ray_release(agg_value); if (!col || RAY_IS_ERR(col)) { @@ -8924,7 +12742,13 @@ static ray_t* eval_scalar_agg_outputs(ray_t** dict_elems, int64_t dict_n, /* (select {from: t [where: pred] [by: key] [col: expr ...]}) * Special form — receives unevaluated dict arg. */ ray_t* ray_select(ray_t** args, int64_t n); -static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved); +/* How far a select's planning has gone, for a select re-entered with a + * rewritten query: the rewrites already made are not made again. */ +enum { + SELECT_ALIASES_RESOLVED = 1, /* grouped aliases planned */ + SELECT_COLUMN_FREE_PLANNED = 2, /* column-free aggregate sources evaluated */ +}; +static ray_t* ray_select_impl(ray_t** args, int64_t n, unsigned plan); ray_t* ray_update(ray_t** args, int64_t n); ray_t* ray_insert(ray_t** args, int64_t n); ray_t* ray_upsert(ray_t** args, int64_t n); @@ -9248,10 +13072,12 @@ typedef enum { } count_cmp_op_t; typedef struct { - const ray_t* col; + const ray_t* col; /* the plain vector; NULL when read by range */ int64_t rhs; count_cmp_op_t op; int64_t* counts; + ray_col_src_t* src; /* the bound source (range reads) */ + ray_scan_fail_t* fail; } count_compare_ctx_t; static inline int64_t count_atom_i64(ray_t* a) { @@ -9287,29 +13113,16 @@ static count_cmp_op_t count_cmp_flip(count_cmp_op_t op) { } } -static void count_compare_task(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { - count_compare_ctx_t* ctx = (count_compare_ctx_t*)vctx; - const ray_t* col = ctx->col; - const void* data = ray_data((ray_t*)col); - int64_t rhs = ctx->rhs; - count_cmp_op_t op = ctx->op; +/* Rows of data[start, end) (type, attrs: the column's or the piece's) + * that compare true against rhs, every element widened to int64: the + * reference, and the path of the 64-bit and SYM types. */ +static int64_t count_compare_span_ref(int8_t type, uint8_t attrs, const void* data, + int64_t start, int64_t end, int64_t rhs, count_cmp_op_t op) { int64_t local = 0; - - switch (col->type) { + switch (type) { case RAY_BOOL: case RAY_U8: { const uint8_t* x = (const uint8_t*)data; - if ((op == COUNT_CMP_EQ || op == COUNT_CMP_NE) && rhs >= 0 && rhs <= 255) { - uint8_t needle = (uint8_t)rhs; - if (op == COUNT_CMP_EQ) { - for (int64_t i = start; i < end; i++) - local += x[i] == needle; - } else { - for (int64_t i = start; i < end; i++) - local += x[i] != needle; - } - break; - } for (int64_t i = start; i < end; i++) local += count_compare_i64((int64_t)x[i], rhs, op); break; @@ -9327,13 +13140,13 @@ static void count_compare_task(void* vctx, uint32_t worker_id, int64_t start, in break; } case RAY_I64: - case RAY_TIMESTAMP: { + case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* x = (const int64_t*)data; for (int64_t i = start; i < end; i++) local += count_compare_i64(x[i], rhs, op); break; } case RAY_SYM: { - uint8_t esz = col_esz(col); + uint8_t esz = ray_sym_elem_size(RAY_SYM, attrs); for (int64_t i = start; i < end; i++) local += count_compare_i64(read_by_esz(data, i, esz), rhs, op); break; @@ -9341,16 +13154,204 @@ static void count_compare_task(void* vctx, uint32_t worker_id, int64_t start, in default: break; } - ctx->counts[worker_id] += local; + return local; +} + +/* Native-width compares: the literal at the element width, a narrow + * counter per piece of at most 65535 rows (it cannot wrap), widened once + * per piece. */ +#define COUNT_NATIVE(NAME, ET, ACC) \ +static int64_t NAME(const ET* restrict x, int64_t n, ET r, count_cmp_op_t op) { \ + int64_t total = 0; \ + for (int64_t b = 0; b < n; b += 65535) { \ + const int64_t e = n - b < 65535 ? n : b + 65535; \ + ACC acc = 0; \ + switch (op) { \ + case COUNT_CMP_EQ: for (int64_t i = b; i < e; i++) acc += x[i] == r; break; \ + case COUNT_CMP_NE: for (int64_t i = b; i < e; i++) acc += x[i] != r; break; \ + case COUNT_CMP_LT: for (int64_t i = b; i < e; i++) acc += x[i] < r; break; \ + case COUNT_CMP_LE: for (int64_t i = b; i < e; i++) acc += x[i] <= r; break; \ + case COUNT_CMP_GT: for (int64_t i = b; i < e; i++) acc += x[i] > r; break; \ + case COUNT_CMP_GE: for (int64_t i = b; i < e; i++) acc += x[i] >= r; break; \ + default: break; \ + } \ + total += acc; \ + } \ + return total; \ +} +COUNT_NATIVE(count_native_u8, uint8_t, uint16_t) +COUNT_NATIVE(count_native_i16, int16_t, uint16_t) +COUNT_NATIVE(count_native_i32, int32_t, uint32_t) + +/* A literal outside the element type's values [lo, hi]: the compare is the + * same for every element, so the count is all or none. */ +static int64_t count_outside(int64_t rhs, int64_t hi, int64_t n, count_cmp_op_t op) { + bool above = rhs > hi; + switch (op) { + case COUNT_CMP_NE: return n; + case COUNT_CMP_LT: case COUNT_CMP_LE: return above ? n : 0; + case COUNT_CMP_GT: case COUNT_CMP_GE: return above ? 0 : n; + default: return 0; /* EQ */ + } } -static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_count) { - if (!tbl || !where_expr || where_expr->type != RAY_LIST || ray_len(where_expr) != 3) - return 0; - ray_t** we = (ray_t**)ray_data(where_expr); - if (!we[0] || we[0]->type != -RAY_SYM) return 0; +/* Rows of data[start, end) (type, attrs: the column's or the piece's) + * that compare true against rhs. */ +static int64_t count_compare_span(int8_t type, uint8_t attrs, const void* data, + int64_t start, int64_t end, int64_t rhs, count_cmp_op_t op) { + const int64_t n = end - start; + if (n <= 0) return 0; + switch (type) { + case RAY_BOOL: + case RAY_U8: + if (rhs < 0 || rhs > UINT8_MAX) return count_outside(rhs, UINT8_MAX, n, op); + return count_native_u8((const uint8_t*)data + start, n, (uint8_t)rhs, op); + case RAY_I16: + if (rhs < INT16_MIN || rhs > INT16_MAX) return count_outside(rhs, INT16_MAX, n, op); + return count_native_i16((const int16_t*)data + start, n, (int16_t)rhs, op); + case RAY_I32: + case RAY_DATE: + case RAY_TIME: + if (rhs < INT32_MIN || rhs > INT32_MAX) return count_outside(rhs, INT32_MAX, n, op); + return count_native_i32((const int32_t*)data + start, n, (int32_t)rhs, op); + default: + return count_compare_span_ref(type, attrs, data, start, end, rhs, op); + } +} + +static void count_compare_task(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { + count_compare_ctx_t* ctx = (count_compare_ctx_t*)vctx; + const ray_t* col = ctx->col; + ctx->counts[worker_id] += count_compare_span(col->type, col->attrs, ray_data((ray_t*)col), + start, end, ctx->rhs, ctx->op); +} + +/* Range reads: one call per piece of the walk (generation 2: per vector). */ +typedef struct { count_compare_ctx_t* c; int64_t local; } count_piece_ctx_t; +static void count_piece(void* vctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + count_piece_ctx_t* pc = (count_piece_ctx_t*)vctx; + pc->local += count_compare_span(pc->c->src->type, p[0].attrs, p[0].data, 0, e - b, + pc->c->rhs, pc->c->op); +} +/* The zone gate's comparison for a count op; 0 for none. */ +static uint16_t count_zone_op(count_cmp_op_t op) { + switch (op) { + case COUNT_CMP_EQ: return OP_EQ; + case COUNT_CMP_NE: return OP_NE; + case COUNT_CMP_LT: return OP_LT; + case COUNT_CMP_LE: return OP_LE; + case COUNT_CMP_GT: return OP_GT; + case COUNT_CMP_GE: return OP_GE; + default: return 0; + } +} +/* Chunk ch of the bound source decided from its directory: 1 every row + * compares true, 0 none, -1 undecided. The source has no nulls (the fast + * path declines nullable columns other than SYM, which is never decided + * here: its ids carry no string order, #738). */ +static int count_chunk_decision(const count_compare_ctx_t* ctx, int64_t ch) { + uint16_t op = count_zone_op(ctx->op); + if (!op || !zone_dir_type(ctx->src->type)) return -1; + ray_enc_chunk_stat_t st; + if (!ray_col_src_chunk_stat(ctx->src, ch, &st)) return -1; + return zone_cmp_core(st.min, st.max, st.has_minmax, false, false, op, ctx->rhs); +} +/* Vector v of an undecided chunk decided from its descriptor (the same + * rule over the vector's statistics, which nest inside the chunk's): the + * count is answer-only, so a decided vector is never read. */ +static int count_vec_decision(const count_compare_ctx_t* ctx, uint16_t op, int64_t v) { + int64_t mn, mx; uint32_t nn; + if (!ray_col_src_vec_stat(ctx->src, v, &mn, &mx, &nn)) return -1; + return zone_cmp_core(mn, mx, true, nn > 0, false, op, ctx->rhs); +} +/* Rows [start, end) of a generation-2 source: each chunk decided from the + * directory, then each vector of an undecided chunk from its descriptor; + * an undecided vector the task holds whole is counted on its view + * (ray_enc_count_cmp: runs, packed residuals, codes; nothing decoded); + * the rest are read through one task cursor, consecutive ones in one + * walk. A vector at a task edge is always read: no answer depends on + * where the pool cuts the rows. */ +static void count_compare_enc_task(void* vctx, uint32_t worker_id, int64_t start, int64_t end) { + count_compare_ctx_t* ctx = (count_compare_ctx_t*)vctx; + if (ray_scan_fail_skip(ctx->fail, start)) return; + count_piece_ctx_t pc = { ctx, 0 }; + ray_col_src_t* srcs[1] = { ctx->src }; + const void* plain[1] = { NULL }; + _Static_assert(RAY_ENC_CHUNK == 1 << 16, "count decisions read 64K-row chunks"); + const uint16_t op = count_zone_op(ctx->op); + const bool by_vec = op && zone_dir_type(ctx->src->type); + /* SYM: no statistics decision (ids carry no string order, #738, and + * "" is decided by the null count alone), but == / != count on views */ + const bool by_view = by_vec || (op && ctx->src->type == RAY_SYM); + ray_col_fixed_t fixed; /* the task's decode vector: no worker heap */ + ray_enc_vview_t view; /* the task's vector view: on its stack too */ + ray_col_cursor_t cur; + ray_col_cursor_init_lent(&cur, ctx->src, &fixed); + ray_t* err = NULL; + for (int64_t b = start; b < end && !err; ) { + int64_t e = ((b >> 16) + 1) << 16; /* the end of b's chunk */ + if (e > end) e = end; + int d = count_chunk_decision(ctx, b >> 16); + if (d == 1) pc.local += e - b; + else if (d != 0 && !by_view) err = ray_col_walk_cur(srcs, plain, 1, &cur, b, e, &pc, worker_id, count_piece); + else if (d != 0) { + int64_t run = -1; /* first row of the undecided vectors pending */ + for (int64_t vb = b, ve; vb < e && !err; vb = ve) { + ve = (vb / RAY_ENC_VEC + 1) * RAY_ENC_VEC; + if (ve > e) ve = e; + int vd = by_vec ? count_vec_decision(ctx, op, vb / RAY_ENC_VEC) : -1; + if (vd < 0 && vb % RAY_ENC_VEC == 0 && + ve - vb == (ctx->src->len - vb < RAY_ENC_VEC ? ctx->src->len - vb : RAY_ENC_VEC)) { + /* the whole vector inside the task: its view may answer */ + int64_t n; + int vr = ray_col_src_vview(ctx->src, vb / RAY_ENC_VEC, &view, &err); + if (vr < 0) { /* the lower rows' read reports first */ + ray_t* werr = run >= 0 ? ray_col_walk_cur(srcs, plain, 1, &cur, run, vb, &pc, worker_id, count_piece) : NULL; + if (werr) { ray_error_free(err); err = werr; } + break; + } + if (vr > 0 && view.n == ve - vb && ray_enc_count_cmp(&view, op, ctx->rhs, &n)) { + if (run >= 0) { err = ray_col_walk_cur(srcs, plain, 1, &cur, run, vb, &pc, worker_id, count_piece); run = -1; } + pc.local += n; + continue; + } + } + if (vd < 0) { if (run < 0) run = vb; continue; } + if (run >= 0) { err = ray_col_walk_cur(srcs, plain, 1, &cur, run, vb, &pc, worker_id, count_piece); run = -1; } + if (vd == 1) pc.local += ve - vb; + } + if (!err && run >= 0) err = ray_col_walk_cur(srcs, plain, 1, &cur, run, e, &pc, worker_id, count_piece); + } + b = e; + } + ray_col_cursor_free(&cur); + if (err) { ray_scan_fail_note(ctx->fail, start, err); return; } + ctx->counts[worker_id] += pc.local; +} + +/* Counts the fast path answered since process start (test hook). */ +static _Atomic(uint64_t) g_count_fast; +uint64_t ray_query_test_count_fast(void) { return atomic_load(&g_count_fast); } +int64_t ray_query_test_count_compare(int8_t type, const void* data, int64_t n, int64_t rhs, int op, bool ref) { + return ref ? count_compare_span_ref(type, 0, data, 0, n, rhs, (count_cmp_op_t)op) + : count_compare_span(type, 0, data, 0, n, rhs, (count_cmp_op_t)op); +} + +/* 1 handled (*out_count), 0 not this shape, -1 a range read failed (*err + * owned). */ +/* `(op col literal)` or `(op literal col)` with op one of < > == != <= >=, + * the column an unquoted name and the literal a non-null atom that is not a + * name (nor a quoted symbol naming a column): the column's name, the + * literal and the op as read column-first. false for any other shape. */ +static bool count_cmp_parse(ray_t* tbl, ray_t* e, count_cmp_op_t* op_out, + ray_t** col_out, ray_t** rhs_out) { + if (!tbl || !e || e->type != RAY_LIST || ray_len(e) != 3) + return false; + ray_t** we = (ray_t**)ray_data(e); + if (!we[0] || we[0]->type != -RAY_SYM) return false; ray_t* op_name = ray_sym_str(we[0]->i64); - if (!op_name) return 0; + if (!op_name) return false; const char* op_s = ray_str_ptr(op_name); size_t op_len = ray_str_len(op_name); count_cmp_op_t op = 0; @@ -9363,7 +13364,7 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ else if (op_s[0] == '<' && op_s[1] == '=') op = COUNT_CMP_LE; else if (op_s[0] == '>' && op_s[1] == '=') op = COUNT_CMP_GE; } - if (!op) return 0; + if (!op) return false; ray_t* col_expr = we[1]; ray_t* rhs_expr = we[2]; @@ -9375,11 +13376,11 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ op = count_cmp_flip(op); } if (!col_expr || col_expr->type != -RAY_SYM || (col_expr->attrs & ATTR_QUOTED)) - return 0; + return false; if (!rhs_expr || !ray_is_atom(rhs_expr) || (rhs_expr->type == -RAY_SYM && !(rhs_expr->attrs & ATTR_QUOTED)) || RAY_ATOM_IS_NULL(rhs_expr)) - return 0; + return false; /* B3 Part 2: a QUOTED -RAY_SYM rhs that NAMES a from-table column does * NOT compare against the literal symbol — inside a query it resolves to @@ -9389,42 +13390,73 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ * comparison consistently. A quoted sym naming no column stays a literal * and is handled here as before. */ if (rhs_expr->type == -RAY_SYM && (rhs_expr->attrs & ATTR_QUOTED) && - ray_table_get_col(tbl, rhs_expr->i64)) - return 0; - - ray_t* col = ray_table_get_col(tbl, col_expr->i64); - if (!col || col->len != ray_table_nrows(tbl)) return 0; - if (ray_vec_may_have_nulls(col)) return 0; + tbl_has_col(tbl, rhs_expr->i64)) + return false; + *op_out = op; *col_out = col_expr; *rhs_out = rhs_expr; + return true; +} - switch (col->type) { - case RAY_BOOL: - case RAY_U8: - case RAY_I16: - case RAY_I32: - case RAY_I64: - case RAY_DATE: - case RAY_TIME: - case RAY_TIMESTAMP: - if (!is_numeric(rhs_expr) && !is_temporal(rhs_expr)) return 0; - break; +/* The literal suits the compare of a `type` column, as the single-compare + * count reads it: an integer, BOOL or temporal column takes an integer or + * temporal literal (no float; a temporal of another type only on TIMESTAMP), + * a SYM column a symbol under == / != only (#738). `float_ok` also admits a + * numeric literal on an F32 / F64 column (the conjunction whitelist; the + * single-compare kernel has no float compare). */ +static bool count_cmp_types_ok(int8_t type, count_cmp_op_t op, ray_t* rhs, bool float_ok) { + switch (type) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: + if (!is_numeric(rhs) && !is_temporal(rhs)) return false; + if (rhs->type == -RAY_F64 || rhs->type == -RAY_F32) return false; + if (is_temporal(rhs) && rhs->type != -type && type != RAY_TIMESTAMP) return false; + return true; case RAY_SYM: - if (rhs_expr->type != -RAY_SYM) return 0; - break; + return rhs->type == -RAY_SYM && (op == COUNT_CMP_EQ || op == COUNT_CMP_NE); + case RAY_F32: case RAY_F64: + return float_ok && is_numeric(rhs); default: - return 0; + return false; } +} - /* The raw compare below is right only for a literal in the column's own - * units. A float literal decoded to 0 here, and a different temporal - * type compared days, milliseconds and nanoseconds as one unit. A - * TIMESTAMP column takes a DATE or TIME literal on its nanosecond scale, - * as the eval path does; every other mix goes the general way. */ - if (rhs_expr->type == -RAY_F64 || rhs_expr->type == -RAY_F32) return 0; - bool rhs_ns = false; - if (is_temporal(rhs_expr) && rhs_expr->type != -col->type) { - if (col->type != RAY_TIMESTAMP) return 0; - rhs_ns = true; - } +static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_count, + ray_t** err) { + count_cmp_op_t op = 0; + ray_t* col_expr = NULL; + ray_t* rhs_expr = NULL; + if (!count_cmp_parse(tbl, where_expr, &op, &col_expr, &rhs_expr)) return 0; + + ray_col_meta_t cm; + if (!ray_table_col_meta(tbl, col_expr->i64, &cm) || cm.len != ray_table_nrows(tbl)) return 0; + if (ray_col_bind_declines(tbl, col_expr->i64)) return 0; + /* Bind without decoding (finding C2). A bind failure declines: the + * general count path re-reads the column and reports it there. */ + ray_col_src_t src; + ray_t* be = ray_table_col_src(tbl, col_expr->i64, &src); + if (be) { ray_error_free(be); return 0; } + if (!src.obj) return 0; + ray_t* ready = ray_col_src_ready(&src); + /* plain: today's loop over the vector; a parted source declines as today + * (its wrapper's length is the segment count) */ + ray_t* col = (ready && !RAY_IS_PARTED(ready->type)) ? ready : NULL; + int ok = 0; + if (src.parted || src.len != ray_table_nrows(tbl)) goto out; + /* A SYM column needs no null proof (issue #533): its null is id 0 in + * every domain (a file domain seeds "" at position 0) and the literal + * is non-null, so a raw id EQ / NE is already the null-aware count. + * (ray_vec_may_have_nulls is always true for a plain SYM vector, which + * declined generation 0 here.) Ordered SYM compares decline below. */ + if (src.type != RAY_SYM && (col ? ray_vec_may_have_nulls(col) : src.may_null)) goto out; + + /* Symbols order by string, not by intern id or domain position (#738): + * only EQ / NE are raw-id answers. The raw compare below is right only + * for a literal in the column's own units. A float literal decoded to 0 + * here, and a different temporal type compared days, milliseconds and + * nanoseconds as one unit. A TIMESTAMP column takes a DATE or TIME + * literal on its nanosecond scale, as the eval path does; every other mix + * goes the general way. */ + if (!count_cmp_types_ok(src.type, op, rhs_expr, false)) goto out; + bool rhs_ns = is_temporal(rhs_expr) && rhs_expr->type != -src.type; int64_t rhs = count_atom_i64(rhs_expr); if (rhs_ns) { @@ -9439,34 +13471,42 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ * for runtime-domain columns). Absent ⇒ -1: never equals any cell * (cells are non-negative), so EQ counts 0 and NE counts all — * exactly the absent-literal-matches-nothing contract. */ - if (col->type == RAY_SYM && - ray_sym_vec_domain(col) != ray_sym_runtime_domain()) { + if (src.type == RAY_SYM && src.dom != ray_sym_runtime_domain()) { ray_t* s = ray_sym_str(rhs); - rhs = s ? ray_sym_vec_lookup(col, ray_str_ptr(s), ray_str_len(s)) : -1; + rhs = s ? ray_col_src_sym_find(&src, ray_str_ptr(s), ray_str_len(s)) : -1; } ray_pool_t* pool = ray_pool_get(); uint32_t nworkers = pool ? ray_pool_total_workers(pool) : 1; ray_t* counts_block = ray_alloc((size_t)nworkers * sizeof(int64_t)); - if (!counts_block) return 0; + if (!counts_block) goto out; int64_t* counts = (int64_t*)ray_data(counts_block); memset(counts, 0, (size_t)nworkers * sizeof(int64_t)); + ray_scan_fail_t fail; ray_scan_fail_init(&fail); count_compare_ctx_t ctx = { - .col = col, - .rhs = rhs, - .op = op, - .counts = counts, + .col = col, .rhs = rhs, .op = op, .counts = counts, .src = &src, .fail = &fail, }; - int64_t nrows = col->len; - if (pool && nrows >= RAY_PARALLEL_THRESHOLD) - ray_pool_dispatch(pool, count_compare_task, &ctx, nrows); - else - count_compare_task(&ctx, 0, 0, nrows); - + int64_t nrows = src.len; + void (*task)(void*, uint32_t, int64_t, int64_t) = col ? count_compare_task : count_compare_enc_task; + if (!col) ray_col_src_advise(&src, 0, nrows); + bool par = pool && nrows >= RAY_PARALLEL_THRESHOLD; + if (par) ray_pool_dispatch(pool, task, &ctx, nrows); + else task(&ctx, 0, 0, nrows); + ray_t* ferr = ray_scan_fail_finish(&fail, par ? pool : NULL); + if (ferr) { + *err = ferr; + ray_release(counts_block); + ok = -1; + goto out; + } int64_t total = 0; for (uint32_t i = 0; i < nworkers; i++) total += counts[i]; ray_release(counts_block); *out_count = total; - return 1; + atomic_fetch_add_explicit(&g_count_fast, 1, memory_order_relaxed); + ok = 1; +out: + ray_col_src_release(&src); + return ok; } /* A where: value that is not already a BOOL mask of `tn` rows goes through @@ -9480,6 +13520,41 @@ static ray_t* where_mask_spread(ray_t* m, int64_t tn, const char* label) { return ray_where_mask_coerce(m, tn, label); } +/* `where` is an `(and ...)` call of two or more conjuncts. */ +static bool count_where_is_and(ray_t* w) { + if (!w || w->type != RAY_LIST || ray_len(w) < 3) return false; + ray_t* h = ((ray_t**)ray_data(w))[0]; + if (!h || h->type != -RAY_SYM) return false; + ray_t* wn = ray_sym_str(h->i64); + return wn && ray_str_len(wn) == 3 && memcmp(ray_str_ptr(wn), "and", 3) == 0; +} + +/* A conjunct the count shortcut answers as the select does: a nested + * `(and ...)` of such conjuncts, or a compare of a column with a literal the + * single-compare count would take (count_cmp_parse, count_cmp_types_ok), + * plus a numeric literal on a float column. Nullability is not part of the + * shape: a null cell fails every compare in the selection as in the + * select. */ +static bool count_conj_ok(ray_t* tbl, ray_t* e, int depth) { + if (depth > 16) return false; + if (count_where_is_and(e)) { + ray_t** el = (ray_t**)ray_data(e); + for (int64_t i = 1; i < ray_len(e); i++) + if (!count_conj_ok(tbl, el[i], depth + 1)) return false; + return true; + } + count_cmp_op_t op = 0; + ray_t* col = NULL; + ray_t* rhs = NULL; + if (!count_cmp_parse(tbl, e, &op, &col, &rhs)) return false; + ray_col_meta_t cm; + if (!ray_table_col_meta(tbl, col->i64, &cm)) return false; + int8_t type = RAY_IS_PARTED(cm.type) ? (int8_t)RAY_PARTED_BASETYPE(cm.type) : cm.type; + /* a column shorter than the table is a scalar broadcast */ + if (!RAY_IS_PARTED(cm.type) && cm.len != ray_table_nrows(tbl)) return false; + return count_cmp_types_ok(type, op, rhs, true); +} + ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { if (handled) *handled = 0; if (!expr || expr->type != RAY_LIST || ray_len(expr) != 2) return NULL; @@ -9496,15 +13571,6 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { ray_t* from_expr = dict_get(dict, "from"); ray_t* where_expr = dict_get(dict, "where"); if (!from_expr) return NULL; - if (where_expr && where_expr->type == RAY_LIST && ray_len(where_expr) >= 3) { - ray_t** we = (ray_t**)ray_data(where_expr); - if (we[0] && we[0]->type == -RAY_SYM) { - ray_t* wn = ray_sym_str(we[0]->i64); - if (wn && ray_str_len(wn) == 3 && - memcmp(ray_str_ptr(wn), "and", 3) == 0) - return NULL; - } - } int64_t from_id = dict_key_id(dict, "from"); int64_t where_id = dict_key_id(dict, "where"); @@ -9542,8 +13608,26 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { return ray_i64(nrows); } + /* A conjunction is counted off its selection below (the fused + * predicate, else the bool mask), never gathering a column, only when + * every conjunct is whitelisted (count_conj_ok). Anything else (`or`, + * constants, aggregates, arithmetic) is the select's: its optimizer + * folds constants and its chained filters refine what an aggregate + * reads. */ + if (count_where_is_and(where_expr) && !count_conj_ok(tbl, where_expr, 0)) { + ray_release(tbl); + return NULL; + } + int64_t direct_count = 0; - if (try_count_simple_compare(tbl, where_expr, &direct_count)) { + ray_t* cerr0 = NULL; + int dc = try_count_simple_compare(tbl, where_expr, &direct_count, &cerr0); + if (dc < 0) { /* a range read failed: the query's error */ + if (handled) *handled = 1; + ray_release(tbl); + return cerr0; + } + if (dc > 0) { if (handled) *handled = 1; ray_release(tbl); return ray_i64(direct_count); @@ -9557,6 +13641,7 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { ray_op_t* pred = compile_expr_dag(g, where_expr); if (!pred && g->compile_err) { ray_t* cerr = graph_take_compile_err(g); + if (handled) *handled = 1; /* the query's answer: eval.c drops an unhandled one */ ray_graph_free(g); ray_release(tbl); return cerr; @@ -9603,11 +13688,17 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { int64_t pre_nrows = ray_table_nrows(tbl); /* Fused predicate→selection: count directly off the streamed rowsel, - * skipping the full BOOL vec + the BOOL→rowsel scan. Unsupported shapes, - * or >RAY_POOL_MAX_TASKS fall through to exec_node. */ + * skipping the full BOOL vec + the BOOL→rowsel scan. Unsupported shapes + * fall through to exec_node. */ { bool all_pass = false; ray_t* fsel = exec_pred_to_selection(g, pred, pre_nrows, &all_pass); + if (fsel && RAY_IS_ERR(fsel)) { /* a failed bind or range read */ + if (handled) *handled = 1; + ray_graph_free(g); + ray_release(tbl); + return fsel; + } if (all_pass || fsel) { int64_t nrows = pre_nrows; if (fsel) { @@ -9658,37 +13749,52 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { return ray_i64(nrows); } -/* Walk `expr` and collect column-name symbols (unflagged name-ref atoms, - * ATTR_QUOTED clear, that resolve to a real column in `tbl`). Also follows - * the head of dotted names so a `Timestamp.date` reference contributes its - * base column. +static int col_refs_add(int64_t* out_syms, int max_out, int n, int64_t want) { + for (int i = 0; i < n; i++) if (out_syms[i] == want) return n; + if (n < max_out) out_syms[n++] = want; + return n; +} + +/* Walk `expr` and collect the columns of `tbl` it reads: a name reference + * that resolves to a column (the head of a dotted name too, so a + * `Timestamp.date` reference contributes its base column), and a quoted + * symbol naming a column, which a query resolves to that column (the + * literal-column rule, ray_active_query_literal). A named helper's own + * literals reach a query only inlined, wrapped in `(quote ...)` + * (query_inline_walk), and nothing under a quote is evaluated, so a quote + * form contributes nothing. A symbol vector is a column tuple (multi-column + * asc:/desc:/by:) unless `sym_vecs_data`: an aggregate source never holds + * one, so there it is a literal. * `out_syms` is treated as an append-only set (dedup against existing * entries) up to `max_out`; returns the new count. Used to determine - * the subset of input columns the rest of a (select …) clause actually + * the subset of input columns the rest of a (select ...) clause actually * touches, so a prefilter materialise can skip everything else. */ -static int collect_col_refs_set(ray_t* expr, ray_t* tbl, - int64_t* out_syms, int max_out, int n) { +static int collect_col_refs_walk(ray_t* expr, ray_t* tbl, int64_t* out_syms, + int max_out, int n, bool sym_vecs_data) { if (!expr || n >= max_out) return n; - if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { - int64_t want = -1; - if (ray_table_get_col(tbl, expr->i64)) { - want = expr->i64; - } else if (ray_sym_is_dotted(expr->i64)) { + if (expr->type == -RAY_SYM) { + if (expr->attrs & ATTR_QUOTED) + return tbl_has_col(tbl, expr->i64) + ? col_refs_add(out_syms, max_out, n, expr->i64) : n; + if (tbl_has_col(tbl, expr->i64)) + return col_refs_add(out_syms, max_out, n, expr->i64); + if (ray_sym_is_dotted(expr->i64)) { const int64_t* segs; int nsegs = ray_sym_segs(expr->i64, &segs); - if (nsegs >= 1 && ray_table_get_col(tbl, segs[0])) want = segs[0]; - } - if (want >= 0) { - for (int i = 0; i < n; i++) if (out_syms[i] == want) return n; - if (n < max_out) out_syms[n++] = want; + if (nsegs >= 1 && tbl_has_col(tbl, segs[0])) + return col_refs_add(out_syms, max_out, n, segs[0]); } return n; } if (expr->type == RAY_LIST) { ray_t** elems = (ray_t**)ray_data(expr); int64_t cnt = ray_len(expr); + if (cnt == 2 && elems[0] && elems[0]->type == -RAY_SYM && + !(elems[0]->attrs & ATTR_QUOTED) && + elems[0]->i64 == ray_sym_intern("quote", 5)) + return n; for (int64_t i = 0; i < cnt && n < max_out; i++) - n = collect_col_refs_set(elems[i], tbl, out_syms, max_out, n); + n = collect_col_refs_walk(elems[i], tbl, out_syms, max_out, n, sym_vecs_data); return n; } if (expr->type == RAY_DICT) { @@ -9699,26 +13805,108 @@ static int collect_col_refs_set(ray_t* expr, ray_t* tbl, * return the refs gathered so far. */ if (DICT_VIEW_OVERFLOW(dv)) { DICT_VIEW_CLOSE(dv); return n; } for (int64_t i = 0; i + 1 < dv_n && n < max_out; i += 2) - n = collect_col_refs_set(dv[i + 1], tbl, out_syms, max_out, n); + n = collect_col_refs_walk(dv[i + 1], tbl, out_syms, max_out, n, sym_vecs_data); DICT_VIEW_CLOSE(dv); return n; } - if (expr->type == RAY_SYM) { + if (expr->type == RAY_SYM && !sym_vecs_data) { /* Sym vector — each element is a column name (e.g. multi-col * asc:/desc:/by: tuples). Pull syms out at the storage width. */ int64_t len = ray_len(expr); for (int64_t i = 0; i < len && n < max_out; i++) { /* cell-data → runtime name id (column lookup) */ int64_t s = sym_cell_runtime_id(expr, i); - if (ray_table_get_col(tbl, s)) { - int dup = 0; - for (int j = 0; j < n; j++) if (out_syms[j] == s) { dup = 1; break; } - if (!dup && n < max_out) out_syms[n++] = s; - } + if (tbl_has_col(tbl, s)) n = col_refs_add(out_syms, max_out, n, s); + } + return n; + } + return n; +} + +static int collect_col_refs_set(ray_t* expr, ray_t* tbl, + int64_t* out_syms, int max_out, int n) { + return collect_col_refs_walk(expr, tbl, out_syms, max_out, n, false); +} + +/* Can evaluating `e` reach a column of `tbl` only by naming it? True when + * the tree holds nothing but literals (no symbols among them), column names + * and names of global builtins other than eval: a lambda (bound or literal + * body aside, which is walked), a local, a quoted name or an unknown name may + * read query locals by name at run time, so those keep every column bound. */ +static bool expr_reads_named_columns_only(ray_t* e, ray_t* tbl) { + if (!e) return true; + if (e->type == -RAY_SYM) { + if (e->attrs & ATTR_QUOTED) return false; + if (tbl_has_col(tbl, e->i64)) return true; + if (ray_sym_is_dotted(e->i64)) { + const int64_t* segs; + int nsegs = ray_sym_segs(e->i64, &segs); + return nsegs >= 1 && tbl_has_col(tbl, segs[0]); } - return n; + if (ray_env_get_local(e->i64)) return false; + ray_t* fn = ray_env_get(e->i64); + if (!fn || (fn->type != RAY_UNARY && fn->type != RAY_BINARY && fn->type != RAY_VARY)) + return false; + ray_t* nm = ray_sym_str(e->i64); + return !(nm && ray_str_len(nm) == 4 && memcmp(ray_str_ptr(nm), "eval", 4) == 0); } - return n; + if (e->type == RAY_LIST) { + ray_t** el = (ray_t**)ray_data(e); + for (int64_t i = 0; i < ray_len(e); i++) + if (!expr_reads_named_columns_only(el[i], tbl)) return false; + return true; + } + if (e->type < 0) return true; /* a non-symbol atom */ + return ray_is_vec(e) && e->type != RAY_SYM; /* a literal vector */ +} + +/* Bind the columns of `tbl` as query locals for evaluating exprs[0..n): every + * plain column, as always, and an encoded one only when some expression names + * it (collect_col_refs_set) and no expression can reach a column otherwise + * (expr_reads_named_columns_only), so the evaluation decodes just the columns + * it reads. NULL, or the owned error of a column that fails to materialize + * (or of the scratch carve). The caller has pushed the query scope. */ +static ray_t* bind_referenced_columns(ray_t* tbl, ray_t* const* exprs, int64_t n) { + int64_t nc = ray_table_ncols(tbl); + ray_t* refs_hdr = NULL; + int64_t* refs = NULL; + int n_refs = -1; /* collected on the first encoded slot */ + bool narrow = true; + for (int64_t c = 0; c < nc; c++) { + int64_t cn = ray_table_col_name(tbl, c); + if (narrow && ray_table_get_col_enc_idx(tbl, c)) { + if (n_refs < 0) { + for (int64_t e = 0; e < n && narrow; e++) + narrow = expr_reads_named_columns_only(exprs[e], tbl); + } + if (narrow && n_refs < 0) { + refs = (int64_t*)scratch_alloc(&refs_hdr, (size_t)nc * sizeof(int64_t)); + if (!refs) return ray_error("oom", NULL); + n_refs = 0; + for (int64_t e = 0; e < n; e++) + n_refs = collect_col_refs_set(exprs[e], tbl, refs, (int)nc, n_refs); + } + bool named = !narrow; + for (int i = 0; i < n_refs && !named; i++) named = refs[i] == cn; + if (!named) continue; + } + ray_t* cv = ray_table_col_idx(tbl, c); + if (cv && RAY_IS_ERR(cv)) { scratch_free(refs_hdr); return cv; } + if (cv) ray_env_set_query_local(cn, cv); + } + scratch_free(refs_hdr); + return NULL; +} + +/* bind_referenced_columns with bind_all_columns' contract: publishes `tbl` + * as the active query table and returns the previous one (the caller + * restores it after the matching ray_env_pop_scope); `*err` is the owned + * error of a column that failed to materialize, else NULL. */ +static ray_t* bind_referenced_query(ray_t* tbl, ray_t* const* exprs, int64_t n, ray_t** err) { + ray_t* prev = g_active_query_table; + g_active_query_table = tbl; + *err = bind_referenced_columns(tbl, exprs, n); + return prev; } /* Build a narrow projection of `src_tbl` containing only the columns in @@ -9731,7 +13919,7 @@ static ray_t* project_table_cols(ray_t* src_tbl, const int64_t* keep_syms, ray_t* nt = ray_table_new(n_keep); if (!nt || RAY_IS_ERR(nt)) return nt ? nt : ray_error("oom", NULL); for (int i = 0; i < n_keep; i++) { - ray_t* col = ray_table_get_col(src_tbl, keep_syms[i]); + ray_t* col = ray_table_slot(src_tbl, keep_syms[i]); /* the slot object: an encoded column stays encoded */ if (!col) { ray_release(nt); return ray_error("domain", "select: projected column not found"); } ray_t* nt2 = ray_table_add_col(nt, keep_syms[i], col); if (!nt2 || RAY_IS_ERR(nt2)) { @@ -9897,23 +14085,23 @@ static int filt_compact_keep(ray_t* dict, ray_t* by_expr, ray_t* tbl, int64_t nk = ray_len(by_expr); const int64_t* key_syms = (const int64_t*)ray_data(by_expr); for (int64_t k = 0; k < nk; k++) { /* (d) keys */ - ray_t* kc = ray_table_get_col(tbl, key_syms[k]); - if (!kc) return 0; - switch (kc->type) { + ray_col_meta_t kcm; + if (!ray_table_col_meta(tbl, key_syms[k], &kcm)) return 0; + switch (kcm.type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: case RAY_SYM: case RAY_STR: break; + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: case RAY_STR: break; default: return 0; } } int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { /* (d) all source columns */ - ray_t* cc = ray_table_get_col_idx(tbl, c); - if (!cc) return 0; - switch (cc->type) { + ray_col_meta_t ccm; + if (!ray_table_col_meta_idx(tbl, c, &ccm)) return 0; + switch (ccm.type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: case RAY_SYM: case RAY_F64: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: case RAY_F64: case RAY_GUID: case RAY_STR: case RAY_LIST: break; default: return 0; } @@ -9939,6 +14127,99 @@ static int filt_compact_keep(ray_t* dict, ray_t* by_expr, ray_t* tbl, return n; } +/* The bound eval_group_keep's set can never exceed: every column of `tbl` + * plus the published proj_keep entries (which need not be columns). */ +static int64_t eval_group_keep_cap(ray_t* tbl) { + ray_vm_t* vm = __VM; + return ray_table_ncols(tbl) + (vm ? vm->proj_keep_n : 0) + 1; +} + +/* Can every column `e` reads be named (expr_reads_named_columns_only)? + * A by-dict is judged by its values. */ +static bool eval_group_keep_ok(ray_t* e, ray_t* tbl) { + if (e && e->type == RAY_DICT) { /* a by-dict: its values */ + ray_t* vals = ray_dict_vals(e); + if (!vals || vals->type != RAY_LIST) return false; + ray_t** v = (ray_t**)ray_data(vals); + for (int64_t i = 0; i < ray_len(vals); i++) + if (!expr_reads_named_columns_only(v[i], tbl)) return false; + return true; + } + return expr_reads_named_columns_only(e, tbl); +} + +/* Filter-compaction keep-set for a grouped select whose where: runs as its + * own filter before the group (#769): every eval-level group but the one + * filt_compact_keep serves, and the DAG group's materialize path (a + * count(distinct) output over a parted table). A group with outputs + * reads the filtered table through its by: and its outputs only — take:, + * asc: and desc: order and cut the grouped result, whose columns are the + * keys and the outputs — so the filter need only gather the columns those + * expressions name: the by-keys and the column refs of every output + * expression (collect_col_refs_set). An output whose reads cannot be + * named (a lambda, a local, a quoted name, eval — + * expr_reads_named_columns_only) keeps every column. + * + * The implicit-all group (no outputs) emits the first of every column, so + * it keeps every column unless, exactly as filt_compact_keep requires, a + * projection hint is active at this depth (proj_keep names what the + * consumer reads) AND the select has no clause but from/where/by: a take:, + * asc: or desc: there sorts or cuts by columns the consumer never names + * (and a group with them is not the shape the hint describes). Under + * those conditions the set is keys ∪ proj_keep. + * + * Returns the deduped keep count, or 0 (carry all). `max` is + * eval_group_keep_cap(tbl): the keys and refs are distinct columns of + * `tbl` (at most ncols together, the dedup set is shared) and proj_keep + * adds at most proj_keep_n, so n stays below max; should it ever reach max + * a column may have been dropped, and the set is declined (carry all). */ +static int eval_group_keep(ray_t* dict, ray_t* by_expr, ray_t* tbl, int64_t n_out, + int64_t from_id, int64_t where_id, int64_t by_id, + int64_t take_id, int64_t asc_id, int64_t desc_id, + int64_t* out, int max) { + ray_vm_t* vm = __VM; + bool hint = vm && vm->proj_active && vm->eval_depth == vm->proj_depth + 1; + if (n_out == 0 && !hint) return 0; /* first of every column */ + DICT_VIEW_DECL(pv); + DICT_VIEW_OPEN(dict, pv); + if (DICT_VIEW_OVERFLOW(pv)) { DICT_VIEW_CLOSE(pv); return 0; } + if (n_out == 0) { /* only from/where/by */ + for (int64_t i = 0; i + 1 < pv_n; i += 2) { + int64_t kid = pv[i]->i64; + if (kid != from_id && kid != where_id && kid != by_id) { DICT_VIEW_CLOSE(pv); return 0; } + } + } + int n = 0; + if (by_expr && by_expr->type == RAY_SYM) { /* by: [k1 k2 …] */ + int64_t nk = ray_len(by_expr); + for (int64_t k = 0; k < nk && n < max; k++) { + int64_t s = sym_cell_runtime_id(by_expr, k); + if (!tbl_has_col(tbl, s)) { DICT_VIEW_CLOSE(pv); return 0; } /* a key made later: carry all */ + bool dup = false; + for (int j = 0; j < n; j++) if (out[j] == s) { dup = true; break; } + if (!dup) out[n++] = s; + } + } else { + if (!eval_group_keep_ok(by_expr, tbl)) { DICT_VIEW_CLOSE(pv); return 0; } + n = collect_col_refs_set(by_expr, tbl, out, max, n); + } + for (int64_t i = 0; i + 1 < pv_n; i += 2) { + int64_t kid = pv[i]->i64; + if (kid == from_id || kid == where_id || kid == by_id || + kid == take_id || kid == asc_id || kid == desc_id) continue; + if (!eval_group_keep_ok(pv[i + 1], tbl)) { DICT_VIEW_CLOSE(pv); return 0; } + n = collect_col_refs_set(pv[i + 1], tbl, out, max, n); + } + DICT_VIEW_CLOSE(pv); /* pv dead past the clause scan */ + for (int j = 0; hint && j < vm->proj_keep_n && n < max; j++) { + int64_t s = vm->proj_keep[j]; + bool dup = false; + for (int q = 0; q < n; q++) if (out[q] == s) { dup = true; break; } + if (!dup) out[n++] = s; + } + return n < max ? n : 0; /* a full buffer may have dropped one */ +} + /* Materialize pure temporal arithmetic with the unit-aware evaluator once, * then let the normal typed GROUP pipeline reduce that column. The expression * DAG's raw integer arithmetic remains guarded for mixed temporal units. */ @@ -9946,8 +14227,9 @@ static bool temporal_materialize_pure(ray_t* expr, ray_t* tbl) { if (!expr) return false; if (ray_is_atom(expr)) { if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { - ray_t* col = ray_table_get_col(tbl, expr->i64); - return col && !RAY_IS_PARTED(col->type) && col->type != RAY_MAPCOMMON; + ray_col_meta_t cm; + return ray_table_col_meta(tbl, expr->i64, &cm) && + !RAY_IS_PARTED(cm.type) && cm.type != RAY_MAPCOMMON; } return true; } @@ -9960,7 +14242,7 @@ static bool temporal_materialize_pure(ray_t* expr, ray_t* tbl) { return (c == '+' || c == '-' || c == '*') && temporal_materialize_pure(es[1], tbl) && temporal_materialize_pure(es[2], tbl); } -static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { +static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl, unsigned plan) { if (!dict_get(dict, "by")) return NULL; ray_t* vals = ray_dict_vals(dict); ray_t* keys = ray_dict_keys(dict); @@ -9981,8 +14263,9 @@ static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { if (arg >= expr->len || !expr_contains_temporal_arith(es[arg], tbl) || !temporal_materialize_pure(es[arg], tbl)) continue; if (ray_env_push_query_scope() != RAY_OK) goto oom; - ray_t* previous = bind_all_columns(tbl); - ray_t* value = ray_eval(es[arg]); + ray_t* bind_err_ = NULL; + ray_t* previous = bind_all_columns(tbl, &bind_err_); + ray_t* value = bind_err_ ? bind_err_ : ray_eval(es[arg]); g_active_query_table = previous; ray_env_pop_scope(); if (value && !RAY_IS_ERR(value) && ray_is_lazy(value)) value = ray_lazy_materialize(value); @@ -9998,7 +14281,7 @@ static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { do { int len = snprintf(name, sizeof(name), "_temporal_agg_%u", seq++); sym = ray_sym_intern(name, (size_t)len); - } while (ray_table_get_col(extended, sym)); + } while (tbl_has_col(extended, sym)); extended = ray_table_add_col(extended, sym, value); ray_release(value); MAT_CHECK(extended); if (!replacement) { @@ -10028,7 +14311,7 @@ static ray_t* try_temporal_group_materialize(ray_t* dict, ray_t* tbl) { rewritten = ray_dict_upsert(rewritten, from, extended); ray_release(from); ray_release(extended); extended = NULL; MAT_CHECK(rewritten); - ray_t* result = ray_select_impl(&rewritten, 1, true); + ray_t* result = ray_select_impl(&rewritten, 1, plan | SELECT_ALIASES_RESOLVED); ray_release(rewritten); return result; oom: @@ -10075,7 +14358,8 @@ static ray_t* select_fallback_bind_alias(ray_t* tbl, int64_t kid, ray_t* col) { ray_t* t2 = ray_cow(tbl); /* a failed copy leaves `tbl` untouched */ if (!t2 || RAY_IS_ERR(t2)) { ray_release(tbl); return t2; } ray_table_set_col_idx(t2, c, col); - if (ray_table_get_col_idx(t2, c) != col) { ray_release(t2); return ray_error("oom", NULL); } + /* Slot objects on both sides: an encoded column is its own slot. */ + if (ray_table_slot_idx(t2, c) != col) { ray_release(t2); return ray_error("oom", NULL); } return t2; } return ray_table_add_col(tbl, kid, col); @@ -10111,7 +14395,8 @@ static ray_t* select_fallback_finish_columns(ray_t* result, uint32_t* scalar_col int64_t nrows) { for (int64_t c = 0; c < ray_table_ncols(result); c++) { if (!scalar_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(result, c); + ray_t* col = ray_table_col_idx(result, c); /* a computed column: plain */ + if (!col || RAY_IS_ERR(col)) { ray_release(result); return col ? col : ray_error("domain", "select: lost a column"); } ray_retain(col); ray_t* wide = select_fallback_broadcast(col, nrows); if (!wide || RAY_IS_ERR(wide)) { @@ -10186,9 +14471,9 @@ static int select_fallback_scalar_proj(ray_t* expr, const int64_t* scalars, int6 (via || ray_is_atom(expr)); } -static bool select_alias_head_is_agg(ray_t* head) { +static bool select_alias_head_is_agg(ray_t* head, int64_t nargs) { if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; - if (resolve_agg_opcode(head->i64) != 0) return true; + if (resolve_agg_call_opcode(head->i64, nargs) != 0) return true; ray_t* s = ray_sym_str(head->i64); return s && ray_str_len(s) == 8 && memcmp(ray_str_ptr(s), "distinct", 8) == 0; } @@ -10283,7 +14568,7 @@ static bool select_expr_reads_col(ray_t* expr, ray_t* tbl, const int64_t* shadow if (!expr) return false; if (expr->type == -RAY_SYM) { for (int i = 0; i < n_shadow; i++) if (shadow[i] == expr->i64) return false; - return ray_table_get_col(tbl, expr->i64) != NULL; + return tbl_has_col(tbl, expr->i64); } if (expr->type != RAY_LIST || expr->len < 1) return false; ray_t** el = (ray_t**)ray_data(expr); @@ -10376,7 +14661,7 @@ static ray_t* select_where_shield_alias_literals(ray_t* e, void* vctx) { for (int64_t i = 0; i < c->nk && !names_alias; i++) { ray_t* k = c->d_elems[i * 2]; names_alias = k && k->type == -RAY_SYM && k->i64 == e->i64 && - !ray_table_get_col(c->tbl, k->i64); + !ray_table_has_col(c->tbl, k->i64); } if (!names_alias) { ray_retain(e); return e; } ray_t* head = ray_sym(ray_sym_intern("quote", 5)); @@ -10480,7 +14765,7 @@ static ray_t* select_alias_subst(ray_t* expr, void* vctx) { for (int i = 0; i < c->n_shadow; i++) if (c->shadow[i] == expr->i64) { ray_retain(expr); return expr; } /* inside an aggregate's argument a source column is the source column */ - if (c->in_agg && ray_table_get_col(c->tbl, expr->i64)) { ray_retain(expr); return expr; } + if (c->in_agg && tbl_has_col(c->tbl, expr->i64)) { ray_retain(expr); return expr; } for (int i = c->n_alias - 1; i >= 0; i--) { if (c->names[i] != expr->i64) continue; if (c->kinds[i] == SEL_ALIAS_GROUP) { @@ -10499,7 +14784,7 @@ static ray_t* select_alias_subst(ray_t* expr, void* vctx) { return c->exprs[i]; } if (!c->in_agg && !select_sym_in(expr->i64, c->keys, c->n_keys) && - ray_table_get_col(c->tbl, expr->i64)) c->refs_row = true; + tbl_has_col(c->tbl, expr->i64)) c->refs_row = true; ray_retain(expr); return expr; } if (expr->type != RAY_LIST || expr->len < 1) { ray_retain(expr); return expr; } @@ -10520,7 +14805,7 @@ static ray_t* select_alias_subst(ray_t* expr, void* vctx) { return out; } select_alias_subst_ctx_t inner = *c; - inner.in_agg = c->in_agg || select_alias_head_is_agg(el[0]); + inner.in_agg = c->in_agg || select_alias_head_is_agg(el[0], ray_len(expr) - 1); /* a call whose head is itself a form — `((fn [x] …) 1)` — is walked * from the head, which is where such a lambda's body lives */ ray_t* out = select_alias_map_list(expr, el[0]->type == RAY_LIST ? 0 : 1, @@ -10815,7 +15100,7 @@ static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan for (int64_t i = 0; i + 1 < dv_n && laid_out; i += 2) { int64_t cn = dv[i]->i64; if (cn == from_id || cn == where_id || cn == by_id || cn == take_id || cn == asc_id || cn == desc_id || cn == nearest_id) continue; - if (!ray_table_get_col(result, cn)) continue; /* folded away */ + if (!ray_table_has_col(result, cn)) continue; /* folded away */ want++; while (c < ncols && ray_table_col_name(result, c) != cn) { /* a key: must not be named like any output */ @@ -10848,14 +15133,14 @@ static ray_t* select_apply_derived(ray_t* result, ray_t* dict, select_alias_plan for (int64_t c2 = c + 1; c2 < ncols && last; c2++) if (ray_table_col_name(result, c2) == cn) last = false; if ((is_output && last) || is_hidden) continue; - out = ray_table_add_col(out, cn, ray_table_get_col_idx(result, c)); + out = ray_table_add_col(out, cn, ray_table_slot_idx(result, c)); } for (int64_t i = 0; i + 1 < dv_n && out && !RAY_IS_ERR(out); i += 2) { int64_t cn = dv[i]->i64; if (cn == from_id || cn == where_id || cn == by_id || cn == take_id || cn == asc_id || cn == desc_id || cn == nearest_id) continue; - ray_t* col = NULL; + ray_t* col = NULL; /* the slot object, encoded or plain */ for (int64_t c = ncols - 1; c >= 0 && !col; c--) - if (ray_table_col_name(result, c) == cn) col = ray_table_get_col_idx(result, c); + if (ray_table_col_name(result, c) == cn) col = ray_table_slot_idx(result, c); if (!col) continue; /* an output the engine folded away (e.g. a key projection) */ out = ray_table_add_col(out, cn, col); } @@ -10945,7 +15230,7 @@ static void scan_gate_conjunct(select_scan_t* ss, ray_t* e, ray_t* tbl) { else if (fl == 6 && memcmp(f, "within", 6) == 0) op = G_WITHIN; else return; if (!el[1] || el[1]->type != -RAY_SYM || (el[1]->attrs & ATTR_QUOTED)) return; - ray_t* col = ray_table_get_col(tbl, el[1]->i64); + ray_t* col = tbl_plain_col(tbl, el[1]->i64); /* generation 2 reads by range */ if (!col || !ray_is_vec(col) || col->len != ss->scan.rows) return; int8_t ct = col->type; if (!scan_gate_int_type(ct) && !scan_gate_temporal(ct)) return; @@ -11078,12 +15363,12 @@ ray_t* query_cd_gate_where_rows(ray_t* tbl, ray_t* where_expr, int64_t n_table, if (!syms) return NULL; int n_ref = collect_col_refs_set(where_expr, tbl, syms, (int)ncols_max, 0); for (int i = 0; i < n_ref; i++) { - ray_t* c = ray_table_get_col(tbl, syms[i]); + ray_t* c = tbl_plain_col(tbl, syms[i]); /* an encoded column declines */ if (!c || RAY_IS_ERR(c) || RAY_IS_PARTED(c->type) || c->type == RAY_MAPCOMMON || c->len < n_table) { n_ref = 0; break; } switch (c->type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: - case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_F64: case RAY_F32: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: case RAY_F32: case RAY_SYM: break; default: n_ref = 0; break; } @@ -11108,7 +15393,7 @@ ray_t* query_cd_gate_where_rows(ray_t* tbl, ray_t* where_expr, int64_t n_table, for (int64_t ch = 0; ch < nch; ch++) if ((ss.scan.gate[ch >> 6] >> (ch & 63)) & 1) pass[n_pass++] = (uint32_t)ch; if (n_pass == nch) { - scratch_free(pass_hdr); pass = NULL; /* nothing ruled out */ + scratch_free(pass_hdr); pass_hdr = NULL; pass = NULL; /* nothing ruled out; freed once (#898) */ } else { P = n_pass << lg; if (n_pass > 0 && pass[n_pass - 1] == (uint32_t)(nch - 1)) @@ -11148,7 +15433,7 @@ ray_t* query_cd_gate_where_rows(ray_t* tbl, ray_t* where_expr, int64_t n_table, uint8_t* esz = gv_mem + (size_t)n_ref * (sizeof(ray_t*) + sizeof(void*) * 2); int n_g = 0; for (int i = 0; i < n_ref; i++) { - ray_t* c = ray_table_get_col(tbl, syms[i]); + ray_t* c = tbl_plain_col(tbl, syms[i]); /* the pages the sampled rows fall on, asked for ahead of the reads */ ray_col_want_rows(c, idx, n_s); /* a SYM column at its own code width: ray_vec_new would make a @@ -11269,14 +15554,14 @@ static void select_scan_register(ray_t** args, ray_t* dict, ray_t* tbl, ray_t* w } DICT_VIEW_CLOSE(pv); for (int i = 0; i < nw; i++) - exec_scan_add_col(&ss->scan, ray_table_get_col(tbl, wsyms[i])); + exec_scan_add_col(&ss->scan, tbl_plain_col(tbl, wsyms[i])); int64_t nrows = ray_table_nrows(tbl); bool rows_set = ss->scan.rows >= 0; if (!rows_set) ss->scan.rows = nrows; /* the gate is sized by it */ if (where) scan_gate_where(ss, where, tbl, 0); bool defer = where && !ss->scan.gate; for (int i = 0; i < n; i++) - exec_scan_add_col(defer ? &ss->defer : &ss->scan, ray_table_get_col(tbl, syms[i])); + exec_scan_add_col(defer ? &ss->defer : &ss->scan, tbl_plain_col(tbl, syms[i])); /* Once every column is in: the gate's cached ones are not requested. */ if (ss->scan.gate) scan_gate_drop_cached(&ss->scan); /* A column the filter also reads is requested with it. */ @@ -11376,7 +15661,7 @@ ray_t* ray_select(ray_t** args, int64_t n) { select_scan_t* prev_ss = t_select_scan; const ray_pool_scan_t* prev_scan = ray_pool_scan_get(); t_select_scan = &ss; - ray_t* r = ray_select_impl(args, n, false); + ray_t* r = ray_select_impl(args, n, 0); t_select_scan = prev_ss; ray_pool_scan_set(prev_scan); if (ss.gate_hdr) scratch_free(ss.gate_hdr); @@ -11442,7 +15727,60 @@ static bool sym_names_col(ray_t* tbl, int64_t s) { head = segs[0]; } if (ray_env_get_lexical_local(head)) return false; - return ray_table_get_col(tbl, head) != NULL; + return tbl_has_col(tbl, head); +} + +/* Does clause `v`, run on one partition's segment of the parted table + * `tbl`, give that segment's rows of what it gives on the whole table, so + * the per-segment sort/take and asof routes may run it partition by + * partition? The DAG decides: `v` is compiled into a scratch graph over + * `tbl` (compile_expr_dag) and the executor's streaming admission + * (dag_can_stream) must accept it: row-wise ops over the table's columns + * and scalar constants. A lexical local or a global compiles to a + * constant, so a vector of any length (a mask of the table's or of one + * partition's rows, a projected vector) is refused, as are an aggregate, a + * scan, a moving window, a form the compiler does not lower (a nested + * query, `til`, `rand`, `eval`, a computed callee, a closure, a dict path) + * and a helper whose inlined body holds one of them. Two things that + * admission cannot tell are settled here: + * - the set of `in`/`not-in` is no row operand: a constant set (a + * membership list of any length) reads the same on every segment and + * is admitted, while a set computed over the columns would be one + * partition's on each segment and is refused (the admission walks the + * set as an elementwise operand); + * - a clause that compiles to one scalar constant (a literal, a local or + * global atom) is the same on every segment and is admitted (the + * admission refuses a graph that scans no column, since the executor's + * streaming would repeat such a result per partition). */ +static bool clause_streams_per_segment(ray_t* v, ray_t* tbl) { + if (!v || RAY_IS_ERR(v) || !tbl || tbl->type != RAY_TABLE) return false; + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return false; + ray_op_t* root = compile_expr_dag(g, v); + bool ok = root != NULL; + uint32_t root_id = ok ? root->id : 0; + if (ok && root->opcode == OP_CONST) { + ray_op_ext_t* ext = find_ext(g, root_id); + ok = ext && ext->literal && ray_is_atom(ext->literal); + ray_graph_free(g); + return ok; + } + /* The scalar a constant set is swapped for, made before the loop + * takes node pointers (a new node may move g->nodes). */ + ray_op_t* unit = ok ? ray_const_bool(g, true) : NULL; + ok = unit != NULL; + uint32_t unit_id = ok ? unit->id : 0; + for (uint32_t i = 0; ok && i < g->node_count; i++) { + ray_op_t* op = &g->nodes[i]; + if ((op->opcode != OP_IN && op->opcode != OP_NOT_IN) || op->arity < 2) continue; + ray_op_t* set = op_child(g, op, 1); + if (!set) ok = false; + else if (set->opcode == OP_CONST) op->in_id[1] = unit_id; + else if (dag_can_stream(g, set)) ok = false; /* a set over the rows */ + } + ok = ok && dag_can_stream(g, &g->nodes[root_id]); + ray_graph_free(g); + return ok; } static bool clause_runs_code_in(ray_t* v, ray_t* tbl, bool containers); @@ -11487,8 +15825,16 @@ static bool parted_clauses_plain(ray_t* dict, ray_t* tbl); /* The columns of a parted table a select reads, flattened: every column a * clause names, in the table's order; the whole table when a clause runs - * code whose column reads it does not show, or names no column. */ -static ray_t* parted_flatten_read_cols(ray_t* dict, ray_t* tbl) { + * code whose column reads it does not show. When the clauses name no + * column, the whole table too, unless `keep_unread`: then `tbl` itself, + * retained, since nothing in the select reads a column of it. `also`, a + * symbol or symbol vector or NULL, names columns kept beside those: the + * group keys a by-dict has added under their aliases, which no clause + * names. When every one of them is a column, a by-dict's values have been + * evaluated into them, so the source columns those values name are read + * only if another clause names them too. */ +static ray_t* parted_flatten_read_cols(ray_t* dict, ray_t* tbl, bool keep_unread, + ray_t* also) { int64_t nc = ray_table_ncols(tbl); ray_t* keys = ray_dict_keys(dict); ray_t* vals = ray_dict_vals(dict); @@ -11498,26 +15844,43 @@ static ray_t* parted_flatten_read_cols(ray_t* dict, ray_t* tbl) { int64_t id_from = ray_sym_intern("from", 4); int64_t refs[256]; int nref = 0; + int64_t id_by = ray_sym_intern("by", 2); + int64_t nalso = also && also->type == -RAY_SYM ? 1 : (also && also->type == RAY_SYM ? also->len : 0); + bool also_cols = nalso > 0; + for (int64_t j = 0; j < nalso; j++) { + int64_t s = also->type == -RAY_SYM ? also->i64 : sym_cell_runtime_id(also, j); + bool seen = false; + for (int r = 0; r < nref; r++) seen |= refs[r] == s; + if (!tbl_has_col(tbl, s)) { also_cols = false; continue; } + if (!seen && nref < 256) refs[nref++] = s; + } for (int64_t i = 0; i < ray_dict_len(dict); i++) { - if (sym_cell_runtime_id(keys, i) == id_from) continue; + int64_t kid = sym_cell_runtime_id(keys, i); + if (kid == id_from) continue; ray_t* v = ((ray_t**)ray_data(vals))[i]; + if (kid == id_by && also_cols && v && v->type == RAY_DICT) continue; int64_t nsym = v && v->type == -RAY_SYM ? 1 : (v && v->type == RAY_SYM ? v->len : 0); for (int64_t j = 0; j < nsym; j++) { /* a sort key, quoted or not */ int64_t s = v->type == -RAY_SYM ? v->i64 : sym_cell_runtime_id(v, j); bool seen = false; for (int r = 0; r < nref; r++) seen |= refs[r] == s; - if (!seen && nref < 256 && ray_table_get_col(tbl, s)) refs[nref++] = s; + if (!seen && nref < 256 && tbl_has_col(tbl, s)) refs[nref++] = s; } if (nsym == 0) nref = collect_col_refs_set(v, tbl, refs, 256, nref); } - if (nref == 0) return query_materialize_parted_table(tbl); + if (nref == 0) { + if (!keep_unread) return query_materialize_parted_table(tbl); + ray_retain(tbl); + return tbl; + } ray_t* out = ray_table_new(nref); for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { int64_t cn = ray_table_col_name(tbl, c); bool want = false; for (int r = 0; r < nref; r++) want |= refs[r] == cn; if (!want) continue; - ray_t* v = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + ray_t* v = ray_table_col_idx(tbl, c); + if (v && !RAY_IS_ERR(v)) v = query_materialize_parted_col(v, tbl); if (!v || RAY_IS_ERR(v)) { ray_release(out); return v ? v : ray_error("oom", NULL); } out = ray_table_add_col(out, cn, v); ray_release(v); @@ -11557,7 +15920,7 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam * hidden column named after the expression. */ ray_t* keyed = NULL; /* the (filtered) source plus the evaluated key column */ bool where_applied = false; - if (!ray_table_get_col(tbl, hidden)) { + if (!tbl_has_col(tbl, hidden)) { ray_graph_t* g = ray_graph_new(tbl); bool lowered = g && compile_expr_dag(g, by_expr) != NULL; if (g) ray_graph_free(g); @@ -11583,7 +15946,7 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam if (fv && !RAY_IS_ERR(fv)) fv = ray_list_append(fv, where_expr); ray_t* fdict = ray_dict_new(fk, fv); if (!fdict || RAY_IS_ERR(fdict)) { ray_release(base); return fdict ? fdict : ray_error("oom", NULL); } - ray_t* filtered = ray_select_impl(&fdict, 1, true); + ray_t* filtered = ray_select_impl(&fdict, 1, SELECT_ALIASES_RESOLVED); ray_release(fdict); if (filtered && !RAY_IS_ERR(filtered) && ray_is_lazy(filtered)) filtered = ray_lazy_materialize(filtered); if (!filtered || RAY_IS_ERR(filtered)) { ray_release(base); return filtered ? filtered : ray_error("oom", NULL); } @@ -11605,7 +15968,7 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam any_out = !rsv; } if (!any_out) { ray_release(base); return NULL; } - ray_t* flat = parted_flatten_read_cols(dict, base); + ray_t* flat = parted_flatten_read_cols(dict, base, false, NULL); ray_release(base); if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); base = flat; @@ -11663,7 +16026,7 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam if (is_decomposable_agg_compound(v, tbl)) continue; needs_eval = true; } - if (!needs_eval || ray_table_get_col(tbl, hidden)) return NULL; + if (!needs_eval || tbl_has_col(tbl, hidden)) return NULL; /* The hidden key is the expression itself, grouped by the engine, or * the evaluated column, grouped as a plain column of that name. */ @@ -11729,6 +16092,108 @@ static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_nam return engine; } +/* A literal of value `v` for a query dict: a symbol is quoted, so it is + * not read as a name. Consumes `v`. */ +static ray_t* select_literal_of(ray_t* v) { + if (!v || RAY_IS_ERR(v) || v->type != -RAY_SYM) return v; + ray_t* q = ray_sym(v->i64); + ray_release(v); + if (q && !RAY_IS_ERR(q)) q->attrs |= ATTR_QUOTED; + return q; +} + +/* A grouped aggregate whose source reads no column and has no DAG node + * (`(sum (at [1 2 3] 0))`, `(sum (til 5))`) has one value whatever the + * row. It is evaluated once, here, and the select planned with what it + * gave: a scalar stands for every row, as `1` in `(sum 1)` does, so the + * output becomes `(agg )`, which the engine folds over each + * group's rows; a collection is aggregated as it stands, as without by:, + * and its aggregate is the same in every group, a literal output (or, a + * collection itself, the aggregate over the quoted value). The table + * already evaluated is the new from:, and the select runs again with + * SELECT_COLUMN_FREE_PLANNED, so each source is evaluated once. NULL when + * no output has that shape. */ +static ray_t* select_plan_column_free_aggs(ray_t* dict, ray_t* tbl) { + if (!dict_get(dict, "by")) return NULL; + ray_t* keys = ray_dict_keys(dict); + ray_t* vals = ray_dict_vals(dict); + if (!keys || keys->type != RAY_SYM || !vals || vals->type != RAY_LIST) return NULL; + static const char* const reserved[] = { "from", "where", "by", "take", "asc", "desc", "nearest" }; + int64_t rid[7]; + for (int i = 0; i < 7; i++) rid[i] = ray_sym_intern(reserved[i], strlen(reserved[i])); + ray_t* engine = NULL; + int64_t nd = ray_dict_len(dict); + for (int64_t i = 0; i < nd; i++) { + int64_t kid = sym_cell_runtime_id(keys, i); + bool clause = false; + for (int r = 0; r < 7; r++) clause |= kid == rid[r]; + if (clause) continue; + ray_t* v = ((ray_t**)ray_data(vals))[i]; + if (!is_agg_expr(v) || ray_len(v) != 2) continue; + ray_t** el = (ray_t**)ray_data(v); + ray_t* fn_obj = ray_env_get(el[0]->i64); + if (!fn_obj || fn_obj->type != RAY_UNARY) continue; + ray_t* src = query_inline_helpers(el[1], tbl); + if (!src || RAY_IS_ERR(src)) { if (engine) ray_release(engine); return src ? src : ray_error("oom", NULL); } + bool take = src->type == RAY_LIST && !expr_contains_agg(src) && expr_reads_no_column(src, tbl); + if (take) { + ray_graph_t* pg = ray_graph_new(tbl); + take = pg && compile_expr_dag(pg, src) == NULL; + if (pg) ray_graph_free(pg); + } + if (!take) { ray_release(src); continue; } + ray_t* val = eval_expr_whole_column_impl(src, tbl); + ray_release(src); + if (!val || RAY_IS_ERR(val)) { if (engine) ray_release(engine); return val ? val : ray_error("oom", NULL); } + ray_t* out; + if (ray_is_atom(val)) { + ray_t* lit = select_literal_of(val); + out = lit && !RAY_IS_ERR(lit) ? ray_list_new(2) : lit; + if (out && !RAY_IS_ERR(out)) out = ray_list_append(out, el[0]); + if (out && !RAY_IS_ERR(out)) out = ray_list_append(out, lit); + if (lit && !RAY_IS_ERR(lit)) ray_release(lit); + } else { + ray_t* agg = ((ray_unary_fn)(uintptr_t)fn_obj->i64)(val); + if (agg && !RAY_IS_ERR(agg) && ray_is_lazy(agg)) agg = ray_lazy_materialize(agg); + if (agg && !RAY_IS_ERR(agg) && !ray_is_atom(agg)) { + /* An aggregate with a collection result is no one value + * per group: the output stays the aggregate, planned as + * any other, over the value already made, quoted so that + * nothing evaluates the source again (each group takes + * the quote). A vector quoted would be a vector constant, + * which stands for a column: a vector's aggregate is an + * atom, so none comes here, but should one, its output + * keeps the source. */ + ray_release(agg); + if (ray_is_vec(val)) { ray_release(val); continue; } + ray_t* q = query_quote_value(val); + ray_release(val); + out = q ? ray_list_new(2) : ray_error("oom", NULL); + if (out && !RAY_IS_ERR(out)) out = ray_list_append(out, el[0]); + if (out && !RAY_IS_ERR(out)) out = ray_list_append(out, q); + if (q) ray_release(q); + } else { + ray_release(val); + out = select_literal_of(agg); + } + } + if (!out || RAY_IS_ERR(out)) { if (engine) ray_release(engine); return out ? out : ray_error("oom", NULL); } + if (!engine) { engine = dict; ray_retain(engine); } + ray_t* k = ray_sym(kid); + if (!k || RAY_IS_ERR(k)) { ray_release(out); ray_release(engine); return k ? k : ray_error("oom", NULL); } + engine = ray_dict_upsert(engine, k, out); + ray_release(k); + ray_release(out); + if (!engine || RAY_IS_ERR(engine)) return engine ? engine : ray_error("oom", NULL); + } + if (!engine) return NULL; + ray_t* k_from = ray_sym(rid[0]); + if (!k_from || RAY_IS_ERR(k_from)) { ray_release(engine); return k_from ? k_from : ray_error("oom", NULL); } + engine = ray_dict_upsert(engine, k_from, tbl); + ray_release(k_from); + return engine ? engine : ray_error("oom", NULL); +} + /* Names the hidden key column of a select_plan_computed_key result. */ static ray_t* select_name_computed_key(ray_t* r, int64_t key_name) { if (r && !RAY_IS_ERR(r) && ray_is_lazy(r)) r = ray_lazy_materialize(r); @@ -11748,13 +16213,427 @@ static ray_t* select_name_computed_key(ray_t* r, int64_t key_name) { ray_t* out = ray_table_new(nc); for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { if (c != key_at && ray_table_col_name(r, c) == key_name) continue; - out = ray_table_add_col(out, ray_table_col_name(r, c), ray_table_get_col_idx(r, c)); + out = ray_table_add_col(out, ray_table_col_name(r, c), ray_table_slot_idx(r, c)); /* encoded or plain, not decoded */ } if (!out || RAY_IS_ERR(out)) { ray_release(r); return out ? out : ray_error("oom", NULL); } ray_release(r); return out; } +/* The update sub-table evaluation (and select's partition pruning) is only + * equivalent to the whole-table evaluation for elementwise expressions. + * Accept a call only when its head resolves to a builtin flagged + * RAY_FN_ATOMIC and every argument is a column of `tbl`, a literal, a + * quoted symbol, or such a call. A bare symbol that is not a column (a + * free variable, possibly a table-length vector), an order-dependent + * function (deltas, sums, ...), an aggregate, a special form, or a lambda + * call is not elementwise. `meta_cols` (select): columns are found from + * metadata, never fetched, and a name bound as a lexical local (which + * shadows the column) is not a column. */ +static bool update_expr_elementwise(ray_t* e, ray_t* tbl, bool meta_cols) { + if (!e || RAY_IS_ERR(e)) return false; + if (e->type == -RAY_SYM) { + if (e->attrs & ATTR_QUOTED) return true; + ray_col_meta_t m; + if (!meta_cols) return ray_table_col_meta(tbl, e->i64, &m); + return !ray_env_has_lexical_local(e->i64) && ray_table_col_meta(tbl, e->i64, &m); + } + if (e->type < 0) return true; + if (e->type != RAY_LIST) return false; + int64_t n = ray_len(e); + if (n < 2) return false; + ray_t** el = (ray_t**)ray_data(e); + ray_t* head = el[0]; + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; + ray_t* fn = ray_env_get(head->i64); + if (!fn || RAY_IS_ERR(fn)) return false; + if (fn->type != RAY_UNARY && fn->type != RAY_BINARY && fn->type != RAY_VARY) return false; + if (!(fn->attrs & RAY_FN_ATOMIC)) return false; + for (int64_t i = 1; i < n; i++) + if (!update_expr_elementwise(el[i], tbl, meta_cols)) return false; + return true; +} + +/* ---- Partition pruning before fetch ---- + * + * A select over a parted source whose where: compares the partition key + * with a literal (== != < > <= >= in, alone or as a conjunct of a top-level + * `and`) runs over a source holding only the partitions that can pass, so + * a pruned partition's columns are never fetched or decoded. The original + * where runs unchanged over the smaller source. + * + * A pruned partition's rows all fail the where, so dropping them changes + * no answer as long as nothing reads rows the where rejects: every where + * conjunct, by: expression and output must be elementwise (an output may + * be an aggregate of elementwise arguments), and the key must not be + * shadowed by a lexical local. + * + * One pruned partition is kept as a stand-in: its key with a single + * synthetic row of zero cells, built from metadata without a decode. Its + * row fails the where like the rows it replaces, so the where stays partial + * exactly when it was over the whole table (never all-pass, which routes + * consumers differently, nor zero-row). + * + * Consumers that size their route from the source's shape still see a + * smaller source with a one-row partition, usually first: the totals and + * per-partition averages cover the kept partitions only. A consumer must + * not size its route from that one row: the parted group samples its + * cardinality from the first partition holding more than one row + * (exec_group_parted), so a pruned and an unpruned query over partitions of + * similar shape take the same group route. */ + +/* The partition-pruning opcode of a where head, or 0. */ +static uint16_t prune_cmp_op(ray_t* head) { + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return 0; + ray_t* op = ray_sym_str(head->i64); + if (!op) return 0; + size_t n = ray_str_len(op); + const char* o = ray_str_ptr(op); + if (n == 1 && o[0] == '<') return OP_LT; + if (n == 1 && o[0] == '>') return OP_GT; + if (n == 2 && o[0] == '=' && o[1] == '=') return OP_EQ; + if (n == 2 && o[0] == '!' && o[1] == '=') return OP_NE; + if (n == 2 && o[0] == '<' && o[1] == '=') return OP_LE; + if (n == 2 && o[0] == '>' && o[1] == '=') return OP_GE; + if (n == 2 && o[0] == 'i' && o[1] == 'n') return OP_IN; + return 0; +} + +static bool prune_is_and(ray_t* head) { + if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; + ray_t* op = ray_sym_str(head->i64); + return op && ray_str_len(op) == 3 && memcmp(ray_str_ptr(op), "and", 3) == 0; +} + +/* AND into `acc` the partitions the where expression `e` can pass, for + * every recognised comparison of the key column `key_id` (values `kv`) + * with a literal of the key's exact type; anything else keeps every + * partition. `tmp` is scratch of the same width. */ +static void prune_where_mask(ray_t* e, int64_t key_id, ray_t* kv, + uint64_t* acc, uint64_t* tmp, int64_t n_words) { + if (!e || e->type != RAY_LIST || ray_len(e) < 2) return; + ray_t** x = (ray_t**)ray_data(e); + int64_t n = ray_len(e); + if (prune_is_and(x[0])) { + for (int64_t i = 1; i < n; i++) + prune_where_mask(x[i], key_id, kv, acc, tmp, n_words); + return; + } + uint16_t op = prune_cmp_op(x[0]); + if (!op || n != 3) return; + ray_t* l = x[1]; + ray_t* r = x[2]; + bool l_key = l && l->type == -RAY_SYM && !(l->attrs & ATTR_QUOTED) && l->i64 == key_id; + bool r_key = r && r->type == -RAY_SYM && !(r->attrs & ATTR_QUOTED) && r->i64 == key_id; + if (l_key == r_key) return; + ray_t* lit = l_key ? r : l; + if (!lit) return; + if (op == OP_IN) { + if (lit->type != kv->type) return; /* a typed vector literal */ + if (ray_sym_elem_size(lit->type, lit->attrs) != ray_sym_elem_size(kv->type, kv->attrs)) return; + } else { + if (lit->type != -kv->type || RAY_ATOM_IS_NULL(lit)) return; + if (lit->type == -RAY_SYM && !(lit->attrs & ATTR_QUOTED)) return; /* a name, not a symbol */ + } + memset(tmp, 0, (size_t)n_words * sizeof(uint64_t)); + if (!ray_part_prune_mask(kv, op, r_key, lit, tmp)) return; + for (int64_t w = 0; w < n_words; w++) acc[w] &= tmp[w]; +} + +/* Can a one-row zero-cell stand-in segment of this base type be built? */ +static bool prune_stand_in_type_ok(int8_t t) { + switch (t) { + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_F32: case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: + case RAY_GUID: case RAY_SYM: case RAY_STR: + return true; + default: + return false; + } +} + +/* A one-row segment of zero cells (SYM id 0, the empty string) shaped like + * `seg` — its type, SYM width and domain — read from metadata, no decode. */ +static ray_t* prune_stand_in_seg(ray_t* seg) { + ray_col_meta_t m; + if (!ray_col_meta_of(seg, &m)) return ray_error("schema", NULL); + ray_t* v; + if (m.type == RAY_SYM) { + v = ray_sym_vec_new(m.attrs & RAY_SYM_W_MASK, 1); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + memset(ray_data(v), 0, ray_sym_elem_size(v->type, v->attrs)); + v->len = 1; + if (seg->type == RAY_ENCCOL) ray_enccol_adopt_domain(v, seg); + else ray_sym_vec_adopt_domain(v, seg); + return v; + } + if (m.type == RAY_STR) { + v = ray_vec_new(RAY_STR, 1); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + return ray_str_vec_append(v, "", 0); + } + v = ray_vec_new(m.type, 1); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + memset(ray_data(v), 0, (size_t)ray_type_sizes[(uint8_t)m.type]); + v->len = 1; + return v; +} + +/* Segment p of parted column c without a decode (NULL: a ragged gap). */ +static ray_t* prune_seg(ray_t* tbl, int64_t c, int64_t p) { + ray_t* enc = ray_table_get_col_enc_idx(tbl, c); + return enc ? ray_enccol_seg(enc, p) + : ((ray_t**)ray_data(ray_table_col_idx(tbl, c)))[p]; /* plain wrapper */ +} + +/* A copy of the parted table `tbl` holding the partitions set in `keep` + * (n_keep of them) and, at its place in partition order, the stand-in for + * pruned partition `stand`: its key, one row, prune_stand_in_seg cells + * (shaped like any partition's segment of the column). + * Kept segments are retained, never decoded (an encoded column stays + * encoded). */ +static ray_t* parted_keep_partitions(ray_t* tbl, const uint64_t* keep, int64_t n_parts, + int64_t n_keep, int64_t stand) { + int64_t n_out = n_keep + 1; + int64_t ncols = ray_table_ncols(tbl); + ray_t* out = ray_table_new(ncols); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + for (int64_t c = 0; c < ncols; c++) { + int64_t name = ray_table_col_name(tbl, c); + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m)) { ray_release(out); return ray_error("schema", NULL); } + ray_t* slot = NULL; + if (m.type == RAY_MAPCOMMON) { + ray_t* mc = ray_table_col_idx(tbl, c); /* MAPCOMMON: plain */ + ray_t** mp = (ray_t**)ray_data(mc); + ray_t* kv = mp[0]; + ray_t* rc = mp[1]; + size_t esz = (size_t)ray_sym_elem_size(kv->type, kv->attrs); + ray_t* nkv = col_vec_new(kv, n_out); + ray_t* nrc = ray_vec_new(RAY_I64, n_out); + slot = ray_alloc(2 * sizeof(ray_t*)); + if (!nkv || RAY_IS_ERR(nkv) || !nrc || RAY_IS_ERR(nrc) || !slot || RAY_IS_ERR(slot)) { + if (nkv && !RAY_IS_ERR(nkv)) ray_release(nkv); + if (nrc && !RAY_IS_ERR(nrc)) ray_release(nrc); + if (slot && !RAY_IS_ERR(slot)) ray_release(slot); + ray_release(out); + return ray_error("oom", NULL); + } + int64_t k = 0; + for (int64_t p = 0; p < n_parts; p++) { + bool kept = (keep[p / 64] >> (p % 64)) & 1; + if (!kept && p != stand) continue; + memcpy((char*)ray_data(nkv) + (size_t)k * esz, + (const char*)ray_data(kv) + (size_t)p * esz, esz); + ((int64_t*)ray_data(nrc))[k] = kept ? ((const int64_t*)ray_data(rc))[p] : 1; + k++; + } + nkv->len = n_out; + nkv->attrs = kv->attrs; + if (nkv->type == RAY_SYM) ray_sym_vec_adopt_domain(nkv, kv); + nrc->len = n_out; + slot->type = RAY_MAPCOMMON; + slot->len = 2; + slot->attrs = mc->attrs; + memcpy(slot->aux, mc->aux, sizeof slot->aux); + ((ray_t**)ray_data(slot))[0] = nkv; /* adopts the new refs */ + ((ray_t**)ray_data(slot))[1] = nrc; /* not-a-table */ + } else { + ray_t* enc = ray_table_get_col_enc_idx(tbl, c); + ray_t* w = enc ? NULL : ray_table_col_idx(tbl, c); /* plain wrapper: no decode */ + ray_t* nw = ray_alloc((size_t)n_out * sizeof(ray_t*)); + if (!nw || RAY_IS_ERR(nw)) { ray_release(out); return ray_error("oom", NULL); } + nw->type = m.type; + nw->len = 0; + nw->attrs = w ? w->attrs : 0; + memset(nw->aux, 0, sizeof nw->aux); + ray_t** segs = (ray_t**)ray_data(nw); + bool any_enc = false; + for (int64_t p = 0; p < n_parts; p++) { + bool kept = (keep[p / 64] >> (p % 64)) & 1; + if (!kept && p != stand) continue; + ray_t* seg = prune_seg(tbl, c, p); + if (kept) { + if (seg) ray_retain(seg); + } else { + /* shaped like any partition's segment (the pruned one may be a ragged gap) */ + for (int64_t q = 0; !seg && q < n_parts; q++) seg = prune_seg(tbl, c, q); + seg = seg ? prune_stand_in_seg(seg) : ray_error("schema", NULL); + if (!seg || RAY_IS_ERR(seg)) { + ray_release(nw); ray_release(out); + return seg ? seg : ray_error("oom", NULL); + } + } + any_enc |= seg && seg->type == RAY_ENCCOL; + segs[nw->len++] = seg; + } + slot = nw; + if (any_enc) { + slot = ray_enccol_parted_new(nw); + ray_release(nw); + if (!slot || RAY_IS_ERR(slot)) { ray_release(out); return slot ? slot : ray_error("oom", NULL); } + } + } + out = ray_table_add_col(out, name, slot); + ray_release(slot); + if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); + } + return out; +} + +/* Does partition p of the parted table hold a segment of every column? */ +static bool parted_partition_whole(ray_t* tbl, int64_t p, int64_t key_col) { + /* The caller validated one MAPCOMMON key and all other parted columns. */ + int64_t ncols = ray_table_ncols(tbl); + for (int64_t c = 0; c < ncols; c++) { + if (c == key_col) continue; + if (!prune_seg(tbl, c, p)) return false; + } + return true; +} + +/* Every conjunct of a where is elementwise (`in` against a literal vector + * included), so a row's verdict depends on that row alone. */ +static bool prune_where_elementwise(ray_t* e, ray_t* tbl) { + if (e && e->type == RAY_LIST && ray_len(e) >= 2) { + ray_t** x = (ray_t**)ray_data(e); + int64_t n = ray_len(e); + if (prune_is_and(x[0])) { + for (int64_t i = 1; i < n; i++) + if (!prune_where_elementwise(x[i], tbl)) return false; + return true; + } + if (prune_cmp_op(x[0]) == OP_IN && n == 3) + return update_expr_elementwise(x[1], tbl, true) && + x[2] && x[2]->type > 0 && x[2]->type != RAY_LIST; + } + return update_expr_elementwise(e, tbl, true); +} + +/* An output reads only the rows the where keeps: elementwise, or an + * aggregate (RAY_FN_AGGR builtin) of elementwise arguments. */ +static bool prune_output_ok(ray_t* e, ray_t* tbl) { + if (update_expr_elementwise(e, tbl, true)) return true; + if (!e || e->type != RAY_LIST || ray_len(e) < 2) return false; + ray_t** el = (ray_t**)ray_data(e); + if (!el[0] || el[0]->type != -RAY_SYM || (el[0]->attrs & ATTR_QUOTED)) return false; + ray_t* fn = ray_env_get(el[0]->i64); + if (!fn || RAY_IS_ERR(fn) || !(fn->attrs & RAY_FN_AGGR)) return false; + if (fn->type != RAY_UNARY && fn->type != RAY_BINARY && fn->type != RAY_VARY) return false; + for (int64_t i = 1; i < ray_len(e); i++) + if (!update_expr_elementwise(el[i], tbl, true)) return false; + return true; +} + +/* A by: clause of column names or elementwise expressions. */ +static bool prune_by_ok(ray_t* by, ray_t* tbl) { + if (!by) return true; + if (by->type == RAY_SYM) { /* [k m] */ + for (int64_t i = 0; i < by->len; i++) { + int64_t id = sym_cell_runtime_id(by, i); + ray_col_meta_t m; + if (ray_env_has_lexical_local(id) || !ray_table_col_meta(tbl, id, &m)) return false; + } + return true; + } + if (by->type == RAY_DICT) { /* {k: expr …} */ + ray_t* vals = ray_dict_vals(by); + if (!vals || vals->type != RAY_LIST) return false; + for (int64_t i = 0; i < vals->len; i++) + if (!update_expr_elementwise(((ray_t**)ray_data(vals))[i], tbl, true)) return false; + return true; + } + return update_expr_elementwise(by, tbl, true); +} + +/* Every where conjunct, by: expression and output of the select reads only + * the rows the where keeps. */ +static bool prune_shape_ok(ray_t* dict, ray_t* tbl, ray_t* where) { + if (!prune_where_elementwise(where, tbl)) return false; + if (!prune_by_ok(dict_get(dict, "by"), tbl)) return false; + ray_t* keys = ray_dict_keys(dict); + ray_t* vals = ray_dict_vals(dict); + if (!keys || keys->type != RAY_SYM || !vals || vals->type != RAY_LIST) return false; + static const char* const reserved[] = { "from", "where", "by", "take", "asc", "desc", "nearest" }; + for (int64_t i = 0; i < keys->len; i++) { + ray_t* k = ray_sym_vec_cell(keys, i); + if (!k) return false; + bool res = false; + for (size_t r = 0; r < sizeof reserved / sizeof *reserved; r++) + if (ray_str_len(k) == strlen(reserved[r]) && + memcmp(ray_str_ptr(k), reserved[r], ray_str_len(k)) == 0) res = true; + if (!res && !prune_output_ok(((ray_t**)ray_data(vals))[i], tbl)) return false; + } + return true; +} + +/* The pruned source for the select `dict` (where: `where`) over the parted + * table `tbl`; NULL when tbl is not a whole parted table (one MAPCOMMON key, + * every other column parted over the same partitions), the shape may read + * rows the where rejects, the key is shadowed, nothing is pruned, or a kept + * partition is ragged; or an error. */ +static ray_t* select_prune_partitions(ray_t* dict, ray_t* tbl, ray_t* where) { + if (!where || where->type != RAY_LIST || !tbl || tbl->type != RAY_TABLE) return NULL; + int64_t ncols = ray_table_ncols(tbl); + int64_t key_id = -1; + int64_t key_col = -1; + ray_t* kv = NULL; + for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m)) return NULL; + if (m.type != RAY_MAPCOMMON) continue; + if (kv) return NULL; /* one partition key */ + ray_t* mc = ray_table_col_idx(tbl, c); + if (!mc || RAY_IS_ERR(mc) || mc->len < 2) return NULL; + ray_t** mp = (ray_t**)ray_data(mc); + if (!mp[0] || !mp[1] || mp[1]->type != RAY_I64 || mp[0]->len != mp[1]->len) return NULL; + kv = mp[0]; + key_id = ray_table_col_name(tbl, c); + key_col = c; + } + if (!kv || kv->len <= 0) return NULL; + if (ray_env_has_lexical_local(key_id)) return NULL; /* a formal shadows the key */ + /* the widths ray_part_prune_mask reads: 4-byte DATE/I32/TIME keys, 8 otherwise */ + bool narrow = kv->type == RAY_DATE || kv->type == RAY_I32 || kv->type == RAY_TIME; + if (ray_sym_elem_size(kv->type, kv->attrs) != (narrow ? 4 : 8)) return NULL; + int64_t n_parts = kv->len; + for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m)) return NULL; + if (m.type == RAY_MAPCOMMON) continue; + if (!RAY_IS_PARTED(m.type) || m.n_segs != n_parts) return NULL; + if (!prune_stand_in_type_ok((int8_t)RAY_PARTED_BASETYPE(m.type))) return NULL; + } + int64_t n_words = (n_parts + 63) / 64; + uint64_t* acc = (uint64_t*)ray_alloc_raw((size_t)n_words * 2 * sizeof(uint64_t)); + if (!acc) return NULL; /* no pruning: the full source is correct */ + uint64_t* tmp = acc + n_words; + for (int64_t w = 0; w < n_words; w++) acc[w] = ~0ULL; + prune_where_mask(where, key_id, kv, acc, tmp, n_words); + int64_t n_keep = 0; + int64_t stand = -1; /* the first pruned partition */ + for (int64_t p = 0; p < n_parts; p++) { + bool kept = (acc[p / 64] >> (p % 64)) & 1; + n_keep += kept; + if (!kept && stand < 0) stand = p; + } + if (n_keep == n_parts) { + ray_free_raw(acc); + return NULL; /* the full source stays unchanged */ + } + bool ok = true; + for (int64_t p = 0; ok && p < n_parts; p++) { + bool kept = (acc[p / 64] >> (p % 64)) & 1; + /* a kept ragged partition: the pruned copy would be just as malformed */ + if (kept && !parted_partition_whole(tbl, p, key_col)) ok = false; + } + ray_t* out = NULL; + if (ok && n_keep < n_parts && stand >= 0 && prune_shape_ok(dict, tbl, where)) + out = parted_keep_partitions(tbl, acc, n_parts, n_keep, stand); + ray_free_raw(acc); + return out; +} + /* Does the clause value `v` name `s` anywhere: a name, a name list, a * dict's keys or values, nested in a call? */ static bool clause_names_sym(ray_t* v, int64_t s) { @@ -11772,13 +16651,31 @@ static bool clause_names_sym(ray_t* v, int64_t s) { return false; } +/* Does the value of by-dict pair `i` (`d_elems` interleaves names and + * values) name an alias an earlier pair adds as a new column of `tbl`? + * The eager by-dict loop binds that column as a flat vector, so the value + * must be evaluated over flat columns too: over a parted table it would + * pair every partition with the alias column read again from row 0. A + * value that runs code (a helper) may read the alias as a free name in + * its body, unseen here: it is taken to read it. */ +static bool bydict_names_earlier_alias(ray_t** d_elems, int64_t i, ray_t* tbl) { + ray_t* v = d_elems[i * 2 + 1]; + bool runs_code = clause_runs_code_in(v, tbl, true); + for (int64_t j = 0; j < i; j++) { + ray_t* k = d_elems[j * 2]; + if (!k || k->type != -RAY_SYM || ray_table_has_col(tbl, k->i64)) continue; + if (runs_code || clause_names_sym(v, k->i64)) return true; + } + return false; +} + /* May the narrow copy of a parted table add a row-number column named * `row_sym`? Not when the table has a column of that name or the select * names it anywhere (as a key, an alias, or a value the column would * shadow). A variable of that name is shadowed only through a name the * select writes, or code it runs (parted_clauses_plain declines that). */ static bool parted_row_name_free(ray_t* dict, ray_t* tbl, int64_t row_sym) { - if (ray_table_get_col(tbl, row_sym)) return false; + if (ray_table_has_col(tbl, row_sym)) return false; return !clause_names_sym(dict, row_sym); } @@ -11858,6 +16755,60 @@ static bool clauses_name_their_columns(ray_t* dict, ray_t* tbl) { return !clauses_run_code(dict, tbl, false); } +/* Does `expr` hold a vector of several values, written or named (a global + * that is no column and no local)? Grouped, such a vector stands for a + * column of the table it was written against, so it must meet the rows + * before a where: removes any. A quoted form is no value read. */ +static bool expr_holds_vector_const(ray_t* expr, ray_t* tbl) { + if (!expr) return false; + if (expr->type == -RAY_SYM) { + if ((expr->attrs & ATTR_QUOTED) || ray_table_has_col(tbl, expr->i64) || + ray_sym_is_dotted(expr->i64) || ray_env_has_lexical_local(expr->i64)) + return false; + ray_t* v = ray_env_get(expr->i64); + return v && ray_is_vec(v) && ray_len(v) != 1; + } + if (expr->type == RAY_LIST) { + ray_t** el = (ray_t**)ray_data(expr); + int64_t n = ray_len(expr); + if (n == 2 && el[0] && el[0]->type == -RAY_SYM && + !(el[0]->attrs & ATTR_QUOTED) && + el[0]->i64 == ray_sym_intern("quote", 5)) + return false; + for (int64_t i = 0; i < n; i++) + if (expr_holds_vector_const(el[i], tbl)) return true; + return false; + } + if (expr->type == RAY_DICT) { + DICT_VIEW_DECL(dv); + DICT_VIEW_OPEN(expr, dv); + bool holds = DICT_VIEW_OVERFLOW(dv); + for (int64_t i = 0; !holds && i + 1 < dv_n; i += 2) + holds = expr_holds_vector_const(dv[i + 1], tbl); + DICT_VIEW_CLOSE(dv); + return holds; + } + return ray_is_vec(expr) && ray_len(expr) != 1; +} + +/* expr_holds_vector_const over the outputs and the by: of a select. */ +static bool select_outputs_hold_vector_const(ray_t* dict, ray_t* tbl) { + static const char* skip[] = { "from", "where", "take", "asc", "desc", "nearest" }; + int64_t skip_ids[6]; + for (int i = 0; i < 6; i++) skip_ids[i] = ray_sym_intern(skip[i], strlen(skip[i])); + DICT_VIEW_DECL(dv); + DICT_VIEW_OPEN(dict, dv); + bool holds = DICT_VIEW_OVERFLOW(dv); + for (int64_t i = 0; !holds && i + 1 < dv_n; i += 2) { + bool reserved = false; + for (int j = 0; j < 6; j++) + reserved |= dv[i] && dv[i]->type == -RAY_SYM && dv[i]->i64 == skip_ids[j]; + if (!reserved) holds = expr_holds_vector_const(dv[i + 1], tbl); + } + DICT_VIEW_CLOSE(dv); + return holds; +} + /* Rows rv[0..n) of a parted table, gathered one column at a time without * flattening the table: the rows are marked, a column is compacted to the * marked rows (in ascending order) by sel_compact, and when rv is not @@ -11923,15 +16874,34 @@ static ray_t* parted_rows_open(parted_rows_t* pr, ray_t* tbl, const int64_t* rv, return err; } +/* Column `c` of parted `tbl` flattened, owned. A generation-2 fixed-width + * column is decoded straight into the flat vector by range reads (no + * whole-column materialization kept beside the copy); any other column is + * read as a column and flattened. */ +static ray_t* parted_flat_col_idx(ray_t* tbl, int64_t c) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && m.enc && RAY_IS_PARTED(m.type)) { + int8_t base = (int8_t)RAY_PARTED_BASETYPE(m.type); + if (base != RAY_STR && base != RAY_LIST && base != RAY_GUID) { + int64_t ncnt = 0; + const int64_t* cnt = parted_table_counts(tbl, &ncnt); + return parted_flatten_fixed_c(ray_table_slot_idx(tbl, c), ray_table_nrows(tbl), cnt, ncnt); + } + } + ray_t* v = ray_table_col_idx(tbl, c); + if (v && !RAY_IS_ERR(v)) v = query_materialize_parted_col(v, tbl); + return v; +} + /* Column `c` of the table at the rows, owned. */ static ray_t* parted_rows_gather(parted_rows_t* pr, int64_t c) { ray_t* v; if (!pr->sel) { - v = query_materialize_parted_col(ray_table_get_col_idx(pr->tbl, c)); + v = parted_flat_col_idx(pr->tbl, c); } else { int64_t cn = ray_table_col_name(pr->tbl, c); ray_t* one = sel_compact(NULL, pr->tbl, pr->sel, &cn, 1); - v = (one && !RAY_IS_ERR(one)) ? ray_table_get_col(one, cn) : one; + v = (one && !RAY_IS_ERR(one)) ? ray_table_col(one, cn) : one; if (v && !RAY_IS_ERR(v)) ray_retain(v); if (one && !RAY_IS_ERR(one)) ray_release(one); } @@ -11960,7 +16930,7 @@ static void parted_rows_close(parted_rows_t* pr) { * partitions at just those rows, one column at a time, and the result is * laid out as the select lays out the flattened table. NULL when the * shape is not handled here (the caller flattens the table). */ -static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_resolved) { +static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, unsigned plan) { int64_t nc = ray_table_ncols(tbl); int64_t nrows = ray_table_nrows(tbl); if (nc <= 0 || nc > 256) return NULL; /* sel_compact's column limit */ @@ -11988,16 +16958,8 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res for (int i = 0; i < 3; i++) { ray_t* v = dict_get(dict, clause[i]); if (!v) continue; - /* A quoted symbol standing for the whole clause names a column - * there too (`by: 's`, `desc: 'h`); collect_col_refs_set takes - * only name references. */ - if (v->type == -RAY_SYM && (v->attrs & ATTR_QUOTED)) { - bool seen = !ray_table_get_col(tbl, v->i64); - for (int j = 0; j < nref && !seen; j++) if (refs[j] == v->i64) seen = true; - if (!seen && nref < nc) refs[nref++] = v->i64; - } else { - nref = collect_col_refs_set(v, tbl, refs, (int)nc, nref); - } + /* a quoted symbol names a column too (`by: 's`, `desc: 'h`) */ + nref = collect_col_refs_set(v, tbl, refs, (int)nc, nref); } keynames[nkn++] = derived_key_name(by_expr); if (by_expr->type == -RAY_SYM && ray_sym_is_dotted(by_expr->i64)) { @@ -12025,7 +16987,7 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res ray_t* narrow = ray_table_new(nc + 1); for (int64_t c = 0; c < nc && narrow && !RAY_IS_ERR(narrow); c++) { if (!real[c]) continue; - ray_t* v = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + ray_t* v = parted_flat_col_idx(tbl, c); if (!v || RAY_IS_ERR(v)) { ray_release(narrow); narrow = v ? v : ray_error("oom", NULL); break; } narrow = ray_table_add_col(narrow, ray_table_col_name(tbl, c), v); ray_release(v); @@ -12052,7 +17014,7 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res if (k_from) ray_release(k_from); ray_release(narrow); if (!engine || RAY_IS_ERR(engine)) { scratch_free(buf_hdr); return engine ? engine : ray_error("oom", NULL); } - ray_t* res = ray_select_impl(&engine, 1, aliases_resolved); + ray_t* res = ray_select_impl(&engine, 1, plan); ray_release(engine); if (res && !RAY_IS_ERR(res) && ray_is_lazy(res)) res = ray_lazy_materialize(res); if (!res || RAY_IS_ERR(res) || res->type != RAY_TABLE) { scratch_free(buf_hdr); return res ? res : ray_error("oom", NULL); } @@ -12071,8 +17033,8 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res if (pos >= rc - 1 || ray_table_col_name(res, pos) != cn) fits = false; pos++; } - ray_t* rows = fits && pos == rc - 1 ? ray_table_get_col_idx(res, rc - 1) : NULL; - if (!rows || rows->type != RAY_I64) { ray_release(res); scratch_free(buf_hdr); return NULL; } + ray_t* rows = fits && pos == rc - 1 ? ray_table_col_idx(res, rc - 1) : NULL; /* a computed column: plain */ + if (!rows || RAY_IS_ERR(rows) || rows->type != RAY_I64) { ray_release(res); scratch_free(buf_hdr); return NULL; } int64_t n = rows->len; const int64_t* rv = (const int64_t*)ray_data(rows); parted_rows_t pr; @@ -12082,10 +17044,7 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res * replaces, in its order -- a real one from res, any other gathered. */ ray_t* out = err ? err : ray_table_new(rc + nc); for (int64_t k = 0; k < nkeys && out && !RAY_IS_ERR(out); k++) { - ray_t* v = ray_table_get_col_idx(res, k); - ray_retain(v); - out = ray_table_add_col(out, ray_table_col_name(res, k), v); - ray_release(v); + out = ray_table_add_col(out, ray_table_col_name(res, k), ray_table_slot_idx(res, k)); /* as it is */ } for (int64_t c = 0; c < nc && out && !RAY_IS_ERR(out); c++) { int64_t cn = ray_table_col_name(tbl, c); @@ -12094,9 +17053,9 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res if (is_key) continue; ray_t* v; if (real[c]) { /* res rows are in place already */ - v = ray_table_get_col(res, cn); - if (v) ray_retain(v); - else v = ray_error("domain", "select by: lost a column of a parted table"); + v = ray_table_col(res, cn); + if (v && !RAY_IS_ERR(v)) ray_retain(v); + else if (!v) v = ray_error("domain", "select by: lost a column of a parted table"); } else { v = parted_rows_gather(&pr, c); } @@ -12117,7 +17076,7 @@ static ray_t* select_parted_first_rows(ray_t* dict, ray_t* tbl, bool aliases_res * columns its outputs name. Outputs must be bare columns, and each sort * key a column of the table. NULL when the shape is not handled here * (the caller flattens the table). */ -static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, bool aliases_resolved) { +static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, unsigned plan) { int64_t nc = ray_table_ncols(tbl); if (nc <= 0 || nc > 256) return NULL; /* sel_compact's column limit */ int64_t row_sym = ray_sym_intern("__row", 5); @@ -12144,7 +17103,7 @@ static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, bool aliases_resolve else if (kid == id_from) continue; else if (kid == id_take || kid == id_asc || kid == id_desc) n_clause++; else if (!v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED) || - !ray_table_get_col(tbl, v->i64) || !sym_names_col(tbl, v->i64)) + !ray_table_has_col(tbl, v->i64) || !sym_names_col(tbl, v->i64)) ok = false; /* a stored column the name reads (no local hides it) */ else n_out++; } @@ -12182,7 +17141,7 @@ static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, bool aliases_resolve ray_t* narrow = ray_table_new(nc + 1); for (int64_t c = 0; c < nc && narrow && !RAY_IS_ERR(narrow); c++) { if (!real[c]) continue; - ray_t* v = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + ray_t* v = parted_flat_col_idx(tbl, c); if (!v || RAY_IS_ERR(v)) { ray_release(narrow); narrow = v ? v : ray_error("oom", NULL); break; } narrow = ray_table_add_col(narrow, ray_table_col_name(tbl, c), v); ray_release(v); @@ -12225,13 +17184,13 @@ static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, bool aliases_resolve scratch_free(buf_hdr); return engine ? engine : ray_error("oom", NULL); } - ray_t* res = ray_select_impl(&engine, 1, aliases_resolved); + ray_t* res = ray_select_impl(&engine, 1, plan); ray_release(engine); if (res && !RAY_IS_ERR(res) && ray_is_lazy(res)) res = ray_lazy_materialize(res); if (!res || RAY_IS_ERR(res) || res->type != RAY_TABLE) { scratch_free(buf_hdr); return res ? res : ray_error("oom", NULL); } int64_t rc = ray_table_ncols(res); - ray_t* rows = rc > 0 && ray_table_col_name(res, rc - 1) == row_sym ? ray_table_get_col_idx(res, rc - 1) : NULL; - if (!rows || rows->type != RAY_I64) { ray_release(res); scratch_free(buf_hdr); return NULL; } + ray_t* rows = rc > 0 && ray_table_col_name(res, rc - 1) == row_sym ? ray_table_col_idx(res, rc - 1) : NULL; + if (!rows || RAY_IS_ERR(rows) || rows->type != RAY_I64) { ray_release(res); scratch_free(buf_hdr); return NULL; } parted_rows_t pr; ray_t* err = parted_rows_open(&pr, tbl, (const int64_t*)ray_data(rows), rows->len); @@ -12251,9 +17210,9 @@ static ray_t* select_parted_sorted(ray_t* dict, ray_t* tbl, bool aliases_resolve for (int64_t s = 0; s < nc && c < 0; s++) if (ray_table_col_name(tbl, s) == src) c = s; ray_t* v; if (c >= 0 && real[c]) { /* the sort rows are in place already */ - v = ray_table_get_col(res, src); - if (v) ray_retain(v); - else v = ray_error("domain", "select: lost a column of a parted table"); + v = ray_table_col(res, src); + if (v && !RAY_IS_ERR(v)) ray_retain(v); + else if (!v) v = ray_error("domain", "select: lost a column of a parted table"); } else { v = c >= 0 ? parted_rows_gather(&pr, c) : ray_error("domain", "select: lost a column of a parted table"); } @@ -12277,18 +17236,18 @@ typedef struct { * a quoted key symbol); by_expr points into it */ } select_owned_t; -static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, +static ray_t* ray_select_body(ray_t** args, int64_t n, unsigned plan, select_owned_t* own); -static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { +static ray_t* ray_select_impl(ray_t** args, int64_t n, unsigned plan) { select_owned_t own = {0}; - ray_t* r = ray_select_body(args, n, aliases_resolved, &own); + ray_t* r = ray_select_body(args, n, plan, &own); if (own.selection) ray_release(own.selection); if (own.by_syms) ray_release(own.by_syms); return r; } -static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, +static ray_t* ray_select_body(ray_t** args, int64_t n, unsigned plan, select_owned_t* own) { if (n < 1) return ray_error("arity", "select: expects a query dict, got %lld args", (long long)n); ray_t* dict = args[0]; @@ -12351,14 +17310,30 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (tbl->type != RAY_TABLE) { int8_t tbl_t = tbl->type; ray_release(tbl); return ray_error("type", "select: `from:` must evaluate to a table, got %s", ray_type_name(tbl_t)); } select_scan_register(args, dict, tbl, where_expr); - if (!aliases_resolved) { - select_alias_plan_t plan; - ray_t* engine = select_plan_grouped_aliases(dict, tbl, &plan); + /* Prune partitions the where: rules out before any column is fetched. */ + { + ray_t* pruned = select_prune_partitions(dict, tbl, where_expr); + if (pruned) { + ray_release(tbl); + if (RAY_IS_ERR(pruned)) return pruned; + tbl = pruned; + } + } + + /* The top N groups by a count, exactly, without grouping every row. */ + { + ray_t* top = select_topk_hh(dict, tbl); + if (top) { ray_release(tbl); return top; } + } + + if (!(plan & SELECT_ALIASES_RESOLVED)) { + select_alias_plan_t aplan; + ray_t* engine = select_plan_grouped_aliases(dict, tbl, &aplan); if (engine && RAY_IS_ERR(engine)) { ray_release(tbl); return engine; } if (engine) { - ray_t* r = ray_select_impl(&engine, 1, true); - if (plan.n_derived > 0) r = select_apply_derived(r, dict, &plan, tbl); - select_alias_plan_free(&plan); + ray_t* r = ray_select_impl(&engine, 1, plan | SELECT_ALIASES_RESOLVED); + if (aplan.n_derived > 0) r = select_apply_derived(r, dict, &aplan, tbl); + select_alias_plan_free(&aplan); ray_release(engine); ray_release(tbl); return r; @@ -12370,14 +17345,25 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_t* engine = select_plan_computed_key(dict, tbl, &key_name); if (engine && RAY_IS_ERR(engine)) { ray_release(tbl); return engine; } if (engine) { - ray_t* r = ray_select_impl(&engine, 1, true); + ray_t* r = ray_select_impl(&engine, 1, plan | SELECT_ALIASES_RESOLVED); + ray_release(engine); + ray_release(tbl); + return select_name_computed_key(r, key_name); + } + } + + if (!(plan & SELECT_COLUMN_FREE_PLANNED)) { + ray_t* engine = select_plan_column_free_aggs(dict, tbl); + if (engine && RAY_IS_ERR(engine)) { ray_release(tbl); return engine; } + if (engine) { + ray_t* r = ray_select_impl(&engine, 1, plan | SELECT_COLUMN_FREE_PLANNED); ray_release(engine); ray_release(tbl); - return select_name_computed_key(r, key_name); + return r; } } - ray_t* temporal_result = try_temporal_group_materialize(dict, tbl); + ray_t* temporal_result = try_temporal_group_materialize(dict, tbl, plan); if (temporal_result) { ray_release(tbl); return temporal_result; } ray_t* by_expr = dict_get(dict, "by"); @@ -12463,7 +17449,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * at the rows kept (select_parted_first_rows); a shape that helper does * not take flattens the table. A where: flattens the rows it keeps. */ if (n_out == 0 && by_expr && !where_expr && table_has_parted_columns(tbl)) { - ray_t* first = select_parted_first_rows(dict, tbl, aliases_resolved); + ray_t* first = select_parted_first_rows(dict, tbl, plan); if (first) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return first; } ray_t* flat = query_materialize_parted_table(tbl); if (!flat || RAY_IS_ERR(flat)) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return flat ? flat : ray_error("oom", NULL); } @@ -12475,7 +17461,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_release(tbl); DICT_VIEW_CLOSE(dv); if (!fd || RAY_IS_ERR(fd)) return fd ? fd : ray_error("oom", NULL); - ray_t* r = ray_select_impl(&fd, 1, true); + ray_t* r = ray_select_impl(&fd, 1, plan | SELECT_ALIASES_RESOLVED); ray_release(fd); return r; } @@ -12539,7 +17525,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * (select_parted_sorted); a shape it does not take flattens the table. * A where: flattens the rows it keeps itself. */ if (has_sort && !by_expr && !where_expr && !nearest_expr && table_has_parted_columns(tbl)) { - ray_t* sorted = select_parted_sorted(dict, tbl, aliases_resolved); + ray_t* sorted = select_parted_sorted(dict, tbl, plan); if (sorted) { ray_release(tbl); DICT_VIEW_CLOSE(dv); return sorted; } ray_t* flat = query_materialize_parted_table(tbl); ray_release(tbl); @@ -12615,12 +17601,13 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (alias_ref) { bad_clause = 1; break; } } if (v && v->type == -RAY_SYM && !(v->attrs & ATTR_QUOTED)) { - ray_t* oc = ray_table_get_col(tbl, v->i64); - if (!oc) { bad_clause = 1; break; } - int8_t ot = oc->type; + if (!sym_names_col(tbl, v->i64)) { bad_clause = 1; break; } + ray_col_meta_t om; + if (!ray_table_col_meta(tbl, v->i64, &om)) { bad_clause = 1; break; } + int8_t ot = om.type; if (RAY_IS_PARTED(ot) || ot == RAY_MAPCOMMON) { bad_clause = 1; break; } - if (!ray_is_vec(oc)) + if (!(ot >= RAY_BOOL && ot <= RAY_STR)) { bad_clause = 1; break; } out_syms[n_out_syms] = v->i64; out_aliases[n_out_syms] = kid; @@ -12636,12 +17623,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, bad_clause = 1; } else { for (int64_t c = 0; c < nc; c++) { - ray_t* oc = ray_table_get_col_idx(tbl, c); - if (!oc) { bad_clause = 1; break; } - int8_t ot = oc->type; + ray_col_meta_t om; + if (!ray_table_col_meta_idx(tbl, c, &om)) { bad_clause = 1; break; } + int8_t ot = om.type; if (RAY_IS_PARTED(ot) || ot == RAY_MAPCOMMON) { bad_clause = 1; break; } - if (!ray_is_vec(oc)) + if (!(ot >= RAY_BOOL && ot <= RAY_STR)) { bad_clause = 1; break; } int64_t cn = ray_table_col_name(tbl, c); out_syms[n_out_syms] = cn; @@ -12657,10 +17644,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * Output columns are also handled — the fused materialiser * propagates null bitmaps via ray_vec_set_null. */ if (!bad_clause) { - for (uint32_t i = 0; i < n_sort_keys && !bad_clause; i++) { - ray_t* kc = ray_table_get_col(tbl, sort_key_syms[i]); - if (!kc) bad_clause = 1; - } + for (uint32_t i = 0; i < n_sort_keys && !bad_clause; i++) + if (!tbl_has_col(tbl, sort_key_syms[i])) bad_clause = 1; } /* Without a sort the positional path takes only a literal K: * an expression is left to the general path, which evaluates @@ -12680,10 +17665,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * the table, found without scanning the rest. */ bool sorted_asc = false; if (n_sort_keys == 1 && !sort_descs[0]) { - ray_t* kc = ray_table_get_col(tbl, sort_key_syms[0]); - sorted_asc = kc && (kc->attrs & RAY_ATTR_SORTED) && - !(kc->attrs & RAY_ATTR_SLICE) && - !ray_vec_may_have_nulls(kc); + ray_col_meta_t km; + sorted_asc = ray_table_col_meta(tbl, sort_key_syms[0], &km) && + (km.attrs & RAY_ATTR_SORTED) && + !(km.attrs & RAY_ATTR_SLICE) && + !tbl_col_may_have_nulls(tbl, sort_key_syms[0]); } if (where_expr && (n_sort_keys == 0 || (sorted_asc && k > 0)) && k != 0 && k != INT64_MIN && @@ -12696,7 +17682,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_release(tbl); DICT_VIEW_CLOSE(dv); return res; } - if (res && RAY_IS_ERR(res)) ray_error_free(res); + if (res && RAY_IS_ERR(res)) { /* a failed bind or range read: the query's error */ + ray_release(tbl); + DICT_VIEW_CLOSE(dv); return res; + } } if (n_sort_keys > 0 && k > 0 && k <= FPK_MAX_K && k < ray_table_nrows(tbl)) { ray_t* res = ray_fused_topk_select(tbl, where_expr, @@ -12710,7 +17699,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_release(tbl); DICT_VIEW_CLOSE(dv); return res; } - if (res && RAY_IS_ERR(res)) ray_error_free(res); + if (res && RAY_IS_ERR(res)) { /* a failed bind or range read: the query's error */ + ray_release(tbl); + DICT_VIEW_CLOSE(dv); return res; + } } } else if (tv) { ray_release(tv); @@ -12737,6 +17729,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * FLAT path so nothing there changes. */ bool parted_bydict_deferred = false; bool computed_single_key = false; /* by: is one expression, compiled or const */ + bool named_value_key = false; /* by: is a name holding a value, no column */ /* Sort keys that are source columns no output scans: carried through * the projection (appended after the outputs) so the sort can read * them, dropped from the result after it ran. */ @@ -12829,9 +17822,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, dep_candidate = false; } if (dep_candidate && base_sym >= 0) { - ray_t* base_col = ray_table_get_col(tbl, base_sym); - dep_candidate = base_col && key_type_i64_projectable(base_col->type) && - !ray_vec_has_nulls(base_col); + ray_col_meta_t bm; + dep_candidate = ray_table_col_meta(tbl, base_sym, &bm) && + key_type_i64_projectable(bm.type) && + !ray_table_col_has_nulls(tbl, base_sym); } /* Exact-size carve (unbounded): at most nk dependent-key entries can * ever be collected (one per by-dict pair). On the dependent-key @@ -12859,7 +17853,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, dep_candidate = false; break; } - bool already_in_tbl = (ray_table_get_col(tbl, k->i64) != NULL); + bool already_in_tbl = tbl_has_col(tbl, k->i64); bool trivial_self = (v->type == -RAY_SYM && v->i64 == k->i64); if (already_in_tbl && !trivial_self) { dep_candidate = false; @@ -12935,9 +17929,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, { int64_t in_nc = ray_table_ncols(tbl); for (int64_t c = 0; c < in_nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || - col->type == RAY_MAPCOMMON)) { + ray_col_meta_t cm; + if (ray_table_col_meta_idx(tbl, c, &cm) && (RAY_IS_PARTED(cm.type) || + cm.type == RAY_MAPCOMMON)) { by_input_parted = true; break; } } @@ -12958,8 +17952,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t j = 0; j < i; j++) if (d_elems[j * 2]->i64 == k->i64) { defer_ok = false; break; } if (!defer_ok) break; + /* a value reading an earlier alias is evaluated eagerly */ + if (bydict_names_earlier_alias(d_elems, i, tbl)) { defer_ok = false; break; } bool trivial_self = (v && v->type == -RAY_SYM && v->i64 == k->i64); - if (ray_table_get_col(tbl, k->i64) && !trivial_self) { + if (tbl_has_col(tbl, k->i64) && !trivial_self) { defer_ok = false; break; /* alias shadows an input column */ } if (v && v->type == RAY_LIST) { /* computed expr: one the planner lowers */ @@ -12970,9 +17966,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, continue; } if (v && v->type == -RAY_SYM && !(v->attrs & ATTR_QUOTED)) { - ray_t* src = ray_table_get_col(tbl, v->i64); - if (!src || - !query_key_type_streamable(query_col_base_type(src))) { + if (!tbl_has_col(tbl, v->i64) || + !query_key_type_streamable(tbl_col_base_type(tbl, v->i64))) { defer_ok = false; break; } continue; @@ -13011,7 +18006,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * column and hid the key column's index from the group side. */ bool bare_ref = v && v->type == -RAY_SYM && !(v->attrs & ATTR_QUOTED) && - ray_table_get_col(tbl, v->i64) != NULL; + tbl_has_col(tbl, v->i64); if (!(v && v->type == -RAY_SYM && v->i64 == k->i64) && !bare_ref) { has_computed_by_val = true; break; @@ -13074,7 +18069,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * filtered table dominates what was meant to be a cheap prefilter * (single-col filter is O(passing × esz), full filter scales with * every projected column). */ - if (where_expr && (prefilter_computed_by || prefilter_multi_key_where)) { + /* A vector constant read as rows stays as long as the table it was + * written against: the rows reach the grouping unfiltered, the + * where: as its selection. */ + if (where_expr && (prefilter_computed_by || prefilter_multi_key_where) && + !select_outputs_hold_vector_const(dict, tbl)) { /* Exact-size carve: collect_col_refs_set dedups against real * table columns, so ray_table_ncols(tbl) is a hard upper bound — * no silent cap on wide tables past the former [256]. */ @@ -13195,7 +18194,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, DICT_VIEW_CLOSE(dv); DICT_VIEW_CLOSE(byv); if (!rewritten || RAY_IS_ERR(rewritten)) return rewritten ? rewritten : ray_error("oom", NULL); - ray_t* r = ray_select_impl(&rewritten, 1, aliases_resolved); + ray_t* r = ray_select_impl(&rewritten, 1, plan); ray_release(rewritten); return r; } @@ -13203,21 +18202,22 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } /* A by-dict value the planner cannot lower (a helper, a builtin - * with no kernel) is evaluated below over whole columns: over a - * parted table, flatten the columns the select reads first (the - * whole table with no output, or when a clause runs code whose - * reads are unseen). */ + * with no kernel), or one reading an earlier alias, is evaluated + * below over whole columns: over a parted table, flatten the + * columns the select reads first (the whole table with no output, + * or when a clause runs code whose reads are unseen). */ if (table_has_parted_columns(tbl)) { bool unlowered = false; for (int64_t i = 0; i < nk && !unlowered; i++) { ray_t* v = d_elems[i * 2 + 1]; + if (bydict_names_earlier_alias(d_elems, i, tbl)) { unlowered = true; break; } if (!v || v->type != RAY_LIST) continue; ray_graph_t* pg = ray_graph_new(tbl); unlowered = !pg || compile_expr_dag(pg, v) == NULL; if (pg) ray_graph_free(pg); } if (unlowered) { - ray_t* flat = n_out > 0 ? parted_flatten_read_cols(dict, tbl) + ray_t* flat = n_out > 0 ? parted_flatten_read_cols(dict, tbl, false, NULL) : query_materialize_parted_table(tbl); ray_release(tbl); if (!flat || RAY_IS_ERR(flat)) { @@ -13229,11 +18229,30 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } ray_env_push_query_scope(); - int64_t in_ncols = ray_table_ncols(tbl); - for (int64_t c = 0; c < in_ncols; c++) { - int64_t cn = ray_table_col_name(tbl, c); - ray_t* cv = ray_table_get_col_idx(tbl, c); - if (cv) ray_env_set_query_local(cn, cv); + { + /* The by-vals the loop below evaluates (a self-alias {x: x} is + * not evaluated): an encoded column is bound only when one of + * them names it. A value evaluated by range (key_eval_by_range) + * reads its columns a range at a time and binds nothing here. */ + ray_t* bv_hdr = NULL; + ray_t** bvals = (ray_t**)scratch_alloc(&bv_hdr, (size_t)nk * sizeof(ray_t*)); + ray_t* berr = bvals ? NULL : ray_error("oom", NULL); + int64_t n_bv = 0; + for (int64_t i = 0; bvals && i < nk; i++) { + ray_t* k = d_elems[i * 2]; + ray_t* v = d_elems[i * 2 + 1]; + if (k && v && v->type == -RAY_SYM && v->i64 == k->i64) continue; + key_range_plan_t kp; + if (bydict_enc_rename(v, tbl) || key_range_plan(v, tbl, &kp)) continue; + bvals[n_bv++] = v; + } + if (!berr) berr = bind_referenced_columns(tbl, bvals, n_bv); + scratch_free(bv_hdr); + if (berr) { + ray_env_pop_scope(); + ray_release(tbl); + DICT_VIEW_CLOSE(dv); DICT_VIEW_CLOSE(byv); return berr; + } } by_sym_vec_owned = ray_vec_new(RAY_SYM, nk); @@ -13267,13 +18286,13 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } /* Collision check: if the dict key already exists in the * input table, ray_table_add_col would append a second - * column with the same name and ray_table_get_col finds + * column with the same name and ray_table_col finds * the ORIGINAL, so the group-by would silently scan the * user's existing column instead of our materialised * one. The one allowed exception is {x: x}, a trivial * self-alias: the input column is already exactly what * we want to group on. */ - bool already_in_tbl = (ray_table_get_col(tbl, k->i64) != NULL); + bool already_in_tbl = tbl_has_col(tbl, k->i64); bool trivial_self = (v->type == -RAY_SYM && v->i64 == k->i64); if (already_in_tbl && !trivial_self) { fail_err = ray_error("domain", @@ -13285,12 +18304,27 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, sv_data[i] = k->i64; continue; } - ray_t* col_vec = group_key_eval(v, tbl); + /* A rename of an encoded column the grouping reads by range + * (bydict_enc_rename): the slot itself under the new name. */ + ray_t* ren = bydict_enc_rename(v, tbl); + if (ren) { + ray_t* new_tbl = ray_table_add_col(tbl, k->i64, ren); + if (!new_tbl || RAY_IS_ERR(new_tbl)) { + fail_err = new_tbl ? new_tbl : ray_error("oom", NULL); + failed = true; break; + } + tbl = new_tbl; + sv_data[i] = k->i64; + continue; + } + ray_t* col_vec = group_key_eval_bound(v, tbl); if (!col_vec || RAY_IS_ERR(col_vec)) { fail_err = col_vec ? col_vec : ray_error("domain", "by-dict val eval"); failed = true; break; } - if (!ray_is_vec(col_vec) || ray_len(col_vec) != expected_len) { + /* a LIST column groups by its cells, as `by: l` does */ + if (!(ray_is_vec(col_vec) || col_vec->type == RAY_LIST) || + ray_len(col_vec) != expected_len) { ray_release(col_vec); fail_err = ray_error("length", "by-dict val must be a column vector"); failed = true; break; @@ -13323,6 +18357,61 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * decl, dv-threaded returns below only close dv). */ DICT_VIEW_CLOSE(byv); + /* A by: name that reads no column but holds one value per row of the + * table (a lambda parameter, a let, a global vector) is carried under a + * where: as the hidden column __by_key, so the filter keeps its rows in + * the one run of where: (the eval-level grouping, which outputs the + * grouping DAG does not serve take, groups on it; the DAG route reads + * the name itself). A parted table is flattened first, to the columns + * the clauses read: a flat column beside parted ones is no table the + * filter reads (it kept every row of a comparison on a name the key + * hides), and such a grouping does not stream. */ + bool by_key_carried = false; + bool by_key_carry = false; /* an output the grouping DAG does not serve, or a where: below */ + for (int64_t i = 0; i + 1 < dict_n && !by_key_carry; i += 2) { + int64_t kid = dict_elems[i]->i64; + if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || + kid == asc_id || kid == desc_id || kid == nearest_id) continue; + ray_t* ov = dict_elems[i + 1]; + by_key_carry = !is_single_group_key_projection(by_expr, ov) && + !is_group_dag_agg_expr(ov, tbl) && !is_decomposable_agg_compound(ov, tbl); + } + /* A where: comparing the name of a column the key's local hides reads + * the local; the parted aggregate grouping raised length on that, so + * the key is carried (the parted table copied to the columns read) for + * it too. Any other aggregate grouping keeps the table as it is, and so + * does a select with no outputs: it returns every input column. */ + if (!by_key_carry && n_out > 0 && where_expr && by_expr && by_expr->type == -RAY_SYM && + !(by_expr->attrs & ATTR_QUOTED) && table_has_parted_columns(tbl) && + ray_env_get_lexical_local(by_expr->i64) && tbl_has_col(tbl, by_expr->i64) && + clause_names_sym(where_expr, by_expr->i64)) + by_key_carry = true; + if (where_expr && by_key_carry && by_expr && by_expr->type == -RAY_SYM && + !(by_expr->attrs & ATTR_QUOTED) && !sym_names_col(tbl, by_expr->i64) && + !tbl_has_col(tbl, ray_sym_intern("__by_key", 8))) { + ray_t* kv = sym_binding(by_expr->i64); + if (kv && !ray_is_atom(kv) && (ray_is_vec(kv) || kv->type == RAY_LIST) && + ray_len(kv) == ray_table_nrows(tbl)) { + if (table_has_parted_columns(tbl)) { + /* by_key_carry holds only with an output (n_out > 0) */ + ray_t* flat = parted_flatten_read_cols(dict, tbl, false, NULL); + ray_release(tbl); + if (!flat || RAY_IS_ERR(flat)) { + scratch_free(dep_src_hdr); + DICT_VIEW_CLOSE(dv); return flat ? flat : ray_error("oom", NULL); + } + tbl = flat; + } + ray_t* keyed = ray_table_add_col(tbl, ray_sym_intern("__by_key", 8), kv); /* consumes tbl */ + if (!keyed || RAY_IS_ERR(keyed)) { + scratch_free(dep_src_hdr); + DICT_VIEW_CLOSE(dv); return keyed ? keyed : ray_error("oom", NULL); + } + tbl = keyed; + by_key_carried = true; + } + } + /* Build DAG */ ray_graph_t* g = ray_graph_new(tbl); if (!g) { @@ -13428,8 +18517,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Apply WHERE filter. */ if (where_expr) { + uint32_t where_input_id = root->id; /* When the WHERE is `(and a b c …)`, compile each conjunct as its - * own OP_FILTER. + * own OP_FILTER only when every complete subtree is invariant + * under default-source row restriction. A reduction or running + * descendant must see the original WHERE input, not prior survivors. * exec_filter on a TABLE input refines g->selection in place via * ray_rowsel_refine, so subsequent conjuncts only need to make * their predicate's output bool VALID for surviving rows — the @@ -13461,16 +18553,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * to the existing OP_AND tree, which ray_optimize * already constant-folds. */ int all_ok = 1; - /* `reorder_safe` flips to 0 when any conjunct contains - * an op that can fault, error or have observable - * side effects — division, modulo, call into a user - * function, etc. In that case we still chain the - * conjuncts as separate filters (the selection-aware - * win), but evaluate them in user-given order so an - * earlier guard like `(!= y 0)` keeps protecting a - * later `(< (/ x y) 10)`. */ + /* Keep the existing conservative error/order cost + * policy in addition to the domain proof. This flag + * alone never licenses chaining a cross-row expression. */ int reorder_safe = 1; - ray_op_t* compiled[64]; + uint32_t compiled[64]; int cost[64]; if (k > 64) all_ok = 0; /* Each conjunct must compile, must not be a pure @@ -13485,8 +18572,14 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * evaluate over a far smaller rowsel. */ for (int64_t i = 0; i < k && all_ok; i++) { ray_op_t* p = compile_expr_dag(g, elems[i + 1]); - if (!p || p->opcode == OP_CONST) { all_ok = 0; break; } - /* Walk the sub-DAG via stack DFS, looking for + if (!p || p->opcode == OP_CONST || + !ray_expr_subset_invariant(g, p->id)) { + all_ok = 0; + break; + } + /* Cost only: the complete dependency proof above + * covers hidden operands and fails closed on limits. + * Walk the sub-DAG via stack DFS, looking for * any OP_SCAN; tally cost contributions along * the way. Bound the depth to keep this check * cheap on degenerate trees. */ @@ -13494,8 +18587,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int c = 0; ray_op_t* stk[64]; int sp = 0; + uint32_t cost_budget = 4096; stk[sp++] = p; - while (sp > 0) { + while (sp > 0 && cost_budget > 0) { + cost_budget--; ray_op_t* cur = stk[--sp]; if (cur->opcode == OP_SCAN) has_scan = 1; /* Coarse per-node cost: comparison ops are @@ -13521,15 +18616,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, break; /* leaves — no compute cost */ default: c += 5; - /* Unknown op — could be arithmetic that - * faults (OP_DIV / OP_MOD divide-by-zero), - * a user-defined call with side effects, - * or any op whose error behavior depends - * on what the prior conjuncts already - * filtered out. Keep this conjunct in - * its user-given position so a guard like - * `(!= y 0)` continues to short-circuit - * a later `(< (/ x y) 10)`. */ + /* Do not broaden the old cost-based order + * policy merely because the expression is + * now proved row-local. Domain admission + * and error/order conservatism are separate. */ reorder_safe = 0; break; } @@ -13538,8 +18628,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (ch) stk[sp++] = ch; } } + if (sp > 0) reorder_safe = 0; /* truncated cost, not a proof */ if (!has_scan) { all_ok = 0; break; } - compiled[i] = p; + /* Later conjunct compilation may grow g->nodes. */ + compiled[i] = p->id; cost[i] = c; } if (all_ok) { @@ -13564,8 +18656,13 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } } } - for (int64_t i = 0; i < k; i++) - root = ray_filter(g, root, compiled[order[i]]); + uint32_t input_id = where_input_id; + for (int64_t i = 0; i < k; i++) { + root = ray_filter(g, op_node(g, input_id), + op_node(g, compiled[order[i]])); + if (!root) break; + input_id = root->id; + } and_chained = 1; } } @@ -13581,7 +18678,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, return pred_err ? pred_err : ray_error("domain", "select: failed to evaluate `where:` predicate"); } - root = ray_filter(g, root, pred); + root = ray_filter(g, op_node(g, where_input_id), pred); + } + if (!root) { + ray_graph_free(g); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return ray_error("oom", NULL); } } @@ -13909,12 +19011,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * reads through its KEY_READ macro). */ int use_eval_group = 0; if (by_key_sym >= 0) { - ray_t* key_col = ray_table_get_col(tbl, by_key_sym); - if (key_col) { - int8_t kct = key_col->type; + ray_col_meta_t km; + if (ray_table_col_meta(tbl, by_key_sym, &km)) { + int8_t kct = km.type; if (RAY_IS_PARTED(kct)) kct = (int8_t)RAY_PARTED_BASETYPE(kct); if (kct == RAY_LIST && (any_nonagg || n_out == 0 || - RAY_IS_PARTED(key_col->type) || !ray_agg_engine_v2)) + RAY_IS_PARTED(km.type) || !ray_agg_engine_v2)) use_eval_group = 1; else if (kct == RAY_GUID && (any_nonagg || n_out == 0)) /* RAY_GUID routes to eval-level ray_group_indices_fn only @@ -13940,9 +19042,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int64_t nk = ray_len(by_expr); int64_t* sym_ids = (int64_t*)ray_data(by_expr); for (int64_t k = 0; k < nk; k++) { - ray_t* key_col = ray_table_get_col(tbl, sym_ids[k]); - if (!key_col) continue; - int8_t kct = key_col->type; + ray_col_meta_t km; + if (!ray_table_col_meta(tbl, sym_ids[k], &km)) continue; + int8_t kct = km.type; if (RAY_IS_PARTED(kct)) kct = (int8_t)RAY_PARTED_BASETYPE(kct); /* STR keys (dict-encoded OR plain) take the parallel DAG path: * dict-STR substitutes int32 codes; plain/computed STR groups @@ -13950,7 +19052,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * O(N*ngroups) eval toy-grouper (33% allocator churn). LIST * composites with plain aggregates use v2 structural grouping. */ if (kct == RAY_LIST && (any_nonagg || n_out == 0 || - RAY_IS_PARTED(key_col->type) || !ray_agg_engine_v2)) { + RAY_IS_PARTED(km.type) || !ray_agg_engine_v2)) { use_eval_group = 1; break; } @@ -13993,6 +19095,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } else if (by_expr->type == RAY_SYM && ray_len(by_expr) == 1) { single_scalar_key = 1; } + /* The scatter maps rows through the key column: a key that is + * no column the name reads (a lexical local hides it, or it is + * a global vector) is grouped by its value at eval level. */ + if (single_scalar_key && by_key_sym >= 0 && !sym_names_col(tbl, by_key_sym)) + single_scalar_key = 0; /* A plain multi-key by: stays on the DAG path when the outputs * the DAG cannot serve are count(distinct) aggregates and * literal broadcasts (no true row expression): the scatter @@ -14007,14 +19114,16 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_t* eval_tbl = tbl; if (where_expr) { root = ray_optimize(g, root); - /* Projection-aware compaction: when this WHERE filter feeds only - * the keys-only multi-key DISTINCT path under an active outer - * projection hint, publish the keys∪proj_keep keep-set so the - * filter finalization (ray_execute_inner) gathers just those - * columns. Scoped to this ray_execute via save/restore. */ - /* keep-set = by-keys ∪ proj_keep; carve exactly that many - * int64 (union ≤ nk + proj_keep_n) so the write never - * truncates a group key or a proj_keep entry. */ + /* Projection-aware compaction: publish the columns the group + * reads so the filter finalization (ray_execute_inner) gathers + * just those — keys ∪ proj_keep when this WHERE feeds only the + * keys-only multi-key DISTINCT path under an active outer + * projection hint (filt_compact_keep), else the columns the + * by: and the outputs name (eval_group_keep). Scoped to this + * ray_execute via save/restore. */ + /* The carve covers both sets: nk + proj_keep_n for the first, + * every column + proj_keep_n for the second, so the write + * never truncates a group key or a referenced column. */ ray_vm_t* fvm = __VM; ray_t* filt_hdr = NULL; int64_t* filt_buf = NULL; @@ -14023,12 +19132,27 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int32_t sv_fd = fvm ? fvm->filt_depth : 0; if (fvm) { int64_t filt_cap = (by_expr ? ray_len(by_expr) : 0) + fvm->proj_keep_n; - if (filt_cap < 1) filt_cap = 1; + int64_t eg_cap = eval_group_keep_cap(tbl); + if (filt_cap < eg_cap) filt_cap = eg_cap; + if (by_key_carried) filt_cap++; filt_buf = (int64_t*)scratch_alloc(&filt_hdr, (size_t)filt_cap * sizeof(int64_t)); if (filt_buf) { int fk_n = filt_compact_keep(dict, by_expr, tbl, from_id, where_id, by_id, filt_buf, (int)filt_cap); + /* every other eval-level group: the columns its by: + * and outputs name (#769) */ + if (fk_n == 0) + fk_n = eval_group_keep(dict, by_expr, tbl, n_out, + from_id, where_id, by_id, + take_id, asc_id, desc_id, + filt_buf, (int)filt_cap); + if (fk_n > 0 && by_key_carried) { + int64_t hidden = ray_sym_intern("__by_key", 8); + bool found = false; + for (int j = 0; j < fk_n; j++) found |= filt_buf[j] == hidden; + if (!found) filt_buf[fk_n++] = hidden; + } if (fk_n > 0) { fvm->filt_keep = filt_buf; fvm->filt_keep_n = fk_n; fvm->filt_depth = fvm->eval_depth; @@ -14051,6 +19175,23 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } else { ray_graph_free(g); g = NULL; } + /* Eval-level grouping, composite or single-key, reads key and + * output cells row by row, which a parted column does not + * serve. A where: hands back a flattened copy of the rows it + * keeps; when the table reaches here as is, flatten the columns + * the clauses read and the keys (a by-dict key is a column + * under its alias, which no clause names); with no outputs + * every column is read (first of each group below), so the + * whole table is flattened. */ + if (eval_tbl == tbl && table_has_parted_columns(tbl)) { + ray_t* flat = n_out > 0 ? parted_flatten_read_cols(dict, tbl, false, by_expr) + : query_materialize_parted_table(tbl); + if (!flat || RAY_IS_ERR(flat)) { + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return flat ? flat : ray_error("oom", NULL); + } + eval_tbl = flat; + } if (by_key_sym < 0 && by_expr->type == RAY_SYM && ray_len(by_expr) > 1) { int64_t nk = ray_len(by_expr); int64_t* key_syms = (int64_t*)ray_data(by_expr); @@ -14071,7 +19212,14 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } for (int64_t k = 0; k < nk; k++) { - key_cols[k] = ray_table_get_col(eval_tbl, key_syms[k]); + key_cols[k] = ray_table_col(eval_tbl, key_syms[k]); + if (key_cols[k] && RAY_IS_ERR(key_cols[k])) { + ray_t* kerr = key_cols[k]; + scratch_free(keycols_hdr); + if (eval_tbl != tbl) ray_release(eval_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return kerr; + } if (!key_cols[k]) { scratch_free(keycols_hdr); if (eval_tbl != tbl) ray_release(eval_tbl); @@ -14099,7 +19247,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, switch (key_cols[k]->type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: case RAY_SYM: case RAY_STR: break; + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: case RAY_STR: break; default: distinct_only = false; break; } } @@ -14107,12 +19255,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * parted/mapcommon/nested fall back to the legacy path. */ int64_t dchk_nc = ray_table_ncols(eval_tbl); for (int64_t c = 0; c < dchk_nc && distinct_only; c++) { - ray_t* cc = ray_table_get_col_idx(eval_tbl, c); - if (!cc) { distinct_only = false; break; } - switch (cc->type) { + ray_col_meta_t cm; + if (!ray_table_col_meta_idx(eval_tbl, c, &cm)) { distinct_only = false; break; } + switch (cm.type) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: case RAY_SYM: case RAY_F64: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: case RAY_F64: case RAY_GUID: case RAY_STR: case RAY_LIST: break; default: distinct_only = false; break; } @@ -14145,15 +19293,25 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * the routing change above, every all-count-agg >1-key by: * answers through the parallel DAG/v2 path instead (see * test/rfl/query/width_matrix.rfl's ROUTING NOTE on the `rmk` - * cell). The only remaining trigger into this block is a - * RAY_LIST-typed by-key column, which hits a pre-existing - * vec_new(LIST) bug building the key output column. Left in - * place — not correctness-load-bearing — pending a follow-up - * that either fixes the LIST-key case or deletes this block. */ + * cell). The only remaining trigger into this block was a + * RAY_LIST-typed by-key column (an all-count output set is + * all DAG aggregates, so only a LIST key sets + * use_eval_group for it), whose cells the int64 key reader + * does not hold (the key column then failed in vec_new): a + * key it cannot read leaves the shape to the composite path + * below, which makes the block unreachable. The STR and + * GUID arms of that gate are defensive. Left in place — + * not correctness-load-bearing — pending a follow-up that + * deletes this block. */ int64_t pre_take_groups = nrows; bool has_pre_take = unsorted_positive_take_limit( dict_elems, dict_n, asc_id, desc_id, take_id, nrows, &pre_take_groups); + for (int64_t k = 0; k < nk && has_pre_take; k++) { + int8_t pkt = query_col_base_type(key_cols[k]); + if (pkt == RAY_LIST || pkt == RAY_STR || pkt == RAY_GUID) + has_pre_take = false; + } if (has_pre_take && pre_take_groups <= 1024) { /* Per-key reader and per-output name buffers carved to the * exact key / output counts (no fixed slot cap). Both live @@ -14310,6 +19468,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, case RAY_SYM: atom = ray_sym(key_vals[off]); break; case RAY_I64: case RAY_TIMESTAMP: atom = ray_i64(key_vals[off]); break; + case RAY_TIMESPAN: atom = ray_timespan(key_vals[off]); break; case RAY_I32: case RAY_DATE: case RAY_TIME: atom = ray_i32((int32_t)key_vals[off]); break; @@ -14489,7 +19648,13 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_t* agg_col_expr = agg_elems[1]; ray_t* src_col_val = NULL; if (agg_col_expr->type == -RAY_SYM && !(agg_col_expr->attrs & ATTR_QUOTED)) { - src_col_val = ray_table_get_col(eval_tbl, agg_col_expr->i64); + src_col_val = ray_table_col(eval_tbl, agg_col_expr->i64); + if (src_col_val && RAY_IS_ERR(src_col_val)) { + for (int ai = 0; ai < n_agg_out; ai++) if (agg_results[ai]) ray_release(agg_results[ai]); + scratch_free(aggnames_hdr); scratch_free(aggres_hdr); scratch_free(keycols_hdr); + ray_release(groups); if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return src_col_val; + } if (src_col_val) ray_retain(src_col_val); } if (!src_col_val) { @@ -14618,9 +19783,24 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, size_t slen = cell ? ray_str_len(cell) : 0; key_vec = ray_str_vec_append(key_vec, sp ? sp : "", sp ? slen : 0); } + } else if (kt == RAY_LIST) { + /* A LIST key's cells are the source's items: the key + * column lists them (no typed vector holds them). */ + key_vec = ray_list_new(out_groups); + for (int64_t gi = 0; gi < out_groups && key_vec && !RAY_IS_ERR(key_vec); gi++) { + ray_t* row_key = grp_items[gi * 2]; + ray_t* cell = (row_key && row_key->type == RAY_LIST && k < row_key->len) + ? ((ray_t**)ray_data(row_key))[k] : NULL; + key_vec = ray_list_append(key_vec, cell ? cell : RAY_NULL_OBJ); + } } else { + /* The composite cells are SYM atoms (runtime ids, + * collection_elem's atom rule), so the key column is a + * runtime-domain W64 vec: the source's width sizes ids + * of the source's own (file) domain and truncated the + * runtime ids into unrelated symbols. */ key_vec = (kt == RAY_SYM) - ? ray_sym_vec_new(src->attrs & RAY_SYM_W_MASK, out_groups) + ? ray_sym_vec_new(RAY_SYM_W64, out_groups) : ray_vec_new(kt, out_groups); if (key_vec && !RAY_IS_ERR(key_vec)) { key_vec->len = out_groups; @@ -14682,7 +19862,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, bool is_key = false; for (int64_t k = 0; k < nk; k++) if (key_syms[k] == cn) { is_key = true; break; } if (is_key) continue; - ray_t* sc = ray_table_get_col_idx(eval_tbl, c); + ray_t* sc = ray_table_col_idx(eval_tbl, c); + if (sc && RAY_IS_ERR(sc)) { + ray_free(fi_hdr); ray_release(result); ray_release(groups); if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return sc; + } if (!sc) continue; ray_t* dst = NULL; if (sc->type == RAY_STR) { @@ -14751,17 +19935,19 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * outputs, and the result's key column is named as the DAG path * names a computed key (#707). */ int64_t key_out_name = by_key_sym; - if (by_key_sym < 0 && by_expr->type != RAY_SYM) { + /* A key name that reads no column (a lexical local hides it, or + * it names a global vector) is evaluated the same way. */ + bool key_is_value = by_key_sym >= 0 && by_expr->type == -RAY_SYM && + !sym_names_col(eval_tbl, by_key_sym); + int64_t key_col_sym = ray_sym_intern("__by_key", 8); + if (key_is_value && by_key_carried && tbl_has_col(eval_tbl, key_col_sym)) { + by_key_sym = key_col_sym; /* filtered with the rows (by_key_carried) */ + } else if ((by_key_sym < 0 && by_expr->type != RAY_SYM) || key_is_value) { int64_t kn = ray_table_nrows(eval_tbl); ray_t* kv = NULL; if (ray_env_push_query_scope() != RAY_OK) kv = ray_error("oom", NULL); else { - int64_t enc = ray_table_ncols(eval_tbl); - for (int64_t c = 0; c < enc; c++) { - ray_t* cv = ray_table_get_col_idx(eval_tbl, c); - if (cv) ray_env_set_query_local(ray_table_col_name(eval_tbl, c), cv); - } - kv = group_key_eval(by_expr, eval_tbl); + kv = group_key_eval_bound(by_expr, eval_tbl); /* an error is the query's */ ray_env_pop_scope(); } if (kv && !RAY_IS_ERR(kv) && ray_is_atom(kv)) { @@ -14769,6 +19955,15 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_release(kv); kv = wide ? wide : ray_error("type", "by: cannot broadcast the key"); } + /* A named key is one value per row of the table, as on the + * DAG path; under a where: it came through the filter. */ + if (key_is_value && kv && !RAY_IS_ERR(kv) && !ray_is_atom(kv) && + ray_len(kv) != ray_table_nrows(tbl)) { + int64_t got = ray_len(kv); + ray_release(kv); + kv = ray_error("length", "by: key has %lld values for %lld rows", + (long long)got, (long long)ray_table_nrows(tbl)); + } if (kv && !RAY_IS_ERR(kv) && (!ray_is_vec(kv) || ray_len(kv) != kn)) { int64_t got = ray_len(kv); ray_release(kv); @@ -14781,7 +19976,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return kv ? kv : ray_error("domain", "by: key produced no result"); } by_key_sym = ray_sym_intern("__by_key", 8); - if (ray_table_get_col(eval_tbl, by_key_sym)) { + if (tbl_has_col(eval_tbl, by_key_sym)) { ray_release(kv); if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); @@ -14797,8 +19992,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return keyed ? keyed : ray_error("oom", NULL); } eval_tbl = keyed; - key_out_name = derived_key_name(by_expr); - for (int64_t i = 0; i + 1 < dict_n; i += 2) { + /* A named key keeps its name, as on the no-output form; an + * output of that name keeps both columns, the key first. */ + key_out_name = key_is_value ? key_out_name : derived_key_name(by_expr); + for (int64_t i = 0; i + 1 < dict_n && !key_is_value; i += 2) { int64_t kid = dict_elems[i]->i64; if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id) continue; @@ -14812,7 +20009,13 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("nyi", "eval-level groupby requires scalar key"); } - ray_t* key_col = ray_table_get_col(eval_tbl, by_key_sym); + ray_t* key_col = ray_table_col(eval_tbl, by_key_sym); + if (!key_col || RAY_IS_ERR(key_col)) { + if (eval_tbl != tbl) ray_release(eval_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return key_col ? key_col : ray_error("domain", "group key column not found"); + } /* Fast path: (select {from: t by: k}) with no aggs and * no non-agg expressions — we only need first-of-group @@ -14901,7 +20104,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, cn = ray_table_col_name(eval_tbl, pass - 1); if (cn == by_key_sym) continue; } - ray_t* sc = ray_table_get_col(eval_tbl, cn); + ray_t* sc = ray_table_col(eval_tbl, cn); + if (sc && RAY_IS_ERR(sc)) { first_err = sc; break; } if (!sc) continue; ray_t* dst = NULL; int8_t sct = sc->type; @@ -15015,8 +20219,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int64_t nc0 = ray_table_ncols(eval_tbl); ray_t* empty = ray_table_new(nc0); if (!RAY_IS_ERR(empty)) { - /* Key column first */ - { ray_t* sc = ray_table_get_col(eval_tbl, by_key_sym); + /* Key column first (key_col: read for the grouping above) */ + { ray_t* sc = key_col; if (sc) { ray_t* ev = ray_group_gather(sc, NULL, 0); if (ev && !RAY_IS_ERR(ev)) { empty = ray_table_add_col(empty, by_key_sym, ev); ray_release(ev); } @@ -15025,10 +20229,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t c = 0; c < nc0; c++) { int64_t cn = ray_table_col_name(eval_tbl, c); if (cn == by_key_sym) continue; - ray_t* sc = ray_table_get_col_idx(eval_tbl, c); - ray_t* ev = (sc->type == RAY_STR) ? ray_vec_new(RAY_STR, 0) : - (sc->type == RAY_LIST) ? ray_list_new(0) : - ray_vec_new(sc->type, 0); + ray_col_meta_t scm; + (void)ray_table_col_meta_idx(eval_tbl, c, &scm); + ray_t* ev = (scm.type == RAY_STR) ? ray_vec_new(RAY_STR, 0) : + (scm.type == RAY_LIST) ? ray_list_new(0) : + ray_vec_new(scm.type, 0); if (ev && !RAY_IS_ERR(ev)) { empty = ray_table_add_col(empty, cn, ev); ray_release(ev); } } } @@ -15091,7 +20296,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Resolve source column from filtered table */ ray_t* src_col_val = NULL; if (agg_col_expr->type == -RAY_SYM && !(agg_col_expr->attrs & ATTR_QUOTED)) { - src_col_val = ray_table_get_col(eval_tbl, agg_col_expr->i64); + src_col_val = ray_table_col(eval_tbl, agg_col_expr->i64); + if (src_col_val && RAY_IS_ERR(src_col_val)) { + for (int ai = 0; ai < n_agg_out; ai++) { if (agg_results[ai]) ray_release(agg_results[ai]); } + scratch_free(aggnames_hdr); scratch_free(aggres_hdr); + ray_release(groups); if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return src_col_val; + } if (src_col_val) ray_retain(src_col_val); } if (!src_col_val) { @@ -15224,8 +20434,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_release(groups); if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } - ray_t* _aqt = bind_all_columns(eval_tbl); - ray_t* full_val = ray_eval(val_expr_item); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_referenced_query(eval_tbl, &val_expr_item, 1, &bind_err_); + ray_t* full_val = bind_err_ ? bind_err_ : ray_eval(val_expr_item); g_active_query_table = _aqt; ray_env_pop_scope(); if (RAY_IS_ERR(full_val)) { @@ -15317,9 +20528,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Key column: build a typed vector matching the source column type */ ray_t** grp_items = (ray_t**)ray_data(groups); - ray_t* key_col_src = ray_table_get_col(eval_tbl, by_key_sym); + ray_col_meta_t key_src_m; + bool key_src_has = ray_table_col_meta(eval_tbl, by_key_sym, &key_src_m); { - int8_t ktype = key_col_src ? key_col_src->type : RAY_I64; + int8_t ktype = key_src_has ? key_src_m.type : RAY_I64; if (RAY_IS_PARTED(ktype)) ktype = (int8_t)RAY_PARTED_BASETYPE(ktype); ray_t* key_vec; if (ktype == RAY_STR) { @@ -15335,7 +20547,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t gi = 0; gi < n_groups && key_vec && !RAY_IS_ERR(key_vec); gi++) key_vec = ray_list_append(key_vec, grp_items[gi * 2]); } else { - uint8_t kattrs = key_col_src ? key_col_src->attrs : 0; + uint8_t kattrs = key_src_has ? key_src_m.attrs : 0; if (ktype == RAY_SYM) key_vec = ray_sym_vec_new(kattrs & RAY_SYM_W_MASK, n_groups); else @@ -15388,7 +20600,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t c = 0; c < nc && !RAY_IS_ERR(result); c++) { int64_t cn = ray_table_col_name(eval_tbl, c); if (cn == by_key_sym) continue; - ray_t* sc = ray_table_get_col_idx(eval_tbl, c); + ray_t* sc = ray_table_col_idx(eval_tbl, c); + if (sc && RAY_IS_ERR(sc)) { ray_release(result); result = sc; break; } ray_t* dst = NULL; if (sc->type == RAY_STR) { dst = ray_vec_new(RAY_STR, n_groups); @@ -15473,8 +20686,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, { int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && RAY_IS_PARTED(col->type)) { table_is_parted = 1; break; } + ray_col_meta_t cm; + if (ray_table_col_meta_idx(tbl, c, &cm) && RAY_IS_PARTED(cm.type)) { table_is_parted = 1; break; } } } /* Classification + arith-of-aggs pre-decomposition. The @@ -15542,6 +20755,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, continue; } } + /* A constant output is broadcast over the groups after the + * group runs (the scatter's constant arm), reading no row: + * a parted table stays in place and a WHERE stays fused. */ + if (const_output_expr(expr, tbl, 0)) continue; has_nonagg_needing_flat = 1; } } @@ -15551,27 +20768,13 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * below by materializing only the group key and distinct column when * needed; other non-aggs still require a flat table view. */ if (has_nonagg_needing_flat && table_is_parted) { - ray_t* flat_tbl = ray_table_new(ray_table_ncols(tbl)); + /* Every parted slot, encoded or not, is read and flattened; only + * a non-parted encoded column passes into flat_tbl encoded. */ + ray_t* flat_tbl = query_materialize_parted_table(tbl); if (!flat_tbl || RAY_IS_ERR(flat_tbl)) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return flat_tbl ? flat_tbl : ray_error("oom", NULL); } - int64_t ncols = ray_table_ncols(tbl); - for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - int64_t name = ray_table_col_name(tbl, c); - ray_t* flat_col = query_materialize_parted_col(col); - if (!flat_col || RAY_IS_ERR(flat_col)) { - ray_release(flat_tbl); ray_graph_free(g); ray_release(tbl); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return flat_col ? flat_col : ray_error("oom", NULL); - } - flat_tbl = ray_table_add_col(flat_tbl, name, flat_col); - ray_release(flat_col); - if (!flat_tbl || RAY_IS_ERR(flat_tbl)) { - ray_graph_free(g); ray_release(tbl); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return flat_tbl ? flat_tbl : ray_error("oom", NULL); - } - } ray_graph_free(g); ray_release(tbl); tbl = flat_tbl; @@ -15665,10 +20868,22 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, by_name = by_expr->i64; else if (by_expr->type == RAY_SYM && ray_len(by_expr) == 1) by_name = ((int64_t*)ray_data(by_expr))[0]; - ray_t* by_col = (by_name >= 0) - ? ray_table_get_col(tbl, by_name) : NULL; - if (by_col) - sg_armed = ray_slice_group_probe(g, root, by_col); + /* The probe needs a SYM key with a hash or part index: + * decided from metadata, the key read only then. */ + ray_col_meta_t bm; + if (by_name >= 0 && ray_table_col_meta(tbl, by_name, &bm) && + bm.type == RAY_SYM && + (bm.index_kind == RAY_IDX_HASH || bm.index_kind == RAY_IDX_PART)) { + ray_t* bix = NULL; + ray_t* ixe = ray_table_col_index(tbl, by_name, &bix); + ray_t* by_col = ixe ? ixe : ray_table_col(tbl, by_name); /* cached: no second decode */ + if (by_col && RAY_IS_ERR(by_col)) { + ray_graph_free(g); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return by_col; + } + if (by_col) + sg_armed = ray_slice_group_probe(g, root, by_col); + } } if (sg_armed) goto where_done; /* exec_node populates g->selection as a side effect @@ -15701,7 +20916,39 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } } else { root = ray_optimize(g, root); + /* The group over the filtered table reads only the columns + * its by: and outputs name: publish them so the filter + * finalization gathers just those (#769: a parted + * count(distinct) group copied every column). Scoped to + * this ray_execute via save/restore. */ + ray_vm_t* fvm = __VM; + ray_t* filt_hdr = NULL; + const int64_t* sv_fk = fvm ? fvm->filt_keep : NULL; + int sv_fn = fvm ? fvm->filt_keep_n : 0; + int32_t sv_fd = fvm ? fvm->filt_depth : 0; + if (fvm) { + int64_t filt_cap = eval_group_keep_cap(tbl) + (by_key_carried ? 1 : 0); + int64_t* filt_buf = (int64_t*)scratch_alloc(&filt_hdr, (size_t)filt_cap * sizeof(int64_t)); + int fk_n = filt_buf + ? eval_group_keep(dict, parted_bydict_deferred ? deferred_bydict : by_expr, + tbl, n_out, from_id, where_id, by_id, + take_id, asc_id, desc_id, filt_buf, (int)filt_cap) + : 0; + if (fk_n > 0 && by_key_carried) { + int64_t hidden = ray_sym_intern("__by_key", 8); + bool found = false; + for (int j = 0; j < fk_n; j++) found |= filt_buf[j] == hidden; + if (!found) filt_buf[fk_n++] = hidden; + } + if (fk_n > 0) { + fvm->filt_keep = filt_buf; fvm->filt_keep_n = fk_n; + fvm->filt_depth = fvm->eval_depth; + } + } ray_t* fres = ray_execute(g, root); + if (fvm) { fvm->filt_keep = sv_fk; fvm->filt_keep_n = sv_fn; + fvm->filt_depth = sv_fd; } + scratch_free(filt_hdr); /* filt_buf dead past the restore */ ray_graph_free(g); g = NULL; if (!fres || RAY_IS_ERR(fres)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return fres ? fres : ray_error("domain", "select: `where:` filter produced no result"); } if (ray_is_lazy(fres)) fres = ray_lazy_materialize(fres); @@ -15753,8 +21000,19 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * named the way the eval-level path names a computed key. (The * grouping decided over the distinct values, derived_key_vocab_aggs, * was tried ahead of the WHERE.) */ - ray_t* dom_key = derived_key_over_sym_domain(by_expr, tbl, g->selection); - if (dom_key) { + ray_t* dom_key = by_key_carried ? NULL + : derived_key_over_sym_domain(by_expr, tbl, g->selection); + if (by_key_carried) { + /* This is still a value key, not a source-column key. + * Keep its constant-key grouping route, using the values + * already narrowed by the filter. */ + ray_t* carried = ray_table_col(tbl, ray_sym_intern("__by_key", 8)); + key_ops[0] = carried && !RAY_IS_ERR(carried) ? ray_const_vec(g, carried) : NULL; + if (carried && RAY_IS_ERR(carried)) { + if (!g->compile_err) g->compile_err = carried; + else ray_error_free(carried); + } + } else if (dom_key) { key_ops[0] = ray_const_vec(g, dom_key); ray_release(dom_key); } else { @@ -15763,6 +21021,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Only a real expression is renamed: a bare column symbol lands * here too and keeps its own name. */ computed_single_key = (key_ops[0] != NULL && by_expr->type == RAY_LIST); + /* A name that reads no column (a lexical local hides it, or a + * global holds a vector) compiles to a constant, which carries + * no name: the key keeps the name, as on the eval-level path. */ + named_value_key = key_ops[0] != NULL && (by_key_carried || key_ops[0]->opcode == OP_CONST) && + by_expr->type == -RAY_SYM && !(by_expr->attrs & ATTR_QUOTED) && + !sym_names_col(tbl, by_expr->i64); if (!key_ops[0]) { ray_t* cerr = graph_take_compile_err(g); ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr ? cerr : ray_error("domain", "select by: failed to compile group key expression"); } n_keys = 1; } @@ -15816,9 +21080,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Canonical aggregand type-admission (matches the scalar * builtins): reject non-numeric / absolute-temporal inputs so a * by-group sum/avg/var never silently folds symbol ids etc. */ - if (agg_ins[n_aggs]->out_type > 0 && - !agg_type_admitted(op, agg_ins[n_aggs]->out_type)) { - int8_t in_t = agg_ins[n_aggs]->out_type; /* capture BEFORE free */ + if (dag_operand_type(g, agg_ins[n_aggs]) > 0 && + !agg_type_admitted(op, dag_operand_type(g, agg_ins[n_aggs]))) { + int8_t in_t = dag_operand_type(g, agg_ins[n_aggs]); /* capture BEFORE free */ ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("type", "select by: aggregation does not admit input type %s", ray_type_name(in_t)); } agg_ins2[n_aggs] = NULL; @@ -15829,9 +21093,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, agg_ins2[n_aggs] = compile_expr_dag(g, agg_elems[2]); agg_in2_ids[n_aggs] = agg_ins2[n_aggs] ? agg_ins2[n_aggs]->id : RAY_OP_NONE; if (!agg_ins2[n_aggs]) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile binary aggregation second argument"); } - if (agg_ins2[n_aggs]->out_type > 0 && - !agg_type_admitted(op, agg_ins2[n_aggs]->out_type)) { - int8_t in_t = agg_ins2[n_aggs]->out_type; + if (dag_operand_type(g, agg_ins2[n_aggs]) > 0 && + !agg_type_admitted(op, dag_operand_type(g, agg_ins2[n_aggs]))) { + int8_t in_t = dag_operand_type(g, agg_ins2[n_aggs]); ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("type", "select by: binary aggregation does not admit second input type %s", ray_type_name(in_t)); } has_binary_agg = 1; @@ -15896,9 +21160,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr ? cerr : ray_error("domain", "select by: failed to compile aggregation argument"); } - if (agg_ins[n_aggs]->out_type > 0 && - !agg_type_admitted(hop, agg_ins[n_aggs]->out_type)) { - int8_t in_t = agg_ins[n_aggs]->out_type; + if (dag_operand_type(g, agg_ins[n_aggs]) > 0 && + !agg_type_admitted(hop, dag_operand_type(g, agg_ins[n_aggs]))) { + int8_t in_t = dag_operand_type(g, agg_ins[n_aggs]); for (int ci = 0; ci < n_compound; ci++) ray_release(compound_rw[ci]); ray_graph_free(g); ray_release(tbl); @@ -15917,9 +21181,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: failed to compile binary aggregation second argument"); } - if (agg_ins2[n_aggs]->out_type > 0 && - !agg_type_admitted(hop, agg_ins2[n_aggs]->out_type)) { - int8_t in_t = agg_ins2[n_aggs]->out_type; + if (dag_operand_type(g, agg_ins2[n_aggs]) > 0 && + !agg_type_admitted(hop, dag_operand_type(g, agg_ins2[n_aggs]))) { + int8_t in_t = dag_operand_type(g, agg_ins2[n_aggs]); for (int ci = 0; ci < n_compound; ci++) ray_release(compound_rw[ci]); ray_graph_free(g); ray_release(tbl); @@ -16055,7 +21319,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * A dotted name like `Timestamp.date` compiles to a scan + trunc * chain, not a direct column lookup, so it must land in the * computed-key fallback path below (key_sym stays -1). Otherwise - * downstream `ray_table_get_col(filtered_tbl, key_sym)` would + * downstream `ray_table_col(filtered_tbl, key_sym)` would * return NULL for the non-existent "Timestamp.date" column and * the subsequent deref would crash. */ int64_t key_sym = -1; @@ -16066,12 +21330,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, key_sym = ((int64_t*)ray_data(by_expr))[0]; /* So must a name that is no column of the table (a global * vector): the grouping above evaluated it as an expression. */ - if (key_sym >= 0 && !ray_table_get_col(filtered_tbl, key_sym)) + if (key_sym >= 0 && !ray_table_has_col(filtered_tbl, key_sym)) key_sym = -1; /* And a column name the grouping did not read as that column: a * local of the same name shadows it, the key is the local's value * and its grouped column is not named after the column. */ - if (key_sym >= 0 && !ray_table_get_col(grouped, key_sym)) + if (key_sym >= 0 && !ray_table_has_col(grouped, key_sym)) key_sym = -1; if (n_groups == 0) { @@ -16088,10 +21352,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int64_t empty_key_name = key_sym; ray_t* empty_key_vec = NULL; if (key_sym >= 0) { - ray_t* sc = ray_table_get_col(filtered_tbl, key_sym); - if (sc) { - empty_key_vec = ray_group_gather(sc, NULL, 0); - } + empty_key_vec = tbl_col_empty(filtered_tbl, key_sym); } else { /* Match the computed-key fallback's naming * rules (dotted tail / last name arg) and @@ -16133,11 +21394,15 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * to get a length-0 key vector typed like the * non-empty path would produce it. */ ray_env_push_query_scope(); - for (int64_t c = 0; c < nc0; c++) { - ray_env_set_query_local(ray_table_col_name(filtered_tbl, c), - ray_table_get_col_idx(filtered_tbl, c)); + ray_t* ck_vec = bind_referenced_columns(filtered_tbl, &by_expr, 1); + if (ck_vec) { /* a column that cannot materialize */ + ray_env_pop_scope(); + ray_release(empty); + if (filtered_tbl != tbl) ray_release(filtered_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ck_vec; } - ray_t* ck_vec = ray_eval(by_expr); + ck_vec = ray_eval(by_expr); if (ck_vec && !RAY_IS_ERR(ck_vec) && ray_is_lazy(ck_vec)) ck_vec = ray_lazy_materialize(ck_vec); ray_env_pop_scope(); @@ -16162,10 +21427,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t c = 0; c < nc0; c++) { int64_t cn = ray_table_col_name(filtered_tbl, c); if (cn == empty_key_name) continue; - ray_t* sc = ray_table_get_col_idx(filtered_tbl, c); - ray_t* ev = (sc->type == RAY_STR) ? ray_vec_new(RAY_STR, 0) : - (sc->type == RAY_LIST) ? ray_list_new(0) : - ray_vec_new(sc->type, 0); + ray_col_meta_t scm; + (void)ray_table_col_meta_idx(filtered_tbl, c, &scm); + ray_t* ev = (scm.type == RAY_STR) ? ray_vec_new(RAY_STR, 0) : + (scm.type == RAY_LIST) ? ray_list_new(0) : + ray_vec_new(scm.type, 0); if (!RAY_IS_ERR(ev)) { empty = ray_table_add_col(empty, cn, ev); ray_release(ev); } } } @@ -16180,17 +21446,21 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Computed group key (e.g., xbar) — fall back to eval-level groupby */ ray_release(grouped); int64_t tbl_ncols = ray_table_ncols(filtered_tbl); - ray_env_push_query_scope(); - for (int64_t c = 0; c < tbl_ncols; c++) { - int64_t cn = ray_table_col_name(filtered_tbl, c); - ray_t* cv = ray_table_get_col_idx(filtered_tbl, c); - ray_env_set_query_local(cn, cv); + ray_t* computed_key = NULL; + int64_t carried_sym = ray_sym_intern("__by_key", 8); + if (by_key_carried && tbl_has_col(filtered_tbl, carried_sym)) { + /* This value key has already followed the where mask. */ + computed_key = ray_table_col(filtered_tbl, carried_sym); + if (computed_key && !RAY_IS_ERR(computed_key)) ray_retain(computed_key); + } else { + ray_env_push_query_scope(); + computed_key = bind_referenced_columns(filtered_tbl, &by_expr, 1); + if (!computed_key) computed_key = derived_key_over_sym_domain(by_expr, filtered_tbl, NULL); + if (!computed_key) computed_key = ray_eval(by_expr); + if (computed_key && !RAY_IS_ERR(computed_key) && ray_is_lazy(computed_key)) + computed_key = ray_lazy_materialize(computed_key); + ray_env_pop_scope(); } - ray_t* computed_key = derived_key_over_sym_domain(by_expr, filtered_tbl, NULL); - if (!computed_key) computed_key = ray_eval(by_expr); - if (computed_key && !RAY_IS_ERR(computed_key) && ray_is_lazy(computed_key)) - computed_key = ray_lazy_materialize(computed_key); /* `(mmax 2 x)` */ - ray_env_pop_scope(); if (!computed_key || RAY_IS_ERR(computed_key)) { if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); @@ -16344,7 +21614,15 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * key: e.g. `by: Timestamp` (plain, non-dotted) would * collide with the source Timestamp column. */ if (cn == ckey_name) continue; - ray_t* sc = ray_table_get_col_idx(filtered_tbl, c); + ray_t* sc = ray_table_col_idx(filtered_tbl, c); + if (sc && RAY_IS_ERR(sc)) { + ray_release(res2); + if (fi2_hdr) ray_free(fi2_hdr); + ray_release(groups2); ray_release(computed_key); + if (filtered_tbl != tbl) ray_release(filtered_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return sc; + } ray_t* dc = ray_group_gather(sc, fi2, ng2); if (!dc || RAY_IS_ERR(dc)) { ray_release(res2); @@ -16362,12 +21640,15 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return res2; } - ray_t* orig_key_col = ray_table_get_col(filtered_tbl, key_sym); - int64_t nrows_orig = orig_key_col ? orig_key_col->len : 0; - + ray_t* orig_key_col = ray_table_col(filtered_tbl, key_sym); /* Read group key values from grouped table BEFORE releasing it. * grp_key_col points into grouped — must not access after release. */ - ray_t* grp_key_col = ray_table_get_col(grouped, key_sym); + ray_t* grp_key_col = (orig_key_col && RAY_IS_ERR(orig_key_col)) + ? orig_key_col : ray_table_col(grouped, key_sym); + if (grp_key_col && RAY_IS_ERR(grp_key_col)) { + ray_release(grouped); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return grp_key_col; + } + int64_t nrows_orig = orig_key_col ? orig_key_col->len : 0; int8_t kt = orig_key_col ? orig_key_col->type : 0; /* Both hold once key_sym names a column the grouping read (see * where key_sym is resolved); refuse rather than read unset keys. */ @@ -16557,24 +21838,24 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Build result table: key column first, then others */ int64_t ncols = ray_table_ncols(filtered_tbl); ray_t* result = ray_table_new(ncols); - if (RAY_IS_ERR(result)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } + if (RAY_IS_ERR(result)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } /* Add key column first */ - ray_t* key_vec_src = ray_table_get_col(filtered_tbl, key_sym); + ray_t* key_vec_src = orig_key_col; /* ray_table_col(filtered_tbl, key_sym), read above */ if (key_vec_src->type == RAY_STR) { ray_t* key_vec_dst = ray_vec_new(RAY_STR, n_groups); - if (!key_vec_dst || RAY_IS_ERR(key_vec_dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return key_vec_dst ? key_vec_dst : ray_error("oom", NULL); } + if (!key_vec_dst || RAY_IS_ERR(key_vec_dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return key_vec_dst ? key_vec_dst : ray_error("oom", NULL); } for (int64_t gi = 0; gi < n_groups; gi++) { size_t slen = 0; const char* sp = ray_str_vec_get(key_vec_src, first_idx[gi], &slen); key_vec_dst = ray_str_vec_append(key_vec_dst, sp ? sp : "", sp ? slen : 0); - if (RAY_IS_ERR(key_vec_dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return key_vec_dst; } + if (RAY_IS_ERR(key_vec_dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return key_vec_dst; } } result = ray_table_add_col(result, key_sym, key_vec_dst); ray_release(key_vec_dst); } else { ray_t* key_vec_dst = ray_vec_new(key_vec_src->type, n_groups); - if (RAY_IS_ERR(key_vec_dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return key_vec_dst; } + if (RAY_IS_ERR(key_vec_dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return key_vec_dst; } /* Set len BEFORE the store loop: store_typed_elem routes * null atoms through ray_vec_set_null, which range-checks * idx against vec->len and silently returns RAY_ERR_RANGE @@ -16597,25 +21878,26 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(filtered_tbl, c); if (col_name == key_sym) continue; - ray_t* src_col = ray_table_get_col_idx(filtered_tbl, c); + ray_t* src_col = ray_table_col_idx(filtered_tbl, c); + if (src_col && RAY_IS_ERR(src_col)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return src_col; } int8_t ct = src_col->type; if (ct == RAY_STR) { /* String column: build STR vector */ ray_t* dst = ray_vec_new(RAY_STR, n_groups); - if (!dst || RAY_IS_ERR(dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return dst ? dst : ray_error("oom", NULL); } + if (!dst || RAY_IS_ERR(dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return dst ? dst : ray_error("oom", NULL); } for (int64_t gi = 0; gi < n_groups; gi++) { size_t slen = 0; const char* sp = ray_str_vec_get(src_col, first_idx[gi], &slen); dst = ray_str_vec_append(dst, sp ? sp : "", sp ? slen : 0); - if (RAY_IS_ERR(dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return dst; } + if (RAY_IS_ERR(dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return dst; } } result = ray_table_add_col(result, col_name, dst); ray_release(dst); } else if (ct == RAY_LIST) { /* List column: pick items */ ray_t* dst = ray_alloc(n_groups * sizeof(ray_t*)); - if (!dst) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } + if (!dst) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } dst->type = RAY_LIST; dst->len = n_groups; ray_t** dout = (ray_t**)ray_data(dst); @@ -16632,7 +21914,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * propagate through store_typed_elem → ray_vec_set_null * (same reason as the key column above). */ ray_t* dst = ray_vec_new(ct, n_groups); - if (RAY_IS_ERR(dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return dst; } + if (RAY_IS_ERR(dst)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); ray_release(result); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return dst; } dst->len = n_groups; for (int64_t gi = 0; gi < n_groups; gi++) { int alloc = 0; @@ -16643,7 +21925,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, result = ray_table_add_col(result, col_name, dst); ray_release(dst); } - if (RAY_IS_ERR(result)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } + if (RAY_IS_ERR(result)) { if (fi_heap_hdr) ray_free(fi_heap_hdr); if (filtered_tbl != tbl) ray_release(filtered_tbl); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } } if (fi_heap_hdr) ray_free(fi_heap_hdr); @@ -16745,9 +22027,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * builtins): reject non-numeric (SYM/STR/GUID) and, for sum, * absolute-temporal (DATE/TIMESTAMP) inputs so the DAG never * silently aggregates raw symbol ids / string bytes / dates. */ - if (s_agg_ins[s_n_aggs]->out_type > 0 && - !agg_type_admitted(op, s_agg_ins[s_n_aggs]->out_type)) { - int8_t in_t = s_agg_ins[s_n_aggs]->out_type; /* capture BEFORE free */ + if (dag_operand_type(g, s_agg_ins[s_n_aggs]) > 0 && + !agg_type_admitted(op, dag_operand_type(g, s_agg_ins[s_n_aggs]))) { + int8_t in_t = dag_operand_type(g, s_agg_ins[s_n_aggs]); /* capture BEFORE free */ if (g->selection) { ray_release(g->selection); g->selection = NULL; } ray_graph_free(g); ray_release(tbl); scratch_free(sagg_hdr); @@ -16765,9 +22047,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, s_use_eval_fallback = 1; break; } - if (s_agg_ins2[s_n_aggs]->out_type > 0 && - !agg_type_admitted(op, s_agg_ins2[s_n_aggs]->out_type)) { - int8_t in_t = s_agg_ins2[s_n_aggs]->out_type; + if (dag_operand_type(g, s_agg_ins2[s_n_aggs]) > 0 && + !agg_type_admitted(op, dag_operand_type(g, s_agg_ins2[s_n_aggs]))) { + int8_t in_t = dag_operand_type(g, s_agg_ins2[s_n_aggs]); if (g->selection) { ray_release(g->selection); g->selection = NULL; } ray_graph_free(g); ray_release(tbl); scratch_free(sagg_hdr); @@ -16789,6 +22071,21 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return eval_tbl ? eval_tbl : ray_error("oom", NULL); } release_eval_tbl = 1; + } else if (table_has_parted_columns(tbl)) { + /* The evaluator binds each column as a whole vector: + * over a parted table flatten the columns the select + * reads, as sel_compact does for the where: rows. A + * select reading no column (`(count [1 2 3])`) keeps + * the parted table: its columns are bound as they are + * (bind_all_columns in eval_expr_whole_column_impl), + * but nothing reads one, so none is materialised. */ + eval_tbl = parted_flatten_read_cols(dict, tbl, true, NULL); + if (!eval_tbl || RAY_IS_ERR(eval_tbl)) { + ray_graph_free(g); ray_release(tbl); + scratch_free(sagg_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return eval_tbl ? eval_tbl : ray_error("oom", NULL); + } + release_eval_tbl = 1; } ray_t* result = eval_scalar_agg_outputs(dict_elems, dict_n, eval_tbl, from_id, where_id, by_id, @@ -16879,7 +22176,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t k = 0; k < nk; k++) { int64_t ks = val->type == -RAY_SYM ? val->i64 : sym_cell_runtime_id(val, k); if (select_scan_output(g, col_ops, nc, ks) >= 0) continue; - if (!ray_table_get_col(tbl, ks) || nc >= nc_max) continue; + if (!tbl_has_col(tbl, ks) || nc >= nc_max) continue; ray_t* nm = ray_sym_str(ks); ray_op_t* sc = nm ? ray_scan(g, ray_str_ptr(nm)) : NULL; if (!sc) continue; @@ -17028,7 +22325,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * alias bound below as a one-row column must not be read * per row. A bare column name is the column itself. */ ray_t* expr = dict_elems[i + 1]; - int whole_verb = is_whole_column_projection(expr, tbl); + int whole_verb = select_fallback_bulk_minmax(expr, tbl, nrows) || + is_whole_column_projection(expr, tbl); int one_value = !whole_verb && (!any_row_proj || (select_fallback_has_agg(expr) && !expr_refs_row_column(expr, tbl)) || @@ -17086,6 +22384,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, col = at_row0 ? eval_expr_per_row_impl(expr, eval_tbl, 1) : (whole_verb || one_value) ? eval_expr_whole_column_impl(expr, eval_tbl) + : nrows == 0 ? select_fallback_empty_col(expr, eval_tbl) : eval_expr_per_row_impl(expr, eval_tbl, nrows); bool enlist_scalar = whole_verb && expr->type == RAY_LIST && ((ray_t**)ray_data(expr))[0]->i64 == ray_sym_intern("enlist", 6); @@ -17263,8 +22562,10 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * machinery — has_sort keeps the two disjoint). Also NOT pushed when a * deferred key WHERE runs AFTER the group (post_group_where_expr): that * filter drops result rows, so taking the first N groups before it would - * under-fill the answer. Nor over a PARTED input (exec_group_parted - * mis-applies the hint on empty partitions — see table_is_parted), nor + * under-fill the answer. A PARTED input takes the hint too: the parted + * group keeps the first N groups in first-seen order (the per-partition + * route carries each group's first global row and keeps the N smallest; + * the flattened group takes the hint itself). Nor * with a LIST-producing aggregate (top/bot): exec.c's HEAD/TAIL table trim * now retains LIST cells, but the group's LIST output has no reason to pay * a trim it can skip, and the take is a no-op there anyway. */ @@ -17272,8 +22573,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, take_pre_t take_pre = {0}; /* decoded take: value, reused by apply_sort_take */ bool group_take_push = (take_expr && by_expr && !nearest_expr && !has_sort && !post_group_where_expr && !has_list_agg - && !group_keys_have_bool(by_expr, tbl) - && !table_is_parted(tbl)); + && !group_keys_have_bool(by_expr, tbl)); if (take_expr && !nearest_expr && (!by_expr || group_take_push)) { ray_t* tv = ray_eval(take_expr); if (!tv || RAY_IS_ERR(tv)) { ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return tv ? tv : ray_error("domain", "select: failed to evaluate `take:`"); } @@ -17346,7 +22646,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, ray_t* kept = keep_n >= 0 ? ray_table_new(keep_n > 0 ? keep_n : 1) : NULL; for (int64_t c = 0; kept && !RAY_IS_ERR(kept) && c < keep_n; c++) kept = ray_table_add_col(kept, ray_table_col_name(result, c), - ray_table_get_col_idx(result, c)); + ray_table_slot_idx(result, c)); if (kept && !RAY_IS_ERR(kept)) { ray_release(result); result = kept; } else if (kept) ray_release(kept); } @@ -17365,6 +22665,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (ray_table_col_name(result, c) == kname) { kname = ray_sym_intern("key", 3); break; } ray_table_set_col_name(result, 0, kname); } + if (named_value_key && result && !RAY_IS_ERR(result) && ray_is_lazy(result)) + result = ray_lazy_materialize(result); + if (named_value_key && result && !RAY_IS_ERR(result) && result->type == RAY_TABLE && + ray_table_ncols(result) > 0) + ray_table_set_col_name(result, 0, by_expr->i64); if (self_emit_set) ray_group_emit_filter_set(prev_self_emit); if (post_group_where_expr && result && !RAY_IS_ERR(result)) @@ -17394,18 +22699,29 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (by_expr && result && !RAY_IS_ERR(result) && result->type == RAY_TABLE) { if (ray_is_lazy(result)) result = ray_lazy_materialize(result); if (result && !RAY_IS_ERR(result) && result->type == RAY_TABLE) { - ray_t* key_col = ray_table_get_col_idx(result, 0); - if (key_col && key_col->type == RAY_BOOL && key_col->len >= 2) { + ray_col_meta_t rkm; + ray_t* key_col = (ray_table_col_meta_idx(result, 0, &rkm) && + rkm.type == RAY_BOOL && rkm.len >= 2) + ? ray_table_col_idx(result, 0) : NULL; + ray_col_meta_t okm; + int64_t by_sym = -1; + ray_t* orig_key = NULL; + if (key_col && !RAY_IS_ERR(key_col)) { /* Find first-occurrence order of bool values in original * table. Accept both scalar `-RAY_SYM` and single-element * `RAY_SYM` vector forms. */ - int64_t by_sym = -1; if (by_expr->type == -RAY_SYM) by_sym = by_expr->i64; else if (by_expr->type == RAY_SYM && ray_len(by_expr) == 1) by_sym = ((int64_t*)ray_data(by_expr))[0]; - ray_t* orig_key = (by_sym >= 0) ? ray_table_get_col(tbl, by_sym) : NULL; - if (orig_key && orig_key->type == RAY_BOOL && orig_key->len > 0) { + if (by_sym >= 0 && ray_table_col_meta(tbl, by_sym, &okm) && + okm.type == RAY_BOOL && okm.len > 0) + orig_key = ray_table_col(tbl, by_sym); + if (orig_key && RAY_IS_ERR(orig_key)) key_col = orig_key; + } + if (key_col && RAY_IS_ERR(key_col)) { ray_release(result); result = key_col; } + else if (key_col) { + if (orig_key) { bool first_val = ((bool*)ray_data(orig_key))[0]; bool result_first = ((bool*)ray_data(key_col))[0]; if (first_val != result_first) { @@ -17417,7 +22733,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int ok = 1; for (int64_t c = 0; c < ncols_r && ok; c++) { int64_t cn = ray_table_col_name(result, c); - ray_t* col = ray_table_get_col_idx(result, c); + ray_t* col = ray_table_col_idx(result, c); + if (col && RAY_IS_ERR(col)) { ray_release(result); result = col; ok = 0; break; } int esz = ray_elem_size(col->type); ray_t* new_col = ray_vec_new(col->type, nrows_r); if (RAY_IS_ERR(new_col)) { ok = 0; break; } @@ -17469,8 +22786,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (rebuilt && !RAY_IS_ERR(rebuilt)) { for (int64_t c = 0; c < nc - 1; c++) { int64_t cn = ray_table_col_name(result, c); - ray_t* col = ray_table_get_col_idx(result, c); - rebuilt = ray_table_add_col(rebuilt, cn, col); + rebuilt = ray_table_add_col(rebuilt, cn, ray_table_slot_idx(result, c)); } ray_release(result); result = rebuilt; @@ -17588,9 +22904,11 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * rows: the flag lets `concat` treat a reduced text cell * as a cell (a null is empty text, a literal joins it) * rather than as a collection. */ - for (int hi = 0; hi < n_hidden_aggs; hi++) - (void)ray_env_set_local_rows(hidden_agg_names[hi], - ray_table_get_col_idx(result, hbase + hi), 1); + for (int hi = 0; hi < n_hidden_aggs && !cerr; hi++) { + ray_t* hc = ray_table_col_idx(result, hbase + hi); + if (hc && RAY_IS_ERR(hc)) cerr = hc; + else (void)ray_env_set_local_rows(hidden_agg_names[hi], hc, 1); + } int64_t n_groups = ray_table_nrows(result); /* The wrappers are query text over the group result: * `concat` and the other query-aware forms read the @@ -17637,7 +22955,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, for (int64_t c = 0; c < rnc && nt && !RAY_IS_ERR(nt); c++) { if (c >= hbase && c < hbase + n_hidden_aggs) continue; nt = ray_table_add_col(nt, ray_table_col_name(result, c), - ray_table_get_col_idx(result, c)); + ray_table_slot_idx(result, c)); } for (int ci = 0; ci < n_compound && nt && !RAY_IS_ERR(nt); ci++) nt = ray_table_add_col(nt, compound_names[ci], @@ -17678,6 +22996,18 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (result && !RAY_IS_ERR(result) && result->type == RAY_TABLE) { int64_t n_groups = ray_table_nrows(result); + /* Every non-agg constant (const_output_expr) reads no row, so + * with no group the key is not read either: the empty columns + * are built directly. */ + int all_const = 1; + for (int64_t ni = 0; ni < n_nonaggs && all_const; ni++) + if (!const_output_expr(nonagg_exprs[ni], tbl, 0)) all_const = 0; + if (n_groups == 0 && all_const) { + result = grouped_nonagg_empty(result, tbl, nonagg_exprs, nonagg_names, n_nonaggs); + if (RAY_IS_ERR(result)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } + goto nonagg_done; + } + /* R8 fast path: every non-agg is a literal atom expression * with no column refs. Skip the entire row→gid mapping — * each non-agg becomes a typed broadcast vec the same width @@ -17713,6 +23043,67 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } goto nonagg_done; } + /* Every non-agg constant, some a call (`(+ 1 2)`): each is + * evaluated once, as the row scatter below does, and its + * atom broadcast into per-group LIST cells, the scatter's + * constant disposition; the literals among them take that + * disposition too. No row is read, so a parted table is + * never flattened for it. A value that is not an atom + * (an atomic builtin over atoms yields one) goes the row + * way, which evaluates the pure call again. */ + if (all_const) { + ray_t* cvals_hdr = NULL; + ray_t** cvals = (ray_t**)scratch_calloc(&cvals_hdr, + (size_t)n_nonaggs * sizeof(ray_t*)); + if (!cvals) { + ray_release(result); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); + } + ray_t* cerr = NULL; + int all_atoms = 1; + /* One query scope for them all: a constant binds no + * column (const_output_expr admits no column name). */ + if (ray_env_push_query_scope() != RAY_OK) cerr = ray_error("oom", NULL); + else { + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_referenced_query(tbl, nonagg_exprs, n_nonaggs, &bind_err_); + if (bind_err_) cerr = bind_err_; + for (int64_t ni = 0; ni < n_nonaggs && !cerr && all_atoms; ni++) { + ray_t* v = ray_eval(nonagg_exprs[ni]); + if (!v || RAY_IS_ERR(v)) { + cerr = v ? v : ray_error("domain", "select by: failed to evaluate non-aggregate column expression"); + break; + } + cvals[ni] = v; + if (!ray_is_atom(v)) all_atoms = 0; + } + g_active_query_table = _aqt; + ray_env_pop_scope(); + } + for (int64_t ni = 0; ni < n_nonaggs && !cerr && all_atoms; ni++) { + ray_t* list_col = ray_alloc((size_t)n_groups * sizeof(ray_t*)); + if (!list_col) { cerr = ray_error("oom", NULL); break; } + list_col->type = RAY_LIST; + list_col->len = n_groups; + ray_t** cells = (ray_t**)ray_data(list_col); + for (int64_t gi = 0; gi < n_groups; gi++) { + ray_retain(cvals[ni]); + cells[gi] = cvals[ni]; + } + result = ray_table_add_col(result, nonagg_names[ni], list_col); + ray_release(list_col); + if (RAY_IS_ERR(result)) { cerr = result; result = NULL; } + } + for (int64_t ni = 0; ni < n_nonaggs; ni++) + if (cvals[ni]) ray_release(cvals[ni]); + scratch_free(cvals_hdr); + if (cerr) { + if (result) ray_release(result); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr; + } + if (all_atoms) goto nonagg_done; + } } /* Resolve key sym — a single scalar key, or the first key of a @@ -17735,9 +23126,18 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("domain", "select by: could not resolve scalar group key symbol"); } - ray_t* orig_key = ray_table_get_col(tbl, ks); - ray_t* grp_key = ray_table_get_col(result, ks); - int64_t nrows = orig_key ? ray_parted_nrows(orig_key) : 0; + /* A single-file encoded key is handed to the bounded count as + * its slot (read by range) and decoded only for the slices. */ + ray_t* key_enc = mk_nk <= 1 ? cd_enc_slot(tbl, ks) : NULL; + ray_col_meta_t key_em; + ray_t* orig_key = key_enc ? key_enc : ray_table_col(tbl, ks); + ray_t* grp_key = (orig_key && RAY_IS_ERR(orig_key)) ? orig_key : ray_table_col(result, ks); + if (grp_key && RAY_IS_ERR(grp_key)) { + ray_release(result); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return grp_key; + } + int64_t nrows = key_enc ? (ray_col_meta_of(key_enc, &key_em) ? key_em.len : 0) + : orig_key ? ray_parted_nrows(orig_key) : 0; if (!orig_key || !grp_key) { ray_release(result); ray_release(tbl); @@ -17745,10 +23145,45 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } if (n_groups > 0 && nrows > 0) { + /* Every non-agg a count(distinct col) over one key: count + * them in bounded memory from the key column itself, with + * no row map, no slices and no flattened parted columns. */ + if (mk_nk <= 1 && + cd_bounded_scatter_ok(nonagg_exprs, n_nonaggs, tbl, orig_key, + grp_key, saved_selection, nrows, n_groups)) { + ray_t* cd_err = NULL; + for (int64_t ni = 0; ni < n_nonaggs && !cd_err; ni++) { + ray_t* cd_inner = match_count_distinct(nonagg_exprs[ni]); + ray_t* src = cd_enc_slot(tbl, cd_inner->i64); /* read by range */ + if (!src) src = ray_table_col(tbl, cd_inner->i64); + ray_t* col = src && RAY_IS_ERR(src) ? src + : ray_cd_bounded(tbl, orig_key, grp_key, NULL, n_groups, + src, saved_selection, nrows); + if (!col) col = ray_error("domain", "select by: count distinct column does not cover the table's rows"); + if (RAY_IS_ERR(col)) { cd_err = col; break; } + result = ray_table_add_col(result, nonagg_names[ni], col); + ray_release(col); + if (RAY_IS_ERR(result)) { cd_err = result; result = NULL; } + } + if (cd_err) { + if (result) ray_release(result); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cd_err; + } + goto nonagg_done; + } + if (key_enc) { /* the slices read the key decoded */ + orig_key = ray_table_col(tbl, ks); + if (!orig_key || RAY_IS_ERR(orig_key)) { + ray_release(result); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return orig_key ? orig_key : ray_error("domain", "select by: group key column not found"); + } + } ray_t* scan_key = orig_key; int scan_key_owned = 0; if (RAY_IS_PARTED(scan_key->type) || scan_key->type == RAY_MAPCOMMON) { - scan_key = query_materialize_parted_col(scan_key); + scan_key = query_materialize_parted_col(scan_key, tbl); if (!scan_key || RAY_IS_ERR(scan_key)) { ray_release(result); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return scan_key ? scan_key : ray_error("oom", NULL); @@ -17788,7 +23223,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, (dst) = _u; break; } \ case RAY_DATE: case RAY_TIME: \ (dst) = ((const int32_t*)_d)[idx]; break; \ - case RAY_TIMESTAMP: \ + case RAY_TIMESPAN: case RAY_TIMESTAMP: \ (dst) = ((const int64_t*)_d)[idx]; break; \ /* SYM: raw index — scan_key vs grp_key, where grp_key \ * is gathered FROM scan_key (same domain), never a \ @@ -17836,8 +23271,22 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, /* Allocations — any failure errors out rather than * silently returning partial results. */ + /* A composite key under a selection whose every non-agg the + * bounded kernel counts: the row map holds the selected + * rows only (in selection order), not one cell for every + * row of the table. */ + bool cd_compact = mk_nk > 1 && saved_selection && n_nonaggs > 0 && + (ray_cd_bounded_preferred(tbl, NULL, NULL, NULL, nrows, n_groups) || + cd_nonaggs_by_range(nonagg_exprs, n_nonaggs, tbl)); + for (int64_t ni = 0; ni < n_nonaggs && cd_compact; ni++) { + ray_t* cd_inner = match_count_distinct(nonagg_exprs[ni]); + cd_compact = cd_inner && cd_inner->type == -RAY_SYM && + !(cd_inner->attrs & ATTR_QUOTED) && + cd_src_bounded_ok(tbl, cd_inner); + } + int64_t rg_rows = cd_compact ? ray_rowsel_meta(saved_selection)->total_pass : nrows; ray_t* gk_hdr = ray_alloc((size_t)n_groups * sizeof(int64_t)); - ray_t* rg_hdr = ray_alloc((size_t)nrows * sizeof(int64_t)); + ray_t* rg_hdr = ray_alloc((size_t)(rg_rows > 0 ? rg_rows : 1) * sizeof(int64_t)); ray_t* cnt_hdr = ray_alloc((size_t)n_groups * sizeof(int64_t)); ray_t* off_hdr = ray_alloc((size_t)n_groups * sizeof(int64_t)); ray_t* pos_hdr = ray_alloc((size_t)n_groups * sizeof(int64_t)); @@ -17873,7 +23322,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, int rgid_did_mask = 0; if (mk_nk > 1) { ray_t* mk_err = rgid_build_multikey(tbl, result, by_expr, nrows, - n_groups, saved_selection, row_gid); + n_groups, saved_selection, row_gid, + cd_compact); if (mk_err) { ray_free(gk_hdr); ray_free(rg_hdr); ray_free(cnt_hdr); ray_free(off_hdr); ray_free(pos_hdr); @@ -17882,6 +23332,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return mk_err; } rgid_did_mask = 1; /* the probe applied the selection */ + if (cd_compact) ray_profile_tick("count-distinct: row map over the kept rows"); } else if (okt == RAY_STR) { /* Dict-code row_gid fast path: when the group key is a * dict-encoded STR column, exec_group already grouped on its @@ -18194,16 +23645,23 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * non-agg shape — including count(distinct) on small * group counts — falls into count_distinct_per_group_buf * which requires idx_buf+offsets+grp_cnt. */ + /* The bounded kernel (ray_cd_bounded) counts a plain + * column over the row map without the slices either, + * where the slices' row buffers would not fit. */ + bool cd_bounded_rows = ray_cd_bounded_preferred(tbl, NULL, NULL, NULL, nrows, n_groups) || + cd_nonaggs_by_range(nonagg_exprs, n_nonaggs, tbl); int needs_slice_idx = 0; for (int64_t ni = 0; ni < n_nonaggs && !needs_slice_idx; ni++) { ray_t* cd_inner = match_count_distinct(nonagg_exprs[ni]); - int simple_cd_global = (cd_inner && - cd_inner->type == -RAY_SYM && - !(cd_inner->attrs & ATTR_QUOTED) && - n_groups > 50000); + int simple_cd = cd_inner && cd_inner->type == -RAY_SYM && + !(cd_inner->attrs & ATTR_QUOTED); + if (simple_cd && cd_bounded_rows && + cd_src_bounded_ok(tbl, cd_inner)) + continue; + int simple_cd_global = simple_cd && n_groups > 50000; if (simple_cd_global) { - ray_t* source = ray_table_get_col(tbl, cd_inner->i64); - int8_t type = source ? source->type : 0; + ray_col_meta_t sm; + int8_t type = (!ray_env_get_lexical_local(cd_inner->i64) && ray_table_col_meta(tbl, cd_inner->i64, &sm)) ? sm.type : 0; simple_cd_global = type == RAY_BOOL || type == RAY_U8 || type == RAY_I16 || type == RAY_I32 || type == RAY_I64 || type == RAY_F32 || type == RAY_F64 || type == RAY_DATE || @@ -18245,14 +23703,44 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, * computed expressions use the per-group fallback. */ ray_t* src_for_global = NULL; int src_owned = 0; - if (cd_inner->type == -RAY_SYM && - !(cd_inner->attrs & ATTR_QUOTED)) { - src_for_global = ray_table_get_col(tbl, cd_inner->i64); + /* The column itself is read only for the bounded + * kernel and the global-hash kernel; the per-group + * slice path reads it from tbl. */ + bool cd_col_ref = cd_inner->type == -RAY_SYM && + !(cd_inner->attrs & ATTR_QUOTED) && + !ray_env_get_lexical_local(cd_inner->i64) && + tbl_has_col(tbl, cd_inner->i64); + /* the bounded kernel reads an encoded column by + * range (cd_enc_slot); the other kernels decoded */ + ray_t* src_enc = cd_col_ref && cd_bounded_rows ? cd_enc_slot(tbl, cd_inner->i64) : NULL; + if (cd_col_ref && (cd_bounded_rows || n_groups > 50000)) { + src_for_global = src_enc ? src_enc : ray_table_col(tbl, cd_inner->i64); + if (src_for_global && RAY_IS_ERR(src_for_global)) { + col = src_for_global; /* the query's error, below */ + src_for_global = NULL; + } } - if (src_for_global && n_groups > 50000) { + if (src_for_global && cd_bounded_rows && + ray_cd_bounded_col_ok(src_for_global, true)) { + col = ray_cd_bounded(tbl, NULL, NULL, row_gid, n_groups, + src_for_global, cd_compact ? saved_selection : NULL, + nrows); + if (!col && cd_compact) + col = ray_error("domain", "select by: count distinct column does not cover the table's rows"); + if (!col && !idx_buf && n_groups <= 50000) + col = ray_error("domain", "select by: count distinct column does not cover the table's rows"); + } + if (!col && src_enc && src_for_global == src_enc) { + src_for_global = ray_table_col(tbl, cd_inner->i64); + if (src_for_global && RAY_IS_ERR(src_for_global)) { + col = src_for_global; /* the query's error, below */ + src_for_global = NULL; + } + } + if (!col && src_for_global && n_groups > 50000) { if (RAY_IS_PARTED(src_for_global->type) || src_for_global->type == RAY_MAPCOMMON) { - ray_t* flat = query_materialize_parted_col(src_for_global); + ray_t* flat = query_materialize_parted_col(src_for_global, tbl); if (!flat || RAY_IS_ERR(flat)) { col = flat ? flat : ray_error("oom", NULL); src_for_global = NULL; @@ -18262,7 +23750,7 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } } } - if (src_for_global) { + if (cd_col_ref && (src_for_global || n_groups <= 50000)) { /* COUNT(DISTINCT) is exact per SQL/DSL * semantics — the streaming HLL fast path * here silently returned an approximate @@ -18358,8 +23846,9 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, if (ray_env_push_query_scope() != RAY_OK) { scatter_err = ray_error("oom", NULL); break; } - ray_t* _aqt = bind_all_columns(tbl); - ray_t* full_val = ray_eval(nonagg_exprs[ni]); + ray_t* bind_err_ = NULL; + ray_t* _aqt = bind_referenced_query(tbl, &nonagg_exprs[ni], 1, &bind_err_); + ray_t* full_val = bind_err_ ? bind_err_ : ray_eval(nonagg_exprs[ni]); g_active_query_table = _aqt; ray_env_pop_scope(); if (!full_val || RAY_IS_ERR(full_val)) { @@ -18467,21 +23956,8 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, } #undef RELEASE_SCAN_KEY } else { - /* Empty grouped aggregates retain their result type; - * ordinary row expressions produce per-group LIST cells. */ - for (int64_t ni = 0; ni < n_nonaggs; ni++) { - ray_t* expr = nonagg_exprs[ni]; - ray_t* empty_list = match_count_distinct(expr) ? ray_vec_new(RAY_I64, 0) - : is_streaming_aggr_unary_call(expr, tbl) ? aggr_unary_per_group_buf(expr, tbl, NULL, NULL, NULL, 0) - : can_atom_broadcast(expr) ? atom_broadcast_vec(expr, 0) : ray_list_new(0); - if (!empty_list || RAY_IS_ERR(empty_list)) { - ray_release(result); ray_release(tbl); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return empty_list ? empty_list : ray_error("oom", NULL); - } - result = ray_table_add_col(result, nonagg_names[ni], empty_list); - ray_release(empty_list); - if (RAY_IS_ERR(result)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } - } + result = grouped_nonagg_empty(result, tbl, nonagg_exprs, nonagg_names, n_nonaggs); + if (RAY_IS_ERR(result)) { ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } } nonagg_done: ; /* R8 fast-path target; nothing else to do here */ } @@ -18496,7 +23972,12 @@ static ray_t* ray_select_body(ray_t** args, int64_t n, bool aliases_resolved, scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } if (result && result->type == RAY_TABLE) { - ray_t* base_col = ray_table_get_col(result, dep_key_base_sym); + ray_t* base_col = ray_table_col(result, dep_key_base_sym); + if (base_col && RAY_IS_ERR(base_col)) { + ray_release(result); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return base_col; + } if (!base_col || !key_type_i64_projectable(base_col->type)) { ray_release(result); ray_release(tbl); @@ -18568,6 +24049,10 @@ static void xbar_par_fn(void* vctx, uint32_t worker_id, if (c->pow2) { int64_t mask = ~(b - 1); for (int64_t i = start; i < end; i++) o[i] = in[i] & mask; + } else if (b == -1) { + /* Every integer is a multiple of -1; dividing the null + * sentinel INT64_MIN by -1 would trap (SIGFPE). */ + for (int64_t i = start; i < end; i++) o[i] = in[i]; } else { for (int64_t i = start; i < end; i++) { int64_t a = in[i]; @@ -18616,6 +24101,8 @@ static bool xbar_bucket_fits_vec_type(int8_t out_type, int64_t b) { } ray_t* ray_xbar_fn(ray_t* col, ray_t* bucket) { + if (ray_has_timespan(col) || ray_has_timespan(bucket)) + return ray_timespan_xbar(col, bucket); /* Vectorised fast path for `(xbar VEC scalar_int)` on integer or * temporal columns. The generic atomic_map_binary path was * allocating one ray_t* atom per row and calling ray_xbar_fn @@ -18635,7 +24122,9 @@ ray_t* ray_xbar_fn(ray_t* col, ray_t* bucket) { col->type == RAY_I16 || col->type == RAY_TIMESTAMP || col->type == RAY_DATE || col->type == RAY_TIME) && !RAY_ATOM_IS_NULL(bucket)) { - int64_t b = bucket->i64; + /* Read the bucket by its own width: a narrow atom keeps only its + * low bytes, so bucket->i64 of an I16/I32 -7 is 65529/4294967289. */ + int64_t b = as_i64(bucket); if (b == 0) return ray_error("domain", "xbar: bucket size must be non-zero"); if (!xbar_bucket_fits_vec_type(col->type, b)) return atomic_map_binary(ray_xbar_fn, col, bucket); @@ -18690,31 +24179,39 @@ ray_t* ray_xbar_fn(ray_t* col, ray_t* bucket) { /* Both are integer types (i64, i32, i16) → integer xbar */ if (is_numeric(col) && is_numeric(bucket) && !is_float_op(col, bucket)) { int64_t a = as_i64(col), b = as_i64(bucket); - if (b == 0 || RAY_ATOM_IS_NULL(col) || RAY_ATOM_IS_NULL(bucket)) - return ray_error("domain", "xbar: bucket size must be non-zero and operands non-null"); + if (b == 0 || RAY_ATOM_IS_NULL(bucket)) + return ray_error("domain", "xbar: bucket size must be non-zero and non-null"); + /* Result type follows the wider of the two operands */ + int8_t rt = -RAY_I64; + if (col->type == -RAY_I32 && bucket->type == -RAY_I32) rt = -RAY_I32; + if (col->type == -RAY_I16 && bucket->type == -RAY_I16) rt = -RAY_I16; + /* A null value buckets to the null of the result type, as a null + * element of a vector does. */ + if (RAY_ATOM_IS_NULL(col)) return ray_typed_null(rt); int64_t q = a / b; if ((a ^ b) < 0 && q * b != a) q--; int64_t result = q * b; - /* Result type follows the wider of the two operands */ - if (col->type == -RAY_I32 && bucket->type == -RAY_I32) return make_i32((int32_t)result); - if (col->type == -RAY_I16 && bucket->type == -RAY_I16) return make_i16((int16_t)result); + if (rt == -RAY_I32) return make_i32((int32_t)result); + if (rt == -RAY_I16) return make_i16((int16_t)result); return make_i64(result); } /* Float path: either operand is f64 */ if (is_numeric(col) && is_numeric(bucket)) { - if (RAY_ATOM_IS_NULL(col) || RAY_ATOM_IS_NULL(bucket)) - return ray_error("domain", "xbar: operands must be non-null"); double c = as_f64(col), b = as_f64(bucket); - if (b == 0.0) return ray_error("domain", "xbar: bucket size must be non-zero"); + if (b == 0.0 || RAY_ATOM_IS_NULL(bucket)) + return ray_error("domain", "xbar: bucket size must be non-zero and non-null"); + if (RAY_ATOM_IS_NULL(col)) return ray_typed_null(-RAY_F64); double fq = floor(c / b); return make_f64(fq * b); } /* Temporal xbar: col is temporal, bucket is integer or temporal (not float) */ if (is_temporal(col) && (is_temporal(bucket) || (is_numeric(bucket) && bucket->type != -RAY_F64))) { - int64_t a = col->i64, b; + /* DATE / TIME atoms are 32-bit: their typed null writes only the + * low word, so col->i64 of 0Nd read 2^31 (5881610.07.10). */ + int64_t a = col->type == -RAY_TIMESTAMP ? col->i64 : (int64_t)col->i32, b; if (is_temporal(bucket)) { - b = bucket->i64; + b = bucket->type == -RAY_TIMESTAMP ? bucket->i64 : (int64_t)bucket->i32; /* Cross-temporal conversion: TIME(ms) bucket on TIMESTAMP(ns) col */ if (col->type == -RAY_TIMESTAMP && bucket->type == -RAY_TIME) b *= 1000000LL; @@ -18722,6 +24219,8 @@ ray_t* ray_xbar_fn(ray_t* col, ray_t* bucket) { b = as_i64(bucket); } if (b == 0 || RAY_ATOM_IS_NULL(bucket)) return ray_error("domain", "xbar: bucket size must be non-zero and non-null"); + /* A null value is the column type's null, as in the vector path. */ + if (RAY_ATOM_IS_NULL(col)) return ray_typed_null(col->type); int64_t q = a / b; if ((a ^ b) < 0 && q * b != a) q--; int64_t result = q * b; @@ -18820,6 +24319,11 @@ static ray_t* append_atom_to_col(ray_t* col_vec, ray_t* atom) { int32_t v = atom->i32; return ray_vec_append(col_vec, &v); } + case RAY_TIMESPAN: { + if (at != -RAY_TIMESPAN) return ray_error("type", "insert: timespan column requires a timespan value, got %s", ray_type_name(at)); + int64_t v = atom->i64; + return ray_vec_append(col_vec, &v); + } case RAY_TIMESTAMP: { if (at != -RAY_TIMESTAMP) return ray_error("type", "insert: timestamp column requires a timestamp value, got %s", ray_type_name(at)); int64_t v = atom->i64; @@ -18912,34 +24416,7 @@ static ray_t* append_boxed_table_col(ray_t* orig_col, ray_t* payload, static bool upsert_col_ok(ray_t* col); /* defined with the upsert path below */ static int64_t upsert_atom_int(ray_t* a); -/* The sub-table evaluation is only equivalent to the legacy whole-table - * evaluation for elementwise expressions. Accept a call only when its - * head resolves to a builtin flagged RAY_FN_ATOMIC and every argument is - * a column of `tbl`, a literal, a quoted symbol, or such a call. A bare - * symbol that is not a column (a free variable, possibly a table-length - * vector), an order-dependent function (deltas, sums, ...), an - * aggregate, a special form, or a lambda call keeps the legacy arm. */ -static bool update_expr_elementwise(ray_t* e, ray_t* tbl) { - if (!e || RAY_IS_ERR(e)) return false; - if (e->type == -RAY_SYM) { - if (e->attrs & ATTR_QUOTED) return true; - return ray_table_get_col(tbl, e->i64) != NULL; - } - if (e->type < 0) return true; - if (e->type != RAY_LIST) return false; - int64_t n = ray_len(e); - if (n < 2) return false; - ray_t** el = (ray_t**)ray_data(e); - ray_t* head = el[0]; - if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; - ray_t* fn = ray_env_get(head->i64); - if (!fn || RAY_IS_ERR(fn)) return false; - if (fn->type != RAY_UNARY && fn->type != RAY_BINARY && fn->type != RAY_VARY) return false; - if (!(fn->attrs & RAY_FN_ATOMIC)) return false; - for (int64_t i = 1; i < n; i++) - if (!update_expr_elementwise(el[i], tbl)) return false; - return true; -} +/* update_expr_elementwise is defined with select's partition pruning above. */ /* Rows matching `(== col atom)` through a fresh hash index on col. * Returns 1 with rows copied into *rows (n in *n_out), 0 when the @@ -18950,22 +24427,30 @@ static int update_where_index_rows(ray_t* tbl, ray_t* where_expr, ray_t** el = (ray_t**)ray_data(where_expr); if (!el[0] || el[0]->type != -RAY_SYM) return 0; if (el[0]->i64 != ray_sym_intern("==", 2)) return 0; - ray_t* col = NULL; ray_t* val_node = NULL; - for (int side = 1; side <= 2 && !col; side++) { + ray_col_meta_t m; + int64_t col_sym = -1; ray_t* val_node = NULL; + for (int side = 1; side <= 2 && col_sym < 0; side++) { ray_t* a = el[side]; - if (a && a->type == -RAY_SYM && ray_table_get_col(tbl, a->i64)) { - col = ray_table_get_col(tbl, a->i64); + if (a && a->type == -RAY_SYM && ray_table_col_meta(tbl, a->i64, &m)) { + col_sym = a->i64; val_node = el[3 - side]; } } - if (!col || !val_node || RAY_IS_ERR(val_node)) return 0; + if (col_sym < 0 || !val_node || RAY_IS_ERR(val_node)) return 0; /* The other side must be a value: a literal, a quoted symbol, or a * variable — never a column name (that is a column-column compare). */ - if (val_node->type == -RAY_SYM && ray_table_get_col(tbl, val_node->i64)) return 0; + ray_col_meta_t vm; + if (val_node->type == -RAY_SYM && ray_table_col_meta(tbl, val_node->i64, &vm)) return 0; if (!ray_is_atom(val_node)) return 0; - if (col->attrs & RAY_ATTR_HAS_NULLS) return 0; - if (ray_index_kind(col) != RAY_IDX_HASH) return 0; - if (col->type == RAY_F64 || col->type == RAY_STR || col->type == RAY_GUID) return 0; + if (m.index_kind != RAY_IDX_HASH) return 0; /* metadata first: no null scan */ + if (ray_table_col_has_nulls(tbl, col_sym)) return 0; + if (m.type == RAY_F64 || m.type == RAY_STR || m.type == RAY_GUID) return 0; + ray_t* ix; + ray_t* ie = ray_table_col_index(tbl, col_sym, &ix); + if (ie) { ray_error_free(ie); return 0; } + if (!ix) return 0; + ray_t* col = ray_table_col(tbl, col_sym); /* cached with its index */ + if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return 0; } ray_t* v = ray_eval(val_node); if (!v) return 0; if (RAY_IS_ERR(v)) { ray_error_free(v); return 0; } @@ -19006,8 +24491,9 @@ static ray_t* update_where_mask_vec(ray_t* tbl, ray_t* where_expr) { } if (!rejected && (!mask_vec || RAY_IS_ERR(mask_vec))) { ray_env_push_query_scope(); - ray_t* prev_table = bind_all_columns(tbl); - mask_vec = eval_query_expr(where_expr, tbl); + ray_t* bind_err = NULL; + ray_t* prev_table = bind_referenced_query(tbl, &where_expr, 1, &bind_err); + mask_vec = bind_err ? bind_err : eval_query_expr(where_expr, tbl); g_active_query_table = prev_table; ray_env_pop_scope(); } @@ -19111,11 +24597,12 @@ static int expr_refs_any_column(ray_t* expr, ray_t* tbl) { if (!expr) return 0; if (expr->type == -RAY_SYM && !(expr->attrs & ATTR_QUOTED)) { if (ray_env_has_lexical_local(expr->i64)) return 0; - if (ray_table_get_col(tbl, expr->i64)) return 1; + ray_col_meta_t m; + if (ray_table_col_meta(tbl, expr->i64, &m)) return 1; if (ray_sym_is_dotted(expr->i64)) { const int64_t* segs; int nsegs = ray_sym_segs(expr->i64, &segs); - if (nsegs >= 1 && ray_table_get_col(tbl, segs[0])) return 1; + if (nsegs >= 1 && ray_table_col_meta(tbl, segs[0], &m)) return 1; } return 0; } @@ -19209,10 +24696,15 @@ static ray_t* update_eval_on_impl(ray_t* sub, ray_t* expr, bool expand, bool* da } if (!per_row) { ray_env_push_query_scope(); - ray_t* prev_table = bind_all_columns(sub); - out = expand ? eval_query_expr(expr, sub) : ray_eval(expr); + ray_t* bind_err = NULL; + ray_t* prev_table = bind_referenced_query(sub, &expr, 1, &bind_err); + out = bind_err ? NULL : expand ? eval_query_expr(expr, sub) : ray_eval(expr); g_active_query_table = prev_table; ray_env_pop_scope(); + if (bind_err) { + if (cerr) ray_error_free(cerr); + return bind_err; + } } else { out = expand ? eval_expr_per_row(expr, sub, nrows) : eval_expr_per_row_impl(expr, sub, nrows); @@ -19365,7 +24857,7 @@ static ray_t* update_where_inplace(ray_t* tbl, int64_t inplace_sym, ray_t* dict, int64_t ncols = ray_table_ncols(tbl); if (inplace_sym < 0 || ncols <= 0) return NULL; if (tbl->rc != 2 || tbl->mmod != 0 || (tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA))) return NULL; - ray_t* live_cols = ((ray_t**)ray_data(tbl))[1]; + ray_t* live_cols = ray_table_cols_inplace(tbl); /* NULL: an encoded slot */ if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) return NULL; ray_t** slots = (ray_t**)ray_data(live_cols); for (int64_t c = 0; c < ncols; c++) @@ -19398,7 +24890,7 @@ static ray_t* update_where_inplace(ray_t* tbl, int64_t inplace_sym, ray_t* dict, if (kid == from_id || kid == where_id || kid == by_id) continue; if (kid != cn) continue; ucol[nu] = c; uexpr[nu] = updf[d + 1]; uval[nu] = NULL; nu++; - if (!update_expr_elementwise(updf[d + 1], tbl)) rowwise = false; + if (!update_expr_elementwise(updf[d + 1], tbl, false)) rowwise = false; break; } } @@ -19536,21 +25028,9 @@ ray_t* ray_update(ray_t** args, int64_t n) { * materialising parted columns on demand; replicate it here by flattening * the whole table once so every branch below sees wrapped-free vectors. */ if (table_has_parted_columns(tbl)) { - ray_t* flat_tbl = ray_table_new(ray_table_ncols(tbl)); - if (!flat_tbl || RAY_IS_ERR(flat_tbl)) { ray_release(tbl); return flat_tbl ? flat_tbl : ray_error("oom", NULL); } - int64_t nc = ray_table_ncols(tbl); - for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - ray_t* flat_col = query_materialize_parted_col(col); - if (!flat_col || RAY_IS_ERR(flat_col)) { - ray_release(flat_tbl); ray_release(tbl); - return flat_col ? flat_col : ray_error("oom", NULL); - } - flat_tbl = ray_table_add_col(flat_tbl, ray_table_col_name(tbl, c), flat_col); - ray_release(flat_col); - if (!flat_tbl || RAY_IS_ERR(flat_tbl)) { ray_release(tbl); return flat_tbl ? flat_tbl : ray_error("oom", NULL); } - } + ray_t* flat_tbl = query_materialize_parted_table(tbl); ray_release(tbl); + if (!flat_tbl || RAY_IS_ERR(flat_tbl)) return flat_tbl ? flat_tbl : ray_error("oom", NULL); tbl = flat_tbl; } @@ -19592,7 +25072,8 @@ ray_t* ray_update(ray_t** args, int64_t n) { if (by_col_name < 0) { ray_release(tbl); DICT_VIEW_CLOSE(updv); return ray_error("type", "update by: group key must be a column name symbol"); } /* Find group column in table */ - ray_t* grp_col = ray_table_get_col(tbl, by_col_name); + ray_t* grp_col = ray_table_col(tbl, by_col_name); + if (grp_col && RAY_IS_ERR(grp_col)) { ray_release(tbl); DICT_VIEW_CLOSE(updv); return grp_col; } if (!grp_col) { ray_release(tbl); DICT_VIEW_CLOSE(updv); return ray_error("domain", "update by: group key column not found"); } int64_t nrows2 = ray_table_nrows(tbl); @@ -19666,8 +25147,8 @@ ray_t* ray_update(ray_t** args, int64_t n) { /* We need to evaluate the aggregate per group. * Build the result column by evaluating the expression on each group's subset. */ int8_t out_type = RAY_I64; - ray_t* target_col = ray_table_get_col(tbl, kid); - if (ngroups == 0 && target_col) out_type = target_col->type; + ray_col_meta_t tm; + if (ngroups == 0 && ray_table_col_meta(tbl, kid, &tm)) out_type = tm.type; ray_t* out_col = ray_vec_new(out_type, nrows2); /* resized to expression type on first group */ if (RAY_IS_ERR(out_col)) { UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return out_col; } if (ngroups == 0) { @@ -19689,7 +25170,11 @@ ray_t* ray_update(ray_t** args, int64_t n) { if (RAY_IS_ERR(sub_tbl)) { ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return sub_tbl; } for (int64_t c = 0; c < ncols; c++) { int64_t cn = ray_table_col_name(tbl, c); - ray_t* full_col = ray_table_get_col_idx(tbl, c); + ray_t* full_col = ray_table_col_idx(tbl, c); + if (!full_col || RAY_IS_ERR(full_col)) { + ray_release(sub_tbl); ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); + return full_col ? full_col : ray_error("oom", NULL); + } int8_t ct = full_col->type; /* Create sub_col with the SOURCE column's width. For a SYM * column that dictionary-index width is adaptive @@ -19843,7 +25328,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { upd_cols[ui] = NULL; upd_used[ui] = 1; } else { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); ray_retain(col); result = ray_table_add_col(result, cn, col); ray_release(col); @@ -19903,8 +25388,9 @@ ray_t* ray_update(ray_t** args, int64_t n) { if (!rejected && (!mask_vec || RAY_IS_ERR(mask_vec))) { /* Bind column names to column vectors in env, then eval */ ray_env_push_query_scope(); - ray_t* prev_table = bind_all_columns(tbl); - mask_vec = eval_query_expr(where_expr, tbl); + ray_t* bind_err = NULL; + ray_t* prev_table = bind_referenced_query(tbl, &where_expr, 1, &bind_err); + mask_vec = bind_err ? bind_err : eval_query_expr(where_expr, tbl); g_active_query_table = prev_table; ray_env_pop_scope(); } @@ -19938,7 +25424,6 @@ ray_t* ray_update(ray_t** args, int64_t n) { for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(tbl, c); - ray_t* orig_col = ray_table_get_col_idx(tbl, c); /* Check if this column has an update expression */ ray_t* update_expr = NULL; @@ -19948,6 +25433,15 @@ ray_t* ray_update(ray_t** args, int64_t n) { if (kid == col_name) { update_expr = dict_elems[d + 1]; break; } } + /* A column copied as-is keeps its encoded object; an updated one + * is read for the merge. */ + ray_t* orig_col = update_expr ? NULL : ray_table_get_col_enc_idx(tbl, c); + if (!orig_col) orig_col = ray_table_col_idx(tbl, c); + if (orig_col && RAY_IS_ERR(orig_col)) { + ray_release(result); ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); + return orig_col; + } + if (!update_expr) { /* No update for this column — copy as-is */ ray_retain(orig_col); @@ -20008,7 +25502,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { ray_vec_set_null(new_col, r, true); switch (ct) { case RAY_F64: ((double*)ray_data(new_col))[r] = NULL_F64; break; - case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)ray_data(new_col))[r] = NULL_I64; break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)ray_data(new_col))[r] = NULL_I64; break; case RAY_I32: case RAY_DATE: case RAY_TIME:((int32_t*)ray_data(new_col))[r] = NULL_I32; break; case RAY_I16: ((int16_t*)ray_data(new_col))[r] = NULL_I16; break; default: break; @@ -20089,7 +25583,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { for (int64_t r = 0; r < nrows; r++) d[r] = NULL_F64; break; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(bcast); for (int64_t r = 0; r < nrows; r++) d[r] = NULL_I64; break; @@ -20275,8 +25769,6 @@ ray_t* ray_update(ray_t** args, int64_t n) { for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(tbl, c); - ray_t* orig_col = ray_table_get_col_idx(tbl, c); - ray_t* update_expr = NULL; for (int64_t d = 0; d + 1 < dict_n; d += 2) { int64_t kid = dict_elems[d]->i64; @@ -20285,10 +25777,16 @@ ray_t* ray_update(ray_t** args, int64_t n) { } if (!update_expr) { + /* Copied as-is: the slot object, encoded or plain. */ + ray_t* orig_col = ray_table_slot_idx(tbl, c); ray_retain(orig_col); result = ray_table_add_col(result, col_name, orig_col); ray_release(orig_col); } else { + /* The replaced column is only typed: its values are not read. */ + ray_col_meta_t om; + ray_table_col_meta_idx(tbl, c, &om); + int8_t oct = om.type; /* DAG first, then the interpreter (update_eval_on). */ ray_t* expr_vec = update_eval_on(tbl, update_expr); if (!expr_vec || RAY_IS_ERR(expr_vec)) { ray_release(result); ray_release(tbl); DICT_VIEW_CLOSE(upda); return expr_vec ? expr_vec : ray_error("type", "update: failed to evaluate column update expression"); } @@ -20303,7 +25801,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { /* Broadcast scalar atom to full column vector if needed */ if (expr_vec->type < 0) { int64_t nrows = ray_table_nrows(tbl); - int8_t ct = orig_col->type; + int8_t ct = oct; /* Type check atom against column type BEFORE broadcast */ int ok = (expr_vec->type == -ct); if (!ok && ct == RAY_F64 && expr_vec->type == -RAY_I64) ok = 1; @@ -20360,7 +25858,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { for (int64_t r = 0; r < nrows; r++) d[r] = NULL_F64; break; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(bcast); for (int64_t r = 0; r < nrows; r++) d[r] = NULL_I64; break; @@ -20383,7 +25881,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { } /* Promote I64 vector to F64 if column is F64 */ - if (expr_vec->type == RAY_I64 && orig_col->type == RAY_F64) { + if (expr_vec->type == RAY_I64 && oct == RAY_F64) { int64_t nr = ray_len(expr_vec); ray_t* promoted = ray_vec_new(RAY_F64, nr); if (RAY_IS_ERR(promoted)) { ray_release(expr_vec); ray_release(result); ray_release(tbl); DICT_VIEW_CLOSE(upda); return promoted; } @@ -20410,18 +25908,18 @@ ray_t* ray_update(ray_t** args, int64_t n) { * Atoms (type<0) will be broadcast later, check after broadcast. * For vectors, check now: only numeric promotions or same type. * Also allow SYM/LIST interop (columns may be stored as LIST). */ - if (expr_vec->type > 0 && expr_vec->type != orig_col->type) { + if (expr_vec->type > 0 && expr_vec->type != oct) { int is_ok = 0; /* Numeric promotions */ - if ((orig_col->type == RAY_I64 || orig_col->type == RAY_I32 || orig_col->type == RAY_F64) && + if ((oct == RAY_I64 || oct == RAY_I32 || oct == RAY_F64) && (expr_vec->type == RAY_I64 || expr_vec->type == RAY_I32 || expr_vec->type == RAY_F64)) is_ok = 1; /* SYM/LIST interop */ - if ((orig_col->type == RAY_SYM || orig_col->type == RAY_LIST) && + if ((oct == RAY_SYM || oct == RAY_LIST) && (expr_vec->type == RAY_SYM || expr_vec->type == RAY_LIST)) is_ok = 1; if (!is_ok) { - int8_t ev_t = expr_vec->type, oc_t = orig_col->type; /* capture BEFORE free */ + int8_t ev_t = expr_vec->type, oc_t = oct; /* capture BEFORE free */ ray_release(expr_vec); ray_release(result); ray_release(tbl); DICT_VIEW_CLOSE(upda); return ray_error("type", "update: expression type %s does not match %s column", ray_type_name(ev_t), ray_type_name(oc_t)); } @@ -20500,7 +25998,7 @@ ray_t* ray_update(ray_t** args, int64_t n) { for (int64_t r = 0; r < nrows; r++) d[r] = NULL_F64; break; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t* d = (int64_t*)ray_data(bcast); for (int64_t r = 0; r < nrows; r++) d[r] = NULL_I64; break; @@ -20547,21 +26045,33 @@ static bool table_has_parted_columns(ray_t* tbl) { if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return false; int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (col->type == RAY_MAPCOMMON || RAY_IS_PARTED(col->type))) + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && + (m.type == RAY_MAPCOMMON || RAY_IS_PARTED(m.type))) return true; } return false; } /* A fresh table with every parted / mapcommon column of `tbl` flattened - * (query_materialize_parted_col); plain columns are shared. Owned. */ + * (query_materialize_parted_col); plain columns are shared, an encoded + * non-parted slot as its encoded object. Owned. */ static ray_t* query_materialize_parted_table(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); ray_t* flat_tbl = ray_table_new(nc); if (!flat_tbl || RAY_IS_ERR(flat_tbl)) return flat_tbl ? flat_tbl : ray_error("oom", NULL); for (int64_t c = 0; c < nc; c++) { - ray_t* flat_col = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); + ray_col_meta_t m; + ray_t* enc = ray_table_get_col_enc_idx(tbl, c); + ray_t* flat_col; + if (enc && ray_table_col_meta_idx(tbl, c, &m) && !RAY_IS_PARTED(m.type)) { + ray_retain(enc); + flat_col = enc; + } else { + ray_t* src = ray_table_col_idx(tbl, c); + if (src && RAY_IS_ERR(src)) { ray_release(flat_tbl); return src; } + flat_col = query_materialize_parted_col(src, tbl); + } if (!flat_col || RAY_IS_ERR(flat_col)) { ray_release(flat_tbl); return flat_col ? flat_col : ray_error("oom", NULL); @@ -20683,19 +26193,24 @@ static ray_t* validate_parted_insert_target(ray_t* tbl, memset(out, 0, sizeof(*out)); if (tbl->len != 2 || tbl->attrs != 0) return ray_error("corrupt", "insert: parted target has non-canonical table metadata"); - ray_t** table_slots = (ray_t**)ray_data(tbl); - ray_t* schema = table_slots[0]; - ray_t* columns = table_slots[1]; + ray_t* schema = ray_table_schema(tbl); if (!schema || RAY_IS_ERR(schema) || schema->type != RAY_I64 || - schema->attrs != 0 || schema->len < 0 || - !columns || RAY_IS_ERR(columns) || columns->type != RAY_LIST || - columns->attrs != 0 || columns->len != schema->len) + schema->attrs != 0 || schema->len < 0 || !ray_table_cols_canonical(tbl)) return ray_error("corrupt", "insert: parted target has a malformed table container"); int64_t ncols = ray_table_ncols(tbl); + /* Canonical layout: every schema position holds a column slot. */ + for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t sm; + if (!ray_table_col_meta_idx(tbl, c, &sm)) + return ray_error("corrupt", "insert: parted target has a malformed table container"); + } if (ncols < 2) return ray_error("type", "insert: parted target must have a MAPCOMMON column and at least one physical column"); - ray_t* mc = ray_table_get_col_idx(tbl, 0); + /* A MAPCOMMON slot is never encoded: it is read without a decode. */ + ray_col_meta_t mm; + ray_t* mc = (ray_table_col_meta_idx(tbl, 0, &mm) && mm.type == RAY_MAPCOMMON && !mm.enc) + ? ray_table_col_idx(tbl, 0) : NULL; if (!mc || mc->type != RAY_MAPCOMMON || mc->len != 2 || mc->attrs > RAY_MC_I64) return ray_error("type", "insert: three-argument table form requires a canonical .db.parted.get table"); @@ -20756,7 +26271,13 @@ static ray_t* validate_parted_insert_target(ray_t* tbl, ray_t* common_rep = NULL; bool active_missing = false; for (int64_t c = 1; c < ncols; c++) { - ray_t* wrapper = ray_table_get_col_idx(tbl, c); + /* Shape from metadata first; the wrapper is read for its segments + * (an encoded parted slot materializes to a plain wrapper). */ + ray_col_meta_t wm; + if (!ray_table_col_meta_idx(tbl, c, &wm) || !RAY_IS_PARTED(wm.type) || wm.n_segs != nparts) + return ray_error("corrupt", "insert: physical column %lld is not a canonical PARTED wrapper", (long long)(c - 1)); + ray_t* wrapper = ray_table_col_idx(tbl, c); + if (wrapper && RAY_IS_ERR(wrapper)) return wrapper; if (!wrapper || !RAY_IS_PARTED(wrapper->type) || wrapper->len != nparts || wrapper->attrs != 0) return ray_error("corrupt", "insert: physical column %lld is not a canonical PARTED wrapper", (long long)(c - 1)); @@ -20878,8 +26399,9 @@ static ray_t* normalize_parted_insert_rows(ray_t* tbl, } ray_t** items = (ray_t**)ray_data(rows); for (int64_t c = 0; c < v->ndata; c++) { - ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); - if (RAY_PARTED_BASETYPE(wrapper->type) == RAY_LIST) { + ray_col_meta_t wm; + ray_table_col_meta_idx(tbl, c + 1, &wm); /* validated wrapper */ + if (RAY_PARTED_BASETYPE(wm.type) == RAY_LIST) { ray_t* one = ray_list_new(1); if (!one || RAY_IS_ERR(one)) { ray_release(vals); @@ -20919,7 +26441,8 @@ static ray_t* normalize_parted_insert_rows(ray_t* tbl, } } for (int64_t c = 1; c < v->ncols; c++) { - ray_t* col = ray_table_get_col(rows, ray_table_col_name(tbl, c)); + /* an error (a failed decode) is taken by parted_values_append */ + ray_t* col = ray_table_col(rows, ray_table_col_name(tbl, c)); vals = parted_values_append(vals, col, false); if (!vals || RAY_IS_ERR(vals)) return vals; } @@ -20957,8 +26480,9 @@ static ray_t* normalize_parted_insert_rows(ray_t* tbl, } if (dvals->type == RAY_LIST) { ray_t* item = ((ray_t**)ray_data(dvals))[found]; - ray_t* wrapper = ray_table_get_col_idx(tbl, c); - if (RAY_PARTED_BASETYPE(wrapper->type) == RAY_LIST && + ray_col_meta_t wm; + ray_table_col_meta_idx(tbl, c, &wm); /* validated wrapper */ + if (RAY_PARTED_BASETYPE(wm.type) == RAY_LIST && item && item->type == RAY_LIST) { ray_t* one = ray_list_new(1); if (!one || RAY_IS_ERR(one)) { @@ -21055,8 +26579,9 @@ static ray_t* validate_parted_payloads(ray_t* tbl, } for (int64_t c = 0; c < v->ndata; c++) { - ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); - int8_t dst = (int8_t)RAY_PARTED_BASETYPE(wrapper->type); + ray_col_meta_t wm; + ray_table_col_meta_idx(tbl, c + 1, &wm); /* validated wrapper */ + int8_t dst = (int8_t)RAY_PARTED_BASETYPE(wm.type); ray_t* payload = pv[c]; if (dst == RAY_LIST) { if (!parted_value_is_scalar(payload) && payload->type != RAY_LIST) @@ -21132,7 +26657,7 @@ static ray_t* append_parted_atom(ray_t* vec, int8_t dst, ray_t* atom) { case RAY_F64: { double x = atom->f64; return ray_vec_append(vec, &x); } case RAY_DATE: { int32_t x = atom->i32; return ray_vec_append(vec, &x); } case RAY_TIME: { int32_t x = atom->i32; return ray_vec_append(vec, &x); } - case RAY_TIMESTAMP: { int64_t x = atom->i64; return ray_vec_append(vec, &x); } + case RAY_TIMESPAN: case RAY_TIMESTAMP: { int64_t x = atom->i64; return ray_vec_append(vec, &x); } case RAY_GUID: return ray_vec_append(vec, ray_data(atom->obj)); case RAY_STR: return ray_str_vec_append(vec, ray_str_ptr(atom), ray_str_len(atom)); default: return ray_error("type", "insert: unsupported parted append type %s", ray_type_name(dst)); @@ -21404,7 +26929,7 @@ static ray_t* build_parted_mapcommon(parted_insert_view_t* v, mc->attrs = v->mapcommon->attrs; memset(mc->aux, 0, 16); ((ray_t**)ray_data(mc))[0] = keys; /* transfer ownership */ - ((ray_t**)ray_data(mc))[1] = counts; + ((ray_t**)ray_data(mc))[1] = counts; /* not-a-table */ return mc; } @@ -21448,8 +26973,9 @@ static ray_t* intern_parted_payload_symbols(ray_t* tbl, int64_t batch) { ray_t** pv = (ray_t**)ray_data(vals); for (int64_t c = 0; c < v->ndata; c++) { - ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); - if (RAY_PARTED_BASETYPE(wrapper->type) != RAY_SYM) continue; + ray_col_meta_t wm; + ray_table_col_meta_idx(tbl, c + 1, &wm); /* validated wrapper */ + if (RAY_PARTED_BASETYPE(wm.type) != RAY_SYM) continue; ray_t* payload = pv[c]; int64_t n = parted_value_is_scalar(payload) ? (batch ? 1 : 0) : batch; for (int64_t r = 0; r < n; r++) { @@ -21472,8 +26998,9 @@ static ray_t* fill_parted_payload_symbols(ray_t* tbl, ray_t** pv = (ray_t**)ray_data(vals); ray_t** sv = (ray_t**)ray_data(staged); for (int64_t c = 0; c < v->ndata; c++) { - ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); - if (RAY_PARTED_BASETYPE(wrapper->type) != RAY_SYM) continue; + ray_col_meta_t wm; + ray_table_col_meta_idx(tbl, c + 1, &wm); /* validated wrapper */ + if (RAY_PARTED_BASETYPE(wm.type) != RAY_SYM) continue; ray_t* payload = pv[c]; ray_t* seg = sv[c]; for (int64_t r = 0; r < batch; r++) { @@ -21545,7 +27072,14 @@ static ray_t* insert_parted_rows(ray_t* tbl, ray_t* key, ray_t* rows) { } ray_t** pv = (ray_t**)ray_data(vals); for (int64_t c = 0; c < v.ndata; c++) { - ray_t* wrapper = ray_table_get_col_idx(tbl, c + 1); + /* Read only: the active segment is rebuilt into a fresh one and the + * wrapper is replaced, so a materialized (shared) wrapper is never + * written. */ + ray_t* wrapper = ray_table_col_idx(tbl, c + 1); + if (!wrapper || RAY_IS_ERR(wrapper)) { + ray_release(staged); ray_release(vals); + return wrapper ? wrapper : ray_error("corrupt", "insert: physical column %lld is missing", (long long)c); + } ray_t** segs = (ray_t**)ray_data(wrapper); int8_t base = (int8_t)RAY_PARTED_BASETYPE(wrapper->type); ray_t* old_seg = new_partition ? NULL : segs[v.nparts - 1]; @@ -21593,7 +27127,11 @@ static ray_t* insert_parted_rows(ray_t* tbl, ray_t* key, ray_t* rows) { } ray_t** staged_segs = (ray_t**)ray_data(staged); for (int64_t c = 0; c < v.ndata; c++) { - ray_t* old_wrapper = ray_table_get_col_idx(tbl, c + 1); + ray_t* old_wrapper = ray_table_col_idx(tbl, c + 1); /* read above: cached */ + if (!old_wrapper || RAY_IS_ERR(old_wrapper)) { + ray_release(result); ray_release(staged); ray_release(vals); + return old_wrapper ? old_wrapper : ray_error("corrupt", "insert: physical column %lld is missing", (long long)c); + } ray_t** old_segs = (ray_t**)ray_data(old_wrapper); ray_t* wrapper = ray_alloc((size_t)new_nparts * sizeof(ray_t*)); if (!wrapper || RAY_IS_ERR(wrapper)) { @@ -21945,9 +27483,17 @@ ray_t* ray_insert(ray_t** args, int64_t n) { ray_t** trl = (ray_t**)ray_data(tbl_row_list); for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(tbl, c); - ray_t* src_col = ray_table_get_col(row, col_name); - if (!src_col) src_col = ray_table_get_col_idx(row, c); + ray_t* src_col = ray_table_col(row, col_name); + if (!src_col) src_col = ray_table_col_idx(row, c); + if (src_col && RAY_IS_ERR(src_col)) { + for (int64_t k = 0; k < c; k++) ray_release(trl[k]); + tbl_row_list->len = 0; + ray_free(tbl_row_list); + ray_release(tbl); ray_release(row_orig); + return src_col; + } if (!src_col) { + for (int64_t k = 0; k < c; k++) ray_release(trl[k]); tbl_row_list->len = 0; ray_free(tbl_row_list); ray_release(tbl); ray_release(row_orig); @@ -22045,7 +27591,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { !(tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); ray_t* live_cols = NULL; if (inplace_ok) { - live_cols = ((ray_t**)ray_data(tbl))[1]; + live_cols = ray_table_cols_inplace(tbl); /* NULL: an encoded slot */ if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) inplace_ok = false; } @@ -22214,12 +27760,43 @@ ray_t* ray_insert(ray_t** args, int64_t n) { return err ? err : ray_sym(inplace_sym); } + /* The rebuild copies every column: read them all first, so a column + * that fails to materialize returns before anything is built (the + * loop below then reads the cached columns). */ + /* Every exit below releases the row payload carriers and the operands. */ + #define INSERT_REBUILD_FREE() do { \ + if (dict_vals) { \ + ray_t** dv_ = (ray_t**)ray_data(dict_vals); \ + for (int64_t k_ = 0; k_ < ncols; k_++) if (dv_[k_]) ray_release(dv_[k_]); \ + dict_vals->len = 0; /* prevent ray_free from double-releasing children */ \ + ray_free(dict_vals); \ + } \ + if (tbl_row_list) { \ + ray_t** trl_ = (ray_t**)ray_data(tbl_row_list); \ + for (int64_t k_ = 0; k_ < ncols; k_++) if (trl_[k_]) ray_release(trl_[k_]); \ + tbl_row_list->len = 0; \ + ray_free(tbl_row_list); \ + } \ + ray_release(tbl); \ + ray_release(row_orig); \ + } while (0) + for (int64_t c = 0; c < ncols; c++) { + ray_t* col = ray_table_col_idx(tbl, c); + if (!col || !RAY_IS_ERR(col)) continue; + INSERT_REBUILD_FREE(); + return col; + } + ray_t* result = ray_table_new(ncols); - if (RAY_IS_ERR(result)) return result; + if (RAY_IS_ERR(result)) { INSERT_REBUILD_FREE(); return result; } for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(tbl, c); - ray_t* orig_col = ray_table_get_col_idx(tbl, c); + ray_t* orig_col = ray_table_col_idx(tbl, c); /* read above: cached */ + if (!orig_col || RAY_IS_ERR(orig_col)) { + ray_release(result); INSERT_REBUILD_FREE(); + return orig_col ? orig_col : ray_error("domain", "insert: target column %lld is missing", (long long)c); + } int8_t ct = orig_col->type; /* Typeless empty column (an empty () list, adopt-on-first-insert). @@ -22232,17 +27809,17 @@ ray_t* ray_insert(ray_t** args, int64_t n) { ray_t* new_col = append_boxed_table_col( orig_col, row_elems[c], tbl_row_list != NULL); if (!new_col || RAY_IS_ERR(new_col)) { - ray_release(result); + ray_release(result); INSERT_REBUILD_FREE(); return new_col ? new_col : ray_error("oom", NULL); } result = ray_table_add_col(result, col_name, new_col); ray_release(new_col); - if (!result || RAY_IS_ERR(result)) return result; + if (!result || RAY_IS_ERR(result)) { INSERT_REBUILD_FREE(); return result; } continue; } ray_t* new_col = ray_vec_new(ct, nrows + 1); - if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } + if (RAY_IS_ERR(new_col)) { ray_release(result); INSERT_REBUILD_FREE(); return new_col; } /* Copy existing data */ bool src_has_nulls = ray_vec_may_have_nulls(orig_col); @@ -22257,7 +27834,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { const char* sp = ray_str_vec_get(orig_col, r, &slen); new_col = ray_str_vec_append(new_col, sp ? sp : "", sp ? slen : 0); } - if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } + if (RAY_IS_ERR(new_col)) { ray_release(result); INSERT_REBUILD_FREE(); return new_col; } } } else if (ct == RAY_SYM) { /* The output MIXES orig_col cells with the appended row value @@ -22266,7 +27843,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { for (int64_t r = 0; r < nrows; r++) { int64_t sym_val = sym_cell_runtime_id(orig_col, r); new_col = ray_vec_append(new_col, &sym_val); - if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } + if (RAY_IS_ERR(new_col)) { ray_release(result); INSERT_REBUILD_FREE(); return new_col; } if (src_has_nulls && ray_vec_is_null(orig_col, r)) ray_vec_set_null(new_col, new_col->len - 1, true); } @@ -22275,7 +27852,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { uint8_t* src = (uint8_t*)ray_data(orig_col); for (int64_t r = 0; r < nrows; r++) { new_col = ray_vec_append(new_col, src + r * elem_sz); - if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } + if (RAY_IS_ERR(new_col)) { ray_release(result); INSERT_REBUILD_FREE(); return new_col; } if (src_has_nulls && ray_vec_is_null(orig_col, r)) ray_vec_set_null(new_col, new_col->len - 1, true); } @@ -22316,28 +27893,16 @@ ray_t* ray_insert(ray_t** args, int64_t n) { } else { new_col = append_atom_to_col(new_col, row_elems[c]); } - if (RAY_IS_ERR(new_col)) { ray_release(result); return new_col; } + if (RAY_IS_ERR(new_col)) { ray_release(result); INSERT_REBUILD_FREE(); return new_col; } result = ray_table_add_col(result, col_name, new_col); ray_release(new_col); - if (RAY_IS_ERR(result)) return result; + if (RAY_IS_ERR(result)) { INSERT_REBUILD_FREE(); return result; } } /* Cleanup dict_vals, tbl_row_list, and original row */ - if (dict_vals) { - ray_t** dv = (ray_t**)ray_data(dict_vals); - for (int64_t c = 0; c < ncols; c++) if (dv[c]) ray_release(dv[c]); - dict_vals->len = 0; /* prevent ray_free from double-releasing children */ - ray_free(dict_vals); - } - if (tbl_row_list) { - ray_t** trl = (ray_t**)ray_data(tbl_row_list); - for (int64_t c = 0; c < ncols; c++) if (trl[c]) ray_release(trl[c]); - tbl_row_list->len = 0; - ray_free(tbl_row_list); - } - ray_release(tbl); - ray_release(row_orig); + INSERT_REBUILD_FREE(); + #undef INSERT_REBUILD_FREE /* In-place: store the new table in the env and return the symbol. */ if (inplace_sym >= 0 && result && !RAY_IS_ERR(result)) { @@ -22376,7 +27941,7 @@ ray_t* ray_insert(ray_t** args, int64_t n) { static bool upsert_key_type_ok(int8_t t) { switch (t) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: - case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: case RAY_SYM: case RAY_STR: case RAY_GUID: return true; default: @@ -22556,8 +28121,8 @@ static void ukey_extend_after_append(ray_t* tbl, int64_t nrows0) { ray_table_ukey_drop(tbl); return; } - ray_t* cols = ((ray_t**)ray_data(tbl))[1]; - if (!cols || RAY_IS_ERR(cols)) { ray_table_ukey_drop(tbl); return; } + ray_t* cols = ray_table_cols_inplace(tbl); + if (!cols) { ray_table_ukey_drop(tbl); return; } ray_t** slots = (ray_t**)ray_data(cols); int64_t kci[RAY_UKEY_MAX_COLS]; int64_t nk = ix->u.ukey.nk; @@ -22692,6 +28257,7 @@ static ray_t* upsert_cell_fits(int8_t ct, ray_t* cell) { case RAY_DATE: ok = (at == -RAY_DATE); break; case RAY_TIME: ok = (at == -RAY_TIME); break; case RAY_TIMESTAMP: ok = (at == -RAY_TIMESTAMP); break; + case RAY_TIMESPAN: ok = (at == -RAY_TIMESPAN); break; case RAY_GUID: ok = (at == -RAY_GUID); break; case RAY_SYM: ok = (at == -RAY_SYM); break; case RAY_STR: ok = (at == -RAY_STR); break; @@ -22784,13 +28350,14 @@ static void upsert_rollback_appends(ray_t** slots, int64_t ncols, int64_t nrows0 static bool upsert_vec_payload_ok(ray_t* tbl, ray_t** src_cols, int64_t ncols, int64_t m) { for (int64_t c = 0; c < ncols; c++) { ray_t* sc = src_cols[c]; - ray_t* tc = ray_table_get_col_idx(tbl, c); - if (!sc || RAY_IS_ERR(sc) || sc->type != tc->type) return false; + ray_col_meta_t tm; + if (!ray_table_col_meta_idx(tbl, c, &tm)) return false; + if (!sc || RAY_IS_ERR(sc) || sc->type != tm.type) return false; if (sc->attrs & RAY_ATTR_SLICE) return false; if (sc->len != m) return false; - switch (tc->type) { + switch (tm.type) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: - case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_F64: case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_GUID: break; case RAY_SYM: @@ -22877,7 +28444,7 @@ upsert_vec_move_impl(ray_t* dst, const int64_t* di, int64_t dbase, case RAY_BOOL: case RAY_U8: UPSERT_MOVE(uint8_t); break; case RAY_I16: UPSERT_MOVE(int16_t); break; case RAY_I32: case RAY_DATE: case RAY_TIME: UPSERT_MOVE(int32_t); break; - case RAY_I64: case RAY_TIMESTAMP: UPSERT_MOVE(int64_t); break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: UPSERT_MOVE(int64_t); break; case RAY_F64: UPSERT_MOVE(double); break; case RAY_GUID: for (int64_t i = 0; i < n; i++) { @@ -23106,11 +28673,17 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, int64_t nrows0 = ray_table_nrows(tbl); if (ncols <= 0 || m <= 0) return NULL; - for (int64_t c = 0; c < ncols; c++) - if (!upsert_col_ok(ray_table_get_col_idx(tbl, c))) return NULL; + /* An encoded slot is judged by the column it materializes to, which the + * copy below copies; a failed decode declines to the legacy arms, which + * read the column again and report it. */ + for (int64_t c = 0; c < ncols; c++) { + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); return NULL; } + if (!upsert_col_ok(col)) return NULL; + } for (int64_t k = 0; k < nk; k++) { - ray_t* kc = ray_table_get_col_idx(tbl, kci[k]); - if (!upsert_key_type_ok(kc->type)) return NULL; + ray_col_meta_t km; + if (!ray_table_col_meta_idx(tbl, kci[k], &km) || !upsert_key_type_ok(km.type)) return NULL; } /* Sole-owner check, as in insert's in-place path: the binding holds @@ -23120,7 +28693,7 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, !(tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); ray_t* live_cols = NULL; if (inplace) { - live_cols = ((ray_t**)ray_data(tbl))[1]; + live_cols = ray_table_cols_inplace(tbl); /* NULL: an encoded slot */ if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) inplace = false; } @@ -23175,18 +28748,22 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, for (int64_t r = 0; r < m && !err && !vec_path; r++) { ray_t** rc = cells + (size_t)r * ncols; for (int64_t k = 0; k < nk && !err; k++) { - ray_t* kc = ray_table_get_col_idx(tbl, kci[k]); + ray_col_meta_t km; + ray_table_col_meta_idx(tbl, kci[k], &km); ray_t* a = rc[kci[k]]; if (!a) { err = ray_error("domain", "upsert: key value missing"); - } else if (kc->type == RAY_STR && a->type != -RAY_STR) { + } else if (km.type == RAY_STR && a->type != -RAY_STR) { err = ray_error("type", "upsert: key column is str but key value is %s", ray_type_name(a->type)); - } else if (kc->type == RAY_SYM && a->type != -RAY_SYM) { + } else if (km.type == RAY_SYM && a->type != -RAY_SYM) { err = ray_error("type", "upsert: key column is sym but key value is %s", ray_type_name(a->type)); } } - for (int64_t c = 0; c < ncols && !err; c++) - if (rc[c]) err = upsert_cell_fits(ray_table_get_col_idx(tbl, c)->type, rc[c]); + for (int64_t c = 0; c < ncols && !err; c++) { + ray_col_meta_t cm; + ray_table_col_meta_idx(tbl, c, &cm); + if (rc[c]) err = upsert_cell_fits(cm.type, rc[c]); + } } /* Work table: the live columns, or a private copy of them. */ @@ -23198,7 +28775,10 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, work = ray_table_new(ncols); if (RAY_IS_ERR(work)) { err = work; work = NULL; } for (int64_t c = 0; c < ncols && !err; c++) { - ray_t* orig = ray_table_get_col_idx(tbl, c); + /* An encoded slot's cached materialization reaches ray_cow + * shared (rc 2 with this retain), so it is copied. */ + ray_t* orig = ray_table_col_idx(tbl, c); + if (!orig || RAY_IS_ERR(orig)) { err = orig ? orig : ray_error("oom", NULL); break; } ray_retain(orig); ray_t* cp = ray_cow(orig); if (!cp || RAY_IS_ERR(cp)) { @@ -23210,7 +28790,12 @@ static ray_t* upsert_apply(ray_t* tbl, int64_t inplace_sym, ray_release(cp); if (RAY_IS_ERR(work)) { err = work; work = NULL; } } - if (!err) slots = (ray_t**)ray_data(((ray_t**)ray_data(work))[1]); + if (!err) { + /* a table of private copies: never an encoded slot */ + ray_t* wc = ray_table_cols_inplace(work); + if (wc) slots = (ray_t**)ray_data(wc); + else err = ray_error("oom", NULL); + } } } @@ -23491,7 +29076,13 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { if (!src_cols) { scratch_free(tkci_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("oom", NULL); } for (int64_t c = 0; c < ncols; c++) { int64_t cn = ray_table_col_name(tbl, c); - src_cols[c] = ray_table_get_col(row, cn); + src_cols[c] = ray_table_col(row, cn); + if (src_cols[c] && RAY_IS_ERR(src_cols[c])) { + ray_t* e = src_cols[c]; + scratch_free(srcs_hdr); scratch_free(tkci_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return e; + } } bool fast_handled = false; @@ -23708,7 +29299,12 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { if (!key_sym_want) { scratch_free(kci_hdr); ray_release(tbl); ray_release(key_sym); ray_release(row); return ray_error("oom", NULL); } for (int64_t k = 0; k < n_key_cols; k++) { int64_t kci = key_col_indices[k]; - ray_t* key_col = ray_table_get_col_idx(tbl, kci); + ray_t* key_col = ray_table_col_idx(tbl, kci); + if (!key_col || RAY_IS_ERR(key_col)) { + scratch_free(kw_hdr); scratch_free(kci_hdr); + ray_release(tbl); ray_release(key_sym); ray_release(row); + return key_col ? key_col : ray_error("domain", "upsert: key column not found in target table"); + } ray_t* key_atom = row_elems[kci]; int8_t kt = key_col->type; if (kt == RAY_STR && key_atom->type != -RAY_STR) { @@ -23742,7 +29338,7 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { int match = 1; for (int64_t k = 0; k < n_key_cols && match; k++) { int64_t kci = key_col_indices[k]; - ray_t* key_col = ray_table_get_col_idx(tbl, kci); + ray_t* key_col = ray_table_col_idx(tbl, kci); /* read above: cached */ ray_t* key_atom = row_elems[kci]; int8_t kt = key_col->type; if (kt == RAY_F64) { @@ -23794,7 +29390,11 @@ ray_t* ray_upsert(ray_t** args, int64_t n) { for (int64_t c = 0; c < ncols; c++) { int64_t col_name = ray_table_col_name(tbl, c); - ray_t* orig_col = ray_table_get_col_idx(tbl, c); + ray_t* orig_col = ray_table_col_idx(tbl, c); + if (!orig_col || RAY_IS_ERR(orig_col)) { + ray_release(result); ray_release(tbl); ray_release(key_sym); ray_release(row); + return orig_col ? orig_col : ray_error("domain", "upsert: target column %lld is missing", (long long)c); + } int8_t ct = orig_col->type; ray_t* new_col = ray_vec_new(ct, nrows); @@ -23924,11 +29524,12 @@ static ray_t* join_impl(ray_t** args, int64_t n, uint8_t join_type) { return ray_error("type", "join: key must be a symbol name, got %s", ray_type_name(ke_t)); } int64_t key_name = key_elems[i]->i64; - ray_t* left_key_col = ray_table_get_col(left_tbl, key_name); - ray_t* right_key_col = ray_table_get_col(right_tbl, key_name); - if (!left_key_col || !right_key_col) { + ray_col_meta_t lkm, rkm; /* key types only: the scans read the data */ + bool has_l = ray_table_col_meta(left_tbl, key_name, &lkm); + bool has_r = ray_table_col_meta(right_tbl, key_name, &rkm); + if (!has_l || !has_r) { ray_t* key_name_str = ray_sym_str(key_name); - const char* side = !left_key_col ? "left" : "right"; + const char* side = !has_l ? "left" : "right"; scratch_free(keyops_hdr); ray_graph_free(g); if (_bxk) ray_release(_bxk); if (key_name_str) { @@ -23938,8 +29539,8 @@ static ray_t* join_impl(ray_t** args, int64_t n, uint8_t join_type) { } return ray_error("domain", "join: key column not found in %s table", side); } - int8_t left_key_type = left_key_col->type; - int8_t right_key_type = right_key_col->type; + int8_t left_key_type = lkm.type; + int8_t right_key_type = rkm.type; if (RAY_IS_PARTED(left_key_type)) left_key_type = (int8_t)RAY_PARTED_BASETYPE(left_key_type); if (RAY_IS_PARTED(right_key_type)) right_key_type = (int8_t)RAY_PARTED_BASETYPE(right_key_type); if ((left_key_type == RAY_STR) != (right_key_type == RAY_STR)) { @@ -24022,11 +29623,12 @@ static ray_t* antijoin_impl(ray_t** args, int64_t n) { return ray_error("type", "antijoin: key must be a symbol name, got %s", ray_type_name(ke_t)); } int64_t key_name = key_elems[i]->i64; - ray_t* left_key_col = ray_table_get_col(left_tbl, key_name); - ray_t* right_key_col = ray_table_get_col(right_tbl, key_name); - if (!left_key_col || !right_key_col) { + ray_col_meta_t lkm, rkm; /* key types only: the scans read the data */ + bool has_l = ray_table_col_meta(left_tbl, key_name, &lkm); + bool has_r = ray_table_col_meta(right_tbl, key_name, &rkm); + if (!has_l || !has_r) { ray_t* key_name_str = ray_sym_str(key_name); - const char* side = !left_key_col ? "left" : "right"; + const char* side = !has_l ? "left" : "right"; scratch_free(keyops_hdr); ray_graph_free(g); if (_bxk) ray_release(_bxk); if (key_name_str) @@ -24034,8 +29636,8 @@ static ray_t* antijoin_impl(ray_t** args, int64_t n) { (int)ray_str_len(key_name_str), ray_str_ptr(key_name_str), side); return ray_error("domain", "antijoin: key column not found in %s table", side); } - int8_t left_key_type = left_key_col->type; - int8_t right_key_type = right_key_col->type; + int8_t left_key_type = lkm.type; + int8_t right_key_type = rkm.type; if (RAY_IS_PARTED(left_key_type)) left_key_type = (int8_t)RAY_PARTED_BASETYPE(left_key_type); if (RAY_IS_PARTED(right_key_type)) right_key_type = (int8_t)RAY_PARTED_BASETYPE(right_key_type); if ((left_key_type == RAY_STR) != (right_key_type == RAY_STR)) { @@ -24478,6 +30080,13 @@ static int8_t join_i64_eq_key_type(ray_t* col) { return t; } +/* The same, from a table column's metadata (0 when absent). */ +static int8_t join_i64_eq_key_type_of(ray_t* tbl, int64_t sym) { + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, sym, &m)) return 0; + return RAY_IS_PARTED(m.type) ? (int8_t)RAY_PARTED_BASETYPE(m.type) : m.type; +} + static bool join_i64_eq_key_supported(int8_t t) { switch (t) { case RAY_BOOL: @@ -24487,7 +30096,7 @@ static bool join_i64_eq_key_supported(int8_t t) { case RAY_I64: case RAY_DATE: case RAY_TIME: - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: return true; default: @@ -24535,9 +30144,14 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { int64_t right_nrows = ray_table_nrows(right_tbl); /* Get left time column */ - ray_t* left_time = ray_table_get_col(left_tbl, time_key); - ray_t* right_time = ray_table_get_col(right_tbl, time_key); - if (!left_time || !right_time) return ray_error("domain", "window-join: time key column not found in both tables"); + ray_t* left_time = ray_table_col(left_tbl, time_key); + if (left_time && RAY_IS_ERR(left_time)) { for (int i = 0; i < 4; i++) ray_release(eargs[i]); return left_time; } + ray_t* right_time = ray_table_col(right_tbl, time_key); + if (right_time && RAY_IS_ERR(right_time)) { for (int i = 0; i < 4; i++) ray_release(eargs[i]); return right_time; } + if (!left_time || !right_time) { + for (int i = 0; i < 4; i++) ray_release(eargs[i]); + return ray_error("domain", "window-join: time key column not found in both tables"); + } /* Get equality columns. One calloc'd carve holds every n_eq-sized eq * buffer: five pointer arrays (left_eq/right_eq/eq_data/left_eq_hdr/ @@ -24558,8 +30172,16 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { uint8_t* eq_attrs = (uint8_t*)(eq_type + n_eq); for (int64_t e = 0; e < n_eq; e++) { int64_t eq_key = sym_cell_runtime_id(keys_vec, e); - left_eq[e] = ray_table_get_col(left_tbl, eq_key); - right_eq[e] = ray_table_get_col(right_tbl, eq_key); + left_eq[e] = ray_table_col(left_tbl, eq_key); + right_eq[e] = left_eq[e] && RAY_IS_ERR(left_eq[e]) ? NULL : ray_table_col(right_tbl, eq_key); + ray_t* eq_err = left_eq[e] && RAY_IS_ERR(left_eq[e]) ? left_eq[e] + : right_eq[e] && RAY_IS_ERR(right_eq[e]) ? right_eq[e] : NULL; + if (eq_err) { + left_eq[e] = right_eq[e] = NULL; + scratch_free(eq_hdr); + for (int i = 0; i < 4; i++) ray_release(eargs[i]); + return eq_err; + } if (!left_eq[e] || !right_eq[e]) { scratch_free(eq_hdr); for (int i = 0; i < 4; i++) ray_release(eargs[i]); @@ -24703,7 +30325,13 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { scratch_free(agg_hdr); scratch_free(eq_hdr); return ray_error("domain", "window-join: unsupported aggregation op"); } - ray_t* src = ray_table_get_col(right_tbl, agg_src_ids[a]); + ray_t* src = ray_table_col(right_tbl, agg_src_ids[a]); + if (src && RAY_IS_ERR(src)) { + for (int64_t b = 0; b < a; b++) ray_release(agg_result_vecs[b]); + for (int i = 0; i < 4; i++) ray_release(eargs[i]); + scratch_free(agg_hdr); scratch_free(eq_hdr); + return src; + } if (!src) { for (int64_t b = 0; b < a; b++) ray_release(agg_result_vecs[b]); for (int i = 0; i < 4; i++) ray_release(eargs[i]); @@ -24717,7 +30345,7 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { switch (t) { case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_F64: case RAY_F32: case RAY_BOOL: - case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: break; default: for (int64_t b = 0; b < a; b++) ray_release(agg_result_vecs[b]); @@ -25068,15 +30696,18 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { /* Build result table: left columns + every aggregation column */ int64_t ncols = ray_table_ncols(left_tbl); ray_t* result = ray_table_new(ncols + n_agg); - for (int64_t c = 0; c < ncols; c++) { + if (!result) result = ray_error("oom", NULL); + /* ray_table_add_col consumes `result` on failure: stop adding then. */ + for (int64_t c = 0; c < ncols && !RAY_IS_ERR(result); c++) { int64_t cn = ray_table_col_name(left_tbl, c); - ray_t* cv = ray_table_get_col_idx(left_tbl, c); + ray_t* cv = ray_table_slot_idx(left_tbl, c); ray_retain(cv); result = ray_table_add_col(result, cn, cv); ray_release(cv); } for (int64_t a = 0; a < n_agg; a++) { - result = ray_table_add_col(result, agg_names[a], agg_result_vecs[a]); + if (!RAY_IS_ERR(result)) + result = ray_table_add_col(result, agg_names[a], agg_result_vecs[a]); ray_release(agg_result_vecs[a]); } for (int i = 0; i < 4; i++) ray_release(eargs[i]); @@ -25137,10 +30768,8 @@ static ray_t* window_join_impl(ray_t** args, int64_t n, int mode) { if (!nm) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxeq) ray_release(_bxeq); return ray_error("domain", "window-join: unknown equality key symbol"); } eq_ops[i] = ray_scan(g, ray_str_ptr(nm)); if (!eq_ops[i]) { scratch_free(eqops_hdr); ray_graph_free(g); if (_bxeq) ray_release(_bxeq); return ray_error("domain", "window-join: equality key column not found"); } - ray_t* lcol = ray_table_get_col(left_tbl, eq_elems[i]->i64); - ray_t* rcol = ray_table_get_col(right_tbl, eq_elems[i]->i64); - int8_t lct = join_i64_eq_key_type(lcol); - int8_t rct = join_i64_eq_key_type(rcol); + int8_t lct = join_i64_eq_key_type_of(left_tbl, eq_elems[i]->i64); + int8_t rct = join_i64_eq_key_type_of(right_tbl, eq_elems[i]->i64); if (!join_i64_eq_key_supported(lct) || !join_i64_eq_key_supported(rct)) { scratch_free(eqops_hdr); @@ -25262,10 +30891,8 @@ static ray_t* ray_asof_join_core(ray_t* keys_vec, ray_t* left_tbl, ray_t* right_ /* The asof kernel reads equality keys through read_col_i64 * (asof_eq_lread). Decline types it cannot represent instead of * returning silently corrupted matches. */ - ray_t* lcol = ray_table_get_col(left_tbl, eq_syms[i]->i64); - ray_t* rcol = ray_table_get_col(right_tbl, eq_syms[i]->i64); - int8_t lct = join_i64_eq_key_type(lcol); - int8_t rct = join_i64_eq_key_type(rcol); + int8_t lct = join_i64_eq_key_type_of(left_tbl, eq_syms[i]->i64); + int8_t rct = join_i64_eq_key_type_of(right_tbl, eq_syms[i]->i64); if (!join_i64_eq_key_supported(lct) || !join_i64_eq_key_supported(rct)) { scratch_free(eqops_hdr); @@ -25304,11 +30931,12 @@ static int64_t asof_parted_seg_count(ray_t* tbl) { if (!tbl || tbl->type != RAY_TABLE) return -1; int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (!col) continue; - if (RAY_IS_PARTED(col->type)) return col->len; - if (col->type == RAY_MAPCOMMON) { + ray_col_meta_t m; /* metadata: an encoded column stays encoded */ + if (!ray_table_col_meta_idx(tbl, c, &m)) continue; + if (RAY_IS_PARTED(m.type)) return m.n_segs; + if (m.type == RAY_MAPCOMMON) { /* MAPCOMMON layout: [key_values, ...]; seg count = key_values len */ + ray_t* col = ray_table_col_idx(tbl, c); /* never encoded: no decode */ ray_t** mc = (ray_t**)ray_data(col); return (col->len >= 1 && mc[0]) ? mc[0]->len : -1; } @@ -25360,6 +30988,18 @@ static ray_t* asof_parted_select_operand(ray_t* arg_ast, ray_t** out_dict) { (sl == 4 && memcmp(sp, "desc", 4) == 0) || (sl == 7 && memcmp(sp, "nearest", 7) == 0); if (blocked) { ray_release(tbl); return NULL; } + /* A where: or projection runs on each day's segment only when the + * DAG streams it (clause_streams_per_segment): a value of the + * table's rows (a local, a global vector) or a computation over the + * rows' order or the whole column (sums, an aggregate) misreads one + * day's segment. */ + ray_t* vals = ray_dict_vals(dict); + bool is_from = sl == 4 && memcmp(sp, "from", 4) == 0; + if (!is_from && (!vals || vals->type != RAY_LIST || i >= vals->len || + !clause_streams_per_segment(((ray_t**)ray_data(vals))[i], tbl))) { + ray_release(tbl); + return NULL; + } } *out_dict = dict; return tbl; /* owned */ @@ -25401,7 +31041,7 @@ static ray_t* asof_eval_select_segment(ray_t* dict, ray_t* parted_tbl, int32_t s ray_retain(keys); ray_t* ndict = ray_dict_new(keys, nvals); /* consumes both */ if (!ndict || RAY_IS_ERR(ndict)) return ndict ? ndict : ray_error("oom", NULL); - ray_t* r = ray_select_impl(&ndict, 1, true); + ray_t* r = ray_select_impl(&ndict, 1, SELECT_ALIASES_RESOLVED); ray_release(ndict); return r; } @@ -25494,15 +31134,21 @@ static ray_t* try_stream_parted_order_by( * same invariant as try_stream_parted_order_by_topk's output-shape gate. * An aggregate/expression output collapses per segment (one row per * partition), which would concat into nseg wrong rows instead of the - * flat path's single correctly-aggregated result, so it declines here. */ + * flat path's single correctly-aggregated result, so it declines here. + * An output must read its column (a name a lexical local hides is the + * local, not the column), and the where: runs on a segment only when + * the DAG streams it (clause_streams_per_segment). */ for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; + if (kid == where_id && !clause_streams_per_segment(dict_elems[i + 1], tbl)) return NULL; if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id || kid == nearest_id) continue; ray_t* v = dict_elems[i + 1]; if (!v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED)) return NULL; - if (!ray_table_get_col(tbl, v->i64)) return NULL; + if (!sym_names_col(tbl, v->i64)) return NULL; + ray_col_meta_t vm; + if (!ray_table_col_meta(tbl, v->i64, &vm)) return NULL; } /* Carve: key syms + resolved parted columns + two per-segment key-vec @@ -25534,16 +31180,24 @@ static ray_t* try_stream_parted_order_by( * an undecidable key even when every segment is 0/1 rows (where the * per-segment sortedness check would trivially pass). */ for (int64_t k = 0; k < n_keys; k++) { - ray_t* col = ray_table_get_col(tbl, key_syms[k]); - if (!col || !RAY_IS_PARTED(col->type) || col->len != nseg) { + ray_col_meta_t km; + if (!ray_table_col_meta(tbl, key_syms[k], &km) || + !RAY_IS_PARTED(km.type) || km.n_segs != nseg) { scratch_free(hdr); return NULL; } - int8_t bt = (int8_t)RAY_PARTED_BASETYPE(col->type); + int8_t bt = (int8_t)RAY_PARTED_BASETYPE(km.type); if (bt != RAY_BOOL && bt != RAY_U8 && bt != RAY_I16 && bt != RAY_I32 && bt != RAY_I64 && bt != RAY_DATE && bt != RAY_TIME && bt != RAY_TIMESTAMP && bt != RAY_SYM) { scratch_free(hdr); return NULL; } + /* The segments are read: a failed decode declines, and the flat + * path reads the column again and reports it. */ + ray_t* col = ray_table_col(tbl, key_syms[k]); + if (!col || RAY_IS_ERR(col)) { + if (col) ray_error_free(col); + scratch_free(hdr); return NULL; + } kcols[k] = col; } @@ -25712,15 +31366,22 @@ static ray_t* try_stream_parted_order_by_topk( * negative / range take is a slice, not a top-k — decline it. */ if (k < 0) return NULL; - /* Every output column must be a bare source-column ref (row-preserving). */ + /* Every output column must be a bare source-column ref (row-preserving) + * that reads its column (no lexical local hiding it), and the where: + * runs on a segment only when the DAG streams it + * (clause_streams_per_segment): a value of the table's rows would be + * read whole against each segment. */ for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; + if (kid == where_id && !clause_streams_per_segment(dict_elems[i + 1], tbl)) return NULL; if (kid == from_id || kid == where_id || kid == by_id || kid == take_id || kid == asc_id || kid == desc_id || kid == nearest_id) continue; ray_t* v = dict_elems[i + 1]; if (!v || v->type != -RAY_SYM || (v->attrs & ATTR_QUOTED)) return NULL; - if (!ray_table_get_col(tbl, v->i64)) return NULL; + if (!sym_names_col(tbl, v->i64)) return NULL; + ray_col_meta_t vm; + if (!ray_table_col_meta(tbl, v->i64, &vm)) return NULL; } /* Every sort key must be an output of that column under its name: the @@ -25793,8 +31454,12 @@ static ray_t* asof_parted_date_keys(ray_t* tbl, int64_t* out_n) { if (!tbl || tbl->type != RAY_TABLE) return NULL; int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && col->type == RAY_MAPCOMMON) { + /* A MAPCOMMON slot is never encoded: found from metadata, read + * without a decode (so this never fails). */ + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m) || m.type != RAY_MAPCOMMON || m.enc) continue; + ray_t* col = ray_table_col_idx(tbl, c); + if (col && !RAY_IS_ERR(col) && col->type == RAY_MAPCOMMON) { ray_t** mc = (ray_t**)ray_data(col); if (col->len >= 1 && mc[0] && mc[0]->type == RAY_DATE) { *out_n = mc[0]->len; @@ -25817,13 +31482,17 @@ static ray_t* asof_empty_right(ray_t* dict, ray_t* parted_tbl) { ray_t* out = ray_table_new(nc); if (!out || RAY_IS_ERR(out)) { ray_release(seg0); return out ? out : ray_error("oom", NULL); } for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(seg0, c); + ray_col_meta_t m; + bool has = ray_table_col_meta_idx(seg0, c, &m); int64_t nm = ray_table_col_name(seg0, c); - int8_t ct = col ? col->type : RAY_I64; + int8_t ct = has ? m.type : RAY_I64; ray_t* ev = ray_vec_new(ct, 0); if (!ev || RAY_IS_ERR(ev)) { ray_release(seg0); ray_release(out); return ev ? ev : ray_error("oom", NULL); } ev->len = 0; - if (ct == RAY_SYM && col) ray_sym_vec_adopt_domain(ev, col); + if (ct == RAY_SYM && has) { /* the column's domain, without a decode */ + if (m.enc) ray_enccol_adopt_domain(ev, m.enc); + else ray_sym_vec_adopt_domain(ev, ray_table_col_idx(seg0, c)); + } out = ray_table_add_col(out, nm, ev); ray_release(ev); if (!out || RAY_IS_ERR(out)) { ray_release(seg0); return out ? out : ray_error("oom", NULL); } @@ -25946,7 +31615,7 @@ static ray_t* asof_carry_recompute(ray_t* qtab, ray_t* template, ray_t* dict = ray_dict_new(keys, vals); /* consumes keys + vals */ if (!dict || RAY_IS_ERR(dict)) return dict ? dict : ray_error("oom", NULL); - ray_t* raw = ray_select_impl(&dict, 1, true); + ray_t* raw = ray_select_impl(&dict, 1, SELECT_ALIASES_RESOLVED); ray_release(dict); if (!raw || RAY_IS_ERR(raw)) return raw ? raw : ray_error("type", NULL); @@ -25956,7 +31625,7 @@ static ray_t* asof_carry_recompute(ray_t* qtab, ray_t* template, if (!out || RAY_IS_ERR(out)) { ray_release(raw); return out ? out : ray_error("oom", NULL); } for (int64_t c = 0; c < ncols; c++) { int64_t nm = ray_table_col_name(template, c); - ray_t* col = ray_table_get_col(raw, nm); + ray_t* col = ray_table_slot(raw, nm); if (!col) { ray_release(raw); ray_release(out); return ray_error("schema", "asof carry: column %lld missing from group-last", (long long)nm); } out = ray_table_add_col(out, nm, col); if (!out || RAY_IS_ERR(out)) { ray_release(raw); return out ? out : ray_error("oom", NULL); } @@ -26349,17 +32018,9 @@ ray_t* ray_delete(ray_t** args, int64_t n) { * path declines a parted table anyway (upsert_col_ok rejects the * wrapper), so this only feeds the copying form. */ if (table_has_parted_columns(tbl)) { - ray_t* flat = ray_table_new(ray_table_ncols(tbl)); - if (!flat || RAY_IS_ERR(flat)) { ray_release(tbl); return flat ? flat : ray_error("oom", NULL); } - int64_t nc = ray_table_ncols(tbl); - for (int64_t c = 0; c < nc; c++) { - ray_t* fc = query_materialize_parted_col(ray_table_get_col_idx(tbl, c)); - if (!fc || RAY_IS_ERR(fc)) { ray_release(flat); ray_release(tbl); return fc ? fc : ray_error("oom", NULL); } - flat = ray_table_add_col(flat, ray_table_col_name(tbl, c), fc); - ray_release(fc); - if (!flat || RAY_IS_ERR(flat)) { ray_release(tbl); return flat ? flat : ray_error("oom", NULL); } - } + ray_t* flat = query_materialize_parted_table(tbl); ray_release(tbl); + if (!flat || RAY_IS_ERR(flat)) return flat ? flat : ray_error("oom", NULL); tbl = flat; } @@ -26371,12 +32032,16 @@ ray_t* ray_delete(ray_t** args, int64_t n) { * leaves ray_data resolving into the parent's storage, so compacting the * copy would move the PARENT's elements. The in-place path declines one * through upsert_col_ok; the copying form has no such backstop, so refuse - * rather than corrupt a buffer somebody else owns. */ - for (int64_t c = 0; c < ncols; c++) - if (ray_table_get_col_idx(tbl, c)->attrs & RAY_ATTR_SLICE) { + * rather than corrupt a buffer somebody else owns. SLICE is a runtime + * attr of a plain slot; an encoded slot is never a slice. */ + for (int64_t c = 0; c < ncols; c++) { + if (ray_table_get_col_enc_idx(tbl, c)) continue; + ray_t* col = ray_table_col_idx(tbl, c); /* plain: no decode */ + if (col && (col->attrs & RAY_ATTR_SLICE)) { ray_release(tbl); return ray_error("domain", "delete: column %lld is a slice view", (long long)c); } + } /* Decide in-place BEFORE evaluating the predicate. The predicate machinery * binds the table's columns into a query scope (and builds a graph over @@ -26385,7 +32050,7 @@ ray_t* ray_delete(ray_t** args, int64_t n) { !(tbl->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); ray_t* live_cols = NULL; if (inplace) { - live_cols = ((ray_t**)ray_data(tbl))[1]; + live_cols = ray_table_cols_inplace(tbl); /* NULL: an encoded slot */ if (!live_cols || live_cols->rc != 1 || live_cols->len != ncols) inplace = false; } for (int64_t c = 0; inplace && c < ncols; c++) { @@ -26439,7 +32104,10 @@ ray_t* ray_delete(ray_t** args, int64_t n) { return work ? work : ray_error("oom", NULL); } for (int64_t c = 0; c < ncols && !err; c++) { - ray_t* orig = ray_table_get_col_idx(tbl, c); + /* An encoded slot's cached materialization reaches ray_cow shared + * (rc 2 with this retain), so it is copied. */ + ray_t* orig = ray_table_col_idx(tbl, c); + if (!orig || RAY_IS_ERR(orig)) { err = orig ? orig : ray_error("oom", NULL); break; } ray_retain(orig); ray_t* cp = ray_cow(orig); if (!cp || RAY_IS_ERR(cp)) { ray_release(orig); err = cp ? cp : ray_error("oom", NULL); break; } @@ -26448,8 +32116,10 @@ ray_t* ray_delete(ray_t** args, int64_t n) { if (!work || RAY_IS_ERR(work)) { err = work ? work : ray_error("oom", NULL); work = NULL; } } if (!err) { - ray_t** wslots = (ray_t**)ray_data(((ray_t**)ray_data(work))[1]); - err = delete_compact_cols(wslots, ncols, nrows0, rows, k); + /* a table of private copies: never an encoded slot */ + ray_t* wc = ray_table_cols_inplace(work); + err = wc ? delete_compact_cols((ray_t**)ray_data(wc), ncols, nrows0, rows, k) + : ray_error("oom", NULL); } scratch_free(rows_hdr); ray_release(tbl); diff --git a/src/ops/rerank.c b/src/ops/rerank.c index 0c8e80c8f..5e17ea79f 100644 --- a/src/ops/rerank.c +++ b/src/ops/rerank.c @@ -28,6 +28,7 @@ */ #include "ops/internal.h" +#include "table/table.h" #include "ops/rowsel.h" #include "lang/format.h" #include "store/hnsw.h" @@ -98,10 +99,10 @@ static ray_t* empty_result_with_dist(ray_t* src) { ray_t* out = ray_table_new(ncols + 1); if (!out || RAY_IS_ERR(out)) return NULL; for (int64_t c = 0; c < ncols; c++) { - ray_t* sc = ray_table_get_col_idx(src, c); - if (!sc) continue; - int8_t ct = RAY_IS_PARTED(sc->type) - ? (int8_t)RAY_PARTED_BASETYPE(sc->type) : sc->type; + ray_col_meta_t sm; + if (!ray_table_col_meta_idx(src, c, &sm)) continue; + int8_t ct = RAY_IS_PARTED(sm.type) + ? (int8_t)RAY_PARTED_BASETYPE(sm.type) : sm.type; ray_t* nc = (ct == RAY_LIST) ? ray_list_new(0) : ray_vec_new(ct, 0); if (!nc || RAY_IS_ERR(nc)) { ray_release(out); return NULL; } nc->len = 0; @@ -119,7 +120,8 @@ static ray_t* empty_result_with_dist(ray_t* src) { /* Gather k rows from `tbl` at dense `rowids[]`, appending a `_dist` F64 * column with the parallel distances. Caller owns the returned table. - * Returns NULL on OOM. */ + * Returns NULL on OOM, or an error object (unsupported column, a column that + * fails to load). */ static ray_t* gather_rows_with_dist(ray_t* tbl, const int64_t* rowids, const double* dists, int64_t k) { @@ -128,7 +130,8 @@ static ray_t* gather_rows_with_dist(ray_t* tbl, if (!result || RAY_IS_ERR(result)) return NULL; for (int64_t c = 0; c < ncols; c++) { - ray_t* src_col = ray_table_get_col_idx(tbl, c); + ray_t* src_col = ray_table_col_idx(tbl, c); + if (src_col && RAY_IS_ERR(src_col)) { ray_release(result); return src_col; } if (!src_col) { ray_release(result); return NULL; } /* PARTED columns carry ray_t** segment pointers in their data @@ -450,7 +453,8 @@ ray_t* exec_knn_rerank(ray_graph_t* g, ray_op_t* op, ray_t* src) { /* We walk the ORIGINAL source table and skip non-accepted rows via * an accepted-rowid list. Avoids sel_compact, which currently * doesn't correctly materialise RAY_LIST columns. */ - ray_t* col = ray_table_get_col(src, col_sym); + ray_t* col = ray_table_col(src, col_sym); + if (col && RAY_IS_ERR(col)) return col; if (!col) return ray_error("name", NULL); if (col->type != RAY_LIST) return ray_error("type", "knn rerank: vector column must be a list of vectors, got %s", ray_type_name(col->type)); diff --git a/src/ops/rowsel.c b/src/ops/rowsel.c index a3d56cd09..4891cb6c9 100644 --- a/src/ops/rowsel.c +++ b/src/ops/rowsel.c @@ -313,6 +313,64 @@ void rowsel_emit_segment(rowsel_builder_t* b, uint32_t seg, b->seg_off[seg + 1] = b->idx_len; } +void rowsel_emit_uniform(rowsel_builder_t* b, uint32_t seg, uint8_t d, int64_t n) { + assert(seg < b->n_segs && "rowsel_emit_uniform: seg is not builder-local"); + b->seg_off[seg] = b->idx_len; + /* rowsel_emit_segment's classification of n equal bools */ + if (d && n > 0) { b->seg_flags[seg] = RAY_SEL_ALL; b->total_pass += n; } + else b->seg_flags[seg] = RAY_SEL_NONE; + b->seg_off[seg + 1] = b->idx_len; +} + +void rowsel_emit_runs(rowsel_builder_t* b, uint32_t seg, const uint16_t* ends, + const uint8_t* pass, uint32_t n_runs, int64_t n) { + assert(seg < b->n_segs && "rowsel_emit_runs: seg is not builder-local"); + b->seg_off[seg] = b->idx_len; + uint32_t pc = 0, s0 = 0; + for (uint32_t r = 0; r < n_runs; r++) { + pc += pass[r] ? (uint32_t)ends[r] - s0 : 0; + s0 = ends[r]; + } + b->total_pass += pc; + /* rowsel_emit_segment's NONE / ALL / MIX classification */ + if (pc == 0) { + b->seg_flags[seg] = RAY_SEL_NONE; + } else if ((int64_t)pc == n) { + b->seg_flags[seg] = RAY_SEL_ALL; + } else { + b->seg_flags[seg] = RAY_SEL_MIX; + /* room for pc indices plus one 16-index store past them (below) */ + if (b->idx_len + pc + 16 > b->idx_cap) { + uint32_t newcap = b->idx_cap ? b->idx_cap : 8u; + while (newcap < b->idx_len + pc + 16) newcap *= 2u; + b->idx = (uint16_t*)ray_realloc_raw(b->idx, (size_t)newcap * sizeof(uint16_t)); + b->idx_cap = newcap; + } + /* a passing run's indices in fixed 16-index stores: the indices a + * store writes past the run are overwritten by the next passing + * run's (out advances by the run's length only), and the last + * store's tail lies past idx_len, inside the capacity reserved + * above, where nothing reads it */ + typedef uint16_t idx16_t __attribute__((vector_size(32))); + const idx16_t iota = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + uint16_t* out = b->idx + b->idx_len; + s0 = 0; + for (uint32_t r = 0; r < n_runs; r++) { + const uint32_t e = ends[r]; + if (pass[r]) { + for (uint32_t i = s0; i < e; i += 16) { + const idx16_t v = iota + (uint16_t)i; + memcpy(out + (i - s0), &v, sizeof v); + } + out += e - s0; + } + s0 = e; + } + b->idx_len += pc; + } + b->seg_off[seg + 1] = b->idx_len; +} + ray_t* rowsel_builder_finish(rowsel_builder_t* builders, uint32_t n_workers, int64_t nrows) { int64_t total_pass = 0; @@ -694,3 +752,56 @@ ray_t* ray_rowsel_intersect(ray_t* a, ray_t* b) { oo[ns] = cum; return out; } + +ray_t* ray_rowsel_head(ray_t* sel, int64_t limit) { + if (!sel) return NULL; + ray_rowsel_t* m = ray_rowsel_meta(sel); + const uint8_t* fl = ray_rowsel_flags(sel); + const uint32_t* off = ray_rowsel_offsets(sel); + const uint16_t* ix = ray_rowsel_idx(sel); + uint32_t ns = m->n_segs; + if (limit < 0) limit = 0; + if (limit > m->total_pass) limit = m->total_pass; + + /* Segments [0, whole) are kept as they are; cut_n rows of segment + * `whole` finish the head. */ + uint32_t whole = 0; + int64_t kept = 0, cut_n = 0, idx_count = 0; + for (; whole < ns && kept < limit; whole++) { + int64_t ss = (int64_t)whole * RAY_MORSEL_ELEMS; + int64_t se = ss + RAY_MORSEL_ELEMS; + if (se > m->nrows) se = m->nrows; + int64_t pc = fl[whole] == RAY_SEL_NONE ? 0 + : fl[whole] == RAY_SEL_ALL ? se - ss + : (int64_t)(off[whole + 1] - off[whole]); + if (kept + pc > limit) { cut_n = limit - kept; idx_count += cut_n; break; } + kept += pc; + if (fl[whole] == RAY_SEL_MIX) idx_count += pc; + } + + ray_t* out = ray_rowsel_new(m->nrows, limit, idx_count); + if (!out) return NULL; + uint8_t* of = ray_rowsel_flags(out); + uint32_t* oo = ray_rowsel_offsets(out); + uint16_t* oi = ray_rowsel_idx(out); + uint32_t cum = 0; + for (uint32_t s = 0; s < ns; s++) { + oo[s] = cum; + if (s < whole) { + of[s] = fl[s]; + if (fl[s] == RAY_SEL_MIX) { + uint32_t pc = off[s + 1] - off[s]; + memcpy(oi + cum, ix + off[s], pc * sizeof(uint16_t)); + cum += pc; + } + } else if (s == whole && cut_n > 0) { + of[s] = RAY_SEL_MIX; + for (int64_t i = 0; i < cut_n; i++) + oi[cum++] = fl[s] == RAY_SEL_ALL ? (uint16_t)i : ix[off[s] + i]; + } else { + of[s] = RAY_SEL_NONE; + } + } + oo[ns] = cum; + return out; +} diff --git a/src/ops/rowsel.h b/src/ops/rowsel.h index a4139e4fb..fe559b887 100644 --- a/src/ops/rowsel.h +++ b/src/ops/rowsel.h @@ -189,6 +189,12 @@ ray_t* ray_rowsel_refine(ray_t* existing, ray_t* pred); * preserving NONE/ALL compression without materializing a bool vector. */ ray_t* ray_rowsel_intersect(ray_t* a, ray_t* b); +/* The first `limit` rows `sel` keeps (borrowed), as a fresh rowsel over + * the same rows: segments before the cut as they are, the cut segment MIX, + * NONE after it. A limit past total_pass keeps every row. O(n_segs + + * limit). NULL on OOM. */ +ray_t* ray_rowsel_head(ray_t* sel, int64_t limit); + /* ────────────────────────────────────────────────────────────────── * Streaming builder — per-morsel selection emitter * @@ -249,6 +255,17 @@ void rowsel_builder_init(rowsel_builder_t* b, uint32_t n_segs); void rowsel_emit_segment(rowsel_builder_t* b, uint32_t seg, const uint8_t* morsel_bool, int64_t n); +/* rowsel_emit_segment of `n` bools all equal to d (0 / 1), never + * scanned: NONE or ALL. */ +void rowsel_emit_uniform(rowsel_builder_t* b, uint32_t seg, uint8_t d, int64_t n); + +/* rowsel_emit_segment of a morsel given as n_runs runs: run r covers the + * rows [ends[r - 1], ends[r]) (ends[-1] = 0, ends[n_runs - 1] = n) and + * passes when pass[r] is set. The segment is byte-identical to emitting + * the runs' expanded bools. */ +void rowsel_emit_runs(rowsel_builder_t* b, uint32_t seg, const uint16_t* ends, + const uint8_t* pass, uint32_t n_runs, int64_t n); + /* Concatenate `n_workers` builders (segment ranges globally ordered by * worker index) into a fresh ray_rowsel_new(nrows, total_pass, idx_count) * block with the standard layout: seg_flags, seg_offsets (prefix sum diff --git a/src/ops/select_merge.c b/src/ops/select_merge.c index 1918d1112..c93c159e8 100644 --- a/src/ops/select_merge.c +++ b/src/ops/select_merge.c @@ -99,7 +99,7 @@ static ray_t* merge_put(ray_t* d, int64_t id, ray_t* value) { /* Reject shadowed builtins, including source columns used as call heads. */ static ray_t* merge_fn(merge_scope_t* s, ray_t* head) { if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED) || - ray_table_get_col(s->table, head->i64) || ray_env_has_lexical_local(head->i64)) return NULL; + ray_table_has_col(s->table, head->i64) || ray_env_has_lexical_local(head->i64)) return NULL; for (int i = 0; i < s->n; i++) if (s->cols[i].name == head->i64) return NULL; return ray_env_get(head->i64); } @@ -129,9 +129,10 @@ static ray_t* merge_expr(merge_scope_t* s, ray_t* e, int* type, bool* column, in *type = s->cols[i].type; *column = true; return merge_ref(s->cols[i].expr); } - ray_t* col = ray_table_get_col(s->table, e->i64); - if (col && !s->projected && col->type > 0 && col->type <= RAY_STR) { - *type = col->type; *column = true; + ray_col_meta_t cm; /* metadata: an encoded column stays encoded */ + bool col = ray_table_col_meta(s->table, e->i64, &cm); + if (col && !s->projected && ray_is_vector_type(cm.type)) { + *type = cm.type; *column = true; return merge_ref(e); } /* A quoted literal must not become a column reference after merge. */ @@ -178,8 +179,8 @@ static ray_t* merge_expr(merge_scope_t* s, ray_t* e, int* type, bool* column, in * intermediates (even when a later multiplier promotes the result to F64). */ static bool merge_scaled_f64(ray_t* table, ray_t* e) { if (e->type == -RAY_SYM) { - ray_t* col = ray_table_get_col(table, e->i64); - return col && col->type == RAY_F64; + ray_col_meta_t cm; + return ray_table_col_meta(table, e->i64, &cm) && cm.type == RAY_F64; } if (e->type != RAY_LIST || e->len != 3) return false; ray_t** es = ray_data(e); @@ -236,7 +237,10 @@ static bool merge_prefix_nonempty(ray_t* table, ray_t* where) { ray_t* prefix = ray_table_new(nc); if (!prefix || RAY_IS_ERR(prefix)) { merge_drop(prefix); return false; } for (int64_t i = 0; i < nc; i++) { - ray_t* c = ray_vec_slice(ray_table_get_col_idx(table, i), 0, MERGE_PREFIX_ROWS); + /* an encoded column is not sliced (that would decode it whole): + * no proof, the query stays as written */ + if (ray_table_get_col_enc_idx(table, i)) { merge_drop(prefix); return false; } + ray_t* c = ray_vec_slice(ray_table_col_idx(table, i), 0, MERGE_PREFIX_ROWS); /* plain: checked above */ if (!c || RAY_IS_ERR(c)) { merge_drop(c); merge_drop(prefix); return false; } prefix = ray_table_add_col(prefix, ray_table_col_name(table, i), c); merge_drop(c); @@ -265,8 +269,8 @@ static ray_t* merge_pair(ray_t* outer, ray_t* inner) { /* Partitioned/lazy and list columns need their own materialization proof, * including errors from columns an outer projection would discard. */ for (int64_t i = 0; i < ray_table_ncols(tbl); i++) { - ray_t* c = ray_table_get_col_idx(tbl, i); - if (!c || c->type <= 0 || c->type > RAY_STR) return NULL; + ray_col_meta_t m; /* metadata: an encoded column stays encoded */ + if (!ray_table_col_meta_idx(tbl, i, &m) || m.type <= 0 || m.type > RAY_STR) return NULL; } ray_t* ik = ray_dict_keys(inner), **iv = ray_data(ray_dict_vals(inner)); ray_t* ok = ray_dict_keys(outer), **ov = ray_data(ray_dict_vals(outer)); @@ -293,7 +297,7 @@ static ray_t* merge_pair(ray_t* outer, ray_t* inner) { int64_t name = sym_cell_runtime_id(ik, i); if (merge_clause(name)) continue; v = merge_expr(&s, iv[i], &type, &col, 0); - if (!v || !col || (ray_table_get_col(tbl, name) && !merge_identity(v, name))) goto done; + if (!v || !col || (ray_table_has_col(tbl, name) && !merge_identity(v, name))) goto done; s.cols[s.n++] = (merge_col_t){.name = name, .expr = v, .type = type, .computed = v->type == RAY_LIST}; v = NULL; @@ -338,7 +342,7 @@ static ray_t* merge_pair(ray_t* outer, ray_t* inner) { v = merge_ref(ov[i]); } else { v = merge_output(&s, ov[i], &type); - if (!v || (ray_table_get_col(tbl, name) && !merge_identity(v, name))) goto decline; + if (!v || (ray_table_has_col(tbl, name) && !merge_identity(v, name))) goto decline; aggregate |= v->type == RAY_LIST && v->len == 2; if (merge_get(outer, 4) && !(v->type == RAY_LIST && v->len == 2) && (type == RAY_SYM || type == RAY_STR)) goto decline; @@ -363,8 +367,8 @@ static ray_t* merge_pair(ray_t* outer, ray_t* inner) { } if (!nout && !s.projected && merge_get(outer, 4)) { for (int64_t i = 0; i < ray_table_ncols(tbl); i++) { - ray_t* c = ray_table_get_col_idx(tbl, i); - if (!c || c->type == RAY_SYM || c->type == RAY_STR) goto decline; + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, i, &m) || m.type == RAY_SYM || m.type == RAY_STR) goto decline; } } for (int clause = 5; clause <= 6; clause++) { @@ -375,7 +379,7 @@ static ray_t* merge_pair(ray_t* outer, ray_t* inner) { for (int i = 0; i < s.n; i++) if (s.cols[i].name == sort->i64 && !merge_identity(s.cols[i].expr, sort->i64)) goto decline; - bool visible = !nout && !s.projected && ray_table_get_col(tbl, sort->i64); + bool visible = !nout && !s.projected && ray_table_has_col(tbl, sort->i64); for (int i = 0; i < nout; i++) visible |= outputs[i] == sort->i64; if (!nout) for (int i = 0; i < s.n; i++) visible |= s.cols[i].name == sort->i64; /* A group key is also an output even without an explicit projection. */ diff --git a/src/ops/sort.c b/src/ops/sort.c index 3e8a02edf..b03065300 100644 --- a/src/ops/sort.c +++ b/src/ops/sort.c @@ -26,6 +26,9 @@ #include "ops/ops.h" #include "ops/idxop.h" #include "mem/sys.h" +#include "ops/colgather.h" /* generation-2 top-K gathers */ +#include "ops/rowsel.h" /* exec_sort_head_sel: the winners' rowsel */ +#include /* -------------------------------------------------------------------------- * Sort comparator: compare two row indices across all sort keys. @@ -61,7 +64,7 @@ int sort_cmp(const sort_cmp_ctx_t* ctx, int64_t a, int64_t b) { float vb = ((float*)ray_data(col))[b]; if (va < vb) cmp = -1; else if (va > vb) cmp = 1; - } else if (col->type == RAY_I64 || col->type == RAY_TIMESTAMP) { + } else if (col->type == RAY_I64 || col->type == RAY_TIMESPAN || col->type == RAY_TIMESTAMP) { int64_t va = ((int64_t*)ray_data(col))[a]; int64_t vb = ((int64_t*)ray_data(col))[b]; if (va < vb) cmp = -1; @@ -251,6 +254,12 @@ static void sortedness_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { for (int64_t i = start + 1; i < end; i++) { if (keys[i] < keys[i - 1]) unsorted++; } + /* a clamped dispatch's task spans several grains: the caller counts + * every grain boundary pair, so this task's inner ones are taken back */ + const int64_t grain = RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; + if (RAY_UNLIKELY(end - start > grain)) + for (int64_t b = (start / grain + 1) * grain; b < end; b += grain) + if (keys[b] < keys[b - 1]) unsorted--; c->pw_unsorted[wid] += unsorted; } @@ -948,7 +957,7 @@ void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { if (c->n_keys <= 1) { /* Single-key fast path */ switch (c->type) { - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* d = (const int64_t*)c->data; bool has_nulls = c->col && ray_vec_may_have_nulls(c->col); bool nf = c->nulls_first; @@ -1139,13 +1148,11 @@ void radix_encode_fn(void* arg, uint32_t wid, int64_t start, int64_t end) { if (c->enum_ranks[k]) { uint32_t raw = (uint32_t)ray_read_sym(ray_data(col), i, col->type, col->attrs); val = (int64_t)c->enum_ranks[k][raw]; - } else if (col->type == RAY_I64 || col->type == RAY_TIMESTAMP) { + } else if (col->type == RAY_I64 || col->type == RAY_TIMESPAN || col->type == RAY_TIMESTAMP) { val = ((const int64_t*)ray_data(col))[i]; } else if (col->type == RAY_F64) { - uint64_t bits; - memcpy(&bits, &((const double*)ray_data(col))[i], 8); - uint64_t mask = -(bits >> 63) | ((uint64_t)1 << 63); - val = (int64_t)(bits ^ mask); + double x = ((const double*)ray_data(col))[i]; + val = radix_f64_is_null(x) ? c->mins[k] : radix_f64_ord(x); } else if (col->type == RAY_I32 || col->type == RAY_DATE || col->type == RAY_TIME) { val = (int64_t)((const int32_t*)ray_data(col))[i]; } else if (col->type == RAY_I16) { @@ -2199,13 +2206,6 @@ void mk_prescan_fn(void* arg, uint32_t wid, int64_t* my_mins = c->pw_mins + (int64_t)wid * nk; int64_t* my_maxs = c->pw_maxs + (int64_t)wid * nk; - /* Initialize on first morsel, merge on subsequent */ - for (uint32_t k = 0; k < nk; k++) { - if (my_mins[k] == INT64_MAX) { - /* first morsel for this worker — will be set below */ - } - } - for (uint32_t k = 0; k < nk; k++) { ray_t* col = c->vecs[k]; int64_t kmin = my_mins[k], kmax = my_maxs[k]; @@ -2221,7 +2221,7 @@ void mk_prescan_fn(void* arg, uint32_t wid, if (v < kmin) kmin = v; if (v > kmax) kmax = v; } - } else if (col->type == RAY_I64 || col->type == RAY_TIMESTAMP) { + } else if (col->type == RAY_I64 || col->type == RAY_TIMESPAN || col->type == RAY_TIMESTAMP) { const int64_t* d = (const int64_t*)ray_data(col); for (int64_t i = start; i < end; i++) { if (d[i] < kmin) kmin = d[i]; @@ -2230,10 +2230,8 @@ void mk_prescan_fn(void* arg, uint32_t wid, } else if (col->type == RAY_F64) { const double* d = (const double*)ray_data(col); for (int64_t i = start; i < end; i++) { - uint64_t bits; - memcpy(&bits, &d[i], 8); - uint64_t mask = -(bits >> 63) | ((uint64_t)1 << 63); - int64_t v = (int64_t)(bits ^ mask); + if (radix_f64_is_null(d[i])) continue; + int64_t v = radix_f64_ord(d[i]); if (v < kmin) kmin = v; if (v > kmax) kmax = v; } @@ -2269,7 +2267,7 @@ void mk_prescan_fn(void* arg, uint32_t wid, * Sequential writes — no random access. */ static void radix_decode_into(void* dst, int8_t type, const uint64_t* sorted_keys, int64_t n, bool desc) { - if (type == RAY_I64 || type == RAY_TIMESTAMP) { + if (type == RAY_I64 || type == RAY_TIMESPAN || type == RAY_TIMESTAMP) { int64_t* d = (int64_t*)dst; if (desc) for (int64_t i = 0; i < n; i++) @@ -2332,10 +2330,12 @@ static void radix_decode_into(void* dst, int8_t type, const uint64_t* sorted_key * nrows: number of rows in each column * sorted_keys_out: if non-NULL, receives sorted radix keys (caller frees keys_hdr_out) * keys_hdr_out: if non-NULL, receives scratch header for sorted_keys_out + * prepared_ranks: optional borrowed lexical ranks; caller retains ownership * Returns: ray_t* I64 vector of sorted indices (caller owns), or RAY_ERROR */ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, uint32_t n_cols, int64_t nrows, - uint64_t** sorted_keys_out, ray_t** keys_hdr_out) { + uint64_t** sorted_keys_out, ray_t** keys_hdr_out, + uint32_t* const* prepared_ranks) { if (n_cols == 0 || nrows <= 0) return ray_vec_new(RAY_I64, 0); /* No n_cols cap here: the composite-radix fast path below (`fits`) @@ -2415,8 +2415,10 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first if (enum_ranks) { for (uint32_t k = 0; k < n_cols; k++) { if (RAY_IS_SYM(cols[k]->type)) { - enum_ranks[k] = build_enum_rank(cols[k], nrows, - &enum_rank_hdrs[k]); + enum_ranks[k] = prepared_ranks ? prepared_ranks[k] : NULL; + if (!enum_ranks[k]) + enum_ranks[k] = build_enum_rank(cols[k], nrows, + &enum_rank_hdrs[k]); if (!enum_ranks[k]) { can_radix = false; break; } } } @@ -2649,30 +2651,14 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first uint16_t total_bits = 0; bool fits = true; - /* A float null is NaN, and the composite encode packs a - * double by flipping its bits — which puts NaN above every - * real number, i.e. last on ascending, whatever - * sort_nulls_first says. The other types carry a sentinel - * that already lands where the rule wants it (INT64_MIN is - * the smallest), so only F64 disagrees. Rather than teach - * the packing a second placement, hand a null-bearing float - * key to the rank-then-compose fallback, which ranks - * through sort_indices_ex and is null-aware. Leaving it in - * the direct encode is what made a multi-key sort place - * floats one way below 64 rows and the other way above. */ - bool nullable_f64_key = false; - for (uint32_t k = 0; k < n_cols; k++) - if (cols[k]->type == RAY_F64 && - ray_vec_may_have_nulls(cols[k])) { - nullable_f64_key = true; - break; - } - + /* A null-bearing F64 key packs its nulls into a reserved + * slot below its minimum (radix_key_bounds_finish), so it + * stays on the composite with the placement the comparator + * gives, at every row count. */ ray_pool_t* mk_prescan_pool = (nrows >= SMALL_POOL_THRESHOLD) ? pool : NULL; - if (has_wide_key || nullable_f64_key) { + if (has_wide_key) { /* RAY_STR / RAY_GUID can't be packed into a composite - * uint64 key, and a nullable float must not be. Force - * the rank-then-compose fallback. */ + * uint64 key. Force the rank-then-compose fallback. */ total_bits = UINT16_MAX; fits = false; } else if (n_cols <= MK_PRESCAN_MAX_KEYS && mk_prescan_pool) { @@ -2706,6 +2692,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first if (wmin < kmin) kmin = wmin; if (wmax > kmax) kmax = wmax; } + radix_key_bounds_finish(cols[k], &kmin, &kmax); mins[k] = kmin; maxs[k] = kmax; /* Unsigned subtraction: kmin can be the i64 null @@ -2734,7 +2721,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first if (v < kmin) kmin = v; if (v > kmax) kmax = v; } - } else if (col->type == RAY_I64 || col->type == RAY_TIMESTAMP) { + } else if (col->type == RAY_I64 || col->type == RAY_TIMESPAN || col->type == RAY_TIMESTAMP) { const int64_t* d = (const int64_t*)ray_data(col); for (int64_t i = 0; i < nrows; i++) { if (d[i] < kmin) kmin = d[i]; @@ -2743,10 +2730,8 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first } else if (col->type == RAY_F64) { const double* d = (const double*)ray_data(col); for (int64_t i = 0; i < nrows; i++) { - uint64_t bits; - memcpy(&bits, &d[i], 8); - uint64_t mask = -(bits >> 63) | ((uint64_t)1 << 63); - int64_t v = (int64_t)(bits ^ mask); + if (radix_f64_is_null(d[i])) continue; + int64_t v = radix_f64_ord(d[i]); if (v < kmin) kmin = v; if (v > kmax) kmax = v; } @@ -2770,6 +2755,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first } } + radix_key_bounds_finish(cols[k], &kmin, &kmax); mins[k] = kmin; maxs[k] = kmax; /* Unsigned subtraction: kmin can be the i64 null @@ -2815,7 +2801,8 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first uint8_t nf_arg[1] = { knf }; ray_t* sk_idx = sort_indices_ex(col_arg, desc_arg, nf_arg, 1, nrows, - NULL, NULL); + NULL, NULL, + enum_ranks + k); if (!sk_idx || RAY_IS_ERR(sk_idx)) { rank_ok = false; break; } int64_t* sk_idx_data = (int64_t*)ray_data(sk_idx); uint32_t* r = (uint32_t*)scratch_alloc(&rank_hdrs[k], @@ -2929,9 +2916,9 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first uint8_t accum = 0; for (int k = n_cols - 1; k >= 0; k--) { bit_shifts[k] = accum; - uint64_t range = (uint64_t)(maxs[k] - mins[k]); + uint64_t range = (uint64_t)maxs[k] - (uint64_t)mins[k]; uint8_t bits = 1; - while (((uint64_t)1 << bits) <= range && bits < 64) + while (bits < 64 && ((uint64_t)1 << bits) <= range) bits++; accum += bits; } @@ -2952,7 +2939,7 @@ static ray_t* sort_indices_ex(ray_t** cols, uint8_t* descs, uint8_t* nulls_first }; for (uint32_t k = 0; k < n_cols; k++) { enc.mins[k] = mins[k]; - enc.ranges[k] = maxs[k] - mins[k]; + enc.ranges[k] = (int64_t)((uint64_t)maxs[k] - (uint64_t)mins[k]); enc.bit_shifts[k] = bit_shifts[k]; enc.descs[k] = descs ? descs[k] : 0; enc.enum_ranks[k] = enum_ranks[k]; @@ -3140,8 +3127,10 @@ static void topk_cmp_sift_down(const sort_cmp_ctx_t* ctx, int64_t* heap, /* Comparator-based top-K: works for any comparable sort key types and any * number of keys (1..n). Used when the radix-encoded fast path is not - * applicable. O(n log K + K log K). */ -static ray_t* topk_indices_cmp(ray_t** cols, uint8_t* descs, uint8_t* nfs, + * applicable. O(n log K + K log K). Always inlined: ray_topk_table_multi + * keeps the code it had as the only caller (exec_sort_head_sel is the + * second). */ +static inline __attribute__((always_inline)) ray_t* topk_indices_cmp(ray_t** cols, uint8_t* descs, uint8_t* nfs, uint8_t n_cols, int64_t nrows, int64_t k) { if (!cols || n_cols == 0 || k <= 0 || nrows <= 0 || k >= nrows) return NULL; for (uint8_t c = 0; c < n_cols; c++) if (!cols[c]) return NULL; @@ -3231,7 +3220,7 @@ static ray_t* topk_indices_single(ray_t* col, uint8_t desc, uint8_t nf, int8_t type = col->type; /* Whitelist of types where radix_encode_fn produces an order-preserving * uint64 — exactly the cases topk can handle without a comparator. */ - bool ok = (type == RAY_I64 || type == RAY_TIMESTAMP || + bool ok = (type == RAY_I64 || type == RAY_TIMESPAN || type == RAY_TIMESTAMP || type == RAY_F64 || type == RAY_F32 || type == RAY_I32 || type == RAY_DATE || type == RAY_TIME || type == RAY_SYM || type == RAY_STR || type == RAY_GUID || @@ -3350,8 +3339,9 @@ static ray_t* topk_indices_single(ray_t* col, uint8_t desc, uint8_t nf, static bool table_has_parted_col(ray_t* tbl) { int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && + (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON)) return true; } return false; @@ -3366,10 +3356,21 @@ static ray_t* topk_gather_rows(ray_t* tbl, ray_t* idx, int64_t k) { ray_t* result = ray_table_new(ncols); if (!result || RAY_IS_ERR(result)) { ray_release(idx); return result; } for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(tbl, c); int64_t name = ray_table_col_name(tbl, c); + ray_t* dst = NULL; + /* a generation-2 slot: the K rows' vectors, decoded by range */ + ray_t* enc = ray_col_gather_slot(ray_table_get_col_enc_idx(tbl, c)); + if (enc) { + ray_t* err = ray_col_gather_enc(enc, NULL, true, idx_data, k, &dst); + if (err) { ray_release(idx); ray_release(result); return err; } + result = ray_table_add_col(result, name, dst); + ray_release(dst); + if (!result || RAY_IS_ERR(result)) { ray_release(idx); return result ? result : ray_error("oom", NULL); } + continue; + } + ray_t* src = ray_table_col_idx(tbl, c); + if (src && RAY_IS_ERR(src)) { ray_release(idx); ray_release(result); return src; } if (!src) continue; - ray_t* dst; if (src->type == RAY_LIST) { dst = ray_list_new(k); if (!dst || RAY_IS_ERR(dst)) { @@ -3412,8 +3413,8 @@ ray_t* ray_topk_table(ray_t* tbl, ray_t* col, uint8_t desc, uint8_t nf, if (k >= nrows) return NULL; int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(tbl, c); - if (src && src->type == RAY_LIST) return NULL; + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && m.type == RAY_LIST) return NULL; } ray_t* idx = topk_indices_single(col, desc, nf, nrows, k); @@ -3439,8 +3440,8 @@ ray_t* ray_topk_table_multi(ray_t* tbl, ray_t** key_cols, uint8_t* descs, if (k <= 0 || nrows <= 0 || k >= nrows) return NULL; int64_t ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < ncols; c++) { - ray_t* src = ray_table_get_col_idx(tbl, c); - if (src && src->type == RAY_LIST) return NULL; + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && m.type == RAY_LIST) return NULL; } for (uint8_t i = 0; i < n_keys; i++) if (!key_cols[i] || key_cols[i]->len < nrows) return NULL; @@ -3518,7 +3519,7 @@ ray_t* ray_bot_fn(ray_t* v, ray_t* n_obj) { ray_t* ray_sort_indices(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, uint8_t n_cols, int64_t nrows) { - return sort_indices_ex(cols, descs, nulls_first, n_cols, nrows, NULL, NULL); + return sort_indices_ex(cols, descs, nulls_first, n_cols, nrows, NULL, NULL, NULL); } ray_t* ray_sort(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, @@ -3527,7 +3528,7 @@ ray_t* ray_sort(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, uint64_t* sorted_keys = NULL; ray_t* keys_hdr = NULL; ray_t* idx = sort_indices_ex(cols, descs, nulls_first, 1, nrows, - &sorted_keys, &keys_hdr); + &sorted_keys, &keys_hdr, NULL); if (!idx || RAY_IS_ERR(idx)) return idx; bool c0_shifted = ray_vec_may_have_nulls(cols[0]) && @@ -3577,7 +3578,8 @@ ray_t* ray_sort(ray_t** cols, uint8_t* descs, uint8_t* nulls_first, * POSITION: the projection names scans by their source column and * expressions `_e`, so a hidden key or a renamed output can share a * name with another projected column and a name lookup would read the - * wrong one. Any other key resolves by name. Borrowed. */ + * wrong one. Any other key resolves by name. Borrowed; NULL when absent, + * an owned error when an encoded column fails to materialize. */ static ray_t* sort_key_scan_col(ray_graph_t* g, ray_op_t* op, ray_t* tbl, uint32_t key_id, int64_t key_sym) { ray_op_t* child = g ? op_child(g, op, 0) : NULL; @@ -3587,9 +3589,58 @@ static ray_t* sort_key_scan_col(ray_graph_t* g, ray_op_t* op, ray_t* tbl, (int64_t)se->sort.n_cols == ray_table_ncols(tbl)) for (uint32_t c = 0; c < se->sort.n_cols; c++) if (se->sort.columns[c] == key_id) - return ray_table_get_col_idx(tbl, c); + return ray_table_col_idx(tbl, c); } - return ray_table_get_col(tbl, key_sym); + return ray_table_col(tbl, key_sym); +} + +/* ---- The top-k shortcut's gate, one copy for exec_sort and + * exec_sort_head_sel (the late route must decline exactly where the + * shortcut would not run on the compacted table) ---- */ + +/* The shape: 1..16 keys (the shortcut's fixed key arrays), K below the + * rows and at most 8192. */ +static inline bool topk_shortcut_shape(uint32_t n_sort, int64_t limit, int64_t nrows) { + return limit > 0 && n_sort >= 1 && n_sort <= 16 && limit < nrows && limit <= 8192; +} + +/* Key k is a column scan (the shortcut takes no computed key): its op id + * and name symbol. */ +static inline bool topk_scan_key(ray_graph_t* g, const ray_op_ext_t* ext, uint32_t k, uint32_t* id, int64_t* sym) { + ray_op_t* key_op = op_node(g, ext->sort.columns[k]); + ray_op_ext_t* key_ext = find_ext(g, key_op->id); + if (!key_ext || key_ext->base.opcode != OP_SCAN) return false; + *id = key_op->id; + *sym = key_ext->sym; + return true; +} + +/* Key k's column of `tbl` as the shortcut reads it (sort_key_scan_col); + * NULL for a computed key or a missing column (an error, freed: the full + * sort re-reads the key and reports it). */ +static inline ray_t* topk_key_col(ray_graph_t* g, ray_op_t* op, const ray_op_ext_t* ext, ray_t* tbl, uint32_t k) { + uint32_t id; int64_t sym; + if (!topk_scan_key(g, ext, k, &id, &sym)) return NULL; + ray_t* col = sort_key_scan_col(g, op, tbl, id, sym); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); col = NULL; } + return col; +} + +/* Key k's nulls-first flag, the sort's default when unset. */ +static inline uint8_t topk_key_nf(const ray_op_ext_t* ext, uint32_t k) { + uint8_t d = ext->sort.desc ? ext->sort.desc[k] : 0; + return ext->sort.nulls_first ? ext->sort.nulls_first[k] : sort_nulls_first(d); +} + +/* A LIST column (flat or parted): ray_topk_table / _multi decline. */ +static inline bool topk_has_list(ray_t* tbl) { + int64_t ncols = ray_table_ncols(tbl); + for (int64_t c = 0; c < ncols; c++) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && (m.type == RAY_LIST || m.type == RAY_PARTED_BASE + RAY_LIST)) + return true; + } + return false; } ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { @@ -3615,38 +3666,20 @@ ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { * n_sort <= 16: the shortcut's key_cols/nfs scratch below is a * fixed-16 stack array; wider sorts skip straight to the general * sort_indices_ex path (itself n_cols-unbounded). */ - if (limit > 0 && n_sort >= 1 && n_sort <= 16 && limit < nrows && limit <= 8192 && - g && g->selection == NULL) { + if (topk_shortcut_shape(n_sort, limit, nrows) && g && g->selection == NULL) { ray_t* key_cols[16]; int all_scan = 1; - for (uint32_t k = 0; k < n_sort; k++) { - ray_op_t* key_op = op_node(g, ext->sort.columns[k]); - ray_op_ext_t* key_ext = find_ext(g, key_op->id); - if (key_ext && key_ext->base.opcode == OP_SCAN) { - key_cols[k] = sort_key_scan_col(g, op, tbl, key_op->id, key_ext->sym); - if (!key_cols[k]) { all_scan = 0; break; } - } else { - all_scan = 0; - break; - } - } + for (uint32_t k = 0; k < n_sort; k++) + if (!(key_cols[k] = topk_key_col(g, op, ext, tbl, k))) { all_scan = 0; break; } if (all_scan) { if (n_sort == 1) { uint8_t desc = ext->sort.desc ? ext->sort.desc[0] : 0; - uint8_t nf = ext->sort.nulls_first - ? ext->sort.nulls_first[0] - : sort_nulls_first(desc); - ray_t* topk_res = ray_topk_table(tbl, key_cols[0], desc, nf, limit); + ray_t* topk_res = ray_topk_table(tbl, key_cols[0], desc, topk_key_nf(ext, 0), limit); if (topk_res && !RAY_IS_ERR(topk_res)) return topk_res; if (topk_res && RAY_IS_ERR(topk_res)) ray_release(topk_res); } else { uint8_t nfs[16]; - for (uint32_t k = 0; k < n_sort; k++) { - uint8_t d = ext->sort.desc ? ext->sort.desc[k] : 0; - nfs[k] = ext->sort.nulls_first - ? ext->sort.nulls_first[k] - : sort_nulls_first(d); - } + for (uint32_t k = 0; k < n_sort; k++) nfs[k] = topk_key_nf(ext, k); ray_t* topk_res = ray_topk_table_multi(tbl, key_cols, ext->sort.desc, nfs, n_sort, limit); if (topk_res && !RAY_IS_ERR(topk_res)) return topk_res; @@ -3694,6 +3727,29 @@ ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { } } + /* With no take, an already ordered table needs no permutation or + * gather. The shared check rejects null-bearing and unsupported key + * types; mixed directions still require the general comparator. */ + if (limit <= 0 && n_sort > 0 && !table_has_parted_col(tbl) && + (!g || !g->selection)) { + uint8_t descending = ext->sort.desc ? ext->sort.desc[0] : 0; + bool uniform = ray_is_vec(sort_vecs[0]) && sort_vecs[0]->len == nrows; + for (uint32_t k = 1; k < n_sort && uniform; k++) + if (!ray_is_vec(sort_vecs[k]) || sort_vecs[k]->len != nrows || + (ext->sort.desc ? ext->sort.desc[k] : 0) != descending) { + uniform = false; + break; + } + if (uniform && ray_key_cols_sorted(sort_vecs, n_sort, descending, nrows) && + !pool_cancelled(ray_pool_get())) { + for (uint32_t k = 0; k < n_sort; k++) + if (sort_owned[k]) ray_release(sort_vecs[k]); + scratch_free(sort_hdr); + ray_retain(tbl); + return tbl; + } + } + /* ---- Sort-index permutation reuse ---- * When there is exactly one ascending sort key that is a direct column * scan and that column carries a fresh, null-free sort index, reuse the @@ -3723,6 +3779,7 @@ ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { /* Index eligible and fresh: consult + hit. */ ray_idx_consults[IDX_SITE_SORT]++; ray_idx_hits[IDX_SITE_SORT]++; + ray_idx_note_use(sort_vecs[0]); ray_retain(perm); idx_vec = perm; goto sort_idx_ready; @@ -3730,7 +3787,7 @@ ray_t* exec_sort(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t limit) { } idx_vec = sort_indices_ex(sort_vecs, ext->sort.desc, ext->sort.nulls_first, n_sort, nrows, - &sorted_keys, &sorted_keys_hdr); + &sorted_keys, &sorted_keys_hdr, NULL); sort_idx_ready:; if (!idx_vec || RAY_IS_ERR(idx_vec)) { if (sorted_keys_hdr) scratch_free(sorted_keys_hdr); @@ -3778,10 +3835,24 @@ sort_idx_ready:; /* Pre-allocate all output columns, then do a single fused gather pass */ ray_pool_t* gather_pool = (gather_rows > RAY_PARALLEL_THRESHOLD) ? ray_pool_get() : NULL; ray_t* new_cols[ncols]; + ray_t* src_cols[ncols]; /* borrowed: the plain source columns */ int64_t col_names[ncols]; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_col_idx(tbl, c); col_names[c] = ray_table_col_name(tbl, c); + src_cols[c] = col; + if (col && RAY_IS_ERR(col)) { + for (int64_t j = 0; j < c; j++) + if (new_cols[j]) ray_release(new_cols[j]); + ray_release(result); + if (sorted_keys_hdr) scratch_free(sorted_keys_hdr); + for (uint32_t k = 0; k < n_sort; k++) + if (sort_owned[k] && sort_vecs[k] && !RAY_IS_ERR(sort_vecs[k])) + ray_release(sort_vecs[k]); + scratch_free(sort_hdr); + ray_release(idx_vec); + return col; + } if (!col) { new_cols[c] = NULL; continue; } ray_t* nc; if (col->type == RAY_LIST) { @@ -3859,7 +3930,7 @@ sort_idx_ready:; int64_t g_nc = 0; for (; base < ncols && g_nc < MGATHER_MAX_COLS; base++) { if (!new_cols[base] || base == decode_col_idx) continue; - ray_t* col = ray_table_get_col_idx(tbl, base); + ray_t* col = src_cols[base]; if (col->type == RAY_LIST) continue; g_srcs[g_nc] = (char*)ray_data(col); g_dsts[g_nc] = (char*)ray_data(new_cols[base]); @@ -3888,7 +3959,7 @@ sort_idx_ready:; /* Propagate str_pool / null bitmaps from source columns */ for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = src_cols[c]; if (!col) continue; col_propagate_str_pool(new_cols[c], col); /* Gather null bits in sorted order */ @@ -3920,6 +3991,164 @@ sort_idx_ready:; return result; } +/* ---- HEAD(SORT) under a lazy selection: late materialization ---- + * The old route compacted every column of the table under the selection, + * then took the top `limit` rows of the compacted table (ray_topk_table / + * _multi) and gathered them again. Here only the sort keys are compacted; + * the top-k runs on them exactly as it ran on the compacted table (the + * same values at the same positions, ties kept by the lower position); + * the winners' positions are mapped back to source rows through the + * selection, and only those rows of every column are compacted (a rowsel + * of the winners, ascending) and put in the top-k order by the same + * gather. So the answer is the old route's, row for row, and every + * column but the keys is read for `limit` rows instead of the selection's + * (parted q24: 646 survivors of 105 columns gathered for 10 results). + * NULL when the shape is not the one the top-k shortcut takes (the caller + * compacts the whole table and sorts, as before). */ +static ray_t* sel_rows_rowsel(int64_t nrows, const int64_t* rows, int64_t k) { + int64_t idx_count = 0; + for (int64_t i = 0; i < k; ) { + int64_t seg = rows[i] / RAY_MORSEL_ELEMS, j = i; + while (j < k && rows[j] / RAY_MORSEL_ELEMS == seg) j++; + int64_t seglen = nrows - seg * RAY_MORSEL_ELEMS < RAY_MORSEL_ELEMS ? nrows - seg * RAY_MORSEL_ELEMS : RAY_MORSEL_ELEMS; + if (j - i != seglen) idx_count += j - i; + i = j; + } + ray_t* sel = ray_rowsel_new(nrows, k, idx_count); + if (!sel) return NULL; + ray_rowsel_t* m = ray_rowsel_meta(sel); + uint8_t* flags = ray_rowsel_flags(sel); + uint32_t* offs = ray_rowsel_offsets(sel); + uint16_t* idx = ray_rowsel_idx(sel); + memset(flags, RAY_SEL_NONE, m->n_segs); + uint32_t at = 0; + int64_t i = 0; + for (uint32_t seg = 0; seg < m->n_segs; seg++) { + offs[seg] = at; + int64_t j = i; + while (j < k && rows[j] / RAY_MORSEL_ELEMS == (int64_t)seg) j++; + if (j == i) continue; + int64_t seglen = nrows - (int64_t)seg * RAY_MORSEL_ELEMS < RAY_MORSEL_ELEMS + ? nrows - (int64_t)seg * RAY_MORSEL_ELEMS : RAY_MORSEL_ELEMS; + if (j - i == seglen) { + flags[seg] = RAY_SEL_ALL; + } else { + flags[seg] = RAY_SEL_MIX; + for (int64_t q = i; q < j; q++) idx[at++] = (uint16_t)(rows[q] - (int64_t)seg * RAY_MORSEL_ELEMS); + } + i = j; + } + offs[m->n_segs] = at; + return sel; +} + +/* A position pair: the winner's position in the compacted keys and its + * rank in the top-k order. */ +typedef struct { int64_t pos, rank; } sel_late_pair_t; +static int sel_late_cmp(const void* a, const void* b) { + int64_t x = ((const sel_late_pair_t*)a)->pos, y = ((const sel_late_pair_t*)b)->pos; + return (x > y) - (x < y); +} + +static _Atomic(uint64_t) g_late_heads; /* test hook: late-materialized HEAD(SORT)s */ +uint64_t ray_sort_test_late_heads(void) { return atomic_load_explicit(&g_late_heads, memory_order_relaxed); } + +ray_t* exec_sort_head_sel(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* sel, int64_t limit) { + if (!g || !tbl || tbl->type != RAY_TABLE || !sel) return NULL; + ray_op_ext_t* ext = find_ext(g, op->id); + if (!ext) return NULL; + uint32_t n_sort = ext->sort.n_cols; + ray_rowsel_t* meta = ray_rowsel_meta(sel); + int64_t nrows = ray_table_nrows(tbl), pass = meta->total_pass; + /* exec_sort's top-k shortcut gate, as it would see the compacted + * table (its rows: the selection's), and ray_topk_table's LIST rule */ + if (!topk_shortcut_shape(n_sort, limit, pass) || meta->nrows != nrows || topk_has_list(tbl)) return NULL; + /* keys resolved by name on the key table (sort_key_scan_col's + * projected-child case keeps the old route) */ + ray_op_t* child = op_child(g, op, 0); + if (child && child->opcode == OP_SELECT) return NULL; + int64_t ncols = ray_table_ncols(tbl); + int64_t keys[16]; + for (uint32_t k = 0; k < n_sort; k++) { + uint32_t id; + if (!topk_scan_key(g, ext, k, &id, &keys[k])) return NULL; + bool found = false; + for (int64_t c = 0; c < ncols && !found; c++) found = ray_table_col_name(tbl, c) == keys[k]; + if (!found) return NULL; + } + ray_t* ktbl = sel_compact(g, tbl, sel, keys, (int)n_sort); + if (!ktbl || RAY_IS_ERR(ktbl)) return ktbl; + ray_t* key_cols[16]; + uint8_t nfs[16]; + for (uint32_t k = 0; k < n_sort; k++) { + key_cols[k] = topk_key_col(g, op, ext, ktbl, k); + nfs[k] = topk_key_nf(ext, k); + /* a short key: sel_compact's alloc fallback handed back the table */ + if (!key_cols[k] || key_cols[k]->len != pass) { ray_release(ktbl); return key_cols[k] ? ray_error("oom", NULL) : NULL; } + } + ray_t* idx = n_sort == 1 + ? topk_indices_single(key_cols[0], ext->sort.desc ? ext->sort.desc[0] : 0, nfs[0], pass, limit) + : topk_indices_cmp(key_cols, ext->sort.desc, nfs, (uint8_t)n_sort, pass, limit); + ray_release(ktbl); + if (!idx || RAY_IS_ERR(idx)) { /* unsupported, or the full sort reports it */ + if (idx) ray_error_free(idx); + return NULL; + } + /* the winners' source rows, ascending, through the selection's segments */ + const int64_t* pos = (const int64_t*)ray_data(idx); + ray_t* ph = NULL; + sel_late_pair_t* pr = (sel_late_pair_t*)scratch_alloc(&ph, (size_t)limit * sizeof(sel_late_pair_t)); + ray_t* rh = NULL; + int64_t* rows = (int64_t*)scratch_alloc(&rh, (size_t)limit * sizeof(int64_t)); + ray_t* perm = ray_vec_new(RAY_I64, limit); + if (!pr || !rows || !perm || RAY_IS_ERR(perm)) { + if (ph) scratch_free(ph); + if (rh) scratch_free(rh); + if (perm && !RAY_IS_ERR(perm)) ray_release(perm); + ray_release(idx); + return ray_error("oom", NULL); + } + for (int64_t i = 0; i < limit; i++) { pr[i].pos = pos[i]; pr[i].rank = i; } + ray_release(idx); + qsort(pr, (size_t)limit, sizeof *pr, sel_late_cmp); + const uint8_t* flags = ray_rowsel_flags(sel); + const uint32_t* offs = ray_rowsel_offsets(sel); + const uint16_t* sidx = ray_rowsel_idx(sel); + int64_t cum = 0, q = 0; + for (uint32_t seg = 0; seg < meta->n_segs && q < limit; seg++) { + if (flags[seg] == RAY_SEL_NONE) continue; + int64_t lo = (int64_t)seg * RAY_MORSEL_ELEMS; + int64_t cnt = flags[seg] == RAY_SEL_ALL ? (nrows - lo < RAY_MORSEL_ELEMS ? nrows - lo : RAY_MORSEL_ELEMS) + : (int64_t)offs[seg + 1] - (int64_t)offs[seg]; + for (; q < limit && pr[q].pos < cum + cnt; q++) { + int64_t l = pr[q].pos - cum; + rows[q] = lo + (flags[seg] == RAY_SEL_ALL ? l : (int64_t)sidx[offs[seg] + l]); + } + cum += cnt; + } + perm->len = limit; + int64_t* pm = (int64_t*)ray_data(perm); + for (int64_t i = 0; i < limit; i++) pm[pr[i].rank] = i; /* rank -> its row's place among the winners */ + scratch_free(ph); + ray_t* err = NULL; + if (q != limit) err = ray_error("corrupt", "sort: selection holds fewer rows than its %lld", (long long)pass); + ray_t* wsel = err ? NULL : sel_rows_rowsel(nrows, rows, limit); + scratch_free(rh); + if (!err && !wsel) err = ray_error("oom", NULL); + if (err) { ray_release(perm); return err; } + ray_t* wtbl = sel_compact(g, tbl, wsel, NULL, 0); + ray_rowsel_release(wsel); + if (!wtbl || RAY_IS_ERR(wtbl)) { ray_release(perm); return wtbl ? wtbl : ray_error("oom", NULL); } + if (ray_table_nrows(wtbl) != limit) { /* sel_compact's alloc fallback: the table itself */ + ray_release(wtbl); ray_release(perm); + return ray_error("oom", NULL); + } + ray_t* result = topk_gather_rows(wtbl, perm, limit); /* releases perm */ + ray_release(wtbl); + atomic_fetch_add_explicit(&g_late_heads, 1, memory_order_relaxed); + return result; +} + /* ── Builtins ── */ /* Shared eager kernel — called by the OP_ASC executor. */ @@ -4026,22 +4255,82 @@ ray_t* ray_rank_fn(ray_t* x) { * published through it; the dispatch barrier joins all tasks before return. */ typedef struct { ray_t** key_cols; + uint32_t** sym_ranks; /* lexical rank by raw intern ID, prepared before dispatch */ int64_t n_keys; uint8_t descending; _Atomic int* ordered; } sorted_check_ctx_t; +/* Unranked symbol keys are scanned serially; a rank budget refusal does + * not mean their lexical order is undecidable. Equal IDs need no lookup. */ +static int sorted_check_sym_cmp(const sorted_check_ctx_t* c, int64_t k, + int64_t ia, int64_t ib) { + if (ia == ib) return 0; + if (c->sym_ranks && c->sym_ranks[k]) + return (c->sym_ranks[k][ia] > c->sym_ranks[k][ib]) - + (c->sym_ranks[k][ia] < c->sym_ranks[k][ib]); + struct ray_sym_domain_s* dom = ray_sym_vec_domain(c->key_cols[k]); + ray_t* sa = ray_sym_domain_str(dom, ia); + ray_t* sb = ray_sym_domain_str(dom, ib); + uint32_t la = sa ? (uint32_t)ray_str_len(sa) : 0; + uint32_t lb = sb ? (uint32_t)ray_str_len(sb) : 0; + uint32_t ml = la < lb ? la : lb; + int cmp = ml ? memcmp(ray_str_ptr(sa), ray_str_ptr(sb), ml) : 0; + return cmp ? cmp : (la > lb) - (la < lb); +} + +/* Share the budgeted probe and worker scan at the secondary's physical + * width. TIME is int32_t; I64/TIMESTAMP are int64_t. Dispatch once outside + * rows; comparison budget is still spent only at unequal SYM boundaries. */ +#define SORTED_SYM_SECONDARY(lane_t) do { \ + int64_t comparisons = 0; \ + ray_t* sc = c->key_cols[0]; \ + const void* sd = ray_data(sc); \ + uint8_t sattrs = sc->attrs; \ + const lane_t* restrict tv = (const lane_t*)ray_data(c->key_cols[1]); \ + for (int64_t b = start; b < end; b += 4096) { \ + if (!atomic_load_explicit(c->ordered, memory_order_relaxed)) return false; \ + int64_t e = b + 4096 < end ? b + 4096 : end; \ + for (int64_t i = b; i < e; i++) { \ + int64_t ia = ray_read_sym(sd, i - 1, RAY_SYM, sattrs); \ + int64_t ib = ray_read_sym(sd, i, RAY_SYM, sattrs); \ + if (RAY_LIKELY(ia == ib)) { \ + if (tv[i] < tv[i - 1]) { atomic_store_explicit(c->ordered, 0, memory_order_relaxed); return false; } \ + } else { \ + int cmp = sorted_check_sym_cmp(c, 0, ia, ib); \ + if (cmp > 0) { atomic_store_explicit(c->ordered, 0, memory_order_relaxed); return false; } \ + if (next_row && ++comparisons >= RAY_MORSEL_ELEMS) { \ + *next_row = i + 1; \ + return true; \ + } \ + } \ + } \ + } \ + if (next_row) *next_row = end; \ + return true; \ +} while (0) + +static bool sorted_check_sym_numeric(sorted_check_ctx_t* c, int64_t start, + int64_t end, int64_t* next_row) { + if (c->key_cols[1]->type == RAY_TIME) + SORTED_SYM_SECONDARY(int32_t); + else + SORTED_SYM_SECONDARY(int64_t); +} +#undef SORTED_SYM_SECONDARY + static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; sorted_check_ctx_t* c = (sorted_check_ctx_t*)raw; if (start < 1) start = 1; - /* Specialized (SYM, i64-family) two-key loop — the canonical - * (sym, time) shape. The generic loop below pays a type-switch per - * read and an atomic flag load per row; here adjacent sym ids + /* Specialized (SYM, integer-secondary) two-key loop. The generic loop + * below pays a type-switch per read and an atomic flag load per row; + * here adjacent sym ids * compare directly (equal ids on ~all rows of a sorted table — the - * string comparison only runs at run boundaries), the secondary key - * reads raw i64, and the bail flag is polled per 4096-row block. + * lexical comparison only runs at run boundaries), the secondary key + * reads TIME as int32_t and I64/TIMESTAMP as int64_t, and the bail flag + * is polled per 4096-row block. * * Callers reach this only for null-free keys (ray_key_cols_sorted rejects * actual nulls up front, including for SYM). That is not squeamishness @@ -4054,31 +4343,7 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) c->key_cols[1]->type == RAY_TIME || c->key_cols[1]->type == RAY_TIMESTAMP) && !ray_vec_may_have_nulls(c->key_cols[1])) { - ray_t* sc = c->key_cols[0]; - const void* sd = ray_data(sc); - uint8_t sattrs = sc->attrs; - const int64_t* restrict tv = (const int64_t*)ray_data(c->key_cols[1]); - struct ray_sym_domain_s* dom = ray_sym_vec_domain(sc); - for (int64_t b = start; b < end; b += 4096) { - if (!atomic_load_explicit(c->ordered, memory_order_relaxed)) return; - int64_t e = b + 4096 < end ? b + 4096 : end; - for (int64_t i = b; i < e; i++) { - int64_t ia = ray_read_sym(sd, i - 1, RAY_SYM, sattrs); - int64_t ib = ray_read_sym(sd, i, RAY_SYM, sattrs); - if (RAY_LIKELY(ia == ib)) { - if (tv[i] < tv[i - 1]) { atomic_store_explicit(c->ordered, 0, memory_order_relaxed); return; } - } else { - ray_t* sa = ray_sym_domain_str(dom, ia); - ray_t* sb = ray_sym_domain_str(dom, ib); - uint32_t la = sa ? (uint32_t)ray_str_len(sa) : 0; - uint32_t lb = sb ? (uint32_t)ray_str_len(sb) : 0; - uint32_t ml = la < lb ? la : lb; - int cmp = ml ? memcmp(ray_str_ptr(sa), ray_str_ptr(sb), ml) : 0; - if (cmp == 0) cmp = (la > lb) - (la < lb); - if (cmp > 0) { atomic_store_explicit(c->ordered, 0, memory_order_relaxed); return; } - } - } - } + sorted_check_sym_numeric(c, start, end, NULL); return; } @@ -4091,14 +4356,7 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) int64_t ia = ray_read_sym(ray_data(col), i - 1, RAY_SYM, col->attrs); int64_t ib = ray_read_sym(ray_data(col), i, RAY_SYM, col->attrs); if (ia != ib) { - struct ray_sym_domain_s* dom = ray_sym_vec_domain(col); - ray_t* sa = ray_sym_domain_str(dom, ia); - ray_t* sb = ray_sym_domain_str(dom, ib); - uint32_t la = sa ? (uint32_t)ray_str_len(sa) : 0; - uint32_t lb = sb ? (uint32_t)ray_str_len(sb) : 0; - uint32_t ml = la < lb ? la : lb; - if (ml > 0) cmp = memcmp(ray_str_ptr(sa), ray_str_ptr(sb), ml); - if (cmp == 0) cmp = (la > lb) - (la < lb); + cmp = sorted_check_sym_cmp(c, k, ia, ib); } } else { int64_t va = read_col_i64(ray_data(col), i - 1, col->type, col->attrs); @@ -4110,6 +4368,90 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) } } +/* Preparation-only serial probe. Spend at most one morsel of actual + * symbol comparisons, rather than one morsel of rows. Equal IDs and keys + * bypassed by a preceding key's ordering consume no budget. Constant and + * low-transition inputs finish here without any rank preparation. */ +static bool sorted_check_probe(sorted_check_ctx_t* c, int64_t nrows, + int64_t* next_row) { + /* Probe and worker use the same width-correct ascending typed scan. */ + if (!c->descending && c->n_keys == 2 && + c->key_cols[0]->type == RAY_SYM && + (c->key_cols[1]->type == RAY_I64 || + c->key_cols[1]->type == RAY_TIME || + c->key_cols[1]->type == RAY_TIMESTAMP) && + !ray_vec_may_have_nulls(c->key_cols[1])) + return sorted_check_sym_numeric(c, 1, nrows, next_row); + int64_t comparisons = 0; + for (int64_t i = 1; i < nrows; i++) { + int cmp = 0; + for (int64_t k = 0; k < c->n_keys && cmp == 0; k++) { + ray_t* col = c->key_cols[k]; + if (col->type == RAY_SYM) { + int64_t ia = ray_read_sym(ray_data(col), i - 1, RAY_SYM, col->attrs); + int64_t ib = ray_read_sym(ray_data(col), i, RAY_SYM, col->attrs); + if (ia != ib) { + comparisons++; + cmp = sorted_check_sym_cmp(c, k, ia, ib); + } + } else { + int64_t va = read_col_i64(ray_data(col), i - 1, col->type, col->attrs); + int64_t vb = read_col_i64(ray_data(col), i, col->type, col->attrs); + cmp = (va > vb) - (va < vb); + } + } + if (c->descending ? cmp < 0 : cmp > 0) return false; + if (comparisons >= RAY_MORSEL_ELEMS) { + *next_row = i + 1; + return true; + } + } + *next_row = nrows; + return true; +} + +/* Only table scans large enough to use secondary workers prepare ranks, + * and only after the unranked probe exhausts its comparison budget. Small, + * serial and partition checks keep their cheap early-exit string scan. + * Prepared ranks are returned to the table caller, which either frees them + * on the sorted shortcut or lends them to the real sort after a late + * inversion. A density/OOM refusal retains serial lexical comparison. + * Optional rank/header arrays are caller-owned, zeroed heap storage; the + * partition caller supplies neither and needs no per-key rank buffers. */ +static bool sorted_check_run(ray_t** key_cols, int64_t n_keys, + uint8_t descending, int64_t nrows, + uint32_t** ranks, ray_t** rank_hdrs) { + if (nrows < 2) return true; + _Atomic int ordered = 1; + sorted_check_ctx_t sctx = { + .key_cols = key_cols, .sym_ranks = ranks, .n_keys = n_keys, + .descending = descending, .ordered = &ordered, + }; + ray_pool_t* pool = ray_pool_get(); + bool parallel = pool && ray_pool_total_workers(pool) > 1 && + nrows >= RAY_PARALLEL_THRESHOLD; + bool has_sym = false; + for (int64_t k = 0; k < n_keys; k++) + if (key_cols[k]->type == RAY_SYM) { has_sym = true; break; } + int64_t start = 1; + if (has_sym && ranks && rank_hdrs && parallel) { + if (!sorted_check_probe(&sctx, nrows, &start)) return false; + if (start == nrows) return true; + for (int64_t k = 0; k < n_keys; k++) { + if (key_cols[k]->type != RAY_SYM) continue; + ranks[k] = build_enum_rank(key_cols[k], nrows, &rank_hdrs[k]); + if (!ranks[k]) { parallel = false; break; } + } + } else if (has_sym) { + parallel = false; + } + if (parallel) + ray_pool_dispatch(pool, sorted_check_fn, &sctx, nrows); + else + sorted_check_fn(&sctx, 0, start, nrows); + return atomic_load_explicit(&ordered, memory_order_relaxed) != 0; +} + /* Public: are these key columns already in sorted order under the sort's * lexicographic ordering (single uniform direction across all keys)? Only * null-free integer-family / SYM keys are decidable — anything else (float, @@ -4130,7 +4472,8 @@ static void sorted_check_fn(void* raw, uint32_t wid, int64_t start, int64_t end) * asked for the other end. So the rejection is conservatism about the * requested placement, not an undecidable ordering — a caller that pins the * default could decide it. - * O(nrows) with early bail on the first violation; a 0/1-row column is + * O(nrows) with early bail on the first violation. Symbol keys use a serial + * string scan without domain-sized rank preparation. A 0/1-row column is * trivially sorted. Used by the parted ORDER BY streaming path in query.c * to verify each partition is internally sorted at O(partition), never a * full sort. */ @@ -4149,18 +4492,7 @@ bool ray_key_cols_sorted(ray_t** key_cols, int64_t n_keys, uint8_t descending, t != RAY_TIMESTAMP && t != RAY_SYM) return false; } - if (nrows < 2) return true; - _Atomic int ordered = 1; - sorted_check_ctx_t sctx = { - .key_cols = key_cols, .n_keys = n_keys, - .descending = descending, .ordered = &ordered, - }; - ray_pool_t* pool = ray_pool_get(); - if (pool && nrows >= RAY_PARALLEL_THRESHOLD) - ray_pool_dispatch(pool, sorted_check_fn, &sctx, nrows); - else - sorted_check_fn(&sctx, 0, 1, nrows); - return atomic_load_explicit(&ordered, memory_order_relaxed) != 0; + return sorted_check_run(key_cols, n_keys, descending, nrows, NULL, NULL); } static bool sort_part_key_type(int8_t t) { @@ -4219,7 +4551,10 @@ static ray_t* sort_stamp_ordered_table(ray_t* tbl, int64_t key_id, } for (int64_t c = 0; c < ncols; c++) { int64_t cn = ray_table_col_name(tbl, c); - ray_t* col = (cn == key_id) ? stamped : ray_table_get_col_idx(tbl, c); + ray_t* col = stamped; + if (cn != key_id) { + col = ray_table_slot_idx(tbl, c); + } out = ray_table_add_col(out, cn, col); if (!out || RAY_IS_ERR(out)) { ray_release(stamped); @@ -4251,16 +4586,20 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { if (n_keys == 0) { ray_retain(tbl); return tbl; } - /* Exact-size carve for the key ids, resolved key columns and per-key - * descending flags: one block, the two 8-byte arrays (key_ids, - * key_cols) followed by the descs bytes. Unbounded key count; freed - * at every exit below. */ + /* Exact-size heap carve: ids, columns, optional rank pointers/headers, + * then descending bytes. Key counts are unbounded, including repeated + * names, so no per-key arrays may live on the stack. Freed on every exit. */ + const size_t per_key = sizeof(int64_t) + sizeof(ray_t*) + + sizeof(uint32_t*) + sizeof(ray_t*) + sizeof(uint8_t); + if ((uint64_t)n_keys > SIZE_MAX / per_key) + return ray_error("limit", "xasc/xdesc: too many sort keys"); ray_t* k_hdr; - int64_t* key_ids = (int64_t*)scratch_alloc(&k_hdr, - (size_t)n_keys * (sizeof(int64_t) + sizeof(ray_t*) + sizeof(uint8_t))); + int64_t* key_ids = (int64_t*)scratch_calloc(&k_hdr, (size_t)n_keys * per_key); if (!key_ids) return ray_error("oom", NULL); ray_t** key_cols = (ray_t**)(key_ids + n_keys); - uint8_t* descs = (uint8_t*)(key_cols + n_keys); + uint32_t** prepared_ranks = (uint32_t**)(key_cols + n_keys); + ray_t** prepared_hdrs = (ray_t**)(prepared_ranks + n_keys); + uint8_t* descs = (uint8_t*)(prepared_hdrs + n_keys); if (keys->type == -RAY_SYM) { /* Single symbol atom */ @@ -4286,7 +4625,12 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { /* Resolve key columns */ for (int64_t i = 0; i < n_keys; i++) { - key_cols[i] = ray_table_get_col(tbl, key_ids[i]); + key_cols[i] = ray_table_col(tbl, key_ids[i]); + if (key_cols[i] && RAY_IS_ERR(key_cols[i])) { + ray_t* err = key_cols[i]; + scratch_free(k_hdr); + return err; + } if (!key_cols[i]) { scratch_free(k_hdr); return ray_error("domain", "xasc/xdesc: key column not found in table"); @@ -4305,8 +4649,9 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { * input retained: the sort, the whole-table gather and the null/attr * propagation all vanish. Restricted to null-free integer-family and * SYM keys: null placement and float NaN ordering belong to the real - * sort. An unsorted input bails at its first violation, so the scan - * costs a few comparisons, not O(n). */ + * sort. A bounded-comparison serial probe rejects common unsorted inputs + * and finishes low-transition inputs without rank setup. Late inversions + * after rank setup reuse prepared ranks in the real sort. */ { bool detectable = true; for (int64_t k = 0; k < n_keys && detectable; k++) { @@ -4318,20 +4663,12 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { detectable = false; } if (detectable) { - _Atomic int ordered = 1; - sorted_check_ctx_t sctx = { - .key_cols = key_cols, .n_keys = n_keys, - .descending = descending, .ordered = &ordered, - }; - ray_pool_t* pool = ray_pool_get(); - if (pool && nrows >= RAY_PARALLEL_THRESHOLD) - ray_pool_dispatch(pool, sorted_check_fn, &sctx, nrows); - else - sorted_check_fn(&sctx, 0, 1, nrows); - if (atomic_load_explicit(&ordered, memory_order_relaxed)) { + if (sorted_check_run(key_cols, n_keys, descending, nrows, + prepared_ranks, prepared_hdrs)) { ray_t* out = (descending || n_keys <= 1) ? NULL : sort_stamp_ordered_table(tbl, key_ids[0], key_cols[0], n_keys > 1 ? key_ids[1] : -1); + for (int64_t k = 0; k < n_keys; k++) scratch_free(prepared_hdrs[k]); scratch_free(k_hdr); if (out) return out; ray_retain(tbl); @@ -4343,7 +4680,8 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { uint64_t* sorted_keys = NULL; ray_t* sorted_keys_hdr = NULL; ray_t* idx = sort_indices_ex(key_cols, descs, NULL, n_keys, nrows, - &sorted_keys, &sorted_keys_hdr); + &sorted_keys, &sorted_keys_hdr, prepared_ranks); + for (int64_t k = 0; k < n_keys; k++) scratch_free(prepared_hdrs[k]); if (RAY_IS_ERR(idx)) { if (sorted_keys_hdr) scratch_free(sorted_keys_hdr); scratch_free(k_hdr); @@ -4368,7 +4706,8 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { ray_t* nc_hdr = NULL; ray_t** new_cols = (ray_t**)scratch_alloc(&nc_hdr, - (size_t)ncols * sizeof(ray_t*)); + (size_t)ncols * 2 * sizeof(ray_t*)); + ray_t** src_cols = new_cols ? new_cols + ncols : NULL; /* borrowed plain sources */ ray_t* cn_hdr = NULL; int64_t* col_names = (int64_t*)scratch_alloc(&cn_hdr, (size_t)ncols * sizeof(int64_t)); @@ -4380,11 +4719,22 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { ray_release(idx); return ray_error("oom", NULL); } - for (int64_t c = 0; c < ncols; c++) new_cols[c] = NULL; + for (int64_t c = 0; c < ncols; c++) { new_cols[c] = NULL; src_cols[c] = NULL; } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_col_idx(tbl, c); col_names[c] = ray_table_col_name(tbl, c); + src_cols[c] = col; + if (col && RAY_IS_ERR(col)) { + for (int64_t j = 0; j < c; j++) + if (new_cols[j]) ray_release(new_cols[j]); + scratch_free(nc_hdr); + scratch_free(cn_hdr); + if (sorted_keys_hdr) scratch_free(sorted_keys_hdr); + scratch_free(k_hdr); + ray_release(idx); + return col; + } if (!col) continue; ray_t* nc; if (col->type == RAY_LIST) @@ -4452,7 +4802,7 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { int64_t g_nc = 0; for (; base < ncols && g_nc < MGATHER_MAX_COLS; base++) { if (!new_cols[base] || base == decode_col_idx) continue; - ray_t* col = ray_table_get_col_idx(tbl, base); + ray_t* col = src_cols[base]; if (col->type == RAY_LIST) continue; g_srcs[g_nc] = (char*)ray_data(col); g_dsts[g_nc] = (char*)ray_data(new_cols[base]); @@ -4483,7 +4833,7 @@ ray_t* sort_table_by_keys(ray_t* tbl, ray_t* keys, uint8_t descending) { * gather_by_idx. */ for (int64_t c = 0; c < ncols; c++) { if (!new_cols[c]) continue; - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = src_cols[c]; if (!col) continue; col_propagate_str_pool(new_cols[c], col); bool src_has_nulls = ray_vec_may_have_nulls(col); diff --git a/src/ops/strdom.c b/src/ops/strdom.c new file mode 100644 index 000000000..bba18a680 --- /dev/null +++ b/src/ops/strdom.c @@ -0,0 +1,416 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "ops/strdom.h" +#include "ops/rowsel.h" +#include "ops/idxop.h" /* RAY_IDX_DICT: a segment's persisted DICT */ +#include "store/enccol.h" +#include "store/encfmt.h" +#include "vec/str.h" + +#include +#include + +/* Open addressing over the interned strings, at most half full. A slot + * holds 0 (empty) or the id + 1 in its low 40 bits under a 24-bit tag from + * the hash's top bits, so a probe compares the tag before it loads the + * entry. Entries {offset into the arena, len}; the full hashes are kept + * apart, for the rehash. */ +#define SD_ID_BITS 40 +#define SD_ID_MASK (((uint64_t)1 << SD_ID_BITS) - 1) +typedef struct { uint32_t off, len; } sd_ent_t; +struct ray_strdom_s { + char* arena; + size_t used, cap; /* arena bytes; cap <= UINT32_MAX */ + sd_ent_t* ent; + uint64_t* hash; + int64_t n, ecap; /* entries; n <= UINT32_MAX + 1 (one empty string) */ + uint64_t* slots; + uint64_t mask; /* slots - 1 */ +}; + +static inline uint64_t sd_tag(uint64_t h) { return h >> SD_ID_BITS; } + +int64_t ray_strdom_count(const ray_strdom_t* d) { return d ? d->n : 0; } + +void ray_strdom_free(ray_strdom_t* d) { + if (!d) return; + ray_free_raw(d->arena); ray_free_raw(d->ent); ray_free_raw(d->hash); + ray_free_raw(d->slots); + ray_free_raw(d); +} + +static ray_t* sd_rehash(ray_strdom_t* d, uint64_t nslots) { + uint64_t* s = (uint64_t*)ray_calloc_raw((size_t)nslots * sizeof(uint64_t)); + if (!s) return ray_error("oom", NULL); + uint64_t m = nslots - 1; + for (int64_t i = 0; i < d->n; i++) { + uint64_t p = d->hash[i] & m; + while (s[p]) p = (p + 1) & m; + s[p] = (sd_tag(d->hash[i]) << SD_ID_BITS) | (uint64_t)(i + 1); + } + ray_free_raw(d->slots); + d->slots = s; d->mask = m; + return NULL; +} + +/* The id of the bytes [p, p + n) with hash h, interned when new. */ +static ray_t* sd_intern(ray_strdom_t* d, const char* p, uint32_t n, uint64_t h, int64_t* id) { + uint64_t q = h & d->mask, tag = sd_tag(h); + for (uint64_t s; (s = d->slots[q]) != 0; q = (q + 1) & d->mask) { + if ((s >> SD_ID_BITS) != tag) continue; + int64_t i = (int64_t)(s & SD_ID_MASK) - 1; + if (d->ent[i].len == n && (n == 0 || memcmp(d->arena + d->ent[i].off, p, n) == 0)) { *id = i; return NULL; } + } + if (d->used + n > UINT32_MAX) + return ray_error("range", "string domain: more than %u bytes of distinct strings", UINT32_MAX); + if (d->used + n > d->cap) { + size_t c = d->cap ? d->cap : 4096; + while (c < d->used + n) c *= 2; + if (c > UINT32_MAX) c = UINT32_MAX; + char* a = (char*)ray_realloc_raw(d->arena, c); + if (!a) return ray_error("oom", NULL); + d->arena = a; d->cap = c; + } + if (d->n == d->ecap) { + int64_t c = d->ecap ? d->ecap * 2 : 256; + sd_ent_t* ee = (sd_ent_t*)ray_realloc_raw(d->ent, (size_t)c * sizeof(sd_ent_t)); + if (!ee) return ray_error("oom", NULL); + d->ent = ee; + uint64_t* hh = (uint64_t*)ray_realloc_raw(d->hash, (size_t)c * sizeof(uint64_t)); + if (!hh) return ray_error("oom", NULL); + d->hash = hh; + d->ecap = c; + } + int64_t i = d->n++; + if (n) memcpy(d->arena + d->used, p, n); + d->ent[i].off = (uint32_t)d->used; d->ent[i].len = n; + d->hash[i] = h; + d->used += n; + d->slots[q] = (tag << SD_ID_BITS) | (uint64_t)(i + 1); + *id = i; + if ((uint64_t)d->n * 2 > d->mask + 1) return sd_rehash(d, (d->mask + 1) * 2); + return NULL; +} + +/* One build: the domain, the source's cursor, the destination parts, the + * last string interned (consecutive rows repeat one often: a CONST vector + * is one) and the source's segments (a parted source's, else the source + * itself as one). A segment that is a single-file encoded column (not + * synthetic, not materialized) with a STR_DICT entry reads its STR_DICT + * vectors as views: each code maps to its id through the segment's remap, + * filled on the code's first occurrence among the rows read. A segment + * recording a persisted DICT (P6b) takes precedence: its codes are read by + * range (one call per vector piece), materialized or not, and mapped the + * same way. Codes are segment-local: a remap lives while its segment is + * read. */ +typedef struct { + ray_strdom_t* d; + ray_col_cursor_t cur; + int64_t n_parts; + const int64_t* part_off; + int64_t* const* part_dst; + int64_t p; /* the part holding the current row */ + const char* lp; + uint32_t ln; + int64_t lid; + int64_t n_segs; + ray_t* const* segv; /* borrowed */ + const int64_t* seg_off; /* n_segs + 1 */ + int64_t sg; /* the current segment, -1 before the first */ + ray_enccol_t* se; /* its codes column (with a STR_DICT entry), else NULL */ + const ray_enc_sdict_t* sdict; + const ray_enc_idict_t* dd; /* the current segment's persisted DICT, else NULL */ + int64_t* remap; /* sdict->n (dd->n_distinct) ids, -1 unseen; allocated on first use */ + ray_enc_vview_t* vv; /* the build's view (on the builder's stack) */ + int64_t vv_at; /* the segment-local vector vv describes, -1 none */ + bool vv_codes; /* vv_at is a STR_DICT view (else read by range) */ +} sd_build_t; + +/* Row r's id slot; r moves forward, or back inside a morsel (its + * unselected rows are zeroed before its selected ones are read). */ +static inline int64_t* sd_slot(sd_build_t* b, int64_t r) { + while (r < b->part_off[b->p]) b->p--; + while (r >= b->part_off[b->p + 1]) b->p++; + return &b->part_dst[b->p][r - b->part_off[b->p]]; +} + +/* A segment's codes column: single-file encoded, not synthetic, and + * either recording a persisted DICT (its codes read the mapping, not the + * decoded column) or without a published materialization (read by range + * otherwise). */ +static ray_enccol_t* sd_codes_col(ray_t* o) { + if (!o || o->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e = ray_enccol_of(o); + if (!e || e->kind != RAY_ENCCOL_SINGLE || e->synthetic) return NULL; + if (e->hdr.index_kind != RAY_IDX_DICT && ray_enccol_decoded_peek(o)) return NULL; + return e; +} + +/* Make the segment holding row r current: a new segment drops the last + * one's remap and view and looks up its own dictionary. */ +static ray_t* sd_seg(sd_build_t* b, int64_t r) { + int64_t s = b->sg < 0 ? 0 : b->sg; + while (s > 0 && r < b->seg_off[s]) s--; + while (s + 1 < b->n_segs && r >= b->seg_off[s + 1]) s++; + if (s == b->sg) return NULL; + ray_free_raw(b->remap); + b->remap = NULL; b->se = NULL; b->sdict = NULL; b->dd = NULL; b->vv_at = -1; b->sg = s; + ray_enccol_t* e = sd_codes_col(b->segv[s]); + if (!e) return NULL; + const ray_enc_idict_t* dd = NULL; + ray_t* err = ray_enccol_idict(e, &dd); + if (err) return err; + if (dd) { + b->se = e; b->dd = dd; + b->remap = ray_enccol_test_nth_alloc_fails() ? NULL /* the materialization fail hook */ + : (int64_t*)ray_alloc_raw((size_t)dd->n_distinct * sizeof(int64_t)); + if (!b->remap) return ray_error("oom", NULL); + for (int64_t k = 0; k < dd->n_distinct; k++) b->remap[k] = -1; + return NULL; + } + if (ray_enccol_decoded_peek(b->segv[s])) return NULL; /* materialized: read by range */ + const ray_enc_sdict_t* sd = NULL; + err = ray_enccol_strdict(e, &sd); + if (err) return err; + if (sd) { b->se = e; b->sdict = sd; } + return NULL; +} + +/* Is segment-local vector v of the current segment a STR_DICT view (vv)? + * 1 yes, 0 no (read it by range: another encoding, or a declined view, + * which the range read decodes), -1 an owned *err. */ +static int sd_view(sd_build_t* b, int64_t v, int64_t vrows, ray_t** err) { + if (b->vv_at == v) return b->vv_codes; + b->vv_at = -1; + const ray_enc_desc_t* d = ray_enccol_descs(b->se, v / RAY_ENC_VECS_PER_CHUNK); + int got = 0; + if (d[v % RAY_ENC_VECS_PER_CHUNK].encoding == RAY_ENC_STR_DICT) { + got = ray_enccol_vview(b->se, v, b->vv, err); + if (got < 0) return -1; + if (got > 0 && b->vv->enc != RAY_ENC_STR_DICT) got = 0; + /* an invariant check, not a validation: the view's row count and + * entry count come from the same descriptors and dictionary as + * vrows and b->sdict, so this cannot fire on any file */ + if (got > 0 && (b->vv->n != vrows || b->vv->dict_n != b->sdict->n)) { + *err = ray_error("corrupt", "column %s: string domain: vector %lld holds %d rows of %u entries", + b->se->path, (long long)v, b->vv->n, b->vv->dict_n); + return -1; + } + if (got > 0 && !b->remap) { + b->remap = ray_enccol_test_nth_alloc_fails() ? NULL /* the materialization fail hook */ + : (int64_t*)ray_alloc_raw((size_t)(b->sdict->n ? b->sdict->n : 1) * sizeof(int64_t)); + if (!b->remap) { *err = ray_error("oom", NULL); return -1; } + for (uint32_t k = 0; k < b->sdict->n; k++) b->remap[k] = -1; + } + } + b->vv_at = v; b->vv_codes = got > 0; + return b->vv_codes; +} + +/* Intern rows [lo, hi) (idx NULL) or rows lo + idx[0..n_idx) (ascending). */ +static ray_t* sd_rows(sd_build_t* b, int64_t lo, int64_t hi, const uint16_t* idx, int64_t n_idx) { + int64_t j = 0; + for (int64_t r = idx ? lo + idx[0] : lo; idx ? j < n_idx : r < hi; ) { + ray_t* err = b->segv ? sd_seg(b, r) : NULL; + if (err) return err; + if (b->dd) { + /* a DICT segment: the codes of the vector piece holding r, by + * range (each checked below n_distinct), through the remap */ + const int64_t base = b->seg_off[b->sg], v = (r - base) / RAY_ENC_VEC; + const int64_t v0 = base + v * RAY_ENC_VEC; + int64_t vend = v0 + RAY_ENC_VEC; + if (vend > b->seg_off[b->sg + 1]) vend = b->seg_off[b->sg + 1]; + const int32_t* cd = NULL; + err = ray_enccol_idict_codes(b->se, v0 - base, vend - v0, &cd); + if (err) return err; + for (; r < vend; ) { + const int32_t c = cd[r - v0]; + int64_t id = b->remap[c]; + if (id < 0) { + const char* p; uint32_t n; + ray_enc_sdict_entry(b->dd->ent, (uint32_t)c, &p, &n); + err = sd_intern(b->d, p, n, ray_str_bytes_hash(p, n), &id); + if (err) return err; + b->remap[c] = id; + /* the arena may have moved: the last string is this one */ + b->lid = id; b->ln = n; b->lp = n ? b->d->arena + b->d->ent[id].off : p; /* "": maybe no arena yet */ + } + *sd_slot(b, r) = id; + if (idx) { if (++j >= n_idx) return NULL; r = lo + idx[j]; } + else if (++r >= hi) return NULL; + } + continue; + } + if (b->se) { + const int64_t base = b->seg_off[b->sg], v = (r - base) / RAY_ENC_VEC; + int64_t vend = base + (v + 1) * RAY_ENC_VEC; + if (vend > b->seg_off[b->sg + 1]) vend = b->seg_off[b->sg + 1]; + const int got = sd_view(b, v, vend - base - v * RAY_ENC_VEC, &err); + if (got < 0) return err; + if (got) { + /* codes through the segment's remap: every row of the + * vector read (without idx) or the selected ones */ + const int64_t v0 = base + v * RAY_ENC_VEC; + const uint32_t* cd = b->vv->codes; + const ray_enc_sdict_t* sd = b->sdict; + for (; r < vend; ) { + const uint32_t k = cd[r - v0]; + int64_t id = b->remap[k]; + if (id < 0) { + const char* p; uint32_t n; + ray_enc_sdict_entry(sd, k, &p, &n); + err = sd_intern(b->d, p, n, ray_str_bytes_hash(p, n), &id); + if (err) return err; + b->remap[k] = id; + /* the arena may have moved: the last string is this one */ + b->lid = id; b->ln = n; b->lp = n ? b->d->arena + b->d->ent[id].off : p; /* "": maybe no arena yet */ + } + *sd_slot(b, r) = id; + if (idx) { if (++j >= n_idx) return NULL; r = lo + idx[j]; } + else if (++r >= hi) return NULL; + } + continue; + } + } + const ray_col_range_t* v; + err = ray_col_cursor_at(&b->cur, r, &v); + if (err) return err; + const ray_str_t* s = (const ray_str_t*)v->data; + int64_t vend = v->start + v->n; + for (; r < vend; ) { + const ray_str_t* e = &s[r - v->start]; + uint32_t n = e->len; + const char* p = n ? ray_str_t_ptr(e, v->str_pool) : ""; + int64_t id = 0; + if (b->lid >= 0 && n == b->ln && memcmp(p, b->lp, n) == 0) id = b->lid; + else { + err = sd_intern(b->d, p, n, ray_str_t_hash(e, v->str_pool), &id); + if (err) return err; + b->lid = id; b->ln = n; b->lp = n ? b->d->arena + b->d->ent[id].off : p; /* "": maybe no arena yet */ + } + *sd_slot(b, r) = id; + if (idx) { if (++j >= n_idx) return NULL; r = lo + idx[j]; } + else if (++r >= hi) return NULL; + } + } + return NULL; +} + +ray_t* ray_strdom_build_parts(ray_col_src_t* src, ray_t* sel, int64_t n_parts, const int64_t* part_off, + int64_t* const* part_dst, ray_strdom_t** dom_out) { + *dom_out = NULL; + if (!src || !src->obj || src->type != RAY_STR) + return ray_error("type", "string domain: not a STR source"); + int64_t len = src->len; + if (n_parts < 0 || (n_parts == 0 ? len != 0 : (part_off[0] != 0 || part_off[n_parts] != len))) + return ray_error("range", "string domain: parts do not cover the source"); + if (sel && ray_rowsel_meta(sel)->nrows != len) sel = NULL; /* not this source's: read every row */ + sd_build_t b; + memset(&b, 0, sizeof b); + b.d = (ray_strdom_t*)ray_calloc_raw(sizeof *b.d); + if (!b.d) return ray_error("oom", NULL); + ray_t* err = sd_rehash(b.d, 1024); + if (err) { ray_strdom_free(b.d); return err; } + b.n_parts = n_parts; b.part_off = part_off; b.part_dst = part_dst; b.lid = -1; + /* the segments: a parted source's, else the source as one */ + ray_enc_vview_t vv; /* about 21 KB: on the stack (P3 rule) */ + int64_t one_off[2] = { 0, len }; + b.vv = &vv; b.sg = -1; b.vv_at = -1; + if (src->parted) { + ray_t** segs = NULL; const int64_t* off = NULL; int64_t ns = 0; + if (!ray_col_src_parted_segs(src, &ns, &segs, &off, &err)) { + ray_strdom_free(b.d); + return err ? err : ray_error("type", "string domain: parted source without segments"); + } + if (ns > 0 && off[ns] == len) { b.n_segs = ns; b.segv = segs; b.seg_off = off; } + } else if (len > 0) { + b.n_segs = 1; b.segv = &src->obj; b.seg_off = one_off; + } + /* Serial, each vector read decoded once into a stack vector: the + * interning is the walk's shared state. */ + ray_col_fixed_t fixed; + ray_col_cursor_init_lent(&b.cur, src, &fixed); + if (!sel) err = len > 0 ? sd_rows(&b, 0, len, NULL, 0) : NULL; + else { + /* the selected rows only, by morsel: the ids are first-occurrence + * over the selection; an unselected row (never grouped) gets 0 and + * a vector holding none is never read */ + const uint8_t* fl = ray_rowsel_flags(sel); + const uint32_t* so = ray_rowsel_offsets(sel); + const uint16_t* ix = ray_rowsel_idx(sel); + uint32_t ns = ray_rowsel_meta(sel)->n_segs; + for (uint32_t m = 0; m < ns && !err; m++) { + int64_t lo = (int64_t)m * RAY_MORSEL_ELEMS; + int64_t hi = lo + RAY_MORSEL_ELEMS < len ? lo + RAY_MORSEL_ELEMS : len; + if (fl[m] != RAY_SEL_ALL) + for (int64_t r = lo; r < hi; r++) *sd_slot(&b, r) = 0; + if (fl[m] == RAY_SEL_ALL) err = sd_rows(&b, lo, hi, NULL, 0); + else if (fl[m] == RAY_SEL_MIX && so[m + 1] > so[m]) + err = sd_rows(&b, lo, hi, ix + so[m], (int64_t)(so[m + 1] - so[m])); + } + } + ray_col_cursor_free(&b.cur); + ray_free_raw(b.remap); + if (err) { ray_strdom_free(b.d); return err; } + *dom_out = b.d; + return NULL; +} + +ray_t* ray_strdom_build(ray_col_src_t* src, ray_strdom_t** dom_out, ray_t** ids_out) { + *dom_out = NULL; *ids_out = NULL; + if (!src || !src->obj || src->type != RAY_STR) + return ray_error("type", "string domain: not a STR source"); + int64_t len = src->len; + ray_t* ids = ray_vec_new(RAY_I64, len > 0 ? len : 1); + if (!ids || RAY_IS_ERR(ids)) return ids ? ids : ray_error("oom", NULL); + ids->len = len; + int64_t off[2] = { 0, len }; + int64_t* dst[1] = { (int64_t*)ray_data(ids) }; + ray_t* err = ray_strdom_build_parts(src, NULL, 1, off, dst, dom_out); + if (err) { ray_release(ids); return err; } + *ids_out = ids; + return NULL; +} + +ray_t* ray_strdom_emit(const ray_strdom_t* d, const int64_t* ids, int64_t n, ray_t** out) { + *out = NULL; + if (n <= 0) { + ray_t* v = ray_vec_new(RAY_STR, 1); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + *out = v; return NULL; + } + const char** ptrs = (const char**)ray_alloc_raw((size_t)n * sizeof(const char*)); + uint32_t* lens = (uint32_t*)ray_alloc_raw((size_t)n * sizeof(uint32_t)); + if (!ptrs || !lens) { ray_free_raw(ptrs); ray_free_raw(lens); return ray_error("oom", NULL); } + for (int64_t i = 0; i < n; i++) { + int64_t id = ids[i]; + if (id < 0 || id >= d->n) { ptrs[i] = ""; lens[i] = 0; } + else { lens[i] = d->ent[id].len; ptrs[i] = lens[i] ? d->arena + d->ent[id].off : ""; } + } + ray_t* v = ray_str_vec_from_parts(ptrs, lens, NULL, n); + ray_free_raw(ptrs); ray_free_raw(lens); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + *out = v; + return NULL; +} diff --git a/src/ops/strdom.h b/src/ops/strdom.h new file mode 100644 index 000000000..1e6f0587e --- /dev/null +++ b/src/ops/strdom.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_OPS_STRDOM_H +#define RAY_OPS_STRDOM_H + +/* A query-wide string domain: the distinct strings of a STR column, interned + * while it is read by range, each with a dense id. A group-by keys a + * generation-2 STR column on the ids (an I64 key column built for the query) + * and emits the groups' strings from the domain, so the column is never + * materialized. Ids are assigned in first-occurrence order over the rows + * read (the selected rows, under a selection): a route emitting groups in + * first-occurrence order or in id order emits them in the order generation + * 0's STR key gives. "" is the STR null (its canonical empty payload): + * null and "" rows share one id. */ + +#include +#include "store/colrange.h" + +typedef struct ray_strdom_s ray_strdom_t; +/* Intern every value of a STR source into a new query-wide domain, writing + * each row's id (nulls: the id of the empty string) into an I64 vector. + * Reads the source by range; never materializes it. The domain grows only + * from the bytes read (its arena is bounded by UINT32_MAX: `range` past it); + * the id vector is sized by the source's row count. NULL with *dom_out and + * *ids_out owned, or an owned error with both NULL. */ +ray_t* ray_strdom_build(ray_col_src_t* src, ray_strdom_t** dom_out, ray_t** ids_out); +/* ray_strdom_build reading only the rows `sel` selects (a ray_rowsel over + * the source's rows; NULL, or one over another row count: every row), the + * ids written into caller parts: rows [part_off[i], part_off[i + 1]) into + * part_dst[i] (NULL only for an empty part), part_off[0] == 0 and + * part_off[n_parts] the source's rows. An unselected row's id is 0 (it is + * never grouped). NULL with *dom_out owned, or an owned error. */ +ray_t* ray_strdom_build_parts(ray_col_src_t* src, ray_t* sel, int64_t n_parts, const int64_t* part_off, + int64_t* const* part_dst, ray_strdom_t** dom_out); +/* The strings of ids[0..n) as a new STR vector (the group keys' output); an + * id outside the domain (none a group emits) reads as "". NULL with *out + * owned, or an owned error with *out NULL. */ +ray_t* ray_strdom_emit(const ray_strdom_t* d, const int64_t* ids, int64_t n, ray_t** out); +int64_t ray_strdom_count(const ray_strdom_t* d); +void ray_strdom_free(ray_strdom_t* d); + +#endif /* RAY_OPS_STRDOM_H */ diff --git a/src/ops/string.c b/src/ops/string.c index 73bd2792b..bddc121d0 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -359,10 +359,14 @@ static ray_t* exec_like_input(ray_graph_t* g, ray_op_t* input_op) { scan_tbl = g->table; if (!scan_tbl) return exec_node(g, input_op); - ray_t* col = ray_table_get_col(scan_tbl, ext->sym); + ray_col_meta_t cm; + if (!ray_table_col_meta(scan_tbl, ext->sym, &cm) || !RAY_IS_PARTED(cm.type)) + return exec_node(g, input_op); + ray_t* col = ray_table_col(scan_tbl, ext->sym); + if (col && RAY_IS_ERR(col)) return col; if (!col) return exec_node(g, input_op); - if (RAY_IS_PARTED(col->type)) { - int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); + { + int8_t base = (int8_t)RAY_PARTED_BASETYPE(cm.type); if (base == RAY_STR || RAY_IS_SYM(base)) { ray_retain(col); return col; @@ -777,9 +781,8 @@ static void strlen_sym_task(void* vctx, uint32_t worker_id, int64_t lo, int64_t if (ray_vec_is_null(input, i)) { c->dst[i] = NULL_I64; any_null = true; continue; } int64_t sid = ray_read_sym(base, i, input->type, input->attrs); if (c->raw_ok && sid >= 0 && sid < c->raw.count) { - size_t sl; - (void)ray_sym_domain_raw_str(&c->raw, sid, &sl); - c->dst[i] = (int64_t)sl; + int64_t sl = ray_sym_domain_raw_len(&c->raw, sid); + c->dst[i] = sl < 0 ? 0 : sl; } else { const char* sp; size_t sl; sym_elem(input, i, &sp, &sl); diff --git a/src/ops/strop.c b/src/ops/strop.c index 3aba16454..10a115995 100644 --- a/src/ops/strop.c +++ b/src/ops/strop.c @@ -257,6 +257,8 @@ static ray_t* string_unary_fn(ray_t* x, uint16_t opcode, ray_op_t* (*ctor)(ray_graph_t*, ray_op_t*)) { if (!x || RAY_IS_ERR(x)) return x; if (ray_is_lazy(x)) { + ray_t* perr = ray_lazy_promote(x); /* a column reference becomes its scan */ + if (perr) return perr; ray_op_t* prev = RAY_LAZY_OP(x); if (!prev || (prev->out_type != RAY_STR && prev->out_type != RAY_SYM)) return ray_error("type", "string transform: expected string or symbol vector"); @@ -348,6 +350,8 @@ ray_t* ray_substr_fn(ray_t** args, int64_t n) { return ray_error("type", "substr: length must be an integer atom or I64/I32 vector"); if (ray_is_lazy(str)) { + ray_t* perr = ray_lazy_promote(str); /* a column reference becomes its scan */ + if (perr) return perr; ray_graph_t* g = RAY_LAZY_GRAPH(str); ray_op_t* prev = RAY_LAZY_OP(str); if (!prev || (prev->out_type != RAY_STR && prev->out_type != RAY_SYM)) @@ -445,6 +449,8 @@ ray_t* ray_replace_fn(ray_t** args, int64_t n) { return ray_error("type", "replace: to must be string or symbol atom"); if (ray_is_lazy(str)) { + ray_t* perr = ray_lazy_promote(str); /* a column reference becomes its scan */ + if (perr) return perr; ray_graph_t* g = RAY_LAZY_GRAPH(str); ray_op_t* prev = RAY_LAZY_OP(str); if (!prev || (prev->out_type != RAY_STR && prev->out_type != RAY_SYM)) @@ -585,6 +591,8 @@ ray_t* ray_str_find_fn(ray_t* hay, ray_t* pattern) { return ray_error("domain", "str-find: '*' is not supported in search patterns"); if (ray_is_lazy(hay)) { + ray_t* perr = ray_lazy_promote(hay); /* a column reference becomes its scan */ + if (perr) return perr; ray_graph_t* g = RAY_LAZY_GRAPH(hay); ray_op_t* prev = RAY_LAZY_OP(hay); if (!prev || (prev->out_type != RAY_STR && prev->out_type != RAY_SYM)) @@ -870,8 +878,16 @@ ray_t* ray_split_fn(ray_t* str, ray_t* delim) { ray_t* result = ray_list_new(8); if (RAY_IS_ERR(result)) { if (sym_str_s) ray_release(sym_str_s); if (sym_str_d) ray_release(sym_str_d); return result; } - if (dlen == 0 || slen == 0) { + /* A longer delimiter cannot occur in the input. Guard the unsigned + * slen - dlen bound in the search loop below. */ + if (dlen == 0 || slen < dlen) { ray_t* part = ray_str(sp, slen); + if (!part || RAY_IS_ERR(part)) { + ray_release(result); + if (sym_str_s) ray_release(sym_str_s); + if (sym_str_d) ray_release(sym_str_d); + return part ? part : ray_error("oom", NULL); + } result = ray_list_append(result, part); ray_release(part); if (sym_str_s) ray_release(sym_str_s); diff --git a/src/ops/system.c b/src/ops/system.c index 46e35fb73..43f09f245 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -41,12 +41,14 @@ #include "core/qmeasure.h" /* shared per-query measurement lifecycle */ #include "core/qlog.h" /* g_qlog — (.sys.querylog) */ #include "store/serde.h" +#include "store/enccol.h" #include "store/splay.h" #include "store/part.h" #include "core/ipc.h" #include "core/mcast.h" #include "core/poll.h" #include "core/timer.h" +#include "core/pool.h" /* ray_pool_get — the pool size in .sys.info */ /* Forward decls: keep this TU decoupled from core/runtime.h — only * the opaque accessors are needed. */ @@ -71,8 +73,8 @@ void* ray_runtime_get_sys_args(void); #define RAY_PCLOSE(f) _pclose(f) #endif -static int parse_sys_int_arg(const char* s, bool nonnegative, bool core_count, - int64_t* out) { +int parse_sys_int_arg(const char* s, bool nonnegative, bool core_count, + int64_t* out) { if (!s || !*s) return 0; const unsigned char* p = (const unsigned char*)s; if (!nonnegative && (*p == '+' || *p == '-')) p++; @@ -84,7 +86,8 @@ static int parse_sys_int_arg(const char* s, bool nonnegative, bool core_count, errno = 0; long long v = strtoll(s, &end, 10); if (errno == ERANGE || end == s || *end != '\0' || - (nonnegative && v < 0) || (core_count && v > INT_MAX)) + (nonnegative && v < 0) || + (core_count && v > (int64_t)RAY_HEAP_ID_BITS - 1)) return 0; *out = (int64_t)v; return 1; @@ -175,10 +178,10 @@ static const char* str_to_cpath(ray_t* s, char* buf, size_t bufsz) { return buf; } -/* (.db.splayed.set "dir" table) or (.db.splayed.set "dir" table "sym_path") */ +/* (.db.splayed.set "dir" table), (... "sym_path"), (... opts), (... "sym_path" opts) */ ray_t* ray_set_splayed_fn(ray_t** args, int64_t n) { - if (n < 2 || n > 3) - return ray_error("domain", ".db.splayed.set expects 2 or 3 arguments, got %lld", (long long)n); + if (n < 2 || n > 4) + return ray_error("domain", ".db.splayed.set expects 2 to 4 arguments, got %lld", (long long)n); char dir[1024]; if (!str_to_cpath(args[0], dir, sizeof(dir))) @@ -190,12 +193,59 @@ ray_t* ray_set_splayed_fn(ray_t** args, int64_t n) { char sym[1024]; const char* sym_path = NULL; - if (n == 3 && args[2] && args[2]->type == -RAY_STR) - sym_path = str_to_cpath(args[2], sym, sizeof(sym)); - else - sym_path = splay_resolve_sym(dir, sym, sizeof(sym), true); + ray_t* opts = NULL; + bool sym_given = false; + for (int64_t i = 2; i < n; i++) { + ray_t* a = args[i]; + if (a && a->type == RAY_DICT) { + if (opts) return ray_error("domain", ".db.splayed.set: a second options dict"); + opts = a; + } else if (i == 2) { + /* a string names the symfile; anything else is ignored and the + * convention applies, as before */ + if (a && a->type == -RAY_STR) { + sym_given = true; /* an empty or over-long path stays NULL */ + sym_path = str_to_cpath(a, sym, sizeof(sym)); + } + } else { + return ray_error("domain", ".db.splayed.set: argument 4 must be an options dict, got %s", + a ? ray_type_name(a->type) : "null"); + } + } + /* options: compress (true/false) and symfile ('shared/'column) */ + ray_t* okeys = opts ? ray_dict_keys(opts) : NULL; + for (int64_t i = 0; okeys && okeys->type == RAY_SYM && i < okeys->len; i++) { + ray_t* k = ray_sym_vec_cell(okeys, i); + bool known = k && ((ray_str_len(k) == 8 && memcmp(ray_str_ptr(k), "compress", 8) == 0) || + (ray_str_len(k) == 7 && memcmp(ray_str_ptr(k), "symfile", 7) == 0)); + if (!known) + return ray_error("domain", "unknown option '%.*s' (compress and symfile are accepted)", + k ? (int)ray_str_len(k) : 1, k ? ray_str_ptr(k) : "?"); + } + ray_compress_t mode; + ray_t* oerr = ray_compress_opt_parse(opts, false, &mode); + if (oerr) return oerr; + ray_symfile_t layout; + oerr = ray_symfile_opt_parse(opts, &layout); + if (oerr) return oerr; + if (!sym_given) sym_path = splay_resolve_sym(dir, sym, sizeof(sym), true); + /* A symfile per column has no shared symfile to name, and the segments + * of a parted table resolve over its one root symfile: 'column takes + * neither a symfile path nor a partition directory (whose convention + * resolves to the parted root's symfile, not dir/.sym). */ + if (layout == RAY_SYMFILE_COLUMN) { + char own[1024]; + size_t dlen = strlen(dir); + while (dlen > 1 && dir[dlen - 1] == '/') dlen--; + int on = snprintf(own, sizeof(own), "%.*s/.sym", (int)dlen, dir); + bool partition = sym_path && on > 0 && (size_t)on < sizeof(own) && strcmp(own, sym_path) != 0; + if (sym_given || partition) + return ray_error("domain", sym_given + ? ".db.splayed.set: a symfile path with symfile 'column" + : ".db.splayed.set: symfile 'column for a partition of a parted table"); + } - ray_err_t err = ray_splay_save(tbl, dir, sym_path); + ray_err_t err = ray_splay_save_layout(tbl, dir, sym_path, mode, layout); if (err != RAY_OK) return ray_error(ray_err_code_str(err), NULL); ray_retain(tbl); @@ -711,6 +761,12 @@ static bool objsize_push_children(ray_objsize_walk_t* w, ray_t* v) { OBJSIZE_PUSH(v->obj); return true; } + if (v->type == RAY_ENCCOL) { /* the decoded cache (and its index), the parted wrapper */ + ray_t* kids[2]; + int nk = ray_enccol_children(v, kids); + for (int i = 0; i < nk; i++) OBJSIZE_PUSH(kids[i]); + return true; + } if (v->attrs & RAY_ATTR_SLICE) { OBJSIZE_PUSH(v->slice_parent); return true; @@ -739,7 +795,7 @@ static bool objsize_push_children(ray_objsize_walk_t* w, ray_t* v) { if (v->type == RAY_MAPCOMMON || v->type == RAY_TABLE || v->type == RAY_DICT) { ray_t** slots = (ray_t**)ray_data(v); OBJSIZE_PUSH(slots[0]); - OBJSIZE_PUSH(slots[1]); + OBJSIZE_PUSH(slots[1]); /* plain-table */ return true; } if (v->type == RAY_LIST) { @@ -787,6 +843,10 @@ ray_t* ray_mem_ts_fn(ray_t** args, int64_t n) { ray_query_measure_t measure; ray_query_measure_begin(&measure); ray_t* result = ray_eval(args[0]); + /* Force a lazy result inside the measured scope so the time, worker and + * allocation figures cover the computation, not just graph construction + * (#856). Consumes the handle; yields an owned value or an error. */ + if (ray_is_lazy(result)) result = ray_lazy_materialize(result); ray_query_metrics_t metrics; ray_query_measure_end(&measure, &metrics); @@ -875,6 +935,8 @@ ray_t* ray_gc_fn(ray_t** args, int64_t n) { (void)args; if (n != 0) return ray_error("arity", ".sys.gc takes no arguments"); ray_heap_gc(); + /* Dead memory the heap keeps for reuse is not kept locked against swap. */ + ray_heap_unlock_idle(); /* Same statement-boundary rules as the REPL: under memory pressure what * is free goes back now, and an explicit maintenance call is also a * chance to notice the process has gone quiet. */ @@ -1267,7 +1329,8 @@ ray_t* ray_internals_fn(ray_t** args, int64_t n) { /* (.sys.mem) -- return dict with memory allocator statistics */ ray_t* ray_memstat_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".sys.mem takes no arguments"); ray_mem_stats_t st; ray_mem_stats(&st); @@ -1288,6 +1351,11 @@ ray_t* ray_memstat_fn(ray_t** args, int64_t n) { { "anon-committed", 14, ray_heap_anon_committed() }, { "anon-peak", 9, ray_heap_anon_peak() }, { "anon-watermark", 14, ray_heap_anon_watermark() }, + /* the heap's mappings locked against swap-out (bytes mapped, not + * resident), the kernel's refusals, and the bytes left unlocked */ + { "locked-bytes", 12, ray_heap_locked_bytes() }, + { "lock-failed", 11, ray_heap_lock_failures() }, + { "lock-skipped", 12, ray_heap_lock_skipped() }, { "group-perpart-runs", 18, ray_group_perpart_runs() }, { "asof-perpart-runs", 17, ray_asof_perpart_runs() }, { "sort-perpart-runs", 17, ray_sort_perpart_runs() }, @@ -1329,7 +1397,8 @@ ray_t* ray_memstat_fn(ray_t** args, int64_t n) { * no query has run. Profiling is toggled with `:t` / the `-t` flag. */ ray_t* ray_prof_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".sys.prof takes no arguments"); /* Read the snapshot of the last completed query — NOT the in-flight * buffer, which currently holds this `(.sys.prof)` call's own spans. @@ -1524,16 +1593,18 @@ static bool ray_os_hostname(char* buf, size_t cap) { } ray_t* ray_sysinfo_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".sys.info takes no arguments"); ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 5); if (RAY_IS_ERR(keys)) return keys; ray_t* vals = ray_list_new(5); if (RAY_IS_ERR(vals)) { ray_release(keys); return vals; } #if !defined(RAY_OS_WINDOWS) + /* cores: the CPUs this process may run on (its affinity mask) */ int64_t s1 = ray_sym_intern("cores", 5); keys = ray_vec_append(keys, &s1); - ray_t* v1 = make_i64(sysconf(_SC_NPROCESSORS_ONLN)); + ray_t* v1 = make_i64((int64_t)ray_cpu_set_count()); vals = ray_list_append(vals, v1); ray_release(v1); int64_t s2 = ray_sym_intern("page-size", 9); @@ -1565,6 +1636,13 @@ ray_t* ray_sysinfo_fn(ray_t** args, int64_t n) { vals = ray_list_append(vals, v3); ray_release(v3); #endif + /* workers: the threads of the execution pool, main included (the size + * a default pool would get while none exists; none is created here) */ + int64_t sw = ray_sym_intern("workers", 7); + keys = ray_vec_append(keys, &sw); + ray_t* vw = make_i64((int64_t)ray_pool_size()); + vals = ray_list_append(vals, vw); ray_release(vw); + /* Process and host identity (#573). An embedded process previously had * no way to name itself: pid plus hostname plus a start timestamp is a * diagnosable epoch, where a random token only tells you that two runs @@ -1634,6 +1712,8 @@ ray_t* ray_build_sys_args(int argc, char** argv) { else if (strcmp(argv[i], "-U") == 0 && i + 1 < argc) i++; /* skip secret */ else if ((strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "-L") == 0) && i + 1 < argc) log = argv[++i]; + else if ((strcmp(argv[i], "-m") == 0 || strcmp(argv[i], "--mem") == 0) && i + 1 < argc) + i++; /* RAM budget is configured by the launcher, not exposed here */ else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { /* ignore */ } else file = argv[i]; } diff --git a/src/ops/tblop.c b/src/ops/tblop.c index 2e65da07a..022b7f53e 100644 --- a/src/ops/tblop.c +++ b/src/ops/tblop.c @@ -65,7 +65,8 @@ uint16_t pivot_fn_to_agg_op(ray_t* fn) { * Returns NULL when the column has no -0.0 (caller uses the original table), * or RAY_ERR on allocation failure. */ static ray_t* pivot_normalize_f64_key(ray_t* tbl, int64_t pcol_name) { - ray_t* pcol = ray_table_get_col(tbl, pcol_name); + ray_t* pcol = ray_table_col(tbl, pcol_name); + if (pcol && RAY_IS_ERR(pcol)) return pcol; if (!pcol || pcol->type != RAY_F64) return NULL; int64_t nr = pcol->len; const double* src = (const double*)ray_data(pcol); @@ -85,7 +86,10 @@ static ray_t* pivot_normalize_f64_key(ray_t* tbl, int64_t pcol_name) { if (!wt || RAY_IS_ERR(wt)) { ray_release(norm); return wt ? wt : ray_error("oom", NULL); } for (int64_t c = 0; c < ncols && !RAY_IS_ERR(wt); c++) { int64_t cn = ray_table_col_name(tbl, c); - ray_t* cv = (cn == pcol_name) ? norm : ray_table_get_col_idx(tbl, c); + ray_t* cv = norm; + if (cn != pcol_name) { + cv = ray_table_slot_idx(tbl, c); + } wt = ray_table_add_col(wt, cn, cv); } ray_release(norm); @@ -109,7 +113,7 @@ static ray_t* pivot_fn_impl(ray_t* tbl, ray_t* index_arg, ray_t* pivot_col_name, /* Determine index columns. idx_syms are column NAME ids: atoms are * runtime-domain by design and collection_elem re-expresses SYM vec * cells into runtime atoms (the Task-3 chokepoint), so the - * ray_sym_str / ray_table_get_col calls below stay global. + * ray_sym_str / ray_table_col calls below stay global. * * No count cap: pivot's index-column bound used to mirror exec_pivot's * ght layout's fixed [8]-slot key array (pivot.c: n_keys = n_idx + 1 > @@ -165,9 +169,11 @@ static ray_t* pivot_fn_impl(ray_t* tbl, ray_t* index_arg, ray_t* pivot_col_name, } /* Get pivot column, value column */ - ray_t* pcol = ray_table_get_col(tbl, pivot_col_name->i64); + ray_t* pcol = ray_table_col(tbl, pivot_col_name->i64); + if (pcol && RAY_IS_ERR(pcol)) { scratch_free(ic_hdr); return pcol; } if (!pcol) { scratch_free(ic_hdr); return ray_error("domain", "pivot: pivot column not found"); } - ray_t* vcol = ray_table_get_col(tbl, value_col_name->i64); + ray_t* vcol = ray_table_col(tbl, value_col_name->i64); + if (vcol && RAY_IS_ERR(vcol)) { scratch_free(ic_hdr); return vcol; } if (!vcol) { scratch_free(ic_hdr); return ray_error("domain", "pivot: value column not found"); } /* The pivot column's distinct values become output column NAMES (syms); @@ -181,7 +187,8 @@ static ray_t* pivot_fn_impl(ray_t* tbl, ray_t* index_arg, ray_t* pivot_col_name, /* Get index columns (icols carved together with idx_syms above) */ for (int64_t i = 0; i < n_idx; i++) { - icols[i] = ray_table_get_col(tbl, idx_syms[i]); + icols[i] = ray_table_col(tbl, idx_syms[i]); + if (icols[i] && RAY_IS_ERR(icols[i])) { ray_t* e = icols[i]; scratch_free(ic_hdr); return e; } if (!icols[i]) { scratch_free(ic_hdr); return ray_error("domain", "pivot: index column not found"); } } @@ -311,9 +318,19 @@ static ray_t* pivot_fn_impl(ray_t* tbl, ray_t* index_arg, ray_t* pivot_col_name, ray_t* g_icols_hdr = NULL; ray_t** g_icols = (ray_t**)scratch_alloc(&g_icols_hdr, (size_t)vla_idx * sizeof(ray_t*)); if (!g_icols) { ray_release(grouped); scratch_free(ic_hdr); return ray_error("oom", NULL); } - for (int64_t i = 0; i < n_idx; i++) - g_icols[i] = ray_table_get_col(grouped, idx_syms[i]); - ray_t* g_pcol = ray_table_get_col(grouped, pivot_col_name->i64); + for (int64_t i = 0; i < n_idx; i++) { + g_icols[i] = ray_table_col(grouped, idx_syms[i]); + if (g_icols[i] && RAY_IS_ERR(g_icols[i])) { + ray_t* e = g_icols[i]; + scratch_free(g_icols_hdr); ray_release(grouped); scratch_free(ic_hdr); + return e; + } + } + ray_t* g_pcol = ray_table_col(grouped, pivot_col_name->i64); + if (g_pcol && RAY_IS_ERR(g_pcol)) { + scratch_free(g_icols_hdr); ray_release(grouped); scratch_free(ic_hdr); + return g_pcol; + } /* Collect distinct pivot values and index keys from grouped table. * ray_distinct_fn returns a lazy for concrete vecs; materialise here @@ -790,7 +807,12 @@ static ray_t* table_row_value_dict(ray_t* tbl, const int64_t* key_syms, return nkeys_obj ? nkeys_obj : ray_error("oom", NULL); } keys = nkeys_obj; - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) { + ray_release(keys); + ray_release(vals); + return col; + } int alloc = 0; ray_t* cell = collection_elem(col, row, &alloc); if (!cell || RAY_IS_ERR(cell)) { @@ -838,7 +860,7 @@ ray_t* ray_xcol_fn(ray_t* tbl, ray_t* names) { ray_t* out = ray_table_new(ncols); if (!out || RAY_IS_ERR(out)) { ray_free_raw(syms); return out ? out : ray_error("oom", NULL); } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); out = ray_table_add_col(out, syms[c], col); if (!out || RAY_IS_ERR(out)) { ray_free_raw(syms); return out ? out : ray_error("oom", NULL); } } @@ -859,7 +881,7 @@ ray_t* ray_xcols_fn(ray_t* tbl, ray_t* cols) { ray_t* out = ray_table_new(n); if (!out || RAY_IS_ERR(out)) { ray_free_raw(syms); return out ? out : ray_error("oom", NULL); } for (int64_t i = 0; i < n; i++) { - ray_t* col = ray_table_get_col(tbl, syms[i]); + ray_t* col = ray_table_slot(tbl, syms[i]); if (!col) { ray_release(out); ray_free_raw(syms); @@ -886,7 +908,13 @@ ray_t* ray_xkey_fn(ray_t* tbl, ray_t* keys_arg) { ray_t** key_cols = (ray_t**)ray_alloc_raw((size_t)nkeys * sizeof(ray_t*)); if (!key_cols) { ray_free_raw(key_syms); return ray_error("oom", NULL); } for (int64_t k = 0; k < nkeys; k++) { - key_cols[k] = ray_table_get_col(tbl, key_syms[k]); + key_cols[k] = ray_table_col(tbl, key_syms[k]); + if (key_cols[k] && RAY_IS_ERR(key_cols[k])) { + ray_t* e = key_cols[k]; + ray_free_raw(key_cols); + ray_free_raw(key_syms); + return e; + } if (!key_cols[k]) { ray_free_raw(key_cols); ray_free_raw(key_syms); @@ -998,7 +1026,13 @@ ray_t* ray_xgroup_fn(ray_t* tbl, ray_t* keys_arg) { ray_t** key_cols = (ray_t**)ray_alloc_raw((size_t)nkeys * sizeof(ray_t*)); if (!key_cols) { ray_free_raw(key_syms); return ray_error("oom", NULL); } for (int64_t k = 0; k < nkeys; k++) { - key_cols[k] = ray_table_get_col(tbl, key_syms[k]); + key_cols[k] = ray_table_col(tbl, key_syms[k]); + if (key_cols[k] && RAY_IS_ERR(key_cols[k])) { + ray_t* e = key_cols[k]; + ray_free_raw(key_cols); + ray_free_raw(key_syms); + return e; + } if (!key_cols[k]) { ray_free_raw(key_cols); ray_free_raw(key_syms); @@ -1127,6 +1161,16 @@ ray_t* ray_xgroup_fn(ray_t* tbl, ray_t* keys_arg) { return ray_dict_new(keys, vals); } +/* The plain column at `c` when it carries a link, else NULL. A generation-2 + * column is never linked (metadata answers without decoding); a generation-0 + * slot is plain, so the fetch cannot fail. */ +static ray_t* fkeys_linked_col(ray_t* tbl, int64_t c) { + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tbl, c, &m) || m.enc) return NULL; + ray_t* col = ray_table_col_idx(tbl, c); + return ray_link_has(col) ? col : NULL; +} + /* (fkeys table) — linked-column metadata as col->target dict. */ ray_t* ray_fkeys_fn(ray_t* tbl) { if (!tbl || tbl->type != RAY_TABLE) @@ -1135,8 +1179,7 @@ ray_t* ray_fkeys_fn(ray_t* tbl) { int64_t ncols = ray_table_ncols(tbl); int64_t count = 0; for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (ray_link_has(col)) count++; + if (fkeys_linked_col(tbl, c)) count++; } ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, count); @@ -1145,8 +1188,8 @@ ray_t* ray_fkeys_fn(ray_t* tbl) { if (!vals || RAY_IS_ERR(vals)) { ray_release(keys); return vals ? vals : ray_error("oom", NULL); } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (!ray_link_has(col)) continue; + ray_t* col = fkeys_linked_col(tbl, c); + if (!col) continue; int64_t name = ray_table_col_name(tbl, c); int64_t target = ray_link_target_id(col); ray_t* nkeys_obj = ray_vec_append(keys, &name); @@ -1191,7 +1234,8 @@ ray_t* ray_modify_fn(ray_t** args, int64_t n) { return ray_error("type", "modify: second arg must be a symbol, got %s", ray_type_name(col_name->type)); int64_t target_sym = col_name->i64; - ray_t* col = ray_table_get_col(tbl, target_sym); + ray_t* col = ray_table_col(tbl, target_sym); + if (col && RAY_IS_ERR(col)) return col; if (!col) return ray_error("domain", "modify: column not found"); /* Apply fn to the entire column vector (atomic fns will map element-wise) */ @@ -1205,7 +1249,10 @@ ray_t* ray_modify_fn(ray_t** args, int64_t n) { for (int64_t i = 0; i < ncols; i++) { int64_t cname = ray_table_col_name(tbl, i); - ray_t* cvec = (cname == target_sym) ? new_col : ray_table_get_col_idx(tbl, i); + ray_t* cvec = new_col; + if (cname != target_sym) { + cvec = ray_table_slot_idx(tbl, i); + } result = ray_table_add_col(result, cname, cvec); if (RAY_IS_ERR(result)) { ray_release(new_col); return result; } } @@ -1245,6 +1292,13 @@ ray_t* ray_alter_fn(ray_t** args, int64_t n) { /* Resolve the variable */ ray_t* var = ray_env_get(name_sym->i64); if (!var) { ray_release(name_sym); return ray_error("name", NULL); } + /* alter writes through ray_env_set, which binds globally. Refuse a + * local target before any mutation rather than reading the local and + * silently replacing a different (global) binding. */ + if (ray_env_get_local(name_sym->i64)) { + ray_release(name_sym); + return ray_error("domain", "alter: local bindings are not supported"); + } /* Second arg: operation name (unevaluated, must be a name) */ ray_t* op = args[1]; @@ -1319,14 +1373,17 @@ ray_t* ray_alter_fn(ray_t** args, int64_t n) { * binding's reference and ours. The other three exclusions keep the * previous behaviour exactly — ray_cow returns an arena block as-is, * and a slice or a mapped block is not ours to write through. */ - /* A dotted name is NOT a candidate. ray_env_get resolves `d.x` to the - * leaf living inside the container, which typically holds the only - * reference to it — so the leaf passes an rc test that says nothing - * about whether the CONTAINER is shared. Writing through it would be - * seen by every alias of the dict or table, and env_set_dotted's - * COW-rebuild of the chain cannot undo a write that already - * happened. The copy is what made that safe. */ - bool sole = !ray_sym_is_dotted(name_sym->i64) && + /* A dotted name is a candidate only when the whole chain is ours. + * ray_env_get resolves `d.x` to the leaf living inside the container, + * which typically holds the only reference to it — so the leaf passes + * an rc test that says nothing about whether the CONTAINER is shared. + * Writing through it would be seen by every alias of the dict or + * table, and env_set_dotted's COW-rebuild of the chain cannot undo a + * write that already happened. ray_env_dotted_sole checks every dict + * on the path (and its vals list) is held once; a table head, a + * shadowed head or any shared level keeps the copy. */ + bool dotted = ray_sym_is_dotted(name_sym->i64); + bool sole = (!dotted || ray_env_dotted_sole(name_sym->i64, var)) && var->rc == 2 && var->mmod == 0 && !(var->attrs & (RAY_ATTR_SLICE | RAY_ATTR_ARENA)); ray_t* cow_result = sole ? var : ray_cow(var); @@ -1407,7 +1464,10 @@ ray_t* ray_alter_fn(ray_t** args, int64_t n) { ray_release(idx); } ray_release(val); - ray_env_set(name_sym->i64, var); + /* A dotted leaf written in place is already where the chain points; + * rebinding it would only copy each dict on the way up. The index + * drop above may still have copied it, and that copy must be bound. */ + if (!(dotted && sole && var == original_var)) ray_env_set(name_sym->i64, var); /* The retain-first at the top of the set path gave us an owning * ref to var; ray_env_set retained its own for the binding, so * drop ours. In-place amend returns the symbol, not the value. */ @@ -1560,8 +1620,14 @@ ray_t* ray_union_all_fn(ray_t* t1, ray_t* t2) { for (int64_t c = 0; c < ncols; c++) { int64_t name_id = ray_table_col_name(t1, c); - ray_t* col1 = ray_table_get_col_idx(t1, c); - ray_t* col2 = ray_table_get_col_idx(t2, c); + ray_t* col1 = ray_table_col_idx(t1, c); + ray_t* col2 = ray_table_col_idx(t2, c); + if ((col1 && RAY_IS_ERR(col1)) || (col2 && RAY_IS_ERR(col2))) { + ray_t* e = (col1 && RAY_IS_ERR(col1)) ? col1 : col2; + if (e == col1 && col2 && RAY_IS_ERR(col2)) ray_error_free(col2); + ray_release(result); + return e; + } if (!col1 || !col2) { ray_release(result); diff --git a/src/ops/timespan.c b/src/ops/timespan.c new file mode 100644 index 000000000..c0bebb8ce --- /dev/null +++ b/src/ops/timespan.c @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "lang/internal.h" +#include "core/pool.h" +#include "vec/vec.h" + +/* Local selector; bucket evaluation does not allocate a DAG opcode. */ +#define SPAN_BUCKET UINT16_MAX + +static int8_t span_base(int8_t t) { + if (t < 0) return (int8_t)-t; + return RAY_IS_PARTED(t) ? (int8_t)RAY_PARTED_BASETYPE(t) : t; +} + +bool ray_has_timespan(const ray_t* x) { + return x && span_base(x->type) == RAY_TIMESPAN; +} + +static bool span_number(int8_t t) { return t >= RAY_BOOL && t <= RAY_F64; } +static bool span_divisor(int8_t t) { + return span_number(t) || t == RAY_TIMESPAN || t == RAY_TIME || + t == RAY_DATE || t == RAY_TIMESTAMP; +} + +int8_t ray_timespan_binary_type(uint16_t op, int8_t left, int8_t right) { + int8_t a = span_base(left), b = span_base(right); + bool an = a == RAY_TIMESPAN, bn = b == RAY_TIMESPAN; + if (op == OP_SUB && a == RAY_TIMESTAMP && b == RAY_TIMESTAMP) return RAY_TIMESPAN; + if (!an && !bn) return 0; + if (op == SPAN_BUCKET && span_divisor(a) && span_divisor(b)) + return a == RAY_F64 || a == RAY_F32 || b == RAY_F64 || b == RAY_F32 + ? RAY_F64 : span_number(a) ? RAY_I64 : a; + + if (op >= OP_EQ && op <= OP_GE) + return ((an && (bn || span_number(b) || b == RAY_TIME || b == RAY_TIMESTAMP)) || + (bn && (span_number(a) || a == RAY_TIME || a == RAY_TIMESTAMP))) ? RAY_BOOL : -1; + if (op == OP_ADD || op == OP_SUB) { + if (a == RAY_DATE || b == RAY_DATE || a == RAY_TIMESTAMP || b == RAY_TIMESTAMP) + return RAY_TIMESTAMP; + if ((an || span_number(a) || a == RAY_TIME) && + (bn || span_number(b) || b == RAY_TIME)) + return a == RAY_F64 || b == RAY_F64 ? RAY_F64 : RAY_TIMESPAN; + } + if (op == OP_DIV && span_divisor(a) && span_divisor(b)) return RAY_F64; + if (op == OP_IDIV && span_divisor(a) && span_divisor(b)) + return an ? RAY_TIMESPAN : (a == RAY_F32 ? RAY_F64 : a == RAY_BOOL || a == RAY_U8 || a == RAY_I16 ? RAY_I32 : a); + if ((op == OP_MUL || op == OP_MOD) && an != bn && + (an ? span_number(b) : span_number(a))) + return a == RAY_F64 || b == RAY_F64 ? RAY_F64 : RAY_TIMESPAN; + if ((op == OP_MIN2 || op == OP_MAX2) && an && bn) return RAY_TIMESPAN; + return -1; +} + +static int64_t span_value(ray_t* x, uint16_t op) { + if (op == OP_DIV || op == OP_IDIV || op == SPAN_BUCKET) { + if (x->type == -RAY_DATE || x->type == -RAY_TIME) return x->i32; + } + if (x->type == -RAY_DATE) return wrap_mul_i64(x->i32, INT64_C(86400000000000)); + if (x->type == -RAY_TIME) return (int64_t)x->i32 * INT64_C(1000000); + if (x->type == -RAY_F32 || x->type == -RAY_F64) return ray_cast_f64_to_i64_null(round(x->f64)); + return as_i64(x); +} + +static ray_binary_fn span_fn(uint16_t op) { + switch (op) { + case OP_ADD: return ray_add_fn; case OP_SUB: return ray_sub_fn; + case OP_MUL: return ray_mul_fn; case OP_DIV: return ray_div_fn; + case OP_IDIV: return ray_idiv_fn; case OP_MOD: return ray_mod_fn; + case OP_EQ: return ray_eq_fn; case OP_NE: return ray_neq_fn; + case OP_LT: return ray_lt_fn; case OP_LE: return ray_lte_fn; + case OP_GT: return ray_gt_fn; case OP_GE: return ray_gte_fn; + case OP_MIN2: return ray_min2_fn; case OP_MAX2: return ray_max2_fn; + case SPAN_BUCKET: return ray_xbar_fn; + default: return NULL; + } +} + +typedef struct { + int64_t i; + double f; + bool missing; +} span_result_t; + +static span_result_t span_eval(uint16_t op, ray_t* a, ray_t* b, int8_t out) { + bool na = RAY_ATOM_IS_NULL(a), nb = RAY_ATOM_IS_NULL(b); + int64_t av = span_value(a, op), bv = span_value(b, op), value = 0; + if (out == RAY_BOOL) { + if (a->type == -RAY_TIMESTAMP && !na) { + av %= INT64_C(86400000000000); + if (av < 0) av += INT64_C(86400000000000); + } + if (b->type == -RAY_TIMESTAMP && !nb) { + bv %= INT64_C(86400000000000); + if (bv < 0) bv += INT64_C(86400000000000); + } + int cmp; + if (na || nb) cmp = na == nb ? 0 : na ? -1 : 1; + else if (a->type == -RAY_F64 || b->type == -RAY_F64 || + a->type == -RAY_F32 || b->type == -RAY_F32) { + double x = is_numeric(a) ? as_f64(a) : (double)av; + double y = is_numeric(b) ? as_f64(b) : (double)bv; + cmp = x < y ? -1 : x > y; + } else cmp = av < bv ? -1 : av > bv; + return (span_result_t){.i = (op == OP_EQ ? cmp == 0 : op == OP_NE ? cmp != 0 : + op == OP_LT ? cmp < 0 : op == OP_LE ? cmp <= 0 : + op == OP_GT ? cmp > 0 : cmp >= 0)}; + } + if (op == OP_MAX2 && (na || nb) && na != nb) + return (span_result_t){.i = na ? bv : av}; + if (na || nb) return (span_result_t){.missing = true}; + if (out == RAY_F64) { + double x = is_numeric(a) ? as_f64(a) : (double)av; + double y = is_numeric(b) ? as_f64(b) : (double)bv; + double v = op == OP_ADD ? x + y : op == OP_SUB ? x - y : + op == OP_MUL ? x * y : op == OP_DIV ? x / y : + op == OP_IDIV ? floor(x / y) : op == SPAN_BUCKET ? y * floor(x / y) : x - y * floor(x / y); + return (span_result_t){.f = __builtin_isfinite(v) ? v : NULL_F64}; + } + switch (op) { + case OP_ADD: value = wrap_add_i64(av, bv); break; + case OP_SUB: value = (int64_t)((uint64_t)av - (uint64_t)bv); break; + case OP_MUL: value = wrap_mul_i64(av, bv); break; + case OP_IDIV: case OP_MOD: case SPAN_BUCKET: + if (!bv) return (span_result_t){.missing = true}; + value = av / bv; + if (av % bv && (av < 0) != (bv < 0)) value--; + if (op == OP_MOD) { + value = av % bv; + if (value && (av < 0) != (bv < 0)) value += bv; + } + if (op == SPAN_BUCKET) value = wrap_mul_i64(value, bv); + break; + case OP_MIN2: value = av < bv ? av : bv; break; + case OP_MAX2: value = av > bv ? av : bv; break; + default: return (span_result_t){.missing = true}; + } + return (span_result_t){.i = value}; +} + +static ray_t* span_atom(int8_t type, span_result_t value) { + if (value.missing) return ray_typed_null(-type); + switch (type) { + case RAY_BOOL: return ray_bool(value.i != 0); + case RAY_F64: return ray_f64(value.f); + case RAY_TIMESPAN: return ray_timespan(value.i); + case RAY_TIMESTAMP: return ray_timestamp(value.i); + case RAY_TIME: return ray_time(value.i); + case RAY_DATE: return ray_date(value.i); + default: return make_typed_int(-type, value.i); + } +} + +static ray_t span_cell(ray_t* vector, int64_t row) { + ray_t atom = {.type = (int8_t)-vector->type}; + const void* data = ray_data(vector); + switch (vector->type) { + case RAY_BOOL: atom.b8 = ((const uint8_t*)data)[row]; break; + case RAY_U8: atom.u8 = ((const uint8_t*)data)[row]; break; + case RAY_I16: atom.i16 = ((const int16_t*)data)[row]; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: atom.i32 = ((const int32_t*)data)[row]; break; + case RAY_F32: atom.f64 = ((const float*)data)[row]; break; + case RAY_F64: atom.f64 = ((const double*)data)[row]; break; + default: atom.i64 = ((const int64_t*)data)[row]; break; + } + return atom; +} + +ray_t* ray_timespan_binary(uint16_t op, ray_t* a, ray_t* b) { + if (a->type == RAY_LIST || b->type == RAY_LIST || + RAY_IS_PARTED(a->type) || RAY_IS_PARTED(b->type)) { + ray_binary_fn fn = span_fn(op); + return fn ? atomic_map_binary(fn, a, b) : ray_error("type", "unsupported duration operation"); + } + int8_t type = ray_timespan_binary_type(op, a->type, b->type); + if (type <= 0) return ray_error("type", "duration operation is not defined for %s and %s", + ray_type_name(a->type), ray_type_name(b->type)); + bool av = ray_is_vec(a), bv = ray_is_vec(b); + if (!av && !bv) return span_atom(type, span_eval(op, a, b, type)); + if (av && bv && a->len != b->len) + return ray_error("length", "duration operand lengths must match"); + int64_t n = av ? a->len : b->len; + ray_t* result = ray_vec_new(type, n); + if (RAY_IS_ERR(result)) return result; + result->len = n; + void* data = ray_data(result); + bool missing = false; + ray_pool_t* pool = ray_pool_get(); + for (int64_t i = 0; i < n; i++) { + if ((i & 65535) == 0 && (ray_interrupted() || + (pool && atomic_load_explicit(&pool->cancelled, memory_order_acquire)))) { + ray_release(result); + return ray_error("cancel", NULL); + } + ray_t left, right; + if (av) left = span_cell(a, i); + if (bv) right = span_cell(b, i); + span_result_t value = span_eval(op, av ? &left : a, bv ? &right : b, type); + if (type == RAY_F64) ((double*)data)[i] = value.missing ? NULL_F64 : value.f; + else if (type == RAY_BOOL || type == RAY_U8) + ((uint8_t*)data)[i] = value.missing ? 0 : (uint8_t)value.i; + else if (type == RAY_I16) + ((int16_t*)data)[i] = value.missing ? NULL_I16 : (int16_t)value.i; + else if (type == RAY_I32 || type == RAY_DATE || type == RAY_TIME) + ((int32_t*)data)[i] = value.missing ? NULL_I32 : (int32_t)value.i; + else ((int64_t*)data)[i] = value.missing ? NULL_I64 : value.i; + missing |= ray_raw_is_null(type, 0, data, i); + } + if (missing) result->attrs |= RAY_ATTR_HAS_NULLS; + return result; +} + +ray_t* ray_timespan_xbar(ray_t* values, ray_t* width) { + return ray_timespan_binary(SPAN_BUCKET, values, width); +} diff --git a/src/ops/traverse.c b/src/ops/traverse.c index 76466e086..653926a60 100644 --- a/src/ops/traverse.c +++ b/src/ops/traverse.c @@ -977,8 +977,9 @@ ray_t* exec_dijkstra(ray_graph_t* g, ray_op_t* op, /* Find weight column in edge properties */ int64_t weight_sym = ext->graph.weight_col_sym; ray_t* props = rel->fwd.props; - ray_t* weight_vec = ray_table_get_col(props, weight_sym); - if (!weight_vec || RAY_IS_ERR(weight_vec)) return ray_error("schema", NULL); + ray_t* weight_vec = ray_table_col(props, weight_sym); + if (weight_vec && RAY_IS_ERR(weight_vec)) return weight_vec; + if (!weight_vec) return ray_error("schema", NULL); if (weight_vec->type != RAY_F64) return ray_error("schema", NULL); double* weights = (double*)ray_data(weight_vec); @@ -1980,7 +1981,8 @@ ray_t* exec_mst(ray_graph_t* g, ray_op_t* op) { if (n <= 0) return ray_error("length", "graph.mst: graph must have at least one node, got %lld", (long long)n); int64_t weight_sym = ext->graph.weight_col_sym; - ray_t* weight_vec = ray_table_get_col(rel->fwd.props, weight_sym); + ray_t* weight_vec = ray_table_col(rel->fwd.props, weight_sym); + if (weight_vec && RAY_IS_ERR(weight_vec)) return weight_vec; if (!weight_vec || weight_vec->type != RAY_F64) return ray_error("schema", NULL); double* weights = (double*)ray_data(weight_vec); @@ -2287,13 +2289,16 @@ ray_t* exec_astar(ray_graph_t* g, ray_op_t* op, /* Resolve weight column from edge properties */ int64_t weight_sym = ext->graph.weight_col_sym; - ray_t* weight_vec = ray_table_get_col(rel->fwd.props, weight_sym); - if (!weight_vec || RAY_IS_ERR(weight_vec)) return ray_error("schema", NULL); + ray_t* weight_vec = ray_table_col(rel->fwd.props, weight_sym); + if (weight_vec && RAY_IS_ERR(weight_vec)) return weight_vec; + if (!weight_vec) return ray_error("schema", NULL); double* weights_arr = (double*)ray_data(weight_vec); /* Resolve coordinate columns from node properties */ - ray_t* lat_vec = ray_table_get_col(np, ext->graph.coord_col_syms[0]); - ray_t* lon_vec = ray_table_get_col(np, ext->graph.coord_col_syms[1]); + ray_t* lat_vec = ray_table_col(np, ext->graph.coord_col_syms[0]); + if (lat_vec && RAY_IS_ERR(lat_vec)) return lat_vec; + ray_t* lon_vec = ray_table_col(np, ext->graph.coord_col_syms[1]); + if (lon_vec && RAY_IS_ERR(lon_vec)) return lon_vec; if (!lat_vec || !lon_vec) return ray_error("schema", NULL); double* lat = (double*)ray_data(lat_vec); double* lon = (double*)ray_data(lon_vec); @@ -2431,8 +2436,9 @@ ray_t* exec_k_shortest(ray_graph_t* g, ray_op_t* op, return ray_error("range", "graph.k-shortest: src and dst node ids must be in 0..%lld, got %lld and %lld", (long long)(n - 1), (long long)src_id, (long long)dst_id); int64_t weight_sym = ext->graph.weight_col_sym; - ray_t* weight_vec = ray_table_get_col(rel->fwd.props, weight_sym); - if (!weight_vec || RAY_IS_ERR(weight_vec)) return ray_error("schema", NULL); + ray_t* weight_vec = ray_table_col(rel->fwd.props, weight_sym); + if (weight_vec && RAY_IS_ERR(weight_vec)) return weight_vec; + if (!weight_vec) return ray_error("schema", NULL); double* weights_k = (double*)ray_data(weight_vec); int64_t* fwd_off = (int64_t*)ray_data(rel->fwd.offsets); diff --git a/src/ops/window.c b/src/ops/window.c index 491b6d896..8b454bcbd 100644 --- a/src/ops/window.c +++ b/src/ops/window.c @@ -35,7 +35,7 @@ static inline bool win_keys_differ(ray_t* const* vecs, uint32_t n_keys, ray_t* col = vecs[k]; if (!col) continue; switch (col->type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: if (((const int64_t*)ray_data(col))[ra] != ((const int64_t*)ray_data(col))[rb]) return true; break; @@ -96,7 +96,7 @@ static inline double win_read_f64(ray_t* col, int64_t row) { switch (col->type) { case RAY_F64: return ((const double*)ray_data(col))[row]; case RAY_F32: return (double)((const float*)ray_data(col))[row]; - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: return (double)((const int64_t*)ray_data(col))[row]; case RAY_I32: case RAY_DATE: case RAY_TIME: return (double)((const int32_t*)ray_data(col))[row]; @@ -110,7 +110,7 @@ static inline double win_read_f64(ray_t* col, int64_t row) { static inline int64_t win_read_i64(ray_t* col, int64_t row) { switch (col->type) { - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)ray_data(col))[row]; case RAY_I32: case RAY_DATE: case RAY_TIME: return (int64_t)((const int32_t*)ray_data(col))[row]; @@ -128,13 +128,14 @@ static inline int64_t win_read_i64(ray_t* col, int64_t row) { #define win_set_null par_set_null #define win_finalize_nulls par_finalize_nulls -/* Resolve a graph op node to a column vector from tbl */ +/* Resolve a graph op node to a column vector from tbl. A scan key that + * fails to materialize comes back as an owned error (never `owned`). */ static ray_t* win_resolve_vec(ray_graph_t* g, ray_op_t* key_op, ray_t* tbl, uint8_t* owned) { ray_op_ext_t* key_ext = find_ext(g, key_op->id); if (key_ext && key_ext->base.opcode == OP_SCAN) { *owned = 0; - return ray_table_get_col(tbl, key_ext->sym); + return ray_table_col(tbl, key_ext->sym); } *owned = 1; ray_t* saved = g->table; @@ -657,8 +658,8 @@ static void pkey_gather_fn(void* arg, uint32_t wid, static int64_t window_parted_seg_count(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && RAY_IS_PARTED(col->type)) return col->len; + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && RAY_IS_PARTED(m.type)) return m.n_segs; } return 0; /* not parted (a table of only MAPCOMMON keys can't occur) */ } @@ -724,8 +725,9 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { for (uint32_t k = 0; k < ext->window.n_part_keys && !eligible; k++) { ray_op_ext_t* key_ext = find_ext(g, ext->window.part_keys[k]); if (key_ext && key_ext->base.opcode == OP_SCAN) { - ray_t* col = ray_table_get_col(tbl, key_ext->sym); - if (col && col->type == RAY_MAPCOMMON) eligible = true; + ray_col_meta_t m; + if (ray_table_col_meta(tbl, key_ext->sym, &m) && m.type == RAY_MAPCOMMON) + eligible = true; } } if (eligible) { @@ -772,8 +774,9 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { { int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON)) { + ray_col_meta_t m; + if (ray_table_col_meta_idx(tbl, c, &m) && + (RAY_IS_PARTED(m.type) || m.type == RAY_MAPCOMMON)) { int64_t nseg = window_parted_seg_count(tbl); ray_t* flat = NULL; for (int64_t s = 0; s < nseg; s++) { @@ -1052,6 +1055,10 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { uint16_t total_bits = 0; bool fits = true; + /* A null-bearing F64 key packs its nulls into a reserved + * slot below its minimum (radix_key_bounds_finish), so it + * stays on the composite with the placement the single-key + * encode and the merge comparator give, at every row count. */ ray_pool_t* mk_prescan_pool2 = (nrows >= SMALL_POOL_THRESHOLD) ? pool2 : NULL; if (n_sort <= MK_PRESCAN_MAX_KEYS && mk_prescan_pool2) { uint32_t nw = ray_pool_total_workers(mk_prescan_pool2); @@ -1083,11 +1090,14 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { if (wmin < kmin) kmin = wmin; if (wmax > kmax) kmax = wmax; } + radix_key_bounds_finish(sort_vecs[k], &kmin, &kmax); mins[k] = kmin; maxs[k] = kmax; - uint64_t range = (uint64_t)(kmax - kmin); + /* Unsigned subtraction: kmin can be the i64 null + * sentinel, and kmax - kmin then overflows i64. */ + uint64_t range = (uint64_t)kmax - (uint64_t)kmin; uint8_t bits = 1; - while (((uint64_t)1 << bits) <= range && bits < 64) + while (bits < 64 && ((uint64_t)1 << bits) <= range) bits++; total_bits += bits; } @@ -1107,12 +1117,20 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { if (v < kmin) kmin = v; if (v > kmax) kmax = v; } - } else if (col->type == RAY_I64 || col->type == RAY_TIMESTAMP) { + } else if (col->type == RAY_I64 || col->type == RAY_TIMESPAN || col->type == RAY_TIMESTAMP) { const int64_t* d = (const int64_t*)ray_data(col); for (int64_t i = 0; i < nrows; i++) { if (d[i] < kmin) kmin = d[i]; if (d[i] > kmax) kmax = d[i]; } + } else if (col->type == RAY_F64) { + const double* d = (const double*)ray_data(col); + for (int64_t i = 0; i < nrows; i++) { + if (radix_f64_is_null(d[i])) continue; + int64_t v = radix_f64_ord(d[i]); + if (v < kmin) kmin = v; + if (v > kmax) kmax = v; + } } else if (col->type == RAY_I32 || col->type == RAY_DATE || col->type == RAY_TIME) { const int32_t* d = (const int32_t*)ray_data(col); for (int64_t i = 0; i < nrows; i++) { @@ -1132,11 +1150,14 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { if (d[i] > kmax) kmax = (int64_t)d[i]; } } + radix_key_bounds_finish(sort_vecs[k], &kmin, &kmax); mins[k] = kmin; maxs[k] = kmax; - uint64_t range = (uint64_t)(kmax - kmin); + /* Unsigned subtraction: kmin can be the i64 null + * sentinel, and kmax - kmin then overflows i64. */ + uint64_t range = (uint64_t)kmax - (uint64_t)kmin; uint8_t bits = 1; - while (((uint64_t)1 << bits) <= range && bits < 64) + while (bits < 64 && ((uint64_t)1 << bits) <= range) bits++; total_bits += bits; } @@ -1154,9 +1175,9 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { uint8_t accum = 0; for (int k = n_sort - 1; k >= 0; k--) { bit_shifts[k] = accum; - uint64_t range = (uint64_t)(maxs[k] - mins[k]); + uint64_t range = (uint64_t)maxs[k] - (uint64_t)mins[k]; uint8_t bits = 1; - while (((uint64_t)1 << bits) <= range && bits < 64) + while (bits < 64 && ((uint64_t)1 << bits) <= range) bits++; accum += bits; } @@ -1174,7 +1195,7 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { }; for (uint32_t k = 0; k < n_sort; k++) { enc.mins[k] = mins[k]; - enc.ranges[k] = maxs[k] - mins[k]; + enc.ranges[k] = (int64_t)((uint64_t)maxs[k] - (uint64_t)mins[k]); enc.bit_shifts[k] = bit_shifts[k]; enc.descs[k] = sort_descs[k]; enc.enum_ranks[k] = enum_ranks[k]; @@ -1375,11 +1396,10 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { goto oom; } result_vecs[f]->len = nrows; - /* Pre-stamp every slot with the width-correct null sentinel. The - * per-partition compute loops below write valid values into - * "active" slots and call win_set_null on null-producing slots - * without re-writing the payload — pre-stamping ensures every - * null slot already holds the correct sentinel. */ + /* Pre-stamp every slot with the width-correct null sentinel. The + * per-partition loops overwrite active slots and also store the + * sentinel through win_set_null on null-producing slots. Headers + * stay unchanged until win_finalize_nulls after the dispatch. */ if (is_f64[f]) { double* d = (double*)ray_data(result_vecs[f]); for (int64_t i = 0; i < nrows; i++) d[i] = NULL_F64; @@ -1437,7 +1457,7 @@ ray_t* exec_window(ray_graph_t* g, ray_op_t* op, ray_t* tbl) { /* Pass-through original columns */ for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = ray_table_slot_idx(tbl, c); if (!col) continue; int64_t name_id = ray_table_col_name(tbl, c); ray_retain(col); diff --git a/src/store/col.c b/src/store/col.c index ebdd8d286..76ce2a7ab 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -34,6 +34,8 @@ #include "mem/sys.h" /* ray_sys_alloc — the shared-mapping descriptor */ #include "store/serde.h" #include "store/fileio.h" +#include "store/encfmt.h" +#include "store/enccol.h" #include "table/sym.h" #include "table/domain.h" #include "table/dict.h" @@ -44,6 +46,9 @@ #include #include #include + +_Static_assert(COL_DISK_ATTRS_MASK == (uint8_t)(RAY_SYM_W_MASK | RAY_ATTR_SORTED | RAY_ATTR_HAS_NULLS), + "COL_DISK_ATTRS_MASK literal values drifted"); #ifdef RAY_OS_WINDOWS #include #else @@ -112,6 +117,16 @@ static ray_err_t validate_sym_bounds(const void* data, int64_t len, static size_t col_str_pool_payload_len(const ray_t* vec); +/* A file in one of the magic-prefixed formats above (no ray_t header; may + * be shorter than 32 bytes): always generation 0. */ +bool ray_col_header_is_ext(const void* head, size_t n) { + if (n < 4) return false; + uint32_t magic; + memcpy(&magic, head, 4); + return magic == STR_LIST_MAGIC || magic == STR_VEC_MAGIC || + magic == LIST_MAGIC || magic == TABLE_MAGIC; +} + /* -------------------------------------------------------------------------- * Column file format: * Bytes 0-15: aux — RESERVED for postponed on-disk index persistence @@ -148,8 +163,8 @@ static size_t col_str_pool_payload_len(const ray_t* vec); * materialization, BEFORE any error path can release the object. Link * sidecar reattach (try_load_link_sidecar) runs after masking and sets * HAS_LINK with a freshly interned sym ID, so legit links are unaffected. */ -#define COL_DISK_ATTRS_MASK \ - ((uint8_t)(RAY_SYM_W_MASK | RAY_ATTR_SORTED | RAY_ATTR_HAS_NULLS)) +/* The definition lives in col.h so the generation-2 writer and reader + * share it. */ /* "Index present" marker written to the on-disk header's reserved aux[0..3] * (see col.h: aux is reserved for index persistence). Existing files leave @@ -167,7 +182,7 @@ static bool is_serializable_type(int8_t t) { switch (t) { case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: case RAY_F32: case RAY_F64: - case RAY_DATE: case RAY_TIME: case RAY_TIMESTAMP: case RAY_GUID: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_GUID: case RAY_SYM: case RAY_STR: return true; default: @@ -182,6 +197,7 @@ static bool is_serializable_type(int8_t t) { static ray_err_t col_preflight_recursive(ray_t* obj) { if (!obj || RAY_IS_ERR(obj)) return RAY_ERR_TYPE; int8_t type = obj->type; + if (type == RAY_ENCCOL) return RAY_OK; if (type < 0 || is_serializable_type(type)) return RAY_OK; if (type == RAY_LIST) { @@ -196,8 +212,10 @@ static ray_err_t col_preflight_recursive(ray_t* obj) { if (type == RAY_TABLE) { int64_t ncols = ray_table_ncols(obj); for (int64_t c = 0; c < ncols; c++) { - ray_err_t err = col_preflight_recursive( - ray_table_get_col_idx(obj, c)); + ray_t* sc = ray_table_get_col_enc_idx(obj, c); + if (!sc) sc = ray_table_col_idx(obj, c); + ray_err_t err = col_preflight_recursive(sc); + if (sc && RAY_IS_ERR(sc)) ray_error_free(sc); if (err != RAY_OK) return err; } return RAY_OK; @@ -215,6 +233,9 @@ static ray_err_t col_preflight_recursive(ray_t* obj) { ray_err_t ray_col_save_preflight(ray_t* vec) { if (!vec || RAY_IS_ERR(vec)) return RAY_ERR_TYPE; + /* An encoded column's logical type is always storable; a parted one + * (like a plain parted wrapper) has no single-file form. */ + if (vec->type == RAY_ENCCOL) return ray_enccol_is_parted(vec) ? RAY_ERR_NYI : RAY_OK; if (is_serializable_type(vec->type)) return RAY_OK; if (vec->type == RAY_LIST || vec->type == RAY_TABLE) return col_preflight_recursive(vec); @@ -319,6 +340,7 @@ static ray_t* col_load_str_vec(const uint8_t* ptr, size_t remaining) { * atoms (type < 0): * -RAY_STR: [4B len][data bytes] * -RAY_SYM: [4B len][data bytes] (resolved string; load re-interns) + * -RAY_GUID: [16B value] * other: [8B raw value] * RAY_SYM vector: [8B len][per cell: 4B len + data bytes] * other vectors with is_serializable_type: [8B len][raw data] @@ -352,6 +374,12 @@ static ray_err_t col_write_recursive(ray_t* obj, FILE* f) { uint32_t len32 = (uint32_t)slen; if (fwrite(&len32, 4, 1, f) != 1) return RAY_ERR_IO; if (slen > 0 && fwrite(sp, 1, slen, f) != slen) return RAY_ERR_IO; + } else if (type == -RAY_GUID) { + /* GUID atoms hold their 16 bytes behind obj: write the value, + * never the pointer (a NULL obj is the null GUID). */ + static const uint8_t null_guid[16] = {0}; + const uint8_t* b = obj->obj ? (const uint8_t*)ray_data(obj->obj) : null_guid; + if (fwrite(b, 1, 16, f) != 16) return RAY_ERR_IO; } else { /* Fixed-size atom: write 8 bytes of the value union */ if (fwrite(&obj->i64, 8, 1, f) != 1) return RAY_ERR_IO; @@ -418,7 +446,12 @@ static ray_err_t col_write_recursive(ray_t* obj, FILE* f) { for (int64_t c = 0; c < ncols; c++) { int64_t name_sym = ray_table_col_name(obj, c); if (fwrite(&name_sym, 8, 1, f) != 1) return RAY_ERR_IO; - ray_t* col = ray_table_get_col_idx(obj, c); + ray_t* col = ray_table_col_idx(obj, c); + if (col && RAY_IS_ERR(col)) { + ray_err_t ce = ray_err_from_obj(col); + ray_error_free(col); + return ce; + } ray_err_t err = col_write_recursive(col, f); if (err != RAY_OK) return err; } @@ -462,6 +495,14 @@ static ray_t* col_read_recursive(const uint8_t** pp, size_t* remaining) { ray_t* s = ray_str((const char*)*pp, (size_t)slen); *pp += slen; *remaining -= slen; return s; + } else if (type == -RAY_GUID) { + /* GUID atom: its 16-byte value. Files written before this + * held a process pointer here and were never readable. */ + if (*remaining < 16) return ray_error("corrupt", NULL); + uint8_t gb[16]; + memcpy(gb, *pp, 16); + *pp += 16; *remaining -= 16; + return ray_guid(gb); } else { /* Fixed atom: 8 bytes */ if (*remaining < 8) return ray_error("corrupt", NULL); @@ -527,11 +568,23 @@ static ray_t* col_read_recursive(const uint8_t** pp, size_t* remaining) { size_t data_size = (size_t)len * esz; if (data_size > *remaining) return ray_error("corrupt", NULL); - ray_t* vec = ray_vec_new(type, len); - if (!vec || RAY_IS_ERR(vec)) return vec; - vec->len = len; - if (data_size > 0) - memcpy(ray_data(vec), *pp, data_size); + /* The nested format carries no attrs for fixed-width vectors, so + * their HAS_NULLS is rebuilt from the sentinels — the source of + * truth — by ray_vec_from_raw's construction scan. Without it a + * null cell loaded as plain data (`[0N 2]` read back as + * `[-9223372036854775808 2]`). */ + ray_t* vec; + if (type == RAY_STR) { + vec = ray_vec_new(type, len); + if (!vec || RAY_IS_ERR(vec)) return vec; + vec->len = len; + if (data_size > 0) + memcpy(ray_data(vec), *pp, data_size); + } else { + vec = ray_vec_from_raw(type, *pp, len); + if (!vec) return ray_error("oom", NULL); + if (RAY_IS_ERR(vec)) return vec; + } *pp += data_size; *remaining -= data_size; if (type == RAY_STR) { @@ -760,8 +813,12 @@ ray_err_t ray_col_append_index(const char* path, const void* ix_v, (void)col_len; (void)col_type; FILE* f = fopen(path, "r+b"); if (!f) return RAY_ERR_IO; - uint32_t cur_mg = 0; - if (fread(&cur_mg, 1, 4, f) == 4 && cur_mg == COL_IDX_AUX_MAGIC) { fclose(f); return RAY_ERR_CORRUPT; } + uint8_t h32[32]; + if (fread(h32, 1, 32, f) != 32) { fclose(f); return RAY_ERR_CORRUPT; } + int gen = ray_col_gen_of(h32); + if (gen != 0) { fclose(f); return gen == RAY_ENC_GEN_CORRUPT ? RAY_ERR_CORRUPT : RAY_ERR_VERSION; } + uint32_t cur_mg; memcpy(&cur_mg, h32, 4); + if (cur_mg == COL_IDX_AUX_MAGIC) { fclose(f); return RAY_ERR_CORRUPT; } int64_t payload_end = 0; ray_err_t err = ray_col_write_index_region(f, ix_v, &payload_end); if (err == RAY_OK) { @@ -942,7 +999,7 @@ static bool col_payload_has_nulls(ray_t* vec) { for (int64_t i = 0; i < n; i++) if (d[i] != d[i]) return true; return false; } - case RAY_I64: case RAY_TIMESTAMP: { + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* d = (const int64_t*)p; for (int64_t i = 0; i < n; i++) if (d[i] == NULL_I64) return true; return false; @@ -1110,14 +1167,26 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { * Load/mmap reattach the domain below. */ if (vec->type == RAY_SYM) memset(header.aux, 0, 16); + /* RAY_STR: aux bytes 8-15 hold the runtime str_pool pointer; it used + * to reach the file whenever HAS_NULLS kept aux above (a heap address + * on disk, different on every run). No reader uses those bytes: both + * loaders zero aux before attaching the pool. */ + if (vec->type == RAY_STR) + memset(header.aux + 8, 0, 8); /* FILE-domain SYM re-expressed to runtime ids: width follows the * global table, SORTED dropped (id order changed). */ if (sym_xlate) header.attrs = (uint8_t)((header.attrs & ~(uint8_t)(RAY_SYM_W_MASK | RAY_ATTR_SORTED)) | sym_xlate_attrs); + /* aux[0..3] is the generation discriminator on disk: nothing durable + * lives there except the index marker stamped below, so zero it + * unconditionally (in-memory aux bytes, e.g. a saved_aux restore on a + * nullable column, must never reach the file). */ + memset(header.aux, 0, 4); + /* Stamp the "index present" marker into the reserved aux (after all - * other aux manipulation, which zeroes it for the common cases). */ + * other aux manipulation). */ if (persist_index) { ray_col_stamp_index(&header); } @@ -1471,6 +1540,7 @@ typedef struct { uint32_t saved_sym_count; bool has_index; /* aux marker present → inline index region at tail */ size_t index_offset; /* 32-aligned start of the index region (has_index) */ + bool gen2; /* generation-2 file: only mapped/header are set */ } col_mapped_t; static size_t col_str_pool_payload_len(const ray_t* vec) { @@ -1514,20 +1584,9 @@ static ray_err_t col_validate_str_region(ray_t* hdr, const void* ptr, if (pool_size > mapped_size - offset - 32) return RAY_ERR_CORRUPT; + /* the region's extents only: the descriptors are taken as written */ ray_str_t* elems = (ray_str_t*)((char*)ptr + 32); const char* pool_base = (const char*)ptr + offset + 32; - for (int64_t i = 0; i < hdr->len; i++) { - uint32_t len = elems[i].len; - if (len <= RAY_STR_INLINE_MAX) continue; - if (pool_size == 0 || elems[i].pool_off > pool_size || - len > pool_size - elems[i].pool_off) - return RAY_ERR_CORRUPT; - if (len >= 4) { - const char* p = pool_base + elems[i].pool_off; - if (memcmp(elems[i].prefix, p, 4) != 0) - return RAY_ERR_CORRUPT; - } - } /* A current writer stores every pooled descriptor's content hash and * marks the header (RAY_COL_STR_HASHED, col.h): those descriptors are @@ -1596,15 +1655,29 @@ static ray_t* col_validate_mapped(const char* path, col_mapped_t* out) { ray_t* hdr = (ray_t*)ptr; - /* Validate the on-disk format major version (the `order` byte) BEFORE - * interpreting type/len. FRESH SWAP, NO LEGACY: a file whose major - * does not match the reader is rejected here. The loaders below reset - * the runtime `order` to its correct value, so reading the version out - * of `order` here does not leak into the live block order. */ - if (ray_col_check_format(hdr) != RAY_OK) { + /* Generation discriminator (spec "Generation discriminator"): the pair + * (order, aux[0..3]) is validated BEFORE type/len are interpreted or + * either parser runs. FRESH SWAP, NO LEGACY: an unknown major is + * rejected, and a cross pair is corrupt, never a fallback to the other + * layout. The loaders below reset the runtime `order`, so reading the + * version out of `order` here does not leak into the live block order. */ + int gen = ray_col_gen_of(ptr); + if (gen == RAY_ENC_GEN_VERSION) { + ray_vm_unmap_file(ptr, mapped_size); + return ray_error("version", "column %s: bad format version", path); + } + if (gen == RAY_ENC_GEN_CORRUPT) { ray_vm_unmap_file(ptr, mapped_size); - return ray_error("version", "col %s: bad format version", path); + return ray_error("corrupt", "column %s: format byte and generation marker disagree", path); } + if (gen == 2) { + out->gen2 = true; + out->mapped = ptr; + out->mapped_size = mapped_size; + out->header = hdr; + return NULL; /* the generation-2 parser validates the rest */ + } + out->gen2 = false; /* Validate type from untrusted file data -- allowlist only */ if (!is_serializable_type(hdr->type)) { @@ -1733,6 +1806,14 @@ static ray_t* col_load_impl(const char* path, struct ray_sym_domain_s* dom, col_mapped_t cm = {0}; ray_t* err = col_validate_mapped(path, &cm); if (err) return err; + if (cm.gen2) { + ray_t* enc = ray_enccol_open(cm.mapped, cm.mapped_size, path, dom, require_dom); + if (!enc || RAY_IS_ERR(enc)) return enc; + ray_t* v = ray_enccol_materialize(enc); + if (!RAY_IS_ERR(v)) ray_retain(v); /* outlives the object */ + ray_release(enc); + return v; + } /* Allocate buddy block and copy file data */ ray_t* vec = ray_alloc(cm.data_size); @@ -1776,7 +1857,10 @@ static ray_t* col_load_impl(const char* path, struct ray_sym_domain_s* dom, if (vec->type == RAY_SYM) { if (dom) { /* Splayed/parted load: on-disk cells are positions in the - * table's symfile — attach ITS domain (one ref per column). */ + * table's symfile — attach ITS domain (one ref per column). + * The symfile the caller named must hold every id the column + * was saved over (its saved count; a column without one is + * scanned), as the mmap load checks it. */ vec->sym_domain = dom; ray_sym_domain_retain(dom); int64_t dcount = ray_sym_domain_count(dom); @@ -1786,12 +1870,14 @@ static ray_t* col_load_impl(const char* path, struct ray_sym_domain_s* dom, "column %s: saved sym count %u exceeds symfile count %lld", path, cm.saved_sym_count, (long long)dcount); } - uint32_t bound = dcount > UINT32_MAX ? UINT32_MAX : (uint32_t)dcount; - ray_err_t sym_err = validate_sym_bounds(ray_data(vec), vec->len, - vec->attrs, bound); - if (sym_err != RAY_OK) { - ray_release(vec); - return ray_error(ray_err_code_str(sym_err), NULL); + if (cm.saved_sym_count == 0) { + uint32_t bound = dcount > UINT32_MAX ? UINT32_MAX : (uint32_t)dcount; + ray_err_t sym_err = validate_sym_bounds(ray_data(vec), vec->len, + vec->attrs, bound); + if (sym_err != RAY_OK) { + ray_release(vec); + return ray_error(ray_err_code_str(sym_err), NULL); + } } } else if (require_dom) { /* A stored SYM column without a resolvable symfile must @@ -1847,15 +1933,8 @@ static ray_t* col_mmap_impl(const char* path, struct ray_sym_domain_s* dom, col_mapped_t cm = {0}; ray_t* err = col_validate_mapped(path, &cm); if (err) return err; - - /* Validate that the file size matches the expected layout. Without an - * inline index the payload is the whole file (ray_free reconstructs the - * munmap size from the same formula). With an index, the file extends past - * the payload by the 32-aligned index region — that's expected, not a tear. */ - if (!cm.has_index && cm.tail_offset != cm.mapped_size) { - ray_vm_unmap_file(cm.mapped, cm.mapped_size); - return ray_error("io", NULL); - } + if (cm.gen2) + return ray_enccol_open(cm.mapped, cm.mapped_size, path, dom, require_dom); ray_t* vec = cm.header; diff --git a/src/store/col.h b/src/store/col.h index 12c415b53..bc5ef1ce0 100644 --- a/src/store/col.h +++ b/src/store/col.h @@ -27,6 +27,7 @@ #include #include #include +#include "store/colrange.h" struct ray_sym_domain_s; @@ -66,14 +67,20 @@ static inline void ray_col_stamp_format(ray_t* header) { header->order = RAY_COL_FORMAT_MAJOR; } -/* Validate the format generation in a mapped/built column header's `order` - * byte (offset 17). Returns RAY_OK iff it matches the reader's generation, - * else RAY_ERR_VERSION. Strict equality: with the current generation at 0, - * legacy/pre-stamp files (order==0) load and any other generation is refused. */ +/* Accepts the generations this build reads (0 and 2); the pair check that + * separates them is ray_col_gen_of (store/encfmt.h). */ static inline ray_err_t ray_col_check_format(const ray_t* header) { - return header->order == RAY_COL_FORMAT_MAJOR ? RAY_OK : RAY_ERR_VERSION; + return (header->order == RAY_COL_FORMAT_MAJOR || header->order == 2) + ? RAY_OK : RAY_ERR_VERSION; } +/* Allowlist of attr bits the save path persists; see the rationale in + * col.c (loaders mask untrusted disk attrs to this set). Literal values + * because this header does not include table/sym.h; col.c asserts them. */ +#define COL_DISK_ATTRS_MASK ((uint8_t)(0x03 /* RAY_SYM_W_MASK */ | \ + 0x20 /* RAY_ATTR_SORTED */ | \ + 0x40 /* RAY_ATTR_HAS_NULLS */)) + /* STR column files: a writer that stored every pooled descriptor's content * hash (ray_str_t.hash32) says so by putting this value in the header's * `rc` field, which is otherwise 0 on disk for STR (RAY_SYM uses it for @@ -101,6 +108,87 @@ static inline void ray_col_stamp_str_hashed(ray_t* header) { * loads attach that symfile's domain (sym-domain architecture spec). */ ray_err_t ray_col_save(ray_t* vec, const char* path); ray_err_t ray_col_save_bulk(ray_t* vec, const char* path); +/* Write `vec` in the given generation (0 or 2). ray_col_save / _bulk stay + * generation 0 only. A column generation 2 cannot hold is written as 0. */ +ray_err_t ray_col_save_gen(ray_t* vec, const char* path, uint8_t gen); +ray_err_t ray_col_save_bulk_gen(ray_t* vec, const char* path, uint8_t gen); + +/* Write context (spec "Writers"): a bound source (plain or encoded), the + * resolved generation and the SYM target domain. Handles plain->0, + * plain->2, encoded->0 (materialize, then the generation-0 writer) and + * encoded->2 (range reads, SYM ids remapped into the target domain, no + * whole-column materialization). On failure every temporary is released and + * the staging file removed; nothing is renamed into place. */ +/* The tri-state `compress` option of a save (spec "Generation + * resolution"): explicit true / false set every file; absent inherits. */ +typedef enum { RAY_COMPRESS_ABSENT = 0, RAY_COMPRESS_ON = 1, RAY_COMPRESS_OFF = 2 } ray_compress_t; + +enum { RAY_COL_IDX_KEEP = 0, RAY_COL_IDX_REBUILD = 1, RAY_COL_IDX_DROP = 2 }; +typedef struct { + ray_col_src_t src; /* bound by the caller (ray_col_src_bind); not released here */ + const char* name; /* column name, diagnostics */ + uint8_t gen; /* resolved generation: 0 or 2 */ + struct ray_sym_domain_s* target_dom; /* SYM: destination symfile domain; NULL = bare */ + uint8_t index_decision; /* RAY_COL_IDX_*: generation 2 keeps, rebuilds or drops a + * region index; generation 0 takes KEEP only */ + uint8_t index_kind; /* generation 2: kind to record (0 = from the source) */ + bool durable; +} ray_col_write_t; +ray_err_t ray_col_save_ctx(ray_col_write_t* w, const char* path); +void ray_col_test_fail_alloc(int64_t nth); /* test hook; 0 disarms */ +/* Spec "Writing the index" (P6b): generation 0's STR DICT build condition, + * STR and RAY_DICT_MIN_ROWS <= len <= INT32_MAX (splay_build_index_col, + * ray_dict_acc_finish). The callers add their own path rule (index + * building asked for, no HASH). False while ray_col_test_no_dict is on. */ +bool ray_col_dict_wanted(int8_t type, int64_t len); +/* Test hook: true makes ray_col_dict_wanted answer false (a generation-2 + * STR save writes no DICT); false disarms (ray_test_hooks_off). */ +void ray_col_test_no_dict(bool on); + +/* Generation resolution, decided by a save under the destination's + * .write.lock. `dest_cur` is the destination's current published + * generation directory, NULL or "" when it holds no published table. + * ON: 2 for every file generation 2 can hold; OFF: 0; ABSENT: 2 when the + * source is a RAY_ENCCOL or the destination's current generation stores the + * file `name` as generation 2, else 0. Linked, nested and list columns + * are always 0; an indexed column is generation 2 with its index region + * (a SYM column's HASH or PART rebuilt over the target ids). */ +/* lossy: read errors read as 0 — writers use the *_err forms */ +uint8_t ray_col_file_gen(const char* path); /* 2 when the file is generation 2, else 0 (missing included) */ +/* lossy: read errors read as 0 — writers use the *_err forms */ +uint8_t ray_col_resolve_gen(ray_compress_t mode, ray_t* src, + const char* dest_cur, const char* name, size_t name_len); +/* The same rule for writers that have only the column's type (streams). + * lossy: read errors read as 0 — writers use the *_err forms */ +uint8_t ray_col_resolve_gen_type(ray_compress_t mode, int8_t type, + const char* dest_cur, const char* name, size_t name_len); +/* Checked forms, for savers: a missing destination file is generation 0, + * but a file that cannot be read (permissions, short, bad discriminator) or + * a path that overflows is an error, never a silent 0. The uint8_t forms + * above read every error as 0. */ +ray_err_t ray_col_file_gen_err(const char* path, uint8_t* gen); +/* First bytes of a magic-prefixed (header-less, generation-0) column file? */ +bool ray_col_header_is_ext(const void* head, size_t n); +ray_err_t ray_col_resolve_gen_err(ray_compress_t mode, ray_t* src, const char* dest_cur, + const char* name, size_t name_len, uint8_t* gen); +/* Would resolving `src` under `mode` consult the destination? Only an + * inheriting (ABSENT) save of a plain eligible column does. */ +bool ray_col_resolve_needs_dest(ray_compress_t mode, ray_t* src); +/* The same question for writers that have only the column's type (streams). */ +bool ray_col_resolve_type_needs_dest(ray_compress_t mode, int8_t type); +ray_err_t ray_col_resolve_gen_type_err(ray_compress_t mode, int8_t type, const char* dest_cur, + const char* name, size_t name_len, uint8_t* gen); +/* Parse the `compress` option from `opts` (a RAY_DICT with SYM keys; NULL: + * absent). strict: any key other than `compress` is a domain error. A + * non-bool `compress` is a domain error. Returns NULL or an owned error. */ +ray_t* ray_compress_opt_parse(ray_t* opts, bool strict, ray_compress_t* mode); +void ray_store_test_force_compress(bool on); /* equivalence run: absent behaves as true */ + +/* Can generation 2 hold this plain vector (type, no link)? Index meta: + * the kind (every fresh kind) and the UNIQUE flag a plain column records; + * a stale root records none. */ +bool ray_col_gen2_eligible(ray_t* col); +void ray_col_gen2_index_meta(ray_t* col, uint8_t* index_kind, uint8_t* col_flags); /* Validate the complete object graph accepted by ray_col_save without * opening or modifying a file. Splayed saves use this before mutating a * symfile or any already-committed column generation. */ diff --git a/src/store/colrange.c b/src/store/colrange.c new file mode 100644 index 000000000..53d222b32 --- /dev/null +++ b/src/store/colrange.c @@ -0,0 +1,922 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "store/colrange.h" +#include "core/platform.h" +#include "core/pool.h" +#include "store/col.h" +#include "store/enccol.h" +#include "store/enceval.h" +#include "table/sym.h" +#include "table/domain.h" +#include "table/table.h" +#include "ops/ops.h" +#include "ops/idxop.h" +#include "vec/vec.h" +#include + +/* Fixed scratch: one vector of the widest element (GUID, 16 bytes). */ +#define SCRATCH_FIXED_BYTES ((size_t)RAY_ENC_VEC * 16) +_Static_assert(SCRATCH_FIXED_BYTES == RAY_COL_FIXED_BYTES, "a lent fixed vector holds one vector"); + +void ray_col_scratch_init(ray_col_scratch_t* s) { memset(s, 0, sizeof *s); } + +void ray_col_scratch_lend(ray_col_scratch_t* s, ray_col_fixed_t* buf) { + if (!s->fixed_lent) ray_free_raw(s->fixed); + s->fixed = buf->b; + s->fixed_lent = true; +} + +static _Atomic(uint64_t) g_fixed_allocs; /* test hook */ +uint64_t ray_col_test_fixed_allocs(void) { return atomic_load(&g_fixed_allocs); } + +/* Decoded bytes are counted per scratch and column, not per vector: the + * counters are shared by every worker. The scratch references the column + * it counts for (once per column, not per vector), so a flush never reads a + * freed column, whatever the order of the scratch's and source's release. */ +static _Atomic(uint64_t) g_wide_hits; /* test hook */ +uint64_t ray_col_test_wide_hits(void) { return atomic_load(&g_wide_hits); } + +static void scratch_flush(ray_col_scratch_t* s) { + if (s->acc_e) { + ray_enccol_note_decoded(s->acc_e, s->acc_bytes); + ray_enccol_unref(s->acc_e); + } + if (s->wide_hits) atomic_fetch_add_explicit(&g_wide_hits, s->wide_hits, memory_order_relaxed); + s->acc_e = NULL; + s->acc_bytes = 0; + s->wide_hits = 0; +} +static void scratch_count(ray_col_scratch_t* s, ray_enccol_t* e, uint64_t nb) { + if (s->acc_e != e) { scratch_flush(s); ray_enccol_ref(e); s->acc_e = e; } + s->acc_bytes += nb; +} + +void ray_col_scratch_free(ray_col_scratch_t* s) { + scratch_flush(s); + if (!s->fixed_lent) ray_free_raw(s->fixed); + ray_free_raw(s->pool); + memset(s, 0, sizeof *s); +} + +static ray_t* plain_owner(ray_t* v) { return (v->attrs & RAY_ATTR_SLICE) ? v->slice_parent : v; } + +/* The domain a SYM source's ids resolve over: the first present segment's + * for a parted source (segments share one domain). */ +static struct ray_sym_domain_s* sym_domain_of(ray_t* obj) { + if (obj->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of(obj); + if (e->kind == RAY_ENCCOL_SINGLE) return e->dom; + obj = e->wrapper; + } + if (RAY_IS_PARTED(obj->type)) { + ray_t** segs = (ray_t**)ray_data(obj); + for (int64_t i = 0; i < obj->len; i++) + if (segs[i]) return sym_domain_of(segs[i]); + return ray_sym_runtime_domain(); + } + return ray_sym_vec_domain(obj); +} + +static bool may_null_of(ray_t* obj) { + ray_col_meta_t m; + ray_col_meta_of(obj, &m); + if (m.null_count >= 0) return m.null_count > 0; + if (RAY_IS_PARTED(m.type)) { + ray_t* w = obj->type == RAY_ENCCOL ? ray_enccol_of(obj)->wrapper : obj; + ray_t** segs = (ray_t**)ray_data(w); + for (int64_t i = 0; i < w->len; i++) + if (segs[i] && may_null_of(segs[i])) return true; + return false; + } + /* generation 0: the existing nullability proof (always true for SYM + * and STR, whose nulls are in-band) */ + return ray_is_vec(obj) ? ray_vec_may_have_nulls(obj) : (m.attrs & RAY_ATTR_HAS_NULLS) != 0; +} + +ray_t* ray_col_src_bind(ray_t* col, ray_col_src_t* out) { + memset(out, 0, sizeof *out); + if (!col || RAY_IS_ERR(col)) return ray_error("type", "source bind: no column"); + if (col->type == RAY_MAPCOMMON) return ray_error("nyi", "source bind: partition key column"); + if ((col->attrs & RAY_ATTR_SLICE) && (col->type == RAY_ENCCOL || RAY_IS_PARTED(col->type))) + return ray_error("nyi", "source bind: slice of an encoded or parted column"); + ray_col_meta_t m; + ray_col_meta_of(col, &m); + out->type = RAY_IS_PARTED(m.type) ? (int8_t)RAY_PARTED_BASETYPE(m.type) : m.type; + out->attrs = m.attrs & COL_DISK_ATTRS_MASK; + out->len = m.len; + out->may_null = may_null_of(col); + out->parted = RAY_IS_PARTED(m.type); + if (out->type == RAY_SYM) { + out->dom = sym_domain_of(col); + out->dom_owned = out->dom != ray_sym_runtime_domain(); + if (out->dom_owned) ray_sym_domain_retain(out->dom); + } + ray_retain(col); + out->obj = col; + return NULL; +} + +void ray_col_src_release(ray_col_src_t* s) { + ray_free_raw(atomic_load_explicit(&s->seg_off, memory_order_acquire)); + if (s->obj) ray_release(s->obj); + if (s->dom && s->dom_owned) ray_sym_domain_release(s->dom); + memset(s, 0, sizeof *s); +} + +ray_t* ray_table_col_src(ray_t* tbl, int64_t name_id, ray_col_src_t* out) { + memset(out, 0, sizeof *out); + ray_col_meta_t m; + if (!ray_table_col_meta(tbl, name_id, &m)) return NULL; + ray_t* obj = m.enc ? m.enc : ray_table_col(tbl, name_id); /* plain: no decode */ + if (!obj || RAY_IS_ERR(obj)) return obj; + return ray_col_src_bind(obj, out); +} + +static void range_plain(ray_t* v, int64_t start, int64_t n, ray_col_range_t* out) { + uint8_t esz = ray_sym_elem_size(v->type, v->attrs); + if (n > v->len - start) n = v->len - start; + out->data = (const char*)ray_data(v) + (size_t)start * esz; + out->n = n; + out->type = v->type; + out->attrs = v->attrs & COL_DISK_ATTRS_MASK; + out->may_null = ray_vec_may_have_nulls(v); + ray_t* own = plain_owner(v); + out->str_pool = (v->type == RAY_STR && own->str_pool && !RAY_IS_ERR(own->str_pool)) + ? (const char*)ray_data(own->str_pool) : NULL; + out->dom = v->type == RAY_SYM ? ray_sym_vec_domain(v) : NULL; +} + +static ray_t* range_enc(ray_enccol_t* e, int64_t start, int64_t n, + ray_col_scratch_t* sc, ray_col_range_t* out) { + int64_t vec = start / RAY_ENC_VEC; + int64_t off = start % RAY_ENC_VEC; + int64_t vlen = ray_enc_vec_len(e->len, vec); + if (n > vlen - off) n = vlen - off; + if (!sc->fixed) { + sc->fixed = ray_alloc_raw(SCRATCH_FIXED_BYTES); + if (!sc->fixed) return ray_error("oom", "range read scratch"); + atomic_fetch_add_explicit(&g_fixed_allocs, 1, memory_order_relaxed); + } + int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + int j = (int)(vec % RAY_ENC_VECS_PER_CHUNK); + const ray_enc_desc_t* descs = ray_enccol_descs(e, c); + ray_t* err; + if (e->type != RAY_STR && e->type != RAY_GUID) { + /* a RAW vector without nulls is its own decode: read it in place. + * An integer one counts its bytes as delivered, so the read-once + * counts of a key hold whatever its vectors' encodings; a float + * one counts none (Task 9). */ + const void* pv = ray_enccol_raw_view(e, c, j, &descs[j]); + if (pv) { + if (e->type != RAY_F64 && e->type != RAY_F32) scratch_count(sc, e, (uint64_t)vlen * ray_enccol_esz(e)); + out->data = (const uint8_t*)pv + (size_t)off * ray_enccol_esz(e); + out->n = n; + out->type = e->type; + out->attrs = e->attrs; + out->may_null = false; + out->str_pool = NULL; + out->dom = e->type == RAY_SYM ? e->dom : NULL; + return NULL; + } + } + if (e->type == RAY_STR) { + uint64_t pb = 0; + err = ray_enccol_desc_pool_bytes(e, c, j, &descs[j], &pb); + if (err) return err; + if (pb > sc->pool_cap) { /* no copy of bytes about to be overwritten */ + ray_free_raw(sc->pool); + sc->pool = NULL; + sc->pool_cap = 0; + sc->pool = ray_alloc_raw((size_t)pb); + if (!sc->pool) return ray_error("oom", "range read pool"); + sc->pool_cap = (size_t)pb; + } + } + uint64_t nb = 0; + err = ray_enccol_decode_into(e, c, j, &descs[j], sc->fixed, sc->pool, 0, &nb); + if (err) return err; /* the view is never returned */ + scratch_count(sc, e, nb); + out->data = sc->fixed + (size_t)off * ray_enccol_esz(e); + out->n = n; + out->type = e->type; + out->attrs = e->attrs; + out->may_null = descs[j].n_nulls > 0; + out->str_pool = e->type == RAY_STR ? sc->pool : NULL; + out->dom = e->type == RAY_SYM ? e->dom : NULL; + return NULL; +} + +/* The plain or encoded parted wrapper behind obj, or NULL. */ +static ray_t* parted_wrapper(ray_t* obj) { + if (obj->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of(obj); + return e->kind == RAY_ENCCOL_SINGLE ? NULL : e->wrapper; + } + return RAY_IS_PARTED(obj->type) ? obj : NULL; +} + +/* A parted source's segment row offsets (off[i] = first row of segment i, + * off[n] = len), built on the first range read and published once (workers + * share the source). A missing segment (hand-built only) holds no rows. + * The encoded wrapper and its materialization have the same segments. */ +static ray_t* src_seg_off(ray_col_src_t* s, ray_t* w, const int64_t** out) { + int64_t* a = atomic_load_explicit(&s->seg_off, memory_order_acquire); + if (!a) { + a = ray_alloc_raw((size_t)(w->len + 1) * sizeof *a); + if (!a) return ray_error("oom", "parted segment offsets"); + ray_t** segs = (ray_t**)ray_data(w); + a[0] = 0; + for (int64_t i = 0; i < w->len; i++) + a[i + 1] = a[i] + (segs[i] ? ray_table_col_nrows(segs[i]) : 0); + int64_t* exp = NULL; + if (!atomic_compare_exchange_strong_explicit(&s->seg_off, &exp, a, memory_order_acq_rel, + memory_order_acquire)) { + ray_free_raw(a); + a = exp; + } + } + *out = a; + return NULL; +} + +/* off: the parted wrapper's segment offsets (src_seg_off), NULL otherwise. */ +static ray_t* range_obj(ray_t* obj, int64_t start, int64_t n, const int64_t* off, + ray_col_scratch_t* sc, ray_col_range_t* out) { + if (obj->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of(obj); + if (e->kind == RAY_ENCCOL_SINGLE) return range_enc(e, start, n, sc, out); + obj = e->wrapper; + } + if (RAY_IS_PARTED(obj->type)) { + ray_t** segs = (ray_t**)ray_data(obj); + int64_t ns = obj->len; + if (!off || ns <= 0 || start < 0 || start >= off[ns]) + return ray_error("range", "range read past the last segment"); + int64_t lo = 0, hi = ns - 1; /* the last i with off[i] <= start */ + while (lo < hi) { + int64_t mid = lo + (hi - lo + 1) / 2; + if (off[mid] <= start) lo = mid; else hi = mid - 1; + } + int64_t sl = off[lo + 1] - off[lo]; /* > 0: start < off[lo + 1] */ + int64_t local = start - off[lo]; + if (n > sl - local) n = sl - local; /* never cross a segment */ + return range_obj(segs[lo], local, n, NULL, sc, out); + } + range_plain(obj, start, n, out); + return NULL; +} + +/* range_obj over the source's object `obj` (s->obj or its published + * materialization), with the segment offsets for a parted one. */ +static ray_t* range_src(ray_col_src_t* s, ray_t* obj, int64_t start, int64_t n, + ray_col_scratch_t* sc, ray_col_range_t* out) { + const int64_t* off = NULL; + ray_t* w = parted_wrapper(obj); + if (w) { + ray_t* err = src_seg_off(s, w, &off); + if (err) return err; + } + return range_obj(obj, start, n, off, sc, out); +} + +ray_t* ray_col_range(ray_col_src_t* src, int64_t start, int64_t n, + ray_col_scratch_t* scratch, ray_col_range_t* out) { + memset(out, 0, sizeof *out); + if (!src || !src->obj || start < 0 || n < 0 || start > src->len) + return ray_error("range", "range read [%lld, +%lld) outside %lld rows", + (long long)start, (long long)n, src ? (long long)src->len : 0LL); + out->start = start; + out->type = src->type; + out->attrs = src->attrs; + out->dom = src->dom; + if (n == 0 || start == src->len) return NULL; + ray_t* err = range_src(src, src->obj, start, n, scratch, out); + out->start = start; + return err; +} + +ray_t* ray_col_range_wide(ray_col_src_t* src, int64_t start, int64_t n, ray_col_scratch_t* sc, + int8_t wide, void* dst, int64_t* got) { + *got = 0; + if (!src || !src->obj || src->obj->type != RAY_ENCCOL || start < 0 || n <= 0 || start % RAY_ENC_VEC) return NULL; + ray_enccol_t* e = ray_enccol_of(src->obj); + if (e->kind != RAY_ENCCOL_SINGLE || start >= e->len) return NULL; + int64_t vec = start / RAY_ENC_VEC; + if (n != ray_enc_vec_len(e->len, vec)) return NULL; + int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + const ray_enc_desc_t* descs = ray_enccol_descs(e, c); + uint64_t nb = 0; + if (ray_enccol_decode_wide(e, c, (int)(vec % RAY_ENC_VECS_PER_CHUNK), &descs[vec % RAY_ENC_VECS_PER_CHUNK], + wide, dst, &nb)) { + scratch_count(sc, e, nb); + sc->wide_hits++; + *got = n; + } + return NULL; +} + +/* The vector starting at row `start` of a generation-2 vector source: + * the single file (or a parted source's segment) and the vector's local + * position; false when row `start` is not such a vector's first row. */ +static bool into_vec(ray_col_src_t* s, int64_t start, ray_enccol_t** ep, int64_t* local, ray_t** err) { + ray_t* obj = s->obj; + *err = NULL; + if (!obj || obj->type != RAY_ENCCOL || ray_enccol_decoded_peek(obj)) return false; /* published: read in place */ + ray_enccol_t* e = ray_enccol_of(obj); + if (e->kind != RAY_ENCCOL_SINGLE) { + const int64_t* off = NULL; + ray_t* w = e->wrapper; + if ((*err = src_seg_off(s, w, &off)) != NULL) return false; + int64_t ns = w->len; + if (ns <= 0 || start >= off[ns]) return false; + int64_t lo = 0, hi = ns - 1; /* the last i with off[i] <= start */ + while (lo < hi) { + int64_t mid = lo + (hi - lo + 1) / 2; + if (off[mid] <= start) lo = mid; else hi = mid - 1; + } + ray_t* sg = ((ray_t**)ray_data(w))[lo]; + if (!sg || sg->type != RAY_ENCCOL) return false; + e = ray_enccol_of(sg); + if (e->kind != RAY_ENCCOL_SINGLE) return false; + start -= off[lo]; + } + if (start % RAY_ENC_VEC || start >= e->len) return false; + *ep = e; + *local = start; + return true; +} + +static _Atomic(uint64_t) g_into_calls, g_into_rows; /* test hook */ +void ray_col_test_into(uint64_t* calls, uint64_t* rows) { + *calls = atomic_load(&g_into_calls); + *rows = atomic_load(&g_into_rows); +} + +ray_t* ray_col_range_into(ray_col_src_t* src, int64_t start, int64_t n, ray_col_scratch_t* sc, + uint8_t attrs, void* dst, int64_t* got) { + *got = 0; + if (!src || start < 0 || n <= 0 || start >= src->len) return NULL; + ray_enccol_t* e; + int64_t local; + ray_t* err; + if (!into_vec(src, start, &e, &local, &err)) return err; + if (e->type == RAY_STR || e->type == RAY_GUID) return NULL; + if (e->type == RAY_SYM && ((e->attrs ^ attrs) & RAY_SYM_W_MASK)) return NULL; /* another width: widen by range */ + int64_t vec = local / RAY_ENC_VEC; + int64_t vlen = ray_enc_vec_len(e->len, vec); + if (vlen > n) return NULL; + int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + int j = (int)(vec % RAY_ENC_VECS_PER_CHUNK); + const ray_enc_desc_t* descs = ray_enccol_descs(e, c); + const size_t esz = ray_enccol_esz(e); + const char* pv = ray_enccol_raw_view(e, c, j, &descs[j]); + if (!pv) { + uint64_t nb = 0; + if ((err = ray_enccol_decode_into(e, c, j, &descs[j], dst, NULL, 0, &nb)) != NULL) return err; + scratch_count(sc, e, nb); + *got = vlen; + atomic_fetch_add_explicit(&g_into_calls, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&g_into_rows, (uint64_t)vlen, memory_order_relaxed); + return NULL; + } + /* RAW vectors are their own decode (as range_enc reads them): the run + * of them whose payloads lie end to end in the mapping is one copy (a + * large copy streams; a vector at a time took twice a plain segment's + * copy, ClickBench q32's WatchID on partitions) */ + int64_t rows = vlen; + while (rows < n && local + rows < e->len) { + int64_t v2 = (local + rows) / RAY_ENC_VEC, l2 = ray_enc_vec_len(e->len, v2); + if (rows + l2 > n) break; + int64_t c2 = v2 / RAY_ENC_VECS_PER_CHUNK; + int j2 = (int)(v2 % RAY_ENC_VECS_PER_CHUNK); + const ray_enc_desc_t* d2 = ray_enccol_descs(e, c2); + if (ray_enccol_raw_view(e, c2, j2, &d2[j2]) != pv + (size_t)rows * esz) break; + rows += l2; + } + memcpy(dst, pv, (size_t)rows * esz); + if (e->type != RAY_F64 && e->type != RAY_F32) scratch_count(sc, e, (uint64_t)rows * esz); + *got = rows; + atomic_fetch_add_explicit(&g_into_calls, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&g_into_rows, (uint64_t)rows, memory_order_relaxed); + return NULL; +} + +ray_t* ray_col_src_plain(ray_col_src_t* s, ray_t** out) { + *out = NULL; + if (!s || !s->obj) return ray_error("type", "source not bound"); + if (s->obj->type != RAY_ENCCOL) { *out = s->obj; return NULL; } + ray_t* p = ray_enccol_materialize(s->obj); /* the object's once-state, cached */ + if (RAY_IS_ERR(p)) return p; + *out = p; + return NULL; +} + +int64_t ray_col_src_sym_find(const ray_col_src_t* s, const char* str, size_t len) { + if (!s || s->type != RAY_SYM || !s->dom) return -1; + return ray_sym_domain_find(s->dom, str, len); +} + +/* Codes are assigned by first occurrence (not sorted), so there is no + * persisted string->code map: scan the n_distinct first-occurrence rows. */ +int64_t ray_col_src_dict_code(const ray_col_src_t* s, const char* str, size_t len) { + if (!s || s->type != RAY_STR || !s->obj || s->obj->type == RAY_ENCCOL || s->parted) return -2; + ray_t* col = s->obj; + if (ray_index_kind(col) != RAY_IDX_DICT) return -2; + const ray_index_t* dix = ray_index_payload(col->index); + int64_t nd = dix->u.dict.n_distinct; + if (nd <= 0 || !dix->u.dict.first_occ || RAY_IS_ERR(dix->u.dict.first_occ)) return -1; + const int32_t* focc = (const int32_t*)ray_data(dix->u.dict.first_occ); + for (int64_t c = 0; c < nd; c++) { + size_t l = 0; + const char* p = ray_str_vec_get(col, focc[c], &l); + if (!p) continue; + if (l == len && (len == 0 || memcmp(p, str, len) == 0)) return c; + } + return -1; +} + +/* ---- Scan side: cursors, the piece walk, the failure envelope ---- */ + +uint8_t ray_col_src_esz(const ray_col_src_t* s) { return ray_sym_elem_size(s->type, s->attrs); } + +ray_t* ray_col_src_ready(const ray_col_src_t* s) { + if (!s || !s->obj) return NULL; + if (s->obj->type != RAY_ENCCOL) return s->obj; + return ray_enccol_decoded_peek(s->obj); /* published materialization, or NULL */ +} + +const void* ray_col_src_base(const ray_col_src_t* s) { + ray_t* rd = ray_col_src_ready(s); + return (rd && !RAY_IS_PARTED(rd->type)) ? ray_data(rd) : NULL; +} + +void ray_col_cursor_init(ray_col_cursor_t* c, ray_col_src_t* src) { + memset(c, 0, sizeof *c); + c->src = src; + ray_col_scratch_init(&c->sc); +} + +void ray_col_cursor_init_lent(ray_col_cursor_t* c, ray_col_src_t* src, ray_col_fixed_t* buf) { + ray_col_cursor_init(c, src); + ray_col_scratch_lend(&c->sc, buf); +} + +void ray_col_cursor_free(ray_col_cursor_t* c) { + ray_col_scratch_free(&c->sc); + memset(c, 0, sizeof *c); +} + +ray_t* ray_col_cursor_at(ray_col_cursor_t* c, int64_t r, const ray_col_range_t** out) { + *out = NULL; + if (c->have && r >= c->v.start && r < c->v.start + c->v.n) { *out = &c->v; return NULL; } + ray_col_src_t* s = c->src; + if (!s || !s->obj || r < 0 || r >= s->len) return ray_error("range", "scan cursor: row %lld", (long long)r); + c->have = false; + /* A published materialization is read in place (single: a plain vector; + * parted: the plain parted wrapper, read segment by segment). */ + ray_t* obj = s->obj; + if (obj->type == RAY_ENCCOL) { + ray_t* pk = ray_enccol_decoded_peek(obj); + if (pk) obj = pk; + } + memset(&c->v, 0, sizeof c->v); + c->v.start = r; + c->v.type = s->type; + c->v.attrs = s->attrs; + c->v.dom = s->dom; + ray_t* err = range_src(s, obj, r, s->len - r, &c->sc, &c->v); /* ray_col_range's body, same clipping */ + c->v.start = r; + if (err) return err; + if (c->v.n <= 0) return ray_error("range", "scan cursor: empty range read at row %lld", (long long)r); + c->have = true; + *out = &c->v; + return NULL; +} + +/* A plain source's piece fields other than data, fixed for the call. */ +static ray_col_piece_t plain_piece(const ray_col_src_t* s) { + ray_col_piece_t p = { 0 }; + p.attrs = s->attrs; + p.may_null = s->may_null; + p.dom = s->dom; + if (s->type == RAY_STR) { + ray_t* rd = ray_col_src_ready(s); + if (rd && !RAY_IS_PARTED(rd->type)) { + ray_t* own = plain_owner(rd); + if (own->str_pool && !RAY_IS_ERR(own->str_pool)) p.str_pool = (const char*)ray_data(own->str_pool); + } + } + return p; +} + +/* The piece loop of a non-contiguous walk over cursors cur (one per cursor + * source; their views persist past the call) and the fixed fields pc. */ +static ray_t* walk_pieces(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + ray_col_cursor_t* cur, ray_col_piece_t* pc, int64_t lo, int64_t hi, + void* ctx, uint32_t wid, ray_col_piece_fn fn) { + ray_t* err = NULL; + for (int64_t b = lo; b < hi && !err; ) { + int64_t e = hi; + for (uint32_t i = 0; i < n; i++) { + ray_col_src_t* s = srcs[i]; + if (!s) continue; + if (plain[i]) { pc[i].data = (const char*)plain[i] + (size_t)b * ray_col_src_esz(s); continue; } + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(&cur[i], b, &v)) != NULL) break; + uint8_t vesz = ray_sym_elem_size(v->type, v->attrs); + pc[i].data = (const char*)v->data + (size_t)(b - v->start) * vesz; + pc[i].attrs = v->attrs; pc[i].may_null = v->may_null; + pc[i].str_pool = v->str_pool; pc[i].dom = v->dom; + if (v->start + v->n < e) e = v->start + v->n; + } + if (err) break; + fn(ctx, wid, b, e, pc); + b = e; + } + return err; +} + +#define WALK_STACK 16 +ray_t* ray_col_walk_cur(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + ray_col_cursor_t* cur, int64_t lo, int64_t hi, + void* ctx, uint32_t wid, ray_col_piece_fn fn) { + if (lo >= hi) return NULL; + ray_col_piece_t pst[WALK_STACK]; + ray_col_piece_t* pc = n > WALK_STACK ? ray_calloc_raw((size_t)n * sizeof *pc) : pst; + if (!pc) return ray_error("oom", "scan walk"); + bool any_cursor = false; + for (uint32_t i = 0; i < n; i++) { + pc[i] = srcs[i] ? plain_piece(srcs[i]) : (ray_col_piece_t){ 0 }; + any_cursor |= srcs[i] && !plain[i]; + } + ray_t* err = NULL; + if (any_cursor) { + err = walk_pieces(srcs, plain, n, cur, pc, lo, hi, ctx, wid, fn); + } else { + for (uint32_t i = 0; i < n; i++) + if (srcs[i]) pc[i].data = (const char*)plain[i] + (size_t)lo * ray_col_src_esz(srcs[i]); + fn(ctx, wid, lo, hi, pc); + } + if (pc != pst) ray_free_raw(pc); + return err; +} + +ray_t* ray_col_walk(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + int64_t lo, int64_t hi, bool contiguous, + void* ctx, uint32_t wid, ray_col_piece_fn fn) { + if (lo >= hi) return NULL; + if (contiguous && hi - lo > RAY_COL_BLOCK_ROWS) + return ray_error("range", "scan walk: contiguous block of %lld rows", (long long)(hi - lo)); + ray_col_cursor_t cst[WALK_STACK]; ray_col_piece_t pst[WALK_STACK]; void* bst[WALK_STACK]; + ray_col_cursor_t* cur = cst; ray_col_piece_t* pc = pst; void** buf = bst; + if (n > WALK_STACK) { + cur = ray_calloc_raw((size_t)n * sizeof *cur); + pc = ray_calloc_raw((size_t)n * sizeof *pc); + buf = ray_calloc_raw((size_t)n * sizeof *buf); + if (!cur || !pc || !buf) { ray_free_raw(cur); ray_free_raw(pc); ray_free_raw(buf); return ray_error("oom", "scan walk"); } + } + /* Plain and skipped sources get their fixed fields once; only cursor + * sources hold a cursor (and, contiguous, a buffer) and are re-read per + * piece. */ + bool any_cursor = false; + for (uint32_t i = 0; i < n; i++) { + pc[i] = srcs[i] ? plain_piece(srcs[i]) : (ray_col_piece_t){ 0 }; + if (srcs[i] && !plain[i]) { + ray_col_cursor_init(&cur[i], srcs[i]); + buf[i] = NULL; + any_cursor = true; + } + } + ray_t* err = NULL; + if (contiguous) { + for (uint32_t i = 0; i < n && !err; i++) { + ray_col_src_t* s = srcs[i]; + if (!s) continue; + uint8_t esz = ray_col_src_esz(s); + if (plain[i]) { pc[i].data = (const char*)plain[i] + (size_t)lo * esz; continue; } + if (s->type != RAY_F32 && s->type != RAY_F64) { err = ray_error("nyi", "scan walk: contiguous non-float source"); break; } + const ray_col_range_t* v; + if ((err = ray_col_cursor_at(&cur[i], lo, &v)) != NULL) break; + if (v->start + v->n >= hi) { /* one view covers the block: no copy */ + pc[i].data = (const char*)v->data + (size_t)(lo - v->start) * esz; + pc[i].may_null = v->may_null; + continue; + } + buf[i] = ray_alloc_raw((size_t)(hi - lo) * esz); + if (!buf[i]) { err = ray_error("oom", "scan walk block"); break; } + bool mn = false; + for (int64_t r = lo; r < hi; ) { + if ((err = ray_col_cursor_at(&cur[i], r, &v)) != NULL) break; + int64_t take = v->start + v->n - r; if (take > hi - r) take = hi - r; + memcpy((char*)buf[i] + (size_t)(r - lo) * esz, (const char*)v->data + (size_t)(r - v->start) * esz, (size_t)take * esz); + mn |= v->may_null; + r += take; + } + pc[i].data = buf[i]; + pc[i].may_null = mn; + } + if (!err) fn(ctx, wid, lo, hi, pc); + } else if (!any_cursor) { + /* Every source in place: one piece, no cursor reads. */ + for (uint32_t i = 0; i < n; i++) + if (srcs[i]) pc[i].data = (const char*)plain[i] + (size_t)lo * ray_col_src_esz(srcs[i]); + fn(ctx, wid, lo, hi, pc); + } else { + err = walk_pieces(srcs, plain, n, cur, pc, lo, hi, ctx, wid, fn); + } + if (any_cursor) + for (uint32_t i = 0; i < n; i++) + if (srcs[i] && !plain[i]) { ray_col_cursor_free(&cur[i]); ray_free_raw(buf[i]); } + if (n > WALK_STACK) { ray_free_raw(cur); ray_free_raw(pc); ray_free_raw(buf); } + return err; +} + +void ray_scan_fail_init(ray_scan_fail_t* f) { + memset(f, 0, sizeof *f); + atomic_store(&f->key, INT64_MAX); +} + +void ray_scan_fail_note(ray_scan_fail_t* f, int64_t key, ray_t* err) { + while (atomic_exchange_explicit(&f->lock, 1, memory_order_acquire)) RAY_CPU_RELAX(); + if (key < atomic_load_explicit(&f->key, memory_order_relaxed)) { + ray_enc_snap_take(&f->snap, err); /* snapshots on this thread, frees err */ + atomic_store_explicit(&f->key, key, memory_order_release); + } else { + ray_error_free(err); + } + atomic_store_explicit(&f->lock, 0, memory_order_release); +} + +ray_t* ray_scan_fail_error(ray_scan_fail_t* f) { + if (!ray_scan_failed(f)) return NULL; + /* The snapshot is written under the lock: copy it there so a note + * racing a late reader cannot tear it. */ + while (atomic_exchange_explicit(&f->lock, 1, memory_order_acquire)) RAY_CPU_RELAX(); + ray_enc_snap_t snap = f->snap; + atomic_store_explicit(&f->lock, 0, memory_order_release); + return ray_enc_snap_error(&snap); /* allocates outside the lock */ +} + +ray_t* ray_scan_fail_finish(ray_scan_fail_t* f, ray_pool_t* pool) { + if (ray_scan_failed(f)) return ray_scan_fail_error(f); + if (ray_interrupted() || (pool && atomic_load_explicit(&pool->cancelled, memory_order_acquire))) + return ray_error("cancel", "scan: interrupted"); + return NULL; +} + +/* ---- Directory statistics and read-ahead ---- */ + +bool ray_col_src_chunk_stat(const ray_col_src_t* s, int64_t c, struct ray_enc_chunk_stat_s* out) { + if (!ray_col_src_encoded(s)) return false; + ray_enccol_t* e = ray_enccol_of(s->obj); + if (e->kind != RAY_ENCCOL_SINGLE || c < 0 || c >= e->n_chunks) return false; + ray_enccol_chunk_stat(e, c, out); + return true; +} + +bool ray_col_src_vec_stat(const ray_col_src_t* s, int64_t v, int64_t* min, int64_t* max, uint32_t* n_nulls) { + if (!ray_col_src_encoded(s)) return false; + ray_enccol_t* e = ray_enccol_of(s->obj); + if (e->kind != RAY_ENCCOL_SINGLE || e->synthetic || e->type == RAY_STR || v < 0 || v * RAY_ENC_VEC >= e->len) return false; + const ray_enc_desc_t* d = &ray_enccol_descs(e, v / RAY_ENC_VECS_PER_CHUNK)[v % RAY_ENC_VECS_PER_CHUNK]; + if (d->flags & RAY_ENC_STAT_ABSENT) return false; + *min = d->min; *max = d->max; *n_nulls = d->n_nulls; + return true; +} + +int ray_col_src_vview(const ray_col_src_t* s, int64_t v, ray_enc_vview_t* out, ray_t** err) { + *err = NULL; + if (!ray_col_src_encoded(s) || ray_enccol_decoded_peek(s->obj)) return 0; /* read it in place */ + return ray_enccol_vview(ray_enccol_of(s->obj), v, out, err); /* declines parted and synthetic */ +} + +bool ray_col_src_parted_chunks(ray_col_src_t* s, void* ctx, ray_col_chunk_fn fn, ray_t** err) { + *err = NULL; + if (!s || !s->obj || !s->parted) return false; + ray_t* w = parted_wrapper(s->obj); + if (!w) return false; + const int64_t* off; + if ((*err = src_seg_off(s, w, &off)) != NULL) return false; + ray_t** segs = (ray_t**)ray_data(w); + for (int64_t i = 0; i < w->len; i++) { + int64_t sl = off[i + 1] - off[i]; + ray_enccol_t* e = segs[i] && segs[i]->type == RAY_ENCCOL ? ray_enccol_of(segs[i]) : NULL; + if (e && (e->kind != RAY_ENCCOL_SINGLE || e->len != sl)) e = NULL; + for (int64_t c = 0; c * RAY_ENC_CHUNK < sl; c++) { + int64_t lo = off[i] + c * RAY_ENC_CHUNK; + int64_t hi = lo + RAY_ENC_CHUNK < off[i + 1] ? lo + RAY_ENC_CHUNK : off[i + 1]; + ray_enc_chunk_stat_t st; + if (e) ray_enccol_chunk_stat(e, c, &st); + fn(ctx, lo, hi, e ? &st : NULL); + } + } + return true; +} + +bool ray_col_src_parted_segs(ray_col_src_t* s, int64_t* n, ray_t*** segs, const int64_t** off, ray_t** err) { + *err = NULL; + if (!s || !s->obj || !s->parted) return false; + ray_t* w = parted_wrapper(s->obj); + if (!w) return false; + if ((*err = src_seg_off(s, w, off)) != NULL) return false; + *n = w->len; + *segs = (ray_t**)ray_data(w); + return true; +} + +/* The single-file encoded column holding row `row` of a generation-2 + * source, not materialized: the column itself, or the row's parted segment + * when that is one (*seg0 its first row); NULL for anything else, read by + * a cursor. */ +static ray_enccol_t* src_point_col(ray_col_src_t* s, int64_t row, int64_t* seg0, int64_t* seg1) { + if (!ray_col_src_encoded(s) || ray_enccol_decoded_peek(s->obj)) return NULL; /* the cursor reads it in place */ + ray_enccol_t* e = ray_enccol_of(s->obj); + if (e->kind == RAY_ENCCOL_SINGLE) { *seg0 = 0; *seg1 = e->len; return e; } + /* parted: the row's segment, when it is a single-file encoded one */ + ray_t* w = parted_wrapper(s->obj); + const int64_t* off; + if (!w || w->len <= 0 || row < 0 || row >= s->len) return NULL; + ray_t* oerr = src_seg_off(s, w, &off); /* seg_off: published once, atomically */ + if (oerr) { ray_error_free(oerr); return NULL; } /* the cursor reports it */ + int64_t lo = 0, hi = w->len - 1; /* the last i with off[i] <= row */ + while (lo < hi) { + int64_t mid = lo + (hi - lo + 1) / 2; + if (off[mid] <= row) lo = mid; else hi = mid - 1; + } + ray_t* sg = ((ray_t**)ray_data(w))[lo]; + if (!sg || sg->type != RAY_ENCCOL || ray_enccol_decoded_peek(sg)) return NULL; + ray_enccol_t* se = ray_enccol_of(sg); + if (se->kind != RAY_ENCCOL_SINGLE) return NULL; + *seg0 = off[lo]; *seg1 = off[lo + 1]; + return se; +} + +int ray_col_src_point_i64(ray_col_src_t* s, int64_t row, int64_t* out, ray_t** err) { + *err = NULL; + int64_t s0, s1; + ray_enccol_t* e = src_point_col(s, row, &s0, &s1); + return e ? ray_enccol_point_i64(e, row - s0, out, err) : 0; +} + +int ray_col_src_points_i64(ray_col_src_t* s, const int64_t* rows, int64_t n, int64_t* out, ray_t** err) { + *err = NULL; + int64_t s0, s1; + ray_enccol_t* e = n > 0 ? src_point_col(s, rows[0], &s0, &s1) : NULL; + return e ? ray_enccol_points_i64(e, rows, n, s0, out, err) : 0; +} + +int ray_col_src_gather_points(ray_col_src_t* s, const int64_t* rows, int64_t n, int64_t* out, uint8_t* nul, + ray_t** err) { + *err = NULL; + int64_t s0, s1; + ray_enccol_t* e = n > 0 ? src_point_col(s, rows[0], &s0, &s1) : NULL; + return e ? ray_enccol_gather_points(e, rows, n, s0, out, nul, err) : 0; +} + +bool ray_col_src_vec_span(ray_col_src_t* s, int64_t row, int64_t* lo, int64_t* hi) { + int64_t s0, s1; + ray_enccol_t* e = src_point_col(s, row, &s0, &s1); + if (!e || row < s0 || row >= s1) return false; + *lo = s0 + ((row - s0) & ~(int64_t)(RAY_ENC_VEC - 1)); + *hi = *lo + RAY_ENC_VEC < s1 ? *lo + RAY_ENC_VEC : s1; + return true; +} + +int ray_col_src_runview(ray_col_src_t* s, int64_t row, ray_enc_vview_t* out, int64_t* lo, int64_t* hi, ray_t** err) { + *err = NULL; + *lo = row; *hi = row + 1; + if (!s || !s->obj || row < 0 || row >= s->len) return 0; + int64_t s0 = 0, s1 = s->len; /* the rows that read alike: source, segment */ + ray_enccol_t* e = NULL; + if (ray_col_src_encoded(s) && !ray_enccol_decoded_peek(s->obj)) { + ray_enccol_t* ce = ray_enccol_of(s->obj); + if (ce->kind == RAY_ENCCOL_SINGLE) e = ce; + else { + ray_t* w = parted_wrapper(s->obj); + const int64_t* off; + if (!w || w->len <= 0) return 0; + ray_t* oerr = src_seg_off(s, w, &off); + if (oerr) { ray_error_free(oerr); return 0; } /* the cursor reports it */ + int64_t a = 0, b = w->len - 1; /* the last i with off[i] <= row */ + while (a < b) { + int64_t mid = a + (b - a + 1) / 2; + if (off[mid] <= row) a = mid; else b = mid - 1; + } + s0 = off[a]; s1 = off[a + 1]; + ray_t* sg = ((ray_t**)ray_data(w))[a]; + if (sg && sg->type == RAY_ENCCOL && !ray_enccol_decoded_peek(sg) && + ray_enccol_of(sg)->kind == RAY_ENCCOL_SINGLE) + e = ray_enccol_of(sg); + } + } + if (!e || e->synthetic) { *lo = s0; *hi = s1; return 0; } /* a plain or stand-in segment: read alike */ + const int64_t vec = (row - s0) / RAY_ENC_VEC; + const int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + const int j = (int)(vec % RAY_ENC_VECS_PER_CHUNK); + *lo = s0 + vec * RAY_ENC_VEC; + *hi = *lo + RAY_ENC_VEC < s1 ? *lo + RAY_ENC_VEC : s1; + const uint8_t enc = ray_enccol_descs(e, c)[j].encoding; + if ((enc != RAY_ENC_RLE && enc != RAY_ENC_CONST) || e->type == RAY_F32 || e->type == RAY_F64) + return 0; /* no other codec builds a view */ + int r = ray_enccol_vview(e, vec, out, err); + if (r <= 0) return r; + if (out->enc != enc || out->nullmap || out->n != *hi - *lo) return 0; + return 1; +} + +/* One read-ahead span: page-aligned start, bytes. */ +typedef void (*advise_emit_fn)(void* ctx, uintptr_t start, size_t len); + +/* Round p down to the host page. Every mapping starts on a page boundary + * (mmap), so the rounded start stays inside it. */ +static uintptr_t page_down(uintptr_t p) { + return p & ~(uintptr_t)(ray_vm_page_size() - 1); +} + +/* The spans of rows [lo, hi) of obj (within its rows), one per touched + * mapping: a generation-2 column's chunk bytes from its directory, a plain + * mapped column's element bytes, each touched segment of a parted one; a + * heap vector has none. A synthetic segment lives in an anonymous mapping: + * its span is as harmless a hint as a file's. */ +static void advise_spans(ray_t* obj, int64_t lo, int64_t hi, advise_emit_fn emit, void* ctx) { + if (!obj || lo >= hi) return; + if (obj->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of(obj); + if (e->kind == RAY_ENCCOL_PARTED) { advise_spans(e->wrapper, lo, hi, emit, ctx); return; } + uint64_t off, len; + ray_enccol_byte_range(e, lo, hi, &off, &len); + uintptr_t p = (uintptr_t)(e->base + off), a = page_down(p); + emit(ctx, a, (size_t)(p + len - a)); + return; + } + if (RAY_IS_PARTED(obj->type)) { + ray_t** segs = (ray_t**)ray_data(obj); + int64_t acc = 0; + for (int64_t i = 0; i < obj->len && acc < hi; i++) { + int64_t sl = segs[i] ? ray_table_col_nrows(segs[i]) : 0; + int64_t a = lo > acc ? lo - acc : 0, b = hi - acc < sl ? hi - acc : sl; + if (a < b) advise_spans(segs[i], a, b, emit, ctx); + acc += sl; + } + return; + } + ray_t* own = plain_owner(obj); + if (own->mmod != 1) return; /* heap vector: nothing to hint */ + int64_t base_row = (obj->attrs & RAY_ATTR_SLICE) ? obj->slice_offset : 0; + uint8_t esz = ray_sym_elem_size(own->type, own->attrs); + uintptr_t p = (uintptr_t)ray_data(own) + (uintptr_t)(base_row + lo) * esz; + uintptr_t a = page_down(p); + emit(ctx, a, (size_t)(p + (uintptr_t)(hi - lo) * esz - a)); +} + +static void advise_emit(void* ctx, uintptr_t start, size_t len) { + (void)ctx; + ray_vm_advise_seq((void*)start, len); +} + +/* [lo, hi) clipped to the source's rows. */ +static void advise_walk(const ray_col_src_t* s, int64_t lo, int64_t hi, advise_emit_fn emit, void* ctx) { + if (!s || !s->obj) return; + if (lo < 0) lo = 0; + if (hi > s->len) hi = s->len; + advise_spans(s->obj, lo, hi, emit, ctx); +} + +void ray_col_src_advise(const ray_col_src_t* s, int64_t lo, int64_t hi) { + advise_walk(s, lo, hi, advise_emit, NULL); +} + +typedef struct { uintptr_t* start; size_t* len; int cap, n; } advise_collect_t; +static void advise_collect(void* ctx, uintptr_t start, size_t len) { + advise_collect_t* c = ctx; + if (c->n < c->cap) { c->start[c->n] = start; c->len[c->n] = len; } + c->n++; +} + +int ray_col_src_test_advise_spans(const ray_col_src_t* s, int64_t lo, int64_t hi, + uintptr_t* start, size_t* len, int cap) { + advise_collect_t c = { start, len, cap, 0 }; + advise_walk(s, lo, hi, advise_collect, &c); + return c.n; +} diff --git a/src/store/colrange.h b/src/store/colrange.h new file mode 100644 index 000000000..f3eafc5de --- /dev/null +++ b/src/store/colrange.h @@ -0,0 +1,358 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_COLRANGE_H +#define RAY_COLRANGE_H + +#include +#include +#include "store/enc_once.h" +#include "ops/ops.h" /* RAY_DISPATCH_MORSELS, RAY_MORSEL_ELEMS: the pool's task grain */ + +struct ray_sym_domain_s; +struct ray_enc_chunk_stat_s; /* store/enccol.h */ +struct ray_enc_vview_s; /* store/enccol.h */ + +/* A bound column source: the object a scan reads ranges of. Binding + * retains the object (and a non-runtime SYM domain) and never decodes. + * The struct owns seg_off: never copy it by value (bind it in place, share + * it by pointer, release it once). */ +typedef struct { + ray_t* obj; /* retained: plain vector, slice, RAY_ENCCOL, or plain parted wrapper */ + struct ray_sym_domain_s* dom; /* SYM: the domain ids resolve over */ + bool dom_owned; /* dom was retained */ + int8_t type; /* logical element type (parted: base) */ + uint8_t attrs; /* persisted attrs; parted: not authoritative, see ray_col_range */ + int64_t len; /* rows (parted: sum over segments) */ + bool may_null; /* HAS_NULLS, or directory null counts for generation 2 */ + bool parted; /* a parted source (per-range attrs are authoritative) */ + _Atomic(int64_t*) seg_off; /* parted: segment row offsets (n_segs + 1), built on the + * first range read, published once, owned (a by-value + * copy would free it twice), freed on release */ +} ray_col_src_t; + +/* A view of rows [start, start + n): elements in the generation-0 + * representation, nulls in-band. */ +typedef struct { + const void* data; + bool may_null; + int8_t type; + uint8_t attrs; + int64_t start, n; + const char* str_pool; /* STR: base of pooled ray_str_t offsets */ + struct ray_sym_domain_s* dom; /* SYM: the domain the ids resolve over */ +} ray_col_range_t; + +/* Per-source scratch for generation-2 decodes: one fixed vector (1024 + * elements of the widest width, 16 KB) and a growable STR pool, both from + * ray_alloc_raw. Serves one source in one scan task. The bytes it decodes + * are counted (ray_enc_counters_get, the column's decoded_bytes) when the + * scratch moves to another column or is freed, not per vector; the scratch + * holds a reference on that column meanwhile, so it may outlive its source. + * A RAW vector read in place (ray_enccol_raw_view) decodes nothing: an + * integer one (SYM included) still counts the bytes it delivers, so a key's + * read-once counts hold whatever its vectors' encodings; a float one + * counts none. */ +typedef struct { + uint8_t* fixed; + bool fixed_lent; /* fixed is the caller's (ray_col_scratch_lend): never freed here */ + char* pool; + size_t pool_cap; + struct ray_enccol_s* acc_e; /* the column acc_bytes belong to (a reference) */ + uint64_t acc_bytes; /* decoded, not yet counted */ + uint64_t wide_hits; /* ray_col_range_wide decodes, not yet counted */ +} ray_col_scratch_t; + +/* The fixed vector a scan task lends its scratch from its own stack, so + * a worker's first decode allocates nothing: a fresh worker heap maps and + * faults in a whole pool on its first allocation, a fixed cost per worker + * that generation 0, reading its columns in place, never pays. One per + * scratch, alive until the scratch is freed. */ +#define RAY_COL_FIXED_BYTES ((size_t)1024 * 16) /* one vector of the widest element (GUID) */ +typedef struct { _Alignas(64) uint8_t b[RAY_COL_FIXED_BYTES]; } ray_col_fixed_t; + +/* NULL or an owned error (ray_error_free). */ +ray_t* ray_col_src_bind(ray_t* col, ray_col_src_t* out); +void ray_col_src_release(ray_col_src_t* s); +void ray_col_scratch_init(ray_col_scratch_t* s); +void ray_col_scratch_free(ray_col_scratch_t* s); +/* An initialised scratch decodes into buf (the caller's, outliving the + * scratch's use) instead of a fixed vector from the heap. */ +void ray_col_scratch_lend(ray_col_scratch_t* s, ray_col_fixed_t* buf); +/* Test hook: fixed vectors range reads took from the heap since process + * start (a lent scratch takes none). */ +uint64_t ray_col_test_fixed_allocs(void); + +/* Range of [start, start + n), clipped at the source end, at a parted + * segment or slice boundary and (generation 2) at the next vector boundary; + * `out->n` says how many rows were returned (0 only at the source end or + * for n == 0). Generation 0 is zero copy; generation 2 decodes the vector + * into `scratch`. The view is valid until the next call with the same + * scratch or until the source is released. A loaded parted source has no + * missing segment (ray_read_parted gives a ragged partition's absent + * column a segment of nulls, #724); a hand-built wrapper's missing segment holds no rows, + * matching ray_parted_nrows, and the executor refuses a table whose parted + * columns' row counts differ, so a scan never reads one. + * For a parted source the SYM element width and SORTED are per range only + * (segments may differ): read them from the view's `attrs`, never from the + * source's. */ +ray_t* ray_col_range(ray_col_src_t* src, int64_t start, int64_t n, + ray_col_scratch_t* scratch, ray_col_range_t* out); + +/* Rows [start, start + n) decoded straight into dst as `wide` (RAY_I64 / + * RAY_F64) elements, nulls as NULL_I64 / NULL_F64 (an expression + * register), when they are exactly one whole vector of a single-file + * generation-2 source that ray_enccol_decode_wide takes: *got = n. Else + * *got = 0 and nothing is decoded: read the rows with ray_col_range. NULL + * or an owned error. */ +ray_t* ray_col_range_wide(ray_col_src_t* src, int64_t start, int64_t n, ray_col_scratch_t* scratch, + int8_t wide, void* dst, int64_t* got); + +/* The vector of a generation-2 source (single file, or a parted source's + * encoded segment, neither with a published materialization) that starts + * at row `start`, decoded straight into dst at the generation-0 width, + * when it ends inside [start, start + n) and is not STR or GUID (SYM: of + * the width in `attrs`): *got = its rows (a RAW vector: with the RAW + * vectors after it inside the range, copied at once). Else *got = 0 and nothing is + * read: read the rows with ray_col_range or a cursor. dst may hold a + * partial vector on an error. NULL or an owned error. */ +ray_t* ray_col_range_into(ray_col_src_t* src, int64_t start, int64_t n, ray_col_scratch_t* sc, + uint8_t attrs, void* dst, int64_t* got); +/* Test hook: ray_col_range_into's deliveries and the rows they held + * since process start. */ +void ray_col_test_into(uint64_t* calls, uint64_t* rows); + +/* Test hook: vectors ray_col_range_wide decoded since process start + * (counted when their scratch is freed). */ +uint64_t ray_col_test_wide_hits(void); + +/* Bind a table column without decoding; an absent column leaves out->obj + * NULL and returns NULL. */ +ray_t* ray_table_col_src(ray_t* tbl, int64_t name_id, ray_col_src_t* out); + +/* The bound source's plain column (borrowed; valid while the source is + * bound): the object itself for generation 0, the cached materialization + * for generation 2. NULL or an owned error. */ +ray_t* ray_col_src_plain(ray_col_src_t* s, ray_t** out); +/* Literal translation into the source's SYM domain, without decoding: + * the position of the bytes, -1 when absent. */ +int64_t ray_col_src_sym_find(const ray_col_src_t* s, const char* str, size_t len); +/* STR dictionary code of a constant: >= 0 the code, -1 provably absent, + * -2 no dictionary to resolve against (generation 2 in P1: STR_DICT + * arrives in P6). Reads only the generation-0 column's DICT index. */ +int64_t ray_col_src_dict_code(const ray_col_src_t* s, const char* str, size_t len); + +/* ---- Scan side: cursors, the piece walk, the failure envelope ---- */ + +/* The contiguous-mode block bound: the pool's task grain (8192 rows). */ +#define RAY_COL_BLOCK_ROWS (RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS) + +/* The source's object is a RAY_ENCCOL (generation 2, or a parted column + * with an encoded or synthetic segment). */ +static inline bool ray_col_src_encoded(const ray_col_src_t* s) { + return s && s->obj && s->obj->type == RAY_ENCCOL; +} + +/* The plain column a scan can read in place, without decoding: a plain + * object (vector, slice, plain parted wrapper) itself, or a RAY_ENCCOL's + * published materialization; NULL when reading it would decode. + * Borrowed from the source; never decodes. */ +ray_t* ray_col_src_ready(const ray_col_src_t* s); +/* The base pointer (row 0) a scan reads the source at in place: the ready + * plain vector's data; NULL when it must be read by range (not ready, or a + * parted wrapper, which has no single base). Never decodes. */ +const void* ray_col_src_base(const ray_col_src_t* s); +/* Generation-0 element width of the source (SYM: its persisted width). */ +uint8_t ray_col_src_esz(const ray_col_src_t* s); + +/* Chunk c's statistics when the source is a single-file generation-2 + * column; false otherwise (plain, parted, slice). */ +bool ray_col_src_chunk_stat(const ray_col_src_t* s, int64_t c, struct ray_enc_chunk_stat_s* out); +/* Vector v's statistics (rows [v * RAY_ENC_VEC, + RAY_ENC_VEC), the + * vector's descriptor, nested inside the chunk's statistics) when the + * source is a single-file generation-2 column and the vector carries them: + * min / max are logical_T values as ray_enc_chunk_stat_t's, n_nulls the + * vector's null count. False otherwise: not such a source, v outside it, + * or statistics absent (every row null, or a type without them). */ +bool ray_col_src_vec_stat(const ray_col_src_t* s, int64_t v, int64_t* min, int64_t* max, uint32_t* n_nulls); +/* Vector v of a single-file generation-2 source (not synthetic, not + * materialized) as a view: ray_enccol_vview's 1 / 0 / -1. 0 for any + * other source (read it by range; a published materialization is read in + * place). */ +int ray_col_src_vview(const ray_col_src_t* s, int64_t v, struct ray_enc_vview_s* out, ray_t** err); +/* The statistics of a parted source, chunk by chunk in row order: fn is + * called for rows [lo, hi) of every RAY_ENC_CHUNK-row chunk of every + * segment, with the chunk's directory statistics when the segment is a + * single-file generation-2 column, else NULL (a plain segment). False + * when the source is not parted, or with an owned *err (OOM). */ +typedef void (*ray_col_chunk_fn)(void* ctx, int64_t lo, int64_t hi, const struct ray_enc_chunk_stat_s* st); +bool ray_col_src_parted_chunks(ray_col_src_t* s, void* ctx, ray_col_chunk_fn fn, ray_t** err); +/* The segments of a parted source: *n of them in row order (borrowed + * RAY_ENCCOL or plain vectors, NULL for a missing one), segment i holding + * rows [off[i], off[i + 1]). False when the source is not parted, or with + * an owned *err (OOM). Publishes the segment offsets on first use. */ +bool ray_col_src_parted_segs(ray_col_src_t* s, int64_t* n, ray_t*** segs, const int64_t** off, ray_t** err); +/* Row `row` of a single-file or parted generation-2 integer source (not + * SYM) read without decoding its vector (ray_enccol_point_i64: FOR_BP, + * DICT over FOR_BP, CONST or RLE, without nulls; a parted row is its + * segment's): 1 + * served into *out (the value widened to int64), 0 declined (read the row + * through a cursor, which decodes the vector; always for a + * plain or materialized source or segment), -1 an owned error in *err. + * For samplers: a sampled row costs no vector decode. A parted source + * publishes its segment offsets on first use (so the source is not const). */ +int ray_col_src_point_i64(ray_col_src_t* s, int64_t row, int64_t* out, ray_t** err); +/* ray_col_src_point_i64 of the ascending rows[0, n), all inside one + * vector (ray_col_src_vec_span), the vector's body read once + * (ray_enccol_points_i64): 1 every row served into out, 0 declined (read + * the vector through a cursor; out partly written), -1 an owned *err. */ +int ray_col_src_points_i64(ray_col_src_t* s, const int64_t* rows, int64_t n, int64_t* out, ray_t** err); +/* ray_col_src_points_i64 for a gather (ray_enccol_gather_points): SYM ids + * and vectors with a null bitmap served too, nul[q] 1 for a bitmap null. */ +int ray_col_src_gather_points(ray_col_src_t* s, const int64_t* rows, int64_t n, int64_t* out, uint8_t* nul, + ray_t** err); +/* The rows [*lo, *hi) of the vector holding row `row` (segment-local + * vectors for a parted source) when ray_col_src_point_i64 may serve it (a + * single-file encoded column or segment, not materialized): true. False + * for any other row, which a cursor reads. For a caller choosing between + * point reads and one decode by how many of a vector's rows it needs. */ +bool ray_col_src_vec_span(ray_col_src_t* s, int64_t row, int64_t* lo, int64_t* hi); +/* The vector holding row `row` as a run view: a single-file generation-2 + * integer or SYM source, or a parted source's single-file encoded segment + * (segment-local vectors), neither materialized, whose descriptor says + * CONST or RLE (no other codec builds a view) and which ray_enccol_vview + * vouches for, without a bitmap of nulls (SYM nulls are in-band ids, run + * values like the others). *lo / *hi are set in every case to rows of + * the source holding row and read alike: the vector, or a plain, + * materialized or stand-in segment (the source) whole. 1: the view of the + * vector [*lo, *hi); 0 declined (read the rows through a cursor, which + * decodes the vector); -1 an owned *err (a side entry's oom). */ +int ray_col_src_runview(ray_col_src_t* s, int64_t row, struct ray_enc_vview_s* out, int64_t* lo, int64_t* hi, ray_t** err); +/* Open decision D2 (ruled per codec at the measured crossovers of a + * batched point read against one decode, re-measured in Task 10b): a + * vector's requested rows are point-read when there are at most + * RAY_ENC_VEC / 32 of them in a FOR_BP vector, RAY_ENC_VEC / 16 in an RLE, + * CONST or DICT one or any vector with a null bitmap (a RAW one without + * nulls is read in place); any other codec declines (ray_enccol_points_i64 decides; enccol.c records the + * measurements). RAY_COL_POINT_ROWS is the largest of them, the most + * rows a caller hands one call (RAY_ENC_VEC = RAY_MORSEL_ELEMS values). + * Structural ratios, not knobs. */ +#define RAY_COL_POINT_ROWS (RAY_MORSEL_ELEMS / 16) +/* One sequential read-ahead hint for rows [lo, hi): plain mmapped + * columns hint their element bytes, generation 2 the chunk bytes from the + * directory, parted sources each touched segment; heap vectors nothing. */ +void ray_col_src_advise(const ray_col_src_t* s, int64_t lo, int64_t hi); +/* Test hook: the spans ray_col_src_advise would hint (page-aligned start, + * bytes), the first `cap` stored; returns how many there are. */ +int ray_col_src_test_advise_spans(const ray_col_src_t* s, int64_t lo, int64_t hi, + uintptr_t* start, size_t* len, int cap); + +/* One source in one task: P1's scratch plus the current view. */ +typedef struct { + ray_col_src_t* src; /* borrowed; bound for the execution */ + ray_col_scratch_t sc; + ray_col_range_t v; /* valid when have */ + bool have; +} ray_col_cursor_t; + +void ray_col_cursor_init(ray_col_cursor_t* c, ray_col_src_t* src); +/* ray_col_cursor_init with its scratch lent buf (ray_col_scratch_lend). */ +void ray_col_cursor_init_lent(ray_col_cursor_t* c, ray_col_src_t* src, ray_col_fixed_t* buf); +void ray_col_cursor_free(ray_col_cursor_t* c); +/* The view covering row r (0 <= r < len): the current one when it covers + * r, else a range read of [r, len) (generation 2: up to the end of r's + * vector; plain: to the source, segment or slice end). A RAY_ENCCOL whose + * materialization is published is read from that vector. NULL or an + * owned error; *out is valid until the next call or the cursor's free. */ +ray_t* ray_col_cursor_at(ray_col_cursor_t* c, int64_t r, const ray_col_range_t** out); + +/* One source's view of a piece: data points at the piece's first row. */ +typedef struct { + const void* data; + uint8_t attrs; /* SYM: the width class of data */ + bool may_null; + const char* str_pool; /* STR */ + struct ray_sym_domain_s* dom; +} ray_col_piece_t; + +typedef void (*ray_col_piece_fn)(void* ctx, uint32_t wid, int64_t b, int64_t e, + const ray_col_piece_t* p); + +/* Walk [lo, hi) of n sources. plain[i] is the base pointer of source i + * (its row 0) when it can be read in place, or NULL to read it through a + * cursor (generation 2, RAY_ENCCOL_PARTED, a plain parted wrapper); a NULL + * srcs[i] is skipped (COUNT inputs). Each call of fn covers a piece + * [b, e) with one ray_col_piece_t per source. Plain sources point at + * plain + b * esz; cursor sources point into their view, so a piece ends + * at the nearest view end. contiguous: one piece [lo, hi) + * (hi - lo <= RAY_COL_BLOCK_ROWS), every cursor F32/F64 source copied into + * a buffer of the call (any other cursor type is `nyi` in this mode). + * Cursors and buffers live for the call: allocate at its start, free at its + * end. NULL or an owned error (fn is not called again after an error). */ +ray_t* ray_col_walk(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + int64_t lo, int64_t hi, bool contiguous, + void* ctx, uint32_t wid, ray_col_piece_fn fn); + +/* ray_col_walk's non-contiguous mode through the caller's cursors: cur[i] + * is source i's cursor (ray_col_cursor_init'd for every srcs[i] with a NULL + * plain[i]; other entries unused), kept by the caller across calls. A task + * walking consecutive blocks with one cursor set decodes the vector one + * block ends inside once, not once per block. NULL or an owned error. */ +ray_t* ray_col_walk_cur(ray_col_src_t* const* srcs, const void* const* plain, uint32_t n, + ray_col_cursor_t* cur, int64_t lo, int64_t hi, + void* ctx, uint32_t wid, ray_col_piece_fn fn); + +/* A dispatch's failure envelope (R-FAIL): a worker notes a range error + * keyed by its task's first row and stops reading. The answer is the + * lowest-keyed failure, independent of scheduling, so a task may return + * early only when ray_scan_fail_skip says a LOWER key already failed (a + * task below the lowest failure still runs: it may fail lower). After the + * join, every coordinator calls ray_scan_fail_finish, which also turns a + * cancelled dispatch (tasks the pool skipped note nothing) into `cancel`. */ +typedef struct { + _Atomic(uint32_t) lock; + _Atomic(int64_t) key; /* lowest failing key; INT64_MAX when none */ + ray_enc_snap_t snap; +} ray_scan_fail_t; + +void ray_scan_fail_init(ray_scan_fail_t* f); +/* Consumes err; snapshots its code and this thread's message when key is + * the lowest so far. */ +void ray_scan_fail_note(ray_scan_fail_t* f, int64_t key, ray_t* err); +static inline bool ray_scan_failed(ray_scan_fail_t* f) { + return atomic_load_explicit(&f->key, memory_order_acquire) != INT64_MAX; +} +/* True only when a failure with a key lower than `key` is already noted: + * the task of `key` cannot change the answer and may skip its work. */ +static inline bool ray_scan_fail_skip(ray_scan_fail_t* f, int64_t key) { + return atomic_load_explicit(&f->key, memory_order_acquire) < key; +} +/* NULL, or a fresh error rebuilt on the calling thread. */ +ray_t* ray_scan_fail_error(ray_scan_fail_t* f); +/* The coordinator's verdict after the join: the lowest noted failure; else + * `cancel` when the dispatch was cancelled (ray_interrupted(), or `pool`'s + * cancel flag; pool may be NULL); else NULL. A noted failure stands over a + * cancel: it is a real fault of the data, a cancel only an absence of work. */ +ray_t* ray_scan_fail_finish(ray_scan_fail_t* f, ray_pool_t* pool); + +#endif /* RAY_COLRANGE_H */ diff --git a/src/store/colwrite.c b/src/store/colwrite.c new file mode 100644 index 000000000..d9f4b7b34 --- /dev/null +++ b/src/store/colwrite.c @@ -0,0 +1,577 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#if defined(__APPLE__) +# define _DARWIN_C_SOURCE +#elif !defined(_WIN32) +# define _GNU_SOURCE +#endif +#include "store/col.h" +#include "store/encw.h" +#include "store/colrange.h" +#include "store/enccol.h" +#include "vec/str.h" +#include "store/fileio.h" +#include "mem/heap.h" +#include "ops/idxop.h" +#include "table/sym.h" +#include "table/domain.h" +#include +#include +#include +#include + +/* tmp -> fsync (durable) -> rename -> dir sync; removes a stale .link + * sidecar (generation-2 columns are never linked). */ +static ray_err_t colw_publish(const char* tmp, const char* path, bool durable) { + ray_err_t e; + if (durable) { + ray_fd_t fd = ray_file_open(tmp, RAY_OPEN_READ | RAY_OPEN_WRITE); + if (fd == RAY_FD_INVALID) { remove(tmp); return RAY_ERR_IO; } + e = ray_file_sync(fd); + ray_file_close(fd); + if (e != RAY_OK) { remove(tmp); return e; } + } + if ((e = ray_file_rename(tmp, path)) != RAY_OK) { remove(tmp); return e; } + if (durable && (e = ray_file_sync_dir(path)) != RAY_OK) return e; + char link[1100]; + if (snprintf(link, sizeof link, "%s.link", path) < (int)sizeof link) remove(link); + return RAY_OK; +} + +/* Generation 2 holds plain vectors of BOOL..STR without a link (spec + * "Always generation 0"), with every index kind: a SYM column's HASH or + * PART is rebuilt over the target ids by the range writer (spec "SYM + * columns"). */ +bool ray_col_gen2_eligible(ray_t* col) { + if (!col || RAY_IS_ERR(col)) return false; + if (!ray_encw_type_supported(col->type)) return false; + if (col->attrs & RAY_ATTR_HAS_LINK) return false; + return true; +} + +/* Index kind and UNIQUE flag a plain column records: every fresh kind with + * a region or a synthesized form; DICT and a stale root record nothing. */ +void ray_col_gen2_index_meta(ray_t* col, uint8_t* index_kind, uint8_t* col_flags) { + *index_kind = 0; *col_flags = 0; + if (!ray_index_has(col)) return; + ray_index_t* ix = ray_index_payload(col->index); + if (ix->built_for_len != col->len) return; /* stale: dropped */ + if (ix->markers & RAY_MARK_UNIQUE) *col_flags |= RAY_ENC_FLAG_UNIQUE; + switch (ix->kind) { + case RAY_IDX_ZONE: case RAY_IDX_CHUNK_ZONE: case RAY_IDX_HASH: + case RAY_IDX_SORT: case RAY_IDX_BLOOM: case RAY_IDX_PART: + *index_kind = (uint8_t)ix->kind; break; + default: break; + } +} + +/* The order name of a trustworthy root, or NULL (spec "order_sym"). */ +static const char* colw_order_name(const ray_t* root, uint32_t* len) { + *len = 0; + int64_t s = ray_enc_index_trusted_order(root); + if (s < 0) return NULL; + ray_t* na = ray_sym_str(s); + if (!na || RAY_IS_ERR(na) || ray_str_len(na) < 1 || ray_str_len(na) > RAY_ENC_IDX_NAME_MAX) return NULL; + *len = (uint32_t)ray_str_len(na); + return ray_str_ptr(na); +} + +/* The region writer's "index region: ..." message gains the column's + * "column %s: " prefix (the spec's message form); the code is unchanged. */ +static void colw_region_msg(const char* path) { + const char* m = ray_error_msg(); + if (!m || strncmp(m, "index region:", 13) != 0) return; + char copy[256]; + snprintf(copy, sizeof copy, "%s", m); + ray_error_free(ray_error("io", "column %s: %s", path, copy)); /* sets the message; code unused */ +} + +static ray_err_t colw_gen2_vec(ray_t* vec, const char* path, bool durable, uint8_t ik_override, + uint8_t ix_decision) { + if (!ray_enc_gen2_supported()) return RAY_ERR_NYI; /* before .tmp exists */ + char tmp[1100]; + if (snprintf(tmp, sizeof tmp, "%s.tmp", path) >= (int)sizeof tmp) return RAY_ERR_IO; + FILE* f = fopen(tmp, "wb+"); + if (!f) return RAY_ERR_IO; + uint8_t ik, cf; + ray_col_gen2_index_meta(vec, &ik, &cf); + /* a region from the root's own kind; an override never re-labels a + * region root, and DROP writes none */ + bool region = ray_enc_idx_kind_has_region(ik) && (!ik_override || ik_override == ik) && + ix_decision != RAY_COL_IDX_DROP; + if (ik_override) ik = ik_override; + /* DICT (spec "Writing the index"): only when this save asks for it; the + * writer builds it from the values, so no region is taken from a root */ + if (ik == RAY_IDX_DICT && ik_override != RAY_IDX_DICT) ik = 0; + if (ray_enc_idx_kind_has_region(ik) && !region) ik = 0; /* no region: none recorded */ + /* the writer applies the same matrix as the validator (spec step 3) */ + if ((ik && !ray_index_kind_admits((ray_idx_kind_t)ik, vec->type)) || + ((cf & RAY_ENC_FLAG_UNIQUE) && !ray_index_kind_admits(RAY_IDX_NONE, vec->type))) { + fclose(f); remove(tmp); + return RAY_ERR_NYI; + } + uint32_t sc = 0; /* SYM never reaches here: colw_gen2_range */ + uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); + const char* data = (const char*)ray_data(vec); /* slice-safe */ + ray_t* owner = (vec->attrs & RAY_ATTR_SLICE) ? vec->slice_parent : vec; + const char* pool = (vec->type == RAY_STR && owner->str_pool && !RAY_IS_ERR(owner->str_pool)) + ? (const char*)ray_data(owner->str_pool) : NULL; + ray_encw_t w; + ray_err_t e = ray_encw_begin(&w, f, vec->type, vec->attrs, vec->len, sc, ik, cf); + if (e == RAY_OK && region) { + ray_enc_idx_src_t is = { vec->index, vec->type, vec->attrs, vec->len, NULL, 0 }; + is.order_name = colw_order_name(vec->index, &is.order_len); + ray_encw_set_index(&w, &is); + } + for (int64_t c = 0; e == RAY_OK && c < w.n_chunks; c++) { + int64_t n = vec->len - c * RAY_ENC_CHUNK; + if (n > RAY_ENC_CHUNK) n = RAY_ENC_CHUNK; + e = ray_encw_chunk(&w, data + (size_t)c * RAY_ENC_CHUNK * esz, pool, n); + } + /* colw_region_msg reads the thread-local message: clear it first, so a + * plain io error from finish never picks up a stale "index region:" */ + if (e == RAY_OK && region) ray_error_clear(); + if (e == RAY_OK && (e = ray_encw_finish(&w)) != RAY_OK && region) colw_region_msg(path); + ray_encw_free(&w); + if (fclose(f) != 0 && e == RAY_OK) e = RAY_ERR_IO; + if (e != RAY_OK) { remove(tmp); return e; } /* nothing of this write remains */ + return colw_publish(tmp, path, durable); +} + +/* Index kind / flags recorded for a source: a plain column's attached + * index, or an encoded column's own header (every recorded kind). A SYM + * column's stale HASH / PART still names its kind (*stale): the range + * writer rebuilds every SYM index from the column, so the stale contents + * never matter, but its UNIQUE and order name are not trusted (generation + * 0 rebuilds a stale SYM HASH too: generation 2 keeps at least as much). */ +static void colw_src_index_meta(ray_t* obj, uint8_t* ik, uint8_t* cf, bool* stale) { + *stale = false; + if (obj->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of(obj); + *ik = e->hdr.index_kind; + *cf = e->hdr.col_flags & RAY_ENC_FLAG_UNIQUE; + return; + } + ray_col_gen2_index_meta(obj, ik, cf); /* a stale root: no kind, no UNIQUE */ + if (*ik == 0 && obj->type == RAY_SYM && ray_index_has(obj)) { + ray_idx_kind_t k = ray_index_kind(obj); + if (k == RAY_IDX_HASH || k == RAY_IDX_PART) { *ik = (uint8_t)k; *stale = true; } + } +} + +/* The target id of `id` (P1 Task 14's rule): checked against target_dom + * when the source already resolves over it, re-expressed in target_dom + * from another domain, or through the runtime LUT for a bare save of a + * FILE-domain source. False: the id has no target. */ +static bool colw_sym_map(ray_col_write_t* w, struct ray_sym_domain_s* vdom, const int64_t* lut, + int64_t id, int64_t* pos) { + *pos = id; + if (w->target_dom && vdom == w->target_dom) { + if (id < 0 || id >= ray_sym_domain_count(w->target_dom)) *pos = -1; + } else if (w->target_dom) { + ray_t* str = ray_sym_domain_str(vdom, id); + *pos = str ? ray_sym_domain_find(w->target_dom, ray_str_ptr(str), ray_str_len(str)) : -1; + } else if (lut) { + *pos = (id >= 0 && id < ray_sym_domain_count(vdom)) ? lut[id] : -1; + } + return *pos >= 0; +} + +/* A fresh root of `kind` built by the generation-0 builder over `v` + * (owned: consumed on every path; a shared vector is copied by the + * builder, never modified). */ +static ray_t* colw_rebuild_root(ray_t* v, uint8_t kind, ray_t** root_out) { + *root_out = NULL; + ray_t* r = kind == RAY_IDX_HASH ? ray_index_attach_hash(&v) + : kind == RAY_IDX_SORT ? ray_index_attach_sort(&v) + : kind == RAY_IDX_BLOOM ? ray_index_attach_bloom(&v) + : ray_index_attach_part(&v); + if (!r || RAY_IS_ERR(r)) { ray_release(v); return r ? r : ray_error("oom", "index rebuild"); } + *root_out = r->index; + ray_retain(*root_out); + ray_release(r); + return NULL; +} + +/* SYM: `plain` (borrowed) remapped into the target ids at the target width + * (`attrs`), then its HASH / PART rebuilt (spec "SYM columns", "Index + * rebuild"). */ +static ray_t* colw_sym_rebuild(ray_col_write_t* w, ray_t* plain, uint8_t attrs, const int64_t* lut, + uint8_t kind, ray_t** root_out) { + *root_out = NULL; + ray_t* rm = ray_sym_vec_new(attrs & RAY_SYM_W_MASK, plain->len); + if (!rm || RAY_IS_ERR(rm)) return rm ? rm : ray_error("oom", "index rebuild"); + rm->len = plain->len; + /* no HAS_NULLS: SYM nulls are in-band (id 0) and the builders read a + * SYM column as possibly null whatever its attrs + * (ray_vec_may_have_nulls); the root they build records nothing of it + * on the wire (saved_attrs is not serialized) */ + struct ray_sym_domain_s* vdom = ray_sym_vec_domain(plain); + const void* sd = ray_data(plain); + for (int64_t i = 0; i < plain->len; i++) { + int64_t pos; + if (!colw_sym_map(w, vdom, lut, ray_read_sym(sd, i, RAY_SYM, plain->attrs), &pos)) { + ray_release(rm); + return ray_error("corrupt", "col %s: SYM id outside the target domain", w->name ? w->name : "?"); + } + ray_write_sym(ray_data(rm), i, (uint64_t)pos, RAY_SYM, attrs); + } + return colw_rebuild_root(rm, kind, root_out); +} + +/* The region of a range write (spec "Index decisions"), decided before the + * file exists: a root to serialize (*root, owned: a SYM HASH / PART + * rebuilt over the target ids, or any kind on REBUILD, built from the + * materialized column), or an encoded non-SYM source's region to copy + * verbatim (*copy, into the source's mapping). The order name of a + * rebuilt root is the source root's trustworthy one (none for a stale + * root), which a materialization of generation 2 carries (its parsed + * root). */ +static ray_t* colw_region_prepare(ray_col_write_t* w, uint8_t ik, uint8_t attrs, const int64_t* lut, bool stale, + ray_t** root, const uint8_t** copy, uint64_t* copy_len, + const char** order, uint32_t* order_len) { + ray_t* src = w->src.obj; + bool enc = src->type == RAY_ENCCOL; + if (enc && w->src.type != RAY_SYM && w->index_decision == RAY_COL_IDX_KEEP) { + ray_enccol_t* se = ray_enccol_of(src); + *copy = se->base + se->hdr.index_off; + *copy_len = se->hdr.end_off - se->hdr.index_off; + return NULL; + } + /* a materialization is counted once and owned by the source */ + ray_t* plain = enc ? ray_enccol_materialize(src) : src; + if (RAY_IS_ERR(plain)) return plain; + if (!stale && ray_index_has(plain)) *order = colw_order_name(plain->index, order_len); + if (w->src.type == RAY_SYM) return colw_sym_rebuild(w, plain, attrs, lut, ik, root); + ray_retain(plain); + return colw_rebuild_root(plain, ik, root); +} + +/* Test hook: the nth allocation of the range writer's own buffers fails. */ +static _Atomic int64_t g_colw_fail_at; +static void* colw_alloc(void* old, size_t n) { + int64_t k = atomic_load(&g_colw_fail_at); + if (k > 0 && atomic_fetch_sub(&g_colw_fail_at, 1) == 1) return NULL; + return old ? ray_realloc_raw(old, n) : ray_alloc_raw(n); +} +void ray_col_test_fail_alloc(int64_t nth) { atomic_store(&g_colw_fail_at, nth); } + +static _Atomic(bool) g_colw_no_dict; +void ray_col_test_no_dict(bool on) { atomic_store(&g_colw_no_dict, on); } +bool ray_col_dict_wanted(int8_t type, int64_t len) { + return type == RAY_STR && len >= RAY_DICT_MIN_ROWS && len <= INT32_MAX && !atomic_load(&g_colw_no_dict); +} + +/* Generation 2 from range reads: encoded sources and every SYM source. + * One chunk of generation-0 values is staged at a time (spec "Writers": + * no whole-column materialization). */ +static ray_err_t colw_gen2_range(ray_col_write_t* w, const char* path) { + if (!ray_enc_gen2_supported()) return RAY_ERR_NYI; /* before .tmp exists */ + ray_col_src_t* s = &w->src; + int8_t type = s->type; + uint8_t attrs = s->attrs; + uint32_t sc = 0; + const int64_t* lut = NULL; + if (type == RAY_SYM) { + if (w->target_dom) { + int64_t dc = ray_sym_domain_count(w->target_dom); + if (dc > UINT32_MAX) return RAY_ERR_RANGE; + uint8_t keep_sorted = (s->dom == w->target_dom) ? (attrs & RAY_ATTR_SORTED) : 0; + attrs = (uint8_t)(ray_sym_dict_width(dc) | keep_sorted | (attrs & RAY_ATTR_HAS_NULLS)); + sc = (uint32_t)dc; + } else { + /* bare file: process-local runtime ids, as col_save_impl writes them */ + if (s->dom != ray_sym_runtime_domain()) { + lut = ray_sym_domain_runtime_lut(s->dom); + if (!lut) return RAY_ERR_OOM; + attrs = (uint8_t)(ray_sym_dict_width((int64_t)ray_sym_count()) | (attrs & RAY_ATTR_HAS_NULLS)); + } + sc = ray_sym_count(); + } + } + uint8_t src_ik, cf; + bool stale; + colw_src_index_meta(s->obj, &src_ik, &cf, &stale); + /* a region from the source's own kind (as colw_gen2_vec): an override + * never re-labels a region kind, DROP writes none, and a region kind is + * never recorded without its region */ + bool region = ray_enc_idx_kind_has_region(src_ik) && (!w->index_kind || w->index_kind == src_ik) && + w->index_decision != RAY_COL_IDX_DROP; + uint8_t ik = w->index_kind ? w->index_kind : src_ik; + if (ik == RAY_IDX_DICT && w->index_kind != RAY_IDX_DICT) ik = 0; /* never inherited (P6b) */ + if (ray_enc_idx_kind_has_region(ik) && !region) ik = 0; + if ((ik && !ray_index_kind_admits((ray_idx_kind_t)ik, type)) || + ((cf & RAY_ENC_FLAG_UNIQUE) && !ray_index_kind_admits(RAY_IDX_NONE, type))) + return RAY_ERR_NYI; + uint8_t esz = ray_sym_elem_size(type, attrs); + char tmp[1100]; + if (snprintf(tmp, sizeof tmp, "%s.tmp", path) >= (int)sizeof tmp) return RAY_ERR_IO; + /* the region is decided before the file exists: a rebuilt root must be + * whole before the chunk loop, and ray_encw_set_index borrows it */ + ray_t* idx_root = NULL; /* owned; released on every exit */ + const uint8_t* idx_copy = NULL; uint64_t idx_copy_len = 0; + const char* order = NULL; uint32_t order_len = 0; + if (region) { + ray_t* ierr = colw_region_prepare(w, ik, attrs, lut, stale, &idx_root, &idx_copy, &idx_copy_len, + &order, &order_len); + /* a stale SYM PART over values no longer in contiguous blocks has + * no rebuild: it records nothing, as a stale root did before */ + if (ierr && stale && strcmp(ray_err_code(ierr), "domain") == 0) { + ray_error_free(ierr); ierr = NULL; + ik = 0; + } + if (ierr) { ray_err_t ie = ray_err_from_obj(ierr); ray_error_free(ierr); return ie; } + } + uint8_t* buf = colw_alloc(NULL, (size_t)RAY_ENC_CHUNK * (esz ? esz : 1)); + char* pool = NULL; size_t pool_cap = 0; + ray_col_scratch_t scr; ray_col_scratch_init(&scr); + FILE* f = buf ? fopen(tmp, "wb+") : NULL; + ray_err_t e = !buf ? RAY_ERR_OOM : (!f ? RAY_ERR_IO : RAY_OK); + ray_encw_t ew; memset(&ew, 0, sizeof ew); + if (e == RAY_OK) e = ray_encw_begin(&ew, f, type, attrs, s->len, sc, ik, cf); + if (e == RAY_OK && idx_root) { + /* the source attrs, as colw_gen2_vec passes them: finish writes the + * region at the column's final persisted attrs (SYM PART keys at + * the saved width) */ + ray_enc_idx_src_t is = { idx_root, type, s->attrs, s->len, order, order_len }; + ray_encw_set_index(&ew, &is); + } else if (e == RAY_OK && idx_copy) { + ray_encw_set_index_copy(&ew, ik, idx_copy, idx_copy_len); + } + for (int64_t c = 0; e == RAY_OK && c < ew.n_chunks; c++) { + int64_t base = c * RAY_ENC_CHUNK; + int64_t rows = s->len - base < RAY_ENC_CHUNK ? s->len - base : RAY_ENC_CHUNK; + size_t pool_used = 0; + for (int64_t r = 0; e == RAY_OK && r < rows; ) { + ray_col_range_t v; + ray_t* err = ray_col_range(s, base + r, rows - r, &scr, &v); + if (err) { e = ray_err_from_obj(err); ray_error_free(err); break; } + if (v.n <= 0) { e = RAY_ERR_CORRUPT; break; } + if (type == RAY_SYM) { + for (int64_t i = 0; i < v.n; i++) { + int64_t pos; + if (!colw_sym_map(w, v.dom, lut, ray_read_sym(v.data, i, RAY_SYM, v.attrs), &pos)) { + e = RAY_ERR_CORRUPT; break; + } + ray_write_sym(buf, r + i, (uint64_t)pos, RAY_SYM, attrs); + } + } else if (type == RAY_STR) { + const ray_str_t* d = v.data; + ray_str_t* o = (ray_str_t*)buf + r; + for (int64_t i = 0; i < v.n; i++) { + o[i] = d[i]; + if (ray_str_is_inline(&d[i])) continue; + if (pool_used + d[i].len > pool_cap) { + size_t nc = pool_cap ? pool_cap * 2 : 1 << 20; + while (nc < pool_used + d[i].len) nc *= 2; + char* np = colw_alloc(pool, nc); + if (!np) { e = RAY_ERR_OOM; break; } + pool = np; pool_cap = nc; + } + memcpy(pool + pool_used, v.str_pool + d[i].pool_off, d[i].len); + o[i].pool_off = (uint32_t)pool_used; /* chunk-local pool */ + pool_used += d[i].len; + } + } else { + memcpy(buf + (size_t)r * esz, v.data, (size_t)v.n * esz); + } + r += v.n; + } + if (e == RAY_OK) e = ray_encw_chunk(&ew, buf, pool, rows); + } + bool has_region = idx_root || idx_copy; + /* colw_region_msg reads the thread-local message: clear it first */ + if (e == RAY_OK && has_region) ray_error_clear(); + if (e == RAY_OK && (e = ray_encw_finish(&ew)) != RAY_OK && has_region) colw_region_msg(path); + ray_encw_free(&ew); + if (idx_root) ray_release(idx_root); + ray_col_scratch_free(&scr); + ray_free_raw(buf); ray_free_raw(pool); + if (f && fclose(f) != 0 && e == RAY_OK) e = RAY_ERR_IO; + if (e != RAY_OK) { if (f) remove(tmp); return e; } + return colw_publish(tmp, path, w->durable); +} + +static bool colw_src_gen2_ok(ray_t* obj) { + if (!obj) return false; + if (obj->type == RAY_ENCCOL) return !ray_enccol_is_parted(obj); + return ray_col_gen2_eligible(obj); +} + +ray_err_t ray_col_save_ctx(ray_col_write_t* w, const char* path) { + ray_t* obj = w->src.obj; + if (!obj || !path) return RAY_ERR_TYPE; + if (w->index_decision > RAY_COL_IDX_DROP) return RAY_ERR_TYPE; + /* parted sources have no single-file form; a later preflight admitting + * RAY_ENCCOL must keep excluding parted kinds */ + if (RAY_IS_PARTED(obj->type) || (obj->type == RAY_ENCCOL && ray_enccol_is_parted(obj))) + return RAY_ERR_NYI; + if (w->gen == 2 && colw_src_gen2_ok(obj)) { + /* direct pointers; a REBUILD goes by range, the path that holds it */ + if (obj->type != RAY_ENCCOL && obj->type != RAY_SYM && w->index_decision != RAY_COL_IDX_REBUILD) + return colw_gen2_vec(obj, path, w->durable, w->index_kind, w->index_decision); + return colw_gen2_range(w, path); + } + if (w->gen != 0 && w->gen != 2) return RAY_ERR_VERSION; + /* generation 0 writes its index as today: it takes no other decision */ + if (w->index_decision != RAY_COL_IDX_KEEP) return RAY_ERR_NYI; + ray_t* col = obj; + if (obj->type == RAY_ENCCOL) { + col = ray_enccol_materialize(obj); /* the object's own once-state */ + if (RAY_IS_ERR(col)) { ray_err_t e = ray_err_from_obj(col); ray_error_free(col); return e; } + } + if (col->type == RAY_SYM && w->target_dom) + return ray_col_save_sym_encoded(col, path, w->target_dom, w->durable); + return w->durable ? ray_col_save(col, path) : ray_col_save_bulk(col, path); +} + +static ray_err_t colw_save_gen(ray_t* vec, const char* path, uint8_t gen, bool durable) { + if (!vec || RAY_IS_ERR(vec)) return RAY_ERR_TYPE; + if (!path) return RAY_ERR_IO; + ray_col_write_t w; memset(&w, 0, sizeof w); + ray_t* err = ray_col_src_bind(vec, &w.src); + if (err) { ray_err_t be = ray_err_from_obj(err); ray_error_free(err); return be; } + w.gen = gen; w.durable = durable; + ray_err_t e = ray_col_save_ctx(&w, path); + ray_col_src_release(&w.src); + return e; +} + +ray_err_t ray_col_save_gen(ray_t* vec, const char* path, uint8_t gen) { + return colw_save_gen(vec, path, gen, true); +} +ray_err_t ray_col_save_bulk_gen(ray_t* vec, const char* path, uint8_t gen) { + return colw_save_gen(vec, path, gen, false); +} + +/* Equivalence-run hook: an absent option behaves as true. */ +static _Atomic(bool) g_force_compress; +void ray_store_test_force_compress(bool on) { atomic_store(&g_force_compress, on); } + +/* A missing file is generation 0; any other failure to read the header + * (permissions, a short file, a bad discriminator) is an error, so an + * absent option never silently drops a destination's generation. */ +ray_err_t ray_col_file_gen_err(const char* path, uint8_t* gen) { + *gen = 0; + if (!path) return RAY_ERR_IO; + errno = 0; + FILE* f = fopen(path, "rb"); + if (!f) return errno == ENOENT ? RAY_OK : RAY_ERR_IO; + uint8_t h[32]; + size_t n = fread(h, 1, 32, f); + bool rd_err = ferror(f) != 0; + fclose(f); + if (rd_err) return RAY_ERR_IO; + if (ray_col_header_is_ext(h, n)) return RAY_OK; /* list / string formats */ + if (n != 32) return RAY_ERR_CORRUPT; + int g = ray_col_gen_of(h); + if (g == RAY_ENC_GEN_VERSION) return RAY_ERR_VERSION; + if (g < 0) return RAY_ERR_CORRUPT; + *gen = g == 2 ? 2 : 0; + return RAY_OK; +} + +uint8_t ray_col_file_gen(const char* path) { + uint8_t g; + return ray_col_file_gen_err(path, &g) == RAY_OK ? g : 0; +} + +/* The generation the destination's current generation stores `name` in. */ +static ray_err_t colw_dest_gen(const char* cur, const char* name, size_t nlen, uint8_t* gen) { + *gen = 0; + if (!cur || !cur[0]) return RAY_OK; /* no published table */ + if (!name) return RAY_ERR_TYPE; + char p[1200]; + int n = snprintf(p, sizeof p, "%s/%.*s", cur, (int)nlen, name); + if (n < 0 || (size_t)n >= sizeof p) return RAY_ERR_RANGE; + return ray_col_file_gen_err(p, gen); +} + +ray_err_t ray_col_resolve_gen_err(ray_compress_t mode, ray_t* src, const char* cur, + const char* name, size_t nlen, uint8_t* gen) { + *gen = 0; + if (!colw_src_gen2_ok(src) || mode == RAY_COMPRESS_OFF) return RAY_OK; + *gen = 2; + if (mode == RAY_COMPRESS_ON || atomic_load(&g_force_compress)) return RAY_OK; + /* the slot still holds a column saved encoded (a synthetic stand-in, + * e.g. a ragged partition's absent column, inherits like a plain one) */ + if (src->type == RAY_ENCCOL && !ray_enccol_is_synthetic(src)) return RAY_OK; + return colw_dest_gen(cur, name, nlen, gen); /* the destination already stores it as 2 */ +} + +bool ray_col_resolve_needs_dest(ray_compress_t mode, ray_t* src) { + return mode == RAY_COMPRESS_ABSENT && colw_src_gen2_ok(src) && + !atomic_load(&g_force_compress) && + (src->type != RAY_ENCCOL || ray_enccol_is_synthetic(src)); +} + +bool ray_col_resolve_type_needs_dest(ray_compress_t mode, int8_t type) { + return mode == RAY_COMPRESS_ABSENT && ray_encw_type_supported(type) && + !atomic_load(&g_force_compress); +} + +ray_err_t ray_col_resolve_gen_type_err(ray_compress_t mode, int8_t type, const char* cur, + const char* name, size_t nlen, uint8_t* gen) { + *gen = 0; + if (!ray_encw_type_supported(type) || mode == RAY_COMPRESS_OFF) return RAY_OK; + *gen = 2; + if (mode == RAY_COMPRESS_ON || atomic_load(&g_force_compress)) return RAY_OK; + return colw_dest_gen(cur, name, nlen, gen); +} + +uint8_t ray_col_resolve_gen(ray_compress_t mode, ray_t* src, + const char* cur, const char* name, size_t nlen) { + uint8_t g; + return ray_col_resolve_gen_err(mode, src, cur, name, nlen, &g) == RAY_OK ? g : 0; +} + +uint8_t ray_col_resolve_gen_type(ray_compress_t mode, int8_t type, + const char* cur, const char* name, size_t nlen) { + uint8_t g; + return ray_col_resolve_gen_type_err(mode, type, cur, name, nlen, &g) == RAY_OK ? g : 0; +} + +ray_t* ray_compress_opt_parse(ray_t* opts, bool strict, ray_compress_t* mode) { + *mode = RAY_COMPRESS_ABSENT; + if (!opts) return NULL; + if (opts->type != RAY_DICT) return ray_error("type", "options must be a dict"); + ray_t* keys = ray_dict_keys(opts); + if (keys && keys->len > 0 && keys->type != RAY_SYM) + return ray_error("domain", "option keys must be symbols"); + for (int64_t i = 0; strict && keys && i < keys->len; i++) { + ray_t* k = ray_sym_vec_cell(keys, i); + if (!k || ray_str_len(k) != 8 || memcmp(ray_str_ptr(k), "compress", 8) != 0) + return ray_error("domain", "unknown option '%.*s' (only compress is accepted)", + k ? (int)ray_str_len(k) : 1, k ? ray_str_ptr(k) : "?"); + } + ray_t* key = ray_sym(ray_sym_intern("compress", 8)); + if (!key || RAY_IS_ERR(key)) return key ? key : ray_error("oom", NULL); + ray_t* v = ray_dict_get(opts, key); + ray_release(key); + if (!v) return NULL; + if (RAY_IS_ERR(v)) return v; + bool ok = v->type == -RAY_BOOL; + if (ok) *mode = v->b8 ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF; + ray_release(v); + return ok ? NULL : ray_error("domain", "compress must be true or false"); +} diff --git a/src/store/csr.c b/src/store/csr.c index b042fb51b..95c73a9dd 100644 --- a/src/store/csr.c +++ b/src/store/csr.c @@ -23,6 +23,7 @@ #include "csr.h" #include "store/col.h" +#include "store/enccol.h" #include "mem/sys.h" #include "store/fileio.h" /* ray_mkdir */ #include @@ -30,6 +31,7 @@ #include #include #include +#include "core/pool.h" /* Forward declaration */ static void csr_free(ray_csr_t* csr); @@ -38,63 +40,72 @@ static void csr_free(ray_csr_t* csr); * CSR construction helpers * -------------------------------------------------------------------------- */ -/* Pair for sorting edges */ +/* One (target, row) cell of an adjacency list, for sorting a long list. */ typedef struct { - int64_t src; - int64_t dst; - int64_t row; /* original row index for rowmap */ -} edge_pair_t; - -/* Comparison by src then dst, with .row as a final tie-break. - * - * qsort is not a stable sort: for parallel edges (equal src AND equal dst) - * the relative order of their original rows would otherwise be platform- and - * input-dependent, making rowmap (and any golden test or MST that consumes it) - * non-deterministic. The .row tie-break pins a total order. */ -static int cmp_edge_by_src(const void* a, const void* b) { - const edge_pair_t* ea = (const edge_pair_t*)a; - const edge_pair_t* eb = (const edge_pair_t*)b; - if (ea->src < eb->src) return -1; - if (ea->src > eb->src) return 1; - if (ea->dst < eb->dst) return -1; - if (ea->dst > eb->dst) return 1; - if (ea->row < eb->row) return -1; - if (ea->row > eb->row) return 1; + int64_t target; + int64_t row; +} adj_cell_t; + +static int cmp_adj_cell(const void* a, const void* b) { + const adj_cell_t* x = (const adj_cell_t*)a; + const adj_cell_t* y = (const adj_cell_t*)b; + if (x->target < y->target) return -1; + if (x->target > y->target) return 1; + if (x->row < y->row) return -1; + if (x->row > y->row) return 1; return 0; } -/* Comparison by dst then src (for reverse CSR), with .row as a final tie-break - * for determinism (see cmp_edge_by_src). */ -static int cmp_edge_by_dst(const void* a, const void* b) { - const edge_pair_t* ea = (const edge_pair_t*)a; - const edge_pair_t* eb = (const edge_pair_t*)b; - if (ea->dst < eb->dst) return -1; - if (ea->dst > eb->dst) return 1; - if (ea->src < eb->src) return -1; - if (ea->src > eb->src) return 1; - if (ea->row < eb->row) return -1; - if (ea->row > eb->row) return 1; - return 0; -} +/* Sort every adjacency list by (target, row). + * + * The order is a total one, so a CSR built from the same edges is the same + * bytes on every platform: parallel edges (equal key AND equal target) are + * pinned by their original row, which rowmap (and any golden test or MST + * that consumes it) relies on. Lists are short in the common case, so an + * insertion sort serves them; a hub's list past ADJ_INSERTION_MAX is packed + * into (target, row) cells and qsorted to stay O(d log d). */ +#define ADJ_INSERTION_MAX 32 -/* Sort targets within each adjacency list (for LFTJ) */ static void csr_sort_adjacency_lists(ray_csr_t* csr) { int64_t* offsets = (int64_t*)ray_data(csr->offsets); int64_t* targets = (int64_t*)ray_data(csr->targets); int64_t* rowmap = csr->rowmap ? (int64_t*)ray_data(csr->rowmap) : NULL; + adj_cell_t* cells = NULL; + int64_t cells_cap = 0; + for (int64_t node = 0; node < csr->n_nodes; node++) { int64_t start = offsets[node]; int64_t end = offsets[node + 1]; int64_t deg = end - start; if (deg <= 1) continue; - /* Simple insertion sort — adjacency lists are typically small */ + if (deg > ADJ_INSERTION_MAX && rowmap) { + if (deg > cells_cap) { + ray_free_raw(cells); + cells_cap = deg; + cells = (adj_cell_t*)ray_alloc_raw((size_t)cells_cap * sizeof(adj_cell_t)); + if (!cells) { cells_cap = 0; goto insertion; } /* OOM: slow path */ + } + for (int64_t i = 0; i < deg; i++) { + cells[i].target = targets[start + i]; + cells[i].row = rowmap[start + i]; + } + qsort(cells, (size_t)deg, sizeof(adj_cell_t), cmp_adj_cell); + for (int64_t i = 0; i < deg; i++) { + targets[start + i] = cells[i].target; + rowmap[start + i] = cells[i].row; + } + continue; + } + +insertion: for (int64_t i = start + 1; i < end; i++) { int64_t key = targets[i]; int64_t row_key = rowmap ? rowmap[i] : 0; int64_t j = i - 1; - while (j >= start && targets[j] > key) { + while (j >= start && (targets[j] > key || + (targets[j] == key && rowmap && rowmap[j] > row_key))) { targets[j + 1] = targets[j]; if (rowmap) rowmap[j + 1] = rowmap[j]; j--; @@ -103,32 +114,278 @@ static void csr_sort_adjacency_lists(ray_csr_t* csr) { if (rowmap) rowmap[j + 1] = row_key; } } + ray_free_raw(cells); +} + +/* Parallel two-level build. Keys are first partitioned into B contiguous + * node-range buckets (B ~ CSR_PAR_BUCKETS, each a power-of-two range of + * nodes), then every bucket is counting-sorted on its own. Each task has + * a private histogram row, so no pass touches a shared counter; the only + * cross-task step is the serial prefix scan over T*B entries. + * + * Scratch is (key, val) as int32 when n_nodes fits (the usual case; the + * scatter is memory-bound and this cuts its traffic by a third) plus the + * int64 row, so 16 bytes per edge; 24 with int64 keys. */ +int64_t ray_csr_par_min_edges = 1 << 20; +#define CSR_PAR_MAX_TASKS 8 /* memory-bound: 4-8 tasks is the knee on a 32-thread box */ +#define CSR_PAR_BUCKETS 256 + +typedef struct { + const int64_t* keys; /* NULL: key = row index */ + const int64_t* vals; + int64_t n_edges, n_nodes; + int T, B, shift; + bool narrow; /* int32 scratch */ + int64_t* hist; /* [T * B]: counts, then cursors */ + uint8_t* wide; /* [T]: a task saw an in-range value past int32 */ + int64_t* bstart; /* [B + 1]: bucket edge ranges in scratch */ + void* skeys; void* svals; /* int32 or int64, n_edges each */ + int64_t* srow; /* n_edges */ + int64_t* off; int64_t* tgt; int64_t* rmap; /* final CSR arrays */ + int64_t* pos; /* [n_nodes] cursors (per-bucket private) */ +} csr_par_t; + +static inline int64_t csr_par_key(const csr_par_t* c, int64_t i) { + return c->keys ? c->keys[i] : i; +} + +static void csr_par_task_range(const csr_par_t* c, uint32_t t, + int64_t* lo, int64_t* hi) { + *lo = c->n_edges * (int64_t)t / c->T; + *hi = c->n_edges * (int64_t)(t + 1) / c->T; +} + +/* Phase 1: per-task bucket histogram. */ +static void csr_par_hist_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; (void)end; + csr_par_t* c = (csr_par_t*)ctx; + uint32_t t = (uint32_t)start; + int64_t lo, hi; csr_par_task_range(c, t, &lo, &hi); + int64_t* h = c->hist + (size_t)t * c->B; + bool wide = false; + for (int64_t i = lo; i < hi; i++) { + int64_t k = csr_par_key(c, i); + if (k < 0 || k >= c->n_nodes) continue; + h[k >> c->shift]++; + int64_t v = c->vals[i]; + wide |= (v < INT32_MIN || v > INT32_MAX); + } + c->wide[t] = wide; +} + +/* Phase 2: per-task scatter into bucket-ordered scratch. */ +static void csr_par_scatter_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; (void)end; + csr_par_t* c = (csr_par_t*)ctx; + uint32_t t = (uint32_t)start; + int64_t lo, hi; csr_par_task_range(c, t, &lo, &hi); + int64_t* cur = c->hist + (size_t)t * c->B; + if (c->narrow) { + int32_t* sk = (int32_t*)c->skeys; int32_t* sv = (int32_t*)c->svals; + for (int64_t i = lo; i < hi; i++) { + int64_t k = csr_par_key(c, i); + if (k < 0 || k >= c->n_nodes) continue; + int64_t p = cur[k >> c->shift]++; + sk[p] = (int32_t)k; sv[p] = (int32_t)c->vals[i]; c->srow[p] = i; + } + } else { + int64_t* sk = (int64_t*)c->skeys; int64_t* sv = (int64_t*)c->svals; + for (int64_t i = lo; i < hi; i++) { + int64_t k = csr_par_key(c, i); + if (k < 0 || k >= c->n_nodes) continue; + int64_t p = cur[k >> c->shift]++; + sk[p] = k; sv[p] = c->vals[i]; c->srow[p] = i; + } + } +} + +/* Phase 3: one task per bucket — counting sort of that bucket's node + * range. off[v] for v in the range and the bucket's edge span of tgt/rmap + * are written by this task only. */ +static void csr_par_bucket_fn(void* ctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; (void)end; + csr_par_t* c = (csr_par_t*)ctx; + int b = (int)start; + int64_t nlo = (int64_t)b << c->shift, nhi = (int64_t)(b + 1) << c->shift; + if (nhi > c->n_nodes) nhi = c->n_nodes; + if (nlo >= nhi) return; + int64_t elo = c->bstart[b], ehi = c->bstart[b + 1]; + for (int64_t v = nlo; v < nhi; v++) c->pos[v] = 0; + if (c->narrow) { + const int32_t* sk = (const int32_t*)c->skeys; + for (int64_t i = elo; i < ehi; i++) c->pos[sk[i]]++; + } else { + const int64_t* sk = (const int64_t*)c->skeys; + for (int64_t i = elo; i < ehi; i++) c->pos[sk[i]]++; + } + int64_t run = elo; + for (int64_t v = nlo; v < nhi; v++) { + int64_t d = c->pos[v]; c->off[v] = run; c->pos[v] = run; run += d; + } + if (c->narrow) { + const int32_t* sk = (const int32_t*)c->skeys; + const int32_t* sv = (const int32_t*)c->svals; + for (int64_t i = elo; i < ehi; i++) { + int64_t p = c->pos[sk[i]]++; + c->tgt[p] = sv[i]; c->rmap[p] = c->srow[i]; + } + } else { + const int64_t* sk = (const int64_t*)c->skeys; + const int64_t* sv = (const int64_t*)c->svals; + for (int64_t i = elo; i < ehi; i++) { + int64_t p = c->pos[sk[i]]++; + c->tgt[p] = sv[i]; c->rmap[p] = c->srow[i]; + } + } +} + +/* A cancelled dispatch skips the tasks that have not started and returns + * normally (pool.h, ORDER CONTRACT); every pass here needs all of its + * tasks, so after each one the build asks and gives up on a cancel. */ +static inline bool csr_par_cancelled(ray_pool_t* pool) { + if (ray_interrupted()) return true; + return atomic_load_explicit(&pool->cancelled, memory_order_relaxed); +} + +static void csr_par_drop(ray_t** v) { + if (*v) { if (RAY_IS_ERR(*v)) ray_error_free(*v); else ray_release(*v); } + *v = NULL; +} + +/* Count valid edges and fill out->offsets/targets/rowmap in parallel. + * Returns 1 when out is built, 0 when the pool should not be used or + * scratch cannot be had (nothing is left in out; the caller builds + * serially), -1 when a cancel interrupted a pass (nothing is left in out; + * the caller reports RAY_ERR_CANCEL rather than hand back a CSR whose + * skipped tasks never wrote their slots). */ +static int csr_build_parallel(const int64_t* keys, const int64_t* vals, + int64_t n_edges, int64_t n_nodes, + ray_csr_t* out) { + ray_pool_t* pool = ray_pool_get(); + if (!ray_pool_par_dispatch_ok(pool, n_edges, ray_csr_par_min_edges) || + n_nodes < 2) + return 0; + int T = (int)ray_pool_total_workers(pool); + if (T > CSR_PAR_MAX_TASKS) T = CSR_PAR_MAX_TASKS; + int shift = 0; + while (((n_nodes - 1) >> shift) >= CSR_PAR_BUCKETS) shift++; + int B = (int)(((n_nodes - 1) >> shift) + 1); + csr_par_t c = { .keys = keys, .vals = vals, .n_edges = n_edges, + .n_nodes = n_nodes, .T = T, .B = B, .shift = shift }; + c.hist = ray_calloc_raw((size_t)T * B * sizeof(int64_t)); + c.wide = ray_calloc_raw((size_t)T); + c.bstart = ray_alloc_raw((size_t)(B + 1) * sizeof(int64_t)); + c.srow = ray_alloc_raw((size_t)n_edges * sizeof(int64_t)); + c.pos = ray_alloc_raw((size_t)n_nodes * sizeof(int64_t)); + bool ok = c.hist && c.wide && c.bstart && c.srow && c.pos; + bool cancelled = false; + + if (ok) { + ray_pool_dispatch_n(pool, csr_par_hist_fn, &c, (uint32_t)T); + cancelled = csr_par_cancelled(pool); + } + if (ok && !cancelled) { + /* Scratch width, known only now: values are stored unchecked (an + * out-of-range dst stays in fwd), so the narrow scratch needs every + * kept edge's value to fit, and phase 1 saw them all. */ + bool narrow = n_nodes <= INT32_MAX; + for (int t = 0; t < T && narrow; t++) narrow = !c.wide[t]; + c.narrow = narrow; + size_t cell = narrow ? sizeof(int32_t) : sizeof(int64_t); + c.skeys = ray_alloc_raw((size_t)n_edges * cell); + c.svals = ray_alloc_raw((size_t)n_edges * cell); + ok = c.skeys && c.svals; + } + if (ok && !cancelled) { + int64_t run = 0; + for (int b = 0; b < B; b++) { + c.bstart[b] = run; + for (int t = 0; t < T; t++) { + int64_t* h = c.hist + (size_t)t * B + b; + int64_t d = *h; *h = run; run += d; + } + } + c.bstart[B] = run; + int64_t valid_edges = run; + out->n_edges = valid_edges; + + out->offsets = ray_vec_new(RAY_I64, n_nodes + 1); + out->targets = ray_vec_new(RAY_I64, valid_edges > 0 ? valid_edges : 1); + out->rowmap = ray_vec_new(RAY_I64, valid_edges > 0 ? valid_edges : 1); + ok = out->offsets && !RAY_IS_ERR(out->offsets) && + out->targets && !RAY_IS_ERR(out->targets) && + out->rowmap && !RAY_IS_ERR(out->rowmap); + if (ok) { + out->offsets->len = n_nodes + 1; + out->targets->len = valid_edges; + out->rowmap->len = valid_edges; + c.off = (int64_t*)ray_data(out->offsets); + c.tgt = (int64_t*)ray_data(out->targets); + c.rmap = (int64_t*)ray_data(out->rowmap); + c.off[n_nodes] = valid_edges; + ray_pool_dispatch_n(pool, csr_par_scatter_fn, &c, (uint32_t)T); + cancelled = csr_par_cancelled(pool); + if (!cancelled) { + ray_pool_dispatch_n(pool, csr_par_bucket_fn, &c, (uint32_t)B); + cancelled = csr_par_cancelled(pool); + } + } + if (!ok || cancelled) { + /* ray_vec_new hands back an error object on OOM, and + * ray_release is a no-op on those: free them as errors. */ + csr_par_drop(&out->offsets); + csr_par_drop(&out->targets); + csr_par_drop(&out->rowmap); + out->n_edges = 0; + } + } + ray_free_raw(c.hist); ray_free_raw(c.wide); ray_free_raw(c.bstart); + ray_free_raw(c.skeys); ray_free_raw(c.svals); + ray_free_raw(c.srow); ray_free_raw(c.pos); + if (cancelled) return -1; + return ok ? 1 : 0; } -/* Build CSR from sorted edge pairs. - * pairs must be sorted by the 'key' field (src for fwd, dst for rev). */ -static ray_err_t csr_build_from_pairs(edge_pair_t* pairs, int64_t n_edges, - int64_t n_nodes, bool is_reverse, - bool sort_targets, ray_csr_t* out) { +/* Build one CSR direction straight from the edge columns by counting sort: + * degree count, prefix sum, scatter in row order, then sort each list. + * + * keys[i] is the list an edge belongs to and vals[i] its target; a NULL + * keys means key = i (an FK column: every row of the source table is one + * node with one outgoing edge). An edge whose key falls outside + * [0, n_nodes) is dropped; its val is stored as-is, like the row index. + * + * The lists come out sorted by (target, row), the one order a build from + * these edges has ever had, so `sort_targets` only records that fact. */ +static ray_err_t csr_build_direct(const int64_t* keys, const int64_t* vals, + int64_t n_edges, int64_t n_nodes, + bool sort_targets, ray_csr_t* out) { out->n_nodes = n_nodes; out->props = NULL; - /* Count valid edges (those within [0, n_nodes) range) */ - int64_t valid_edges = 0; - for (int64_t i = 0; i < n_edges; i++) { - int64_t key = is_reverse ? pairs[i].dst : pairs[i].src; - if (key >= 0 && key < n_nodes) valid_edges++; + int par = csr_build_parallel(keys, vals, n_edges, n_nodes, out); + if (par < 0) return RAY_ERR_CANCEL; + if (par > 0) { + csr_sort_adjacency_lists(out); + out->sorted = sort_targets; + return RAY_OK; } - out->n_edges = valid_edges; - /* Allocate offsets (n_nodes + 1) */ + /* Offsets (n_nodes + 1), zeroed: off[k + 1] accumulates the degree of k. */ out->offsets = ray_vec_new(RAY_I64, n_nodes + 1); if (!out->offsets || RAY_IS_ERR(out->offsets)) return RAY_ERR_OOM; out->offsets->len = n_nodes + 1; int64_t* off = (int64_t*)ray_data(out->offsets); memset(off, 0, (size_t)(n_nodes + 1) * sizeof(int64_t)); + int64_t valid_edges = 0; + for (int64_t i = 0; i < n_edges; i++) { + int64_t key = keys ? keys[i] : i; + if (key >= 0 && key < n_nodes) { off[key + 1]++; valid_edges++; } + } + out->n_edges = valid_edges; + + for (int64_t i = 1; i <= n_nodes; i++) + off[i] += off[i - 1]; - /* Allocate targets */ out->targets = ray_vec_new(RAY_I64, valid_edges > 0 ? valid_edges : 1); if (!out->targets || RAY_IS_ERR(out->targets)) { ray_release(out->offsets); out->offsets = NULL; @@ -137,7 +394,6 @@ static ray_err_t csr_build_from_pairs(edge_pair_t* pairs, int64_t n_edges, out->targets->len = valid_edges; int64_t* tgt = (int64_t*)ray_data(out->targets); - /* Allocate rowmap */ out->rowmap = ray_vec_new(RAY_I64, valid_edges > 0 ? valid_edges : 1); if (!out->rowmap || RAY_IS_ERR(out->rowmap)) { ray_release(out->offsets); out->offsets = NULL; @@ -147,17 +403,7 @@ static ray_err_t csr_build_from_pairs(edge_pair_t* pairs, int64_t n_edges, out->rowmap->len = valid_edges; int64_t* rmap = (int64_t*)ray_data(out->rowmap); - /* Count degrees */ - for (int64_t i = 0; i < n_edges; i++) { - int64_t key = is_reverse ? pairs[i].dst : pairs[i].src; - if (key >= 0 && key < n_nodes) off[key + 1]++; - } - - /* Prefix sum */ - for (int64_t i = 1; i <= n_nodes; i++) - off[i] += off[i - 1]; - - /* Fill targets + rowmap using a position array */ + /* Scatter: pos[k] is the next free slot of list k. */ ray_t* pos_hdr = ray_alloc((size_t)(n_nodes > 0 ? n_nodes : 1) * sizeof(int64_t)); if (!pos_hdr) { ray_release(out->offsets); out->offsets = NULL; @@ -170,24 +416,17 @@ static ray_err_t csr_build_from_pairs(edge_pair_t* pairs, int64_t n_edges, memcpy(pos, off, (size_t)n_nodes * sizeof(int64_t)); for (int64_t i = 0; i < n_edges; i++) { - int64_t key = is_reverse ? pairs[i].dst : pairs[i].src; - int64_t val = is_reverse ? pairs[i].src : pairs[i].dst; + int64_t key = keys ? keys[i] : i; if (key >= 0 && key < n_nodes) { int64_t p = pos[key]++; - tgt[p] = val; - rmap[p] = pairs[i].row; + tgt[p] = vals[i]; + rmap[p] = i; } } ray_free(pos_hdr); - /* Sort within adjacency lists if requested */ - if (sort_targets) { - csr_sort_adjacency_lists(out); - out->sorted = true; - } else { - out->sorted = false; - } - + csr_sort_adjacency_lists(out); + out->sorted = sort_targets; return RAY_OK; } @@ -206,8 +445,15 @@ ray_rel_t* ray_rel_from_edges(ray_t* edge_table, int64_t dst_sym = ray_sym_intern(dst_col, strlen(dst_col)); if (src_sym < 0 || dst_sym < 0) return NULL; /* sym intern OOM */ - ray_t* src_vec = ray_table_get_col(edge_table, src_sym); - ray_t* dst_vec = ray_table_get_col(edge_table, dst_sym); + /* Known gap: the signature has no error channel, so a column that cannot + * materialize declines with NULL and the error message is dropped. */ + ray_t* src_vec = ray_table_col(edge_table, src_sym); + ray_t* dst_vec = ray_table_col(edge_table, dst_sym); + if ((src_vec && RAY_IS_ERR(src_vec)) || (dst_vec && RAY_IS_ERR(dst_vec))) { + if (src_vec && RAY_IS_ERR(src_vec)) ray_error_free(src_vec); + if (dst_vec && RAY_IS_ERR(dst_vec)) ray_error_free(dst_vec); + return NULL; + } if (!src_vec || !dst_vec) return NULL; if (src_vec->type != RAY_I64 || dst_vec->type != RAY_I64) return NULL; @@ -215,48 +461,31 @@ ray_rel_t* ray_rel_from_edges(ray_t* edge_table, if (n_edges != dst_vec->len) return NULL; if (n_src_nodes < 0 || n_dst_nodes < 0) return NULL; - /* Build edge pairs */ - ray_t* pairs_hdr = ray_alloc((size_t)n_edges * sizeof(edge_pair_t)); - if (!pairs_hdr) return NULL; - edge_pair_t* pairs = (edge_pair_t*)ray_data(pairs_hdr); - - int64_t* src_data = (int64_t*)ray_data(src_vec); - int64_t* dst_data = (int64_t*)ray_data(dst_vec); - for (int64_t i = 0; i < n_edges; i++) { - pairs[i].src = src_data[i]; - pairs[i].dst = dst_data[i]; - pairs[i].row = i; - } + const int64_t* src_data = (const int64_t*)ray_data(src_vec); + const int64_t* dst_data = (const int64_t*)ray_data(dst_vec); - /* Allocate rel */ ray_rel_t* rel = (ray_rel_t*)ray_sys_alloc(sizeof(ray_rel_t)); - if (!rel) { ray_free(pairs_hdr); return NULL; } + if (!rel) return NULL; memset(rel, 0, sizeof(ray_rel_t)); rel->name_sym = -1; - /* Build forward CSR (sorted by src) */ - /* qsort is from libc, not an external dep */ - qsort(pairs, (size_t)n_edges, sizeof(edge_pair_t), cmp_edge_by_src); - ray_err_t err = csr_build_from_pairs(pairs, n_edges, n_src_nodes, false, - sort_targets, &rel->fwd); + /* Forward CSR: lists keyed by src, targets are dst. */ + ray_err_t err = csr_build_direct(src_data, dst_data, n_edges, n_src_nodes, + sort_targets, &rel->fwd); if (err != RAY_OK) { - ray_free(pairs_hdr); ray_sys_free(rel); return NULL; } - /* Build reverse CSR (sorted by dst) */ - qsort(pairs, (size_t)n_edges, sizeof(edge_pair_t), cmp_edge_by_dst); - err = csr_build_from_pairs(pairs, n_edges, n_dst_nodes, true, - sort_targets, &rel->rev); + /* Reverse CSR: lists keyed by dst, targets are src. */ + err = csr_build_direct(dst_data, src_data, n_edges, n_dst_nodes, + sort_targets, &rel->rev); if (err != RAY_OK) { - ray_free(pairs_hdr); csr_free(&rel->fwd); ray_sys_free(rel); return NULL; } - ray_free(pairs_hdr); return rel; } @@ -270,52 +499,49 @@ ray_rel_t* ray_rel_build(ray_t* from_table, const char* fk_col, return NULL; int64_t fk_sym = ray_sym_intern(fk_col, strlen(fk_col)); - ray_t* fk_vec = ray_table_get_col(from_table, fk_sym); + /* Known gap: a column that cannot materialize declines with NULL and the + * error message is dropped (no error channel in the signature). */ + ray_t* fk_vec = ray_table_col(from_table, fk_sym); + if (fk_vec && RAY_IS_ERR(fk_vec)) { ray_error_free(fk_vec); return NULL; } if (!fk_vec || fk_vec->type != RAY_I64) return NULL; if (n_target_nodes < 0) return NULL; int64_t n_edges = fk_vec->len; int64_t n_src_nodes = ray_table_nrows(from_table); - /* Build edge pairs: src = row index, dst = fk value */ - ray_t* pairs_hdr = ray_alloc((size_t)n_edges * sizeof(edge_pair_t)); - if (!pairs_hdr) return NULL; - edge_pair_t* pairs = (edge_pair_t*)ray_data(pairs_hdr); - - int64_t* fk_data = (int64_t*)ray_data(fk_vec); - for (int64_t i = 0; i < n_edges; i++) { - pairs[i].src = i; - pairs[i].dst = fk_data[i]; - pairs[i].row = i; - } + const int64_t* fk_data = (const int64_t*)ray_data(fk_vec); ray_rel_t* rel = (ray_rel_t*)ray_sys_alloc(sizeof(ray_rel_t)); - if (!rel) { ray_free(pairs_hdr); return NULL; } + if (!rel) return NULL; memset(rel, 0, sizeof(ray_rel_t)); rel->name_sym = -1; - /* Build forward CSR */ - qsort(pairs, (size_t)n_edges, sizeof(edge_pair_t), cmp_edge_by_src); - ray_err_t err = csr_build_from_pairs(pairs, n_edges, n_src_nodes, false, - sort_targets, &rel->fwd); + /* Forward CSR: row i is node i with the single edge i -> fk[i]. */ + ray_err_t err = csr_build_direct(NULL, fk_data, n_edges, n_src_nodes, + sort_targets, &rel->fwd); if (err != RAY_OK) { - ray_free(pairs_hdr); ray_sys_free(rel); return NULL; } - /* Build reverse CSR */ - qsort(pairs, (size_t)n_edges, sizeof(edge_pair_t), cmp_edge_by_dst); - err = csr_build_from_pairs(pairs, n_edges, n_target_nodes, true, - sort_targets, &rel->rev); + /* Reverse CSR: lists keyed by fk value, targets are the row indices. */ + ray_t* rows_hdr = ray_alloc((size_t)(n_edges > 0 ? n_edges : 1) * sizeof(int64_t)); + if (!rows_hdr) { + csr_free(&rel->fwd); + ray_sys_free(rel); + return NULL; + } + int64_t* rows = (int64_t*)ray_data(rows_hdr); + for (int64_t i = 0; i < n_edges; i++) rows[i] = i; + err = csr_build_direct(fk_data, rows, n_edges, n_target_nodes, + sort_targets, &rel->rev); + ray_free(rows_hdr); if (err != RAY_OK) { - ray_free(pairs_hdr); csr_free(&rel->fwd); ray_sys_free(rel); return NULL; } - ray_free(pairs_hdr); return rel; } @@ -397,6 +623,31 @@ static ray_err_t csr_save(ray_csr_t* csr, const char* dir, const char* prefix) { return RAY_OK; } +/* The CSR files are plain vectors. The mapping loader refuses an encoded + * (generation-2) column; the copying loader materializes it into a plain + * vector. RAY_OK with *out set; RAY_ERR_NYI for an encoded file mapped + * (the optional ones included: only a missing file is "absent"); + * RAY_ERR_IO for anything else. */ +static ray_err_t csr_col(const char* path, bool use_mmap, ray_t** out) { + *out = NULL; + ray_t* c = use_mmap ? ray_col_mmap(path) : ray_col_load(path); + if (c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL) { ray_release(c); return RAY_ERR_NYI; } + if (c && RAY_IS_ERR(c)) { + /* a nyi on a generation-2 file (e.g. a big-endian host) */ + bool enc = false; + if (strcmp(ray_err_code(c), "nyi") == 0) { + FILE* f = fopen(path, "rb"); + uint8_t h[32]; + if (f) { enc = fread(h, 1, 32, f) == 32 && ray_col_gen_of(h) == 2; fclose(f); } + } + ray_error_free(c); + return enc ? RAY_ERR_NYI : RAY_ERR_IO; + } + if (!c) return RAY_ERR_IO; + *out = c; + return RAY_OK; +} + static ray_err_t csr_load_impl(ray_csr_t* csr, const char* dir, const char* prefix, bool use_mmap) { char path[1024]; @@ -404,28 +655,26 @@ static ray_err_t csr_load_impl(ray_csr_t* csr, const char* dir, const char* pref len = snprintf(path, sizeof(path), "%s/%s_offsets", dir, prefix); if (len < 0 || (size_t)len >= sizeof(path)) return RAY_ERR_IO; - csr->offsets = use_mmap ? ray_col_mmap(path) : ray_col_load(path); - if (!csr->offsets || RAY_IS_ERR(csr->offsets)) { - csr->offsets = NULL; - return RAY_ERR_IO; - } + ray_err_t ce = csr_col(path, use_mmap, &csr->offsets); + if (ce != RAY_OK) return ce; len = snprintf(path, sizeof(path), "%s/%s_targets", dir, prefix); if (len < 0 || (size_t)len >= sizeof(path)) return RAY_ERR_IO; - csr->targets = use_mmap ? ray_col_mmap(path) : ray_col_load(path); - if (!csr->targets || RAY_IS_ERR(csr->targets)) { + ce = csr_col(path, use_mmap, &csr->targets); + if (ce != RAY_OK) { ray_release(csr->offsets); csr->offsets = NULL; - csr->targets = NULL; - return RAY_ERR_IO; + return ce; } len = snprintf(path, sizeof(path), "%s/%s_rowmap", dir, prefix); if (len < 0 || (size_t)len >= sizeof(path)) return RAY_ERR_IO; - csr->rowmap = use_mmap ? ray_col_mmap(path) : ray_col_load(path); - if (!csr->rowmap || RAY_IS_ERR(csr->rowmap)) { - /* rowmap is optional — ignore error */ - csr->rowmap = NULL; + ce = csr_col(path, use_mmap, &csr->rowmap); + if (ce == RAY_ERR_NYI) { + ray_release(csr->offsets); csr->offsets = NULL; + ray_release(csr->targets); csr->targets = NULL; + return ce; } + /* rowmap is optional — a missing or unreadable file is absent */ if (csr->offsets->len < 1) { ray_release(csr->offsets); csr->offsets = NULL; @@ -514,8 +763,13 @@ static ray_rel_t* rel_load_impl(const char* dir, bool use_mmap) { char path[1024]; int len = snprintf(path, sizeof(path), "%s/meta", dir); if (len >= 0 && (size_t)len < sizeof(path)) { - ray_t* meta = use_mmap ? ray_col_mmap(path) : ray_col_load(path); - if (meta && !RAY_IS_ERR(meta) && meta->len >= 5) { + ray_t* meta = NULL; + if (csr_col(path, use_mmap, &meta) == RAY_ERR_NYI) { + csr_free(&rel->fwd); csr_free(&rel->rev); + ray_sys_free(rel); + return NULL; + } + if (meta && meta->len >= 5) { int64_t* md = (int64_t*)ray_data(meta); rel->from_table = (uint16_t)md[0]; rel->to_table = (uint16_t)md[1]; @@ -523,7 +777,7 @@ static ray_rel_t* rel_load_impl(const char* dir, bool use_mmap) { rel->fwd.sorted = md[3] != 0; rel->rev.sorted = md[4] != 0; ray_release(meta); - } else if (meta && !RAY_IS_ERR(meta)) { + } else if (meta) { ray_release(meta); } } diff --git a/src/store/csr.h b/src/store/csr.h index ece3a532b..b9237ac80 100644 --- a/src/store/csr.h +++ b/src/store/csr.h @@ -76,4 +76,9 @@ static inline int64_t* ray_csr_neighbors(ray_csr_t* csr, int64_t node, int64_t* return &t[o[node]]; } +/* Edge count from which ray_rel_from_edges / ray_rel_build count and + * scatter on the pool (csr.c); below it the build is serial. Tests move + * it to force one path or the other. */ +extern int64_t ray_csr_par_min_edges; + #endif /* RAY_CSR_H */ diff --git a/src/store/enc.h b/src/store/enc.h new file mode 100644 index 000000000..e6bbfb5d3 --- /dev/null +++ b/src/store/enc.h @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_ENC_H +#define RAY_ENC_H + +/* Lightweight column encodings over 1024-value vectors. Pure codec + * functions over arrays of T-bit patterns held in uint64_t; no file or + * format knowledge. The byte grammar is normative: see the spec + * docs/superpowers/specs/2026-10-05-compressed-columns-design.md, + * "Encodings". */ + +#include +#include +#include +#include + +#include "store/fsst.h" + +#define RAY_ENC_VEC 1024 +#define RAY_ENC_CHUNK 65536 +#define RAY_ENC_DEPTH_MAX 3 + +/* ---- bit packing (interleaved layout) ---- + * Value i of 1024 belongs to lane i % L, row i / L, L = 1024 / T. Each + * lane packs its T values in row order, least-significant bit first, into + * w consecutive T-bit words; word k of lane l is stored at word index + * k*L + l. w == 0 stores nothing. */ +size_t ray_enc_packed_bytes(int w); +void ray_enc_pack(const uint64_t* u, int T, int w, uint8_t* out); +void ray_enc_unpack(const uint8_t* in, int T, int w, uint64_t* u); +int ray_enc_bitlen(uint64_t x); + +/* ---- kinds and logical values ---- */ +typedef struct { uint8_t T; bool is_signed; bool is_float; } ray_enc_kind_t; + +bool ray_enc_kind_of(int8_t type, uint8_t attrs, ray_enc_kind_t* k); +/* The value kind of a type: ray_enc_kind_of for integer kinds, a float + * kind ({32|64, false, true}) for F32 / F64; false otherwise. */ +bool ray_enc_value_kind(int8_t type, uint8_t attrs, ray_enc_kind_t* k); +bool ray_enc_has_bitmap(int8_t type); +/* A float kind's T-bit pattern (T = 32 or 64) as a double: F32 widened, + * which is exact. The one helper every float path reads values with. */ +static inline double ray_enc_fval(uint64_t b, int T) { + if (T == 32) { uint32_t u = (uint32_t)b; float f; memcpy(&f, &u, 4); return (double)f; } + double d; memcpy(&d, &b, 8); return d; +} +int64_t ray_enc_logical(uint64_t bits, ray_enc_kind_t k); +/* a < b in kind order; on a float kind this is dictionary order: numeric + * on the value (F32 widened), -0.0 before +0.0. The float order is defined + * on non-NaN values only (a NaN is not ordered, so it breaks a sort or a + * binary search): float callers (training, dict_codes, stats) must drop + * NaN / null rows first. */ +bool ray_enc_lt(uint64_t a, uint64_t b, ray_enc_kind_t k); + +/* One vector of input: T-bit patterns, null bitmap (bit i set = row i + * null, bitmap-carrying types only) and the null count (in-band nulls of + * SYM are counted too, with no bitmap). */ +typedef struct { + uint64_t bits[RAY_ENC_VEC]; + uint8_t nullmap[RAY_ENC_VEC / 8]; + int n; + int n_nulls; + ray_enc_kind_t k; + bool bitmap; +} ray_enc_input_t; + +/* n must be 0..RAY_ENC_VEC; otherwise returns false. */ +bool ray_enc_load(const void* data, int8_t type, uint8_t attrs, + int64_t start, int n, ray_enc_input_t* in); + +typedef struct { uint64_t min, max; int runs; bool all_equal; } ray_enc_stats_t; +void ray_enc_stats(const uint64_t* v, int n, ray_enc_kind_t k, ray_enc_stats_t* s); + +/* ---- codec types ---- */ +typedef enum { + RAY_ENC_RAW = 0, RAY_ENC_CONST = 1, RAY_ENC_FOR_BP = 2, RAY_ENC_DELTA_BP = 3, + RAY_ENC_RLE = 4, RAY_ENC_DICT = 5, RAY_ENC_ALP = 6, RAY_ENC_ALP_RD = 7, + RAY_ENC_STR_DICT = 8, RAY_ENC_FSST = 9 +} ray_enc_code_t; + +/* Input contract for every encoder entry point (choose / write / widths): + * values are T-bit patterns held in uint64_t (T in {8,16,32,64}), n in + * 0..1024. Bits above T are ignored by FOR_BP / DELTA_BP, which emit + * masked bases and starts, so a sign-extended input still yields the + * canonical body; RLE and DICT compare whole words and expect canonical + * (masked) input. Packed widths satisfy w <= T. */ + +/* Growable output buffer over the buddy heap. */ +typedef struct { uint8_t* p; size_t len, cap; bool oom; } ray_enc_buf_t; +void ray_enc_buf_free(ray_enc_buf_t* b); +bool ray_enc_buf_put(ray_enc_buf_t* b, const void* src, size_t n); +bool ray_enc_buf_pad8(ray_enc_buf_t* b); + +/* Body sizes in bytes (codec bodies are 8-aligned). */ +int64_t ray_enc_size_raw(int n, int T); +int64_t ray_enc_size_const(void); +int ray_enc_for_width(const uint64_t* v, int n, ray_enc_kind_t k, uint64_t* base); +int64_t ray_enc_size_for(int w); +int ray_enc_delta_width(const uint64_t* v, int n, ray_enc_kind_t k, uint64_t* dbase); +int64_t ray_enc_size_delta(int T, int w); + +/* Child slots (spec "Child slots"). The top-level vector is depth 0. */ +typedef enum { + RAY_ENC_SLOT_TOP = 0, + RAY_ENC_SLOT_RLE_VALUES, /* kind: element type at depth 1, else the enclosing slot's kind */ + RAY_ENC_SLOT_RLE_ENDS, /* kind U16 */ + RAY_ENC_SLOT_CODES, /* kind U32 (DICT / STR_DICT codes) */ + RAY_ENC_SLOT_ALP_INTS, /* kind I64 (spec erratum E-P5-1: the slot table says U64) */ + RAY_ENC_SLOT_ALP_RD_LEFT, /* kind U8 */ + RAY_ENC_SLOT_FSST_LENGTHS /* kind U32: RAW, FOR_BP */ +} ray_enc_slot_t; + +typedef struct { const uint64_t* v; uint32_t n; } ray_enc_dict_t; +typedef struct { uint8_t enc, width; int64_t bytes; } ray_enc_choice_t; + +ray_enc_choice_t ray_enc_choose(const uint64_t* v, int n, ray_enc_kind_t k, + ray_enc_slot_t slot, int depth, + const ray_enc_dict_t* dict); +bool ray_enc_write(const uint64_t* v, int n, ray_enc_kind_t k, + ray_enc_slot_t slot, int depth, const ray_enc_dict_t* dict, + ray_enc_buf_t* out, ray_enc_choice_t* chosen); +/* Write a top-level body in encoding `enc` (children still go through + * selection). False when `enc` is not legal for the kind / dictionary, + * not applicable to the values (CONST on unequal values, DICT on a value + * outside the dictionary), or on OOM. */ +bool ray_enc_write_as(uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* dict, ray_enc_buf_t* out, ray_enc_choice_t* chosen); +/* Size of a top-level body in `enc` (RAW, CONST, FOR_BP, DELTA_BP, RLE, + * DICT), or -1 when not legal or not applicable. */ +int64_t ray_enc_body_size(uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* dict); +/* Decode a body ray_enc_write wrote (depth 0: the body at p; depth > 0: a + * child, its 8-byte header first) into n values; the bytes it spans. */ +int64_t ray_enc_read(const uint8_t* p, size_t avail, uint8_t enc, uint8_t width, + int n, ray_enc_kind_t k, ray_enc_slot_t slot, int depth, + const ray_enc_dict_t* dict, uint64_t* out); +/* Distinct sorted values of v in the logical order of k (ray_enc_lt; on a + * float kind v must hold no NaN, see ray_enc_lt). Returns 1 = + * trained (*out holds *out_n values; free with ray_free_raw), 0 = no + * dictionary (n <= 0 or more than 1<<16 distinct values), -1 = out of + * memory. *out is untouched unless 1 is returned. */ +int ray_enc_train_dict(const uint64_t* v, int64_t n, ray_enc_kind_t k, + uint64_t** out, uint32_t* out_n); + +/* ---- ALP (src/store/enc_alp.c, compiled with strict IEEE flags) ---- + * v holds T-bit float patterns (T 32 or 64), n in 1..1024. */ +/* Runtime control check, not a change of the caller's FP environment. + * Checks standard rounding, and SSE controls where available. Other control + * modes must still obey the documented default-environment precondition. */ +bool ray_enc_fp_env_ok(void); +#define RAY_ENC_FPENV_MSG "generation-2 float encoding/decoding requires default FP controls (FE_TONEAREST, masked exceptions, no FTZ/DAZ)" +#define RAY_ENC_ALP_CANDS 5 +typedef struct { uint8_t e, f; } ray_enc_alp_ef_t; +typedef struct { ray_enc_alp_ef_t c[RAY_ENC_ALP_CANDS]; int n; } ray_enc_alp_cands_t; +/* Candidates from the filled bit patterns of a column's first chunk + * (n values, T 32 or 64): every 32nd value of each 1024-value vector. */ +void ray_enc_alp_train(const uint64_t* bits, int64_t n, int T, ray_enc_alp_cands_t* out); +/* Smallest ALP body over the candidates (*best = its index), -1 when there + * are none. */ +int64_t ray_enc_alp_size(const uint64_t* v, int n, int T, const ray_enc_alp_cands_t* c, int* best); +bool ray_enc_alp_write(const uint64_t* v, int n, int T, uint8_t e, uint8_t f, ray_enc_buf_t* out); +/* Decodes an ALP body into T-bit patterns; returns the body bytes. */ +int64_t ray_enc_alp_read(const uint8_t* p, size_t avail, int n, int T, uint64_t* out); + +/* ---- ALP_RD (src/store/enc_alp.c): each value split into a left part + * (the top T - right_bits bits, a code into an 8-entry dictionary, or an + * exception) and its low right_bits bits packed. v holds T-bit float + * patterns (T 32 or 64), n in 1..1024. The best right_bits in T-16..T-1 + * depends on v only, so size and write agree. ---- */ +/* Smallest ALP_RD body, -1 on bad arguments or OOM. */ +int64_t ray_enc_alprd_size(const uint64_t* v, int n, int T); +/* Appends the body; false on bad arguments (n outside 1..1024, T not 32 + * or 64) or OOM (out->oom), with no partial body left in out. */ +bool ray_enc_alprd_write(const uint64_t* v, int n, int T, ray_enc_buf_t* out); +/* Decodes an ALP_RD body into T-bit patterns (out holds RAY_ENC_VEC + * values); returns the body bytes. */ +int64_t ray_enc_alprd_read(const uint8_t* p, size_t avail, int n, int T, uint64_t* out); + +/* ---- the float top level ---- */ +/* The float vector's top-level choice among RAW, CONST, RLE, DICT, ALP, + * ALP_RD; `extra` is the trailer's bytes, counted on both sides of the + * 1/8 gain rule. dict and c may be NULL (no DICT, no ALP). */ +ray_enc_choice_t ray_enc_float_choose(const uint64_t* v, int n, int T, const ray_enc_dict_t* dict, + const ray_enc_alp_cands_t* c, int64_t extra); +/* Write `enc`'s body (false: not applicable, illegal or OOM; out->oom tells). */ +bool ray_enc_float_write(uint8_t enc, const uint64_t* v, int n, int T, const ray_enc_dict_t* dict, + const ray_enc_alp_cands_t* c, ray_enc_buf_t* out, ray_enc_choice_t* chosen); +/* Decode any float body; the bytes used. */ +int64_t ray_enc_float_read(const uint8_t* p, size_t avail, uint8_t enc, int n, int T, + const ray_enc_dict_t* dict, uint64_t* out); + +/* ---- STR bodies (src/store/enc_str.c), n in 0..1024 ---- + * STR_DICT: child `codes` (U32), each below the STR_DICT entry count. + * FSST: child `lengths` (U32, RAW or FOR_BP), u64 total_bytes (the sum of + * the lengths), the compressed bytes padded to 8 with zeros. */ +int64_t ray_enc_strdict_size(const uint64_t* codes, int n); +bool ray_enc_strdict_write(const uint64_t* codes, int n, ray_enc_buf_t* out); +/* The n codes of a STR_DICT body. */ +void ray_enc_strdict_read(const uint8_t* p, size_t avail, int n, uint64_t* codes); +/* Compress n strings: buf receives the concatenated codes (capacity at + * least 2 x the strings' bytes), clen[i] each string's compressed length. + * Returns the total compressed bytes. */ +uint64_t ray_enc_fsst_encode(const ray_fsst_table_t* t, const ray_fsst_index_t* ix, + const char* const* s, const uint32_t* len, int n, + uint8_t* buf, uint64_t* clen); +int64_t ray_enc_fsst_size(const uint64_t* clen, int n, uint64_t total); +/* Appends the body; false on bad arguments (n outside 0..1024, a length + * above UINT32_MAX, total not their sum) or OOM (out->oom), with no + * partial body left in out. */ +bool ray_enc_fsst_write(const uint64_t* clen, int n, const uint8_t* bytes, uint64_t total, + ray_enc_buf_t* out); +/* An FSST body against table t: clen[] (compressed lengths), xlen[] + * (expanded lengths) and *bytes (the compressed area). */ +void ray_enc_fsst_parse(const uint8_t* p, size_t avail, int n, const ray_fsst_table_t* t, + uint64_t* clen, uint64_t* xlen, const uint8_t** bytes); + +#endif /* RAY_ENC_H */ diff --git a/src/store/enc_alp.c b/src/store/enc_alp.c new file mode 100644 index 000000000..53326fe1f --- /dev/null +++ b/src/store/enc_alp.c @@ -0,0 +1,509 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* ALP (spec "Encodings", code 6): a float vector as decimal integers + * ints[i] with one exponent / factor pair (e, f) per vector, decoded by + * the fixed expression (double)ints[i] * F10[f] * IF10[e]. The encoder + * keeps a value only if that expression gives back its exact bits; + * everything else (NaN, inf, -0.0, out of range, not decimal) is an + * exception stored raw. + * + * This file is compiled with strict IEEE arithmetic in every build + * profile (STRICT_FP_CFLAGS, Makefile): reassociation or contraction would + * change the decoded bits between a release and a debug build. */ +#include "store/enc.h" +#include +#include +#include /* qsort (ALP_RD) */ +#include +#if !defined(__wasm__) +#include +#endif +#if defined(__SSE__) +#include +#endif + +bool ray_enc_fp_env_ok(void) { +#if defined(__wasm__) + /* WebAssembly's arithmetic has fixed nearest rounding and no host FCSR. */ + return true; +#else + if (fegetround() != FE_TONEAREST) return false; +#if defined(__SSE__) + /* Ignore accrued exception status; validate rounding, denormal controls + * and exception masks, including an SSE/x87 rounding mismatch. */ + const unsigned control_mask = 0xffc0u; + const unsigned default_controls = 0x1f80u; + if ((_mm_getcsr() & control_mask) != default_controls) return false; +#endif + return true; +#endif +} + +#if defined(__FAST_MATH__) || defined(__ASSOCIATIVE_MATH__) || defined(__NO_SIGNED_ZEROS__) || \ + (defined(__GCC_IEC_559) && __GCC_IEC_559 < 2) +# error "src/store/enc_alp.c needs strict IEEE flags (STRICT_FP_CFLAGS, Makefile)" +#endif +_Static_assert(FLT_EVAL_METHOD == 0, "ALP needs FLT_EVAL_METHOD 0 (no x87 excess precision)"); +#if defined(__clang__) +/* Clang defines none of the macros above; the Makefile rule is what + * protects it, and these pragmas pin the same rules in the source. */ +# pragma clang fp contract(off) reassociate(off) +#endif + +/* Fixed tables of 10^k and 10^-k in the element's precision (spec "ALP"). */ +static const double F10[19] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, + 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18 }; +static const double IF10[19] = { 1e0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, + 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16, 1e-17, 1e-18 }; +static const float F10F[19] = { 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, 1e8f, 1e9f, 1e10f, + 1e11f, 1e12f, 1e13f, 1e14f, 1e15f, 1e16f, 1e17f, 1e18f }; +static const float IF10F[19] = { 1e0f, 1e-1f, 1e-2f, 1e-3f, 1e-4f, 1e-5f, 1e-6f, 1e-7f, 1e-8f, 1e-9f, 1e-10f, + 1e-11f, 1e-12f, 1e-13f, 1e-14f, 1e-15f, 1e-16f, 1e-17f, 1e-18f }; + +static inline int64_t p8(int64_t x) { return (x + 7) & ~(int64_t)7; } +/* The ints child is I64 (spec erratum E-P5-1): FOR_BP takes its base and + * range in signed order, so mixed-sign decimals pack at their real width. */ +static const ray_enc_kind_t K_I64 = { 64, true, false }; +static inline bool alp_t_ok(int T) { return T == 32 || T == 64; } + +/* Decode of one integer (the spec's expression). */ +static uint64_t alp_dec1(int64_t n, int T, int e, int f) { + if (T == 64) { double b = (double)n * F10[f] * IF10[e]; uint64_t u; memcpy(&u, &b, 8); return u; } + float b = (float)n * F10F[f] * IF10F[e]; uint32_t u; memcpy(&u, &b, 4); return u; +} + +/* The value's integer in (e, f), or false when it is an exception. */ +static bool alp_enc1(uint64_t bits, int T, int e, int f, int64_t* out) { + int64_t r; + if (T == 64) { + double x; memcpy(&x, &bits, 8); + double d = x * F10[e] * IF10[f]; + if (!(d > -9.0e18 && d < 9.0e18)) return false; /* NaN, inf, out of range */ + r = (int64_t)(d < 0 ? d - 0.5 : d + 0.5); + } else { + uint32_t b32 = (uint32_t)bits; float x; memcpy(&x, &b32, 4); + float d = x * F10F[e] * IF10F[f]; + if (!(d > -9.0e18f && d < 9.0e18f)) return false; + r = (int64_t)(d < 0 ? d - 0.5f : d + 0.5f); + bits = b32; /* the lane's 32 bits only */ + } + if (alp_dec1(r, T, e, f) != bits) return false; /* keep only bit-exact values */ + *out = r; + return true; +} + +typedef struct { int n_exc; uint16_t pos[RAY_ENC_VEC]; uint64_t ints[RAY_ENC_VEC]; } alp_plan_t; + +/* ints for every row and the exception positions; an exception row holds + * the vector's first non-exception integer (0 if none). */ +static void alp_plan(const uint64_t* v, int n, int T, int e, int f, alp_plan_t* p) { + int64_t first = 0; bool have = false; + p->n_exc = 0; + for (int i = 0; i < n; i++) { + int64_t r; + if (alp_enc1(v[i], T, e, f, &r)) { + if (!have) { first = r; have = true; } + p->ints[i] = (uint64_t)r; + } else { + p->pos[p->n_exc++] = (uint16_t)i; + p->ints[i] = UINT64_MAX; /* marked; set below */ + } + } + for (int k = 0; k < p->n_exc; k++) p->ints[p->pos[k]] = (uint64_t)first; +} + +static int64_t alp_plan_size(const alp_plan_t* p, int n, int T) { + ray_enc_choice_t c = ray_enc_choose(p->ints, n, K_I64, RAY_ENC_SLOT_ALP_INTS, 1, NULL); + return 8 + c.bytes + p8(2LL * p->n_exc) + p8((int64_t)p->n_exc * (T / 8)); +} + +/* alp_plan_t is about 10 KB: heap, not stack (this runs on pool workers). */ +static bool alp_args_ok(int n, int T, const ray_enc_alp_cands_t* c) { + if (!c || c->n <= 0 || c->n > RAY_ENC_ALP_CANDS || n <= 0 || n > RAY_ENC_VEC || !alp_t_ok(T)) return false; + for (int i = 0; i < c->n; i++) if (c->c[i].e > 18 || c->c[i].f > c->c[i].e) return false; + return true; +} + +int64_t ray_enc_alp_size(const uint64_t* v, int n, int T, const ray_enc_alp_cands_t* c, int* best) { + if (!alp_args_ok(n, T, c)) return -1; + alp_plan_t* p = ray_alloc_raw(sizeof *p); + if (!p) return -1; + int64_t bs = -1; + for (int i = 0; i < c->n; i++) { + alp_plan(v, n, T, c->c[i].e, c->c[i].f, p); + int64_t s = alp_plan_size(p, n, T); + if (bs < 0 || s < bs) { bs = s; *best = i; } + } + ray_free_raw(p); + return bs; +} + +bool ray_enc_alp_write(const uint64_t* v, int n, int T, uint8_t e, uint8_t f, ray_enc_buf_t* out) { + if (n <= 0 || n > RAY_ENC_VEC || !alp_t_ok(T) || e > 18 || f > e) return false; + alp_plan_t* p = ray_alloc_raw(sizeof *p); + if (!p) { out->oom = true; return false; } + alp_plan(v, n, T, e, f, p); + size_t at = out->len; + uint16_t ne = (uint16_t)p->n_exc; + uint8_t h[8] = { e, f, 0, 0, 0, 0, 0, 0 }; + memcpy(h + 2, &ne, 2); + ray_enc_choice_t c; + bool ok = ray_enc_buf_put(out, h, 8) && + ray_enc_write(p->ints, n, K_I64, RAY_ENC_SLOT_ALP_INTS, 1, NULL, out, &c) && + ray_enc_buf_put(out, p->pos, 2u * ne) && ray_enc_buf_pad8(out); + for (int k = 0; ok && k < ne; k++) ok = ray_enc_buf_put(out, &v[p->pos[k]], (size_t)T / 8); + ok = ok && ray_enc_buf_pad8(out); + ray_free_raw(p); + if (!ok) out->len = at; /* no partial body */ + return ok; +} + +/* The body of an ALP ints child at c when it is a FOR_BP child (decoded + * by the fused pass below); else NULL, and ray_enc_read reads the child. */ +static const uint8_t* alp_for_child(const uint8_t* c) { + return c[0] == RAY_ENC_FOR_BP ? c + 8 : NULL; +} + +/* ALP decode fused with the FOR_BP unpack of its ints (I64 lanes: L = 16 + * words per row, row r's field at bit r * w of its lane): base + field, + * then alp_dec1, row by row over contiguous lanes. The same integers and + * the same expression as ray_enc_read followed by the alp_dec1 loop. */ +static inline __attribute__((always_inline)) void alp_dec_for(const uint8_t* b, int w, int n, int T, int e, int f, + uint64_t* restrict out) { + enum { L = RAY_ENC_VEC / 64 }; + uint64_t base; memcpy(&base, b, 8); + const uint8_t* pk = b + 8; + const uint64_t vm = w >= 64 ? ~0ull : (1ull << w) - 1; + /* F64 with every integer inside [-2^51, 2^51): the integer added to + * the pattern of 1.5 * 2^52, then 1.5 * 2^52 subtracted, is the + * integer as a double exactly (both steps are exact), so the bits + * are (double)n's; unlike the int64 conversion it vectorises. The + * multiplies are alp_dec1's, in its order. */ + const int64_t lim = (int64_t)1 << 51; + /* w <= 50 is kept although the base test bounds base + u for most + * widths: at w = 64, (int64_t)vm is -1 and the test would admit a base + * near 2^51 with u up to 2^64 - 1. The guard keeps vm < 2^50, so + * lim - vm cannot wrap and every base + u lies in [-2^51, 2^51). */ + if (T == 64 && w >= 1 && w <= 50 && (int64_t)base >= -lim && (int64_t)base < lim - (int64_t)vm) { + const double m1 = F10[f], m2 = IF10[e], mg = 6755399441055744.0; /* 1.5 * 2^52 */ + const uint64_t mgb = 0x4338000000000000ull; + for (int r = 0, bit = 0; r * L < n; r++, bit += w) { + const int k = bit / 64, off = bit % 64; + const int nl = n - r * L < L ? n - r * L : L; + uint64_t* o = out + (size_t)r * L; + const uint8_t* lo = pk + (size_t)k * L * 8; + const unsigned sl = (unsigned)(64 - off) & 63; + const bool two = off + w > 64; + for (int l = 0; l < nl; l++) { + uint64_t x0, x1 = 0; memcpy(&x0, lo + 8 * l, 8); + if (two) memcpy(&x1, lo + 8 * (l + L), 8); + const uint64_t u = ((x0 >> off) | (two ? x1 << sl : 0)) & vm; + const uint64_t t = base + u + mgb; + double d; memcpy(&d, &t, 8); + const double b = (d - mg) * m1 * m2; + memcpy(&o[l], &b, 8); + } + } + return; + } + for (int r = 0, bit = 0; r * L < n; r++, bit += w) { + const int k = bit / 64, off = bit % 64; + const int nl = n - r * L < L ? n - r * L : L; + uint64_t* o = out + (size_t)r * L; + const uint8_t* lo = pk + (size_t)k * L * 8; + if (w == 0) { + for (int l = 0; l < nl; l++) o[l] = alp_dec1((int64_t)base, T, e, f); + } else if (off + w > 64) { + for (int l = 0; l < nl; l++) { + uint64_t x0, x1; memcpy(&x0, lo + 8 * l, 8); memcpy(&x1, lo + 8 * (l + L), 8); + o[l] = alp_dec1((int64_t)(base + (((x0 >> off) | (x1 << (64 - off))) & vm)), T, e, f); + } + } else { + for (int l = 0; l < nl; l++) { + uint64_t x0; memcpy(&x0, lo + 8 * l, 8); + o[l] = alp_dec1((int64_t)(base + ((x0 >> off) & vm)), T, e, f); + } + } + } +} + +int64_t ray_enc_alp_read(const uint8_t* p, size_t avail, int n, int T, uint64_t* out) { + uint8_t e = p[0], f = p[1]; + uint16_t ne; memcpy(&ne, p + 2, 2); + /* A FOR_BP ints child (the usual case) is decoded below in one fused + * pass; any other child is read by ray_enc_read. */ + const uint8_t* fb = alp_for_child(p + 8); + int64_t a; + if (fb) { + uint32_t bb; memcpy(&bb, p + 8 + 4, 4); + a = 8 + (int64_t)bb; + } else { + a = ray_enc_read(p + 8, avail - 8, 0, 0, n, K_I64, RAY_ENC_SLOT_ALP_INTS, 1, NULL, out); /* ints, decoded in place below */ + } + size_t at = 8 + (size_t)a, esz = (size_t)T / 8; + size_t pb = (size_t)p8(2LL * ne), rb = (size_t)p8((int64_t)ne * (int64_t)esz); + const uint8_t* pos = p + at; + const uint8_t* raw = pos + pb; + if (fb) { + if (T == 64) alp_dec_for(fb, p[9], n, 64, e, f, out); else alp_dec_for(fb, p[9], n, 32, e, f, out); + } else { + for (int i = 0; i < n; i++) out[i] = alp_dec1((int64_t)out[i], T, e, f); + } + for (int k = 0; k < ne; k++) { + uint16_t q; memcpy(&q, pos + 2 * k, 2); + uint64_t x = 0; memcpy(&x, raw + (size_t)k * esz, esz); + out[q] = x; + } + return (int64_t)(at + pb + rb); +} + +/* ---- candidates: 32-value samples, the five most frequent winners ---- */ +/* The (e, f) with the fewest exceptions on the sample, then the narrowest + * integer range; scanned in increasing e, then f, replacing only on a + * strictly better pair, so ties keep the smaller pair. */ +static void alp_best_ef(const uint64_t* s, int ns, int T, int* be, int* bf, int* bexc) { + int best_exc = ns + 1, best_w = 65, e_best = 0, f_best = 0; + for (int e = 0; e <= 18; e++) + for (int f = 0; f <= e; f++) { + int exc = 0; bool have = false; int64_t mn = 0, mx = 0; + for (int i = 0; i < ns; i++) { + int64_t r; + if (!alp_enc1(s[i], T, e, f, &r)) { exc++; continue; } + if (!have || r < mn) mn = r; + if (!have || r > mx) mx = r; + have = true; + } + int w = have ? ray_enc_bitlen((uint64_t)mx - (uint64_t)mn) : 0; + if (exc < best_exc || (exc == best_exc && w < best_w)) { + best_exc = exc; best_w = w; e_best = e; f_best = f; + } + } + *be = e_best; *bf = f_best; *bexc = best_exc; +} + +void ray_enc_alp_train(const uint64_t* bits, int64_t n, int T, ray_enc_alp_cands_t* out) { + uint32_t count[19][19]; + memset(count, 0, sizeof count); + memset(out, 0, sizeof *out); + for (int64_t s = 0; s < n; s += RAY_ENC_VEC) { + int vn = (int)(n - s < RAY_ENC_VEC ? n - s : RAY_ENC_VEC); + uint64_t smp[RAY_ENC_VEC / 32]; + int ns = 0; + for (int i = 0; i < vn; i += 32) smp[ns++] = bits[s + i]; + int e, f, exc; + alp_best_ef(smp, ns, T, &e, &f, &exc); + if (exc < ns) count[e][f]++; + } + for (int k = 0; k < RAY_ENC_ALP_CANDS; k++) { + uint32_t bc = 0; int be = -1, bf = -1; + for (int e = 0; e <= 18; e++) + for (int f = 0; f <= e; f++) + if (count[e][f] > bc) { bc = count[e][f]; be = e; bf = f; } /* ties: smaller e, f first */ + if (be < 0) break; + out->c[out->n].e = (uint8_t)be; out->c[out->n].f = (uint8_t)bf; out->n++; + count[be][bf] = 0; + } +} + +/* ---- ALP_RD (spec "Encodings", code 7) ---- + * Integer arithmetic only: the bytes do not depend on the float flags. */ +static const ray_enc_kind_t K_U8 = { 8, false, false }; + +typedef struct { + int rb, dict_n, n_exc; + uint16_t dict[8]; + uint64_t codes[RAY_ENC_VEC]; + uint16_t pos[RAY_ENC_VEC], lefts[RAY_ENC_VEC]; +} alprd_plan_t; + +static inline uint64_t alprd_mask(int T) { return T == 64 ? ~0ull : 0xFFFFFFFFull; } + +static int u16_cmp(const void* a, const void* b) { + uint16_t x = *(const uint16_t*)a, y = *(const uint16_t*)b; + return x < y ? -1 : x > y; +} + +/* The plan at one right_bits: the eight most frequent left parts as the + * dictionary (strictly ascending), a code per row, the rest exceptions + * (code 0, raw left part kept). */ +static void alprd_plan_rb(const uint64_t* v, int n, int T, int rb, alprd_plan_t* p) { + const uint64_t m = alprd_mask(T); + uint16_t s[RAY_ENC_VEC]; + for (int i = 0; i < n; i++) s[i] = (uint16_t)((v[i] & m) >> rb); + if (n > 1) qsort(s, (size_t)n, 2, u16_cmp); + /* the eight most frequent left parts; ties: the smaller value */ + uint16_t val[8]; int cnt[8]; int nd = 0; + for (int i = 0; i < n;) { + int j = i; while (j < n && s[j] == s[i]) j++; + int c = j - i; + int at = nd; + while (at > 0 && cnt[at - 1] < c) at--; /* stable: equal counts keep order */ + if (at < 8) { + for (int k = (nd < 8 ? nd : 7); k > at; k--) { val[k] = val[k - 1]; cnt[k] = cnt[k - 1]; } + val[at] = s[i]; cnt[at] = c; + if (nd < 8) nd++; + } + i = j; + } + if (nd > 1) qsort(val, (size_t)nd, 2, u16_cmp); /* strictly ascending */ + p->rb = rb; p->dict_n = nd; p->n_exc = 0; + if (nd > 0) memcpy(p->dict, val, (size_t)nd * 2); + for (int i = 0; i < n; i++) { + uint16_t l = (uint16_t)((v[i] & m) >> rb); + int code = -1; + for (int k = 0; k < nd; k++) if (p->dict[k] == l) { code = k; break; } + if (code < 0) { p->codes[i] = 0; p->pos[p->n_exc] = (uint16_t)i; p->lefts[p->n_exc++] = l; } + else p->codes[i] = (uint64_t)code; + } +} + +static int64_t alprd_plan_size(const alprd_plan_t* p, int n) { + ray_enc_choice_t c = ray_enc_choose(p->codes, n, K_U8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL); + return 8 + p8(2LL * p->dict_n) + c.bytes + (int64_t)ray_enc_packed_bytes(p->rb) + 2 * p8(2LL * p->n_exc); +} + +/* The smallest plan over right_bits T-1 down to T-16 (ties keep the larger + * right_bits); -1 on OOM. alprd_plan_t is about 12 KB: heap, not stack. */ +static int64_t alprd_best(const uint64_t* v, int n, int T, alprd_plan_t* best) { + alprd_plan_t* p = ray_alloc_raw(sizeof *p); + if (!p) return -1; + int64_t bs = -1; + for (int rb = T - 1; rb >= T - 16; rb--) { + alprd_plan_rb(v, n, T, rb, p); + int64_t s = alprd_plan_size(p, n); + if (bs < 0 || s < bs) { bs = s; if (best) *best = *p; } + } + ray_free_raw(p); + return bs; +} + +int64_t ray_enc_alprd_size(const uint64_t* v, int n, int T) { + if (n <= 0 || n > RAY_ENC_VEC || !alp_t_ok(T)) return -1; + return alprd_best(v, n, T, NULL); +} + +bool ray_enc_alprd_write(const uint64_t* v, int n, int T, ray_enc_buf_t* out) { + if (n <= 0 || n > RAY_ENC_VEC || !alp_t_ok(T)) return false; + alprd_plan_t* p = ray_alloc_raw(sizeof *p); + if (!p) { out->oom = true; return false; } + if (alprd_best(v, n, T, p) < 0) { ray_free_raw(p); out->oom = true; return false; } /* p unset */ + size_t at = out->len; + const uint64_t m = alprd_mask(T), rm = (1ull << p->rb) - 1; /* rb <= T - 1 <= 63 */ + uint16_t ne = (uint16_t)p->n_exc; + uint8_t h[8] = { (uint8_t)p->rb, (uint8_t)p->dict_n, 0, 0, 0, 0, 0, 0 }; + memcpy(h + 2, &ne, 2); + ray_enc_choice_t c; + bool ok = ray_enc_buf_put(out, h, 8) && ray_enc_buf_put(out, p->dict, 2u * (size_t)p->dict_n) && + ray_enc_buf_pad8(out) && + ray_enc_write(p->codes, n, K_U8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL, out, &c); + if (ok) { + uint64_t* u = p->codes; /* codes written: reuse for the right parts */ + for (int i = 0; i < RAY_ENC_VEC; i++) u[i] = i < n ? (v[i] & m & rm) : 0; /* pad rows 0 */ + size_t pk = out->len; + ok = ray_enc_buf_put(out, NULL, ray_enc_packed_bytes(p->rb)); + if (ok) ray_enc_pack(u, T, p->rb, out->p + pk); + } + ok = ok && ray_enc_buf_put(out, p->pos, 2u * ne) && ray_enc_buf_pad8(out) && + ray_enc_buf_put(out, p->lefts, 2u * ne) && ray_enc_buf_pad8(out); + ray_free_raw(p); + if (!ok) out->len = at; /* no partial body */ + return ok; +} + +int64_t ray_enc_alprd_read(const uint8_t* p, size_t avail, int n, int T, uint64_t* out) { + int rb = p[0], dn = p[1]; + uint16_t ne; memcpy(&ne, p + 2, 2); + size_t at = 8, db = (size_t)p8(2LL * dn); + uint16_t dict[8]; + for (int k = 0; k < dn; k++) memcpy(&dict[k], p + at + 2 * k, 2); + at += db; + uint64_t codes[RAY_ENC_VEC]; + int64_t a = ray_enc_read(p + at, avail - at, 0, 0, n, K_U8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL, codes); + at += (size_t)a; + size_t pk = ray_enc_packed_bytes(rb); + size_t pb = (size_t)p8(2LL * ne); + const uint8_t* pos = p + at + pk; + const uint8_t* lefts = pos + pb; + /* the right parts go straight into out (a whole vector: no second 8 KB + * array), then the left parts */ + ray_enc_unpack(p + at, T, rb, out); + for (int i = 0; i < n; i++) out[i] |= (uint64_t)dict[codes[i]] << rb; + for (int k = 0; k < ne; k++) { + uint16_t q, l; memcpy(&q, pos + 2 * k, 2); memcpy(&l, lefts + 2 * k, 2); + out[q] = (out[q] & ((1ull << rb) - 1)) | ((uint64_t)l << rb); /* code 0 replaced */ + } + return (int64_t)(at + pk + 2 * pb); +} + +/* ---- the float top level ---- */ +ray_enc_choice_t ray_enc_float_choose(const uint64_t* v, int n, int T, const ray_enc_dict_t* dict, + const ray_enc_alp_cands_t* c, int64_t extra) { + ray_enc_kind_t fk = { (uint8_t)T, false, true }; + int64_t raw = ray_enc_size_raw(n, T); + ray_enc_choice_t best = { RAY_ENC_RAW, 0, raw }; + if (!alp_t_ok(T) || n <= 0 || n > RAY_ENC_VEC) return best; + static const uint8_t ints_like[] = { RAY_ENC_CONST, RAY_ENC_RLE, RAY_ENC_DICT }; + for (size_t i = 0; i < sizeof ints_like; i++) { + int64_t s = ray_enc_body_size(ints_like[i], v, n, fk, dict); + if (s >= 0 && s < best.bytes) { best.enc = ints_like[i]; best.bytes = s; } + } + int bi; + int64_t s = ray_enc_alp_size(v, n, T, c, &bi); /* -1: no candidates (or OOM) */ + if (s >= 0 && s < best.bytes) { best.enc = RAY_ENC_ALP; best.bytes = s; } + s = ray_enc_alprd_size(v, n, T); + if (s >= 0 && s < best.bytes) { best.enc = RAY_ENC_ALP_RD; best.bytes = s; } + if (best.enc != RAY_ENC_RAW && (best.bytes + extra) * 8 > (raw + extra) * 7) { /* 1/8 gain */ + best.enc = RAY_ENC_RAW; best.bytes = raw; + } + return best; +} + +bool ray_enc_float_write(uint8_t enc, const uint64_t* v, int n, int T, const ray_enc_dict_t* dict, + const ray_enc_alp_cands_t* c, ray_enc_buf_t* out, ray_enc_choice_t* chosen) { + if (!alp_t_ok(T)) return false; + ray_enc_kind_t fk = { (uint8_t)T, false, true }; + size_t at = out->len; + bool ok; + if (enc == RAY_ENC_ALP) { + int bi; + if (!alp_args_ok(n, T, c)) return false; /* no candidates: not applicable */ + if (ray_enc_alp_size(v, n, T, c, &bi) < 0) { out->oom = true; return false; } /* valid args: OOM */ + ok = ray_enc_alp_write(v, n, T, c->c[bi].e, c->c[bi].f, out); + } else if (enc == RAY_ENC_ALP_RD) { + ok = ray_enc_alprd_write(v, n, T, out); + } else { + return ray_enc_write_as(enc, v, n, fk, dict, out, chosen); + } + if (!ok) { out->len = at; return false; } + if (chosen) { chosen->enc = enc; chosen->width = 0; chosen->bytes = (int64_t)(out->len - at); } + return true; +} + +int64_t ray_enc_float_read(const uint8_t* p, size_t avail, uint8_t enc, int n, int T, + const ray_enc_dict_t* dict, uint64_t* out) { + if (enc == RAY_ENC_ALP) return ray_enc_alp_read(p, avail, n, T, out); + if (enc == RAY_ENC_ALP_RD) return ray_enc_alprd_read(p, avail, n, T, out); + ray_enc_kind_t fk = { (uint8_t)T, false, true }; + return ray_enc_read(p, avail, enc, 0, n, fk, RAY_ENC_SLOT_TOP, 0, dict, out); +} diff --git a/src/store/enc_codec.c b/src/store/enc_codec.c new file mode 100644 index 000000000..2694d0804 --- /dev/null +++ b/src/store/enc_codec.c @@ -0,0 +1,436 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "store/enc.h" +#include +#include + +static inline uint64_t tmask(int T) { return T == 64 ? ~0ull : ((1ull << T) - 1); } +static inline int64_t pad8(int64_t x) { return (x + 7) & ~(int64_t)7; } + +/* ---- buffer ---- */ +void ray_enc_buf_free(ray_enc_buf_t* b) { + if (b->p) ray_free_raw(b->p); + b->p = NULL; b->len = b->cap = 0; b->oom = false; +} + +bool ray_enc_buf_put(ray_enc_buf_t* b, const void* src, size_t n) { + if (b->oom) return false; + if (b->len + n > b->cap) { + size_t cap = b->cap ? b->cap : 4096; + while (cap < b->len + n) cap *= 2; + void* p = ray_realloc_raw(b->p, cap); + if (!p) { b->oom = true; return false; } + b->p = p; b->cap = cap; + } + if (src) memcpy(b->p + b->len, src, n); else memset(b->p + b->len, 0, n); + b->len += n; + return true; +} + +bool ray_enc_buf_pad8(ray_enc_buf_t* b) { + size_t want = (size_t)pad8((int64_t)b->len); + return ray_enc_buf_put(b, NULL, want - b->len); +} + +/* ---- sizes ---- */ +int64_t ray_enc_size_raw(int n, int T) { return pad8((int64_t)n * T / 8); } +int64_t ray_enc_size_const(void) { return 8; } +int64_t ray_enc_size_for(int w) { return 8 + (int64_t)ray_enc_packed_bytes(w); } +int64_t ray_enc_size_delta(int T, int w) { + return 8 + 8 * (int64_t)(RAY_ENC_VEC / T) + (int64_t)ray_enc_packed_bytes(w); +} + +int ray_enc_for_width(const uint64_t* v, int n, ray_enc_kind_t k, uint64_t* base) { + ray_enc_stats_t s; + ray_enc_stats(v, n, k, &s); + *base = s.min & tmask(k.T); /* canonical: a T-bit pattern */ + uint64_t range = (s.max - s.min) & tmask(k.T); + return ray_enc_bitlen(range); +} + +/* d[i] = (bits(v[i]) - bits(v[i-L])) mod 2^T for i >= L over the vector + * padded to 1024 with its last value; dbase = unsigned min of d[L..1023]; + * width = bit length of the unsigned max of (d - dbase) mod 2^T. */ +static void delta_fill(const uint64_t* v, int n, int T, uint64_t* d) { + const int L = RAY_ENC_VEC / T; + const uint64_t m = tmask(T); + uint64_t last = n ? v[n - 1] & m : 0; + for (int i = L; i < RAY_ENC_VEC; i++) { + uint64_t a = i < n ? v[i] & m : last, b = (i - L) < n ? v[i - L] & m : last; + d[i] = (a - b) & m; + } +} + +int ray_enc_delta_width(const uint64_t* v, int n, ray_enc_kind_t k, uint64_t* dbase) { + const int T = k.T, L = RAY_ENC_VEC / T; + const uint64_t m = tmask(T); + uint64_t d[RAY_ENC_VEC]; + delta_fill(v, n, T, d); + uint64_t mn = d[L], mx = 0; + for (int i = L; i < RAY_ENC_VEC; i++) if (d[i] < mn) mn = d[i]; + for (int i = L; i < RAY_ENC_VEC; i++) { uint64_t r = (d[i] - mn) & m; if (r > mx) mx = r; } + *dbase = mn; + return ray_enc_bitlen(mx); +} + +/* ---- slots ---- */ +static const ray_enc_kind_t K_U16 = { 16, false, false }; +static const ray_enc_kind_t K_U32 = { 32, false, false }; +static const ray_enc_kind_t K_I64 = { 64, true, false }; +static const ray_enc_kind_t K_U8 = { 8, false, false }; + +/* Kind of a child slot's values given the parent's kind. */ +static ray_enc_kind_t slot_child_kind(ray_enc_slot_t child, ray_enc_kind_t parent) { + switch (child) { + case RAY_ENC_SLOT_RLE_ENDS: return K_U16; + case RAY_ENC_SLOT_CODES: return K_U32; + case RAY_ENC_SLOT_ALP_INTS: return K_I64; /* signed: spec erratum E-P5-1 */ + case RAY_ENC_SLOT_ALP_RD_LEFT: return K_U8; + case RAY_ENC_SLOT_FSST_LENGTHS: return K_U32; + default: return parent; /* RLE values: enclosing kind */ + } +} + +/* Is `enc` legal for (slot, depth)? DICT also needs a dictionary. */ +static bool enc_legal(uint8_t enc, ray_enc_slot_t slot, int depth, ray_enc_kind_t k, + const ray_enc_dict_t* dict) { + if (depth >= RAY_ENC_DEPTH_MAX && enc != RAY_ENC_RAW && enc != RAY_ENC_FOR_BP) return false; + switch (slot) { + case RAY_ENC_SLOT_TOP: + if (k.is_float) /* ALP / ALP_RD live in enc_alp.c */ + return enc == RAY_ENC_RAW || enc == RAY_ENC_CONST || enc == RAY_ENC_RLE || + (enc == RAY_ENC_DICT && dict && dict->n > 0); + if (enc == RAY_ENC_DELTA_BP) return k.is_signed; /* integer and temporal only */ + if (enc == RAY_ENC_DICT) return k.is_signed && dict && dict->n > 0; + return enc == RAY_ENC_RAW || enc == RAY_ENC_CONST || enc == RAY_ENC_FOR_BP || enc == RAY_ENC_RLE; + case RAY_ENC_SLOT_RLE_VALUES: + return enc == RAY_ENC_RAW || (enc == RAY_ENC_FOR_BP && !k.is_float); + case RAY_ENC_SLOT_RLE_ENDS: + return enc == RAY_ENC_RAW || enc == RAY_ENC_FOR_BP || enc == RAY_ENC_DELTA_BP; + case RAY_ENC_SLOT_CODES: + return enc == RAY_ENC_RAW || enc == RAY_ENC_FOR_BP || enc == RAY_ENC_RLE; + case RAY_ENC_SLOT_ALP_INTS: + return enc == RAY_ENC_RAW || enc == RAY_ENC_FOR_BP || enc == RAY_ENC_DELTA_BP || enc == RAY_ENC_RLE; + case RAY_ENC_SLOT_ALP_RD_LEFT: + return enc == RAY_ENC_RAW || enc == RAY_ENC_FOR_BP || enc == RAY_ENC_RLE; + case RAY_ENC_SLOT_FSST_LENGTHS: + return enc == RAY_ENC_RAW || enc == RAY_ENC_FOR_BP; + } + return false; +} + +/* ---- RLE and DICT helpers ---- */ +static int rle_split(const uint64_t* v, int n, uint64_t* vals, uint64_t* ends) { + int r = 0; + for (int i = 0; i < n; i++) { + if (i == 0 || v[i] != v[i - 1]) vals[r++] = v[i]; + ends[r - 1] = (uint64_t)(i + 1); + } + return r; +} + +static bool dict_codes(const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* d, uint64_t* codes) { + for (int i = 0; i < n; i++) { + uint32_t lo = 0, hi = d->n; + while (lo < hi) { + uint32_t mid = (lo + hi) / 2; + if (ray_enc_lt(d->v[mid], v[i], k)) lo = mid + 1; else hi = mid; + } + if (lo >= d->n || d->v[lo] != v[i]) return false; /* not in dictionary */ + codes[i] = lo; + } + return true; +} + +static int64_t hdr(int depth) { return depth > 0 ? 8 : 0; } + +/* Size of encoding `enc` for v, or -1 if not applicable. */ +static int64_t enc_size(uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k, + ray_enc_slot_t slot, int depth, const ray_enc_dict_t* dict, + uint8_t* width) { + uint64_t base; + *width = 0; + switch (enc) { + case RAY_ENC_RAW: return ray_enc_size_raw(n, k.T); + case RAY_ENC_CONST: { + ray_enc_stats_t s; ray_enc_stats(v, n, k, &s); + return s.all_equal ? ray_enc_size_const() : -1; + } + case RAY_ENC_FOR_BP: { int w = ray_enc_for_width(v, n, k, &base); *width = (uint8_t)w; return ray_enc_size_for(w); } + case RAY_ENC_DELTA_BP: { int w = ray_enc_delta_width(v, n, k, &base); *width = (uint8_t)w; return ray_enc_size_delta(k.T, w); } + case RAY_ENC_RLE: { + if (depth + 1 > RAY_ENC_DEPTH_MAX) return -1; + uint64_t vals[RAY_ENC_VEC], ends[RAY_ENC_VEC]; /* locals: children recurse */ + int r = rle_split(v, n, vals, ends); + ray_enc_kind_t vk = slot_child_kind(RAY_ENC_SLOT_RLE_VALUES, k); + ray_enc_choice_t cv = ray_enc_choose(vals, r, vk, RAY_ENC_SLOT_RLE_VALUES, depth + 1, NULL); + ray_enc_choice_t ce = ray_enc_choose(ends, r, K_U16, RAY_ENC_SLOT_RLE_ENDS, depth + 1, NULL); + return 8 + cv.bytes + ce.bytes; + } + case RAY_ENC_DICT: { + if (!dict) return -1; /* never dereference a missing dictionary */ + uint64_t codes[RAY_ENC_VEC]; + if (!dict_codes(v, n, k, dict, codes)) return -1; + ray_enc_choice_t cc = ray_enc_choose(codes, n, K_U32, RAY_ENC_SLOT_CODES, depth + 1, NULL); + return cc.bytes; + } + } + return -1; +} + +ray_enc_choice_t ray_enc_choose(const uint64_t* v, int n, ray_enc_kind_t k, + ray_enc_slot_t slot, int depth, + const ray_enc_dict_t* dict) { + static const uint8_t order[] = { RAY_ENC_RAW, RAY_ENC_CONST, RAY_ENC_FOR_BP, + RAY_ENC_DELTA_BP, RAY_ENC_RLE, RAY_ENC_DICT }; + uint8_t w; + int64_t raw = ray_enc_size_raw(n, k.T); + ray_enc_choice_t best = { RAY_ENC_RAW, 0, raw }; + for (size_t i = 1; i < sizeof order; i++) { + uint8_t e = order[i]; + if (!enc_legal(e, slot, depth, k, dict)) continue; + int64_t sz = enc_size(e, v, n, k, slot, depth, dict, &w); + if (sz >= 0 && sz < best.bytes) { best.enc = e; best.width = w; best.bytes = sz; } + } + if (best.enc != RAY_ENC_RAW && best.bytes * 8 > raw * 7) { /* need >= 1/8 gain */ + best.enc = RAY_ENC_RAW; best.width = 0; best.bytes = raw; + } + best.bytes += hdr(depth); + return best; +} + +/* ---- writers ---- */ +static bool put_u64(ray_enc_buf_t* b, uint64_t x) { return ray_enc_buf_put(b, &x, 8); } + +static bool write_raw(const uint64_t* v, int n, int T, ray_enc_buf_t* b) { + for (int i = 0; i < n; i++) if (!ray_enc_buf_put(b, &v[i], (size_t)T / 8)) return false; + return ray_enc_buf_pad8(b); +} + +static bool write_packed(const uint64_t* u, int T, int w, ray_enc_buf_t* b) { + size_t at = b->len; + if (!ray_enc_buf_put(b, NULL, ray_enc_packed_bytes(w))) return false; + ray_enc_pack(u, T, w, b->p + at); + return true; +} + +static bool write_body(uint8_t enc, uint8_t w, const uint64_t* v, int n, ray_enc_kind_t k, + ray_enc_slot_t slot, int depth, const ray_enc_dict_t* dict, + ray_enc_buf_t* b) { + const uint64_t m = tmask(k.T); + switch (enc) { + case RAY_ENC_RAW: return write_raw(v, n, k.T, b); + case RAY_ENC_CONST: return write_raw(v, 1, k.T, b); + case RAY_ENC_FOR_BP: { + uint64_t base; (void)ray_enc_for_width(v, n, k, &base); + base &= m; + uint64_t u[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) u[i] = i < n ? (((v[i] & m) - base) & m) : 0; /* pad: base */ + return put_u64(b, base) && write_packed(u, k.T, w, b); + } + case RAY_ENC_DELTA_BP: { + const int L = RAY_ENC_VEC / k.T; + uint64_t dbase; (void)ray_enc_delta_width(v, n, k, &dbase); + uint64_t d[RAY_ENC_VEC], r[RAY_ENC_VEC]; + delta_fill(v, n, k.T, d); + uint64_t last = n ? v[n - 1] & m : 0; + dbase &= m; + if (!put_u64(b, dbase)) return false; + for (int l = 0; l < L; l++) if (!put_u64(b, (l < n ? v[l] & m : last))) return false; + for (int i = 0; i < RAY_ENC_VEC; i++) r[i] = i < L ? 0 : ((d[i] - dbase) & m); + return write_packed(r, k.T, w, b); + } + case RAY_ENC_RLE: { + uint64_t vals[RAY_ENC_VEC], ends[RAY_ENC_VEC]; + int nr = rle_split(v, n, vals, ends); + uint32_t hdrw[2] = { (uint32_t)nr, 0 }; + ray_enc_choice_t c; + ray_enc_kind_t vk = slot_child_kind(RAY_ENC_SLOT_RLE_VALUES, k); + return ray_enc_buf_put(b, hdrw, 8) + && ray_enc_write(vals, nr, vk, RAY_ENC_SLOT_RLE_VALUES, depth + 1, NULL, b, &c) + && ray_enc_write(ends, nr, K_U16, RAY_ENC_SLOT_RLE_ENDS, depth + 1, NULL, b, &c); + } + case RAY_ENC_DICT: { + if (!dict) return false; /* never dereference a missing dictionary */ + uint64_t codes[RAY_ENC_VEC]; + if (!dict_codes(v, n, k, dict, codes)) return false; + ray_enc_choice_t c; + return ray_enc_write(codes, n, K_U32, RAY_ENC_SLOT_CODES, depth + 1, NULL, b, &c); + } + } + return false; +} + +bool ray_enc_write(const uint64_t* v, int n, ray_enc_kind_t k, + ray_enc_slot_t slot, int depth, const ray_enc_dict_t* dict, + ray_enc_buf_t* out, ray_enc_choice_t* chosen) { + if (n < 0 || n > RAY_ENC_VEC) return false; + ray_enc_choice_t c = ray_enc_choose(v, n, k, slot, depth, dict); + size_t at = out->len; + if (depth > 0) { + uint8_t h[8] = { c.enc, c.width, 0, 0, 0, 0, 0, 0 }; + if (!ray_enc_buf_put(out, h, 8)) { out->len = at; return false; } + } + size_t body_at = out->len; + if (!write_body(c.enc, c.width, v, n, k, slot, depth, dict, out)) { out->len = at; return false; } + if (depth > 0) { + uint32_t bb = (uint32_t)(out->len - body_at); + memcpy(out->p + at + 4, &bb, 4); + } + if ((int64_t)(out->len - at) != c.bytes) { out->len = at; return false; } /* size model and writer agree */ + if (chosen) *chosen = c; + return true; +} + +bool ray_enc_write_as(uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* dict, ray_enc_buf_t* out, ray_enc_choice_t* chosen) { + if (n < 0 || n > RAY_ENC_VEC) return false; + if (enc > RAY_ENC_DICT || !enc_legal(enc, RAY_ENC_SLOT_TOP, 0, k, dict)) return false; + uint8_t w; + int64_t sz = enc_size(enc, v, n, k, RAY_ENC_SLOT_TOP, 0, dict, &w); + if (sz < 0) return false; + size_t at = out->len; + if (!write_body(enc, w, v, n, k, RAY_ENC_SLOT_TOP, 0, dict, out)) { out->len = at; return false; } + if ((int64_t)(out->len - at) != sz) { out->len = at; return false; } /* size model and writer agree */ + if (chosen) { chosen->enc = enc; chosen->width = w; chosen->bytes = sz; } + return true; +} + +int64_t ray_enc_body_size(uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* dict) { + if (n < 0 || n > RAY_ENC_VEC || enc > RAY_ENC_DICT || !enc_legal(enc, RAY_ENC_SLOT_TOP, 0, k, dict)) return -1; + uint8_t w; + return enc_size(enc, v, n, k, RAY_ENC_SLOT_TOP, 0, dict, &w); +} + +/* ---- readers ---- + * The bodies are ours (written by ray_enc_write): they are read as + * written, every count and offset taken from the body. */ +static void get_raw(const uint8_t* p, int n, int T, uint64_t* out) { + for (int i = 0; i < n; i++) { + uint64_t x = 0; memcpy(&x, p + (size_t)i * (size_t)T / 8, (size_t)T / 8); out[i] = x; + } +} + +static int64_t read_body(const uint8_t* p, size_t avail, uint8_t enc, uint8_t w, int n, + ray_enc_kind_t k, ray_enc_slot_t slot, int depth, + const ray_enc_dict_t* dict, uint64_t* out) { + const uint64_t m = tmask(k.T); + (void)slot; + switch (enc) { + case RAY_ENC_RAW: + get_raw(p, n, k.T, out); + return ray_enc_size_raw(n, k.T); + case RAY_ENC_CONST: { + uint64_t x; + get_raw(p, 1, k.T, &x); + for (int i = 0; i < n; i++) out[i] = x; + return ray_enc_size_raw(1, k.T); + } + case RAY_ENC_FOR_BP: { + uint64_t base; memcpy(&base, p, 8); + uint64_t u[RAY_ENC_VEC]; + ray_enc_unpack(p + 8, k.T, w, u); + for (int i = 0; i < n; i++) out[i] = (base + u[i]) & m; + return ray_enc_size_for(w); + } + case RAY_ENC_DELTA_BP: { + const int L = RAY_ENC_VEC / k.T; + uint64_t dbase; memcpy(&dbase, p, 8); + uint64_t full[RAY_ENC_VEC], r[RAY_ENC_VEC]; + for (int l = 0; l < L; l++) memcpy(&full[l], p + 8 + 8 * (size_t)l, 8); + ray_enc_unpack(p + 8 + 8 * (size_t)L, k.T, w, r); + for (int i = L; i < RAY_ENC_VEC; i++) full[i] = (full[i - L] + dbase + r[i]) & m; + memcpy(out, full, sizeof(uint64_t) * (size_t)n); + return ray_enc_size_delta(k.T, w); + } + case RAY_ENC_RLE: { + uint32_t nr; memcpy(&nr, p, 4); + uint64_t vals[RAY_ENC_VEC], ends[RAY_ENC_VEC]; + ray_enc_kind_t vk = slot_child_kind(RAY_ENC_SLOT_RLE_VALUES, k); + int64_t a = ray_enc_read(p + 8, avail - 8, 0, 0, (int)nr, vk, RAY_ENC_SLOT_RLE_VALUES, depth + 1, + NULL, vals); + int64_t e = ray_enc_read(p + 8 + a, avail - 8 - (size_t)a, 0, 0, (int)nr, K_U16, RAY_ENC_SLOT_RLE_ENDS, depth + 1, NULL, ends); + uint64_t prev = 0; + for (uint32_t i = 0; i < nr; i++) { + for (uint64_t j = prev; j < ends[i]; j++) out[j] = vals[i]; + prev = ends[i]; + } + return 8 + a + e; + } + case RAY_ENC_DICT: { + uint64_t codes[RAY_ENC_VEC]; + int64_t c = ray_enc_read(p, avail, 0, 0, n, K_U32, RAY_ENC_SLOT_CODES, depth + 1, NULL, codes); + for (int i = 0; i < n; i++) out[i] = dict->v[codes[i]]; + return c; + } + } + return 0; +} + +int64_t ray_enc_read(const uint8_t* p, size_t avail, uint8_t enc, uint8_t width, + int n, ray_enc_kind_t k, ray_enc_slot_t slot, int depth, + const ray_enc_dict_t* dict, uint64_t* out) { + if (depth == 0) return read_body(p, avail, enc, width, n, k, slot, depth, dict, out); + uint32_t bb; memcpy(&bb, p + 4, 4); + (void)read_body(p + 8, bb, p[0], p[1], n, k, slot, depth, dict, out); + return 8 + (int64_t)bb; +} + + +/* ---- VALUE_DICT training: distinct sorted values, at most 1<<16 ---- */ +/* Bottom-up merge sort in the logical order of `k`; reentrant (no shared state). */ +static void sort_kind(uint64_t* a, uint64_t* tmp, int64_t n, ray_enc_kind_t k) { + for (int64_t w = 1; w < n; w *= 2) { + for (int64_t lo = 0; lo < n; lo += 2 * w) { + int64_t mid = lo + w < n ? lo + w : n, hi = lo + 2 * w < n ? lo + 2 * w : n; + int64_t i = lo, j = mid, o = lo; + while (i < mid && j < hi) tmp[o++] = ray_enc_lt(a[j], a[i], k) ? a[j++] : a[i++]; + while (i < mid) tmp[o++] = a[i++]; + while (j < hi) tmp[o++] = a[j++]; + } + memcpy(a, tmp, sizeof(uint64_t) * (size_t)n); + } +} + +/* Returns 1 trained (*out owned by the caller, ray_free_raw), 0 no + * dictionary (n <= 0 or more than 1<<16 distinct values), -1 out of memory. */ +int ray_enc_train_dict(const uint64_t* v, int64_t n, ray_enc_kind_t k, + uint64_t** out, uint32_t* out_n) { + if (n <= 0) return 0; + uint64_t* tmp = ray_alloc_raw(sizeof(uint64_t) * 2 * (size_t)n); + if (!tmp) return -1; + memcpy(tmp, v, sizeof(uint64_t) * (size_t)n); + sort_kind(tmp, tmp + n, n, k); + int64_t d = 0; + for (int64_t i = 0; i < n; i++) if (i == 0 || tmp[i] != tmp[d - 1]) tmp[d++] = tmp[i]; + if (d > (1 << 16)) { ray_free_raw(tmp); return 0; } + /* ray_realloc_raw never shrinks: copy into a block sized to the distinct count. */ + uint64_t* fit = ray_alloc_raw(sizeof(uint64_t) * (size_t)d); + if (!fit) { ray_free_raw(tmp); return -1; } + memcpy(fit, tmp, sizeof(uint64_t) * (size_t)d); + ray_free_raw(tmp); + *out = fit; *out_n = (uint32_t)d; + return 1; +} diff --git a/src/store/enc_once.c b/src/store/enc_once.c new file mode 100644 index 000000000..4d93d24b9 --- /dev/null +++ b/src/store/enc_once.c @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) +# define _POSIX_C_SOURCE 200809L +#endif +#include "store/enc_once.h" +#include "core/platform.h" +#include "core/runtime.h" +#include +#include +#include +#ifdef RAY_OS_WINDOWS +# include +#else +# include +#endif + +void ray_enc_yield(void) { +#if defined(RAY_OS_WINDOWS) + SwitchToThread(); +#elif defined(RAY_OS_WASM) + /* single-threaded: nothing to wait for */ +#else + for (int i = 0; i < 64; i++) RAY_CPU_RELAX(); + sched_yield(); +#endif +} + +static void once_lock(ray_enc_once_t* o) { + for (;;) { + if (!atomic_load_explicit(&o->lock, memory_order_relaxed) && + !atomic_exchange_explicit(&o->lock, 1, memory_order_acquire)) return; + RAY_CPU_RELAX(); + } +} +/* A DRAINING state returns to IDLE once its last waiter has copied the + * snapshot (under the lock, after waiters was decremented). */ +static void once_drain_reset(ray_enc_once_t* o) { + if (o->waiters == 0 && + atomic_load_explicit(&o->state, memory_order_relaxed) == RAY_ENC_ONCE_DRAINING) + atomic_store_explicit(&o->state, RAY_ENC_ONCE_IDLE, memory_order_release); +} +static void once_unlock(ray_enc_once_t* o) { + atomic_store_explicit(&o->lock, 0, memory_order_release); +} + +void ray_enc_once_init(ray_enc_once_t* o) { + memset(o, 0, sizeof *o); + atomic_store(&o->lock, 0); + atomic_store(&o->state, RAY_ENC_ONCE_IDLE); +} + +uint32_t ray_enc_once_waiters(ray_enc_once_t* o) { + once_lock(o); + uint32_t w = o->waiters; + once_unlock(o); + return w; +} + +bool ray_enc_code_transient(const char* code) { + return code && (strcmp(code, "oom") == 0 || strcmp(code, "cancel") == 0 || + strcmp(code, "fpenv") == 0); +} + +void ray_enc_snap_set(ray_enc_snap_t* s, const char* code, const char* fmt, ...) { + memset(s, 0, sizeof *s); + snprintf(s->code, sizeof s->code, "%s", code ? code : "error"); + if (fmt) { + va_list ap; va_start(ap, fmt); + vsnprintf(s->msg, sizeof s->msg, fmt, ap); + va_end(ap); + } + s->is_transient = ray_enc_code_transient(s->code); +} + +/* Must run on the thread that created `err`: the message is that thread's + * thread-local ray_last_err_msg (src/core/runtime.c). */ +void ray_enc_snap_take(ray_enc_snap_t* s, ray_t* err) { + memset(s, 0, sizeof *s); + const char* code = (err && RAY_IS_ERR(err)) ? ray_err_code(err) : "error"; + snprintf(s->code, sizeof s->code, "%s", code ? code : "error"); + const char* m = ray_error_msg(); + if (m) snprintf(s->msg, sizeof s->msg, "%s", m); + s->is_transient = ray_enc_code_transient(s->code); + ray_error_free(err); /* a no-op on the static OOM sentinel */ +} + +ray_t* ray_enc_snap_error(const ray_enc_snap_t* s) { + return s->msg[0] ? ray_error(s->code, "%s", s->msg) : ray_error(s->code, NULL); +} + +void ray_enc_once_test_drain(ray_enc_once_t* o, const ray_enc_snap_t* snap, uint32_t waiters) { + once_lock(o); + o->snap = *snap; o->waiters = waiters; o->attempt++; + atomic_store_explicit(&o->state, RAY_ENC_ONCE_DRAINING, memory_order_release); + once_unlock(o); +} + +void ray_enc_once_test_waiter_done(ray_enc_once_t* o, ray_enc_snap_t* out) { + once_lock(o); + *out = o->snap; + o->waiters--; + once_drain_reset(o); + once_unlock(o); +} + +ray_t* ray_enc_once_get(ray_enc_once_t* o, ray_t** slot, ray_enc_once_fn fn, void* ctx) { + once_lock(o); + for (;;) { + uint32_t st = atomic_load_explicit(&o->state, memory_order_relaxed); + if (st == RAY_ENC_ONCE_DONE) { ray_t* v = *slot; once_unlock(o); return v; } + if (st == RAY_ENC_ONCE_FAILED) { + ray_enc_snap_t s = o->snap; once_unlock(o); + return ray_enc_snap_error(&s); + } + if (st == RAY_ENC_ONCE_RUNNING) { + uint64_t mine = o->attempt; + o->waiters++; + once_unlock(o); + while (atomic_load_explicit(&o->state, memory_order_acquire) == RAY_ENC_ONCE_RUNNING) + ray_enc_yield(); + once_lock(o); + o->waiters--; + st = atomic_load_explicit(&o->state, memory_order_relaxed); + if (st == RAY_ENC_ONCE_DRAINING && o->attempt == mine) { + ray_enc_snap_t s = o->snap; + once_drain_reset(o); + once_unlock(o); + return ray_enc_snap_error(&s); + } + continue; /* DONE or FAILED: answered above */ + } + if (st == RAY_ENC_ONCE_DRAINING) { + /* A failed attempt still has waiters to read its snapshot: do not + * start a new attempt that would overwrite it. */ + once_unlock(o); + ray_enc_yield(); + once_lock(o); + continue; + } + /* IDLE: this caller runs the attempt. */ + o->attempt++; + atomic_store_explicit(&o->state, RAY_ENC_ONCE_RUNNING, memory_order_relaxed); + once_unlock(o); + break; + } + ray_enc_snap_t fail; + memset(&fail, 0, sizeof fail); + ray_t* v = fn(ctx, &fail); + if (v && RAY_IS_ERR(v)) { /* fn returned an error object */ + ray_enc_snap_take(&fail, v); /* on this thread, before the lock */ + v = NULL; + } + if (!v && !fail.code[0]) ray_enc_snap_set(&fail, "error", NULL); + if (!v) fail.is_transient = ray_enc_code_transient(fail.code); + once_lock(o); + if (v) { + *slot = v; + atomic_store_explicit(&o->state, RAY_ENC_ONCE_DONE, memory_order_release); + once_unlock(o); + /* fn returns a heap object, not the address of its output-only + * stack snapshot (enc_once.h). cppcheck propagates &fail through + * an opaque callback as a possible return value. */ + // cppcheck-suppress returnDanglingLifetime + return v; + } + o->snap = fail; + uint32_t next = !fail.is_transient ? RAY_ENC_ONCE_FAILED + : (o->waiters ? RAY_ENC_ONCE_DRAINING : RAY_ENC_ONCE_IDLE); + atomic_store_explicit(&o->state, next, memory_order_release); + once_unlock(o); + return ray_enc_snap_error(&fail); +} diff --git a/src/store/enc_once.h b/src/store/enc_once.h new file mode 100644 index 000000000..2bed4d01c --- /dev/null +++ b/src/store/enc_once.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RAY_ENC_ONCE_H +#define RAY_ENC_ONCE_H + +#include +#include +#include +#include + +/* Attempt result / error envelope (spec "Error envelopes"): fixed size, so + * recording it needs no allocation and cannot fail on OOM. */ +typedef struct { + char code[8]; + char msg[256]; + bool is_transient; +} ray_enc_snap_t; + +enum { RAY_ENC_ONCE_IDLE = 0, RAY_ENC_ONCE_RUNNING, RAY_ENC_ONCE_DONE, + RAY_ENC_ONCE_FAILED, RAY_ENC_ONCE_DRAINING }; + +/* One once-state with its attempt record inline (spec "Attempt records"): + * a transient failure resets to IDLE only when the attempt's last waiter + * has copied the snapshot; arrivals in between wait (DRAINING). */ +typedef struct { + _Atomic(uint32_t) lock; + _Atomic(uint32_t) state; + uint32_t waiters; + uint64_t attempt; + ray_enc_snap_t snap; +} ray_enc_once_t; + +/* The result is an independently allocated object, never `fail` or any + * storage within it. `fail` is an output-only, copied error snapshot. */ +typedef ray_t* (*ray_enc_once_fn)(void* ctx, ray_enc_snap_t* fail); + +void ray_enc_once_init(ray_enc_once_t* o); +ray_t* ray_enc_once_get(ray_enc_once_t* o, ray_t** slot, ray_enc_once_fn fn, void* ctx); +uint32_t ray_enc_once_waiters(ray_enc_once_t* o); +bool ray_enc_code_transient(const char* code); +void ray_enc_snap_take(ray_enc_snap_t* s, ray_t* err); +void ray_enc_snap_set(ray_enc_snap_t* s, const char* code, const char* fmt, ...); +ray_t* ray_enc_snap_error(const ray_enc_snap_t* s); +void ray_enc_yield(void); + +/* Test hooks: force DRAINING with `waiters` outstanding, and run one waiter's + * snapshot-copy-and-release step. */ +void ray_enc_once_test_drain(ray_enc_once_t* o, const ray_enc_snap_t* snap, uint32_t waiters); +void ray_enc_once_test_waiter_done(ray_enc_once_t* o, ray_enc_snap_t* out); + +#endif /* RAY_ENC_ONCE_H */ diff --git a/src/store/enc_pack.c b/src/store/enc_pack.c new file mode 100644 index 000000000..1c5383746 --- /dev/null +++ b/src/store/enc_pack.c @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "store/enc.h" +#include + +size_t ray_enc_packed_bytes(int w) { return (size_t)RAY_ENC_VEC * (size_t)w / 8; } + +int ray_enc_bitlen(uint64_t x) { return x ? 64 - __builtin_clzll(x) : 0; } + +static inline uint64_t word_get(const uint8_t* p, int T, size_t idx) { + switch (T) { + case 8: return p[idx]; + case 16: { uint16_t v; memcpy(&v, p + idx * 2, 2); return v; } + case 32: { uint32_t v; memcpy(&v, p + idx * 4, 4); return v; } + default: { uint64_t v; memcpy(&v, p + idx * 8, 8); return v; } + } +} + +static inline void word_put(uint8_t* p, int T, size_t idx, uint64_t v) { + switch (T) { + case 8: p[idx] = (uint8_t)v; break; + case 16: { uint16_t x = (uint16_t)v; memcpy(p + idx * 2, &x, 2); break; } + case 32: { uint32_t x = (uint32_t)v; memcpy(p + idx * 4, &x, 4); break; } + default: memcpy(p + idx * 8, &v, 8); break; + } +} + +static inline uint64_t tmask(int T) { return T == 64 ? ~0ull : ((1ull << T) - 1); } + +void ray_enc_pack(const uint64_t* u, int T, int w, uint8_t* out) { + if (w == 0) return; + const int L = RAY_ENC_VEC / T; + memset(out, 0, ray_enc_packed_bytes(w)); + const uint64_t vmask = w == 64 ? ~0ull : ((1ull << w) - 1); + const uint64_t wm = tmask(T); + for (int l = 0; l < L; l++) { + int bit = 0; /* offset in lane's stream */ + for (int r = 0; r < T; r++, bit += w) { + uint64_t x = u[l + r * L] & vmask; + int k = bit / T, off = bit % T; + size_t i0 = (size_t)k * (size_t)L + (size_t)l; + word_put(out, T, i0, (word_get(out, T, i0) | (x << off)) & wm); + if (off + w > T) { + size_t i1 = (size_t)(k + 1) * (size_t)L + (size_t)l; + word_put(out, T, i1, (word_get(out, T, i1) | (x >> (T - off))) & wm); + } + } + } +} + +/* Row-major over the lanes: row r of every lane shares its word index and + * shift, so the inner loop is a contiguous, vectorisable pass over the L + * lanes (the lane-major loop above it is the writer's, not hot). */ +#define UNPACK_T(UT, TB) do { \ + enum { L = RAY_ENC_VEC / TB }; \ + const UT* a = (const UT*)(const void*)in; \ + for (int r = 0, bit = 0; r < TB; r++, bit += w) { \ + const int k = bit / TB, off = bit % TB; \ + const UT* lo = a + (size_t)k * L; \ + uint64_t* o = u + (size_t)r * L; \ + if (off + w > TB) { \ + const UT* hi = lo + L; \ + for (int l = 0; l < L; l++) { \ + UT x0, x1; memcpy(&x0, lo + l, sizeof x0); memcpy(&x1, hi + l, sizeof x1); \ + o[l] = (((uint64_t)x0 >> off) | ((uint64_t)x1 << (TB - off))) & vmask; \ + } \ + } else { \ + for (int l = 0; l < L; l++) { \ + UT x0; memcpy(&x0, lo + l, sizeof x0); \ + o[l] = ((uint64_t)x0 >> off) & vmask; \ + } \ + } \ + } } while (0) + +void ray_enc_unpack(const uint8_t* in, int T, int w, uint64_t* u) { + if (w == 0) { memset(u, 0, sizeof(uint64_t) * RAY_ENC_VEC); return; } + const uint64_t vmask = w == 64 ? ~0ull : ((1ull << w) - 1); + switch (T) { + case 8: UNPACK_T(uint8_t, 8); break; + case 16: UNPACK_T(uint16_t, 16); break; + case 32: UNPACK_T(uint32_t, 32); break; + default: UNPACK_T(uint64_t, 64); break; + } +} +#undef UNPACK_T diff --git a/src/store/enc_str.c b/src/store/enc_str.c new file mode 100644 index 000000000..786a66792 --- /dev/null +++ b/src/store/enc_str.c @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* STR codec bodies (spec "Codec bodies", STR_DICT and FSST). Pure + * functions over one vector; the STR_DICT entries and the FSST table are + * side data the caller passes in. */ + +#include "store/enc.h" +#include "store/fsst.h" +#include +#include + +static const ray_enc_kind_t K_U32 = { 32, false, false }; +static inline uint64_t p8(uint64_t x) { return (x + 7) & ~(uint64_t)7; } + +/* ---- STR_DICT: child `codes` ---- */ +int64_t ray_enc_strdict_size(const uint64_t* codes, int n) { + return ray_enc_choose(codes, n, K_U32, RAY_ENC_SLOT_CODES, 1, NULL).bytes; +} + +bool ray_enc_strdict_write(const uint64_t* codes, int n, ray_enc_buf_t* out) { + ray_enc_choice_t c; + return ray_enc_write(codes, n, K_U32, RAY_ENC_SLOT_CODES, 1, NULL, out, &c); +} + +void ray_enc_strdict_read(const uint8_t* p, size_t avail, int n, uint64_t* codes) { + (void)ray_enc_read(p, avail, 0, 0, n, K_U32, RAY_ENC_SLOT_CODES, 1, NULL, codes); +} + +/* ---- FSST: child `lengths`, u64 total_bytes, compressed bytes padded to 8 ---- */ +uint64_t ray_enc_fsst_encode(const ray_fsst_table_t* t, const ray_fsst_index_t* ix, + const char* const* s, const uint32_t* len, int n, + uint8_t* buf, uint64_t* clen) { + uint64_t total = 0; + for (int i = 0; i < n; i++) { + int64_t k = ray_fsst_encode_ix(t, ix, (const uint8_t*)s[i], len[i], buf + total); + clen[i] = (uint64_t)k; + total += (uint64_t)k; + } + return total; +} + +int64_t ray_enc_fsst_size(const uint64_t* clen, int n, uint64_t total) { + return ray_enc_choose(clen, n, K_U32, RAY_ENC_SLOT_FSST_LENGTHS, 1, NULL).bytes + 8 + (int64_t)p8(total); +} + +bool ray_enc_fsst_write(const uint64_t* clen, int n, const uint8_t* bytes, uint64_t total, + ray_enc_buf_t* out) { + if (n < 0 || n > RAY_ENC_VEC || total > SIZE_MAX - 8) return false; + uint64_t sum = 0; /* total is the lengths' sum (each U32, n <= 1024) */ + for (int i = 0; i < n; i++) { + if (clen[i] > UINT32_MAX) return false; + sum += clen[i]; + } + if (sum != total) return false; + size_t at = out->len; + ray_enc_choice_t c; + if (ray_enc_write(clen, n, K_U32, RAY_ENC_SLOT_FSST_LENGTHS, 1, NULL, out, &c) && + ray_enc_buf_put(out, &total, 8) && ray_enc_buf_put(out, bytes, (size_t)total) && + ray_enc_buf_pad8(out)) + return true; + out->len = at; + return false; +} + +void ray_enc_fsst_parse(const uint8_t* p, size_t avail, int n, const ray_fsst_table_t* t, + uint64_t* clen, uint64_t* xlen, const uint8_t** bytes) { + int64_t a = ray_enc_read(p, avail, 0, 0, n, K_U32, RAY_ENC_SLOT_FSST_LENGTHS, 1, NULL, clen); + const uint8_t* b = p + a + 8; /* past the u64 total */ + uint64_t at = 0; + for (int i = 0; i < n; i++) { + xlen[i] = (uint64_t)ray_fsst_expanded_len(t, b + at, (uint32_t)clen[i]); + at += clen[i]; + } + *bytes = b; +} diff --git a/src/store/enc_vec.c b/src/store/enc_vec.c new file mode 100644 index 000000000..0f9cb5150 --- /dev/null +++ b/src/store/enc_vec.c @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "store/enc.h" +#include +#include "table/sym.h" +#include + +static inline uint64_t tmask(int T) { return T == 64 ? ~0ull : ((1ull << T) - 1); } + +bool ray_enc_kind_of(int8_t type, uint8_t attrs, ray_enc_kind_t* k) { + switch (type) { + case RAY_BOOL: case RAY_U8: *k = (ray_enc_kind_t){ 8, false, false }; return true; + case RAY_I16: *k = (ray_enc_kind_t){ 16, true, false }; return true; + case RAY_I32: case RAY_DATE: + case RAY_TIME: *k = (ray_enc_kind_t){ 32, true, false }; return true; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: *k = (ray_enc_kind_t){ 64, true, false }; return true; + case RAY_SYM: + *k = (ray_enc_kind_t){ (uint8_t)(8 * RAY_SYM_ELEM(attrs)), false, false }; + return true; + default: return false; + } +} + +bool ray_enc_value_kind(int8_t type, uint8_t attrs, ray_enc_kind_t* k) { + if (type == RAY_F32) { *k = (ray_enc_kind_t){ 32, false, true }; return true; } + if (type == RAY_F64) { *k = (ray_enc_kind_t){ 64, false, true }; return true; } + return ray_enc_kind_of(type, attrs, k); +} + +bool ray_enc_has_bitmap(int8_t type) { + switch (type) { + case RAY_I16: case RAY_I32: case RAY_I64: case RAY_DATE: case RAY_TIME: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F32: case RAY_F64: return true; + default: return false; + } +} + +int64_t ray_enc_logical(uint64_t bits, ray_enc_kind_t k) { + if (k.T == 64) return (int64_t)bits; + uint64_t m = tmask(k.T); + bits &= m; + if (k.is_signed && (bits >> (k.T - 1)) & 1) return (int64_t)(bits | ~m); + return (int64_t)bits; +} + +bool ray_enc_lt(uint64_t a, uint64_t b, ray_enc_kind_t k) { + if (k.is_float) { /* dictionary order (spec "Comparison semantics") */ + double x = ray_enc_fval(a, k.T), y = ray_enc_fval(b, k.T); + if (x < y) return true; + if (x > y) return false; + return ((a >> (k.T - 1)) & 1) && !((b >> (k.T - 1)) & 1); /* -0.0 before +0.0 */ + } + if (k.is_signed) return ray_enc_logical(a, k) < ray_enc_logical(b, k); + uint64_t m = tmask(k.T); + return (a & m) < (b & m); +} + +bool ray_enc_load(const void* data, int8_t type, uint8_t attrs, + int64_t start, int n, ray_enc_input_t* in) { + if (n < 0 || n > RAY_ENC_VEC) return false; + if (!ray_enc_kind_of(type, attrs, &in->k)) return false; + in->n = n; + in->n_nulls = 0; + in->bitmap = ray_enc_has_bitmap(type); + memset(in->nullmap, 0, sizeof in->nullmap); + const uint64_t m = tmask(in->k.T); + for (int i = 0; i < n; i++) { + int64_t r = start + i; + uint64_t b; bool null = false; + switch (type) { + case RAY_BOOL: case RAY_U8: b = ((const uint8_t*)data)[r]; break; + case RAY_I16: { int16_t v = ((const int16_t*)data)[r]; null = v == NULL_I16; b = (uint64_t)(uint16_t)v; break; } + case RAY_I32: case RAY_DATE: case RAY_TIME: + { int32_t v = ((const int32_t*)data)[r]; null = v == NULL_I32; b = (uint64_t)(uint32_t)v; break; } + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: + { int64_t v = ((const int64_t*)data)[r]; null = v == NULL_I64; b = (uint64_t)v; break; } + case RAY_SYM: { int64_t v = ray_read_sym(data, r, type, attrs); null = v == 0; b = (uint64_t)v; break; } + default: return false; + } + in->bits[i] = b & m; + if (null) { + in->n_nulls++; + if (in->bitmap) in->nullmap[i >> 3] |= (uint8_t)(1u << (i & 7)); + } + } + if (in->bitmap && in->n_nulls > 0) { + bool have = false; uint64_t mn = 0; + for (int i = 0; i < n; i++) { + if ((in->nullmap[i >> 3] >> (i & 7)) & 1) continue; + if (!have || ray_enc_lt(in->bits[i], mn, in->k)) { mn = in->bits[i]; have = true; } + } + if (!have) mn = 0; /* all null: fill zero */ + for (int i = 0; i < n; i++) + if ((in->nullmap[i >> 3] >> (i & 7)) & 1) in->bits[i] = mn; + } + return true; +} + +void ray_enc_stats(const uint64_t* v, int n, ray_enc_kind_t k, ray_enc_stats_t* s) { + s->min = s->max = n ? v[0] : 0; + s->runs = n ? 1 : 0; + for (int i = 1; i < n; i++) { + if (ray_enc_lt(v[i], s->min, k)) s->min = v[i]; + if (ray_enc_lt(s->max, v[i], k)) s->max = v[i]; + if (v[i] != v[i - 1]) s->runs++; + } + s->all_equal = s->runs <= 1; +} diff --git a/src/store/enccol.c b/src/store/enccol.c new file mode 100644 index 000000000..9f0a622d9 --- /dev/null +++ b/src/store/enccol.c @@ -0,0 +1,2669 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "store/enccol.h" +#include "store/col.h" +#include "store/encw.h" /* ray_encw_type_supported / _summable / _has_dict */ +#include "store/encidx.h" /* the index region: parse */ +#include "ops/idxop.h" /* ray_index_kind_admits, ray_idx_lazy_forget */ +#include "lang/format.h" /* ray_type_name */ +#include "core/platform.h" +#include "mem/sys.h" /* ray_sys_alloc: the map descriptor, as col.c */ +#include "table/sym.h" +#include "table/domain.h" +#include "vec/vec.h" /* ray_vec_has_nulls */ +#include "store/enc.h" +#include "store/colrange.h" /* RAY_COL_POINT_ROWS: the most rows a caller hands one point read */ +#include "vec/str.h" +#include "ops/hash.h" /* ray_hash_bytes: the STR dictionary lookup table */ +#include "core/pool.h" +#include "mem/heap.h" /* ray_heap_anon_watermark: the trim budget */ +#include "core/block.h" /* ray_block_size: what a kept decode occupies */ +#include "lang/eval.h" /* ray_eval_depth: the trim waits for the statement */ +#include +#include +#include + +ray_enccol_t* ray_enccol_of(ray_t* v) { + if (!v || RAY_IS_ERR(v) || v->type != RAY_ENCCOL) return NULL; + ray_enccol_t* e; + memcpy(&e, v->data, sizeof e); + return e; +} + +static _Atomic(int64_t) g_enccol_live; /* test hook, see enccol.h */ +int64_t ray_enccol_test_live(void) { return atomic_load(&g_enccol_live); } + +/* Columns whose whole-column decode is published, for the statement- + * boundary trim. A decode may be published from a worker, so the list has + * its own lock; only the boundary drops decodes. */ +static atomic_flag g_dec_lock = ATOMIC_FLAG_INIT; +static ray_enccol_t* g_dec_head; +static _Atomic(uint64_t) g_dec_stmt = 1; + +static void dec_lock(void) { while (atomic_flag_test_and_set_explicit(&g_dec_lock, memory_order_acquire)) ray_enc_yield(); } +static void dec_unlock(void) { atomic_flag_clear_explicit(&g_dec_lock, memory_order_release); } + +static void dec_unlink(ray_enccol_t* e) { /* under the lock */ + if (!atomic_load_explicit(&e->dec_listed, memory_order_relaxed)) return; + if (e->dec_prev) e->dec_prev->dec_next = e->dec_next; else g_dec_head = e->dec_next; + if (e->dec_next) e->dec_next->dec_prev = e->dec_prev; + e->dec_prev = e->dec_next = NULL; + atomic_store_explicit(&e->dec_listed, false, memory_order_release); +} + +/* Bytes a kept decode frees when dropped: none while something else holds it. */ +static int64_t dec_bytes(ray_t* d) { + if (!d || ray_atomic_load(&d->rc) > 1) return 0; + return (int64_t)ray_block_size(d); +} + +static void dec_note(ray_enccol_t* e) { + atomic_store_explicit(&e->dec_used, atomic_load_explicit(&g_dec_stmt, memory_order_relaxed), + memory_order_relaxed); + if (atomic_load_explicit(&e->dec_listed, memory_order_acquire)) return; + dec_lock(); + if (!atomic_load_explicit(&e->dec_listed, memory_order_relaxed) && e->decoded) { + e->dec_prev = NULL; + e->dec_next = g_dec_head; + if (g_dec_head) g_dec_head->dec_prev = e; + g_dec_head = e; + atomic_store_explicit(&e->dec_listed, true, memory_order_release); + } + dec_unlock(); +} + +int64_t ray_enccol_cache_bytes(void) { + int64_t total = 0; + dec_lock(); + for (ray_enccol_t* e = g_dec_head; e; e = e->dec_next) total += dec_bytes(e->decoded); + dec_unlock(); + return total; +} + +void ray_enccol_cache_trim(void) { + uint64_t stmt = atomic_fetch_add_explicit(&g_dec_stmt, 1, memory_order_relaxed); + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return; + if (ray_eval_depth() > 0) return; /* a statement is still on the stack */ + if (atomic_load_explicit(&ray_parallel_flag, memory_order_acquire) != 0) return; + int64_t cap = wm / 4; + dec_lock(); + int64_t total = 0; + for (ray_enccol_t* e = g_dec_head; e; e = e->dec_next) total += dec_bytes(e->decoded); + while (total > cap) { + ray_enccol_t* v = NULL; + uint64_t vu = 0; int64_t vb = 0; + for (ray_enccol_t* e = g_dec_head; e; e = e->dec_next) { + int64_t b = dec_bytes(e->decoded); + if (b == 0) continue; + uint64_t u = atomic_load_explicit(&e->dec_used, memory_order_relaxed); + if (!v || u < vu || (u == vu && b > vb)) { v = e; vu = u; vb = b; } + } + if (!v) break; + ray_t* d = v->decoded; + v->decoded = NULL; + ray_enc_once_init(&v->once); /* the next read decodes again */ + dec_unlink(v); + ray_idx_lazy_forget(d); /* a lazy hash goes with its object */ + ray_release(d); + total -= vb; + } + dec_unlock(); + (void)stmt; +} + +static void enccol_free(ray_enccol_t* e) { + atomic_fetch_sub_explicit(&g_enccol_live, 1, memory_order_relaxed); + if (atomic_load_explicit(&e->dec_listed, memory_order_acquire)) { dec_lock(); dec_unlink(e); dec_unlock(); } + ray_idx_lazy_forget_enc(e); /* a pending probe count goes with the payload */ + if (e->decoded) { + ray_idx_lazy_forget(e->decoded); /* a lazy hash goes with its object */ + ray_release(e->decoded); + } + if (e->dict) ray_release(e->dict); + if (e->sdict) ray_release(e->sdict); + if (e->fsst) ray_release(e->fsst); + if (e->idict) ray_release(e->idict); + if (e->icodes) ray_release(e->icodes); + if (e->wrapper) ray_release(e->wrapper); + if (e->dom && e->dom_owned) ray_sym_domain_release(e->dom); + if (e->map) ray_file_map_release(e->map); + ray_free_raw((void*)e->touch_ok); + ray_free_raw(e); +} + +void ray_enccol_ref(ray_enccol_t* e) { atomic_fetch_add_explicit(&e->rc, 1, memory_order_relaxed); } +void ray_enccol_unref(ray_enccol_t* e) { + if (atomic_fetch_sub_explicit(&e->rc, 1, memory_order_acq_rel) == 1) enccol_free(e); +} + +void ray_enccol_payload_retain(ray_t* v) { + ray_enccol_t* e = ray_enccol_of(v); + if (e) atomic_fetch_add_explicit(&e->rc, 1, memory_order_relaxed); +} + +void ray_enccol_payload_release(ray_t* v) { + ray_enccol_t* e = ray_enccol_of(v); + if (!e) return; + memset(v->data, 0, sizeof e); + if (atomic_fetch_sub_explicit(&e->rc, 1, memory_order_acq_rel) == 1) enccol_free(e); +} + +void ray_enccol_payload_detach(ray_t* v) { + if (v && v->type == RAY_ENCCOL) memset(v->data, 0, sizeof(ray_enccol_t*)); +} + +size_t ray_enccol_own_bytes(ray_t* v) { + ray_enccol_t* e = ray_enccol_of(v); + return (e && e->map) ? e->map->len : 0; +} + +int ray_enccol_children(ray_t* v, ray_t* out[2]) { + ray_enccol_t* e = ray_enccol_of(v); + int n = 0; + if (!e) return 0; + if (e->decoded) out[n++] = e->decoded; + if (e->wrapper) out[n++] = e->wrapper; + return n; +} + +ray_t* ray_enccol_wrap(ray_enccol_t* e) { + ray_t* v = ray_alloc(sizeof(ray_enccol_t*)); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + v->type = RAY_ENCCOL; + v->attrs = 0; + v->len = e->len; + memset(v->aux, 0, 16); + memcpy(v->data, &e, sizeof e); + return v; +} + +static bool enc_type_float(int8_t t) { return t == RAY_F32 || t == RAY_F64; } + +static uint64_t rd_u64(const uint8_t* p) { uint64_t x; memcpy(&x, p, 8); return x; } + +#define ENC_CORRUPT(...) return ray_error("corrupt", __VA_ARGS__) + +/* The side table (spec "Side data"): where each entry starts and how long + * it is. Its contents are taken as written; only its extents are checked, + * once, so a short file fails whole instead of reading past its mapping. */ +static ray_t* enc_parse_side_table(ray_enccol_t* e) { + const uint8_t* s = e->base + e->hdr.side_off; + uint64_t sl = e->hdr.side_len; + uint32_t ne; memcpy(&ne, s, 4); + if (ne == 0 || ne > 3) ENC_CORRUPT("column %s: side table entry count %u", e->path, ne); + if (8 + 24ull * ne > sl) ENC_CORRUPT("column %s: side table longer than the side data", e->path); + for (uint32_t i = 0; i < ne; i++) { + const uint8_t* t = s + 8 + 24 * i; + uint16_t kind; memcpy(&kind, t, 2); + uint64_t off = rd_u64(t + 8), len = rd_u64(t + 16); + if (len < 8 || len > sl || off > sl - len) + ENC_CORRUPT("column %s: side entry %u overruns the side data", e->path, i); + if (kind == RAY_ENC_SIDE_VALUE_DICT) { e->vdict_off = e->hdr.side_off + off; e->vdict_len = len; } + else if (kind == RAY_ENC_SIDE_STR_DICT) { e->sdict_off = e->hdr.side_off + off; e->sdict_len = len; } + else { e->fsst_off = e->hdr.side_off + off; e->fsst_len = len; } + } + return NULL; +} + +/* The headers, the chunk count, the directory's null total and the side + * table. Only the header version selects a reader; the values are taken + * as written (files rayforce wrote are trusted). The extents of every + * section are checked against the file's size, once at open: a truncated + * or short file fails whole, with its name. */ +static ray_t* enc_parse_load(ray_enccol_t* e, uint32_t* saved_sym) { + const uint8_t* b = e->base; + uint64_t size = e->size; + if (size < RAY_ENC_DIR_OFF) ENC_CORRUPT("column %s: generation-2 file shorter than its headers", e->path); + ray_t h; memcpy(&h, b, 32); + uint32_t rc; memcpy(&rc, b + offsetof(ray_t, rc), 4); + *saved_sym = rc; + e->type = h.type; e->attrs = h.attrs; e->len = h.len; + ray_enc_hdr_t* eh = &e->hdr; + memcpy(eh, b + RAY_ENC_HDR_OFF, sizeof *eh); + if (eh->header_version != RAY_ENC_HDR_VERSION) + return ray_error("version", "column %s: generation-2 header version %u", e->path, eh->header_version); + if (eh->end_off != size) + ENC_CORRUPT("column %s: end offset %llu, file is %llu bytes (truncated?)", e->path, + (unsigned long long)eh->end_off, (unsigned long long)size); + /* the directory must fit: bound len before deriving the chunk count */ + if (h.len < 0 || + (uint64_t)h.len > ((size - RAY_ENC_DIR_OFF) / sizeof(ray_enc_dirent_t)) * (uint64_t)RAY_ENC_CHUNK) + ENC_CORRUPT("column %s: length %lld exceeds what the file holds", e->path, (long long)h.len); + e->n_chunks = ray_enc_nchunks(h.len); + if ((uint64_t)e->n_chunks > (size - RAY_ENC_DIR_OFF) / sizeof(ray_enc_dirent_t)) + ENC_CORRUPT("column %s: directory past the end of the file", e->path); + e->null_count = 0; + for (int64_t c = 0; c < e->n_chunks; c++) { + ray_enc_dirent_t de; + memcpy(&de, b + RAY_ENC_DIR_OFF + c * sizeof de, sizeof de); + if ((de.offset & 7) || de.bytes < RAY_ENC_DESC_AREA || de.offset > size || de.bytes > size - de.offset) + ENC_CORRUPT("column %s: chunk %lld at %llu, %llu bytes, overruns the file", e->path, (long long)c, + (unsigned long long)de.offset, (unsigned long long)de.bytes); + e->null_count += de.null_count; + } + if (eh->side_off) { + if (eh->side_len < 8 || eh->side_off > size || eh->side_len > size - eh->side_off) + ENC_CORRUPT("column %s: side data overruns the file", e->path); + ray_t* serr = enc_parse_side_table(e); + if (serr) return serr; + } + /* the region opens with the 80-byte wire root (spec "Index region") */ + if (eh->index_off && (eh->index_off >= size || size - eh->index_off < 80)) + ENC_CORRUPT("column %s: index region overruns the file", e->path); + return NULL; +} + +ray_t* ray_enccol_open(void* mapped, size_t size, const char* path, + struct ray_sym_domain_s* dom, bool require_dom) { + /* Only this gate keeps a big-endian host from reading the + * little-endian layout. */ + if (!ray_enc_gen2_supported()) { + ray_vm_unmap_file(mapped, size); + return ray_error("nyi", "column %s: generation 2 needs a little-endian host", path); + } + ray_file_map_t* m = (ray_file_map_t*)ray_sys_alloc(sizeof(*m)); + if (!m) { ray_vm_unmap_file(mapped, size); return ray_error("oom", NULL); } + m->base = mapped; m->len = size; m->rc = 1; m->next = NULL; + ray_enccol_t* e = ray_calloc_raw(sizeof *e); + if (!e) { ray_file_map_release(m); return ray_error("oom", NULL); } + atomic_fetch_add_explicit(&g_enccol_live, 1, memory_order_relaxed); + atomic_store(&e->rc, 1); + e->kind = RAY_ENCCOL_SINGLE; + e->map = m; e->base = (const uint8_t*)mapped; e->size = size; + snprintf(e->path, sizeof e->path, "%s", path ? path : "?"); + ray_enc_once_init(&e->once); + ray_enc_once_init(&e->dict_once); + ray_enc_once_init(&e->sdict_once); + ray_enc_once_init(&e->fsst_once); + ray_enc_once_init(&e->idict_once); + ray_enc_once_init(&e->icodes_once); + uint32_t saved = 0; + /* Descriptors and packed bodies are read in place as 8-byte words: the + * format keeps every offset 8-aligned, and a mapping starts on a page. */ + ray_t* err = ((uintptr_t)mapped & 7) ? ray_error("nyi", "column %s: mapping not 8-aligned", e->path) + : enc_parse_load(e, &saved); + if (!err && e->n_chunks > 0 && e->type != RAY_GUID && e->type != RAY_STR) { + e->touch_ok = ray_calloc_raw((size_t)e->n_chunks); + if (!e->touch_ok) err = ray_error("oom", "column %s: chunk flags", e->path); + } + if (!err && e->type == RAY_SYM) { + if (dom) { + /* the symfile the caller named must hold every id the column + * was saved over (a usage check: another table's symfile) */ + int64_t dcount = ray_sym_domain_count(dom); + if (saved > 0 && (int64_t)saved > dcount) + err = ray_error("corrupt", "column %s: saved sym count %u exceeds symfile count %lld", + e->path, saved, (long long)dcount); + e->dom = dom; ray_sym_domain_retain(dom); e->dom_owned = true; + } else if (require_dom) { + err = ray_error("sym", "column %s: SYM data but no symfile resolved " + "(missing /sym or explicit sym argument)", e->path); + } else { + /* runtime ids of another process: the live table must hold them */ + uint32_t cur = ray_sym_count(); + if (saved > 0 && cur > 0 && cur < saved) err = ray_error("corrupt", "column %s: saved sym count %u exceeds %u", e->path, saved, cur); + e->dom = ray_sym_runtime_domain(); e->dom_owned = false; + } + } + if (err) { enccol_free(e); return err; } + ray_t* v = ray_enccol_wrap(e); + if (!v || RAY_IS_ERR(v)) enccol_free(e); + return v; +} + +static _Atomic(uint64_t) g_enc_materialized; +static _Atomic(uint64_t) g_enc_decoded_bytes; +static _Atomic(uint64_t) g_enc_at_first_exec = UINT64_MAX; +void ray_enc_note_exec_start(void) { + uint64_t want = UINT64_MAX; + atomic_compare_exchange_strong(&g_enc_at_first_exec, &want, atomic_load(&g_enc_materialized)); +} +void ray_enc_counters_get(ray_enc_counters_t* o) { + o->at_first_exec = atomic_load(&g_enc_at_first_exec); + o->materialized = atomic_load(&g_enc_materialized); + o->decoded_bytes = atomic_load(&g_enc_decoded_bytes); +} +void ray_enc_counters_reset(void) { + atomic_store(&g_enc_materialized, 0); + atomic_store(&g_enc_decoded_bytes, 0); + atomic_store(&g_enc_at_first_exec, UINT64_MAX); +} + +uint8_t ray_enccol_esz(const ray_enccol_t* e) { return ray_sym_elem_size(e->type, e->attrs); } + +static int64_t chunk_rows(const ray_enccol_t* e, int64_t c) { + int64_t r = e->len - c * RAY_ENC_CHUNK; + return r > RAY_ENC_CHUNK ? RAY_ENC_CHUNK : r; +} + +static void dirent_at(const ray_enccol_t* e, int64_t c, ray_enc_dirent_t* de) { + memcpy(de, e->base + RAY_ENC_DIR_OFF + c * sizeof *de, sizeof *de); +} + + +/* Chunk c's 64 descriptors, in place in the mapping. */ +const ray_enc_desc_t* ray_enccol_descs(const ray_enccol_t* e, int64_t c) { + ray_enc_dirent_t de; dirent_at(e, c, &de); + return (const ray_enc_desc_t*)(e->base + de.offset); /* 8-aligned: ray_enccol_open */ +} + +static _Atomic(int64_t) g_fail_alloc_at; +static char g_fail_path[256]; +static _Atomic(bool) g_fail_path_on; +void ray_enccol_test_fail_alloc(int64_t nth) { atomic_store(&g_fail_alloc_at, nth); } +void ray_enccol_test_fail_path(const char* sub) { + atomic_store(&g_fail_path_on, false); + if (sub) { snprintf(g_fail_path, sizeof g_fail_path, "%s", sub); atomic_store(&g_fail_path_on, true); } +} +bool ray_enccol_test_nth_alloc_fails(void) { + int64_t v = atomic_load(&g_fail_alloc_at); + while (v > 0) + if (atomic_compare_exchange_weak(&g_fail_alloc_at, &v, v - 1)) return v == 1; + return false; +} +static bool enc_alloc_fails(const ray_enccol_t* e) { + if (atomic_load(&g_fail_path_on) && strstr(e->path, g_fail_path)) return true; + return ray_enccol_test_nth_alloc_fails(); +} + +/* ---- VALUE_DICT side entry: read once (spec "Side data") ---- */ +static ray_t* enc_dict_load(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + ray_enc_kind_t k; + (void)ray_enc_value_kind(e->type, e->attrs, &k); + if (enc_alloc_fails(e)) { ray_enc_snap_set(fail, "oom", "column %s: VALUE_DICT", e->path); return NULL; } + const uint8_t* d = e->base + e->vdict_off; + uint32_t n; memcpy(&n, d, 4); + const size_t esz = (size_t)k.T / 8; + ray_t* vals = ray_vec_new(RAY_I64, n); + if (!vals || RAY_IS_ERR(vals)) { + ray_error_free(vals); /* vec_new can return an owned error, not just NULL */ + ray_enc_snap_set(fail, "oom", "column %s: VALUE_DICT", e->path); + return NULL; + } + vals->len = n; + uint64_t* out = (uint64_t*)ray_data(vals); + for (uint32_t i = 0; i < n; i++) { uint64_t x = 0; memcpy(&x, d + 8 + i * esz, esz); out[i] = x; } + return vals; +} + +/* The dictionary once published, else false (never loads): read without + * the once-state's lock, as the DONE store releases the slot it publishes + * (ray_enccol_decoded_peek relies on the same). */ +static bool enc_dict_ready(const ray_enccol_t* e, ray_enc_dict_t* out) { + if (atomic_load_explicit(&e->dict_once.state, memory_order_acquire) != RAY_ENC_ONCE_DONE) return false; + out->v = (const uint64_t*)ray_data(e->dict); + out->n = (uint32_t)e->dict->len; + return true; +} + +static ray_t* enc_dict(ray_enccol_t* e, ray_enc_dict_t* out) { + if (enc_dict_ready(e, out)) return NULL; /* every vector decode of a DICT column asks */ + ray_t* d = ray_enc_once_get(&e->dict_once, &e->dict, enc_dict_load, e); + if (RAY_IS_ERR(d)) return d; + out->v = (const uint64_t*)ray_data(d); + out->n = (uint32_t)d->len; + return NULL; +} + +/* ---- STR side entries (P6): read once, before first use ---- */ + +/* The entry table of a STR dictionary (the STR_DICT side entry, or the + * persisted DICT's entries, P6b): over n entries at offs / bytes, a zeroed + * RAY_U8 blob of head + sizeof(ray_enc_sdict_t) + cap * 4 bytes whose + * ray_enc_sdict_t sits at offset head (8-aligned), filled: the slot table, + * null_code, pooled. NULL with *blob set, or an owned oom error. */ +static ray_t* enc_sdict_build(const ray_enccol_t* e, const char* what, const uint64_t* offs, + const uint8_t* bytes, uint64_t n, size_t head, ray_t** blob) { + *blob = NULL; + uint64_t cap = 16; while (cap < 2ull * n) cap <<= 1; + const int64_t blen = (int64_t)(head + sizeof(ray_enc_sdict_t) + cap * sizeof(uint32_t)); + ray_t* b = ray_vec_new(RAY_U8, blen); + if (!b || RAY_IS_ERR(b)) { + if (b) ray_error_free(b); + return ray_error("oom", "column %s: %s", e->path, what); + } + b->len = blen; + memset(ray_data(b), 0, (size_t)blen); + ray_enc_sdict_t* d = (ray_enc_sdict_t*)((uint8_t*)ray_data(b) + head); + d->n = (uint32_t)n; d->null_code = UINT32_MAX; d->offs = offs; d->bytes = bytes; d->mask = cap - 1; + for (uint64_t k = 0; k < n; k++) { + const uint64_t len = offs[k + 1] - offs[k]; + if (len == 0) d->null_code = (uint32_t)k; /* at most one: entries are distinct */ + if (len > RAY_STR_INLINE_MAX) d->pooled += len; + uint64_t h = ray_hash_bytes(bytes + offs[k], (size_t)len) & d->mask; + while (d->slot[h]) h = (h + 1) & d->mask; + d->slot[h] = (uint32_t)k + 1; + } + *blob = b; + return NULL; +} + +/* The code of s in an entry table: >= 0, or -1 absent. */ +static int64_t enc_sdict_find(const ray_enc_sdict_t* d, const char* s, size_t len) { + uint64_t h = ray_hash_bytes(s, len) & d->mask; + while (d->slot[h]) { + const uint32_t q = d->slot[h] - 1; + if (d->offs[q + 1] - d->offs[q] == len && memcmp(d->bytes + d->offs[q], s, len) == 0) return q; + h = (h + 1) & d->mask; + } + return -1; +} + +static ray_t* enc_sdict_load(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + if (enc_alloc_fails(e)) { ray_enc_snap_set(fail, "oom", "column %s: STR_DICT", e->path); return NULL; } + const uint8_t* p = e->base + e->sdict_off; + uint32_t n; memcpy(&n, p, 4); + const uint64_t* offs = (const uint64_t*)(p + 8); /* 8-aligned: 32-aligned entry in a mapping */ + const uint8_t* bytes = p + 8 + 8ull * (n + 1); + ray_t* blob = NULL; + ray_t* err = enc_sdict_build(e, "STR_DICT", offs, bytes, n, 0, &blob); + if (err) { ray_enc_snap_take(fail, err); return NULL; } + return blob; +} + +/* The dictionary once published, else NULL (never loads): read without + * the once-state's lock, as enc_dict_ready. */ +static const ray_enc_sdict_t* enc_sdict_ready(const ray_enccol_t* e) { + if (atomic_load_explicit(&e->sdict_once.state, memory_order_acquire) != RAY_ENC_ONCE_DONE) return NULL; + return (const ray_enc_sdict_t*)ray_data(e->sdict); +} + +ray_t* ray_enccol_strdict(ray_enccol_t* e, const ray_enc_sdict_t** out) { + *out = NULL; + if (e->type != RAY_STR || !e->sdict_len) return NULL; + if ((*out = enc_sdict_ready(e)) != NULL) return NULL; /* every STR_DICT vector decode asks */ + ray_t* b = ray_enc_once_get(&e->sdict_once, &e->sdict, enc_sdict_load, e); + if (RAY_IS_ERR(b)) return b; + *out = (const ray_enc_sdict_t*)ray_data(b); + return NULL; +} + +ray_t* ray_enccol_strdict_code(ray_enccol_t* e, const char* s, size_t len, int64_t* code) { + const ray_enc_sdict_t* d; + ray_t* err = ray_enccol_strdict(e, &d); + if (err) return err; + if (!d) { *code = -2; return NULL; } + *code = enc_sdict_find(d, s, len); + return NULL; +} + +/* ---- the persisted DICT (P6b, spec "STR dictionary index") ---- + * Two once-states: the entry table (parsed from the region) precedes every + * use; the heap copy of the codes precedes every whole-codes use. */ +typedef struct { + ray_enc_idict_t pub; +} enc_idict_blob_t; +/* The blob: this head, then the entry table */ +_Static_assert(sizeof(enc_idict_blob_t) % _Alignof(ray_enc_sdict_t) == 0, "the entry table follows aligned"); + +static ray_t* enc_idict_load(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + if (enc_alloc_fails(e)) { ray_enc_snap_set(fail, "oom", "column %s: DICT", e->path); return NULL; } + ray_enc_dict_view_t v; + ray_enc_dict_parse(e->base + e->hdr.index_off, &v); + ray_t* blob = NULL; + ray_t* err = enc_sdict_build(e, "DICT", v.offs, v.bytes, (uint64_t)v.n_distinct, sizeof(enc_idict_blob_t), &blob); + if (err) { ray_enc_snap_take(fail, err); return NULL; } + enc_idict_blob_t* d = (enc_idict_blob_t*)ray_data(blob); + d->pub.len = v.len; d->pub.n_distinct = v.n_distinct; d->pub.codes = v.codes; d->pub.first_occ = v.first_occ; + d->pub.ent = (const ray_enc_sdict_t*)((const uint8_t*)ray_data(blob) + sizeof(enc_idict_blob_t)); + return blob; +} + +/* The entry table once published, else NULL (never loads): read without + * the once-state's lock, as enc_sdict_ready. */ +static const enc_idict_blob_t* enc_idict_ready(const ray_enccol_t* e) { + if (atomic_load_explicit(&e->idict_once.state, memory_order_acquire) != RAY_ENC_ONCE_DONE) return NULL; + return (const enc_idict_blob_t*)ray_data(e->idict); +} + +bool ray_enccol_has_idict(const ray_enccol_t* e) { + return e && e->kind == RAY_ENCCOL_SINGLE && !e->synthetic && e->hdr.index_kind == RAY_IDX_DICT; +} + +static ray_t* enc_idict_get(ray_enccol_t* e, const enc_idict_blob_t** out) { + *out = NULL; + if (!ray_enccol_has_idict(e)) return NULL; + if ((*out = enc_idict_ready(e)) != NULL) return NULL; + ray_t* b = ray_enc_once_get(&e->idict_once, &e->idict, enc_idict_load, e); + if (RAY_IS_ERR(b)) return b; + *out = (const enc_idict_blob_t*)ray_data(b); + return NULL; +} + +ray_t* ray_enccol_idict(ray_enccol_t* e, const ray_enc_idict_t** out) { + const enc_idict_blob_t* b; + ray_t* err = enc_idict_get(e, &b); + *out = b ? &b->pub : NULL; + return err; +} + +ray_t* ray_enccol_idict_code(ray_enccol_t* e, const char* s, size_t len, int64_t* code) { + const ray_enc_idict_t* d; + ray_t* err = ray_enccol_idict(e, &d); + if (err) return err; + if (!d) { *code = -2; return NULL; } + *code = enc_sdict_find(d->ent, s, len); + return NULL; +} + +ray_t* ray_enccol_idict_codes(ray_enccol_t* e, int64_t start, int64_t n, const int32_t** out) { + *out = NULL; + const ray_enc_idict_t* d; + ray_t* err = ray_enccol_idict(e, &d); + if (err) return err; + if (!d) return ray_error("type", "column %s: no DICT index", e ? e->path : "?"); + if (start < 0 || n < 0 || start > d->len || n > d->len - start) + return ray_error("range", "column %s: DICT codes [%lld, +%lld) outside %lld rows", e->path, + (long long)start, (long long)n, (long long)d->len); + *out = d->codes + start; + return NULL; +} + +/* The heap copy of the codes: not a materialization (spec + * "Instrumentation", P6b), so neither e->once nor the counters move. */ +static ray_t* enc_icodes_build(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + const enc_idict_blob_t* d; + ray_t* err = enc_idict_get(e, &d); + if (err) { ray_enc_snap_take(fail, err); return NULL; } + if (!d) { ray_enc_snap_set(fail, "type", "column %s: no DICT index", e->path); return NULL; } + ray_t* v = enc_alloc_fails(e) ? NULL : ray_vec_new(RAY_I32, d->pub.len); + if (!v || RAY_IS_ERR(v)) { + if (v) ray_error_free(v); + ray_enc_snap_set(fail, "oom", "column %s: DICT codes", e->path); + return NULL; + } + v->len = d->pub.len; + memcpy(ray_data(v), d->pub.codes, (size_t)d->pub.len * sizeof(int32_t)); + return v; +} + +ray_t* ray_enccol_idict_codes_vec(ray_enccol_t* e, ray_t** out) { + *out = NULL; + if (!e) return ray_error("type", "column ?: no DICT index"); + if (atomic_load_explicit(&e->icodes_once.state, memory_order_acquire) == RAY_ENC_ONCE_DONE) { + *out = e->icodes; return NULL; + } + ray_t* v = ray_enc_once_get(&e->icodes_once, &e->icodes, enc_icodes_build, e); + if (RAY_IS_ERR(v)) return v; + *out = v; + return NULL; +} + +/* FSST_TABLE (spec "Side data"): u8 n, 7 zero bytes, n symbol lengths + * padded to 8, n symbols of 8 bytes (zero past their length). */ +static ray_t* enc_fsst_load(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + if (enc_alloc_fails(e)) { ray_enc_snap_set(fail, "oom", "column %s: FSST_TABLE", e->path); return NULL; } + const uint8_t* p = e->base + e->fsst_off; + const uint8_t n = p[0]; + ray_t* blob = ray_vec_new(RAY_U8, (int64_t)sizeof(ray_fsst_table_t)); + if (!blob || RAY_IS_ERR(blob)) { + if (blob) ray_error_free(blob); + ray_enc_snap_set(fail, "oom", "column %s: FSST_TABLE", e->path); + return NULL; + } + blob->len = (int64_t)sizeof(ray_fsst_table_t); + ray_fsst_table_t* t = (ray_fsst_table_t*)ray_data(blob); + memset(t, 0, sizeof *t); + t->n = n; + const uint8_t* syms = p + 8 + ray_enc_pad8(n); + for (int k = 0; k < n; k++) { t->len[k] = p[8 + k]; memcpy(t->sym[k], syms + 8 * k, 8); } + return blob; +} + +static ray_t* enc_fsst(ray_enccol_t* e, const ray_fsst_table_t** out) { + *out = NULL; + if (atomic_load_explicit(&e->fsst_once.state, memory_order_acquire) == RAY_ENC_ONCE_DONE) { + *out = (const ray_fsst_table_t*)ray_data(e->fsst); /* published: no lock (enc_dict_ready) */ + return NULL; + } + ray_t* b = ray_enc_once_get(&e->fsst_once, &e->fsst, enc_fsst_load, e); + if (RAY_IS_ERR(b)) return b; + *out = (const ray_fsst_table_t*)ray_data(b); + return NULL; +} + +static ray_t* dec_ints(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, + const uint8_t* p, uint64_t avail, const uint8_t* bm, void* out) { + ray_enc_kind_t k; + (void)ray_enc_kind_of(e->type, e->attrs, &k); + ray_enc_dict_t dict = {0}; + if (d->encoding == RAY_ENC_DICT) { ray_t* err = enc_dict(e, &dict); if (err) return err; } + uint64_t bits[RAY_ENC_VEC]; + (void)ray_enc_read(p, (size_t)avail, d->encoding, d->width, vlen, k, + RAY_ENC_SLOT_TOP, 0, d->encoding == RAY_ENC_DICT ? &dict : NULL, bits); + const uint8_t esz = ray_enccol_esz(e); + const bool sym = e->type == RAY_SYM; + for (int i = 0; i < vlen; i++) { + const bool null = bm && ((bm[i >> 3] >> (i & 7)) & 1); + const uint64_t x = bits[i]; + switch (esz) { + case 1: ((uint8_t*)out)[i] = (uint8_t)x; break; + case 2: if (sym) ((uint16_t*)out)[i] = (uint16_t)x; else ((int16_t*)out)[i] = null ? NULL_I16 : (int16_t)x; break; + case 4: if (sym) ((uint32_t*)out)[i] = (uint32_t)x; else ((int32_t*)out)[i] = null ? NULL_I32 : (int32_t)x; break; + default: if (sym) ((uint64_t*)out)[i] = x; else ((int64_t*)out)[i] = null ? NULL_I64 : (int64_t)x; break; + } + } + return NULL; +} + +/* The float trailer after a codec body that ends at t (spec "Floats"): + * its raw NaN bits written at their rows (after the canonical nulls). */ +static void enc_float_trailer(ray_enccol_t* e, const ray_enc_desc_t* d, const uint8_t* t, void* out) { + if (!(d->flags & RAY_ENC_DESC_TRAILER)) return; + const size_t esz = e->type == RAY_F32 ? 4 : 8; + uint16_t cnt; memcpy(&cnt, t, 2); + const uint8_t* raw = t + 8 + ray_enc_pad8(2ull * cnt); + for (int i = 0; i < cnt; i++) { + uint16_t pos; memcpy(&pos, t + 8 + 2 * i, 2); + memcpy((uint8_t*)out + pos * esz, raw + i * esz, esz); + } +} + +/* Every float encoding (RAW, CONST, RLE, DICT, ALP, ALP_RD): the codec + * body, then the canonical nulls, then the trailer's raw bits (spec + * "Floats"). */ +static ray_t* dec_floats(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, + const uint8_t* p, uint64_t avail, const uint8_t* bm, void* out) { + const bool f32 = e->type == RAY_F32; + const size_t esz = f32 ? 4 : 8; + ray_enc_dict_t dict = {0}; + if (d->encoding == RAY_ENC_DICT) { ray_t* err = enc_dict(e, &dict); if (err) return err; } + uint64_t bits[RAY_ENC_VEC]; + int64_t used = ray_enc_float_read(p, (size_t)avail, d->encoding, vlen, f32 ? 32 : 64, + d->encoding == RAY_ENC_DICT ? &dict : NULL, bits); + for (int i = 0; i < vlen; i++) { + uint8_t* q = (uint8_t*)out + (size_t)i * esz; + if (bm && ((bm[i >> 3] >> (i & 7)) & 1)) { + if (f32) { float nf = NULL_F32; memcpy(q, &nf, 4); } else { double nd = NULL_F64; memcpy(q, &nd, 8); } + continue; + } + memcpy(q, &bits[i], esz); + } + enc_float_trailer(e, d, p + used, out); + return NULL; +} + +static void dec_guid(const ray_enc_desc_t* d, int vlen, const uint8_t* p, void* out) { + if (d->encoding == RAY_ENC_CONST) { + for (int i = 0; i < vlen; i++) memcpy((uint8_t*)out + i * 16, p, 16); + } else { + memcpy(out, p, (size_t)vlen * 16); + } +} + +/* STR vectors: the RAW / CONST grammar (spec "STR RAW"), STR_DICT codes + * into the column's dictionary and FSST slices against its table. With + * out == NULL it only sizes the decoded pool bytes; with out set pool_out + * has room for pool_base + pooled bytes. dict_pool_off: NULL in vector + * scope, where a STR_DICT vector copies each distinct pooled code's entry + * once, at its first row, and every row of that code shares the offset + * (Ruling 3-1: the layout of the dictionary-first pool; both passes meet + * the codes in the same order, so they count the same bytes); at + * materialization the dictionary region's offset of each code, whose + * entries add no bytes to the vector's (Task 4). */ +static ray_t* dec_str(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, + const uint8_t* p, uint64_t avail, void* out, char* pool_out, + uint64_t pool_base, uint64_t* pooled_out, const uint32_t* dict_pool_off) { + ray_str_t* o = (ray_str_t*)out; + uint64_t pooled = 0; + if (d->encoding == RAY_ENC_STR_DICT) { + const ray_enc_sdict_t* sd; + ray_t* err = ray_enccol_strdict(e, &sd); + if (err) return err; + uint64_t codes[RAY_ENC_VEC]; + ray_enc_strdict_read(p, (size_t)avail, vlen, codes); + /* vector scope: the pooled codes met so far (code + 1) and their + * offsets in the vector's pool; at most vlen <= 1024 of them */ + uint32_t vk[2 * RAY_ENC_VEC], vo[2 * RAY_ENC_VEC]; + _Static_assert(2 * RAY_ENC_VEC == 1 << 11, "the slot hash below keeps the product's top 11 bits"); + if (!dict_pool_off) memset(vk, 0, sizeof vk); + for (int i = 0; i < vlen; i++) { + const char* sp; uint32_t len; + ray_enc_sdict_entry(sd, (uint32_t)codes[i], &sp, &len); + const bool pooled_row = len > RAY_STR_INLINE_MAX; + uint32_t slot = 0; bool first = false; + if (pooled_row && !dict_pool_off) { + slot = (uint32_t)(codes[i] * 0x9E3779B1u) >> (32 - 11); /* 2048 slots: the high bits (multiples of 2048 spread) */ + while (vk[slot] && vk[slot] != (uint32_t)codes[i] + 1) slot = (slot + 1) & (2 * RAY_ENC_VEC - 1); + if (!vk[slot]) { + first = true; + vk[slot] = (uint32_t)codes[i] + 1; + vo[slot] = (uint32_t)pooled; + pooled += len; + } + } + if (!out) continue; + memset(&o[i], 0, sizeof o[i]); + o[i].len = len; + if (!pooled_row) { memcpy(o[i].data, sp, len); continue; } + memcpy(o[i].prefix, sp, 4); + if (dict_pool_off) { o[i].pool_off = dict_pool_off[codes[i]]; continue; } + const uint64_t off = pool_base + vo[slot]; + if (first) memcpy(pool_out + off, sp, len); + o[i].pool_off = (uint32_t)off; + } + } else if (d->encoding == RAY_ENC_FSST) { + const ray_fsst_table_t* t; + ray_t* err = enc_fsst(e, &t); + if (err) return err; + uint64_t clen[RAY_ENC_VEC], xlen[RAY_ENC_VEC]; const uint8_t* cb; + ray_enc_fsst_parse(p, (size_t)avail, vlen, t, clen, xlen, &cb); + for (int i = 0; i < vlen; i++) if (xlen[i] > RAY_STR_INLINE_MAX) pooled += xlen[i]; + uint64_t at = 0, run = 0; + for (int i = 0; out && i < vlen; i++) { + memset(&o[i], 0, sizeof o[i]); + o[i].len = (uint32_t)xlen[i]; + if (xlen[i] <= RAY_STR_INLINE_MAX) { + (void)ray_fsst_decode(t, cb + at, (uint32_t)clen[i], (uint8_t*)o[i].data); + } else { + uint8_t* dst = (uint8_t*)pool_out + pool_base + run; + (void)ray_fsst_decode(t, cb + at, (uint32_t)clen[i], dst); + memcpy(o[i].prefix, dst, 4); + o[i].pool_off = (uint32_t)(pool_base + run); + run += xlen[i]; + } + at += clen[i]; + } + } else if (d->encoding == RAY_ENC_CONST) { + uint32_t len; memcpy(&len, p, 4); + if (len > RAY_STR_INLINE_MAX) pooled = (uint64_t)len * (uint64_t)vlen; + if (out) { + for (int i = 0; i < vlen; i++) { + memset(&o[i], 0, sizeof o[i]); + o[i].len = len; + if (len <= RAY_STR_INLINE_MAX) { memcpy(o[i].data, p + 8, len); continue; } + uint64_t off = pool_base + (uint64_t)i * len; + memcpy(pool_out + off, p + 8, len); + memcpy(o[i].prefix, p + 8, 4); + o[i].pool_off = (uint32_t)off; + } + } + } else { + const uint64_t dbytes = (uint64_t)vlen * 16; + memcpy(&pooled, p + dbytes, 8); + if (out) { + const uint8_t* vp = p + dbytes + 8; + uint64_t run = 0; + for (int i = 0; i < vlen; i++) { + const uint8_t* w = p + (size_t)i * 16; + uint32_t len; memcpy(&len, w, 4); + if (len <= RAY_STR_INLINE_MAX) { memcpy(&o[i], w, 16); continue; } + memcpy(pool_out + pool_base + run, vp + run, len); + memset(&o[i], 0, sizeof o[i]); + o[i].len = len; memcpy(o[i].prefix, w + 4, 4); + o[i].pool_off = (uint32_t)(pool_base + run); + run += len; + } + } + } + if (pooled_out) *pooled_out = pooled; + return NULL; +} + +/* Split a payload into bitmap and body; shared by decode and pool sizing. */ +static void payload_parts(const ray_enccol_t* e, int64_t c, const ray_enc_desc_t* d, + const uint8_t** body, uint64_t* avail, const uint8_t** bm) { + ray_enc_dirent_t de; dirent_at(e, c, &de); + const uint8_t* p = e->base + de.offset + d->payload_off; + uint64_t n = d->payload_bytes; + *bm = NULL; + if (d->n_nulls > 0 && ray_enc_has_bitmap(e->type)) { *bm = p; p += 128; n -= 128; } + *body = p; *avail = n; +} + +/* ---- Integer fast path: FOR_BP / DELTA_BP straight into the destination ---- + * One pass unpacks the interleaved lanes at the lane width T, adds the base + * (DELTA_BP: the lane's previous row and the delta base) and stores the + * element, at the generation-0 width or widened for an expression register; + * with a bitmap, one more pass writes the null into its rows. No u64 + * intermediate, no aside copy. It declines only on shapes it has no kernel + * for (an alignment, a code child, a widening it does not do), and the + * reference path decodes those. */ + +/* Lane l's field of the current row: w bits at bit offset off of word a[l] + * (off + w > T: continued in the next word row, a[l + L]). Arithmetic is + * in PT (unsigned, or uint64_t for 64-bit lanes) with shift counts masked + * below T, so the compiler keeps T-bit lanes (no widening to int). */ +#define FK_FIELD1(UT, PT, a, l, sr, m) ((UT)((PT)((PT)(a)[l] >> (sr)) & (PT)(m))) +#define FK_FIELD2(UT, PT, L, a, l, sr, sl, m) \ + ((UT)((PT)(((PT)(a)[l] >> (sr)) | ((PT)(a)[(l) + (L)] << (sl))) & (PT)(m))) + +/* One row of lanes [0, nl): the T-bit value V stored widened from ST to OT. */ +#define FK_ROW(UT, ST, OT, V) do { for (int l = 0; l < nl; l++) { const UT v_ = (V); o[l] = (OT)(ST)v_; } } while (0) + +/* FOR_BP: out[i] = base + field, rows below n. ST: the signed (or + * unsigned) view the element widens from; OT: the stored element. */ +#define FK_FOR(NAME, UT, PT, TB, ST, OT) \ +static void NAME(const UT* restrict in, int w, UT base, OT* restrict out, int n) { \ + enum { L = RAY_ENC_VEC / TB }; \ + const UT m = w >= TB ? (UT)~(UT)0 : (UT)(((PT)1 << w) - 1); \ + for (int r = 0, bit = 0; r * L < n; r++, bit += w) { \ + const int k = bit / TB, off = bit % TB; \ + const unsigned sr = (unsigned)off & (TB - 1), sl = (unsigned)(TB - off) & (TB - 1); \ + const int nl = n - r * L < L ? n - r * L : L; \ + const UT* a = in + (size_t)k * L; \ + OT* o = out + (size_t)r * L; \ + if (w == 0) FK_ROW(UT, ST, OT, base); \ + else if (off + w > TB) FK_ROW(UT, ST, OT, (UT)((PT)base + FK_FIELD2(UT, PT, L, a, l, sr, sl, m))); \ + else FK_ROW(UT, ST, OT, (UT)((PT)base + FK_FIELD1(UT, PT, a, l, sr, m))); \ + } \ +} +/* DELTA_BP: row 0 is the heads, row r the row above plus dbase plus field r. */ +#define FK_DELTA(NAME, UT, PT, TB, ST, OT) \ +static void NAME(const UT* restrict in, int w, UT dbase, const UT* restrict head, \ + OT* restrict out, int n) { \ + enum { L = RAY_ENC_VEC / TB }; \ + const UT m = w >= TB ? (UT)~(UT)0 : (UT)(((PT)1 << w) - 1); \ + UT prev[L]; \ + for (int l = 0; l < L; l++) prev[l] = head[l]; \ + { const int nl = n < L ? n : L; OT* o = out; FK_ROW(UT, ST, OT, prev[l]); } \ + for (int r = 1, bit = w; r * L < n; r++, bit += w) { \ + const int k = bit / TB, off = bit % TB; \ + const unsigned sr = (unsigned)off & (TB - 1), sl = (unsigned)(TB - off) & (TB - 1); \ + const int nl = n - r * L < L ? n - r * L : L; \ + const UT* a = in + (size_t)k * L; \ + OT* o = out + (size_t)r * L; \ + if (w == 0) FK_ROW(UT, ST, OT, prev[l] = (UT)((PT)prev[l] + dbase)); \ + else if (off + w > TB) \ + FK_ROW(UT, ST, OT, prev[l] = (UT)((PT)prev[l] + dbase + FK_FIELD2(UT, PT, L, a, l, sr, sl, m))); \ + else FK_ROW(UT, ST, OT, prev[l] = (UT)((PT)prev[l] + dbase + FK_FIELD1(UT, PT, a, l, sr, m))); \ + } \ +} +FK_FOR(fk_for8, uint8_t, unsigned, 8, uint8_t, uint8_t) +FK_FOR(fk_for16, uint16_t, unsigned, 16, uint16_t, uint16_t) +FK_FOR(fk_for32, uint32_t, unsigned, 32, uint32_t, uint32_t) +FK_FOR(fk_for64, uint64_t, uint64_t, 64, uint64_t, uint64_t) +FK_FOR(fk_for8_i, uint8_t, unsigned, 8, uint8_t, int64_t) +FK_FOR(fk_for16_i, uint16_t, unsigned, 16, int16_t, int64_t) +FK_FOR(fk_for32_i, uint32_t, unsigned, 32, int32_t, int64_t) +FK_FOR(fk_for8_f, uint8_t, unsigned, 8, uint8_t, double) +FK_FOR(fk_for16_f, uint16_t, unsigned, 16, int16_t, double) +FK_FOR(fk_for32_f, uint32_t, unsigned, 32, int32_t, double) +FK_DELTA(fk_dlt16, uint16_t, unsigned, 16, uint16_t, uint16_t) +FK_DELTA(fk_dlt32, uint32_t, unsigned, 32, uint32_t, uint32_t) +FK_DELTA(fk_dlt64, uint64_t, uint64_t, 64, uint64_t, uint64_t) +FK_DELTA(fk_dlt16_i, uint16_t, unsigned, 16, int16_t, int64_t) +FK_DELTA(fk_dlt32_i, uint32_t, unsigned, 32, int32_t, int64_t) +FK_DELTA(fk_dlt16_f, uint16_t, unsigned, 16, int16_t, double) +FK_DELTA(fk_dlt32_f, uint32_t, unsigned, 32, int32_t, double) + +/* The bitmap's rows become the null z. Out of line, so the loop + * vectorises. */ +#define FK_MERGE(NAME, OT, MT) \ +static __attribute__((noinline)) void NAME(OT* restrict o, int n, const uint8_t* restrict bm, OT z) { \ + for (int i = 0; i < n; i++) { \ + const MT nul = (MT)-(MT)((bm[i >> 3] >> (i & 7)) & 1u); \ + o[i] = nul ? z : o[i]; \ + } \ +} +FK_MERGE(fk_merge16, int16_t, uint16_t) +FK_MERGE(fk_merge32, int32_t, uint32_t) +FK_MERGE(fk_merge64, int64_t, uint64_t) +FK_MERGE(fk_mergef, double, uint64_t) + +static bool fk_int_type(int8_t t) { + return t != RAY_F32 && t != RAY_F64 && t != RAY_GUID && t != RAY_STR; +} + +/* The nulls of a signed kind at the generation-0 width: the bitmap's rows + * become the type's null. */ +static void fk_nulls_native(const ray_enc_desc_t* d, int T, int vlen, const uint8_t* bm, void* out) { + if (!d->n_nulls || !bm) return; + switch (T) { + case 16: fk_merge16((int16_t*)out, vlen, bm, NULL_I16); break; + case 32: fk_merge32((int32_t*)out, vlen, bm, NULL_I32); break; + case 64: fk_merge64((int64_t*)out, vlen, bm, NULL_I64); break; + default: break; /* BOOL, U8: no nulls */ + } +} + +/* The codes of a DICT body over a U32 FOR_BP code child, unpacked by the + * lane kernel. false (declined) on another code child or when the + * dictionary is not yet published (the reference path loads it). */ +static bool fk_dict_codes(ray_enccol_t* e, int vlen, const uint8_t* body, uint64_t avail, + ray_enc_dict_t* dict, uint32_t* codes) { + if (avail < 16 || body[0] != RAY_ENC_FOR_BP) return false; + if (!enc_dict_ready(e, dict)) return false; + uint64_t base; memcpy(&base, body + 8, 8); + fk_for32((const uint32_t*)(body + 16), body[1], (uint32_t)base, codes, vlen); + return true; +} + +/* DICT over a U32 FOR_BP code child, at the generation-0 width: the codes + * unpacked by the lane kernel, gathered from the dictionary, then the + * nulls as the FOR_BP path writes them. */ +static int dec_fast_dict(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, const uint8_t* body, + uint64_t avail, const uint8_t* bm, ray_enc_kind_t k, void* out) { + if (!k.is_signed) return 0; + ray_enc_dict_t dict; + _Alignas(64) uint32_t codes[RAY_ENC_VEC]; + if (!fk_dict_codes(e, vlen, body, avail, &dict, codes)) return 0; + const uint64_t* dv = dict.v; +#define FK_GATHER(UT) do { UT* o = out; for (int i = 0; i < vlen; i++) o[i] = (UT)dv[codes[i]]; } while (0) + switch (k.T) { + case 16: FK_GATHER(uint16_t); break; + case 32: FK_GATHER(uint32_t); break; + case 64: FK_GATHER(uint64_t); break; + default: return 0; + } +#undef FK_GATHER + fk_nulls_native(d, k.T, vlen, bm, out); + return 1; +} + +/* ---- CONST / RLE: the runs read, then filled at the element width ---- + * A CONST vector is one run. An RLE vector is nr runs: its values and its + * run ends are children at depth 1 (RAW or FOR_BP values of the element + * kind; RAW, FOR_BP or DELTA_BP U16 ends), each unpacked for its nr values + * only, by the lane kernels above. Then each run is filled, at the + * generation-0 width or widened as the FOR_BP kernels widen, and the + * bitmap's rows set to the null. */ + +/* nr T-bit values, by lane width (the view's lane buffer, enccol.h). */ +typedef ray_enc_lanes_t fk_vals_t; + +static uint64_t fk_val(const fk_vals_t* v, int T, uint32_t i) { + switch (T) { case 8: return v->b[i]; case 16: return v->h[i]; case 32: return v->s[i]; default: return v->q[i]; } +} + +/* An RLE child at depth 1: an 8-byte header at p, then nr values of T + * bits into out. The bytes used, or -1 for an encoding it has no kernel + * for. */ +static int64_t fk_child(const uint8_t* p, uint32_t nr, int T, fk_vals_t* out) { + const uint8_t enc = p[0], w = p[1]; + uint32_t bb; memcpy(&bb, p + 4, 4); + const uint8_t* b = p + 8; + if (enc == RAY_ENC_RAW) { + memcpy(out, b, (size_t)nr * (size_t)T / 8); + } else if (enc == RAY_ENC_FOR_BP) { + uint64_t base; memcpy(&base, b, 8); + switch (T) { + case 8: fk_for8((const uint8_t*)(b + 8), w, (uint8_t)base, out->b, (int)nr); break; + case 16: fk_for16((const uint16_t*)(b + 8), w, (uint16_t)base, out->h, (int)nr); break; + case 32: fk_for32((const uint32_t*)(b + 8), w, (uint32_t)base, out->s, (int)nr); break; + default: fk_for64((const uint64_t*)(b + 8), w, base, out->q, (int)nr); break; + } + } else if (enc == RAY_ENC_DELTA_BP && T == 16) { + enum { L = RAY_ENC_VEC / 16 }; + uint64_t dbase; memcpy(&dbase, b, 8); + uint16_t head[L]; + for (int l = 0; l < L; l++) { uint64_t x; memcpy(&x, b + 8 + 8 * (size_t)l, 8); head[l] = (uint16_t)x; } + fk_dlt16((const uint16_t*)(b + 8 + 8 * (size_t)L), w, (uint16_t)dbase, head, out->h, (int)nr); + } else { + return -1; + } + return 8 + (int64_t)bb; +} + +/* The runs of a CONST or RLE body of kind T: *nr values, run i ending at + * ends[i]. 1, or 0 declined. */ +static int fk_runs(uint8_t enc, int vlen, const uint8_t* body, int T, + fk_vals_t* vals, fk_vals_t* ends, uint32_t* nr_out) { + uint32_t nr; + if (enc == RAY_ENC_CONST) { + memcpy(vals, body, (size_t)T / 8); + ends->h[0] = (uint16_t)vlen; + nr = 1; + } else { + memcpy(&nr, body, 4); + int64_t a = fk_child(body + 8, nr, T, vals); + if (a < 0 || fk_child(body + 8 + a, nr, 16, ends) < 0) return 0; + } + *nr_out = nr; + return 1; +} + +/* A CONST / RLE vector of e's type into out (dec_fast's contract). */ +static int dec_fast_runs(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, const uint8_t* body, + const uint8_t* bm, int8_t wide, ray_enc_kind_t k, void* out) { + const int T = k.T; + const bool sym = e->type == RAY_SYM; + _Alignas(64) fk_vals_t vals, ends; + uint32_t nr; + if (!fk_runs(d->encoding, vlen, body, T, &vals, &ends, &nr)) return 0; + /* A run of at most 8 rows away from the vector's end is filled with + * one fixed 8-element store: the rows it writes past the run's end + * belong to the runs after it, which are filled later and wholly, so + * every row ends up holding its own run's value; nothing is written + * past vlen. */ +#define FK_FILL(OT, V) do { OT* o_ = (OT*)out; uint32_t p_ = 0; \ + for (uint32_t i = 0; i < nr; i++) { \ + const OT v_ = (OT)(V); const uint32_t e_ = ends.h[i]; \ + if (e_ - p_ <= 8 && p_ + 8 <= (uint32_t)vlen) \ + for (uint32_t z = 0; z < 8; z++) o_[p_ + z] = v_; \ + else \ + for (uint32_t r = p_; r < e_; r++) o_[r] = v_; \ + p_ = e_; } } while (0) + switch (T * 4 + (wide == RAY_I64 ? 1 : wide == RAY_F64 ? 2 : 0)) { + case 8 * 4: FK_FILL(uint8_t, vals.b[i]); break; + case 8 * 4 + 1: FK_FILL(int64_t, vals.b[i]); break; + case 8 * 4 + 2: FK_FILL(double, vals.b[i]); break; + case 16 * 4: FK_FILL(uint16_t, vals.h[i]); break; + case 16 * 4 + 1: FK_FILL(int64_t, (int16_t)vals.h[i]); break; + case 16 * 4 + 2: FK_FILL(double, (int16_t)vals.h[i]); break; + case 32 * 4: FK_FILL(uint32_t, vals.s[i]); break; + case 32 * 4 + 1: FK_FILL(int64_t, (int32_t)vals.s[i]); break; + case 32 * 4 + 2: FK_FILL(double, (int32_t)vals.s[i]); break; + case 64 * 4: FK_FILL(uint64_t, vals.q[i]); break; + default: return 0; + } +#undef FK_FILL + if (sym || !k.is_signed || !d->n_nulls || !bm) return 1; + if (!wide) fk_nulls_native(d, T, vlen, bm, out); + else if (wide == RAY_F64) fk_mergef((double*)out, vlen, bm, NULL_F64); + else fk_merge64((int64_t*)out, vlen, bm, NULL_I64); + return 1; +} + +/* A RAW vector of e's type at the generation-0 width into out: the values + * copied, the bitmap merged. */ +static int dec_fast_raw(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, const uint8_t* body, + const uint8_t* bm, ray_enc_kind_t k, void* out) { + memcpy(out, body, (size_t)vlen * k.T / 8); + if (e->type != RAY_SYM && k.is_signed) fk_nulls_native(d, k.T, vlen, bm, out); + return 1; +} + +/* ---- Float fast path: every float encoding straight into the destination ---- + * The values are written at the element width, then (with a bitmap) one + * branch-free pass writes the canonical null into the bitmap's rows. It + * declines (0) on a trailer and on shapes it has no kernel for; the + * reference path decodes those. */ +#define FL_MERGE(NAME, FT, UT, NULLV) \ +static __attribute__((noinline)) void NAME(UT* restrict o, int n, const uint8_t* restrict bm) { \ + FT nf = NULLV; UT nb; memcpy(&nb, &nf, sizeof nb); \ + for (int i = 0; i < n; i++) { \ + const UT nul = (UT)-(UT)((bm[i >> 3] >> (i & 7)) & 1u); \ + o[i] = (UT)((o[i] & ~nul) | (nb & nul)); \ + } \ +} +FL_MERGE(fl_merge64, double, uint64_t, NULL_F64) +FL_MERGE(fl_merge32, float, uint32_t, NULL_F32) +#undef FL_MERGE + +static int dec_fast_float(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, + const uint8_t* body, uint64_t avail, const uint8_t* bm, void* out) { + const bool f32 = e->type == RAY_F32; + const int T = f32 ? 32 : 64; + const uint8_t enc = d->encoding; + if (d->flags & RAY_ENC_DESC_TRAILER) return 0; + if (((uintptr_t)body & 7) || ((uintptr_t)out & ((size_t)T / 8 - 1))) return 0; + switch (enc) { + case RAY_ENC_CONST: case RAY_ENC_RLE: case RAY_ENC_DICT: { + _Alignas(64) fk_vals_t vals, ends; + uint32_t nr; + if (enc == RAY_ENC_DICT) { + if (avail >= 8 && body[0] == RAY_ENC_FOR_BP) { + ray_enc_dict_t dict; + _Alignas(64) uint32_t codes[RAY_ENC_VEC]; + if (!fk_dict_codes(e, vlen, body, avail, &dict, codes)) return 0; + const uint64_t* dv = dict.v; + if (f32) { uint32_t* o = out; for (int i = 0; i < vlen; i++) o[i] = (uint32_t)dv[codes[i]]; } + else { uint64_t* o = out; for (int i = 0; i < vlen; i++) o[i] = dv[codes[i]]; } + break; + } + /* an RLE code child (depth 1, its children at depth 2): the + * runs at the U32 code kind, each code an entry */ + if (avail < 16 || body[0] != RAY_ENC_RLE) return 0; + ray_enc_dict_t dict; + if (!enc_dict_ready(e, &dict)) return 0; + if (!fk_runs(RAY_ENC_RLE, vlen, body + 8, 32, &vals, &ends, &nr)) return 0; + /* the runs' values: the entries their codes name (nr <= vlen, + * so in place, at a lane index never above the code's) */ + if (f32) for (uint32_t i = 0; i < nr; i++) vals.s[i] = (uint32_t)dict.v[vals.s[i]]; + else for (uint32_t i = nr; i-- > 0;) vals.q[i] = dict.v[vals.s[i]]; + } else { + if (!fk_runs(enc, vlen, body, T, &vals, &ends, &nr)) return 0; + } + /* Each run in fixed FL_W-element stores while they stay inside + * the vector (one store for most runs, no per-row loop); the rows a + * store writes past the run's end belong to the runs after it, + * which are filled later and wholly, so every row ends up holding + * its own run's value; nothing is written past vlen. */ +#define FL_FILL(OT, V) do { OT* o_ = (OT*)out; uint32_t p_ = 0; \ + for (uint32_t i = 0; i < nr; i++) { \ + const OT v_ = (V); const uint32_t e_ = ends.h[i]; \ + uint32_t r_ = p_; \ + while (r_ < e_ && r_ + FL_W <= (uint32_t)vlen) { \ + for (uint32_t z = 0; z < FL_W; z++) o_[r_ + z] = v_; \ + r_ += FL_W; \ + } \ + for (; r_ < e_; r_++) o_[r_] = v_; \ + p_ = e_; } } while (0) +#define FL_W 16 + if (f32) FL_FILL(uint32_t, vals.s[i]); else FL_FILL(uint64_t, vals.q[i]); +#undef FL_W +#undef FL_FILL + break; + } + case RAY_ENC_RAW: + memcpy(out, body, (size_t)vlen * (size_t)T / 8); + break; + case RAY_ENC_ALP: case RAY_ENC_ALP_RD: { + /* ALP writes vlen patterns, ALP_RD a whole vector: F64 straight + * into out when that fits, else aside */ + if (!f32 && (enc == RAY_ENC_ALP || vlen == RAY_ENC_VEC)) { + (void)ray_enc_float_read(body, (size_t)avail, enc, vlen, 64, NULL, (uint64_t*)out); + break; + } + _Alignas(64) uint64_t bits[RAY_ENC_VEC]; + (void)ray_enc_float_read(body, (size_t)avail, enc, vlen, T, NULL, bits); + if (f32) { uint32_t* o = out; for (int i = 0; i < vlen; i++) o[i] = (uint32_t)bits[i]; } + else memcpy(out, bits, (size_t)vlen * 8); + break; + } + default: return 0; + } + if (bm && d->n_nulls) { if (f32) fl_merge32((uint32_t*)out, vlen, bm); else fl_merge64((uint64_t*)out, vlen, bm); } + return 1; +} + +/* Decode a FOR_BP / DELTA_BP / CONST / RLE vector body of e's type into + * out: `wide` 0 at the generation-0 width, RAY_I64 / RAY_F64 widened with + * nulls as NULL_I64 / NULL_F64 (narrow non-SYM types only). DICT over a + * FOR_BP code child (dec_fast_dict) and RAW (dec_fast_raw) at the + * generation-0 width; every float encoding at its width (dec_fast_float, + * wide 0 only). 1 decoded, 0 declined (out may be partly written). */ +static int dec_fast(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, + const uint8_t* body, uint64_t avail, const uint8_t* bm, int8_t wide, void* out) { + const uint8_t enc = d->encoding; + ray_enc_kind_t k; + if (e->type == RAY_F32 || e->type == RAY_F64) return wide ? 0 : dec_fast_float(e, d, vlen, body, avail, bm, out); + if (!fk_int_type(e->type) || !ray_enc_kind_of(e->type, e->attrs, &k)) return 0; + if (enc == RAY_ENC_CONST || enc == RAY_ENC_RLE || enc == RAY_ENC_RAW) { + if ((uintptr_t)body & 7) return 0; + if (wide && (e->type == RAY_SYM || k.T == 64 || enc == RAY_ENC_RAW)) return 0; + if ((uintptr_t)out & ((wide ? 8 : (size_t)k.T / 8) - 1)) return 0; + return enc == RAY_ENC_RAW ? dec_fast_raw(e, d, vlen, body, bm, k, out) + : dec_fast_runs(e, d, vlen, body, bm, wide, k, out); + } + if (enc != RAY_ENC_FOR_BP && enc != RAY_ENC_DELTA_BP && enc != RAY_ENC_DICT) return 0; + if (enc == RAY_ENC_DICT) { + if (wide || e->type == RAY_SYM) return 0; + if (((uintptr_t)body & 7) || ((uintptr_t)out & ((size_t)k.T / 8 - 1))) return 0; + return dec_fast_dict(e, d, vlen, body, avail, bm, k, out); + } + const int T = k.T, w = d->width, L = RAY_ENC_VEC / T; + const bool sym = e->type == RAY_SYM, delta = enc == RAY_ENC_DELTA_BP; + if (wide && (sym || T == 64)) return 0; + if (delta && !k.is_signed) return 0; + const size_t osz = wide ? 8 : (size_t)T / 8; + if (((uintptr_t)body & 7) || ((uintptr_t)out & (osz - 1))) return 0; + uint64_t base; memcpy(&base, body, 8); + const uint8_t* pk = body + 8 + (delta ? 8 * (size_t)L : 0); + union { uint8_t b[128]; uint16_t h[64]; uint32_t s[32]; uint64_t q[16]; } head; + if (delta) { + for (int l = 0; l < L; l++) { + uint64_t x; memcpy(&x, body + 8 + 8 * (size_t)l, 8); + switch (T) { case 16: head.h[l] = (uint16_t)x; break; case 32: head.s[l] = (uint32_t)x; break; default: head.q[l] = x; break; } + } + } + const int8_t wt = wide; +#define FK_RUN(FOR, DLT, UT, OT) do { \ + if (delta) DLT((const UT*)pk, w, (UT)base, (const UT*)head.b, (OT*)out, vlen); \ + else FOR((const UT*)pk, w, (UT)base, (OT*)out, vlen); } while (0) +#define FK_RUN_FOR(FOR, UT, OT) FOR((const UT*)pk, w, (UT)base, (OT*)out, vlen) + switch (T * 4 + (wt == RAY_I64 ? 1 : wt == RAY_F64 ? 2 : 0)) { + case 8 * 4: FK_RUN_FOR(fk_for8, uint8_t, uint8_t); break; + case 8 * 4 + 1: FK_RUN_FOR(fk_for8_i, uint8_t, int64_t); break; + case 8 * 4 + 2: FK_RUN_FOR(fk_for8_f, uint8_t, double); break; + case 16 * 4: FK_RUN(fk_for16, fk_dlt16, uint16_t, uint16_t); break; + case 16 * 4 + 1: FK_RUN(fk_for16_i, fk_dlt16_i, uint16_t, int64_t); break; + case 16 * 4 + 2: FK_RUN(fk_for16_f, fk_dlt16_f, uint16_t, double); break; + case 32 * 4: FK_RUN(fk_for32, fk_dlt32, uint32_t, uint32_t); break; + case 32 * 4 + 1: FK_RUN(fk_for32_i, fk_dlt32_i, uint32_t, int64_t); break; + case 32 * 4 + 2: FK_RUN(fk_for32_f, fk_dlt32_f, uint32_t, double); break; + case 64 * 4: FK_RUN(fk_for64, fk_dlt64, uint64_t, uint64_t); break; + default: return 0; + } +#undef FK_RUN +#undef FK_RUN_FOR + if (sym || !k.is_signed || !d->n_nulls || !bm) return 1; /* SYM nulls are in band; BOOL, U8 have none */ + if (!wt) fk_nulls_native(d, T, vlen, bm, out); + else if (wt == RAY_F64) fk_mergef((double*)out, vlen, bm, NULL_F64); + else fk_merge64((int64_t*)out, vlen, bm, NULL_I64); + return 1; +} + +/* The reference decoders by type, into out (vlen elements). */ +static ray_t* dec_ref(ray_enccol_t* e, const ray_enc_desc_t* d, int vlen, + const uint8_t* body, uint64_t avail, const uint8_t* bm, void* out) { + switch (e->type) { + case RAY_F32: case RAY_F64: return dec_floats(e, d, vlen, body, avail, bm, out); + case RAY_GUID: dec_guid(d, vlen, body, out); return NULL; + default: return dec_ints(e, d, vlen, body, avail, bm, out); + } +} + +/* Vector j of chunk c read in place: the mapped payload of a RAW vector + * with no nulls and no trailer, whose bits equal its decode. */ +const void* ray_enccol_raw_view(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d) { + (void)j; + if (e->kind != RAY_ENCCOL_SINGLE || e->type == RAY_GUID || e->type == RAY_STR || + d->encoding != RAY_ENC_RAW || d->n_nulls != 0 || (d->flags & RAY_ENC_DESC_TRAILER)) + return NULL; + ray_enc_dirent_t de; dirent_at(e, c, &de); + if (e->touch_ok && !atomic_load_explicit(&e->touch_ok[c], memory_order_acquire)) { + /* A chunk's RAW payloads are read through once, in order, when its + * first vector is viewed. A grouping that re-scans its input in + * waves then finds those pages still cached where memory is short: + * without this pass a 2 GB box read the near-unique two-key count + * (WatchID, ClientIP) half as much again from disk on every run. */ + const ray_enc_desc_t* descs = ray_enccol_descs(e, c); + int nv = (int)((chunk_rows(e, c) + RAY_ENC_VEC - 1) / RAY_ENC_VEC); + uint64_t acc = 0; + for (int v = 0; v < nv; v++) { + if (descs[v].encoding != RAY_ENC_RAW) continue; + const uint64_t* w = (const uint64_t*)(e->base + de.offset + descs[v].payload_off); + for (uint64_t i = 0; i < descs[v].payload_bytes / 8; i++) acc ^= w[i]; + } + static _Atomic(uint64_t) sink; /* keeps the reads; workers fold in at once */ + atomic_fetch_xor_explicit(&sink, acc, memory_order_relaxed); + atomic_store_explicit(&e->touch_ok[c], 1, memory_order_release); + } + return e->base + de.offset + d->payload_off; /* no bitmap: n_nulls == 0 */ +} + +/* The shared vector decode: straight into `out`, through the fast kernels + * or the reference decoders. An error (oom of a side entry, the FP + * environment) leaves `out` unwritten. */ +static ray_t* decode_vec(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, + void* out, char* pool_out, uint64_t pool_base, + uint64_t* produced, const uint32_t* dict_pool_off) { + *produced = 0; + if ((e->type == RAY_F32 || e->type == RAY_F64) && + d->encoding == RAY_ENC_ALP && !ray_enc_fp_env_ok()) + return ray_error("fpenv", "column %s: " RAY_ENC_FPENV_MSG, e->path); + int64_t rows = chunk_rows(e, c); + int vlen = (int)(rows - (int64_t)j * RAY_ENC_VEC < RAY_ENC_VEC ? rows - (int64_t)j * RAY_ENC_VEC : RAY_ENC_VEC); + const uint8_t* body = NULL; uint64_t avail = 0; const uint8_t* bm = NULL; + payload_parts(e, c, d, &body, &avail, &bm); + uint64_t pooled = 0; + const size_t nbytes = (size_t)vlen * ray_enccol_esz(e); + ray_t* err = NULL; + if (e->type == RAY_STR) + err = dec_str(e, d, vlen, body, avail, out, pool_out, pool_base, &pooled, dict_pool_off); + else if (!dec_fast(e, d, vlen, body, avail, bm, 0, out)) + err = dec_ref(e, d, vlen, body, avail, bm, out); + if (!err) *produced = (uint64_t)nbytes + pooled; + return err; +} + +void ray_enccol_note_decoded(ray_enccol_t* e, uint64_t nb) { + if (!nb) return; + atomic_fetch_add_explicit(&g_enc_decoded_bytes, nb, memory_order_relaxed); + atomic_fetch_add_explicit(&e->decoded_bytes, nb, memory_order_relaxed); /* per column */ +} + +ray_t* ray_enccol_decode_into(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, + void* out, char* pool_out, uint64_t pool_base, uint64_t* produced) { + return decode_vec(e, c, j, d, out, pool_out, pool_base, produced, NULL); +} + +int ray_enccol_decode_wide(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, + int8_t wide, void* out, uint64_t* produced) { + *produced = 0; + if ((wide != RAY_I64 && wide != RAY_F64) || !fk_int_type(e->type) || e->type == RAY_SYM || + ray_enccol_esz(e) == 8) + return 0; + int64_t rows = chunk_rows(e, c); + int vlen = (int)(rows - (int64_t)j * RAY_ENC_VEC < RAY_ENC_VEC ? rows - (int64_t)j * RAY_ENC_VEC : RAY_ENC_VEC); + const uint8_t* body = NULL; uint64_t avail = 0; const uint8_t* bm = NULL; + payload_parts(e, c, d, &body, &avail, &bm); + if (!dec_fast(e, d, vlen, body, avail, bm, wide, out)) return 0; + *produced = (uint64_t)vlen * ray_enccol_esz(e); /* counted as the generation-0 bytes */ + return 1; +} + +/* ---- Point reads: one row of a packed vector without decoding it ---- + * Value i of a packed body is lane i % L, row i / L (L = 1024 / T): its w + * bits start at bit (i / L) * w of the lane, in word (bit / T) * L + lane, + * continued in the lane's next word when they cross a T-bit boundary. + * The body is ray_enc_size_for(w) bytes, so every word read is inside it. */ +static uint64_t point_field(const uint8_t* pk, int T, int w, int i) { + if (w == 0) return 0; + const int L = RAY_ENC_VEC / T, bit = (i / L) * w, off = bit % T; + const size_t at = (size_t)(bit / T) * (size_t)L + (size_t)(i % L), tb = (size_t)T / 8; + uint64_t lo = 0, hi = 0; + memcpy(&lo, pk + at * tb, tb); /* little-endian: the low tb bytes */ + if (off + w > T) memcpy(&hi, pk + (at + (size_t)L) * tb, tb); + uint64_t v = lo >> off; + if (off + w > T) v |= hi << (T - off); + return w >= 64 ? v : v & ((1ull << w) - 1); +} + +/* Row i of a CONST / RLE body: its run's T-bit value into *x, the run + * found by binary search over the ends. Out of line: its 16 KB of run + * buffers stay off the FOR_BP / DICT point read's frame. */ +static __attribute__((noinline)) bool point_run(uint8_t enc, const uint8_t* p, int vlen, int i, + int T, uint64_t* x) { + if ((uintptr_t)p & 7) return false; + _Alignas(64) fk_vals_t vals, ends; + uint32_t nr; + if (!fk_runs(enc, vlen, p, T, &vals, &ends, &nr)) return false; + uint32_t lo = 0, hi = nr - 1; /* the first run whose end is above i */ + while (lo < hi) { + uint32_t mid = lo + (hi - lo) / 2; + if (ends.h[mid] > (uint32_t)i) hi = mid; else lo = mid + 1; + } + *x = fk_val(&vals, T, lo); + return true; +} + +/* Row i of vector body p (descriptor d, vlen rows) as its T-bit pattern: + * 1 served; 0 declined when the vector has nulls (the bitmap decides) or + * the codec is not FOR_BP, DICT over a FOR_BP code child, CONST or RLE, so + * the vector decode decides; -1 the dictionary's error (oom). */ +static int point_body(ray_enccol_t* e, const ray_enc_desc_t* d, const uint8_t* p, uint64_t avail, + int vlen, int i, ray_enc_kind_t k, uint64_t* x, ray_t** err) { + if (d->n_nulls) return 0; + const uint64_t m = k.T == 64 ? ~0ull : (1ull << k.T) - 1; + uint64_t v; + if (d->encoding == RAY_ENC_FOR_BP) { + uint64_t base; memcpy(&base, p, 8); + v = (base + point_field(p + 8, k.T, d->width, i)) & m; + } else if (d->encoding == RAY_ENC_DICT && d->width == 0) { + /* the codes child: an 8-byte header (encoding, width, reserved, + * body bytes), then a U32 FOR_BP body filling the payload */ + if (avail < 16 || p[0] != RAY_ENC_FOR_BP) return 0; + uint64_t base; memcpy(&base, p + 8, 8); + uint64_t code = (base + point_field(p + 16, 32, p[1], i)) & 0xffffffffull; + ray_enc_dict_t dict; + if ((*err = enc_dict(e, &dict)) != NULL) return -1; + v = dict.v[code] & m; + } else if ((d->encoding == RAY_ENC_CONST || d->encoding == RAY_ENC_RLE) && d->width == 0) { + if (!point_run(d->encoding, p, vlen, i, k.T, &v)) return 0; + v &= m; + } else { + return 0; + } + *x = v; + return 1; +} + +static bool point_type(const ray_enccol_t* e, ray_enc_kind_t* k) { + return fk_int_type(e->type) && e->type != RAY_SYM && ray_enc_kind_of(e->type, e->attrs, k); +} + +/* Row i of vector j of chunk c (descriptor d, body p of avail bytes) as + * its logical value: 1 served, 0 declined, -1 with *err. */ +static int point_read(ray_enccol_t* e, const ray_enc_desc_t* d, const uint8_t* p, uint64_t avail, + int vlen, int i, ray_enc_kind_t k, int64_t* out, ray_t** err) { + uint64_t x; + int r = point_body(e, d, p, avail, vlen, i, k, &x, err); + if (r != 1) return r; + *out = ray_enc_logical(x, k); + return 1; +} + +int ray_enccol_point_i64(ray_enccol_t* e, int64_t row, int64_t* out, ray_t** err) { + *err = NULL; + ray_enc_kind_t k; + if (e->kind != RAY_ENCCOL_SINGLE || row < 0 || row >= e->len || !point_type(e, &k)) return 0; + const int64_t c = row / RAY_ENC_CHUNK; + const int j = (int)(row % RAY_ENC_CHUNK / RAY_ENC_VEC), i = (int)(row % RAY_ENC_VEC); + const ray_enc_desc_t* d = &ray_enccol_descs(e, c)[j]; + ray_enc_dirent_t de; dirent_at(e, c, &de); + const int64_t rows = chunk_rows(e, c); + const int vlen = (int)(rows - (int64_t)j * RAY_ENC_VEC < RAY_ENC_VEC ? rows - (int64_t)j * RAY_ENC_VEC : RAY_ENC_VEC); + return point_read(e, d, e->base + de.offset + d->payload_off, d->payload_bytes, vlen, i, k, out, err); +} + +/* ---- Batched point reads: the rows of one vector, its body read once ---- + * The most rows of one vector a batched point read serves, per codec: + * past it one decode is the cheaper read (open decision D2, re-measured + * and extended per codec in Task 10b). Release microbenchmark over the + * 10M ClickBench store's vectors, warm: one cursor range read of a vector + * against one batched point read of N rows spread over it, as a fraction + * of the read (crossover: where it reaches 1): + * FOR_BP decode 140-420 ns N=16 0.30-0.77, N=32 0.47-1.33 -> RAY_ENC_VEC / 32 + * RLE decode 200-1100 ns N=32 0.68-1.20, N=64 0.99-1.91 -> RAY_ENC_VEC / 16 + * CONST decode ~100 ns N=8 0.79-0.86, N=16 1.18-1.33 -> RAY_ENC_VEC / 16, as + * ruled for runs (the warm crossover is ~10 rows; the group + * key reads pinned at 10-26 rows per vector rely on it) + * DICT decode 660-1350 ns N=64 0.30-0.61 -> RAY_ENC_VEC / 16 + * RAW, viewed a view, 34-38 ns N=1 1.05-1.26 -> declined + * with a bitmap decode 1.8-2.4 us N=64 0.17-0.25 (every codec) -> RAY_ENC_VEC / 16 + * SYM vectors took the same limits (FOR_BP N=32 0.52-0.55, RLE N=64 + * 1.01-1.87, CONST N=8 0.79, N=64 3.2). RAY_ENC_VEC / 16 is RAY_COL_POINT_ROWS, + * the most rows a caller hands one call. Structural ratios, not knobs. */ +#define PT_ROWS_FOR (RAY_ENC_VEC / 32) +#define PT_ROWS_RUNS (RAY_ENC_VEC / 16) +#define PT_ROWS_CONST (RAY_ENC_VEC / 16) +#define PT_ROWS_DICT (RAY_ENC_VEC / 16) +#define PT_ROWS_NULLS (RAY_ENC_VEC / 16) +_Static_assert(PT_ROWS_RUNS <= RAY_COL_POINT_ROWS && PT_ROWS_DICT <= RAY_COL_POINT_ROWS && + PT_ROWS_NULLS <= RAY_COL_POINT_ROWS && PT_ROWS_FOR <= RAY_COL_POINT_ROWS && + PT_ROWS_CONST <= RAY_COL_POINT_ROWS, + "a codec's point-read limit is at most the caller's batch"); + +/* One vector's point-read context: its kind, the bitmap (NULL: the vector + * has none) and whether it is SYM. */ +typedef struct { + const ray_enccol_t* e; + const uint8_t* bm; /* the null bitmap, or NULL */ + uint8_t* nul; /* the caller's null flags (NULL: none taken) */ + ray_enc_kind_t k; + uint64_t m; /* the lane mask */ + bool sym; +} pt_ctx_t; + +/* Row i (output q) in the bitmap: a null, flagged; nothing else of the row + * is read (a null slot's value or code may be anything the writer chose). */ +static inline __attribute__((always_inline)) bool pt_null(const pt_ctx_t* t, int i, int64_t q, int64_t* out) { + if (!t->bm || !((t->bm[i >> 3] >> (i & 7)) & 1)) return false; + t->nul[q] = 1; + out[q] = 0; + return true; +} + +/* The T-bit pattern x of a row outside the bitmap as its logical value + * (SYM ids as themselves, id 0 the in-band null). */ +static inline __attribute__((always_inline)) void pt_val(const pt_ctx_t* t, uint64_t x, int64_t q, int64_t* out) { + const int sh = 64 - t->k.T; + out[q] = !t->sym && t->k.is_signed ? (int64_t)(x << sh) >> sh : (int64_t)x; +} + +/* Rows of one CONST / RLE vector (local rows rows[q] - base, ascending) + * read off its runs: the runs read once (fk_runs), each row's run found + * by advancing over the ends. Out of line, as point_run. 1 / 0. */ +static __attribute__((noinline)) int points_runs(const pt_ctx_t* t, uint8_t enc, const uint8_t* p, int vlen, + const int64_t* rows, int64_t n, int64_t base, int64_t* out) { + if ((uintptr_t)p & 7) return 0; + _Alignas(64) fk_vals_t vals, ends; + uint32_t nr; + if (!fk_runs(enc, vlen, p, t->k.T, &vals, &ends, &nr)) return 0; + uint32_t r = 0; + for (int64_t q = 0; q < n; q++) { + const int64_t i = rows[q] - base; + if (pt_null(t, (int)i, q, out)) continue; + while (r + 1 < nr && ends.h[r] <= (uint32_t)i) r++; + pt_val(t, fk_val(&vals, t->k.T, r) & t->m, q, out); + } + return 1; +} + +/* point_field at a fixed lane width UT: L = 1024 / T lanes (LS = log2 L, + * TS = log2 T), the divisions as shifts and masks, fixed-size loads. */ +#define PT_FIELD(NAME, UT, LS, TS) \ +static inline __attribute__((always_inline)) uint64_t NAME(const UT* lanes, int w, uint64_t wm, int i) { \ + const int T = 8 * (int)sizeof(UT); \ + const int bit = (i >> (LS)) * w, off = bit & (T - 1); \ + const size_t at = (size_t)(bit >> (TS)) * ((size_t)1 << (LS)) + (size_t)(i & ((1 << (LS)) - 1)); \ + UT lo, hi; \ + memcpy(&lo, lanes + at, sizeof lo); \ + uint64_t f = (uint64_t)lo >> off; \ + if (off + w > T) { memcpy(&hi, lanes + at + ((size_t)1 << (LS)), sizeof hi); f |= (uint64_t)hi << (T - off); } \ + return f & wm; \ +} +PT_FIELD(pt_field8, uint8_t, 7, 3) +PT_FIELD(pt_field16, uint16_t, 6, 4) +PT_FIELD(pt_field32, uint32_t, 5, 5) +PT_FIELD(pt_field64, uint64_t, 4, 6) +#undef PT_FIELD + +/* Rows of one FOR_BP vector: the lane arithmetic per row. */ +static void points_for(const pt_ctx_t* t, int w, const uint8_t* p, const int64_t* rows, int64_t n, + int64_t base, int64_t* out) { + const int T = t->k.T; + uint64_t fb; memcpy(&fb, p, 8); + const uint8_t* pk = p + 8; + const uint64_t wm = w >= 64 ? ~0ull : (1ull << w) - 1; +#define FOR_POINTS(UT, FIELD) do { \ + const UT* lanes = (const UT*)(const void*)pk; \ + for (int64_t q = 0; q < n; q++) { \ + const int i = (int)(rows[q] - base); \ + if (pt_null(t, i, q, out)) continue; \ + const uint64_t f = w ? FIELD(lanes, w, wm, i) : 0; \ + pt_val(t, (fb + f) & t->m, q, out); \ + } \ + } while (0) + switch (T) { + case 8: FOR_POINTS(uint8_t, pt_field8); break; + case 16: FOR_POINTS(uint16_t, pt_field16); break; + case 32: FOR_POINTS(uint32_t, pt_field32); break; + default: FOR_POINTS(uint64_t, pt_field64); break; + } +#undef FOR_POINTS +} + +/* Rows of one DICT vector over a U32 FOR_BP code child: the dictionary + * loaded (once per column, its oom -1), then per row the code unpacked at + * its lane and its entry read. 0: another code child (the decode reads + * it). */ +static int points_dict(const pt_ctx_t* t, ray_enccol_t* e, const uint8_t* p, uint64_t avail, const int64_t* rows, + int64_t n, int64_t base, int64_t* out, ray_t** err) { + if (avail < 16 || p[0] != RAY_ENC_FOR_BP) return 0; + const int w = p[1]; + uint64_t cb; memcpy(&cb, p + 8, 8); + ray_enc_dict_t dict; + if ((*err = enc_dict(e, &dict)) != NULL) return -1; + const uint32_t* lanes = (const uint32_t*)(const void*)(p + 16); + const uint64_t wm = w >= 64 ? ~0ull : (1ull << w) - 1; + for (int64_t q = 0; q < n; q++) { + const int i = (int)(rows[q] - base); + if (pt_null(t, i, q, out)) continue; + const uint64_t code = (cb + (w ? pt_field32(lanes, w, wm, i) : 0)) & 0xffffffffull; + pt_val(t, dict.v[code] & t->m, q, out); + } + return 1; +} + +/* Rows of one RAW vector with a bitmap: each row's T-bit element. */ +static void points_raw(const pt_ctx_t* t, const uint8_t* p, const int64_t* rows, int64_t n, + int64_t base, int64_t* out) { + const size_t tb = (size_t)t->k.T / 8; + for (int64_t q = 0; q < n; q++) { + const int i = (int)(rows[q] - base); + if (pt_null(t, i, q, out)) continue; + uint64_t x = 0; + memcpy(&x, p + (size_t)i * tb, tb); /* little-endian: the low tb bytes */ + pt_val(t, x, q, out); + } +} + +/* ray_enccol_points_i64 and ray_enccol_gather_points: nul NULL declines + * SYM and vectors with a null bitmap, else both are served (nul[q] set for + * a bitmap row). */ +static int points_core(ray_enccol_t* e, const int64_t* rows, int64_t n, int64_t base, int64_t* out, uint8_t* nul, + ray_t** err) { + *err = NULL; + ray_enc_kind_t k; + if (n <= 0 || e->kind != RAY_ENCCOL_SINGLE || !fk_int_type(e->type) || !ray_enc_kind_of(e->type, e->attrs, &k)) + return 0; + const bool sym = e->type == RAY_SYM; + if (sym && !nul) return 0; /* ids only to a caller that takes them */ + const int64_t r0 = rows[0] - base; + if (r0 < 0 || r0 >= e->len) return 0; + const int64_t c = r0 / RAY_ENC_CHUNK; + const int j = (int)(r0 % RAY_ENC_CHUNK / RAY_ENC_VEC); + const int64_t vs = c * RAY_ENC_CHUNK + (int64_t)j * RAY_ENC_VEC; + const int64_t rows_c = chunk_rows(e, c); + const int vlen = (int)(rows_c - (int64_t)j * RAY_ENC_VEC < RAY_ENC_VEC ? rows_c - (int64_t)j * RAY_ENC_VEC : RAY_ENC_VEC); + for (int64_t q = 0; q < n; q++) /* one vector, ascending: the caller's contract */ + if (rows[q] - base < vs || rows[q] - base >= vs + vlen || (q && rows[q] < rows[q - 1])) return 0; + const ray_enc_desc_t* d = &ray_enccol_descs(e, c)[j]; + ray_enc_dirent_t de; dirent_at(e, c, &de); + const uint8_t* p = e->base + de.offset + d->payload_off; + uint64_t avail = d->payload_bytes; + pt_ctx_t t = { .e = e, .bm = NULL, .nul = nul, .k = k, + .m = k.T == 64 ? ~0ull : (1ull << k.T) - 1, .sym = sym }; + if (d->n_nulls && !sym) { + if (!nul || !ray_enc_has_bitmap(e->type)) return 0; + t.bm = p; p += 128; avail -= 128; + } + /* the codec's limit (above): a vector with a bitmap decodes through + * the merge, so its point reads win up to the caller's batch */ + const bool bm = t.bm != NULL; + const int64_t vb = base + vs; + switch (d->encoding) { + case RAY_ENC_CONST: + if (d->width || n > (bm ? PT_ROWS_NULLS : PT_ROWS_CONST)) return 0; + break; + case RAY_ENC_RLE: + if (d->width || n > (bm ? PT_ROWS_NULLS : PT_ROWS_RUNS)) return 0; + break; + case RAY_ENC_FOR_BP: + if (n > (bm ? PT_ROWS_NULLS : PT_ROWS_FOR)) return 0; + break; + case RAY_ENC_DICT: + if (d->width || n > (bm ? PT_ROWS_NULLS : PT_ROWS_DICT)) return 0; + break; + case RAY_ENC_RAW: + /* without a bitmap the in-place view is the cheaper read */ + if (!bm || n > PT_ROWS_NULLS) return 0; + break; + default: + return 0; /* DELTA_BP and the rest: the decode */ + } + if (nul) memset(nul, 0, (size_t)n); + switch (d->encoding) { + case RAY_ENC_CONST: case RAY_ENC_RLE: return points_runs(&t, d->encoding, p, vlen, rows, n, vb, out); + case RAY_ENC_FOR_BP: points_for(&t, d->width, p, rows, n, vb, out); return 1; + case RAY_ENC_DICT: return points_dict(&t, e, p, avail, rows, n, vb, out, err); + default: points_raw(&t, p, rows, n, vb, out); return 1; + } +} + +int ray_enccol_points_i64(ray_enccol_t* e, const int64_t* rows, int64_t n, int64_t base, int64_t* out, ray_t** err) { + return points_core(e, rows, n, base, out, NULL, err); +} + +int ray_enccol_gather_points(ray_enccol_t* e, const int64_t* rows, int64_t n, int64_t base, int64_t* out, + uint8_t* nul, ray_t** err) { + return points_core(e, rows, n, base, out, nul, err); +} + +/* ---- Encoded vector views: a body parsed, never expanded ---- + * A view is built for CONST, RLE, FOR_BP and DICT (over a U32 FOR_BP code + * child) integer bodies, CONST, RLE and DICT float bodies and STR_DICT + * codes; on any other shape it declines and the caller's range read + * decodes the vector. The writer's base of a FOR_BP body is the vector + * minimum, so its residuals compare in logical order. */ + +void ray_enccol_unpack_resid(const ray_enc_vview_t* v, void* out) { + switch (v->k.T) { + case 8: fk_for8 ((const uint8_t*) v->packed, v->width, 0, (uint8_t*) out, v->n); break; + case 16: fk_for16((const uint16_t*)v->packed, v->width, 0, (uint16_t*)out, v->n); break; + case 32: fk_for32((const uint32_t*)v->packed, v->width, 0, (uint32_t*)out, v->n); break; + default: fk_for64((const uint64_t*)v->packed, v->width, 0, (uint64_t*)out, v->n); break; + } +} + +/* Fused unpack-and-compare (perf fix 6): rows of n packed fields that + * compare true (unsigned, at the lane width) against t, never storing + * the fields. FK_FOR's row walk with the store replaced by a count. */ +#define FK_CNT_ROW(UT, CMP, V) do { for (int l = 0; l < nl; l++) { const UT v_ = (V); acc += (uint32_t)(v_ CMP t); } } while (0) +#define FK_CNT(NAME, UT, PT, TB, CMP) \ +static uint32_t NAME(const UT* restrict in, int w, UT t, int n) { \ + enum { L = RAY_ENC_VEC / TB }; \ + const UT m = w >= TB ? (UT)~(UT)0 : (UT)(((PT)1 << w) - 1); \ + uint32_t acc = 0; \ + for (int r = 0, bit = 0; r * L < n; r++, bit += w) { \ + const int k = bit / TB, off = bit % TB; \ + const unsigned sr = (unsigned)off & (TB - 1), sl = (unsigned)(TB - off) & (TB - 1); \ + const int nl = n - r * L < L ? n - r * L : L; \ + const UT* a = in + (size_t)k * L; \ + if (w == 0) FK_CNT_ROW(UT, CMP, (UT)0); \ + else if (off + w > TB) FK_CNT_ROW(UT, CMP, FK_FIELD2(UT, PT, L, a, l, sr, sl, m)); \ + else FK_CNT_ROW(UT, CMP, FK_FIELD1(UT, PT, a, l, sr, m)); \ + } \ + return acc; \ +} +#define FK_CNT_OPS(T, UT, PT) FK_CNT(fk_cnt##T##_eq, UT, PT, T, ==) FK_CNT(fk_cnt##T##_ne, UT, PT, T, !=) \ + FK_CNT(fk_cnt##T##_lt, UT, PT, T, <) FK_CNT(fk_cnt##T##_le, UT, PT, T, <=) \ + FK_CNT(fk_cnt##T##_gt, UT, PT, T, >) FK_CNT(fk_cnt##T##_ge, UT, PT, T, >=) +FK_CNT_OPS(8, uint8_t, unsigned) +FK_CNT_OPS(16, uint16_t, unsigned) +FK_CNT_OPS(32, uint32_t, unsigned) +FK_CNT_OPS(64, uint64_t, uint64_t) +#define FK_CNT_CALL(T, UT) switch (op) { \ + case OP_EQ: return fk_cnt##T##_eq((const UT*)v->packed, v->width, (UT)t, v->n); \ + case OP_NE: return fk_cnt##T##_ne((const UT*)v->packed, v->width, (UT)t, v->n); \ + case OP_LT: return fk_cnt##T##_lt((const UT*)v->packed, v->width, (UT)t, v->n); \ + case OP_LE: return fk_cnt##T##_le((const UT*)v->packed, v->width, (UT)t, v->n); \ + case OP_GT: return fk_cnt##T##_gt((const UT*)v->packed, v->width, (UT)t, v->n); \ + default: return fk_cnt##T##_ge((const UT*)v->packed, v->width, (UT)t, v->n); } +uint32_t ray_enccol_count_resid(const ray_enc_vview_t* v, uint16_t op, uint64_t t) { + switch (v->k.T) { + case 8: FK_CNT_CALL(8, uint8_t); + case 16: FK_CNT_CALL(16, uint16_t); + case 32: FK_CNT_CALL(32, uint32_t); + default: FK_CNT_CALL(64, uint64_t); + } +} +#undef FK_CNT_CALL +#undef FK_CNT_OPS +#undef FK_CNT +#undef FK_CNT_ROW + +/* The U32 FOR_BP code child spanning the DICT body (its encoding byte + * checked by the caller): the codes unpacked into v->codes. Shared by the + * integer and float DICT views. */ +static void vview_codes_for(const uint8_t* body, ray_enc_vview_t* v) { + uint64_t base; memcpy(&base, body + 8, 8); + fk_for32((const uint32_t*)(body + 16), body[1], (uint32_t)base, v->codes, v->n); +} + +/* A STR_DICT vector's view: the codes (a U32 FOR_BP child through + * vview_codes_for, any other code child through ray_enc_strdict_read). No + * entry is read, no byte decoded or counted. */ +static int vview_str_dict(ray_enccol_t* e, const uint8_t* body, uint64_t avail, ray_enc_vview_t* v, ray_t** err) { + const ray_enc_sdict_t* sd; + if ((*err = ray_enccol_strdict(e, &sd)) != NULL) return -1; /* read once per column */ + if (avail >= 16 && body[0] == RAY_ENC_FOR_BP) { + vview_codes_for(body, v); + } else { + uint64_t codes[RAY_ENC_VEC]; + ray_enc_strdict_read(body, (size_t)avail, v->n, codes); + for (int i = 0; i < v->n; i++) v->codes[i] = (uint32_t)codes[i]; + } + v->dict_n = sd->n; + return 1; +} + +/* Vector vec of a float column as a view: CONST, RLE (RAW values) and DICT + * over a FOR_BP code child; anything else declines (the caller decodes). */ +static int vview_float(ray_enccol_t* e, const ray_enc_desc_t* d, const uint8_t* body, uint64_t avail, + ray_enc_vview_t* v, ray_t** err) { + if (d->width) return 0; + const int T = v->k.T; + switch (d->encoding) { + case RAY_ENC_CONST: + if (!fk_runs(RAY_ENC_CONST, v->n, body, T, &v->run_vals, &v->run_ends, &v->n_runs)) return 0; + v->cbits = T == 32 ? v->run_vals.s[0] : v->run_vals.q[0]; + return 1; + case RAY_ENC_RLE: + if (avail < 16 || body[8] != RAY_ENC_RAW) return 0; + return fk_runs(RAY_ENC_RLE, v->n, body, T, &v->run_vals, &v->run_ends, &v->n_runs) ? 1 : 0; + case RAY_ENC_DICT: { + if (avail < 16 || body[0] != RAY_ENC_FOR_BP) return 0; + ray_enc_dict_t dict; + if ((*err = enc_dict(e, &dict)) != NULL) return -1; /* read once per column */ + vview_codes_for(body, v); + v->dict = dict.v; v->dict_n = dict.n; + return 1; + } + default: return 0; + } +} + +int ray_enccol_vview(ray_enccol_t* e, int64_t vec, ray_enc_vview_t* v, ray_t** err) { + *err = NULL; + if (vec < 0 || vec >= ray_enc_nvecs(e->len) || e->kind != RAY_ENCCOL_SINGLE || e->synthetic) return 0; + const int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + const int j = (int)(vec % RAY_ENC_VECS_PER_CHUNK); + const ray_enc_desc_t* d = &ray_enccol_descs(e, c)[j]; + const int n = ray_enc_vec_len(e->len, vec); + const bool fl = enc_type_float(e->type); + if (d->flags & RAY_ENC_DESC_TRAILER) return 0; /* floats only: decline (D6) */ + const bool str = e->type == RAY_STR; + if (str) { + if (d->encoding != RAY_ENC_STR_DICT) return 0; /* RAW, CONST, FSST: decode */ + v->k = (ray_enc_kind_t){ 32, false, false }; /* the codes */ + } else if (fl) { + if (d->encoding != RAY_ENC_CONST && d->encoding != RAY_ENC_RLE && d->encoding != RAY_ENC_DICT) return 0; + if (!ray_enc_value_kind(e->type, e->attrs, &v->k)) return 0; /* { 32 | 64, unsigned, float } */ + } else { + if (!fk_int_type(e->type) || !ray_enc_kind_of(e->type, e->attrs, &v->k)) return 0; + if (d->encoding != RAY_ENC_CONST && d->encoding != RAY_ENC_FOR_BP && + d->encoding != RAY_ENC_RLE && d->encoding != RAY_ENC_DICT) return 0; + } + const uint8_t* body; uint64_t avail; const uint8_t* bm; + payload_parts(e, c, d, &body, &avail, &bm); + if ((uintptr_t)body & 7) return 0; + v->enc = d->encoding; v->n = n; v->n_nulls = d->n_nulls; v->nullmap = bm; v->type = e->type; + v->cbits = 0; v->base = 0; v->width = 0; v->packed = NULL; + v->n_runs = 0; v->dict = NULL; v->dict_n = 0; + if (str) return vview_str_dict(e, body, avail, v, err); /* nulls in band: no bitmap */ + if (fl) return vview_float(e, d, body, avail, v, err); + const int T = v->k.T; + switch (d->encoding) { + case RAY_ENC_CONST: case RAY_ENC_RLE: + if (d->width) return 0; + if (!fk_runs(d->encoding, n, body, T, &v->run_vals, &v->run_ends, &v->n_runs)) return 0; + if (d->encoding == RAY_ENC_CONST) v->cbits = fk_val(&v->run_vals, T, 0); + return 1; + case RAY_ENC_FOR_BP: { + uint64_t base; memcpy(&base, body, 8); + v->base = base; v->width = d->width; v->packed = body + 8; + return 1; + } + case RAY_ENC_DICT: { + if (d->width || !v->k.is_signed || e->type == RAY_SYM || avail < 16 || body[0] != RAY_ENC_FOR_BP) return 0; + ray_enc_dict_t dict; + if ((*err = enc_dict(e, &dict)) != NULL) return -1; /* read once per column */ + vview_codes_for(body, v); + v->dict = dict.v; v->dict_n = dict.n; + return 1; + } + default: + return 0; + } +} + +/* A stand-in column of `type` for the body hooks; with a VALUE_DICT of + * dict[0, n_dict) (T-bit patterns). */ +static ray_enccol_t* test_col(int8_t type, uint8_t attrs, const uint64_t* dict, uint32_t n_dict) { + ray_enccol_t* e = ray_calloc_raw(sizeof *e); + if (!e) return NULL; + e->type = type; e->attrs = attrs; + snprintf(e->path, sizeof e->path, "decode_body"); + ray_enc_once_init(&e->dict_once); + ray_enc_kind_t k; + if (dict && ray_enc_value_kind(type, attrs, &k)) { /* floats: their F32 / F64 patterns */ + size_t esz = (size_t)k.T / 8, len = 8 + (size_t)ray_enc_pad8((uint64_t)n_dict * esz); + uint8_t* b = ray_calloc_raw(len); + if (!b) { ray_free_raw(e); return NULL; } + memcpy(b, &n_dict, 4); + for (uint32_t i = 0; i < n_dict; i++) memcpy(b + 8 + i * esz, &dict[i], esz); + e->base = b; + e->vdict_off = 0; + e->vdict_len = len; + } + return e; +} +static void test_col_free(ray_enccol_t* e) { + if (e->dict) ray_release(e->dict); + ray_free_raw((void*)e->base); + ray_free_raw(e); +} + +/* The kernels read a published dictionary only: publish it first. */ +static void test_col_dict(ray_enccol_t* e) { + ray_enc_dict_t dd; + ray_t* err = enc_dict(e, &dd); + if (err) ray_error_free(err); +} + +int ray_enccol_test_point_body(int8_t type, const uint64_t* dict, uint32_t n_dict, uint8_t enc, + uint8_t width, int n_nulls, const uint8_t* body, uint64_t avail, + int vlen, int64_t* out, int8_t* res) { + ray_enccol_t* e = test_col(type, 0, dict, n_dict); + if (!e) return -1; + ray_enc_desc_t d; memset(&d, 0, sizeof d); + d.encoding = enc; d.width = width; d.n_nulls = (uint16_t)n_nulls; + d.flags = RAY_ENC_STAT_ABSENT; + ray_enc_kind_t k; + const bool ok = point_type(e, &k); + for (int i = 0; i < vlen; i++) { + ray_t* err = NULL; + int64_t v = 0; + res[i] = ok ? (int8_t)point_read(e, &d, body, avail, vlen, i, k, &v, &err) : 0; + if (res[i] == 1) out[i] = v; + if (err) ray_error_free(err); + } + test_col_free(e); + return 0; +} + +static int test_decode(ray_enccol_t* e, uint8_t enc, uint8_t width, int n_nulls, const uint8_t* bm, + const uint8_t* body, uint64_t avail, int vlen, bool fast, int8_t wide, void* out) { + ray_enc_desc_t d; memset(&d, 0, sizeof d); + d.encoding = enc; d.width = width; d.n_nulls = (uint16_t)n_nulls; + d.flags = RAY_ENC_STAT_ABSENT; + if (fast) return dec_fast(e, &d, vlen, body, avail, bm, wide, out); + if (wide) return -1; + ray_t* err = dec_ints(e, &d, vlen, body, avail, bm, out); + if (err) ray_error_free(err); + return err ? -1 : 1; +} + +int ray_enccol_test_decode_body(int8_t type, uint8_t attrs, uint8_t enc, + uint8_t width, int n_nulls, const uint8_t* bm, const uint8_t* body, + uint64_t avail, int vlen, bool fast, int8_t wide, void* out) { + ray_enccol_t* e = test_col(type, attrs, NULL, 0); + if (!e) return -1; + int r = test_decode(e, enc, width, n_nulls, bm, body, avail, vlen, fast, wide, out); + test_col_free(e); + return r; +} + +int ray_enccol_test_decode_float(int8_t type, const uint64_t* dict, uint32_t n_dict, uint8_t enc, int n_nulls, + const uint8_t* bm, const uint8_t* body, uint64_t avail, int vlen, + bool fast, void* out) { + if (!enc_type_float(type)) return -1; + ray_enccol_t* e = test_col(type, 0, dict, n_dict); + if (!e) return -1; + if (dict && fast) test_col_dict(e); + ray_enc_desc_t d; memset(&d, 0, sizeof d); + d.encoding = enc; d.n_nulls = (uint16_t)n_nulls; + d.flags = RAY_ENC_STAT_ABSENT; + int r; + if (fast) r = dec_fast(e, &d, vlen, body, avail, bm, 0, out); + else { + ray_t* err = dec_floats(e, &d, vlen, body, avail, bm, out); + if (err) ray_error_free(err); + r = err ? -1 : 1; + } + test_col_free(e); + return r; +} + +int ray_enccol_test_decode_dict(int8_t type, const uint64_t* dict, uint32_t n_dict, + int n_nulls, const uint8_t* bm, const uint8_t* body, uint64_t avail, + int vlen, bool fast, void* out) { + ray_enccol_t* e = test_col(type, 0, dict, n_dict); + if (!e) return -1; + if (fast) test_col_dict(e); + int r = test_decode(e, RAY_ENC_DICT, 0, n_nulls, bm, body, avail, vlen, fast, 0, out); + test_col_free(e); + return r; +} + +ray_t* ray_enccol_desc_pool_bytes(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, uint64_t* out) { + *out = 0; + if (e->type != RAY_STR) return NULL; + int64_t rows = chunk_rows(e, c); + int vlen = (int)(rows - (int64_t)j * RAY_ENC_VEC < RAY_ENC_VEC ? rows - (int64_t)j * RAY_ENC_VEC : RAY_ENC_VEC); + const uint8_t* body = NULL; uint64_t avail = 0; const uint8_t* bm = NULL; + payload_parts(e, c, d, &body, &avail, &bm); + return dec_str(e, d, vlen, body, avail, NULL, NULL, 0, out, NULL); /* vector scope */ +} + +ray_t* ray_enccol_decode_vec(ray_enccol_t* e, int64_t vec, void* out, char* pool_out, uint64_t pool_base) { + if (vec < 0 || vec >= ray_enc_nvecs(e->len)) return ray_error("range", "column %s: vector %lld", e->path, (long long)vec); + int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + int j = (int)(vec % RAY_ENC_VECS_PER_CHUNK); + uint64_t nb; + ray_t* err = decode_vec(e, c, j, &ray_enccol_descs(e, c)[j], out, pool_out, pool_base, &nb, NULL); + if (!err) ray_enccol_note_decoded(e, nb); + return err; +} + +ray_t* ray_enccol_vec_pool_bytes(ray_enccol_t* e, int64_t vec, uint64_t* out) { + *out = 0; + if (vec < 0 || vec >= ray_enc_nvecs(e->len)) return ray_error("range", "column %s: vector %lld", e->path, (long long)vec); + int64_t c = vec / RAY_ENC_VECS_PER_CHUNK; + int j = (int)(vec % RAY_ENC_VECS_PER_CHUNK); + return ray_enccol_desc_pool_bytes(e, c, j, &ray_enccol_descs(e, c)[j], out); +} + +/* ---- Single-column materialization (spec "Materialized equivalence") ---- */ + +typedef struct { ray_enc_snap_t snap; bool failed; bool done; } enc_task_res_t; + +typedef struct { + ray_enccol_t* e; + uint8_t* out; + char* pool; + const uint64_t* chunk_pool; /* STR: decoded-pool base of each chunk */ + const uint32_t* dict_pool_off; /* STR with a STR_DICT entry: each code's offset in the + * dictionary region (UINT32_MAX: inline entry) */ + enc_task_res_t* res; /* one attempt result per chunk (task) */ + _Atomic(int64_t) lowest_failed; /* lowest failed chunk so far (INT64_MAX: none) */ +} enc_mat_ctx_t; + +static _Atomic(int64_t) g_interrupt_after; /* test hook, see enccol.h */ +void ray_enccol_test_interrupt_after(int64_t nth) { atomic_store(&g_interrupt_after, nth); } + +/* One task per chunk. Every failure, cancellation included, goes into the + * task's own fixed-size result from this thread's state; the coordinator + * picks the lowest failing chunk. */ +static void enc_mat_chunk(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + enc_mat_ctx_t* x = raw; + ray_enccol_t* e = x->e; + uint8_t esz = ray_enccol_esz(e); + for (int64_t c = start; c < end; c++) { + enc_task_res_t* r = &x->res[c]; + /* Once a chunk has failed, chunks above it cannot change the + * reported (lowest) failure: stop decoding them. Lower chunks + * still run, so the result stays deterministic. */ + if (c > atomic_load_explicit(&x->lowest_failed, memory_order_relaxed)) continue; + if (ray_interrupted()) { + ray_enc_snap_set(&r->snap, "cancel", "column %s: interrupted", e->path); + r->failed = true; + continue; + } + const ray_enc_desc_t* descs = ray_enccol_descs(e, c); + ray_t* err = NULL; + int64_t rows = chunk_rows(e, c); + int nv = (int)((rows + RAY_ENC_VEC - 1) / RAY_ENC_VEC); + uint64_t pbase = x->chunk_pool ? x->chunk_pool[c] : 0; + uint64_t produced = 0; /* counted once per chunk */ + for (int j = 0; !err && j < nv; j++) { + int64_t row = c * RAY_ENC_CHUNK + (int64_t)j * RAY_ENC_VEC; + uint8_t* dst = x->out + (size_t)row * esz; /* private until published */ + uint64_t nb = 0; + /* ray_enccol_decode_into with the dictionary region's offsets */ + err = decode_vec(e, c, j, &descs[j], dst, x->pool, pbase, &nb, x->dict_pool_off); + produced += nb; + if (!err && e->type == RAY_STR) { + int vlen = ray_enc_vec_len(e->len, row / RAY_ENC_VEC); + ray_str_t* s = (ray_str_t*)dst; + /* the vector's own pool bytes: a STR_DICT vector's rows point + * into the dictionary region and add none (its nb is its + * descriptors' bytes only), so the pool advances only over + * RAW, CONST and FSST vectors, as the prepass counted them */ + pbase += nb - (uint64_t)vlen * esz; + for (int i = 0; i < vlen; i++) { + if (ray_str_is_inline(&s[i])) continue; + /* the generation-0 rule (col_str_region), computed + * whatever the decoder left in the field */ + uint32_t h = (uint32_t)ray_str_t_hash(&s[i], x->pool); + s[i].hash32 = h != 0 ? h : 1u; + } + } + } + ray_enccol_note_decoded(e, produced); + if (err) { ray_enc_snap_take(&r->snap, err); r->failed = true; } + if (r->failed) { + int64_t cur = atomic_load_explicit(&x->lowest_failed, memory_order_relaxed); + while (c < cur && !atomic_compare_exchange_weak_explicit(&x->lowest_failed, &cur, c, + memory_order_relaxed, memory_order_relaxed)) {} + } else { + int64_t k = atomic_load_explicit(&g_interrupt_after, memory_order_relaxed); + while (k > 0 && !atomic_compare_exchange_weak(&g_interrupt_after, &k, k - 1)) {} + r->done = true; + if (k == 1) ray_request_interrupt(); + } + } +} + +/* STR column-scope pass (spec "STR pool"): the decoded pool is the + * dictionary's entries over 12 bytes once, in code order (sd, the STR_DICT + * entry, or NULL), then every RAW / CONST / FSST vector's pooled bytes in + * row order; STR_DICT vectors share the dictionary region and add none. + * chunk_pool[c] is where chunk c's pooled bytes start. */ +static ray_t* enc_str_prepass(ray_enccol_t* e, uint64_t* chunk_pool, const ray_enc_sdict_t* sd) { + uint64_t total = sd ? sd->pooled : 0; /* rule 1: the dictionary region first */ + for (int64_t c = 0; c < e->n_chunks; c++) { + const ray_enc_desc_t* descs = ray_enccol_descs(e, c); + chunk_pool[c] = total; + int nv = (int)((chunk_rows(e, c) + RAY_ENC_VEC - 1) / RAY_ENC_VEC); + for (int j = 0; j < nv; j++) { + if (descs[j].encoding == RAY_ENC_STR_DICT) continue; /* rows in the dictionary region */ + uint64_t pb; + ray_t* err = ray_enccol_desc_pool_bytes(e, c, j, &descs[j], &pb); + if (err) return err; + total += pb; + } + } + return NULL; +} + +static _Atomic(bool) g_fail_index_parse; +void ray_enccol_test_fail_index_parse(bool on) { atomic_store(&g_fail_index_parse, on); } + +static double dbl_of(int64_t b) { double d; memcpy(&d, &b, 8); return d; } + +/* ZONE: combined min/max (first of ties wins, row order) and null count; + * 0/0 when no value (zone_scan_int / zone_scan_float, src/ops/idxop.c). */ +static ray_t* enc_synth_zone(ray_enccol_t* e) { + ray_t* root = enc_alloc_fails(e) ? NULL : ray_index_new_root(RAY_IDX_ZONE, e->type, e->len); + if (!root || RAY_IS_ERR(root)) return root ? root : ray_error("oom", "column %s: zone", e->path); + ray_index_t* ix = ray_index_payload(root); + bool fl = enc_type_float(e->type), have = false; + int64_t mn = 0, mx = 0; + for (int64_t c = 0; c < e->n_chunks; c++) { + ray_enc_dirent_t de; dirent_at(e, c, &de); + if ((de.flags & RAY_ENC_STAT_ABSENT) || e->type == RAY_STR) continue; /* STR: code bounds, no order */ + bool lt = fl ? dbl_of(de.min) < dbl_of(mn) : de.min < mn; + bool gt = fl ? dbl_of(de.max) > dbl_of(mx) : de.max > mx; + if (!have || lt) mn = de.min; + if (!have || gt) mx = de.max; + have = true; + } + if (fl) { ix->u.zone.min_f = have ? dbl_of(mn) : 0.0; ix->u.zone.max_f = have ? dbl_of(mx) : 0.0; } + else { ix->u.zone.min_i = have ? mn : 0; ix->u.zone.max_i = have ? mx : 0; } + ix->u.zone.n_nulls = e->null_count; + return root; +} + +/* CHUNK_ZONE at chunk_log2 16 (the builder default) from the directory; + * all-null chunks keep the builder's empty extrema (INT64_MAX / INT64_MIN, + * +inf / -inf); aggs [sum_lo | non-null rows | sum_hi] only for the types + * whose directory carries sums (ray_encw_type_summable), NULL otherwise + * (readers accept a NULL aggs). */ +static ray_t* enc_synth_chunk_zone(ray_enccol_t* e) { + ray_t* root = enc_alloc_fails(e) ? NULL : ray_index_new_root(RAY_IDX_CHUNK_ZONE, e->type, e->len); + if (!root || RAY_IS_ERR(root)) return root ? root : ray_error("oom", "column %s: chunk zone", e->path); + ray_index_t* ix = ray_index_payload(root); + uint32_t nc = (uint32_t)e->n_chunks; + bool fl = enc_type_float(e->type); + bool sums = ray_encw_type_summable(e->type); + ix->u.chunk_zone.n_chunks = nc; + ix->u.chunk_zone.chunk_log2 = 16; + ix->u.chunk_zone.is_f64 = fl ? 1 : 0; + ray_t* mins = ray_vec_new(fl ? RAY_F64 : RAY_I64, nc); + ray_t* maxs = ray_vec_new(fl ? RAY_F64 : RAY_I64, nc); + ray_t* nb = ray_vec_new(RAY_U8, (nc + 7) / 8); + ray_t* aggs = sums ? ray_vec_new(RAY_I64, 3 * (int64_t)nc) : NULL; + /* Stored before any check so ray_release(root) frees what exists. */ + ix->u.chunk_zone.mins = (mins && !RAY_IS_ERR(mins)) ? mins : NULL; + ix->u.chunk_zone.maxs = (maxs && !RAY_IS_ERR(maxs)) ? maxs : NULL; + ix->u.chunk_zone.null_bits = (nb && !RAY_IS_ERR(nb)) ? nb : NULL; + ix->u.chunk_zone.aggs = (aggs && !RAY_IS_ERR(aggs)) ? aggs : NULL; + if (!ix->u.chunk_zone.mins || !ix->u.chunk_zone.maxs || !ix->u.chunk_zone.null_bits || + (sums && !ix->u.chunk_zone.aggs) || enc_alloc_fails(e)) { + ray_release(root); + return ray_error("oom", "column %s: chunk zone", e->path); + } + mins->len = maxs->len = nc; + nb->len = (nc + 7) / 8; + memset(ray_data(nb), 0, (size_t)nb->len); + if (aggs) aggs->len = 3 * (int64_t)nc; + for (uint32_t c = 0; c < nc; c++) { + ray_enc_dirent_t de; dirent_at(e, c, &de); + bool absent = (de.flags & RAY_ENC_STAT_ABSENT) || e->type == RAY_STR; /* STR: code bounds, no order */ + if (fl) { + ((double*)ray_data(mins))[c] = absent ? INFINITY : dbl_of(de.min); + ((double*)ray_data(maxs))[c] = absent ? -INFINITY : dbl_of(de.max); + } else { + ((int64_t*)ray_data(mins))[c] = absent ? INT64_MAX : de.min; + ((int64_t*)ray_data(maxs))[c] = absent ? INT64_MIN : de.max; + } + if (de.null_count) ((uint8_t*)ray_data(nb))[c >> 3] |= (uint8_t)(1u << (c & 7)); + if (aggs) { + int64_t* ag = (int64_t*)ray_data(aggs); + ag[c] = (int64_t)de.sum_lo; + ag[nc + c] = chunk_rows(e, c) - (int64_t)de.null_count; + ag[2 * (int64_t)nc + c] = (int64_t)de.sum_hi; + } + } + return root; +} + +/* Recorded kind or UNIQUE (single file). */ +static bool enc_may_have_index(const ray_enccol_t* e) { + return e->kind == RAY_ENCCOL_SINGLE && (e->hdr.index_kind || (e->hdr.col_flags & RAY_ENC_FLAG_UNIQUE)); +} + +/* ZONE / CHUNK_ZONE roots are synthesized from the directory; HASH / + * SORT / BLOOM / PART roots are parsed from the index region on first + * materialization. The UNIQUE marker comes from + * the column flag (the parse leaves it to this caller). A recorded DICT + * (P6b) attaches a heap root from the persisted region: codes the heap copy + * (shared with the aware paths), first_occ a copy; nothing in the root + * refers to the mapping. UNIQUE marks whichever root results. */ +static ray_t* enc_attach_index(ray_enccol_t* e, ray_t** vp) { + uint8_t kind = e->hdr.index_kind; + bool unique = e->hdr.col_flags & RAY_ENC_FLAG_UNIQUE; + if (kind == 0 && !unique) return NULL; + ray_t* root = NULL; + if (kind == RAY_IDX_ZONE || kind == RAY_IDX_CHUNK_ZONE) { + root = kind == RAY_IDX_ZONE ? enc_synth_zone(e) : enc_synth_chunk_zone(e); + if (RAY_IS_ERR(root)) return root; + } else if (kind == RAY_IDX_HASH || kind == RAY_IDX_SORT || kind == RAY_IDX_BLOOM || kind == RAY_IDX_PART) { + /* the nth counter's step (fail_path already failed at "materialize") */ + if (enc_alloc_fails(e) || atomic_load(&g_fail_index_parse)) + return ray_error("oom", "column %s: index parse", e->path); + ray_enc_idx_view_t iv; + ray_enc_index_view(e->base + e->hdr.index_off, e->hdr.end_off - e->hdr.index_off, + kind, e->type, e->attrs, e->len, &iv); + ray_t* perr = ray_enc_index_parse(&iv, *vp, &root); + if (perr) { + /* the parse names no path: keep its code, add the column's */ + char code[8], msg[200]; + snprintf(code, sizeof code, "%s", ray_err_code(perr) ? ray_err_code(perr) : "error"); + const char* m = ray_error_msg(); + snprintf(msg, sizeof msg, "%s", m ? m : "index parse"); + ray_error_free(perr); + return ray_error(code, "column %s: %s", e->path, msg); + } + } else if (kind == RAY_IDX_DICT) { + /* spec "Materialization" step 2 (P6b): both tiers, then a heap root */ + if (enc_alloc_fails(e) || atomic_load(&g_fail_index_parse)) + return ray_error("oom", "column %s: index parse", e->path); + const ray_enc_idict_t* d; + ray_t* cv = NULL; + ray_t* err = ray_enccol_idict(e, &d); + if (!err) err = ray_enccol_idict_codes_vec(e, &cv); + if (err) return err; + ray_t* fo = enc_alloc_fails(e) ? NULL : ray_vec_new(RAY_I32, d->n_distinct); + root = fo && !RAY_IS_ERR(fo) && !enc_alloc_fails(e) ? ray_index_new_root(RAY_IDX_DICT, RAY_STR, e->len) : NULL; + if (!root || RAY_IS_ERR(root)) { + if (fo && !RAY_IS_ERR(fo)) ray_release(fo); else if (fo) ray_error_free(fo); + if (root) ray_error_free(root); + return ray_error("oom", "column %s: DICT index", e->path); + } + fo->len = d->n_distinct; + memcpy(ray_data(fo), d->first_occ, (size_t)d->n_distinct * 4); + ray_retain(cv); /* shared with the aware paths */ + ray_index_t* ix = ray_index_payload(root); + ix->u.dict.codes = cv; ix->u.dict.first_occ = fo; ix->u.dict.n_distinct = d->n_distinct; + } + if (unique) { + if (!root) { + root = enc_alloc_fails(e) ? NULL : ray_index_new_root(RAY_IDX_NONE, e->type, e->len); + if (!root || RAY_IS_ERR(root)) return root ? root : ray_error("oom", "column %s: unique marker", e->path); + } + ray_index_payload(root)->markers |= RAY_MARK_UNIQUE; + } + ray_t* r = ray_index_attach_persisted(vp, root); /* consumes root */ + if (RAY_IS_ERR(r)) return r; + *vp = r; + return NULL; +} + +/* Test hook: STR pools allocated by materialization (after the prepass, so a + * column it rejects allocates none). */ +static _Atomic(uint64_t) g_str_pool_allocs; +uint64_t ray_enccol_test_str_pool_allocs(void) { return atomic_load(&g_str_pool_allocs); } + +static ray_t* enc_materialize_single(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + if (ray_interrupted()) { ray_enc_snap_set(fail, "cancel", "column %s: interrupted", e->path); return NULL; } + if (enc_alloc_fails(e)) { ray_enc_snap_set(fail, "oom", "column %s: materialize", e->path); return NULL; } + ray_t* vec = e->type == RAY_SYM ? ray_sym_vec_new(e->attrs & RAY_SYM_W_MASK, e->len) + : ray_vec_new(e->type, e->len); + if (!vec || RAY_IS_ERR(vec)) { + if (vec) ray_enc_snap_take(fail, vec); else ray_enc_snap_set(fail, "oom", "column %s: materialize", e->path); + return NULL; + } + vec->len = e->len; + ray_t* err = NULL; + uint64_t* chunk_pool = NULL; + uint32_t* dict_pool_off = NULL; + enc_task_res_t* res = NULL; + if (e->type == RAY_STR) { + const ray_enc_sdict_t* sd = NULL; /* the dictionary first: the pool starts with it */ + if ((err = ray_enccol_strdict(e, &sd)) != NULL) goto fail; + chunk_pool = enc_alloc_fails(e) ? NULL : ray_alloc_raw((size_t)(e->n_chunks + 1) * sizeof(uint64_t)); + if (!chunk_pool) { err = ray_error("oom", "column %s: materialize", e->path); goto fail; } + if ((err = enc_str_prepass(e, chunk_pool, sd)) != NULL) goto fail; + if (e->hdr.str_pool_bytes > 0) { + ray_t* pool = enc_alloc_fails(e) ? NULL : ray_alloc((size_t)e->hdr.str_pool_bytes); + if (!pool || RAY_IS_ERR(pool)) { err = pool ? pool : ray_error("oom", "column %s: pool", e->path); goto fail; } + pool->type = RAY_U8; + pool->len = (int64_t)e->hdr.str_pool_bytes; + vec->str_pool = pool; + atomic_fetch_add_explicit(&g_str_pool_allocs, 1, memory_order_relaxed); + } + if (sd) { + /* the dictionary region: entries over 12 bytes once, in code + * order, at the pool's start (the prepass counted sd->pooled + * of it, so a pool exists when any entry is pooled) */ + dict_pool_off = enc_alloc_fails(e) ? NULL : ray_alloc_raw((size_t)sd->n * sizeof(uint32_t)); + if (!dict_pool_off) { err = ray_error("oom", "column %s: materialize", e->path); goto fail; } + char* pb = vec->str_pool ? (char*)ray_data(vec->str_pool) : NULL; + uint64_t at = 0; + for (uint32_t k = 0; k < sd->n; k++) { + const char* sp; uint32_t len; + ray_enc_sdict_entry(sd, k, &sp, &len); + if (len <= RAY_STR_INLINE_MAX) { dict_pool_off[k] = UINT32_MAX; continue; } + memcpy(pb + at, sp, len); + dict_pool_off[k] = (uint32_t)at; /* at + len <= sd->pooled <= str_pool_bytes <= UINT32_MAX */ + at += len; + } + } + } + res = enc_alloc_fails(e) ? NULL : ray_calloc_raw((size_t)(e->n_chunks + 1) * sizeof *res); + if (!res) { err = ray_error("oom", "column %s: materialize", e->path); goto fail; } + enc_mat_ctx_t x = { + .e = e, .out = (uint8_t*)ray_data(vec), + .pool = vec->str_pool ? (char*)ray_data(vec->str_pool) : NULL, + .chunk_pool = chunk_pool, .dict_pool_off = dict_pool_off, + .res = res, + }; + atomic_init(&x.lowest_failed, INT64_MAX); + if (e->n_chunks > (int64_t)UINT32_MAX) { err = ray_error("range", "column %s: too many chunks", e->path); goto fail; } + ray_pool_t* tp = ray_pool_get(); + if (e->n_chunks >= 2 && ray_pool_par_dispatch_ok(tp, e->n_chunks, 2)) + ray_pool_dispatch_n(tp, enc_mat_chunk, &x, (uint32_t)e->n_chunks); + else + enc_mat_chunk(&x, 0, 0, e->n_chunks); + /* A cancel also stops the pool from running its remaining tasks: a chunk + * that neither finished nor failed was never run and counts as cancelled. */ + for (int64_t c = 0; c < e->n_chunks; c++) + if (res[c].failed || !res[c].done) { /* the lowest-numbered failing task */ + if (res[c].failed) *fail = res[c].snap; + else ray_enc_snap_set(fail, "cancel", "column %s: interrupted", e->path); + ray_free_raw(res); ray_free_raw(chunk_pool); ray_free_raw(dict_pool_off); ray_release(vec); + return NULL; + } + ray_free_raw(res); res = NULL; + ray_free_raw(chunk_pool); chunk_pool = NULL; + ray_free_raw(dict_pool_off); dict_pool_off = NULL; + vec->attrs = e->attrs; /* persisted attrs (SYM width included) */ + if (e->type == RAY_SYM) { + vec->sym_domain = e->dom; /* sym_vec_new's runtime domain is immortal */ + if (e->dom_owned) ray_sym_domain_retain(e->dom); + } + if ((err = enc_attach_index(e, &vec)) != NULL) goto fail; + atomic_fetch_add_explicit(&g_enc_materialized, 1, memory_order_relaxed); + return vec; +fail: + ray_free_raw(res); ray_free_raw(chunk_pool); ray_free_raw(dict_pool_off); + ray_release(vec); + ray_enc_snap_take(fail, err); + return NULL; +} + +/* ---- Parted object (Task 12) ---- */ + +bool ray_enccol_is_parted(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + return e && e->kind == RAY_ENCCOL_PARTED; +} + +void ray_enccol_set_synthetic(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + if (e && e->kind == RAY_ENCCOL_SINGLE) e->synthetic = true; +} + +bool ray_enccol_is_synthetic(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + if (!e) return false; + if (e->kind == RAY_ENCCOL_SINGLE) return e->synthetic; + if (!e->wrapper) return false; + ray_t** segs = (ray_t**)ray_data(e->wrapper); + for (int64_t i = 0; i < e->wrapper->len; i++) + if (segs[i] && segs[i]->type == RAY_ENCCOL && !ray_enccol_is_synthetic(segs[i])) return false; + return true; +} + +ray_t* ray_enccol_parted_new(ray_t* wrapper) { + if (!wrapper || RAY_IS_ERR(wrapper) || !RAY_IS_PARTED(wrapper->type)) + return ray_error("type", "parted encoded column needs a parted wrapper"); + ray_enccol_t* e = ray_calloc_raw(sizeof *e); + if (!e) return ray_error("oom", NULL); + atomic_fetch_add_explicit(&g_enccol_live, 1, memory_order_relaxed); + atomic_store(&e->rc, 1); + e->kind = RAY_ENCCOL_PARTED; + e->type = (int8_t)RAY_PARTED_BASETYPE(wrapper->type); + e->len = ray_parted_nrows(wrapper); + ray_t** segs = (ray_t**)ray_data(wrapper); + for (int64_t i = 0; i < wrapper->len; i++) { + if (!segs[i]) continue; + ray_col_meta_t m; + if (!ray_col_meta_of(segs[i], &m)) continue; + /* an encoded segment: its directory's null count (in-band text nulls + * included); a plain one: the exact check, which scans a SYM/STR + * payload (text nulls set no flag) */ + bool nulls = m.null_count >= 0 ? m.null_count > 0 + : !m.enc && (m.type == RAY_SYM || m.type == RAY_STR) ? ray_vec_has_nulls(segs[i]) + : (m.attrs & RAY_ATTR_HAS_NULLS) != 0; + if (nulls) e->attrs |= RAY_ATTR_HAS_NULLS; /* OR across every segment; width and + * SORTED are per-segment properties */ + } + /* Distinct from every segment's path: a segment-scoped failure (or test + * hook) never matches the wrapper itself. */ + snprintf(e->path, sizeof e->path, "(parted)"); + ray_enc_once_init(&e->once); + ray_enc_once_init(&e->dict_once); + ray_retain(wrapper); + e->wrapper = wrapper; + ray_t* v = ray_enccol_wrap(e); + if (!v || RAY_IS_ERR(v)) { enccol_free(e); return v ? v : ray_error("oom", NULL); } + return v; +} + +ray_t* ray_enccol_seg(ray_t* encv, int64_t i) { + ray_enccol_t* e = ray_enccol_of(encv); + if (!e || e->kind != RAY_ENCCOL_PARTED || !e->wrapper || i < 0 || i >= e->wrapper->len) return NULL; + return ((ray_t**)ray_data(e->wrapper))[i]; +} + +ray_t* ray_enccol_seg_col(ray_t* encv, int64_t i) { + ray_t* s = ray_enccol_seg(encv, i); + if (!s) return NULL; + return s->type == RAY_ENCCOL ? ray_enccol_materialize(s) : s; +} + +typedef struct { + ray_t** in; /* the wrapper's segments */ + ray_t** plain; /* borrowed results */ + enc_task_res_t* res; /* one attempt result per segment (task) */ +} enc_seg_ctx_t; + +/* One task per segment; each materializes through its own once-state, so a + * segment keeps its cached vector or failure whatever the others do. The + * snapshot is taken from the error on this thread. */ +static void enc_seg_task(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + enc_seg_ctx_t* x = raw; + for (int64_t i = start; i < end; i++) { + ray_t* s = x->in[i]; + if (!s || s->type != RAY_ENCCOL) { x->plain[i] = s; x->res[i].done = true; continue; } + ray_t* m = ray_enccol_materialize(s); + if (RAY_IS_ERR(m)) { + ray_enc_snap_take(&x->res[i].snap, m); + x->res[i].failed = true; + continue; + } + x->plain[i] = m; + x->res[i].done = true; + } +} + +static _Atomic(int) g_parted_mode; /* test hook: 0 auto, 1 coordinator, 2 per-segment tasks */ +void ray_enccol_test_parted_mode(int mode) { atomic_store(&g_parted_mode, mode); } + +static ray_t* enc_materialize_parted(void* ctx, ray_enc_snap_t* fail) { + ray_enccol_t* e = ctx; + int64_t n = e->wrapper->len; + bool inj = enc_alloc_fails(e); + ray_t* out = inj ? NULL : ray_alloc((size_t)n * sizeof(ray_t*)); + ray_t** plain = inj ? NULL : ray_calloc_raw((size_t)(n + 1) * sizeof(ray_t*)); + enc_task_res_t* res = inj ? NULL : ray_calloc_raw((size_t)(n + 1) * sizeof *res); + if (!out || RAY_IS_ERR(out) || !plain || !res) { + if (out && !RAY_IS_ERR(out)) ray_free(out); + ray_free_raw(plain); ray_free_raw(res); + ray_enc_snap_set(fail, "oom", "column %s: parted materialize", e->path); + return NULL; + } + out->type = e->wrapper->type; + out->len = n; + out->attrs = 0; + memset(out->aux, 0, 16); + memset(ray_data(out), 0, (size_t)n * sizeof(ray_t*)); + enc_seg_ctx_t x = { (ray_t**)ray_data(e->wrapper), plain, res }; + ray_pool_t* pool = ray_pool_get(); + /* Per-segment tasks run their chunks serially (nested dispatch), so with + * fewer encoded segments left than workers the coordinator takes them one + * after another and each keeps full chunk parallelism. Either way every + * segment is attempted and reported through its own result slot. */ + int64_t n_enc = 0; + for (int64_t i = 0; i < n; i++) { + ray_t* sg = x.in[i]; + if (sg && sg->type == RAY_ENCCOL && !ray_enccol_of(sg)->decoded) n_enc++; + } + int mode = atomic_load(&g_parted_mode); + bool fan = n >= 2 && n <= (int64_t)UINT32_MAX && ray_pool_par_dispatch_ok(pool, n, 2) && + n_enc >= (int64_t)pool->n_workers; + if (mode == 1) fan = false; + else if (mode == 2) fan = n >= 2 && n <= (int64_t)UINT32_MAX && ray_pool_par_dispatch_ok(pool, n, 2); + if (fan) ray_pool_dispatch_n(pool, enc_seg_task, &x, (uint32_t)n); + else enc_seg_task(&x, 0, 0, n); + /* A task the pool skipped on cancel neither finished nor failed. */ + for (int64_t i = 0; i < n; i++) + if (res[i].failed || !res[i].done) { /* lowest-numbered failing segment */ + if (res[i].failed) *fail = res[i].snap; + else ray_enc_snap_set(fail, "cancel", "column %s: interrupted", e->path); + ray_free(out); /* no segment reference was taken yet */ + ray_free_raw(plain); ray_free_raw(res); + return NULL; + } + ray_t** segs = (ray_t**)ray_data(out); + for (int64_t i = 0; i < n; i++) if (plain[i]) { ray_retain(plain[i]); segs[i] = plain[i]; } + ray_free_raw(plain); ray_free_raw(res); + return out; +} + +/* A caller waiting on another thread's attempt (ray_enc_once_get) does not + * observe its own cancellation: it waits for the attempt, which polls + * ray_interrupted() once per chunk and ends with a transient "cancel" + * (the state then resets), so the wait is bounded by one chunk's decode. */ +ray_t* ray_enccol_materialize(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + if (!e) return ray_error("type", "materialize: not an encoded column"); + /* Reject before the once/cache lookup: caller control state is not a + * permanent property of the file, and workers can have distinct state. */ + if ((e->type == RAY_F32 || e->type == RAY_F64) && !ray_enc_fp_env_ok()) + return ray_error("fpenv", "column %s: " RAY_ENC_FPENV_MSG, e->path); + ray_t* r = ray_enc_once_get(&e->once, &e->decoded, + e->kind == RAY_ENCCOL_PARTED ? enc_materialize_parted : enc_materialize_single, e); + if (r && !RAY_IS_ERR(r)) dec_note(e); + return r; +} + +static _Atomic(int64_t) g_kept_limit_test; /* test hook: the budget, 0 = a quarter of the watermark */ +void ray_enccol_test_kept_limit(int64_t bytes) { + atomic_store_explicit(&g_kept_limit_test, bytes > 0 ? bytes : 0, memory_order_relaxed); +} + +bool ray_enccol_decode_kept(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + if (!e) return true; + int64_t cap = atomic_load_explicit(&g_kept_limit_test, memory_order_relaxed); + if (cap <= 0) { + int64_t wm = ray_heap_anon_watermark(); + if (wm <= 0) return true; /* no watermark keeps everything */ + cap = wm / 4; /* ray_enccol_cache_trim's budget */ + } + return (double)e->len * (double)ray_enccol_esz(e) <= (double)cap; +} + +void ray_enccol_adopt_domain(ray_t* out, ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + if (!e || !out || out->type != RAY_SYM || e->type != RAY_SYM || !e->dom) return; + out->sym_domain = e->dom; /* sym_vec_new's runtime domain is immortal */ + if (e->dom_owned) ray_sym_domain_retain(e->dom); +} + +void ray_enccol_meta(ray_t* encv, ray_col_meta_t* m) { + ray_enccol_t* e = ray_enccol_of(encv); + memset(m, 0, sizeof *m); + m->enc = encv; + m->len = e->len; + if (e->kind == RAY_ENCCOL_PARTED) { + m->type = (int8_t)(RAY_PARTED_BASE + e->type); + m->attrs = e->attrs; + m->n_segs = e->wrapper ? e->wrapper->len : 0; + m->null_count = -1; + return; + } + m->type = e->type; + m->attrs = e->attrs; + m->index_kind = e->hdr.index_kind; + m->unique = (e->hdr.col_flags & RAY_ENC_FLAG_UNIQUE) != 0; + m->null_count = e->null_count; +} + +/* Generation-0 payload bytes of a plain vector (STR: its pool too). */ +uint64_t ray_enccol_plain_bytes(ray_t* s) { + if (!s || !ray_is_vec(s)) return 0; + uint64_t b = (uint64_t)s->len * ray_sym_elem_size(s->type, s->attrs); + if (s->type == RAY_STR && s->str_pool) b += (uint64_t)s->str_pool->len; + return b; +} + +ray_t* ray_enccol_info(ray_t* encv, ray_enccol_info_t* out) { + memset(out, 0, sizeof *out); + ray_enccol_t* e = ray_enccol_of(encv); + if (!e) return ray_error("type", "info: not an encoded column"); + out->synthetic = ray_enccol_is_synthetic(encv); + if (e->kind == RAY_ENCCOL_PARTED) { + int64_t ns = e->wrapper ? e->wrapper->len : 0; + for (int64_t i = 0; i < ns; i++) { + ray_t* s = ray_enccol_seg(encv, i); + if (!s) continue; + ray_enccol_info_t si; + if (s->type == RAY_ENCCOL) { + ray_t* err = ray_enccol_info(s, &si); + if (err) return err; + } else { + memset(&si, 0, sizeof si); + si.encoded_bytes = si.raw_bytes = ray_enccol_plain_bytes(s); + } + for (int k = 0; k < 10; k++) out->vectors[k] += si.vectors[k]; + out->encoded_bytes += si.encoded_bytes; + out->raw_bytes += si.raw_bytes; + out->materialized |= si.materialized; + } + out->materialized |= ray_enccol_decoded_peek(encv) != NULL; + return NULL; + } + /* a synthetic stand-in has an in-memory null image, not a file: no + * encodings and no file bytes */ + for (int64_t c = 0; !out->synthetic && c < e->n_chunks; c++) { + const ray_enc_desc_t* d = ray_enccol_descs(e, c); + int64_t rows = e->len - c * RAY_ENC_CHUNK; + int nv = (int)(((rows > RAY_ENC_CHUNK ? RAY_ENC_CHUNK : rows) + RAY_ENC_VEC - 1) / RAY_ENC_VEC); + for (int j = 0; j < nv; j++) if (d[j].encoding < 10) out->vectors[d[j].encoding]++; + } + out->encoded_bytes = out->synthetic ? 0 : e->hdr.end_off; + /* the materialized column's bytes: for STR, str_pool_bytes is the + * decoded pool's exact size, which holds each STR_DICT entry once (spec + * "STR pool"), so a STR_DICT column reports less than its generation-0 + * file's per-occurrence pool (P6 D15; the header keeps no + * per-occurrence count, and .idx.info decodes nothing) */ + out->raw_bytes = (uint64_t)e->len * ray_enccol_esz(e) + (e->type == RAY_STR ? e->hdr.str_pool_bytes : 0); + out->materialized = ray_enccol_decoded_peek(encv) != NULL; + return NULL; +} + +bool ray_enccol_may_have_index(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + return e && enc_may_have_index(e); +} + +ray_t* ray_enccol_decoded_peek(ray_t* encv) { + ray_enccol_t* e = ray_enccol_of(encv); + if (!e) return NULL; + if (atomic_load_explicit(&e->once.state, memory_order_acquire) != RAY_ENC_ONCE_DONE) return NULL; + return e->decoded; +} + +void ray_enccol_chunk_stat(const ray_enccol_t* e, int64_t c, ray_enc_chunk_stat_t* out) { + ray_enc_dirent_t de; + dirent_at(e, c, &de); + out->rows = chunk_rows(e, c); + /* STR bounds are code bounds (first-occurrence codes, not ordered + * values): only ray_enccol_code_bounds reads them */ + out->has_minmax = (de.flags & RAY_ENC_STAT_ABSENT) == 0 && e->type != RAY_STR; + out->min = e->type == RAY_STR ? 0 : de.min; /* a reader ignoring has_minmax sees no codes */ + out->max = e->type == RAY_STR ? 0 : de.max; + out->null_count = de.null_count; + out->sum_lo = de.sum_lo; out->sum_hi = de.sum_hi; +} + +bool ray_enccol_code_bounds(const ray_enccol_t* e, int64_t c, int j, int64_t* lo, int64_t* hi) { + if (e->type != RAY_STR || e->kind != RAY_ENCCOL_SINGLE || e->synthetic || c < 0 || c >= e->n_chunks) return false; + if (j < 0) { + ray_enc_dirent_t de; dirent_at(e, c, &de); + if (de.flags & RAY_ENC_STAT_ABSENT) return false; + *lo = de.min; *hi = de.max; + return true; + } + if (j >= RAY_ENC_VECS_PER_CHUNK || (c * RAY_ENC_VECS_PER_CHUNK + j) * RAY_ENC_VEC >= e->len) return false; + const ray_enc_desc_t* d = &ray_enccol_descs(e, c)[j]; + if (d->flags & RAY_ENC_STAT_ABSENT) return false; + *lo = d->min; *hi = d->max; + return true; +} + +void ray_enccol_dir_totals(ray_enccol_t* e, ray_enc_col_totals_t* out) { + if (atomic_load_explicit(&e->totals_state, memory_order_acquire) == 2) { *out = e->totals; return; } + bool fl = enc_type_float(e->type); + out->sum_wrapped = 0; out->sum_hi = 0; out->sum_lo = 0; out->nonnull = 0; + out->min_i = INT64_MAX; out->max_i = INT64_MIN; + out->min_f = INFINITY; out->max_f = -INFINITY; + out->mm_partial = false; + for (int64_t c = 0; c < e->n_chunks; c++) { + ray_enc_dirent_t de; + dirent_at(e, c, &de); + out->sum_wrapped += de.sum_lo; + uint64_t l = out->sum_lo + de.sum_lo; /* ray_i128_add128 */ + out->sum_hi += (int64_t)de.sum_hi + (l < de.sum_lo ? 1 : 0); + out->sum_lo = l; + out->nonnull += chunk_rows(e, c) - (int64_t)de.null_count; + if ((de.flags & RAY_ENC_STAT_ABSENT) || e->type == RAY_STR) { /* STR: code bounds are no ordered statistic */ + if ((int64_t)de.null_count < chunk_rows(e, c)) out->mm_partial = true; + continue; + } + if (fl) { + double mn = dbl_of(de.min), mx = dbl_of(de.max); + if (mn < out->min_f) out->min_f = mn; + if (mx > out->max_f) out->max_f = mx; + } else { + if (de.min < out->min_i) out->min_i = de.min; + if (de.max > out->max_i) out->max_i = de.max; + } + } + /* first finisher stores the (identical) totals; readers wait for 2 */ + uint8_t idle = 0; + if (atomic_compare_exchange_strong_explicit(&e->totals_state, &idle, 1, + memory_order_acq_rel, memory_order_relaxed)) { + e->totals = *out; + atomic_store_explicit(&e->totals_state, 2, memory_order_release); + } +} + +void ray_enccol_byte_range(const ray_enccol_t* e, int64_t lo, int64_t hi, + uint64_t* off, uint64_t* len) { + int64_t c0 = lo / RAY_ENC_CHUNK, c1 = (hi - 1) / RAY_ENC_CHUNK; + ray_enc_dirent_t a, b; + dirent_at(e, c0, &a); + dirent_at(e, c1, &b); + *off = a.offset; + *len = b.offset + b.bytes - a.offset; +} diff --git a/src/store/enccol.h b/src/store/enccol.h new file mode 100644 index 000000000..dd0088ecc --- /dev/null +++ b/src/store/enccol.h @@ -0,0 +1,457 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RAY_ENCCOL_H +#define RAY_ENCCOL_H + +#include +#include +#include "mem/heap.h" /* ray_file_map_t */ +#include "ops/ops.h" /* RAY_ENCCOL */ +#include "store/encfmt.h" +#include "store/enc_once.h" +#include "table/table.h" /* ray_col_meta_t */ + +struct ray_sym_domain_s; + +#define RAY_ENCCOL_SINGLE 1 +#define RAY_ENCCOL_PARTED 2 + +/* Whole-column totals of a single-file column's directory, in one pass + * (what a loop of ray_enccol_chunk_stat over every chunk would add up): + * the wrapping sum of the chunk low words, the exact 128-bit sum, the + * non-null rows, and the extremes over the chunks with min/max (integer + * types in min_i / max_i from INT64_MAX / INT64_MIN, float types in + * min_f / max_f from +inf / -inf). */ +typedef struct { + uint64_t sum_wrapped; + int64_t sum_hi; + uint64_t sum_lo; + int64_t nonnull; + int64_t min_i, max_i; + double min_f, max_f; + bool mm_partial; /* a chunk with non-null rows carries no min / max: the extremes are incomplete */ +} ray_enc_col_totals_t; + +typedef struct ray_enccol_s { + _Atomic(uint32_t) rc; /* shared by RAY_ENCCOL header copies */ + uint8_t kind; /* RAY_ENCCOL_SINGLE / RAY_ENCCOL_PARTED */ + int8_t type; /* logical element type (parted: base type) */ + uint8_t attrs; /* persisted attrs (masked) */ + int64_t len; /* logical rows (parted: sum over segments) */ + /* single file */ + ray_file_map_t* map; /* one reference to the mapping */ + const uint8_t* base; + uint64_t size; + ray_enc_hdr_t hdr; /* the header's copy */ + int64_t n_chunks; + int64_t null_count; /* sum of the directory null counts */ + struct ray_sym_domain_s* dom; /* SYM: the domain ids resolve over (retained unless runtime) */ + bool dom_owned; + bool synthetic; /* an in-memory stand-in (a ragged partition's absent + * column), not data saved encoded */ + char path[1024]; + uint64_t vdict_off, vdict_len; /* VALUE_DICT entry (file offset, bytes); 0 when absent */ + ray_enc_once_t dict_once; /* VALUE_DICT, read once (Task 7) */ + ray_t* dict; /* VALUE_DICT values as RAY_I64 bit patterns */ + /* STR side entries (P6): file offset and bytes, 0 when absent */ + uint64_t sdict_off, sdict_len; /* STR_DICT */ + uint64_t fsst_off, fsst_len; /* FSST_TABLE */ + ray_enc_once_t sdict_once; /* STR_DICT, read once */ + ray_enc_once_t fsst_once; /* FSST_TABLE, read once */ + ray_t* sdict; /* STR_DICT: a RAY_U8 blob holding a ray_enc_sdict_t */ + ray_t* fsst; /* FSST_TABLE: a RAY_U8 blob holding a ray_fsst_table_t */ + /* persisted DICT (P6b): the entry tier and the code tier, once each */ + ray_enc_once_t idict_once; + ray_t* idict; /* RAY_U8 blob: enc_idict_blob_t (the ray_enc_idict_t), then + * the entry table (ray_enc_sdict_t) */ + ray_enc_once_t icodes_once; + ray_t* icodes; /* RAY_I32: a heap copy of the codes */ + /* parted (Task 12) */ + ray_t* wrapper; /* RAY_PARTED_BASE + type; segments are RAY_ENCCOL or plain */ + /* materialization (Task 8) */ + ray_enc_once_t once; + ray_t* decoded; + /* the statement-boundary trim (ray_enccol_cache_trim): columns whose + * whole-column decode is published, linked while it is */ + struct ray_enccol_s* dec_prev; + struct ray_enccol_s* dec_next; + _Atomic(bool) dec_listed; + _Atomic(uint64_t) dec_used; /* the statement that last asked for the decode */ + _Atomic(uint64_t) decoded_bytes; /* bytes produced by this column's vector decodes */ + _Atomic(uint8_t)* touch_ok; /* per chunk: its RAW payloads read through (ray_enccol_raw_view) */ + /* single file: ray_enccol_dir_totals' cache; totals_state 0 none, + * 1 being stored, 2 stored (acquire before reading totals) */ + _Atomic(uint8_t) totals_state; + ray_enc_col_totals_t totals; +} ray_enccol_t; + +/* A STR_DICT side entry (heap blob; offs / bytes point into the + * immutable mapping). Entries are pairwise distinct; "" (the STR null, in + * band) is an ordinary entry, null_code its code (UINT32_MAX when no entry + * is empty). slot[] is an open-addressing table over ray_hash_bytes of the + * entry bytes: code + 1, 0 empty. */ +typedef struct { + uint32_t n; + uint32_t null_code; + const uint64_t* offs; /* n + 1 */ + const uint8_t* bytes; + uint64_t pooled; /* sum of entry lengths over 12 */ + uint64_t mask; /* hash slots - 1 */ + uint32_t slot[]; /* mask + 1 */ +} ray_enc_sdict_t; +static inline void ray_enc_sdict_entry(const ray_enc_sdict_t* d, uint32_t k, const char** p, uint32_t* len) { + *p = (const char*)d->bytes + d->offs[k]; *len = (uint32_t)(d->offs[k + 1] - d->offs[k]); +} + +ray_enccol_t* ray_enccol_of(ray_t* v); +ray_t* ray_enccol_open(void* mapped, size_t size, const char* path, + struct ray_sym_domain_s* dom, bool require_dom); +ray_t* ray_enccol_wrap(ray_enccol_t* e); +void ray_enccol_payload_retain(ray_t* v); +void ray_enccol_payload_release(ray_t* v); +void ray_enccol_payload_detach(ray_t* v); +size_t ray_enccol_own_bytes(ray_t* v); +int ray_enccol_children(ray_t* v, ray_t* out[2]); + +/* Chunk c's 64 descriptors, in place in the mapping (valid while the + * column is). The file is ours: they are read as written. */ +const ray_enc_desc_t* ray_enccol_descs(const ray_enccol_t* e, int64_t c); +/* Vector j of chunk c read in place: the mapped payload of a RAW vector + * with no nulls and no trailer (F32, F64 and the integer types, SYM + * included), whose bits equal its decode. NULL: decode it instead. */ +const void* ray_enccol_raw_view(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d); +/* Decode vector j of chunk c into `out` (vlen elements, generation-0 + * element width). STR: pooled bytes are copied to pool_out[pool_base ...] + * (sized by ray_enccol_desc_pool_bytes) and descriptors get pool_off = + * pool_base + offset within the vector; hash32 is left 0. The decoded + * bytes are returned in *produced instead of counted; the caller counts + * them with ray_enccol_note_decoded. NULL or an owned error (oom of a + * side entry, the FP environment). */ +ray_t* ray_enccol_decode_into(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, + void* out, char* pool_out, uint64_t pool_base, uint64_t* produced); +/* Vector j of chunk c straight into an expression register: RAY_I64 or + * RAY_F64 elements (`wide`), nulls as NULL_I64 / NULL_F64, for a FOR_BP, + * DELTA_BP, CONST or RLE vector of a narrow integer column (BOOL, U8, I16, + * I32, DATE, TIME). 1 decoded (*produced as ray_enccol_decode_into), 0 declined: the + * caller reads the vector by range. */ +int ray_enccol_decode_wide(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, + int8_t wide, void* out, uint64_t* produced); +/* Row `row` of a single-file integer column (not SYM), read from its packed + * vector without decoding the vector: a FOR_BP vector, DICT over a FOR_BP + * code child, CONST or RLE (the row's run found by binary search, no row + * expanded), with no nulls. 1 served (*out: the value widened to int64, + * as the decode would hold it), 0 declined (read the vector by range), -1 + * an owned error in *err (the dictionary's oom). */ +int ray_enccol_point_i64(ray_enccol_t* e, int64_t row, int64_t* out, ray_t** err); +/* ray_enccol_point_i64 of rows rows[q] - base, q in [0, n): ascending + * rows of one vector, its body read once (CONST / RLE: the runs parsed + * once, not once per row). 1: every row served into out; 0: declined (as + * ray_enccol_point_i64; above open decision D2's limit for the codec, + * RAY_ENC_VEC / 32 rows of a FOR_BP vector, RAY_ENC_VEC / 16 of an RLE, + * CONST or DICT one; a RAW vector without nulls, which a view reads; a + * vector with nulls; SYM; any other codec; or rows outside one vector or + * not ascending), out partly written; -1: an owned error in *err. */ +int ray_enccol_points_i64(ray_enccol_t* e, const int64_t* rows, int64_t n, int64_t base, int64_t* out, ray_t** err); +/* ray_enccol_points_i64 for a gather, which takes nulls and SYM ids: also + * serves a vector with a null bitmap (nul[q] 1 for a row in it, out[q] + * then 0, and nothing else of the row read) and a SYM column's ids (id 0, + * the in-band null, as itself). nul[q] is 0 for every other row. The + * codecs and their per-vector row limits are ray_enccol_points_i64's: + * FOR_BP, DICT over FOR_BP codes, CONST or RLE, and RAW with a bitmap. + * 1 / 0 / -1 as there. */ +int ray_enccol_gather_points(ray_enccol_t* e, const int64_t* rows, int64_t n, int64_t base, int64_t* out, + uint8_t* nul, ray_t** err); + +/* RAY_ENC_VEC lane values at the kind's width T (the fast kernels' own + * buffer: enccol.c's fk_vals_t is a typedef of this). */ +typedef union { + uint8_t b[RAY_ENC_VEC]; uint16_t h[RAY_ENC_VEC]; + uint32_t s[RAY_ENC_VEC]; uint64_t q[RAY_ENC_VEC]; +} ray_enc_lanes_t; + +/* A parsed top-level vector body; never expanded to values. + * About 21 KB: a scan task keeps one on its stack (never the heap). + * Floats (CONST, RLE, DICT): k is { 32 | 64, unsigned, float }; cbits, the + * run values and the dictionary entries are F32 / F64 bit patterns. */ +typedef struct ray_enc_vview_s { + uint8_t enc; /* RAY_ENC_CONST, _FOR_BP, _RLE, _DICT or _STR_DICT (a view exists only for these) */ + int n, n_nulls; + const uint8_t* nullmap; /* the 128-byte bitmap (bitmap types with nulls), else NULL */ + ray_enc_kind_t k; + int8_t type; + uint64_t cbits; /* CONST: the value's T-bit pattern */ + uint64_t base; /* FOR_BP: the T-bit base */ + int width; /* FOR_BP */ + const uint8_t* packed; /* FOR_BP: the packed lanes in the mapping */ + uint32_t n_runs; /* RLE (CONST: 1) */ + ray_enc_lanes_t run_vals; /* RLE / CONST: run values at width T */ + ray_enc_lanes_t run_ends; /* RLE / CONST: .h[r] exclusive, strictly ascending, last == n */ + uint32_t codes[RAY_ENC_VEC]; /* DICT, STR_DICT */ + const uint64_t* dict; /* DICT: VALUE_DICT entries (T-bit patterns, strictly ascending in dictionary order) */ + uint32_t dict_n; +} ray_enc_vview_t; + +/* Column-global vector `vec` of a single-file column as a view. 1: a + * view of a CONST, RLE, FOR_BP or DICT (over a U32 FOR_BP code child) + * integer body, a CONST, RLE or DICT float body (no trailer), or a STR + * STR_DICT vector as its codes (k U32, type RAY_STR, dict NULL, dict_n the + * entry count, nullmap NULL: the null is the empty entry's code, in band). + * A FOR_BP body's base is the vector minimum (the writer's), so its + * residuals compare in logical order. 0: declined (RAW, DELTA_BP, another + * code child, a float trailer, STR other than STR_DICT): read the vector + * by range; -1: an owned error in *err (a side entry's oom). Never counts + * decoded bytes. A declined view may be partly written; the caller + * ignores it. */ +int ray_enccol_vview(ray_enccol_t* e, int64_t vec, ray_enc_vview_t* out, ray_t** err); + +/* The FOR_BP residuals of a view (no base added) at width T into out + * (n elements of T bits), through the lane kernels (fk_forT, base 0). + * FOR_BP views only (any other view has packed NULL); out is aligned to + * T / 8 bytes and holds n elements. */ +void ray_enccol_unpack_resid(const ray_enc_vview_t* v, void* out); +/* The residuals of a FOR_BP view comparing true (op: OP_EQ .. OP_GE, at + * the lane width, unsigned) against t, unpacked and compared in one pass + * of the lane kernels without storing them (perf fix 6's count). */ +uint32_t ray_enccol_count_resid(const ray_enc_vview_t* v, uint16_t op, uint64_t t); +/* A reference on the column's payload (the RAY_ENCCOL headers share it). */ +void ray_enccol_ref(ray_enccol_t* e); +void ray_enccol_unref(ray_enccol_t* e); +/* Count decoded bytes (global and per column counters). */ +void ray_enccol_note_decoded(ray_enccol_t* e, uint64_t bytes); +/* Decoded-pool bytes of vector j of chunk c (STR; 0 otherwise). */ +ray_t* ray_enccol_desc_pool_bytes(ray_enccol_t* e, int64_t c, int j, const ray_enc_desc_t* d, + uint64_t* out); +/* Column-global vector decoded into out (its bytes counted); STR pooled + * bytes at pool_out[pool_base ...], sized by ray_enccol_vec_pool_bytes. */ +ray_t* ray_enccol_decode_vec(ray_enccol_t* e, int64_t vec, void* out, char* pool_out, uint64_t pool_base); +ray_t* ray_enccol_vec_pool_bytes(ray_enccol_t* e, int64_t vec, uint64_t* out); +uint8_t ray_enccol_esz(const ray_enccol_t* e); /* generation-0 element width */ + +/* The plain column (borrowed, cached for the object's lifetime) or an + * owned RAY_ERROR. Single and (Task 12) parted objects. */ +ray_t* ray_enccol_materialize(ray_t* encv); + +/* The cached plain column when the materialization has completed, else NULL; + * never decodes and is safe against a concurrent materialize. */ +ray_t* ray_enccol_decoded_peek(ray_t* encv); + +/* Whether a whole decode of the column would stay cached from one + * statement to the next: its generation-0 bytes fit the budget + * ray_enccol_cache_trim keeps (a quarter of the anonymous watermark; no + * watermark keeps everything). A consumer that can read the column by + * range does so when it would not: such a decode takes the column's whole + * size at once and is dropped at the statement's end, so every query pays + * it again. Metadata only. */ +bool ray_enccol_decode_kept(ray_t* encv); +/* Test hook: a positive budget replaces the quarter of the watermark in + * ray_enccol_decode_kept until reset to 0. */ +void ray_enccol_test_kept_limit(int64_t bytes); + +/* At a statement boundary: drop the whole-column decodes, least recently + * asked for first, until those still kept fit a quarter of the anonymous + * watermark. A decode something else retains is neither counted nor + * dropped (dropping it would free nothing and the next read would decode a + * second copy). Does nothing while an evaluation is on this thread's stack + * (a request served from inside a statement's sync send) or a dispatch is in + * flight, and without a watermark. */ +void ray_enccol_cache_trim(void); +/* Bytes of the whole-column decodes currently kept (test hook). */ +int64_t ray_enccol_cache_bytes(void); + +/* Counters (spec "Instrumentation"); reset by tests. decoded_bytes is + * the bytes vector decodes produce, plus the bytes an integer RAW vector + * read in place delivers (ray_enccol_raw_view through a range read); a + * float RAW view delivers its bytes uncounted. */ +typedef struct { + uint64_t materialized; + uint64_t decoded_bytes; + uint64_t at_first_exec; /* materialized when the first ray_execute since the last reset started; UINT64_MAX until then */ +} ray_enc_counters_t; +void ray_enc_note_exec_start(void); +void ray_enc_counters_get(ray_enc_counters_t* out); +void ray_enc_counters_reset(void); + +/* Test hooks. fail_alloc: the nth allocation inside generation-2 decode + * or materialization (and a string-domain build's per-segment code remap, + * strdom.c) fails (1 = the next one); 0 disables. fail_path: + * while set, every such allocation fails for a column whose path contains + * `sub` (NULL disables); both report "oom" (transient). */ +void ray_enccol_test_fail_alloc(int64_t nth); +void ray_enccol_test_fail_path(const char* sub); +/* The fail_alloc counter, for a materialization step outside this file + * (the index-region parse): true when this allocation is the nth. It is + * the counter only (ray_enc_index_parse takes no path). fail_path never + * reaches the region: it fails the column's first materialization + * allocation ("materialize"), before the region is parsed; + * the parse is reached by the nth counter (the materializer's own check + * before the parse, then this one inside it) and by fail_index_parse. */ +bool ray_enccol_test_nth_alloc_fails(void); +/* Test hook: while set, the index parse of every materialization fails + * with "oom" ("column : index parse"); transient, so not cached. */ +void ray_enccol_test_fail_index_parse(bool on); +/* interrupt_after: the nth chunk decoded successfully from now on calls + * ray_request_interrupt() (0 disables), exercising the per-chunk poll. */ +void ray_enccol_test_interrupt_after(int64_t nth); +/* Parted materialization: 0 auto, 1 always on the coordinator, 2 always per-segment tasks. */ +void ray_enccol_test_parted_mode(int mode); +/* Encoded column objects alive (opened, not yet freed). */ +int64_t ray_enccol_test_live(void); +/* One top-level integer vector body (`enc`, `width`) of a column of `type` + * (SYM: `attrs` width class), vlen rows, `bm` the null bitmap or NULL, + * n_nulls as its descriptor says. fast: through the fast kernel only, + * writing `wide` elements (0: the generation-0 width; RAY_I64 / RAY_F64: + * an expression register); else through the reference path (wide must be + * 0). 1 decoded, 0 the fast kernel declined, -1 the reference path + * failed (oom). */ +int ray_enccol_test_decode_body(int8_t type, uint8_t attrs, uint8_t enc, + uint8_t width, int n_nulls, const uint8_t* bm, const uint8_t* body, + uint64_t avail, int vlen, bool fast, int8_t wide, void* out); +/* One top-level DICT vector body of a column of `type` whose VALUE_DICT + * holds dict[0, n_dict) (T-bit patterns); otherwise as + * ray_enccol_test_decode_body at the generation-0 width (fast: the + * dictionary published first, as a column's first decode leaves it). */ +int ray_enccol_test_decode_dict(int8_t type, const uint64_t* dict, uint32_t n_dict, + int n_nulls, const uint8_t* bm, const uint8_t* body, uint64_t avail, + int vlen, bool fast, void* out); +/* One top-level float vector body (`enc`, any float encoding; F32 / F64) + * of a column with the VALUE_DICT dict[0, n_dict) (NULL: none), n_nulls + * as its descriptor says, no trailer. fast: through the fast kernel only + * (the dictionary published first); else through dec_floats. 1 decoded, + * 0 the fast kernel declined, -1 the reference path failed. */ +int ray_enccol_test_decode_float(int8_t type, const uint64_t* dict, uint32_t n_dict, uint8_t enc, int n_nulls, + const uint8_t* bm, const uint8_t* body, uint64_t avail, int vlen, + bool fast, void* out); +/* ray_enccol_point_i64's body read of every row [0, vlen) of one top-level + * body (`enc`, `width`, n_nulls as its descriptor says) of a column of + * `type` with the VALUE_DICT dict[0, n_dict) (NULL: none): res[i] is the + * point read's 1 / 0 / -1 and out[i] its value when served. 0, or -1 on + * OOM. */ +int ray_enccol_test_point_body(int8_t type, const uint64_t* dict, uint32_t n_dict, uint8_t enc, + uint8_t width, int n_nulls, const uint8_t* body, uint64_t avail, + int vlen, int64_t* out, int8_t* res); + +/* Wrap a plain-type parted wrapper (RAY_PARTED_BASE + base) whose segments + * include at least one RAY_ENCCOL; retains the wrapper. */ +ray_t* ray_enccol_parted_new(ray_t* wrapper); +/* Segment i: its RAY_ENCCOL or plain vector (borrowed; NULL for a missing + * segment, which ray_read_parted never builds: a ragged partition's absent + * column is a lazy all-null RAY_ENCCOL segment, or for LIST a heap fill). */ +ray_t* ray_enccol_seg(ray_t* encv, int64_t i); +/* Segment i materialized (borrowed plain vector, NULL for a missing one) + * or an owned error. */ +ray_t* ray_enccol_seg_col(ray_t* encv, int64_t i); +bool ray_enccol_is_parted(ray_t* encv); +/* A synthetic column stands in for data that was never saved encoded (a + * ragged partition's absent column, ray_read_parted): generation + * inheritance treats it as plain. Parted: every encoded segment is + * synthetic. */ +void ray_enccol_set_synthetic(ray_t* encv); +bool ray_enccol_is_synthetic(ray_t* encv); + +/* A column's format, for .idx.info: vectors per encoding code (RAW .. + * FSST), file bytes, generation-0 bytes, whether the plain column exists. + * Reads descriptors only (statistics are reported, never trusted to size + * memory) and never decodes a payload. */ +typedef struct { + int64_t vectors[10]; + uint64_t encoded_bytes; /* file bytes (end_off) of real encoded files; a plain parted segment + * counts its raw bytes, a synthetic stand-in counts 0 */ + uint64_t raw_bytes; /* materialized payload: len * width (+ the decoded STR pool, which + * holds each STR_DICT entry once) */ + bool materialized; + bool synthetic; /* every encoded segment is a synthetic stand-in */ +} ray_enccol_info_t; +/* Generation-0 payload bytes of a plain vector: len * width (+ STR pool). */ +uint64_t ray_enccol_plain_bytes(ray_t* v); +/* NULL, or an owned type error (not an encoded column). */ +ray_t* ray_enccol_info(ray_t* encv, ray_enccol_info_t* out); + +/* One chunk's directory statistics. */ +typedef struct ray_enc_chunk_stat_s { + int64_t rows; /* rows in the chunk */ + int64_t min, max; /* logical_T values (float types: the double's bits); valid when has_minmax */ + bool has_minmax; /* directory flag bit 0 clear */ + uint32_t null_count; + uint64_t sum_lo; /* exact 128-bit sum (BOOL, U8, I16, I32, I64, TIME: ray_encw_type_summable) */ + int64_t sum_hi; +} ray_enc_chunk_stat_t; +/* Chunk c of a single-file encoded column. c must be below e->n_chunks. */ +void ray_enccol_chunk_stat(const ray_enccol_t* e, int64_t c, ray_enc_chunk_stat_t* out); +/* STR code bounds (membership bounds, spec "Statistics") of chunk c (j < 0) + * or of vector j of chunk c: true with [*lo, *hi] when present. The only + * reader of STR statistics as statistics; every generic accessor reports + * none for STR (chunk_stat with min / max 0, dir_totals, vec_stat), and the + * ZONE / CHUNK_ZONE synthesis treats STR chunks as without them. */ +bool ray_enccol_code_bounds(const ray_enccol_t* e, int64_t c, int j, int64_t* lo, int64_t* hi); +/* The totals below, computed once per column (the directory is immutable). */ +void ray_enccol_dir_totals(ray_enccol_t* e, ray_enc_col_totals_t* out); +/* File byte range holding rows [lo, hi): from the first touched chunk's + * descriptors to the end of the last touched chunk. Precondition: + * 0 <= lo < hi <= e->len (a row past the end would read a directory entry + * past the last chunk). */ +void ray_enccol_byte_range(const ray_enccol_t* e, int64_t lo, int64_t hi, + uint64_t* off, uint64_t* len); + +void ray_enccol_meta(ray_t* encv, ray_col_meta_t* m); +/* Could materialization attach an index: a recorded kind or UNIQUE + * (single-file)? Known without decoding. */ +bool ray_enccol_may_have_index(ray_t* encv); + +/* The column's STR dictionary (*out NULL when it has none, or the column + * is not STR), or an owned oom error (read once). */ +ray_t* ray_enccol_strdict(ray_enccol_t* e, const ray_enc_sdict_t** out); +/* Code of `s` in the column's dictionary: *code >= 0, -1 absent, -2 no + * dictionary. NULL, or an owned oom error (*code untouched). */ +ray_t* ray_enccol_strdict_code(ray_enccol_t* e, const char* s, size_t len, int64_t* code); + +/* A persisted DICT (spec "STR dictionary index"), parsed. Pointers into + * the immutable mapping; ent is a STR_DICT-form view of the entries (offs + * / bytes in the mapping, slots in the blob). */ +typedef struct { + int64_t len, n_distinct; + const int32_t* codes; /* len: read through ray_enccol_idict_codes */ + const int32_t* first_occ; /* n_distinct */ + const ray_enc_sdict_t* ent; /* ent->n == n_distinct */ +} ray_enc_idict_t; +/* The column records a persisted DICT (P6b): a single file, not synthetic, + * its header naming kind 7. The one gate of every DICT reader. */ +bool ray_enccol_has_idict(const ray_enccol_t* e); +/* The column's persisted DICT, parsed once (*out NULL: the column + * records none, or is parted / synthetic), or an owned error (once). */ +ray_t* ray_enccol_idict(ray_enccol_t* e, const ray_enc_idict_t** out); +/* Code of s: *code >= 0, -1 absent, -2 no persisted DICT. */ +ray_t* ray_enccol_idict_code(ray_enccol_t* e, const char* s, size_t len, int64_t* code); +/* Codes of rows [start, start + n) in place (vector scope); no decode, no + * decoded bytes. The column must record a DICT (ray_enccol_idict gave + * one). */ +ray_t* ray_enccol_idict_codes(ray_enccol_t* e, int64_t start, int64_t n, const int32_t** out); +/* The whole codes as a heap RAY_I32 vector, + * made once and kept for the object's lifetime (borrowed: retain to keep). */ +ray_t* ray_enccol_idict_codes_vec(ray_enccol_t* e, ray_t** out); +/* Test hook: how many STR pools materialization has allocated so far. */ +uint64_t ray_enccol_test_str_pool_allocs(void); +/* A fresh SYM vector `out` (runtime domain) takes the domain the column's ids + * resolve over, as its materialization would; no decode. */ +void ray_enccol_adopt_domain(ray_t* out, ray_t* encv); + +#endif /* RAY_ENCCOL_H */ diff --git a/src/store/enceval.c b/src/store/enceval.c new file mode 100644 index 000000000..a371dcd87 --- /dev/null +++ b/src/store/enceval.c @@ -0,0 +1,504 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "store/enceval.h" +#include +#include + +static inline int cmp_one(int64_t x, uint16_t op, int64_t c) { + switch (op) { + case OP_EQ: return x == c; case OP_NE: return x != c; + case OP_LT: return x < c; case OP_LE: return x <= c; + case OP_GT: return x > c; case OP_GE: return x >= c; + default: return 0; + } +} +/* the predicate comparator on doubles: -0.0 == +0.0; a NaN never reaches + * here (it is the null, in the bitmap) */ +static inline int cmp_one_f(double x, uint16_t op, double c) { + switch (op) { + case OP_EQ: return x == c; case OP_NE: return x != c; + case OP_LT: return x < c; case OP_LE: return x <= c; + case OP_GT: return x > c; case OP_GE: return x >= c; + default: return 0; + } +} +static inline uint64_t lane(const ray_enc_lanes_t* l, int T, uint32_t i) { + switch (T) { case 8: return l->b[i]; case 16: return l->h[i]; case 32: return l->s[i]; default: return l->q[i]; } +} +static inline bool is_float(int8_t t) { return t == RAY_F32 || t == RAY_F64; } +static inline bool is_cmp_op(uint16_t op) { return op >= OP_EQ && op <= OP_GE; } + +void ray_enc_mask_nulls(const ray_enc_vview_t* v, uint8_t nr, uint8_t* bits) { + if (!v->nullmap) return; + for (int i = 0; i < v->n; i++) + if ((v->nullmap[i >> 3] >> (i & 7)) & 1) bits[i] = nr; +} + +int ray_enc_const_decision(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t nr) { + if (v->enc != RAY_ENC_CONST || is_float(v->type) || !is_cmp_op(op)) return -1; + if (v->type == RAY_SYM && op != OP_EQ && op != OP_NE) return -1; /* never order ids (#738) */ + if (v->nullmap && v->n_nulls == v->n) return nr; /* all null: every row is null_result */ + int r = cmp_one(ray_enc_logical(v->cbits, v->k), op, c); + if (!v->nullmap || r == nr) return r; + return -1; +} + +int ray_enc_const_decision_f64(const ray_enc_vview_t* v, uint16_t op, double c, uint8_t nr) { + if (v->enc != RAY_ENC_CONST || !is_float(v->type) || !is_cmp_op(op)) return -1; + if (isnan(c)) return -1; /* a NaN constant is the null constant: decline */ + if (v->nullmap && v->n_nulls == v->n) return nr; + int r = cmp_one_f(ray_enc_fval(v->cbits, v->type == RAY_F64 ? 64 : 32), op, c); + if (!v->nullmap || r == nr) return r; + return -1; +} + +/* FOR_BP: x = logical(base) + u with 0 <= u <= umax and no wrap in logical + * space (the view checked it on the actual residuals), so x op c <=> u op t + * with t = c - logical(base), computed in 128 bits; t outside [0, umax] + * decides every non-null row alike. The residuals come from the lane + * kernels at width T and compare as unsigned T-bit values. */ +#define EVAL_RES(UT) do { const UT* u_ = (const UT*)res; const UT t_ = (UT)tt; \ + switch (op) { \ + case OP_EQ: for (int i = 0; i < v->n; i++) bits[i] = u_[i] == t_; break; \ + case OP_NE: for (int i = 0; i < v->n; i++) bits[i] = u_[i] != t_; break; \ + case OP_LT: for (int i = 0; i < v->n; i++) bits[i] = u_[i] < t_; break; \ + case OP_LE: for (int i = 0; i < v->n; i++) bits[i] = u_[i] <= t_; break; \ + case OP_GT: for (int i = 0; i < v->n; i++) bits[i] = u_[i] > t_; break; \ + case OP_GE: for (int i = 0; i < v->n; i++) bits[i] = u_[i] >= t_; break; \ + default: memset(bits, 0, (size_t)v->n); break; } } while (0) + +static void eval_for(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t* bits) { + const uint64_t umax = v->width >= 64 ? ~0ull : ((1ull << v->width) - 1); + /* one formula for every kind: the only unsigned 64-bit kind is SYM W64, + * whose ids (and so its base) are below 2^32, where logical(base) is + * the base itself; a negative c then lands in t < 0, which is right + * for EQ / NE, the only operators SYM reaches */ + const __int128 t = (__int128)c - (__int128)ray_enc_logical(v->base, v->k); + if (t < 0 || t > (__int128)umax) { + memset(bits, cmp_one(t < 0 ? 1 : -1, op, 0), (size_t)v->n); /* x > c, or x < c, for every row */ + return; + } + const uint64_t tt = (uint64_t)t; + _Alignas(64) ray_enc_lanes_t lanes; /* the residuals, on the stack */ + const void* res = &lanes; + ray_enccol_unpack_resid(v, &lanes); + switch (v->k.T) { + case 8: EVAL_RES(uint8_t); break; + case 16: EVAL_RES(uint16_t); break; + case 32: EVAL_RES(uint32_t); break; + default: EVAL_RES(uint64_t); break; + } +} +#undef EVAL_RES + +/* DICT: VALUE_DICT is strictly ascending in native order (the view admits + * signed integer kinds only); the passing codes form one interval [lo, hi) + * or its complement (NE). */ +static uint32_t lower_bound(const ray_enc_vview_t* v, int64_t c) { + uint32_t lo = 0, hi = v->dict_n; + while (lo < hi) { uint32_t mid = lo + (hi - lo) / 2; if (ray_enc_logical(v->dict[mid], v->k) < c) lo = mid + 1; else hi = mid; } + return lo; +} +static uint32_t upper_bound(const ray_enc_vview_t* v, int64_t c) { + uint32_t lo = 0, hi = v->dict_n; + while (lo < hi) { uint32_t mid = lo + (hi - lo) / 2; if (ray_enc_logical(v->dict[mid], v->k) <= c) lo = mid + 1; else hi = mid; } + return lo; +} +static void eval_dict(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t* bits) { + const uint32_t lb = lower_bound(v, c), ub = upper_bound(v, c); + uint32_t lo = 0, hi = 0; uint8_t neg = 0; + switch (op) { + case OP_EQ: lo = lb; hi = ub; break; + case OP_NE: lo = lb; hi = ub; neg = 1; break; + case OP_LT: lo = 0; hi = lb; break; + case OP_LE: lo = 0; hi = ub; break; + case OP_GT: lo = ub; hi = v->dict_n; break; + case OP_GE: lo = lb; hi = v->dict_n; break; + default: break; + } + const uint32_t span = hi - lo; + for (int i = 0; i < v->n; i++) + bits[i] = (uint8_t)((v->codes[i] - lo < span) ^ neg); /* unsigned: one compare */ +} + +/* x in set: the set sorted ascending, distinct */ +static bool in_set(const int64_t* set, int nset, int64_t x) { + int lo = 0, hi = nset; + while (lo < hi) { int mid = lo + (hi - lo) / 2; if (set[mid] < x) lo = mid + 1; else hi = mid; } + return lo < nset && set[lo] == x; +} +/* RLE: each run's value decides its rows (CONST takes one memset), under + * a comparison or a membership. */ +typedef struct { bool member; uint16_t op; int64_t c; const int64_t* set; int nset; } run_pred_t; +static inline int run_pred(const run_pred_t* p, int64_t x) { + return p->member ? in_set(p->set, p->nset, x) : cmp_one(x, p->op, p->c); +} +/* ray_enc_logical, inlined for the per-run loop */ +static inline int64_t logical_of(uint64_t bits, ray_enc_kind_t k) { + if (k.T == 64) return (int64_t)bits; + const uint64_t m = (1ull << k.T) - 1; + bits &= m; + return k.is_signed && (bits >> (k.T - 1)) & 1 ? (int64_t)(bits | ~m) : (int64_t)bits; +} +/* bits[i, e) = b in 8-byte stores (runs are often a few rows: a memset + * call per run costs more than the run). A store may reach past e, never + * past n: the next run, which starts at e, overwrites those bytes. */ +static inline void fill_run(uint8_t* bits, uint32_t i, uint32_t e, uint32_t n, uint8_t b) { + const uint64_t pat = 0x0101010101010101ull * b; + for (; i + 8 <= e; i += 8) memcpy(bits + i, &pat, 8); + if (i < e) { + if (i + 8 <= n) memcpy(bits + i, &pat, 8); + else for (; i < e; i++) bits[i] = b; + } +} +static void eval_runs(const ray_enc_vview_t* v, const run_pred_t* p, uint8_t* bits) { + uint32_t i = 0; + for (uint32_t r = 0; r < v->n_runs; r++) { + const uint8_t b = (uint8_t)run_pred(p, logical_of(lane(&v->run_vals, v->k.T, r), v->k)); + const uint32_t e = v->run_ends.h[r]; + fill_run(bits, i, e, (uint32_t)v->n, b); + i = e; + } +} + +/* Some run of v holds the logical value c: its T-bit pattern compared + * against the run values, one pass (no per-run fill), for equality's + * all-fail case. A value outside the kind's range is held by none. */ +#define RUNS_HOLD(UT, F) do { const UT x_ = (UT)pat; bool hit_ = false; \ + for (uint32_t r = 0; r < v->n_runs; r++) hit_ |= v->run_vals.F[r] == x_; \ + return hit_; } while (0) +static bool runs_hold(const ray_enc_vview_t* v, int64_t c) { + const int T = v->k.T; + if (T < 64) { + const int64_t lo = v->k.is_signed ? -((int64_t)1 << (T - 1)) : 0; + const int64_t hi = v->k.is_signed ? ((int64_t)1 << (T - 1)) - 1 : (int64_t)((1ull << T) - 1); + if (c < lo || c > hi) return false; + } else if (!v->k.is_signed && c < 0) { + return false; + } + const uint64_t pat = T == 64 ? (uint64_t)c : (uint64_t)c & ((1ull << T) - 1); + switch (T) { + case 8: RUNS_HOLD(uint8_t, b); + case 16: RUNS_HOLD(uint16_t, h); + case 32: RUNS_HOLD(uint32_t, s); + default: RUNS_HOLD(uint64_t, q); + } +} +#undef RUNS_HOLD + +/* eval_runs of EQ / NE for a constant some run holds (runs_hold, so it + * lies inside the kind's range): its T-bit pattern once, then one compare + * per run at the lane width (no per-run widening or operator switch). */ +#define RUNS_EQ(UT, F) do { const UT x_ = (UT)pat; \ + for (uint32_t r = 0; r < v->n_runs; r++) { \ + const uint32_t e_ = v->run_ends.h[r]; \ + fill_run(bits, i, e_, (uint32_t)v->n, (uint8_t)((v->run_vals.F[r] == x_) ^ ne)); \ + i = e_; \ + } } while (0) +static void eval_runs_eq(const ray_enc_vview_t* v, int64_t c, uint8_t ne, uint8_t* bits) { + const int T = v->k.T; + const uint64_t pat = T == 64 ? (uint64_t)c : (uint64_t)c & ((1ull << T) - 1); + uint32_t i = 0; + switch (T) { + case 8: RUNS_EQ(uint8_t, b); break; + case 16: RUNS_EQ(uint16_t, h); break; + case 32: RUNS_EQ(uint32_t, s); break; + default: RUNS_EQ(uint64_t, q); break; + } +} +#undef RUNS_EQ + +bool ray_enc_eval_cmp_f64(const ray_enc_vview_t* v, uint16_t op, double c, uint8_t nr, uint8_t* bits) { + if (!is_float(v->type) || !is_cmp_op(op) || isnan(c)) return false; + const int T = v->k.T; + switch (v->enc) { + case RAY_ENC_CONST: + memset(bits, cmp_one_f(ray_enc_fval(v->cbits, T), op, c), (size_t)v->n); + break; + case RAY_ENC_RLE: { + uint32_t i = 0; + for (uint32_t r = 0; r < v->n_runs; r++) { + const uint32_t e = v->run_ends.h[r]; + fill_run(bits, i, e, (uint32_t)v->n, (uint8_t)cmp_one_f(ray_enc_fval(lane(&v->run_vals, T, r), T), op, c)); + i = e; + } + break; + } + case RAY_ENC_DICT: { + /* the entries ascend in dictionary order, numerically nondecreasing + * (the order only puts -0.0 before +0.0), so the entries equal to c + * under the predicate comparator are one interval [lb, ub): both + * zeros for a zero c */ + uint32_t lo = 0, hi = v->dict_n; + while (lo < hi) { uint32_t mid = lo + (hi - lo) / 2; if (ray_enc_fval(v->dict[mid], T) < c) lo = mid + 1; else hi = mid; } + const uint32_t lb = lo; + hi = v->dict_n; + while (lo < hi) { uint32_t mid = lo + (hi - lo) / 2; if (ray_enc_fval(v->dict[mid], T) <= c) lo = mid + 1; else hi = mid; } + const uint32_t ub = lo; + uint32_t a = 0, b = 0; uint8_t neg = 0; + switch (op) { + case OP_EQ: a = lb; b = ub; break; + case OP_NE: a = lb; b = ub; neg = 1; break; + case OP_LT: a = 0; b = lb; break; + case OP_LE: a = 0; b = ub; break; + case OP_GT: a = ub; b = v->dict_n; break; + default: a = lb; b = v->dict_n; break; /* OP_GE */ + } + const uint32_t span = b - a; + for (int i = 0; i < v->n; i++) + bits[i] = (uint8_t)((v->codes[i] - a < span) ^ neg); /* unsigned: one compare */ + break; + } + default: + return false; + } + /* a null row holds a real value (the fill rule) or, wholly null, any + * bits: the mask decides it */ + ray_enc_mask_nulls(v, nr, bits); + return true; +} + +bool ray_enc_eval_cmp(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t nr, uint8_t* bits) { + if (is_float(v->type)) return false; /* floats: ray_enc_eval_cmp_f64 */ + if (!is_cmp_op(op)) return false; + if (v->type == RAY_SYM && op != OP_EQ && op != OP_NE) return false; /* never order ids (#738) */ + switch (v->enc) { + case RAY_ENC_CONST: + memset(bits, cmp_one(ray_enc_logical(v->cbits, v->k), op, c), (size_t)v->n); + break; + case RAY_ENC_FOR_BP: eval_for(v, op, c, bits); break; + case RAY_ENC_RLE: + if ((op == OP_EQ || op == OP_NE) && !runs_hold(v, c)) memset(bits, op == OP_NE, (size_t)v->n); + else if (op == OP_EQ || op == OP_NE) eval_runs_eq(v, c, op == OP_NE, bits); + else eval_runs(v, &(run_pred_t){ false, op, c, NULL, 0 }, bits); + break; + case RAY_ENC_DICT: eval_dict(v, op, c, bits); break; + default: return false; + } + ray_enc_mask_nulls(v, nr, bits); + return true; +} + +bool ray_enc_eval_cmp_runs(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t* pass) { + if (v->enc != RAY_ENC_RLE || v->nullmap || is_float(v->type) || !is_cmp_op(op)) return false; + if (v->type == RAY_SYM && op != OP_EQ && op != OP_NE) return false; /* never order ids (#738) */ + if ((op == OP_EQ || op == OP_NE) && !runs_hold(v, c)) { + memset(pass, op == OP_NE, v->n_runs); + return true; + } + if (op == OP_EQ || op == OP_NE) { + const int T = v->k.T; + const uint64_t pat = T == 64 ? (uint64_t)c : (uint64_t)c & ((1ull << T) - 1); + const uint8_t ne = op == OP_NE; +#define RUNS_PASS(UT, F) do { const UT x_ = (UT)pat; \ + for (uint32_t r = 0; r < v->n_runs; r++) pass[r] = (uint8_t)((v->run_vals.F[r] == x_) ^ ne); \ + } while (0) + switch (T) { + case 8: RUNS_PASS(uint8_t, b); break; + case 16: RUNS_PASS(uint16_t, h); break; + case 32: RUNS_PASS(uint32_t, s); break; + default: RUNS_PASS(uint64_t, q); break; + } +#undef RUNS_PASS + return true; + } + for (uint32_t r = 0; r < v->n_runs; r++) + pass[r] = (uint8_t)cmp_one(logical_of(lane(&v->run_vals, v->k.T, r), v->k), op, c); + return true; +} + +bool ray_enc_eval_cmp_runs_f64(const ray_enc_vview_t* v, uint16_t op, double c, uint8_t* pass) { + if (v->enc != RAY_ENC_RLE || v->nullmap || !is_float(v->type) || !is_cmp_op(op) || isnan(c)) return false; + const int T = v->k.T; + for (uint32_t r = 0; r < v->n_runs; r++) + pass[r] = (uint8_t)cmp_one_f(ray_enc_fval(lane(&v->run_vals, T, r), T), op, c); + return true; +} + +bool ray_enc_eval_in(const ray_enc_vview_t* v, const int64_t* set, int nset, uint8_t nr, uint8_t* bits) { + if (is_float(v->type)) return false; + if (nset < 0) nset = 0; + switch (v->enc) { + case RAY_ENC_CONST: + memset(bits, in_set(set, nset, ray_enc_logical(v->cbits, v->k)), (size_t)v->n); + break; + case RAY_ENC_RLE: eval_runs(v, &(run_pred_t){ true, 0, 0, set, nset }, bits); break; + case RAY_ENC_DICT: { + /* the codes of the set's members: a bitmap over dict_n <= 2^16 codes (8 KB) */ + uint64_t pass[(1u << 16) / 64]; + memset(pass, 0, ((size_t)v->dict_n + 63) / 64 * 8); + for (int s = 0; s < nset; s++) { + const uint32_t lb = lower_bound(v, set[s]); + if (lb < v->dict_n && ray_enc_logical(v->dict[lb], v->k) == set[s]) pass[lb >> 6] |= 1ull << (lb & 63); + } + for (int i = 0; i < v->n; i++) bits[i] = (uint8_t)((pass[v->codes[i] >> 6] >> (v->codes[i] & 63)) & 1); + break; + } + case RAY_ENC_FOR_BP: { + /* x = logical(base) + u with no wrap (the view's guarantee), so the + * wrapping 64-bit sum is the logical value exactly */ + const uint64_t lb = (uint64_t)ray_enc_logical(v->base, v->k); + _Alignas(64) ray_enc_lanes_t lanes; /* the residuals, on the stack */ + ray_enccol_unpack_resid(v, &lanes); + for (int i = 0; i < v->n; i++) + bits[i] = (uint8_t)in_set(set, nset, (int64_t)(lb + lane(&lanes, v->k.T, (uint32_t)i))); + break; + } + default: return false; + } + ray_enc_mask_nulls(v, nr, bits); + return true; +} + +/* CONST: n_nonnull * logical(value) (0 when every row is null); FOR_BP: + * n_nonnull * logical(base) + the non-null residuals (no wrap, the view's + * guarantee; the writer fills null slots with the base, and the residual + * sum skips them all the same); RLE without nulls: logical(value) * run + * length per run. */ +bool ray_enc_vec_sum(const ray_enc_vview_t* v, int64_t* hi, uint64_t* lo, int64_t* nn) { + switch (v->type) { + case RAY_I16: case RAY_I32: case RAY_I64: case RAY_TIME: break; + case RAY_BOOL: case RAY_U8: if (v->n_nulls) return false; break; + default: return false; + } + __int128 s = 0; + const int64_t n_nonnull = (int64_t)v->n - v->n_nulls; + switch (v->enc) { + case RAY_ENC_CONST: + if (n_nonnull) s = (__int128)n_nonnull * ray_enc_logical(v->cbits, v->k); + break; + case RAY_ENC_FOR_BP: { + _Alignas(64) ray_enc_lanes_t u; /* the residuals, on the stack */ + ray_enccol_unpack_resid(v, &u); + const uint8_t* nm = v->n_nulls ? v->nullmap : NULL; + __int128 r = 0; + if (v->k.T == 64) { + if (nm) { for (int i = 0; i < v->n; i++) if (!((nm[i >> 3] >> (i & 7)) & 1)) r += u.q[i]; } + else { for (int i = 0; i < v->n; i++) r += u.q[i]; } + } else { + /* at most 1024 residuals below 2^32: the 64-bit total cannot wrap */ + uint64_t r64 = 0; + for (int i = 0; i < v->n; i++) { + uint64_t x = lane(&u, v->k.T, (uint32_t)i); + if (nm) x &= (uint64_t)((nm[i >> 3] >> (i & 7)) & 1) - 1; /* a null row adds 0 */ + r64 += x; + } + r = r64; + } + s = (__int128)n_nonnull * ray_enc_logical(v->base, v->k) + r; + break; + } + case RAY_ENC_RLE: { + if (v->n_nulls) return false; /* nullable RLE decodes */ + uint32_t prev = 0; + for (uint32_t r = 0; r < v->n_runs; r++) { + s += (__int128)ray_enc_logical(lane(&v->run_vals, v->k.T, r), v->k) * (int64_t)(v->run_ends.h[r] - prev); + prev = v->run_ends.h[r]; + } + break; + } + default: return false; + } + *hi = (int64_t)(s >> 64); + *lo = (uint64_t)s; + *nn = n_nonnull; + return true; +} + +/* Counts (the count fast path): the evaluators' rules, summed instead of + * written out. A view with a bitmap declines (its nulls would need the + * mask); SYM ids count == / != only, never ordered (#738). */ +/* FOR_BP: eval_for's threshold t = c - logical(base) over the residuals + * (no wrap, the view's guarantee); t outside [0, umax] decides every row. + * The residuals are compared as the lane kernels unpack them, never + * stored (ray_enccol_count_resid: measured 12-16% faster than unpacking + * into a lane buffer and counting it). */ +static int64_t count_for(const ray_enc_vview_t* v, uint16_t op, int64_t c) { + const uint64_t umax = v->width >= 64 ? ~0ull : ((1ull << v->width) - 1); + const __int128 t = (__int128)c - (__int128)ray_enc_logical(v->base, v->k); + if (t < 0 || t > (__int128)umax) return cmp_one(t < 0 ? 1 : -1, op, 0) ? v->n : 0; + return ray_enccol_count_resid(v, op, (uint64_t)t); +} + +bool ray_enc_count_cmp(const ray_enc_vview_t* v, uint16_t op, int64_t c, int64_t* count) { + if (v->nullmap || is_float(v->type) || !is_cmp_op(op)) return false; + if (v->type == RAY_SYM && op != OP_EQ && op != OP_NE) return false; /* never order ids (#738) */ + int64_t n = 0; + switch (v->enc) { + case RAY_ENC_CONST: + n = cmp_one(ray_enc_logical(v->cbits, v->k), op, c) ? v->n : 0; + break; + case RAY_ENC_RLE: { + uint32_t prev = 0; + for (uint32_t r = 0; r < v->n_runs; r++) { + const uint32_t e = v->run_ends.h[r]; + if (cmp_one(logical_of(lane(&v->run_vals, v->k.T, r), v->k), op, c)) n += e - prev; + prev = e; + } + break; + } + case RAY_ENC_FOR_BP: n = count_for(v, op, c); break; + case RAY_ENC_DICT: { + const uint32_t lb = lower_bound(v, c), ub = upper_bound(v, c); + uint32_t lo = 0, hi = 0; + switch (op) { + case OP_EQ: case OP_NE: lo = lb; hi = ub; break; + case OP_LT: hi = lb; break; + case OP_LE: hi = ub; break; + case OP_GT: lo = ub; hi = v->dict_n; break; + default: lo = lb; hi = v->dict_n; break; /* OP_GE */ + } + const uint32_t span = hi - lo; + uint32_t a = 0; + for (int i = 0; i < v->n; i++) a += v->codes[i] - lo < span; /* unsigned: one compare */ + n = op == OP_NE ? v->n - (int64_t)a : (int64_t)a; + break; + } + default: return false; + } + *count = n; + return true; +} + +bool ray_enc_runs(const ray_enc_vview_t* v, void* ctx, ray_enc_run_fn fn) { + if ((v->enc != RAY_ENC_CONST && v->enc != RAY_ENC_RLE) || is_float(v->type)) return false; + uint32_t prev = 0; + for (uint32_t r = 0; r < v->n_runs; r++) { + const uint32_t e = v->run_ends.h[r]; + fn(ctx, logical_of(lane(&v->run_vals, v->k.T, r), v->k), (int32_t)prev, (int32_t)e); + prev = e; + } + return true; +} + +void ray_enc_view_range(const ray_enc_vview_t* v, int64_t* mn, int64_t* mx) { + int64_t a = INT64_MAX, b = INT64_MIN; + /* only run values are a value range; any other view yields the empty range */ + for (uint32_t q = 0; (v->enc == RAY_ENC_CONST || v->enc == RAY_ENC_RLE) && q < v->n_runs; q++) { + const int64_t x = logical_of(lane(&v->run_vals, v->k.T, q), v->k); + if (x < a) a = x; + if (x > b) b = x; + } + *mn = a; *mx = b; +} diff --git a/src/store/enceval.h b/src/store/enceval.h new file mode 100644 index 000000000..7a89ba2e6 --- /dev/null +++ b/src/store/enceval.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RAY_ENCEVAL_H +#define RAY_ENCEVAL_H + +#include "store/enccol.h" +#include "ops/ops.h" /* OP_EQ .. OP_GE */ + +/* Encoded comparison and membership over a validated vector view + * (ray_enccol_vview), never expanding the vector. The semantics are the + * predicate comparator's: values are logical_T in native order (signed for + * I16, I32, I64 and the temporal types, unsigned for BOOL, U8 and SYM ids); + * floats compare numerically with -0.0 == +0.0, a NaN being the null. + * SYM ids decide == / != / in only: an ordered operator on SYM declines, + * never ordering ids (#738). Every buffer is the caller's or on the stack. */ + +/* Comparison operators: OP_EQ .. OP_GE of src/ops/ops.h. */ +/* `c` and the members of `set` are integer constants in the column's + * logical domain (a SYM constant is an id of the column's domain). A + * caller holding a float literal against an integer column never + * truncates it into c (generation 0 compares those in double): it + * declines and decodes. A null constant is the caller's to fold too. + * An operator outside OP_EQ .. OP_GE declines (false / -1). */ +/* (x op c) over a viewed vector into bits[0..n), integer kinds (every + * encoding P1 writes for integer, temporal, BOOL, U8 and SYM), with null + * masking: rows whose bitmap bit is set get `null_result`. False when + * the view has no evaluator (RAW, DELTA_BP, a float type: see + * ray_enc_eval_cmp_f64): decode. */ +bool ray_enc_eval_cmp(const ray_enc_vview_t* v, uint16_t op, int64_t c, + uint8_t null_result, uint8_t* bits); +/* (x op c) of each run of an RLE view without bitmap nulls into + * pass[0..n_runs): the run-level answer ray_enc_eval_cmp expands into + * bits, for a consumer that takes runs (a selection emitted from the + * runs). False for any other view, a bitmap, or an operator + * ray_enc_eval_cmp declines. */ +bool ray_enc_eval_cmp_runs(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t* pass); +/* (x in set): set holds nset logical values, sorted ascending, distinct. */ +bool ray_enc_eval_in(const ray_enc_vview_t* v, const int64_t* set, int nset, + uint8_t null_result, uint8_t* bits); +/* Apply the null mask: bits[i] = null_result where the bitmap bit is set. */ +void ray_enc_mask_nulls(const ray_enc_vview_t* v, uint8_t null_result, uint8_t* bits); +/* Whole-vector answer of a CONST view: 1 / 0 when every row has the same + * result (the value's result equals null_result, or no nulls), else -1. */ +int ray_enc_const_decision(const ray_enc_vview_t* v, uint16_t op, int64_t c, uint8_t null_result); +/* The same for a float CONST view (F32 / F64 cbits) under the predicate + * comparator (-0.0 == +0.0); -1 for any other view and for a NaN c + * (generation 0 reads a NaN literal as the null constant). */ +int ray_enc_const_decision_f64(const ray_enc_vview_t* v, uint16_t op, double c, uint8_t null_result); +/* (x op c) over a float view (F32 widened) under the predicate comparator + * (-0.0 == +0.0), null rows set to null_result. CONST: one test; RLE: + * one test per run; DICT: the code interval [lo, hi) of the entries equal + * to c, by lower / upper bound searches on the widened entries. False for + * any other view (RAW, ALP and ALP_RD have none: decode), a non-float + * view, an operator outside OP_EQ .. OP_GE and a NaN c (the null + * constant, as ray_enc_const_decision_f64). */ +bool ray_enc_eval_cmp_f64(const ray_enc_vview_t* v, uint16_t op, double c, + uint8_t null_result, uint8_t* bits); +/* (x op c) of each run of a float RLE view without bitmap nulls into + * pass[0..n_runs), under ray_enc_eval_cmp_f64's comparator: the run-level + * answer it expands into bits. False for any other view, a bitmap, an + * operator it declines and a NaN c. */ +bool ray_enc_eval_cmp_runs_f64(const ray_enc_vview_t* v, uint16_t op, double c, uint8_t* pass); + +/* Exact 128-bit sum of the non-null logical values of a fully selected + * integer vector, and its non-null count. False when the encoding has no + * sum rule (DICT, nullable RLE; RAW and DELTA_BP have no view): decode. + * Integer types summed as ray_encw_type_summable lists them (BOOL, U8, + * I16, I32, I64, TIME): floats, DATE, TIMESTAMP and SYM decline, and so + * does a BOOL / U8 view holding nulls (their kernels count every row). */ +bool ray_enc_vec_sum(const ray_enc_vview_t* v, int64_t* hi, uint64_t* lo, int64_t* n_nonnull); + +/* Rows of a viewed vector without bitmap nulls (SYM: ids, EQ / NE only) + * that compare true against c: CONST n or 0, RLE the lengths of the + * passing runs, FOR_BP a count over the packed residuals (fix 6), DICT a + * count of codes in the interval. False when the view carries a bitmap + * with nulls or has no rule (a float view, an operator outside OP_EQ .. + * OP_GE): read the vector and count it as today. c is in the column's + * logical domain, as for ray_enc_eval_cmp. */ +bool ray_enc_count_cmp(const ray_enc_vview_t* v, uint16_t op, int64_t c, int64_t* count); +/* The runs of a CONST / RLE view as (logical value, first row, end row) + * triples through fn, in row order; false for any other view. A SYM + * value is its id, a BOOL / U8 one unsigned, the others signed: the value + * the vector's decode holds at those rows (a bitmap null row reads as the + * run's stored value: a caller that must see nulls declines a view with + * a nullmap). */ +typedef void (*ray_enc_run_fn)(void* ctx, int64_t value, int32_t lo, int32_t hi); +bool ray_enc_runs(const ray_enc_vview_t* v, void* ctx, ray_enc_run_fn fn); + +/* The [min, max] of the run values of a CONST / RLE view (nulls not + * excluded: a caller declines a view with a bitmap). */ +void ray_enc_view_range(const ray_enc_vview_t* v, int64_t* mn, int64_t* mx); + +#endif /* RAY_ENCEVAL_H */ diff --git a/src/store/encfmt.h b/src/store/encfmt.h new file mode 100644 index 000000000..cbc1969ce --- /dev/null +++ b/src/store/encfmt.h @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RAY_ENCFMT_H +#define RAY_ENCFMT_H + +/* Generation-2 column file layout (spec "Format"). Normative: + * [32B ray_t header][enc header 64B][directory n_chunks x 64B] + * [chunk: 64 x 48B descriptors][payloads] ... [side data] [index region] + * Every structure is little-endian; generation 2 is defined only for + * little-endian hosts (RAY_ENC_LE). */ + +#include +#include +#include +#include "store/enc.h" + +#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define RAY_ENC_LE 1 +#elif defined(_WIN32) +# define RAY_ENC_LE 1 +#else +# define RAY_ENC_LE 0 +#endif + +#define RAY_ENC_GEN ((uint8_t)2) +#define RAY_ENC_XENC 0x434E4558u /* aux bytes 0..3 "XENC" */ +#define RAY_ENC_XIDX 0x58444958u /* generation-0 "XIDX" index marker */ +#define RAY_ENC_RENC 0x434E4552u /* enc header magic "RENC" */ +#define RAY_ENC_HDR_VERSION 1 +#define RAY_ENC_HDR_OFF 32 +#define RAY_ENC_DIR_OFF 96 +#define RAY_ENC_VECS_PER_CHUNK 64 +#define RAY_ENC_DESC_AREA (RAY_ENC_VECS_PER_CHUNK * 48) +#define RAY_ENC_FLAG_UNIQUE 0x01 /* col_flags bit 0 */ +#define RAY_ENC_STAT_ABSENT 0x01 /* directory and descriptor flags bit 0 */ +#define RAY_ENC_DESC_TRAILER 0x02 /* descriptor flags bit 1 */ +#define RAY_ENC_SIDE_VALUE_DICT 1 +#define RAY_ENC_SIDE_STR_DICT 2 +#define RAY_ENC_SIDE_FSST_TABLE 3 + +#define RAY_ENC_GEN_CORRUPT (-1) +#define RAY_ENC_GEN_VERSION (-2) + +typedef struct ray_enc_hdr_s { + uint8_t magic[4]; /* 0 "RENC" */ + uint16_t header_version; /* 4 */ + uint8_t index_kind; /* 6 ray_idx_kind_t */ + uint8_t col_flags; /* 7 bit 0 UNIQUE */ + uint32_t rsv0; /* 8 */ + uint32_t rsv1; /* 12 */ + uint64_t side_off; /* 16 */ + uint64_t side_len; /* 24 */ + uint64_t index_off; /* 32 */ + uint32_t rsv2; /* 40 */ + uint32_t rsv3; /* 44 */ + uint64_t str_pool_bytes; /* 48 */ + uint64_t end_off; /* 56 */ +} ray_enc_hdr_t; + +typedef struct { + uint64_t offset; /* 0 */ + uint64_t bytes; /* 8 */ + int64_t min; /* 16 */ + int64_t max; /* 24 */ + uint64_t sum_lo; /* 32 */ + int64_t sum_hi; /* 40 */ + uint32_t rsv0; /* 48 */ + uint32_t null_count; /* 52 */ + uint32_t flags; /* 56 */ + uint32_t rsv1; /* 60 */ +} ray_enc_dirent_t; + +typedef struct { + uint8_t encoding; /* 0 */ + uint8_t width; /* 1 */ + uint16_t n_nulls; /* 2 */ + uint16_t flags; /* 4 */ + uint16_t rsv0; /* 6 */ + uint64_t payload_off; /* 8 */ + uint64_t payload_bytes; /* 16 */ + uint32_t rsv1; /* 24 */ + uint32_t rsv2; /* 28 */ + int64_t min; /* 32 */ + int64_t max; /* 40 */ +} ray_enc_desc_t; + +#define ENC_OFF(T, f, o) _Static_assert(offsetof(T, f) == (o), #T "." #f " offset") +_Static_assert(sizeof(ray_enc_hdr_t) == 64, "enc header is 64 bytes"); +ENC_OFF(ray_enc_hdr_t, magic, 0); +ENC_OFF(ray_enc_hdr_t, header_version, 4); +ENC_OFF(ray_enc_hdr_t, index_kind, 6); +ENC_OFF(ray_enc_hdr_t, col_flags, 7); +ENC_OFF(ray_enc_hdr_t, rsv0, 8); +ENC_OFF(ray_enc_hdr_t, rsv1, 12); +ENC_OFF(ray_enc_hdr_t, side_len, 24); +ENC_OFF(ray_enc_hdr_t, rsv2, 40); +ENC_OFF(ray_enc_hdr_t, rsv3, 44); +ENC_OFF(ray_enc_dirent_t, offset, 0); +ENC_OFF(ray_enc_dirent_t, bytes, 8); +ENC_OFF(ray_enc_dirent_t, min, 16); +ENC_OFF(ray_enc_dirent_t, max, 24); +ENC_OFF(ray_enc_dirent_t, sum_lo, 32); +ENC_OFF(ray_enc_dirent_t, sum_hi, 40); +ENC_OFF(ray_enc_dirent_t, rsv0, 48); +ENC_OFF(ray_enc_dirent_t, rsv1, 60); +ENC_OFF(ray_enc_desc_t, encoding, 0); +ENC_OFF(ray_enc_desc_t, width, 1); +ENC_OFF(ray_enc_desc_t, n_nulls, 2); +ENC_OFF(ray_enc_desc_t, flags, 4); +ENC_OFF(ray_enc_desc_t, rsv0, 6); +ENC_OFF(ray_enc_desc_t, payload_bytes, 16); +ENC_OFF(ray_enc_desc_t, rsv1, 24); +ENC_OFF(ray_enc_desc_t, rsv2, 28); +ENC_OFF(ray_enc_desc_t, max, 40); +_Static_assert(RAY_ENC_DESC_AREA == RAY_ENC_VECS_PER_CHUNK * sizeof(ray_enc_desc_t), + "descriptor area is 64 descriptors"); +_Static_assert(offsetof(ray_enc_hdr_t, side_off) == 16, "side_off at 16"); +_Static_assert(offsetof(ray_enc_hdr_t, index_off) == 32, "index_off at 32"); +_Static_assert(offsetof(ray_enc_hdr_t, str_pool_bytes) == 48, "str_pool_bytes at 48"); +_Static_assert(offsetof(ray_enc_hdr_t, end_off) == 56, "end_off at 56"); +_Static_assert(sizeof(ray_enc_dirent_t) == 64, "directory entry is 64 bytes"); +_Static_assert(offsetof(ray_enc_dirent_t, null_count) == 52, "null_count at 52"); +_Static_assert(offsetof(ray_enc_dirent_t, flags) == 56, "flags at 56"); +_Static_assert(sizeof(ray_enc_desc_t) == 48, "descriptor is 48 bytes"); +_Static_assert(offsetof(ray_enc_desc_t, payload_off) == 8, "payload_off at 8"); +_Static_assert(offsetof(ray_enc_desc_t, min) == 32, "desc min at 32"); + +/* Generation of a file from its first 32 bytes (the pair order, aux[0..3]): + * (2, "XENC") -> 2; (0, 0 or "XIDX") -> 0; + * (0, anything else) and (2, not "XENC") -> RAY_ENC_GEN_CORRUPT; + * any other order byte -> RAY_ENC_GEN_VERSION. */ +static inline int ray_col_gen_of(const void* file_header) { + const uint8_t* p = (const uint8_t*)file_header; + uint32_t aux0; + memcpy(&aux0, p, 4); + uint8_t order = p[17]; + /* "XENC" is compared as bytes so a big-endian host still recognises + * generation 2 and answers nyi (ray_enccol_open), not corrupt. */ + if (order == RAY_ENC_GEN) return memcmp(p, "XENC", 4) == 0 ? 2 : RAY_ENC_GEN_CORRUPT; + if (order == 0) return (aux0 == 0 || aux0 == RAY_ENC_XIDX) ? 0 : RAY_ENC_GEN_CORRUPT; + return RAY_ENC_GEN_VERSION; +} + +/* Whether this build can read generation 2 (little-endian hosts only). */ +static inline int ray_enc_gen2_supported(void) { return RAY_ENC_LE; } + +static inline uint64_t ray_enc_pad8(uint64_t x) { return (x + 7) & ~(uint64_t)7; } +static inline uint64_t ray_enc_pad32(uint64_t x) { return (x + 31) & ~(uint64_t)31; } +static inline int64_t ray_enc_nchunks(int64_t len) { + return len <= 0 ? 0 : (int64_t)(((uint64_t)len + RAY_ENC_CHUNK - 1) / RAY_ENC_CHUNK); +} +static inline int64_t ray_enc_nvecs(int64_t len) { + return len <= 0 ? 0 : (int64_t)(((uint64_t)len + RAY_ENC_VEC - 1) / RAY_ENC_VEC); +} +/* Length of column-global vector `vec`: 1024 except the column's last. + * Precondition: 0 <= vec < ray_enc_nvecs(len). */ +static inline int ray_enc_vec_len(int64_t len, int64_t vec) { + int64_t rem = len - vec * RAY_ENC_VEC; + return rem >= RAY_ENC_VEC ? RAY_ENC_VEC : (int)rem; +} + +#endif /* RAY_ENCFMT_H */ diff --git a/src/store/encidx.c b/src/store/encidx.c new file mode 100644 index 000000000..5a483277a --- /dev/null +++ b/src/store/encidx.c @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "store/encidx.h" +#include "store/encfmt.h" +#include "store/enccol.h" /* ray_enccol_test_nth_alloc_fails: the materialization fail hook */ +#include "ops/idxop.h" +#include "table/sym.h" +#include "lang/format.h" +#include "core/pool.h" +#include "ops/ops.h" /* RAY_PARALLEL_THRESHOLD */ +#include +#include +#include + +/* ray_enc_idx_kind_has_region (freestanding, numeric) names these kinds. */ +_Static_assert(RAY_IDX_HASH == 1 && RAY_IDX_SORT == 2 && RAY_IDX_BLOOM == 4 && RAY_IDX_PART == 6, + "ray_enc_idx_kind_has_region kinds are HASH, SORT, BLOOM, PART"); +_Static_assert(RAY_IDX_DICT == 7, "ray_enc_idx_kind_in_file names DICT as 7"); + +static const char* ei_kind_name(uint8_t k) { + switch (k) { + case RAY_IDX_HASH: return "HASH"; case RAY_IDX_SORT: return "SORT"; + case RAY_IDX_BLOOM: return "BLOOM"; case RAY_IDX_PART: return "PART"; + case RAY_IDX_DICT: return "DICT"; + default: return "?"; + } +} + +/* Bytes of one PART key of parent type t (SYM: the width class in attrs). */ +static int ei_key_esz(int8_t t, uint8_t attrs) { + switch (t) { + case RAY_BOOL: case RAY_U8: return 1; + case RAY_I16: return 2; + case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_F32: return 4; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: return 8; + case RAY_SYM: return ray_sym_elem_size(RAY_SYM, attrs); + default: return 0; + } +} + +/* The normalized layout (Decisions): child i at pad32 of the previous end + * starting at 96, the name block last, the region ending at pad32. False + * when the layout would pass EI_LAYOUT_MAX: every sum and pad stays below + * 2^63, so offsets compare as int64 and nothing wraps. */ +typedef struct { uint64_t off[4], bytes[4]; uint64_t name_off, end; } ei_layout_t; + +#define EI_LAYOUT_MAX (UINT64_MAX / 2) + +static bool ei_layout(int n, const uint64_t* bytes, uint32_t name_len, ei_layout_t* L) { + uint64_t cur = RAY_ENC_IDX_FIRST_CHILD; /* invariant: cur <= EI_LAYOUT_MAX */ + for (int i = 0; i < n; i++) { + /* compared before padding, which adds at most 31 */ + if (cur > EI_LAYOUT_MAX - 31 || bytes[i] > EI_LAYOUT_MAX - 31 - cur) return false; + L->off[i] = ray_enc_pad32(cur); + L->bytes[i] = bytes[i]; + cur = L->off[i] + bytes[i]; + } + if (cur > EI_LAYOUT_MAX - 31 - 8 - (uint64_t)name_len) return false; + if (name_len) { L->name_off = ray_enc_pad32(cur); cur = L->name_off + 8 + name_len; } + else L->name_off = 0; + L->end = ray_enc_pad32(cur); + return true; +} + +/* The scalar rules of spec "Index region" over a root's counts: the + * writer refuses (nyi) a source breaking one. */ +typedef enum { + EI_RULE_OK = 0, + EI_RULE_HASH_NG, EI_RULE_HASH_NK, EI_RULE_HASH_POW2, EI_RULE_HASH_FULL, EI_RULE_HASH_BIG, + EI_RULE_HASH_CAP, + EI_RULE_BLOOM_POW2, EI_RULE_BLOOM_K, EI_RULE_BLOOM_NK, EI_RULE_BLOOM_M, + EI_RULE_PART_NP, EI_RULE_LEN, +} ei_rule_t; + +static const char* ei_rule_text(ei_rule_t r) { + switch (r) { + case EI_RULE_HASH_NG: return "HASH n_groups negative or above n_keys"; + case EI_RULE_HASH_NK: return "HASH n_keys above the column's rows"; + case EI_RULE_HASH_POW2: return "HASH bucket count is not a power of two"; + case EI_RULE_HASH_FULL: return "HASH table has no empty bucket"; + case EI_RULE_HASH_BIG: return "HASH table too large"; + case EI_RULE_HASH_CAP: return "HASH bucket count is not the builder's for n_groups"; + case EI_RULE_BLOOM_POW2: return "BLOOM bit count is not a power of two of at least 8"; + case EI_RULE_BLOOM_K: return "BLOOM k outside 1 .. the builder's maximum"; + case EI_RULE_BLOOM_NK: return "BLOOM n_keys negative or above the column's rows"; + case EI_RULE_BLOOM_M: return "BLOOM bit count is not the builder's for n_keys"; + case EI_RULE_PART_NP: return "PART n_parts outside 1 .. rows (0 only with no rows)"; + case EI_RULE_LEN: return "negative row count"; + default: return ""; + } +} + +/* At most 2^59 buckets (2^62 bytes, past any region): cap * 8 never wraps. */ +#define EI_HASH_CAP_MAX ((uint64_t)1 << 59) + +/* The builders' sizes (src/ops/idxop.c: attach_hash_impl, hash_build_par + * and ray_index_hash_carry_append size the bucket table by distinct keys; + * ray_index_attach_bloom sizes the bits by non-null rows): + * HASH mask + 1 = 8 when n_groups < 4, else next_pow2(2 * n_groups); + * BLOOM m_mask + 1 = 64 when n_keys < 8, else next_pow2(8 * n_keys). + * Callers bound the count first (n_groups < cap <= EI_HASH_CAP_MAX; + * n_keys <= 2^56). */ +static uint64_t ei_pow2_at_least(uint64_t x) { + uint64_t p = 1; + while (p < x) p <<= 1; + return p; +} +static uint64_t ei_hash_cap_for(int64_t ng) { + return ng < 4 ? 8 : ei_pow2_at_least(2 * (uint64_t)ng); +} +static uint64_t ei_bloom_bits_for(int64_t nk) { + return nk < 8 ? 64 : ei_pow2_at_least(8 * (uint64_t)nk); +} + +static ei_rule_t ei_hash_rule(int64_t ng, int64_t nk, uint64_t mask, int64_t len) { + if (len < 0) return EI_RULE_LEN; + if (ng < 0 || ng > nk) return EI_RULE_HASH_NG; + if (nk > len) return EI_RULE_HASH_NK; + uint64_t cap = mask + 1; + if (cap == 0 || (cap & (cap - 1))) return EI_RULE_HASH_POW2; + if (cap <= (uint64_t)ng) return EI_RULE_HASH_FULL; + if (cap > EI_HASH_CAP_MAX) return EI_RULE_HASH_BIG; + if (cap != ei_hash_cap_for(ng)) return EI_RULE_HASH_CAP; /* ng < cap <= 2^59 */ + return EI_RULE_OK; +} +static ei_rule_t ei_bloom_rule(uint64_t m_mask, uint32_t k, int64_t nk, int64_t len) { + if (len < 0) return EI_RULE_LEN; + uint64_t m = m_mask + 1; + if (m < 8 || (m & (m - 1))) return EI_RULE_BLOOM_POW2; + if (k < 1 || k > RAY_ENC_IDX_BLOOM_K_MAX) return EI_RULE_BLOOM_K; + if (nk < 0 || nk > len) return EI_RULE_BLOOM_NK; + /* past 2^56 keys the bits pass 2^59 bytes: no region holds them */ + if (nk > ((int64_t)1 << 56) || m != ei_bloom_bits_for(nk)) return EI_RULE_BLOOM_M; + return EI_RULE_OK; +} +static ei_rule_t ei_part_rule(int64_t np, int64_t len) { + if (len < 0) return EI_RULE_LEN; + if (np < 0 || np > len || (np == 0) != (len == 0)) return EI_RULE_PART_NP; + return EI_RULE_OK; +} + +static bool ei_put(FILE* f, const void* p, size_t n, uint64_t* pos) { + if (n && fwrite(p, 1, n, f) != n) return false; + *pos += n; + return true; +} +static bool ei_zero(FILE* f, uint64_t upto, uint64_t* pos) { + static const uint8_t z[256]; + while (*pos < upto) { + size_t k = upto - *pos < sizeof z ? (size_t)(upto - *pos) : sizeof z; + if (!ei_put(f, z, k, pos)) return false; + } + return true; +} + +int64_t ray_enc_index_trusted_order(const ray_t* root) { + if (!root || RAY_IS_ERR(root) || root->type != RAY_INDEX) return -1; + const ray_index_t* ix = ray_index_payload((ray_t*)root); + if (ix->markers & RAY_MARK_MMAP) return -1; /* generation-0 passenger */ + if (ix->kind == RAY_IDX_HASH) return ix->u.hash.order_sym; + if (ix->kind == RAY_IDX_PART) return ix->u.part.order_sym; + return -1; +} + +#define EI_NYI(...) do { return ray_error("nyi", __VA_ARGS__); } while (0) + +static bool ei_child_ok(const ray_t* c, int8_t type, int64_t n) { + return c && !RAY_IS_ERR(c) && c->type == type && c->len == n; +} + +static ray_t* ei_index_write(FILE* f, const ray_enc_idx_src_t* s, const ray_index_t* ix, uint64_t* bytes) { + uint8_t kind = ix->kind; + if (!ray_enc_idx_kind_has_region(kind)) + EI_NYI("index region: kind %u has no region", kind); + if (!ray_index_kind_admits((ray_idx_kind_t)kind, s->parent_type) || + ix->parent_type != s->parent_type || ix->built_for_len != s->len) + EI_NYI("index region: %s on type %s is not admitted", ei_kind_name(kind), ray_type_name(s->parent_type)); + uint8_t root[RAY_ENC_IDX_FIRST_CHILD]; + memset(root, 0, sizeof root); + root[0] = (uint8_t)s->parent_type; + memcpy(root + 8, &s->len, 8); + const ray_t* ch[4] = { NULL, NULL, NULL, NULL }; + uint64_t cb[4] = { 0, 0, 0, 0 }; + int nch = 0; + /* Only HASH and PART carry order_name; a name that is empty, too long + * or holding a NUL is written as -1. */ + uint32_t nlen = ((kind == RAY_IDX_HASH || kind == RAY_IDX_PART) && s->order_name && + s->order_len >= 1 && s->order_len <= RAY_ENC_IDX_NAME_MAX && + !memchr(s->order_name, 0, s->order_len)) ? s->order_len : 0; + int kesz = 0; + switch (kind) { + case RAY_IDX_HASH: { + uint64_t cap = ix->u.hash.mask + 1; + int64_t ng = ix->u.hash.n_groups, nk = ix->u.hash.n_keys; + ei_rule_t r = ei_hash_rule(ng, nk, ix->u.hash.mask, s->len); + if (r) EI_NYI("index region: %s", ei_rule_text(r)); + if (!ei_child_ok(ix->u.hash.table, RAY_I64, (int64_t)cap) || + !ei_child_ok(ix->u.hash.gkeys, RAY_I64, ng) || !ei_child_ok(ix->u.hash.offs, RAY_I64, ng + 1) || + !ei_child_ok(ix->u.hash.rows, RAY_I64, nk)) + EI_NYI("index region: HASH child of the wrong type or length"); + ch[0] = ix->u.hash.table; ch[1] = ix->u.hash.gkeys; ch[2] = ix->u.hash.offs; ch[3] = ix->u.hash.rows; + cb[0] = cap * 8; cb[1] = (uint64_t)ng * 8; cb[2] = (uint64_t)(ng + 1) * 8; cb[3] = (uint64_t)nk * 8; + nch = 4; + break; + } + case RAY_IDX_SORT: + if (!ei_child_ok(ix->u.sort.perm, RAY_I64, s->len)) EI_NYI("index region: SORT child of the wrong type or length"); + ch[0] = ix->u.sort.perm; cb[0] = (uint64_t)s->len * 8; nch = 1; + break; + case RAY_IDX_BLOOM: { + uint64_t m = ix->u.bloom.m_mask + 1; + ei_rule_t r = ei_bloom_rule(ix->u.bloom.m_mask, ix->u.bloom.k, ix->u.bloom.n_keys, s->len); + if (r) EI_NYI("index region: %s", ei_rule_text(r)); + if (!ei_child_ok(ix->u.bloom.bits, RAY_U8, (int64_t)(m / 8))) + EI_NYI("index region: BLOOM child of the wrong type or length"); + ch[0] = ix->u.bloom.bits; cb[0] = m / 8; nch = 1; + break; + } + default: { /* PART */ + int64_t np = ix->u.part.n_parts; + ei_rule_t r = ei_part_rule(np, s->len); + if (r) EI_NYI("index region: %s", ei_rule_text(r)); + kesz = ei_key_esz(s->parent_type, s->attrs); + if (!kesz || !ei_child_ok(ix->u.part.keys, s->parent_type, np) || + !ei_child_ok(ix->u.part.starts, RAY_I64, np) || !ei_child_ok(ix->u.part.lens, RAY_I64, np)) + EI_NYI("index region: PART child of the wrong type or length"); + if (s->parent_type == RAY_SYM && kesz < 8) { + /* A key id past the column's width class would be truncated; + * checked before the first byte is written. */ + const ray_t* kv = ix->u.part.keys; + for (int64_t j = 0; j < np; j++) + if ((uint64_t)ray_read_sym(ray_data((ray_t*)kv), j, RAY_SYM, kv->attrs) >> (8 * kesz)) + EI_NYI("index region: PART key wider than the column's symbol width"); + } + ch[0] = ix->u.part.keys; ch[1] = ix->u.part.starts; ch[2] = ix->u.part.lens; + cb[0] = (uint64_t)np * (uint64_t)kesz; cb[1] = cb[2] = (uint64_t)np * 8; + nch = 3; + break; + } + } + ei_layout_t L; + if (!ei_layout(nch, cb, nlen, &L)) EI_NYI("index region: %s too large", ei_kind_name(kind)); + int64_t name_field = nlen ? (int64_t)L.name_off : -1; + uint8_t* ka = root + 16; + switch (kind) { + case RAY_IDX_HASH: { + ray_enc_idx_hash_t h = { (int64_t)L.off[0], (int64_t)L.off[1], (int64_t)L.off[2], (int64_t)L.off[3], + ix->u.hash.mask, ix->u.hash.n_keys, ix->u.hash.n_groups, name_field }; + memcpy(ka, &h, sizeof h); + break; + } + case RAY_IDX_SORT: { ray_enc_idx_sort_t so = { (int64_t)L.off[0] }; memcpy(ka, &so, sizeof so); break; } + case RAY_IDX_BLOOM: { + ray_enc_idx_bloom_t b = { (int64_t)L.off[0], ix->u.bloom.m_mask, ix->u.bloom.k, 0, ix->u.bloom.n_keys }; + memcpy(ka, &b, sizeof b); + break; + } + default: { + ray_enc_idx_part_t p = { (int64_t)L.off[0], (int64_t)L.off[1], (int64_t)L.off[2], ix->u.part.n_parts, name_field }; + memcpy(ka, &p, sizeof p); + break; + } + } + uint64_t pos = 0; + if (!ei_put(f, root, sizeof root, &pos)) return ray_error("io", "index region: short write"); + for (int i = 0; i < nch; i++) { + if (!ei_zero(f, L.off[i], &pos)) return ray_error("io", "index region: short write"); + const ray_t* c = ch[i]; + if (kind == RAY_IDX_PART && i == 0 && s->parent_type == RAY_SYM) { + /* SYM keys are written at the column's width class (Decisions). */ + uint8_t buf[4096]; + int64_t per = (int64_t)sizeof buf / kesz; + for (int64_t at = 0; at < c->len; at += per) { + int64_t k = c->len - at < per ? c->len - at : per; + for (int64_t j = 0; j < k; j++) + ray_write_sym(buf, j, (uint64_t)ray_read_sym(ray_data((ray_t*)c), at + j, RAY_SYM, c->attrs), + RAY_SYM, s->attrs); + if (!ei_put(f, buf, (size_t)(k * kesz), &pos)) return ray_error("io", "index region: short write"); + } + } else if (!ei_put(f, ray_data((ray_t*)c), (size_t)L.bytes[i], &pos)) { + return ray_error("io", "index region: short write"); + } + } + if (nlen) { + if (!ei_zero(f, L.name_off, &pos)) return ray_error("io", "index region: short write"); + uint32_t hdr[2] = { nlen, 0 }; + if (!ei_put(f, hdr, 8, &pos) || !ei_put(f, s->order_name, nlen, &pos)) + return ray_error("io", "index region: short write"); + } + if (!ei_zero(f, L.end, &pos)) return ray_error("io", "index region: short write"); + *bytes = pos; + return NULL; +} + +ray_t* ray_enc_index_write(FILE* f, const ray_enc_idx_src_t* s, uint64_t* bytes) { + *bytes = 0; + if (!ray_enc_gen2_supported()) EI_NYI("index region: generation 2 needs a little-endian host"); + if (!s->root || RAY_IS_ERR(s->root) || s->root->type != RAY_INDEX) + return ray_error("type", "index region: not an index object"); + const ray_index_t* ix = ray_index_payload((ray_t*)s->root); + if (ix->kind != RAY_IDX_HASH) return ei_index_write(f, s, ix, bytes); + /* A HASH region stores the generation-1 layout (I64 arrays, the low-bits + * home rule, groups by first occurrence): an index built narrow or under + * the high-bits rule (RAY_MARK_HASH_HIGH) is written as that layout, so + * the region's bytes do not depend on the builder. */ + ray_index_t lx = *ix; + if (!ray_index_hash_legacy(ix, &lx.u.hash.table, &lx.u.hash.gkeys, &lx.u.hash.offs, &lx.u.hash.rows)) + return ei_index_write(f, s, ix, bytes); /* no arrays to lay out: the writer's own refusal */ + lx.markers &= (uint8_t)~RAY_MARK_HASH_HIGH; + ray_t* err = ei_index_write(f, s, &lx, bytes); + ray_release(lx.u.hash.table); + ray_release(lx.u.hash.gkeys); + ray_release(lx.u.hash.offs); + ray_release(lx.u.hash.rows); + return err; +} + +/* ===== DICT (P6b, spec "Index region": DICT) ===== + * + * The region: the 80-byte root (parent_type STR, built_for_len, the DICT + * kind fields), then four children at pad32 offsets from 96: codes (I32, + * len), first_occ (I32, n_distinct), offs (u64, n_distinct + 1, the last + * the terminal bytes_len) and the entry bytes (bytes_len), the region + * ending at pad32. Every pad byte is zero. */ + +/* The count and offset rules: the writer refuses a source breaking one + * (nyi). See the writer's header comment. */ +static const char* ei_dict_rule(int64_t len, int64_t nd, const uint64_t* offs, uint64_t bytes_len) { + if (len < 1 || len > INT32_MAX) return "rows outside 1 .. INT32_MAX"; + if (nd < 1 || nd > len) return "n_distinct outside 1 .. rows"; + if (offs[0] != 0) return "offsets not starting at 0"; + for (int64_t c = 0; c < nd; c++) { + uint64_t end = c + 1 < nd ? offs[c + 1] : bytes_len; + if (end < offs[c] || end - offs[c] > UINT32_MAX) return "offsets decreasing or an entry over UINT32_MAX bytes"; + } + return NULL; +} + +ray_t* ray_enc_dict_write(FILE* f, const ray_enc_dict_src_t* s, uint64_t* bytes) { + *bytes = 0; + if (!ray_enc_gen2_supported()) EI_NYI("index region: generation 2 needs a little-endian host"); + const char* why = ei_dict_rule(s->len, s->n_distinct, s->offs, s->bytes_len); + if (why) EI_NYI("index region: DICT %s", why); + const uint64_t nd = (uint64_t)s->n_distinct; + uint64_t cb[4] = { (uint64_t)s->len * 4, nd * 4, (nd + 1) * 8, s->bytes_len }; + ei_layout_t L; + if (!ei_layout(4, cb, 0, &L)) EI_NYI("index region: DICT too large"); + for (int i = 0; i < 4; i++) /* a 32-bit host: every child's size fits a size_t */ + if ((uint64_t)(size_t)cb[i] != cb[i]) EI_NYI("index region: DICT too large"); + uint8_t root[RAY_ENC_IDX_FIRST_CHILD]; + memset(root, 0, sizeof root); + root[0] = (uint8_t)RAY_STR; + memcpy(root + 8, &s->len, 8); + ray_enc_idx_dict_t d = { (int64_t)L.off[0], (int64_t)L.off[1], (int64_t)L.off[2], (int64_t)L.off[3], + s->n_distinct, s->bytes_len }; + memcpy(root + 16, &d, sizeof d); + uint64_t pos = 0; + #define EI_PUT(p, n) do { if (!ei_put(f, (p), (n), &pos)) return ray_error("io", "index region: short write"); } while (0) + #define EI_PAD(to) do { if (!ei_zero(f, (to), &pos)) return ray_error("io", "index region: short write"); } while (0) + EI_PUT(root, sizeof root); + EI_PAD(L.off[0]); EI_PUT(s->codes, (size_t)cb[0]); + EI_PAD(L.off[1]); EI_PUT(s->first_occ, (size_t)cb[1]); + EI_PAD(L.off[2]); EI_PUT(s->offs, (size_t)cb[2] - 8); EI_PUT(&s->bytes_len, 8); /* the terminal offset */ + EI_PAD(L.off[3]); if (s->bytes_len) EI_PUT(s->bytes, (size_t)s->bytes_len); + EI_PAD(L.end); + #undef EI_PUT + #undef EI_PAD + *bytes = pos; + return NULL; +} + +/* ===== Reading a region we wrote ===== + * + * The region is taken as written: the root names every child's offset and + * count. Every read goes through memcpy, so the caller's base alignment + * never matters. */ + +static int64_t ev_i64(const uint8_t* p) { int64_t x; memcpy(&x, p, 8); return x; } + +/* ---- DICT: the root fields and the children's places ---- */ +void ray_enc_dict_parse(const uint8_t* b, ray_enc_dict_view_t* v) { + ray_enc_idx_dict_t d; memcpy(&d, b + 16, sizeof d); + v->len = ev_i64(b + 8); v->n_distinct = d.n_distinct; + v->codes = (const int32_t*)(b + d.codes); v->first_occ = (const int32_t*)(b + d.first_occ); + v->offs = (const uint64_t*)(b + d.offs); v->bytes = b + d.bytes; +} + +/* ---- HASH / SORT / BLOOM / PART: the kind's fields and the name ---- */ +void ray_enc_index_view(const uint8_t* b, uint64_t size, uint8_t kind, int8_t pt, uint8_t attrs, int64_t len, + ray_enc_idx_view_t* v) { + memset(v, 0, sizeof *v); + v->kind = kind; v->parent_type = pt; v->attrs = attrs; v->len = len; v->base = b; v->size = size; + const uint8_t* ka = b + 16; + int64_t name_field = -1; + switch (kind) { + case RAY_IDX_HASH: memcpy(&v->hash, ka, sizeof v->hash); name_field = v->hash.order_name; break; + case RAY_IDX_SORT: memcpy(&v->sort, ka, sizeof v->sort); break; + case RAY_IDX_BLOOM: memcpy(&v->bloom, ka, sizeof v->bloom); break; + default: memcpy(&v->part, ka, sizeof v->part); name_field = v->part.order_name; break; + } + if (name_field != -1) { + uint32_t nlen; memcpy(&nlen, b + name_field, 4); + v->order_name = (const char*)(b + name_field + 8); v->order_len = nlen; + } +} + +/* ===== Parse (spec "Materialization" step 2) ===== + * + * A view becomes a fresh heap root: the ray_index_t is rebuilt field by + * field and every child is copied out of the region, so nothing in the + * root refers to the mapping and the root outlives it. */ + +/* A large child is copied over the pool in pieces of EP_PIECE bytes (the + * copy's page faults are most of its cost); a piece the pool skipped on + * cancel is copied here, so the copy is always whole. */ +#define EP_PIECE ((size_t)1 << 20) +typedef struct { uint8_t* dst; const uint8_t* src; size_t n; _Atomic(bool)* done; } ep_par_copy_t; +static void ep_copy_piece(void* ctx, uint32_t wid, int64_t i0, int64_t i1) { + (void)wid; + ep_par_copy_t* x = ctx; + for (int64_t i = i0; i < i1; i++) { + size_t at = (size_t)i * EP_PIECE, k = x->n - at < EP_PIECE ? x->n - at : EP_PIECE; + memcpy(x->dst + at, x->src + at, k); + atomic_store_explicit(&x->done[i], true, memory_order_release); + } +} +static void ep_memcpy(uint8_t* dst, const uint8_t* src, size_t n) { + size_t np = (n + EP_PIECE - 1) / EP_PIECE; + ray_pool_t* tp = ray_pool_get(); + _Atomic(bool)* done = NULL; + if (np >= 4 && np <= RAY_POOL_INIT_TASKS && ray_pool_par_dispatch_ok(tp, (int64_t)np, 4)) + done = ray_calloc_raw(np * sizeof *done); + if (!done) { memcpy(dst, src, n); return; } + ep_par_copy_t x = { dst, src, n, done }; + ray_pool_dispatch_n(tp, ep_copy_piece, &x, (uint32_t)np); + for (size_t i = 0; i < np; i++) + if (!atomic_load_explicit(&done[i], memory_order_acquire)) ep_copy_piece(&x, 0, (int64_t)i, (int64_t)i + 1); + ray_free_raw(done); +} + +/* A heap vector of `type` holding n elements copied from p; NULL on oom. */ +static ray_t* ep_copy(int8_t type, const uint8_t* p, int64_t n, size_t esz) { + if (ray_enccol_test_nth_alloc_fails()) return NULL; + ray_t* c = ray_vec_new(type, n > 0 ? n : 1); + if (!c) return NULL; + if (RAY_IS_ERR(c)) { ray_error_free(c); return NULL; } + c->len = n; + if (n) ep_memcpy(ray_data(c), p, (size_t)n * esz); + return c; +} + +ray_t* ray_enc_index_parse(const ray_enc_idx_view_t* v, ray_t* vec, ray_t** root_out) { + *root_out = NULL; + const uint8_t* b = v->base; + int kesz = v->kind == RAY_IDX_PART ? ei_key_esz(v->parent_type, v->attrs) : 0; + /* SYM PART keys resolve over the decoded column's domain. */ + if (v->kind == RAY_IDX_PART && v->parent_type == RAY_SYM && (!vec || RAY_IS_ERR(vec) || vec->type != RAY_SYM)) + return ray_error("type", "index parse: SYM PART keys need the decoded SYM column"); + + ray_t* root = ray_enccol_test_nth_alloc_fails() ? NULL + : ray_index_new_root((ray_idx_kind_t)v->kind, v->parent_type, v->len); + if (!root || RAY_IS_ERR(root)) { + if (root) ray_error_free(root); + return ray_error("oom", "index parse"); + } + ray_index_t* ix = ray_index_payload(root); + bool ok; + switch (v->kind) { + case RAY_IDX_HASH: + ix->u.hash.mask = v->hash.mask; ix->u.hash.n_keys = v->hash.n_keys; + ix->u.hash.n_groups = v->hash.n_groups; ix->u.hash.order_sym = -1; + ok = (ix->u.hash.table = ep_copy(RAY_I64, b + v->hash.table, (int64_t)(v->hash.mask + 1), 8)) && + (ix->u.hash.gkeys = ep_copy(RAY_I64, b + v->hash.gkeys, v->hash.n_groups, 8)) && + (ix->u.hash.offs = ep_copy(RAY_I64, b + v->hash.offs, v->hash.n_groups + 1, 8)) && + (ix->u.hash.rows = ep_copy(RAY_I64, b + v->hash.rows, v->hash.n_keys, 8)); + break; + case RAY_IDX_SORT: + ok = (ix->u.sort.perm = ep_copy(RAY_I64, b + v->sort.perm, v->len, 8)) != NULL; + break; + case RAY_IDX_BLOOM: + ix->u.bloom.m_mask = v->bloom.m_mask; ix->u.bloom.k = v->bloom.k; ix->u.bloom.n_keys = v->bloom.n_keys; + ok = (ix->u.bloom.bits = ep_copy(RAY_U8, b + v->bloom.bits, (int64_t)((v->bloom.m_mask + 1) / 8), 1)) != NULL; + break; + default: { + int64_t np = v->part.n_parts; + ix->u.part.n_parts = np; ix->u.part.order_sym = -1; + if (v->parent_type == RAY_SYM) { + /* the column's width class, as written; ids are positions in + * the column's domain */ + ray_t* k = ray_enccol_test_nth_alloc_fails() ? NULL + : ray_sym_vec_new(v->attrs & RAY_SYM_W_MASK, np > 0 ? np : 1); + if (k && RAY_IS_ERR(k)) { ray_error_free(k); k = NULL; } + if (k) { + k->len = np; + if (np) memcpy(ray_data(k), b + v->part.keys, (size_t)np * (size_t)kesz); + ray_sym_vec_adopt_domain(k, vec); + } + ix->u.part.keys = k; + } else { + ix->u.part.keys = ep_copy(v->parent_type, b + v->part.keys, np, (size_t)kesz); + } + ok = ix->u.part.keys && + (ix->u.part.starts = ep_copy(RAY_I64, b + v->part.starts, np, 8)) && + (ix->u.part.lens = ep_copy(RAY_I64, b + v->part.lens, np, 8)); + break; + } + } + /* order_name: interned in this process (HASH and PART carry one) */ + if (ok && v->order_name && (v->kind == RAY_IDX_HASH || v->kind == RAY_IDX_PART)) { + int64_t id = ray_sym_intern(v->order_name, v->order_len); + if (id < 0) ok = false; + else if (v->kind == RAY_IDX_HASH) ix->u.hash.order_sym = id; + else ix->u.part.order_sym = id; + } + if (!ok) { ray_release(root); return ray_error("oom", "index parse"); } /* releases the set children */ + *root_out = root; + return NULL; +} diff --git a/src/store/encidx.h b/src/store/encidx.h new file mode 100644 index 000000000..dd29310d8 --- /dev/null +++ b/src/store/encidx.h @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_ENCIDX_H +#define RAY_ENCIDX_H + +/* Generation-2 index region (spec "Index region"). Little-endian and + * ABI-independent: never a copy of ray_index_t, never an address. The + * part above RAY_ENC_IDX_WIRE_ONLY is freestanding (stdint / stddef only) + * so the wasm32 layout check compiles it. */ + +#include +#include + +#define RAY_ENC_IDX_ROOT_BYTES 80 +#define RAY_ENC_IDX_FIRST_CHILD 96 /* pad32(80): children start here */ +#define RAY_ENC_IDX_NAME_MAX 255 /* order_name: a column (file) name */ +#define RAY_ENC_IDX_BLOOM_K_MAX 3 /* k of ray_index_attach_bloom */ + +typedef struct { + int8_t parent_type; /* 0 the column's logical type */ + uint8_t rsv[7]; /* 1 */ + int64_t built_for_len; /* 8 */ + uint8_t kind_area[64]; /* 16 the kind's fields, unused tail zero */ +} ray_enc_idx_root_t; + +typedef struct { /* HASH, in kind_area */ + int64_t table, gkeys, offs, rows; + uint64_t mask; + int64_t n_keys, n_groups, order_name; +} ray_enc_idx_hash_t; + +typedef struct { int64_t perm; } ray_enc_idx_sort_t; + +typedef struct { /* BLOOM */ + int64_t bits; + uint64_t m_mask; + uint32_t k; + uint32_t rsv; + int64_t n_keys; +} ray_enc_idx_bloom_t; + +typedef struct { /* PART */ + int64_t keys, starts, lens, n_parts, order_name; +} ray_enc_idx_part_t; + +typedef struct { /* DICT, in kind_area (P6b) */ + int64_t codes, first_occ, offs, bytes, n_distinct; + uint64_t bytes_len; +} ray_enc_idx_dict_t; /* 48 bytes */ + +#define ENCIDX_OFF(T, f, o) _Static_assert(offsetof(T, f) == (o), #T "." #f " offset") +_Static_assert(sizeof(ray_enc_idx_root_t) == RAY_ENC_IDX_ROOT_BYTES, "wire root is 80 bytes"); +_Static_assert(RAY_ENC_IDX_FIRST_CHILD == ((RAY_ENC_IDX_ROOT_BYTES + 31) & ~31), + "children start at pad32 of the root"); +ENCIDX_OFF(ray_enc_idx_root_t, parent_type, 0); +ENCIDX_OFF(ray_enc_idx_root_t, rsv, 1); +ENCIDX_OFF(ray_enc_idx_root_t, built_for_len, 8); +ENCIDX_OFF(ray_enc_idx_root_t, kind_area, 16); +_Static_assert(sizeof(((ray_enc_idx_root_t*)0)->kind_area) == 64, "kind area is 64 bytes"); + +_Static_assert(sizeof(ray_enc_idx_hash_t) == 64, "HASH fills the kind area"); +ENCIDX_OFF(ray_enc_idx_hash_t, table, 0); +ENCIDX_OFF(ray_enc_idx_hash_t, gkeys, 8); +ENCIDX_OFF(ray_enc_idx_hash_t, offs, 16); +ENCIDX_OFF(ray_enc_idx_hash_t, rows, 24); +ENCIDX_OFF(ray_enc_idx_hash_t, mask, 32); +ENCIDX_OFF(ray_enc_idx_hash_t, n_keys, 40); +ENCIDX_OFF(ray_enc_idx_hash_t, n_groups, 48); +ENCIDX_OFF(ray_enc_idx_hash_t, order_name, 56); + +_Static_assert(sizeof(ray_enc_idx_sort_t) == 8, "SORT kind fields"); +ENCIDX_OFF(ray_enc_idx_sort_t, perm, 0); + +_Static_assert(sizeof(ray_enc_idx_bloom_t) == 32, "BLOOM kind fields"); +ENCIDX_OFF(ray_enc_idx_bloom_t, bits, 0); +ENCIDX_OFF(ray_enc_idx_bloom_t, m_mask, 8); +ENCIDX_OFF(ray_enc_idx_bloom_t, k, 16); +ENCIDX_OFF(ray_enc_idx_bloom_t, rsv, 20); +ENCIDX_OFF(ray_enc_idx_bloom_t, n_keys, 24); + +_Static_assert(sizeof(ray_enc_idx_part_t) == 40, "PART kind fields"); +ENCIDX_OFF(ray_enc_idx_part_t, keys, 0); +ENCIDX_OFF(ray_enc_idx_part_t, starts, 8); +ENCIDX_OFF(ray_enc_idx_part_t, lens, 16); +ENCIDX_OFF(ray_enc_idx_part_t, n_parts, 24); +ENCIDX_OFF(ray_enc_idx_part_t, order_name, 32); + +_Static_assert(sizeof(ray_enc_idx_dict_t) == 48, "DICT kind fields"); +ENCIDX_OFF(ray_enc_idx_dict_t, codes, 0); +ENCIDX_OFF(ray_enc_idx_dict_t, first_occ, 8); +ENCIDX_OFF(ray_enc_idx_dict_t, offs, 16); +ENCIDX_OFF(ray_enc_idx_dict_t, bytes, 24); +ENCIDX_OFF(ray_enc_idx_dict_t, n_distinct, 32); +ENCIDX_OFF(ray_enc_idx_dict_t, bytes_len, 40); + +#define ENCIDX_FITS(T) _Static_assert(sizeof(T) <= sizeof(((ray_enc_idx_root_t*)0)->kind_area), \ + #T " fits in the kind area") +ENCIDX_FITS(ray_enc_idx_hash_t); +ENCIDX_FITS(ray_enc_idx_sort_t); +ENCIDX_FITS(ray_enc_idx_bloom_t); +ENCIDX_FITS(ray_enc_idx_part_t); +ENCIDX_FITS(ray_enc_idx_dict_t); + +/* The index kinds that carry a region: HASH, SORT, BLOOM, PART. */ +static inline int ray_enc_idx_kind_has_region(uint8_t k) { + return k == 1 || k == 2 || k == 4 || k == 6; +} + +/* The kinds whose file carries a region after the side data: the + * root-parsed kinds, and DICT (P6b), whose region the column writer builds + * and the reader parses on its own (ray_enc_dict_parse). */ +static inline int ray_enc_idx_kind_in_file(uint8_t k) { /* a region follows the side data */ + return ray_enc_idx_kind_has_region(k) || k == 7; +} + +#ifndef RAY_ENC_IDX_WIRE_ONLY +#include +#include + +typedef struct { + const ray_t* root; /* RAY_INDEX block: HASH, SORT, BLOOM or PART */ + int8_t parent_type; /* the column's logical type */ + uint8_t attrs; /* the column's persisted attrs (width of SYM PART keys) */ + int64_t len; /* the column's rows */ + const char* order_name; /* NULL: order_name -1 */ + uint32_t order_len; +} ray_enc_idx_src_t; + +/* Stream the normalized region to f at its current position; *bytes is + * the region size (a multiple of 32). NULL, or an owned error: nyi for a + * kind / type the admission matrix refuses or a child of the wrong type + * or length (naming the kind), io on a short write. */ +ray_t* ray_enc_index_write(FILE* f, const ray_enc_idx_src_t* s, uint64_t* bytes); + +/* A region's root fields by kind, the name into the region. */ +typedef struct { + uint8_t kind; + int8_t parent_type; + uint8_t attrs; + int64_t len; + const uint8_t* base; /* the region */ + uint64_t size; + ray_enc_idx_hash_t hash; /* the kind's fields, by kind */ + ray_enc_idx_sort_t sort; + ray_enc_idx_bloom_t bloom; + ray_enc_idx_part_t part; + const char* order_name; /* into the region, or NULL */ + uint32_t order_len; +} ray_enc_idx_view_t; + +/* `size` bytes at `region`, an index of `kind` for a column of + * (parent_type, attrs, len) that rayforce wrote, as a view: the kind's + * fields and the order name, read as written. */ +void ray_enc_index_view(const uint8_t* region, uint64_t size, uint8_t kind, + int8_t parent_type, uint8_t attrs, int64_t len, ray_enc_idx_view_t* out); + +/* A fresh heap RAY_INDEX root from a view, every child copied into a heap + * vector of its slot's type. SYM PART keys adopt the domain of `vec` (the + * decoded column); order_name is interned in this process. NULL with + * *root_out set (owned), or an owned oom error (a SYM PART without a SYM + * `vec` is a type error). Nothing in the root refers to the region, so it + * outlives the mapping. */ +ray_t* ray_enc_index_parse(const ray_enc_idx_view_t* v, ray_t* vec, ray_t** root_out); + +/* order_sym a writer may convert to a name (spec "Writing the index"): + * the root's HASH / PART order_sym when RAY_MARK_MMAP is clear, else -1. */ +int64_t ray_enc_index_trusted_order(const ray_t* root); + +/* ---- DICT (P6b, spec "Index region": DICT) ---- */ + +typedef struct { /* what the writer persists (no ownership) */ + int64_t len, n_distinct; + const int32_t* codes; /* len */ + const int32_t* first_occ; /* n_distinct */ + const uint64_t* offs; /* n_distinct: start of each entry in bytes */ + const char* bytes; /* bytes_len: the entries in code order */ + uint64_t bytes_len; +} ray_enc_dict_src_t; + +typedef struct { /* a region's children: pointers into it */ + int64_t len, n_distinct; + const int32_t* codes; /* len */ + const int32_t* first_occ; /* n_distinct */ + const uint64_t* offs; /* n_distinct + 1 */ + const uint8_t* bytes; /* offs[n_distinct] */ +} ray_enc_dict_view_t; + +/* Stream the DICT region of s to f at its position (spec "Index region", + * DICT); *bytes its size, a multiple of 32. nyi naming DICT for a source + * breaking the count or offset rules (n_distinct outside 1..len, len + * outside 1..INT32_MAX, offsets not starting at 0, decreasing, an entry + * over UINT32_MAX bytes or past bytes_len) or a child too large for this + * host's size_t; io on a short + * write. The first-occurrence rules (first_occ[0] == 0, strictly + * ascending, below len) and the codes' rules are not checked here: the + * writer's caller (ray_encw) gives ray_dict_acc_t's arrays, which hold them + * by construction. */ +ray_t* ray_enc_dict_write(FILE* f, const ray_enc_dict_src_t* s, uint64_t* bytes); + +/* The DICT region at `region` (32-aligned) that rayforce wrote: its root + * fields and its children's places, read as written. */ +void ray_enc_dict_parse(const uint8_t* region, ray_enc_dict_view_t* out); +#endif /* RAY_ENC_IDX_WIRE_ONLY */ + +#endif /* RAY_ENCIDX_H */ diff --git a/src/store/encw.c b/src/store/encw.c new file mode 100644 index 000000000..5f00d2eab --- /dev/null +++ b/src/store/encw.c @@ -0,0 +1,947 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "store/encw.h" +#include "vec/str.h" +#include "ops/idxop.h" /* ray_i128_add */ +#include "mem/heap.h" +#include "ops/hash.h" /* ray_hash_bytes */ +#include "store/col.h" /* COL_DISK_ATTRS_MASK */ +#include "core/platform.h" /* ray_vm_map_anon */ +#include +#include + +#define ENC_F64_CANON 0x7FF8000000000000ull +#define ENC_F32_CANON 0x7FC00000ull +/* The null NaN patterns are the engine's NULL_F64 / NULL_F32 bits. */ +static bool canon_matches(void) { + double d = NULL_F64; float f = NULL_F32; uint64_t b64; uint32_t b32; + memcpy(&b64, &d, 8); memcpy(&b32, &f, 4); + return b64 == ENC_F64_CANON && b32 == ENC_F32_CANON; +} + +bool ray_encw_type_has_dict(int8_t t) { + return t == RAY_I16 || t == RAY_I32 || t == RAY_I64 || + t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP || t == RAY_TIMESPAN || + t == RAY_F32 || t == RAY_F64; +} + +bool ray_encw_type_summable(int8_t t) { + return t == RAY_BOOL || t == RAY_U8 || t == RAY_I16 || t == RAY_I32 || + t == RAY_I64 || t == RAY_TIME; +} + +bool ray_encw_type_supported(int8_t t) { return ray_is_vector_type(t); } + +static _Atomic(int) g_encw_force = -1; +void ray_encw_test_force(int enc) { atomic_store(&g_encw_force, enc); } +static _Atomic(int) g_encw_force_float = -1; +void ray_encw_test_force_float(int enc) { atomic_store(&g_encw_force_float, enc); } +static _Atomic(int) g_encw_force_str = -1; +void ray_encw_test_force_str(int enc) { atomic_store(&g_encw_force_str, enc); } + +void ray_encw_vec_init(ray_encw_vec_t* v) { memset(v, 0, sizeof *v); } +void ray_encw_vec_free(ray_encw_vec_t* v) { ray_enc_buf_free(&v->payload); } + +static void vec_reset(ray_encw_vec_t* o) { + ray_enc_buf_t keep = o->payload; + keep.len = 0; keep.oom = false; + memset(o, 0, sizeof *o); + o->payload = keep; +} + +static ray_err_t put(ray_encw_vec_t* o, const void* p, size_t n) { + return ray_enc_buf_put(&o->payload, p, n) ? RAY_OK : RAY_ERR_OOM; +} +static ray_err_t pad8(ray_encw_vec_t* o) { + return ray_enc_buf_pad8(&o->payload) ? RAY_OK : RAY_ERR_OOM; +} + +/* ---- integer kinds: BOOL, U8, I16, I32, I64, DATE, TIME, TIMESTAMP, SYM ---- */ +static ray_err_t encw_int(int8_t type, uint8_t attrs, const void* data, int64_t start, + int n, const ray_enc_dict_t* dict, ray_encw_vec_t* o) { + ray_enc_input_t* in = ray_alloc_raw(sizeof *in); + if (!in) return RAY_ERR_OOM; + ray_err_t err = RAY_OK; + if (!ray_enc_load(data, type, attrs, start, n, in)) { err = RAY_ERR_NYI; goto out; } + o->n_nulls = in->n_nulls; + bool nullable = type != RAY_BOOL && type != RAY_U8; + bool all_null = nullable && in->n_nulls == n; + if (in->bitmap && in->n_nulls > 0 && (err = put(o, in->nullmap, 128)) != RAY_OK) goto out; + bool have = false; int64_t mn = 0, mx = 0; + bool sum = ray_encw_type_summable(type); + for (int i = 0; i < n; i++) { + bool null = in->bitmap ? ((in->nullmap[i >> 3] >> (i & 7)) & 1) + : (type == RAY_SYM && in->bits[i] == 0); + if (null) continue; + int64_t x = ray_enc_logical(in->bits[i], in->k); + if (!have || x < mn) mn = x; + if (!have || x > mx) mx = x; + have = true; + if (sum) ray_i128_add(&o->sum_hi, &o->sum_lo, x); + } + if (all_null) { + /* Spec "Nulls": an all-null vector is always CONST of the fill (0). */ + o->desc.encoding = RAY_ENC_CONST; + if ((err = put(o, NULL, 8)) != RAY_OK) goto out; + } else { + ray_enc_choice_t c; + int forced = atomic_load(&g_encw_force); + bool ok = forced >= 0 + ? ray_enc_write_as((uint8_t)forced, in->bits, n, in->k, dict, &o->payload, &c) + : ray_enc_write(in->bits, n, in->k, RAY_ENC_SLOT_TOP, 0, dict, &o->payload, &c); + if (!ok) { + err = o->payload.oom ? RAY_ERR_OOM : (forced >= 0 ? RAY_ERR_NYI : RAY_ERR_RANGE); + goto out; + } + o->desc.encoding = c.enc; + o->desc.width = (c.enc == RAY_ENC_FOR_BP || c.enc == RAY_ENC_DELTA_BP) ? c.width : 0; + } + if (have) { o->desc.min = mn; o->desc.max = mx; o->has_stats = true; } + else o->desc.flags |= RAY_ENC_STAT_ABSENT; +out: + ray_free_raw(in); + return err; +} + +/* ---- F32 / F64: NaN nulls in the bitmap, bit-restore trailer ---- */ +/* Float fill (spec "Nulls"): bits of rows [start, start+n), NaN rows set in + * nullmap and filled with the minimum non-null value's bits (first of + * ties), +0.0 when all are null. Returns the null count; vmin / vmax get + * the non-null extrema when has != NULL. The extrema follow the + * generation-0 min/max kernels' rule: strict compare, the first of tied + * values wins (so -0.0 vs +0.0 keeps whichever came first). No NaN is + * left in bits, which the float dictionary order requires. */ +static int float_fill(int8_t type, const void* data, int64_t start, int n, uint64_t* bits, + uint8_t* nullmap, double* vmin, double* vmax, bool* has) { + const bool f32 = type == RAY_F32; + const size_t esz = f32 ? 4 : 8; + int nn = 0; bool have = false; double mn = 0, mx = 0; uint64_t fill = 0; + memset(nullmap, 0, RAY_ENC_VEC / 8); + for (int i = 0; i < n; i++) { + uint64_t b = 0; + memcpy(&b, (const uint8_t*)data + (size_t)(start + i) * esz, esz); + bits[i] = b; + double x; + if (f32) { float f; uint32_t b32 = (uint32_t)b; memcpy(&f, &b32, 4); x = (double)f; } + else memcpy(&x, &b, 8); + if (x != x) { nullmap[i >> 3] |= (uint8_t)(1u << (i & 7)); nn++; continue; } /* every NaN is a null */ + if (!have || x < mn) { mn = x; fill = b; } + if (!have || x > mx) mx = x; + have = true; + } + if (!have) fill = 0; /* all null: +0.0 */ + for (int i = 0; i < n; i++) if ((nullmap[i >> 3] >> (i & 7)) & 1) bits[i] = fill; + if (has) { *has = have; *vmin = mn; *vmax = mx; } + return nn; +} + +/* The forced-encoding test hook's ALP on a column whose first chunk trained + * no candidate: (e, f) = (0, 0), so every value is an integer or an + * exception. Selection never uses it. */ +static const ray_enc_alp_cands_t g_alp00 = { { { 0, 0 } }, 1 }; + +static ray_err_t encw_float(int8_t type, const void* data, int64_t start, int n, + const ray_encw_side_t* side, ray_encw_vec_t* o) { + if (!ray_enc_fp_env_ok()) return RAY_ERR_FPENV; + if (!canon_matches()) return RAY_ERR_RANGE; + const bool f32 = type == RAY_F32; + const size_t esz = f32 ? 4 : 8; + const int T = f32 ? 32 : 64; + const uint64_t canon = f32 ? ENC_F32_CANON : ENC_F64_CANON; + const ray_enc_dict_t* dict = side ? side->dict : NULL; + const ray_enc_alp_cands_t* alp = side ? side->alp : NULL; + uint64_t bits[RAY_ENC_VEC]; + uint8_t nullmap[RAY_ENC_VEC / 8]; + uint16_t tpos[RAY_ENC_VEC]; + uint64_t traw[RAY_ENC_VEC]; + int nt = 0; + for (int i = 0; i < n; i++) { /* trailer: non-canonical NaN payloads, before the fill */ + uint64_t b = 0; + memcpy(&b, (const uint8_t*)data + (size_t)(start + i) * esz, esz); + double x; + if (f32) { float f; uint32_t b32 = (uint32_t)b; memcpy(&f, &b32, 4); x = (double)f; } + else memcpy(&x, &b, 8); + if (x != x && b != canon) { tpos[nt] = (uint16_t)i; traw[nt] = b; nt++; } + } + double vmin = 0, vmax = 0; bool have = false; + o->n_nulls = float_fill(type, data, start, n, bits, nullmap, &vmin, &vmax, &have); + /* The trailer's size counts in every encoding's estimate (spec "Floats"). */ + uint64_t tb = nt ? 8 + ray_enc_pad8(2ull * (uint64_t)nt) + ray_enc_pad8((uint64_t)nt * esz) : 0; + ray_err_t err; + if (o->n_nulls > 0 && (err = put(o, nullmap, 128)) != RAY_OK) return err; + ray_enc_choice_t c; + int forced = atomic_load(&g_encw_force_float); + if (forced < 0) forced = atomic_load(&g_encw_force); + if (o->n_nulls == n) { + /* Spec "Nulls": an all-null vector is always CONST of the fill (+0.0). */ + if (!ray_enc_float_write(RAY_ENC_CONST, bits, n, T, NULL, NULL, &o->payload, &c)) + return o->payload.oom ? RAY_ERR_OOM : RAY_ERR_RANGE; + } else if (forced >= 0) { + const ray_enc_alp_cands_t* ac = forced == RAY_ENC_ALP && (!alp || alp->n == 0) ? &g_alp00 : alp; + if (forced > UINT8_MAX || + !ray_enc_float_write((uint8_t)forced, bits, n, T, dict, ac, &o->payload, &c)) + return o->payload.oom ? RAY_ERR_OOM : RAY_ERR_NYI; + } else { + ray_enc_choice_t want = ray_enc_float_choose(bits, n, T, dict, alp, (int64_t)tb); + if (!ray_enc_float_write(want.enc, bits, n, T, dict, alp, &o->payload, &c)) + return o->payload.oom ? RAY_ERR_OOM : RAY_ERR_RANGE; + } + o->desc.encoding = c.enc; + if (nt > 0) { + uint16_t cnt = (uint16_t)nt; + uint8_t zero6[6] = {0}; + if ((err = put(o, &cnt, 2)) != RAY_OK || (err = put(o, zero6, 6)) != RAY_OK) return err; + if ((err = put(o, tpos, (size_t)nt * 2)) != RAY_OK || (err = pad8(o)) != RAY_OK) return err; + for (int i = 0; i < nt; i++) + if ((err = put(o, &traw[i], esz)) != RAY_OK) return err; + if ((err = pad8(o)) != RAY_OK) return err; + o->desc.flags |= RAY_ENC_DESC_TRAILER; + } + if (have) { + uint64_t bmin, bmax; + memcpy(&bmin, &vmin, 8); memcpy(&bmax, &vmax, 8); + o->desc.min = (int64_t)bmin; o->desc.max = (int64_t)bmax; + o->has_stats = true; + } else { + o->desc.flags |= RAY_ENC_STAT_ABSENT; + } + return RAY_OK; +} + +/* ---- GUID: RAW or CONST; 16 zero bytes are the in-band null ---- */ +static ray_err_t encw_guid(const void* data, int64_t start, int n, ray_encw_vec_t* o) { + static const uint8_t zero[16]; + const uint8_t* p = (const uint8_t*)data + (size_t)start * 16; + bool eq = true; + for (int i = 0; i < n; i++) { + if (memcmp(p + (size_t)i * 16, zero, 16) == 0) o->n_nulls++; + if (i && memcmp(p + (size_t)i * 16, p, 16) != 0) eq = false; + } + uint64_t raw = (uint64_t)n * 16; + ray_err_t err; + int forced = atomic_load(&g_encw_force); + if (o->n_nulls < n && forced >= 0 && forced != RAY_ENC_RAW && !(forced == RAY_ENC_CONST && eq)) + return RAY_ERR_NYI; + if (o->n_nulls == n || (forced == RAY_ENC_CONST) || (forced < 0 && eq && 16 * 8 <= raw * 7)) { + o->desc.encoding = RAY_ENC_CONST; + err = put(o, o->n_nulls == n ? zero : p, 16); + } else { + o->desc.encoding = RAY_ENC_RAW; + err = put(o, p, (size_t)raw); + } + o->desc.flags |= RAY_ENC_STAT_ABSENT; + return err; +} + +/* ---- STR: RAW (wire descriptors + vector pool), CONST, STR_DICT, FSST; "" is the null ---- */ + +/* The forced encoding for STR vectors (-1: selection). */ +static int str_forced(void) { + int f = atomic_load(&g_encw_force_str); + return f >= 0 ? f : atomic_load(&g_encw_force); +} + +static void sd_free(ray_encw_sdict_t* d) { + ray_free_raw(d->slot); ray_free_raw(d->at); ray_free_raw(d->offs); + ray_free_raw(d->lens); ray_free_raw(d->bytes); + memset(d, 0, sizeof *d); +} + +static bool sd_rehash(ray_encw_sdict_t* d, uint64_t ncap) { + uint32_t* s = ray_calloc_raw((size_t)ncap * sizeof(uint32_t)); + if (!s) return false; + for (uint32_t k = 0; k < d->n; k++) { + uint64_t h = ray_hash_bytes(d->bytes + d->offs[k], d->lens[k]) & (ncap - 1); + while (s[h]) h = (h + 1) & (ncap - 1); + s[h] = k + 1; d->at[k] = h; + } + ray_free_raw(d->slot); d->slot = s; d->mask = ncap - 1; + return true; +} + +/* The entry's code, adding it when new; -1 on OOM. */ +static int64_t sd_code(ray_encw_sdict_t* d, const char* p, uint32_t len) { + if (!d->slot && !sd_rehash(d, 1024)) return -1; + uint64_t h = ray_hash_bytes(p, len) & d->mask; + for (;;) { + uint32_t c1 = d->slot[h]; + if (!c1) break; + uint32_t k = c1 - 1; + if (d->lens[k] == len && (len == 0 || memcmp(d->bytes + d->offs[k], p, len) == 0)) return k; + h = (h + 1) & d->mask; + } + if (d->n == d->cap) { + uint32_t nc = d->cap ? d->cap * 2 : 1024; + uint64_t* o = ray_realloc_raw(d->offs, (size_t)nc * 8); if (o) d->offs = o; + uint32_t* l = o ? ray_realloc_raw(d->lens, (size_t)nc * 4) : NULL; if (l) d->lens = l; + uint64_t* a = l ? ray_realloc_raw(d->at, (size_t)nc * 8) : NULL; if (a) d->at = a; + if (!o || !l || !a) return -1; + d->cap = nc; + } + if (!d->bytes || d->blen + len > d->bcap) { /* never NULL: "" may be the first entry */ + uint64_t nb = d->bcap ? d->bcap : 65536; + while (nb < d->blen + len) nb *= 2; + char* b = ray_realloc_raw(d->bytes, (size_t)nb); + if (!b) return -1; + d->bytes = b; d->bcap = nb; + } + if (len) memcpy(d->bytes + d->blen, p, len); + uint32_t k = d->n++; + d->offs[k] = d->blen; d->lens[k] = len; d->blen += len; + if (len > RAY_STR_INLINE_MAX) d->pooled += len; + d->slot[h] = k + 1; d->at[k] = h; + if ((uint64_t)d->n * 2 > d->mask + 1 && !sd_rehash(d, (d->mask + 1) * 2)) return -1; + return k; +} + +/* Drop the entries added since `keep`. Removing in reverse insertion order + * is safe for linear probing: every surviving entry was inserted before the + * removed ones, so its probe path never crossed a removed slot; a rehash + * re-places only entries already present, and `at` tracks every slot. */ +static void sd_truncate(ray_encw_sdict_t* d, uint32_t keep) { + while (d->n > keep) { + uint32_t k = --d->n; + d->slot[d->at[k]] = 0; + d->blen = d->offs[k]; + if (d->lens[k] > RAY_STR_INLINE_MAX) d->pooled -= d->lens[k]; + } +} + +typedef struct { uint8_t enc; uint64_t bytes; } str_choice_t; + +/* The best plain encoding of one STR vector: RAW, CONST, FSST (smallest + * wins, ties in that order; RAW unless the winner is at most 7/8 of it), or + * the forced one. An all-null vector is CONST of "" whatever is forced. + * With fbuf != NULL the FSST codes of an FSST winner are kept for the + * writer (*fbuf owned by the caller, ray_free_raw). */ +static ray_err_t str_choose_plain(const ray_str_t* s, const char* pool, int n, const ray_encw_side_t* side, + int forced, str_choice_t* out, uint8_t** fbuf, uint64_t* clen, uint64_t* ftotal) { + uint64_t pooled = 0, sum = 0; bool eq = true; int nulls = 0; + for (int i = 0; i < n; i++) { + uint32_t len = s[i].len; + nulls += len == 0; sum += len; + if (len > RAY_STR_INLINE_MAX) pooled += len; + if (i && eq && (len != s[0].len || + memcmp(ray_str_t_ptr(&s[i], pool), ray_str_t_ptr(&s[0], pool), len) != 0)) eq = false; + } + uint64_t raw = (uint64_t)n * 16 + 8 + ray_enc_pad8(pooled); + uint64_t cst = 8 + ray_enc_pad8(s[0].len); + out->enc = RAY_ENC_RAW; out->bytes = raw; + if (nulls == n) { out->enc = RAY_ENC_CONST; out->bytes = 8; return RAY_OK; } /* all null: CONST of "" */ + int64_t fs = -1; + uint8_t* fb = NULL; uint64_t cl[RAY_ENC_VEC]; uint64_t ft = 0; + if (side && side->fsst && (forced < 0 || forced == RAY_ENC_FSST)) { + fb = ray_alloc_raw((size_t)(2 * sum + 8)); + if (!fb) return RAY_ERR_OOM; + const char* sp[RAY_ENC_VEC]; uint32_t sl[RAY_ENC_VEC]; + for (int i = 0; i < n; i++) { sp[i] = ray_str_t_ptr(&s[i], pool); sl[i] = s[i].len; } + ft = ray_enc_fsst_encode(side->fsst, side->fsst_ix, sp, sl, n, fb, cl); + bool fit = true; /* the lengths child is U32 */ + for (int i = 0; i < n; i++) if (cl[i] > UINT32_MAX) fit = false; + if (fit) fs = ray_enc_fsst_size(cl, n, ft); + else { ray_free_raw(fb); fb = NULL; } + } + if (forced >= 0) { + bool ok = forced == RAY_ENC_RAW || (forced == RAY_ENC_CONST && eq) || (forced == RAY_ENC_FSST && fs >= 0); + if (!ok) { ray_free_raw(fb); return RAY_ERR_NYI; } + out->enc = (uint8_t)forced; + out->bytes = forced == RAY_ENC_CONST ? cst : forced == RAY_ENC_FSST ? (uint64_t)fs : raw; + } else { + if (eq && cst < out->bytes) { out->enc = RAY_ENC_CONST; out->bytes = cst; } + if (fs >= 0 && (uint64_t)fs < out->bytes) { out->enc = RAY_ENC_FSST; out->bytes = (uint64_t)fs; } + if (out->enc != RAY_ENC_RAW && out->bytes * 8 > raw * 7) { out->enc = RAY_ENC_RAW; out->bytes = raw; } + } + if (fbuf && out->enc == RAY_ENC_FSST) { *fbuf = fb; memcpy(clen, cl, (size_t)n * 8); *ftotal = ft; } + else ray_free_raw(fb); + return RAY_OK; +} + +/* Planning pass of one STR chunk: its codes plus the dictionary entries it + * adds, against the sum of its vectors' best plain encodings. The chunk is + * a STR_DICT chunk when that is at most 7/8 of the plain total (the 1/8 + * minimum gain at chunk level) or STR_DICT is forced; its entries are then + * kept, otherwise removed. All-null vectors are CONST either way (8 bytes + * on both sides) and add no entry, so every entry occurs in a STR_DICT + * vector. Skipping them is safe: a chunk holding an all-null CONST + * vector has no directory bounds; the column's DICT, when the save builds + * one, is the persisted one (P6b), and no consumer needs "" coded in the + * STR_DICT entry where it was never written. A chunk with no + * non-null row is never a dictionary chunk (the null image relies on it). + * A chunk whose entries would pass the cap abandons the accumulator. */ +static ray_err_t str_plan_chunk(ray_encw_t* w, const void* data, const char* pool, int64_t n, bool* dict_chunk) { + ray_encw_sdict_t* sd = &w->sdict; + const ray_str_t* s = (const ray_str_t*)data; + *dict_chunk = false; + int forced = str_forced(); + if (forced >= 0 && forced != RAY_ENC_STR_DICT) return RAY_OK; + bool any = false; + for (int64_t i = 0; i < n && !any; i++) any = s[i].len != 0; + if (!any) return RAY_OK; + if (sd->abandoned) return forced == RAY_ENC_STR_DICT ? RAY_ERR_NYI : RAY_OK; + uint32_t keep = sd->n; uint64_t bkeep = sd->blen; + uint64_t codes_total = 0, plain_total = 0; + ray_encw_side_t side = { .fsst = w->fsst, .fsst_ix = w->fsst_ix }; + uint64_t codes[RAY_ENC_VEC]; + for (int64_t at = 0; at < n; at += RAY_ENC_VEC) { + int vn = (int)(n - at < RAY_ENC_VEC ? n - at : RAY_ENC_VEC); + bool vany = false; + for (int i = 0; i < vn && !vany; i++) vany = s[at + i].len != 0; + if (!vany) { codes_total += 8; plain_total += 8; continue; } + for (int i = 0; i < vn; i++) { + int64_t k = sd_code(sd, ray_str_t_ptr(&s[at + i], pool), s[at + i].len); + if (k < 0) { sd_truncate(sd, keep); return RAY_ERR_OOM; } + codes[i] = (uint64_t)k; + } + codes_total += (uint64_t)ray_enc_strdict_size(codes, vn); + if (forced < 0) { + str_choice_t pc; + ray_err_t err = str_choose_plain(s + at, pool, vn, &side, -1, &pc, NULL, NULL, NULL); + if (err != RAY_OK) { sd_truncate(sd, keep); return err; } + plain_total += pc.bytes; + } + } + if (sd->n > RAY_ENCW_SDICT_CAP) { + sd_truncate(sd, keep); + sd->abandoned = true; + return forced == RAY_ENC_STR_DICT ? RAY_ERR_NYI : RAY_OK; + } + uint64_t dict_total = codes_total + (sd->blen - bkeep) + 8ull * (sd->n - keep); + if (forced == RAY_ENC_STR_DICT || dict_total * 8 <= plain_total * 7) { *dict_chunk = true; return RAY_OK; } + sd_truncate(sd, keep); + return RAY_OK; +} + +/* The encoding pass of one STR vector. side->sdict is non-NULL exactly for + * the vectors of a STR_DICT chunk, whose entries the plan already added. */ +static ray_err_t encw_str(const void* data, const char* pool, int64_t start, int n, + const ray_encw_side_t* side, ray_encw_vec_t* o) { + const ray_str_t* s = (const ray_str_t*)data + start; + uint64_t pooled = 0; + for (int i = 0; i < n; i++) { + if (s[i].len == 0) o->n_nulls++; + if (s[i].len > RAY_STR_INLINE_MAX) pooled += s[i].len; + } + if (pooled > UINT32_MAX) return RAY_ERR_RANGE; + o->str_occ = pooled; /* the generation-0 bound */ + /* Pool order rule 2: RAW, CONST and FSST strings over 12 bytes count once per row. */ + o->str_pooled = pooled; + o->desc.flags |= RAY_ENC_STAT_ABSENT; + ray_err_t err; + if (side && side->sdict && o->n_nulls < n) { /* a STR_DICT chunk */ + ray_encw_sdict_t* sd = side->sdict; + uint32_t planned = sd->n; + uint64_t codes[RAY_ENC_VEC]; + int64_t mn = INT64_MAX, mx = -1; + for (int i = 0; i < n; i++) { + int64_t k = sd_code(sd, ray_str_t_ptr(&s[i], pool), s[i].len); + if (k < 0) return RAY_ERR_OOM; + codes[i] = (uint64_t)k; + if (s[i].len == 0) continue; /* bounds over non-null rows (D4) */ + if (k < mn) mn = k; + if (k > mx) mx = k; + } + if (sd->n != planned) return RAY_ERR_RANGE; /* every entry comes from the plan */ + if (!ray_enc_strdict_write(codes, n, &o->payload)) return RAY_ERR_OOM; + sd->used = true; + o->str_pooled = 0; /* entries live in the dictionary (rule 1) */ + o->desc.encoding = RAY_ENC_STR_DICT; + o->desc.flags &= (uint16_t)~RAY_ENC_STAT_ABSENT; + o->desc.min = mn; o->desc.max = mx; o->has_stats = true; + return RAY_OK; + } + str_choice_t c; uint8_t* fbuf = NULL; uint64_t clen[RAY_ENC_VEC]; uint64_t ftotal = 0; + if ((err = str_choose_plain(s, pool, n, side, str_forced(), &c, &fbuf, clen, &ftotal)) != RAY_OK) return err; + o->desc.encoding = c.enc; + if (c.enc == RAY_ENC_FSST) { + bool ok = ray_enc_fsst_write(clen, n, fbuf, ftotal, &o->payload); + ray_free_raw(fbuf); + if (!ok) return o->payload.oom ? RAY_ERR_OOM : RAY_ERR_RANGE; + o->fsst_used = true; + return RAY_OK; + } + if (c.enc == RAY_ENC_CONST) { + uint32_t hdr[2] = { o->n_nulls == n ? 0 : s[0].len, 0 }; + if ((err = put(o, hdr, 8)) != RAY_OK) return err; + if (hdr[0] && (err = put(o, ray_str_t_ptr(&s[0], pool), hdr[0])) != RAY_OK) return err; + return pad8(o); + } + uint32_t off = 0; + for (int i = 0; i < n; i++) { + uint8_t w[16] = {0}; + uint32_t len = s[i].len; + memcpy(w, &len, 4); + const char* b = ray_str_t_ptr(&s[i], pool); + if (len <= RAY_STR_INLINE_MAX) { + memcpy(w + 4, b, len); + } else { + memcpy(w + 4, b, 4); + memcpy(w + 8, &off, 4); /* hash32 (w + 12) stays 0 */ + off += len; + } + if ((err = put(o, w, 16)) != RAY_OK) return err; + } + if ((err = put(o, &pooled, 8)) != RAY_OK) return err; + for (int i = 0; i < n; i++) + if (s[i].len > RAY_STR_INLINE_MAX && + (err = put(o, ray_str_t_ptr(&s[i], pool), s[i].len)) != RAY_OK) return err; + return pad8(o); +} + +ray_err_t ray_encw_vec_side(int8_t type, uint8_t attrs, const void* data, const char* str_pool, + int64_t start, int n, const ray_encw_side_t* side, ray_encw_vec_t* o) { + if (!ray_enc_gen2_supported()) { + return RAY_ERR_NYI; + } + vec_reset(o); + if (n <= 0 || n > RAY_ENC_VEC) return RAY_ERR_RANGE; + ray_err_t err; + switch (type) { + case RAY_F32: case RAY_F64: err = encw_float(type, data, start, n, side, o); break; + case RAY_GUID: err = encw_guid(data, start, n, o); break; + case RAY_STR: err = encw_str(data, str_pool, start, n, side, o); break; + case RAY_BOOL: case RAY_U8: case RAY_I16: case RAY_I32: case RAY_I64: + case RAY_DATE: case RAY_TIME: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_SYM: + err = encw_int(type, attrs, data, start, n, + ray_encw_type_has_dict(type) && side ? side->dict : NULL, o); + break; + default: return RAY_ERR_NYI; + } + if (err != RAY_OK) return err; + if (o->n_nulls > UINT16_MAX) return RAY_ERR_RANGE; + o->desc.n_nulls = (uint16_t)o->n_nulls; + o->desc.payload_bytes = o->payload.len; + return RAY_OK; +} + +ray_err_t ray_encw_vec(int8_t type, uint8_t attrs, const void* data, const char* str_pool, + int64_t start, int n, const ray_enc_dict_t* dict, ray_encw_vec_t* out) { + ray_encw_side_t side = { .dict = dict }; + return ray_encw_vec_side(type, attrs, data, str_pool, start, n, &side, out); +} + +static ray_err_t fput(ray_encw_t* w, const void* p, size_t n) { + static const uint8_t zeros[4096]; + while (n > 0) { + size_t k = p ? n : (n < sizeof zeros ? n : sizeof zeros); + if (fwrite(p ? p : zeros, 1, k, w->f) != k) return RAY_ERR_IO; + w->pos += k; n -= k; + if (p) break; + } + return RAY_OK; +} + +void ray_encw_free(ray_encw_t* w) { + ray_free_raw(w->dir); w->dir = NULL; + ray_free_raw(w->dict_v); w->dict_v = NULL; + sd_free(&w->sdict); + ray_free_raw(w->fsst); w->fsst = NULL; + ray_free_raw(w->fsst_ix); w->fsst_ix = NULL; + ray_enc_buf_free(&w->chunk); + ray_encw_vec_free(&w->vec); + if (w->idict) { ray_dict_acc_free(w->idict); ray_free_raw(w->idict); w->idict = NULL; } +} + +ray_err_t ray_encw_begin(ray_encw_t* w, FILE* f, int8_t type, uint8_t attrs, int64_t len, + uint32_t sym_count, uint8_t index_kind, uint8_t col_flags) { + memset(w, 0, sizeof *w); + if (!ray_enc_gen2_supported()) { + return RAY_ERR_NYI; + } + if (!ray_encw_type_supported(type) || len < 0) return RAY_ERR_NYI; + w->f = f; w->type = type; w->attrs = attrs; w->len = len; + w->sym_count = type == RAY_SYM ? sym_count : 0; + w->index_kind = index_kind; w->col_flags = col_flags; + if (index_kind == RAY_IDX_DICT) { + /* spec "Writing the index" (P6b): the writer builds the DICT itself */ + if (type != RAY_STR || len < 1 || len > INT32_MAX) return RAY_ERR_NYI; + w->idict = ray_alloc_raw(sizeof *w->idict); + if (!w->idict) return RAY_ERR_OOM; + ray_err_t de = ray_dict_acc_init(w->idict); + if (de != RAY_OK) { ray_free_raw(w->idict); w->idict = NULL; return de; } + } + w->n_chunks = ray_enc_nchunks(len); + if (w->n_chunks > 0) { + w->dir = ray_calloc_raw((size_t)w->n_chunks * sizeof(ray_enc_dirent_t)); + if (!w->dir) return RAY_ERR_OOM; + } + /* Headers and directory are written last, at offset 0 (finish). */ + return fput(w, NULL, (size_t)RAY_ENC_DIR_OFF + (size_t)w->n_chunks * sizeof(ray_enc_dirent_t)); +} + +void ray_encw_set_index(ray_encw_t* w, const ray_enc_idx_src_t* s) { + w->idx = *s; + w->has_idx = true; + w->idx_copy = NULL; w->idx_copy_len = 0; + w->index_kind = ray_index_payload((ray_t*)s->root)->kind; +} + +void ray_encw_set_index_copy(ray_encw_t* w, uint8_t kind, const uint8_t* region, uint64_t len) { + w->has_idx = false; + w->idx_copy = region; w->idx_copy_len = len; + w->index_kind = kind; +} + +/* VALUE_DICT is trained on the column's first chunk and frozen (spec + * "Encoding selection"): the filled T-bit values of every vector. Float + * columns go through float_fill, so no NaN reaches the dictionary, and + * train their ALP candidates from the same values. */ +static ray_err_t train_dict(ray_encw_t* w, const void* data, int64_t n) { + ray_enc_kind_t k; + if (!ray_enc_value_kind(w->type, w->attrs, &k)) return RAY_OK; + uint64_t* all = ray_alloc_raw((size_t)n * sizeof(uint64_t)); + ray_enc_input_t* in = k.is_float ? NULL : ray_alloc_raw(sizeof *in); + if (!all || (!k.is_float && !in)) { ray_free_raw(all); ray_free_raw(in); return RAY_ERR_OOM; } + for (int64_t s = 0; s < n; s += RAY_ENC_VEC) { + int vn = (int)(n - s < RAY_ENC_VEC ? n - s : RAY_ENC_VEC); + if (k.is_float) { + uint8_t nm[RAY_ENC_VEC / 8]; + (void)float_fill(w->type, data, s, vn, all + s, nm, NULL, NULL, NULL); + } else { + if (!ray_enc_load(data, w->type, w->attrs, s, vn, in)) { + ray_free_raw(all); ray_free_raw(in); + return RAY_ERR_RANGE; + } + memcpy(all + s, in->bits, (size_t)vn * sizeof(uint64_t)); + } + } + /* P0 final-review ruling: train_dict returns 1 trained, 0 no dictionary + * (empty or more than 1<<16 distinct), -1 out of memory; OOM fails the + * save so resident and streamed saves never diverge silently. */ + int tr = ray_enc_train_dict(all, n, k, &w->dict_v, &w->dict_n); + if (k.is_float) ray_enc_alp_train(all, n, k.T, &w->alp); + ray_free_raw(all); ray_free_raw(in); + if (tr < 0) return RAY_ERR_OOM; + if (tr == 0) { w->dict_v = NULL; w->dict_n = 0; } + return RAY_OK; +} + +/* The FSST table is trained on the column's first chunk and frozen (spec + * "Encoding selection"); no table (no string bytes, no candidate) means no + * FSST for the column. Training OOM fails the save (D3), so resident and + * streamed saves never diverge under memory pressure. */ +static ray_err_t train_fsst(ray_encw_t* w, const void* data, const char* pool, int64_t n) { + const ray_str_t* s = (const ray_str_t*)data; + const uint8_t** sp = ray_alloc_raw((size_t)n * sizeof *sp); + uint32_t* sl = ray_alloc_raw((size_t)n * sizeof *sl); + w->fsst = ray_calloc_raw(sizeof *w->fsst); + w->fsst_ix = ray_calloc_raw(sizeof *w->fsst_ix); + if (!sp || !sl || !w->fsst || !w->fsst_ix) { ray_free_raw(sp); ray_free_raw(sl); return RAY_ERR_OOM; } + for (int64_t i = 0; i < n; i++) { sp[i] = (const uint8_t*)ray_str_t_ptr(&s[i], pool); sl[i] = s[i].len; } + int tr = ray_fsst_train(sp, sl, n, w->fsst); + ray_free_raw(sp); ray_free_raw(sl); + if (tr < 0) return RAY_ERR_OOM; + if (tr == 0 || w->fsst->n == 0) { + ray_free_raw(w->fsst); ray_free_raw(w->fsst_ix); w->fsst = NULL; w->fsst_ix = NULL; + return RAY_OK; + } + ray_fsst_index_build(w->fsst, w->fsst_ix); + return RAY_OK; +} + +static bool type_is_float(int8_t t) { return t == RAY_F32 || t == RAY_F64; } +static double bits_double(int64_t b) { double d; memcpy(&d, &b, 8); return d; } + +/* Chunk body (descriptors, then payloads) of n rows into w->chunk and its + * directory entry into *de (offset left to the caller). */ +static ray_err_t encw_chunk_body(ray_encw_t* w, const void* data, const char* str_pool, int64_t n, + ray_enc_dirent_t* de) { + ray_err_t err; + ray_enc_dict_t dict = { w->dict_v, w->dict_n }; + w->chunk.len = 0; w->chunk.oom = false; + if (!ray_enc_buf_put(&w->chunk, NULL, RAY_ENC_DESC_AREA)) return RAY_ERR_OOM; + memset(de, 0, sizeof *de); + bool have = false, fl = type_is_float(w->type); + bool str = w->type == RAY_STR, dict_chunk = false, all_sdict = true; + if (str && (err = str_plan_chunk(w, data, str_pool, n, &dict_chunk)) != RAY_OK) return err; + int64_t nv = (n + RAY_ENC_VEC - 1) / RAY_ENC_VEC; + for (int64_t j = 0; j < nv; j++) { + int vn = (int)(n - j * RAY_ENC_VEC < RAY_ENC_VEC ? n - j * RAY_ENC_VEC : RAY_ENC_VEC); + ray_encw_side_t side = { .dict = w->dict_n ? &dict : NULL, .alp = w->alp.n ? &w->alp : NULL, + .fsst = w->fsst, .fsst_ix = w->fsst_ix, + .sdict = dict_chunk ? &w->sdict : NULL }; + err = ray_encw_vec_side(w->type, w->attrs, data, str_pool, j * RAY_ENC_VEC, vn, &side, &w->vec); + if (err != RAY_OK) return err; + ray_enc_desc_t desc = w->vec.desc; + desc.payload_off = w->chunk.len; + if (!ray_enc_buf_put(&w->chunk, w->vec.payload.p, w->vec.payload.len)) return RAY_ERR_OOM; + memcpy(w->chunk.p + j * sizeof(ray_enc_desc_t), &desc, sizeof desc); + if (desc.encoding == RAY_ENC_DICT) w->dict_used = true; + de->null_count += (uint32_t)w->vec.n_nulls; + if (w->vec.n_nulls > 0 && ray_enc_has_bitmap(w->type)) w->any_bitmap_null = true; + if (w->vec.fsst_used) w->fsst_used = true; + if (desc.encoding != RAY_ENC_STR_DICT) all_sdict = false; + /* Pool bound (plan Decisions, "Pool bound"): range on the per-occurrence count, + * the generation-0 bound, though dictionary entries count once. */ + w->str_occ_bytes += w->vec.str_occ; + if (w->str_occ_bytes > UINT32_MAX) return RAY_ERR_RANGE; + w->str_pool_bytes += w->vec.str_pooled; + if (ray_encw_type_summable(w->type)) + ray_i128_add128(&de->sum_hi, &de->sum_lo, w->vec.sum_hi, w->vec.sum_lo); + if (w->vec.has_stats) { + /* Combined in row order with the vector rule: strict compare, + * the first of tied values wins. */ + bool lt = fl ? bits_double(desc.min) < bits_double(de->min) : desc.min < de->min; + bool gt = fl ? bits_double(desc.max) > bits_double(de->max) : desc.max > de->max; + if (!have || lt) de->min = desc.min; + if (!have || gt) de->max = desc.max; + have = true; + } + } + /* STR: code bounds only when every vector is STR_DICT (D5); the combine + * above folded only STR_DICT vectors. */ + if (!have || (str && !all_sdict)) { de->flags = RAY_ENC_STAT_ABSENT; de->min = de->max = 0; } + de->bytes = w->chunk.len; + return RAY_OK; +} + +ray_err_t ray_encw_chunk(ray_encw_t* w, const void* data, const char* str_pool, int64_t n) { + if (w->chunk_i >= w->n_chunks) return RAY_ERR_RANGE; + int64_t want = w->len - w->chunk_i * RAY_ENC_CHUNK; + if (want > RAY_ENC_CHUNK) want = RAY_ENC_CHUNK; + if (n != want) return RAY_ERR_RANGE; + /* First-chunk dictionary training tries ALP before encw_float. */ + if ((w->type == RAY_F32 || w->type == RAY_F64) && !ray_enc_fp_env_ok()) + return RAY_ERR_FPENV; + ray_err_t err; + if (w->chunk_i == 0 && ray_encw_type_has_dict(w->type) && + (err = train_dict(w, data, n)) != RAY_OK) return err; + if (w->chunk_i == 0 && w->type == RAY_STR && (err = train_fsst(w, data, str_pool, n)) != RAY_OK) return err; + ray_enc_dirent_t* de = &w->dir[w->chunk_i]; + if ((err = encw_chunk_body(w, data, str_pool, n, de)) != RAY_OK) return err; + /* the DICT reads the chunk the body was encoded from: every writer feeds + * the same rows in the same order, so the same codes and bytes */ + if (w->idict && (err = ray_dict_acc_add_raw(w->idict, (const ray_str_t*)data, str_pool, n)) != RAY_OK) + return err; + de->offset = w->pos; + if ((err = fput(w, w->chunk.p, w->chunk.len)) != RAY_OK) return err; + w->chunk_i++; + return RAY_OK; +} + +/* The persisted attrs of the column: the source's disk attrs, HAS_NULLS + * for bitmap nulls. */ +static uint8_t encw_final_attrs(const ray_encw_t* w, bool has_nulls) { + return (uint8_t)((w->attrs & COL_DISK_ATTRS_MASK) | (has_nulls ? RAY_ATTR_HAS_NULLS : 0)); +} + +/* The 32-byte outer header and the enc header of a column of w->pos bytes. */ +static void encw_headers(const ray_encw_t* w, uint64_t side_off, uint64_t side_len, bool has_nulls, + uint64_t index_off, ray_t* hdr, ray_enc_hdr_t* eh) { + memset(eh, 0, sizeof *eh); + memcpy(eh->magic, "RENC", 4); + eh->header_version = RAY_ENC_HDR_VERSION; + eh->index_kind = w->index_kind; + eh->col_flags = w->col_flags; + eh->side_off = side_off; eh->side_len = side_len; + eh->index_off = index_off; + eh->str_pool_bytes = w->type == RAY_STR ? w->str_pool_bytes : 0; + eh->end_off = w->pos; + memset(hdr, 0, sizeof *hdr); + uint32_t xenc = RAY_ENC_XENC; + memcpy(hdr->aux, &xenc, 4); + hdr->order = RAY_ENC_GEN; + hdr->type = w->type; + hdr->attrs = encw_final_attrs(w, has_nulls); + hdr->rc = w->sym_count; + hdr->len = w->len; +} + +/* Side data (spec "Side data"): the table, then each entry 32-aligned + * relative to the side start, in kind order; each written only when used. + * A one-entry table is 32 bytes with its entry at 32. */ +static ray_err_t encw_side(ray_encw_t* w, uint64_t* side_off, uint64_t* side_len) { + *side_off = *side_len = 0; + uint16_t kind[3]; uint64_t eb[3]; int ne = 0; + size_t esz = 0; + if (w->dict_used) { + ray_enc_kind_t k; + if (!ray_enc_value_kind(w->type, w->attrs, &k)) return RAY_ERR_RANGE; + esz = (size_t)k.T / 8; /* F32 4 bytes, F64 8 */ + kind[ne] = RAY_ENC_SIDE_VALUE_DICT; eb[ne++] = 8 + ray_enc_pad8((uint64_t)w->dict_n * esz); + } + if (w->sdict.used) { + if (w->sdict.n == 0 || w->sdict.n > RAY_ENCW_SDICT_CAP) return RAY_ERR_RANGE; + kind[ne] = RAY_ENC_SIDE_STR_DICT; eb[ne++] = 8 + 8ull * (w->sdict.n + 1) + ray_enc_pad8(w->sdict.blen); + } + if (w->fsst_used) { + if (!w->fsst || w->fsst->n == 0) return RAY_ERR_RANGE; + kind[ne] = RAY_ENC_SIDE_FSST_TABLE; eb[ne++] = (uint64_t)ray_fsst_table_bytes(w->fsst); + } + if (!ne) return RAY_OK; + ray_err_t err; + *side_off = ray_enc_pad32(w->pos); + if ((err = fput(w, NULL, (size_t)(*side_off - w->pos))) != RAY_OK) return err; + uint64_t off[3], at = 8 + 24ull * (uint64_t)ne; + for (int i = 0; i < ne; i++) { off[i] = ray_enc_pad32(at); at = off[i] + eb[i]; } + uint8_t tbl[8 + 24 * 3]; memset(tbl, 0, sizeof tbl); + uint32_t n32 = (uint32_t)ne; memcpy(tbl, &n32, 4); + for (int i = 0; i < ne; i++) { + memcpy(tbl + 8 + 24 * i, &kind[i], 2); + memcpy(tbl + 8 + 24 * i + 8, &off[i], 8); + memcpy(tbl + 8 + 24 * i + 16, &eb[i], 8); + } + if ((err = fput(w, tbl, 8 + 24 * (size_t)ne)) != RAY_OK) return err; + uint64_t rel = 8 + 24ull * (uint64_t)ne; + for (int i = 0; i < ne; i++) { + if ((err = fput(w, NULL, (size_t)(off[i] - rel))) != RAY_OK) return err; + uint64_t start = w->pos; + if (kind[i] == RAY_ENC_SIDE_VALUE_DICT) { + uint32_t h[2] = { w->dict_n, 0 }; + if ((err = fput(w, h, 8)) != RAY_OK) return err; + for (uint32_t k = 0; k < w->dict_n; k++) + if ((err = fput(w, &w->dict_v[k], esz)) != RAY_OK) return err; /* LE low bytes */ + } else if (kind[i] == RAY_ENC_SIDE_STR_DICT) { + uint32_t h[2] = { w->sdict.n, 0 }; + if ((err = fput(w, h, 8)) != RAY_OK) return err; + if ((err = fput(w, w->sdict.offs, (size_t)w->sdict.n * 8)) != RAY_OK) return err; + if ((err = fput(w, &w->sdict.blen, 8)) != RAY_OK) return err; /* offsets[n] */ + if (w->sdict.blen && (err = fput(w, w->sdict.bytes, (size_t)w->sdict.blen)) != RAY_OK) return err; + } else { + const ray_fsst_table_t* t = w->fsst; + uint8_t h[8] = { t->n, 0, 0, 0, 0, 0, 0, 0 }; + if ((err = fput(w, h, 8)) != RAY_OK) return err; + if ((err = fput(w, t->len, t->n)) != RAY_OK) return err; + if ((err = fput(w, NULL, (size_t)(ray_enc_pad8(t->n) - t->n))) != RAY_OK) return err; + if ((err = fput(w, t->sym, (size_t)t->n * 8)) != RAY_OK) return err; + } + uint64_t used = w->pos - start; + if (used > eb[i]) return RAY_ERR_RANGE; + if ((err = fput(w, NULL, (size_t)(eb[i] - used))) != RAY_OK) return err; /* pad8 */ + rel = off[i] + eb[i]; + } + *side_len = rel; + return RAY_OK; +} + +ray_err_t ray_encw_finish(ray_encw_t* w) { + if (w->chunk_i != w->n_chunks) return RAY_ERR_RANGE; + ray_err_t err; + uint64_t side_off = 0, side_len = 0; + if ((err = encw_side(w, &side_off, &side_len)) != RAY_OK) return err; + /* Pool order rule 1: every STR_DICT entry over 12 bytes, once. */ + if (w->sdict.used) w->str_pool_bytes += w->sdict.pooled; + /* the index region follows the side data, 32-aligned (spec "Writers") */ + uint64_t index_off = 0; + if (w->has_idx || w->idx_copy || w->idict) { + index_off = ray_enc_pad32(w->pos); + if ((err = fput(w, NULL, (size_t)(index_off - w->pos))) != RAY_OK) return err; + if (w->idict) { + const ray_dict_acc_t* a = w->idict; + if (a->dead || a->n_rows != w->len) return RAY_ERR_RANGE; /* internal: every row fed */ + ray_enc_dict_src_t s = { .len = w->len, .n_distinct = a->n_distinct, .codes = a->codes, + .first_occ = a->first_occ, .offs = a->offs, .bytes = a->pool, + .bytes_len = a->pool_len }; + uint64_t nb = 0; + ray_t* ie = ray_enc_dict_write(w->f, &s, &nb); + if (ie) { ray_err_t c = ray_err_from_obj(ie); ray_error_free(ie); return c; } + w->pos += nb; + } else if (w->idx_copy) { + if ((err = fput(w, w->idx_copy, (size_t)w->idx_copy_len)) != RAY_OK) return err; + } else { + ray_enc_idx_src_t s = w->idx; + s.attrs = encw_final_attrs(w, w->any_bitmap_null); /* SYM PART keys at the saved width */ + uint64_t nb = 0; + ray_t* ie = ray_enc_index_write(w->f, &s, &nb); + if (ie) { ray_err_t c = ray_err_from_obj(ie); ray_error_free(ie); return c; } + w->pos += nb; + } + } + ray_enc_hdr_t eh; + ray_t hdr; + encw_headers(w, side_off, side_len, w->any_bitmap_null, index_off, &hdr, &eh); + if (fflush(w->f) != 0 || fseek(w->f, 0, SEEK_SET) != 0) return RAY_ERR_IO; + if (fwrite(&hdr, 1, 32, w->f) != 32 || fwrite(&eh, 1, 64, w->f) != 64) return RAY_ERR_IO; + if (w->n_chunks > 0 && + fwrite(w->dir, sizeof(ray_enc_dirent_t), (size_t)w->n_chunks, w->f) != (size_t)w->n_chunks) + return RAY_ERR_IO; + return fflush(w->f) == 0 ? RAY_OK : RAY_ERR_IO; +} + +/* An all-null column image (spec "Nulls": every vector CONST of the fill, + * statistics absent; the non-nullable BOOL / U8 read 0, with statistics). + * Every full chunk has the same body, so two bodies are encoded (a full + * chunk and the last) and the full one is copied (the format keeps chunks + * contiguous, so bodies cannot be shared): the image is about n_chunks x + * (64 B entry + one chunk body), 11.5 KiB per 65536 rows of I64 (descriptors + * plus a 128 B bitmap and a CONST per vector; ~18 MB per 100M rows) and + * 3.5 KiB for STR. `fill` holds min(len, 65536) null cells of `type` in its + * generation-0 width (SYM: `attrs` width) with `attrs` as the heap fill + * carries them. Headers follow ray_encw_finish exactly (persisted attrs of + * the source, HAS_NULLS added for bitmap nulls), so the image is byte for + * byte the file the generation-2 writer writes for the `len`-row heap fill: + * HAS_NULLS on SYM / STR / GUID comes from the fill's attrs, as it would + * when that vector is saved. The image lives in a ray_vm_map_anon mapping + * returned in *out (released by ray_vm_unmap_file, e.g. by ray_enccol_open + * on failure or its release). */ +ray_err_t ray_encw_null_image(int8_t type, uint8_t attrs, int64_t len, uint32_t sym_count, + const void* fill, void** out, size_t* out_size) { + *out = NULL; *out_size = 0; + if (!ray_enc_gen2_supported()) return RAY_ERR_NYI; + if (!ray_encw_type_supported(type) || len < 0) return RAY_ERR_NYI; + ray_encw_t w; + memset(&w, 0, sizeof w); + w.type = type; w.attrs = attrs; w.len = len; + w.sym_count = type == RAY_SYM ? sym_count : 0; + w.n_chunks = ray_enc_nchunks(len); + int64_t last_rows = len - (w.n_chunks - 1) * RAY_ENC_CHUNK; + ray_enc_buf_t full = {0}; + ray_enc_dirent_t full_de, last_de; + memset(&full_de, 0, sizeof full_de); + memset(&last_de, 0, sizeof last_de); + ray_err_t err = RAY_OK; + if (w.n_chunks > 1 || (w.n_chunks == 1 && last_rows == RAY_ENC_CHUNK)) { + if ((err = encw_chunk_body(&w, fill, NULL, RAY_ENC_CHUNK, &full_de)) != RAY_OK) goto out; + if (!ray_enc_buf_put(&full, w.chunk.p, w.chunk.len)) { err = RAY_ERR_OOM; goto out; } + } + if (w.n_chunks > 0 && last_rows < RAY_ENC_CHUNK && + (err = encw_chunk_body(&w, fill, NULL, last_rows, &last_de)) != RAY_OK) goto out; + if (w.n_chunks > 0 && last_rows == RAY_ENC_CHUNK) { /* the last chunk is full */ + last_de = full_de; + w.chunk.len = 0; + if (!ray_enc_buf_put(&w.chunk, full.p, full.len)) { err = RAY_ERR_OOM; goto out; } + } + uint64_t size = RAY_ENC_DIR_OFF + (uint64_t)w.n_chunks * sizeof(ray_enc_dirent_t); + if (w.n_chunks > 0) size += (uint64_t)(w.n_chunks - 1) * full.len + w.chunk.len; + uint8_t* img = ray_vm_map_anon((size_t)size); + if (!img) { err = RAY_ERR_OOM; goto out; } + uint64_t at = RAY_ENC_DIR_OFF + (uint64_t)w.n_chunks * sizeof(ray_enc_dirent_t); + for (int64_t c = 0; c < w.n_chunks; c++) { + bool last = c == w.n_chunks - 1; + ray_enc_dirent_t de = last ? last_de : full_de; + de.offset = at; + memcpy(img + RAY_ENC_DIR_OFF + (size_t)c * sizeof de, &de, sizeof de); + memcpy(img + at, last ? w.chunk.p : full.p, last ? w.chunk.len : full.len); + at += de.bytes; + } + w.pos = size; + ray_enc_hdr_t eh; + ray_t hdr; + encw_headers(&w, 0, 0, w.any_bitmap_null, 0, &hdr, &eh); /* ray_encw_finish's rule */ + memcpy(img, &hdr, 32); + memcpy(img + RAY_ENC_HDR_OFF, &eh, sizeof eh); + *out = img; *out_size = (size_t)size; +out: + ray_enc_buf_free(&full); + ray_encw_free(&w); + return err; +} diff --git a/src/store/encw.h b/src/store/encw.h new file mode 100644 index 000000000..bc80d0244 --- /dev/null +++ b/src/store/encw.h @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RAY_ENCW_H +#define RAY_ENCW_H + +#include +#include +#include "store/enc.h" +#include "store/encfmt.h" +#include "store/encidx.h" +#include "store/fsst.h" + +typedef struct { + ray_enc_desc_t desc; /* payload_off is set by the column writer */ + ray_enc_buf_t payload; + int n_nulls; + bool has_stats; + int64_t sum_hi; + uint64_t sum_lo; + uint64_t str_pooled; /* pool bytes this vector adds (0 for STR_DICT: rule 1) */ + uint64_t str_occ; /* per-occurrence pooled bytes of the vector, every encoding */ + bool fsst_used; /* the vector is FSST */ +} ray_encw_vec_t; + +/* The STR_DICT accumulator (spec "Encoding selection"): entries in code + * (first-occurrence) order, open addressing over code + 1 (0 empty). */ +#define RAY_ENCW_SDICT_CAP (1u << 20) /* the STR_DICT entry limit (spec "Side data") */ +typedef struct ray_encw_sdict_s { + uint32_t* slot; uint64_t mask; /* open addressing: code + 1, 0 empty */ + uint64_t* at; /* slot of each entry (truncation) */ + uint64_t* offs; uint32_t* lens; uint32_t n, cap; + char* bytes; uint64_t blen, bcap; + uint64_t pooled; /* sum of entry lengths over 12 */ + bool abandoned, used; +} ray_encw_sdict_t; + +/* Column-level structures trained on the first chunk (spec "Encoding + * selection"); every field may be NULL. */ +typedef struct { + const ray_enc_dict_t* dict; /* VALUE_DICT: integer, temporal, F32, F64 */ + const ray_enc_alp_cands_t* alp; /* ALP candidates: F32, F64 */ + const ray_fsst_table_t* fsst; /* STR: the column's FSST table */ + const ray_fsst_index_t* fsst_ix; /* STR: its encode index */ + ray_encw_sdict_t* sdict; /* STR: non-NULL exactly in a STR_DICT chunk */ +} ray_encw_side_t; + +void ray_encw_vec_init(ray_encw_vec_t* v); +void ray_encw_vec_free(ray_encw_vec_t* v); +ray_err_t ray_encw_vec_side(int8_t type, uint8_t attrs, const void* data, const char* str_pool, + int64_t start, int n, const ray_encw_side_t* side, ray_encw_vec_t* out); +/* ray_encw_vec_side with { .dict = dict }: no ALP candidates; STR vectors + * select RAW or CONST only (no FSST table, no dictionary). */ +ray_err_t ray_encw_vec(int8_t type, uint8_t attrs, const void* data, const char* str_pool, + int64_t start, int n, const ray_enc_dict_t* dict, ray_encw_vec_t* out); +bool ray_encw_type_has_dict(int8_t type); +bool ray_encw_type_summable(int8_t type); +bool ray_encw_type_supported(int8_t type); +/* Test hook: every following vector uses top-level encoding `enc` where it + * is legal for the type and applicable to the values (all-null vectors stay + * CONST; floats take RAW, CONST, RLE, DICT, ALP and ALP_RD); -1 restores + * selection. A forced encoding that is not applicable fails the vector + * with RAY_ERR_NYI. */ +void ray_encw_test_force(int enc); +/* Test hook: like ray_encw_test_force, for F32 / F64 vectors only (it wins + * over ray_encw_test_force there); other types keep selection or the general + * force. -1 restores. */ +void ray_encw_test_force_float(int enc); +/* Test hook: like ray_encw_test_force, for STR vectors only (it wins over + * ray_encw_test_force there); -1 restores. STR's encodings are RAW, CONST, + * STR_DICT and FSST; all-null vectors stay CONST whatever is forced. A + * forced STR (or general) encoding gives RAY_ERR_NYI on a vector with a + * non-null row when it does not apply: CONST over unequal strings; FSST + * with no trained table (ray_encw_vec, or a column with no string bytes to + * train on) or a slice longer than UINT32_MAX; STR_DICT outside a column + * writer (ray_encw_vec has no dictionary) or once the column's entries + * would pass RAY_ENCW_SDICT_CAP; any other code. */ +void ray_encw_test_force_str(int enc); + +/* Column assembly (spec "Format"): begin, one chunk per 65536 rows, finish. */ +typedef struct { + FILE* f; + int8_t type; + uint8_t attrs; /* source attrs; masked + HAS_NULLS derived at finish */ + int64_t len; + uint32_t sym_count; /* outer header rc (SYM) */ + uint8_t index_kind; /* the recorded kind; a region kind needs a region (set_index*) */ + uint8_t col_flags; /* RAY_ENC_FLAG_UNIQUE */ + int64_t n_chunks, chunk_i; + ray_enc_dirent_t* dir; + uint64_t pos; /* bytes written == current file offset */ + uint64_t str_pool_bytes; + bool any_bitmap_null; + uint64_t* dict_v; uint32_t dict_n; bool dict_used; + ray_enc_buf_t chunk; + ray_encw_vec_t vec; + ray_enc_idx_src_t idx; bool has_idx; /* region from a heap root */ + const uint8_t* idx_copy; uint64_t idx_copy_len; /* region copied verbatim */ + ray_enc_alp_cands_t alp; /* F32 / F64 ALP candidates from chunk 0 (n == 0: none) */ + ray_encw_sdict_t sdict; /* STR: the STR_DICT accumulator */ + ray_fsst_table_t* fsst; /* STR: FSST table from chunk 0 (NULL: none) */ + ray_fsst_index_t* fsst_ix; + bool fsst_used; /* some vector is FSST: the FSST_TABLE entry is written */ + uint64_t str_occ_bytes; /* per-occurrence pooled bytes (the generation-0 bound) */ + struct ray_dict_acc_s* idict; /* STR, index_kind DICT (P6b): generation 0's accumulator, fed per chunk */ +} ray_encw_t; +/* index_kind RAY_IDX_DICT (P6b, spec "Writing the index"): the writer + * builds the DICT region itself from the chunks it encodes and writes it at + * finish; RAY_ERR_NYI on a type other than STR or len outside 1..INT32_MAX. + * An OOM building it fails the column (ray_encw_chunk / finish). */ +ray_err_t ray_encw_begin(ray_encw_t* w, FILE* f, int8_t type, uint8_t attrs, int64_t len, + uint32_t sym_count, uint8_t index_kind, uint8_t col_flags); +ray_err_t ray_encw_chunk(ray_encw_t* w, const void* data, const char* str_pool, int64_t n); +ray_err_t ray_encw_finish(ray_encw_t* w); +void ray_encw_free(ray_encw_t* w); +/* Write s's index as the region (index_kind = the root's kind). A writer + * begun with RAY_IDX_DICT takes neither this nor ray_encw_set_index_copy. The root + * must stay alive until ray_encw_finish; s->attrs is replaced by the + * column's final persisted attrs at finish. A region writer failure leaves + * its "index region: ..." message in ray_error_msg(). */ +void ray_encw_set_index(ray_encw_t* w, const ray_enc_idx_src_t* s); +/* Copy `len` bytes of an already validated region of `kind` verbatim (never + * on a writer begun with RAY_IDX_DICT). */ +void ray_encw_set_index_copy(ray_encw_t* w, uint8_t kind, const uint8_t* region, uint64_t len); + +/* An all-null generation-2 column image of `len` rows in an anonymous + * mapping (*out, *out_size; ray_vm_unmap_file releases it). `fill`: min(len, + * 65536) null cells of `type` (generation-0 width; SYM at `attrs` width). */ +ray_err_t ray_encw_null_image(int8_t type, uint8_t attrs, int64_t len, uint32_t sym_count, + const void* fill, void** out, size_t* out_size); + +#endif /* RAY_ENCW_H */ diff --git a/src/store/fsst.c b/src/store/fsst.c new file mode 100644 index 000000000..58f42ff68 --- /dev/null +++ b/src/store/fsst.c @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "store/fsst.h" +#include +#include +#include + +/* Index: symbols grouped by first byte (start/cnt into ids), within a group + * longest first, ties by code. Built once per table, matched per position. */ +void ray_fsst_index_build(const ray_fsst_table_t* t, ray_fsst_index_t* ix) { + memset(ix, 0, sizeof *ix); + for (int c = 0; c < t->n; c++) ix->cnt[t->sym[c][0]]++; + uint8_t pos[256]; int acc = 0; + for (int f = 0; f < 256; f++) { ix->start[f] = (uint8_t)acc; pos[f] = (uint8_t)acc; acc += ix->cnt[f]; } + for (int len = 8; len >= 1; len--) + for (int c = 0; c < t->n; c++) + if (t->len[c] == len) ix->ids[pos[t->sym[c][0]]++] = (uint8_t)c; +} + +static int fsst_match(const ray_fsst_table_t* t, const ray_fsst_index_t* ix, + const uint8_t* s, uint32_t rem) { + uint8_t f = s[0]; + const uint8_t* ids = ix->ids + ix->start[f]; + for (int j = 0; j < ix->cnt[f]; j++) { + int c = ids[j]; + if (t->len[c] <= rem && memcmp(t->sym[c], s, t->len[c]) == 0) return c; + } + return -1; +} + +int64_t ray_fsst_encode_ix(const ray_fsst_table_t* t, const ray_fsst_index_t* ix, + const uint8_t* s, uint32_t len, uint8_t* out) { + int64_t o = 0; + for (uint32_t i = 0; i < len;) { + int c = fsst_match(t, ix, s + i, len - i); + if (c >= 0) { out[o++] = (uint8_t)c; i += t->len[c]; } + else { out[o++] = RAY_FSST_ESC; out[o++] = s[i++]; } + } + return o; +} + +int64_t ray_fsst_encode(const ray_fsst_table_t* t, const uint8_t* s, uint32_t len, uint8_t* out) { + ray_fsst_index_t ix; ray_fsst_index_build(t, &ix); + return ray_fsst_encode_ix(t, &ix, s, len, out); +} + +int64_t ray_fsst_expanded_len(const ray_fsst_table_t* t, const uint8_t* in, uint32_t len) { + int64_t x = 0; + for (uint32_t i = 0; i < len; i++) { + uint8_t c = in[i]; + if (c == RAY_FSST_ESC) { i++; x += 1; } + else x += t->len[c]; + } + return x; +} + +int64_t ray_fsst_decode(const ray_fsst_table_t* t, const uint8_t* in, uint32_t len, uint8_t* out) { + size_t o = 0; + for (uint32_t i = 0; i < len; i++) { + uint8_t c = in[i]; + if (c == RAY_FSST_ESC) out[o++] = in[++i]; + else { memcpy(out + o, t->sym[c], t->len[c]); o += t->len[c]; } + } + return (int64_t)o; +} + +int64_t ray_fsst_decode_fast(const ray_fsst_table_t* t, const uint8_t* in, uint32_t len, uint8_t* out) { + size_t o = 0; + for (uint32_t i = 0; i < len;) { + uint8_t c = in[i++]; + if (c != RAY_FSST_ESC) { memcpy(out + o, t->sym[c], 8); o += t->len[c]; } + else out[o++] = in[i++]; + } + return (int64_t)o; +} + +int64_t ray_fsst_table_bytes(const ray_fsst_table_t* t) { + return 8 + (((int64_t)t->n + 7) & ~(int64_t)7) + 8 * (int64_t)t->n; +} + +/* ---- training ---- + * Five rounds. Each round compresses the sample with the current table and + * counts how often each symbol occurs (count1) and how often each pair of + * consecutive symbols occurs (count2, pairs whose concatenation is at most + * 8 bytes). Escaped bytes count as single-byte candidate symbols. The next + * table is the 255 candidates with the highest gain (count * length), ties + * broken by length, then bytes, so training is deterministic. */ +typedef struct { uint8_t len; uint8_t b[8]; uint64_t gain; } fsst_cand_t; + +static int cand_cmp(const fsst_cand_t* a, const fsst_cand_t* b) { + if (a->gain != b->gain) return a->gain > b->gain ? -1 : 1; + if (a->len != b->len) return a->len > b->len ? -1 : 1; + return memcmp(a->b, b->b, 8); +} + +/* Training sample budget: when the input holds more than this many bytes, every + * stride-th string is used (stride = ceil(total / budget)), so the sample spans + * the whole input evenly. The candidate map holds 2^17 slots; a new key is + * dropped once it is half full while existing keys keep counting. With a + * 256 KiB sample that cap is rarely reached. */ +#define FSST_SAMPLE_BYTES (1u << 18) + +static int cand_qcmp(const void* a, const void* b) { + return cand_cmp((const fsst_cand_t*)a, (const fsst_cand_t*)b); +} + +/* Candidates live in a small open-addressing map keyed by (len, bytes). */ +#define FSST_MAP_BITS 17 +typedef struct { fsst_cand_t* e; uint32_t n, cap; } fsst_map_t; + +static uint64_t cand_key_hash(uint8_t len, const uint8_t* b) { + uint64_t h = 0x9E3779B97F4A7C15ull ^ len; + for (int i = 0; i < len; i++) h = (h ^ b[i]) * 0x100000001B3ull; + return h; +} + +static void map_add(fsst_map_t* m, uint8_t len, const uint8_t* b, uint64_t g) { + uint32_t mask = m->cap - 1; + for (uint32_t i = (uint32_t)cand_key_hash(len, b) & mask;; i = (i + 1) & mask) { + fsst_cand_t* e = &m->e[i]; + if (e->len == 0) { if (m->n >= m->cap / 2) return; e->len = len; memset(e->b, 0, 8); memcpy(e->b, b, len); e->gain = g; m->n++; return; } + if (e->len == len && memcmp(e->b, b, len) == 0) { e->gain += g; return; } + } +} + +int ray_fsst_train(const uint8_t* const* strs, const uint32_t* lens, int64_t n, + ray_fsst_table_t* t) { + memset(t, 0, sizeof *t); + uint64_t total = 0; + for (int64_t i = 0; i < n; i++) total += lens[i]; + if (total == 0) return 0; /* no string bytes */ + int64_t stride = total > FSST_SAMPLE_BYTES ? (int64_t)((total + FSST_SAMPLE_BYTES - 1) / FSST_SAMPLE_BYTES) : 1; + fsst_map_t m = { NULL, 0, 1u << FSST_MAP_BITS }; + m.e = ray_calloc_raw(sizeof(fsst_cand_t) * m.cap); + fsst_cand_t* all = ray_calloc_raw(sizeof(fsst_cand_t) * (m.cap / 2 + 1)); + if (!m.e || !all) { ray_free_raw(m.e); ray_free_raw(all); return -1; } /* t stays empty */ + for (int round = 0; round < 5; round++) { + memset(m.e, 0, sizeof(fsst_cand_t) * m.cap); m.n = 0; + ray_fsst_index_t ix; ray_fsst_index_build(t, &ix); + for (int64_t si = 0; si < n; si += stride) { + const uint8_t* s = strs[si]; uint32_t len = lens[si]; + int prev_len = 0; uint8_t prev[8]; + for (uint32_t i = 0; i < len;) { + int c = t->n ? fsst_match(t, &ix, s + i, len - i) : -1; + uint8_t cl = c >= 0 ? t->len[c] : 1; + const uint8_t* cb = c >= 0 ? t->sym[c] : s + i; + map_add(&m, cl, cb, cl); /* count1 * len */ + if (prev_len && prev_len + cl <= 8) { + uint8_t cat[8]; memcpy(cat, prev, (size_t)prev_len); memcpy(cat + prev_len, cb, cl); + map_add(&m, (uint8_t)(prev_len + cl), cat, (uint64_t)(prev_len + cl)); /* count2 * len */ + } + memcpy(prev, cb, cl); prev_len = cl; + i += cl; + } + } + /* total order (gain, len, bytes) over distinct keys: sort, keep the first 255 */ + size_t k = 0; + for (uint32_t i = 0; i < m.cap; i++) if (m.e[i].len) all[k++] = m.e[i]; + qsort(all, k, sizeof *all, cand_qcmp); + if (k > 255) k = 255; + ray_fsst_table_t nt; memset(&nt, 0, sizeof nt); + nt.n = (uint8_t)k; + for (size_t c = 0; c < k; c++) { nt.len[c] = all[c].len; memcpy(nt.sym[c], all[c].b, 8); } + *t = nt; + } + ray_free_raw(all); + ray_free_raw(m.e); + return t->n > 0 ? 1 : 0; +} diff --git a/src/store/fsst.h b/src/store/fsst.h new file mode 100644 index 000000000..b587dd5f3 --- /dev/null +++ b/src/store/fsst.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_FSST_H +#define RAY_FSST_H + +/* FSST string compression (Boncz, Neumann, Leis, VLDB 2020): a table of at + * most 255 symbols of 1..8 bytes; code c < n expands to symbol c, code 255 + * escapes one literal byte. Each string is compressed on its own. */ + +#include +#include + +#define RAY_FSST_ESC 255 + +typedef struct { uint8_t n; uint8_t len[255]; uint8_t sym[255][8]; } ray_fsst_table_t; + +/* Compact encode index (~0.5 KB): symbols grouped by first byte, longest first. */ +typedef struct ray_fsst_index_s { uint8_t start[256]; uint8_t cnt[256]; uint8_t ids[255]; } ray_fsst_index_t; + +void ray_fsst_index_build(const ray_fsst_table_t* t, ray_fsst_index_t* ix); +/* out must hold 2*len bytes (worst case: every byte escaped). */ +int64_t ray_fsst_encode_ix(const ray_fsst_table_t* t, const ray_fsst_index_t* ix, + const uint8_t* s, uint32_t len, uint8_t* out); + +/* Trains *t on the strings (sampled to 256 KiB). Returns 1 = trained + * (t->n > 0), 0 = no table (no string bytes or no candidate; t->n == 0), + * -1 = out of memory (t->n == 0). A caller whose output must not depend + * on memory pressure fails on -1. */ +int ray_fsst_train(const uint8_t* const* strs, const uint32_t* lens, int64_t n, + ray_fsst_table_t* t); +/* out must hold 2*len bytes. Builds an index per call; use ray_fsst_encode_ix in loops. */ +int64_t ray_fsst_encode(const ray_fsst_table_t* t, const uint8_t* s, uint32_t len, uint8_t* out); +/* Expand the codes in[0, len) of a string ray_fsst_encode wrote: out + * receives ray_fsst_expanded_len bytes; returns that length. */ +int64_t ray_fsst_decode(const ray_fsst_table_t* t, const uint8_t* in, uint32_t len, uint8_t* out); +/* ray_fsst_decode copying each symbol as a whole 8-byte word: out must + * hold 8 bytes past the expanded length. */ +int64_t ray_fsst_decode_fast(const ray_fsst_table_t* t, const uint8_t* in, uint32_t len, uint8_t* out); +int64_t ray_fsst_expanded_len(const ray_fsst_table_t* t, const uint8_t* in, uint32_t len); +int64_t ray_fsst_table_bytes(const ray_fsst_table_t* t); + +#endif diff --git a/src/store/part.c b/src/store/part.c index b888a8477..ef677e834 100644 --- a/src/store/part.c +++ b/src/store/part.c @@ -27,6 +27,9 @@ #define _GNU_SOURCE #endif #include "part.h" +#include "table/table.h" +#include "store/enccol.h" +#include "store/encw.h" /* ray_encw_null_image */ #include "core/runtime.h" #include "mem/sys.h" #include "mem/heap.h" @@ -36,6 +39,7 @@ #include "table/domain.h" #include "lang/cal.h" /* MONTHDAYS, date_leap_year — calendar-date validation */ #include "core/numparse.h" /* ray_parse_i64 — overflow-checked integer names */ +#include "lang/format.h" /* ray_type_name */ #include #include #include @@ -258,6 +262,95 @@ static ray_t* collect_part_dirs(const char* db_root, char*** out_dirs, return NULL; } +/* -------------------------------------------------------------------------- + * ray_null_fill — `rows` cells of `type`'s null on the heap (part.h). It is + * the segment of a column a ragged partition lacks only where generation 2 + * cannot hold the type (LIST, or a big-endian host); otherwise it is the + * fill one chunk of the lazy segment is encoded from (missing_seg), and the + * group's plain stand-in for that segment (group.c, grp_synth_plain). + * -------------------------------------------------------------------------- */ +ray_t* ray_null_fill(int8_t type, int64_t rows, struct ray_sym_domain_s* dom) { + if (type == RAY_LIST) { + ray_t* l = ray_list_new(rows); + if (!l || RAY_IS_ERR(l)) return l ? l : ray_error("oom", NULL); + ray_t** e = (ray_t**)ray_data(l); + for (int64_t i = 0; i < rows; i++) e[i] = RAY_NULL_OBJ; /* arena object: no ref */ + l->len = rows; + return l; + } + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W8, rows) : ray_vec_new(type, rows); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + v->len = rows; + void* p = ray_data(v); + switch (type) { + case RAY_F64: + for (int64_t i = 0; i < rows; i++) ((double*)p)[i] = NULL_F64; + break; + case RAY_F32: + for (int64_t i = 0; i < rows; i++) ((float*)p)[i] = NULL_F32; + break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: + for (int64_t i = 0; i < rows; i++) ((int64_t*)p)[i] = NULL_I64; + break; + case RAY_I32: case RAY_DATE: case RAY_TIME: + for (int64_t i = 0; i < rows; i++) ((int32_t*)p)[i] = NULL_I32; + break; + case RAY_I16: + for (int64_t i = 0; i < rows; i++) ((int16_t*)p)[i] = NULL_I16; + break; + case RAY_SYM: case RAY_STR: case RAY_GUID: /* id 0, the empty string, the zero GUID */ + case RAY_BOOL: case RAY_U8: + memset(p, 0, (size_t)rows * ray_sym_elem_size(type, v->attrs)); + break; + default: + ray_release(v); + return ray_error("nyi", "parted: a partition lacks a column of type %s", ray_type_name(type)); + } + if (type != RAY_BOOL && type != RAY_U8 && rows > 0) v->attrs |= RAY_ATTR_HAS_NULLS; + if (type == RAY_SYM && dom) { + ray_sym_domain_retain(dom); + v->sym_domain = dom; /* the fresh vector holds the immortal runtime domain: no release */ + } + return v; +} + +/* -------------------------------------------------------------------------- + * missing_seg — the segment of a column a ragged partition lacks: `rows` + * rows of the column's null, so every column of a parted table has the + * table's row count, segment by segment, and a consumer never meets a + * missing segment (#724). + * + * Every type generation 2 stores gets a lazy all-null segment: a + * generation-2 RAY_ENCCOL over an in-memory image (ray_encw_null_image, an + * anonymous mapping the enccol owns and unmaps), so opening costs about + * n_chunks x (64 B + one chunk body) of mapped memory — 11.5 KiB per 65536 + * rows of I64, ~18 MB per 100M rows where a heap fill held 800 MB — and the + * rows decode only when a query reads them, like any encoded segment (its + * directory answers null presence without a decode). The image is the file + * the generation-2 writer writes for ray_null_fill's vector, so its + * materialization is that vector: the same nulls and attrs (HAS_NULLS on + * every nullable type), SYM over `dom`. The segment is marked synthetic: + * generation inheritance treats it as the plain fill it stands for (a save + * without a compress option over a generation-0 or fresh destination writes + * generation 0, as the heap fill did). The image is never a file: a save + * re-encodes it through the writers. LIST (and every type on a + * host without generation 2) keeps the heap fill: rows x element size, + * held for the table's lifetime. `what` names the segment in errors. + * -------------------------------------------------------------------------- */ +static ray_t* missing_seg(int8_t type, int64_t rows, struct ray_sym_domain_s* dom, const char* what) { + if (!ray_enc_gen2_supported() || !ray_encw_type_supported(type)) + return ray_null_fill(type, rows, dom); + ray_t* fill = ray_null_fill(type, rows < RAY_ENC_CHUNK ? rows : RAY_ENC_CHUNK, dom); + if (!fill || RAY_IS_ERR(fill)) return fill ? fill : ray_error("oom", NULL); + void* img = NULL; size_t size = 0; + ray_err_t e = ray_encw_null_image(type, fill->attrs, rows, 0, ray_data(fill), &img, &size); + ray_release(fill); + if (e != RAY_OK) return ray_error(ray_err_code_str(e), "%s: null segment", what); + ray_t* v = ray_enccol_open(img, size, what, type == RAY_SYM ? dom : NULL, false); + if (v && !RAY_IS_ERR(v)) ray_enccol_set_synthetic(v); /* inherits as plain (colwrite.c) */ + return v; +} + /* -------------------------------------------------------------------------- * Partition reuse across mounts * @@ -431,7 +524,7 @@ static bool part_keep_used(const part_cache_entry_t* e, const void* ctx) { (void)ctx; if (ray_atomic_load(&e->tbl->rc) > 1) return true; for (int64_t i = 0; i < ray_table_ncols(e->tbl); i++) { - ray_t* col = ray_table_get_col_idx(e->tbl, i); + ray_t* col = ray_table_slot_idx(e->tbl, i); /* the slot itself: never decoded */ if (col && ray_atomic_load(&col->rc) > 1) return true; } return false; @@ -443,9 +536,14 @@ void ray_parted_cache_prune(void) { static bool part_domain_matches(ray_t* tbl, struct ray_sym_domain_s* dom) { for (int64_t i = 0; i < ray_table_ncols(tbl); i++) { - ray_t* col = ray_table_get_col_idx(tbl, i); - if (col && col->type == RAY_SYM && ray_sym_vec_domain(col) != dom) + ray_t* col = ray_table_slot_idx(tbl, i); /* the slot itself: never decoded */ + if (!col) continue; + if (col->type == RAY_ENCCOL) { + ray_enccol_t* e = ray_enccol_of(col); + if (e && e->type == RAY_SYM && e->dom != dom) return false; + } else if (col->type == RAY_SYM && ray_sym_vec_domain(col) != dom) { return false; + } } return true; } @@ -544,7 +642,10 @@ void ray_parted_cache_clear(void) { * * Builds parted columns (RAY_PARTED_BASE + base_type) where each segment * is an mmap'd vector from ray_read_splayed. Also builds a MAPCOMMON column - * with partition key names and row counts. + * with partition key names and row counts. No segment is missing: a + * partition lacking a tail column gets a segment of nulls of its row count + * (missing_seg: a lazy all-null encoded segment, O(chunks) bytes at open), + * so every column's segment p has MAPCOMMON row count p. * -------------------------------------------------------------------------- */ ray_t* ray_read_parted(const char* db_root, const char* table_name) { @@ -581,8 +682,7 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { if (!dom) { part_cache_sweep(db_root, table_name, seq); return ray_error("corrupt", - "symfile %s: unreadable or invalid (bad magic, torn record, " - "or missing \"\" at position 0)", sym_path); + "symfile %s: unreadable or not a symfile", sym_path); } } @@ -677,8 +777,9 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { /* Cross-partition schema validation: column association is by INDEX * (see the data-column loop below), so every column a partition has * must match the first partition's name and type at the same index. - * A partition MAY have fewer columns — the missing tail becomes NULL - * segments (supported ragged mode) — but never more, and never a + * A partition MAY have fewer columns — the missing tail reads as + * segments of nulls (supported ragged mode, missing_seg) — but + * never more, and never a * renamed/retyped column (silent mis-association otherwise). SYM * index width (attrs) may legally differ per partition — partitions * written at different dictionary sizes carry different index @@ -696,9 +797,10 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { for (int64_t c = 0; c < ncols_p; c++) { int64_t n0 = ray_table_col_name(part_tables[0], c); int64_t np = ray_table_col_name(part_tables[p], c); - ray_t* c0 = ray_table_get_col_idx(part_tables[0], c); - ray_t* cp = ray_table_get_col_idx(part_tables[p], c); - if (n0 != np || !c0 || !cp || c0->type != cp->type) { + ray_col_meta_t m0, mp; + bool h0 = ray_table_col_meta_idx(part_tables[0], c, &m0); + bool hp = ray_table_col_meta_idx(part_tables[p], c, &mp); + if (n0 != np || !h0 || !hp || m0.type != mp.type) { ray_t* na = ray_sym_str(np); part_err = ray_error("corrupt", "parted %s: partition %s/%s column %lld ('%.*s') " @@ -788,8 +890,8 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { /* ---- Data columns (after MAPCOMMON) ---- */ for (int64_t c = 0; c < ncols; c++) { int64_t name_id = ray_table_col_name(part_tables[0], c); - ray_t* first_seg = ray_table_get_col_idx(part_tables[0], c); - if (!first_seg) continue; + ray_col_meta_t m0; + if (!ray_table_col_meta_idx(part_tables[0], c, &m0)) continue; ray_t* parted = ray_alloc((size_t)part_count * sizeof(ray_t*)); if (!parted || RAY_IS_ERR(parted)) { @@ -798,24 +900,56 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { ray_release(result); goto fail_tables; } - parted->type = RAY_PARTED_BASE + first_seg->type; + parted->type = RAY_PARTED_BASE + m0.type; parted->len = part_count; parted->attrs = 0; memset(parted->aux, 0, 16); + /* Segments are the slot objects themselves, encoded or plain, never + * decoded here: a decode failure surfaces on materialization. */ + bool any_enc = false; ray_t** segs = (ray_t**)ray_data(parted); + memset(segs, 0, (size_t)part_count * sizeof(ray_t*)); for (int64_t p = 0; p < part_count; p++) { - ray_t* seg = ray_table_get_col_idx(part_tables[p], c); - if (!seg) { - segs[p] = NULL; + ray_t* seg = ray_table_get_col_enc_idx(part_tables[p], c); + if (seg) any_enc = true; + else seg = ray_table_col_idx(part_tables[p], c); /* plain slot: a lookup */ + if (seg && !RAY_IS_ERR(seg)) { + ray_retain(seg); + segs[p] = seg; continue; } - ray_retain(seg); + /* Ragged: partition p lacks this tail column. Its rows read + * as the column's nulls, so the column has the MAPCOMMON row + * count of every partition. */ + if (!seg) { + char what[1200]; + ray_t* na = ray_sym_str(name_id); + snprintf(what, sizeof what, "%s/%s/%s/%.*s (absent: nulls)", db_root, part_dirs[p], + table_name, na ? (int)ray_str_len(na) : 1, na ? ray_str_ptr(na) : "?"); + seg = missing_seg(m0.type, ray_table_nrows(part_tables[p]), dom, what); + if (seg && !RAY_IS_ERR(seg) && seg->type == RAY_ENCCOL) any_enc = true; + } + if (!seg || RAY_IS_ERR(seg)) { + ray_release(parted); /* releases the filled segs */ + ray_release(result); + part_err = seg ? seg : ray_error("oom", NULL); + goto fail_tables; + } segs[p] = seg; } - - result = ray_table_add_col(result, name_id, parted); - ray_release(parted); + ray_t* slot = parted; + if (any_enc) { + slot = ray_enccol_parted_new(parted); + ray_release(parted); + if (!slot || RAY_IS_ERR(slot)) { + ray_release(result); + part_err = slot ? slot : ray_error("oom", NULL); + goto fail_tables; + } + } + result = ray_table_add_col(result, name_id, slot); + ray_release(slot); if (!result || RAY_IS_ERR(result)) goto fail_tables; } @@ -918,22 +1052,22 @@ static ray_t* empty_table_like(ray_t* tmpl) { ray_t* out = ray_table_new(ncols); if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tmpl, c); - if (!col) { ray_release(out); return ray_error("type", "empty_table_like: null column"); } + ray_col_meta_t m; + if (!ray_table_col_meta_idx(tmpl, c, &m)) { ray_release(out); return ray_error("type", "empty_table_like: null column"); } ray_t* ecol = NULL; - if (col->type == RAY_LIST) { + if (m.type == RAY_LIST) { ecol = ray_list_new(0); - } else if (col->type == RAY_TABLE || col->type == RAY_DICT) { + } else if (m.type == RAY_TABLE || m.type == RAY_DICT) { int64_t name_id = ray_table_col_name(tmpl, c); ray_t* name = ray_sym_str(name_id); const char* name_ptr = name ? ray_str_ptr(name) : "?"; int name_len = name ? (int)ray_str_len(name) : 1; - const char* type_name = col->type == RAY_TABLE ? "TABLE" : "DICT"; + const char* type_name = m.type == RAY_TABLE ? "TABLE" : "DICT"; ray_release(out); return ray_error("nyi", "empty_table_like: column '%.*s' has unsupported nested type %s", name_len, name_ptr, type_name); } else { - ecol = ray_vec_new(col->type, 0); + ecol = ray_vec_new(m.type, 0); } if (!ecol || RAY_IS_ERR(ecol)) { ray_release(out); return ecol ? ecol : ray_error("oom", NULL); } ray_t* nout = ray_table_add_col(out, ray_table_col_name(tmpl, c), ecol); diff --git a/src/store/part.h b/src/store/part.h index 094f624b0..8ec488d68 100644 --- a/src/store/part.h +++ b/src/store/part.h @@ -49,4 +49,14 @@ ray_t* ray_parted_tables(const char* db_root); * nothing needed fixing), or an error. */ ray_t* ray_parted_fill(const char* db_root); +/* `rows` cells of `type`'s null on the heap: the sentinel ray_vec_set_null + * writes, HAS_NULLS set; the non-nullable BOOL / U8 read 0; STR cells are + * the empty string, GUID cells zero; SYM cells are id 0, the empty symbol, + * at width W8 (id 0 fits it, and it is the width a ragged partition's + * stand-in is encoded at, so its decode is this vector), resolved over + * `dom` when given; LIST cells are the null object. An owned vector, or an + * error (`oom`; `nyi` for a type without a null fill). */ +struct ray_sym_domain_s; +ray_t* ray_null_fill(int8_t type, int64_t rows, struct ray_sym_domain_s* dom); + #endif /* RAY_PART_H */ diff --git a/src/store/serde.c b/src/store/serde.c index bbf7bfb57..cbd2810ce 100644 --- a/src/store/serde.c +++ b/src/store/serde.c @@ -28,8 +28,10 @@ #include "serde.h" #include "store/col.h" #include "store/fileio.h" +#include "store/enccol.h" /* ray_enccol_is_parted */ #include "core/types.h" #include "mem/heap.h" +#include "table/table.h" #include "vec/str.h" #include "vec/vec.h" #include "ops/ops.h" @@ -211,10 +213,467 @@ static inline bool sym_enc_cacheable(ray_t* obj) { } +/* ---- Vector cell payloads ------------------------------------------------ + * The bytes after a vector's type/attrs/len header. Shared by the flat + * vector cases and the parted-column writer below, which streams each + * partition segment's cells through the same code so a parted column goes + * out byte-identical to its flat equivalent. */ + +/* Bytes per cell of a fixed-width vector type; 0 for a variable-width one. */ +static int64_t serde_fixed_esz(int8_t type) { + switch (type) { + case RAY_BOOL: case RAY_U8: return 1; + case RAY_I16: return 2; + case RAY_I32: case RAY_DATE: case RAY_TIME: + case RAY_F32: return 4; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: return 8; + case RAY_GUID: return 16; + default: return 0; + } +} + +/* SYM VECTOR cells are positions in THE VEC's domain — resolve each + * through ray_sym_vec_cell, not the global table (sym-domain Phase 2; + * identical strings while the domain is the runtime singleton). Also + * honors narrow W8/16/32 index widths. sym_cells_size and + * sym_cells_write must stay in lockstep. */ +static int64_t sym_cells_size(ray_t* obj) { + int64_t size = 0; + int64_t i = 0; + if (sym_enc_cacheable(obj)) { + const void* data = ray_data(obj); + uint8_t attrs = obj->attrs; + uint32_t seen = 0, hits = 0; + for (; i < obj->len; i++) { + int64_t id = ray_read_sym(data, i, RAY_SYM, attrs); + sym_enc_ent* e = &g_sym_enc_cache[(uint64_t)id & (SYM_ENC_CACHE_N - 1)]; + if (e->ptr && e->id == id) { size += (int64_t)e->len + 1; hits++; } + else { + ray_t* a = ray_sym_str(id); + uint32_t l = a ? (uint32_t)ray_str_len(a) : 0u; + const char* pp = a ? ray_str_ptr(a) : NULL; + if (pp) { e->ptr = pp; e->len = l; e->id = id; } + size += (int64_t)l + 1; + } + /* Thrashing column: leave the rest to the plain loop below, + * which is what this path costs without a cache. */ + if (++seen == SYM_ENC_SAMPLE && hits * 4u < seen) { i++; break; } + } + } + for (; i < obj->len; i++) { + ray_t* a = ray_sym_vec_cell(obj, i); + size += (a ? (int64_t)ray_str_len(a) : 0) + 1; + } + return size; +} + +/* Each cell as its NUL-terminated string; returns the bytes written. */ +static int64_t sym_cells_write(uint8_t* buf, ray_t* obj) { + int64_t c = 0; + int64_t i = 0; + if (sym_enc_cacheable(obj)) { + const void* data = ray_data(obj); + uint8_t attrs = obj->attrs; + uint32_t seen = 0, hits = 0; + for (; i < obj->len; i++) { + int64_t id = ray_read_sym(data, i, RAY_SYM, attrs); + sym_enc_ent* e = &g_sym_enc_cache[(uint64_t)id & (SYM_ENC_CACHE_N - 1)]; + const char* pp; uint32_t slen; + if (e->ptr && e->id == id) { pp = e->ptr; slen = e->len; hits++; } + else { + ray_t* a = ray_sym_str(id); + slen = a ? (uint32_t)ray_str_len(a) : 0u; + pp = a ? ray_str_ptr(a) : NULL; + if (pp) { e->ptr = pp; e->len = slen; e->id = id; } + } + if (slen) { memcpy(buf + c, pp, slen); c += (int64_t)slen; } + buf[c++] = '\0'; + if (++seen == SYM_ENC_SAMPLE && hits * 4u < seen) { i++; break; } + } + } + for (; i < obj->len; i++) { + ray_t* a = ray_sym_vec_cell(obj, i); + if (a) { + size_t slen = ray_str_len(a); + memcpy(buf + c, ray_str_ptr(a), slen); + c += (int64_t)slen; + } + buf[c++] = '\0'; + } + return c; +} + +/* STR cells: each as i64 length + raw bytes. */ +static int64_t str_cells_size(ray_t* obj) { + int64_t size = 0; + ray_str_t* elems = (ray_str_t*)ray_data(obj); + for (int64_t i = 0; i < obj->len; i++) + size += 8 + elems[i].len; + return size; +} + +static int64_t str_cells_write(uint8_t* buf, ray_t* obj) { + ray_str_t* elems = (ray_str_t*)ray_data(obj); + const char* pool = obj->str_pool ? (const char*)ray_data(obj->str_pool) : NULL; + int64_t c = 0; + for (int64_t i = 0; i < obj->len; i++) { + int64_t slen = (int64_t)elems[i].len; + memcpy(buf + c, &slen, 8); + c += 8; + const char* p = ray_str_t_ptr(&elems[i], pool); + memcpy(buf + c, p, (size_t)slen); + c += slen; + } + return c; +} + +/* ---- Parted tables ------------------------------------------------------- + * A parted table (.db.parted.get) holds per-partition storage views, not + * vectors: a parted column (RAY_PARTED_BASE + type) is an array of one + * segment per partition, and the partition-key column (RAY_MAPCOMMON) a key + * and a row count per partition. On the wire it is the flat table it + * stands for, written without building it: each column goes out as the + * flat vector of its type, its cells streamed segment by segment in + * partition order. The partition-key column writes each key once per row + * of its partition. A NULL segment — a partition without the column + * (ragged mode, see store/part.c) — writes that partition's rows as + * typed nulls; its row count comes from the partition-key counts, the + * table's authoritative row numbering. */ + +static bool serde_col_is_parted(ray_t* col) { + return col && !RAY_IS_ERR(col) && + (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON); +} + +/* A table slot is parted: a plain parted wrapper or MAPCOMMON, or an + * encoded column over a parted wrapper (generation-2 segments). */ +static bool serde_table_is_parted(ray_t* tbl) { + ray_t* cols = ((ray_t**)ray_data(tbl))[1]; /* plain-table */ + if (!cols || RAY_IS_ERR(cols) || cols->type != RAY_LIST) return false; + for (int64_t c = 0; c < cols->len; c++) { + ray_t* slot = ray_table_slot_idx(tbl, c); + if (serde_col_is_parted(slot)) return true; + if (slot && slot->type == RAY_ENCCOL && ray_enccol_is_parted(slot)) return true; + } + return false; +} + +typedef struct { + ray_t* tbl; /* the table; columns read through ray_table_col_idx */ + int64_t ncols; + const int64_t* counts; /* partition-key row counts, NULL if none */ + int64_t nparts; +} serde_parted_t; + +/* Column c as plain (an encoded slot's cached materialization; borrowed), + * NULL when absent or when it fails to load: the size pass + * (serde_parted_cols_size) reports a failure first, so a write meets the + * cached column. */ +static ray_t* serde_pcol(const serde_parted_t* x, int64_t c) { + ray_t* col = ray_table_col_idx(x->tbl, c); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); return NULL; } + return col; +} + +static void serde_parted_init(serde_parted_t* x, ray_t* tbl) { + ray_t* cols = ((ray_t**)ray_data(tbl))[1]; /* plain-table */ + x->tbl = tbl; + x->ncols = cols->len; + x->counts = NULL; + x->nparts = 0; + for (int64_t c = 0; c < x->ncols; c++) { + ray_t* col = serde_pcol(x, c); + if (!col || RAY_IS_ERR(col) || col->type != RAY_MAPCOMMON) continue; + ray_t* rc = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + if (rc && !RAY_IS_ERR(rc)) { + x->counts = (const int64_t*)ray_data(rc); + x->nparts = rc->len; + } + break; + } +} + +/* Rows of partition p: the partition-key count; without a key column, the + * longest segment any parted column holds for that partition. */ +static int64_t serde_part_rows(const serde_parted_t* x, int64_t p) { + if (x->counts) return p < x->nparts ? x->counts[p] : 0; + int64_t n = 0; + for (int64_t c = 0; c < x->ncols; c++) { + ray_t* col = serde_pcol(x, c); + if (!col || RAY_IS_ERR(col) || !RAY_IS_PARTED(col->type) || p >= col->len) + continue; + ray_t* seg = ((ray_t**)ray_data(col))[p]; + if (seg && !RAY_IS_ERR(seg) && seg->len > n) n = seg->len; + } + return n; +} + +/* Rows a segment slot contributes: its own length, or for a NULL segment + * the partition's row count (written as nulls). */ +static int64_t serde_seg_rows(const serde_parted_t* x, ray_t* seg, int64_t p) { + if (seg && !RAY_IS_ERR(seg)) return seg->len; + return serde_part_rows(x, p); +} + +/* Type, attrs and length of the flat vector a parted column stands for. + * HAS_NULLS is the OR over the segments (as the flattened column carries + * it), set too when a NULL segment fills rows with nulls of a nullable + * type. BOOL/U8 have no null: their missing rows are written as 0. */ +static int64_t serde_parted_header(const serde_parted_t* x, ray_t* col, + int8_t* type, uint8_t* attrs) { + int64_t total = 0; + uint8_t a = 0; + if (col->type == RAY_MAPCOMMON) { + ray_t* kv = ((ray_t**)ray_data(col))[0]; + ray_t* rc = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + *type = kv ? kv->type : 0; + if (rc) { + const int64_t* cnt = (const int64_t*)ray_data(rc); + for (int64_t p = 0; p < rc->len; p++) total += cnt[p]; + } + } else { + int8_t base = (int8_t)RAY_PARTED_BASETYPE(col->type); + ray_t** segs = (ray_t**)ray_data(col); + *type = base; + for (int64_t p = 0; p < col->len; p++) { + ray_t* seg = segs[p]; + int64_t n = serde_seg_rows(x, seg, p); + total += n; + if (seg && !RAY_IS_ERR(seg)) a |= seg->attrs & RAY_ATTR_HAS_NULLS; + else if (n > 0 && base != RAY_BOOL && base != RAY_U8 && base != RAY_LIST) + a |= RAY_ATTR_HAS_NULLS; + } + } + *attrs = a; + return total; +} + +static int64_t serde_parted_col_size(const serde_parted_t* x, ray_t* col) { + int8_t type; uint8_t attrs; + int64_t total = serde_parted_header(x, col, &type, &attrs); + if (total < 0 || total > (INT64_MAX - 32) / 16) return -1; + int64_t esz = serde_fixed_esz(type); + if (esz) return 1 + 1 + 8 + total * esz; + + int64_t size = 1 + 1 + 8; + if (col->type == RAY_MAPCOMMON) { + /* keys: DATE / I64 are fixed-width (above); SYM keys repeat */ + ray_t* kv = ((ray_t**)ray_data(col))[0]; + ray_t* rc = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + if (type != RAY_SYM || !kv || !rc) return 0; + const int64_t* cnt = (const int64_t*)ray_data(rc); + for (int64_t p = 0; p < rc->len && p < kv->len; p++) { + ray_t* a = ray_sym_vec_cell(kv, p); + size += cnt[p] * ((a ? (int64_t)ray_str_len(a) : 0) + 1); + } + return size; + } + ray_t** segs = (ray_t**)ray_data(col); + for (int64_t p = 0; p < col->len; p++) { + ray_t* seg = segs[p]; + if (!seg || RAY_IS_ERR(seg)) { + /* null rows: SYM "" + NUL, STR length 0, LIST the null marker */ + int64_t n = serde_part_rows(x, p); + if (type == RAY_SYM || type == RAY_LIST) size += n; + else if (type == RAY_STR) size += n * 8; + else return 0; + continue; + } + if (type == RAY_SYM) size += sym_cells_size(seg); + else if (type == RAY_STR) size += str_cells_size(seg); + else if (type == RAY_LIST) { + ray_t** elems = (ray_t**)ray_data(seg); + for (int64_t i = 0; i < seg->len; i++) { + int64_t child = ray_serde_size(elems[i]); + if (child <= 0) return child; + size += child; + } + } else return 0; + } + return size; +} + +/* Typed null cells of a fixed-width type (the NULL_* sentinels; GUID all + * zero bytes; BOOL/U8, which have none, 0). */ +static void serde_fill_nulls(uint8_t* buf, int8_t type, int64_t n) { + switch (type) { + case RAY_F64: { + double v = NULL_F64; + for (int64_t i = 0; i < n; i++) memcpy(buf + i * 8, &v, 8); + return; + } + case RAY_F32: { + float v = NULL_F32; + for (int64_t i = 0; i < n; i++) memcpy(buf + i * 4, &v, 4); + return; + } + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: { + int64_t v = NULL_I64; + for (int64_t i = 0; i < n; i++) memcpy(buf + i * 8, &v, 8); + return; + } + case RAY_I32: case RAY_DATE: case RAY_TIME: { + int32_t v = NULL_I32; + for (int64_t i = 0; i < n; i++) memcpy(buf + i * 4, &v, 4); + return; + } + case RAY_I16: { + int16_t v = NULL_I16; + for (int64_t i = 0; i < n; i++) memcpy(buf + i * 2, &v, 2); + return; + } + default: + memset(buf, 0, (size_t)(n * serde_fixed_esz(type))); + return; + } +} + +static int64_t serde_parted_col_write(uint8_t* buf, const serde_parted_t* x, + ray_t* col) { + int8_t type; uint8_t attrs; + int64_t total = serde_parted_header(x, col, &type, &attrs); + buf[0] = (uint8_t)type; + buf[1] = attrs; + memcpy(buf + 2, &total, 8); + int64_t c = 1 + 1 + 8; + int64_t esz = serde_fixed_esz(type); + + if (col->type == RAY_MAPCOMMON) { + ray_t* kv = ((ray_t**)ray_data(col))[0]; + ray_t* rc = ((ray_t**)ray_data(col))[1]; /* not-a-table */ + if (!kv || !rc) return 0; + const int64_t* cnt = (const int64_t*)ray_data(rc); + for (int64_t p = 0; p < rc->len && p < kv->len; p++) { + if (esz) { + const uint8_t* key = (const uint8_t*)ray_data(kv) + p * esz; + for (int64_t r = 0; r < cnt[p]; r++, c += esz) + memcpy(buf + c, key, (size_t)esz); + } else if (type == RAY_SYM) { + ray_t* a = ray_sym_vec_cell(kv, p); + size_t slen = a ? ray_str_len(a) : 0; + const char* sp = a ? ray_str_ptr(a) : NULL; + for (int64_t r = 0; r < cnt[p]; r++) { + if (slen) { memcpy(buf + c, sp, slen); c += (int64_t)slen; } + buf[c++] = '\0'; + } + } else return 0; + } + return c; + } + + ray_t** segs = (ray_t**)ray_data(col); + for (int64_t p = 0; p < col->len; p++) { + ray_t* seg = segs[p]; + if (!seg || RAY_IS_ERR(seg)) { + int64_t n = serde_part_rows(x, p); + if (esz) { + serde_fill_nulls(buf + c, type, n); + c += n * esz; + } else if (type == RAY_SYM) { + memset(buf + c, 0, (size_t)n); + c += n; + } else if (type == RAY_STR) { + memset(buf + c, 0, (size_t)(n * 8)); + c += n * 8; + } else if (type == RAY_LIST) { + memset(buf + c, RAY_SERDE_NULL, (size_t)n); + c += n; + } else return 0; + continue; + } + if (esz) { + memcpy(buf + c, ray_data(seg), (size_t)(seg->len * esz)); + c += seg->len * esz; + } else if (type == RAY_SYM) { + c += sym_cells_write(buf + c, seg); + } else if (type == RAY_STR) { + c += str_cells_write(buf + c, seg); + } else if (type == RAY_LIST) { + ray_t** elems = (ray_t**)ray_data(seg); + for (int64_t i = 0; i < seg->len; i++) { + int64_t child = ray_ser_raw(buf + c, elems[i]); + if (child <= 0) return child; + c += child; + } + } else return 0; + } + return c; +} + +/* The column list of a parted table, laid out as ray_ser_raw lays out the + * RAY_LIST of a flat table's columns. */ +static int64_t ser_note_col_failure(ray_t* err); +static int64_t serde_parted_cols_size(ray_t* tbl) { + ray_t* cl = ((ray_t**)ray_data(tbl))[1]; /* plain-table */ + for (int64_t c = 0; c < cl->len; c++) { /* a column that fails to load fails the size */ + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) return ser_note_col_failure(col); + } + serde_parted_t x; + serde_parted_init(&x, tbl); + int64_t size = 1 + 1 + 8; + for (int64_t c = 0; c < x.ncols; c++) { + ray_t* col = serde_pcol(&x, c); + int64_t child = serde_col_is_parted(col) ? serde_parted_col_size(&x, col) + : ray_serde_size(col); + if (child <= 0) return child; + size += child; + } + return size; +} + +static int64_t serde_parted_cols_write(uint8_t* buf, ray_t* tbl) { + serde_parted_t x; + serde_parted_init(&x, tbl); + ray_t* cols = ((ray_t**)ray_data(tbl))[1]; /* plain-table */ + buf[0] = (uint8_t)RAY_LIST; + buf[1] = cols->attrs & RAY_SERDE_ATTR_WIRE_MASK; + memcpy(buf + 2, &cols->len, 8); + int64_t c = 1 + 1 + 8; + for (int64_t i = 0; i < x.ncols; i++) { + ray_t* col = serde_pcol(&x, i); + int64_t child = serde_col_is_parted(col) ? serde_parted_col_write(buf + c, &x, col) + : ray_ser_raw(buf + c, col); + if (child <= 0) return child; + c += child; + } + return c; +} + /* -------------------------------------------------------------------------- * ray_serde_size — calculate serialized size (excluding IPC header) * -------------------------------------------------------------------------- */ +/* A column whose decode failed during the size phase: its code is kept here + * (the message stays in the error slot) so ray_ser reports it as itself. */ +static _Thread_local char g_ser_fail_code[8]; + +void ray_serde_fail_clear(void) { g_ser_fail_code[0] = '\0'; } +const char* ray_serde_fail_code(void) { return g_ser_fail_code[0] ? g_ser_fail_code : NULL; } + +static int64_t ser_note_col_failure(ray_t* err) { + const char* code = ray_err_code(err); + snprintf(g_ser_fail_code, sizeof g_ser_fail_code, "%s", code ? code : "domain"); + ray_error_free(err); + return -1; +} + +/* Wire size of a table's cols LIST, framed by hand: each column is read + * through ray_table_col_idx, so an encoded column is serialized from its + * cached materialization and no scratch table is built. */ +static int64_t ser_table_cols_size(ray_t* tbl, ray_t* cols_list) { + int64_t nc = cols_list ? cols_list->len : 0; + int64_t size = 1 + 1 + 8; + for (int64_t c = 0; c < nc; c++) { + ray_t* col = ray_table_col_idx(tbl, c); + if (col && RAY_IS_ERR(col)) return ser_note_col_failure(col); + int64_t child = ray_serde_size(col); + if (child <= 0) return child; + size += child; + } + return size; +} + int64_t ray_serde_size(ray_t* obj) { if (!obj) return 1; /* RAY_SERDE_NULL marker */ if (RAY_IS_ERR(obj)) return 1 + 8; /* type + sdata */ @@ -237,9 +696,9 @@ int64_t ray_serde_size(ray_t* obj) { case RAY_TIME: case RAY_F32: return 1 + 1 + 4; case RAY_I64: - if (obj->attrs & RAY_ATTR_GRAPH) return 0; + if (obj->attrs & (RAY_ATTR_GRAPH | RAY_ATTR_HNSW | RAY_ATTR_DLPROG)) return 0; return 1 + 1 + 8; - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: return 1 + 1 + 8; case RAY_GUID: return 1 + 1 + 16; case RAY_SYM: { @@ -272,50 +731,11 @@ int64_t ray_serde_size(ray_t* obj) { case RAY_TIME: case RAY_F32: return 1 + 1 + 8 + obj->len * 4; case RAY_I64: - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: return 1 + 1 + 8 + obj->len * 8; case RAY_GUID: return 1 + 1 + 8 + obj->len * 16; - case RAY_SYM: { - /* SYM VECTOR cells are positions in THE VEC's domain — resolve - * each through ray_sym_vec_cell, not the global table (sym-domain - * Phase 2; identical strings while the domain is the runtime - * singleton). Also honors narrow W8/16/32 index widths. Must - * stay in lockstep with the ray_ser_raw RAY_SYM loop below. */ - int64_t size = 1 + 1 + 8; - int64_t i = 0; - if (sym_enc_cacheable(obj)) { - const void* data = ray_data(obj); - uint8_t attrs = obj->attrs; - uint32_t seen = 0, hits = 0; - for (; i < obj->len; i++) { - int64_t id = ray_read_sym(data, i, RAY_SYM, attrs); - sym_enc_ent* e = &g_sym_enc_cache[(uint64_t)id & (SYM_ENC_CACHE_N - 1)]; - if (e->ptr && e->id == id) { size += (int64_t)e->len + 1; hits++; } - else { - ray_t* a = ray_sym_str(id); - uint32_t l = a ? (uint32_t)ray_str_len(a) : 0u; - const char* pp = a ? ray_str_ptr(a) : NULL; - if (pp) { e->ptr = pp; e->len = l; e->id = id; } - size += (int64_t)l + 1; - } - /* Thrashing column: leave the rest to the plain loop below, - * which is what this path costs without a cache. */ - if (++seen == SYM_ENC_SAMPLE && hits * 4u < seen) { i++; break; } - } - } - for (; i < obj->len; i++) { - ray_t* a = ray_sym_vec_cell(obj, i); - size += (a ? (int64_t)ray_str_len(a) : 0) + 1; - } - return size; - } - case RAY_STR: { - int64_t size = 1 + 1 + 8; - ray_str_t* elems = (ray_str_t*)ray_data(obj); - for (int64_t i = 0; i < obj->len; i++) - size += 8 + elems[i].len; /* i64 length + raw bytes */ - return size; - } + case RAY_SYM: return 1 + 1 + 8 + sym_cells_size(obj); + case RAY_STR: return 1 + 1 + 8 + str_cells_size(obj); case RAY_LIST: { int64_t size = 1 + 1 + 8; ray_t** elems = (ray_t**)ray_data(obj); @@ -331,7 +751,8 @@ int64_t ray_serde_size(ray_t* obj) { ray_t** slots = (ray_t**)ray_data(obj); int64_t schema = schema_names_serde_size(slots[0]); if (schema <= 0) return schema; - int64_t cols = ray_serde_size(slots[1]); + int64_t cols = serde_table_is_parted(obj) ? serde_parted_cols_size(obj) + : ser_table_cols_size(obj, slots[1]); /* plain-table */ if (cols <= 0) return cols; return 1 + 1 + schema + cols; } @@ -340,7 +761,7 @@ int64_t ray_serde_size(ray_t* obj) { ray_t** slots = (ray_t**)ray_data(obj); int64_t keys = ray_serde_size(slots[0]); if (keys <= 0) return keys; - int64_t vals = ray_serde_size(slots[1]); + int64_t vals = ray_serde_size(slots[1]); /* not-a-table */ if (vals <= 0) return vals; return 1 + 1 + keys + vals; } @@ -348,7 +769,7 @@ int64_t ray_serde_size(ray_t* obj) { ray_t** slots = (ray_t**)ray_data(obj); int64_t params = ray_serde_size(slots[0]); if (params <= 0) return params; - int64_t body = ray_serde_size(slots[1]); + int64_t body = ray_serde_size(slots[1]); /* not-a-table */ if (body <= 0) return body; int64_t size = 1 + 1 + params + body; if (LAMBDA_CLOSURE(obj)) { @@ -408,7 +829,8 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { * carries the typed-null marker (aux[0] & 1 on the source atom) * so (de (ser 0Nl)) roundtrips instead of decoding as plain 0. */ if (type < 0) { - if (type == -RAY_I64 && (obj->attrs & RAY_ATTR_GRAPH)) return 0; + if (type == -RAY_I64 && + (obj->attrs & (RAY_ATTR_GRAPH | RAY_ATTR_HNSW | RAY_ATTR_DLPROG))) return 0; buf[0] = (uint8_t)type; buf++; uint8_t aflags = (uint8_t)(obj->aux[0] & 1); @@ -441,7 +863,7 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { return 1 + 1 + 4; } case RAY_I64: - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: memcpy(buf, &obj->i64, 8); return 1 + 1 + 8; case RAY_F64: @@ -516,7 +938,7 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { return c; } case RAY_I64: - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: { buf[0] = wire_attrs; buf++; memcpy(buf, &obj->len, 8); buf += 8; @@ -535,61 +957,16 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { } case RAY_SYM: { /* Cells resolve through THE VEC's domain (sym-domain Phase 2); - * the wire format is unchanged — only the resolution source. - * Must stay in lockstep with the ray_serde_size RAY_SYM loop. */ + * the wire format is unchanged — only the resolution source. */ buf[0] = wire_attrs; buf++; memcpy(buf, &obj->len, 8); buf += 8; - c = 0; - { - int64_t i = 0; - if (sym_enc_cacheable(obj)) { - const void* data = ray_data(obj); - uint8_t attrs = obj->attrs; - uint32_t seen = 0, hits = 0; - for (; i < obj->len; i++) { - int64_t id = ray_read_sym(data, i, RAY_SYM, attrs); - sym_enc_ent* e = &g_sym_enc_cache[(uint64_t)id & (SYM_ENC_CACHE_N - 1)]; - const char* pp; uint32_t slen; - if (e->ptr && e->id == id) { pp = e->ptr; slen = e->len; hits++; } - else { - ray_t* a = ray_sym_str(id); - slen = a ? (uint32_t)ray_str_len(a) : 0u; - pp = a ? ray_str_ptr(a) : NULL; - if (pp) { e->ptr = pp; e->len = slen; e->id = id; } - } - if (slen) { memcpy(buf + c, pp, slen); c += (int64_t)slen; } - buf[c++] = '\0'; - if (++seen == SYM_ENC_SAMPLE && hits * 4u < seen) { i++; break; } - } - } - for (; i < obj->len; i++) { - ray_t* a = ray_sym_vec_cell(obj, i); - if (a) { - size_t slen = ray_str_len(a); - memcpy(buf + c, ray_str_ptr(a), slen); - c += (int64_t)slen; - } - buf[c++] = '\0'; - } - } - return 1 + 1 + 8 + c; + return 1 + 1 + 8 + sym_cells_write(buf, obj); } case RAY_STR: { buf[0] = wire_attrs; buf++; memcpy(buf, &obj->len, 8); buf += 8; - ray_str_t* elems = (ray_str_t*)ray_data(obj); - const char* pool = obj->str_pool ? (const char*)ray_data(obj->str_pool) : NULL; - c = 0; - for (int64_t i = 0; i < obj->len; i++) { - int64_t slen = (int64_t)elems[i].len; - memcpy(buf + c, &slen, 8); - c += 8; - const char* p = ray_str_t_ptr(&elems[i], pool); - memcpy(buf + c, p, (size_t)slen); - c += slen; - } - return 1 + 1 + 8 + c; + return 1 + 1 + 8 + str_cells_write(buf, obj); } case RAY_LIST: { @@ -614,8 +991,27 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { ray_t** slots = (ray_t**)ray_data(obj); c = ser_schema_names(buf, slots[0]); /* schema names as RAY_SYM vector */ if (c <= 0) return c; - int64_t cols = ray_ser_raw(buf + c, slots[1]); /* cols (RAY_LIST) */ - if (cols <= 0) return cols; + int64_t cols; + if (serde_table_is_parted(obj)) { /* cols (RAY_LIST) */ + cols = serde_parted_cols_write(buf + c, obj); + if (cols <= 0) return cols; + } else { + /* cols LIST framed by hand, each column through ray_table_col_idx */ + ray_t* cl = slots[1]; /* plain-table */ + int64_t ncl = cl ? cl->len : 0; /* NULL cols: 0 columns, as the size arm */ + uint8_t* lp = buf + c; + lp[0] = (uint8_t)RAY_LIST; + lp[1] = cl ? cl->attrs & RAY_SERDE_ATTR_WIRE_MASK : 0; + memcpy(lp + 2, &ncl, 8); + cols = 1 + 1 + 8; + for (int64_t i = 0; i < ncl; i++) { + ray_t* col = ray_table_col_idx(obj, i); + if (col && RAY_IS_ERR(col)) { ray_error_free(col); return -1; } + int64_t child = ray_ser_raw(lp + cols, col); + if (child <= 0) return child; + cols += child; + } + } c += cols; return 1 + 1 + c; } @@ -626,7 +1022,7 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { ray_t** slots = (ray_t**)ray_data(obj); c = ray_ser_raw(buf, slots[0]); if (c <= 0) return c; - int64_t vals = ray_ser_raw(buf + c, slots[1]); + int64_t vals = ray_ser_raw(buf + c, slots[1]); /* not-a-table */ if (vals <= 0) return vals; c += vals; return 1 + 1 + c; @@ -638,7 +1034,7 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { ray_t** slots = (ray_t**)ray_data(obj); c = ray_ser_raw(buf, slots[0]); /* params */ if (c <= 0) return c; - int64_t body = ray_ser_raw(buf + c, slots[1]); /* body */ + int64_t body = ray_ser_raw(buf + c, slots[1]); /* not-a-table */ /* body */ if (body <= 0) return body; c += body; if (LAMBDA_CLOSURE(obj)) { @@ -749,10 +1145,10 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { if (*len < 8) return ray_error("domain", "deserialize atom: truncated i64, need 8 bytes"); { int64_t v; memcpy(&v, buf, 8); *len -= 8; return is_null ? ray_typed_null(type) : ray_i64(v); } - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: if (*len < 8) return ray_error("domain", "deserialize atom: truncated timestamp, need 8 bytes"); { int64_t v; memcpy(&v, buf, 8); *len -= 8; - return is_null ? ray_typed_null(type) : ray_timestamp(v); } + return is_null ? ray_typed_null(type) : (type == -RAY_TIMESPAN ? ray_timespan(v) : ray_timestamp(v)); } case RAY_F64: if (*len < 8) return ray_error("domain", "deserialize atom: truncated f64, need 8 bytes"); { double v; memcpy(&v, buf, 8); *len -= 8; @@ -800,7 +1196,7 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { case RAY_TIME: case RAY_F32: case RAY_I64: - case RAY_TIMESTAMP: + case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_F64: case RAY_GUID: { if (*len < 9) return ray_error("domain", "deserialize vector: truncated %s header, need 9 bytes (attr+len)", ray_type_name(type)); @@ -1122,7 +1518,7 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { dict->attrs = dict_attrs & RAY_SERDE_ATTR_WIRE_MASK; dict->len = 2; ((ray_t**)ray_data(dict))[0] = keys; - ((ray_t**)ray_data(dict))[1] = vals; + ((ray_t**)ray_data(dict))[1] = vals; /* not-a-table */ return dict; } @@ -1174,7 +1570,7 @@ static ray_t* de_raw_inner(uint8_t* buf, int64_t* len) { lambda->len = 0; memset(ray_data(lambda), 0, LAMBDA_SLOTS * sizeof(ray_t*)); ((ray_t**)ray_data(lambda))[0] = params; - ((ray_t**)ray_data(lambda))[1] = body; + ((ray_t**)ray_data(lambda))[1] = body; /* not-a-table */ LAMBDA_CLOSURE(lambda) = closure; return lambda; } @@ -1226,7 +1622,15 @@ ray_t* ray_ser(ray_t* obj) { owned = true; } + g_ser_fail_code[0] = '\0'; int64_t payload = ray_serde_size(obj); + if (payload < 0 && g_ser_fail_code[0]) { /* an encoded column failed to decode */ + char code[8], msg[256]; + snprintf(code, sizeof code, "%s", g_ser_fail_code); + snprintf(msg, sizeof msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (owned) ray_release(obj); + return ray_error(code, "%s", msg); + } if (payload <= 0) { ray_t* e = ray_error("domain", payload < 0 ? "serialize: payload size overflow" @@ -1252,8 +1656,9 @@ ray_t* ray_ser(ray_t* obj) { hdr->size = payload; int64_t written = ray_ser_raw((uint8_t*)ray_data(buf) + sizeof(ray_ipc_header_t), obj); - if (written == 0) { - ray_t* e = ray_error("domain", "serialize: ray_ser_raw wrote 0 bytes for %s", ray_type_name(obj->type)); + if (written != payload) { + ray_t* e = ray_error("domain", "serialize: ray_ser_raw wrote %lld of %lld bytes for %s", + (long long)written, (long long)payload, ray_type_name(obj->type)); ray_release(buf); if (owned) ray_release(obj); return e; diff --git a/src/store/serde.h b/src/store/serde.h index 29ce445a1..84b76d4d7 100644 --- a/src/store/serde.h +++ b/src/store/serde.h @@ -83,6 +83,12 @@ ray_t* ray_ser(ray_t* obj); /* Top-level: deserialize from U8 vector (validates IPC header) */ ray_t* ray_de(ray_t* bytes); +/* After ray_serde_size() returned < 0: the error code of the encoded column + * whose decode failed (its message is in ray_error_msg()), or NULL when the + * object was simply not serializable. */ +const char* ray_serde_fail_code(void); +void ray_serde_fail_clear(void); /* call before ray_serde_size */ + /* File I/O: save/load any object in binary format */ ray_err_t ray_obj_save(ray_t* obj, const char* path); ray_t* ray_obj_load(const char* path); diff --git a/src/store/splay.c b/src/store/splay.c index 069747a1e..a74396315 100644 --- a/src/store/splay.c +++ b/src/store/splay.c @@ -29,6 +29,8 @@ #include "core/pool.h" #include "mem/sys.h" #include "store/col.h" +#include "store/enccol.h" +#include "store/encfmt.h" #include "store/fileio.h" #include "store/serde.h" #include "table/sym.h" @@ -36,7 +38,6 @@ #include "table/domain.h" #include "ops/idxop.h" #include "core/profile.h" -#include "io/csv.h" /* ray_csv_hash_upgrade_check — shared index policy */ #include "vec/str.h" #include "lang/format.h" #include @@ -68,13 +69,51 @@ * format) and needs no symfile. */ static bool table_has_sym_cols(ray_t* tbl) { int64_t nc = ray_table_ncols(tbl); - for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (col && !RAY_IS_ERR(col) && col->type == RAY_SYM) return true; - } + ray_col_meta_t m; + for (int64_t c = 0; c < nc; c++) + if (ray_table_col_meta_idx(tbl, c, &m) && m.type == RAY_SYM) return true; return false; } +/* The slot object of column c: its RAY_ENCCOL, or the plain column. Never + * decodes. */ +static ray_t* splay_slot(ray_t* tbl, int64_t c) { + ray_t* e = ray_table_get_col_enc_idx(tbl, c); + return e ? e : ray_table_col_idx(tbl, c); +} + +/* The symfile of SYM column `name` under the per-column layout: the dotfile + * `/..sym` next to the column file (dir: the directory holding + * the columns, a generation or the table root of a table written once). + * Column names never start with '.', so the name cannot be a column's; every + * file derived from a symfile (`.ix`, `.lk`, `.tmp`) carries a suffix past + * `.sym`, so it cannot be another column's symfile either. */ +bool ray_splay_col_sym_path(char* out, size_t cap, const char* dir, + const char* name, size_t name_len) { + if (!out || !cap || !dir || !name) return false; + int n = snprintf(out, cap, "%s/.%.*s.sym", dir, (int)name_len, name); + return n > 0 && (size_t)n < cap; +} + +ray_t* ray_symfile_opt_parse(ray_t* opts, ray_symfile_t* layout) { + *layout = RAY_SYMFILE_SHARED; + if (!opts || opts->type != RAY_DICT) return NULL; + ray_t* key = ray_sym(ray_sym_intern("symfile", 7)); + if (!key || RAY_IS_ERR(key)) return key ? key : ray_error("oom", NULL); + ray_t* v = ray_dict_get(opts, key); + ray_release(key); + if (!v) return NULL; + if (RAY_IS_ERR(v)) return v; + ray_t* s = v->type == -RAY_SYM ? ray_sym_str(v->i64) : NULL; + bool ok = s && !RAY_IS_ERR(s); + if (ok && ray_str_len(s) == 6 && memcmp(ray_str_ptr(s), "column", 6) == 0) + *layout = RAY_SYMFILE_COLUMN; + else if (!(ok && ray_str_len(s) == 6 && memcmp(ray_str_ptr(s), "shared", 6) == 0)) + ok = false; + ray_release(v); + return ok ? NULL : ray_error("domain", "symfile must be 'shared or 'column"); +} + /* -------------------------------------------------------------------------- * ray_splay_save — save a table to a splayed table directory * -------------------------------------------------------------------------- */ @@ -247,7 +286,22 @@ static ray_err_t splay_has_file(const char* dir, const char* name, bool* exists) return *exists || errno == ENOENT ? RAY_OK : RAY_ERR_IO; } +/* Removes what `path` names, best effort. A link goes, never what it + * points to: opendir follows a link, so the path is examined with lstat + * first and only a real directory is descended. Every caller relies on + * this: the generation prune (a link placed directly under .generations), + * the staged-directory removal and the clearing of a failed first write. */ static void splay_remove_tree_best_effort(const char* path) { + struct stat top; +#ifdef RAY_OS_WINDOWS + if (stat(path, &top) != 0) return; +#else + if (lstat(path, &top) != 0) return; +#endif + if (!S_ISDIR(top.st_mode)) { + (void)unlink(path); + return; + } DIR* d = opendir(path); if (!d) { (void)unlink(path); @@ -334,6 +388,24 @@ static void splay_retire_legacy_schema(const char* root) { if (S_ISDIR(st.st_mode)) continue; /* not a column file */ if (unlink(path) != 0) all_gone = false; } + /* the column's own symfile (per-column layout) and its index and + * lock: they describe the root column only */ + static const char* const sym_suffix[] = {"", ".ix", ".lk"}; + char spath[1100]; + if (all_gone && ray_splay_col_sym_path(spath, sizeof(spath), root, name, len)) { + size_t sl = strlen(spath); + for (size_t k = 0; all_gone && k < sizeof(sym_suffix) / sizeof(sym_suffix[0]); k++) { + if (sl + strlen(sym_suffix[k]) >= sizeof(spath)) break; + memcpy(spath + sl, sym_suffix[k], strlen(sym_suffix[k]) + 1); + struct stat st; +#ifdef RAY_OS_WINDOWS + if (stat(spath, &st) != 0) continue; +#else + if (lstat(spath, &st) != 0) continue; +#endif + if (!S_ISDIR(st.st_mode) && unlink(spath) != 0) all_gone = false; + } + } } ray_release(names); if (all_gone) (void)unlink(retired); @@ -381,7 +453,12 @@ static ray_err_t splay_validate_save(ray_t* tbl, const char* dir, * columns have already replaced an existing committed generation. */ int64_t preflight_ncols = ray_table_ncols(tbl); for (int64_t c = 0; c < preflight_ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = splay_slot(tbl, c); + if (col && RAY_IS_ERR(col)) { /* a failed decode: its code, message left in the slot */ + ray_err_t derr = ray_err_from_obj(col); + ray_error_free(col); + return derr; + } ray_err_t err = ray_col_save_preflight(col); if (err != RAY_OK) return err; } @@ -426,10 +503,54 @@ static ray_err_t splay_validate_save(ray_t* tbl, const char* dir, return RAY_OK; } +static void splay_build_indexes_gens(const char* dir, ray_t* tbl, const uint8_t* gens); + +/* Distinct-merge SYM column `col`'s vocabulary into `dom` (find-or-append, + * by a walk of its cells read by range, so an encoded column decodes one + * vector at a time through its own domain). A column already over `dom` + * is merged by construction. */ +static ray_err_t splay_merge_vocab(ray_t* col, ray_sym_domain_t* dom) { + ray_col_src_t src; + ray_t* berr = ray_col_src_bind(col, &src); + if (berr) { ray_err_t e = ray_err_from_obj(berr); ray_error_free(berr); return e; } + if (src.dom == dom) { ray_col_src_release(&src); return RAY_OK; } /* already merged */ + ray_col_scratch_t scr; ray_col_scratch_init(&scr); + ray_err_t merr = RAY_OK; + for (int64_t r = 0; merr == RAY_OK && r < src.len; ) { + ray_col_range_t v; + ray_t* rerr = ray_col_range(&src, r, src.len - r, &scr, &v); + if (rerr) { merr = ray_err_from_obj(rerr); ray_error_free(rerr); break; } + if (v.n <= 0) { merr = RAY_ERR_CORRUPT; break; } + for (int64_t i = 0; i < v.n; i++) { + ray_t* str = ray_sym_domain_str(v.dom, ray_read_sym(v.data, i, RAY_SYM, v.attrs)); + if (!str) { merr = RAY_ERR_CORRUPT; break; } + if (ray_sym_domain_intern(dom, ray_str_ptr(str), ray_str_len(str)) < 0) { + merr = RAY_ERR_OOM; + break; + } + } + r += v.n; + } + ray_col_scratch_free(&scr); + ray_col_src_release(&src); + return merr; +} + +static void splay_release_cdoms(ray_sym_domain_t** cdoms, int64_t n) { + if (!cdoms) return; + for (int64_t c = 0; c < n; c++) + if (cdoms[c]) ray_sym_domain_release(cdoms[c]); + ray_free_raw(cdoms); +} + +/* write: the held lock's state (mode, current generation; receives the + * resolved generations), or NULL for a private directory. */ static ray_err_t splay_write_table_impl(ray_t* tbl, const char* dir, const char* sym_path, bool durable, - bool flush_sym, bool build_indexes) { - ray_err_t validation = splay_validate_save(tbl, dir, sym_path); + bool flush_sym, bool build_indexes, + ray_compress_t mode, ray_splay_write_t* write, + bool sym_col) { + ray_err_t validation = splay_validate_save(tbl, dir, sym_col ? NULL : sym_path); if (validation != RAY_OK) return validation; /* Create directory and any missing parents (mkdir -p semantics). * Required for partitioned layouts like "/db/2024.01.01/t/" where the @@ -437,6 +558,30 @@ static ray_err_t splay_write_table_impl(ray_t* tbl, const char* dir, ray_err_t mkdir_err = ray_mkdir_p(dir); if (mkdir_err != RAY_OK) return mkdir_err; + /* 0. Each file's generation, decided once and before anything is + * written: the option, else the source (an encoded slot stays 2), + * else the destination's current generation (read under its lock + * by ray_splay_write_begin). */ + int64_t ncols_res = ray_table_ncols(tbl); + uint8_t* gens = ray_calloc_raw((size_t)(ncols_res > 0 ? ncols_res : 1)); + if (!gens) return RAY_ERR_OOM; + for (int64_t c = 0; c < ncols_res; c++) { + ray_t* na = ray_sym_str(ray_table_col_name(tbl, c)); + if (!na) continue; + if (write && write->cur_err != RAY_OK && + ray_col_resolve_needs_dest(mode, splay_slot(tbl, c))) { + ray_free_raw(gens); + return write->cur_err; /* inheritance needs the destination */ + } + ray_err_t gerr = ray_col_resolve_gen_err(mode, splay_slot(tbl, c), + write ? write->cur : NULL, + ray_str_ptr(na), ray_str_len(na), &gens[c]); + if (gerr != RAY_OK) { ray_free_raw(gens); return gerr; } /* nothing written yet */ + } + if (write) { ray_free_raw(write->gens); write->gens = gens; write->ngens = ncols_res; } + ray_err_t ret = RAY_OK; + ray_t* schema = NULL; + /* 1. Symfile FIRST — column data must never reference positions the * symfile doesn't persist (crash ordering: sym → columns → .d). * @@ -445,14 +590,48 @@ static ray_err_t splay_write_table_impl(ray_t* tbl, const char* dir, * column's vocabulary into it (append-only — existing positions * stay; the find-or-append rides the cell walk), flush, then * write columns re-encoded as positions during the column pass. + * The walk reads each source by range, so an encoded column is + * decoded one vector at a time through its own domain. * * Skipped entirely for symbol-free tables: nothing to enumerate * (spec: no-symbol-columns exemption). */ ray_sym_domain_t* dom = NULL; - if (table_has_sym_cols(tbl)) { - if (!sym_path) return RAY_ERR_DOMAIN; /* SYM columns need a symfile */ + ray_sym_domain_t** cdoms = NULL; /* per-column layout: column c's own, or NULL */ + if (table_has_sym_cols(tbl) && sym_col) { + /* Per-column layout: every SYM column gets its own symfile next to + * its column file (ray_splay_col_sym_path), holding that column's + * vocabulary only, so a scan of one column reads its strings and no + * other column's. Same order as the shared layout: each symfile + * merged and flushed before any column is written. */ + cdoms = ray_calloc_raw((size_t)(ncols_res > 0 ? ncols_res : 1) * sizeof(*cdoms)); + if (!cdoms) { ret = RAY_ERR_OOM; goto out; } + for (int64_t c = 0; c < ncols_res; c++) { + ray_t* col = splay_slot(tbl, c); + ray_col_meta_t m; + if (!col || RAY_IS_ERR(col) || !ray_col_meta_of(col, &m) || m.type != RAY_SYM) + continue; + ray_t* na = ray_sym_str(ray_table_col_name(tbl, c)); + char cpath[1024]; + if (!na || !ray_splay_col_sym_path(cpath, sizeof(cpath), dir, + ray_str_ptr(na), ray_str_len(na))) { + ret = RAY_ERR_RANGE; + goto out; + } + cdoms[c] = ray_sym_domain_open_or_create(cpath); + if (!cdoms[c]) { ret = RAY_ERR_IO; goto out; } + if (ray_sym_domain_count(cdoms[c]) == 0 && + ray_sym_domain_intern(cdoms[c], "", 0) != 0) { /* see the seeding below */ + ret = RAY_ERR_OOM; + goto out; + } + ray_err_t merr = splay_merge_vocab(col, cdoms[c]); + if (merr == RAY_OK && flush_sym) merr = ray_sym_domain_flush(cdoms[c], durable); + if (merr != RAY_OK) { ret = merr; goto out; } + } + } else if (table_has_sym_cols(tbl)) { + if (!sym_path) { ret = RAY_ERR_DOMAIN; goto out; } /* SYM columns need a symfile */ dom = ray_sym_domain_open_or_create(sym_path); - if (!dom) return RAY_ERR_IO; + if (!dom) { ret = RAY_ERR_IO; goto out; } /* Empty-vocabulary seeding: a 0-row SYM table merges nothing * below, and ray_sym_domain_flush no-ops at count == disk_count @@ -464,44 +643,38 @@ static ray_err_t splay_write_table_impl(ray_t* tbl, const char* dir, * non-empty vocabulary the intern is a find hit, a no-op). */ if (ray_sym_domain_count(dom) == 0 && ray_sym_domain_intern(dom, "", 0) != 0) { - ray_sym_domain_release(dom); - return RAY_ERR_OOM; + ret = RAY_ERR_OOM; + goto out; } int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (!col || RAY_IS_ERR(col) || col->type != RAY_SYM) continue; - if (ray_sym_vec_domain(col) == dom) continue; /* already merged */ - for (int64_t i = 0; i < col->len; i++) { - ray_t* s = ray_sym_vec_cell(col, i); - if (!s) { ray_sym_domain_release(dom); return RAY_ERR_CORRUPT; } - if (ray_sym_domain_intern(dom, ray_str_ptr(s), - ray_str_len(s)) < 0) { - ray_sym_domain_release(dom); - return RAY_ERR_OOM; - } - } + ray_t* col = splay_slot(tbl, c); + ray_col_meta_t m; + if (!col || RAY_IS_ERR(col) || !ray_col_meta_of(col, &m) || m.type != RAY_SYM) + continue; + ray_err_t merr = splay_merge_vocab(col, dom); + if (merr != RAY_OK) { ret = merr; goto out; } } ray_err_t sym_err = flush_sym ? ray_sym_domain_flush(dom, durable) : RAY_OK; - if (sym_err != RAY_OK) { - ray_sym_domain_release(dom); - return sym_err; - } + if (sym_err != RAY_OK) { ret = sym_err; goto out; } } int64_t ncols = ray_table_ncols(tbl); - /* 2. Write the column files in the caller's unpublished directory. */ - ray_t* schema = ray_vec_new(RAY_STR, ncols > 0 ? ncols : 1); + /* 2. Write the column files in the caller's unpublished directory, each + * in its resolved generation, from the slot object (an encoded slot + * is read by range for generation 2). */ + schema = ray_vec_new(RAY_STR, ncols > 0 ? ncols : 1); if (!schema || RAY_IS_ERR(schema)) { if (schema) ray_release(schema); - if (dom) ray_sym_domain_release(dom); - return RAY_ERR_OOM; + schema = NULL; + ret = RAY_ERR_OOM; + goto out; } for (int64_t c = 0; c < ncols; c++) { - ray_t* col = ray_table_get_col_idx(tbl, c); + ray_t* col = splay_slot(tbl, c); if (!col) continue; ray_t* name_atom = ray_sym_str(ray_table_col_name(tbl, c)); if (!name_atom) continue; @@ -515,58 +688,95 @@ static ray_err_t splay_write_table_impl(ray_t* tbl, const char* dir, int path_len = snprintf(path, sizeof(path), "%s/%.*s", dir, (int)name_len, name); if (path_len < 0 || (size_t)path_len >= sizeof(path)) { - ray_release(schema); - if (dom) ray_sym_domain_release(dom); - return RAY_ERR_RANGE; - } - ray_err_t err = (col->type == RAY_SYM) - ? ray_col_save_sym_encoded(col, path, dom, durable) - : (durable ? ray_col_save(col, path) - : ray_col_save_bulk(col, path)); - if (err != RAY_OK) { - /* No new .d or .current is published on failure. */ - ray_release(schema); - if (dom) ray_sym_domain_release(dom); - return err; + ret = RAY_ERR_RANGE; + goto out; } + ray_col_meta_t m; + ray_col_meta_of(col, &m); + ray_col_write_t w; + memset(&w, 0, sizeof w); + ray_t* berr = ray_col_src_bind(col, &w.src); + if (berr) { ret = ray_err_from_obj(berr); ray_error_free(berr); goto out; } + w.name = name; + w.gen = gens[c]; + w.target_dom = m.type != RAY_SYM ? NULL : cdoms ? cdoms[c] : dom; + w.durable = durable; + /* Generation 0 persists a chunk zone for numeric columns of at least + * one chunk (ray_splay_build_indexes); generation 2 records it when + * the column records no other kind (a stale root records none). */ + uint8_t rec_kind = m.index_kind, rec_flags = 0; + if (ray_is_vec(col)) ray_col_gen2_index_meta(col, &rec_kind, &rec_flags); + if (w.gen == 2 && build_indexes && ray_zone_acc_supported(m.type) && + m.len >= RAY_ENC_CHUNK && rec_kind == 0) + w.index_kind = RAY_IDX_CHUNK_ZONE; + /* generation 0 builds a STR DICT in the same pass (splay_build_index_col): + * at least RAY_DICT_MIN_ROWS rows, unless a HASH takes the slot */ + if (w.gen == 2 && build_indexes && ray_col_dict_wanted(m.type, m.len) && rec_kind != RAY_IDX_HASH) + w.index_kind = RAY_IDX_DICT; + ray_err_t err = ray_col_save_ctx(&w, path); + ray_col_src_release(&w.src); + /* No new .d or .current is published on failure. */ + if (err != RAY_OK) { ret = err; goto out; } schema = ray_str_vec_append(schema, name, name_len); if (!schema || RAY_IS_ERR(schema)) { if (schema) ray_release(schema); - if (dom) ray_sym_domain_release(dom); - return RAY_ERR_OOM; + schema = NULL; + ret = RAY_ERR_OOM; + goto out; } } - if (dom) ray_sym_domain_release(dom); + if (dom) { ray_sym_domain_release(dom); dom = NULL; } + splay_release_cdoms(cdoms, ncols_res); + cdoms = NULL; /* Indexes belong to this generation and must precede publication. They are * rebuildable accelerators; ray_col_append_index writes the marker last and - * intentionally does not fsync them again after ray_col_save fsyncs data. */ + * intentionally does not fsync them again after ray_col_save fsyncs data. + * Generation-2 files record theirs in the enc header instead. */ if (build_indexes) - ray_splay_build_indexes(dir, tbl); + splay_build_indexes_gens(dir, tbl, gens); + + /* A cancel before the commit marker leaves nothing committed: the + * write finish removes what this save created. */ + if (ray_interrupted()) { + ray_release(schema); + return RAY_ERR_CANCEL; + } /* 3. .d LAST — the commit marker. */ { char path[1024]; int path_len = snprintf(path, sizeof(path), "%s/.d", dir); if (path_len < 0 || (size_t)path_len >= sizeof(path)) { - ray_release(schema); - return RAY_ERR_RANGE; + ret = RAY_ERR_RANGE; + goto out; } ray_err_t err = durable ? ray_col_save(schema, path) : ray_col_save_bulk(schema, path); - ray_release(schema); - if (err != RAY_OK) return err; + if (err != RAY_OK) { ret = err; goto out; } } /* 4. Sweep files that are no longer part of the table. */ splay_sweep_stale(tbl, dir); - return RAY_OK; +out: + if (schema) ray_release(schema); + if (dom) ray_sym_domain_release(dom); + splay_release_cdoms(cdoms, ncols_res); + if (!write) ray_free_raw(gens); + return ret; } ray_err_t ray_splay_write_table(ray_t* tbl, const char* dir, const char* sym_path, bool durable) { - return splay_write_table_impl(tbl, dir, sym_path, durable, true, true); + return splay_write_table_impl(tbl, dir, sym_path, durable, true, true, + RAY_COMPRESS_ABSENT, NULL, false); +} + +ray_err_t ray_splay_write_table_ctx(ray_t* tbl, ray_splay_write_t* write, + const char* sym_path, bool durable) { + return splay_write_table_impl(tbl, write->dir, sym_path, durable, true, true, + write->mode, write, write->sym_col); } #ifdef RAY_OS_WINDOWS @@ -733,6 +943,13 @@ static void splay_remove_created(const ray_splay_write_t* write, bool unlink_loc ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, bool durable) { + /* The last moment a cancel can stop a staged write: its generation is + * not published yet, so the call reports the cancel and the previous + * one stays current. A first write commits in place with its .d, so + * the writers check before writing it; this check is the deliberate + * backstop for the .d write itself and for writers yet to come. */ + if (result == RAY_OK && write->staged && ray_interrupted()) + result = RAY_ERR_CANCEL; if (result == RAY_OK && write->staged) { /* ray_file_sync_dir syncs the PARENT of its argument. */ char schema[1100]; @@ -773,6 +990,9 @@ ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, write->before = NULL; write->nbefore = 0; } + ray_free_raw(write->gens); + write->gens = NULL; + write->ngens = 0; bool unlink_lock = locked || write->unlink_lock; #ifndef RAY_OS_WINDOWS /* Under the lock; a writer waiting on it then finds its lock file @@ -862,6 +1082,15 @@ ray_err_t ray_splay_write_begin(const char* dir, ray_splay_write_t* write) { if (err == RAY_OK) err = splay_has_file(write->root, ".current", ¤t); if (err != RAY_OK) return ray_splay_write_finish(write, err, false); write->staged = schema || current; + /* The destination's current generation, read under the lock: the + * generation inheritance rule compares against it. */ + write->cur[0] = '\0'; + if (write->staged) { + /* A failure matters only to a column that inherits from the + * destination (splay_write_table_impl); explicit modes proceed. */ + write->cur_err = ray_splay_resolve_dir(write->root, write->cur, sizeof write->cur); + if (write->cur_err != RAY_OK) write->cur[0] = '\0'; + } if (!write->staged) { splay_snapshot_root(write); memcpy(write->dir, write->root, len + 1); @@ -893,27 +1122,58 @@ ray_err_t ray_splay_write_begin(const char* dir, ray_splay_write_t* write) { return RAY_OK; } +ray_err_t ray_splay_write_begin_mode(const char* dir, ray_compress_t mode, + ray_splay_write_t* write) { + ray_err_t err = ray_splay_write_begin(dir, write); + if (err == RAY_OK) write->mode = mode; + return err; +} + static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, - const char* sym_path, bool durable) { - ray_err_t err = splay_validate_save(tbl, dir, sym_path); + const char* sym_path, bool durable, + ray_compress_t mode, bool sym_col) { + /* the per-column layout writes no shared symfile: no collision to check */ + ray_err_t err = splay_validate_save(tbl, dir, sym_col ? NULL : sym_path); if (err != RAY_OK) return err; ray_splay_write_t write; - err = ray_splay_write_begin(dir, &write); + err = ray_splay_write_begin_mode(dir, mode, &write); if (err != RAY_OK) return err; - err = ray_splay_write_table(tbl, write.dir, sym_path, durable); + write.sym_col = sym_col; + err = ray_splay_write_table_ctx(tbl, &write, sym_path, durable); return ray_splay_write_finish(&write, err, durable); } ray_err_t ray_splay_save(ray_t* tbl, const char* dir, const char* sym_path) { - return splay_save_impl(tbl, dir, sym_path, true); + return splay_save_impl(tbl, dir, sym_path, true, RAY_COMPRESS_ABSENT, false); } ray_err_t ray_splay_save_bulk(ray_t* tbl, const char* dir, const char* sym_path) { - return splay_save_impl(tbl, dir, sym_path, false); + return splay_save_impl(tbl, dir, sym_path, false, RAY_COMPRESS_ABSENT, false); +} + +ray_err_t ray_splay_save_mode(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode) { + return splay_save_impl(tbl, dir, sym_path, true, mode, false); +} + +ray_err_t ray_splay_save_bulk_mode(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode) { + return splay_save_impl(tbl, dir, sym_path, false, mode, false); +} + +ray_err_t ray_splay_save_layout(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode, ray_symfile_t layout) { + return splay_save_impl(tbl, dir, sym_path, true, mode, layout == RAY_SYMFILE_COLUMN); } ray_err_t ray_splay_save_staged_bulk(ray_t* tbl, const char* dir, const char* sym_path) { - return splay_write_table_impl(tbl, dir, sym_path, false, false, false); + return splay_write_table_impl(tbl, dir, sym_path, false, false, false, + RAY_COMPRESS_ABSENT, NULL, false); +} + +ray_err_t ray_splay_save_staged_bulk_mode(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode) { + return splay_write_table_impl(tbl, dir, sym_path, false, false, false, mode, NULL, false); } /* -------------------------------------------------------------------------- @@ -924,8 +1184,11 @@ ray_err_t ray_splay_save_staged_bulk(ray_t* tbl, const char* dir, const char* sy * The .d schema is always loaded via ray_col_load (small, buddy copy). * -------------------------------------------------------------------------- */ +/* col_syms: a column's own symfile (the per-column layout) is honoured; a + * partition of a parted table (ray_read_splayed_dom) refuses one instead, + * as its segments must all resolve over the table's one domain. */ static ray_t* splay_load_dom_impl(const char* dir, ray_sym_domain_t* dom, - bool use_mmap) { + bool use_mmap, bool col_syms) { if (!dir) return ray_error("io", NULL); bool trace = getenv("RAY_CSV_TRACE") != NULL; if (trace) @@ -995,20 +1258,63 @@ static ray_t* splay_load_dom_impl(const char* dir, ray_sym_domain_t* dom, dir, (long long)c, sizeof(path)); } + /* A column written with the per-column layout resolves over its + * own symfile, `/..sym` (ray_splay_col_sym_path), in + * place of the table's. The name is a dotfile no column can have, + * and only that layout's writers make it. */ + ray_sym_domain_t* cdom = NULL; + { + char spath[1100]; + struct stat sst; + if (!ray_splay_col_sym_path(spath, sizeof(spath), dir, name, name_len)) { + ray_release(schema); + ray_release(tbl); + return ray_error("range", "splayed %s: symfile path for column '%.*s' is too long", + dir, (int)name_len, name); + } + if (stat(spath, &sst) == 0 && !col_syms) { + ray_release(schema); + ray_release(tbl); + return ray_error("nyi", "splayed %s: column '%.*s' has a symfile of its own " + "(symfile 'column), which a partition does not take", + dir, (int)name_len, name); + } + if (stat(spath, &sst) == 0) { + cdom = ray_sym_domain_open(spath); + if (!cdom) { + ray_release(schema); + ray_release(tbl); + return ray_error("corrupt", + "symfile %s: unreadable or invalid (bad magic, torn " + "record, or missing \"\" at position 0)", spath); + } + } else if (errno != ENOENT) { + ray_release(schema); + ray_release(tbl); + return ray_error("io", "symfile %s: cannot stat", spath); + } + } + ray_sym_domain_t* udom = cdom ? cdom : dom; + /* Domain-attaching loaders: a SYM column resolves over the * table's symfile (dom); dom == NULL + SYM column is the loud * "sym" error from the col loader (spec: never silent * resolution against incidental state). */ - ray_t* col = use_mmap ? ray_col_mmap_splayed_dom(path, dom) - : ray_col_load_dom(path, dom); + ray_t* col = use_mmap ? ray_col_mmap_splayed_dom(path, udom) + : ray_col_load_dom(path, udom); if (use_mmap && col && RAY_IS_ERR(col) && - strcmp(ray_err_code(col), "nyi") == 0) { + strcmp(ray_err_code(col), "nyi") == 0 && ray_error_msg() == NULL) { + /* Contract: the generation-0 mmap refusals that the plain loader + * can still serve (col.c) are message-less "nyi"; a "nyi" with a + * message is final (a generation-2 file on a big-endian host) + * and must reach the caller unchanged. */ /* ray_release on an error object is a no-op (rayforce.h:180); * must use ray_error_free to actually reclaim the error * before retrying with the non-mmap loader. */ ray_error_free(col); - col = ray_col_load_dom(path, dom); + col = ray_col_load_dom(path, udom); } + if (cdom) ray_sym_domain_release(cdom); /* the column holds its own */ if (!col || RAY_IS_ERR(col)) { if (trace) fprintf(stderr, "splayed.get: col load failed path=%s err=%s\n", @@ -1028,17 +1334,6 @@ static ray_t* splay_load_dom_impl(const char* dir, ray_sym_domain_t* dom, dir, (int)name_len, name); } - if (c > 0 && col->len != ray_table_nrows(tbl)) { - ray_t* err = ray_error("corrupt", - "splayed %s: column '%.*s' has %lld rows, expected %lld " - "(torn overwrite?)", dir, (int)name_len, name, - (long long)col->len, (long long)ray_table_nrows(tbl)); - ray_release(col); - ray_release(schema); - ray_release(tbl); - return err; - } - ray_t* new_df = ray_table_add_col(tbl, name_id, col); if (!new_df || RAY_IS_ERR(new_df)) { ray_release(col); @@ -1114,18 +1409,40 @@ static ray_t* splay_load_once(const char* dir, const char* sym_path, if (*held) { ray_sym_domain_release(*held); *held = NULL; } if (!dom) return ray_error("corrupt", - "symfile %s: unreadable or invalid (bad magic, torn " - "record, or missing \"\" at position 0)", sym_path); + "symfile %s: unreadable or not a symfile", sym_path); } } /* An earlier attempt's domain not replaced above (no symfile this * time) is let go here, before *held is overwritten. */ if (*held) ray_sym_domain_release(*held); - ray_t* tbl = splay_load_dom_impl(resolved, dom, use_mmap); + ray_t* tbl = splay_load_dom_impl(resolved, dom, use_mmap, true); *held = dom; /* released by the caller; columns hold their own refs */ return tbl; } +/* The table's symbol files read whole while the memory left after them + * still holds RAY_SYM_PRELOAD_COLS (default 1) of its columns at 8 bytes a + * row: the room a query's columns and its work take. One file per column + * goes in column order, so a small machine reads some of them. */ +static void splay_preload_syms(ray_t* tbl) { + int64_t k = 1; + const char* e = getenv("RAY_SYM_PRELOAD_COLS"); + if (e && *e) k = atoll(e); + int64_t headroom = k * ray_table_nrows(tbl) * 8; + int64_t nc = ray_table_ncols(tbl); + for (int64_t c = 0; c < nc; c++) { + ray_t* col = ray_table_slot_idx(tbl, c); + if (!col) continue; + ray_sym_domain_t* d = NULL; + if (col->type == RAY_SYM) d = col->sym_domain; + else if (col->type == RAY_ENCCOL) { + ray_enccol_t* ec = ray_enccol_of(col); + if (ec && ec->type == RAY_SYM) d = ec->dom; + } + if (d && d != ray_sym_runtime_domain()) ray_sym_domain_preload(d, headroom); + } +} + static ray_t* splay_load_impl(const char* dir, const char* sym_path, bool use_mmap) { char resolved[1024]; @@ -1141,6 +1458,7 @@ static ray_t* splay_load_impl(const char* dir, const char* sym_path, if (!why) break; ray_error_free(tbl); } + if (tbl && !RAY_IS_ERR(tbl)) splay_preload_syms(tbl); if (held) ray_sym_domain_release(held); return tbl; } @@ -1163,14 +1481,6 @@ ray_t* ray_splay_load(const char* dir, const char* sym_path) { return splay_load_impl(dir, sym_path, false); } -/* `dir`/ into out[cap]; false when it does not fit. */ -static bool splay_col_path(const char* dir, ray_t* tbl, int64_t c, char* out, size_t cap) { - ray_t* nstr = ray_sym_str(ray_table_col_name(tbl, c)); - if (!nstr || RAY_IS_ERR(nstr)) return false; - int n = snprintf(out, cap, "%s/%.*s", dir, (int)ray_str_len(nstr), ray_str_ptr(nstr)); - return n > 0 && (size_t)n < cap; -} - /* Hash-index `col` and append the index to its index-less file `path`: * built in place in the file (no copy of the column, the arrays written * once), or where that does not apply, attached to a copy and appended. */ @@ -1195,13 +1505,17 @@ static ray_err_t splay_hash_append(const char* path, ray_t* col) { /* Index one column of a just-written splayed table (see * ray_splay_build_indexes). Columns are independent — each reads and * appends to its own file — so the caller runs one task per column. */ -/* deferred: when non-NULL and the column qualifies for a hash index, the - * computed zone is stored there instead of persisted and nothing is written; - * splay_persist_hash_or_zone finishes the column. */ -static void splay_build_index_col(const char* dir, ray_t* tbl, int64_t c, ray_t** deferred) { +/* gens: the resolved generation per column, or NULL (all generation 0); a + * generation-2 file records its index in the enc header and is skipped. */ +static void splay_build_index_col(const char* dir, ray_t* tbl, int64_t c, + const uint8_t* gens) { + /* Index policy (compressed-columns PI): no heuristic HASH is persisted + * for any generation; only explicit .idx.hash indexes are (below). + * A generation-2 file records its zone in the enc header. */ + if (gens && gens[c] == 2) return; { - ray_t* col = ray_table_get_col_idx(tbl, c); - if (!col || RAY_IS_ERR(col)) return; + ray_t* col = ray_table_col_idx(tbl, c); + if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return; } /* best effort: no index */ /* Explicit SYM index: a SYM column carrying a grouped (hash) index in * memory gets a hash index persisted inline — regardless of length (the @@ -1258,39 +1572,15 @@ static void splay_build_index_col(const char* dir, ray_t* tbl, int64_t c, ray_t* if (col->len < (1 << 16)) return; /* STR columns get a dictionary (group on int codes); numeric/temporal - * get the per-chunk min/max for block-skip. - * - * High-entropy numeric columns are then upgraded to a persisted HASH - * index using the same chunk-zone entropy heuristic the in-memory - * .csv.read load applies (ray_csv_hash_upgrade_check): the index - * decision is made ONCE at conversion time, so a `.db.splayed.get` - * reload serves equality probes exactly as fast as a fresh CSV load - * (previously the reloaded store had only the zone map and e.g. - * ClickBench q10 ran 5x slower on-disk than in-memory). */ + * get the per-chunk min/max for block-skip. No HASH is built here: + * index policy (compressed-columns PI) — converters persist only the + * indexes every scan uses; explicit .idx.hash indexes were persisted + * by ray_col_save, and ray_col_append_index refuses a marked file. */ ray_t* idx = (col->type == RAY_STR) ? ray_index_dict_compute(col) : ray_index_chunk_zone_compute(col, 16); if (!idx || RAY_IS_ERR(idx)) { if (idx) ray_error_free(idx); return; } - if (col->type != RAY_STR && - ray_csv_hash_upgrade_check(col->type, col->len, - ray_index_payload(idx))) { - if (deferred) { - /* Inside a per-column task: the hash build has its own - * parallel path that needs the pool, so hand the zone - * back and let the caller build the hash afterwards. */ - *deferred = idx; - return; - } - char hpath[1100]; - if (splay_col_path(dir, tbl, c, hpath, sizeof(hpath)) && - splay_hash_append(hpath, col) == RAY_OK) { - ray_release(idx); /* zone sacrificed for the hash */ - return; - } - /* Hash build failed — fall through and persist the zone. */ - } - ray_t* nstr = ray_sym_str(ray_table_col_name(tbl, c)); if (nstr && !RAY_IS_ERR(nstr)) { char path[1100]; @@ -1304,85 +1594,35 @@ static void splay_build_index_col(const char* dir, ray_t* tbl, int64_t c, ray_t* } } -/* Persist a deferred column: its hash index when the build succeeded - * (hashed[c]), else the zone it was computed with (deferred[c]). */ -typedef struct { const char* dir; ray_t* tbl; ray_t** deferred; ray_t** hashed; } splay_index_ctx_t; - -static void splay_persist_deferred(splay_index_ctx_t* x, int64_t c) { - ray_t* col = ray_table_get_col_idx(x->tbl, c); - ray_t* nstr = ray_sym_str(ray_table_col_name(x->tbl, c)); - char path[1100]; - int n = (nstr && !RAY_IS_ERR(nstr)) - ? snprintf(path, sizeof(path), "%s/%.*s", x->dir, (int)ray_str_len(nstr), ray_str_ptr(nstr)) - : -1; - bool have_path = n > 0 && n < (int)sizeof(path); - ray_t* hi = x->hashed[c]; - if (hi) { - if (have_path) - (void)ray_col_append_index(path, ray_index_payload(hi->index), hi->len, hi->type); - ray_release(hi); - } else if (have_path) { - (void)ray_col_append_index(path, ray_index_payload(x->deferred[c]), col->len, col->type); - } - ray_release(x->deferred[c]); - x->hashed[c] = NULL; x->deferred[c] = NULL; -} +typedef struct { + const char* dir; ray_t* tbl; + const uint8_t* gens; /* per-column generation, NULL = all 0 */ +} splay_index_ctx_t; -static void splay_persist_task(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; (void)end; - splay_index_ctx_t* x = (splay_index_ctx_t*)raw; - if (x->deferred[start]) splay_persist_deferred(x, start); -} static void splay_build_index_task(void* raw, uint32_t wid, int64_t start, int64_t end) { (void)wid; (void)end; splay_index_ctx_t* c = (splay_index_ctx_t*)raw; - splay_build_index_col(c->dir, c->tbl, start, &c->deferred[start]); + splay_build_index_col(c->dir, c->tbl, start, c->gens); } void ray_splay_build_indexes(const char* dir, ray_t* tbl) { + splay_build_indexes_gens(dir, tbl, NULL); +} + +static void splay_build_indexes_gens(const char* dir, ray_t* tbl, const uint8_t* gens) { if (!dir || !tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return; int64_t nc = ray_table_ncols(tbl); if (nc <= 0) return; - /* One task per column: the zone / dictionary / hash builds are per-row + /* One task per column: the zone / dictionary builds are per-row * scans of each column and used to run one after another on the * calling thread — the longest serial stretch of a CSV → splayed load. */ ray_pool_t* pool = ray_pool_get(); if (ray_pool_par_dispatch_ok(pool, nc, 2)) { - /* Zones / dictionaries per column in parallel; the columns that - * qualify for a hash index come back deferred and are built one - * after another on this thread, each hash build parallel inside. */ - ray_t** deferred = (ray_t**)ray_sys_alloc((size_t)nc * 2 * sizeof(ray_t*)); - if (!deferred) { - for (int64_t c = 0; c < nc; c++) splay_build_index_col(dir, tbl, c, NULL); - return; - } - memset(deferred, 0, (size_t)nc * 2 * sizeof(ray_t*)); - splay_index_ctx_t ctx = { .dir = dir, .tbl = tbl, .deferred = deferred, .hashed = deferred + nc }; + splay_index_ctx_t ctx = { .dir = dir, .tbl = tbl, .gens = gens }; ray_pool_dispatch_n(pool, splay_build_index_task, &ctx, (uint32_t)nc); - /* Hash builds one after another (each parallel inside), each into - * its file; where that cannot be done in place, built in memory and - * written with the zones of the other deferred columns. */ - for (int64_t c = 0; c < nc; c++) { - if (!deferred[c]) continue; - ray_t* col = ray_table_get_col_idx(tbl, c); - char path[1100]; - ray_err_t e = splay_col_path(dir, tbl, c, path, sizeof(path)) - ? ray_col_build_hash_index(path, col, NULL) : RAY_ERR_IO; - if (e == RAY_OK) { /* the zone is sacrificed for the hash */ - ray_release(deferred[c]); - deferred[c] = NULL; - continue; - } - if (e != RAY_ERR_NYI) continue; /* the zone, then */ - ray_t* hi = ray_idx_hash_fn(col); - if (hi && !RAY_IS_ERR(hi) && (hi->attrs & RAY_ATTR_HAS_INDEX)) ctx.hashed[c] = hi; - else if (hi) { if (RAY_IS_ERR(hi)) ray_error_free(hi); else ray_release(hi); } - } - ray_pool_dispatch_n(pool, splay_persist_task, &ctx, (uint32_t)nc); - ray_sys_free(deferred); } else { - for (int64_t c = 0; c < nc; c++) splay_build_index_col(dir, tbl, c, NULL); + for (int64_t c = 0; c < nc; c++) splay_build_index_col(dir, tbl, c, gens); } } @@ -1402,7 +1642,7 @@ static ray_t* splay_read_dom_once(const char* dir, ray_sym_domain_t* dom, if (!fresh) return ray_error("corrupt", "cannot refresh splayed symfile"); dom = fresh; } - ray_t* tbl = splay_load_dom_impl(resolved, dom, true); + ray_t* tbl = splay_load_dom_impl(resolved, dom, true, false); if (fresh) ray_sym_domain_release(fresh); return tbl; } @@ -1420,53 +1660,3 @@ ray_t* ray_read_splayed_dom(const char* dir, struct ray_sym_domain_s* dom) { ray_error_free(tbl); } } - -ray_err_t ray_splay_hash_column(const char* path, ray_t* zone) { - if (!path) return RAY_ERR_DOMAIN; - bool trace = getenv("RAY_CSV_TRACE") != NULL; /* the converters' phase trace */ - int64_t t0 = trace ? ray_profile_now_ns() : 0; - ray_t* col = ray_col_mmap(path); - if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return RAY_ERR_IO; } - int64_t t1 = trace ? ray_profile_now_ns() : 0; - ray_hash_trace_t ht; - memset(&ht, 0, sizeof(ht)); - /* The build reads the column front to back, twice, and not again: - * larger read-ahead, and its pages are the first to go under pressure - * rather than the build's own. */ - if (col->len > 0) /* from the header: madvise wants the mapping's page */ - ray_vm_advise_seq(col, 32 + (size_t)col->len * ray_sym_elem_size(col->type, col->attrs)); - /* Built over the mapping, straight into the file: the arrays are - * written once, where they end up, and the column is not copied. */ - ray_err_t err = ray_col_build_hash_index(path, col, trace ? &ht : NULL); - if (err == RAY_ERR_NYI) { - /* No in-place build here: attached in memory, then appended. The - * mapping is the column's only reference, so the attach builds on it - * rather than on a copy. */ - ray_t* r = ray_index_attach_hash(&col); - if (!RAY_IS_ERR(r) && (col->attrs & RAY_ATTR_HAS_INDEX)) { - const ray_index_t* hx = ray_index_payload(col->index); - ht.n_keys = hx->u.hash.n_keys; - ht.n_groups = hx->u.hash.n_groups; - ray_hash_mark_t tm = trace ? ray_hash_trace_mark() : (ray_hash_mark_t){0}; - err = ray_col_append_index(path, hx, col->len, col->type); - /* the region is read from the built arrays and written to the file */ - if (trace) ray_hash_trace_add(&ht, RAY_HXT_APPEND, tm, 2 * ray_index_inline_size(hx)); - } else { - if (RAY_IS_ERR(r)) ray_error_free(r); - err = RAY_ERR_IO; - } - } - int64_t t2 = trace ? ray_profile_now_ns() : 0; - if (trace && err == RAY_OK) { - fprintf(stderr, "splayed hash: file=%s rows=%" PRId64 " keys=%" PRId64 " groups=%" PRId64 - " mmap=%.1fms build=%.1fms write=%.1fms\n", - path, col->len, ht.n_keys, ht.n_groups, (double)(t1 - t0) / 1e6, - (double)(t2 - t1 - ht.ns[RAY_HXT_APPEND]) / 1e6, (double)ht.ns[RAY_HXT_APPEND] / 1e6); - ray_hash_trace_print(stderr, "splayed hash io", &ht, - col->len * (int64_t)ray_sym_elem_size(col->type, col->attrs)); - } - if (err != RAY_OK && zone) - err = ray_col_append_index(path, ray_index_payload(zone), col->len, col->type); - ray_release(col); - return err; -} diff --git a/src/store/splay.h b/src/store/splay.h index 0f89d32a2..620d3dc4e 100644 --- a/src/store/splay.h +++ b/src/store/splay.h @@ -26,6 +26,7 @@ #include #include "store/fileio.h" +#include "store/col.h" struct ray_sym_domain_s; @@ -45,14 +46,28 @@ typedef struct { char created[1024]; /* shallowest directory of root begin created */ char dir[1024]; char generation[256]; + ray_compress_t mode; /* the call's tri-state compress option */ + char cur[1024]; /* destination's current generation dir, "" when none (under the lock) */ + ray_err_t cur_err; /* resolving cur failed: only an inheriting column fails on it */ + uint8_t* gens; /* resolved generation per column file (ray_alloc_raw), freed by finish */ + int64_t ngens; + bool sym_col; /* per-column symfiles (RAY_SYMFILE_COLUMN); set after begin */ } ray_splay_write_t; ray_err_t ray_splay_write_begin(const char* dir, ray_splay_write_t* write); +/* begin with the call's compress option; the generations are resolved + * per file by ray_splay_write_table_ctx against write->cur. */ +ray_err_t ray_splay_write_begin_mode(const char* dir, ray_compress_t mode, + ray_splay_write_t* write); ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, bool durable); /* Write only to a fresh/unpublished directory owned by the caller. */ ray_err_t ray_splay_write_table(ray_t* tbl, const char* dir, const char* sym_path, bool durable); +/* Write into write->dir under the held lock, resolving each file's + * generation from write->mode and write->cur (kept in write->gens). */ +ray_err_t ray_splay_write_table_ctx(ray_t* tbl, ray_splay_write_t* write, + const char* sym_path, bool durable); /* The returned generation may be removed by the next publish: open every file * of a read right after resolving, and resolve again if one is missing (the * splayed loaders and ray_splay_has_schema do). */ @@ -72,6 +87,34 @@ ray_err_t ray_splay_save_bulk(ray_t* tbl, const char* dir, const char* sym_path) /* Private import directory only: caller holds the shared symbol domain alive * and flushes it before publishing the root. Bulk writes are not durable. */ ray_err_t ray_splay_save_staged_bulk(ray_t* tbl, const char* dir, const char* sym_path); +/* The same with the call's compress option (ray_compress_t); the forms + * above pass RAY_COMPRESS_ABSENT, so every caller inherits. */ +ray_err_t ray_splay_save_mode(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode); +ray_err_t ray_splay_save_bulk_mode(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode); +ray_err_t ray_splay_save_staged_bulk_mode(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode); +/* The symfile layout of a save. SHARED (the default): one symfile, + * sym_path, holds the vocabulary of every SYM column. COLUMN: each SYM + * column gets a symfile of its own next to its column file, + * `/..sym` (ray_splay_col_sym_path; dir is the directory the + * columns are written to, the selected generation once the table has one), + * holding that column's strings only, so a scan of one column reads none + * of another's; sym_path is then not written. The loaders find a column's + * own symfile by that name and resolve the column over it, whatever symfile + * they were given; a column without one resolves over the shared domain as + * before. */ +typedef enum { RAY_SYMFILE_SHARED = 0, RAY_SYMFILE_COLUMN = 1 } ray_symfile_t; +ray_err_t ray_splay_save_layout(ray_t* tbl, const char* dir, const char* sym_path, + ray_compress_t mode, ray_symfile_t layout); +/* The `symfile` option of an options dict (NULL or no key: SHARED): the + * symbol 'shared or 'column, anything else a domain error. Returns NULL or + * an owned error. */ +ray_t* ray_symfile_opt_parse(ray_t* opts, ray_symfile_t* layout); +/* `/..sym` into out; false when it does not fit. */ +bool ray_splay_col_sym_path(char* out, size_t cap, const char* dir, + const char* name, size_t name_len); ray_t* ray_splay_load(const char* dir, const char* sym_path); ray_t* ray_read_splayed(const char* dir, const char* sym_path); @@ -80,10 +123,6 @@ ray_t* ray_read_splayed(const char* dir, const char* sym_path); * `.db.splayed.set` only; the CSV and Parquet converters build their indexes * inline in the stream writer. Best-effort, per numeric column. */ void ray_splay_build_indexes(const char* dir, ray_t* tbl); -/* Append a hash index to the column file at path, using its kept chunk zone - * Re-reads the column file, appends a hash, and falls back to appending - * `zone` when no hash results. The caller keeps ownership of zone. Best effort. */ -ray_err_t ray_splay_hash_column(const char* path, ray_t* zone); /* Loader accepting a shared FILE domain. It resolves the generation first, * then refreshes the cached domain to include any externally appended symbols. */ diff --git a/src/store/stream.c b/src/store/stream.c index 635545979..00b4ddaaa 100644 --- a/src/store/stream.c +++ b/src/store/stream.c @@ -4,12 +4,12 @@ #include "ops/hash.h" #include "store/col.h" #include "store/fileio.h" +#include "store/encw.h" +#include "store/encfmt.h" #include "mem/heap.h" #include "table/sym.h" #include "table/domain.h" #include "vec/str.h" -#include "io/csv.h" /* ray_csv_hash_upgrade_check: the shared upgrade policy */ -#include "store/splay.h" /* ray_splay_hash_column */ #include "core/pool.h" #include "core/profile.h" #include "core/runtime.h" @@ -22,8 +22,13 @@ ray_err_t ray_col_stream_open(ray_col_stream_t* w, const char* dir, int64_t name_id, int8_t type, - struct ray_sym_domain_s* dom) { + struct ray_sym_domain_s* dom, + uint8_t gen) { memset(w, 0, sizeof(*w)); + if (gen != 0 && gen != 2) return RAY_ERR_VERSION; + /* a big-endian build refuses generation 2 before any file exists */ + if (gen == 2 && !ray_enc_gen2_supported()) return RAY_ERR_NYI; + w->gen = gen; w->type = type; w->attrs = (type == RAY_SYM) ? RAY_SYM_W32 : 0; w->dom = dom; @@ -73,8 +78,10 @@ static bool ray_col_stream_lut(ray_col_stream_t* w) { } ray_err_t ray_col_stream_index_begin(ray_col_stream_t* w, int64_t start_row) { - if (w->zone || w->dict) return RAY_ERR_DOMAIN; + if (w->zone || w->dict || w->want_dict) return RAY_ERR_DOMAIN; if (w->type == RAY_STR) { + /* generation 2 builds the DICT from the chunks it encodes at finish */ + if (w->gen == 2) { w->want_dict = true; return RAY_OK; } w->dict = (ray_dict_acc_t*)ray_alloc_raw(sizeof(*w->dict)); if (!w->dict) return RAY_ERR_OOM; ray_err_t err = ray_dict_acc_init(w->dict); @@ -99,8 +106,6 @@ ray_err_t ray_col_stream_index_merge(ray_col_stream_t* dst, ray_col_stream_t* sr static void stream_drop_index(ray_col_stream_t* w) { if (w->zone) { ray_zone_acc_free(w->zone); ray_free_raw(w->zone); w->zone = NULL; } if (w->dict) { ray_dict_acc_free(w->dict); ray_free_raw(w->dict); w->dict = NULL; } - if (w->index) { ray_release(w->index); w->index = NULL; } - w->wants_hash = false; } ray_err_t ray_col_stream_append(ray_col_stream_t* w, @@ -134,7 +139,9 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, for (int64_t i = 0; i < count; i++) u.h32[i] = (uint32_t)ray_hash_bytes(strings[i],lengths[i]); ok = ray_sym_domain_intern_batch(w->dom,count,strings,lengths,u.h32,ids); } - if (!ok) return RAY_ERR_OOM; + /* The intern declines a cancelled batch as well as a failed + * allocation; report the cancel as one. */ + if (!ok) return ray_interrupted() ? RAY_ERR_CANCEL : RAY_ERR_OOM; for (int64_t i = 0; i < count; i++) { if (ids[i] < 0 || (uint64_t)ids[i] >= UINT32_MAX) return RAY_ERR_RANGE; u.pos[i] = (uint32_t)ids[i]; if (!ids[i]) w->had_nulls = true; @@ -159,6 +166,12 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, * chunk's own pool, before the offset is rebased. */ buf[i].hash32 = ray_str_t_hash32(&buf[i], pool_base); buf[i].pool_off += (uint32_t)w->pool_bytes; + /* generation 2 copies each occurrence into its vector's + * pool: count the decoded bytes so the row that crosses + * the limit fails (descriptors may share pooled ranges, + * so the staged pool can be far smaller) */ + if (w->gen == 2 && (w->dec_pool += buf[i].len) > UINT32_MAX) + return RAY_ERR_RANGE; } if (!buf[i].len) w->had_nulls = true; } @@ -259,6 +272,59 @@ ray_err_t ray_col_stream_append(ray_col_stream_t* w, return RAY_OK; } +/* Generation-2 finish: the staging file holds the raw generation-0 payload + * ([32 B zero header][rows x element][STR: 32 B pool header + pool]); it is + * mapped and transcoded chunk by chunk into a second staging file, which + * then replaces the first (published by ray_col_stream_publish as today). + * The zone accumulator is recorded as CHUNK_ZONE only (in the enc header); + * a STR column whose index_begin ran records the DICT, which the column + * writer builds from the chunks it encodes (P6b). Closes w->fp on every path. */ +static ray_err_t stream_finish_gen2(ray_col_stream_t* w, bool durable) { + if (w->zone && w->zone->saw_null) w->had_nulls = true; + uint8_t ik = (w->zone && w->rows >= RAY_ENC_CHUNK && + ray_index_kind_admits(RAY_IDX_CHUNK_ZONE, w->type)) ? RAY_IDX_CHUNK_ZONE + : (w->want_dict && ray_col_dict_wanted(w->type, w->rows)) ? RAY_IDX_DICT : 0; + stream_drop_index(w); /* the DICT is built by the column writer */ + ray_err_t err = fflush(w->fp) == 0 ? RAY_OK : RAY_ERR_IO; + if (fclose(w->fp) != 0 && err == RAY_OK) err = RAY_ERR_IO; + w->fp = NULL; + if (err != RAY_OK) return err; + uint8_t esz = w->type == RAY_SYM ? 4 : ray_sym_elem_size(w->type, 0); + uint64_t need = 32 + (uint64_t)w->rows * esz + (w->type == RAY_STR ? 32 + w->pool_bytes : 0); + size_t msz = 0; + void* m = ray_vm_map_file(w->tmp_path, &msz); + /* the index was dropped above, so the staging file is exactly the payload */ + if (!m || msz != need) { if (m) ray_vm_unmap_file(m, msz); return RAY_ERR_IO; } + const uint8_t* data = (const uint8_t*)m + 32; + const char* pool = w->type == RAY_STR ? (const char*)m + 32 + (size_t)w->rows * 16 + 32 : NULL; + char enc_path[1100]; + snprintf(enc_path, sizeof enc_path, "%s.g2", w->tmp_path); + FILE* f = fopen(enc_path, "wb+"); + err = f ? RAY_OK : RAY_ERR_IO; + ray_encw_t ew; memset(&ew, 0, sizeof ew); + uint8_t attrs = (uint8_t)(w->attrs | (w->had_nulls ? RAY_ATTR_HAS_NULLS : 0)); + uint32_t sc = w->type == RAY_SYM ? (uint32_t)ray_sym_domain_count(w->dom) : 0; + if (err == RAY_OK) err = ray_encw_begin(&ew, f, w->type, attrs, w->rows, sc, ik, 0); + for (int64_t c = 0; err == RAY_OK && c < ew.n_chunks; c++) { + if (ray_interrupted()) { err = RAY_ERR_CANCEL; break; } + int64_t n = w->rows - c * RAY_ENC_CHUNK; + if (n > RAY_ENC_CHUNK) n = RAY_ENC_CHUNK; + err = ray_encw_chunk(&ew, data + (size_t)c * RAY_ENC_CHUNK * esz, pool, n); + } + if (err == RAY_OK) err = ray_encw_finish(&ew); + ray_encw_free(&ew); + ray_vm_unmap_file(m, msz); + if (f && fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; + if (err == RAY_OK && durable) { + ray_fd_t fd = ray_file_open(enc_path, RAY_OPEN_READ | RAY_OPEN_WRITE); + if (fd == RAY_FD_INVALID) err = RAY_ERR_IO; + else { err = ray_file_sync(fd); ray_file_close(fd); } + } + if (err == RAY_OK) err = ray_file_rename(enc_path, w->tmp_path); + if (err != RAY_OK) remove(enc_path); + return err; +} + ray_err_t ray_col_stream_finish(ray_col_stream_t* w, bool durable) { ray_col_stream_drop_lut(w); if (!w->fp) return RAY_OK; @@ -286,10 +352,15 @@ ray_err_t ray_col_stream_finish(ray_col_stream_t* w, bool durable) { if (w->pool_fp) { if (fclose(w->pool_fp) && err == RAY_OK) err = RAY_ERR_IO; w->pool_fp = NULL; } if (w->pool_path[0]) remove(w->pool_path); + if (err == RAY_OK && w->gen == 2) { + err = stream_finish_gen2(w, durable); + if (err != RAY_OK) { remove(w->tmp_path); stream_drop_index(w); } + else w->finished = true; + return err; + } + /* The index region goes after the payload and the marker into the same - * header write, so the rename publishes data and index together. A - * zone the hash policy wants upgraded is handed back instead: the - * converter re-reads only that column to build the hash. */ + * header write, so the rename publishes data and index together. */ bool inline_index = false; /* The persisted HAS_NULLS bit derives from the payload (col.c #495): a * sentinel in any slice, flagged or not, publishes the bit, so the @@ -301,23 +372,22 @@ ray_err_t ray_col_stream_finish(ray_col_stream_t* w, bool durable) { ray_free_raw(w->zone); ray_free_raw(w->dict); w->zone = NULL; w->dict = NULL; if (idx && RAY_IS_ERR(idx)) { ray_error_free(idx); idx = NULL; } /* best effort */ if (idx) { + /* Index policy (compressed-columns PI): the converters persist + * the zone or dictionary they streamed and never upgrade it to + * a HASH of their own; explicit .idx.hash is persisted by + * ray_col_save. */ const ray_index_t* ix = ray_index_payload(idx); - if (ix->kind == RAY_IDX_CHUNK_ZONE && - ray_csv_hash_upgrade_check(w->type, w->rows, ix)) { - w->index = idx; w->wants_hash = true; - } else { - int64_t payload_end = 0; - ray_err_t ierr = ray_col_write_index_region(w->fp, ix, &payload_end); - inline_index = ierr == RAY_OK; - /* The index is a best-effort accelerator: when its region - * cannot be written, cut the file back to the payload and - * publish the column without it. Only a failed cut is an - * error, since the file would then be unloadable. */ - if (ierr != RAY_OK && payload_end > 0 && - !ray_col_truncate(w->fp, payload_end)) - err = RAY_ERR_IO; - ray_release(idx); - } + int64_t payload_end = 0; + ray_err_t ierr = ray_col_write_index_region(w->fp, ix, &payload_end); + inline_index = ierr == RAY_OK; + /* The index is a best-effort accelerator: when its region + * cannot be written, cut the file back to the payload and + * publish the column without it. Only a failed cut is an + * error, since the file would then be unloadable. */ + if (ierr != RAY_OK && payload_end > 0 && + !ray_col_truncate(w->fp, payload_end)) + err = RAY_ERR_IO; + ray_release(idx); } } @@ -357,7 +427,8 @@ ray_err_t ray_col_stream_finish(ray_col_stream_t* w, bool durable) { } ray_err_t ray_col_stream_publish(ray_col_stream_t* w, bool durable) { - if (!w->finished) return RAY_OK; + /* an open writer was never finished: its tmp file is incomplete */ + if (!w->finished) return w->fp ? RAY_ERR_DOMAIN : RAY_OK; w->finished = false; ray_err_t err = ray_file_rename(w->tmp_path, w->path); if (err == RAY_OK && durable) err = ray_file_sync_dir(w->path); @@ -376,6 +447,7 @@ typedef struct { int64_t* col_ns; bool durable; _Atomic(ray_err_t) err; + _Atomic(int64_t) done; /* columns finished: a skipped task is not */ } stream_finish_ctx_t; static void stream_finish_task(void* raw, uint32_t wid, int64_t start, int64_t end) { @@ -387,6 +459,8 @@ static void stream_finish_task(void* raw, uint32_t wid, int64_t start, int64_t e if (e != RAY_OK) { ray_err_t ok = RAY_OK; atomic_compare_exchange_strong_explicit(&a->err, &ok, e, memory_order_relaxed, memory_order_relaxed); + } else { + atomic_fetch_add_explicit(&a->done, 1, memory_order_relaxed); } } @@ -396,13 +470,18 @@ ray_err_t ray_col_stream_close_all(ray_col_stream_t* w, int64_t n, bool durable, /* finish touches only the writer's own files and never dispatches, so * every column finishes side by side: STR pool merges and dictionary * regions, which used to run one after another on the caller. */ - stream_finish_ctx_t ctx = { .w = w, .col_ns = col_ns, .durable = durable, .err = RAY_OK }; + stream_finish_ctx_t ctx = { .w = w, .col_ns = col_ns, .durable = durable, .err = RAY_OK, + .done = 0 }; ray_pool_t* pool = ray_pool_get(); if (ray_pool_par_dispatch_ok(pool, n, 2)) ray_pool_dispatch_n(pool, stream_finish_task, &ctx, (uint32_t)n); else for (int64_t c = 0; c < n; c++) stream_finish_task(&ctx, 0, c, c + 1); ray_err_t err = ctx.err; + /* A cancel skips the finish tasks not yet started and the dispatch + * returns normally: an unfinished column has no file to publish. */ + if (err == RAY_OK && atomic_load_explicit(&ctx.done, memory_order_relaxed) != n) + err = RAY_ERR_CANCEL; /* The renames stay serial and in column order (microseconds each). */ for (int64_t c = 0; c < n; c++) { ray_err_t cerr = (err == RAY_OK) ? ray_col_stream_publish(&w[c], durable) : RAY_ERR_IO; @@ -412,91 +491,6 @@ ray_err_t ray_col_stream_close_all(ray_col_stream_t* w, int64_t n, bool durable, return err; } -typedef struct { - ray_col_stream_t* w; - const int64_t* cand; - int64_t base; - int64_t* col_ns; -} stream_hash_ctx_t; - -static void stream_hash_task(void* raw, uint32_t wid, int64_t start, int64_t end) { - (void)wid; (void)end; - stream_hash_ctx_t* a = (stream_hash_ctx_t*)raw; - int64_t c = a->cand[a->base + start]; - int64_t t0 = a->col_ns ? ray_profile_now_ns() : 0; - (void)ray_splay_hash_column(a->w[c].path, a->w[c].index); /* best effort */ - if (a->col_ns) a->col_ns[c] = ray_profile_now_ns() - t0; -} - -/* Peak private memory of one in-flight hash build, per row of the column. - * Inside a pool task the build takes the serial path of - * ray_index_attach_hash: the probe table (next_pow2(2n) x 8 B: 16-32 B/row, - * 21.5 at 100 M rows) lives only during the key pass and is freed before - * the CSR table of the same size is built, so the two never coexist; rgid, - * gkeys, offs and rows are 8 B/row each (worst case: every key distinct) - * and the index stays allocated until its region is written. That is - * ~54 B/row on paper; measured as a 58 B/row RSS delta per column in - * flight (2 M-row I64 columns), which is the figure used here. The mmap of - * the column file itself is page cache and not counted. */ -#define STREAM_HASH_BYTES_PER_ROW 58 -/* Share of the RAM budget the in-flight builds may take together. */ -#define STREAM_HASH_RAM_SHARE 4 - -int64_t ray_col_stream_hash_wave(int64_t ram_limit, int64_t rows, int64_t candidates) { - int64_t budget = ram_limit / STREAM_HASH_RAM_SHARE; - int64_t per_col = (rows > 0 ? rows : 1) * STREAM_HASH_BYTES_PER_ROW; - int64_t wave = budget / per_col; - if (wave < 1) wave = 1; - if (wave > candidates) wave = candidates; - return wave; -} - -void ray_col_stream_hash_all(ray_col_stream_t* w, int64_t n, int64_t* col_ns) { - int64_t* cand = (int64_t*)ray_alloc_raw((size_t)(n > 0 ? n : 1) * sizeof(int64_t)); - int64_t ncand = 0, rows = 0; - if (cand) - for (int64_t c = 0; c < n; c++) - if (w[c].wants_hash) { cand[ncand++] = c; if (w[c].rows > rows) rows = w[c].rows; } - ray_pool_t* pool = ray_pool_get(); - if (ncand >= 2 && ray_pool_par_dispatch_ok(pool, ncand, 2)) { - /* Columns in flight at once, from the RAM budget (-m, else physical - * RAM / cgroup): W = ram_limit / SHARE / (58 B * rows), clamped to - * [1, ncand]. Each task builds serially, so K columns finish in - * ceil(K / W) serial build times instead of K parallel-inside builds - * that scale to ~2x on 24 threads. */ - int64_t wave = ray_col_stream_hash_wave(ray_sys_ram_limit(), rows, ncand); - for (int64_t base = 0; base < ncand; base += wave) { - int64_t k = ncand - base < wave ? ncand - base : wave; - stream_hash_ctx_t ctx = { .w = w, .cand = cand, .base = base, .col_ns = col_ns }; - if (k == 1) - /* A lone build runs here, outside any dispatch, so - * ray_parallel_flag stays down and its builder is parallel. */ - stream_hash_task(&ctx, 0, 0, 1); - else - ray_pool_dispatch_n(pool, stream_hash_task, &ctx, (uint32_t)k); - } - } else { - /* one candidate (or no pool): the build is parallel inside */ - for (int64_t i = 0; i < ncand; i++) { - stream_hash_ctx_t ctx = { .w = w, .cand = cand, .base = i, .col_ns = col_ns }; - stream_hash_task(&ctx, 0, 0, 1); - } - } - /* built (or, OOM on the candidate list, left with their zones): a - * later call has nothing to do for them */ - for (int64_t c = 0; c < n; c++) w[c].wants_hash = false; - ray_free_raw(cand); - for (int64_t c = 0; c < n; c++) - if (w[c].index) { ray_release(w[c].index); w[c].index = NULL; } -} - -void ray_col_stream_hash_one(ray_col_stream_t* w) { - if (!w->wants_hash) return; - (void)ray_splay_hash_column(w->path, w->index); /* best effort */ - w->wants_hash = false; - if (w->index) { ray_release(w->index); w->index = NULL; } -} - void ray_col_stream_abort(ray_col_stream_t* w) { ray_col_stream_drop_lut(w); stream_drop_index(w); diff --git a/src/store/stream.h b/src/store/stream.h index a69400ac4..bfe66df94 100644 --- a/src/store/stream.h +++ b/src/store/stream.h @@ -35,15 +35,16 @@ typedef struct { uint32_t* lut_pos; /* [COL_STREAM_LUT] position per slot */ ray_zone_acc_t* zone; /* numeric / temporal: the running chunk zone */ ray_dict_acc_t* dict; /* STR: the running dictionary */ - ray_t* index; /* after close: the zone kept for a hash candidate; - * the caller releases it AND sets it to NULL, or - * must not call abort afterwards */ - bool wants_hash; /* after close: build a hash by re-reading the file */ + bool want_dict; /* generation 2, STR: index_begin asked for the DICT (built at finish) */ bool finished; /* finish done: the tmp file is complete, not yet renamed */ + uint8_t gen; /* output generation: 0, or 2 (transcoded at finish) */ + uint64_t dec_pool; /* generation 2: decoded STR pool bytes so far */ } ray_col_stream_t; +/* gen 0 writes today's format; gen 2 stages the same raw payload and + * transcodes it chunk by chunk at finish (any other gen: RAY_ERR_VERSION). */ ray_err_t ray_col_stream_open(ray_col_stream_t* w, const char* dir, int64_t name, - int8_t type, struct ray_sym_domain_s* domain); + int8_t type, struct ray_sym_domain_s* domain, uint8_t gen); /* Start building the column's index from global row start_row. Call after * open and before the first append; no-op for types without an index. */ ray_err_t ray_col_stream_index_begin(ray_col_stream_t* w, int64_t start_row); @@ -60,26 +61,15 @@ ray_err_t ray_col_stream_close(ray_col_stream_t* w, bool durable); * finish error the tmp file is already removed; the caller still calls abort * on every writer. */ ray_err_t ray_col_stream_finish(ray_col_stream_t* w, bool durable); +/* Refuses (RAY_ERR_DOMAIN) a writer whose finish never ran; a no-op on one + * already published or aborted. */ ray_err_t ray_col_stream_publish(ray_col_stream_t* w, bool durable); /* finish every writer as one pool task per column (serially without a * pool), then publish them in order. The first finish error is returned; - * on any error every writer is aborted and nothing is published. + * a task the pool skipped (cancellation) is RAY_ERR_CANCEL; on any error + * every writer is aborted and nothing is published. * `col_ns` (optional, n entries) receives each column's finish time. */ ray_err_t ray_col_stream_close_all(ray_col_stream_t* w, int64_t n, bool durable, int64_t* col_ns); -/* Build the hash index of every closed writer whose zone asked for one - * (wants_hash) by re-reading its published file, and release the zones. - * Several candidates build as pool tasks (one column per task, in waves - * sized from the RAM budget); a single one builds with the parallel - * builder. Best effort: a failed build leaves the column with its zone. */ -void ray_col_stream_hash_all(ray_col_stream_t* w, int64_t n, int64_t* col_ns); -/* Build the hash index of one closed writer whose zone asked for one, right - * away and with the whole pool, while its file is still in the page cache; - * the zone is released and a later ray_col_stream_hash_all skips the - * writer. Best effort, as there. Call outside any pool dispatch. */ -void ray_col_stream_hash_one(ray_col_stream_t* w); -/* Hash builds in flight at once: clamp(ram_limit / 4 / (58 B * max(rows, 1)), - * 1, candidates). Pure; `candidates` >= 1 expected. */ -int64_t ray_col_stream_hash_wave(int64_t ram_limit, int64_t rows, int64_t candidates); void ray_col_stream_abort(ray_col_stream_t* w); #endif diff --git a/src/table/dict.c b/src/table/dict.c index d37d4e2b5..c6f7fef97 100644 --- a/src/table/dict.c +++ b/src/table/dict.c @@ -55,7 +55,7 @@ static ray_t* dict_alloc_block(ray_t* keys, ray_t* vals) { memset(d->aux, 0, 16); ray_t** slots = ray_dict_slots(d); slots[0] = keys; - slots[1] = vals; + slots[1] = vals; /* not-a-table */ return d; } @@ -68,7 +68,10 @@ static ray_t* dict_alloc_block(ray_t* keys, ray_t* vals) { ray_t* ray_dict_new(ray_t* keys, ray_t* vals) { if (!keys || RAY_IS_ERR(keys)) { - if (vals && !RAY_IS_ERR(vals)) ray_release(vals); + if (vals && vals != keys) { + if (RAY_IS_ERR(vals)) ray_error_free(vals); + else ray_release(vals); + } return keys ? keys : ray_error("type", "dict: keys vector is null"); } if (!vals || RAY_IS_ERR(vals)) { @@ -169,7 +172,7 @@ ray_t* ray_dict_probe_sym_borrowed(ray_t* d, int64_t sym_id) { ray_t* ray_container_probe_sym(ray_t* v, int64_t sym_id) { if (!v || RAY_IS_ERR(v)) return NULL; if (v->type == RAY_DICT) return ray_dict_probe_sym_borrowed(v, sym_id); - if (v->type == RAY_TABLE) return ray_table_get_col(v, sym_id); + if (v->type == RAY_TABLE) return ray_table_col(v, sym_id); /* plain column or owned error */ return NULL; } @@ -263,6 +266,7 @@ int64_t ray_dict_find_idx(ray_t* d, ray_t* key_atom) { } } case RAY_I64: + case RAY_TIMESPAN: case RAY_TIMESTAMP: { const int64_t* a = (const int64_t*)base; int64_t v = key_atom->i64; @@ -358,6 +362,7 @@ static ray_t* dict_vals_at(ray_t* vals, int64_t idx, bool* owned_out) { case RAY_F64: atom = ray_f64(((double*)base)[idx]); break; case RAY_DATE: atom = ray_date(((int32_t*)base)[idx]); break; case RAY_TIME: atom = ray_time(((int32_t*)base)[idx]); break; + case RAY_TIMESPAN: atom = ray_timespan(((int64_t*)base)[idx]); break; case RAY_TIMESTAMP: atom = ray_timestamp(((int64_t*)base)[idx]); break; case RAY_SYM: { int64_t id = ray_read_sym(base, idx, vals->type, vals->attrs); @@ -541,7 +546,7 @@ ray_t* ray_dict_upsert(ray_t* d, ray_t* key_atom, ray_t* val) { ray_t** slots = ray_dict_slots(d); ray_t* keys = slots[0]; - ray_t* vals = slots[1]; + ray_t* vals = slots[1]; /* not-a-table */ /* The append/set helpers consume the input ref and return an owned ref * (possibly the same pointer, or a fresh one after grow — in which case @@ -553,16 +558,16 @@ ray_t* ray_dict_upsert(ray_t* d, ray_t* key_atom, ray_t* val) { if (vals->type == RAY_LIST) { ray_t* new_vals = ray_list_set(vals, idx, val); if (!new_vals || RAY_IS_ERR(new_vals)) { ray_release(d); return new_vals ? new_vals : ray_error("oom", NULL); } - slots[1] = new_vals; + slots[1] = new_vals; /* not-a-table */ } else { /* Typed vector path: promote to LIST first, then update. */ ray_t* lst = promote_vals_to_list(vals); if (!lst || RAY_IS_ERR(lst)) { ray_release(d); return lst ? lst : ray_error("oom", NULL); } ray_release(vals); - slots[1] = lst; + slots[1] = lst; /* not-a-table */ ray_t* new_lst = ray_list_set(lst, idx, val); if (!new_lst || RAY_IS_ERR(new_lst)) { ray_release(d); return new_lst ? new_lst : ray_error("oom", NULL); } - slots[1] = new_lst; + slots[1] = new_lst; /* not-a-table */ } return d; } @@ -572,7 +577,7 @@ ray_t* ray_dict_upsert(ray_t* d, ray_t* key_atom, ray_t* val) { ray_t* lst = promote_vals_to_list(vals); if (!lst || RAY_IS_ERR(lst)) { ray_release(d); return lst ? lst : ray_error("oom", NULL); } ray_release(vals); - slots[1] = lst; + slots[1] = lst; /* not-a-table */ vals = lst; } @@ -627,7 +632,7 @@ ray_t* ray_dict_upsert(ray_t* d, ray_t* key_atom, ray_t* val) { /* Append val — list_append consumes vals, returns owned (possibly new). */ ray_t* new_vals = ray_list_append(vals, val); if (!new_vals || RAY_IS_ERR(new_vals)) { ray_release(d); return new_vals ? new_vals : ray_error("oom", NULL); } - slots[1] = new_vals; + slots[1] = new_vals; /* not-a-table */ return d; } @@ -655,14 +660,14 @@ ray_t* ray_dict_remove(ray_t* d, ray_t* key_atom) { ray_t** slots = ray_dict_slots(d); ray_t* keys = slots[0]; - ray_t* vals = slots[1]; + ray_t* vals = slots[1]; /* not-a-table */ /* Promote typed-vector vals to LIST so we can remove uniformly. */ if (vals->type != RAY_LIST) { ray_t* lst = promote_vals_to_list(vals); if (!lst || RAY_IS_ERR(lst)) { ray_release(d); return lst ? lst : ray_error("oom", NULL); } ray_release(vals); - slots[1] = lst; + slots[1] = lst; /* not-a-table */ vals = lst; } @@ -726,7 +731,7 @@ ray_t* ray_dict_remove(ray_t* d, ray_t* key_atom) { /* Drop vals[idx] from the LIST. */ vals = ray_cow(vals); if (!vals || RAY_IS_ERR(vals)) { ray_release(d); return vals; } - slots[1] = vals; + slots[1] = vals; /* not-a-table */ ray_t** vslots = (ray_t**)ray_data(vals); if (vslots[idx]) ray_release(vslots[idx]); for (int64_t i = idx; i + 1 < vals->len; i++) vslots[i] = vslots[i + 1]; diff --git a/src/table/dict.h b/src/table/dict.h index a6e1d0d92..0325c1d11 100644 --- a/src/table/dict.h +++ b/src/table/dict.h @@ -62,7 +62,9 @@ int64_t ray_dict_find_sym(ray_t* d, int64_t sym_id); ray_t* ray_dict_probe_sym_borrowed(ray_t* d, int64_t sym_id); /* Borrowed sym-key probe for either RAY_DICT or RAY_TABLE — returns the - * value slot for dicts and the column vector for tables. NULL on miss. */ + * value slot for dicts and the column vector for tables. NULL on miss. A + * table slot that fails to materialize yields an owned RAY_ERROR (free it with + * ray_error_free); callers test RAY_IS_ERR on a non-NULL result. */ ray_t* ray_container_probe_sym(ray_t* v, int64_t sym_id); #endif /* RAY_DICT_H */ diff --git a/src/table/domain.c b/src/table/domain.c index 6fddaf8c3..34f7e017a 100644 --- a/src/table/domain.c +++ b/src/table/domain.c @@ -39,15 +39,38 @@ * refcounts, appends, the lazily built reverse index and the runtime-id * LUT build. Bulk imports can hold it while growing a large dictionary; * contending workers sleep instead of spending CPU time spinning. The - * two hot read paths are LOCK-FREE: ray_sym_domain_str reads the + * hot read paths are LOCK-FREE: ray_sym_domain_str reads the * atomically published (count, atoms) pair — appends publish a slot - * write with a release store of the count, growth REPLACES the array - * (old arrays are retired, never freed in place, so a stale pointer is - * always valid memory covering every position < its publish count) — - * and ray_sym_domain_runtime_lut reads an atomically published array - * (invalidated and rebuilt across appends; retired likewise). The - * runtime singleton never touches the lock (immortal, delegates to - * sym.c's own locking). + * write with a release store of the count, growth REPLACES the array — + * ray_sym_domain_raw_pin copies the published (map, checkpoints, count) + * record, and ray_sym_domain_runtime_lut reads an atomically published + * array (invalidated and rebuilt across appends). The runtime singleton + * never touches the lock (immortal, delegates to sym.c's own locking). + * + * What happens to a REPLACED array, record or mapping depends on who can + * still be reading it: + * - append paths (dom_append_locked, the batch commit): import workers + * probe a snapshot outside the lock while another worker commits, so + * the old one is RETIRED (dom_retire) and freed with the domain; a + * stale pointer is always valid memory covering every position below + * its publish count. + * - external extend (dom_extend_from_file_locked: the symfile grew under + * another process, reopened on a cache hit): FREED at once + * (dom_drop_locked), unless a batch intern is in flight, then retired. + * Safe because a reopen runs under the lock on the calling thread + * between kernels: the pool is fork-join (the main thread is worker 0, + * a dispatch drains before it returns), the IPC loop is one thread, + * every reopen site runs before a dispatch, and the one lock-free + * reader that outlives a lock release — the batch probe — is counted + * in batch_inflight. The flush paths (ray_sym_domain_flush, _append) + * also read `atoms` after releasing the lock, but only while + * count != disk_count, and an extend refuses a dirty domain, so no + * extend can run while they read. Retiring here too was #717: a + * replica reopening + * on a timer never drops its last reference, so every reopen leaked a + * generation. The contract this rests on is in domain.h at + * ray_sym_domain_raw_pin: no pin across a reopen, no reopen under a + * running kernel. */ #if defined(__APPLE__) @@ -68,6 +91,8 @@ #include "core/pool.h" /* batch intern: parallel read-only probe */ #include "sym.h" /* ray_sym_intern_prehashed (runtime fallback) */ #include "symimp.h" /* DOM_IMPORT */ +#include "store/enccol.h" /* ray_enccol_of: a generation-2 SYM column's domain */ +#include "store/fsst.h" /* compressed symfiles: each record FSST-coded */ #include #include #include @@ -81,6 +106,17 @@ #elif !defined(RAY_OS_WASM) #include #endif +#include +#if defined(RAY_OS_WINDOWS) +#include +#define dom_pid() ((unsigned long long)_getpid()) +#else +#include +#include /* dom_src_open: explicit reads */ +#include +#include /* kill(pid, 0): a temporary file's writer still runs */ +#define dom_pid() ((unsigned long long)getpid()) +#endif #ifndef PATH_MAX # define PATH_MAX 4096 #endif @@ -88,6 +124,17 @@ /* Same on-disk format constant as src/table/sym.c (private there). */ #define DOMAIN_STRL_MAGIC 0x4C525453U /* "STRL" */ +/* A compressed symfile, "STRZ": the STRL header, then the FSST symbol table + * the records are coded with (fixed size: the symbol count, 255 lengths, + * 255 symbols of 8 bytes), then one record per entry, [u32 coded length | + * coded bytes]. Its index (.ix) gives each entry's string length decoded, + * as for a plain file, so a length is still read without its record; the + * records of a block are walked by their own headers. Written by + * ray_sym_domain_compress; appends to it are coded with its table. */ +#define DOMAIN_STRZ_MAGIC 0x5A525453U /* "STRZ" */ +#define DOM_Z_TAB (1 + 255 + 255 * 8) +#define DOM_Z_REC0 ((size_t)12 + DOM_Z_TAB) /* byte offset of a compressed file's first record */ + typedef enum { DOM_RUNTIME = 0, DOM_FILE = 1, @@ -122,12 +169,99 @@ typedef struct dom_retired_map_s { size_t size; struct dom_retired_map_s* next; } dom_retired_map_t; +/* ---- sparse record index --------------------------------------------------- + * + * A symfile's records are variable-length, so finding entry `pos` needs the + * byte offset of a record at or before it. The domain keeps a block table: + * blocks of DOM_IX_STRIDE (28) entries, each one cache line (64 bytes): the + * offset of its first record (a checkpoint) and the length of each entry's + * string in two bytes (65535: 65535 or longer, the record's own u32 then + * says). Entry j of block pos / 28 is found from the checkpoint by adding up + * the records before it — from the lengths, a 65535 one from its record + * header — so a lookup touches one cache line of the table and reads the + * record it wants and nothing before it, and a string's length needs no + * record at all unless it is 65535 or longer (ray_sym_domain_raw_len). + * + * The table is persisted next to the symfile, in `.ix`, so that + * opening a domain reads neither the records nor the table: only the 128-byte + * header; the blocks are mapped and paged in as entries are read. An index + * is used only for the very file it was written for: the inode, the + * modification and status-change times and the size it records match the + * mapped file's. Anything else (another file of the name, the file grown + * or rewritten by a writer that left the index as it was, an earlier + * format) is not used: the open walks every record once, reading the file + * in large explicit reads (dom_src_t), and writes the index anew. The + * symfile and its index are ours: an index that names the file is read as + * written, with no check of its blocks or of the records. + * + * The index file (all integers little-endian): + * + * 0 u32 "STRX" 4 u32 version 8 u32 stride (28) 12 u32 0 + * 16 i64 count: entries covered 24 u64 end: byte offset past their records + * 32 u64 inode, 40 u64 stamp of the modification and status-change times + * of the file it was written for + * 48 u64 checkpoint of the last block (n - 1) + * 56 u32 0 60 u32 0 64 u32 0 68 u32 0 + * 72 u64 cap: block slots 80 .. 127: zeros + * 128 n blocks of 64 bytes, n = ceil(count / 28), then zeros up to cap: + * u64 offset of the block's first record, then 28 u16 lengths (those + * past `count` in the last block: 0) + * + * The symfile is append-only, and so is the block array: a writer that + * appended records writes the block the old entries ended in and the + * blocks they open into the reserved slots, then the header — the cost of + * what it appended — and writes the index whole (tmp + rename, with room + * for more blocks) when the slots run out or the index on disk is not the + * one it last read or wrote. It is a cache, never the only copy of + * anything: never synced. */ +#define DOM_IX_STRIDE ((int64_t)RAY_SYM_INDEX_STRIDE) +typedef ray_sym_ixblk_t dom_ixb_t; +#define DOM_IX_MAGIC 0x58525453U /* "STRX" */ +#define DOM_IX_VERSION 5u +#define DOM_IX_HDR 128 /* the blocks start on a cache line */ +#define DOM_IX_HEAD 4096 /* an extend compares this many bytes of the first records */ +#define DOM_LEN_LONG 65535 /* a length of 65535: the escape, 65535 or longer, its record header says */ + +/* The block table of an image of `count` entries whose records end at + * `end`; one allocation. The entries' lengths: this allocation's own (a + * walk), or the mapped index file (the domain keeps the mapping until it + * dies). */ +typedef struct dom_blk_s { + int64_t n; + int64_t count; + uint64_t end; + const dom_ixb_t* ib; /* block k: starts at map + ib[k].off, its entries' lengths */ + dom_ixb_t* own_ib; /* ib, when this allocation holds it (a walk) */ +} dom_blk_t; + typedef struct dom_raw_snap_s { const unsigned char* map; - const size_t* offsets; + dom_blk_t* blk; int64_t count; } dom_raw_snap_t; +/* Growable checkpoint list (sys memory: process-global, like the domain). */ +typedef struct { + uint64_t* v; + int64_t n, cap; +} dom_ck_t; + +/* ---- atom slots -------------------------------------------------------------- + * + * atoms[pos] is reached through a directory of fixed-size slot chunks, a + * chunk allocated (zeroed, from the domain arena) the first time a slot in + * it is set. A flat array of one pointer per entry would commit 8 bytes per + * entry of the vocabulary at open, materialized or not. */ +#define DOM_SLOT_LOG 11 +#define DOM_SLOTS ((int64_t)1 << DOM_SLOT_LOG) +typedef struct { + _Atomic(ray_t*) a[DOM_SLOTS]; +} dom_slots_t; +typedef struct { + int64_t n; /* chunk pointers: covers n * DOM_SLOTS slots */ + _Atomic(dom_slots_t*) c[]; +} dom_dir_t; + struct ray_sym_domain_s { uint8_t kind; /* dom_kind_t */ bool immortal; /* runtime singleton: retain/release skip */ @@ -138,6 +272,7 @@ struct ray_sym_domain_s { * created domain with no file yet). */ void* map; size_t map_size; + ray_file_id_t map_id; /* the mapped file's identity (from its descriptor) */ int64_t base_count; /* entries that came from the mapping */ /* FILE: persisted state — how much of the vocabulary the file holds @@ -151,11 +286,12 @@ struct ray_sym_domain_s { * on first access from the arena. A slot is NULL until materialized; * the per-slot publication is an atomic release store. count is * release-published AFTER the slot write (for appends); growth REPLACES - * the array via atomic store and retires the old one. Lock-free readers + * the array via atomic store; an append retires the old one, an external + * extend frees it (see the concurrency note above). Lock-free readers * load count (acquire) then atoms (acquire) then the slot (acquire). */ _Atomic(int64_t) count; - _Atomic(ray_t**) atoms; - int64_t atoms_cap; /* guarded by g_dom_lock */ + _Atomic(dom_dir_t*) atoms; + int64_t atoms_cap; /* slots the directory covers; guarded by g_dom_lock */ /* FILE: per-domain ray_arena_t backing every materialized string atom * (lazy file slots + runtime-appended interns). Atoms carry @@ -163,17 +299,28 @@ struct ray_sym_domain_s { * Guarded by g_dom_lock (only ever touched under it). */ ray_arena_t* arena; - /* FILE: byte offset within `map` of each file entry's record (the u32 - * length prefix). base_count entries, covering the file prefix - * [0, base_count) only. Built in one pass at open (no per-entry alloc); - * used to materialize atoms[pos] on demand from the mmap bytes. - * malloc'd; NULL when base_count == 0. */ - size_t* offsets; - /* Published raw snapshot (see ray_sym_domain_raw_pin): map, offsets and - * the file-prefix count as one immutable record. Replaced whole on - * extend; the previous record, its offsets and its mapping are retired - * (retired / retired_maps) rather than freed, so a reader holding the - * old snapshot stays valid until the domain is destroyed. */ + /* FILE: block table of the mapped records, the file prefix + * [0, base_count) (see the sparse record index above): from the index + * file or one walk at open. Read under g_dom_lock; lock-free readers + * take it from the raw snapshot. NULL when base_count == 0. */ + dom_blk_t* blk; + /* FILE: what the index did for this domain (ray_sym_domain_ix_info). */ + bool ix_used; /* the open took its blocks from the index */ + /* FILE: checkpoints of the entries this process flushed past the + * mapping, positions in [base_count, disk_count) that are multiples of + * the stride, offsets in the file as written. Guarded by the symfile's + * `.lk` flock (the flush paths), published under g_dom_lock. */ + dom_ck_t wck; + /* FILE: entries, and the byte offset past their records, the index + * file covered when this process last read or wrote it. */ + _Atomic(int64_t) ix_count; + _Atomic(uint64_t) ix_end; + int64_t ix_covered; /* entries the open (or extend) took from the index */ + /* Published raw snapshot (see ray_sym_domain_raw_pin): map, checkpoints + * and the file-prefix count as one immutable record. Replaced whole on + * extend; the previous record, its checkpoints and its mapping are freed + * then, or retired (retired / retired_maps) while a batch intern is + * probing outside the lock — see the concurrency note above. */ _Atomic(struct dom_raw_snap_s*) raw_snap; struct dom_retired_map_s* retired_maps; @@ -191,14 +338,26 @@ struct ray_sym_domain_s { uint64_t* buckets; uint64_t bucket_mask; /* cap - 1; 0 = not built yet */ /* Batch interns currently probing a snapshot of `buckets` outside the - * lock (guarded by g_dom_lock). While non-zero a replaced table is - * retired instead of freed. */ + * lock (guarded by g_dom_lock). While non-zero, whatever an extend + * or an index rebuild replaces is retired instead of freed. */ int32_t batch_inflight; - dom_retired_t* retired; /* replaced atom arrays + old LUTs */ + dom_retired_t* retired; /* replaced directories, checkpoints, snapshot records, LUTs */ struct ray_symimp_s* imp; /* DOM_IMPORT: the import dictionary */ + /* FILE, compressed symfile: its symbol table and the encoder's index + * (immutable after open), the byte offset of its first record (12 for + * a plain file), and a decode buffer for the paths under g_dom_lock. */ + ray_fsst_table_t* z; + ray_fsst_index_t* zix; + size_t rec0; + uint8_t* zbuf; + size_t zcap; + + /* FILE: the bytes of the file read whole at open (ray_sym_domain_preload); 0: lazy */ + size_t preloaded; + struct ray_sym_domain_s* next; /* cache chain */ }; @@ -320,40 +479,452 @@ static bool dom_retire(ray_sym_domain_t* d, void* p) { return true; } -/* Drop a replaced reverse-index table: freed at once unless a batch intern - * is probing a snapshot outside the lock, then retired with the domain. */ -static bool dom_drop_buckets_locked(ray_sym_domain_t* d, uint64_t* old) { +/* Drop something a lock-free reader of this domain MAY hold: freed at once + * unless a batch intern is probing a snapshot outside the lock, then + * retired with the domain. Correct only where no other reader can be + * holding it -- the reverse index (probed by batch interns alone) and the + * generation replaced by an external extend (see the concurrency note at + * the top of the file: a reopen runs between kernels, and a pin does not + * survive one). The append paths keep dom_retire: their readers are the + * concurrent import workers. */ +static bool dom_drop_locked(ray_sym_domain_t* d, void* old) { if (!old) return true; if (d->batch_inflight == 0) { ray_sys_free(old); return true; } return dom_retire(d, old); } +static bool dom_drop_buckets_locked(ray_sym_domain_t* d, uint64_t* old) { + return dom_drop_locked(d, old); +} -/* Publish (map, offsets, count) as the domain's raw snapshot; the previous - * record is retired. Called with the file's current image in place. */ -static bool dom_publish_raw_snap(ray_sym_domain_t* d) { +/* Publish (map, block table, count) as the domain's raw snapshot. The + * previous record is dropped (external extend: no reader holds it) or + * retired. Called with the file's current image in place. */ +static bool dom_publish_raw_snap(ray_sym_domain_t* d, bool drop_old) { dom_raw_snap_t* snap = NULL; - if (d->map && d->offsets && d->base_count > 0) { + if (d->map && d->blk && d->base_count > 0) { snap = (dom_raw_snap_t*)ray_sys_alloc(sizeof(*snap)); if (!snap) return false; snap->map = (const unsigned char*)d->map; - snap->offsets = d->offsets; + snap->blk = d->blk; snap->count = d->base_count; } dom_raw_snap_t* old = atomic_exchange_explicit(&d->raw_snap, snap, memory_order_acq_rel); - if (old) (void)dom_retire(d, old); + if (old) (void)(drop_old ? dom_drop_locked(d, old) : dom_retire(d, old)); + return true; +} + +/* ---- atom slots ---------------------------------------------------------- */ + +/* A directory covering `slots` slots (whole chunks), carrying the chunks of + * `old`. NULL on OOM. Fresh pointers are NULL (sys memory is zeroed). */ +static dom_dir_t* dom_dir_new(int64_t slots, dom_dir_t* old) { + int64_t n = (slots + DOM_SLOTS - 1) >> DOM_SLOT_LOG; + if (n < 1) n = 1; + dom_dir_t* dir = (dom_dir_t*)ray_sys_alloc(sizeof(dom_dir_t) + + (size_t)n * sizeof(dom_slots_t*)); + if (!dir) return NULL; + dir->n = n; + int64_t keep = old ? (old->n < n ? old->n : n) : 0; + for (int64_t k = 0; k < keep; k++) + atomic_store_explicit(&dir->c[k], + atomic_load_explicit(&old->c[k], memory_order_relaxed), + memory_order_relaxed); + return dir; +} + +/* Slot `pos` of `dir`: the atom, or NULL (not materialized, or a chunk this + * directory has not seen). Lock-free. */ +static inline ray_t* dom_slot_get(dom_dir_t* dir, int64_t pos) { + if (!dir || pos < 0 || (pos >> DOM_SLOT_LOG) >= dir->n) return NULL; + dom_slots_t* c = atomic_load_explicit(&dir->c[pos >> DOM_SLOT_LOG], memory_order_acquire); + return c ? atomic_load_explicit(&c->a[pos & (DOM_SLOTS - 1)], memory_order_acquire) + : NULL; +} + +/* The current directory's chunk holding slot `pos` (< atoms_cap), made in + * the arena when absent. Under g_dom_lock. NULL on OOM. */ +static dom_slots_t* dom_chunk_locked(ray_sym_domain_t* d, int64_t pos) { + dom_dir_t* dir = atomic_load_explicit(&d->atoms, memory_order_relaxed); + _Atomic(dom_slots_t*)* cp = &dir->c[pos >> DOM_SLOT_LOG]; + dom_slots_t* c = atomic_load_explicit(cp, memory_order_relaxed); + if (c) return c; + c = (dom_slots_t*)ray_arena_alloc_raw(d->arena, sizeof(dom_slots_t)); + if (!c) return NULL; + for (int64_t i = 0; i < DOM_SLOTS; i++) + atomic_store_explicit(&c->a[i], NULL, memory_order_relaxed); + atomic_store_explicit(cp, c, memory_order_release); + return c; +} + +static bool dom_slot_set_locked(ray_sym_domain_t* d, int64_t pos, ray_t* a) { + dom_slots_t* c = dom_chunk_locked(d, pos); + if (!c) return false; + atomic_store_explicit(&c->a[pos & (DOM_SLOTS - 1)], a, memory_order_release); + return true; +} + +/* Cover `need` slots: a grown directory REPLACES the current one (lock-free + * readers may hold it, so it is retired). Under g_dom_lock. */ +static bool dom_grow_locked(ray_sym_domain_t* d, int64_t need) { + if (need <= d->atoms_cap) return true; + int64_t ncap = d->atoms_cap < DOM_SLOTS ? DOM_SLOTS : d->atoms_cap; + while (ncap < need) ncap *= 2; + dom_dir_t* old = atomic_load_explicit(&d->atoms, memory_order_relaxed); + dom_dir_t* dir = dom_dir_new(ncap, old); + if (!dir) return false; + if (!dom_retire(d, old)) { ray_sys_free(dir); return false; } + atomic_store_explicit(&d->atoms, dir, memory_order_release); + d->atoms_cap = dir->n << DOM_SLOT_LOG; + return true; +} + +/* ---- records and blocks ------------------------------------------------------ */ + +static bool dom_ck_reserve(dom_ck_t* ck, int64_t want) { + if (want <= ck->cap) return true; + uint64_t* nv = (uint64_t*)ray_sys_alloc((size_t)want * sizeof(uint64_t)); + if (!nv) return false; + if (ck->n) memcpy(nv, ck->v, (size_t)ck->n * sizeof(uint64_t)); + ray_sys_free(ck->v); + ck->v = nv; + ck->cap = want; + return true; +} + +static bool dom_ck_push(dom_ck_t* ck, uint64_t off) { + if (ck->n == ck->cap && !dom_ck_reserve(ck, ck->cap < 64 ? 64 : ck->cap * 2)) + return false; + ck->v[ck->n++] = off; + return true; +} + +static void dom_ck_free(dom_ck_t* ck) { + ray_sys_free(ck->v); + ck->v = NULL; + ck->n = ck->cap = 0; +} + +static inline int64_t dom_ck_count(int64_t entries) { + return (entries + DOM_IX_STRIDE - 1) / DOM_IX_STRIDE; +} + +static inline uint32_t dom_rd32(const uint8_t* p) { uint32_t v; memcpy(&v, p, 4); return v; } +static inline uint64_t dom_rd64(const uint8_t* p) { uint64_t v; memcpy(&v, p, 8); return v; } + +_Static_assert(sizeof(ray_fsst_table_t) == DOM_Z_TAB, "a symbol table is stored as laid out"); + +/* The byte offset of the first record of a symfile image (by its magic). */ +static inline size_t dom_rec0_of(const uint8_t* map) { + return dom_rd32(map) == DOMAIN_STRZ_MAGIC ? DOM_Z_REC0 : 12; +} + +/* Buffer `*buf` of at least `need` bytes (sys memory, grown by doubling). */ +static uint8_t* dom_buf_need(uint8_t** buf, size_t* cap, size_t need) { + if (need <= *cap) return *buf; + size_t c = *cap ? *cap : 256; + while (c < need) c *= 2; + uint8_t* nb = (uint8_t*)ray_sys_alloc(c); + if (!nb) return NULL; + ray_sys_free(*buf); + *buf = nb; + *cap = c; + return nb; +} + +/* The coded record of entry `pos` of a compressed image: past the records + * before it in its block by their own headers. */ +static inline const uint8_t* dom_z_rec(const uint8_t* map, const dom_ixb_t* ib, int64_t pos, + uint32_t* clen) { + int64_t k = pos / DOM_IX_STRIDE, j = pos % DOM_IX_STRIDE; + const uint8_t* p = map + ib[k].off; + for (int64_t i = 0; i < j; i++) p += 4 + (size_t)dom_rd32(p); + *clen = dom_rd32(p); + return p + 4; +} + +/* Entry `pos`'s decoded length: from the index, the escape's from its record. */ +static inline size_t dom_z_len(const ray_fsst_table_t* z, const dom_ixb_t* ib, int64_t pos, + const uint8_t* rec, uint32_t clen) { + uint16_t e = ib[pos / DOM_IX_STRIDE].len[pos % DOM_IX_STRIDE]; + return e < DOM_LEN_LONG ? e : (size_t)ray_fsst_expanded_len(z, rec, clen); +} + +/* The decode buffers of the calling thread, used in turn (domain.h). */ +typedef struct { + uint8_t* b[RAY_SYM_RAW_RING]; + size_t cap[RAY_SYM_RAW_RING]; + unsigned at; +} dom_zring_t; +static _Thread_local dom_zring_t g_zring; + +void ray_sym_domain_raw_decode(const ray_sym_domain_raw_t* r, int64_t pos, char* out) { + uint32_t clen; + const uint8_t* rec = dom_z_rec(r->map, r->ib, pos, &clen); + ray_fsst_decode_fast((const ray_fsst_table_t*)r->z, rec, clen, (uint8_t*)out); +} + +const char* ray_sym_domain_raw_str_z(const ray_sym_domain_raw_t* r, int64_t pos, size_t* len) { + const ray_fsst_table_t* z = (const ray_fsst_table_t*)r->z; + uint32_t clen; + const uint8_t* rec = dom_z_rec(r->map, r->ib, pos, &clen); + size_t dl = dom_z_len(z, r->ib, pos, rec, clen); + unsigned k = g_zring.at++ % RAY_SYM_RAW_RING; + uint8_t* out = dom_buf_need(&g_zring.b[k], &g_zring.cap[k], dl + 8); + if (!out) { *len = 0; return NULL; } + ray_fsst_decode_fast(z, rec, clen, out); + *len = dl; + return (const char*)out; +} + +/* A block table for `count` entries; with room for its own checkpoints + * and lengths when `own` (else both are the index file's, set by the + * caller). NULL on OOM. */ +static dom_blk_t* dom_blk_new(int64_t count, bool own) { + int64_t n = dom_ck_count(count); + size_t head = (sizeof(dom_blk_t) + 7) & ~(size_t)7; + size_t ibb = own ? (size_t)n * sizeof(dom_ixb_t) : 0; + dom_blk_t* b = (dom_blk_t*)ray_sys_alloc(head + ibb); + if (!b) return NULL; + uint8_t* p = (uint8_t*)b + head; + b->n = n; + b->count = count; + b->end = 0; + b->own_ib = own ? (dom_ixb_t*)p : NULL; + b->ib = b->own_ib; + if (own) memset(b->own_ib, 0, ibb); /* unused lengths of the last block: 0 */ + return b; +} + +static inline uint64_t dom_blk_lim(const dom_blk_t* b, int64_t k) { + return k + 1 < b->n ? b->ib[k + 1].off : b->end; +} + +/* Where a walk reads the records: the mapping, or the file read + * with explicit, large reads into a buffer (dom_src_open). A walk over + * much of the file through the mapping faults it in a page cluster at a + * time (some 128 KiB a request) and leaves the pages mapped — kept by the + * reclaim as referenced, so a walk over a file larger than the memory + * thrashes its own read-ahead; read() into a buffer takes it in 4 MiB + * requests, each page read once. */ +#define DOM_RD_CHUNK ((size_t)4 << 20) +typedef struct { + const uint8_t* map; /* the mapping (no reads), or NULL */ + int fd; + uint8_t* buf; + size_t cap; + uint64_t lo, hi; /* the file bytes buf holds */ + uint64_t size; /* the image's bytes */ +} dom_src_t; + +static inline dom_src_t dom_src_map(const uint8_t* map, uint64_t size) { + dom_src_t s; + memset(&s, 0, sizeof(s)); + s.map = map; + s.fd = -1; + s.size = size; + return s; +} + +/* Explicit reads of the file `path` — only if it is still the file of + * identity `id` that is mapped (size `size`). False where it cannot be: + * the caller reads through the mapping. */ +static bool dom_src_open(dom_src_t* s, const char* path, const ray_file_id_t* id, uint64_t size) { + memset(s, 0, sizeof(*s)); + s->fd = -1; + s->size = size; +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) + if (!path || !id || !id->valid) return false; + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return false; + struct stat st; + if (fstat(fd, &st) != 0 || (uint64_t)st.st_ino != id->ino || (uint64_t)st.st_size != size) { + close(fd); + return false; + } +#if defined(POSIX_FADV_SEQUENTIAL) + (void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL); +#endif + s->fd = fd; + return true; +#else + (void)path; (void)id; + return false; +#endif +} + +static void dom_src_close(dom_src_t* s) { +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) + if (s->fd >= 0) close(s->fd); +#endif + ray_sys_free(s->buf); + s->buf = NULL; + s->fd = -1; +} + +/* Bytes [off, off + len) of the image: in the mapping, or read into the + * buffer (from `off`, at least a chunk). NULL past the image or on a read + * error. */ +static const uint8_t* dom_src_get(dom_src_t* s, uint64_t off, uint64_t len) { + if (off > s->size || len > s->size - off) return NULL; + if (s->map) return s->map + off; + if (off >= s->lo && off + len <= s->hi) return s->buf + (off - s->lo); +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) + uint64_t n = len > DOM_RD_CHUNK ? len : DOM_RD_CHUNK; + if (n > s->size - off) n = s->size - off; + if (n > s->cap) { + uint8_t* nb = (uint8_t*)ray_sys_alloc((size_t)n); + if (!nb) return NULL; + ray_sys_free(s->buf); + s->buf = nb; + s->cap = (size_t)n; + } + uint64_t got = 0; + while (got < n) { + ssize_t r = pread(s->fd, s->buf + got, (size_t)(n - got), (off_t)(off + got)); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) { s->lo = s->hi = 0; return NULL; } + got += (uint64_t)r; + } +#if defined(POSIX_FADV_WILLNEED) + /* the next chunk is read while this one is checked; the one just + * read is not needed again (pages the mapping holds stay) */ + if (off + n < s->size) + (void)posix_fadvise(s->fd, (off_t)(off + n), (off_t)DOM_RD_CHUNK, POSIX_FADV_WILLNEED); + if (s->hi > s->lo) + (void)posix_fadvise(s->fd, (off_t)s->lo, (off_t)(s->hi - s->lo), POSIX_FADV_DONTNEED); +#endif + s->lo = off; + s->hi = off + n; + return s->buf; +#else + return NULL; +#endif +} + +/* Walk entries [from, b->count) of the image, the first at byte *off: the + * checkpoint of every block that starts on the way and, into the table's own + * lengths, the length of every entry (of a compressed image `z`, decoded + * from its record). False when a read of the file fails. */ +static bool dom_blk_walk_src(dom_src_t* src, dom_blk_t* b, int64_t from, size_t* off, + const ray_fsst_table_t* z) { + uint64_t o = *off; + for (int64_t i = from; i < b->count; i++) { + int64_t k = i / DOM_IX_STRIDE, j = i % DOM_IX_STRIDE; + if (!j) b->own_ib[k].off = o; + const uint8_t* h = dom_src_get(src, o, 4); + if (!h) return false; + uint32_t l = dom_rd32(h), sl = l; + if (z) { + const uint8_t* rec = dom_src_get(src, o + 4, l); + if (!rec) return false; + sl = (uint32_t)ray_fsst_expanded_len(z, rec, l); + } + o += 4 + (uint64_t)l; + b->own_ib[k].len[j] = sl < DOM_LEN_LONG ? (uint16_t)sl : (uint16_t)DOM_LEN_LONG; + } + *off = (size_t)o; return true; } +/* Entry `pos`: from its block's checkpoint past the records before it, by + * their lengths (a 65535 one by its header). */ +static inline const uint8_t* dom_blk_entry(const uint8_t* map, const dom_blk_t* b, + int64_t pos, uint32_t* len) { + int64_t k = pos / DOM_IX_STRIDE, j = pos % DOM_IX_STRIDE; + const uint8_t* p = map + b->ib[k].off; + for (int64_t i = 0; i < j; i++) { + uint16_t l = b->ib[k].len[i]; + p += 4 + (l < DOM_LEN_LONG ? (size_t)l : (size_t)dom_rd32(p)); + } + *len = dom_rd32(p); + return p + 4; +} + +static void dom_blk_save(const char* path, const uint8_t* map, size_t map_size, + const dom_blk_t* b, const ray_file_id_t* id); +static size_t dom_ix_min(void); + +/* The string of a compressed record [rec, rec + clen) of length `dl`, + * decoded into the domain's buffer. Under g_dom_lock. */ +static const uint8_t* dom_z_decode_locked(ray_sym_domain_t* d, const uint8_t* rec, uint32_t clen, + size_t dl) { + uint8_t* out = dom_buf_need(&d->zbuf, &d->zcap, dl + 8); + if (!out) return NULL; + ray_fsst_decode_fast(d->z, rec, clen, out); + return out; +} + +/* Entry `pos` of the mapped prefix (of a compressed file decoded, valid + * until the next such read). Under g_dom_lock. NULL when out of range. */ +static const uint8_t* dom_entry_locked(ray_sym_domain_t* d, int64_t pos, uint32_t* len) { + if (pos < 0 || pos >= d->base_count || !d->blk) return NULL; + if (d->z) { + uint32_t clen; + const uint8_t* rec = dom_z_rec((const uint8_t*)d->map, d->blk->ib, pos, &clen); + size_t dl = dom_z_len(d->z, d->blk->ib, pos, rec, clen); + *len = (uint32_t)dl; + return dom_z_decode_locked(d, rec, clen, dl); + } + return dom_blk_entry((const uint8_t*)d->map, d->blk, pos, len); +} + +/* Bytes of entry `pos` in order, for a pass over the whole vocabulary + * (pos = 0, 1, ..., *off starting at d->rec0): the mapped records read in + * turn (a compressed one decoded, valid until the next call), then the + * appended atoms. Under g_dom_lock. */ +static bool dom_next_locked(ray_sym_domain_t* d, int64_t pos, size_t* off, + const char** p, size_t* len) { + if (pos < d->base_count) { + size_t o = *off; + uint32_t l = dom_rd32((const uint8_t*)d->map + o); + const uint8_t* rec = (const uint8_t*)d->map + o + 4; + *off = o + 4 + l; + if (d->z) { + size_t dl = dom_z_len(d->z, d->blk->ib, pos, rec, l); + const uint8_t* out = dom_z_decode_locked(d, rec, l, dl); + if (!out) return false; + *p = (const char*)out; + *len = dl; + return true; + } + *p = (const char*)rec; + *len = l; + return true; + } + ray_t* a = dom_slot_get(atomic_load_explicit(&d->atoms, memory_order_relaxed), pos); + if (!a) return false; + *p = ray_str_ptr(a); + *len = ray_str_len(a); + return true; +} + +/* Bytes of entry `pos`: its atom when there is one, else its record in the + * mapping — nothing materialized. Under g_dom_lock. NULL if unresolvable. */ +static const char* dom_bytes_locked(ray_sym_domain_t* d, int64_t pos, size_t* len) { + ray_t* a = dom_slot_get(atomic_load_explicit(&d->atoms, memory_order_relaxed), pos); + if (a) { *len = ray_str_len(a); return ray_str_ptr(a); } + uint32_t l = 0; + const uint8_t* p = dom_entry_locked(d, pos, &l); + *len = l; + return (const char*)p; +} + /* Free a FILE domain after the last reference dropped. Caller has * already unlinked it from the cache. */ +static void dom_preload_release(ray_sym_domain_t* d); + static void dom_destroy(ray_sym_domain_t* d) { + dom_preload_release(d); if (d->imp) ray_symimp_free(d->imp); - /* Atoms are RAY_ATTR_ARENA — never refcounted, never individually freed. - * The arena bulk-frees them; we only free the pointer ARRAY here. */ - ray_t** atoms = atomic_load_explicit(&d->atoms, memory_order_relaxed); - ray_sys_free(atoms); + ray_sys_free(d->z); + ray_sys_free(d->zix); + ray_sys_free(d->zbuf); + /* Atoms and slot chunks are arena memory — never individually freed. + * The arena bulk-frees them; only the directory is freed here. */ + ray_sys_free(atomic_load_explicit(&d->atoms, memory_order_relaxed)); if (d->arena) ray_arena_destroy(d->arena); - ray_sys_free(d->offsets); + ray_sys_free(d->blk); + dom_ck_free(&d->wck); ray_sys_free(atomic_load_explicit(&d->runtime_lut, memory_order_relaxed)); for (dom_retired_t* r = d->retired; r;) { dom_retired_t* nxt = r->next; @@ -374,80 +945,378 @@ static void dom_destroy(ray_sym_domain_t* d) { ray_sys_free(d); } -/* Index a mapped STRL image in one pass WITHOUT materializing any atom: - * validate magic + count, then record each record's byte offset (the start - * of its u32 length prefix) into a fresh offsets array. atoms[] are all - * NULL — every slot is materialized lazily on first access. Returns false - * on structural inconsistency (bad magic, truncated record, trailing bytes) - * or OOM. On success *out_atoms (calloc'd NULLs) and *out_offsets (malloc'd - * byte offsets), each exactly *out_count entries; both NULL when empty. */ -static bool dom_parse_strl_atoms(const void* map, size_t map_size, - ray_t*** out_atoms, size_t** out_offsets, - int64_t* out_count) { - const uint8_t* base = (const uint8_t*)map; - if (map_size < 12) return false; - - uint32_t magic; - memcpy(&magic, base, 4); - if (magic != DOMAIN_STRL_MAGIC) return false; - - int64_t count; - memcpy(&count, base + 4, 8); - if (count < 0 || count > UINT32_MAX) return false; - - ray_t** atoms = NULL; - size_t* offsets = NULL; - if (count > 0) { - atoms = (ray_t**)ray_sys_alloc((size_t)((size_t)count) * (sizeof(ray_t*))); - if (!atoms) return false; - offsets = (size_t*)ray_sys_alloc((size_t)count * sizeof(size_t)); - if (!offsets) { ray_sys_free(atoms); return false; } - } - - size_t off = 12; - size_t remaining = map_size - 12; - for (int64_t i = 0; i < count; i++) { - offsets[i] = off; /* start of this record's u32 len prefix */ - uint32_t slen; - if (remaining < 4) goto fail; - memcpy(&slen, base + off, 4); - off += 4; remaining -= 4; - if ((size_t)slen > remaining) goto fail; - off += slen; remaining -= slen; - } - if (remaining != 0) goto fail; - - *out_atoms = atoms; - *out_offsets = offsets; - *out_count = count; +/* ---- the index file ------------------------------------------------------- */ + +/* Symfiles smaller than this get no index file: walking them at open costs + * less than reading one. RAY_SYM_INDEX_MIN overrides it (bytes). */ +static size_t dom_ix_min(void) { + const char* e = getenv("RAY_SYM_INDEX_MIN"); + if (e && *e) return (size_t)strtoull(e, NULL, 10); + return (size_t)1 << 20; +} + +static bool dom_ix_name(char* out, size_t cap, const char* sym, const char* suffix) { + int n = snprintf(out, cap, "%s.ix%s", sym, suffix); + return n > 0 && (size_t)n < cap; +} + +static bool dom_fseek_ix(FILE* f, int64_t off) { +#ifdef RAY_OS_WINDOWS + return _fseeki64(f, off, SEEK_SET) == 0; +#else + return fseeko(f, (off_t)off, SEEK_SET) == 0; +#endif +} + +/* Remove the temporary index files (`.ix..tmp`) a process that + * no longer runs left behind. */ +static void dom_ix_sweep_tmp(const char* path) { +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) + char dir[PATH_MAX], pre[PATH_MAX]; + const char* slash = strrchr(path, '/'); + const char* base = slash ? slash + 1 : path; + size_t dl = slash ? (size_t)(slash - path) : 0; + if (dl >= sizeof(dir)) return; + if (slash) { memcpy(dir, path, dl); dir[dl] = 0; } else { dir[0] = '.'; dir[1] = 0; } + int prl = snprintf(pre, sizeof(pre), "%s.ix.", base); + if (prl <= 0 || (size_t)prl >= sizeof(pre)) return; + DIR* dh = opendir(dir); + if (!dh) return; + struct dirent* e; + while ((e = readdir(dh))) { + size_t el = strlen(e->d_name); + if (el <= (size_t)prl + 4 || strncmp(e->d_name, pre, (size_t)prl) != 0 || + strcmp(e->d_name + el - 4, ".tmp") != 0) continue; + char* stop = NULL; + long long pid = strtoll(e->d_name + prl, &stop, 10); + if (pid <= 0 || stop != e->d_name + el - 4) continue; + if ((unsigned long long)pid == dom_pid()) continue; + if (kill((pid_t)pid, 0) == 0 || errno != ESRCH) continue; + char full[PATH_MAX]; + if (snprintf(full, sizeof(full), "%s/%s", dir, e->d_name) < (int)sizeof(full)) + (void)unlink(full); + } + closedir(dh); +#else + (void)path; +#endif +} + +/* The identity an index records for the file it was written for: the inode + * and one value of the modification and status-change times (the latter + * cannot be set back by a writer: an in-place rewrite always moves it). */ +static inline uint64_t dom_id_stamp(const ray_file_id_t* id) { + return (uint64_t)id->mtime_ns ^ ((uint64_t)id->ctime_ns * UINT64_C(0x9E3779B97F4A7C15)); +} + +/* The index file's header, parsed. */ +typedef struct { + int64_t count; /* entries covered */ + uint64_t end; /* byte offset past their records */ + uint64_t ino, stamp; /* the file it was written for (both 0: none claimed) */ + uint64_t last_ckpt; /* checkpoint of the last block */ + uint64_t cap; /* block slots */ +} dom_ixh_t; + + + +static void dom_ixh_put(uint8_t* h, const dom_ixh_t* x) { + memset(h, 0, DOM_IX_HDR); + uint32_t w = DOM_IX_MAGIC; memcpy(h, &w, 4); + w = DOM_IX_VERSION; memcpy(h + 4, &w, 4); + w = (uint32_t)DOM_IX_STRIDE; memcpy(h + 8, &w, 4); + memcpy(h + 16, &x->count, 8); + memcpy(h + 24, &x->end, 8); + memcpy(h + 32, &x->ino, 8); + memcpy(h + 40, &x->stamp, 8); + memcpy(h + 48, &x->last_ckpt, 8); + memcpy(h + 72, &x->cap, 8); +} + +static bool dom_ixh_get(const uint8_t* h, dom_ixh_t* x) { + if (dom_rd32(h) != DOM_IX_MAGIC || dom_rd32(h + 4) != DOM_IX_VERSION || + dom_rd32(h + 8) != (uint32_t)DOM_IX_STRIDE) + return false; + memcpy(&x->count, h + 16, 8); + x->end = dom_rd64(h + 24); + x->ino = dom_rd64(h + 32); + x->stamp = dom_rd64(h + 40); + x->last_ckpt = dom_rd64(h + 48); + x->cap = dom_rd64(h + 72); + return x->count > 0 && x->end > 12 && x->cap >= (uint64_t)dom_ck_count(x->count) && + x->cap <= (uint64_t)dom_ck_count(x->count) * 2 + 4096; +} + +/* Keep a mapping until the domain dies (the index a table points into). */ +static void dom_keep_map(ray_sym_domain_t* d, void* m, size_t sz) { + dom_retired_map_t* rm = (dom_retired_map_t*)ray_sys_alloc(sizeof(*rm)); + if (!rm) return; /* stays mapped for the process lifetime */ + rm->map = m; + rm->size = sz; + rm->next = d->retired_maps; + d->retired_maps = rm; +} + +/* The index of symfile `path` for its mapped image (`size` bytes, `count` + * entries per its header, identity `id`): a block table pointing at its + * checkpoints and its lengths in the index file, mapped (*ixmap / + * *ixsize: for the caller to keep while the table lives). Taken only when + * written for this very file — its identity, size and count are the + * image's — in this format, with its block sections all there. Reads the + * header only; the checkpoints and the lengths are paged in as entries are + * read. NULL otherwise (or on OOM). */ +static dom_blk_t* dom_ix_load(const char* path, const uint8_t* map, size_t size, int64_t count, + const ray_file_id_t* id, void** ixmap, size_t* ixsize, + dom_ixh_t* hx) { + char ip[PATH_MAX]; + if (count <= 0 || !path || !id || !id->valid || id->size != size || + !dom_ix_name(ip, sizeof(ip), path, "")) + return NULL; + FILE* f = fopen(ip, "rb"); + if (!f) return NULL; + uint8_t h[DOM_IX_HDR]; + dom_ixh_t x; + bool ok = fread(h, 1, DOM_IX_HDR, f) == DOM_IX_HDR && dom_ixh_get(h, &x) && + x.count == count && x.end == size && (x.ino | x.stamp) != 0 && + x.ino == id->ino && x.stamp == dom_id_stamp(id); + fclose(f); + (void)map; + dom_blk_t* b = ok ? dom_blk_new(count, false) : NULL; + void* m = NULL; + size_t msz = 0; + ray_file_id_t iid; + if (b) { + m = ray_vm_map_file_id(ip, &msz, &iid); + /* the file mapped is the one read: the same header, every length */ + ok = m && msz >= DOM_IX_HDR + x.cap * sizeof(dom_ixb_t) && + memcmp(m, h, DOM_IX_HDR) == 0; + } + if (!b || !ok) { + if (m) ray_vm_unmap_file(m, msz); + ray_sys_free(b); + return NULL; + } + b->end = size; + b->ib = (const dom_ixb_t*)((const uint8_t*)m + DOM_IX_HDR); + *ixmap = m; + *ixsize = msz; + *hx = x; + return b; +} + +/* Write `bytes` zero bytes to f. */ +static bool dom_write_zeros(FILE* f, uint64_t bytes) { + static const uint8_t z[4096]; + while (bytes) { + size_t c = bytes < sizeof(z) ? (size_t)bytes : sizeof(z); + if (fwrite(z, 1, c, f) != c) return false; + bytes -= c; + } return true; +} -fail: - ray_sys_free(atoms); - ray_sys_free(offsets); - return false; +/* Where a writer takes the entries' lengths from: those of entries below + * `na` from the blocks `pb` (a table's own or mapped ones), the others from + * lb[i - na]. */ +typedef struct { + const dom_ixb_t* pb; + int64_t na; + const uint16_t* lb; +} dom_lsrc_t; + +static inline uint16_t dom_ls_get(const dom_lsrc_t* s, int64_t i) { + return i < s->na ? s->pb[i / DOM_IX_STRIDE].len[i % DOM_IX_STRIDE] : s->lb[i - s->na]; +} + +/* Blocks [k0, k1) of an index of `count` entries — checkpoints ck[k], lengths + * from ls (0 past the last entry) — written to f. */ +static bool dom_write_blocks(FILE* f, const uint64_t* ck, const dom_lsrc_t* ls, int64_t count, + int64_t k0, int64_t k1) { + enum { CHUNK = 64 }; + dom_ixb_t buf[CHUNK]; + for (int64_t k = k0; k < k1;) { + int64_t c = k1 - k < CHUNK ? k1 - k : CHUNK; + memset(buf, 0, sizeof(dom_ixb_t) * (size_t)c); + for (int64_t q = 0; q < c; q++) { + buf[q].off = ck[k + q]; + int64_t i0 = (k + q) * DOM_IX_STRIDE; + for (int64_t j = 0; j < DOM_IX_STRIDE && i0 + j < count; j++) + buf[q].len[j] = dom_ls_get(ls, i0 + j); + } + if (fwrite(buf, sizeof(dom_ixb_t), (size_t)c, f) != (size_t)c) return false; + k += c; + } + return true; +} + +/* Write the whole index of symfile `path`, whose `map` holds the records of + * its first `count` entries, ending at byte `end`, with checkpoints + * ck[0..n) and the entries' lengths (ls); claimed as the index of the file + * of identity `id` when given (and of the size `end`); with room for a + * quarter more blocks; to a temporary file renamed over the index. Best + * effort: the index is a cache. */ +static void dom_ix_save(const char* path, const uint8_t* map, size_t map_size, + const uint64_t* ck, int64_t n, const dom_lsrc_t* ls, + int64_t count, uint64_t end, const ray_file_id_t* id) { + if (!path || count <= 0 || n != dom_ck_count(count) || end > map_size || map_size < 12 || + ck[0] != dom_rec0_of(map) || + ck[n - 1] >= end || (ls->na > 0 && !ls->pb) || (ls->na < count && !ls->lb)) + return; + char ip[PATH_MAX], tp[PATH_MAX]; + char sfx[32]; + snprintf(sfx, sizeof(sfx), ".%llu.tmp", dom_pid()); + if (!dom_ix_name(ip, sizeof(ip), path, "") || !dom_ix_name(tp, sizeof(tp), path, sfx)) return; + dom_ixh_t x; + memset(&x, 0, sizeof(x)); + x.count = count; + x.end = end; + if (id && id->valid && id->size == end) { + x.ino = id->ino; + x.stamp = dom_id_stamp(id); + } + x.last_ckpt = ck[n - 1]; + x.cap = (uint64_t)n + (uint64_t)n / 4 + 64; + uint8_t h[DOM_IX_HDR]; + dom_ixh_put(h, &x); + dom_ix_sweep_tmp(path); + FILE* f = fopen(tp, "wb"); + bool ok = f && fwrite(h, 1, DOM_IX_HDR, f) == DOM_IX_HDR && + dom_write_blocks(f, ck, ls, count, 0, n) && + dom_write_zeros(f, (x.cap - (uint64_t)n) * sizeof(dom_ixb_t)); + if (f && fclose(f) != 0) ok = false; + if (ok) ok = ray_file_rename(tp, ip) == RAY_OK; + if (!ok && f) remove(tp); +} + +/* A writer's refresh of the index of `path` after it appended (`count` + * entries, their records ending at `end`; checkpoints ck[0..n), lengths as + * dom_ix_save's): when the index on disk is the one this process last read + * or wrote (covering `ix_count` entries ending at `ix_end`) and has slots + * for the new blocks, the block the old entries ended in and the new blocks + * are written into the slots, then the header — the cost of what was + * appended; otherwise the index is written whole. The file is mapped for + * its identity, claimed when `stamp`. Under the symfile's `.lk` flock. Best effort. */ +static void dom_ix_refresh(const char* path, const uint64_t* ck, int64_t n, + const dom_lsrc_t* ls, int64_t count, uint64_t end, + int64_t ix_count, uint64_t ix_end, bool stamp) { + if (end < dom_ix_min() || count <= 0 || n != dom_ck_count(count)) return; + size_t size = 0; + ray_file_id_t id; + uint8_t* map = (uint8_t*)ray_vm_map_file_id(path, &size, &id); + if (!map) return; + char ip[PATH_MAX]; + FILE* f = ix_count > 0 && end <= size && dom_ix_name(ip, sizeof(ip), path, "") + ? fopen(ip, "r+b") : NULL; + uint8_t h[DOM_IX_HDR]; + dom_ixh_t x; + bool app = f && fread(h, 1, DOM_IX_HDR, f) == DOM_IX_HDR && dom_ixh_get(h, &x) && + x.count == ix_count && x.end == ix_end && x.count <= count && + (uint64_t)n <= x.cap && size >= 12 && ck[0] == dom_rec0_of(map) && ck[n - 1] < end; + if (app) { + int64_t k0 = dom_ck_count(x.count) - 1; + x.count = count; + x.end = end; + x.ino = x.stamp = 0; + if (stamp && id.valid && id.size == end) { x.ino = id.ino; x.stamp = dom_id_stamp(&id); } + x.last_ckpt = ck[n - 1]; + dom_ixh_put(h, &x); + app = dom_fseek_ix(f, DOM_IX_HDR + k0 * (int64_t)sizeof(dom_ixb_t)) && + dom_write_blocks(f, ck, ls, count, k0, n) && + fflush(f) == 0 && dom_fseek_ix(f, 0) && fwrite(h, 1, DOM_IX_HDR, f) == DOM_IX_HDR; + } + if (f && fclose(f) != 0) app = false; + if (!app) dom_ix_save(path, map, size, ck, n, ls, count, end, stamp ? &id : NULL); + ray_vm_unmap_file(map, size); +} + +static void dom_ix_save_file(const char* path, const uint64_t* ck, int64_t n, + const uint16_t* lens, int64_t count, uint64_t end) { + if (end < dom_ix_min()) return; + size_t size = 0; + ray_file_id_t id; + void* map = ray_vm_map_file_id(path, &size, &id); + if (!map) return; + dom_lsrc_t ls = { NULL, 0, lens }; + dom_ix_save(path, (const uint8_t*)map, size, ck, n, &ls, count, end, &id); + ray_vm_unmap_file(map, size); +} + +/* The index of the table `b` (its own blocks, from a walk): written whole. */ +static void dom_blk_save(const char* path, const uint8_t* map, size_t map_size, + const dom_blk_t* b, const ray_file_id_t* id) { + uint64_t* ck = (uint64_t*)ray_sys_alloc((size_t)b->n * sizeof(uint64_t)); + if (!ck) return; + for (int64_t k = 0; k < b->n; k++) ck[k] = b->ib[k].off; + dom_lsrc_t ls = { b->ib, b->count, NULL }; + dom_ix_save(path, map, map_size, ck, b->n, &ls, b->count, b->end, id); + ray_sys_free(ck); +} + +void ray_sym_domain_index_save(const char* path, const uint64_t* ckpt, int64_t n, + const uint16_t* lens, int64_t count, uint64_t end) { + if (path && ckpt && lens) dom_ix_save_file(path, ckpt, n, lens, count, end); +} + +void ray_sym_domain_index_remove(const char* path) { + char ip[PATH_MAX]; + if (path && dom_ix_name(ip, sizeof(ip), path, "")) (void)remove(ip); } -/* Materialize atoms[pos] from the file bytes at offsets[pos] into the arena +/* The block table of the mapped image of `d` (its `count` entries per the + * header): from the index file when it is this file's, else by one walk of + * all the records (read with explicit reads, dom_src_t), the index then + * written for the file. False when a read of the file fails, when its + * records do not end at its end (a truncated file), or on OOM. */ +static bool dom_index_image(ray_sym_domain_t* d, int64_t count) { + const uint8_t* map = (const uint8_t*)d->map; + size_t size = d->map_size; + dom_ixh_t hx; + void* ixm = NULL; + size_t ixs = 0; + dom_blk_t* b = dom_ix_load(d->path, map, size, count, &d->map_id, &ixm, &ixs, &hx); + bool have = b != NULL; + if (have) { + dom_keep_map(d, ixm, ixs); + } else { + b = dom_blk_new(count, true); + if (!b) return false; + b->end = size; + size_t o = d->rec0; + dom_src_t src; + if (!dom_src_open(&src, d->path, &d->map_id, size)) src = dom_src_map(map, size); + bool walked = dom_blk_walk_src(&src, b, 0, &o, d->z) && o == size; + dom_src_close(&src); + if (!walked) { ray_sys_free(b); return false; } + } + d->blk = b; + d->ix_used = have; + d->ix_count = have ? count : 0; + d->ix_end = have ? size : 0; + d->ix_covered = have ? count : 0; + if (!have && count > 0 && size >= dom_ix_min()) { + dom_blk_save(d->path, map, size, b, &d->map_id); + d->ix_count = count; + d->ix_end = size; + } else if (!have && size < dom_ix_min()) { + ray_sym_domain_index_remove(d->path); /* one left by a larger file of the name */ + } + return true; +} + +/* Materialize slot `pos` of the file prefix from its record into the arena * and publish it. CALLER MUST HOLD g_dom_lock. Idempotent: returns an - * already-published slot without re-materializing. pos must be a valid file - * position (0 <= pos < base_count); runtime-appended slots (pos >= - * base_count) are materialized at append time and are never NULL. Returns - * NULL on arena OOM. */ + * already-published slot without re-materializing. Runtime-appended slots + * (pos >= base_count) are set at append time and never NULL. Returns NULL + * on arena OOM. */ static ray_t* dom_atom_at_locked(ray_sym_domain_t* d, int64_t pos) { - ray_t** atoms = atomic_load_explicit(&d->atoms, memory_order_relaxed); - ray_t* a = atomic_load_explicit((_Atomic(ray_t*)*)&atoms[pos], - memory_order_relaxed); + ray_t* a = dom_slot_get(atomic_load_explicit(&d->atoms, memory_order_relaxed), pos); if (a) return a; - - /* Lazy file slot: read [u32 len | bytes] at offsets[pos] from the map. */ - const uint8_t* base = (const uint8_t*)d->map; - size_t off = d->offsets[pos]; - uint32_t slen; - memcpy(&slen, base + off, 4); - a = ray_arena_str(d->arena, (const char*)base + off + 4, slen); - if (!a) return NULL; - atomic_store_explicit((_Atomic(ray_t*)*)&atoms[pos], a, memory_order_release); + if (pos < 0 || pos >= d->base_count) return NULL; + uint32_t slen = 0; + const uint8_t* p = dom_entry_locked(d, pos, &slen); + if (!p) return NULL; + a = ray_arena_str(d->arena, (const char*)p, slen); + if (!a || !dom_slot_set_locked(d, pos, a)) return NULL; return a; } @@ -458,104 +1327,169 @@ static ray_t* dom_atom_at_locked(ray_sym_domain_t* d, int64_t pos) { * appends (a second writer) — fails. Called under g_dom_lock with the * file's current size in st_size. */ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { + if (d->z) return false; /* a compressed file grows only by this process's flushes */ int64_t count = atomic_load_explicit(&d->count, memory_order_relaxed); if (st_size < d->disk_size) return false; /* shrunk: rewritten */ if (count != d->disk_count) return false; /* our tail is dirty */ size_t map_size = 0; - void* map = ray_vm_map_file(d->path, &map_size); + ray_file_id_t nid; + void* map = ray_vm_map_file_id(d->path, &map_size, &nid); if (!map) return false; - - ray_t** fresh = NULL; /* all-NULL (lazy) slot array for the new image */ - size_t* fresh_offsets = NULL; - int64_t fresh_count = 0; - if (!dom_parse_strl_atoms(map, map_size, &fresh, &fresh_offsets, - &fresh_count)) { - ray_vm_unmap_file(map, map_size); - return false; - } - - bool ok = fresh_count >= count; - const uint8_t* nbase = (const uint8_t*)map; /* new image bytes */ - const uint8_t* obase = (const uint8_t*)d->map; /* old image bytes (count > 0) */ - /* Read a file record's [len, ptr] at byte offset `off` within `b`. */ - #define DOM_REC(b, off, lp, pp) do { \ - uint32_t _l; memcpy(&_l, (b) + (off), 4); \ - (lp) = _l; (pp) = (const char*)((b) + (off) + 4); \ - } while (0) + int64_t fresh_count = -1; + bool ok = map_size >= 12 && dom_rd32(nbase) == DOMAIN_STRL_MAGIC; + if (ok) { + memcpy(&fresh_count, nbase + 4, 8); + ok = fresh_count >= count && fresh_count <= (int64_t)UINT32_MAX; + } /* Position-0 reservation also holds for externally grown files: the * first record of a non-empty file must be the empty string. */ - if (ok && count == 0 && fresh_count > 0) { - uint32_t l0; const char* p0; (void)p0; - DOM_REC(nbase, fresh_offsets[0], l0, p0); - if (l0 != 0) ok = false; - } + if (ok && count == 0 && fresh_count > 0) + ok = map_size >= 16 && dom_rd32(nbase + 12) == 0; /* Append-only prefix check: every position we already published must be - * byte-identical between the old and new file images (compare mmap bytes - * directly via the old/new offsets — no materialization needed). */ - for (int64_t i = 0; ok && i < count; i++) { - uint32_t ol, nl; const char *op, *np; - DOM_REC(obase, d->offsets[i], ol, op); - DOM_REC(nbase, fresh_offsets[i], nl, np); - if (ol != nl || (ol > 0 && memcmp(op, np, ol) != 0)) ok = false; + * the same between the old and the new file images. The new image's + * block table comes from the index the writer that grew the file left + * (when it is that file's, as at open) or from one walk. The mapped + * prefix [0, base_count) is compared by its table — the same checkpoints + * and the same lengths, so the old image's records are not read — + * and by the bytes of its first records and of its last, partial block. + * A flush of this process wrote the rest, [base_count, count), from + * appended atoms (never NULL), compared record by record. A failure + * with the index is tried once more with a walk. */ + dom_blk_t* ob = d->blk; + const uint8_t* obase = (const uint8_t*)d->map; + dom_dir_t* cur = atomic_load_explicit(&d->atoms, memory_order_relaxed); + dom_blk_t* nb = NULL; + bool from_ix = false; + void* nixm = NULL; + size_t nixs = 0; + dom_ixh_t nhx; + memset(&nhx, 0, sizeof(nhx)); + for (int pass = 0; ok && pass < 2; pass++) { + nb = pass == 0 ? dom_ix_load(d->path, nbase, map_size, fresh_count, &nid, &nixm, &nixs, &nhx) + : NULL; + if (pass == 0 && !nb) pass = 1; + if (!nb) { + nb = dom_blk_new(fresh_count, true); + if (!nb) { ok = false; break; } + nb->end = map_size; + size_t o = 12; + dom_src_t src; + if (!dom_src_open(&src, d->path, &nid, map_size)) src = dom_src_map(nbase, map_size); + bool walked = dom_blk_walk_src(&src, nb, 0, &o, NULL) && o == map_size; + dom_src_close(&src); + if (!walked) { ray_sys_free(nb); nb = NULL; ok = false; break; } + } + from_ix = pass == 0; + bool good = true; + if (d->base_count > 0) { + int64_t full = d->base_count / DOM_IX_STRIDE; + good = map_size >= d->map_size; + for (int64_t k = 0; good && k < full; k++) + good = nb->ib[k].off == ob->ib[k].off && dom_blk_lim(nb, k) == dom_blk_lim(ob, k) && + memcmp(nb->ib[k].len, ob->ib[k].len, sizeof(nb->ib[k].len)) == 0; + for (int64_t i = full * DOM_IX_STRIDE; good && i < d->base_count; i++) + good = nb->ib[full].len[i - full * DOM_IX_STRIDE] == ob->ib[full].len[i - full * DOM_IX_STRIDE]; + if (good && full < ob->n) { + uint64_t at = ob->ib[full].off; + good = at <= d->map_size && at <= map_size && nb->ib[full].off == at && + memcmp(nbase + at, obase + at, d->map_size - (size_t)at) == 0; + } + if (good) { + size_t hb = d->map_size - 12 < DOM_IX_HEAD ? d->map_size - 12 : DOM_IX_HEAD; + good = memcmp(nbase + 12, obase + 12, hb) == 0; + } + } + /* the entries this process flushed past the mapping, in order */ + size_t ro = d->base_count > 0 ? d->map_size : 12; + for (int64_t i = d->base_count; good && i < count; i++) { + ray_t* a = dom_slot_get(cur, i); + good = a && (i % DOM_IX_STRIDE || nb->ib[i / DOM_IX_STRIDE].off == ro) && + map_size - ro >= 4; + uint32_t nl = good ? dom_rd32(nbase + ro) : 0; + good = good && (size_t)nl <= map_size - ro - 4 && nl == ray_str_len(a) && + (nl == 0 || memcmp(nbase + ro + 4, ray_str_ptr(a), nl) == 0); + ro += 4 + (size_t)nl; + } + if (good) break; + ray_sys_free(nb); + nb = NULL; + if (nixm) { ray_vm_unmap_file(nixm, nixs); nixm = NULL; } + if (pass == 1) ok = false; } - #undef DOM_REC if (ok && fresh_count > count) { - /* Publish the grown vocabulary. Build a NEW slot array (replace, - * never realloc — lock-free readers may hold the old one): carry the - * already-materialized prefix atoms (arena-owned, still valid; long - * atoms hold their own copy, so swapping the map is safe), new file - * slots start NULL (lazy). */ - ray_t** atoms = atomic_load_explicit(&d->atoms, memory_order_relaxed); - ray_t** narr = (ray_t**)ray_sys_alloc((size_t)fresh_count * sizeof(ray_t*)); + /* Publish the grown vocabulary. A NEW directory (replace, never + * grow in place, so a batch intern probing outside the lock keeps a + * valid one) carries the already-materialized prefix atoms + * (arena-owned, still valid; long atoms hold their own copy, so + * swapping the map is safe); new file slots start NULL (lazy). */ + dom_dir_t* narr = dom_dir_new(fresh_count, cur); if (!narr) { ok = false; - } else if (!dom_retire(d, atoms)) { - ray_sys_free(narr); - ok = false; } else { - if (count > 0) memcpy(narr, atoms, (size_t)count * sizeof(ray_t*)); - for (int64_t i = count; i < fresh_count; i++) narr[i] = NULL; - ray_sys_free(fresh); /* fresh slot array unused — narr carries the prefix */ - - /* Swap in the new offsets + map. Prefix atoms are arena - * copies, but a raw snapshot may still point at the old - * offsets and mapping: retire both instead of freeing. */ - (void)dom_retire(d, d->offsets); - d->offsets = fresh_offsets; + /* Swap in the new checkpoints + map, publish, then let go of + * the superseded generation. Nothing holds it: a reopen runs + * on the calling thread between kernels, and a raw snapshot + * does not survive one (domain.h) -- unless a batch intern is + * probing outside the lock, in which case dom_drop_locked + * retires instead. Retiring until the domain dies here was + * #717: a replica never lets its domain die. */ + dom_blk_t* old_blk = d->blk; + d->blk = nb; + d->map_id = nid; + nb = NULL; + d->ix_used = from_ix; + d->ix_count = from_ix ? nhx.count : 0; + d->ix_end = from_ix ? nhx.end : 0; + d->ix_covered = from_ix ? fresh_count : 0; + if (nixm) { dom_keep_map(d, nixm, nixs); nixm = NULL; } void* old_map = d->map; size_t old_map_size = d->map_size; d->map = map; d->map_size = map_size; d->base_count = fresh_count; + /* every flushed entry is in the mapping now */ + dom_ck_free(&d->wck); atomic_store_explicit(&d->atoms, narr, memory_order_release); - d->atoms_cap = fresh_count; + d->atoms_cap = narr->n << DOM_SLOT_LOG; atomic_store_explicit(&d->count, fresh_count, memory_order_release); d->disk_count = fresh_count; d->disk_size = st_size; - + /* The new snapshot record must be published before the old + * generation goes. When its allocation fails the old record + * stays published and still points at the old checkpoints and + * mapping, so those are retired (valid memory, covering fewer + * positions, as before) rather than freed; the directory is + * referenced by no record and goes either way. */ + bool snap_ok = dom_publish_raw_snap(d, true); + + (void)dom_drop_locked(d, cur); + if (snap_ok) (void)dom_drop_locked(d, old_blk); + else (void)dom_retire(d, old_blk); if (old_map) { - dom_retired_map_t* rm = (dom_retired_map_t*)ray_sys_alloc(sizeof(*rm)); - if (rm) { rm->map = old_map; rm->size = old_map_size; rm->next = d->retired_maps; d->retired_maps = rm; } - /* no rm: the old mapping stays mapped for the process - * lifetime — never unmapped under a live snapshot */ + if (snap_ok && d->batch_inflight == 0) { + ray_vm_unmap_file(old_map, old_map_size); + } else { + dom_retired_map_t* rm = (dom_retired_map_t*)ray_sys_alloc(sizeof(*rm)); + if (rm) { rm->map = old_map; rm->size = old_map_size; rm->next = d->retired_maps; d->retired_maps = rm; } + /* no rm: the old mapping stays mapped for the process + * lifetime — never unmapped under a live snapshot */ + } } - (void)dom_publish_raw_snap(d); /* Reverse index + LUT now cover a stale prefix: drop both. - * A retire-OOM here would keep the stale LUT published over - * the grown count (OOB reads for lock-free consumers) — the - * same corner dom_append_locked hits; mirror its loud abort - * (the count is already published, there is no clean undo). */ + * A retire-OOM here (batch in flight) would keep the stale LUT + * published over the grown count (OOB reads for lock-free + * consumers) — the same corner dom_append_locked hits; mirror + * its loud abort (the count is already published, there is no + * clean undo). */ if (d->buckets) { - /* A batch intern may be probing a snapshot of this - * table outside the lock. */ if (!dom_drop_buckets_locked(d, d->buckets)) { fprintf(stderr, "rayforce: sym domain '%s': OOM retiring " "reverse index after external extend\n", @@ -566,28 +1500,115 @@ static bool dom_extend_from_file_locked(ray_sym_domain_t* d, size_t st_size) { } int64_t* lut = atomic_load_explicit(&d->runtime_lut, memory_order_relaxed); if (lut) { - if (!dom_retire(d, lut)) { + atomic_store_explicit(&d->runtime_lut, NULL, memory_order_release); + if (!dom_drop_locked(d, lut)) { fprintf(stderr, "rayforce: sym domain '%s': OOM retiring " "runtime LUT after external extend — cannot " "keep id translation consistent\n", d->path ? d->path : "?"); abort(); } - atomic_store_explicit(&d->runtime_lut, NULL, memory_order_release); } return true; } } /* Failure, or nothing actually new (size-only change): drop the fresh - * parse and the new mapping; keep the existing image. */ + * table and the new mapping; keep the existing image. */ if (ok && fresh_count == count) d->disk_size = st_size; - ray_sys_free(fresh); - ray_sys_free(fresh_offsets); + ray_sys_free(nb); + if (nixm) ray_vm_unmap_file(nixm, nixs); ray_vm_unmap_file(map, map_size); return ok; } +/* ---- preload ---- + * A symbol file the memory holds with room to spare is read whole when its + * table opens (ray_sym_domain_preload): the pool's workers read it in + * DOM_PL_CHUNK pieces, many requests in flight, so the page cache holds it + * before the first query and the query's reads of the mapping are minor + * faults. A storage request takes its latency however fast the device is, + * so one sequential stream reads at a fraction of its throughput. A file + * left out stays lazy (read by the faults of the queries that touch it). + * The kernel still evicts these pages under pressure; the lazy path then + * reads them again. */ +#define DOM_PL_CHUNK ((size_t)8 << 20) +#define DOM_PL_MIN ((size_t)1 << 20) /* smaller files: their faults are cheap */ +static _Atomic(int64_t) g_dom_preloaded; /* bytes of the open domains read at open */ + +typedef struct { + int fd; + size_t size; +} dom_pl_ctx_t; + +static void dom_preload_fn(void* raw, uint32_t wid, int64_t c0, int64_t c1) { + (void)wid; + const dom_pl_ctx_t* x = (const dom_pl_ctx_t*)raw; + uint8_t* buf = (uint8_t*)ray_sys_alloc(DOM_PL_CHUNK); + if (!buf) return; /* the pages stay lazy */ + for (int64_t c = c0; c < c1; c++) { + size_t off = (size_t)c * DOM_PL_CHUNK; + size_t n = x->size - off < DOM_PL_CHUNK ? x->size - off : DOM_PL_CHUNK; + for (size_t got = 0; got < n;) { + ssize_t r = pread(x->fd, buf + got, n - got, (off_t)(off + got)); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) break; + got += (size_t)r; + } + } + ray_sys_free(buf); +} + +void ray_sym_domain_preload(ray_sym_domain_t* d, int64_t headroom) { +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) + if (!d || d->kind != DOM_FILE || d->preloaded) return; + size_t size = d->map_size; + if (!d->map || size < DOM_PL_MIN) return; + const char* e = getenv("RAY_SYM_PRELOAD"); + int mode = (e && *e) ? atoi(e) : -1; /* -1: by the memory left; 0 never; 1 always */ + if (mode == 0) return; + bool trace = getenv("RAY_SYM_TRACE") != NULL; + int64_t lim = ray_sys_ram_limit(); + int64_t anon = ray_heap_anon_committed(); + int64_t had = atomic_fetch_add_explicit(&g_dom_preloaded, (int64_t)size, memory_order_relaxed); + int64_t left = lim - anon - had - (int64_t)size; + if (mode < 0 && (lim <= 0 || left < headroom)) { + atomic_fetch_sub_explicit(&g_dom_preloaded, (int64_t)size, memory_order_relaxed); + if (trace) + fprintf(stderr, "sym preload %s: lazy (%zu B; would leave %lld B, needs %lld B)\n", + d->path, size, (long long)left, (long long)headroom); + return; + } + int fd = open(d->path, O_RDONLY | O_CLOEXEC); + if (fd < 0) { + atomic_fetch_sub_explicit(&g_dom_preloaded, (int64_t)size, memory_order_relaxed); + return; + } + d->preloaded = size; + int64_t t0 = trace ? ray_profile_now_ns() : 0; + dom_pl_ctx_t x = { fd, size }; + int64_t nc = (int64_t)((size + DOM_PL_CHUNK - 1) / DOM_PL_CHUNK); + ray_pool_t* pool = ray_pool_get(); + if (ray_pool_par_dispatch_ok(pool, nc, 2)) + ray_pool_dispatch_n(pool, dom_preload_fn, &x, (uint32_t)nc); + else + dom_preload_fn(&x, 0, 0, nc); + close(fd); + if (trace) + fprintf(stderr, "sym preload %s: read %zu B in %.2f s (leaves %lld B, needs %lld B)\n", + d->path, size, (double)(ray_profile_now_ns() - t0) / 1e9, + (long long)left, (long long)headroom); +#else + (void)d; (void)headroom; +#endif +} + +static void dom_preload_release(ray_sym_domain_t* d) { + if (d->preloaded) + atomic_fetch_sub_explicit(&g_dom_preloaded, (int64_t)d->preloaded, memory_order_relaxed); + d->preloaded = 0; +} + static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { if (!path) return NULL; @@ -632,44 +1653,46 @@ static ray_sym_domain_t* dom_open_impl(const char* path, bool create) { atomic_store_explicit(&d->raw_snap, NULL, memory_order_relaxed); d->retired_maps = NULL; d->path = rpath; + d->rec0 = 12; /* String atoms (lazy file slots + runtime-appended interns) live here, * off the per-thread buddy heap. 64 KB chunks. */ d->arena = ray_arena_new(64 * 1024); if (!d->arena) { ray_sys_free(d); ray_sys_free(rpath); return NULL; } if (exists) { - d->map = ray_vm_map_file(rpath, &d->map_size); - ray_t** atoms = NULL; - size_t* offsets = NULL; - int64_t count = 0; - if (!d->map || - !dom_parse_strl_atoms(d->map, d->map_size, &atoms, &offsets, &count)) { + /* Mapped, not read: the records are reached through checkpoints + * (the sparse record index above), from the index file when it is + * valid, so opening reads only the index and the records after it. */ + d->map = ray_vm_map_file_id(rpath, &d->map_size, &d->map_id); + int64_t count = -1; + const uint8_t* m = (const uint8_t*)d->map; + if (m && d->map_size >= 12 && dom_rd32(m) == DOMAIN_STRL_MAGIC) + memcpy(&count, m + 4, 8); + if (m && d->map_size >= DOM_Z_REC0 && dom_rd32(m) == DOMAIN_STRZ_MAGIC) { + /* a compressed file: its symbol table (and the encoder's index, + * for appends) is copied out of the header */ + d->z = (ray_fsst_table_t*)ray_sys_alloc(sizeof(ray_fsst_table_t)); + d->zix = (ray_fsst_index_t*)ray_sys_alloc(sizeof(ray_fsst_index_t)); + if (d->z && d->zix) { + memcpy(d->z, m + 12, DOM_Z_TAB); + ray_fsst_index_build(d->z, d->zix); + d->rec0 = DOM_Z_REC0; + memcpy(&count, m + 4, 8); + } + } + if (count < 0 || count > (int64_t)UINT32_MAX || !dom_index_image(d, count)) { dom_destroy(d); return NULL; } - atomic_store_explicit(&d->atoms, atoms, memory_order_relaxed); + dom_dir_t* dir = count > 0 ? dom_dir_new(count, NULL) : NULL; + if (count > 0 && !dir) { dom_destroy(d); return NULL; } + atomic_store_explicit(&d->atoms, dir, memory_order_relaxed); atomic_store_explicit(&d->count, count, memory_order_relaxed); - d->offsets = offsets; - d->atoms_cap = count; + d->atoms_cap = dir ? dir->n << DOM_SLOT_LOG : 0; d->base_count = count; - (void)dom_publish_raw_snap(d); + (void)dom_publish_raw_snap(d, false); d->disk_count = count; d->disk_size = d->map_size; - /* Position-0 reservation: every non-empty symfile must carry the - * empty string at position 0 (mirrors global id 0 — the SYM - * null; group kernels and null conventions treat id 0 as "" / - * null). A vocabulary that starts with anything else is - * structurally corrupt for domain use. Empty files are fine. - * Check the file bytes directly (slen at offsets[0] must be 0) — - * no atom materialization needed. */ - if (count > 0) { - uint32_t l0; - memcpy(&l0, (const uint8_t*)d->map + offsets[0], 4); - if (l0 != 0) { - dom_destroy(d); - return NULL; - } - } } /* create && !exists: empty domain — vocabulary appears via intern * ("" seeded at position 0) and reaches disk on first flush. */ @@ -729,6 +1752,7 @@ ray_sym_domain_t* ray_sym_domain_new(void) { if (!d) return NULL; d->kind = DOM_FILE; d->rc = 1; + d->rec0 = 12; atomic_store_explicit(&d->raw_snap, NULL, memory_order_relaxed); d->arena = ray_arena_new(64 * 1024); if (!d->arena) { ray_sys_free(d); return NULL; } @@ -765,17 +1789,19 @@ ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos) { if (dom->kind == DOM_RUNTIME) return ray_sym_str(pos); if (dom->kind == DOM_IMPORT) return NULL; - /* Lock-free fast path: acquire the published count, then the array, then - * the slot. Appends release-publish the count after the slot write; - * array replacements are release-published before the count bump and old - * arrays are retired (valid memory) — a reader can never index a - * published position into memory that lacks it. A NULL slot is an - * unmaterialized lazy file entry: fall to the lock-held materialize. */ + /* Lock-free fast path: acquire the published count, then the directory, + * then the chunk and the slot. Appends release-publish the count after + * the slot write; directory replacements are release-published before + * the count bump, and an append retires the old directory (valid memory) + * — a reader can never index a published position into memory that + * lacks it. An external extend frees the old directory instead: no + * reader runs during a reopen (see the concurrency note at the top of + * the file). A NULL slot is an unmaterialized lazy file entry (or one + * whose chunk this directory has not seen): fall to the lock-held + * materialize. */ int64_t count = atomic_load_explicit(&dom->count, memory_order_acquire); if (pos < 0 || pos >= count) return NULL; - ray_t** atoms = atomic_load_explicit(&dom->atoms, memory_order_acquire); - ray_t* a = atomic_load_explicit((_Atomic(ray_t*)*)&atoms[pos], - memory_order_acquire); + ray_t* a = dom_slot_get(atomic_load_explicit(&dom->atoms, memory_order_acquire), pos); if (a) return a; dom_lock(); @@ -789,12 +1815,36 @@ bool ray_sym_domain_raw_pin(ray_sym_domain_t* dom, ray_sym_domain_raw_t* out) { dom_raw_snap_t* snap = atomic_load_explicit(&dom->raw_snap, memory_order_acquire); if (!snap) return false; out->map = snap->map; - out->offsets = snap->offsets; + out->ib = snap->blk->ib; out->count = snap->count; + out->blk = snap->blk; + out->dom = dom; + out->z = dom->z; return true; } + +int64_t ray_sym_domain_strlen(ray_sym_domain_t* dom, int64_t pos) { + if (!dom || pos < 0) return -1; + ray_sym_domain_raw_t r; + if (dom->kind == DOM_FILE && ray_sym_domain_raw_pin(dom, &r) && pos < r.count) + return ray_sym_domain_raw_len(&r, pos); + ray_t* s = ray_sym_domain_str(dom, pos); + return s ? (int64_t)ray_str_len(s) : -1; +} + +bool ray_sym_domain_ix_info(ray_sym_domain_t* dom, ray_sym_domain_ix_info_t* out) { + if (!dom || !out || dom->kind != DOM_FILE) return false; + dom_lock(); + out->from_index = dom->ix_used; + out->lens_mapped = dom->blk && dom->blk->ib && !dom->blk->own_ib; + out->covered = dom->ix_covered; + dom_unlock(); + return true; +} + void ray_sym_domain_raw_unpin(ray_sym_domain_t* dom) { - (void)dom; /* the snapshot outlives its readers by construction */ + (void)dom; /* the snapshot outlives its readers by contract: no pin + * across a reopen (domain.h, ray_sym_domain_raw_pin) */ } /* Empty-vocabulary FILE domains get a distinct non-NULL LUT so callers * can branch on NULL == "runtime domain, ids pass through". Never @@ -820,13 +1870,18 @@ const int64_t* ray_sym_domain_runtime_lut(ray_sym_domain_t* dom) { if (!lut) { dom_unlock(); return NULL; } /* THE sanctioned interning of a file vocabulary into the global * table: one sequential pass over the VOCABULARY (never the - * rows). Callers that hand ids to ray_pool_dispatch workers + * rows), straight from the records — no domain atom is made for + * it. Callers that hand ids to ray_pool_dispatch workers * must request this LUT during sequential setup — interning * inside a worker violates sym.c's frozen-table rule. */ + size_t off = dom->rec0; for (int64_t i = 0; i < count; i++) { - ray_t* a = dom_atom_at_locked(dom, i); - if (!a) { ray_sys_free(lut); dom_unlock(); return NULL; } - lut[i] = ray_sym_intern(ray_str_ptr(a), ray_str_len(a)); + const char* p = NULL; + size_t l = 0; + if (!dom_next_locked(dom, i, &off, &p, &l)) { + ray_sys_free(lut); dom_unlock(); return NULL; + } + lut[i] = ray_sym_intern(p, l); if (lut[i] < 0) { /* 7a-review hardening: never publish a LUT carrying -1 * intern failures — a silent -1 makes cross-domain keys @@ -868,10 +1923,13 @@ static bool dom_build_index_locked(ray_sym_domain_t* d, int64_t extra) { buckets[slot] = e; } } else { + /* One pass over the records, hashed where they lie: no atom. */ + size_t off = d->rec0; for (int64_t i = 0; i < count; i++) { - ray_t* a = dom_atom_at_locked(d, i); - if (!a) { ray_sys_free(buckets); return false; } - uint32_t h = (uint32_t)ray_hash_bytes(ray_str_ptr(a), ray_str_len(a)); + const char* p = NULL; + size_t l = 0; + if (!dom_next_locked(d, i, &off, &p, &l)) { ray_sys_free(buckets); return false; } + uint32_t h = (uint32_t)ray_hash_bytes(p, l); uint64_t slot = h & mask; while (buckets[slot] != 0) slot = (slot + 1) & mask; buckets[slot] = ((uint64_t)h << 32) | ((uint64_t)(uint32_t)i + 1); @@ -897,9 +1955,9 @@ static int64_t dom_probe_locked(ray_sym_domain_t* d, uint32_t h, uint64_t e = d->buckets[slot]; if ((uint32_t)(e >> 32) == h) { int64_t pos = (int64_t)(uint32_t)e - 1; - ray_t* a = dom_atom_at_locked(d, pos); - if (a && ray_str_len(a) == len && - (len == 0 || memcmp(ray_str_ptr(a), str, len) == 0)) + size_t l = 0; + const char* p = dom_bytes_locked(d, pos, &l); + if (p && l == len && (len == 0 || memcmp(p, str, len) == 0)) return pos; } slot = (slot + 1) & mask; @@ -945,18 +2003,10 @@ static int64_t dom_append_locked(ray_sym_domain_t* d, uint32_t h, int64_t count = atomic_load_explicit(&d->count, memory_order_relaxed); if (count >= (int64_t)UINT32_MAX) return -1; - /* Grow the published array by REPLACING it — never realloc in place: + /* Grow the published directory by REPLACING it — never in place: * lock-free readers may hold the old pointer. */ - if (count >= d->atoms_cap) { - int64_t ncap = d->atoms_cap < 8 ? 8 : d->atoms_cap * 2; - ray_t** narr = (ray_t**)ray_sys_alloc((size_t)ncap * sizeof(ray_t*)); - if (!narr) return -1; - ray_t** old = atomic_load_explicit(&d->atoms, memory_order_relaxed); - if (count > 0) memcpy(narr, old, (size_t)count * sizeof(ray_t*)); - if (!dom_retire(d, old)) { ray_sys_free(narr); return -1; } - atomic_store_explicit(&d->atoms, narr, memory_order_release); - d->atoms_cap = ncap; - } + if (!dom_grow_locked(d, count + 1)) return -1; + if (!dom_chunk_locked(d, count)) return -1; /* Bucket headroom (rebuild covers everything published so far). */ uint64_t cap = d->bucket_mask + 1; @@ -970,8 +2020,7 @@ static int64_t dom_append_locked(ray_sym_domain_t* d, uint32_t h, ray_t* s = ray_arena_str(d->arena, str, len); if (!s) return -1; - ray_t** atoms = atomic_load_explicit(&d->atoms, memory_order_relaxed); - atoms[count] = s; + (void)dom_slot_set_locked(d, count, s); /* its chunk exists (above) */ atomic_store_explicit(&d->count, count + 1, memory_order_release); uint64_t mask = d->bucket_mask; @@ -1046,7 +2095,7 @@ int64_t ray_sym_domain_intern(ray_sym_domain_t* dom, const char* str, size_t len typedef struct { const uint64_t* buckets; uint64_t mask; - ray_t* const* atoms; + dom_dir_t* atoms; int64_t count; ray_sym_domain_raw_t raw; /* raw.count == 0: no file prefix */ const char* const* strs; @@ -1065,7 +2114,9 @@ typedef struct { int64_t* uoff; /* [total] its byte offset in region */ char* region; /* one arena region for the whole batch */ int64_t base; /* position of new string 0 */ - ray_t** atoms_w; /* current atom array (fill target) */ + dom_dir_t* atoms_w; /* current directory (fill target; chunks made) */ + _Atomic(uint8_t)* done; /* [n_tasks] insert task t finished (parallel commit) */ + int64_t insert_total; /* Set when a probe met an entry it could not compare (no atom, no * raw bytes): the misses are then resolved under the lock instead. */ _Atomic(bool) unsure; @@ -1090,8 +2141,7 @@ static void dom_batch_probe_fn(void* raw, uint32_t wid, int64_t start, int64_t e if (pos < b->count) { const char* p = NULL; size_t l = 0; - ray_t* a = atomic_load_explicit((_Atomic(ray_t*)*)&b->atoms[pos], - memory_order_acquire); + ray_t* a = dom_slot_get(b->atoms, pos); if (a) { p = ray_str_ptr(a); l = ray_str_len(a); } else if (pos < b->raw.count) p = ray_sym_domain_raw_str(&b->raw, pos, &l); else atomic_store_explicit((_Atomic(bool)*)&b->unsure, true, memory_order_relaxed); @@ -1164,7 +2214,9 @@ static void dom_batch_insert_fn(void* raw, uint32_t wid, int64_t k0, int64_t k1) int64_t i = b->ui[k]; int64_t pos = b->base + k; ray_t* s = ray_arena_str_at(b->region + b->uoff[k], b->strs[i], b->lens[i]); - b->atoms_w[pos] = s; + dom_slots_t* c = atomic_load_explicit(&b->atoms_w->c[pos >> DOM_SLOT_LOG], + memory_order_relaxed); + atomic_store_explicit(&c->a[pos & (DOM_SLOTS - 1)], s, memory_order_relaxed); uint32_t h = b->hashes[i]; uint64_t e = ((uint64_t)h << 32) | ((uint64_t)(uint32_t)pos + 1); uint64_t slot = h & b->mask; @@ -1178,6 +2230,24 @@ static void dom_batch_insert_fn(void* raw, uint32_t wid, int64_t k0, int64_t k1) } } +/* The insert in tasks of DOM_INSERT_GRAIN new strings, each flagged done + * when it finishes. A cancelled pool dispatch skips tasks that have not + * started but runs a started one to its end (nothing here polls), so after + * the dispatch every task is either whole or untouched, and the caller + * completes the untouched ones serially: the commit then always publishes + * every string, cancel or not, without a serial pass over all of them. */ +#define DOM_INSERT_GRAIN 4096 +static void dom_batch_insert_task_fn(void* raw, uint32_t wid, int64_t t0, int64_t t1) { + dom_batch_ctx_t* b = (dom_batch_ctx_t*)raw; + for (int64_t t = t0; t < t1; t++) { + int64_t k0 = t * DOM_INSERT_GRAIN; + int64_t k1 = k0 + DOM_INSERT_GRAIN; + if (k1 > b->insert_total) k1 = b->insert_total; + dom_batch_insert_fn(raw, wid, k0, k1); + atomic_store_explicit(&b->done[t], 1, memory_order_release); + } +} + /* A repeated miss takes the position its first occurrence received. */ static void dom_batch_repeat_fn(void* raw, uint32_t wid, int64_t j0, int64_t j1) { (void)wid; @@ -1189,6 +2259,34 @@ static void dom_batch_repeat_fn(void* raw, uint32_t wid, int64_t j0, int64_t j1) } } +/* Whether a pool dispatch issued now would skip tasks: the evaluator's + * interrupt flag, or the pool's own cancel flag (set together by + * ray_request_interrupt; a handler on a worker thread can leave the pool's + * set alone for a moment). */ +static inline bool dom_batch_cancelled(ray_pool_t* pool) { + if (ray_interrupted()) return true; + return pool && atomic_load_explicit(&pool->cancelled, memory_order_relaxed); +} + +#ifdef DEBUG +static _Atomic(int) g_dom_batch_cancel_phase_for_test = 0; + +void ray_sym_domain_batch_cancel_for_test(int phase) { + atomic_store_explicit(&g_dom_batch_cancel_phase_for_test, phase, + memory_order_relaxed); +} + +static void dom_batch_cancel_for_test(int phase) { + int expected = phase; + if (atomic_compare_exchange_strong_explicit( + &g_dom_batch_cancel_phase_for_test, &expected, 0, + memory_order_relaxed, memory_order_relaxed)) + ray_request_interrupt(); +} +#else +#define dom_batch_cancel_for_test(...) ((void)0) +#endif + static bool dom_batch_append_serial_locked(ray_sym_domain_t* dom, int64_t n, const char* const* strs, const size_t* lens, const uint32_t* hashes, int64_t* out_pos) { @@ -1207,6 +2305,7 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, const uint32_t* hashes, int64_t* out_pos) { if (!dom || n < 0) return false; if (n == 0) return true; + if (ray_interrupted()) return false; if (dom->kind == DOM_IMPORT) { /* The import dictionary keys on all 64 bits of the hash, which a * caller of this entry point has dropped: hashed again here @@ -1257,8 +2356,15 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, ray_pool_t* pool = ray_pool_get(); bool par = ray_pool_par_dispatch_ok(pool, n, 4096); + dom_batch_cancel_for_test(RAY_SYM_DOMAIN_CANCEL_PROBE); if (par) ray_pool_dispatch(pool, dom_batch_probe_fn, &b, n); else dom_batch_probe_fn(&b, 0, 0, n); + if (dom_batch_cancelled(pool)) { + dom_lock(); + dom->batch_inflight--; + dom_unlock(); + return false; + } /* Misses, grouped by hash partition: no more partitions than workers*4 * or than the batch fills with a few thousand misses each. Every @@ -1312,13 +2418,33 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, b.tab_off[n_part] = tcap; b.tab = (int64_t*)ray_sys_alloc((size_t)(tcap > 0 ? tcap : 1) * sizeof(int64_t)); if (!b.tab) ok = false; - else if (par) ray_pool_dispatch_n(pool, dom_batch_dedupe_fn, &b, (uint32_t)n_part); - else dom_batch_dedupe_fn(&b, 0, 0, n_part); + else { + dom_batch_cancel_for_test(RAY_SYM_DOMAIN_CANCEL_DEDUPE); + if (par) ray_pool_dispatch_n(pool, dom_batch_dedupe_fn, &b, (uint32_t)n_part); + else dom_batch_dedupe_fn(&b, 0, 0, n_part); + if (dom_batch_cancelled(pool)) ok = false; + } ray_profile_tick("dom batch: misses deduped"); } dom_lock(); dom->batch_inflight--; /* no probe outside the lock past this point */ + if (dom_batch_cancelled(pool)) { + dom_unlock(); + ray_sys_free(b.miss); + ray_sys_free(b.uniq); + ray_sys_free(b.part_off); + ray_sys_free(b.uniq_n); + ray_sys_free(b.tab_off); + ray_sys_free(b.tab); + return false; + } + /* An external extend meanwhile dropped the reverse index the probe + * read (dom_extend_from_file_locked): everything below, the serial + * fallback included, probes the current vocabulary, so rebuild it + * first; without one there is nothing to fall back to. */ + bool indexed = dom->buckets || dom_build_index_locked(dom, n + 1); + if (!indexed) ok = false; bool unchanged = ok && dom->buckets == b.buckets && atomic_load_explicit(&dom->count, memory_order_relaxed) == b.count && !atomic_load_explicit(&b.unsure, memory_order_relaxed); @@ -1351,23 +2477,13 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, for (int p = 0; p < n_part; p++) total += b.uniq_n[p]; int64_t base = b.count; ok = base + total < (int64_t)UINT32_MAX; - /* Atom array: grow once by replacement (lock-free readers may hold - * the old pointer). */ - if (ok && base + total > dom->atoms_cap) { - int64_t ncap = dom->atoms_cap < 8 ? 8 : dom->atoms_cap; - while (ncap < base + total) ncap *= 2; - ray_t** narr = (ray_t**)ray_sys_alloc((size_t)ncap * sizeof(ray_t*)); - if (!narr) ok = false; - else { - ray_t** old = atomic_load_explicit(&dom->atoms, memory_order_relaxed); - if (base > 0) memcpy(narr, old, (size_t)base * sizeof(ray_t*)); - if (!dom_retire(dom, old)) { ray_sys_free(narr); ok = false; } - else { - atomic_store_explicit(&dom->atoms, narr, memory_order_release); - dom->atoms_cap = ncap; - } - } - } + /* Directory: grow once by replacement (lock-free readers may hold + * the old pointer), and make the chunks the new slots fall in, so + * the insert tasks only store into them. */ + if (ok) ok = dom_grow_locked(dom, base + total); + for (int64_t k = base >> DOM_SLOT_LOG; + ok && total > 0 && k <= (base + total - 1) >> DOM_SLOT_LOG; k++) + ok = dom_chunk_locked(dom, k << DOM_SLOT_LOG) != NULL; if (ok && total > 0) { b.ui = (int64_t*)ray_sys_alloc((size_t)total * 2 * sizeof(int64_t)); if (!b.ui) ok = false; @@ -1397,14 +2513,40 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, if (ok) { b.base = base; b.atoms_w = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + /* The commit is not interruptible: once bucket and atom + * publication starts, a partial insert cannot be rolled + * back. It still runs in parallel: a cancel arriving now + * makes the dispatch skip tasks, and every skipped task is + * run here afterwards (dom_batch_insert_task_fn), so the + * publication is whole either way. The repeat pass is + * idempotent and simply re-runs serially after a cancel. */ + dom_batch_cancel_for_test(RAY_SYM_DOMAIN_CANCEL_INSERT); if (total > 0) { - if (par && ray_pool_par_dispatch_ok(pool, total, 4096)) - ray_pool_dispatch(pool, dom_batch_insert_fn, &b, total); - else dom_batch_insert_fn(&b, 0, 0, total); + int64_t n_tasks = (total + DOM_INSERT_GRAIN - 1) / DOM_INSERT_GRAIN; + b.insert_total = total; + void* done_mem = NULL; + if (par && ray_pool_par_dispatch_ok(pool, total, DOM_INSERT_GRAIN) && + n_tasks <= RAY_POOL_MAX_TASKS) + done_mem = ray_sys_alloc((size_t)n_tasks); + b.done = done_mem; + if (done_mem) { + memset(done_mem, 0, (size_t)n_tasks); + ray_pool_dispatch_n(pool, dom_batch_insert_task_fn, &b, (uint32_t)n_tasks); + for (int64_t t = 0; t < n_tasks; t++) + if (!atomic_load_explicit(&b.done[t], memory_order_acquire)) + dom_batch_insert_task_fn(&b, 0, t, t + 1); + ray_sys_free(done_mem); + b.done = NULL; + } else { + dom_batch_insert_fn(&b, 0, 0, total); + } } - if (par && ray_pool_par_dispatch_ok(pool, n_miss, 4096)) + if (par && ray_pool_par_dispatch_ok(pool, n_miss, 4096)) { ray_pool_dispatch(pool, dom_batch_repeat_fn, &b, n_miss); - else dom_batch_repeat_fn(&b, 0, 0, n_miss); + if (dom_batch_cancelled(pool)) dom_batch_repeat_fn(&b, 0, 0, n_miss); + } else { + dom_batch_repeat_fn(&b, 0, 0, n_miss); + } ray_profile_tick("dom batch: inserted"); atomic_store_explicit(&dom->count, pos, memory_order_release); /* Same invalidation as dom_append_locked: the runtime LUT @@ -1428,7 +2570,7 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, } else { for (int64_t i = 0; i < n; i++) if (out_pos[i] < -1) out_pos[i] = -1; } - if (!unchanged || !ok) + if (indexed && (!unchanged || !ok)) ok = dom_batch_append_serial_locked(dom, n, strs, lens, hashes, out_pos); dom_unlock(); ray_profile_tick("dom batch: done"); @@ -1473,6 +2615,58 @@ const char* ray_sym_domain_path(ray_sym_domain_t* dom) { /* ---- flush ------------------------------------------------------------------ */ +/* The index file once a flush left the symfile holding `count` entries + * whose records end at byte `end`: the mapped prefix's checkpoints and the + * flushed ones, the prefix's lengths (its table's) and the flushed + * entries' (their atoms'), after every flush of a file large enough — + * appended to the index on disk, at the cost of the records flushed + * (dom_ix_refresh), so a reader never finds an index short of the file. + * Called under the symfile's `.lk` flock. */ +/* The record bytes of an appended string `s`: itself, or of a compressed + * file coded with its table into *buf. NULL on OOM. */ +static const uint8_t* dom_rec_bytes(const ray_sym_domain_t* dom, const char* s, size_t slen, + uint8_t** buf, size_t* cap, size_t* rlen) { + if (!dom->z) { *rlen = slen; return (const uint8_t*)s; } + uint8_t* out = dom_buf_need(buf, cap, 2 * slen + 8); + if (!out) return NULL; + *rlen = (size_t)ray_fsst_encode_ix(dom->z, dom->zix, (const uint8_t*)s, (uint32_t)slen, out); + return out; +} + +static void dom_flush_index(ray_sym_domain_t* dom, int64_t count, uint64_t end) { + dom_lock(); + bool want = end >= dom_ix_min(); + int64_t nb = dom->blk ? dom->blk->n : 0, n = nb + dom->wck.n; + int64_t base = dom->base_count; + const dom_ixb_t* bl = dom->blk ? dom->blk->ib : NULL; /* stays mapped or retired, never freed */ + uint64_t* all = want && n == dom_ck_count(count) && (base == 0 || bl) + ? (uint64_t*)ray_sys_alloc((size_t)n * sizeof(uint64_t)) : NULL; + uint16_t* tl = all && count > base ? (uint16_t*)ray_sys_alloc((size_t)(count - base) * 2) : NULL; + if (all && count > base && !tl) { ray_sys_free(all); all = NULL; } + if (all) { + for (int64_t k = 0; k < nb; k++) all[k] = dom->blk->ib[k].off; + if (dom->wck.n) memcpy(all + nb, dom->wck.v, (size_t)dom->wck.n * sizeof(uint64_t)); + dom_dir_t* dir = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + for (int64_t i = base; i < count; i++) { + ray_t* a = dom_slot_get(dir, i); + size_t l = a ? ray_str_len(a) : 0; + tl[i - base] = l < DOM_LEN_LONG ? (uint16_t)l : (uint16_t)DOM_LEN_LONG; + } + } + int64_t ixc = dom->ix_count; + uint64_t ixe = dom->ix_end; + dom_unlock(); + if (!all) return; + dom_lsrc_t ls = { bl, base, tl }; + dom_ix_refresh(dom->path, all, n, &ls, count, end, ixc, ixe, true); + ray_sys_free(all); + ray_sys_free(tl); + dom_lock(); + dom->ix_count = count; + dom->ix_end = end; + dom_unlock(); +} + ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { if (!dom) return RAY_ERR_TYPE; if (dom->kind == DOM_RUNTIME) return RAY_OK; /* sym.c owns its own files */ @@ -1480,21 +2674,9 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { if (!dom->path) return RAY_ERR_DOMAIN; dom_lock(); - int64_t count = atomic_load_explicit(&dom->count, memory_order_relaxed); - int64_t disk_count = dom->disk_count; - size_t disk_size = dom->disk_size; - /* Materialize every slot under the lock so the lock-free snapshot below - * has no NULL (lazy) entries to write. The atoms are arena-owned, so - * once materialized they stay valid for the rest of this call. */ - if (count != disk_count) { - for (int64_t i = 0; i < count; i++) { - if (!dom_atom_at_locked(dom, i)) { dom_unlock(); return RAY_ERR_OOM; } - } - } - ray_t** atoms = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + bool dirty = atomic_load_explicit(&dom->count, memory_order_relaxed) != dom->disk_count; dom_unlock(); - - if (count == disk_count) return RAY_OK; /* nothing new */ + if (!dirty) return RAY_OK; /* nothing new */ char lock_path[1024]; char tmp_path[1024]; @@ -1509,6 +2691,26 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { ray_err_t err = ray_file_lock_ex(lock_fd); if (err != RAY_OK) { ray_file_close(lock_fd); return err; } + /* What to write, read under the flock: no other flush of this file runs + * now, and while this process holds unflushed entries no reopen + * replaces the mapping (dom_extend_from_file_locked refuses a dirty + * domain). The mapped prefix is written from its records, the rest + * from the appended atoms (never NULL). */ + dom_lock(); + int64_t count = atomic_load_explicit(&dom->count, memory_order_relaxed); + int64_t disk_count = dom->disk_count; + size_t disk_size = dom->disk_size; + int64_t base_count = dom->base_count; + const uint8_t* bmap = (const uint8_t*)dom->map; + size_t bsize = dom->map_size; + dom_dir_t* dir = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + dom_unlock(); + if (count == disk_count) { + ray_file_unlock(lock_fd); + ray_file_close(lock_fd); + return RAY_OK; + } + /* Verify-base-unchanged: the file on disk must be EXACTLY what this * object last persisted (size + header count). In-memory interning * assigns positions speculatively, so any divergence means a second @@ -1522,6 +2724,9 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { ray_file_close(lock_fd); return RAY_ERR_CORRUPT; /* concurrent writer created it */ } + /* a new file: an index left by an earlier one under this name + * describes nothing in it */ + ray_sym_domain_index_remove(dom->path); } else { bool ok = exists && (size_t)st.st_size == disk_size; if (ok) { @@ -1530,7 +2735,8 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { int64_t fcount = -1; if (!vf || fread(&magic, 4, 1, vf) != 1 || fread(&fcount, 8, 1, vf) != 1 || - magic != DOMAIN_STRL_MAGIC || fcount != disk_count) + magic != (dom->z ? DOMAIN_STRZ_MAGIC : DOMAIN_STRL_MAGIC) || + fcount != disk_count) ok = false; if (vf) fclose(vf); } @@ -1542,8 +2748,9 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { } } - /* Write base + tail to tmp. */ + /* Write base + tail to tmp, noting the checkpoints of the tail. */ size_t written_size = 0; + dom_ck_t tail = {0}; { FILE* f = fopen(tmp_path, "wb"); if (!f) { @@ -1551,21 +2758,35 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { ray_file_close(lock_fd); return RAY_ERR_IO; } - uint32_t magic = DOMAIN_STRL_MAGIC; + /* a compressed file keeps its header (the symbol table) and codes + * the new records with it */ + uint32_t magic = dom->z && base_count > 0 ? DOMAIN_STRZ_MAGIC : DOMAIN_STRL_MAGIC; err = RAY_OK; if (fwrite(&magic, 4, 1, f) != 1 || fwrite(&count, 8, 1, f) != 1) err = RAY_ERR_IO; written_size = 12; + if (err == RAY_OK && base_count > 0) { + if (fwrite(bmap + 12, 1, bsize - 12, f) != bsize - 12) err = RAY_ERR_IO; + written_size = bsize; + } /* Records are packed into a large buffer first: two stdio calls per * entry dominated the flush of a big vocabulary. */ enum { FLUSH_BUF = 1u << 20 }; uint8_t* wb = (uint8_t*)ray_sys_alloc(FLUSH_BUF); - size_t wn = 0; + uint8_t* zb = NULL; + size_t zc = 0, wn = 0; if (!wb) err = RAY_ERR_OOM; - for (int64_t i = 0; err == RAY_OK && i < count; i++) { - ray_t* s = atoms[i]; + for (int64_t i = base_count; err == RAY_OK && i < count; i++) { + ray_t* s = dom_slot_get(dir, i); + if (!s) { err = RAY_ERR_CORRUPT; break; } + if (!(i % DOM_IX_STRIDE) && !dom_ck_push(&tail, written_size)) { + err = RAY_ERR_OOM; + break; + } size_t slen = ray_str_len(s); if (slen > UINT32_MAX) { err = RAY_ERR_RANGE; break; } + const uint8_t* rb = dom_rec_bytes(dom, ray_str_ptr(s), slen, &zb, &zc, &slen); + if (!rb) { err = RAY_ERR_OOM; break; } uint32_t len32 = (uint32_t)slen; if (wn + 4 + slen > FLUSH_BUF) { if (wn && fwrite(wb, 1, wn, f) != wn) { err = RAY_ERR_IO; break; } @@ -1574,19 +2795,20 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { if (4 + slen > FLUSH_BUF) { /* Oversized record: straight through. */ if (fwrite(&len32, 4, 1, f) != 1 || - fwrite(ray_str_ptr(s), 1, slen, f) != slen) { + fwrite(rb, 1, slen, f) != slen) { err = RAY_ERR_IO; break; } } else { memcpy(wb + wn, &len32, 4); - if (slen) memcpy(wb + wn + 4, ray_str_ptr(s), slen); + if (slen) memcpy(wb + wn + 4, rb, slen); wn += 4 + slen; } written_size += 4 + slen; } if (err == RAY_OK && wn && fwrite(wb, 1, wn, f) != wn) err = RAY_ERR_IO; ray_sys_free(wb); + ray_sys_free(zb); if (fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; } if (err != RAY_OK) goto fail_tmp; @@ -1602,6 +2824,14 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { err = ray_file_rename(tmp_path, dom->path); if (err != RAY_OK) goto fail_tmp; + dom_lock(); + dom->disk_count = count; + dom->disk_size = written_size; + dom_ck_free(&dom->wck); + dom->wck = tail; + dom_unlock(); + tail.v = NULL; + if (durable) { err = ray_file_sync_dir(dom->path); if (err != RAY_OK) { @@ -1611,16 +2841,13 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable) { } } - dom_lock(); - dom->disk_count = count; - dom->disk_size = written_size; - dom_unlock(); - + dom_flush_index(dom, count, written_size); ray_file_unlock(lock_fd); ray_file_close(lock_fd); return RAY_OK; fail_tmp: + dom_ck_free(&tail); remove(tmp_path); ray_file_unlock(lock_fd); ray_file_close(lock_fd); @@ -1642,17 +2869,9 @@ ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable) { if (!dom->path) return RAY_ERR_DOMAIN; dom_lock(); - int64_t count = atomic_load_explicit(&dom->count, memory_order_relaxed); - int64_t disk_count = dom->disk_count; - size_t disk_size = dom->disk_size; - /* Only the entries past the persisted prefix are written: materialize - * those under the lock (arena-owned, they stay valid after it). */ - for (int64_t i = disk_count; i < count; i++) { - if (!dom_atom_at_locked(dom, i)) { dom_unlock(); return RAY_ERR_OOM; } - } - ray_t** atoms = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + bool dirty = atomic_load_explicit(&dom->count, memory_order_relaxed) != dom->disk_count; dom_unlock(); - if (count == disk_count && !durable) return RAY_OK; + if (!dirty && !durable) return RAY_OK; char lock_path[1024]; if (snprintf(lock_path, sizeof(lock_path), "%s.lk", dom->path) >= (int)sizeof(lock_path)) @@ -1663,6 +2882,20 @@ ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable) { ray_err_t err = ray_file_lock_ex(lock_fd); if (err != RAY_OK) { ray_file_close(lock_fd); return err; } + /* Only the entries past the persisted prefix are written: appended + * atoms (never NULL), read under the flock as in ray_sym_domain_flush. */ + dom_lock(); + int64_t count = atomic_load_explicit(&dom->count, memory_order_relaxed); + int64_t disk_count = dom->disk_count; + size_t disk_size = dom->disk_size; + dom_dir_t* dir = atomic_load_explicit(&dom->atoms, memory_order_relaxed); + dom_unlock(); + if (count == disk_count && !durable) { + ray_file_unlock(lock_fd); + ray_file_close(lock_fd); + return RAY_OK; + } + /* The file must still be the persisted size: anything else is another * writer. */ struct stat st; @@ -1673,6 +2906,7 @@ ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable) { ray_file_close(lock_fd); return RAY_ERR_CORRUPT; } + if (disk_count == 0) ray_sym_domain_index_remove(dom->path); /* a new file */ FILE* f = fopen(dom->path, disk_count == 0 ? "wb+" : "rb+"); if (!f) { ray_file_unlock(lock_fd); ray_file_close(lock_fd); return RAY_ERR_IO; } size_t size = disk_size; @@ -1684,33 +2918,41 @@ ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable) { } else if (!dom_fseek(f, (int64_t)disk_size)) { err = RAY_ERR_IO; } + dom_ck_t tail = {0}; enum { FLUSH_BUF = 1u << 20 }; uint8_t* wb = err == RAY_OK ? (uint8_t*)ray_sys_alloc(FLUSH_BUF) : NULL; - size_t wn = 0; + uint8_t* zb = NULL; + size_t zc = 0, wn = 0; if (err == RAY_OK && !wb) err = RAY_ERR_OOM; for (int64_t i = disk_count; err == RAY_OK && i < count; i++) { - ray_t* s = atoms[i]; + ray_t* s = dom_slot_get(dir, i); + if (!s) { err = RAY_ERR_CORRUPT; break; } + if (!(i % DOM_IX_STRIDE) && !dom_ck_push(&tail, size)) { err = RAY_ERR_OOM; break; } size_t slen = ray_str_len(s); if (slen > UINT32_MAX) { err = RAY_ERR_RANGE; break; } + /* appended to a compressed file: coded with its table */ + const uint8_t* rb = dom_rec_bytes(dom, ray_str_ptr(s), slen, &zb, &zc, &slen); + if (!rb) { err = RAY_ERR_OOM; break; } uint32_t len32 = (uint32_t)slen; if (wn + 4 + slen > FLUSH_BUF) { if (wn && fwrite(wb, 1, wn, f) != wn) { err = RAY_ERR_IO; break; } wn = 0; } if (4 + slen > FLUSH_BUF) { - if (fwrite(&len32, 4, 1, f) != 1 || fwrite(ray_str_ptr(s), 1, slen, f) != slen) { + if (fwrite(&len32, 4, 1, f) != 1 || fwrite(rb, 1, slen, f) != slen) { err = RAY_ERR_IO; break; } } else { memcpy(wb + wn, &len32, 4); - if (slen) memcpy(wb + wn + 4, ray_str_ptr(s), slen); + if (slen) memcpy(wb + wn + 4, rb, slen); wn += 4 + slen; } size += 4 + slen; } if (err == RAY_OK && wn && fwrite(wb, 1, wn, f) != wn) err = RAY_ERR_IO; ray_sys_free(wb); + ray_sys_free(zb); /* the count goes in last, once the records it covers are written */ if (err == RAY_OK && (fflush(f) != 0 || !dom_fseek(f, 4) || fwrite(&count, 8, 1, f) != 1 || fflush(f) != 0)) @@ -1730,13 +2972,205 @@ ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable) { dom_lock(); dom->disk_count = count; dom->disk_size = size; + for (int64_t k = 0; err == RAY_OK && k < tail.n; k++) + if (!dom_ck_push(&dom->wck, tail.v[k])) err = RAY_ERR_OOM; + if (err != RAY_OK) dom_ck_free(&dom->wck); /* no index from here on */ dom_unlock(); + if (err == RAY_OK) dom_flush_index(dom, count, size); + err = RAY_OK; /* the symfile is written; the index is a cache */ } + dom_ck_free(&tail); ray_file_unlock(lock_fd); ray_file_close(lock_fd); return err; } +/* ---- compressing a symfile -------------------------------------------------- */ + +/* One window of the coding pass: chunk c holds the records of blocks + * [k0 + c * cb, k0 + (c + 1) * cb), coded into out[c] (olen[c] bytes), the + * offset of each of its blocks' first record in rel[c][]. */ +typedef struct { + const uint8_t* map; + const dom_ixb_t* ib; + int64_t n, count, k0, cb; + uint64_t end; + const ray_fsst_table_t* t; + const ray_fsst_index_t* ix; + uint8_t** out; + size_t* cap; + size_t* olen; + uint64_t** rel; + _Atomic(bool) oom; +} dom_zc_ctx_t; + +static void dom_zc_chunk_fn(void* vctx, uint32_t wid, int64_t c0, int64_t c1) { + (void)wid; + dom_zc_ctx_t* x = (dom_zc_ctx_t*)vctx; + for (int64_t c = c0; c < c1; c++) { + int64_t ka = x->k0 + c * x->cb, kb = ka + x->cb < x->n ? ka + x->cb : x->n; + uint64_t lo = x->ib[ka].off, hi = kb < x->n ? x->ib[kb].off : x->end; + uint8_t* out = dom_buf_need(&x->out[c], &x->cap[c], 2 * (size_t)(hi - lo) + 16); + if (!out) { atomic_store_explicit(&x->oom, true, memory_order_relaxed); return; } + const uint8_t* p = x->map + lo; + size_t o = 0; + int64_t ie = kb * DOM_IX_STRIDE < x->count ? kb * DOM_IX_STRIDE : x->count; + for (int64_t i = ka * DOM_IX_STRIDE; i < ie; i++) { + if (!(i % DOM_IX_STRIDE)) x->rel[c][i / DOM_IX_STRIDE - ka] = o; + uint32_t l = dom_rd32(p); + uint32_t cl = (uint32_t)ray_fsst_encode_ix(x->t, x->ix, p + 4, l, out + o + 4); + memcpy(out + o, &cl, 4); + o += 4 + cl; + p += 4 + l; + } + x->olen[c] = o; + } +} + +ray_err_t ray_sym_domain_compress(const char* path) { + if (!path) return RAY_ERR_TYPE; + char* rpath = dom_resolve_path(path); + if (!rpath) return RAY_ERR_IO; + /* the file is replaced under its name: no domain may have it open */ + dom_lock(); + for (ray_sym_domain_t* d = g_domains; d; d = d->next) + if (dom_path_eq(d->path, rpath)) { dom_unlock(); ray_sys_free(rpath); return RAY_ERR_DOMAIN; } + dom_unlock(); + + size_t size = 0; + ray_file_id_t id; + const uint8_t* map = (const uint8_t*)ray_vm_map_file_id(rpath, &size, &id); + int64_t count = -1; + if (map && size >= 12 && dom_rd32(map) == DOMAIN_STRL_MAGIC) memcpy(&count, map + 4, 8); + if (count <= 0 || count > (int64_t)UINT32_MAX) { + /* not a plain symfile with entries (a compressed one stays as it is) */ + if (map) ray_vm_unmap_file((void*)map, size); + ray_sys_free(rpath); + return RAY_OK; + } + ray_vm_advise_seq((void*)map, size); + /* the block table: from the file's index, else one walk */ + dom_ixh_t hx; + void* ixm = NULL; + size_t ixs = 0; + dom_blk_t* b = dom_ix_load(rpath, map, size, count, &id, &ixm, &ixs, &hx); + if (!b) { + b = dom_blk_new(count, true); + size_t o = 12; + dom_src_t src; + if (b && !dom_src_open(&src, rpath, &id, size)) src = dom_src_map(map, size); + bool walked = b && dom_blk_walk_src(&src, b, 0, &o, NULL) && o == size; + if (b) dom_src_close(&src); + if (!walked) { + ray_sys_free(b); + ray_vm_unmap_file((void*)map, size); + ray_sys_free(rpath); + return b ? RAY_ERR_IO : RAY_ERR_OOM; + } + b->end = size; + } + ray_err_t err = RAY_OK; + int64_t n = b->n; + + /* the training sample: every record of every sb-th block, some 1 MiB */ + int64_t sb = (int64_t)((size - 12) >> 20); + if (sb < 1) sb = 1; + int64_t sn = 0, scap = ((n + sb - 1) / sb) * DOM_IX_STRIDE; + const uint8_t** sp = (const uint8_t**)ray_sys_alloc((size_t)scap * sizeof(*sp)); + uint32_t* sl = (uint32_t*)ray_sys_alloc((size_t)scap * sizeof(*sl)); + ray_fsst_table_t* t = (ray_fsst_table_t*)ray_sys_alloc(sizeof(*t)); + ray_fsst_index_t* tix = (ray_fsst_index_t*)ray_sys_alloc(sizeof(*tix)); + if (!sp || !sl || !t || !tix) err = RAY_ERR_OOM; + for (int64_t k = 0; err == RAY_OK && k < n; k += sb) { + const uint8_t* p = map + b->ib[k].off; + int64_t ie = (k + 1) * DOM_IX_STRIDE < count ? (k + 1) * DOM_IX_STRIDE : count; + for (int64_t i = k * DOM_IX_STRIDE; i < ie; i++) { + sl[sn] = dom_rd32(p); + sp[sn++] = p + 4; + p += 4 + (size_t)dom_rd32(p); + } + } + int tr = err == RAY_OK ? ray_fsst_train(sp, sl, sn, t) : 0; + ray_sys_free(sp); + ray_sys_free(sl); + if (err == RAY_OK && tr < 0) err = RAY_ERR_OOM; + bool code = err == RAY_OK && tr > 0; /* no table: the file stays plain */ + + char tp[PATH_MAX]; + uint64_t* ck = code ? (uint64_t*)ray_sys_alloc((size_t)n * sizeof(uint64_t)) : NULL; + if (code && (!ck || snprintf(tp, sizeof(tp), "%s.z.%llu.tmp", rpath, dom_pid()) >= (int)sizeof(tp))) + err = ck ? RAY_ERR_IO : RAY_ERR_OOM; + FILE* f = code && err == RAY_OK ? fopen(tp, "wb") : NULL; + if (code && err == RAY_OK && !f) err = RAY_ERR_IO; + uint64_t pos = DOM_Z_REC0; + if (f) { + ray_fsst_index_build(t, tix); + uint32_t magic = DOMAIN_STRZ_MAGIC; + if (fwrite(&magic, 4, 1, f) != 1 || fwrite(&count, 8, 1, f) != 1 || + fwrite(t, 1, DOM_Z_TAB, f) != DOM_Z_TAB) + err = RAY_ERR_IO; + /* windows of chunks of some 2 MiB of records, coded in parallel and + * written in order */ + ray_pool_t* pool = ray_pool_get(); + uint32_t nw = pool ? ray_pool_total_workers(pool) : 1; + int64_t cb = (int64_t)(((uint64_t)(2u << 20) * (uint64_t)n) / (size - 12)); + if (cb < 1) cb = 1; + int64_t wn = 2 * (int64_t)nw < 64 ? 2 * (int64_t)nw : 64; + dom_zc_ctx_t x; + memset(&x, 0, sizeof(x)); + x.map = map; x.ib = b->ib; x.n = n; x.count = count; x.cb = cb; x.end = size; + x.t = t; x.ix = tix; + x.out = (uint8_t**)ray_sys_alloc((size_t)wn * sizeof(uint8_t*)); + x.cap = (size_t*)ray_sys_alloc((size_t)wn * sizeof(size_t)); + x.olen = (size_t*)ray_sys_alloc((size_t)wn * sizeof(size_t)); + x.rel = (uint64_t**)ray_sys_alloc((size_t)wn * sizeof(uint64_t*)); + if (!x.out || !x.cap || !x.olen || !x.rel) err = RAY_ERR_OOM; + for (int64_t c = 0; err == RAY_OK && c < wn; c++) + if (!(x.rel[c] = (uint64_t*)ray_sys_alloc((size_t)cb * sizeof(uint64_t)))) err = RAY_ERR_OOM; + for (int64_t k0 = 0; err == RAY_OK && k0 < n; k0 += wn * cb) { + int64_t nc = (n - k0 + cb - 1) / cb; + if (nc > wn) nc = wn; + x.k0 = k0; + if (pool && nc > 1) ray_pool_dispatch_n(pool, dom_zc_chunk_fn, &x, (uint32_t)nc); + else dom_zc_chunk_fn(&x, 0, 0, nc); + if (atomic_load_explicit(&x.oom, memory_order_relaxed)) { err = RAY_ERR_OOM; break; } + for (int64_t c = 0; c < nc; c++) { + int64_t ka = k0 + c * cb, kb = ka + cb < n ? ka + cb : n; + for (int64_t k = ka; k < kb; k++) ck[k] = pos + x.rel[c][k - ka]; + if (fwrite(x.out[c], 1, x.olen[c], f) != x.olen[c]) { err = RAY_ERR_IO; break; } + pos += x.olen[c]; + } + } + for (int64_t c = 0; x.out && c < wn; c++) ray_sys_free(x.out[c]); + for (int64_t c = 0; x.rel && c < wn; c++) ray_sys_free(x.rel[c]); + ray_sys_free(x.out); ray_sys_free(x.cap); ray_sys_free(x.olen); ray_sys_free(x.rel); + if (fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; + /* the index describes the old file until it is written anew */ + if (err == RAY_OK) ray_sym_domain_index_remove(rpath); + if (err == RAY_OK) err = ray_file_rename(tp, rpath); + if (err != RAY_OK) remove(tp); + } + if (code && err == RAY_OK && pos >= dom_ix_min()) { + size_t zsize = 0; + ray_file_id_t zid; + const uint8_t* zmap = (const uint8_t*)ray_vm_map_file_id(rpath, &zsize, &zid); + if (zmap) { + /* the lengths are the strings', as before: the old table's */ + dom_lsrc_t ls = { b->ib, count, NULL }; + dom_ix_save(rpath, zmap, zsize, ck, n, &ls, count, zsize, &zid); + ray_vm_unmap_file((void*)zmap, zsize); + } + } + ray_sys_free(ck); + ray_sys_free(t); + ray_sys_free(tix); + ray_sys_free(b); + if (ixm) ray_vm_unmap_file(ixm, ixs); + ray_vm_unmap_file((void*)map, size); + ray_sys_free(rpath); + return err; +} + /* ---- RAY_SYM_AUDIT ----------------------------------------------------------- */ /* Cached at ray_sym_init (table/sym.c) from the RAY_SYM_AUDIT env var. */ diff --git a/src/table/domain.h b/src/table/domain.h index 17bd76712..88f5d7f26 100644 --- a/src/table/domain.h +++ b/src/table/domain.h @@ -78,6 +78,9 @@ #include #include +#include +#include +#include #include typedef struct ray_sym_domain_s ray_sym_domain_t; @@ -133,30 +136,130 @@ ray_t* ray_sym_domain_str(ray_sym_domain_t* dom, int64_t pos); /* Raw vocabulary access for a FILE domain: the bytes of the entries the * file holds, read straight from the mapping — no atom, no lock. Pin - * takes an atomically published snapshot of (map, offsets, count); a - * later extend (the symfile grew under another opener) publishes a new - * snapshot and RETIRES the old mapping and offsets until the domain is - * destroyed, so a snapshot stays readable for as long as its holder keeps - * the domain alive — no waiting on either side, no lock order to respect. + * takes an atomically published snapshot of (map, block table, count); an + * entry is found from the checkpoint of its block of RAY_SYM_INDEX_STRIDE + * entries. + * + * LIFETIME: a snapshot stays readable across in-process appends + * (ray_sym_domain_intern, _batch, flush) for as long as its holder keeps + * the domain alive. It does NOT survive a reopen of the same symfile + * after another process grew it (ray_sym_domain_open on a cached path: + * the extend frees the mapping and block table it replaces). Nothing + * counts pins, so this is a rule for callers: never hold a snapshot across + * a call that may reopen (.db.parted.get, splayed reads, + * ray_sym_domain_open), and never reopen from a thread while another runs + * a kernel over the domain. Today every reopen runs on the calling thread + * between kernels. + * * Returns false for the runtime domain or an empty file; the caller then * resolves through ray_sym_domain_str as before. Only positions below * `count` (the file prefix) are readable this way; runtime-appended - * positions keep going through ray_sym_domain_str. Unpin is a no-op kept - * for symmetry. */ + * positions keep going through ray_sym_domain_str. ray_sym_domain_raw_str + * returns NULL (and *len 0) for a position out of range. Unpin is a no-op + * kept for symmetry. + * + * A compressed symfile (each record FSST-coded, see domain.c) has `z` set: + * its strings are decoded into a small ring of buffers of the calling + * thread, so a pointer ray_sym_domain_raw_str returns for it stays valid + * only until that thread's RAY_SYM_RAW_RING-th next read of a compressed + * entry. Enough for a comparison of two entries; a caller that keeps + * pointers longer copies the bytes (or reads their lengths with + * ray_sym_domain_raw_len, which decodes nothing). */ +#define RAY_SYM_INDEX_STRIDE 28 /* entries in a block of the index: 64 bytes with its offset */ +typedef struct { + uint64_t off; /* byte offset of the block's first record */ + uint16_t len[RAY_SYM_INDEX_STRIDE]; /* the entries' string lengths, 65535 = 65535 or longer */ +} ray_sym_ixblk_t; +_Static_assert(sizeof(ray_sym_ixblk_t) == 64, "an index block is one cache line"); +#define RAY_SYM_RAW_RING 4 /* decode buffers per thread for compressed entries */ typedef struct { const unsigned char* map; - const size_t* offsets; + const ray_sym_ixblk_t* ib; /* block k: starts at map + ib[k].off; NULL: none */ int64_t count; + void* blk; /* the domain's block table */ + ray_sym_domain_t* dom; + const void* z; /* the symbol table of a compressed file; NULL: plain */ } ray_sym_domain_raw_t; bool ray_sym_domain_raw_pin(ray_sym_domain_t* dom, ray_sym_domain_raw_t* out); +/* Reads the file of a FILE domain whole into the page cache, in parallel, + * when the memory left after it (the RAM limit less the committed heap and + * the files read so far) is at least `headroom`; else leaves it lazy. Once + * per domain. RAY_SYM_PRELOAD=0 never reads, =1 always; RAY_SYM_TRACE + * prints the decision. */ +void ray_sym_domain_preload(ray_sym_domain_t* dom, int64_t headroom); void ray_sym_domain_raw_unpin(ray_sym_domain_t* dom); +const char* ray_sym_domain_raw_str_z(const ray_sym_domain_raw_t* r, int64_t pos, size_t* len); +/* Entry `pos` (below r->count) of a compressed file decoded into `out`, which + * holds its length (ray_sym_domain_raw_len) and 8 bytes more: a caller that + * keeps the bytes places them itself. */ +void ray_sym_domain_raw_decode(const ray_sym_domain_raw_t* r, int64_t pos, char* out); static inline const char* ray_sym_domain_raw_str(const ray_sym_domain_raw_t* r, int64_t pos, size_t* len) { - const unsigned char* rec = r->map + r->offsets[pos]; - uint32_t l; memcpy(&l, rec, 4); + if (pos < 0 || pos >= r->count || !r->ib) { *len = 0; return NULL; } + if (r->z) return ray_sym_domain_raw_str_z(r, pos, len); + /* past the records before the entry by their lengths (65535: the + * record header's) */ + const int64_t k = pos / RAY_SYM_INDEX_STRIDE; + const unsigned char* p = r->map + r->ib[k].off; + for (int64_t i = k * RAY_SYM_INDEX_STRIDE; i < pos; i++) { + uint32_t l = r->ib[k].len[i - k * RAY_SYM_INDEX_STRIDE]; + if (l == 65535) memcpy(&l, p, 4); + p += 4 + (size_t)l; + } + uint32_t l; memcpy(&l, p, 4); *len = l; - return (const char*)rec + 4; + return (const char*)p + 4; +} +/* The length of entry `pos`'s string (-1 where ray_sym_domain_raw_str would + * give NULL): from its length (2 bytes in the index), without reading the + * record, unless the string is 65535 bytes or longer (the escape) — then + * its record header (4 bytes). For a function of a string's length per + * symbol (strlen per code), so that a vocabulary's lengths are read and + * not its strings. */ +static inline int64_t ray_sym_domain_raw_len(const ray_sym_domain_raw_t* r, int64_t pos) { + if (pos < 0 || pos >= r->count || !r->ib) return -1; + const uint16_t e = r->ib[pos / RAY_SYM_INDEX_STRIDE].len[pos % RAY_SYM_INDEX_STRIDE]; + if (e < 65535) return e; + size_t l = 0; + (void)ray_sym_domain_raw_str(r, pos, &l); + return (int64_t)l; } +/* The same for any domain and position (the appended ones from their atom). */ +int64_t ray_sym_domain_strlen(ray_sym_domain_t* dom, int64_t pos); + +/* What the record index did for a FILE domain, for tests: the open took + * its blocks from the index file (covering `covered` entries), and whether + * the lengths are read from the index file. */ +typedef struct { + bool from_index; /* the open took the table from the index file */ + bool lens_mapped; /* the lengths are read from the index file, as needed */ + int64_t covered; /* entries the index covered */ +} ray_sym_domain_ix_info_t; +bool ray_sym_domain_ix_info(ray_sym_domain_t* dom, ray_sym_domain_ix_info_t* out); + +/* What the record index guarantees, and where it stops (domain.c): + * - An index is taken only for the very file it was written for: the + * inode, the modification and status-change times and the size it + * records match the file mapped. The status-change time cannot be set + * back by a writer, so an in-place rewrite, even with its modification + * time restored, is not taken for the same file. Any other index — + * another file of the name, the file grown or rewritten by a writer + * that left the index as it was, an earlier format — is not used: the + * open walks every record once and writes the index anew. Where the + * platform has no such identity (Windows, WASM) every open walks. + * - The symfile and its index are ours: an index taken is read as + * written, its blocks and the records they name are not checked. */ + +/* The symfile's record index, `.ix` (format in domain.c): written + * by the writers of a symfile so that opening it reads neither the records + * nor their lengths. Save: ckpt[k] is the byte offset of the record of + * entry k * RAY_SYM_INDEX_STRIDE, n = ceil(count / RAY_SYM_INDEX_STRIDE), + * lens[i] the length of entry i's string (65535: 65535 or longer), the first + * `count` records ending at byte `end`; best effort, and a no-op for a small + * file. Remove: before a new file is made under the name. */ +void ray_sym_domain_index_save(const char* path, const uint64_t* ckpt, int64_t n, + const uint16_t* lens, int64_t count, uint64_t end); +void ray_sym_domain_index_remove(const char* path); /* Position of `str` in the domain, or -1 if absent. * FILE: builds the reverse index on first call (O(|vocabulary|)). */ @@ -167,8 +270,10 @@ int64_t ray_sym_domain_find(ray_sym_domain_t* dom, const char* str, size_t len); * RUNTIME: NULL — ids ARE runtime ids, callers use them as-is. * FILE: `count` entries, lut[pos] = ray_sym_intern(vocab[pos]); * built ONCE on first request (double-checked under the - * domain lock, atomically published), then lock-free reads - * for the domain's lifetime. + * domain lock, atomically published), then lock-free reads. + * Invalidated by growth: an append retires it (the pointer + * stays valid memory), a reopen after external growth frees + * it — same rule as a raw snapshot, see ray_sym_domain_raw_pin. * * Building the LUT INTERNS the whole vocabulary into the global table — * the sanctioned, SEQUENTIAL one-time cost of crossing a FILE domain @@ -196,6 +301,14 @@ int64_t ray_sym_domain_intern(ray_sym_domain_t* dom, const char* str, size_t len bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, const char* const* strs, const size_t* lens, const uint32_t* hashes, int64_t* out_pos); +#ifdef DEBUG +enum { + RAY_SYM_DOMAIN_CANCEL_PROBE = 1, + RAY_SYM_DOMAIN_CANCEL_DEDUPE = 2, + RAY_SYM_DOMAIN_CANCEL_INSERT = 3 /* before the commit's insert dispatch */ +}; +void ray_sym_domain_batch_cancel_for_test(int phase); +#endif /* The same with hashes[i] = ray_hash_bytes of strs[i], all 64 bits: the * import dictionary keys on them (the 32-bit entry point hashes its strings * again for it); the other domains take their low 32 bits. */ @@ -227,6 +340,16 @@ ray_err_t ray_sym_domain_flush(ray_sym_domain_t* dom, bool durable); * was interned. */ ray_err_t ray_sym_domain_flush_append(ray_sym_domain_t* dom, bool durable); +/* Rewrite the plain symfile at `path` compressed: each string coded with an + * FSST symbol table trained on a sample of them (domain.c, "STRZ"), the + * positions, lengths and index kept. For a file written whole and read + * after, such as one column's vocabulary: reads of an entry then decode it + * (ray_sym_domain_raw_str), and the file and the memory it takes when read + * shrink. No domain may have the file open (RAY_ERR_DOMAIN). A file with + * no entries, one already compressed or one no table helps stays as it is + * (RAY_OK). */ +ray_err_t ray_sym_domain_compress(const char* path); + /* RAY_SYM_AUDIT=1 support (cached at ray_sym_init): when set, * ray_sym_vec_cell cross-checks every resolution and aborts with full * context on an invariant violation (unresolvable atom / position out diff --git a/src/table/sym.c b/src/table/sym.c index cd1e5fde4..a662e4b2e 100644 --- a/src/table/sym.c +++ b/src/table/sym.c @@ -22,6 +22,7 @@ */ #include "sym.h" +#include "domain.h" /* ray_sym_domain_index_remove */ #include "core/platform.h" #include "store/fileio.h" #include "mem/heap.h" @@ -93,16 +94,28 @@ static sym_table_t g_sym; static _Atomic(bool) g_sym_inited = false; static bool sym_lazy_materialize_to_locked(uint32_t target_id); -/* Spinlock protecting g_sym mutations in ray_sym_intern */ -static _Atomic(int) g_sym_lock = 0; +/* Spinlock protecting g_sym mutations in ray_sym_intern. On its own + * 64-byte line: ray_sym_str takes it per call, and a lock sharing a line + * with g_sym or g_sym_inited turns every acquire into an invalidation of + * the line every reader needs (Ruling 8-2: a .bss shift of 0x20 gave + * generation-0 q29 1.365x). */ +static struct { + _Alignas(64) _Atomic(int) v; + char pad[64 - sizeof(_Atomic(int))]; +} g_sym_lock_line; +_Static_assert(sizeof(g_sym_lock_line) == 64, "the symbol lock fills its line"); static inline void sym_lock(void) { - while (atomic_exchange_explicit(&g_sym_lock, 1, memory_order_acquire)) { + while (atomic_exchange_explicit(&g_sym_lock_line.v, 1, memory_order_acquire)) { RAY_CPU_RELAX(); } } static inline void sym_unlock(void) { - atomic_store_explicit(&g_sym_lock, 0, memory_order_release); + atomic_store_explicit(&g_sym_lock_line.v, 0, memory_order_release); } +uintptr_t ray_sym_test_lock_addr(void) { return (uintptr_t)&g_sym_lock_line.v; } +uintptr_t ray_sym_test_table_addr(void) { return (uintptr_t)&g_sym; } +size_t ray_sym_test_table_size(void) { return sizeof g_sym; } +uintptr_t ray_sym_test_inited_addr(void) { return (uintptr_t)&g_sym_inited; } /* String atoms for the global sym table live in its arena (off the per-thread * buddy heap) — see ray_arena_str in mem/arena.c. */ @@ -1203,7 +1216,10 @@ ray_err_t ray_sym_save(const char* path) { return err; } - /* Atomic rename: tmp -> final path */ + /* Atomic rename: tmp -> final path. Whatever was there goes, and + * with it the record index of a symfile of that name (domain.h): this + * writer keeps none, and the new file need not extend the old one. */ + ray_sym_domain_index_remove(path); err = ray_file_rename(tmp_path, path); if (err != RAY_OK) { remove(tmp_path); diff --git a/src/table/sym.h b/src/table/sym.h index 7ed5e0bf7..ecef10b8e 100644 --- a/src/table/sym.h +++ b/src/table/sym.h @@ -186,4 +186,10 @@ static inline size_t ray_sym_bytes_upper(size_t len) { return 32 + chars_block; } +/* Test hooks: addresses and size of the lock, g_sym and g_sym_inited. */ +uintptr_t ray_sym_test_lock_addr(void); +uintptr_t ray_sym_test_table_addr(void); +size_t ray_sym_test_table_size(void); +uintptr_t ray_sym_test_inited_addr(void); + #endif /* RAY_SYM_H */ diff --git a/src/table/symimp.c b/src/table/symimp.c index 5c0f7f564..db6dfd11a 100644 --- a/src/table/symimp.c +++ b/src/table/symimp.c @@ -25,6 +25,7 @@ # define _GNU_SOURCE #endif #include "symimp.h" +#include "domain.h" /* the record index written at the final sync */ #include "ops/hash.h" /* ray_hash_bytes: position 0 is "" */ #if defined(RAY_OS_LINUX) || defined(RAY_OS_MACOS) || defined(__linux__) || defined(__APPLE__) @@ -86,6 +87,8 @@ struct ray_symimp_s { int64_t tail; /* bytes of records + header */ int64_t fsize; /* the file's current length */ int64_t synced; /* bytes whose writeback was started */ + int64_t ix_count, ix_tail; /* the last durable sync's: its index is + * written at free when nothing came after */ _Atomic(int64_t)* count_out; /* A replaced shard table may still be read by a lock-free lookup that * loaded it. Lookups register in the parity of the epoch they start @@ -448,6 +451,7 @@ ray_symimp_t* ray_symimp_create(const char* path, _Atomic(int64_t)* count) { m->path = (char*)ray_sys_alloc(pl + 1); if (!m->path) goto fail; memcpy(m->path, path, pl + 1); + ray_sym_domain_index_remove(path); /* describes the file truncated here */ m->fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); if (m->fd < 0) goto fail; /* Address space for the whole file up front: it only grows by ftruncate. */ @@ -485,6 +489,28 @@ ray_symimp_t* ray_symimp_create(const char* path, _Atomic(int64_t)* count) { return NULL; } +/* The file's record index (table/domain.h), once it holds its final + * records: the offset of the first of every block of them, which this + * dictionary knows. */ +static void si_save_index(ray_symimp_t* m, int64_t count, int64_t tail) { + int64_t n = (count + RAY_SYM_INDEX_STRIDE - 1) / RAY_SYM_INDEX_STRIDE; + if (n <= 0) return; + uint64_t* ck = (uint64_t*)ray_sys_alloc((size_t)n * sizeof(uint64_t)); + uint16_t* lens = (uint16_t*)ray_sys_alloc((size_t)count * 2); + if (ck && lens) { + for (int64_t k = 0; k < n; k++) ck[k] = si_off(m, k * RAY_SYM_INDEX_STRIDE); + /* the lengths, from the offsets this dictionary keeps of every record */ + for (int64_t i = 0; i < count; i++) { + uint64_t a = si_off(m, i), b = i + 1 < count ? si_off(m, i + 1) : (uint64_t)tail; + uint64_t l = b - a - 4; + lens[i] = l < 65535 ? (uint16_t)l : (uint16_t)65535; + } + ray_sym_domain_index_save(m->path, ck, n, lens, count, (uint64_t)tail); + } + ray_sys_free(ck); + ray_sys_free(lens); +} + ray_err_t ray_symimp_sync(ray_symimp_t* m, bool durable) { if (!m) return RAY_ERR_TYPE; pthread_mutex_lock(&m->alock); @@ -508,7 +534,12 @@ ray_err_t ray_symimp_sync(ray_symimp_t* m, bool durable) { return RAY_OK; } if (msync(m->map, (size_t)tail, MS_SYNC) != 0 || fsync(m->fd) != 0) return RAY_ERR_IO; - return ray_file_sync_dir(m->path); + err = ray_file_sync_dir(m->path); + /* The index claims the file's identity, which on macOS the unmap of a + * written shared mapping still moves (its modification time): it is + * written at free, once the mapping is gone. */ + if (err == RAY_OK) { m->ix_count = count; m->ix_tail = tail; } + return err; } void ray_symimp_stats(ray_symimp_t* m, ray_symimp_stats_t* out) { @@ -551,9 +582,10 @@ void ray_symimp_free(ray_symimp_t* m) { } for (int k = 0; k < 2; k++) for (si_tab_t* t = m->retired[k]; t;) { si_tab_t* nx = t->next; ray_sys_free(t); t = nx; } - for (int c = 0; c < SI_OFF_CHUNKS; c++) ray_sys_free(m->offc[c]); if (m->map) munmap(m->map, m->reserve); if (m->fd >= 0) close(m->fd); + if (m->ix_count > 0 && m->tail == m->ix_tail) si_save_index(m, m->ix_count, m->ix_tail); + for (int c = 0; c < SI_OFF_CHUNKS; c++) ray_sys_free(m->offc[c]); ray_sys_free(m->path); ray_sys_free(m); } diff --git a/src/table/table.c b/src/table/table.c index 10d39b6ef..5e46c69e0 100644 --- a/src/table/table.c +++ b/src/table/table.c @@ -25,6 +25,9 @@ #include "mem/heap.h" #include "ops/ops.h" #include "lang/format.h" +#include "ops/idxop.h" +#include "store/enccol.h" +#include "vec/vec.h" #include /* -------------------------------------------------------------------------- @@ -75,16 +78,20 @@ static bool table_col_is_valid(ray_t* col) { return col->type == RAY_LIST || ray_is_vec(col) || RAY_IS_PARTED(col->type) || - col->type == RAY_MAPCOMMON; + col->type == RAY_MAPCOMMON || + col->type == RAY_ENCCOL; /* single or parted; len is logical */ } static int64_t table_col_nrows(ray_t* col) { - if (!col) return 0; + if (!col || ray_is_atom(col)) return 0; /* an atom has no rows (its len field is payload) */ + if (col->type == RAY_ENCCOL) return col->len; /* no decode */ if (RAY_IS_PARTED(col->type) || col->type == RAY_MAPCOMMON) return ray_parted_nrows(col); return col->len; } +int64_t ray_table_col_nrows(ray_t* col) { return table_col_nrows(col); } + /* -------------------------------------------------------------------------- * ray_table_new — allocates an empty table with capacity for `ncols`. * @@ -208,10 +215,13 @@ ray_t* ray_table_validate_rectangular(ray_t* tbl, const char* context) { } /* -------------------------------------------------------------------------- - * ray_table_get_col — lookup column by sym id; borrowed pointer or NULL. + * Slot lookups (borrowed slot object, plain or RAY_ENCCOL), then the + * accessors built on them: metadata (never decodes), plain column + * (materializes an encoded slot), index, encoded object, and the legacy + * getters. * -------------------------------------------------------------------------- */ -ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id) { +static ray_t* tbl_slot_by_name(ray_t* tbl, int64_t name_id) { if (!tbl_is_table(tbl)) return NULL; ray_t* schema = tbl_schema(tbl); ray_t* cols = tbl_cols(tbl); @@ -224,11 +234,7 @@ ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id) { return NULL; } -/* -------------------------------------------------------------------------- - * ray_table_get_col_idx — borrowed pointer at slot `idx`, or NULL. - * -------------------------------------------------------------------------- */ - -ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx) { +static ray_t* tbl_slot_by_idx(ray_t* tbl, int64_t idx) { if (!tbl_is_table(tbl)) return NULL; ray_t* cols = tbl_cols(tbl); if (!cols) return NULL; @@ -236,6 +242,150 @@ ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx) { return ((ray_t**)ray_data(cols))[idx]; } +bool ray_col_meta_of(ray_t* c, ray_col_meta_t* m) { + memset(m, 0, sizeof *m); + if (!c || RAY_IS_ERR(c)) return false; + if (c->type == RAY_ENCCOL) { ray_enccol_meta(c, m); return true; } + m->type = c->type; + m->attrs = c->attrs; + m->len = table_col_nrows(c); + m->null_count = -1; + if (RAY_IS_PARTED(c->type)) { m->n_segs = c->len; return true; } + if (ray_is_vec(c) && ray_index_has(c)) { + ray_index_t* ix = ray_index_payload(c->index); + m->index_kind = ix->kind; + m->unique = (ix->markers & RAY_MARK_UNIQUE) != 0; + } + return true; +} + +bool ray_table_col_meta(ray_t* tbl, int64_t name_id, ray_col_meta_t* m) { + return ray_col_meta_of(tbl_slot_by_name(tbl, name_id), m); +} +bool ray_table_col_meta_idx(ray_t* tbl, int64_t idx, ray_col_meta_t* m) { + return ray_col_meta_of(tbl_slot_by_idx(tbl, idx), m); +} + +static ray_t* slot_plain(ray_t* c) { + if (!c) return NULL; + return c->type == RAY_ENCCOL ? ray_enccol_materialize(c) : c; +} +/* The result is borrowed and read-only: encoded objects are shared between + * table copies and share one decoded cache, so never write through it. */ +ray_t* ray_table_col(ray_t* tbl, int64_t name_id) { return slot_plain(tbl_slot_by_name(tbl, name_id)); } +ray_t* ray_table_col_idx(ray_t* tbl, int64_t idx) { return slot_plain(tbl_slot_by_idx(tbl, idx)); } + +static ray_t* slot_index(ray_t* c, ray_t** index) { + *index = NULL; + if (!c) return NULL; + if (c->type != RAY_ENCCOL) { + if (ray_is_vec(c) && ray_index_has(c)) *index = c->index; + return NULL; + } + if (!ray_enccol_may_have_index(c)) return NULL; /* parted answers false too */ + ray_t* d = ray_enccol_materialize(c); + if (RAY_IS_ERR(d)) return d; + if (ray_index_has(d)) *index = d->index; + return NULL; +} +ray_t* ray_table_col_index(ray_t* tbl, int64_t name_id, ray_t** index) { + return slot_index(tbl_slot_by_name(tbl, name_id), index); +} +ray_t* ray_table_col_index_idx(ray_t* tbl, int64_t idx, ray_t** index) { + return slot_index(tbl_slot_by_idx(tbl, idx), index); +} + +ray_t* ray_table_get_col_enc(ray_t* tbl, int64_t name_id) { + ray_t* c = tbl_slot_by_name(tbl, name_id); + return (c && c->type == RAY_ENCCOL) ? c : NULL; +} +ray_t* ray_table_get_col_enc_idx(ray_t* tbl, int64_t idx) { + ray_t* c = tbl_slot_by_idx(tbl, idx); + return (c && c->type == RAY_ENCCOL) ? c : NULL; +} + +ray_t* ray_table_slot(ray_t* tbl, int64_t name_id) { return tbl_slot_by_name(tbl, name_id); } +ray_t* ray_table_slot_idx(ray_t* tbl, int64_t idx) { return tbl_slot_by_idx(tbl, idx); } + +static ray_t* slot_parted_seg(ray_t* c, int64_t s) { + if (!c) return NULL; + if (c->type == RAY_ENCCOL) return ray_enccol_is_parted(c) ? ray_enccol_seg(c, s) : NULL; + if (!RAY_IS_PARTED(c->type) || s < 0 || s >= c->len) return NULL; + return ((ray_t**)ray_data(c))[s]; /* parted wrapper, not a table */ +} +ray_t* ray_table_parted_seg(ray_t* tbl, int64_t name_id, int64_t s) { + return slot_parted_seg(tbl_slot_by_name(tbl, name_id), s); +} +ray_t* ray_table_parted_seg_idx(ray_t* tbl, int64_t idx, int64_t s) { + return slot_parted_seg(tbl_slot_by_idx(tbl, idx), s); +} + +/* aux[0] of a parted SYM/STR wrapper: its null presence once computed. */ +#define PARTED_TEXT_NULLS_KNOWN 0x01 +#define PARTED_TEXT_NULLS_HAS 0x02 + +bool ray_table_col_has_nulls(ray_t* tbl, int64_t name_id) { + ray_t* c = tbl_slot_by_name(tbl, name_id); + if (!c) return false; + ray_col_meta_t m; + ray_col_meta_of(c, &m); + if (m.null_count >= 0) return m.null_count > 0; /* generation 2: directory */ + if (m.enc) return (m.attrs & RAY_ATTR_HAS_NULLS) != 0; + if (RAY_IS_PARTED(c->type)) { /* the wrapper carries no flag: ask each segment */ + /* A text wrapper caches its answer in aux[0] (PARTED_TEXT_NULLS_*): + * the segment scans run once per wrapper, not on every planning + * call. A wrapper is never edited in place (an insert builds a new + * one, aux zeroed) and its loaded segments are read-only. The byte + * is written with the same value by any racing caller. */ + int8_t base = (int8_t)RAY_PARTED_BASETYPE(c->type); + bool text_base = base == RAY_SYM || base == RAY_STR; + if (text_base) { + uint8_t k = __atomic_load_n(&c->aux[0], __ATOMIC_RELAXED); + if (k & PARTED_TEXT_NULLS_KNOWN) return (k & PARTED_TEXT_NULLS_HAS) != 0; + } + bool any = false; + ray_t** segs = (ray_t**)ray_data(c); + for (int64_t i = 0; i < c->len; i++) { + ray_col_meta_t sm; + if (!ray_col_meta_of(segs[i], &sm)) continue; + bool text = !sm.enc && (sm.type == RAY_SYM || sm.type == RAY_STR); + bool nulls = sm.null_count >= 0 ? sm.null_count > 0 /* an encoded segment's directory */ + /* a plain text segment: the exact check, which scans + * the payload (text nulls are in-band, no flag) */ + : text ? ray_vec_has_nulls(segs[i]) + : (sm.attrs & RAY_ATTR_HAS_NULLS) != 0; + if (nulls) { any = true; break; } + } + if (text_base) + __atomic_store_n(&c->aux[0], (uint8_t)(PARTED_TEXT_NULLS_KNOWN | + (any ? PARTED_TEXT_NULLS_HAS : 0)), __ATOMIC_RELAXED); + return any; + } + return ray_is_vec(c) && ray_vec_has_nulls(c); /* generation 0: today's scan */ +} + +/* Legacy getters (public, include/rayforce.h). A plain slot (the common + * case) is a pure lookup that leaves the error slot alone; only an encoded + * slot saves the pending message, clears the slot and decodes. Success + * restores the pending message; a failure disposes of the error with + * ray_error_free and returns NULL with its message left in the slot. */ +static ray_t* legacy_slot(ray_t* slot) { + if (!slot || slot->type != RAY_ENCCOL) return slot; + char pending[256]; + snprintf(pending, sizeof pending, "%s", ray_error_msg() ? ray_error_msg() : ""); + ray_error_clear(); + ray_t* c = ray_enccol_materialize(slot); + if (RAY_IS_ERR(c)) { ray_error_free(c); return NULL; } + if (pending[0]) ray_error_free(ray_error("domain", "%s", pending)); + return c; +} +ray_t* ray_table_get_col(ray_t* tbl, int64_t name_id) { + return legacy_slot(tbl_slot_by_name(tbl, name_id)); +} +ray_t* ray_table_get_col_idx(ray_t* tbl, int64_t idx) { + return legacy_slot(tbl_slot_by_idx(tbl, idx)); +} + /* -------------------------------------------------------------------------- * ray_table_set_col_idx — replace the column vector at slot `idx`. COWs the * cols list, releases the previous column and retains `col_vec`. No-op when @@ -304,10 +454,7 @@ int64_t ray_table_nrows(ray_t* tbl) { ray_t* first_col = ((ray_t**)ray_data(cols))[0]; if (!first_col || RAY_IS_ERR(first_col)) return 0; - if (RAY_IS_PARTED(first_col->type) || first_col->type == RAY_MAPCOMMON) - return ray_parted_nrows(first_col); - - return first_col->len; + return table_col_nrows(first_col); } int64_t ray_parted_nrows(ray_t* v) { @@ -339,3 +486,26 @@ ray_t* ray_table_schema(ray_t* tbl) { if (!tbl_is_table(tbl)) return NULL; return tbl_schema(tbl); } + +bool ray_table_cols_canonical(ray_t* tbl) { + if (!tbl_is_table(tbl)) return false; + ray_t* schema = tbl_schema(tbl); + ray_t* cols = tbl_cols(tbl); + return schema && !RAY_IS_ERR(schema) && cols && !RAY_IS_ERR(cols) && + cols->type == RAY_LIST && cols->attrs == 0 && cols->len == schema->len; +} + +ray_t* ray_table_cols_inplace(ray_t* tbl) { + if (!tbl_is_table(tbl)) return NULL; + ray_t* cols = tbl_cols(tbl); + if (!cols || RAY_IS_ERR(cols)) return NULL; + ray_t** cv = (ray_t**)ray_data(cols); + for (int64_t i = 0; i < cols->len; i++) + if (cv[i] && cv[i]->type == RAY_ENCCOL) return NULL; + return cols; +} + +bool ray_table_has_col(ray_t* tbl, int64_t name_id) { + ray_col_meta_t m; + return tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE && ray_table_col_meta(tbl, name_id, &m); +} diff --git a/src/table/table.h b/src/table/table.h index dfd1c34a4..4658748fb 100644 --- a/src/table/table.h +++ b/src/table/table.h @@ -34,7 +34,69 @@ */ #include +#include +/* Rows of a parted wrapper: the sum of its present segments' lengths (a + * MAPCOMMON: the sum of its row counts; anything else: len). A wrapper from + * ray_read_parted has every segment, a ragged partition's absent column + * a segment of nulls of the partition's row count, so this is the table's row count + * (#724). A missing segment (hand-built wrappers only) counts 0 rows; the + * executor refuses a table whose parted and MAPCOMMON row counts differ. */ int64_t ray_parted_nrows(ray_t* parted_col); +/* Logical rows of any column object (plain, parted wrapper, MAPCOMMON, + * RAY_ENCCOL) without decoding. */ +int64_t ray_table_col_nrows(ray_t* col); + +typedef struct { + int8_t type; /* logical type; parted: RAY_PARTED_BASE + base */ + uint8_t attrs; /* generation 0: the vector's attrs; generation 2: persisted attrs */ + int64_t len; /* rows (parted: sum over segments) */ + int64_t n_segs; /* parted: segment count; else 0 */ + uint8_t index_kind; /* attached (gen 0) or recorded (gen 2) ray_idx_kind_t */ + bool unique; + int64_t null_count; /* generation 2: exact, from the directory; -1 when unknown */ + ray_t* enc; /* borrowed RAY_ENCCOL, or NULL */ +} ray_col_meta_t; + +bool ray_col_meta_of(ray_t* col, ray_col_meta_t* m); /* any slot object */ +bool ray_table_col_meta(ray_t* tbl, int64_t name_id, ray_col_meta_t* m); +/* Whether `tbl` (a table) has column `name_id`, from metadata: an encoded + * column is not materialized. */ +bool ray_table_has_col(ray_t* tbl, int64_t name_id); +bool ray_table_col_meta_idx(ray_t* tbl, int64_t idx, ray_col_meta_t* m); + +/* Index of a column without decoding when it cannot carry one: NULL with + * *index set (borrowed RAY_INDEX block or NULL), or an owned error. */ +ray_t* ray_table_col_index(ray_t* tbl, int64_t name_id, ray_t** index); +ray_t* ray_table_col_index_idx(ray_t* tbl, int64_t idx, ray_t** index); + +/* The borrowed RAY_ENCCOL object of a slot, or NULL (absent, plain). */ +ray_t* ray_table_get_col_enc(ray_t* tbl, int64_t name_id); +ray_t* ray_table_get_col_enc_idx(ray_t* tbl, int64_t idx); + +/* The slot object itself, plain or encoded (borrowed; never decodes), or + * NULL when absent: for handing a column to another table unread. */ +ray_t* ray_table_slot(ray_t* tbl, int64_t name_id); +ray_t* ray_table_slot_idx(ray_t* tbl, int64_t idx); + +/* Segment s of a parted slot (borrowed; never decodes): the encoded + * wrapper's segment object or the plain wrapper's segment. NULL when the + * slot is absent or not parted, s is out of range, or the segment is + * missing (a hand-built wrapper). */ +ray_t* ray_table_parted_seg(ray_t* tbl, int64_t name_id, int64_t s); +ray_t* ray_table_parted_seg_idx(ray_t* tbl, int64_t idx, int64_t s); + +/* Null presence from metadata; never materializes. */ +bool ray_table_col_has_nulls(ray_t* tbl, int64_t name_id); + +/* The table's column list for an in-place value write, or NULL when the + * table is not a table or any slot holds a RAY_ENCCOL (callers then take + * their copy route). Ownership checks (rc) stay with the caller. */ +ray_t* ray_table_cols_inplace(ray_t* tbl); + +/* The column-list container is canonical: a RAY_LIST with zero attrs whose + * length is the schema's. Reads only the container header, never a slot. */ +bool ray_table_cols_canonical(ray_t* tbl); + #endif /* RAY_TABLE_H */ diff --git a/src/vec/atom.c b/src/vec/atom.c index 084143222..6042a967a 100644 --- a/src/vec/atom.c +++ b/src/vec/atom.c @@ -152,11 +152,20 @@ ray_t* ray_sym(int64_t id) { * narrowed to the correct element width. * -------------------------------------------------------------------------- */ +/* DATE and TIME hold 32 bits, as their vector cells do. The constructors + * take an int64_t, so the result of atom arithmetic or a cast can be out of + * range: keep its low 32 bits, sign-extended, so that every reader agrees. + * The null check reads x->i32 and arithmetic reads x->i64; an unwrapped + * value made an atom print, compare and store wrapped but add unwrapped. */ +static inline int64_t atom_wrap_i32(int64_t val) { + return (int64_t)(int32_t)(uint32_t)(uint64_t)val; +} + ray_t* ray_date(int64_t val) { ray_t* v = ray_alloc(0); if (RAY_IS_ERR(v)) return v; v->type = -RAY_DATE; - v->i64 = val; + v->i64 = atom_wrap_i32(val); return v; } @@ -164,7 +173,7 @@ ray_t* ray_time(int64_t val) { ray_t* v = ray_alloc(0); if (RAY_IS_ERR(v)) return v; v->type = -RAY_TIME; - v->i64 = val; + v->i64 = atom_wrap_i32(val); return v; } @@ -176,6 +185,12 @@ ray_t* ray_timestamp(int64_t val) { return v; } +ray_t* ray_timespan(int64_t nanoseconds) { + ray_t* v = ray_i64(nanoseconds); + if (!RAY_IS_ERR(v)) v->type = -RAY_TIMESPAN; + return v; +} + ray_t* ray_typed_null(int8_t type) { if (type >= 0) return ray_error("type", "typed_null: expects a negative atom type tag, got %s", ray_type_name(type)); /* GUID null is the canonical all-zero 16-byte value: allocate the @@ -197,7 +212,7 @@ ray_t* ray_typed_null(int8_t type) { switch (type) { case -RAY_F64: v->f64 = NULL_F64; break; case -RAY_F32: v->f64 = (double)NULL_F32; break; - case -RAY_I64: case -RAY_TIMESTAMP: v->i64 = NULL_I64; break; + case -RAY_TIMESPAN: case -RAY_I64: case -RAY_TIMESTAMP: v->i64 = NULL_I64; break; case -RAY_I32: case -RAY_DATE: case -RAY_TIME: v->i32 = NULL_I32; break; case -RAY_I16: v->i16 = NULL_I16; break; case -RAY_SYM: diff --git a/src/vec/growth.h b/src/vec/growth.h new file mode 100644 index 000000000..2bebef466 --- /dev/null +++ b/src/vec/growth.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef RAY_CELL_GROWTH_H +#define RAY_CELL_GROWTH_H + +#include "mem/heap.h" + +/* A direct mapping includes a prefix and object header and is page-rounded. + * Keep a single allocation's mapped size representable in the allocator's + * signed byte counters as well as size_t. This is a ceiling, not a request. */ +static inline size_t ray_cell_growth_limit(void) { + size_t limit = SIZE_MAX; + if ((uint64_t)limit > (uint64_t)INT64_MAX) limit = (size_t)INT64_MAX; + return (limit & ~(size_t)4095) - RAY_DIRECT_HDR - 32; +} + +/* Check actual growth requests; no signed sum or byte product may wrap. + * Bulk APIs preflight externally requested counts before COW/index changes. + * Physical width matters (notably for narrow SYM). Zero-count raw appends + * retain their earlier no-op path and need not call this helper. */ +static inline bool ray_cell_growth_bytes(int64_t len, int64_t count, + size_t width, size_t* required) { + if (len < 0 || count < 0 || width == 0 || count > INT64_MAX - len) + return false; + uint64_t n = (uint64_t)(len + count); + if (n > (uint64_t)SIZE_MAX) return false; + size_t bytes; + if (__builtin_mul_overflow((size_t)n, width, &bytes) || + bytes > ray_cell_growth_limit()) return false; + *required = bytes; + return true; +} + +/* Called only when required exceeds owned usable room. Buddy rounding of + * payload+header already supplies geometric growth: do not pre-round payload. + * Direct mappings instead round to pages, so grow from their actual capacity + * explicitly. Larger cached mappings and allocator-owned spill use the same + * capacity rule. Nothing here changes allocation/free/cache policy. */ +static inline bool ray_cell_growth_request(size_t room, size_t required, + size_t* request) { + size_t limit = ray_cell_growth_limit(); + if (required > limit || room > limit) return false; + size_t bytes = required; + if (ray_order_for_size(required) >= RAY_HEAP_POOL_ORDER) { + size_t doubled = room > limit / 2 ? limit : room * 2; + if (doubled > bytes) bytes = doubled; + } + *request = bytes; + return true; +} + +/* Rare allocation geometry must not inflate the register frame of a + * reserved-capacity single append. Bulk callers preflight their count. */ +static __attribute__((cold, noinline, unused)) +ray_t* ray_cell_grow_one(ray_t* value, size_t width) { + size_t required, request; + if (!ray_cell_growth_bytes(value->len, 1, width, &required) || + !ray_cell_growth_request(ray_block_data_bytes(value), required, &request)) + return NULL; + return ray_scratch_realloc(value, request); +} + +#endif /* RAY_CELL_GROWTH_H */ diff --git a/src/vec/list.c b/src/vec/list.c index 1f16f3f0c..875257bf6 100644 --- a/src/vec/list.c +++ b/src/vec/list.c @@ -23,6 +23,7 @@ #include "list.h" #include "mem/heap.h" +#include "vec/growth.h" #include "lang/format.h" /* ray_type_name */ #include @@ -72,6 +73,7 @@ ray_t* ray_list_append(ray_t* list, ray_t* item) { if (!list || RAY_IS_ERR(list)) return list; /* COW if shared */ + ray_t* original = list; list = ray_cow(list); if (!list || RAY_IS_ERR(list)) return list; @@ -80,20 +82,7 @@ ray_t* ray_list_append(ray_t* list, ray_t* item) { /* Grow if needed */ if (list->len >= cap) { - size_t new_data_size = (size_t)(list->len + 1) * sizeof(ray_t*); - if (new_data_size < 32) new_data_size = 32; - else { - size_t s = 32; - while (s < new_data_size) { - if (s > SIZE_MAX / 2) { - if (list != original) ray_release(list); - return ray_error("oom", NULL); - } - s *= 2; - } - new_data_size = s; - } - ray_t* new_list = ray_scratch_realloc(list, new_data_size); + ray_t* new_list = ray_cell_grow_one(list, sizeof(ray_t*)); if (!new_list || RAY_IS_ERR(new_list)) { if (list != original) ray_release(list); return new_list ? new_list : ray_error("oom", NULL); @@ -161,6 +150,7 @@ ray_t* ray_list_insert_at(ray_t* list, int64_t idx, ray_t* item) { if (idx < 0 || idx > list->len) return ray_error("range", "list_insert_at: index out of bounds [0,%lld], got %lld", (long long)list->len, (long long)idx); + ray_t* original = list; list = ray_cow(list); if (!list || RAY_IS_ERR(list)) return list; @@ -168,20 +158,7 @@ ray_t* ray_list_insert_at(ray_t* list, int64_t idx, ray_t* item) { int64_t cap = list_capacity(list); if (list->len >= cap) { - size_t new_data_size = (size_t)(list->len + 1) * sizeof(ray_t*); - if (new_data_size < 32) new_data_size = 32; - else { - size_t s = 32; - while (s < new_data_size) { - if (s > SIZE_MAX / 2) { - if (list != original) ray_release(list); - return ray_error("oom", NULL); - } - s *= 2; - } - new_data_size = s; - } - ray_t* new_list = ray_scratch_realloc(list, new_data_size); + ray_t* new_list = ray_cell_grow_one(list, sizeof(ray_t*)); if (!new_list || RAY_IS_ERR(new_list)) { if (list != original) ray_release(list); return new_list ? new_list : ray_error("oom", NULL); diff --git a/src/vec/str.h b/src/vec/str.h index f6ce5d47b..513118e79 100644 --- a/src/vec/str.h +++ b/src/vec/str.h @@ -86,19 +86,14 @@ static inline int ray_str_t_cmp(const ray_str_t* a, const char* pool_a, return (a->len > b->len) - (a->len < b->len); } -/* Hash a ray_str_t element. Uses FNV-1a which is self-contained and fast for - * the typical short-to-medium strings stored in ray_str_t. - * pool_base: pool base pointer for pooled strings (NULL when inline-only). */ -static inline uint64_t ray_str_t_hash(const ray_str_t* s, const char* pool_base) { - if (s->len == 0) return 0x9E3779B97F4A7C15ULL; /* golden ratio constant for empty */ - if (!ray_str_is_inline(s)) { - assert(pool_base != NULL && "ray_str_t_hash: pooled string requires non-NULL pool_base"); - } - const char* p = ray_str_is_inline(s) ? s->data : pool_base + s->pool_off; - /* 8-byte-block multiply-mix hash: far fewer multiplies than per-byte - * hashing for medium/long keys (URLs, titles). */ +/* Hash the bytes [p, p + len) of a string: an 8-byte-block multiply-mix + * hash, far fewer multiplies than per-byte hashing for medium/long keys + * (URLs, titles); "" hashes to a constant (p unread). The one string hash + * of ray_str_t_hash: a consumer hashing bytes it holds outside a ray_str_t + * (a STR_DICT entry) gets the same hash for the same string. */ +static inline uint64_t ray_str_bytes_hash(const char* p, uint32_t len) { + if (len == 0) return 0x9E3779B97F4A7C15ULL; /* golden ratio constant for empty */ const uint64_t m = 0xc6a4a7935bd1e995ULL; - uint32_t len = s->len; uint64_t h = 0xe17a1465ULL ^ ((uint64_t)len * m); uint32_t i = 0; for (; i + 8 <= len; i += 8) { @@ -118,6 +113,17 @@ static inline uint64_t ray_str_t_hash(const ray_str_t* s, const char* pool_base) return h; } +/* Hash a ray_str_t element: ray_str_bytes_hash of its bytes. + * pool_base: pool base pointer for pooled strings (NULL when inline-only). */ +static inline uint64_t ray_str_t_hash(const ray_str_t* s, const char* pool_base) { + if (s->len == 0) return ray_str_bytes_hash(NULL, 0); + if (!ray_str_is_inline(s)) { + assert(pool_base != NULL && "ray_str_t_hash: pooled string requires non-NULL pool_base"); + } + const char* p = ray_str_is_inline(s) ? s->data : pool_base + s->pool_off; + return ray_str_bytes_hash(p, s->len); +} + /* Pooled descriptors have four bytes that are not needed for addressing. * Cache a non-zero 32-bit content hash there so joins can hash long STR keys * without rereading the pool on every execution. A zero field denotes an diff --git a/src/vec/vec.c b/src/vec/vec.c index 9a342d571..117dff61d 100644 --- a/src/vec/vec.c +++ b/src/vec/vec.c @@ -24,6 +24,7 @@ #include "vec.h" #include "core/platform.h" #include "mem/heap.h" +#include "vec/growth.h" #include "table/sym.h" #include "table/domain.h" #include "vec/embedding.h" @@ -43,47 +44,35 @@ static int pair_cmp_idx_then_k(const void* a, const void* b) { return (pa[1] > pb[1]) - (pa[1] < pb[1]); } -/* Sentinel-based per-element null test. Caller guarantees v is a - * non-slice vector (type > 0) and idx is in range. Returns true iff - * payload[idx] equals the type-correct NULL_* sentinel. F64/F32 use - * (x != x) to detect any NaN bit pattern. BOOL/U8 are non-nullable - * and return false. */ -static inline bool sentinel_is_null(const ray_t* v, int64_t idx) { - const void* p = ray_data((ray_t*)v); - switch (v->type) { - case RAY_F64: { - double x = ((const double*)p)[idx]; - return x != x; - } - case RAY_F32: { - float x = ((const float*)p)[idx]; - return x != x; - } - case RAY_I64: - case RAY_TIMESTAMP: - return ((const int64_t*)p)[idx] == NULL_I64; - case RAY_I32: - case RAY_DATE: - case RAY_TIME: - return ((const int32_t*)p)[idx] == NULL_I32; - case RAY_I16: - return ((const int16_t*)p)[idx] == NULL_I16; - /* SYM uses id 0 as its canonical in-band null. Width-aware handling - * lives in ray_vec_is_null, so there is no arm here. */ - case RAY_STR: - return ((const ray_str_t*)p)[idx].len == 0; +/* Sentinel null test on a raw generation-0 element array. F64/F32 use + * (x != x) to detect any NaN bit pattern; SYM tests id 0 at the width class + * in `attrs`; BOOL/U8 are non-nullable and return false. */ +bool ray_raw_is_null(int8_t type, uint8_t attrs, const void* p, int64_t idx) { + switch (type) { + case RAY_F64: { double x = ((const double*)p)[idx]; return x != x; } + case RAY_F32: { float x = ((const float*)p)[idx]; return x != x; } + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: return ((const int64_t*)p)[idx] == NULL_I64; + case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)p)[idx] == NULL_I32; + case RAY_I16: return ((const int16_t*)p)[idx] == NULL_I16; + case RAY_SYM: return ray_read_sym(p, idx, RAY_SYM, attrs) == 0; + case RAY_STR: return ((const ray_str_t*)p)[idx].len == 0; case RAY_GUID: { /* GUID null = 16 all-zero bytes (canonical convention). */ static const uint8_t Z[16] = {0}; return memcmp((const uint8_t*)p + idx * 16, Z, 16) == 0; } - case RAY_BOOL: - case RAY_U8: - default: - return false; + default: return false; /* BOOL, U8: non-nullable */ } } +/* Sentinel-based per-element null test. Caller guarantees v is a + * non-slice vector (type > 0) and idx is in range. Returns true iff + * payload[idx] equals the type-correct NULL_* sentinel. SYM is resolved + * (width-aware) by ray_vec_is_null before it gets here. */ +static inline bool sentinel_is_null(const ray_t* v, int64_t idx) { + return ray_raw_is_null(v->type, v->attrs, ray_data((ray_t*)v), idx); +} + /* In-place drop of attached index — caller must hold a unique ref (rc==1) * on `v` itself. Used by mutation paths to invalidate the (now stale) * index before writing. HAS_NULLS was preserved through the attachment @@ -133,7 +122,8 @@ static inline void vec_drop_index_inplace(ray_t* v) { * * A vector's capacity is determined by its buddy order: * capacity = (2^order - 32) / elem_size - * When len reaches capacity, realloc to next power-of-2 data size. + * Growth requests include header-aware buddy rounding or explicit direct-block + * doubling; payload alone is not pre-rounded. * -------------------------------------------------------------------------- */ static int64_t vec_capacity(ray_t* vec) { @@ -151,7 +141,7 @@ static int64_t vec_capacity(ray_t* vec) { * -------------------------------------------------------------------------- */ ray_t* ray_vec_new(int8_t type, int64_t capacity) { - if (type <= 0 || type >= RAY_TYPE_COUNT) + if (!ray_is_vector_type(type)) return ray_error("type", "vec_new: type must be a positive concrete vector type, got %s", ray_type_name(type)); if (type == RAY_SYM) return ray_sym_vec_new(RAY_SYM_W64, capacity); /* default: global sym IDs */ @@ -241,11 +231,12 @@ void ray_sym_vec_adopt_domain(ray_t* out, ray_t* in) { ray_t* ray_vec_append(ray_t* vec, const void* elem) { if (!vec || RAY_IS_ERR(vec)) return vec; - if (vec->type <= 0 || vec->type >= RAY_TYPE_COUNT) + if (!ray_is_vec(vec)) return ray_error("type", "vec_append: expects a concrete vector type, got %s", ray_type_name(vec->type)); if (vec->type == RAY_STR) return ray_error("type", "vec_append: str vectors use ray_str_vec_append, got %s", ray_type_name(vec->type)); /* COW: if shared, copy first */ + uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); ray_t* original = vec; vec = ray_cow(vec); if (!vec || RAY_IS_ERR(vec)) return vec; @@ -253,23 +244,11 @@ ray_t* ray_vec_append(ray_t* vec, const void* elem) { /* Append changes len + writes data; any attached index is now stale. */ vec_drop_index_inplace(vec); - uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); int64_t cap = vec_capacity(vec); /* Grow if needed */ if (vec->len >= cap) { - size_t new_data_size = (size_t)(vec->len + 1) * esz; - /* Round up to next power of 2 block */ - if (new_data_size < 32) new_data_size = 32; - else { - size_t s = 32; - while (s < new_data_size) { - if (s > SIZE_MAX / 2) goto fail; - s *= 2; - } - new_data_size = s; - } - ray_t* new_vec = ray_scratch_realloc(vec, new_data_size); + ray_t* new_vec = ray_cell_grow_one(vec, esz); if (!new_vec || RAY_IS_ERR(new_vec)) { if (vec != original) ray_release(vec); return new_vec ? new_vec : ray_error("oom", NULL); @@ -287,9 +266,6 @@ ray_t* ray_vec_append(ray_t* vec, const void* elem) { return vec; -fail: - if (vec != original) ray_release(vec); - return ray_error("oom", NULL); } /* -------------------------------------------------------------------------- @@ -297,7 +273,7 @@ ray_t* ray_vec_append(ray_t* vec, const void* elem) { * * Append `count` raw elements with one capacity reserve and one memcpy. * Same contract as ray_vec_append (COW when shared, index drop, amortized - * power-of-two growth, original left alive on failure), minus the + * geometric growth, original left alive on failure), minus the * per-element call overhead — this is the batch-ingest primitive. * * The raw cells are copied verbatim, sentinels included; the caller @@ -308,34 +284,30 @@ ray_t* ray_vec_append(ray_t* vec, const void* elem) { ray_t* ray_vec_append_raw(ray_t* vec, const void* src, int64_t count) { if (!vec || RAY_IS_ERR(vec)) return vec; - if (vec->type <= 0 || vec->type >= RAY_TYPE_COUNT) + if (!ray_is_vec(vec)) return ray_error("type", "vec_append_raw: expects a concrete vector type, got %s", ray_type_name(vec->type)); if (vec->type == RAY_STR) return ray_error("type", "vec_append_raw: str vectors use ray_str_vec_append, got %s", ray_type_name(vec->type)); if (count < 0) return ray_error("range", "vec_append_raw: count must be non-negative, got %lld", (long long)count); if (count == 0) return vec; if (!src) return ray_error("domain", "vec_append_raw: source pointer is null but count is %lld", (long long)count); + uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); + size_t required; + if (!ray_cell_growth_bytes(vec->len, count, esz, &required)) + return ray_error("oom", NULL); + ray_t* original = vec; vec = ray_cow(vec); if (!vec || RAY_IS_ERR(vec)) return vec; vec_drop_index_inplace(vec); - uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); int64_t cap = vec_capacity(vec); - if (vec->len > INT64_MAX - count) goto fail; if (vec->len + count > cap) { - size_t new_data_size = (size_t)(vec->len + count) * esz; - if (new_data_size < 32) new_data_size = 32; - else { - size_t s = 32; - while (s < new_data_size) { - if (s > SIZE_MAX / 2) goto fail; - s *= 2; - } - new_data_size = s; - } + size_t new_data_size; + if (!ray_cell_growth_request(ray_block_data_bytes(vec), required, &new_data_size)) + goto fail; ray_t* new_vec = ray_scratch_realloc(vec, new_data_size); if (!new_vec || RAY_IS_ERR(new_vec)) { if (vec != original) ray_release(vec); @@ -687,12 +659,13 @@ ray_t* ray_vec_concat(ray_t* a, ray_t* b) { ray_t* ray_vec_insert_at(ray_t* vec, int64_t idx, const void* elem) { if (!vec || RAY_IS_ERR(vec)) return vec; - if (vec->type <= 0 || vec->type >= RAY_TYPE_COUNT) + if (!ray_is_vec(vec)) return ray_error("type", "vec_insert_at: expects a concrete vector type, got %s", ray_type_name(vec->type)); if (vec->type == RAY_STR) return ray_error("type", "vec_insert_at: str vectors use ray_str_vec_insert_at, got %s", ray_type_name(vec->type)); if (idx < 0 || idx > vec->len) return ray_error("range", "vec_insert_at: index out of bounds [0,%lld], got %lld", (long long)vec->len, (long long)idx); /* COW: if shared, copy first */ + uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); ray_t* original = vec; vec = ray_cow(vec); if (!vec || RAY_IS_ERR(vec)) return vec; @@ -701,22 +674,11 @@ ray_t* ray_vec_insert_at(ray_t* vec, int64_t idx, const void* elem) { * accelerator index is now stale. */ vec_drop_index_inplace(vec); - uint8_t esz = ray_sym_elem_size(vec->type, vec->attrs); int64_t cap = vec_capacity(vec); /* Grow if needed */ if (vec->len >= cap) { - size_t new_data_size = (size_t)(vec->len + 1) * esz; - if (new_data_size < 32) new_data_size = 32; - else { - size_t s = 32; - while (s < new_data_size) { - if (s > SIZE_MAX / 2) goto fail_oom; - s *= 2; - } - new_data_size = s; - } - ray_t* new_vec = ray_scratch_realloc(vec, new_data_size); + ray_t* new_vec = ray_cell_grow_one(vec, esz); if (!new_vec || RAY_IS_ERR(new_vec)) { if (vec != original) ray_release(vec); return new_vec ? new_vec : ray_error("oom", NULL); @@ -750,9 +712,6 @@ ray_t* ray_vec_insert_at(ray_t* vec, int64_t idx, const void* elem) { return vec; -fail_oom: - if (vec != original) ray_release(vec); - return ray_error("oom", NULL); } /* -------------------------------------------------------------------------- @@ -807,7 +766,7 @@ ray_t* ray_vec_insert_many(ray_t* vec, ray_t* idxs, ray_t* vals) { if (!vec || RAY_IS_ERR(vec)) return vec; if (!idxs || RAY_IS_ERR(idxs)) return idxs; if (!vals || RAY_IS_ERR(vals)) return vals; - if (vec->type <= 0 || vec->type >= RAY_TYPE_COUNT) return ray_error("type", "vec_insert_many: dest expects a concrete vector type, got %s", ray_type_name(vec->type)); + if (!ray_is_vec(vec)) return ray_error("type", "vec_insert_many: dest expects a concrete vector type, got %s", ray_type_name(vec->type)); if (vec->type == RAY_STR) return ray_error("type", "vec_insert_many: str vectors are unsupported, use ray_vec_insert_vec_at in a loop, got %s", ray_type_name(vec->type)); if (idxs->type != RAY_I64) return ray_error("type", "vec_insert_many: indices must be an i64 vector, got %s", ray_type_name(idxs->type)); @@ -962,7 +921,7 @@ ray_t* ray_vec_insert_many(ray_t* vec, ray_t* idxs, ray_t* vals) { * -------------------------------------------------------------------------- */ ray_t* ray_vec_from_raw(int8_t type, const void* data, int64_t count) { - if (type <= 0 || type >= RAY_TYPE_COUNT) + if (!ray_is_vector_type(type)) return ray_error("type", "vec_from_raw: type must be a positive concrete vector type, got %s", ray_type_name(type)); if (type == RAY_STR) return ray_error("type", "vec_from_raw: str vectors are unsupported (no pool), got %s", ray_type_name(type)); if (count < 0) return ray_error("range", "vec_from_raw: count must be non-negative, got %lld", (long long)count); @@ -1003,7 +962,7 @@ ray_t* ray_vec_from_raw(int8_t type, const void* data, int64_t count) { } break; case RAY_F64: case RAY_F32: - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: case RAY_GUID: for (int64_t i = 0; i < count; i++) { @@ -1064,7 +1023,7 @@ ray_err_t ray_vec_set_null_checked(ray_t* vec, int64_t idx, bool is_null) { switch (vec->type) { case RAY_F64: ((double*)p)[idx] = NULL_F64; break; case RAY_F32: ((float*)p)[idx] = NULL_F32; break; - case RAY_I64: case RAY_TIMESTAMP: ((int64_t*)p)[idx] = NULL_I64; break; + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: ((int64_t*)p)[idx] = NULL_I64; break; case RAY_I32: case RAY_DATE: case RAY_TIME: ((int32_t*)p)[idx] = NULL_I32; break; case RAY_I16: ((int16_t*)p)[idx] = NULL_I16; break; case RAY_SYM: @@ -1152,6 +1111,51 @@ static inline void str_pool_add_dead(ray_t* vec, uint32_t bytes) { memcpy(vec->str_pool->aux, &d, 4); } +/* -------------------------------------------------------------------------- + * ray_str_pool_reserve — room for len more bytes in a STR pool + * + * Creates the pool on first use (a RAY_U8 block of max(256, 2 * len) + * bytes), refuses an end offset above UINT32_MAX (RAY_ERR_RANGE), and + * doubles the block until the bytes fit (RAY_ERR_OOM; a failed grow + * leaves *pool as it was). *off is the offset the bytes go at; the + * caller copies them and advances (*pool)->len. + * -------------------------------------------------------------------------- */ + +static inline ray_err_t str_pool_reserve(ray_t** pool, size_t len, int64_t* off) { + if (!*pool) { + ray_t* p = ray_alloc(len < 256 ? 256 : len * 2); + if (!p || RAY_IS_ERR(p)) return RAY_ERR_OOM; + p->type = RAY_U8; + p->len = 0; + *pool = p; + } + int64_t pool_used = (*pool)->len; + if (pool_used < 0 || (uint64_t)pool_used > UINT32_MAX || + (uint64_t)len > UINT32_MAX - (uint64_t)pool_used) + return RAY_ERR_RANGE; + size_t pool_cap = ray_block_data_bytes(*pool); + size_t need = (size_t)pool_used + len; + if (need > pool_cap) { + size_t new_cap = pool_cap; + if (new_cap == 0) new_cap = 256; + while (new_cap < need) { + if (new_cap > SIZE_MAX / 2) return RAY_ERR_OOM; + new_cap *= 2; + } + ray_t* np = ray_scratch_realloc(*pool, new_cap); + if (!np || RAY_IS_ERR(np)) return RAY_ERR_OOM; + *pool = np; + } + *off = pool_used; + return RAY_OK; +} + +/* Exported for builders outside this file; ray_str_vec_append inlines the + * same body. */ +ray_err_t ray_str_pool_reserve(ray_t** pool, size_t len, int64_t* off) { + return str_pool_reserve(pool, len, off); +} + /* -------------------------------------------------------------------------- * ray_str_vec_append — append a string to a RAY_STR vector * @@ -1164,6 +1168,7 @@ ray_t* ray_str_vec_append(ray_t* vec, const char* s, size_t len) { if (vec->type != RAY_STR) return ray_error("type", "str_vec_append: expects a str vector, got %s", ray_type_name(vec->type)); if (len > UINT32_MAX) return ray_error("range", "str_vec_append: string length exceeds %lld bytes, got %lld", (long long)UINT32_MAX, (long long)len); + ray_t* original = vec; vec = ray_cow(vec); if (!vec || RAY_IS_ERR(vec)) return vec; @@ -1171,52 +1176,15 @@ ray_t* ray_str_vec_append(ray_t* vec, const char* s, size_t len) { int64_t pool_off = 0; if (len > RAY_STR_INLINE_MAX) { - if (!vec->str_pool) { - size_t init_pool = len < 256 ? 256 : len * 2; - vec->str_pool = ray_alloc(init_pool); - if (!vec->str_pool || RAY_IS_ERR(vec->str_pool)) { - vec->str_pool = NULL; - goto fail_oom; - } - vec->str_pool->type = RAY_U8; - vec->str_pool->len = 0; - } - - int64_t pool_used = vec->str_pool->len; - if (pool_used < 0 || (uint64_t)pool_used > UINT32_MAX || - (uint64_t)len > UINT32_MAX - (uint64_t)pool_used) - goto fail_range; - size_t pool_cap = ray_block_data_bytes(vec->str_pool); - size_t need = (size_t)pool_used + len; - if (need > pool_cap) { - size_t new_cap = pool_cap; - if (new_cap == 0) new_cap = 256; - while (new_cap < need) { - if (new_cap > SIZE_MAX / 2) goto fail_oom; - new_cap *= 2; - } - ray_t* np = ray_scratch_realloc(vec->str_pool, new_cap); - if (!np || RAY_IS_ERR(np)) goto fail_oom; - vec->str_pool = np; - } - - pool_off = pool_used; + ray_err_t pe = str_pool_reserve(&vec->str_pool, len, &pool_off); + if (pe == RAY_ERR_RANGE) goto fail_range; + if (pe != RAY_OK) goto fail_oom; } /* Grow element array if needed — pool is already ready */ int64_t cap = vec_capacity(vec); if (vec->len >= cap) { - size_t new_data_size = (size_t)(vec->len + 1) * sizeof(ray_str_t); - if (new_data_size < 32) new_data_size = 32; - else { - size_t s2 = 32; - while (s2 < new_data_size) { - if (s2 > SIZE_MAX / 2) goto fail_oom; - s2 *= 2; - } - new_data_size = s2; - } - ray_t* nv = ray_scratch_realloc(vec, new_data_size); + ray_t* nv = ray_cell_grow_one(vec, sizeof(ray_str_t)); if (!nv || RAY_IS_ERR(nv)) goto fail_oom; vec = nv; } @@ -1612,7 +1580,7 @@ bool ray_vec_is_null(ray_t* vec, int64_t idx) { switch (vec->type) { case RAY_F64: case RAY_F32: - case RAY_I64: case RAY_TIMESTAMP: + case RAY_I64: case RAY_TIMESPAN: case RAY_TIMESTAMP: case RAY_I32: case RAY_DATE: case RAY_TIME: case RAY_I16: case RAY_GUID: diff --git a/src/vec/vec.h b/src/vec/vec.h index 45c38388b..79ae438be 100644 --- a/src/vec/vec.h +++ b/src/vec/vec.h @@ -63,6 +63,16 @@ static inline bool ray_vec_has_nulls(const ray_t* v) { return false; } +/* Sentinel null test on a raw generation-0 element array (range views, + * scan pieces); SYM at the width class in `attrs`. */ +bool ray_raw_is_null(int8_t type, uint8_t attrs, const void* base, int64_t idx); + +/* Room for len more bytes in the STR pool *pool, created on first use and + * grown as ray_str_vec_append grows it: RAY_OK with the bytes' offset in + * *off (the caller copies them and advances (*pool)->len), RAY_ERR_RANGE + * when the end would pass UINT32_MAX, RAY_ERR_OOM (*pool unchanged). */ +ray_err_t ray_str_pool_reserve(ray_t** pool, size_t len, int64_t* off); + /* Copy null bits from src to dst (sentinel-based). dst and src must have * the same length. Internal helper. */ ray_err_t ray_vec_copy_nulls(ray_t* dst, const ray_t* src); diff --git a/test/data/enc/bool_rle.bin b/test/data/enc/bool_rle.bin new file mode 100644 index 000000000..1da7ab91f Binary files /dev/null and b/test/data/enc/bool_rle.bin differ diff --git a/test/data/enc/f32_alp.bin b/test/data/enc/f32_alp.bin new file mode 100644 index 000000000..d8ca78b7e Binary files /dev/null and b/test/data/enc/f32_alp.bin differ diff --git a/test/data/enc/f32_zeros.bin b/test/data/enc/f32_zeros.bin new file mode 100644 index 000000000..33b4ac414 Binary files /dev/null and b/test/data/enc/f32_zeros.bin differ diff --git a/test/data/enc/f64_alp.bin b/test/data/enc/f64_alp.bin new file mode 100644 index 000000000..2c46ab101 Binary files /dev/null and b/test/data/enc/f64_alp.bin differ diff --git a/test/data/enc/f64_alp_trailer.bin b/test/data/enc/f64_alp_trailer.bin new file mode 100644 index 000000000..9ac9ac84e Binary files /dev/null and b/test/data/enc/f64_alp_trailer.bin differ diff --git a/test/data/enc/f64_alprd_len1.bin b/test/data/enc/f64_alprd_len1.bin new file mode 100644 index 000000000..c739ba482 Binary files /dev/null and b/test/data/enc/f64_alprd_len1.bin differ diff --git a/test/data/enc/f64_alprd_len1023.bin b/test/data/enc/f64_alprd_len1023.bin new file mode 100644 index 000000000..6a45ff299 Binary files /dev/null and b/test/data/enc/f64_alprd_len1023.bin differ diff --git a/test/data/enc/f64_const.bin b/test/data/enc/f64_const.bin new file mode 100644 index 000000000..5aa89aecb Binary files /dev/null and b/test/data/enc/f64_const.bin differ diff --git a/test/data/enc/f64_dict_signed.bin b/test/data/enc/f64_dict_signed.bin new file mode 100644 index 000000000..9a0c363b9 Binary files /dev/null and b/test/data/enc/f64_dict_signed.bin differ diff --git a/test/data/enc/f64_rle.bin b/test/data/enc/f64_rle.bin new file mode 100644 index 000000000..e1eb74fa2 Binary files /dev/null and b/test/data/enc/f64_rle.bin differ diff --git a/test/data/enc/f64_trailer.bin b/test/data/enc/f64_trailer.bin new file mode 100644 index 000000000..566bb8baf Binary files /dev/null and b/test/data/enc/f64_trailer.bin differ diff --git a/test/data/enc/guid_mixed.bin b/test/data/enc/guid_mixed.bin new file mode 100644 index 000000000..9a34336cb Binary files /dev/null and b/test/data/enc/guid_mixed.bin differ diff --git a/test/data/enc/i16_all_null.bin b/test/data/enc/i16_all_null.bin new file mode 100644 index 000000000..bdf2dd09c Binary files /dev/null and b/test/data/enc/i16_all_null.bin differ diff --git a/test/data/enc/i16_delta_wT.bin b/test/data/enc/i16_delta_wT.bin new file mode 100644 index 000000000..16a69a0e0 Binary files /dev/null and b/test/data/enc/i16_delta_wT.bin differ diff --git a/test/data/enc/i32_delta_wT.bin b/test/data/enc/i32_delta_wT.bin new file mode 100644 index 000000000..ee0c8c129 Binary files /dev/null and b/test/data/enc/i32_delta_wT.bin differ diff --git a/test/data/enc/i32_for.bin b/test/data/enc/i32_for.bin new file mode 100644 index 000000000..77e46af07 Binary files /dev/null and b/test/data/enc/i32_for.bin differ diff --git a/test/data/enc/i32_nulls.bin b/test/data/enc/i32_nulls.bin new file mode 100644 index 000000000..c4de6abd7 Binary files /dev/null and b/test/data/enc/i32_nulls.bin differ diff --git a/test/data/enc/i32_two_chunks.bin b/test/data/enc/i32_two_chunks.bin new file mode 100644 index 000000000..ce25d40d8 Binary files /dev/null and b/test/data/enc/i32_two_chunks.bin differ diff --git a/test/data/enc/i64_const.bin b/test/data/enc/i64_const.bin new file mode 100644 index 000000000..3967cb946 Binary files /dev/null and b/test/data/enc/i64_const.bin differ diff --git a/test/data/enc/i64_delta.bin b/test/data/enc/i64_delta.bin new file mode 100644 index 000000000..8d96a1fea Binary files /dev/null and b/test/data/enc/i64_delta.bin differ diff --git a/test/data/enc/i64_delta_wT.bin b/test/data/enc/i64_delta_wT.bin new file mode 100644 index 000000000..1e7d67316 Binary files /dev/null and b/test/data/enc/i64_delta_wT.bin differ diff --git a/test/data/enc/i64_dict.bin b/test/data/enc/i64_dict.bin new file mode 100644 index 000000000..9ea496946 Binary files /dev/null and b/test/data/enc/i64_dict.bin differ diff --git a/test/data/enc/i64_dict_codes_raw.bin b/test/data/enc/i64_dict_codes_raw.bin new file mode 100644 index 000000000..9c202faf2 Binary files /dev/null and b/test/data/enc/i64_dict_codes_raw.bin differ diff --git a/test/data/enc/i64_dict_codes_rle.bin b/test/data/enc/i64_dict_codes_rle.bin new file mode 100644 index 000000000..986d9f9de Binary files /dev/null and b/test/data/enc/i64_dict_codes_rle.bin differ diff --git a/test/data/enc/i64_dict_const_child.bin b/test/data/enc/i64_dict_const_child.bin new file mode 100644 index 000000000..df3d368c8 Binary files /dev/null and b/test/data/enc/i64_dict_const_child.bin differ diff --git a/test/data/enc/i64_empty.bin b/test/data/enc/i64_empty.bin new file mode 100644 index 000000000..d6f268475 Binary files /dev/null and b/test/data/enc/i64_empty.bin differ diff --git a/test/data/enc/i64_rle_ends_delta.bin b/test/data/enc/i64_rle_ends_delta.bin new file mode 100644 index 000000000..aa285f8bd Binary files /dev/null and b/test/data/enc/i64_rle_ends_delta.bin differ diff --git a/test/data/enc/i64_rle_ends_for.bin b/test/data/enc/i64_rle_ends_for.bin new file mode 100644 index 000000000..836c6fe70 Binary files /dev/null and b/test/data/enc/i64_rle_ends_for.bin differ diff --git a/test/data/enc/i64_rle_values_for.bin b/test/data/enc/i64_rle_values_for.bin new file mode 100644 index 000000000..f925018ad Binary files /dev/null and b/test/data/enc/i64_rle_values_for.bin differ diff --git a/test/data/enc/idx_bloom_i64.bin b/test/data/enc/idx_bloom_i64.bin new file mode 100644 index 000000000..356688070 Binary files /dev/null and b/test/data/enc/idx_bloom_i64.bin differ diff --git a/test/data/enc/idx_dict_str.bin b/test/data/enc/idx_dict_str.bin new file mode 100644 index 000000000..00ad090c8 Binary files /dev/null and b/test/data/enc/idx_dict_str.bin differ diff --git a/test/data/enc/idx_hash_i64.bin b/test/data/enc/idx_hash_i64.bin new file mode 100644 index 000000000..fe0b5a9e1 Binary files /dev/null and b/test/data/enc/idx_hash_i64.bin differ diff --git a/test/data/enc/idx_hash_str.bin b/test/data/enc/idx_hash_str.bin new file mode 100644 index 000000000..3d94071f6 Binary files /dev/null and b/test/data/enc/idx_hash_str.bin differ diff --git a/test/data/enc/idx_hash_sym.bin b/test/data/enc/idx_hash_sym.bin new file mode 100644 index 000000000..a37979372 Binary files /dev/null and b/test/data/enc/idx_hash_sym.bin differ diff --git a/test/data/enc/idx_hash_unique.bin b/test/data/enc/idx_hash_unique.bin new file mode 100644 index 000000000..32f6e0b1a Binary files /dev/null and b/test/data/enc/idx_hash_unique.bin differ diff --git a/test/data/enc/idx_part_f64.bin b/test/data/enc/idx_part_f64.bin new file mode 100644 index 000000000..3c909d32b Binary files /dev/null and b/test/data/enc/idx_part_f64.bin differ diff --git a/test/data/enc/idx_part_i64.bin b/test/data/enc/idx_part_i64.bin new file mode 100644 index 000000000..7a54182e7 Binary files /dev/null and b/test/data/enc/idx_part_i64.bin differ diff --git a/test/data/enc/idx_part_order.bin b/test/data/enc/idx_part_order.bin new file mode 100644 index 000000000..f90dd77a9 Binary files /dev/null and b/test/data/enc/idx_part_order.bin differ diff --git a/test/data/enc/idx_part_sym.bin b/test/data/enc/idx_part_sym.bin new file mode 100644 index 000000000..3a0393ad2 Binary files /dev/null and b/test/data/enc/idx_part_sym.bin differ diff --git a/test/data/enc/idx_sort_i32.bin b/test/data/enc/idx_sort_i32.bin new file mode 100644 index 000000000..620a44763 Binary files /dev/null and b/test/data/enc/idx_sort_i32.bin differ diff --git a/test/data/enc/str_const.bin b/test/data/enc/str_const.bin new file mode 100644 index 000000000..94f01e514 Binary files /dev/null and b/test/data/enc/str_const.bin differ diff --git a/test/data/enc/str_dict.bin b/test/data/enc/str_dict.bin new file mode 100644 index 000000000..88a2a66f3 Binary files /dev/null and b/test/data/enc/str_dict.bin differ diff --git a/test/data/enc/str_dict_codes_rle.bin b/test/data/enc/str_dict_codes_rle.bin new file mode 100644 index 000000000..fb058c43e Binary files /dev/null and b/test/data/enc/str_dict_codes_rle.bin differ diff --git a/test/data/enc/str_fsst.bin b/test/data/enc/str_fsst.bin new file mode 100644 index 000000000..bc62b86e3 Binary files /dev/null and b/test/data/enc/str_fsst.bin differ diff --git a/test/data/enc/str_inline.bin b/test/data/enc/str_inline.bin new file mode 100644 index 000000000..7bf598d01 Binary files /dev/null and b/test/data/enc/str_inline.bin differ diff --git a/test/data/enc/str_mixed.bin b/test/data/enc/str_mixed.bin new file mode 100644 index 000000000..9234eb7c7 Binary files /dev/null and b/test/data/enc/str_mixed.bin differ diff --git a/test/data/enc/str_pooled.bin b/test/data/enc/str_pooled.bin new file mode 100644 index 000000000..3e87b853e Binary files /dev/null and b/test/data/enc/str_pooled.bin differ diff --git a/test/data/enc/str_repeated.bin b/test/data/enc/str_repeated.bin new file mode 100644 index 000000000..6afe7457b Binary files /dev/null and b/test/data/enc/str_repeated.bin differ diff --git a/test/data/enc/sym_w32_rle.bin b/test/data/enc/sym_w32_rle.bin new file mode 100644 index 000000000..eccc08967 Binary files /dev/null and b/test/data/enc/sym_w32_rle.bin differ diff --git a/test/data/enc/sym_w8_for.bin b/test/data/enc/sym_w8_for.bin new file mode 100644 index 000000000..d2772647d Binary files /dev/null and b/test/data/enc/sym_w8_for.bin differ diff --git a/test/data/enc/u8_raw.bin b/test/data/enc/u8_raw.bin new file mode 100644 index 000000000..41da91ec1 Binary files /dev/null and b/test/data/enc/u8_raw.bin differ diff --git a/test/main.c b/test/main.c index fb49f13be..c667a273a 100644 --- a/test/main.c +++ b/test/main.c @@ -35,6 +35,7 @@ #include "test.h" #include "ops/agg_engine.h" /* --census: agg_route_stats */ +#include "core/pool.h" /* ray_pool_test_ring_fail */ #include "test_rfl.h" #include @@ -51,6 +52,10 @@ #include "ops/internal.h" #include "ops/idxop.h" #include "store/fileio.h" /* ray_mkdir_p — ray_test_mkdir_p */ +#include "store/col.h" /* ray_store_test_force_compress — equivalence pass */ +#include "store/enccol.h" /* ray_test_hooks_off */ +#include "store/encw.h" +#include "ops/colbind.h" /* __RUNTIME is internal test plumbing; runtime API declarations come from * . */ @@ -161,7 +166,23 @@ extern const test_entry_t sel_entries[]; extern const test_entry_t select_merge_entries[]; extern const test_entry_t sort_entries[]; extern const test_entry_t splay_entries[]; +extern const test_entry_t srccheck_entries[]; extern const test_entry_t store_entries[]; +extern const test_entry_t idx_uses_entries[]; +extern const test_entry_t enc_entries[]; +extern const test_entry_t encfmt_entries[]; +extern const test_entry_t encidx_entries[]; +extern const test_entry_t encfloat_entries[]; +extern const test_entry_t encstr_entries[]; +extern const test_entry_t enconce_entries[]; +extern const test_entry_t enccol_entries[]; +extern const test_entry_t large_entries[]; +extern const test_entry_t colrange_entries[]; +extern const test_entry_t scanrange_entries[]; +extern const test_entry_t aware_entries[]; +extern const test_entry_t parted_ragged_entries[]; +extern const test_entry_t compress_entries[]; +extern const test_entry_t fsst_entries[]; extern const test_entry_t stress_eval_entries[]; extern const test_entry_t stress_matrix_entries[]; extern const test_entry_t stress_random_entries[]; @@ -205,7 +226,16 @@ static const test_entry_t* const compiled_groups[] = { pool_entries, progress_entries, public_api_entries, repl_entries, rowsel_entries, runtime_entries, sel_entries, select_merge_entries, - sort_entries, splay_entries, store_entries, + sort_entries, splay_entries, srccheck_entries, store_entries, enc_entries, + encfmt_entries, encidx_entries, encfloat_entries, encstr_entries, enconce_entries, enccol_entries, + large_entries, + colrange_entries, + scanrange_entries, + aware_entries, + parted_ragged_entries, + compress_entries, + idx_uses_entries, + fsst_entries, stress_eval_entries, stress_matrix_entries, stress_random_entries, @@ -366,6 +396,8 @@ static ray_t* rfl_eval(const char* src, const char* path, int line_no) { return v; } +static char* tmp_subst(const char* s); /* the per-process /tmp rewrite, below */ + static test_result_t run_rfl_file(const char* path) { FILE* f = fopen(path, "rb"); if (!f) FAILF("cannot open %s", path); @@ -378,6 +410,9 @@ static test_result_t run_rfl_file(const char* path) { size_t r = fread(src, 1, (size_t)n, f); src[r] = '\0'; fclose(f); + /* every "/tmp" path the file names moves under this process's root */ + char* moved = tmp_subst(src); + if (moved) { free(src); src = moved; } /* ";; @requires: posix" anywhere in a file marks it as depending on a * POSIX shell / filesystem (.sys.exec pipelines, /proc). Where that @@ -388,6 +423,13 @@ static test_result_t run_rfl_file(const char* path) { SKIP("requires POSIX shell/filesystem"); } #endif + /* ";; @requires: linux": Linux-only facilities (taskset, cgroups). */ +#if !defined(__linux__) + if (strstr(src, ";; @requires: linux")) { + free(src); + SKIP("requires Linux"); + } +#endif int line_no = 0; int assert_count = 0; /* tallies LHS -- RHS and EXPR !- SUBSTR lines */ @@ -888,6 +930,113 @@ int ray_test_mkdir_p(const char* path) { return ray_mkdir_p(path) == RAY_OK ? 0 : -1; } +void ray_test_hooks_off(void) { + ray_enccol_test_fail_alloc(0); + ray_enccol_test_fail_path(NULL); + ray_enccol_test_interrupt_after(0); + ray_enccol_test_parted_mode(0); + ray_enccol_test_fail_index_parse(false); + ray_col_test_fail_alloc(0); + ray_col_test_no_dict(false); + ray_encw_test_force(-1); + ray_encw_test_force_float(-1); + ray_encw_test_force_str(-1); + ray_graph_bind_test_fail_alloc(0); + ray_store_test_force_compress(false); + ray_idx_lazy_test_fail_build(NULL); + ray_expr_test_parted_all_segments(false); + ray_group_test_route(0); + ray_group_test_fail_scalar_alloc(0); + ray_group_test_scalar_grain(0); + ray_pool_test_ring_fail(0); + agg_test_force_smallhash(false); + agg_test_no_wide_dense(false); + ray_clear_interrupt(); +} + +/* ---- Per-process scratch root (declared in test.h) ---- */ + +static char g_tmp_root[64]; /* "/tmp/rayforce_t.", set in main() */ +static size_t g_tmp_root_len; + +/* A "/tmp" path starts at s[i]: "/tmp" as a whole path component, not part + * of a longer name ("/var/tmp", "/tmpx"), and not already under the root. */ +static bool tmp_hit(const char* s, size_t n, size_t i) { + if (i + 4 > n || memcmp(s + i, "/tmp", 4) != 0) return false; + if (i > 0) { + char c = s[i - 1]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '_' || c == '.' || c == '-' || c == '/' || c == '~') return false; + } + char r = s[i + 4]; + if (!(r == '/' || r == '\0' || r == '"' || r == '\\' || r == '\'' || r == ' ' || + r == ')' || r == ';' || r == '\n' || r == '\t')) return false; + bool under_root = strncmp(s + i, g_tmp_root, g_tmp_root_len) == 0 && + (s[i + g_tmp_root_len] == '/' || s[i + g_tmp_root_len] == '\0'); + return !under_root; +} + +/* The rewrite of `s` (malloc'd), or NULL when `s` names no "/tmp" path or + * the root is not set yet. */ +static char* tmp_subst(const char* s) { + if (!g_tmp_root_len || !s) return NULL; + size_t n = strlen(s), hits = 0; + for (size_t i = 0; i < n; i++) if (tmp_hit(s, n, i)) hits++; + if (!hits) return NULL; + char* out = (char*)malloc(n + hits * g_tmp_root_len + 1); + if (!out) { fprintf(stderr, "ray_test_tmp: out of memory\n"); abort(); } + size_t o = 0; + for (size_t i = 0; i < n; ) { + if (tmp_hit(s, n, i)) { memcpy(out + o, g_tmp_root, g_tmp_root_len); o += g_tmp_root_len; i += 4; } + else out[o++] = s[i++]; + } + out[o] = '\0'; + return out; +} + +/* Interned results: an open-addressed table keyed by the argument's text. */ +typedef struct { char* key; char* val; } tmp_ent_t; +static tmp_ent_t* g_tmp_tab; +static size_t g_tmp_cap, g_tmp_n; + +static size_t tmp_hash(const char* s) { + uint64_t h = 1469598103934665603ull; + for (; *s; s++) h = (h ^ (unsigned char)*s) * 1099511628211ull; + return (size_t)h; +} +static char* tmp_strdup(const char* s) { + size_t n = strlen(s) + 1; + char* d = (char*)malloc(n); + if (!d) { fprintf(stderr, "ray_test_tmp: out of memory\n"); abort(); } + return memcpy(d, s, n); +} + +const char* ray_test_tmp(const char* s) { + if (!s) return s; + if (g_tmp_n * 2 >= g_tmp_cap) { + size_t ncap = g_tmp_cap ? g_tmp_cap * 2 : 1024; + tmp_ent_t* nt = (tmp_ent_t*)calloc(ncap, sizeof *nt); + if (!nt) { fprintf(stderr, "ray_test_tmp: out of memory\n"); abort(); } + for (size_t i = 0; i < g_tmp_cap; i++) { + if (!g_tmp_tab[i].key) continue; + size_t j = tmp_hash(g_tmp_tab[i].key) & (ncap - 1); + while (nt[j].key) j = (j + 1) & (ncap - 1); + nt[j] = g_tmp_tab[i]; + } + free(g_tmp_tab); g_tmp_tab = nt; g_tmp_cap = ncap; + } + size_t j = tmp_hash(s) & (g_tmp_cap - 1); + while (g_tmp_tab[j].key) { + if (strcmp(g_tmp_tab[j].key, s) == 0) return g_tmp_tab[j].val; + j = (j + 1) & (g_tmp_cap - 1); + } + char* v = tmp_subst(s); + g_tmp_tab[j].key = tmp_strdup(s); + g_tmp_tab[j].val = v ? v : g_tmp_tab[j].key; + g_tmp_n++; + return g_tmp_tab[j].val; +} + #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX @@ -909,6 +1058,58 @@ long ray_test_sysconf(int name) { } #endif +/* ─── Equivalence pass ──────────────────────────────────────────────── + * Every save in these tests is written as generation 2 (absent compress + * behaves as true) and every load reads it back: results must equal the + * generation-0 run. An assert on a generation-0 property (mapped-in-place + * residency, an auto-built persisted index, header bytes) is written + * generation-aware (TEST_ASSERT_LOADED_MMOD, a header check, or an explicit + * {compress: false} save) so the rest of the test still runs here; a test + * that cannot run twice in one process is listed in equiv_skip with the + * reason. Anything else that differs is a bug in the generation-2 path, + * never a test change. */ +static const char* const equiv_skip[] = { + /* runs its own heap lifecycle and leaks a domain into the process-wide + * cache on purpose: a second run in the same process (this pass) opens + * no domain. It saves a symbol file only, no table. */ + "equiv/domain/survives_heap_recycle", + NULL, +}; + +static bool equiv_skipped(const char* name) { + for (int i = 0; equiv_skip[i]; i++) if (strcmp(equiv_skip[i], name) == 0) return true; + return false; +} + +static bool rfl_file_saves(const char* path) { + static const char* const forms[] = { ".db.splayed.set", ".csv.splayed", ".csv.parted", + ".parquet.splayed", ".parquet.parted", NULL }; + FILE* f = fopen(path, "rb"); + if (!f) return false; + static char buf[1 << 20]; + size_t n = fread(buf, 1, sizeof buf - 1, f); + fclose(f); + buf[n] = '\0'; + for (int i = 0; forms[i]; i++) if (strstr(buf, forms[i])) return true; + return false; +} + +static const test_entry_t* g_equiv_inner; +static bool g_equiv_on; +bool ray_test_equiv_pass(void) { return g_equiv_on; } +static void equiv_c_setup(void) { + if (g_equiv_inner->setup) g_equiv_inner->setup(); + ray_store_test_force_compress(true); + g_equiv_on = true; +} +static void equiv_c_teardown(void) { + g_equiv_on = false; + ray_store_test_force_compress(false); + if (g_equiv_inner->teardown) g_equiv_inner->teardown(); +} +static void equiv_rfl_setup(void) { rfl_setup(); ray_store_test_force_compress(true); g_equiv_on = true; } +static void equiv_rfl_teardown(void) { g_equiv_on = false; ray_store_test_force_compress(false); rfl_teardown(); } + int main(int argc, char** argv) { #if defined(_WIN32) (void)_mkdir("/tmp"); /* tests use "/tmp/..." paths (see test.h) */ @@ -937,6 +1138,10 @@ int main(int argc, char** argv) { } if (g_census) setvbuf(g_census, NULL, _IOLBF, 0); /* closed by the OS at exit; lines land as written */ + snprintf(g_tmp_root, sizeof g_tmp_root, "/tmp/rayforce_t.%ld", (long)getpid()); + (void)ray_test_rm_rf(g_tmp_root); /* a dead run's leftovers under a reused pid */ + if (ray_test_mkdir_p(g_tmp_root) != 0) { fprintf(stderr, "cannot create %s\n", g_tmp_root); return 2; } + g_tmp_root_len = strlen(g_tmp_root); const char* rfl_root = getenv("RFL_ROOT"); if (!rfl_root || !*rfl_root) rfl_root = "test/rfl"; if (rfl_scan(rfl_root) < 0) return 2; @@ -948,6 +1153,9 @@ int main(int argc, char** argv) { const test_entry_t* g = compiled_groups[gi]; for (int i = 0; g[i].name; i++) { if (!name_matches_filter(g[i].name, filter)) continue; + /* large/ tests need several GiB of RAM and disk: only on request */ + if (strncmp(g[i].name, "large/", 6) == 0 && + !(filter && strncmp(filter, "large/", 6) == 0)) continue; total++; run_one(&g[i], &pass, &fail, &skip); } @@ -966,6 +1174,39 @@ int main(int argc, char** argv) { run_one(&e, &pass, &fail, &skip); } + /* Equivalence pass: C groups that save and reload tables, then every + * .rfl file that saves one. */ + static const test_entry_t* const equiv_groups[] = { + splay_entries, store_entries, partition_exec_entries, link_entries, + /* query-heavy groups that save tables */ + stress_eval_entries, stress_matrix_entries, stress_random_entries, + lang_entries, index_entries, csr_entries, domain_entries, sym_entries, + NULL, + }; + char ename[600]; + for (int gi = 0; equiv_groups[gi]; gi++) { + for (int i = 0; equiv_groups[gi][i].name; i++) { + snprintf(ename, sizeof ename, "equiv/%s", equiv_groups[gi][i].name); + if (!name_matches_filter(ename, filter) || equiv_skipped(ename)) continue; + g_equiv_inner = &equiv_groups[gi][i]; + test_entry_t e = { .name = ename, .func = equiv_groups[gi][i].func, + .setup = equiv_c_setup, .teardown = equiv_c_teardown }; + total++; + run_one(&e, &pass, &fail, &skip); + } + } + for (int i = 0; i < g_rfl_count; i++) { + snprintf(ename, sizeof ename, "equiv/%s", g_rfl_names[i]); + if (!name_matches_filter(ename, filter) || equiv_skipped(ename)) continue; + if (!rfl_file_saves(g_rfl_paths[i])) continue; + test_entry_t e = { .name = ename, .func = rfl_thunks[i], + .setup = equiv_rfl_setup, .teardown = equiv_rfl_teardown }; + total++; + run_one(&e, &pass, &fail, &skip); + } + + (void)ray_test_rm_rf(g_tmp_root); + printf("\n%s=== %d of %d passed (%d skipped, %d failed) ===%s\n", fail ? C_RED : (skip ? C_YELLOW : C_GREEN), pass, total, skip, fail, C_RESET); diff --git a/test/rfl/agg/minmax_dyadic.rfl b/test/rfl/agg/minmax_dyadic.rfl new file mode 100644 index 000000000..f217b5262 --- /dev/null +++ b/test/rfl/agg/minmax_dyadic.rfl @@ -0,0 +1,56 @@ +;; Dyadic (min a b) / (max a b): element-wise, null lowest, and the result +;; takes the promoted type of the operands whichever one is chosen (an +;; integer against a boolean is an integer, against a float a float). + +;; ── the result type does not depend on which operand wins ─────────── +(min 1 2.5) -- 1.0 +(type (min 1 2.5)) -- 'f64 +(type (max 3 2.5)) -- 'f64 +(min true 3) -- 1 +(type (min true 3)) -- 'i64 +(max false 0) -- 0 +(min [2 0] true) -- [1 0] +(type (min [2 0] true)) -- 'I64 +(min [2 0] [true true]) -- [1 0] +(max (as 'U8 [1 9]) (as 'I16 [5 5])) -- (as 'I16 [5 9]) +(type (max (as 'U8 [1 9]) (as 'I16 [5 5]))) -- 'I16 + +;; a scalar wider than the vector is not narrowed to the vector's type, +;; whichever side it is on +(max 300 (as 'U8 [1 2])) -- [300 300] +(max (as 'U8 [1 2]) 300) -- [300 300] +(min -5 (as 'U8 [1 2])) -- [-5 -5] +(min 1 (as 'U8 [5 0])) -- [1 0] + +;; same types are unchanged +(min [3 9 1] [2 10 4]) -- [2 9 1] +(max [3 9 1] 5) -- [5 9 5] +(min 'a 'b) -- 'a +(max [true false] false) -- [true false] + +;; DATE against TIMESTAMP gives a TIMESTAMP +(type (max 2024.01.02 (as 'TIMESTAMP 2024.01.01))) -- 'timestamp +(max 2024.01.02 (as 'TIMESTAMP 2024.01.01)) -- (as 'TIMESTAMP 2024.01.02) +(type (min (as 'DATE [2024.01.02]) (as 'TIMESTAMP 2024.01.01))) -- 'TIMESTAMP + +;; nulls stay lowest, and promote with the result +(min 0Nl 1) -- 0Nl +(max 0Nl 1) -- 1 +(min 0Nl 1.5) -- 0Nf +(max 0Nf 1) -- 1.0 +(min [0Nl 1] 0) -- [0Nl 0] +(max [0Nf 2.0] 1) -- [1.0 2.0] + +;; ── over a LIST, uniform results make a vector ────────────────────── +(min (list 1 2) 1) -- [1 1] +(type (max (list 1 2) 1)) -- 'I64 +(max (list 1 2) (list 3 0)) -- [3 2] +;; results of different types stay a LIST +(max (list 1 2.0) 1) -- (list 1 2.0) +;; a nested LIST keeps its shape +(min (list [1 5] [3 0]) 2) -- (list [1 2] [2 0]) + +;; ── errors ────────────────────────────────────────────────────────── +(min [1 2] [1 2 3]) !- length +(min 1 'a) !- type +(max [1 2] [1 2 3]) !- length diff --git a/test/rfl/agg/parted_f64_agg.rfl b/test/rfl/agg/parted_f64_agg.rfl index da76aa4a7..55e44913d 100644 --- a/test/rfl/agg/parted_f64_agg.rfl +++ b/test/rfl/agg/parted_f64_agg.rfl @@ -150,5 +150,110 @@ (sum (at Pl 'l)) !- type (count (select {r: ((fn [c] (sum (first (list c)))) 'l) from: Pl})) -- 3 +;; ─── parted two-input aggregates (#730, #780) ──────────────────────── +;; wsum/wavg/cov/scov/pearson_corr over a parted table go through the +;; concat fallback, which flattens only the columns the group references. +;; A column used ONLY as the second input (agg_ins2) used to be left out, +;; so the aggregate read it as missing (0.0 / 0Nf / garbage). +(.sys.exec "rm -rf /tmp/rfl_agg_pbin /tmp/rfl_agg_pbinw") +(.db.splayed.set "/tmp/rfl_agg_pbinw/2024.01.01/t/" (table [a b] (list [1 2 3] [10.0 20.0 30.0]))) +(.db.splayed.set "/tmp/rfl_agg_pbinw/2024.01.02/t/" (table [a b] (list [4 5] [40.0 50.0]))) +(set Pbw (.db.parted.get "/tmp/rfl_agg_pbinw/" 't)) +(first (at (select {w: (wavg a b) from: Pbw}) 'w)) -- (wavg [1 2 3 4 5] [10.0 20.0 30.0 40.0 50.0]) +(at (select {w: (wsum a b) from: Pbw}) 'w) -- [550.0] +(first (at (select {w: (wavg a b) from: Pbw where: (> a 1)}) 'w)) -- (wavg [2 3 4 5] [20.0 30.0 40.0 50.0]) +(set mkbin (fn [lo n] (do (set i (+ lo (til n))) (table [w x y] (list (% i 7) (as 'F64 (% (* i 13) 101)) (as 'I64 (% (* i 7) 53))))))) +(.db.splayed.set "/tmp/rfl_agg_pbin/1/t/" (mkbin 0 300)) +(.db.splayed.set "/tmp/rfl_agg_pbin/2/t/" (mkbin 300 300)) +(.db.splayed.set "/tmp/rfl_agg_pbin/3/t/" (mkbin 600 300)) +(set Pb (.db.parted.get "/tmp/rfl_agg_pbin/" 't)) +(set Fb (concat (concat (mkbin 0 300) (mkbin 300 300)) (mkbin 600 300))) +;; grouped: x is referenced only as the second input in each select +(at (select {c: (wsum y x) from: Pb by: w asc: w}) 'c) -- (at (select {c: (wsum y x) from: Fb by: w asc: w}) 'c) +(at (select {c: (wavg y x) from: Pb by: w asc: w}) 'c) -- (at (select {c: (wavg y x) from: Fb by: w asc: w}) 'c) +(< (max (abs (- (at (select {c: (cov y x) from: Pb by: w asc: w}) 'c) (at (select {c: (cov y x) from: Fb by: w asc: w}) 'c)))) 0.000001) -- true +(< (max (abs (- (at (select {c: (scov y x) from: Pb by: w asc: w}) 'c) (at (select {c: (scov y x) from: Fb by: w asc: w}) 'c)))) 0.000001) -- true +;; pearson_corr read a missing x as all 0Nf, and (< 0Nf eps) is true — the +;; tolerance compare alone cannot fail, so pin non-null first. +(set PcP (at (select {c: (pearson_corr y x) from: Pb by: w asc: w}) 'c)) +(set PcF (at (select {c: (pearson_corr y x) from: Fb by: w asc: w}) 'c)) +(any (nil? PcF)) -- false +(any (nil? PcP)) -- false +(< (max (abs (- PcP PcF))) 0.000001) -- true +(at (select {c: (wsum y x) from: Pb where: (> w 2) by: w asc: w}) 'c) -- (at (select {c: (wsum y x) from: Fb where: (> w 2) by: w asc: w}) 'c) +;; ungrouped +(at (select {c: (wsum y x) from: Pb}) 'c) -- (at (select {c: (wsum y x) from: Fb}) 'c) +(at (select {c: (wavg y x) from: Pb}) 'c) -- (at (select {c: (wavg y x) from: Fb}) 'c) +(set PuP (first (at (select {c: (pearson_corr y x) from: Pb}) 'c))) +(set PuF (first (at (select {c: (pearson_corr y x) from: Fb}) 'c))) +(nil? PuF) -- false +(nil? PuP) -- false +(< (abs (- PuP PuF)) 0.000001) -- true +;; second operand an EXPRESSION over a column referenced nowhere else: the +;; optimizer's liveness/DCE passes walked agg_ins but not agg_ins2, so that +;; subtree was marked dead, its source column was left out of the parted +;; flatten and the select failed with `schema`. Oracle: the same aggregate +;; over a flat table holding the expression as a plain column x2. +(set Fx (table [w y x2] (list (at Fb 'w) (at Fb 'y) (* (at Fb 'x) 2.0)))) +(set Wk (at (select {c: (wsum y x2) from: Fx by: w asc: w}) 'c)) +(set Ak (at (select {c: (wavg y x2) from: Fx by: w asc: w}) 'c)) +(set Ck (at (select {c: (cov y x2) from: Fx by: w asc: w}) 'c)) +(set Rk (at (select {c: (pearson_corr y x2) from: Fx by: w asc: w}) 'c)) +(any (nil? Ck)) -- false +(any (nil? Rk)) -- false +;; grouped, flat +(at (select {c: (wsum y (* x 2.0)) from: Fb by: w asc: w}) 'c) -- Wk +(at (select {c: (wavg y (* x 2.0)) from: Fb by: w asc: w}) 'c) -- Ak +(< (max (abs (- (at (select {c: (cov y (* x 2.0)) from: Fb by: w asc: w}) 'c) Ck))) 0.000001) -- true +(< (max (abs (- (at (select {c: (pearson_corr y (* x 2.0)) from: Fb by: w asc: w}) 'c) Rk))) 0.000001) -- true +;; grouped, parted +(at (select {c: (wsum y (* x 2.0)) from: Pb by: w asc: w}) 'c) -- Wk +(at (select {c: (wavg y (* x 2.0)) from: Pb by: w asc: w}) 'c) -- Ak +(set CkP (at (select {c: (cov y (* x 2.0)) from: Pb by: w asc: w}) 'c)) +(set RkP (at (select {c: (pearson_corr y (* x 2.0)) from: Pb by: w asc: w}) 'c)) +(any (nil? CkP)) -- false +(any (nil? RkP)) -- false +(< (max (abs (- CkP Ck))) 0.000001) -- true +(< (max (abs (- RkP Rk))) 0.000001) -- true +;; keyless, flat and parted +(set Wu (at (select {c: (wsum y x2) from: Fx}) 'c)) +(set Au (at (select {c: (wavg y x2) from: Fx}) 'c)) +(set Cu (first (at (select {c: (cov y x2) from: Fx}) 'c))) +(set Ru (first (at (select {c: (pearson_corr y x2) from: Fx}) 'c))) +(nil? Cu) -- false +(nil? Ru) -- false +(at (select {c: (wsum y (* x 2.0)) from: Fb}) 'c) -- Wu +(at (select {c: (wavg y (* x 2.0)) from: Fb}) 'c) -- Au +(< (abs (- (first (at (select {c: (cov y (* x 2.0)) from: Fb}) 'c)) Cu)) 0.000001) -- true +(< (abs (- (first (at (select {c: (pearson_corr y (* x 2.0)) from: Fb}) 'c)) Ru)) 0.000001) -- true +(at (select {c: (wsum y (* x 2.0)) from: Pb}) 'c) -- Wu +(at (select {c: (wavg y (* x 2.0)) from: Pb}) 'c) -- Au +(set CuP (first (at (select {c: (cov y (* x 2.0)) from: Pb}) 'c))) +(set RuP (first (at (select {c: (pearson_corr y (* x 2.0)) from: Pb}) 'c))) +(nil? CuP) -- false +(nil? RuP) -- false +(< (abs (- CuP Cu)) 0.000001) -- true +(< (abs (- RuP Ru)) 0.000001) -- true +;; a constant second operand — literal or constant-folded once the folder +;; reaches agg_ins2 — is an atom; the pair loops indexed it per row (garbage) +;; until it was broadcast like a constant first operand. +(set Sy (* 6.0 (at (select {c: (sum y) from: Fb by: w asc: w}) 'c))) +(at (select {c: (wsum y 6.0) from: Fb by: w asc: w}) 'c) -- Sy +(at (select {c: (wsum y (* 2.0 3.0)) from: Fb by: w asc: w}) 'c) -- Sy +(at (select {c: (wsum y 6.0) from: Pb by: w asc: w}) 'c) -- Sy +(at (select {c: (wsum y (* 2.0 3.0)) from: Pb by: w asc: w}) 'c) -- Sy +(at (select {c: (wavg y 6.0) from: Fb by: w asc: w}) 'c) -- [6.0 6.0 6.0 6.0 6.0 6.0 6.0] +(first (at (select {c: (wsum y 6.0) from: Fb}) 'c)) -- (sum Sy) +(first (at (select {c: (wsum y 6.0) from: Pb}) 'c)) -- (sum Sy) +;; ungrouped over > RAY_PARALLEL_THRESHOLD rows: the keyless group takes the +;; radix emit, whose key-column VLAs were sized n_keys == 0 (UBSan abort). +(.sys.exec "rm -rf /tmp/rfl_agg_pbin") +(.db.splayed.set "/tmp/rfl_agg_pbin/1/t/" (mkbin 0 40000)) +(.db.splayed.set "/tmp/rfl_agg_pbin/2/t/" (mkbin 40000 40000)) +(set Pb (.db.parted.get "/tmp/rfl_agg_pbin/" 't)) +(set Fb (concat (mkbin 0 40000) (mkbin 40000 40000))) +(at (select {c: (wsum y x) from: Pb}) 'c) -- (at (select {c: (wsum y x) from: Fb}) 'c) +(at (select {c: (wavg y x) from: Pb}) 'c) -- (at (select {c: (wavg y x) from: Fb}) 'c) + ;; ─── cleanup ───────────────────────────────────────────────────────── -(.sys.exec "rm -rf /tmp/rfl_agg_pf64 /tmp/rfl_agg_pf64b /tmp/rfl_agg_pf64g /tmp/rfl_agg_pi64 /tmp/rfl_agg_pwrap /tmp/rfl_agg_pdate /tmp/rfl_agg_pts /tmp/rfl_agg_plist") +(.sys.exec "rm -rf /tmp/rfl_agg_pf64 /tmp/rfl_agg_pf64b /tmp/rfl_agg_pf64g /tmp/rfl_agg_pi64 /tmp/rfl_agg_pwrap /tmp/rfl_agg_pdate /tmp/rfl_agg_pts /tmp/rfl_agg_plist /tmp/rfl_agg_pbin /tmp/rfl_agg_pbinw") diff --git a/test/rfl/agg/timespan_rank_query.rfl b/test/rfl/agg/timespan_rank_query.rfl new file mode 100644 index 000000000..2b5179dd8 --- /dev/null +++ b/test/rfl/agg/timespan_rank_query.rfl @@ -0,0 +1,39 @@ +;; MED retains the existing native F64-nanosecond contract, not duration rounding. +(set H973 (table [s] (list [0D01:00:00 0D02:00:00]))) +(med (at H973 's)) -- 5400000000000.0 +(type (med (at H973 's))) -- 'f64 +(type (at (select {m: (med s) from: H973}) 'm)) -- 'F64 +(at (select {m: (med s) from: H973}) 'm) -- [5400000000000.0] +(set T973 (table [g s] (list [0 1 0 1 2 2 3 3] (as 'TIMESPAN [1 2 3 4 0Nl 0Nl -4 -1])))) +(med (at T973 's)) -- 1.5 +(at (select {m: (med s) from: T973}) 'm) -- [1.5] +(at (select {s: (med s) from: T973}) 's) -- [1.5] +(at (select {m: (med s) from: T973 where: (< g 2)}) 'm) -- [2.5] +(at (select {m: (med s) from: T973 where: (in g [0 3])}) 'm) -- [0.0] +(set G973 (select {m: (med s) from: T973 by: g asc: g})) +(at G973 'g) -- [0 1 2 3] +(type (at G973 'm)) -- 'F64 +(at G973 'm) -- [2.0 3.0 0Nf -2.5] +(nil? (at G973 'm)) -- [false false true false] +(at (select {m: (med s) c: (count s) from: T973 by: g asc: g}) 'c) -- [2 2 2 2] +(at (select {m: (med s) c: (count s) from: T973 by: g asc: g}) 'm) -- [2.0 3.0 0Nf -2.5] +(set S973 (table [s] (list (as 'TIMESPAN [7])))) +(at (select {m: (med s) from: S973}) 'm) -- [7.0] +(set N973 (table [s] (list [0Nn 0Nn]))) +(type (at (select {m: (med s) from: N973}) 'm)) -- 'F64 +(nil? (at (select {m: (med s) from: N973}) 'm)) -- [true] +(set P973 (table [s] (list (as 'TIMESPAN [-4 -1])))) +(at (select {m: (med s) from: P973}) 'm) -- [-2.5] +;; The shared reader must also honor caller-supplied grouped quantile metadata. +(at (select {q: (quantile s 0.25) from: T973 by: g asc: g}) 'q) -- [1.5 2.5 0Nf -3.25] +(at (select {q: (percentile s 25) from: T973 by: g asc: g}) 'q) -- [1.5 2.5 0Nf -3.25] +;; Numeric controls and native atom admission are unchanged. +(at (select {m: (med v) from: (table [v] (list [1 2]))}) 'm) -- [1.5] +(med 0D01:00:00) !- type +(med (take [1D] 0)) -- 0Nf + +;; Bounded larger groups exercise the existing rank dispatch geometry. +(set I973 (til 65539)) +(set L973 (table [g s] (list (% I973 7) (as 'TIMESPAN (- (% I973 511) 255))))) +(type (at (select {m: (med s) from: L973 by: g asc: g}) 'm)) -- 'F64 +(at (select {m: (med s) from: L973 by: g asc: g}) 'm) -- [-3.0 -2.0 -1.0 0.0 1.0 2.0 3.0] diff --git a/test/rfl/agg/timespan_rank_storage.rfl b/test/rfl/agg/timespan_rank_storage.rfl new file mode 100644 index 000000000..1edb1ebcd --- /dev/null +++ b/test/rfl/agg/timespan_rank_storage.rfl @@ -0,0 +1,22 @@ +;; @requires: posix (temporary fixture cleanup) +;; Unequal partitions rule out median-of-partition-medians. +(.sys.exec "rm -rf /tmp/rfl_span_rank973") -- 0 +(set A973 (table [g s] (list [0 1 0 2 3] (as 'TIMESPAN [0 2 100 0Nl -4])))) +(set B973 (table [g s] (list [0 1 2 3] (as 'TIMESPAN [1 4 0Nl -1])))) +(set ALL973 (concat A973 B973)) +(set CHECK973 (fn [t] (list (type (at (select {m: (med s) from: t}) 'm)) (at (select {m: (med s) from: t}) 'm) (at (select {m: (med s) from: t by: g asc: g}) 'm) (nil? (at (select {m: (med s) from: t by: g asc: g}) 'm)) (at (select {m: (med s) from: t where: (== g 0)}) 'm)))) +(CHECK973 ALL973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(.db.splayed.set "/tmp/rfl_span_rank973/plain" ALL973 {compress:false}) +(set D973 (.db.splayed.get "/tmp/rfl_span_rank973/plain")) +(CHECK973 D973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(CHECK973 D973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(.db.splayed.set "/tmp/rfl_span_rank973/encoded" ALL973 {compress:true}) +(set E973 (.db.splayed.get "/tmp/rfl_span_rank973/encoded")) +(CHECK973 E973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(CHECK973 E973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(.db.splayed.set "/tmp/rfl_span_rank973/p/2024.01.01/t" A973 {compress:false}) +(.db.splayed.set "/tmp/rfl_span_rank973/p/2024.01.02/t" B973 {compress:true}) +(set P973 (.db.parted.get "/tmp/rfl_span_rank973/p" 't)) +(CHECK973 P973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(CHECK973 P973) -- (list 'F64 [1.0] [1.0 3.0 0Nf -2.5] [false false true false] [1.0]) +(.sys.exec "rm -rf /tmp/rfl_span_rank973") -- 0 diff --git a/test/rfl/arith/branch_cov.rfl b/test/rfl/arith/branch_cov.rfl index 1f3fef1f5..80bfc5f6f 100644 --- a/test/rfl/arith/branch_cov.rfl +++ b/test/rfl/arith/branch_cov.rfl @@ -219,13 +219,13 @@ (nil? (- (as 'TIMESTAMP 5000) 0Nt)) -- true (type (- (as 'TIMESTAMP 5000) 0Nt)) -- 'timestamp -;; ── L146-148: TIMESTAMP - TIMESTAMP null → null I64 ── +;; ── L146-148: TIMESTAMP - TIMESTAMP null → null TIMESPAN ── (nil? (- 0Np (as 'TIMESTAMP 2000))) -- true -(type (- 0Np (as 'TIMESTAMP 2000))) -- 'i64 +(type (- 0Np (as 'TIMESTAMP 2000))) -- 'timespan (nil? (- (as 'TIMESTAMP 5000) 0Np)) -- true -(type (- (as 'TIMESTAMP 5000) 0Np)) -- 'i64 +(type (- (as 'TIMESTAMP 5000) 0Np)) -- 'timespan ;; ── L158: numeric null sub propagation (I16 null) ── @@ -717,16 +717,15 @@ (type (+ 5i 0Nl)) -- 'i64 ;; ══════════════════════════════════════════════════════════════════════ -;; Additional sub branches — promote_int_type_right paths +;; Additional sub branches — promote_int_type paths ;; ══════════════════════════════════════════════════════════════════════ -;; sub result type follows RIGHT operand's width (promote_int_type_right) -(type (- 10 5i)) -- 'i32 -(type (- 10 5h)) -- 'i16 -(type (- 10 (as 'U8 3))) -- 'u8 +;; Like add/mul, subtraction promotes both integer operand widths. +(type (- 10 5i)) -- 'i64 +(type (- 10 5h)) -- 'i64 +(type (- 10 (as 'U8 3))) -- 'i64 -;; When right is not a recognized int type, fall through to left -;; (but all numeric types are recognized, so just test coverage of each) +;; The reverse operand order retains the same wider result. (type (- 10h 5)) -- 'i64 (type (- 10i 5)) -- 'i64 diff --git a/test/rfl/arith/sub.rfl b/test/rfl/arith/sub.rfl index 58608b1b5..82b9f887a 100644 --- a/test/rfl/arith/sub.rfl +++ b/test/rfl/arith/sub.rfl @@ -143,9 +143,9 @@ ;; TIMESTAMP - TIME → TIMESTAMP (type (- (as 'TIMESTAMP 5000) (as 'TIME 0))) -- 'timestamp -;; TIMESTAMP - TIMESTAMP → i64 nanos -(- (as 'TIMESTAMP 5000) (as 'TIMESTAMP 2000)) -- 3000 -(type (- (as 'TIMESTAMP 5000) (as 'TIMESTAMP 2000))) -- 'i64 +;; TIMESTAMP - TIMESTAMP → TIMESPAN +(- (as 'TIMESTAMP 5000) (as 'TIMESTAMP 2000)) -- 0D00:00:00.000003000 +(type (- (as 'TIMESTAMP 5000) (as 'TIMESTAMP 2000))) -- 'timespan ;; TIMESTAMP - DATE → type error (- (as 'TIMESTAMP 1000) (as 'DATE 7305)) !- type diff --git a/test/rfl/arith/temporal_wrap.rfl b/test/rfl/arith/temporal_wrap.rfl new file mode 100644 index 000000000..c91fc45a4 --- /dev/null +++ b/test/rfl/arith/temporal_wrap.rfl @@ -0,0 +1,29 @@ +;; DATE and TIME are 32-bit, in vectors and atoms alike. A result past that +;; range keeps its low 32 bits, as a vector cell does, so an atom prints, +;; compares, converts and adds with the same value it would hold in a vector +;; (#876). + +;; TIME: 25 days of milliseconds is past 2^31 +(set p (* 25 24:00:00.000)) +(type p) -- 'time +(as 'I64 p) -- -2134967296 +(+ 2024.01.01D00:00:00.000 p) -- 2023.12.07D06:57:12.704000000 +(== (+ 2024.01.01D00:00:00.000 p) (at (+ 2024.01.01D00:00:00.000 (enlist p)) 0)) -- true +(== p (at (enlist p) 0)) -- true +(> p 24:00:00.000) -- false +(* 100 24:00:00.000) -- 13:54:25.408 +(== (as 'TIME 5000000000) (at (as 'TIME [5000000000]) 0)) -- true + +;; (A wrap onto the null sentinel is left out: whether a vector cell holding it +;; reads as null depends on HAS_NULLS, the question of #841.) + +;; DATE: 3e9 days is past 2^31. Only atom-vector agreement is pinned: what +;; an operand or cast out of range should become is a separate question. +(set d (+ 2000.01.01 3000000000)) +(== d (at (+ (enlist 2000.01.01) 3000000000) 0)) -- true + +;; in range, nothing changes +(* 2 12:00:00.000) -- 24:00:00.000 +(+ 2024.01.01D00:00:00.000 48:00:00.000) -- 2024.01.03D00:00:00.000000000 +(as 'TIME 2147483647) -- (at (as 'TIME [2147483647]) 0) +(+ 2024.01.31 1) -- 2024.02.01 diff --git a/test/rfl/arith/xbar.rfl b/test/rfl/arith/xbar.rfl index 27d9e47f0..e497050d3 100644 --- a/test/rfl/arith/xbar.rfl +++ b/test/rfl/arith/xbar.rfl @@ -22,3 +22,59 @@ (xbar (as 'I32 [-10 20]) 4294967296) -- [-4294967296 0] (type (xbar (as 'I16 [10 20]) 65536)) -- 'I64 (xbar (as 'I16 [-10 20]) 65536) -- [-65536 0] + +;; A null atom buckets to its typed null, as a null element of a vector does. +;; The temporal atom path read a DATE / TIME atom through its 64-bit slot, so +;; 0Nd (low word 0x80000000) bucketed to 5881610.07.10; the integer and float +;; atom paths raised a domain error that the vector path never raised. +(xbar 0Nd 7) -- 0Nd +(type (xbar 0Nd 7)) -- 'date +(xbar 0Nd 7) -- (first (xbar [0Nd] 7)) +(xbar 0Nd -7) -- 0Nd +(xbar 0Nd (as 'I16 7)) -- 0Nd +(xbar 0Nd 2000.01.08) -- 0Nd +(xbar 0Nt 7000) -- 0Nt +(type (xbar 0Nt 7000)) -- 'time +(xbar 0Nt 7000) -- (first (xbar [0Nt] 7000)) +(xbar 0Np 60000000000) -- 0Np +(xbar 0Np 00:01:00.000) -- 0Np +(type (xbar 0Np 60000000000)) -- 'timestamp +(xbar 0Nl 7) -- 0Nl +(xbar 0Nl 7) -- (first (xbar [0Nl] 7)) +(xbar 0Ni (as 'I32 7)) -- 0Ni +(xbar 0Nh (as 'I16 7)) -- 0Nh +(xbar 0Nl 2.5) -- 0Nf +(xbar 0Nf 2.0) -- 0Nf +(xbar [1.5 0Nf 4.5] 2.0) -- [0.0 0Nf 4.0] +;; non-null temporal atoms, either side of the epoch +(xbar 2000.01.10 7) -- 2000.01.08 +(xbar 1999.12.26 7) -- 1999.12.25 +(xbar 2000.01.10 7) -- (first (xbar [2000.01.10] 7)) +;; a zero or null bucket stays a domain error, null value or not +(xbar 0Nd 0) !- domain +(xbar 0Nd 0N) !- domain +(xbar 2000.01.10 0N) !- domain +(xbar 0Nl 0) !- domain +(xbar 17 0N) !- domain +(xbar 0Nf 0Nf) !- domain +(xbar 'a 7) !- type +;; a constant null atom in a query the evaluator serves +(set Tn (table [d x] (list [2000.01.10 0Nd 1999.12.26] [1 2 3]))) +(at (select {k: (xbar 0Nd 7) from: Tn by: x}) 'k) -- [0Nd 0Nd 0Nd] +(at (select {k: (xbar 0Nd 7) from: Tn}) 'k) -- [0Nd 0Nd 0Nd] +(at (select {k: (xbar d 7) from: Tn}) 'k) -- [2000.01.08 0Nd 1999.12.25] + +;; A negative narrow bucket in the vector fast path: the bucket was read +;; through its 64-bit slot, so an I16 -7 was 65529 and an I32 -7 4294967289. +(xbar [17 -17] (as 'I16 -7)) -- [21 -14] +(xbar [17 -17] (as 'I32 -7)) -- [21 -14] +(xbar (as 'I32 [17 -17]) (as 'I16 -7)) -- (as 'I32 [21 -14]) +(xbar [2000.01.10 1999.12.26] (as 'I16 -7)) -- [2000.01.15 2000.01.01] +(xbar [2000.01.01D00:00:00.000000010] (as 'I32 -7)) -- [2000.01.01D00:00:00.000000014] + +;; A -1 bucket over a 64-bit vector holding a null divided the INT64_MIN +;; sentinel by -1 in the fast path, which traps (SIGFPE). +(xbar [0Nl 5 -5] -1) -- [0Nl 5 -5] +(xbar [0Np 2000.01.01D00:00:00.000000005] -1) -- [0Np 2000.01.01D00:00:00.000000005] +(xbar 0Np -1) -- 0Np +(xbar 0Nl -1) -- 0Nl diff --git a/test/rfl/cmp/cmp_branch_cov.rfl b/test/rfl/cmp/cmp_branch_cov.rfl index de136f286..f8a2fcf75 100644 --- a/test/rfl/cmp/cmp_branch_cov.rfl +++ b/test/rfl/cmp/cmp_branch_cov.rfl @@ -272,11 +272,11 @@ (<= 'foo 1) !- type ;; ══════════════════════════════════════════════════════════════════ -;; 19. BOOL_VEC_BINOP — min-length truncation (line 209) -;; When vectors have different lengths, uses the shorter. +;; 19. BOOL_VEC_BINOP — vectors of different lengths are a length +;; error, as for comparisons (they used to truncate to the shorter). ;; ══════════════════════════════════════════════════════════════════ -(and [true true true false] [true false]) -- [true false] -(or [true false] [false false true]) -- [true false] +(and [true true true false] [true false]) !- length +(or [true false] [false false true]) !- length ;; ══════════════════════════════════════════════════════════════════ ;; 20. gt/lt temporal — false branch of temporal_as_ns comparison diff --git a/test/rfl/cmp/list_logic.rfl b/test/rfl/cmp/list_logic.rfl new file mode 100644 index 000000000..f8f5ec75f --- /dev/null +++ b/test/rfl/cmp/list_logic.rfl @@ -0,0 +1,66 @@ +;; Comparisons and and/or/not over a LIST, and over vectors that are not +;; B8, work element by element, booleans out (#820). +;; +;; A LIST of numbers turns up unasked, e.g. from a lookup that missed a +;; key; a filter built on it used to collapse to one truth value and +;; accept every row. + +;; ── comparisons on a LIST give a B8 vector ────────────────────────── +(> (list 1 2) 1) -- [false true] +(type (> (list 1 2) 1)) -- 'B8 +(type (>= (list 1 2) 1)) -- 'B8 +(< (list 1 2) (list 2 1)) -- [true false] +(== (list 1 2.0 3) [1 2 3]) -- [true true true] +(type (== (list 1 2.0 3) [1 2 3])) -- 'B8 +(!= (list 1 2) 1) -- [false true] +(<= 1 (list 0 1 2)) -- [false true true] +(== (list 0Nl 1) [0Nl 1]) -- [true true] + +;; a nested LIST keeps its shape, each part compared +(== (list [1 2] [3 4]) 1) -- (list [true false] [false false]) + +;; an element that cannot be compared, or a length mismatch, is an error +(== (list 1 'a) 1) !- type +(> (list 1 2 3) [1 2]) !- length + +;; ── and / or are element-wise on any collection ───────────────────── +(and (list false false) [true true]) -- [false false] +(or (list false false) [false false]) -- [false false] +(and (list true false) true) -- [true false] +(or false (list true false)) -- [true false] +(and (list true false) (list true true)) -- [true false] +(type (and (list true false) (list true true))) -- 'B8 + +;; numeric vectors: each element by truthiness, booleans out +(and [1 0 2] [1 1 0]) -- [true false false] +(or (list 0 0) [false true]) -- [false true] + +;; variadic, with a LIST in the middle +(and [true true true] (list true false true) [true true false]) -- [true false false] + +;; nested lists recurse +(and (list [true false] [true true]) true) -- (list [true false] [true true]) + +;; lengths must match, B8 vectors included +(and [true false] [true]) !- length +(or [true false] [true]) !- length +(and (list true false) [true]) !- length + +;; empty +(and (list) (list)) -- [] + +;; atoms are unchanged +(and true false) -- false +(or false true) -- true +(and 1 2) -- true + +;; ── not is element-wise on a LIST ─────────────────────────────────── +(not (list true false)) -- [false true] +(type (not (list true false))) -- 'B8 +(not (list 1 0)) -- [false true] +(not (list 1 0 [0 1])) -- (list false true [true false]) + +;; ── the filter from the issue: a missing key no longer passes all ─── +(set counts (list 3 0Nl 5)) +(set fresh [true true true]) +(and fresh (>= (fill 0 counts) 2)) -- [true false true] diff --git a/test/rfl/collection/at.rfl b/test/rfl/collection/at.rfl index ee74a002c..8cd3ee7cd 100644 --- a/test/rfl/collection/at.rfl +++ b/test/rfl/collection/at.rfl @@ -8,9 +8,9 @@ (type (at (as 'I64 [10 20 30 40 50]) [0 2 4])) -- 'I64 (+ 1 (at (as 'I64 [10 20 30 40 50]) [0 2 4])) -- [11 31 51] (type (at (as 'F64 [1.5 2.5 3.5]) [2 0])) -- 'F64 -(type (at (as 'I64 [10 20 30]) [0 99])) -- 'LIST +(type (at (as 'I64 [10 20 30]) [0 99])) -- 'I64 (nil? (at (at (as 'I64 [10 20 30]) [0 99]) 1)) -- true -(type (at (as 'I64 [10 20 30]) (as 'I64 [0 0N 2]))) -- 'LIST +(type (at (as 'I64 [10 20 30]) (as 'I64 [0 0N 2]))) -- 'I64 ;; table row indices return a table, not a boxed list of row dicts (type (at (table [a b] (list [1 2 3] [4 5 6])) [0 2])) -- 'TABLE @@ -54,3 +54,55 @@ (count (at [10 20 30] (as 'I64 (list)))) -- 0 ;; dict missing key → 0Nl typed null (line 1667) (nil? (at (dict ['a 'b] [1 2]) 'missing)) -- true + +;; ─── a vector indexed by an integer vector keeps its type (#819) ───── +;; A null or out-of-range index gives the type's null in place, as the +;; scalar `at` gives a typed null atom; it never boxes the whole result. +(at [5 6 7] (as 'I64 (list 0Nl 1))) -- [0Nl 6] +(at [5 6 7] [1 9]) -- [6 0Nl] +(at [5 6 7] [-1 0]) -- [0Nl 5] +(type (at [5 6 7] (as 'I64 (list 0Nl 1)))) -- 'I64 +(fill 0 (at [5 6 7] (as 'I64 (list 0Nl 1)))) -- [0 6] +(type (fill 0 (at [5 6 7] (as 'I64 (list 0Nl 1))))) -- 'I64 + +;; the alignment through find: a missing key no longer changes the type +(set ks ['a 'b 'c]) +(set vs [1.5 2.5 3.5]) +(at vs (find ks ['c 'z 'a])) -- [3.5 0Nf 1.5] +(type (at vs (find ks ['c 'z 'a]))) -- 'F64 +(> (at vs (find ks ['c 'z 'a])) 2.0) -- [true false false] + +;; every nullable type keeps its type and gets its own null +(at (as 'I32 [5 6]) [1 -1]) -- (as 'I32 (list 6 0Ni)) +(type (at (as 'I32 [5 6]) [1 -1])) -- 'I32 +(type (at (as 'I16 [5 6]) [1 9])) -- 'I16 +(type (at [1.5 2.5] [0 5])) -- 'F64 +(nil? (at (at [1.5 2.5] [0 5]) 1)) -- true +(type (at [2024.01.01 2024.01.02] [1 7])) -- 'DATE +(nil? (at (at [2024.01.01 2024.01.02] [1 7]) 1)) -- true +(type (at ['a 'b] [0 5])) -- 'SYM +(at ['a 'b] [1 5]) -- ['b '] +(type (at (as 'STR (list "x" "y")) [0 5])) -- 'STR +(at (at (as 'STR (list "x" "y")) [0 5]) 1) -- "" + +;; BOOL and U8 have no null: a missing position is false / 0x00 +(at [true false] [0 5]) -- [true false] +(type (at [true false] [0 5])) -- 'B8 +(type (at (as 'U8 [1 2]) [0 5])) -- 'U8 + +;; an empty source gives all nulls, of its type +(at (as 'I64 []) (as 'I64 (list 0Nl))) -- [0Nl] +(type (at (as 'I64 []) [0 1])) -- 'I64 +(count (at (as 'I64 []) [0 1])) -- 2 +(type (at (as 'SYM []) [0 1])) -- 'SYM + +;; index vectors of the narrower integer types gather typed too +(at [5 6 7] (as 'I32 [2 0])) -- [7 5] +(type (at [5 6 7] (as 'I32 [2 0]))) -- 'I64 +(type (at [5 6 7] (as 'I16 [2 0]))) -- 'I64 +(type (at [5 6 7] (as 'U8 [2 0]))) -- 'I64 +(at [5 6 7] (as 'I32 (list 0Ni 1))) -- [0Nl 6] + +;; a nested index keeps its shape, each part typed +(at [5 6 7] (list [0 1] [2 9])) -- (list [5 6] [7 0Nl]) +(type (at (at [5 6 7] (list [0 1] [2 9])) 1)) -- 'I64 diff --git a/test/rfl/collection/distinct.rfl b/test/rfl/collection/distinct.rfl index 8cf07c215..1c7a731e8 100644 --- a/test/rfl/collection/distinct.rfl +++ b/test/rfl/collection/distinct.rfl @@ -30,6 +30,10 @@ (distinct ['a 'b 'ab 'aa 'a 'aa]) -- ['a 'b 'ab 'aa] (set l (guid 2)) (set l (concat l l)) (count (distinct l)) -- 2 (distinct (list [3i 3i] 2i [3i 3i] 2i)) -- (list 2i [3i 3i]) +;; tables and dicts in a list: equal ones collapse, different ones stay +;; (cell equality saw every table / dict of one length as equal) +(count (distinct (list (table [q] (list [1])) (table [q] (list [2])) (table [q] (list [1])) (table [r] (list [1]))))) -- 3 +(count (distinct (list {p: 1} {p: 2} {p: 1} {r: 1}))) -- 3 ;; ========== NULL BITMAP PROPAGATION ========== ;; distinct preserves one null (distinct [1 0Nl 2 0Nl 1]) -- [0Nl 1 2] diff --git a/test/rfl/collection/group.rfl b/test/rfl/collection/group.rfl index 28664e80a..5914b5042 100644 --- a/test/rfl/collection/group.rfl +++ b/test/rfl/collection/group.rfl @@ -174,3 +174,85 @@ ;; `error: limit`. Post-fix: 1500 distinct groups, one row each. (set Tmk (table [k1 k2 v] (list (til 1500) (til 1500) (til 1500)))) (count (select {from: Tmk r: (* v 2) by: {k1: k1 k2: k2}})) -- 1500 + +;; ─── LIST cells holding tables / dicts ─── +;; Cell equality fell through to the vector branch, which compares +;; len * elem_size bytes, zero for TABLE/DICT, so every table (and every +;; dict) of one length landed in one group. Equal tables (same column names +;; in order, equal columns) group together, built apart or not; a different +;; column name or value starts a group of its own. Same for dicts. +(set TA1 (table [q] (list [1 2]))) +(set TA2 (table [q] (list [1 2]))) +(set TB (table [r] (list [1 2]))) +(set TC (table [q] (list [1 3]))) +(set TL (list TA1 TB TA2 TC TA1)) +(set TLT (table [x c] (list [1 2 3 4 5] TL))) +(map count (value (group TL))) -- [3 1 1] +(value (group TL)) -- (list [0 2 4] [1] [3]) +(at (select {x: (sum x) from: TLT by: c}) 'x) -- [9 2 4] +(at (select {x: x from: TLT by: c}) 'x) -- (list [1 3 5] [2] [4]) +(at (select {x: (sum x) from: (table [x c s] (list [1 2 3 4 5] TL ['a 'a 'a 'a 'b])) by: [c s]}) 'x) -- [4 2 4 5] +(set TT2 (at (list (table [q] (list [1])) (table [q] (list [2]))) (% (til 5) 2))) +(at (select {x: (sum x) from: (table [x c] (list [1 2 3 4 5] TT2)) by: c}) 'x) -- [9 6] +;; SYM columns compare by symbol, STR columns by content +(set TS1 (table [n] (list ['a 'b]))) +(set TS2 (table [n] (list (as 'SYM ["a" "b"])))) +(set TS3 (table [n] (list ["a long string beyond the inline size" "b"]))) +(set TS4 (table [n] (list (concat ["a long string beyond the inline size"] ["b"])))) +(at (select {x: (sum x) from: (table [x c] (list [1 2 3 4] (list TS1 TS2 TS3 TS4))) by: c}) 'x) -- [3 7] +(map count (value (group (list TS1 TS2 TS3 TS4)))) -- [2 2] +(set DL (list {p: 1} {p: 2} {r: 1} {p: 1} (dict ['p] (list 1)))) +(map count (value (group DL))) -- [3 1 1] +(at (select {x: (sum x) from: (table [x c] (list [1 2 3 4 5] DL)) by: c}) 'x) -- [10 2 3] +;; a SYM column of a splayed table holds file-domain positions at a narrow +;; width: the cells compare by symbol text, read at the column's own width +;; (an 8-byte read a cell ran past the end of a W8 column) +(.sys.exec "rm -rf /tmp/rfl_grp_tblcell") +(.db.splayed.set "/tmp/rfl_grp_tblcell/" (table [n] (list ['b 'a]))) +(set FN (at (.db.splayed.get "/tmp/rfl_grp_tblcell/") 'n)) +(set TFL (list (table [n] (list FN)) (table [n] (list ['b 'a])) (table [n] (list ['a 'b])))) +(at (select {x: (sum x) from: (table [x c] (list [1 2 4] TFL)) by: c}) 'x) -- [3 4] +(set DFL (list (dict FN [1 2]) (dict ['b 'a] [1 2]) (dict ['a 'b] [1 2]))) +(at (select {x: (sum x) from: (table [x c] (list [1 2 4] DFL)) by: c}) 'x) -- [3 4] +(map count (value (group TFL))) -- [2 1] +(map count (value (group DFL))) -- [2 1] +(count (distinct TFL)) -- 2 +(.db.splayed.set "/tmp/rfl_grp_tblcell/" (table [n] (list (take ['b 'a 'c] 300000)))) +(set FW1 (at (.db.splayed.get "/tmp/rfl_grp_tblcell/") 'n)) +(set FW2 (at (.db.splayed.get "/tmp/rfl_grp_tblcell/") 'n)) +(map count (value (group (list (table [n] (list FW1)) (table [n] (list FW2)))))) -- [2] +(map count (value (group (list (dict FW1 (til 300000)) (dict FW2 (til 300000)))))) -- [2] +;; (map count (value (group (list FN ['b 'a])))) -- [2] ;; xfail BUG: group/distinct compare plain vector cells byte for byte, so file-domain and runtime symbols of equal text split (and a narrow SYM cell is read 8 bytes a cell) — the atom_eq vector branch, rewritten on fix/iss-801 +(.sys.exec "rm -rf /tmp/rfl_grp_tblcell") +;; equal long strings at different pool offsets: compared by content +(set VS1 ["a long string beyond the inline size" "b"]) +(set VS2 (drop ["another long string beyond the inline size" "a long string beyond the inline size" "b"] 1)) +(map count (value (group (list (table [s] (list VS1)) (table [s] (list VS2)))))) -- [2] +(at (select {x: (sum x) from: (table [x c] (list [1 2] (list (table [s] (list VS1)) (table [s] (list VS2))))) by: c}) 'x) -- [3] +(map count (value (group (list (dict VS1 [1 2]) (dict VS2 [1 2]))))) -- [2] +;; (map count (value (group (list (table [v] (list [0.0])) (table [v] (list [-0.0])))))) -- [2] ;; xfail BUG: 0.0 and -0.0 F64 cells compare byte for byte and split (by: too) +;; the same cell equality backs find, in, except, union and the lookup in a +;; dict keyed by a LIST (here group's keys); on every pair of tables of one +;; length it answered equal +(set TQ1 (table [q] (list [1 2]))) +(set TQ2 (table [q] (list [1 3]))) +(set TR3 (table [r] (list [1 2]))) +(set TQL (list TQ1 TQ2 TR3)) +(find TQL (table [q] (list [1 3]))) -- 1 +(in (list (table [q] (list [1 3])) (table [q] (list [9 9]))) TQL) -- [true false] +(count (except TQL (list (table [q] (list [1 3]))))) -- 2 +(count (union TQL (list (table [q] (list [1 2])) (table [q] (list [7]))))) -- 4 +(at (group (list TQ1 TQ2 TR3 TQ2)) (table [q] (list [1 3]))) -- [1 3] +(find (list {p: 1} {p: 2}) {p: 2}) -- 1 +(at (group (list {p: 1} {p: 2} {p: 2})) {p: 2}) -- [1 2] +;; a few thousand distinct table cells, each twice: the TABLE hash arms only +;; spread them over the buckets; this pins the grouping they serve +(set MT (map (fn [i] (table [q] (list (+ i [0 1])))) (til 3000))) +(set MT2 (concat MT MT)) +(count (group MT2)) -- 3000 +(distinct (map count (value (group MT2)))) -- [2] +(set MR (select {n: (count x) from: (table [x c] (list (til 6000) MT2)) by: c})) +(count MR) -- 3000 +(distinct (at MR 'n)) -- [2] +(at (at MR 'c) 2999) -- (table [q] (list [2999 3000])) +(count (distinct MT2)) -- 3000 diff --git a/test/rfl/collection/prior_symbol_storage.rfl b/test/rfl/collection/prior_symbol_storage.rfl new file mode 100644 index 000000000..c0c840f3a --- /dev/null +++ b/test/rfl/collection/prior_symbol_storage.rfl @@ -0,0 +1,26 @@ +;; @requires: posix (fixture cleanup via .sys.exec) +;; #966: explicit result types, not just element-wise value equivalence. +(.sys.exec "rm -rf /tmp/rfl_prior_symbol_storage") -- 0 +(set PS (as 'SYM (list "" "" "a" "a" "" "b"))) +(.db.splayed.set "/tmp/rfl_prior_symbol_storage/s/" (table [s] (list PS))) +(set ST (.db.splayed.get "/tmp/rfl_prior_symbol_storage/s/")) +(set SC (at ST 's)) +(type SC) -- 'SYM +(type (prior == SC)) -- 'B8 +(type (prior != SC)) -- 'B8 +(prior == SC) -- [true true false true false false] +(prior != SC) -- [false false true false true true] +(where (prior == SC)) -- [0 1 3] +(prior == (take SC -3)) -- [true false false] + +;; The equal a/a pair crosses the partition boundary. +(.db.splayed.set "/tmp/rfl_prior_symbol_storage/p/2024.01.01/t/" (table [s] (list (take PS 3)))) +(.db.splayed.set "/tmp/rfl_prior_symbol_storage/p/2024.01.02/t/" (table [s] (list (take PS -3)))) +(set PT (.db.parted.get "/tmp/rfl_prior_symbol_storage/p/" 't)) +(set PC (at PT 's)) +(type PC) -- 'SYM +(type (prior == PC)) -- 'B8 +(prior == PC) -- [true true false true false false] +(prior != PC) -- [false false true false true true] +(where (prior == PC)) -- [0 1 3] +(.sys.exec "rm -rf /tmp/rfl_prior_symbol_storage") -- 0 diff --git a/test/rfl/collection/prior_where.rfl b/test/rfl/collection/prior_where.rfl index 5d556bb0d..e72ed0271 100644 --- a/test/rfl/collection/prior_where.rfl +++ b/test/rfl/collection/prior_where.rfl @@ -8,6 +8,8 @@ (prior > [3 1 4 1 5]) -- [false false true false true] (prior <= [1 1 2]) -- [true true false] (prior >= [1 1 2]) -- [true true true] +(type (prior == ['a 'a 'b 'b 'a])) -- 'B8 +(type (prior != ['a 'a 'b 'b 'a])) -- 'B8 (prior == ['a 'a 'b 'b 'a]) -- [true true false true false] (prior != ['a 'a 'b 'b 'a]) -- [false false true false true] (prior != [1.5 1.5 2.0]) -- [false false true] @@ -36,3 +38,20 @@ (where (> (til 100000) 99997)) -- [99998 99999] (count (where (>= (til 32) 0))) -- 32 (where [false false false]) -- (as 'I64 (list)) + +;; #966: SYM null0 compares as an ordinary canonical code for EQ/NE. +(set PS (as 'SYM (list "" "" "a" "a" "" "b"))) +(type (prior == PS)) -- 'B8 +(prior == PS) -- [true true false true false false] +(prior != PS) -- [false false true false true true] +(where (prior == PS)) -- [0 1 3] +(type (prior == (take PS -3))) -- 'B8 +(prior == (take PS -3)) -- [true false false] +(prior != (take PS -3)) -- [false true true] +(type (prior == ['a])) -- 'B8 +(prior == ['a]) -- [true] +(count (prior == (as 'SYM (list)))) -- 0 +;; Arbitrary callbacks and nullable numeric inputs retain their boxed path. +(type (prior (fn [a b] (== a b)) ['a 'b 'b])) -- 'LIST +(type (prior == VN)) -- 'LIST +(where (and (prior < [3 2 1]) (prior == ['a 'b 'b]))) -- [2] diff --git a/test/rfl/collection/reverse.rfl b/test/rfl/collection/reverse.rfl index 52669e1c4..b40a2fbc3 100644 --- a/test/rfl/collection/reverse.rfl +++ b/test/rfl/collection/reverse.rfl @@ -35,6 +35,23 @@ (reverse ['x]) -- ['x] (reverse ["one"]) -- ["one"] +;; Tables reverse rows while preserving column names and column types. +(set _reverse_table (table [a b] (list [1 2 3] ["x" "y" "z"]))) +(key (reverse _reverse_table)) -- [a b] +(at (reverse _reverse_table) 'a) -- [3 2 1] +(at (reverse _reverse_table) 'b) -- ["z" "y" "x"] +(count (reverse (table [a] (list [])))) -- 0 + +;; Dictionary entries move together for typed and boxed values. +(set _reverse_dict (dict ['a 'b 'c] [10 20 30])) +(key (reverse _reverse_dict)) -- ['c 'b 'a] +(value (reverse _reverse_dict)) -- [30 20 10] +(at (reverse _reverse_dict) 'b) -- 20 +(set _reverse_boxed (dict ['a 'b] (list [1 2] "x"))) +(key (reverse _reverse_boxed)) -- ['b 'a] +(at (reverse _reverse_boxed) 'a) -- [1 2] +(at (reverse _reverse_boxed) 'b) -- "x" + ;; OP_REVERSE vector-input guard: a lazy chain whose previous op is ;; an aggregator (FIRST) yields a scalar at materialisation; OP_REVERSE ;; must reject the non-vec input rather than dispatching to diff --git a/test/rfl/collection/reverse_parted.rfl b/test/rfl/collection/reverse_parted.rfl new file mode 100644 index 000000000..c7619cf88 --- /dev/null +++ b/test/rfl/collection/reverse_parted.rfl @@ -0,0 +1,16 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) +;; reverse and row selection by index vector over a parted table: the +;; parted columns are flattened and the MAPCOMMON partition key expanded +;; before the gather, so rows come back reversed instead of failing in +;; the allocator. +(.sys.exec "rm -rf /tmp/rfl_reverse_parted") +(.db.splayed.set "/tmp/rfl_reverse_parted/2024.01.01/t/" (table [a s] (list [1 2] [x y])) "/tmp/rfl_reverse_parted/.sym") +(.db.splayed.set "/tmp/rfl_reverse_parted/2024.01.02/t/" (table [a s] (list [3 4 5] [z w v])) "/tmp/rfl_reverse_parted/.sym") +(set _rp (.db.parted.get "/tmp/rfl_reverse_parted/" 't)) +(count (reverse _rp)) -- 5 +(at (reverse _rp) 'a) -- [5 4 3 2 1] +(at (reverse _rp) 's) -- ['v 'w 'z 'y 'x] +(at (reverse _rp) 'date) -- [2024.01.02 2024.01.02 2024.01.02 2024.01.01 2024.01.01] +(at (reverse (reverse _rp)) 'a) -- [1 2 3 4 5] +(at (at _rp [4 0 2]) 'a) -- [5 1 3] +(at (at _rp [4 0 2]) 'date) -- [2024.01.02 2024.01.01 2024.01.02] diff --git a/test/rfl/collection/take_parted.rfl b/test/rfl/collection/take_parted.rfl new file mode 100644 index 000000000..cc9bc83d3 --- /dev/null +++ b/test/rfl/collection/take_parted.rfl @@ -0,0 +1,84 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) +;; take over a parted table handle (.db.parted.get): the parted columns and +;; the MAPCOMMON partition key are not dense vectors, so the table arm of +;; take materializes just the rows it needs (head or tail window, or all +;; rows when the count wraps) and then answers exactly as for the flat table +;; with the same rows (#855). +(.sys.exec "rm -rf /tmp/rfl_take_parted") +;; partition 2024.01.02 lacks the b and name columns (NULL segments, read +;; back as typed nulls); c carries i64 nulls. +(.db.splayed.set "/tmp/rfl_take_parted/2024.01.01/t/" (table [a s c b name] (list [1 2] [x y] [10 0Nl] [0.5 1.5] (list "alpha" "beta")))) +(.db.splayed.set "/tmp/rfl_take_parted/2024.01.02/t/" (table [a s c] (list [3 4 5] [z w v] [0Nl 40 50]))) +(.db.splayed.set "/tmp/rfl_take_parted/2024.01.03/t/" (table [a s c b name] (list [6 7] [u x] [60 70] [6.5 7.5] (list "gamma" "delta")))) +(set _tp (.db.parted.get "/tmp/rfl_take_parted/" 't)) +(set _tf (table [date a s c b name] (list [2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.02 2024.01.03 2024.01.03] [1 2 3 4 5 6 7] [x y z w v u x] [10 0Nl 0Nl 40 50 60 70] [0.5 1.5 0Nf 0Nf 0Nf 6.5 7.5] (list "alpha" "beta" "" "" "" "gamma" "delta")))) +(count _tp) -- 7 + +;; the issue's repro: head and tail +(count (take _tp 2)) -- 2 +(at (take _tp 2) 'a) -- [1 2] +(at (take _tp -2) 'a) -- [6 7] +(take _tp 2) -- (at _tp (til 2)) +(take _tp -2) -- (at _tp [5 6]) + +;; same rows as the flat table, crossing partition boundaries +(take _tp 3) -- (take _tf 3) +(take _tp -4) -- (take _tf -4) +(take _tp 7) -- (take _tf 7) +(take _tp -7) -- (take _tf -7) + +;; the partition key, sym and string columns +(at (take _tp 3) 'date) -- [2024.01.01 2024.01.01 2024.01.02] +(at (take _tp -3) 'date) -- [2024.01.02 2024.01.03 2024.01.03] +(at (take _tp 3) 's) -- ['x 'y 'z] +(at (take _tp -3) 's) -- ['v 'u 'x] +(at (take _tp 2) 'name) -- (list "alpha" "beta") +(at (take _tp -2) 'name) -- (list "gamma" "delta") + +;; nulls in a column and in the partition without the column stay null +(at (take _tp 4) 'c) -- [10 0Nl 0Nl 40] +(nil? (at (at (take _tp 2) 'c) 1)) -- true +(at (take _tp -5) 'b) -- [0Nf 0Nf 0Nf 6.5 7.5] +(nil? (at (at (take _tp -5) 'name) 0)) -- true +(at (at (take _tp -5) 'name) 3) -- "gamma" + +;; zero rows keeps the schema +(count (take _tp 0)) -- 0 +(take _tp 0) -- (take _tf 0) + +;; a count past the row count wraps, as for flat tables and vectors +(count (take _tp 9)) -- 9 +(take _tp 9) -- (take _tf 9) +(take _tp -9) -- (take _tf -9) +(at (take _tp 9) 'date) -- [2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.02 2024.01.03 2024.01.03 2024.01.01 2024.01.01] + +;; range take [start amount] +(take _tp [1 3]) -- (take _tf [1 3]) +(take _tp [-3 2]) -- (take _tf [-3 2]) +(take _tp [5 10]) -- (take _tf [5 10]) +(count (take _tp [7 2])) -- 0 +(.sys.exec "rm -rf /tmp/rfl_take_parted") + +;; take over a compressed (generation 2) table: an encoded column is read +;; for the rows taken only, and every form answers exactly as for the same +;; table saved plain. +(.sys.exec "rm -rf /tmp/rfl_take_gen2") +(set _gi (til 70000)) +(set _gt (table [a b s] (list (* (- (% _gi 1000) 500) 7919) (* 0.5 (as 'F64 (% _gi 301))) (as 'SYM (at ["red" "green" "blue" "cyan"] (% _gi 4)))))) +(.db.splayed.set "/tmp/rfl_take_gen2/c/" _gt "/tmp/rfl_take_gen2/c.sym" {compress: true}) +(.db.splayed.set "/tmp/rfl_take_gen2/p/" _gt "/tmp/rfl_take_gen2/p.sym") +(set _gc (.db.splayed.get "/tmp/rfl_take_gen2/c/" "/tmp/rfl_take_gen2/c.sym")) +(set _gp (.db.splayed.get "/tmp/rfl_take_gen2/p/" "/tmp/rfl_take_gen2/p.sym")) +(take _gc 5) -- (take _gp 5) +(take _gc -5) -- (take _gp -5) +(take _gc 0) -- (take _gp 0) +(take _gc 70000) -- (take _gp 70000) +(take _gc -70000) -- (take _gp -70000) +(take _gc 70003) -- (take _gp 70003) +(take _gc [3 4]) -- (take _gp [3 4]) +(take _gc [-3 10]) -- (take _gp [-3 10]) +(take _gc [69998 10]) -- (take _gp [69998 10]) +(take _gc [70000 2]) -- (take _gp [70000 2]) +(take _gc [66000 8000]) -- (take _gp [66000 8000]) +(at (take _gc -2) 'a) -- [3943662 3951581] +(.sys.exec "rm -rf /tmp/rfl_take_gen2") diff --git a/test/rfl/datalog/datalog_coverage.rfl b/test/rfl/datalog/datalog_coverage.rfl index 413b2b858..035852540 100644 --- a/test/rfl/datalog/datalog_coverage.rfl +++ b/test/rfl/datalog/datalog_coverage.rfl @@ -567,6 +567,10 @@ (dl-free CPcopy) !- type (dl-free CP) -- true +;; Rebinding an unfreed handle must release the program automatically. +(set AutoReleased (dl-program)) +(set AutoReleased 0) + ;; --- Claim 4: fixpoint non-convergence must error loudly, not return a partial result --- ;; Reachability over a linear chain needs ~N iterations. The loop caps at 1000. diff --git a/test/rfl/embedding/embedding_coverage.rfl b/test/rfl/embedding/embedding_coverage.rfl index 4b701a503..757a658dd 100644 --- a/test/rfl/embedding/embedding_coverage.rfl +++ b/test/rfl/embedding/embedding_coverage.rfl @@ -100,6 +100,9 @@ (at (hnsw-info IdxCos) 'nrows) -- 5 (at (hnsw-info IdxCos) 'dim) -- 3 (first (at (ann IdxCos [1.0 0.0 0.0] 1) '_rowid)) -- 0 +;; Opaque index pointers must never cross the serde boundary as plain I64s. +(ser IdxCos) !- domain +(ser (list IdxCos)) !- domain (hnsw-free IdxCos) (set IdxIp (hnsw-build V 'ip 16 64)) diff --git a/test/rfl/expr/const_expr.rfl b/test/rfl/expr/const_expr.rfl index 1e45c1846..5a81b8aa4 100644 --- a/test/rfl/expr/const_expr.rfl +++ b/test/rfl/expr/const_expr.rfl @@ -45,7 +45,8 @@ ;; (div 10.0 3) → OP_IDIV, l_is_f64=true. ;; At line 111: l_is_f64=true → F64 branch fires. ;; Line 120: case OP_IDIV: r = rv!=0.0 ? floor(lv/rv) : NAN → floor(10.0/3)=3.0. -;; const_expr_to_i64: c_is_f64=true, c_f=3.0, modf(3.0)==0.0 → *out=3. +;; const_expr_to_i64: c_is_f64=true → declines the linear plan; the +;; evaluator applies the builtin, whose (div 10.0 3) is the I64 3. ;; sum(x * 3) = 45. ;; =================================================================== (select {s: (sum (* x (div 10.0 3))) from: Tce}) -- (table [s] (list [45])) @@ -111,7 +112,8 @@ ;; =================================================================== ;; F64 NEG constant → eval_const_numeric_expr NEG/ABS branch (line 83:25) ;; (neg 3.0): inner CONST is F64 → a_is_f64=true → Branch(83:25) True. -;; const_expr_to_i64: modf(-3.0)=0 → k=-3. -;; sum(x * -3) = (1+2+3+4+5)*(-3) = -45 +;; const_expr_to_i64: c_is_f64=true → declines the linear plan, so the +;; F64 product is summed as F64, as the builtin does. +;; sum(x * -3.0) = (1+2+3+4+5)*(-3.0) = -45.0 ;; =================================================================== -(select {s: (sum (* x (neg 3.0))) from: Tce}) -- (table [s] (list [-45])) +(select {s: (sum (* x (neg 3.0))) from: Tce}) -- (table [s] (list [-45.0])) diff --git a/test/rfl/expr/expr_branch_cov.rfl b/test/rfl/expr/expr_branch_cov.rfl index 0834c1a33..27282de29 100644 --- a/test/rfl/expr/expr_branch_cov.rfl +++ b/test/rfl/expr/expr_branch_cov.rfl @@ -212,16 +212,18 @@ ;; whose div/mod post-pass marks the zero-divisor row null (lines ;; ~2142-2153, the !r_scalar I64 b[i]==0 -> ray_vec_set_null arm). ;; `%` lowers to OP_MOD, which DOES fuse -> expr_exec_binary I64 -;; OP_MOD b[j]==0 guard writes 0 (no fused null post-pass). +;; OP_MOD b[j]==0 guard writes the null sentinel, as the builtin +;; (% (at Tdz 'a) (at Tdz 'z)) does, and the output scan flags it. ;; z has a zero in the middle row. ;; ==================================================================== (set Tdz (table [a z] (list [10 20 30 40] [2 0 5 4]))) ;; div (non-fused, OP_IDIV) -> zero-divisor row is NULL. (at (select {r: (div a z) from: Tdz}) 'r) -- [5 0Nl 6 10] (nil? (at (at (select {r: (div a z) from: Tdz}) 'r) 1)) -- true -;; mod (fused, OP_MOD) -> zero-divisor row is 0, not null. -(at (select {r: (% a z) from: Tdz}) 'r) -- [0 0 0 0] -(nil? (at (at (select {r: (% a z) from: Tdz}) 'r) 1)) -- false +;; mod (fused, OP_MOD) -> zero-divisor row is NULL too. +(at (select {r: (% a z) from: Tdz}) 'r) -- [0 0Nl 0 0] +(at (select {r: (% a z) from: Tdz}) 'r) -- (% (at Tdz 'a) (at Tdz 'z)) +(nil? (at (at (select {r: (% a z) from: Tdz}) 'r) 1)) -- true ;; ==================================================================== ;; 12. Fused F64 -> I64 CAST out-of-range clamp (expr_exec_unary dt=I64, diff --git a/test/rfl/expr/narrow_cast.rfl b/test/rfl/expr/narrow_cast.rfl index 8ceb63282..59fe918fd 100644 --- a/test/rfl/expr/narrow_cast.rfl +++ b/test/rfl/expr/narrow_cast.rfl @@ -93,13 +93,13 @@ ;; at expr.c:1360 lacked opcode gating, so OP_CAST hit the OP_ISNULL ;; specialization and filled dst with 0 regardless of input. Fix gates ;; the branch on opc and adds a CAST arm that applies truthy semantics -;; treating NULL_I64 (INT64_MIN) sentinel as false. -;; Input: [1 2 0Nl 4 5] → [true true false true true]. +;; treating the non-zero NULL_I64 (INT64_MIN) sentinel as true. +;; Input: [1 2 0Nl 4 5] → [true true true true true]. (set TnullI_bool (at (select {x: (as 'BOOL v) from: TnullI}) 'x)) (type TnullI_bool) -- 'B8 (at TnullI_bool 0) -- true (at TnullI_bool 1) -- true -(at TnullI_bool 2) -- false ;; null → false (was 0 via ISNULL-stuck bug) +(at TnullI_bool 2) -- true ;; non-zero null sentinel → true (at TnullI_bool 3) -- true (at TnullI_bool 4) -- true diff --git a/test/rfl/fused/fused_take_early_stop.rfl b/test/rfl/fused/fused_take_early_stop.rfl index 66e0c8bec..a42ab31ef 100644 --- a/test/rfl/fused/fused_take_early_stop.rfl +++ b/test/rfl/fused/fused_take_early_stop.rfl @@ -74,3 +74,14 @@ tcnt -- 1 (sum FD) -- 104852100 (first FD) -- 200007 (at (select {x: x from: TK where: (and (== c 7) (> x 900000)) asc: s take: 3}) 'x) -- [900007 901007 902007] + +;; A nested `and` is the flat `and` of its leaves: (and (and a b) c) takes +;; the fused path as (and a b c) does, and keeps the null flags of the rows +;; it gathers: p is null on every 7th row, so x = 0 and 70 are null here. +(set TN (table [x c p] (list (til 1000) (% (til 1000) 10) (til 1000)))) +(set TN (update {from: TN p: (if (== 0 (% p 7)) 0Nl p)})) +(at (select {from: TN where: (and (and (== c 0) (>= x 0)) (< x 500)) take: 10}) 'x) -- [0 10 20 30 40 50 60 70 80 90] +(at (select {from: TN where: (and (== c 0) (and (>= x 0) (and (< x 500) (!= x 30)))) take: 3}) 'x) -- [0 10 20] +(sum (nil? (at (select {from: TN where: (and (and (== c 0) (>= x 0)) (< x 500)) take: 10}) 'p))) -- 2 +;; the fused top-K reads the same gate +(at (select {from: TN where: (and (and (== c 0) (>= x 100)) (< x 500)) desc: x take: 3}) 'x) -- [490 480 470] diff --git a/test/rfl/group/affine_float_bias_type.rfl b/test/rfl/group/affine_float_bias_type.rfl new file mode 100644 index 000000000..ec295c74f --- /dev/null +++ b/test/rfl/group/affine_float_bias_type.rfl @@ -0,0 +1,78 @@ +;; affine_float_bias_type.rfl — sum/avg of (col +/- c) over an integer col with +;; a FLOAT constant c is F64, as the builtin over the column gives it, and so +;; are the linear forms (* col 2.0) and (- 100.0 col). +;; +;; try_affine_sumavg_input folded a whole-number FLOAT c (100.0, 2.0e) into an +;; integer bias on the integer accumulator, and const_expr_to_i64 did the same +;; for the linear plan, so SUM came back I64: keyless selects over in-memory +;; and splayed tables, grouped selects over zero rows, grouped top-N +;; (desc:/asc: take:) and the parted by-dict route. 100.5 was declined and +;; already F64. The scalar route delays a whole-number FLOAT bias only when +;; type and row-count bounds prove exact per-row and reduction arithmetic; +;; every other route, and the linear plan, evaluate the FLOAT expression. +;; @requires: posix + +;; ─── fixtures: nullable I64 w, I32 i, non-null n and U8 u ────────────────── +(set T (table [k w n i u] (list [0 1 0 1 0] [1 2 0Nl 4 50] [1 2 3 4 5] (as 'I32 [1 2 0Nl 4 50]) (as 'U8 [1 2 3 4 5])))) +(.sys.exec "rm -rf /tmp/rfl_affine_f64") +(.db.splayed.set "/tmp/rfl_affine_f64/sp/t/" T "/tmp/rfl_affine_f64/sp/.sym") +(set S (.db.splayed.get "/tmp/rfl_affine_f64/sp/t/" "/tmp/rfl_affine_f64/sp/.sym")) +;; 2000-group sym key over 2 partitions (the parted by-dict route) +(set K (% (* (til 8000) 7919) 2000)) +(set W (table [s w v] (list (at (as 'SYMBOL (map (fn [j] (format "w%" j)) (til 2000))) K) (as 'I64 (map (fn [k] (if (< (% k 5) 1) 0Nl (% k 13))) K)) (til 8000)))) +(.db.splayed.set "/tmp/rfl_affine_f64/tn/2024.01.01/t/" (take W 4000) "/tmp/rfl_affine_f64/tn/.sym") +(.db.splayed.set "/tmp/rfl_affine_f64/tn/2024.01.02/t/" (drop W 4000) "/tmp/rfl_affine_f64/tn/.sym") +(set P (.db.parted.get "/tmp/rfl_affine_f64/tn" 't)) + +;; ─── keyless, in-memory: c on either side, -, F32 c, narrow columns ─────── +(at (select {m: (sum (+ w 100.0)) from: T}) 'm) -- [457.0] +(at (select {m: (sum (+ 100.0 w)) from: T}) 'm) -- [457.0] +(at (select {m: (sum (- w 100.0)) from: T}) 'm) -- [-343.0] +(at (select {m: (sum (+ w 2.0e)) from: T}) 'm) -- [65.0] +(at (select {m: (sum (+ i 100.0)) from: T}) 'm) -- [457.0] +(at (select {m: (sum (+ u 100.0)) from: T}) 'm) -- [515.0] + +;; ─── keyless, filtered, zero rows, splayed ──────────────────────────────── +(at (select {m: (sum (+ w 100.0)) from: T where: (> n 3)}) 'm) -- [254.0] +(at (select {m: (sum (+ w 100.0)) from: T where: (> n 9)}) 'm) -- [0.0] +(type (at (select {m: (sum (+ w 100.0)) from: (take T 0)}) 'm)) -- 'F64 +(at (select {m: (sum (+ w 100.0)) from: S}) 'm) -- [457.0] + +;; ─── the F64 sum does not wrap at 2^63, as the builtin's does not ───────── +(set B (table [w] (list [9000000000000000000 9000000000000000000]))) +(== (at (at (select {m: (sum (+ w 100.0)) from: B}) 'm) 0) 1.8e19) -- true + +;; Integer accumulation followed by a bias is not equivalent to converting +;; and adding on each row: the first I64 loses its low bit on F64 conversion. +(set C (table [x k] (list [9007199254740993 -9007199254740992] [0 0]))) +(set CV (+ (at C 'x) 0.5)) +(at (select {m: (sum (+ x 0.5)) from: C}) 'm) -- (enlist (sum CV)) +(at (select {m: (avg (+ x 0.5)) from: C}) 'm) -- (enlist (avg CV)) +(at (select {m: (sum (+ x 0.5)) from: C by: k}) 'm) -- (enlist (sum CV)) +(at (select {m: (sum (+ x 1.0)) from: C}) 'm) -- [1.0] +;; A narrow column can also round per row when the FLOAT bias is large. +(set D (table [h] (list (as 'I16 [1 2])))) +(at (select {m: (sum (+ h 9007199254740992.0)) from: D}) 'm) -- (enlist (sum (+ (at D 'h) 9007199254740992.0))) + +;; ─── avg: the F64 values summed, then divided, as the builtin avg does ──── +(set X (+ (at W 'w) -3.0)) +(== (at (select {m: (avg (+ w -3.0)) from: W}) 'm) (enlist (avg X))) -- [true] + +;; ─── linear plan: a FLOAT factor or constant over a non-null column ─────── +(at (select {m: (sum (* n 2.0)) from: T}) 'm) -- [30.0] +(at (select {m: (sum (- 100.0 n)) from: T}) 'm) -- [485.0] + +;; ─── grouped: zero rows, top-N, parted by-dict ──────────────────────────── +(type (at (select {m: (sum (+ w 100.0)) from: T by: k where: (> n 9)}) 'm)) -- 'F64 +(type (at (select {m: (sum (+ w 100.0)) from: (take T 0) by: k}) 'm)) -- 'F64 +(at (select {m: (sum (+ w 100.0)) from: T by: k desc: m take: 1}) 'm) -- [251.0] +(at (select {m: (sum (+ w 100.0)) from: T by: k asc: m take: 1}) 'm) -- [206.0] +(take (at (select {m: (sum (+ w 100.0)) from: P by: {s: s z: (% v 1) t: s}}) 'm) 3) -- [0.0 432.0 420.0] +(at (select {m: (sum (+ w 100.0)) from: P by: {s: s z: (% v 1) t: s} desc: m take: 3}) 'm) -- [448.0 448.0 448.0] + +;; ─── controls: unchanged on dev ─────────────────────────────────────────── +(at (select {m: (sum (+ w 100.5)) from: T}) 'm) -- [459.0] +(at (select {m: (sum (+ w 100)) from: T}) 'm) -- [457] +(at (select {m: (sum (+ w 100.0)) from: T by: k}) 'm) -- [251.0 206.0] + +(.sys.exec "rm -rf /tmp/rfl_affine_f64") diff --git a/test/rfl/group/count_distinct_paths.rfl b/test/rfl/group/count_distinct_paths.rfl index 054ca2fe1..f5d13ec03 100644 --- a/test/rfl/group/count_distinct_paths.rfl +++ b/test/rfl/group/count_distinct_paths.rfl @@ -13,6 +13,7 @@ ;; - n_groups <= 50000 → count_distinct_per_group_buf ;; └─ n_groups >= 4 + pool >= 2 + flat → parallel cdpg_buf_par_fn ;; └─ else / type miss → exec_count_distinct per group +;; - either, when ray_cd_bounded_preferred → ray_cd_bounded (section 14) ;; ;; All inputs are happy-path: correct types/shapes, no null payloads. ;; @@ -328,3 +329,140 @@ (sum (at Rxc 'c)) -- 6 ;; Ungrouped reference: distinct(v) over the whole column = {10,20,30,40,50,60} = 6. (count (distinct (at Txc 'v))) -- 6 + +;; ════════════════════════════════════════════════════════════════════ +;; 14. Bounded scatter — ray_cd_bounded (cdfuse.c) +;; From 65536 rows up to 50000 groups the post-group scatter counts +;; (count (distinct col)) from the key and value columns themselves — +;; no row map, no per-group slices — where the slices would not fit +;; the memory budget, for a parted or not-resident column, and (sampled, +;; from 64 M rows) for a dominant group or pairs that dedup to a quarter +;; of the rows. In memory these shapes take the slices (parted ones +;; too, below 64 M rows); the same selects under a budget that sends +;; them to the kernel, its route asserted, are agg_contract/ +;; cd_bounded_select. A second aggregate beside the +;; count keeps these off the count-only rewrite (try_count_distinct_ +;; v2_rewrite), which is how a select reaches the scatter. The +;; oracle is the same count through a group by [k v]. The kernel's +;; rounds under a small budget, its slot layouts and single-group +;; shapes are in test_agg_contract.c (agg_contract/cd_bounded_*). +;; ════════════════════════════════════════════════════════════════════ + +(set Nb2 300000) +(set ib (til Nb2)) +(set Tb2 (table [k v a] (list (% ib 97) (% ib 503) (% ib 5)))) +;; 97 and 503 are coprime and every group has >= 503 rows: each group +;; holds all 503 values. The other aggregates ride the same select. +(set Rb2 (select {s: (sum a) c: (count a) m: (avg a) u: (count (distinct v)) from: Tb2 by: k})) +(count Rb2) -- 97 +(distinct (at Rb2 'u)) -- [503] +(sum (at Rb2 's)) -- 600000 +(sum (at Rb2 'c)) -- 300000 +(set Ob2 (select {n: (count x) from: (select {x: (count v) from: Tb2 by: [k v]}) by: k asc: k})) +(at (select {u: (count (distinct v)) c: (count v) from: Tb2 by: k asc: k}) 'u) -- (at Ob2 'n) + +;; pseudo-random pairs with repeats, I64 and I32 values (8- and 4-byte slots) +(set Tb3 (table [k v w] (list (% (* ib 40503) 1000) (% (* ib 7919) 61) (as 'I32 (% (* ib 7919) 61))))) +(set Ob3 (select {n: (count x) from: (select {x: (count v) from: Tb3 by: [k v]}) by: k asc: k})) +(set Rb3 (select {u: (count (distinct v)) uw: (count (distinct w)) c: (count v) from: Tb3 by: k asc: k})) +(at Rb3 'u) -- (at Ob3 'n) +(at Rb3 'uw) -- (at Ob3 'n) + +;; nulls in the key and in the value: the null key is a group of its own, +;; a null value one distinct value +;; k 0N -> 0N 0N one k 1 -> 10 10 one +;; k 2 -> 0N 30 two k 3 -> 20 40 two +(set Mb 262144) +(set rb (til Mb)) +(set gb (% rb 4)) +(set Tbn (table [k v] (list (at [0N 1 2 3] gb) (at [0N 10 0N 20 0N 10 30 40] (% rb 8))))) +(set Rbn (select {n: (count (distinct v)) c: (count v) from: Tbn by: k asc: k})) +(at Rbn 'n) -- [1 1 2 2] +(at Rbn 'k) -- [0N 1 2 3] + +;; a single group: all-distinct and all-equal values +(set Tb1 (table [k v w] (list (* 0 rb) rb (* 0 rb)))) +(set Rb1 (select {n: (count (distinct v)) m: (count (distinct w)) c: (count v) from: Tb1 by: k})) +(at Rb1 'n) -- [262144] +(at Rb1 'm) -- [1] + +;; SYM values, and STR values (the slices serve those): five per group +(set Tbs (table [k v] (list (% rb 3) (at ['a 'b 'c 'd 'e] (% rb 5))))) +(at (select {n: (count (distinct v)) c: (count v) from: Tbs by: k}) 'n) -- [5 5 5] +(set SVb (as 'STR (list "p" "q" "r" "s" "t"))) +(set Tbt (table [k v] (list (% rb 3) (at SVb (% rb 5))))) +(at (select {n: (count (distinct v)) c: (count v) from: Tbt by: k}) 'n) -- [5 5 5] + +;; F64 values: every NaN is the null, -0.0 is 0.0 +;; g0 -> 0Nf 0Nf one g1 -> 1.5 1.5 one g2 -> -0.0 0.0 one g3 -> 2.5 3.5 two +(set Tbf (table [k v] (list gb (at [0Nf 1.5 -0.0 2.5 0Nf 1.5 0.0 3.5] (% rb 8))))) +(at (select {n: (count (distinct v)) c: (count v) from: Tbf by: k}) 'n) -- [1 1 1 2] +(set nanb (% 0.0 0.0)) +(set Tbf2 (table [k v] (list gb (at (list nanb 1.5 nanb 2.5 0Nf 1.5 7.5 3.5) (% rb 8))))) +(at (select {n: (count (distinct v)) c: (count v) from: Tbf2 by: k}) 'n) -- [1 1 2 2] + +;; a selection (where:) over the rows: mixed morsels +(set Wb (select {u: (count (distinct v)) c: (count v) from: Tb3 where: (== (% (* ib 13) 7) 2) by: k asc: k})) +(set Ob4 (select {n: (count x) from: (select {x: (count v) from: Tb3 where: (== (% (* ib 13) 7) 2) by: [k v]}) by: k asc: k})) +(at Wb 'u) -- (at Ob4 'n) +(at Wb 'k) -- (at Ob4 'k) + +;; a composite key: the row map is built, the slices are not +;; 77 groups (period lcm(7,11)), each sees all 13 residues of v +(set Tbm (table [k1 k2 v] (list (% rb 7) (% rb 11) (% rb 13)))) +(set Rbm (select {n: (count (distinct v)) c: (count v) from: Tbm by: [k1 k2]})) +(count Rbm) -- 77 +(distinct (at Rbm 'n)) -- [13] + +;; more rows than one chunk of tasks: 1.2 M rows, 50000 groups (the last +;; group count the scatter takes), 5 values a group +(set Nbc 1200000) +(set ic (til Nbc)) +(set Tbc (table [k v] (list (% ic 50000) (% (div ic 50000) 5)))) +(set Rbc (select {n: (count (distinct v)) c: (count v) from: Tbc by: k})) +(count Rbc) -- 50000 +(distinct (at Rbc 'n)) -- [5] +(sum (at Rbc 'c)) -- 1200000 + +;; the count-only shape (ClickBench's #9 form) below the fused kernel's +;; rows and without a dense (K, X) pack, then desc/take on the count +(set Tb9 (table [k v] (list (% rb 211) (% (* rb 104729) 200003)))) +(set Rb9 (select {u: (count (distinct v)) from: Tb9 by: k desc: u take: 3})) +(count Rb9) -- 3 +(set Ob9 (select {n: (count x) from: (select {x: (count v) from: Tb9 by: [k v]}) by: k desc: n take: 3})) +(at Rb9 'u) -- (at Ob9 'n) + +;; a parted table: 3 partitions of 30000 rows, the last without v (its rows +;; read as nulls). By k: values = g mod 10 over [0, 1500) plus the null +;; = 151; by the partition date (MAPCOMMON key): 1000, 1000, the null; by +;; a SYM key: [0, 1500) plus the null; a MAPCOMMON value: 3 dates. +(set Mp 30000) +(set ip (til Mp)) +(.sys.exec "rm -rf /tmp/rfl_cdb") +(.db.splayed.set "/tmp/rfl_cdb/2024.01.01/t/" (table [k s v] (list (% ip 10) (at ['a 'b 'c] (% ip 3)) (% ip 1000)))) +(.db.splayed.set "/tmp/rfl_cdb/2024.01.02/t/" (table [k s v] (list (% ip 10) (at ['a 'b 'c] (% ip 3)) (+ 500 (% ip 1000))))) +(.db.splayed.set "/tmp/rfl_cdb/2024.01.03/t/" (table [k s] (list (% ip 10) (at ['a 'b 'c] (% ip 3))))) +(set Pb (.db.parted.get "/tmp/rfl_cdb/" 't)) +(count Pb) -- 90000 +(distinct (at (select {u: (count (distinct v)) c: (count k) from: Pb by: k}) 'u)) -- [151] +(at (select {u: (count (distinct v)) c: (count k) from: Pb by: date}) 'u) -- [1000 1000 1] +(distinct (at (select {u: (count (distinct v)) c: (count k) from: Pb by: s}) 'u)) -- [1501] +(distinct (at (select {u: (count (distinct date)) c: (count k) from: Pb by: k}) 'u)) -- [3] +(at (select {u: (count (distinct v)) c: (count k) from: Pb where: (> k 4) by: k}) 'u) -- [151 151 151 151 151] +(.sys.exec "rm -rf /tmp/rfl_cdb") -- 0 + +;; a parted table whose SYM columns index a symfile of 40100 symbols at 16 +;; bits: ids past 32767 must read unsigned. Partition 1: 40000 values a +;; 100th each per key (400 distinct a key); partition 2: 3000 values over +;; the same keys. agg_contract/cd_bounded_select counts the same table +;; through the kernel. +(set Zb (as 'SYM (as 'STR (+ 2000000 (til 40000))))) +(set Kb (as 'SYM (as 'STR (+ 3000000 (til 100))))) +(set jb (til 100000)) +(.sys.exec "rm -rf /tmp/rfl_cdb16") +(.db.splayed.set "/tmp/rfl_cdb16/2024.01.01/t/" (table [v k c] (list (at Zb (% jb 40000)) (at Kb (% jb 100)) jb))) +(.db.splayed.set "/tmp/rfl_cdb16/2024.01.02/t/" (table [v k c] (list (at Zb (% (* jb 7919) 3000)) (at Kb (% jb 100)) jb))) +(set Pb16 (.db.parted.get "/tmp/rfl_cdb16/" 't)) +(sum (at (select {u: (count (distinct v)) c: (count c) from: Pb16 by: k}) 'u)) -- 42940 +(sum (at (select {n: (count x) from: (select {x: (count c) from: Pb16 by: [k v]}) by: k}) 'n)) -- 42940 +(.sys.exec "rm -rf /tmp/rfl_cdb16") -- 0 diff --git a/test/rfl/group/dense_wide_sym_range.rfl b/test/rfl/group/dense_wide_sym_range.rfl new file mode 100644 index 000000000..956130a7b --- /dev/null +++ b/test/rfl/group/dense_wide_sym_range.rfl @@ -0,0 +1,71 @@ +;; A grouping by one FILE-domain symbol column whose ids are spread over a +;; range wider than the row count (here 600k rows, ids across 0..600100 in +;; the shared symbol file) counts into one array of the id range when that +;; array fits the memory budget, instead of the radix scatter. The answers +;; are those of the same grouping over a selection that keeps every row but is +;; not trivially true, which takes the radix route. Plain, gen-2 compressed, +;; parted and desc/asc take: N tables. +(.sys.exec "rm -rf /tmp/rfl_dwsr/") -- 0 +(set N 600000) +(set i (til N)) +(set pad (as 'SYMBOL (as 'STR i))) +(set both (concat pad (as 'SYMBOL (as 'STR (+ N (til 100)))))) +(set m (as 'I64 (== 0 (% i 5)))) +(set key (at both (+ (* m (+ N (% i 100))) (* (- 1 m) (* 16 (% (* i 31) 40000)))))) +(set v (% i 97)) +(set T (table [pad key v] (list pad key v))) +(.db.splayed.set "/tmp/rfl_dwsr/plain/" T) +(.db.splayed.set "/tmp/rfl_dwsr/gen2/" T "/tmp/rfl_dwsr/gen2.sym" {compress: true}) +(set same (fn [A B] (and (== (count A) (count B)) (all (== (at (select {from: A asc: key}) 'c) (at (select {from: B asc: key}) 'c))) (all (== (as 'STR (at (select {from: A asc: key}) 'key)) (as 'STR (at (select {from: B asc: key}) 'key))))))) +(set check (fn [F] (do (let A (select {from: F by: key c: (count key)})) (let B (select {from: F by: key c: (count key) where: (!= (% v 1000) 999)})) (let AS (select {from: F by: key c: (count key) s: (sum v)})) (let BS (select {from: F by: key c: (count key) s: (sum v) where: (!= (% v 1000) 999)})) (list (same A B) (all (== (at (select {from: AS asc: key}) 's) (at (select {from: BS asc: key}) 's))) (== (sum (at A 'c)) N) (count A))))) +(set RP (check (.db.splayed.get "/tmp/rfl_dwsr/plain/"))) +(set RG (check (.db.splayed.get "/tmp/rfl_dwsr/gen2/" "/tmp/rfl_dwsr/gen2.sym"))) +(at RP 0) -- true +(at RP 1) -- true +(at RP 2) -- true +(at RG 0) -- true +(at RG 1) -- true +(at RG 2) -- true +(== (at RP 3) (at RG 3)) -- true +(at RP 3) -- 30026 +;; top-N: counts equal the full grouping's largest / smallest +(set F (.db.splayed.get "/tmp/rfl_dwsr/plain/")) +(set O (select {from: F by: key c: (count key) where: (!= (% v 1000) 999)})) +(set top (select {from: F by: key c: (count key) desc: c take: 10})) +(count top) -- 10 +(all (== (at top 'c) (at (take (xdesc O 'c) 10) 'c))) -- true +(set bot (select {from: F by: key c: (count key) asc: c take: 10})) +(all (== (at bot 'c) (at (take (xasc O 'c) 10) 'c))) -- true +;; ties at the boundary are cut by first row, as the radix route cuts them: +;; the same groups, not only the same counts +(set topr (select {from: F by: key c: (count key) desc: c take: 10 where: (!= (% v 1000) 999)})) +(set botr (select {from: F by: key c: (count key) asc: c take: 10 where: (!= (% v 1000) 999)})) +(all (== (as 'STR (at top 'key)) (as 'STR (at topr 'key)))) -- true +(all (== (as 'STR (at bot 'key)) (as 'STR (at botr 'key)))) -- true +(set O2 (select {from: F by: key c: (count key) s: (sum v) where: (!= (% v 1000) 999)})) +(set top2 (select {from: F by: key c: (count key) s: (sum v) desc: c take: 10})) +(all (== (as 'STR (at top2 'key)) (as 'STR (at (take (xdesc O2 'c) 10) 'key)))) -- true +(all (== (at top2 's) (at (take (xdesc O2 'c) 10) 's))) -- true +(set F2 (.db.splayed.get "/tmp/rfl_dwsr/gen2/" "/tmp/rfl_dwsr/gen2.sym")) +(all (== (as 'STR (at (select {from: F2 by: key c: (count key) desc: c take: 10}) 'key)) (as 'STR (at top 'key)))) -- true +(all (== (as 'STR (at (select {from: F2 by: key c: (count key) asc: c take: 10}) 'key)) (as 'STR (at bot 'key)))) -- true +;; an unordered take: N is the first N groups in first-seen order +(set first5 (select {from: F by: key c: (count key) take: 5})) +(count first5) -- 5 +(all (== (as 'STR (at first5 'key)) (as 'STR (take (distinct (at F 'key)) 5)))) -- true +(== (sum (at first5 'c)) (count (where (in (at F 'key) (at first5 'key))))) -- true +;; the nested form: the top-N result as the source of another select +(set nested (select {from: (select {from: F by: key c: (count key) desc: c take: 10}) one: 1 key: key c: c})) +(all (== (at nested 'c) (at top 'c))) -- true +;; the same rows as three partitions of one parted table +(set wr (fn [k] (.db.splayed.set (format "/tmp/rfl_dwsr/parted/%/t/" (+ k 1)) (table [pad key v] (list (at pad (+ (* k 200000) (til 200000))) (at key (+ (* k 200000) (til 200000))) (at v (+ (* k 200000) (til 200000))))) "/tmp/rfl_dwsr/parted/.sym" {compress: false}))) +(count (map wr (til 3))) -- 3 +(set PT (.db.parted.get "/tmp/rfl_dwsr/parted/" 't)) +(count PT) -- 600000 +(set RT (check PT)) +(at RT 0) -- true +(at RT 1) -- true +(at RT 2) -- true +(at RT 3) -- 30026 +(all (== (at (select {from: PT by: key c: (count key) desc: c take: 10}) 'c) (at top 'c))) -- true +(.sys.exec "rm -rf /tmp/rfl_dwsr/") -- 0 diff --git a/test/rfl/group/dense_wide_where.rfl b/test/rfl/group/dense_wide_where.rfl new file mode 100644 index 000000000..0d7797fb3 --- /dev/null +++ b/test/rfl/group/dense_wide_where.rfl @@ -0,0 +1,20 @@ +;; A where-filtered count over an integer key whose range is within the row +;; count (600k rows, 590k key values) counts the selected rows only, whichever +;; route takes it (on a small memory budget the one shared slab does, see +;; agg_contract/dense_wide_budget_sel). Each answer is checked against the +;; same grouping over a table of just the selected rows. +(set N 600000) +(set i (til N)) +(set T (table [k v] (list (% (* i 7919) 590000) i))) +(set S (select {from: T where: (> v 1000)})) +(count S) -- 598999 +(set same (fn [A B] (and (== (count A) (count B)) (all (== (at (select {from: A asc: k}) 'k) (at (select {from: B asc: k}) 'k))) (all (== (at (select {from: A asc: k}) 'c) (at (select {from: B asc: k}) 'c)))))) +(same (select {from: T by: k c: (count v) where: (> v 1000)}) (select {from: S by: k c: (count v)})) -- true +(same (select {from: T by: k c: (count v) where: (and (> v 1000) (< v 300000))}) (select {from: (select {from: T where: (and (> v 1000) (< v 300000))}) by: k c: (count v)})) -- true +(set A (select {from: T by: k c: (count v) s: (sum v) where: (> v 1000)})) +(set B (select {from: S by: k c: (count v) s: (sum v)})) +(all (== (at (select {from: A asc: k}) 's) (at (select {from: B asc: k}) 's))) -- true +(sum (at A 'c)) -- 598999 +(set top (select {from: T by: k c: (count v) desc: c take: 5 where: (> v 1000)})) +(count top) -- 5 +(all (== (at top 'c) (at (take (xdesc (select {from: S by: k c: (count v)}) 'c) 5) 'c))) -- true diff --git a/test/rfl/group/derived_key_sym_domain.rfl b/test/rfl/group/derived_key_sym_domain.rfl index 8f6ccd544..9e036c7ed 100644 --- a/test/rfl/group/derived_key_sym_domain.rfl +++ b/test/rfl/group/derived_key_sym_domain.rfl @@ -77,13 +77,17 @@ ;; the derived name yields to an aggregate of the same name (== (cols (select {from: T by: (substr ref 0 2) ref: (min ref) c: (count v)})) ['key 'ref 'c]) -- [true true true] -;; a quoted symbol that names a column of the table resolves to that column -;; in the compiled key — such a key is not a function of the symbol alone -(set RQ (select {from: T by: (if (== 'v ref) "same" "diff") c: (count v)})) -(set OQ (select {from: (select {from: T k: (if (== 'v ref) "same" "diff") v: v}) by: k c: (count v)})) -(count RQ) -- 1 -(== (at (value RQ) 0) (at (value OQ) 0)) -- [true] -(== (at RQ 'c) (at OQ 'c)) -- [true] +;; A quoted symbol naming a column resolves to that column. Equality +;; between F64 column v and SYM ref is incompatible, not a raw-ID false value. +(select {from: T by: (if (== 'v ref) "same" "diff") c: (count v)}) !- type +(select {from: (select {from: T k: (if (== 'v ref) "same" "diff") v: v}) by: k c: (count v)}) !- type +;; Preserve a supported two-column derived key with the same quoted-column +;; resolution. It must not be evaluated once per distinct symbol. Compare +;; against unquoted column reads and the earlier independently materialised key. +(set RQ (select {from: T by: (if (> 'v 50) (substr ref 0 4) ref) c: (count ref)})) +(set OQ (select {from: (select {from: T k: (if (> v 50) (substr ref 0 4) ref) ref: ref}) by: k c: (count ref)})) +(all (== (FP2 RQ) (FP2 OQ))) -- true +(all (== (FP2 RQ) (FP2 R3))) -- true ;; ── the column's ids in a FILE domain (a splayed table read back) ────── ;; The per-symbol evaluation then runs over the vocabulary's bytes, a @@ -239,7 +243,7 @@ ;; inside one expression (a line of this file interns its own names when ;; it is parsed), after a first call of each shape (hidden names) and of ;; (.sys.mem) itself (its first call interns its own key names). -(count (.sys.mem)) -- 18 +(count (.sys.mem)) -- 21 (set nogrow (fn [f] (do (let s0 (at (.sys.mem) 'sym-count)) (let r (f)) (list (- (at (.sys.mem) 'sym-count) s0) r)))) (set KV (fn [t] (select {from: t by: (let p (str-find ref "://") (let s (substr ref (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr ref 1 4) "http") (not (nil? sl))) (substr r 1 sl) ref))))) c: (count ref) l: (avg (strlen ref)) mn: (min ref) where: (!= ref "")}))) (set KD (fn [t] (select {from: t by: (let p (str-find ref "://") (let s (substr ref (+ p (abs 4)) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr ref 1 4) "http") (not (nil? sl))) (substr r 1 sl) ref))))) c: (count ref) sv: (sum v)}))) diff --git a/test/rfl/group/derived_key_vocab_aggs.rfl b/test/rfl/group/derived_key_vocab_aggs.rfl index 6c958ae0f..ae1a32cb9 100644 --- a/test/rfl/group/derived_key_vocab_aggs.rfl +++ b/test/rfl/group/derived_key_vocab_aggs.rfl @@ -43,7 +43,7 @@ ;; the in-memory one. The snapshot is taken inside one expression (a line ;; of this file interns its own names when it is parsed), and (.sys.mem) is ;; called once beforehand (its first call interns its own key names). -(count (.sys.mem)) -- 18 +(count (.sys.mem)) -- 21 (set nogrow (fn [f] (do (let s0 (at (.sys.mem) 'sym-count)) (let r (f)) (list (- (at (.sys.mem) 'sym-count) s0) r)))) (set NG (nogrow (fn [] (key F)))) (at NG 0) -- 0 @@ -79,4 +79,62 @@ (set RU (select {from: F by: (substr ref 1 4) c: (count ref)})) (as 'STR (at RU 'ref)) -- ["" "http" "ab5" "ab0" "ab9" "ab4" "ab3" "ab8" "ab2" "ab1" "ab6" "ab7"] (at RU 'c) -- [18203 164471 1733 1736 1733 1733 1734 1731 1731 1731 1732 1732] -(.sys.exec "rm -rf /tmp/rfl_dkv/") -- 0 +;; ── the same column under a name no global holds ─────────────────────── +;; (`ref` is a global above as well; the having match below reads an +;; aggregate over a global's name as one over a constant, not a column) +(.sys.exec "rm -rf /tmp/rfl_dkv_u/") -- 0 +(.db.splayed.set "/tmp/rfl_dkv_u/" (table [url v] (list (at T 'ref) (at T 'v)))) +(set FU (.db.splayed.get "/tmp/rfl_dkv_u/")) +;; the key "" comes first, wherever its first value lies (the place a key +;; domain gives the empty string, and the row path's order) +(set E (select {from: FU by: (substr url 40 3) c: (count url) where: (!= url "")})) +(as 'STR (at E 'url)) -- ["" "/pa" "pag" "age" "e?i" "ge?"] +(at E 'c) -- [121196 34795 21138 4268 200 200] +(as 'STR (at (select {from: FU by: (substr url 40 3) c: (count url) sv: (sum v) where: (!= url "")}) 'url)) -- ["" "/pa" "pag" "age" "e?i" "ge?"] +;; the first value with a key, "https://host29.example.org/p/1919", keys "19" +(set E2 (select {from: FU by: (substr url 30 2) c: (count url) where: (!= url "")})) +(take (as 'STR (at E2 'url)) 6) -- ["" "19" "83" "/p" "16" "14"] +(take (at E2 'c) 6) -- [17660 4134 536 51927 3266 2998] +;; no where: the null value and the short values share the key "": the +;; group's min and max skip the null, its avg divides by the others' rows +(set N3 (select {from: FU by: (substr url 40 3) c: (count url) mn: (min url) mx: (max url) l: (avg (strlen url))})) +(set N3O (select {from: FU by: (substr url 40 3) c: (count url) mn: (min url) mx: (max url) l: (avg (strlen url)) sv: (sum v)})) +(as 'STR (at (select {from: N3 asc: url}) 'mn)) -- ["ab0" "http://www.host10.example.org/path/1200/page?id=15600" "http://www.host0.example.org/path/210/page?id=2730" "http://www.host3.example.org/path/3/page?id=39" "http://www.host2.example.org/path/72/page?id=936" "http://www.host0.example.org/path/1050/page?id=13650"] +(all (== (as 'STR (at (select {from: N3 asc: url}) 'mn)) (as 'STR (at (select {from: N3O asc: url}) 'mn)))) -- true +(all (== (as 'STR (at (select {from: N3 asc: url}) 'mx)) (as 'STR (at (select {from: N3O asc: url}) 'mx)))) -- true +(all (== (at (select {from: N3 asc: url}) 'l) (at (select {from: N3O asc: url}) 'l))) -- true +(all (== (at (select {from: N3 asc: url}) 'c) (at (select {from: N3O asc: url}) 'c))) -- true +;; ── an enclosing where over the count ────────────────────────────────── +;; `(select {from: (select {… c: (count url) …}) where: (> c N)})` arms +;; the group emit filter for the inner grouping: the groups it drops are +;; dropped before their key or min is made. The enclosing where still runs, +;; so the answer is the row path's. +(set HQ (fn [t] (select {from: (select {from: t by: (let p (str-find url "://") (let s (substr url (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr url 1 4) "http") (not (nil? sl))) (substr r 1 sl) url))))) l: (avg (strlen url)) c: (count url) mn: (min url) where: (!= url "")}) where: (> c 2600)}))) +(set HV (HQ FU)) +(set HO (select {from: (select {from: FU by: (let p (str-find url "://") (let s (substr url (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr url 1 4) "http") (not (nil? sl))) (substr r 1 sl) url))))) l: (avg (strlen url)) c: (count url) mn: (min url) sv: (sum v) where: (!= url "")}) where: (> c 2600)})) +(count HV) -- 19 +(same HV HO 'c) -- true +(same HV HO 'l) -- true +(all (== (as 'STR (at HV 'mn)) (as 'STR (at HO 'mn)))) -- true +(all (== (as 'STR (at HV 'p)) (as 'STR (at HO 'p)))) -- true +;; a grouping that sorts and takes picks among all its groups first: the +;; five longest have about 866 rows each, so none passes the where +(set TK (fn [t] (select {from: t by: (let p (str-find url "://") (let s (substr url (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr url 1 4) "http") (not (nil? sl))) (substr r 1 sl) url))))) l: (avg (strlen url)) c: (count url) mn: (min url) where: (!= url "") desc: l take: 5}))) +(at (TK FU) 'c) -- [866 866 866 867 868] +(set TKH (fn [t] (select {from: (select {from: t by: (let p (str-find url "://") (let s (substr url (+ p 4) -1) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s) (let sl (str-find r "/") (if (and (within p [4 5]) (== (substr url 1 4) "http") (not (nil? sl))) (substr r 1 sl) url))))) l: (avg (strlen url)) c: (count url) mn: (min url) where: (!= url "") desc: l take: 5}) where: (> c 2600)}))) +(count (TKH FU)) -- 0 +;; the cut without a where: the kept group of the key "" holds the null value, +;; which its min skips +(set HQ2 (fn [t] (select {from: (select {from: t by: (substr url 40 3) c: (count url) mn: (min url) l: (avg (strlen url))}) where: (> c 30000)}))) +(as 'STR (at (HQ2 FU) 'mn)) -- ["ab0" "http://www.host10.example.org/path/1200/page?id=15600"] +(at (HQ2 FU) 'c) -- [139399 34795] +;; a generation-2 (compressed) store of the same column agrees +(.sys.exec "rm -rf /tmp/rfl_dkv_z/") -- 0 +(.db.splayed.set "/tmp/rfl_dkv_z/" (table [url v] (list (at T 'ref) (at T 'v))) "/tmp/rfl_dkv_z/.sym" {compress: true}) +(set FZ (.db.splayed.get "/tmp/rfl_dkv_z/" "/tmp/rfl_dkv_z/.sym")) +(count (HQ FZ)) -- 19 +(all (== (as 'STR (at (HQ FZ) 'mn)) (as 'STR (at HV 'mn)))) -- true +(all (== (at (HQ FZ) 'l) (at HV 'l))) -- true +(as 'STR (at (HQ2 FZ) 'mn)) -- ["ab0" "http://www.host10.example.org/path/1200/page?id=15600"] +(take (as 'STR (at (select {from: FZ by: (substr url 30 2) c: (count url) where: (!= url "")}) 'url)) 6) -- ["" "19" "83" "/p" "16" "14"] +(.sys.exec "rm -rf /tmp/rfl_dkv/ /tmp/rfl_dkv_u/ /tmp/rfl_dkv_z/") -- 0 diff --git a/test/rfl/group/emit_filter_v2_route.rfl b/test/rfl/group/emit_filter_v2_route.rfl index 41a1ba01d..a72449f38 100644 --- a/test/rfl/group/emit_filter_v2_route.rfl +++ b/test/rfl/group/emit_filter_v2_route.rfl @@ -134,3 +134,26 @@ ;; ascending: the smallest counts, again first-seen among the ties (set r9a (select {from: t9 by: [a b] c: (count v) asc: c take: 10})) (all (== (at r9a 'a) (take (at (select {from: f9 where: (== c (min c))}) 'a) 10))) -- true + +;; over a million rows, the top groups by count: the grouping cut, whichever +;; route answers (the grouping when it fits the memory budget, else two +;; passes: heavy hitters of the key hash, then the candidates' rows counted +;; by key), the same groups, counts and order, the tied ones by first row. +;; 1.2 M rows, about 700 K groups of one or two rows and +;; seven heavy ones, three of them tied at 850 around the 5th place; a +;; computed key (the minute) and a symbol key. +(set n10 1200000) +(set i10 (til n10)) +(set o10 (% (* i10 7919) n10)) +(set hc10 [900 880 860 850 850 850 840]) +(set h10 (as 'I64 (< o10 (sum hc10)))) +(set g10 (+ (* h10 (bin (- (sums hc10) hc10) o10)) (* (- 1 h10) (+ 100 (% (* (- o10 (sum hc10)) 13) 700000))))) +(set t10 (table [u et s] (list (+ 400000000000000000 (* (div g10 3) 1000003)) (+ 2013.07.01D00:00:00.000000000 (* 60000000000 (% g10 1440))) (at ['a 'b 'c 'd] (% g10 4))))) +(set f10 (xdesc (select {from: t10 by: {u: u m: (minute et) s: s} c: (count u)}) 'c)) +(set r10 (select {from: t10 by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 5})) +(at r10 'c) -- [900 880 860 850 850] +(all (== (at r10 'u) (take (at f10 'u) 5))) -- true +(all (== (at r10 'm) (take (at f10 'm) 5))) -- true +(all (== (as 'STR (at r10 's)) (as 'STR (take (at f10 's) 5)))) -- true +(set r10u (select {from: t10 by: u c: (count u) desc: c take: 2})) +(at r10u 'c) -- [2640 2550] diff --git a/test/rfl/group/group_key_types.rfl b/test/rfl/group/group_key_types.rfl index a0ff799a0..a9498f131 100644 --- a/test/rfl/group/group_key_types.rfl +++ b/test/rfl/group/group_key_types.rfl @@ -224,3 +224,32 @@ (at (select {c: (first (upper "a")) from: TSa by: s}) 'c) -- ["A" "A" "A"] (at (select {c: (last (trim " a")) from: TSa by: s}) 'c) -- ["a" "a" "a"] (at (select {c: (first "zz") from: TSa}) 'c) -- ["zz"] + +;; A null atom as an aggregate input is null in every row. The broadcast +;; copied its sentinel without setting HAS_NULLS, so no null skip fired: +;; (avg 0Nl) averaged INT64_MIN per group and wsum summed it. Keyless, the +;; SUM/AVG constant fold read 0Nl as INT64_MIN the same way. Oracle: the same +;; aggregate over a real all-null column z. +(set TNa (table [w y z] (list (% (til 70) 7) (as 'F64 (til 70)) (take 0Nl 70)))) +(at (select {s: (avg 0Nl) from: TNa by: w}) 's) -- [0Nf 0Nf 0Nf 0Nf 0Nf 0Nf 0Nf] +(at (select {s: (avg 0Nl) from: TNa by: w}) 's) -- (at (select {s: (avg z) from: TNa by: w}) 's) +(at (select {s: (wsum 0Nl y) from: TNa by: w}) 's) -- [0.0 0.0 0.0 0.0 0.0 0.0 0.0] +(at (select {s: (wsum 0Nl y) from: TNa by: w}) 's) -- (at (select {s: (wsum z y) from: TNa by: w}) 's) +(at (select {s: (wsum y 0Nl) from: TNa by: w}) 's) -- (at (select {s: (wsum y z) from: TNa by: w}) 's) +(at (select {s: (wavg y 0Nl) from: TNa by: w}) 's) -- (at (select {s: (wavg y z) from: TNa by: w}) 's) +(at (select {s: (avg 0Nf) from: TNa by: w}) 's) -- [0Nf 0Nf 0Nf 0Nf 0Nf 0Nf 0Nf] +(at (select {s: (min 0Nl) from: TNa by: w}) 's) -- (at (select {s: (min z) from: TNa by: w}) 's) +(at (select {s: (var 0Nl) from: TNa by: w}) 's) -- [0Nf 0Nf 0Nf 0Nf 0Nf 0Nf 0Nf] +(at (select {s: (avg 0Ni) from: TNa by: w}) 's) -- [0Nf 0Nf 0Nf 0Nf 0Nf 0Nf 0Nf] +(at (select {s: (avg 0Nl) from: TNa}) 's) -- [0Nf] +(at (select {s: (avg (+ y 0Nl)) from: TNa}) 's) -- [0Nf] +(at (select {s: (avg (* 2 0Nl)) from: TNa}) 's) -- [0Nf] +(at (select {s: (wsum 0Nl y) from: TNa}) 's) -- [0.0] + +;; I64 key spanning more than INT64_MAX: the dense-array min/max prescan +;; (minmax_scan_fn) checked its span budget as kmax - kmin in i64, which +;; overflowed (UBSan abort) once one batch had seen both extremes. +(set GKspan (table [k v] (list (take [-9000000000000000000 9000000000000000000 7] 3000) (til 3000)))) +(set GRspan (select {c: (count v) s: (sum v) from: GKspan by: (* k 1)})) +(at GRspan 'c) -- [1000 1000 1000] +(asc (at GRspan 's)) -- [1498500 1499500 1500500] diff --git a/test/rfl/group/parted_group_bydict.rfl b/test/rfl/group/parted_group_bydict.rfl index 71d339039..29674608c 100644 --- a/test/rfl/group/parted_group_bydict.rfl +++ b/test/rfl/group/parted_group_bydict.rfl @@ -104,5 +104,83 @@ (at RPd 'sv) -- (at RFd 'sv) (at RPd 'cv) -- (at RFd 'cv) +;; ══════════════════════════════════════════════════════════════════════════ +;; (e) LIST by-dict value — `by: {a: l}` over a LIST column groups as `by: l` +;; does (structural equality of the cells), under the alias. The by-dict +;; loop took only typed vectors and answered `by-dict val must be a +;; column vector`, in memory as well. Alongside: a composite key with a +;; LIST part built its key column with vec_new(LIST) (non-aggregate and +;; no-output forms), and the eval-level grouping read the cells of a +;; parted table row by row without flattening it (LIST, STR and GUID keys +;; beside a row output; a by-dict alias the flattened copy dropped). +;; ══════════════════════════════════════════════════════════════════════════ +(set LX1 [1 2 3 4 5]) +(set LX2 [10 20 30 40 50]) +(set LS ['a 'b 'a 'b 'a]) +(set LL (list [1 2] [3] [1 2] [0Nl] [3])) +(set LW ["p" "q" "p" "" "q"]) +(set LGU (take (guid 2) 5)) +(set LI (table [x s l w g] (list LX1 LS LL LW LGU))) +(.sys.exec "rm -rf /tmp/rfl_pgbd_list /tmp/rfl_pgbd_lsp") +(.db.splayed.set "/tmp/rfl_pgbd_list/1/t/" LI) +(.db.splayed.set "/tmp/rfl_pgbd_list/2/t/" (table [x s l w g] (list LX2 LS LL LW LGU))) +(.db.splayed.set "/tmp/rfl_pgbd_lsp/" LI) +(set LP (.db.parted.get "/tmp/rfl_pgbd_list/" 't)) +(set LSP (.db.splayed.get "/tmp/rfl_pgbd_lsp/")) +;; flat oracle of the parted rows (part 1 ++ part 2) +(set LF (table [x s l w g] (list (concat LX1 LX2) (concat LS LS) (concat LL LL) (concat LW LW) (concat LGU LGU)))) + +;; in memory: the alias names the key, the groups are by: l's +(set RLa (select {x: (sum x) from: LI by: {a: l}})) +(key RLa) -- [a x] +(at RLa 'a) -- (list [1 2] [3] [0Nl]) +(at RLa 'x) -- [4 7 4] +(at RLa 'x) -- (at (select {x: (sum x) from: LI by: l}) 'x) +(nil? (last (at RLa 'a))) -- [true] +(at (select {x: x from: LI by: {a: l}}) 'x) -- (list [1 3] [2 5] [4]) +(at (select {x: (count x) from: LI where: (> x 1) by: {a: l}}) 'a) -- (list [3] [1 2] [0Nl]) +(key (select {from: LI by: {a: l}})) -- [a x s l w g] +;; composite key with a LIST part, row output and no output +(set RLc (select {x: x from: LI by: [l s]})) +(at RLc 'l) -- (list [1 2] [3] [0Nl] [3]) +(at RLc 's) -- ['a 'b 'b 'a] +(at RLc 'x) -- (list [1 3] [2] [4] [5]) +(at (select {from: LI by: [l s]}) 'x) -- [1 2 4 5] +(set RLd (select {x: x from: LI by: {a: l t: s}})) +(key RLd) -- [a t x] +(at RLd 'a) -- (list [1 2] [3] [0Nl] [3]) +(at RLd 'x) -- (list [1 3] [2] [4] [5]) +(at (select {x: (sum x) from: LI by: {a: l t: s}}) 'x) -- [4 2 4 5] + +;; splayed: the same answers +(at (select {x: (sum x) from: LSP by: {a: l}}) 'a) -- (at RLa 'a) +(at (select {x: (sum x) from: LSP by: {a: l}}) 'a) -- (at (select {x: (sum x) from: LSP by: l}) 'l) +(at (select {x: (sum x) from: LSP by: {a: l}}) 'x) -- [4 7 4] +(at (select {x: x from: LSP by: {a: l t: s}}) 'x) -- (at RLd 'x) + +;; parted: parity with the flat oracle +(set PLa (select {x: (sum x) from: LP by: {a: l}})) +(at PLa 'a) -- (at (select {x: (sum x) from: LF by: {a: l}}) 'a) +(at PLa 'a) -- (at (select {x: (sum x) from: LP by: l}) 'l) +(at PLa 'x) -- [44 77 44] +(at PLa 'x) -- (at (select {x: (sum x) from: LF by: l}) 'x) +(at (select {x: (sum x) from: LP by: l}) 'x) -- [44 77 44] +(at (select {x: x from: LP by: l}) 'x) -- (at (select {x: x from: LF by: l}) 'x) +(at (select {x: x from: LP by: {a: l}}) 'x) -- (list [1 3 10 30] [2 5 20 50] [4 40]) +(at (select {x: (sum x) from: LP where: (> x 2) by: {a: l}}) 'x) -- (at (select {x: (sum x) from: LF where: (> x 2) by: {a: l}}) 'x) +(at (select {x: (sum x) from: LP by: [l s]}) 'x) -- [44 22 44 55] +(at (select {x: x from: LP by: [l s]}) 'x) -- (at (select {x: x from: LF by: [l s]}) 'x) +(set PLd (select {x: x from: LP by: {a: l t: s}})) +(at PLd 'a) -- (at RLd 'a) +(at PLd 'a) -- (at (select {x: x from: LP by: [l s]}) 'l) +(at PLd 'x) -- (list [1 3 10 30] [2 20] [4 40] [5 50]) +(at (select {from: LP by: {a: l t: s}}) 'x) -- [1 2 4 5] +;; STR and GUID keys beside a row output read the parted cells the same way +(at (select {x: x from: LP by: w}) 'x) -- (at (select {x: x from: LF by: w}) 'x) +(at (select {x: x from: LP by: {a: w}}) 'x) -- (list [1 3 10 30] [2 5 20 50] [4 40]) +(at (select {x: x from: LP by: g}) 'x) -- (at (select {x: x from: LF by: g}) 'x) +(at (select {x: x from: LP by: {a: g t: s}}) 'x) -- (at (select {x: x from: LF by: {a: g t: s}}) 'x) +(.sys.exec "rm -rf /tmp/rfl_pgbd_list /tmp/rfl_pgbd_lsp") + ;; ─── cleanup ───────────────────────────────────────────────────────────────── (.sys.exec "rm -rf /tmp/rfl_pgbd") diff --git a/test/rfl/group/parted_group_str_key.rfl b/test/rfl/group/parted_group_str_key.rfl new file mode 100644 index 000000000..8a71f83ad --- /dev/null +++ b/test/rfl/group/parted_group_str_key.rfl @@ -0,0 +1,67 @@ +;; parted_group_str_key.rfl — per-partition streaming GROUP BY whose key (or a +;; FIRST/LAST input) is a STR expression, under a selective WHERE (#737). +;; +;; `(if cond Referer "")` over a SYM column yields a STR key column in each +;; partition's partial. The merge pass concatenated the partials' key and agg +;; columns with a raw cell copy: a STR cell is a descriptor into its own +;; vector's string pool, so the merged column held pool offsets with no pool +;; and the merge group read a NULL string (SIGSEGV in agg_group_keys). The +;; merge now copies STR (and LIST) columns cell by cell into the output's own +;; storage. +;; +;; Ten partitions, so the merge runs two batches (MERGE_BATCH is 8) and the +;; second one carries the running result's STR columns too. Some partitions +;; keep no row (another date, another CounterID). The strings are longer than +;; the inline width, so they live in the pool. Gen 0 and gen 2 stores, each +;; against an identical-data flat oracle; 'group-perpart-runs proves the +;; streaming route ran. +(.sys.exec "rm -rf /tmp/rfl_pg737_0 /tmp/rfl_pg737_2") +(set refs (as 'SYM ["http://referer.example.com/long/path/a" "" "http://referer.example.com/long/path/b"])) +(set urls (as 'SYM ["http://url.example.com/some/long/page/1" "http://url.example.com/some/long/page/2" ""])) +(set mk (fn [n c d] (table [CounterID EventDate IsRefresh TraficSourceID SearchEngineID AdvEngineID Referer URL] (list (as 'I32 (+ c (% (til n) 97))) (+ d (* 0 (til n))) (as 'I16 (% (til n) 4)) (as 'I16 (+ 1 (% (til n) 2))) (as 'I16 (* 3 (% (til n) 3))) (as 'I16 (% (til n) 5)) (at refs (% (til n) 3)) (at urls (% (til n) 7)))))) +(set cids [0 0 1000 0 0 0 1000 0 0 0]) +(set days [2013.07.15 2013.07.14 2013.07.15 2013.07.15 2013.07.15 2013.07.14 2013.07.15 2013.07.15 2013.07.15 2013.07.15]) +(set parts (map (fn [k] (mk 4000 (at cids k) (at days k))) (til 10))) +(set wr (fn [root k c] (.db.splayed.set (format "%/%/hits/" root (+ k 1)) (at parts k) (format "%/.sym" root) (if c {compress: true} {compress: false})))) +(count (map (fn [k] (wr "/tmp/rfl_pg737_0" k false)) (til 10))) -- 10 +(count (map (fn [k] (wr "/tmp/rfl_pg737_2" k true)) (til 10))) -- 10 +(set P0 (.db.parted.get "/tmp/rfl_pg737_0/" 'hits)) +(set P2 (.db.parted.get "/tmp/rfl_pg737_2/" 'hits)) +(set F (fold concat parts)) +(count F) -- 40000 + +;; ─── (1) the issue's shape: STR expression key beside a SYM key ───────────── +(set q1 (fn [t] (select {from: (select {PageViews: (count URL) from: t where: (and (== CounterID 62) (== EventDate 2013.07.15) (== IsRefresh 0) (== TraficSourceID 1)) by: {TraficSourceID: TraficSourceID SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID Src: (if (and (== SearchEngineID 0) (== AdvEngineID 0)) Referer "") Dst: URL} desc: PageViews take: 1010}) asc: [Src Dst SearchEngineID AdvEngineID]}))) +(set RF1 (q1 F)) +(set B1 (at (.sys.mem) 'group-perpart-runs)) +(set R01 (q1 P0)) +(> (at (.sys.mem) 'group-perpart-runs) B1) -- true +(set B2 (at (.sys.mem) 'group-perpart-runs)) +(set R21 (q1 P2)) +(> (at (.sys.mem) 'group-perpart-runs) B2) -- true +(> (count RF1) 8) -- true +(type (at R01 'Src)) -- 'STR +(== (format "%" R01) (format "%" RF1)) -- true +(== (format "%" R21) (format "%" RF1)) -- true + +;; ─── (2) STR FIRST / LAST partials beside the STR key ─────────────────────── +(set q2 (fn [t] (select {from: (select {c: (count URL) f: (first (if (== AdvEngineID 0) Referer "")) l: (last (if (== AdvEngineID 1) Referer "none")) from: t where: (and (== CounterID 62) (== EventDate 2013.07.15) (== IsRefresh 0)) by: {SearchEngineID: SearchEngineID Src: (if (== AdvEngineID 0) Referer "")} desc: c take: 100}) asc: [Src SearchEngineID]}))) +(set RF2 (q2 F)) +(set B3 (at (.sys.mem) 'group-perpart-runs)) +(set R02 (q2 P0)) +(> (at (.sys.mem) 'group-perpart-runs) B3) -- true +(type (at R02 'f)) -- 'STR +(== (format "%" R02) (format "%" RF2)) -- true +(== (format "%" (q2 P2)) (format "%" RF2)) -- true + +;; ─── (3) STR FIRST / LAST partials under a fixed-width key only ───────────── +(set q3 (fn [t] (select {from: (select {c: (count URL) f: (first (if (== AdvEngineID 0) Referer "")) l: (last (if (== AdvEngineID 1) Referer "none")) from: t where: (and (== CounterID 62) (== EventDate 2013.07.15) (== IsRefresh 0)) by: {SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID}}) asc: [SearchEngineID AdvEngineID]}))) +(set RF3 (q3 F)) +(set B4 (at (.sys.mem) 'group-perpart-runs)) +(set R03 (q3 P0)) +(> (at (.sys.mem) 'group-perpart-runs) B4) -- true +(type (at R03 'f)) -- 'STR +(== (format "%" R03) (format "%" RF3)) -- true +(== (format "%" (q3 P2)) (format "%" RF3)) -- true + +(.sys.exec "rm -rf /tmp/rfl_pg737_0 /tmp/rfl_pg737_2") -- 0 diff --git a/test/rfl/group/parted_group_where.rfl b/test/rfl/group/parted_group_where.rfl index 6a2a87a0c..2228643b6 100644 --- a/test/rfl/group/parted_group_where.rfl +++ b/test/rfl/group/parted_group_where.rfl @@ -138,5 +138,356 @@ (at RPd2 'cv) -- (at RFd2 'cv) (at RPd2 'mxv) -- (at RFd2 'mxv) +;; (d3) grouped on the partition key alone, P1 the empty reference +;; partition: its sub-group has no key and answers one row of +;; empty-input aggregates, which must not surface as a group of P1. +(set Bd3 (at (.sys.mem) 'group-perpart-runs)) +(set RPd3 (select {cv: (count v) by: part from: Pw where: (> u 700)})) +(> (at (.sys.mem) 'group-perpart-runs) Bd3) -- true +(at RPd3 'part) -- [2 3 4] +(at RPd3 'cv) -- [99 400 400] +(set RPd4 (select {cv: (count v) by: part from: Pw where: (and (== part 3) (> v 100))})) +(at RPd4 'part) -- [3] +(at RPd4 'cv) -- [299] +(set RPd5 (select {cv: (count v) sv: (sum v) by: part from: Pw where: (== part 3)})) +(at RPd5 'part) -- [3] +(at RPd5 'cv) -- [400] +(set RPd6 (select {cv: (count v) by: {p: part} from: Pw where: (in part [2 4])})) +(at RPd6 'p) -- [2 4] +(at RPd6 'cv) -- [400 400] +(count (select {cv: (count v) by: part from: Pw where: (> u 5000)})) -- 0 + +;; ══════════════════════════════════════════════════════════════════════════ +;; (e) NO KEY AT ALL — a whole-table aggregate answers one row whatever the +;; where: keeps (the aggregates of no rows), as over a flat table. The +;; row comes from the reference partition; when that partition held no +;; rows its sub-group answered none, every later zero-survivor partition +;; was skipped, and the select came back with 0 rows. The avg of no rows +;; is null (the merge divided by a zero count to 0.0). +;; ══════════════════════════════════════════════════════════════════════════ +(set Re1 (select {c: (count v) s: (sum u) a: (avg v) mn: (min u) from: Pw where: (> u 5000)})) +(set Fe1 (select {c: (count v) s: (sum u) a: (avg v) mn: (min u) from: TF where: (> u 5000)})) +(count Re1) -- 1 +(at Re1 'c) -- (at Fe1 'c) +(at Re1 's) -- (at Fe1 's) +(at Re1 'a) -- [0Nf] +(at Re1 'a) -- (at Fe1 'a) +(at Re1 'mn) -- (at Fe1 'mn) + +;; empty partitions first and last, rows only in the middle one +(.sys.exec "rm -rf /tmp/rfl_pgwh_e") +(.db.splayed.set "/tmp/rfl_pgwh_e/2024.01.01/t/" (table [a b] (list (take [1] 0) (take [1] 0)))) +(.db.splayed.set "/tmp/rfl_pgwh_e/2024.01.02/t/" (table [a b] (list [4 5] [40 50]))) +(.db.splayed.set "/tmp/rfl_pgwh_e/2024.01.03/t/" (table [a b] (list (take [1] 0) (take [1] 0)))) +(set Pe (.db.parted.get "/tmp/rfl_pgwh_e/" 't)) +(set Fe (table [a b] (list [4 5] [40 50]))) +(set Be2 (at (.sys.mem) 'group-perpart-runs)) +(set Re2 (select {c: (count a) s: (sum b) from: Pe where: (> a 40)})) +(> (at (.sys.mem) 'group-perpart-runs) Be2) -- true +(count Re2) -- 1 +(at Re2 'c) -- [0] +(at Re2 's) -- [0] +(at Re2 'c) -- (at (select {c: (count a) s: (sum b) from: Fe where: (> a 40)}) 'c) +(at (select {c: (count a) from: Pe where: (> a 40)}) 'c) -- [0] +(at (select {mx: (max b) a: (avg b) from: Pe where: (> a 40)}) 'mx) -- [0Nl] +(at (select {mx: (max b) a: (avg b) from: Pe where: (> a 40)}) 'a) -- [0Nf] +(at (select {c: (count a) s: (sum b) from: Pe where: (> a 4)}) 's) -- [50] +(at (select {c: (count a) s: (sum b) from: Pe}) 'c) -- [2] +;; keyed, the same where: keeps no group +(count (select {c: (count a) by: date from: Pe where: (> a 40)})) -- 0 +(.sys.exec "rm -rf /tmp/rfl_pgwh_e") + +;; ══════════════════════════════════════════════════════════════════════════ +;; (f) ORDERED TAKE ON AN AGGREGATE (#729) — `asc:/desc: c take: N` and the +;; `having` shape arm a top-N / threshold emit filter for the select's +;; group. It describes the MERGED groups: applied to each partition's +;; partial it kept only that partition's top N, and the merge summed the +;; survivors. Uneven partitions with a small first one (keys 0..10) clear +;; the cardinality gate, so every shape below streams per partition. +;; ══════════════════════════════════════════════════════════════════════════ +(set mkp (fn [n m o] (table [k v] (list (% (* (+ o (til n)) 7919) m) (+ o (til n)))))) +(set Q1 (mkp 40 11 0)) +(set Q2 (mkp 6000 31 5)) +(set Q3 (mkp 900 17 11)) +(set Q4 (mkp 8000 29 3)) +(.sys.exec "rm -rf /tmp/rfl_pgtk") +(.db.splayed.set "/tmp/rfl_pgtk/2024.01.01/t/" Q1) +(.db.splayed.set "/tmp/rfl_pgtk/2024.01.02/t/" Q2) +(.db.splayed.set "/tmp/rfl_pgtk/2024.01.03/t/" Q3) +(.db.splayed.set "/tmp/rfl_pgtk/2024.01.04/t/" Q4) +(set Pt (.db.parted.get "/tmp/rfl_pgtk/" 't)) +(set TK (table [date k v] (list (concat (concat (take 2024.01.01 40) (take 2024.01.02 6000)) (concat (take 2024.01.03 900) (take 2024.01.04 8000))) (concat (concat (at Q1 'k) (at Q2 'k)) (concat (at Q3 'k) (at Q4 'k))) (concat (concat (at Q1 'v) (at Q2 'v)) (concat (at Q3 'v) (at Q4 'v)))))) + +(set Be (at (.sys.mem) 'group-perpart-runs)) +(set RPe1 (select {c: (count v) by: k from: Pt asc: c take: 2})) +(set RPe2 (select {c: (sum v) by: k from: Pt desc: c take: 3})) +(set RPe3 (select {c: (min v) by: k from: Pt desc: c take: 3})) +(set RPe4 (select {c: (max v) by: k from: Pt asc: c take: 3})) +(set RPe5 (select {c: (count v) by: k from: Pt where: (>= date 2024.01.02) asc: c take: 2})) +(set RPe6 (select {c: (sum v) by: {kk: k} from: Pt where: (> v 100) desc: c take: 3})) +(set RPe7 (select {n: (count v) c: (sum v) by: k from: Pt desc: c take: 3})) +(set Ae (at (.sys.mem) 'group-perpart-runs)) +;; PROVES all seven ran through exec_group_per_partition. +(- Ae Be) -- 7 +(set RFe1 (select {c: (count v) by: k from: TK asc: c take: 2})) +(set RFe2 (select {c: (sum v) by: k from: TK desc: c take: 3})) +(set RFe3 (select {c: (min v) by: k from: TK desc: c take: 3})) +(set RFe4 (select {c: (max v) by: k from: TK asc: c take: 3})) +(set RFe5 (select {c: (count v) by: k from: TK where: (>= date 2024.01.02) asc: c take: 2})) +(set RFe6 (select {c: (sum v) by: {kk: k} from: TK where: (> v 100) desc: c take: 3})) +(set RFe7 (select {n: (count v) c: (sum v) by: k from: TK desc: c take: 3})) +(at RPe1 'k) -- (at RFe1 'k) +(at RPe1 'c) -- (at RFe1 'c) +(at RPe1 'c) -- [193 194] +(at RPe2 'k) -- (at RFe2 'k) +(at RPe2 'c) -- (at RFe2 'c) +(at RPe3 'k) -- (at RFe3 'k) +(at RPe3 'c) -- (at RFe3 'c) +(at RPe4 'k) -- (at RFe4 'k) +(at RPe4 'c) -- (at RFe4 'c) +(at RPe5 'k) -- (at RFe5 'k) +(at RPe5 'c) -- (at RFe5 'c) +(at RPe6 'kk) -- (at RFe6 'kk) +(at RPe6 'c) -- (at RFe6 'c) +(at RPe7 'k) -- (at RFe7 'k) +(at RPe7 'n) -- (at RFe7 'n) +(at RPe7 'c) -- (at RFe7 'c) + +;; `having` over a per-partition group: the count threshold also applies to +;; the merged counts, not to each partition's partial counts. +(set RPe8 (select {from: (select {c: (count v) by: k from: Pt}) where: (> c 520)})) +(set RFe8 (select {from: (select {c: (count v) by: k from: TK}) where: (> c 520)})) +(count RPe8) -- 17 +(count RPe8) -- (count RFe8) +(asc (at RPe8 'k)) -- (asc (at RFe8 'k)) +(asc (at RPe8 'c)) -- (asc (at RFe8 'c)) +(.sys.exec "rm -rf /tmp/rfl_pgtk") + +;; Each key leads one partition and trails another, so a partition's own top +;; 2 is not the merged top 2: a top-N applied per partition kept dd and a +;; from partitions 1 and 2 only (dd 250250, a 250250 for desc:), and a 124500 +;; and dd 124750 for asc:. +(.sys.exec "rm -rf /tmp/rfl_pgtq") +(.db.splayed.set "/tmp/rfl_pgtq/01/t/" (table [q v] (list (at ['a 'b 'c 'dd] (% (til 1000) 4)) (til 1000)))) +(.db.splayed.set "/tmp/rfl_pgtq/02/t/" (table [q v] (list (at ['a 'b 'c 'dd] (% (+ 1 (til 1000)) 4)) (til 1000)))) +(.db.splayed.set "/tmp/rfl_pgtq/03/t/" (table [q v] (list (at ['a 'b 'c 'dd] (% (+ 2 (til 1000)) 4)) (til 1000)))) +(set Pq (.db.parted.get "/tmp/rfl_pgtq/" 't)) +(set Bq (at (.sys.mem) 'group-perpart-runs)) +(set RPq1 (select {from: Pq by: q s: (sum v) desc: s take: 2})) +(set RPq2 (select {from: Pq by: q s: (sum v) asc: s take: 2})) +(- (at (.sys.mem) 'group-perpart-runs) Bq) -- 2 +(at RPq1 'q) -- ['dd 'a] +(at RPq1 's) -- [375000 374750] +(at RPq2 'q) -- ['c 'b] +(at RPq2 's) -- [374250 374500] +(.sys.exec "rm -rf /tmp/rfl_pgtq") + +;; ══════════════════════════════════════════════════════════════════════════ +;; (g) STR KEYS AND STR PARTIALS (#737) — a selective where caps est_groups by +;; the survivors, so a STR key (plain or computed) streams too. The merge +;; concatenated the partials' STR cells raw, leaving the merged key column +;; with no string pool: the merge group read the long strings through a +;; NULL pointer. 10 partitions span two merge batches (the running +;; result is merged again); strings are empty, inline and pooled. +;; ══════════════════════════════════════════════════════════════════════════ +(set NS 2000) +(set RS (take ["short" "a_rather_long_reason_text_value" "" "x" "another_long_reason_string_here" "mid_size_str" "yy"] NS)) +(set ES (% (til NS) 3)) +(set SS (take ["https_example_com_some_long_page_1" "https_example_com_other_long_page_2" "q"] NS)) +(set VS (til NS)) +(set PS (table [r e s v] (list RS ES SS VS))) +(.sys.exec "rm -rf /tmp/rfl_pgwh_str") +(.db.splayed.set "/tmp/rfl_pgwh_str/01/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/02/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/03/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/04/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/05/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/06/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/07/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/08/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/09/t/" PS) +(.db.splayed.set "/tmp/rfl_pgwh_str/10/t/" PS) +(set Ps (.db.parted.get "/tmp/rfl_pgwh_str/" 't)) +(set TFs (table [r e s v] (list (raze (take (list RS) 10)) (raze (take (list ES) 10)) (raze (take (list SS) 10)) (raze (take (list VS) 10))))) +(count TFs) -- 20000 + +;; (g1) bare STR key — the reported shape (count, desc, take) +(set Be1 (at (.sys.mem) 'group-perpart-runs)) +(set RPe1 (select {from: Ps where: (== (% v 200) 7) by: r n: (count r) desc: n take: 12})) +(> (at (.sys.mem) 'group-perpart-runs) Be1) -- true +(set RPe1 (select {from: Ps where: (== (% v 200) 7) by: r n: (count r) asc: r})) +(set RFe1 (select {from: TFs where: (== (% v 200) 7) by: r n: (count r) asc: r})) +(at RPe1 'r) -- ["" "a_rather_long_reason_text_value" "another_long_reason_string_here" "mid_size_str" "short" "x" "yy"] +(at RPe1 'r) -- (at RFe1 'r) +(at RPe1 'n) -- (at RFe1 'n) + +;; (g2) computed STR key beside an int key, STR min/max/first partials +(set Be2 (at (.sys.mem) 'group-perpart-runs)) +(set RPe2 (select {from: Ps where: (== (% v 200) 7) by: {e: e k: (if (== e 0) s "")} n: (count v) mn: (min r) mx: (max r) fr: (first r) asc: e})) +(> (at (.sys.mem) 'group-perpart-runs) Be2) -- true +(set RFe2 (select {from: TFs where: (== (% v 200) 7) by: {e: e k: (if (== e 0) s "")} n: (count v) mn: (min r) mx: (max r) fr: (first r) asc: e})) +(at RPe2 'k) -- ["https_example_com_some_long_page_1" "" ""] +(at RPe2 'k) -- (at RFe2 'k) +(at RPe2 'n) -- (at RFe2 'n) +(at RPe2 'mn) -- (at RFe2 'mn) +(at RPe2 'mx) -- (at RFe2 'mx) +(at RPe2 'fr) -- (at RFe2 'fr) +;; (g3) no where: a computed STR key with few values streams on its own +(set Be3 (at (.sys.mem) 'group-perpart-runs)) +(set RPe3 (select {from: Ps by: {k: (if (== e 0) s "")} n: (count v) asc: k})) +(> (at (.sys.mem) 'group-perpart-runs) Be3) -- true +(at RPe3 'k) -- ["" "https_example_com_some_long_page_1"] +(at RPe3 'n) -- [13330 6670] + +;; (g4) LIST partials: first/last over a LIST column are concatenated by +;; reference (a raw copy aliased the partials' elements); 10 partitions +;; span two merge batches here as well. +(set LS (take (list [1 2] [3] [4 5 6] [7]) NS)) +(set PL (table [e v l] (list ES VS LS))) +(.sys.exec "rm -rf /tmp/rfl_pgwh_lst") +(.db.splayed.set "/tmp/rfl_pgwh_lst/01/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/02/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/03/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/04/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/05/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/06/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/07/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/08/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/09/t/" PL) +(.db.splayed.set "/tmp/rfl_pgwh_lst/10/t/" PL) +(set Pl (.db.parted.get "/tmp/rfl_pgwh_lst/" 't)) +(set TFl (table [e v l] (list (raze (take (list ES) 10)) (raze (take (list VS) 10)) (raze (take (list LS) 10))))) +(set Be4 (at (.sys.mem) 'group-perpart-runs)) +(set RPe4 (select {from: Pl where: (== (% v 50) 7) by: e n: (count v) fl: (first l) ll: (last l) asc: e})) +(> (at (.sys.mem) 'group-perpart-runs) Be4) -- true +(set RFe4 (select {from: TFl where: (== (% v 50) 7) by: e n: (count v) fl: (first l) ll: (last l) asc: e})) +(at RPe4 'e) -- [0 1 2] +(at RPe4 'n) -- (at RFe4 'n) +(at RPe4 'fl) -- (at RFe4 'fl) +(at RPe4 'll) -- (at RFe4 'll) + +;; ══════════════════════════════════════════════════════════════════════════ +;; (h) COMPOSITE KEY WITH A ROW OUTPUT (#731) — `b: b by: [s bo]` groups at +;; eval level on boxed key cells; a cell is a SYM atom holding the RUNTIME +;; id, and the key column was built at the source column's width, which +;; sizes FILE-domain ids: the runtime ids were truncated into unrelated +;; symbols. Without a where the parted columns reached the row reader +;; unflattened (`type` error). +;; ══════════════════════════════════════════════════════════════════════════ +(.sys.exec "rm -rf /tmp/rfl_pgwh_cmp") +(.db.splayed.set "/tmp/rfl_pgwh_cmp/2024.01.01/t/" (table [s bo b] (list ['alpha 'beta 'alpha] [true false true] [91 92 93]))) +(.db.splayed.set "/tmp/rfl_pgwh_cmp/2024.01.02/t/" (table [s bo b] (list ['gamma 'beta] [false true] [94 95]))) +(set Pc (.db.parted.get "/tmp/rfl_pgwh_cmp/" 't)) +(set RPf1 (select {b: b by: [s bo] from: Pc where: (> b 90)})) +(at RPf1 's) -- ['alpha 'beta 'gamma 'beta] +(at RPf1 'bo) -- [true false false true] +(at RPf1 'b) -- (list [91 93] [92] [94] [95]) +(set RPf2 (select {b: b c: (+ b 1) by: [s bo] from: Pc})) +(at RPf2 's) -- ['alpha 'beta 'gamma 'beta] +(at RPf2 'b) -- (list [91 93] [92] [94] [95]) +(at RPf2 'c) -- (list [92 94] [93] [95] [96]) +;; no outputs: the first row of each group, every column of it +(set RPf3 (select {by: [s bo] from: Pc})) +(at RPf3 's) -- ['alpha 'beta 'gamma 'beta] +(at RPf3 'b) -- [91 92 94 95] +(set RPf4 (select {by: [s bo] from: Pc where: (> b 0)})) +(at RPf4 's) -- ['alpha 'beta 'gamma 'beta] +(at RPf4 'b) -- [91 92 94 95] +;; a splayed (FILE-domain, non-parted) source took the same path +(.db.splayed.set "/tmp/rfl_pgwh_cmp/flat/" (table [s bo b] (list ['alpha 'beta 'alpha 'gamma 'beta] [true false true false true] [91 92 93 94 95]))) +(set Sc (.db.splayed.get "/tmp/rfl_pgwh_cmp/flat/")) +(set RSc (select {b: b by: [s bo] from: Sc where: (> b 90)})) +(at RSc 's) -- ['alpha 'beta 'gamma 'beta] +(at RSc 'bo) -- [true false false true] +(at RSc 'b) -- (list [91 93] [92] [94] [95]) +(at (select {b: b by: [s bo] from: Sc}) 's) -- ['alpha 'beta 'gamma 'beta] +;; a source wide enough for a two-byte index (300 symbols) +(set S16 (table [s bo b] (list (as 'SYM (% (til 600) 300)) (== (% (til 600) 2) 0) (til 600)))) +(.db.splayed.set "/tmp/rfl_pgwh_cmp/w16/" S16) +(set Sw (.db.splayed.get "/tmp/rfl_pgwh_cmp/w16/")) +(set RPw (select {b: b by: [s bo] from: Sw})) +(set RFw (select {b: b by: [s bo] from: S16})) +(count RPw) -- 300 +(at RPw 's) -- (at RFw 's) +(at RPw 'b) -- (at RFw 'b) + +;; ══════════════════════════════════════════════════════════════════════════ +;; (i) EVAL-LEVEL GROUPING OVER EVERY TABLE KIND (#766) — an output that is no +;; plain aggregate (a literal, a row expression) sends a multi-key by: to +;; the composite grouping (h); a STR / GUID / LIST key goes to the +;; single-key eval grouping, which took no flattened copy of a parted +;; table: `group: argument must be a vector or list` without a where:. +;; A by-dict key is a column under its alias, which no clause names: the +;; flattened copy left it out (`group key column not found`). A LIST key +;; in a composite key raised `vec_new ... got LIST` building the key +;; column, in the composite path and in its count-only take: block. +;; Oracle: the same select over an in-memory copy (Ia for the splayed +;; table, I2 for the two partitions). +;; ══════════════════════════════════════════════════════════════════════════ +(.sys.exec "rm -rf /tmp/rfl_pgwh_766") +(set Ia (table [s g k v st gu l] (list (as 'SYM (at ['aa 'bb 'cc] (% (til 24) 3))) (% (til 24) 4) (til 24) (% (* 7 (til 24)) 10) (at (list "x" "yy") (% (til 24) 2)) (at (guid 2) (% (til 24) 2)) (at (list [1 2] [3]) (% (til 24) 2))))) +(.db.splayed.set "/tmp/rfl_pgwh_766/sp/" Ia) +(.db.splayed.set "/tmp/rfl_pgwh_766/pt/2024.01.01/t/" Ia) +(.db.splayed.set "/tmp/rfl_pgwh_766/pt/2024.01.02/t/" Ia) +(set Sa (.db.splayed.get "/tmp/rfl_pgwh_766/sp/")) +(set Pa (.db.parted.get "/tmp/rfl_pgwh_766/pt/" 't)) +(set I2 (concat Ia Ia)) +;; the issue's shapes: a literal or a row expression beside a SYM key +(at (select {one: 1 c: (count k) from: Sa by: [s g]}) 's) -- [aa bb cc aa bb cc aa bb cc aa bb cc] +(select {one: 1 c: (count k) from: Sa by: [s g]}) -- (select {one: 1 c: (count k) from: Ia by: [s g]}) +(select {one: 1 c: (count k) from: Pa by: [s g]}) -- (select {one: 1 c: (count k) from: I2 by: [s g]}) +(select {x: (+ g 1) c: (count k) from: Sa by: [g s]}) -- (select {x: (+ g 1) c: (count k) from: Ia by: [g s]}) +(select {x: (+ g 1) c: (count k) from: Pa by: [g s]}) -- (select {x: (+ g 1) c: (count k) from: I2 by: [g s]}) +(select {one: 1 c: (count k) from: Pa where: (> v 3) by: [s g]}) -- (select {one: 1 c: (count k) from: I2 where: (> v 3) by: [s g]}) +(select {c: (count (distinct v)) from: Sa where: (> v 3) by: [g s] take: 3}) -- (select {c: (count (distinct v)) from: Ia where: (> v 3) by: [g s] take: 3}) +(select {c: (count (distinct v)) from: Pa where: (> v 3) by: [g s] take: 3}) -- (select {c: (count (distinct v)) from: I2 where: (> v 3) by: [g s] take: 3}) +(select {c: (count (distinct v)) from: Pa by: [g s] take: 3}) -- (select {c: (count (distinct v)) from: I2 by: [g s] take: 3}) +(set RIa (select {from: Pa where: (> v 3) by: [g s] desc: k})) +(set RIb (select {from: I2 where: (> v 3) by: [g s] desc: k})) +(at RIa 's) -- (at RIb 's) +(at RIa 'k) -- (at RIb 'k) +;; single-key eval grouping: STR, GUID and LIST keys +(select {x: s from: Sa by: st}) -- (select {x: s from: Ia by: st}) +(select {x: s from: Pa by: st}) -- (select {x: s from: I2 by: st}) +(select {x: (+ g 1) from: Pa by: gu}) -- (select {x: (+ g 1) from: I2 by: gu}) +(select {x: s from: Pa by: l}) -- (select {x: s from: I2 by: l}) +(select {c: (count k) from: Pa by: l}) -- (select {c: (count k) from: I2 by: l}) +;; by-dict keys under their aliases +(select {x: k from: Pa by: {a: s b: g}}) -- (select {x: k from: I2 by: {a: s b: g}}) +(select {x: k from: Pa by: {a: s b: (% k 3)}}) -- (select {x: k from: I2 by: {a: s b: (% k 3)}}) +(select {x: s from: Pa by: {a: st}}) -- (select {x: s from: I2 by: {a: st}}) +;; the flattened copy takes the aliases, not the by-dict's source columns, +;; unless an output reads one +(select {x: s from: Pa by: {a: st b: (% k 3)}}) -- (select {x: s from: I2 by: {a: st b: (% k 3)}}) +(select {x: st y: k from: Pa by: {a: st b: g}}) -- (select {x: st y: k from: I2 by: {a: st b: g}}) +;; a by-dict value reading an earlier alias: the alias column is flat, so +;; the value is evaluated over flat columns (over the parted table each +;; partition paired with the alias read again from row 0); a plain aggregate +;; beside it raised `schema: column 'a' not found` +(set mkd (fn [n o] (table [s g k v] (list (as 'SYM (at ['aa 'bb 'cc] (% (+ o (til n)) 3))) (% (+ o (til n)) 4) (+ (* 100 o) (til n)) (% (* 7 (+ o (til n))) 10))))) +(.db.splayed.set "/tmp/rfl_pgwh_766/pd/2024.01.01/t/" (mkd 7 0)) +(.db.splayed.set "/tmp/rfl_pgwh_766/pd/2024.01.02/t/" (mkd 5 1)) +(.db.splayed.set "/tmp/rfl_pgwh_766/pd/2024.01.03/t/" (mkd 6 2)) +(set Pd (.db.parted.get "/tmp/rfl_pgwh_766/pd/" 't)) +(set Id (concat (concat (mkd 7 0) (mkd 5 1)) (mkd 6 2))) +(take (at (select {x: s from: Pd by: {a: (+ g 1) b: (* a k)}}) 'b) 9) -- [0 2 6 12 4 10 18 200 303] +(select {x: s from: Pd by: {a: (+ g 1) b: (* a k)}}) -- (select {x: s from: Id by: {a: (+ g 1) b: (* a k)}}) +(select {c: (count (distinct v)) from: Pd by: {a: (+ g 1) b: (* a k)}}) -- (select {c: (count (distinct v)) from: Id by: {a: (+ g 1) b: (* a k)}}) +(select {c: (sum v) from: Pd by: {a: (+ g 1) b: (* a k)}}) -- (select {c: (sum v) from: Id by: {a: (+ g 1) b: (* a k)}}) +(select {c: (sum v) from: Pd where: (> v 2) by: {a: (+ g 1) b: (* a k)}}) -- (select {c: (sum v) from: Id where: (> v 2) by: {a: (+ g 1) b: (* a k)}}) +(select {x: s from: Pd by: {a: g b: (* a k)}}) -- (select {x: s from: Id by: {a: g b: (* a k)}}) +;; the alias read as a free name in a helper's body +(set hbd (fn [y] (* y a))) +(take (at (select {x: s from: Pd by: {a: (+ g 1) b: (hbd k)}}) 'b) 9) -- [0 2 6 12 4 10 18 200 303] +(select {x: s from: Pd by: {a: (+ g 1) b: (hbd k)}}) -- (select {x: s from: Id by: {a: (+ g 1) b: (hbd k)}}) +(select {c: (sum v) from: Pd by: {a: (+ g 1) b: (hbd k)}}) -- (select {c: (sum v) from: Id by: {a: (+ g 1) b: (hbd k)}}) +;; a LIST key beside another in the composite grouping +(select {c: (count k) one: 1 from: Ia by: [l s]}) -- (table [l s c one] (list (list [1 2] [3] [1 2] [3] [1 2] [3]) [aa bb cc aa bb cc] [4 4 4 4 4 4] [1 1 1 1 1 1])) +(select {c: (count k) from: Pa by: [l s]}) -- (select {c: (count k) from: I2 by: [l s]}) +(select {x: k from: Sa by: [l s]}) -- (select {x: k from: Ia by: [l s]}) +(select {c: (count k) from: Pa by: [l s] take: 2}) -- (select {c: (count k) from: I2 by: [l s] take: 2}) +(select {x: k from: Pa by: [l s] take: 2}) -- (select {x: k from: I2 by: [l s] take: 2}) + ;; ─── cleanup ───────────────────────────────────────────────────────────────── (.sys.exec "rm -rf /tmp/rfl_pgwh") +(.sys.exec "rm -rf /tmp/rfl_pgwh_str /tmp/rfl_pgwh_lst /tmp/rfl_pgwh_cmp /tmp/rfl_pgwh_766") diff --git a/test/rfl/group/parted_group_wide.rfl b/test/rfl/group/parted_group_wide.rfl index d171ac195..010d7d800 100644 --- a/test/rfl/group/parted_group_wide.rfl +++ b/test/rfl/group/parted_group_wide.rfl @@ -79,5 +79,232 @@ (< (max (abs (- (at RP 'sdv) (at RF 'sdv)))) 0.000001) -- true (< (max (abs (- (at RP 'vrv) (at RF 'vrv)))) 0.000001) -- true +;; ─── nullable inputs: AVG/VAR/STDDEV divide by the NON-NULL count (#767) ───── +;; The streaming kernel decomposes AVG into SUM+COUNT and VAR/STDDEV into +;; SUM+SUM(x²)+COUNT. SUM skips nulls, so the COUNT must too — it used to be +;; the group row count, dividing the non-null sum by every row. Fixture: 2 +;; partitions × 600 rows, key g = i mod 3 (gate: 3*100 <= 600). Every 4th row +;; is null; g=2 is null everywhere (all-null group → null avg/var, as flat); +;; g=1 is all null in partition 1 only. f is F64, k the same values as I64. +(set mknull (fn [n off] (do (set i (+ (til n) off)) (set g (% i 3)) (set z (or (or (== g 2) (== (% i 4) 0)) (and (< off 1) (== g 1)))) (set f (/ (as 'F64 i) (as 'F64 (not z)))) (table [g f k] (list g f (as 'I64 f)))))) +(.sys.exec "rm -rf /tmp/rfl_pgwn") +(.db.splayed.set "/tmp/rfl_pgwn/2024.01.01/t/" (mknull 600 0)) +(.db.splayed.set "/tmp/rfl_pgwn/2024.01.02/t/" (mknull 600 600)) +(set Pn (.db.parted.get "/tmp/rfl_pgwn/" 't)) +(set Fn (concat (mknull 600 0) (mknull 600 600))) +(set qn (fn [T] (select {a: (avg f) v: (var f) vp: (var_pop f) d: (dev f) sd: (stddev f) sp: (stddev_pop f) ak: (avg k) vk: (var k) dk: (dev k) fi: (first f) la: (last k) from: T by: g asc: g}))) +(set Bn (at (.sys.mem) 'group-perpart-runs)) +(set NP (qn Pn)) +(> (at (.sys.mem) 'group-perpart-runs) Bn) -- true +(set NF (qn Fn)) +(at NP 'a) -- [600.0 900.0 0Nf] +(at NP 'ak) -- [600.0 900.0 0Nf] +(at NP 'a) -- (at NF 'a) +(at NP 'ak) -- (at NF 'ak) +(at NP 'fi) -- (at NF 'fi) +(at NP 'la) -- (at NF 'la) +(nil? (at NP 'v)) -- (nil? (at NF 'v)) +(nil? (at NP 'vk)) -- (nil? (at NF 'vk)) +(< (max (abs (- (take (at NP 'v) 2) (take (at NF 'v) 2)))) 0.000001) -- true +(< (max (abs (- (take (at NP 'vp) 2) (take (at NF 'vp) 2)))) 0.000001) -- true +(< (max (abs (- (take (at NP 'd) 2) (take (at NF 'd) 2)))) 0.000001) -- true +(< (max (abs (- (take (at NP 'sd) 2) (take (at NF 'sd) 2)))) 0.000001) -- true +(< (max (abs (- (take (at NP 'sp) 2) (take (at NF 'sp) 2)))) 0.000001) -- true +(< (max (abs (- (take (at NP 'vk) 2) (take (at NF 'vk) 2)))) 0.000001) -- true +(< (max (abs (- (take (at NP 'dk) 2) (take (at NF 'dk) 2)))) 0.000001) -- true +;; same under a pushed-down WHERE (k is not filtered, so its nulls survive) +(set wn (fn [T] (select {a: (avg k) v: (var k) from: T where: (> g 0) by: g asc: g}))) +(at (wn Pn) 'a) -- (at (wn Fn) 'a) +(< (abs (- (first (at (wn Pn) 'v)) (first (at (wn Fn) 'v)))) 0.000001) -- true +;; ungrouped, and grouped by the MAPCOMMON partition column +(set un (fn [T] (select {a: (avg f) ak: (avg k) v: (var k) from: T}))) +(at (un Pn) 'a) -- (at (un Fn) 'a) +(at (un Pn) 'ak) -- (at (un Fn) 'ak) +(< (abs (- (first (at (un Pn) 'v)) (first (at (un Fn) 'v)))) 0.000001) -- true +(at (select {a: (avg f) ak: (avg k) from: Pn by: date}) 'a) -- [300.0 900.0] +(at (select {a: (avg f) ak: (avg k) from: Pn by: date}) 'ak) -- [300.0 900.0] +;; mixed partitions: partition 1 has no nulls (its segments carry no +;; HAS_NULLS, so its divisor slot takes the free group row count), partition 2 +;; does (that slot sums a not-null indicator). A user (count f) sits next to +;; (avg f): both divisor columns were named "f_count" by the first partial, so +;; the merge — which scans by name — read the row count for avg's divisor. +(set mkclean (fn [n off] (do (set i (+ (til n) off)) (table [g f k] (list (% i 3) (as 'F64 i) i))))) +(.sys.exec "rm -rf /tmp/rfl_pgwm") +(.db.splayed.set "/tmp/rfl_pgwm/2024.01.01/t/" (mkclean 600 0)) +(.db.splayed.set "/tmp/rfl_pgwm/2024.01.02/t/" (mknull 600 600)) +(set Pm (.db.parted.get "/tmp/rfl_pgwm/" 't)) +(set Fm (concat (mkclean 600 0) (mknull 600 600))) +(set qm (fn [T] (select {c: (count f) a: (avg f) v: (var f) ck: (count k) ak: (avg k) dk: (dev k) from: T by: g asc: g}))) +(set Bm (at (.sys.mem) 'group-perpart-runs)) +(set MP (qm Pm)) +(> (at (.sys.mem) 'group-perpart-runs) Bm) -- true +(set MF (qm Fm)) +(last (at MP 'a)) -- 300.5 +(at MP 'a) -- (at MF 'a) +(at MP 'ak) -- (at MF 'ak) +(at MP 'c) -- (at MF 'c) +(at MP 'ck) -- (at MF 'ck) +(any (nil? (at MP 'v))) -- false +(any (nil? (at MP 'dk))) -- false +(< (max (abs (- (at MP 'v) (at MF 'v)))) 0.000001) -- true +(< (max (abs (- (at MP 'dk) (at MF 'dk)))) 0.000001) -- true +;; ungrouped over the same mix +(set um (fn [T] (select {c: (count f) a: (avg f) v: (var k) from: T}))) +(at (um Pm) 'a) -- (at (um Fm) 'a) +(at (um Pm) 'c) -- (at (um Fm) 'c) +(< (abs (- (first (at (um Pm) 'v)) (first (at (um Fm) 'v)))) 0.000001) -- true + +;; avg-only shapes: the partition group runs on the v2 engine, which counts +;; each nullable column's live rows in place (internal non-null count, one +;; kernel per representation) instead of summing a materialized indicator. +;; Mixed with a null-free partition (row-count divisor) in Pm. +(set mkty (fn [n off] (do (set t (mknull n off)) (table [g f k i h d] (list (at t 'g) (at t 'f) (at t 'k) (as 'I32 (at t 'k)) (as 'I16 (% (at t 'k) 1000)) (as 'DATE (at t 'k))))))) +(.sys.exec "rm -rf /tmp/rfl_pgwt") +(.db.splayed.set "/tmp/rfl_pgwt/2024.01.01/t/" (mkty 600 0)) +(.db.splayed.set "/tmp/rfl_pgwt/2024.01.02/t/" (mkty 600 600)) +(set Pt (.db.parted.get "/tmp/rfl_pgwt/" 't)) +(set Ft (concat (mkty 600 0) (mkty 600 600))) +(set qt (fn [T] (select {a: (avg f) ak: (avg k) ai: (avg i) ah: (avg h) s: (sum f) from: T by: g asc: g}))) +(set Bt (at (.sys.mem) 'group-perpart-runs)) +(set TP (qt Pt)) +(> (at (.sys.mem) 'group-perpart-runs) Bt) -- true +(set TF (qt Ft)) +(at TP 'a) -- [600.0 900.0 0Nf] +(at TP 'ak) -- [600.0 900.0 0Nf] +(at TP 'ai) -- [600.0 900.0 0Nf] +(at TP 'a) -- (at TF 'a) +(at TP 'ak) -- (at TF 'ak) +(at TP 'ai) -- (at TF 'ai) +(at TP 'ah) -- (at TF 'ah) +(at TP 's) -- (at TF 's) +;; v2 has no SUM over DATE (a DATE avg's partial), so this partition group +;; runs on the legacy engine: its non-null count slots (OP_COUNT_NN) are +;; re-planned there as SUM over a not-null indicator, whatever the pool size +(at (select {a: (avg d) af: (avg f) from: Pt by: g asc: g}) 'a) -- (at (select {a: (avg d) af: (avg f) from: Ft by: g asc: g}) 'a) +(at (select {a: (avg d) af: (avg f) from: Pt by: g asc: g}) 'af) -- [600.0 900.0 0Nf] +;; a TIME input: SUM over TIME emits a 4-byte TIME partial on both engines, +;; which the readout took as I64 (garbage averages, zero variances); the +;; partial is summed as I64. Every 4th row null, no all-null group. +(set mktm (fn [n off] (do (set i (+ (til n) off)) (set k (as 'I64 (/ (as 'F64 i) (as 'F64 (!= (% i 4) 0))))) (table [g t k] (list (% i 3) (as 'TIME k) k))))) +(.sys.exec "rm -rf /tmp/rfl_pgwtm") +(.db.splayed.set "/tmp/rfl_pgwtm/2024.01.01/t/" (mktm 600 0)) +(.db.splayed.set "/tmp/rfl_pgwtm/2024.01.02/t/" (mktm 600 600)) +(set Ptm (.db.parted.get "/tmp/rfl_pgwtm/" 't)) +(set Ftm (concat (mktm 600 0) (mktm 600 600))) +(set qtm (fn [T] (select {a: (avg t) v: (var t) d: (dev t) ak: (avg k) from: T by: g asc: g}))) +(set Btm (at (.sys.mem) 'group-perpart-runs)) +(set MTP (qtm Ptm)) +(> (at (.sys.mem) 'group-perpart-runs) Btm) -- true +(set MTF (qtm Ftm)) +(at MTP 'a) -- [600.0 600.0 600.0] +(at MTP 'a) -- (at MTF 'a) +(at MTP 'ak) -- (at MTF 'ak) +(any (nil? (at MTP 'v))) -- false +(< (max (abs (- (at MTP 'v) (at MTF 'v)))) 0.000001) -- true +(< (max (abs (- (at MTP 'd) (at MTF 'd)))) 0.000001) -- true +(set qa (fn [T] (select {c: (count f) a: (avg f) ak: (avg k) from: T by: g asc: g}))) +(at (qa Pm) 'a) -- (at (qa Fm) 'a) +(at (qa Pm) 'ak) -- (at (qa Fm) 'ak) +(at (qa Pm) 'c) -- (at (qa Fm) 'c) +(last (at (qa Pm) 'a)) -- 300.5 + +;; ─── key column named like an aggregate partial ───────────────────────────── +;; The merge table holds the key columns next to the partials and the merge +;; GROUP BY scanned them by name, so a key named after a partial ("f_count" +;; for (count f)) was read in the partial's place: counts [0 3 6], avg +;; [0Nf 499833.33 250083.33]. Keys named like the positional merge names +;; (_gm0.._gm3) must not clash either; _gpnn1 is one more name of that shape. +(set mkname (fn [n off] (do (set i (+ (til n) off)) (table [_gpnn1 f_count _gm0 _gm1 _gm3 f] (list (% i 3) (% i 3) (% i 3) (% i 3) (% i 3) (as 'F64 i)))))) +(.sys.exec "rm -rf /tmp/rfl_pgwk") +(.db.splayed.set "/tmp/rfl_pgwk/2024.01.01/t/" (mkname 1000 0)) +(.db.splayed.set "/tmp/rfl_pgwk/2024.01.02/t/" (mkname 1000 1000)) +(.db.splayed.set "/tmp/rfl_pgwk/2024.01.03/t/" (mkname 1000 2000)) +(set Pk (.db.parted.get "/tmp/rfl_pgwk/" 't)) +(set Fk (concat (mkname 1000 0) (concat (mkname 1000 1000) (mkname 1000 2000)))) +(set Bk (at (.sys.mem) 'group-perpart-runs)) +(set KA (select {a: (avg f) from: Pk by: _gpnn1 asc: _gpnn1})) +(> (at (.sys.mem) 'group-perpart-runs) Bk) -- true +(at KA 'a) -- [1498.5 1499.5 1500.5] +(at KA 'a) -- (at (select {a: (avg f) from: Fk by: _gpnn1 asc: _gpnn1}) 'a) +(at (select {c: (count f) from: Pk by: f_count asc: f_count}) 'c) -- [1000 1000 1000] +(at (select {c: (count f) from: Pk by: f_count asc: f_count}) 'c) -- (at (select {c: (count f) from: Fk by: f_count asc: f_count}) 'c) +(set qk (fn [T] (select {c: (count f) a: (avg f) v: (var f) s: (sum f) from: T by: {_gm1: _gm1 date: date _gm3: _gm3} asc: [_gm1 date]}))) +(set Bq (at (.sys.mem) 'group-perpart-runs)) +(set KP (qk Pk)) +(> (at (.sys.mem) 'group-perpart-runs) Bq) -- true +(set mkd (fn [n off d] (update {date: d from: (mkname n off)}))) +(set KF (qk (concat (mkd 1000 0 2024.01.01) (concat (mkd 1000 1000 2024.01.02) (mkd 1000 2000 2024.01.03))))) +(at KP 'c) -- (at KF 'c) +(at KP 's) -- (at KF 's) +(at KP '_gm3) -- (at KF '_gm3) +(< (max (abs (- (at KP 'v) (at KF 'v)))) 0.000001) -- true +(at KP 'a) -- (at KF 'a) +(at KP 'a) -- [499.5 1500.0 2499.0 499.0 1499.5 2500.0 500.0 1499.0 2499.5] + +;; ─── null atom as an aggregate input (parted) ──────────────────────────────── +;; Its broadcast filled the sentinel without HAS_NULLS, so (avg 0Nl) averaged +;; INT64_MIN per group and wsum summed it. +(at (select {s: (avg 0Nl) from: Pm by: g asc: g}) 's) -- [0Nf 0Nf 0Nf] +(at (select {s: (wsum 0Nl f) from: Pm by: g asc: g}) 's) -- [0.0 0.0 0.0] +(at (select {s: (wsum f 0Nl) from: Pm by: g asc: g}) 's) -- [0.0 0.0 0.0] +(at (select {s: (avg 0Nl) from: Pm}) 's) -- [0Nf] +(at (select {s: (wsum 0Nl f) from: Pm}) 's) -- [0.0] + +;; ─── cardinality gate over a full-span or nullable integer key ────────────── +;; The gate's range proxy hi - lo + 1 overflowed (UBSan abort) for an I64 key +;; spanning more than INT64_MAX or holding 0N next to a positive value, and in +;; i32 arithmetic for an I32 key spanning more than INT32_MAX or holding 0Ni. +(.sys.exec "rm -rf /tmp/rfl_pgs") +(.db.splayed.set "/tmp/rfl_pgs/1/t/" (table [a b c d v] (list [-9000000000000000000 9000000000000000000 3] [0N 5 3] (as 'I32 [-2000000000 2000000000 3]) (as 'I32 [0N 5 3]) [10 20 30]))) +(.db.splayed.set "/tmp/rfl_pgs/2/t/" (table [a b c d v] (list [-9000000000000000000 9000000000000000000 4] [0N 5 4] (as 'I32 [-2000000000 2000000000 4]) (as 'I32 [0N 5 4]) [40 50 60]))) +(set Ps (.db.parted.get "/tmp/rfl_pgs/" 't)) +;; Route pinned too: 3 rows per partition, so the full-span keys saturate the +;; estimate to rows_per_part+1 and the nullable ones count 3 values plus the +;; null; est_groups*100 > rows_per_part either way, so none of these streams +;; per partition. A span computed in signed arithmetic that wrapped small +;; would pick the per-partition route by accident and still sum right. +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Ps by: a asc: a}) 's) -- [50 30 60 70] +(at (select {s: (sum v) from: Ps by: b asc: b}) 's) -- [50 30 60 70] +(at (select {s: (sum v) from: Ps by: c asc: c}) 's) -- [50 30 60 70] +(at (select {s: (sum v) from: Ps by: d asc: d}) 's) -- [50 30 60 70] +(at (.sys.mem) 'group-perpart-runs) -- B +(.sys.exec "rm -rf /tmp/rfl_pgs") + +;; A nullable low-cardinality key must still stream per partition: the gate +;; took the null sentinel as the low end of the range, so 0N next to 1..3 +;; estimated rows_per_part+1 groups (I64) or ~2^31 (I32) and sent the group-by +;; to the concat path. Four groups (null + 1..3) over 1000 rows/partition +;; clear est_groups*100 <= rows_per_part only when the null counts as one group. +(set NN 1000) +;; The same for the other integer-like widths — DATE, TIME, TIMESTAMP, I16 — +;; which had no range estimate at all (card = rows of the partition) and so +;; always left the per-partition path. +(set PN (fn [b] (table [k j d t p h v] (list (at [0N 1 2 3] (% (til NN) 4)) (as 'I32 (at [0N 1 2 3] (% (til NN) 4))) (as 'DATE (at [0N 1 2 3] (% (til NN) 4))) (as 'TIME (at [0N 1 2 3] (% (til NN) 4))) (as 'TIMESTAMP (at [0N 1 2 3] (% (til NN) 4))) (as 'I16 (at [0N 1 2 3] (% (til NN) 4))) (+ b (til NN)))))) +(.sys.exec "rm -rf /tmp/rfl_pgn") +(.db.splayed.set "/tmp/rfl_pgn/1/t/" (PN 0)) +(.db.splayed.set "/tmp/rfl_pgn/2/t/" (PN 1000)) +(.db.splayed.set "/tmp/rfl_pgn/3/t/" (PN 2000)) +(set Pn (.db.parted.get "/tmp/rfl_pgn/" 't)) +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Pn by: k asc: k}) 's) -- [1123500 1124250 1125000 1125750] +(> (at (.sys.mem) 'group-perpart-runs) B) -- true +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Pn by: j asc: j}) 's) -- [1123500 1124250 1125000 1125750] +(> (at (.sys.mem) 'group-perpart-runs) B) -- true +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Pn by: d asc: d}) 's) -- [1123500 1124250 1125000 1125750] +(> (at (.sys.mem) 'group-perpart-runs) B) -- true +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Pn by: t asc: t}) 's) -- [1123500 1124250 1125000 1125750] +(> (at (.sys.mem) 'group-perpart-runs) B) -- true +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Pn by: p asc: p}) 's) -- [1123500 1124250 1125000 1125750] +(> (at (.sys.mem) 'group-perpart-runs) B) -- true +(set B (at (.sys.mem) 'group-perpart-runs)) +(at (select {s: (sum v) from: Pn by: h asc: h}) 's) -- [1123500 1124250 1125000 1125750] +(> (at (.sys.mem) 'group-perpart-runs) B) -- true +(.sys.exec "rm -rf /tmp/rfl_pgn") + ;; ─── cleanup ───────────────────────────────────────────────────────────────── -(.sys.exec "rm -rf /tmp/rfl_pgw") +(.sys.exec "rm -rf /tmp/rfl_pgw /tmp/rfl_pgwn /tmp/rfl_pgwm /tmp/rfl_pgwk /tmp/rfl_pgwt /tmp/rfl_pgwtm") diff --git a/test/rfl/group/strlen_grow.rfl b/test/rfl/group/strlen_grow.rfl index d39bbbc47..30bd65c04 100644 --- a/test/rfl/group/strlen_grow.rfl +++ b/test/rfl/group/strlen_grow.rfl @@ -106,3 +106,251 @@ ;; key 1000 -> only row v=1000 -> bot-1 = [1000] (per-group list) (first (first (at (select {b: (bot v 1) by: k from: Ttk where: (== k 1000)}) 'b))) -- 1000 (first (at (select {b: (bot v 1) by: k from: Ttk where: (== k 1000)}) 'k)) -- 1000 + +;; ──────────────────────────────────────────────────────────────────── +;; strlen fusion null semantics: "" is the STR/SYM null, strlen maps it +;; to null, so sum/avg(strlen s) skip it — neither the sum nor the AVG +;; divisor counts it — on every route (issue #770). The keyless scalar +;; route and the direct-array route (reached by an integer key under the +;; count emit filter `where: (> c N)` over the inner select) counted "" +;; as length 0. Non-empty lengths 2 4 6 2 4: avg 3.6; g=0 -> (2+4)/2 = +;; 3.0, g=1 -> (6+2+4)/3 = 4.0, g=2 all "" -> avg null, sum 0. +;; ──────────────────────────────────────────────────────────────────── +(.sys.exec "rm -rf rf_test_strlen_null_spl rf_test_strlen_null_part rf_test_strlen_null_party") +(set Tn (table [g s] (list [0 0 0 0 1 1 1 1 2 2] (list "aa" "" "bbbb" "" "cccccc" "dd" "" "eeee" "" "")))) +(set Yn (table [g s] (list (at Tn 'g) (as 'SYM (at Tn 's))))) +(avg (strlen (at Tn 's))) -- 3.6 +(avg (strlen (at Yn 's))) -- 3.6 +;; keyless scalar route +(at (select {a: (avg (strlen s)) from: Tn}) 'a) -- [3.6] +(at (select {b: (sum (strlen s)) from: Tn}) 'b) -- [18] +(at (select {a: (avg (strlen s)) from: Yn}) 'a) -- [3.6] +(at (select {a: (avg (strlen s)) from: Tn where: (== g 0)}) 'a) -- [3.0] +(at (select {a: (avg (strlen s)) from: Tn where: (== g 2)}) 'a) -- [0Nf] +(at (select {b: (sum (strlen s)) from: Tn where: (== g 2)}) 'b) -- [0] +(at (select {a: (avg (strlen s)) m: (min (strlen s)) x: (max (strlen s)) from: Tn}) 'm) -- [2] +;; v2 grouped route +(at (select {a: (avg (strlen s)) from: Tn by: g}) 'a) -- [3.0 4.0 0Nf] +(at (select {a: (avg (strlen s)) from: Yn by: g}) 'a) -- [3.0 4.0 0Nf] +;; direct-array route: SUM/AVG-only accumulator (STR and SYM) +(set Rd (select {from: (select {c: (count s) a: (avg (strlen s)) b: (sum (strlen s)) from: Tn by: g}) where: (> c 1)})) +(at Rd 'g) -- [0 1 2] +(at Rd 'a) -- [3.0 4.0 0Nf] +(at Rd 'b) -- [6 12 0] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Yn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +;; direct-array route: generic accumulator (a MAX alongside) +(at (select {from: (select {c: (count s) a: (avg (strlen s)) m: (max g) from: Tn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) m: (max g) from: Yn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +;; hash route: sparse wide keys +(set Wn (table [g s] (list (+ 7 (* 100000000 (at Tn 'g))) (at Tn 's)))) +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Wn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +;; SYM key +(set Kn (table [g s] (list (as 'SYM (at Tn 'g)) (at Tn 's)))) +(at (select {a: (avg (strlen s)) from: Kn by: g}) 'a) -- [3.0 4.0 0Nf] +;; splayed STR and SYM +(.db.splayed.set "rf_test_strlen_null_spl/T/" Tn) +(.db.splayed.set "rf_test_strlen_null_spl/Y/" Yn) +(set TSn (.db.splayed.get "rf_test_strlen_null_spl/T/")) +(set YSn (.db.splayed.get "rf_test_strlen_null_spl/Y/")) +(at (select {a: (avg (strlen s)) from: TSn}) 'a) -- [3.6] +(at (select {a: (avg (strlen s)) from: YSn}) 'a) -- [3.6] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: TSn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: YSn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +;; parted STR and SYM: two copies of the table, same ratios +(.db.splayed.set "rf_test_strlen_null_part/2024.01.01/t/" Tn) +(.db.splayed.set "rf_test_strlen_null_part/2024.01.02/t/" Tn) +(.db.splayed.set "rf_test_strlen_null_party/2024.01.01/t/" Yn) +(.db.splayed.set "rf_test_strlen_null_party/2024.01.02/t/" Yn) +(set Pn (.db.parted.get "rf_test_strlen_null_part/" 't)) +(set PYn (.db.parted.get "rf_test_strlen_null_party/" 't)) +(at (select {a: (avg (strlen s)) from: Pn}) 'a) -- [3.6] +(at (select {b: (sum (strlen s)) from: Pn}) 'b) -- [36] +(at (select {a: (avg (strlen s)) from: Pn where: (== g 0)}) 'a) -- [3.0] +(at (select {a: (avg (strlen s)) from: PYn}) 'a) -- [3.6] +(at (select {a: (avg (strlen s)) from: Pn by: g}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Pn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: PYn by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(.sys.exec "rm -rf rf_test_strlen_null_spl rf_test_strlen_null_part rf_test_strlen_null_party") +;; above the parallel threshold: every third value "", otherwise "abcd" +(set NL 100000) +(set Tl (table [g s] (list (% (til NL) 2) (take (list "abcd" "abcd" "") NL)))) +(avg (strlen (at Tl 's))) -- 4.0 +(at (select {a: (avg (strlen s)) from: Tl}) 'a) -- [4.0] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Tl by: g}) where: (> c 1)}) 'a) -- [4.0 4.0] +(set Yl (table [g s] (list (at Tl 'g) (as 'SYM (at Tl 's))))) +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Yl by: g}) where: (> c 1)}) 'a) -- [4.0 4.0] +;; SUM-only strlen (no null tracking: "" adds 0) on the keyless and the +;; direct-array routes, STR and SYM +(at (select {b: (sum (strlen s)) from: Yn}) 'b) -- [18] +(at (select {from: (select {c: (count s) b: (sum (strlen s)) from: Tn by: g}) where: (> c 1)}) 'b) -- [6 12 0] +(at (select {from: (select {c: (count s) b: (sum (strlen s)) from: Yn by: g}) where: (> c 1)}) 'b) -- [6 12 0] +;; AVG(strlen) beside an aggregate over a nullable column (per-agg non-null +;; counts present): v is null on rows 1 and 4 +(set Tv (table [g s v] (list (at Tn 'g) (at Tn 's) [1 0N 3 4 0N 6 7 8 9 10]))) +(set Rv (select {from: (select {c: (count s) a: (avg (strlen s)) m: (max v) from: Tv by: g}) where: (> c 1)})) +(at Rv 'a) -- [3.0 4.0 0Nf] +(at Rv 'm) -- [4 8 10] +(set Rv2 (select {from: (select {c: (count s) a: (avg (strlen s)) x: (avg v) from: Tv by: g}) where: (> c 1)})) +(at Rv2 'a) -- [3.0 4.0 0Nf] +(at Rv2 'x) -- [2.6666666666666665 7.0 9.5] +;; per-worker merges. 2000 slots x 3 cells = 6000 per accumulator, so 100000 +;; rows allow 16 accumulators: with the 2 workers `make test` pins +;; (RAYFORCE_CORES=2) each worker keeps its own and the parallel slot merge +;; runs; fewer rows or more slots would change the path. FIRST beside +;; (row-ordered merge); every group holds both "abcd" and "" +(set Tm (table [g s] (list (% (til NL) 2000) (take (list "abcd" "abcd" "") NL)))) +(set Rm (select {from: (select {c: (count s) a: (avg (strlen s)) from: Tm by: g}) where: (> c 1)})) +(count Rm) -- 2000 +(distinct (at Rm 'a)) -- [4.0] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) f: (first g) from: Tl by: g}) where: (> c 1)}) 'a) -- [4.0 4.0] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) f: (first g) from: Yl by: g}) where: (> c 1)}) 'a) -- [4.0 4.0] +;; one strlen agg beside COUNTs (the specialised direct-array loop): key +;; widths and signedness, SYM key, >=4096 slots (the two `where:` queries +;; below carry a selection, so they run the generic da_accum_row) +(set Kw (table [g s] (list [0 0 0 0 1 1 1 1 2 2] (at Tn 's)))) +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (as 'I32 (at Kw 'g)) (at Kw 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (as 'I16 (at Kw 'g)) (at Kw 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (as 'U8 (at Kw 'g)) (at Kw 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (- (at Kw 'g) 5) (at Yn 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (as 'SYM (at Kw 'g)) (at Kw 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Tn by: g where: (!= g 1)}) where: (> c 1)}) 'a) -- [3.0 0Nf] +(at (select {from: (select {c: (count s) b: (sum (strlen s)) from: Yn by: g where: (!= g 0)}) where: (> c 1)}) 'b) -- [12 0] +;; 5000 slots: with RAYFORCE_CORES=2 (make test) 100000 rows give a budget of +;; 6 accumulators, so the per-worker accumulators are merged slot-parallel +(set Tw (table [g s] (list (% (til NL) 5000) (take (list "abcd" "abcd" "") NL)))) +(distinct (at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Tw by: g}) where: (> c 1)}) 'a)) -- [4.0] +(set Yw (table [g s] (list (at Tw 'g) (as 'SYM (at Tw 's))))) +(distinct (at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Yw by: g}) where: (> c 1)}) 'a)) -- [4.0] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (as 'I16 (- (at Kw 'g) 5)) (at Kw 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: (table [g s] (list (as 'I32 (- (at Kw 'g) 5)) (at Kw 's))) by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +;; a null SYM key groups with itself +(set Kz (table [g s] (list (as 'SYM (list "" "" "" "" "b" "b" "b" "b" "c" "c")) (at Tn 's)))) +(at (select {from: (select {c: (count s) a: (avg (strlen s)) from: Kz by: g}) where: (> c 1)}) 'a) -- [3.0 4.0 0Nf] +;; exact sums across the 512-row length blocks of the specialised loop +(at (select {from: (select {c: (count s) b: (sum (strlen s)) from: Tl by: g}) where: (> c 1)}) 'b) -- [133332 133336] +(at (select {from: (select {c: (count s) b: (sum (strlen s)) from: Yl by: g}) where: (> c 1)}) 'b) -- [133332 133336] + +;; ──────────────────────────────────────────────────────────────────── +;; FILE-domain SYM through the specialised loop (SYM id widths W16/W32), +;; the keyless route, narrow SYM key widths, a composite key, and the +;; slot-partitioned drain. Expected values are hand-computed constants +;; or the vector-level (sum/avg (strlen ...)) of the same column. +;; ──────────────────────────────────────────────────────────────────── +(.sys.exec "rm -rf /tmp/rfl_strlen888_w16 /tmp/rfl_strlen888_w32 /tmp/rfl_strlen888_k8 /tmp/rfl_strlen888_k16 /tmp/rfl_strlen888_k32") +;; W16: 300 distinct symbols '0..'299 (lengths 1/2/3) plus six "" nulls at +;; rows 1000..1005, groups i % 4. Group sums 638 638 642 642 over 250 +;; non-empty rows each (the vector-level oracle agrees). +(set M16 (concat (as 'SYM (% (til 1000) 300)) (as 'SYM (list "" "" "" "" "" "")))) +(set G16 (% (til 1006) 4)) +(sum (strlen M16)) -- 2560 +(sum (strlen (at M16 (where (== G16 2))))) -- 642 +(.db.splayed.set "/tmp/rfl_strlen888_w16/T/" (table [g s] (list G16 M16))) +(set Y16 (.db.splayed.get "/tmp/rfl_strlen888_w16/T/")) +(set R16 (select {from: (select {c: (count s) b: (sum (strlen s)) from: Y16 by: g}) where: (> c 1)})) +(set R16m (select {from: (select {c: (count s) m: (avg (strlen s)) from: Y16 by: g}) where: (> c 1)})) +(at R16 'b) -- [638 638 642 642] +(at R16m 'm) -- [2.552 2.552 2.568 2.568] +;; keyless over the same FILE-domain column (the pinned vocabulary) +(at (select {b: (sum (strlen s)) m: (avg (strlen s)) from: Y16}) 'b) -- [2560] +(at (select {b: (sum (strlen s)) from: Y16 where: (== g 3)}) 'b) -- [642] +;; W32: 70000 distinct symbols '0..'69999, groups below / from 35000: +;; lengths 10*1 + 90*2 + 900*3 + 9000*4 + 25000*5 = 163890, and 35000*5. +(set M32 (as 'SYM (til 70000))) +(set G32 (div (til 70000) 35000)) +(.db.splayed.set "/tmp/rfl_strlen888_w32/T/" (table [g s] (list G32 M32))) +(set Y32 (.db.splayed.get "/tmp/rfl_strlen888_w32/T/")) +(set R32 (select {from: (select {c: (count s) b: (sum (strlen s)) from: Y32 by: g}) where: (> c 1)})) +(set R32m (select {from: (select {c: (count s) m: (avg (strlen s)) from: Y32 by: g}) where: (> c 1)})) +(at R32 'b) -- [163890 175000] +(at R32m 'm) -- [4.682571428571428 5.0] +(at (select {b: (sum (strlen s)) from: Y32}) 'b) -- [338890] +;; narrow SYM key widths (mapped columns): every key holds the four rows +;; "" "ab" "cde" "fghi" -> sum 9 over 3 non-empty rows, avg 3.0. +;; K=200 keys (W8), K=300 (W16); the W32 key follows below. +(set Wk (fn [K] (table [g s] (list (as 'SYM (% (til (* 4 K)) K)) (at (list "" "ab" "cde" "fghi") (div (til (* 4 K)) K)))))) +(.db.splayed.set "/tmp/rfl_strlen888_k8/T/" (Wk 200)) +(.db.splayed.set "/tmp/rfl_strlen888_k16/T/" (Wk 300)) +(set K8 (select {from: (select {c: (count s) b: (sum (strlen s)) from: (.db.splayed.get "/tmp/rfl_strlen888_k8/T/") by: g}) where: (> c 1)})) +(set K8m (select {from: (select {c: (count s) m: (avg (strlen s)) from: (.db.splayed.get "/tmp/rfl_strlen888_k8/T/") by: g}) where: (> c 1)})) +(set K16 (select {from: (select {c: (count s) b: (sum (strlen s)) from: (.db.splayed.get "/tmp/rfl_strlen888_k16/T/") by: g}) where: (> c 1)})) +(set K16m (select {from: (select {c: (count s) m: (avg (strlen s)) from: (.db.splayed.get "/tmp/rfl_strlen888_k16/T/") by: g}) where: (> c 1)})) +(count K8) -- 200 +(count K16) -- 300 +(distinct (at K8 'b)) -- [9] +(distinct (at K16 'b)) -- [9] +(distinct (at K8m 'm)) -- [3.0] +(distinct (at K16m 'm)) -- [3.0] +;; W32 key: 65600 filler rows with distinct key symbols come first, so the +;; keys of the last 60000 rows (a slice, below the parallel threshold) have +;; ids above 65535 and are read at 4 bytes. Each of 30000 tail keys holds +;; two rows of the same class ("" "ab" "cde" "fghi" by row mod 4): +;; sum = 2 * length, avg = length, null for "". The oracle is the +;; vector-level strlen of the tail's first 30000 rows. +(set F32 65600) +(set S32 (at (list "" "ab" "cde" "fghi") (% (til 60000) 4))) +(set T32 (table [g s] (list (as 'SYM (concat (til F32) (+ F32 (% (til 60000) 30000)))) (concat (take (list "x") F32) S32)))) +(.db.splayed.set "/tmp/rfl_strlen888_k32/T/" T32) +(set Z32 (drop (.db.splayed.get "/tmp/rfl_strlen888_k32/T/") F32)) +(set O32 (strlen (take (at Z32 's) 30000))) +(set K32 (select {from: (select {c: (count s) b: (sum (strlen s)) from: Z32 by: g}) where: (> c 1)})) +(set K32m (select {from: (select {c: (count s) m: (avg (strlen s)) from: Z32 by: g}) where: (> c 1)})) +(count K32) -- 30000 +(sum (at K32 'b)) -- 135000 +(sum (== (at K32 'b) (* 2 O32))) -- 22500 +(sum (== (at K32m 'm) (as 'F64 O32))) -- 30000 +(sum (nil? (at K32m 'm))) -- 7500 +(.sys.exec "rm -rf /tmp/rfl_strlen888_w16 /tmp/rfl_strlen888_w32 /tmp/rfl_strlen888_k8 /tmp/rfl_strlen888_k16 /tmp/rfl_strlen888_k32") +;; composite (two-key) direct-array AVG(strlen): groups (0,0) (0,1) (1,0) +;; (1,1) (2,0); "aa"+"" -> 2.0, "bbbb"+"" -> 4.0, "cccccc"+"dd" -> 4.0, +;; ""+"eeee" -> 4.0, ""+"" -> null (sum 0) +(set Tc (table [a b s] (list [0 0 0 0 1 1 1 1 2 2] [0 0 1 1 0 0 1 1 0 0] (list "aa" "" "bbbb" "" "cccccc" "dd" "" "eeee" "" "")))) +(set Rc (select {from: (select {c: (count s) m: (avg (strlen s)) t: (sum (strlen s)) from: Tc by: [a b]}) where: (> c 1)})) +(at Rc 'm) -- [2.0 4.0 4.0 4.0 0Nf] +(at Rc 't) -- [2 4 8 4 0] +(set Yc (table [a b s] (list (at Tc 'a) (at Tc 'b) (as 'SYM (at Tc 's))))) +(at (select {from: (select {c: (count s) m: (avg (strlen s)) from: Yc by: [a b]}) where: (> c 1)}) 'm) -- [2.0 4.0 4.0 4.0 0Nf] +;; slot-partitioned drain: 17999 slots x 3 cells = 53997 per worker against +;; 107994 scanned rows leaves the budget under 2 workers, so with 2 or more +;; workers the rows are bucketed by slot span (n_slots >= 2 * workers). +;; Each group holds rows g + 17999*j, j = 0..5: two "" and four "abcd". +(set NP 107994) +(set Tq (table [g s] (list (% (til NP) 17999) (take (list "abcd" "abcd" "") NP)))) +(set Rq (select {from: (select {c: (count s) b: (sum (strlen s)) from: Tq by: g}) where: (> c 1)})) +(set Rqm (select {from: (select {c: (count s) m: (avg (strlen s)) from: Tq by: g}) where: (> c 1)})) +(count Rq) -- 17999 +(distinct (at Rq 'b)) -- [16] +(distinct (at Rqm 'm)) -- [4.0] +(set Yq (table [g s] (list (at Tq 'g) (as 'SYM (at Tq 's))))) +(set Rqy (select {from: (select {c: (count s) b: (sum (strlen s)) from: Yq by: g}) where: (> c 1)})) +(set Rqym (select {from: (select {c: (count s) m: (avg (strlen s)) from: Yq by: g}) where: (> c 1)})) +(distinct (at Rqy 'b)) -- [16] +(distinct (at Rqym 'm)) -- [4.0] + +;; FILE-domain SYM column (a splayed table's symbol file with its .sym.ix +;; index): strlen reads the lengths from the index. Symbols of 0, 1, 5, 254, +;; 255, 256, 300 and 1000 bytes and multi-byte UTF-8 ones (6, 254, 256, 258 +;; bytes) must give the lengths the in-memory twin (runtime domain) gives, +;; through the plain vector strlen, the keyless sum, the direct-array group-by +;; (the ClickBench #28 shape, with a where: and a second select) and the +;; sparse one. +(.os.setenv "RAY_SYM_INDEX_MIN" "0") -- "0" +(.sys.exec "rm -rf /tmp/rfl_strlen_ix") +(set LNx [0 1 5 254 255 256 300 1000]) +(set VAx (map (fn [n] (raze (take (list "a") n))) LNx)) +(set VUx (map (fn [n] (raze (take (list "é") n))) [3 127 128 129])) +(set VSx (concat VAx VUx)) +(set NRx 70000) +(set SYx (as 'SYM (map (fn [i] (at VSx i)) (% (til NRx) (count VSx))))) +(set Tix (table [k w s] (list (% (til NRx) 3) (* 1000000 (% (til NRx) 5)) SYx))) +(count (.db.splayed.set "/tmp/rfl_strlen_ix/" Tix)) -- 70000 +(set Fix (.db.splayed.get "/tmp/rfl_strlen_ix/")) +(count (.sys.exec "ls /tmp/rfl_strlen_ix/.sym.ix")) -- 1 +(all (== (strlen (at Fix 's)) (strlen SYx))) -- true +(sum (strlen (at Fix 's))) -- 16595145 +(distinct (strlen (at Fix 's))) -- [0Nl 1 5 6 254 255 256 258 300 1000] +(sum (at (select {t: (sum (strlen s)) from: Fix}) 't)) -- 16595145 +(at (select {from: (select {l: (avg (strlen s)) c: (count s) by: k from: Fix where: (!= s "")}) where: (> c 100)}) 'l) -- (at (select {from: (select {l: (avg (strlen s)) c: (count s) by: k from: Tix where: (!= s "")}) where: (> c 100)}) 'l) +(at (select {t: (sum (strlen s)) c: (count s) by: k from: Fix}) 't) -- (at (select {t: (sum (strlen s)) c: (count s) by: k from: Tix}) 't) +(at (select {l: (avg (strlen s)) by: w from: Fix where: (!= s "")}) 'l) -- (at (select {l: (avg (strlen s)) by: w from: Tix where: (!= s "")}) 'l) +(.sys.exec "rm -rf /tmp/rfl_strlen_ix") +(.os.setenv "RAY_SYM_INDEX_MIN" "") -- "" diff --git a/test/rfl/group/strlen_staged.rfl b/test/rfl/group/strlen_staged.rfl new file mode 100644 index 000000000..4d4f26022 --- /dev/null +++ b/test/rfl/group/strlen_staged.rfl @@ -0,0 +1,190 @@ +;; Relative fixture paths stay isolated in the harness per-process working directory. +;; @requires: posix +;; Staged SYM strlen uses piece-relative rows and widths. +;; SUM and AVG are separate queries: exactly one strlen aggregate beside COUNT. +(.sys.exec "rm -rf rfl_strlen_staged; mkdir -p rfl_strlen_staged") +(set SLI (til 131079)) +(set SLH (as 'I16 (- (% SLI 7) 3))) +(set SLM (as 'I32 SLH)) +(set SLL (as 'I64 SLH)) +(set SLQ (as 'I32 (- (% SLI 8192) 4096))) +(set SLY (as 'SYM (at ["" "a" "bb" "cccccc" "lengthier" "" "a" "" "cccccc" "lengthier" "" "a" "bb" "cccccc" "" "" "a" "bb" "cccccc" "lengthier" "" "" "bb" "cccccc" "lengthier" "" "a" "bb" "" "lengthier" "" "a" "bb" "cccccc" "lengthier"] (% SLI 35)))) +(set SLT (table [h m l p y] (list SLH SLM SLL SLQ SLY))) +(.db.splayed.set "rfl_strlen_staged/small/" SLT "rfl_strlen_staged/small.sym" {compress: true}) +(set SLU (.db.splayed.get "rfl_strlen_staged/small/" "rfl_strlen_staged/small.sym")) +;; small: h, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: h asc: h})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: h asc: h})) +(as 'I64 (at SLR 'h)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'h)) -- (type (at SLP 'h)) +(at SLR 'a) -- [0 67411 67412 67416 67410 67410 67410] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; small: h, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: h asc: h})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: h asc: h})) +(as 'I64 (at SLR 'h)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'h)) -- (type (at SLP 'h)) +(at SLR 'a) -- [0Nf 4.499766370736266 4.499833121954476 4.500100126827315 4.5 4.5 4.5] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [true false false false false false false] +;; small: m, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: m asc: m})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: m asc: m})) +(as 'I64 (at SLR 'm)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'm)) -- (type (at SLP 'm)) +(at SLR 'a) -- [0 67411 67412 67416 67410 67410 67410] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; small: m, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: m asc: m})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: m asc: m})) +(as 'I64 (at SLR 'm)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'm)) -- (type (at SLP 'm)) +(at SLR 'a) -- [0Nf 4.499766370736266 4.499833121954476 4.500100126827315 4.5 4.5 4.5] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [true false false false false false false] +;; small: l, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: l asc: l})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: l asc: l})) +(as 'I64 (at SLR 'l)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'l)) -- (type (at SLP 'l)) +(at SLR 'a) -- [0 67411 67412 67416 67410 67410 67410] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; small: l, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: l asc: l})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: l asc: l})) +(as 'I64 (at SLR 'l)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'l)) -- (type (at SLP 'l)) +(at SLR 'a) -- [0Nf 4.499766370736266 4.499833121954476 4.500100126827315 4.5 4.5 4.5] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [true false false false false false false] +;; 8192 slots enables the piece-bounded prefetch loop. +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: p asc: p})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: p asc: p})) +(as 'I64 (at SLR 'p)) -- (- (til 8192) 4096) +(sum (at SLR 'c)) -- 131079 +(value SLR) -- (value SLP) +;; 8192 slots enables the piece-bounded prefetch loop. +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: p asc: p})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: p asc: p})) +(as 'I64 (at SLR 'p)) -- (- (til 8192) 4096) +(sum (at SLR 'c)) -- 131079 +(value SLR) -- (value SLP) +(set SLV (as 'SYM (map (fn [j] (format "v%" j)) (til 300)))) +(set SLY (at (concat (enlist (as 'SYM "")) SLV) (% SLI 301))) +(set SLT (table [h m l p y] (list SLH SLM SLL SLQ SLY))) +(.db.splayed.set "rfl_strlen_staged/wide16/" SLT "rfl_strlen_staged/wide16.sym" {compress: true}) +(set SLU (.db.splayed.get "rfl_strlen_staged/wide16/" "rfl_strlen_staged/wide16.sym")) +;; wide16: h, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: h asc: h})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: h asc: h})) +(as 'I64 (at SLR 'h)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'h)) -- (type (at SLP 'h)) +(at SLR 'a) -- [66620 67492 67492 67928 68360 68360 68360] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; wide16: h, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: h asc: h})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: h asc: h})) +(as 'I64 (at SLR 'h)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'h)) -- (type (at SLP 'h)) +(at SLR 'a) -- [3.642427556041553 3.6041866922994767 3.6041866922994767 3.6274698280465665 3.650734312416555 3.650734312416555 3.650734312416555] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [false false false false false false false] +;; wide16: m, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: m asc: m})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: m asc: m})) +(as 'I64 (at SLR 'm)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'm)) -- (type (at SLP 'm)) +(at SLR 'a) -- [66620 67492 67492 67928 68360 68360 68360] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; wide16: m, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: m asc: m})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: m asc: m})) +(as 'I64 (at SLR 'm)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'm)) -- (type (at SLP 'm)) +(at SLR 'a) -- [3.642427556041553 3.6041866922994767 3.6041866922994767 3.6274698280465665 3.650734312416555 3.650734312416555 3.650734312416555] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [false false false false false false false] +;; wide16: l, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: l asc: l})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: l asc: l})) +(as 'I64 (at SLR 'l)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'l)) -- (type (at SLP 'l)) +(at SLR 'a) -- [66620 67492 67492 67928 68360 68360 68360] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; wide16: l, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: l asc: l})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: l asc: l})) +(as 'I64 (at SLR 'l)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'l)) -- (type (at SLP 'l)) +(at SLR 'a) -- [3.642427556041553 3.6041866922994767 3.6041866922994767 3.6274698280465665 3.650734312416555 3.650734312416555 3.650734312416555] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [false false false false false false false] +(set SLV (as 'SYM (map (fn [j] (format "v%" j)) (til 80000)))) +(set SLY (at (concat (enlist (as 'SYM "")) SLV) (% SLI 80001))) +(set SLT (table [h m l p y] (list SLH SLM SLL SLQ SLY))) +(.db.splayed.set "rfl_strlen_staged/wide32/" SLT "rfl_strlen_staged/wide32.sym" {compress: true}) +(set SLU (.db.splayed.get "rfl_strlen_staged/wide32/" "rfl_strlen_staged/wide32.sym")) +;; wide32: h, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: h asc: h})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: h asc: h})) +(as 'I64 (at SLR 'h)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'h)) -- (type (at SLP 'h)) +(at SLR 'a) -- [109176 109179 109180 109182 109177 109173 109175] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; wide32: h, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: h asc: h})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: h asc: h})) +(as 'I64 (at SLR 'h)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'h)) -- (type (at SLP 'h)) +(at SLR 'a) -- [5.830493991989319 5.830342838833707 5.830396240521201 5.830503043896187 5.830547396528705 5.830645161290323 5.830440587449933] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [false false false false false false false] +;; wide32: m, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: m asc: m})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: m asc: m})) +(as 'I64 (at SLR 'm)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'm)) -- (type (at SLP 'm)) +(at SLR 'a) -- [109176 109179 109180 109182 109177 109173 109175] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; wide32: m, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: m asc: m})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: m asc: m})) +(as 'I64 (at SLR 'm)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'm)) -- (type (at SLP 'm)) +(at SLR 'a) -- [5.830493991989319 5.830342838833707 5.830396240521201 5.830503043896187 5.830547396528705 5.830645161290323 5.830440587449933] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [false false false false false false false] +;; wide32: l, sum +(set SLR (select {a: (sum (strlen y)) c: (count y) from: SLU by: l asc: l})) +(set SLP (select {a: (sum (strlen y)) c: (count y) from: SLT by: l asc: l})) +(as 'I64 (at SLR 'l)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'l)) -- (type (at SLP 'l)) +(at SLR 'a) -- [109176 109179 109180 109182 109177 109173 109175] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +;; wide32: l, avg +(set SLR (select {a: (avg (strlen y)) c: (count y) from: SLU by: l asc: l})) +(set SLP (select {a: (avg (strlen y)) c: (count y) from: SLT by: l asc: l})) +(as 'I64 (at SLR 'l)) -- [-3 -2 -1 0 1 2 3] +(type (at SLR 'l)) -- (type (at SLP 'l)) +(at SLR 'a) -- [5.830493991989319 5.830342838833707 5.830396240521201 5.830503043896187 5.830547396528705 5.830645161290323 5.830440587449933] +(at SLR 'c) -- [18726 18726 18726 18726 18725 18725 18725] +(value SLR) -- (value SLP) +(nil? (at SLR 'a)) -- [false false false false false false false] +(.sys.exec "rm -rf rfl_strlen_staged") diff --git a/test/rfl/group/take_unordered_dense.rfl b/test/rfl/group/take_unordered_dense.rfl index a95aebe72..613435c91 100644 --- a/test/rfl/group/take_unordered_dense.rfl +++ b/test/rfl/group/take_unordered_dense.rfl @@ -67,13 +67,14 @@ (set Fs (.db.splayed.get "rf_test_firstn_take/")) (eqt (select {from: Fs by: [u s] c: (count u) sv: (sum v) f: (min i) take: 10}) (select {from: F by: [u s] c: (count u) sv: (sum v) f: (min i) take: 10})) -- true (eqt (select {from: Fs by: y c: (count u) mx: (max v) f: (min i) take: 10}) (select {from: F by: y c: (count u) mx: (max v) f: (min i) take: 10})) -- true -;; a parted table keeps the post-execution take over its own group order: -;; the take is the head of its full result, and the groups are exact +;; a parted table answers like the in-memory table: the first groups in +;; first-seen order (f, the first row index of each group, is ascending), +;; and the groups are exact (.db.splayed.set "rf_test_firstn_parted/1/t/" (take F [0 100000])) (.db.splayed.set "rf_test_firstn_parted/2/t/" (take F [100000 100000])) (.db.splayed.set "rf_test_firstn_parted/3/t/" (take F [200000 100000])) (set Fp (.db.parted.get "rf_test_firstn_parted/" 't)) (set Pfull (select {from: Fp by: [u s] c: (count u) sv: (sum v) f: (min i)})) -(eqt (select {from: Fp by: [u s] c: (count u) sv: (sum v) f: (min i) take: 10}) (take Pfull 10)) -- true +(eqt (select {from: Fp by: [u s] c: (count u) sv: (sum v) f: (min i) take: 10}) (take (xasc Pfull 'f) 10)) -- true (eqt (xasc Pfull 'f) (xasc (select {from: F by: [u s] c: (count u) sv: (sum v) f: (min i)}) 'f)) -- true (.sys.exec "rm -rf rf_test_firstn_take rf_test_firstn_parted") -- 0 diff --git a/test/rfl/group/topn_parted_ties.rfl b/test/rfl/group/topn_parted_ties.rfl new file mode 100644 index 000000000..5184b8057 --- /dev/null +++ b/test/rfl/group/topn_parted_ties.rfl @@ -0,0 +1,71 @@ +;; @requires: posix +;; ════════════════════════════════════════════════════════════════════ +;; topn_parted_ties.rfl — ties at the cut of a grouped top-N over a +;; PARTED table (issue #801). +;; +;; `select … by … desc:|asc: take: N` (N <= 1024) arms the group +;; emit filter. On the legacy radix fat-entry path (a computed key keeps +;; the group off the v2 engine; high cardinality sends a parted input to +;; the concat fallback) the bounded heap topn_heap_push cut the groups to +;; exactly N comparing on the value only, so groups tied at the cut were +;; kept in (radix partition, gid) push order — and the gid inside a radix +;; partition depends on how workers claimed morsels. The answer changed +;; from run to run and did not match the stable sort. +;; +;; REFERENCE. `take: 1025` is above the emit-filter cap, so it is the +;; full group set (emitted by earliest source row) + stable sort; its +;; first N rows break ties on earliest source row. The heap now breaks +;; value ties the same way (earlier first row wins), so the take: N +;; answer must equal that prefix on every run. +;; +;; FIXTURE. 4 partitions x 150000 rows; partition p holds keys +;; base_p + (i mod 15000), 10 rows each, with base_p DESCENDING +;; (300000, 200000, 100000, 0) so key order disagrees with source-row +;; order. Partitions 2 and 4 append 5 more rows for each of their +;; first 50 keys (count 15). desc take: 120 keeps the 100 count-15 +;; groups and cuts 20 of the 59900 groups tied at 10 — those must be +;; keys 300000..300019 (partition 1, earliest rows). asc take: 50 +;; cuts 50 of the groups tied at 10: again partition 1's first keys. +;; Keys are spread by a large multiplier and grouped through a computed +;; expression (+ k 0) with a SYM side key, which reaches the radix heap. +;; ════════════════════════════════════════════════════════════════════ + +(.sys.exec "rm -rf /tmp/rfl_topn801") +(set I801 (% (til 150000) 15000)) +(set E801 (concat (concat (til 50) (til 50)) (concat (concat (til 50) (til 50)) (til 50)))) +(set mk801 (fn [b ix] (table [k j v] (list (* 1000000007 (+ b ix)) (as 'SYM (% ix 7)) (til (count ix)))))) +(.db.splayed.set "/tmp/rfl_topn801/1/t/" (mk801 300000 I801)) +(.db.splayed.set "/tmp/rfl_topn801/2/t/" (mk801 200000 (concat I801 E801))) +(.db.splayed.set "/tmp/rfl_topn801/3/t/" (mk801 100000 I801)) +(.db.splayed.set "/tmp/rfl_topn801/4/t/" (mk801 0 (concat I801 E801))) +(set P801 (.db.parted.get "/tmp/rfl_topn801/" 't)) + +(set REFD801 (take (select {c: (count v) by: {kk: (+ k 0) j: j} from: P801 desc: c take: 1025}) 120)) +(set REFA801 (take (select {c: (count v) by: {kk: (+ k 0) j: j} from: P801 asc: c take: 1025}) 50)) + +;; the reference itself: 100 groups at 15, then partition 1's first keys +;; (key x is stored as x * 1000000007) +(sum (at REFD801 'c)) -- 1700 +(at (at REFD801 'kk) 100) -- 300000002100000 +(at (at REFD801 'kk) 119) -- 300019002100133 +(at (at REFA801 'kk) 0) -- 300000002100000 +(at (at REFA801 'kk) 49) -- 300049002100343 + +;; desc: every run keeps exactly the reference rows, in reference order +(set D801 (fn [] (select {c: (count v) by: {kk: (+ k 0) j: j} from: P801 desc: c take: 120}))) +(at (D801) 'kk) -- (at REFD801 'kk) +(at (D801) 'kk) -- (at REFD801 'kk) +(at (D801) 'kk) -- (at REFD801 'kk) +(at (D801) 'kk) -- (at REFD801 'kk) +(at (D801) 'kk) -- (at REFD801 'kk) +(at (D801) 'c) -- (at REFD801 'c) + +;; asc: same tie-break at the bottom +(set A801 (fn [] (select {c: (count v) by: {kk: (+ k 0) j: j} from: P801 asc: c take: 50}))) +(at (A801) 'kk) -- (at REFA801 'kk) +(at (A801) 'kk) -- (at REFA801 'kk) +(at (A801) 'kk) -- (at REFA801 'kk) +(at (A801) 'kk) -- (at REFA801 'kk) +(at (A801) 'kk) -- (at REFA801 'kk) + +(.sys.exec "rm -rf /tmp/rfl_topn801") diff --git a/test/rfl/hof/iterate_typed.rfl b/test/rfl/hof/iterate_typed.rfl new file mode 100644 index 000000000..d42335285 --- /dev/null +++ b/test/rfl/hof/iterate_typed.rfl @@ -0,0 +1,50 @@ +;; map, fold, fold-right, scan and scan-right over typed vectors box one +;; element per call instead of the whole vector up front (#823). Each +;; element type must still reach the function as the same atom, nulls +;; included, and an error part-way through must stop the walk cleanly. + +;; element types reach the function unchanged +(map (fn [x] x) [1 2 3]) -- (list 1 2 3) +(map (fn [x] (+ x 1)) [1.5 2.5]) -- (list 2.5 3.5) +(map (fn [x] x) ['a 'b]) -- (list 'a 'b) +(map (fn [x] (count x)) (list "ab" "cde")) -- (list 2 3) +(map (fn [x] x) [true false]) -- (list true false) +(map (fn [x] (nil? x)) [1 0Nl 3]) -- (list false true false) +(map (fn [x] x) (as 'I32 [7 8])) -- (list 7i 8i) +(map (fn [x] x) []) -- (list) + +;; binary map over a typed vector, and with a scalar +(map + 10 [1 2 3]) -- (list 11 12 13) +(map + 10 5) -- 15 + +;; fold: seeded, unseeded, single element, empty +(fold + 0 [1 2 3]) -- 6 +(fold + [1 2 3]) -- 6 +(fold + [42]) -- 42 +(fold + 7 []) -- 7 +(fold (fn [a x] (+ (* a 10) x)) 0 [1 2 3]) -- 123 +(fold (fn [a x] (if (== x 'b) (+ a 1) a)) 0 ['a 'b 'b]) -- 2 +(fold (fn [a x] (- a x)) [10 1 2]) -- 7 + +;; fold-right: order of arguments and of elements +(fold-right (fn [x a] (- x a)) [10 1 2]) -- 11 +(fold-right (fn [x a] (+ (* a 10) x)) 0 [1 2 3]) -- 321 +(fold-right + 5 []) -- 5 + +;; scan and scan-right through a lambda (the generic path) +(scan (fn [a x] (+ a x)) [1 2 3 4]) -- (list 1 3 6 10) +(scan (fn [a x] (+ a x)) [5]) -- (list 5) +(scan-right (fn [x a] (+ x a)) [1 2 3 4]) -- (list 10 9 7 4) +(scan-right (fn [x a] (+ x a)) [5]) -- (list 5) + +;; the boxed element outlives its call when the function keeps it +(set kept (list)) +(map (fn [x] (set kept (concat kept (list x)))) [4 5 6]) +kept -- (list 4 5 6) + +;; an error part-way through stops the walk +(map (fn [x] (if (== x 2) (+ x 'a) x)) [1 2 3]) !- type +(fold (fn [a x] (if (== x 2) (+ x 'a) (+ a x))) 0 [1 2 3]) !- type +(fold-right (fn [x a] (if (== x 2) (+ x 'a) (+ a x))) 0 [1 2 3]) !- type +(scan (fn [a x] (if (== x 3) (+ x 'a) (+ a x))) [1 2 3 4]) !- type +(scan-right (fn [x a] (if (== x 2) (+ x 'a) (+ a x))) [1 2 3 4]) !- type diff --git a/test/rfl/integration/math.rfl b/test/rfl/integration/math.rfl index 155c660da..6f653e520 100644 --- a/test/rfl/integration/math.rfl +++ b/test/rfl/integration/math.rfl @@ -182,11 +182,11 @@ (- 2025.03.04D15:41:47.087221025 1000000000i) -- 2025.03.04D15:41:46.087221025 (- 2025.03.04D15:41:47.087221025 3000000000) -- 2025.03.04D15:41:44.087221025 (- 2025.03.04D15:41:47.087221025 01:01:00.000) -- 2025.03.04D14:40:47.087221025 -(- 2025.03.04D15:41:47.087221025 2025.03.04D15:41:47.087221025) -- 0 +(- 2025.03.04D15:41:47.087221025 2025.03.04D15:41:47.087221025) -- 0D (- 2025.03.04D15:41:47.087221025 [1000000000i]) -- [2025.03.04D15:41:46.087221025] (- 2025.03.04D15:41:47.087221025 [3000000000]) -- [2025.03.04D15:41:44.087221025] (- 2025.03.04D15:41:47.087221025 [01:01:00.000]) -- [2025.03.04D14:40:47.087221025] -(- 2025.03.04D15:41:47.087221025 [2025.03.04D15:41:47.087221025]) -- [0] +(- 2025.03.04D15:41:47.087221025 [2025.03.04D15:41:47.087221025]) -- [0D] (- [3i 5i] 2i) -- [1i 3i] (- [3i 5i] 2) -- [1 3] (- [3i 5i] 2.5) -- [0.5 2.5] @@ -226,11 +226,11 @@ (- [2025.03.04D15:41:47.087221025] 1000000000i) -- [2025.03.04D15:41:46.087221025] (- [2025.03.04D15:41:47.087221025] 3000000000) -- [2025.03.04D15:41:44.087221025] (- [2025.03.04D15:41:47.087221025] 01:01:00.000) -- [2025.03.04D14:40:47.087221025] -(- [2025.03.04D15:41:47.087221025] 2025.03.04D15:41:47.087221025) -- [0] +(- [2025.03.04D15:41:47.087221025] 2025.03.04D15:41:47.087221025) -- [0D] (- [2025.03.04D15:41:47.087221025] [1000000000i]) -- [2025.03.04D15:41:46.087221025] (- [2025.03.04D15:41:47.087221025] [3000000000]) -- [2025.03.04D15:41:44.087221025] (- [2025.03.04D15:41:47.087221025] [01:01:00.000]) -- [2025.03.04D14:40:47.087221025] -(- [2025.03.04D15:41:47.087221025] [2025.03.04D15:41:47.087221025]) -- [0] +(- [2025.03.04D15:41:47.087221025] [2025.03.04D15:41:47.087221025]) -- [0D] (- 2025.03.04D15:41:47.087221025 2025.12.13) !- type ;; u8 sub (- 0x05 0x03) -- 0x02 @@ -2525,11 +2525,14 @@ (div [5 6] [0 2]) -- [0Nl 3] (set TdivZ (table [a b] (list [5 6] [0 2]))) (at (select {q: (div a b) from: TdivZ}) 'q) -- [0Nl 3] -;; narrow-output floor div (I32 / I16 / U8 arms), incl. div-by-zero -> 0 +;; narrow-output floor div (I32 / I16 / U8 arms), incl. div-by-zero -> null +;; in a query as in the builtin (div (at TdivN 'a) (at TdivN 'b)) -> [14 0Nh 3] (div (as 'I32 [100 55 -7]) (as 'I32 [7 8 2])) -- (as 'I32 [14 6 -4]) (div (as 'I16 [100 55 -7]) (as 'I16 [7 8 2])) -- (as 'I16 [14 6 -4]) (set TdivN (table [a b] (list (as 'I16 [100 55 6]) (as 'I16 [7 0 2])))) -(at (select {q: (div a b) from: TdivN}) 'q) -- (as 'I16 [14 0 3]) +(nil? (div (at TdivN 'a) (at TdivN 'b))) -- [false true false] +(nil? (at (select {q: (div a b) from: TdivN}) 'q)) -- [false true false] +(at (at (select {q: (div a b) from: TdivN}) 'q) [0 2]) -- [14 3] ;; ── #403 follow-up: the ±2^53 gate rides inside the I64 divide loop for ;; `I64 column ÷ (I64 column | int scalar)`, so the column is read once diff --git a/test/rfl/io/csv_branch_cov.rfl b/test/rfl/io/csv_branch_cov.rfl index 93eead2d6..7cfb66bd2 100644 --- a/test/rfl/io/csv_branch_cov.rfl +++ b/test/rfl/io/csv_branch_cov.rfl @@ -348,12 +348,10 @@ (.sys.exec "rm -rf rf_test_csvbc_pttrace") -- 0 ;; ════════════════════════════════════════════════════════════════════════════ -;; 22. Chunk-zone + hash-index attach (ray_read_csv_named_opts lines ~1937-1945): -;; a numeric column only gets a per-chunk zone index once its length reaches -;; one chunk (65536 rows); high-entropy values then upgrade to a hash index -;; (csv_should_attach_hash). A 70000-row pseudo-random I64 column crosses -;; both thresholds. Spot-check aggregates so the index attach can't quietly -;; corrupt the payload. +;; 22. A numeric column of one chunk or more (65536 rows) read by .csv.read: +;; the read attaches no index (zones and dictionaries are streamed by the +;; conversions, index policy PI). A 70000-row pseudo-random I64 column +;; spot-checks the payload of that path. ;; ════════════════════════════════════════════════════════════════════════════ (.sys.exec "awk 'BEGIN{print \"id\"; for(i=1;i<=70000;i++) print (i*2654435761)%2000000000}' > rf_test_csvbc_zone.csv") -- 0 (set Tz (.csv.read [I64] "rf_test_csvbc_zone.csv")) diff --git a/test/rfl/join/asof_clause_fallback.rfl b/test/rfl/join/asof_clause_fallback.rfl index 2702c7f64..30eebd19c 100644 --- a/test/rfl/join/asof_clause_fallback.rfl +++ b/test/rfl/join/asof_clause_fallback.rfl @@ -115,3 +115,97 @@ (at RSwh 'Bid) -- (at ORwh 'Bid) (at RSwh 'Price) -- (at ORwh 'Price) (at RSwh 'Bid) -- (as 'F64 [100.0]) + +;; ════════════════════════════════════════════════════════════════════════════ +;; A clause reading a lambda parameter or let of the table's rows (a mask, a +;; projected vector) reads the whole table: run on one day's segment it met +;; that day's rows (length / ragged errors). Such an operand declines to the +;; flat eager kernel and matches the flat tables; a scalar local or a local +;; list of another length (a membership list) still streams. +;; ════════════════════════════════════════════════════════════════════════════ +(.sys.exec "rm -rf /tmp/rfl_asof_cf_ll /tmp/rfl_asof_cf_lr") +(.db.splayed.set "/tmp/rfl_asof_cf_ll/2024.01.01/t/" (table [Ts P] (list [1 5 9] [10 20 30]))) +(.db.splayed.set "/tmp/rfl_asof_cf_ll/2024.01.02/t/" (table [Ts P] (list [12 16 18] [40 50 60]))) +(.db.splayed.set "/tmp/rfl_asof_cf_lr/2024.01.01/t/" (table [Ts B] (list [0 4 8] [100 200 300]))) +(.db.splayed.set "/tmp/rfl_asof_cf_lr/2024.01.02/t/" (table [Ts B] (list [11 15 17] [400 500 600]))) +(set Lll (.db.parted.get "/tmp/rfl_asof_cf_ll/" 't)) +(set Llr (.db.parted.get "/tmp/rfl_asof_cf_lr/" 't)) +(set Fll (select {from: Lll where: (>= Ts 0)})) +(set Flr (select {from: Llr where: (>= Ts 0)})) +(set Mll [true false true false true true]) +(set alw (fn [l r m] (asof-join [Ts] (select {from: l where: m}) (select {from: r})))) +(set Blw (at (.sys.mem) 'asof-perpart-runs)) +(set RSlw (alw Lll Llr Mll)) +(- (at (.sys.mem) 'asof-perpart-runs) Blw) -- 0 +(value RSlw) -- (value (alw Fll Flr Mll)) +(at RSlw 'B) -- [100 300 500 600] +(set alo (fn [l r Q] (asof-join [Ts] (select {Ts: Ts Q: Q from: l}) (select {from: r})))) +(value (alo Lll Llr [1 2 3 4 5 6])) -- (value (alo Fll Flr [1 2 3 4 5 6])) +(at (alo Lll Llr [1 2 3 4 5 6]) 'Q) -- [1 2 3 4 5 6] +(set Bls (at (.sys.mem) 'asof-perpart-runs)) +(at (alo Lll Llr 7) 'Q) -- [7 7 7 7 7 7] +(- (at (.sys.mem) 'asof-perpart-runs) Bls) -- 2 +(set ali (fn [l r m] (asof-join [Ts] (select {from: l where: (in P m)}) (select {from: r})))) +(set Bli (at (.sys.mem) 'asof-perpart-runs)) +(at (ali Lll Llr [10 50]) 'B) -- [100 500] +(- (at (.sys.mem) 'asof-perpart-runs) Bli) -- 2 +(value (ali Lll Llr [10 50])) -- (value (ali Fll Flr [10 50])) +;; a path into a config dict is no form the DAG compiles: the operand is +;; joined by the flat kernel +(set alc (fn [l r c] (asof-join [Ts] (select {from: l where: (> P c.lo)}) (select {from: r})))) +(set Blc (at (.sys.mem) 'asof-perpart-runs)) +(at (alc Lll Llr {lo: 15}) 'B) -- [200 300 400 500 600] +(- (at (.sys.mem) 'asof-perpart-runs) Blc) -- 0 +(value (alc Lll Llr {lo: 15})) -- (value (alc Fll Flr {lo: 15})) +;; a mask as long as one day, local or global, is no mask of the table: it +;; raises length as on the flat tables (it filtered each day); a global mask +;; of the table's rows filters the whole table +(set Gll [true false true false true true]) +(set Gls [true false true]) +(set Bls2 (at (.sys.mem) 'asof-perpart-runs)) +(alw Lll Llr [true false true]) !- length +(- (at (.sys.mem) 'asof-perpart-runs) Bls2) -- 0 +(alw Fll Flr [true false true]) !- length +(asof-join [Ts] (select {from: Lll where: Gls}) (select {from: Llr})) !- length +(value (asof-join [Ts] (select {from: Lll where: Gll}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {from: Fll where: Gll}) (select {from: Flr}))) +(at (asof-join [Ts] (select {from: Lll where: Gll}) (select {from: Llr})) 'B) -- [100 300 500 600] +;; a projection or where: over the rows' order or the whole column (a scan, +;; an aggregate) is the whole table's, not each day's +(set Bsc2 (at (.sys.mem) 'asof-perpart-runs)) +(at (asof-join [Ts] (select {Ts: Ts c: (sums P) from: Lll}) (select {from: Llr})) 'c) -- [10 30 60 100 150 210] +(- (at (.sys.mem) 'asof-perpart-runs) Bsc2) -- 0 +(value (asof-join [Ts] (select {Ts: Ts c: (sums P) from: Lll}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {Ts: Ts c: (sums P) from: Fll}) (select {from: Flr}))) +(value (asof-join [Ts] (select {Ts: Ts c: (deltas P) from: Lll}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {Ts: Ts c: (deltas P) from: Fll}) (select {from: Flr}))) +(value (asof-join [Ts] (select {from: Lll where: (> P (avg P))}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {from: Fll where: (> P (avg P))}) (select {from: Flr}))) +(at (asof-join [Ts] (select {from: Lll where: (> P (avg P))}) (select {from: Llr})) 'P) -- [40 50 60] +(value (asof-join [Ts] (select {from: Lll}) (select {Ts: Ts B: (fills B) from: Llr}))) -- (value (asof-join [Ts] (select {from: Fll}) (select {Ts: Ts B: (fills B) from: Flr}))) +;; a membership in a column is the whole table's too +(value (asof-join [Ts] (select {Ts: Ts c: (in P (- Ts 2)) from: Lll}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {Ts: Ts c: (in P (- Ts 2)) from: Fll}) (select {from: Flr}))) +(value (asof-join [Ts] (select {Ts: Ts c: P from: Lll where: (in Ts (- (/ P 10) 2))}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {Ts: Ts c: P from: Fll where: (in Ts (- (/ P 10) 2))}) (select {from: Flr}))) +;; a row-wise projection still streams +(set Brw (at (.sys.mem) 'asof-perpart-runs)) +(at (asof-join [Ts] (select {Ts: Ts c: (* 2 P) from: Lll}) (select {from: Llr})) 'c) -- [20 40 60 80 100 120] +(- (at (.sys.mem) 'asof-perpart-runs) Brw) -- 2 +;; a projection calling a helper the DAG inlines streams when the helper is +;; row-wise in its parameters; one reading an aggregate is the whole table's +(set a2p (fn [v] (* 2 v))) +(set aap (fn [] (avg P))) +(set Brw (at (.sys.mem) 'asof-perpart-runs)) +(at (asof-join [Ts] (select {Ts: Ts c: (a2p P) from: Lll}) (select {from: Llr})) 'c) -- [20 40 60 80 100 120] +(- (at (.sys.mem) 'asof-perpart-runs) Brw) -- 2 +(set Brw (at (.sys.mem) 'asof-perpart-runs)) +(at (asof-join [Ts] (select {from: Lll where: (> P (aap))}) (select {from: Llr})) 'P) -- [40 50 60] +(value (asof-join [Ts] (select {Ts: Ts c: (- P (aap)) from: Lll}) (select {from: Llr}))) -- (value (asof-join [Ts] (select {Ts: Ts c: (- P (aap)) from: Fll}) (select {from: Flr}))) +(- (at (.sys.mem) 'asof-perpart-runs) Brw) -- 0 +;; a parameter that hides a projected column is the parameter: a vector of +;; the table's rows is the whole table's, a scalar the same on every day +(set alp (fn [l r P] (asof-join [Ts] (select {Ts: Ts P: P from: l}) (select {from: r})))) +(set Brw (at (.sys.mem) 'asof-perpart-runs)) +(at (alp Lll Llr [1 2 3 4 5 6]) 'P) -- [1 2 3 4 5 6] +(- (at (.sys.mem) 'asof-perpart-runs) Brw) -- 0 +(value (alp Lll Llr [1 2 3 4 5 6])) -- (value (alp Fll Flr [1 2 3 4 5 6])) +(set Brw (at (.sys.mem) 'asof-perpart-runs)) +(at (alp Lll Llr 7) 'P) -- [7 7 7 7 7 7] +(- (at (.sys.mem) 'asof-perpart-runs) Brw) -- 2 +(value (alp Lll Llr 7)) -- (value (alp Fll Flr 7)) +(.sys.exec "rm -rf /tmp/rfl_asof_cf_ll /tmp/rfl_asof_cf_lr") diff --git a/test/rfl/join/asof_sym_index.rfl b/test/rfl/join/asof_sym_index.rfl new file mode 100644 index 000000000..5f5ee56dc --- /dev/null +++ b/test/rfl/join/asof_sym_index.rfl @@ -0,0 +1,11 @@ +;; A null-free SYM equality key can use its PART index for as-of lookup. +;; The right side is sorted by symbol and time; each symbol's time slice +;; stays ordered even though the full time column is not. +(set Qsi (xasc (table [sym ts bid] (list (at ['aa 'bb 'cc] (% (til 3000) 3)) (til 3000) (as 'F64 (til 3000)))) ['sym 'ts])) +(set Lsi (table [sym ts] (list ['aa 'bb 'cc] [100 200 2999]))) +(at (asof-join [sym ts] Lsi Qsi) 'bid) -- [99.0 199.0 2999.0] + +;; The same admission rule applies when the first of several keys is SYM. +(set Qmi (xasc (table [sym k ts bid] (list (at ['aa 'bb 'cc 'dd 'ee 'ff 'gg 'hh] (% (til 3200) 8)) (div (% (til 3200) 16) 8) (til 3200) (as 'F64 (til 3200)))) ['sym 'ts])) +(set Lmi (table [sym k ts] (list ['aa 'bb] [0 1] [100 101]))) +(at (asof-join [sym k ts] Lmi Qmi) 'bid) -- [96.0 89.0] diff --git a/test/rfl/join/join_identity.rfl b/test/rfl/join/join_identity.rfl new file mode 100644 index 000000000..64b09a8df --- /dev/null +++ b/test/rfl/join/join_identity.rfl @@ -0,0 +1,20 @@ +;; One-to-one LEFT joins preserve left values and mutation isolation. +(set identity_left (table [k v s nested] (list [1 2 3] [10 0Nl 30] [z a b] (list [1 2] [3] [4 5])))) +(set identity_right (table [k r] (list [1 3] [100 300]))) +(set identity_join (left-join [k] identity_left identity_right)) +(at identity_join 'v) -- [10 0Nl 30] +(at identity_join 's) -- [z a b] +(at identity_join 'nested) -- (list [1 2] [3] [4 5]) +(set identity_changed (update {v: 99 where: (== k 1) from: identity_join})) +(at identity_left 'v) -- [10 0Nl 30] +(at identity_join 'v) -- [10 0Nl 30] +(at identity_changed 'v) -- [99 0Nl 30] +(set identity_left (update {v: 77 where: (== k 3) from: identity_left})) +(at identity_join 'v) -- [10 0Nl 30] +(at identity_left 'v) -- [10 0Nl 77] +;; All unmatched rows still preserve the left side. +(count (left-join [k] identity_left (table [k r] (list [8] [80])))) -- 3 +;; Duplicate matches must expand and gather the left side. +(at (left-join [k] identity_left (table [k r] (list [1 1 3] [4 5 6]))) 'k) -- [1 1 2 3] +;; FULL joins must allocate, since right-only rows change the left side. +(count (full-join [k] identity_left (table [k r] (list [1 8] [4 5])))) -- 4 diff --git a/test/rfl/join/tiny_chained_prefetch.rfl b/test/rfl/join/tiny_chained_prefetch.rfl new file mode 100644 index 000000000..02ed22b12 --- /dev/null +++ b/test/rfl/join/tiny_chained_prefetch.rfl @@ -0,0 +1,84 @@ +;; Exact pair-ID correctness coverage for tiny and boundary-sized build tables. +;; These cases also pass without the prefetch optimization. +;; Expected pairs were independently enumerated with tuple equality, null==null. +;; Pair IDs normalized to -1 for absent rows, then lexicographically sorted. +;; Normalization avoids assuming null sort order. IDs themselves are nonnegative. +;; No disk paths, pool knobs, cancellation or execution-policy changes. + +;; Tiny mixed SYM/I64 composite keys: duplicate Cartesian pairs, partial/all +;; nulls, near misses on the other component, and unmatched rows on both sides. +(set JPTL (table [a b li] (list (as 'SYM ["a" "a" "b" "" "a" "" "x" "a" "b" "" "z" "a"]) [1 1 2 1 0N 0N 9 2 2 2 0 1] (til 12)))) +(set JPTR (table [a b ri] (list (as 'SYM ["a" "a" "b" "" "a" "" "q" "" "a"]) [1 1 2 1 0N 0N 7 3 2] (+ 100 (til 9))))) +(set JPJ (inner-join [a b] JPTL JPTR)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 12 +(at JPP 'li) -- [0 0 1 1 2 3 4 5 7 8 11 11] +(at JPP 'ri) -- [100 101 100 101 102 103 104 105 108 102 100 101] +(set JPJ (left-join [a b] JPTL JPTR)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 15 +(at JPP 'li) -- [0 0 1 1 2 3 4 5 6 7 8 9 10 11 11] +(at JPP 'ri) -- [100 101 100 101 102 103 104 105 -1 108 102 -1 -1 100 101] +(set JPJ (full-join [a b] JPTL JPTR)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 17 +(at JPP 'li) -- [-1 -1 0 0 1 1 2 3 4 5 6 7 8 9 10 11 11] +(at JPP 'ri) -- [106 107 100 101 100 101 102 103 104 105 -1 108 102 -1 -1 100 101] + +;; Right build size 128: capacity starts 256 and doubles until >= 2*n. +(set JPB128L (table [a b li] (list (til 140) (take 7 140) (til 140)))) +(set JPB128R (table [a b ri] (list (til 128) (take 7 128) (+ 1000 (til 128))))) +(set JPJ (inner-join [a b] JPB128L JPB128R)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 128 +(all (== (at JPP 'li) (til 128))) -- true +(all (== (at JPP 'ri) (+ 1000 (til 128)))) -- true +(set JPJ (left-join [a b] JPB128L JPB128R)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 140 +(all (== (at JPP 'li) (til 140))) -- true +(all (== (at JPP 'ri) (concat (+ 1000 (til 128)) (take -1 12)))) -- true +(set JPJ (full-join [a b] JPB128L JPB128R)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 140 +(all (== (at JPP 'li) (til 140))) -- true +(all (== (at JPP 'ri) (concat (+ 1000 (til 128)) (take -1 12)))) -- true + +;; Right build size 129: capacity starts 256 and doubles until >= 2*n. +(set JPB129L (table [a b li] (list (til 140) (take 7 140) (til 140)))) +(set JPB129R (table [a b ri] (list (til 129) (take 7 129) (+ 1000 (til 129))))) +(set JPJ (inner-join [a b] JPB129L JPB129R)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 129 +(all (== (at JPP 'li) (til 129))) -- true +(all (== (at JPP 'ri) (+ 1000 (til 129)))) -- true +(set JPJ (left-join [a b] JPB129L JPB129R)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 140 +(all (== (at JPP 'li) (til 140))) -- true +(all (== (at JPP 'ri) (concat (+ 1000 (til 129)) (take -1 11)))) -- true +(set JPJ (full-join [a b] JPB129L JPB129R)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 140 +(all (== (at JPP 'li) (til 140))) -- true +(all (== (at JPP 'ri) (concat (+ 1000 (til 129)) (take -1 11)))) -- true + +;; 8197 probes: matches at start, both sides of morsel boundary, and tail; +;; right key 8192 duplicates, right-only 9000. Exact all-row IDs, not sums. +(set JPML (table [a b li] (list (til 8197) (take 7 8197) (til 8197)))) +(set JPMR (table [a b ri] (list [0 8191 8192 8192 8196 9000] (take 7 6) (+ 100 (til 6))))) +(set JPJ (inner-join [a b] JPML JPMR)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 5 +(at JPP 'li) -- [0 8191 8192 8192 8196] +(at JPP 'ri) -- [100 101 102 103 104] +(set JPJ (left-join [a b] JPML JPMR)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 8198 +(all (== (at JPP 'li) (concat (til 8193) (+ 8192 (til 5))))) -- true +(all (== (at JPP 'ri) (concat (concat (concat (concat [100] (take -1 8190)) (+ 101 (til 3))) (take -1 3)) [104]))) -- true +(set JPJ (full-join [a b] JPML JPMR)) +(set JPP (xasc (table [li ri] (list (fill -1 (at JPJ 'li)) (fill -1 (at JPJ 'ri)))) [li ri])) +(count JPP) -- 8199 +(all (== (at JPP 'li) (concat (+ -1 (til 8194)) (+ 8192 (til 5))))) -- true +(all (== (at JPP 'ri) (concat (concat (concat (concat (concat [105] [100]) (take -1 8190)) (+ 101 (til 3))) (take -1 3)) [104]))) -- true diff --git a/test/rfl/journal/ops_journal_wrappers.rfl b/test/rfl/journal/ops_journal_wrappers.rfl index 8d9f8633b..7f72decad 100644 --- a/test/rfl/journal/ops_journal_wrappers.rfl +++ b/test/rfl/journal/ops_journal_wrappers.rfl @@ -57,7 +57,9 @@ (.log.roll) !- domain (.log.roll 1) !- arity (.log.snapshot) !- domain +(.log.snapshot 1) !- arity (nil? (.log.sync)) -- true +(.log.sync 1) !- arity (nil? (.log.close)) -- true ;; ════════════════════════════════════════════════════════════════════════ diff --git a/test/rfl/lang/f32_literals.rfl b/test/rfl/lang/f32_literals.rfl new file mode 100644 index 000000000..2b7c8b2a1 --- /dev/null +++ b/test/rfl/lang/f32_literals.rfl @@ -0,0 +1,51 @@ +;; F32 suffixes, exponent disambiguation, and printer/readback types. +(type 42e) -- 'f32 +(type 1.5e) -- 'f32 +(type -1.5e) -- 'f32 +(type 0e) -- 'f32 +(type -0e) -- 'f32 +1.5e -- (as 'F32 1.5) +-42e -- (as 'F32 -42) +(type 1e3) -- 'f64 +(type 1E3) -- 'f64 +(type 1e+3) -- 'f64 +(type 1e-3) -- 'f64 +(type 1e3e) -- 'f32 +(type 1E-3e) -- 'f32 +1e3e -- (as 'F32 1000) +1e-3e -- (as 'F32 0.001) +1e39e -- (as 'F32 1e39) +-1e39e -- (as 'F32 -1e39) +1e-46e -- 0e +(type [1e -2.5e 0Ne]) -- 'F32 +(nil? [1e -2.5e 0Ne]) -- [false false true] +(format "%" 1.5e) -- "1.5e" +(format "%" [1e 0Ne 3e]) -- "[1.0e 0Ne 3.0e]" +(type (eval (parse (format "%" 1.5e)))) -- 'f32 +(type (eval (parse (format "%" [1e 0Ne 3e])))) -- 'F32 +(eval (parse (format "%" [1e 0Ne 3e]))) -- [1e 0Ne 3e] +(type (eval (parse (format "%" 1e20e)))) -- 'f32 +(type (eval (parse (format "%" 1e-20e)))) -- 'f32 +(parse "1e+") !- parse +(parse "1e-") !- parse +(parse "1E") !- parse +(parse "1ee") !- parse +(parse "1.5ex") !- parse +(parse "1e3ee") !- parse + +;; STR casts produce numeric data, while format produces literal syntax. +(as 'STR 1.5e) -- "1.5" +(as 'str -2.5e) -- "-2.5" +(as 'STR -0e) -- "0" +(as 'STR 0Ne) -- "" +(as 'STR [1.5e -2.5e 0e 0Ne]) -- ["1.5" "-2.5" "0" ""] +(as 'F32 (as 'STR 1.5e)) -- 1.5e +(as 'F64 (as 'STR 1.5e)) -- 1.5 +(as 'F32 (as 'STR [1.5e -2.5e 0e 0Ne])) -- [1.5e -2.5e 0e 0Ne] +(as 'F64 (as 'STR [1.5e -2.5e 0e 0Ne])) -- [1.5 -2.5 0.0 0Nf] +;; Nine significant digits suffice for exact F32 readback, including values +;; beyond the display precision, scientific notation and subnormals. +(set f32_text_values [1.23456789e 1e20e 1e-20e 1e-40e]) +(all (== f32_text_values (as 'F32 (as 'STR f32_text_values)))) -- true +(as 'STR f32_text_values) -- (as 'STR (as 'SYMBOL f32_text_values)) +(format "%" 1.5e) -- "1.5e" diff --git a/test/rfl/lang/if_chain.rfl b/test/rfl/lang/if_chain.rfl new file mode 100644 index 000000000..b9a3236a0 --- /dev/null +++ b/test/rfl/lang/if_chain.rfl @@ -0,0 +1,61 @@ +;; (if c1 r1 c2 r2 ... else?) — condition/result pairs tried in order, an +;; odd trailing arg is the fallback. Covers the tree-walking evaluator +;; (top level) and the bytecode compiler (inside a lambda) alike. + +;; ── tree-walking evaluator ────────────────────────────────────────────────── +(if false 1 false 2 3) -- 3 +(if false 1 true 2 3) -- 2 +(if true 1 false 2 3) -- 1 +(if false 1 false 2 false 3 4) -- 4 +(if false 1 false 2 true 3 4) -- 3 +;; even arg count: no fallback, 0 when nothing matches +(if false 1 false 2) -- 0 +(if false 1 true 2) -- 2 +;; the three-arg form is unchanged +(if false 1 3) -- 3 +(if true 1 3) -- 1 +(if false 1) -- 0 + +;; ── bytecode compiler ────────────────────────────────────────────────────── +(set classify (fn [x] (if (> x 100) "high" (> x 50) "mid" "low"))) +(classify 200) -- "high" +(classify 60) -- "mid" +(classify 10) -- "low" +((fn [] (if false 1 false 2 false 3 4))) -- 4 +((fn [] (if false 1 false 2))) -- 0 +((fn [] (if false 1 true 2))) -- 2 + +;; ── only the taken branch is evaluated ───────────────────────────────────── +(set n 0) +(if false (set n 1) true (set n 2) (set n 3)) +n -- 2 +(set m 0) +((fn [] (if false (set m 1) false (set m 2) (set m 3)))) +m -- 3 +;; conditions after the first truthy one are not evaluated +(set k 0) +((fn [] (if true 1 (set k 9) 2 3))) +k -- 0 + +;; ── inside queries ───────────────────────────────────────────────────────── +;; A chain with a fallback lowers to nested element-wise OP_IF (the planner +;; and the fused kernels), so where:, by: and projections see it row by row, +;; and a text literal becomes a SYM cell as in the three-argument form; a +;; pure helper holding one is inlined the same way. A chain with no +;; fallback stays with the evaluator, which runs it per row in a projection. +(set Tq (table [v s] (list [1 3 6 9 150] ["a" "b" "c" "d" "e"]))) +(set clq (fn [x] (if (> x 100) "high" (> x 5) "mid" "low"))) +(at (select {k: (if (> v 100) "high" (> v 5) "mid" "low") from: Tq}) 'k) -- ['low 'low 'mid 'mid 'high] +(at (select {k: (clq v) from: Tq}) 'k) -- ['low 'low 'mid 'mid 'high] +(at (select {from: Tq where: (if (> v 100) false (> v 5) true false)}) 'v) -- [6 9] +(at (select {from: Tq where: (if (> v 100) (== s "e") (> v 5) (!= s "c") false)}) 'v) -- [9 150] +(set Bq (select {n: (count v) mx: (max v) from: Tq by: {k: (if (> v 100) "high" (> v 5) "mid" "low")}})) +(at Bq 'k) -- ['low 'mid 'high] +(at Bq 'n) -- [2 2 1] +(at Bq 'mx) -- [3 9 150] +(at (select {n: (count v) from: Tq by: {k: (clq v)}}) 'n) -- [2 2 1] +(at (update {k: (if (> v 100) 3 (> v 5) 2 1) from: Tq}) 'k) -- [1 1 2 2 3] +;; numeric chain with a nested arithmetic result and a where: on top +(at (select {k: (if (> v 100) (* v 2) (> v 5) (+ v 1) 0) from: Tq where: (> v 1)}) 'k) -- [0 7 10 300] +;; no fallback: the evaluator's per-row path, 0 where nothing matches +(at (select {k: (if (> v 100) 3 (> v 5) 2) from: Tq}) 'k) -- [0 0 2 2 3] diff --git a/test/rfl/lang/special_form_locals.rfl b/test/rfl/lang/special_form_locals.rfl index 3b876a302..69ab9cce3 100644 --- a/test/rfl/lang/special_form_locals.rfl +++ b/test/rfl/lang/special_form_locals.rfl @@ -15,6 +15,20 @@ (count data) -- 2 (at data 1) -- 7 +;; alter reads local bindings but writes globals. Reject the local before +;; changing either it or an unrelated global with the same name. +((fn [] (let alter_only_local [1 2 3]) (alter 'alter_only_local set 0 9))) !- domain +alter_only_local !- name +(set alter_shadow [5 5]) +((fn [] (let alter_shadow [1 2 3]) (alter 'alter_shadow set 0 9))) !- domain +alter_shadow -- [5 5] +((fn [] (let alter_shadow [1 2 3]) (alter 'alter_shadow concat [4]))) !- domain +alter_shadow -- [5 5] +((fn [] (let alter_shadow (list 1 2 3)) (alter 'alter_shadow remove 0))) !- domain +alter_shadow -- [5 5] +((fn [alter_shadow] (alter 'alter_shadow set 0 9)) [1 2 3]) !- domain +alter_shadow -- [5 5] + ;; and/or with params — must match the top-level (tree-walk) results: ;; scalar-falsy short-circuit returns the accumulator, otherwise the ;; element-wise combine yields a boolean diff --git a/test/rfl/lang/sym_null_format.rfl b/test/rfl/lang/sym_null_format.rfl new file mode 100644 index 000000000..eb3fc3029 --- /dev/null +++ b/test/rfl/lang/sym_null_format.rfl @@ -0,0 +1,21 @@ +;; The empty symbol ' is SYM's null. It prints as ' wherever it appears, a +;; vector cell included, so the printed form reads back as the same value. +;; A vector cell used to print as `null`, which reads back as the symbol +;; `null`, a different, non-null value (#871). + +(format "%" ') -- "'" +(format "%" [A ' B]) -- "[A ' B]" +(format "%" [' ' ']) -- "[' ' ']" +(format "%" (list [A ' B] 1)) -- "(list [A ' B] 1)" +(format "%" (dict [A B] [' X])) -- "{A:' B:X}" +(format "%" (dict [' A] [1 2])) -- "{':1 A:2}" +(format "%" (take ' 2)) -- "[' ']" + +;; round trip: the printed cell parses back as the null +(nil? [A ' B]) -- [false true false] +(nil? (eval (parse (format "%" [A ' B])))) -- [false true false] +(== [A ' B] (eval (parse (format "%" [A ' B])))) -- [true true true] + +;; the symbol `null` is an ordinary, non-null symbol and prints as itself +(nil? [A null B]) -- [false false false] +(format "%" [A null B]) -- "[A null B]" diff --git a/test/rfl/lang/times.rfl b/test/rfl/lang/times.rfl index 05fd9c00b..a7324b63d 100644 --- a/test/rfl/lang/times.rfl +++ b/test/rfl/lang/times.rfl @@ -122,3 +122,76 @@ out -- 6 (set i 0) (times 3 (do (let sq (* i i)) (set out (concat out sq))) (set i (+ i 1))) out -- (list 0 1 4) + +;; ── indexed form: (times [i n] body...) ────────────────────────────── +;; i runs over 0, 1, ..., n-1, one value per pass +(set out (list)) +(times [i 4] (set out (concat out i))) +out -- [0 1 2 3] + +;; the count is any expression, evaluated once +(set qty [1 2 3]) +(set delta [10 20 30]) +(times [j (count qty)] (alter 'qty set j (+ (at qty j) (at delta j)))) +qty -- [11 22 33] + +;; a name as the count is a reference, not a symbol literal +(set m 3) +(set s 0) +(times [k m] (set s (+ s k))) +s -- 3 + +;; i is bound like a let and keeps the last index after the loop +(times [last 5] 0) +last -- 4 + +;; zero and negative counts run no pass and leave i alone +(set z 99) +(times [z 0] (set z 1)) +z -- 99 +(times [z -2] (set z 1)) +z -- 99 + +;; rebinding i in the body lasts for the rest of that pass only +(set seen (list)) +(times [i 3] (set seen (concat seen i)) (set i 100)) +seen -- [0 1 2] + +;; still a statement form +(nil? (times [i 3] i)) -- true + +;; ── indexed form, compiled ─────────────────────────────────────────── +((fn [n] (let acc 0) (times [k n] (let acc (+ acc k))) acc) 5) -- 10 +((fn [n] (let s (list)) (times [k n] (let s (concat s k)) (let k 100)) s) 3) -- [0 1 2] +((fn [] (times [k 5] 0) k)) -- 4 +((fn [n] (let k 99) (times [k n] (let k 1)) k) 0) -- 99 +((fn [n] (let k 99) (times [k n] (let k 1)) k) -3) -- 99 +((fn [n] (times [k n] (if (== k 2) (return (* k 10)))) -1) 10) -- 20 +((fn [] (times [i "3"] 1))) !- type +((fn [] (times [i 1.5] 1))) !- type + +;; the index reaches a compiled loop's alter, the backtester shape +(set pos [5 5 5 5]) +((fn [d] (times [i (count pos)] (alter 'pos set i (- (at pos i) (at d i))))) [1 2 3 4]) +pos -- [4 3 2 1] + +;; nested, each index its own; the hidden bounds do not collide +((fn [] (let t 0) (times [a 3] (times [b 4] (let t (+ t (* a b))))) t)) -- 18 +(set t 0) +(times [a 3] (times [b 4] (set t (+ t (* a b))))) +t -- 18 + +;; indexed and plain loops nest in either order +((fn [] (let t 0) (times 2 (times [b 3] (let t (+ t b)))) t)) -- 6 +((fn [] (let t 0) (times [a 3] (times 2 (let t (+ t a)))) t)) -- 6 + +;; a closure made in the body sees the index of its pass +((fn [] (let fs (list)) (times [i 3] (let fs (concat fs (list (fn [] i))))) (map (fn [f] (f)) fs))) -- [0 1 2] + +;; ── indexed form, errors ───────────────────────────────────────────── +(set c 0) +(== (try (times [i (raise 'bad-count)] (set c (+ c 1))) (fn [e] e)) 'bad-count) -- true +c -- 0 +(times [.sys.gc 3] 1) !- reserve +((fn [] (times [.sys.gc 3] 1))) !- reserve +(times [i 1.5] 1) !- type diff --git a/test/rfl/mem/heap_coverage.rfl b/test/rfl/mem/heap_coverage.rfl index 781bfbfc6..a30df4ca4 100644 --- a/test/rfl/mem/heap_coverage.rfl +++ b/test/rfl/mem/heap_coverage.rfl @@ -368,5 +368,123 @@ FV1 -- [1.5 2.5 3.5] ;; fast path. Nothing to assert; see line 1106 in the trace. ;; ════════════════════════════════════════════════════════════════════════════ +;; ════════════════════════════════════════════════════════════════════════════ +;; 13. Releasing deeply nested values (ray_free_walk). +;; A dying container freed each child through a nested ray_free, one +;; chain of C frames per level, so dropping a value nested some 150k +;; deep overflowed an 8 MB stack in a release build (a few thousand +;; under ASan). Each chain below is deeper than that, is dropped by +;; rebinding, and must hand every block back: bytes-allocated returns +;; to where it was before the build, where a skipped subtree leaks MBs. +;; ════════════════════════════════════════════════════════════════════════════ + +(set heapb (fn [] (at (.sys.mem) 'bytes-allocated))) +(set down (fn [x k] (times k (let x (first x))) x)) + +;; a list chain, 300k levels +(set h0 (heapb)) +(set a (enlist 1)) +(times 300000 (set a (enlist a))) +(> (- (heapb) h0) 10000000) -- true +(set a 0) +(< (- (heapb) h0) 65536) -- true + +;; a dict chain: dict -> values list -> dict, the keys vector per level +(set h0 (heapb)) +(set d (dict ['k] (list 1))) +(times 150000 (set d (dict ['k] (list d)))) +(> (- (heapb) h0) 10000000) -- true +(set d 0) +(< (- (heapb) h0) 65536) -- true + +;; a table chain: table -> column list -> list column -> table +(set h0 (heapb)) +(set t (table [c] (list (list 1)))) +(times 100000 (set t (table [c] (list (list t))))) +(> (- (heapb) h0) 10000000) -- true +(set t 0) +(< (- (heapb) h0) 65536) -- true + +;; a closure chain: each lambda captures the previous one, and all of them +;; share the template's body and bytecode, which must survive the drop +(set mk (fn [g] (fn [] (g)))) +(set f (fn [] 7)) +(times 3 (set f (mk f))) +(f) -- 7 +(set h0 (heapb)) +(times 100000 (set f (mk f))) +(> (- (heapb) h0) 10000000) -- true +(set f (fn [] 7)) +(< (- (heapb) h0) 65536) -- true +((mk (mk f))) -- 7 + +;; every level holds the next one twice: a child whose count drops to zero +;; on its parent's second reference, not its first +(set h0 (heapb)) +(set g (list 1)) +(times 300000 (set g (list g g))) +(set g 0) +(< (- (heapb) h0) 65536) -- true + +;; every level mixes leaves (a long string atom, a vector, atoms) with the +;; next level, held both directly and through a dict +(set h0 (heapb)) +(set m (list 0)) +(times 100000 (set m (list m "a string longer than seven" [1 2 3] 'sym 1.5 (dict ['x] (list m))))) +(set m 0) +(< (- (heapb) h0) 65536) -- true + +;; the next level first and leaves after it: the walk comes back up to a +;; parent with slots still to release, in a list and in a dict's values +(set h0 (heapb)) +(set a (enlist 1)) +(times 100000 (set a (list a (til 3) "a string longer than seven"))) +(> (- (heapb) h0) 10000000) -- true +(set a 0) +(< (- (heapb) h0) 65536) -- true +(set h0 (heapb)) +(set e (dict ['k] (list 1))) +(times 100000 (set e (dict ['k 'x 'y] (list e (til 3) "a string longer than seven")))) +(> (- (heapb) h0) 10000000) -- true +(set e 0) +(< (- (heapb) h0) 65536) -- true + +;; leaves that own references of their own (fresh long strings) and empty +;; containers, one level after another: each must be freed along with the +;; level, not just have its block returned +(set h0 (heapb)) +(set a (enlist 1)) +(times 100000 (set a (list a (concat "a string longer than seven" "x") (list) (format "%" 123456789012)))) +(> (- (heapb) h0) 10000000) -- true +(set a 0) +(< (- (heapb) h0) 65536) -- true +(set h0 (heapb)) +(set z (list)) +(times 100000 (set z (list z (list) (dict [] (list))))) +(> (- (heapb) h0) 10000000) -- true +(set z 0) +(< (- (heapb) h0) 65536) -- true + +;; a chain still referenced from the middle: dropping the top frees only +;; the levels above it, and the rest stays whole until it goes too +(set h0 (heapb)) +(set a (enlist 1)) +(times 200000 (set a (enlist a))) +(set mid a) +(times 200000 (set a (enlist a))) +(set a 0) +(down mid 200000) -- [1] +(set mid 0) +(< (- (heapb) h0) 65536) -- true + +;; one vector held by two lists: dropping either leaves it to the other +(set s (til 5)) +(set p1 (list s s)) +(set p2 (list s)) +(set s 0) +(set p1 0) +(sum (at p2 0)) -- 10 +(set p2 0) + ;; ────────────── teardown ────────────── (.sys.exec "rm -rf /tmp/rfl_heap_*") diff --git a/test/rfl/mem/iterate_typed_peak.rfl b/test/rfl/mem/iterate_typed_peak.rfl new file mode 100644 index 000000000..1d0709c7e --- /dev/null +++ b/test/rfl/mem/iterate_typed_peak.rfl @@ -0,0 +1,18 @@ +;; iterate_typed_peak.rfl — fold, fold-right and the scalar walks of map and +;; scan box a typed vector's elements one at a time (#823). +;; +;; They used to turn the whole vector into a LIST of boxed atoms before the +;; first call and keep it for the whole walk: about ten times the vector's +;; memory, even for a builtin with a scalar accumulator. Measured first in +;; this file, so the peak counter holds only what these walks cost: the +;; vector (1.6 MB) plus O(1), well under twice the vector. Boxed up front, the +;; peak was ~5x the vector. +(set X (til 200000)) +(set bound (* 2 (* 8 200000))) +(fold + 0 X) -- 19999900000 +(< (at (.sys.mem) 'peak-bytes) bound) -- true +(fold (fn [a i] (+ a i)) 0 X) -- 19999900000 +(< (at (.sys.mem) 'peak-bytes) bound) -- true +(fold + X) -- 19999900000 +(fold-right + 0 X) -- 19999900000 +(< (at (.sys.mem) 'peak-bytes) bound) -- true diff --git a/test/rfl/mem/query_fallback_alloc.rfl b/test/rfl/mem/query_fallback_alloc.rfl new file mode 100644 index 000000000..9622a7c45 --- /dev/null +++ b/test/rfl/mem/query_fallback_alloc.rfl @@ -0,0 +1,41 @@ +;; @requires: posix +;; Query-scoped, all-thread managed allocation traffic for computed keys. +;; 64 unused I32 columns x40000 rows require 10240000 payload bytes for +;; a full flatten (before headers/buddy rounding). The 8MiB traffic bound +;; separates that from the measured <4.2MiB required-column path. It is NOT +;; the old 960000-byte calling-heap historical-peak-growth assertion. +;; Cold pruning/cache publication is independently checked in C; here prime +;; ONLY the two named columns, never the select whose behavior we constrain. +(.sys.exec "rm -rf rfl_fallback_alloc") +(set Nma 5000) +(set mkma (fn [p] (table (concat ['k 'lo] (as 'SYMBOL (map (fn [j] (format "c%" j)) (til 64)))) (concat (list (+ (* p Nma) (til Nma)) (% (til Nma) 10)) (map (fn [j] (as 'I32 (+ j (til Nma)))) (til 64)))))) +(map (fn [p] (do (.db.splayed.set (format "rfl_fallback_alloc/2024.01.0%/t/" (+ p 1)) (mkma p)) 0)) (til 8)) +(set Pma (.db.parted.get "rfl_fallback_alloc/" 't)) +(set _prime (at Pma 'k)) +(set _prime 0) +(set _prime (at Pma 'lo)) +(set _prime 0) +(set ma_bare (fn [] (count (select {c: (count k) by: (reverse lo) from: Pma})))) +(set ma_dict (fn [] (count (select {c: (count k) by: {kk: (reverse lo)} from: Pma})))) +(set _measurement (.mem.ts (ma_bare))) +(at _measurement 'result) -- 10 +(< (at _measurement 'allocated-bytes) 8388608) -- true +(set _measurement 0) +(set _measurement (.mem.ts (ma_dict))) +(at _measurement 'result) -- 10 +(< (at _measurement 'allocated-bytes) 8388608) -- true +(set _measurement 0) +;; Stabilize closures/caches, then discard all per-call results inside a +;; separate scope. Do not free a previous measurement inside the next trace. +(times 20 (ma_bare)) +(set _measurement (.mem.ts (do (times 20 (ma_bare)) 0))) +(at _measurement 'result) -- 0 +(< (abs (at _measurement 'net-bytes)) 4096) -- true +(set _measurement 0) +(times 20 (ma_dict)) +(set _measurement (.mem.ts (do (times 20 (ma_dict)) 0))) +(at _measurement 'result) -- 0 +(< (abs (at _measurement 'net-bytes)) 4096) -- true +(set _measurement 0) +(set Pma 0) +(.sys.exec "rm -rf rfl_fallback_alloc") diff --git a/test/rfl/mem/query_input_release.rfl b/test/rfl/mem/query_input_release.rfl index fe80e7772..704d64dd2 100644 --- a/test/rfl/mem/query_input_release.rfl +++ b/test/rfl/mem/query_input_release.rfl @@ -18,8 +18,8 @@ (set probe (fn [f warm reps] (do (map f (til warm)) (map f (til reps)) (set h0 (heapb)) (map f (til reps)) (< (- (heapb) h0) 4096)))) ;; Peak memory of selects over a parted table, measured first in this file: -;; the peak counter starts with the file, so nothing larger run before hides -;; a query's own peak. A grouped select with no outputs, or a sort without +;; peak-bytes is the calling heap's historical high-water mark, not a +;; process-wide query peak. These checks precede larger result probes. A grouped select with no outputs, or a sort without ;; by:, reads the columns its clauses name and gathers the others at the rows ;; it keeps; whatever the number of groups or rows kept, its peak stays ;; below what flattening the table costs (the table, then its rows again for @@ -31,6 +31,17 @@ (map (fn [p] (do (.db.splayed.set (format "/tmp/rfl_ckmw/2024.01.0%/t/" (+ p 1)) (mkmw p)) 0)) (til 8)) (set Pmw (.db.parted.get "/tmp/rfl_ckmw/" 't)) (set Bmw (* (* 8 Nmw) 96)) +;; a scalar aggregate that reads no column binds nothing of the table: +;; it flattens none of it +(set pk0 (at (.sys.mem) 'peak-bytes)) +(at (select {x: (count [1 2 3]) from: Pmw}) 'x) -- [3] +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +(set pk0 (at (.sys.mem) 'peak-bytes)) +(at (select {x: (first (asc [3 1 2])) from: Pmw}) 'x) -- [1] +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true +(set pk0 (at (.sys.mem) 'peak-bytes)) +(at (select {x: (count (til 5)) from: Pmw}) 'x) -- [5] +(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true ;; a sort without by: taking 3 rows reads the key and those 3 rows only (set pk0 (at (.sys.mem) 'peak-bytes)) (at (select {from: Pmw desc: k take: 3}) 'k) -- [39999 39998 39997] @@ -47,14 +58,13 @@ (set pk0 (at (.sys.mem) 'peak-bytes)) (count (select {by: {kk: (+ lo 1)} from: Pmw})) -- 10 (< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true -;; a key the planner cannot lower flattens only the columns the select reads -(set pk0 (at (.sys.mem) 'peak-bytes)) +;; A key the planner cannot lower flattens only named source columns. +;; Its resource oracle lives in query_fallback_alloc.rfl and the cold-cache +;; scanrange test: decoded caches can belong to the caller or helper heaps, +;; so subtracting the caller's historical peak is not a query-scoped budget. (count (select {c: (count k) by: (reverse lo) from: Pmw})) -- 10 -(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true ;; as a by-dict value too -(set pk0 (at (.sys.mem) 'peak-bytes)) (count (select {c: (count k) by: {kk: (reverse lo)} from: Pmw})) -- 10 -(< (- (at (.sys.mem) 'peak-bytes) pk0) (/ Bmw 4)) -- true ;; every key unique: the result is the whole table, and little more (set pk0 (at (.sys.mem) 'peak-bytes)) (count (select {by: k from: Pmw})) -- 40000 diff --git a/test/rfl/mem/vec_growth_capacity.rfl b/test/rfl/mem/vec_growth_capacity.rfl new file mode 100644 index 000000000..885f78117 --- /dev/null +++ b/test/rfl/mem/vec_growth_capacity.rfl @@ -0,0 +1,16 @@ +;; A two-column initial batch uses minimal header-inclusive buddy blocks. +;; This is caller-live allocation for a serial append, not RSS/high-water or +;; a guarantee that freed pools return to the OS. Allow incidental metadata; +;; the old two8MiB column blocks exceed this9MiB bound by a wide margin. +(set n 333004) +(set src (table [a b] (list (til n) (til n)))) +(set L (table [a b] (list (take [0] 0) (take [0] 0)))) +(set before (at (.sys.mem) 'bytes-allocated)) +(insert 'L src) +(set used (- (at (.sys.mem) 'bytes-allocated) before)) +(< used 9437184) -- true +(count L) -- n +(sum (at L 'a)) -- (sum (til n)) +(sum (at L 'b)) -- (sum (til n)) +(at (at L 'a) [0 166502 333003]) -- [0 166502 333003] +(at (at L 'b) [0 166502 333003]) -- [0 166502 333003] diff --git a/test/rfl/null/cast.rfl b/test/rfl/null/cast.rfl index 663c0f495..15a57d5c0 100644 --- a/test/rfl/null/cast.rfl +++ b/test/rfl/null/cast.rfl @@ -4,7 +4,7 @@ (sum (map nil? (as 'I32 [1 0N 3]))) -- 1 (sum (map nil? (as 'I16 [1 0N 3]))) -- 1 ;; Post-Phase-1: B8 / U8 are non-nullable. Casting an integer null to -;; B8 collapses the null to b8-zero (no NULL_B8 sentinel exists), so +;; B8 converts the non-zero integer null sentinel to true, so ;; the post-cast nil? scan reports 0 nulls. (sum (map nil? (as 'B8 [1 0N 3]))) -- 0 diff --git a/test/rfl/null/f32_guid_null_literals.rfl b/test/rfl/null/f32_guid_null_literals.rfl new file mode 100644 index 000000000..c3ebaca2a --- /dev/null +++ b/test/rfl/null/f32_guid_null_literals.rfl @@ -0,0 +1,35 @@ +;; F32 and GUID nulls read back: 0Ne and 0Ng parse, and every printer +;; writes them that way (#881). + +;; ----- 1. Literals ----- + +(type 0Ne) -- 'f32 +(nil? 0Ne) -- true +(type 0Ng) -- 'guid +(nil? 0Ng) -- true +(type [0Ne 0Ne]) -- 'F32 +(nil? [0Ne 0Ne]) -- [true true] +(type [0Ng 0Ng]) -- 'GUID +(count [0Ng 0Ng]) -- 2 + +;; ----- 2. The literal is the value a cast produces ----- + +0Ne -- (as 'F32 0Nl) +0Ng -- (as 'GUID 0Nl) +0Ng -- (as 'GUID "00000000-0000-0000-0000-000000000000") +[0Ng] -- (enlist (as 'GUID 0Nl)) + +;; ----- 3. Every printer writes the literal ----- + +(format "%" 0Ne) -- "0Ne" +(format "%" 0Ng) -- "0Ng" +(format "%" (as 'GUID 0Nl)) -- "0Ng" +(format "%" [0Ne 0Ne]) -- "[0Ne 0Ne]" +(format "%" [0Ng 0Ng]) -- "[0Ng 0Ng]" + +;; ----- 4. as 'F32 keeps nulls ----- +;; Non-null F32 elements retain their type through printing and parsing. + +(type (as 'F32 [1 0Nl 3])) -- 'F32 +(nil? (as 'F32 [1 0Nl 3])) -- [false true false] +(format "%" (as 'F32 [1 0Nl 3])) -- "[1.0e 0Ne 3.0e]" diff --git a/test/rfl/null/fused_agg_input.rfl b/test/rfl/null/fused_agg_input.rfl index 7405839d0..01a6a195e 100644 --- a/test/rfl/null/fused_agg_input.rfl +++ b/test/rfl/null/fused_agg_input.rfl @@ -36,3 +36,87 @@ ;; would overflow to 0 only by coincidence for exactly 2 null rows). (at (at (select {s: (sum (* x 2)) from: T by: k where: (== k 1)}) 's) 0) -- 60 (at (at (select {s: (sum (* x 2)) from: T by: k where: (== k 2)}) 's) 0) -- 0 + +;; ── Affine input (col +/- c) over a nullable col (issue #814) ────────────── +;; try_affine_sumavg_input aggregates the bare column and adds the bias at +;; emit. (col + c) is null wherever col is, so a SUM adds bias * NON-NULL +;; count, not bias * group rows: an all-null group sums to 0 and a partly +;; null group is not off by c per null row. The oracle is the same agg over +;; the materialized expression column (e = w + 100, f = w - 7, nulls kept). +;; Keys: w is null when k % 5 == 0 (all-null groups) or v % 7 == 0 (partly +;; null groups). Values are small integers, so F64 sums are exact. +(set AffEq (fn [x y] (and (== (count x) (count y)) (all (== x y))))) +(set AffMk (fn [n ng ty] (do (set k (% (* (til n) 7919) ng)) (set v (til n)) (set w (as ty (at (concat (til 13) (take 0Nl 13)) (+ (% (+ k v) 13) (* 13 (as 'I64 (or (== (% k 5) 0) (== (% v 7) 0)))))))) (table [k s v w e f] (list k (at (as 'SYMBOL (map (fn [j] (format "a%" j)) (til ng))) k) v w (+ w 100) (- w 7)))))) +(set AffChk (fn [T] (do (set x (select {m: (sum (+ w 100)) r: (sum (+ 100 w)) d: (sum (- w 7)) a: (avg (+ w 100)) from: T by: {s: s z: (% v 1) t: s}})) (set y (select {m: (sum e) r: (sum e) d: (sum f) a: (avg e) from: T by: {s: s z: (% v 1) t: s}})) (and (AffEq (at x 's) (at y 's)) (AffEq (at x 'm) (at y 'm)) (AffEq (at x 'r) (at y 'r)) (AffEq (at x 'd) (at y 'd)) (AffEq (at x 'a) (at y 'a)))))) +(set AffZero (fn [T] (at (select {m: (sum (+ w 100)) from: T by: {s: s z: (% v 1) t: s} where: (== s 'a0)}) 'm))) + +;; Keyless: the scalar reduction emits through emit_agg_columns. +(set Ta (table [w e f] (list [0N 1 2 0N 4] (+ [0N 1 2 0N 4] 100) (- [0N 1 2 0N 4] 7)))) +(at (select {m: (sum (+ w 100)) d: (sum (- w 7)) from: Ta}) 'm) -- [307] +(at (select {m: (sum (+ w 100)) d: (sum (- w 7)) from: Ta}) 'd) -- [-14] +(at (select {m: (sum (+ w 100)) from: Ta}) 'm) -- [307] +(at (select {m: (avg (+ w 100)) from: Ta}) 'm) -- [102.33333333333333] +(set Tb (table [w] (list [0N 1.5 2.0 0N 4.5]))) +(at (select {m: (sum (+ w 100.0)) d: (sum (- w 7)) from: Tb}) 'm) -- [308.0] +(at (select {m: (sum (+ w 100.0)) from: Tb}) 'm) -- [308.0] +(at (select {m: (sum (+ w 100)) from: (table [w] (list (as 'I64 [0N 0N])))}) 'm) -- [0] + +;; Parted, compound key: each partition groups on its own. 8000 rows over two +;; partitions run the sequential HT emit; 2 x 70000 rows (above the parallel +;; threshold) run the radix phase-3 emit. +(.sys.exec "rm -rf /tmp/rfl_aff814") +(set Wi (AffMk 8000 2000 'I64)) +(.db.splayed.set "/tmp/rfl_aff814/s/2024.01.01/t/" (take Wi 4000) "/tmp/rfl_aff814/s/.sym") +(.db.splayed.set "/tmp/rfl_aff814/s/2024.01.02/t/" (drop Wi 4000) "/tmp/rfl_aff814/s/.sym") +(AffChk (.db.parted.get "/tmp/rfl_aff814/s" 't)) -- true +(AffZero (.db.parted.get "/tmp/rfl_aff814/s" 't)) -- [0] +(set Wf (AffMk 8000 2000 'F64)) +(.db.splayed.set "/tmp/rfl_aff814/sf/2024.01.01/t/" (take Wf 4000) "/tmp/rfl_aff814/sf/.sym") +(.db.splayed.set "/tmp/rfl_aff814/sf/2024.01.02/t/" (drop Wf 4000) "/tmp/rfl_aff814/sf/.sym") +(AffChk (.db.parted.get "/tmp/rfl_aff814/sf" 't)) -- true +(AffZero (.db.parted.get "/tmp/rfl_aff814/sf" 't)) -- [0.0] +(set Wi (AffMk 140000 3000 'I64)) +(.db.splayed.set "/tmp/rfl_aff814/r/2024.01.01/t/" (take Wi 70000) "/tmp/rfl_aff814/r/.sym") +(.db.splayed.set "/tmp/rfl_aff814/r/2024.01.02/t/" (drop Wi 70000) "/tmp/rfl_aff814/r/.sym") +(AffChk (.db.parted.get "/tmp/rfl_aff814/r" 't)) -- true +(AffZero (.db.parted.get "/tmp/rfl_aff814/r" 't)) -- [0] +(set Wf (AffMk 140000 3000 'F64)) +(.db.splayed.set "/tmp/rfl_aff814/rf/2024.01.01/t/" (take Wf 70000) "/tmp/rfl_aff814/rf/.sym") +(.db.splayed.set "/tmp/rfl_aff814/rf/2024.01.02/t/" (drop Wf 70000) "/tmp/rfl_aff814/rf/.sym") +(AffChk (.db.parted.get "/tmp/rfl_aff814/rf" 't)) -- true +(AffZero (.db.parted.get "/tmp/rfl_aff814/rf" 't)) -- [0.0] +(.sys.exec "rm -rf /tmp/rfl_aff814") + +;; Grouped take over an affine SUM of a nullable col. The radix top-N heap +;; ranks by the raw accumulator slot (sum of col alone); the emitted value is +;; raw + c * non-null count, so with nulls the two orders disagree even when +;; every group has the same row count. 2000 groups of 4 rows: even groups +;; are w = 0 (raw 0, emitted 4c), odd groups are one 1 and three nulls (raw 1, +;; emitted 1 + c). Ranking by the raw slot returns the odd groups for desc:. +;; For (- y 7) the even groups are y = 5 (raw 20, emitted -8) so that the raw +;; order again disagrees with the emitted one (odd groups emit -6). +(.sys.exec "rm -rf /tmp/rfl_aff814t") +(set Kt (% (til 8000) 2000)) +(set Wti (as 'I64 (map (fn [i] (if (== 0 (% (at Kt i) 2)) 0 (if (< i 2000) 1 0Nl))) (til 8000)))) +(set Yti (as 'I64 (map (fn [i] (if (== 0 (% (at Kt i) 2)) 5 (if (< i 2000) 1 0Nl))) (til 8000)))) +(set Wt (table [s w x y yf v] (list (at (as 'SYMBOL (map (fn [j] (format "w%" j)) (til 2000))) Kt) Wti (as 'F64 Wti) Yti (as 'F64 Yti) (til 8000)))) +(at (select {m: (sum (+ w 100)) from: Wt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [400 400 400 400 400] +(at (select {m: (sum (+ w 100)) from: Wt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [101 101 101 101 101] +(at (select {m: (sum (- y 7)) from: Wt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [-6 -6 -6 -6 -6] +(at (select {m: (sum (- y 7)) from: Wt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [-8 -8 -8 -8 -8] +(at (select {m: (sum (+ x 2.5)) from: Wt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [10.0 10.0 10.0 10.0 10.0] +(at (select {m: (sum (+ x 2.5)) from: Wt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [3.5 3.5 3.5 3.5 3.5] +(at (select {m: (sum (- yf 7)) from: Wt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [-6.0 -6.0 -6.0 -6.0 -6.0] +(at (select {m: (sum (- yf 7)) from: Wt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [-8.0 -8.0 -8.0 -8.0 -8.0] +(.db.splayed.set "/tmp/rfl_aff814t/2024.01.01/t/" (take Wt 4000) "/tmp/rfl_aff814t/.sym") +(.db.splayed.set "/tmp/rfl_aff814t/2024.01.02/t/" (drop Wt 4000) "/tmp/rfl_aff814t/.sym") +(set Pt (.db.parted.get "/tmp/rfl_aff814t" 't)) +(at (select {m: (sum (+ w 100)) from: Pt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [400 400 400 400 400] +(at (select {m: (sum (+ w 100)) from: Pt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [101 101 101 101 101] +(at (select {m: (sum (- y 7)) from: Pt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [-6 -6 -6 -6 -6] +(at (select {m: (sum (- y 7)) from: Pt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [-8 -8 -8 -8 -8] +(at (select {m: (sum (+ x 2.5)) from: Pt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [10.0 10.0 10.0 10.0 10.0] +(at (select {m: (sum (+ x 2.5)) from: Pt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [3.5 3.5 3.5 3.5 3.5] +(at (select {m: (sum (- yf 7)) from: Pt by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- [-6.0 -6.0 -6.0 -6.0 -6.0] +(at (select {m: (sum (- yf 7)) from: Pt by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- [-8.0 -8.0 -8.0 -8.0 -8.0] +(.sys.exec "rm -rf /tmp/rfl_aff814t") diff --git a/test/rfl/null/nonnullable_cast.rfl b/test/rfl/null/nonnullable_cast.rfl new file mode 100644 index 000000000..654995741 --- /dev/null +++ b/test/rfl/null/nonnullable_cast.rfl @@ -0,0 +1,57 @@ +;; #880: non-nullable casts agree for atoms, vectors, lists and queries. +(as 'U8 0Nl) -- 0x00 +(as 'B8 0Nl) -- true +(type (as 'U8 0Nl)) -- 'u8 +(type (as 'B8 0Nl)) -- 'b8 +(nil? (as 'U8 0Nl)) -- false +(nil? (as 'B8 0Nl)) -- false +(as 'U8 [1 0Nl 3]) -- [0x01 0x00 0x03] +(as 'B8 [1 0Nl 3]) -- [true true true] +(enlist (as 'U8 0Nl)) -- [0x00] +(enlist (as 'B8 0Nl)) -- [true] +(+ (as 'U8 0Nl) (as 'U8 1)) -- 0x01 +(as 'B8 [0 0Nl -1]) -- [false true true] +(as 'B8 (list 0 0Nl -1)) -- [false true true] +(as 'U8 (list 1 0Nl 3)) -- [0x01 0x00 0x03] +;; All numeric and temporal null widths use the same rule. +(set nulls (list 0Nh 0Ni 0Nl 0Ne 0Nf 0Nd 0Nt 0Np)) +(map (fn [x] (as 'B8 x)) nulls) -- (take [true] 8) +(map (fn [x] (nil? (as 'B8 x))) nulls) -- (take [false] 8) +(map (fn [x] (as 'U8 x)) nulls) -- (take [0x00] 8) +(map (fn [x] (nil? (as 'U8 x))) nulls) -- (take [false] 8) +(map (fn [x] (== (enlist (as 'B8 x)) (as 'B8 (enlist x)))) nulls) -- (take (list [true]) 8) +(map (fn [x] (== (enlist (as 'U8 x)) (as 'U8 (enlist x)))) nulls) -- (take (list [true]) 8) +;; Floating nulls are true too; floating zero remains false. +(as 'B8 [0.0 0Nf -1.5]) -- [false true true] +(as 'B8 (as 'F32 [0.0 0Nf -1.5])) -- [false true true] +(as 'U8 [0.0 0Nf 3.0]) -- [0x00 0x00 0x03] +;; Empty text converts to false; nullable numeric targets preserve nulls. +(as 'B8 "") -- false +(nil? (as 'F64 0Nl)) -- true +(nil? (as 'I32 0Nl)) -- true +;; Direct column casts and casts consumed by aggregates or predicates. +(set T (table [i f h n r] (list [0 0Nl -1] [0.0 0Nf -1.5] [0h 0Nh -1h] [0i 0Ni -1i] (as 'F32 [0.0 0Nf -1.5])))) +(at (select {from:T b:(as 'BOOL i)}) 'b) -- [false true true] +(at (select {from:T b:(as 'BOOL f)}) 'b) -- [false true true] +(at (select {from:T b:(as 'BOOL h)}) 'b) -- [false true true] +(at (select {from:T b:(as 'BOOL n)}) 'b) -- [false true true] +(at (select {from:T b:(as 'BOOL r)}) 'b) -- [false true true] +(at (select {from:T b:(as 'U8 f)}) 'b) -- [0x00 0x00 0x00] +(at (select {from:T s:(sum (as 'BOOL i))}) 's) -- [2] +(at (select {from:T s:(sum (as 'BOOL f))}) 's) -- [2] +(count (select {from:T where:(as 'BOOL f)})) -- 2 +;; Exercise the bulk parallel conversion path with null-containing vectors. +(sum (as 'B8 (take [0Nf 0.0] 300000))) -- 150000 +(sum (as 'U8 (take [0Nf 1.0] 300000))) -- 150000 +(nil? (at (select {from:T b:(as 'BOOL f)}) 'b)) -- [false false false] +(nil? (as 'B8 (list 0Nl 0Nf))) -- [false false] +(nil? (as 'U8 (list 0Nl 0Nf))) -- [false false] + +;; A whole-column producer forces the cast through the typed fallback. +;; The leading null survives fills, and must still convert to true. +(set C (table [i h n f] (list [0Nl 0 -1] [0Nh 0h -1h] [0Ni 0i -1i] [0Nf 0.0 -1.0]))) +(as 'BOOL (fills (at C 'i))) -- [true false true] +(at (select {from:C b:(as 'BOOL (fills i))}) 'b) -- [true false true] +(at (select {from:C b:(as 'BOOL (fills h))}) 'b) -- [true false true] +(at (select {from:C b:(as 'BOOL (fills n))}) 'b) -- [true false true] +(at (select {from:C b:(as 'BOOL (fills f))}) 'b) -- [true false true] diff --git a/test/rfl/null/sym_str_null_compare.rfl b/test/rfl/null/sym_str_null_compare.rfl index bde1fa4ef..689be1db7 100644 --- a/test/rfl/null/sym_str_null_compare.rfl +++ b/test/rfl/null/sym_str_null_compare.rfl @@ -195,6 +195,10 @@ (count (.db.splayed.set "rf_test_nullcmp_store" SU)) -- 98304 (set ST (.db.splayed.get "rf_test_nullcmp_store" 'SU)) (count ST) -- 98304 +;; The dict index is what a generation-0 save attaches. A generation-2 +;; (compressed) save, as in the equivalence pass, persists the same DICT in +;; the column's index region (P6b: over 65536 rows, "" in band) and attaches +;; it at materialization: one assertion for both generations. (.idx.info (at ST 'u)) -- {kind:dict length:98304 parent_type:13 saved_attrs:64 n_distinct:3} (set SA_F (select {u: u n: n from: ST where: (!= u "") desc: n take: 5})) diff --git a/test/rfl/ops/atom_sub_width.rfl b/test/rfl/ops/atom_sub_width.rfl new file mode 100644 index 000000000..29f758e72 --- /dev/null +++ b/test/rfl/ops/atom_sub_width.rfl @@ -0,0 +1,90 @@ +;; #970: atom subtraction uses both operand types, as existing atom addition does. +;; Five integral kinds, both orders. No new global widening/overflow policy. +(type (- true true)) -- 'i64 +(- true true) -- 0 +(type (- true 0x03)) -- 'i64 +(- true 0x03) -- -2 +(type (- true 30000h)) -- 'i16 +(- true 30000h) -- -29999h +(type (- true 90000i)) -- 'i32 +(- true 90000i) -- -89999i +(type (- true 100000)) -- 'i64 +(- true 100000) -- -99999 +(type (- 0x03 true)) -- 'i64 +(- 0x03 true) -- 2 +(type (- 0x03 0x03)) -- 'u8 +(- 0x03 0x03) -- 0x00 +(type (- 0x03 30000h)) -- 'i16 +(- 0x03 30000h) -- -29997h +(type (- 0x03 90000i)) -- 'i32 +(- 0x03 90000i) -- -89997i +(type (- 0x03 100000)) -- 'i64 +(- 0x03 100000) -- -99997 +(type (- 30000h true)) -- 'i16 +(- 30000h true) -- 29999h +(type (- 30000h 0x03)) -- 'i16 +(- 30000h 0x03) -- 29997h +(type (- 30000h 30000h)) -- 'i16 +(- 30000h 30000h) -- 0h +(type (- 30000h 90000i)) -- 'i32 +(- 30000h 90000i) -- -60000i +(type (- 30000h 100000)) -- 'i64 +(- 30000h 100000) -- -70000 +(type (- 90000i true)) -- 'i32 +(- 90000i true) -- 89999i +(type (- 90000i 0x03)) -- 'i32 +(- 90000i 0x03) -- 89997i +(type (- 90000i 30000h)) -- 'i32 +(- 90000i 30000h) -- 60000i +(type (- 90000i 90000i)) -- 'i32 +(- 90000i 90000i) -- 0i +(type (- 90000i 100000)) -- 'i64 +(- 90000i 100000) -- -10000 +(type (- 100000 true)) -- 'i64 +(- 100000 true) -- 99999 +(type (- 100000 0x03)) -- 'i64 +(- 100000 0x03) -- 99997 +(type (- 100000 30000h)) -- 'i64 +(- 100000 30000h) -- 70000 +(type (- 100000 90000i)) -- 'i64 +(- 100000 90000i) -- 10000 +(type (- 100000 100000)) -- 'i64 +(- 100000 100000) -- 0 + +;; Originally reported narrow-right data loss. +(- 2 0x03) -- -1 +(- 100000 3h) -- 99997 +(- 5000000000 3i) -- 4999999997 +(- 1i 0x02) -- -1i +(- [100000] 3h) -- [99997] + +;; Existing same-width modular wrapping and generated I64 null remain. +(- 0x02 0x03) -- 0xff +(- 30000h -30000h) -- -5536h +(- 2000000000i -2000000000i) -- -294967296i +(nil? (- 9223372036854775807 -1)) -- true +(type (- 9223372036854775807 -1)) -- 'i64 + +;; Null promotion already uses both operands; normal values must agree. +(type (- 0Ni 3h)) -- 'i32 +(nil? (- 0Ni 3h)) -- true +(type (- 3h 0Ni)) -- 'i32 +(nil? (- 3h 0Ni)) -- true +(type (- 100000 0Nh)) -- 'i64 +(nil? (- 100000 0Nh)) -- true + +;; Float and temporal dispatch are outside this repair. +(- 2.5 3h) -- -0.5 +(type (- 2.5e 1.0e)) -- 'f32 +(- 2.5e 1.0e) -- 1.5e +(- 2024.01.03 2024.01.02) -- 1i +(- 2024.01.03 1h) -- 2024.01.02 +(- 10:30:00.000 09:30:00.000) -- 01:00:00.000 +(type (- 2024.01.03D00:00:00.000000000 2024.01.02D00:00:00.000000000)) -- 'timespan + +;; The compiled atom call must not reintroduce right-width narrowing. +(set SUBF (fn [a b] (- a b))) +(type (SUBF 100000 3h)) -- 'i64 +(SUBF 100000 3h) -- 99997 +(type (SUBF 1i 0x02)) -- 'i32 +(SUBF 1i 0x02) -- -1i diff --git a/test/rfl/ops/builtins_branch_cov.rfl b/test/rfl/ops/builtins_branch_cov.rfl index ecd7ef0eb..833d71373 100644 --- a/test/rfl/ops/builtins_branch_cov.rfl +++ b/test/rfl/ops/builtins_branch_cov.rfl @@ -48,12 +48,11 @@ ;; I64 null (line 67) (format "%" 0Nl) -- "0Nl" -;; default null (line 74) — null_literal_str returns "null" for types -;; not in the switch (BOOL, U8, GUID, etc.) -;; The all-zeros GUID is the null GUID, and GUID isn't in the switch, -;; so it triggers the default branch. -;; Exercise this via println/format of the null GUID atom: -(format "%" (as 'GUID "00000000-0000-0000-0000-000000000000")) -- "null" +;; format/println print a null atom with the same table as the REPL +;; (ray_fmt_null_literal). The all-zeros GUID is the null GUID, and it +;; prints as 0Ng, which reads back as the same value. +(format "%" (as 'GUID "00000000-0000-0000-0000-000000000000")) -- "0Ng" +(format "%" 0Ne) -- "0Ne" ;; ═════════════════════════════════════════════════════════════════════ ;; 2. ray_lang_print branches — println drives the switch @@ -68,6 +67,9 @@ ;; -RAY_BOOL true path (format "%" true) -- "true" +;; Casting to non-nullable BOOL produces an ordinary true value. +(format "%" (as 'B8 0Nl)) -- "true" + ;; ═════════════════════════════════════════════════════════════════════ ;; 3. fmt_interpolate — per-type branches in "format" / println ;; Lines 166-224: each type arg hits a different branch. @@ -140,15 +142,15 @@ ;; null → I16 (nil? (as 'I16 0Nh)) -- true -;; null → U8 — produces null U8 sentinel -(nil? (as 'U8 0Nl)) -- true +;; null → U8 — produces ordinary zero +(nil? (as 'U8 0Nl)) -- false ;; null → F64 (nil? (as 'F64 0Nf)) -- true (nil? (as 'F64 0Nl)) -- true -;; null → BOOL — produces null BOOL sentinel -(nil? (as 'BOOL 0Nl)) -- true +;; numeric null → BOOL — produces ordinary true +(nil? (as 'BOOL 0Nl)) -- false ;; empty sym → canonical SYMBOL null (nil? (as 'SYMBOL ')) -- true @@ -218,7 +220,7 @@ (as 'BOOL 1.0) -- true ;; F64 → BOOL (as 'BOOL 0.0) -- false ;; F64 → BOOL (zero) (as 'BOOL "hi") -- true ;; STR → BOOL (non-empty) -(nil? (as 'BOOL "")) -- true +(nil? (as 'BOOL "")) -- false ;; --- Cast to STR --- (as 'STR "hi") -- "hi" ;; already STR @@ -1337,10 +1339,6 @@ ;; ═════════════════════════════════════════════════════════════════════ ;; UNREACHABLE BRANCHES (documented): ;; -;; Line 68: RAY_F32 case in null_literal_str — F32 typed null atom is -;; not directly constructible from RFL syntax. No `0Ne` parser literal -;; exists; (as 'F32 ...) is not a valid cast target. -;; ;; Lines 84, 351-355: Lazy materialization paths — RFL-visible APIs ;; always return materialized values by the time they reach println ;; or resolve. Lazy handles are internal to the query engine. diff --git a/test/rfl/ops/enlist_numeric_admission.rfl b/test/rfl/ops/enlist_numeric_admission.rfl new file mode 100644 index 000000000..a0177659f --- /dev/null +++ b/test/rfl/ops/enlist_numeric_admission.rfl @@ -0,0 +1,30 @@ +;; I64/F64 presence does not authorize interpreting other kinds as numbers. +(type (enlist 1 'a 1.5)) -- 'LIST +(at (enlist 1 'a 1.5) 1) -- 'a +(type (enlist 1 2024.01.01 1.5)) -- 'LIST +(at (enlist 1 2024.01.01 1.5) 1) -- 2024.01.01 +(type (enlist 1 true 1.5)) -- 'LIST +(at (enlist 1 true 1.5) 1) -- true +(type (enlist 1 "s" 1.5)) -- 'LIST +(at (enlist 1 "s" 1.5) 1) -- "s" +(type (enlist -1i 2 1.5)) -- 'LIST +(type (at (enlist -1i 2 1.5) 0)) -- 'i32 +(at (enlist -1i 2 1.5) 0) -- -1i +(type (enlist -1h 2 1.5)) -- 'LIST +(type (at (enlist -1h 2 1.5) 0)) -- 'i16 +(at (enlist -1h 2 1.5) 0) -- -1h + +;; Containers and typed nulls also stay boxed; preserve the nested value. +(type (enlist 1 [2 3] 1.5)) -- 'LIST +(at (enlist 1 [2 3] 1.5) 1) -- [2 3] +(type (enlist 1 0Ni 1.5)) -- 'LIST +(type (at (enlist 1 0Ni 1.5) 1)) -- 'i32 +(nil? (at (enlist 1 0Ni 1.5) 1)) -- true + +;; Existing numeric promotion, nulls, and homogeneous cases are unchanged. +(enlist 1 2.5 -3) -- [1.0 2.5 -3.0] +(type (enlist 1 2.5 -3)) -- 'F64 +(enlist 1 0Nl 3.0) -- [1.0 0Nf 3.0] +(enlist 1 2 3) -- [1 2 3] +(enlist -1i 2i) -- [-1i 2i] +(count (enlist)) -- 0 diff --git a/test/rfl/ops/filter.rfl b/test/rfl/ops/filter.rfl index 1649a148d..b9f2e2e57 100644 --- a/test/rfl/ops/filter.rfl +++ b/test/rfl/ops/filter.rfl @@ -44,14 +44,13 @@ ;; AND / OR / NOT composites (count (select {from: T where: (and (> i 3) (< i 8))})) -- 4 (sum (at (select {from: T where: (and (> i 3) (< i 8))}) 'i)) -- 22 -;; B3 Part 2 in-query collision rule: a literal `'col` that names a -;; from-table column resolves to that column. `'a` and `'c` name no column -;; of T, so they stay literal symbols. `'b` DOES name a column (the bool -;; column `b`), so `(== s 'b)` compares the SYM column `s` against the BOOL -;; column `b` — those never compare equal, contributing 0 rows. The OR thus -;; reduces to its `(== s 'a)` arm: rows where `s == 'a` → count 4, sum(i) 22. -(count (select {from: T where: (or (== s 'a) (== s 'b))})) -- 4 -(sum (at (select {from: T where: (or (== s 'a) (== s 'b))}) 'i)) -- 22 +;; A tick naming an existing column resolves to that column. Here b is +;; BOOL, so this mixed SYM/BOOL comparison must report TYPE, not compare IDs. +(count (select {from: T where: (or (== s 'a) (== s 'b))})) !- type +(sum (at (select {from: T where: (or (== s 'a) (== s 'b))}) 'i)) !- type +;; Explicit quote keeps the intended two-symbol OR filter and its row oracle. +(count (select {from: T where: (or (== s (quote a)) (== s (quote b)))})) -- 7 +(sum (at (select {from: T where: (or (== s (quote a)) (== s (quote b)))}) 'i)) -- 37 (count (select {from: T where: (not (== s 'c))})) -- 7 (sum (at (select {from: T where: (not (== s 'c))}) 'i)) -- 37 (count (select {from: T where: (and (== s 'a) (> i 5))})) -- 2 diff --git a/test/rfl/ops/i64_exact_ordering.rfl b/test/rfl/ops/i64_exact_ordering.rfl index 8b2fecdcf..df291ebeb 100644 --- a/test/rfl/ops/i64_exact_ordering.rfl +++ b/test/rfl/ops/i64_exact_ordering.rfl @@ -55,7 +55,7 @@ (> (take Q 3) (as 'i32 [1 2 3])) -- [true true true] ;; ── timestamps: nanosecond arithmetic and ordering ────────────────────────── -(- D C) -- [1000000 1000000 1000000] +(- D C) -- [0D00:00:00.001 0D00:00:00.001 0D00:00:00.001] (> (take (+ t0 2) 3) (take (+ t0 1) 3)) -- [true true true] (== (take (+ t0 1) 3) (take (+ t0 1) 3)) -- [true true true] (!= (take (+ t0 2) 3) (take (+ t0 1) 3)) -- [true true true] @@ -67,7 +67,7 @@ (> R P62) -- [false false true] (+ R 0) -- R (max R) -- (+ P62 1) -(- (+ t0 1000000) t0) -- 1000000 +(- (+ t0 1000000) t0) -- 0D00:00:00.001 ;; ── nulls and floats through the same arms are unchanged ──────────────────── (+ [1 0N 3] [1 1 1]) -- [2 0N 4] diff --git a/test/rfl/ops/pivot_coverage.rfl b/test/rfl/ops/pivot_coverage.rfl index 29695a4d6..cc6433b99 100644 --- a/test/rfl/ops/pivot_coverage.rfl +++ b/test/rfl/ops/pivot_coverage.rfl @@ -861,7 +861,7 @@ RTimedead -- [09:30:00.000 11:00:00.000] ;; widened the way the out-of-band integer and float sentinels had to be. (set TN (table [c s] (list [true false true] (as 'SYM ["a" "b" "c"])))) (type (at (select {r: (if c s ') from: TN}) 'r)) -- 'SYM -(format "%s" (at (select {r: (if c s ') from: TN}) 'r)) -- "[a null c]s" +(format "%s" (at (select {r: (if c s ') from: TN}) 'r)) -- "[a ' c]s" ;; ── a parted column answers as the same data flattened does ──────────── ;; Its type is carried in a wrapper that no promotion ladder knows, so the diff --git a/test/rfl/opt/const_fold.rfl b/test/rfl/opt/const_fold.rfl index ac12af353..9d2ab3ad7 100644 --- a/test/rfl/opt/const_fold.rfl +++ b/test/rfl/opt/const_fold.rfl @@ -143,9 +143,11 @@ ;; FLOOR(i64) in SELECT — line 365: is_f64=false (at (select {c: (floor 2) from: Tbase}) 'c) -- [2 2 2] -;; NEG(u8) in SELECT — atom_to_numeric case -RAY_U8 (line 290, falls through to U8/BOOL code) -;; 0x42 = 66 (U8 hex literal), neg → -66 (stored as i64 after fold) -(at (select {c: (neg 0x42) from: Tbase}) 'c) -- [-66 -66 -66] +;; SQRT(u8) in SELECT — atom_to_numeric case -RAY_U8 (falls through to U8/BOOL code) +(at (select {c: (sqrt 0x04) from: Tbase}) 'c) -- [2.0 2.0 2.0] +;; NEG(u8) is not folded: `neg` rejects U8 as the builtin does (#854) +(neg 0x42) !- type +(select {c: (neg 0x42) from: Tbase}) !- type ;; ==================================================================== ;; Section 3: fold_binary_const — I64 arithmetic edge cases diff --git a/test/rfl/query/affine_sum_topn.rfl b/test/rfl/query/affine_sum_topn.rfl new file mode 100644 index 000000000..8e04472ba --- /dev/null +++ b/test/rfl/query/affine_sum_topn.rfl @@ -0,0 +1,11 @@ +;; A grouped take must rank by the emitted SUM, including the per-row bias. +;; The compound SYM key over two partitions takes the radix top-N route. +(.sys.exec "rm -rf /tmp/rfl_affine_sum_topn") +(set K (map (fn [i] (if (< i 3000) (% i 50) (% (* i 7919) 2000))) (til 8000))) +(set W (table [s w v] (list (at (as 'SYMBOL (map (fn [j] (format "w%" j)) (til 2000))) K) (as 'I64 (map (fn [k] (if (< k 50) 0 (% k 13))) K)) (til 8000)))) +(.db.splayed.set "/tmp/rfl_affine_sum_topn/2024.01.01/t/" (take W 4000) "/tmp/rfl_affine_sum_topn/.sym") +(.db.splayed.set "/tmp/rfl_affine_sum_topn/2024.01.02/t/" (drop W 4000) "/tmp/rfl_affine_sum_topn/.sym") +(set P (.db.parted.get "/tmp/rfl_affine_sum_topn" 't)) +(at (select {m: (sum (+ w 100)) from: P by: {s: s z: (% v 1) t: s} desc: m take: 20}) 'm) -- (take 6300 20) +(at (take (select {m: (sum (+ w 100)) from: P by: {s: s z: (% v 1) t: s} desc: m take: 1025}) 20) 'm) -- (take 6300 20) +(.sys.exec "rm -rf /tmp/rfl_affine_sum_topn") diff --git a/test/rfl/query/binary_temporal_arith.rfl b/test/rfl/query/binary_temporal_arith.rfl new file mode 100644 index 000000000..9ff835bc7 --- /dev/null +++ b/test/rfl/query/binary_temporal_arith.rfl @@ -0,0 +1,174 @@ +;; @requires: posix (splayed / parted fixtures under /tmp, cleaned through a POSIX shell via .sys.exec) +;; Binary arithmetic with a temporal operand inside a query follows the +;; builtin, not the DAG kernel's raw counts. +;; +;; dag_temporal_arith_needs_eval (src/ops/query.c) declined only + - * on a +;; DATE / TIME / TIMESTAMP operand. `/`, `div` and `%` were lowered to the +;; DAG, which saw day / millisecond / nanosecond counts: `(/ d 2)` came back +;; as F64 4383.0 and `(div d 2)` as I64 4383 where the builtins raise +;; `cannot divide date by i64` and `cannot div date by i64`, and `(% d 2)` +;; came back as I64 [0 1 0] where the builtin keeps DATE. Every arithmetic +;; verb the DAG lowers now declines a temporal operand and leaves the +;; builtin to the evaluator: select's fallback applies it row by row, an +;; ordinary update to the whole columns. The exception is `%` of a temporal +;; column by a non-null, nonzero integer literal (dag_temporal_mod): the MOD +;; kernel computes the builtin's floor modulo on the raw counts and the +;; result is cast back to the column's type. + +(set F (table [d t p i j f k] (list [2024.01.01 2024.01.02 2024.01.03] [00:00:01.000 00:00:02.000 00:00:03.000] [2024.01.01D00:00:00.000000001 2024.01.02D00:00:00.000000002 2024.01.03D00:00:00.000000003] [1 2 3] (as 'I32 [1 2 3]) [1.5 2.0 2.5] [1 1 2]))) + +;; ── the builtins are the oracle ───────────────────────────────────────────── +(/ (at F 'd) 2) !- type +(div (at F 'd) 2) !- type +(% (at F 'd) 2) -- [2000.01.01 2000.01.02 2000.01.01] + +;; ── `/`: rejected with any temporal operand, either side ──────────────────── +(select {x: (/ d 2) from: F}) !- type +(select {x: (/ d 2i) from: F}) !- type +(select {x: (/ d 2.0) from: F}) !- type +(select {x: (/ d i) from: F}) !- type +(select {x: (/ d j) from: F}) !- type +(select {x: (/ d f) from: F}) !- type +(select {x: (/ d d) from: F}) !- type +(select {x: (/ t 2) from: F}) !- type +(select {x: (/ t t) from: F}) !- type +(select {x: (/ p i) from: F}) !- type +(select {x: (/ p p) from: F}) !- type +(select {x: (/ 2 d) from: F}) !- type +(select {x: (/ i t) from: F}) !- type +(select {x: (/ f p) from: F}) !- type +(select {x: (/ 2024.01.02 i) from: F}) !- type + +;; ── `div`: rejected with any temporal operand, either side ────────────────── +(select {x: (div d 2) from: F}) !- type +(select {x: (div d i) from: F}) !- type +(select {x: (div d j) from: F}) !- type +(select {x: (div d f) from: F}) !- type +(select {x: (div d d) from: F}) !- type +(select {x: (div t 2) from: F}) !- type +(select {x: (div t 2.0) from: F}) !- type +(select {x: (div p 2) from: F}) !- type +(select {x: (div p t) from: F}) !- type +(select {x: (div 2 d) from: F}) !- type +(select {x: (div j t) from: F}) !- type +(select {x: (div f p) from: F}) !- type +(select {x: (div 00:00:02.000 i) from: F}) !- type + +;; ── `%`: temporal by a number keeps the temporal type ─────────────────────── +(type (at (select {x: (% d 2) from: F}) 'x)) -- 'DATE +(at (select {x: (% d 2) from: F}) 'x) -- [2000.01.01 2000.01.02 2000.01.01] +(at (select {x: (% d 2i) from: F}) 'x) -- [2000.01.01 2000.01.02 2000.01.01] +(at (select {x: (% d i) from: F}) 'x) -- [2000.01.01 2000.01.02 2000.01.03] +(at (select {x: (% d j) from: F}) 'x) -- (% (at F 'd) (at F 'j)) +(at (select {x: (% d 2.0) from: F}) 'x) -- (% (at F 'd) 2.0) +(at (select {x: (% d f) from: F}) 'x) -- (% (at F 'd) (at F 'f)) +(type (at (select {x: (% t 2) from: F}) 'x)) -- 'TIME +(at (select {x: (% t 7) from: F}) 'x) -- (% (at F 't) 7) +(at (select {x: (% t i) from: F}) 'x) -- (% (at F 't) (at F 'i)) +(type (at (select {x: (% p 2) from: F}) 'x)) -- 'TIMESTAMP +(at (select {x: (% p 2) from: F}) 'x) -- [2000.01.01D00:00:00.000000001 2000.01.01D00:00:00.000000000 2000.01.01D00:00:00.000000001] +(at (select {x: (% p j) from: F}) 'x) -- (% (at F 'p) (at F 'j)) +(at (select {x: (% 2024.01.02 i) from: F}) 'x) -- (% 2024.01.02 (at F 'i)) + +;; ── `%`: rejected with a temporal divisor or two temporals ────────────────── +(select {x: (% 2 d) from: F}) !- type +(select {x: (% i t) from: F}) !- type +(select {x: (% f p) from: F}) !- type +(select {x: (% d d) from: F}) !- type +(select {x: (% t t) from: F}) !- type +(select {x: (% p d) from: F}) !- type + +;; ── `pow` keeps rejecting temporals; + - * keep their meaning ─────────────── +(select {x: (pow d 2) from: F}) !- type +(select {x: (pow 2 t) from: F}) !- type +(at (select {x: (+ d 1) from: F}) 'x) -- [2024.01.02 2024.01.03 2024.01.04] +(at (select {x: (- d 2024.01.01) from: F}) 'x) -- (- (at F 'd) 2024.01.01) +(at (select {x: (* t 2) from: F}) 'x) -- (* (at F 't) 2) + +;; ── where: / by: / update ─────────────────────────────────────────────────── +(select {i: i from: F where: (> (/ d 2) 0)}) !- type +(select {i: i from: F where: (> (div t 2) 0)}) !- type +(at (select {i: i from: F where: (== (% d 2) 2000.01.02)}) 'i) -- [2] +(at (select {n: (count i) from: F by: {x: (% d 2)}}) 'x) -- [2000.01.01 2000.01.02] +(type (at (select {n: (count i) from: F by: {x: (% d 2)}}) 'x)) -- 'DATE +(select {n: (count i) from: F by: {x: (div d 2)}}) !- type +(at (select {x: (% p 2) from: F by: k}) 'x) -- (list [2000.01.01D00:00:00.000000001 2000.01.01D00:00:00.000000000] [2000.01.01D00:00:00.000000001]) +(at (update {x: (% d 2) from: F}) 'x) -- [2000.01.01 2000.01.02 2000.01.01] +(update {x: (/ d 2) from: F}) !- type +(update {x: (div p 2) from: F}) !- type + +;; ── `%` by an integer literal in the DAG: the builtin's values and nulls ───── +(set N (table [d t p z] (list [2024.01.01 0Nd 1999.12.30 1900.01.01] [00:00:01.003 0Nt 00:00:00.000 23:59:59.999] [2024.01.01D00:00:00.000000001 0Np 1990.01.01D00:00:00.000000007 1710.01.01D00:00:00.000000003] [0 3 -3 0]))) +(% (at N 'd) -3) -- [2000.01.01 0Nd 1999.12.30 1999.12.30] +(at (select {x: (% d -3) from: N}) 'x) -- [2000.01.01 0Nd 1999.12.30 1999.12.30] +(at (select {x: (% d 7) from: N}) 'x) -- (% (at N 'd) 7) +(at (select {x: (% d 2h) from: N}) 'x) -- (% (at N 'd) 2h) +(at (select {x: (% d 5000000000) from: N}) 'x) -- (% (at N 'd) 5000000000) +(at (select {x: (% t -7i) from: N}) 'x) -- (% (at N 't) -7i) +(at (select {x: (% t 86400000) from: N}) 'x) -- (% (at N 't) 86400000) +(at (select {x: (% p 1000000007) from: N}) 'x) -- (% (at N 'p) 1000000007) +(at (select {x: (% p -5000000000) from: N}) 'x) -- (% (at N 'p) -5000000000) +(at (select {x: (% p true) from: N}) 'x) -- (% (at N 'p) true) +(at (update {x: (% p -3) from: N}) 'x) -- (% (at N 'p) -3) +(at (select {k: z from: N where: (== (% d -3) 1999.12.30)}) 'k) -- [-3 0] +;; a zero or null divisor is a typed null, over a column without nulls too +(set Z (table [d t p z] (list [2024.01.01 2024.01.02] [00:00:01.000 00:00:02.000] [2024.01.01D00:00:00.000000001 2024.01.02D00:00:00.000000002] [0 3]))) +(at (select {x: (% d 0) from: Z}) 'x) -- [0Nd 0Nd] +(at (select {x: (% t 0i) from: Z}) 'x) -- [0Nt 0Nt] +(at (select {x: (% p false) from: Z}) 'x) -- [0Np 0Np] +(at (select {x: (% d 0N) from: Z}) 'x) -- [0Nd 0Nd] +(at (update {x: (% p 0) from: Z}) 'x) -- [0Np 0Np] +(at (select {x: (% d z) from: Z}) 'x) -- (% (at Z 'd) (at Z 'z)) +(at (select {x: (% p z) from: Z}) 'x) -- (% (at Z 'p) (at Z 'z)) + +;; ── no rows: the builtin's typed empty result, not an empty LIST ──────────── +(set E (table [d t p i f] (list (as 'DATE []) (as 'TIME []) (as 'TIMESTAMP []) (as 'I64 []) (as 'F64 [])))) +(type (% (at E 'd) 2)) -- 'DATE +(type (at (select {x: (% d 2) from: E}) 'x)) -- 'DATE +(type (at (select {x: (% t 2) from: E}) 'x)) -- 'TIME +(type (at (select {x: (% p 2) from: E}) 'x)) -- 'TIMESTAMP +(type (at (select {x: (% d 2.0) from: E}) 'x)) -- 'DATE +(type (at (select {x: (% t i) from: E}) 'x)) -- 'TIME +(type (at (select {x: (% p f) from: E}) 'x)) -- 'TIMESTAMP +(type (at (update {x: (% d 2) from: E}) 'x)) -- 'DATE +(type (at (update {x: (% t 2.0) from: E}) 'x)) -- 'TIME +(type (at (select {x: (% d 2) from: F where: (> i 5)}) 'x)) -- 'DATE +(type (at (select {x: (% t 2.0) from: F where: (> i 5)}) 'x)) -- 'TIME +(type (at (select {x: (% p j) from: F where: (> i 5)}) 'x)) -- 'TIMESTAMP +(type (at (select {x: (+ d 1) from: E}) 'x)) -- 'DATE +(type (at (select {x: (- d d) from: E}) 'x)) -- 'I32 +(type (at (select {x: (* t 2) from: E}) 'x)) -- 'TIME +;; a lexical local shadows the column of its name, over no rows as over +;; rows: the empty-result probe must not read the column for it +(set _shadow (fn [d tb] (at (select {x: (% d 2) from: tb}) 'x))) +(_shadow 7 (table [d] (list [2024.01.01 2024.01.02]))) -- [1 1] +(type (_shadow 7 E)) -- 'I64 + +;; ── splayed table ─────────────────────────────────────────────────────────── +(.sys.exec "rm -rf /tmp/rfl_binary_temporal_arith") +(.db.splayed.set "/tmp/rfl_binary_temporal_arith/sp/t/" (table [a d] (list [1 2 3] [2024.01.05 2024.01.06 2024.01.07])) "/tmp/rfl_binary_temporal_arith/sp/.sym") +(set _S (.db.splayed.get "/tmp/rfl_binary_temporal_arith/sp/t/" "/tmp/rfl_binary_temporal_arith/sp/.sym")) +(select {x: (/ d 2) from: _S}) !- type +(select {x: (div d a) from: _S}) !- type +(at (select {x: (% d 2) from: _S}) 'x) -- (% (at _S 'd) 2) +(at (select {x: (% d 2) from: _S}) 'x) -- [2000.01.01 2000.01.02 2000.01.01] +(at (update {x: (% d 2) from: _S}) 'x) -- [2000.01.01 2000.01.02 2000.01.01] + +;; ── parted table: the DATE partition key and a stored DATE column ─────────── +(.db.splayed.set "/tmp/rfl_binary_temporal_arith/db/2024.01.01/t/" (table [a d] (list [1 2] [2024.01.05 2024.01.06])) "/tmp/rfl_binary_temporal_arith/db/.sym") +(.db.splayed.set "/tmp/rfl_binary_temporal_arith/db/2024.01.02/t/" (table [a d] (list [3 4 5] [2024.01.07 2024.01.08 2024.01.09])) "/tmp/rfl_binary_temporal_arith/db/.sym") +(set _P (.db.parted.get "/tmp/rfl_binary_temporal_arith/db/" 't)) +(% (at _P 'date) 2) -- [2000.01.01 2000.01.01 2000.01.02 2000.01.02 2000.01.02] +(at (select {x: (% date 2) from: _P}) 'x) -- [2000.01.01 2000.01.01 2000.01.02 2000.01.02 2000.01.02] +(select {x: (/ date 2) from: _P}) !- type +(select {x: (div date 2) from: _P}) !- type +(select {x: (pow date 2) from: _P}) !- type +(at (select {x: (% d 2) from: _P}) 'x) -- [2000.01.01 2000.01.02 2000.01.01 2000.01.02 2000.01.01] +(select {x: (/ d 2) from: _P}) !- type +(select {x: (div d a) from: _P}) !- type +(at (select {x: (% date 2) from: _P where: (> a 1)}) 'x) -- [2000.01.01 2000.01.02 2000.01.02 2000.01.02] +(at (select {n: (count a) from: _P by: {x: (% date 2)}}) 'x) -- [2000.01.01 2000.01.02] +(at (select {n: (count a) from: _P by: {x: (% date 0)}}) 'x) -- [0Nd] +(at (update {x: (% date 0) from: _P}) 'x) -- [0Nd 0Nd 0Nd 0Nd 0Nd] +(select {a: a from: _P where: (> (/ date 2) 0)}) !- type +(.sys.exec "rm -rf /tmp/rfl_binary_temporal_arith") diff --git a/test/rfl/query/concat_helper_consistency.rfl b/test/rfl/query/concat_helper_consistency.rfl index 689b66987..a3de9474e 100644 --- a/test/rfl/query/concat_helper_consistency.rfl +++ b/test/rfl/query/concat_helper_consistency.rfl @@ -177,7 +177,7 @@ G -- 700 ;; it read position 0's flag), a cell at position 64 is still a cell (an ;; empty cell is empty text, the rows where: keeps included), and a STR cell ;; there still makes the result STR -(at (select {r: (concat (first s) 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z ') from: TC}) 'r) -- [null] +(at (select {r: (concat (first s) 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z ') from: TC}) 'r) -- ['] (at (select {r: (concat 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z (first s)) from: TC}) 'r) -- [zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza] (at (select {r: (concat 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z (first s)) from: (select {from: TC where: (== x 2)})}) 'r) -- [zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz] (at (select {r: (concat 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z 'z (first s)) from: TS}) 'r) -- ["zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"] diff --git a/test/rfl/query/count_distinct_where_splayed.rfl b/test/rfl/query/count_distinct_where_splayed.rfl new file mode 100644 index 000000000..6d6889262 --- /dev/null +++ b/test/rfl/query/count_distinct_where_splayed.rfl @@ -0,0 +1,16 @@ +;; @requires: posix +;; Grouped count-distinct under a where: on a splayed (mapped) table. The +;; route's where-sample gates the table's zones first; when the gate rules +;; out no chunk it dropped its chunk list and then dropped it again on the +;; way out, and the allocator handed the freed block out twice (#898). The +;; answer must match the in-memory table's. +(.sys.exec "rm -rf /tmp/rfl_cd_where_splayed") +(set T (table [k v] (list (% (til 80000) 7) (% (* (til 80000) 13) 1000)))) +(.db.splayed.set "/tmp/rfl_cd_where_splayed/t/" T) +(set U (.db.splayed.get "/tmp/rfl_cd_where_splayed/t/")) +;; every zone holds a survivor: the gate rules nothing out +(count (select {c: (count (distinct v)) by: k from: U where: (> v 100)})) -- 7 +(select {c: (count (distinct v)) by: k from: U where: (> v 100)}) -- (select {c: (count (distinct v)) by: k from: T where: (> v 100)}) +;; A second row-selection predicate agrees too; zone-elimination coverage is not claimed. +(select {c: (count (distinct v)) by: k from: U where: (< v 50)}) -- (select {c: (count (distinct v)) by: k from: T where: (< v 50)}) +(.sys.exec "rm -rf /tmp/rfl_cd_where_splayed") diff --git a/test/rfl/query/eval_fallback_parted.rfl b/test/rfl/query/eval_fallback_parted.rfl index a4c4b8265..5867c3345 100644 --- a/test/rfl/query/eval_fallback_parted.rfl +++ b/test/rfl/query/eval_fallback_parted.rfl @@ -27,4 +27,83 @@ (at (select {str: str x: (+ d 1) from: P}) 'str) -- (list "a" "" "ccc" "dd" "a" "" "ccc" "dd") ;; with a where: clause (at (select {i: i x: (+ d 1) from: P where: (> i 2)}) 'i) -- [3 4 3 4] + +;; ─── arithmetic on the partition key itself ───────────────────────────────── +;; The key scans as the MAPCOMMON wrapper, which named no value type to the +;; planner's type guards: `(+ date 1)` ran as raw integer arithmetic and came +;; back as day counts (8768, not 2024.01.03), `(in (+ date 0) [..])` compared +;; those against a DATE set and kept no row, and the arithmetic on a SYM key +;; added to interned ids. Oracle: the same select over a flat copy. +(set F (select {from: P where: (> i 0)})) +(at (select {i: i from: P where: (in (+ date 0) [2024.01.02])}) 'i) -- [1 2 3 4] +(at (select {i: i from: P where: (in (+ date 0) [2024.01.02])}) 'i) -- (at (select {i: i from: F where: (in (+ date 0) [2024.01.02])}) 'i) +(at (select {i: i from: P where: (in (+ date 1) [2024.01.02])}) 'i) -- [1 2 3 4] +(at (select {i: i from: P where: (not (in (- date 1) [2023.12.31]))}) 'i) -- [1 2 3 4] +(at (select {i: i from: P where: (and (> i 2) (in (+ date 0) [2024.01.01]))}) 'i) -- [3 4] +(count (select {i: i from: P where: (in (+ date 0) [2024.01.05])})) -- 0 +(at (select {c: (count i) from: P where: (in (+ date 0) [2024.01.02])}) 'c) -- [4] +(type (at (select {c: (count i) by: {m: (+ date 1)} from: P}) 'm)) -- 'DATE +(at (select {c: (count i) by: {m: (+ date 1)} from: P}) 'm) -- [2024.01.02 2024.01.03] +(at (select {c: (count i) by: {m: (+ date 1)} from: P}) 'm) -- (at (select {c: (count i) by: {m: (+ date 1)} from: F}) 'm) +(at (select {c: (count i) by: {m: (+ date 1)} from: P where: (> i 2)}) 'c) -- [2 2] +(at (select {c: (count i) by: {m: (- date 1) n: name} from: P where: (> i 3)}) 'm) -- [2023.12.31 2024.01.01] +(at (select {x: (+ date 1) from: P}) 'x) -- (at (select {x: (+ date 1) from: F}) 'x) +(at (select {m: (max (+ date 1)) from: P}) 'm) -- [2024.01.03] +;; A where: the planner declines is evaluated over the columns it reads, +;; flattened: one read through a quoted symbol (the column inside a query) +;; too, and every column when it calls a helper the planner does not +;; inline, whose reads it does not show. Both raised `cannot add ? and i64`. +(at (select {i: i from: P where: (in (+ 'date 0) [2024.01.02])}) 'i) -- [1 2 3 4] +(at (select {i: i from: P where: (in (+ 'date 0) [2024.01.02])}) 'i) -- (at (select {i: i from: F where: (in (+ 'date 0) [2024.01.02])}) 'i) +(set gdx (fn [x] (set gdq 1) (+ date x))) +(at (select {i: i from: P where: (== (gdx 1) 2024.01.03)}) 'i) -- [1 2 3 4] +(at (select {i: i from: P where: (== (gdx 1) 2024.01.03)}) 'i) -- (at (select {i: i from: F where: (== (gdx 1) 2024.01.03)}) 'i) +;; The key's value type guards unary ops, aggregate admission and `and` +;; too. The wrapper holds one value per partition, which `neg`/`abs` read +;; as the rows (dates came back), and `sum` folded the day counts. A unary +;; op on the key is evaluated, as the builtin over the key's values; `sum` +;; rejects a DATE key as it rejects a flat DATE column. +(select {d: (neg date) from: P}) !- type +(select {d: (abs date) from: P}) !- type +(neg (at F 'date)) !- type +(select {c: (sum date) from: P}) !- type +(select {c: (sum date) from: F}) !- type +(select {c: (sum date) by: i from: P}) !- type +(select {c: (sum date) by: i from: F}) !- type +(select {c: (+ (sum date) 0) from: P}) !- type +(select {c: (and date (> i 0)) from: P}) !- type +(select {c: (and date (> i 0)) from: F}) !- type +(at (select {d: (min date) from: P}) 'd) -- (at (select {d: (min date) from: F}) 'd) +(at (select {d: (neg date) from: F}) 'd) !- type +(at (select {d: (abs date) from: F}) 'd) !- type (.sys.exec "rm -rf /tmp/rfl_evalfb_parted") + +;; An integer key keeps its I64 lane; a partition with no rows takes part. +(.sys.exec "rm -rf /tmp/rfl_evalfb_parted_int") +(.db.splayed.set "/tmp/rfl_evalfb_parted_int/1/t/" (table [i] (list [1 2]))) +(.db.splayed.set "/tmp/rfl_evalfb_parted_int/2/t/" (table [i] (list (take [1] 0)))) +(.db.splayed.set "/tmp/rfl_evalfb_parted_int/3/t/" (table [i] (list [3 4 5]))) +(set PI (.db.parted.get "/tmp/rfl_evalfb_parted_int/" 't)) +(at (select {i: i from: PI where: (in (+ part 0) [3])}) 'i) -- [3 4 5] +(at (select {i: i from: PI where: (in (* part 2) [2])}) 'i) -- [1 2] +(at (select {c: (count i) by: {m: (+ part 1)} from: PI}) 'm) -- [2 4] +(type (at (select {c: (count i) by: {m: (+ part 1)} from: PI}) 'm)) -- 'I64 +(set FI (select {from: PI where: (> i 0)})) +(at (select {d: (neg part) from: PI}) 'd) -- [-1 -1 -3 -3 -3] +(at (select {d: (neg part) from: PI}) 'd) -- (at (select {d: (neg part) from: FI}) 'd) +(at (select {d: (abs (neg part)) from: PI}) 'd) -- (at (select {d: (abs (neg part)) from: FI}) 'd) +(.sys.exec "rm -rf /tmp/rfl_evalfb_parted_int") + +;; A SYM key has no arithmetic, as over a flat SYM column. +(.sys.exec "rm -rf /tmp/rfl_evalfb_parted_sym") +(.db.splayed.set "/tmp/rfl_evalfb_parted_sym/1.2.3/t/" (table [i] (list [1 2]))) +(.db.splayed.set "/tmp/rfl_evalfb_parted_sym/4.5.6/t/" (table [i] (list [3]))) +(set PS (.db.parted.get "/tmp/rfl_evalfb_parted_sym/" 't)) +(select {x: (+ part 1) from: PS}) !- type +(select {i: i from: PS where: (in (+ part 1) [2])}) !- type +(select {c: (count i) by: {m: (+ part 1)} from: PS}) !- type +;; nor a sum: it summed the interned ids +(select {c: (sum part) from: PS}) !- type +(select {c: (sum part) from: (select {from: PS where: (> i 0)})}) !- type +(select {c: (sum part) by: i from: PS}) !- type +(.sys.exec "rm -rf /tmp/rfl_evalfb_parted_sym") diff --git a/test/rfl/query/fused_zero_divisor.rfl b/test/rfl/query/fused_zero_divisor.rfl new file mode 100644 index 000000000..735fdb9a1 --- /dev/null +++ b/test/rfl/query/fused_zero_divisor.rfl @@ -0,0 +1,144 @@ +;; @requires: posix (splayed / parted fixtures under /tmp, cleaned through a POSIX shell via .sys.exec) +;; A zero divisor gives a typed null in a query, as in the builtin. +;; +;; A select / update / where / by expression over null-free columns +;; compiles to the fused expression kernel with every instruction plain +;; (null_aware = 0). The plain I64 DIV / IDIV / MOD kernels wrote 0 for a +;; zero divisor, so `(select {x: (% k 0) from: T})` gave [0 0] where +;; `(% (at T 'k) 0)` gives [0Nl 0Nl]. They now write the null sentinel +;; (the destination is already nullable, expr_op_generates_null), and the +;; output scan sets HAS_NULLS, so nil? finds the nulls and sum / avg skip +;; them. The typed executor covers I16, U8, BOOL, F64 and F32 divisors +;; (it covered I64 / I32 only); the I16-to-I64 div kernel writes nulls in +;; its producer loop. Constant folding no longer folds a zero divisor to 0 +;; (or x/0 to inf). Where the builtin's result is U8, or `%` takes a U8 +;; divisor, there is no null: the +;; result stays 0. + +(set T (table [k i h u b f e g w] (list [5 7 -3 9 4 -8] (as 'I32 [2 0 5 0 3 1]) (as 'I16 [2 0 5 0 3 1]) (as 'U8 [2 0 5 0 3 1]) [true false true false true true] [2.0 0.0 5.0 0.0 3.0 1.0] (as 'F32 [2.0 0.0 5.0 0.0 3.0 1.0]) [0 1 0 1 0 1] [1 1 0 1 1 1]))) + +;; ── the reported cases ────────────────────────────────────────────────────── +(% (at T 'k) 0) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(at (select {x: (% k 0) from: T}) 'x) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(% 2 (at T 'b)) -- [0 0Nl 0 0Nl 0 0] +(at (select {x: (% 2 b) from: T}) 'x) -- [0 0Nl 0 0Nl 0 0] + +;; ── `%`, `div`, `/` by every divisor type, against the builtin ───────────── +(at (select {x: (% k i) from: T}) 'x) -- [1 0Nl 2 0Nl 1 0] +(at (select {x: (% k h) from: T}) 'x) -- [1 0Nl 2 0Nl 1 0] +(at (select {x: (% k b) from: T}) 'x) -- (% (at T 'k) (at T 'b)) +(at (select {x: (% k f) from: T}) 'x) -- (% (at T 'k) (at T 'f)) +(at (select {x: (% k e) from: T}) 'x) -- (% (at T 'k) (at T 'e)) +(at (select {x: (div k 0) from: T}) 'x) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(at (select {x: (div k i) from: T}) 'x) -- [2 0Nl -1 0Nl 1 -8] +(at (select {x: (div k i) from: T}) 'x) -- (div (at T 'k) (at T 'i)) +(at (select {x: (div k h) from: T}) 'x) -- (div (at T 'k) (at T 'h)) +(at (select {x: (div k u) from: T}) 'x) -- [2 0Nl -1 0Nl 1 -8] +(at (select {x: (div k u) from: T}) 'x) -- (div (at T 'k) (at T 'u)) +(at (select {x: (div k b) from: T}) 'x) -- (div (at T 'k) (at T 'b)) +(at (select {x: (div k f) from: T}) 'x) -- (div (at T 'k) (at T 'f)) +(at (select {x: (div k e) from: T}) 'x) -- (div (at T 'k) (at T 'e)) +(at (select {x: (div e e) from: T}) 'x) -- [1 0Nl 1 0Nl 1 1] +(at (select {x: (/ k 0) from: T}) 'x) -- [0Nf 0Nf 0Nf 0Nf 0Nf 0Nf] +(at (select {x: (/ k i) from: T}) 'x) -- (/ (at T 'k) (at T 'i)) +(at (select {x: (/ k u) from: T}) 'x) -- (/ (at T 'k) (at T 'u)) +(at (select {x: (/ k f) from: T}) 'x) -- (/ (at T 'k) (at T 'f)) + +;; ── no null where the builtin's result has none ───────────────────────────── +(% (at T 'u) (at T 'u)) -- [0x00 0x00 0x00 0x00 0x00 0x00] +(at (select {x: (% u u) from: T}) 'x) -- [0x00 0x00 0x00 0x00 0x00 0x00] +(at (select {x: (% i u) from: T}) 'x) -- (% (at T 'i) (at T 'u)) +(at (select {x: (+ (% k u) 1) from: T}) 'x) -- [2 1 3 1 2 1] +(at (update {x: (% i u) from: T}) 'x) -- (% (at T 'i) (at T 'u)) +(% (at T 'k) 0x00) -- [0 0 0 0 0 0] +(at (select {x: (% k 0x00) from: T}) 'x) -- [0 0 0 0 0 0] + +;; ── HAS_NULLS: nil? finds the nulls, aggregates skip them ─────────────────── +(sum (nil? (at (select {x: (% k i) from: T}) 'x))) -- 2 +(at (select {n: (sum (nil? (% k i))) from: T}) 'n) -- [2] +(at (select {s: (sum (% k i)) from: T}) 's) -- [4] +(at (select {s: (sum (div k i)) from: T}) 's) -- [-6] +(at (select {s: (avg (% k i)) from: T}) 's) -- [1.0] +(at (select {s: (min (div k 0)) from: T}) 's) -- [0Nl] +(at (select {s: (sum (% k 0)) from: T}) 's) -- [0] +(at (select {x: (+ (% k i) 1) from: T}) 'x) -- [2 0Nl 3 0Nl 2 1] + +;; ── update / where / by ───────────────────────────────────────────────────── +(at (update {x: (% k i) from: T}) 'x) -- [1 0Nl 2 0Nl 1 0] +(at (update {x: (div k 0) from: T}) 'x) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(at (select {x: (% k i) from: T where: (> w 0)}) 'x) -- [1 0Nl 0Nl 1 0] +(at (select {x: k from: T where: (nil? (% k i))}) 'x) -- [7 9] +(at (select {x: k from: T where: (nil? (div k b))}) 'x) -- [7 9] +(at (select {s: (sum (% k i)) from: T by: g}) 's) -- [4 0] +(at (select {n: (sum (nil? (% k i))) from: T by: g}) 'n) -- [0 2] +(asc (at (select {n: (count g) from: T by: {x: (% k i)}}) 'x)) -- [0Nl 0 1 2] + +;; ── a literal zero folded with a literal dividend ─────────────────────────── +(at (select {x: (% 7 0) from: T}) 'x) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(at (select {x: (div 7 0) from: T}) 'x) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(at (select {x: (/ 7 0) from: T}) 'x) -- [0Nf 0Nf 0Nf 0Nf 0Nf 0Nf] +(at (select {x: (% -7 2) from: T}) 'x) -- [1 1 1 1 1 1] +(at (select {x: (% -7.5 2.0) from: T}) 'x) -- [0.5 0.5 0.5 0.5 0.5 0.5] + +;; ── parallel morsels ──────────────────────────────────────────────────────── +(set B (table [k j] (list (til 200000) (% (til 200000) 7)))) +(at (select {n: (sum (nil? (% k j))) from: B}) 'n) -- [28572] +(at (select {s: (sum (% k j)) from: B}) 's) -- (enlist (sum (% (at B 'k) (at B 'j)))) +(at (select {x: (div k j) from: B}) 'x) -- (div (at B 'k) (at B 'j)) +(set H (table [k h] (list (til 200000) (as 'I16 (% (til 200000) 7))))) +(at (select {n: (sum (nil? (div k h))) from: H}) 'n) -- [28572] +(at (select {x: (div k h) from: H}) 'x) -- (div (at H 'k) (at H 'h)) + +;; ── `%` by a U8 divisor ───────────────────────────────────────────────────── +;; A zero U8 divisor gives the builtin's 0 (U8 has no null). A length-one +;; U8 column is a scalar to the typed executor, and its zero-divisor pass +;; nulled it where an atom 0x00 gave 0. +(set Z (table [k u] (list [5] (as 'U8 [0])))) +(at (select {x: (% k u) from: Z}) 'x) -- [0] +(nil? (at (select {x: (% k u) from: Z}) 'x)) -- [false] +(at (select {n: (sum (nil? (% k u))) from: Z}) 'n) -- [0] +(at (update {x: (% k u) from: Z}) 'x) -- [0] +(set Z (table [k u] (list [-7] (as 'U8 [0])))) +(at (select {x: (% k u) from: Z}) 'x) -- (% (at Z 'k) (at Z 'u)) +(nil? (at (select {x: (% k u) from: Z}) 'x)) -- [false] +(at (select {x: k from: Z where: (nil? (% k u))}) 'x) -- (take [0] 0) +(at (update {x: (% k u) from: Z}) 'x) -- [0] +(set Z (table [h u] (list (as 'I16 [-7]) (as 'U8 [0])))) +(at (select {x: (% h u) from: Z}) 'x) -- (% (at Z 'h) (at Z 'u)) +(nil? (at (select {x: (% h u) from: Z}) 'x)) -- [false] +(at (select {n: (sum (nil? (% h u))) from: Z}) 'n) -- [0] +;; A narrow dividend takes the typed executor's I16 arm, which computed +;; bare C % ((% -7h 2) gave -1, builtin 1): floor modulo, as I32 / I64. +(set Z (table [h u] (list (as 'I16 [-7 -7]) (as 'U8 [2 2])))) +(list (at (select {x: (% h u) from: Z}) 'x) (% (at Z 'h) (at Z 'u))) -- (list (as 'I16 [1 1]) (as 'I16 [1 1])) +(set Z (table [h u] (list (as 'I16 [-7 300 5 -1]) (as 'U8 [3 7 0 4])))) +(at (select {x: (% h u) from: Z}) 'x) -- (as 'I16 [2 6 0 3]) +(at (update {x: (% h u) from: Z}) 'x) -- (as 'I16 [2 6 0 3]) +(at (select {x: (+ (% h u) 1) from: Z}) 'x) -- (as 'I16 [3 7 1 4]) +(at (select {x: (% h 0x03) from: Z}) 'x) -- (as 'I16 [2 0 2 2]) + +;; ── floor modulo in the I16 arm (xbar's lowering, I16 divisors) ───────────── +;; xbar lowers to (- x (% x b)) with floor modulo; with a U8 bucket the +;; modulo takes the typed executor. +(set X (table [h u] (list (as 'I16 [-7 300 5 9 -1]) (as 'U8 [3 7 1 2 4])))) +(at (select {x: (xbar h u) from: X}) 'x) -- (xbar (at X 'h) (at X 'u)) +(at (select {x: (xbar h u) from: X}) 'x) -- (as 'I16 [-9 294 5 8 -4]) +(at (select {x: (xbar h 0x07) from: X}) 'x) -- (xbar (at X 'h) 0x07) +(at (select {x: (% h (as 'I16 [3 3 3 3 3])) from: X}) 'x) -- (% (at X 'h) (as 'I16 [3 3 3 3 3])) +(at (select {x: (% h (as 'I16 [-3 -3 -3 -3 -3])) from: X}) 'x) -- (% (at X 'h) (as 'I16 [-3 -3 -3 -3 -3])) + +;; ── splayed and parted tables ─────────────────────────────────────────────── +(.sys.exec "rm -rf /tmp/rfl_fused_zero_divisor") +(.db.splayed.set "/tmp/rfl_fused_zero_divisor/sp/t/" T "/tmp/rfl_fused_zero_divisor/sp/.sym") +(set _S (.db.splayed.get "/tmp/rfl_fused_zero_divisor/sp/t/" "/tmp/rfl_fused_zero_divisor/sp/.sym")) +(at (select {x: (% k i) from: _S}) 'x) -- [1 0Nl 2 0Nl 1 0] +(at (select {x: (div k b) from: _S}) 'x) -- (div (at T 'k) (at T 'b)) +(at (select {n: (sum (nil? (% k 0))) from: _S}) 'n) -- [6] +(.db.splayed.set "/tmp/rfl_fused_zero_divisor/db/2024.01.01/t/" (take T 3) "/tmp/rfl_fused_zero_divisor/db/.sym") +(.db.splayed.set "/tmp/rfl_fused_zero_divisor/db/2024.01.02/t/" (take T -3) "/tmp/rfl_fused_zero_divisor/db/.sym") +(set _P (.db.parted.get "/tmp/rfl_fused_zero_divisor/db/" 't)) +(at (select {x: (% k i) from: _P}) 'x) -- [1 0Nl 2 0Nl 1 0] +(at (select {x: (div k 0) from: _P}) 'x) -- [0Nl 0Nl 0Nl 0Nl 0Nl 0Nl] +(at (select {n: (sum (nil? (div k i))) from: _P}) 'n) -- [2] +(at (select {s: (sum (% k i)) from: _P by: g}) 's) -- [4 0] +(.sys.exec "rm -rf /tmp/rfl_fused_zero_divisor") diff --git a/test/rfl/query/group_f32_key.rfl b/test/rfl/query/group_f32_key.rfl index c1ba25e96..b5f472815 100644 --- a/test/rfl/query/group_f32_key.rfl +++ b/test/rfl/query/group_f32_key.rfl @@ -10,21 +10,44 @@ (set T (select {from: (table [p s x] (list (as 'F64 (% (til N) 10)) (take ['a 'b] N) (til N))) p: (as 'F32 p) s: s x: x})) (set R (select {from: T by: p c: (count x) asc: p})) (count R) -- 10 -(at R 'p) -- (as 'F64 (til 10)) +(at R 'p) -- (as 'F32 (til 10)) (at R 'c) -- (take [10000] 10) (set Rd (select {from: T by: p n: (count (distinct x)) asc: p})) -(at Rd 'p) -- (as 'F64 (til 10)) +(at Rd 'p) -- (as 'F32 (til 10)) (at Rd 'n) -- (take [10000] 10) (set Rc (select {from: T by: [p s] c: (count x) n: (count (distinct x)) asc: [p s]})) (count Rc) -- 10 -(at Rc 'p) -- (as 'F64 (til 10)) +(at Rc 'p) -- (as 'F32 (til 10)) (at Rc 's) -- (take ['a 'b] 10) (at Rc 'c) -- (take [10000] 10) (at Rc 'n) -- (take [10000] 10) -(at (select {from: T by: [s p] c: (count x) asc: [s p]}) 'p) -- (as 'F64 [0 2 4 6 8 1 3 5 7 9]) +(at (select {from: T by: [s p] c: (count x) asc: [s p]}) 'p) -- (as 'F32 [0 2 4 6 8 1 3 5 7 9]) ;; -0.0 and +0.0 are one group on the parallel path too, and a null key its own (set Z (select {from: (table [z s x] (list (as 'F64 (% (til N) 4)) (take ['a 'b] N) (til N))) z: (as 'F32 (* (if (== z 1.0) -1.0 1.0) (if (< z 2.0) 0.0 z))) s: s x: x})) (at (select {from: Z by: z c: (count x) asc: z}) 'c) -- [50000 25000 25000] (at (select {from: Z by: [z s] c: (count x) n: (count (distinct x)) asc: [z s]}) 'n) -- [25000 25000 25000 25000] (set Q (select {from: (table [z x] (list (as 'F64 (% (til N) 3)) (til N))) z: (as 'F32 (if (== z 0.0) 0Nf z)) x: x})) (at (select {from: Q by: z c: (count x) asc: z}) 'c) -- [33334 33333 33333] +;; #765 — more than 256 distinct F32 keys: one byte per key capped the parallel +;; result at 256 groups. 1000 keys j/8 (exact in F32), 200 rows each. +(set NF 200000) +(set TF (select {from: (table [i] (list (til NF))) k: (as 'F32 (/ (as 'F64 (% i 1000)) 8.0)) g: (% i 3) v: i})) +(set RF (select {from: TF by: k c: (count v) s: (sum v) asc: k})) +(count RF) -- 1000 +(all (== (at RF 'k) (/ (as 'F64 (til 1000)) 8.0))) -- true +(at RF 'c) -- (take [200] 1000) +(at RF 's) -- (+ 19900000 (* 200 (til 1000))) +(set RC (select {from: TF by: [k g] c: (count v) asc: [k g]})) +(count RC) -- 3000 +(sum (at RC 'c)) -- 200000 +(count (select {from: (select {from: (table [i] (list (til 70000))) k: (as 'F32 (/ (as 'F64 i) 7.0)) v: i}) by: k c: (count v)})) -- 70000 +;; The group by above only reaches read_col_i64 on a 2..8-worker pool (larger +;; pools admit float keys to the v2 engine, which reads F32 natively), so on a +;; wide pool those checks pass without the F32 arm. Joins hash and compare +;; their keys through the same reader on any pool size: one byte per key made +;; 1000 distinct F32 keys collide and the join fanned out to ~40M rows. +(set JF (inner-join [k] TF RF)) +(count JF) -- 200000 +(sum (at JF 'c)) -- 40000000 +(count (left-join [k] TF RF)) -- 200000 +(count (inner-join [k g] TF RC)) -- 200000 diff --git a/test/rfl/query/literal_col_ref.rfl b/test/rfl/query/literal_col_ref.rfl index f80c95495..94e789fe5 100644 --- a/test/rfl/query/literal_col_ref.rfl +++ b/test/rfl/query/literal_col_ref.rfl @@ -41,13 +41,12 @@ ;; --- regression: count-select fast path must agree with materialised select. ;; T2 has both a SYM column `s` and a BOOL column `b`. `'b` names a column, ;; so inside the query `(== s 'b)` compares the sym column against the bool -;; column (0 matches) — the in-query collision rule. The count fast path -;; (try_count_simple_compare) and the materialised path MUST return the same -;; value; pin BOTH to 0 so a future divergence fails the suite. +;; column — the in-query collision rule, not a literal-symbol comparison. +;; SYM/BOOL is incompatible: both count-select and materialised select must +;; report the builtin type error rather than comparing symbol IDs with bits. (set T2 (table [s b] (list ['a 'b 'c 'a] [true false true false]))) -(count (select {from: T2 where: (== s 'b)})) -- 0 -(set R2 (select {from: T2 where: (== s 'b)})) -(count R2) -- 0 +(count (select {from: T2 where: (== s 'b)})) !- type +(select {from: T2 where: (== s 'b)}) !- type ;; --- regression: a literal `by:` symbol naming NO column must produce a ;; clean column-not-found error (domain) — the SAME as a bare `by: nonexistent` @@ -75,9 +74,9 @@ ;; stays the literal even when it names a column (the AST-shape boundary above). ;; T2 has SYM col `s` (['a 'b 'c 'a]) and BOOL col `b`. ;; (quote b): literal 'b -> (== s 'b-literal) matches the 'b row -> 1 -;; 'b (tick): resolves to col b -> (== s b) sym-vs-bool -> 0 +;; 'b (tick): resolves to col b -> (== s b) sym-vs-bool -> type (count (select {from: T2 where: (== s (quote b))})) -- 1 -(count (select {from: T2 where: (== s 'b)})) -- 0 +(count (select {from: T2 where: (== s 'b)})) !- type ;; a symbol naming NO column: (quote a) and 'a agree (both literal) -> 2 (count (select {from: T2 where: (== s (quote a))})) -- 2 (count (select {from: T2 where: (== s 'a)})) -- 2 diff --git a/test/rfl/query/minmax_call_arity.rfl b/test/rfl/query/minmax_call_arity.rfl new file mode 100644 index 000000000..cb688fbc0 --- /dev/null +++ b/test/rfl/query/minmax_call_arity.rfl @@ -0,0 +1,86 @@ +;; Dyadic min/max remain row expressions; only unary calls reduce. +(set M971 (table [k x y] (list ['A 'A 'B 'B 'C] [1 5 3 8 9] [4 2 6 7 0]))) +(min (at M971 'x) (at M971 'y)) -- [1 2 3 7 0] +(max (at M971 'x) (at M971 'y)) -- [4 5 6 8 9] +(at (select {r: (min x y) from: M971}) 'r) -- [1 2 3 7 0] +(at (select {r: (max x y) from: M971}) 'r) -- [4 5 6 8 9] +(count (select {r: (min x y) from: M971})) -- 5 +(type (at (select {r: (min x y) from: M971}) 'r)) -- 'I64 +(at (select {r: (min x) from: M971}) 'r) -- [1] +(at (select {r: (max x) from: M971}) 'r) -- [9] +(at (select {r: (min x 2) from: M971}) 'r) -- [1 2 2 2 2] +(at (select {r: (min 2 x) from: M971}) 'r) -- [1 2 2 2 2] +(at (select {r: (max x 2) from: M971}) 'r) -- [2 5 3 8 9] +(at (select {r: (max 2 x) from: M971}) 'r) -- [2 5 3 8 9] +(at (select {r: (+ 10 (min x y)) from: M971}) 'r) -- [11 12 13 17 10] +(at (select {r: (sum (min x y)) from: M971}) 'r) -- [13] +(at (select {r: (sum (max x y)) from: M971}) 'r) -- [32] +(at (select {r: (min (sum x) (sum y)) from: M971}) 'r) -- [19] +(at (select {r: (max (sum x) (sum y)) from: M971}) 'r) -- [26] +;; Multi-row groups distinguish pointwise LIST cells from reducing atoms. +(set G971 (select {r: (min x y) from: M971 by: k asc: k})) +(at G971 'r) -- (list [1 2] [3 7] [0]) +(type (at G971 'r)) -- 'LIST +(type (at (at G971 'r) 0)) -- 'I64 +(at (select {r: (max x y) from: M971 by: k asc: k}) 'r) -- (list [4 5] [6 8] [9]) +(at (select {r: (sum (min x y)) from: M971 by: k asc: k}) 'r) -- [3 10 0] +(at (select {r: (sum (max x y)) from: M971 by: k asc: k}) 'r) -- [9 14 9] +(at (select {r: (min (sum x) (sum y)) from: M971 by: k asc: k}) 'r) -- [6 11 0] +(at (select {r: (max (sum x) (sum y)) from: M971 by: k asc: k}) 'r) -- [6 13 9] +;; Selection/order/take do not silently turn a dyadic call into a reduction. +(at (select {r: (min x y) from: M971 where: (> x 3)}) 'r) -- [2 7 0] +(at (select {r: (sum (min x y)) from: M971 where: (> x 3)}) 'r) -- [9] +(at (select {r: (min x y) from: M971 desc: x take: 2}) 'r) -- [0 7] +;; Binary calls use row-output aliases; unary aggregates retain source scope. +(at (select {x: (+ x 100) r: (min x y) from: M971}) 'r) -- [4 2 6 7 0] +;; Preserve language null-low ordering, notably max(null,1)=1. +(set N971 (table [x y] (list [0Nl 3 0Nl 2] [1 0Nl 0Nl 5]))) +(at (select {r: (min x y) from: N971}) 'r) -- [0Nl 0Nl 0Nl 2] +(at (select {r: (max x y) from: N971}) 'r) -- [1 3 0Nl 5] +(at (select {r: (min x 1.5) from: M971}) 'r) -- [1.0 1.5 1.5 1.5 1.5] +(count (select {r: (min x y) from: M971 where: (< x 0)})) -- 0 + +;; Mixed reducing/row outputs and an alias also exercise unary fallback admission. +(set Q971 (select {n: (count x) r: (min x y) from: M971 by: k asc: k})) +(at Q971 'n) -- [2 2 1] +(at Q971 'r) -- (list [1 2] [3 7] [0]) +(set FMIN971 min) +(at (select {n: (count x) r: (FMIN971 x y) from: M971 by: k asc: k}) 'r) -- (list [1 2] [3 7] [0]) + +;; Arithmetic over earlier group scalars is not reducer nesting. +(at (select {a: (sum x) b: (sum y) r: (min a b) from: M971 by: k asc: k}) 'r) -- [6 11 0] +(at (select {a: (sum x) b: (sum y) r: (max a b) from: M971 by: k asc: k}) 'r) -- [6 13 9] + +;; Repeated compiled caller and existing UPDATE path retain dyadic semantics. +(set MF971 (fn [t] (select {r: (min x y) from: t}))) +(at (MF971 M971) 'r) -- [1 2 3 7 0] +(at (MF971 M971) 'r) -- [1 2 3 7 0] +(at (update {r: (max x y) from: M971}) 'r) -- [4 5 6 8 9] +;; Invalid arities must not manufacture a reduction from the first argument. +(select {r: (min) from: M971}) !- arity +(select {r: (max) from: M971}) !- arity +(select {r: (min x y 0) from: M971}) !- arity +(select {r: (max x y 0) from: M971 by: k}) !- arity +;; These really are nested reductions and remain errors. +(select {r: (sum (min x)) from: M971 by: k}) !- domain +(select {a: (sum x) r: (min a) from: M971 by: k}) !- domain + +;; An earlier group alias still cannot mix with source rows. +(select {n: (count x) r: (min y n) from: M971 by: k}) !- domain +;; A literal reducer can broadcast inside its group, like existing +/lambda calls. +(at (select {r: (min (sum x) y) from: M971 by: k asc: k}) 'r) -- (list [4 2] [6 7] [0]) +(at (select {r: (max (sum x) y) from: M971 by: k asc: k}) 'r) -- (list [6 6] [11 11] [9]) + +;; Scalar-only and lexical vectors retain their original row/rank contracts. +(at (select {r: (min 1 2) from: M971}) 'r) -- [1 1 1 1 1] +(set LOCAL971 (fn [x] (at (select {r: (min x y) from: M971}) 'r))) +(LOCAL971 [1 2]) -- (list [1 2] [1 2] [1 2] [1 2] [0 0]) +(set CAPTURE971 ((fn [x] (fn [] (at (select {r: (max x y) from: M971}) 'r))) [1 2])) +(CAPTURE971) -- (list [4 4] [2 2] [6 6] [7 7] [1 2]) +(set HEAD971 (fn [min] (at (select {r: (min x y) from: M971}) 'r))) +(HEAD971 (fn [a b] (list a b))) -- (list (list 1 4) (list 5 2) (list 3 6) (list 8 7) (list 9 0)) + +;; Result null metadata must remain usable by downstream consumers. +(where (nil? (at (select {r: (min x y) from: N971}) 'r))) -- [0 1 2] +(where (nil? (at (select {r: (max x y) from: N971}) 'r))) -- [2] +(count (where (nil? (at (select {r: (min 0Nl x) from: M971}) 'r)))) -- 5 diff --git a/test/rfl/query/minmax_call_arity_storage.rfl b/test/rfl/query/minmax_call_arity_storage.rfl new file mode 100644 index 000000000..ef986436f --- /dev/null +++ b/test/rfl/query/minmax_call_arity_storage.rfl @@ -0,0 +1,13 @@ +;; @requires: posix +;; Both operands remain visible with mapped/encoded and two-part source tables. +(.sys.exec "rm -rf /tmp/rfl_minmax971") -- 0 +(set M971S (table [k x y] (list ['A 'A 'B 'B 'C] [1 5 3 8 9] [4 2 6 7 0]))) +(set CHECK971 (fn [t] (list (at (select {r: (min x y) from: t}) 'r) (at (select {r: (max x y) from: t}) 'r) (at (select {r: (sum (min x y)) from: t}) 'r) (at (select {r: (min x y) from: t by: k asc: k}) 'r) (at (select {r: (sum (min x y)) from: t by: k asc: k}) 'r) (at (select {r: (max (sum x) (sum y)) from: t by: k asc: k}) 'r) (at (select {r: (min x y) from: t where: (> x 3)}) 'r) (at (select {r: (min x y) from: t desc: x take: 2}) 'r)))) +(.db.splayed.set "/tmp/rfl_minmax971/s/" M971S) +(set S971 (.db.splayed.get "/tmp/rfl_minmax971/s/")) +(CHECK971 S971) -- (list [1 2 3 7 0] [4 5 6 8 9] [13] (list [1 2] [3 7] [0]) [3 10 0] [6 13 9] [2 7 0] [0 7]) +(.db.splayed.set "/tmp/rfl_minmax971/p/2024.01.01/t/" (table [k x y] (list ['A 'A 'B] [1 5 3] [4 2 6]))) +(.db.splayed.set "/tmp/rfl_minmax971/p/2024.01.02/t/" (table [k x y] (list ['B 'C] [8 9] [7 0]))) +(set P971 (.db.parted.get "/tmp/rfl_minmax971/p/" 't)) +(CHECK971 P971) -- (list [1 2 3 7 0] [4 5 6 8 9] [13] (list [1 2] [3 7] [0]) [3 10 0] [6 13 9] [2 7 0] [0 7]) +(.sys.exec "rm -rf /tmp/rfl_minmax971") -- 0 diff --git a/test/rfl/query/nullable_min_topn.rfl b/test/rfl/query/nullable_min_topn.rfl new file mode 100644 index 000000000..a5c0a91af --- /dev/null +++ b/test/rfl/query/nullable_min_topn.rfl @@ -0,0 +1,12 @@ +;; The radix top-N path must rank all-null MIN groups as the final sort does. +;; take: 1025 bypasses the heap and provides the reference order. +(.sys.exec "rm -rf /tmp/rfl_nullable_min_topn") +(set K (% (* (til 8000) 7919) 2000)) +(set W (as 'I64 (map (fn [k] (if (< (% k 5) 1) 0Nl (% k 13))) K))) +(set T (table [s w v] (list (at (as 'SYMBOL (map (fn [j] (format "w%" j)) (til 2000))) K) W (til 8000)))) +(.db.splayed.set "/tmp/rfl_nullable_min_topn/2024.01.01/t/" (take T 4000) "/tmp/rfl_nullable_min_topn/.sym") +(.db.splayed.set "/tmp/rfl_nullable_min_topn/2024.01.02/t/" (drop T 4000) "/tmp/rfl_nullable_min_topn/.sym") +(set P (.db.parted.get "/tmp/rfl_nullable_min_topn" 't)) +(at (select {m: (min w) from: P by: {s: s z: (% v 1) t: s} desc: m take: 5}) 'm) -- (at (take (select {m: (min w) from: P by: {s: s z: (% v 1) t: s} desc: m take: 1025}) 5) 'm) +(at (select {m: (min w) from: P by: {s: s z: (% v 1) t: s} asc: m take: 5}) 'm) -- (at (take (select {m: (min w) from: P by: {s: s z: (% v 1) t: s} asc: m take: 1025}) 5) 'm) +(.sys.exec "rm -rf /tmp/rfl_nullable_min_topn") diff --git a/test/rfl/query/parted_gen2_differential.rfl b/test/rfl/query/parted_gen2_differential.rfl new file mode 100644 index 000000000..b1c72483f --- /dev/null +++ b/test/rfl/query/parted_gen2_differential.rfl @@ -0,0 +1,53 @@ +;; The same parted table saved as generation 0 and as generation 2 answers +;; every query identically: grouped outputs (aggregate and not), pruned, +;; partial and contradictory wheres, sorts, takes, and update by. The +;; partitions are uneven, one is tiny, and the columns carry nulls. +(.sys.exec "rm -rf rf_test_pdiff0 rf_test_pdiff2") -- 0 +(set syms ['p 'q 'r 'u 'v 'w 'z 'a 'm]) +(set mk (fn [n o] (table [a b s f x i bo ts] (list (concat [0Nl] (- (% (* (+ o (til (- n 1))) 7919) 1000) 500)) (% (* (+ o (til n)) 31) 97) (at syms (% (* (+ o (til n)) 13) 9)) (concat (as 'F64 (% (* (+ o (til (- n 1))) 17) 101)) [0Nf]) (at (list "aa" "bb" "" "cc" "dddd") (% (+ o (til n)) 5)) (as 'I32 (% (+ o (til n)) 50)) (== 0 (% (+ o (til n)) 3)) (+ 2024.01.01D00:00:00.000000000 (* 1000000000 (+ o (til n)))))))) +(set days [2024.01.01 2024.01.02 2024.01.03 2024.01.04 2024.01.05 2024.01.06]) +(set ns [50 2000 3 70000 10 3]) +(set offs [0 50 2050 2053 72053 72063]) +(set wr (fn [root k c] (.db.splayed.set (format "%/%/t/" root (at days k)) (mk (at ns k) (at offs k)) (format "%/.sym" root) (if c {compress: true} {compress: false})))) +(count (map (fn [k] (wr "rf_test_pdiff0" k false)) (til 6))) -- 6 +(count (map (fn [k] (wr "rf_test_pdiff2" k true)) (til 6))) -- 6 +(set P0 (.db.parted.get "rf_test_pdiff0/" 't)) +(set P2 (.db.parted.get "rf_test_pdiff2/" 't)) +;; an answer, or the error's text, in printed form +(set ans (fn [q t] (format "%" (try (q t) (fn [e] (format "error %" e)))))) +(set same (fn [q] (== (ans q P0) (ans q P2)))) +(same (fn [t] (select {a: a by: s from: t asc: s}))) -- true +(same (fn [t] (select {a: a by: s from: t where: (== date 2024.01.04) asc: s}))) -- true +(same (fn [t] (select {a: a by: s from: t where: (> b 50) asc: s}))) -- true +(same (fn [t] (select {a: a by: s from: t where: (> date 2024.01.02) asc: s}))) -- true +(same (fn [t] (select {a: a by: s from: t where: (or (== date 2024.01.03) (> a 450)) asc: s}))) -- true +(same (fn [t] (select {u: (- a (avg a)) by: s from: t asc: s}))) -- true +(same (fn [t] (select {u: (- a (avg a)) by: bo from: t where: (> b 10) asc: bo}))) -- true +(same (fn [t] (select {l: (last a) f: (first b) d: (deltas b) by: s from: t where: (> date 2024.01.03) asc: s}))) -- true +(same (fn [t] (select {x: x by: s from: t where: (> b 90) asc: s}))) -- true +(same (fn [t] (select {a: a by: s from: t where: (in s ['p 'q]) asc: s}))) -- true +(same (fn [t] (select {c: (count a) top: (first a) by: s from: t where: (> b 90) asc: s}))) -- true +(same (fn [t] (select {a: (+ a 1) by: s from: t where: (> b 90) asc: s}))) -- true +(same (fn [t] (select {c: (count a) sm: (sum a) mx: (max f) mn: (min ts) by: s from: t asc: s}))) -- true +(same (fn [t] (select {c: (count a) by: [s i] from: t where: (>= date 2024.01.04) asc: c take: 3}))) -- true +(same (fn [t] (select {c: (count a) by: [s x] from: t where: (>= date 2024.01.04) take: 3}))) -- true +(same (fn [t] (select {c: (count a) by: x from: t where: (in date [2024.01.03 2024.01.06]) asc: x}))) -- true +(same (fn [t] (select {c: (count a) by: date from: t where: (< date 2024.01.03) desc: c}))) -- true +(same (fn [t] (select {d: date c: (count a) by: date from: t where: (> date 2024.01.02)}))) -- true +(same (fn [t] (select {f: (first s) l: (last x) by: date from: t where: (in date [2024.01.02 2024.01.05])}))) -- true +(same (fn [t] (select {from: t where: (== date 0Nd)}))) -- true +(same (fn [t] (select {c: (count a) from: t where: (in date (as 'DATE []))}))) -- true +(same (fn [t] (select {from: t where: (not (== date 2024.01.02)) take: 3}))) -- true +(same (fn [t] (select {a: a from: t where: (== date 2024.01.04) take: -3}))) -- true +(same (fn [t] (select {from: t where: (and (== date 2024.01.02) (== date 2024.01.04))}))) -- true +(same (fn [t] (select {c: (count a) by: s from: t where: (and (== date 2024.01.02) (== date 2024.01.04))}))) -- true +(same (fn [t] (select {s: (sum a) m: (max ts) from: t where: (and (== date 2024.01.02) (== date 2024.01.04))}))) -- true +(same (fn [t] (select {x: (count (distinct date)) from: t where: (> date 2024.01.02)}))) -- true +(same (fn [t] (select {m: (min x) from: t where: (== date 2024.01.03)}))) -- true +(same (fn [t] (select {z: (* 2 a) from: t where: (and (> date 2024.01.04) (null a))}))) -- true +(same (fn [t] (select {from: t where: (== date 2024.01.03) asc: x}))) -- true +(same (fn [t] (select {from: t where: (>= date 2024.01.05) desc: ts}))) -- true +(same (fn [t] (count (select {from: t where: (!= date 2024.01.04)})))) -- true +(same (fn [t] (select {c: (count a) s: (sum f) by: (% b 7) from: t where: (== date 2024.01.02) asc: b}))) -- true +(same (fn [t] (count (update {m: (max a) from: t by: s})))) -- true +(.sys.exec "rm -rf rf_test_pdiff0 rf_test_pdiff2") -- 0 diff --git a/test/rfl/query/parted_group_topn_pruned.rfl b/test/rfl/query/parted_group_topn_pruned.rfl new file mode 100644 index 000000000..12038080a --- /dev/null +++ b/test/rfl/query/parted_group_topn_pruned.rfl @@ -0,0 +1,122 @@ +;; Grouped top-N (`asc:`/`desc:` on an aggregate with `take:`) and unordered +;; `take:` after `by:` over a parted table, with and without partition +;; pruning. Every answer equals the same query over an in-memory copy. +;; +;; The partitions are uneven (50 / 2000 / 3 / 70000 / 10 / 3 rows). A pruned +;; where keeps a one-row stand-in partition first; the parted group must not +;; size its route from it, and the per-partition route must never trim each +;; partition to the top N groups before the merge (a group's count is a sum +;; over partitions). The second table has a tiny first partition and no +;; pruning: the same per-partition route, reached without the stand-in. +(.sys.exec "rm -rf rf_test_gtopn rf_test_gtopn2") -- 0 +(set syms ['p 'q 'r 'u 'v 'w 'z 'a 'm]) +(set strs (list "aa" "bb" "" "cc" "dddd")) +(set mk (fn [n o] (table [a b s x i] (list (- (% (* (+ o (til n)) 7919) 1000) 500) (% (* (+ o (til n)) 31) 97) (at syms (% (* (+ o (til n)) 13) 9)) (at strs (% (+ o (til n)) 5)) (as 'I32 (% (+ o (til n)) 50)))))) +(set days [2024.01.01 2024.01.02 2024.01.03 2024.01.04 2024.01.05 2024.01.06]) +(set ns [50 2000 3 70000 10 3]) +(set offs [0 50 2050 2053 72053 72063]) +(set wr (fn [root k] (.db.splayed.set (format "%/%/t/" root (at days k)) (mk (at ns k) (at offs k)) (format "%/.sym" root)))) +(count (map (fn [k] (wr "rf_test_gtopn" k)) (til 6))) -- 6 +(set P (.db.parted.get "rf_test_gtopn/" 't)) +(set F (raze (map (fn [k] (update {date: (take (at days k) (at ns k)) from: (mk (at ns k) (at offs k))})) (til 6)))) +(count P) -- 72066 +(count F) -- 72066 +;; same values, column by column, compared through their text form +(set eqc (fn [a b c] (all (== (as 'STR (at a c)) (as 'STR (at b c)))))) +(set eqt (fn [a b] (all (map (fn [c] (eqc a b c)) (cols a))))) + +;; ordered top-N: the aggregate column is exact (keys may differ among ties) +(set q1 (fn [tb] (select {c: (count a) by: s from: tb where: (>= date 2024.01.04) asc: c take: 3}))) +(set q2 (fn [tb] (select {c: (count a) by: s from: tb where: (>= date 2024.01.04) desc: c take: 3}))) +(set q3 (fn [tb] (select {c: (count a) by: [s i] from: tb where: (>= date 2024.01.04) asc: c take: 3}))) +(set q4 (fn [tb] (select {c: (count a) by: [s i] from: tb where: (>= date 2024.01.04) desc: c take: 3}))) +(set q5 (fn [tb] (select {c: (count a) by: [s x] from: tb where: (in date [2024.01.02 2024.01.04]) asc: c take: 4}))) +(set q6 (fn [tb] (select {c: (count a) by: [s b] from: tb where: (> date 2024.01.01) asc: c take: 5}))) +(set q7 (fn [tb] (select {t: (sum b) by: s from: tb where: (>= date 2024.01.04) asc: t take: 3}))) +(set q8 (fn [tb] (select {t: (sum b) by: [s i] from: tb where: (>= date 2024.01.04) desc: t take: 3}))) +(set q9 (fn [tb] (select {c: (count a) by: s from: tb where: (>= date 2024.01.04) asc: c take: 100}))) +(set q10 (fn [tb] (select {c: (count a) by: s from: tb where: (>= date 2024.01.04) desc: c take: 100}))) +(set q11 (fn [tb] (select {c: (count a) by: [s i] from: tb where: (and (>= date 2024.01.04) (> b 10)) asc: c take: 3}))) +(set q12 (fn [tb] (select {c: (count a) by: s from: tb where: (and (>= date 2024.01.04) (> b 0)) asc: c take: 3}))) +(eqc (q1 P) (q1 F) 'c) -- true +(eqc (q2 P) (q2 F) 'c) -- true +(eqc (q3 P) (q3 F) 'c) -- true +(eqc (q4 P) (q4 F) 'c) -- true +(eqc (q5 P) (q5 F) 'c) -- true +(eqc (q6 P) (q6 F) 'c) -- true +(eqc (q7 P) (q7 F) 't) -- true +(eqc (q8 P) (q8 F) 't) -- true +(eqc (q9 P) (q9 F) 'c) -- true +(eqc (q10 P) (q10 F) 'c) -- true +(eqc (q11 P) (q11 F) 'c) -- true +(eqc (q12 P) (q12 F) 'c) -- true +(count (q9 P)) -- 9 +(at (q3 P) 'c) -- [155 155 155] + +;; unordered take after by: the first N groups in first-seen order +(set u1 (fn [tb] (select {c: (count a) by: [s x] from: tb where: (>= date 2024.01.04) take: 3}))) +(set u2 (fn [tb] (select {c: (count a) by: s from: tb where: (>= date 2024.01.04) take: 4}))) +(set u3 (fn [tb] (select {c: (count a) by: [s i] from: tb where: (in date [2024.01.02 2024.01.04]) take: 5}))) +(set u4 (fn [tb] (select {c: (count a) by: s from: tb where: (and (>= date 2024.01.02) (> b 50)) take: 2}))) +(eqt (u1 P) (u1 F)) -- true +(eqt (u2 P) (u2 F)) -- true +(eqt (u3 P) (u3 F)) -- true +(eqt (u4 P) (u4 F)) -- true + +;; the group route is the same with and without pruning: the stand-in +;; partition never drives the parted group's cardinality estimate (the `or` +;; form is not pruned) +(set runs (fn [] (at (.sys.mem) 'group-perpart-runs))) +(set r0 (runs)) +(count (select {c: (count a) by: s from: P where: (>= date 2024.01.04)})) -- 9 +(set r1 (runs)) +(count (select {c: (count a) by: s from: P where: (or (>= date 2024.01.04) (>= date 2024.01.04))})) -- 9 +(set r2 (runs)) +(- r1 r0) -- 1 +(- r2 r1) -- 1 +(count (select {c: (count a) by: [s i] from: P where: (>= date 2024.01.04)})) -- 450 +(set r3 (runs)) +(count (select {c: (count a) by: [s i] from: P where: (or (>= date 2024.01.04) (>= date 2024.01.04))})) -- 450 +(set r4 (runs)) +(- r3 r2) -- 0 +(- r4 r3) -- 0 +;; an unordered take keeps the per-partition route: each group carries its +;; first global row, and the N smallest are kept in that order +(eqt (u2 P) (u2 F)) -- true +(set r5 (runs)) +(- r5 r4) -- 1 +;; more wanted than there are groups, past the first-key scan's budget +;; (70016 rows, 50 groups first seen from 3): the hidden first-row slot +;; orders them +(set u5 (fn [tb] (select {c: (count a) by: i from: tb where: (>= date 2024.01.04) take: 60}))) +(eqt (u5 P) (u5 F)) -- true +(set u6 (fn [tb] (select {c: (count a) s2: (sum b) by: [s i] from: tb where: (> b 3) take: 7}))) +(eqt (u6 P) (u6 F)) -- true + +;; a tiny first partition, no pruning +(set ns [1 2000 3 70000 10 3]) +(set offs [0 1 2001 2004 72004 72014]) +(count (map (fn [k] (wr "rf_test_gtopn2" k)) (til 6))) -- 6 +(set P2 (.db.parted.get "rf_test_gtopn2/" 't)) +(set F2 (raze (map (fn [k] (update {date: (take (at days k) (at ns k)) from: (mk (at ns k) (at offs k))})) (til 6)))) +(set d1 (fn [tb] (select {c: (count a) by: [s i] from: tb asc: c take: 3}))) +(set d2 (fn [tb] (select {c: (count a) by: s from: tb where: (> b 0) asc: c take: 3}))) +(set d3 (fn [tb] (select {c: (count a) by: [s i] from: tb where: (> b 10) desc: c take: 3}))) +(set d4 (fn [tb] (select {c: (count a) by: [s x] from: tb take: 3}))) +(eqc (d1 P2) (d1 F2) 'c) -- true +(eqc (d2 P2) (d2 F2) 'c) -- true +(eqc (d3 P2) (d3 F2) 'c) -- true +(eqt (d4 P2) (d4 F2)) -- true +;; grouped by the partition key alone: one group per non-empty partition, +;; so an unordered take reads only the first N non-empty partitions +(.sys.exec "rm -rf rf_test_gtopn3") -- 0 +(.db.splayed.set "rf_test_gtopn3/2024.01.01/t/" (table [a] (list (take 0 0))) "rf_test_gtopn3/.sym") +(.db.splayed.set "rf_test_gtopn3/2024.01.02/t/" (table [a] (list (til 3000))) "rf_test_gtopn3/.sym") +(.db.splayed.set "rf_test_gtopn3/2024.01.03/t/" (table [a] (list (take 0 0))) "rf_test_gtopn3/.sym") +(.db.splayed.set "rf_test_gtopn3/2024.01.04/t/" (table [a] (list (til 5000))) "rf_test_gtopn3/.sym") +(.db.splayed.set "rf_test_gtopn3/2024.01.05/t/" (table [a] (list (til 2000))) "rf_test_gtopn3/.sym") +(set P3 (.db.parted.get "rf_test_gtopn3/" 't)) +(at (select {c: (count a) by: date from: P3 take: 2}) 'c) -- [3000 5000] +(at (select {c: (count a) by: date from: P3 take: 2}) 'date) -- [2024.01.02 2024.01.04] +(at (select {c: (count a) by: date from: P3 take: 5}) 'c) -- [3000 5000 2000] +(.sys.exec "rm -rf rf_test_gtopn rf_test_gtopn2 rf_test_gtopn3") -- 0 diff --git a/test/rfl/query/parted_nonagg_by.rfl b/test/rfl/query/parted_nonagg_by.rfl new file mode 100644 index 000000000..9d8925a22 --- /dev/null +++ b/test/rfl/query/parted_nonagg_by.rfl @@ -0,0 +1,36 @@ +;; Non-aggregate outputs beside by: over a saved parted table (the grouped +;; scatter reads a flat copy of the source). Every answer equals the same +;; query over an in-memory copy, with no where, a pruned where and a partial +;; where; the equivalence pass runs it over generation-2 saves. +(.sys.exec "rm -rf rf_test_nagby") -- 0 +(set syms ['p 'q 'r 'u 'v 'w]) +(set mk (fn [n o] (table [a b s x i f bo ts] (list (- (% (* (+ o (til n)) 7919) 1000) 500) (% (* (+ o (til n)) 31) 97) (at syms (% (* (+ o (til n)) 13) 6)) (at (list "aa" "bb" "" "cc") (% (+ o (til n)) 4)) (as 'I32 (% (+ o (til n)) 50)) (as 'F64 (% (* (+ o (til n)) 17) 101)) (== 0 (% (+ o (til n)) 3)) (+ 2024.01.01D00:00:00.000000000 (* 1000000000 (+ o (til n)))))))) +(set days [2024.01.01 2024.01.02 2024.01.03 2024.01.04 2024.01.05 2024.01.06]) +(set ns [50 2000 3 70000 10 3]) +(set offs [0 50 2050 2053 72053 72063]) +(count (map (fn [k] (.db.splayed.set (format "rf_test_nagby/%/t/" (at days k)) (mk (at ns k) (at offs k)) "rf_test_nagby/.sym")) (til 6))) -- 6 +(set P (.db.parted.get "rf_test_nagby/" 't)) +(set F (raze (map (fn [k] (update {date: (take (at days k) (at ns k)) from: (mk (at ns k) (at offs k))})) (til 6)))) +;; tables with list columns compared through their printed form +(set eqt (fn [a b] (== (format "%" a) (format "%" b)))) +(set n1 (fn [tb] (select {a: a by: s from: tb asc: s}))) +(set n2 (fn [tb] (select {u: (- a (avg a)) by: s from: tb asc: s}))) +(set n3 (fn [tb] (select {a: a x: x by: s from: tb where: (== date 2024.01.03) asc: s}))) +(set n4 (fn [tb] (select {a: a by: s from: tb where: (>= date 2024.01.02) asc: s}))) +(set n5 (fn [tb] (select {a: a by: s from: tb where: (or (== date 2024.01.03) (> a 450)) asc: s}))) +(set n6 (fn [tb] (select {a: a b: b by: s from: tb where: (> b 90) asc: s}))) +(set n7 (fn [tb] (select {c: (count a) a: a by: s from: tb where: (and (>= date 2024.01.02) (< b 10)) asc: s}))) +(eqt (n1 P) (n1 F)) -- true +(eqt (n2 P) (n2 F)) -- true +(eqt (n3 P) (n3 F)) -- true +(eqt (n4 P) (n4 F)) -- true +(eqt (n5 P) (n5 F)) -- true +(eqt (n6 P) (n6 F)) -- true +(eqt (n7 P) (n7 F)) -- true +(count (n5 P)) -- 6 +;; the unsorted forms: every row lands in its own group +(count (select {a: a by: s from: P})) -- 6 +(set w5 (fn [tb] (select {a: a by: s from: tb where: (or (== date 2024.01.03) (> a 450))}))) +(== (sum (map count (at (w5 P) 'a))) (count (select {from: F where: (or (== date 2024.01.03) (> a 450))}))) -- true +(eqt (xasc (w5 P) 's) (xasc (w5 F) 's)) -- true +(.sys.exec "rm -rf rf_test_nagby") -- 0 diff --git a/test/rfl/query/parted_prune_metadata.rfl b/test/rfl/query/parted_prune_metadata.rfl new file mode 100644 index 000000000..230ed1cda --- /dev/null +++ b/test/rfl/query/parted_prune_metadata.rfl @@ -0,0 +1,62 @@ +;; @requires: posix +;; Reusing the validated partition-key column index must leave pruning's +;; answers, schema and nulls unchanged. These semantic checks are expected +;; to pass before the performance repair too; metadata-call counting is a +;; separate structural control, not a wall-clock CI assertion. +(.sys.exec "rm -rf rf_prune_meta_whole rf_prune_meta_ragged") -- 0 +(set w1 (table [id label v] (list [0 1 2 3 4] [a b a c a] (as 'I32 [-3 -2 -1 0 1])))) +(set w2 (table [id label v] (list [5 6 7 8 9 10 11] [b a c a b a c] (as 'I32 [2 3 0Nl 5 6 7 8])))) +(set w3 (table [id label v] (list [12 13 14 15] [a b a c] (as 'I32 [9 10 11 12])))) +(.db.splayed.set "rf_prune_meta_whole/2024.01.01/t/" w1 "rf_prune_meta_whole/.sym") +(.db.splayed.set "rf_prune_meta_whole/2024.01.02/t/" w2 "rf_prune_meta_whole/.sym") +(.db.splayed.set "rf_prune_meta_whole/2024.01.03/t/" w3 "rf_prune_meta_whole/.sym") +(.db.splayed.set "rf_prune_meta_ragged/2024.01.01/t/" w1 "rf_prune_meta_ragged/.sym") +(.db.splayed.set "rf_prune_meta_ragged/2024.01.02/t/" (table [id label] (list [5 6 7 8 9 10 11] [b a c a b a c])) "rf_prune_meta_ragged/.sym") +(.db.splayed.set "rf_prune_meta_ragged/2024.01.03/t/" w3 "rf_prune_meta_ragged/.sym") +(set P (.db.parted.get "rf_prune_meta_whole/" 't)) +(set R (.db.parted.get "rf_prune_meta_ragged/" 't)) +(set dates (concat (concat (take 2024.01.01 5) (take 2024.01.02 7)) (take 2024.01.03 4))) +(set labels [a b a c a b a c a b a c a b a c]) +(set F (table [date id label v] (list dates (til 16) labels (as 'I32 [-3 -2 -1 0 1 2 3 0Nl 5 6 7 8 9 10 11 12])))) +(set G (table [date id label v] (list dates (til 16) labels (as 'I32 [-3 -2 -1 0 1 0Nl 0Nl 0Nl 0Nl 0Nl 0Nl 0Nl 9 10 11 12])))) +(set eqc (fn [a b c] (all (== (as 'STR (at a c)) (as 'STR (at b c)))))) +(set eqt (fn [a b] (all (map (fn [c] (eqc a b c)) (cols a))))) +;; No partition-key predicate, and an explicit all-kept key predicate. +(set qa (fn [tb] (select {from: tb where: (== label 'a)}))) +(set qt (fn [tb] (select {from: tb where: (>= date 2024.01.01)}))) +(eqt (qa P) (qa F)) -- true +(eqt (qa R) (qa G)) -- true +(at (qa P) 'id) -- [0 2 4 6 8 10 12 14] +(sum (nil? (at (qa R) 'v))) -- 3 +(eqt (qt P) (qt F)) -- true +(eqt (qt R) (qt G)) -- true +(count (qt R)) -- 16 +;; Partial pruning keeps the formerly missing column's partition too. +(set qp (fn [tb] (select {from: tb where: (and (>= date 2024.01.02) (== label 'a)) take: 3}))) +(eqt (qp P) (qp F)) -- true +(eqt (qp R) (qp G)) -- true +(at (qp P) 'id) -- [6 8 10] +(sum (nil? (at (qp R) 'v))) -- 3 +(type (at (qp R) 'v)) -- 'I32 +;; Exclude the ragged partition; retain rows/order and group cardinalities. +(set qe (fn [tb] (select {from: tb where: (in date [2024.01.01 2024.01.03])}))) +(eqt (qe P) (qe F)) -- true +(eqt (qe R) (qe G)) -- true +(at (qe R) 'id) -- [0 1 2 3 4 12 13 14 15] +(sum (at (qe R) 'v)) -- 37 +(at (select {n: (count id) by: date from: R where: (>= date 2024.01.02) asc: date}) 'n) -- [7 4] +;; All pruned still retains the empty projected schema. +(set qn (fn [tb] (select {from: tb where: (> date 2024.01.03)}))) +(eqt (qn P) (qn F)) -- true +(eqt (qn R) (qn G)) -- true +(count (qn R)) -- 0 +(type (at (qn R) 'v)) -- 'I32 +;; A nonlocal predicate is not newly eligible for partition pruning. +;; AVG sees the whole 16-row WHERE domain (7.5), not just the later dates. +(set qu (fn [tb] (select {from: tb where: (and (>= date 2024.01.02) (> id (avg id)))}))) +(eqt (qu P) (qu F)) -- true +(eqt (qu R) (qu G)) -- true +(at (qu P) 'id) -- [8 9 10 11 12 13 14 15] +(set P 0) +(set R 0) +(.sys.exec "rm -rf rf_prune_meta_whole rf_prune_meta_ragged") -- 0 diff --git a/test/rfl/query/query_sort_take_coverage.rfl b/test/rfl/query/query_sort_take_coverage.rfl index 68dd9fcd8..080384ebe 100644 --- a/test/rfl/query/query_sort_take_coverage.rfl +++ b/test/rfl/query/query_sort_take_coverage.rfl @@ -497,6 +497,72 @@ (select {from: Pck desc: 'y}) -- (select {from: Mck desc: 'y}) (select {x: x from: Pck desc: x}) -- (select {x: x from: Mck desc: x}) (select {y: y from: Pck desc: x}) -- (select {y: y from: Mck desc: x}) +;; a where: that keeps every row leaves no selection and hands the sort the +;; parted table itself; it sorts it flattened, as a partial where: does +(select {from: Pck where: (>= y 0) desc: x}) -- (select {from: Mck desc: x}) +(select {from: Pck where: (>= y 0) asc: [x y]}) -- (select {from: Mck asc: [x y]}) +(select {from: Pck where: (>= y 0) desc: x take: 2}) -- (select {from: Mck desc: x take: 2}) +(select {from: Pck where: (>= y 0) asc: s}) -- (select {from: Mck asc: s}) +(select {from: Pck where: (>= y 0) desc: r take: 3}) -- (select {from: Mck desc: r take: 3}) +(select {from: Pck where: (>= y 0) desc: date}) -- (select {from: Mck desc: date}) +(select {y: y from: Pck where: (>= y 0) desc: x}) -- (select {y: y from: Mck desc: x}) +(select {x: x from: Pck where: (>= y 0) desc: y take: 2}) -- (select {x: x from: Mck desc: y take: 2}) +;; a ragged parted table (a partition lacks a column) sorts, filters and +;; projects as the flat table with typed nulls in that partition's rows, +;; the way it prints and serializes; the missing rows come from the +;; partition-key counts. The partition without the column is in the +;; middle here, then last. +(.sys.exec "rm -rf /tmp/rfl_ckragged") +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.01/t/" (table [a b h] (list [0 1] [0.5 1.5] [true false]))) +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.02/t/" (table [a] (list [2 3 4]))) +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.03/t/" (table [a b h] (list [5 6] [5.5 6.5] [true true]))) +(set Prg (.db.parted.get "/tmp/rfl_ckragged/" 't)) +(set Frg (table [date a b h] (list [2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.02 2024.01.03 2024.01.03] [0 1 2 3 4 5 6] [0.5 1.5 0Nf 0Nf 0Nf 5.5 6.5] [true false false false false true true]))) +(select {from: Prg where: (>= a 0) desc: a take: 3}) -- (select {from: Frg desc: a take: 3}) +(select {from: Prg where: (>= a 0) asc: h}) -- (select {from: Frg asc: h}) +(select {from: Prg where: (>= a 0) desc: b}) -- (select {from: Frg desc: b}) +(select {from: Prg desc: b}) -- (select {from: Frg desc: b}) +(select {from: Prg asc: a take: 3}) -- (select {from: Frg asc: a take: 3}) +(select {from: Prg where: (>= a 0)}) -- Frg +(count (select {from: Prg where: (>= a 0)})) -- 7 +(de (ser (select {from: Prg where: (>= a 0)}))) -- Frg +(select {from: Prg where: (> a 1)}) -- (select {from: Frg where: (> a 1)}) +(select {b: b h: h from: Prg where: (> a 1)}) -- (select {b: b h: h from: Frg where: (> a 1)}) +(select {b: b from: Prg where: (> a 1) desc: a take: 2}) -- (select {b: b from: Frg where: (> a 1) desc: a take: 2}) +(select {from: Prg take: 4}) -- (select {from: Frg take: 4}) +(select {from: Prg take: -4}) -- (select {from: Frg take: -4}) +(select {s: (sum b) n: (count b) f: (first b) from: Prg by: date}) -- (select {s: (sum b) n: (count b) f: (first b) from: Frg by: date}) +(.sys.exec "rm -rf /tmp/rfl_ckragged") +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.01/t/" (table [a b] (list [0 1] [0.5 1.5]))) +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.02/t/" (table [a b] (list [2 3] [2.5 3.5]))) +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.03/t/" (table [a] (list [4 5]))) +(set Prg (.db.parted.get "/tmp/rfl_ckragged/" 't)) +(set Frg (table [date a b] (list [2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.03 2024.01.03] [0 1 2 3 4 5] [0.5 1.5 2.5 3.5 0Nf 0Nf]))) +(select {from: Prg where: (>= a 0) asc: b}) -- (select {from: Frg asc: b}) +(select {from: Prg where: (>= a 0) desc: a take: 2}) -- (select {from: Frg desc: a take: 2}) +(select {from: Prg desc: a take: 2}) -- (select {from: Frg desc: a take: 2}) +(.sys.exec "rm -rf /tmp/rfl_ckragged") +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.01/t/" (table [a b] (list [0 1] [0.5 1.5]))) +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.02/t/" (table [a] (list (as 'I64 [])))) +(.db.splayed.set "/tmp/rfl_ckragged/2024.01.03/t/" (table [a b] (list [5 6] [5.5 6.5]))) +(set Prg (.db.parted.get "/tmp/rfl_ckragged/" 't)) +(set Frg (table [date a b] (list [2024.01.01 2024.01.01 2024.01.03 2024.01.03] [0 1 5 6] [0.5 1.5 5.5 6.5]))) +(select {from: Prg where: (>= a 0) desc: a take: 3}) -- (select {from: Frg desc: a take: 3}) +(select {from: Prg where: (>= a 0) asc: b}) -- (select {from: Frg asc: b}) +(.sys.exec "rm -rf /tmp/rfl_ckragged") +;; a select with no clauses answers the parted table itself, uncopied; it +;; counts, prints and serializes as its rows: ser writes each parted column +;; as the flat vector it stands for, byte for byte, and de reads a flat table +(count (select {from: Pck})) -- (count Mck) +(ser Pck) -- (ser Mck) +(ser (select {from: Pck})) -- (ser Mck) +(de (ser Pck)) -- Mck +(de (ser (select {from: Pck}))) -- Mck +(ser (list Pck 1)) -- (ser (list Mck 1)) +(ser (dict [k] (list Pck))) -- (ser (dict [k] (list Mck))) +(format "%" (select {from: Pck})) -- (format "%" Mck) +;; and a parted table formats as its rows (its column types were `?`) +(format "%" Pck) -- (format "%" Mck) ;; sort keys no output carries, or carried under another name: the sort ;; reads them as columns whatever the outputs are named, as the flat one ;; does; an output naming another output reads that output @@ -635,3 +701,512 @@ (select {from: Prn asc: s}) -- (select {from: Mrn asc: s}) (set __row 0) (.sys.exec "rm -rf /tmp/rfl_ckrown") +;; a lambda parameter or let hides the column of its name in an output on +;; every sorted and taken route, as it does without take: (the parameter +;; and let bindings take precedence over query columns). The fused top-k +;; and positional take gathered the column by name; the parted per-segment +;; routes ran the select on each partition, where a local of the whole +;; table's rows met a segment's rows. A sort key names a column either way. +(.sys.exec "rm -rf /tmp/rfl_cklocal") +(.db.splayed.set "/tmp/rfl_cklocal/p/2024.01.01/t/" (table [x y] (list [3 1 4] [30 10 40]))) +(.db.splayed.set "/tmp/rfl_cklocal/p/2024.01.02/t/" (table [x y] (list [2 3 1] [20 35 15]))) +(.db.splayed.set "/tmp/rfl_cklocal/q/2024.01.01/t/" (table [x y] (list [1 2 3] [10 15 20]))) +(.db.splayed.set "/tmp/rfl_cklocal/q/2024.01.02/t/" (table [x y] (list [4 5 6] [30 35 40]))) +(.db.splayed.set "/tmp/rfl_cklocal/s/t/" (table [x y] (list [3 1 4 2 3 1] [30 10 40 20 35 15]))) +(set Plc (.db.parted.get "/tmp/rfl_cklocal/p/" 't)) +(set Qlc (.db.parted.get "/tmp/rfl_cklocal/q/" 't)) +(set Slc (.db.splayed.get "/tmp/rfl_cklocal/s/t/")) +(set Tlc (select {from: Plc where: (> x 0)})) +(set Ulc (select {from: Qlc where: (> x 0)})) +(set lca (fn [tbl y] (select {x: x yy: y from: tbl asc: x take: 4}))) +(set lcan (fn [tbl y] (select {x: x yy: y from: tbl asc: x}))) +(at (lca Tlc 5) 'yy) -- [5 5 5 5] +(lca Tlc 5) -- (select {from: (lcan Tlc 5) take: 4}) +(lca Slc 5) -- (select {from: (lcan Slc 5) take: 4}) +(lca Plc 5) -- (select {from: (lcan Plc 5) take: 4}) +(set lcd (fn [tbl y] (select {x: x yy: y from: tbl desc: x take: 3}))) +(set lcdn (fn [tbl y] (select {x: x yy: y from: tbl desc: x}))) +(lcd Tlc 5) -- (select {from: (lcdn Tlc 5) take: 3}) +(lcd Slc 5) -- (select {from: (lcdn Slc 5) take: 3}) +(lcd Plc 5) -- (select {from: (lcdn Plc 5) take: 3}) +;; take: alone, and a where: with take: alone (the positional fused take) +(set lct (fn [tbl y] (select {x: x yy: y from: tbl take: 3}))) +(set lctn (fn [tbl y] (select {x: x yy: y from: tbl}))) +(lct Tlc 5) -- (select {from: (lctn Tlc 5) take: 3}) +(lct Plc 5) -- (select {from: (lctn Plc 5) take: 3}) +(at (lct Plc 5) 'yy) -- [5 5 5] +(lct Plc 5) -- (lct Tlc 5) +(at (lct Plc 5) 'x) -- [3 1 4] +(set lcw (fn [tbl y] (select {x: x yy: y from: tbl where: (> x 1) take: 2}))) +(set lcwe (fn [tbl y] (select {x: x yy: y from: tbl where: (> x 1) take: -2}))) +(set lcwn (fn [tbl y] (select {x: x yy: y from: tbl where: (> x 1)}))) +(at (lcw Tlc 5) 'yy) -- [5 5] +(lcw Tlc 5) -- (select {from: (lcwn Tlc 5) take: 2}) +(lcw Slc 5) -- (select {from: (lcwn Slc 5) take: 2}) +(lcw Plc 5) -- (select {from: (lcwn Plc 5) take: 2}) +(lcwe Tlc 5) -- (select {from: (lcwn Tlc 5) take: -2}) +(lcwe Slc 5) -- (select {from: (lcwn Slc 5) take: -2}) +(lcwe Plc 5) -- (select {from: (lcwn Plc 5) take: -2}) +;; a where: with a sort and take: +(set lcws (fn [tbl y] (select {x: x yy: y from: tbl where: (> x 1) asc: x take: 2}))) +(set lcwsn (fn [tbl y] (select {x: x yy: y from: tbl where: (> x 1) asc: x}))) +(lcws Tlc 5) -- (select {from: (lcwsn Tlc 5) take: 2}) +(lcws Slc 5) -- (select {from: (lcwsn Slc 5) take: 2}) +(lcws Plc 5) -- (select {from: (lcwsn Plc 5) take: 2}) +;; a let, and several sort keys (a key named like the local is the column) +(set lcl (fn [tbl] (let y 7) (select {x: x yy: y from: tbl asc: x take: 4}))) +(at (lcl Tlc) 'yy) -- [7 7 7 7] +(at (lcl Plc) 'yy) -- [7 7 7 7] +(set lcm (fn [tbl y] (select {x: x yy: y from: tbl asc: [x y] take: 3}))) +(set lcmn (fn [tbl y] (select {x: x yy: y from: tbl asc: [x y]}))) +(lcm Tlc 5) -- (select {from: (lcmn Tlc 5) take: 3}) +(lcm Plc 5) -- (select {from: (lcmn Plc 5) take: 3}) +(set lck (fn [tbl x] (select {x: x yy: y from: tbl asc: x take: 3}))) +(set lckn (fn [tbl x] (select {x: x yy: y from: tbl asc: x}))) +(count (lck Tlc 5)) -- 3 +(count (lck Plc 5)) -- 3 +(at (lck Tlc 5) 'x) -- [5 5 5] +(at (lck Plc 5) 'x) -- [5 5 5] +;; OPEN: which x a sort key names when a parameter x hides the column and +;; an output is named x is undecided. The ungrouped path sorts by the +;; source column (yy [10 15 20] here), the grouped path by the output of +;; that name (`(fn [tbl x] (select {x: (first x) yy: (sum y) by: y from: tbl +;; asc: x}))`), so the order is not pinned until one rule covers both: +;; (lck Tlc 5) -- (table [x yy] (list [5 5 5] [10 15 20])) +(lck Tlc 5) -- (select {from: (lckn Tlc 5) take: 3}) +(lck Plc 5) -- (select {from: (lckn Plc 5) take: 3}) +;; a local of the table's rows: gathered in the sorted order, on the flat, +;; splayed and parted table alike +(set Vlc [9 8 7 6 5 4]) +(set lcv (fn [tbl x] (select {x: x yy: y from: tbl asc: y take: 4}))) +(set lcvn (fn [tbl x] (select {x: x yy: y from: tbl asc: y}))) +(at (lcv Tlc Vlc) 'x) -- [8 4 6 9] +(lcv Tlc Vlc) -- (select {from: (lcvn Tlc Vlc) take: 4}) +(lcv Slc Vlc) -- (select {from: (lcvn Slc Vlc) take: 4}) +(lcv Plc Vlc) -- (select {from: (lcvn Plc Vlc) take: 4}) +(set lcy (fn [tbl y] (select {x: x yy: y from: tbl desc: x take: 2}))) +(set lcyn (fn [tbl y] (select {x: x yy: y from: tbl desc: x}))) +(at (lcy Ulc Vlc) 'yy) -- [4 5] +(lcy Ulc Vlc) -- (select {from: (lcyn Ulc Vlc) take: 2}) +(lcy Qlc Vlc) -- (select {from: (lcyn Qlc Vlc) take: 2}) +(lcy Plc Vlc) -- (select {from: (lcyn Plc Vlc) take: 2}) +;; on partitions sorted on the key, without take: +(set lcq (fn [tbl y] (select {x: x yy: y from: tbl asc: x}))) +(lcq Qlc Vlc) -- (lcq Ulc Vlc) +(at (lcq Qlc Vlc) 'yy) -- Vlc +(lcq Qlc 5) -- (lcq Ulc 5) +;; a where: reading a local of the table's rows filters the whole table +(set Mlc [false true false true false true]) +(set lcm2 (fn [tbl m] (select {y: y from: tbl where: m asc: y take: 2}))) +(set lcm2n (fn [tbl m] (select {y: y from: tbl where: m asc: y}))) +(at (lcm2n Ulc Mlc) 'y) -- [15 30 40] +(lcm2n Qlc Mlc) -- (lcm2n Ulc Mlc) +(lcm2 Ulc Mlc) -- (select {from: (lcm2n Ulc Mlc) take: 2}) +(lcm2 Qlc Mlc) -- (select {from: (lcm2n Ulc Mlc) take: 2}) +;; a local scalar in a where: is one value on every route +(set lcs (fn [tbl x] (select {y: y from: tbl where: (> x 1) asc: y take: 2}))) +(at (lcs Qlc 5) 'y) -- [10 15] +(at (lcs Ulc 5) 'y) -- [10 15] +(count (lcs Qlc 0)) -- 0 +;; a grouped select: the key and an aggregate read the local +(set lcb (fn [tbl x] (select {s: (sum y) by: x from: tbl desc: s take: 1}))) +(set lcbn (fn [tbl x] (select {s: (sum y) by: x from: tbl desc: s}))) +(set Klc [1 1 1 2 2 2]) +(lcb Tlc Klc) -- (select {from: (lcbn Tlc Klc) take: 1}) +(lcb Plc Klc) -- (select {from: (lcbn Plc Klc) take: 1}) +(lcb Slc Klc) -- (select {from: (lcbn Slc Klc) take: 1}) +(value (lcb Slc Klc)) -- (list [1] [80]) +;; the parted routes stream a where: only when the DAG streams it: compiled, +;; a local or a global is a constant, and only a scalar constant streams. +;; The set of in / not-in is no row operand: a membership list reads the +;; same on every segment, whatever its length (one partition's rows here, +;; or none), and streams +(set lcin (fn [tbl m] (select {x: x y: y from: tbl where: (in x m) desc: x take: 2}))) +(set lcio (fn [tbl m] (select {x: x y: y from: tbl where: (in x m) asc: x}))) +(set lcc1 (fn [tbl c] (select {x: x from: tbl where: (> x c.lo) desc: x take: 2}))) +(set lcc2 (fn [tbl c] (select {x: x from: tbl where: (> x (at c 'lo)) asc: x take: 2}))) +(set lcc3 (fn [tbl u] (select {x: x from: tbl where: (in x u.x) desc: x take: 2}))) +(set Bsr (at (.sys.mem) 'sort-perpart-runs)) +(lcin Qlc [1 4 5 9]) -- (table [x y] (list [5 4] [35 30])) +(- (at (.sys.mem) 'sort-perpart-runs) Bsr) -- 2 +(set Bso (at (.sys.mem) 'sort-perpart-runs)) +(lcio Qlc [1 4 5 9]) -- (table [x y] (list [1 4 5] [10 30 35])) +(- (at (.sys.mem) 'sort-perpart-runs) Bso) -- 2 +(lcio Qlc [1 4 5 9]) -- (lcio Ulc [1 4 5 9]) +(set Bso (at (.sys.mem) 'sort-perpart-runs)) +(lcio Qlc [1 4 5]) -- (lcio Ulc [1 4 5]) +(- (at (.sys.mem) 'sort-perpart-runs) Bso) -- 2 +(set Bso (at (.sys.mem) 'sort-perpart-runs)) +(count (lcio Qlc [])) -- 0 +(- (at (.sys.mem) 'sort-perpart-runs) Bso) -- 2 +(set Bso (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Qlc where: (within x [2 5]) desc: x take: 3}) 'x) -- [5 4 3] +(- (at (.sys.mem) 'sort-perpart-runs) Bso) -- 2 +;; a path into a config dict or a table passed in is no form the DAG +;; compiles: it is answered on the whole table +(set Bsc (at (.sys.mem) 'sort-perpart-runs)) +(select {from: (lcc1 Qlc {lo: 2 hi: 9}) take: 9}) -- (lcc1 Ulc {lo: 2 hi: 9}) +(- (at (.sys.mem) 'sort-perpart-runs) Bsc) -- 0 +(set Bsc (at (.sys.mem) 'sort-perpart-runs)) +(lcc2 Qlc {lo: 2 hi: 9}) -- (lcc2 Ulc {lo: 2 hi: 9}) +(- (at (.sys.mem) 'sort-perpart-runs) Bsc) -- 0 +(set Bsc (at (.sys.mem) 'sort-perpart-runs)) +(lcc3 Qlc (table [x] (list [1 5]))) -- (table [x] (list [5 1])) +(- (at (.sys.mem) 'sort-perpart-runs) Bsc) -- 0 +;; a computed value of the table's or a partition's length (a til, the +;; first of a list holding a mask, a helper returning a mask, a nested +;; select over the outer table) is no row operand the DAG streams: parted +;; answers as flat +(set Bsc (at (.sys.mem) 'sort-perpart-runs)) +(select {x: x from: Qlc where: (< (til 3) 2) desc: x take: 2}) !- length +(select {x: x from: Ulc where: (< (til 3) 2) desc: x take: 2}) !- length +(select {x: x from: Qlc where: (< (til 6) 3) desc: x take: 2}) -- (select {x: x from: Ulc where: (< (til 6) 3) desc: x take: 2}) +(at (select {x: x from: Qlc where: (< (til 6) 3) desc: x take: 2}) 'x) -- [3 2] +(set Lwm (list [true false true false true true])) +(set gwm (fn [] [true false true false true true])) +(set cyl (fn [t] (at t 'y))) +(select {x: x from: Qlc where: (first Lwm) desc: x take: 3}) !- schema +(select {x: x from: Ulc where: (first Lwm) desc: x take: 3}) !- schema +;; xfail BUG: the first of a global list holding a mask raises schema +;; ("column 'Lwm' not found") in a where: on the flat table too, where it +;; should filter by the mask +;; (at (select {x: x from: Ulc where: (first Lwm) desc: x take: 3}) 'x) -- [6 5 3] +(at (select {x: x from: Qlc where: (gwm) desc: x take: 3}) 'x) -- [6 5 3] +(select {x: x from: Qlc where: (gwm) asc: x}) -- (select {x: x from: Ulc where: (gwm) asc: x}) +(at (select {x: x from: Qlc where: (in y (cyl (select {y: y from: Qlc where: (> x 4)}))) desc: x take: 3}) 'x) -- [6 5] +(select {x: x from: Qlc where: (in y (cyl (select {y: y from: Qlc where: (> x 4)}))) asc: x}) -- (select {x: x from: Ulc where: (in y (cyl (select {y: y from: Ulc where: (> x 4)}))) asc: x}) +(- (at (.sys.mem) 'sort-perpart-runs) Bsc) -- 0 +;; a mask as long as one partition, local or global, is no mask of the +;; table: the parted routes raise length as the flat ones do (they +;; filtered each partition with it); a global mask of the table's rows +;; filters the whole table +(set Gsm [true false true]) +(set Gwm [true false true false true true]) +(lcm2 Qlc [true false true]) !- length +(lcm2 Ulc [true false true]) !- length +(lcm2n Qlc [true false true]) !- length +(select {y: y from: Qlc where: Gsm desc: y take: 2}) !- length +(select {y: y from: Ulc where: Gsm desc: y take: 2}) !- length +(select {y: y from: Qlc where: Gwm desc: y take: 2}) -- (select {y: y from: Ulc where: Gwm desc: y take: 2}) +(select {y: y from: Qlc where: Gwm asc: y}) -- (select {y: y from: Ulc where: Gwm asc: y}) +(at (select {y: y from: Qlc where: Gwm asc: y}) 'y) -- [10 20 35 40] +;; a where: over the rows' order or the whole column (a scan, an aggregate) +;; is the whole table's, not each partition's +(select {x: x from: Qlc where: (> (sums x) 5) asc: x}) -- (select {x: x from: Ulc where: (> (sums x) 5) asc: x}) +(at (select {x: x from: Qlc where: (> (sums x) 5) asc: x}) 'x) -- [3 4 5 6] +(select {x: x from: Qlc where: (> x (avg x)) asc: x take: 2}) -- (select {x: x from: Ulc where: (> x (avg x)) asc: x take: 2}) +(at (select {x: x from: Qlc where: (> x (avg x)) asc: x take: 2}) 'x) -- [4 5] +(select {x: x from: Qlc where: (> (deltas x) 0) desc: x take: 2}) -- (select {x: x from: Ulc where: (> (deltas x) 0) desc: x take: 2}) +;; only row-wise ops keep a partition's rows: a set of in or not-in that +;; reads a column, bin, concat and the vector distances are the whole +;; table's (each answered per partition) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(select {x: x from: Qlc where: (in x (- (/ y 5) 2)) asc: x}) -- (select {x: x from: Ulc where: (in x (- (/ y 5) 2)) asc: x}) +(at (select {x: x from: Qlc where: (in x (- (/ y 5) 2)) asc: x}) 'x) -- [1 2 4 5 6] +(at (select {x: x from: Qlc where: (in x (- (/ y 5) 4)) asc: x}) 'x) -- [2 3 4] +(at (select {x: x from: Qlc where: (in x (- (/ y 5) 4)) desc: x take: 2}) 'x) -- [4 3] +(at (select {x: x from: Qlc where: (not-in x (- (/ y 5) 4)) desc: x take: 2}) 'x) -- [6 5] +(select {x: x from: Qlc where: (not-in x (- (/ y 5) 2)) asc: x}) -- (select {x: x from: Ulc where: (not-in x (- (/ y 5) 2)) asc: x}) +(select {x: x from: Qlc where: (> (bin y y) 2) asc: x take: 2}) -- (select {x: x from: Ulc where: (> (bin y y) 2) asc: x take: 2}) +(select {x: x from: Qlc where: (in x (concat (- (/ y 5) 2) [9])) asc: x}) -- (select {x: x from: Ulc where: (in x (concat (- (/ y 5) 2) [9])) asc: x}) +(select {x: x from: Qlc where: (> (* 5 y) (inner-prod x x)) asc: x}) -- (select {x: x from: Ulc where: (> (* 5 y) (inner-prod x x)) asc: x}) +(select {x: x from: Qlc where: (> (* 0.01 y) (cos-dist x y)) asc: x}) -- (select {x: x from: Ulc where: (> (* 0.01 y) (cos-dist x y)) asc: x}) +(select {x: x from: Qlc where: (> (* 3 y) (l2-dist x (* 0 x))) asc: x}) -- (select {x: x from: Ulc where: (> (* 3 y) (l2-dist x (* 0 x))) asc: x}) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +;; a lookup into a value by a column and a membership in a subquery's +;; result (its table as long as a partition) are no forms the DAG +;; compiles: they are answered on the whole table +(set Dlc (dict [1 2 3 4 5 6] [0 0 1 1 0 1])) +(set Ulc3 (table [x z] (list [1 5 9] [0 0 0]))) +(set cxlc (fn [t] (at t 'x))) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Qlc where: (== (at Dlc x) 1) desc: x take: 2}) 'x) -- [6 4] +(at ((fn [t d] (select {x: x from: t where: (== (at d x) 1) desc: x take: 2})) Qlc Dlc) 'x) -- [6 4] +(at (select {x: x from: Qlc where: (in x (cxlc (select {x: x from: Ulc3 where: (> x 2)}))) desc: x take: 2}) 'x) -- [5] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +;; a helper the DAG inlines streams when its body is row-wise in its +;; parameters, bound or written inline; one that reads an aggregate, +;; directly or through another helper, a draw through a helper, eval, and +;; a computed callee are answered on the whole table +(set f2lc (fn [v] (* 2 v))) +(set galc (fn [] (avg x))) +(set halc (fn [] (galc))) +(set rlc (fn [] (rand 6 100))) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Qlc where: (> (f2lc x) 5) desc: x take: 2}) 'x) -- [6 5] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(select {x: x from: Qlc where: (> (f2lc x) 5) asc: x}) -- (select {x: x from: Ulc where: (> (f2lc x) 5) asc: x}) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Qlc where: (> ((fn [v] (* 2 v)) x) 5) desc: x take: 2}) 'x) -- [6 5] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Qlc where: (> x (halc)) asc: x take: 2}) 'x) -- [4 5] +(at (select {x: x from: Qlc where: (> x (galc)) asc: x}) 'x) -- [4 5 6] +(at (select {x: x from: Qlc where: (> x ((fn [] (avg x)))) asc: x take: 2}) 'x) -- [4 5] +(count (select {x: x from: Qlc where: (>= (rlc) 0) desc: x take: 2})) -- 2 +(at (select {x: x from: Qlc where: (eval (list > 'x 4)) desc: x take: 2}) 'x) -- [6 5] +(at (select {x: x from: Qlc where: (> ((if (> 1 0) f2lc neg) x) 5) desc: x take: 2}) 'x) -- [6 5] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +;; an output a helper computes takes the general path (the routes gather +;; bare columns) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(select {x: x d: (f2lc x) from: Qlc desc: x take: 2}) -- (select {x: x d: (f2lc x) from: Ulc desc: x take: 2}) +(select {x: x d: ((fn [v] (* 2 v)) x) from: Qlc asc: x}) -- (select {x: x d: ((fn [v] (* 2 v)) x) from: Ulc asc: x}) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +;; a mask as long as one partition read through a dict path, an at chain or +;; a table column is no mask of the table: parted raises length as flat does +(set Cdm {m: [true false true] a: {b: {d: {e: [true false true]}}}}) +(set Cdw {a: {b: {d: {e: [true false true false true true]}}}}) +(set lcdm (fn [t c] (select {x: x from: t where: c.m asc: x}))) +(set lcde (fn [t c] (select {x: x from: t where: c.a.b.d.e asc: x}))) +(set lcda (fn [t c] (select {x: x from: t where: (at (at (at (at c 'a) 'b) 'd) 'e) asc: x}))) +(set lctm (fn [t u] (select {x: x from: t where: u.m asc: x}))) +(lcdm Qlc Cdm) !- length +(lcdm Ulc Cdm) !- length +(lcde Qlc Cdm) !- length +(lcde Ulc Cdm) !- length +(lcda Qlc Cdm) !- length +(lctm Qlc (table [m] (list [true false true]))) !- length +(lctm Ulc (table [m] (list [true false true]))) !- length +(lcde Qlc Cdw) -- (lcde Ulc Cdw) +(at (lcde Qlc Cdw) 'x) -- [1 3 5 6] +;; the null test, if and within between row-wise bounds stream; sym-name +;; and a cast to STR are no forms the DAG compiles, so str-find, like and +;; a text concat over them are answered on the whole table +(.db.splayed.set "/tmp/rfl_cklocal/w/2024.01.01/t/" (table [x y s] (list [1 2 3] [10.0 0Nf 20.0] ['a 'b 'c]))) +(.db.splayed.set "/tmp/rfl_cklocal/w/2024.01.02/t/" (table [x y s] (list [4 5 6] [30.0 35.0 0Nf] ['a 'x 'b]))) +(set Pwr (.db.parted.get "/tmp/rfl_cklocal/w/" 't)) +(set Fwr (select {from: Pwr where: (> x 0)})) +(set lcw1 (fn [t] (select {x: x from: t where: (not (nil? y)) desc: x take: 2}))) +(set lcw2 (fn [t] (select {x: x from: t where: (if (> x 3) (nil? y) (> y 5)) desc: x take: 2}))) +(set lcw3 (fn [t] (select {x: x from: t where: (>= (str-find (as 'STR s) "a") 0) desc: x take: 2}))) +(set lcw4 (fn [t] (select {x: x from: t where: (like (sym-name s) "a*") desc: x take: 2}))) +(set lcw5 (fn [t] (select {x: x from: t where: (like (concat (as 'STR s) "z") "az") desc: x take: 2}))) +(set lcw6 (fn [t] (select {x: x from: t where: (within y (list x 100)) desc: x take: 2}))) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (lcw1 Pwr) 'x) -- [5 4] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +(lcw1 Pwr) -- (lcw1 Fwr) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(lcw2 Pwr) -- (lcw2 Fwr) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(lcw3 Pwr) -- (lcw3 Fwr) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(lcw4 Pwr) -- (lcw4 Fwr) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(lcw5 Pwr) -- (lcw5 Fwr) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +(at (lcw5 Pwr) 'x) -- [4 1] +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(lcw6 Pwr) -- (lcw6 Fwr) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +(at (lcw6 Pwr) 'x) -- [5 4] +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Pwr where: (like s "a*") desc: x take: 2}) 'x) -- [4 1] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 2 +;; the clock verbs read the clock, not a row: answered on the whole table +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(at (select {x: x from: Pwr where: (< 0 (as 'I64 (timestamp 'local))) desc: x take: 2}) 'x) -- [6 5] +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +;; a concat of collections is not row-wise (it changes the length) +(set Brw (at (.sys.mem) 'sort-perpart-runs)) +(select {x: x from: Pwr where: (in x (concat (as 'I64 y) [4])) desc: x take: 2}) -- (select {x: x from: Fwr where: (in x (concat (as 'I64 y) [4])) desc: x take: 2}) +(- (at (.sys.mem) 'sort-perpart-runs) Brw) -- 0 +;; a draw is one draw over the table, not one per partition +(set Bsd (at (.sys.mem) 'sort-perpart-runs)) +(count (select {x: x from: Qlc where: (>= (rand 6 100) 0) desc: x take: 2})) -- 2 +(- (at (.sys.mem) 'sort-perpart-runs) Bsd) -- 0 +;; count and count(distinct) of a bound vector (a lambda parameter, a let, +;; a global) count the collection, whole, in every group, whatever its name +;; (functions.md: counting a constant collection returns its length): a +;; parameter named like a column is no column, on every count-distinct +;; route (the composite rewrite, the per-group kernel, the high-cardinality +;; global hash, the eval-level grouping), flat, splayed and parted, with and +;; without take:. The routes read the column of the name. A key a local +;; holds groups by the local's values. +(.db.splayed.set "/tmp/rfl_cklocal/c/2024.01.01/t/" (table [k y] (list [1 1 2] [10 10 20]))) +(.db.splayed.set "/tmp/rfl_cklocal/c/2024.01.02/t/" (table [k y] (list [2 3 3] [30 40 50]))) +(.db.splayed.set "/tmp/rfl_cklocal/d/t/" (table [k y] (list [1 1 2 2 3 3] [10 10 20 30 40 50]))) +(set Pcd (.db.parted.get "/tmp/rfl_cklocal/c/" 't)) +(set Scd (.db.splayed.get "/tmp/rfl_cklocal/d/t/")) +(set Tcd (table [k y] (list [1 1 2 2 3 3] [10 10 20 30 40 50]))) +(set Vcd [1 2 3 3 4 4]) +(set cdl (fn [tbl y] (at (select {c: (count (distinct y)) by: k from: tbl}) 'c))) +(set cdle (fn [tbl y] (at (select {c: (count (distinct (+ y 0))) by: k from: tbl}) 'c))) +(set cdz (fn [tbl z] (at (select {c: (count (distinct z)) by: k from: tbl}) 'c))) +(cdl Tcd Vcd) -- [4 4 4] +(cdl Tcd Vcd) -- (cdz Tcd Vcd) +(cdl Tcd Vcd) -- (cdle Tcd Vcd) +(cdl Scd Vcd) -- [4 4 4] +(cdl Pcd Vcd) -- [4 4 4] +(cdz Pcd Vcd) -- [4 4 4] +;; a helper that reads a column, itself or through another helper, reads +;; the rows: its operand is counted per group, as sum sees it +(set gycd (fn [] y)) +(set hycd (fn [z] (+ y z))) +(set iycd (fn [] (gycd))) +(at (select {c: (count (distinct (gycd))) by: k from: Tcd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (gycd))) by: k from: Scd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (gycd))) by: k from: Pcd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (hycd 0))) by: k from: Tcd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (hycd 0))) by: k from: Scd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (hycd 0))) by: k from: Pcd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (iycd))) by: k from: Tcd}) 'c) -- [1 2 2] +(at (select {c: (count (distinct (iycd))) by: k from: Pcd}) 'c) -- [1 2 2] +(at (select {c: (sum (gycd)) by: k from: Tcd}) 'c) -- [20 50 90] +((fn [tbl y] (at (select {c: (count y) by: k from: tbl}) 'c)) Tcd Vcd) -- ((fn [tbl z] (at (select {c: (count z) by: k from: tbl}) 'c)) Tcd Vcd) +(set cdlt (fn [tbl y] (select {c: (count (distinct y)) by: k from: tbl desc: c take: 1}))) +(set cdltn (fn [tbl y] (select {c: (count (distinct y)) by: k from: tbl desc: c}))) +(value (cdlt Tcd Vcd)) -- (list [1] [4]) +(cdlt Tcd Vcd) -- (select {from: (cdltn Tcd Vcd) take: 1}) +(cdlt Scd Vcd) -- (select {from: (cdltn Scd Vcd) take: 1}) +(cdlt Pcd Vcd) -- (select {from: (cdltn Pcd Vcd) take: 1}) +(set cdlw (fn [tbl y] (at (select {c: (count (distinct y)) by: k from: tbl where: (> k 1)}) 'c))) +(cdlw Tcd Vcd) -- [4 4] +(cdlw Pcd Vcd) -- [4 4] +(cdlw Tcd Vcd) -- ((fn [tbl z] (at (select {c: (count (distinct z)) by: k from: tbl where: (> k 1)}) 'c)) Tcd Vcd) +;; NOTE: sum and first of a bound vector of the table's length stay row-wise +;; on the DAG grouping (s below is per group), unlike count: that +;; inconsistency is kept as it is +(value ((fn [tbl y] (select {c: (count (distinct y)) s: (sum y) by: k from: tbl})) Tcd Vcd)) -- (list [1 2 3] [4 4 4] [3 6 8]) +;; a scalar local is no list, as outside a query +(cdl Tcd 7) !- type +(cdl Pcd 7) !- type +;; over 50000 groups (the global hash): the column y has 2 values per group, +;; the parameter 3 values in all +(set Nhc 120000) +(set Thc (table [k y] (list (% (til Nhc) 60000) (til Nhc)))) +(distinct (cdl Thc (% (til Nhc) 3))) -- [3] +(count (cdl Thc (% (til Nhc) 3))) -- 60000 +;; dense keys take the composite (K, X) rewrite +(set Tdn (table [k y] (list (% (til 1200) 3) (% (til 1200) 4)))) +(cdl Tdn (% (til 1200) 6)) -- [6 6 6] +(cdl Tdn (% (til 1200) 6)) -- (cdz Tdn (% (til 1200) 6)) +(value (cdlt Tdn (% (til 1200) 6))) -- (list [0] [6]) +;; a key a local holds, or a global vector, groups by its values +(set Kcd [1 1 1 2 2 2]) +(set cdk (fn [tbl k] (at (select {c: (count (distinct y)) by: k from: tbl}) 'c))) +(cdk Tcd Kcd) -- [2 3] +(cdk Scd Kcd) -- [2 3] +(cdk Pcd Kcd) -- [2 3] +(at (select {c: (count (distinct y)) by: Kcd from: Tcd}) 'c) -- [2 3] +;; the key keeps its name on the aggregate grouping too (its constant carried +;; no name there) +(set cdks (fn [tbl k] (select {s: (sum y) by: k from: tbl}))) +(key (cdks Tcd Kcd)) -- [k s] +(key (cdks Scd Kcd)) -- [k s] +(key (cdks Pcd Kcd)) -- [k s] +(value (cdks Pcd Kcd)) -- (list [1 2] [40 120]) +(key (select {s: (sum y) by: Kcd from: Tcd})) -- [Kcd s] +(key (select {s: (sum y) by: Kcd from: Tcd where: (> y 15)})) -- [Kcd s] +(key ((fn [tbl k] (select {s: (sum y) by: k from: tbl where: (> y 15)})) Pcd Kcd)) -- [k s] +(set cdkt (fn [tbl k] (select {c: (count (distinct y)) by: k from: tbl desc: c take: 1}))) +(value (cdkt Tcd Kcd)) -- (list [2] [3]) +(value (cdkt Pcd Kcd)) -- (list [2] [3]) +(value ((fn [tbl k] (select {c: (count (distinct y)) n: (count y) by: k from: tbl})) Tcd Kcd)) -- (list [1 2] [2 3] [3 3]) +(cdk Tdn (% (til 1200) 2)) -- [2 2] +(value (cdkt Tdn (% (til 1200) 2))) -- (list [0] [2]) +;; under a where: the key meets the rows it keeps, as the aggregate form's +(set cdkw (fn [tbl k] (select {c: (count (distinct y)) by: k from: tbl where: (> y 15)}))) +(value (cdkw Tcd Kcd)) -- (list [1 2] [1 3]) +(value (cdkw Pcd Kcd)) -- (list [1 2] [1 3]) +(value (cdkw Tcd Kcd)) -- (value ((fn [tbl k] (select {c: (count y) by: k from: tbl where: (> y 15)})) Tcd Kcd)) +;; a bound vector of another length than the table is a collection too; an +;; operand over a column of another length (a take of it) has no value for +;; some rows: the per-group kernel read past it +(set Tln (table [k y] (list (% (til 1000) 10) (til 1000)))) +(cdl Tln (list "a" "b")) -- (cdz Tln (list "a" "b")) +(distinct (cdl Tln (list "a" "b"))) -- [2] +(distinct (cdl Tln [1 2])) -- [2] +(distinct (cdl Thc [1 2])) -- [2] +(select {c: (count (distinct (take y 2))) by: k from: Tln}) !- length +;; a named key must have one value per row of the table, under a where: too +;; (a key as long as the rows the where: keeps is no key of the table) +((fn [t k] (select {c: (count (distinct y)) by: k from: t where: (> y 15)})) Tcd [7 7 8 8]) !- length +((fn [t k] (select {c: (count y) by: k from: t where: (> y 15)})) Tcd [7 7 8 8]) !- length +;; the key meets the rows of the one run of where: (a predicate with an +;; effect runs once and the key follows what it kept), flat and parted +(set Ctg 0) +(set tgp (fn [v] (set Ctg (+ Ctg 1)) (if (== 1 (% Ctg 2)) (> v 15) (> v 35)))) +(value ((fn [t k] (select {c: (count (distinct y)) by: k from: t where: (tgp y)})) Tcd Kcd)) -- (list [1 2] [1 3]) +Ctg -- 1 +(set Ctg 0) +(value ((fn [t k] (select {c: (count (distinct y)) by: k from: t where: (tgp y)})) Pcd Kcd)) -- (list [1 2] [1 3]) +Ctg -- 1 +(value ((fn [t k] (select {c: (count y) by: k from: t where: (> y 15)})) Pcd Kcd)) -- (list [1 2] [1 3]) +(value ((fn [t k] (select {c: (count (distinct y)) d: (reverse y) by: k from: t where: (> y 15)})) Pcd Kcd)) -- (list [1 2] [1 3] (list [20] [50 40 30])) +;; with no outputs the select returns every input column, the partition +;; column too, and no hidden key: a where: on the name the key's local hides +;; leaves the parted table whole, as on its flat copy +(set nok (fn [t k] (select {from: t by: k where: (> k 1)}))) +(set Fcd (select {from: Pcd where: (> y 0)})) +(key (nok Pcd [9 2 2 3 3 3])) -- [k date y] +(nok Pcd [9 2 2 3 3 3]) -- (nok Fcd [9 2 2 3 3 3]) +(key (nok Pcd [9 2 2 3 3 3])) -- (key (nok Fcd [9 2 2 3 3 3])) +(key (nok Pcd [5 5 7 7 9 9])) -- (key (nok Fcd [5 5 7 7 9 9])) +(nok Pcd [5 5 7 7 9 9]) -- (nok Fcd [5 5 7 7 9 9]) +(nok Scd [9 2 2 3 3 3]) -- (nok Tcd [9 2 2 3 3 3]) +(nok Scd [5 5 7 7 9 9]) -- (nok Tcd [5 5 7 7 9 9]) +(value (nok Scd [5 5 7 7 9 9])) -- (list [5 7 9] [10 20 40]) +;; the carried key costs only the columns the clauses read: an aggregate +;; route leaves the parted table as it is (the grouping reads the name), and +;; the eval-level route copies the columns its clauses name, not the other +;; eight (a whole copy peaked at 13 MB here; the aggregate route stays +;; under 0.7 MB, 1.25 MB with a carried key; a where: on the key's hidden +;; name carries it at 1.35 MB, 5.8 MB as a whole copy) +(.db.splayed.set "/tmp/rfl_cklocal/m/2024.01.01/t/" (table [k y a b c d e f g h] (list (% (til 20000) 7) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000)))) +(.db.splayed.set "/tmp/rfl_cklocal/m/2024.01.02/t/" (table [k y a b c d e f g h] (list (% (til 20000) 7) (+ 20000 (til 20000)) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000) (til 20000)))) +(set Pmk (.db.parted.get "/tmp/rfl_cklocal/m/" 't)) +(set Fmk (select {from: Pmk where: (> y -1)})) +(set Kmk (% (til 40000) 5)) +(set fmk (fn [t k] (select {s: (sum y) by: k from: t where: (> y 15)}))) +(set gmk (fn [t k] (select {s: (count (distinct y)) by: k from: t where: (> y 15)}))) +(< (at (.mem.ts (fmk Pmk Kmk)) 'peak-live-bytes) 1000000) -- true +(< (at (.mem.ts (gmk Pmk Kmk)) 'peak-live-bytes) 8000000) -- true +(fmk Pmk Kmk) -- (fmk Fmk Kmk) +(set hmk (fn [t k] (select {s: (sum y) by: k from: t where: (> k 1)}))) +(hmk Pmk Kmk) -- (hmk Fmk Kmk) +(< (at (.mem.ts (hmk Pmk Kmk)) 'peak-live-bytes) 3000000) -- true +(gmk Pmk Kmk) -- (gmk Fmk Kmk) +;; a where: on the name the key's local hides reads the local, on the +;; parted table as on the flat one (the carried key beside the parted +;; columns kept every row of such a comparison) +(set Kcr [3 3 1 1 2 2]) +(set cdkr (fn [t k] (value (select {c: (count (distinct y)) by: k from: t where: (> k 1)})))) +(cdkr Tcd Kcr) -- (list [3 2] [1 2]) +(cdkr Pcd Kcr) -- (cdkr Tcd Kcr) +(cdkr Scd Kcr) -- (cdkr Tcd Kcr) +((fn [t k] (value (select {c: (count (distinct y)) by: k from: t where: (< k 3)}))) Pcd Kcr) -- (list [1 2] [2 2]) +((fn [t k] (value (select {c: (count (distinct y)) by: k from: t where: (== k 1)}))) Pcd Kcr) -- (list [1] [2]) +;; the aggregate grouping by a local named like a column, under a where: +;; on that name, reads the local on a parted table too (it raised length) +((fn [t k] (value (select {c: (sum y) by: k from: t where: (> k 1)}))) Pcd Kcr) -- (list [2 3] [90 20]) +((fn [t k] (value (select {c: (sum y) by: k from: t where: (> k 1)}))) Pcd Kcr) -- ((fn [t k] (value (select {c: (sum y) by: k from: t where: (> k 1)}))) Tcd Kcr) +;; the key's own name in an aggregate reads the local as any other name of +;; that value does on the same grouping +((fn [t k] (value (select {c: (count (distinct y)) m: (max k) n: (count k) by: k from: t}))) Tcd Kcr) -- ((fn [t k z] (value (select {c: (count (distinct y)) m: (max z) n: (count z) by: k from: t}))) Tcd Kcr Kcr) +((fn [t k] (value (select {c: (count (distinct y)) m: (max k) by: k from: t where: (> y 15)}))) Tcd Kcr) -- ((fn [t k z] (value (select {c: (count (distinct y)) m: (max z) by: k from: t where: (> y 15)}))) Tcd Kcr Kcr) +;; xfail BUG: aggregates of a bound vector depend on the grouping route: on +;; the DAG grouping (an integer key, aggregate outputs only) sum/max/first +;; are row-wise per group, on the eval-level grouping (a STR key, a key a +;; local holds, a row expression beside) they take the whole vector: +;; (max z) [4 4 4] and (sum z) [17 17 17] beside (reverse y), where the DAG +;; route gives [2 3 4] and [3 6 8] +;; ((fn [t z] (at (select {m: (max z) r: (reverse y) by: k from: t}) 'm)) Tcd Vcd) -- [2 3 4] +;; xfail BUG: on the eval-level grouping (a STR key, a key a local or a global +;; vector holds) an output calling a lambda literal that reduces its argument +;; runs once over the whole table and spreads that one value: [5 error error] +;; with a STR key, [5 error] with a local key (it raised domain before), where +;; the DAG path gives the per-group counts [1 2 2] for an integer key +;; (at (select {c: ((fn [v] (count (distinct v))) y) by: k from: (table [k y] (list (list "a" "a" "b" "b" "c" "c") [10 10 20 30 40 50]))}) 'c) -- [1 2 2] +;; ((fn [t k] (at (select {c: ((fn [v] (count (distinct v))) y) by: k from: t}) 'c)) Tcd Kcd) -- [2 3] +;; xfail BUG: a grouped row expression over a local vector under a where: +;; raises length (operand lengths 4 and 6); ungrouped it meets the rows the +;; where: keeps, as the grouped form should: [[23 34] [45 56]] +;; ((fn [t z] (at (select {d: (+ y z) by: k from: t where: (> y 15)}) 'd)) Tcd [1 2 3 4 5 6]) -- (list [23 34] [45 56]) +(.sys.exec "rm -rf /tmp/rfl_cklocal") diff --git a/test/rfl/query/select_agg_row_mix_fallback.rfl b/test/rfl/query/select_agg_row_mix_fallback.rfl index 813154f3b..be821853b 100644 --- a/test/rfl/query/select_agg_row_mix_fallback.rfl +++ b/test/rfl/query/select_agg_row_mix_fallback.rfl @@ -41,7 +41,7 @@ (at (select {m: (== n (last n)) x: (+ ts 1) from: T}) 'm) -- [false false false true] ;; ── the temporal column mixed with its own aggregate ───────────────────────── -(at (select {m: (- ts (min ts)) x: i from: T}) 'm) -- [0 10 20 30] +(at (select {m: (- ts (min ts)) x: i from: T}) 'm) -- (as 'TIMESPAN [0 10 20 30]) (at (select {m: (- ts.yyyy (max i)) x: (+ ts 1) from: T}) 'm) -- [2020 2020 2020 2020] ;; ── where: filters before the aggregate is reduced ─────────────────────────── diff --git a/test/rfl/query/select_whole_column_projection.rfl b/test/rfl/query/select_whole_column_projection.rfl index b7cb3dfaf..6c461aff4 100644 --- a/test/rfl/query/select_whole_column_projection.rfl +++ b/test/rfl/query/select_whole_column_projection.rfl @@ -1,4 +1,4 @@ -;; Whole-column verbs (distinct / asc / desc / reverse) as SELECT projections. +;; Whole-column verbs (distinct / asc / desc / reverse / where) as SELECT projections. ;; ;; These builtins consume an entire column and return a vector; the DAG has no ;; bucket for them, so the projection lands in the eval fallback. Previously the @@ -33,6 +33,20 @@ ;; ── SYM column distinct (first-occurrence order) ──────────────────────────── (at (select {d: (distinct d) from: (table [d] (list ['zebra 'apple 'mango 'apple]))}) 'd) -- ['zebra 'apple 'mango] +;; ── where: the indices of the true rows, over the whole column ────────────── +;; Scattered per row it was handed one b8 cell, and failed with "where: +;; argument must be a b8 vector, got b8". A null compares false, as the +;; where: clause drops it. +(set TW (table [i j] (list [1 0Nl 3 4] [5 6 7 8]))) +(at (select {w: (where (> i 2)) from: TW}) 'w) -- (where (> [1 0Nl 3 4] 2)) +(at (select {w: (where (> i 2)) from: TW}) 'w) -- [2 3] +(at (select {c: (count (where (> i 2))) from: TW}) 'c) -- [2] +(first (at (select {c: (count (where (> i 2))) from: TW}) 'c)) -- (count (select {from: TW where: (> i 2)})) +(at (select {c: (count (where (> i 2))) from: TW where: (> j 5)}) 'c) -- [2] +(at (select {c: (first (where (> i 2))) from: TW}) 'c) -- [2] +(select {w: (where (> i 2)) j: j from: TW}) !- length +(where true) !- type + ;; ── ragged result rejected: a length-changing column beside a full column ──── (select {a: (distinct v) b: v from: T}) !- length @@ -60,3 +74,241 @@ (at (select {y: x k: (if true 7 0) from: TPB}) 'k) -- (take 7 7) (count (select {k: (+ (sum x) 0) from: TPB})) -- 1 (.sys.exec "rm -rf /tmp/rfl_scalar_bcast_parted") -- 0 + +;; A scalar aggregate over a whole-column verb, `(first (asc k))`, has no DAG +;; node and lands in the scalar-aggregate eval fallback, which binds every +;; column whole. Over a parted table it bound the parted column itself, and +;; `asc` rejected it ("asc expects a vector", #732). Parted == flat for +;; first/last over asc/desc, with or without where:, across column types. +(.sys.exec "rm -rf /tmp/rfl_scalar_asc_parted") +(set W1 (table [s k f t d n] (list ['b 'a 'c] [3 1 2] [1.5 0.5 2.5] (list "bb" "aa" "cc") [2024.03.02 2024.03.01 2024.03.05] [7 0Nl 5]))) +(set W2 (table [s k f t d n] (list ['a ' 'd] [5 4 6] [-1.0 4.0 0Nf] (list "ab" "" "zz") [2024.02.01 2024.04.01 2024.01.09] [0Nl 2 9]))) +(.db.splayed.set "/tmp/rfl_scalar_asc_parted/2024.01.01/t/" W1) +(.db.splayed.set "/tmp/rfl_scalar_asc_parted/2024.01.02/t/" W2) +(set TPW (.db.parted.get "/tmp/rfl_scalar_asc_parted/" 't)) +(set TFW (table [s k f t d n] (list (concat (at W1 's) (at W2 's)) (concat (at W1 'k) (at W2 'k)) (concat (at W1 'f) (at W2 'f)) (concat (at W1 't) (at W2 't)) (concat (at W1 'd) (at W2 'd)) (concat (at W1 'n) (at W2 'n))))) +(at (select {x: (first (asc k)) from: TPW}) 'x) -- [1] +(select {x: (first (asc k)) from: TPW}) -- (select {x: (first (asc k)) from: TFW}) +(select {x: (last (asc k)) y: (first (desc k)) from: TPW}) -- (select {x: (last (asc k)) y: (first (desc k)) from: TFW}) +(select {x: (first (asc f)) y: (last (asc f)) from: TPW}) -- (select {x: (first (asc f)) y: (last (asc f)) from: TFW}) +(select {x: (first (asc s)) y: (last (asc s)) z: (first (desc s)) from: TPW}) -- (select {x: (first (asc s)) y: (last (asc s)) z: (first (desc s)) from: TFW}) +(select {x: (first (asc t)) y: (last (asc t)) from: TPW}) -- (select {x: (first (asc t)) y: (last (asc t)) from: TFW}) +(select {x: (first (asc d)) y: (last (desc d)) from: TPW}) -- (select {x: (first (asc d)) y: (last (desc d)) from: TFW}) +(select {x: (first (asc n)) y: (last (asc n)) from: TPW}) -- (select {x: (first (asc n)) y: (last (asc n)) from: TFW}) +(select {x: (first (asc k)) c: (count k) m: (min s) from: TPW}) -- (select {x: (first (asc k)) c: (count k) m: (min s) from: TFW}) +(select {x: (first (asc s)) y: (last (asc k)) from: TPW where: (> k 1)}) -- (select {x: (first (asc s)) y: (last (asc k)) from: TFW where: (> k 1)}) +;; A scalar aggregate whose source reads no column has nothing of the +;; table to bind: over a parted table it answers as over a flat one. +(at (select {x: (count [1 2 3]) from: TPW}) 'x) -- [3] +(at (select {x: (first (asc [3 1 2])) from: TPW}) 'x) -- [1] +(select {x: (count [1 2 3]) y: (first (asc [3 1 2])) from: TPW}) -- (select {x: (count [1 2 3]) y: (first (asc [3 1 2])) from: TFW}) + +;; An aggregate source that reads no column and has no DAG node, `(til 5)`, +;; is one collection whatever the row: `(count (til 5))` is 5, as outside a +;; select. It was evaluated row by row and counted once per row (the row +;; count; `sum`/`max` rejected the list of per-row vectors). A scalar +;; source keeps its per-row meaning: `(sum 1)` is the row count. +(at (select {x: (count (til 5)) from: TFW}) 'x) -- [5] +(at (select {x: (count (til 5)) from: TPW}) 'x) -- [5] +(at (select {x: (count (til 5)) from: TFW where: (> k 2)}) 'x) -- [5] +(at (select {x: (count (til 5)) from: TPW where: (> k 2)}) 'x) -- [5] +(at (select {x: (count (+ 1 (til 5))) y: (count k) from: TPW}) 'x) -- [5] +(at (select {x: (max (til 5)) from: TFW}) 'x) -- [4] +(at (select {x: (max (til 5)) from: TPW}) 'x) -- [4] +(set n5 5) +(at (select {x: (count (til n5)) from: TPW}) 'x) -- [5] +(at (select {x: (count (til 5)) from: TFW by: s asc: s}) 'x) -- [5 5 5 5 5] +(at (select {x: (count (til 5)) from: TPW by: s asc: s}) 'x) -- [5 5 5 5 5] +(at (select {x: (sum 1) from: TPW}) 'x) -- [6] +(at (select {x: (count 1) from: TFW}) 'x) -- [6] +;; Grouped, every aggregate over such a source takes it whole in each +;; group; the groups are uneven ('a holds two rows), so counting or summing +;; the group's rows shows. +(at (select {x: (sum (til 5)) from: TFW by: s asc: s}) 'x) -- [10 10 10 10 10] +(at (select {x: (sum (til 5)) from: TPW by: s asc: s}) 'x) -- [10 10 10 10 10] +(at (select {x: (min (+ 1 (til 5))) y: (max (til 5)) from: TFW by: s asc: s}) 'x) -- [1 1 1 1 1] +(at (select {x: (min (+ 1 (til 5))) y: (max (til 5)) from: TPW by: s asc: s}) 'y) -- [4 4 4 4 4] +(at (select {x: (avg (til 5)) from: TFW by: s asc: s}) 'x) -- [2.0 2.0 2.0 2.0 2.0] +(at (select {x: (avg (til 5)) from: TPW by: s asc: s}) 'x) -- [2.0 2.0 2.0 2.0 2.0] +(at (select {x: (first (reverse (til 5))) y: (last (til 5)) z: (sum k) from: TFW by: s asc: s}) 'x) -- [4 4 4 4 4] +(at (select {x: (first (reverse (til 5))) y: (last (til 5)) z: (sum k) from: TPW by: s asc: s}) 'y) -- [4 4 4 4 4] +(at (select {x: (sum (til 5)) z: (sum k) from: TPW by: s asc: s}) 'z) -- (at (select {z: (sum k) from: TFW by: s asc: s}) 'z) + +;; Without by: the source is evaluated once, scalar or collection, so an +;; effect in it runs once, not once per row. +;; `where` returns the positions it keeps, not one value per row: an +;; aggregate over it takes what it returns, in each group (positions within +;; the group) and over the whole table. Grouped, count/sum/max read the +;; group's rows instead (count gave the group sizes). +(set TWi (table [i j] (list [1 1 3 4 5] [5 5 6 6 6]))) +(at (select {c: (count (where (> i 2))) by: j from: TWi}) 'c) -- [0 3] +(at (select {c: (first (where (> i 2))) by: j from: TWi}) 'c) -- [0Nl 0] +(at (select {c: (sum (where (> i 2))) d: (sum i) by: j from: TWi}) 'c) -- [0 3] +(at (select {c: (count (where (> i 2))) from: TWi}) 'c) -- [3] +(at (select {c: (sum (where (> i 2))) from: TWi where: (> i 1)}) 'c) -- [3] +(at (select {x: (count (where (> k 2))) from: TFW by: s asc: s}) 'x) -- [1 1 1 0 1] +(at (select {x: (count (where (> k 2))) from: TPW by: s asc: s}) 'x) -- [1 1 1 0 1] +(at (select {x: (sum (where (> k 2))) y: (max (where (> k 2))) from: TPW by: s asc: s}) 'x) -- [0 1 0 0 0] +(at (select {x: (sum (where (> k 2))) y: (max (where (> k 2))) from: TPW by: s asc: s}) 'y) -- [0 1 0 0Nl 0] +(at (select {x: (count (where (> k 2))) from: TPW}) 'x) -- [4] + +;; A grouped source that reads no column and gives one value stands for +;; every row of the group, as without by: (`(sum 1)` is the row count): 2 in +;; groups of 1 2 1 1 1 rows sums to 2 4 2 2 2. It is evaluated once, not +;; once per group; it was taken as one value per group (1 per group). +(at (select {x: (sum (at [1 2 3] 1)) from: TFW by: s asc: s}) 'x) -- [2 4 2 2 2] +(at (select {x: (sum (at [1 2 3] 1)) from: TPW by: s asc: s}) 'x) -- [2 4 2 2 2] +(at (select {x: (count (at [1 2 3] 1)) from: TPW by: s asc: s}) 'x) -- [1 2 1 1 1] +(at (select {x: (first (at ['p 'q] 1)) from: TFW by: s asc: s}) 'x) -- ['q 'q 'q 'q 'q] +(set TB (table [a b] (list (til 10) (< (til 10) 3)))) +(at (select {x: (sum (at [1 2 3] 0)) from: TB by: b}) 'x) -- [3 7] +(at (select {x: (sum (at [1 2 3] 1)) from: TB by: b}) 'x) -- [6 14] +(at (select {x: (sum (at [1 2 3] 1)) from: TB by: b where: (> a 1)}) 'x) -- [2 14] +(set ticks 0) +(at (select {x: (sum (do (set ticks (+ ticks 1)) (at [1 2 3] 1))) from: TPW by: s asc: s}) 'x) -- [2 4 2 2 2] +ticks -- 1 +(set ticks 0) +(at (select {x: (sum (do (set ticks (+ ticks 1)) (til 5))) y: (sum k) from: TFW by: s asc: s}) 'x) -- [10 10 10 10 10] +ticks -- 1 + +;; A vector constant in an aggregate stands for a column: one of the +;; table's length is sliced per group and filtered by where: (the table's +;; rows before the filter; a parted table's rows across its partitions). +;; Any other length is a length error; it was read past its end. One +;; value spreads over the rows, and count keeps the vector's own length. +(set W6 [10 20 30 40 50 60]) +(at (select {x: (sum W6) from: TFW}) 'x) -- [210] +(at (select {x: (sum W6) from: TPW}) 'x) -- [210] +(at (select {x: (sum W6) from: TFW where: (> k 2)}) 'x) -- [160] +(at (select {x: (sum W6) from: TPW where: (> k 2)}) 'x) -- [160] +(at (select {x: (sum W6) from: TFW by: s asc: s}) 'x) -- [50 60 10 30 60] +(at (select {x: (sum W6) from: TPW by: s asc: s}) 'x) -- [50 60 10 30 60] +(at (select {x: (sum W6) from: TPW by: s where: (> k 2) asc: s}) 'x) -- [50 40 10 60] +(at (select {x: (sum [7]) from: TFW}) 'x) -- [42] +(set L3 [5 1 9]) +(select {x: (sum [1 2 3]) from: TFW}) !- length +(select {x: (sum [1 2 3]) from: TPW}) !- length +(select {x: (avg L3) from: TFW}) !- length +(select {x: (sum (+ 1 L3)) from: TFW}) !- length +(select {x: (max [1 2 3]) from: TFW by: s}) !- length +(select {x: (max L3) from: TPW by: s}) !- length +(select {x: (first L3) from: TFW by: s}) !- length +(select {x: (sum [1 2 3 4]) from: TFW where: (> k 2)}) !- length +(at (select {x: (count L3) from: TFW}) 'x) -- [3] +(at (select {x: (count L3) from: TPW by: s asc: s}) 'x) -- [3 3 3 3 3] + +(set ticks 0) +(at (select {x: (sum (do (set ticks (+ ticks 1)) (at [1 2 3] 0))) from: TFW}) 'x) -- [6] +ticks -- 1 +(set ticks 0) +(at (select {x: (count (at (do (set ticks (+ ticks 1)) (til 3)) 1)) from: TPW where: (> k 2)}) 'x) -- [4] +ticks -- 1 +(set ticks 0) +(at (select {x: (count (do (set ticks (+ ticks 1)) (til 5))) from: TPW}) 'x) -- [5] +ticks -- 1 +;; A column-free source with by: is evaluated once and its value spliced back +;; into the query: every value type must survive the round trip, the other +;; clauses must apply, and a name that is both a global and a column must +;; still read the column. +(set TCF (table [acf b] (list [1 2 3 4 5 6] ['x 'x 'y 'y 'y 'z]))) +(at (select {s: (first (at ['p 'q] 0)) from: TCF by: b}) 's) -- ['p 'p 'p] +(at (select {s: (first (at ["xy" "z"] 0)) from: TCF by: b}) 's) -- ["xy" "xy" "xy"] +(at (select {s: (first (list [1 2] [3])) from: TCF by: b}) 's) -- (list [1 2] [1 2] [1 2]) +(at (select {s: (first (at [2024.01.01 2024.02.02] 1)) from: TCF by: b}) 's) -- [2024.02.02 2024.02.02 2024.02.02] +(at (select {s: (sum (at [1.5 2.5] 0)) from: TCF by: b}) 's) -- [3.0 4.5 1.5] +(at (select {s: (sum (at [0N 1] 0)) from: TCF by: b}) 's) -- [0 0 0] +(at (select {s: (avg (at [0N 1] 0)) from: TCF by: b}) 's) -- [0Nf 0Nf 0Nf] +(at (select {s: (max (at [3 9] 1)) n: (count acf) from: TCF by: b}) 'n) -- [2 3 1] +(at (select {s: (sum (at [2 3] 0)) from: TCF by: b where: (> acf 1) desc: s take: 1}) 's) -- [6] +(set GCF 5) +(at (select {s: (sum (+ GCF 0)) from: TCF by: b}) 's) -- [10 15 5] +(set acf 100) +(at (select {s: (sum (+ acf 0)) from: TCF by: b}) 's) -- [3 12 6] +(set fcf (fn [x] (+ x 1))) +(at (select {s: (sum (fcf 1)) from: TCF by: b}) 's) -- [4 6 2] +(at (select {s: (sum (fcf acf)) from: TCF by: b}) 's) -- [5 15 7] +(set ticks 0) +(count (select {s: (sum (at [2 3] 0)) from: (do (set ticks (+ ticks 1)) TCF) by: b})) -- 3 +ticks -- 1 +(set ticks 0) +(at (select {s: (sum (do (set ticks (+ ticks 1)) (til 3))) from: TCF}) 's) -- [3] +ticks -- 1 +;; A quoted symbol that names a column is the column inside a query (the +;; literal-column rule): a source holding one reads a column, so it is +;; sliced per group like the bare name. It was classed as reading no +;; column and evaluated once over the whole table ([1300 1300], [3 3]), or +;; over a parted table met the segmented column whole (`at: index must be +;; an integer`). +(set MQ (table [k v s] (list [1 1 2 2 2] [10 20 30 40 50] ['a 'b 'a 'c 'a]))) +(at (select {c: (sum (at [100 200 300] 'k)) by: k from: MQ}) 'c) -- [400 900] +(at (select {c: (sum (at [100 200 300] 'k)) by: k from: MQ}) 'c) -- (at (select {c: (sum (at [100 200 300] k)) by: k from: MQ}) 'c) +(at (select {c: (count (distinct 's)) by: k from: MQ}) 'c) -- [2 2] +(at (select {c: (sum (at [0 10 20 30 40 50 60] 'k)) from: TPW by: s asc: s}) 'c) -- (at (select {c: (sum (at [0 10 20 30 40 50 60] 'k)) from: TFW by: s asc: s}) 'c) +(at (select {c: (sum (at [0 10 20 30 40 50 60] 'k)) from: TPW by: s asc: s}) 'c) -- [40 60 30 20 60] +;; A symbol vector inside a source is a literal, whatever names it holds: +;; `['v 'k]` counts 2 in each group as `['p 'q]` does (it was read as the +;; columns v and k, and counted the group's rows). +(at (select {c: (count (at (list ['v 'k]) 0)) by: k from: MQ}) 'c) -- [2 2] +(at (select {c: (count (at (list ['v 'k]) 0)) by: k from: MQ}) 'c) -- (at (select {c: (count (at (list ['p 'q]) 0)) by: k from: MQ}) 'c) +(at (select {c: (first (at (list ['v 'k]) 0)) from: MQ}) 'c) -- ['v] +;; A column-free source is evaluated once for the whole select: not once to +;; plan the output and again for each group, nor again when the select is +;; planned anew around another rewritten output. A collection-valued +;; aggregate (`first` of a list) keeps the value it was planned with. Both +;; shapes counted 4 and 3 evaluations. +(set ticks 0) +(at (select {c: (first (do (set ticks (+ ticks 1)) (list [1 2] [3]))) d: (sum (til 3)) by: k from: MQ}) 'c) -- (list [1 2] [1 2]) +ticks -- 1 +(set ticks 0) +(at (select {c: (first (do (set ticks (+ ticks 1)) (list [1 2] [3]))) by: k from: MQ}) 'c) -- (list [1 2] [1 2]) +ticks -- 1 +(set ticks 0) +(at (select {c: (first (do (set ticks (+ ticks 1)) (list [1 2] [3]))) d: (sum (til 3)) by: k from: MQ}) 'd) -- [3 3] +ticks -- 1 +;; The scalar it gives stands for every row, `(sum 1)` included, and the +;; groups come out in the order every other aggregate gives them (the +;; first rows where: keeps); they came in the table's order. +(at (select {c: (sum (at [1 2 3] 0)) by: s from: MQ where: (> v 10)}) 's) -- (at (select {c: (count v) by: s from: MQ where: (> v 10)}) 's) +(at (select {c: (sum (at [1 2 3] 0)) by: s from: MQ where: (> v 10)}) 's) -- (at (select {c: (sum v) by: s from: MQ where: (> v 10)}) 's) +(at (select {c: (sum 1) by: s from: MQ where: (> v 10)}) 's) -- (at (select {c: (count v) by: s from: MQ where: (> v 10)}) 's) +(at (select {c: (sum (at [1 2 3] 0)) n: (count v) by: s from: MQ where: (> v 10)}) 'c) -- (at (select {c: (sum (at [1 2 3] 0)) n: (count v) by: s from: MQ where: (> v 10)}) 'n) +;; A vector constant of the table's length stays aligned with its rows when +;; a selective where: compacts the group's input (an expression input +;; beside it): it was read from its first cell, raising `length` (dev read +;; V2[0..8] silently). The projection and a computed input alike. +(set T3 (table [a k] (list (til 1000) (% (til 1000) 3)))) +(set V2 (* 2 (til 1000))) +(at (select {s: (sum V2) by: k from: T3 where: (> a 990) asc: k}) 's) -- [5976 5964 5970] +(at (select {s: (sum V2) m: (sum (+ a 1)) by: k from: T3 where: (> a 990) asc: k}) 's) -- [5976 5964 5970] +(at (select {s: (sum (+ a V2)) by: k from: T3 where: (> a 990) asc: k}) 's) -- [8964 8946 8955] +(at (select {s: (+ a V2) m: (* a 2) from: T3 where: (> a 990)}) 's) -- [2973 2976 2979 2982 2985 2988 2991 2994 2997] +(select {s: (sum [1 2]) m: (sum (+ a 1)) by: k from: T3 where: (> a 990)}) !- length +(select {s: (sum [1 2]) m: (sum (+ a 1)) by: k from: T3 where: (> a 99999)}) !- length +;; take: and a dict computed key filter the rows before grouping too: +;; the vector meets them unfiltered, the where: as their selection (both +;; raised `length`; dev read the vector's first cells). +(at (select {c: (sum V2) by: k from: T3 where: (> a 500)}) 'c) -- [250500 248834 249166] +(at (select {c: (sum V2) by: k from: T3 where: (> a 500) take: 2}) 'c) -- [250500 248834] +(at (select {c: (sum V2) by: {m: (+ k 1)} from: T3 where: (> a 500)}) 'c) -- [250500 248834 249166] +(at (select {c: (sum V2) by: {m: (+ k 1)} from: T3 where: (> a 500)}) 'm) -- [1 2 3] +(at (select {c: (sum (+ a V2)) by: {m: (+ k 1)} from: T3 where: (> a 500) take: 2}) 'c) -- [375750 373251] +;; Over an empty table nothing of the vector is read: the sum of no +;; values, as `(sum (til 3))` over it (an empty table grouped, none keyless). +(set T7 (table [a k] (list (til 10) (% (til 10) 3)))) +(key (select {f: (sum [1 2]) by: k from: (take T7 0)})) -- [k f] +(count (select {f: (sum [1 2]) by: k from: (take T7 0)})) -- 0 +(key (select {f: (sum [1 2]) from: (take T7 0)})) -- [f] +(count (select {f: (sum [1 2]) from: (take T7 0)})) -- 0 +(select {f: (sum [1 2]) by: k from: T7 where: (> a 100)}) !- length +;; A collection-valued aggregate of a column-free source is one cell +;; without by: too, as each group takes it (it raised `length`). +(set M5 (table [k v] (list [1 1 2 2 2] [10 20 30 40 50]))) +(at (select {c: (first (enlist [7 8])) from: M5}) 'c) -- (list [7 8]) +(at (select {c: (first (enlist [7 8])) by: k from: M5}) 'c) -- (list [7 8] [7 8]) +(at (select {c: (first (enlist ['v 'k])) from: M5}) 'c) -- (list ['v 'k]) +;; A helper of several statements is not inlined: it runs once per group. +(set cntcf 0) +(set hcf (fn [x] (set cntcf (+ cntcf 1)) (til x))) +(at (select {c: (sum (hcf 3)) by: k from: M5}) 'c) -- [3 3] +cntcf -- 2 +(.sys.exec "rm -rf /tmp/rfl_scalar_asc_parted") -- 0 diff --git a/test/rfl/query/sorted_select_passthrough.rfl b/test/rfl/query/sorted_select_passthrough.rfl new file mode 100644 index 000000000..a44dfab01 --- /dev/null +++ b/test/rfl/query/sorted_select_passthrough.rfl @@ -0,0 +1,14 @@ +;; An already ordered select without take can reuse its input table. +(set Ssp (xasc (table [k v] (list [3 1 2 1] [30 10 20 11])) 'k)) +(at (select {from: Ssp asc: k}) 'v) -- [10 11 20 30] +(at (select {from: Ssp where: (> v 10) asc: k}) 'v) -- [11 20 30] +(set Dsp (xdesc Ssp 'k)) +(at (select {from: Dsp desc: k}) 'v) -- [30 20 10 11] + +;; Multi-key order uses the same lexicographic check. A mixed-direction +;; request and a null-bearing key must still take the general sort path. +(set Msp (xasc (table [a b v] (list [2 1 1 2] [1 2 1 0] [40 30 20 10])) ['a 'b])) +(at (select {from: Msp asc: [a b]}) 'v) -- [20 30 10 40] +(at (select {from: Msp asc: a desc: b}) 'v) -- [30 20 40 10] +(set Nsp (table [k v] (list (as 'I64 [0N 1 2]) [10 20 30]))) +(at (select {from: Nsp asc: k}) 'v) -- [10 20 30] diff --git a/test/rfl/query/sym_compare_admission.rfl b/test/rfl/query/sym_compare_admission.rfl new file mode 100644 index 000000000..289135d49 --- /dev/null +++ b/test/rfl/query/sym_compare_admission.rfl @@ -0,0 +1,22 @@ +;; Non-null SYM/numeric equality is not a comparison of internal IDs. +(set T768 (table [s b k n r] (list (take ['a 'b 'c] 9) (take [true false false] 9) (til 9) (as 'sym (take ["" "a" ""] 9)) (take ["a" "b" "c"] 9)))) +(count (select {from: T768 where: (== s 1)})) !- type +(select {from: T768 where: (== 1 s)}) !- type +(select {from: T768 where: (!= s 1)}) !- type +(count (select {from: T768 where: (!= 1 s)})) !- type +(select {from: T768 where: (== s b)}) !- type +(select {from: T768 where: (!= b s)}) !- type +(count (select {from: T768 where: (== s 'b)})) !- type +(select {from: T768 where: (!= 'k s)}) !- type +(select {from: T768 where: (== s true) take: 2}) !- type +(select {from: T768 where: (and b (== s 1))}) !- type +(select {from: T768 where: (or b (== s 1))}) !- type +(select {from: T768 where: (== n 1)}) !- type +(at (select {from: T768 where: (== s 'a)}) 'k) -- [0 3 6] +(at (select {from: T768 where: (== s "a")}) 'k) -- [0 3 6] +(at (select {from: T768 where: (== r "a")}) 'k) -- [0 3 6] +(count (select {from: T768 where: (== s 's)})) -- 9 +(count (select {from: T768 where: (== s 'zz)})) -- 0 +(at (select {from: T768 where: (== n 0Nl)}) 'k) -- [0 2 3 5 6 8] +(at (select {from: T768 where: (!= 0Nl n)}) 'k) -- [1 4 7] +(select {from: T768 where: (== (quote a) 1)}) !- type diff --git a/test/rfl/query/sym_compare_storage.rfl b/test/rfl/query/sym_compare_storage.rfl new file mode 100644 index 000000000..d2b5acc3e --- /dev/null +++ b/test/rfl/query/sym_compare_storage.rfl @@ -0,0 +1,49 @@ +;; @requires: posix +;; The equivalence runner repeats this fixture with generation2 writes. +(set T768 (table [s b k n r] (list (take ['a 'b 'c] 9) (take [true false false] 9) (til 9) (as 'sym (take ["" "a" ""] 9)) (take ["a" "b" "c"] 9)))) +(.db.splayed.set "__sym768/sp/" T768 "__sym768/sp.sym") +(.db.splayed.set "__sym768/pt/2024.01.01/t/" (table [s b k n r] (list ['a 'b 'c] [true false false] [0 1 2] (as 'sym ["" "a" ""]) ["a" "b" "c"])) "__sym768/pt/.sym") +(.db.splayed.set "__sym768/pt/2024.01.02/t/" (table [s b k n r] (list ['a 'b 'c 'a 'b 'c] [true false false true false false] [3 4 5 6 7 8] (as 'sym ["" "a" "" "" "a" ""]) ["a" "b" "c" "a" "b" "c"])) "__sym768/pt/.sym") +(set S768 (.db.splayed.get "__sym768/sp/" "__sym768/sp.sym")) +(set P768 (.db.parted.get "__sym768/pt/" 't)) +(count (select {from: S768 where: (== s 1)})) !- type +(select {from: S768 where: (== 1 s)}) !- type +(select {from: S768 where: (!= s 1)}) !- type +(count (select {from: S768 where: (!= 1 s)})) !- type +(select {from: S768 where: (== s b)}) !- type +(select {from: S768 where: (!= b s)}) !- type +(count (select {from: S768 where: (== s 'b)})) !- type +(select {from: S768 where: (!= 'k s)}) !- type +(select {from: S768 where: (== s true) take: 2}) !- type +(select {from: S768 where: (and b (== s 1))}) !- type +(select {from: S768 where: (or b (== s 1))}) !- type +(select {from: S768 where: (== n 1)}) !- type +(at (select {from: S768 where: (== s 'a)}) 'k) -- [0 3 6] +(at (select {from: S768 where: (== s "a")}) 'k) -- [0 3 6] +(at (select {from: S768 where: (== r "a")}) 'k) -- [0 3 6] +(count (select {from: S768 where: (== s 's)})) -- 9 +(count (select {from: S768 where: (== s 'zz)})) -- 0 +(at (select {from: S768 where: (== n 0Nl)}) 'k) -- [0 2 3 5 6 8] +(at (select {from: S768 where: (!= 0Nl n)}) 'k) -- [1 4 7] +(count (select {from: P768 where: (== s 1)})) !- type +(select {from: P768 where: (== 1 s)}) !- type +(select {from: P768 where: (!= s 1)}) !- type +(count (select {from: P768 where: (!= 1 s)})) !- type +(select {from: P768 where: (== s b)}) !- type +(select {from: P768 where: (!= b s)}) !- type +(count (select {from: P768 where: (== s 'b)})) !- type +(select {from: P768 where: (!= 'k s)}) !- type +(select {from: P768 where: (== s true) take: 2}) !- type +(select {from: P768 where: (and b (== s 1))}) !- type +(select {from: P768 where: (or b (== s 1))}) !- type +(select {from: P768 where: (== n 1)}) !- type +(at (select {from: P768 where: (== s 'a)}) 'k) -- [0 3 6] +(at (select {from: P768 where: (== s "a")}) 'k) -- [0 3 6] +(at (select {from: P768 where: (== r "a")}) 'k) -- [0 3 6] +(count (select {from: P768 where: (== s 's)})) -- 9 +(count (select {from: P768 where: (== s 'zz)})) -- 0 +(at (select {from: P768 where: (== n 0Nl)}) 'k) -- [0 2 3 5 6 8] +(at (select {from: P768 where: (!= 0Nl n)}) 'k) -- [1 4 7] +(set S768 0) +(set P768 0) +(.sys.exec "rm -rf __sym768") diff --git a/test/rfl/query/unary_arith_types.rfl b/test/rfl/query/unary_arith_types.rfl new file mode 100644 index 000000000..82b0073b7 --- /dev/null +++ b/test/rfl/query/unary_arith_types.rfl @@ -0,0 +1,200 @@ +;; unary_arith_types.rfl — a unary arithmetic verb in a query takes the +;; column types its builtin takes (#854). +;; +;; The planner lowered `neg`/`abs`/`exp`/`log`/`sqrt`/`ceil`/`floor`/`round` +;; to DAG kernels that read any fixed-width lane as a number: over a DATE +;; column `(neg d)` came back as negated day counts ([-8766 ...]) and +;; `(sqrt d)` as roots of them, TIME and TIMESTAMP likewise, SYM as interned +;; ids (`(round s)` crashed), and `neg`/`abs` took BOOL and U8, all of which +;; the builtins reject with `type`. The integer lanes of `ceil`/`floor`/ +;; `round` returned garbage where the builtin is the identity (round: F64). +;; Such a projection now declines to the evaluator, which applies the +;; builtin; over an integer column ceil / floor lower to the column itself +;; and round to a cast to F64, which is what the builtins return. Oracle: +;; the builtin over the column itself. +;; @requires: posix + +(set F (table [d t ts b u h l f s k] (list [2024.01.01 2024.01.02 2024.01.03] [10:00:00.000 11:00:00.000 12:00:00.000] [2024.01.01D10:00:00.000000000 2024.01.02D10:00:00.000000000 2024.01.03D10:00:00.000000000] [true false true] (as 'U8 [1 2 3]) (as 'I16 [1 -2 3]) [1 -2 3] [1.5 -2.5 3.5] ['a 'b 'c] [1 1 2]))) + +;; ─── the builtins reject temporal columns ─────────────────────────────────── +(neg (at F 'd)) !- type +(sqrt (at F 'ts)) !- type +(round (at F 't)) !- type + +;; ─── so does a projection over a flat table: DATE ─────────────────────────── +(select {x: (neg d) from: F}) !- type +(select {x: (abs d) from: F}) !- type +(select {x: (exp d) from: F}) !- type +(select {x: (log d) from: F}) !- type +(select {x: (sqrt d) from: F}) !- type +(select {x: (ceil d) from: F}) !- type +(select {x: (floor d) from: F}) !- type +(select {x: (round d) from: F}) !- type + +;; TIME +(select {x: (neg t) from: F}) !- type +(select {x: (abs t) from: F}) !- type +(select {x: (exp t) from: F}) !- type +(select {x: (log t) from: F}) !- type +(select {x: (sqrt t) from: F}) !- type +(select {x: (ceil t) from: F}) !- type +(select {x: (floor t) from: F}) !- type +(select {x: (round t) from: F}) !- type + +;; TIMESTAMP +(select {x: (neg ts) from: F}) !- type +(select {x: (abs ts) from: F}) !- type +(select {x: (exp ts) from: F}) !- type +(select {x: (log ts) from: F}) !- type +(select {x: (sqrt ts) from: F}) !- type +(select {x: (ceil ts) from: F}) !- type +(select {x: (floor ts) from: F}) !- type +(select {x: (round ts) from: F}) !- type + +;; SYM: the kernels read the interned ids +(select {x: (neg s) from: F}) !- type +(select {x: (sqrt s) from: F}) !- type +(select {x: (floor s) from: F}) !- type +(select {x: (round s) from: F}) !- type + +;; neg / abs reject BOOL and U8 as well; exp/log/sqrt take them +(neg (at F 'b)) !- type +(select {x: (neg b) from: F}) !- type +(select {x: (abs b) from: F}) !- type +(select {x: (neg u) from: F}) !- type +(select {x: (abs u) from: F}) !- type +(at (select {x: (sqrt b) from: F}) 'x) -- (sqrt (at F 'b)) +(at (select {x: (exp u) from: F}) 'x) -- (exp (at F 'u)) + +;; a temporal literal is not folded to its count either +(neg 2024.01.01) !- type +(select {x: (neg 2024.01.01) from: F}) !- type +(select {x: (sqrt 10:00:00.000) from: F}) !- type + +;; ─── the same verb inside update, where:, by: and an aggregate ────────────── +(update {x: (neg d) from: F}) !- type +(select {k: k from: F where: (< (neg d) 0)}) !- type +(select {x: (abs d) by: k from: F}) !- type +(select {x: (sum (neg d)) from: F}) !- type +(select {x: (+ (sqrt ts) 1) from: F}) !- type + +;; ─── numeric columns still compute ────────────────────────────────────────── +(at (select {x: (neg l) from: F}) 'x) -- [-1 2 -3] +(at (select {x: (abs h) from: F}) 'x) -- (abs (at F 'h)) +(at (select {x: (neg f) from: F}) 'x) -- [-1.5 2.5 -3.5] +(at (select {x: (abs f) from: F}) 'x) -- [1.5 2.5 3.5] +(at (select {x: (sqrt l) from: F}) 'x) -- (sqrt (at F 'l)) +(at (select {x: (exp f) from: F}) 'x) -- (exp (at F 'f)) +(at (select {x: (log h) from: F}) 'x) -- (log (at F 'h)) +(at (select {x: (ceil f) from: F}) 'x) -- [2.0 -2.0 4.0] +(at (select {x: (floor f) from: F}) 'x) -- [1.0 -3.0 3.0] +(at (select {x: (round f) from: F}) 'x) -- [2.0 -3.0 4.0] +;; ceil / floor of an integer column is the identity; round is F64 +(at (select {x: (ceil l) from: F}) 'x) -- [1 -2 3] +(at (select {x: (floor h) from: F}) 'x) -- (floor (at F 'h)) +(at (select {x: (round l) from: F}) 'x) -- [1.0 -2.0 3.0] +(at (select {x: (round h) from: F}) 'x) -- (round (at F 'h)) +(at (select {x: (ceil b) from: F}) 'x) -- (ceil (at F 'b)) +(at (select {x: (neg (- d 2024.01.01)) from: F}) 'x) -- [0 -1 -2] +;; ─── ceil / floor / round over every integer width, with nulls ────────────── +;; ceil and floor keep the column (type and nulls); round is F64, 0Nf for null +(set Z (table [b u h i l k] (list [true false true false] (as 'U8 [1 2 3 0]) (as 'I16 [1 0N -3 7]) (as 'I32 [1 0N -3 7]) [1 0N -3 7] [1 1 2 2]))) +(at (select {x: (ceil b) from: Z}) 'x) -- (ceil (at Z 'b)) +(at (select {x: (floor b) from: Z}) 'x) -- (floor (at Z 'b)) +(at (select {x: (round b) from: Z}) 'x) -- (round (at Z 'b)) +(at (select {x: (ceil u) from: Z}) 'x) -- (ceil (at Z 'u)) +(at (select {x: (floor u) from: Z}) 'x) -- (floor (at Z 'u)) +(at (select {x: (round u) from: Z}) 'x) -- (round (at Z 'u)) +(at (select {x: (ceil h) from: Z}) 'x) -- (ceil (at Z 'h)) +(at (select {x: (floor h) from: Z}) 'x) -- (floor (at Z 'h)) +(at (select {x: (round h) from: Z}) 'x) -- (round (at Z 'h)) +(at (select {x: (ceil i) from: Z}) 'x) -- (ceil (at Z 'i)) +(at (select {x: (floor i) from: Z}) 'x) -- (floor (at Z 'i)) +(at (select {x: (round i) from: Z}) 'x) -- (round (at Z 'i)) +(at (select {x: (ceil l) from: Z}) 'x) -- (ceil (at Z 'l)) +(at (select {x: (floor l) from: Z}) 'x) -- (floor (at Z 'l)) +(at (select {x: (round l) from: Z}) 'x) -- (round (at Z 'l)) +(type (at (select {x: (floor b) from: Z}) 'x)) -- 'B8 +(type (at (select {x: (ceil u) from: Z}) 'x)) -- 'U8 +(type (at (select {x: (floor h) from: Z}) 'x)) -- 'I16 +(type (at (select {x: (ceil i) from: Z}) 'x)) -- 'I32 +(type (at (select {x: (floor l) from: Z}) 'x)) -- 'I64 +(type (at (select {x: (round b) from: Z}) 'x)) -- 'F64 +(type (at (select {x: (round h) from: Z}) 'x)) -- 'F64 +(type (at (select {x: (round i) from: Z}) 'x)) -- 'F64 +(at (select {x: (floor i) from: Z}) 'x) -- (as 'I32 [1 0N -3 7]) +(at (select {x: (round i) from: Z}) 'x) -- [1.0 0Nf -3.0 7.0] +(nil? (at (select {x: (ceil h) from: Z}) 'x)) -- [false true false false] +(nil? (at (select {x: (round l) from: Z}) 'x)) -- [false true false false] +;; the output keeps its own name next to the column it reads, either order +(select {i: i x: (floor i) from: Z}) -- (table [i x] (list (at Z 'i) (at Z 'i))) +(select {x: (ceil l) l: l y: (round l) from: Z}) -- (table [x l y] (list (at Z 'l) (at Z 'l) (round (at Z 'l)))) +(select {a: (floor h) b: (ceil h) from: Z}) -- (table [a b] (list (at Z 'h) (at Z 'h))) +;; update, where:, by: and aggregates +(at (update {x: (floor i) from: Z}) 'x) -- (at Z 'i) +(at (update {x: (round i) from: Z}) 'x) -- (round (at Z 'i)) +(at (update {l: (floor l) from: Z}) 'l) -- (at Z 'l) +(at (select {k: k from: Z where: (> (floor i) 0)}) 'k) -- [1 2] +(at (select {k: k from: Z where: (nil? (ceil h))}) 'k) -- [1] +(at (select {k: k from: Z where: (> (round l) 0.0)}) 'k) -- [1 2] +(at (select {k: k from: Z where: (floor b)}) 'k) -- [1 2] +(select {x: (sum (floor i)) by: k from: Z}) -- (select {x: (sum i) by: k from: Z}) +(select {x: (sum (round l)) by: k from: Z}) -- (table [k x] (list [1 2] [1.0 4.0])) +(select {n: (count k) by: {g: (floor h)} from: Z}) -- (select {n: (count k) by: {g: h} from: Z}) +(at (select {x: (sum (ceil h)) from: Z}) 'x) -- (at (select {x: (sum h) from: Z}) 'x) +(at (select {x: (max (floor i)) from: Z}) 'x) -- (at (select {x: (max i) from: Z}) 'x) +(at (select {x: (min (ceil u)) from: Z}) 'x) -- (at (select {x: (min u) from: Z}) 'x) +(at (select {x: (avg (round i)) from: Z}) 'x) -- (at (select {x: (avg i) from: Z}) 'x) +(at (select {x: (count (floor l)) from: Z}) 'x) -- [4] +;; nested and constant operands +(at (select {x: (floor (+ i 1)) from: Z}) 'x) -- (floor (+ (at Z 'i) 1)) +(at (select {x: (round (neg i)) from: Z}) 'x) -- (round (neg (at Z 'i))) +(at (select {x: (floor (neg h)) from: Z}) 'x) -- (floor (neg (at Z 'h))) +(at (select {x: (ceil (neg i)) from: Z}) 'x) -- (ceil (neg (at Z 'i))) +(at (select {x: (floor (ceil l)) from: Z}) 'x) -- (at Z 'l) +(at (select {x: (round (floor i)) from: Z}) 'x) -- (round (at Z 'i)) +(at (select {x: (+ (floor l) 1) from: Z}) 'x) -- (+ (at Z 'l) 1) +(at (select {x: (floor (> l 0)) from: Z}) 'x) -- (> (at Z 'l) 0) +(at (select {x: (+ l (floor 2)) from: Z}) 'x) -- (+ (at Z 'l) 2) +(at (select {x: (+ i (round 0Ni)) from: Z}) 'x) -- [0Nf 0Nf 0Nf 0Nf] +(at (select {x: (+ i (floor (as 'I32 5))) from: Z}) 'x) -- (+ (at Z 'i) (as 'I32 5)) + +(at (select {x: (sum (abs l)) from: F}) 'x) -- [6] +(at (update {x: (neg f) from: F}) 'x) -- [-1.5 2.5 -3.5] +(at (select {k: k from: F where: (< (neg l) 0)}) 'k) -- [1 2] +;; order-preserving verbs on temporals are not arithmetic and stay as they were +(at (select {x: (maxs d) from: F}) 'x) -- (maxs (at F 'd)) +(at (select {x: (deltas ts) from: F}) 'x) -- (deltas (at F 'ts)) + +;; ─── a splayed copy and a parted table's DATE column ───────────────────────── +(.sys.exec "rm -rf /tmp/rfl_unary_arith_types") +(set N (table [d ts f] (list (at F 'd) (at F 'ts) (at F 'f)))) +(.db.splayed.set "/tmp/rfl_unary_arith_types/s/" N) +(set S (.db.splayed.get "/tmp/rfl_unary_arith_types/s/")) +(select {x: (neg d) from: S}) !- type +(select {x: (sqrt ts) from: S}) !- type +(select {x: (floor d) from: S}) !- type +(at (select {x: (neg f) from: S}) 'x) -- [-1.5 2.5 -3.5] +(set NI (table [h i l] (list (at Z 'h) (at Z 'i) (at Z 'l)))) +(.db.splayed.set "/tmp/rfl_unary_arith_types/si/" NI) +(set SI (.db.splayed.get "/tmp/rfl_unary_arith_types/si/")) +(at (select {x: (floor i) from: SI}) 'x) -- (at NI 'i) +(at (select {x: (ceil h) from: SI}) 'x) -- (at NI 'h) +(at (select {x: (round l) from: SI}) 'x) -- (round (at NI 'l)) +(.db.splayed.set "/tmp/rfl_unary_arith_types/p/2024.01.01/t/" N) +(.db.splayed.set "/tmp/rfl_unary_arith_types/p/2024.01.02/t/" N) +(set P (.db.parted.get "/tmp/rfl_unary_arith_types/p/" 't)) +(select {x: (neg d) from: P}) !- type +(select {x: (abs ts) from: P}) !- type +(select {x: (round d) from: P}) !- type +(at (select {x: (neg f) from: P}) 'x) -- [-1.5 2.5 -3.5 -1.5 2.5 -3.5] +(.db.splayed.set "/tmp/rfl_unary_arith_types/pi/2024.01.01/t/" NI) +(.db.splayed.set "/tmp/rfl_unary_arith_types/pi/2024.01.02/t/" NI) +(set PI (.db.parted.get "/tmp/rfl_unary_arith_types/pi/" 't)) +(select {x: (floor date) from: PI}) !- type +(select {x: (round date) from: PI}) !- type +(at (select {x: (floor i) from: PI}) 'x) -- (concat (at NI 'i) (at NI 'i)) +(at (select {x: (ceil h) from: PI}) 'x) -- (concat (at NI 'h) (at NI 'h)) +(at (select {x: (round l) from: PI}) 'x) -- (concat (round (at NI 'l)) (round (at NI 'l))) +(at (select {x: (sum (round i)) by: date from: PI}) 'x) -- [5.0 5.0] +(.sys.exec "rm -rf /tmp/rfl_unary_arith_types") diff --git a/test/rfl/query/update_fallback_semantics.rfl b/test/rfl/query/update_fallback_semantics.rfl index b1f6e0629..ebf93a00b 100644 --- a/test/rfl/query/update_fallback_semantics.rfl +++ b/test/rfl/query/update_fallback_semantics.rfl @@ -3,7 +3,7 @@ ;; path (review of #690, second pass). ;; ;; The eval fallback evaluated the expression once with whole columns bound. -;; The interpreter's `if` tests one truth value, so `(if (> i 2) 1 (- ts ts))` +;; The interpreter's `if` tests one truth value, so `(if (> i 2) 1 (as 'I64 (- ts ts)))` ;; wrote the then-branch to every row; a column of the wrong length was added ;; unchecked (ragged table); `update by:` took the column type from the first ;; group and cast the rest; and a misspelt column reported `name` instead of @@ -24,38 +24,38 @@ (update {i: (list 1 2) from: t where: (> i 1)}) !- length ;; a constant / reduced expression still broadcasts (at (update {n: 7 from: t}) 'n) -- [7 7 7 7 7] -(at (update {n: (max (- ts ts)) from: t}) 'n) -- [0 0 0 0 0] +(at (update {n: (max (as 'I64 (- ts ts))) from: t}) 'n) -- [0 0 0 0 0] (at (update {n: (max (+ i 1)) from: t}) 'n) -- [6 6 6 6 6] ;; ─── 2. `if` over a temporal expression is per row, as in select ──────────── -(at (select {x: (if (> i 2) 1 (- ts ts)) from: t}) 'x) -- [0 0 1 1 1] -(at (update {x: (if (> i 2) 1 (- ts ts)) from: t}) 'x) -- [0 0 1 1 1] -(at (update {i: (if (> i 2) 1 (- ts ts)) from: t}) 'i) -- [0 0 1 1 1] -(at (update {x: (if (> i 2) 1 (- ts ts)) from: t where: (> i 1)}) 'x) -- [0Nl 0 1 1 1] -(at (update {i: (if (> i 2) 1 (- ts ts)) from: t where: (> i 1)}) 'i) -- [1 0 1 1 1] +(at (select {x: (if (> i 2) 1 (as 'I64 (- ts ts))) from: t}) 'x) -- [0 0 1 1 1] +(at (update {x: (if (> i 2) 1 (as 'I64 (- ts ts))) from: t}) 'x) -- [0 0 1 1 1] +(at (update {i: (if (> i 2) 1 (as 'I64 (- ts ts))) from: t}) 'i) -- [0 0 1 1 1] +(at (update {x: (if (> i 2) 1 (as 'I64 (- ts ts))) from: t where: (> i 1)}) 'x) -- [0Nl 0 1 1 1] +(at (update {i: (if (> i 2) 1 (as 'I64 (- ts ts))) from: t where: (> i 1)}) 'i) -- [1 0 1 1 1] ;; under by: the compiled path is per row within the group; the fallback too (at (update {x: (if (> i 2) 1 (- i i)) by: k from: t}) 'x) -- [0 0 1 1 1] -(at (update {x: (if (> i 2) 1 (- ts ts)) by: k from: t}) 'x) -- [0 0 1 1 1] +(at (update {x: (if (> i 2) 1 (as 'I64 (- ts ts))) by: k from: t}) 'x) -- [0 0 1 1 1] ;; a reduced expression under by: is still one value per group -(at (update {m: (max (- ts ts)) by: k from: t}) 'm) -- [0 0 0 0 0] +(at (update {m: (max (as 'I64 (- ts ts))) by: k from: t}) 'm) -- [0 0 0 0 0] (at (update {m: (max (+ i 1)) by: k from: t}) 'm) -- [3 3 6 6 6] ;; an `if` whose condition mixes a row column with an aggregate cannot be ;; evaluated per row (the aggregate would see one cell); it stays an error ;; until the fallback can reduce aggregates first (#692) (update {x: (if (> i (avg i)) (+ ts 1) ts) from: t}) !- nyi -(update {i: (if (> i (avg i)) 1 (- ts ts)) from: t where: (> i 1)}) !- nyi +(update {i: (if (> i (avg i)) 1 (as 'I64 (- ts ts))) from: t where: (> i 1)}) !- nyi (update {x: (if (> i (avg i)) (+ ts 1) ts) by: k from: t}) !- nyi ;; an aggregate over a literal or a global is the same on every row: fine -(at (update {x: (if (> i 2) (count [1 2 3]) (- ts ts)) from: t}) 'x) -- [0 0 3 3 3] +(at (update {x: (if (> i 2) (count [1 2 3]) (as 'I64 (- ts ts))) from: t}) 'x) -- [0 0 3 3 3] (set GL [1 2 3 4]) -(at (update {x: (if (> i 2) (count GL) (- ts ts)) from: t}) 'x) -- [0 0 4 4 4] +(at (update {x: (if (> i 2) (count GL) (as 'I64 (- ts ts))) from: t}) 'x) -- [0 0 4 4 4] ;; ─── 3. update by: with group results of differing types ──────────────────── (set g (table [k ts tm i] (list [a a b c c c] (+ 2024.01.01D00:00:00.000000000 (* 10 (til 6))) (as 'TIME (* 1000 (til 6))) [1 2 3 4 5 6]))) (at (update {m: (if (> (count i) 1) (max (- i i)) 2.5) by: k from: g}) 'm) -- [0.0 0.0 2.5 0.0 0.0 0.0] -(at (update {m: (if (> (count i) 1) (max (- ts ts)) 2.5) by: k from: g}) 'm) -- [0.0 0.0 2.5 0.0 0.0 0.0] -(type (at (update {m: (if (> (count i) 1) (max (- ts ts)) 2.5) by: k from: g}) 'm)) -- 'F64 +(at (update {m: (if (> (count i) 1) (max (as 'I64 (- ts ts))) 2.5) by: k from: g}) 'm) -- [0.0 0.0 2.5 0.0 0.0 0.0] +(type (at (update {m: (if (> (count i) 1) (max (as 'I64 (- ts ts))) 2.5) by: k from: g}) 'm)) -- 'F64 ;; a TIMESTAMP cannot be written into a TIME column: reject, do not cast (update {m: (if (> (count i) 1) (max (+ tm 0)) (max (+ ts 0))) by: k from: g}) !- type diff --git a/test/rfl/query/update_temporal_arith_fallback.rfl b/test/rfl/query/update_temporal_arith_fallback.rfl index 8f9238536..6a61fe0fa 100644 --- a/test/rfl/query/update_temporal_arith_fallback.rfl +++ b/test/rfl/query/update_temporal_arith_fallback.rfl @@ -20,7 +20,7 @@ (type (at (update {from: t x: (+ ts 1)}) 'name)) -- 'SYM (at (update {from: t x: (+ ts 1)}) 'name) -- [Alice Bob Carol] ;; in place on a quoted table name -(do (update {from: 't y: (- ts ts)}) (type (at t 'y))) -- 'I64 +(do (update {from: 't y: (- ts ts)}) (type (at t 'y))) -- 'TIMESPAN ;; ─── update by: with temporal arithmetic in the aggregate ─────────────────── (set g (table [k ts] (list [a a b] [2001.01.01D01:01:01.000000000 2002.02.02D02:02:02.000000000 2003.03.03D03:03:03.000000000]))) diff --git a/test/rfl/query/where_and_take.rfl b/test/rfl/query/where_and_take.rfl new file mode 100644 index 000000000..d493c24c7 --- /dev/null +++ b/test/rfl/query/where_and_take.rfl @@ -0,0 +1,96 @@ +;; @requires: posix +;; `where: (and …) take: K` that the fused take declines: the optimizer +;; splits the `and` into chained filters, the inner ones leave a selection, +;; and an outer term whose verdicts survive a row subset narrows it as a +;; chained filter does before the first K rows are gathered. Every form +;; answers what the unsplit `(== (and …) true)` does, null flags included, +;; flat and parted. +;; 3000 rows span three morsels; the parted copies, generation 0 and 2, +;; have three ragged partitions. +(.sys.exec "rm -rf /tmp/rfl_wat") +(set N 3000) +(set BS ['B0 'B1 'B2 'B3 'B4 'B5 'B6 'B7 'B8 'B9]) +(set W (table [x a b n] (list (til N) (at ['A0 'A1] (% (til N) 2)) (at BS (% (* (til N) 7) 10)) (til N)))) +(set W (update {from: W n: (if (== 0 (% x 3)) 0Nl n)})) +(.db.splayed.set "/tmp/rfl_wat/2024.01.01/t/" (select {from: W where: (< x 1500)})) +(.db.splayed.set "/tmp/rfl_wat/2024.01.02/t/" (select {from: W where: (and (>= x 1500) (< x 2200))})) +(.db.splayed.set "/tmp/rfl_wat/2024.01.03/t/" (select {from: W where: (>= x 2200)})) +(set PW (.db.parted.get "/tmp/rfl_wat/" 't)) +(count PW) -- 3000 + +;; two terms past the fused take's cap of 8192 +(set R (select {from: W where: (== (and (== a 'A1) (!= b 'B7)) true) take: 10000})) +(count R) -- 1200 +(set S (select {from: W where: (and (== a 'A1) (!= b 'B7)) take: 10000})) +(at S 'x) -- (at R 'x) +(sum (nil? (at S 'n))) -- (sum (nil? (at R 'n))) +(sum (nil? (at S 'n))) -- 400 +(at (select {from: W where: (and (== a 'A1) (!= b 'B7)) take: 3}) 'x) -- [3 5 7] + +;; an `or` inside keeps the split at any K; K crosses a morsel +(set R (select {from: W where: (== (and (or (== a 'A1) (== b 'B4)) (!= b 'B8)) true) take: 1200})) +(set S (select {from: W where: (and (or (== a 'A1) (== b 'B4)) (!= b 'B8)) take: 1200})) +(count S) -- 1200 +(sum (as 'I64 (== (at S 'x) (at R 'x)))) -- 1200 +(sum (as 'I64 (== (nil? (at S 'n)) (nil? (at R 'n))))) -- 1200 +(at S 'b) -- (at R 'b) + +;; the outer term reads a column with nulls +(set R (select {from: W where: (== (and (== a 'A0) (> n 100)) true) take: 10000})) +(set S (select {from: W where: (and (== a 'A0) (> n 100)) take: 10000})) +(at S 'x) -- (at R 'x) +(sum (nil? (at S 'n))) -- 0 + +;; an outer term that reads other rows (a running sum, an aggregate) sees +;; the whole table, as in the unsplit form: one `where:` is not a sequence +;; of selects (#904) +(set R (select {from: W where: (== (and (== a 'A1) (< (sums x) 200)) true) take: 100})) +(set S (select {from: W where: (and (== a 'A1) (< (sums x) 200)) take: 100})) +(count S) -- 10 +(at S 'x) -- (at R 'x) +(at (select {from: W where: (and (== a 'A1) (> x (avg x))) take: 3}) 'x) -- (at (select {from: W where: (== (and (== a 'A1) (> x (avg x))) true) take: 3}) 'x) + +;; `like` and `in` outer terms +(set R (select {from: W where: (== (and (== a 'A1) (like b "B[1-3]")) true) take: 10000})) +(set S (select {from: W where: (and (== a 'A1) (like b "B[1-3]")) take: 10000})) +(count S) -- (count R) +(at S 'x) -- (at R 'x) +(set R (select {from: W where: (== (and (== a 'A1) (in b ['B1 'B5])) true) take: 10000})) +(set S (select {from: W where: (and (== a 'A1) (in b ['B1 'B5])) take: 10000})) +(count S) -- (count R) +(at S 'x) -- (at R 'x) + +;; no row passes the inner terms, or the outer one; take 0 +(count (select {from: W where: (and (or (== a 'A2) (== b 'B4)) (== b 'B5)) take: 5})) -- 0 +(count (select {from: W where: (and (or (== a 'A1) (== b 'B4)) (== x -1)) take: 5})) -- 0 +(count (select {from: W where: (and (or (== a 'A1) (== b 'B4)) (!= b 'B8)) take: 0})) -- 0 + +;; parted: every `and` takes the split path +(set R (select {from: PW where: (== (and (== a 'A1) (!= b 'B7)) true) take: 1500})) +(set S (select {from: PW where: (and (== a 'A1) (!= b 'B7)) take: 1500})) +(count S) -- 1200 +(at S 'x) -- (at R 'x) +(at S 'b) -- (at R 'b) +(sum (nil? (at S 'n))) -- 400 +(set S (select {from: PW where: (and (and (== a 'A1) (!= b 'B7)) (!= b 'B8)) take: 600})) +(at S 'x) -- (take (at (select {from: W where: (and (== a 'A1) (!= b 'B7) (!= b 'B8))}) 'x) 600) +(set S (select {from: PW where: (and (or (== a 'A1) (== b 'B4)) (!= b 'B8)) take: 1200})) +(sum (as 'I64 (== (at S 'x) (take (at (select {from: W where: (and (or (== a 'A1) (== b 'B4)) (!= b 'B8))}) 'x) 1200)))) -- 1200 + +;; parted, generation 2: the outer term reads compressed columns +(.db.splayed.set "/tmp/rfl_wat/g2/2024.01.01/t/" (select {from: W where: (< x 1500)}) "/tmp/rfl_wat/g2/.sym" {compress: true}) +(.db.splayed.set "/tmp/rfl_wat/g2/2024.01.02/t/" (select {from: W where: (and (>= x 1500) (< x 2200))}) "/tmp/rfl_wat/g2/.sym" {compress: true}) +(.db.splayed.set "/tmp/rfl_wat/g2/2024.01.03/t/" (select {from: W where: (>= x 2200)}) "/tmp/rfl_wat/g2/.sym" {compress: true}) +(set P2 (.db.parted.get "/tmp/rfl_wat/g2/" 't)) +(set R (select {from: P2 where: (== (and (== a 'A1) (!= b 'B7)) true) take: 1500})) +(set S (select {from: P2 where: (and (== a 'A1) (!= b 'B7)) take: 1500})) +(count S) -- 1200 +(at S 'x) -- (at R 'x) +(sum (nil? (at S 'n))) -- 400 +(set R (select {from: P2 where: (== (and (or (== a 'A1) (== b 'B4)) (> n 100)) true) take: 1200})) +(set S (select {from: P2 where: (and (or (== a 'A1) (== b 'B4)) (> n 100)) take: 1200})) +(count S) -- (count R) +(at S 'x) -- (at R 'x) +(at S 'b) -- (at R 'b) +(at (select {from: P2 where: (and (== a 'A1) (!= b 'B7)) take: 3}) 'x) -- [3 5 7] +(.sys.exec "rm -rf /tmp/rfl_wat") diff --git a/test/rfl/query/where_row_domain_aggregate.rfl b/test/rfl/query/where_row_domain_aggregate.rfl new file mode 100644 index 000000000..64a3519ef --- /dev/null +++ b/test/rfl/query/where_row_domain_aggregate.rfl @@ -0,0 +1,24 @@ +;; A conjunct's aggregate reads the original WHERE input, not survivors +;; of another conjunct. This must hold for both AST construction and +;; optimizer splitting/reordering, including an unsafe nested subtree. +(set S (table [name room score] (list ['Ann 'Cid 'Bob 'Dan] ['A 'A 'B 'B] [60 45 20 35]))) +(at (select {from: S where: (and (== room 'A) (> score (avg score)))}) 'name) -- ['Ann 'Cid] +(at (select {from: S where: (and (> score (avg score)) (== room 'A))}) 'name) -- ['Ann 'Cid] +(at (select {from: S where: (and (== room 'A) (> score (avg score))) take: 5}) 'name) -- ['Ann 'Cid] +(at (select {from: S where: (and (and (== room 'A) (> score (avg score))) (< score 70))}) 'name) -- ['Ann 'Cid] +(at (select {from: S where: (and (and (== room 'A) (< score 70)) (> score (avg score)))}) 'name) -- ['Ann 'Cid] +(at (select {from: S where: (== (and (== room 'A) (> score (avg score))) true)}) 'name) -- ['Ann 'Cid] +(first (at (select {from: S where: (and (== room 'A) (> score (avg score))) take: 1}) 'name)) -- 'Ann +(count (select {from: S where: (and (== room 'A) (> score (avg score))) take: 0})) -- 0 +;; Legitimate SELECT reductions still consume WHERE survivors. +(first (at (select {a: (avg score) s: (sum score) from: S where: (== room 'A)}) 'a)) -- 52.5 +(first (at (select {a: (avg score) s: (sum score) from: S where: (== room 'A)}) 's)) -- 105 +(at (select {from: S where: (and (> score 20) (< score 60))}) 'name) -- ['Cid 'Dan] +;; A captured row-aligned vector is not a scalar broadcast after a gather. +(set aligned_scores [60 45 20 35]) +(at (select {from: S where: (and (== room 'A) (== score aligned_scores)) take: 5}) 'name) -- ['Ann 'Cid] +;; Nonlocal descendants remain nonlocal through OR and a hidden IF branch. +(at (select {from: S where: (and (== room 'A) (or (> score (avg score)) (== name 'Nobody)))}) 'name) -- ['Ann 'Cid] +(at (select {from: S where: (and (== room 'A) (if (== room 'A) (> score (avg score)) false))}) 'name) -- ['Ann 'Cid] +;; A genuine nested SELECT establishes a new logical input domain. +(at (select {from: (select {from: S where: (== room 'A)}) where: (> score (avg score))}) 'name) -- ['Ann] diff --git a/test/rfl/query/where_row_domain_projection.rfl b/test/rfl/query/where_row_domain_projection.rfl new file mode 100644 index 000000000..426f7cc57 --- /dev/null +++ b/test/rfl/query/where_row_domain_projection.rfl @@ -0,0 +1,54 @@ +;; A running, moving or order verb in a projection reads its input over +;; the whole table, rows the WHERE drops included, then keeps the WHERE's +;; rows. Its input's producer must therefore write every row: a binary op +;; under the lazy selection skips whole 1024-row blocks with no kept row. +(set N 200000) +(set x (til N)) +(set T (table [order region amount] (list x (at ['US 'EU] (as 'I64 (or (< x 1024) (>= x 199000)))) (+ 1 (* 0 x))))) +(set T (update {from: T amount: (if (== 5 (% order 10)) 0Nl amount)})) +(set W (fn [v] (at v (at (select {from: T where: (== region 'EU)}) 'order)))) +(set P (* (fills (at T 'amount)) 2)) +(set S (fn [] (last (at (select {from: T where: (== region 'EU) s: (sums (* (fills amount) 2))}) 's)))) +(S) -- 400000 +(S) -- 400000 +(last (at (select {from: T where: (== region 'EU) s: (sums (* (fills amount) 2)) take: 5000}) 's)) -- 400000 +(last (at (select {from: T where: (== region 'EU) s: (sums (* (fills amount) 2)) sort: order}) 's)) -- 400000 +(at (select {from: T where: (== region 'EU) by: region s: (last (sums (* (fills amount) 2)))}) 's) -- [400000] +;; Every kept row, against the verb over the whole column. +(at (select {from: T where: (== region 'EU) o: order s: (sums (* (fills amount) 2))}) 's) -- (W (sums P)) +(set V (* (fills (at T 'amount)) (at T 'order))) +(set K (fn [v] (at v [0 2048]))) +;; Row 2048 opens a block after one the WHERE drops whole: a verb reading +;; the row before it reads a row the binary op would leave unwritten. +(at (select {from: T where: (in order [0 2048]) s: (deltas (* (fills amount) order))}) 's) -- (K (deltas V)) +(at (select {from: T where: (in order [0 2048]) s: (ratios (* (fills amount) order))}) 's) -- (K (ratios V)) +(at (select {from: T where: (in order [0 2048]) s: (lag (* (fills amount) order))}) 's) -- (K (lag V)) +(at (select {from: T where: (in order [0 2048]) s: (msum 3 (* (fills amount) order))}) 's) -- (K (msum 3 V)) +;; Other producers that skip or zero-fill dropped rows: the SYM like +;; kernel, and `if` with a branch that is not a bare column or literal. +;; An eager `if` takes a vector condition as one truth value, so its +;; row-wise oracle is `update`, which evaluates over the whole table. +(at (select {from: T where: (== region 'EU) s: (sums (as 'I64 (like region "U*")))}) 's) -- (W (sums (as 'I64 (like (at T 'region) "U*")))) +(at (select {from: T where: (== region 'EU) s: (sums (if (== region 'EU) 0 (* amount 3)))}) 's) -- (W (at (update {from: T s: (sums (if (== region 'EU) 0 (* amount 3)))}) 's)) +;; Whole-table rule on a small table: running verbs see rows B too, an +;; aggregate and a nested select as from: see the survivors only. +(set R (table [name room score] (list ['Ann 'Bob 'Cid 'Dan] ['A 'B 'A 'B] [60 20 45 35]))) +(at (select {from: R where: (== room 'A) s: (sums score)}) 's) -- [60 125] +(at (select {from: R where: (== room 'A) s: (deltas score)}) 's) -- [0Nl 25] +(at (select {from: (select {from: R where: (== room 'A)}) s: (sums score)}) 's) -- [60 105] +(at (select {from: R where: (== room 'A) s: (avg score)}) 's) -- [52.5] +;; The aggregate nested under the running verb sees the whole table too: +;; avg over all four rows is 40, the running sum of 20 -20 5 -5 is +;; 20 0 5 0, and rows A keep 20 and 5. +(at (select {from: R where: (== room 'A) s: (sums (- score (avg score)))}) 's) -- [20.0 5.0] +;; A `let` value used both under a running verb and outside it is one +;; value per row domain: whole table under sums, the kept rows elsewhere. +;; The expansion and the swapped `if` give the same result. +(at (select {from: R where: (== room 'A) s: (let x (* score (count score)) (+ (sums x) (max x)))}) 's) -- [360 620] +(at (select {from: R where: (== room 'A) s: (+ (sums (* score (count score))) (max (* score (count score))))}) 's) -- [360 620] +(at (select {from: R where: (== room 'A) s: (let p (- score (avg score)) (if (<= score 50) (sums p) p))}) 's) -- [7.5 5.0] +(at (select {from: R where: (== room 'A) s: (let p (- score (avg score)) (if (> score 50) p (sums p)))}) 's) -- [7.5 5.0] +;; A `let` value the `if` reads under the selection, then sums over every +;; row: the binary op under the selection skips the dropped blocks. +(set E (as 'I64 (== 0 (% (at T 'order) 2)))) +(at (select {from: T where: (== region 'EU) s: (let p (* (fills amount) 2) (if (== 0 (% order 2)) p (sums p)))}) 's) -- (W (+ (* E P) (* (- 1 E) (sums P)))) diff --git a/test/rfl/query/where_row_domain_running.rfl b/test/rfl/query/where_row_domain_running.rfl new file mode 100644 index 000000000..5b2662ab1 --- /dev/null +++ b/test/rfl/query/where_row_domain_running.rfl @@ -0,0 +1,18 @@ +;; The running predicate needs actual contributions from every original +;; row, including whole morsels rejected by its sibling conjunct. Filling +;; unproduced lanes with zero is not a semantic repair. +(set N 200000) +(set x (til N)) +(set T (table [order region amount] (list x (at ['US 'EU] (as 'I64 (or (< x 1024) (>= x 199000)))) (+ 1 (* 0 x))))) +(set T (update {from: T amount: (if (== 5 (% order 10)) 0Nl amount)})) +(set Q (fn [] (count (select {from: T where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000))})))) +(set K (fn [] (count (select {from: T where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000)) take: 5000})))) +(set U (fn [] (count (select {from: T where: (== (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000)) true)})))) +(Q) -- 1000 +(K) -- 1000 +(U) -- 1000 +(Q) -- 1000 +(K) -- 1000 +;; Pin every surviving row, not only its count. +(at (select {from: T where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000))}) 'order) -- (+ 199000 (til 1000)) +(at (select {from: T where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000)) take: 5000}) 'order) -- (+ 199000 (til 1000)) diff --git a/test/rfl/query/where_row_domain_storage.rfl b/test/rfl/query/where_row_domain_storage.rfl new file mode 100644 index 000000000..de103f755 --- /dev/null +++ b/test/rfl/query/where_row_domain_storage.rfl @@ -0,0 +1,32 @@ +;; @requires: posix +;; The equivalence runner repeats saved-table fixtures with generation 2. +;; Relative paths stay inside the harness per-process working directory. +(.sys.exec "rm -rf rfl_where_row_domain") +(set S (table [name room score] (list ['Ann 'Cid 'Bob 'Dan] ['A 'A 'B 'B] [60 45 20 35]))) +(.db.splayed.set "rfl_where_row_domain/s/" S) +(set A (.db.splayed.get "rfl_where_row_domain/s/")) +(at (select {from: A where: (and (== room 'A) (> score (avg score)))}) 'name) -- ['Ann 'Cid] +(at (select {from: A where: (and (> score (avg score)) (== room 'A)) take: 5}) 'name) -- ['Ann 'Cid] +(first (at (select {a: (avg score) from: A where: (== room 'A)}) 'a)) -- 52.5 +(.db.splayed.set "rfl_where_row_domain/db/2024.01.01/s/" (table [name room score] (list ['Ann 'Cid] ['A 'A] [60 45]))) +(.db.splayed.set "rfl_where_row_domain/db/2024.01.02/s/" (table [name room score] (list ['Bob 'Dan] ['B 'B] [20 35]))) +(set P (.db.parted.get "rfl_where_row_domain/db/" 's)) +(at (select {from: P where: (and (== room 'A) (> score (avg score)))}) 'name) -- ['Ann 'Cid] +(at (select {from: P where: (and (> score (avg score)) (== room 'A)) take: 5}) 'name) -- ['Ann 'Cid] +(first (at (select {a: (avg score) from: P where: (== room 'A)}) 'a)) -- 52.5 +(set x (til 200000)) +(set T (table [order region amount] (list x (at ['US 'EU] (as 'I64 (or (< x 1024) (>= x 199000)))) (+ 1 (* 0 x))))) +(set T (update {from: T amount: (if (== 5 (% order 10)) 0Nl amount)})) +(.db.splayed.set "rfl_where_row_domain/t/" T) +(set B (.db.splayed.get "rfl_where_row_domain/t/")) +(count (select {from: B where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000))})) -- 1000 +(count (select {from: B where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000)) take: 5000})) -- 1000 +(.db.splayed.set "rfl_where_row_domain/p/2024.01.01/t/" (select {from: T where: (< order 65536)})) +(.db.splayed.set "rfl_where_row_domain/p/2024.01.02/t/" (select {from: T where: (and (>= order 65536) (< order 131072))})) +(.db.splayed.set "rfl_where_row_domain/p/2024.01.03/t/" (select {from: T where: (>= order 131072)})) +(set R (.db.parted.get "rfl_where_row_domain/p/" 't)) +(count (select {from: R where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000))})) -- 1000 +(count (select {from: R where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000)) take: 5000})) -- 1000 +(at (select {from: B where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000))}) 'order) -- (+ 199000 (til 1000)) +(at (select {from: R where: (and (== region 'EU) (>= (sums (* (fills amount) 2)) 398000)) take: 5000}) 'order) -- (+ 199000 (til 1000)) +(.sys.exec "rm -rf rfl_where_row_domain") -- 0 diff --git a/test/rfl/query/window.rfl b/test/rfl/query/window.rfl index ba65e8ffc..0f54ad00f 100644 --- a/test/rfl/query/window.rfl +++ b/test/rfl/query/window.rfl @@ -65,6 +65,53 @@ (at FV 'l) -- [3.5 3.5 20.0 3.5 20.0] (.sys.exec "rm -f /tmp/rfl_window_f32.csv") +;; ── composite radix prescan over full-span, nullable or F64 keys ──────────── +;; The per-key span kmax - kmin overflowed i64 (UBSan abort) when a key spans +;; more than INT64_MAX, or when the 0N sentinel sits next to a positive key. +;; Checked against the same running window over a small-span key with the same +;; partitions. 200 rows take the serial prescan, 10000 rows the pooled one. +;; The same blocks cover an F64 order key: the serial prescan had no F64 arm, +;; so the key got a 1-bit span and the composite OR-ed raw float bits into the +;; partition bits. A mixed-sign F64 key of large magnitude (±1e300) checks +;; that both prescans take min/max in the encoded order (positives used to +;; sort before negatives), against an I64 surrogate o of the same order. A +;; nullable F64 order key must place its null first, as the single-key window +;; and xasc do, at every row count (it went last on the composite path). +(set WR (fn [t] (at (window {from: t part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs))) +(set W1 (fn [t] (at (window {from: t order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs))) +(set WP (fn [n] (take [0 0 0 0 1 1 1 1] n))) +(set WF (fn [n] (concat (as 'F64 (til (- n 1))) [0Nf]))) +(set WT (WF 60)) +(WR (table [k o v] (list (take [0] 60) WT (til 60)))) -- (W1 (table [o v] (list WT (til 60)))) +(last (WR (table [k o v] (list (take [0] 60) WT (til 60))))) -- 59 +(set WN 200) +(set WV (til WN)) +(set WO (- WN WV)) +(set WS (at (window {from: (table [k o v] (list (% WV 2) WO WV)) part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs)) +(first WS) -- 9900 +(at (window {from: (table [k o v] (list (take [-9000000000000000000 9000000000000000000] WN) WO WV)) part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs) -- WS +(at (window {from: (table [k o v] (list (take [0N 5] WN) WO WV)) part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs) -- WS +(WR (table [k o v] (list (% WV 2) (* 0.5 (as 'F64 WO)) WV))) -- WS +(WR (table [k o v] (list (WP WN) (take [1e300 -1e300 2e300 -2e300] WN) WV))) -- (WR (table [k o v] (list (WP WN) (take [1 -1 2 -2] WN) WV))) +(set WT (WF WN)) +(WR (table [k o v] (list (take [0] WN) WT WV))) -- (W1 (table [o v] (list WT WV))) +(last (WR (table [k o v] (list (take [0] WN) WT WV)))) -- (- WN 1) +(set WN 10000) +(set WV (til WN)) +(set WO (- WN WV)) +(set WS (at (window {from: (table [k o v] (list (% WV 2) WO WV)) part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs)) +(first WS) -- 24995000 +(at (window {from: (table [k o v] (list (take [-9000000000000000000 9000000000000000000] WN) WO WV)) part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs) -- WS +(at (window {from: (table [k o v] (list (take [0N 5] WN) WO WV)) part: [k] order: [o] frame: 'running funcs: {cs: (sum v)}}) 'cs) -- WS +(WR (table [k o v] (list (% WV 2) (* 0.5 (as 'F64 WO)) WV))) -- WS +(WR (table [k o v] (list (WP WN) (take [1e300 -1e300 2e300 -2e300] WN) WV))) -- (WR (table [k o v] (list (WP WN) (take [1 -1 2 -2] WN) WV))) +(set WT (WF WN)) +(WR (table [k o v] (list (take [0] WN) WT WV))) -- (W1 (table [o v] (list WT WV))) +(last (WR (table [k o v] (list (take [0] WN) WT WV)))) -- (- WN 1) +(set WN 20000) +(set WV (til WN)) +(WR (table [k o v] (list (WP WN) (take [1e300 -1e300 2e300 -2e300] WN) WV))) -- (WR (table [k o v] (list (WP WN) (take [1 -1 2 -2] WN) WV))) + ;; ── fby shape: rows equal to their group's min (keeps ties) ───────────────── ;; min over k: a→2 (only row v=2), b→4 (rows v=4,4 both) → 3 rows total (count (select {from: (window {from: T part: [k] funcs: {mn: (min v)}}) where: (== v mn)})) -- 3 diff --git a/test/rfl/sort/sort_coverage2.rfl b/test/rfl/sort/sort_coverage2.rfl index e0b34c284..9b09cf11f 100644 --- a/test/rfl/sort/sort_coverage2.rfl +++ b/test/rfl/sort/sort_coverage2.rfl @@ -651,3 +651,46 @@ (set T256 (table [d000 d001 d002 d003 d004 d005 d006 d007 d008 d009 d010 d011 d012 d013 d014 d015 d016 d017 d018 d019 d020 d021 d022 d023 d024 d025 d026 d027 d028 d029 d030 d031 d032 d033 d034 d035 d036 d037 d038 d039 d040 d041 d042 d043 d044 d045 d046 d047 d048 d049 d050 d051 d052 d053 d054 d055 d056 d057 d058 d059 d060 d061 d062 d063 d064 d065 d066 d067 d068 d069 d070 d071 d072 d073 d074 d075 d076 d077 d078 d079 d080 d081 d082 d083 d084 d085 d086 d087 d088 d089 d090 d091 d092 d093 d094 d095 d096 d097 d098 d099 d100 d101 d102 d103 d104 d105 d106 d107 d108 d109 d110 d111 d112 d113 d114 d115 d116 d117 d118 d119 d120 d121 d122 d123 d124 d125 d126 d127 d128 d129 d130 d131 d132 d133 d134 d135 d136 d137 d138 d139 d140 d141 d142 d143 d144 d145 d146 d147 d148 d149 d150 d151 d152 d153 d154 d155 d156 d157 d158 d159 d160 d161 d162 d163 d164 d165 d166 d167 d168 d169 d170 d171 d172 d173 d174 d175 d176 d177 d178 d179 d180 d181 d182 d183 d184 d185 d186 d187 d188 d189 d190 d191 d192 d193 d194 d195 d196 d197 d198 d199 d200 d201 d202 d203 d204 d205 d206 d207 d208 d209 d210 d211 d212 d213 d214 d215 d216 d217 d218 d219 d220 d221 d222 d223 d224 d225 d226 d227 d228 d229 d230 d231 d232 d233 d234 d235 d236 d237 d238 d239 d240 d241 d242 d243 d244 d245 d246 d247 d248 d249 d250 d251 d252 d253 d254 sk pay] (concat (take (list [0 0]) 255) (list [2 1] [20 10])))) (count (xasc T256 ['d000 'd001 'd002 'd003 'd004 'd005 'd006 'd007 'd008 'd009 'd010 'd011 'd012 'd013 'd014 'd015 'd016 'd017 'd018 'd019 'd020 'd021 'd022 'd023 'd024 'd025 'd026 'd027 'd028 'd029 'd030 'd031 'd032 'd033 'd034 'd035 'd036 'd037 'd038 'd039 'd040 'd041 'd042 'd043 'd044 'd045 'd046 'd047 'd048 'd049 'd050 'd051 'd052 'd053 'd054 'd055 'd056 'd057 'd058 'd059 'd060 'd061 'd062 'd063 'd064 'd065 'd066 'd067 'd068 'd069 'd070 'd071 'd072 'd073 'd074 'd075 'd076 'd077 'd078 'd079 'd080 'd081 'd082 'd083 'd084 'd085 'd086 'd087 'd088 'd089 'd090 'd091 'd092 'd093 'd094 'd095 'd096 'd097 'd098 'd099 'd100 'd101 'd102 'd103 'd104 'd105 'd106 'd107 'd108 'd109 'd110 'd111 'd112 'd113 'd114 'd115 'd116 'd117 'd118 'd119 'd120 'd121 'd122 'd123 'd124 'd125 'd126 'd127 'd128 'd129 'd130 'd131 'd132 'd133 'd134 'd135 'd136 'd137 'd138 'd139 'd140 'd141 'd142 'd143 'd144 'd145 'd146 'd147 'd148 'd149 'd150 'd151 'd152 'd153 'd154 'd155 'd156 'd157 'd158 'd159 'd160 'd161 'd162 'd163 'd164 'd165 'd166 'd167 'd168 'd169 'd170 'd171 'd172 'd173 'd174 'd175 'd176 'd177 'd178 'd179 'd180 'd181 'd182 'd183 'd184 'd185 'd186 'd187 'd188 'd189 'd190 'd191 'd192 'd193 'd194 'd195 'd196 'd197 'd198 'd199 'd200 'd201 'd202 'd203 'd204 'd205 'd206 'd207 'd208 'd209 'd210 'd211 'd212 'd213 'd214 'd215 'd216 'd217 'd218 'd219 'd220 'd221 'd222 'd223 'd224 'd225 'd226 'd227 'd228 'd229 'd230 'd231 'd232 'd233 'd234 'd235 'd236 'd237 'd238 'd239 'd240 'd241 'd242 'd243 'd244 'd245 'd246 'd247 'd248 'd249 'd250 'd251 'd252 'd253 'd254 'sk])) -- 2 (at (xasc T256 ['d000 'd001 'd002 'd003 'd004 'd005 'd006 'd007 'd008 'd009 'd010 'd011 'd012 'd013 'd014 'd015 'd016 'd017 'd018 'd019 'd020 'd021 'd022 'd023 'd024 'd025 'd026 'd027 'd028 'd029 'd030 'd031 'd032 'd033 'd034 'd035 'd036 'd037 'd038 'd039 'd040 'd041 'd042 'd043 'd044 'd045 'd046 'd047 'd048 'd049 'd050 'd051 'd052 'd053 'd054 'd055 'd056 'd057 'd058 'd059 'd060 'd061 'd062 'd063 'd064 'd065 'd066 'd067 'd068 'd069 'd070 'd071 'd072 'd073 'd074 'd075 'd076 'd077 'd078 'd079 'd080 'd081 'd082 'd083 'd084 'd085 'd086 'd087 'd088 'd089 'd090 'd091 'd092 'd093 'd094 'd095 'd096 'd097 'd098 'd099 'd100 'd101 'd102 'd103 'd104 'd105 'd106 'd107 'd108 'd109 'd110 'd111 'd112 'd113 'd114 'd115 'd116 'd117 'd118 'd119 'd120 'd121 'd122 'd123 'd124 'd125 'd126 'd127 'd128 'd129 'd130 'd131 'd132 'd133 'd134 'd135 'd136 'd137 'd138 'd139 'd140 'd141 'd142 'd143 'd144 'd145 'd146 'd147 'd148 'd149 'd150 'd151 'd152 'd153 'd154 'd155 'd156 'd157 'd158 'd159 'd160 'd161 'd162 'd163 'd164 'd165 'd166 'd167 'd168 'd169 'd170 'd171 'd172 'd173 'd174 'd175 'd176 'd177 'd178 'd179 'd180 'd181 'd182 'd183 'd184 'd185 'd186 'd187 'd188 'd189 'd190 'd191 'd192 'd193 'd194 'd195 'd196 'd197 'd198 'd199 'd200 'd201 'd202 'd203 'd204 'd205 'd206 'd207 'd208 'd209 'd210 'd211 'd212 'd213 'd214 'd215 'd216 'd217 'd218 'd219 'd220 'd221 'd222 'd223 'd224 'd225 'd226 'd227 'd228 'd229 'd230 'd231 'd232 'd233 'd234 'd235 'd236 'd237 'd238 'd239 'd240 'd241 'd242 'd243 'd244 'd245 'd246 'd247 'd248 'd249 'd250 'd251 'd252 'd253 'd254 'sk]) 'pay) -- [10 20] + +;; ── composite sort over a mixed-sign F64 key of large magnitude ───────────── +;; The composite prescans took SIGNED min/max over the unsigned-ordered F64 +;; encoding: with values like ±1e300 the span fit ~58 bits, the direct +;; composite ran, and every positive sorted before every negative within a +;; k. Checked against an I64 surrogate s with the same order as f. 100 rows +;; take the serial prescan + introsort, 6000 the serial prescan + radix +;; (RADIX_SORT_THRESHOLD 4096 < n < SMALL_POOL_THRESHOLD 8192), 20000 the +;; pooled prescan + radix. +(set FS (fn [n] (table [k f s] (list (take [0 0 0 0 1 1 1 1] n) (take [1e300 -1e300 2e300 -2e300] n) (take [1 -1 2 -2] n))))) +(set Tfs (FS 100)) +(at (at (xasc Tfs [k f]) 'f) [0 13 26 39 52 65 78 91]) -- [-2e300 -1e300 1e300 2e300 -2e300 -1e300 1e300 2e300] +(at (xasc Tfs [k f]) 'f) -- (at (xasc Tfs [k s]) 'f) +(at (xdesc Tfs [k f]) 'f) -- (at (xdesc Tfs [k s]) 'f) +(set Tfs (FS 6000)) +(at (xasc Tfs [k f]) 'f) -- (at (xasc Tfs [k s]) 'f) +(at (xdesc Tfs [k f]) 'f) -- (at (xdesc Tfs [k s]) 'f) +(set Tfs (FS 20000)) +(at (xasc Tfs [k f]) 'f) -- (at (xasc Tfs [k s]) 'f) +(at (xdesc Tfs [k f]) 'f) -- (at (xdesc Tfs [k s]) 'f) + +;; ── composite sort over a nullable F64 key ────────────────────────────────── +;; A float null is NaN; packed by its bits it went above every real number, +;; so a multi-key sort placed it last above 64 rows and first (comparator) +;; below. The composite now reserves the slot below the key's minimum for +;; nulls: first on ascending, last on descending, at every row count, as the +;; I64 surrogate s (0N is INT64_MIN) and the single-key sort place theirs. +(set FN (fn [n] (table [k f s] (list (take [0 0 0 0 1 1 1 1] n) (take [1.5 0Nf -2.5 3.5] n) (take [1 0N -2 3] n))))) +(set Tfn (FN 100)) +(at (at (xasc Tfn [k f]) 'f) [0 13 26 39 52 64 76 88]) -- [0Nf -2.5 1.5 3.5 0Nf -2.5 1.5 3.5] +(at (xasc Tfn [k f]) 'f) -- (at (xasc Tfn [k s]) 'f) +(at (xdesc Tfn [k f]) 'f) -- (at (xdesc Tfn [k s]) 'f) +(at (xasc Tfn [k f]) 's) -- (at (xasc Tfn [k s]) 's) +(set Tfn (FN 6000)) +(at (xasc Tfn [k f]) 'f) -- (at (xasc Tfn [k s]) 'f) +(at (xdesc Tfn [k f]) 'f) -- (at (xdesc Tfn [k s]) 'f) +(set Tfn (FN 20000)) +(at (xasc Tfn [k f]) 'f) -- (at (xasc Tfn [k s]) 'f) +(at (xdesc Tfn [k f]) 'f) -- (at (xdesc Tfn [k s]) 'f) +;; every row null in the float key: a single slot, the other key decides +(set Tfa (table [k f v] (list (take [1 0] 6000) (take [0Nf] 6000) (til 6000)))) +(at (xasc Tfa [k f]) 'k) -- (at (xasc Tfa [k]) 'k) +(sum (at (xasc Tfa [f k]) 'v)) -- 17997000 diff --git a/test/rfl/sort/sort_many_repeated_keys.rfl b/test/rfl/sort/sort_many_repeated_keys.rfl new file mode 100644 index 000000000..ab2f6ea03 --- /dev/null +++ b/test/rfl/sort/sort_many_repeated_keys.rfl @@ -0,0 +1,10 @@ +;; Repeated names are valid sort keys. The 300k-key list needs heap storage, +;; even for a tiny table whose keys all tie and take the sorted shortcut. +(set keys (take [s] 300000)) +(set symbols (table [s row] (list [same-key same-key] [2 1]))) +(at (xasc symbols keys) 'row) -- [2 1] +(at (xdesc symbols keys) 'row) -- [2 1] +;; Integer checks must also avoid per-key stack buffers. +(set integers (table [s row] (list [7 7] [2 1]))) +(at (xasc integers keys) 'row) -- [2 1] +(at (xdesc integers keys) 'row) -- [2 1] diff --git a/test/rfl/sort/sorted_symbol_ranks.rfl b/test/rfl/sort/sorted_symbol_ranks.rfl new file mode 100644 index 000000000..5f6d578a5 --- /dev/null +++ b/test/rfl/sort/sorted_symbol_ranks.rfl @@ -0,0 +1,18 @@ +;; Lexical order differs from symbol creation order. Prefixes and equal-key +;; rows check lexical ranking and stable row order through xasc/xdesc. +(set syms [rank-z rank-a rank-aa rank-a rank-z rank-aa rank-a]) +(set times (as 'TIMESTAMP [2 1 1 2 1 2 1])) +(set t (table [ts sym row] (list times syms (til 7)))) +(set asc_ts (xasc t [ts sym])) +(at asc_ts 'row) -- [1 6 2 4 3 5 0] +(at (xasc asc_ts [ts sym]) 'row) -- [1 6 2 4 3 5 0] +(at (xasc (reverse t) [ts sym]) 'row) -- [6 1 2 4 3 5 0] +(set desc_ts (xdesc t [ts sym])) +(at desc_ts 'row) -- [0 5 3 4 2 1 6] +(at (xdesc desc_ts [ts sym]) 'row) -- [0 5 3 4 2 1 6] +(set asc_sym (xasc t [sym ts])) +(at asc_sym 'row) -- [1 6 3 2 5 4 0] +(at (xasc asc_sym [sym ts]) 'row) -- [1 6 3 2 5 4 0] +(set desc_sym (xdesc t [sym ts])) +(at desc_sym 'row) -- [0 4 5 2 3 1 6] +(at (xdesc desc_sym [sym ts]) 'row) -- [0 4 5 2 3 1 6] diff --git a/test/rfl/sort/sorted_symbol_sparse_parted.rfl b/test/rfl/sort/sorted_symbol_sparse_parted.rfl new file mode 100644 index 000000000..280c0e16e --- /dev/null +++ b/test/rfl/sort/sorted_symbol_sparse_parted.rfl @@ -0,0 +1,27 @@ +;; @requires: posix +;; Populate the database FILE domain before writing the used symbol. Merely +;; interning unrelated runtime names would not give the file column high IDs. +(.sys.exec "rm -rf /tmp/rfl_sparse_rank_parts") +(set padding (as 'SYM (map (fn [i] (format "unused-rank-%" i)) (til 70000)))) +(.db.splayed.set "/tmp/rfl_sparse_rank_parts/2024.01.01/padding/" (table [s] (list padding))) +(set late (take [late-sorted-key] 10000)) +(.db.splayed.set "/tmp/rfl_sparse_rank_parts/2024.01.01/t/" (table [s seq] (list late (til 10000)))) +(.db.splayed.set "/tmp/rfl_sparse_rank_parts/2024.01.02/t/" (table [s seq] (list late (+ 10000 (til 10000))))) +(set parts (.db.parted.get "/tmp/rfl_sparse_rank_parts/" 't)) +;; Each 10k-row segment is within the rank builder's density budget. Repeated +;; calls must preserve streaming without preparing a 70k-ID LUT per segment. +(set before (at (.sys.mem) 'sort-perpart-runs)) +(set first (select {from: parts asc: s})) +(set second (select {from: parts desc: s})) +(- (at (.sys.mem) 'sort-perpart-runs) before) -- 4 +(at first 'seq) -- (til 20000) +(at second 'seq) -- (til 20000) +;; Eight-row segments exceed the LUT density budget but are still sorted. +(.db.splayed.set "/tmp/rfl_sparse_rank_parts/2024.01.01/tiny/" (table [s seq] (list (take late 8) (til 8)))) +(.db.splayed.set "/tmp/rfl_sparse_rank_parts/2024.01.02/tiny/" (table [s seq] (list (take late 8) (+ 8 (til 8))))) +(set tiny (.db.parted.get "/tmp/rfl_sparse_rank_parts/" 'tiny)) +(set before (at (.sys.mem) 'sort-perpart-runs)) +(set result (select {from: tiny asc: s})) +(- (at (.sys.mem) 'sort-perpart-runs) before) -- 2 +(at result 'seq) -- (til 16) +(.sys.exec "rm -rf /tmp/rfl_sparse_rank_parts") diff --git a/test/rfl/storage/compress_aware.rfl b/test/rfl/storage/compress_aware.rfl new file mode 100644 index 000000000..fd135a7b3 --- /dev/null +++ b/test/rfl/storage/compress_aware.rfl @@ -0,0 +1,74 @@ +;; @requires: posix (cleanup runs through a POSIX shell via .sys.exec) +;; Compressed-columns P3: the encoding-aware operator paths over a +;; generation-2 splayed table answer exactly as over the generation-0 copy +;; of the same data. Each table has its own symbol file, so its SYM +;; columns are file-domain and the "" compares translate the literal into +;; that domain. The P2 scan shapes (compress_scan.rfl) carry, plus the +;; shapes P3 reads on codes, statistics, views and point reads. +(.sys.exec "rm -rf /tmp/rf_test_caware") -- 0 +(set i (til 150000)) +(set T (table [k g v d s e b u h n w t] (list i (as 'I16 (% i 9)) (as 'I32 (map (fn [j] (if (== 0 (% j 11)) 0N j)) i)) (as 'DATE (% i 900)) (take ['x 'y 'z] 150000) (as 'SYM (take ["p" "" "q" "r"] 150000)) (== 0 (% i 3)) (as 'U8 (% i 200)) (% (* i 7919) 1000003) (map (fn [j] (if (== 0 (% j 7)) 0N (% (* j 31) 1009))) i) (take [9223372036854775807 -9223372036854775807 9223372036854775806 -9223372036854775806 1] 150000) (map (fn [j] (format "text %" (% j 333))) i)))) +(.db.splayed.set "/tmp/rf_test_caware/g2/" T "/tmp/rf_test_caware/g2.sym" {compress: true}) +(.db.splayed.set "/tmp/rf_test_caware/g0/" T "/tmp/rf_test_caware/g0.sym" {compress: false}) +(set A (.db.splayed.get "/tmp/rf_test_caware/g2/" "/tmp/rf_test_caware/g2.sym")) +(set B (.db.splayed.get "/tmp/rf_test_caware/g0/" "/tmp/rf_test_caware/g0.sym")) +(at (.idx.info A 'k) 'gen) -- 2 +(at (.idx.info B 'k) 'gen) -- 0 +;; the P2 scan shapes +(count (select {from: A where: (> v 70000)})) -- (count (select {from: B where: (> v 70000)})) +(count (select {from: A where: (== g 4)})) -- (count (select {from: B where: (== g 4)})) +(sum (at A 'v)) -- (sum (at B 'v)) +(min (at A 'k)) -- (min (at B 'k)) +(select {s: (sum v) from: A by: g}) -- (select {s: (sum v) from: B by: g}) +(select {c: (count k) from: A where: (== s 'y) by: g}) -- (select {c: (count k) from: B where: (== s 'y) by: g}) +(select {k: k from: A where: (> v 100) desc: k take: 3}) -- (select {k: k from: B where: (> v 100) desc: k take: 3}) +;; SYM != against "" on a column with "" rows (e) and without (s) +(count (select {from: A where: (!= e "")})) -- (count (select {from: B where: (!= e "")})) +(count (select {from: A where: (!= s "")})) -- (count (select {from: B where: (!= s "")})) +(select {c: (count k) from: A where: (!= e "") by: e asc: e}) -- (select {c: (count k) from: B where: (!= e "") by: e asc: e}) +;; == "" and != "" on a SYM column with and without "" rows +(count (select {from: A where: (== e "")})) -- (count (select {from: B where: (== e "")})) +(count (select {from: A where: (== s "")})) -- (count (select {from: B where: (== s "")})) +(select {k: k e: e from: A where: (== e "") take: 5}) -- (select {k: k e: e from: B where: (== e "") take: 5}) +;; the same compares by value: both tables are file-domain, so a wrong "" +;; translation would agree on both sides ("" is id 0 in every domain) +(count (select {from: A where: (!= e "")})) -- 112500 +(count (select {from: A where: (== e "")})) -- 37500 +(count (select {from: A where: (!= s "")})) -- 150000 +(count (select {from: A where: (== s "")})) -- 0 +(select {s: (sum u) from: A where: (and (!= e "") (!= s ""))}) -- (select {s: (sum u) from: B where: (and (!= e "") (!= s ""))}) +;; in / not in on integer columns +(count (select {from: A where: (in g [1 4 7])})) -- (count (select {from: B where: (in g [1 4 7])})) +(count (select {from: A where: (in h [0 7919 15838 999999])})) -- (count (select {from: B where: (in h [0 7919 15838 999999])})) +(count (select {from: A where: (not-in u [0 1 2 199])})) -- (count (select {from: B where: (not-in u [0 1 2 199])})) +(select {c: (count k) from: A where: (in v [11 12 13 22 70001]) by: g}) -- (select {c: (count k) from: B where: (in v [11 12 13 22 70001]) by: g}) +;; sum and avg at the I64 extremes +(sum (at A 'w)) -- (sum (at B 'w)) +(avg (at A 'w)) -- (avg (at B 'w)) +(select {s: (sum w) a: (avg w) mn: (min w) mx: (max w) from: A}) -- (select {s: (sum w) a: (avg w) mn: (min w) mx: (max w) from: B}) +(select {s: (sum w) a: (avg w) from: A where: (< g 4)}) -- (select {s: (sum w) a: (avg w) from: B where: (< g 4)}) +(select {s: (sum w) a: (avg w) from: A by: g}) -- (select {s: (sum w) a: (avg w) from: B by: g}) +;; top-k over a nullable key, both directions +(select {k: k n: n from: A desc: n take: 5}) -- (select {k: k n: n from: B desc: n take: 5}) +(select {k: k n: n from: A asc: n take: 5}) -- (select {k: k n: n from: B asc: n take: 5}) +(select {k: k n: n from: A where: (> g 2) desc: n take: 7}) -- (select {k: k n: n from: B where: (> g 2) desc: n take: 7}) +(select {k: k n: n from: A where: (> g 2) asc: n take: 7}) -- (select {k: k n: n from: B where: (> g 2) asc: n take: 7}) +(select {k: k v: v from: A asc: v take: 4}) -- (select {k: k v: v from: B asc: v take: 4}) +(select {k: k v: v from: A desc: v take: 4}) -- (select {k: k v: v from: B desc: v take: 4}) +;; a STR group key +(select {c: (count k) from: A by: t asc: t}) -- (select {c: (count k) from: B by: t asc: t}) +(select {c: (count k) s: (sum v) from: A where: (< g 3) by: t asc: t}) -- (select {c: (count k) s: (sum v) from: B where: (< g 3) by: t asc: t}) +;; the ClickBench-shaped P2 carries: q2, q8, q18, q39, q42 +(count (select {from: A where: (!= u 0)})) -- (count (select {from: B where: (!= u 0)})) +(select {u: u c: (count u) from: A where: (!= u 0) by: u desc: c take: 10}) -- (select {u: u c: (count u) from: B where: (!= u 0) by: u desc: c take: 10}) +(select {c: (count h) from: A by: {h: h s: s} take: 10}) -- (select {c: (count h) from: B by: {h: h s: s} take: 10}) +(take (select {s: s p: (count s) from: A where: (and (== g 3) (>= d 100) (<= d 400) (== b false) (!= u 0)) by: s desc: p take: 1010}) -10) -- (take (select {s: s p: (count s) from: B where: (and (== g 3) (>= d 100) (<= d 400) (== b false) (!= u 0)) by: s desc: p take: 1010}) -10) +(select {n: (count u) from: A where: (and (== s 'z) (>= d 100) (<= d 130) (== b false)) by: {u: u g: g} desc: n take: 10}) -- (select {n: (count u) from: B where: (and (== s 'z) (>= d 100) (<= d 130) (== b false)) by: {u: u g: g} desc: n take: 10}) +;; nothing above read these columns whole +(at (.idx.info A 'g) 'materialized) -- false +(at (.idx.info A 'u) 'materialized) -- false +(at (.idx.info A 'd) 'materialized) -- false +(at (.idx.info A 's) 'materialized) -- false +(at (.idx.info A 'e) 'materialized) -- false +(at (.idx.info A 'w) 'materialized) -- false +(.sys.exec "rm -rf /tmp/rf_test_caware") -- 0 diff --git a/test/rfl/storage/compress_float.rfl b/test/rfl/storage/compress_float.rfl new file mode 100644 index 000000000..0a337ef84 --- /dev/null +++ b/test/rfl/storage/compress_float.rfl @@ -0,0 +1,32 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) +;; Float encodings end to end (compressed-columns P5): generation-2 answers +;; equal generation 0, both zeros, NaN nulls. -0.0 appears only inside a +;; vector literal or alone in a form (#824: -0.0 and 0.0 merge inside one +;; lambda). +(.sys.exec "rm -rf /tmp/rf_test_p5fl") +(set n 200000) +(set i (til n)) +(set price (/ (as 'F64 (% (* i 7919) 100000)) 100.0)) +(set zs (at [-3.5 -0.0 0.0 2.25] (% (div i 3) 4))) +(set runs (as 'F64 (div i 5000))) +(set rnd (+ 1.0 (/ (as 'F64 (% (* i 2654435761) 1000003)) 1000003.0))) +(set nul (map (fn [j] (if (== 0 (% j 13)) 0Nf (as 'F64 j))) i)) +(set T (table [price zs runs rnd nul] (list price zs runs rnd nul))) +(.db.splayed.set "/tmp/rf_test_p5fl/g0/" T {compress: false}) +(.db.splayed.set "/tmp/rf_test_p5fl/g2/" T {compress: true}) +(set A (.db.splayed.get "/tmp/rf_test_p5fl/g0/")) +(set C (.db.splayed.get "/tmp/rf_test_p5fl/g2/")) +(count (select {from: C where: (== zs 0.0)})) -- (count (select {from: A where: (== zs 0.0)})) +(count (select {from: C where: (== zs -0.0)})) -- (count (select {from: A where: (== zs -0.0)})) +(count (select {from: C where: (< zs 0.0)})) -- (count (select {from: A where: (< zs 0.0)})) +(count (select {from: C where: (>= zs -0.0)})) -- (count (select {from: A where: (>= zs -0.0)})) +(count (select {from: C where: (> price 500.25)})) -- (count (select {from: A where: (> price 500.25)})) +(count (select {from: C where: (== runs 7.0)})) -- (count (select {from: A where: (== runs 7.0)})) +(count (select {from: C where: (> nul 1000.0)})) -- (count (select {from: A where: (> nul 1000.0)})) +(sum (at C 'price)) -- (sum (at A 'price)) +(avg (at C 'rnd)) -- (avg (at A 'rnd)) +(min (at C 'zs)) -- (min (at A 'zs)) +(max (at C 'nul)) -- (max (at A 'nul)) +(sum (at C 'nul)) -- (sum (at A 'nul)) +(at (select {p: price from: C desc: price take: 3}) 'p) -- (at (select {p: price from: A desc: price take: 3}) 'p) +(.sys.exec "rm -rf /tmp/rf_test_p5fl") -- 0 diff --git a/test/rfl/storage/compress_index.rfl b/test/rfl/storage/compress_index.rfl new file mode 100644 index 000000000..929467b3e --- /dev/null +++ b/test/rfl/storage/compress_index.rfl @@ -0,0 +1,69 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) +;; Indexed columns written as generation 2 (compressed-columns P4): every +;; persisted kind round-trips with generation-0 answers. +(.sys.exec "rm -rf /tmp/rf_test_p4idx /tmp/rf_test_p4idx_child.rfl /tmp/rf_test_p4idx_route.rfl") + +(set n 100000) +(set i (til n)) +(set K (.idx.hash (% (* i 7919) 100003))) +(set S (.idx.sort (as 'I32 (- (% (* i 31) 9973) 4000)))) +(set B (.idx.bloom (% (* i 17) 50021))) +(set P (.attr.set 'parted (div i 1000))) +(set Y (.attr.set 'grouped (at ['zeta 'alpha 'mu 'omega] (% i 4)))) +;; four ascending blocks; the -0.0 and +0.0 blocks merge into one PART block +;; whose key keeps the first row's sign (-0.0) +(set Z (.attr.set 'parted (at [-2.5 -0.0 0.0 1.5] (div (* i 4) n)))) +(set T (table [k s b p y z v] (list K S B P Y Z i))) +(.db.splayed.set "/tmp/rf_test_p4idx/g0/" T {compress: false}) +(.db.splayed.set "/tmp/rf_test_p4idx/g2/" T {compress: true}) +(set A (.db.splayed.get "/tmp/rf_test_p4idx/g0/")) +(set C (.db.splayed.get "/tmp/rf_test_p4idx/g2/")) + +;; generation 2 records the kinds, without materializing +(at (.idx.info C 'k) 'gen) -- 2 +(at (.idx.info C 'k) 'index) -- 'hash +(at (.idx.info C 's) 'index) -- 'sort +(at (.idx.info C 'b) 'index) -- 'bloom +(at (.idx.info C 'p) 'index) -- 'part +(at (.idx.info C 'y) 'index) -- 'hash +(at (.idx.info C 'z) 'index) -- 'part +(at (.idx.info C 'k) 'materialized) -- false + +;; equality, in, ranges, grouping: generation-0 answers (a projected column, +;; so the select runs the filter; count(select) would take the count fast +;; path, which consults no index) +(sum (at (select {from: C where: (== k 4242)}) 'v)) -- (sum (at (select {from: A where: (== k 4242)}) 'v)) +(sum (at (select {from: C where: (in k [1 2 3 4242])}) 'v)) -- (sum (at (select {from: A where: (in k [1 2 3 4242])}) 'v)) +(sum (at (select {from: C where: (> s 3000)}) 'v)) -- (sum (at (select {from: A where: (> s 3000)}) 'v)) +(sum (at (select {from: C where: (== p 77)}) 'v)) -- (sum (at (select {from: A where: (== p 77)}) 'v)) +(sum (at (select {from: C where: (== y 'mu)}) 'v)) -- (sum (at (select {from: A where: (== y 'mu)}) 'v)) +(select {c: (count v) from: C by: y asc: y}) -- (select {c: (count v) from: A by: y asc: y}) +(sum (at (select {from: C where: (== z 0.0)}) 'v)) -- (sum (at (select {from: A where: (== z 0.0)}) 'v)) +(sum (at (select {from: C where: (== z -0.0)}) 'v)) -- (sum (at (select {from: A where: (== z -0.0)}) 'v)) + +;; .attr.get after materialization, index kind on the column value +(.attr.get (at C 'y)) -- (.attr.get (at A 'y)) +(.attr.get (at C 'p)) -- (.attr.get (at A 'p)) +(at (.idx.info (at C 'k)) 'kind) -- 'hash + +;; as-of on a PART-indexed key ordered by time, in another process with a +;; different interning order: the name block, not the id, carries order_sym. +;; The key is I64: the as-of index variant needs a right side proven +;; null-free, and a SYM column never is (ray_vec_may_have_nulls), so a SYM +;; key never reaches the ordered route on either generation (#842). +;; xasc of an already ordered table stamps PART on id with order_sym ts +;; (sort_stamp_ordered_table, src/ops/sort.c): sort once, then again +(set Q (xasc (xasc (table [id ts bid] (list (% (til 3000) 3) (til 3000) (as 'F64 (til 3000)))) ['id 'ts]) ['id 'ts])) +(at (.idx.info (at Q 'id)) 'kind) -- 'part +(.db.splayed.set "/tmp/rf_test_p4idx/q2/" Q {compress: true}) +(.db.splayed.set "/tmp/rf_test_p4idx/q0/" Q {compress: false}) +(at (.idx.info (.db.splayed.get "/tmp/rf_test_p4idx/q2/") 'id) 'index) -- 'part +;; the answers: tables do not compare with ==, so column by column +(.sys.exec "printf '%s\n' '(set junk (map (fn [j] (as (quote SYMBOL) (format \"w%\" j))) (til 2000)))' '(set Q2 (.db.splayed.get \"/tmp/rf_test_p4idx/q2/\"))' '(set Q0 (.db.splayed.get \"/tmp/rf_test_p4idx/q0/\"))' '(set L (table [id ts] (list [0 1 2] [100 200 2999])))' '(set A2 (asof-join [id ts] L Q2))' '(set A0 (asof-join [id ts] L Q0))' '(println (and (== (count A2) (count A0)) (all (map (fn [c] (all (== (at A2 c) (at A0 c)))) (key A0)))))' > /tmp/rf_test_p4idx_child.rfl") -- 0 +;; the route, on the generation-2 load alone (generation 0 keeps an integer +;; PART's order too, so the answer script would show it either way) +(.sys.exec "printf '%s\n' '(set junk (map (fn [j] (as (quote SYMBOL) (format \"w%\" j))) (til 2000)))' '(set Q2 (.db.splayed.get \"/tmp/rf_test_p4idx/q2/\"))' '(set L (table [id ts] (list [0 1 2] [100 200 2999])))' '(println (count (asof-join [id ts] L Q2)))' > /tmp/rf_test_p4idx_route.rfl") -- 0 +(.sys.exec "RAY_IDX_STATS=1 ./rayforce -f /tmp/rf_test_p4idx_route.rfl 2>&1 | grep -q 'idx_route asof-ordered consults=1 '") -- 0 +(.sys.exec "./rayforce -f /tmp/rf_test_p4idx_child.rfl 2>/dev/null | tail -1 | grep -q true") -- 0 + +(.sys.exec "rm -rf /tmp/rf_test_p4idx /tmp/rf_test_p4idx_child.rfl /tmp/rf_test_p4idx_route.rfl") -- 0 diff --git a/test/rfl/storage/compress_scan.rfl b/test/rfl/storage/compress_scan.rfl new file mode 100644 index 000000000..9b448fdfc --- /dev/null +++ b/test/rfl/storage/compress_scan.rfl @@ -0,0 +1,72 @@ +;; @requires: posix (cleanup runs through a POSIX shell via .sys.exec) +;; .idx.info over a compressed (generation 2) and a plain (generation 0) +;; splayed column: format generation and bytes, read without decoding. +(.sys.exec "rm -rf /tmp/rf_test_cscan_a /tmp/rf_test_cscan_b") -- 0 +(set S (table [k] (list (til 150000)))) +(.db.splayed.set "/tmp/rf_test_cscan_a/" S {compress: true}) +(.db.splayed.set "/tmp/rf_test_cscan_b/" S {compress: false}) +(set A (.db.splayed.get "/tmp/rf_test_cscan_a/")) +(set B (.db.splayed.get "/tmp/rf_test_cscan_b/")) +(at (.idx.info A 'k) 'gen) -- 2 +(at (.idx.info B 'k) 'gen) -- 0 +(at (.idx.info A 'k) 'raw_bytes) -- 1200000 +(at (.idx.info A 'k) 'materialized) -- false +(.idx.info [1 2 3]) -- (.idx.info [1 2 3]) +(.sys.exec "rm -rf /tmp/rf_test_cscan_a /tmp/rf_test_cscan_b") -- 0 +;; Compressed-columns P2: the scan shapes over a generation-2 splayed table +;; answer exactly as over the generation-0 copy of the same data, and leave +;; the scanned columns unmaterialized (a top-k's sort key is the exception). +(.sys.exec "rm -rf /tmp/rf_test_cscan") -- 0 +(set i (til 150000)) +(set T (table [k g v f s] (list i (as 'I16 (% i 9)) (as 'I32 (map (fn [j] (if (== 0 (% j 11)) 0N j)) i)) (as 'F64 (% i 977)) (take ['x 'y 'z] 150000)))) +(.db.splayed.set "/tmp/rf_test_cscan/g2/" T {compress: true}) +(.db.splayed.set "/tmp/rf_test_cscan/g0/" T {compress: false}) +(set A (.db.splayed.get "/tmp/rf_test_cscan/g2/")) +(set B (.db.splayed.get "/tmp/rf_test_cscan/g0/")) +(count (select {from: A where: (> v 70000)})) -- (count (select {from: B where: (> v 70000)})) +(count (select {from: A where: (== g 4)})) -- (count (select {from: B where: (== g 4)})) +(sum (at A 'v)) -- (sum (at B 'v)) +(avg (at A 'f)) -- (avg (at B 'f)) +(min (at A 'k)) -- (min (at B 'k)) +(at (select {s: (sum v) from: A by: g}) 's) -- (at (select {s: (sum v) from: B by: g}) 's) +(at (.idx.info A 'v) 'materialized) -- false +(at (.idx.info A 'g) 'materialized) -- false +(at (.idx.info A 'f) 'materialized) -- false +(at (.idx.info A 'k) 'materialized) -- false +;; a filtered group-by over fewer survivors than the parallel threshold +;; gathers its key and input by range (the v2 compact fallback, P3 Task 6); +;; its SYM equality predicate compares the column's ids on the fused path +;; (P3 Task 4), so nothing is materialized +(at (select {c: (count k) from: A where: (== s 'y) by: g}) 'c) -- (at (select {c: (count k) from: B where: (== s 'y) by: g}) 'c) +(at (.idx.info A 'g) 'materialized) -- false +(at (.idx.info A 'k) 'materialized) -- false +(at (.idx.info A 's) 'materialized) -- false +(at (select {m: (max f) from: A where: (< k 1000)}) 'm) -- (at (select {m: (max f) from: B where: (< k 1000)}) 'm) +(at (select {k: k from: A where: (> v 100) desc: k take: 3}) 'k) -- (at (select {k: k from: B where: (> v 100) desc: k take: 3}) 'k) +(at (.idx.info A 'v) 'materialized) -- false +(at (.idx.info A 'f) 'materialized) -- false +(.sys.exec "rm -rf /tmp/rf_test_cscan") -- 0 +;; A computed key or a count distinct over a compressed column whose whole +;; decode would not stay cached (past a quarter of the anon watermark, as +;; every 4- and 8-byte column here is under -m 2M) reads it by range: in a +;; child run under that watermark the by-dict minute key, the computed key +;; beside a distinct output, the global count distinct and the grouped ones +;; answer as over the plain copy, with u, et and r left unmaterialized (read +;; in the query's own statement: the boundary drops a decode that size). +;; Here, under the default watermark, they decode as before and answer the +;; same. +(.sys.exec "rm -rf /tmp/rf_test_cscan_r") -- 0 +(set i (til 140000)) +(set h (% (* i 2654435761) 1000003)) +(set T (table [u et r s] (list (+ (at [0N 0 0 0 0 0 0] (% i 7)) (% (+ (* h 7919) i) 9000)) (+ 2013.07.01D00:00:00.000000000 (* 1000000000 (% (* h 13) 86400))) (as 'I32 (sqrt (as 'F64 (% (* h h) 2500)))) (at (as 'SYMBOL (map (fn [k] (format "p%" k)) (til 3000))) (% (* (% (* h h) 1009) 13) 3000))))) +(.db.splayed.set "/tmp/rf_test_cscan_r/c/" T "/tmp/rf_test_cscan_r/c.sym" {compress: true}) +(.db.splayed.set "/tmp/rf_test_cscan_r/p/" T "/tmp/rf_test_cscan_r/p.sym") +(.sys.exec "printf '%s\n' '(set C (.db.splayed.get \"/tmp/rf_test_cscan_r/c/\" \"/tmp/rf_test_cscan_r/c.sym\"))' '(set P (.db.splayed.get \"/tmp/rf_test_cscan_r/p/\" \"/tmp/rf_test_cscan_r/p.sym\"))' '(set nv (fn [v] (if (== (type v) (quote SYM)) (as (quote STR) v) v)))' '(set fp (fn [x] (if (== (type x) (quote TABLE)) (ser (xasc (table (cols x) (map (fn [c] (nv (at x c))) (cols x))) (cols x))) x)))' '(set eq (fn [a b] (if (== (count a) (count b)) (all (== a b)) false)))' '(set un (fn [c] (not (at (.idx.info C c) (quote materialized)))))' '(set chk (fn [f] (do (set a (fp (f C))) (set m (and (un (quote u)) (and (un (quote et)) (un (quote r))))) (and m (eq a (fp (f P)))))))' '(println (chk (fn [t] (select {from: t by: {u: u m: (minute et)} c: (count u)}))))' '(println (chk (fn [t] (select {from: t by: (hour et) d: (count (distinct u))}))))' '(println (chk (fn [t] (count (distinct (at t (quote u)))))))' '(println (chk (fn [t] (select {from: t by: r d: (count (distinct u))}))))' '(println (chk (fn [t] (select {from: t by: r c: (count u) d: (count (distinct u))}))))' '(println (chk (fn [t] (select {from: t by: s d: (count (distinct u)) where: (!= s \"p7\")}))))' > /tmp/rf_test_cscan_r/q.rfl") -- 0 +(.sys.exec "./rayforce -m 2M /tmp/rf_test_cscan_r/q.rfl /tmp/rf_test_cscan_r/q.out 2>&1; [ $(grep -c '^true$' /tmp/rf_test_cscan_r/q.out) -eq 6 ]") -- 0 +(set A (.db.splayed.get "/tmp/rf_test_cscan_r/c/" "/tmp/rf_test_cscan_r/c.sym")) +(set B (.db.splayed.get "/tmp/rf_test_cscan_r/p/" "/tmp/rf_test_cscan_r/p.sym")) +(at (select {from: A by: {u: u m: (minute et)} c: (count u) desc: c take: 5}) 'c) -- (at (select {from: B by: {u: u m: (minute et)} c: (count u) desc: c take: 5}) 'c) +(count (distinct (at A 'u))) -- (count (distinct (at B 'u))) +(at (select {from: A by: r d: (count (distinct u)) asc: r}) 'd) -- (at (select {from: B by: r d: (count (distinct u)) asc: r}) 'd) +(at (select {from: A by: r c: (count u) d: (count (distinct u)) asc: r}) 'd) -- (at (select {from: B by: r c: (count u) d: (count (distinct u)) asc: r}) 'd) +(.sys.exec "rm -rf /tmp/rf_test_cscan_r") -- 0 diff --git a/test/rfl/storage/compress_str.rfl b/test/rfl/storage/compress_str.rfl new file mode 100644 index 000000000..c819253cf --- /dev/null +++ b/test/rfl/storage/compress_str.rfl @@ -0,0 +1,43 @@ +;; @requires: posix (fixtures/checks run through a POSIX shell via .sys.exec) +;; STR encodings end to end (compressed-columns P6): generation-2 answers +;; equal generation 0 for STR_DICT, FSST, RAW and CONST columns. +(.sys.exec "rm -rf /tmp/rf_test_p6str") +(set n 140000) +(set i (til n)) +(set low (as 'STR (map (fn [j] (if (== 0 (% j 11)) "" (format "category % long" (% j 37)))) i))) +(set url (as 'STR (map (fn [j] (format "https://www.example.com/path/%/item?id=%" (% j 4999) (% (* j 7919) 100003))) i))) +(set zam (as 'STR (at ["z" "a" "m"] (% i 3)))) +(set T (table [low url zam v] (list low url zam i))) +(.db.splayed.set "/tmp/rf_test_p6str/g0/" T {compress: false}) +(.db.splayed.set "/tmp/rf_test_p6str/g2/" T {compress: true}) +(set A (.db.splayed.get "/tmp/rf_test_p6str/g0/")) +(set C (.db.splayed.get "/tmp/rf_test_p6str/g2/")) +(at (.idx.info C 'low) 'gen) -- 2 +(at (.idx.info A 'low) 'gen) -- 0 +(at (at (.idx.info C 'low) 'enc) 'str_dict) -- 137 +(at (at (.idx.info C 'url) 'enc) 'fsst) -- 137 +(at (at (.idx.info C 'zam) 'enc) 'str_dict) -- 137 +(count (select {from: C where: (== low "category 3 long")})) -- (count (select {from: A where: (== low "category 3 long")})) +(count (select {from: C where: (!= low "")})) -- (count (select {from: A where: (!= low "")})) +(count (select {from: C where: (== url "https://www.example.com/path/7/item?id=55433")})) -- (count (select {from: A where: (== url "https://www.example.com/path/7/item?id=55433")})) +(select {c: (count v) from: C by: zam asc: zam}) -- (select {c: (count v) from: A by: zam asc: zam}) +;; group keys on codes: first-occurrence order and counts, alone and composite +(select {c: (count v) from: C by: low}) -- (select {c: (count v) from: A by: low}) +(select {c: (count v) from: C by: {low: low z: zam} asc: [low z]}) -- (select {c: (count v) from: A by: {low: low z: zam} asc: [low z]}) +(select {c: (count v) from: C where: (!= low "") by: zam}) -- (select {c: (count v) from: A where: (!= low "") by: zam}) +(count (select {c: (count v) from: C by: url})) -- (count (select {c: (count v) from: A by: url})) +;; code order is not lexical order: ranges, like, min / max and top-k decode +(count (select {from: C where: (< zam "m")})) -- (count (select {from: A where: (< zam "m")})) +(count (select {from: C where: (<= zam "m")})) -- (count (select {from: A where: (<= zam "m")})) +(count (select {from: C where: (> zam "a")})) -- (count (select {from: A where: (> zam "a")})) +(count (select {from: C where: (>= zam "m")})) -- (count (select {from: A where: (>= zam "m")})) +(count (select {from: C where: (like url "*path/12/*")})) -- (count (select {from: A where: (like url "*path/12/*")})) +(min (at C 'zam)) -- (min (at A 'zam)) +(max (at C 'low)) -- (max (at A 'low)) +(at (select {z: zam from: C asc: zam take: 3}) 'z) -- (at (select {z: zam from: A asc: zam take: 3}) 'z) +(at C 'url) -- (at A 'url) +;; the file's last group-by is generation 2's: a generation-0 DICT group-by +;; leaves its code stash behind, which the next test's group-by frees after +;; the heap is gone (#865) +(count (select {c: (count v) from: C by: zam})) -- 3 +(.sys.exec "rm -rf /tmp/rf_test_p6str") -- 0 diff --git a/test/rfl/storage/index_policy.rfl b/test/rfl/storage/index_policy.rfl new file mode 100644 index 000000000..574449b2a --- /dev/null +++ b/test/rfl/storage/index_policy.rfl @@ -0,0 +1,40 @@ +;; @requires: posix (cleanup runs through a POSIX shell via .sys.exec) +;; Index policy (compressed-columns PI): explicit .idx.hash requests are +;; always persisted by .db.splayed.set, survive a reload and are consulted, +;; for I64, STR and SYM columns, whatever the converters do on their own. +(.sys.exec "rm -rf /tmp/rf_test_idx_policy") -- 0 +(set n 300000) +(set i (til n)) +;; unclustered I64: the auto heuristic's shape; here the hash is explicit +(set h (.idx.hash (% (* i 7919) 1000003))) +(set s (.idx.hash (as 'STR (map (fn [j] (format "k%" (% j 977))) (til 70000))))) +(set y (.idx.hash (as 'SYMBOL (map (fn [j] (format "y%" (% j 31))) (til 70000))))) +;; below one chunk: the auto heuristic never hashes this, only the explicit request does +(set m (.idx.hash (% (* (til 5000) 7919) 1009))) +(.db.splayed.set "/tmp/rf_test_idx_policy/c/" (table [m] (list m))) +(.db.splayed.set "/tmp/rf_test_idx_policy/a/" (table [h] (list h))) +(.db.splayed.set "/tmp/rf_test_idx_policy/b/" (table [s y] (list s y))) +(set A (.db.splayed.get "/tmp/rf_test_idx_policy/a/")) +(set B (.db.splayed.get "/tmp/rf_test_idx_policy/b/")) +(set C (.db.splayed.get "/tmp/rf_test_idx_policy/c/")) +(at (.idx.info (at A 'h)) 'kind) -- 'hash +(at (.idx.info (at C 'm)) 'kind) -- 'hash +(at (.idx.info (at B 's)) 'kind) -- 'hash +(at (.idx.info (at B 'y)) 'kind) -- 'hash +;; the persisted hash answers equality (7919 = 1 * 7919 is the only row) and is consulted +(do (.idx.uses A) null) +(at (select {h: h from: A where: (== h 7919)}) 'h) -- [7919] +(at (.idx.uses A) 'h) -- 1 +;; a conversion persists zones only: the unclustered column is not hashed +(set u (% (* i 7919) 1000003)) +(.csv.write (table [u c] (list u i)) "/tmp/rf_test_idx_policy.csv") -- 0 +(set C2 (.csv.splayed [u c] [I64 I64] "/tmp/rf_test_idx_policy.csv" "/tmp/rf_test_idx_policy/c2/")) +(at (.idx.info (at C2 'u)) 'kind) -- 'chunk_zone +(at (.idx.info (at C2 'c)) 'kind) -- 'chunk_zone +(set D2 (.db.splayed.get "/tmp/rf_test_idx_policy/c2/")) +(at (.idx.info (at D2 'u)) 'kind) -- 'chunk_zone +;; a re-save of a converted table does not add a hash either +(.db.splayed.set "/tmp/rf_test_idx_policy/d2/" D2) +(at (.idx.info (at (.db.splayed.get "/tmp/rf_test_idx_policy/d2/") 'u)) 'kind) -- 'chunk_zone +(.sys.exec "rm -f /tmp/rf_test_idx_policy.csv") -- 0 +(.sys.exec "rm -rf /tmp/rf_test_idx_policy") -- 0 diff --git a/test/rfl/storage/shared_sym_domain.rfl b/test/rfl/storage/shared_sym_domain.rfl index 780677f79..b50b1305c 100644 --- a/test/rfl/storage/shared_sym_domain.rfl +++ b/test/rfl/storage/shared_sym_domain.rfl @@ -75,5 +75,78 @@ (count Back) -- 0 (count (at Back 's)) -- 0 +;; ── per-column symfiles: {symfile: 'column} ──────────────────────────── +;; Every SYM column gets its own symfile, `..sym` next to its column +;; file, so the two SYM columns of one table resolve over two different FILE +;; domains. Every cross-column operation must answer as over the in-memory +;; table (one runtime domain). 70000 rows: past the 65536-row fast paths. +;; FP: a position-weighted string-length sum, independent of any domain. +(.sys.exec "rm -rf /tmp/rfl_col_dom") +(set I (til 70000)) +(set P (as 'SYM (concat [""] (map (fn [x] (format "https://site%.com/p/%" (% x 97) x)) (til 6000))))) +(set CT (table [id URL Ref] (list I (at P (% (* I 7919) 5001)) (at P (+ 1000 (% (* I 104729) 5001)))))) +(set FP (fn [v] (sum (* (+ 1 (til (count v))) (strlen v))))) +(.db.splayed.set "/tmp/rfl_col_dom/c0/" CT {symfile: 'column}) +(.db.splayed.set "/tmp/rfl_col_dom/c2/" CT {symfile: 'column compress: true}) +(.sys.exec "cd /tmp/rfl_col_dom/c0 && test -f .URL.sym && test -f .Ref.sym && test ! -e .sym && test ! -e .id.sym") -- 0 +(.sys.exec "cd /tmp/rfl_col_dom/c2 && test -f .URL.sym && test -f .Ref.sym && test ! -e .sym") -- 0 +(set C0 (.db.splayed.get "/tmp/rfl_col_dom/c0/")) +(set C2 (.db.splayed.get "/tmp/rfl_col_dom/c2/")) +(FP (at C0 'URL)) -- (FP (at CT 'URL)) +(FP (at C2 'Ref)) -- (FP (at CT 'Ref)) +;; comparisons between the columns of two domains +(sum (== (at C0 'URL) (at C0 'Ref))) -- (sum (== (at CT 'URL) (at CT 'Ref))) +(count (select {from: C2 where: (== URL Ref)})) -- (count (select {from: CT where: (== URL Ref)})) +(count (select {from: C0 where: (!= URL Ref)})) -- (count (select {from: CT where: (!= URL Ref)})) +(sum (< (at C0 'URL) (at C2 'Ref))) -- (sum (< (at CT 'URL) (at CT 'Ref))) +(sum (in (at C0 'URL) (at C2 'Ref))) -- (sum (in (at CT 'URL) (at CT 'Ref))) +(count (select {from: C2 where: (like URL "*site1*")})) -- (count (select {from: CT where: (like URL "*site1*")})) +;; grouping by both columns, distinct over a union, set operations +(set GT (xasc (select {n: (count id) from: CT by: [URL Ref]}) ['URL 'Ref])) +(set G0 (xasc (select {n: (count id) from: C0 by: [URL Ref]}) ['URL 'Ref])) +(set G2 (xasc (select {n: (count id) from: C2 by: [Ref URL]}) ['URL 'Ref])) +(count G0) -- (count GT) +(FP (at G0 'URL)) -- (FP (at GT 'URL)) +(FP (at G0 'Ref)) -- (FP (at GT 'Ref)) +(FP (at G2 'Ref)) -- (FP (at GT 'Ref)) +(sum (* (til (count G2)) (at G2 'n))) -- (sum (* (til (count GT)) (at GT 'n))) +(FP (asc (distinct (concat (at C0 'URL) (at C2 'Ref))))) -- (FP (asc (distinct (concat (at CT 'URL) (at CT 'Ref))))) +(FP (asc (union (at C2 'URL) (at C0 'Ref)))) -- (FP (asc (union (at CT 'URL) (at CT 'Ref)))) +(FP (asc (except (at C0 'URL) (at C0 'Ref)))) -- (FP (asc (except (at CT 'URL) (at CT 'Ref)))) +(FP (concat (at C0 'URL) (at C0 'Ref))) -- (FP (concat (at CT 'URL) (at CT 'Ref))) +;; joins on SYM keys drawn from different columns and tables +(set JT (inner-join [k] (select {k: URL v: id from: CT}) (select {k: Ref w: id from: CT}))) +(set J0 (inner-join [k] (select {k: URL v: id from: C0}) (select {k: Ref w: id from: C2}))) +(count J0) -- (count JT) +(sum (at J0 'w)) -- (sum (at JT 'w)) +(count (inner-join [URL Ref] (select {URL: URL Ref: Ref v: id from: C0}) (select {URL: Ref Ref: URL w: id from: C2}))) -- (count (inner-join [URL Ref] (select {URL: URL Ref: Ref v: id from: CT}) (select {URL: Ref Ref: URL w: id from: CT}))) +;; sort and table concat over both layouts +(FP (at (xasc C0 ['Ref 'URL 'id]) 'URL)) -- (FP (at (xasc CT ['Ref 'URL 'id]) 'URL)) +(FP (at (xasc (concat C0 C2) ['URL 'id]) 'Ref)) -- (FP (at (xasc (concat CT CT) ['URL 'id]) 'Ref)) +;; re-saves across layouts: per-column to shared, and shared back to per-column +(.db.splayed.set "/tmp/rfl_col_dom/s/" C2 {symfile: 'shared}) +(.sys.exec "test -f /tmp/rfl_col_dom/s/.sym && test ! -e /tmp/rfl_col_dom/s/.URL.sym") -- 0 +(FP (at (.db.splayed.get "/tmp/rfl_col_dom/s/") 'Ref)) -- (FP (at CT 'Ref)) +(.db.splayed.set "/tmp/rfl_col_dom/c0/" (.db.splayed.get "/tmp/rfl_col_dom/s/") {symfile: 'column}) +(FP (at (.db.splayed.get "/tmp/rfl_col_dom/c0/") 'URL)) -- (FP (at CT 'URL)) +;; the first write's root symfiles go with its root columns +(.sys.exec "test ! -e /tmp/rfl_col_dom/c0/.URL.sym && test ! -e /tmp/rfl_col_dom/c0/URL") -- 0 +;; a shared re-save over a per-column table: its generation has no column symfile +(.db.splayed.set "/tmp/rfl_col_dom/c0/" C0) +(FP (at (.db.splayed.get "/tmp/rfl_col_dom/c0/") 'Ref)) -- (FP (at CT 'Ref)) +;; option errors +(.db.splayed.set "/tmp/rfl_col_dom/e/" CT {symfile: 'bogus}) !- domain +(.db.splayed.set "/tmp/rfl_col_dom/e/" CT {symfile: 1}) !- domain +(.db.splayed.set "/tmp/rfl_col_dom/e/" CT "/tmp/rfl_col_dom/e.sym" {symfile: 'column}) !- domain +(.db.splayed.set "/tmp/rfl_col_dom/e/" CT "/tmp/rfl_col_dom/e/.sym" {symfile: 'column}) !- domain +(.db.splayed.set "/tmp/rfl_col_dom/e/" CT {bogus: true}) !- domain +(.db.splayed.set "/tmp/rfl_col_dom/2024.01.01/t/" CT {symfile: 'column}) !- domain +(.sys.exec "test ! -e /tmp/rfl_col_dom/e && test ! -e /tmp/rfl_col_dom/2024.01.01") -- 0 +;; a partition takes no column symfile: its segments share the root .sym +(.db.splayed.set "/tmp/rfl_col_dom/db/2024.01.01/t/" (take CT 10)) +(count (.db.parted.get "/tmp/rfl_col_dom/db/" 't)) -- 10 +(.sys.exec "cp /tmp/rfl_col_dom/c2/.URL.sym /tmp/rfl_col_dom/db/2024.01.01/t/.URL.sym") -- 0 +(.db.parted.get "/tmp/rfl_col_dom/db/" 't) !- nyi + ;; ── cleanup ──────────────────────────────────────────────────────────── -(.sys.exec "rm -rf /tmp/rfl_shared_dom /tmp/rfl_shared_dom_lone /tmp/rfl_shared_dom_empty") -- 0 +(.sys.exec "rm -rf /tmp/rfl_shared_dom /tmp/rfl_shared_dom_lone /tmp/rfl_shared_dom_empty /tmp/rfl_col_dom") -- 0 diff --git a/test/rfl/store/col_format_generation.rfl b/test/rfl/store/col_format_generation.rfl index d9b2de411..c7f786357 100644 --- a/test/rfl/store/col_format_generation.rfl +++ b/test/rfl/store/col_format_generation.rfl @@ -12,10 +12,13 @@ (set T-Gen (table [a b] (list [1 2 3] [10.0 20.0 30.0]))) ;; ─── generation-0 (legacy/pre-stamp) data loads ─── +;; Both saves ask for generation 0 explicitly: the byte patched below is the +;; generation-0 discriminator, which a generation-2 file (the equivalence +;; pass's default) refuses as corrupt by design. ;; Force every column file + .d to order==0, mimicking data written before any ;; version byte existed. This fails loudly if the generation is ever bumped ;; back off 0 (writer would stamp non-zero, reader would reject the forced 0s). -(.db.splayed.set "/tmp/rfl_colgen_legacy/" T-Gen) +(.db.splayed.set "/tmp/rfl_colgen_legacy/" T-Gen {compress: false}) (.sys.exec "for f in /tmp/rfl_colgen_legacy/.d /tmp/rfl_colgen_legacy/a /tmp/rfl_colgen_legacy/b; do printf '\\000' | dd of=$f bs=1 seek=17 count=1 conv=notrunc 2>/dev/null; done") -- 0 (count (.db.splayed.get "/tmp/rfl_colgen_legacy/")) -- 3 (at (.db.splayed.get "/tmp/rfl_colgen_legacy/") 'a) -- (at T-Gen 'a) @@ -24,6 +27,6 @@ ;; ─── the version gate still rejects an unknown generation ─── ;; Stamp the .d header's order byte to 0x07 and confirm the load is refused ;; (proves the check did not regress into accepting everything). -(.db.splayed.set "/tmp/rfl_colgen_bad/" T-Gen) +(.db.splayed.set "/tmp/rfl_colgen_bad/" T-Gen {compress: false}) (.sys.exec "printf '\\007' | dd of=/tmp/rfl_colgen_bad/.d bs=1 seek=17 count=1 conv=notrunc 2>/dev/null") -- 0 (.db.splayed.get "/tmp/rfl_colgen_bad/") !- version diff --git a/test/rfl/store/splayed_str_pool_lifetime.rfl b/test/rfl/store/splayed_str_pool_lifetime.rfl index ca7e588f7..87ffdf666 100644 --- a/test/rfl/store/splayed_str_pool_lifetime.rfl +++ b/test/rfl/store/splayed_str_pool_lifetime.rfl @@ -93,6 +93,9 @@ (set _BT (table [id note] (list (til _N) (at (list "alpha" "beta" "gamma" "delta") (% (til _N) 4))))) (.db.splayed.set "rf_bigstr/" _BT) (set _BT 0) +;; (a generation-2 save, as in the equivalence pass, persists the same dict +;; index in the column's index region, P6b: over 65536 rows, so indexed in +;; both generations) (.idx.has? (at (.db.splayed.get "rf_bigstr/") 'note)) -- true (set _m0 (at (.sys.mem) 'sys-mapped)) @@ -113,7 +116,8 @@ ;; is not a whole number of pages left its tail behind: a 20,000-row ;; table read 1,000 times ended millions of bytes below zero. ───────── (.sys.exec "rm -rf rf_mapcnt") -- 0 -(.db.splayed.set "rf_mapcnt/" (table [i f s c] (list (til 20000) (as 'F64 (til 20000)) (take [x y z] 20000) (take ["ab" "cde" ""] 20000)))) +;; Saved as generation 0: the count is of files mapped in place. +(.db.splayed.set "rf_mapcnt/" (table [i f s c] (list (til 20000) (as 'F64 (til 20000)) (take [x y z] 20000) (take ["ab" "cde" ""] 20000))) {compress: false}) (set _m0 (at (.sys.mem) 'sys-mapped)) (set u (.db.splayed.get "rf_mapcnt/")) ;; Held, the table is counted: the check below is not vacuous. diff --git a/test/rfl/store/symfile_external_growth.rfl b/test/rfl/store/symfile_external_growth.rfl new file mode 100644 index 000000000..7722a7b92 --- /dev/null +++ b/test/rfl/store/symfile_external_growth.rfl @@ -0,0 +1,40 @@ +;; @requires: posix (the writer runs as a child process through .sys.exec) +;; A reader that reopens a root whose symfile another process grew keeps +;; memory proportional to the vocabulary, however often it reopens — #717. +;; +;; Each reopen is a cache hit that extends the shared domain. The arrays +;; it replaces and the mapping it supersedes used to be kept until the +;; domain died, and a reader that always holds the previous view never +;; lets it die: one more copy of the vocabulary's arrays and one more +;; mapping of the symfile per reopen. Now they are freed by the reopen. + +;; The writer: K rows whose SYM column holds _0 .. _, +;; written outside the root through the root's symfile. +(.sys.exec "rm -rf /tmp/rfl_717 && mkdir -p /tmp/rfl_717/root") -- 0 +(write "/tmp/rfl_717/writer.rfl" "(set a (get (.sys.args) 'user)) (set k (as 'i64 (get a 'k))) (set names (map (fn [j] (format \"%_%\" (get a 'p) j)) (til k))) (.db.splayed.set (get a 'dir) (table [s v] (list (as 'sym names) (til k))) (get a 'sym)) (exit 0)") +(.sys.exec "./rayforce -c 1 /tmp/rfl_717/writer.rfl -- -dir /tmp/rfl_717/root/1/t -sym /tmp/rfl_717/root/.sym -p base -k 5000") -- 0 + +(set P (.db.parted.get "/tmp/rfl_717/root" 't)) +(count P) -- 5000 + +;; One step: the writer appends 10 symbols, the reader reopens. +(set grow (fn [i] (do (.sys.exec (format "./rayforce -c 1 /tmp/rfl_717/writer.rfl -- -dir /tmp/rfl_717/scratch/t -sym /tmp/rfl_717/root/.sym -p new% -k 10" i)) (set P (.db.parted.get "/tmp/rfl_717/root" 't)) (count P)))) + +;; Warm-up: the first reopens materialise what the reader touches. +(map grow (til 2)) -- [5000 5000] +(set m2 (.sys.mem)) +(distinct (map grow (+ 2 (til 18)))) -- [5000] +(set m20 (.sys.mem)) + +;; The grown vocabulary is there: a symbol the last writer added resolves. +(.sys.exec "./rayforce -c 1 /tmp/rfl_717/writer.rfl -- -dir /tmp/rfl_717/scratch/t -sym /tmp/rfl_717/root/.sym -p new19 -k 10") -- 0 +(count (select {s: s from: (.db.splayed.get "/tmp/rfl_717/scratch/t" "/tmp/rfl_717/root/.sym") where: (== s 'new19_9)})) -- 1 + +;; 18 reopens later: no copy of the vocabulary per reopen (the leak was +;; about 90 KB each here, 1.6 MB over the run; the bound leaves room for a +;; heap pool or arena growing meanwhile), and the symfile is mapped once — +;; each reopen unmapped the image it replaced. +(< (- (get m20 'sys-current) (get m2 'sys-current)) 524288) -- true +(<= (- (get m20 'sys-mapped) (get m2 'sys-mapped)) (.fs.size "/tmp/rfl_717/root/.sym")) -- true + +(.sys.exec "rm -rf /tmp/rfl_717") -- 0 diff --git a/test/rfl/strop/split.rfl b/test/rfl/strop/split.rfl index 06d41baa8..6e59bcc2a 100644 --- a/test/rfl/strop/split.rfl +++ b/test/rfl/strop/split.rfl @@ -28,6 +28,12 @@ (split "" "--") -- (list "") (split "--" "--") -- (list "" "") (split "--a--" "--") -- (list "" "a" "") +;; A non-empty input shorter than a multi-character delimiter is no match. +;; The search bound must not wrap when subtracting unsigned lengths. +(split "a" "ab") -- (list "a") +(split "x" "xyz") -- (list "x") +(split 'a "ab") -- (list "a") +(split "ab" "ab") -- (list "" "") (split 'asasd "d") -- (list "asas" "") (split 'asasd 'd') -- (list "asas" "") ;; Basic vector splitting with I64 indices diff --git a/test/rfl/system/cli_missing_args.rfl b/test/rfl/system/cli_missing_args.rfl new file mode 100644 index 000000000..0e9f2001b --- /dev/null +++ b/test/rfl/system/cli_missing_args.rfl @@ -0,0 +1,4 @@ +;; CLI flags that require values must fail as option errors, not as attempts +;; to open the flag token as a script path. + +(.sys.exec "rm -f /tmp/rfl_cli_missing_arg.out; for opt in -p --port -c --cores -t --timeit -Q --querylog -f --file -m --mem -u -U -l -L; do ./rayforce $opt /tmp/rfl_cli_missing_arg.out 2>&1; rc=$?; grep -Fq \"error: $opt expects a value\" /tmp/rfl_cli_missing_arg.out || exit 10; [ $rc -eq 2 ] || exit 11; done; for opt in -x --bogus; do ./rayforce $opt /tmp/rfl_cli_missing_arg.out 2>&1; rc=$?; grep -Fq \"error: unknown option '$opt'\" /tmp/rfl_cli_missing_arg.out || exit 12; [ $rc -eq 2 ] || exit 13; done") -- 0 diff --git a/test/rfl/system/cpu_set_size.rfl b/test/rfl/system/cpu_set_size.rfl new file mode 100644 index 000000000..ef37820cc --- /dev/null +++ b/test/rfl/system/cpu_set_size.rfl @@ -0,0 +1,26 @@ +;; @requires: posix (the instances run as child processes through .sys.exec) +;; @requires: linux (taskset and cgroups; elsewhere the pool takes every online CPU) +;; The default pool has one thread per CPU the process may run on: its +;; affinity mask (taskset, a cpuset), or fewer under a cgroup CPU quota +;; (docker --cpus, systemd CPUQuota=). .sys.info reports the CPU count and +;; the pool size. + +(.sys.exec "rm -rf /tmp/rf_cpu_set && mkdir -p /tmp/rf_cpu_set") +(.sys.exec "printf '(set i (.sys.info))\\n(println (format \"%% %%\" (at i (quote cores)) (at i (quote workers))))\\n' > /tmp/rf_cpu_set/info.rfl") + +;; Under taskset the default pool has one thread per allowed CPU. The CPUs +;; are the first of the runner's own mask; a runner under a CPU quota below +;; two CPUs (q, its own default pool size) caps the pool at that. +;; RAYFORCE_CORES, which the test harness sets, would size the pool itself. +(.sys.exec "set -- $(taskset -pc $$ | sed 's/.*: //' | tr ',' '\\n' | awk -F- '{ if (NF == 2) for (i = $1; i <= $2; i++) print i; else print $1 }'); [ $# -ge 2 ] || exit 0; q=$(env -u RAYFORCE_CORES ./rayforce -f /tmp/rf_cpu_set/info.rfl 2>/dev/null | tail -1); q=${q#* }; e=2; [ \"$q\" -lt 2 ] && e=$q; o=$(env -u RAYFORCE_CORES taskset -c $1,$2 ./rayforce -f /tmp/rf_cpu_set/info.rfl 2>/dev/null | tail -1); [ \"$o\" = \"2 $e\" ]") -- 0 +(.sys.exec "set -- $(taskset -pc $$ | sed 's/.*: //' | tr ',' '\\n' | awk -F- '{ if (NF == 2) for (i = $1; i <= $2; i++) print i; else print $1 }'); o=$(env -u RAYFORCE_CORES taskset -c $1 ./rayforce -f /tmp/rf_cpu_set/info.rfl 2>/dev/null | tail -1); [ \"$o\" = '1 1' ]") -- 0 +;; -c past the set is obeyed, with a warning on stderr +(.sys.exec "set -- $(taskset -pc $$ | sed 's/.*: //' | tr ',' '\\n' | awk -F- '{ if (NF == 2) for (i = $1; i <= $2; i++) print i; else print $1 }'); o=$(env -u RAYFORCE_CORES taskset -c $1 ./rayforce -c 3 -f /tmp/rf_cpu_set/info.rfl 2>/dev/null | tail -1); [ \"$o\" = '1 3' ]") -- 0 +(.sys.exec "set -- $(taskset -pc $$ | sed 's/.*: //' | tr ',' '\\n' | awk -F- '{ if (NF == 2) for (i = $1; i <= $2; i++) print i; else print $1 }'); env -u RAYFORCE_CORES taskset -c $1 ./rayforce -c 3 -f /tmp/rf_cpu_set/info.rfl 2>&1 >/dev/null | grep -q 'gives 3 threads, more than the 1 CPU this process may use'") -- 0 +;; -c within what the process may use: no warning +(.sys.exec "set -- $(taskset -pc $$ | sed 's/.*: //' | tr ',' '\\n' | awk -F- '{ if (NF == 2) for (i = $1; i <= $2; i++) print i; else print $1 }'); [ $# -ge 2 ] || exit 0; q=$(env -u RAYFORCE_CORES ./rayforce -f /tmp/rf_cpu_set/info.rfl 2>/dev/null | tail -1); q=${q#* }; e=2; [ \"$q\" -lt 2 ] && e=$q; ! env -u RAYFORCE_CORES taskset -c $1,$2 ./rayforce -c $e -f /tmp/rf_cpu_set/info.rfl 2>&1 >/dev/null | grep -q warning") -- 0 + +;; The CPU quota case runs as pool/cpu_quota_child (test/test_pool.c), where +;; a missing systemd user manager shows as a skip. + +(.sys.exec "rm -rf /tmp/rf_cpu_set") diff --git a/test/rfl/system/csv_explicit_numeric_types.rfl b/test/rfl/system/csv_explicit_numeric_types.rfl index facf89284..29693f1db 100644 --- a/test/rfl/system/csv_explicit_numeric_types.rfl +++ b/test/rfl/system/csv_explicit_numeric_types.rfl @@ -11,19 +11,19 @@ (type (at T 'f32b)) -- 'F32 (type (at T 'i32)) -- 'I32 (type (at T 'i16)) -- 'I16 -(at (at T 'f32a) 0) -- 1.25 -(at (at T 'f32a) 1) -- -2.5 -(at (at (select {x: (- f32a f32b) from: T}) 'x) 0) -- 1.0 -(at (at (select {x: (- f32a f32b) from: T}) 'x) 2) -- 4.0 +(at (at T 'f32a) 0) -- 1.25e +(at (at T 'f32a) 1) -- -2.5e +(at (at (select {x: (- f32a f32b) from: T}) 'x) 0) -- 1.0e +(at (at (select {x: (- f32a f32b) from: T}) 'x) 2) -- 4.0e (type (at (select {x: (+ f32a f32b) from: T}) 'x)) -- 'F32 ;; 2^24 + 1 rounds back to 2^24 at F32 precision. -(at (at (select {x: (+ f32a f32b) from: T}) 'x) 3) -- 16777216.0 +(at (at (select {x: (+ f32a f32b) from: T}) 'x) 3) -- 16777216.0e (type (at (at T 'f32a) 0)) -- 'f32 (type (at (at T 'f32b) 0)) -- 'f32 (type (+ (at (at T 'f32a) 0) (at (at T 'f32b) 0))) -- 'f32 -(+ (at (at T 'f32a) 0) (at (at T 'f32b) 0)) -- 1.5 +(+ (at (at T 'f32a) 0) (at (at T 'f32b) 0)) -- 1.5e (type (at (select {x: (neg f32a) from: T}) 'x)) -- 'F32 -(at (at (select {x: (neg f32a) from: T}) 'x) 1) -- 2.5 +(at (at (select {x: (neg f32a) from: T}) 'x) 1) -- 2.5e (type (at (select {x: (+ f32a i32) from: T}) 'x)) -- 'F64 (at (at (select {x: (+ f32a i32) from: T}) 'x) 0) -- 100001.25 (type (wavg (at T 'i32) (at T 'f32b))) -- 'f64 @@ -42,7 +42,7 @@ (type (at R 'f32b)) -- 'F32 (type (at R 'i32)) -- 'I32 (type (at R 'i16)) -- 'I16 -(at (at R 'f32a) 2) -- 3.75 +(at (at R 'f32a) 2) -- 3.75e (at (at R 'i32) 1) -- -7 (at (at R 'i16) 2) -- 9 diff --git a/test/rfl/system/ipc_diff.rfl b/test/rfl/system/ipc_diff.rfl index 7e53ed584..dccf3953d 100644 --- a/test/rfl/system/ipc_diff.rfl +++ b/test/rfl/system/ipc_diff.rfl @@ -79,6 +79,42 @@ (.ipc.send h "(do (set E (table [src dst] (list [0 1] [1 0]))) (set G (.graph.build E 'src 'dst)) G)") !- type (.ipc.send h "(do (set E2 (table [src dst] (list [0 1] [1 0]))) (set G2 (.graph.build E2 'src 'dst)) (list G2 1))") !- type +;; ── a parted table ───────────────────────────────────────────────── +;; A parted table, bare or as a select with no clauses (which answers the +;; parted table itself), goes back as the flat table it stands for: the +;; reply streams each partition segment onto the wire. Both failed with a +;; `type` error reply. The table is ragged (2024.01.03 has no x or s +;; columns): that partition's rows answer nulls, and a sort over it +;; answers the sorted flat table, whichever partition lacks the column. +(.sys.exec "rm -rf /tmp/rfl_ipc_parted") +(.db.splayed.set "/tmp/rfl_ipc_parted/2024.01.01/t/" (table [a x s] (list [0 1 2] [5.0 3.0 9.0] ['p 'q 'p]))) +(.db.splayed.set "/tmp/rfl_ipc_parted/2024.01.02/t/" (table [a x s] (list [3 4 5] [1.0 7.0 2.0] ['r 'p 'q]))) +(.db.splayed.set "/tmp/rfl_ipc_parted/2024.01.03/t/" (table [a] (list [6 7]))) +(set Pipc (.db.parted.get "/tmp/rfl_ipc_parted/" 't)) +(.ipc.send h "(do (set Pipc (.db.parted.get \"/tmp/rfl_ipc_parted/\" 't)) 0)") -- 0 +(set Fipc (table [date a x s] (list [2024.01.01 2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.02 2024.01.03 2024.01.03] (til 8) [5.0 3.0 9.0 1.0 7.0 2.0 0Nf 0Nf] ['p 'q 'p 'r 'p 'q ' ']))) +(.ipc.send h "Pipc") -- Fipc +(.ipc.send h "(select {from: Pipc})") -- Fipc +(ser (.ipc.send h "Pipc")) -- (ser Fipc) +(ser (.ipc.send h "(select {from: Pipc})")) -- (ser Pipc) +(.ipc.send h "(list Pipc 1)") -- (list Fipc 1) +(.ipc.send h "(select {from: Pipc where: (>= a 0) desc: x take: 2})") -- (select {from: Fipc desc: x take: 2}) +(.ipc.send h "(select {from: Pipc desc: x take: 2})") -- (select {from: Fipc desc: x take: 2}) +(.sys.exec "rm -rf /tmp/rfl_ipc_parted") -- 0 +(.sys.exec "rm -rf /tmp/rfl_ipc_ragmid") +(.db.splayed.set "/tmp/rfl_ipc_ragmid/2024.01.01/t/" (table [a b s h t] (list [0 1] [0.5 1.5] ['p 'q] [true false] (as 'STR (list "u" "a longer string value"))))) +(.db.splayed.set "/tmp/rfl_ipc_ragmid/2024.01.02/t/" (table [a] (list [2 3 4]))) +(.db.splayed.set "/tmp/rfl_ipc_ragmid/2024.01.03/t/" (table [a b s h t] (list [5 6] [5.5 6.5] ['r 'p] [true true] (as 'STR (list "w" "another long string value"))))) +(.ipc.send h "(do (set Pmid (.db.parted.get \"/tmp/rfl_ipc_ragmid/\" 't)) 0)") -- 0 +(set Fmid (table [date a b s h t] (list [2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.02 2024.01.03 2024.01.03] (til 7) [0.5 1.5 0Nf 0Nf 0Nf 5.5 6.5] ['p 'q ' ' ' 'r 'p] [true false false false false true true] (as 'STR (list "u" "a longer string value" "" "" "" "w" "another long string value"))))) +(.ipc.send h "(select {from: Pmid where: (>= a 0) desc: a take: 3})") -- (select {from: Fmid desc: a take: 3}) +(.ipc.send h "(select {from: Pmid where: (>= a 0) asc: h})") -- (select {from: Fmid asc: h}) +(.ipc.send h "(select {from: Pmid where: (>= a 0) desc: b})") -- (select {from: Fmid desc: b}) +(.ipc.send h "(select {from: Pmid where: (>= a 0) asc: t take: 2})") -- (select {from: Fmid asc: t take: 2}) +(.ipc.send h "(select {from: Pmid where: (> a 1)})") -- (select {from: Fmid where: (> a 1)}) +(.ipc.send h "(count Pmid)") -- 7 +(.sys.exec "rm -rf /tmp/rfl_ipc_ragmid") -- 0 + ;; ── large payloads ───────────────────────────────────────────────── ;; Multi-KB results over the framing path. These no longer exercise ;; ray_ipc_compress: since #541 a loopback link never compresses, so diff --git a/test/rfl/system/part.rfl b/test/rfl/system/part.rfl index d6a3f808f..b08210d67 100644 --- a/test/rfl/system/part.rfl +++ b/test/rfl/system/part.rfl @@ -154,6 +154,16 @@ (set Rcd (select {RegionID: RegionID u: (count (distinct UserID)) from: Pcd by: RegionID desc: u take: 3})) (at Rcd 'RegionID) -- [2 3 1] (at Rcd 'u) -- [3 2 1] +;; scalar outputs over a whole-column verb, with no where: or one every row +;; passes: no selection compacts the source, and the verb reads the parted +;; columns and the partition key flattened, as after a partial where: +(at (select {c: (count (distinct date)) from: Pcd}) 'c) -- [2] +(at (select {c: (count (distinct date)) from: Pcd where: (> UserID 0)}) 'c) -- [2] +(at (select {c: (count (distinct date)) from: Pcd where: (> UserID 10)}) 'c) -- [2] +(set Rcdv (select {d: (first (desc date)) r: (last (reverse RegionID)) u: (count (distinct UserID)) from: Pcd})) +(at Rcdv 'd) -- [2024.01.02] +(at Rcdv 'r) -- [1] +(at Rcdv 'u) -- [6] (set CD-S1 (table [phrase user] (list ['skip 'alpha 'alpha 'beta] [1 2 3 4]))) (set CD-S2 (table [phrase user] (list ['skip 'beta 'gamma 'gamma] [5 6 7 8]))) (.db.splayed.set "/tmp/rfl_part_cd_sym/2024.02.01/s/" CD-S1) @@ -505,6 +515,26 @@ (at (select {from: PKI where: (> ts 3) take: 2}) 'part) -- [1 7] (key (select {from: PKI where: (> ts 30)})) -- [part ts v] (.sys.exec "rm -rf /tmp/rfl_part_keep") +;; take: after a where: gathers the null cells as nulls, not as the +;; sentinel's plain value, as take: alone and where: alone do +(.db.splayed.set "/tmp/rfl_part_keep/2024.01.01/t/" (table [a b] (list (as 'I64 [0N 1 2 0N 4]) (as 'I32 [5 0N 7 8 9])))) +(.db.splayed.set "/tmp/rfl_part_keep/2024.01.02/t/" (table [a b] (list (as 'I64 [0N 1 2 0N 4]) (as 'I32 [5 0N 7 8 9])))) +(set PKN (.db.parted.get "/tmp/rfl_part_keep/" 't)) +(at (select {from: PKN where: (not (== date 2024.01.02)) take: 3}) 'a) -- [0Nl 1 2] +(at (select {from: PKN where: (not (== date 2024.01.02)) take: 3}) 'b) -- (as 'I32 [5 0N 7]) +(at (select {from: PKN where: (< b 100) take: 3}) 'a) -- [0Nl 1 2] +(at (select {from: PKN where: (> date 2024.01.01) take: 4}) 'a) -- [0Nl 1 2 0Nl] +(nil? (at (select {from: PKN where: (< b 100) take: 3}) 'a)) -- [true false false] +(at (select {from: PKN take: 3}) 'a) -- [0Nl 1 2] +;; a flat table under where: and take: (the predicate a `not` routes to +;; the same gather): the flat branch copied the sentinels without marks +(set MKN (table [date a b] (list [2024.01.01 2024.01.01 2024.01.02 2024.01.03 2024.01.03] (as 'I64 [0N 1 2 0N 4]) (as 'I32 [5 0N 7 8 9])))) +(at (select {from: MKN where: (not (== date 2024.01.02)) take: 4}) 'a) -- [0Nl 1 0Nl 4] +(at (select {from: MKN where: (not (== date 2024.01.02)) take: 4}) 'a) -- (at (select {from: MKN where: (not (== date 2024.01.02))}) 'a) +(nil? (at (select {from: MKN where: (not (== date 2024.01.02)) take: 4}) 'a)) -- [true false true false] +(at (select {from: MKN where: (not (== date 2024.01.02)) take: 4}) 'b) -- (as 'I32 [5 0N 8 9]) +(nil? (at (select {from: MKN where: (not (== date 2024.01.02)) take: 4}) 'b)) -- [false true false false] +(.sys.exec "rm -rf /tmp/rfl_part_keep") ;; ────────────── failed first write of a partition ────────────── ;; A first write writes in place; when it fails (here the symbol file sits diff --git a/test/rfl/system/reserved_namespace.rfl b/test/rfl/system/reserved_namespace.rfl index 4a881d429..3179419f7 100644 --- a/test/rfl/system/reserved_namespace.rfl +++ b/test/rfl/system/reserved_namespace.rfl @@ -9,8 +9,8 @@ ;; the implementation can reject unexpected arguments explicitly. (.sys.gc) -- 0 (.sys.gc 0) !- arity -(count (.sys.info)) -- 5 -(count (.sys.mem)) -- 18 +(count (.sys.info)) -- 6 +(count (.sys.mem)) -- 21 (count (.sys.build)) -- 2 ;; The namespace roots themselves are real dicts — typing just ;; `.sys` at the REPL returns a dict with every `.sys.*` entry diff --git a/test/rfl/system/serde.rfl b/test/rfl/system/serde.rfl index 9f788d32b..b55a2761e 100644 --- a/test/rfl/system/serde.rfl +++ b/test/rfl/system/serde.rfl @@ -46,3 +46,71 @@ ;; the C level in test_store.c (store/serde_builtin_name_roundtrip). ((de (ser .db.parted.tables)) 123) !- type ((de (ser .sys.querylog.enable)) 1 2) !- domain + +;; ────────────── a parted table ────────────── +;; ser writes a parted table (.db.parted.get) as the flat table it stands +;; for, streamed from the partition segments without a flat copy: each +;; column byte-identical to the flattened column, the date key repeated on +;; every row of its partition, and de reads back a plain table. It failed +;; with a misleading `domain: zero serialized size`. +(.sys.exec "rm -rf /tmp/rfl_serde_parted") +(set Gser (guid 7)) +(set mkser (fn [lo n] (table [i j h f b s t g ts l] (list (+ lo (til n)) (as 'I32 (+ lo (til n))) (as 'I16 (+ lo (til n))) (as 'F64 (+ lo (til n))) (as 'B8 (% (+ lo (til n)) 2)) (take (drop ['x 'y 'zz 'x 'q 'r 'x] lo) n) (as 'STR (map (fn [x] (as 'STR x)) (+ lo (til n)))) (take (drop Gser lo) n) (as 'TIMESTAMP (+ lo (til n))) (map (fn [x] (list x (as 'STR x))) (+ lo (til n))))))) +(set Aser (mkser 0 3)) +(set Bser (mkser 3 2)) +(set Cser (mkser 5 2)) +(.db.splayed.set "/tmp/rfl_serde_parted/f/2024.01.01/t/" Aser) +(.db.splayed.set "/tmp/rfl_serde_parted/f/2024.01.02/t/" Bser) +(.db.splayed.set "/tmp/rfl_serde_parted/f/2024.01.03/t/" Cser) +(set Pser (.db.parted.get "/tmp/rfl_serde_parted/f/" 't)) +(set Dser [2024.01.01 2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.03 2024.01.03]) +(set catser (fn [c] (concat (concat (at Aser c) (at Bser c)) (at Cser c)))) +(set Fser (table [date i j h f b s t g ts l] (list Dser (catser 'i) (catser 'j) (catser 'h) (catser 'f) (catser 'b) (catser 's) (catser 't) (catser 'g) (catser 'ts) (catser 'l)))) +(ser Pser) -- (ser Fser) +(ser Pser) -- (ser (select {from: Pser where: (>= i 0)})) +(de (ser Pser)) -- Fser +(count (de (ser Pser))) -- 7 +(ser (list Pser 1)) -- (ser (list Fser 1)) +(ser (dict [k] (list Pser))) -- (ser (dict [k] (list Fser))) +(de (ser (list 1 (dict [k] (list Pser))))) -- (list 1 (dict [k] (list Fser))) +;; a ragged table: the 2024.01.02 partition has no columns h..l, so their +;; segments are NULL; its rows go out as typed nulls (B8, which has none, +;; as false), exactly as the same flat table with nulls +(.db.splayed.set "/tmp/rfl_serde_parted/r/2024.01.01/t/" Aser) +(.db.splayed.set "/tmp/rfl_serde_parted/r/2024.01.02/t/" (table [i j] (list (at Bser 'i) (at Bser 'j)))) +(.db.splayed.set "/tmp/rfl_serde_parted/r/2024.01.03/t/" Cser) +(set Rser (.db.parted.get "/tmp/rfl_serde_parted/r/" 't)) +(set nulser (fn [c n] (concat (concat (at Aser c) n) (at Cser c)))) +(set Gnul (at (left-join [k] (table [k] (list [0 0])) (table [k g] (list [1] (take Gser 1)))) 'g)) +(set Nser (table [date i j h f b s t g ts l] (list Dser (catser 'i) (catser 'j) (nulser 'h (as 'I16 [0N 0N])) (nulser 'f (take 0Nf 2)) (nulser 'b [false false]) (nulser 's (as 'SYM (list "" ""))) (nulser 't (as 'STR (list "" ""))) (nulser 'g Gnul) (nulser 'ts (as 'TIMESTAMP [0N 0N])) (nulser 'l (list null null))))) +(ser Rser) -- (ser Nser) +(de (ser Rser)) -- Nser +(at (de (ser Rser)) 'f) -- [0.0 1.0 2.0 0Nf 0Nf 5.0 6.0] +(ser (list Rser 1)) -- (ser (list Nser 1)) +;; and it prints as that flat table: typed nulls in the partition's rows +;; (format "%" printed the column flattened by `at`, short of those rows) +(format "%" Rser) -- (format "%" Nser) +(format "%" Pser) -- (format "%" Fser) +;; a present segment holding nulls (no NULL segment): the flat column +;; carries HAS_NULLS (the OR over the segments), so the bytes match the +;; flat copy and the nulls read back as nulls +(.db.splayed.set "/tmp/rfl_serde_parted/n/2024.01.01/t/" (table [i f s] (list [1 2] [1.5 2.5] ['x 'y]))) +(.db.splayed.set "/tmp/rfl_serde_parted/n/2024.01.02/t/" (table [i f s] (list [3 0N 5] [0Nf 4.5 5.5] ['z ' 'x]))) +(.db.splayed.set "/tmp/rfl_serde_parted/n/2024.01.03/t/" (table [i f s] (list [6 7] [6.5 7.5] ['y 'z]))) +(set NPser (.db.parted.get "/tmp/rfl_serde_parted/n/" 't)) +(set NFser (table [date i f s] (list [2024.01.01 2024.01.01 2024.01.02 2024.01.02 2024.01.02 2024.01.03 2024.01.03] [1 2 3 0N 5 6 7] [1.5 2.5 0Nf 4.5 5.5 6.5 7.5] ['x 'y 'z ' 'x 'y 'z]))) +(ser NPser) -- (ser NFser) +(de (ser NPser)) -- NFser +(nil? (at (de (ser NPser)) 'i)) -- [false false false true false false false] +(nil? (at (de (ser NPser)) 'f)) -- [false false true false false false false] +(nil? (at (de (ser NPser)) 's)) -- [false false false true false false false] +;; SYM segments of different index widths (W8, then W16 past 256 symbols) +;; and an integer partition key +(.db.splayed.set "/tmp/rfl_serde_parted/w/0/t/" (table [a s] (list [1 2 3] ['x 'y 'x]))) +(.db.splayed.set "/tmp/rfl_serde_parted/w/1/t/" (table [a s] (list (til 400) (as 'SYM (map (fn [x] (as 'STR (+ 1000 x))) (til 400)))))) +(.db.splayed.set "/tmp/rfl_serde_parted/w/2/t/" (table [a s] (list [7 8] ['y 'x]))) +(set Wser (.db.parted.get "/tmp/rfl_serde_parted/w/" 't)) +(ser Wser) -- (ser (select {from: Wser where: (>= a 0)})) +(at (at (de (ser Wser)) 's) [0 3 402 403 404]) -- ['x '1000 '1399 'y 'x] +(at (at (de (ser Wser)) 'part) [0 3 403]) -- [0 1 2] +(.sys.exec "rm -rf /tmp/rfl_serde_parted") -- 0 diff --git a/test/rfl/system/splayed.rfl b/test/rfl/system/splayed.rfl index e7f8a7037..390058ab4 100644 --- a/test/rfl/system/splayed.rfl +++ b/test/rfl/system/splayed.rfl @@ -60,3 +60,73 @@ (count (.db.parted.get "/tmp/rfl_parted/" 't)) -- 10 ;; column count = 1 partition-key + 2 data columns (count (key (.db.parted.get "/tmp/rfl_parted/" 't))) -- 3 + +;; ────────────── LIST column cells keep their nulls ────────────── +;; A LIST column is stored in the nested format, which carries no attrs for a +;; fixed-width vector cell. The loader rebuilt the cell without HAS_NULLS, so +;; the sentinel read back as plain data: `[0N 2]` came back as +;; `[-9223372036854775808 2]`, and sum/nil? saw no null. One cell per +;; nullable nested type, a nested LIST cell among them. +(.sys.exec "rm -rf /tmp/rfl_splayed_listnull /tmp/rfl_parted_listnull") +(set LG (concat (guid 1) (as 'GUID 0N))) +(set LN (list [0Nl 2] [0Ni 3i] [0Nh 4h] [0Nf 1.5] [0Nd 2024.01.01] [0Nt 12:00:00.000] [0Np 2024.01.01D00:00:00.000000000] (concat ['a] (as 'SYM "")) ["x" ""] LG (list [0Nl 5] [1 2]))) +(set LT (table [k l] (list (til 11) LN))) +(set LNULLS (list [true false] [true false] [true false] [true false] [true false] [true false] [true false] [false true] [false true] [false true])) +;; the in-memory table is the reference +(take (map nil? (at LT 'l)) 10) -- LNULLS +(.db.splayed.set "/tmp/rfl_splayed_listnull/" LT) +(set LR (.db.splayed.get "/tmp/rfl_splayed_listnull/")) +(take (map nil? (at LR 'l)) 10) -- LNULLS +(nil? (first (at (at LR 'l) 10))) -- [true false] +(nil? (last (at (at LR 'l) 10))) -- [false false] +(map type (at LR 'l)) -- (map type (at LT 'l)) +(sum (first (at LR 'l))) -- 2 +(sum (at (at LR 'l) 3)) -- 1.5 +(at LR 'l) -- (at LT 'l) + +;; a parted table reads its LIST segments through the same loader +(.db.splayed.set "/tmp/rfl_parted_listnull/2024.01.01/t/" LT) +(.db.splayed.set "/tmp/rfl_parted_listnull/2024.01.02/t/" LT) +(set LP (.db.parted.get "/tmp/rfl_parted_listnull/" 't)) +(set LPL (at LP 'l)) +(count LPL) -- 22 +(take (map nil? LPL) 10) -- LNULLS +(take (map nil? (drop LPL 11)) 10) -- LNULLS +(nil? (first (at LPL 21))) -- [true false] +(map sum (at (select {from: LP where: (== k 0)}) 'l)) -- [2 2] +(.sys.exec "rm -rf /tmp/rfl_splayed_listnull /tmp/rfl_parted_listnull") + +;; ────────────── GUID atoms inside LIST cells ────────────── +;; The nested writer stored 8 bytes of a GUID atom's value union, which for +;; GUID is the pointer to its 16-byte payload: a fresh process dereferenced a +;; stale address (SIGSEGV), and in the writing process the loaded atom shared +;; the source's payload without a reference. The atom is now written as its +;; 16 bytes. The source table is released before the read back, and a second +;; process reads the same files. The flat GUID column g is the reference. +(.sys.exec "rm -rf /tmp/rfl_splayed_guidatom /tmp/rfl_parted_guidatom /tmp/rfl_guidatom_read.rfl") +(set GA (guid 3)) +(set GT (table [k g a] (list [0 1 2] GA (list (list (at GA 0) 1) (list 2 (list (at GA 1) (as 'GUID 0N))) (list (at GA 2)))))) +(.db.splayed.set "/tmp/rfl_splayed_guidatom/" GT) +(.db.splayed.set "/tmp/rfl_parted_guidatom/2024.01.01/t/" GT) +(.db.splayed.set "/tmp/rfl_parted_guidatom/2024.01.02/t/" GT) +(set GT 0) +(set GR (.db.splayed.get "/tmp/rfl_splayed_guidatom/")) +(== (first (at (at GR 'a) 0)) (at (at GR 'g) 0)) -- true +(== (first (last (at (at GR 'a) 1))) (at (at GR 'g) 1)) -- true +(== (first (at (at GR 'a) 2)) (at (at GR 'g) 2)) -- true +(nil? (last (last (at (at GR 'a) 1)))) -- true +(nil? (first (last (at (at GR 'a) 1)))) -- false +(set GP (.db.parted.get "/tmp/rfl_parted_guidatom/" 't)) +(count (at GP 'a)) -- 6 +(== (first (at (at GP 'a) 3)) (at (at GP 'g) 3)) -- true +(== (first (last (at (at GP 'a) 4))) (at (at GP 'g) 1)) -- true +(nil? (last (last (at (at GP 'a) 4)))) -- true +(set GR 0) +(set GP 0) +(.sys.exec "printf '%s\n' '(set R (.db.splayed.get \"/tmp/rfl_splayed_guidatom/\"))' '(set P (.db.parted.get \"/tmp/rfl_parted_guidatom/\" (quote t)))' '(println (and (== (first (at (at R (quote a)) 0)) (at (at R (quote g)) 0)) (== (first (last (at (at R (quote a)) 1))) (at (at R (quote g)) 1)) (nil? (last (last (at (at R (quote a)) 1)))) (== (first (at (at P (quote a)) 5)) (at (at P (quote g)) 2))))' > /tmp/rfl_guidatom_read.rfl") -- 0 +(.sys.exec "./rayforce /tmp/rfl_guidatom_read.rfl (at (.sys.info) 'cores) 0) -- true +(type (at (.sys.info) 'workers)) -- 'i64 +(> (at (.sys.info) 'workers) 0) -- true (> (at (.sys.info) 'total-mem) 0) -- true -(count (value (.sys.info))) -- 5 +(count (value (.sys.info))) -- 6 ;; ══════════════════════════════════════════════════════════════════════ ;; ray_hopen_fn (lines 769-825) diff --git a/test/rfl/system/timeit_lazy.rfl b/test/rfl/system/timeit_lazy.rfl new file mode 100644 index 000000000..af85f70dd --- /dev/null +++ b/test/rfl/system/timeit_lazy.rfl @@ -0,0 +1,26 @@ +;; timeit and .mem.ts must force a lazy result inside the measured span (#856). +;; A reduction over a named vector returns a lazy handle; if it is only built +;; (and released) inside the span, no worker ever runs and the reported time +;; covers graph construction alone. Worker activity is a deterministic proxy +;; for "the work ran inside the scope", unlike a wall-clock bound. +(set _tlv (as 'F64 (til 1000000))) + +;; .mem.ts: the reduction runs inside the measurement, and returns its value. +(set _tlm (.mem.ts (sum _tlv))) +(at _tlm 'result) -- 499999500000.0 +(> (at _tlm 'workers) 0) -- true +(> (at _tlm 'worker-busy-ns) 0) -- true + +;; timeit: the timed reduction executes (observed via an enclosing .mem.ts). +(set _tlt (.mem.ts (timeit (sum _tlv)))) +(type (at _tlt 'result)) -- 'f64 +(> (at _tlt 'workers) 0) -- true +(> (at _tlt 'worker-busy-ns) 0) -- true + +;; Same through a lambda returning the lazy reduction. +(set _tlf (fn [] (sum _tlv))) +(set _tltf (.mem.ts (timeit (_tlf)))) +(> (at _tltf 'worker-busy-ns) 0) -- true + +;; Errors from the timed expression still propagate. +(try (timeit (+ 1 'a)) (fn [e] 'err)) -- 'err diff --git a/test/rfl/table/alter.rfl b/test/rfl/table/alter.rfl index 5500c0653..72d2bac1b 100644 --- a/test/rfl/table/alter.rfl +++ b/test/rfl/table/alter.rfl @@ -56,12 +56,13 @@ EE -- [5 5 7] GG -- [42 4 5] FF -- [1 2 3 4 5] -;; ── a dotted target keeps taking the copy ─────────────────────────────── +;; ── a dotted target takes the copy when anything on its path is shared ── ;; `ray_env_get` resolves `d.x` to the leaf inside the container, and that ;; leaf usually holds the only reference to itself — so an rc test on it says ;; nothing about whether the container is shared. Writing through it would be ;; seen by every alias of the dict, and env_set_dotted's COW-rebuild of the -;; chain cannot undo a write that already landed. +;; chain cannot undo a write that already landed. Only a chain of dicts each +;; held once is amended in place (test_link.c pins that it is in place). (set DA (dict ['x] (list (til 3)))) (set DB DA) (alter 'DA.x set 0 99) @@ -75,3 +76,34 @@ DB.x -- [0 1 2] (alter 'TA.c set 0 77) (at TA 'c) -- [0 1 2] (at TB 'c) -- [0 1 2] + +;; sole-owned chain: amended in place, at any depth +(set DC (dict [cash v] (list 100 (til 4)))) +(alter 'DC.v set 1 50) +(alter 'DC.v set [2 3] 7) +DC.v -- [0 50 7 7] +DC.cash -- 100 +(set DN (dict [a] (list (dict [v] (list (til 3)))))) +(alter 'DN.a.v set 2 60) +DN.a.v -- [0 1 60] + +;; an alias of the head, of an inner dict, or of the leaf itself keeps its value +(set DM DN) +(alter 'DN.a.v set 0 9) +DN.a.v -- [9 1 60] +DM.a.v -- [0 1 60] +(set DI DN.a) +(alter 'DN.a.v set 1 8) +DN.a.v -- [9 8 60] +DI.v -- [9 1 60] +(set DL DC.v) +(alter 'DC.v set 0 -1) +DC.v -- [-1 50 7 7] +DL -- [0 50 7 7] + +;; an indexed leaf: dropping the index copies it, and the copy is bound +(set DX (dict [v] (list (.idx.zone [5 1 9])))) +(alter 'DX.v set 0 2) +DX.v -- [2 1 9] +(.idx.has? DX.v) -- false + diff --git a/test/rfl/temporal/time.rfl b/test/rfl/temporal/time.rfl index 0c935fece..ca727d498 100644 --- a/test/rfl/temporal/time.rfl +++ b/test/rfl/temporal/time.rfl @@ -19,3 +19,17 @@ ;; ordering (< 09:00:00.000 10:00:00.000) -- true (== 12:30:45.000 12:30:45.000) -- true + +;; the fraction is a decimal fraction of a second, as in a timestamp literal +;; and the CSV reader: short fractions are padded, digits past the third +;; dropped (#883) +09:30:00.5 -- 09:30:00.500 +09:30:00.50 -- 09:30:00.500 +09:30:00.05 -- 09:30:00.050 +09:30:00.123 -- 09:30:00.123 +09:30:00.1239 -- 09:30:00.123 +09:30:00.500000000 -- 09:30:00.500 +(as 'I64 00:00:00.5) -- 500 +(as 'I64 -00:00:00.5) -- -500 +[00:00:00.5 00:00:01.25] -- [00:00:00.500 00:00:01.250] +(== (as 'I64 00:00:00.5) (div (as 'I64 (- 2000.01.01D00:00:00.5 2000.01.01D00:00:00.000)) 1000000)) -- true diff --git a/test/rfl/temporal/timespan.rfl b/test/rfl/temporal/timespan.rfl new file mode 100644 index 000000000..9f3ebbec4 --- /dev/null +++ b/test/rfl/temporal/timespan.rfl @@ -0,0 +1,86 @@ +;; Signed nanosecond duration literals and full-width readback. +(type 1D) -- 'timespan +(type [1D 0D01:00:00]) -- 'TIMESPAN +(as 'I64 1D) -- 86400000000000 +(as 'I64 -0D00:00:00.000000001) -- -1 +(as 'I64 0D00:00:00.5) -- 500000000 +(format "%" -0D00:00:01) -- "-0D00:00:01.000000000" +(format "%" 1D) -- "1D00:00:00.000000000" +(type 0Nn) -- 'timespan +(nil? 0Nn) -- true +(nil? [1D 0Nn]) -- [false true] +(as 'I64 106751D23:47:16.854775807) -- 9223372036854775807 +(as 'I64 -106751D23:47:16.854775807) -- -9223372036854775807 +(eval (parse (format "%" [1D -0D00:00:00.000000001 0Nn]))) -- [1D -0D00:00:00.000000001 0Nn] +(as 'I64 106752D) -- -9223371273709551616 +0D24:00:00 -- 1D +(parse "0D00:60:00") !- domain +(parse "0D00:00:60") !- domain +(parse "1Dfoo") !- parse +(as 'timespan "0D00:00:01.25") -- 0D00:00:01.25 +(as 'TIMESPAN [1 0Nl -1]) -- [0D00:00:00.000000001 0Nn -0D00:00:00.000000001] +(as 'TIMESPAN 01:00:00.000) -- 0D01:00:00 +(as 'TIMESPAN [01:00:00.000 0Nt]) -- [0D01:00:00 0Nn] +;; Timestamp differences and offsets preserve duration units. +(- 2000.01.02D00:00:00.000000000 2000.01.01D00:00:00.000000000) -- 1D +(+ 2000.01.01D00:00:00.000000000 1D) -- 2000.01.02D00:00:00.000000000 +(- 2000.01.02D00:00:00.000000000 1D) -- 2000.01.01D00:00:00.000000000 +(+ 1D 2000.01.01D00:00:00.000000000) -- 2000.01.02D00:00:00.000000000 +(+ 1D 1) -- 1D00:00:00.000000001 +(== 1D 86400000000000) -- true +(* 0D00:00:01 3) -- 0D00:00:03 +(* 3 0D00:00:01) -- 0D00:00:03 +(div 0D00:00:03 2) -- 0D00:00:01.5 +(div 0D00:00:03 0D00:00:01) -- 0D00:00:00.000000003 +(/ 0D00:00:03 0D00:00:01) -- 3.0 +(% 0D00:00:03 0D00:00:01) !- type +(* 1D 1D) !- type +(div -0D00:00:00.000000001 2) -- -0D00:00:00.000000001 +(% -0D00:00:00.000000001 1000000000) -- 0D00:00:00.999999999 +(div 1D 0) -- 0Nn +(+ 1D 0Nn) -- 0Nn +(neg 1D) -- -1D +(+ [1D 0Nn] 1D) -- [2D 0Nn] +(* [1D 0D01:00:00] 2) -- [2D 0D02:00:00] +(neg [1D -1D 0Nn]) -- [-1D 1D 0Nn] +(xbar 2000.01.01D01:23:45.000000000 0D01:00:00) -- 2000.01.01D01:00:00.000000000 +(asc [1D -1D 0Nn 0D]) -- [0Nn -1D 0D 1D] +(min [1D 0D01:00:00 0Nn]) -- 0D01:00:00 +(max [1D 0D01:00:00 0Nn]) -- 1D +(sum [1D 1D 0Nn]) -- 2D +(avg [0D00:00:00.000000001 0D00:00:00.000000003]) -- 2.0 +;; Typed storage and query routes must keep the duration tag. +(de (ser [1D 0Nn -1D])) -- [1D 0Nn -1D] +(type (de (ser 1D))) -- 'timespan +(set T (table [s t] (list [1D 0D01:00:00 0Nn] [2000.01.01D00:00:00.000000000 2000.01.02D00:00:00.000000000 0Np]))) +(at (select {from:T y:(+ s 1D)}) 'y) -- [2D 1D01:00:00 0Nn] +(at (select {from:T y:(- t 2000.01.01D00:00:00.000000000)}) 'y) -- [0D 1D 0Nn] +(at (select {from:T y:(+ t s)}) 'y) -- [2000.01.02D00:00:00.000000000 2000.01.02D01:00:00.000000000 0Np] +(at (select {from:T y:(div s 2)}) 'y) -- [0D12:00:00 0D00:30:00 0Nn] +(count (select {from:T where:(> s 0) })) -- 2 +(type (take [1D 0Nn] 0)) -- 'TIMESPAN +(first [1D 0Nn]) -- 1D +(last [0Nn 1D]) -- 1D +(lag [1D 2D]) -- [0Nn 1D] +(count (distinct [1D 1D 0Nn 0Nn])) -- 2 +(count (inner-join [s] (table [s x] (list [1D 0D] [1 2])) (table [s y] (list [0D 1D] [3 4])))) -- 2 +(type (+ (as 'TIMESPAN []) 1)) -- 'TIMESPAN +(type (/ (as 'TIMESPAN []) 1D)) -- 'F64 +(+ [1D] [1 2]) !- length +(+ [0Nn 1D] [1D 0Nn]) -- [0Nn 0Nn] +(+ [1D] 0.5) -- [86400000000000.5] +(div [1D] [0D00:00:01]) -- [0D00:00:00.000086400] + +;; Mutation keeps duration payloads and rejects timestamp atoms. +(set SP (table [k s] (list [1 2] [1D 2D]))) +(insert 'SP (list 3 3D)) -- 'SP +(upsert 'SP 1 (list 2 0Nn)) -- 'SP +(at SP 's) -- [1D 0Nn 3D] +(upsert 'SP 1 (table [k s] (list [1 4] [-1D 4D]))) -- 'SP +(at SP 's) -- [-1D 0Nn 3D 4D] +(insert 'SP (list 5 2000.01.01D00:00:00.000000000)) !- type + +;; Bucket output uses the value column's physical width. +(xbar (as 'I16 [1 3 5]) 0D00:00:00.000000002) -- [0 2 4] +(xbar (as 'U8 [1 3 5]) 0D00:00:00.000000002) -- [0 2 4] +(xbar (as 'F32 [1 3 5]) 0D00:00:00.000000002) -- [0.0 2.0 4.0] diff --git a/test/rfl/temporal/timespan_operators.rfl b/test/rfl/temporal/timespan_operators.rfl new file mode 100644 index 000000000..5a0da360b --- /dev/null +++ b/test/rfl/temporal/timespan_operators.rfl @@ -0,0 +1,129 @@ +;; Scalar result types and values at duration operation boundaries. +(type (min [0Nn])) -- 'timespan +(as 'I64 (min [0Nn])) -- 9223372036854775807 +(type (max [0Nn])) -- 'timespan +(as 'I64 (max [0Nn])) -- -9223372036854775807 +(type (min (as 'TIMESPAN []))) -- 'timespan +(as 'I64 (min (as 'TIMESPAN []))) -- 9223372036854775807 +(type (max (as 'TIMESPAN []))) -- 'timespan +(as 'I64 (max (as 'TIMESPAN []))) -- -9223372036854775807 +(type (min [0Wn])) -- 'timespan +(as 'I64 (min [0Wn])) -- 9223372036854775807 +(type (max [-0Wn])) -- 'timespan +(as 'I64 (max [-0Wn])) -- -9223372036854775807 +(type 0D1) -- 'timespan +(as 'I64 0D1) -- 3600000000000 +(type 1D001) -- 'timespan +(as 'I64 1D001) -- 86460000000000 +(type 0D12345) -- 'timespan +(as 'I64 0D12345) -- 445500000000000 +(type 0D123456) -- 'timespan +(as 'I64 0D123456) -- 45296000000000 +(type 1D1.5) -- 'timespan +(as 'I64 1D1.5) -- 90000500000000 +(type 106752D) -- 'timespan +(as 'I64 106752D) -- -9223371273709551616 +(type 999999D) -- 'timespan +(as 'I64 999999D) -- -5833806768547758080 +(type (div 0D00:00:01 00:00:01.000)) -- 'timespan +(as 'I64 (div 0D00:00:01 00:00:01.000)) -- 1000000 +(type (/ 0D00:00:01 00:00:01.000)) -- 'f64 +(/ 0D00:00:01 00:00:01.000) -- 1000000.0 +(type (in 1D [86400000000000])) -- 'b8 +(in 1D [86400000000000]) -- true +(type (in 0Nn [0Nl])) -- 'b8 +(in 0Nn [0Nl]) -- true +(type (xbar 2000.01.02D01:00:00.000000000 1D)) -- 'timestamp +(as 'I64 (xbar 2000.01.02D01:00:00.000000000 1D)) -- 86400000000000 +(type (xbar 2000.01.02D01:00:00.000000000 0D)) -- 'timestamp +(nil? (xbar 2000.01.02D01:00:00.000000000 0D)) -- true +(type (xbar 2000.01.02D01:00:00.000000000 0Nn)) -- 'timestamp +(nil? (xbar 2000.01.02D01:00:00.000000000 0Nn)) -- true +(type (xbar 1D -2D)) -- 'timespan +(as 'I64 (xbar 1D -2D)) -- 172800000000000 +(type (xbar -0D00:00:00.000000001 0D00:00:01)) -- 'timespan +(as 'I64 (xbar -0D00:00:00.000000001 0D00:00:01)) -- -1000000000 +(type (xbar 2000.01.02 1D)) -- 'date +(as 'I64 (xbar 2000.01.02 1D)) -- 0 +(type (xbar 86400000000000 1D)) -- 'i64 +(xbar 86400000000000 1D) -- 86400000000000 +(type (xbar 0D00:00:00.000000004 2.5)) -- 'f64 +(xbar 0D00:00:00.000000004 2.5) -- 2.5 +(type 1D) -- 'timespan +(as 'I64 1D) -- 86400000000000 +(type -0D00:00:00.000000001) -- 'timespan +(as 'I64 -0D00:00:00.000000001) -- -1 +(type 1D01) -- 'timespan +(as 'I64 1D01) -- 90000000000000 +(type 0D24:00:00) -- 'timespan +(as 'I64 0D24:00:00) -- 86400000000000 +(type 0D99:00:00) -- 'timespan +(as 'I64 0D99:00:00) -- 356400000000000 +(type 0D00:00:00.1234567899) -- 'timespan +(as 'I64 0D00:00:00.1234567899) -- 123456789 +(type 0Wn) -- 'timespan +(as 'I64 0Wn) -- 9223372036854775807 +(type -0Wn) -- 'timespan +(as 'I64 -0Wn) -- -9223372036854775807 +(type (+ 0Wn 1)) -- 'timespan +(nil? (+ 0Wn 1)) -- true +(type (+ 0Wn 0Wn)) -- 'timespan +(as 'I64 (+ 0Wn 0Wn)) -- -2 +(type (+ 1D 1)) -- 'timespan +(as 'I64 (+ 1D 1)) -- 86400000000001 +(type (+ 1 1D)) -- 'timespan +(as 'I64 (+ 1 1D)) -- 86400000000001 +(type (- 1D 1)) -- 'timespan +(as 'I64 (- 1D 1)) -- 86399999999999 +(type (- 1 1D)) -- 'timespan +(as 'I64 (- 1 1D)) -- -86399999999999 +(type (+ 1D (as 'F32 1))) -- 'timespan +(as 'I64 (+ 1D (as 'F32 1))) -- 86400000000001 +(type (+ 1D 1.0)) -- 'f64 +(+ 1D 1.0) -- 86400000000000.0 +(type (* 1D 2)) -- 'timespan +(as 'I64 (* 1D 2)) -- 172800000000000 +(type (* 2 1D)) -- 'timespan +(as 'I64 (* 2 1D)) -- 172800000000000 +(type (* 1D (as 'F32 0.5))) -- 'timespan +(as 'I64 (* 1D (as 'F32 0.5))) -- 86400000000000 +(type (* 1D 0.5)) -- 'f64 +(* 1D 0.5) -- 43200000000000.0 +(* 1D 1D) !- type +(type (div 1D 1D)) -- 'timespan +(as 'I64 (div 1D 1D)) -- 1 +(type (div 1D 2)) -- 'timespan +(as 'I64 (div 1D 2)) -- 43200000000000 +(type (div 1D 2.5)) -- 'timespan +(as 'I64 (div 1D 2.5)) -- 28800000000000 +(type (div 1D 0)) -- 'timespan +(nil? (div 1D 0)) -- true +(% 1D 1D) !- type +(type (div -0D00:00:00.000000001 2)) -- 'timespan +(as 'I64 (div -0D00:00:00.000000001 2)) -- -1 +(type (% -0D00:00:00.000000001 1000000000)) -- 'timespan +(as 'I64 (% -0D00:00:00.000000001 1000000000)) -- 999999999 +(type (/ 1D 1D)) -- 'f64 +(/ 1D 1D) -- 1.0 +(type (/ 0D00:00:03 0D00:00:02)) -- 'f64 +(/ 0D00:00:03 0D00:00:02) -- 1.5 +(type (== 1D 86400000000000)) -- 'b8 +(== 1D 86400000000000) -- true +(type (== 0Nn 0Nl)) -- 'b8 +(== 0Nn 0Nl) -- true +(type (< 1D 86400000000001)) -- 'b8 +(< 1D 86400000000001) -- true +(type (- 2000.01.02D00:00:00.000000000 2000.01.01D00:00:00.000000000)) -- 'timespan +(as 'I64 (- 2000.01.02D00:00:00.000000000 2000.01.01D00:00:00.000000000)) -- 86400000000000 +(type (sum [1D 0Nn 2D])) -- 'timespan +(as 'I64 (sum [1D 0Nn 2D])) -- 259200000000000 +(type (avg [1D 0Nn 2D])) -- 'f64 +(avg [1D 0Nn 2D]) -- 129600000000000.0 +(type (min [1D 0Nn 2D])) -- 'timespan +(as 'I64 (min [1D 0Nn 2D])) -- 86400000000000 +(type (max [1D 0Nn 2D])) -- 'timespan +(as 'I64 (max [1D 0Nn 2D])) -- 172800000000000 +(type (neg 1D)) -- 'timespan +(as 'I64 (neg 1D)) -- -86400000000000 +(type (abs -1D)) -- 'timespan +(as 'I64 (abs -1D)) -- 86400000000000 diff --git a/test/rfl/temporal/timespan_parallel.rfl b/test/rfl/temporal/timespan_parallel.rfl new file mode 100644 index 000000000..955b20359 --- /dev/null +++ b/test/rfl/temporal/timespan_parallel.rfl @@ -0,0 +1,14 @@ +;; Duration keys and accumulators retain their 64-bit lanes across morsels. +(set N 100000) +(set K (table [s v] (list (as 'TIMESPAN (% (til N) 10)) (til N)))) +(set G (select {from:K by:s n:(count v) asc:s})) +(count G) -- 10 +(type (at G 's)) -- 'TIMESPAN +(as 'I64 (at G 's)) -- (til 10) +(at G 'n) -- (take [10000] 10) +(set V (table [k s] (list (% (til N) 10) (as 'TIMESPAN (til N))))) +(set R (select {from:V by:k total:(sum s) asc:k})) +(type (at R 'total)) -- 'TIMESPAN +(as 'I64 (at R 'total)) -- (+ 499950000 (* 10000 (til 10))) +(count (select {from:K where:(>= s 5)})) -- 50000 +(count (inner-join [s] K G)) -- N diff --git a/test/rfl/temporal/timespan_storage.rfl b/test/rfl/temporal/timespan_storage.rfl new file mode 100644 index 000000000..d937a32be --- /dev/null +++ b/test/rfl/temporal/timespan_storage.rfl @@ -0,0 +1,39 @@ +;; Duration columns retain their type in ordinary, encoded and parted storage. +(.sys.exec "rm -rf /tmp/rfl_timespan_store") -- 0 +(set S (table [k s] (list [1 1 2 2] [1D 0Nn -1D 0D01:00:00]))) +(.db.splayed.set "/tmp/rfl_timespan_store/plain" S {compress:false}) +(set P (.db.splayed.get "/tmp/rfl_timespan_store/plain")) +(type (at P 's)) -- 'TIMESPAN +(at P 's) -- [1D 0Nn -1D 0D01:00:00] +(at (select {from:P y:(+ s 1D)}) 'y) -- [2D 0Nn 0D 1D01:00:00] +(.db.splayed.set "/tmp/rfl_timespan_store/encoded" S {compress:true}) +(set E (.db.splayed.get "/tmp/rfl_timespan_store/encoded")) +(type (at E 's)) -- 'TIMESPAN +(at E 's) -- [1D 0Nn -1D 0D01:00:00] +(at (select {from:E y:(+ s 1D)}) 'y) -- [2D 0Nn 0D 1D01:00:00] +(sum (at E 's)) -- 0D01:00:00 +(min (at E 's)) -- -1D +(at (select {from:E by:k y:(sum s) asc:k}) 'y) -- [1D -0D23:00:00] +(at (select {from:E by:s n:(count k) asc:s}) 's) -- [0Nn -1D 0D01:00:00 1D] +(.db.splayed.set "/tmp/rfl_timespan_store/parts/2024.01.01/t" S {compress:false}) +(.db.splayed.set "/tmp/rfl_timespan_store/parts/2024.01.02/t" S {compress:true}) +(set D (.db.parted.get "/tmp/rfl_timespan_store/parts" 't)) +(at D 's) -- [1D 0Nn -1D 0D01:00:00 1D 0Nn -1D 0D01:00:00] +(sum (at D 's)) -- 0D02:00:00 +(at (select {from:D by:k y:(sum s) asc:k}) 'y) -- [2D -1D22:00:00] +(type (de (ser (at E 's)))) -- 'TIMESPAN +(.sys.exec "rm -rf /tmp/rfl_timespan_store") -- 0 +(.csv.write S "/tmp/rfl_timespan_store.csv") +(set C (.csv.read [I64 TIMESPAN] "/tmp/rfl_timespan_store.csv")) +(at C 's) -- [1D 0Nn -1D 0D01:00:00] +(.sys.exec "rm -f /tmp/rfl_timespan_store.csv") -- 0 + +;; Endpoint values and all-null groups retain duration extrema in encoded storage. +(set X (table [k s] (list [1 1 2 2] [0Wn 0Wn 0Nn 0Nn]))) +(.db.splayed.set "/tmp/rfl_timespan_extrema" X {compress:true}) +(set X (.db.splayed.get "/tmp/rfl_timespan_extrema")) +(min (at X 's)) -- 0Wn +(max (at X 's)) -- 0Wn +(at (select {from:X by:k lo:(min s) hi:(max s) asc:k}) 'lo) -- [0Wn 0Wn] +(at (select {from:X by:k lo:(min s) hi:(max s) asc:k}) 'hi) -- [0Wn -0Wn] +(.sys.exec "rm -rf /tmp/rfl_timespan_extrema") -- 0 diff --git a/test/rfl/type/as.rfl b/test/rfl/type/as.rfl index dd6d5e8d4..1e8e6186d 100644 --- a/test/rfl/type/as.rfl +++ b/test/rfl/type/as.rfl @@ -340,10 +340,12 @@ (as 'time "12x34x56") !- domain (as 'time "12:3") !- domain (as 'time "x") !- domain -;; time literals with 1-3 digit fractional seconds -10:00:00.1 -- 10:00:00.001 -10:00:00.01 -- 10:00:00.001 -10:00:00.12 -- 10:00:00.012 +;; time literals with 1-3 digit fractional seconds: a decimal fraction, as +;; the string cast above reads it +10:00:00.1 -- 10:00:00.100 +10:00:00.01 -- 10:00:00.010 +10:00:00.12 -- 10:00:00.120 +(== 10:00:00.1 (as 'time "10:00:00.1")) -- true 10:00:00.011 -- 10:00:00.011 10:00:00.123 -- 10:00:00.123 ;; ========== TIME VECTOR CASTS ========== @@ -643,3 +645,50 @@ (nil? (as 'I64 NaNf)) -- true (nil? (as 'I32 NaNf)) -- true (nil? (as 'I16 NaNf)) -- true + +;; ========== F32 (#881) ========== +;; f32 <- atoms +(type (as 'F32 1.5)) -- 'f32 +(as 'f32 1.5) -- (as 'F32 1.5) +(as 'F64 (as 'F32 1.5)) -- 1.5 +(as 'F64 (as 'F32 7)) -- 7.0 +(as 'F64 (as 'F32 true)) -- 1.0 +(as 'F64 (as 'F32 "2.5")) -- 2.5 +(nil? (as 'F32 "inf")) -- true +(nil? (as 'F32 0Nl)) -- true +(nil? (as 'F32 0Nf)) -- true +;; past the F32 range saturates to exactly +-FLT_MAX, as integer +;; narrowings do; it is not the null +(as 'F64 (as 'F32 1e300)) -- 3.4028234663852886e38 +(as 'F64 (as 'F32 -1e300)) -- -3.4028234663852886e38 +(nil? (as 'F32 [1e300 -1e300])) -- [false false] +;; temporal atoms, vectors and lists cast through their storage +(as 'F64 (as 'F32 2024.01.15)) -- 8780.0 +(as 'F64 (as 'F32 [2024.01.15])) -- [8780.0] +(as 'F64 (as 'F32 00:00:01.000)) -- 1000.0 +(as 'F64 (as 'F32 [00:00:01.000])) -- [1000.0] +(as 'F64 (as 'F32 2000.01.01D00:00:00.000001000)) -- 1000.0 +(as 'F64 (as 'F32 (list 2024.01.15 00:00:01.000))) -- [8780.0 1000.0] +;; f32 -> other atoms +(as 'i64 (as 'F32 7.9)) -- 7 +(as 'i32 (as 'F32 7.9)) -- 7i +(as 'b8 (as 'F32 2)) -- true +(as 'sym (as 'F32 0.5)) -- '0.5 +;; f32 <- vectors (null-preserving), and back +(type (as 'F32 [1 2 3])) -- 'F32 +(as 'F64 (as 'F32 [1 0Nl 3])) -- [1.0 0Nf 3.0] +(as 'F64 (as 'F32 [1.5 0Nf 2.25])) -- [1.5 0Nf 2.25] +(as 'I64 (as 'F32 [1.5 0Nf 7.9])) -- [1 0Nl 7] +(as 'I16 (as 'F32 [1e10 -1e10])) -- [32767h -32767h] +(as 'F64 (as 'F32 (list 1 2.5 0Nl))) -- [1.0 2.5 0Nf] +(nil? (as 'F32 [0Nl 0Nf])) -- [true true] +;; large enough for the parallel cast path +(sum (as 'F64 (as 'F32 (til 300000)))) -- 44999850000.0 +;; the builtin, vector and query casts agree, both signs and nulls +(set F32V [1e300 -1e300 0Nf 1.5]) +(set F32T (table [v d] (list F32V [2024.01.15 2024.01.16 0Nd 2024.01.17]))) +(as 'F64 (as 'F32 F32V)) -- [3.4028234663852886e38 -3.4028234663852886e38 0Nf 1.5] +(as 'F64 (at (select {x: (as 'F32 v) from: F32T}) 'x)) -- [3.4028234663852886e38 -3.4028234663852886e38 0Nf 1.5] +(as 'F64 (at (update {w: (as 'F32 v) from: F32T}) 'w)) -- [3.4028234663852886e38 -3.4028234663852886e38 0Nf 1.5] +(as 'F64 (at (select {x: (as 'F32 d) from: F32T}) 'x)) -- [8780.0 8781.0 0Nf 8782.0] +(as 'F64 (as 'F32 (at F32T 'd))) -- [8780.0 8781.0 0Nf 8782.0] diff --git a/test/rfl/type/as_nested_str.rfl b/test/rfl/type/as_nested_str.rfl new file mode 100644 index 000000000..7fef3d543 --- /dev/null +++ b/test/rfl/type/as_nested_str.rfl @@ -0,0 +1,16 @@ +;; A flat STR result needs one string atom per input cell, not a nested vector. +(set NestedStrSource (list [1 2] [3 4])) +(as 'STR NestedStrSource) !- type +NestedStrSource -- (list [1 2] [3 4]) +(as 'STR (list 7 [1 2])) !- type +(as 'STR (list "a long first string cell" [1 2])) !- type +(as 'STR (list (list 1 2))) !- type +(as 'STR (list [])) !- type + +(as 'STR 42) -- "42" +(as 'STR [1 2]) -- ["1" "2"] +(as 'STR (list 1 2)) -- ["1" "2"] +(as 'STR (list 1 true 'x)) -- ["1" "true" "x"] +(as 'STR (list "" "text")) -- ["" "text"] +(type (as 'STR [])) -- 'STR +(count (as 'STR [])) -- 0 diff --git a/test/rfl/type/as_nested_str_parted.rfl b/test/rfl/type/as_nested_str_parted.rfl new file mode 100644 index 000000000..6ed9b4bcb --- /dev/null +++ b/test/rfl/type/as_nested_str_parted.rfl @@ -0,0 +1,14 @@ +;; @requires: posix +;; Original #733 shape: grouped parted output holds I64 vectors in a LIST. +(.db.splayed.set "__cast733/2024.01.01/t/" (table [s v] (list ['b 'a 'c] [10 20 30]))) +(.db.splayed.set "__cast733/2024.01.02/t/" (table [s v] (list ['a 'b 'd] [40 50 60]))) +(set Cast733 (.db.parted.get "__cast733/" 't)) +(set Cast733Vals (at (select {a: v by: s from: Cast733}) 'a)) +(type Cast733Vals) -- 'LIST +(count Cast733Vals) -- 4 +(type (at Cast733Vals 0)) -- 'I64 +(as 'STR Cast733Vals) !- type +(count Cast733Vals) -- 4 +(set Cast733Vals 0) +(set Cast733 0) +(.sys.exec "rm -rf __cast733") diff --git a/test/test.h b/test/test.h index 8f67db58d..d284e3ee0 100644 --- a/test/test.h +++ b/test/test.h @@ -36,6 +36,7 @@ #ifndef RAY_TEST_H #define RAY_TEST_H +#include #include #include #include @@ -46,6 +47,31 @@ int ray_test_rm_rf(const char* path); /* rm -rf path */ int ray_test_mkdir_p(const char* path); /* mkdir -p path */ +/* Per-process scratch root. Every "/tmp/..." path a test names goes + * through ray_test_tmp(), which returns the string with each "/tmp" path + * prefix moved under this process's own root (/tmp/rayforce_t., + * created at startup and removed at exit), so two suites running on one + * host never share a file. The argument may be a whole Rayfall source or + * shell line: every "/tmp" path inside it moves. The result is interned + * and valid for the life of the process. .rfl files get the same rewrite + * when they are read. Call it from the test thread only. */ +const char* ray_test_tmp(const char* s); + +/* Disarm every global store / decode / bind test hook and clear a pending + * interrupt request. Teardowns of suites that arm hooks call it, so a test + * that fails between arming and disarming never leaks the hook into the + * tests after it. */ +void ray_test_hooks_off(void); + +/* True while the equivalence pass runs a test (every save is generation 2). + * A loaded column or segment is mapped in place (mmod 1; a string pool + * shares the mapping, mmod 3) after a generation-0 save, and decoded into + * heap memory (mmod 0) after a generation-2 one: residency asserts take the + * generation into account so the rest of the test still runs in both. */ +bool ray_test_equiv_pass(void); +#define TEST_ASSERT_LOADED_MMOD(v, gen0_mmod) \ + TEST_ASSERT_EQ_U((v)->mmod, ray_test_equiv_pass() ? 0u : (unsigned)(gen0_mmod)) + #if defined(_WIN32) /* POSIX helpers the tests rely on, mapped onto their MSVCRT equivalents. * Test paths use "/tmp/...", which Windows resolves to :\tmp; the diff --git a/test/test_agg_contract.c b/test/test_agg_contract.c index 143dc6048..4484cf38a 100644 --- a/test/test_agg_contract.c +++ b/test/test_agg_contract.c @@ -17,6 +17,7 @@ #include "lang/internal.h" #include "lang/env.h" #include "table/sym.h" +#include "store/enccol.h" /* ray_enccol_of: decoded bytes of a generation-2 column */ #include #include @@ -32,6 +33,9 @@ static void contract_setup(void) { static void contract_teardown(void) { ray_agg_engine_v2 = true; ray_agg_first_n = true; + ray_agg_tablestack = true; + ray_agg_radix_wave_bytes = 0; + ray_agg_radix_spill = 0; ray_runtime_destroy(contract_runtime); if (ray_pool_total_workers(ray_pool_get()) != contract_cores) { ray_pool_destroy(); @@ -653,6 +657,346 @@ static test_result_t test_dense_symbol_output(void) { PASS(); } +/* One integer key whose range passes the row count (600k rows, a 1.2M-slot + * range) runs as the shared slab when the slab fits the room under the memory + * watermark, and takes the radix route it took before when the watermark + * leaves no room. Both answer alike: each group's count and sum equal the + * oracle's; a count-only slab holds u32 counters and a count + sum slab the + * 8-byte states; and under an armed `desc|asc: count take: 10` filter exactly + * the oracle's ten groups come out (ties at the boundary cut by first row), + * the dense emit allocating those ten and no entry per group. */ +static test_result_t test_dense_wide_range(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + const int64_t n = 600000, groups = 150000, step = 8; + ray_t* key = ray_vec_new(RAY_I64, n); + ray_t* val = ray_vec_new(RAY_I64, n); + key->len = val->len = n; + static int64_t counts[150000], sums[150000], firstrow[150000]; + static bool want[2][150000]; + memset(counts, 0, sizeof counts); memset(sums, 0, sizeof sums); memset(want, 0, sizeof want); + for (int64_t g = 0; g < groups; g++) firstrow[g] = INT64_MAX; + for (int64_t i = 0; i < n; i++) { + int64_t g = i % 4 == 0 ? (i / 4) % 1000 : (i * 31) % groups; + ((int64_t*)ray_data(key))[i] = g * step + 5; + ((int64_t*)ray_data(val))[i] = i % 97; + counts[g]++; sums[g] += i % 97; + if (firstrow[g] == INT64_MAX) firstrow[g] = i; + } + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("k", 1), key); + tbl = ray_table_add_col(tbl, ray_sym_intern("v", 1), val); + ray_release(key); ray_release(val); + int64_t present = 0; + for (int64_t g = 0; g < groups; g++) present += counts[g] > 0; + /* the ten groups a top-10 cut answers: by count, then by first row */ + for (int dir = 0; dir < 2; dir++) /* 0: desc, 1: asc */ + for (int pick = 0; pick < 10; pick++) { + int64_t best = -1; + for (int64_t g = 0; g < groups; g++) { + if (!counts[g] || want[dir][g]) continue; + if (best < 0 || (dir ? counts[g] < counts[best] : counts[g] > counts[best]) || + (counts[g] == counts[best] && firstrow[g] < firstrow[best])) best = g; + } + want[dir][best] = true; + } + /* the boundary of the desc cut is a tie of several groups */ + int64_t tied = 0, edge = 0; + for (int64_t g = 0; g < groups; g++) if (want[0][g] && (!edge || counts[g] < edge)) edge = counts[g]; + for (int64_t g = 0; g < groups; g++) tied += counts[g] == edge; + TEST_ASSERT_TRUE(tied > 1); + const int64_t wm = ray_heap_anon_watermark(); + for (int room = 0; room < 4; room++) { + /* 0 count, 1 count+sum, 2 count desc take 10, 3 count asc take 10, + * 4 count+sum desc take 10 */ + for (int mode = 0; mode < 5; mode++) { + ray_graph_t* graph = ray_graph_new(tbl); + ray_op_t* keys[] = {ray_scan(graph, "k")}; + ray_op_t* v = ray_scan(graph, "v"); + ray_op_t* inputs[] = {v, v}; + uint16_t ops[] = {OP_COUNT, OP_SUM}; + ray_op_t* group = ray_group(graph, keys, 1, ops, inputs, mode == 1 || mode == 4 ? 2 : 1); + ray_group_emit_filter_t prev = ray_group_emit_filter_get(); + if (mode >= 2) { + ray_group_emit_filter_t f = {0}; + f.enabled = 1; f.agg_index = 0; f.top_count_take = 10; f.desc = mode != 3; + ray_group_emit_filter_set(f); + } + /* little room: the watermark sits a megabyte (room 1: under the range + * cap), 6 MB (room 2: past the cap, short of the u32 slab and a third + * more) or 8 MB (room 3: the u32 slab fits, the 8-byte states do not) + * past what is committed and not reusable by this heap */ + if (room) { + int64_t tight = ray_heap_anon_committed() - ray_heap_anon_reusable() + + (room == 1 ? INT64_C(1) << 20 : room == 2 ? INT64_C(6) << 20 : INT64_C(8) << 20); + ray_heap_set_anon_watermark(tight > 0 ? tight : 1); + } + agg_route_reset(); + ray_t* out = ray_execute(graph, group); + agg_route_stats_t st = agg_route_stats(); + ray_heap_set_anon_watermark(wm); + ray_group_emit_filter_set(prev); + TEST_ASSERT_NOT_NULL(out); TEST_ASSERT_FALSE(RAY_IS_ERR(out)); + TEST_ASSERT_EQ_I(st.radix_spill_bytes, 0); + bool dense = false; + bool count_only = mode == 0 || mode == 2 || mode == 3; +#if ATOMIC_LLONG_LOCK_FREE == 2 + if ((!room || (room == 3 && count_only)) && wm > 0) { + dense = true; + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 1); + TEST_ASSERT_EQ_I(st.dense_strategy, AGG_DENSE_SHARED); + TEST_ASSERT_EQ_I(st.dense_local_slots, (groups - 1) * step + 1); + /* count alone: u32 counters; count + sum: the 8-byte states */ + TEST_ASSERT_EQ_I(st.dense_count32, count_only); + /* under a top-N filter the emit allocates the ten groups only */ + TEST_ASSERT_EQ_I(st.dense_emit_slots, mode >= 2 ? 10 : present); + } + if (room && !dense) { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 0); + TEST_ASSERT_FALSE(st.dense_plan_available); + } +#endif + ray_t* ko = ray_table_get_col_idx(out, 0); + ray_t* co = ray_table_get_col_idx(out, 1); + ray_t* so = mode == 1 || mode == 4 ? ray_table_get_col_idx(out, 2) : NULL; + TEST_ASSERT_EQ_I(ko->len, mode >= 2 ? 10 : present); + int64_t prev_first = -1; + for (int64_t r = 0; r < ko->len; r++) { + int64_t k = ((int64_t*)ray_data(ko))[r]; + TEST_ASSERT_EQ_I((k - 5) % step, 0); + int64_t g = (k - 5) / step; + TEST_ASSERT_TRUE(g >= 0 && g < groups); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(co))[r], counts[g]); + if (so) TEST_ASSERT_EQ_I(((int64_t*)ray_data(so))[r], sums[g]); + if (mode >= 2) { + TEST_ASSERT_TRUE(want[mode == 3][g]); + /* equal counts keep first-row order, as the radix route emits them */ + if (dense) { TEST_ASSERT_TRUE(firstrow[g] > prev_first); prev_first = firstrow[g]; } + } + } + ray_release(out); ray_graph_free(graph); + } + } + /* Four groups spread over the same wide range: the sample sees few + * distinct keys, so the range is not worth a slab and the key keeps its + * sparse-key route. */ + { + ray_t* sk = ray_vec_new(RAY_I64, n); + sk->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(sk))[i] = (i % 4) * 1000000; + ray_t* st = ray_table_new(1); + st = ray_table_add_col(st, ray_sym_intern("k", 1), sk); + ray_release(sk); + ray_graph_t* graph = ray_graph_new(st); + ray_op_t* keys[] = {ray_scan(graph, "k")}; + uint16_t ops[] = {OP_COUNT}; + ray_op_t* inputs[] = {ray_scan(graph, "k")}; + ray_op_t* group = ray_group(graph, keys, 1, ops, inputs, 1); + agg_route_reset(); + ray_t* out = ray_execute(graph, group); + TEST_ASSERT_NOT_NULL(out); TEST_ASSERT_FALSE(RAY_IS_ERR(out)); + TEST_ASSERT_EQ_I(agg_route_stats().routes[AGG_ROUTE_V2_DENSE], 0); + TEST_ASSERT_EQ_I(ray_table_nrows(out), 4); + ray_release(out); ray_graph_free(graph); ray_release(st); + } + ray_release(tbl); + PASS(); +} + +/* A key whose range is within the row count but whose per-worker slabs do not + * fit the dense budget (a quarter of a low watermark) is a wide plan too: the + * shared u32 slab is considered before the per-worker budget check turns the + * grouping to the radix route. With less room than that slab it still takes + * the radix route; the answers are the same. */ +static test_result_t test_dense_wide_budget(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + const int64_t n = 600000, range = 590000; + ray_t* key = ray_vec_new(RAY_I64, n); + ray_t* val = ray_vec_new(RAY_I64, n); + key->len = val->len = n; + static int64_t counts[590000]; + memset(counts, 0, sizeof counts); + for (int64_t i = 0; i < n; i++) { + int64_t g = (i * 7919) % range; + ((int64_t*)ray_data(key))[i] = g; + ((int64_t*)ray_data(val))[i] = i; + counts[g]++; + } + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("k", 1), key); + tbl = ray_table_add_col(tbl, ray_sym_intern("v", 1), val); + ray_release(key); ray_release(val); + const int64_t wm = ray_heap_anon_watermark(); + for (int level = 0; level < 2; level++) { + ray_graph_t* graph = ray_graph_new(tbl); + ray_op_t* keys[] = {ray_scan(graph, "k")}; + ray_op_t* v = ray_scan(graph, "v"); + ray_op_t* inputs[32]; + uint16_t ops[32]; + for (int a = 0; a < 32; a++) { inputs[a] = v; ops[a] = OP_COUNT; } + ray_op_t* group = ray_group(graph, keys, 1, ops, inputs, 32); + /* level 0: 20 MB of room, a quarter of the watermark under the 156 MB + * the per-worker slabs need; level 1: 1 MB of room, under the slab */ + int64_t tight = ray_heap_anon_committed() - ray_heap_anon_reusable() + + (level ? INT64_C(1) << 20 : INT64_C(20) << 20); + TEST_ASSERT_TRUE(tight / 4 < range * (32 * 8 + 9)); + ray_heap_set_anon_watermark(tight > 0 ? tight : 1); + agg_route_reset(); + ray_t* out = ray_execute(graph, group); + agg_route_stats_t st = agg_route_stats(); + ray_heap_set_anon_watermark(wm); + TEST_ASSERT_NOT_NULL(out); TEST_ASSERT_FALSE(RAY_IS_ERR(out)); +#if ATOMIC_LLONG_LOCK_FREE == 2 + if (!level) { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 1); + TEST_ASSERT_EQ_I(st.dense_strategy, AGG_DENSE_SHARED); + TEST_ASSERT_TRUE(st.dense_count32); + TEST_ASSERT_FALSE(st.dense_worker_budget); + } else { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 0); + } +#endif + ray_t* ko = ray_table_get_col_idx(out, 0); + TEST_ASSERT_EQ_I(ko->len, range); + for (int a = 1; a <= 32; a++) { + ray_t* co = ray_table_get_col_idx(out, a); + for (int64_t r = 0; r < ko->len; r += 97) + TEST_ASSERT_EQ_I(((int64_t*)ray_data(co))[r], counts[((int64_t*)ray_data(ko))[r]]); + } + ray_release(out); ray_graph_free(graph); + } + ray_release(tbl); + PASS(); +} + +/* A key whose slab alone fits the dense budget (a quarter of a low watermark) + * but whose per-worker slabs and partitioned plan do not: the planner keeps + * it off the wide plan, and no per-worker dense plan fits, so the one shared + * u32 slab runs it instead of the radix scatter. The slab is sized from the + * room this heap has: 0.9 of a quarter of the watermark, over twice as many + * rows, every group counted twice. */ +static test_result_t test_dense_wide_after_worker_budget(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + const int64_t wm = ray_heap_anon_watermark(); + int64_t base = ray_heap_anon_committed() - ray_heap_anon_reusable(); + if (base < 0) base = 0; + const int64_t room = INT64_C(64) << 20; + int64_t range = (int64_t)(0.9 * (double)((base + room) / 4) / (8 + 8 + 1)) | 1; + while (range % 7919 == 0) range += 2; + const int64_t n = 2 * range; + ray_t* key = ray_vec_new(RAY_I64, n); + key->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(key))[i] = (i * 7919) % range; + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("k", 1), key); + ray_release(key); + for (int level = 0; level < 2; level++) { + ray_graph_t* graph = ray_graph_new(tbl); + ray_op_t* keys[] = {ray_scan(graph, "k")}; + uint16_t ops[] = {OP_COUNT}; + ray_op_t* inputs[] = {ray_scan(graph, "k")}; + ray_op_t* group = ray_group(graph, keys, 1, ops, inputs, 1); + /* level 0: the watermark 64 MB past what this heap holds (the table + * included); level 1: 1 MB past it, under the u32 slab */ + int64_t held = ray_heap_anon_committed() - ray_heap_anon_reusable(); + int64_t tight = (held > 0 ? held : 0) + (level ? INT64_C(1) << 20 : room); + if (!level) TEST_ASSERT_TRUE(range * (8 + 8 + 1) <= tight / 4); /* the slab alone fits */ + ray_heap_set_anon_watermark(tight); + agg_route_reset(); + ray_t* out = ray_execute(graph, group); + agg_route_stats_t st = agg_route_stats(); + ray_heap_set_anon_watermark(wm); + TEST_ASSERT_NOT_NULL(out); TEST_ASSERT_FALSE(RAY_IS_ERR(out)); +#if ATOMIC_LLONG_LOCK_FREE == 2 + if (!level) { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 1); + TEST_ASSERT_EQ_I(st.dense_strategy, AGG_DENSE_SHARED); + TEST_ASSERT_TRUE(st.dense_count32); + TEST_ASSERT_FALSE(st.dense_worker_budget); + TEST_ASSERT_EQ_I(st.radix_spill_bytes, 0); + } else { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 0); + } +#endif + TEST_ASSERT_EQ_I(ray_table_nrows(out), range); + ray_t* ko = ray_table_get_col_idx(out, 0); + ray_t* co = ray_table_get_col_idx(out, 1); + bool* seen = ray_calloc_raw((size_t)range); + TEST_ASSERT_NOT_NULL(seen); + for (int64_t r = 0; r < ko->len; r++) { + int64_t k = ((int64_t*)ray_data(ko))[r]; + TEST_ASSERT_TRUE(k >= 0 && k < range && !seen[k]); + seen[k] = true; + TEST_ASSERT_EQ_I(((int64_t*)ray_data(co))[r], 2); + } + ray_free_raw(seen); + ray_release(out); ray_graph_free(graph); + } + ray_release(tbl); + PASS(); +} + +/* The same ordering under a where filter: the plan within the row count whose + * per-worker slabs do not fit is promoted to the one shared slab, which + * counts the selected rows only. */ +static test_result_t test_dense_wide_budget_sel(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + const int64_t n = 600000, range = 590000, cut = 1000; + static int64_t counts[590000]; + memset(counts, 0, sizeof counts); + int64_t kept = 0; + for (int64_t i = cut + 1; i < n; i++) { counts[(i * 7919) % range]++; kept++; } + ray_t* r = ray_eval_str("(set wbs_i (til 600000))" + "(set wbs_t (table [k v] (list (% (* wbs_i 7919) 590000) wbs_i)))"); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); ray_release(r); + char q[2048]; + int len = snprintf(q, sizeof q, "(select {from: wbs_t by: k"); + for (int a = 0; a < 32; a++) len += snprintf(q + len, sizeof q - len, " c%d: (count v)", a); + snprintf(q + len, sizeof q - len, " where: (> v %lld)})", (long long)cut); + const int64_t wm = ray_heap_anon_watermark(); + for (int level = 0; level < 2; level++) { + int64_t tight = ray_heap_anon_committed() - ray_heap_anon_reusable() + + (level ? INT64_C(1) << 20 : INT64_C(20) << 20); + TEST_ASSERT_TRUE(tight / 4 < range * (32 * 8 + 9)); + ray_heap_set_anon_watermark(tight > 0 ? tight : 1); + agg_route_reset(); + ray_t* out = ray_eval_str(q); + agg_route_stats_t st = agg_route_stats(); + ray_heap_set_anon_watermark(wm); + TEST_ASSERT_NOT_NULL(out); TEST_ASSERT_FALSE(RAY_IS_ERR(out)); +#if ATOMIC_LLONG_LOCK_FREE == 2 + if (!level) { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 1); + TEST_ASSERT_EQ_I(st.dense_strategy, AGG_DENSE_SHARED); + TEST_ASSERT_TRUE(st.dense_count32); + TEST_ASSERT_FALSE(st.dense_worker_budget); + } else { + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_DENSE], 0); + } +#endif + ray_t* ko = ray_table_get_col_idx(out, 0); + int64_t present = 0, total = 0; + for (int64_t g = 0; g < range; g++) present += counts[g] > 0; + TEST_ASSERT_EQ_I(ko->len, present); + for (int a = 1; a <= 32; a += 31) { + ray_t* co = ray_table_get_col_idx(out, a); + for (int64_t i = 0; i < ko->len; i++) { + int64_t k = ((int64_t*)ray_data(ko))[i]; + TEST_ASSERT_EQ_I(((int64_t*)ray_data(co))[i], counts[k]); + if (a == 1) total += counts[k]; + } + } + TEST_ASSERT_EQ_I(total, kept); + ray_release(out); + } + r = ray_eval_str("(set wbs_i 0) (set wbs_t 0)"); + if (r) ray_release(r); + PASS(); +} + /* Task input ranges can be disjoint, cross bitmap words, and contain only nulls. * Repeating the query also verifies that reused occupancy bits are cleared. */ static test_result_t test_dense_task_local(void) { @@ -731,6 +1075,66 @@ static test_result_t test_dense_task_local(void) { PASS(); } +/* #973: adding duration support to indexed rank consumers must not broaden + * unrelated aggregators' type admission. No execution is needed to test it. */ +static test_result_t test_timespan_rank_admission(void) { + ray_t* tbl = ray_eval_str("(table [k v] (list [0 0 1 1] (as 'TIMESPAN [1 2 -4 -1])))"); + TEST_ASSERT_FMT(tbl && !RAY_IS_ERR(tbl), "duration admission fixture"); + const uint16_t operations[] = { OP_MEDIAN, OP_QUANTILE, OP_MODE }; + for (int a = 0; a < 3; a++) { + ray_graph_t* graph = ray_graph_new(tbl); + TEST_ASSERT_NOT_NULL(graph); + ray_op_t* keys[] = { ray_scan(graph, "k") }; + ray_op_t* ins[] = { ray_scan(graph, "v") }; + int64_t param = 0; + double q = 0.25; + if (operations[a] == OP_QUANTILE) memcpy(¶m, &q, sizeof(param)); + uint16_t operation = operations[a]; + ray_op_t* group = ray_group_build(graph, keys, 1, &operation, ins, NULL, ¶m, 1); + bool built = group != NULL; + agg_v2_reason_t got = built ? agg_v2_admission(graph, group, tbl) : AGG_V2_SHAPE; + ray_graph_free(graph); + agg_v2_reason_t want = a < 2 ? AGG_V2_ADMITTED : AGG_V2_AGG_TYPE; + TEST_ASSERT_FMT(built && got == want, "duration rank admission op=%u got=%d want=%d", + operations[a], got, want); + } + ray_release(tbl); + PASS(); +} + +/* Native F64 nanoseconds, NULL publication, empty groups, explicit reversed + * row indices and an actual offset SLICE (not merely a negative TAKE). */ +static test_result_t test_timespan_rank_slice(void) { + ray_t* parent = ray_eval_str("(as 'TIMESPAN [123 0Nl 1 2 0Nl -4 -1 0Nl 0Nl 456])"); + TEST_ASSERT_FMT(parent && !RAY_IS_ERR(parent), "duration slice fixture"); + int64_t original[10]; + memcpy(original, ray_data(parent), sizeof(original)); + ray_t* slice = ray_vec_slice(parent, 1, 8); + TEST_ASSERT_FMT(slice && !RAY_IS_ERR(slice) && (slice->attrs & RAY_ATTR_SLICE), "real offset slice"); + const int64_t identity[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; + const int64_t reversed[] = { 3, 2, 1, 0, 5, 4, 7, 6 }; + const int64_t offsets[] = { 0, 4, 6, 8 }, counts[] = { 4, 2, 2, 0 }; + for (int indexed = 0; indexed < 2; indexed++) { + for (int quantile = 0; quantile < 2; quantile++) { + ray_t* out = quantile + ? ray_quantile_per_group_buf(slice, indexed ? reversed : identity, offsets, counts, 4, 0.25) + : ray_median_per_group_buf(slice, indexed ? reversed : identity, offsets, counts, 4); + TEST_ASSERT_FMT(out && !RAY_IS_ERR(out), "duration rank slice result"); + TEST_ASSERT_EQ_I(out->type, RAY_F64); + TEST_ASSERT_EQ_I(out->len, 4); + TEST_ASSERT_EQ_F(((double*)ray_data(out))[0], quantile ? 1.25 : 1.5, 0.0); + TEST_ASSERT_EQ_F(((double*)ray_data(out))[1], quantile ? -3.25 : -2.5, 0.0); + TEST_ASSERT_TRUE(out->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(out, 2)); + TEST_ASSERT_TRUE(ray_vec_is_null(out, 3)); + ray_release(out); + } + } + TEST_ASSERT_TRUE(memcmp(original, ray_data(parent), sizeof(original)) == 0); + ray_release(slice); ray_release(parent); + PASS(); +} + static test_result_t test_rank_widths_nulls_and_slices(void) { const int8_t types[] = { RAY_BOOL, RAY_F32 }; for (int t = 0; t < 2; t++) { @@ -994,7 +1398,7 @@ static test_result_t test_fused_typed_comparisons(void) { ray_op_t* rhs = ray_const_atom(graph, constant); ray_op_t* predicate = ctors[op](graph, &graph->nodes[id], rhs); fp_pred_t compiled = {0}; - TEST_ASSERT_FMT(fp_compile_pred(graph, predicate, tbl, &compiled) == 0, + TEST_ASSERT_FMT(fp_compile_pred(graph, predicate, tbl, &compiled, &(ray_t*){NULL}) == 0, "fused %s comparison %d declined", ray_type_name(types[t]), op); uint8_t bits[4]; fp_eval_pred(&compiled, 0, 4, bits); for (int r = 0; r < 4; r++) { @@ -2070,6 +2474,46 @@ static test_result_t test_dense_unordered_take(void) { PASS(); } +static bool first_n_same_table(ray_t* a, ray_t* b); + +/* Unordered take: N where the first N groups hold a large share of the + * rows (one heavy group) on a dense key: the pre-pass gives the shape to the + * bounded full run, whose task-local dense route selects the N smallest + * first rows itself (an unbounded run plus a pick is slower there). The + * pick is taken only where the bounded run would leave the dense routes. */ +static test_result_t test_first_n_heavy_dense(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(8), RAY_OK); + ray_t* setup = ray_eval_str( + "(set hv_i (til 400000)) " + "(set hv_t (table [k v] (list (as 'I32 (* (!= 0 (% hv_i 3)) (% (* hv_i 7919) 50000))) hv_i)))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + ray_agg_first_n = false; + ray_t* old = ray_eval_str("(select {from:hv_t c:(count v) s:(sum v) by:k take:10})"); + ray_agg_first_n = true; + agg_route_reset(); + ray_t* r = ray_eval_str("(select {from:hv_t c:(count v) s:(sum v) by:k take:10})"); + agg_route_stats_t stats = agg_route_stats(); + TEST_ASSERT_TRUE(old && !RAY_IS_ERR(old) && r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(stats.first_n, 0); + TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_V2_DENSE], 1); + TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_V2_RADIX], 0); + TEST_ASSERT_EQ_I(stats.dense_strategy, AGG_DENSE_TASK_LOCAL); + TEST_ASSERT_TRUE(first_n_same_table(old, r)); + /* row 0 starts the heavy group 0 (a third of the rows), then rows 1, 2, + * 4, 5, ... start (i*7919) % 50000 */ + const int32_t* k = (const int32_t*)ray_data(ray_table_get_col_idx(r, 0)); + const int64_t* c = (const int64_t*)ray_data(ray_table_get_col_idx(r, 1)); + TEST_ASSERT_EQ_I(k[0], 0); + TEST_ASSERT_TRUE(c[0] > 130000); + TEST_ASSERT_EQ_I(k[1], 7919); + TEST_ASSERT_EQ_I(k[2], (2 * 7919) % 50000); + TEST_ASSERT_EQ_I(k[3], (4 * 7919) % 50000); + ray_release(old); ray_release(r); + ray_release(ray_eval_str("(set hv_t 0) (set hv_i 0)")); + PASS(); +} + /* Same names, types, row order and cells (SYM cells by their text). */ static bool first_n_same_table(ray_t* a, ray_t* b) { if (!a || !b || RAY_IS_ERR(a) || RAY_IS_ERR(b)) return false; @@ -2134,13 +2578,15 @@ static test_result_t test_first_n_take(void) { { "(select {from:fn_t by:u sf:(sum fl) take:10})", 0 }, { "(select {from:fn_t by:u fv:(first v) take:10})", 0 }, { "(select {from:fn_t by:u c:(count u) take:2000})", 0 }, - { "(select {from:fn_t by:g c:(count u) take:10})", 0 }, { "(select {from:fn_t by:u c:(count u) desc:c take:10})", 0 }, { "(select {from:fn_t by:u c:(count u) take:-5})", 0 }, { "(select {from:fn_t by:u c:(count u) take:0})", 0 }, { "(select {from:fn_t by:u c:(count u) take:[-5 3]})", 0 }, { "(select {from:fn_small by:u c:(count u) take:10})", 0 }, { "(select {from:fn_t by:w c:(count u) take:100})", 0 }, + /* the 10 groups hold 10/97 of the rows: the bounded run, on its + * dense route, selects them */ + { "(select {from:fn_t by:g c:(count u) take:10})", 0 }, { "(select {from:fn_t where:(> v 100000) by:u c:(count u) take:10})", 0 }, }; for (size_t q = 0; q < sizeof(shapes) / sizeof(shapes[0]); q++) { @@ -2161,6 +2607,513 @@ static test_result_t test_first_n_take(void) { PASS(); } +/* A per-process directory name for the stores the wave test writes. */ +#if !defined(_WIN32) +#include +#include +static long long wave_pid(void) { return (long long)getpid(); } +#else +static long long wave_pid(void) { return 0; } +#endif +#if defined(__linux__) +/* Descriptors this process holds (the directory read itself is one, always). */ +static int wave_open_fds(void) { + int n = 0; + DIR* d = opendir("/proc/self/fd"); + if (!d) return -1; + while (readdir(d)) n++; + closedir(d); + return n; +} +#endif + +/* Radix wave knobs of one run: payload bytes per wave (0 = from the heap, + * < 0 = the unreduced one-pass oracle) and how later waves are fed (0 = by + * bytes moved, 1 = re-scan, 2 = spill file). */ +typedef struct { int64_t bytes; int spill; } wave_knob_t; + +/* Run `q` under `knob` and return its result and the route counters of that + * run; the knobs go back to their defaults. */ +static ray_t* wave_run(const char* q, wave_knob_t knob, agg_route_stats_t* st) { + ray_agg_radix_wave_bytes = knob.bytes; + ray_agg_radix_spill = knob.spill; + agg_route_reset(); + ray_t* r = ray_eval_str(q); + *st = agg_route_stats(); + ray_agg_radix_wave_bytes = 0; + ray_agg_radix_spill = 0; + return r; +} + +/* The heap's own watermark setting: an explicit one reads back the same + * from both accessors; the default (0) leaves the budget at the RAM limit. */ +static int64_t wave_watermark_setting(void) { + int64_t wm = ray_heap_anon_watermark(); + return ray_heap_mem_budget() == wm ? wm : 0; +} + +/* The group node alone under an armed `desc|asc: count take: N` filter: its + * output is the kept superset (every group beyond the threshold plus N tied + * ones, in first-row order) that the select's sort+take then cuts. */ +static ray_t* wave_group_kept(ray_t* tbl, wave_knob_t knob, uint8_t desc, int64_t take, + agg_route_stats_t* st) { + ray_graph_t* g = ray_graph_new(tbl); + if (!g) return NULL; + ray_op_t* a = ray_scan(g, "a"); + uint16_t ops[] = { OP_COUNT }; + ray_op_t* ins[] = { a }; + ray_op_t* keys[] = { a }; + ray_op_t* grp = ray_group(g, keys, 1, ops, ins, 1); + ray_group_emit_filter_t prev = ray_group_emit_filter_get(); + ray_group_emit_filter_t f = {0}; + f.enabled = 1; + f.agg_index = 0; + f.top_count_take = take; + f.desc = desc; + ray_group_emit_filter_set(f); + ray_agg_radix_wave_bytes = knob.bytes; + ray_agg_radix_spill = knob.spill; + agg_route_reset(); + ray_t* res = grp ? ray_execute(g, grp) : NULL; + *st = agg_route_stats(); + ray_agg_radix_wave_bytes = 0; + ray_agg_radix_spill = 0; + ray_group_emit_filter_set(prev); + ray_graph_free(g); + return res; +} + +/* Top-N radix groupings (`desc:|asc: AGG take: N`) reduce every finished + * partition to its 2N best groups, and under memory pressure scatter the + * payload in waves of partitions. Neither may change a byte of the answer: + * each shape is compared, cell by cell and in row order, with the one-pass + * unreduced radix (knob < 0), with the reduction alone (default knob, one + * wave on this box), with forced waves, and with one partition per wave. + * Counts of 1 and 2 put ~60k groups on the take boundary, so the tie cut + * (smaller first row first) decides most emitted rows. */ +static test_result_t test_radix_topn_waves(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + agg_test_no_wide_dense(true); /* the keys are a wide sparse range: keep them on the radix route */ + char dir[96]; + snprintf(dir, sizeof dir, "/tmp/rf_agg_radix_waves_%lld", wave_pid()); + ray_t* setup = ray_eval_str( + "(set wv_i (til 250000)) " + "(set wv_a (% (* wv_i 7919) 190000)) " + "(set wv_t (table [i a b v w s] (list wv_i wv_a (as 'I32 (% wv_a 1000)) " + "(as 'I16 (% wv_i 2)) (as 'I16 (% (* wv_i 13) 1900)) " + "(as 'SYM (as 'STR (% (* wv_i 31) 70000)))))) " + /* nulls: in both keys (one null-key group of ~2.6k rows) and in w */ + "(set wv_n (update {from: wv_t a: 0Nl b: 0Ni where: (== (% i 97) 0)})) " + "(set wv_n (update {from: wv_n w: 0Nh where: (== (% i 89) 0)})) " + /* a few groups over a sparse key: most partitions stay empty */ + "(set wv_e (table [a v] (list (* (% wv_i 40) 1000000007) (% wv_i 7)))) " + /* just over the parallel threshold: 512 partitions */ + "(set wv_m (take wv_t 70000))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + /* a splayed copy (file-domain SYM column) and a two-partition parted one */ + char store_src[1024]; + snprintf(store_src, sizeof store_src, + "(.db.splayed.set \"%s/sp/\" wv_t) " + "(set wv_sp (.db.splayed.get \"%s/sp/\")) " + "(.db.splayed.set \"%s/pt/1/t/\" (take wv_t 125000)) " + "(.db.splayed.set \"%s/pt/2/t/\" (take wv_t -125000)) " + "(set wv_pt (.db.parted.get \"%s/pt/\" 't))", + dir, dir, dir, dir, dir); + setup = ray_eval_str(store_src); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + ray_agg_tablestack = false; /* the empty-partition shape is low-cardinality */ + /* reduced: the emit filter is armed and the partitions shrink (an avg + * ordering arms no filter: the full result is sorted and cut, as before; + * forty groups never fill a partition past 2N) */ + enum { FULL, NATIVE, REDUCED }; + static const struct { const char* q; bool radix; int mode; int64_t rows; } shapes[] = { + { "(select {from:wv_t by:[a b] c:(count b) sr:(sum v) ar:(avg w) desc:c take:10})", true, REDUCED, 10 }, + { "(select {from:wv_t by:[a b] c:(count b) asc:c take:7})", true, REDUCED, 7 }, + { "(select {from:wv_t by:[a b] sr:(sum v) c:(count b) desc:sr take:25})", true, REDUCED, 25 }, + { "(select {from:wv_t by:[a b] ar:(avg w) c:(count b) desc:ar take:10})", true, FULL, 10 }, + { "(select {from:wv_t by:[a b] mx:(max w) asc:mx take:10})", true, REDUCED, 10 }, + { "(select {from:wv_t by:[a b] c:(count b) sr:(sum v) where:(< w 1500) desc:c take:10})", true, REDUCED, 10 }, + { "(select {from:wv_n by:[a b] c:(count b) sr:(sum v) ar:(avg w) desc:c take:10})", true, REDUCED, 10 }, + { "(select {from:wv_n by:[a b] mn:(min w) c:(count b) asc:mn take:10})", true, REDUCED, 10 }, + { "(select {from:wv_t by:[a s] c:(count a) desc:c take:10})", true, REDUCED, 10 }, + { "(select {from:wv_sp by:[a s] c:(count a) sr:(sum v) desc:c take:10})", true, REDUCED, 10 }, + { "(select {from:wv_sp by:{s: s a: a} c:(count a) desc:c take:10})", true, REDUCED, 10 }, + { "(select {from:wv_e by:a c:(count v) sv:(sum v) desc:sv take:3})", true, NATIVE, 3 }, + { "(select {from:wv_m by:[a b] c:(count b) sr:(sum v) desc:c take:10})", true, REDUCED, 10 }, + /* parted: too many groups per partition for the per-partition + * merge, so the concatenated rows group on the radix route */ + { "(select {from:wv_pt by:[a b] c:(count b) sr:(sum v) ar:(avg w) desc:c take:10})", true, REDUCED, 10 }, + }; + const wave_knob_t oracle = { -1, 0 }; + const wave_knob_t knobs[] = { { 0, 0 }, { (int64_t)1 << 40, 0 }, { 1500000, 1 }, { 1500000, 2 } }; + for (size_t c = 0; c < sizeof(shapes) / sizeof(shapes[0]); c++) { + agg_route_stats_t base_st; + ray_t* base = wave_run(shapes[c].q, oracle, &base_st); + TEST_ASSERT_NOT_NULL(base); TEST_ASSERT_FALSE(RAY_IS_ERR(base)); + TEST_ASSERT_FMT(ray_table_nrows(base) == shapes[c].rows, "case %zu rows", c); + TEST_ASSERT_FMT(base_st.radix_compacted == 0 && base_st.radix_waves <= 1, + "case %zu oracle reduced", c); + if (shapes[c].radix) + TEST_ASSERT_FMT(base_st.routes[AGG_ROUTE_V2_RADIX] == 1, "case %zu not radix", c); + if (c == 13) TEST_ASSERT_EQ_I(base_st.routes[AGG_ROUTE_PARTED], 1); + for (size_t k = 0; k < sizeof(knobs) / sizeof(knobs[0]); k++) { + agg_route_stats_t st; + ray_t* r = wave_run(shapes[c].q, knobs[k], &st); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_FMT(first_n_same_table(base, r), "case %zu knob %zu differs", c, k); + /* the group emit itself keeps the same superset: every group + * beyond the threshold and N tied ones */ + TEST_ASSERT_FMT(st.topn_kept == base_st.topn_kept, "case %zu knob %zu kept %lld, oracle %lld", + c, k, (long long)st.topn_kept, (long long)base_st.topn_kept); + for (int64_t col = 0; col < ray_table_ncols(r); col++) + TEST_ASSERT_FMT((ray_table_get_col_idx(r, col)->attrs & RAY_ATTR_HAS_NULLS) == + (ray_table_get_col_idx(base, col)->attrs & RAY_ATTR_HAS_NULLS), + "case %zu knob %zu column %lld nulls flag", c, k, (long long)col); + if (shapes[c].radix) + TEST_ASSERT_FMT(st.routes[AGG_ROUTE_V2_RADIX] == 1, "case %zu knob %zu route", c, k); + TEST_ASSERT_FMT(st.topn_native == (shapes[c].mode != FULL), + "case %zu knob %zu native %d", c, k, (int)st.topn_native); + if (shapes[c].mode == FULL) { + TEST_ASSERT_FMT(st.radix_compacted == 0 && st.radix_waves <= 1, + "case %zu knob %zu reduced an unfiltered run", c, k); + } else { + /* the waves follow the knob: one at the default (this box + * has the room) and past any payload, several below it */ + if (k <= 1) TEST_ASSERT_FMT(st.radix_waves == 1, "case %zu knob %zu waves %u", c, k, st.radix_waves); + else TEST_ASSERT_FMT(st.radix_waves > 1, "case %zu knob %zu waves %u", c, k, st.radix_waves); + if (shapes[c].mode == REDUCED) + TEST_ASSERT_FMT(st.radix_compacted > 0, "case %zu knob %zu not reduced", c, k); + else + TEST_ASSERT_EQ_I(st.radix_compacted, 0); + /* the forced file holds every later wave's records */ + TEST_ASSERT_FMT((st.radix_spill_bytes > 0) == (knobs[k].spill == 2), + "case %zu knob %zu spilled %llu", c, k, + (unsigned long long)st.radix_spill_bytes); + } + ray_release(r); + } + ray_release(base); + } + ray_agg_tablestack = true; + /* one partition per wave: as many waves as partitions, same answer */ + { + agg_route_stats_t st; + ray_t* base = wave_run(shapes[12].q, oracle, &st); + ray_t* r = wave_run(shapes[12].q, (wave_knob_t){ 1, 1 }, &st); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(st.radix_waves, 512); + TEST_ASSERT_TRUE(first_n_same_table(base, r)); + ray_release(r); ray_release(base); + } + /* The production plan (default knobs) under real watermarks. Shape 0 + * scatters 250k records of 32 bytes: 8 MB of payload. Below the + * committed memory the plan still cuts at most 64 waves; with 12 MB of + * room one wave holds the whole payload (the in-flight tables and the + * candidates need about 1 MB, not half the room); with 5 MB it splits. + * In-memory input never spills; the splayed copy's file-backed columns + * make the spill file move fewer bytes than 64 re-scans. */ + { + int64_t saved = wave_watermark_setting(); + /* kb > 0 fixes the wave size (the room then only bounds the spill + * buffers: at most an eighth of it); sp is the spill knob. */ + static const struct { int q; int64_t room; uint32_t lo, hi; bool spill; int64_t kb; int sp; } plans[] = { + { 0, -1, 2, 64, false, 0, 0 }, + { 0, 12 << 20, 1, 1, false, 0, 0 }, + { 0, 5 << 20, 2, 8, false, 0, 0 }, + { 0, 8200000, 2, 8, false, 0, 0 }, + /* file-backed, past the watermark: no room for buffers, re-scan */ + { 9, -1, 2, 64, false, 0, 0 }, + { 9, 6 << 20, 2, 2, false, 0, 0 }, + { 9, 5000000, 2, 2, false, 0, 0 }, + /* the cost rule: many waves spill, few re-scan */ + { 9, 64 << 20, 5, 64, true, 300000, 0 }, + { 9, 64 << 20, 2, 4, false, 3000000, 0 }, + /* a forced spill whose buffers (>= 64 KB per worker and wave) + * do not fit an eighth of a 512 KB room is refused: re-scan */ + { 9, 512 << 10, 5, 64, false, 300000, 2 }, + }; + for (size_t i = 0; i < sizeof(plans) / sizeof(plans[0]); i++) { + agg_route_stats_t bst, st; + ray_t* base = wave_run(shapes[plans[i].q].q, oracle, &bst); + TEST_ASSERT_NOT_NULL(base); TEST_ASSERT_FALSE(RAY_IS_ERR(base)); + ray_heap_set_anon_watermark(plans[i].room < 0 ? 1 + : ray_heap_anon_committed() + plans[i].room); + ray_t* r = wave_run(shapes[plans[i].q].q, (wave_knob_t){ plans[i].kb, plans[i].sp }, &st); + ray_heap_set_anon_watermark(saved); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_FMT(st.radix_waves >= plans[i].lo && st.radix_waves <= plans[i].hi, + "plan %zu waves %u", i, st.radix_waves); + TEST_ASSERT_FMT((st.radix_spill_bytes > 0) == plans[i].spill, + "plan %zu spilled %llu", i, (unsigned long long)st.radix_spill_bytes); + if (plans[i].spill) + TEST_ASSERT_FMT(st.radix_spill_buf > 0 && (int64_t)st.radix_spill_buf <= plans[i].room / 8, + "plan %zu buffers %llu of %lld", i, + (unsigned long long)st.radix_spill_buf, (long long)plans[i].room / 8); + else + TEST_ASSERT_FMT(st.radix_spill_buf == 0, "plan %zu buffers %llu", i, + (unsigned long long)st.radix_spill_buf); + TEST_ASSERT_FMT(first_n_same_table(base, r), "plan %zu differs", i); + ray_release(r); ray_release(base); + } + } +#if !defined(_WIN32) + /* No spill file to be had (a missing spill directory): the forced spill + * falls back to re-scanning every wave, same answer. */ + { + const char* prev = getenv("RAY_HEAP_SWAP"); + char keep[512] = ""; + if (prev) snprintf(keep, sizeof keep, "%s", prev); + setenv("RAY_HEAP_SWAP", "/nonexistent/rf_agg_radix_waves/", 1); + agg_route_stats_t bst, st; + ray_t* base = wave_run(shapes[0].q, oracle, &bst); + ray_t* r = wave_run(shapes[0].q, knobs[3], &st); + if (prev) setenv("RAY_HEAP_SWAP", keep, 1); else unsetenv("RAY_HEAP_SWAP"); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_TRUE(st.radix_waves > 1); + TEST_ASSERT_EQ_I(st.radix_spill_bytes, 0); + TEST_ASSERT_TRUE(first_n_same_table(base, r)); + ray_release(r); ray_release(base); + } + /* The spill file fails after it was opened (every write, or every + * read-back): the waves not yet served are re-scanned from the restored + * cursors, same answer as the one-pass oracle. The process holds the same + * number of open descriptors after all of the runs, cancelled ones + * included (the file is unlinked at open, so a leaked descriptor is the + * only trace a leaked spill file leaves). */ + { + const char* prev = getenv("RAY_HEAP_SWAP"); + char keep[512] = ""; + if (prev) snprintf(keep, sizeof keep, "%s", prev); + setenv("RAY_HEAP_SWAP", dir, 1); + agg_route_stats_t bst, st; +#if defined(__linux__) + ray_release(wave_run(shapes[0].q, oracle, &bst)); /* lazy descriptors opened */ + int fds_before = wave_open_fds(); +#endif + for (int fault = 3; fault <= 4; fault++) { + for (int q = 0; q <= 9; q += 9) { + ray_t* base = wave_run(shapes[q].q, oracle, &bst); + ray_t* r = wave_run(shapes[q].q, (wave_knob_t){ 1500000, fault }, &st); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_FMT(st.radix_waves > 1, "fault %d shape %d waves %u", fault, q, st.radix_waves); + TEST_ASSERT_FMT(st.radix_spill_bytes > 0, "fault %d shape %d: spill never entered", fault, q); + TEST_ASSERT_FMT(first_n_same_table(base, r), "fault %d shape %d differs", fault, q); + ray_release(r); ray_release(base); + } + } + /* cancelled during the read-back, and in a later wave's reduction */ + for (int fault = 5; fault <= 6; fault++) { + ray_t* r = wave_run(shapes[0].q, (wave_knob_t){ 1500000, fault }, &st); + atomic_store_explicit(&ray_pool_get()->cancelled, 0, memory_order_relaxed); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "cancel"); + ray_error_free(r); + } + ray_t* ok = wave_run(shapes[0].q, oracle, &bst); /* the pool is usable again */ + TEST_ASSERT_NOT_NULL(ok); TEST_ASSERT_FALSE(RAY_IS_ERR(ok)); + ray_release(ok); +#if defined(__linux__) + int fds_after = wave_open_fds(); +#endif + if (prev) setenv("RAY_HEAP_SWAP", keep, 1); else unsetenv("RAY_HEAP_SWAP"); +#if defined(__linux__) + TEST_ASSERT_FMT(fds_after == fds_before, "open fds %d before, %d after", fds_before, fds_after); +#endif + } +#endif + /* A buffered aggregate beside the ordering count: its per-group states + * own memory (destroy hook), so no partition may be cut — the shape + * leaves the radix route for the shared index today; either way it is + * never reduced and answers as the oracle does. */ + { + const char* q = "(select {from:wv_t by:[a b] m:(med w) c:(count b) desc:c take:10})"; + agg_route_stats_t bst, st; + ray_t* base = wave_run(q, oracle, &bst); + ray_t* r = wave_run(q, knobs[3], &st); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(st.radix_compacted, 0); + TEST_ASSERT_TRUE(st.radix_waves <= 1); + TEST_ASSERT_TRUE(first_n_same_table(base, r)); + ray_release(r); ray_release(base); + } + /* The kept superset itself, on keys that all hash to radix partition 0 + * of 512: nine of count 3 (beyond the threshold 2) and ten of count 2 + * whose first rows are the earliest of all the tied groups, so the + * superset is those 19 groups. Partition 0 holds them plus its share of + * the later count-2 filler, so its 2N = 20 survivors must be exactly the + * nine strict groups and all ten early ties; anything less (a cut at N) + * would keep later ties from other partitions instead. */ + setup = ray_eval_str( + "(set adv_p [1000068 1000212 1001329 1001673 1002214 1002415 1003521 1003768 1004324 " + "1004465 1006438 1007204 1007594 1007644 1008544 1008966 1009034 1009730 1010993]) " + "(set adv_a (concat (concat (at adv_p (+ 9 (% (til 20) 10))) (at adv_p (% (til 27) 9))) " + "(+ 2000000 (div (til 69953) 2)))) " + "(set wv_adv (table [a v] (list adv_a (til 70000))))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + { + ray_t* adv = ray_eval_str("wv_adv"); + TEST_ASSERT_NOT_NULL(adv); TEST_ASSERT_FALSE(RAY_IS_ERR(adv)); + agg_route_stats_t st; + ray_t* base = wave_group_kept(adv, oracle, 1, 10, &st); + TEST_ASSERT_NOT_NULL(base); TEST_ASSERT_FALSE(RAY_IS_ERR(base)); + TEST_ASSERT_EQ_I(st.routes[AGG_ROUTE_V2_RADIX], 1); + TEST_ASSERT_TRUE(st.topn_native); + TEST_ASSERT_EQ_I(ray_table_nrows(base), 19); + const int64_t* bk = (const int64_t*)ray_data(ray_table_get_col_idx(base, 0)); + const int64_t* bc = (const int64_t*)ray_data(ray_table_get_col_idx(base, 1)); + static const int64_t adv_p[19] = { 1000068, 1000212, 1001329, 1001673, 1002214, + 1002415, 1003521, 1003768, 1004324, 1004465, 1006438, 1007204, 1007594, + 1007644, 1008544, 1008966, 1009034, 1009730, 1010993 }; + for (int i = 0; i < 19; i++) { /* first-row order: the ties, then the strict */ + TEST_ASSERT_EQ_I(bk[i], adv_p[i < 10 ? 9 + i : i - 10]); + TEST_ASSERT_EQ_I(bc[i], i < 10 ? 2 : 3); + } + for (size_t k = 0; k < sizeof(knobs) / sizeof(knobs[0]); k++) { + ray_t* r = wave_group_kept(adv, knobs[k], 1, 10, &st); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_TRUE(st.radix_compacted > 0); + TEST_ASSERT_FMT(first_n_same_table(base, r), "superset knob %zu differs", k); + ray_release(r); + } + ray_release(base); + /* asc: the last filler key (one row) lies beyond the threshold 2, + * and the ten early partition-0 pairs are the first tied groups */ + base = wave_group_kept(adv, oracle, 0, 10, &st); + TEST_ASSERT_NOT_NULL(base); TEST_ASSERT_FALSE(RAY_IS_ERR(base)); + TEST_ASSERT_EQ_I(ray_table_nrows(base), 11); + for (size_t k = 0; k < sizeof(knobs) / sizeof(knobs[0]); k++) { + ray_t* r = wave_group_kept(adv, knobs[k], 0, 10, &st); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_FMT(first_n_same_table(base, r), "asc superset knob %zu differs", k); + ray_release(r); + } + ray_release(base); + ray_release(adv); + } + /* independent oracle: the full grouping, sorted and cut the same way */ + ray_t* check = ray_eval_str( + "(all (== (at (select {from:wv_t by:[a b] c:(count b) desc:c take:10}) 'c) " + "(take (at (xdesc (select {from:wv_t by:[a b] c:(count b)}) 'c) 'c) 10)))"); + TEST_ASSERT_NOT_NULL(check); TEST_ASSERT_FALSE(RAY_IS_ERR(check)); + TEST_ASSERT_EQ_I(check->i64, 1); + ray_release(check); + char cleanup[256]; + snprintf(cleanup, sizeof cleanup, + "(set wv_sp 0) (set wv_pt 0) (.sys.exec \"rm -rf %s\")", dir); + ray_release(ray_eval_str(cleanup)); + ray_release(ray_eval_str("(set wv_i 0) (set wv_a 0) (set wv_t 0) (set wv_n 0) (set wv_e 0) (set wv_m 0) " + "(set adv_p 0) (set adv_a 0) (set wv_adv 0)")); + agg_test_no_wide_dense(false); + PASS(); +} + +/* Bytes the range reads of generation-2 column `name` of table `tname` + * decoded so far (0 when the column is not encoded). */ +static uint64_t wave_g2_decoded(const char* tname, const char* name) { + ray_t* t = ray_eval_str(tname); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return 0; } + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern(name, strlen(name))); + ray_enccol_t* e = ec ? ray_enccol_of(ec) : NULL; + uint64_t r = e && e->kind == RAY_ENCCOL_SINGLE ? atomic_load(&e->decoded_bytes) : 0; + ray_release(t); + return r; +} + +/* The waved and spilled radix top-N over a generation-2 (compressed) table: + * its columns are read by range, every wave re-reading them through the + * cursors (re-scan), or one scatter writing the later waves to the spill + * file. Each shape answers, cell by cell and in row order, as the one-pass + * unreduced radix over the same table and over its generation-0 copy; the + * waved runs take the two passes (the fused pass's chunk-major payload does + * not split), and the key column's range reads decode it once more per + * re-scanned wave. */ +static test_result_t test_radix_topn_waves_gen2(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + char dir[96]; + snprintf(dir, sizeof dir, "/tmp/rf_agg_radix_waves_g2_%lld", wave_pid()); + char src[1024]; + snprintf(src, sizeof src, + "(set wg_i (til 250000)) " + "(set wg_a (%% (* wg_i 7919) 190000)) " + "(set wg_t (table [a b v w s] (list wg_a (as 'I32 (%% wg_a 1000)) " + "(as 'I16 (%% wg_i 2)) (as 'I16 (%% (* wg_i 13) 1900)) " + "(as 'SYM (as 'STR (%% (* wg_i 31) 70000)))))) " + "(.db.splayed.set \"%s/g0/\" wg_t {compress: false}) " + "(.db.splayed.set \"%s/g2/\" wg_t {compress: true}) " + "(set wg_0 (.db.splayed.get \"%s/g0/\")) " + "(set wg_2 (.db.splayed.get \"%s/g2/\"))", + dir, dir, dir, dir); + ray_t* setup = ray_eval_str(src); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + { + ray_t* t2 = ray_eval_str("wg_2"); + TEST_ASSERT_NOT_NULL(t2); TEST_ASSERT_FALSE(RAY_IS_ERR(t2)); + TEST_ASSERT_TRUE(ray_table_get_col_enc(t2, ray_sym_intern("a", 1)) != NULL); + ray_release(t2); + } + ray_agg_tablestack = false; + static const char* const shapes[] = { + "(select {from:%s by:[a b] c:(count b) sr:(sum v) desc:c take:10})", + "(select {from:%s by:[a b] mx:(max w) asc:mx take:10})", + "(select {from:%s by:[a s] c:(count a) sr:(sum v) desc:c take:10})", + "(select {from:%s by:[a b] c:(count b) sr:(sum v) where:(< w 1500) desc:c take:10})", + }; + const wave_knob_t oracle = { -1, 0 }; + const wave_knob_t knobs[] = { { 0, 0 }, { 1500000, 1 }, { 1500000, 2 } }; + for (size_t c = 0; c < sizeof(shapes) / sizeof(shapes[0]); c++) { + char q0[256], q2[256]; + snprintf(q0, sizeof q0, shapes[c], "wg_0"); + snprintf(q2, sizeof q2, shapes[c], "wg_2"); + agg_route_stats_t st0, st2; + ray_t* base0 = wave_run(q0, oracle, &st0); + ray_t* base2 = wave_run(q2, oracle, &st2); + TEST_ASSERT_NOT_NULL(base0); TEST_ASSERT_FALSE(RAY_IS_ERR(base0)); + TEST_ASSERT_NOT_NULL(base2); TEST_ASSERT_FALSE(RAY_IS_ERR(base2)); + TEST_ASSERT_FMT(st2.routes[AGG_ROUTE_V2_RADIX] == 1, "case %zu gen2 oracle not radix", c); + TEST_ASSERT_FMT(st2.radix_compacted == 0 && st2.radix_waves <= 1, "case %zu oracle reduced", c); + TEST_ASSERT_FMT(first_n_same_table(base0, base2), "case %zu gen2 oracle differs from gen0", c); + for (size_t k = 0; k < sizeof(knobs) / sizeof(knobs[0]); k++) { + agg_route_stats_t st; + uint64_t a0 = wave_g2_decoded("wg_2", "a"); + ray_t* r = wave_run(q2, knobs[k], &st); + uint64_t da = wave_g2_decoded("wg_2", "a") - a0; + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_FMT(st.routes[AGG_ROUTE_V2_RADIX] == 1, "case %zu knob %zu route", c, k); + TEST_ASSERT_FMT(first_n_same_table(base2, r), "case %zu knob %zu differs", c, k); + TEST_ASSERT_FMT(st.topn_kept == st2.topn_kept, "case %zu knob %zu kept %lld, oracle %lld", + c, k, (long long)st.topn_kept, (long long)st2.topn_kept); + TEST_ASSERT_FMT(st.radix_compacted > 0, "case %zu knob %zu not reduced", c, k); + if (k == 0) { + TEST_ASSERT_FMT(st.radix_waves == 1, "case %zu default waves %u", c, st.radix_waves); + ray_release(r); + continue; + } + TEST_ASSERT_FMT(st.radix_waves > 1, "case %zu knob %zu waves %u", c, k, st.radix_waves); + TEST_ASSERT_FMT(st.radix_phase1 == AGG_RADIX_P1_TWO_PASS, + "case %zu knob %zu phase 1 %u", c, k, (unsigned)st.radix_phase1); + TEST_ASSERT_FMT((st.radix_spill_bytes > 0) == (knobs[k].spill == 2), + "case %zu knob %zu spilled %llu", c, k, + (unsigned long long)st.radix_spill_bytes); + /* key a (8-byte I64, 250k rows) read by range: the count pass, + * then one scatter per wave (re-scan) or one in all (spill) */ + uint64_t full = 250000u * 8u; + uint64_t want = knobs[k].spill == 2 ? 2 * full : (uint64_t)(1 + st.radix_waves) * full; + TEST_ASSERT_FMT(da >= want, "case %zu knob %zu decoded %llu of a, want %llu", c, k, + (unsigned long long)da, (unsigned long long)want); + ray_release(r); + } + ray_release(base0); ray_release(base2); + } + ray_agg_tablestack = true; + char cleanup[256]; + snprintf(cleanup, sizeof cleanup, + "(set wg_0 0) (set wg_2 0) (set wg_t 0) (set wg_i 0) (set wg_a 0) (.sys.exec \"rm -rf %s\")", dir); + ray_release(ray_eval_str(cleanup)); + PASS(); +} + #if defined(__linux__) #include #include @@ -2232,6 +3185,7 @@ static test_result_t test_select_read_ahead_mapped(void) { { "(select {from:X s:(sum (+ u v)) where:(> v 5)})", AGG_ROUTE_NONE }, { "(select {from:X where:(> v 970) asc:u take:5})", AGG_ROUTE_NONE }, }; + agg_test_no_wide_dense(true); /* case 3 is the radix route on a mapped key */ for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) { char qm[512], qt[512]; const char* x = strstr(cases[c].q, "X"); @@ -2258,6 +3212,7 @@ static test_result_t test_select_read_ahead_mapped(void) { TEST_ASSERT_FMT(stats.routes[cases[c].route] >= 1, "case %zu: expected route %d", c, (int)cases[c].route); } + agg_test_no_wide_dense(false); r = ray_eval_str("(set pfs_m 0)"); if (r) ray_release(r); (void)ray_test_rm_rf(PFS_ROOT); @@ -2690,6 +3645,445 @@ static test_result_t test_card_estimate(void) { PASS(); } +static int cdb_pair_cmp(const void* a, const void* b) { + const int64_t* x = (const int64_t*)a; + const int64_t* y = (const int64_t*)b; + if (x[0] != y[0]) return x[0] < y[0] ? -1 : 1; + return x[1] < y[1] ? -1 : x[1] > y[1]; +} + +#define CDB_MAX_ROUNDS_TEST 5 /* the kernel's CDB_MAX_ROUNDS (3) and the rounding of its take */ + +static int cdb_rounds(void) { + int rounds = 0; + for (int32_t i = 0; i < g_ray_profile.n; i++) + if (g_ray_profile.spans[i].msg && + !strcmp(g_ray_profile.spans[i].msg, "count-distinct: bounded round")) rounds++; + return rounds; +} + +/* The bounded grouped count-distinct (ray_cd_bounded) under a budget far + * below its sets counts in several rounds, each reading the input again for + * the partitions the earlier ones left, and agrees with one round and with a + * sorted-pairs oracle: 8- and 4-byte values, 2- and 4-byte group tags (past + * 65534 groups), group ids from the key column (through the result keys, in + * an order of their own, a null key among them) and from a row map, nulls + * among the values, and keys with no group skipped. The last shape has + * more groups than per-worker count arrays are kept for (2.1 M groups, + * shared counts), in one round. */ +static test_result_t test_cd_bounded_rounds(void) { + const int64_t n_max = 4200000; + ray_t* pairs_hdr = ray_alloc((size_t)n_max * 2 * sizeof(int64_t)); + ray_t* gid_hdr = ray_alloc((size_t)n_max * sizeof(int64_t)); + ray_t* expect_hdr = ray_alloc((size_t)2100002 * sizeof(int64_t)); + TEST_ASSERT_TRUE(pairs_hdr && gid_hdr && expect_hdr); + int64_t* pairs = (int64_t*)ray_data(pairs_hdr); + int64_t* row_gid = (int64_t*)ray_data(gid_hdr); + int64_t* expect = (int64_t*)ray_data(expect_hdr); + for (int shape = 0; shape < 5; shape++) { + bool narrow = shape & 1; + bool shared = shape == 4; + const int64_t n = shared ? n_max : 400000; + /* groups with a key, plus the null key */ + int64_t ng = shared ? 2100000 : (shape & 2) ? 70000 : 1000; + ray_t* key = ray_vec_new(RAY_I64, n); + ray_t* val = ray_vec_new(narrow ? RAY_I32 : RAY_I64, n); + ray_t* gk = ray_vec_new(RAY_I64, ng + 2); + TEST_ASSERT_TRUE(key && val && gk); + key->len = val->len = n; + gk->len = ng + 2; + /* result key g is ng-1-g; the null key is group ng; group ng+1 + * repeats group 0's key, which keeps its first group (no rows + * here); key ng (every 1013th row) has no group */ + for (int64_t g = 0; g < ng; g++) ((int64_t*)ray_data(gk))[g] = ng - 1 - g; + ((int64_t*)ray_data(gk))[ng] = NULL_I64; + ((int64_t*)ray_data(gk))[ng + 1] = ng - 1; + int64_t np = 0; + for (int64_t i = 0; i < n; i++) { + int64_t k = i % 97 == 0 ? NULL_I64 : i % 1013 == 0 ? ng : (i * 40503) % ng; + int64_t v = i % 89 == 0 ? (narrow ? NULL_I32 : NULL_I64) : (i * 7919) % 3001; + ((int64_t*)ray_data(key))[i] = k; + if (narrow) ((int32_t*)ray_data(val))[i] = (int32_t)v; + else ((int64_t*)ray_data(val))[i] = v; + int64_t gid = k == NULL_I64 ? ng : k == ng ? -1 : ng - 1 - k; + row_gid[i] = gid; + if (gid >= 0) { pairs[np * 2] = gid; pairs[np * 2 + 1] = v; np++; } + } + qsort(pairs, (size_t)np, 2 * sizeof(int64_t), cdb_pair_cmp); + memset(expect, 0, (size_t)(ng + 2) * sizeof(int64_t)); + for (int64_t i = 0; i < np; i++) + if (i == 0 || pairs[i * 2] != pairs[i * 2 - 2] || pairs[i * 2 + 1] != pairs[i * 2 - 1]) + expect[pairs[i * 2]]++; + + for (int run = 0; run < 3; run++) { + if (shared && run == 1) continue; + int64_t watermark = ray_heap_anon_watermark(); + if (run > 0 && !shared) + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + + (INT64_C(2) << 20)); + g_ray_profile.active = true; + g_ray_profile.n = 0; + ray_t* out = ray_cd_bounded(NULL, run < 2 ? key : NULL, run < 2 ? gk : NULL, + run < 2 ? NULL : row_gid, ng + 2, val, NULL, n); + int rounds = cdb_rounds(); + g_ray_profile.active = false; + g_ray_profile.n = 0; + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_FMT(out && !RAY_IS_ERR(out), "shape %d run %d failed", shape, run); + TEST_ASSERT_EQ_I(out->type, RAY_I64); + TEST_ASSERT_EQ_I(out->len, ng + 2); + if (run == 0 || shared) TEST_ASSERT_EQ_I(rounds, 1); + else TEST_ASSERT_FMT(rounds >= 2 && rounds <= 4, "shape %d run %d: %d rounds under a 2 MB room", + shape, run, rounds); + for (int64_t g = 0; g <= ng + 1; g++) + TEST_ASSERT_FMT(((int64_t*)ray_data(out))[g] == expect[g], + "shape %d run %d group %lld: %lld, expected %lld", shape, run, + (long long)g, (long long)((int64_t*)ray_data(out))[g], + (long long)expect[g]); + ray_release(out); + } + ray_release(key); ray_release(val); ray_release(gk); + } + ray_free(pairs_hdr); ray_free(gid_hdr); ray_free(expect_hdr); + + /* 2 M distinct pairs, some 30 MB of sets, under the 4 MB floor of a + * 2 MB room: the first trim's projection raises the budget, so the + * input is read a few times, not once a partition. */ + { + ray_t* key = ray_eval_str("(% (til 2000000) 1000)"); + ray_t* val = ray_eval_str("(til 2000000)"); + ray_t* gk = ray_eval_str("(til 1000)"); + TEST_ASSERT_TRUE(key && val && gk && !RAY_IS_ERR(key) && !RAY_IS_ERR(val) && !RAY_IS_ERR(gk)); + int64_t watermark = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + + (INT64_C(2) << 20)); + g_ray_profile.active = true; + g_ray_profile.n = 0; + ray_t* out = ray_cd_bounded(NULL, key, gk, NULL, 1000, val, NULL, 2000000); + int rounds = cdb_rounds(); + g_ray_profile.active = false; + g_ray_profile.n = 0; + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out) && out->len == 1000); + TEST_ASSERT_FMT(rounds >= 2 && rounds <= CDB_MAX_ROUNDS_TEST, "%d rounds over 2 M pairs", rounds); + for (int64_t g = 0; g < 1000; g++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[g], 2000); + ray_release(out); ray_release(key); ray_release(val); ray_release(gk); + } + PASS(); +} + +/* The kernel under a room of a few MB or none against the answer it gives + * with all the memory it wants (one round) and the pairs counted by + * construction (row i is key i mod ng, value i): no cliff at the budget + * floor — 100 K pairs, whose sets fit the floor, count in one round whatever + * the room, and the others in at most CDB_MAX_ROUNDS_TEST — and the same + * query repeated under one watermark fixed beforehand takes the same rounds + * (the blocks the first leaves on the heap's freelists are room again). */ +static test_result_t test_cd_bounded_floor(void) { + static const struct { int64_t n, ng, room; } c[] = { + { 100000, 1000, 2 }, { 100000, 1000, 0 }, { 200000, 1000, 2 }, { 400000, 1000, 2 }, + { 200000, 50, 0 }, { 800000, 1000, 2 }, { 1500000, 1000, 2 }, { 300000, 70000, 2 }, + }; + for (size_t i = 0; i < sizeof(c) / sizeof(c[0]); i++) { + char b[160]; + snprintf(b, sizeof b, "(%% (til %lld) %lld)", (long long)c[i].n, (long long)c[i].ng); + ray_t* key = ray_eval_str(b); + snprintf(b, sizeof b, "(til %lld)", (long long)c[i].n); + ray_t* val = ray_eval_str(b); + snprintf(b, sizeof b, "(til %lld)", (long long)c[i].ng); + ray_t* gk = ray_eval_str(b); + TEST_ASSERT_TRUE(key && val && gk && !RAY_IS_ERR(key) && !RAY_IS_ERR(val) && !RAY_IS_ERR(gk)); + ray_t* ref = ray_cd_bounded(NULL, key, gk, NULL, c[i].ng, val, NULL, c[i].n); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref) && ref->len == c[i].ng); + int64_t watermark = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + + (c[i].room << 20)); + g_ray_profile.active = true; + g_ray_profile.n = 0; + ray_t* out = ray_cd_bounded(NULL, key, gk, NULL, c[i].ng, val, NULL, c[i].n); + int rounds = cdb_rounds(); + g_ray_profile.active = false; + g_ray_profile.n = 0; + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_FMT(out && !RAY_IS_ERR(out) && out->len == c[i].ng, "case %zu failed", i); + if (i < 2) TEST_ASSERT_FMT(rounds == 1, "case %zu: %d rounds for sets within the floor", i, rounds); + TEST_ASSERT_FMT(rounds >= 1 && rounds <= CDB_MAX_ROUNDS_TEST, "case %zu: %d rounds", i, rounds); + for (int64_t g = 0; g < c[i].ng; g++) { + int64_t want = (c[i].n - g + c[i].ng - 1) / c[i].ng; + TEST_ASSERT_FMT(((int64_t*)ray_data(out))[g] == want && + ((int64_t*)ray_data(ref))[g] == want, + "case %zu group %lld: %lld (unbounded %lld), expected %lld", i, + (long long)g, (long long)((int64_t*)ray_data(out))[g], + (long long)((int64_t*)ray_data(ref))[g], (long long)want); + } + ray_release(out); ray_release(ref); ray_release(key); ray_release(val); ray_release(gk); + } + /* the same query repeated, a freed block having left reusable room: the + * room is the watermark's less what is committed and not reusable */ + { + ray_t* key = ray_eval_str("(% (til 400000) 1000)"); + ray_t* val = ray_eval_str("(til 400000)"); + ray_t* gk = ray_eval_str("(til 1000)"); + TEST_ASSERT_TRUE(key && val && gk && !RAY_IS_ERR(key) && !RAY_IS_ERR(val) && !RAY_IS_ERR(gk)); + ray_t* pad = ray_alloc((size_t)24 << 20); /* leaves reusable blocks behind */ + TEST_ASSERT_TRUE(pad && !RAY_IS_ERR(pad)); + ray_free(pad); + int64_t watermark = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + + (INT64_C(64) << 20)); + int rounds[3]; + for (int run = 0; run < 3; run++) { + g_ray_profile.active = true; + g_ray_profile.n = 0; + ray_t* out = ray_cd_bounded(NULL, key, gk, NULL, 1000, val, NULL, 400000); + rounds[run] = cdb_rounds(); + g_ray_profile.active = false; + g_ray_profile.n = 0; + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out) && out->len == 1000); + for (int64_t g = 0; g < 1000; g++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[g], 400); + ray_release(out); + } + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_FMT(rounds[0] == 1 && rounds[1] == 1 && rounds[2] == 1, + "rounds of one query repeated in 64 MB of room: %d %d %d", + rounds[0], rounds[1], rounds[2]); + ray_release(key); ray_release(val); ray_release(gk); + } + PASS(); +} + +/* A partition that alone outgrows the budget: 300 K distinct values, all in + * the pairs' partition 0 (found with the kernel's hash), each twice, one + * group, under a 2 MB room. The round trims every other partition and keeps + * that one whole, past the budget; the count is the number of values. */ +static test_result_t test_cd_bounded_hot_partition(void) { + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, 600000, 65536); + uint32_t W = par ? ray_pool_total_workers(pool) : 1; + uint32_t P = 256; + while (P < 1024u && P < 8 * W) P <<= 1; + const uint64_t limit = UINT64_MAX >> __builtin_ctz(P); /* hash <= limit: top bits zero */ + const int64_t nv = 300000; + ray_t* val = ray_vec_new(RAY_I64, 2 * nv); + ray_t* key = ray_vec_new(RAY_I64, 2 * nv); + ray_t* gk = ray_eval_str("[0]"); + TEST_ASSERT_TRUE(val && key && gk && !RAY_IS_ERR(gk)); + int64_t* vd = (int64_t*)ray_data(val); + int64_t found = 0; + for (uint64_t x = 1; found < nv; x++) { + uint64_t h = (uint64_t)x * 0x9E3779B97F4A7C15ULL + 1 * 0xC2B2AE3D27D4EB4FULL; + h ^= h >> 33; h *= 0xff51afd7ed558ccdULL; h ^= h >> 33; + h *= 0xc4ceb9fe1a85ec53ULL; h ^= h >> 33; + if (h <= limit) { vd[2 * found] = vd[2 * found + 1] = (int64_t)x; found++; } + } + val->len = key->len = 2 * nv; + memset(ray_data(key), 0, (size_t)(2 * nv) * sizeof(int64_t)); + int64_t watermark = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + (INT64_C(2) << 20)); + ray_t* out = ray_cd_bounded(NULL, key, gk, NULL, 1, val, NULL, 2 * nv); + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out) && out->len == 1); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[0], nv); + ray_release(out); ray_release(key); ray_release(val); ray_release(gk); + PASS(); +} + +/* ray_cd_bounded on the shapes its route gate leaves to the slices in + * memory: a single group of all-distinct and of all-equal values, F64 + * values (every NaN the null, -0.0 equal to 0.0), SYM keys and values with + * SYM nulls among them — one call each, from the key column through the + * result keys. */ +static test_result_t test_cd_bounded_edges(void) { + static const struct { const char* key; const char* gk; const char* val; int64_t ng; int64_t expect[4]; } c[] = { + { "(* 0 (til 100000))", "[0]", "(til 100000)", 1, { 100000 } }, + { "(* 0 (til 100000))", "[0]", "(+ 7 (* 0 (til 100000)))", 1, { 1 } }, + { "(% (til 100000) 4)", "[0 1 2 3]", + "(at [0Nf 1.5 -0.0 2.5 0Nf 1.5 0.0 3.5] (% (til 100000) 8))", 4, { 1, 1, 1, 2 } }, + { "(% (til 100000) 4)", "[3 2 1 0]", + "(at (% [0.0 1.5 0.0 2.5 0Nf 1.5 7.5 3.5] [0.0 2.0 0.0 3.0 1.0 2.0 8.0 4.0]) (% (til 100000) 8))", 4, { 2, 2, 1, 1 } }, + { "(at ['a 'b 'c] (% (til 100000) 3))", "['c 'a 'b]", + "(at ['p 'q 'r 's 't] (% (til 100000) 5))", 3, { 5, 5, 5 } }, + { "(at ['a 'b 'c] (% (til 100000) 3))", "['a 'b 'c]", + "(at ['p 'q 'r 's 't] (% (til 100000) 15))", 3, { 3, 3, 2 } }, /* past 't: null */ + }; + for (size_t i = 0; i < sizeof(c) / sizeof(c[0]); i++) { + ray_t* key = ray_eval_str(c[i].key); + ray_t* gk = ray_eval_str(c[i].gk); + ray_t* val = ray_eval_str(c[i].val); + TEST_ASSERT_FMT(key && gk && val && !RAY_IS_ERR(key) && !RAY_IS_ERR(gk) && !RAY_IS_ERR(val), + "case %zu inputs", i); + ray_t* out = ray_cd_bounded(NULL, key, gk, NULL, c[i].ng, val, NULL, 100000); + TEST_ASSERT_FMT(out && !RAY_IS_ERR(out), "case %zu failed", i); + TEST_ASSERT_EQ_I(out->len, c[i].ng); + for (int64_t g = 0; g < c[i].ng; g++) + TEST_ASSERT_FMT(((int64_t*)ray_data(out))[g] == c[i].expect[g], + "case %zu group %lld: %lld, expected %lld", i, (long long)g, + (long long)((int64_t*)ray_data(out))[g], (long long)c[i].expect[g]); + ray_release(out); ray_release(key); ray_release(gk); ray_release(val); + } + PASS(); +} + +/* Selects whose count-distinct scatter takes ray_cd_bounded because the + * slices' row buffers do not fit (the anon watermark lowered to a few MB + * above what is committed and cannot be reused), against the same count + * through a group by [k v] computed beforehand: another aggregate beside + * the count, nulls in the key and the value, a selection, a composite key + * (the row-map source), top-N on the count of the group, SYM values, a + * parted table — the route asserted by the kernel's profile ticks — whose + * SYM columns are 16-bit indices past 32767 into a shared symfile, one with + * a partition that lacks the counted column (its rows nulls), grouped by a + * column and by the partition date (MAPCOMMON); and a + * composite key over STR values, which the kernel does not read: the row + * map's slices are built for it (no kernel round), however short memory + * is. The first query counts in more than one round. */ +static test_result_t test_cd_bounded_select(void) { + ray_t* setup = ray_eval_str( + "(do (set i (til 300000))" + " (set T (table [k v s a] (list (at (concat [0N] (til 96)) (% i 97)) (at (concat [0N] (til 2999)) (% (* i 7919) 3000))" + " (at ['p 'q 'r 's 't 'u 'v] (% (* i 13) 7)) (% i 5))))" + " (set T2 (table [k1 k2 s a] (list (% i 7) (% i 11) (at (as 'STR (list \"p\" \"q\" \"r\" \"s\" \"t\")) (% i 5)) (% i 3))))" + " (set T3 (table [k f w kc ov uq nv a] (list (at (concat [0N] (til 96)) (% i 97))" + " (at [0Nf 1.5 -0.0 2.5 0.0 3.5] (% i 6)) (as 'I32 (% (* i 7919) 3000)) (* 0 i) (+ 7 (* 0 i)) i" + " (at [0N] (* 0 i)) (% i 5))))" + " (.sys.exec \"rm -rf /tmp/rayforce_test_cdb\")" + " (set Z (as 'SYM (as 'STR (+ 2000000 (til 40000)))))" + " (set K (as 'SYM (as 'STR (+ 3000000 (til 100)))))" + " (set j (til 100000))" + " (.db.splayed.set \"/tmp/rayforce_test_cdb/2024.01.01/t/\" (table [v k c] (list (at Z (% j 40000)) (at K (% j 100)) j)))" + " (.db.splayed.set \"/tmp/rayforce_test_cdb/2024.01.02/t/\" (table [v k c] (list (at Z (% (* j 7919) 3000)) (at K (% j 100)) j)))" + " (set P (.db.parted.get \"/tmp/rayforce_test_cdb/\" 't))" + " (set m (til 30000))" + " (.db.splayed.set \"/tmp/rayforce_test_cdb/r/2024.01.01/t/\" (table [k v] (list (% m 10) (% m 1000))))" + " (.db.splayed.set \"/tmp/rayforce_test_cdb/r/2024.01.02/t/\" (table [k v] (list (% m 10) (+ 500 (% m 1000)))))" + " (.db.splayed.set \"/tmp/rayforce_test_cdb/r/2024.01.03/t/\" (table [k] (list (% m 10))))" + " (set R (.db.parted.get \"/tmp/rayforce_test_cdb/r/\" 't)) 0)"); + TEST_ASSERT_TRUE(setup && !RAY_IS_ERR(setup)); ray_release(setup); + static const struct { const char* query; const char* oracle; bool kernel; } q[] = { + { "(at (select {u: (count (distinct v)) s: (sum a) from: T by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T by: [k v]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct v)) c: (count a) from: T where: (== (% (* i 13) 11) 3) by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T where: (== (% (* i 13) 11) 3) by: [k v]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct v)) c: (count a) from: T by: [k s] asc: [k s]}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T by: [k s v]}) by: [k s] asc: [k s]}) 'n)", true }, + { "(at (select {u: (count (distinct v)) c: (count a) from: T by: k desc: c take: 5}) 'u)", + "(at (select {n: (count x) c: (sum x) from: (select {x: (count a) from: T by: [k v]}) by: k desc: c take: 5}) 'n)", true }, + { "(at (select {u: (count (distinct s)) c: (count a) from: T by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T by: [k s]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct v)) c: (count c) from: P by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count c) from: P by: [k v]}) by: k asc: k}) 'n)", true }, + /* a partition without v reads as nulls: g mod 10 over [0, 1500) and the null */ + { "(at (select {u: (count (distinct v)) c: (count k) from: R by: k asc: k}) 'u)", "[151 151 151 151 151 151 151 151 151 151]", true }, + { "(at (select {u: (count (distinct v)) c: (count k) from: R by: date}) 'u)", "[1000 1000 1]", true }, + { "(at (select {u: (count (distinct s)) c: (count a) from: T2 by: [k1 k2] asc: [k1 k2]}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T2 by: [k1 k2 s]}) by: [k1 k2] asc: [k1 k2]}) 'n)", false }, + /* F64 (null, -0.0 equal to 0.0), I32, all-null, one value, one value a row, one group */ + { "(at (select {u: (count (distinct f)) c: (count a) from: T3 by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T3 by: [k f]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct w)) c: (count a) from: T3 by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T3 by: [k w]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct nv)) c: (count a) from: T3 by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T3 by: [k nv]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct ov)) c: (count a) from: T3 by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T3 by: [k ov]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct uq)) c: (count a) from: T3 by: k asc: k}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T3 by: [k uq]}) by: k asc: k}) 'n)", true }, + { "(at (select {u: (count (distinct uq)) c: (count a) from: T3 by: kc}) 'u)", "[300000]", true }, + { "(at (select {u: (count (distinct f)) c: (count a) from: T3 by: kc}) 'u)", "[5]", true }, + { "(at (select {u: (count (distinct ov)) c: (count a) from: T3 by: kc}) 'u)", "[1]", true }, + /* STR values are not read by the kernel: the slices count them */ + { "(at (select {u: (count (distinct s)) c: (count a) from: T2 by: k1 asc: k1}) 'u)", + "(at (select {n: (count x) from: (select {x: (count a) from: T2 by: [k1 s]}) by: k1 asc: k1}) 'n)", false }, + }; + for (size_t i = 0; i < sizeof(q) / sizeof(q[0]); i++) { + ray_t* want = ray_eval_str(q[i].oracle); + TEST_ASSERT_FMT(want && !RAY_IS_ERR(want) && want->type == RAY_I64, "oracle %zu", i); + int64_t watermark = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + + (INT64_C(4) << 20)); + g_ray_profile.active = true; + ray_t* got = ray_eval_str(q[i].query); + int rounds = cdb_rounds(); + g_ray_profile.active = false; + g_ray_profile.n = 0; + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_FMT(got && !RAY_IS_ERR(got) && got->type == RAY_I64, "query %zu", i); + if (q[i].kernel) + TEST_ASSERT_FMT(rounds >= (i == 0 ? 2 : 1), "query %zu: %d bounded rounds", i, rounds); + else + TEST_ASSERT_FMT(rounds == 0, "query %zu: %d bounded rounds", i, rounds); + TEST_ASSERT_EQ_I(got->len, want->len); + for (int64_t g = 0; g < got->len; g++) + TEST_ASSERT_FMT(((int64_t*)ray_data(got))[g] == ((int64_t*)ray_data(want))[g], + "query %zu group %lld: %lld, expected %lld", i, (long long)g, + (long long)((int64_t*)ray_data(got))[g], + (long long)((int64_t*)ray_data(want))[g]); + ray_release(got); ray_release(want); + } + if (q[5].kernel) { /* the parted counts: 100 groups, 42940 pairs */ + ray_t* tot = ray_eval_str("(sum (at (select {u: (count (distinct v)) c: (count c) from: P by: k}) 'u))"); + TEST_ASSERT_TRUE(tot && !RAY_IS_ERR(tot)); + TEST_ASSERT_EQ_I(tot->i64, 42940); + ray_release(tot); + } + ray_t* rm = ray_eval_str("(do (set P 0) (set R 0) (.sys.exec \"rm -rf /tmp/rayforce_test_cdb\"))"); + if (rm) ray_release(rm); + PASS(); +} + +static int cdb_ticks(const char* msg) { + int n = 0; + for (int32_t i = 0; i < g_ray_profile.n; i++) + if (g_ray_profile.spans[i].msg && !strcmp(g_ray_profile.spans[i].msg, msg)) n++; + return n; +} + +/* A selective where: over a composite key counted by the bounded kernel + * keeps a row map of the kept rows only (one id for each, not one for every + * row of the table), whatever the selection holds: whole segments, mixed + * ones, none. The counts equal a group by [k s v] counted beforehand, at a + * watermark a few MB above what is committed. */ +static test_result_t test_cd_bounded_filtered(void) { + ray_t* setup = ray_eval_str( + "(do (set i (til 300000))" + " (set TF (table [k s v a] (list (% i 7) (at ['p 'q 'r 's 't 'u 'v] (% (* i 13) 7))" + " (at (concat [0N] (til 2999)) (% (* i 7919) 3000)) (% i 5)))) 0)"); + TEST_ASSERT_TRUE(setup && !RAY_IS_ERR(setup)); ray_release(setup); + static const char* wh[] = { + "(== (% (* i 13) 11) 3)", /* mixed segments */ + "(< i 100000)", /* whole segments and a mixed one */ + "(> i 290000)", /* none in most segments */ + "(== (% i 9973) 5)", /* a few rows */ + }; + for (size_t w = 0; w < sizeof(wh) / sizeof(wh[0]); w++) { + char qs[512], os[512]; + snprintf(qs, sizeof(qs), + "(at (select {u: (count (distinct v)) c: (count a) from: TF where: %s by: [k s] asc: [k s]}) 'u)", wh[w]); + snprintf(os, sizeof(os), + "(at (select {n: (count x) from: (select {x: (count a) from: TF where: %s by: [k s v]}) by: [k s] asc: [k s]}) 'n)", wh[w]); + ray_t* want = ray_eval_str(os); + TEST_ASSERT_FMT(want && !RAY_IS_ERR(want) && want->type == RAY_I64, "oracle %zu", w); + int64_t watermark = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(ray_heap_anon_committed() - ray_heap_anon_reusable() + + (INT64_C(4) << 20)); + g_ray_profile.active = true; + ray_t* got = ray_eval_str(qs); + int maps = cdb_ticks("count-distinct: row map over the kept rows"); + int rounds = cdb_rounds(); + g_ray_profile.active = false; + g_ray_profile.n = 0; + ray_heap_set_anon_watermark(watermark); + TEST_ASSERT_FMT(got && !RAY_IS_ERR(got) && got->type == RAY_I64, "query %zu", w); + TEST_ASSERT_FMT(maps == 1 && rounds >= 1, "query %zu: %d kept-row maps, %d rounds", w, maps, rounds); + TEST_ASSERT_EQ_I(got->len, want->len); + for (int64_t g = 0; g < got->len; g++) + TEST_ASSERT_FMT(((int64_t*)ray_data(got))[g] == ((int64_t*)ray_data(want))[g], + "query %zu group %lld", w, (long long)g); + ray_release(got); ray_release(want); + } + PASS(); +} + /* The route gate for a grouped distinct count (ray_cd_two_pass_preferred, * #756): the two-pass rewrite (true) against the slice dedup (false), from * the estimates above over 1,048,576 rows. Each case turns on one rule. */ @@ -2907,6 +4301,12 @@ static test_result_t test_cd_route(void) { const test_entry_t agg_contract_entries[] = { { "agg_contract/card_estimate", test_card_estimate, contract_setup, contract_teardown }, { "agg_contract/cd_route", test_cd_route, contract_setup, contract_teardown }, + { "agg_contract/cd_bounded_rounds", test_cd_bounded_rounds, contract_setup, contract_teardown }, + { "agg_contract/cd_bounded_edges", test_cd_bounded_edges, contract_setup, contract_teardown }, + { "agg_contract/cd_bounded_floor", test_cd_bounded_floor, contract_setup, contract_teardown }, + { "agg_contract/cd_bounded_hot_partition", test_cd_bounded_hot_partition, contract_setup, contract_teardown }, + { "agg_contract/cd_bounded_select", test_cd_bounded_select, contract_setup, contract_teardown }, + { "agg_contract/cd_bounded_filtered", test_cd_bounded_filtered, contract_setup, contract_teardown }, { "agg_contract/empty_inference_errors", test_empty_inference_errors, contract_setup, contract_teardown }, { "agg_contract/nth_bounds", test_nth_bounds, contract_setup, contract_teardown }, { "agg_contract/native_binary_output", test_native_binary_output, contract_setup, contract_teardown }, @@ -2918,8 +4318,13 @@ const test_entry_t agg_contract_entries[] = { { "agg_contract/derived_key_per_symbol_route", test_derived_key_per_symbol_route, contract_setup, contract_teardown }, { "agg_contract/narrow_extrema_limits", test_narrow_extrema_limits, contract_setup, contract_teardown }, { "agg_contract/dense_strategies", test_dense_strategies, contract_setup, contract_teardown }, + { "agg_contract/first_n_heavy_dense", test_first_n_heavy_dense, contract_setup, contract_teardown }, { "agg_contract/dense_symbol_output", test_dense_symbol_output, contract_setup, contract_teardown }, { "agg_contract/dense_task_local", test_dense_task_local, contract_setup, contract_teardown }, + { "agg_contract/dense_wide_range", test_dense_wide_range, contract_setup, contract_teardown }, + { "agg_contract/dense_wide_after_worker_budget", test_dense_wide_after_worker_budget, contract_setup, contract_teardown }, + { "agg_contract/dense_wide_budget", test_dense_wide_budget, contract_setup, contract_teardown }, + { "agg_contract/dense_wide_budget_sel", test_dense_wide_budget_sel, contract_setup, contract_teardown }, { "agg_contract/dense_cache_bound", test_dense_cache_bound, contract_setup, contract_teardown }, { "agg_contract/dense_composite_compaction", test_dense_composite_compaction, contract_setup, contract_teardown }, { "agg_contract/radix_native_topn", test_radix_native_topn, contract_setup, contract_teardown }, @@ -2927,6 +4332,10 @@ const test_entry_t agg_contract_entries[] = { { "agg_contract/dense_native_topn", test_dense_native_topn, contract_setup, contract_teardown }, { "agg_contract/dense_unordered_take", test_dense_unordered_take, contract_setup, contract_teardown }, { "agg_contract/first_n_take", test_first_n_take, contract_setup, contract_teardown }, + { "agg_contract/radix_topn_waves", test_radix_topn_waves, contract_setup, contract_teardown }, + { "agg_contract/radix_topn_waves_gen2", test_radix_topn_waves_gen2, contract_setup, contract_teardown }, + { "agg_contract/timespan_rank_admission", test_timespan_rank_admission, contract_setup, contract_teardown }, + { "agg_contract/timespan_rank_slice", test_timespan_rank_slice, contract_setup, contract_teardown }, { "agg_contract/rank_widths_nulls_slices", test_rank_widths_nulls_and_slices, contract_setup, contract_teardown }, { "agg_contract/nullable_differential", test_nullable_differential, contract_setup, contract_teardown }, { "agg_contract/wide_key_routes", test_wide_key_routes, contract_setup, contract_teardown }, diff --git a/test/test_agg_engine.c b/test/test_agg_engine.c index 1ea8436fe..b8dbdc20e 100644 --- a/test/test_agg_engine.c +++ b/test/test_agg_engine.c @@ -21,6 +21,14 @@ #include "ops/rowsel.h" /* ray_rowsel_from_pred, ray_rowsel_release */ #include "core/pool.h" #include "table/sym.h" +#include "core/runtime.h" +#include "core/platform.h" +#include "lang/eval.h" +#include "store/enccol.h" +#include "store/encfmt.h" +#include "store/splay.h" +#include "table/table.h" +#include #include #include #include @@ -2381,6 +2389,385 @@ static test_result_t test_avg_exact_i128_engines(void) { return res; } +/* ---- Task 17c: the fused radix chunk cap, the parallel parted flatten ---- + * Runtime fixtures over stores saved under the process's own tmp root. */ +#define AE_TMP "/tmp/rayforce_aeroutes" +static ray_runtime_t* g_ae_rt; +static void ae_rt_setup(void) { + g_ae_rt = ray_runtime_create(0, NULL); + (void)ray_test_rm_rf(ray_test_tmp(AE_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(AE_TMP)); +} +static void ae_rt_teardown(void) { + ray_cache_llc_set_for_test(0); + ray_cancel_reset(); + ray_pool_destroy(); (void)ray_pool_init_total(0); + ray_test_hooks_off(); + (void)ray_test_rm_rf(ray_test_tmp(AE_TMP)); + ray_runtime_destroy(g_ae_rt); +} +static ray_t* ae_eval(const char* src) { return ray_eval_str(ray_test_tmp(src)); } +static void ae_drop(ray_t* o) { if (!o) return; if (RAY_IS_ERR(o)) ray_error_free(o); else ray_release(o); } +static void ae_eval_ok(const char* src) { + ray_t* r = ae_eval(src); + if (r && RAY_IS_ERR(r)) { fprintf(stderr, "ae_eval_ok: %s: %s\n", src, ray_error_msg()); ray_error_free(r); abort(); } + if (r) ray_release(r); +} +static void ae_evalf_ok(const char* fmt, ...) { + char buf[2048]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + ae_eval_ok(buf); +} +/* Bytes decoded so far of column `name` of table t (summed over a parted + * column's encoded segments); *full: its generation-0 bytes. */ +static uint64_t ae_col_dec(ray_t* t, const char* name, uint64_t* full) { + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern(name, strlen(name))); + uint64_t r = 0; + *full = 0; + if (!ec) return 0; + ray_enccol_t* e = ray_enccol_of(ec); + if (e->kind == RAY_ENCCOL_SINGLE) { + *full = (uint64_t)e->len * ray_enccol_esz(e); + return atomic_load(&e->decoded_bytes); + } + for (int64_t i = 0; e->wrapper && i < e->wrapper->len; i++) { + ray_t* sg = ray_enccol_seg(ec, i); + if (!sg || sg->type != RAY_ENCCOL) continue; + ray_enccol_t* se = ray_enccol_of(sg); + r += atomic_load(&se->decoded_bytes); + *full += (uint64_t)se->len * ray_enccol_esz(se); + } + return r; +} +static uint64_t ae_dec(const char* name, uint64_t* full) { + ray_t* t = ae_eval("T"); + uint64_t r = ae_col_dec(t, name, full); + ae_drop(t); + return r; +} +/* q's answer as .csv.write bytes (malloc'd; NULL on a failure). */ +static char* ae_csv(const char* q, size_t* n) { + char path[512], e[1024]; + snprintf(path, sizeof path, "%s/a.csv", ray_test_tmp(AE_TMP)); + snprintf(e, sizeof e, "(.csv.write %s \"%s\")", q, path); + ray_t* r = ae_eval(e); + bool ok = r && !RAY_IS_ERR(r); + ae_drop(r); + FILE* f = ok ? fopen(path, "rb") : NULL; + if (!f) return NULL; + fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); + char* b = malloc((size_t)len + 1); + *n = b ? fread(b, 1, (size_t)len, f) : 0; + fclose(f); + if (b && *n != (size_t)len) { free(b); b = NULL; } + return b; +} + +/* q17's shape on the v2 radix route: two wide keys, a count and an F64 + * sum, 1.2M rows (2048 partitions: a run wants 16384-row chunks, 2 + * blocks). The last-level cache is set for 2 workers so a worker's + * staging share holds (0.75 * llc / 2 - 4 * 2048) / 26 rows (the staged + * k, m and f, 8 bytes each, and a partition id): about 14100 (one block + * fits, half a run: the fused pass on 8192-row chunks, the keys decode + * once per run, within 5% for the vectors a chunk starts inside), then + * about 6900 (under a block, under half a run: the two + * passes, the keys decode twice; whole chunks are + * scanrange/v2_radix_decode_once's). Every answer is generation 0's + * byte for byte (the F64 sum's bits follow the records' order inside a + * partition). */ +static test_result_t test_radix_fused_capped_decode_once(void) { + ae_eval_ok("(set j (til 1200000))"); + ae_eval_ok("(set R (table [k m f] (list (* (% (* j 7919) 300007) 1000003) (* (% j 13) 1000033) " + "(/ (as 'F64 j) 7.0))))"); + ae_eval_ok("(.db.splayed.set \"" AE_TMP "/r0/\" R {compress: false})"); + ae_eval_ok("(.db.splayed.set \"" AE_TMP "/r2/\" R {compress: true})"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(2), RAY_OK); + static const char* const q = "(select {c: (count f) a: (sum f) from: T by: {k: k m: m}})"; + static const struct { uint64_t llc; double lo, hi; const char* what; } cs[] = { + { 1000000, 1.0, 1.05, "fused, one-block chunks at half a run" }, + { 500000, 2.0, 2.2, "two passes under half a run" }, + }; + ae_eval_ok("(set T (.db.splayed.get \"" AE_TMP "/r0/\"))"); + size_t nref = 0; + char* ref = ae_csv(q, &nref); + TEST_ASSERT_TRUE(ref != NULL && nref > 0); + ae_eval_ok("(set T (.db.splayed.get \"" AE_TMP "/r2/\"))"); + ae_drop(ae_eval(q)); /* binds and loads once: the pin is per run */ + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + uint64_t fk, fm, k0 = ae_dec("k", &fk), m0 = ae_dec("m", &fm); + ray_cache_llc_set_for_test(cs[i].llc); + agg_route_reset(); + size_t n = 0; + char* b = ae_csv(q, &n); + agg_route_stats_t st = agg_route_stats(); + ray_cache_llc_set_for_test(0); + double xk = (double)(ae_dec("k", &fk) - k0) / (double)fk, xm = (double)(ae_dec("m", &fm) - m0) / (double)fm; + bool same = b && n == nref && memcmp(b, ref, n) == 0; + free(b); + if (!same || st.routes[AGG_ROUTE_V2_RADIX] != 1 || !(xk >= cs[i].lo && xk <= cs[i].hi) || + !(xm >= cs[i].lo && xm <= cs[i].hi)) { + free(ref); + TEST_ASSERT_FMT(same, "%s: generation 2 differs from generation 0", cs[i].what); + TEST_ASSERT_FMT(false, "%s: radix %llu, k decoded %.4fx, m %.4fx", cs[i].what, + (unsigned long long)st.routes[AGG_ROUTE_V2_RADIX], xk, xm); + } + } + free(ref); + PASS(); +} + +/* The below-half side of the fused cap: 4.2M rows (4096 partitions, so a + * run wants 32768-row chunks, 4 blocks) over 2 workers, the last-level + * cache set so a worker's staging share holds about 13700 rows ((0.75 * + * llc / 2 - 4 * 4096) / 18: the staged k and m, 8 bytes each, and a + * partition id). The cap rounds down to one block, which holds a quarter of a run: + * the two passes, the keys decode twice (fused on one-block chunks, they + * would decode once). The answer is the in-memory table's. */ +static test_result_t test_radix_fused_capped_below_half(void) { + ae_eval_ok("(set j (til 4200000))"); + ae_eval_ok("(set R (table [k m] (list (* (% j 20011) 1000003) (% j 13))))"); + ae_eval_ok("(.db.splayed.set \"" AE_TMP "/r2/\" R {compress: true})"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(2), RAY_OK); + static const char* const q = "(select {c: (count k) from: T by: {k: k m: m}})"; + ae_eval_ok("(set T R)"); + size_t nref = 0; + char* ref = ae_csv(q, &nref); + TEST_ASSERT_TRUE(ref != NULL && nref > 0); + ae_eval_ok("(set T (.db.splayed.get \"" AE_TMP "/r2/\"))"); + ae_drop(ae_eval(q)); /* binds and loads once: the pin is per run */ + uint64_t fk, fm, k0 = ae_dec("k", &fk), m0 = ae_dec("m", &fm); + ray_cache_llc_set_for_test(700000); + agg_route_reset(); + size_t n = 0; + char* b = ae_csv(q, &n); + agg_route_stats_t st = agg_route_stats(); + ray_cache_llc_set_for_test(0); + double xk = (double)(ae_dec("k", &fk) - k0) / (double)fk, xm = (double)(ae_dec("m", &fm) - m0) / (double)fm; + bool same = b && n == nref && memcmp(b, ref, n) == 0; + free(b); free(ref); + TEST_ASSERT_FMT(same, "generation 2 differs from the in-memory table"); + TEST_ASSERT_FMT(st.routes[AGG_ROUTE_V2_RADIX] == 1 && xk >= 2.0 && xk <= 2.2 && xm >= 2.0 && xm <= 2.2, + "two passes at a quarter of a run: radix %llu, k decoded %.4fx, m %.4fx", + (unsigned long long)st.routes[AGG_ROUTE_V2_RADIX], xk, xm); + PASS(); +} + +static ray_t* ae_flatten(ray_t* t, const char* col, int64_t total) { + return parted_flatten_fixed(ray_table_slot(t, ray_sym_intern(col, strlen(col))), total); +} + +/* parted_flatten_fixed on the pool (4 workers), three partitions of + * 200000 rows: an I64 column, a SYM one and an F64 one with nulls flatten + * byte for byte as generation 0's (whose plain segments stay one serial + * copy), each generation-2 column decoding once (within 5%: a slice's + * first vector); q18's shape (first-n over the segment-streamed table, + * which flattens its keys) answers as generation 0. Only a flatten that + * decodes runs on the pool: a cancelled generation-2 flatten is `cancel`, + * while generation 0 (plain segments) and a generation-2 column whose + * materialization is published are one serial copy, which completes under + * ray_cancel() (it does not poll) and decodes nothing. */ +static test_result_t test_parted_flatten_parallel(void) { + ae_eval_ok("(set j (til 600000))"); + ae_eval_ok("(set P (table [u s f] (list (* (% (* j 7919) 50021) 1000003) " + "(as 'SYMBOL (map (fn [x] (format \"w%\" (% x 300))) (% (* j 31) 9973))) " + "(map (fn [x] (if (== 0 (% x 97)) 0Nf (/ (as 'F64 x) 3.0))) j))))"); + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + ae_evalf_ok("(.db.splayed.set \"" AE_TMP "/p%d/2024.01.0%d/t/\" (take (drop P %d) 200000) {compress: %s})", + gen, p + 1, p * 200000, gen ? "true" : "false"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_t* t0 = ae_eval("(.db.parted.get \"" AE_TMP "/p0\" 't)"); + ray_t* t2 = ae_eval("(.db.parted.get \"" AE_TMP "/p2\" 't)"); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + static const char* const cols[] = { "u", "s", "f" }; + for (int c = 0; c < 3; c++) { + uint64_t full, d0 = ae_col_dec(t2, cols[c], &full); + ray_t* a = ae_flatten(t0, cols[c], 600000); + ray_t* b = ae_flatten(t2, cols[c], 600000); + double x = (double)(ae_col_dec(t2, cols[c], &full) - d0) / (double)(full ? full : 1); + bool ok = a && !RAY_IS_ERR(a) && b && !RAY_IS_ERR(b) && a->type == b->type && a->len == 600000 && + b->len == 600000 && a->attrs == b->attrs && + memcmp(ray_data(a), ray_data(b), (size_t)600000 * ray_sym_elem_size(a->type, a->attrs)) == 0; + ae_drop(a); ae_drop(b); + if (!ok || !(x >= 1.0 && x <= 1.05)) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(ok, "%s: the flat copies differ", cols[c]); + TEST_ASSERT_FMT(x >= 1.0 && x <= 1.05, "%s: decoded %.4fx", cols[c], x); + } + static const char* const q = "(select {c: (count f) from: T by: {u: u s: s} take: 10})"; + ae_eval_ok("(set T (.db.parted.get \"" AE_TMP "/p0\" 't))"); + size_t n0 = 0, n2 = 0; + char* a0 = ae_csv(q, &n0); + ae_eval_ok("(set T (.db.parted.get \"" AE_TMP "/p2\" 't))"); + char* a2 = ae_csv(q, &n2); + bool same = a0 && a2 && n0 == n2 && n0 > 0 && memcmp(a0, a2, n0) == 0; + free(a0); free(a2); + if (!same) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(same, "%s: generation 2 differs from generation 0", q); + + ray_cancel(); /* the pool skips every slice */ + ray_t* v = ae_flatten(t2, "u", 600000); + ray_cancel_reset(); + bool cancelled = v && RAY_IS_ERR(v) && strcmp(ray_err_code(v), "cancel") == 0; + ae_drop(v); + if (!cancelled) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_TRUE(cancelled); + + /* the serial copies: generation 0, then generation 2 once its + * materialization is published, each under ray_cancel() */ + ray_t* ref = ae_flatten(t0, "u", 600000); + ray_t* mat = ray_enccol_materialize(ray_table_slot(t2, ray_sym_intern("u", 1))); + bool mat_ok = ref && !RAY_IS_ERR(ref) && mat && !RAY_IS_ERR(mat); + if (mat && RAY_IS_ERR(mat)) ray_error_free(mat); /* else borrowed: the column's */ + if (!mat_ok) { ae_drop(ref); ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_TRUE(mat_ok); + uint64_t full, d0 = ae_col_dec(t2, "u", &full); + for (int gen = 0; gen <= 2; gen += 2) { + ray_cancel(); + v = ae_flatten(gen ? t2 : t0, "u", 600000); + ray_cancel_reset(); + bool ok = v && !RAY_IS_ERR(v) && v->len == 600000 && + memcmp(ray_data(v), ray_data(ref), (size_t)600000 * sizeof(int64_t)) == 0; + ae_drop(v); + if (!ok) { ae_drop(ref); ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(ok, "generation %d under ray_cancel(): not the serial copy", gen); + } + uint64_t d1 = ae_col_dec(t2, "u", &full); + ae_drop(ref); ae_drop(t0); ae_drop(t2); + TEST_ASSERT_FMT(d1 == d0, "materialized u decoded %llu bytes", (unsigned long long)(d1 - d0)); + PASS(); +} + +/* Task 17i: a parallel flatten decodes each whole vector of an encoded + * segment straight into the flat vector, and copies a run of RAW vectors + * lying end to end at once. Three partitions of 200001, 199999 and + * 200000 rows (segments end inside vectors): r wide random I64 (RAW + * vectors), k an RLE-ish I32 with nulls, s a SYM; each flattens byte for + * byte as generation 0's, the whole vectors arriving straight (all rows + * but the slices' cut vectors), r's RAW runs in under half as many copies + * as its vectors (a run ends at a chunk, a slice or a non-RAW vector). */ +static test_result_t test_parted_flatten_in_place(void) { + ae_eval_ok("(set j (til 600000))"); + ae_eval_ok("(set P (table [r k s] (list (* (% (* j 7919) 600011) -6148914691236517205) " + "(as 'I32 (map (fn [x] (if (== 0 (% x 1001)) 0N (/ x 37))) j)) " + "(as 'SYMBOL (map (fn [x] (format \"w%\" (% x 300))) (% (* j 31) 9973))))))"); + static const int64_t rows[3] = { 200001, 199999, 200000 }; + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0, at = 0; p < 3; at += (int)rows[p], p++) + ae_evalf_ok("(.db.splayed.set \"" AE_TMP "/f%d/2024.01.0%d/t/\" (take (drop P %d) %lld) {compress: %s})", + gen, p + 1, at, (long long)rows[p], gen ? "true" : "false"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_t* t0 = ae_eval("(.db.parted.get \"" AE_TMP "/f0\" 't)"); + ray_t* t2 = ae_eval("(.db.parted.get \"" AE_TMP "/f2\" 't)"); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + static const char* const cols[] = { "r", "k", "s" }; + for (int c = 0; c < 3; c++) { + uint64_t c0, r0, c1, r1; + ray_col_test_into(&c0, &r0); + ray_t* a = ae_flatten(t0, cols[c], 600000); + ray_t* b = ae_flatten(t2, cols[c], 600000); + ray_col_test_into(&c1, &r1); + bool ok = a && !RAY_IS_ERR(a) && b && !RAY_IS_ERR(b) && a->type == b->type && a->len == 600000 && + b->len == 600000 && a->attrs == b->attrs && + memcmp(ray_data(a), ray_data(b), (size_t)600000 * ray_sym_elem_size(a->type, a->attrs)) == 0; + ae_drop(a); ae_drop(b); + /* 16 slices of 40960 rows: at most two cut vectors each, read by the cursor */ + bool straight = r1 - r0 >= 600000 - 16 * 2 * 1024; + bool runs = c != 0 || (c1 - c0) * 2 < 600000 / 1024; + if (!ok || !straight || !runs) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(ok, "%s: the flat copies differ", cols[c]); + TEST_ASSERT_FMT(straight, "%s: %llu rows decoded in place", cols[c], (unsigned long long)(r1 - r0)); + TEST_ASSERT_FMT(runs, "%s: %llu copies for %d vectors", cols[c], (unsigned long long)(c1 - c0), 600000 / 1024); + } + ae_drop(t0); ae_drop(t2); + PASS(); +} + +/* Fix round 1: ray_col_range_into's bounds, each pinned by a call into + * a buffer of exactly n elements (ASan) and by the parallel flatten. + * Three partitions of 200001 / 199999 / 200000 rows: r wide random I64 + * (RAW vectors), s a SYM whose first segment holds 100 symbols (W8) and + * the others 1000 (W16). + * - Another SYM width declines: segment 0 into a W16 output delivers + * nothing (at W8 it delivers its first vector), and the flatten of s + * (W16) equals generation 0's byte for byte. + * - A vector longer than the range declines: 500 or 1023 rows from a + * vector's first row deliver nothing. + * - A RAW run (chunk 1's vectors are RAW, laid end to end) stops at the + * vector that would cross the range's end: 3 vectors and 100 rows + * deliver 3 vectors, in partition 2 (vectors offset by 200001) as in + * partition 1. + * - A flatten to fewer rows than the column (its last slice ends inside a + * vector) equals generation 0's. */ +static test_result_t test_parted_flatten_into_bounds(void) { + static const int64_t rows[3] = { 200001, 199999, 200000 }; + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0, at = 0; p < 3; at += (int)rows[p], p++) { + ae_evalf_ok("(set j (+ %d (til %lld)))", at, (long long)rows[p]); + ae_evalf_ok("(.db.splayed.set \"" AE_TMP "/b%d/2024.01.0%d/t/\" (table [r s] (list " + "(* (%% (* j 7919) 600011) -6148914691236517205) " + "(as 'SYMBOL (map (fn [x] (format \"w%%\" x)) (%% (* j 31) %d))))) {compress: %s})", + gen, p + 1, p ? 1000 : 100, gen ? "true" : "false"); + } + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_t* t0 = ae_eval("(.db.parted.get \"" AE_TMP "/b0\" 't)"); + ray_t* t2 = ae_eval("(.db.parted.get \"" AE_TMP "/b2\" 't)"); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + ray_t* sc2 = ray_table_slot(t2, ray_sym_intern("s", 1)); + ray_col_meta_t m0, m1; + bool widths = ray_col_meta_of(ray_enccol_seg(sc2, 0), &m0) && ray_col_meta_of(ray_enccol_seg(sc2, 1), &m1) && + (m0.attrs & RAY_SYM_W_MASK) == RAY_SYM_W8 && (m1.attrs & RAY_SYM_W_MASK) == RAY_SYM_W16; + if (!widths) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(widths, "s: segment widths %u / %u, want W8 / W16", m0.attrs & RAY_SYM_W_MASK, m1.attrs & RAY_SYM_W_MASK); + + /* the direct calls, each into a buffer of exactly n elements */ + struct { const char* col; int64_t start, n; uint8_t attrs; int64_t want; } calls[] = { + { "s", 0, 4096, RAY_SYM_W16, 0 }, /* another width */ + { "s", 0, 4096, RAY_SYM_W8, 4096 }, /* its own: the control (a RAW run) */ + { "r", 0, 500, 0, 0 }, /* vector longer than the range */ + { "r", 1024, 1023, 0, 0 }, + { "r", 65536, 500, 0, 0 }, /* a RAW one (chunk 1's vectors are) */ + { "r", 65536, 3 * 1024 + 100, 0, 3 * 1024 }, /* RAW run stops before the crossing vector */ + { "r", 200001 + 65536, 2 * 1024 + 5, 0, 2 * 1024 }, + }; + for (size_t i = 0; i < sizeof calls / sizeof calls[0]; i++) { + ray_col_src_t src; + ray_t* err = ray_col_src_bind(ray_table_slot(t2, ray_sym_intern(calls[i].col, 1)), &src); + TEST_ASSERT_TRUE(err == NULL); + ray_col_cursor_t cur; + ray_col_cursor_init(&cur, &src); + size_t esz = calls[i].col[0] == 's' ? (calls[i].attrs == RAY_SYM_W8 ? 1 : 2) : 8; + void* dst = malloc((size_t)calls[i].n * esz); + int64_t got = -1; + err = ray_col_range_into(&src, calls[i].start, calls[i].n, &cur.sc, calls[i].attrs, dst, &got); + free(dst); + ray_col_cursor_free(&cur); + ray_col_src_release(&src); + bool ok = err == NULL && got == calls[i].want; + if (err) ray_error_free(err); + if (!ok) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(ok, "%s at %lld for %lld (width %u): delivered %lld, want %lld", calls[i].col, + (long long)calls[i].start, (long long)calls[i].n, calls[i].attrs, + (long long)got, (long long)calls[i].want); + } + + /* the flatten: whole, and to fewer rows than the column */ + static const struct { const char* col; int64_t total; } fl[] = { + { "s", 600000 }, { "r", 600000 }, { "r", 600000 - 500 }, { "s", 600000 - 1500 }, + }; + for (size_t i = 0; i < sizeof fl / sizeof fl[0]; i++) { + ray_t* a = ae_flatten(t0, fl[i].col, fl[i].total); + ray_t* b = ae_flatten(t2, fl[i].col, fl[i].total); + bool ok = a && !RAY_IS_ERR(a) && b && !RAY_IS_ERR(b) && a->type == b->type && a->len == fl[i].total && + b->len == fl[i].total && a->attrs == b->attrs && + (fl[i].col[0] != 's' || (b->attrs & RAY_SYM_W_MASK) == RAY_SYM_W16) && + memcmp(ray_data(a), ray_data(b), (size_t)fl[i].total * ray_sym_elem_size(a->type, a->attrs)) == 0; + ae_drop(a); ae_drop(b); + if (!ok) { ae_drop(t0); ae_drop(t2); } + TEST_ASSERT_FMT(ok, "%s to %lld rows: the flat copies differ", fl[i].col, (long long)fl[i].total); + } + ae_drop(t0); ae_drop(t2); + PASS(); +} + const test_entry_t agg_engine_entries[] = { { "pearson_old_engine_r_vs_r2", test_pearson_old_engine_r_vs_r2, NULL, NULL }, { "diff_group_pearson_1k", test_diff_group_pearson_1k, NULL, NULL }, @@ -2459,5 +2846,10 @@ const test_entry_t agg_engine_entries[] = { { "group_keys_multi", test_group_keys_multi, NULL, NULL }, { "agg_run_one_i64", test_agg_run_one_i64, NULL, NULL }, { "avg_exact_i128_engines", test_avg_exact_i128_engines, NULL, NULL }, + { "radix_fused_capped_decode_once", test_radix_fused_capped_decode_once, ae_rt_setup, ae_rt_teardown }, + { "radix_fused_capped_below_half", test_radix_fused_capped_below_half, ae_rt_setup, ae_rt_teardown }, + { "parted_flatten_parallel", test_parted_flatten_parallel, ae_rt_setup, ae_rt_teardown }, + { "parted_flatten_in_place", test_parted_flatten_in_place, ae_rt_setup, ae_rt_teardown }, + { "parted_flatten_into_bounds", test_parted_flatten_into_bounds, ae_rt_setup, ae_rt_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_aware.c b/test/test_aware.c new file mode 100644 index 000000000..b93e36fd4 --- /dev/null +++ b/test/test_aware.c @@ -0,0 +1,5466 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include +#include "mem/heap.h" +#include "ops/ops.h" +#include "ops/internal.h" +#include "ops/rowsel.h" +#include "ops/fused_topk.h" +#include "table/sym.h" +#include "table/table.h" +#include "core/runtime.h" +#include "lang/format.h" +#include "store/col.h" +#include "ops/idxop.h" /* RAY_IDX_DICT */ +#include "store/enc.h" +#include "store/encfmt.h" +#include "store/encw.h" +#include "store/enccol.h" +#include "store/colrange.h" +#include "store/enceval.h" +#include "lang/env.h" +#include "store/splay.h" +#include "store/part.h" +#include "ops/colgather.h" +#include "ops/agg_engine.h" /* agg_route_stats: the first-n route */ +#include "core/pool.h" /* ray_cancel */ +#include "vec/str.h" +#include +#include +#include +#include + +/* Written as "/tmp/..." in the sources; every use goes through + * ray_test_tmp (a per-process root), so concurrent suites never share it. */ +#define AW_TMP "/tmp/rayforce_aware" +/* Set while a test runs under ray_group_test_scalar_grain: answers are checked, the + * decoded-byte counts (which then include task-edge vectors) are not. */ +static bool g_aw_unaligned; +static const char* aw_root(void) { return ray_test_tmp(AW_TMP); } +static ray_runtime_t* g_awrt; +static uint8_t* g_img; static size_t g_len; +static void aw_setup(void) { g_awrt = ray_runtime_create(0, NULL); (void)ray_test_rm_rf(aw_root()); (void)ray_test_mkdir_p(aw_root()); } +static void aw_teardown(void) { + ray_test_hooks_off(); ray_encw_test_force(-1); + free(g_img); g_img = NULL; g_len = 0; + (void)ray_test_rm_rf(aw_root()); ray_runtime_destroy(g_awrt); +} + +/* Every Rayfall string with a "/tmp" path goes through ray_test_tmp. */ +__attribute__((unused)) static ray_t* aw_eval(const char* src) { return ray_eval_str(ray_test_tmp(src)); } +static void aw_eval_ok(const char* src) { + ray_t* r = ray_eval_str(ray_test_tmp(src)); + if (r && RAY_IS_ERR(r)) { fprintf(stderr, "aw_eval_ok: %s: %s\n", src, ray_error_msg()); ray_error_free(r); abort(); } + if (r) ray_release(r); +} + +/* Save the rayfall table expression `tbl` twice: 0 as generation 0 and + * 2 as generation 2 with every vector's top-level encoding forced to + * `enc` (-1: the encoder's own choice). */ +static void aw_save(const char* name, const char* tbl, int enc) { + char q[4096]; + snprintf(q, sizeof q, "(set W %s)", tbl); + aw_eval_ok(q); + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s0/\" W {compress: false})", name); + aw_eval_ok(q); + ray_encw_test_force(enc); + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s2/\" W {compress: true})", name); + aw_eval_ok(q); + ray_encw_test_force(-1); +} + +/* Table loaded with .db.splayed.get (owned), or NULL. */ +static ray_t* aw_load(const char* name, int gen) { + char q[512]; + snprintf(q, sizeof q, "(.db.splayed.get \"" AW_TMP "/%s%d/\")", name, gen); + ray_t* t = ray_eval_str(ray_test_tmp(q)); + return (t && !RAY_IS_ERR(t)) ? t : NULL; +} + +/* Encoding of vector `vec` of column `col` of table 2 (its + * descriptor, read in place), or -1. */ +__attribute__((unused)) static int aw_vec_enc(const char* name, const char* col, int64_t vec) { + ray_t* t = aw_load(name, 2); + ray_t* encv = t ? ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))) : NULL; + int enc = -1; + if (encv) { + enc = ray_enccol_descs(ray_enccol_of(encv), vec / RAY_ENC_VECS_PER_CHUNK)[vec % RAY_ENC_VECS_PER_CHUNK].encoding; + } + if (t) ray_release(t); + return enc; +} + +/* Runs `q` (table as T) on 0 and 2; equal formatted results and + * exactly want_mat materializations on generation 2. Leaves the + * generation-2 table loaded as T (aw_col_decoded reads it). */ +__attribute__((unused)) static test_result_t aw_same(const char* name, const char* q, uint64_t want_mat) { + char buf[2048]; ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s%d/\"))", name, gen ? 2 : 0); + aw_eval_ok(buf); + ray_enc_counters_reset(); + out[gen] = ray_eval_str(ray_test_tmp(q)); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "%s gen %d: %s", q, gen, ray_error_msg()); + if (gen) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == want_mat, "%s: %llu materializations, want %llu", q, + (unsigned long long)k.materialized, (unsigned long long)want_mat); + } + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s differs", q); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + PASS(); +} +#define AW_SAME(n, q, m) do { test_result_t r_ = aw_same((n), (q), (m)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* aw_same with no materialization, then exactly want_decoded bytes decoded + * by the generation-2 run (-1: not checked). */ +__attribute__((unused)) static test_result_t aw_reduce(const char* name, const char* q, int64_t want_decoded) { + test_result_t r = aw_same(name, q, 0); + if (r.status != TEST_PASS) return r; + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (want_decoded >= 0 && !g_aw_unaligned) + TEST_ASSERT_FMT(k.decoded_bytes == (uint64_t)want_decoded, "%s: decoded %llu, want %lld", q, + (unsigned long long)k.decoded_bytes, (long long)want_decoded); + PASS(); +} + +/* Bytes decoded from column `col` of the loaded table T (P1's per-column + * counter, ray_enccol_t.decoded_bytes, counted when a scratch moves on). */ +__attribute__((unused)) static uint64_t aw_col_decoded(const char* col) { + ray_t* t = ray_eval_str("T"); + ray_t* encv = t && !RAY_IS_ERR(t) ? ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))) : NULL; + uint64_t b = encv ? atomic_load(&ray_enccol_of(encv)->decoded_bytes) : 0; + if (t && !RAY_IS_ERR(t)) ray_release(t); + return b; +} + +/* Logical values of a view, expanded here only for the test oracle + * (ray_enc_unpack is fine in a test). */ +static uint64_t aw_lane(const ray_enc_lanes_t* l, int T, uint32_t i) { + switch (T) { case 8: return l->b[i]; case 16: return l->h[i]; case 32: return l->s[i]; default: return l->q[i]; } +} +static void aw_view_values(const ray_enc_vview_t* v, int64_t* out) { + uint64_t u[RAY_ENC_VEC]; + const uint64_t m = v->k.T == 64 ? ~0ull : ((1ull << v->k.T) - 1); + switch (v->enc) { + case RAY_ENC_CONST: for (int i = 0; i < v->n; i++) out[i] = ray_enc_logical(v->cbits, v->k); break; + case RAY_ENC_FOR_BP: + ray_enc_unpack(v->packed, v->k.T, v->width, u); + for (int i = 0; i < v->n; i++) out[i] = ray_enc_logical((v->base + u[i]) & m, v->k); + break; + case RAY_ENC_RLE: { + int i = 0; + for (uint32_t r = 0; r < v->n_runs; r++) + for (; i < v->run_ends.h[r]; i++) out[i] = ray_enc_logical(aw_lane(&v->run_vals, v->k.T, r), v->k); + break; + } + case RAY_ENC_DICT: for (int i = 0; i < v->n; i++) out[i] = ray_enc_logical(v->dict[v->codes[i]], v->k); break; + default: break; + } +} + +/* The residual lanes ray_enccol_unpack_resid writes equal the generic + * unpack's (the oracle), at the kind's width. */ +static bool aw_resid_ok(const ray_enc_vview_t* v) { + _Alignas(64) ray_enc_lanes_t res; + uint64_t u[RAY_ENC_VEC]; + ray_enccol_unpack_resid(v, &res); + ray_enc_unpack(v->packed, v->k.T, v->width, u); + for (int i = 0; i < v->n; i++) if (aw_lane(&res, v->k.T, (uint32_t)i) != u[i]) return false; + return true; +} + +static test_result_t aw_check_view(const char* name, const char* col, int enc) { + ray_t* t2 = aw_load(name, 2); ray_t* t0 = aw_load(name, 0); + TEST_ASSERT_TRUE(t2 && t0); + int64_t sym = ray_sym_intern(col, strlen(col)); + ray_t* encv = ray_table_get_col_enc(t2, sym); + TEST_ASSERT_NOT_NULL(encv); + ray_t* plain = ray_table_col(t0, sym); + ray_enccol_t* e = ray_enccol_of(encv); + ray_enc_vview_t v; /* on the stack, as a scan task holds it */ + int64_t vals[RAY_ENC_VEC]; + ray_enc_counters_reset(); + for (int64_t vec = 0; vec < ray_enc_nvecs(e->len); vec++) { + ray_t* err = NULL; + TEST_ASSERT_EQ_I(ray_enccol_vview(e, vec, &v, &err), 1); + TEST_ASSERT_EQ_I(v.enc, enc); + TEST_ASSERT_EQ_I(v.n, ray_enc_vec_len(e->len, vec)); + if (v.enc == RAY_ENC_FOR_BP) TEST_ASSERT_TRUE(aw_resid_ok(&v)); + aw_view_values(&v, vals); + int nn = 0; + for (int i = 0; i < v.n; i++) { + int64_t r = vec * RAY_ENC_VEC + i; + bool isnull = v.nullmap && ((v.nullmap[i >> 3] >> (i & 7)) & 1); + nn += isnull; + if (isnull) { TEST_ASSERT_TRUE(ray_vec_is_null(plain, r)); continue; } + TEST_ASSERT_FMT(vals[i] == read_col_i64(ray_data(plain), r, plain->type, plain->attrs), + "%s row %lld", col, (long long)r); + } + if (v.nullmap) TEST_ASSERT_EQ_I(nn, v.n_nulls); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* a view is not a decode */ + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(atomic_load(&e->decoded_bytes), 0); + ray_release(t2); ray_release(t0); + PASS(); +} + +static test_result_t test_vview_encodings(void) { + /* 70000 rows: two chunks, nulls every 9th row in x */ + const char* tbl = "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (- (% j 50) 20))) (til 70000)))))"; + const char* cst = "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (div j 1024))) (til 70000)))))"; + const char* sym = "(table [s] (list (as 'SYMBOL (map (fn [j] (if (== 0 (% j 7)) \"\" (format \"w%\" (% j 13)))) (til 70000)))))"; + test_result_t r; + aw_save("vf", tbl, RAY_ENC_FOR_BP); if ((r = aw_check_view("vf", "x", RAY_ENC_FOR_BP)).status != TEST_PASS) return r; + aw_save("vr", tbl, RAY_ENC_RLE); if ((r = aw_check_view("vr", "x", RAY_ENC_RLE)).status != TEST_PASS) return r; + aw_save("vd", tbl, RAY_ENC_DICT); if ((r = aw_check_view("vd", "x", RAY_ENC_DICT)).status != TEST_PASS) return r; + aw_save("vc", cst, RAY_ENC_CONST); if ((r = aw_check_view("vc", "x", RAY_ENC_CONST)).status != TEST_PASS) return r; + aw_save("vs", sym, RAY_ENC_FOR_BP); if ((r = aw_check_view("vs", "s", RAY_ENC_FOR_BP)).status != TEST_PASS) return r; + aw_save("vt", sym, RAY_ENC_RLE); if ((r = aw_check_view("vt", "s", RAY_ENC_RLE)).status != TEST_PASS) return r; + PASS(); +} + +/* FOR_BP vectors of column `col` of 2 whose worst case base + + * (2^w - 1) passes the kind's largest value (the no-wrap check then reads + * the actual residuals), or -1. */ +static int64_t aw_near_top(const char* name, const char* col) { + ray_t* t = aw_load(name, 2); + ray_t* encv = t ? ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))) : NULL; + if (!encv) { if (t) ray_release(t); return -1; } + ray_enccol_t* e = ray_enccol_of(encv); + ray_enc_vview_t v; + int64_t hits = 0; + for (int64_t vec = 0; vec < ray_enc_nvecs(e->len); vec++) { + ray_t* err = NULL; + if (ray_enccol_vview(e, vec, &v, &err) != 1 || v.enc != RAY_ENC_FOR_BP) { if (err) ray_error_free(err); continue; } + const uint64_t m = v.k.T == 64 ? ~0ull : (1ull << v.k.T) - 1; + const uint64_t umax = v.width >= 64 ? ~0ull : (1ull << v.width) - 1; + const uint64_t room = v.k.is_signed ? (uint64_t)(int64_t)(m >> 1) - (uint64_t)ray_enc_logical(v.base, v.k) : m - v.base; + hits += umax > room; + } + ray_release(t); + return hits; +} + +/* Sound FOR_BP vectors near the top of their kind: the writer's base is + * the minimum, so base + (2^w - 1) may pass the largest value while every + * actual residual stays inside it. Each vouches and equals the decode. */ +static test_result_t test_vview_near_top(void) { + static const struct { const char* name; const char* col; const char* tbl; } fx[] = { + { "nu", "x", "(table [x] (list (as 'U8 (map (fn [j] (+ 200 (% j 56))) (til 3000)))))" }, + { "n16", "x", "(table [x] (list (as 'I16 (map (fn [j] (if (== 0 (% j 9)) 0N (- 32767 (% j 48)))) (til 3000)))))" }, + { "n32", "x", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (- 2147483647 (% j 48)))) (til 3000)))))" }, + { "n64", "x", "(table [x] (list (map (fn [j] (if (== 0 (% j 9)) 0N (- 9223372036854775807 (% j 48)))) (til 3000))))" }, + /* T = 64, w = 64: the least and the largest non-null value */ + { "nw", "x", "(table [x] (list (map (fn [j] (if (== 0 (% j 2)) -9223372036854775807 9223372036854775807)) (til 3000))))" }, + /* SYM W8: ids 1..250 in the first vector (the domain), 130..250 after */ + { "ns", "s", "(table [s] (list (as 'SYMBOL (map (fn [j] (format \"a%\" (if (< j 1024) (% j 250) (+ 129 (% j 121))))) (til 4000)))))" }, + }; + for (size_t i = 0; i < sizeof fx / sizeof fx[0]; i++) { + aw_save(fx[i].name, fx[i].tbl, RAY_ENC_FOR_BP); + test_result_t r = aw_check_view(fx[i].name, fx[i].col, RAY_ENC_FOR_BP); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(aw_near_top(fx[i].name, fx[i].col) > 0, "%s: no vector near the top", fx[i].name); + } + PASS(); +} + +/* ---- Declines: single-column files patched in place (the P2 corrupt-test + * pattern of test_enc_corrupt.c: the directory at byte 96, 64 bytes per + * chunk; 48-byte descriptors; payloads after the descriptor area) ---- */ + +static bool img_load(const char* p) { + free(g_img); g_img = NULL; g_len = 0; + FILE* f = fopen(p, "rb"); if (!f) return false; + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return false; } + long sz = ftell(f); if (sz < 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return false; } + g_len = (size_t)sz; g_img = malloc(g_len ? g_len : 1); + bool ok = g_img && fread(g_img, 1, g_len, f) == g_len; + fclose(f); + return ok; +} +static bool img_store(const char* p) { + FILE* f = fopen(p, "wb"); if (!f) return false; + bool ok = fwrite(g_img, 1, g_len, f) == g_len; + return fclose(f) == 0 && ok; +} +static uint64_t rd64(size_t off) { uint64_t x; memcpy(&x, g_img + off, 8); return x; } +#define DIR(c) (96 + 64 * (size_t)(c)) +#define EH 32 +static size_t desc_at(int j) { return (size_t)rd64(DIR(0)) + 48 * (size_t)j; } +/* Save v (owned) as one generation-2 column file, top-level encoding forced + * to `enc` (-1: the encoder's choice), and load its image. */ +static bool dv_save(ray_t* v, int enc, const char* p) { + ray_encw_test_force(enc); + ray_err_t e = ray_col_save_gen(v, p, 2); + ray_encw_test_force(-1); + ray_release(v); + return e == RAY_OK && img_load(p); +} +/* A SYM W8 column of n ids with saved count 200 (ids 200 and up are outside the domain). */ +static bool dv_save_sym_n(const uint8_t* ids, int n, int enc, uint32_t count, const char* p) { + FILE* f = fopen(p, "wb+"); + if (!f) return false; + ray_encw_t w; + ray_encw_test_force(enc); + bool ok = ray_encw_begin(&w, f, RAY_SYM, RAY_SYM_W8, n, count, 0, 0) == RAY_OK && + ray_encw_chunk(&w, ids, NULL, n) == RAY_OK && ray_encw_finish(&w) == RAY_OK; + ray_encw_test_force(-1); + ray_encw_free(&w); fclose(f); + return ok && img_load(p); +} + +static bool dv_save_sym(const uint8_t* ids, int n, int enc, const char* p) { return dv_save_sym_n(ids, n, enc, 200, p); } + +static bool msg_has(const char* needle) { + const char* m = ray_error_msg(); + return m && strstr(m, needle) != NULL; +} + +/* Store the image; the view of vector 0 returns `want` (-1: an error + * `corrupt` naming `needle`); then a range read of the vector reports + * `corrupt` naming `needle` (NULL: the read succeeds). */ +static const char* dv_expect(const char* p, int want, const char* needle) { + static char why[512]; + if (!img_store(p)) return "store"; + ray_t* c = ray_col_mmap(p); + if (!c || RAY_IS_ERR(c)) { + snprintf(why, sizeof why, "load failed: %s", c ? ray_error_msg() : "null"); + if (c) ray_error_free(c); + return why; + } + const char* res = NULL; + ray_enc_vview_t v; ray_t* err = NULL; + ray_error_clear(); + int got = ray_enccol_vview(ray_enccol_of(c), 0, &v, &err); + if (got != want) { + snprintf(why, sizeof why, "view gave %d (%s), want %d [%s]", got, err ? ray_error_msg() : "", want, needle ? needle : ""); + res = why; + } else if (want == -1 && !(err && strcmp(ray_err_code(err), "corrupt") == 0 && msg_has(needle))) { + snprintf(why, sizeof why, "view error %s: \"%s\", want corrupt [%s]", err ? ray_err_code(err) : "none", + err ? ray_error_msg() : "", needle); + res = why; + } else if (want != -1 && err) { + res = "an error beside a 0 / 1"; + } + if (err) ray_error_free(err); + if (!res) { + ray_col_src_t src; + ray_t* m = ray_col_src_bind(c, &src); + if (m) { ray_error_free(m); res = "bind failed"; } + else { + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + ray_error_clear(); + m = ray_col_range(&src, 0, src.len < RAY_ENC_VEC ? src.len : RAY_ENC_VEC, &sc, &r); + bool is_err = m && RAY_IS_ERR(m); + if (needle ? !(is_err && strcmp(ray_err_code(m), "corrupt") == 0 && msg_has(needle)) : is_err) { + snprintf(why, sizeof why, "range read gave %s: \"%s\", want %s [%s]", is_err ? ray_err_code(m) : "a view", + is_err && ray_error_msg() ? ray_error_msg() : "", needle ? "corrupt" : "a view", needle ? needle : ""); + res = why; + } + if (is_err) ray_error_free(m); + ray_col_scratch_free(&sc); ray_col_src_release(&src); + } + } + ray_release(c); + return res; +} +#define DV(p, want, needle) do { const char* w_ = dv_expect((p), (want), (needle)); \ + TEST_ASSERT_FMT(w_ == NULL, "%s:%d %s", __FILE__, __LINE__, w_); } while (0) +#define DV_SAVE(v, enc, p) TEST_ASSERT_TRUE(dv_save((v), (enc), (p))) +#define DV_SAVE_SYM(ids, n, enc, p) TEST_ASSERT_TRUE(dv_save_sym((ids), (n), (enc), (p))) +#define NEED_ENC(j, enc) TEST_ASSERT_FMT(g_img[desc_at(j)] == (enc), \ + "descriptor %d is encoding %d, the test pins %d", j, g_img[desc_at(j)], enc) + +/* 1024 rows of `type` (U8 / I16 / I32): base + a hash of i in [0, 64). */ +static ray_t* dv_hash(int8_t type, int base, int null_every) { + ray_t* v = ray_vec_new(type, 1024); + if (!v || RAY_IS_ERR(v)) return NULL; + v->len = 1024; + for (int i = 0; i < 1024; i++) { + int x = base + (int)(((uint32_t)i * 2654435761u) >> 26); + bool nul = null_every && i % null_every == 0; + if (type == RAY_U8) ((uint8_t*)ray_data(v))[i] = (uint8_t)x; + else if (type == RAY_I16) ((int16_t*)ray_data(v))[i] = nul ? NULL_I16 : (int16_t)x; + else ((int32_t*)ray_data(v))[i] = nul ? NULL_I32 : x; + } + if (null_every) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} +/* 1024 I32 rows: runs of 100 (values 7 + run), nulls every 10th row when asked. */ +static ray_t* dv_runs(int null_every, bool constant) { + ray_t* v = ray_vec_new(RAY_I32, 1024); v->len = 1024; + for (int i = 0; i < 1024; i++) + ((int32_t*)ray_data(v))[i] = null_every && i % null_every == 0 ? NULL_I32 : 7 + (constant ? 0 : i / 100); + if (null_every) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} +/* Four wide values at hash-scattered rows: DICT over a FOR_BP w=2 code child. */ +static ray_t* dv_dict(void) { + static const int64_t vals[4] = { 11, 900000000001ll, 77, 123456789012345ll }; + ray_t* v = ray_vec_new(RAY_I64, 1024); v->len = 1024; + for (int i = 0; i < 1024; i++) ((int64_t*)ray_data(v))[i] = vals[(uint32_t)((uint32_t)i * 2654435761u) >> 30]; + return v; +} +static ray_t* dv_f64(bool constant) { + ray_t* v = ray_vec_new(RAY_F64, 1024); v->len = 1024; + for (int i = 0; i < 1024; i++) ((double*)ray_data(v))[i] = constant ? 2.5 : (double)i * 0.25; + return v; +} + +/* RAW and DELTA_BP have no view; a view never vouches for a vector its + * decode rejects. One sub-case per rule of the view's validation: each + * declines (0) or reports what the decode reports (-1), and the range read + * of the same vector then reports it `corrupt` with its exact rule. */ +static test_result_t test_vview_declines(void) { + const char* p = ray_test_tmp(AW_TMP "/dv"); + for (int i = 0; i < 256; i++) { char b[8]; int n = snprintf(b, sizeof b, "s%d", i); (void)ray_sym_intern(b, (size_t)n); } + /* no view: RAW, DELTA_BP, a float other than CONST */ + DV_SAVE(dv_hash(RAY_I32, 5000, 0), RAY_ENC_RAW, p); NEED_ENC(0, RAY_ENC_RAW); DV(p, 0, NULL); + { + ray_t* v = ray_vec_new(RAY_I32, 1024); v->len = 1024; + for (int i = 0; i < 1024; i++) ((int32_t*)ray_data(v))[i] = i * 3 + (i * 7) % 5; + DV_SAVE(v, RAY_ENC_DELTA_BP, p); NEED_ENC(0, RAY_ENC_DELTA_BP); DV(p, 0, NULL); + } + DV_SAVE(dv_f64(false), RAY_ENC_RAW, p); NEED_ENC(0, RAY_ENC_RAW); DV(p, 0, NULL); + /* a view: FOR_BP (with nulls too), CONST, RLE, SYM, DICT, float CONST */ + DV_SAVE(dv_hash(RAY_I32, 5000, 0), RAY_ENC_FOR_BP, p); NEED_ENC(0, RAY_ENC_FOR_BP); DV(p, 1, NULL); + DV_SAVE(dv_hash(RAY_I32, 5000, 10), RAY_ENC_FOR_BP, p); NEED_ENC(0, RAY_ENC_FOR_BP); DV(p, 1, NULL); + DV_SAVE(dv_hash(RAY_I16, 5000, 10), RAY_ENC_FOR_BP, p); NEED_ENC(0, RAY_ENC_FOR_BP); DV(p, 1, NULL); + DV_SAVE(dv_hash(RAY_U8, 0, 0), RAY_ENC_FOR_BP, p); NEED_ENC(0, RAY_ENC_FOR_BP); DV(p, 1, NULL); + DV_SAVE(dv_runs(0, true), RAY_ENC_CONST, p); NEED_ENC(0, RAY_ENC_CONST); DV(p, 1, NULL); + DV_SAVE(dv_runs(10, true), RAY_ENC_CONST, p); NEED_ENC(0, RAY_ENC_CONST); DV(p, 1, NULL); + DV_SAVE(dv_runs(0, false), RAY_ENC_RLE, p); NEED_ENC(0, RAY_ENC_RLE); DV(p, 1, NULL); + { + uint8_t ids[1024]; + for (int i = 0; i < 1024; i++) ids[i] = 5; + DV_SAVE_SYM(ids, 1024, RAY_ENC_CONST, p); NEED_ENC(0, RAY_ENC_CONST); DV(p, 1, NULL); + for (int i = 0; i < 1024; i++) ids[i] = (uint8_t)(1 + i / 100); + DV_SAVE_SYM(ids, 1024, RAY_ENC_RLE, p); NEED_ENC(0, RAY_ENC_RLE); DV(p, 1, NULL); + for (int i = 0; i < 1024; i++) ids[i] = (uint8_t)(100 + i % 16); + DV_SAVE_SYM(ids, 1024, RAY_ENC_FOR_BP, p); NEED_ENC(0, RAY_ENC_FOR_BP); DV(p, 1, NULL); + } + DV_SAVE(dv_dict(), RAY_ENC_DICT, p); NEED_ENC(0, RAY_ENC_DICT); DV(p, 1, NULL); + DV_SAVE(dv_f64(true), RAY_ENC_CONST, p); NEED_ENC(0, RAY_ENC_CONST); DV(p, 1, NULL); + PASS(); +} + +/* ray_col_src_vview: a single-file generation-2 source gives its views; a + * generation-0 source and a published materialization decline (read them + * in place). */ +static test_result_t test_vview_source(void) { + aw_save("vq", "(table [x] (list (as 'I32 (map (fn [j] (% j 50)) (til 3000)))))", RAY_ENC_FOR_BP); + for (int gen = 0; gen < 2; gen++) { + ray_t* t = aw_load("vq", gen ? 2 : 0); + TEST_ASSERT_NOT_NULL(t); + ray_col_src_t s; + ray_t* err = ray_table_col_src(t, ray_sym_intern("x", 1), &s); + TEST_ASSERT_NULL(err); + ray_enc_vview_t v; + for (int64_t vec = 0; vec < 3; vec++) { + TEST_ASSERT_EQ_I(ray_col_src_vview(&s, vec, &v, &err), gen ? 1 : 0); + TEST_ASSERT_NULL(err); + if (gen) { TEST_ASSERT_EQ_I(v.enc, RAY_ENC_FOR_BP); TEST_ASSERT_EQ_I(v.n, vec < 2 ? 1024 : 3000 - 2048); } + } + TEST_ASSERT_EQ_I(ray_col_src_vview(&s, 3, &v, &err), 0); /* past the end */ + TEST_ASSERT_EQ_I(ray_col_src_vview(&s, -1, &v, &err), 0); + if (gen) { + ray_t* m = ray_enccol_materialize(s.obj); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_col_src_vview(&s, 0, &v, &err), 0); /* published: read it in place */ + } + ray_col_src_release(&s); + ray_release(t); + } + PASS(); +} + +/* ---- Encoded comparison and membership evaluators (store/enceval.h) ---- */ + +static int aw_ref_cmp(int64_t x, uint16_t op, int64_t c) { + switch (op) { + case OP_EQ: return x == c; case OP_NE: return x != c; + case OP_LT: return x < c; case OP_LE: return x <= c; + case OP_GT: return x > c; case OP_GE: return x >= c; + default: return 0; + } +} +/* null_result as the fused kernels give it: a null ranks below every value. */ +static uint8_t aw_null_result(uint16_t op) { return op == OP_NE || op == OP_LT || op == OP_LE; } + +static test_result_t aw_eval_all(const char* name, int enc, const int64_t* consts, int nc) { + ray_t* t = aw_load(name, 2); + TEST_ASSERT_NOT_NULL(t); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + ray_enc_vview_t vb, *v = &vb; /* a scan task's stack view */ + ray_t* verr = NULL; + int64_t vals[RAY_ENC_VEC]; uint8_t bits[RAY_ENC_VEC]; + static const uint16_t ops[] = { OP_EQ, OP_NE, OP_LT, OP_LE, OP_GT, OP_GE }; + ray_enc_counters_reset(); + for (int64_t vec = 0; vec < ray_enc_nvecs(e->len); vec++) { + TEST_ASSERT_EQ_I(ray_enccol_vview(e, vec, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, enc); + aw_view_values(v, vals); + for (int oi = 0; oi < 6; oi++) for (int ci = 0; ci < nc; ci++) { + uint8_t nr = aw_null_result(ops[oi]); + TEST_ASSERT_TRUE(ray_enc_eval_cmp(v, ops[oi], consts[ci], nr, bits)); + for (int i = 0; i < v->n; i++) { + bool isnull = v->nullmap && ((v->nullmap[i >> 3] >> (i & 7)) & 1); + int want = isnull ? nr : aw_ref_cmp(vals[i], ops[oi], consts[ci]); + TEST_ASSERT_FMT(bits[i] == want, "%s vec %lld op %u c %lld row %d", name, + (long long)vec, ops[oi], (long long)consts[ci], i); + } + } + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* answered from the views, nothing decoded */ + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(t); + PASS(); +} + +static test_result_t test_eval_encodings(void) { + const char* tbl = "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (- (% j 50) 20))) (til 3000)))))"; + static const int64_t cs[] = { -100, -21, -20, -1, 0, 7, 29, 30, 1000 }; + test_result_t r; + aw_save("ef", tbl, RAY_ENC_FOR_BP); if ((r = aw_eval_all("ef", RAY_ENC_FOR_BP, cs, 9)).status != TEST_PASS) return r; + aw_save("er", tbl, RAY_ENC_RLE); if ((r = aw_eval_all("er", RAY_ENC_RLE, cs, 9)).status != TEST_PASS) return r; + aw_save("ed", tbl, RAY_ENC_DICT); if ((r = aw_eval_all("ed", RAY_ENC_DICT, cs, 9)).status != TEST_PASS) return r; + aw_save("ec", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N 7)) (til 3000)))))", RAY_ENC_CONST); + if ((r = aw_eval_all("ec", RAY_ENC_CONST, cs, 9)).status != TEST_PASS) return r; + /* I64 at the domain edges, residuals at 64 bits */ + static const int64_t c64[] = { INT64_MIN + 1, -9223372036854775806LL, -1, 0, 9223372036854775806LL, INT64_MAX }; + aw_save("e64", "(table [x] (list (as 'I64 (map (fn [j] (if (== 0 (% j 3)) -9223372036854775807 (if (== 1 (% j 3)) 9223372036854775807 0))) (til 3000)))))", + RAY_ENC_FOR_BP); + if ((r = aw_eval_all("e64", RAY_ENC_FOR_BP, c64, 6)).status != TEST_PASS) return r; + PASS(); +} + +/* Review focus 2: signedness and the domain edges. */ +static test_result_t test_eval_for_edges(void) { + static const int64_t c16[] = { -32768, -32767, -151, -150, -129, -128, 0, 127, 128, 149, 150, 32767 }; + test_result_t r; + aw_save("e16", "(table [x] (list (as 'I16 (- (% (til 3000) 300) 150))))", RAY_ENC_FOR_BP); + if ((r = aw_eval_all("e16", RAY_ENC_FOR_BP, c16, 12)).status != TEST_PASS) return r; + static const int64_t cu8[] = { -1, 0, 1, 99, 100, 126, 127, 128, 129, 159, 160, 255, 256 }; + aw_save("eu8", "(table [x] (list (as 'U8 (+ 100 (% (til 3000) 60)))))", RAY_ENC_FOR_BP); /* 100..159 crosses 127/128 */ + if ((r = aw_eval_all("eu8", RAY_ENC_FOR_BP, cu8, 13)).status != TEST_PASS) return r; + static const int64_t c32[] = { -2147483647LL, -1000001, -1000000, -999999, -999994, -999993, 0, 2147483647LL }; + aw_save("e32", "(table [x] (list (as 'I32 (- (% (til 3000) 7) 1000000))))", RAY_ENC_FOR_BP); + if ((r = aw_eval_all("e32", RAY_ENC_FOR_BP, c32, 8)).status != TEST_PASS) return r; + PASS(); +} + +/* Review focus 1: a nullable CONST vector. */ +static test_result_t test_eval_const_nulls(void) { + aw_save("cn", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 5)) 0N 10)) (til 1024)))))", RAY_ENC_CONST); + ray_t* t = aw_load("cn", 2); + TEST_ASSERT_NOT_NULL(t); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + ray_enc_vview_t vb, *v = &vb; /* a scan task's stack view */ + ray_t* verr = NULL; + TEST_ASSERT_EQ_I(ray_enccol_vview(e, 0, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_LT, 20, 1), 1); /* 10 < 20 and null < 20: ALL */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_GT, 5, 0), -1); /* 10 > 5, nulls fail: MIX */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_EQ, 3, 0), 0); /* nothing passes: NONE */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_NE, 3, 1), 1); /* 10 != 3 and null != 3: ALL */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_GE, 20, 1), -1); /* 10 fails, nulls pass: MIX */ + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(v, OP_LT, 20.0, 1), -1); /* not a float view */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_EQ - 1, 10, 0), -1); /* not a comparison */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_GE + 1, 10, 0), -1); + { uint8_t bits[RAY_ENC_VEC]; TEST_ASSERT_FALSE(ray_enc_eval_cmp(v, OP_GE + 1, 10, 0, bits)); } + ray_release(t); + /* every row null: every row is null_result */ + aw_save("ca", "(table [x] (list (as 'I32 (map (fn [j] 0N) (til 1024)))))", RAY_ENC_CONST); + t = aw_load("ca", 2); + TEST_ASSERT_NOT_NULL(t); + e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + TEST_ASSERT_EQ_I(ray_enccol_vview(e, 0, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_GT, 5, 0), 0); + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_LT, 5, 1), 1); + ray_release(t); + /* no nulls: decided whole either way */ + aw_save("cv", "(table [x] (list (as 'I32 (map (fn [j] 10) (til 1024)))))", RAY_ENC_CONST); + t = aw_load("cv", 2); + TEST_ASSERT_NOT_NULL(t); + e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + TEST_ASSERT_EQ_I(ray_enccol_vview(e, 0, v, &verr), 1); + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_GT, 5, 0), 1); + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_LT, 5, 1), 0); + ray_release(t); + PASS(); +} + +static test_result_t test_eval_in(void) { + aw_save("ei", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 11)) 0N (% j 40))) (til 3000)))))", RAY_ENC_DICT); + aw_save("eiF", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 11)) 0N (% j 40))) (til 3000)))))", RAY_ENC_FOR_BP); + aw_save("eiR", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 11)) 0N (% j 40))) (til 3000)))))", RAY_ENC_RLE); + aw_save("eiC", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 11)) 0N 17)) (til 3000)))))", RAY_ENC_CONST); + static const char* names[] = { "ei", "eiF", "eiR", "eiC" }; + static const int encs[] = { RAY_ENC_DICT, RAY_ENC_FOR_BP, RAY_ENC_RLE, RAY_ENC_CONST }; + static const int64_t set[] = { -5, 3, 17, 39, 41 }; + ray_enc_counters_reset(); + for (int s = 0; s < 4; s++) { + ray_t* t = aw_load(names[s], 2); + TEST_ASSERT_NOT_NULL(t); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + ray_enc_vview_t vb, *v = &vb; /* a scan task's stack view */ + ray_t* verr = NULL; + int64_t vals[RAY_ENC_VEC]; uint8_t bits[RAY_ENC_VEC]; + for (int64_t vec = 0; vec < 3; vec++) { + TEST_ASSERT_EQ_I(ray_enccol_vview(e, vec, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, encs[s]); + aw_view_values(v, vals); + for (uint8_t nr = 0; nr < 2; nr++) { + TEST_ASSERT_TRUE(ray_enc_eval_in(v, set, 5, nr, bits)); + for (int i = 0; i < v->n; i++) { + bool isnull = v->nullmap && ((v->nullmap[i >> 3] >> (i & 7)) & 1); + int want = isnull ? nr : (vals[i] == 3 || vals[i] == 17 || vals[i] == 39); + TEST_ASSERT_FMT(bits[i] == want, "%s vec %lld row %d", names[s], (long long)vec, i); + } + TEST_ASSERT_TRUE(ray_enc_eval_in(v, set, 0, nr, bits)); /* the empty set */ + for (int i = 0; i < v->n; i++) { + bool isnull = v->nullmap && ((v->nullmap[i >> 3] >> (i & 7)) & 1); + TEST_ASSERT_EQ_I(bits[i], isnull ? nr : 0); + } + } + } + ray_release(t); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* answered from the views, nothing decoded */ + TEST_ASSERT_EQ_U(k.materialized, 0); + PASS(); +} + +/* The integer evaluators against the generation-0 engine itself: the + * vector comparison of the gen-0 copy, row for row, on a nullable I16 and + * a U8 column under every encoding, with constants inside, at the edges + * of and outside the vectors' range (and the type's). */ +static test_result_t test_eval_gen0(void) { + static const uint16_t ops[] = { OP_EQ, OP_NE, OP_LT, OP_LE, OP_GT, OP_GE }; + static const char* opname[] = { "==", "!=", "<", "<=", ">", ">=" }; + static const int encs[] = { RAY_ENC_FOR_BP, RAY_ENC_RLE, RAY_ENC_DICT }; + static const struct { const char* tbl; int64_t cs[8]; int nc; bool nullable; } cols[] = { + { "(table [x] (list (as 'I16 (map (fn [j] (if (== 0 (% j 13)) 0N (- (% (div j 3) 300) 150))) (til 3000)))))", + { -40000, -32768, -151, -150, 0, 149, 150, 40000 }, 8, true }, + { "(table [x] (list (as 'U8 (+ 100 (% (div (til 3000) 3) 60)))))", + { -1, 0, 99, 100, 127, 128, 159, 300 }, 8, false }, + }; + uint8_t bits[RAY_ENC_VEC]; + for (int ci = 0; ci < 2; ci++) for (int ei = 0; ei < 3; ei++) { + if (encs[ei] == RAY_ENC_DICT && !cols[ci].nullable) continue; /* DICT views are signed kinds only */ + aw_save("eg", cols[ci].tbl, encs[ei]); + ray_t* t = aw_load("eg", 2); + TEST_ASSERT_NOT_NULL(t); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + ray_enc_vview_t vb, *v = &vb; + ray_t* verr = NULL; + for (int oi = 0; oi < 6; oi++) for (int k = 0; k < cols[ci].nc; k++) { + char q[256]; + snprintf(q, sizeof q, "(%s (at (.db.splayed.get \"" AW_TMP "/eg0/\") 'x) %lld)", opname[oi], + (long long)cols[ci].cs[k]); + ray_t* r = aw_eval(q); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_BOOL && r->len == e->len, "%s", q); + const uint8_t* rb = (const uint8_t*)ray_data(r); + const uint8_t nr = aw_null_result(ops[oi]); + for (int64_t vec = 0; vec < ray_enc_nvecs(e->len); vec++) { + TEST_ASSERT_EQ_I(ray_enccol_vview(e, vec, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, encs[ei]); + TEST_ASSERT_TRUE(ray_enc_eval_cmp(v, ops[oi], cols[ci].cs[k], nr, bits)); + for (int i = 0; i < v->n; i++) + TEST_ASSERT_FMT(bits[i] == rb[vec * RAY_ENC_VEC + i], "%s enc %d vec %lld row %d", q, encs[ei], + (long long)vec, i); + } + ray_release(r); + } + ray_release(t); + char rm[256]; + snprintf(rm, sizeof rm, "%s/eg0", aw_root()); (void)ray_test_rm_rf(rm); + snprintf(rm, sizeof rm, "%s/eg2", aw_root()); (void)ray_test_rm_rf(rm); + } + PASS(); +} + +/* SYM: ids compare as unsigned, == / != / in only; an ordered operator + * declines (never order ids, #738). */ +static test_result_t test_eval_sym(void) { + static const int encs[] = { RAY_ENC_FOR_BP, RAY_ENC_RLE, RAY_ENC_CONST }; + static const char* tbls[] = { + "(table [x] (list (as 'SYM (map (fn [j] (if (== 0 (% j 7)) (as 'SYM \"\") (at ['a 'b 'c 'd 'e] (% j 5)))) (til 3000)))))", + "(table [x] (list (as 'SYM (map (fn [j] (if (== 0 (% (div j 100) 7)) (as 'SYM \"\") (at ['a 'b 'c 'd 'e] (% (div j 100) 5)))) (til 3000)))))", + "(table [x] (list (take ['b] 3000)))", + }; + static const uint16_t ord[] = { OP_LT, OP_LE, OP_GT, OP_GE }; + for (int s = 0; s < 3; s++) { + char nm[8]; snprintf(nm, sizeof nm, "es%d", s); + aw_save(nm, tbls[s], encs[s]); + ray_t* t = aw_load(nm, 2); + ray_enc_counters_reset(); + TEST_ASSERT_NOT_NULL(t); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + TEST_ASSERT_EQ_I(e->type, RAY_SYM); + ray_enc_vview_t vb, *v = &vb; + ray_t* verr = NULL; + int64_t vals[RAY_ENC_VEC]; uint8_t bits[RAY_ENC_VEC]; + for (int64_t vec = 0; vec < ray_enc_nvecs(e->len); vec++) { + TEST_ASSERT_EQ_I(ray_enccol_vview(e, vec, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, encs[s]); + aw_view_values(v, vals); + for (int o = 0; o < 4; o++) TEST_ASSERT_FALSE(ray_enc_eval_cmp(v, ord[o], vals[0], 0, bits)); + /* constants: every id of the vector, "" (id 0) and an id past the bound */ + int64_t cs[RAY_ENC_VEC + 2]; int nc = 0; + cs[nc++] = 0; cs[nc++] = ray_sym_domain_count(e->dom) + 5; + for (int i = 0; i < v->n && nc < 8; i++) { bool dup = false; for (int q = 0; q < nc; q++) dup |= cs[q] == vals[i]; if (!dup) cs[nc++] = vals[i]; } + for (int ci = 0; ci < nc; ci++) for (int o = 0; o < 2; o++) { + const uint16_t op = o ? OP_NE : OP_EQ; + TEST_ASSERT_TRUE(ray_enc_eval_cmp(v, op, cs[ci], 0, bits)); + for (int i = 0; i < v->n; i++) TEST_ASSERT_EQ_I(bits[i], aw_ref_cmp(vals[i], op, cs[ci])); + } + int64_t set[8]; int ns = 0; /* sorted, distinct */ + for (int ci = 0; ci < nc; ci += 2) set[ns++] = cs[ci]; + for (int a = 1; a < ns; a++) for (int b = a; b > 0 && set[b - 1] > set[b]; b--) { int64_t x = set[b]; set[b] = set[b - 1]; set[b - 1] = x; } + TEST_ASSERT_TRUE(ray_enc_eval_in(v, set, ns, 0, bits)); + for (int i = 0; i < v->n; i++) { + int want = 0; for (int q = 0; q < ns; q++) want |= vals[i] == set[q]; + TEST_ASSERT_EQ_I(bits[i], want); + } + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(t); + } + PASS(); +} + +/* ray_enc_const_decision_f64 on CONST -0.0, +0.0 and nullable 1.5 vectors + * (F64 and F32) against both zero literals under all six operators: the + * answer equals the generation-0 comparison's over the vector's rows + * (1 all pass, 0 none, -1 mixed). */ +static ray_t* aw_fvec(int8_t type, double x, int null_every) { + ray_t* v = ray_vec_new(type, 1024); + if (!v || RAY_IS_ERR(v)) return NULL; + v->len = 1024; + for (int i = 0; i < 1024; i++) { + if (type == RAY_F64) ((double*)ray_data(v))[i] = x; else ((float*)ray_data(v))[i] = (float)x; + } + if (null_every) for (int i = 0; i < 1024; i += null_every) ray_vec_set_null(v, i, true); + return v; +} +static test_result_t test_eval_float_const(void) { + static const uint16_t ops[] = { OP_EQ, OP_NE, OP_LT, OP_LE, OP_GT, OP_GE }; + static const char* opname[] = { "==", "!=", "<", "<=", ">", ">=" }; + static const double xs[] = { -0.0, 0.0, 1.5 }; + static const int nulls[] = { 0, 0, 5 }; + static const int8_t types[] = { RAY_F64, RAY_F32 }; + static const double cs[] = { -0.0, 0.0 }; + static const char* clit[] = { "-0.0", "0.0" }; + for (int ti = 0; ti < 2; ti++) for (int xi = 0; xi < 3; xi++) { + ray_t* col = aw_fvec(types[ti], xs[xi], nulls[xi]); + TEST_ASSERT_NOT_NULL(col); + ray_t* tb = ray_table_new(1); + tb = ray_table_add_col(tb, ray_sym_intern("x", 1), col); ray_release(col); + TEST_ASSERT_TRUE(tb && !RAY_IS_ERR(tb)); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("WF", 2), tb), RAY_OK); + ray_release(tb); + aw_save("fc", "WF", RAY_ENC_CONST); + ray_t* t = aw_load("fc", 2); + TEST_ASSERT_NOT_NULL(t); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern("x", 1))); + ray_enc_vview_t vb, *v = &vb; + ray_t* verr = NULL; + TEST_ASSERT_EQ_I(ray_enccol_vview(e, 0, v, &verr), 1); + TEST_ASSERT_EQ_I(v->enc, RAY_ENC_CONST); + if (xi == 0) TEST_ASSERT_EQ_U(v->cbits, types[ti] == RAY_F64 ? 0x8000000000000000ull : 0x80000000ull); + uint8_t bits[RAY_ENC_VEC]; + TEST_ASSERT_FALSE(ray_enc_eval_cmp(v, OP_EQ, 0, 0, bits)); /* floats: no integer evaluator */ + TEST_ASSERT_EQ_I(ray_enc_const_decision(v, OP_EQ, 0, 0), -1); + for (int oi = 0; oi < 6; oi++) /* a NaN constant is the null one */ + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(v, ops[oi], NAN, aw_null_result(ops[oi])), -1); + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(v, OP_EQ - 1, 0.0, 0), -1); /* not a comparison */ + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(v, OP_GE + 1, 0.0, 0), -1); + for (int oi = 0; oi < 6; oi++) for (int ci = 0; ci < 2; ci++) { + char q[256]; + snprintf(q, sizeof q, "(%s (at (.db.splayed.get \"" AW_TMP "/fc0/\") 'x) %s)", opname[oi], clit[ci]); + ray_t* r = aw_eval(q); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_BOOL && r->len == 1024, "%s", q); + const uint8_t* rb = (const uint8_t*)ray_data(r); + int all = 1, none = 1; uint8_t nr = aw_null_result(ops[oi]); + for (int i = 0; i < 1024; i++) { + all &= rb[i] != 0; none &= rb[i] == 0; + if (nulls[xi] && i % nulls[xi] == 0) TEST_ASSERT_EQ_I(rb[i], nr); /* a null ranks below */ + } + ray_release(r); + int want = all ? 1 : none ? 0 : -1; + TEST_ASSERT_FMT(ray_enc_const_decision_f64(v, ops[oi], cs[ci], nr) == want, + "type %d x %g %s %s", types[ti], xs[xi], opname[oi], clit[ci]); + } + ray_release(t); + char rm[256]; + snprintf(rm, sizeof rm, "%s/fc0", aw_root()); (void)ray_test_rm_rf(rm); + snprintf(rm, sizeof rm, "%s/fc2", aw_root()); (void)ray_test_rm_rf(rm); + } + PASS(); +} + +/* ---- Task 3: fused filters on encoded leaves ---- */ + +/* Fused selection over 0 and 2: equal rowsels; the generation-2 + * run materializes nothing and decodes exactly `want_decoded` bytes + * (-1: do not check). */ +static test_result_t aw_sel_same(const char* name, ray_op_t* (*build)(ray_graph_t*), int64_t want_decoded) { + ray_t* blk[2] = { NULL, NULL }; bool all[2] = { false, false }; + for (int gen = 0; gen <= 2; gen += 2) { + ray_t* t = aw_load(name, gen); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + ray_op_t* pred = build(g); + ray_enc_counters_reset(); + blk[gen / 2] = exec_pred_to_selection(g, pred, ray_table_nrows(t), &all[gen / 2]); + TEST_ASSERT_FMT(!(blk[gen / 2] && RAY_IS_ERR(blk[gen / 2])), "%s gen %d: %s", name, gen, ray_error_msg()); + TEST_ASSERT_FMT(blk[gen / 2] || all[gen / 2], "%s gen %d: the fused path declined", name, gen); + if (gen == 2) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + if (want_decoded >= 0) + TEST_ASSERT_FMT(k.decoded_bytes == (uint64_t)want_decoded, "%s: decoded %llu, want %lld", + name, (unsigned long long)k.decoded_bytes, (long long)want_decoded); + } + ray_graph_free(g); ray_release(t); + } + TEST_ASSERT_EQ_I(all[0], all[1]); + if (blk[0]) { + ray_rowsel_t* a = ray_rowsel_meta(blk[0]); ray_rowsel_t* b = ray_rowsel_meta(blk[1]); + TEST_ASSERT_EQ_I(a->total_pass, b->total_pass); + TEST_ASSERT_TRUE(memcmp(ray_rowsel_flags(blk[0]), ray_rowsel_flags(blk[1]), a->n_segs) == 0); + uint32_t nidx = ray_rowsel_offsets(blk[0])[a->n_segs]; + TEST_ASSERT_TRUE(memcmp(ray_rowsel_idx(blk[0]), ray_rowsel_idx(blk[1]), (size_t)nidx * 2) == 0); + ray_rowsel_release(blk[0]); ray_rowsel_release(blk[1]); + } + PASS(); +} +static ray_op_t* ap_x_eq7(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "x"), ray_const_i64(g, 7)); } +static ray_op_t* ap_x_gt10(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "x"), ray_const_i64(g, 10)); } +static ray_op_t* ap_x_lt1000(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "x"), ray_const_i64(g, 1000)); } +static ray_op_t* ap_band(ray_graph_t* g) { + return ray_and(g, ray_ge(g, ray_scan(g, "x"), ray_const_i64(g, -5)), ray_le(g, ray_scan(g, "x"), ray_const_i64(g, 12))); +} +static ray_op_t* ap_f_gt(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "f"), ray_const_f64(g, 0.0)); } + +static test_result_t test_filter_encoded_leaves(void) { + const char* tbl = "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (- (% j 50) 20))) (til 70000)))))"; + test_result_t r; + static const int enc[] = { RAY_ENC_FOR_BP, RAY_ENC_RLE, RAY_ENC_DICT }; + static const char* nm[] = { "lf", "lr", "ld" }; + for (int i = 0; i < 3; i++) { + aw_save(nm[i], tbl, enc[i]); + TEST_ASSERT_EQ_I(aw_vec_enc(nm[i], "x", 0), enc[i]); + if ((r = aw_sel_same(nm[i], ap_x_eq7, 0)).status != TEST_PASS) return r; /* codes answer: no decode */ + if ((r = aw_sel_same(nm[i], ap_band, 0)).status != TEST_PASS) return r; + } + /* RAW: no evaluator; every vector holds 7 and other values, so none is + * decided and every one decodes: all 70000 rows x 4 bytes */ + aw_save("lw", tbl, RAY_ENC_RAW); + if ((r = aw_sel_same("lw", ap_x_eq7, 70000 * 4)).status != TEST_PASS) return r; + PASS(); +} + +/* Vector-level decisions: x = row; a predicate true for rows 0..999 decides + * every vector from its descriptor except vector 0 (rows 0..1023), which the + * FOR_BP leaf answers without a decode. The descriptor half passes at HEAD + * (17b); vector 0's leaf is this task's. */ +static test_result_t test_filter_vector_decisions(void) { + aw_save("vd1", "(table [x] (list (til 70000)))", RAY_ENC_FOR_BP); + return aw_sel_same("vd1", ap_x_lt1000, 0); +} + +/* Review focus 1: nullable CONST vectors and null masking. x is constant + * per vector (vector index) with every 5th row null. */ +static test_result_t test_filter_nulls_masked(void) { + aw_save("nm", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 5)) 0N (div j 1024))) (til 70000)))))", RAY_ENC_CONST); + test_result_t r; + if ((r = aw_sel_same("nm", ap_x_lt1000, 0)).status != TEST_PASS) return r; /* value < c and null < c: every vector ALL */ + if ((r = aw_sel_same("nm", ap_x_gt10, 0)).status != TEST_PASS) return r; /* passing vectors are MIX (nulls fail >) */ + PASS(); +} + +/* Mixed generations: x generation 2 (a leaf), y generation 0 (a plain + * register in the same program). The generation-0 save of the pair is the + * reference. */ +static ray_op_t* ap_mixed(ray_graph_t* g) { + return ray_and(g, ray_eq(g, ray_scan(g, "x"), ray_const_i64(g, 7)), ray_gt(g, ray_scan(g, "y"), ray_const_i64(g, 300))); +} +static test_result_t test_filter_mixed_generations(void) { + aw_eval_ok("(set W (table [x y] (list (as 'I32 (- (% (til 70000) 50) 20)) (% (* (til 70000) 7) 1000))))"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/mx0/\" W {compress: false})"); + /* generation 2 for x only: save compressed, then put y back as generation 0 */ + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/mx2/\" W {compress: true})"); + char dir[512]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(ray_test_tmp(AW_TMP "/mx2"), dir, sizeof dir), RAY_OK); + char ypath[600]; snprintf(ypath, sizeof ypath, "%s/y", dir); + ray_t* y0 = aw_eval("(at W 'y)"); + TEST_ASSERT_TRUE(y0 && !RAY_IS_ERR(y0)); + TEST_ASSERT_EQ_I(ray_col_save_gen(y0, ypath, 0), RAY_OK); + ray_release(y0); + ray_t* t = aw_load("mx", 2); + TEST_ASSERT_NOT_NULL(t); + ray_col_meta_t mx, my; + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("x", 1), &mx) && mx.enc); + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("y", 1), &my) && !my.enc); + ray_release(t); + return aw_sel_same("mx", ap_mixed, 0); /* x: leaves; y: generation 0, read in place */ +} + +/* A parted table: the plan is built per segment. */ +static test_result_t test_filter_parted_leaves(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/pl%d/2024.01.0%d/t/\" " + "(table [x] (list (as 'I32 (- (%% (til 70000) 50) 20)))) {compress: %s})", + gen, p + 1, gen ? "true" : "false"); + aw_eval_ok(q); + } + ray_t* a = aw_eval("(count (select {from: (.db.parted.get \"" AW_TMP "/pl0\" 't) where: (== x 7)}))"); + ray_enc_counters_reset(); + ray_t* b = aw_eval("(count (select {from: (.db.parted.get \"" AW_TMP "/pl2\" 't) where: (== x 7)}))"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b)); + TEST_ASSERT_EQ_I(a->i64, b->i64); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* leaves on the encoded segments */ + ray_release(a); ray_release(b); + PASS(); +} + +/* Floats: f is -0.0 in vectors 0-1, +0.0 in vectors 2-3, null in vector 4 + * (rows 4096..5119), then j. Vectors 0-3 are CONST and decided by their + * descriptors (-0.0 == +0.0: max <= 0.0 fails > 0.0); vector 4 is an + * all-null CONST vector without statistics, which only the float leaf + * answers (ray_enc_const_decision_f64: every row null_result, 0 for >, + * 1 for <); the RAW vectors of j are decided by their descriptors and + * chunk 1 by its directory. Nothing decodes. */ +static ray_op_t* ap_f_lt(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "f"), ray_const_f64(g, 1e12)); } +static test_result_t test_filter_floats(void) { + aw_save("fl", "(table [f] (list (as 'F64 (map (fn [j] (if (< j 2048) -0.0 (if (< j 4096) 0.0 (if (< j 5120) 0Nf (as 'F64 j))))) " + "(til 70000)))))", -1); + TEST_ASSERT_EQ_I(aw_vec_enc("fl", "f", 1), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(aw_vec_enc("fl", "f", 4), RAY_ENC_CONST); + test_result_t r; + if ((r = aw_sel_same("fl", ap_f_gt, 0)).status != TEST_PASS) return r; + return aw_sel_same("fl", ap_f_lt, 0); +} + +/* D8: the fused top-k predicate. x nullable (the leaf fixtures): the sort + * key x is materialized once, so the predicate reads it in place and adds + * no decode. x without nulls beside a sort key k: the predicate leaf is + * answered on x's views, so x decodes nothing at all. */ +static test_result_t test_fused_pred_leaves(void) { + const char* tbl = "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (- (% j 50) 20))) (til 70000)))))"; + const char* tbk = "(table [x k] (list (as 'I32 (- (% (til 70000) 50) 20)) (% (* (til 70000) 7) 200)))"; + static const int enc[] = { RAY_ENC_FOR_BP, RAY_ENC_RLE, RAY_ENC_DICT }; + static const char* nm[] = { "lf", "lr", "ld" }; + static const char* nk[] = { "kf", "kr", "kd" }; + for (int i = 0; i < 3; i++) { + aw_save(nm[i], tbl, enc[i]); + uint64_t ran, dec; + ray_fused_topk_counters_reset(); + test_result_t r = aw_same(nm[i], "(select {x: x from: T where: (== x 7) desc: x take: 3})", 0); + if (r.status != TEST_PASS) return r; + ray_fused_topk_counters(&ran, &dec); + TEST_ASSERT_EQ_U(ran, 2); /* both generations take the fused top-k */ + /* the sort key is read by range (fpk_rk_t), never materialized: a + * vector with a passing row is decoded by the predicate and by the + * key's cursor, at most twice the column */ + TEST_ASSERT_TRUE(aw_col_decoded("x") <= 2 * 70000 * 4); + + aw_save(nk[i], tbk, enc[i]); + TEST_ASSERT_EQ_I(aw_vec_enc(nk[i], "x", 0), enc[i]); + ray_fused_topk_counters_reset(); + r = aw_same(nk[i], "(select {k: k from: T where: (== x 7) desc: k take: 3})", 0); + if (r.status != TEST_PASS) return r; + ray_fused_topk_counters(&ran, &dec); + TEST_ASSERT_EQ_U(ran, 2); + TEST_ASSERT_EQ_U(aw_col_decoded("x"), 0); /* the leaf reads x's views */ + ray_fused_topk_counters_reset(); + r = aw_same(nk[i], "(select {k: k from: T where: (> x 25) take: 5})", 0); /* the fused take (k: gathered by range, Task 6) */ + if (r.status != TEST_PASS) return r; + ray_fused_topk_counters(&ran, &dec); + TEST_ASSERT_EQ_U(ran, 2); + TEST_ASSERT_EQ_U(aw_col_decoded("x"), 0); + /* from the end: windows end at the table's last row, so they lie + * inside a vector (the leaf's whole-vector answer is cut) */ + ray_fused_topk_counters_reset(); + r = aw_same(nk[i], "(select {k: k from: T where: (> x 25) take: -1500})", 0); + if (r.status != TEST_PASS) return r; + ray_fused_topk_counters(&ran, &dec); + TEST_ASSERT_EQ_U(ran, 2); + TEST_ASSERT_EQ_U(aw_col_decoded("x"), 0); + } + PASS(); +} + +/* Every operator, both operand orders, constants below, inside and above + * the I16 range and the values, on a nullable I16 column under each + * encoding with a view (FOR_BP, RLE, DICT, CONST per vector): the leaf + * answers equal generation 0's and nothing decodes. */ +static uint16_t g_lop; static int64_t g_lc; static bool g_lsw; +static ray_op_t* ap_leaf_op(ray_graph_t* g) { + ray_op_t* x = ray_scan(g, "x"); ray_op_t* c = ray_const_i64(g, g_lc); + ray_op_t* a = g_lsw ? c : x; ray_op_t* b = g_lsw ? x : c; + switch (g_lop) { + case OP_EQ: return ray_eq(g, a, b); case OP_NE: return ray_ne(g, a, b); + case OP_LT: return ray_lt(g, a, b); case OP_LE: return ray_le(g, a, b); + case OP_GT: return ray_gt(g, a, b); default: return ray_ge(g, a, b); + } +} +static test_result_t test_filter_leaf_ops(void) { + const char* tbl = "(table [x] (list (as 'I16 (map (fn [j] (if (== 0 (% j 7)) 0N (- (% j 50) 20))) (til 9000)))))"; + const char* tbc = "(table [x] (list (as 'I16 (map (fn [j] (if (== 0 (% j 7)) 0N (- (div j 1024) 4))) (til 9000)))))"; + static const int enc[] = { RAY_ENC_FOR_BP, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_CONST }; + static const int64_t cs[] = { -100000, -32768, -21, -20, 3, 29, 30, 32767, 100000 }; + static const uint16_t ops[] = { OP_EQ, OP_NE, OP_LT, OP_LE, OP_GT, OP_GE }; + for (int e = 0; e < 4; e++) { + aw_save("lo", e == 3 ? tbc : tbl, enc[e]); + TEST_ASSERT_EQ_I(aw_vec_enc("lo", "x", 1), enc[e]); + for (int o = 0; o < 6; o++) + for (size_t ci = 0; ci < sizeof cs / sizeof cs[0]; ci++) + for (int sw = 0; sw < 2; sw++) { + g_lop = ops[o]; g_lc = cs[ci]; g_lsw = sw; + test_result_t r = aw_sel_same("lo", ap_leaf_op, 0); + if (r.status != TEST_PASS) { + fprintf(stderr, "enc %d op %u c %lld swapped %d\n", enc[e], ops[o], (long long)cs[ci], sw); + return r; + } + } + char rm[256]; + snprintf(rm, sizeof rm, "%s/lo0", aw_root()); (void)ray_test_rm_rf(rm); + snprintf(rm, sizeof rm, "%s/lo2", aw_root()); (void)ray_test_rm_rf(rm); + } + PASS(); +} + +/* ---- Task 4: SYM equality and membership on ids ---- */ + +static ray_op_t* ap_s_eq(ray_graph_t* g) { + ray_t* lit = ray_str("w7", 2); + ray_op_t* o = ray_eq(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* ap_s_ne_empty(ray_graph_t* g) { + ray_t* lit = ray_str("", 0); + ray_op_t* o = ray_ne(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* ap_s_eq_absent(ray_graph_t* g) { + ray_t* lit = ray_str("not-a-symbol", 12); + ray_op_t* o = ray_eq(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* ap_s_ne_absent(ray_graph_t* g) { + ray_t* lit = ray_str("not-a-symbol", 12); + ray_op_t* o = ray_ne(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* ap_s_eq_empty(ray_graph_t* g) { + ray_t* lit = ray_str("", 0); + ray_op_t* o = ray_eq(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* ap_s_lt(ray_graph_t* g) { + ray_t* lit = ray_str("w5", 2); + ray_op_t* o = ray_lt(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +/* the constant on the left, as a SYM atom (a runtime id, translated too) */ +static ray_op_t* ap_s_sym_left(ray_graph_t* g) { + ray_t* lit = ray_sym(ray_sym_intern("w2", 2)); + ray_op_t* o = ray_ne(g, ray_const_atom(g, lit), ray_scan(g, "s")); ray_release(lit); return o; +} +/* one constant node feeding two compares */ +static ray_op_t* ap_s_shared(ray_graph_t* g) { + ray_t* lit = ray_str("w5", 2); + ray_op_t* c = ray_const_atom(g, lit); ray_release(lit); + return ray_or(g, ray_eq(g, ray_scan(g, "s"), c), ray_and(g, ray_ne(g, ray_scan(g, "s"), c), + ray_ne(g, ray_scan(g, "s"), ray_const_str(g, "", 0)))); +} +static ray_t* aw_sym_set(const char* const* xs, int n) { + ray_t* set = ray_vec_new(RAY_SYM, n); set->len = n; + for (int i = 0; i < n; i++) ((int64_t*)ray_data(set))[i] = ray_sym_intern(xs[i], strlen(xs[i])); + return set; +} +static const char* const g_sin_w7[] = { "w7", "w1", "zz-absent" }; +static const char* const g_sin_empty[] = { "w7", "" }; +static const char* const g_sin_far[] = { "w13", "w15" }; +static ray_op_t* ap_s_in(ray_graph_t* g) { + ray_t* set = aw_sym_set(g_sin_w7, 3); + ray_op_t* o = ray_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* ap_s_notin(ray_graph_t* g) { + ray_t* set = aw_sym_set(g_sin_w7, 3); + ray_op_t* o = ray_not_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* ap_s_in_empty(ray_graph_t* g) { + ray_t* set = aw_sym_set(g_sin_empty, 2); + ray_op_t* o = ray_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* ap_s_notin_empty(ray_graph_t* g) { + ray_t* set = aw_sym_set(g_sin_empty, 2); + ray_op_t* o = ray_not_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +/* every member absent from the file domain: an empty probe, so no verdict + * LUT is built and the nullable column takes exec_in's null-checked loop + * (id-0 rows pass neither `in` nor `not in`) */ +static const char* const g_sin_none[] = { "zz-absent", "zz-absent2" }; +static ray_op_t* ap_s_notin_none(ray_graph_t* g) { + ray_t* set = aw_sym_set(g_sin_none, 2); + ray_op_t* o = ray_not_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* ap_s_notin_far(ray_graph_t* g) { + ray_t* set = aw_sym_set(g_sin_far, 2); + ray_op_t* o = ray_not_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} + +static const int64_t* g_iset; static int g_ineg; +static ray_op_t* ap_x_in(ray_graph_t* g) { + ray_t* set = ray_vec_new(RAY_I32, 3); set->len = 3; + for (int i = 0; i < 3; i++) ((int32_t*)ray_data(set))[i] = (int32_t)g_iset[i]; + ray_op_t* c = ray_const_vec(g, set); ray_release(set); + return g_ineg ? ray_not_in(g, ray_scan(g, "x"), c) : ray_in(g, ray_scan(g, "x"), c); +} + +/* The symbol index of row j of the "sy" fixture: -1 for "" (id 0). */ +static int aw_sy_val(int64_t j) { + if (j >= 65536 && j % 3 == 0) return -1; + return (int)(4 * (j / 65536) + j % 4); +} +/* Fused selection of : its pass count, the decoded bytes and + * materializations in *k; -1 when the fused path declines. */ +static int64_t aw_sel_count(const char* name, int gen, ray_op_t* (*build)(ray_graph_t*), ray_enc_counters_t* k) { + ray_t* t = aw_load(name, gen); + if (!t) return -2; + ray_graph_t* g = ray_graph_new(t); + ray_enc_counters_reset(); + bool all = false; + ray_t* s = exec_pred_to_selection(g, build(g), ray_table_nrows(t), &all); + if (k) ray_enc_counters_get(k); + int64_t n = s && !RAY_IS_ERR(s) ? ray_rowsel_meta(s)->total_pass : all ? ray_table_nrows(t) : -1; + if (s && RAY_IS_ERR(s)) { ray_error_free(s); n = -3; } + else if (s) ray_rowsel_release(s); + ray_graph_free(g); ray_release(t); + return n; +} +/* The count of rayfall `q` (table as T) on 0 through the unfused + * executor: the reference every fused answer is held to. */ +static int64_t aw_unfused_count(const char* name, const char* q) { + char buf[512]; + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s0/\"))", name); + aw_eval_ok(buf); + ray_expr_disable = true; + ray_t* r = ray_eval_str(ray_test_tmp(q)); + ray_expr_disable = false; + int64_t n = r && !RAY_IS_ERR(r) ? r->i64 : -1; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + return n; +} + +static test_result_t test_sym_membership(void) { + /* s clustered: each chunk holds 4 distinct symbols, empty strings (null) in chunks 1-3 */ + aw_save("sy", "(table [s] (list (as 'SYMBOL (map (fn [j] (if (and (>= j 65536) (== 0 (% j 3))) \"\" " + "(format \"w%\" (+ (* 4 (div j 65536)) (% j 4))))) (til 200000)))))", -1); + test_result_t r; + if ((r = aw_sel_same("sy", ap_s_eq, -1)).status != TEST_PASS) return r; + if ((r = aw_sel_same("sy", ap_s_ne_empty, -1)).status != TEST_PASS) return r; + if ((r = aw_sel_same("sy", ap_s_eq_absent, 0)).status != TEST_PASS) return r; + if ((r = aw_sel_same("sy", ap_s_ne_absent, 0)).status != TEST_PASS) return r; + /* "" (id 0): chunk 0 has no "" rows (== "" all-fail there, from the + * null count), chunks 1-3 have some (decided per vector by n_nulls or + * evaluated on ids) */ + if ((r = aw_sel_same("sy", ap_s_eq_empty, -1)).status != TEST_PASS) return r; + if ((r = aw_sel_same("sy", ap_s_sym_left, -1)).status != TEST_PASS) return r; + if ((r = aw_sel_same("sy", ap_s_shared, -1)).status != TEST_PASS) return r; + /* the answers by construction (raw-id semantics: "" == "" holds and + * "" != c holds for every other c) */ + int64_t n7 = 0, ne = 0, n2 = 0; + for (int64_t j = 0; j < 200000; j++) { + int v = aw_sy_val(j); + n7 += v == 7; ne += v < 0; n2 += v == 2; + } + /* the short last vector (rows 199680..199999, chunk 3, with "" rows) + * is RAW: no view, so a predicate its statistics leave open decodes + * exactly its 320 W8 ids; every other vector is answered on ids */ + TEST_ASSERT_EQ_I(aw_vec_enc("sy", "s", 195), RAY_ENC_RAW); + ray_enc_counters_t k; + for (int gen = 0; gen <= 2; gen += 2) { + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_eq, &k), n7); + if (gen) { TEST_ASSERT_EQ_U(k.decoded_bytes, 0); TEST_ASSERT_EQ_U(k.materialized, 0); } + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_ne_empty, &k), 200000 - ne); + if (gen) { TEST_ASSERT_EQ_U(k.decoded_bytes, 320); TEST_ASSERT_EQ_U(k.materialized, 0); } + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_eq_empty, &k), ne); + if (gen) TEST_ASSERT_EQ_U(k.decoded_bytes, 320); + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_eq_absent, NULL), 0); + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_ne_absent, NULL), 200000); + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_sym_left, NULL), 200000 - n2); + TEST_ASSERT_EQ_I(aw_sel_count("sy", gen, ap_s_shared, NULL), 200000 - ne); + } + /* the same answers through the unfused executor (generation 0) and + * through rayfall on both generations, STR and SYM literals */ + static const char* const qs[] = { + "(count (select {from: T where: (== s \"w7\")}))", + "(count (select {from: T where: (== s 'w7)}))", + "(count (select {from: T where: (!= s \"\")}))", + "(count (select {from: T where: (== s \"\")}))", + "(count (select {from: T where: (== s \"not-a-symbol\")}))", + "(count (select {from: T where: (!= s \"not-a-symbol\")}))", + "(count (select {from: T where: (!= s 'w2)}))", + "(count (select {from: T where: (or (== s 'w5) (== s 'w9))}))", + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + int64_t want = aw_unfused_count("sy", qs[i]); + TEST_ASSERT_FMT(want >= 0, "%s: unfused", qs[i]); + AW_SAME("sy", qs[i], 0); + ray_t* got = aw_eval(qs[i]); /* T: generation 2 (aw_same) */ + TEST_ASSERT_FMT(got && !RAY_IS_ERR(got) && got->i64 == want, "%s: %lld, unfused %lld", qs[i], + got && !RAY_IS_ERR(got) ? (long long)got->i64 : -1LL, (long long)want); + ray_release(got); + } + /* ordered compares on a file-domain SYM column keep + * EXPR_BAIL_SYM_DOMAIN (the fused program never orders ids). This pins + * only the bail and generation 0 == generation 2 == the unfused + * executor, which orders file-domain SYM by string (#738). */ + { + ray_t* t = aw_load("sy", 0); + ray_graph_t* g = ray_graph_new(t); + ray_expr_t ex; ray_t* cerr = NULL; + uint64_t before = ray_expr_bail_counts[EXPR_BAIL_SYM_DOMAIN]; + TEST_ASSERT_FALSE(expr_compile(g, t, ap_s_lt(g), &ex, &cerr)); + TEST_ASSERT_NULL(cerr); + TEST_ASSERT_EQ_U(ray_expr_bail_counts[EXPR_BAIL_SYM_DOMAIN], before + 1); + ray_graph_free(g); ray_release(t); + } + int64_t wlt = aw_unfused_count("sy", "(count (select {from: T where: (< s 'w5)}))"); + AW_SAME("sy", "(count (select {from: T where: (< s 'w5)}))", 1); + { + ray_t* got = aw_eval("(count (select {from: T where: (< s 'w5)}))"); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got)); + TEST_ASSERT_EQ_I(got->i64, wlt); + ray_release(got); + } + /* w7 lives only in chunk 1: chunks 0, 2 and 3 are decided from their id + * bounds without a decode, chunk 1's vectors are answered on ids */ + ray_t* t = aw_load("sy", 2); + ray_graph_t* g = ray_graph_new(t); + ray_enc_counters_reset(); + bool all = false; + ray_t* s = exec_pred_to_selection(g, ap_s_eq(g), ray_table_nrows(t), &all); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_rowsel_release(s); ray_graph_free(g); ray_release(t); + PASS(); +} + +/* The null SYM literal (', the SYM null "", id 0) against a generation-2 + * column with no index is decided on ids, as "" is: no materialization, + * equality and inequality as on generation 0, splayed and parted. + * Generation 0 keeps its fallback for it (the compile bails as before). */ +static ray_op_t* ap_s_eq_null(ray_graph_t* g) { + ray_t* lit = ray_sym(0); + ray_op_t* o = ray_eq(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* ap_s_ne_null(ray_graph_t* g) { + ray_t* lit = ray_sym(0); + ray_op_t* o = ray_ne(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static test_result_t test_sym_null_literal(void) { + aw_save("sn", "(table [s v] (list (as 'SYMBOL (map (fn [j] (if (and (>= j 65536) (== 0 (% j 3))) \"\" " + "(format \"w%\" (+ (* 4 (div j 65536)) (% j 4))))) (til 200000))) (til 200000)))", -1); + int64_t ne = 0, vs = 0; + for (int64_t j = 0; j < 200000; j++) if (aw_sy_val(j) < 0) { ne++; vs += j; } + static const char* const qs[] = { + "(count (select {from: T where: (== s ')}))", + "(count (select {from: T where: (!= s ')}))", + "(sum (at (select {from: T where: (== s ')}) 'v))", + "(count (select {from: T where: (and (== s ') (> v 100000))}))", + "(count (select {from: T where: (or (!= s ') (== v 3))}))", + NULL, + }; + for (int i = 0; qs[i]; i++) { + int64_t want = aw_unfused_count("sn", qs[i]); + TEST_ASSERT_FMT(want >= 0, "%s: unfused", qs[i]); + AW_SAME("sn", qs[i], 0); + ray_t* got = aw_eval(qs[i]); /* T: generation 2 (aw_same) */ + TEST_ASSERT_FMT(got && !RAY_IS_ERR(got) && got->i64 == want, "%s: %lld, unfused %lld", qs[i], + got && !RAY_IS_ERR(got) ? (long long)got->i64 : -1LL, (long long)want); + ray_release(got); + } + TEST_ASSERT_EQ_I(aw_unfused_count("sn", qs[0]), ne); /* null == null holds */ + TEST_ASSERT_EQ_I(aw_unfused_count("sn", qs[1]), 200000 - ne); + TEST_ASSERT_EQ_I(aw_unfused_count("sn", qs[2]), vs); + /* the fused selection on generation 2: on ids, nothing materialized */ + ray_enc_counters_t k; + TEST_ASSERT_EQ_I(aw_sel_count("sn", 2, ap_s_eq_null, &k), ne); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_I(aw_sel_count("sn", 2, ap_s_ne_null, &k), 200000 - ne); + TEST_ASSERT_EQ_U(k.materialized, 0); + /* generation 0 is unchanged: the compile still declines this constant */ + { + ray_t* t = aw_load("sn", 0); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + ray_expr_t ex; ray_t* cerr = NULL; + uint64_t before = ray_expr_bail_counts[EXPR_BAIL_SYM_DOMAIN]; + TEST_ASSERT_FALSE(expr_compile(g, t, ap_s_eq_null(g), &ex, &cerr)); + TEST_ASSERT_NULL(cerr); + TEST_ASSERT_EQ_U(ray_expr_bail_counts[EXPR_BAIL_SYM_DOMAIN], before + 1); + ray_graph_free(g); ray_release(t); + } + /* parted: two partitions over one symfile, "" rows in the second */ + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/pn%d/2024.01.0%d/t/\" " + "(table [s v] (list (as 'SYMBOL (map (fn [j] (if (and (== %d 1) (== 0 (%% j 5))) \"\" (format \"w%%\" (%% j 9)))) (til 70000))) " + "(til 70000))) \"" AW_TMP "/pn%d/.sym\" {compress: %s})", gen, p + 1, p, gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + static const char* const pq[] = { + "(count (select {from: (.db.parted.get \"" AW_TMP "/pn%d\" 't) where: (== s ')}))", + "(count (select {from: (.db.parted.get \"" AW_TMP "/pn%d\" 't) where: (!= s ')}))", + "(sum (at (select {from: (.db.parted.get \"" AW_TMP "/pn%d\" 't) where: (== s ')}) 'v))", + NULL, + }; + for (int i = 0; pq[i]; i++) { + char q0[400], q2[400]; + snprintf(q0, sizeof q0, pq[i], 0); snprintf(q2, sizeof q2, pq[i], 2); + ray_t* a = aw_eval(q0); + ray_enc_counters_reset(); + ray_t* b = aw_eval(q2); + ray_enc_counters_get(&k); + TEST_ASSERT_FMT(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && a->i64 == b->i64, "%s: %lld vs %lld", pq[i], + a && !RAY_IS_ERR(a) ? (long long)a->i64 : -1LL, b && !RAY_IS_ERR(b) ? (long long)b->i64 : -1LL); + TEST_ASSERT_FMT(k.materialized == 0, "%s: %llu materializations", pq[i], (unsigned long long)k.materialized); + if (i == 0) TEST_ASSERT_EQ_I(a->i64, 14000); + ray_release(a); ray_release(b); + } + PASS(); +} + +/* `in` / `not in` by membership bounds: a set none of whose ids lies in a + * chunk's or vector's [min, max] decides it without a read (`not in` only + * without "" rows); the rest is answered on the views' ids. Generation 0 + * (the unchanged in-place kernel) is the reference. */ +static test_result_t test_sym_in_bounds(void) { + aw_save("sb", "(table [s] (list (as 'SYMBOL (map (fn [j] (if (and (>= j 65536) (== 0 (% j 3))) \"\" " + "(format \"w%\" (+ (* 4 (div j 65536)) (% j 4))))) (til 200000)))))", -1); + test_result_t r; + /* decoded bytes: only the RAW tail vector (320 W8 ids, with "" rows) + * when its chunk's bounds leave it open. `in` decides chunk 3 from its + * ids (a "" member of a SYM set is a null element, dropped from the + * probe as exec_in does, so it matches no row); the `not in` shapes + * cannot (chunk 3 holds "" rows) */ + ray_op_t* (*const shapes[])(ray_graph_t*) = { ap_s_in, ap_s_notin, ap_s_in_empty, ap_s_notin_empty, ap_s_notin_far }; + static const int64_t dec[] = { 0, 320, 0, 320, 320 }; + for (size_t i = 0; i < sizeof shapes / sizeof shapes[0]; i++) + if ((r = aw_sel_same("sb", shapes[i], dec[i])).status != TEST_PASS) { fprintf(stderr, "shape %zu\n", i); return r; } + int64_t nin = 0; + for (int64_t j = 0; j < 200000; j++) { int v = aw_sy_val(j); nin += v == 7 || v == 1; } + TEST_ASSERT_EQ_I(aw_sel_count("sb", 2, ap_s_in, NULL), nin); + /* without a LUT the null-checked loop answers id-0 rows 0 under + * `not in`, as the LUT does (#739); the views clear their id-0 rows + * the same way, so only the RAW tail vector is decoded; chunk 0, + * without "", is decided from its statistics */ + if ((r = aw_sel_same("sb", ap_s_notin_none, 320)).status != TEST_PASS) return r; + { + int64_t want = 0; + for (int64_t j = 0; j < 200000; j++) want += aw_sy_val(j) >= 0; + TEST_ASSERT_EQ_I(aw_sel_count("sb", 2, ap_s_notin_none, NULL), want); + } + /* integers: a nullable I32 column, sets inside and outside the bounds */ + aw_save("ib", "(table [x] (list (as 'I32 (map (fn [j] (if (and (>= j 65536) (== 0 (% j 7))) 0N (+ (div j 1000) (% j 3)))) (til 140000)))))", -1); + static const int64_t sets[][3] = { { 5, 70, 9000 }, { -4, 1000, 2000 }, { 66, 67, 68 } }; + for (int si = 0; si < 3; si++) + for (int neg = 0; neg < 2; neg++) { + g_iset = sets[si]; g_ineg = neg; + if ((r = aw_sel_same("ib", ap_x_in, 0)).status != TEST_PASS) { + fprintf(stderr, "set %d negate %d\n", si, neg); + return r; + } + } + PASS(); +} + +/* Float membership bounds: the probe as doubles (NaN members match + * nothing, -0.0 equals +0.0), no view evaluator (a float vector is read). + * f: -0.0 in vector 0, null every 13th row in chunk 1, else the row; g the + * same as F32; x an I32 column against a float set (the widened integer + * bounds). Generation 0 (the unchanged kernel) is the reference. */ +static const double* g_fset; static int g_fnset; static int g_fneg; static const char* g_fcol; +static ray_op_t* ap_f_in(ray_graph_t* g) { + ray_t* set = ray_vec_new(RAY_F64, g_fnset); set->len = g_fnset; + for (int i = 0; i < g_fnset; i++) ((double*)ray_data(set))[i] = g_fset[i]; + ray_op_t* c = ray_const_vec(g, set); ray_release(set); + return g_fneg ? ray_not_in(g, ray_scan(g, g_fcol), c) : ray_in(g, ray_scan(g, g_fcol), c); +} +static test_result_t test_float_in_bounds(void) { + aw_save("fb", "(select {f: f g: (as 'F32 f) x: x from: (table [f x] (list " + "(as 'F64 (map (fn [j] (if (< j 1024) -0.0 (if (and (>= j 65536) (< j 131072) (== 0 (% j 13))) 0Nf (as 'F64 j)))) (til 140000))) " + "(as 'I32 (div (til 140000) 1000))))})", -1); + static const double s_zero[] = { 0.0, 1e9, NAN }; /* +0.0 matches vector 0's -0.0 */ + static const double s_12[] = { 12.0 }; /* row 12 is -0.0: matches nothing */ + static const double s_x[] = { 5.0, 70.5, 139.0 }; + static const char* const cols[] = { "f", "g" }; + test_result_t r; + for (int ci = 0; ci < 2; ci++) { + g_fcol = cols[ci]; + const size_t esz = ci == 0 ? 8 : 4; + /* `in` +0.0: only vector 0 (bounds [-0.0, -0.0] hold +0.0) is read */ + g_fset = s_zero; g_fnset = 3; g_fneg = 0; + if ((r = aw_sel_same("fb", ap_f_in, (int64_t)(1024 * esz))).status != TEST_PASS) return r; + TEST_ASSERT_EQ_I(aw_sel_count("fb", 2, ap_f_in, NULL), 1024); + /* `not in` +0.0: vector 0 read; chunk 1's vectors all hold a null + * (every 13th row), so they are read; the rest decided */ + g_fneg = 1; + if ((r = aw_sel_same("fb", ap_f_in, (int64_t)((1024 + 64 * 1024) * esz))).status != TEST_PASS) return r; + /* 12.0: no range holds it; `in` reads nothing, `not in` only the + * null-bearing chunk 1 */ + g_fset = s_12; g_fnset = 1; g_fneg = 0; + if ((r = aw_sel_same("fb", ap_f_in, 0)).status != TEST_PASS) return r; + TEST_ASSERT_EQ_I(aw_sel_count("fb", 2, ap_f_in, NULL), 0); + g_fneg = 1; + if ((r = aw_sel_same("fb", ap_f_in, (int64_t)(64 * 1024 * esz))).status != TEST_PASS) return r; + } + /* an integer column against a float set */ + g_fcol = "x"; g_fset = s_x; g_fnset = 3; + for (g_fneg = 0; g_fneg < 2; g_fneg++) + if ((r = aw_sel_same("fb", ap_f_in, -1)).status != TEST_PASS) return r; + PASS(); +} + +/* The same shapes route through the fused path on generation 0 now. */ +static test_result_t test_sym_fused_gen0(void) { + aw_save("sz", "(table [s] (list (as 'SYMBOL (map (fn [j] (format \"w%\" (% j 5))) (til 10000)))))", -1); + ray_t* t = aw_load("sz", 0); + ray_graph_t* g = ray_graph_new(t); + ray_expr_t ex; + ray_t* cerr = NULL; + TEST_ASSERT_TRUE(expr_compile(g, t, ap_s_eq(g), &ex, &cerr)); /* no EXPR_BAIL_SYM_DOMAIN */ + TEST_ASSERT_NULL(cerr); + ray_graph_free(g); ray_release(t); + PASS(); +} + +/* ---- Task 5: gathers under the output contract ---- */ + +/* Review focus 4: non-monotone, repeated ids across vectors and two + * partitions; pooled STR in two vectors whose scratch is reused; the result + * outlives the sources and every scratch. */ +static test_result_t test_gather_rows_contract(void) { + for (int p = 0; p < 2; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/gp/2024.01.0%d/t/\" " + "(table [s y v] (list (map (fn [j] (format \"a long pooled string number %%\" (+ j %d))) (til 3000)) " + "(as 'SYMBOL (map (fn [j] (format \"y%%\" (%% j %d))) (til 3000))) (+ %d (til 3000)))) " + "\"" AW_TMP "/gp/.sym\" {compress: %s})", p + 1, p * 3000, p ? 400 : 30, p * 3000, + p ? "false" : "true"); /* partition 0 generation 2, partition 1 generation 0 */ + aw_eval_ok(q); + } + ray_t* t = aw_eval("(.db.parted.get \"" AW_TMP "/gp\" 't)"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + static const int64_t ids[] = { 5000, 3, 1030, 3, 2999, 3000, 1030, 5999, 0, 4100 }; + const int64_t n = 10; + ray_t* res[3] = { NULL, NULL, NULL }; + static const char* cols[] = { "s", "y", "v" }; + ray_enc_counters_reset(); + for (int c = 0; c < 3; c++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern(cols[c], 1), &s)); + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, n, &res[c])); + ray_col_src_release(&s); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + /* v's generation-2 segment: ids 0, 3 (vector 0), 1030 (vector 1), 2999 + * (vector 2: 952 rows), each vector read once despite repeats and order. + * Its vectors are DELTA_BP, which a point read declines (Task 6b), so + * the few ids of each still decode it (gather_points pins the served + * encodings) */ + ray_t* venc = ray_table_get_col_enc(t, ray_sym_intern("v", 1)); + TEST_ASSERT_NOT_NULL(venc); + ray_t* vseg0 = ray_enccol_seg(venc, 0); + TEST_ASSERT_TRUE(vseg0 && vseg0->type == RAY_ENCCOL); + const ray_enc_desc_t* vd = ray_enccol_descs(ray_enccol_of(vseg0), 0); + for (int j = 0; j < 3; j++) TEST_ASSERT_EQ_I(vd[j].encoding, RAY_ENC_DELTA_BP); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(vseg0)->decoded_bytes), (1024 + 1024 + 952) * 8); + ray_release(t); /* sources gone: results must stand alone */ + for (int64_t i = 0; i < n; i++) { + char want[64]; + int wl = snprintf(want, sizeof want, "a long pooled string number %lld", (long long)ids[i]); + size_t len = 0; const char* got = ray_str_vec_get(res[0], i, &len); + TEST_ASSERT_FMT(len == (size_t)wl && memcmp(got, want, len) == 0, "s[%lld]", (long long)i); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(res[2]))[i], ids[i]); + int64_t yid = ray_read_sym(ray_data(res[1]), i, RAY_SYM, res[1]->attrs); + ray_t* ys = ray_sym_domain_str(ray_sym_vec_domain(res[1]), yid); + int64_t local = ids[i] < 3000 ? ids[i] % 30 : (ids[i] - 3000) % 400; + int yl = snprintf(want, sizeof want, "y%lld", (long long)local); + TEST_ASSERT_TRUE(ys && ray_str_len(ys) == (size_t)yl && memcmp(ray_str_ptr(ys), want, (size_t)yl) == 0); + } + TEST_ASSERT_EQ_I(res[1]->attrs & RAY_SYM_W_MASK, RAY_SYM_W16); /* widened for the 400-symbol segment */ + for (int c = 0; c < 3; c++) ray_release(res[c]); + PASS(); +} + +/* Rowsel compaction over the mixed parted table: rows 3, 1030, 2999, 3000 + * and 4100; rowsel segment 2 spans the partition boundary, yet each local + * vector is read once; results checked after the source is released. */ +static test_result_t test_gather_sel_parted(void) { + for (int p = 0; p < 2; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/gq/2024.01.0%d/t/\" " + "(table [s v] (list (map (fn [j] (format \"a long pooled string number %%\" (+ j %d))) (til 3000)) " + "(+ %d (til 3000)))) \"" AW_TMP "/gq/.sym\" {compress: %s})", p + 1, p * 3000, p * 3000, p ? "false" : "true"); + aw_eval_ok(q); + } + ray_t* t = aw_eval("(.db.parted.get \"" AW_TMP "/gq\" 't)"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* pred = ray_vec_new(RAY_BOOL, 6000); pred->len = 6000; + memset(ray_data(pred), 0, 6000); + static const int64_t rows[] = { 3, 1030, 2999, 3000, 4100 }; + for (int i = 0; i < 5; i++) ((uint8_t*)ray_data(pred))[rows[i]] = 1; + ray_t* sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + ray_t* res[2] = { NULL, NULL }; + static const char* cols[] = { "s", "v" }; + for (int c = 0; c < 2; c++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern(cols[c], 1), &s)); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &res[c])); + ray_col_src_release(&s); + } + /* DELTA_BP vectors (as in gather_rows_contract): declined point reads, + * each touched vector decoded once */ + ray_t* venc = ray_table_get_col_enc(t, ray_sym_intern("v", 1)); + const ray_enc_desc_t* vd = ray_enccol_descs(ray_enccol_of(ray_enccol_seg(venc, 0)), 0); + for (int j = 0; j < 3; j++) TEST_ASSERT_EQ_I(vd[j].encoding, RAY_ENC_DELTA_BP); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(ray_enccol_seg(venc, 0))->decoded_bytes), (1024 + 1024 + 952) * 8); + ray_release(t); ray_rowsel_release(sel); ray_release(pred); + for (int i = 0; i < 5; i++) { + char want[64]; + int wl = snprintf(want, sizeof want, "a long pooled string number %lld", (long long)rows[i]); + size_t len = 0; const char* got = ray_str_vec_get(res[0], i, &len); + TEST_ASSERT_TRUE(len == (size_t)wl && memcmp(got, want, len) == 0); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(res[1]))[i], rows[i]); + } + ray_release(res[0]); ray_release(res[1]); + PASS(); +} + +static test_result_t test_gather_sel_skips_none(void) { + aw_save("gs", "(table [x] (list (til 70000)))", RAY_ENC_FOR_BP); + ray_t* t = aw_load("gs", 2); + ray_graph_t* g = ray_graph_new(t); + bool all = false; + ray_t* sel = exec_pred_to_selection(g, ray_lt(g, ray_scan(g, "x"), ray_const_i64(g, 1500)), 70000, &all); + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("x", 1), &s)); + ray_enc_counters_reset(); + ray_t* out = NULL; + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &out)); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_I(out->len, 1500); + TEST_ASSERT_EQ_U(k.decoded_bytes, 2 * 1024 * 8); /* only vectors 0 and 1 are touched */ + for (int64_t i = 0; i < 1500; i++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[i], i); + ray_release(out); ray_col_src_release(&s); ray_rowsel_release(sel); ray_graph_free(g); ray_release(t); + PASS(); +} + +/* The generation-0 answer, bit for bit: every type's gather from the + * generation-2 copy equals the same gather from the generation-0 copy + * (data bytes, HAS_NULLS, STR pool bytes, SYM width and domain), for a + * row list and a rowsel, nulls (canonical sentinels) included. */ +static test_result_t aw_vec_same(ray_t* a, ray_t* b, const char* what) { + TEST_ASSERT_FMT(a->type == b->type && a->len == b->len && a->attrs == b->attrs, + "%s: type %d/%d len %lld/%lld attrs %x/%x", what, a->type, b->type, + (long long)a->len, (long long)b->len, a->attrs, b->attrs); + size_t esz = ray_sym_elem_size(a->type, a->attrs); + if (a->type != RAY_SYM) + TEST_ASSERT_FMT(memcmp(ray_data(a), ray_data(b), (size_t)a->len * esz) == 0, "%s: data", what); + if (a->type == RAY_STR) { + TEST_ASSERT_FMT(!a->str_pool == !b->str_pool, "%s: pool presence", what); + if (a->str_pool) + TEST_ASSERT_FMT(a->str_pool->len == b->str_pool->len && + memcmp(ray_data(a->str_pool), ray_data(b->str_pool), (size_t)a->str_pool->len) == 0, + "%s: pool", what); + } + for (int64_t i = 0; a->type == RAY_SYM && i < a->len; i++) { /* each copy has its own symfile */ + ray_t* sa = ray_sym_domain_str(ray_sym_vec_domain(a), ray_read_sym(ray_data(a), i, RAY_SYM, a->attrs)); + ray_t* sb = ray_sym_domain_str(ray_sym_vec_domain(b), ray_read_sym(ray_data(b), i, RAY_SYM, b->attrs)); + TEST_ASSERT_FMT(sa && sb && ray_str_len(sa) == ray_str_len(sb) && + memcmp(ray_str_ptr(sa), ray_str_ptr(sb), ray_str_len(sa)) == 0, "%s[%lld]: symbol", what, (long long)i); + } + PASS(); +} +/* A gather result against its generation-0 reference (`at`): type, length, + * HAS_NULLS, SYM width, values (STR by bytes; SYM by raw id and domain when + * both resolve over one symfile, else by symbol). */ +static test_result_t aw_gather_ref(ray_t* got, ray_t* ref, bool one_symfile, const char* what) { + /* a parted SYM `at` widens to W64; the contract's width is the widest + * segment's (parted_sym_width), pinned by gather_rows_contract */ + uint8_t wm = (ref->type == RAY_SYM && (ref->attrs & RAY_SYM_W_MASK) == RAY_SYM_W64) ? 0 : RAY_SYM_W_MASK; + TEST_ASSERT_FMT(got->len == ref->len && got->type == ref->type && + (got->attrs & (RAY_ATTR_HAS_NULLS | wm)) == (ref->attrs & (RAY_ATTR_HAS_NULLS | wm)), + "%s: type %d/%d len %lld/%lld attrs %x/%x", what, got->type, ref->type, + (long long)got->len, (long long)ref->len, got->attrs, ref->attrs); + for (int64_t i = 0; i < ref->len; i++) { + if (ref->type == RAY_STR) { + size_t la = 0, lb = 0; + const char* pa = ray_str_vec_get(got, i, &la); + const char* pb = ray_str_vec_get(ref, i, &lb); + TEST_ASSERT_FMT(la == lb && (la == 0 || memcmp(pa, pb, la) == 0), "%s[%lld]", what, (long long)i); + } else if (ref->type == RAY_SYM && !one_symfile) { + ray_t* sa = ray_sym_domain_str(ray_sym_vec_domain(got), ray_read_sym(ray_data(got), i, RAY_SYM, got->attrs)); + ray_t* sb = ray_sym_domain_str(ray_sym_vec_domain(ref), ray_read_sym(ray_data(ref), i, RAY_SYM, ref->attrs)); + TEST_ASSERT_FMT(sa && sb && ray_str_len(sa) == ray_str_len(sb) && + memcmp(ray_str_ptr(sa), ray_str_ptr(sb), ray_str_len(sa)) == 0, "%s[%lld]: symbol", what, (long long)i); + } else { + size_t esz = ray_sym_elem_size(ref->type, ref->attrs); + TEST_ASSERT_FMT(memcmp((char*)ray_data(got) + i * esz, (char*)ray_data(ref) + i * esz, esz) == 0, + "%s[%lld]", what, (long long)i); + } + } + if (ref->type == RAY_SYM && one_symfile) TEST_ASSERT_TRUE(ray_sym_vec_domain(got) == ray_sym_vec_domain(ref)); + PASS(); +} +#define AW_GATHER_REF(g, r, one, w) do { test_result_t r_ = aw_gather_ref((g), (r), (one), (w)); if (r_.status != TEST_PASS) return r_; } while (0) + +static test_result_t test_gather_gen0_parity(void) { + /* (as 'F32 ...) evaluates only on a select's compiled path (I16 / F32 + * casts); TIMESTAMP and GUID columns are built outside it */ + aw_save("gz", "(select {i: i f: f s: s y: y d: d h: (as 'I16 i) g: (as 'F32 f) ts: ts from: " + "(table [i f s y d ts] (list " + "(map (fn [j] (if (== 0 (% j 7)) 0Nl (* j 3))) (til 5000)) " + "(map (fn [j] (if (== 0 (% j 11)) 0Nf (* j 0.5))) (til 5000)) " + "(map (fn [j] (if (== 0 (% j 5)) \"\" (if (== 0 (% j 2)) \"short\" (format \"a pooled string of row %\" j)))) (til 5000)) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (% j 13)) \"\" (format \"k%\" (% j 300)))) (til 5000))) " + "(as 'DATE (til 5000)) " + "(as 'TIMESTAMP (map (fn [j] (if (== 0 (% j 9)) 0Nl (* j 1000))) (til 5000)))))})", -1); + aw_save("gu", "(table [u] (list (take (as 'GUID (list \"00000000-0000-0000-0000-000000000001\" " + "\"00000000-0000-0000-0000-0000000000a2\" \"\" \"10000000-0000-0000-0000-000000000003\")) 5000)))", -1); + for (int tb = 0; tb < 2; tb++) { + const char* tn = tb ? "gu" : "gz"; + ray_t* t0 = aw_load(tn, 0); ray_t* t2 = aw_load(tn, 2); + TEST_ASSERT_TRUE(t0 && t2); + static const int64_t ids[] = { 4999, 0, 7, 2048, 7, 13, 1100, 3, 4096, 2047, 35, 0 }; + ray_t* pred = ray_vec_new(RAY_BOOL, 5000); pred->len = 5000; + for (int64_t r = 0; r < 5000; r++) ((uint8_t*)ray_data(pred))[r] = (r < 1024) || (r % 3 == 0 && r > 3000); + ray_t* sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + static const char* cols[2][8] = { { "i", "f", "s", "y", "d", "h", "g", "ts" }, { "u" } }; + for (int c = 0; c < (tb ? 1 : 8); c++) { + const char* cn = cols[tb][c]; + ray_t* out[2][2]; + int64_t nm = ray_sym_intern(cn, strlen(cn)); + for (int gen = 0; gen < 2; gen++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(gen ? t2 : t0, nm, &s)); + TEST_ASSERT_FMT(s.type == ray_table_get_col(t0, nm)->type, "%s", cn); + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, 12, &out[gen][0])); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &out[gen][1])); + ray_col_src_release(&s); + } + /* the reference: today's generation-0 index gather, `at` */ + char q[512]; + for (int w = 0; w < 2; w++) { + snprintf(q, sizeof q, "(at (at (.db.splayed.get \"" AW_TMP "/%s0/\") '%s) %s)", tn, cn, + w ? "(where (or (< (til 5000) 1024) (and (> (til 5000) 3000) (== 0 (% (til 5000) 3)))))" + : "[4999 0 7 2048 7 13 1100 3 4096 2047 35 0]"); + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + AW_GATHER_REF(out[0][w], ref, true, cn); + AW_GATHER_REF(out[1][w], ref, false, cn); /* 2 has its own symfile */ + ray_release(ref); + test_result_t r = aw_vec_same(out[0][w], out[1][w], cn); + if (r.status != TEST_PASS) return r; + ray_release(out[0][w]); ray_release(out[1][w]); + } + } + ray_rowsel_release(sel); ray_release(pred); + if (tb) { ray_release(t0); ray_release(t2); continue; } + ray_t* e = NULL; + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("i", 1), &s)); + static const int64_t bad[] = { 1, 5000 }; + ray_t* err = ray_col_gather_rows(&s, bad, 2, &e); + TEST_ASSERT_TRUE(err && RAY_IS_ERR(err) && e == NULL); + TEST_ASSERT_STR_EQ(ray_err_code(err), "range"); + ray_error_free(err); ray_col_src_release(&s); + ray_release(t0); ray_release(t2); + } + PASS(); +} + +/* Important 1 (review): the in-order row list. Sorted ids with repeats and + * runs crossing a vector boundary (1023..1025) and a partition boundary + * (2999..3001), both partitions generation 2, against generation 0's `at` + * over an all-generation-0 copy; each touched vector decoded once. */ +static test_result_t test_gather_rows_sorted(void) { + for (int gen = 0; gen < 3; gen += 2) + for (int p = 0; p < 2; p++) { + char q[700]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/gr%d/2024.01.0%d/t/\" " + "(table [s v y] (list (map (fn [j] (format \"a long pooled string number %%\" (+ j %d))) (til 3000)) " + "(+ %d (til 3000)) (as 'SYMBOL (map (fn [j] (format \"y%%\" (%% j %d))) (til 3000))))) " + "\"" AW_TMP "/gr%d/.sym\" {compress: %s})", gen, p + 1, p * 3000, p * 3000, p ? 400 : 30, + gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + ray_t* t = aw_eval("(.db.parted.get \"" AW_TMP "/gr2\" 't)"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + static const int64_t ids[] = { 0, 1, 2, 2, 1023, 1024, 1025, 2999, 3000, 3001, 3001, 5999 }; + static const char* cols[] = { "s", "v", "y" }; + ray_enc_counters_reset(); + for (int c = 0; c < 3; c++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern(cols[c], 1), &s)); + ray_t* got = NULL; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, 12, &got)); + ray_col_src_release(&s); + char q[300]; + snprintf(q, sizeof q, "(at (at (.db.parted.get \"" AW_TMP "/gr0\" 't) '%s) [0 1 2 2 1023 1024 1025 2999 3000 3001 3001 5999])", cols[c]); + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + AW_GATHER_REF(got, ref, false, cols[c]); + ray_release(ref); ray_release(got); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + /* v: partition 1 vectors 0, 1, 2 (952 rows); partition 2 vectors 0, 2 */ + ray_t* venc = ray_table_get_col_enc(t, ray_sym_intern("v", 1)); + TEST_ASSERT_NOT_NULL(venc); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(ray_enccol_seg(venc, 0))->decoded_bytes), (1024 + 1024 + 952) * 8); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(ray_enccol_seg(venc, 1))->decoded_bytes), (1024 + 952) * 8); + /* Task 6 fix round 2: sorted ids whose repeats balance a gap ({0,0,2}: + * its endpoints span two steps as a run would), all repeats, and a + * repeat inside a run are value lists, never one copy */ + static const struct { int64_t ids[6]; int n; const char* lit; } rs[] = { + { { 0, 0, 2 }, 3, "[0 0 2]" }, + { { 1, 1, 1 }, 3, "[1 1 1]" }, + { { 3, 4, 4, 5, 7 }, 5, "[3 4 4 5 7]" }, + { { 3000, 3000, 3002 }, 3, "[3000 3000 3002]" }, + }; + for (size_t i = 0; i < sizeof rs / sizeof rs[0]; i++) + for (int c = 0; c < 3; c++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern(cols[c], 1), &s)); + ray_t* got = NULL; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, rs[i].ids, rs[i].n, &got)); + ray_col_src_release(&s); + char q[300]; + snprintf(q, sizeof q, "(at (at (.db.parted.get \"" AW_TMP "/gr0\" 't) '%s) %s)", cols[c], rs[i].lit); + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + AW_GATHER_REF(got, ref, false, rs[i].lit); + ray_release(ref); ray_release(got); + } + ray_release(t); + PASS(); +} + +/* Minor 5 (review): empty requests and all-null columns. n = 0 and an + * empty selection read nothing and give empty vectors; an all-empty STR + * column (no pool) and an all-"" SYM column (a CONST-0 vector) give + * generation 0's nulls and HAS_NULLS. A rowsel whose segments hold more + * rows than its total_pass is `corrupt` before any row past it is written. */ +static test_result_t test_gather_empty_and_nulls(void) { + aw_save("ge", "(table [e y v] (list (map (fn [j] \"\") (til 3000)) (as 'SYMBOL (map (fn [j] \"\") (til 3000))) (til 3000)))", -1); + TEST_ASSERT_EQ_I(aw_vec_enc("ge", "y", 1), RAY_ENC_CONST); + ray_t* t0 = aw_load("ge", 0); ray_t* t2 = aw_load("ge", 2); + TEST_ASSERT_TRUE(t0 && t2); + ray_t* pred = ray_vec_new(RAY_BOOL, 3000); pred->len = 3000; + memset(ray_data(pred), 0, 3000); + ray_t* none = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(none); + for (int64_t r = 0; r < 3000; r++) ((uint8_t*)ray_data(pred))[r] = r % 4 == 1; + ray_t* sel = ray_rowsel_from_pred(pred); + static const int64_t ids[] = { 2999, 5, 1500, 5 }; + static const char* cols[] = { "e", "y", "v" }; + for (int c = 0; c < 3; c++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern(cols[c], 1), &s)); + ray_enc_counters_reset(); + ray_t* a = NULL; ray_t* b = NULL; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, 0, &a)); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, none, &b)); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + for (int w = 0; w < 2; w++) { + ray_t* o = w ? b : a; + TEST_ASSERT_FMT(o->len == 0 && o->type == s.type && !(o->attrs & RAY_ATTR_HAS_NULLS) && + (o->type != RAY_STR || !o->str_pool), + "%s %d: len %lld type %d/%d attrs %x pool %p", cols[c], w, (long long)o->len, o->type, s.type, + o->attrs, (void*)o->str_pool); + ray_release(o); + } + if (c < 2) { /* all null */ + ray_t* g[2] = { NULL, NULL }; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, 4, &g[0])); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &g[1])); + for (int w = 0; w < 2; w++) { + char q[300]; + snprintf(q, sizeof q, "(at (at (.db.splayed.get \"" AW_TMP "/ge0/\") '%s) %s)", cols[c], + w ? "(where (== 1 (% (til 3000) 4)))" : "[2999 5 1500 5]"); + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + AW_GATHER_REF(g[w], ref, false, cols[c]); + TEST_ASSERT_TRUE((g[w]->attrs & RAY_ATTR_HAS_NULLS) && (g[w]->type != RAY_STR || !g[w]->str_pool)); + ray_release(ref); ray_release(g[w]); + } + } + if (c == 2) { /* Minor 2: a rowsel holding more rows than it says */ + int64_t tp = ray_rowsel_meta(sel)->total_pass; + ray_rowsel_meta(sel)->total_pass = 1; /* a one-row output, 750 rows in the segments */ + ray_t* o = NULL; + ray_t* err = ray_col_gather_sel(&s, sel, &o); + ray_rowsel_meta(sel)->total_pass = tp; + TEST_ASSERT_TRUE(err && RAY_IS_ERR(err) && o == NULL); + TEST_ASSERT_STR_EQ(ray_err_code(err), "corrupt"); + /* refused by the per-segment bound, before the write (the end + * check alone would report it after writing past the output) */ + TEST_ASSERT_FMT(strstr(ray_error_msg(), "more rows than") != NULL, "%s", ray_error_msg()); + ray_error_free(err); + } + ray_col_src_release(&s); + } + ray_rowsel_release(none); ray_rowsel_release(sel); ray_release(pred); ray_release(t0); ray_release(t2); + PASS(); +} + +/* Minor 5 (review): a ragged parted source. Partition 2 lacks w, so the + * load gives it a synthetic all-null segment; the gather across both + * equals generation 0's `at` over an explicit-null copy. */ +static test_result_t test_gather_ragged(void) { + static const char* roots[] = { "gw", "gn" }; + for (int r = 0; r < 2; r++) + for (int p = 0; p < 2; p++) { + char q[600]; + const char* tbl = p == 0 ? "(table [x w] (list (til 3000) (* 2 (til 3000))))" + : r == 0 ? "(table [x] (list (til 3000)))" + : "(table [x w] (list (til 3000) (take [0Nl] 3000)))"; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s/2024.01.0%d/t/\" %s {compress: %s})", + roots[r], p + 1, tbl, r == 0 ? "true" : "false"); + aw_eval_ok(q); + } + ray_t* t = aw_eval("(.db.parted.get \"" AW_TMP "/gw\" 't)"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + static const int64_t ids[] = { 5999, 1, 3000, 2999, 4500, 1 }; + ray_t* pred = ray_vec_new(RAY_BOOL, 6000); pred->len = 6000; + for (int64_t r = 0; r < 6000; r++) ((uint8_t*)ray_data(pred))[r] = r % 5 == 0 || (r > 2000 && r < 4100); + ray_t* sel = ray_rowsel_from_pred(pred); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("w", 1), &s)); + ray_t* g[2] = { NULL, NULL }; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, 6, &g[0])); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &g[1])); + ray_col_src_release(&s); + ray_release(t); + for (int w = 0; w < 2; w++) { + ray_t* ref = aw_eval(w ? "(at (at (.db.parted.get \"" AW_TMP "/gn\" 't) 'w) " + "(where (or (== 0 (% (til 6000) 5)) (and (> (til 6000) 2000) (< (til 6000) 4100)))))" + : "(at (at (.db.parted.get \"" AW_TMP "/gn\" 't) 'w) [5999 1 3000 2999 4500 1])"); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "ragged ref %d: %s", w, ray_error_msg()); + AW_GATHER_REF(g[w], ref, true, "w"); + TEST_ASSERT_TRUE(g[w]->attrs & RAY_ATTR_HAS_NULLS); + ray_release(ref); ray_release(g[w]); + } + ray_rowsel_release(sel); ray_release(pred); + PASS(); +} + +/* ---- Task 6: gathers in the operators ---------------------------------- */ + +/* aw_same / AW_SAME: Task 1. */ +static const char* AW_WIDE = + "(table [k g v s t] (list (til 200000) (as 'I16 (% (til 200000) 7)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 10)) 0N j)) (til 200000))) " + "(take ['a 'b 'c] 200000) (map (fn [j] (format \"text value %\" (% j 333))) (til 200000))))"; + +/* q's answer as .csv.write bytes of table expression q over T (malloc'd; + * NULL on a failure). */ +static char* aw_csv(const char* q, const char* tag, size_t* len) { + char path[600], e[2048]; + snprintf(path, sizeof path, "%s/%s.csv", aw_root(), tag); + snprintf(e, sizeof e, "(.csv.write %s \"%s\")", q, path); + ray_t* r = ray_eval_str(e); + if (!r || RAY_IS_ERR(r)) { if (r) ray_error_free(r); return NULL; } + ray_release(r); + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET); + char* b = malloc((size_t)n + 1); + if (b && fread(b, 1, (size_t)n, f) != (size_t)n) { free(b); b = NULL; } + fclose(f); + *len = (size_t)n; + return b; +} + +/* Result tables a (generation 0) and b (generation 2) of `what`: the same + * column types and every SYM column at the same width. */ +static test_result_t aw_widths_same(const char* what, ray_t* a, ray_t* b) { + TEST_ASSERT_EQ_I(ray_table_ncols(a), ray_table_ncols(b)); + for (int64_t c = 0; c < ray_table_ncols(a); c++) { + ray_t* x = ray_table_col_idx(a, c); + ray_t* y = ray_table_col_idx(b, c); + TEST_ASSERT_TRUE(x && y && !RAY_IS_ERR(x) && !RAY_IS_ERR(y)); + TEST_ASSERT_EQ_I(x->type, y->type); + if (x->type == RAY_SYM) + TEST_ASSERT_FMT((x->attrs & RAY_SYM_W_MASK) == (y->attrs & RAY_SYM_W_MASK), "%s: SYM width %d vs %d", + what, x->attrs & RAY_SYM_W_MASK, y->attrs & RAY_SYM_W_MASK); + } + PASS(); +} + +/* `q` over the generation-0 and generation-2 tables tbl0 / tbl2 (Rayfall + * expressions, loaded as T): byte-equal .csv.write answers, exactly + * want_mat materializations on generation 2, and every SYM column of the + * two results at the same width. */ +static test_result_t aw_csv_same(const char* tbl0, const char* tbl2, const char* q, uint64_t want_mat) { + char buf[1024]; char* csv[2]; size_t len[2]; ray_t* res[2]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T %s)", gen ? tbl2 : tbl0); + aw_eval_ok(buf); + ray_enc_counters_reset(); + res[gen] = ray_eval_str(ray_test_tmp(q)); + TEST_ASSERT_FMT(res[gen] && !RAY_IS_ERR(res[gen]) && res[gen]->type == RAY_TABLE, "%s gen %d: %s", + q, gen, ray_error_msg()); + if (gen) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == want_mat, "%s: %llu materializations, want %llu", q, + (unsigned long long)k.materialized, (unsigned long long)want_mat); + } + ray_env_set(ray_sym_intern("R", 1), res[gen]); + csv[gen] = aw_csv("R", gen ? "r2" : "r0", &len[gen]); + } + bool same = csv[0] && csv[1] && len[0] == len[1] && memcmp(csv[0], csv[1], len[0]) == 0; + free(csv[0]); free(csv[1]); + TEST_ASSERT_FMT(same, "%s: csv differs", q); + aw_eval_ok("(set R 0)"); + test_result_t r = aw_widths_same(q, res[0], res[1]); + ray_release(res[0]); ray_release(res[1]); + return r; +} +#define AW_CSV_SAME(a, b, q, m) do { test_result_t r_ = aw_csv_same((a), (b), (q), (m)); if (r_.status != TEST_PASS) return r_; } while (0) + +static test_result_t test_gather_operators(void) { + aw_save("go", AW_WIDE, -1); + AW_SAME("go", "(select {from: T where: (< k 100)})", 0); /* selection gather, every column */ + AW_SAME("go", "(select {k: k t: t from: T where: (== g 3) take: 7})", 0); /* take: filter head */ + AW_SAME("go", "(select {k: k v: v t: t from: T where: (> v 100) desc: k take: 5})", 0); /* top-k: the key read by range */ + AW_SAME("go", "(select {t: t from: T where: (> v 100) asc: [g k] take: 4})", 0); /* two sort keys */ + /* the same answers byte for byte through .csv.write */ + const char* t0 = "(.db.splayed.get \"" AW_TMP "/go0/\")"; + const char* t2 = "(.db.splayed.get \"" AW_TMP "/go2/\")"; + AW_CSV_SAME(t0, t2, "(select {from: T where: (< k 100)})", 0); + AW_CSV_SAME(t0, t2, "(select {k: k t: t from: T where: (== g 3) take: 7})", 0); + AW_CSV_SAME(t0, t2, "(select {k: k v: v s: s t: t from: T where: (> v 100) desc: k take: 5})", 0); + AW_CSV_SAME(t0, t2, "(select {k: k s: s t: t from: T where: (< v 50) take: -6})", 0); + /* no row passes: the empty table with every column's type */ + AW_CSV_SAME(t0, t2, "(select {from: T where: (< k 0)})", 0); + AW_CSV_SAME(t0, t2, "(select {k: k s: s t: t from: T where: (and (< k 100) (> v 1000))})", 0); + PASS(); +} + +/* SR_COMPACT_GROUP's shape: a filtered group under the parallel threshold + * gathers its key and input through agg_build_compact. */ +static test_result_t test_gather_compact_group(void) { + aw_save("gc", AW_WIDE, -1); + AW_SAME("gc", "(select {c: (count k) from: T where: (< k 1000) by: g})", 0); + AW_SAME("gc", "(select {c: (count k) m: (max v) from: T where: (< k 1000) by: s})", 0); + PASS(); +} + +/* q39's shape: a conjunction whose first conjunct passes <= 25% of the + * rows; the later conjuncts refine its selection, compacting their + * predicate columns (sel_compact). */ +static test_result_t test_gather_refine(void) { + aw_save("gr", AW_WIDE, -1); + AW_SAME("gr", "(select {c: (count k) from: T where: (and (< k 30000) (> v 100) (!= g 0))})", 0); + AW_SAME("gr", "(select {k: k t: t from: T where: (and (< k 30000) (> v 100) (!= g 0))})", 0); + AW_SAME("gr", "(take (select {s: s p: (count s) from: T where: (and (< k 30000) (== g 3) (> v 100)) " + "by: s desc: p take: 2}) -1)", 0); + PASS(); +} + +/* LIST cells beside generation-2 columns: gathered by a selection, the + * result read after the source table is released (ASan); then a partial + * failure (k's chunk-0 descriptors corrupted, so its gather fails after p + * and l were gathered) releases every retained cell and the partial + * columns once. */ +static test_result_t test_gather_list_cells(void) { + aw_eval_ok("(set W (table [p l k] (list (til 3000) (map (fn [j] (list j (* 2 j))) (til 3000)) (til 3000))))"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/li2/\" W {compress: true})"); + aw_eval_ok("(set T (.db.splayed.get \"" AW_TMP "/li2/\"))"); + ray_t* r = aw_eval("(select {p: p l: l k: k from: T where: (< p 10)})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + aw_eval_ok("(set T 0)"); /* the source table is gone */ + ray_t* fr = ray_fmt(r, 0); + ray_t* want = aw_eval("(select {p: p l: l k: k from: W where: (< p 10)})"); + ray_t* fw = ray_fmt(want, 0); + TEST_ASSERT_TRUE(ray_str_len(fr) == ray_str_len(fw) && memcmp(ray_str_ptr(fr), ray_str_ptr(fw), ray_str_len(fr)) == 0); + ray_release(fr); ray_release(fw); ray_release(r); ray_release(want); + PASS(); +} + +/* An index row list: nothing materializes (the HASH region is probed where + * it is mapped, ray_enc_hash_eq_rowsel). */ +static test_result_t test_gather_index_rows(void) { + aw_eval_ok("(set W (table [h v t] (list (.idx.hash (% (* (til 100000) 7919) 1000003)) (til 100000) " + "(map (fn [j] (format \"r%\" j)) (til 100000)))))"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/ix0/\" W {compress: false})"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/ix2/\" W {compress: true})"); + /* the HASH key is probed in place; v and t are gathered by rows */ + AW_SAME("ix", "(select {v: v t: t from: T where: (== h 7919)})", 0); + PASS(); +} + +/* Parted SYM outputs: partition 1 holds 3 symbols (W8), partition 2 adds + * 400 (W16). Every row-returning route (selection compaction, filter + * head, filter refinement, the sequential filter) answers byte for byte as + * generation 0 and at generation 0's width (the widest segment's), with + * nothing materialized. */ +static void aw_gather_parted_sym_tables(void) { + for (int gen = 0; gen <= 2; gen += 2) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/ps%d/2024.01.01/t/\" " + "(table [k s v] (list (til 70000) (take ['a 'b 'c] 70000) (as 'I32 (%% (til 70000) 50)))) " + "\"" AW_TMP "/ps%d/.sym\" {compress: %s})", gen, gen, gen ? "true" : "false"); + aw_eval_ok(q); + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/ps%d/2024.01.02/t/\" " + "(table [k s v] (list (+ 70000 (til 70000)) (as 'SYMBOL (map (fn [j] (format \"w%%\" (%% j 400))) (til 70000))) " + "(as 'I32 (%% (til 70000) 50)))) \"" AW_TMP "/ps%d/.sym\" {compress: %s})", gen, gen, gen ? "true" : "false"); + aw_eval_ok(q); + } +} +static test_result_t test_gather_parted_sym(void) { + aw_gather_parted_sym_tables(); + const char* t0 = "(.db.parted.get \"" AW_TMP "/ps0\" 't)"; + const char* t2 = "(.db.parted.get \"" AW_TMP "/ps2\" 't)"; + static const char* const qs[] = { + "(select {k: k s: s from: T where: (or (< k 20) (> k 139990))})", + "(select {k: k s: s from: T where: (> k 69990) take: 20})", + "(select {k: k s: s from: T where: (and (> k 69000) (== v 7) (< k 71000))})", + "(select {from: T where: (== v 7)})", + NULL, + }; + for (int i = 0; qs[i]; i++) AW_CSV_SAME(t0, t2, qs[i], 0); + /* the parted output's width is the widest segment's */ + aw_eval_ok("(set T (.db.parted.get \"" AW_TMP "/ps2\" 't))"); + ray_t* r = aw_eval("(select {s: s from: T where: (or (< k 3) (> k 139997))})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_t* s = ray_table_col_idx(r, 0); + TEST_ASSERT_TRUE(s && s->type == RAY_SYM); + TEST_ASSERT_EQ_I(s->attrs & RAY_SYM_W_MASK, RAY_SYM_W16); + ray_release(r); + PASS(); +} + +/* Fix round 1: a selection of at least RAY_PARALLEL_THRESHOLD rows is + * gathered by pool tasks. 300000 rows (five chunks) under ALL, MIX and + * NONE segments, every type a view carries (nulls, NaN, in-band SYM and + * STR nulls, pooled and inline STR): each result equals generation 0's + * `at` and the generation-0 source's own gather (pool bytes included, so + * the task pools are appended in row order), and the dispatch ran. */ +#define AW_GP_PRED "(or (< (til 300000) 70000) (and (>= (til 300000) 100000) (< (til 300000) 260000) (!= 0 (% (til 300000) 5))) (> (til 300000) 290000))" +static test_result_t test_gather_sel_parallel(void) { + aw_save("gp", "(table [i f s y d h] (list " + "(map (fn [j] (if (== 0 (% j 7)) 0Nl (* j 3))) (til 300000)) " + "(map (fn [j] (if (== 0 (% j 11)) 0Nf (* j 0.5))) (til 300000)) " + "(map (fn [j] (if (== 0 (% j 5)) \"\" (if (== 0 (% j 2)) \"short\" (format \"a pooled string of row %\" j)))) (til 300000)) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (% j 13)) \"\" (format \"k%\" (% j 300)))) (til 300000))) " + "(as 'DATE (til 300000)) (% (til 300000) 251)))", -1); + ray_t* t0 = aw_load("gp", 0); ray_t* t2 = aw_load("gp", 2); + TEST_ASSERT_TRUE(t0 && t2); + ray_t* pred = aw_eval(AW_GP_PRED); + TEST_ASSERT_TRUE(pred && !RAY_IS_ERR(pred) && pred->type == RAY_BOOL); + ray_t* sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + TEST_ASSERT_TRUE(ray_rowsel_meta(sel)->total_pass >= RAY_PARALLEL_THRESHOLD); + static const char* cols[] = { "i", "f", "s", "y", "d", "h" }; + for (int c = 0; c < 6; c++) { + int64_t nm = ray_sym_intern(cols[c], 1); + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(gen ? t2 : t0, nm, &s)); + uint64_t p0 = ray_col_test_gather_par(); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &out[gen])); + TEST_ASSERT_EQ_U(ray_col_test_gather_par(), p0 + 1); /* the pool tasks ran */ + ray_col_src_release(&s); + } + char q[700]; + snprintf(q, sizeof q, "(at (at (.db.splayed.get \"" AW_TMP "/gp0/\") '%s) (where %s))", cols[c], AW_GP_PRED); + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + AW_GATHER_REF(out[0], ref, true, cols[c]); + AW_GATHER_REF(out[1], ref, false, cols[c]); + ray_release(ref); + test_result_t r = aw_vec_same(out[0], out[1], cols[c]); + if (r.status != TEST_PASS) return r; + if (cols[c][0] == 's') TEST_ASSERT_TRUE(out[1]->str_pool && out[1]->str_pool->len > 0); + ray_release(out[0]); ray_release(out[1]); + } + ray_rowsel_release(sel); ray_release(pred); + ray_release(t0); ray_release(t2); + PASS(); +} + +/* P3 Task 6b fix round 1: a long ascending row list (repeats included) is + * gathered by pool tasks over position ranges (grows_par), each with its + * own cursor; STR pools merge in position order. Every type equals the + * generation-0 reference and the generation-0 source's own gather. */ +static test_result_t test_gather_rows_parallel(void) { + aw_save("gr", "(table [i s y h] (list " + "(map (fn [j] (if (== 0 (% j 7)) 0Nl (* j 3))) (til 300000)) " + "(map (fn [j] (if (== 0 (% j 5)) \"\" (if (== 0 (% j 2)) \"short\" (format \"a pooled string of row %\" j)))) (til 300000)) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (% j 13)) \"\" (format \"k%\" (% j 300)))) (til 300000))) " + "(% (til 300000) 251)))", -1); + ray_t* t0 = aw_load("gr", 0); ray_t* t2 = aw_load("gr", 2); + TEST_ASSERT_TRUE(t0 && t2); + const int64_t n = 2 * 100000; + ray_t* idv = ray_vec_new(RAY_I64, n); idv->len = n; + int64_t* ids = (int64_t*)ray_data(idv); + for (int64_t k = 0; k < n; k++) ids[k] = (k / 2) * 3; /* every third row, twice */ + TEST_ASSERT_TRUE(n >= RAY_PARALLEL_THRESHOLD); + static const char* cols[] = { "i", "s", "y", "h" }; + for (int c = 0; c < 4; c++) { + int64_t nm = ray_sym_intern(cols[c], 1); + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + ray_col_src_t sr; + TEST_ASSERT_NULL(ray_table_col_src(gen ? t2 : t0, nm, &sr)); + TEST_ASSERT_NULL(ray_col_gather_rows(&sr, ids, n, &out[gen])); + ray_col_src_release(&sr); + } + ray_t* ref = ray_at_fn(ray_table_col(t0, nm), idv); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + AW_GATHER_REF(out[0], ref, true, cols[c]); + AW_GATHER_REF(out[1], ref, false, cols[c]); + ray_release(ref); + test_result_t r = aw_vec_same(out[0], out[1], cols[c]); + if (r.status != TEST_PASS) return r; + ray_release(out[0]); ray_release(out[1]); + } + ray_release(idv); ray_release(t0); ray_release(t2); + PASS(); +} + +/* A chained filter built through the API, the q41 order: FILTER(in or + * not in of `col` against `set`, FILTER(k < 3000, T)), unoptimized so the + * membership test arrives over the first filter's selection (1.5% of the + * rows) and is answered by the refinement. */ +static ray_t* aw_refine_in_run(ray_t* t, const char* col, bool neg, ray_t* set, uint64_t* mat) { + ray_graph_t* g = ray_graph_new(t); + ray_op_t* f1 = ray_filter(g, ray_const_table(g, t), ray_lt(g, ray_scan(g, "k"), ray_const_i64(g, 3000))); + ray_op_t* m = neg ? ray_not_in(g, ray_scan(g, col), ray_const_vec(g, set)) + : ray_in(g, ray_scan(g, col), ray_const_vec(g, set)); + ray_op_t* f2 = ray_filter(g, f1, m); + ray_enc_counters_reset(); + ray_t* r = ray_execute(g, f2); + ray_enc_counters_t k; ray_enc_counters_get(&k); + *mat = k.materialized; + ray_graph_free(g); + return r; +} + +/* Fix round 2: the parallel gather's other exits. i holds one null, at + * row 250001 (a late task's segment only): HAS_NULLS is set and the value + * is null, equal to generation 0's `at`. Under ray_cancel() the pool + * skips the tasks: both the I64 and the pooled STR gather answer `cancel`, + * with no output and nothing left allocated. */ +static test_result_t test_gather_sel_late_null_cancel(void) { + aw_save("gl", "(table [i t u] (list (map (fn [j] (if (== j 250001) 0Nl j)) (til 300000)) " + "(map (fn [j] (format \"a pooled string of row %\" j)) (til 300000)) " + "(map (fn [j] (if (> j 295000) (format \"a late pooled string %\" j) \"s\")) (til 300000))))", -1); + ray_t* t0 = aw_load("gl", 0); ray_t* t2 = aw_load("gl", 2); + TEST_ASSERT_TRUE(t0 && t2); + ray_t* pred = ray_vec_new(RAY_BOOL, 300000); pred->len = 300000; + for (int64_t r = 0; r < 300000; r++) ((uint8_t*)ray_data(pred))[r] = r % 3 != 1; + ray_t* sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("i", 1), &s)); + uint64_t p0 = ray_col_test_gather_par(); + ray_t* got = NULL; + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &got)); + TEST_ASSERT_EQ_U(ray_col_test_gather_par(), p0 + 1); + ray_col_src_release(&s); + TEST_ASSERT_TRUE(got->attrs & RAY_ATTR_HAS_NULLS); + int64_t at = 0; + for (int64_t r = 0; r < 250001; r++) at += r % 3 != 1; + TEST_ASSERT_TRUE(ray_vec_is_null(got, at)); + ray_t* ref = aw_eval("(at (at (.db.splayed.get \"" AW_TMP "/gl0/\") 'i) (where (!= 1 (% (til 300000) 3))))"); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + AW_GATHER_REF(got, ref, true, "i"); + ray_release(ref); ray_release(got); + /* u is pooled only in the last task's rows (295001-299999): its pool, adopted */ + TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("u", 1), &s)); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &got)); + ray_col_src_release(&s); + ref = aw_eval("(at (at (.db.splayed.get \"" AW_TMP "/gl0/\") 'u) (where (!= 1 (% (til 300000) 3))))"); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + AW_GATHER_REF(got, ref, true, "u"); + ray_release(ref); ray_release(got); + static const char* cols[] = { "i", "t" }; + for (int c = 0; c < 2; c++) { + TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern(cols[c], 1), &s)); + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + p0 = ray_col_test_gather_par(); + ray_t* g = NULL; + ray_cancel(); + ray_t* e = ray_col_gather_sel(&s, sel, &g); + ray_cancel_reset(); + TEST_ASSERT_EQ_U(ray_col_test_gather_par(), p0 + 1); + TEST_ASSERT_FMT(e && RAY_IS_ERR(e) && !g, "%s: not an error", cols[c]); + TEST_ASSERT_STR_EQ(ray_err_code(e), "cancel"); + ray_error_free(e); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + ray_col_src_release(&s); + } + ray_rowsel_release(sel); ray_release(pred); ray_release(t0); ray_release(t2); + PASS(); +} + +/* Fix round 1 (q41's TraficSourceID): a later conjunct `in` / `not in` + * over a selective first one is answered by the refinement on the + * survivors' gathered values, so the column is not materialized; nullable + * members answer as generation 0. */ +static test_result_t test_refine_in(void) { + aw_save("ri", AW_WIDE, -1); + AW_SAME("ri", "(select {c: (count k) from: T where: (and (== g 3) (in k [3 10 17 24 1000 5000]))})", 0); + AW_SAME("ri", "(select {k: k v: v from: T where: (and (== g 3) (not-in v [3 10 17 24]))})", 0); + AW_SAME("ri", "(select {c: (count k) from: T where: (and (== g 3) (in v [0N 101 115 20001]))})", 0); + AW_SAME("ri", "(select {c: (count k) by: s from: T where: (and (== g 3) (in v [0N 101 115 20001]))})", 0); + /* the refinement itself: I16 and nullable I32 members, in and not in */ + ray_t* t0 = aw_load("ri", 0); ray_t* t2 = aw_load("ri", 2); + TEST_ASSERT_TRUE(t0 && t2); + static const struct { const char* col; bool neg; const char* set; } cs[] = { + { "g", false, "[-1 6 3]" }, { "g", true, "[-1 6 3]" }, + { "v", false, "(as 'I32 [0N 101 115 2001])" }, { "v", true, "(as 'I32 [101 115 2001])" }, + }; + for (int i = 0; i < 4; i++) { + ray_t* set = aw_eval(cs[i].set); + TEST_ASSERT_TRUE(set && !RAY_IS_ERR(set)); + uint64_t m0 = 0, m2 = 0, h0 = ray_exec_test_refine_in(); + ray_t* r0 = aw_refine_in_run(t0, cs[i].col, cs[i].neg, set, &m0); + TEST_ASSERT_EQ_U(ray_exec_test_refine_in(), h0); /* generation 0 keeps its route */ + ray_t* r2 = aw_refine_in_run(t2, cs[i].col, cs[i].neg, set, &m2); + TEST_ASSERT_EQ_U(ray_exec_test_refine_in(), h0 + 1); /* the refinement answered it */ + TEST_ASSERT_TRUE(r0 && r2 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r2) && r0->type == RAY_TABLE); + TEST_ASSERT_FMT(m2 == 0, "%s %d: %llu materializations", cs[i].col, cs[i].neg, (unsigned long long)m2); + TEST_ASSERT_TRUE(ray_table_nrows(r0) > 0 && ray_table_nrows(r0) < 3000); + ray_t* fa = ray_fmt(r0, 0); ray_t* fb = ray_fmt(r2, 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s %d differs", cs[i].col, cs[i].neg); + ray_release(fa); ray_release(fb); ray_release(r0); ray_release(r2); ray_release(set); + } + /* SYM `in` is not admitted by the refinement (exec_in does not + * translate the file domain): this direct refinement call keeps the + * full-width path. Through the language the later conjunct is read by + * range over the installed selection (P3 Task 14b, the single-file arm + * of exec_in_parted_selection, whose probe translates the set into the + * column's domain): 0 materializations (it read s whole before, 1); as + * a first conjunct Task 4's fused leaf answers it on ids + * (sym_membership) */ + { + ray_t* set = aw_eval("['a 'c 'zz]"); + TEST_ASSERT_TRUE(set && !RAY_IS_ERR(set)); + uint64_t m0 = 0, m2 = 0, h0 = ray_exec_test_refine_in(); + ray_t* r0 = aw_refine_in_run(t0, "s", false, set, &m0); + ray_t* r2 = aw_refine_in_run(t2, "s", false, set, &m2); + TEST_ASSERT_EQ_U(ray_exec_test_refine_in(), h0); + TEST_ASSERT_TRUE(r0 && r2 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r2)); + TEST_ASSERT_TRUE(ray_table_nrows(r0) > 0); + ray_t* fa = ray_fmt(r0, 0); ray_t* fb = ray_fmt(r2, 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + ray_release(fa); ray_release(fb); ray_release(r0); ray_release(r2); ray_release(set); + AW_SAME("ri", "(select {c: (count k) by: g from: T where: (and (== g 3) (in s ['a 'c 'zz]))})", 0); + } + ray_release(t0); ray_release(t2); + /* F64 members: NaN nulls, -0.0 against +0.0, through exec_in on the + * survivors, equal to generation 0 */ + aw_save("rf", "(table [k f] (list (til 200000) (map (fn [j] (if (== 0 (% j 10)) 0Nf (if (== 0 (% j 7)) -0.0 (* 0.5 (% j 9))))) (til 200000))))", -1); + t0 = aw_load("rf", 0); t2 = aw_load("rf", 2); + TEST_ASSERT_TRUE(t0 && t2); + static const struct { bool neg; const char* set; } fs[] = { + { false, "[0.0 2.5 0Nf]" }, { true, "[0.0 2.5]" }, { false, "[-0.0 4.0]" }, { true, "[0Nf 1.0]" }, + }; + for (int i = 0; i < 4; i++) { + ray_t* set = aw_eval(fs[i].set); + TEST_ASSERT_TRUE(set && !RAY_IS_ERR(set) && set->type == RAY_F64); + uint64_t m0 = 0, m2 = 0, h0 = ray_exec_test_refine_in(); + ray_t* r0 = aw_refine_in_run(t0, "f", fs[i].neg, set, &m0); + ray_t* r2 = aw_refine_in_run(t2, "f", fs[i].neg, set, &m2); + TEST_ASSERT_EQ_U(ray_exec_test_refine_in(), h0 + 1); + TEST_ASSERT_TRUE(r0 && r2 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r2)); + TEST_ASSERT_FMT(m2 == 0, "f %s: %llu materializations", fs[i].set, (unsigned long long)m2); + TEST_ASSERT_TRUE(ray_table_nrows(r0) > 0); + ray_t* fa = ray_fmt(r0, 0); ray_t* fb = ray_fmt(r2, 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "f %s differs", fs[i].set); + ray_release(fa); ray_release(fb); ray_release(r0); ray_release(r2); ray_release(set); + } + ray_release(t0); ray_release(t2); + /* q41's shape: a grouped take, whose conjuncts run as a filter chain */ + AW_SAME("ri", "(take (select {c: (count k) from: T where: (and (== g 3) (>= k 100) (<= k 150000) " + "(in v [101 115 136 20001 0N]) (!= s 'q)) by: {s: s k: k} desc: c take: 20}) -10)", 0); + AW_SAME("ri", "(take (select {c: (count k) from: T where: (and (== g 3) (>= k 100) (<= k 150000) " + "(not-in v [101 115 136 20001])) by: {s: s k: k} desc: c take: 20}) -10)", 0); + PASS(); +} + +/* The operators called directly on generation-0 and generation-2 copies + * of one table: exec_filter (its parallel gather over 200000 rows and the + * parted arm over 140000; its sequential arm under the parallel + * threshold), exec_filter_head and the sort top-K (topk_gather_rows, the + * key passed as a plain vector). Generation 2 answers byte for byte + * (.csv.write) as generation 0's operator, with SYM at the same width and + * nothing materialized; the filters also equal generation 0's selection + * compaction of the same rows (the language route, sel_compact), so a null + * bit lost by a flat or parted gather shows here: exec_filter's flat + * gathers and exec_filter_head's flat and parted ones copied values + * without their null bits before P3 Task 6. */ +static test_result_t aw_csv_eq(const char* what, int op, ray_t* a, ray_t* b) { + char* csv[2]; size_t len[2]; + ray_t* r[2] = { a, b }; + for (int i = 0; i < 2; i++) { + ray_env_set(ray_sym_intern("R", 1), r[i]); + csv[i] = aw_csv("R", i ? "o2" : "o0", &len[i]); + } + aw_eval_ok("(set R 0)"); + bool same = csv[0] && csv[1] && len[0] == len[1] && memcmp(csv[0], csv[1], len[0]) == 0; + free(csv[0]); free(csv[1]); + TEST_ASSERT_FMT(same, "%s op %d: csv differs", what, op); + PASS(); +} +static test_result_t aw_ops_same(const char* tbl0, const char* tbl2, bool topk) { + char buf[1024]; + ray_t* t[2]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "%s", gen ? tbl2 : tbl0); + t[gen] = aw_eval(buf); + TEST_ASSERT_FMT(t[gen] && !RAY_IS_ERR(t[gen]), "%s: %s", buf, ray_error_msg()); + } + int64_t n = ray_table_nrows(t[0]); + ray_t* pred = ray_vec_new(RAY_BOOL, n); pred->len = n; + ray_t* head = ray_vec_new(RAY_BOOL, n); head->len = n; /* the first 7 passing rows */ + int64_t kept = 0; + for (int64_t r = 0; r < n; r++) { + uint8_t b = r < 5 || r % 97 == 3 || r > n - 3; + ((uint8_t*)ray_data(pred))[r] = b; + ((uint8_t*)ray_data(head))[r] = b && kept < 7; + kept += b; + } + ray_t* key = ray_table_col(t[0], ray_sym_intern("k", 1)); /* generation 0's, a plain vector */ + TEST_ASSERT_TRUE(key && !RAY_IS_ERR(key)); + for (int op = 0; op < (topk ? 3 : 2); op++) { + ray_t* res[2]; + for (int gen = 0; gen < 2; gen++) { + ray_enc_counters_reset(); + res[gen] = op == 0 ? exec_filter(NULL, NULL, t[gen], pred) + : op == 1 ? exec_filter_head(t[gen], pred, 7) + : ray_topk_table(t[gen], key, 1, 0, 6); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (gen) TEST_ASSERT_FMT(k.materialized == 0, "%s op %d: %llu materializations", tbl2, op, + (unsigned long long)k.materialized); + TEST_ASSERT_FMT(res[gen] && !RAY_IS_ERR(res[gen]) && res[gen]->type == RAY_TABLE, "%s op %d gen %d: %s", + tbl2, op, gen, ray_error_msg()); + } + test_result_t r = aw_csv_eq(tbl2, op, res[0], res[1]); + if (r.status == TEST_PASS && op < 2) { + ray_t* sel = ray_rowsel_from_pred(op ? head : pred); + TEST_ASSERT_NOT_NULL(sel); + ray_t* ref = sel_compact(NULL, t[0], sel, NULL, 0); + ray_rowsel_release(sel); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + r = aw_csv_eq("selection compaction", op, ref, res[1]); + ray_release(ref); + } + if (r.status == TEST_PASS) + TEST_ASSERT_EQ_I(ray_table_nrows(res[1]), op == 0 ? kept : op == 1 ? 7 : 6); + if (r.status == TEST_PASS) r = aw_widths_same(tbl2, res[0], res[1]); + ray_release(res[0]); ray_release(res[1]); + if (r.status != TEST_PASS) return r; + } + ray_release(pred); ray_release(head); ray_release(t[0]); ray_release(t[1]); + PASS(); +} + +static test_result_t test_gather_filter_ops(void) { + aw_save("fo", AW_WIDE, -1); + test_result_t r = aw_ops_same("(.db.splayed.get \"" AW_TMP "/fo0/\")", "(.db.splayed.get \"" AW_TMP "/fo2/\")", true); + if (r.status != TEST_PASS) return r; + aw_save("fs", "(table [k g v s t] (list (til 3000) (as 'I16 (% (til 3000) 7)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 10)) 0N j)) (til 3000))) " + "(as 'SYMBOL (map (fn [j] (format \"y%\" (% j 300))) (til 3000))) " + "(map (fn [j] (format \"a longer text value %\" (% j 333))) (til 3000))))", -1); + r = aw_ops_same("(.db.splayed.get \"" AW_TMP "/fs0/\")", "(.db.splayed.get \"" AW_TMP "/fs2/\")", true); + if (r.status != TEST_PASS) return r; + aw_gather_parted_sym_tables(); + r = aw_ops_same("(.db.parted.get \"" AW_TMP "/ps0\" 't)", "(.db.parted.get \"" AW_TMP "/ps2\" 't)", false); + if (r.status != TEST_PASS) return r; + /* the language route to exec_filter_head (a parted take under a where: + * on the partition key): the null at row 0 stays null on both + * generations (generation 0 printed -9223372036854775808 before) */ + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/hn%d/2024.01.0%d/t/\" " + "(table [a b] (list (as 'I64 [0N 1 2 0N 4]) (as 'I32 [5 0N 7 8 9]))) {compress: %s})", + gen, p + 1, gen ? "true" : "false"); + aw_eval_ok(q); + } + for (int gen = 0; gen <= 2; gen += 2) { + char q[600]; + snprintf(q, sizeof q, "(set T (.db.parted.get \"" AW_TMP "/hn%d\" 't))", gen); + aw_eval_ok(q); + ray_t* got = aw_eval("(select {from: T where: (not (== date 2024.01.02)) take: 3})"); + ray_t* want = aw_eval("(table [date a b] (list (take 2024.01.01 3) (as 'I64 [0N 1 2]) (as 'I32 [5 0N 7])))"); + TEST_ASSERT_TRUE(got && want && !RAY_IS_ERR(got) && !RAY_IS_ERR(want)); + ray_t* fg = ray_fmt(got, 0); ray_t* fw = ray_fmt(want, 0); + bool same = ray_str_len(fg) == ray_str_len(fw) && memcmp(ray_str_ptr(fg), ray_str_ptr(fw), ray_str_len(fg)) == 0; + TEST_ASSERT_FMT(same, "gen %d: %.*s", gen, (int)ray_str_len(fg), ray_str_ptr(fg)); + ray_release(fg); ray_release(fw); ray_release(got); ray_release(want); + } + /* no row passes the operators: empty tables equal to generation 0's */ + for (int big = 0; big < 2; big++) { + ray_t* tz[2]; + for (int gen = 0; gen < 2; gen++) { + tz[gen] = aw_load(big ? "fo" : "fs", gen ? 2 : 0); + TEST_ASSERT_NOT_NULL(tz[gen]); + } + int64_t n = ray_table_nrows(tz[0]); + ray_t* zp = ray_vec_new(RAY_BOOL, n); zp->len = n; + memset(ray_data(zp), 0, (size_t)n); + for (int op = 0; op < 2; op++) { + ray_t* res[2]; + for (int gen = 0; gen < 2; gen++) { + ray_enc_counters_reset(); + res[gen] = op ? exec_filter_head(tz[gen], zp, 5) : exec_filter(NULL, NULL, tz[gen], zp); + TEST_ASSERT_TRUE(res[gen] && !RAY_IS_ERR(res[gen]) && ray_table_nrows(res[gen]) == 0); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (gen) TEST_ASSERT_EQ_U(k.materialized, 0); + } + r = aw_csv_eq("no row passes", op, res[0], res[1]); + if (r.status == TEST_PASS) r = aw_widths_same("no row passes", res[0], res[1]); + ray_release(res[0]); ray_release(res[1]); + if (r.status != TEST_PASS) return r; + } + ray_release(zp); ray_release(tz[0]); ray_release(tz[1]); + } + PASS(); +} + +/* ---- Task 6b: group keys read at rows ---- */ + +/* q18's shape (Task 15 gap 1): a group-by take without an order runs the + * first-n pre-pass over the keys' sources, nothing unstaged. */ +static test_result_t test_firstn_by_range(void) { + aw_save("fn", "(table [h s v] (list (% (* (til 300000) 7919) 100003) " + "(as 'SYMBOL (map (fn [j] (format \"p%\" (% j 97))) (til 300000))) (til 300000)))", -1); + static const char* const qs[] = { + "(select {c: (count h) from: T by: {h: h s: s} take: 10})", + "(select {c: (count h) s: (sum v) from: T by: h take: 25})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + agg_route_reset(); + AW_SAME("fn", qs[i], 0); + TEST_ASSERT_FMT(agg_route_stats().first_n == 2, "%s: first-n answered %llu of 2 runs", qs[i], + (unsigned long long)agg_route_stats().first_n); + } + PASS(); +} + +/* The parted form: two partitions of the fn table under a generation-0 and + * a generation-2 root. The first-n passes run over the parted sources (no + * flat copy), nothing is materialized, answers and group order are + * generation 0's. */ +static void aw_firstn_parted_tables(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/fp%d/2024.01.0%d/t/\" " + "(table [h s v] (list (%% (* (+ (til 150000) %d) 7919) 100003) " + "(as 'SYMBOL (map (fn [j] (format \"p%%\" (%% (+ j %d) 97))) (til 150000))) (+ (til 150000) %d))) " + "\"" AW_TMP "/fp%d/.sym\" {compress: %s})", + gen, p + 1, p * 150000, p * 150000, p * 150000, gen, gen ? "true" : "false"); + aw_eval_ok(q); + } +} +static test_result_t test_firstn_parted(void) { + aw_firstn_parted_tables(); + /* a mixed root: partition 1 generation 0, partition 2 generation 2 */ + for (int p = 0; p < 2; p++) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/fpm/2024.01.0%d/t/\" " + "(table [h s v] (list (%% (* (+ (til 150000) %d) 7919) 100003) " + "(as 'SYMBOL (map (fn [j] (format \"p%%\" (%% (+ j %d) 97))) (til 150000))) (+ (til 150000) %d))) " + "\"" AW_TMP "/fpm/.sym\" {compress: %s})", + p + 1, p * 150000, p * 150000, p * 150000, p ? "true" : "false"); + aw_eval_ok(q); + } + /* the mixed root, and the declines over a segment-streamed table (too + * few groups: 97 symbols for a take of 200; heavy: 3 of 97 groups + * hold a share above 1/64), each answered as generation 0 */ + static const char* const ds[] = { + "(select {c: (count h) from: T by: {h: h s: s} take: 10})", + "(select {c: (count h) s: (sum v) from: T by: s take: 200})", + "(select {c: (count h) s: (sum v) from: T by: s take: 3})", + NULL, + }; + static const char* const roots[] = { "fpm", "fp2", "fp2" }; + for (int i = 0; ds[i]; i++) { + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + char b[256]; + snprintf(b, sizeof b, "(set T (.db.parted.get \"" AW_TMP "/%s\" 't))", gen ? roots[i] : "fp0"); + aw_eval_ok(b); + ray_enc_counters_reset(); + out[gen] = aw_eval(ds[i]); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "%s gen %d: %s", ds[i], gen, ray_error_msg()); + if (gen) { ray_enc_counters_t k; ray_enc_counters_get(&k); TEST_ASSERT_EQ_U(k.materialized, 0); } + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s (%s) differs", ds[i], roots[i]); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + static const char* const qs[] = { + "(select {c: (count h) from: T by: {h: h s: s} take: 10})", + "(select {c: (count h) s: (sum v) from: T by: h take: 25})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + char b[256]; + snprintf(b, sizeof b, "(set T (.db.parted.get \"" AW_TMP "/fp%d\" 't))", gen ? 2 : 0); + aw_eval_ok(b); + ray_enc_counters_reset(); + agg_route_reset(); + int64_t f0 = ray_group_test_flat_copies(), s0 = ray_group_segstream_runs(); + out[gen] = aw_eval(qs[i]); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "%s gen %d: %s", qs[i], gen, ray_error_msg()); + if (!gen) continue; + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == 0, "%s: %llu materializations", qs[i], (unsigned long long)k.materialized); + TEST_ASSERT_FMT(ray_group_test_flat_copies() == f0, "%s: %lld flat copies", qs[i], + (long long)(ray_group_test_flat_copies() - f0)); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 1, "%s: not grouped in place", qs[i]); + TEST_ASSERT_FMT(agg_route_stats().first_n >= 1, "%s: not first-n", qs[i]); + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s differs", qs[i]); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + PASS(); +} + +/* q42's shape: a selective filter, keys read at a few rows of a few + * vectors: point reads, no vector decoded for the keys. w and h are runs + * (RLE) or packed (FOR_BP) without nulls, the encodings a point read + * serves. c is answered from its statistics; the second conjunct is not + * a fused leaf, so it compacts w over c's 3000 rows (vectors 181-184, each + * holding more than RAY_COL_POINT_ROWS of them: decoded once, by the + * filter). The group's key reads (the dense plan's selection bounds and + * the compact gather of its ~60 survivors) decode nothing. */ +static test_result_t test_sparse_key_points(void) { + aw_save("sp", "(table [c w h] (list (div (til 300000) 3000) (as 'I16 (% (div (til 300000) 7) 300)) " + "(as 'I16 (% (div (til 300000) 11) 200))))", -1); + for (int64_t v = 181; v <= 184; v++) { /* c == 62: rows 186000..188999 */ + int ew = aw_vec_enc("sp", "w", v), eh = aw_vec_enc("sp", "h", v); + TEST_ASSERT_FMT(ew == RAY_ENC_RLE || ew == RAY_ENC_FOR_BP || ew == RAY_ENC_CONST, "w vector %lld: %d", (long long)v, ew); + TEST_ASSERT_FMT(eh == RAY_ENC_RLE || eh == RAY_ENC_FOR_BP || eh == RAY_ENC_CONST, "h vector %lld: %d", (long long)v, eh); + } + AW_SAME("sp", "(select {n: (count w) from: T where: (and (== c 62) (== 0 (% w 50))) by: {w: w h: h} desc: n take: 10})", 0); + TEST_ASSERT_FMT(aw_col_decoded("w") == 4 * 1024 * 2 && aw_col_decoded("h") == 0, "w %llu h %llu", + (unsigned long long)aw_col_decoded("w"), (unsigned long long)aw_col_decoded("h")); + PASS(); +} + +/* Point reads in the row-list and selection gathers (open decision D2, + * per codec in Task 10b): per encoding, a vector holding at most its + * codec's limit of requested rows (vector 0: lim rows, vector 5: one row, + * repeated) is point-read and decodes nothing, one holding more (vector 1: + * lim + 1 rows) is decoded; a declined read (DELTA_BP) decodes every + * touched vector. A vector with a null bitmap is point-read on every + * codec (pn, pw), its nulls as the decode writes them. Ids sorted, + * reversed and repeated; values equal generation 0's. */ +static test_result_t test_gather_points(void) { + /* lim: the codec's limit (RAY_ENC_VEC / 32 packed lanes, / 16 runs, + * DICT and any vector with a bitmap); 0: the codec declines */ + static const struct { const char* name; const char* x; int enc; int64_t lim; } cs[] = { + { "pf", "(% (* (til 70000) 7919) 1000)", RAY_ENC_FOR_BP, RAY_ENC_VEC / 32 }, + { "pr", "(div (til 70000) 5)", RAY_ENC_RLE, RAY_ENC_VEC / 16 }, + { "pc", "(div (til 70000) 2048)", RAY_ENC_CONST, RAY_ENC_VEC / 16 }, + { "pd", "(* 1000003 (% (til 70000) 5))", RAY_ENC_DICT, RAY_ENC_VEC / 16 }, + { "pe", "(% (* (til 70000) 7919) 1000)", RAY_ENC_DELTA_BP, 0 }, + { "pn", "(map (fn [j] (if (== 0 (% j 100)) 0N (% (* j 7919) 1000))) (til 70000))", RAY_ENC_FOR_BP, RAY_ENC_VEC / 16 }, + { "pw", "(map (fn [j] (if (== 0 (% j 100)) 0N (* j 7919))) (til 70000))", RAY_ENC_RAW, RAY_ENC_VEC / 16 }, + { "pq", "(map (fn [j] (if (== 0 (% j 100)) 0N (* 1000003 (% j 5)))) (til 70000))", RAY_ENC_DICT, RAY_ENC_VEC / 16 }, + }; + for (size_t c = 0; c < sizeof cs / sizeof cs[0]; c++) { + /* vector 0: lim rows (point-read when lim > 0), vector 1: lim + 1 + * rows (decoded), vector 5: one row, twice; a declining codec uses + * the RLE limit's counts */ + const int64_t L = cs[c].lim ? cs[c].lim : RAY_ENC_VEC / 16; + int64_t ids[RAY_ENC_VEC / 16 * 2 + 3]; + int64_t n = 0; + for (int64_t i = 0; i < L; i++) ids[n++] = 2 * i; + for (int64_t i = 0; i <= L; i++) ids[n++] = 1024 + i; + ids[n++] = 5 * 1024 + 7; ids[n++] = 5 * 1024 + 7; + int64_t rev[sizeof ids / sizeof ids[0]]; + for (int64_t i = 0; i < n; i++) rev[i] = ids[n - 1 - i]; + const bool point = cs[c].lim > 0; + char tq[256]; + snprintf(tq, sizeof tq, "(table [x] (list %s))", cs[c].x); + aw_save(cs[c].name, tq, cs[c].enc); + for (int64_t v = 0; v <= 5; v += 5) TEST_ASSERT_EQ_I(aw_vec_enc(cs[c].name, "x", v), cs[c].enc); + ray_t* t0 = aw_load(cs[c].name, 0); + ray_t* t2 = aw_load(cs[c].name, 2); + TEST_ASSERT_TRUE(t0 && t2); + ray_t* ref = ray_table_col(t0, ray_sym_intern("x", 1)); + const int64_t* rv = (const int64_t*)ray_data(ref); + ray_t* encv = ray_table_get_col_enc(t2, ray_sym_intern("x", 1)); + TEST_ASSERT_NOT_NULL(encv); + const uint64_t want = (point ? 1 : 3) * 1024 * 8; /* vector 1, or vectors 0, 1 and 5 */ + for (int pass = 0; pass < 3; pass++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("x", 1), &s)); + uint64_t d0 = atomic_load(&ray_enccol_of(encv)->decoded_bytes); + ray_t* out = NULL; + ray_t* sel = NULL; ray_t* pred = NULL; + const int64_t* want_ids = pass == 1 ? rev : ids; + int64_t want_n = n; + if (pass < 2) { + TEST_ASSERT_NULL(ray_col_gather_rows(&s, want_ids, n, &out)); + } else { /* a rowsel of the distinct rows */ + pred = ray_vec_new(RAY_BOOL, 70000); pred->len = 70000; + memset(ray_data(pred), 0, 70000); + for (int64_t i = 0; i < n; i++) ((uint8_t*)ray_data(pred))[ids[i]] = 1; + sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &out)); + want_n = n - 1; + } + ray_col_src_release(&s); + uint64_t got = atomic_load(&ray_enccol_of(encv)->decoded_bytes) - d0; + TEST_ASSERT_FMT(got == want, "%s pass %d: decoded %llu, want %llu", cs[c].name, pass, + (unsigned long long)got, (unsigned long long)want); + TEST_ASSERT_EQ_I(out->len, want_n); + TEST_ASSERT_EQ_I(out->attrs & RAY_ATTR_HAS_NULLS, ref->attrs & RAY_ATTR_HAS_NULLS); + for (int64_t i = 0; i < want_n; i++) + TEST_ASSERT_FMT(((int64_t*)ray_data(out))[i] == rv[want_ids[i]], "%s pass %d row %lld", + cs[c].name, pass, (long long)i); + ray_release(out); + if (sel) ray_rowsel_release(sel); + if (pred) ray_release(pred); + } + ray_release(t0); ray_release(t2); + } + /* parted: segment-local vectors (partitions of 3000 rows, so vectors + * and segments straddle the global morsels); few ids per local vector, + * unsorted and repeated, as a row list and as a rowsel: nothing + * decoded */ + ray_encw_test_force(RAY_ENC_FOR_BP); + for (int p = 0; p < 2; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/gpp/2024.01.0%d/t/\" " + "(table [x] (list (%% (* (+ (til 3000) %d) 7919) 1000))) {compress: true})", p + 1, p * 3000); + aw_eval_ok(q); + } + ray_encw_test_force(-1); + ray_t* tp = aw_eval("(.db.parted.get \"" AW_TMP "/gpp\" 't)"); + TEST_ASSERT_TRUE(tp && !RAY_IS_ERR(tp)); + static const int64_t pids[] = { 3075, 3070, 5999, 3075, 10, 2999, 3000, 4100 }; + const int64_t pn = 8; + ray_t* penc = ray_table_get_col_enc(tp, ray_sym_intern("x", 1)); + TEST_ASSERT_NOT_NULL(penc); + for (int sg = 0; sg < 2; sg++) { + const ray_enc_desc_t* d = ray_enccol_descs(ray_enccol_of(ray_enccol_seg(penc, sg)), 0); + for (int j = 0; j < 3; j++) TEST_ASSERT_EQ_I(d[j].encoding, RAY_ENC_FOR_BP); + } + ray_t* ppred = ray_vec_new(RAY_BOOL, 6000); ppred->len = 6000; + memset(ray_data(ppred), 0, 6000); + for (int64_t i = 0; i < pn; i++) ((uint8_t*)ray_data(ppred))[pids[i]] = 1; + ray_t* psel = ray_rowsel_from_pred(ppred); + TEST_ASSERT_NOT_NULL(psel); + static const int64_t psorted[] = { 10, 2999, 3000, 3070, 3075, 4100, 5999 }; + for (int pass = 0; pass < 2; pass++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(tp, ray_sym_intern("x", 1), &s)); + ray_enc_counters_reset(); + ray_t* out = NULL; + TEST_ASSERT_NULL(pass ? ray_col_gather_sel(&s, psel, &out) : ray_col_gather_rows(&s, pids, pn, &out)); + ray_col_src_release(&s); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.decoded_bytes == 0 && k.materialized == 0, "parted pass %d: decoded %llu", pass, + (unsigned long long)k.decoded_bytes); + const int64_t* w = pass ? psorted : pids; + TEST_ASSERT_EQ_I(out->len, pass ? 7 : pn); + for (int64_t i = 0; i < out->len; i++) + TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[i], (w[i] * 7919) % 1000); + ray_release(out); + } + ray_rowsel_release(psel); ray_release(ppred); ray_release(tp); + /* parted DICT with a null bitmap (Task 10b): the rows on both sides of + * the partition boundary at 3000 (one global morsel over two segments' + * vectors), as a rowsel and as a row list, point-read: nothing decoded, + * nulls where generation 0 has them */ + ray_encw_test_force(RAY_ENC_DICT); + for (int p = 0; p < 2; p++) { + char q[700]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/gpd/2024.01.0%d/t/\" " + "(table [x] (list (map (fn [j] (if (== 0 (%% j 100)) 0N (* 1000003 (%% j 5)))) (+ (til 3000) %d)))) " + "{compress: true})", p + 1, p * 3000); + aw_eval_ok(q); + } + ray_encw_test_force(-1); + ray_t* td = aw_eval("(.db.parted.get \"" AW_TMP "/gpd\" 't)"); + TEST_ASSERT_TRUE(td && !RAY_IS_ERR(td)); + { + ray_t* denc = ray_table_get_col_enc(td, ray_sym_intern("x", 1)); + TEST_ASSERT_NOT_NULL(denc); + for (int sg = 0; sg < 2; sg++) { + const ray_enc_desc_t* d = ray_enccol_descs(ray_enccol_of(ray_enccol_seg(denc, sg)), 0); + TEST_ASSERT_TRUE(d[2].encoding == RAY_ENC_DICT && d[2].n_nulls > 0); + TEST_ASSERT_TRUE(d[0].encoding == RAY_ENC_DICT && d[0].n_nulls > 0); + } + } + static const int64_t dids[] = { 2900, 2990, 2999, 3000, 3005, 3100, 4100 }; + ray_t* dpred = ray_vec_new(RAY_BOOL, 6000); dpred->len = 6000; + memset(ray_data(dpred), 0, 6000); + for (int i = 0; i < 7; i++) ((uint8_t*)ray_data(dpred))[dids[i]] = 1; + ray_t* dsel = ray_rowsel_from_pred(dpred); + TEST_ASSERT_NOT_NULL(dsel); + for (int pass = 0; pass < 2; pass++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(td, ray_sym_intern("x", 1), &s)); + ray_enc_counters_reset(); + ray_t* out = NULL; + TEST_ASSERT_NULL(pass ? ray_col_gather_sel(&s, dsel, &out) : ray_col_gather_rows(&s, dids, 7, &out)); + ray_col_src_release(&s); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.decoded_bytes == 0, "parted DICT pass %d: decoded %llu", pass, (unsigned long long)k.decoded_bytes); + TEST_ASSERT_EQ_I(out->len, 7); + TEST_ASSERT_TRUE(out->attrs & RAY_ATTR_HAS_NULLS); + for (int i = 0; i < 7; i++) + TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[i], dids[i] % 100 == 0 ? NULL_I64 : 1000003 * (dids[i] % 5)); + ray_release(out); + } + ray_rowsel_release(dsel); ray_release(dpred); ray_release(td); + PASS(); +} + +static bool aw_forge_absent(const char* path, int64_t c); + +/* Task 10b: a RAW vector without nulls is read in place (the view, which + * counts the vector's bytes), however few of its rows a gather asks for. */ +static test_result_t test_gather_raw_points(void) { + aw_save("pv", "(table [x] (list (* (til 70000) 7919)))", RAY_ENC_RAW); + for (int64_t v = 0; v <= 5; v++) TEST_ASSERT_EQ_I(aw_vec_enc("pv", "x", v), RAY_ENC_RAW); + ray_t* t0 = aw_load("pv", 0); ray_t* t2 = aw_load("pv", 2); + TEST_ASSERT_TRUE(t0 && t2); + const int64_t* rv = (const int64_t*)ray_data(ray_table_col(t0, ray_sym_intern("x", 1))); + ray_t* encv = ray_table_get_col_enc(t2, ray_sym_intern("x", 1)); + TEST_ASSERT_NOT_NULL(encv); + ray_enccol_t* e = ray_enccol_of(encv); + static const struct { int64_t v, n; uint64_t want; } rd[] = { + { 5, RAY_ENC_VEC / 128, 1024 * 8 }, + { 1, RAY_ENC_VEC / 128 + 1, 1024 * 8 }, + { 5, 1, 1024 * 8 }, + }; + for (int r = 0; r < 3; r++) { + int64_t ids[RAY_ENC_VEC / 128 + 1]; + for (int64_t q = 0; q < rd[r].n; q++) ids[q] = rd[r].v * 1024 + 3 * q; + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("x", 1), &s)); + uint64_t d0 = atomic_load(&e->decoded_bytes); + ray_t* out = NULL; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, rd[r].n, &out)); + ray_col_src_release(&s); + uint64_t got = atomic_load(&e->decoded_bytes) - d0; + TEST_ASSERT_FMT(got == rd[r].want, "read %d: decoded %llu, want %llu", r, (unsigned long long)got, + (unsigned long long)rd[r].want); + for (int64_t q = 0; q < rd[r].n; q++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(out))[q], rv[ids[q]]); + ray_release(out); + } + ray_release(t0); ray_release(t2); + PASS(); +} + +/* Encodings of every vector of column `col` of the parted table `t` + * (segment-local descriptors): per encoding, how many. */ +static void aw_parted_encs(ray_t* t, const char* col, int64_t cnt[8]) { + memset(cnt, 0, 8 * sizeof(int64_t)); + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))); + if (!encv) return; + for (int64_t sg = 0; ; sg++) { + ray_t* seg = ray_enccol_seg(encv, sg); + if (!seg) break; + ray_enccol_t* e = ray_enccol_of(seg); + if (!e || e->kind != RAY_ENCCOL_SINGLE) continue; + for (int64_t v = 0; v * RAY_ENC_VEC < e->len; v++) { + const ray_enc_desc_t* d = ray_enccol_descs(e, v / RAY_ENC_VECS_PER_CHUNK); + int enc = d[v % RAY_ENC_VECS_PER_CHUNK].encoding; + if (enc >= 0 && enc < 8) cnt[enc]++; + } + } +} + +/* Task 10b: SYM ids point-read by the selection and row-list gathers of a + * parted source. Two partitions (3000 and 67000 rows, so segment vectors + * straddle the global morsels): a in vector-wide constants, b in runs of 7 + * with every 13th run "" (the in-band null), c cycling over 300 symbols, + * so CONST, RLE and packed vectors all occur. A few rows per vector + * (every 997th row and the rows at the partition boundary), sorted and + * unsorted: nothing decoded (a RAW vector is read in place), and the + * result equals generation 0's own gather and `at` (width, domain, nulls + * and symbols). */ +static test_result_t test_gather_sym_points(void) { + static const int64_t np[2] = { 3000, 67000 }; + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[1600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/sy%d/2024.01.0%d/t/\" " + "(table [k a b c] (list (+ %lld (til %lld)) " + "(as 'SYMBOL (map (fn [j] (format \"c%%\" (div j 4096))) (til %lld))) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (%% (div j 7) 13)) \"\" (format \"r%%\" (%% (div j 7) 97)))) (til %lld))) " + "(as 'SYMBOL (map (fn [j] (format \"w%%\" (%% (* j 7919) 300))) (til %lld))))) " + "\"" AW_TMP "/sy%d/.sym\" {compress: %s})", gen, p + 1, (long long)(p ? np[0] : 0), + (long long)np[p], (long long)np[p], (long long)np[p], (long long)np[p], gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + ray_t* tp[2] = { aw_eval("(.db.parted.get \"" AW_TMP "/sy0\" 't)"), aw_eval("(.db.parted.get \"" AW_TMP "/sy2\" 't)") }; + TEST_ASSERT_TRUE(tp[0] && tp[1] && !RAY_IS_ERR(tp[0]) && !RAY_IS_ERR(tp[1])); + int64_t ca[8], cb[8], cc[8]; + aw_parted_encs(tp[1], "a", ca); aw_parted_encs(tp[1], "b", cb); aw_parted_encs(tp[1], "c", cc); + TEST_ASSERT_FMT(ca[RAY_ENC_CONST] > 0 && cb[RAY_ENC_RLE] > 0 && cc[RAY_ENC_FOR_BP] + cc[RAY_ENC_DICT] > 0, + "a CONST %lld, b RLE %lld, c FOR_BP %lld DICT %lld RAW %lld", (long long)ca[RAY_ENC_CONST], + (long long)cb[RAY_ENC_RLE], (long long)cc[RAY_ENC_FOR_BP], (long long)cc[RAY_ENC_DICT], + (long long)cc[RAY_ENC_RAW]); + const int64_t n = np[0] + np[1]; + ray_t* pred = ray_vec_new(RAY_BOOL, n); pred->len = n; + memset(ray_data(pred), 0, (size_t)n); + int64_t ids[128], ni = 0; + for (int64_t r = 0; r < n; r++) + if (r % 997 == 5 || (r >= 2998 && r <= 3001) || r == n - 1) { + ((uint8_t*)ray_data(pred))[r] = 1; + if (ni < 128) ids[ni++] = r; + } + for (int64_t i = 0; i < ni / 2; i++) { int64_t x = ids[i]; ids[i] = ids[ni - 1 - i]; ids[ni - 1 - i] = x; } /* unsorted */ + ray_t* sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + static const char* const cols[] = { "a", "b", "c" }; + for (int c = 0; c < 3; c++) { + ray_t* out[2][2]; + for (int g = 0; g < 2; g++) { + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(tp[g], ray_sym_intern(cols[c], 1), &s)); + ray_enc_counters_reset(); + TEST_ASSERT_NULL(ray_col_gather_sel(&s, sel, &out[g][0])); + TEST_ASSERT_NULL(ray_col_gather_rows(&s, ids, ni, &out[g][1])); + ray_col_src_release(&s); + ray_enc_counters_t k; ray_enc_counters_get(&k); + /* a RAW vector without nulls is read in place, its bytes + * counted as delivered (a view, not a decode) */ + const bool raw = (c == 0 ? ca : c == 1 ? cb : cc)[RAY_ENC_RAW] > 0; + if (g && !g_aw_unaligned) + TEST_ASSERT_FMT((raw || k.decoded_bytes == 0) && k.materialized == 0, "%s: decoded %llu", cols[c], + (unsigned long long)k.decoded_bytes); + } + for (int w = 0; w < 2; w++) { + char q[1600]; + if (w) { + char lst[128 * 8] = "["; + for (int64_t i = 0; i < ni; i++) + snprintf(lst + strlen(lst), sizeof lst - strlen(lst), "%s%lld", i ? " " : "", (long long)ids[i]); + strcat(lst, "]"); + snprintf(q, sizeof q, "(at (at (.db.parted.get \"" AW_TMP "/sy0\" 't) '%s) %s)", cols[c], lst); + } else { + snprintf(q, sizeof q, "(at (at (.db.parted.get \"" AW_TMP "/sy0\" 't) '%s) (where (or (== 5 (%% (til %lld) 997)) " + "(and (>= (til %lld) 2998) (<= (til %lld) 3001)) (== (til %lld) %lld))))", cols[c], + (long long)n, (long long)n, (long long)n, (long long)n, (long long)(n - 1)); + } + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + AW_GATHER_REF(out[0][w], ref, false, cols[c]); + AW_GATHER_REF(out[1][w], ref, false, cols[c]); + ray_release(ref); + test_result_t r = aw_vec_same(out[0][w], out[1][w], cols[c]); + if (r.status != TEST_PASS) return r; + ray_release(out[0][w]); ray_release(out[1][w]); + } + } + ray_rowsel_release(sel); ray_release(pred); + ray_release(tp[0]); ray_release(tp[1]); + PASS(); +} + +/* Task 10b: HEAD(SORT) under a lazy selection over a parted table (late + * materialization). The keys are compacted and top-k'd, then only the + * winners' rows of every column gathered: the answer is the full sort's + * first rows (ties kept by row order, nulls where the sort puts them), + * on both generations, and generation 2's equals generation 0's. k has + * ties and nulls, s is a SYM key (string order), f an F64 key with nulls, + * w a STR key and payload, t the row number; one selection holds whole + * segments (ALL) beside partial ones. Takes at the selection's rows minus + * one (late) and at or past them, an empty selection and a LIST column + * keep the old route (counter unchanged). */ +static test_result_t aw_late_same(const char* t0, const char* t2, const char* q, const char* ref, bool late) { + uint64_t h0 = ray_sort_test_late_heads(); + AW_CSV_SAME(t0, t2, q, 0); + uint64_t got = ray_sort_test_late_heads() - h0; + TEST_ASSERT_FMT(got == (late ? 2u : 0u), "%s: %llu late heads", q, (unsigned long long)got); + /* generation 0's answer is the full sort's first rows */ + char buf[600]; char* csv[2]; size_t len[2]; + snprintf(buf, sizeof buf, "(set T %s)", t0); + aw_eval_ok(buf); + for (int w = 0; w < 2; w++) { + ray_t* r = ray_eval_str(w ? ref : q); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "%s: %s", w ? ref : q, ray_error_msg()); + ray_env_set(ray_sym_intern("R", 1), r); + ray_release(r); + csv[w] = aw_csv("R", w ? "lr" : "lq", &len[w]); + } + bool same = csv[0] && csv[1] && len[0] == len[1] && memcmp(csv[0], csv[1], len[0]) == 0; + free(csv[0]); free(csv[1]); + aw_eval_ok("(set R 0)"); + TEST_ASSERT_FMT(same, "%s: differs from the full sort's first rows", q); + PASS(); +} +#define AW_LATE_SAME(a, b, q, r, l) do { test_result_t r_ = aw_late_same((a), (b), (q), (r), (l)); if (r_.status != TEST_PASS) return r_; } while (0) + +static test_result_t test_sort_head_late(void) { + static const int64_t np[2] = { 3000, 37000 }; + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[2400]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/sl%d/2024.01.0%d/t/\" " + "(table [k v s t f w] (list (map (fn [j] (if (== 0 (%% j 101)) 0N (%% (* j 7919) 50))) (til %lld)) " + "(as 'I32 (%% (* (til %lld) 31) 1000)) " + "(as 'SYMBOL (map (fn [j] (format \"s%%\" (%% j 37))) (til %lld))) (+ %lld (til %lld)) " + "(map (fn [j] (if (== 0 (%% j 89)) 0Nf (* 0.5 (%% (* j 13) 400)))) (til %lld)) " + "(map (fn [j] (if (== 0 (%% j 71)) \"\" (format \"a pooled string %%\" (%% (* j 17) 53)))) (til %lld)))) " + "\"" AW_TMP "/sl%d/.sym\" {compress: %s})", gen, p + 1, (long long)np[p], (long long)np[p], + (long long)np[p], (long long)(p ? np[0] : 0), (long long)np[p], (long long)np[p], (long long)np[p], + gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + const char* t0 = "(.db.parted.get \"" AW_TMP "/sl0\" 't)"; + const char* t2 = "(.db.parted.get \"" AW_TMP "/sl2\" 't)"; + static const struct { const char* q; const char* ref; bool late; } qs[] = { + { "(select {from: T where: (> v 900) asc: k take: 25})", + "(take (select {from: T where: (> v 900) asc: k}) 25)", true }, + { "(select {from: T where: (> v 900) desc: k take: 25})", + "(take (select {from: T where: (> v 900) desc: k}) 25)", true }, + { "(select {from: T where: (< v 500) asc: [k s] take: 40})", + "(take (select {from: T where: (< v 500) asc: [k s]}) 40)", true }, + { "(select {from: T where: (== (% v 7) 3) desc: s take: 12})", + "(take (select {from: T where: (== (% v 7) 3) desc: s}) 12)", true }, + { "(select {from: T where: (> v 700) asc: w take: 15})", /* a STR key */ + "(take (select {from: T where: (> v 700) asc: w}) 15)", true }, + { "(select {from: T where: (< v 300) desc: f take: 9})", /* an F64 key with nulls */ + "(take (select {from: T where: (< v 300) desc: f}) 9)", true }, + { "(select {from: T where: (< v 300) asc: [f w] take: 30})", + "(take (select {from: T where: (< v 300) asc: [f w]}) 30)", true }, + { "(select {from: T where: (or (< t 2048) (== 0 (% v 3))) asc: t take: 2100})", + "(take (select {from: T where: (or (< t 2048) (== 0 (% v 3))) asc: t}) 2100)", true }, + { "(select {from: T where: (or (< t 2048) (== 0 (% v 3))) desc: v take: 50})", /* part of the ALL segments */ + "(take (select {from: T where: (or (< t 2048) (== 0 (% v 3))) desc: v}) 50)", true }, + { "(select {from: T where: (> v 998) asc: k take: 5000})", + "(select {from: T where: (> v 998) asc: k})", false }, /* a longer take would cycle */ + { "(select {from: T where: (> v 5000) asc: k take: 5})", /* an empty selection */ + "(select {from: T where: (> v 5000) asc: k})", false }, + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) AW_LATE_SAME(t0, t2, qs[i].q, qs[i].ref, qs[i].late); + /* K at the selection's rows minus one (the late route) and at them (the + * old route: the shortcut needs K below the rows) */ + aw_eval_ok("(set T (.db.parted.get \"" AW_TMP "/sl0\" 't))"); + ray_t* cnt = ray_eval_str("(count (select {from: T where: (> v 990)}))"); + TEST_ASSERT_TRUE(cnt && !RAY_IS_ERR(cnt) && cnt->i64 > 2); + const int64_t pass = cnt->i64; + ray_release(cnt); + for (int e = 0; e < 2; e++) { + char q[300], ref[300]; + snprintf(q, sizeof q, "(select {from: T where: (> v 990) desc: k take: %lld})", (long long)(pass - 1 + e)); + if (e) snprintf(ref, sizeof ref, "(select {from: T where: (> v 990) desc: k})"); + else snprintf(ref, sizeof ref, "(take (select {from: T where: (> v 990) desc: k}) %lld)", (long long)(pass - 1)); + AW_LATE_SAME(t0, t2, q, ref, e == 0); + } + /* a LIST column: ray_topk_table declines, so the late route does too + * (generation 0: LIST stays plain in either store) */ + for (int p = 0; p < 2; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/sll/2024.01.0%d/t/\" " + "(table [k v l] (list (%% (* (til 3000) 7919) 50) (%% (til 3000) 10) (map (fn [j] (list j)) (til 3000)))))", + p + 1); + aw_eval_ok(q); + } + aw_eval_ok("(set T (.db.parted.get \"" AW_TMP "/sll\" 't))"); + { + uint64_t h0 = ray_sort_test_late_heads(); + ray_t* a = ray_eval_str("(select {from: T where: (> v 5) asc: k take: 7})"); + ray_t* r = ray_eval_str("(take (select {from: T where: (> v 5) asc: k}) 7)"); + TEST_ASSERT_FMT(a && r && !RAY_IS_ERR(a) && !RAY_IS_ERR(r), "LIST: %s", ray_error_msg()); + TEST_ASSERT_EQ_U(ray_sort_test_late_heads(), h0); + ray_t* fa = ray_fmt(a, 0); ray_t* fr = ray_fmt(r, 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fr) && memcmp(ray_str_ptr(fa), ray_str_ptr(fr), ray_str_len(fa)) == 0, + "LIST: differs from the full sort's first rows"); + ray_release(fa); ray_release(fr); ray_release(a); ray_release(r); + } + PASS(); +} + +/* First-n on runs: keys whose vectors are run views (h: runs of 11; s: a + * SYM in runs of 7, every 13th run "", the in-band null) are probed once + * per span of equal tuples, without decoding (agg_firstn_runs). h decodes + * only the vector pass 1 reads through its cursor; the sample point-reads + * it and pass 2 reads its runs. With a where: the table is compacted + * first (firstn_sel installs a selection itself); answers and order are + * generation 0's. */ +static test_result_t test_firstn_runs(void) { + aw_save("fr", "(table [h s] (list (% (* (div (til 300000) 11) 7919) 100003) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (% (div j 7) 13)) \"\" (format \"r%\" (% (div j 7) 97)))) (til 300000)))))", + RAY_ENC_RLE); + for (int64_t v = 0; v < 290; v += 41) { + TEST_ASSERT_EQ_I(aw_vec_enc("fr", "h", v), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("fr", "s", v), RAY_ENC_RLE); + } + static const char* const qs[] = { + "(select {c: (count h) from: T by: {h: h s: s} take: 10})", + "(select {c: (count h) m: (max h) from: T where: (!= s 'r5) by: {s: s h: h} take: 7})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + agg_route_reset(); + AW_SAME("fr", qs[i], 0); + TEST_ASSERT_FMT(agg_route_stats().first_n == 2, "%s: first-n %llu", qs[i], (unsigned long long)agg_route_stats().first_n); + if (i == 0) /* the where: compacts the table first (HEAD(GROUP) over a selection): all of h gathered */ + TEST_ASSERT_FMT(aw_col_decoded("h") == 1024 * 8, "%s: h decoded %llu", qs[i], (unsigned long long)aw_col_decoded("h")); + } + PASS(); +} + +/* The parallel strategies' selection reads (agg_idx_walk) with few rows + * per vector: every 40th row of 3M (25 or 26 per vector, under both + * codecs' D2 limits; above the parallel threshold) grouped by two I32 + * keys read at those rows by point reads into the walk's sparse views, + * by the table-stack sampler and by the dense plan's bounds: neither key + * decodes a vector. */ +static test_result_t test_sparse_walk_points(void) { + aw_save("sw", "(table [a b v w] (list (as 'I32 (% (* (div (til 3000000) 7) 7919) 1000)) (as 'I32 (% (div (til 3000000) 50000) 7)) " + "(til 3000000) (% (* (til 3000000) 7919) 3000017)))", -1); + for (int64_t v = 0; v < 2900; v += 397) { + int ea = aw_vec_enc("sw", "a", v), eb = aw_vec_enc("sw", "b", v); + TEST_ASSERT_FMT(ea == RAY_ENC_RLE || ea == RAY_ENC_FOR_BP, "a vector %lld: %d", (long long)v, ea); + TEST_ASSERT_FMT(eb == RAY_ENC_RLE || eb == RAY_ENC_CONST, "b vector %lld: %d", (long long)v, eb); + } + static const char* const qs[] = { + "(select {n: (count a) from: T where: (== 0 (% v 40)) by: {a: a b: b} desc: n take: 10})", + "(select {n: (count a) s: (sum v) from: T where: (== 0 (% v 40)) by: a})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + AW_SAME("sw", qs[i], 0); + TEST_ASSERT_FMT(aw_col_decoded("a") == 0 && aw_col_decoded("b") == 0, "%s: a %llu b %llu", qs[i], + (unsigned long long)aw_col_decoded("a"), (unsigned long long)aw_col_decoded("b")); + } + /* the dense plan's row probe (agg_sel_bounds_impossible): by {a w}, + * w spread (FOR_BP, point-read), so 64 probed rows already span more + * slots than the 75000 selected rows; the plan is declined before any + * bounds scan, the answer is generation 0's, and the plan of {a b} + * (it fits) is not */ + uint64_t p0 = ray_agg_test_sel_probe_hits(); + AW_SAME("sw", "(select {n: (count a) from: T where: (== 0 (% v 40)) by: {a: a w: w} desc: n take: 5})", 0); + TEST_ASSERT_FMT(ray_agg_test_sel_probe_hits() == p0 + 1, "probe hits %llu", (unsigned long long)(ray_agg_test_sel_probe_hits() - p0)); + p0 = ray_agg_test_sel_probe_hits(); + AW_SAME("sw", qs[0], 0); + TEST_ASSERT_EQ_U(ray_agg_test_sel_probe_hits(), p0); + PASS(); +} + +/* A SYM group key read like ClickBench q13 (P3 Task 14b). Its rows are + * 600000 (ten chunks): the selected third (f == 0) holds 100 bulk symbols + * and, once each, the symbol interned first (row 0) and the last selected + * row's symbol, interned after 400000 unselected ones. The exact id range + * of the selected rows exceeds their count, so the dense plan is + * impossible; 64 evenly spaced selected rows span only the bulk (and row + * 0), so the row probe alone is undecided, and the chunks holding the + * directory's lowest minimum and highest maximum (two of ten) decide it: + * no bounds scan of every selected row. The answer (a tied top 5: emit + * order) is generation 0's; nothing is materialized. */ +static test_result_t test_sym_key_chunk_extremes(void) { + aw_save("pq", "(table [s f] (list (as 'SYMBOL (map (fn [j] (if (== j 0) \"plo\" (if (== j 599997) \"phi\" " + "(if (== 0 (% j 3)) (format \"b%\" (% j 100)) (format \"u%\" j))))) (til 600000))) " + "(as 'I32 (% (til 600000) 3))))", -1); + const char* q = "(select {c: (count s) from: T where: (== f 0) by: s desc: c take: 5})"; + uint64_t p0 = ray_agg_test_sel_probe_hits(); + AW_SAME("pq", q, 0); + TEST_ASSERT_FMT(ray_agg_test_sel_probe_hits() == p0 + 1, "probe hits %llu", (unsigned long long)(ray_agg_test_sel_probe_hits() - p0)); + /* without the two extremes selected (f == 1: u symbols only, ids + * within the selected count of each other) the plan is not proved + * impossible, and the answer still agrees */ + p0 = ray_agg_test_sel_probe_hits(); + AW_SAME("pq", "(select {c: (count s) from: T where: (and (== f 0) (!= s 'plo) (!= s 'phi)) by: s desc: c take: 5})", 0); + TEST_ASSERT_EQ_U(ray_agg_test_sel_probe_hits(), p0); + PASS(); +} + +/* SYM keys read by point reads (agg_src_points: ids through + * ray_col_src_gather_points) in the selection walk, the table-stack + * samplers and the dense plan's probe: every 20th of 1.5M rows (51 per + * vector, under the RLE limit), a SYM key on runs of 7 and an I32 one. + * The SYM key decodes no vector; the answers are generation 0's. */ +static test_result_t test_sym_key_points(void) { + aw_save("sp", "(table [k b v] (list (at (as 'SYMBOL (map (fn [x] (format \"k%\" x)) (til 1000))) " + "(% (div (til 1500000) 7) 1000)) (as 'I32 (% (div (til 1500000) 50000) 7)) (til 1500000)))", -1); + for (int64_t v = 0; v < 1400; v += 197) + TEST_ASSERT_FMT(aw_vec_enc("sp", "k", v) == RAY_ENC_RLE, "k vector %lld: %d", (long long)v, aw_vec_enc("sp", "k", v)); + static const char* const qs[] = { + "(select {n: (count k) from: T where: (== 0 (% v 20)) by: {k: k b: b} desc: n take: 10})", + "(select {n: (count k) s: (sum v) from: T where: (== 0 (% v 20)) by: k})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + AW_SAME("sp", qs[i], 0); + TEST_ASSERT_FMT(aw_col_decoded("k") == 0, "%s: k decoded %llu", qs[i], (unsigned long long)aw_col_decoded("k")); + } + PASS(); +} + +/* A selection whose program is one encoded leaf is emitted from the + * vector's view (expr_leaf_emit): an RLE vector from its runs, a CONST + * one as a uniform segment, any other through the evaluator's bools. + * The selection is byte-for-byte generation 0's under every operator, + * for an I32 column on runs of 3 and a SYM one alternating "" runs with + * symbols (both forced RLE); a nullable RLE column (a bitmap) keeps the + * bools. */ +static ray_op_t* ap_x_lt500(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "x"), ray_const_i64(g, 500)); } +static test_result_t test_leaf_emit_runs(void) { + aw_save("lr", "(table [x s] (list (as 'I32 (div (% (til 300000) 3000) 3)) " + "(as 'SYMBOL (map (fn [j] (if (< (% j 10) 6) \"\" (format \"w%\" (% (div j 10) 50)))) (til 300000)))))", RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("lr", "x", 5), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("lr", "s", 5), RAY_ENC_RLE); + ray_op_t* (*const ps[])(ray_graph_t*) = { ap_x_eq7, ap_x_gt10, ap_x_lt500, ap_s_ne_empty, ap_s_eq_empty, ap_s_eq, NULL }; + for (int i = 0; ps[i]; i++) { + int64_t r0 = ray_expr_test_leaf_runs(); + test_result_t r = aw_sel_same("lr", ps[i], -1); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(ray_expr_test_leaf_runs() > r0, "predicate %d: no segment from runs", i); + } + aw_save("ln", "(table [x] (list (as 'I32 (map (fn [j] (if (== 0 (% j 50)) 0N (div (% j 3000) 3))) (til 300000)))))", RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("ln", "x", 5), RAY_ENC_RLE); + ray_op_t* (*const pn[])(ray_graph_t*) = { ap_x_eq7, ap_x_gt10, ap_x_lt500, NULL }; + for (int i = 0; pn[i]; i++) { + int64_t r0 = ray_expr_test_leaf_runs(); + test_result_t r = aw_sel_same("ln", pn[i], -1); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_EQ_I(ray_expr_test_leaf_runs(), r0); /* a bitmap: the bools */ + } + PASS(); +} + +/* The direct-array prescan of a staged key that cannot fit (ClickBench + * q29: by a wide SYM key beside avg (strlen key), the group.c route) stops + * as the plain scan does, once a worker's bounds exceed the slot budget: + * 900000 rows, the first 300000 interning 300000 symbols in row order + * (unselected), the selected 600000 spreading their ids over all of them + * in every vector. The walk reads eight vectors at a time and checks the + * worker's bounds after each piece, so it stops within a few vectors per + * worker, not after every selected row. The answer is generation 0's. */ +static test_result_t test_da_prescan_abort_staged(void) { + aw_save("dp", "(table [s f] (list (at (as 'SYMBOL (map (fn [x] (format \"r%\" x)) (til 300000))) " + "(raze (list (til 300000) (% (* (til 600000) 7919) 300000)))) (til 900000)))", -1); + const char* q = "(select {n: (count l) t: (sum l) m: (max c) from: (select {l: (avg (strlen s)) c: (count s) " + "from: T where: (>= f 300000) by: s})})"; + int64_t r0 = ray_group_test_minmax_staged_rows(); + AW_SAME("dp", q, 0); + int64_t dr = ray_group_test_minmax_staged_rows() - r0; + TEST_ASSERT_FMT(dr > 0 && dr <= 150000, "staged prescan rows %lld", (long long)dr); + PASS(); +} + +/* The first-n passes under a selection (the language compacts a where: + * before an unordered take, so a C caller installs the rowsel): every + * third row dropped (MIX segments), keys on runs (agg_firstn_runs) and, + * for a key set over the RLE keys plus a FOR_BP one, through the cursor + * pieces (agg_firstn_piece). Results and order equal generation 0's; + * nothing is materialized. */ +static ray_t* aw_firstn_sel_run(ray_t* t, int with_v, int64_t limit) { + ray_graph_t* g = ray_graph_new(t); + ray_t* pred = ray_vec_new(RAY_BOOL, 300000); pred->len = 300000; + for (int64_t r = 0; r < 300000; r++) ((uint8_t*)ray_data(pred))[r] = r % 3 != 0; + g->selection = ray_rowsel_from_pred(pred); + ray_release(pred); + ray_op_t* keys[3] = { ray_scan(g, "h"), ray_scan(g, "s"), with_v ? ray_scan(g, "v") : NULL }; + ray_op_t* ins[2] = { ray_scan(g, "h"), ray_scan(g, "h") }; + uint16_t ops[2] = { OP_COUNT, OP_MAX }; + ray_op_t* grp = ray_group(g, keys, with_v ? 3 : 2, ops, ins, 2); + ray_t* r = exec_group(g, grp, t, limit); + ray_graph_free(g); + return r; +} +static test_result_t test_firstn_sel(void) { + aw_save("fs", "(table [h s v] (list (% (* (div (til 300000) 11) 7919) 100003) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (% (div j 7) 13)) \"\" (format \"r%\" (% (div j 7) 97)))) (til 300000))) " + "(% (div (til 300000) 3) 5)))", RAY_ENC_RLE); + ray_t* t[2] = { aw_load("fs", 0), aw_load("fs", 2) }; + TEST_ASSERT_TRUE(t[0] && t[1]); + for (int with_v = 0; with_v < 2; with_v++) + for (int64_t limit = 5; limit <= 40; limit += 35) { + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + ray_enc_counters_reset(); + agg_route_reset(); + out[gen] = aw_firstn_sel_run(t[gen], with_v, limit); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "gen %d v %d: %s", gen, with_v, ray_error_msg()); + TEST_ASSERT_FMT(agg_route_stats().first_n == 1, "gen %d v %d: not first-n", gen, with_v); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (gen) TEST_ASSERT_EQ_U(k.materialized, 0); + } + TEST_ASSERT_EQ_I(ray_table_nrows(out[0]), limit); + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "v %d limit %lld differs", with_v, (long long)limit); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + ray_release(t[0]); ray_release(t[1]); + PASS(); +} + +/* q42's filter: a chained where: over generation-2 predicate columns is + * refined on the segments the selection keeps, through the encoded leaves + * (exec_pred_refine_selection), so no predicate value is gathered: p, + * r and the nullable q (every vector RLE) decode nothing; answers equal + * generation 0's, nulls failing their compare. */ +static test_result_t test_refine_on_views(void) { + aw_save("rv", "(table [c p r q g v] (list (div (til 300000) 3000) (% (* (til 300000) 7) 13) (div (til 300000) 300) " + "(map (fn [j] (if (== 0 (% j 11)) 0N (% j 6))) (til 300000)) (% (til 300000) 5) (til 300000)))", RAY_ENC_RLE); + static const char* const qs[] = { + "(select {n: (count v) s: (sum v) from: T where: (and (== c 62) (== p 3)) by: g})", + "(select {n: (count v) from: T where: (and (>= c 40) (<= c 41) (> r 405) (< p 9)) by: g})", + "(select {n: (count v) from: T where: (and (== c 7) (> q 2)) by: g})", + "(select {n: (count v) from: T where: (and (== c 7) (== p 100)) by: g})", + NULL, + }; + for (int64_t v = 0; v < 290; v += 37) { + TEST_ASSERT_EQ_I(aw_vec_enc("rv", "r", v), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("rv", "p", v), RAY_ENC_RLE); + } + for (int i = 0; qs[i]; i++) { + AW_SAME("rv", qs[i], 0); + TEST_ASSERT_FMT(aw_col_decoded("p") == 0 && aw_col_decoded("r") == 0 && aw_col_decoded("q") == 0, + "%s: p %llu r %llu q %llu", qs[i], (unsigned long long)aw_col_decoded("p"), + (unsigned long long)aw_col_decoded("r"), (unsigned long long)aw_col_decoded("q")); + } + PASS(); +} + +/* Equality on runs: answered on the vectors' run views, a run scan + * deciding a vector whose runs never hold the constant without per-run + * fills (enceval's runs_hold). I64 runs with RAW values (h: spread + * hashes) and I16 runs with packed ones (s); the constant held in some + * vectors, in none, outside the I16 range; == and !=, run twice. Answers + * equal generation 0's and nothing decodes. */ +static test_result_t test_eq_runs_lack(void) { + aw_save("rl", "(table [h s v] (list (* 1000000007 (% (* (div (til 70000) 3) 7919) 100003)) " + "(as 'I16 (% (div (til 70000) 5) 300)) (til 70000)))", RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("rl", "h", 3), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("rl", "s", 3), RAY_ENC_RLE); + static const char* const qs[] = { + "(select {n: (count v) s: (sum v) from: T where: (== h 7919000055433)})", /* j div 3 = 1 */ + "(select {n: (count v) from: T where: (== h 5)})", + "(select {n: (count v) s: (sum v) from: T where: (!= h 7919000055433)})", + "(select {n: (count v) s: (sum v) from: T where: (== s 17)})", + "(select {n: (count v) from: T where: (== s 100000)})", + "(select {n: (count v) from: T where: (!= s 100000)})", + NULL, + }; + for (int rep = 0; rep < 2; rep++) + for (int i = 0; qs[i]; i++) { + AW_SAME("rl", qs[i], 0); + TEST_ASSERT_FMT(g_aw_unaligned || (aw_col_decoded("h") == 0 && aw_col_decoded("s") == 0), "%s: h %llu s %llu", qs[i], + (unsigned long long)aw_col_decoded("h"), (unsigned long long)aw_col_decoded("s")); + } + PASS(); +} + +/* Review focus 5: sums at the I64 extremes with nulls, from the directory, + * on a column without a recorded CHUNK_ZONE (the C3 gate does not cover it). */ +static test_result_t test_sum_extremes(void) { + /* the converter records a CHUNK_ZONE for a plain column of this size; a + * plain ZONE already on it stands in, so the column has none to answer from */ + aw_save("sx", "(table [x] (list (.idx.zone (as 'I64 (map (fn [j] (if (== 0 (% j 7)) 0N (if (== 0 (% j 2)) 9223372036854775807 -9223372036854775807))) (til 200000))))))", -1); + test_result_t r; + if ((r = aw_reduce("sx", "(sum (at T 'x))", 0)).status != TEST_PASS) return r; + ray_t* ix = ray_eval_str(ray_test_tmp("(at (.idx.info T 'x) 'index)")); + TEST_ASSERT_TRUE(ix && !RAY_IS_ERR(ix) && ix->type == -RAY_SYM && + ix->i64 == ray_sym_intern("zone", 4)); /* not chunk_zone: no recorded CHUNK_ZONE */ + ray_release(ix); + if ((r = aw_reduce("sx", "(avg (at T 'x))", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sx", "(count (at T 'x))", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sx", "(min (at T 'x))", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sx", "(max (at T 'x))", 0)).status != TEST_PASS) return r; + /* a total beyond INT64_MAX: the wrapped low word for sum, the exact 128-bit mean for avg */ + aw_save("sw", "(table [x] (list (.idx.zone (as 'I64 (map (fn [j] (if (== 0 (% j 5)) 0N 9223372036854775807)) (til 200000))))))", -1); + static const char* const swag[] = { "sum", "avg", "min", "max" }; + for (int i = 0; i < 4; i++) { + char q[80]; snprintf(q, sizeof q, "(%s (at T 'x))", swag[i]); + if ((r = aw_reduce("sw", q, 0)).status != TEST_PASS) return r; + } + /* planning-time answers keep generation 0's CHUNK_ZONE gate (D5): this one decodes, equal */ + if ((r = aw_reduce("sx", "(select {s: (sum x) a: (avg x) mx: (max x) from: T})", -1)).status != TEST_PASS) return r; + PASS(); +} + +/* Parted: two generation-2 partitions and one generation-0 partition. */ +static test_result_t test_sum_parted_dir(void) { + for (int p = 0; p < 3; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/sp/2024.01.0%d/t/\" " + "(table [x y] (list (as 'I32 (map (fn [j] (if (== 0 (%% j 11)) 0N (- j 50000))) (til 90000))) " + "(map (fn [j] (if (== 0 (%% j 11)) 0N (- 9223372036854775807 (%% j 3)))) (til 90000)))) {compress: %s})", + p + 1, p == 1 ? "false" : "true"); + aw_eval_ok(q); + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/sq/2024.01.0%d/t/\" " + "(table [x y] (list (as 'I32 (map (fn [j] (if (== 0 (%% j 11)) 0N (- j 50000))) (til 90000))) " + "(map (fn [j] (if (== 0 (%% j 11)) 0N (- 9223372036854775807 (%% j 3)))) (til 90000)))) {compress: false})", p + 1); + aw_eval_ok(q); + } + static const char* const aggs[] = { "sum", "avg", "min", "max", "count", NULL }; + for (int c = 0; c < 2; c++) + for (int i = 0; aggs[i]; i++) { + char a[300], b[300]; + snprintf(a, sizeof a, "(%s (at (.db.parted.get \"" AW_TMP "/sq\" 't) '%c))", aggs[i], c ? 'y' : 'x'); + snprintf(b, sizeof b, "(%s (at (.db.parted.get \"" AW_TMP "/sp\" 't) '%c))", aggs[i], c ? 'y' : 'x'); + ray_t* x = aw_eval(a); + ray_enc_counters_reset(); + ray_t* y = aw_eval(b); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(x && y && !RAY_IS_ERR(x) && !RAY_IS_ERR(y)); + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); + TEST_ASSERT_FMT(ray_str_len(fx) == ray_str_len(fy) && memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0, "%s", aggs[i]); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* the generation-0 partition is read in place */ + ray_release(fx); ray_release(fy); ray_release(x); ray_release(y); + } + PASS(); +} + +/* A ragged parted table: partition 2 lacks the column (a synthetic stand-in), + * 1 and 3 are generation 2, 4 generation 0. Results equal the + * all-generation-0 table's. A nullable stand-in is all null and decodes + * nothing; a BOOL / U8 one is non-null zeros (ray_null_fill), so min is 0 + * and avg counts its rows, and the select form agrees with the scalar one. */ +static test_result_t test_sum_parted_ragged(void) { + static const struct { const char* name; const char* col; const char* zero; bool nullable; } ty[] = { + { "i64", "(map (fn [j] (if (== 0 (% j 13)) 0N (- j 70000))) (til 80000))", NULL, true }, + { "u8", "(as 'U8 (+ 1 (% (til 80000) 200)))", "(as 'U8 0)", false }, + { "bool", "(>= (til 80000) 0)", "(== 1 0)", false }, + }; + static const char* roots[] = { "rw", "rn" }; + static const char* const aggs[] = { "sum", "avg", "min", "max", NULL }; + for (int t = 0; t < 3; t++) { + (void)ray_test_rm_rf(aw_root()); (void)ray_test_mkdir_p(aw_root()); + for (int r = 0; r < 2; r++) + for (int p = 0; p < 4; p++) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s/2024.01.0%d/t/\" %s%s%s {compress: %s})", + roots[r], p + 1, + p == 1 ? "(table [y] (list (til 3000)))" : "(table [y x] (list (til 80000) ", + p == 1 ? "" : ty[t].col, p == 1 ? "" : "))", + r == 0 && p != 3 ? "true" : "false"); + aw_eval_ok(q); + } + aw_eval_ok("(set TW (.db.parted.get \"" AW_TMP "/rw\" 't))"); + aw_eval_ok("(set TN (.db.parted.get \"" AW_TMP "/rn\" 't))"); + for (int i = 0; aggs[i]; i++) { + char a[300], b[300], c[300]; + snprintf(a, sizeof a, "(%s (at TN 'x))", aggs[i]); + snprintf(b, sizeof b, "(%s (at TW 'x))", aggs[i]); + snprintf(c, sizeof c, "(first (at (select {m: (%s x) from: TW}) 'm))", aggs[i]); + ray_t* x = aw_eval(a); + ray_enc_counters_reset(); + ray_t* y = aw_eval(b); + ray_enc_counters_t k; ray_enc_counters_get(&k); + ray_t* z = aw_eval(c); + TEST_ASSERT_TRUE(x && y && z && !RAY_IS_ERR(x) && !RAY_IS_ERR(y) && !RAY_IS_ERR(z)); + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); ray_t* fz = ray_fmt(z, 0); + TEST_ASSERT_FMT(ray_str_len(fx) == ray_str_len(fy) && memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0, + "%s %s: gen 0 vs mixed", ty[t].name, aggs[i]); + TEST_ASSERT_FMT(ray_str_len(fz) == ray_str_len(fy) && memcmp(ray_str_ptr(fz), ray_str_ptr(fy), ray_str_len(fz)) == 0, + "%s %s: select vs scalar", ty[t].name, aggs[i]); + TEST_ASSERT_EQ_U(k.materialized, 0); + if (ty[t].nullable) TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + if (ty[t].zero && i == 2) { /* min: the stand-in's zero wins */ + ray_t* zr = aw_eval(ty[t].zero); + ray_t* fr = ray_fmt(zr, 0); + TEST_ASSERT_FMT(ray_str_len(fr) == ray_str_len(fy) && memcmp(ray_str_ptr(fr), ray_str_ptr(fy), ray_str_len(fr)) == 0, + "%s min is the stand-in's zero", ty[t].name); + ray_release(fr); ray_release(zr); + } + ray_release(fx); ray_release(fy); ray_release(fz); ray_release(x); ray_release(y); ray_release(z); + } + } + PASS(); +} + +/* `q` on 0 and 2: the result atoms' f64 bits are equal (ray_fmt + * clears the sign of zero, so comparing text pins nothing), no + * materialization, and want_decoded bytes decoded by generation 2 (-1: not + * checked). */ +static test_result_t aw_f64_bits(const char* name, const char* q, int64_t want_decoded) { + ray_t* out[2]; + uint64_t dec = 0; + for (int gen = 0; gen < 2; gen++) { + char buf[512]; + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s%d/\"))", name, gen ? 2 : 0); + aw_eval_ok(buf); + ray_enc_counters_reset(); + out[gen] = ray_eval_str(ray_test_tmp(q)); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]) && out[gen]->type == -RAY_F64, "%s gen %d", q, gen); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (gen) { dec = k.decoded_bytes; TEST_ASSERT_EQ_U(k.materialized, 0); } + } + TEST_ASSERT_FMT(memcmp(&out[0]->f64, &out[1]->f64, sizeof(double)) == 0, "%s: f64 bits differ (%g vs %g)", q, + out[0]->f64, out[1]->f64); + if (want_decoded >= 0) TEST_ASSERT_FMT(dec == (uint64_t)want_decoded, "%s: decoded %llu, want %lld", q, + (unsigned long long)dec, (long long)want_decoded); + ray_release(out[0]); ray_release(out[1]); + PASS(); +} + +/* Float sums decode and stay bit-identical, -0.0 included; float min / max + * come from the directory (D4: decoded 0) with the same bits. */ +static test_result_t test_float_sum_decoded(void) { + test_result_t r; + aw_save("fs", "(table [f] (list (map (fn [j] (if (< j 1024) -0.0 (* 0.1 j))) (til 3000))))", -1); + if ((r = aw_f64_bits("fs", "(sum (at T 'f))", -1)).status != TEST_PASS) return r; + if ((r = aw_f64_bits("fs", "(avg (at T 'f))", -1)).status != TEST_PASS) return r; + aw_save("fz", "(table [f] (list (take [-0.0] 2048)))", -1); + if ((r = aw_f64_bits("fz", "(sum (at T 'f))", -1)).status != TEST_PASS) return r; /* the sign of zero */ + { /* the literal is a negative zero (the stored value and the D4 min carry the + * sign), so the bit compares pin the sign; the sum is +0.0 on both + * generations: the kernel starts from +0.0 and +0.0 + -0.0 is +0.0 */ + ray_t* z0 = ray_eval_str("(first (at T 'f))"); + ray_t* zm = ray_eval_str("(min (at T 'f))"); + ray_t* zs = ray_eval_str("(sum (at T 'f))"); + TEST_ASSERT_TRUE(z0 && !RAY_IS_ERR(z0) && z0->type == -RAY_F64 && z0->f64 == 0.0 && signbit(z0->f64)); + TEST_ASSERT_TRUE(zm && !RAY_IS_ERR(zm) && zm->type == -RAY_F64 && zm->f64 == 0.0 && signbit(zm->f64)); + TEST_ASSERT_TRUE(zs && !RAY_IS_ERR(zs) && zs->type == -RAY_F64 && zs->f64 == 0.0 && !signbit(zs->f64)); + ray_release(z0); ray_release(zm); ray_release(zs); + } + if ((r = aw_f64_bits("fs", "(min (at T 'f))", 0)).status != TEST_PASS) return r; /* -0.0 under D4 */ + if ((r = aw_f64_bits("fs", "(max (at T 'f))", 0)).status != TEST_PASS) return r; + aw_save("fm", "(table [f] (list (map (fn [j] (if (== 0 (% j 2)) -0.0 0.0)) (til 3000))))", -1); + if ((r = aw_f64_bits("fm", "(min (at T 'f))", 0)).status != TEST_PASS) return r; /* which zero: the first */ + if ((r = aw_f64_bits("fm", "(max (at T 'f))", 0)).status != TEST_PASS) return r; + PASS(); +} + +/* Fully selected vectors are answered from their encoding; the selection + * (< k 1500) keeps vector 0 whole (ALL) and part of vector 1 (MIX), and no + * chunk is fully selected, so the chunk path cannot answer. */ +static test_result_t test_sum_encoded_vectors(void) { + const char* q = "(select {s: (sum x) a: (avg x) from: T where: (< k 1500)})"; + static const struct { const char* name; const char* x; int force; int x_enc; uint64_t want; } cs[] = { + { "sf", "(map (fn [j] (if (== 0 (% j 9)) 0N (- (% j 50) 20))) (til 200000))", RAY_ENC_FOR_BP, RAY_ENC_FOR_BP, 1024 * 4 }, + { "sc", "(map (fn [j] (if (== 0 (% j 9)) 0N (div j 1024))) (til 200000))", -1, RAY_ENC_CONST, 1024 * 4 }, + { "sr", "(div (til 200000) 100)", RAY_ENC_RLE, RAY_ENC_RLE, 1024 * 4 }, + { "sn", "(map (fn [j] (if (== 0 (% j 9)) 0N (div j 100))) (til 200000))", RAY_ENC_RLE, RAY_ENC_RLE, 2 * 1024 * 4 }, /* nullable RLE decodes */ + }; + for (int i = 0; i < 4; i++) { + char tbl[512]; + snprintf(tbl, sizeof tbl, "(table [k x] (list (til 200000) (as 'I32 %s)))", cs[i].x); + aw_save(cs[i].name, tbl, cs[i].force); + TEST_ASSERT_EQ_I(aw_vec_enc(cs[i].name, "x", 0), cs[i].x_enc); + test_result_t r = aw_same(cs[i].name, q, 0); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(g_aw_unaligned || aw_col_decoded("x") == cs[i].want, "%s: x decoded %llu, want %llu", cs[i].name, + (unsigned long long)aw_col_decoded("x"), (unsigned long long)cs[i].want); + } + PASS(); +} + +/* With a selection: ALL segments from vectors, MIX segments decoded. */ +static test_result_t test_agg_under_selection(void) { + aw_save("as", "(table [k x] (list (til 200000) (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (% j 50))) (til 200000)))))", -1); + test_result_t r; + if ((r = aw_reduce("as", "(select {s: (sum x) a: (avg x) c: (count x) from: T where: (< k 65536)})", -1)).status != TEST_PASS) return r; + if ((r = aw_reduce("as", "(select {s: (sum x) c: (count x) from: T where: (< k 1500)})", -1)).status != TEST_PASS) return r; + if ((r = aw_reduce("as", "(select {m: (max x) from: T where: (== x 3)})", -1)).status != TEST_PASS) return r; + PASS(); +} + +static test_result_t test_scalar_route_stats(void) { + aw_save("sq", "(table [k g x f] (list (til 200000) (as 'I16 (% (til 200000) 7)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (% j 50))) (til 200000))) (* 0.5 (til 200000))))", -1); + test_result_t r; + if ((r = aw_reduce("sq", "(select {s: (sum x) c: (count k) a: (avg x) from: T where: (< k 131072)})", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sq", "(select {mn: (min x) mx: (max k) from: T where: (>= k 65536)})", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sq", "(select {s: (sum f) from: T where: (< k 131072)})", -1)).status != TEST_PASS) return r; /* floats: P2's RAW float view (uncounted) or a decode, never statistics */ + if ((r = aw_reduce("sq", "(select {s: (sum x) from: T where: (== g 3)})", -1)).status != TEST_PASS) return r; /* MIX everywhere */ + PASS(); +} + +/* Several inputs of one select, each by its own rule under one selection: + * integer sums and extremes from statistics, a float extreme from + * statistics (D4), a float sum and a SYM extreme decoded (they keep P2's + * dispatch), BOOL / U8 inputs as non-null values, the I64 extremes with a + * total beyond INT64_MAX, an all-null chunk, and selections that cut + * chunks and vectors at odd rows. Every answer equals generation 0. */ +static test_result_t test_scalar_route_mixed(void) { + aw_save("sm", "(table [k x y b u f d s n] (list (til 300000) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (- (% j 50) 20))) (til 300000))) " + "(map (fn [j] (if (== 0 (% j 5)) 0N 9223372036854775807)) (til 300000)) " + "(== 0 (% (til 300000) 3)) (as 'U8 (% (til 300000) 251)) " + "(map (fn [j] (if (== 0 (% j 7)) 0N (- (* 0.25 j) 1000.0))) (til 300000)) " + "(as 'DATE (+ 7000 (div (til 300000) 1000))) " + "(as 'SYM (map (fn [j] (if (== 0 (% j 4)) \"b\" \"a\")) (til 300000))) " + "(as 'I16 (map (fn [j] (if (and (>= j 65536) (< j 131072)) 0N (% j 300))) (til 300000)))))", -1); + static const char* const qs[] = { + "(select {s: (sum x) a: (avg x) mn: (min x) mx: (max x) c: (count x) from: T where: (< k 196608)})", + "(select {s: (sum y) a: (avg y) mx: (max y) from: T where: (>= k 70000)})", + "(select {s: (sum b) a: (avg b) mn: (min b) mx: (max u) su: (sum u) au: (avg u) from: T where: (< k 131072)})", + "(select {mn: (min f) mx: (max f) mx2: (max d) mn2: (min d) from: T where: (< k 196608)})", + "(select {s: (sum n) a: (avg n) mn: (min n) mx: (max n) c: (count n) from: T where: (< k 196608)})", + "(select {s: (sum x) a: (avg x) mn: (min x) mx: (max x) c: (count x) from: T where: (< k 200000)})", + "(select {s: (sum x) mn: (min n) mx: (max f) from: T where: (and (>= k 1000) (< k 250001))})", + "(select {s: (sum x) a: (avg x) mx: (max n) from: T where: (== (% k 3) 1)})", + "(select {s: (sum x) sf: (sum f) from: T where: (< k 131072)})", + "(select {s: (sum x) ms: (min s) from: T where: (< k 131072)})", + "(select {s: (sum x) mx: (max y) a: (avg n) from: T})", + "(select {s: (sum x) c: (count k) from: T where: (> k 400000)})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + test_result_t r = aw_reduce("sm", qs[i], -1); + if (r.status != TEST_PASS) return r; + } + /* whole chunks from the directory and vectors from statistics: nothing decodes */ + test_result_t r; + if ((r = aw_reduce("sm", qs[0], 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sm", qs[3], 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("sm", qs[4], 0)).status != TEST_PASS) return r; + PASS(); +} + +/* TIME sums and extremes and TIMESTAMP extremes under selections: whole + * chunks from the directory, whole vectors (the partial last vector of the + * partial last chunk included, (>= k 199680)) from their views and + * descriptors, every answer generation 0's. */ +static test_result_t test_scalar_route_time(void) { + static const struct { const char* name; int force; } fs[] = { + { "tf", RAY_ENC_FOR_BP }, { "tr", RAY_ENC_RLE }, { "tm", -1 }, + }; + for (int f = 0; f < 3; f++) { + aw_save(fs[f].name, "(table [k t c p] (list (til 200000) " + "(as 'TIME (map (fn [j] (if (== 0 (% j 13)) 0N (* 1000 (- (div j 3) 30000)))) (til 200000))) " + "(as 'TIME (* 1000 (div (til 200000) 1024))) " + "(as 'TIMESTAMP (map (fn [j] (if (== 0 (% j 17)) 0N (* 1000000007 (- j 90000)))) (til 200000)))))", + fs[f].force); + static const char* const qs[] = { + "(select {s: (sum t) a: (avg t) mn: (min t) mx: (max t) sc: (sum c) mc: (max c) pn: (min p) px: (max p) from: T where: (< k 131072)})", + "(select {s: (sum t) a: (avg t) mn: (min t) mx: (max t) sc: (sum c) ac: (avg c) pn: (min p) px: (max p) from: T where: (>= k 199680)})", + "(select {s: (sum t) mx: (max p) sc: (sum c) from: T where: (>= k 197000)})", + "(select {s: (sum t) mn: (min p) from: T where: (== (% k 5) 0)})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + test_result_t r = aw_reduce(fs[f].name, qs[i], -1); + if (r.status != TEST_PASS) return r; + } + /* the partial last vector [199680, 200000) answers at vector level */ + if (fs[f].force == RAY_ENC_FOR_BP) { + test_result_t r = aw_reduce(fs[f].name, qs[1], 0); + if (r.status != TEST_PASS) return r; + } + } + PASS(); +} + +/* Infinite float extremes: generation 0's strict compares from +/-DBL_MAX + * never take +inf as a min or -inf as a max (an all-+inf min is DBL_MAX). + * The statistics hold the infinities; the route reads a non-finite one + * (D4: finite only), and its fold's same strict compares would agree. */ +static test_result_t test_scalar_route_float_inf(void) { + const int64_t n = 200000; + ray_t* k = ray_vec_new(RAY_I64, n); + ray_t* f = ray_vec_new(RAY_F64, n); + TEST_ASSERT_TRUE(k && f && !RAY_IS_ERR(k) && !RAY_IS_ERR(f)); + k->len = f->len = n; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(k))[i] = i; + ((double*)ray_data(f))[i] = i < 70000 ? INFINITY : i < 140000 ? -INFINITY : 0.25 * (double)i; + } + ray_t* tb = ray_table_new(2); + tb = ray_table_add_col(tb, ray_sym_intern("k", 1), k); ray_release(k); + tb = ray_table_add_col(tb, ray_sym_intern("f", 1), f); ray_release(f); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("W", 1), tb), RAY_OK); + ray_release(tb); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/fi0/\" W {compress: false})"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/fi2/\" W {compress: true})"); + static const char* const qs[] = { + "(select {mn: (min f) mx: (max f) from: T where: (< k 65536)})", + "(select {mn: (min f) mx: (max f) from: T where: (and (>= k 65536) (< k 196608))})", + "(select {mn: (min f) mx: (max f) from: T where: (>= k 1024)})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + test_result_t r = aw_reduce("fi", qs[i], -1); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* A ragged parted table under a selection: partition 2 lacks the column (a + * synthetic stand-in), 1 and 3 are generation 2, 4 generation 0. A + * nullable stand-in is all null; a BOOL / U8 one is non-null zeros + * (ray_null_fill), so min is 0 and avg counts its rows. Results equal the + * all-generation-0 table's, and the selected select form equals the scalar + * form over the selected rows. */ +static test_result_t test_scalar_route_parted(void) { + static const struct { const char* name; const char* col; bool nullable; } ty[] = { + { "i32", "(as 'I32 (map (fn [j] (if (== 0 (% j 13)) 0N (- j 70000))) (til 80000)))", true }, + { "u8", "(as 'U8 (+ 1 (% (til 80000) 200)))", false }, + { "bool", "(>= (til 80000) 0)", false }, + }; + static const char* roots[] = { "rw", "rn" }; + static const char* const aggs[] = { "sum", "avg", "min", "max", "count", NULL }; + static const char* const wh[] = { "(>= y 0)", "(< y 70000)", "(>= y 65536)", "(== (% y 5) 2)", NULL }; + for (int t = 0; t < 3; t++) { + (void)ray_test_rm_rf(aw_root()); (void)ray_test_mkdir_p(aw_root()); + for (int r = 0; r < 2; r++) + for (int p = 0; p < 4; p++) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s/2024.01.0%d/t/\" %s%s%s {compress: %s})", + roots[r], p + 1, + p == 1 ? "(table [y] (list (til 3000)))" : "(table [y x] (list (til 80000) ", + p == 1 ? "" : ty[t].col, p == 1 ? "" : "))", + r == 0 && p != 3 ? "true" : "false"); + aw_eval_ok(q); + } + aw_eval_ok("(set TW (.db.parted.get \"" AW_TMP "/rw\" 't))"); + aw_eval_ok("(set TN (.db.parted.get \"" AW_TMP "/rn\" 't))"); + for (int w = 0; wh[w]; w++) + for (int i = 0; aggs[i]; i++) { + char a[400], b[400], c[400]; + snprintf(a, sizeof a, "(first (at (select {m: (%s x) from: TN where: %s}) 'm))", aggs[i], wh[w]); + snprintf(b, sizeof b, "(first (at (select {m: (%s x) from: TW where: %s}) 'm))", aggs[i], wh[w]); + snprintf(c, sizeof c, "(%s (at (select {x: x from: TW where: %s}) 'x))", aggs[i], wh[w]); + ray_t* x = aw_eval(a); + ray_enc_counters_reset(); + ray_t* y = aw_eval(b); + ray_enc_counters_t k; ray_enc_counters_get(&k); + ray_t* z = aw_eval(c); + TEST_ASSERT_FMT(x && y && z && !RAY_IS_ERR(x) && !RAY_IS_ERR(y) && !RAY_IS_ERR(z), "%s %s %s", ty[t].name, aggs[i], wh[w]); + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); ray_t* fz = ray_fmt(z, 0); + TEST_ASSERT_FMT(ray_str_len(fx) == ray_str_len(fy) && memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0, + "%s %s %s: gen 0 vs mixed", ty[t].name, aggs[i], wh[w]); + TEST_ASSERT_FMT(ray_str_len(fz) == ray_str_len(fy) && memcmp(ray_str_ptr(fz), ray_str_ptr(fy), ray_str_len(fz)) == 0, + "%s %s %s: select vs scalar", ty[t].name, aggs[i], wh[w]); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(fx); ray_release(fy); ray_release(fz); ray_release(x); ray_release(y); ray_release(z); + } + } + PASS(); +} + +/* Bytes decoded from column `col` of the parted table named `tbl` (each + * generation-2 segment's own counter). */ +static uint64_t aw_parted_col_decoded(const char* tbl, const char* col) { + ray_t* t = ray_eval_str(tbl); + ray_t* encv = t && !RAY_IS_ERR(t) ? ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))) : NULL; + uint64_t b = 0; + ray_enccol_t* e = encv && encv->type == RAY_ENCCOL ? ray_enccol_of(encv) : NULL; + if (e && e->kind == RAY_ENCCOL_PARTED && e->wrapper) { + ray_t** segs = (ray_t**)ray_data(e->wrapper); + for (int64_t i = 0; i < e->wrapper->len; i++) + if (segs[i] && segs[i]->type == RAY_ENCCOL) b += atomic_load(&ray_enccol_of(segs[i])->decoded_bytes); + } + if (t && !RAY_IS_ERR(t)) ray_release(t); + return b; +} + +/* Parted, every partition generation 2 (each runs the route on its own + * rows): whole chunks under the selection answer from the directory and + * whole vectors from their statistics, so the aggregate input decodes + * nothing; a partly selected vector is read. */ +static test_result_t test_scalar_route_parted_stats(void) { + for (int r = 0; r < 2; r++) + for (int p = 0; p < 3; p++) { + char q[700]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s/2024.01.0%d/t/\" " + "(table [y x] (list (til 70001) (as 'I32 (map (fn [j] (if (== 0 (%% j 11)) 0N (- (%% j 50) 20))) (til 70001))))) {compress: %s})", + r ? "pn" : "pw", p + 1, r ? "false" : "true"); + aw_eval_ok(q); + } + aw_eval_ok("(set TW (.db.parted.get \"" AW_TMP "/pw\" 't))"); + aw_eval_ok("(set TN (.db.parted.get \"" AW_TMP "/pn\" 't))"); + static const char* const qs[] = { + "(select {s: (sum x) mn: (min x) mx: (max x) c: (count x) from: %s where: (< y 65536)})", + "(select {s: (sum x) mn: (min x) mx: (max x) c: (count x) from: %s where: (>= y 2048)})", + "(select {s: (sum x) mx: (max x) from: %s where: (== (%% y 4) 1)})", + /* a nullable avg counts its non-nulls per partition through an + * indicator expression (#767), evaluated over every row: equal only */ + "(select {s: (sum x) a: (avg x) from: %s where: (< y 65536)})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + char a[400], b[400]; + snprintf(a, sizeof a, qs[i], "TN"); + snprintf(b, sizeof b, qs[i], "TW"); + ray_t* x = aw_eval(a); + ray_enc_counters_reset(); + ray_t* y = aw_eval(b); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(x && y && !RAY_IS_ERR(x) && !RAY_IS_ERR(y), "%s", b); + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); + TEST_ASSERT_FMT(ray_str_len(fx) == ray_str_len(fy) && memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0, "%s", b); + TEST_ASSERT_EQ_U(k.materialized, 0); + if (i < 2 && !g_aw_unaligned) TEST_ASSERT_FMT(aw_parted_col_decoded("TW", "x") == 0, "%s: x decoded %llu", b, + (unsigned long long)aw_parted_col_decoded("TW", "x")); + ray_release(fx); ray_release(fy); ray_release(x); ray_release(y); + } + PASS(); +} + +/* q2's shape: count over a column of CONST and RLE vectors with no nulls; + * the count is answered from the runs, no byte decoded; FOR_BP vectors + * count on their packed residuals, DICT vectors on their codes, SYM RLE + * vectors on their ids (== / != only; an absent symbol matches nothing; + * the "" literal is the null atom, which the fast path declines). */ +static test_result_t test_count_on_runs(void) { + /* a: CONST 0 in 3 of 4 vectors, RLE [0 7 0] in the fourth (the + * AdvEngineID shape); b: FOR_BP 0..49 */ + aw_save("cr", "(table [a b] (list (as 'I16 (map (fn [j] (if (and (== 3 (% (div j 1024) 4)) (> (% j 1024) 100) (< (% j 1024) 300)) 7 0)) (til 200000))) " + "(as 'I32 (% (til 200000) 50))))", -1); + static const char* const q[] = { + "(count (select {from: T where: (!= a 0)}))", + "(count (select {from: T where: (== a 7)}))", + "(count (select {from: T where: (> b 20)}))", + "(count (select {from: T where: (== b 7)}))", + "(count (select {from: T where: (< a 7)}))", + "(count (select {from: T where: (>= b 49)}))", + "(count (select {from: T where: (<= b -1)}))", + "(count (select {from: T where: (!= b 50)}))", + "(count (select {from: T where: (< b 13)}))", + "(count (select {from: T where: (<= b 13)}))", + "(count (select {from: T where: (!= b 13)}))", + "(count (select {from: T where: (>= b 0)}))", + "(count (select {from: T where: (< 30 b)}))", + NULL, + }; + uint64_t f0 = ray_query_test_count_fast(); + for (int i = 0; q[i]; i++) { + test_result_t r = aw_reduce("cr", q[i], 0); /* equal answers, 0 decoded bytes */ + if (r.status != TEST_PASS) return r; + } + TEST_ASSERT_TRUE(ray_query_test_count_fast() > f0); /* the fast path ran */ + TEST_ASSERT_EQ_I(aw_vec_enc("cr", "a", 3), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(aw_vec_enc("cr", "b", 3), RAY_ENC_FOR_BP); + /* DICT (forced): 37 wide values, every operator around and on them */ + aw_save("cd", "(table [d] (list (* 1000003 (- (% (* (til 200000) 7) 37) 18))))", RAY_ENC_DICT); + TEST_ASSERT_EQ_I(aw_vec_enc("cd", "d", 5), RAY_ENC_DICT); + static const char* const dq[] = { + "(count (select {from: T where: (== d 3000009)}))", "(count (select {from: T where: (!= d 3000009)}))", + "(count (select {from: T where: (< d 3000009)}))", "(count (select {from: T where: (<= d 3000009)}))", + "(count (select {from: T where: (> d 3000010)}))", "(count (select {from: T where: (>= d -18000054)}))", + "(count (select {from: T where: (== d 5)}))", "(count (select {from: T where: (!= d 5)}))", + NULL, + }; + for (int i = 0; dq[i]; i++) { + test_result_t r = aw_reduce("cd", dq[i], 0); + if (r.status != TEST_PASS) return r; + } + /* SYM: runs of 300 rows over 7 symbols and "" */ + aw_save("cs", "(table [s] (list (as 'SYMBOL (map (fn [j] (if (== 3 (% (div j 300) 8)) \"\" (format \"s%\" (% (div j 300) 7)))) (til 200000)))))", -1); + static const char* const sq[] = { + "(count (select {from: T where: (== s 's3)}))", "(count (select {from: T where: (!= s 's3)}))", + "(count (select {from: T where: (== s 'zz)}))", "(count (select {from: T where: (!= s 'zz)}))", + NULL, + }; + for (int i = 0; sq[i]; i++) { + test_result_t r = aw_reduce("cs", sq[i], 0); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* q8's shape: a COUNT group by the same key under its own != 0 filter. + * The RLE vectors' runs add to their slots (and fold the selection + * bounds); nothing decoded. Also unfiltered (no selection), a selection + * that cuts runs (MIX segments), COUNT beside a group of no count (the + * per-row path), a SYM key, and a parted table, every partition + * generation 2 or one generation 0, ragged (a partition without the key: + * an I16 stand-in is all null, a U8 one zeros). */ +static test_result_t test_group_count_on_runs(void) { + /* the RLE vectors' runs hold over 65536 selected rows: the parallel + * dense route (below the threshold the selection is compacted) */ + aw_save("gr", "(table [a] (list (as 'I16 (map (fn [j] (if (and (== 3 (% (div j 1024) 4)) (> (% j 1024) 100) (< (% j 1024) 900)) (+ 1 (% (div j 4096) 5)) 0)) (til 400000)))))", -1); + test_result_t r = aw_reduce("gr", "(select {a: a c: (count a) from: T where: (!= a 0) by: a desc: c take: 10})", 0); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_TRUE(g_aw_unaligned || agg_route_stats().dense_strategy == AGG_DENSE_TASK_LOCAL); + if ((r = aw_reduce("gr", "(select {c: (count a) from: T by: a})", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("gr", "(select {c: (count a) from: T where: (!= a 3) by: a})", 0)).status != TEST_PASS) return r; + /* a selection that cuts runs (MIX segments): rows of the run where + * a second predicate fails */ + aw_save("gm", "(table [a k] (list (as 'I16 (map (fn [j] (if (and (> (% j 1024) 100) (< (% j 1024) 900)) (+ 1 (% (div j 1024) 5)) 0)) (til 300000))) (til 300000)))", -1); + if ((r = aw_reduce("gm", "(select {a: a c: (count a) from: T where: (and (!= a 0) (!= 0 (% k 3))) by: a desc: c take: 10})", -1)).status != TEST_PASS) return r; + if (!g_aw_unaligned) TEST_ASSERT_FMT(aw_col_decoded("a") == 0, "gm: a decoded %llu", (unsigned long long)aw_col_decoded("a")); + if ((r = aw_reduce("gm", "(select {c: (count k) d: (count a) from: T where: (< (% k 7) 4) by: a})", -1)).status != TEST_PASS) return r; + if (!g_aw_unaligned) TEST_ASSERT_FMT(aw_col_decoded("a") == 0, "gm 2: a decoded %llu", (unsigned long long)aw_col_decoded("a")); + /* not COUNT only: the per-row path, same answers */ + if ((r = aw_reduce("gm", "(select {c: (count a) s: (sum k) from: T where: (!= a 0) by: a})", -1)).status != TEST_PASS) return r; + /* a nullable key in runs: a vector with nulls carries a bitmap, so its + * run view declines (counting it by runs would put the null rows under + * the run's stored value: 5 groups instead of 6) */ + aw_save("gn", "(table [a] (list (as 'I16 (map (fn [j] (if (== 500 (% j 4096)) 0Nh (+ 1 (% (div j 1024) 5)))) (til 300000)))))", -1); + if ((r = aw_reduce("gn", "(select {c: (count a) from: T by: a})", -1)).status != TEST_PASS) return r; + { + aw_eval_ok("(set R (select {c: (count a) from: T by: a}))"); + ray_t* n = ray_eval_str("(count R)"); + TEST_ASSERT_TRUE(n && !RAY_IS_ERR(n) && n->i64 == 6); + ray_release(n); + } + /* packed keys (every vector FOR_BP, or DICT): no run view, so each + * vector is decoded and counted per row, as before (D6); the same + * answers, nothing materialized */ + static const struct { const char* name; int enc; } pk[] = { { "gp", RAY_ENC_FOR_BP }, { "gd", RAY_ENC_DICT } }; + for (int i = 0; i < 2; i++) { + aw_save(pk[i].name, "(table [a v] (list (as 'I32 (- (* 100 (% (* (til 300000) 7) 13)) 600)) (% (til 300000) 7)))", pk[i].enc); + TEST_ASSERT_EQ_I(aw_vec_enc(pk[i].name, "a", 7), pk[i].enc); + if ((r = aw_reduce(pk[i].name, "(select {a: a c: (count a) from: T where: (!= a 0) by: a desc: c take: 10})", -1)).status != TEST_PASS) return r; + if ((r = aw_reduce(pk[i].name, "(select {c: (count a) from: T by: a})", -1)).status != TEST_PASS) return r; + if ((r = aw_reduce(pk[i].name, "(select {c: (count a) from: T where: (!= v 0) by: a})", -1)).status != TEST_PASS) return r; + } + /* a SYM key in runs, "" (id 0) among them */ + aw_save("gs", "(table [s] (list (as 'SYMBOL (map (fn [j] (if (== 3 (% (div j 300) 8)) \"\" (format \"s%\" (% (div j 300) 7)))) (til 300000)))))", -1); + if ((r = aw_reduce("gs", "(select {c: (count s) from: T by: s})", -1)).status != TEST_PASS) return r; + if ((r = aw_reduce("gs", "(select {c: (count s) from: T where: (!= s 's2) by: s desc: c take: 3})", -1)).status != TEST_PASS) return r; + /* parted: g (every partition generation 2), m (partition 2 generation + * 0), d (I16, partition 3 without a: all-null stand-in), u (U8, + * partition 3 without a: zeros) */ + static const struct { const char* root; const char* ty; int gen0, ragged; } pt[] = { + { "pg", "I16", -1, -1 }, { "pm", "I16", 1, -1 }, { "pd", "I16", -1, 2 }, { "pu", "U8", -1, 2 }, + }; + for (int t = 0; t < 4; t++) + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) { + char q[1200]; + const bool g2 = gen == 2 && p != pt[t].gen0; + if (p == pt[t].ragged) + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s%d/2024.01.0%d/t/\" (table [k] (list (til 70000))) {compress: %s})", + pt[t].root, gen, p + 1, g2 ? "true" : "false"); + else + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s%d/2024.01.0%d/t/\" " + "(table [k a] (list (til 100000) (as '%s (map (fn [j] (if (and (> (%% j 1024) 100) (< (%% j 1024) 900)) (+ 1 (%% (div j 1024) 5)) 0)) (+ (til 100000) %d))))) " + "{compress: %s})", pt[t].root, gen, p + 1, pt[t].ty, p * 777, g2 ? "true" : "false"); + aw_eval_ok(q); + } + static const char* const pq[] = { + "(select {a: a c: (count a) from: T where: (!= a 0) by: a desc: c take: 10})", + "(select {c: (count a) from: T by: a})", + NULL, + }; + for (int t = 0; t < 4; t++) + for (int i = 0; pq[i]; i++) { + char b[512]; + ray_t* out[2]; + for (int gen = 0; gen <= 2; gen += 2) { + snprintf(b, sizeof b, "(set T (.db.parted.get \"" AW_TMP "/%s%d\" 't))", pt[t].root, gen); + aw_eval_ok(b); + ray_enc_counters_reset(); + out[gen / 2] = ray_eval_str(pq[i]); + TEST_ASSERT_FMT(out[gen / 2] && !RAY_IS_ERR(out[gen / 2]), "%s %s: %s", pt[t].root, pq[i], ray_error_msg()); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + if (!g_aw_unaligned && pt[t].ragged < 0) /* a stand-in segment is read (decoded) per row */ + TEST_ASSERT_FMT(aw_parted_col_decoded("T", "a") == 0, "%s %s: a decoded %llu", pt[t].root, pq[i], + (unsigned long long)aw_parted_col_decoded("T", "a")); + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s %s differs", pt[t].root, pq[i]); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + PASS(); +} + +/* The scalar chunk route cut into tasks that are no multiple of a vector or + * a chunk (the grain ray_pool_dispatch re-derives when it clamps to its + * ring): every answer still equals generation 0's. */ +static test_result_t test_unaligned_grain(void) { + static test_result_t (*const fns[])(void) = { + test_scalar_route_mixed, test_eq_runs_lack, test_scalar_route_parted_stats, test_scalar_route_time, + }; + static const int64_t grains[] = { 5000, 70001 }; /* inside a chunk, across chunks */ + for (size_t g = 0; g < sizeof grains / sizeof *grains; g++) + for (size_t i = 0; i < sizeof fns / sizeof *fns; i++) { + if (g > 0 && i > 1) break; /* the second cut: two shapes */ + (void)ray_test_rm_rf(aw_root()); (void)ray_test_mkdir_p(aw_root()); + ray_group_test_scalar_grain(grains[g]); + g_aw_unaligned = true; + test_result_t r = fns[i](); + g_aw_unaligned = false; + ray_group_test_scalar_grain(0); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Chunk c of the generation-2 column file at `path` rewritten without + * statistics: its directory entry and every vector that has values carry + * RAY_ENC_STAT_ABSENT and zero bounds (a valid file: the writer may omit + * them; all-null vectors never carry any). */ +static bool aw_forge_absent(const char* path, int64_t c) { + FILE* f = fopen(path, "r+b"); if (!f) return false; + ray_enc_dirent_t de; + long doff = (long)(RAY_ENC_DIR_OFF + (uint64_t)c * sizeof de); + bool ok = fseek(f, doff, SEEK_SET) == 0 && fread(&de, sizeof de, 1, f) == 1 && !(de.flags & RAY_ENC_STAT_ABSENT); + if (ok) { + de.flags |= RAY_ENC_STAT_ABSENT; de.min = 0; de.max = 0; + ok = fseek(f, doff, SEEK_SET) == 0 && fwrite(&de, sizeof de, 1, f) == 1; + } + for (int j = 0; ok && j < RAY_ENC_VECS_PER_CHUNK; j++) { + ray_enc_desc_t d; + long off = (long)(de.offset + (uint64_t)j * sizeof d); + ok = fseek(f, off, SEEK_SET) == 0 && fread(&d, sizeof d, 1, f) == 1; + if (!ok || (d.encoding == 0 && d.payload_bytes == 0)) break; /* past the last vector */ + if (d.flags & RAY_ENC_STAT_ABSENT) continue; + d.flags |= RAY_ENC_STAT_ABSENT; d.min = 0; d.max = 0; + ok = fseek(f, off, SEEK_SET) == 0 && fwrite(&d, sizeof d, 1, f) == 1; + } + return fclose(f) == 0 && ok; +} + +/* Review focus 6: every pruning case, results and order equal to + * generation 0; nothing materializes (the sort key is read by range). kn has a + * null every 1000 rows and chunk 2 all null; its values climb to 300004 + * at row 299999 and restart at 5. */ +static test_result_t test_topk_prune_cases(void) { + aw_save("tp", "(table [kn v] (list (as 'I64 (map (fn [j] (if (or (== 0 (% j 1000)) (and (>= j 131072) (< j 196608))) 0N " + "(+ 5 (% j 300000)))) (til 400000))) (% (* (til 400000) 13) 1000)))", -1); + static const char* const q[] = { + "(select {kn: kn v: v from: T where: (> v 100) asc: kn take: 20})", + "(select {kn: kn v: v from: T where: (> v 100) desc: kn take: 20})", + "(select {kn: kn v: v from: T where: (== v 7) asc: [kn v] take: 5})", /* two sort keys */ + "(select {kn: kn from: T desc: kn take: 401})", /* K above the null count of a chunk */ + "(select {kn: kn v: v from: T asc: kn take: 8000})", /* near FPK_MAX_K (8192), past the leading nulls */ + "(select {kn: kn v: v from: T where: (> v 900) asc: kn take: 3})", /* the answer: nulls of chunk 2 */ + "(select {kn: kn v: v from: T where: (< v 50) desc: kn take: 7})", + NULL, + }; + static const uint64_t mat[] = { 0, 0, 0, 0, 0, 0, 0 }; /* the sort keys are read by range */ + for (int i = 0; q[i]; i++) AW_SAME("tp", q[i], mat[i]); + /* Ties on the first key at the bound: k1 is constant over 4096 rows, so + * the first morsel fills the heap and publishes k1 = 0 while the next + * vectors (minimum 0, equal to the bound) still hold better rows by k2. */ + aw_save("tq", "(table [k1 k2] (list (div (til 200000) 4096) (- 200000 (til 200000))))", -1); + AW_SAME("tq", "(select {k1: k1 k2: k2 from: T asc: [k1 k2] take: 3})", 0); + AW_SAME("tq", "(select {k1: k1 k2: k2 from: T where: (> k2 0) desc: [k1 k2] take: 3})", 0); + /* pruning happened at both levels on the generation-2 key */ + aw_eval_ok("(set T (.db.splayed.get \"" AW_TMP "/tp2/\"))"); + aw_eval_ok("(select {kn: kn v: v from: T where: (> v 100) desc: kn take: 20})"); + uint64_t pc = 0, pv = 0; + ray_fused_topk_test_pruned(&pc, &pv); + /* chunk-slot prunes only on aligned grains: a clamped ring may hand the + * best chunks to one task, whose bound then never undercuts a later + * chunk (as the tr cases below) */ + if (!g_aw_unaligned) TEST_ASSERT_TRUE(pc > 0); + TEST_ASSERT_TRUE(pv > 0); /* also under a clamped grain */ + /* I32 and TIMESTAMP first keys: negative values climbing through zero + * (row j holds j - 150000, the timestamp that many seconds from the + * epoch), a null every 5000 rows (every chunk has some, most vectors + * none), and chunk 3 all null. Ascending prunes vectors only (every + * chunk has nulls); descending prunes at both levels. */ + aw_save("tr", "(table [i t v] (list " + "(as 'I32 (map (fn [j] (if (or (== 0 (% j 5000)) (and (>= j 196608) (< j 262144))) 0N (- j 150000))) (til 300000))) " + "(as 'TIMESTAMP (map (fn [j] (if (or (== 0 (% j 5000)) (and (>= j 196608) (< j 262144))) 0N (* (- j 150000) 1000000000))) (til 300000))) " + "(% (* (til 300000) 13) 1000)))", -1); + static const char* const qr[] = { + "(select {i: i v: v from: T where: (> v 100) asc: i take: 12})", + "(select {i: i v: v from: T where: (> v 100) desc: i take: 12})", + "(select {t: t v: v from: T where: (> v 100) asc: t take: 12})", + "(select {t: t v: v from: T where: (> v 100) desc: t take: 12})", + "(select {i: i v: v from: T asc: i take: 70})", /* past the 60 nulls outside chunk 3 */ + "(select {t: t i: i from: T where: (< v 20) desc: [t i] take: 9})", + NULL, + }; + static const uint64_t matr[] = { 0, 0, 0, 0, 0, 0 }; + static const bool descr[] = { false, true, false, true, false, true }; + for (int i = 0; qr[i]; i++) { + AW_SAME("tr", qr[i], matr[i]); + /* q5's answer is nulls (no bound is published); a clamped grain may + * leave the best chunk to one task that scans it in rising order */ + if (i == 4 || g_aw_unaligned) continue; + ray_fused_topk_test_pruned(&pc, &pv); + TEST_ASSERT_FMT(pv > 0 && (!descr[i] || pc > 0), "%s: pruned %llu chunk slots, %llu vectors", qr[i], + (unsigned long long)pc, (unsigned long long)pv); + } + /* generation 0 never takes the directory path */ + aw_eval_ok("(set T (.db.splayed.get \"" AW_TMP "/tp0/\"))"); + aw_eval_ok("(select {kn: kn v: v from: T where: (> v 100) desc: kn take: 20})"); + ray_fused_topk_test_pruned(&pc, &pv); + TEST_ASSERT_EQ_I(pc + pv, 0); + /* A chunk without statistics (chunk 4, which holds the largest keys) is + * never pruned: visited after the ordered chunks, it still wins. */ + { + char dir[512], path[600]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(ray_test_tmp(AW_TMP "/tp2/"), dir, sizeof dir), RAY_OK); + snprintf(path, sizeof path, "%s/kn", dir); + TEST_ASSERT_TRUE(aw_forge_absent(path, 4)); + AW_SAME("tp", q[1], 0); + AW_SAME("tp", q[3], 0); + AW_SAME("tp", "(select {kn: kn v: v from: T where: (< v 500) asc: kn take: 9})", 0); + } + PASS(); +} + +/* Range-read sort keys (fpk_rk_t): a generation-2 key is never + * materialized for the top-k, its vectors are read by range and the heaps + * carry the values; answers, order and ties equal generation 0's. 300000 + * rows (five chunks): t a TIMESTAMP with every value on three rows and a + * null every 5003 rows, s a SYM of 50 words ("" among them), k2 an I32 of + * five values, f an F64 of 1000 values with a NaN null every 13 rows, v + * the predicate column, u a STR, ts a sorted TIMESTAMP. */ +static test_result_t test_topk_range_keys(void) { + aw_eval_ok("(set PH (as 'SYMBOL (concat [\"\"] (map (fn [j] (format \"w%\" (- 60 j))) (til 49)))))"); + aw_save("tk", "(table [t s k2 f v u ts] (list " + "(as 'TIMESTAMP (map (fn [j] (if (== 0 (% j 5003)) 0N (* (div (% (* j 7919) 300007) 3) 1000000000))) (til 300000))) " + "(at PH (% (* (til 300000) 7) 50)) (as 'I32 (% (til 300000) 5)) " + "(as 'F64 (map (fn [j] (if (== 0 (% j 13)) 0N (% (* j 31) 1000))) (til 300000))) " + "(% (* (til 300000) 13) 1000) (as 'STR (map (fn [j] (format \"u%\" (% j 97))) (til 300000))) " + "(as 'TIMESTAMP (* (til 300000) 1000000000))))", -1); + static const char* const q[] = { + "(select {t: t v: v from: T where: (> v 100) asc: t take: 20})", /* nulls first, by row */ + "(select {t: t v: v from: T where: (> v 100) desc: t take: 20})", + "(select {t: t v: v from: T where: (> v 100) asc: t take: 200})", /* past the 60 nulls: ties of three */ + "(select {t: t s: s from: T where: (!= s ') asc: [t s] take: 30})", /* a SYM second key */ + "(select {t: t s: s from: T where: (!= s ') desc: [t s] take: 30})", + "(select {k2: k2 t: t from: T asc: [k2 t] take: 50})", /* five-value first key */ + "(select {k2: k2 v: v from: T asc: k2 desc: v take: 12})", /* mixed directions */ + "(select {f: f v: v from: T where: (< v 500) desc: [f v] take: 15})", /* a float key */ + "(select {f: f v: v from: T where: (< v 500) asc: [f v] take: 15})", /* NaN nulls first */ + "(select {s: s v: v from: T asc: [s v] take: 10})", /* a SYM first key */ + "(select {s: s v: v from: T desc: [s v] take: 10})", + "(select {t: t v: v from: T where: (== v 7) asc: t take: 5000})", /* every passing row */ + "(select {t: t k2: k2 from: T where: (> v 998) desc: [k2 t] take: 7})", + NULL, + }; + for (int i = 0; q[i]; i++) AW_SAME("tk", q[i], 0); /* no key materialized */ + /* a sorted key (ts, the row's second) is read only where it can win */ + AW_SAME("tk", "(select {ts: ts v: v from: T where: (> v 100) asc: ts take: 10})", 0); + TEST_ASSERT_FMT(g_aw_unaligned || aw_col_decoded("ts") < 300000 * 8 / 2, "ts decoded %llu", + (unsigned long long)aw_col_decoded("ts")); + AW_SAME("tk", "(select {ts: ts t: t from: T desc: [ts t] take: 10})", 0); + /* the first key's directory still prunes the range-read key */ + aw_eval_ok("(set T (.db.splayed.get \"" AW_TMP "/tk2/\"))"); + aw_eval_ok("(select {t: t v: v from: T where: (> v 100) desc: t take: 20})"); + uint64_t pc = 0, pv = 0; + ray_fused_topk_test_pruned(&pc, &pv); + TEST_ASSERT_TRUE(g_aw_unaligned || pv > 0); + /* a STR key keeps the materialized path: both keys */ + AW_SAME("tk", "(select {u: u v: v from: T where: (> v 990) asc: [u v] take: 6})", 2); + PASS(); +} + +/* One cut of test_group_topn_ties: `shape` at take n over the parted P + * equals ref (the stable full sort's first n rows) and the splayed copy's + * answer, on every iteration and on the radix ladder. */ +static test_result_t aw_topn_case(const char* shape, int n, int gen, int iters, ray_t* ref) { + char q[600], body[300]; + snprintf(body, sizeof body, shape, "S", n); + snprintf(q, sizeof q, "(select %s)", body); + ray_t* spl = aw_eval(q); + TEST_ASSERT_FMT(spl && !RAY_IS_ERR(spl), "%s: %s", q, ray_error_msg()); + test_result_t r = aw_csv_eq(q, gen, ref, spl); + ray_release(spl); + if (r.status != TEST_PASS) return r; + snprintf(body, sizeof body, shape, "P", n); + snprintf(q, sizeof q, "(select %s)", body); + for (int it = 0; it < iters; it++) { + agg_route_reset(); + ray_t* got = aw_eval(q); + TEST_ASSERT_FMT(got && !RAY_IS_ERR(got), "%s: %s", q, ray_error_msg()); + agg_route_stats_t st = agg_route_stats(); + /* the flattened parted group, on the radix ladder, not v2 */ + bool radix = st.routes[AGG_ROUTE_PARTED] > 0 && st.routes[AGG_ROUTE_LEGACY] > 0 && !st.topn_native; + if (!radix) ray_release(got); + TEST_ASSERT_FMT(radix, "%s: not on the radix ladder", q); + r = aw_csv_eq(q, it, ref, got); + ray_release(got); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* aw_topn_case against the reference built here: the first n rows of the + * same shape over P at take: 1025 (above the filter's cap: a full sort). */ +static test_result_t aw_topn_check(const char* shape, int n, int gen, int iters) { + char q[600], body[300]; + snprintf(body, sizeof body, shape, "P", 1025); + snprintf(q, sizeof q, "(take (select %s) %d)", body, n); + ray_t* ref = aw_eval(q); + TEST_ASSERT_FMT(ref && !RAY_IS_ERR(ref), "%s: %s", q, ray_error_msg()); + int64_t ref_rows = ray_table_nrows(ref); + if (ref_rows != n) ray_release(ref); + TEST_ASSERT_FMT(ref_rows == n, "%s: %lld rows, %d wanted", q, (long long)ref_rows, n); + test_result_t r = aw_topn_case(shape, n, gen, iters, ref); + ray_release(ref); + return r; +} + +/* #801: a grouped take (`by … desc: take: N`, N <= 1024) arms the + * radix group's top-N emit filter, which cuts the groups to exactly N. + * Groups tied at the cut value are decided by the earliest source row, the + * order the radix route's phase 3 and the stable sort follow: the answer + * equals the stable full sort's first N rows (take: 1025 is above the + * filter's cap, so it sorts everything) and the splayed copy's answer (the + * same ladder over one unpartitioned table, whose dispatch cuts differ), at + * every iteration. The row-to-group map + * is aperiodic against the 10050-row partitions and the dispatch tasks: + * rows [0, 20000) hold group i*i mod 10007 (about 4 rows each) and rows + * [20000, 40000) hold 10007 + i*i mod 5003 (about 8 rows each), groups + * that first appear past the first task, so their earliest row is found + * only by taking the minimum across workers and partitions. 50 more rows + * go to groups 0..49 at the end. Every cut falls inside a tie set of + * thousands of groups. The SYM keys beside a computed one take the + * flattened parted group onto the radix fat-entry path; the integer keys + * take its v2 direct-insert phase 2. */ +static test_result_t test_group_topn_ties(void) { + aw_eval_ok("(set K (concat (concat (% (* (til 20000) (til 20000)) 10007) (+ 10007 (% (* (til 20000) (til 20000)) 5003))) " + "(% (til 200) 50)))"); + aw_eval_ok("(set W (table [s u v g] (list (at (as 'SYMBOL (map (fn [j] (format \"w%\" j)) (til 15010))) K) " + "(% K 3) (til 40200) K)))"); + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 4; p++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/tt%d/2024.01.0%d/t/\" (take (drop W %d) 10050) " + "\"" AW_TMP "/tt%d/.sym\" {compress: %s})", gen, p + 1, p * 10050, gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/ts/t/\" W \"" AW_TMP "/ts/.sym\")"); + aw_eval_ok("(set S (.db.splayed.get \"" AW_TMP "/ts/t/\" \"" AW_TMP "/ts/.sym\"))"); + static const char* const shapes[] = { + "{c: (count v) from: %s by: {s: s z: (%% v 1) t: s} desc: c take: %d}", + "{c: (count v) from: %s by: {s: s z: (%% v 1) t: s} asc: c take: %d}", + "{m: (min u) c: (count v) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{q: (sum u) from: %s by: {s: s z: (%% v 1) t: s} asc: q take: %d}", + "{q: (max u) from: %s by: {s: s z: (%% v 1) t: s} desc: q take: %d}", + "{c: (count v) from: %s by: {g: g z: (%% v 1) h: g} desc: c take: %d}", + "{q: (sum u) from: %s by: {g: g z: (%% v 1) h: g} asc: q take: %d}", + }; + static const int takes[] = { 100, 7 }; + for (int gen = 0; gen <= 2; gen += 2) { + char q[600]; + snprintf(q, sizeof q, "(set P (.db.parted.get \"" AW_TMP "/tt%d\" 't))", gen); + aw_eval_ok(q); + for (size_t si = 0; si < sizeof shapes / sizeof *shapes; si++) + for (size_t ti = 0; ti < sizeof takes / sizeof *takes; ti++) { + /* the race needs repeats; the other cuts are checked a few times */ + int iters = si == 0 && ti == 0 && !g_aw_unaligned ? 20 : 3; + test_result_t r = aw_topn_check(shapes[si], takes[ti], gen, iters); + if (r.status != TEST_PASS) return r; + } + } + aw_eval_ok("(set P 0)"); aw_eval_ok("(set S 0)"); aw_eval_ok("(set W 0)"); aw_eval_ok("(set K 0)"); + PASS(); +} + +/* #808: an all-null group's aggregate is a null, and the stable sort ranks + * nulls below every value: first under asc:, last under desc:. The radix + * top-N ranks such a group there too, not by the slot's init sentinel (MIN's + * INT64_MAX put all-null groups at the top of a desc: take and dropped them + * from an asc: one). 2000 groups over two partitions, 400 of them all-null + * in w; take 5 runs the fused per-partition scan, take 30 the serial one. */ +static test_result_t test_group_topn_nulls(void) { + aw_eval_ok("(set K (% (* (til 8000) 7919) 2000))"); + aw_eval_ok("(set W (table [s w v] (list (at (as 'SYMBOL (map (fn [j] (format \"w%\" j)) (til 2000))) K) " + "(as 'I64 (map (fn [k] (if (< (% k 5) 1) 0Nl (% k 13))) K)) (til 8000))))"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tn/2024.01.01/t/\" (take W 4000) \"" AW_TMP "/tn/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tn/2024.01.02/t/\" (drop W 4000) \"" AW_TMP "/tn/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tns/t/\" W \"" AW_TMP "/tns/.sym\")"); + aw_eval_ok("(set P (.db.parted.get \"" AW_TMP "/tn\" 't))"); + aw_eval_ok("(set S (.db.splayed.get \"" AW_TMP "/tns/t/\" \"" AW_TMP "/tns/.sym\"))"); + static const char* const shapes[] = { + "{m: (min w) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (min w) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{m: (max w) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (max w) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{m: (sum w) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (sum w) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{m: (avg w) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (avg w) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + }; + static const int takes[] = { 5, 30 }; + for (size_t si = 0; si < sizeof shapes / sizeof *shapes; si++) + for (size_t ti = 0; ti < sizeof takes / sizeof *takes; ti++) { + test_result_t r = aw_topn_check(shapes[si], takes[ti], 0, 2); + if (r.status != TEST_PASS) return r; + } + aw_eval_ok("(set P 0)"); aw_eval_ok("(set S 0)"); aw_eval_ok("(set W 0)"); aw_eval_ok("(set K 0)"); + PASS(); +} + +/* #813: SUM/AVG of `col +/- const` aggregate the column and add + * bias * count at emit; the radix top-N ranks by that final value too, not + * by the column's sum. Groups 0..49 hold 60 rows each with w = 0, the + * others about 2.5 rows each: with a +100 bias the large groups lead, with + * -100 they trail, and the raw sum ranks them the other way. Two + * partitions; take 5 runs the fused per-partition scan, take 20 the serial + * one. */ +static test_result_t test_group_topn_affine(void) { + aw_eval_ok("(set K (map (fn [i] (if (< i 3000) (% i 50) (% (* i 7919) 2000))) (til 8000)))"); + /* wn is nullable so the ordering SUM's non-null counts sit beside + * another slot's: the heap must read its own slot's (agg_slot > 0) */ + aw_eval_ok("(set W (table [s w v wn] (list (at (as 'SYMBOL (map (fn [j] (format \"w%\" j)) (til 2000))) K) " + "(map (fn [k] (if (< k 50) 0 (% k 13))) K) (til 8000) " + "(as 'I64 (map (fn [k] (if (< (% k 5) 1) 0Nl (% k 7))) K)))))"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/ta/2024.01.01/t/\" (take W 4000) \"" AW_TMP "/ta/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/ta/2024.01.02/t/\" (drop W 4000) \"" AW_TMP "/ta/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tas/t/\" W \"" AW_TMP "/tas/.sym\")"); + aw_eval_ok("(set P (.db.parted.get \"" AW_TMP "/ta\" 't))"); + aw_eval_ok("(set S (.db.splayed.get \"" AW_TMP "/tas/t/\" \"" AW_TMP "/tas/.sym\"))"); + static const char* const shapes[] = { + "{m: (sum (+ w 100)) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (sum (+ w 100)) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{m: (sum (- w 100)) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (sum (- w 100)) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{m: (sum (+ -100 w)) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (avg (+ w 100)) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (avg (+ w 100)) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{m: (avg (- w 100)) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{m: (avg (- w 100)) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + "{a: (min wn) m: (sum (+ w 100)) from: %s by: {s: s z: (%% v 1) t: s} desc: m take: %d}", + "{a: (min wn) m: (sum (+ w 100)) from: %s by: {s: s z: (%% v 1) t: s} asc: m take: %d}", + }; + static const int takes[] = { 20, 5 }; + for (size_t si = 0; si < sizeof shapes / sizeof *shapes; si++) + for (size_t ti = 0; ti < sizeof takes / sizeof *takes; ti++) { + test_result_t r = aw_topn_check(shapes[si], takes[ti], 0, 2); + if (r.status != TEST_PASS) return r; + } + aw_eval_ok("(set P 0)"); aw_eval_ok("(set S 0)"); aw_eval_ok("(set W 0)"); aw_eval_ok("(set K 0)"); + PASS(); +} + +/* csv-equal answers of two table expressions, under `what`. */ +static test_result_t aw_tables_same(const char* what, const char* qa, const char* qb) { + ray_t* a = aw_eval(qa); + TEST_ASSERT_FMT(a && !RAY_IS_ERR(a), "%s: %s", qa, ray_error_msg()); + ray_t* b = aw_eval(qb); + if (!b || RAY_IS_ERR(b)) ray_release(a); + TEST_ASSERT_FMT(b && !RAY_IS_ERR(b), "%s: %s", qb, ray_error_msg()); + test_result_t r = aw_csv_eq(what, 0, a, b); + ray_release(a); ray_release(b); + return r; +} + +/* #814: SUM of `col +/- c` over a nullable column is the sum of the + * non-null rows' col + c, so the bias counts only the non-null rows (an + * all-null group sums to 0), and AVG adds c to the non-null average. wn is + * all-null in every group with k mod 5 == 0 (the #808 fixture), wp is null + * on every third row (partially null groups), wf is wp as F64. Checked against the + * in-memory table's `by: s` (the v2 engine): the parted `by: s`, the + * 3-key parted shape (the serial emit), and the radix top-N (its values + * against the in-memory full sort's first n, its rows against take: 1025). + * The no-key answers, with and without a where:, over the in-memory, + * splayed and parted tables, against the sum of the materialized input. */ +static test_result_t test_group_affine_nulls(void) { + aw_eval_ok("(set K (% (* (til 8000) 7919) 2000))"); + aw_eval_ok("(set W (table [s wn wp v] (list (at (as 'SYMBOL (map (fn [j] (format \"w%\" j)) (til 2000))) K) " + "(as 'I64 (map (fn [k] (if (< (% k 5) 1) 0Nl (% k 13))) K)) " + "(as 'I64 (map (fn [i] (if (== 0 (% i 3)) 0Nl (% i 11))) (til 8000))) (til 8000))))"); + aw_eval_ok("(set W (select {s: s wn: wn wp: wp v: v wf: (as 'F64 wp) from: W}))"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tz/2024.01.01/t/\" (take W 4000) \"" AW_TMP "/tz/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tz/2024.01.02/t/\" (drop W 4000) \"" AW_TMP "/tz/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/tzs/t/\" W \"" AW_TMP "/tzs/.sym\")"); + aw_eval_ok("(set P (.db.parted.get \"" AW_TMP "/tz\" 't))"); + aw_eval_ok("(set S (.db.splayed.get \"" AW_TMP "/tzs/t/\" \"" AW_TMP "/tzs/.sym\"))"); + /* the inputs materialized: the reference for the scalar (no-key) answers */ + aw_eval_ok("(set X (select {a: (+ wn 100) b: (- wn 100) c: (+ wp 100) d: (- wp 100) e: (+ wf 100) v: v from: W}))"); + static const char* const aggs[] = { + "(sum (+ wn 100))", "(sum (- wn 100))", "(sum (+ wp 100))", "(sum (- wp 100))", + "(avg (+ wn 100))", "(avg (- wn 100))", "(avg (+ wp 100))", "(avg (- wp 100))", + "(sum (+ wf 100))", "(avg (+ wf 100))", + }; + static const char* const mats[] = { + "(sum a)", "(sum b)", "(sum c)", "(sum d)", "(avg a)", "(avg b)", "(avg c)", "(avg d)", + "(sum e)", "(avg e)", + }; + static const char* const tbls[] = { "W", "S", "P" }; + static const char* const dirs[] = { "desc", "asc" }; + static const int takes[] = { 5, 20 }; + for (size_t ai = 0; ai < sizeof aggs / sizeof *aggs; ai++) { + char qa[700], qb[700], shape[300]; + const char* ag = aggs[ai]; + /* no key, and under a where: */ + for (int t = 0; t < 3; t++) { + snprintf(qa, sizeof qa, "(select {m: %s from: X})", mats[ai]); + snprintf(qb, sizeof qb, "(select {m: %s from: %s})", ag, tbls[t]); + test_result_t r = aw_tables_same(qb, qa, qb); + if (r.status != TEST_PASS) return r; + snprintf(qa, sizeof qa, "(select {m: %s from: X where: (< v 5000)})", mats[ai]); + snprintf(qb, sizeof qb, "(select {m: %s from: %s where: (< v 5000)})", ag, tbls[t]); + r = aw_tables_same(qb, qa, qb); + if (r.status != TEST_PASS) return r; + } + /* every group's value, by key */ + snprintf(qa, sizeof qa, "(select {s: s m: m from: (select {m: %s from: W by: s}) asc: s})", ag); + snprintf(qb, sizeof qb, "(select {s: s m: m from: (select {m: %s from: P by: s}) asc: s})", ag); + test_result_t r = aw_tables_same(qb, qa, qb); + if (r.status != TEST_PASS) return r; + snprintf(qb, sizeof qb, "(select {s: s m: m from: (select {m: %s from: P by: {s: s z: (%% v 1) t: s}}) asc: s})", ag); + r = aw_tables_same(qb, qa, qb); + if (r.status != TEST_PASS) return r; + for (int d = 0; d < 2; d++) + for (size_t ti = 0; ti < sizeof takes / sizeof *takes; ti++) { + int n = takes[ti]; + /* the cut's values are the full sort's first n, ties aside */ + snprintf(qa, sizeof qa, "(table [m] (list (take (at (select {m: %s from: W by: s %s: m}) 'm) %d)))", + ag, dirs[d], n); + snprintf(qb, sizeof qb, "(table [m] (list (at (select {m: %s from: P by: {s: s z: (%% v 1) t: s} " + "%s: m take: %d}) 'm)))", ag, dirs[d], n); + r = aw_tables_same(qb, qa, qb); + if (r.status != TEST_PASS) return r; + snprintf(shape, sizeof shape, "{m: %s from: %%s by: {s: s z: (%%%% v 1) t: s} %s: m take: %%d}", + ag, dirs[d]); + r = aw_topn_check(shape, n, 0, 2); + if (r.status != TEST_PASS) return r; + } + } + aw_eval_ok("(set P 0)"); aw_eval_ok("(set S 0)"); aw_eval_ok("(set W 0)"); aw_eval_ok("(set K 0)"); + aw_eval_ok("(set X 0)"); + PASS(); +} + +/* Group-by on a generation-2 STR key through a query-wide string domain + * (strdom.c): the key column t is never materialized and the groups equal + * generation 0's. */ +static void aw_str_key_tables(const char* tag, int n_part, int n_flat) { + /* STR key with vectors of one repeated string and vectors of many (CONST + * and RAW before P6; P6 selection makes every chunk STR_DICT, and the + * forced-RAW twin keeps the RAW vectors), + * equal strings crossing every vector boundary; two partitions, the + * second offset and longer, a string in the first only */ + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[1000]; + int n = n_part + p * 1000, off = p * 777; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%sk%d/2024.01.0%d/t/\" " + "(table [t v] (list (map (fn [j] (if (and (== %d 0) (== (%% j 4000) 17)) \"in the first partition only\" " + "(if (< (%% j 2048) 1024) \"constant run text\" (format \"long key %%\" (%% j 37))))) (+ %d (til %d))) " + "(+ %d (til %d)))) {compress: %s})", + tag, gen, p + 1, p, off, n, off, n, gen ? "true" : "false"); + aw_eval_ok(q); + } + /* the unparted case: one column mixing CONST and RAW vectors */ + for (int gen = 0; gen <= 2; gen += 2) { + char q[800]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%su%d/\" " + "(table [t v] (list (map (fn [j] (if (< (%% j 2048) 1024) \"constant run text\" " + "(format \"long key %%\" (%% j 37)))) (til %d)) (til %d))) {compress: %s})", + tag, gen, n_flat, n_flat, gen ? "true" : "false"); + aw_eval_ok(q); + } + /* CONST vectors beside a non-dictionary vector (P6): each chunk opens + * with 1024 distinct long keys (no dictionary chunk, so that vector is + * FSST or RAW), then runs of two constants, one per vector (CONST) */ + for (int gen = 0; gen <= 2; gen += 2) { + char q[900]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%sc%d/\" " + "(table [t v] (list (map (fn [j] (if (< (%% j 65536) 1024) " + "(format \"https://www.example.com/path/%%/item?id=%%\" j (%% (* j 7919) 100003)) " + "(if (< (%% j 2048) 1024) \"constant run text\" \"another constant run\"))) (til %d)) (til %d))) " + "{compress: %s})", + tag, gen, n_flat, n_flat, gen ? "true" : "false"); + aw_eval_ok(q); + } + /* nulls: "" is the STR null (its canonical empty payload): the null and + * "" rows are one group in either generation, beside short (inline) and + * long (pooled) keys */ + for (int gen = 0; gen <= 2; gen += 2) { + char q[800]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%sn%d/\" " + "(table [t v] (list (map (fn [j] (if (== (%% j 7) 3) \"\" (if (== (%% j 7) 1) " + "(format \"a long pooled key %%\" (%% j 3)) (format \"k%%\" (%% j 5))))) (til %d)) (til %d))) " + "{compress: %s})", + tag, gen, n_flat, n_flat, gen ? "true" : "false"); + aw_eval_ok(q); + } + /* first occurrence over a selection: z0 z1 z2, then the cycle b a m; + * a filter past the z rows sees a m b first, in two partitions */ + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) { + char q[800]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%so%d/2024.01.0%d/t/\" " + "(table [t v] (list (map (fn [j] (if (< j 3) (format \"z%%\" j) (at [\"b\" \"a\" \"m\"] (%% j 3)))) " + "(til %d)) (til %d))) {compress: %s})", + tag, gen, p + 1, n_part, n_part, gen ? "true" : "false"); + aw_eval_ok(q); + } +} + +/* Each query on table T, loaded as (k and o parted), on + * both generations: equal formatted results. AW_SK_KEY (and AW_SK_STRICT): + * generation 2 leaves t unmaterialized (its vectors as `mix` says). + * AW_SK_STRICT on a large table: nothing at all materializes; the others + * may materialize v, as below RAY_PARALLEL_THRESHOLD rows the serial + * whole-column strategy (R-RANDOM) reads the aggregates' column whole + * whatever the key, and a composite key's expression is evaluated over its + * materialized column (bind_referenced_columns). AW_SK_DECLINE: shapes + * the string-domain swap declines (the key column read by an aggregate or + * another key), answers only. */ +enum { AW_SK_DECLINE, AW_SK_KEY, AW_SK_STRICT }; +typedef struct { char kind; int mode; const char* q; } aw_sk_q_t; +/* The STR key's encoding mix on generation 2 (kinds k and u; kind c holds + * CONST vectors beside FSST / RAW ones under selection): what + * selection gives the data (P6: every chunk a dictionary chunk, so every + * vector STR_DICT, the constant runs included), or every vector RAW when + * the tables were saved forced RAW (the RAW cursor path). */ +enum { AW_SK_MIX_SELECT, AW_SK_MIX_RAW }; +static test_result_t aw_str_key_check(const char* tag, const aw_sk_q_t* qs, bool strict_ok, int mix) { + int64_t tsym = ray_sym_intern("t", 1); + for (int i = 0; qs[i].q; i++) { + ray_t* out[2]; + for (int gen = 0; gen <= 2; gen += 2) { + char b[512]; + if (qs[i].kind == 'k' || qs[i].kind == 'o') + snprintf(b, sizeof b, "(set T (.db.parted.get \"" AW_TMP "/%s%c%d\" 't))", tag, qs[i].kind, gen); + else + snprintf(b, sizeof b, "(set T (.db.splayed.get \"" AW_TMP "/%s%c%d/\"))", tag, qs[i].kind, gen); + aw_eval_ok(b); + ray_enc_counters_reset(); + out[gen / 2] = ray_eval_str(qs[i].q); + TEST_ASSERT_FMT(out[gen / 2] && !RAY_IS_ERR(out[gen / 2]), "%s%c%d %s: %s", tag, qs[i].kind, gen, + qs[i].q, ray_error_msg()); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + ray_t* t = ray_eval_str("T"); + ray_t* encv = ray_table_get_col_enc(t, tsym); + ray_enccol_info_t info; + TEST_ASSERT_TRUE(encv && !ray_enccol_info(encv, &info)); + ray_release(t); + if (qs[i].mode != AW_SK_DECLINE) { + TEST_ASSERT_FMT(!info.materialized, "%s%c %s: t materialized", tag, qs[i].kind, qs[i].q); + if (qs[i].kind == 'c' && mix == AW_SK_MIX_SELECT) + TEST_ASSERT_FMT(info.vectors[RAY_ENC_CONST] > 0 && + info.vectors[RAY_ENC_FSST] + info.vectors[RAY_ENC_RAW] > 0, + "%sc: RAW %lld CONST %lld STR_DICT %lld FSST %lld", tag, + (long long)info.vectors[RAY_ENC_RAW], (long long)info.vectors[RAY_ENC_CONST], + (long long)info.vectors[RAY_ENC_STR_DICT], (long long)info.vectors[RAY_ENC_FSST]); + else if (qs[i].kind != 'n' && qs[i].kind != 'o') { + if (mix == AW_SK_MIX_SELECT) + TEST_ASSERT_FMT(info.vectors[RAY_ENC_STR_DICT] > 0 && info.vectors[RAY_ENC_RAW] == 0 && + info.vectors[RAY_ENC_CONST] == 0 && info.vectors[RAY_ENC_FSST] == 0, + "%s%c: RAW %lld CONST %lld STR_DICT %lld FSST %lld", tag, qs[i].kind, + (long long)info.vectors[RAY_ENC_RAW], (long long)info.vectors[RAY_ENC_CONST], + (long long)info.vectors[RAY_ENC_STR_DICT], (long long)info.vectors[RAY_ENC_FSST]); + else + TEST_ASSERT_FMT(info.vectors[RAY_ENC_RAW] > 0 && info.vectors[RAY_ENC_CONST] == 0 && + info.vectors[RAY_ENC_STR_DICT] == 0 && info.vectors[RAY_ENC_FSST] == 0, + "%s%c: not all RAW", tag, qs[i].kind); + } + } + if (strict_ok && qs[i].mode == AW_SK_STRICT) + TEST_ASSERT_FMT(k.materialized == 0, "%s%c %s: %llu materializations", tag, qs[i].kind, qs[i].q, + (unsigned long long)k.materialized); + ray_t* fx = ray_fmt(out[0], 0); ray_t* fy = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fx) == ray_str_len(fy) && memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0, + "%s%c %s differs", tag, qs[i].kind, qs[i].q); + ray_release(fx); ray_release(fy); ray_release(out[0]); ray_release(out[1]); + } + aw_eval_ok("(set T 0)"); + PASS(); +} + +static const aw_sk_q_t* aw_str_key_queries(void); +static test_result_t aw_str_key_run(const char* ts, const char* tl, int mix) { + /* ts: the brief's sizes (the serial strategy); tl: above the parallel + * threshold, every partition too */ + aw_str_key_tables(ts, 5000, 10000); + aw_str_key_tables(tl, 70000, 140000); + test_result_t r = aw_str_key_check(ts, aw_str_key_queries(), false, mix); + if (r.status != TEST_PASS) return r; + return aw_str_key_check(tl, aw_str_key_queries(), true, mix); +} + +/* The key column as selection writes it (P6: all STR_DICT). Subject: the + * string-domain path over STR_DICT vectors; the persisted DICT would take + * the large tables' keys (P6b), so they are saved without it. */ +static test_result_t test_str_key_domain(void) { + ray_col_test_no_dict(true); + test_result_t r = aw_str_key_run("s", "l", AW_SK_MIX_SELECT); + ray_col_test_no_dict(false); + return r; +} + +/* P6: RAW STR vectors are this twin's subject (the cursor path the key took + * before STR_DICT): the same tables saved with every STR vector forced RAW, + * and without the persisted DICT, which would take the large tables' keys + * (P6b). */ +static test_result_t test_str_key_domain_raw(void) { + ray_encw_test_force_str(RAY_ENC_RAW); + ray_col_test_no_dict(true); + test_result_t r = aw_str_key_run("rs", "rl", AW_SK_MIX_RAW); + ray_col_test_no_dict(false); + ray_encw_test_force_str(-1); + return r; +} + +/* P6b: the same tables as saved, the large ones with the persisted DICT: + * a single-file key groups on its codes, a parted one remaps each DICT + * segment's codes; the same answers, nothing of t materialized. */ +static test_result_t test_str_key_domain_dict(void) { + test_result_t r = aw_str_key_run("ds", "dl", AW_SK_MIX_SELECT); + if (r.status != TEST_PASS) return r; + /* not vacuous: a large single-file key and a large partition record it */ + static const char* const lds[] = { + "(.db.splayed.get \"" AW_TMP "/dlu2/\")", "(.db.splayed.get \"" AW_TMP "/dlk2/2024.01.01/t/\")", + }; + for (int i = 0; i < 2; i++) { + ray_t* t = ray_eval_str(ray_test_tmp(lds[i])); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_meta_t m; + const bool ok = ray_table_col_meta(t, ray_sym_intern("t", 1), &m) && m.enc && m.index_kind == RAY_IDX_DICT; + ray_release(t); + TEST_ASSERT_FMT(ok, "%s: no persisted DICT", lds[i]); + } + PASS(); +} + +static const aw_sk_q_t* aw_str_key_queries(void) { + /* group order is the route's; asc: makes the comparison order-insensitive */ + static const aw_sk_q_t qs[] = { + { 'k', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t asc: t})" }, + { 'k', AW_SK_KEY, "(select {c: (count v) from: T by: {t: t m: (% v 3)} asc: [t m]})" }, /* composite */ + { 'u', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t asc: t})" }, + { 'u', AW_SK_KEY, "(select {c: (count v) from: T by: {t: t m: (% v 3)} asc: [t m]})" }, + { 'n', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t asc: t})" }, + { 'n', AW_SK_KEY, "(select {c: (count v) from: T by: {t: t m: (% v 3)} asc: [t m]})" }, + /* no asc: the ids are in first-occurrence order over the rows + * read (the selection, under a filter), so a route emitting groups + * by first occurrence (or by id) emits generation 0's order */ + { 'n', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t})" }, + { 'u', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t})" }, + { 'k', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t})" }, + { 'o', AW_SK_STRICT, "(select {c: (count v) from: T where: (> v 3) by: t})" }, + { 'o', AW_SK_STRICT, "(select {c: (count v) from: T where: (> v 100) by: t})" }, + { 'u', AW_SK_STRICT, "(select {c: (count v) from: T where: (> v 3000) by: t})" }, + /* a composite without asc: on a single-file column generation 0 + * groups on its DICT codes (RAY_DICT_MIN_ROWS rows and up) or as STR, + * and the ids take the same routes; a parted one is not compared + * unsorted (generation 0's segments group as STR, by first + * occurrence of the tuple, where the ids take the dense route, in + * slot order) */ + { 'u', AW_SK_KEY, "(select {c: (count v) from: T by: {k: (% v 4) t: t}})" }, + { 'n', AW_SK_KEY, "(select {c: (count v) from: T where: (> v 50) by: {t: t k: (% v 4)}})" }, + /* the swap declines: the key column is read by an aggregate or by + * another key's expression */ + { 'u', AW_SK_DECLINE, "(select {f: (first t) c: (count v) from: T by: t asc: t})" }, + { 'n', AW_SK_DECLINE, "(select {c: (count t) from: T by: t asc: t})" }, + { 'k', AW_SK_DECLINE, "(select {d: (count (distinct t)) from: T by: t asc: t})" }, + { 'k', AW_SK_DECLINE, "(select {c: (count v) from: T by: {t: t u: (concat t \"x\")} asc: t})" }, + { 'n', AW_SK_DECLINE, "(select {c: (count v) from: T by: {t: t l: (strlen t)} asc: [t l]})" }, + /* CONST vectors (kind c): the key path's cursor over CONST and + * FSST / RAW vectors, sorted and in first-occurrence order */ + { 'c', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t asc: t})" }, + { 'c', AW_SK_STRICT, "(select {c: (count v) s: (sum v) from: T by: t})" }, + { 'c', AW_SK_STRICT, "(select {c: (count v) from: T where: (> v 1000) by: t})" }, + { 'c', AW_SK_KEY, "(select {c: (count v) from: T by: {t: t m: (% v 3)} asc: [t m]})" }, + { 0, 0, NULL }, + }; + return qs; +} + +/* ray_pool_dispatch clamped to a ring whose growth fails (#792; shrunk to a + * few slots so the clamp runs at test sizes): fused where: filters + * (pred_sel_drive and the expression selection, whose rowsel builders are + * per grain), the scalar route and the other grain users answer as + * unclamped. */ +static test_result_t test_pool_clamp(void) { + static test_result_t (*const fns[])(void) = { + test_scalar_route_mixed, test_eq_runs_lack, test_filter_encoded_leaves, test_scalar_route_stats, + test_count_on_runs, test_group_count_on_runs, test_topk_prune_cases, + test_gather_sym_points, test_sort_head_late, test_group_topn_ties, test_group_topn_nulls, + test_group_topn_affine, test_group_affine_nulls, + }; + static const uint32_t caps[] = { 7, 3 }; + for (size_t c = 0; c < sizeof caps / sizeof *caps; c++) + for (size_t i = 0; i < sizeof fns / sizeof *fns; i++) { + (void)ray_test_rm_rf(aw_root()); (void)ray_test_mkdir_p(aw_root()); + ray_pool_test_ring_fail(caps[c]); + g_aw_unaligned = true; + test_result_t r = fns[i](); + g_aw_unaligned = false; + ray_pool_test_ring_fail(0); + if (r.status != TEST_PASS) return r; + } + /* generation-0 callers of the grain: fused where (pred_sel_drive and the + * expression selection), count distinct by group (cdpg_*), and the sort's + * sortedness estimate, on an in-memory table */ + aw_eval_ok("(set M (table [k g x] (list (til 300000) (% (* (til 300000) 7919) 97) (% (* (til 300000) 31) 1009))))"); + static const char* const qs[] = { + "(select {c: (count k) s: (sum x) from: M where: (< x 500)})", + "(select {c: (count k) s: (sum x) from: M where: (in x [1 2 3 500 777])})", /* pred_sel_worker */ + "(select {c: (count k) from: M where: (and (> x 100) (< g 50))})", + "(select {u: (count (distinct x)) by: g from: M})", + "(take (select {k: k x: x from: M asc: x}) 20)", + "(take (select {k: k from: M where: (== (% x 3) 0) desc: k}) 5)", + NULL, + }; + for (int i = 0; qs[i]; i++) { + ray_t* a = ray_eval_str(qs[i]); + ray_pool_test_ring_fail(3); + ray_t* b = ray_eval_str(qs[i]); + ray_pool_test_ring_fail(0); + TEST_ASSERT_FMT(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b), "%s", qs[i]); + ray_t* fa = ray_fmt(a, 0); ray_t* fb = ray_fmt(b, 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s: clamped dispatch differs", qs[i]); + ray_release(fa); ray_release(fb); ray_release(a); ray_release(b); + } + /* count distinct per group over 60001 groups: the partitioned kernel + * (cdpg_*), whose per-task counters follow the clamped geometry */ + { + const int64_t n = 300000, ng = 60001; + ray_t* src = ray_vec_new(RAY_I64, n); + int64_t* gid = (int64_t*)malloc((size_t)n * sizeof(int64_t)); + TEST_ASSERT_TRUE(src && !RAY_IS_ERR(src) && gid); + src->len = n; + for (int64_t i = 0; i < n; i++) { ((int64_t*)ray_data(src))[i] = (i * 31) % 1009; gid[i] = (i * 7) % ng; } + ray_t* a = ray_count_distinct_per_group(src, gid, n, ng); + ray_pool_test_ring_fail(3); + ray_t* b = ray_count_distinct_per_group(src, gid, n, ng); + ray_pool_test_ring_fail(0); + TEST_ASSERT_TRUE(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && a->len == ng && b->len == ng); + TEST_ASSERT_TRUE(memcmp(ray_data(a), ray_data(b), (size_t)ng * sizeof(int64_t)) == 0); + ray_release(a); ray_release(b); ray_release(src); free(gid); + } + PASS(); +} + +/* ---- Task 12: the P3 gate --------------------------------------------- */ + +/* P3 gate: filtered, rowsel-gather and aggregate shapes, planning included. */ +static test_result_t test_gate_materialization(void) { + aw_save("gm", AW_WIDE, -1); + static const char* const q[] = { + "(select {from: T where: (and (>= k 1000) (< k 3000))})", /* filter + gather */ + "(select {k: k t: t from: T where: (== s 'b) take: 9})", /* SYM equality + take */ + "(select {s: (sum v) a: (avg v) c: (count t) from: T where: (< g 3)})", /* aggregates under a filter */ + "(select {c: (count k) from: T where: (!= s 'a) by: g})", + "(select {c: (count k) from: T by: t})", /* STR key */ + "(sum (at T 'v))", + NULL, + }; + for (int i = 0; q[i]; i++) AW_SAME("gm", q[i], 0); + AW_SAME("gm", "(select {t: t from: T where: (> v 10) desc: v take: 3})", 0); /* top-k: the sort key read by range */ + /* a staged scalar count reads no values: t decodes nothing, and "" + * (STR null) rows count, as on generation 0 */ + AW_SAME("gm", "(select {c: (count t) from: T where: (< g 3)})", 0); + TEST_ASSERT_FMT(aw_col_decoded("t") == 0, "t decoded %llu", (unsigned long long)aw_col_decoded("t")); + aw_save("gn", "(table [g t] (list (as 'I16 (% (til 70000) 7)) " + "(map (fn [j] (if (== 0 (% j 5)) \"\" (format \"text value %\" (% j 333)))) (til 70000))))", -1); + AW_SAME("gn", "(select {c: (count t) d: (count g) from: T where: (< g 3)})", 0); + TEST_ASSERT_FMT(aw_col_decoded("t") == 0, "t decoded %llu", (unsigned long long)aw_col_decoded("t")); + PASS(); +} + +/* Decoded bytes: zero where statistics or codes answer, exact otherwise. */ +static test_result_t test_gate_decoded_bytes(void) { + aw_save("gd", "(table [k x] (list (til 70000) (as 'I32 (% (til 70000) 50))))", RAY_ENC_FOR_BP); + test_result_t r; + if ((r = aw_reduce("gd", "(select {c: (count k) from: T where: (== x 7)})", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("gd", "(select {s: (sum x) from: T})", 0)).status != TEST_PASS) return r; + /* k's leaf runs on FOR_BP. 10 selected rows in x's vector 0 are under + * the FOR_BP point-read limit (RAY_ENC_VEC/32, Task 6b's D2), so they + * are read in place and nothing decodes; 100 rows are over it, so x's + * vector 0 (1024 I32 rows) is decoded and gathered. */ + if ((r = aw_reduce("gd", "(select {x: x from: T where: (< k 10)})", 0)).status != TEST_PASS) return r; + if ((r = aw_reduce("gd", "(select {x: x from: T where: (< k 100)})", 1024 * 4)).status != TEST_PASS) return r; + PASS(); +} + +/* Cross-segment codes: integer VALUE_DICT per partition, the same value + * under different codes and the same code for different values. */ +static test_result_t test_cross_segment_codes(void) { + for (int p = 0; p < 2; p++) { + char q[600]; + /* v repeats within 997 values: every column of the table is forced + * to DICT, and the chunk-0 dictionary (65536 entries at most) must + * cover chunk 1's values */ + snprintf(q, sizeof q, "(table [x v] (list (as 'I32 %s) (%% (til 70000) 997)))", + p ? "(- (% (til 70000) 40) 1000)" : "(% (til 70000) 40)"); /* -1000..-961 / 0..39 */ + char name[16]; snprintf(name, sizeof name, "cs%d", p); + aw_save(name, q, RAY_ENC_DICT); + } + /* assemble both generation-2 tables as partitions of one parted table */ + ray_encw_test_force(RAY_ENC_DICT); /* the re-encode keeps each partition's own VALUE_DICT */ + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/csp/2024.01.01/t/\" (.db.splayed.get \"" AW_TMP "/cs02/\") \"" AW_TMP "/csp/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/csp/2024.01.02/t/\" (.db.splayed.get \"" AW_TMP "/cs12/\") \"" AW_TMP "/csp/.sym\")"); + ray_encw_test_force(-1); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/csq/2024.01.01/t/\" (.db.splayed.get \"" AW_TMP "/cs00/\") \"" AW_TMP "/csq/.sym\")"); + aw_eval_ok("(.db.splayed.set \"" AW_TMP "/csq/2024.01.02/t/\" (.db.splayed.get \"" AW_TMP "/cs10/\") \"" AW_TMP "/csq/.sym\")"); + /* the re-saves inherit generation 2 from their encoded sources, and + * generation 0 from their plain ones */ + for (int gen = 0; gen <= 2; gen += 2) { + ray_t* g = aw_eval(gen ? "(at (.idx.info (.db.parted.get \"" AW_TMP "/csp\" 't) 'x) 'gen)" + : "(at (.idx.info (.db.parted.get \"" AW_TMP "/csq\" 't) 'x) 'gen)"); + TEST_ASSERT_FMT(g && !RAY_IS_ERR(g) && g->i64 == gen, "generation %d: %lld", gen, + g && !RAY_IS_ERR(g) ? (long long)g->i64 : -1LL); + ray_release(g); + } + /* every vector of x in both partitions (2 x 69) is DICT over its own + * partition's dictionary */ + ray_t* nd = aw_eval("(at (at (.idx.info (.db.parted.get \"" AW_TMP "/csp\" 't) 'x) 'enc) 'dict)"); + TEST_ASSERT_FMT(nd && !RAY_IS_ERR(nd) && nd->i64 == 138, "DICT vectors: %lld", + nd && !RAY_IS_ERR(nd) ? (long long)nd->i64 : -1LL); + ray_release(nd); + static const char* const qs[] = { + "(count (select {from: (.db.parted.get \"" AW_TMP "/%s\" 't) where: (== x 5)}))", + "(count (select {from: (.db.parted.get \"" AW_TMP "/%s\" 't) where: (< x -990)}))", + "(select {c: (count v) from: (.db.parted.get \"" AW_TMP "/%s\" 't) by: x asc: x})", + "(select {v: v from: (.db.parted.get \"" AW_TMP "/%s\" 't) where: (in x [3 -997])})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, qs[i], "csq"); snprintf(b, sizeof b, qs[i], "csp"); + ray_t* x = aw_eval(a); + ray_enc_counters_reset(); + ray_t* y = aw_eval(b); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(x && y && !RAY_IS_ERR(x) && !RAY_IS_ERR(y)); + TEST_ASSERT_FMT(k.materialized == 0, "query %d materialized %llu", i, (unsigned long long)k.materialized); + /* `5` matches 1750 rows of partition 0, `< -990` 17500 of partition + * 1: equal counts of zero would pin nothing (checked on the + * generation-0 answer; the generation-2 one equals it below) */ + if (i < 2) TEST_ASSERT_FMT(x->i64 == (i ? 17500 : 1750), "query %d counted %lld", i, (long long)x->i64); + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); + TEST_ASSERT_FMT(ray_str_len(fx) == ray_str_len(fy) && memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0, "query %d", i); + ray_release(fx); ray_release(fy); ray_release(x); ray_release(y); + } + PASS(); +} + +/* A parted `in` / `not in` filter over generation 2 reads each segment by + * range through its own source and probe (exec_in_parted_selection), at + * any position in the where: chain: first (the fused selection), later + * (intersected with the selection installed), after a selective `==` (the + * survivors' compact), grouped and row-returning. Three partitions of + * 70000 rows (segments end inside a morsel); x's values differ per + * partition; nullable integer, SYM and F64 columns, and w with nulls only + * after partition 0 (each segment's own probe and null flag). The chained + * shapes run under a selection with dropped (NONE) morsels and under one + * mixed in every morsel. Answers equal generation 0's; nothing + * materializes. */ +static test_result_t test_parted_in(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) { + char q[1600]; + snprintf(q, sizeof q, + "(.db.splayed.set \"" AW_TMP "/pi%d/2024.01.0%d/t/\" (table [k x v s f w] (list (+ (til 70000) %d) " + "(as 'I32 (- (%% (til 70000) 40) %d)) " + "(as 'I32 (map (fn [j] (if (== 0 (%% j 9)) 0N (%% j 1000))) (til 70000))) " + "(take ['a 'b 'c 'd 'e] 70000) (as 'F64 (%% (til 70000) 50)) %s)) " + "\"" AW_TMP "/pi%d/.sym\" {compress: %s})", + gen, p + 1, p * 70000, p * 500, + p ? "(as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (% j 1000))) (til 70000)))" + : "(as 'I32 (% (til 70000) 1000))", + gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + static const char* const qs[] = { + "(select {from: T where: (in x [3 -497 -980 5])})", /* first, row-returning */ + "(count (select {from: T where: (not-in x [3 -497 -980 5])}))", + "(select {c: (count k) s: (sum v) from: T where: (and (> v 10) (in x [3 -497 -980])) by: x asc: x})", /* second, grouped */ + "(select {c: (count k) from: T where: (and (> v 10) (in x [3 -497]) (< v 900)) by: s asc: s})", /* middle */ + "(select {c: (count k) from: T where: (and (> v 10) (not-in x [3 -497 -998]) (< v 900))})", + "(select {k: k v: v from: T where: (and (== k 70005) (in x [5 -495 -1000]))})", /* after a selective == */ + "(select {c: (count k) from: T where: (in v [1 2 3 9 500])})", /* nullable column */ + "(select {c: (count k) from: T where: (not-in v [1 2 3 9 500])})", + "(select {c: (count k) from: T where: (and (> k 1000) (in s ['a 'c])) by: s asc: s})", + "(select {c: (count k) from: T where: (not-in s ['a 'c])})", + "(select {c: (count k) from: T where: (and (> k 1000) (in f [1.0 7.0 -0.0]))})", + /* w has nulls only after partition 0: each segment answers with its + * own null flag */ + "(select {c: (count k) from: T where: (in w [1 2 3 9 500])})", + "(select {c: (count k) from: T where: (not-in w [1 2 3 9 500])})", + "(select {c: (count k) from: T where: (and (> k 1000) (not-in w [1 2 3 9 500])) by: s asc: s})", + /* x matches partition 0 only, so it is installed first and the + * selection drops every morsel of partitions 1-2 (NONE): the s + * conjunct runs through the chained route, in both written orders + * and with not-in */ + "(count (select {from: T where: (and (in x [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]) (in s ['a 'c]))}))", + "(count (select {from: T where: (and (in s ['a 'c]) (in x [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]))}))", + "(count (select {from: T where: (and (not-in x [-500 -499 -498 -497 -496 -495 -494 -493 -492 -491 -490 -489 -488 -487 -486 -485 -484 -483 -482 -481 -480 -479 -478 -477 -476 -475 -474 -473 -472 -471 -470 -469 -468 -467 -466 -465 -464 -463 -462 -461 -1000 -999 -998 -997 -996 -995 -994 -993 -992 -991 -990 -989 -988 -987 -986 -985 -984 -983 -982 -981 -980 -979 -978 -977 -976 -975 -974 -973 -972 -971 -970 -969 -968 -967 -966 -965 -964 -963 -962 -961]) (in s ['a 'c]))}))", + "(count (select {from: T where: (and (in s ['a 'c]) (not-in x [-500 -499 -498 -497 -496 -495 -494 -493 -492 -491 -490 -489 -488 -487 -486 -485 -484 -483 -482 -481 -480 -479 -478 -477 -476 -475 -474 -473 -472 -471 -470 -469 -468 -467 -466 -465 -464 -463 -462 -461 -1000 -999 -998 -997 -996 -995 -994 -993 -992 -991 -990 -989 -988 -987 -986 -985 -984 -983 -982 -981 -980 -979 -978 -977 -976 -975 -974 -973 -972 -971 -970 -969 -968 -967 -966 -965 -964 -963 -962 -961]))}))", + "(count (select {from: T where: (and (in x [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]) (not-in s ['a 'c]))}))", + /* s is installed first (mixed in every morsel) and x runs chained: + * x == 4 rows are all 'e, outside the selection */ + "(count (select {from: T where: (and (in s ['a 'b 'c 'd]) (in x [3 4 -497 -496 -980]))}))", + "(select {c: (count k) from: T where: (and (in s ['a 'b 'c 'd]) (in x [3 4 -497 -496 -980])) by: x asc: x})", + "(select {c: (count k) from: T where: (in x [12345])})", /* matches nothing */ + "(select {c: (count k) from: T where: (and (> k 1000) (not-in x [100000]))})", /* every row */ + NULL, + }; + for (int i = 0; qs[i]; i++) { + ray_t* out[2]; + for (int gen = 0; gen <= 2; gen += 2) { + char b[256]; + snprintf(b, sizeof b, "(set T (.db.parted.get \"" AW_TMP "/pi%d\" 't))", gen); + aw_eval_ok(b); + ray_enc_counters_reset(); + out[gen / 2] = ray_eval_str(qs[i]); + TEST_ASSERT_FMT(out[gen / 2] && !RAY_IS_ERR(out[gen / 2]), "%s gen %d: %s", qs[i], gen, ray_error_msg()); + if (gen) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == 0, "%s: %llu materializations", qs[i], (unsigned long long)k.materialized); + } + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s differs", qs[i]); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + aw_eval_ok("(set T 0)"); + PASS(); +} + +/* The results of `q` in generation 0 (a) and generation 2 (b), both owned: + * either the same error code, or the same type and formatted result. */ +static test_result_t aw_cmp_pair(const char* q, ray_t* a, ray_t* b) { + TEST_ASSERT_FMT(a && b, "%s: no result (gen 0 %p, gen 2 %p)", q, (void*)a, (void*)b); + bool e0 = RAY_IS_ERR(a), e2 = RAY_IS_ERR(b); + TEST_ASSERT_FMT(e0 == e2, "%s: error in one generation only", q); + if (e0) { + TEST_ASSERT_FMT(strcmp(ray_err_code(a), ray_err_code(b)) == 0, "%s: %s vs %s", q, + ray_err_code(a), ray_err_code(b)); + ray_error_free(a); ray_error_free(b); + PASS(); + } + TEST_ASSERT_FMT(a->type == b->type, "%s: type %d vs %d", q, a->type, b->type); + ray_t* fa = ray_fmt(a, 0); ray_t* fb = ray_fmt(b, 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, "%s differs", q); + ray_release(fa); ray_release(fb); ray_release(a); ray_release(b); + PASS(); +} + +/* Either the same error code in both generations, or equal formatted results. */ +static test_result_t aw_same_or_err(const char* name, const char* q) { + char buf[2048]; ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s%d/\"))", name, gen ? 2 : 0); + aw_eval_ok(buf); + out[gen] = aw_eval(q); + } + return aw_cmp_pair(q, out[0], out[1]); +} +#define AW_SAME_OR_ERR(n, q) do { test_result_t r_ = aw_same_or_err((n), (q)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* `q` formats as `want` in both generations: an absolute pin, for the + * properties gen 0 and gen 2 share code for (a shared mistake passes + * aw_same_or_err). */ +static test_result_t aw_expect(const char* name, const char* q, const char* want) { + char buf[2048]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s%d/\"))", name, gen ? 2 : 0); + aw_eval_ok(buf); + ray_t* r = aw_eval(q); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "%s gen %d: %s", q, gen ? 2 : 0, r ? ray_error_msg() : "no result"); + ray_t* f = ray_fmt(r, 0); + bool ok = ray_str_len(f) == strlen(want) && memcmp(ray_str_ptr(f), want, strlen(want)) == 0; + TEST_ASSERT_FMT(ok, "%s gen %d: %.*s, want %s", q, gen ? 2 : 0, (int)ray_str_len(f), ray_str_ptr(f), want); + ray_release(f); ray_release(r); + } + PASS(); +} +#define AW_EXPECT(n, q, w) do { test_result_t r_ = aw_expect((n), (q), (w)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* Saved SYM width class of column `col` of table 2, or -1. */ +static int aw_sym_width(const char* name, const char* col) { + ray_t* t = aw_load(name, 2); + ray_t* encv = t ? ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))) : NULL; + ray_enccol_t* e = encv ? ray_enccol_of(encv) : NULL; + int w = e ? (int)(e->attrs & RAY_SYM_W_MASK) : -1; + if (t) ray_release(t); + return w; +} + +/* Rows of column f of the loaded T holding -0.0 / +0.0 (by sign bit), read + * from the evaluated column; -1 if it does not come back as a plain F64. */ +static void aw_zero_signs(int64_t* neg, int64_t* pos) { + *neg = *pos = -1; + ray_t* r = ray_eval_str("(at T 'f)"); + if (r && !RAY_IS_ERR(r) && r->type == RAY_F64) { + const double* d = (const double*)ray_data(r); + *neg = *pos = 0; + for (int64_t i = 0; i < r->len; i++) + if (d[i] == 0.0) { if (signbit(d[i])) (*neg)++; else (*pos)++; } + } + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); +} + +/* Both generations of hold exactly `neg` -0.0 and `pos` +0.0 rows. */ +static test_result_t aw_zero_rows(const char* name, int64_t neg, int64_t pos) { + char buf[512]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s%d/\"))", name, gen ? 2 : 0); + aw_eval_ok(buf); + int64_t n, p; aw_zero_signs(&n, &p); + TEST_ASSERT_FMT(n == neg && p == pos, "%s gen %d: %lld -0.0 / %lld +0.0 rows, want %lld / %lld", name, + gen ? 2 : 0, (long long)n, (long long)p, (long long)neg, (long long)pos); + } + PASS(); +} +#define AW_ZERO_ROWS(n, a, b) do { test_result_t r_ = aw_zero_rows((n), (a), (b)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* The sign bit of the F64 result of `q` (an atom or a one-element vector) + * is the same in both generations. */ +static test_result_t aw_zero_mm(const char* name, const char* q) { + char buf[512]; int sb[2]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" AW_TMP "/%s%d/\"))", name, gen ? 2 : 0); + aw_eval_ok(buf); + ray_t* r = aw_eval(q); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "%s gen %d failed", q, gen ? 2 : 0); + double x; + if (r->type == -RAY_F64) x = r->f64; + else { TEST_ASSERT_FMT(r->type == RAY_F64 && r->len == 1, "%s: type %d", q, r->type); x = ((const double*)ray_data(r))[0]; } + TEST_ASSERT_FMT(x == 0.0, "%s gen %d: not a zero", q, gen ? 2 : 0); + sb[gen] = signbit(x) ? 1 : 0; + ray_release(r); + } + TEST_ASSERT_FMT(sb[0] == sb[1], "%s: sign bit %d in gen 0, %d in gen 2", q, sb[0], sb[1]); + PASS(); +} +#define AW_ZERO_MM(n, q) do { test_result_t r_ = aw_zero_mm((n), (q)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* The szc table 2 (vector v of 1024 rows: -0.0 when v % 3 == 0, + * +0.0 when 1, alternating -0.0 / +0.0 when 2), over 64 Ki rows: min / max + * of a selection keep the first selected row's zero under the scalar-grain + * hook (row order, one task). */ +static test_result_t aw_szc_first_zero(const char* name) { + char q[256]; + snprintf(q, sizeof q, "(set T (.db.splayed.get \"" AW_TMP "/%s2/\"))", name); + aw_eval_ok(q); + static const int64_t los[] = { -1, 0, 1000, 1023, 1024, 2047, 64511, 65000, 65535, 65536, 66000 }; + static const int64_t his[] = { 131072, 65536, 65537, 66560, 70000 }; + static const int64_t grains[] = { RAY_COL_BLOCK_ROWS, 131072 }; + for (int g = 0; g < 2; g++) + for (int l = 0; l < 11; l++) for (int h = 0; h < 5; h++) for (int m = 0; m < 2; m++) { + if (his[h] <= los[l] + 1) continue; + int64_t r0 = los[l] + 1, v0 = r0 / 1024; /* the first selected row */ + bool want_neg = v0 % 3 == 0 || (v0 % 3 == 2 && r0 % 2 == 0); + snprintf(q, sizeof q, "(at (select {r: (%s f) from: T where: (and (> k %lld) (< k %lld))}) 'r)", + m ? "max" : "min", (long long)los[l], (long long)his[h]); + ray_group_test_scalar_grain(grains[g]); + ray_t* r = aw_eval(q); + ray_group_test_scalar_grain(0); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_F64 && r->len == 1, "%s failed", q); + double x = ((const double*)ray_data(r))[0]; + ray_release(r); + TEST_ASSERT_FMT(x == 0.0 && (signbit(x) != 0) == want_neg, "%s, grain %lld: %s0.0, want %s0.0", q, + (long long)grains[g], signbit(x) ? "-" : "+", want_neg ? "-" : "+"); + } + PASS(); +} + +/* The signed-zero tables [k f] built in C and saved as aw_save does: the + * zeros are bit patterns (D10). Rayfall cannot build them in a release + * build, where the literal 0.0 parses as -0.0 (#850, -fno-signed-zeros) and + * (neg 0.0) is then +0.0. shape 0 (sz): rows < 1024 -0.0, < 2048 +0.0, then + * -0.0 on even rows and 0.5 * (j - 2600) on odd ones; shape 1 (sz0): the + * same with +0.0 on the odd rows; shape 2 (szc): by vector v = j / 1024, + * -0.0 when v % 3 == 0, +0.0 when 1, -0.0 / +0.0 on even / odd rows when 2. */ +static void aw_save_zeros(const char* name, int shape, int64_t n, int enc) { + const uint64_t neg0 = 1ull << 63, pos0 = 0; + ray_t* k = ray_vec_new(RAY_I64, n); + ray_t* f = ray_vec_new(RAY_F64, n); + if (!k || !f) { fprintf(stderr, "aw_save_zeros: oom\n"); abort(); } + k->len = f->len = n; + for (int64_t j = 0; j < n; j++) { + ((int64_t*)ray_data(k))[j] = j; + uint64_t b; + if (shape == 2) { + int64_t v = j / 1024; + b = v % 3 == 0 ? neg0 : v % 3 == 1 ? pos0 : (j % 2 == 0 ? neg0 : pos0); + } else if (j < 1024) b = neg0; + else if (j < 2048) b = pos0; + else if (j % 2 == 0) b = neg0; + else if (shape == 1) b = pos0; + else { double x = 0.5 * (double)(j - 2600); memcpy(&b, &x, 8); } + memcpy((double*)ray_data(f) + j, &b, 8); + } + ray_t* tb = ray_table_new(2); + tb = ray_table_add_col(tb, ray_sym_intern("k", 1), k); ray_release(k); + tb = ray_table_add_col(tb, ray_sym_intern("f", 1), f); ray_release(f); + if (ray_env_set(ray_sym_intern("W", 1), tb) != RAY_OK) { fprintf(stderr, "aw_save_zeros: bind\n"); abort(); } + ray_release(tb); + char q[512]; + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s0/\" W {compress: false})", name); + aw_eval_ok(q); + ray_encw_test_force(enc); + snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/%s2/\" W {compress: true})", name); + aw_eval_ok(q); + ray_encw_test_force(-1); +} + +/* Signed zeros: CONST vectors of -0.0 and of +0.0 next to a RAW vector + * mixing both; every comparison with both zero literals, in, min, max (which + * zero) and a float top-k. */ +static test_result_t test_signed_zeros(void) { + /* The zeros are built in C (aw_save_zeros): inside one lambda the + * literals -0.0 and 0.0 share a constant-pool slot (compile.c + * add_constant compares by ==, #824), and in a release build the literal + * 0.0 is itself -0.0 (#850), so no rayfall form holds both zeros there. */ + aw_save_zeros("sz", 0, 3072, -1); + TEST_ASSERT_EQ_I(aw_vec_enc("sz", "f", 0), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(aw_vec_enc("sz", "f", 1), RAY_ENC_CONST); + AW_ZERO_ROWS("sz", 1024 + 512, 1024); + static const char* const ops[] = { "==", "!=", "<", "<=", ">", ">=" }; + static const char* const lits[] = { "0.0", "-0.0" }; + char q[256]; + for (int o = 0; o < 6; o++) for (int l = 0; l < 2; l++) { + snprintf(q, sizeof q, "(count (select {from: T where: (%s f %s)}))", ops[o], lits[l]); + AW_SAME_OR_ERR("sz", q); + } + AW_SAME_OR_ERR("sz", "(count (select {from: T where: (in f [0.0 1.5])}))"); + AW_SAME_OR_ERR("sz", "(count (select {from: T where: (in f [-0.0])}))"); + AW_SAME_OR_ERR("sz", "(min (at T 'f))"); + AW_SAME_OR_ERR("sz", "(max (at T 'f))"); + AW_SAME_OR_ERR("sz", "(select {f: f k: k from: T where: (> k 1000) asc: f take: 5})"); + AW_SAME_OR_ERR("sz", "(select {f: f k: k from: T where: (> k 1000) desc: f take: 5})"); + /* Zeros only: which zero min / max return (1/x tells them apart) and how + * the top-k orders -0.0 against 0.0 (k shows the rows taken). */ + aw_save_zeros("sz0", 1, 3072, -1); + TEST_ASSERT_EQ_I(aw_vec_enc("sz0", "f", 0), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(aw_vec_enc("sz0", "f", 1), RAY_ENC_CONST); + /* P5: the mixed +/-0.0 vector has two distinct values, so selection now + * takes DICT (it was RAW); the sign answers below hold for either body. */ + TEST_ASSERT_EQ_I(aw_vec_enc("sz0", "f", 2), RAY_ENC_DICT); + AW_ZERO_ROWS("sz0", 1024 + 512, 1024 + 512); + /* Rayfall prints both zeros as 0.0 and 1/0 is null, so the sign of a + * min / max result is read in C: aw_zero_mm compares it across generations. */ + AW_ZERO_MM("sz0", "(min (at T 'f))"); + AW_ZERO_MM("sz0", "(max (at T 'f))"); + AW_ZERO_MM("sz0", "(at (select {r: (min f) from: T where: (> k 1000)}) 'r)"); + AW_ZERO_MM("sz0", "(at (select {r: (max f) from: T where: (> k 1000)}) 'r)"); + AW_SAME_OR_ERR("sz0", "(select {f: f k: k from: T where: (> k 1000) asc: f take: 5})"); + AW_SAME_OR_ERR("sz0", "(select {f: f k: k from: T where: (> k 1000) desc: f take: 5})"); + AW_SAME_OR_ERR("sz0", "(select {f: f k: k from: T asc: f take: 5})"); + AW_SAME_OR_ERR("sz0", "(select {f: f k: k from: T desc: f take: 5})"); + /* P5: the same mix as a RAW body (the pre-P5 shape): every vector RAW */ + aw_save_zeros("sz0r", 1, 3072, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(aw_vec_enc("sz0r", "f", 2), RAY_ENC_RAW); + AW_ZERO_ROWS("sz0r", 1024 + 512, 1024 + 512); + AW_ZERO_MM("sz0r", "(min (at T 'f))"); + AW_ZERO_MM("sz0r", "(max (at T 'f))"); + AW_ZERO_MM("sz0r", "(at (select {r: (min f) from: T where: (> k 1000)}) 'r)"); + AW_ZERO_MM("sz0r", "(at (select {r: (max f) from: T where: (> k 1000)}) 'r)"); + AW_SAME_OR_ERR("sz0r", "(select {f: f k: k from: T where: (> k 1000) asc: f take: 5})"); + AW_SAME_OR_ERR("sz0r", "(select {f: f k: k from: T where: (> k 1000) desc: f take: 5})"); + AW_SAME_OR_ERR("sz0r", "(select {f: f k: k from: T asc: f take: 5})"); + AW_SAME_OR_ERR("sz0r", "(select {f: f k: k from: T desc: f take: 5})"); + /* Two chunks of zero vectors: -0.0 CONST, +0.0 CONST, a RAW mix, in + * turn. Selections cut inside vectors, at vector and chunk edges, so + * vectors answered from statistics, row-read runs and whole chunks + * alternate in every order. Over 64 Ki rows both generations dispatch + * in parallel and the merge of the workers' zeros is not row order, so + * generation 2 runs in row order under the scalar-grain hook (whole + * blocks, and one task) and must keep the first selected row's zero. */ + aw_save_zeros("szc", 2, 131072, -1); + TEST_ASSERT_EQ_I(aw_vec_enc("szc", "f", 63), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(aw_vec_enc("szc", "f", 64), RAY_ENC_CONST); + /* P5: the +/-0.0 mix now selects DICT (it was RAW) */ + TEST_ASSERT_EQ_I(aw_vec_enc("szc", "f", 65), RAY_ENC_DICT); + { test_result_t r_ = aw_szc_first_zero("szc"); if (r_.status != TEST_PASS) return r_; } + /* P5 (Task 7): the same vectors as RAW bodies (the pre-P5 shape of + * vector 65, and CONST vectors 63 / 64 read as rows) */ + aw_save_zeros("szcr", 2, 131072, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(aw_vec_enc("szcr", "f", 63), RAY_ENC_RAW); + TEST_ASSERT_EQ_I(aw_vec_enc("szcr", "f", 64), RAY_ENC_RAW); + TEST_ASSERT_EQ_I(aw_vec_enc("szcr", "f", 65), RAY_ENC_RAW); + { test_result_t r_ = aw_szc_first_zero("szcr"); if (r_.status != TEST_PASS) return r_; } + PASS(); +} + +/* Symbol order is lexical, not by id: symbols first seen as z, a, m, SYM + * forced to FOR_BP; range operators, LIKE, min, max and top-k equal + * generation 0; equality and in still decide by ids. */ +static test_result_t test_symbol_order(void) { + aw_save("so", "(table [k s] (list (til 3000) (as 'SYMBOL (map (fn [j] (at [\"z\" \"a\" \"m\" \"b\"] (% j 4))) (til 3000)))))", RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_vec_enc("so", "s", 0), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_vec_enc("so", "s", 2), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_sym_width("so", "s"), RAY_SYM_W8); + /* Absolute pins: gen 0 and gen 2 share the string-order code of min, max, + * LIKE and the top-k, so equal answers alone would not catch id order. + * The range operators compare by string in both generations (#738): + * z a m b repeat, 750 rows each. */ + AW_EXPECT("so", "(count (select {from: T where: (< s 'm)}))", "1500"); + AW_EXPECT("so", "(count (select {from: T where: (>= s 'b)}))", "2250"); + AW_EXPECT("so", "(min (at T 's))", "a"); + AW_EXPECT("so", "(max (at T 's))", "z"); + AW_EXPECT("so", "(at (select {s: s k: k from: T asc: s take: 3}) 's)", "[a a a]"); + AW_EXPECT("so", "(at (select {s: s k: k from: T desc: [s k] take: 3}) 's)", "[z z z]"); + AW_EXPECT("so", "(at (select {s: s k: k from: T desc: [s k] take: 3}) 'k)", "[2996 2992 2988]"); + AW_EXPECT("so", "(count (select {from: T where: (like s \"*a*\")}))", "750"); + AW_SAME_OR_ERR("so", "(count (select {from: T where: (< s 'm)}))"); + AW_SAME_OR_ERR("so", "(count (select {from: T where: (>= s 'b)}))"); + AW_SAME_OR_ERR("so", "(count (select {from: T where: (like s \"*a*\")}))"); + AW_SAME_OR_ERR("so", "(min (at T 's))"); + AW_SAME_OR_ERR("so", "(max (at T 's))"); + AW_SAME_OR_ERR("so", "(select {s: s k: k from: T asc: s take: 3})"); + AW_SAME_OR_ERR("so", "(select {s: s k: k from: T desc: [s k] take: 3})"); + AW_SAME_OR_ERR("so", "(count (select {from: T where: (== s 'm)}))"); + AW_SAME_OR_ERR("so", "(count (select {from: T where: (in s ['z 'b])}))"); + PASS(); +} + +/* aw_same_or_err on the parted tables adp0 / adp2, loaded as P. */ +static test_result_t aw_parted_same_or_err(const char* q) { + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + aw_eval_ok(gen ? "(set P (.db.parted.get \"" AW_TMP "/adp2\" 't))" : "(set P (.db.parted.get \"" AW_TMP "/adp0\" 't))"); + out[gen] = aw_eval(q); + } + return aw_cmp_pair(q, out[0], out[1]); +} +#define AW_PARTED_SAME_OR_ERR(q) do { test_result_t r_ = aw_parted_same_or_err(q); if (r_.status != TEST_PASS) return r_; } while (0) + +/* Aggregate admission: sum, avg, count, min, max over every type, flat, + * under a selection and parted: same values, types and errors. */ +static test_result_t test_agg_admission(void) { + const char* tbl = + "(table [k b u h i l f e d t ts s x] (list (til 3000) (== 0 (% (til 3000) 3)) (as 'U8 (% (til 3000) 250)) " + "(as 'I16 (- (% (til 3000) 300) 150)) (as 'I32 (- (til 3000) 1500)) (* (til 3000) 1000003) " + "(at (select {e: (as 'F32 x) from: (table [x] (list (* 0.5 (til 3000))))}) 'e) (* 0.25 (til 3000)) (as 'DATE (% (til 3000) 900)) (as 'TIME (* 1000 (til 3000))) " + "(as 'TIMESTAMP (* 1000000 (til 3000))) (as 'SYMBOL (map (fn [j] (format \"s%\" (% j 7))) (til 3000))) " + "(map (fn [j] (format \"string %\" (% j 11))) (til 3000))))"; + /* `as 'F32` is a query-projection cast only, so column f is cast inside a select. */ + aw_save("ad", tbl, -1); + for (int p = 0; p < 2; p++) for (int gen = 0; gen <= 2; gen += 2) { + char q[1600]; + int n = snprintf(q, sizeof q, "(.db.splayed.set \"" AW_TMP "/adp%d/2024.01.0%d/t/\" %s {compress: %s})", + gen, p + 1, tbl, gen ? "true" : "false"); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof q); + aw_eval_ok(q); + } + static const char* const cols[] = { "b", "u", "h", "i", "l", "f", "e", "d", "t", "ts", "s", "x" }; + static const char* const aggs[] = { "sum", "avg", "count", "min", "max" }; + char q[512]; + for (int c = 0; c < 12; c++) for (int a = 0; a < 5; a++) { + snprintf(q, sizeof q, "(select {r: (%s %s) from: T})", aggs[a], cols[c]); + AW_SAME_OR_ERR("ad", q); + snprintf(q, sizeof q, "(select {r: (%s %s) from: T where: (> k 1700)})", aggs[a], cols[c]); + AW_SAME_OR_ERR("ad", q); + snprintf(q, sizeof q, "(select {r: (%s %s) from: P})", aggs[a], cols[c]); + AW_PARTED_SAME_OR_ERR(q); + } + PASS(); +} + +/* SYM ids at widths 8 and 16 across the sign bit (ids 127/128 and + * 32767/32768) and U8 values across 127/128: min, max, count, the + * not-admitted sum / avg errors, and equality. */ +static test_result_t test_sign_bit_widths(void) { + aw_save("w8", "(table [s u] (list (as 'SYMBOL (map (fn [j] (format \"v%\" (% j 200))) (til 5000))) (as 'U8 (+ 100 (% (til 5000) 60)))))", RAY_ENC_FOR_BP); + aw_save("w16", "(table [s] (list (as 'SYMBOL (map (fn [j] (format \"v%\" (% j 40000))) (til 80000)))))", RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_vec_enc("w8", "s", 0), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_vec_enc("w8", "s", 4), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_sym_width("w8", "s"), RAY_SYM_W8); + TEST_ASSERT_EQ_I(aw_vec_enc("w16", "s", 0), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_vec_enc("w16", "s", 78), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(aw_sym_width("w16", "s"), RAY_SYM_W16); + static const char* const q8[] = { + "(min (at T 's))", "(max (at T 's))", "(count (at T 's))", "(sum (at T 's))", "(avg (at T 's))", + "(count (select {from: T where: (== s 'v127)}))", "(count (select {from: T where: (== s 'v128)}))", + "(sum (at T 'u))", "(avg (at T 'u))", "(min (at T 'u))", "(max (at T 'u))", + "(count (select {from: T where: (> u 127)}))", NULL, + }; + for (int i = 0; q8[i]; i++) AW_SAME_OR_ERR("w8", q8[i]); + static const char* const q16[] = { + "(min (at T 's))", "(max (at T 's))", + "(count (select {from: T where: (== s 'v32767)}))", "(count (select {from: T where: (== s 'v32768)}))", + "(count (select {from: T where: (in s ['v32767 'v32768 'v1])}))", NULL, + }; + for (int i = 0; q16[i]; i++) AW_SAME_OR_ERR("w16", q16[i]); + PASS(); +} + +/* Top-k on F64, BOOL, U8 and SYM first keys: results equal, the fused top-k + * takes each query on generation 2, and nothing is pruned. */ +static test_result_t test_topk_never_pruned(void) { + aw_save("tn", "(table [f b u v s] (list (map (fn [j] (if (== 0 (% j 97)) 0N (* 0.5 (- j 100000)))) (til 200000)) " + "(== 0 (% (til 200000) 5)) (as 'U8 (% (til 200000) 251)) (% (til 200000) 1000) " + "(as 'SYMBOL (map (fn [j] (format \"k%\" (% j 300))) (til 200000)))))", -1); + static const char* const q[] = { + "(select {f: f from: T where: (> v 10) asc: f take: 7})", + "(select {f: f from: T where: (> v 10) desc: f take: 7})", + "(select {b: b v: v from: T where: (> v 990) asc: [b v] take: 7})", + "(select {u: u v: v from: T where: (> v 990) desc: [u v] take: 7})", + "(select {s: s v: v from: T where: (> v 990) asc: [s v] take: 7})", /* SYM first key: never pruned */ + NULL, + }; + for (int i = 0; q[i]; i++) { + AW_SAME_OR_ERR("tn", q[i]); /* leaves T on generation 2 */ + /* Run it once more on generation 2 alone: the fused top-k must take + * it (else the pruned counters would be another call's). */ + ray_fused_topk_counters_reset(); + ray_t* r = aw_eval(q[i]); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "%s: gen 2 rerun failed", q[i]); + ray_release(r); + uint64_t ran = 0, dec = 0; + ray_fused_topk_counters(&ran, &dec); + TEST_ASSERT_FMT(ran >= 1 && dec == 0, "%s: fused top-k ran %llu declined %llu", q[i], + (unsigned long long)ran, (unsigned long long)dec); + uint64_t pc = 1, pv = 1; + ray_fused_topk_test_pruned(&pc, &pv); + TEST_ASSERT_FMT(pc == 0 && pv == 0, "%s pruned %llu chunks %llu vectors", q[i], + (unsigned long long)pc, (unsigned long long)pv); + } + PASS(); +} + +/* A splayed generation-2 `in` / `not in` filter later in the where: + * chain (P3 Task 14b) reads its column by range over the morsels the + * installed selection keeps, ANDed with it (exec_in_parted_selection's + * single-file arm), as the first conjunct does: nullable integer, SYM and + * F64 columns, middle and last conjuncts, grouped and counted. Answers + * equal generation 0's; nothing materializes (the generic OP_IN read the + * column whole). */ +static test_result_t test_splayed_in_later(void) { + aw_save("il", "(table [k x v s f b t] (list (til 210000) (as 'I32 (- (% (til 210000) 40) (* 500 (div (til 210000) 70000)))) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N (% j 1000))) (til 210000))) " + "(take ['a 'b 'c 'd 'e] 210000) (as 'F64 (% (til 210000) 50)) " + "(as 'I16 (% (til 210000) 2)) (as 'I16 (- (% (til 210000) 11) 1))))", -1); + static const char* const qs[] = { + "(select {c: (count k) s: (sum v) from: T where: (and (> v 10) (in x [3 -497 -980])) by: x asc: x})", + "(select {c: (count k) from: T where: (and (> v 10) (in x [3 -497]) (< v 900)) by: s asc: s})", + "(select {c: (count k) from: T where: (and (> v 10) (not-in x [3 -497 -998]) (< v 900))})", + "(select {k: k v: v from: T where: (and (== k 70005) (in x [5 -495 -1000]))})", + "(select {c: (count k) from: T where: (and (> f 10.0) (in v [1 2 3 9 500]))})", + "(select {c: (count k) from: T where: (and (> f 10.0) (not-in v [1 2 3 9 500]))})", + "(select {c: (count k) from: T where: (and (> v 10) (in s ['a 'c])) by: s asc: s})", + "(select {c: (count k) from: T where: (and (> v 10) (not-in s ['a 'c]))})", + "(select {c: (count k) from: T where: (and (> v 10) (in f [1.0 7.0 -0.0]))})", + "(select {c: (count k) from: T where: (and (> v 10) (in x [12345]))})", + "(select {c: (count k) from: T where: (and (> v 10) (not-in x [100000]))})", + "(select {c: (count k) from: T where: (and (== b 0) (in t [-1 6]))})", + "(select {c: (count k) from: T where: (and (== b 1) (not-in t [-1 6 9]))})", + "(select {c: (count k) from: T where: (and (== b 0) (in f [1.0 7.0 -0.0]))})", + "(select {c: (count k) from: T where: (and (== b 0) (in v [1 2 3 9 500]))})", + "(select {c: (count k) from: T where: (and (< v 100) (in x [3 -497 -980]))})", + "(select {c: (count k) from: T where: (and (< v 100) (in f [1.0 7.0 -0.0]))})", + "(select {c: (count k) from: T where: (and (== b 0) (not-in x [3 -497]))})", + "(select {c: (count k) from: T where: (and (== b 0) (not-in f [1.0 7.0]))})", + NULL, + }; + static const char* const in_col[] = { "x", "x", "x", "x", "v", "v", "s", "s", "f", "x", "x", "t", "t", "f", "v", "x", "f", "x", "f" }; + /* the rows that reach exec_node's later-conjunct `in` (the others take + * another route, which the materialization check covers): SYM, I16, + * I32 and F64; each is answered by in_sel_single_within (route + * counter), so disabling that arm for any type fails here */ + static const bool routed[] = { 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1 }; + for (int i = 0; qs[i]; i++) { + uint64_t w0 = ray_exec_test_in_single_within(); + AW_SAME("il", qs[i], 0); + if (routed[i]) + TEST_ASSERT_FMT(ray_exec_test_in_single_within() == w0 + 1, "%s: not read by range over the selection", qs[i]); + /* and the column stays unmaterialized (T: generation 2) */ + char b[128]; + snprintf(b, sizeof b, "(at (.idx.info T '%s) 'materialized)", in_col[i]); + ray_t* mt = aw_eval(b); + TEST_ASSERT_FMT(mt && !RAY_IS_ERR(mt) && mt->b8 == 0, "%s: %s materialized", qs[i], in_col[i]); + ray_release(mt); + } + PASS(); +} + +/* A parted group's (strlen c) SUM / AVG input (ClickBench q28: avg + * (strlen URL) by CounterID) is aggregated by each partition's group over + * the borrowed segment, by range on generation 2, as the splayed group + * does: the SYM segments (URL's type in the ClickBench schema) are not + * materialized (the per-partition path evaluated the expression into a + * column, reading each segment whole). Three partitions of 70000 rows, + * under a filter and without one, with a column without "" and one + * holding it; answers equal generation 0's. */ +static test_result_t test_parted_strlen_avg(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) { + char q[1200]; + snprintf(q, sizeof q, + "(.db.splayed.set \"" AW_TMP "/ps%d/2024.01.0%d/t/\" (table [g u w v] (list (%% (til 70000) 13) " + "(as 'SYM (as 'STR (* (%% (til 70000) 997) %d))) " + "(as 'SYMBOL (map (fn [j] (if (== 0 (%% j 7)) \"\" (format \"w%%\" (%% j 50)))) (til 70000))) (til 70000))) " + "\"" AW_TMP "/ps%d/.sym\" {compress: %s})", + gen, p + 1, 1000 + p * 7, gen, gen ? "true" : "false"); + aw_eval_ok(q); + } + static const char* const qs[] = { + "(select {l: (avg (strlen u)) c: (count v) from: T where: (!= w \"\") by: g asc: g})", + "(select {l: (avg (strlen w)) s: (sum (strlen u)) c: (count v) from: T by: g asc: g})", + "(select {l: (avg (strlen w)) c: (count v) from: T where: (> v 1000) by: g asc: g})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + ray_t* out[2]; + for (int gen = 0; gen <= 2; gen += 2) { + char b[256]; + snprintf(b, sizeof b, "(set T (.db.parted.get \"" AW_TMP "/ps%d\" 't))", gen); + aw_eval_ok(b); + ray_enc_counters_reset(); + int64_t pp0 = ray_group_perpart_done(); + out[gen / 2] = ray_eval_str(qs[i]); + TEST_ASSERT_FMT(out[gen / 2] && !RAY_IS_ERR(out[gen / 2]), "%s gen %d: %s", qs[i], gen, ray_error_msg()); + /* the per-partition group returned the answer (not its concat fallback) */ + TEST_ASSERT_FMT(ray_group_perpart_done() == pp0 + 1, "%s gen %d: not the per-partition group", qs[i], gen); + if (gen) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == 0, "%s: %llu materializations", qs[i], (unsigned long long)k.materialized); + } + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s differs", qs[i]); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + aw_eval_ok("(set T 0)"); + PASS(); +} + +const test_entry_t aware_entries[] = { + { "aware/vview_encodings", test_vview_encodings, aw_setup, aw_teardown }, + { "aware/vview_near_top", test_vview_near_top, aw_setup, aw_teardown }, + { "aware/vview_declines", test_vview_declines, aw_setup, aw_teardown }, + { "aware/vview_source", test_vview_source, aw_setup, aw_teardown }, + { "aware/eval_encodings", test_eval_encodings, aw_setup, aw_teardown }, + { "aware/eval_for_edges", test_eval_for_edges, aw_setup, aw_teardown }, + { "aware/eval_const_nulls", test_eval_const_nulls, aw_setup, aw_teardown }, + { "aware/eval_in", test_eval_in, aw_setup, aw_teardown }, + { "aware/eval_gen0", test_eval_gen0, aw_setup, aw_teardown }, + { "aware/eval_sym", test_eval_sym, aw_setup, aw_teardown }, + { "aware/eval_float_const", test_eval_float_const, aw_setup, aw_teardown }, + { "aware/filter_encoded_leaves", test_filter_encoded_leaves, aw_setup, aw_teardown }, + { "aware/filter_vector_decisions", test_filter_vector_decisions, aw_setup, aw_teardown }, + { "aware/filter_nulls_masked", test_filter_nulls_masked, aw_setup, aw_teardown }, + { "aware/filter_floats", test_filter_floats, aw_setup, aw_teardown }, + { "aware/filter_mixed_generations", test_filter_mixed_generations, aw_setup, aw_teardown }, + { "aware/filter_parted_leaves", test_filter_parted_leaves, aw_setup, aw_teardown }, + { "aware/fused_pred_leaves", test_fused_pred_leaves, aw_setup, aw_teardown }, + { "aware/filter_leaf_ops", test_filter_leaf_ops, aw_setup, aw_teardown }, + { "aware/sym_membership", test_sym_membership, aw_setup, aw_teardown }, + { "aware/sym_in_bounds", test_sym_in_bounds, aw_setup, aw_teardown }, + { "aware/sym_null_literal", test_sym_null_literal, aw_setup, aw_teardown }, + { "aware/sym_fused_gen0", test_sym_fused_gen0, aw_setup, aw_teardown }, + { "aware/float_in_bounds", test_float_in_bounds, aw_setup, aw_teardown }, + { "aware/gather_rows_contract", test_gather_rows_contract, aw_setup, aw_teardown }, + { "aware/gather_sel_skips_none", test_gather_sel_skips_none, aw_setup, aw_teardown }, + { "aware/gather_sel_parted", test_gather_sel_parted, aw_setup, aw_teardown }, + { "aware/gather_gen0_parity", test_gather_gen0_parity, aw_setup, aw_teardown }, + { "aware/gather_rows_sorted", test_gather_rows_sorted, aw_setup, aw_teardown }, + { "aware/gather_empty_and_nulls", test_gather_empty_and_nulls, aw_setup, aw_teardown }, + { "aware/gather_ragged", test_gather_ragged, aw_setup, aw_teardown }, + { "aware/gather_operators", test_gather_operators, aw_setup, aw_teardown }, + { "aware/gather_index_rows", test_gather_index_rows, aw_setup, aw_teardown }, + { "aware/gather_list_cells", test_gather_list_cells, aw_setup, aw_teardown }, + { "aware/gather_compact_group", test_gather_compact_group, aw_setup, aw_teardown }, + { "aware/gather_refine", test_gather_refine, aw_setup, aw_teardown }, + { "aware/gather_parted_sym", test_gather_parted_sym, aw_setup, aw_teardown }, + { "aware/gather_filter_ops", test_gather_filter_ops, aw_setup, aw_teardown }, + { "aware/gather_sel_parallel", test_gather_sel_parallel, aw_setup, aw_teardown }, + { "aware/refine_in", test_refine_in, aw_setup, aw_teardown }, + { "aware/gather_sel_late_null_cancel", test_gather_sel_late_null_cancel, aw_setup, aw_teardown }, + { "aware/firstn_by_range", test_firstn_by_range, aw_setup, aw_teardown }, + { "aware/firstn_parted", test_firstn_parted, aw_setup, aw_teardown }, + { "aware/sparse_key_points", test_sparse_key_points, aw_setup, aw_teardown }, + { "aware/gather_points", test_gather_points, aw_setup, aw_teardown }, + { "aware/gather_raw_points", test_gather_raw_points, aw_setup, aw_teardown }, + { "aware/gather_sym_points", test_gather_sym_points, aw_setup, aw_teardown }, + { "aware/sort_head_late", test_sort_head_late, aw_setup, aw_teardown }, + { "aware/firstn_runs", test_firstn_runs, aw_setup, aw_teardown }, + { "aware/firstn_sel", test_firstn_sel, aw_setup, aw_teardown }, + { "aware/sparse_walk_points", test_sparse_walk_points, aw_setup, aw_teardown }, + { "aware/sym_key_chunk_extremes", test_sym_key_chunk_extremes, aw_setup, aw_teardown }, + { "aware/sym_key_points", test_sym_key_points, aw_setup, aw_teardown }, + { "aware/leaf_emit_runs", test_leaf_emit_runs, aw_setup, aw_teardown }, + { "aware/da_prescan_abort_staged", test_da_prescan_abort_staged, aw_setup, aw_teardown }, + { "aware/refine_on_views", test_refine_on_views, aw_setup, aw_teardown }, + { "aware/eq_on_runs", test_eq_runs_lack, aw_setup, aw_teardown }, + { "aware/gather_rows_parallel", test_gather_rows_parallel, aw_setup, aw_teardown }, + { "aware/sum_extremes", test_sum_extremes, aw_setup, aw_teardown }, + { "aware/sum_parted_dir", test_sum_parted_dir, aw_setup, aw_teardown }, + { "aware/sum_parted_ragged", test_sum_parted_ragged, aw_setup, aw_teardown }, + { "aware/float_sum_decoded", test_float_sum_decoded, aw_setup, aw_teardown }, + { "aware/sum_encoded_vectors", test_sum_encoded_vectors, aw_setup, aw_teardown }, + { "aware/agg_under_selection", test_agg_under_selection, aw_setup, aw_teardown }, + { "aware/scalar_route_stats", test_scalar_route_stats, aw_setup, aw_teardown }, + { "aware/scalar_route_mixed", test_scalar_route_mixed, aw_setup, aw_teardown }, + { "aware/scalar_route_parted", test_scalar_route_parted, aw_setup, aw_teardown }, + { "aware/scalar_route_parted_stats", test_scalar_route_parted_stats, aw_setup, aw_teardown }, + { "aware/scalar_route_time", test_scalar_route_time, aw_setup, aw_teardown }, + { "aware/scalar_route_float_inf", test_scalar_route_float_inf, aw_setup, aw_teardown }, + { "aware/unaligned_grain", test_unaligned_grain, aw_setup, aw_teardown }, + { "aware/pool_clamp", test_pool_clamp, aw_setup, aw_teardown }, + { "aware/count_on_runs", test_count_on_runs, aw_setup, aw_teardown }, + { "aware/group_count_on_runs", test_group_count_on_runs, aw_setup, aw_teardown }, + { "aware/topk_prune_cases", test_topk_prune_cases, aw_setup, aw_teardown }, + { "aware/topk_range_keys", test_topk_range_keys, aw_setup, aw_teardown }, + { "aware/group_topn_ties", test_group_topn_ties, aw_setup, aw_teardown }, + { "aware/group_topn_nulls", test_group_topn_nulls, aw_setup, aw_teardown }, + { "aware/group_topn_affine", test_group_topn_affine, aw_setup, aw_teardown }, + { "aware/group_affine_nulls", test_group_affine_nulls, aw_setup, aw_teardown }, + { "aware/str_key_domain", test_str_key_domain, aw_setup, aw_teardown }, + { "aware/str_key_domain_raw", test_str_key_domain_raw, aw_setup, aw_teardown }, + { "aware/str_key_domain_dict", test_str_key_domain_dict, aw_setup, aw_teardown }, + { "aware/gate_materialization", test_gate_materialization, aw_setup, aw_teardown }, + { "aware/gate_decoded_bytes", test_gate_decoded_bytes, aw_setup, aw_teardown }, + { "aware/cross_segment_codes", test_cross_segment_codes, aw_setup, aw_teardown }, + { "aware/parted_in", test_parted_in, aw_setup, aw_teardown }, + { "aware/splayed_in_later", test_splayed_in_later, aw_setup, aw_teardown }, + { "aware/parted_strlen_avg", test_parted_strlen_avg, aw_setup, aw_teardown }, + { "aware/signed_zeros", test_signed_zeros, aw_setup, aw_teardown }, + { "aware/symbol_order", test_symbol_order, aw_setup, aw_teardown }, + { "aware/agg_admission", test_agg_admission, aw_setup, aw_teardown }, + { "aware/sign_bit_widths", test_sign_bit_widths, aw_setup, aw_teardown }, + { "aware/topk_never_pruned", test_topk_never_pruned, aw_setup, aw_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_colrange.c b/test/test_colrange.c new file mode 100644 index 000000000..ef258ffdc --- /dev/null +++ b/test/test_colrange.c @@ -0,0 +1,634 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#define _POSIX_C_SOURCE 200809L +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "table/domain.h" +#include "table/table.h" +#include "store/col.h" +#include "store/colrange.h" +#include "store/encw.h" +#include "store/enccol.h" +#include "store/splay.h" +#include "store/part.h" +#include "vec/str.h" +#include "vec/vec.h" +#include +#include + +#define CR_TMP "/tmp/rayforce_colrange" + +/* 256 interned symbols, so SYM test ids up to 255 lie inside the runtime domain. */ +static void cr_setup(void) { + ray_heap_init(); (void)ray_sym_init(); (void)ray_test_mkdir_p(ray_test_tmp(CR_TMP)); + for (int i = 0; i < 256; i++) { char b[8]; int n = snprintf(b, sizeof b, "s%d", i); (void)ray_sym_intern(b, (size_t)n); } +} +static void cr_teardown(void) { ray_test_hooks_off(); ray_sym_destroy(); ray_heap_destroy(); (void)ray_test_rm_rf(ray_test_tmp(CR_TMP)); } + +static ray_t* i32_nulls(int64_t n) { + ray_t* v = ray_vec_new(RAY_I32, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int32_t*)ray_data(v))[i] = (i % 5 == 0) ? NULL_I32 : (int32_t)i; + v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} + +/* Deterministic column of `type`; `nulls` puts the type's null in every 7th + * row. STR mixes inline, pooled and empty (null) strings. */ +static ray_t* gen_col(int8_t type, int64_t n, bool nulls, uint8_t symw) { + if (type == RAY_STR) { + ray_t* v = ray_vec_new(RAY_STR, n); + char buf[64]; + for (int64_t i = 0; i < n; i++) { + int len; + if (nulls && i % 7 == 0) len = 0; + else if (i % 3 == 0) len = snprintf(buf, sizeof buf, "ab%lld", (long long)(i % 50)); + else len = snprintf(buf, sizeof buf, "pooled string number %lld", (long long)(i * 31 % 100000)); + v = ray_str_vec_append(v, buf, (size_t)len); + } + return v; + } + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(symw, n) : ray_vec_new(type, n); + v->len = n; + uint8_t* d = ray_data(v); + for (int64_t i = 0; i < n; i++) { + bool null = nulls && i % 7 == 0; + uint64_t x = (uint64_t)(i / 3) * 2654435761u % 1000003u; + switch (type) { + case RAY_BOOL: d[i] = (uint8_t)(x & 1); break; + case RAY_U8: d[i] = (uint8_t)x; break; + case RAY_I16: { int16_t y = null ? NULL_I16 : (int16_t)(x % 30000); memcpy(d + i * 2, &y, 2); break; } + case RAY_I32: case RAY_DATE: case RAY_TIME: + { int32_t y = null ? NULL_I32 : (int32_t)(x * 977 % 2000000000); memcpy(d + i * 4, &y, 4); break; } + case RAY_I64: case RAY_TIMESTAMP: + { int64_t y = null ? NULL_I64 : (int64_t)x * 1000003; memcpy(d + i * 8, &y, 8); break; } + case RAY_F32: { float y = null ? NULL_F32 : (float)(int64_t)(x % 100000) / 8.0f; memcpy(d + i * 4, &y, 4); break; } + case RAY_F64: { double y = null ? NULL_F64 : (double)(int64_t)(x % 1000000) / 16.0; memcpy(d + i * 8, &y, 8); break; } + case RAY_GUID: { memset(d + i * 16, 0, 16); if (!null) { memcpy(d + i * 16, &x, 8); d[i * 16 + 15] = 1; } break; } + case RAY_SYM: ray_write_sym(d, i, null ? 0 : 1 + x % 200, RAY_SYM, v->attrs); break; + } + } + if (nulls && type != RAY_BOOL && type != RAY_U8 && type != RAY_SYM) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} + +/* Row `row` of the plain vector `ref` against row i of the view. */ +static const char* cmp_row(const ray_col_range_t* r, int64_t i, ray_t* ref, int64_t row) { + if (r->type != ref->type) return "type"; + if (ref->type == RAY_SYM && (r->attrs & RAY_SYM_W_MASK) != (ref->attrs & RAY_SYM_W_MASK)) return "sym width"; + if (ref->type == RAY_SYM && r->dom != ray_sym_vec_domain(ref)) return "sym domain"; + bool is_null = ray_vec_is_null(ref, row); + if (is_null && !r->may_null) return "null in a range that says may_null false"; + if (ref->type == RAY_STR) { + const ray_str_t* a = (const ray_str_t*)r->data + i; + const ray_str_t* b = (const ray_str_t*)ray_data(ref) + row; + if (a->len != b->len) return "str len"; + if (a->len == 0) return NULL; + const char* rp = r->str_pool; + const char* fp = ref->str_pool ? (const char*)ray_data(ref->str_pool) : NULL; + if ((a->len > 12 && !rp) || (b->len > 12 && !fp)) return "str pool missing"; + return memcmp(ray_str_t_ptr(a, rp), ray_str_t_ptr(b, fp), a->len) == 0 ? NULL : "str bytes"; + } + uint8_t esz = ray_sym_elem_size(ref->type, ref->attrs); + return memcmp((const char*)r->data + (size_t)i * esz, (const char*)ray_data(ref) + (size_t)row * esz, esz) == 0 + ? NULL : "element"; +} + +/* Walk the whole source with requests of `req` rows; every returned range is + * compared with rows [ref_off + start, ...) of the plain vector `ref`. + * `gen2`: every range must stay inside one 1024-row vector. */ +static test_result_t walk_src(ray_col_src_t* s, ray_t* ref, int64_t ref_off, int64_t req, bool gen2) { + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + int64_t start = 0; + while (start < s->len) { + ray_t* err = ray_col_range(s, start, req, &sc, &r); + TEST_ASSERT_FMT(!err, "range @%lld: %s", (long long)start, err ? ray_err_code(err) : ""); + TEST_ASSERT_FMT(r.n > 0 && r.n <= req && start + r.n <= s->len, "n=%lld @%lld", (long long)r.n, (long long)start); + TEST_ASSERT_EQ_I(r.start, start); + if (gen2) TEST_ASSERT_FMT(start / 1024 == (start + r.n - 1) / 1024, "range @%lld n=%lld crosses a vector", (long long)start, (long long)r.n); + else { /* zero copy: clipped only at the source end */ + int64_t want = s->len - start < req ? s->len - start : req; + TEST_ASSERT_FMT(r.n == want, "gen0 n=%lld want %lld @%lld", (long long)r.n, (long long)want, (long long)start); + uint8_t esz = ray_sym_elem_size(ref->type, ref->attrs); + TEST_ASSERT_TRUE(r.data == (const char*)ray_data(ref) + (size_t)(ref_off + start) * esz); + } + for (int64_t i = 0; i < r.n; i++) { + const char* bad = cmp_row(&r, i, ref, ref_off + start + i); + TEST_ASSERT_FMT(!bad, "row %lld req %lld: %s", (long long)(start + i), (long long)req, bad ? bad : ""); + } + start += r.n; + } + TEST_ASSERT_EQ_I(start, s->len); + /* an empty request and the source end */ + TEST_ASSERT_NULL(ray_col_range(s, s->len, 10, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 0); + TEST_ASSERT_NULL(ray_col_range(s, 0, 0, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 0); + ray_col_scratch_free(&sc); + PASS(); +} + +/* Starts that land mid-vector and mid-chunk. */ +static test_result_t probe_src(ray_col_src_t* s, ray_t* ref, int64_t ref_off, bool gen2) { + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + for (int64_t start = 1; start < s->len; start += 4093) { + int64_t reqs[] = { 1, 37, 1100 }; + for (int k = 0; k < 3; k++) { + ray_t* err = ray_col_range(s, start, reqs[k], &sc, &r); + TEST_ASSERT_FMT(!err, "probe @%lld", (long long)start); + int64_t want = reqs[k]; + if (want > s->len - start) want = s->len - start; + if (gen2) { + int64_t vend = (start / 1024 + 1) * 1024; + if (want > vend - start) want = vend - start; + } + TEST_ASSERT_EQ_I(r.n, want); + for (int64_t i = 0; i < r.n; i++) { + const char* bad = cmp_row(&r, i, ref, ref_off + start + i); + TEST_ASSERT_FMT(!bad, "probe row %lld: %s", (long long)(start + i), bad ? bad : ""); + } + } + } + ray_col_scratch_free(&sc); + PASS(); +} + +#define RUN(call) do { test_result_t _r = (call); if (_r.status != TEST_PASS) return _r; } while (0) + +/* gen-0, slice of gen-0 and gen-2 sources of every P1 type, SYM widths, + * with and without nulls, against the materialized column. */ +static test_result_t test_range_matches_materialized(void) { + static const int8_t types[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, + RAY_TIMESTAMP, RAY_F32, RAY_F64, RAY_GUID, RAY_SYM, RAY_STR }; + static const uint8_t widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; + static const int64_t lens[] = { 1, 1023, 1025, 66000 }; + static const int64_t reqs[] = { 1000, 1024, 70000 }; + for (size_t t = 0; t < sizeof types; t++) + for (size_t w = 0; w < (types[t] == RAY_SYM ? 4u : 1u); w++) + for (size_t l = 0; l < 4; l++) + for (int nl = 0; nl < 2; nl++) { + int64_t n = lens[l]; + ray_t* v = gen_col(types[t], n, nl, widths[w]); + /* generation 0 */ + ray_col_src_t s; + TEST_ASSERT_NULL(ray_col_src_bind(v, &s)); + TEST_ASSERT_EQ_I(s.len, n); + TEST_ASSERT_EQ_I(s.type, types[t]); + for (size_t q = 0; q < 3; q++) RUN(walk_src(&s, v, 0, reqs[q], false)); + if (n > 5000) RUN(probe_src(&s, v, 0, false)); + ray_col_src_release(&s); + /* a slice of it */ + if (n >= 1023) { + ray_t* sl = ray_vec_slice(v, 700, n - 1000); + TEST_ASSERT_NULL(ray_col_src_bind(sl, &s)); + TEST_ASSERT_EQ_I(s.len, n - 1000); + RUN(walk_src(&s, v, 700, 1000, false)); + ray_col_src_release(&s); + ray_release(sl); + } + /* generation 2 */ + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CR_TMP "/c"), 2), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(CR_TMP "/c")); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "mmap"); + TEST_ASSERT_EQ_I(c->type, RAY_ENCCOL); + TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + TEST_ASSERT_EQ_I(s.len, n); + TEST_ASSERT_EQ_I(s.type, types[t]); + ray_t* mat = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(mat && !RAY_IS_ERR(mat)); + if (!nl) TEST_ASSERT_TRUE(!s.may_null); /* directory null counts prove it */ + for (size_t q = 0; q < 3; q++) RUN(walk_src(&s, mat, 0, reqs[q], true)); + RUN(walk_src(&s, v, 0, 1000, true)); /* and against the source rows */ + if (n > 5000) RUN(probe_src(&s, mat, 0, true)); + ray_col_src_release(&s); + ray_release(c); ray_release(v); + } + PASS(); +} + +static test_result_t test_range_gen0_zero_copy(void) { + ray_t* v = i32_nulls(5000); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(v, &s)); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + TEST_ASSERT_NULL(ray_col_range(&s, 1000, 3000, &sc, &r)); + TEST_ASSERT_EQ_PTR(r.data, (int32_t*)ray_data(v) + 1000); /* pointer identity */ + TEST_ASSERT_EQ_I(r.n, 3000); + TEST_ASSERT_TRUE(r.may_null); + TEST_ASSERT_NULL(ray_col_range(&s, 4990, 100, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 10); /* clipped at the end */ + TEST_ASSERT_TRUE(sc.fixed == NULL); /* generation 0 never touches scratch */ + ray_col_scratch_free(&sc); ray_col_src_release(&s); ray_release(v); + PASS(); +} + +static test_result_t test_range_gen2_vector_clip_and_nulls(void) { + ray_t* v = i32_nulls(5000); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CR_TMP "/a"), 2), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(CR_TMP "/a")); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + TEST_ASSERT_TRUE(s.may_null); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + for (int64_t start = 0; start < 5000; ) { /* task boundary 1000, not a chunk boundary */ + TEST_ASSERT_NULL(ray_col_range(&s, start, 1000, &sc, &r)); + int64_t vend = (start / 1024 + 1) * 1024; + int64_t want = 1000; + if (want > vend - start) want = vend - start; + if (want > 5000 - start) want = 5000 - start; + TEST_ASSERT_EQ_I(r.n, want); + TEST_ASSERT_EQ_I(r.start, start); + TEST_ASSERT_TRUE(r.may_null); + TEST_ASSERT_TRUE(memcmp(r.data, (int32_t*)ray_data(v) + start, (size_t)r.n * 4) == 0); /* sentinels in data */ + start += r.n; + } + TEST_ASSERT_EQ_U(sc.pool_cap, 0); + ray_col_scratch_free(&sc); ray_col_src_release(&s); + ray_release(c); ray_release(v); + PASS(); +} + +static test_result_t test_range_two_str_views(void) { + ray_t* a = ray_vec_new(RAY_STR, 3000); ray_t* b = ray_vec_new(RAY_STR, 3000); + char buf[64]; + for (int i = 0; i < 3000; i++) { + int n = snprintf(buf, sizeof buf, "pooled string number %d", i); + a = ray_str_vec_append(a, buf, (size_t)n); + n = snprintf(buf, sizeof buf, "another long text %d", i * 7); + b = ray_str_vec_append(b, buf, (size_t)n); + } + TEST_ASSERT_EQ_I(ray_col_save_gen(b, ray_test_tmp(CR_TMP "/b"), 2), RAY_OK); + ray_t* bc = ray_col_mmap(ray_test_tmp(CR_TMP "/b")); + ray_col_src_t sa, sb; + TEST_ASSERT_NULL(ray_col_src_bind(a, &sa)); /* generation 0 */ + TEST_ASSERT_NULL(ray_col_src_bind(bc, &sb)); /* generation 2 */ + ray_col_scratch_t xa, xb; ray_col_scratch_init(&xa); ray_col_scratch_init(&xb); + ray_col_range_t ra, rb; + TEST_ASSERT_NULL(ray_col_range(&sa, 1500, 1024, &xa, &ra)); + TEST_ASSERT_NULL(ray_col_range(&sb, 1500, 1024, &xb, &rb)); /* both views live */ + const ray_str_t* db = rb.data; + const ray_str_t* ob = (const ray_str_t*)ray_data(b) + 1500; + for (int64_t i = 0; i < rb.n; i++) { + TEST_ASSERT_EQ_I(db[i].len, ob[i].len); + TEST_ASSERT_TRUE(memcmp(ray_str_t_ptr(&db[i], rb.str_pool), ray_str_t_ptr(&ob[i], ray_data(b->str_pool)), ob[i].len) == 0); + TEST_ASSERT_EQ_I(db[i].hash32, 0); + } + for (int64_t i = 0; i < ra.n; i++) { /* the generation-0 view is still intact */ + const ray_str_t* x = (const ray_str_t*)ra.data + i; + const ray_str_t* y = (const ray_str_t*)ray_data(a) + 1500 + i; + TEST_ASSERT_TRUE(x->len == y->len && memcmp(ray_str_t_ptr(x, ra.str_pool), ray_str_t_ptr(y, ray_data(a->str_pool)), x->len) == 0); + } + ray_col_scratch_free(&xa); ray_col_scratch_free(&xb); + ray_col_src_release(&sa); ray_col_src_release(&sb); + ray_release(bc); ray_release(a); ray_release(b); + PASS(); +} + +static test_result_t test_range_slice_and_long_strings(void) { + ray_t* v = i32_nulls(5000); + ray_t* sl = ray_vec_slice(v, 100, 2000); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(sl, &s)); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + TEST_ASSERT_NULL(ray_col_range(&s, 1990, 100, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 10); /* slice boundary */ + TEST_ASSERT_EQ_PTR(r.data, (int32_t*)ray_data(v) + 2090); + ray_col_src_release(&s); ray_release(sl); ray_release(v); + /* scratch grows for a vector of 1000-byte strings: the RAW per-occurrence + * pool (forced RAW; selection takes STR_DICT, whose 26 distinct entries + * a range read copies once each, Ruling 3-1) */ + static char big[1000]; memset(big, 'x', sizeof big); + ray_t* st = ray_vec_new(RAY_STR, 1024); + for (int i = 0; i < 1024; i++) { big[0] = (char)('a' + i % 26); st = ray_str_vec_append(st, big, sizeof big); } + ray_encw_test_force_str(RAY_ENC_RAW); + ray_err_t se = ray_col_save_gen(st, ray_test_tmp(CR_TMP "/big"), 2); + ray_encw_test_force_str(-1); + TEST_ASSERT_EQ_I(se, RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(CR_TMP "/big")); + TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + TEST_ASSERT_NULL(ray_col_range(&s, 0, 1024, &sc, &r)); + TEST_ASSERT_TRUE(sc.pool_cap >= 1024 * 1000); + TEST_ASSERT_EQ_I(((const ray_str_t*)r.data)[1023].len, 1000); + ray_col_scratch_free(&sc); ray_col_src_release(&s); ray_release(c); ray_release(st); + PASS(); +} + +/* Bounds, scratch size and the memory of a released source. */ +static test_result_t test_range_bounds_and_scratch(void) { + ray_t* v = gen_col(RAY_GUID, 3000, true, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CR_TMP "/g"), 2), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(CR_TMP "/g")); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + TEST_ASSERT_NULL(ray_col_range(&s, 0, 5000, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 1024); /* the widest element fills the 16 KB part */ + TEST_ASSERT_TRUE(sc.fixed != NULL && sc.pool == NULL && sc.pool_cap == 0); + ray_t* e1 = ray_col_range(&s, 3001, 1, &sc, &r); /* past the end */ + TEST_ASSERT_TRUE(e1 && RAY_IS_ERR(e1)); TEST_ASSERT_STR_EQ(ray_err_code(e1), "range"); ray_error_free(e1); + e1 = ray_col_range(&s, -1, 1, &sc, &r); + TEST_ASSERT_TRUE(e1 && RAY_IS_ERR(e1)); ray_error_free(e1); + e1 = ray_col_range(&s, 0, -1, &sc, &r); + TEST_ASSERT_TRUE(e1 && RAY_IS_ERR(e1)); ray_error_free(e1); + TEST_ASSERT_NULL(ray_col_range(&s, 3000, 5, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 0); + ray_col_scratch_free(&sc); + TEST_ASSERT_TRUE(sc.fixed == NULL && sc.pool == NULL); + ray_col_scratch_free(&sc); /* idempotent */ + ray_col_src_release(&s); + TEST_ASSERT_TRUE(s.obj == NULL); + ray_col_src_release(&s); + ray_release(c); ray_release(v); + /* a bind of nothing is an error, not a crash */ + ray_t* eb = ray_col_src_bind(NULL, &s); + TEST_ASSERT_TRUE(eb && RAY_IS_ERR(eb)); ray_error_free(eb); + PASS(); +} + +static ray_err_t write_splayed_gen2(const char* dir, ray_t* tbl) { + if (ray_test_mkdir_p(dir) != 0) return RAY_ERR_IO; + int64_t nc = ray_table_ncols(tbl); + ray_t* names = ray_vec_new(RAY_STR, nc); + for (int64_t c = 0; c < nc; c++) { + ray_t* nm = ray_sym_str(ray_table_col_name(tbl, c)); + char p[512]; + if (snprintf(p, sizeof p, "%s/%.*s", dir, (int)ray_str_len(nm), ray_str_ptr(nm)) >= (int)sizeof p) { ray_release(names); return RAY_ERR_IO; } + ray_err_t e = ray_col_save_gen(ray_table_get_col_idx(tbl, c), p, 2); + if (e != RAY_OK) { ray_release(names); return e; } + names = ray_str_vec_append(names, ray_str_ptr(nm), ray_str_len(nm)); + } + char p[512]; + if (snprintf(p, sizeof p, "%s/.d", dir) >= (int)sizeof p) { ray_release(names); return RAY_ERR_IO; } + ray_err_t e = ray_col_save(names, p); + ray_release(names); + return e; +} + +/* Three partitions of t(a I64, s STR, b F64) of different lengths; the + * partitions in gen2_mask are generation 2. With `ragged` the last + * partition has no column b. */ +static ray_t* load_parted(const char* root, int gen2_mask, bool ragged) { + static const int64_t rows[3] = { 3000, 1024, 70000 }; + { /* the shared root symfile the SYM segments' ids resolve over */ + char sp[512]; snprintf(sp, sizeof sp, "%s/.sym", root); + if (ray_test_mkdir_p(root) != 0) return NULL; + ray_sym_domain_t* d = ray_sym_domain_open_or_create(sp); + if (!d) return NULL; + for (int i = 0; i < 512; i++) { char b[8]; int n = snprintf(b, sizeof b, "d%d", i); (void)ray_sym_domain_intern(d, b, (size_t)n); } + ray_err_t fe = ray_sym_domain_flush(d, false); + ray_sym_domain_release(d); + if (fe != RAY_OK) return NULL; + } + for (int p = 0; p < 3; p++) { + char dir[512]; snprintf(dir, sizeof dir, "%s/2024.01.0%d/t", root, p + 1); + char symp[512]; snprintf(symp, sizeof symp, "%s/.sym", root); + ray_t* a = gen_col(RAY_I64, rows[p], true, 0); + ray_t* s = gen_col(RAY_STR, rows[p], true, 0); + ray_t* b = gen_col(RAY_F64, rows[p], true, 0); + static const uint8_t pw[3] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32 }; + ray_t* y = gen_col(RAY_SYM, rows[p], true, pw[p]); /* a different width per partition */ + ray_t* t = ray_table_new(4); + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + t = ray_table_add_col(t, ray_sym_intern("y", 1), y); + t = ray_table_add_col(t, ray_sym_intern("b", 1), b); /* last: the ragged column */ + ray_release(a); ray_release(s); ray_release(b); ray_release(y); + ray_err_t e = (gen2_mask & (1 << p)) ? write_splayed_gen2(dir, t) : ray_splay_save(t, dir, symp); + ray_release(t); + if (e != RAY_OK) return NULL; + if (ragged && p == 2) { + char f[600]; snprintf(f, sizeof f, "%s/b", dir); remove(f); + ray_t* names = ray_vec_new(RAY_STR, 3); + names = ray_str_vec_append(names, "a", 1); names = ray_str_vec_append(names, "s", 1); + names = ray_str_vec_append(names, "y", 1); + snprintf(f, sizeof f, "%s/.d", dir); + e = ray_col_save(names, f); + ray_release(names); + if (e != RAY_OK) return NULL; + } + } + ray_t* t = ray_read_parted(root, "t"); + return (t && !RAY_IS_ERR(t)) ? t : NULL; +} + +/* Walk a parted source against its plain wrapper (segments; NULL = missing). */ +static test_result_t walk_parted(ray_col_src_t* s, ray_t* wrapper, int64_t req) { + ray_t** segs = (ray_t**)ray_data(wrapper); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + int64_t start = 0; + while (start < s->len) { + ray_t* err = ray_col_range(s, start, req, &sc, &r); + TEST_ASSERT_FMT(!err, "parted range @%lld: %s", (long long)start, err ? ray_err_code(err) : ""); + TEST_ASSERT_TRUE(r.n > 0); + int64_t acc = 0, k = 0; + while (k < wrapper->len && (!segs[k] || start >= acc + segs[k]->len)) { if (segs[k]) acc += segs[k]->len; k++; } + TEST_ASSERT_TRUE(k < wrapper->len); + TEST_ASSERT_FMT(start + r.n <= acc + segs[k]->len, "range @%lld n=%lld crosses segment %lld", (long long)start, (long long)r.n, (long long)k); + for (int64_t i = 0; i < r.n; i++) { + const char* bad = cmp_row(&r, i, segs[k], start - acc + i); + TEST_ASSERT_FMT(!bad, "parted row %lld: %s", (long long)(start + i), bad ? bad : ""); + } + start += r.n; + } + ray_col_scratch_free(&sc); + PASS(); +} + +static test_result_t parted_case(const char* root, int mask, bool ragged) { + ray_t* t = load_parted(root, mask, ragged); + TEST_ASSERT_TRUE(t != NULL); + static const char* cols[] = { "a", "s", "b", "y" }; + for (int c = 0; c < 4; c++) { + ray_enc_counters_reset(); + int64_t id = ray_sym_intern(cols[c], 1); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, id, &s)); + TEST_ASSERT_TRUE(s.obj != NULL); + TEST_ASSERT_EQ_I(s.len, 3000 + 1024 + 70000); /* ragged b too: its missing rows are nulls */ + TEST_ASSERT_EQ_I(s.type, c == 0 ? RAY_I64 : c == 1 ? RAY_STR : c == 2 ? RAY_F64 : RAY_SYM); + TEST_ASSERT_TRUE(s.may_null); + /* reading ranges decodes vectors only: nothing is materialized */ + ray_col_scratch_t sc; ray_col_scratch_init(&sc); ray_col_range_t r; + TEST_ASSERT_NULL(ray_col_range(&s, 0, 100, &sc, &r)); + TEST_ASSERT_NULL(ray_col_range(&s, s.len - 50, 100, &sc, &r)); + ray_col_scratch_free(&sc); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t* w = ray_table_col(t, id); /* the materialized reference */ + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w) && RAY_IS_PARTED(w->type)); + if (ragged && c == 2) { /* the load filled the missing segment */ + ray_t* g = ((ray_t**)ray_data(w))[2]; + TEST_ASSERT_TRUE(g && g->type == RAY_F64 && g->len == 70000 && (g->attrs & RAY_ATTR_HAS_NULLS)); + for (int64_t i = 0; i < g->len; i++) TEST_ASSERT_TRUE(ray_vec_is_null(g, i)); + } + if (c == 3 && (mask & 5) == 5) { /* generation 2 keeps each segment's width */ + ray_t** sg = (ray_t**)ray_data(w); + TEST_ASSERT_TRUE((sg[0]->attrs & RAY_SYM_W_MASK) != (sg[2]->attrs & RAY_SYM_W_MASK)); + } + static const int64_t reqs[] = { 1000, 1024, 5000, 1 << 20 }; + for (int q = 0; q < 4; q++) RUN(walk_parted(&s, w, reqs[q])); + /* the boundaries themselves: a range starting at the last row of a segment */ + int64_t bounds[] = { 2999, 3000, 3000 + 1023, 3000 + 1024 }; + for (int q = 0; q < 4 && bounds[q] < s.len; q++) { + ray_col_scratch_t sc2; ray_col_scratch_init(&sc2); + TEST_ASSERT_NULL(ray_col_range(&s, bounds[q], 5000, &sc2, &r)); + int64_t seg_end = bounds[q] < 3000 ? 3000 : bounds[q] < 4024 ? 4024 : s.len; + TEST_ASSERT_TRUE(bounds[q] + r.n <= seg_end); + if (bounds[q] == 2999 || bounds[q] == 4023) TEST_ASSERT_EQ_I(r.n, 1); + ray_col_scratch_free(&sc2); + } + ray_col_src_release(&s); + } + ray_release(t); + PASS(); +} + +static test_result_t test_range_parted_mixed(void) { + RUN(parted_case(ray_test_tmp(CR_TMP "/p5"), 0x5, false)); /* gen2, gen0, gen2 */ + RUN(parted_case(ray_test_tmp(CR_TMP "/p2"), 0x2, false)); /* gen0, gen2, gen0 */ + RUN(parted_case(ray_test_tmp(CR_TMP "/p0"), 0x0, false)); /* all gen0: plain parted wrapper */ + RUN(parted_case(ray_test_tmp(CR_TMP "/p7"), 0x7, false)); /* all gen2 */ + PASS(); +} + +/* A ragged partition's missing column reads as nulls over its rows (#724). + * A missing segment, which only a hand-built wrapper has, holds no rows, + * matching ray_parted_nrows (the executor refuses a table whose parted + * columns' row counts differ, so a scan never meets one). */ +static test_result_t test_range_parted_ragged(void) { + RUN(parted_case(ray_test_tmp(CR_TMP "/r5"), 0x5, true)); + RUN(parted_case(ray_test_tmp(CR_TMP "/r0"), 0x0, true)); + ray_t* t = load_parted(ray_test_tmp(CR_TMP "/rh"), 0x0, false); + TEST_ASSERT_TRUE(t != NULL); + ray_t* b = ray_table_col(t, ray_sym_intern("b", 1)); + TEST_ASSERT_TRUE(b && !RAY_IS_ERR(b) && RAY_IS_PARTED(b->type) && b->len == 3); + ray_t* w = ray_alloc(3 * sizeof(ray_t*)); + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w)); + w->type = b->type; w->len = 3; w->attrs = 0; memset(w->aux, 0, 16); + ray_t** ws = (ray_t**)ray_data(w); + for (int i = 0; i < 3; i++) { ws[i] = i == 1 ? NULL : ((ray_t**)ray_data(b))[i]; if (ws[i]) ray_retain(ws[i]); } + TEST_ASSERT_EQ_I(ray_parted_nrows(w), 3000 + 70000); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_col_src_bind(w, &s)); + TEST_ASSERT_EQ_I(s.len, 3000 + 70000); + RUN(walk_parted(&s, w, 5000)); + ray_col_src_release(&s); + ray_release(w); + ray_release(t); + PASS(); +} + +/* Bind refuses shapes range reads cannot serve. */ +static test_result_t test_bind_refuses_shapes(void) { + ray_col_src_t s; + ray_t fake; /* header only: bind rejects before any use */ + memset(&fake, 0, sizeof fake); + fake.type = RAY_MAPCOMMON; + ray_t* e = ray_col_src_bind(&fake, &s); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); TEST_ASSERT_STR_EQ(ray_err_code(e), "nyi"); ray_error_free(e); + TEST_ASSERT_TRUE(s.obj == NULL); + fake.type = RAY_ENCCOL; fake.attrs = RAY_ATTR_SLICE; + e = ray_col_src_bind(&fake, &s); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); TEST_ASSERT_STR_EQ(ray_err_code(e), "nyi"); ray_error_free(e); + fake.type = RAY_PARTED_BASE + RAY_I64; + e = ray_col_src_bind(&fake, &s); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); TEST_ASSERT_STR_EQ(ray_err_code(e), "nyi"); ray_error_free(e); + PASS(); +} + +static test_result_t test_table_col_src(void) { + ray_t* v = i32_nulls(2000); + ray_t* v2 = i32_nulls(2000); + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("x", 1), v); + ray_release(v); + TEST_ASSERT_EQ_I(ray_col_save_gen(v2, ray_test_tmp(CR_TMP "/e"), 2), RAY_OK); + ray_release(v2); + ray_t* c = ray_col_mmap(ray_test_tmp(CR_TMP "/e")); + t = ray_table_add_col(t, ray_sym_intern("y", 1), c); + ray_release(c); + ray_enc_counters_reset(); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("x", 1), &s)); + TEST_ASSERT_TRUE(s.obj != NULL && s.len == 2000); + ray_col_src_release(&s); + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("y", 1), &s)); + TEST_ASSERT_TRUE(s.obj != NULL && s.obj->type == RAY_ENCCOL && s.len == 2000); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); /* binding never decodes */ + ray_col_src_release(&s); + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("absent", 6), &s)); + TEST_ASSERT_TRUE(s.obj == NULL); + ray_release(t); + PASS(); +} + +static test_result_t test_range_parted_boundary(void) { + for (int p = 0; p < 2; p++) { + char dir[256]; snprintf(dir, sizeof dir, ray_test_tmp(CR_TMP "/pdb/2024.01.0%d/t"), p + 1); + ray_t* t = ray_table_new(1); + ray_t* a = ray_vec_new(RAY_I64, 3000); a->len = 3000; + for (int i = 0; i < 3000; i++) ((int64_t*)ray_data(a))[i] = p * 3000 + i; + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + ray_release(a); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, dir, NULL, p == 0 ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF), RAY_OK); + ray_release(t); + } + ray_t* t = ray_read_parted(ray_test_tmp(CR_TMP "/pdb"), "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("a", 1), &s)); + TEST_ASSERT_EQ_I(s.len, 6000); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + TEST_ASSERT_NULL(ray_col_range(&s, 2990, 100, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, 10); /* segment boundary */ + TEST_ASSERT_EQ_I(((const int64_t*)r.data)[9], 2999); + TEST_ASSERT_NULL(ray_col_range(&s, 3000, 100, &sc, &r)); + ray_col_meta_t m; ray_table_col_meta(t, ray_sym_intern("a", 1), &m); + ray_t* seg1 = ray_enccol_seg(m.enc, 1); /* the generation-0 segment */ + TEST_ASSERT_EQ_PTR(r.data, ray_data(seg1)); /* zero copy */ + TEST_ASSERT_EQ_I(r.n, 100); + ray_col_scratch_free(&sc); ray_col_src_release(&s); ray_release(t); + PASS(); +} + +const test_entry_t colrange_entries[] = { + { "colrange/gen0_zero_copy", test_range_gen0_zero_copy, cr_setup, cr_teardown }, + { "colrange/gen2_vector_clip_nulls", test_range_gen2_vector_clip_and_nulls, cr_setup, cr_teardown }, + { "colrange/two_str_views", test_range_two_str_views, cr_setup, cr_teardown }, + { "colrange/slice_and_long_strings", test_range_slice_and_long_strings, cr_setup, cr_teardown }, + { "colrange/bounds_and_scratch", test_range_bounds_and_scratch, cr_setup, cr_teardown }, + { "colrange/matches_materialized", test_range_matches_materialized, cr_setup, cr_teardown }, + { "colrange/parted_mixed", test_range_parted_mixed, cr_setup, cr_teardown }, + { "colrange/parted_ragged", test_range_parted_ragged, cr_setup, cr_teardown }, + { "colrange/bind_refuses_shapes", test_bind_refuses_shapes, cr_setup, cr_teardown }, + { "colrange/table_col_src", test_table_col_src, cr_setup, cr_teardown }, + { "colrange/parted_boundary", test_range_parted_boundary, cr_setup, cr_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_compile.c b/test/test_compile.c index 5d34a68d1..b9dd645ef 100644 --- a/test/test_compile.c +++ b/test/test_compile.c @@ -899,6 +899,29 @@ static test_result_t test_compile_float_literal(void) { PASS(); } +static test_result_t test_compile_signed_zero_constants(void) { + const char* const exprs[] = { + "(do (set f (fn [] (do 0.0 -0.0))) (f))", + "(do (set f (fn [] (do -0.0 0.0))) (f))", + }; + const uint64_t expected[] = { UINT64_C(0x8000000000000000), UINT64_C(0) }; + for (size_t i = 0; i < sizeof exprs / sizeof exprs[0]; i++) { + ray_t* r = ray_eval_str(exprs[i]); + if (!r || RAY_IS_ERR(r)) { + if (r) ray_error_free(r); + FAILF("eval error on signed-zero constant test"); + } + TEST_ASSERT(r->type == -RAY_F64, "expected f64"); + uint64_t bits; + memcpy(&bits, &r->f64, sizeof bits); + ray_release(r); + TEST_ASSERT_FMT(bits == expected[i], + "signed-zero bits: expected %016llx, got %016llx", + (unsigned long long)expected[i], (unsigned long long)bits); + } + PASS(); +} + /* ════════════════════════════════════════════════════════════════════ * 22. find_local hits existing local (returns slot >= 0) — let re-bind * ════════════════════════════════════════════════════════════════════ */ @@ -1086,6 +1109,7 @@ const test_entry_t compile_entries[] = { { "compile/multi_body_exprs", test_compile_multi_body_exprs, compile_setup, compile_teardown }, { "compile/bool_literal", test_compile_bool_literal, compile_setup, compile_teardown }, { "compile/float_literal", test_compile_float_literal, compile_setup, compile_teardown }, + { "compile/signed_zero_constants", test_compile_signed_zero_constants, compile_setup, compile_teardown }, { "compile/let_rebind", test_compile_let_rebind, compile_setup, compile_teardown }, { "compile/const_dedup", test_compile_const_dedup, compile_setup, compile_teardown }, { "compile/compile_reset", test_compile_ray_compile_reset, compile_setup, compile_teardown }, diff --git a/test/test_compress_save.c b/test/test_compress_save.c new file mode 100644 index 000000000..1e0513693 --- /dev/null +++ b/test/test_compress_save.c @@ -0,0 +1,4937 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + + +#define _POSIX_C_SOURCE 200809L +#include "test.h" +#include +#include "mem/heap.h" +#include "ops/ops.h" +#include "ops/idxop.h" +#include "ops/colbind.h" +#include "ops/fused_pred.h" +#include "ops/fused_topk.h" +#include "ops/internal.h" +#include "ops/rowsel.h" +#include "ops/agg_engine.h" +#include "ops/fused_group.h" +#include "lang/parse.h" +#include "table/sym.h" +#include "table/table.h" +#include "core/runtime.h" +#include "lang/eval.h" +#include "core/platform.h" +#include "store/col.h" +#include "store/colrange.h" +#include "table/domain.h" +#include "store/encfmt.h" +#include "store/enccol.h" +#include "store/splay.h" +#include "store/part.h" +#include "store/serde.h" +#include "store/stream.h" +#include "vec/str.h" +#include "ops/datalog.h" +#include "core/ipc.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#define CS_TMP "/tmp/rayforce_compress" + +static void cs_setup(void) { ray_heap_init(); (void)ray_sym_init(); (void)ray_test_rm_rf(ray_test_tmp(CS_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP)); } +static void cs_teardown(void) { ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(CS_TMP)); ray_sym_destroy(); ray_heap_destroy(); } + +static ray_t* i64_col(int64_t n, int64_t mul) { + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = i * mul; + return v; +} + +/* A loaded table whose column `a` is generation 2 and `b` generation 0. */ +static ray_t* mixed_table(void) { + char p[256]; + (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP "/mix")); + ray_t* a = i64_col(3000, 3); ray_t* b = i64_col(3000, 5); + snprintf(p, sizeof p, "%s/mix/a", ray_test_tmp(CS_TMP)); ray_col_save_gen(a, p, 2); + snprintf(p, sizeof p, "%s/mix/b", ray_test_tmp(CS_TMP)); ray_col_save_gen(b, p, 0); + ray_release(a); ray_release(b); + ray_t* names = ray_vec_new(RAY_STR, 2); + names = ray_str_vec_append(names, "a", 1); names = ray_str_vec_append(names, "b", 1); + snprintf(p, sizeof p, "%s/mix/.d", ray_test_tmp(CS_TMP)); ray_col_save(names, p); ray_release(names); + return ray_read_splayed(ray_test_tmp(CS_TMP "/mix"), NULL); +} + +static test_result_t test_meta_without_decode(void) { + ray_t* t = mixed_table(); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_enc_counters_reset(); + ray_col_meta_t m; + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("a", 1), &m)); + TEST_ASSERT_EQ_I(m.type, RAY_I64); + TEST_ASSERT_EQ_I(m.len, 3000); + TEST_ASSERT_TRUE(m.enc != NULL); + TEST_ASSERT_EQ_I(m.null_count, 0); + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("b", 1), &m)); + TEST_ASSERT_TRUE(m.enc == NULL); + TEST_ASSERT_EQ_I(m.null_count, -1); + TEST_ASSERT_FALSE(ray_table_col_meta(t, ray_sym_intern("zz", 2), &m)); + ray_t* ix = (ray_t*)1; + TEST_ASSERT_NULL(ray_table_col_index(t, ray_sym_intern("a", 1), &ix)); + TEST_ASSERT_NULL(ix); /* no index, no decode */ + TEST_ASSERT_FALSE(ray_table_col_has_nulls(t, ray_sym_intern("a", 1))); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t* a = ray_table_col(t, ray_sym_intern("a", 1)); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && a->type == RAY_I64); + TEST_ASSERT_EQ_PTR(ray_table_col_idx(t, 0), a); /* cached */ + TEST_ASSERT_TRUE(ray_table_get_col_enc(t, ray_sym_intern("a", 1)) != NULL); + TEST_ASSERT_NULL(ray_table_get_col_enc(t, ray_sym_intern("b", 1))); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + ray_release(t); + PASS(); +} + +/* Legacy getters: absent, non-table and success, each after a stale error + * in the slot, keep its message. */ +static test_result_t test_legacy_getters(void) { + ray_t* t = mixed_table(); + ray_t* stale; + stale = ray_error("domain", "stale"); ray_error_free(stale); + TEST_ASSERT_NULL(ray_table_get_col(t, ray_sym_intern("zz", 2))); + TEST_ASSERT_STR_EQ(ray_error_msg(), "stale"); + stale = ray_error("domain", "stale"); ray_error_free(stale); + ray_t* atom = ray_i64(3); + TEST_ASSERT_NULL(ray_table_get_col(atom, 0)); + TEST_ASSERT_STR_EQ(ray_error_msg(), "stale"); + ray_release(atom); + stale = ray_error("domain", "stale"); ray_error_free(stale); + TEST_ASSERT_NOT_NULL(ray_table_get_col(t, ray_sym_intern("a", 1))); + TEST_ASSERT_STR_EQ(ray_error_msg(), "stale"); + ray_release(t); + PASS(); +} + +typedef struct { ray_t* t; int64_t id; ray_t* got; } cs_thr_t; +static void cs_col_thread(void* raw) { + cs_thr_t* x = raw; + x->got = ray_table_col(x->t, x->id); + ray_heap_abandon(); +} + +static test_result_t test_concurrent_one_materialization(void) { + ray_t* t = mixed_table(); + ray_enc_counters_reset(); + cs_thr_t th[8]; ray_thread_t id[8]; + for (int i = 0; i < 8; i++) { th[i].t = t; th[i].id = ray_sym_intern("a", 1); th[i].got = NULL; + TEST_ASSERT_EQ_I(ray_thread_create(&id[i], cs_col_thread, &th[i]), RAY_OK); } + for (int i = 0; i < 8; i++) ray_thread_join(id[i]); + for (int i = 1; i < 8; i++) TEST_ASSERT_EQ_PTR(th[i].got, th[0].got); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + ray_release(t); + PASS(); +} + +typedef struct { ray_t* t; int64_t id; ray_t* ix; ray_t* err; } cs_ix_thr_t; +static void cs_index_thread(void* raw) { + cs_ix_thr_t* x = raw; + x->err = ray_table_col_index(x->t, x->id, &x->ix); + ray_heap_abandon(); +} + +/* Many threads asking one fresh UNIQUE column for its index: one + * materialization, one root for all. */ +static test_result_t test_concurrent_col_index(void) { + (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP "/ux")); + ray_t* a = i64_col(3000, 7); + ray_t* root = ray_index_new_root(RAY_IDX_NONE, RAY_I64, 3000); + ray_index_payload(root)->markers = RAY_MARK_UNIQUE; + ray_t* ua = ray_index_attach_persisted(&a, root); + TEST_ASSERT_TRUE(ua && !RAY_IS_ERR(ua)); a = ua; + TEST_ASSERT_EQ_I(ray_col_save_gen(a, ray_test_tmp(CS_TMP "/ux/a"), 2), RAY_OK); + ray_release(a); + ray_t* names = ray_vec_new(RAY_STR, 1); names = ray_str_vec_append(names, "a", 1); + ray_col_save(names, ray_test_tmp(CS_TMP "/ux/.d")); ray_release(names); + ray_t* t = ray_read_splayed(ray_test_tmp(CS_TMP "/ux"), NULL); + ray_enc_counters_reset(); + cs_ix_thr_t th[8]; ray_thread_t id[8]; + for (int i = 0; i < 8; i++) { th[i] = (cs_ix_thr_t){ t, ray_sym_intern("a", 1), NULL, NULL }; + TEST_ASSERT_EQ_I(ray_thread_create(&id[i], cs_index_thread, &th[i]), RAY_OK); } + for (int i = 0; i < 8; i++) ray_thread_join(id[i]); + for (int i = 0; i < 8; i++) { TEST_ASSERT_NULL(th[i].err); TEST_ASSERT_EQ_PTR(th[i].ix, th[0].ix); } + TEST_ASSERT_NOT_NULL(th[0].ix); + TEST_ASSERT_TRUE(ray_index_payload(th[0].ix)->markers & RAY_MARK_UNIQUE); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + ray_release(t); + PASS(); +} + +/* A transient failure through the legacy getter: NULL with the message in + * the slot, nothing leaked, the next call succeeds. */ +static test_result_t test_legacy_transient_no_leak(void) { + ray_t* t = mixed_table(); + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + for (int i = 0; i < 4; i++) { + ray_enccol_test_fail_alloc(1); + TEST_ASSERT_NULL(ray_table_get_col(t, ray_sym_intern("a", 1))); + ray_enccol_test_fail_alloc(0); + TEST_ASSERT_NOT_NULL(ray_error_msg()); + } + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + ray_error_clear(); + TEST_ASSERT_NOT_NULL(ray_table_get_col(t, ray_sym_intern("a", 1))); + TEST_ASSERT_NULL(ray_error_msg()); + ray_release(t); + PASS(); +} + +/* Serializing a table that holds an encoded column sends its values. */ +static test_result_t test_serde_encoded_table(void) { + ray_t* t = mixed_table(); + ray_t* w = ray_ser(t); + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w)); + ray_t* back = ray_de(w); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + ray_t* a = ray_table_col(back, ray_sym_intern("a", 1)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(a))[2999], 2999 * 3); + ray_release(back); ray_release(w); ray_release(t); + PASS(); +} + +static void rt_setup(void) { ray_runtime_create(0, NULL); (void)ray_test_rm_rf(ray_test_tmp(CS_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP)); } +static void rt_teardown(void) { ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(CS_TMP)); ray_runtime_destroy(__RUNTIME); } + +/* A table `name` (columns k, v: I64 3000 rows, k = i, v = 10 i) saved as + * generation 2, loaded and bound to the global `t`. Returns the retained + * loaded table. */ +static ray_t* bind_gen2_table(const char* name) { + char dir[256], p[300]; + snprintf(dir, sizeof dir, "%s/%s", ray_test_tmp(CS_TMP), name); + (void)ray_test_mkdir_p(dir); + ray_t* k = i64_col(3000, 1); ray_t* v = i64_col(3000, 10); + snprintf(p, sizeof p, "%s/k", dir); if (ray_col_save_gen(k, p, 2) != RAY_OK) return NULL; + snprintf(p, sizeof p, "%s/v", dir); if (ray_col_save_gen(v, p, 2) != RAY_OK) return NULL; + ray_release(k); ray_release(v); + ray_t* names = ray_vec_new(RAY_STR, 2); + names = ray_str_vec_append(names, "k", 1); names = ray_str_vec_append(names, "v", 1); + snprintf(p, sizeof p, "%s/.d", dir); + ray_err_t de = ray_col_save(names, p); ray_release(names); + if (de != RAY_OK) return NULL; + ray_t* t = ray_read_splayed(dir, NULL); + if (!t || RAY_IS_ERR(t)) return NULL; + ray_env_set(ray_sym_intern("t", 1), t); + return t; +} + +static int64_t cell(ray_t* tbl, const char* col, int64_t row) { + ray_t* c = ray_table_col(tbl, ray_sym_intern(col, (int64_t)strlen(col))); + return c && !RAY_IS_ERR(c) ? ((int64_t*)ray_data(c))[row] : INT64_MIN; +} + +/* The in-place insert, upsert, update and delete arms write a table's slots + * as plain vectors: a table loaded with encoded columns must take the copying + * arms. Each verb gets its own freshly loaded table; the retained original + * must keep its values. */ +static test_result_t dml_case(const char* name, const char* src, int64_t nrows_after, + const char* col, int64_t row, int64_t want, bool keep) { + ray_t* orig = bind_gen2_table(name); + TEST_ASSERT_TRUE(orig != NULL); + /* keep: a second reference forces the copying arms; without it the + * binding is the only owner and the in-place gates are what protect the + * encoded slots. */ + if (!keep) { ray_release(orig); orig = NULL; } + TEST_ASSERT_TRUE(!orig || ray_table_get_col_enc(orig, ray_sym_intern("k", 1)) != NULL); + ray_t* r = ray_eval_str(src); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(r); + ray_t* now = ray_env_get(ray_sym_intern("t", 1)); + TEST_ASSERT_EQ_I(ray_table_nrows(now), nrows_after); + TEST_ASSERT_EQ_I(cell(now, col, row), want); + if (keep) { + TEST_ASSERT_EQ_I(ray_table_nrows(orig), 3000); /* the retained original is intact */ + for (int64_t i = 0; i < 3000; i += 499) { + TEST_ASSERT_EQ_I(cell(orig, "k", i), i); + TEST_ASSERT_EQ_I(cell(orig, "v", i), i * 10); + } + ray_release(orig); + } + PASS(); +} +#define DML_TESTS(NAME, SRC, NROWS, COL, ROW, WANT) \ + static test_result_t test_dml_##NAME##_copy(void) { return dml_case(#NAME "c", SRC, NROWS, COL, ROW, WANT, true); } \ + static test_result_t test_dml_##NAME##_inplace(void) { return dml_case(#NAME "i", SRC, NROWS, COL, ROW, WANT, false); } +DML_TESTS(upsert, "(upsert 't 'k (list 5 -1))", 3000, "v", 5, -1) +DML_TESTS(insert, "(insert 't (list 9999 7))", 3001, "k", 3000, 9999) +DML_TESTS(update, "(update {v: 1 from: 't where: (== k 7)})", 3000, "v", 7, 1) +DML_TESTS(delete, "(delete {from: 't where: (== k 7)})", 2999, "k", 7, 8) + +static const char* ev_code(const char* src); + +/* Value operations on a table whose slots are encoded copy the column: the + * cached materialization and other tables sharing the encoded object keep + * the old values (spec "Table core: Mutation"). */ +static test_result_t test_value_ops_copy_encoded(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 'v] (list [1 2 3 4] [10 20 30 40])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/vo\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set a (.db.splayed.get \"" CS_TMP "/vo\"))")), ""); + TEST_ASSERT_STR_EQ(ev_code("(set b a)"), ""); + ray_enc_counters_reset(); + TEST_ASSERT_STR_EQ(ev_code("(set a (update {v: (* v 2) from: a}))"), ""); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); /* (* v 2) range-reads v */ + ray_t* r = ray_eval_str("(sum (at b 'v))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 100); + ray_release(r); + r = ray_eval_str("(sum (at a 'v))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 200); + ray_release(r); + TEST_ASSERT_STR_EQ(ev_code("(set a (insert a (list 5 50)))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set a (delete {from: a where: (== k 1)}))"), ""); + r = ray_eval_str("(count a)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 4); + ray_release(r); + r = ray_eval_str("(sum (at b 'v))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 100); + ray_release(r); + PASS(); +} + +static int64_t ev_i64(const char* src) { + ray_t* r = ray_eval_str(src); + int64_t v = (r && !RAY_IS_ERR(r) && r->type == -RAY_I64) ? r->i64 : INT64_MIN; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + return v; +} + +/* Engine-built tables (a select's output) may carry the source's encoded + * slots: update, insert, upsert and delete on such a result work, by name and + * by value, and the generation-2 source keeps its values. */ +static test_result_t test_dml_on_select_result(void) { + ray_t* g = bind_gen2_table("sr"); + TEST_ASSERT_TRUE(g != NULL); + ray_release(g); + static const char* const steps[] = { + "(set s (select {from: t}))", + "(set s (update {v: (* v 2) from: s where: (< k 10)}))", + "(set s (insert s (list 3000 1)))", + "(set s (upsert s 'k (list 5 -1)))", + "(set s (delete {from: s where: (== k 7)}))", + "(set u (select {k: k v: v from: t}))", + "(update {v: 0 from: 'u where: (== k 1)})", + "(insert 'u (list 3000 1))", + "(upsert 'u 'k (list 2 -2))", + "(delete {from: 'u where: (== k 3)})", + }; + for (size_t i = 0; i < sizeof steps / sizeof *steps; i++) { + const char* code = ev_code(steps[i]); + TEST_ASSERT_FMT(strcmp(code, "") == 0, "%s: %s", steps[i], code); + } + TEST_ASSERT_EQ_I(ev_i64("(count s)"), 3000); + TEST_ASSERT_EQ_I(ev_i64("(at (at s 'v) 4)"), 80); + TEST_ASSERT_EQ_I(ev_i64("(at (at s 'v) 5)"), -1); + TEST_ASSERT_EQ_I(ev_i64("(at (at s 'k) 7)"), 8); + TEST_ASSERT_EQ_I(ev_i64("(at (at s 'v) 2999)"), 1); + TEST_ASSERT_EQ_I(ev_i64("(count u)"), 3000); + TEST_ASSERT_EQ_I(ev_i64("(at (at u 'v) 1)"), 0); + TEST_ASSERT_EQ_I(ev_i64("(at (at u 'v) 2)"), -2); + TEST_ASSERT_EQ_I(ev_i64("(at (at u 'k) 3)"), 4); + TEST_ASSERT_EQ_I(ev_i64("(sum (at t 'v))"), 10 * (2999LL * 3000 / 2)); + TEST_ASSERT_EQ_I(ev_i64("(count t)"), 3000); + PASS(); +} + +/* The generation-2 column `a` beside the generation-0 column `b`, bound to + * `t`. */ +static ray_t* bind_mixed_table(void) { + ray_t* t = mixed_table(); + if (t && !RAY_IS_ERR(t)) ray_env_set(ray_sym_intern("t", 1), t); + return t; +} + +/* An update that never reads the encoded column does not decode it: the + * verbs read encoded columns lazily, so it passes `a` on encoded. */ +static test_result_t test_update_passes_encoded(void) { + ray_t* t = bind_mixed_table(); + TEST_ASSERT_TRUE(t != NULL && !RAY_IS_ERR(t)); + static const char* const lazy[] = { "(update {b: 1 from: t where: (== b 5)})", "(update {b: 1 from: t})" }; + for (size_t i = 0; i < 2; i++) { + ray_enc_counters_reset(); + ray_t* ok = ray_eval_str(lazy[i]); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_FMT(c.materialized == 0, "%s: decoded a", lazy[i]); + TEST_ASSERT_FMT(ok && !RAY_IS_ERR(ok) && ok->type == RAY_TABLE, "%s", lazy[i]); + TEST_ASSERT_TRUE(ray_table_get_col_enc(ok, ray_sym_intern("a", 1)) != NULL); + ray_release(ok); + } + ray_release(t); + PASS(); +} + +/* A generation-0 table and the same table loaded from generation 2 serialize + * to identical bytes. */ +static test_result_t test_serde_byte_identity(void) { + ray_t* ref = ray_table_new(2); + ray_t* a = i64_col(3000, 3); + ray_t* f = ray_vec_new(RAY_F64, 3000); f->len = 3000; + for (int i = 0; i < 3000; i++) ((double*)ray_data(f))[i] = i * 0.5; + ref = ray_table_add_col(ref, ray_sym_intern("a", 1), a); + ref = ray_table_add_col(ref, ray_sym_intern("f", 1), f); + ray_release(a); ray_release(f); + TEST_ASSERT_EQ_I(ray_splay_save(ref, ray_test_tmp(CS_TMP "/g0"), NULL), RAY_OK); + (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP "/g2")); + ray_t* names = ray_vec_new(RAY_STR, 2); + for (int64_t c = 0; c < 2; c++) { + char p[300]; ray_t* nm = ray_sym_str(ray_table_col_name(ref, c)); + snprintf(p, sizeof p, "%s/g2/%.*s", ray_test_tmp(CS_TMP), (int)ray_str_len(nm), ray_str_ptr(nm)); + TEST_ASSERT_EQ_I(ray_col_save_gen(ray_table_get_col_idx(ref, c), p, 2), RAY_OK); + names = ray_str_vec_append(names, ray_str_ptr(nm), ray_str_len(nm)); + } + ray_col_save(names, ray_test_tmp(CS_TMP "/g2/.d")); ray_release(names); + ray_t* t0 = ray_read_splayed(ray_test_tmp(CS_TMP "/g0"), NULL); + ray_t* t2 = ray_read_splayed(ray_test_tmp(CS_TMP "/g2"), NULL); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + TEST_ASSERT_TRUE(ray_table_get_col_enc_idx(t2, 0) != NULL); + int64_t n0 = ray_serde_size(t0), n2 = ray_serde_size(t2); + TEST_ASSERT_TRUE(n0 > 0); + TEST_ASSERT_EQ_I(n0, n2); + ray_t* w0 = ray_ser(t0); ray_t* w2 = ray_ser(t2); + TEST_ASSERT_TRUE(w0 && !RAY_IS_ERR(w0) && w2 && !RAY_IS_ERR(w2)); + TEST_ASSERT_EQ_I(w0->len, w2->len); + TEST_ASSERT_TRUE(memcmp(ray_data(w0), ray_data(w2), (size_t)w0->len) == 0); + ray_release(w0); ray_release(w2); ray_release(t0); ray_release(t2); ray_release(ref); + PASS(); +} + +/* A success must not erase a pending message. */ +static test_result_t test_getter_keeps_pending_message(void) { + ray_t* t = ray_table_new(1); + ray_t* a = i64_col(10, 1); + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + ray_release(a); + ray_error_free(ray_error("domain", "x")); + TEST_ASSERT_NOT_NULL(ray_table_get_col(t, ray_sym_intern("a", 1))); + TEST_ASSERT_TRUE(ray_error_msg() && strcmp(ray_error_msg(), "x") == 0); + TEST_ASSERT_NOT_NULL(ray_table_get_col_idx(t, 0)); + TEST_ASSERT_TRUE(ray_error_msg() && strcmp(ray_error_msg(), "x") == 0); + TEST_ASSERT_NULL(ray_table_get_col(t, ray_sym_intern("zz", 2))); /* absent: not a failure */ + TEST_ASSERT_TRUE(ray_error_msg() && strcmp(ray_error_msg(), "x") == 0); + ray_release(t); + PASS(); +} + +/* .mem.objsize counts the decoded cache of an encoded column. */ +static test_result_t test_objsize_counts_cache(void) { + ray_t* t = bind_gen2_table("os"); + TEST_ASSERT_TRUE(t != NULL); + ray_t* before = ray_eval_str("(.mem.objsize t)"); + TEST_ASSERT_TRUE(before && !RAY_IS_ERR(before)); + int64_t b = before->i64; ray_release(before); + TEST_ASSERT_TRUE(ray_table_col(t, ray_sym_intern("k", 1)) != NULL); + ray_t* after = ray_eval_str("(.mem.objsize t)"); + TEST_ASSERT_TRUE(after && !RAY_IS_ERR(after)); + TEST_ASSERT_TRUE(after->i64 >= b + 3000 * 8); + ray_release(after); ray_release(t); + PASS(); +} + +/* A generation-0 parted column's null flag lives on its segments. */ +static test_result_t test_has_nulls_parted(void) { + ray_t* s0 = i64_col(5, 1); ray_t* s1 = i64_col(5, 1); + s1->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* w = ray_alloc(2 * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + RAY_I64; w->len = 2; w->attrs = 0; + memset(w->aux, 0, 16); + ((ray_t**)ray_data(w))[0] = s0; ((ray_t**)ray_data(w))[1] = s1; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("p", 1), w); + ray_release(w); + TEST_ASSERT_TRUE(ray_table_col_has_nulls(t, ray_sym_intern("p", 1))); + s1->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + TEST_ASSERT_FALSE(ray_table_col_has_nulls(t, ray_sym_intern("p", 1))); + ray_release(t); + PASS(); +} + +/* .db.parted.get loads partitions of either generation, mixed, and + * decodes a generation-2 segment only on materialization. */ +static void write_part(const char* day, int gen) { + char dir[256], p[300]; + snprintf(dir, sizeof dir, "%s/pdb/%s/tb", ray_test_tmp(CS_TMP), day); + (void)ray_test_mkdir_p(dir); + ray_t* a = i64_col(3000, 3); + snprintf(p, sizeof p, "%s/a", dir); ray_col_save_gen(a, p, gen); + ray_release(a); + ray_t* names = ray_vec_new(RAY_STR, 1); names = ray_str_vec_append(names, "a", 1); + snprintf(p, sizeof p, "%s/.d", dir); ray_col_save(names, p); ray_release(names); +} +static test_result_t test_parted_gen2_loads(void) { + write_part("2024.01.01", 0); write_part("2024.01.02", 0); + ray_t* ok = ray_read_parted(ray_test_tmp(CS_TMP "/pdb"), "tb"); + TEST_ASSERT_TRUE(ok && !RAY_IS_ERR(ok)); + TEST_ASSERT_EQ_I(ray_table_ncols(ok), 2); + ray_release(ok); + ray_t* a = NULL; + for (int pass = 0; pass < 2; pass++) { + if (pass == 0) { write_part("2024.01.01", 2); write_part("2024.01.02", 0); } + else { write_part("2024.01.01", 0); write_part("2024.01.02", 2); } + ray_t* t = ray_read_parted(ray_test_tmp(CS_TMP "/pdb"), "tb"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_ncols(t), 2); + a = ray_table_col(t, ray_sym_intern("a", 1)); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + TEST_ASSERT_EQ_I(a->type, RAY_PARTED_BASE + RAY_I64); + TEST_ASSERT_EQ_I(ray_parted_nrows(a), 6000); + ray_t** sg = (ray_t**)ray_data(a); + for (int i = 0; i < 2; i++) { + TEST_ASSERT_TRUE(sg[i] && sg[i]->type == RAY_I64 && sg[i]->len == 3000); + for (int64_t r = 0; r < 3000; r++) + TEST_ASSERT_EQ_I(((int64_t*)ray_data(sg[i]))[r], r * 3); + } + ray_release(t); + } + PASS(); +} + +static uint8_t file_gen(const char* path) { + uint8_t h[32] = {0}; + FILE* f = fopen(path, "rb"); + if (!f) return 255; + size_t n = fread(h, 1, 32, f); fclose(f); + if (n != 32) return 255; + int g = ray_col_gen_of(h); + return g < 0 ? 254 : (uint8_t)g; +} + +static uint8_t* slurp(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); if (!f) return NULL; + fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); + uint8_t* b = malloc((size_t)sz + 1); *n = fread(b, 1, (size_t)sz, f); fclose(f); + return b; +} + +static ray_err_t save_ctx(ray_t* col, const char* path, uint8_t gen, struct ray_sym_domain_s* dom) { + ray_col_write_t w; memset(&w, 0, sizeof w); + ray_t* e = ray_col_src_bind(col, &w.src); + if (e) { ray_error_free(e); return RAY_ERR_TYPE; } + w.name = "c"; w.gen = gen; w.target_dom = dom; w.durable = false; + ray_err_t r = ray_col_save_ctx(&w, path); + ray_col_src_release(&w.src); + return r; +} + +static test_result_t test_matrix_flat(void) { + ray_t* v = i64_col(140000, 7); + /* plain -> 0 is today's writer, byte for byte */ + TEST_ASSERT_EQ_I(save_ctx(v, ray_test_tmp(CS_TMP "/p0"), 0, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, ray_test_tmp(CS_TMP "/ref0")), RAY_OK); + size_t na, nb; uint8_t* a = slurp(ray_test_tmp(CS_TMP "/p0"), &na); uint8_t* b = slurp(ray_test_tmp(CS_TMP "/ref0"), &nb); + TEST_ASSERT_TRUE(na == nb && memcmp(a, b, na) == 0); free(a); free(b); + /* plain -> 2 */ + TEST_ASSERT_EQ_I(save_ctx(v, ray_test_tmp(CS_TMP "/p2"), 2, NULL), RAY_OK); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/p2")), 2); + /* encoded -> 2: range reads, no materialization, identical bytes */ + ray_t* enc = ray_col_mmap(ray_test_tmp(CS_TMP "/p2")); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/e2"), 2, NULL), RAY_OK); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + a = slurp(ray_test_tmp(CS_TMP "/p2"), &na); b = slurp(ray_test_tmp(CS_TMP "/e2"), &nb); + TEST_ASSERT_TRUE(na == nb && memcmp(a, b, na) == 0); free(a); free(b); + /* encoded -> 0: materializes once, then today's writer */ + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/e0"), 0, NULL), RAY_OK); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/e0")), 0); + a = slurp(ray_test_tmp(CS_TMP "/e0"), &na); b = slurp(ray_test_tmp(CS_TMP "/ref0"), &nb); + TEST_ASSERT_TRUE(na == nb && memcmp(a, b, na) == 0); free(a); free(b); + ray_release(enc); ray_release(v); + PASS(); +} + +/* A SYM column over domain A (insertion order z, a, m) re-encoded into a + * domain B with another order and a wider width class. */ +static test_result_t test_matrix_sym_remap(void) { + struct ray_sym_domain_s* A = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/A.sym")); + struct ray_sym_domain_s* B = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/B.sym")); + TEST_ASSERT_TRUE(A && B); + ray_sym_domain_intern(A, "", 0); ray_sym_domain_intern(B, "", 0); + static const char* w[3] = { "z", "a", "m" }; + for (int i = 0; i < 3; i++) ray_sym_domain_intern(A, w[i], 1); + for (int i = 0; i < 300; i++) { char b[16]; int n = snprintf(b, sizeof b, "pad%d", i); ray_sym_domain_intern(B, b, (size_t)n); } + for (int i = 2; i >= 0; i--) ray_sym_domain_intern(B, w[i], 1); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(A, false), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(B, false), RAY_OK); + ray_t* v = ray_sym_vec_new(RAY_SYM_W8, 5000); v->len = 5000; + for (int64_t i = 0; i < 5000; i++) ray_write_sym(ray_data(v), i, (uint64_t)(i % 4), RAY_SYM, RAY_SYM_W8); + v->sym_domain = A; ray_sym_domain_retain(A); + v->attrs |= RAY_ATTR_HAS_NULLS; + /* plain -> 2 over A, then encoded -> 2 into B, then encoded -> 0 into B */ + TEST_ASSERT_EQ_I(save_ctx(v, ray_test_tmp(CS_TMP "/sa"), 2, A), RAY_OK); + ray_t* enc = ray_col_mmap_splayed_dom(ray_test_tmp(CS_TMP "/sa"), A); + TEST_ASSERT_TRUE(enc && !RAY_IS_ERR(enc)); + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/sb2"), 2, B), RAY_OK); + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/sb0"), 0, B), RAY_OK); + const char* outs[2] = { ray_test_tmp(CS_TMP "/sb2"), ray_test_tmp(CS_TMP "/sb0") }; + for (int o = 0; o < 2; o++) { + ray_t* r = ray_col_load_dom(outs[o], B); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "reload %s", outs[o]); + TEST_ASSERT_EQ_I(r->attrs & RAY_SYM_W_MASK, RAY_SYM_W16); + for (int64_t i = 0; i < 5000; i++) { + ray_t* s0 = ray_sym_vec_cell(v, i); ray_t* s1 = ray_sym_vec_cell(r, i); + TEST_ASSERT_TRUE(ray_str_len(s0) == ray_str_len(s1) && + memcmp(ray_str_ptr(s0), ray_str_ptr(s1), ray_str_len(s0)) == 0); + } + TEST_ASSERT_TRUE(r->attrs & RAY_ATTR_HAS_NULLS); + ray_release(r); + } + ray_release(enc); ray_release(v); + ray_sym_domain_release(A); ray_sym_domain_release(B); + PASS(); +} + +/* Equal long strings at distinct pool offsets with differing cached hashes + * are one value (storage equality ignores pool_off and hash32): CONST, and + * the round trip gives both rows the bytes. */ +static test_result_t test_str_const_distinct_offsets(void) { + static const char txt[] = "a twenty-one-byte str"; /* 21 bytes */ + ray_t* v = ray_vec_new(RAY_STR, 2); v->len = 2; + ray_t* pool = ray_alloc(42); pool->type = RAY_U8; pool->len = 42; + memcpy(ray_data(pool), txt, 21); memcpy((char*)ray_data(pool) + 21, txt, 21); + v->str_pool = pool; + ray_str_t* d = ray_data(v); + for (int i = 0; i < 2; i++) { + memset(&d[i], 0, sizeof d[i]); + d[i].len = 21; memcpy(d[i].prefix, txt, 4); + d[i].pool_off = (uint32_t)(21 * i); d[i].hash32 = i ? 9u : 5u; + } + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/sc"), 2), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(CS_TMP "/sc")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enc_desc_t d0; memcpy(&d0, ray_enccol_of(c)->base + 160, 48); + TEST_ASSERT_EQ_I(d0.encoding, RAY_ENC_CONST); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + for (int i = 0; i < 2; i++) { + size_t n; const char* p = ray_str_vec_get(m, i, &n); + TEST_ASSERT_TRUE(n == 21 && memcmp(p, txt, 21) == 0); + } + TEST_ASSERT_EQ_I(m->str_pool->len, 42); /* once per occurrence */ + ray_release(c); ray_release(v); + PASS(); +} + +/* Failure injection: the range writer's buffers (at least one injection is + * asserted to fire), the encoded source's own allocations and a mid-write I/O + * failure leave no file, no + * staging file and no leaked bytes. */ +static test_result_t test_matrix_failure_inject(void) { + ray_t* v = ray_vec_new(RAY_STR, 70000); v->len = 70000; + ray_t* pool = ray_alloc(70000 * 24); pool->type = RAY_U8; pool->len = 70000 * 24; + ray_str_t* d = ray_data(v); + for (int64_t i = 0; i < 70000; i++) { + memset(&d[i], 0, sizeof d[i]); + d[i].len = 24; d[i].pool_off = (uint32_t)(24 * i); + for (int k = 0; k < 24; k++) ((char*)ray_data(pool))[24 * i + k] = (char)('a' + (i * 7 + k * 13) % 26); + memcpy(d[i].prefix, (char*)ray_data(pool) + 24 * i, 4); + } + v->str_pool = pool; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/s"), 2), RAY_OK); + ray_release(v); + ray_t* enc = ray_col_mmap(ray_test_tmp(CS_TMP "/s")); + TEST_ASSERT_TRUE(enc && !RAY_IS_ERR(enc)); + /* P6: the 26 distinct strings select STR_DICT, whose parsed + * dictionary is a once-state the source keeps after its first read (a + * cache, not a leak): validated before the baseline, so each injection + * counts only what the save owns. The decode-side bound below grows by + * Task 4's gated allocations (the dictionary offsets) within its 16. */ + const ray_enc_sdict_t* sd = NULL; + ray_t* sde = ray_enccol_strdict(ray_enccol_of(enc), &sd); + TEST_ASSERT_NULL(sde); + TEST_ASSERT_NOT_NULL(sd); + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + bool done = false; + int injected = 0; + for (int nth = 1; nth <= 8 && !done; nth++) { + ray_col_test_fail_alloc(nth); + ray_err_t r = save_ctx(enc, ray_test_tmp(CS_TMP "/d"), 2, NULL); + ray_col_test_fail_alloc(0); + if (r == RAY_OK) { done = true; break; } + injected++; + TEST_ASSERT_EQ_I(r, RAY_ERR_OOM); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/d")), 255); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/d.tmp")), 255); + ray_mem_stats(&m1); + TEST_ASSERT_FMT(m1.bytes_allocated == m0.bytes_allocated, "nth %d leaked", nth); + } + TEST_ASSERT_TRUE(done); + TEST_ASSERT_TRUE(injected >= 1); /* the writer's buffers were really failed */ + { /* encoded -> 2 keeps a STR column byte for byte */ + size_t na, nb; uint8_t* a = slurp(ray_test_tmp(CS_TMP "/s"), &na); uint8_t* b = slurp(ray_test_tmp(CS_TMP "/d"), &nb); + TEST_ASSERT_TRUE(a && b && na == nb && memcmp(a, b, na) == 0); free(a); free(b); + } + (void)remove(ray_test_tmp(CS_TMP "/d")); + /* decode-side allocation failures, encoded -> 2 and encoded -> 0 */ + for (int g = 0; g <= 2; g += 2) { + int ok_at = 0; + for (int nth = 1; nth <= 16; nth++) { + ray_enccol_test_fail_alloc(nth); + ray_err_t r = save_ctx(enc, ray_test_tmp(CS_TMP "/g"), (uint8_t)g, NULL); + ray_enccol_test_fail_alloc(0); + if (r == RAY_OK) { (void)remove(ray_test_tmp(CS_TMP "/g")); ok_at = nth; break; } + TEST_ASSERT_EQ_I(r, RAY_ERR_OOM); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/g")), 255); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/g.tmp")), 255); + ray_mem_stats(&m1); + TEST_ASSERT_TRUE(m1.bytes_allocated == m0.bytes_allocated); + } + TEST_ASSERT_FMT(ok_at > 0, "encoded -> %d: no success within the bound", g); + /* encoded -> 0 decodes, so its loop must really inject (7 points at + * HEAD: materialize, chunk_pool, pool, dict_pool_off, chunk results, + * DICT codes, DICT root); encoded -> 2 is a passenger copy that + * decodes nothing (succeeds at nth 1, recorded in Task 4b) */ + if (g == 0) TEST_ASSERT_FMT(ok_at > 1, "encoded -> 0: no injection fired (ok at nth %d)", ok_at); + } + (void)remove(ray_test_tmp(CS_TMP "/g")); + ray_mem_stats(&m0); /* the successful encoded -> 0 cached its materialization */ + /* staging path unusable: the open fails, nothing appears */ + TEST_ASSERT_EQ_I(mkdir(ray_test_tmp(CS_TMP "/e.tmp"), 0700), 0); + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/e"), 2, NULL), RAY_ERR_IO); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/e")), 255); + (void)rmdir(ray_test_tmp(CS_TMP "/e.tmp")); + /* I/O failure while writing: file size limit */ + struct rlimit old, lim; + if (getrlimit(RLIMIT_FSIZE, &old) == 0) { + /* half the source file: the write fails part way (P6: STR_DICT + * makes this file a few KiB, under the 64 KiB the RAW file had) */ + size_t sn = 0; uint8_t* sb = slurp(ray_test_tmp(CS_TMP "/s"), &sn); free(sb); + TEST_ASSERT_TRUE(sn > 4096); + lim = old; lim.rlim_cur = (rlim_t)(sn / 2); + void (*oldsig)(int) = signal(SIGXFSZ, SIG_IGN); + if (setrlimit(RLIMIT_FSIZE, &lim) == 0) { + ray_err_t r = save_ctx(enc, ray_test_tmp(CS_TMP "/f"), 2, NULL); + setrlimit(RLIMIT_FSIZE, &old); + TEST_ASSERT_EQ_I(r, RAY_ERR_IO); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/f")), 255); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/f.tmp")), 255); + } + signal(SIGXFSZ, oldsig); + } + ray_mem_stats(&m1); + TEST_ASSERT_TRUE(m1.bytes_allocated == m0.bytes_allocated); + ray_release(enc); + PASS(); +} + +static ray_t* sym_vec_over(struct ray_sym_domain_s* d, const int64_t* ids, int64_t n) { + ray_t* v = ray_sym_vec_new(RAY_SYM_W8, n); v->len = n; + for (int64_t i = 0; i < n; i++) ray_write_sym(ray_data(v), i, (uint64_t)ids[i], RAY_SYM, RAY_SYM_W8); + v->sym_domain = d; ray_sym_domain_retain(d); + return v; +} + +static test_result_t test_write_sym_domains(void) { + struct ray_sym_domain_s* A = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/A.sym")); + struct ray_sym_domain_s* C = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/C.sym")); + TEST_ASSERT_TRUE(A && C); + static const char* w[4] = { "", "q", "r", "s" }; + for (int i = 0; i < 4; i++) ray_sym_domain_intern(A, w[i], strlen(w[i])); + for (int i = 0; i < 3; i++) ray_sym_domain_intern(C, w[i], strlen(w[i])); /* no "s" */ + TEST_ASSERT_EQ_I(ray_sym_domain_flush(A, false), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(C, false), RAY_OK); + + /* an id past the target's count is corrupt in both generations, nothing left behind */ + int64_t bad[3] = { 1, 2, 9 }; + ray_t* vb = sym_vec_over(A, bad, 3); + for (int g = 0; g <= 2; g += 2) { + TEST_ASSERT_EQ_I(save_ctx(vb, ray_test_tmp(CS_TMP "/bad"), (uint8_t)g, A), RAY_ERR_CORRUPT); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/bad")), 255); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/bad.tmp")), 255); + } + ray_release(vb); + + /* absent from the target domain: corrupt, encoded -> 0 leaves no staging file */ + int64_t ok[6] = { 1, 1, 2, 3, 3, 3 }; /* sorted */ + ray_t* v = sym_vec_over(A, ok, 6); + v->attrs |= RAY_ATTR_SORTED; + TEST_ASSERT_EQ_I(save_ctx(v, ray_test_tmp(CS_TMP "/pa"), 2, A), RAY_OK); + ray_t* enc = ray_col_mmap_splayed_dom(ray_test_tmp(CS_TMP "/pa"), A); + TEST_ASSERT_TRUE(enc && !RAY_IS_ERR(enc)); + for (int g = 0; g <= 2; g += 2) { + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/miss"), (uint8_t)g, C), RAY_ERR_CORRUPT); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/miss")), 255); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/miss.tmp")), 255); + } + /* same domain: byte identical to plain -> 2, SORTED kept, rc = count */ + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/same"), 2, A), RAY_OK); + size_t na, nb; uint8_t* a = slurp(ray_test_tmp(CS_TMP "/pa"), &na); uint8_t* b = slurp(ray_test_tmp(CS_TMP "/same"), &nb); + TEST_ASSERT_TRUE(a && b && na == nb && memcmp(a, b, na) == 0); + uint32_t rc; memcpy(&rc, b + 20, 4); + TEST_ASSERT_EQ_I(rc, 4); free(a); free(b); + ray_t* r = ray_col_load_dom(ray_test_tmp(CS_TMP "/same"), A); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && (r->attrs & RAY_ATTR_SORTED)); + ray_release(r); + /* another domain that has every symbol: SORTED dropped */ + struct ray_sym_domain_s* D = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/D.sym")); + for (int i = 3; i >= 0; i--) ray_sym_domain_intern(D, w[i], strlen(w[i])); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(D, false), RAY_OK); + TEST_ASSERT_EQ_I(save_ctx(enc, ray_test_tmp(CS_TMP "/other"), 2, D), RAY_OK); + r = ray_col_load_dom(ray_test_tmp(CS_TMP "/other"), D); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && !(r->attrs & RAY_ATTR_SORTED)); + ray_release(r); + /* bare file from a FILE-domain source: process-local ids through the LUT */ + for (int g = 0; g <= 2; g += 2) { + const char* o = g ? ray_test_tmp(CS_TMP "/bare2") : ray_test_tmp(CS_TMP "/bare0"); + TEST_ASSERT_EQ_I(save_ctx(enc, o, (uint8_t)g, NULL), RAY_OK); + r = ray_col_load(o); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + for (int64_t i = 0; i < 6; i++) { + ray_t* s0 = ray_sym_vec_cell(v, i); ray_t* s1 = ray_sym_vec_cell(r, i); + TEST_ASSERT_TRUE(ray_str_len(s0) == ray_str_len(s1) && + memcmp(ray_str_ptr(s0), ray_str_ptr(s1), ray_str_len(s0)) == 0); + } + ray_release(r); + } + /* P4: DROP is a decision of generation 2 (no index recorded); generation + * 0 writes its index as today and takes KEEP only */ + ray_col_write_t cw; memset(&cw, 0, sizeof cw); + TEST_ASSERT_TRUE(ray_col_src_bind(v, &cw.src) == NULL); + cw.gen = 2; cw.target_dom = A; cw.index_decision = RAY_COL_IDX_DROP; + ray_err_t de = ray_col_save_ctx(&cw, ray_test_tmp(CS_TMP "/idx")); + cw.gen = 0; + ray_err_t de0 = ray_col_save_ctx(&cw, ray_test_tmp(CS_TMP "/idx0")); + ray_col_src_release(&cw.src); + TEST_ASSERT_EQ_I(de, RAY_OK); + TEST_ASSERT_EQ_I(de0, RAY_ERR_NYI); + TEST_ASSERT_EQ_U(file_gen(ray_test_tmp(CS_TMP "/idx")), 2); + ray_release(enc); ray_release(v); + ray_sym_domain_release(A); ray_sym_domain_release(C); ray_sym_domain_release(D); + PASS(); +} + +/* A parted source is refused up front in both generations, undecoded. */ +static test_result_t test_write_parted_refused(void) { + for (int pass = 0; pass < 2; pass++) { + if (pass == 0) { write_part("2024.01.01", 2); write_part("2024.01.02", 2); } + else { write_part("2024.01.01", 2); write_part("2024.01.02", 0); } + ray_t* t = ray_read_parted(ray_test_tmp(CS_TMP "/pdb"), "tb"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* a = ray_table_col(t, ray_sym_intern("a", 1)); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + ray_enc_counters_reset(); + for (int g = 0; g <= 2; g += 2) { + TEST_ASSERT_EQ_I(save_ctx(a, ray_test_tmp(CS_TMP "/pq"), (uint8_t)g, NULL), RAY_ERR_NYI); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/pq")), 255); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/pq.tmp")), 255); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(t); + } + PASS(); +} + + +/* ---- Task 15: generation resolution in splayed saves ---- */ + +static uint8_t col_gen_in(const char* dir, const char* name) { + char cur[1024], p[1200]; + if (ray_splay_resolve_dir(dir, cur, sizeof cur) != RAY_OK) return 253; + if (snprintf(p, sizeof p, "%s/%s", cur, name) >= (int)sizeof p) return 253; + return file_gen(p); +} + +static ray_t* plain_tbl(int64_t n) { + ray_t* t = ray_table_new(2); + ray_t* a = i64_col(n, 3); ray_t* b = i64_col(n, 5); + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + t = ray_table_add_col(t, ray_sym_intern("b", 1), b); + ray_release(a); ray_release(b); + return t; +} + +static test_result_t test_inherit_destination(void) { + const char* d = ray_test_tmp(CS_TMP "/inh"); + ray_t* t = plain_tbl(3000); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_ON), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 2); + TEST_ASSERT_EQ_I(col_gen_in(d, "b"), 2); + /* a fresh plain table, no option: the destination keeps generation 2 */ + TEST_ASSERT_EQ_I(ray_splay_save(t, d, NULL), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 2); + /* the loaded (encoded) table into a new directory: the source rule */ + ray_t* l = ray_read_splayed(d, NULL); + TEST_ASSERT_EQ_I(ray_splay_save(l, ray_test_tmp(CS_TMP "/inh2"), NULL), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/inh2"), "b"), 2); + ray_release(l); + /* explicit false writes generation 0 */ + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_OFF), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 0); + TEST_ASSERT_EQ_I(col_gen_in(d, "b"), 0); + /* absent over a generation-0 destination stays 0 */ + TEST_ASSERT_EQ_I(ray_splay_save(t, d, NULL), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 0); + ray_release(t); + PASS(); +} + +static test_result_t test_update_then_save(void) { + const char* d = ray_test_tmp(CS_TMP "/upd"); + ray_t* t = plain_tbl(3000); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_ON), RAY_OK); + ray_release(t); + ray_t* l = ray_read_splayed(d, NULL); + ray_t* mut = i64_col(3000, 11); /* a value update's plain result */ + ray_table_set_col_idx(l, 0, mut); + ray_release(mut); + TEST_ASSERT_EQ_I(ray_splay_save(l, d, NULL), RAY_OK); /* same directory */ + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 2); + TEST_ASSERT_EQ_I(col_gen_in(d, "b"), 2); + TEST_ASSERT_EQ_I(ray_splay_save(l, ray_test_tmp(CS_TMP "/upd2"), NULL), RAY_OK); /* new directory */ + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/upd2"), "a"), 0); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/upd2"), "b"), 2); + /* the mixed directory keeps each column's generation on a plain resave */ + ray_release(l); + l = plain_tbl(3000); + TEST_ASSERT_EQ_I(ray_splay_save(l, ray_test_tmp(CS_TMP "/upd2"), NULL), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/upd2"), "a"), 0); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/upd2"), "b"), 2); + ray_release(l); + PASS(); +} + +static test_result_t test_forced_generation0(void) { + const char* d = ray_test_tmp(CS_TMP "/forced"); + ray_t* t = ray_table_new(3); + ray_t* lnk = i64_col(100, 1); + lnk->attrs |= RAY_ATTR_HAS_LINK; lnk->link_target = ray_sym_intern("other", 5); + ray_t* hx = i64_col(100, 2); + ray_t* hi = ray_index_attach_hash(&hx); + TEST_ASSERT_TRUE(hi && !RAY_IS_ERR(hi)); hx = hi; + ray_t* lst = ray_list_new(100); + for (int i = 0; i < 100; i++) { ray_t* x = ray_i64(i); lst = ray_list_append(lst, x); ray_release(x); } + t = ray_table_add_col(t, ray_sym_intern("l", 1), lnk); + t = ray_table_add_col(t, ray_sym_intern("h", 1), hx); + t = ray_table_add_col(t, ray_sym_intern("x", 1), lst); + ray_release(lnk); ray_release(hx); ray_release(lst); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_ON), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "l"), 0); + TEST_ASSERT_EQ_I(col_gen_in(d, "h"), 2); /* P4: an indexed column is generation 2 */ + char cur[1024], p[1200]; + ray_splay_resolve_dir(d, cur, sizeof cur); + snprintf(p, sizeof p, "%s/l.link", cur); + TEST_ASSERT_EQ_I(access(p, F_OK), 0); /* the .link sidecar was written */ + ray_release(t); + PASS(); +} + +/* The four-way matrix over partitions, with ZONE / UNIQUE / linked inputs: + * plain -> 2, encoded -> 2 (index kind and flag carried), encoded -> 0 + * (materialized, the synthesized index persisted the generation-0 way), and + * linked columns stay generation 0 with their sidecar. */ +static test_result_t test_matrix_parted_indexed(void) { + for (int p = 0; p < 2; p++) { + char dir[256]; snprintf(dir, sizeof dir, ray_test_tmp(CS_TMP "/mp/2024.01.0%d/t"), p + 1); + ray_t* z = i64_col(3000, 3 + p); + ray_t* zi = ray_index_attach_zone(&z); TEST_ASSERT_TRUE(zi && !RAY_IS_ERR(zi)); z = zi; + ray_t* u = i64_col(3000, 1); + ray_t* root = ray_index_new_root(RAY_IDX_NONE, RAY_I64, 3000); + ray_index_payload(root)->markers = RAY_MARK_UNIQUE; + ray_t* ui = ray_index_attach_persisted(&u, root); TEST_ASSERT_TRUE(ui && !RAY_IS_ERR(ui)); u = ui; + ray_t* l = i64_col(3000, 1); + l->attrs |= RAY_ATTR_HAS_LINK; l->link_target = ray_sym_intern("other", 5); + ray_t* t = ray_table_new(3); + t = ray_table_add_col(t, ray_sym_intern("z", 1), z); + t = ray_table_add_col(t, ray_sym_intern("u", 1), u); + t = ray_table_add_col(t, ray_sym_intern("l", 1), l); + ray_release(z); ray_release(u); ray_release(l); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, dir, NULL, RAY_COMPRESS_ON), RAY_OK); + ray_release(t); + TEST_ASSERT_EQ_I(col_gen_in(dir, "z"), 2); + TEST_ASSERT_EQ_I(col_gen_in(dir, "u"), 2); + TEST_ASSERT_EQ_I(col_gen_in(dir, "l"), 0); + } + for (int p = 0; p < 2; p++) { + char src[256], d2[256], d0[256], cur[1024], lp[1200]; + snprintf(src, sizeof src, ray_test_tmp(CS_TMP "/mp/2024.01.0%d/t"), p + 1); + snprintf(d2, sizeof d2, ray_test_tmp(CS_TMP "/mp2/2024.01.0%d/t"), p + 1); + snprintf(d0, sizeof d0, ray_test_tmp(CS_TMP "/mp0/2024.01.0%d/t"), p + 1); + ray_t* t = ray_read_splayed(src, NULL); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ray_splay_save(t, d2, NULL), RAY_OK); /* encoded -> 2 */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d0, NULL, RAY_COMPRESS_OFF), RAY_OK); /* encoded -> 0 */ + ray_release(t); + TEST_ASSERT_EQ_I(col_gen_in(d2, "z"), 2); + TEST_ASSERT_EQ_I(col_gen_in(d0, "z"), 0); + ray_splay_resolve_dir(d2, cur, sizeof cur); + snprintf(lp, sizeof lp, "%s/l.link", cur); + TEST_ASSERT_EQ_I(access(lp, F_OK), 0); + ray_t* t2 = ray_read_splayed(d2, NULL); + ray_col_meta_t m; + TEST_ASSERT_TRUE(ray_table_col_meta(t2, ray_sym_intern("z", 1), &m) && m.index_kind == RAY_IDX_ZONE); + TEST_ASSERT_TRUE(ray_table_col_meta(t2, ray_sym_intern("u", 1), &m) && m.unique); + ray_release(t2); + ray_t* t0 = ray_read_splayed(d0, NULL); + ray_t* z0 = ray_table_col(t0, ray_sym_intern("z", 1)); + TEST_ASSERT_EQ_I(ray_index_kind(z0), RAY_IDX_ZONE); + ray_t* u0 = ray_table_col(t0, ray_sym_intern("u", 1)); + TEST_ASSERT_TRUE(ray_index_has(u0) && (ray_index_payload(u0->index)->markers & RAY_MARK_UNIQUE)); + ray_release(t0); + } + ray_t* pt = ray_read_parted(ray_test_tmp(CS_TMP "/mp2"), "t"); + TEST_ASSERT_TRUE(pt && !RAY_IS_ERR(pt)); + TEST_ASSERT_EQ_I(ray_table_nrows(pt), 6000); + ray_release(pt); + PASS(); +} + +static test_result_t test_chunk_zone_recorded(void) { + const char* d = ray_test_tmp(CS_TMP "/cz"); + ray_t* t = plain_tbl(70000); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_ON), RAY_OK); + ray_release(t); + ray_t* l = ray_read_splayed(d, NULL); + ray_col_meta_t m; + TEST_ASSERT_TRUE(ray_table_col_meta(l, ray_sym_intern("a", 1), &m)); + TEST_ASSERT_EQ_I(m.index_kind, RAY_IDX_CHUNK_ZONE); + ray_t* a = ray_table_col(l, ray_sym_intern("a", 1)); + TEST_ASSERT_EQ_I(ray_index_kind(a), RAY_IDX_CHUNK_ZONE); + ray_release(l); + PASS(); +} + +static test_result_t test_staged_and_sym(void) { + ray_t* t = ray_table_new(1); + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, 2000); s->len = 2000; + int64_t ids[3] = { ray_sym_intern("x", 1), ray_sym_intern("y", 1), ray_sym_intern("z", 1) }; + for (int i = 0; i < 2000; i++) ((int64_t*)ray_data(s))[i] = ids[i % 3]; + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + ray_release(s); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/sy"), ray_test_tmp(CS_TMP "/sy.sym"), RAY_COMPRESS_ON), RAY_OK); + ray_release(t); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/sy"), "s"), 2); + ray_t* l = ray_read_splayed(ray_test_tmp(CS_TMP "/sy"), ray_test_tmp(CS_TMP "/sy.sym")); + TEST_ASSERT_TRUE(l && !RAY_IS_ERR(l)); + /* private staging path, absent mode, encoded source: generation 2, into + * another symfile. Like the CSV/Parquet staging callers, the test holds + * the target domain alive across the save and flushes it afterwards. */ + struct ray_sym_domain_s* d2 = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/sy2.sym")); + TEST_ASSERT_NOT_NULL(d2); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ray_splay_save_staged_bulk_mode(l, ray_test_tmp(CS_TMP "/sy2"), ray_test_tmp(CS_TMP "/sy2.sym"), RAY_COMPRESS_ABSENT), RAY_OK); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); /* merge and write by range */ + TEST_ASSERT_EQ_I(ray_sym_domain_flush(d2, false), RAY_OK); + ray_sym_domain_release(d2); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/sy2/s")), 2); + ray_t* l2 = ray_read_splayed(ray_test_tmp(CS_TMP "/sy2"), ray_test_tmp(CS_TMP "/sy2.sym")); + TEST_ASSERT_TRUE(l2 && !RAY_IS_ERR(l2)); + ray_t* c1 = ray_table_col(l, ray_sym_intern("s", 1)); + ray_t* c2 = ray_table_col(l2, ray_sym_intern("s", 1)); + for (int64_t i = 0; i < 2000; i++) { + ray_t* x = ray_sym_vec_cell(c1, i); ray_t* y = ray_sym_vec_cell(c2, i); + TEST_ASSERT_TRUE(ray_str_len(x) == ray_str_len(y) && memcmp(ray_str_ptr(x), ray_str_ptr(y), ray_str_len(x)) == 0); + } + ray_release(l2); ray_release(l); + PASS(); +} + +/* Preflight admits a single encoded column but keeps refusing parted kinds + * (a parted RAY_ENCCOL and a plain parted wrapper) and the partition key + * column: a splayed save of a table carrying one is nyi before anything is + * written, and nothing is decoded. */ +static test_result_t test_save_refuses_parted_kinds(void) { + for (int pass = 0; pass < 2; pass++) { + write_part("2024.01.01", pass ? 0 : 2); write_part("2024.01.02", pass ? 0 : 2); + ray_t* pt = ray_read_parted(ray_test_tmp(CS_TMP "/pdb"), "tb"); + TEST_ASSERT_TRUE(pt && !RAY_IS_ERR(pt)); + TEST_ASSERT_EQ_I(ray_table_ncols(pt), 2); + ray_t* key = ray_table_get_col_enc_idx(pt, 0) ? NULL : ray_table_col_idx(pt, 0); + TEST_ASSERT_TRUE(key && key->type == RAY_MAPCOMMON); + ray_t* enc = ray_table_get_col_enc_idx(pt, 1); + ray_t* slot = enc ? enc : ray_table_col_idx(pt, 1); + if (pass == 0) TEST_ASSERT_TRUE(enc && ray_enccol_is_parted(enc)); + else TEST_ASSERT_TRUE(!enc && RAY_IS_PARTED(slot->type)); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ray_col_save_preflight(slot), RAY_ERR_NYI); + TEST_ASSERT_EQ_I(ray_col_save_preflight(key), RAY_ERR_NYI); + for (int which = 0; which < 3; which++) { + ray_t* t; + if (which == 2) { t = pt; ray_retain(t); } + else { + t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("c", 1), which ? key : slot); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + } + for (int m = 0; m < 3; m++) { + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/pref"), NULL, (ray_compress_t)m), RAY_ERR_NYI); + TEST_ASSERT_FALSE(ray_splay_has_schema(ray_test_tmp(CS_TMP "/pref"))); + TEST_ASSERT_EQ_I(access(ray_test_tmp(CS_TMP "/pref/c"), F_OK), -1); + } + ray_release(t); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(pt); + } + /* a single encoded column passes preflight */ + ray_t* v = i64_col(3000, 3); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/one"), 2), RAY_OK); + ray_release(v); + ray_t* e = ray_col_mmap(ray_test_tmp(CS_TMP "/one")); + TEST_ASSERT_TRUE(e && !RAY_IS_ERR(e) && e->type == RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_col_save_preflight(e), RAY_OK); + ray_release(e); + PASS(); +} + +/* The resolver on its own: explicit modes, the source rule, the destination + * rule, the forced kinds, and the equivalence-run hook. */ +static test_result_t test_resolver_rules(void) { + ray_t* v = i64_col(100, 1); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ON, v, NULL, "a", 1), 2); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_OFF, v, NULL, "a", 1), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, v, NULL, "a", 1), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, v, "", "a", 1), 0); + (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP "/rd")); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/rd/a"), 2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/rd/b"), 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_file_gen(ray_test_tmp(CS_TMP "/rd/a")), 2); + TEST_ASSERT_EQ_I(ray_col_file_gen(ray_test_tmp(CS_TMP "/rd/b")), 0); + TEST_ASSERT_EQ_I(ray_col_file_gen(ray_test_tmp(CS_TMP "/rd/missing")), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, v, ray_test_tmp(CS_TMP "/rd"), "a", 1), 2); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, v, ray_test_tmp(CS_TMP "/rd"), "b", 1), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_OFF, v, ray_test_tmp(CS_TMP "/rd"), "a", 1), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen_type(RAY_COMPRESS_ABSENT, RAY_I64, ray_test_tmp(CS_TMP "/rd"), "a", 1), 2); + TEST_ASSERT_EQ_I(ray_col_resolve_gen_type(RAY_COMPRESS_ABSENT, RAY_I64, ray_test_tmp(CS_TMP "/rd"), "b", 1), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen_type(RAY_COMPRESS_ON, RAY_LIST, NULL, "a", 1), 0); + TEST_ASSERT_EQ_I(ray_col_resolve_gen_type(RAY_COMPRESS_ON, RAY_I64, NULL, "a", 1), 2); + ray_t* e = ray_col_mmap(ray_test_tmp(CS_TMP "/rd/a")); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, e, NULL, "x", 1), 2); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_OFF, e, NULL, "x", 1), 0); + ray_release(e); + ray_t* lnk = i64_col(10, 1); + lnk->attrs |= RAY_ATTR_HAS_LINK; lnk->link_target = ray_sym_intern("other", 5); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ON, lnk, ray_test_tmp(CS_TMP "/rd"), "a", 1), 0); + ray_release(lnk); + ray_store_test_force_compress(true); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, v, NULL, "a", 1), 2); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_OFF, v, NULL, "a", 1), 0); + ray_store_test_force_compress(false); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, v, NULL, "a", 1), 0); + ray_release(v); + PASS(); +} + + +static ray_t* sym_tbl(const char* pfx, int nd, int64_t n) { + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, n); s->len = n; + for (int64_t i = 0; i < n; i++) { + char b[32]; int k = snprintf(b, sizeof b, "%s%d", pfx, (int)(i % nd)); + ((int64_t*)ray_data(s))[i] = ray_sym_intern(b, (size_t)k); + } + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + ray_release(s); + return t; +} + +static bool sym_cells_eq(ray_t* x, ray_t* y, int64_t n) { + if (!x || !y || RAY_IS_ERR(x) || RAY_IS_ERR(y) || x->len != n || y->len != n) return false; + for (int64_t i = 0; i < n; i++) { + ray_t* a = ray_sym_vec_cell(x, i); ray_t* b = ray_sym_vec_cell(y, i); + if (!a || !b || ray_str_len(a) != ray_str_len(b) || + memcmp(ray_str_ptr(a), ray_str_ptr(b), ray_str_len(a)) != 0) return false; + } + return true; +} + +/* Sources of different SYM id widths (an 8-bit and a 16-bit generation-2 + * column over two symfiles, and a plain 64-bit runtime column) through one + * vocabulary merge into a third symfile: decode-free, ids correct. */ +static test_result_t test_merge_mixed_widths(void) { + const int64_t n = 3000; + ray_t* t1 = sym_tbl("p", 2, n); + ray_t* t2 = sym_tbl("k", 300, n); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t1, ray_test_tmp(CS_TMP "/m1"), ray_test_tmp(CS_TMP "/m1.sym"), RAY_COMPRESS_ON), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t2, ray_test_tmp(CS_TMP "/m2"), ray_test_tmp(CS_TMP "/m2.sym"), RAY_COMPRESS_ON), RAY_OK); + ray_t* l1 = ray_read_splayed(ray_test_tmp(CS_TMP "/m1"), ray_test_tmp(CS_TMP "/m1.sym")); + ray_t* l2 = ray_read_splayed(ray_test_tmp(CS_TMP "/m2"), ray_test_tmp(CS_TMP "/m2.sym")); + TEST_ASSERT_TRUE(l1 && !RAY_IS_ERR(l1) && l2 && !RAY_IS_ERR(l2)); + ray_t* e1 = ray_table_get_col_enc_idx(l1, 0); + ray_t* e2 = ray_table_get_col_enc_idx(l2, 0); + TEST_ASSERT_TRUE(e1 && e2); + ray_col_meta_t m1, m2; + TEST_ASSERT_TRUE(ray_col_meta_of(e1, &m1) && ray_col_meta_of(e2, &m2)); + TEST_ASSERT_EQ_I(m1.attrs & RAY_SYM_W_MASK, RAY_SYM_W8); + TEST_ASSERT_EQ_I(m2.attrs & RAY_SYM_W_MASK, RAY_SYM_W16); + ray_t* c3 = ray_table_col_idx(t2, 0); /* plain W64 runtime ids */ + ray_t* t = ray_table_new(3); + t = ray_table_add_col(t, ray_sym_intern("a", 1), e1); + t = ray_table_add_col(t, ray_sym_intern("b", 1), e2); + t = ray_table_add_col(t, ray_sym_intern("c", 1), c3); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + struct ray_sym_domain_s* d3 = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/m3.sym")); + TEST_ASSERT_NOT_NULL(d3); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ray_splay_save_staged_bulk_mode(t, ray_test_tmp(CS_TMP "/m3"), ray_test_tmp(CS_TMP "/m3.sym"), RAY_COMPRESS_ABSENT), RAY_OK); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(d3, false), RAY_OK); + ray_sym_domain_release(d3); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/m3/a")), 2); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/m3/b")), 2); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/m3/c")), 0); + ray_t* l3 = ray_read_splayed(ray_test_tmp(CS_TMP "/m3"), ray_test_tmp(CS_TMP "/m3.sym")); + TEST_ASSERT_TRUE(l3 && !RAY_IS_ERR(l3)); + TEST_ASSERT_TRUE(sym_cells_eq(ray_table_col_idx(l3, 0), ray_table_col_idx(t1, 0), n)); + TEST_ASSERT_TRUE(sym_cells_eq(ray_table_col_idx(l3, 1), ray_table_col_idx(t2, 0), n)); + TEST_ASSERT_TRUE(sym_cells_eq(ray_table_col_idx(l3, 2), ray_table_col_idx(t2, 0), n)); + ray_release(l3); ray_release(t); + ray_release(l1); ray_release(l2); ray_release(t1); ray_release(t2); + PASS(); +} + +static bool files_eq(const char* a, const char* b) { + size_t na, nb; + uint8_t* x = slurp(a, &na); uint8_t* y = slurp(b, &nb); + bool eq = x && y && na == nb && memcmp(x, y, na) == 0; + free(x); free(y); + return eq; +} + +/* Existing users: an absent option onto no destination and onto a + * generation-0 destination writes exactly what the per-column generation-0 + * writers produce (the pre-resolution path). */ +static test_result_t test_absent_byte_identity(void) { + const int64_t n = 3000; + ray_t* t = sym_tbl("v", 7, n); + ray_t* a = i64_col(n, 3); + ray_t* st = ray_vec_new(RAY_STR, n); + for (int64_t i = 0; i < n; i++) { + char b[48]; int k = snprintf(b, sizeof b, i % 3 ? "x%d" : "a long string value %d", (int)i); + st = ray_str_vec_append(st, b, (size_t)k); + } + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + t = ray_table_add_col(t, ray_sym_intern("t", 1), st); + ray_release(a); ray_release(st); + TEST_ASSERT_EQ_I(ray_splay_save(t, ray_test_tmp(CS_TMP "/bi"), ray_test_tmp(CS_TMP "/bi.sym")), RAY_OK); + /* the reference: today's per-column writers */ + (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP "/ref")); + struct ray_sym_domain_s* dom = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/bi.sym")); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_col_save_sym_encoded(ray_table_col_idx(t, 0), ray_test_tmp(CS_TMP "/ref/s"), dom, true), RAY_OK); + ray_sym_domain_release(dom); + TEST_ASSERT_EQ_I(ray_col_save(ray_table_col_idx(t, 1), ray_test_tmp(CS_TMP "/ref/a")), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(ray_table_col_idx(t, 2), ray_test_tmp(CS_TMP "/ref/t")), RAY_OK); + ray_t* names = ray_vec_new(RAY_STR, 3); + names = ray_str_vec_append(names, "s", 1); + names = ray_str_vec_append(names, "a", 1); + names = ray_str_vec_append(names, "t", 1); + TEST_ASSERT_EQ_I(ray_col_save(names, ray_test_tmp(CS_TMP "/ref/.d")), RAY_OK); + ray_release(names); + const char* files[4] = { "s", "a", "t", ".d" }; + for (int pass = 0; pass < 2; pass++) { + if (pass == 1) /* again, onto the generation-0 destination */ + TEST_ASSERT_EQ_I(ray_splay_save(t, ray_test_tmp(CS_TMP "/bi"), ray_test_tmp(CS_TMP "/bi.sym")), RAY_OK); + char cur[1024], p[1200], r[256]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(ray_test_tmp(CS_TMP "/bi"), cur, sizeof cur), RAY_OK); + for (int f = 0; f < 4; f++) { + snprintf(p, sizeof p, "%s/%s", cur, files[f]); + snprintf(r, sizeof r, ray_test_tmp(CS_TMP "/ref/%s"), files[f]); + TEST_ASSERT_TRUE(files_eq(p, r)); + } + } + ray_release(t); + PASS(); +} + +/* An absent option never drops inheritance silently: an unreadable + * destination column or generation pointer fails the save, and nothing is + * published. A destination file in a header-less list format is + * generation 0, not an error. */ +static test_result_t test_unreadable_destination(void) { + if (geteuid() == 0) SKIP("running as root: permissions are not enforced"); + const char* d = ray_test_tmp(CS_TMP "/ur"); + ray_t* t = plain_tbl(3000); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_OFF), RAY_OK); + char cur[1024], cur2[1024], p[1200]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur, sizeof cur), RAY_OK); + snprintf(p, sizeof p, "%s/a", cur); + uint8_t g = 9; + TEST_ASSERT_EQ_I(chmod(p, 0), 0); + TEST_ASSERT_EQ_I(ray_col_file_gen_err(p, &g), RAY_ERR_IO); + TEST_ASSERT_EQ_I(ray_splay_save(t, d, NULL), RAY_ERR_IO); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur2, sizeof cur2), RAY_OK); + TEST_ASSERT_TRUE(strcmp(cur2, cur) == 0); /* nothing published */ + /* an explicit option does not read the destination */ + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_OFF), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 0); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur, sizeof cur), RAY_OK); + snprintf(p, sizeof p, "%s/a", cur); + TEST_ASSERT_EQ_I(chmod(p, 0), 0); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_ON), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 2); + /* the generation pointer itself unreadable: an inheriting save fails, + * explicit ones proceed as before */ + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur, sizeof cur), RAY_OK); + snprintf(p, sizeof p, "%s/.current", d); + TEST_ASSERT_EQ_I(chmod(p, 0), 0); + TEST_ASSERT_TRUE(ray_splay_save(t, d, NULL) != RAY_OK); + TEST_ASSERT_EQ_I(chmod(p, 0644), 0); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur2, sizeof cur2), RAY_OK); + TEST_ASSERT_TRUE(strcmp(cur2, cur) == 0); /* nothing published */ + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), 2); + for (int m = RAY_COMPRESS_ON; m <= RAY_COMPRESS_OFF; m++) { + TEST_ASSERT_EQ_I(chmod(p, 0), 0); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, (ray_compress_t)m), RAY_OK); + TEST_ASSERT_EQ_I(chmod(p, 0644), 0); + TEST_ASSERT_EQ_I(col_gen_in(d, "a"), m == RAY_COMPRESS_ON ? 2 : 0); + } + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur, sizeof cur), RAY_OK); + /* a short (truncated) destination column is corrupt, not 0 */ + snprintf(p, sizeof p, "%s/b", cur); + TEST_ASSERT_EQ_I(truncate(p, 10), 0); + TEST_ASSERT_EQ_I(ray_col_file_gen_err(p, &g), RAY_ERR_CORRUPT); + TEST_ASSERT_EQ_I(ray_col_file_gen_err(ray_test_tmp(CS_TMP "/nope"), &g), RAY_OK); + TEST_ASSERT_EQ_I(g, 0); + TEST_ASSERT_EQ_I(ray_splay_save(t, d, NULL), RAY_ERR_CORRUPT); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(d, cur2, sizeof cur2), RAY_OK); + TEST_ASSERT_TRUE(strcmp(cur2, cur) == 0); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, d, NULL, RAY_COMPRESS_OFF), RAY_OK); /* explicit: replaced */ + TEST_ASSERT_EQ_I(col_gen_in(d, "b"), 0); + ray_release(t); + /* a string-list column file at the name of a now-plain column */ + ray_t* lt = ray_table_new(1); + ray_t* lst = ray_list_new(3); + for (int i = 0; i < 3; i++) { ray_t* x = ray_str("ab", 2); lst = ray_list_append(lst, x); ray_release(x); } + lt = ray_table_add_col(lt, ray_sym_intern("a", 1), lst); + ray_release(lst); + TEST_ASSERT_EQ_I(ray_splay_save(lt, ray_test_tmp(CS_TMP "/ul"), NULL), RAY_OK); + ray_release(lt); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(ray_test_tmp(CS_TMP "/ul"), cur, sizeof cur), RAY_OK); + snprintf(p, sizeof p, "%s/a", cur); + TEST_ASSERT_EQ_I(ray_col_file_gen_err(p, &g), RAY_OK); + TEST_ASSERT_EQ_I(g, 0); + ray_t* pt = ray_table_new(1); + ray_t* v = i64_col(3, 1); + pt = ray_table_add_col(pt, ray_sym_intern("a", 1), v); + ray_release(v); + TEST_ASSERT_EQ_I(ray_splay_save(pt, ray_test_tmp(CS_TMP "/ul"), NULL), RAY_OK); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/ul"), "a"), 0); + ray_release(pt); + PASS(); +} + +/* Evaluate and return the error code ("" for success), releasing the value. */ +static const char* ev_code(const char* src) { + static char code[16]; + ray_t* r = ray_eval_str(src); + snprintf(code, sizeof code, "%s", (r && RAY_IS_ERR(r)) ? ray_err_code(r) : ""); + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + return code; +} + +/* The user-visible values built from a generation-2 table are plain. */ +static test_result_t test_user_values_are_plain(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['a 'b] (list [1 2 3] [4 5 6])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/uv\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u (.db.splayed.get \"" CS_TMP "/uv\"))")), ""); + ray_t* a = ray_eval_str("(at u 'a)"); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && a->type == RAY_I64 && a->len == 3); + ray_release(a); + ray_t* s = ray_eval_str("(format \"%\" u)"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); + ray_release(s); + PASS(); +} + +static test_result_t test_db_splayed_set_forms(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['a 'b] (list [1 2 3] [4 5 6])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f1\" t)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/f1"), "a"), 0); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f2\" t \"" CS_TMP "/f2.sym\")")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f3\" t {compress: true})")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/f3"), "a"), 2); + /* absent over a generation-2 destination inherits it */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f3\" t)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/f3"), "a"), 2); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f3\" t \"" CS_TMP "/f3.sym\" {compress: false})")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/f3"), "a"), 0); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f4\" t {compress: true} {compress: true})")), "domain"); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f4\" t {compress: 1})")), "domain"); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f4\" t {other: true})")), "domain"); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(sum (at (.db.splayed.get \"" CS_TMP "/f3\") 'b))")), ""); + /* round trip through a generation-2 destination */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f5\" t {compress: true})")), ""); + ray_t* r = ray_eval_str(ray_test_tmp("(sum (at (.db.splayed.get \"" CS_TMP "/f5\") 'b))")); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 15); + ray_release(r); + r = ray_eval_str(ray_test_tmp("(all (== (at (.db.splayed.get \"" CS_TMP "/f5\") 'a) [1 2 3]))")); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == -RAY_BOOL && r->b8); + ray_release(r); + /* {} is absent; a null compress is a domain error */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f6\" t {})")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/f6"), "a"), 0); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f6\" t {compress: null})")), "domain"); + /* an empty symfile path keeps its old meaning: no convention fallback */ + TEST_ASSERT_STR_EQ(ev_code("(set ts (table ['s] (list ['x 'y])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/f7\" ts \"\")")), "domain"); + PASS(); +} + +static test_result_t test_csv_parted_option(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['a 'b] (list [1 2 3 4] [10 20 30 40])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.write t \"" CS_TMP "/in.csv\")")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {compress: true} \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr\" 't)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/pr/0/t"), "a"), 2); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr0\" 't)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/pr0/0/t"), "a"), 0); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {compress: true} {compress: true} \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr1\" 't)")), "domain"); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {zone: true} \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr1\" 't)")), "domain"); + /* existing root: explicit modes and inheritance, typed + rows_per_part */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {compress: false} \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr\" 't)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/pr/0/t"), "a"), 0); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {compress: true} \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr\" 't)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/pr/0/t"), "a"), 2); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr\" 't)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/pr/0/t"), "a"), 2); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {compress: true} [I64 I64] \"" CS_TMP "/in.csv\" 2 \"" CS_TMP "/pt\" 't)")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/pt/1/t"), "a"), 2); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.parted {compress: null} \"" CS_TMP "/in.csv\" \"" CS_TMP "/pr1\" 't)")), "domain"); + ray_t* r = ray_eval_str(ray_test_tmp("(sum (at (.db.parted.get \"" CS_TMP "/pr\" 't) 'b))")); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 100); + ray_release(r); + PASS(); +} + +/* ---- Task 17: generation-2 stream writer; .csv.splayed and Parquet ---- */ + +/* Streaming the same I64 values in two appends gives the resident bytes. */ +static test_result_t test_stream_matches_resident(void) { + int64_t n = 140000; + ray_t* v = i64_col(n, 13); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/res"), 2), RAY_OK); + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("str1", 4), RAY_I64, NULL, 2), RAY_OK); + ray_t* p1 = ray_vec_new(RAY_I64, 70000); p1->len = 70000; + ray_t* p2 = ray_vec_new(RAY_I64, n - 70000); p2->len = n - 70000; + for (int64_t i = 0; i < 70000; i++) ((int64_t*)ray_data(p1))[i] = i * 13; + for (int64_t i = 0; i < n - 70000; i++) ((int64_t*)ray_data(p2))[i] = (70000 + i) * 13; + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, p1), RAY_OK); /* streams reject slices */ + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, p2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + ray_col_stream_abort(&w); /* always valid; nothing left */ + size_t na, nb; uint8_t* a = slurp(ray_test_tmp(CS_TMP "/res"), &na); uint8_t* b = slurp(ray_test_tmp(CS_TMP "/str1"), &nb); + TEST_ASSERT_TRUE(a && b); + TEST_ASSERT_TRUE(na == nb && memcmp(a, b, na) == 0); /* no zone accumulator: identical */ + free(a); free(b); + /* with the converters' zone accumulator the stream records CHUNK_ZONE, + * as the generation-0 stream persists one */ + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("str2", 4), RAY_I64, NULL, 2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, p1), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, p2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + ray_col_stream_abort(&w); + b = slurp(ray_test_tmp(CS_TMP "/str2"), &nb); + TEST_ASSERT_TRUE(b && nb >= 96); + ray_enc_hdr_t hb; memcpy(&hb, b + 32, 64); + TEST_ASSERT_EQ_I(hb.index_kind, RAY_IDX_CHUNK_ZONE); + free(b); + ray_release(p1); ray_release(p2); ray_release(v); + PASS(); +} + +/* STR rows [lo, hi): empties, short inline cells and repeating long cells. */ +static ray_t* str_rows(int64_t lo, int64_t hi) { + ray_t* v = ray_vec_new(RAY_STR, hi - lo); + char b[96]; + for (int64_t i = lo; i < hi; i++) { + int len; + if (i % 7 == 0) len = 0; + else if (i % 3 == 0) len = snprintf(b, sizeof b, "s%lld", (long long)(i % 50)); + else len = snprintf(b, sizeof b, "a much longer string value number %lld", (long long)(i % 1000)); + v = ray_str_vec_append(v, b, (size_t)len); + } + return v; +} + +/* Same bytes from offset `from` on. */ +static bool same_file_from(const char* x, const char* y, size_t from) { + size_t na, nb; uint8_t* a = slurp(x, &na); uint8_t* b = slurp(y, &nb); + bool ok = a && b && na == nb && na >= from && memcmp(a + from, b + from, na - from) == 0; + free(a); free(b); + return ok; +} + +/* A STR column across several chunks, streamed in three appends (each its + * own pool) gives the resident generation-2 bytes; generation 0 streams + * stay today's bytes (the resident generation-0 writer's). */ +static test_result_t test_stream_str_matches_resident(void) { + int64_t n = 200000, cut[4] = { 0, 50000, 130001, 200000 }; + ray_t* v = str_rows(0, n); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(CS_TMP "/sres"), 2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_bulk(v, ray_test_tmp(CS_TMP "/sres0")), RAY_OK); + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("sst2", 4), RAY_STR, NULL, 2), RAY_OK); + for (int k = 0; k < 3; k++) { + ray_t* p = str_rows(cut[k], cut[k + 1]); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, p), RAY_OK); + ray_release(p); + } + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + ray_col_stream_abort(&w); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/sst2")), 2); + TEST_ASSERT_TRUE(same_file_from(ray_test_tmp(CS_TMP "/sres"), ray_test_tmp(CS_TMP "/sst2"), 0)); + /* generation 0, one append: the resident generation-0 bytes */ + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("sst0", 4), RAY_STR, NULL, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, v), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + ray_col_stream_abort(&w); + TEST_ASSERT_TRUE(same_file_from(ray_test_tmp(CS_TMP "/sres0"), ray_test_tmp(CS_TMP "/sst0"), 0)); + /* the generation-2 file loads back to the same cells */ + ray_t* back = ray_col_load(ray_test_tmp(CS_TMP "/sst2")); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back) && back->len == n); + for (int64_t i = 0; i < n; i += 997) { + size_t la, lb; const char* a = ray_str_vec_get(v, i, &la); const char* b = ray_str_vec_get(back, i, &lb); + TEST_ASSERT_TRUE(la == lb && (la == 0 || memcmp(a, b, la) == 0)); + } + ray_release(back); + /* I64 generation 0 streamed in two appends: the resident bytes */ + ray_t* iv = i64_col(140000, 13); + TEST_ASSERT_EQ_I(ray_col_save_bulk(iv, ray_test_tmp(CS_TMP "/ires0")), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("ist0", 4), RAY_I64, NULL, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, iv), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); + ray_col_stream_abort(&w); + TEST_ASSERT_TRUE(same_file_from(ray_test_tmp(CS_TMP "/ires0"), ray_test_tmp(CS_TMP "/ist0"), 0)); + /* any other generation is refused before a file exists */ + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("bad", 3), RAY_I64, NULL, 1), RAY_ERR_VERSION); + ray_col_stream_abort(&w); + ray_release(iv); ray_release(v); + PASS(); +} + +/* SYM rows [lo, hi) as strings: a null ("") every 11th row. */ +static ray_t* sym_text_rows(int64_t lo, int64_t hi) { + ray_t* v = ray_vec_new(RAY_STR, hi - lo); + char b[32]; + for (int64_t i = lo; i < hi; i++) { + int len = i % 11 == 0 ? 0 : snprintf(b, sizeof b, "v%lld", (long long)(i % 300)); + v = ray_str_vec_append(v, b, (size_t)len); + } + return v; +} + +static ray_err_t stream_sym(struct ray_sym_domain_s* d, const char* name, uint8_t gen, int64_t n) { + ray_col_stream_t w; + ray_err_t e = ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern(name, strlen(name)), RAY_SYM, d, gen); + int64_t cut[4] = { 0, n / 3, n / 3 * 2 + 1, n }; + for (int k = 0; e == RAY_OK && k < 3; k++) { + ray_t* p = sym_text_rows(cut[k], cut[k + 1]); + e = ray_col_stream_append(&w, p); + ray_release(p); + } + if (e == RAY_OK) e = ray_col_stream_close(&w, false); + ray_col_stream_abort(&w); + return e; +} + +/* A generation-2 SYM stream (three chunks, null ids) loads back to the + * generation-0 stream of the same values; its outer header keeps the + * symfile count in rc, the W32 width it was opened with and HAS_NULLS. */ +static test_result_t test_stream_sym_gen2(void) { + struct ray_sym_domain_s* d = ray_sym_domain_open_or_create(ray_test_tmp(CS_TMP "/s.sym")); + TEST_ASSERT_TRUE(d != NULL); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(d, "", 0), 0); + int64_t n = 140000; + TEST_ASSERT_EQ_I(stream_sym(d, "sy0", 0, n), RAY_OK); + TEST_ASSERT_EQ_I(stream_sym(d, "sy2", 2, n), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(d, false), RAY_OK); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/sy0")), 0); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(CS_TMP "/sy2")), 2); + size_t nb; uint8_t* b = slurp(ray_test_tmp(CS_TMP "/sy2"), &nb); + TEST_ASSERT_TRUE(b && nb >= 32); + ray_t hdr; memcpy(&hdr, b, 32); free(b); + TEST_ASSERT_EQ_I(hdr.type, RAY_SYM); + TEST_ASSERT_EQ_I((int64_t)hdr.rc, ray_sym_domain_count(d)); + TEST_ASSERT_EQ_I(hdr.attrs & RAY_SYM_W_MASK, RAY_SYM_W32); + TEST_ASSERT_TRUE(hdr.attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_EQ_I(hdr.len, n); + ray_t* a = ray_col_load_dom(ray_test_tmp(CS_TMP "/sy0"), d); + ray_t* c = ray_col_load_dom(ray_test_tmp(CS_TMP "/sy2"), d); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && c && !RAY_IS_ERR(c)); + TEST_ASSERT_EQ_I(a->len, n); TEST_ASSERT_EQ_I(c->len, n); + TEST_ASSERT_TRUE(c->attrs & RAY_ATTR_HAS_NULLS); + int64_t nulls = 0; + for (int64_t i = 0; i < n; i++) { + ray_t* s0 = ray_sym_vec_cell(a, i); ray_t* s1 = ray_sym_vec_cell(c, i); + TEST_ASSERT_TRUE(s0 && s1 && ray_str_len(s0) == ray_str_len(s1) && + memcmp(ray_str_ptr(s0), ray_str_ptr(s1), ray_str_len(s0)) == 0); + if (!ray_str_len(s1)) nulls++; + } + TEST_ASSERT_EQ_I(nulls, (n + 10) / 11); + ray_release(a); ray_release(c); + ray_sym_domain_release(d); + PASS(); +} + +/* A generation-2 transcode that cannot write its output (RLIMIT_FSIZE at + * the raw staging size, so only the encoded file overflows) fails the close + * and leaves nothing: no column file, no .stream-* staging or .g2 file. */ +#ifdef RAY_OS_LINUX +static bool cs_dir_has_stream_tmp(const char* dir) { + char cmd[256]; + snprintf(cmd, sizeof cmd, "ls -A %s | grep -q '^\\.stream-'", dir); + return system(cmd) == 0; +} +#endif +static test_result_t test_stream_gen2_transcode_failure(void) { +#ifdef RAY_OS_LINUX + int64_t n = 140000; + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + uint64_t x = 0x9E3779B97F4A7C15ull; + for (int64_t i = 0; i < n; i++) { /* incompressible: RAW vectors */ + x ^= x << 13; x ^= x >> 7; x ^= x << 17; + ((int64_t*)ray_data(v))[i] = (int64_t)(x & 0x7FFFFFFFFFFFFFFFull); + } + pid_t pid = fork(); TEST_ASSERT_TRUE(pid >= 0); + if (!pid) { + ray_col_stream_t w; + struct rlimit limit; + if (getrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + limit.rlim_cur = (rlim_t)(32 + n * 8); /* the raw staging file fits exactly */ + if (signal(SIGXFSZ, SIG_IGN) == SIG_ERR || setrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + if (ray_col_stream_open(&w, ray_test_tmp(CS_TMP), ray_sym_intern("tf", 2), RAY_I64, NULL, 2) != RAY_OK) _exit(2); + if (ray_col_stream_append(&w, v) != RAY_OK) _exit(2); + ray_err_t e = ray_col_stream_close(&w, false); + ray_col_stream_abort(&w); + _exit(e == RAY_ERR_IO ? 0 : 1); + } + int status; + TEST_ASSERT_EQ_I(waitpid(pid, &status, 0), pid); + TEST_ASSERT_TRUE(WIFEXITED(status)); TEST_ASSERT_EQ_I(WEXITSTATUS(status), 0); + TEST_ASSERT_TRUE(access(ray_test_tmp(CS_TMP "/tf"), F_OK) != 0); + TEST_ASSERT_FALSE(cs_dir_has_stream_tmp(ray_test_tmp(CS_TMP))); + ray_release(v); + PASS(); +#else + SKIP("requires Linux RLIMIT_FSIZE fault injection"); +#endif +} + +/* The resident generation-0 STR writer used to copy the runtime str_pool + * pointer (aux bytes 8..15) into the file when HAS_NULLS was set: two saves + * of equal vectors now give identical bytes, with those bytes zero. */ +static test_result_t test_str_header_no_pointer(void) { + ray_t* a = str_rows(0, 5000); + ray_t* b = str_rows(0, 5000); + TEST_ASSERT_TRUE(a->attrs & RAY_ATTR_HAS_NULLS); /* the case that kept aux */ + TEST_ASSERT_EQ_I(ray_col_save(a, ray_test_tmp(CS_TMP "/h1")), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(b, ray_test_tmp(CS_TMP "/h2")), RAY_OK); + TEST_ASSERT_TRUE(same_file_from(ray_test_tmp(CS_TMP "/h1"), ray_test_tmp(CS_TMP "/h2"), 0)); + size_t n; uint8_t* p = slurp(ray_test_tmp(CS_TMP "/h1"), &n); + TEST_ASSERT_TRUE(p && n >= 32); + static const uint8_t zero[8]; + TEST_ASSERT_TRUE(memcmp(p + 8, zero, 8) == 0); + free(p); + ray_t* back = ray_col_load(ray_test_tmp(CS_TMP "/h1")); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back) && back->len == 5000); + for (int64_t i = 0; i < 5000; i++) { + size_t la, lb; const char* x = ray_str_vec_get(a, i, &la); const char* y = ray_str_vec_get(back, i, &lb); + TEST_ASSERT_TRUE(la == lb && (la == 0 || memcmp(x, y, la) == 0)); + } + ray_release(back); ray_release(a); ray_release(b); + PASS(); +} + +/* Parquet: one options dict per call. */ +static test_result_t test_parquet_two_dicts(void) { + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.parquet.splayed {compress: true} {compress: true} \"test/data/parquet/flat-0-v1.parquet\" \"" CS_TMP "/p2d\")")), "domain"); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.parquet.parted {compress: true} {rows: 2} \"test/data/parquet/flat-0-v1.parquet\" \"" CS_TMP "/p2p\" 't)")), "domain"); + PASS(); +} + +static test_result_t test_csv_splayed_option(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['a 's] (list [1 2 3 4] [\"alpha\" \"a much longer value\" \"\" \"x\"])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.write t \"" CS_TMP "/in.csv\")")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.splayed {compress: true} [I64 STR] \"" CS_TMP "/in.csv\" \"" CS_TMP "/cs\")")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/cs"), "a"), 2); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/cs"), "s"), 2); + ray_t* r = ray_eval_str(ray_test_tmp("(at (.db.splayed.get \"" CS_TMP "/cs\") 's)")); + ray_t* want = ray_eval_str("[\"alpha\" \"a much longer value\" \"\" \"x\"]"); + ray_t* fa = ray_fmt(r, 0); ray_t* fb = ray_fmt(want, 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + ray_release(fa); ray_release(fb); ray_release(r); ray_release(want); + /* absent over the generation-2 destination inherits it */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.splayed [I64 STR] \"" CS_TMP "/in.csv\" \"" CS_TMP "/cs\")")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/cs"), "a"), 2); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.splayed {compress: true} {compress: true} \"" CS_TMP "/in.csv\" \"" CS_TMP "/cs2\")")), "domain"); + PASS(); +} + +/* .csv.splayed {compress: true} with a SYMBOL column (nulls, several + * chunks) loads back equal to the generation-0 import. */ +static test_result_t test_csv_splayed_symbol(void) { + FILE* f = fopen(ray_test_tmp(CS_TMP "/sy.csv"), "w"); + TEST_ASSERT_TRUE(f != NULL); + fprintf(f, "a,s\n"); + for (int64_t i = 0; i < 140000; i++) { + if (i % 13 == 0) fprintf(f, "%lld,\n", (long long)i); + else fprintf(f, "%lld,k%lld\n", (long long)i, (long long)(i % 400)); + } + fclose(f); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.splayed {compress: true} [I64 SYMBOL] \"" CS_TMP "/sy.csv\" \"" CS_TMP "/sy2\")")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.csv.splayed {compress: false} [I64 SYMBOL] \"" CS_TMP "/sy.csv\" \"" CS_TMP "/sy0\")")), ""); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/sy2"), "s"), 2); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/sy2"), "a"), 2); + TEST_ASSERT_EQ_I(col_gen_in(ray_test_tmp(CS_TMP "/sy0"), "s"), 0); + ray_t* x = ray_eval_str(ray_test_tmp("(at (.db.splayed.get \"" CS_TMP "/sy2\") 's)")); + ray_t* y = ray_eval_str(ray_test_tmp("(at (.db.splayed.get \"" CS_TMP "/sy0\") 's)")); + TEST_ASSERT_TRUE(x && !RAY_IS_ERR(x) && y && !RAY_IS_ERR(y)); + TEST_ASSERT_EQ_I(x->len, 140000); TEST_ASSERT_EQ_I(y->len, 140000); + int64_t nulls = 0; + for (int64_t i = 0; i < 140000; i++) { + ray_t* s0 = ray_sym_vec_cell(y, i); ray_t* s1 = ray_sym_vec_cell(x, i); + TEST_ASSERT_TRUE(s0 && s1 && ray_str_len(s0) == ray_str_len(s1) && + memcmp(ray_str_ptr(s0), ray_str_ptr(s1), ray_str_len(s0)) == 0); + if (!ray_str_len(s1)) nulls++; + } + TEST_ASSERT_EQ_I(nulls, (140000 + 12) / 13); + ray_release(x); ray_release(y); + PASS(); +} + +static test_result_t test_parquet_option(void) { + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.parquet.splayed {compress: true} \"test/data/parquet/flat-0-v1.parquet\" \"" CS_TMP "/pq\")")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.parquet.splayed \"test/data/parquet/flat-0-v1.parquet\" \"" CS_TMP "/pq0\")")), ""); + ray_t* a = ray_eval_str(ray_test_tmp("(.db.splayed.get \"" CS_TMP "/pq\")")); + ray_t* b = ray_eval_str(ray_test_tmp("(.db.splayed.get \"" CS_TMP "/pq0\")")); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && b && !RAY_IS_ERR(b)); + for (int64_t c = 0; c < ray_table_ncols(a); c++) { + ray_t* nm = ray_sym_str(ray_table_col_name(a, c)); + char cn[256]; snprintf(cn, sizeof cn, "%.*s", (int)ray_str_len(nm), ray_str_ptr(nm)); + ray_col_meta_t m; ray_table_col_meta_idx(a, c, &m); + uint8_t want = (m.type >= RAY_BOOL && m.type <= RAY_STR) ? 2 : 0; + TEST_ASSERT_FMT(col_gen_in(ray_test_tmp(CS_TMP "/pq"), cn) == want, "column %s", cn); + TEST_ASSERT_FMT(col_gen_in(ray_test_tmp(CS_TMP "/pq0"), cn) == 0, "column %s (absent)", cn); + } + ray_t* fa = ray_fmt(a, 0); ray_t* fb = ray_fmt(b, 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + ray_release(fa); ray_release(fb); ray_release(a); ray_release(b); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.parquet.parted {compress: true rows: 2} \"test/data/parquet/flat-0-v1.parquet\" \"" CS_TMP "/pqp\" 't)")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.parquet.splayed {compress: 1} \"test/data/parquet/flat-0-v1.parquet\" \"" CS_TMP "/pq2\")")), "domain"); + PASS(); +} + +/* A loaded table whose three columns are generation 2. */ +static ray_t* gen2_tbl3(void) { + ray_t* t = ray_table_new(3); + ray_t* k = i64_col(5000, 1); + ray_t* v = ray_vec_new(RAY_F64, 5000); v->len = 5000; + for (int i = 0; i < 5000; i++) ((double*)ray_data(v))[i] = i * 0.5; + ray_t* s = ray_vec_new(RAY_STR, 5000); + for (int i = 0; i < 5000; i++) s = ray_str_vec_append(s, (i & 1) ? "odd value text" : "ev", (i & 1) ? 14 : 2); + t = ray_table_add_col(t, ray_sym_intern("k", 1), k); + t = ray_table_add_col(t, ray_sym_intern("v", 1), v); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + ray_release(k); ray_release(v); ray_release(s); + ray_err_t e = ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/plan"), NULL, RAY_COMPRESS_ON); + ray_release(t); + if (e != RAY_OK) return ray_error("io", "save failed"); + return ray_read_splayed(ray_test_tmp(CS_TMP "/plan"), NULL); +} + +static test_result_t test_planning_never_materializes(void) { + ray_t* t = gen2_tbl3(); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_enc_counters_reset(); + ray_graph_t* g = ray_graph_new(t); + ray_op_t* keys[] = { ray_scan(g, "k") }; + ray_op_t* val = ray_scan(g, "v"); + ray_op_t* ins[] = { val }; + uint16_t ops[] = { OP_SUM }; + ray_op_t* grp = ray_group(g, keys, 1, ops, ins, 1); + (void)agg_v2_admission(g, grp, t); + ray_op_t* p = ray_gt(g, ray_scan(g, "k"), ray_const_i64(g, 5)); + (void)ray_optimize(g, p); + ray_t* e1 = ray_parse("(> k 5)"); + ray_t* e2 = ray_parse("(like s \"odd*\")"); + ray_t* e3 = ray_parse("(in k [1 2 3])"); + (void)ray_fused_group_supported(e1, t); + (void)ray_fused_group_supported(e2, t); + (void)ray_fused_group_supported(e3, t); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_EQ_U(c.materialized, 0); + TEST_ASSERT_EQ_U(c.decoded_bytes, 0); + ray_release(e1); ray_release(e2); ray_release(e3); + ray_graph_free(g); + ray_release(t); + PASS(); +} + +static test_result_t test_exec_start_snapshot(void) { + ray_t* t = gen2_tbl3(); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_enc_counters_reset(); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_EQ_U(c.at_first_exec, UINT64_MAX); + ray_graph_t* g = ray_graph_new(t); + ray_op_t* s = ray_scan(g, "k"); + ray_t* out = ray_execute(g, s); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out)); + ray_enc_counters_get(&c); + TEST_ASSERT_EQ_U(c.at_first_exec, 0); /* nothing before execution */ + ray_release(out); ray_graph_free(g); ray_release(t); + PASS(); +} + +/* first (asc v) over a parted column with a null must not become OP_MIN + * (MIN skips nulls; asc puts them first). The wrapper's own attrs are + * always 0, so the check reads the segments' null flags. */ +static int first_asc_stays(ray_t* t, const char* col) { + ray_graph_t* g = ray_graph_new(t); + ray_op_t* f = ray_first(g, ray_asc_op(g, ray_scan(g, col))); + ray_op_t* r = ray_optimize(g, f); + int stays = r && r->opcode != OP_MIN; + ray_graph_free(g); + return stays; +} + +static test_result_t test_first_asc_parted_nulls_gen0(void) { + ray_t* s0 = i64_col(5, 1); ray_t* s1 = i64_col(5, 1); + ray_vec_set_null(s1, 2, true); + ray_t* w = ray_alloc(2 * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + RAY_I64; w->len = 2; w->attrs = 0; + memset(w->aux, 0, 16); + ((ray_t**)ray_data(w))[0] = s0; ((ray_t**)ray_data(w))[1] = s1; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("p", 1), w); + ray_release(w); + TEST_ASSERT_TRUE(first_asc_stays(t, "p")); + /* without a null the rewrite is still taken */ + ray_vec_set_null(s1, 2, false); + s1->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + TEST_ASSERT_FALSE(first_asc_stays(t, "p")); + ray_release(t); + PASS(); +} + +/* A text segment: SYM ids or STR cells; `null_at` >= 0 holds the null (id + * 0, the empty string) there. */ +static ray_t* text_seg(int8_t ty, int64_t n, int64_t null_at) { + static const char* const w[3] = { "aa", "bb", "cc" }; + if (ty == RAY_SYM) { + ray_t* v = ray_sym_vec_new(RAY_SYM_W64, n); v->len = n; + for (int64_t i = 0; i < n; i++) + ((int64_t*)ray_data(v))[i] = i == null_at ? 0 : ray_sym_intern(w[i % 3], 2); + return v; + } + ray_t* v = ray_vec_new(RAY_STR, n); + for (int64_t i = 0; i < n; i++) + v = i == null_at ? ray_str_vec_append(v, "", 0) : ray_str_vec_append(v, w[i % 3], 2); + /* the in-band null alone: appending "" sets the flag, which a segment + * need not carry (SYM ids never do), and the flag would answer for it */ + v->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + return v; +} + +/* (first (asc p)) takes the same route over a parted SYM/STR column as over + * the flat column with the same cells: text nulls are in-band (no flag), so + * the parted check reads each plain segment's payload. */ +static test_result_t test_first_asc_parted_text_nulls(void) { + static const int8_t tys[2] = { RAY_SYM, RAY_STR }; + for (int ti = 0; ti < 2; ti++) { + for (int with_null = 0; with_null < 2; with_null++) { + ray_t* s0 = text_seg(tys[ti], 5, -1); + ray_t* s1 = text_seg(tys[ti], 5, with_null ? 2 : -1); + ray_t* w = ray_alloc(2 * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + tys[ti]; w->len = 2; w->attrs = 0; + memset(w->aux, 0, 16); + ((ray_t**)ray_data(w))[0] = s0; ((ray_t**)ray_data(w))[1] = s1; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("p", 1), w); + ray_release(w); + ray_t* fl = text_seg(tys[ti], 10, with_null ? 7 : -1); /* the same cells, flat */ + ray_t* tf = ray_table_new(1); + tf = ray_table_add_col(tf, ray_sym_intern("p", 1), fl); + ray_release(fl); + bool has = ray_table_col_has_nulls(t, ray_sym_intern("p", 1)); + /* the answer is cached on the wrapper: later calls scan nothing */ + bool cached = (ray_table_slot(t, ray_sym_intern("p", 1))->aux[0] & 0x01) != 0; + bool again = ray_table_col_has_nulls(t, ray_sym_intern("p", 1)); + int parted = first_asc_stays(t, "p"), flat = first_asc_stays(tf, "p"); + ray_release(t); ray_release(tf); + TEST_ASSERT_FMT(has == (bool)with_null, "type %d null %d: has_nulls %d", tys[ti], with_null, has); + TEST_ASSERT_FMT(cached && again == has, "type %d null %d: cached %d", tys[ti], with_null, cached); + TEST_ASSERT_FMT(parted == flat, "type %d null %d: parted route %d, flat %d", tys[ti], with_null, parted, flat); + } + } + PASS(); +} + +/* A parted STR column whose generation-0 segment holds the null beside a + * generation-2 segment: the encoded wrapper reports it too. */ +static void write_str_part(const char* day, int gen, bool with_null) { + char dir[256], p[300]; + snprintf(dir, sizeof dir, "%s/pdt/%s/tb", ray_test_tmp(CS_TMP), day); + (void)ray_test_mkdir_p(dir); + ray_t* a = text_seg(RAY_STR, 3000, with_null ? 7 : -1); + snprintf(p, sizeof p, "%s/a", dir); ray_col_save_gen(a, p, gen); + ray_release(a); + ray_t* names = ray_vec_new(RAY_STR, 1); names = ray_str_vec_append(names, "a", 1); + snprintf(p, sizeof p, "%s/.d", dir); ray_col_save(names, p); ray_release(names); +} + +static test_result_t test_parted_text_nulls_mixed_gen(void) { + for (int pass = 0; pass < 2; pass++) { + (void)ray_test_rm_rf(ray_test_tmp(CS_TMP "/pdt")); + write_str_part("2024.01.01", 0, pass == 0); + write_str_part("2024.01.02", 2, false); + ray_t* t = ray_read_parted(ray_test_tmp(CS_TMP "/pdt"), "tb"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_TRUE(ray_table_get_col_enc(t, ray_sym_intern("a", 1)) != NULL); /* the encoded wrapper */ + bool has = ray_table_col_has_nulls(t, ray_sym_intern("a", 1)); + ray_release(t); + TEST_ASSERT_EQ_I(has, pass == 0); + } + PASS(); +} + +static void write_null_part(const char* day, int gen, bool with_null) { + char dir[256], p[300]; + snprintf(dir, sizeof dir, "%s/pdb/%s/tb", ray_test_tmp(CS_TMP), day); + (void)ray_test_mkdir_p(dir); + ray_t* a = i64_col(3000, 3); + if (with_null) ray_vec_set_null(a, 7, true); + snprintf(p, sizeof p, "%s/a", dir); ray_col_save_gen(a, p, gen); + ray_release(a); + ray_t* names = ray_vec_new(RAY_STR, 1); names = ray_str_vec_append(names, "a", 1); + snprintf(p, sizeof p, "%s/.d", dir); ray_col_save(names, p); ray_release(names); +} + +static test_result_t test_first_asc_parted_nulls_gen2(void) { + for (int pass = 0; pass < 2; pass++) { + (void)ray_test_rm_rf(ray_test_tmp(CS_TMP "/pdb")); + write_null_part("2024.01.01", 2, pass == 0); + write_null_part("2024.01.02", 2, false); + ray_t* t = ray_read_parted(ray_test_tmp(CS_TMP "/pdb"), "tb"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(first_asc_stays(t, "a"), pass == 0); + ray_release(t); + } + PASS(); +} + +/* Binding never decodes; literal translation reads the bound domain; the + * plain column is produced only on request; the graph releases its binds. */ +static test_result_t test_bind_stage(void) { + ray_t* t = ray_table_new(1); + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, 3000); s->len = 3000; + int64_t ids[3] = { ray_sym_intern("x", 1), ray_sym_intern("y", 1), ray_sym_intern("z", 1) }; + for (int i = 0; i < 3000; i++) ((int64_t*)ray_data(s))[i] = ids[i % 3]; + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + ray_release(s); + ray_err_t se = ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/bd"), ray_test_tmp(CS_TMP "/bd.sym"), RAY_COMPRESS_ON); + ray_release(t); + TEST_ASSERT_EQ_I(se, RAY_OK); + t = ray_read_splayed(ray_test_tmp(CS_TMP "/bd"), ray_test_tmp(CS_TMP "/bd.sym")); + ray_enc_counters_reset(); + ray_graph_t* g = ray_graph_new(t); + ray_t* err = NULL; + ray_col_src_t* a = ray_graph_bind_col(g, t, ray_sym_intern("s", 1), &err); + bool dedup = a && ray_graph_bind_col(g, t, ray_sym_intern("s", 1), &err) == a; + bool absent = ray_graph_bind_col(g, t, ray_sym_intern("nope", 4), &err) == NULL && !err; + int64_t py = -1, pabs = 0, dc = 0; + bool file_dom = false, ty_ok = false; + if (a) { + ty_ok = a->type == RAY_SYM; + file_dom = a->dom != ray_sym_runtime_domain(); + py = ray_col_src_sym_find(a, "y", 1); + pabs = ray_col_src_sym_find(a, "absent", 6); + dc = ray_col_src_dict_code(a, "y", 1); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + uint64_t mat_before = k.materialized; + ray_t* plain = NULL; + ray_t* perr = a ? ray_col_src_plain(a, &plain) : NULL; + int64_t cell1 = (plain && plain->type == RAY_SYM) ? ray_read_sym(ray_data(plain), 1, RAY_SYM, plain->attrs) : -9; + ray_enc_counters_get(&k); + uint32_t nb = ray_graph_binds_count(g); + ray_graph_free(g); /* releases the bind (ASan) */ + ray_release(t); + TEST_ASSERT_TRUE(a && !err && dedup && absent && ty_ok); + TEST_ASSERT_TRUE(file_dom); /* the file domain */ + TEST_ASSERT_TRUE(py > 0); + TEST_ASSERT_EQ_I(pabs, -1); + TEST_ASSERT_EQ_I(dc, -2); + TEST_ASSERT_EQ_U(mat_before, 0); /* bind and literal translation never decode */ + TEST_ASSERT_NULL(perr); + TEST_ASSERT_EQ_I(cell1, py); + TEST_ASSERT_EQ_U(k.materialized, 1); + TEST_ASSERT_EQ_I(nb, 1); + PASS(); +} + + +/* A bind is keyed by the table's address and name; a column replaced under the + * same table (or a table released and reallocated at that address) must not + * return the old binding. The replacement is made in the slot list itself. */ +static test_result_t test_bind_dedup_validates(void) { + int64_t sa = ray_sym_intern("a", 1); + ray_t* c1 = ray_vec_new(RAY_I64, 4); c1->len = 4; + for (int i = 0; i < 4; i++) ((int64_t*)ray_data(c1))[i] = i; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, sa, c1); + ray_release(c1); + ray_graph_t* g = ray_graph_new(t); + ray_t* err = NULL; + ray_col_src_t* s1 = ray_graph_bind_col(g, t, sa, &err); + TEST_ASSERT_TRUE(s1 && !err); + TEST_ASSERT_TRUE(ray_graph_bind_col(g, t, sa, &err) == s1); /* same column: the same binding */ + ray_t* o1 = s1->obj; + ray_t* c2 = ray_vec_new(RAY_I64, 4); c2->len = 4; + for (int i = 0; i < 4; i++) ((int64_t*)ray_data(c2))[i] = 100 + i; + ray_t* cols = ((ray_t**)ray_data(t))[1]; + ray_t* old = ((ray_t**)ray_data(cols))[0]; + ((ray_t**)ray_data(cols))[0] = c2; /* takes the reference */ + ray_release(old); + ray_col_src_t* s2 = ray_graph_bind_col(g, t, sa, &err); + TEST_ASSERT_TRUE(s2 && !err && s2 != s1); + ray_t* plain = NULL; + TEST_ASSERT_NULL(ray_col_src_plain(s2, &plain)); + TEST_ASSERT_TRUE(s2->obj != o1 && s2->obj == c2 && ((int64_t*)ray_data(plain))[0] == 100); + TEST_ASSERT_EQ_I(ray_graph_binds_count(g), 2); + ray_graph_free(g); + ray_release(t); + PASS(); +} + +/* The predicate fixture: 3000 rows of row id, a SYM, an I64 and an F64 with + * nulls, saved at generation 0 and 2 under CS_TMP "/0" and "2". */ +enum { FQ_N = 3000 }; +static ray_t* fq_table(void) { + ray_t* t = ray_table_new(5); + ray_t* w = ray_vec_new(RAY_I64, FQ_N); w->len = FQ_N; + for (int i = 0; i < FQ_N; i++) ((int64_t*)ray_data(w))[i] = i % 13; + ray_t* id = ray_vec_new(RAY_I64, FQ_N); id->len = FQ_N; + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, FQ_N); s->len = FQ_N; + ray_t* v = ray_vec_new(RAY_I64, FQ_N); v->len = FQ_N; + ray_t* d = ray_vec_new(RAY_F64, FQ_N); d->len = FQ_N; + const char* names[4] = { "alpha", "beta", "gamma", "alps" }; + for (int i = 0; i < FQ_N; i++) { + ((int64_t*)ray_data(id))[i] = i; + ((int64_t*)ray_data(s))[i] = ray_sym_intern(names[i % 4], strlen(names[i % 4])); + ((int64_t*)ray_data(v))[i] = i % 17; + ((double*)ray_data(d))[i] = (double)(i % 11) * 0.5; + } + for (int i = 0; i < FQ_N; i += 7) { ray_vec_set_null(v, i, true); ray_vec_set_null(d, i, true); } + t = ray_table_add_col(t, ray_sym_intern("i", 1), id); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + t = ray_table_add_col(t, ray_sym_intern("v", 1), v); + t = ray_table_add_col(t, ray_sym_intern("d", 1), d); + t = ray_table_add_col(t, ray_sym_intern("w", 1), w); + ray_release(id); ray_release(s); ray_release(v); ray_release(d); ray_release(w); + return t; +} + +static bool fq_save(const char* name) { + char d0[128], d2[128], s0[136], s2[136]; + snprintf(d0, sizeof d0, "%s/%s0", ray_test_tmp(CS_TMP), name); snprintf(s0, sizeof s0, "%s.sym", d0); + snprintf(d2, sizeof d2, "%s/%s2", ray_test_tmp(CS_TMP), name); snprintf(s2, sizeof s2, "%s.sym", d2); + ray_t* t = fq_table(); + bool ok = ray_splay_save_mode(t, d0, s0, RAY_COMPRESS_OFF) == RAY_OK && + ray_splay_save_mode(t, d2, s2, RAY_COMPRESS_ON) == RAY_OK; + ray_release(t); + return ok; +} + +static ray_t* fq_run(const char* name, int gen, const char* where, const char* tail) { + char q[512]; + snprintf(q, sizeof q, "(select {i:i v:v d:d from: (.db.splayed.get \"%s/%s%d\" \"%s/%s%d.sym\") where: %s %s})", + ray_test_tmp(CS_TMP), name, gen, ray_test_tmp(CS_TMP), name, gen, where, tail); + return ray_eval_str(q); +} + +/* Same columns, same bytes (SYM is not projected: row ids pin the rows). */ +static bool fq_same(ray_t* a, ray_t* b, int64_t want_rows) { + if (!a || !b || RAY_IS_ERR(a) || RAY_IS_ERR(b)) return false; + static const char* const cols[] = { "i", "v", "d" }; + for (int c = 0; c < 3; c++) { + ray_t* x = ray_table_get_col(a, ray_sym_intern(cols[c], 1)); + ray_t* y = ray_table_get_col(b, ray_sym_intern(cols[c], 1)); + if (!x || !y || x->len != y->len || x->len != want_rows) return false; + if (memcmp(ray_data(x), ray_data(y), (size_t)x->len * 8) != 0) return false; + } + return true; +} + +/* Fused take and fused top-k, through select with take:, on generation 0 + * and generation 2: the fused path compiled the predicate on both (never + * declined) and the full results are identical. */ +static test_result_t test_fused_pred_bound(void) { + TEST_ASSERT_TRUE(fq_save("fb")); + static const char* const w[] = { + "(== s 'beta)", "(!= s 'beta)", "(== s 'nowhere)", "(!= s 'nowhere)", + "(in w [1 2 3])", "(like s \"alp*\")", "(like s \"*mm*\")", + "(> v 5)", "(<= v 3)", "(== v 4)", "(!= v 4)", "(< d 2.0)", "(>= d 1.5)", + "(and (== s 'alpha) (> v 5))", + }; + static const char* const tails[] = { "take: 10", "desc: i take: 10" }; + for (size_t i = 0; i < sizeof w / sizeof *w; i++) + for (int m = 0; m < 2; m++) { + ray_fused_topk_counters_reset(); + ray_t* a = fq_run("fb", 0, w[i], tails[m]); + ray_t* b = fq_run("fb", 2, w[i], tails[m]); + uint64_t ran, dec; ray_fused_topk_counters(&ran, &dec); + int64_t rows = (a && !RAY_IS_ERR(a)) ? ray_table_nrows(a) : -1; + bool same = fq_same(a, b, rows); + bool absent = strstr(w[i], "nowhere") && strstr(w[i], "=="); + bool ok = same && ran == 2 && dec == 0 && (absent ? rows == 0 : rows == 10); + if (!ok) fprintf(stderr, "fused_pred_bound: %s %s rows=%lld same=%d ran=%llu declined=%llu\n", + w[i], tails[m], (long long)rows, same, (unsigned long long)ran, (unsigned long long)dec); + if (a) ray_release(a); + if (b) ray_release(b); + TEST_ASSERT_TRUE(ok); + } + PASS(); +} + +/* The compiled predicate over bound encoded sources (no query-entry decode) + * selects the same rows as over generation 0. */ +static test_result_t test_fused_pred_enc_source(void) { + TEST_ASSERT_TRUE(fq_save("fe")); + static const char* const w[] = { + "(== s 'beta)", "(!= s 'nowhere)", "(in w [1 2 3])", "(like s \"alp*\")", + "(> v 5)", "(== v 4)", "(< d 2.0)", "(and (== s 'alpha) (> v 5))", + }; + ray_t* t0 = ray_read_splayed(ray_test_tmp(CS_TMP "/fe0"), ray_test_tmp(CS_TMP "/fe0.sym")); + ray_t* t2 = ray_read_splayed(ray_test_tmp(CS_TMP "/fe2"), ray_test_tmp(CS_TMP "/fe2.sym")); + TEST_ASSERT_TRUE(t0 && t2); + ray_enc_counters_reset(); + for (size_t i = 0; i < sizeof w / sizeof *w; i++) { + uint8_t* bits[2] = { ray_alloc_raw(FQ_N + 64), ray_alloc_raw(FQ_N + 64) }; + ray_t* tb[2] = { t0, t2 }; + int rc[2] = { 0, 0 }; + bool rerr = false; + for (int g = 0; g < 2; g++) { + ray_graph_t* gr = ray_graph_new(tb[g]); + ray_t* e = ray_parse(w[i]); + ray_op_t* dag = compile_expr_dag(gr, e); + fp_pred_t p; ray_t* err = NULL; + rc[g] = dag ? fp_compile_pred(gr, dag, tb[g], &p, &err) : -1; + if (err) { ray_error_free(err); rc[g] = -2; } + memset(bits[g], 0, FQ_N + 64); + if (rc[g] == 0) { /* encoded children read by range */ + fp_scratch_t sc; fp_scratch_init(&sc); + for (int64_t st = 0; st < FQ_N && !rerr; st += 1024) { + ray_t* ee = fp_eval_pred_rs(&p, st, st + 1024 < FQ_N ? st + 1024 : FQ_N, bits[g] + st, &sc); + if (ee) { ray_error_free(ee); rerr = true; } + } + fp_scratch_free(&sc); + fp_pred_cleanup(&p); + } + ray_release(e); + ray_graph_free(gr); + } + bool same = rc[0] == 0 && rc[1] == 0 && !rerr && memcmp(bits[0], bits[1], FQ_N) == 0; + bool any = false; + for (int r = 0; r < FQ_N; r++) if (bits[0][r]) { any = true; break; } + ray_free_raw(bits[0]); ray_free_raw(bits[1]); + if (!same || !any) fprintf(stderr, "fused_pred_enc_source: %s rc=%d,%d any=%d\n", w[i], rc[0], rc[1], any); + if (!(same && any)) { ray_release(t0); ray_release(t2); } + TEST_ASSERT_TRUE(same && any); + } + ray_release(t0); ray_release(t2); + PASS(); +} + +/* A bind failure reaches the query as its error; a bound encoded column + * compiles without a decode (a failed range read is the scan's error, + * scanrange/topk_take_error); a decline stays a decline. */ +static test_result_t test_fused_pred_bind_failure(void) { + TEST_ASSERT_TRUE(fq_save("ff")); + ray_fused_topk_counters_reset(); + ray_graph_bind_test_fail_alloc(1); + ray_t* r = fq_run("ff", 0, "(> v 5)", "take: 10"); + ray_graph_bind_test_fail_alloc(0); + bool is_err = r && RAY_IS_ERR(r); + bool code_ok = is_err && strcmp(ray_err_code(r), "oom") == 0; + bool msg_ok = is_err && ray_error_msg() && strstr(ray_error_msg(), "column bind"); + if (is_err) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_TRUE(is_err && code_ok && msg_ok); + /* the same through the top-k executor */ + ray_graph_bind_test_fail_alloc(1); + r = fq_run("ff", 0, "(> v 5)", "desc: i take: 10"); + ray_graph_bind_test_fail_alloc(0); + is_err = r && RAY_IS_ERR(r); + if (is_err) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_TRUE(is_err); + /* after the injection the query answers normally */ + r = fq_run("ff", 0, "(> v 5)", "take: 10"); + bool ok = r && !RAY_IS_ERR(r) && ray_table_nrows(r) == 10; + if (r && !RAY_IS_ERR(r)) ray_release(r); + TEST_ASSERT_TRUE(ok); + + /* a bound encoded column: compiling decodes nothing (the child reads by + * range), so an injected decode failure is not reached */ + ray_t* t2 = ray_read_splayed(ray_test_tmp(CS_TMP "/ff2"), ray_test_tmp(CS_TMP "/ff2.sym")); + TEST_ASSERT_TRUE(t2 && !RAY_IS_ERR(t2)); + ray_graph_t* gr = ray_graph_new(t2); + ray_op_t* dag = ray_gt(gr, ray_scan(gr, "v"), ray_const_i64(gr, 5)); /* no column lookup: nothing decoded yet */ + fp_pred_t p; ray_t* err = NULL; + ray_enccol_test_fail_alloc(1); + int rc = dag ? fp_compile_pred(gr, dag, t2, &p, &err) : -1; + bool compiled = rc == 0 && !err && p.n_children == 1 && p.children[0].enc; + ray_enccol_test_fail_alloc(0); + if (rc == 0) fp_pred_cleanup(&p); + if (err) ray_error_free(err); + ray_graph_free(gr); + ray_t* e; + /* an unsupported leaf declines without an error */ + gr = ray_graph_new(t2); + e = ray_parse("(== nosuchcol 1)"); + dag = compile_expr_dag(gr, e); + err = NULL; + int rc2 = dag ? fp_compile_pred(gr, dag, t2, &p, &err) : -1; + bool decline = rc2 != 0 && err == NULL; + if (rc2 == 0) fp_pred_cleanup(&p); + ray_release(e); + ray_graph_free(gr); + ray_release(t2); + TEST_ASSERT_TRUE(compiled); + TEST_ASSERT_TRUE(decline); + PASS(); +} + +/* ---- Task 20: expression, aggregate and top-k compilation from bound sources ---- + * + * Query-level checks go through select, which still decodes at its entry + * (transitional: Tasks 30-32 remove it), so select sees plain columns. The + * direct-compile checks below bind a table read from generation-2 files (its + * slots are RAY_ENCCOL), which is where the converted sites read encoded + * sources. */ + +/* Same formatted output. */ +static bool cp_fmt_same(ray_t* x, ray_t* y) { + if (!x || !y || RAY_IS_ERR(x) || RAY_IS_ERR(y)) return false; + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); + bool same = fx && fy && ray_str_len(fx) == ray_str_len(fy) && + memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0; + if (fx) ray_release(fx); + if (fy) ray_release(fy); + return same; +} + +/* An injected bind failure arrives as the oom "column bind" error. */ +static bool cp_is_bind_error(ray_t* r) { + if (!r || !RAY_IS_ERR(r)) return false; + bool ok = strcmp(ray_err_code(r), "oom") == 0 && ray_error_msg() && strstr(ray_error_msg(), "column bind"); + return ok; +} + +/* Brief: group-by with sum / avg over an expression and top-k over a + * generation-2 table equal the generation-0 answers. The compiled paths + * ran (expression compiles counted, fused top-k executions counted). */ +static test_result_t test_compile_paths_bound(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 'v 'w] (list (take [1 2 3] 3000) (til 3000) (* 2 (til 3000)))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/cp2\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/cp0\" t {compress: false})")), ""); + static const char* const q[] = { + "(select {s: (sum (+ v w)) a: (avg (* 3 v)) from: (.db.splayed.get \"%s\") by: k})", + "(select {from: (.db.splayed.get \"%s\") where: (> v 10) desc: v take: 5})", + "(select {from: (.db.splayed.get \"%s\") where: (< w 100) take: 3})", + NULL, + }; + for (int i = 0; q[i]; i++) { + char a2[512], a0[512]; + snprintf(a2, sizeof a2, q[i], ray_test_tmp(CS_TMP "/cp2")); + snprintf(a0, sizeof a0, q[i], ray_test_tmp(CS_TMP "/cp0")); + uint64_t ok0 = ray_expr_compile_ok, ran0, dec0, ran1, dec1; + ray_fused_topk_counters(&ran0, &dec0); + ray_t* x = ray_eval_str(a2); ray_t* y = ray_eval_str(a0); + ray_fused_topk_counters(&ran1, &dec1); + TEST_ASSERT_FMT(x && y && !RAY_IS_ERR(x) && !RAY_IS_ERR(y), "query %d", i); + TEST_ASSERT_FMT(cp_fmt_same(x, y), "query %d differs", i); + if (i == 0) TEST_ASSERT_FMT(ray_expr_compile_ok >= ok0 + 2, "query %d: expression compiled on both", i); + else TEST_ASSERT_FMT(ran1 >= ran0 + 2, "query %d: fused top-k ran on both (ran %llu->%llu)", i, + (unsigned long long)ran0, (unsigned long long)ran1); + ray_release(x); ray_release(y); + } + /* A failed bind anywhere in the group-by planners (expression inputs, the + * linear / affine plans) is the query's error, never a silent fallback. */ + static const char* const qb[] = { + "(select {s: (sum (+ v w)) a: (avg (* 3 v)) from: (.db.splayed.get \"%s\") by: k})", + "(select {s: (sum (+ (* 2 v) w)) from: (.db.splayed.get \"%s\")})", + "(select {s: (sum (+ v 1)) a: (avg (- w 2)) from: (.db.splayed.get \"%s\") by: k})", + NULL, + }; + for (int i = 0; qb[i]; i++) { + char a0[512]; + snprintf(a0, sizeof a0, qb[i], ray_test_tmp(CS_TMP "/cp0")); + int n = 1; + for (; n < 20; n++) { + ray_graph_bind_test_fail_alloc(n); + ray_t* r = ray_eval_str(a0); + ray_graph_bind_test_fail_alloc(0); + bool is_err = r && RAY_IS_ERR(r); + bool be = cp_is_bind_error(r); + if (is_err) ray_error_free(r); else if (r) ray_release(r); + if (!is_err) break; + TEST_ASSERT_FMT(be, "query %d bind %d: not the bind error", i, n); + } + /* v and w, each failing in turn, and the group key k (P2 Task 13: + * the v2 engine binds its keys) */ + TEST_ASSERT_FMT(n - 1 == (i == 1 ? 2 : 3), "query %d: %d binds", i, n - 1); + } + PASS(); +} + + +static ray_t* cp_tiny(int64_t base) { + ray_t* t = ray_table_new(1); + ray_t* c = ray_vec_new(RAY_I64, 4); c->len = 4; + for (int i = 0; i < 4; i++) ((int64_t*)ray_data(c))[i] = base + i; + t = ray_table_add_col(t, ray_sym_intern("a", 1), c); + ray_release(c); + return t; +} + +/* A released temporary table's address is reused by another table with other + * columns: the bind must not return the first table's column. Tables of the + * same shape are built until the allocator hands back the freed address. */ +static test_result_t test_bind_address_reuse(void) { + int64_t sa = ray_sym_intern("a", 1); + ray_t* t1 = cp_tiny(0); + ray_t* host = cp_tiny(500); + ray_graph_t* g = ray_graph_new(host); + ray_t* err = NULL; + ray_col_src_t* s1 = ray_graph_bind_col(g, t1, sa, &err); + TEST_ASSERT_TRUE(s1 && !err); + ray_t* o1 = s1->obj; + ray_t* addr1 = t1; + ray_release(t1); /* released without ray_graph_unbind_table */ + ray_t* pile[256]; int np = 0; + ray_t* t2 = NULL; + while (np < 256 && !t2) { + pile[np] = cp_tiny(100); + if (pile[np] == addr1) t2 = pile[np]; + np++; + } + TEST_ASSERT_TRUE(t2 != NULL); /* the allocator reused the address */ + ray_col_src_t* s2 = ray_graph_bind_col(g, t2, sa, &err); + TEST_ASSERT_TRUE(s2 && !err && s2 != s1 && s2->obj != o1); + ray_t* plain = NULL; + TEST_ASSERT_NULL(ray_col_src_plain(s2, &plain)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(plain))[0], 100); + for (int i = 0; i < np; i++) ray_release(pile[i]); + ray_graph_free(g); + ray_release(host); + PASS(); +} + +/* Binds of a released temporary are dropped by ray_graph_unbind_table: the + * column memory goes back with the table, and a gen-0 group-by over an + * expression drops the binds of its synthetic sub-table with unchanged results. */ +static test_result_t test_unbind_releases_temporaries(void) { + int64_t sa = ray_sym_intern("a", 1); + enum { N = 1 << 17 }; + ray_t* host = cp_tiny(0); + ray_graph_t* g = ray_graph_new(host); + ray_mem_stats_t m0, m1, m2; + ray_err_t dummy = RAY_OK; (void)dummy; + ray_t* err = NULL; + ray_mem_stats(&m0); + /* unbound before the release: the column memory goes back with the table */ + ray_t* big = ray_vec_new(RAY_I64, N); big->len = N; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, sa, big); + ray_release(big); + TEST_ASSERT_TRUE(ray_graph_bind_col(g, t, sa, &err) && !err); + TEST_ASSERT_EQ_I(ray_graph_binds_count(g), 1); + ray_graph_unbind_table(g, t); + TEST_ASSERT_EQ_I(ray_graph_binds_count(g), 0); + ray_release(t); + ray_mem_stats(&m1); + TEST_ASSERT_TRUE(m1.bytes_allocated < m0.bytes_allocated + 4096); + /* released without unbinding: the bind keeps the column */ + big = ray_vec_new(RAY_I64, N); big->len = N; + t = ray_table_new(1); + t = ray_table_add_col(t, sa, big); + ray_release(big); + TEST_ASSERT_TRUE(ray_graph_bind_col(g, t, sa, &err) && !err); + ray_release(t); + ray_mem_stats(&m2); + TEST_ASSERT_TRUE(m2.bytes_allocated >= m0.bytes_allocated + (size_t)N * 8); + ray_graph_free(g); + ray_release(host); + + /* gen-0 group-by over an expression: the sub-table's binds are dropped */ + TEST_ASSERT_STR_EQ(ev_code("(set T (table ['k 'v 'w] (list (take [1 2 3] 200000) (til 200000) (* 2 (til 200000)))))"), ""); + const char* q = "(select {s: (sum (+ v w)) a: (avg (* 3 v)) from: T by: k})"; + uint64_t d0 = ray_graph_binds_dropped(); + ray_t* r = ray_eval_str(q); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_TRUE(ray_graph_binds_dropped() > d0); + TEST_ASSERT_EQ_I(ray_table_nrows(r), 3); + ray_t* s = ray_table_get_col(r, ray_sym_intern("s", 1)); + int64_t tot = 0; + for (int i = 0; i < 3; i++) tot += ((int64_t*)ray_data(s))[i]; + TEST_ASSERT_EQ_I(tot, 3 * ((int64_t)199999 * 200000 / 2)); /* sum of v + w = 3 * v */ + ray_release(r); + + /* gen-0 IF projection: each branch runs over its rows' compacted + * sub-table, whose binds are dropped with it; the memory is back after + * the query */ + ray_mem_stats(&m0); + d0 = ray_graph_binds_dropped(); + r = ray_eval_str("(select {x: (if (> v 100000) (+ v w) (- v w)) from: T})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_TRUE(ray_graph_binds_dropped() >= d0 + 2); /* both branches */ + TEST_ASSERT_EQ_I(ray_table_nrows(r), 200000); + ray_t* x = ray_table_get_col(r, ray_sym_intern("x", 1)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(x))[7], -7); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(x))[150000], 450000); + ray_release(r); + ray_mem_stats(&m1); + TEST_ASSERT_TRUE(m1.bytes_allocated < m0.bytes_allocated + 65536); + PASS(); +} + +/* The compile fixture: CP_N rows saved at generation 0 and 2 under + * CS_TMP "/cp0g" and "/cp2g". Group keys k0 (4 dense), k1 (4 sparse), + * k2 (8192 dense), k4 (all distinct); null-free I64 a, b; null-free F64 f, + * g with exactly representable sums; I64 v and SYM x with nulls; SYM y + * without. */ +enum { CP_N = 70000 }; +static ray_t* cp_table(void) { + ray_t* t = ray_table_new(11); + ray_t* c[11]; + int8_t ty[11] = { RAY_I64, RAY_I64, RAY_I64, RAY_I64, RAY_I64, RAY_I64, RAY_F64, RAY_F64, RAY_I64, RAY_SYM, RAY_SYM }; + static const char* const nm[11] = { "k0", "k1", "k2", "k4", "a", "b", "f", "g", "v", "x", "y" }; + for (int j = 0; j < 11; j++) { + c[j] = ty[j] == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W64, CP_N) : ray_vec_new(ty[j], CP_N); + c[j]->len = CP_N; + } + const char* ys[4] = { "ya", "yb", "yc", "yd" }; + const char* xs[3] = { "xa", "xb", "xc" }; + for (int64_t i = 0; i < CP_N; i++) { + ((int64_t*)ray_data(c[0]))[i] = i % 4; + ((int64_t*)ray_data(c[1]))[i] = (i % 4) * 1000000; + ((int64_t*)ray_data(c[2]))[i] = i % 8192; + ((int64_t*)ray_data(c[3]))[i] = i * 1000000; + ((int64_t*)ray_data(c[4]))[i] = i % 1000; + ((int64_t*)ray_data(c[5]))[i] = (i * 7) % 1000; + ((double*)ray_data(c[6]))[i] = (double)(i % 64) * 0.5; + ((double*)ray_data(c[7]))[i] = (double)(i % 32) * 0.25; + ((int64_t*)ray_data(c[8]))[i] = i % 17; + ((int64_t*)ray_data(c[9]))[i] = ray_sym_intern(xs[i % 3], 2); + ((int64_t*)ray_data(c[10]))[i] = ray_sym_intern(ys[i % 4], 2); + } + for (int64_t i = 0; i < CP_N; i += 9) { ray_vec_set_null(c[8], i, true); ray_vec_set_null(c[9], i, true); } + for (int j = 0; j < 11; j++) { t = ray_table_add_col(t, ray_sym_intern(nm[j], strlen(nm[j])), c[j]); ray_release(c[j]); } + return t; +} + +static bool cp_save(void) { + ray_t* t = cp_table(); + bool ok = ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/cp0g"), ray_test_tmp(CS_TMP "/cp0g.sym"), RAY_COMPRESS_OFF) == RAY_OK && + ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/cp2g"), ray_test_tmp(CS_TMP "/cp2g.sym"), RAY_COMPRESS_ON) == RAY_OK; + ray_release(t); + return ok; +} + +static ray_t* cp_read(int gen) { + return gen == 2 ? ray_read_splayed(ray_test_tmp(CS_TMP "/cp2g"), ray_test_tmp(CS_TMP "/cp2g.sym")) + : ray_read_splayed(ray_test_tmp(CS_TMP "/cp0g"), ray_test_tmp(CS_TMP "/cp0g.sym")); +} + +static ray_op_t* cp_dag(ray_graph_t* g, const char* src, ray_t** e) { + *e = ray_parse(src); + return *e ? compile_expr_dag(g, *e) : NULL; +} + +/* The three sum/avg planners over bound sources, generation 0 and 2: the + * plans read the right data, decline exactly as before, decode nothing on a + * decline, and report bind and plain failures through their error out. */ +static test_result_t test_try_plans_bound(void) { + TEST_ASSERT_TRUE(cp_save()); + for (int gen = 0; gen <= 2; gen += 2) { + ray_t* t = cp_read(gen); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_get_col_enc(t, ray_sym_intern("a", 1)) != NULL, gen == 2); + /* The DAG is built over the table itself: column presence is read from + * metadata, so building it decodes nothing (asserted below). */ + ray_graph_t* gr = ray_graph_new(t); + ray_t *e1, *e2, *e3, *e4, *e5, *e6, *e7, *e8; + ray_t* err = NULL; + + /* a decline decodes nothing: a nullable term, int x int, an unknown column */ + agg_linear_t lin; agg_prod_t prod; agg_affine_t aff; ray_t* vec = NULL; + ray_enc_counters_reset(); + ray_op_t* d_null = cp_dag(gr, "(+ (* 2 b) v)", &e1); + ray_op_t* d_ii = cp_dag(gr, "(* a b)", &e2); + ray_op_t* d_fv = cp_dag(gr, "(* f v)", &e3); + ray_op_t* d_lin = cp_dag(gr, "(+ (+ (* 2 b) a) 7)", &e4); + ray_op_t* d_fg = cp_dag(gr, "(* f g)", &e5); + ray_op_t* d_fa = cp_dag(gr, "(* f a)", &e6); + ray_op_t* d_af = cp_dag(gr, "(- f 1.5)", &e7); + ray_op_t* d_ai = cp_dag(gr, "(+ a 5)", &e8); + TEST_ASSERT_TRUE(d_null && d_ii && d_fv && d_lin && d_fg && d_fa && d_af && d_ai); + ray_enc_counters_t kb; ray_enc_counters_get(&kb); + TEST_ASSERT_EQ_U(kb.materialized, 0); /* DAG construction decodes nothing */ + ray_enc_counters_reset(); + TEST_ASSERT_FALSE(try_linear_sumavg_input_i64(gr, t, d_null, &lin, &err)); TEST_ASSERT_NULL(err); + TEST_ASSERT_FALSE(try_prod_sumavg_input_f64(gr, t, d_ii, &prod, &err)); TEST_ASSERT_NULL(err); + TEST_ASSERT_FALSE(try_prod_sumavg_input_f64(gr, t, d_fv, &prod, &err)); TEST_ASSERT_NULL(err); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_TRUE(ray_graph_binds_count(gr) >= 3); + + if (gen == 2) { + /* P2 Task 10: the linear and product plans read whole-column + * pointers, so encoded terms not yet materialized decline them + * (a shape decline: *err NULL, nothing decoded); the affine plan + * hands back the encoded object for the caller to bind. */ + TEST_ASSERT_FALSE(try_linear_sumavg_input_i64(gr, t, d_lin, &lin, &err)); TEST_ASSERT_NULL(err); + TEST_ASSERT_FALSE(try_prod_sumavg_input_f64(gr, t, d_fg, &prod, &err)); TEST_ASSERT_NULL(err); + TEST_ASSERT_FALSE(try_prod_sumavg_input_f64(gr, t, d_fa, &prod, &err)); TEST_ASSERT_NULL(err); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(d_af && try_affine_sumavg_input(gr, t, d_af, false, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(aff.enabled && aff.bias_f64 == -1.5 && vec && vec->type == RAY_ENCCOL); + TEST_ASSERT_TRUE(vec == ray_table_get_col_enc(t, ray_sym_intern("f", 1))); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(d_ai && try_affine_sumavg_input(gr, t, d_ai, false, &vec, &aff, &err)); + TEST_ASSERT_TRUE(aff.enabled && aff.bias_i64 == 5 && vec->type == RAY_ENCCOL); + ray_enc_counters_get(&k); TEST_ASSERT_EQ_U(k.materialized, 0); + /* a published materialization is a ready column: the plans take it */ + ray_t* fa = ray_table_col(t, ray_sym_intern("a", 1)); + ray_t* fb = ray_table_col(t, ray_sym_intern("b", 1)); + TEST_ASSERT_TRUE(fa && !RAY_IS_ERR(fa) && fb && !RAY_IS_ERR(fb)); + TEST_ASSERT_TRUE(try_linear_sumavg_input_i64(gr, t, d_lin, &lin, &err)); + TEST_ASSERT_TRUE(lin.term_ptrs[0] == ray_data(fb) || lin.term_ptrs[0] == ray_data(fa)); + ray_t* ff = ray_table_col(t, ray_sym_intern("f", 1)); + ray_t* fg = ray_table_col(t, ray_sym_intern("g", 1)); + TEST_ASSERT_TRUE(ff && !RAY_IS_ERR(ff) && fg && !RAY_IS_ERR(fg)); + TEST_ASSERT_TRUE(try_prod_sumavg_input_f64(gr, t, d_fg, &prod, &err)); TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(prod.pa == ray_data(ff) && prod.pb == ray_data(fg)); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(try_affine_sumavg_input(gr, t, d_af, false, &vec, &aff, &err)); TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(vec == ff && vec->type == RAY_F64 && aff.bias_f64 == -1.5); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(try_affine_sumavg_input(gr, t, d_ai, false, &vec, &aff, &err)); + TEST_ASSERT_TRUE(vec == fa && vec->type == RAY_I64 && ((const int64_t*)ray_data(vec))[1234] == 234); + } else { + /* linear: 2 * b + a + 7 */ + TEST_ASSERT_TRUE(d_lin && try_linear_sumavg_input_i64(gr, t, d_lin, &lin, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(lin.enabled && lin.n_terms == 2 && lin.bias_i64 == 7); + for (int64_t i = 0; i < CP_N; i += 997) { + int64_t sum = lin.bias_i64; + for (uint8_t j = 0; j < lin.n_terms; j++) sum += lin.coeff_i64[j] * ((const int64_t*)lin.term_ptrs[j])[i]; + TEST_ASSERT_EQ_I(sum, 2 * ((i * 7) % 1000) + (i % 1000) + 7); + } + /* product: f * g (F64 x F64) and f * a (F64 x I64) */ + TEST_ASSERT_TRUE(d_fg && try_prod_sumavg_input_f64(gr, t, d_fg, &prod, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(prod.enabled && prod.ta == RAY_F64 && prod.tb == RAY_F64); + for (int64_t i = 0; i < CP_N; i += 997) + TEST_ASSERT_TRUE(((const double*)prod.pa)[i] * ((const double*)prod.pb)[i] == (double)(i % 64) * 0.5 * ((double)(i % 32) * 0.25)); + TEST_ASSERT_TRUE(d_fa && try_prod_sumavg_input_f64(gr, t, d_fa, &prod, &err)); + TEST_ASSERT_TRUE(prod.ta == RAY_F64 && prod.tb == RAY_I64); + /* affine: f - 1.5, a + 5 */ + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(d_af && try_affine_sumavg_input(gr, t, d_af, false, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(aff.enabled && aff.bias_f64 == -1.5 && vec && vec->type == RAY_F64 && vec->len == CP_N); + TEST_ASSERT_TRUE(((const double*)ray_data(vec))[5] == 2.5); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(d_ai && try_affine_sumavg_input(gr, t, d_ai, false, &vec, &aff, &err)); + TEST_ASSERT_TRUE(aff.enabled && aff.bias_i64 == 5 && vec->type == RAY_I64 && ((const int64_t*)ray_data(vec))[1234] == 234); + } + + ray_release(e1); ray_release(e2); ray_release(e3); ray_release(e4); + ray_release(e5); ray_release(e6); ray_release(e7); ray_release(e8); + ray_graph_free(gr); + ray_release(t); + + /* a failed bind is the planner's error, not a decline */ + t = cp_read(gen); + gr = ray_graph_new(t); + ray_op_t* dl = cp_dag(gr, "(+ (* 2 b) a)", &e1); + ray_op_t* dp = cp_dag(gr, "(* f g)", &e2); + ray_op_t* da = cp_dag(gr, "(- f 1.5)", &e3); + TEST_ASSERT_TRUE(dl && dp && da); + ray_graph_bind_test_fail_alloc(1); + bool r = try_linear_sumavg_input_i64(gr, t, dl, &lin, &err); + ray_graph_bind_test_fail_alloc(0); + bool bind_err = !r && cp_is_bind_error(err); + if (err) ray_error_free(err); + err = NULL; + ray_graph_bind_test_fail_alloc(1); + r = try_prod_sumavg_input_f64(gr, t, dp, &prod, &err); + ray_graph_bind_test_fail_alloc(0); + bool bind_err2 = !r && cp_is_bind_error(err); + if (err) ray_error_free(err); + err = NULL; + ray_graph_bind_test_fail_alloc(1); + r = try_affine_sumavg_input(gr, t, da, false, &vec, &aff, &err); + ray_graph_bind_test_fail_alloc(0); + bool bind_err3 = !r && cp_is_bind_error(err); + if (err) ray_error_free(err); + err = NULL; + TEST_ASSERT_TRUE(bind_err && bind_err2 && bind_err3); + /* a failed materialization of a bound encoded column: the plans + * no longer request one (P2 Task 10: they decline, or hand back the + * encoded object), so the failure never fires */ + if (gen == 2) { + ray_enccol_test_fail_alloc(1); + r = try_linear_sumavg_input_i64(gr, t, dl, &lin, &err); + ray_enccol_test_fail_alloc(0); + bool plain_err = !r && err && RAY_IS_ERR(err); + if (err) ray_error_free(err); + err = NULL; + ray_enccol_test_fail_alloc(1); + r = try_prod_sumavg_input_f64(gr, t, dp, &prod, &err); + ray_enccol_test_fail_alloc(0); + bool plain_err2 = !r && err && RAY_IS_ERR(err); + if (err) ray_error_free(err); + err = NULL; + ray_enccol_test_fail_alloc(1); + memset(&aff, 0, sizeof aff); + r = try_affine_sumavg_input(gr, t, da, false, &vec, &aff, &err); + ray_enccol_test_fail_alloc(0); + bool plain_err3 = !r && err && RAY_IS_ERR(err); + if (err) ray_error_free(err); + TEST_ASSERT_TRUE(!plain_err && !plain_err2 && !plain_err3); + } + ray_release(e1); ray_release(e2); ray_release(e3); + ray_graph_free(gr); + ray_release(t); + } + PASS(); +} + +/* Run `body` with the nth bind failing, n = 1, 2, ...: every failure before + * the first success must be the bind error (never a decline or a silently + * different answer); returns how many binds the body makes. */ +typedef ray_t* (*cp_body_fn)(void* ctx); +static int cp_bind_sweep(cp_body_fn body, void* ctx, bool* all_errors) { + *all_errors = true; + int n = 1; + for (; n < 40; n++) { + ray_graph_bind_test_fail_alloc(n); + ray_t* r = body(ctx); + ray_graph_bind_test_fail_alloc(0); + bool is_err = r && RAY_IS_ERR(r); + bool bind_err = cp_is_bind_error(r); + if (is_err) ray_error_free(r); else if (r) ray_release(r); + if (!is_err) break; + if (!bind_err) *all_errors = false; + } + return n - 1; +} + +typedef struct { ray_t* t; const char* src; } cp_expr_ctx_t; +static ray_t* cp_expr_body(void* c) { + cp_expr_ctx_t* x = c; + ray_graph_t* g = ray_graph_new(x->t); + ray_t* e = ray_parse(x->src); + ray_op_t* dag = compile_expr_dag(g, e); + ray_t* r = dag ? ray_execute(g, dag) : NULL; + if (r && ray_is_lazy(r)) r = ray_lazy_materialize(r); + ray_release(e); + ray_graph_free(g); + return r; +} + +/* expr_compile over bound sources: the scan arm decides from the source + * (generation 0 and 2 alike), the registers carry their source, and the + * three execution routes (root compile, per-node fusion, predicate to + * selection) answer identically and propagate a failed bind. */ +static test_result_t test_expr_compile_bound(void) { + TEST_ASSERT_TRUE(cp_save()); + ray_t* res[2][3] = {{ NULL }}; + bool nullable[2][3]; + for (int gi = 0; gi < 2; gi++) { + int gen = gi * 2; + ray_t* t = cp_read(gen); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_graph_t* gr = ray_graph_new(t); + ray_t *e3, *e4, *e5; + ray_t* err = NULL; + ray_expr_t ex; + static const char* const srcs[3] = { "(+ (* a 3) b)", "(+ v 1)", "(+ a 1)" }; + for (int s = 0; s < 3; s++) { + ray_t* e; + ray_op_t* d = cp_dag(gr, srcs[s], &e); + TEST_ASSERT_TRUE(d && expr_compile(gr, t, d, &ex, &err)); + TEST_ASSERT_NULL(err); + nullable[gi][s] = false; + bool src_set = false; + for (int r = 0; r < ex.n_regs; r++) { + if (ex.regs[r].kind != REG_SCAN) continue; + if (ex.regs[r].nullable) nullable[gi][s] = true; + /* the register reads a source bound on the graph: the + * registry's entry for one of the scanned columns (a hit, + * no new bind), encoded exactly at generation 2, where it + * is range-read (enc, no captured pointer) */ + src_set = false; + static const char* const cn[3] = { "a", "b", "v" }; + for (int k = 0; k < 3 && !src_set; k++) { + uint32_t nb = ray_graph_binds_count(gr); + ray_col_src_t* bs = ray_graph_bind_col(gr, t, ray_sym_intern(cn[k], 1), &err); + /* a column this expression scans is already bound: a hit */ + bool scanned = strstr(srcs[s], cn[k]) != NULL; + if (scanned) TEST_ASSERT_EQ_I(ray_graph_binds_count(gr), nb); + TEST_ASSERT_NULL(err); + if (!bs || !bs->obj || ex.regs[r].src != bs) continue; + if (gen == 2) { + src_set = bs->obj->type == RAY_ENCCOL && ex.regs[r].enc && !ex.regs[r].data; + } else { + ray_t* plain = NULL; + if (ray_col_src_plain(bs, &plain) || !plain) continue; + src_set = bs->obj->type != RAY_ENCCOL && !ex.regs[r].enc && + ex.regs[r].data == ray_data(plain); + } + } + if (!src_set) break; + } + TEST_ASSERT_TRUE(src_set); + res[gi][s] = expr_eval_full(&ex, CP_N); + TEST_ASSERT_TRUE(res[gi][s] && !RAY_IS_ERR(res[gi][s])); + ray_release(e); + } + /* a: no nulls; v: nulls (the directory count at generation 2) */ + TEST_ASSERT_FALSE(nullable[gi][0]); + TEST_ASSERT_TRUE(nullable[gi][1]); + TEST_ASSERT_FALSE(nullable[gi][2]); + + /* SYM columns read from files resolve over the file's domain: both + * generations bail on the bound source's domain when the fused + * program would read the raw ids as values; EQ / NE against a + * constant compiles, the constant translated into the domain (P3 + * Task 4) */ + uint64_t nb = ray_expr_bail_counts[EXPR_BAIL_SYM_DOMAIN]; + ray_op_t* dx = ray_isnull(gr, ray_scan(gr, "x")); + TEST_ASSERT_FALSE(expr_compile(gr, t, dx, &ex, &err)); + TEST_ASSERT_NULL(err); + ray_op_t* dy = ray_eq(gr, ray_scan(gr, "y"), ray_const_str(gr, "yb", 2)); + TEST_ASSERT_TRUE(expr_compile(gr, t, dy, &ex, &err)); + TEST_ASSERT_NULL(err); + ray_op_t* dw = ray_lt(gr, ray_scan(gr, "y"), ray_const_str(gr, "yb", 2)); + TEST_ASSERT_FALSE(expr_compile(gr, t, dw, &ex, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_EQ_U(ray_expr_bail_counts[EXPR_BAIL_SYM_DOMAIN], nb + 2); + ray_t *e1 = NULL; + /* a partition key column and an unknown column are bails, not errors */ + ray_op_t* dz = cp_dag(gr, "(+ nosuch 1)", &e3); + TEST_ASSERT_FALSE(dz && expr_compile(gr, t, dz, &ex, &err)); + TEST_ASSERT_NULL(err); + ray_release(e3); + + /* the failure paths of the scan arm */ + ray_graph_free(gr); + ray_release(t); + t = cp_read(gen); + gr = ray_graph_new(t); + ray_op_t* d = cp_dag(gr, "(+ a b)", &e4); + ray_graph_bind_test_fail_alloc(1); + bool r = expr_compile(gr, t, d, &ex, &err); + ray_graph_bind_test_fail_alloc(0); + TEST_ASSERT_TRUE(!r && cp_is_bind_error(err)); + ray_error_free(err); err = NULL; + if (gen == 2) { + /* P2: the scan arm no longer decodes (its registers are + * range-read), so a failing decode allocation cannot fail the + * compile; range-read failures are scanrange/expr_error's */ + ray_enccol_test_fail_alloc(1); + ray_enc_counters_reset(); + r = expr_compile(gr, t, d, &ex, &err); + ray_enccol_test_fail_alloc(0); + TEST_ASSERT_TRUE(r && !err); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + TEST_ASSERT_EQ_U(kc.materialized, 0); + } + ray_release(e4); + + /* the predicate-to-selection route */ + ray_op_t* dp = cp_dag(gr, "(> a 500)", &e5); + bool all_pass = false; + ray_t* sel = exec_pred_to_selection(gr, dp, CP_N, &all_pass); + TEST_ASSERT_TRUE(sel && !RAY_IS_ERR(sel)); + int64_t tp = ray_rowsel_meta(sel)->total_pass; + ray_release(sel); + TEST_ASSERT_EQ_I(tp, 70 * 499); /* a > 500 over 70 blocks of a = i % 1000 */ + ray_graph_free(gr); + gr = ray_graph_new(t); /* fresh graph: nothing bound yet */ + ray_graph_bind_test_fail_alloc(1); + dp = cp_dag(gr, "(> a 500)", &e1); + sel = exec_pred_to_selection(gr, dp, CP_N, &all_pass); + ray_graph_bind_test_fail_alloc(0); + TEST_ASSERT_TRUE(cp_is_bind_error(sel)); + ray_error_free(sel); + ray_release(e1); ray_release(e5); + ray_graph_free(gr); + ray_release(t); + } + /* generation 0 and 2 expressions are the same values, nulls included */ + for (int s = 0; s < 3; s++) { + TEST_ASSERT_TRUE(res[0][s]->len == res[1][s]->len && res[0][s]->type == res[1][s]->type); + TEST_ASSERT_TRUE(memcmp(ray_data(res[0][s]), ray_data(res[1][s]), (size_t)res[0][s]->len * 8) == 0); + TEST_ASSERT_EQ_I(nullable[0][s], nullable[1][s]); + ray_release(res[0][s]); ray_release(res[1][s]); + } + + /* the execution routes: root compile and per-node fusion (the root bails on + * the nullable SYM, its subtree compiles) answer the same on both generations + * and every failed bind is returned */ + static const char* const routes[2] = { "(+ a b)", "(+ (as 'I64 (nil? x)) (+ a b))" }; + for (int ri = 0; ri < 2; ri++) { + ray_t* out[2] = { NULL, NULL }; + int nbinds[2] = { 0, 0 }; + for (int gi = 0; gi < 2; gi++) { + ray_t* t = cp_read(gi * 2); + cp_expr_ctx_t cx = { t, routes[ri] }; + uint64_t ok0 = ray_expr_compile_ok; + out[gi] = cp_expr_body(&cx); + TEST_ASSERT_TRUE(out[gi] && !RAY_IS_ERR(out[gi])); + TEST_ASSERT_TRUE(ray_expr_compile_ok > ok0); /* the compile ran */ + bool all_err = false; + nbinds[gi] = cp_bind_sweep(cp_expr_body, &cx, &all_err); + TEST_ASSERT_TRUE(all_err); + TEST_ASSERT_FMT(nbinds[gi] == (ri == 0 ? 2 : 3), "route %d: %d binds", ri, nbinds[gi]); /* every bind of a clean run fails in turn */ + ray_release(t); + } + TEST_ASSERT_EQ_I(nbinds[0], nbinds[1]); + TEST_ASSERT_TRUE(out[0]->len == out[1]->len); + TEST_ASSERT_TRUE(memcmp(ray_data(out[0]), ray_data(out[1]), (size_t)out[0]->len * 8) == 0); + ray_release(out[0]); ray_release(out[1]); + } + PASS(); +} + +typedef struct { ray_t* t; const char* key; uint16_t* ops; const char* const* cols; int na; } cp_group_ctx_t; +static ray_t* cp_group_body(void* c) { + cp_group_ctx_t* x = c; + ray_graph_t* g = ray_graph_new(x->t); + ray_op_t* keys[1] = { ray_scan(g, x->key) }; + ray_op_t* ins[4]; + for (int i = 0; i < x->na; i++) ins[i] = ray_scan(g, x->cols[i]); + ray_t* r = ray_execute(g, ray_group(g, keys, 1, x->ops, ins, (uint8_t)x->na)); + if (r && ray_is_lazy(r)) r = ray_lazy_materialize(r); + ray_graph_free(g); + return r; +} + +typedef struct { int64_t key; int64_t row; } cp_krow_t; +static int cp_krow_cmp(const void* a, const void* b) { + int64_t x = ((const cp_krow_t*)a)->key, y = ((const cp_krow_t*)b)->key; + return x < y ? -1 : x > y; +} + +/* Group results equal as maps from key to the 8-byte aggregate cells. */ +static bool cp_groups_same(ray_t* x, ray_t* y, int64_t want_groups, int ncols) { + if (!x || !y || RAY_IS_ERR(x) || RAY_IS_ERR(y)) return false; + if (ray_table_nrows(x) != want_groups || ray_table_nrows(y) != want_groups) return false; + cp_krow_t* kx = ray_alloc_raw((size_t)want_groups * sizeof *kx); + cp_krow_t* ky = ray_alloc_raw((size_t)want_groups * sizeof *ky); + bool ok = kx && ky; + for (int64_t i = 0; ok && i < want_groups; i++) { + kx[i] = (cp_krow_t){ ((const int64_t*)ray_data(ray_table_get_col_idx(x, 0)))[i], i }; + ky[i] = (cp_krow_t){ ((const int64_t*)ray_data(ray_table_get_col_idx(y, 0)))[i], i }; + } + if (ok) { + qsort(kx, (size_t)want_groups, sizeof *kx, cp_krow_cmp); + qsort(ky, (size_t)want_groups, sizeof *ky, cp_krow_cmp); + for (int64_t i = 0; ok && i < want_groups; i++) { + if (kx[i].key != ky[i].key) { ok = false; break; } + for (int c = 1; c <= ncols; c++) { + const int64_t* cx = ray_data(ray_table_get_col_idx(x, c)); + const int64_t* cy = ray_data(ray_table_get_col_idx(y, c)); + if (cx[kx[i].row] != cy[ky[i].row]) { ok = false; break; } + } + } + } + ray_free_raw(kx); ray_free_raw(ky); + return ok; +} + +/* agg_desc_init, exercised through every parallel strategy that builds a + * descriptor (dense, small-hash/table-stack, radix, shared sample, partition + * payload) over bound sources: generation 0 and 2 answer the same, the route + * is the expected one, and a failed bind of any value column is the + * query's error. */ +static test_result_t test_group_desc_bound(void) { + TEST_ASSERT_TRUE(cp_save()); + uint32_t cores = ray_pool_total_workers(ray_pool_get()); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(2), RAY_OK); + static uint16_t sum_avg[2] = { OP_SUM, OP_AVG }; + static uint16_t min_max[2] = { OP_MIN, OP_MAX }; + static const char* const cols_af[2] = { "a", "f" }; + static const struct { const char* key; uint16_t* ops; int64_t groups; agg_route_t route; } cases[] = { + { "k0", sum_avg, 4, AGG_ROUTE_V2_DENSE }, + { "k1", sum_avg, 4, AGG_ROUTE_V2_TABLESTACK }, + { "k4", sum_avg, CP_N, AGG_ROUTE_V2_RADIX }, + { "k2", sum_avg, 8192, AGG_ROUTE_V2_DENSE }, /* partition payload estimate */ + { "k2", min_max, 8192, AGG_ROUTE_V2_DENSE }, /* shared-state sample */ + }; + for (size_t c = 0; c < sizeof cases / sizeof *cases; c++) { + ray_t* out[2] = { NULL, NULL }; + for (int gi = 0; gi < 2; gi++) { + ray_t* t = cp_read(gi * 2); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + cp_group_ctx_t cx = { t, cases[c].key, cases[c].ops, cols_af, 2 }; + agg_route_reset(); + out[gi] = cp_group_body(&cx); + agg_route_stats_t st = agg_route_stats(); + TEST_ASSERT_FMT(out[gi] && !RAY_IS_ERR(out[gi]), "case %zu gen %d ran", c, gi * 2); + TEST_ASSERT_FMT(st.routes[cases[c].route] == 1, "case %zu gen %d route", c, gi * 2); + /* every failure before the first success is the bind error: the + * key (P2 Task 13: the v2 engine binds its keys) and both value + * columns */ + bool all_err = false; + int nb = cp_bind_sweep(cp_group_body, &cx, &all_err); + TEST_ASSERT_FMT(all_err && nb == 3, "case %zu gen %d sweep nb=%d all_err=%d", c, gi * 2, nb, all_err); + ray_release(t); + } + TEST_ASSERT_FMT(cp_groups_same(out[0], out[1], cases[c].groups, 2), "case %zu answers differ", c); + ray_release(out[0]); ray_release(out[1]); + } + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(cores), RAY_OK); + PASS(); +} + +typedef struct { + ray_t* t; ray_t* where; int mode; /* 0 top-k, 1 take, 2 take from the end */ + int64_t sk[2]; uint8_t desc[2]; int64_t outs[4]; +} cp_topk_ctx_t; +static ray_t* cp_topk_body(void* c) { + cp_topk_ctx_t* x = c; + if (x->mode == 0) + return ray_fused_topk_select(x->t, x->where, x->sk, x->desc, 2, 10, x->outs, NULL, 4); + return ray_fused_take_select(x->t, x->where, x->mode == 1 ? 7 : -7, x->outs, NULL, 4); +} + +/* The fused top-k and take executors on bound sources: sort keys and gathers + * (generation 0 and 2, direct on a table whose slots are encoded) give the + * same rows, run (not decline), and return a failed bind of a sort key, a + * predicate column or a gathered column. */ +static test_result_t test_topk_bound(void) { + TEST_ASSERT_TRUE(fq_save("tk")); + int64_t si = ray_sym_intern("i", 1), sv = ray_sym_intern("v", 1), sd = ray_sym_intern("d", 1); + int64_t ss = ray_sym_intern("s", 1); + struct { int mode; int64_t k0, k1; uint8_t d0; const char* where; int min_binds; } cases[] = { + { 0, sv, si, 1, "(> v 5)", 4 }, /* nullable I64 desc, then i; where on v */ + { 0, ss, si, 0, "(!= s 'beta)", 4 }, /* SYM sort key (file domain at generation 2) */ + { 0, sd, si, 1, "(< d 2.0)", 4 }, /* F64 desc with nulls */ + { 1, 0, 0, 0, "(> v 5)", 4 }, /* take from the front */ + { 2, 0, 0, 0, "(== s 'gamma)", 4 }, /* take from the end */ + }; + for (size_t c = 0; c < sizeof cases / sizeof *cases; c++) { + ray_t* out[2] = { NULL, NULL }; + int nbinds[2] = { 0, 0 }; + for (int gi = 0; gi < 2; gi++) { + ray_t* t = ray_read_splayed(gi ? ray_test_tmp(CS_TMP "/tk2") : ray_test_tmp(CS_TMP "/tk0"), gi ? ray_test_tmp(CS_TMP "/tk2.sym") : ray_test_tmp(CS_TMP "/tk0.sym")); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_get_col_enc(t, si) != NULL, gi); + ray_t* w = ray_parse(cases[c].where); + cp_topk_ctx_t cx = { .t = t, .where = w, .mode = cases[c].mode, + .sk = { cases[c].k0, cases[c].k1 }, .desc = { cases[c].d0, 0 }, + .outs = { si, sv, sd, ss } }; + ray_fused_topk_counters_reset(); + out[gi] = cp_topk_body(&cx); + uint64_t ran, dec; ray_fused_topk_counters(&ran, &dec); + TEST_ASSERT_FMT(out[gi] && !RAY_IS_ERR(out[gi]) && ran == 1 && dec == 0, + "case %zu gen %d ran=%llu declined=%llu", c, gi * 2, + (unsigned long long)ran, (unsigned long long)dec); + bool all_err = false; + nbinds[gi] = cp_bind_sweep(cp_topk_body, &cx, &all_err); + TEST_ASSERT_FMT(all_err && nbinds[gi] == cases[c].min_binds, "case %zu gen %d sweep nb=%d all_err=%d", + c, gi * 2, nbinds[gi], all_err); + ray_release(w); + ray_release(t); + } + TEST_ASSERT_EQ_I(nbinds[0], nbinds[1]); + TEST_ASSERT_FMT(cp_fmt_same(out[0], out[1]), "case %zu rows differ", c); + TEST_ASSERT_TRUE(ray_table_nrows(out[0]) == (cases[c].mode == 0 ? 10 : 7)); + ray_release(out[0]); ray_release(out[1]); + } + /* the plain request of an encoded sort key failing is returned too */ + ray_t* t = ray_read_splayed(ray_test_tmp(CS_TMP "/tk2"), ray_test_tmp(CS_TMP "/tk2.sym")); + ray_t* w = ray_parse("(> v 5)"); + cp_topk_ctx_t cx = { .t = t, .where = w, .mode = 0, .sk = { sv, si }, .desc = { 1, 0 }, .outs = { si, sv, sd, ss } }; + ray_enccol_test_fail_alloc(1); + ray_t* r = cp_topk_body(&cx); + ray_enccol_test_fail_alloc(0); + bool plain_err = r && RAY_IS_ERR(r); + if (plain_err) ray_error_free(r); else if (r) ray_release(r); + ray_release(w); ray_release(t); + TEST_ASSERT_TRUE(plain_err); + PASS(); +} + + +/* ---- Task 27: executor, filter, sort, window, pivot sites ---- */ + +/* `n` rows of a (generation 2, 3 i) and b (generation 0, 5 i). */ +static ray_t* ex_table(int64_t n) { + char p[256]; + (void)ray_test_rm_rf(ray_test_tmp(CS_TMP "/ex")); + (void)ray_test_mkdir_p(ray_test_tmp(CS_TMP "/ex")); + ray_t* a = i64_col(n, 3); ray_t* b = i64_col(n, 5); + snprintf(p, sizeof p, "%s/ex/a", ray_test_tmp(CS_TMP)); ray_col_save_gen(a, p, 2); + snprintf(p, sizeof p, "%s/ex/b", ray_test_tmp(CS_TMP)); ray_col_save_gen(b, p, 0); + ray_release(a); ray_release(b); + ray_t* names = ray_vec_new(RAY_STR, 2); + names = ray_str_vec_append(names, "a", 1); names = ray_str_vec_append(names, "b", 1); + snprintf(p, sizeof p, "%s/ex/.d", ray_test_tmp(CS_TMP)); ray_col_save(names, p); ray_release(names); + return ray_read_splayed(ray_test_tmp(CS_TMP "/ex"), NULL); +} + +typedef enum { EX_HEAD, EX_TAIL, EX_FILTER, EX_FILTER_SOME, EX_SORT_B, EX_SORT_A, EX_TOPK_B, + EX_PIVOT, EX_WINDOW_FN_A, EX_SELECT_PASS, EX_WINDOW_PASS, EX_MERGE, EX_FILTER_NONE, + EX_HEAD_FILTER, EX_EAGER_FILTER, EX_TOPK_A, EX_N } ex_case_t; + +static ray_t* ex_run(ray_t* t, ex_case_t k) { + if (k == EX_MERGE) return ray_result_merge(t, t); + if (k == EX_EAGER_FILTER) { /* the eager gather: the lazy path never reaches it over a table */ + int64_t n = ray_table_nrows(t); + ray_t* pred = ray_vec_new(RAY_BOOL, n); pred->len = n; + for (int64_t i = 0; i < n; i++) ((uint8_t*)ray_data(pred))[i] = i % 3 != 0; + ray_error_clear(); + ray_t* r = exec_filter(NULL, NULL, t, pred); + ray_release(pred); + return r; + } + ray_graph_t* g = ray_graph_new(t); + ray_op_t* tb = ray_const_table(g, t); + ray_op_t* sb = ray_scan(g, "b"); + ray_op_t* root = NULL; + uint8_t nf0[1] = { 0 }, d0[1] = { 0 }; + switch (k) { + case EX_HEAD: root = ray_head(g, tb, 5); break; + case EX_TAIL: root = ray_tail(g, tb, 5); break; + case EX_FILTER: root = ray_filter(g, tb, ray_ge(g, sb, ray_const_i64(g, 5))); break; + case EX_HEAD_FILTER: root = ray_head(g, ray_filter(g, tb, ray_gt(g, sb, ray_const_i64(g, 50))), 4); break; + case EX_FILTER_SOME: root = ray_filter(g, tb, ray_gt(g, sb, ray_const_i64(g, 500))); break; + case EX_FILTER_NONE: root = ray_filter(g, tb, ray_lt(g, sb, ray_const_i64(g, -1))); break; + case EX_SORT_B: { /* descending: b ascends, and an ordered table is returned ungathered */ + uint8_t d1[1] = { 1 }; + ray_op_t* ks[1] = { sb }; root = ray_sort_op(g, tb, ks, d1, nf0, 1); break; } + case EX_SORT_A: { ray_op_t* ks[1] = { ray_scan(g, "a") }; root = ray_sort_op(g, tb, ks, d0, nf0, 1); break; } + case EX_TOPK_A: { ray_op_t* ks[1] = { ray_scan(g, "a") }; root = ray_head(g, ray_sort_op(g, tb, ks, d0, nf0, 1), 3); break; } + case EX_TOPK_B: { ray_op_t* ks[1] = { sb }; root = ray_head(g, ray_sort_op(g, tb, ks, d0, nf0, 1), 3); break; } + case EX_PIVOT: { ray_op_t* ix[1] = { sb }; + root = ray_pivot_op(g, ix, 1, ray_scan(g, "a"), sb, OP_SUM); break; } + case EX_WINDOW_FN_A: case EX_WINDOW_PASS: { + ray_op_t* ord[1] = { sb }; + uint8_t kinds[1] = { RAY_WIN_SUM }; + ray_op_t* fin[1] = { k == EX_WINDOW_FN_A ? ray_scan(g, "a") : sb }; + int64_t prm[1] = { 0 }; + root = ray_window_op(g, tb, NULL, 0, ord, d0, 1, kinds, fin, prm, 1, RAY_FRAME_ROWS, + RAY_BOUND_UNBOUNDED_PRECEDING, RAY_BOUND_UNBOUNDED_FOLLOWING, 0, 0); + break; } + case EX_SELECT_PASS: { ray_op_t* cs[2] = { ray_scan(g, "a"), sb }; root = ray_select_op(g, tb, cs, 2); break; } + default: break; + } + ray_error_clear(); + ray_t* r = root ? ray_execute(g, root) : NULL; + ray_graph_free(g); + return r; +} + +/* The executor sites that only pass or measure a column never decode it. */ +static test_result_t test_exec_sites_pass_encoded(void) { + static const ex_case_t ks[3] = { EX_SELECT_PASS, EX_WINDOW_PASS, EX_FILTER_NONE }; + static const char* const names[3] = { "select-pass", "window-pass", "filter-none" }; + int64_t sa = ray_sym_intern("a", 1); + for (int i = 0; i < 3; i++) { + ray_t* t = ex_table(3000); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_enc_counters_reset(); + ray_t* r = ex_run(t, ks[i]); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_TABLE, "%s: expected a table", names[i]); + ray_enc_counters_t c; ray_enc_counters_get(&c); + if (ks[i] == EX_FILTER_NONE) + TEST_ASSERT_FMT(ray_table_nrows(r) == 0 && ray_table_ncols(r) == 2, "%s: schema", names[i]); + else + TEST_ASSERT_FMT(ray_table_get_col_enc(r, sa) != NULL, "%s: a is passed encoded", names[i]); + TEST_ASSERT_FMT(c.materialized == 0, "%s: materialized %llu", names[i], (unsigned long long)c.materialized); + ray_release(r); + ray_release(t); + } + PASS(); +} + +/* A healthy generation-2 table gives the same answers as the plain one at + * every site above. */ +static test_result_t test_exec_sites_gen2_equal(void) { + ray_t* t2 = ex_table(3000); + TEST_ASSERT_TRUE(t2 && !RAY_IS_ERR(t2)); + ray_t* t0 = ray_table_new(2); + t0 = ray_table_add_col(t0, ray_sym_intern("a", 1), i64_col(3000, 3)); + t0 = ray_table_add_col(t0, ray_sym_intern("b", 1), i64_col(3000, 5)); + for (int k = 0; k < EX_N; k++) { + /* pivot: its output columns follow the hash table's order, so rows are compared by the + * dedicated pivot tests; merge and the eager filter take no graph. */ + if (k == EX_PIVOT || k == EX_MERGE || k == EX_EAGER_FILTER) continue; + ray_t* r2 = ex_run(t2, (ex_case_t)k); + ray_t* r0 = ex_run(t0, (ex_case_t)k); + TEST_ASSERT_FMT(r2 && r0 && !RAY_IS_ERR(r2) && !RAY_IS_ERR(r0), "case %d", k); + TEST_ASSERT_FMT(cp_fmt_same(r0, r2), "case %d rows differ", k); + ray_release(r2); ray_release(r0); + } + ray_release(t0); ray_release(t2); + PASS(); +} + + +/* Rows of a graph FILTER on column s (SYM) or v over the fixture table, run on generation 0 or 2. */ +static int64_t fq_filter_rows(const char* name, int gen, const char* col, ray_t* atom, ray_enc_counters_t* c) { + char d[160], sy[170]; + snprintf(d, sizeof d, "%s/%s%d", ray_test_tmp(CS_TMP), name, gen); snprintf(sy, sizeof sy, "%s.sym", d); + ray_t* t = ray_read_splayed(d, sy); + if (!t || RAY_IS_ERR(t)) return -1; + ray_graph_t* g = ray_graph_new(t); + ray_op_t* root = ray_filter(g, ray_const_table(g, t), + ray_eq(g, ray_scan(g, col), ray_const_atom(g, atom))); + ray_enc_counters_reset(); + ray_t* r = ray_execute(g, root); + ray_enc_counters_get(c); + int64_t n = (r && !RAY_IS_ERR(r)) ? (g->selection ? ray_rowsel_meta(g->selection)->total_pass : ray_table_nrows(r)) : -1; + if (r && !RAY_IS_ERR(r)) ray_release(r); + ray_graph_free(g); + ray_release(t); + return n; +} + +/* An equality on a symbol missing from the column's domain selects no rows from the domain alone: a + * generation-2 column is not decoded to learn that; a present symbol, and a predicate on an encoded + * column with no index, give the same rows on both generations. */ +static test_result_t test_filter_absent_symbol(void) { + TEST_ASSERT_TRUE(fq_save("as")); + ray_t* none = ray_sym(ray_sym_intern("nowhere_at_all", 14)); + ray_t* beta = ray_sym(ray_sym_intern("beta", 4)); + ray_t* four = ray_i64(4); + ray_enc_counters_t c0, c2; + TEST_ASSERT_EQ_I(fq_filter_rows("as", 0, "s", none, &c0), 0); + TEST_ASSERT_EQ_I(fq_filter_rows("as", 2, "s", none, &c2), 0); + TEST_ASSERT_EQ_U(c2.materialized, 0); + TEST_ASSERT_EQ_I(fq_filter_rows("as", 0, "s", beta, &c0), 750); + TEST_ASSERT_EQ_I(fq_filter_rows("as", 2, "s", beta, &c2), 750); + TEST_ASSERT_EQ_U(c2.materialized, 0); /* the scan reads s by range; the result gathers by range (P3 Task 6) */ + int64_t v0 = fq_filter_rows("as", 0, "v", four, &c0); + int64_t v2 = fq_filter_rows("as", 2, "v", four, &c2); + TEST_ASSERT_TRUE(v0 > 0 && v0 == v2); + TEST_ASSERT_EQ_U(c2.materialized, 0); /* no index: the scan and the result gather read by range */ + ray_release(none); ray_release(beta); ray_release(four); + PASS(); +} + +/* ---- Task 23: pruned parted execution ---- */ + +/* Three partitions 2024.01.01..03 (dates 8766..8768). Partition p holds a = + * i * (3 + p), b = 5 i + p over rows[p] rows (3000 for pdb_make); bit p of `gen2` selects + * generation 2, and `ragged` drops column b from the last partition. */ +static ray_t* pdb_make_rows(const char* root, unsigned gen2, bool ragged, const int64_t rows[3]) { + for (int p = 0; p < 3; p++) { + char dir[256]; snprintf(dir, sizeof dir, "%s/2024.01.0%d/t", root, p + 1); + ray_t* t = ray_table_new(2); + ray_t* a = i64_col(rows[p], 3 + p); + ray_t* b = i64_col(rows[p], 5); + for (int64_t i = 0; i < rows[p]; i++) ((int64_t*)ray_data(b))[i] += p; + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + if (!(ragged && p == 2)) t = ray_table_add_col(t, ray_sym_intern("b", 1), b); + ray_release(a); ray_release(b); + if (ray_splay_save_mode(t, dir, NULL, (gen2 >> p) & 1 ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF) != RAY_OK) { + ray_release(t); return NULL; + } + ray_release(t); + } + ray_t* t = ray_read_parted(root, "t"); + return (t && !RAY_IS_ERR(t)) ? t : NULL; +} +static ray_t* pdb_make(const char* root, unsigned gen2, bool ragged) { + static const int64_t rows[3] = { 3000, 3000, 3000 }; + return pdb_make_rows(root, gen2, ragged, rows); +} + +/* Predicates over the partition key and the roots under test. */ +enum { Q_EQ_02, Q_LE_02, Q_01_03, Q_NONE }; +enum { R_SUM, R_A, R_DATE }; + +/* The shared plan: filter(root expr, pred) over default-table scans (a + * const-table root never streams). Reports whether the graph's bind list + * is empty once the run is over (per-segment tables unbound). */ +static ray_t* pruned_run(ray_t* t, int q, int root_kind, bool* binds_clean) { + ray_graph_t* g = ray_graph_new(t); + ray_t* l1 = ray_date(8766); ray_t* l2 = ray_date(8767); ray_t* l3 = ray_date(8768); + ray_op_t* pred = NULL; + switch (q) { + case Q_EQ_02: pred = ray_eq(g, ray_scan(g, "date"), ray_const_atom(g, l2)); break; + case Q_LE_02: pred = ray_le(g, ray_scan(g, "date"), ray_const_atom(g, l2)); break; + case Q_01_03: + pred = ray_or(g, ray_eq(g, ray_scan(g, "date"), ray_const_atom(g, l1)), + ray_eq(g, ray_scan(g, "date"), ray_const_atom(g, l3))); + break; + default: pred = ray_gt(g, ray_scan(g, "date"), ray_const_atom(g, l3)); break; + } + ray_op_t* e = root_kind == R_SUM ? ray_add(g, ray_scan(g, "a"), ray_scan(g, "b")) + : root_kind == R_A ? ray_scan(g, "a") : ray_scan(g, "date"); + ray_op_t* root = ray_optimize(g, ray_filter(g, e, pred)); + ray_t* out = ray_execute(g, root); + if (binds_clean) *binds_clean = ray_graph_binds_count(g) == 0; + ray_release(l1); ray_release(l2); ray_release(l3); ray_graph_free(g); + return out; +} + +/* Same query on two tables: both outcomes are an error with the same code, + * or vectors of the same type and bytes. */ +static bool same_outcome(ray_t* x, ray_t* y) { + if (!x || !y) return false; + if (RAY_IS_ERR(x) || RAY_IS_ERR(y)) + return RAY_IS_ERR(x) && RAY_IS_ERR(y) && strcmp(ray_err_code(x), ray_err_code(y)) == 0; + if (x->type != y->type || x->len != y->len) return false; + size_t esz = (size_t)ray_type_sizes[(uint8_t)x->type]; + return memcmp(ray_data(x), ray_data(y), (size_t)x->len * esz) == 0; +} +static void drop_out(ray_t* o) { if (!o) return; if (RAY_IS_ERR(o)) ray_error_free(o); else ray_release(o); } + +static test_result_t test_parted_pruning_fetch(void) { + ray_t* t = pdb_make(ray_test_tmp(CS_TMP "/pdb"), 7, false); + TEST_ASSERT_NOT_NULL(t); + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/pdb0"), 0, false); + TEST_ASSERT_NOT_NULL(t0); + ray_enc_counters_reset(); + bool clean = false; + ray_t* out = pruned_run(t, Q_EQ_02, R_SUM, &clean); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out)); + TEST_ASSERT_EQ_I(out->len, 3000); + TEST_ASSERT_TRUE(clean); /* per-segment tables unbound */ + ray_enc_counters_t c; ray_enc_counters_get(&c); + /* columns a and b of the surviving partition are range-read by the + * fused (+ a b): nothing is materialized */ + TEST_ASSERT_FMT(c.materialized == 0, "materialized %llu segment columns", (unsigned long long)c.materialized); + const int64_t* d = (const int64_t*)ray_data(out); + for (int i = 0; i < 3000; i++) + TEST_ASSERT_EQ_I(d[i], (int64_t)i * 4 + (int64_t)i * 5 + 1); /* partition 1: 4 i + 5 i + 1 */ + ray_t* o0 = pruned_run(t0, Q_EQ_02, R_SUM, NULL); + TEST_ASSERT_TRUE(same_outcome(out, o0)); + drop_out(out); drop_out(o0); ray_release(t); ray_release(t0); + PASS(); +} + +/* Per-segment execution on generation 0 is unchanged: nothing decoded and + * the answers match generation 2 for every query shape. */ +static test_result_t test_parted_pruning_gen0(void) { + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/p0"), 0, false); + ray_t* t2 = pdb_make(ray_test_tmp(CS_TMP "/p2"), 7, false); + TEST_ASSERT_TRUE(t0 && t2); + ray_enc_counters_reset(); + ray_t* o0 = pruned_run(t0, Q_EQ_02, R_SUM, NULL); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_EQ_U(c.materialized, 0); + TEST_ASSERT_TRUE(o0 && !RAY_IS_ERR(o0) && o0->len == 3000); + ray_t* o2 = pruned_run(t2, Q_EQ_02, R_SUM, NULL); + TEST_ASSERT_TRUE(same_outcome(o0, o2)); + drop_out(o0); drop_out(o2); ray_release(t0); ray_release(t2); + PASS(); +} + +/* Nothing survives: the empty result has generation 0's schema (the key's + * DATE type from the MAPCOMMON, the I64 base of the parted columns) and + * nothing is decoded. */ +static test_result_t test_parted_pruning_empty(void) { + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/e0"), 0, false); + ray_t* t2 = pdb_make(ray_test_tmp(CS_TMP "/e2"), 7, false); + TEST_ASSERT_TRUE(t0 && t2); + static const int8_t want[] = { RAY_I64, RAY_I64, RAY_DATE }; + for (int rk = R_SUM; rk <= R_DATE; rk++) { + ray_enc_counters_reset(); + bool clean = false; + ray_t* o2 = pruned_run(t2, Q_NONE, rk, &clean); + ray_enc_counters_t c; ray_enc_counters_get(&c); + ray_t* o0 = pruned_run(t0, Q_NONE, rk, NULL); + TEST_ASSERT_TRUE(o0 && o2 && !RAY_IS_ERR(o0) && !RAY_IS_ERR(o2)); + TEST_ASSERT_EQ_I(o2->len, 0); + TEST_ASSERT_EQ_I(o2->type, want[rk]); + TEST_ASSERT_EQ_I(o0->type, o2->type); + TEST_ASSERT_EQ_I(o0->len, o2->len); + TEST_ASSERT_EQ_U(c.materialized, 0); + TEST_ASSERT_TRUE(clean); + ray_release(o0); ray_release(o2); + } + ray_release(t0); ray_release(t2); + PASS(); +} + +static test_result_t test_parted_pruning_multi(void) { + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/m0"), 0, false); + ray_t* t2 = pdb_make(ray_test_tmp(CS_TMP "/m2"), 7, false); + TEST_ASSERT_TRUE(t0 && t2); + ray_enc_counters_reset(); + bool clean = false; + ray_t* o2 = pruned_run(t2, Q_LE_02, R_SUM, &clean); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_TRUE(o2 && !RAY_IS_ERR(o2) && o2->len == 6000); + TEST_ASSERT_TRUE(clean); + /* the fused (+ a b) range-reads both partitions' columns */ + TEST_ASSERT_FMT(c.materialized == 0, "materialized %llu segment columns", (unsigned long long)c.materialized); + ray_t* o0 = pruned_run(t0, Q_LE_02, R_SUM, NULL); + TEST_ASSERT_TRUE(same_outcome(o0, o2)); + drop_out(o0); drop_out(o2); ray_release(t0); ray_release(t2); + PASS(); +} + +/* Mixed generations and a ragged tail partition go through the + * per-segment tables like all generation 0. */ +static test_result_t test_parted_pruning_mixed(void) { + static const unsigned masks[] = { 0x5, 0x2 }; + for (int k = 0; k < 2; k++) { + for (int rag = 0; rag < 2; rag++) { + char r0[128], rm[128]; + snprintf(r0, sizeof r0, ray_test_tmp(CS_TMP "/x0_%d_%d"), k, rag); + snprintf(rm, sizeof rm, ray_test_tmp(CS_TMP "/xm_%d_%d"), k, rag); + ray_t* t0 = pdb_make(r0, 0, rag); + ray_t* tm = pdb_make(rm, masks[k], rag); + TEST_ASSERT_TRUE(t0 && tm); + for (int q = Q_EQ_02; q <= Q_NONE; q++) { + for (int rk = R_SUM; rk <= R_A; rk++) { + bool clean = false; + ray_t* a = pruned_run(t0, q, rk, NULL); + ray_t* b = pruned_run(tm, q, rk, &clean); + TEST_ASSERT_FMT(same_outcome(a, b), "mask %u ragged %d query %d root %d", masks[k], rag, q, rk); + TEST_ASSERT_TRUE(clean); + /* ragged too (#724): 2024.01.03's missing b reads as nulls */ + if (rk == R_SUM && q == Q_01_03) TEST_ASSERT_TRUE(!RAY_IS_ERR(b) && b->len == 6000); + drop_out(a); drop_out(b); + } + } + ray_release(t0); ray_release(tm); + } + } + PASS(); +} + + +/* The slice-group kernel's shape admission binds the product columns + * (sg_shape_eligible through the early settle hook): the answer equals the + * plain-sym table's and a failed bind is the query's error. */ +static test_result_t test_slice_group_bound(void) { + TEST_ASSERT_STR_EQ(ev_code("(set SY ['aa 'bb 'cc 'dd 'ee 'ff 'gg 'hh])"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set KS (as 'SYM (at SY (% (til 4000) 8))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set FF (* 0.5 (as 'F64 (% (til 4000) 64))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set GG (* 0.25 (as 'F64 (% (til 4000) 32))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set TP (table [s f g] (list KS FF GG)))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set TI (table [s f g] (list (.attr.set 'grouped KS) FF GG)))"), ""); + const char* qi = "(select {sv: (sum (* f g)) from: TI by: s asc: s where: (in s ['aa 'cc])})"; + const char* qp = "(select {sv: (sum (* f g)) from: TP by: s asc: s where: (in s ['aa 'cc])})"; + uint64_t hits0 = ray_idx_hits[IDX_SITE_GROUP_SLICE]; + ray_t* a = ray_eval_str(qi); + ray_t* b = ray_eval_str(qp); + TEST_ASSERT_TRUE(ray_idx_hits[IDX_SITE_GROUP_SLICE] == hits0 + 1); /* the slice path ran once */ + TEST_ASSERT_TRUE(cp_fmt_same(a, b) && ray_table_nrows(a) == 2); + ray_release(a); ray_release(b); + ray_graph_bind_test_fail_alloc(1); + a = ray_eval_str(qi); + ray_graph_bind_test_fail_alloc(0); + TEST_ASSERT_TRUE(cp_is_bind_error(a)); + ray_error_free(a); + PASS(); +} + +/* ---- Task 28: group-by and the aggregate engine ---- */ + +typedef struct { ray_t* t; const char* key; uint16_t op; const char* c1; const char* c2; } gp_ctx_t; +static ray_t* gp_body(void* c) { + gp_ctx_t* x = c; + ray_graph_t* g = ray_graph_new(x->t); + ray_op_t* keys[1] = { ray_scan(g, x->key) }; + uint16_t ops[1] = { x->op }; + ray_op_t* ins[1] = { ray_scan(g, x->c1) }; + ray_op_t* ins2[1] = { x->c2 ? ray_scan(g, x->c2) : NULL }; + ray_t* r = ray_execute(g, ray_group_build(g, keys, 1, ops, ins, x->c2 ? ins2 : NULL, NULL, 1)); + if (r && ray_is_lazy(r)) r = ray_lazy_materialize(r); + ray_graph_free(g); + return r; +} + +/* A healthy generation-2 table, directly and through a select result, groups + * to the generation-0 answer, and takes the same route with the same + * planning outcome. */ +static test_result_t gp_same_routes(ray_t* t0, ray_t* t2, const char* key, uint16_t op, const char* c1, + const char* c2, const char* what) { + gp_ctx_t c0 = { t0, key, op, c1, c2 }, cg = { t2, key, op, c1, c2 }; + agg_route_reset(); + ray_t* r0 = gp_body(&c0); + agg_route_stats_t s0 = agg_route_stats(); + agg_route_reset(); + ray_t* r2 = gp_body(&cg); + agg_route_stats_t s2 = agg_route_stats(); + TEST_ASSERT_FMT(r0 && r2 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r2), "%s: ran", what); + TEST_ASSERT_FMT(memcmp(s0.routes, s2.routes, sizeof s0.routes) == 0, "%s: routes differ", what); + TEST_ASSERT_FMT(s0.last_v2_reason == s2.last_v2_reason && s0.nullable_key == s2.nullable_key && + s0.dense_plan_available == s2.dense_plan_available && + s0.dense_strategy == s2.dense_strategy && s0.dense_tasks == s2.dense_tasks, + "%s: planning differs", what); + TEST_ASSERT_FMT(cp_fmt_same(r0, r2), "%s: answers differ", what); + ray_release(r0); ray_release(r2); + PASS(); +} + +static test_result_t test_group_sites_routes_same(void) { + TEST_ASSERT_TRUE(cp_save()); + uint32_t cores = ray_pool_total_workers(ray_pool_get()); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(2), RAY_OK); + ray_t* t0 = cp_read(0); ray_t* t2 = cp_read(2); + TEST_ASSERT_TRUE(t0 && t2 && !RAY_IS_ERR(t0) && !RAY_IS_ERR(t2)); + static const struct { const char* key; uint16_t op; const char* c1; const char* c2; } cases[] = { + { "k0", OP_SUM, "a", NULL }, /* dense */ + { "k1", OP_SUM, "a", NULL }, /* sparse: table-stack */ + { "k2", OP_AVG, "f", NULL }, /* dense, 8192 groups */ + { "k4", OP_SUM, "a", NULL }, /* radix */ + { "f", OP_SUM, "a", NULL }, /* F64 key: indexed */ + { "x", OP_SUM, "a", NULL }, /* nullable SYM key */ + { "k0", OP_MEDIAN, "a", NULL }, /* holistic: indexed */ + { "k0", OP_FIRST, "a", NULL }, /* first/last */ + { "k0", OP_PEARSON_CORR, "a", "b" }, /* binary */ + { "k0", OP_COUNT, "a", NULL }, + }; + test_result_t res = { TEST_PASS, NULL }; + for (size_t i = 0; i < sizeof cases / sizeof *cases && res.status == TEST_PASS; i++) { + char w[64]; snprintf(w, sizeof w, "case %zu (%s)", i, cases[i].key); + res = gp_same_routes(t0, t2, cases[i].key, cases[i].op, cases[i].c1, cases[i].c2, w); + } + /* the same shapes over a select result whose slots are encoded */ + if (res.status == TEST_PASS) { + ray_graph_t* g = ray_graph_new(t2); + ray_op_t* cs[3] = { ray_scan(g, "k0"), ray_scan(g, "k4"), ray_scan(g, "a") }; + ray_t* sel = ray_execute(g, ray_select_op(g, ray_const_table(g, t2), cs, 3)); + ray_graph_free(g); + TEST_ASSERT_TRUE(sel && !RAY_IS_ERR(sel) && sel->type == RAY_TABLE); + TEST_ASSERT_TRUE(ray_table_get_col_enc(sel, ray_sym_intern("a", 1)) != NULL); + res = gp_same_routes(t0, sel, "k0", OP_SUM, "a", NULL, "select result k0"); + if (res.status == TEST_PASS) res = gp_same_routes(t0, sel, "k4", OP_SUM, "a", NULL, "select result k4"); + ray_release(sel); + } + /* an expression aggregate (exec_group_v2_exprs passes the encoded slots on) */ + if (res.status == TEST_PASS) { + ray_t* r[2]; agg_route_stats_t st[2]; + for (int gi = 0; gi < 2; gi++) { + ray_t* t = gi ? t2 : t0; + ray_graph_t* g = ray_graph_new(t); + ray_op_t* keys[1] = { ray_scan(g, "k0") }; + uint16_t ops[1] = { OP_SUM }; + ray_op_t* ins[1] = { ray_add(g, ray_scan(g, "a"), ray_mul(g, ray_scan(g, "b"), ray_const_i64(g, 3))) }; + agg_route_reset(); + r[gi] = ray_execute(g, ray_group(g, keys, 1, ops, ins, 1)); + if (r[gi] && ray_is_lazy(r[gi])) r[gi] = ray_lazy_materialize(r[gi]); + st[gi] = agg_route_stats(); + ray_graph_free(g); + } + TEST_ASSERT_TRUE(r[0] && r[1] && !RAY_IS_ERR(r[0]) && !RAY_IS_ERR(r[1])); + TEST_ASSERT_TRUE(memcmp(st[0].routes, st[1].routes, sizeof st[0].routes) == 0); + TEST_ASSERT_TRUE(cp_fmt_same(r[0], r[1])); + ray_release(r[0]); ray_release(r[1]); + } + ray_release(t0); ray_release(t2); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(cores), RAY_OK); + return res; +} + +/* The slice-group route is taken on a table loaded from generation 2 with a + * recorded index, as it is on generation 0. */ +static test_result_t gp_slice_route(const char* dir, bool compress, ray_t** out) { + TEST_ASSERT_STR_EQ(ev_code("(set SY ['aa 'bb 'cc 'dd 'ee 'ff 'gg 'hh])"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set KS (as 'SYM (at SY (% (til 4000) 8))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set FF (* 0.5 (as 'F64 (% (til 4000) 64))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set TI (table [s f] (list (.attr.set 'grouped KS) FF)))"), ""); + char cmd[400]; + snprintf(cmd, sizeof cmd, "(.db.splayed.set \"%s\" TI {compress: %s})", dir, compress ? "true" : "false"); + TEST_ASSERT_STR_EQ(ev_code(cmd), ""); + snprintf(cmd, sizeof cmd, "(set TL (.db.splayed.get \"%s\"))", dir); + TEST_ASSERT_STR_EQ(ev_code(cmd), ""); + uint64_t hits0 = ray_idx_hits[IDX_SITE_GROUP_SLICE]; + *out = ray_eval_str("(select {sv: (sum f) c: (count f) from: TL by: s asc: s where: (in s ['aa 'cc])})"); + TEST_ASSERT_TRUE(*out && !RAY_IS_ERR(*out)); + TEST_ASSERT_FMT(ray_idx_hits[IDX_SITE_GROUP_SLICE] == hits0 + 1, "%s: slice path ran %llu times", compress ? "gen 2" : "gen 0", + (unsigned long long)(ray_idx_hits[IDX_SITE_GROUP_SLICE] - hits0)); + PASS(); +} + +static test_result_t test_group_sites_slice_route(void) { + ray_t *a = NULL, *b = NULL; + test_result_t r = gp_slice_route(ray_test_tmp(CS_TMP "/sl0"), false, &a); + if (r.status != TEST_PASS) return r; + r = gp_slice_route(ray_test_tmp(CS_TMP "/sl2"), true, &b); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_TRUE(cp_fmt_same(a, b) && ray_table_nrows(a) == 2); + ray_release(a); ray_release(b); + PASS(); +} + +/* Parted group-by: the per-partition route (MAPCOMMON key), the concat + * fallback (a parted key) and the pass of encoded segments take the same + * routes and give the same answers on generation 0 and 2; a segment that + * fails to materialize is the query's error. */ + +/* An expression key ((b % 7), per-partition materialized over the borrowed + * segments) or an expression aggregate ((a + b)) over a group. */ +static ray_t* gp_expr_body(ray_t* t, bool expr_key) { + ray_graph_t* g = ray_graph_new(t); + ray_op_t* keys[1] = { expr_key ? ray_mod(g, ray_scan(g, "b"), ray_const_i64(g, 7)) : ray_scan(g, "date") }; + uint16_t ops[1] = { OP_SUM }; + ray_op_t* ins[1] = { expr_key ? ray_scan(g, "a") : ray_add(g, ray_scan(g, "a"), ray_scan(g, "b")) }; + ray_t* r = ray_execute(g, ray_group(g, keys, 1, ops, ins, 1)); + if (r && ray_is_lazy(r)) r = ray_lazy_materialize(r); + ray_graph_free(g); + return r; +} +static test_result_t gp_expr_same(ray_t* t0, ray_t* t2, bool expr_key, bool want_parted, const char* what) { + agg_route_reset(); ray_t* r0 = gp_expr_body(t0, expr_key); agg_route_stats_t s0 = agg_route_stats(); + agg_route_reset(); ray_t* r2 = gp_expr_body(t2, expr_key); agg_route_stats_t s2 = agg_route_stats(); + TEST_ASSERT_FMT(r0 && r2 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r2), "%s: ran", what); + if (want_parted) TEST_ASSERT_FMT(s0.routes[AGG_ROUTE_PARTED] >= 1, "%s: parted route", what); + TEST_ASSERT_FMT(memcmp(s0.routes, s2.routes, sizeof s0.routes) == 0, "%s: routes differ", what); + TEST_ASSERT_FMT(cp_fmt_same(r0, r2), "%s: answers differ", what); + ray_release(r0); ray_release(r2); + PASS(); +} +static test_result_t test_group_sites_parted(void) { + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/gp0"), 0, false); + ray_t* t2 = pdb_make(ray_test_tmp(CS_TMP "/gp2"), 7, false); + TEST_ASSERT_TRUE(t0 && t2); + static const struct { const char* key; uint16_t op; const char* c1; } cases[] = { + { "date", OP_SUM, "a" }, /* per-partition */ + { "date", OP_AVG, "b" }, /* per-partition with the AVG decomposition */ + { "a", OP_SUM, "b" }, /* high cardinality: concat fallback */ + }; + test_result_t res = { TEST_PASS, NULL }; + for (size_t i = 0; i < sizeof cases / sizeof *cases && res.status == TEST_PASS; i++) { + gp_ctx_t c0 = { t0, cases[i].key, cases[i].op, cases[i].c1, NULL }; + gp_ctx_t c2 = { t2, cases[i].key, cases[i].op, cases[i].c1, NULL }; + agg_route_reset(); ray_t* r0 = gp_body(&c0); agg_route_stats_t s0 = agg_route_stats(); + agg_route_reset(); ray_t* r2 = gp_body(&c2); agg_route_stats_t s2 = agg_route_stats(); + TEST_ASSERT_FMT(r0 && r2 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r2), "case %zu ran", i); + TEST_ASSERT_FMT(s0.routes[AGG_ROUTE_PARTED] >= 1, "case %zu: parted route", i); + TEST_ASSERT_FMT(memcmp(s0.routes, s2.routes, sizeof s0.routes) == 0, "case %zu: routes differ", i); + TEST_ASSERT_FMT(cp_fmt_same(r0, r2), "case %zu: answers differ", i); + ray_release(r0); ray_release(r2); + } + /* a table mixing generations (partitions 1 and 3 on generation 2) and the + * expression key / aggregate shapes over encoded and mixed segments */ + ray_t* t5 = pdb_make(ray_test_tmp(CS_TMP "/gp5"), 5, false); + TEST_ASSERT_TRUE(t5); + for (int i = 0; i < 3 && res.status == TEST_PASS; i++) { + gp_ctx_t c0 = { t0, cases[i].key, cases[i].op, cases[i].c1, NULL }; + gp_ctx_t c5 = { t5, cases[i].key, cases[i].op, cases[i].c1, NULL }; + agg_route_reset(); ray_t* r0 = gp_body(&c0); agg_route_stats_t s0 = agg_route_stats(); + agg_route_reset(); ray_t* r5 = gp_body(&c5); agg_route_stats_t s5 = agg_route_stats(); + TEST_ASSERT_FMT(r0 && r5 && !RAY_IS_ERR(r0) && !RAY_IS_ERR(r5), "mixed case %d ran", i); + TEST_ASSERT_FMT(memcmp(s0.routes, s5.routes, sizeof s0.routes) == 0, "mixed case %d: routes differ", i); + TEST_ASSERT_FMT(cp_fmt_same(r0, r5), "mixed case %d: answers differ", i); + ray_release(r0); ray_release(r5); + } + res = gp_expr_same(t0, t2, true, true, "expression key, encoded"); + if (res.status == TEST_PASS) res = gp_expr_same(t0, t5, true, true, "expression key, mixed"); + if (res.status == TEST_PASS) res = gp_expr_same(t0, t2, false, true, "expression aggregate, encoded"); + if (res.status == TEST_PASS) res = gp_expr_same(t0, t5, false, true, "expression aggregate, mixed"); + ray_release(t5); + ray_release(t0); ray_release(t2); + return res; +} + +/* ---- Task 29: joins, table ops and Datalog ---- */ + +/* A table of plain I64 columns saved under `dir` at generation `gen` and + * loaded back. */ +static ray_t* t29_disk(const char* dir, const char* const* names, const int64_t* mul, int nc, int64_t n, + int gen) { + char p[300]; + (void)ray_test_rm_rf(dir); + (void)ray_test_mkdir_p(dir); + ray_t* nm = ray_vec_new(RAY_STR, nc); + for (int j = 0; j < nc; j++) { + ray_t* c = i64_col(n, mul[j]); + snprintf(p, sizeof p, "%s/%s", dir, names[j]); + ray_col_save_gen(c, p, gen); + ray_release(c); + nm = ray_str_vec_append(nm, names[j], strlen(names[j])); + } + snprintf(p, sizeof p, "%s/.d", dir); + ray_col_save(nm, p); + ray_release(nm); + return ray_read_splayed(dir, NULL); +} + +static ray_t* t29_plain(const char* n0, const int64_t* v0, const char* n1, const int64_t* v1, int64_t n) { + ray_t* t = ray_table_new(2); + ray_t* a = ray_vec_from_raw(RAY_I64, v0, n); + ray_t* b = ray_vec_from_raw(RAY_I64, v1, n); + t = ray_table_add_col(t, ray_sym_intern(n0, strlen(n0)), a); + t = ray_table_add_col(t, ray_sym_intern(n1, strlen(n1)), b); + ray_release(a); ray_release(b); + return t; +} + +/* kind 0 join (type jt), 1 anti-join, 2 window join (time key lk, optional eq key). */ +static ray_t* t29_join(ray_t* lt, ray_t* rt, int kind, const char* lk, const char* rk, uint8_t jt, const char* eq) { + ray_graph_t* g = ray_graph_new(lt); + ray_op_t* ln = ray_const_table(g, lt); + ray_op_t* rn = ray_const_table(g, rt); + ray_op_t* root; + if (kind == 2) { + ray_op_t* eqk[1] = { eq ? ray_scan(g, eq) : NULL }; + root = ray_asof_join(g, ln, rn, ray_scan(g, lk), eq ? eqk : NULL, eq ? 1 : 0, jt); + } else { + ray_op_t* l1[1] = { ray_scan(g, lk) }; + ray_op_t* r1[1] = { ray_scan(g, rk) }; + root = kind == 1 ? ray_antijoin(g, ln, l1, rn, r1, 1) : ray_join(g, ln, l1, rn, r1, 1, jt); + root = ray_optimize(g, root); + } + ray_error_clear(); + ray_t* r = ray_execute(g, root); + if (r && ray_is_lazy(r)) r = ray_lazy_materialize(r); + ray_graph_free(g); + return r; +} + +/* Equal serialized bytes: same shape, names, values and nulls. */ +static bool t29_same(ray_t* x, ray_t* y) { + if (!x || !y || RAY_IS_ERR(x) || RAY_IS_ERR(y)) return false; + ray_t* sx = ray_ser(x); ray_t* sy = ray_ser(y); + bool same = sx && sy && !RAY_IS_ERR(sx) && !RAY_IS_ERR(sy) && sx->len == sy->len && + memcmp(ray_data(sx), ray_data(sy), (size_t)sx->len) == 0; + if (sx && !RAY_IS_ERR(sx)) ray_release(sx); + if (sy && !RAY_IS_ERR(sy)) ray_release(sy); + return same; +} + +/* Generation 0 and 2 (and a select result of generation 2) join to the same + * rows, and the null-free key proof is taken on exactly the same joins. */ +static test_result_t test_join_sites_gen2_equal(void) { + TEST_ASSERT_TRUE(cp_save()); + ray_t* t0 = cp_read(0); ray_t* t2 = cp_read(2); + TEST_ASSERT_TRUE(t0 && t2 && !RAY_IS_ERR(t0) && !RAY_IS_ERR(t2)); + int64_t k0v[4] = { 0, 1, 2, 3 }, wv[4] = { 10, 20, 30, 40 }; + ray_t* RK = t29_plain("k0", k0v, "w", wv, 4); + enum { RT_N = 10000 }; + static int64_t tv[RT_N], rvv[RT_N], rk0[RT_N]; + for (int64_t j = 0; j < RT_N; j++) { tv[j] = j * 7000000; rvv[j] = j; rk0[j] = j % 4; } + ray_t* RT = t29_plain("k4", tv, "rv", rvv, RT_N); + ray_t* RT2 = ray_table_new(3); + { + ray_t* a = ray_vec_from_raw(RAY_I64, rk0, RT_N); ray_t* b = ray_vec_from_raw(RAY_I64, tv, RT_N); + ray_t* c = ray_vec_from_raw(RAY_I64, rvv, RT_N); + RT2 = ray_table_add_col(RT2, ray_sym_intern("k0", 2), a); + RT2 = ray_table_add_col(RT2, ray_sym_intern("k4", 2), b); + RT2 = ray_table_add_col(RT2, ray_sym_intern("rv", 2), c); + ray_release(a); ray_release(b); ray_release(c); + } + ray_t* RX = ray_table_new(2); + { + ray_t* x = ray_sym_vec_new(RAY_SYM_W64, 2); x->len = 2; + ((int64_t*)ray_data(x))[0] = ray_sym_intern("xa", 2); ((int64_t*)ray_data(x))[1] = ray_sym_intern("xb", 2); + ray_t* w = ray_vec_from_raw(RAY_I64, wv, 2); + RX = ray_table_add_col(RX, ray_sym_intern("x", 1), x); + RX = ray_table_add_col(RX, ray_sym_intern("wx", 2), w); + ray_release(x); ray_release(w); + } + /* a select result of each: the encoded slots of generation 2 pass through */ + ray_t* sel[2]; + for (int gi = 0; gi < 2; gi++) { + ray_t* t = gi ? t2 : t0; + ray_graph_t* g = ray_graph_new(t); + ray_op_t* cs[4] = { ray_scan(g, "k0"), ray_scan(g, "x"), ray_scan(g, "k4"), ray_scan(g, "a") }; + sel[gi] = ray_execute(g, ray_select_op(g, ray_const_table(g, t), cs, 4)); + ray_graph_free(g); + TEST_ASSERT_TRUE(sel[gi] && !RAY_IS_ERR(sel[gi]) && sel[gi]->type == RAY_TABLE); + } + TEST_ASSERT_TRUE(ray_table_get_col_enc(sel[1], ray_sym_intern("a", 1)) != NULL); + static const struct { int src; int kind; bool t_left; const char* lk; const char* rk; uint8_t jt; const char* eq; int rhs; const char* what; } cs[] = { + { 0, 0, true, "k0", "k0", 0, NULL, 0, "inner k0" }, + { 0, 0, true, "k0", "k0", 1, NULL, 0, "left k0" }, + { 0, 1, true, "k0", "k0", 0, NULL, 0, "anti k0" }, + { 0, 0, false, "k0", "k0", 0, NULL, 0, "inner, table on the right" }, + { 0, 0, true, "x", "x", 0, NULL, 1, "inner nullable SYM key" }, + { 0, 0, true, "x", "x", 1, NULL, 1, "left nullable SYM key" }, + { 0, 1, true, "x", "x", 0, NULL, 1, "anti nullable SYM key" }, + { 0, 2, true, "k4", "k4", 0, NULL, 2, "window join" }, + { 0, 2, true, "k4", "k4", 1, NULL, 2, "window join, left" }, + { 0, 2, true, "k4", "k4", 0, "k0", 3, "window join with an equality key" }, + { 1, 0, true, "k0", "k0", 0, NULL, 0, "select result, inner k0" }, + { 1, 0, true, "x", "x", 1, NULL, 1, "select result, left nullable SYM key" }, + { 1, 1, true, "k0", "k0", 0, NULL, 0, "select result, anti k0" }, + { 1, 2, true, "k4", "k4", 0, NULL, 2, "select result, window join" }, + }; + test_result_t res = { TEST_PASS, NULL }; + ray_t* rhs[4] = { RK, RX, RT, RT2 }; + for (size_t i = 0; i < sizeof cs / sizeof *cs && res.status == TEST_PASS; i++) { + ray_t* a = cs[i].src ? sel[0] : t0; + ray_t* b = cs[i].src ? sel[1] : t2; + ray_t* r[2]; uint64_t nf[2]; + for (int gi = 0; gi < 2; gi++) { + ray_t* t = gi ? b : a; + uint64_t before = ray_join_nullfree_keys; + r[gi] = cs[i].t_left ? t29_join(t, rhs[cs[i].rhs], cs[i].kind, cs[i].lk, cs[i].rk, cs[i].jt, cs[i].eq) + : t29_join(rhs[cs[i].rhs], t, cs[i].kind, cs[i].lk, cs[i].rk, cs[i].jt, cs[i].eq); + nf[gi] = ray_join_nullfree_keys - before; + } + if (!(r[0] && r[1] && !RAY_IS_ERR(r[0]) && !RAY_IS_ERR(r[1]))) { + res = (test_result_t){ TEST_FAIL, "join did not run" }; + fprintf(stderr, " %s: join did not run (%s / %s)\n", cs[i].what, + r[0] && RAY_IS_ERR(r[0]) ? ray_err_code(r[0]) : "ok", r[1] && RAY_IS_ERR(r[1]) ? ray_err_code(r[1]) : "ok"); + } else if (nf[0] != nf[1]) { + res = (test_result_t){ TEST_FAIL, "null-free proof differs" }; + fprintf(stderr, " %s: null-free proofs %llu vs %llu\n", cs[i].what, (unsigned long long)nf[0], (unsigned long long)nf[1]); + } else if (!t29_same(r[0], r[1])) { + res = (test_result_t){ TEST_FAIL, "join answers differ" }; + fprintf(stderr, " %s: answers differ\n", cs[i].what); + } + for (int gi = 0; gi < 2; gi++) if (r[gi]) { if (RAY_IS_ERR(r[gi])) ray_error_free(r[gi]); else ray_release(r[gi]); } + } + ray_release(sel[0]); ray_release(sel[1]); + ray_release(RK); ray_release(RT); ray_release(RT2); ray_release(RX); + ray_release(t0); ray_release(t2); + return res; +} + +/* A table of 2000 rows (a unique id, a key, a nullable value, a float and a + * symbol) saved at generation 0 and 2 under tb0 / tb2. */ +static bool t29_tb_save(void) { + enum { N = 2000 }; + ray_t* t = ray_table_new(5); + ray_t* u = ray_vec_new(RAY_I64, N); u->len = N; + ray_t* k = ray_vec_new(RAY_I64, N); k->len = N; + ray_t* v = ray_vec_new(RAY_I64, N); v->len = N; + ray_t* f = ray_vec_new(RAY_F64, N); f->len = N; + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, N); s->len = N; + static const char* const nm[4] = { "pa", "pb", "pc", "pd" }; + for (int64_t i = 0; i < N; i++) { + ((int64_t*)ray_data(u))[i] = i; + ((int64_t*)ray_data(k))[i] = i % 10; + ((int64_t*)ray_data(v))[i] = i * 3; + ((double*)ray_data(f))[i] = (double)(i % 7) * 0.5; + ((int64_t*)ray_data(s))[i] = ray_sym_intern(nm[i % 4], 2); + } + for (int64_t i = 0; i < N; i += 9) ray_vec_set_null(v, i, true); + t = ray_table_add_col(t, ray_sym_intern("u", 1), u); + t = ray_table_add_col(t, ray_sym_intern("k", 1), k); + t = ray_table_add_col(t, ray_sym_intern("v", 1), v); + t = ray_table_add_col(t, ray_sym_intern("f", 1), f); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + ray_release(u); ray_release(k); ray_release(v); ray_release(f); ray_release(s); + bool ok = ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/tb0"), ray_test_tmp(CS_TMP "/tb0.sym"), RAY_COMPRESS_OFF) == RAY_OK && + ray_splay_save_mode(t, ray_test_tmp(CS_TMP "/tb2"), ray_test_tmp(CS_TMP "/tb2.sym"), RAY_COMPRESS_ON) == RAY_OK; + ray_release(t); + return ok; +} + +/* pivot and the table builtins give the generation-0 answer on a generation-2 + * table and on tables that carry its encoded slots (xcol, xcols, modify). */ +static test_result_t test_tblop_sites_gen2_equal(void) { + TEST_ASSERT_TRUE(t29_tb_save()); + ray_t* t0 = ray_read_splayed(ray_test_tmp(CS_TMP "/tb0"), ray_test_tmp(CS_TMP "/tb0.sym")); + ray_t* t2 = ray_read_splayed(ray_test_tmp(CS_TMP "/tb2"), ray_test_tmp(CS_TMP "/tb2.sym")); + TEST_ASSERT_TRUE(t0 && t2 && !RAY_IS_ERR(t0) && !RAY_IS_ERR(t2)); + TEST_ASSERT_TRUE(ray_table_get_col_enc(t2, ray_sym_intern("u", 1)) != NULL); + TEST_ASSERT_TRUE(ray_table_get_col_enc(t0, ray_sym_intern("u", 1)) == NULL); + static const char* const verbs[] = { + "(pivot T 'k 's 'u sum)", "(pivot T 'k 'f 'u sum)", "(pivot T ['k] 's 'v avg)", + "(pivot T 'k 's 'u (fn [x] (sum x)))", + "(xcol T ['A 'B 'C 'D 'E])", "(xcols T ['v 'k])", "(xkey T ['u])", "(xgroup T ['k])", "(fkeys T)", + "(modify T 'v (fn [c] (+ c 1)))", "(modify T 'u (fn [c] c))", "(union-all T T)", + "(distinct (xcols T ['k 's]))", + }; + int64_t sT = ray_sym_intern("T", 1); + for (size_t i = 0; i < sizeof verbs / sizeof *verbs; i++) { + ray_t* r[2]; + for (int gi = 0; gi < 2; gi++) { + ray_env_set(sT, gi ? t2 : t0); + ray_error_clear(); + r[gi] = ray_eval_str(verbs[i]); + } + bool ok = r[0] && r[1] && !RAY_IS_ERR(r[0]) && !RAY_IS_ERR(r[1]) && t29_same(r[0], r[1]); + if (!ok) fprintf(stderr, " %s: %s / %s\n", verbs[i], r[0] && RAY_IS_ERR(r[0]) ? ray_err_code(r[0]) : "ok", + r[1] && RAY_IS_ERR(r[1]) ? ray_err_code(r[1]) : "ok"); + for (int gi = 0; gi < 2; gi++) if (r[gi]) { if (RAY_IS_ERR(r[gi])) ray_error_free(r[gi]); else ray_release(r[gi]); } + TEST_ASSERT_FMT(ok, "%s: answers differ", verbs[i]); + } + /* the slot-passing builtins keep the encoded object (no decode) */ + ray_env_set(sT, t2); + ray_t* xc = ray_eval_str("(xcols T ['u])"); + TEST_ASSERT_TRUE(xc && !RAY_IS_ERR(xc) && ray_table_get_col_enc(xc, ray_sym_intern("u", 1)) != NULL); + ray_release(xc); + ray_env_set(sT, NULL); + ray_release(t0); ray_release(t2); + PASS(); +} + +/* Builtins that never read the encoded column a do not decode it. */ +static test_result_t test_tblop_sites_lazy(void) { + ray_t* t = bind_mixed_table(); + TEST_ASSERT_TRUE(t != NULL && !RAY_IS_ERR(t)); + static const char* const good[] = { + "(xcol t ['x 'y])", "(xcols t ['a 'b])", "(fkeys t)", "(modify t 'b (fn [c] c))", + }; + for (size_t i = 0; i < sizeof good / sizeof *good; i++) { + ray_error_clear(); + ray_enc_counters_reset(); + ray_t* r = ray_eval_str(good[i]); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "%s: ran", good[i]); + TEST_ASSERT_FMT(c.materialized == 0, "%s: must not decode column a", good[i]); + ray_release(r); + } + ray_release(t); + PASS(); +} + +/* A recursive program with provenance over an EDB loaded from generation 0 + * and 2 derives the same relation and the same proofs; so does a query over + * env-bound tables. */ +static ray_t* t29_dl_run(ray_t* edge, ray_t** prov_off, ray_t** prov_data) { + dl_program_t* prog = dl_program_new(); + if (!prog) return NULL; + prog->flags |= DL_FLAG_PROVENANCE; + dl_add_edb(prog, "edge", edge, 2); + dl_rule_t r0; dl_rule_init(&r0, "path", 2); + dl_rule_head_var(&r0, 0, 0); dl_rule_head_var(&r0, 1, 1); + int b = dl_rule_add_atom(&r0, "edge", 2); + dl_body_set_var(&r0, b, 0, 0); dl_body_set_var(&r0, b, 1, 1); + r0.n_vars = 2; + dl_add_rule(prog, &r0); + dl_rule_t r1; dl_rule_init(&r1, "path", 2); + dl_rule_head_var(&r1, 0, 0); dl_rule_head_var(&r1, 1, 2); + int b0 = dl_rule_add_atom(&r1, "path", 2); + dl_body_set_var(&r1, b0, 0, 0); dl_body_set_var(&r1, b0, 1, 1); + int b1 = dl_rule_add_atom(&r1, "edge", 2); + dl_body_set_var(&r1, b1, 0, 1); dl_body_set_var(&r1, b1, 1, 2); + r1.n_vars = 3; + dl_add_rule(prog, &r1); + ray_t* out = NULL; + if (dl_eval(prog) == 0) { + out = dl_query(prog, "path"); + if (out) ray_retain(out); + ray_t* o = dl_get_provenance_src_offsets(prog, "path"); + ray_t* d = dl_get_provenance_src_data(prog, "path"); + *prov_off = o ? (ray_retain(o), o) : NULL; + *prov_data = d ? (ray_retain(d), d) : NULL; + } + dl_program_free(prog); + return out; +} + +static test_result_t test_datalog_sites_gen2_equal(void) { + static const char* const nm[2] = { "s", "d" }; + static const int64_t mul[2] = { 1, 1 }; + ray_t* e[2]; ray_t* out[2]; ray_t* po[2] = { NULL, NULL }; ray_t* pd[2] = { NULL, NULL }; + for (int gi = 0; gi < 2; gi++) { + e[gi] = t29_disk(gi ? ray_test_tmp(CS_TMP "/e2") : ray_test_tmp(CS_TMP "/e0"), nm, mul, 2, 30, gi ? 2 : 0); + TEST_ASSERT_TRUE(e[gi] && !RAY_IS_ERR(e[gi])); + /* d = s + 1: shift the destination column through a derived table */ + ray_t* s = ray_table_col(e[gi], ray_sym_intern("s", 1)); + ray_t* dd = ray_vec_new(RAY_I64, 30); dd->len = 30; + for (int64_t i = 0; i < 30; i++) ((int64_t*)ray_data(dd))[i] = ((int64_t*)ray_data(s))[i] + 1; + ray_t* te = ray_table_new(2); + ray_t* sc = gi ? ray_table_get_col_enc(e[gi], ray_sym_intern("s", 1)) : s; + te = ray_table_add_col(te, ray_sym_intern("s", 1), sc); + te = ray_table_add_col(te, ray_sym_intern("d", 1), dd); + ray_release(dd); + ray_release(e[gi]); + e[gi] = te; + out[gi] = t29_dl_run(e[gi], &po[gi], &pd[gi]); + } + TEST_ASSERT_TRUE(ray_table_get_col_enc(e[1], ray_sym_intern("s", 1)) != NULL); + TEST_ASSERT_TRUE(out[0] && out[1] && ray_table_nrows(out[0]) == 30 * 31 / 2); + TEST_ASSERT_TRUE(t29_same(out[0], out[1])); + TEST_ASSERT_TRUE(po[0] && po[1] && t29_same(po[0], po[1])); + TEST_ASSERT_TRUE(pd[0] && pd[1] && t29_same(pd[0], pd[1])); + for (int gi = 0; gi < 2; gi++) { ray_release(out[gi]); ray_release(po[gi]); ray_release(pd[gi]); ray_release(e[gi]); } + PASS(); +} + +static test_result_t test_datalog_query_gen2_equal(void) { + static const char* const nm3[3] = { "e", "a", "v" }; + static const int64_t mul3[3] = { 1, 1, 10 }; + static const char* const nm2[2] = { "p", "q" }; + static const int64_t mul2[2] = { 1, 100 }; + ray_t* r[2]; + for (int gi = 0; gi < 2; gi++) { + ray_t* db = t29_disk(gi ? ray_test_tmp(CS_TMP "/q2") : ray_test_tmp(CS_TMP "/q0"), nm3, mul3, 3, 50, gi ? 2 : 0); + ray_t* ex = t29_disk(gi ? ray_test_tmp(CS_TMP "/x2") : ray_test_tmp(CS_TMP "/x0"), nm2, mul2, 2, 50, gi ? 2 : 0); + TEST_ASSERT_TRUE(db && ex && !RAY_IS_ERR(db) && !RAY_IS_ERR(ex)); + if (gi) TEST_ASSERT_TRUE(ray_table_get_col_enc(ex, ray_sym_intern("p", 1)) != NULL); + ray_env_set(ray_sym_intern("qdb", 3), db); + ray_env_set(ray_sym_intern("extra", 5), ex); + ray_error_clear(); + r[gi] = ray_eval_str("(query qdb (find ?x ?b) (where (eav ?x ?p ?v) (extra ?x ?b)))"); + ray_env_set(ray_sym_intern("qdb", 3), NULL); + ray_env_set(ray_sym_intern("extra", 5), NULL); + ray_release(db); ray_release(ex); + } + TEST_ASSERT_TRUE(r[0] && r[1] && !RAY_IS_ERR(r[0]) && !RAY_IS_ERR(r[1])); + TEST_ASSERT_EQ_I((int)ray_table_nrows(r[0]), 50); + TEST_ASSERT_TRUE(t29_same(r[0], r[1])); + ray_release(r[0]); ray_release(r[1]); + PASS(); +} + +/* Update, delete, upsert refusal and the live-tail insert over a parted table + * whose segments are partly or wholly encoded give the generation-0 answer: + * the verbs read the encoded wrappers through the accessors. */ +static test_result_t test_dml_parted_gen2(void) { + static const unsigned masks[] = { 0, 7, 5 }; + static const char* const qs[] = { + "(sum (at (update {a: (* a 2) from: pt where: (> b 6)}) 'a))", + "(sum (at (update {a: (+ a b) from: pt}) 'a))", + "(count (delete {from: pt where: (== b 6)}))", + "(sum (at (delete {from: pt where: (== b 6)}) 'a))", + "(count (insert pt 2024.01.03 (list 7 8)))", + "(sum (at (insert pt 2024.01.04 (list 7 8)) 'b))", + }; + int64_t want[sizeof qs / sizeof *qs]; + for (int m = 0; m < 3; m++) { + char dir[64]; snprintf(dir, sizeof dir, ray_test_tmp(CS_TMP "/dp%d"), m); + ray_t* t = pdb_make(dir, masks[m], false); + TEST_ASSERT_NOT_NULL(t); + if (m) TEST_ASSERT_TRUE(ray_table_get_col_enc(t, ray_sym_intern("a", 1)) != NULL); + ray_env_set(ray_sym_intern("pt", 2), t); + ray_release(t); + int64_t sum0 = ev_i64("(sum (at pt 'a))"), sumb0 = ev_i64("(sum (at pt 'b))"); + TEST_ASSERT_TRUE(sum0 != INT64_MIN && sumb0 != INT64_MIN); + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + int64_t v = ev_i64(qs[i]); + TEST_ASSERT_FMT(v != INT64_MIN, "%s (mask %u): %s", qs[i], masks[m], ev_code(qs[i])); + if (m == 0) want[i] = v; + else TEST_ASSERT_FMT(v == want[i], "%s (mask %u): %lld vs %lld", qs[i], masks[m], + (long long)v, (long long)want[i]); + } + TEST_ASSERT_STR_EQ(ev_code("(upsert pt 'a (list 1 2))"), "nyi"); + /* the by-value verbs left the bound table as it was */ + TEST_ASSERT_EQ_I(ev_i64("(count pt)"), 9000); + TEST_ASSERT_EQ_I(ev_i64("(sum (at pt 'a))"), sum0); + TEST_ASSERT_EQ_I(ev_i64("(sum (at pt 'b))"), sumb0); + ray_env_set(ray_sym_intern("pt", 2), NULL); + } + PASS(); +} + +/* The live-tail insert still refuses a parted target whose column-list + * container is not canonical (a LIST with zero attrs, as long as the schema), + * and accepts the canonical one. */ +static test_result_t test_parted_insert_container(void) { + ray_t* t = pdb_make(ray_test_tmp(CS_TMP "/pc"), 7, false); + TEST_ASSERT_NOT_NULL(t); + ray_env_set(ray_sym_intern("pt", 2), t); + ray_t* cols = ((ray_t**)ray_data(t))[1]; /* test-only container edits, restored */ + const char* q = "(insert pt 2024.01.03 (list 7 8))"; + uint8_t a0 = cols->attrs; + cols->attrs = 1; + ray_error_clear(); + TEST_ASSERT_STR_EQ(ev_code(q), "corrupt"); + cols->attrs = a0; + int8_t t0 = cols->type; + cols->type = RAY_I64; + TEST_ASSERT_STR_EQ(ev_code(q), "corrupt"); + cols->type = t0; + int64_t n0 = cols->len; + cols->len = n0 + 1; + TEST_ASSERT_STR_EQ(ev_code(q), "corrupt"); + cols->len = n0; + TEST_ASSERT_EQ_I(ev_i64("(count (insert pt 2024.01.03 (list 7 8)))"), 9001); + ray_env_set(ray_sym_intern("pt", 2), NULL); + ray_release(t); + PASS(); +} + +/* A join over a parted table whose segments are partly or wholly encoded + * (join_parted_seg_count, join_table_has_parted_col, the per-segment and + * flatten routes) gives the generation-0 answer, on either side. */ +static test_result_t test_join_sites_parted(void) { + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/jp0"), 0, false); + TEST_ASSERT_NOT_NULL(t0); + static const unsigned masks[] = { 7, 5 }; + int64_t pv[3000], cv[3000]; + for (int64_t i = 0; i < 3000; i++) { pv[i] = 5 * i + (i % 3); cv[i] = i; } + ray_t* P = t29_plain("b", pv, "c", cv, 3000); + for (int m = 0; m < 2; m++) { + char dir[64]; snprintf(dir, sizeof dir, ray_test_tmp(CS_TMP "/jp%d"), m + 1); + ray_t* tm = pdb_make(dir, masks[m], false); + TEST_ASSERT_NOT_NULL(tm); + for (int c = 0; c < 6; c++) { + int kind = c % 3 == 2 ? 1 : 0; + uint8_t jt = c % 3 == 1 ? 1 : 0; + bool parted_left = c < 3; + ray_t* r0 = parted_left ? t29_join(t0, P, kind, "b", "b", jt, NULL) : t29_join(P, t0, kind, "b", "b", jt, NULL); + ray_t* rm = parted_left ? t29_join(tm, P, kind, "b", "b", jt, NULL) : t29_join(P, tm, kind, "b", "b", jt, NULL); + bool ok = r0 && rm && !RAY_IS_ERR(r0) && !RAY_IS_ERR(rm) && t29_same(r0, rm); + if (r0) { if (RAY_IS_ERR(r0)) ray_error_free(r0); else ray_release(r0); } + if (rm) { if (RAY_IS_ERR(rm)) ray_error_free(rm); else ray_release(rm); } + TEST_ASSERT_FMT(ok, "mask %u case %d: answers differ", masks[m], c); + } + ray_release(tm); + } + ray_release(P); ray_release(t0); + PASS(); +} + +/* ---- Task 30: query.c helpers before the select implementation ---- */ + +/* A scalar aggregate over a column large enough to record CHUNK_ZONE: + * planning must not materialize it to read the synthesized zone. */ +static test_result_t test_scalar_agg_planning_zoned(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['v] (list (til 70000))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/za\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u (.db.splayed.get \"" CS_TMP "/za\"))")), ""); + ray_col_meta_t m; + ray_t* u = ray_eval_str("u"); + TEST_ASSERT_TRUE(ray_table_col_meta(u, ray_sym_intern("v", 1), &m) && m.index_kind == RAY_IDX_CHUNK_ZONE); + ray_release(u); + static const char* const qs[] = { + "(select {s: (sum v) from: u})", "(select {m: (max v) n: (min v) from: u})", "(select {c: (count v) a: (avg v) from: u})", NULL, + }; + for (int i = 0; qs[i]; i++) { + ray_enc_counters_reset(); + ray_t* r = ray_eval_str(qs[i]); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "query %d", i); + ray_release(r); + ray_enc_counters_t c; ray_enc_counters_get(&c); + /* P2 Task 10 (finding C3): answered during planning from the + * directory, as generation 0 answers from its zone, so the query + * never reaches ray_execute (UINT64_MAX) and nothing decodes. */ + TEST_ASSERT_FMT(c.at_first_exec == UINT64_MAX && c.materialized == 0, + "query %d: %llu materialized, at first exec %llu", i, + (unsigned long long)c.materialized, (unsigned long long)c.at_first_exec); + } + ray_t* r = ray_eval_str("(sum (at u 'v))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == (int64_t)69999 * 70000 / 2); + ray_release(r); + PASS(); +} + +/* DAG construction names columns by metadata: over a generation-2 table, + * compiling every name form succeeds without decoding, and the DAG runs. */ +static test_result_t test_dag_presence_without_decode(void) { + ray_t* t = ex_table(3000); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + static const char* const forms[] = { "a", "(+ a 1)", "(sum (+ a 1))", "'a", "(neg a)", NULL }; + for (int i = 0; forms[i]; i++) { + ray_graph_t* g = ray_graph_new(t); + ray_t* e = ray_parse(forms[i]); + ray_enc_counters_reset(); + ray_op_t* dag = compile_expr_dag(g, e); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_FMT(dag != NULL, "form %s: compiled", forms[i]); + TEST_ASSERT_FMT(c.materialized == 0, "form %s: construction decoded", forms[i]); + if (dag) { + ray_error_clear(); + ray_t* r = ray_execute(g, ray_optimize(g, dag)); + if (r && ray_is_lazy(r)) r = ray_lazy_materialize(r); + bool ran = r && !RAY_IS_ERR(r); + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + if (!ran) { ray_release(e); ray_graph_free(g); ray_release(t); } + TEST_ASSERT_FMT(ran, "form %s: ran", forms[i]); + } + ray_release(e); + ray_graph_free(g); + } + /* an absent name is still absent: a column of another table is not found */ + ray_graph_t* g = ray_graph_new(t); + ray_t* e = ray_parse("nosuchcol"); + ray_op_t* dag = compile_expr_dag(g, e); + ray_t* r = dag ? ray_execute(g, ray_optimize(g, dag)) : NULL; + TEST_ASSERT_TRUE(!dag || (r && RAY_IS_ERR(r))); + if (r && RAY_IS_ERR(r)) ray_error_free(r); + ray_release(e); + ray_graph_free(g); + ray_release(t); + PASS(); +} + +/* Queries over the helpers of this part, on a table read from generation-0 + * and generation-2 files, give the same answer. */ +static test_result_t test_query_helpers_gen2_equal(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 'm 'v 's] (list (% (til 80000) 7) (% (til 80000) 5) (% (* (til 80000) 13) 1000) (take ['aa 'bb 'cc 'dd] 80000))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/q0\" t {compress: false})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/q2\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u0 (.db.splayed.get \"" CS_TMP "/q0\"))")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u2 (.db.splayed.get \"" CS_TMP "/q2\"))")), ""); + ray_t* u2 = ray_eval_str("u2"); + TEST_ASSERT_TRUE(u2 && ray_table_get_col_enc(u2, ray_sym_intern("v", 1)) != NULL); + ray_release(u2); + static const char* const qs[] = { + "(select {c: (count (distinct v)) by: k from: %s})", + "(select {c: (count (distinct v)) by: [k m] from: %s})", + "(select {c: (count (distinct v)) by: k from: %s where: (> v 100)})", + "(select {s: (sum v) a: (avg v) by: k from: %s desc: s take: 3})", + "(select {s: (sum v) by: [k m] from: %s asc: s take: 4})", + "(select {c: (count v) from: %s where: (== k 3)})", + "(select {c: (count v) from: %s where: (> v 500)})", + "(select {c: (count v) by: s from: %s})", + "(select {c: (count v) by: (+ k 1) from: %s})", + "(select {x: (+ (sum v) (count v)) by: k from: %s})", + "(select {x: (med v) y: (max v) by: k from: %s})", + "(select {k: k w: (+ v 1) from: %s take: 5})", + "(select {w: (* v 2) from: %s where: (< k 2) take: 6})", + "(select {s: (sum v) m: (min v) from: %s})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + char q0[256], q2[256]; + snprintf(q0, sizeof q0, qs[i], "u0"); + snprintf(q2, sizeof q2, qs[i], "u2"); + ray_t* a = ray_eval_str(q0); + ray_t* b = ray_eval_str(q2); + bool ok = a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && cp_fmt_same(a, b); + if (!ok) fprintf(stderr, "query_helpers_gen2_equal: %s\n", q2); + if (a && RAY_IS_ERR(a)) ray_error_free(a); else if (a) ray_release(a); + if (b && RAY_IS_ERR(b)) ray_error_free(b); else if (b) ray_release(b); + TEST_ASSERT_FMT(ok, "query %d", i); + } + PASS(); +} + +/* ---- Task 31: ray_select_impl ---- */ + +/* The slice-group probe reads the key's index only after metadata admits it + * (a SYM key with a HASH or PART index). The HASH-indexed SYM key is saved + * as generation 2 with its index rebuilt over the target ids, so the probe + * reads the index its materialization attaches; the slice route runs over + * an encoded aggregate column. */ +static test_result_t test_select_slice_probe_route(void) { + static const char* const cols[] = { "f", NULL }; + for (int c = 0; cols[c]; c++) { + TEST_ASSERT_STR_EQ(ev_code("(set SY ['aa 'bb 'cc 'dd 'ee 'ff 'gg 'hh])"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set KS (as 'SYM (at SY (% (til 4000) 8))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set FF (* 0.5 (as 'F64 (% (til 4000) 64))))"), ""); + TEST_ASSERT_STR_EQ(ev_code("(set TI (table [s f] (list (.attr.set 'grouped KS) FF)))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/sp\" TI {compress: true})")), ""); + char p[128]; snprintf(p, sizeof p, "%s/sp/%s", ray_test_tmp(CS_TMP), cols[c]); + TEST_ASSERT_EQ_U(file_gen(p), 2); + TEST_ASSERT_EQ_U(file_gen(ray_test_tmp(CS_TMP "/sp/s")), 2); /* the HASH-indexed SYM key */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set TL (.db.splayed.get \"" CS_TMP "/sp\"))")), ""); + uint64_t hits0 = ray_idx_hits[IDX_SITE_GROUP_SLICE]; + ray_error_clear(); + ray_t* r = ray_eval_str("(select {sv: (sum f) c: (count f) from: TL by: s asc: s where: (in s ['aa 'cc])})"); + TEST_ASSERT_FMT(ray_idx_hits[IDX_SITE_GROUP_SLICE] == hits0 + 1, "the slice route ran %llu times", + (unsigned long long)(ray_idx_hits[IDX_SITE_GROUP_SLICE] - hits0)); + bool ok = r && !RAY_IS_ERR(r) && r->type == RAY_TABLE && ray_table_nrows(r) == 2; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_FMT(ok, "%s: two groups", cols[c]); + } + PASS(); +} + +/* by-dict values and computed keys bind only the encoded columns they name: + * over a 20-column generation-2 table each query materializes exactly the + * columns it references, and answers as generation 0 does. */ +static test_result_t test_select_bydict_binds_referenced(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k1 'k2 'a 'c03 'c04 'c05 'c06 'c07 'c08 'c09 'c10 'c11 'c12 'c13 'c14 'c15 'c16 'c17 'c18 'c19] " + "(list (% (til 70000) 7) (% (til 70000) 5) (% (* 3 (til 70000)) 1001) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) " + "(til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000) (til 70000))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/w0\" t {compress: false})")), ""); + TEST_ASSERT_STR_EQ(ev_code("(set lam_k2 (fn [] (% k2 2)))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/w2\" t {compress: true})")), ""); + static const struct { const char* q; uint64_t cols; } qs[] = { + { "(select {c: (count a) by: {k1: k1 k2: k2} from: %s})", 0 }, /* P2 Task 13: v2 reads keys by range */ + { "(select {s: (sum a) by: {k1: k1 k2: k2} from: %s})", 0 }, /* P2 Task 13 */ + { "(select {c: (count a) by: {m: (%% a 3)} from: %s})", 1 }, + { "(select {s: (sum a) by: {k1: k1 m: (%% k2 3)} from: %s})", 1 }, /* P2 Task 13: the computed key materializes k2 */ + { "(select {s: (sum a) by: {g: k2} from: %s where: (> a 10)})", 1 }, /* P2 Task 13: a reads by range; the renamed key {g: k2} materializes k2 */ + { "(select {d: (count (distinct a)) by: (%% k2 3) from: %s})", 2 }, + { "(select {c: (count a) by: {g: (lam_k2)} from: %s})", 20 }, /* a lambda may read any column */ + { NULL, 0 }, + }; + for (int i = 0; qs[i].q; i++) { + char q0[256], q2[256]; + snprintf(q0, sizeof q0, qs[i].q, "u0"); + snprintf(q2, sizeof q2, qs[i].q, "u2"); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u0 (.db.splayed.get \"" CS_TMP "/w0\"))")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u2 (.db.splayed.get \"" CS_TMP "/w2\"))")), ""); + ray_t* a = ray_eval_str(q0); + ray_enc_counters_reset(); + ray_t* b = ray_eval_str(q2); + ray_enc_counters_t c; ray_enc_counters_get(&c); + bool same = a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && t29_same(a, b); + if (a && RAY_IS_ERR(a)) ray_error_free(a); else if (a) ray_release(a); + if (b && RAY_IS_ERR(b)) ray_error_free(b); else if (b) ray_release(b); + TEST_ASSERT_FMT(same, "%s: answers differ", q2); + TEST_ASSERT_FMT(c.materialized == qs[i].cols, "%s: materialized %llu, references %llu", + q2, (unsigned long long)c.materialized, (unsigned long long)qs[i].cols); + } + PASS(); +} + +/* A select over a generation-2 table materializes exactly the columns it + * references, never the table's width, for where, by, aggregate and take + * shapes. */ +static test_result_t test_select_decodes_referenced_only(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 'm 'v 'w 'x 'y] (list (% (til 80000) 7) (% (til 80000) 5) (% (* (til 80000) 13) 1000) (% (til 80000) 11) (til 80000) (* 2 (til 80000)))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/rr\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u2 (.db.splayed.get \"" CS_TMP "/rr\"))")), ""); + static const char* const cn[] = { "k", "m", "v", "w", "x", "y" }; + for (int c = 0; c < 6; c++) { + ray_t* u = ray_eval_str("u2"); + bool enc = u && ray_table_get_col_enc(u, ray_sym_intern(cn[c], 1)) != NULL; + ray_release(u); + TEST_ASSERT_FMT(enc, "column %s is encoded", cn[c]); + } + static const struct { const char* q; uint64_t cols; } qs[] = { + { "(select {c: (count v) from: u2 where: (> v 100)})", 0 }, /* P2 Task 10: the scalar route range-reads */ + { "(select {s: (sum v) from: u2 where: (== k 3)})", 0 }, /* P2: k's consult reads the directory; Task 10: v by range */ + { "(select {from: u2 where: (== k 3)})", 0 }, /* every column is output: gathered by range (P3 Task 6) */ + { "(select {s: (sum v) by: k from: u2})", 0 }, /* P2 Task 13: v2 reads by range */ + { "(select {s: (sum v) c: (max w) by: [k m] from: u2})", 0 }, /* P2 Task 13 */ + { "(select {s: (sum v) by: k from: u2 where: (> w 5)})", 0 }, /* P2: w's consult reads the directory; P3 Task 6: the compact gathers by range */ + { "(select {s: (sum v) by: k from: u2 desc: s take: 2})", 0 }, /* P2 Task 13 */ + { "(select {d: (med v) e: (first w) from: u2})", 1 }, /* P2 Task 10: med reads plain v, first w by range */ + { "(select {d: (avg v) e: (dev w) from: u2 where: (< x 1000)})", 0 }, /* P2: x's consult reads the directory; Task 10: v, w by range */ + { "(select {k: k v: v from: u2 take: 5})", 2 }, + { "(select {k: k v: v from: u2 where: (> w 5) take: 5})", 0 }, /* P2: the take scan range-reads w; P3 Task 6: k, v gathered */ + { "(select {v: v from: u2 desc: v take: 3})", 0 }, /* the sort key read by range (fpk_rk_t) */ + { "(select {v: v x: x from: u2 where: (> w 5) asc: x take: 4})", 0 }, /* P2: the top-k scan range-reads w; the sort key x by range too */ + { "(select {z: (+ v x) from: u2 where: (> w 5)})", 0 }, /* P2: a fused side range-reads; w's consult reads the directory */ + { NULL, 0 }, + }; + for (int i = 0; qs[i].q; i++) { + ray_t* u = ray_eval_str(ray_test_tmp("(set u2 (.db.splayed.get \"" CS_TMP "/rr\"))")); /* a fresh load: no cached decode */ + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u)); + ray_release(u); + ray_enc_counters_reset(); + ray_t* r = ray_eval_str(qs[i].q); + ray_enc_counters_t c; ray_enc_counters_get(&c); + bool ok = r && !RAY_IS_ERR(r); + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_FMT(ok, "%s: answered", qs[i].q); + TEST_ASSERT_FMT(c.materialized == qs[i].cols, "%s: materialized %llu, references %llu", + qs[i].q, (unsigned long long)c.materialized, (unsigned long long)qs[i].cols); + } + PASS(); +} + +/* Generation 0 and 2 give the same answers over a broad set of select shapes. */ +static test_result_t test_select_gen2_equal(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 'm 'v 'w 's 'f 'bl 'st 'h] (list (% (til 80000) 7) (% (til 80000) 5) (% (* (til 80000) 13) 1000) (- 40000 (til 80000)) (take ['aa 'bb 'cc 'dd] 80000) (* 0.5 (% (til 80000) 333)) " + "(as 'BOOL (== 0 (% (til 80000) 3))) (as 'STR (take ['red 'green 'blue 'cyan 'magenta] 80000)) (% (til 80000) 60000))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/e0\" t {compress: false})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/e2\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u0 (.db.splayed.get \"" CS_TMP "/e0\"))")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u2 (.db.splayed.get \"" CS_TMP "/e2\"))")), ""); + static const char* const qs[] = { + "(select {from: %s})", + "(select {from: %s where: (== k 3)})", + "(select {from: %s take: 7})", + "(select {from: %s take: -7})", + "(select {from: %s asc: v take: 9})", + "(select {from: %s desc: [k v] take: 9})", + "(select {v: v w: w from: %s where: (> v 990) asc: w})", + "(select {v: v w: w from: %s where: (> v 990) desc: w take: 5})", + "(select {v: v from: %s where: (> w 0) take: 6})", + "(select {v: v from: %s where: (> w 0) take: -6})", + "(select {x: (+ v w) y: (* f 2) from: %s where: (< k 2) take: 8})", + "(select {c: (count v) from: %s})", + "(select {s: (sum v) a: (avg f) mn: (min w) mx: (max w) from: %s})", + "(select {s: (sum v) d: (dev f) from: %s where: (in k [1 2])})", + "(select {d: (med v) from: %s where: (== s 'bb)})", + "(select {s: (sum v) by: k from: %s})", + "(select {s: (sum v) by: s from: %s})", + "(select {s: (sum f) c: (count v) by: [k s] from: %s})", + "(select {s: (sum v) by: k from: %s where: (> w 100)})", + "(select {s: (sum v) by: m from: %s where: (== s 'cc) desc: s})", + "(select {s: (sum v) by: k from: %s asc: s take: 3})", + "(select {f1: (first v) l1: (last w) by: k from: %s})", + "(select {mx: (max f) mn: (min v) by: [m k] from: %s})", + "(select {c: (count (distinct v)) by: m from: %s})", + "(select {c: (count (distinct s)) by: k from: %s where: (> v 10)})", + "(select {x: (+ v 1) by: k from: %s where: (< w -39990)})", + "(select {s: (sum v) by: (%% w 3) from: %s})", + "(select {s: (sum v) by: k from: %s where: (> v 500) desc: s take: 2})", + "(select {a: (avg v) by: k from: %s where: (== s 'aa)})", + "(select {v: v from: %s where: (and (> v 100) (< w 0)) asc: v take: 4})", + "(select {k: k s: s from: %s where: (== v 13) take: 3})", + "(select {q: (* v 2) r: (- w 1) from: %s where: (== k 6) desc: v take: 2})", + "(select {from: %s by: k})", + "(select {from: %s by: m})", + "(select {s: (sum v) by: {k: k} from: %s})", + "(select {s: (sum v) by: {kk: (+ k 1) mm: m} from: %s})", + "(select {c: (count v) by: {k: k kk: (- k 1)} from: %s})", + "(select {s: (sum v) by: bl from: %s})", + "(select {from: %s by: bl})", + "(select {x: (+ v 1) by: st from: %s where: (< w -39990)})", + "(select {m: (max v) x: (+ v 1) by: st from: %s where: (< w -39980)})", + "(select {from: %s by: st})", + "(select {from: %s by: [k f] where: (< w -39900)})", + "(select {from: %s by: k where: (< w -50000)})", + "(select {from: %s by: s where: (< w -50000)})", + "(select {from: %s by: st where: (< w -50000)})", + "(select {s: (sum v) by: k from: %s where: (< w -50000)})", + "(select {s: (sum v) by: (+ k 1) from: %s where: (< w -50000)})", + "(select {s: (sum v) x: (+ v 1) by: k from: %s where: (< w -39990)})", + "(select {c: (count (distinct v)) s: (sum w) by: h from: %s})", + "(select {d: (count (distinct v)) by: (%% m 2) from: %s})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + char q0[256], q2[256]; + snprintf(q0, sizeof q0, qs[i], "u0"); + snprintf(q2, sizeof q2, qs[i], "u2"); + ray_t* a = ray_eval_str(q0); + ray_t* b = ray_eval_str(q2); + bool ok = a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && t29_same(a, b) && cp_fmt_same(a, b); + if (!ok) fprintf(stderr, "select_gen2_equal: %s\n", q2); + if (a && RAY_IS_ERR(a)) ray_error_free(a); else if (a) ray_release(a); + if (b && RAY_IS_ERR(b)) ray_error_free(b); else if (b) ray_release(b); + TEST_ASSERT_FMT(ok, "query %d", i); + } + PASS(); +} + +/* ---- Task 31b: select over a parted table prunes before fetching ---- */ + +/* Select shapes over the parted table t; %s is the where predicate. */ +static const char* const sp_shapes[] = { + "(select {from: t where: %s})", + "(select {s: (sum a) from: t where: %s})", + "(select {c: (count a) from: t by: b where: %s})", + "(select {a: a from: t where: %s take: 10})", + "(select {a: a from: t where: %s take: -4})", + "(select {a: a b: b from: t where: %s desc: a take: 5})", + "(select {s: (sum a) m: (max b) by: date from: t where: %s})", + "(select {c: (count b) from: t where: (and %s (> a 100))})", + "(select {x: (+ a b) from: t where: %s})", + "(select {from: t where: %s asc: b})", + "(select {c: (count (distinct b)) by: date from: t where: %s})", + /* shapes reading rows the where rejects, or positional: not pruned */ + "(select {r: (sums a) from: t where: %s})", + "(select {r: (deltas b) from: t where: %s})", + "(select {r: (- a (avg a)) from: t where: %s})", + "(select {a: a from: t where: (and (> (count a) 6000) %s)})", + "(select {c: (count (distinct date)) from: t where: %s})", + "(select {s: (sum a) by: (sums b) from: t where: %s})", + NULL, +}; +/* Prunable predicates (the second rules every partition out). */ +static const char* const sp_preds[] = { + "(== date 2024.01.02)", "(> date 2024.01.03)", "(<= date 2024.01.02)", + "(in date [2024.01.01 2024.01.03])", "(!= date 2024.01.02)", "(>= 2024.01.02 date)", NULL, +}; + +/* The query of shape i over predicate p; `unpruned` wraps the predicate in + * an `or` the pruner does not read, so the whole table is scanned. */ +static ray_t* sp_eval(int i, const char* p, bool unpruned) { + char pred[160], q[400]; + if (unpruned) snprintf(pred, sizeof pred, "(or %s %s)", p, p); + else snprintf(pred, sizeof pred, "%s", p); + snprintf(q, sizeof q, sp_shapes[i], pred); + return ray_eval_str(q); +} +static void sp_bind(ray_t* t) { ray_env_set(ray_sym_intern("t", 1), t); } + +/* Both outcomes are errors with one code, or the same serialized value. */ +static bool sp_same(ray_t* x, ray_t* y) { + if (!x || !y) return false; + if (RAY_IS_ERR(x) || RAY_IS_ERR(y)) + return RAY_IS_ERR(x) && RAY_IS_ERR(y) && strcmp(ray_err_code(x), ray_err_code(y)) == 0; + return t29_same(x, y) && cp_fmt_same(x, y); +} + +/* A select over a parted generation-2 table decodes only the surviving + * partitions' referenced columns: the where on the partition key prunes + * before any column is fetched. Before this change the four shapes + * materialized 6, 2, 6 and 3 segment columns; since P3 Task 6 the + * surviving rows are gathered by range and only a sort key materializes. */ +static test_result_t test_select_parted_prunes_fetch(void) { + ray_t* t = pdb_make(ray_test_tmp(CS_TMP "/sp"), 7, false); + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/sp0"), 0, false); + TEST_ASSERT_TRUE(t && t0); + ray_release(t); + static const struct { const char* q; uint64_t cols; int64_t rows; } qs[] = { + { "(select {from: t where: (== date 2024.01.02)})", 0, 3000 }, /* a and b of 01.02, gathered by range (P3 Task 6) */ + { "(select {s: (sum a) from: t where: (== date 2024.01.02)})", 0, 1 }, /* P2 Task 10: the scalar route range-reads a of 01.02 */ + { "(select {c: (count a) from: t by: b where: (== date 2024.01.02)})", 0, 3000 }, /* P2 Task 14: the parted group reads a and b of 01.02 by range */ + { "(select {a: a from: t where: (<= date 2024.01.02) take: 10})", 0, 10 }, /* a of 01.01 and 01.02, gathered by range */ + { "(select {a: a from: t where: (<= date 2024.01.02) asc: b})", 2, 6000 }, /* the sort key b of 01.01, 01.02; a gathered */ + { "(select {c: (count a) from: t where: (> date 2024.01.03)})", 0, 1 }, /* the stand-in alone */ + { NULL, 0, 0 }, + }; + for (int i = 0; qs[i].q; i++) { + t = ray_read_parted(ray_test_tmp(CS_TMP "/sp"), "t"); /* a fresh load: nothing cached */ + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + sp_bind(t); + ray_release(t); + ray_enc_counters_reset(); + ray_t* r = ray_eval_str(qs[i].q); + ray_enc_counters_t c; ray_enc_counters_get(&c); + sp_bind(t0); + ray_t* r0 = ray_eval_str(qs[i].q); + bool ok = r && !RAY_IS_ERR(r) && r->type == RAY_TABLE && ray_table_nrows(r) == qs[i].rows; + bool same = sp_same(r, r0); + drop_out(r); drop_out(r0); + TEST_ASSERT_FMT(ok, "%s: answered", qs[i].q); + TEST_ASSERT_FMT(same, "%s: generation 0 and 2 agree", qs[i].q); + TEST_ASSERT_FMT(c.materialized == qs[i].cols, "%s: materialized %llu, expected %llu", + qs[i].q, (unsigned long long)c.materialized, (unsigned long long)qs[i].cols); + } + sp_bind(NULL); + ray_release(t0); + PASS(); +} + +/* Pruned answers (or errors) equal the unpruned scan's, on generation 0 and + * 2, for every shape and prunable predicate (nothing surviving included); + * generation 0 decodes nothing. On these even partitions that includes the + * whole scan's oddities (an empty first-partition group under by: on the + * key, a `type` error for a distinct of the key). On uneven partitions the + * whole scan's spurious empty first-partition group under by: on the key + * no longer appears when pruning applies (see prunes_by_key_uneven); it + * still appears when nothing survives, as on dev, and for unpruned shapes. */ +static test_result_t test_select_parted_prunes_same(void) { + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/sq0"), 0, false); + ray_t* t2 = pdb_make(ray_test_tmp(CS_TMP "/sq2"), 7, false); + TEST_ASSERT_TRUE(t0 && t2); + for (int i = 0; sp_shapes[i]; i++) { + for (int k = 0; sp_preds[k]; k++) { + sp_bind(t0); + ray_enc_counters_reset(); + ray_t* p0 = sp_eval(i, sp_preds[k], false); + ray_enc_counters_t c; ray_enc_counters_get(&c); + ray_t* u0 = sp_eval(i, sp_preds[k], true); + sp_bind(t2); + ray_t* p2 = sp_eval(i, sp_preds[k], false); + bool gen = sp_same(p0, p2); + /* the count-in-where shape (14) is not pruned, and its `or` form + * answers differently on the whole scan already (on dev too) */ + bool unp = i == 14 || sp_same(p0, u0); + drop_out(p0); drop_out(u0); drop_out(p2); + TEST_ASSERT_FMT(gen, "shape %d pred %s: generations agree", i, sp_preds[k]); + TEST_ASSERT_FMT(unp, "shape %d pred %s: pruned equals unpruned", i, sp_preds[k]); + TEST_ASSERT_EQ_U(c.materialized, 0); + } + } + sp_bind(NULL); + ray_release(t0); ray_release(t2); + PASS(); +} + +/* Mixed generations and a ragged tail (the last partition lacks b): the + * pruned answer equals all-generation-0's. A where that prunes the ragged + * partition (or prunes everything) answers as the whole table would, never + * touching it; one that keeps it, or a shape that is not pruned, leaves the + * source unpruned (the existing ragged-table behaviour, not compared here). */ +static test_result_t test_select_parted_prunes_mixed(void) { + static const unsigned masks[] = { 0x5, 0x2 }; + ray_t* t0 = pdb_make(ray_test_tmp(CS_TMP "/sx0"), 0, false); + TEST_ASSERT_NOT_NULL(t0); + for (int rag = 0; rag < 2; rag++) { + for (int m = 0; m < 2; m++) { + char rm[128]; + snprintf(rm, sizeof rm, ray_test_tmp(CS_TMP "/sxm_%d_%d"), m, rag); + ray_t* tm = pdb_make(rm, masks[m], rag); + TEST_ASSERT_NOT_NULL(tm); + for (int i = 0; sp_shapes[i]; i++) { + for (int k = 0; sp_preds[k]; k++) { + if (rag && (k == 3 || k == 4)) continue; /* keeps 01.03 */ + if (rag && i >= 11) continue; /* not pruned: reads 01.03 */ + sp_bind(t0); + ray_t* a = sp_eval(i, sp_preds[k], false); + sp_bind(tm); + ray_t* b = sp_eval(i, sp_preds[k], false); + bool same = sp_same(a, b) && !RAY_IS_ERR(b); + drop_out(a); drop_out(b); + TEST_ASSERT_FMT(same, "mask %u ragged %d shape %d pred %s", masks[m], rag, i, sp_preds[k]); + } + } + ray_release(tm); + } + } + sp_bind(NULL); + ray_release(t0); + PASS(); +} + +/* A lambda formal named like the key shadows it: the where compares the + * formal, so nothing is pruned and the answer is the whole table's. */ +static test_result_t test_select_parted_prunes_shadow(void) { + ray_t* t = pdb_make(ray_test_tmp(CS_TMP "/sh"), 7, false); + TEST_ASSERT_NOT_NULL(t); + sp_bind(t); + ray_release(t); + ray_t* a = ray_eval_str("((fn [date] (select {s: (sum a) from: t where: (<= date 2024.01.01)})) 2024.01.01)"); + ray_t* b = ray_eval_str("(select {s: (sum a) from: t})"); + ray_t* c = ray_eval_str("((fn [date] (select {a: a from: t where: (== date 2024.01.02)})) 2024.01.01)"); + bool same = sp_same(a, b); + bool none = c && !RAY_IS_ERR(c) && c->type == RAY_TABLE && ray_table_nrows(c) == 0; + drop_out(a); drop_out(b); drop_out(c); + sp_bind(NULL); + TEST_ASSERT_TRUE(same); + TEST_ASSERT_TRUE(none); + PASS(); +} + +/* Nothing survives, partitions of different sizes: the source is the + * stand-in alone (01.01's key, one synthetic row), nothing is decoded, and + * the answers equal the whole scan's — an empty table with the source's + * schema, a zero count, and no group under by: date (an empty selection + * forms no group, as in memory). */ +static test_result_t test_select_parted_prunes_none(void) { + static const int64_t rows[3] = { 2500, 700, 1800 }; + ray_t* t = pdb_make_rows(ray_test_tmp(CS_TMP "/sn"), 7, false, rows); + TEST_ASSERT_NOT_NULL(t); + ray_release(t); + static const char* const qs[] = { + "(select {from: t where: %s})", + "(select {c: (count a) s: (sum b) from: t where: %s})", + "(select {c: (count a) by: date from: t where: %s})", + "(select {c: (count a) by: b from: t where: %s})", + "(select {a: a from: t where: %s desc: a take: 3})", + NULL, + }; + ray_t* got[5] = {0}; + for (int i = 0; qs[i]; i++) { + t = ray_read_parted(ray_test_tmp(CS_TMP "/sn"), "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + sp_bind(t); + ray_release(t); + char q[256], u[256]; + snprintf(q, sizeof q, qs[i], "(> date 2024.01.03)"); + snprintf(u, sizeof u, qs[i], "(or (> date 2024.01.03) (> date 2024.01.03))"); + ray_enc_counters_reset(); + got[i] = ray_eval_str(q); + ray_enc_counters_t c; ray_enc_counters_get(&c); + ray_t* ref = ray_eval_str(u); + bool same = sp_same(got[i], ref); + drop_out(ref); + TEST_ASSERT_FMT(same, "%s: equals the whole scan", q); + TEST_ASSERT_FMT(c.materialized == 0, "%s: materialized %llu", q, (unsigned long long)c.materialized); + } + sp_bind(NULL); + bool shape = got[0] && got[0]->type == RAY_TABLE && ray_table_nrows(got[0]) == 0 && ray_table_ncols(got[0]) == 3; + ray_t* cnt = got[1] && got[1]->type == RAY_TABLE ? ray_table_get_col(got[1], ray_sym_intern("c", 1)) : NULL; + bool zero = cnt && cnt->len == 1 && ((const int64_t*)ray_data(cnt))[0] == 0; + ray_t* key = got[2] && got[2]->type == RAY_TABLE ? ray_table_get_col(got[2], ray_sym_intern("date", 4)) : NULL; + bool group = key && key->type == RAY_DATE && key->len == 0; + bool by_b = got[3] && got[3]->type == RAY_TABLE && ray_table_nrows(got[3]) == 0; + bool topk = got[4] && got[4]->type == RAY_TABLE && ray_table_nrows(got[4]) == 0; + for (int i = 0; i < 5; i++) drop_out(got[i]); + TEST_ASSERT_TRUE(shape); + TEST_ASSERT_TRUE(zero); + TEST_ASSERT_TRUE(group); + TEST_ASSERT_TRUE(by_b); + TEST_ASSERT_TRUE(topk); + PASS(); +} + +/* Uneven partitions (50/2000/3/4000/10 rows): a group by the key over a where + * selecting the third partition answers the single correct group, on + * generation 0 and 2. The whole scan (dev) also answers an empty group for + * 2024.01.01 here (its first partition has no survivor and fewer rows pass + * than it holds); pruning drops that partition, and the spurious group with + * it. */ +static test_result_t test_select_parted_prunes_by_key_uneven(void) { + static const int64_t rows[5] = { 50, 2000, 3, 4000, 10 }; + ray_t* t[2] = { NULL, NULL }; + for (int g = 0; g < 2; g++) { + const char* root = g ? ray_test_tmp(CS_TMP "/bu2") : ray_test_tmp(CS_TMP "/bu0"); + for (int p = 0; p < 5; p++) { + char dir[256]; snprintf(dir, sizeof dir, "%s/2024.01.0%d/t", root, p + 1); + ray_t* x = ray_table_new(2); + ray_t* a = i64_col(rows[p], 1); + ray_t* b = i64_col(rows[p], 7); + x = ray_table_add_col(x, ray_sym_intern("a", 1), a); + x = ray_table_add_col(x, ray_sym_intern("b", 1), b); + ray_release(a); ray_release(b); + TEST_ASSERT_TRUE(ray_splay_save_mode(x, dir, NULL, g ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF) == RAY_OK); + ray_release(x); + } + t[g] = ray_read_parted(root, "t"); + TEST_ASSERT_TRUE(t[g] && !RAY_IS_ERR(t[g])); + } + static const struct { const char* q; int ng; int32_t d[2]; int64_t c[2]; } qs[] = { + { "(select {c: (count a) by: date from: t where: (== date 2024.01.03)})", 1, { 8768, 0 }, { 3, 0 } }, + { "(select {c: (count a) by: date from: t where: (in date [2024.01.03 2024.01.05])})", 2, { 8768, 8770 }, { 3, 10 } }, + { "(select {c: (count a) by: date from: t where: (and (== date 2024.01.03) (> a 0))})", 1, { 8768, 0 }, { 2, 0 } }, + { NULL, 0, { 0, 0 }, { 0, 0 } }, + }; + for (int i = 0; qs[i].q; i++) { + ray_t* r[2]; + for (int g = 0; g < 2; g++) { sp_bind(t[g]); r[g] = ray_eval_str(qs[i].q); } + bool same = sp_same(r[0], r[1]); + ray_t* d = r[0] && !RAY_IS_ERR(r[0]) && r[0]->type == RAY_TABLE ? ray_table_get_col(r[0], ray_sym_intern("date", 4)) : NULL; + ray_t* c = r[0] && !RAY_IS_ERR(r[0]) && r[0]->type == RAY_TABLE ? ray_table_get_col(r[0], ray_sym_intern("c", 1)) : NULL; + bool ok = d && c && d->type == RAY_DATE && d->len == qs[i].ng && c->len == qs[i].ng; + for (int k = 0; ok && k < qs[i].ng; k++) + ok = ((const int32_t*)ray_data(d))[k] == qs[i].d[k] && ((const int64_t*)ray_data(c))[k] == qs[i].c[k]; + drop_out(r[0]); drop_out(r[1]); + TEST_ASSERT_FMT(same, "%s: generations agree", qs[i].q); + TEST_ASSERT_FMT(ok, "%s: the surviving groups only", qs[i].q); + } + sp_bind(NULL); + ray_release(t[0]); ray_release(t[1]); + PASS(); +} + +/* A grouped non-aggregate output over a generation-2 table decodes only the + * columns it names (and the key): the full-table evaluation behind the + * per-group scatter binds the referenced columns, not every column. The + * DAG scatter (an integer key) and the eval-level group (a STR key) both. */ +static test_result_t test_grouped_nonagg_binds_referenced(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 's 'v 'w 'z] (list (% (til 3000) 7) (at (list \"a\" \"b\" \"c\") (% (til 3000) 3)) (til 3000) (* 2 (til 3000)) (* 3 (til 3000)))))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/gnb\" t {compress: true})")), ""); + static const char* const qs[] = { + "(select {x: (+ v 1) by: k from: u})", + "(select {x: (+ v 1) by: s from: u})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u (.db.splayed.get \"" CS_TMP "/gnb\"))")), ""); /* nothing cached */ + ray_enc_counters_reset(); + ray_t* r = ray_eval_str(qs[i]); + ray_enc_counters_t c; ray_enc_counters_get(&c); + bool ok = r && !RAY_IS_ERR(r) && r->type == RAY_TABLE; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_FMT(ok, "%s: answered", qs[i]); + TEST_ASSERT_FMT(c.materialized == 2, "%s: materialized %llu, expected 2 (the key and v)", + qs[i], (unsigned long long)c.materialized); + } + PASS(); +} + +/* simplify_agg_idiom: (first (asc c)) -> min is taken only for a null-free + * column. Over a parted generation-0 column with a null in one segment the + * rewrite declines and the group answers as the same rows in memory; the + * parted null-free column still takes it. */ +static test_result_t test_query_first_asc_parted_nulls_gen0(void) { + ray_t* s0 = i64_col(5, 1); ray_t* s1 = i64_col(5, 1); + ray_vec_set_null(s1, 2, true); + ray_t* w = ray_alloc(2 * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + RAY_I64; w->len = 2; w->attrs = 0; + memset(w->aux, 0, 16); + ((ray_t**)ray_data(w))[0] = s0; ((ray_t**)ray_data(w))[1] = s1; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("p", 1), w); + ray_release(w); + ray_t* kc = ray_vec_new(RAY_I64, 10); kc->len = 10; + memset(ray_data(kc), 0, 10 * sizeof(int64_t)); + t = ray_table_add_col(t, ray_sym_intern("k", 1), kc); + ray_release(kc); + ray_env_set(ray_sym_intern("pt", 2), t); + /* the rewrite declines (simplify_agg_idiom sees the segment's null); + * the group then answers as the same rows in memory do */ + ray_t* fl = ray_eval_str("(at (select {m: (first (asc p)) by: k from: " + "(table [p k] (list [0 1 2 3 4 0 1 0N 3 4] [0 0 0 0 0 0 0 0 0 0]))}) 'm)"); + TEST_ASSERT_TRUE(fl && !RAY_IS_ERR(fl) && fl->type == RAY_I64 && fl->len == 1); + ray_t* r = ray_eval_str("(at (select {m: (first (asc p)) by: k from: pt}) 'm)"); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_I64 && r->len == 1, "%s", + r && RAY_IS_ERR(r) ? ray_error_msg() : "not one I64"); + TEST_ASSERT_EQ_I(ray_vec_is_null(r, 0), ray_vec_is_null(fl, 0)); + if (!ray_vec_is_null(fl, 0)) TEST_ASSERT_EQ_I(((const int64_t*)ray_data(r))[0], ((const int64_t*)ray_data(fl))[0]); + ray_release(r); ray_release(fl); + /* without a null the rewrite is taken: the answer is the minimum */ + ray_vec_set_null(s1, 2, false); + ((int64_t*)ray_data(s1))[2] = 7; + s1->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + r = ray_eval_str("(select {m: (first (asc p)) by: k from: pt})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_TABLE); + ray_t* col = ray_table_col(r, ray_sym_intern("m", 1)); + TEST_ASSERT_TRUE(col && col->len == 1 && ((const int64_t*)ray_data(col))[0] == 0); + ray_release(r); + ray_release(t); + PASS(); +} + +/* Planning a full select reads metadata only: no column is materialized + * before the first ray_execute. */ +static test_result_t test_select_planning_no_materialize(void) { + TEST_ASSERT_STR_EQ(ev_code("(set t (table ['k 'v 's] (list [1 2 3 4 5 6] [1.5 2.5 3.5 4.5 5.5 6.5] [\"a\" \"b\" \"a\" \"c\" \"b\" \"a\"])))"), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/sp\" t {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u (.db.splayed.get \"" CS_TMP "/sp\"))")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(.db.splayed.set \"" CS_TMP "/spz\" (table ['v] (list (til 70000))) {compress: true})")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set w (.db.splayed.get \"" CS_TMP "/spz\"))")), ""); + static const char* const qs[] = { + "(select {from: u where: (> k 2)})", + "(select {s: (sum v) from: u by: k})", + "(select {from: u where: (in k [1 3 5])})", + "(select {from: u where: (== s \"a\")})", /* a scalar reduction or group-by under a filter pre-executes it in query.c, never reaching ray_execute */ + "(select {s: (sum v) from: w})", /* 70000 rows: CHUNK_ZONE recorded */ + NULL, + }; + for (int i = 0; qs[i]; i++) { + /* a fresh table per query: a column decoded by an earlier one stays cached */ + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set u (.db.splayed.get \"" CS_TMP "/sp\"))")), ""); + TEST_ASSERT_STR_EQ(ev_code(ray_test_tmp("(set w (.db.splayed.get \"" CS_TMP "/spz\"))")), ""); + ray_enc_counters_reset(); + ray_t* r = ray_eval_str(qs[i]); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "query %d: %s", i, r ? ray_err_code(r) : "null"); + ray_release(r); + ray_enc_counters_t c; ray_enc_counters_get(&c); + /* query 4 is answered at planning from the directory (P2 Task 10, + * finding C3), so it never reaches ray_execute: nothing decodes */ + if (i == 4) TEST_ASSERT_FMT(c.at_first_exec == UINT64_MAX && c.materialized == 0, + "query %d: answered from the directory", i); + else TEST_ASSERT_FMT(c.at_first_exec == 0, "query %d materialized %llu columns before execution", + i, (unsigned long long)c.at_first_exec); + } + PASS(); +} + +/* A computed key beside a renamed one over a parted generation-2 table is + * deferred to the per-partition group kernel, as over generation 0. The + * select's streamable-key gate read an encoded parted slot's type as the + * parted type (RAY_PARTED_BASE + SYM), not its base type, so the by-dict was + * flattened eagerly and the group never streamed. */ +static test_result_t test_select_parted_bydict_streams(void) { + static const char* const gens[] = { "true", "false" }; + ray_t* res[2] = { NULL, NULL }; + for (int g = 0; g < 2; g++) { + char q[900]; + snprintf(q, sizeof q, + "(do (set P (table [ts sg v] (list (til 400) (as 'SYM (%% (til 400) 2)) (as 'F64 (til 400)))))" + " (.db.splayed.set \"%s/pb%d/1/t/\" P {compress: %s})" + " (.db.splayed.set \"%s/pb%d/2/t/\" P {compress: %s})" + " (set t (.db.parted.get \"%s/pb%d/\" 't))" + " (set B (at (.sys.mem) 'group-perpart-runs))" + " (set R (select {sv: (sum v) by: {tb: (xbar ts 200) s: sg} from: t asc: tb}))" + " (list (- (at (.sys.mem) 'group-perpart-runs) B) R))", + ray_test_tmp(CS_TMP), g, gens[g], ray_test_tmp(CS_TMP), g, gens[g], ray_test_tmp(CS_TMP), g); + res[g] = ray_eval_str(q); + TEST_ASSERT_FMT(res[g] && !RAY_IS_ERR(res[g]) && res[g]->type == RAY_LIST && res[g]->len == 2, + "compress %s: answered", gens[g]); + ray_t* runs = ((ray_t**)ray_data(res[g]))[0]; + TEST_ASSERT_FMT(runs->i64 == 1, "compress %s: per-partition runs %lld, expected 1", + gens[g], (long long)runs->i64); + } + ray_t* r2 = ((ray_t**)ray_data(res[0]))[1]; + ray_t* r0 = ((ray_t**)ray_data(res[1]))[1]; + TEST_ASSERT_EQ_I(ray_table_nrows(r2), 4); + TEST_ASSERT_TRUE(sp_same(r2, r0)); + ray_release(res[0]); ray_release(res[1]); + PASS(); +} + +/* The empty-key and nullability helpers of the select planner, over a parted + * generation-2 table, answer as over generation 0: a grouped select whose + * where leaves no row (zero groups: the empty key column is built from the + * filtered table), and a nullable sort key under a positional take. The + * parted arms of those helpers (an encoded parted slot's base type, a plain + * parted wrapper's nulls from its segments) sit behind gates no select + * reaches today: an unfiltered zero-group select needs an empty parted table, + * which the parted group refuses first (nyi, both generations), and the + * nullable-key take needs SORTED, which no parted slot carries. */ +static test_result_t test_select_parted_empty_nullable(void) { + static const char* const qs[] = { + "(select {from: t by: sg where: (> v 1000.0)})", + "(select {from: t by: n where: (> v 1000.0)})", + "(select {from: t by: s where: (> v 1000.0)})", + "(select {x: (count v) from: t by: n where: (> v 1000.0)})", + "(select {from: t where: (> v 10.0) asc: n take: 3})", + "(select {from: t where: (> v 10.0) desc: n take: 3})", + "(select {from: t by: sg})", + NULL, /* (select {from: t}) stays parted: no serialized form to compare (#728) */ + }; + ray_t* tb[2] = { NULL, NULL }; + static const char* const gens[] = { "true", "false" }; + for (int g = 0; g < 2; g++) { + char q[900]; + snprintf(q, sizeof q, + "(do (set P (table [sg v n s] (list (as 'SYM (%% (til 400) 2)) (as 'F64 (til 400))" + " (concat [0N 0N] (til 398)) (at [\"a\" \"\" \"c\"] (%% (til 400) 3)))))" + " (.db.splayed.set \"%s/pe%d/1/t/\" P {compress: %s})" + " (.db.splayed.set \"%s/pe%d/2/t/\" P {compress: %s})" + " (.db.parted.get \"%s/pe%d/\" 't))", + ray_test_tmp(CS_TMP), g, gens[g], ray_test_tmp(CS_TMP), g, gens[g], ray_test_tmp(CS_TMP), g); + tb[g] = ray_eval_str(q); + TEST_ASSERT_FMT(tb[g] && !RAY_IS_ERR(tb[g]) && tb[g]->type == RAY_TABLE, + "compress %s: loaded", gens[g]); + } + TEST_ASSERT_TRUE(ray_table_get_col_enc(tb[0], ray_sym_intern("n", 1)) != NULL); + for (int i = 0; qs[i]; i++) { + sp_bind(tb[0]); + ray_t* r2 = ray_eval_str(qs[i]); + sp_bind(tb[1]); + ray_t* r0 = ray_eval_str(qs[i]); + bool same = sp_same(r2, r0); + drop_out(r2); drop_out(r0); + TEST_ASSERT_FMT(same, "%s: generation 0 and 2 agree", qs[i]); + } + sp_bind(NULL); + ray_release(tb[0]); ray_release(tb[1]); + PASS(); +} + +/* The parted group's cardinality estimate over an I64 key whose first + * partition holds a null (INT64_MIN) beside positive values: the span is + * taken in u64 and capped, never a signed overflow (UBSan), and the grouped + * answer equals the flat one, in both generations. */ +static test_result_t test_parted_group_null_i64_estimate(void) { + static const char* const gens[] = { "true", "false" }; + for (int g = 0; g < 2; g++) { + char q[900]; + snprintf(q, sizeof q, + "(do (set P (table [n v] (list (concat [0N 0N] (%% (til 398) 3)) (as 'F64 (til 400)))))" + " (.db.splayed.set \"%s/pn%d/1/t/\" P {compress: %s})" + " (.db.splayed.set \"%s/pn%d/2/t/\" P {compress: %s})" + " (set t (.db.parted.get \"%s/pn%d/\" 't))" + " (set F (table [n v] (list (concat (at P 'n) (at P 'n)) (concat (at P 'v) (at P 'v)))))" + " (list (select {s: (sum v) c: (count v) from: t by: n asc: n})" + " (select {s: (sum v) c: (count v) from: F by: n asc: n})))", + ray_test_tmp(CS_TMP), g, gens[g], ray_test_tmp(CS_TMP), g, gens[g], ray_test_tmp(CS_TMP), g); + ray_t* r = ray_eval_str(q); + bool ok = r && !RAY_IS_ERR(r) && r->type == RAY_LIST && r->len == 2 && + ray_table_nrows(((ray_t**)ray_data(r))[0]) == 4 && + sp_same(((ray_t**)ray_data(r))[0], ((ray_t**)ray_data(r))[1]); + drop_out(r); + TEST_ASSERT_FMT(ok, "compress %s: parted group equals flat", gens[g]); + } + PASS(); +} + +const test_entry_t compress_entries[] = { + { "compress/select_planning_no_materialize", test_select_planning_no_materialize, rt_setup, rt_teardown }, + { "compress/stream_matches_resident", test_stream_matches_resident, cs_setup, cs_teardown }, + { "compress/stream_str_matches_resident", test_stream_str_matches_resident, cs_setup, cs_teardown }, + { "compress/stream_sym_gen2", test_stream_sym_gen2, cs_setup, cs_teardown }, + { "compress/stream_gen2_transcode_failure", test_stream_gen2_transcode_failure, cs_setup, cs_teardown }, + { "compress/str_header_no_pointer", test_str_header_no_pointer, cs_setup, cs_teardown }, + { "compress/csv_splayed_symbol", test_csv_splayed_symbol, rt_setup, rt_teardown }, + { "compress/csv_splayed_option", test_csv_splayed_option, rt_setup, rt_teardown }, + { "compress/parquet_option", test_parquet_option, rt_setup, rt_teardown }, + { "compress/parquet_two_dicts", test_parquet_two_dicts, rt_setup, rt_teardown }, + { "compress/merge_mixed_widths", test_merge_mixed_widths, cs_setup, cs_teardown }, + { "compress/absent_byte_identity", test_absent_byte_identity, cs_setup, cs_teardown }, + { "compress/unreadable_destination", test_unreadable_destination, cs_setup, cs_teardown }, + { "compress/inherit_destination", test_inherit_destination, cs_setup, cs_teardown }, + { "compress/update_then_save", test_update_then_save, cs_setup, cs_teardown }, + { "compress/forced_generation0", test_forced_generation0, cs_setup, cs_teardown }, + { "compress/chunk_zone_recorded", test_chunk_zone_recorded, cs_setup, cs_teardown }, + { "compress/matrix_parted_indexed", test_matrix_parted_indexed, cs_setup, cs_teardown }, + { "compress/staged_and_sym", test_staged_and_sym, cs_setup, cs_teardown }, + { "compress/save_refuses_parted_kinds", test_save_refuses_parted_kinds, rt_setup, rt_teardown }, + { "compress/resolver_rules", test_resolver_rules, cs_setup, cs_teardown }, + { "compress/write_sym_domains", test_write_sym_domains, cs_setup, cs_teardown }, + { "compress/write_parted_refused", test_write_parted_refused, rt_setup, rt_teardown }, + { "compress/matrix_failure_inject", test_matrix_failure_inject, cs_setup, cs_teardown }, + { "compress/matrix_flat", test_matrix_flat, cs_setup, cs_teardown }, + { "compress/matrix_sym_remap", test_matrix_sym_remap, cs_setup, cs_teardown }, + { "compress/str_const_offsets", test_str_const_distinct_offsets, cs_setup, cs_teardown }, + { "compress/dml_upsert_copy", test_dml_upsert_copy, rt_setup, rt_teardown }, + { "compress/dml_upsert_inplace", test_dml_upsert_inplace, rt_setup, rt_teardown }, + { "compress/dml_insert_copy", test_dml_insert_copy, rt_setup, rt_teardown }, + { "compress/dml_insert_inplace", test_dml_insert_inplace, rt_setup, rt_teardown }, + { "compress/dml_update_copy", test_dml_update_copy, rt_setup, rt_teardown }, + { "compress/dml_update_inplace", test_dml_update_inplace, rt_setup, rt_teardown }, + { "compress/dml_delete_copy", test_dml_delete_copy, rt_setup, rt_teardown }, + { "compress/dml_delete_inplace", test_dml_delete_inplace, rt_setup, rt_teardown }, + { "compress/value_ops_copy_encoded", test_value_ops_copy_encoded, rt_setup, rt_teardown }, + { "compress/dml_on_select_result", test_dml_on_select_result, rt_setup, rt_teardown }, + { "compress/update_passes_encoded", test_update_passes_encoded, rt_setup, rt_teardown }, + { "compress/serde_byte_identity", test_serde_byte_identity, rt_setup, rt_teardown }, + { "compress/getter_keeps_pending_message", test_getter_keeps_pending_message, cs_setup, cs_teardown }, + { "compress/objsize_counts_cache", test_objsize_counts_cache, rt_setup, rt_teardown }, + { "compress/has_nulls_parted", test_has_nulls_parted, cs_setup, cs_teardown }, + { "compress/parted_gen2_loads", test_parted_gen2_loads, rt_setup, rt_teardown }, + { "compress/meta_without_decode", test_meta_without_decode, cs_setup, cs_teardown }, + { "compress/user_values_are_plain", test_user_values_are_plain, rt_setup, rt_teardown }, + { "compress/legacy_getters", test_legacy_getters, cs_setup, cs_teardown }, + { "compress/concurrent_one_materialization",test_concurrent_one_materialization, cs_setup, cs_teardown }, + { "compress/serde_encoded_table", test_serde_encoded_table, cs_setup, cs_teardown }, + { "compress/concurrent_col_index", test_concurrent_col_index, cs_setup, cs_teardown }, + { "compress/legacy_transient_no_leak", test_legacy_transient_no_leak, cs_setup, cs_teardown }, + { "compress/db_splayed_set_forms", test_db_splayed_set_forms, rt_setup, rt_teardown }, + { "compress/csv_parted_option", test_csv_parted_option, rt_setup, rt_teardown }, + { "compress/planning_never_materializes", test_planning_never_materializes, cs_setup, cs_teardown }, + { "compress/exec_start_snapshot", test_exec_start_snapshot, cs_setup, cs_teardown }, + { "compress/first_asc_parted_nulls_gen0", test_first_asc_parted_nulls_gen0, cs_setup, cs_teardown }, + { "compress/query_first_asc_parted_nulls_gen0", test_query_first_asc_parted_nulls_gen0, rt_setup, rt_teardown }, + { "compress/grouped_nonagg_binds_referenced", test_grouped_nonagg_binds_referenced, rt_setup, rt_teardown }, + { "compress/first_asc_parted_nulls_gen2", test_first_asc_parted_nulls_gen2, rt_setup, rt_teardown }, + { "compress/first_asc_parted_text_nulls", test_first_asc_parted_text_nulls, rt_setup, rt_teardown }, + { "compress/parted_text_nulls_mixed_gen", test_parted_text_nulls_mixed_gen, rt_setup, rt_teardown }, + { "compress/bind_stage", test_bind_stage, cs_setup, cs_teardown }, + { "compress/fused_pred_bound", test_fused_pred_bound, rt_setup, rt_teardown }, + { "compress/fused_pred_enc_source", test_fused_pred_enc_source, rt_setup, rt_teardown }, + { "compress/fused_pred_bind_failure", test_fused_pred_bind_failure, rt_setup, rt_teardown }, + { "compress/bind_dedup_validates", test_bind_dedup_validates, rt_setup, rt_teardown }, + { "compress/bind_address_reuse", test_bind_address_reuse, rt_setup, rt_teardown }, + { "compress/unbind_releases_temporaries", test_unbind_releases_temporaries, rt_setup, rt_teardown }, + { "compress/compile_paths_bound", test_compile_paths_bound, rt_setup, rt_teardown }, + { "compress/try_plans_bound", test_try_plans_bound, rt_setup, rt_teardown }, + { "compress/expr_compile_bound", test_expr_compile_bound, rt_setup, rt_teardown }, + { "compress/group_desc_bound", test_group_desc_bound, rt_setup, rt_teardown }, + { "compress/topk_bound", test_topk_bound, rt_setup, rt_teardown }, + { "compress/slice_group_bound", test_slice_group_bound, rt_setup, rt_teardown }, + { "compress/parted_pruning_fetch", test_parted_pruning_fetch, rt_setup, rt_teardown }, + { "compress/parted_pruning_gen0", test_parted_pruning_gen0, rt_setup, rt_teardown }, + { "compress/parted_pruning_empty", test_parted_pruning_empty, rt_setup, rt_teardown }, + { "compress/parted_pruning_multi", test_parted_pruning_multi, rt_setup, rt_teardown }, + { "compress/parted_pruning_mixed", test_parted_pruning_mixed, rt_setup, rt_teardown }, + { "compress/exec_sites_pass_encoded", test_exec_sites_pass_encoded, rt_setup, rt_teardown }, + { "compress/exec_sites_gen2_equal", test_exec_sites_gen2_equal, rt_setup, rt_teardown }, + { "compress/filter_absent_symbol", test_filter_absent_symbol, rt_setup, rt_teardown }, + { "compress/group_sites_routes_same", test_group_sites_routes_same, rt_setup, rt_teardown }, + { "compress/group_sites_slice_route", test_group_sites_slice_route, rt_setup, rt_teardown }, + { "compress/group_sites_parted", test_group_sites_parted, rt_setup, rt_teardown }, + { "compress/join_sites_gen2_equal", test_join_sites_gen2_equal, rt_setup, rt_teardown }, + { "compress/tblop_sites_gen2_equal", test_tblop_sites_gen2_equal, rt_setup, rt_teardown }, + { "compress/tblop_sites_lazy", test_tblop_sites_lazy, rt_setup, rt_teardown }, + { "compress/datalog_sites_gen2_equal", test_datalog_sites_gen2_equal, rt_setup, rt_teardown }, + { "compress/join_sites_parted", test_join_sites_parted, rt_setup, rt_teardown }, + { "compress/dml_parted_gen2", test_dml_parted_gen2, rt_setup, rt_teardown }, + { "compress/parted_insert_container", test_parted_insert_container, rt_setup, rt_teardown }, + { "compress/datalog_query_gen2_equal", test_datalog_query_gen2_equal, rt_setup, rt_teardown }, + { "compress/scalar_agg_planning_zoned", test_scalar_agg_planning_zoned, rt_setup, rt_teardown }, + { "compress/dag_presence_without_decode", test_dag_presence_without_decode, rt_setup, rt_teardown }, + { "compress/query_helpers_gen2_equal", test_query_helpers_gen2_equal, rt_setup, rt_teardown }, + { "compress/select_slice_probe_route", test_select_slice_probe_route, rt_setup, rt_teardown }, + { "compress/select_bydict_binds_referenced", test_select_bydict_binds_referenced, rt_setup, rt_teardown }, + { "compress/select_decodes_referenced_only", test_select_decodes_referenced_only, rt_setup, rt_teardown }, + { "compress/select_parted_prunes_fetch", test_select_parted_prunes_fetch, rt_setup, rt_teardown }, + { "compress/select_parted_prunes_same", test_select_parted_prunes_same, rt_setup, rt_teardown }, + { "compress/select_parted_prunes_mixed", test_select_parted_prunes_mixed, rt_setup, rt_teardown }, + { "compress/select_parted_prunes_shadow", test_select_parted_prunes_shadow, rt_setup, rt_teardown }, + { "compress/select_parted_prunes_none", test_select_parted_prunes_none, rt_setup, rt_teardown }, + { "compress/select_parted_prunes_by_key_uneven", test_select_parted_prunes_by_key_uneven, rt_setup, rt_teardown }, + { "compress/select_gen2_equal", test_select_gen2_equal, rt_setup, rt_teardown }, + { "compress/select_parted_bydict_streams", test_select_parted_bydict_streams, rt_setup, rt_teardown }, + { "compress/select_parted_empty_nullable", test_select_parted_empty_nullable, rt_setup, rt_teardown }, + { "compress/parted_group_null_i64_estimate", test_parted_group_null_i64_estimate, rt_setup, rt_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_csr.c b/test/test_csr.c index dd9eecff3..8e6bbd72c 100644 --- a/test/test_csr.c +++ b/test/test_csr.c @@ -27,6 +27,7 @@ #include "mem/heap.h" #include "ops/ops.h" #include "store/csr.h" +#include "core/pool.h" #include "store/col.h" #include "ops/fvec.h" #include @@ -1047,7 +1048,7 @@ static test_result_t test_csr_save_load(void) { TEST_ASSERT_NOT_NULL(rel); /* Save */ - const char* dir = "/tmp/test_csr_save"; + const char* dir = ray_test_tmp("/tmp/test_csr_save"); ray_err_t err = ray_rel_save(rel, dir); TEST_ASSERT_EQ_I(err, RAY_OK); @@ -1629,7 +1630,7 @@ static test_result_t test_save_load_rev(void) { ray_rel_t* rel = ray_rel_from_edges(edges, "src", "dst", 4, 4, true); TEST_ASSERT_NOT_NULL(rel); - const char* dir = "/tmp/test_csr_rev"; + const char* dir = ray_test_tmp("/tmp/test_csr_rev"); ray_err_t err = ray_rel_save(rel, dir); TEST_ASSERT_EQ_I(err, RAY_OK); @@ -2915,7 +2916,7 @@ static test_result_t test_rel_save_load_errors(void) { TEST_ASSERT_NOT_NULL(rel); /* NULL rel → RAY_ERR_IO */ - TEST_ASSERT_EQ_I(ray_rel_save(NULL, "/tmp/test_csr_err"), RAY_ERR_IO); + TEST_ASSERT_EQ_I(ray_rel_save(NULL, ray_test_tmp("/tmp/test_csr_err")), RAY_ERR_IO); /* NULL dir → RAY_ERR_IO */ TEST_ASSERT_EQ_I(ray_rel_save(rel, NULL), RAY_ERR_IO); @@ -2924,9 +2925,9 @@ static test_result_t test_rel_save_load_errors(void) { /* ray_rel_load on NULL or non-existent dir → NULL */ TEST_ASSERT_EQ_PTR(ray_rel_load(NULL), NULL); - TEST_ASSERT_EQ_PTR(ray_rel_load("/tmp/this_csr_dir_must_not_exist_xyz"), NULL); + TEST_ASSERT_EQ_PTR(ray_rel_load(ray_test_tmp("/tmp/this_csr_dir_must_not_exist_xyz")), NULL); TEST_ASSERT_EQ_PTR(ray_rel_mmap(NULL), NULL); - TEST_ASSERT_EQ_PTR(ray_rel_mmap("/tmp/this_csr_dir_must_not_exist_xyz"), NULL); + TEST_ASSERT_EQ_PTR(ray_rel_mmap(ray_test_tmp("/tmp/this_csr_dir_must_not_exist_xyz")), NULL); ray_rel_free(rel); ray_release(edges); @@ -2947,7 +2948,7 @@ static test_result_t test_rel_save_mmap_reuse(void) { ray_rel_t* rel = ray_rel_from_edges(edges, "src", "dst", 4, 4, true); TEST_ASSERT_NOT_NULL(rel); - const char* dir = "/tmp/test_csr_mmap_reuse"; + const char* dir = ray_test_tmp("/tmp/test_csr_mmap_reuse"); /* First save creates dir */ TEST_ASSERT_EQ_I(ray_rel_save(rel, dir), RAY_OK); /* Second save into existing dir hits the EEXIST branch (mkdir returns -1, errno=EEXIST) */ @@ -3215,7 +3216,7 @@ static test_result_t test_load_nonmonotonic_offsets(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_corrupt_mono"; + const char* dir = ray_test_tmp("/tmp/test_csr_corrupt_mono"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); /* fwd has 4 nodes, 6 edges. Forge offsets[5] = {0,5,2,?,6} so the last @@ -3241,7 +3242,7 @@ static test_result_t test_load_negative_offset(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_corrupt_neg"; + const char* dir = ray_test_tmp("/tmp/test_csr_corrupt_neg"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); /* offsets[1] = -1 with last entry still == n_edges (6). */ @@ -3264,7 +3265,7 @@ static test_result_t test_load_offset_count_mismatch(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_corrupt_count"; + const char* dir = ray_test_tmp("/tmp/test_csr_corrupt_count"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); /* targets has 6 edges; make offsets[4] = 5 (monotonic, but != 6). */ @@ -3288,7 +3289,7 @@ static test_result_t test_load_empty_offsets(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_corrupt_empty_off"; + const char* dir = ray_test_tmp("/tmp/test_csr_corrupt_empty_off"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); csr_overwrite_i64(dir, "fwd_offsets", NULL, 0); /* len 0 */ @@ -3310,7 +3311,7 @@ static test_result_t test_load_rev_corrupt_frees_fwd(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_corrupt_rev"; + const char* dir = ray_test_tmp("/tmp/test_csr_corrupt_rev"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); /* Corrupt only rev_offsets: fwd loads fine, rev load must fail and the @@ -3334,7 +3335,7 @@ static test_result_t test_load_missing_rowmap(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_no_rowmap"; + const char* dir = ray_test_tmp("/tmp/test_csr_no_rowmap"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); /* Delete both rowmap files — they are optional on load. */ @@ -3367,7 +3368,7 @@ static test_result_t test_load_missing_meta(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_no_meta"; + const char* dir = ray_test_tmp("/tmp/test_csr_no_meta"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); char path[1024]; @@ -3397,7 +3398,7 @@ static test_result_t test_load_short_meta(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_short_meta"; + const char* dir = ray_test_tmp("/tmp/test_csr_short_meta"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); /* Overwrite meta with a 2-element vector (need >= 5 to apply). */ @@ -3425,7 +3426,7 @@ static test_result_t test_mmap_missing_rowmap(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_mmap_no_rowmap"; + const char* dir = ray_test_tmp("/tmp/test_csr_mmap_no_rowmap"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); char path[1024]; @@ -3452,7 +3453,7 @@ static test_result_t test_load_missing_targets(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_no_targets"; + const char* dir = ray_test_tmp("/tmp/test_csr_no_targets"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); char path[1024]; @@ -3475,7 +3476,7 @@ static test_result_t test_load_missing_offsets(void) { ray_heap_init(); (void)ray_sym_init(); - const char* dir = "/tmp/test_csr_no_offsets"; + const char* dir = ray_test_tmp("/tmp/test_csr_no_offsets"); TEST_ASSERT_NOT_NULL(csr_make_saved_rel(dir)); char path[1024]; @@ -3524,7 +3525,7 @@ static test_result_t test_multi_edge_roundtrip(void) { TEST_ASSERT_EQ_I(nb[2], 1); TEST_ASSERT_EQ_I(nb[3], 2); - const char* dir = "/tmp/test_csr_multi_edge"; + const char* dir = ray_test_tmp("/tmp/test_csr_multi_edge"); TEST_ASSERT_EQ_I(ray_rel_save(rel, dir), RAY_OK); ray_rel_t* loaded = ray_rel_load(dir); @@ -3568,7 +3569,7 @@ static test_result_t test_single_edge_roundtrip(void) { TEST_ASSERT_EQ_I(ray_csr_degree(&rel->fwd, 1), 0); TEST_ASSERT_EQ_I(ray_csr_degree(&rel->rev, 1), 1); - const char* dir = "/tmp/test_csr_single_edge"; + const char* dir = ray_test_tmp("/tmp/test_csr_single_edge"); TEST_ASSERT_EQ_I(ray_rel_save(rel, dir), RAY_OK); ray_rel_t* loaded = ray_rel_load(dir); TEST_ASSERT_NOT_NULL(loaded); @@ -3665,8 +3666,265 @@ static test_result_t test_csr_tiebreak_determinism(void) { * Suite definition * -------------------------------------------------------------------------- */ + +/* The parallel two-level build must produce the same three arrays as the + * serial counting sort, byte for byte. Build one graph both ways by moving + * the size threshold: 0 forces the parallel path (the harness runs with + * RAYFORCE_CORES=2, so the pool has a worker), INT64_MAX forces serial. + * The graph spans several key buckets, has a hub past the insertion-sort + * cut, parallel edges, out-of-range keys on both sides and, in one + * variant, a value past int32 so the int64 scratch branch runs. */ +static test_result_t csr_par_vs_serial(bool wide_value) { + enum { N_NODES = 3000, M = 20000 }; + if (!ray_pool_par_dispatch_ok(ray_pool_get(), M, 0)) SKIP("no pool worker"); + int64_t* s = ray_alloc_raw((size_t)(M + 6) * sizeof(int64_t)); + int64_t* d = ray_alloc_raw((size_t)(M + 6) * sizeof(int64_t)); + TEST_ASSERT(s && d, "scratch"); + int64_t n = 0; + for (int64_t i = 0; i < M; i++) { + s[n] = (i * 7919) % N_NODES; + d[n] = (i * 104729) % N_NODES; + if (i % 97 == 0) s[n] = 5; /* a hub */ + n++; + } + s[n] = -1; d[n] = 5; n++; + s[n] = N_NODES; d[n] = 5; n++; + s[n] = 2; d[n] = -3; n++; + s[n] = 2; d[n] = N_NODES; n++; + s[n] = 7; d[n] = 7; n++; /* self loop */ + s[n] = 7; d[n] = wide_value ? (INT64_C(1) << 40) : 9; n++; + + ray_t* sv = ray_vec_from_raw(RAY_I64, s, n); + ray_t* dv = ray_vec_from_raw(RAY_I64, d, n); + ray_free_raw(s); ray_free_raw(d); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("src", 3), sv); + tbl = ray_table_add_col(tbl, ray_sym_intern("dst", 3), dv); + ray_release(sv); ray_release(dv); + + int64_t saved = ray_csr_par_min_edges; + ray_csr_par_min_edges = INT64_MAX; + ray_rel_t* a = ray_rel_from_edges(tbl, "src", "dst", N_NODES, N_NODES, true); + ray_csr_par_min_edges = 0; + ray_rel_t* b = ray_rel_from_edges(tbl, "src", "dst", N_NODES, N_NODES, true); + ray_csr_par_min_edges = saved; + ray_release(tbl); + TEST_ASSERT(a && b, "both builds succeed"); + + ray_csr_t* pa[2] = { &a->fwd, &a->rev }; + ray_csr_t* pb[2] = { &b->fwd, &b->rev }; + for (int k = 0; k < 2; k++) { + TEST_ASSERT(pa[k]->n_nodes == pb[k]->n_nodes, "n_nodes"); + TEST_ASSERT(pa[k]->n_edges == pb[k]->n_edges, "n_edges"); + /* fwd drops the two bad-src edges; rev drops the two bad-dst ones + * plus the wide target when it is out of [0, N_NODES). */ + int64_t expect = k == 0 ? M + 6 - 2 : M + 6 - 2 - (wide_value ? 1 : 0); + TEST_ASSERT(pa[k]->n_edges == expect, "out-of-range keys dropped per side"); + TEST_ASSERT(pa[k]->offsets->len == pb[k]->offsets->len, "offsets len"); + TEST_ASSERT(memcmp(ray_data(pa[k]->offsets), ray_data(pb[k]->offsets), + (size_t)pa[k]->offsets->len * sizeof(int64_t)) == 0, + "offsets identical"); + TEST_ASSERT(memcmp(ray_data(pa[k]->targets), ray_data(pb[k]->targets), + (size_t)pa[k]->n_edges * sizeof(int64_t)) == 0, + "targets identical"); + TEST_ASSERT(memcmp(ray_data(pa[k]->rowmap), ray_data(pb[k]->rowmap), + (size_t)pa[k]->n_edges * sizeof(int64_t)) == 0, + "rowmap identical"); + } + /* The wide value survived in fwd (values are stored unchecked). */ + int64_t cnt = 0; + int64_t* nb = ray_csr_neighbors(&b->fwd, 7, &cnt); + TEST_ASSERT(cnt >= 2, "node 7 has its two explicit edges"); + bool seen = false; + for (int64_t i = 0; i < cnt; i++) + if (nb[i] == (wide_value ? (INT64_C(1) << 40) : 9)) seen = true; + TEST_ASSERT(seen, "node 7's explicit target is present"); + + ray_rel_free(a); + ray_rel_free(b); + PASS(); +} + +/* The key-less build (ray_rel_build: forward key = row index, reverse + * keyed by the FK with row indices as values) must match serial byte for + * byte too; ray_rel_from_edges never reaches that branch. */ +static test_result_t test_csr_parallel_fk_matches_serial(void) { + ray_heap_init(); + (void)ray_sym_init(); + enum { N_TARGET = 2500, M = 30000 }; + if (!ray_pool_par_dispatch_ok(ray_pool_get(), M, 0)) SKIP("no pool worker"); + int64_t* f = ray_alloc_raw((size_t)M * sizeof(int64_t)); + TEST_ASSERT(f, "scratch"); + for (int64_t i = 0; i < M; i++) f[i] = (i * 7919) % N_TARGET; + f[11] = -1; f[12] = N_TARGET; f[13] = INT64_C(1) << 40; /* dropped in rev */ + for (int64_t i = 0; i < M; i += 101) f[i] = 3; /* a hub */ + ray_t* fv = ray_vec_from_raw(RAY_I64, f, M); + ray_free_raw(f); + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("fk", 2), fv); + ray_release(fv); + + int64_t saved = ray_csr_par_min_edges; + ray_csr_par_min_edges = INT64_MAX; + ray_rel_t* a = ray_rel_build(tbl, "fk", N_TARGET, true); + ray_csr_par_min_edges = 0; + ray_rel_t* b = ray_rel_build(tbl, "fk", N_TARGET, true); + ray_csr_par_min_edges = saved; + ray_release(tbl); + TEST_ASSERT(a && b, "both builds succeed"); + + for (int k = 0; k < 2; k++) { + const ray_csr_t* x = k == 0 ? &a->fwd : &a->rev; + const ray_csr_t* y = k == 0 ? &b->fwd : &b->rev; + TEST_ASSERT(x->n_nodes == y->n_nodes, "n_nodes equal"); + TEST_ASSERT(x->n_edges == y->n_edges, "n_edges equal"); + TEST_ASSERT(x->n_edges == (k == 0 ? M : M - 3), "edges kept per side"); + TEST_ASSERT(x->offsets->len == y->offsets->len, "offsets len"); + TEST_ASSERT(memcmp(ray_data(x->offsets), ray_data(y->offsets), + (size_t)x->offsets->len * sizeof(int64_t)) == 0, "offsets identical"); + TEST_ASSERT(memcmp(ray_data(x->targets), ray_data(y->targets), + (size_t)x->n_edges * sizeof(int64_t)) == 0, "targets identical"); + TEST_ASSERT(memcmp(ray_data(x->rowmap), ray_data(y->rowmap), + (size_t)x->n_edges * sizeof(int64_t)) == 0, "rowmap identical"); + } + ray_rel_free(a); ray_rel_free(b); + PASS(); +} + +/* A cancel during the parallel build must not hand back a CSR: skipped + * tasks never write their slots. Arm the interrupt first so every pass + * is cut short, then check the build reports the cancel with nothing + * left in the relation. */ +static test_result_t test_csr_parallel_cancel(void) { + ray_heap_init(); + (void)ray_sym_init(); + enum { N_NODES = 3000, M = 20000 }; + if (!ray_pool_par_dispatch_ok(ray_pool_get(), M, 0)) SKIP("no pool worker"); + int64_t* s = ray_alloc_raw((size_t)M * sizeof(int64_t)); + int64_t* d = ray_alloc_raw((size_t)M * sizeof(int64_t)); + TEST_ASSERT(s && d, "scratch"); + for (int64_t i = 0; i < M; i++) { s[i] = (i * 7919) % N_NODES; d[i] = (i * 104729) % N_NODES; } + ray_t* sv = ray_vec_from_raw(RAY_I64, s, M); + ray_t* dv = ray_vec_from_raw(RAY_I64, d, M); + ray_free_raw(s); ray_free_raw(d); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("src", 3), sv); + tbl = ray_table_add_col(tbl, ray_sym_intern("dst", 3), dv); + ray_release(sv); ray_release(dv); + + int64_t saved = ray_csr_par_min_edges; + ray_csr_par_min_edges = 0; + ray_request_interrupt(); + ray_rel_t* r = ray_rel_from_edges(tbl, "src", "dst", N_NODES, N_NODES, true); + ray_clear_interrupt(); + ray_csr_par_min_edges = saved; + ray_release(tbl); + + TEST_ASSERT(r == NULL, "a cancelled parallel build returns no relation"); + PASS(); +} + +static test_result_t test_csr_parallel_matches_serial(void) { + ray_heap_init(); + (void)ray_sym_init(); + test_result_t r = csr_par_vs_serial(false); + if (r.status != TEST_PASS) return r; + return csr_par_vs_serial(true); +} + +/* A hub whose list is long enough to leave the insertion sort behind must + * come out in the same (target, row) order as a short list does, in both + * directions, with out-of-range keys dropped and their rows skipped. */ +static test_result_t test_csr_hub_order(void) { + ray_heap_init(); + (void)ray_sym_init(); + + /* 200 edges out of node 0 to targets 0..49, each 4 times, interleaved + * so that neither targets nor rows arrive sorted; node 1 gets 3 edges; + * four edges fall outside [0, 60) on one side or the other. */ + enum { HUB = 200, N_NODES = 60 }; + int64_t s[HUB + 3 + 4], d[HUB + 3 + 4]; + int64_t n = 0; + for (int64_t i = 0; i < HUB; i++) { + s[n] = 0; + d[n] = (i * 37) % 50; + n++; + } + s[n] = 1; d[n] = 7; n++; + s[n] = 1; d[n] = 3; n++; + s[n] = 1; d[n] = 7; n++; + s[n] = -1; d[n] = 5; n++; /* src out of range: dropped from fwd */ + s[n] = 60; d[n] = 5; n++; /* src out of range: dropped from fwd */ + s[n] = 2; d[n] = -3; n++; /* dst out of range: kept in fwd, dropped from rev */ + s[n] = 2; d[n] = 61; n++; + + ray_t* sv = ray_vec_from_raw(RAY_I64, s, n); + ray_t* dv = ray_vec_from_raw(RAY_I64, d, n); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("src", 3), sv); + tbl = ray_table_add_col(tbl, ray_sym_intern("dst", 3), dv); + ray_release(sv); ray_release(dv); + ray_rel_t* rel = ray_rel_from_edges(tbl, "src", "dst", N_NODES, N_NODES, true); + ray_release(tbl); + TEST_ASSERT_NOT_NULL(rel); + + /* Forward: 200 + 3 + 2 kept (the two src=2 edges carry unchecked dsts). */ + TEST_ASSERT_EQ_I(rel->fwd.n_edges, HUB + 3 + 2); + TEST_ASSERT_TRUE(rel->fwd.sorted); + int64_t* off = (int64_t*)ray_data(rel->fwd.offsets); + int64_t* tgt = (int64_t*)ray_data(rel->fwd.targets); + int64_t* row = (int64_t*)ray_data(rel->fwd.rowmap); + TEST_ASSERT_EQ_I(off[1] - off[0], HUB); + for (int64_t i = off[0] + 1; i < off[1]; i++) { + /* (target, row) strictly ascending: no two cells compare equal. */ + TEST_ASSERT_TRUE(tgt[i - 1] < tgt[i] || + (tgt[i - 1] == tgt[i] && row[i - 1] < row[i])); + } + /* Every target 0..49 exactly four times, and each row maps back. */ + for (int64_t i = off[0]; i < off[1]; i++) { + TEST_ASSERT_EQ_I(tgt[i], (row[i] * 37) % 50); + TEST_ASSERT_TRUE(row[i] >= 0 && row[i] < HUB); + } + /* Node 1: 3, 7(row 200), 7(row 202). */ + TEST_ASSERT_EQ_I(off[2] - off[1], 3); + TEST_ASSERT_EQ_I(tgt[off[1]], 3); TEST_ASSERT_EQ_I(row[off[1]], HUB + 1); + TEST_ASSERT_EQ_I(tgt[off[1] + 1], 7); TEST_ASSERT_EQ_I(row[off[1] + 1], HUB); + TEST_ASSERT_EQ_I(tgt[off[1] + 2], 7); TEST_ASSERT_EQ_I(row[off[1] + 2], HUB + 2); + /* Node 2 keeps both edges with their out-of-range dsts as given. */ + TEST_ASSERT_EQ_I(off[3] - off[2], 2); + TEST_ASSERT_EQ_I(tgt[off[2]], -3); + TEST_ASSERT_EQ_I(tgt[off[2] + 1], 61); + + /* Reverse: keyed by dst. Node 5 gets the two edges whose src was out + * of range (their src is stored unchecked); node 7 gets rows 200, 202 + * from src 1 plus whichever hub edges hit 7. */ + int64_t* roff = (int64_t*)ray_data(rel->rev.offsets); + int64_t* rtgt = (int64_t*)ray_data(rel->rev.targets); + int64_t* rrow = (int64_t*)ray_data(rel->rev.rowmap); + TEST_ASSERT_EQ_I(rel->rev.n_edges, HUB + 3 + 2); + TEST_ASSERT_EQ_I(roff[6] - roff[5], 4 + 2); /* 4 hub edges to 5, plus 2 */ + TEST_ASSERT_EQ_I(rtgt[roff[5]], -1); /* src -1 sorts first */ + TEST_ASSERT_EQ_I(rtgt[roff[6] - 1], 60); /* src 60 sorts last */ + for (int64_t i = roff[5] + 1; i < roff[6]; i++) + TEST_ASSERT_TRUE(rtgt[i - 1] < rtgt[i] || + (rtgt[i - 1] == rtgt[i] && rrow[i - 1] < rrow[i])); + int64_t seen_from_1 = 0; + for (int64_t i = roff[7]; i < roff[8]; i++) + if (rtgt[i] == 1) { TEST_ASSERT_TRUE(rrow[i] == HUB || rrow[i] == HUB + 2); seen_from_1++; } + TEST_ASSERT_EQ_I(seen_from_1, 2); + + ray_rel_free(rel); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + const test_entry_t csr_entries[] = { { "csr/tiebreak_determinism", test_csr_tiebreak_determinism, NULL, NULL }, + { "csr/hub_order", test_csr_hub_order, NULL, NULL }, + { "csr/parallel_matches_serial", test_csr_parallel_matches_serial, NULL, NULL }, + { "csr/parallel_fk_matches_serial", test_csr_parallel_fk_matches_serial, NULL, NULL }, + { "csr/parallel_cancel", test_csr_parallel_cancel, NULL, NULL }, { "csr/build", test_csr_build, NULL, NULL }, { "csr/sorted", test_csr_sorted, NULL, NULL }, { "csr/expand", test_expand, NULL, NULL }, diff --git a/test/test_csv.c b/test/test_csv.c index edc81a559..948d4bba2 100644 --- a/test/test_csv.c +++ b/test/test_csv.c @@ -21,7 +21,11 @@ * SOFTWARE. */ +#if !defined(_WIN32) +#define _POSIX_C_SOURCE 200809L /* setenv / unsetenv */ +#endif #include "test.h" +#include "table/table.h" #include #include #include "mem/heap.h" @@ -31,7 +35,9 @@ #include "table/sym.h" #include "ops/idxop.h" #include "core/runtime.h" +#include "core/pool.h" /* the cancelled column finish needs the pool */ #include +#include #include #include #include @@ -219,6 +225,7 @@ static test_result_t test_csv_null_i64(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n10\n\n30\n"); fclose(f); @@ -251,6 +258,7 @@ static test_result_t test_csv_null_i64_unparseable(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n10\nN/A\n30\n"); fclose(f); @@ -280,6 +288,7 @@ static test_result_t test_csv_null_f64(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n1.5\n\n3.5\n"); fclose(f); @@ -311,6 +320,7 @@ static test_result_t test_csv_null_i16(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n10\n\n30\n"); fclose(f); @@ -342,6 +352,7 @@ static test_result_t test_csv_null_i32(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n10\n\n30\n"); fclose(f); @@ -373,6 +384,7 @@ static test_result_t test_csv_null_date(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "d\n2025-01-02\n\n2026-12-31\n"); fclose(f); @@ -402,6 +414,7 @@ static test_result_t test_csv_null_time(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "t\n12:34:56\n\n23:59:59\n"); fclose(f); @@ -431,6 +444,7 @@ static test_result_t test_csv_null_timestamp(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "ts\n2025-01-02T03:04:05\n\n2026-12-31T23:59:59\n"); fclose(f); @@ -461,6 +475,7 @@ static test_result_t test_csv_null_bool(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "flag\ntrue\n\nfalse\n"); fclose(f); @@ -490,6 +505,7 @@ static test_result_t test_csv_null_sym(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "name\nalice\n\nbob\n"); fclose(f); @@ -521,6 +537,7 @@ static test_result_t test_csv_no_nulls_no_null_bitmap(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n10\n20\n30\n"); fclose(f); @@ -543,6 +560,7 @@ static test_result_t test_csv_null_mixed_columns(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "id,val,name\n1,1.5,alice\n,2.5,\n3,,bob\n"); fclose(f); @@ -585,6 +603,7 @@ static test_result_t test_csv_explicit_str_schema(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); /* Mix inline (<=12B), pooled (>12B), empty/null, and a short */ fprintf(f, "id,note\n" "1,hi\n" @@ -634,6 +653,7 @@ static test_result_t test_csv_escaped_str_roundtrip(void) { /* Write a CSV with fields that require quoting/escaping */ FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "s\n" "\"he,llo\"\n" "\"wo\"\"rld\"\n" @@ -670,7 +690,7 @@ static test_result_t test_csv_escaped_str_roundtrip(void) { TEST_ASSERT_MEM_EQ(11, s, "line1\nline2"); /* Write it back out and verify byte-identical CSV */ - const char* tmp2 = "/tmp/rayforce_test_esc2.csv"; + const char* tmp2 = ray_test_tmp("/tmp/rayforce_test_esc2.csv"); ray_err_t err = ray_write_csv(loaded, tmp2); TEST_ASSERT_EQ_I(err, RAY_OK); @@ -754,6 +774,7 @@ static test_result_t test_csv_infer_date(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "d\n2025-01-02\n2026-12-31\n2000-03-15\n"); fclose(f); @@ -775,6 +796,7 @@ static test_result_t test_csv_infer_time(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "t\n12:34:56\n00:00:00\n23:59:59.123\n"); fclose(f); @@ -798,6 +820,7 @@ static test_result_t test_csv_infer_timestamp_promotion(void) { /* Mix of full timestamps with both 'T' and ' ' separators, plus a * date-only sentinel that should be promoted to TIMESTAMP. */ FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "ts\n2025-01-02T03:04:05\n2025-06-07 08:09:10.123456\n2024-12-31\n"); fclose(f); @@ -819,6 +842,7 @@ static test_result_t test_csv_infer_bool(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "b\ntrue\nfalse\nTRUE\nFALSE\n"); fclose(f); @@ -840,6 +864,7 @@ static test_result_t test_csv_infer_f64_specials(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "v\n1.0\n2e10\n-3.5E-2\nnan\nInf\n+inf\n-INF\n"); fclose(f); @@ -862,6 +887,7 @@ static test_result_t test_csv_infer_null_sentinels(void) { /* Sentinel rows alternating with i64 values; column should infer I64. */ FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n10\nN/A\nNA\nnull\nNULL\nNone\nnone\nn/a\nna\n.\n42\n"); fclose(f); @@ -888,6 +914,7 @@ static test_result_t test_csv_infer_promotions(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "n,b\n1,true\n2,0\n3.5,1\n"); fclose(f); @@ -911,6 +938,7 @@ static test_result_t test_csv_tab_delimiter(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "a\tb\tc\n1\t2\t3\n4\t5\t6\n"); fclose(f); @@ -932,6 +960,7 @@ static test_result_t test_csv_no_header(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "10,20\n30,40\n50,60\n"); fclose(f); @@ -954,7 +983,7 @@ static test_result_t test_csv_read_missing_file(void) { ray_heap_init(); (void)ray_sym_init(); - ray_t* loaded = ray_read_csv("/tmp/__rf_csv_does_not_exist_xyz__.csv"); + ray_t* loaded = ray_read_csv(ray_test_tmp("/tmp/__rf_csv_does_not_exist_xyz__.csv")); TEST_ASSERT_TRUE(RAY_IS_ERR(loaded)); ray_sym_destroy(); @@ -975,7 +1004,7 @@ static test_result_t test_csv_write_bad_path(void) { ray_release(vec); /* Directory that doesn't exist -> fopen of tmp_path fails. */ - ray_err_t err = ray_write_csv(tbl, "/tmp/__nonexistent_dir__/out.csv"); + ray_err_t err = ray_write_csv(tbl, ray_test_tmp("/tmp/__nonexistent_dir__/out.csv")); TEST_ASSERT_EQ_I(err, RAY_ERR_IO); /* NULL table / empty path -> RAY_ERR_TYPE. */ @@ -994,6 +1023,7 @@ static test_result_t test_csv_invalid_schema_type(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "x\n1\n2\n"); fclose(f); @@ -1008,6 +1038,7 @@ static test_result_t test_csv_invalid_schema_type(void) { /* Schema too short for ncols also errors out. */ int8_t one_only[1] = { RAY_I64 }; FILE* g = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(g != NULL); fprintf(g, "a,b\n1,2\n"); fclose(g); ray_t* loaded3 = ray_read_csv_opts(TMP_CSV, ',', true, one_only, 1); @@ -1025,6 +1056,7 @@ static test_result_t test_csv_crlf_line_endings(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "a,b\r\n1,2\r\n3,4\r\n"); fclose(f); @@ -1050,6 +1082,7 @@ static test_result_t test_csv_truncated_row(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "a,b,c\n1,2,3\n4\n7,8,9\n"); fclose(f); @@ -1283,6 +1316,7 @@ static test_result_t test_csv_parallel_parse(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "i,s\n"); /* 9000 rows so n_rows > 8192. */ for (int i = 0; i < 9000; i++) @@ -1312,6 +1346,7 @@ static test_result_t test_csv_sym_narrowing(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "k\n"); /* Only three distinct values across many rows. */ for (int i = 0; i < 200; i++) @@ -1348,6 +1383,7 @@ static test_result_t test_csv_explicit_u8_schema(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "v\n"); /* 10 000 rows ⇒ parallel parse path; values 0..255 cycling so the * truncated bytes fully exercise the U8 range. */ @@ -1390,6 +1426,7 @@ static test_result_t test_csv_explicit_i16_schema_with_nulls(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "v\n"); const int N = 1500; for (int i = 0; i < N; i++) { @@ -1433,6 +1470,7 @@ static test_result_t test_csv_explicit_i32_schema(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "v\n"); const int N = 500; for (int i = 0; i < N; i++) fprintf(f, "%d\n", -100000 + i * 137); @@ -1466,6 +1504,7 @@ static test_result_t test_csv_explicit_u8_schema_serial(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "a,b\n"); /* 200 rows; second column missing on every 50th row → triggers * past-row-boundary fill in the parser. */ @@ -1507,6 +1546,7 @@ static test_result_t test_csv_infer_high_cardinality_str(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); fprintf(f, "payload\n"); for (int i = 0; i < 100; i++) fprintf(f, "unique_payload_%03d\n", i); @@ -1576,6 +1616,7 @@ static test_result_t test_csv_interrupt_mid_parse(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); TEST_ASSERT_NOT_NULL(f); fputs("id,payload\n", f); for (int i = 0; i < 200000; i++) { @@ -1616,6 +1657,7 @@ static test_result_t test_csv_progress_never_goes_backwards(void) { (void)ray_sym_init(); FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); TEST_ASSERT_NOT_NULL(f); fputs("payload,symbol\n", f); for (int i = 0; i < 100000; i++) @@ -1784,6 +1826,7 @@ static test_result_t test_csv_sym_id_order(void) { const int NDNEW = 4000; /* "d0".."d3999", first seen at rows 1,4,7,... */ FILE* f = fopen(TMP_CSV, "wb"); + TEST_ASSERT_TRUE(f != NULL); TEST_ASSERT_NOT_NULL(f); fputs("a,b,c,d\n", f); for (int r = 0; r < NROWS; r++) { @@ -1996,6 +2039,50 @@ static test_result_t test_csv_parted_zones(void) { ray_sym_destroy(); ray_heap_destroy(); PASS(); } +/* Index policy: a parted conversion never persists a segment HASH, even for + * an unclustered I64 column spanning four chunks in every partition (the + * shape the splayed converter hashes). Two partitions of 262144 rows, + * converted twice: into a fresh root (staged path) and again into the now + * existing root (non-staged path, which runs ray_splay_build_indexes). + * A guard that passes today; it cannot go red until the policy changes. */ +static test_result_t csv_parted_assert_no_hash(const char* root) { + char leaf[200], sym[200]; + snprintf(sym, sizeof(sym), "%s/.sym", root); + for (int p = 0; p < 2; p++) { + snprintf(leaf, sizeof(leaf), "%s/%d/t", root, p); + ray_t* t = ray_read_splayed(leaf, sym); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + for (int c = 0; c < 2; c++) { + ray_t* v = ray_table_get_col_idx(t, c); + TEST_ASSERT_TRUE(v != NULL); + TEST_ASSERT_FMT(ray_index_kind(v) != RAY_IDX_HASH, "%s partition %d column %d", root, p, c); + } + ray_release(t); + } + PASS(); +} +static test_result_t test_csv_parted_no_segment_hash(void) { + ray_heap_init(); (void)ray_sym_init(); + char root[160]; + snprintf(root, sizeof(root), "%s", ray_test_tmp("/tmp/rayforce-csv-nohash")); + (void)ray_test_rm_rf(root); + FILE* f = fopen(TMP_CSV, "w"); TEST_ASSERT_TRUE(f != NULL); + fputs("u,c\n", f); + for (long long i = 0; i < 524288; i++) fprintf(f, "%lld,%lld\n", (i * 7919) % 1000003, i); + fclose(f); + int8_t types[] = { RAY_I64, RAY_I64 }; + for (int pass = 0; pass < 2; pass++) { /* 0: fresh root (staged); 1: existing root */ + if (pass) TEST_ASSERT_TRUE(access(root, F_OK) == 0); + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV, ',', true, types, 2, NULL, 0, + root, "t", 262144), RAY_OK); + test_result_t r = csv_parted_assert_no_hash(root); + if (r.status != TEST_PASS) return r; + } + (void)ray_test_rm_rf(root); + unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + static test_result_t test_csv_parted_staging(void) { ray_heap_init(); (void)ray_sym_init(); char root[160],partial[200],path[240]; @@ -2037,13 +2124,19 @@ static test_result_t test_csv_parted_staging(void) { unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); PASS(); } -/* 300000 rows streamed in chunks of 100000 (not a multiple of 65536): the - * clustered column carries a 5-chunk zone, the unclustered one a hash (the - * upgrade needs at least four chunks), the STR column a dict, and the - * nullable column a zone whose null bits come from the parse chunks. */ static bool csv_vec_bytes_eq(ray_t* a, ray_t* b, size_t esz) { return a && b && a->len == b->len && !memcmp(ray_data(a), ray_data(b), (size_t)a->len * esz); } +/* index kind of a slot read from the column metadata (generation-explicit: + * the equivalence pass saves compressed, where the slot is not resident) */ +static int csv_slot_index_kind(ray_t* t, int64_t c) { + ray_col_meta_t m; + return ray_table_col_meta_idx(t, c, &m) ? (int)m.index_kind : -1; +} +/* 300000 rows streamed in chunks of 100000 (not a multiple of 65536): both + * integer columns carry a 5-chunk zone (the converters persist no HASH of + * their own: index policy, compressed-columns PI), the STR column a dict, + * and the nullable column a zone whose null bits come from the parse chunks. */ static test_result_t test_csv_splayed_inline_indexes(void) { ray_heap_init(); (void)ray_sym_init(); char dir[128]; snprintf(dir,sizeof(dir),"/tmp/rayforce-csv-inline-%d",(int)getpid()); @@ -2064,7 +2157,18 @@ static test_result_t test_csv_splayed_inline_indexes(void) { TEST_ASSERT_EQ_I(ix->u.chunk_zone.n_chunks,5); TEST_ASSERT_EQ_I(((int64_t*)ray_data(ix->u.chunk_zone.mins))[1],65536); TEST_ASSERT_EQ_I(((int64_t*)ray_data(ix->u.chunk_zone.maxs))[4],299999); - TEST_ASSERT_EQ_I(ray_index_kind(ray_table_get_col_idx(t,1)),RAY_IDX_HASH); + /* the unclustered column keeps its zone (no longer sacrificed for a hash) */ + TEST_ASSERT_EQ_I(csv_slot_index_kind(t,1),RAY_IDX_CHUNK_ZONE); + ray_t* b=ray_table_get_col_idx(t,1); + ray_t* bplain=ray_vec_from_raw(RAY_I64,ray_data(b),b->len); + ray_t* bref=ray_index_chunk_zone_compute(bplain,16); + TEST_ASSERT_TRUE(bref && !RAY_IS_ERR(bref)); + const ray_index_t* bz=ray_index_payload(b->index); + const ray_index_t* brz=ray_index_payload(bref); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(bz->u.chunk_zone.mins,brz->u.chunk_zone.mins,8)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(bz->u.chunk_zone.maxs,brz->u.chunk_zone.maxs,8)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(bz->u.chunk_zone.aggs,brz->u.chunk_zone.aggs,8)); + ray_release(bref); ray_release(bplain); ray_t* s=ray_table_get_col_idx(t,2); TEST_ASSERT_EQ_I(ray_index_kind(s),RAY_IDX_DICT); TEST_ASSERT_EQ_I(ray_index_payload(s->index)->u.dict.n_distinct,500); @@ -2091,10 +2195,11 @@ static test_result_t test_csv_splayed_inline_indexes(void) { PASS(); } -/* Four unclustered I64 columns (hash candidates) and one clustered column, - * converted twice: with the runtime RAM limit as is, and with it lowered so - * every hash wave holds one column (built on the calling thread, outside any - * dispatch). Both conversions must publish identical column files. */ +/* Four unclustered I64 columns and one clustered column, converted twice: + * with the runtime RAM limit as is, and with it lowered to 4 * 58 B * rows. + * Every column carries its chunk zone (no auto HASH) and both conversions + * publish identical column files. Since the hash waves are gone nothing in + * a conversion reads the RAM limit: this guards that non-dependency. */ static bool csv_files_equal(const char* a, const char* b) { FILE* fa = fopen(a, "rb"); FILE* fb = fopen(b, "rb"); bool ok = fa && fb; @@ -2108,8 +2213,8 @@ static bool csv_files_equal(const char* a, const char* b) { if (fb) fclose(fb); return ok; } -static test_result_t test_csv_splayed_hash_waves(void) { - /* a runtime supplies the RAM limit the wave width is derived from */ +static test_result_t test_csv_splayed_ram_independent(void) { + /* a runtime supplies the RAM limit the old wave width was derived from */ ray_runtime_t* rt = ray_runtime_create(0, NULL); TEST_ASSERT_NOT_NULL(rt); char dirs[2][128]; @@ -2124,14 +2229,14 @@ static test_result_t test_csv_splayed_hash_waves(void) { int8_t types[]={RAY_I64,RAY_I64,RAY_I64,RAY_I64,RAY_I64}; int64_t saved = __RUNTIME->ram_limit; for (int run=0; run<2; run++) { - /* 4 * 58 B * 300000 rows: one column per wave */ + /* 4 * 58 B * 300000 rows: the limit the hash waves used to read */ if (run) __RUNTIME->ram_limit = 4LL*58*300000; ray_err_t e=ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,5,NULL,0,dirs[run],100000); __RUNTIME->ram_limit = saved; TEST_ASSERT_EQ_I(e,RAY_OK); ray_t* t=ray_read_splayed(dirs[run],NULL); TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); - for (int c=0;c<4;c++) TEST_ASSERT_EQ_I(ray_index_kind(ray_table_get_col_idx(t,c)),RAY_IDX_HASH); - TEST_ASSERT_EQ_I(ray_index_kind(ray_table_get_col_idx(t,4)),RAY_IDX_CHUNK_ZONE); + for (int c=0;c<4;c++) TEST_ASSERT_EQ_I(csv_slot_index_kind(t,c),RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_EQ_I(csv_slot_index_kind(t,4),RAY_IDX_CHUNK_ZONE); ray_release(t); } const char* names[]={"a","b","c","d","k"}; @@ -2193,12 +2298,187 @@ static test_result_t test_csv_splayed_sentinel_literal(void) { PASS(); } +/* A cancel skips the pool tasks not yet started and the dispatch returns + * normally (#716): a .csv.splayed load cancelled while it appends or + * finishes its columns must fail with a cancel and leave the previous + * generation current, never publish one whose columns missed a chunk or + * were never finished. RAY_CSV_SPLAYED_INJECT places the cancel. */ +static void csv_cancel_write(int64_t rows, int ncols) { + FILE* f = fopen(TMP_CSV, "w"); + if (!f) return; + fputs(ncols == 1 ? "a\n" : "a,b,s,n\n", f); + for (int64_t i = 0; i < rows; i++) { + if (ncols == 1) fprintf(f, "%lld\n", (long long)i); + else fprintf(f, "%lld,%lld,text %lld,%lld\n", (long long)i, (long long)(i * 7), + (long long)i, (long long)(rows - i)); + } + fclose(f); +} +static test_result_t test_csv_splayed_cancel(void) { + ray_heap_init(); (void)ray_sym_init(); + char dir[128]; snprintf(dir,sizeof(dir),"/tmp/rayforce-csv-cancel-%d",(int)getpid()); + csv_test_rm_rf(dir); + int8_t types[] = {RAY_I64,RAY_I64,RAY_STR,RAY_I64}; + csv_cancel_write(10, 4); + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,4,NULL,0,dir,100000),RAY_OK); + /* "append": cancelled from column 0's task, the others run or are + * skipped; "skip": the last column misses the chunk; "close": every + * finish task is skipped (needs the pool); the single column appends + * and finishes in line, so only the load's own checks see the cancel. */ + ray_pool_t* pool = ray_pool_get(); + bool par = pool && pool->n_workers > 0; + struct { const char* step; int ncols; } cases[] = { + {"append",4}, {"skip",4}, {"close",4}, {"append",1}, + }; + for (size_t k = 0; k < sizeof(cases) / sizeof(cases[0]); k++) { + if (!strcmp(cases[k].step, "close") && !par) continue; + csv_cancel_write(5000, cases[k].ncols); + setenv("RAY_CSV_SPLAYED_INJECT", cases[k].step, 1); + ray_err_t e = ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,cases[k].ncols, + NULL,0,dir,100000); + unsetenv("RAY_CSV_SPLAYED_INJECT"); + ray_clear_interrupt(); + TEST_ASSERT_FMT(e == RAY_ERR_CANCEL, "%s over %d columns: got %d, expected a cancel", + cases[k].step, cases[k].ncols, (int)e); + ray_t* t = ray_read_splayed(dir, NULL); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_ncols(t), 4); + for (int c = 0; c < 4; c++) TEST_ASSERT_EQ_I(ray_table_get_col_idx(t, c)->len, 10); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(t, 3)))[0], 10); + ray_release(t); + } + /* an uncancelled load still replaces it */ + csv_cancel_write(5000, 4); + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,4,NULL,0,dir,100000),RAY_OK); + ray_t* t = ray_read_splayed(dir, NULL); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + for (int c = 0; c < 4; c++) TEST_ASSERT_EQ_I(ray_table_get_col_idx(t, c)->len, 5000); + ray_release(t); + csv_test_rm_rf(dir); + /* a first write commits in place with its .d: cancelled before it, + * it leaves no table behind */ + csv_cancel_write(5000, 1); + setenv("RAY_CSV_SPLAYED_INJECT", "append", 1); + ray_err_t e = ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,1,NULL,0,dir,100000); + unsetenv("RAY_CSV_SPLAYED_INJECT"); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + char schema[160]; snprintf(schema, sizeof(schema), "%s/.d", dir); + TEST_ASSERT_TRUE(access(schema, F_OK) != 0); + csv_test_rm_rf(dir); + unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* A cancel that lands once every column is finished (debug builds raise + * one inside the first hash build, RAY_HASH_INJECT=build) still stops the + * load: over an existing table the previous generation stays current, and + * a first write leaves no table (a directory made beforehand keeps what + * else it holds). */ +static test_result_t test_csv_splayed_cancel_hash(void) { + ray_heap_init(); (void)ray_sym_init(); + char dir[128]; snprintf(dir,sizeof(dir),"/tmp/rayforce-csv-hcancel-%d",(int)getpid()); + csv_test_rm_rf(dir); + int8_t types[] = {RAY_I64,RAY_I64}; + FILE* f = fopen(TMP_CSV, "w"); TEST_ASSERT_NOT_NULL(f); + fputs("a,b\n1,2\n3,4\n5,6\n", f); fclose(f); + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,2,NULL,0,dir,100000),RAY_OK); + f = fopen(TMP_CSV, "w"); TEST_ASSERT_NOT_NULL(f); + fputs("a,b\n", f); + for (long long i = 0; i < 300000; i++) + fprintf(f, "%lld,%lld\n", (i * 7919) % 1000003, (i * 104729 + 7) % 1000003); + fclose(f); + setenv("RAY_HASH_INJECT", "build", 1); + ray_err_t e = ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,2,NULL,0,dir,100000); + unsetenv("RAY_HASH_INJECT"); + bool cancelled = ray_interrupted(); + ray_clear_interrupt(); + if (!cancelled) { + csv_test_rm_rf(dir); unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + SKIP("no in-place hash build on this filesystem"); + } + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + ray_t* t = ray_read_splayed(dir, NULL); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_nrows(t), 3); + ray_release(t); + csv_test_rm_rf(dir); + char schema[160], keep[160]; + snprintf(schema, sizeof(schema), "%s/.d", dir); + snprintf(keep, sizeof(keep), "%s/keep.txt", dir); + for (int premade = 0; premade < 2; premade++) { + if (premade) { + TEST_ASSERT_EQ_I(mkdir(dir, 0755), 0); + f = fopen(keep, "w"); TEST_ASSERT_NOT_NULL(f); fputs("foreign\n", f); fclose(f); + } + setenv("RAY_HASH_INJECT", "build", 1); + e = ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,2,NULL,0,dir,100000); + unsetenv("RAY_HASH_INJECT"); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + TEST_ASSERT_TRUE(access(schema, F_OK) != 0); + if (premade) { + TEST_ASSERT_TRUE(access(keep, F_OK) == 0); + char col[160]; snprintf(col, sizeof(col), "%s/a", dir); + TEST_ASSERT_TRUE(access(col, F_OK) != 0); + } else { + TEST_ASSERT_TRUE(access(dir, F_OK) != 0); + } + } + csv_test_rm_rf(dir); + unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* A cancel during the last chunk's appends stops the load before the + * symfile flush: the root .sym a staged load shares with the current + * generation does not take the cancelled load's vocabulary. */ +static int64_t csv_file_size(const char* path) { + struct stat st; + return stat(path, &st) == 0 ? (int64_t)st.st_size : -1; +} +static test_result_t test_csv_splayed_cancel_symfile(void) { + ray_heap_init(); (void)ray_sym_init(); + char dir[128], sym[160]; + snprintf(dir,sizeof(dir),"/tmp/rayforce-csv-scancel-%d",(int)getpid()); + snprintf(sym,sizeof(sym),"%s/.sym",dir); + csv_test_rm_rf(dir); + int8_t types[] = {RAY_SYM}; + FILE* f = fopen(TMP_CSV, "w"); TEST_ASSERT_NOT_NULL(f); + fputs("s\nalpha\nbeta\nalpha\n", f); fclose(f); + for (int run = 0; run < 2; run++) + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,1,NULL,0,dir,100000),RAY_OK); + int64_t before = csv_file_size(sym); + TEST_ASSERT_TRUE(before > 0); + f = fopen(TMP_CSV, "w"); TEST_ASSERT_NOT_NULL(f); + fputs("s\n", f); + for (int i = 0; i < 5000; i++) fprintf(f, "word%05d\n", i); + fclose(f); + setenv("RAY_CSV_SPLAYED_INJECT", "append", 1); + ray_err_t e = ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,1,NULL,0,dir,100000); + unsetenv("RAY_CSV_SPLAYED_INJECT"); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + TEST_ASSERT_EQ_I(csv_file_size(sym), before); + ray_t* t = ray_read_splayed(dir, sym); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_nrows(t), 3); + ray_release(t); + csv_test_rm_rf(dir); + unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + const test_entry_t csv_entries[] = { + { "csv/splayed_cancel", test_csv_splayed_cancel, NULL, NULL }, + { "csv/splayed_cancel_hash", test_csv_splayed_cancel_hash, NULL, NULL }, + { "csv/splayed_cancel_symfile", test_csv_splayed_cancel_symfile, NULL, NULL }, { "csv/splayed_sentinel_literal", test_csv_splayed_sentinel_literal, NULL, NULL }, { "csv/parted_staging", test_csv_parted_staging, NULL, NULL }, { "csv/parted_zones", test_csv_parted_zones, NULL, NULL }, + { "csv/parted_no_segment_hash", test_csv_parted_no_segment_hash, NULL, NULL }, { "csv/splayed_inline_indexes", test_csv_splayed_inline_indexes, NULL, NULL }, - { "csv/splayed_hash_waves", test_csv_splayed_hash_waves, NULL, NULL }, + { "csv/splayed_ram_independent", test_csv_splayed_ram_independent, NULL, NULL }, { "csv/native_pooled_batches", test_csv_native_pooled_batches, NULL, NULL }, { "csv/roundtrip_i64", test_csv_roundtrip_i64, NULL, NULL }, { "csv/roundtrip_guid", test_csv_guid_roundtrip, NULL, NULL }, diff --git a/test/test_datalog.c b/test/test_datalog.c index d4cd9e448..9e3533a10 100644 --- a/test/test_datalog.c +++ b/test/test_datalog.c @@ -30,6 +30,7 @@ #include #include "mem/heap.h" #include "ops/datalog.h" +#include "store/serde.h" #include "table/sym.h" /* ray_read_sym for SYM column inspection */ #include "lang/eval.h" #include /* fprintf in datalog_rf_setup */ @@ -2710,6 +2711,68 @@ static test_result_t test_rule_expr_ownership(void) { PASS(); } +/* A program handle is uniquely owned. A shallow block copy must be + * detached, and serialization must not turn its opaque pointer into an i64. */ +static test_result_t test_program_handle_ownership(void) { + dl_program_t* program = dl_program_new(); + TEST_ASSERT_NOT_NULL(program); + ray_t* handle = ray_alloc(0); + TEST_ASSERT_NOT_NULL(handle); + handle->type = -RAY_I64; + handle->i64 = (int64_t)(uintptr_t)program; + handle->attrs |= RAY_ATTR_DLPROG; + + TEST_ASSERT_EQ_I(ray_serde_size(handle), 0); + uint8_t serialized[16]; + TEST_ASSERT_EQ_I(ray_ser_raw(serialized, handle), 0); + ray_t* copy = ray_alloc_copy(handle); + TEST_ASSERT_NOT_NULL(copy); + TEST_ASSERT_EQ_I(copy->type, -RAY_I64); + TEST_ASSERT_EQ_I(copy->i64, 0); + TEST_ASSERT_FALSE((copy->attrs & RAY_ATTR_DLPROG) != 0); + TEST_ASSERT_TRUE((handle->attrs & RAY_ATTR_DLPROG) != 0); + TEST_ASSERT_EQ_I(handle->i64, (int64_t)(uintptr_t)program); + + ray_release(copy); + ray_release(handle); + + /* HNSW handles use the same opaque-I64 representation and must not be + * serialized as if their pointer payload were an ordinary integer. */ + ray_t* hnsw = ray_alloc(0); + TEST_ASSERT_NOT_NULL(hnsw); + hnsw->type = -RAY_I64; + hnsw->i64 = 1; /* opaque dummy payload; serialization must reject first */ + hnsw->attrs |= RAY_ATTR_HNSW; + TEST_ASSERT_EQ_I(ray_serde_size(hnsw), 0); + TEST_ASSERT_EQ_I(ray_ser_raw(serialized, hnsw), 0); + hnsw->attrs &= (uint8_t)~RAY_ATTR_HNSW; + ray_release(hnsw); + PASS(); +} + +/* Rebinding a live program handle must run the heap finalizer. The trace + * covers both program allocations and their releases, so deleting that + * finalizer makes the net live bytes positive. */ +static test_result_t test_program_rebind_releases(void) { + ray_t* result = ray_eval_str("(set __datalog_owned_prog (dl-program))"); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + ray_release(result); + + ray_mem_trace_t trace; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + result = ray_eval_str("(set __datalog_owned_prog (dl-program))"); + ray_release(result); + ray_mem_trace_end(&trace); + TEST_ASSERT_FMT(trace.net_bytes == 0, + "Datalog handle rebind retained %lld bytes", + (long long)trace.net_bytes); + + result = ray_eval_str( + "(do (dl-free __datalog_owned_prog) (set __datalog_owned_prog 0))"); + ray_release(result); + PASS(); +} + const test_entry_t datalog_entries[] = { { "datalog/source_provenance", test_source_provenance, datalog_setup, datalog_teardown }, { "datalog/source_prov_requires_flag", test_source_prov_requires_flag, datalog_setup, datalog_teardown }, @@ -2779,6 +2842,8 @@ const test_entry_t datalog_entries[] = { { "datalog/nonlinear_closure_chain", test_nonlinear_closure_chain, datalog_setup, datalog_teardown }, { "datalog/const_filter_f64_column", test_const_filter_f64_column, datalog_setup, datalog_teardown }, { "datalog/rule_expr_ownership", test_rule_expr_ownership, datalog_setup, datalog_teardown }, + { "datalog/program_handle_ownership", test_program_handle_ownership, datalog_setup, datalog_teardown }, + { "datalog/program_rebind_releases", test_program_rebind_releases, datalog_rf_setup, datalog_rf_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_dict.c b/test/test_dict.c index 7d97a1074..61247ca58 100644 --- a/test/test_dict.c +++ b/test/test_dict.c @@ -83,6 +83,56 @@ static test_result_t test_dict_new_err_vals(void) { PASS(); } +/* When both inputs are distinct errors, the returned keys error remains + * caller-owned and the otherwise orphaned vals error must be freed here. */ +static test_result_t test_dict_new_both_errors(void) { + ray_mem_trace_t trace; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + ray_t* keys = ray_error("test", "keys"); + ray_t* vals = ray_error("test", "vals"); + ray_t* d = ray_dict_new(keys, vals); + bool propagated = d == keys && RAY_IS_ERR(d); + ray_error_free(d); + ray_mem_trace_end(&trace); + TEST_ASSERT_TRUE(propagated); + TEST_ASSERT_FMT(trace.net_bytes == 0, + "both-error path retained %lld bytes", + (long long)trace.net_bytes); + PASS(); +} + +/* Aliased errors are one object: preserve it for the caller to free once. */ +static test_result_t test_dict_new_aliased_error(void) { + ray_mem_trace_t trace; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + ray_t* err = ray_error("test", "shared"); + ray_t* d = ray_dict_new(err, err); + bool propagated = d == err && RAY_IS_ERR(d); + ray_error_free(d); + ray_mem_trace_end(&trace); + TEST_ASSERT_TRUE(propagated); + TEST_ASSERT_FMT(trace.net_bytes == 0, + "aliased-error path retained %lld bytes", + (long long)trace.net_bytes); + PASS(); +} + +/* A NULL keys pointer still owns and must free an error passed as vals. */ +static test_result_t test_dict_new_null_keys_error_vals(void) { + ray_mem_trace_t trace; + TEST_ASSERT_TRUE(ray_mem_trace_begin()); + ray_t* vals = ray_error("test", "vals"); + ray_t* d = ray_dict_new(NULL, vals); + bool returned_error = RAY_IS_ERR(d); + ray_error_free(d); + ray_mem_trace_end(&trace); + TEST_ASSERT_TRUE(returned_error); + TEST_ASSERT_FMT(trace.net_bytes == 0, + "NULL-keys/error-vals path retained %lld bytes", + (long long)trace.net_bytes); + PASS(); +} + /* ---- ray_dict_keys / ray_dict_vals / ray_dict_len NULL paths ----------- */ static test_result_t test_dict_keys_null(void) { @@ -1341,6 +1391,9 @@ const test_entry_t dict_entries[] = { { "dict/new_null_vals", test_dict_new_null_vals, dict_setup, dict_teardown }, { "dict/new_err_keys", test_dict_new_err_keys, dict_setup, dict_teardown }, { "dict/new_err_vals", test_dict_new_err_vals, dict_setup, dict_teardown }, + { "dict/new_both_errors", test_dict_new_both_errors, dict_setup, dict_teardown }, + { "dict/new_aliased_error", test_dict_new_aliased_error, dict_setup, dict_teardown }, + { "dict/new_null_keys_error_vals", test_dict_new_null_keys_error_vals, dict_setup, dict_teardown }, { "dict/keys_null", test_dict_keys_null, dict_setup, dict_teardown }, { "dict/keys_nondict", test_dict_keys_nondict, dict_setup, dict_teardown }, { "dict/keys_err", test_dict_keys_err, dict_setup, dict_teardown }, diff --git a/test/test_domain.c b/test/test_domain.c index b9a042b14..9c247080d 100644 --- a/test/test_domain.c +++ b/test/test_domain.c @@ -36,6 +36,8 @@ */ #include "test.h" +#include "ipc_harness.h" /* an IPC reply of corrupt symbols */ +#include "app/repl.h" /* ray_repl_run_file: the REPL display */ #include #include "mem/heap.h" #include "table/sym.h" @@ -52,8 +54,11 @@ #include #include #include +#include /* utimensat: a modification time set back */ +#include /* stat: the symfile size behind the mapping counters */ #include /* setenv */ #include +#include /* nanosleep: a later modification time */ #define TMP_DOM_SYM_PATH "/tmp/rayforce_test_domain_sym" #define TMP_DOM_COL_PATH "/tmp/rayforce_test_domain_col" @@ -65,7 +70,19 @@ static void domain_setup(void) { (void)ray_sym_init(); } +/* What an index test leaves when it fails early (its own cleanup is at its + * end): the knob it set and its files, so the next test starts clean. */ +static void domain_ix_cleanup(void) { + unsetenv("RAY_SYM_INDEX_MIN"); + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(TMP_DOM_SYM_PATH ".ix"); +} + static void domain_teardown(void) { + domain_ix_cleanup(); + ray_clear_interrupt(); + ray_sym_domain_batch_cancel_for_test(0); /* disarm a hook a test left armed */ ray_sym_destroy(); ray_heap_destroy(); } @@ -289,7 +306,7 @@ static test_result_t test_domain_serde_roundtrip(void) { static test_result_t test_domain_col_save_load_mmap(void) { ray_sym_domain_t* rt = ray_sym_runtime_domain(); - unlink(TMP_DOM_COL_PATH); + unlink(ray_test_tmp(TMP_DOM_COL_PATH)); int64_t ida = ray_sym_intern("col_a", 5); int64_t idb = ray_sym_intern("col_b", 5); @@ -303,12 +320,12 @@ static test_result_t test_domain_col_save_load_mmap(void) { * verbatim — the on-disk header must still be pointer-free. */ v->attrs |= RAY_ATTR_HAS_NULLS; - TEST_ASSERT_EQ_I(ray_col_save(v, TMP_DOM_COL_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(v, ray_test_tmp(TMP_DOM_COL_PATH)), RAY_OK); /* Domain pointer never serialized: scan the file bytes. */ { ray_sym_domain_t* dom = v->sym_domain; - FILE* f = fopen(TMP_DOM_COL_PATH, "rb"); + FILE* f = fopen(ray_test_tmp(TMP_DOM_COL_PATH), "rb"); TEST_ASSERT_NOT_NULL(f); uint8_t buf[4096]; size_t n = fread(buf, 1, sizeof(buf), f); @@ -321,13 +338,13 @@ static test_result_t test_domain_col_save_load_mmap(void) { TEST_ASSERT_FALSE(found); } - ray_t* loaded = ray_col_load(TMP_DOM_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_DOM_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_SYM); TEST_ASSERT_EQ_PTR(loaded->sym_domain, rt); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_DOM_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_DOM_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->type, RAY_SYM); TEST_ASSERT_EQ_PTR(mapped->sym_domain, rt); @@ -335,22 +352,22 @@ static test_result_t test_domain_col_save_load_mmap(void) { ray_release(mapped); ray_release(v); - unlink(TMP_DOM_COL_PATH); + unlink(ray_test_tmp(TMP_DOM_COL_PATH)); PASS(); } /* ---- FILE domains over a real symfile ----------------------------------- */ static test_result_t test_domain_open_basic(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); int64_t id_h = ray_sym_intern("file_hello", 10); int64_t id_w = ray_sym_intern("file_world", 10); uint32_t count_at_save = ray_sym_count(); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); - ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); TEST_ASSERT(dom != ray_sym_runtime_domain(), "FILE domain is not the singleton"); @@ -401,14 +418,14 @@ static test_result_t test_domain_open_basic(void) { TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, true), RAY_OK); TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, true), RAY_OK); /* idempotent */ ray_sym_domain_release(dom); - ray_sym_domain_t* re = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* re = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(re); TEST_ASSERT_EQ_I(ray_sym_domain_count(re), (int64_t)count_at_save + 1); TEST_ASSERT_EQ_I(ray_sym_domain_find(re, "file_new", 8), new_pos); ray_sym_domain_release(re); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -419,11 +436,11 @@ static test_result_t test_domain_open_basic(void) { * new distinct strings, a second identical batch changes nothing and "" * is position 0. */ static test_result_t test_domain_intern_batch(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); TEST_ASSERT_NOT_NULL(ray_pool_get()); /* parallel probe path */ - ray_sym_domain_t* dom = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); enum { NV = 20000, NB = 60000, SL = 16 }; @@ -499,7 +516,7 @@ static test_result_t test_domain_intern_batch(void) { /* the flushed file reopens with the same vocabulary */ TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, false), RAY_OK); ray_sym_domain_release(dom); - ray_sym_domain_t* re = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* re = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(re); TEST_ASSERT_EQ_I(ray_sym_domain_count(re), NV + 2); for (int j = 0; j < NB; j += 997) @@ -509,6 +526,79 @@ static test_result_t test_domain_intern_batch(void) { ray_sys_free(vocab); ray_sys_free(pre); ray_sys_free(seen); ray_sys_free(strs); ray_sys_free(lens); ray_sys_free(hashes); ray_sys_free(pos); ray_sys_free(pos2); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); + PASS(); +} + +/* A cancelled pool dispatch can skip tasks while still returning normally. + * The batch intern must not classify misses or commit dedupe output from + * arrays those skipped tasks never filled. */ +static test_result_t test_domain_intern_batch_cancel(void) { + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "seed", 4), 1); + int64_t before = ray_sym_domain_count(dom); + + enum { N = 8192, SL = 24 }; + char* storage = ray_sys_alloc((size_t)N * SL); + const char** strs = ray_sys_alloc((size_t)N * sizeof(*strs)); + size_t* lens = ray_sys_alloc((size_t)N * sizeof(*lens)); + uint32_t* hashes = ray_sys_alloc((size_t)N * sizeof(*hashes)); + int64_t* out = ray_sys_alloc((size_t)N * sizeof(*out)); + TEST_ASSERT_NOT_NULL(storage); TEST_ASSERT_NOT_NULL(strs); + TEST_ASSERT_NOT_NULL(lens); TEST_ASSERT_NOT_NULL(hashes); TEST_ASSERT_NOT_NULL(out); + for (int64_t i = 0; i < N; i++) { + snprintf(storage + (size_t)i * SL, SL, "cancel-%07lld", (long long)i); + strs[i] = storage + (size_t)i * SL; + lens[i] = strlen(strs[i]); + hashes[i] = (uint32_t)ray_hash_bytes(strs[i], lens[i]); + } + + /* out is zero-filled: a skipped probe task then leaves "hits" at + * position 0 behind, which the pre-fix code took as a complete probe + * with no misses and returned true with those ids. */ + const int phases[] = {RAY_SYM_DOMAIN_CANCEL_PROBE, RAY_SYM_DOMAIN_CANCEL_DEDUPE}; + for (size_t p = 0; p < sizeof(phases) / sizeof(phases[0]); p++) { + memset(out, 0, (size_t)N * sizeof(*out)); + ray_sym_domain_batch_cancel_for_test(phases[p]); + TEST_ASSERT_FALSE(ray_sym_domain_intern_batch(dom, N, strs, lens, hashes, out)); + TEST_ASSERT_TRUE(ray_interrupted()); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), before); + for (int64_t i = 0; i < N; i += 257) + TEST_ASSERT_EQ_I(ray_sym_domain_find(dom, strs[i], lens[i]), -1); + } + + /* A cancel that lands once the commit has begun is too late to stop + * it: the parallel insert skips tasks, the caller completes them, and + * the batch is published whole. */ + ray_sym_domain_batch_cancel_for_test(RAY_SYM_DOMAIN_CANCEL_INSERT); + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch(dom, N, strs, lens, hashes, out)); + TEST_ASSERT_TRUE(ray_interrupted()); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), before + N); + for (int64_t i = 0; i < N; i++) + TEST_ASSERT_EQ_I(ray_sym_domain_find(dom, strs[i], lens[i]), out[i]); + for (int64_t i = 0; i < N; i += 257) + TEST_ASSERT_EQ_I(out[i], before + i); + + /* And a second batch of new strings, uncancelled, lands after them. */ + for (int64_t i = 0; i < N; i++) { + snprintf(storage + (size_t)i * SL, SL, "second-%07lld", (long long)i); + lens[i] = strlen(strs[i]); + hashes[i] = (uint32_t)ray_hash_bytes(strs[i], lens[i]); + } + TEST_ASSERT_TRUE(ray_sym_domain_intern_batch(dom, N, strs, lens, hashes, out)); + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), before + 2 * N); + for (int64_t i = 0; i < N; i += 257) + TEST_ASSERT_EQ_I(ray_sym_domain_find(dom, strs[i], lens[i]), out[i]); + + ray_sym_domain_release(dom); + ray_sys_free(storage); ray_sys_free(strs); ray_sys_free(lens); + ray_sys_free(hashes); ray_sys_free(out); unlink(TMP_DOM_SYM_PATH); unlink(TMP_DOM_SYM_PATH ".lk"); PASS(); @@ -546,9 +636,9 @@ static void domain_concurrent_batch_task(void* raw, uint32_t wid, int64_t start, * Check all returned positions and the persisted domain, including a second * all-hit pass after the concurrent growth. */ static test_result_t test_domain_intern_batch_concurrent(void) { - unlink(TMP_DOM_SYM_PATH); unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); domain_concurrent_batch_t ctx = {0}; - ctx.domain = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + ctx.domain = ray_sym_domain_open_or_create(ray_test_tmp(TMP_DOM_SYM_PATH)); ctx.vocabulary = ray_sys_alloc(DOM_CONCURRENT_VOCAB*DOM_CONCURRENT_STRING); ctx.positions = ray_sys_alloc(DOM_CONCURRENT_TASKS*DOM_CONCURRENT_BATCH*sizeof(int64_t)); TEST_ASSERT_NOT_NULL(ctx.domain); TEST_ASSERT_NOT_NULL(ctx.vocabulary); TEST_ASSERT_NOT_NULL(ctx.positions); @@ -574,12 +664,12 @@ static test_result_t test_domain_intern_batch_concurrent(void) { } TEST_ASSERT_EQ_I(ray_sym_domain_flush(ctx.domain, false), RAY_OK); ray_sym_domain_release(ctx.domain); - ctx.domain = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ctx.domain = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(ctx.domain); } ray_sym_domain_release(ctx.domain); ray_sys_free(ctx.vocabulary); ray_sys_free(ctx.positions); - unlink(TMP_DOM_SYM_PATH); unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -587,13 +677,13 @@ static test_result_t test_domain_intern_batch_concurrent(void) { * domain; "" is seeded at position 0 by the first intern; flush creates * the file; verify-base-unchanged makes a racing writer LOUD. */ static test_result_t test_domain_create_flush_concurrent(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); /* plain open of a missing file still fails */ - TEST_ASSERT_NULL(ray_sym_domain_open(TMP_DOM_SYM_PATH)); + TEST_ASSERT_NULL(ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH))); - ray_sym_domain_t* dom = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), 0); @@ -608,7 +698,7 @@ static test_result_t test_domain_create_flush_concurrent(void) { /* flush creates the file with "" first */ TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, false), RAY_OK); { - FILE* f = fopen(TMP_DOM_SYM_PATH, "rb"); + FILE* f = fopen(ray_test_tmp(TMP_DOM_SYM_PATH), "rb"); TEST_ASSERT_NOT_NULL(f); uint32_t magic = 0, len0 = 1; int64_t cnt = -1; @@ -625,7 +715,7 @@ static test_result_t test_domain_create_flush_concurrent(void) { * under us; the next flush of OUR dirty tail must fail loudly. */ TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "cre_b", 5), 2); { - FILE* f = fopen(TMP_DOM_SYM_PATH, "wb"); + FILE* f = fopen(ray_test_tmp(TMP_DOM_SYM_PATH), "wb"); TEST_ASSERT_NOT_NULL(f); uint32_t magic = 0x4C525453u; int64_t cnt = 1; @@ -638,9 +728,9 @@ static test_result_t test_domain_create_flush_concurrent(void) { TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, false), RAY_ERR_CORRUPT); ray_sym_domain_release(dom); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); - unlink(TMP_DOM_SYM_PATH ".tmp"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".tmp")); PASS(); } @@ -663,15 +753,15 @@ static test_result_t test_domain_create_flush_concurrent(void) { * reopen stays clean and the drop hook keeps the cache coherent. */ #define TMP_DOM_RECYCLE_PATH "/tmp/rayforce_test_domain_recycle_sym" static test_result_t test_domain_survives_heap_recycle(void) { - unlink(TMP_DOM_RECYCLE_PATH); - unlink(TMP_DOM_RECYCLE_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_RECYCLE_PATH)); + unlink(ray_test_tmp(TMP_DOM_RECYCLE_PATH ".lk")); /* --- heap A: open a domain with a SMALL vocabulary --- */ ray_heap_init(); (void)ray_sym_init(); (void)ray_sym_intern("recyc_a", 7); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_RECYCLE_PATH), RAY_OK); - ray_sym_domain_t* d1 = ray_sym_domain_open(TMP_DOM_RECYCLE_PATH); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_RECYCLE_PATH)), RAY_OK); + ray_sym_domain_t* d1 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_RECYCLE_PATH)); TEST_ASSERT_NOT_NULL(d1); /* atoms now live on heap A */ /* Deliberately DO NOT release d1 — it stays in the global cache, * exactly the leak that exposed the dangling bug. */ @@ -689,35 +779,35 @@ static test_result_t test_domain_survives_heap_recycle(void) { } (void)ray_sym_intern("recyc_a", 7); (void)ray_sym_intern("recyc_b", 7); /* different vocabulary/size */ - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_RECYCLE_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_RECYCLE_PATH)), RAY_OK); /* Re-open the SAME path. Pre-fix: cache hit on the stale d1; the * size differs so dom_extend dereferences d1's atoms (freed, now * overwritten by the churn above) → SEGV or garbage. Post-fix: the * stale entry is gone, so this builds a fresh domain. */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_RECYCLE_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_RECYCLE_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_t* s0 = ray_sym_domain_str(d2, 0); /* touch the atoms */ TEST_ASSERT_NOT_NULL(s0); TEST_ASSERT_EQ_U(ray_str_len(s0), 0); /* position 0 is "" */ ray_sym_domain_release(d2); - unlink(TMP_DOM_RECYCLE_PATH); - unlink(TMP_DOM_RECYCLE_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_RECYCLE_PATH)); + unlink(ray_test_tmp(TMP_DOM_RECYCLE_PATH ".lk")); ray_sym_destroy(); ray_heap_destroy(); PASS(); } static test_result_t test_domain_open_identity_and_release(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); (void)ray_sym_intern("ident_x", 7); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); /* Same resolved path => same object (pointer equality = identity). */ - ray_sym_domain_t* d1 = ray_sym_domain_open(TMP_DOM_SYM_PATH); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* d1 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(d1); TEST_ASSERT_EQ_PTR(d1, d2); @@ -730,17 +820,17 @@ static test_result_t test_domain_open_identity_and_release(void) { /* Last release dropped the cache entry: a fresh open must build a * fresh, fully functional mapping (and not crash under ASan). */ - ray_sym_domain_t* d3 = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* d3 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(d3); TEST_ASSERT_EQ_I(ray_sym_domain_find(d3, "ident_x", 7), ray_sym_find("ident_x", 7)); ray_sym_domain_release(d3); /* Missing file -> NULL, no crash. */ - TEST_ASSERT_NULL(ray_sym_domain_open("/tmp/rayforce_test_domain_nonexistent")); + TEST_ASSERT_NULL(ray_sym_domain_open(ray_test_tmp("/tmp/rayforce_test_domain_nonexistent"))); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -811,14 +901,14 @@ static test_result_t test_domain_vec_lookup_hit_miss(void) { /* adopt_domain: ref balance with a real FILE domain (ASan is the leak * oracle), plus cell/lookup resolution through the adopted domain. */ static test_result_t test_domain_adopt_domain_refcount(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); (void)ray_sym_intern("adopt_x", 7); (void)ray_sym_intern("adopt_y", 7); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); - ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); int64_t pos_x = ray_sym_domain_find(dom, "adopt_x", 7); @@ -882,13 +972,13 @@ static test_result_t test_domain_adopt_domain_refcount(void) { /* Balance proof: the cache entry must be gone; a fresh open builds a * fully functional mapping (ASan flags any leak/double-free). */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(d2); TEST_ASSERT_EQ_I(ray_sym_domain_find(d2, "adopt_x", 7), pos_x); ray_sym_domain_release(d2); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -897,7 +987,7 @@ static test_result_t test_domain_adopt_domain_refcount(void) { /* Pivot needs the full eval runtime, not just heap + sym table. */ static ray_runtime_t* pvt_rt; static void domain_rt_setup(void) { pvt_rt = ray_runtime_create(0, NULL); } -static void domain_rt_teardown(void) { ray_runtime_destroy(pvt_rt); } +static void domain_rt_teardown(void) { domain_ix_cleanup(); ray_runtime_destroy(pvt_rt); } /* A SYM index column carrying a FILE domain must hand that domain to the * pivot output's index column (the output raw-copies cell ids, so it must @@ -905,16 +995,16 @@ static void domain_rt_teardown(void) { ray_runtime_destroy(pvt_rt); } * attaches the runtime singleton, and only the adopt call at the pivot * scatter site transfers the FILE-domain pointer. */ static test_result_t test_domain_pivot_index_adopts(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); int64_t id_A = ray_sym_intern("pd_A", 4); int64_t id_B = ray_sym_intern("pd_B", 4); int64_t id_x = ray_sym_intern("pd_x", 4); int64_t id_y = ray_sym_intern("pd_y", 4); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); - ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); /* Index col 'a': manually attached to the FILE domain (positions @@ -979,12 +1069,12 @@ static test_result_t test_domain_pivot_index_adopts(void) { ray_release(t); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -1004,12 +1094,12 @@ static test_result_t test_domain_pivot_index_adopts(void) { * of dq_a/dq_b. Returns false if the fixture could not be built. */ static int build_divergent_qsym_fixture(ray_sym_domain_t** out_dom, int64_t* pos_a, int64_t* pos_b) { - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); (void)ray_sym_intern("dq_a", 4); (void)ray_sym_intern("dq_b", 4); - if (ray_sym_save(TMP_DOM_QSYM_PATH) != RAY_OK) return 0; + if (ray_sym_save(ray_test_tmp(TMP_DOM_QSYM_PATH)) != RAY_OK) return 0; /* Restart: fresh global table, REVERSED intern order. */ ray_runtime_destroy(pvt_rt); @@ -1018,7 +1108,7 @@ static int build_divergent_qsym_fixture(ray_sym_domain_t** out_dom, (void)ray_sym_intern("dq_b", 4); (void)ray_sym_intern("dq_a", 4); - ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); if (!dom) return 0; *pos_a = ray_sym_domain_find(dom, "dq_a", 4); *pos_b = ray_sym_domain_find(dom, "dq_b", 4); @@ -1105,12 +1195,12 @@ static test_result_t test_domain_query_upsert_key_lookup(void) { ray_sym_domain_release(dom); /* ref balance: the cache entry must be gone (fresh open rebuilds) */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1148,12 +1238,12 @@ static test_result_t test_domain_query_insert_cell_reexpress(void) { ray_release(t); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1234,12 +1324,12 @@ static test_result_t test_domain_gather_adopts_domain(void) { ray_sym_domain_release(dom); /* ref balance: the cache entry must be gone (fresh open rebuilds) */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1356,12 +1446,12 @@ static test_result_t test_domain_group_by_adopts_domain(void) { ray_sym_domain_release(dom); /* ref balance: the cache entry must be gone (fresh open rebuilds) */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1447,12 +1537,12 @@ static test_result_t test_domain_r7_eq_fast_path(void) { ray_sym_domain_release(dom); /* ref balance: the cache entry must be gone (fresh open rebuilds) */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1512,12 +1602,12 @@ static test_result_t test_domain_sort_and_upper_resolve_domain(void) { ray_release(t); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1569,12 +1659,12 @@ static test_result_t test_domain_serde_sym_file_domain(void) { ray_release(t); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1639,12 +1729,12 @@ static test_result_t test_domain_join_across_domains(void) { ray_release(lt); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1706,12 +1796,12 @@ static test_result_t test_domain_asof_join_across_domains(void) { ray_release(lt); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1811,12 +1901,12 @@ static test_result_t test_domain_parted_flatten_adopts(void) { ray_release(t); ray_sym_domain_release(dom); - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -1828,15 +1918,15 @@ static test_result_t test_domain_parted_flatten_adopts(void) { * resolved bytes match the vocabulary — i.e. behavior is unchanged from * the lazy per-position cache, minus the per-call lock. */ static test_result_t test_domain_str_eager_lockfree(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); int64_t id_a = ray_sym_intern("eager_a", 7); int64_t id_b = ray_sym_intern("eager_b", 7); uint32_t count_at_save = ray_sym_count(); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); - ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_sym_domain_t* dom = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); /* First touch after open: walk EVERY position before any find/LUT @@ -1860,8 +1950,8 @@ static test_result_t test_domain_str_eager_lockfree(void) { TEST_ASSERT_NULL(ray_sym_domain_str(dom, -1)); ray_sym_domain_release(dom); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -1869,14 +1959,14 @@ static test_result_t test_domain_str_eager_lockfree(void) { * bytes and length straight from the mapping, equal to the materialised * atom; the runtime singleton refuses; pins nest and release. */ static test_result_t test_domain_raw_pin(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); int64_t id_a = ray_sym_intern("raw_alpha", 9); int64_t id_b = ray_sym_intern("raw_beta_longer_entry", 21); (void)id_a; (void)id_b; uint32_t count_at_save = ray_sym_count(); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); - ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); + ray_sym_domain_t* dom = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(dom); ray_sym_domain_raw_t raw; TEST_ASSERT_FALSE(ray_sym_domain_raw_pin(ray_sym_runtime_domain(), &raw)); @@ -1902,14 +1992,14 @@ static test_result_t test_domain_raw_pin(void) { TEST_ASSERT_EQ_I(raw.count, (int64_t)count_at_save); ray_sym_domain_raw_unpin(dom); ray_sym_domain_release(dom); - /* The file grows under another writer while a reader holds a snapshot: - * the reopen extends the domain (new mapping, new offsets), and the - * old snapshot must still read every old position from its retired - * mapping, while a fresh pin sees the grown prefix. */ - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); - ray_sym_domain_t* d1 = ray_sym_domain_open(TMP_DOM_SYM_PATH); + /* The file grows under another writer: the reopen extends the domain + * (new mapping, new offsets, the old ones freed), and a pin taken after + * it covers the grown prefix and still reads every old position. A pin + * taken before the reopen is not readable after it (domain.h). */ + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); + ray_sym_domain_t* d1 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(d1); ray_sym_domain_raw_t held; TEST_ASSERT(ray_sym_domain_raw_pin(d1, &held), "pin before growth"); @@ -1918,28 +2008,266 @@ static test_result_t test_domain_raw_pin(void) { char buf[32]; int n = snprintf(buf, sizeof buf, "raw_grow_%d", i); (void)ray_sym_intern(buf, (size_t)n); } - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); /* grown image, same prefix */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_SYM_PATH); /* cache hit → extend */ + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); /* grown image, same prefix */ + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); /* cache hit → extend */ TEST_ASSERT_EQ_PTR(d2, d1); TEST_ASSERT(ray_sym_domain_count(d1) > before, "reopen extended the domain"); + ray_sym_domain_raw_t fresh; + TEST_ASSERT(ray_sym_domain_raw_pin(d1, &fresh), "pin after growth"); + TEST_ASSERT(fresh.count > before, "fresh snapshot covers the grown prefix"); for (int64_t p = 0; p < before; p++) { size_t rl = 0; - const char* rp = ray_sym_domain_raw_str(&held, p, &rl); + const char* rp = ray_sym_domain_raw_str(&fresh, p, &rl); ray_t* g = ray_sym_str(p); TEST_ASSERT_EQ_U(rl, ray_str_len(g)); TEST_ASSERT_MEM_EQ(rl, rp, ray_str_ptr(g)); } - ray_sym_domain_raw_t fresh; - TEST_ASSERT(ray_sym_domain_raw_pin(d1, &fresh), "pin after growth"); - TEST_ASSERT(fresh.count > before, "fresh snapshot covers the grown prefix"); ray_sym_domain_raw_unpin(d1); ray_sym_domain_raw_unpin(d1); ray_sym_domain_release(d2); ray_sym_domain_release(d1); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); + PASS(); +} + +/* #717: a reader that reopens a symfile another process grew must keep + * memory proportional to the vocabulary, however many times it reopened. + * Each reopen is a cache hit that extends the domain; the arrays it + * replaces and the mapping it supersedes used to be retired until the + * domain died — and a replica never lets it die. */ +static test_result_t test_domain_extend_reopen_flat(void) { + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + enum { VOCAB = 20000, WARM = 2, CYCLES = 30, PER_CYCLE = 10 }; + for (int i = 0; i < VOCAB; i++) { + char b[32]; int n = snprintf(b, sizeof b, "flat_base_%d", i); + (void)ray_sym_intern(b, (size_t)n); + } + TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + int64_t map_before_open = 0; + ray_sys_get_mapped(&map_before_open, NULL); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + int64_t base = ray_sym_domain_count(dom); + + int64_t sys0 = 0, next = 0; + for (int c = 0; c < WARM + CYCLES; c++) { + if (c == WARM) ray_sys_get_stat(&sys0, NULL); + for (int j = 0; j < PER_CYCLE; j++, next++) { + char b[32]; int n = snprintf(b, sizeof b, "flat_new_%lld", (long long)next); + (void)ray_sym_intern(b, (size_t)n); + } + TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); /* tmp + rename: a new inode */ + ray_sym_domain_t* again = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_EQ_PTR(again, dom); /* cache hit → extend */ + TEST_ASSERT_EQ_I(ray_sym_domain_count(dom), base + next); + /* the grown tail resolves both ways: lazily materialised atom and + * reverse index (rebuilt over the grown vocabulary) */ + char last[32]; int ln = snprintf(last, sizeof last, "flat_new_%lld", (long long)(next - 1)); + ray_t* s = ray_sym_domain_str(dom, base + next - 1); + TEST_ASSERT_NOT_NULL(s); + TEST_ASSERT_EQ_U(ray_str_len(s), (size_t)ln); + TEST_ASSERT_MEM_EQ((size_t)ln, ray_str_ptr(s), last); + TEST_ASSERT_EQ_I(ray_sym_domain_find(dom, last, (size_t)ln), base + next - 1); + ray_sym_domain_release(again); + } + int64_t sys1 = 0, map1 = 0; + ray_sys_get_stat(&sys1, NULL); + ray_sys_get_mapped(&map1, NULL); + struct stat st; + TEST_ASSERT_EQ_I(stat(TMP_DOM_SYM_PATH, &st), 0); + int64_t one_image = ((int64_t)st.st_size + 4095) & ~(int64_t)4095; + /* a pin taken after the growth covers the whole grown prefix (a pin + * taken before a reopen is not readable after it: see domain.h) */ + ray_sym_domain_raw_t fresh; + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &fresh), "pin after growth"); + TEST_ASSERT_EQ_I(fresh.count, base + next); + for (int64_t p = 0; p < base + next; p += 997) { + size_t rl = 0; + const char* rp = ray_sym_domain_raw_str(&fresh, p, &rl); + ray_t* g = ray_sym_str(p); + TEST_ASSERT_EQ_U(rl, ray_str_len(g)); + TEST_ASSERT_MEM_EQ(rl, rp, ray_str_ptr(g)); + } + ray_sym_domain_raw_unpin(dom); + ray_sym_domain_release(dom); + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + /* committed RAM: nothing per reopen (slack for the atoms materialised + * above and arena growth); file mappings: exactly one image of the + * current file, whatever the number of reopens. Asserted once the + * domain is released, so a failure leaves none cached behind it. */ + /* The leak was one generation per reopen: two pointer-sized arrays + * over the vocabulary, about 320 KB each cycle here, 9.6 MB over the + * run. The bound leaves room for arena and hash-table growth. */ + TEST_ASSERT_FMT(sys1 - sys0 <= 1024 * 1024, + "sys-current grew by %lld bytes over %d reopens", + (long long)(sys1 - sys0), CYCLES); + TEST_ASSERT_FMT(map1 - map_before_open == one_image, + "sys-mapped holds %lld bytes for a %lld-byte symfile", + (long long)(map1 - map_before_open), (long long)one_image); + PASS(); +} +/* Write `words` as the symfile at `path` the way another process's writer + * does: a tmp file renamed over it (a new inode). */ +static bool write_symfile(const char* path, const char* const* words, int n) { + char tmp[256]; + snprintf(tmp, sizeof tmp, "%s.ext", path); + FILE* f = fopen(tmp, "wb"); + if (!f) return false; + uint32_t magic = 0x4C525453U; /* "STRL" */ + int64_t count = n; + bool ok = fwrite(&magic, 4, 1, f) == 1 && fwrite(&count, 8, 1, f) == 1; + for (int i = 0; ok && i < n; i++) { + uint32_t l = (uint32_t)strlen(words[i]); + ok = fwrite(&l, 4, 1, f) == 1 && (l == 0 || fwrite(words[i], 1, l, f) == l); + } + ok = fclose(f) == 0 && ok; + return ok && rename(tmp, path) == 0; +} + +/* Every position resolves to words[pos], by position and by string, and + * a raw pin covers them all: the extend made them file positions. */ +static bool dom_holds(ray_sym_domain_t* dom, const char* const* words, int n) { + if (ray_sym_domain_count(dom) != n) return false; + ray_sym_domain_raw_t raw; + if (!ray_sym_domain_raw_pin(dom, &raw) || raw.count != n) return false; + for (int p = 0; p < n; p++) { + size_t l = strlen(words[p]), rl = 0; + ray_t* s = ray_sym_domain_str(dom, p); + const char* rp = ray_sym_domain_raw_str(&raw, p, &rl); + if (!s || ray_str_len(s) != l || memcmp(ray_str_ptr(s), words[p], l) != 0 || + rl != l || memcmp(rp, words[p], l) != 0 || + ray_sym_domain_find(dom, words[p], l) != p) + return false; + } + ray_sym_domain_raw_unpin(dom); + return true; +} + +/* A reopen after this process flushed its own appends: the positions the + * flush wrote have atoms but no offset into the mapping (none at all when + * the domain was created empty), yet the prefix check must still compare + * them against the grown file — and the extend give them offsets. */ +static test_result_t test_domain_extend_after_flush(void) { + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + + /* (i) created empty, interned, flushed: nothing is mapped */ + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "fa", 2), 1); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "fb", 2), 2); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, false), RAY_OK); + const char* grown1[] = { "", "fa", "fb", "fc", "fd" }; + TEST_ASSERT(write_symfile(TMP_DOM_SYM_PATH, grown1, 5), "external growth"); + ray_sym_domain_t* again = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_EQ_PTR(again, dom); + TEST_ASSERT(dom_holds(dom, grown1, 5), "created-empty domain extended"); + ray_sym_domain_release(again); + ray_sym_domain_release(dom); + + /* (ii) opened from 3 records, 2 interned and flushed: offsets cover 3 */ + const char* base[] = { "", "ga", "gb" }; + TEST_ASSERT(write_symfile(TMP_DOM_SYM_PATH, base, 3), "base file"); + dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "gc", 2), 3); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, "gd", 2), 4); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, false), RAY_OK); + /* a file that disagrees with the flushed tail is refused, and leaves + * the domain as it was */ + const char* wrong[] = { "", "ga", "gb", "gc", "gX", "ge" }; + TEST_ASSERT(write_symfile(TMP_DOM_SYM_PATH, wrong, 6), "diverging file"); + TEST_ASSERT_NULL(ray_sym_domain_open(TMP_DOM_SYM_PATH)); + const char* grown2[] = { "", "ga", "gb", "gc", "gd", "ge", "gf" }; + TEST_ASSERT(write_symfile(TMP_DOM_SYM_PATH, grown2, 7), "external growth"); + again = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_EQ_PTR(again, dom); + TEST_ASSERT(dom_holds(dom, grown2, 7), "flushed tail extended"); + ray_sym_domain_release(again); + ray_sym_domain_release(dom); + + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + PASS(); +} + +/* A reopen that extends the domain while a batch intern probes outside + * the lock drops the reverse index the batch then commits against. The + * batch interns exactly what the external writer appends, so however the + * two interleave — extend first (all hits), during the probe (the misses + * found again in the current index), after the commit (appended in batch + * order; the reopen then refuses the dirty domain) — every string lands + * at the position the file gives it. */ +enum { XB_BASE = 64, XB_N = 50000, XB_ROUNDS = 10, XB_W = 24 }; +typedef struct { + ray_sym_domain_t* dom; + const char* const* strs; + const size_t* lens; + const uint32_t* hashes; + int64_t* out; + _Atomic(bool) started; + bool ok; +} xbatch_ctx_t; + +static void xbatch_run(void* arg) { + xbatch_ctx_t* c = (xbatch_ctx_t*)arg; + atomic_store(&c->started, true); + c->ok = ray_sym_domain_intern_batch(c->dom, XB_N, c->strs, c->lens, c->hashes, c->out); +} + +static test_result_t test_domain_extend_under_batch(void) { + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + enum { ALL = XB_BASE + XB_N }; + char* buf = (char*)ray_sys_alloc((size_t)ALL * XB_W); + const char** words = (const char**)ray_sys_alloc((size_t)ALL * sizeof(char*)); + size_t* lens = (size_t*)ray_sys_alloc((size_t)XB_N * sizeof(size_t)); + uint32_t* hashes = (uint32_t*)ray_sys_alloc((size_t)XB_N * sizeof(uint32_t)); + int64_t* out = (int64_t*)ray_sys_alloc((size_t)XB_N * sizeof(int64_t)); + TEST_ASSERT(buf && words && lens && hashes && out, "buffers"); + for (int r = 0; r < XB_ROUNDS; r++) { + words[0] = ""; + for (int i = 1; i < ALL; i++) { + snprintf(buf + (size_t)i * XB_W, XB_W, "xb%d_%d", r, i); + words[i] = buf + (size_t)i * XB_W; + } + for (int i = 0; i < XB_N; i++) { + lens[i] = strlen(words[XB_BASE + i]); + hashes[i] = (uint32_t)ray_hash_bytes(words[XB_BASE + i], lens[i]); + } + TEST_ASSERT(write_symfile(TMP_DOM_SYM_PATH, words, XB_BASE), "base file"); + TEST_ASSERT(write_symfile(TMP_DOM_SYM_PATH ".grown", words, ALL), "grown file"); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ray_sym_domain_find(dom, words[1], strlen(words[1])), 1); /* index built */ + + xbatch_ctx_t c = { dom, words + XB_BASE, lens, hashes, out, false, false }; + ray_thread_t th; + TEST_ASSERT_EQ_I(ray_thread_create(&th, xbatch_run, &c), RAY_OK); + while (!atomic_load(&c.started)) {} + int moved = rename(TMP_DOM_SYM_PATH ".grown", TMP_DOM_SYM_PATH); + ray_sym_domain_t* again = ray_sym_domain_open(TMP_DOM_SYM_PATH); + ray_thread_join(th); + + TEST_ASSERT_EQ_I(moved, 0); + TEST_ASSERT(c.ok, "batch interned"); + for (int i = 0; i < XB_N; i++) TEST_ASSERT_EQ_I(out[i], XB_BASE + i); + if (again) ray_sym_domain_release(again); /* NULL: the batch committed first */ + ray_sym_domain_release(dom); + } + ray_sys_free(buf); + ray_sys_free(words); + ray_sys_free(lens); + ray_sys_free(hashes); + ray_sys_free(out); unlink(TMP_DOM_SYM_PATH); unlink(TMP_DOM_SYM_PATH ".lk"); PASS(); } + /* Runtime-id LUT: NULL for the runtime singleton; for a FILE domain a * position-indexed array of runtime intern ids (round-trips strings), * built once (idempotent: same pointer). Divergent fixture proves the @@ -1981,8 +2309,8 @@ static test_result_t test_domain_runtime_lut(void) { TEST_ASSERT_EQ_I(lut[0], 0); /* "" reserves position 0 AND global id 0 */ ray_sym_domain_release(dom); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -2022,50 +2350,33 @@ static test_result_t test_domain_concat_text_nulls(void) { ray_release(slice); ray_release(file); ray_release(runtime); } ray_sym_domain_release(dom); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } #define TMP_DOM_BADSYM_PATH "/tmp/rayforce_test_domain_badsym" -/* Position-0 reservation: ray_sym_save-produced files carry "" at - * position 0 (global id 0) and open fine; a crafted symfile whose first - * entry is NOT "" is refused (NULL); an EMPTY vocabulary is fine. */ +/* Position 0: ray_sym_save-produced files carry "" at position 0 (global + * id 0) and open fine; an EMPTY vocabulary is fine. */ static test_result_t test_domain_open_position0_validation(void) { - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); - unlink(TMP_DOM_BADSYM_PATH); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); + unlink(ray_test_tmp(TMP_DOM_BADSYM_PATH)); /* (a) the save path today: "" at position 0 — opens. */ (void)ray_sym_intern("p0_ok", 5); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); - ray_sym_domain_t* good = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_DOM_SYM_PATH)), RAY_OK); + ray_sym_domain_t* good = ray_sym_domain_open(ray_test_tmp(TMP_DOM_SYM_PATH)); TEST_ASSERT_NOT_NULL(good); ray_t* s0 = ray_sym_domain_str(good, 0); TEST_ASSERT_NOT_NULL(s0); TEST_ASSERT_EQ_U(ray_str_len(s0), 0); ray_sym_domain_release(good); - /* (b) crafted STRL whose position 0 is "x": refused. */ - { - FILE* f = fopen(TMP_DOM_BADSYM_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - uint32_t magic = 0x4C525453U; /* "STRL" */ - int64_t count = 2; - uint32_t len_x = 1, len_e = 0; - fwrite(&magic, 4, 1, f); - fwrite(&count, 8, 1, f); - fwrite(&len_x, 4, 1, f); - fwrite("x", 1, 1, f); - fwrite(&len_e, 4, 1, f); - fclose(f); - } - TEST_ASSERT_NULL(ray_sym_domain_open(TMP_DOM_BADSYM_PATH)); - /* (c) empty vocabulary (count 0): structurally fine. */ { - FILE* f = fopen(TMP_DOM_BADSYM_PATH, "wb"); + FILE* f = fopen(ray_test_tmp(TMP_DOM_BADSYM_PATH), "wb"); TEST_ASSERT_NOT_NULL(f); uint32_t magic = 0x4C525453U; int64_t count = 0; @@ -2073,7 +2384,7 @@ static test_result_t test_domain_open_position0_validation(void) { fwrite(&count, 8, 1, f); fclose(f); } - ray_sym_domain_t* empty = ray_sym_domain_open(TMP_DOM_BADSYM_PATH); + ray_sym_domain_t* empty = ray_sym_domain_open(ray_test_tmp(TMP_DOM_BADSYM_PATH)); TEST_ASSERT_NOT_NULL(empty); TEST_ASSERT_EQ_I(ray_sym_domain_count(empty), 0); TEST_ASSERT_NULL(ray_sym_domain_str(empty, 0)); @@ -2082,9 +2393,9 @@ static test_result_t test_domain_open_position0_validation(void) { TEST_ASSERT_NOT_NULL(ray_sym_domain_runtime_lut(empty)); ray_sym_domain_release(empty); - unlink(TMP_DOM_BADSYM_PATH); - unlink(TMP_DOM_SYM_PATH); - unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_BADSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_SYM_PATH ".lk")); PASS(); } @@ -2169,12 +2480,12 @@ static test_result_t test_domain_dict_upsert_file_keys(void) { /* ref balance: the dict's converted keys dropped the FILE-domain ref * (fresh open rebuilds the cache entry). */ - ray_sym_domain_t* d2 = ray_sym_domain_open(TMP_DOM_QSYM_PATH); + ray_sym_domain_t* d2 = ray_sym_domain_open(ray_test_tmp(TMP_DOM_QSYM_PATH)); TEST_ASSERT_NOT_NULL(d2); ray_sym_domain_release(d2); - unlink(TMP_DOM_QSYM_PATH); - unlink(TMP_DOM_QSYM_PATH ".lk"); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH)); + unlink(ray_test_tmp(TMP_DOM_QSYM_PATH ".lk")); PASS(); } @@ -2706,7 +3017,853 @@ static test_result_t test_domain_sk4_reserve_kept_freed(void) { TEST_ASSERT_EQ_I(leaks, 0); PASS(); } +/* ---- the symfile's record index (.ix) --------------------------- */ + +#define TMP_IX_PATH TMP_DOM_SYM_PATH ".ix" +#define IX_MAXN 4096 + +/* A test vocabulary: "" at 0, then strings of varying length, so the + * checkpoints fall at irregular offsets; entries may be replaced. */ +typedef struct { + int64_t n; + char s[IX_MAXN][48]; + uint8_t l[IX_MAXN]; +} ix_vocab_t; +static ix_vocab_t ix_va, ix_vb; + +static void ix_gen(ix_vocab_t* v, const char* tag, int64_t n) { + v->n = n; + for (int64_t i = 0; i < n; i++) { + int l = i == 0 ? 0 : snprintf(v->s[i], sizeof v->s[i], "%s_%lld_%.*s", tag, + (long long)i, (int)(i % 11), "xxxxxxxxxxx"); + if (i == 0) v->s[i][0] = 0; + v->l[i] = (uint8_t)l; + } +} +static void ix_set(ix_vocab_t* v, int64_t i, const char* s) { + size_t l = strlen(s); + memcpy(v->s[i], s, l + 1); + v->l[i] = (uint8_t)l; +} + +/* The symfile bytes of a vocabulary (the format every writer leaves) and + * the offset of each record. */ +static size_t ix_strl(const ix_vocab_t* v, int64_t n, uint8_t* out, uint64_t* offs) { + uint32_t magic = 0x4C525453U; + memcpy(out, &magic, 4); + memcpy(out + 4, &n, 8); + size_t o = 12; + for (int64_t i = 0; i < n; i++) { + if (offs) offs[i] = o; + uint32_t l = v->l[i]; + memcpy(out + o, &l, 4); + memcpy(out + o + 4, v->s[i], l); + o += 4 + l; + } + return o; +} + +static bool ix_write(const char* path, const uint8_t* buf, size_t n) { + FILE* f = fopen(path, "wb"); + if (!f) return false; + bool ok = fwrite(buf, 1, n, f) == n; + return fclose(f) == 0 && ok; +} +static long ix_read(const char* path, uint8_t* buf, size_t cap) { + FILE* f = fopen(path, "rb"); + if (!f) return -1; + size_t n = fread(buf, 1, cap, f); + fclose(f); + return (long)n; +} +static bool ix_exists(const char* path) { struct stat st; return stat(path, &st) == 0; } + +static uint8_t ix_sym[1 << 18], ix_sym2[1 << 18], ix_buf[1 << 16], ix_buf2[1 << 16]; +static uint64_t ix_offs[IX_MAXN]; + +static bool ix_write_vocab(const char* path, const ix_vocab_t* v, int64_t n) { + size_t sz = ix_strl(v, n, ix_sym, ix_offs); + return ix_write(path, ix_sym, sz); +} + +/* An index (the format of domain.c: a 128-byte header, the blocks in + * `cap` 64-byte blocks of an offset and 28 u16 lengths) of `count` entries of the image + * `img` (record offsets `offs`) whose records end at `end`; claimed for the + * file at `path` as it is now (its inode, modification and status-change + * times), or for none (NULL). Returns its size. */ +#define IXH 128 +#define IXS 28 /* entries in a block of 64 bytes */ +static uint8_t ix_sym3[4 << 20]; /* a symfile of long strings */ +static inline int64_t ix_nblk(int64_t count) { return (count + IXS - 1) / IXS; } +static inline int64_t ix_cap(int64_t count) { int64_t n = ix_nblk(count); return n + n / 4 + 64; } + +static inline size_t ix_bytes(int64_t count) { return IXH + 64 * (size_t)ix_cap(count); } +/* A file's modification and status-change times in nanoseconds. */ +static int64_t ix_mtime_ns(const struct stat* st) { +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) + /* Darwin's POSIX namespace exposes seconds/nanoseconds separately. */ + return (int64_t)st->st_mtime * 1000000000 + st->st_mtimensec; +#elif defined(__APPLE__) + return (int64_t)st->st_mtimespec.tv_sec * 1000000000 + st->st_mtimespec.tv_nsec; +#else + return (int64_t)st->st_mtim.tv_sec * 1000000000 + st->st_mtim.tv_nsec; +#endif +} +static int64_t ix_ctime_ns(const struct stat* st) { +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) + return (int64_t)st->st_ctime * 1000000000 + st->st_ctimensec; +#elif defined(__APPLE__) + return (int64_t)st->st_ctimespec.tv_sec * 1000000000 + st->st_ctimespec.tv_nsec; +#else + return (int64_t)st->st_ctim.tv_sec * 1000000000 + st->st_ctim.tv_nsec; +#endif +} +/* Claim an index for a file's current identity, as one written for that + * very file is. */ +static void ix_stamp(uint8_t* ix, const char* path) { + struct stat st; + uint64_t ino = 0, stamp = 0; + if (path && stat(path, &st) == 0) { + ino = (uint64_t)st.st_ino; + int64_t mt = ix_mtime_ns(&st); + int64_t ct = ix_ctime_ns(&st); + stamp = (uint64_t)mt ^ ((uint64_t)ct * UINT64_C(0x9E3779B97F4A7C15)); + } + memcpy(ix + 32, &ino, 8); + memcpy(ix + 40, &stamp, 8); +} +static size_t ix_make(uint8_t* out, const uint8_t* img, const uint64_t* offs, int64_t count, + uint64_t end, const char* path) { + int64_t n = ix_nblk(count), cap = ix_cap(count); + size_t bytes = ix_bytes(count); + memset(out, 0, bytes); + uint32_t w = 0x58525453U; memcpy(out, &w, 4); + w = 5; memcpy(out + 4, &w, 4); + w = IXS; memcpy(out + 8, &w, 4); + memcpy(out + 16, &count, 8); + memcpy(out + 24, &end, 8); + uint64_t last = offs[IXS * (n - 1)]; + memcpy(out + 48, &last, 8); + (void)img; + uint64_t c64 = (uint64_t)cap; memcpy(out + 72, &c64, 8); + for (int64_t k = 0; k < n; k++) memcpy(out + IXH + 64 * (size_t)k, &offs[IXS * k], 8); + for (int64_t i = 0; i < count; i++) { + uint64_t l = (i + 1 < count ? offs[i + 1] : end) - offs[i] - 4; + uint16_t l16 = l < 65535 ? (uint16_t)l : 65535; + memcpy(out + IXH + 64 * (size_t)(i / IXS) + 8 + 2 * (size_t)(i % IXS), &l16, 2); + } + ix_stamp(out, path); + return bytes; +} +/* The checkpoint of block k, and the length byte of entry i, in an index of + * `count` entries. */ +static uint16_t* ix_len_at(uint8_t* ix, int64_t count, int64_t i) { + (void)count; + return (uint16_t*)(ix + IXH + 64 * (size_t)(i / IXS) + 8 + 2 * (size_t)(i % IXS)); +} + +/* Wait until the file system's clock is past `path`'s change time: a file + * written now gets a later one. Some kernels move timestamps only by the + * scheduler tick, and a rewrite in the same tick keeps them (domain.h). */ +static void ix_wait_fs_tick(const char* path) { + struct stat st, pr; + if (stat(path, &st) != 0) return; + const char* probe = TMP_DOM_SYM_PATH ".tick"; + for (int i = 0; i < 5000; i++) { + FILE* f = fopen(probe, "wb"); + if (f) { fputc('t', f); fclose(f); } + if (stat(probe, &pr) == 0 && + ix_ctime_ns(&pr) > ix_ctime_ns(&st)) + break; + struct timespec ts = { 0, 1000 * 1000 }; + nanosleep(&ts, NULL); + } + unlink(probe); +} + +/* Every entry of `dom` is the vocabulary's: first through the raw snapshot + * (the mapped prefix; lock-free, so it checks blocks itself), then the + * atoms, then the reverse index (a pass over the whole vocabulary). */ +static bool ix_check_all(ray_sym_domain_t* dom, const ix_vocab_t* v, int64_t n) { + if (ray_sym_domain_count(dom) != n) return false; + ray_sym_domain_raw_t raw; + if (!ray_sym_domain_raw_pin(dom, &raw) || raw.count > n) return false; + for (int64_t i = 0; i < raw.count; i++) { + size_t l = v->l[i], rl = 0; + const char* rp = ray_sym_domain_raw_str(&raw, i, &rl); + if (!rp || rl != l || (l && memcmp(rp, v->s[i], l) != 0)) return false; + } + for (int64_t i = 0; i < n; i++) { + size_t l = v->l[i]; + ray_t* s = ray_sym_domain_str(dom, i); + if (!s || ray_str_len(s) != l || (l && memcmp(ray_str_ptr(s), v->s[i], l) != 0)) + return false; + } + for (int64_t i = 1; i < n; i += 97) + if (ray_sym_domain_find(dom, v->s[i], v->l[i]) != i) return false; + return true; +} + +static ray_sym_domain_ix_info_t ix_info(ray_sym_domain_t* dom) { + ray_sym_domain_ix_info_t in; + memset(&in, 0, sizeof in); + (void)ray_sym_domain_ix_info(dom, &in); + return in; +} + +static void ix_unlink_all(void) { + unlink(TMP_DOM_SYM_PATH); + unlink(TMP_DOM_SYM_PATH ".lk"); + unlink(TMP_IX_PATH); +} + +/* Open, check every entry, report what the index did, release. */ +static bool ix_open_check(const ix_vocab_t* v, int64_t n, ray_sym_domain_ix_info_t* out) { + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + if (!dom) return false; + bool ok = ix_check_all(dom, v, n); + *out = ix_info(dom); + ray_sym_domain_release(dom); + return ok; +} + +/* The length of every entry, through the raw snapshot and the domain. */ +static bool ix_check_lens(ray_sym_domain_t* dom, const ix_vocab_t* v, int64_t n) { + ray_sym_domain_raw_t raw; + if (!ray_sym_domain_raw_pin(dom, &raw)) return false; + for (int64_t i = 0; i < n; i++) { + if (i < raw.count && ray_sym_domain_raw_len(&raw, i) != v->l[i]) return false; + if (ray_sym_domain_strlen(dom, i) != v->l[i]) return false; + } + return true; +} + +/* An old symfile (no index) opens with one walk and leaves an index; the + * next open takes the table from it — the lengths mapped from it — and + * does not rewrite it. */ +static test_result_t test_domain_index_build_and_use(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 1000 }; + ix_gen(&ix_va, "ix", N); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "write symfile"); + ray_sym_domain_ix_info_t in; + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "old symfile resolves"); + TEST_ASSERT_FALSE(in.from_index); + long n1 = ix_read(TMP_IX_PATH, ix_buf, sizeof ix_buf); + TEST_ASSERT_EQ_I(n1, (long)ix_bytes(N)); + /* what the writer wrote is what the format says, for this very file */ + size_t ib = ix_make(ix_buf2, ix_sym, ix_offs, N, ix_strl(&ix_va, N, ix_sym, ix_offs), + TMP_DOM_SYM_PATH); + TEST_ASSERT_EQ_U(ib, (size_t)n1); + TEST_ASSERT_MEM_EQ(ib, ix_buf, ix_buf2); + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "indexed open resolves"); + TEST_ASSERT_TRUE(in.from_index); + TEST_ASSERT_TRUE(in.lens_mapped); + TEST_ASSERT_EQ_I(in.covered, N); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT(ix_check_lens(dom, &ix_va, N), "lengths from the index"); + ray_sym_domain_release(dom); + TEST_ASSERT_EQ_I(ix_read(TMP_IX_PATH, ix_buf2, sizeof ix_buf2), n1); + TEST_ASSERT_MEM_EQ((size_t)n1, ix_buf2, ix_buf); /* used, not rewritten */ + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* Strings of 255 bytes and longer, before the entries read in their block: + * their length is in the index (two bytes) and no record is read for it, and + * those of 65535 bytes and longer (the escape) take it from the record; every + * entry and every length is the file's. */ +static test_result_t test_domain_index_long_strings(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 200 }; + static const int64_t lens[] = { 254, 255, 256, 300, 1000, 4095, 65534, 65535, 70000 }; + /* the records by hand: the vocabulary type holds short strings only */ + uint64_t offs[N]; + int64_t want[N]; + size_t o = 12; + for (int64_t i = 0; i < N; i++) { + int64_t l = i == 0 ? 0 : (i % IXS >= 3 && i % IXS < 10) ? lens[(i / IXS + i) % 9] : i % 23; + want[i] = l; + offs[i] = o; + uint32_t l32 = (uint32_t)l; + memcpy(ix_sym3 + o, &l32, 4); + for (int64_t c = 0; c < l; c++) ix_sym3[o + 4 + c] = (uint8_t)('a' + (i + c) % 26); + o += 4 + (size_t)l; + } + uint32_t magic = 0x4C525453U; + int64_t cnt = N; + memcpy(ix_sym3, &magic, 4); + memcpy(ix_sym3 + 4, &cnt, 8); + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH, ix_sym3, o), "symfile"); + for (int pass = 0; pass < 2; pass++) { /* walked, then from the index */ + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_EQ_I(ix_info(dom).from_index, pass == 1); + ray_sym_domain_raw_t raw; + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &raw), "pin"); + for (int64_t i = N - 1; i >= 0; i--) { /* the later entries of a block first */ + size_t rl = 0; + const char* rp = ray_sym_domain_raw_str(&raw, i, &rl); + if (!rp || (int64_t)rl != want[i] || memcmp(rp, ix_sym3 + offs[i] + 4, rl) != 0) + FAILF("pass %d entry %lld", pass, (long long)i); + if (ray_sym_domain_raw_len(&raw, i) != want[i] || ray_sym_domain_strlen(dom, i) != want[i]) + FAILF("pass %d length of %lld", pass, (long long)i); + } + ray_sym_domain_release(dom); + } + long nb = ix_read(TMP_IX_PATH, ix_buf, sizeof ix_buf); + TEST_ASSERT_EQ_I(nb, (long)ix_bytes(N)); + for (int64_t i = 0; i < N; i++) + if (*ix_len_at(ix_buf, N, i) != (want[i] < 65535 ? want[i] : 65535)) FAILF("length %lld", (long long)i); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* The index is taken for the very file it was written for only: the same + * bytes written again (a new modification and status-change time), a chmod + * (the status-change time alone), another vocabulary of the same shape — + * each opens by one walk, every entry the file's, and the index is written + * again for it, so the open after takes it. */ +static test_result_t test_domain_index_identity(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 900 }; + ix_gen(&ix_va, "id", N); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "write symfile"); + ray_sym_domain_ix_info_t in; + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "first open"); + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "indexed open"); + TEST_ASSERT_TRUE(in.from_index); + ix_vb = ix_va; + for (int64_t i = 400; i < 420; i++) ix_vb.s[i][0] = 'J'; + for (int v = 0; v < 3; v++) { + ix_wait_fs_tick(TMP_IX_PATH); + const ix_vocab_t* now = v == 2 ? &ix_vb : &ix_va; + if (v == 0) TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "the same bytes again"); + if (v == 1) TEST_ASSERT_EQ_I(chmod(TMP_DOM_SYM_PATH, 0640), 0); + if (v == 2) TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_vb, N), "same-shape vocabulary"); + if (!ix_open_check(now, N, &in)) FAILF("case %d: does not resolve", v); + if (in.from_index) FAILF("case %d: the index was taken", v); + if (!ix_open_check(now, N, &in) || !in.from_index) FAILF("case %d: not rewritten", v); + } + TEST_ASSERT_EQ_I(chmod(TMP_DOM_SYM_PATH, 0644), 0); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* An index that fails a check made at open is not used: the records are + * walked and the index written again for the file. One per check. */ +static test_result_t test_domain_index_rejects_bad(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 777, CASES = 13 }; + ix_gen(&ix_va, "rj", N); + size_t sz = ix_strl(&ix_va, N, ix_sym, ix_offs); + static uint8_t good[1 << 14]; + for (int v = 0; v < CASES; v++) { + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH, ix_sym, sz), "write symfile"); + size_t gb = ix_make(good, ix_sym, ix_offs, N, sz, TMP_DOM_SYM_PATH); + size_t len = gb; + memcpy(ix_buf, good, gb); + uint64_t u; + int64_t c; + switch (v) { + case 0: case 2: case 3: case 4: continue; /* (no checksums) */ + case 1: ix_buf[4] = 3; break; /* earlier format */ + case 5: len = gb - 5; break; /* lengths cut short */ + case 6: c = N - 1; memcpy(ix_buf + 16, &c, 8); break; /* count */ + case 7: u = sz - 1; memcpy(ix_buf + 24, &u, 8); break; /* end */ + case 8: ix_buf[32] ^= 1; break; /* inode */ + case 9: ix_buf[40] ^= 1; break; /* times */ + case 10: memset(ix_buf + 32, 0, 16); break; /* claimed for none */ + case 11: u = 3; memcpy(ix_buf + 72, &u, 8); break; /* fewer slots than blocks */ + case 12: len = 40; break; /* the header cut short */ + } + TEST_ASSERT(ix_write(TMP_IX_PATH, ix_buf, len), "write bad index"); + ray_sym_domain_ix_info_t in; + if (!ix_open_check(&ix_va, N, &in)) FAILF("case %d: does not resolve", v); + if (in.from_index) FAILF("case %d: the index was used", v); + if (ix_read(TMP_IX_PATH, ix_buf2, sizeof ix_buf2) != (long)gb || + memcmp(ix_buf2, good, gb) != 0) + FAILF("case %d: not written again", v); + } + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* A symfile of IXL_N records in `img` — a quarter of them 254 to 70000 bytes + * (those of 65535 and longer the escape), one a multi-byte UTF-8 string — + * with their lengths in `want` and offsets in `offs`; returns its size. */ +enum { IXL_N = 200 }; +static size_t ix_long_image(uint8_t* img, uint64_t* offs, int64_t* want) { + static const int64_t lens[] = { 254, 255, 256, 300, 1000, 4095, 65534, 65535, 70000 }; + size_t o = 12; + for (int64_t i = 0; i < IXL_N; i++) { + int64_t l = i == 0 ? 0 : (i % 8 >= 2 && i % 8 < 4) ? lens[(i / 8) % 9] : i % 23; + want[i] = l; + offs[i] = o; + uint32_t l32 = (uint32_t)l; + memcpy(img + o, &l32, 4); + for (int64_t c = 0; c < l; c++) + img[o + 4 + c] = (uint8_t)(i == 77 ? (c & 1 ? 0xA9 : 0xC3) : 'a' + (i + c) % 26); + o += 4 + (size_t)l; + } + uint32_t magic = 0x4C525453U; + int64_t cnt = IXL_N; + memcpy(img, &magic, 4); + memcpy(img + 4, &cnt, 8); + return o; +} + +/* The length of every id through the domain (any order), against `want`; + * with `only_right`, an id may also be refused (-1) but never wrong. */ +static bool ix_long_lens_ok(ray_sym_domain_t* dom, const int64_t* want, bool only_right) { + for (int64_t j = 0; j < IXL_N; j++) { + int64_t i = (j * 37) % IXL_N, l = ray_sym_domain_strlen(dom, i); + if (l != want[i] && !(only_right && l == -1)) return false; + } + return true; +} + +/* On a domain just opened, every record's header overwritten with 0xFF — + * except the empty first record, and the escape entries' (65535 bytes and + * longer: their header is their length) — and every string's bytes: each + * length, of the short entries and of those of 255 to 65534 bytes alike, + * comes out exact, in any order, from the index alone, and no read is + * counted corrupt. Reading the string of such an entry finds the record + * gone and counts. */ +static test_result_t test_domain_index_cold_long_no_headers(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + int64_t want[IXL_N]; + size_t sz = ix_long_image(ix_sym3, ix_offs, want); + int64_t nlong = 0, nesc = 0; + for (int64_t i = 1; i < IXL_N; i++) { + nlong += want[i] >= 255 && want[i] < 65535; + nesc += want[i] >= 65535; + if (want[i] >= 65535) memset(ix_sym3 + ix_offs[i] + 4, 0xFF, (size_t)want[i]); /* the escape keeps its header */ + else memset(ix_sym3 + ix_offs[i], 0xFF, 4 + (size_t)want[i]); + } + TEST_ASSERT(nlong > 15 && nesc > 3, "long and escape entries"); + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH, ix_sym3, sz), "write symfile"); + size_t ib = ix_make(ix_buf, ix_sym3, ix_offs, IXL_N, sz, TMP_DOM_SYM_PATH); + TEST_ASSERT(ix_write(TMP_IX_PATH, ix_buf, ib), "write index"); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_TRUE(ix_info(dom).from_index); + TEST_ASSERT(ix_long_lens_ok(dom, want, false), "exact lengths"); + ray_sym_domain_release(dom); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* A length is read from the index and the record is left alone: with the + * record header of one entry overwritten (the index byte intact), its + * length still comes out of the index, no read is counted corrupt, and no + * other entry is affected; reading the same entry's string finds the record + * does not say what the index does — it is not answered and counts. The + * bytes of another entry's string overwritten in place change what its + * string reads as and nothing about its length. */ +static test_result_t test_domain_index_len_skips_record(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 3000 }; + ix_gen(&ix_va, "ls", N); + size_t sz = ix_strl(&ix_va, N, ix_sym, ix_offs); + const int64_t hd = 1500, by = 2200; + TEST_ASSERT(ix_va.l[by] > 0, "entry with bytes"); + memcpy(ix_sym2, ix_sym, sz); + uint32_t bad = 4000; + memcpy(ix_sym2 + ix_offs[hd], &bad, 4); /* its header only */ + memset(ix_sym2 + ix_offs[by] + 4, '#', (size_t)ix_va.l[by]); /* its bytes only */ + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH, ix_sym2, sz), "write symfile"); + size_t ib = ix_make(ix_buf, ix_sym, ix_offs, N, sz, TMP_DOM_SYM_PATH); + TEST_ASSERT(ix_write(TMP_IX_PATH, ix_buf, ib), "write index"); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_TRUE(ix_info(dom).from_index); + ray_sym_domain_raw_t raw; + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &raw), "pin"); + TEST_ASSERT_EQ_I(ray_sym_domain_raw_len(&raw, hd), ix_va.l[hd]); + TEST_ASSERT_EQ_I(ray_sym_domain_raw_len(&raw, by), ix_va.l[by]); + TEST_ASSERT_EQ_I(ray_sym_domain_strlen(dom, hd), ix_va.l[hd]); + size_t rl = 0; + const char* rp = ray_sym_domain_raw_str(&raw, by, &rl); + TEST_ASSERT_NOT_NULL(rp); + TEST_ASSERT_EQ_U(rl, (size_t)ix_va.l[by]); + for (size_t c = 0; c < rl; c++) TEST_ASSERT(rp[c] == '#', "bytes are the file's"); + ray_sym_domain_release(dom); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* On a domain just opened (no earlier read), the string bytes of every record + * overwritten, and the headers of the odd short ones (the index intact): the + * length of every id comes + * out right, in any order, and no read is counted corrupt — the lengths + * come from the index and its blocks' own check, which reads no string + * bytes. The strings read at the same ids are the overwritten ones. */ +static test_result_t test_domain_index_cold_len_no_bytes(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 3000 }; + ix_gen(&ix_va, "cl", N); + size_t sz = ix_strl(&ix_va, N, ix_sym, ix_offs); + memcpy(ix_sym2, ix_sym, sz); + for (int64_t i = 0; i < N; i++) + { + memset(ix_sym2 + ix_offs[i] + 4, '#', (size_t)ix_va.l[i]); + if (i % 2) memset(ix_sym2 + ix_offs[i], 0xFF, 4); /* odd short records: header too */ + } + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH, ix_sym2, sz), "write symfile"); + size_t ib = ix_make(ix_buf, ix_sym2, ix_offs, N, sz, TMP_DOM_SYM_PATH); + TEST_ASSERT(ix_write(TMP_IX_PATH, ix_buf, ib), "write index"); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_TRUE(ix_info(dom).from_index); + for (int64_t j = 0; j < N; j++) { + int64_t i = (j * 1237) % N; + if (ray_sym_domain_strlen(dom, i) != ix_va.l[i]) FAILF("length of %lld", (long long)i); + } + ray_sym_domain_raw_t raw; + TEST_ASSERT(ray_sym_domain_raw_pin(dom, &raw), "pin"); + size_t rl = 0; + const char* rp = ray_sym_domain_raw_str(&raw, 1000, &rl); + TEST_ASSERT_NOT_NULL(rp); + TEST_ASSERT_EQ_U(rl, (size_t)ix_va.l[1000]); + for (size_t c = 0; c < rl; c++) TEST_ASSERT(rp[c] == '#', "string read is the file's bytes"); + ray_sym_domain_release(dom); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* Records appended by a writer that left the index as it was (an older + * binary, another tool): the file is not the one the index was written for + * (its size and times moved), so the open walks it and writes the index + * again; the open after takes it whole. */ +static test_result_t test_domain_index_append_unindexed(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 500, M = 300 }; + ix_gen(&ix_va, "au", N + M); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "write symfile"); + ray_sym_domain_ix_info_t in; + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "writes the index"); + ix_wait_fs_tick(TMP_IX_PATH); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N + M), "appended behind the index"); + TEST_ASSERT(ix_open_check(&ix_va, N + M, &in), "walked"); + TEST_ASSERT_FALSE(in.from_index); + TEST_ASSERT(ix_open_check(&ix_va, N + M, &in), "the new index taken"); + TEST_ASSERT_TRUE(in.from_index); + TEST_ASSERT_EQ_I(in.covered, N + M); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* A truncated symbol file (a partial copy) does not open, whether its + * index is there or not: the index is not this file's (the size moved), + * and the walk of its records does not end at its end. A cut through the + * last record, through a middle one and inside the header. */ +static test_result_t test_domain_index_truncated_fails(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 500 }; + ix_gen(&ix_va, "tf", N); + size_t full = ix_strl(&ix_va, N, ix_sym, ix_offs); + const long cuts[] = { (long)full - 1, (long)ix_offs[N / 2] + 2, 8 }; + for (size_t k = 0; k < sizeof cuts / sizeof cuts[0]; k++) { + for (int with_ix = 0; with_ix < 2; with_ix++) { + ix_unlink_all(); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "write symfile"); + ray_sym_domain_ix_info_t in; + if (with_ix) TEST_ASSERT(ix_open_check(&ix_va, N, &in), "writes the index"); + TEST_ASSERT_EQ_I(truncate(TMP_DOM_SYM_PATH, cuts[k]), 0); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + if (dom) { + ray_sym_domain_release(dom); + FAILF("cut at %ld of %zu (index %d): opened", cuts[k], full, with_ix); + } + } + } + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* The writers' indexes describe the files they wrote: a full flush, appends + * (some durable) and the import dictionary's final sync each leave an index + * the next open takes whole — its lengths those of the strings — with no + * block failing its check. */ +static test_result_t test_domain_index_writers(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 700, M = 333 }; + ix_gen(&ix_va, "wr", N + M); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + for (int64_t i = 1; i < N; i++) + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, ix_va.s[i], ix_va.l[i]), i); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, true), RAY_OK); + ray_sym_domain_release(dom); + ray_sym_domain_ix_info_t in; + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "after a full flush"); + TEST_ASSERT_TRUE(in.from_index); + TEST_ASSERT_EQ_I(in.covered, N); + + dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + for (int64_t i = N; i < N + M; i++) { + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, ix_va.s[i], ix_va.l[i]), i); + if (i % 50 == 0) TEST_ASSERT_EQ_I(ray_sym_domain_flush_append(dom, false), RAY_OK); + } + TEST_ASSERT_EQ_I(ray_sym_domain_flush_append(dom, true), RAY_OK); + ray_sym_domain_release(dom); + TEST_ASSERT(ix_open_check(&ix_va, N + M, &in), "after appends"); + TEST_ASSERT_TRUE(in.from_index); + TEST_ASSERT_EQ_I(in.covered, N + M); + dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT(ix_check_lens(dom, &ix_va, N + M), "the lengths the appends wrote"); + ray_sym_domain_release(dom); + ix_unlink_all(); + + const char* p = TMP_DOM_SYM_PATH "_ixi"; + char pix[256]; + snprintf(pix, sizeof pix, "%s.ix", p); + unlink(p); + unlink(pix); + dom = ray_sym_domain_create_import(p); + if (dom) { + for (int64_t i = 1; i < N; i++) + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, ix_va.s[i], ix_va.l[i]), i); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(dom, true), RAY_OK); + ray_sym_domain_release(dom); + /* the import's index as it left it (an open that does not take it + * writes its own) */ + memset(ix_buf, 0, sizeof ix_buf); + FILE* fx = fopen(pix, "rb"); + size_t got = fx ? fread(ix_buf, 1, sizeof ix_buf, fx) : 0; + if (fx) fclose(fx); + ray_sym_domain_t* re = ray_sym_domain_open(p); + TEST_ASSERT_NOT_NULL(re); + TEST_ASSERT(ix_check_all(re, &ix_va, N), "after the import's sync"); + TEST_ASSERT(ix_check_lens(re, &ix_va, N), "the import's lengths"); + in = ix_info(re); + if (!in.from_index) { + /* its claim against the file, each check of the open */ + const uint8_t* h = ix_buf; + int64_t cnt = 0; + uint64_t end = 0, ino = 0, stamp = 0, cap = 0; + memcpy(&cnt, h + 16, 8); memcpy(&end, h + 24, 8); + memcpy(&ino, h + 32, 8); memcpy(&stamp, h + 40, 8); + memcpy(&cap, h + 72, 8); + struct stat st; + memset(&st, 0, sizeof st); + (void)stat(p, &st); + uint64_t now = (uint64_t)ix_mtime_ns(&st) ^ + ((uint64_t)ix_ctime_ns(&st) * UINT64_C(0x9E3779B97F4A7C15)); + ray_sym_domain_release(re); + FAILF("the import's index is not taken: index (%zu B, needs %llu) count %lld " + "end %llu ino %llu stamp %llx; file size %lld ino %llu stamp %llx; covered %lld", + got, (unsigned long long)(IXH + 8 * cap + (uint64_t)cnt), (long long)cnt, (unsigned long long)end, (unsigned long long)ino, + (unsigned long long)stamp, (long long)st.st_size, (unsigned long long)st.st_ino, + (unsigned long long)now, (long long)in.covered); + } + TEST_ASSERT_EQ_I(in.covered, N); + ray_sym_domain_release(re); + } + unlink(p); + unlink(pix); + char plk[256]; + snprintf(plk, sizeof plk, "%s.lk", p); + unlink(plk); + unsetenv("RAY_SYM_INDEX_MIN"); + PASS(); +} + +/* Every flush brings the index up to the file, in place while its slots + * last: the new blocks' checkpoints and the new entries' lengths are + * written into it (the index keeps its inode), so the next open walks + * nothing; past its slots it is written whole, with room again. */ +static test_result_t test_domain_index_refresh_in_place(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 1000, M = 100, L = 2990 }; /* 36 blocks, 109 slots; then 146 blocks */ + ix_gen(&ix_va, "rp", N + M + L); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "write symfile"); + ray_sym_domain_ix_info_t in; + TEST_ASSERT(ix_open_check(&ix_va, N, &in), "first open writes the index"); + struct stat s0, s1; + TEST_ASSERT_EQ_I(stat(TMP_IX_PATH, &s0), 0); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + for (int64_t i = N; i < N + M; i++) + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, ix_va.s[i], ix_va.l[i]), i); + TEST_ASSERT_EQ_I(ray_sym_domain_flush_append(dom, false), RAY_OK); + TEST_ASSERT_EQ_I(stat(TMP_IX_PATH, &s1), 0); + TEST_ASSERT_EQ_U(s1.st_ino, s0.st_ino); /* written into, not rewritten */ + TEST_ASSERT_EQ_I(s1.st_size, (long)ix_bytes(N)); + for (int64_t i = N + M; i < N + M + L; i++) + TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom, ix_va.s[i], ix_va.l[i]), i); + TEST_ASSERT_EQ_I(ray_sym_domain_flush_append(dom, false), RAY_OK); + ray_sym_domain_release(dom); + TEST_ASSERT_EQ_I(stat(TMP_IX_PATH, &s1), 0); + TEST_ASSERT_EQ_I(s1.st_size, (long)ix_bytes(N + M + L)); /* past its slots: whole */ + TEST_ASSERT(ix_open_check(&ix_va, N + M + L, &in), "after the appends"); + TEST_ASSERT_TRUE(in.from_index); + TEST_ASSERT_EQ_I(in.covered, N + M + L); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* Every writer that makes a new file under a name first removes the index + * a file of that name left; and an index write sweeps the temporary files + * of writers that no longer run. */ +static test_result_t test_domain_index_new_file_removes(void) { + ix_unlink_all(); + setenv("RAY_SYM_INDEX_MIN", "0", 1); + ix_gen(&ix_va, "nf", 64); + size_t sz = ix_strl(&ix_va, 64, ix_sym, ix_offs); + size_t ib = ix_make(ix_buf, ix_sym, ix_offs, 64, sz, NULL); + for (int w = 0; w < 4; w++) { + ix_unlink_all(); + TEST_ASSERT(ix_write(TMP_IX_PATH, ix_buf, ib), "an index left behind"); + if (w <= 1) { + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT(ray_sym_domain_intern(dom, "only", 4) > 0, "intern"); + TEST_ASSERT_EQ_I(w == 0 ? ray_sym_domain_flush(dom, false) + : ray_sym_domain_flush_append(dom, false), RAY_OK); + ray_sym_domain_release(dom); + } else if (w == 2) { + ray_sym_domain_t* dom = ray_sym_domain_create_import(TMP_DOM_SYM_PATH); + if (!dom) continue; + ray_sym_domain_release(dom); + } else { + TEST_ASSERT_EQ_I(ray_sym_save(TMP_DOM_SYM_PATH), RAY_OK); + } + if (w <= 1) { + /* a flush writes the new file's index: never the old one */ + int64_t cnt = 0; + TEST_ASSERT(ix_read(TMP_IX_PATH, ix_buf2, sizeof ix_buf2) >= IXH, "index written"); + memcpy(&cnt, ix_buf2 + 16, 8); + if (cnt != 2) FAILF("writer %d left the old index", w); + } else if (ix_exists(TMP_IX_PATH)) FAILF("writer %d left the old index", w); + } + /* a dead writer's temporary file */ + ix_unlink_all(); + const char* tmp = TMP_DOM_SYM_PATH ".ix.999999999.tmp"; + TEST_ASSERT(ix_write(tmp, ix_buf, 16), "temporary file"); + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH, ix_sym, sz), "symfile"); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + ray_sym_domain_release(dom); + TEST_ASSERT_TRUE(ix_exists(TMP_IX_PATH)); + TEST_ASSERT_FALSE(ix_exists(tmp)); + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* A reopen after another process changed the file: growth that keeps every + * published byte extends the domain — through the new file's index, or by + * a walk — and a change inside the old records is refused, with the new + * file's index or without: a length that moves the blocks after it, two in + * one block that keep them, a byte in the last, partial block or in the + * first records. */ +static test_result_t test_domain_index_extend_prefix(void) { + setenv("RAY_SYM_INDEX_MIN", "0", 1); + enum { N = 1000, M = 50 }; + for (int v = 0; v < 10; v++) { + ix_unlink_all(); + ix_gen(&ix_va, "ex", N + M); + TEST_ASSERT(ix_write_vocab(TMP_DOM_SYM_PATH, &ix_va, N), "symfile"); + ray_sym_domain_t* dom = ray_sym_domain_open(TMP_DOM_SYM_PATH); + TEST_ASSERT_NOT_NULL(dom); + TEST_ASSERT_NOT_NULL(ray_sym_domain_str(dom, 5 * IXS + 1)); + /* the grown file, by another process: tmp + rename, as a flush */ + ix_vb = ix_va; + if (v == 2 || v == 3) ix_set(&ix_vb, 5 * IXS + 1, "a_longer_string_in_a_whole_block"); + if (v == 4 || v == 5) ix_vb.s[N - 2][3] ^= 0x20; + if (v == 6 || v == 7) { /* one block's lengths: +3 and -3, its checkpoints kept */ + ix_set(&ix_vb, 335, "ex_335_xxxxxabc"); + ix_set(&ix_vb, 340, "ex_340_xxxxxxx"); + } + if (v == 8 || v == 9) ix_vb.s[2][1] ^= 0x20; /* a byte of the first records */ + size_t s2 = ix_strl(&ix_vb, N + M, ix_sym, ix_offs); + TEST_ASSERT(ix_write(TMP_DOM_SYM_PATH ".tmpx", ix_sym, s2), "grown file"); + TEST_ASSERT_EQ_I(rename(TMP_DOM_SYM_PATH ".tmpx", TMP_DOM_SYM_PATH), 0); + if (v % 2 == 0) { + size_t ib = ix_make(ix_buf, ix_sym, ix_offs, N + M, s2, TMP_DOM_SYM_PATH); + TEST_ASSERT(ix_write(TMP_IX_PATH, ix_buf, ib), "its index"); + } else { + unlink(TMP_IX_PATH); + } + ray_sym_domain_t* again = ray_sym_domain_open(TMP_DOM_SYM_PATH); + if (v <= 1) { + TEST_ASSERT_EQ_PTR(again, dom); + TEST_ASSERT(ix_check_all(dom, &ix_va, N + M), "extended"); + ray_sym_domain_ix_info_t in = ix_info(dom); + if (in.from_index != (v == 0)) FAILF("case %d: from_index %d", v, (int)in.from_index); + ray_sym_domain_release(again); + } else if (again) { + ray_sym_domain_release(again); + ray_sym_domain_release(dom); + FAILF("case %d: a changed prefix was taken for growth", v); + } + ray_sym_domain_release(dom); + } + unsetenv("RAY_SYM_INDEX_MIN"); + ix_unlink_all(); + PASS(); +} + +/* The domain scenarios that reopen, extend, flush and build lookups, run + * once more with every symfile indexed. */ +static test_result_t test_domain_index_scenarios(void) { + setenv("RAY_SYM_INDEX_MIN", "0", 1); + test_result_t (*const runs[])(void) = { + test_domain_open_basic, test_domain_raw_pin, test_domain_extend_reopen_flat, + test_domain_extend_after_flush, test_domain_flush_append, + test_domain_open_position0_validation, test_domain_intern_batch, + }; + for (size_t k = 0; k < sizeof runs / sizeof runs[0]; k++) { + test_result_t r = runs[k](); + if (r.status != TEST_PASS) { unsetenv("RAY_SYM_INDEX_MIN"); unlink(TMP_IX_PATH); return r; } + } + unsetenv("RAY_SYM_INDEX_MIN"); + unlink(TMP_IX_PATH); + PASS(); +} + + const test_entry_t domain_entries[] = { + { "domain/index_build_and_use", test_domain_index_build_and_use, domain_setup, domain_teardown }, + { "domain/index_long_strings", test_domain_index_long_strings, domain_setup, domain_teardown }, + { "domain/index_identity", test_domain_index_identity, domain_setup, domain_teardown }, + { "domain/index_rejects_bad", test_domain_index_rejects_bad, domain_setup, domain_teardown }, + { "domain/index_len_skips_record", test_domain_index_len_skips_record, domain_setup, domain_teardown }, + { "domain/index_cold_long_no_headers", test_domain_index_cold_long_no_headers, domain_setup, domain_teardown }, + { "domain/index_cold_len_no_bytes", test_domain_index_cold_len_no_bytes, domain_setup, domain_teardown }, + { "domain/index_append_unindexed", test_domain_index_append_unindexed, domain_setup, domain_teardown }, + { "domain/index_truncated_fails", test_domain_index_truncated_fails, domain_setup, domain_teardown }, + { "domain/index_writers", test_domain_index_writers, domain_setup, domain_teardown }, + { "domain/index_refresh_in_place", test_domain_index_refresh_in_place, domain_setup, domain_teardown }, + { "domain/index_new_file_removes", test_domain_index_new_file_removes, domain_setup, domain_teardown }, + { "domain/index_extend_prefix", test_domain_index_extend_prefix, domain_setup, domain_teardown }, + { "domain/index_scenarios", test_domain_index_scenarios, domain_setup, domain_teardown }, { "domain/private", test_domain_private, domain_setup, domain_teardown }, { "domain/flush_append", test_domain_flush_append, domain_setup, domain_teardown }, { "domain/import_dict", test_domain_import_dict, domain_setup, domain_teardown }, @@ -2742,10 +3899,14 @@ const test_entry_t domain_entries[] = { { "domain/parted_flatten_adopts", test_domain_parted_flatten_adopts, domain_rt_setup, domain_rt_teardown }, { "domain/str_eager_lockfree", test_domain_str_eager_lockfree, domain_setup, domain_teardown }, { "domain/raw_pin", test_domain_raw_pin, domain_setup, domain_teardown }, + { "domain/extend_reopen_flat", test_domain_extend_reopen_flat, domain_setup, domain_teardown }, + { "domain/extend_after_flush", test_domain_extend_after_flush, domain_setup, domain_teardown }, + { "domain/extend_under_batch", test_domain_extend_under_batch, domain_setup, domain_teardown }, { "domain/concat_text_nulls", test_domain_concat_text_nulls, domain_rt_setup, domain_rt_teardown }, { "domain/runtime_lut", test_domain_runtime_lut, domain_rt_setup, domain_rt_teardown }, { "domain/open_position0_validation", test_domain_open_position0_validation, domain_setup, domain_teardown }, { "domain/intern_batch", test_domain_intern_batch, domain_setup, domain_teardown }, + { "domain/intern_batch_cancel", test_domain_intern_batch_cancel, domain_setup, domain_teardown }, { "domain/intern_batch_concurrent", test_domain_intern_batch_concurrent, domain_setup, domain_teardown }, { "domain/dict_upsert_file_keys", test_domain_dict_upsert_file_keys, domain_rt_setup, domain_rt_teardown }, { NULL, NULL, NULL, NULL }, diff --git a/test/test_embedding.c b/test/test_embedding.c index 587601091..0e04e5192 100644 --- a/test/test_embedding.c +++ b/test/test_embedding.c @@ -390,7 +390,7 @@ static test_result_t test_ann_recall_saturated(void) { /* ============ Persistence round-trip ============ */ static test_result_t test_hnsw_save_load(void) { - const char* dir = "/tmp/ray_hnsw_test_idx"; + const char* dir = ray_test_tmp("/tmp/ray_hnsw_test_idx"); /* Build and save in 'ip metric. */ ray_eval_str("(set __idx (hnsw-build " FIVE_VECS " 'ip 4 50))"); char expr[512]; @@ -943,7 +943,7 @@ static test_result_t test_hnsw_search_filter_null_accept(void) { /* ray_hnsw_mmap: exercised via the C API directly (not exposed as a builtin). */ static test_result_t test_hnsw_mmap_load(void) { - const char* dir = "/tmp/ray_hnsw_mmap_test"; + const char* dir = ray_test_tmp("/tmp/ray_hnsw_mmap_test"); /* Build & save a small index. */ float vecs[5 * 3] = { 1.0f, 0.0f, 0.0f, @@ -1016,7 +1016,7 @@ static test_result_t test_hnsw_vec_size_valid_guard(void) { * malformed file must be rejected by both load entry points before a query * can turn it into an out-of-bounds read / process crash. */ static test_result_t test_hnsw_load_rejects_bad_neighbor(void) { - const char* dir = "/tmp/ray_hnsw_bad_neighbor"; + const char* dir = ray_test_tmp("/tmp/ray_hnsw_bad_neighbor"); float vecs[2 * 2] = { 1.0f, 0.0f, 0.0f, 1.0f }; ray_hnsw_t* idx = ray_hnsw_build(vecs, 2, 2, RAY_HNSW_L2, 4, 50); TEST_ASSERT_NOT_NULL(idx); @@ -1042,9 +1042,9 @@ static test_result_t test_hnsw_load_rejects_bad_neighbor(void) { * upper layer. Loading should discard that unusable edge, while still * rejecting malformed entry-point and layer-width metadata. */ static test_result_t test_hnsw_load_repairs_legacy_layer_edge(void) { - const char* neighbor_dir = "/tmp/ray_hnsw_wrong_layer_neighbor"; - const char* entry_dir = "/tmp/ray_hnsw_wrong_layer_entry"; - const char* width_dir = "/tmp/ray_hnsw_wrong_layer_width"; + const char* neighbor_dir = ray_test_tmp("/tmp/ray_hnsw_wrong_layer_neighbor"); + const char* entry_dir = ray_test_tmp("/tmp/ray_hnsw_wrong_layer_entry"); + const char* width_dir = ray_test_tmp("/tmp/ray_hnsw_wrong_layer_width"); float vecs[128 * 2]; for (int i = 0; i < 128; i++) { vecs[i * 2] = (float)i; diff --git a/test/test_enc.c b/test/test_enc.c new file mode 100644 index 000000000..09332ac6f --- /dev/null +++ b/test/test_enc.c @@ -0,0 +1,739 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "store/enc.h" +#include +#include + +static void enc_setup(void) { ray_heap_init(); (void)ray_sym_init(); } +static void enc_teardown(void) { ray_sym_destroy(); ray_heap_destroy(); } + +/* Deterministic xorshift for test data. */ +static uint64_t enc_rng(uint64_t* s) { + uint64_t x = *s; x ^= x << 13; x ^= x >> 7; x ^= x << 17; return *s = x; +} + +static test_result_t test_pack_roundtrip_all_widths(void) { + static const int Ts[4] = { 8, 16, 32, 64 }; + uint64_t seed = 0x9E3779B97F4A7C15ull; + uint64_t* u = malloc(sizeof(uint64_t) * RAY_ENC_VEC); + uint64_t* back = malloc(sizeof(uint64_t) * RAY_ENC_VEC); + uint8_t* buf = malloc(RAY_ENC_VEC * 8); + TEST_ASSERT_TRUE(u && back && buf); + for (int ti = 0; ti < 4; ti++) { + int T = Ts[ti]; + for (int w = 0; w <= T; w++) { + uint64_t mask = w == 64 ? ~0ull : ((1ull << w) - 1); + for (int i = 0; i < RAY_ENC_VEC; i++) u[i] = enc_rng(&seed) & mask; + memset(buf, 0xA5, RAY_ENC_VEC * 8); + ray_enc_pack(u, T, w, buf); + ray_enc_unpack(buf, T, w, back); + for (int i = 0; i < RAY_ENC_VEC; i++) + TEST_ASSERT_FMT(back[i] == u[i], "T=%d w=%d i=%d", T, w, i); + } + } + free(u); free(back); free(buf); + PASS(); +} + +/* The layout itself, not just the round trip: with T=8, w=1, value i is + * bit (i / L) % 8 of byte i % L where L = 128, because each lane has one + * 8-bit word (w=1 word per lane) holding its 8 rows LSB first. */ +static test_result_t test_pack_layout_t8_w1(void) { + uint64_t u[RAY_ENC_VEC]; + uint8_t out[RAY_ENC_VEC / 8]; + for (int i = 0; i < RAY_ENC_VEC; i++) u[i] = (i == 3 || i == 128 + 5 || i == 7 * 128 + 127) ? 1 : 0; + ray_enc_pack(u, 8, 1, out); + TEST_ASSERT_EQ_U(ray_enc_packed_bytes(1), 128); + for (int b = 0; b < 128; b++) { + uint8_t want = 0; + if (b == 3) want |= 1u << 0; /* i=3: lane 3, row 0 */ + if (b == 5) want |= 1u << 1; /* i=133: lane 5, row 1 */ + if (b == 127) want |= 1u << 7; /* i=1023: lane 127, row 7 */ + TEST_ASSERT_FMT(out[b] == want, "byte %d = %02x want %02x", b, out[b], want); + } + PASS(); +} + +/* T=16, w=3: lane l's 16 values occupy 3 consecutive 16-bit words stored at + * word indexes l, L+l, 2L+l (L = 64); value r of lane l sits at bit 3*r of + * that 48-bit stream. */ +static test_result_t test_pack_layout_t16_w3(void) { + uint64_t u[RAY_ENC_VEC] = {0}; + int L = 64; + u[5 + 6 * L] = 5; /* lane 5, row 6: bits 18..20 -> word 1, bits 2..4 */ + uint16_t words[RAY_ENC_VEC * 3 / 16]; + ray_enc_pack(u, 16, 3, (uint8_t*)words); + for (int k = 0; k < 3; k++) + for (int l = 0; l < L; l++) { + uint16_t want = (k == 1 && l == 5) ? (uint16_t)(5u << 2) : 0; + TEST_ASSERT_FMT(words[k * L + l] == want, "k=%d l=%d", k, l); + } + PASS(); +} + +static test_result_t test_bitlen(void) { + TEST_ASSERT_EQ_I(ray_enc_bitlen(0), 0); + TEST_ASSERT_EQ_I(ray_enc_bitlen(1), 1); + TEST_ASSERT_EQ_I(ray_enc_bitlen(255), 8); + TEST_ASSERT_EQ_I(ray_enc_bitlen(256), 9); + TEST_ASSERT_EQ_I(ray_enc_bitlen(~0ull), 64); + PASS(); +} + +static test_result_t test_kind_of(void) { + ray_enc_kind_t k; + TEST_ASSERT_TRUE(ray_enc_kind_of(RAY_I16, 0, &k)); TEST_ASSERT_EQ_I(k.T, 16); TEST_ASSERT_TRUE(k.is_signed); + TEST_ASSERT_TRUE(ray_enc_kind_of(RAY_DATE, 0, &k)); TEST_ASSERT_EQ_I(k.T, 32); TEST_ASSERT_TRUE(k.is_signed); + TEST_ASSERT_TRUE(ray_enc_kind_of(RAY_TIMESTAMP, 0, &k)); TEST_ASSERT_EQ_I(k.T, 64); + TEST_ASSERT_TRUE(ray_enc_kind_of(RAY_U8, 0, &k)); TEST_ASSERT_EQ_I(k.T, 8); TEST_ASSERT_FALSE(k.is_signed); + TEST_ASSERT_TRUE(ray_enc_kind_of(RAY_SYM, RAY_SYM_W16, &k)); TEST_ASSERT_EQ_I(k.T, 16); TEST_ASSERT_FALSE(k.is_signed); + TEST_ASSERT_FALSE(ray_enc_kind_of(RAY_F64, 0, &k)); + TEST_ASSERT_FALSE(ray_enc_kind_of(RAY_STR, 0, &k)); + PASS(); +} + +static test_result_t test_logical_and_order(void) { + ray_enc_kind_t s16 = { 16, true, false }, u8 = { 8, false, false }; + TEST_ASSERT_EQ_I(ray_enc_logical(0xFFFF, s16), -1); + TEST_ASSERT_EQ_I(ray_enc_logical(0x7FFF, s16), 32767); + TEST_ASSERT_TRUE(ray_enc_lt(0xFFFF, 0x0001, s16)); /* -1 < 1 */ + TEST_ASSERT_EQ_I(ray_enc_logical(0x80, u8), 128); /* no sign extension */ + TEST_ASSERT_TRUE(ray_enc_lt(0x7F, 0x80, u8)); /* 127 < 128 */ + PASS(); +} + +static test_result_t test_load_i64_nulls_fill_min(void) { + int64_t d[5] = { 40, NULL_I64, -7, NULL_I64, 12 }; + ray_enc_input_t in; + TEST_ASSERT_TRUE(ray_enc_load(d, RAY_I64, 0, 0, 5, &in)); + TEST_ASSERT_EQ_I(in.n, 5); + TEST_ASSERT_EQ_I(in.n_nulls, 2); + TEST_ASSERT_TRUE(in.bitmap); + TEST_ASSERT_EQ_U(in.nullmap[0], 0x0A); /* rows 1 and 3 */ + TEST_ASSERT_EQ_I((int64_t)in.bits[1], -7); /* filled with min */ + TEST_ASSERT_EQ_I((int64_t)in.bits[3], -7); + TEST_ASSERT_EQ_I((int64_t)in.bits[4], 12); + PASS(); +} + +static test_result_t test_load_all_null_fills_zero(void) { + int32_t d[3] = { NULL_I32, NULL_I32, NULL_I32 }; + ray_enc_input_t in; + TEST_ASSERT_TRUE(ray_enc_load(d, RAY_I32, 0, 0, 3, &in)); + TEST_ASSERT_EQ_I(in.n_nulls, 3); + for (int i = 0; i < 3; i++) TEST_ASSERT_EQ_U(in.bits[i], 0); + PASS(); +} + +static test_result_t test_load_sym_w8_inband(void) { + uint8_t d[4] = { 0, 127, 128, 255 }; /* id 0 is the in-band null */ + ray_enc_input_t in; + TEST_ASSERT_TRUE(ray_enc_load(d, RAY_SYM, RAY_SYM_W8, 0, 4, &in)); + TEST_ASSERT_FALSE(in.bitmap); + TEST_ASSERT_EQ_I(in.n_nulls, 1); + TEST_ASSERT_EQ_U(in.bits[0], 0); /* stored as itself */ + TEST_ASSERT_EQ_U(in.bits[2], 128); + ray_enc_stats_t s; + ray_enc_stats(in.bits, in.n, in.k, &s); + TEST_ASSERT_EQ_U(s.min, 0); + TEST_ASSERT_EQ_U(s.max, 255); + TEST_ASSERT_EQ_I(s.runs, 4); + PASS(); +} + +static test_result_t test_stats_runs_and_equal(void) { + uint64_t v[6] = { 5, 5, 5, 9, 9, 5 }; + ray_enc_kind_t k = { 32, true, false }; + ray_enc_stats_t s; + ray_enc_stats(v, 6, k, &s); + TEST_ASSERT_EQ_I(s.runs, 3); + TEST_ASSERT_FALSE(s.all_equal); + ray_enc_stats(v, 3, k, &s); + TEST_ASSERT_TRUE(s.all_equal); + TEST_ASSERT_EQ_I(s.runs, 1); + PASS(); +} + +static test_result_t test_load_offset_start(void) { + int16_t d[2000]; + for (int i = 0; i < 2000; i++) d[i] = (int16_t)(i - 1000); + ray_enc_input_t in; + TEST_ASSERT_TRUE(ray_enc_load(d, RAY_I16, 0, 1024, 976, &in)); + TEST_ASSERT_EQ_I(in.n, 976); + TEST_ASSERT_EQ_I(ray_enc_logical(in.bits[0], in.k), 24); + TEST_ASSERT_EQ_I(ray_enc_logical(in.bits[975], in.k), 999); + PASS(); +} + +static test_result_t test_sizes_raw_const(void) { + TEST_ASSERT_EQ_I(ray_enc_size_raw(1024, 16), 2048); + TEST_ASSERT_EQ_I(ray_enc_size_raw(3, 16), 8); /* 6 bytes padded to 8 */ + TEST_ASSERT_EQ_I(ray_enc_size_raw(1, 64), 8); + TEST_ASSERT_EQ_I(ray_enc_size_const(), 8); + PASS(); +} + +static test_result_t test_for_width_signed_extremes(void) { + uint64_t v[3] = { (uint64_t)(INT64_MIN + 1), (uint64_t)INT64_MAX, 0 }; + ray_enc_kind_t k = { 64, true, false }; + uint64_t base; + int w = ray_enc_for_width(v, 3, k, &base); + TEST_ASSERT_EQ_U(base, (uint64_t)(INT64_MIN + 1)); /* native min */ + TEST_ASSERT_EQ_I(w, 64); /* range 2^64 - 2 */ + TEST_ASSERT_EQ_I(ray_enc_size_for(w), 8 + 8192); + PASS(); +} + +static test_result_t test_for_width_narrow(void) { + uint64_t v[4] = { 0xFFFE, 0xFFFF, 0x0000, 0x0001 }; /* -2,-1,0,1 as I16 */ + ray_enc_kind_t k = { 16, true, false }; + uint64_t base; + int w = ray_enc_for_width(v, 4, k, &base); + TEST_ASSERT_EQ_U(base, 0xFFFE); + TEST_ASSERT_EQ_I(w, 2); /* residuals 0..3 */ + PASS(); +} + +static test_result_t test_delta_width_sorted(void) { + static uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(1000000 + 3 * i); + ray_enc_kind_t k = { 64, true, false }; + uint64_t dbase; + int w = ray_enc_delta_width(v, RAY_ENC_VEC, k, &dbase); + TEST_ASSERT_EQ_U(dbase, 3 * 16); /* lane stride L=16 */ + TEST_ASSERT_EQ_I(w, 0); + TEST_ASSERT_EQ_I(ray_enc_size_delta(64, 0), 8 + 8 * 16); + PASS(); +} + +/* Encode at the top level, decode, compare; returns the chosen encoding. */ +static int enc_roundtrip(const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* dict, int64_t* bytes) { + ray_enc_buf_t b = {0}; + ray_enc_choice_t c; + if (!ray_enc_write(v, n, k, RAY_ENC_SLOT_TOP, 0, dict, &b, &c)) return -1; + if ((int64_t)b.len != c.bytes) { ray_enc_buf_free(&b); return -2; } + uint64_t out[RAY_ENC_VEC]; + int64_t used = ray_enc_read(b.p, b.len, c.enc, c.width, n, k, RAY_ENC_SLOT_TOP, 0, dict, out); + int rc = used == (int64_t)b.len ? c.enc : -3; + for (int i = 0; rc >= 0 && i < n; i++) if (out[i] != (v[i] & (k.T == 64 ? ~0ull : ((1ull << k.T) - 1)))) rc = -4; + if (bytes) *bytes = c.bytes; + ray_enc_buf_free(&b); + return rc; +} + +static test_result_t test_choose_const(void) { + uint64_t v[1000]; + for (int i = 0; i < 1000; i++) v[i] = 42; + ray_enc_kind_t k = { 32, true, false }; + int64_t bytes; + TEST_ASSERT_EQ_I(enc_roundtrip(v, 1000, k, NULL, &bytes), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(bytes, 8); + PASS(); +} + +static test_result_t test_choose_rle_runs(void) { + static uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(i / 100) * 1000003ull; /* 11 runs, wide values */ + ray_enc_kind_t k = { 64, true, false }; + TEST_ASSERT_EQ_I(enc_roundtrip(v, RAY_ENC_VEC, k, NULL, NULL), RAY_ENC_RLE); + PASS(); +} + +static test_result_t test_choose_for(void) { + static uint64_t v[RAY_ENC_VEC]; + uint64_t s = 7; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 5000 + (enc_rng(&s) & 0x3F); /* 6-bit spread */ + ray_enc_kind_t k = { 32, true, false }; + int64_t bytes; + TEST_ASSERT_EQ_I(enc_roundtrip(v, RAY_ENC_VEC, k, NULL, &bytes), RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(bytes, 8 + 1024 * 6 / 8); + PASS(); +} + +static test_result_t test_choose_delta(void) { + static uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 1700000000000ull + 1000ull * (uint64_t)i; /* timestamps */ + ray_enc_kind_t k = { 64, true, false }; + TEST_ASSERT_EQ_I(enc_roundtrip(v, RAY_ENC_VEC, k, NULL, NULL), RAY_ENC_DELTA_BP); + PASS(); +} + +static test_result_t test_keep_raw_when_gain_small(void) { + static uint64_t v[RAY_ENC_VEC]; + uint64_t s = 99; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = enc_rng(&s) & 0xFFFF; /* full 16-bit spread */ + ray_enc_kind_t k = { 16, false, false }; + TEST_ASSERT_EQ_I(enc_roundtrip(v, RAY_ENC_VEC, k, NULL, NULL), RAY_ENC_RAW); + PASS(); +} + +static test_result_t test_dict_wide_sparse_values(void) { + static uint64_t v[RAY_ENC_VEC]; + static const uint64_t vals[4] = { 11ull, 900000000001ull, 77ull, 123456789012345ull }; + /* Pseudo-random picks: a period dividing the delta lane stride (16) would make + * DELTA_BP the smaller encoding (all lane deltas zero), which is correct but + * not what this test exercises. */ + uint64_t s = 31; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = vals[enc_rng(&s) & 3]; + ray_enc_kind_t k = { 64, true, false }; + uint64_t* d; uint32_t dn; + TEST_ASSERT_EQ_I(ray_enc_train_dict(v, RAY_ENC_VEC, k, &d, &dn), 1); + TEST_ASSERT_EQ_I(dn, 4); + TEST_ASSERT_EQ_U(d[0], 11ull); + TEST_ASSERT_EQ_U(d[3], 123456789012345ull); + ray_enc_dict_t dict = { d, dn }; + TEST_ASSERT_EQ_I(enc_roundtrip(v, RAY_ENC_VEC, k, &dict, NULL), RAY_ENC_DICT); + ray_free_raw(d); + PASS(); +} + +static test_result_t test_roundtrip_lengths_and_types(void) { + static const int lens[6] = { 1, 2, 1023, 1024, 17, 512 }; + static const ray_enc_kind_t kinds[5] = { { 8, false, false }, { 16, true, false }, { 32, true, false }, { 64, true, false }, { 16, false, false } }; + uint64_t s = 12345; + for (int ki = 0; ki < 5; ki++) + for (int li = 0; li < 6; li++) + for (int shape = 0; shape < 4; shape++) { + static uint64_t v[RAY_ENC_VEC]; + int n = lens[li]; + for (int i = 0; i < n; i++) { + uint64_t x = enc_rng(&s); + v[i] = shape == 0 ? x : shape == 1 ? (x & 3) : shape == 2 ? (uint64_t)(i / 37) : 7; + } + int rc = enc_roundtrip(v, n, kinds[ki], NULL, NULL); + TEST_ASSERT_FMT(rc >= 0, "kind T=%d n=%d shape=%d rc=%d", kinds[ki].T, n, shape, rc); + } + PASS(); +} + +static test_result_t test_i64_extremes_roundtrip(void) { + uint64_t v[6] = { (uint64_t)(INT64_MIN + 1), (uint64_t)INT64_MAX, 0, + (uint64_t)(INT64_MIN + 1), (uint64_t)-5, (uint64_t)INT64_MAX }; + ray_enc_kind_t k = { 64, true, false }; + TEST_ASSERT_TRUE(enc_roundtrip(v, 6, k, NULL, NULL) >= 0); + PASS(); +} + +/* DICT at the top whose codes child is RLE: ~100 distinct wide values in runs of + * 10. Top-level RLE would need RAW wide values (8 B per run); DICT with RLE + * codes (4 B per run) is smaller. DICT is legal only at the top, so this is the + * deepest nesting the encoder emits (DICT -> RLE codes -> RAW/FOR children). */ +static test_result_t test_dict_codes_rle_nested(void) { + static uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 0x123456789ABull * (uint64_t)((i / 10) % 100 + 1); + ray_enc_kind_t k = { 64, true, false }; + uint64_t* d; uint32_t dn; + TEST_ASSERT_EQ_I(ray_enc_train_dict(v, RAY_ENC_VEC, k, &d, &dn), 1); + ray_enc_dict_t dict = { d, dn }; + ray_enc_buf_t b = {0}; + ray_enc_choice_t c; + TEST_ASSERT_TRUE(ray_enc_write(v, RAY_ENC_VEC, k, RAY_ENC_SLOT_TOP, 0, &dict, &b, &c)); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_DICT); + TEST_ASSERT_EQ_I(b.p[0], RAY_ENC_RLE); /* codes child header: encoding */ + uint64_t out[RAY_ENC_VEC]; + TEST_ASSERT_EQ_I(ray_enc_read(b.p, b.len, c.enc, c.width, RAY_ENC_VEC, k, RAY_ENC_SLOT_TOP, 0, &dict, out), (int64_t)b.len); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_FMT(out[i] == v[i], "i=%d", i); + ray_enc_buf_free(&b); + ray_free_raw(d); + PASS(); +} + +/* ---- independent byte-level references (spec "Encodings"), no codec calls ---- */ +static uint64_t ref_mask(int T) { return T == 64 ? ~0ull : ((1ull << T) - 1); } + +/* Bit-by-bit packer: value i is lane i % L, row i / L; its bit b is bit + * (row*w + b) of the lane stream, i.e. bit (that % T) of word (that / T), + * stored at word index k*L + l. */ +static void ref_pack(const uint64_t* u, int T, int w, uint8_t* out) { + int L = RAY_ENC_VEC / T; + memset(out, 0, (size_t)RAY_ENC_VEC * (size_t)w / 8); + for (int i = 0; i < RAY_ENC_VEC; i++) { + int l = i % L, r = i / L; + for (int b = 0; b < w; b++) { + if (!((u[i] >> b) & 1)) continue; + int bit = r * w + b, k = bit / T, o = bit % T; + size_t byte = ((size_t)k * (size_t)L + (size_t)l) * (size_t)(T / 8) + (size_t)(o / 8); + out[byte] |= (uint8_t)(1u << (o % 8)); + } + } +} + +static int ref_bitlen(uint64_t x) { int n = 0; while (x) { n++; x >>= 1; } return n; } +static int64_t ref_logical(uint64_t b, int T) { + b &= ref_mask(T); + if (T < 64 && ((b >> (T - 1)) & 1)) return (int64_t)(b | ~ref_mask(T)); + return (int64_t)b; +} + +/* Expected FOR_BP body for n logical values (padded with base). */ +static size_t ref_for_body(const uint64_t* v, int n, int T, uint8_t* exp, int* wout) { + uint64_t m = ref_mask(T); + int64_t mn = ref_logical(v[0], T), mx = mn; + for (int i = 1; i < n; i++) { + int64_t x = ref_logical(v[i], T); + if (x < mn) mn = x; + if (x > mx) mx = x; + } + uint64_t base = (uint64_t)mn & m; + int w = ref_bitlen(((uint64_t)mx - (uint64_t)mn) & m); + static uint64_t u[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) u[i] = i < n ? ((v[i] - base) & m) : 0; + memcpy(exp, &base, 8); + ref_pack(u, T, w, exp + 8); + *wout = w; + return 8 + (size_t)RAY_ENC_VEC * (size_t)w / 8; +} + +/* Expected DELTA_BP body: v padded with its last value, lane-stride deltas. */ +static size_t ref_delta_body(const uint64_t* v, int n, int T, uint8_t* exp, int* wout) { + uint64_t m = ref_mask(T); + int L = RAY_ENC_VEC / T; + static uint64_t p[RAY_ENC_VEC], d[RAY_ENC_VEC], r[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) p[i] = (i < n ? v[i] : v[n - 1]) & m; + uint64_t db = ~0ull; + for (int i = L; i < RAY_ENC_VEC; i++) { d[i] = (p[i] - p[i - L]) & m; if (d[i] < db) db = d[i]; } + uint64_t mx = 0; + for (int i = 0; i < RAY_ENC_VEC; i++) { r[i] = i < L ? 0 : ((d[i] - db) & m); if (r[i] > mx) mx = r[i]; } + int w = ref_bitlen(mx); + memcpy(exp, &db, 8); + for (int l = 0; l < L; l++) memcpy(exp + 8 + 8 * (size_t)l, &p[l], 8); + ref_pack(r, T, w, exp + 8 + 8 * (size_t)L); + *wout = w; + return 8 + 8 * (size_t)L + (size_t)RAY_ENC_VEC * (size_t)w / 8; +} + +static void for_data(uint64_t* v, int n, int T, int64_t lo, uint64_t span, uint64_t seed) { + for (int i = 0; i < n; i++) v[i] = (uint64_t)(lo + (int64_t)(enc_rng(&seed) % span)) & ref_mask(T); +} +static void delta_data(uint64_t* v, int n, int T) { + for (int i = 0; i < n; i++) v[i] = (uint64_t)(int64_t)(-500 + 7 * i + (i % 3)) & ref_mask(T); +} + +static int layout_case(int want_enc, int T, int n, bool delta, int expect_w) { + static uint64_t v[RAY_ENC_VEC]; + static uint8_t exp[8 + 8 * 128 + RAY_ENC_VEC * 8]; + ray_enc_kind_t k = { (uint8_t)T, true, false }; + if (delta) delta_data(v, n, T); + else for_data(v, n, T, -200, expect_w == 9 ? 512 : 1000, 0x1234567ull + (uint64_t)T + (uint64_t)n); + int w; size_t len = delta ? ref_delta_body(v, n, T, exp, &w) : ref_for_body(v, n, T, exp, &w); + if (expect_w && w != expect_w) return 1; + ray_enc_buf_t b = {0}; + ray_enc_choice_t c; + if (!ray_enc_write(v, n, k, RAY_ENC_SLOT_TOP, 0, NULL, &b, &c)) return 2; + int rc = 0; + if (c.enc != want_enc) rc = 3; + else if (c.width != w) rc = 4; + else if (b.len != len) rc = 5; + else if (memcmp(b.p, exp, len)) rc = 6; + ray_enc_buf_free(&b); + return rc; +} + +static test_result_t test_layout_for_partial(void) { + static const int Ts[2] = { 32, 64 }, ns[2] = { 500, 700 }; + for (int a = 0; a < 2; a++) + for (int b = 0; b < 2; b++) + TEST_ASSERT_FMT(layout_case(RAY_ENC_FOR_BP, Ts[a], ns[b], false, 0) == 0, "FOR T=%d n=%d", Ts[a], ns[b]); + TEST_ASSERT_EQ_I(layout_case(RAY_ENC_FOR_BP, 16, 1000, false, 9), 0); /* straddling width */ + PASS(); +} + +static test_result_t test_layout_delta_partial(void) { + static const int Ts[2] = { 32, 64 }, ns[2] = { 500, 700 }; + for (int a = 0; a < 2; a++) + for (int b = 0; b < 2; b++) + TEST_ASSERT_FMT(layout_case(RAY_ENC_DELTA_BP, Ts[a], ns[b], true, 0) == 0, "DELTA T=%d n=%d", Ts[a], ns[b]); + PASS(); +} + +/* T=16, w=3, value 5 at lane 5 row 5: lane bits 15..17 straddle words 0 and 1. */ +static test_result_t test_pack_layout_straddle(void) { + uint64_t u[RAY_ENC_VEC] = {0}; + int L = 64; + u[5 + 5 * L] = 5; /* 0b101: bit 0 -> word 0 bit 15; bits 1,2 (0b10) -> word 1 bits 0..1 */ + uint16_t words[RAY_ENC_VEC * 3 / 16]; + ray_enc_pack(u, 16, 3, (uint8_t*)words); + for (int k = 0; k < 3; k++) + for (int l = 0; l < L; l++) { + uint16_t want = 0; + if (k == 0 && l == 5) want = 0x8000; + if (k == 1 && l == 5) want = 0x0002; + TEST_ASSERT_FMT(words[k * L + l] == want, "k=%d l=%d got %04x want %04x", k, l, words[k * L + l], want); + } + uint64_t back[RAY_ENC_VEC]; + ray_enc_unpack((const uint8_t*)words, 16, 3, back); + TEST_ASSERT_EQ_U(back[5 + 5 * L], 5); + PASS(); +} + +/* Sign-extended input (bits above T set) encodes to the same bytes as the + * masked input, and the result decodes to the masked values. */ +static test_result_t test_encode_sign_extended(void) { + static uint64_t ext[RAY_ENC_VEC], msk[RAY_ENC_VEC], out[RAY_ENC_VEC]; + for (int ci = 0; ci < 2; ci++) { + int T = ci ? 32 : 16; + ray_enc_kind_t k = { (uint8_t)T, true, false }; + for (int delta = 0; delta < 2; delta++) { + for (int i = 0; i < RAY_ENC_VEC; i++) { + int64_t x = delta ? -500 + 7 * i + (i % 3) : -(i & 1); + ext[i] = (uint64_t)x; /* sign-extended to 64 bits */ + msk[i] = (uint64_t)x & ref_mask(T); + } + ray_enc_buf_t a = {0}, b = {0}; + ray_enc_choice_t ca, cb; + TEST_ASSERT_TRUE(ray_enc_write(ext, RAY_ENC_VEC, k, RAY_ENC_SLOT_TOP, 0, NULL, &a, &ca)); + TEST_ASSERT_TRUE(ray_enc_write(msk, RAY_ENC_VEC, k, RAY_ENC_SLOT_TOP, 0, NULL, &b, &cb)); + TEST_ASSERT_EQ_I(ca.enc, delta ? RAY_ENC_DELTA_BP : RAY_ENC_FOR_BP); + TEST_ASSERT_TRUE(ca.enc == cb.enc && a.len == b.len && !memcmp(a.p, b.p, a.len)); + int64_t used = ray_enc_read(a.p, a.len, ca.enc, ca.width, RAY_ENC_VEC, k, RAY_ENC_SLOT_TOP, 0, NULL, out); + TEST_ASSERT_EQ_I(used, (int64_t)a.len); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_EQ_U(out[i], msk[i]); + ray_enc_buf_free(&a); ray_enc_buf_free(&b); + } + } + /* The small case from the review: I16 {-1, 0}. */ + uint64_t two[2] = { ~0ull, 0 }, o2[2]; + ray_enc_kind_t k16 = { 16, true, false }; + ray_enc_buf_t t = {0}; ray_enc_choice_t ct; + TEST_ASSERT_TRUE(ray_enc_write(two, 2, k16, RAY_ENC_SLOT_TOP, 0, NULL, &t, &ct)); + TEST_ASSERT_EQ_I(ray_enc_read(t.p, t.len, ct.enc, ct.width, 2, k16, RAY_ENC_SLOT_TOP, 0, NULL, o2), (int64_t)t.len); + TEST_ASSERT_EQ_U(o2[0], 0xFFFFull); + TEST_ASSERT_EQ_U(o2[1], 0); + ray_enc_buf_free(&t); + PASS(); +} + +static test_result_t test_load_rejects_bad_n(void) { + static int32_t d[RAY_ENC_VEC + 8]; + static ray_enc_input_t in; + TEST_ASSERT_FALSE(ray_enc_load(d, RAY_I32, 0, 0, RAY_ENC_VEC + 1, &in)); + TEST_ASSERT_FALSE(ray_enc_load(d, RAY_I32, 0, 0, -1, &in)); + TEST_ASSERT_TRUE(ray_enc_load(d, RAY_I32, 0, 0, RAY_ENC_VEC, &in)); + TEST_ASSERT_TRUE(ray_enc_load(d, RAY_I32, 0, 0, 0, &in)); + PASS(); +} + +static test_result_t test_buf_free_clears_oom(void) { + ray_enc_buf_t b = {0}; + b.oom = true; + ray_enc_buf_free(&b); + TEST_ASSERT_FALSE(b.oom); + TEST_ASSERT_TRUE(ray_enc_buf_put(&b, "x", 1)); + ray_enc_buf_free(&b); + PASS(); +} + +static test_result_t test_train_dict_tristate(void) { + static uint64_t v[RAY_ENC_VEC * 70]; + ray_enc_kind_t k = { 64, true, false }; + uint64_t* d = NULL; uint32_t dn = 0; + TEST_ASSERT_EQ_I(ray_enc_train_dict(v, 0, k, &d, &dn), 0); + for (int64_t i = 0; i < (int64_t)RAY_ENC_VEC * 70; i++) v[i] = (uint64_t)i; /* 71680 > 1<<16 distinct */ + TEST_ASSERT_EQ_I(ray_enc_train_dict(v, (int64_t)RAY_ENC_VEC * 70, k, &d, &dn), 0); + for (int64_t i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(i % 5); + TEST_ASSERT_EQ_I(ray_enc_train_dict(v, RAY_ENC_VEC, k, &d, &dn), 1); + TEST_ASSERT_EQ_I(dn, 5); + ray_free_raw(d); + PASS(); +} + +/* Child header: encoding, width, bytes of body at +4. */ +static size_t put_child(uint8_t* p, uint8_t enc, uint32_t body_bytes) { + memset(p, 0, 8); p[0] = enc; memcpy(p + 4, &body_bytes, 4); + return 8; +} + +/* DICT is illegal as an RLE values child. Control pair: a valid RLE body + * with a RAW values child reads; the same body with the values child's + * encoding byte set to DICT (codes child well formed) is rejected. */ +static test_result_t test_read_rle_under_dict(void) { + ray_enc_kind_t k = { 64, true, false }; + uint64_t dv[1] = { 7 }; + ray_enc_dict_t dict = { dv, 1 }; + uint64_t out[RAY_ENC_VEC]; + uint8_t body[96]; + /* control: one run of 4 values, values RAW (one u64), ends RAW U16 (one) */ + memset(body, 0, sizeof body); + uint32_t nruns = 1; memcpy(body, &nruns, 4); + size_t at = 8; + at += put_child(body + at, RAY_ENC_RAW, 8); + uint64_t seven = 7; memcpy(body + at, &seven, 8); at += 8; + at += put_child(body + at, RAY_ENC_RAW, (uint32_t)ray_enc_size_raw(1, 16)); + uint16_t end4 = 4; memcpy(body + at, &end4, 2); at += (size_t)ray_enc_size_raw(1, 16); + int64_t used = ray_enc_read(body, sizeof body, RAY_ENC_RLE, 0, 4, k, + RAY_ENC_SLOT_TOP, 0, &dict, out); + TEST_ASSERT_EQ_I(used, (int64_t)at); + for (int i = 0; i < 4; i++) TEST_ASSERT_EQ_I(out[i], 7); + PASS(); +} + +/* Training sorts in the kind's native order. */ +static test_result_t test_train_dict_native_order(void) { + uint64_t s16[6] = { 0xFFFE, 0x0003, 0x8000, 0x7FFF, 0xFFFE, 0x0000 }; /* -2,3,-32768,32767,-2,0 */ + ray_enc_kind_t ks = { 16, true, false }; + uint64_t* d; uint32_t dn; + TEST_ASSERT_EQ_I(ray_enc_train_dict(s16, 6, ks, &d, &dn), 1); + TEST_ASSERT_EQ_I(dn, 5); + static const uint64_t want_s[5] = { 0x8000, 0xFFFE, 0x0000, 0x0003, 0x7FFF }; + for (int i = 0; i < 5; i++) TEST_ASSERT_FMT(d[i] == want_s[i], "signed i=%d", i); + ray_free_raw(d); + uint64_t u8[4] = { 128, 127, 255, 0 }; + ray_enc_kind_t ku = { 8, false, false }; + TEST_ASSERT_EQ_I(ray_enc_train_dict(u8, 4, ku, &d, &dn), 1); + static const uint64_t want_u[4] = { 0, 127, 128, 255 }; + for (int i = 0; i < 4; i++) TEST_ASSERT_FMT(d[i] == want_u[i], "unsigned i=%d", i); + ray_free_raw(d); + PASS(); +} + +/* Forced writes round-trip and reach what selection never picks. */ +static int forced_roundtrip(uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k, + const ray_enc_dict_t* dict, ray_enc_buf_t* b, ray_enc_choice_t* c) { + b->len = 0; + if (!ray_enc_write_as(enc, v, n, k, dict, b, c)) return -1; + if ((int64_t)b->len != c->bytes || c->enc != enc) return -2; + uint64_t out[RAY_ENC_VEC]; + if (ray_enc_read(b->p, b->len, c->enc, c->width, n, k, RAY_ENC_SLOT_TOP, 0, dict, out) != (int64_t)b->len) return -3; + uint64_t m = k.T == 64 ? ~0ull : ((1ull << k.T) - 1); + for (int i = 0; i < n; i++) if (out[i] != (v[i] & m)) return -4; + return 0; +} + +static test_result_t test_write_as_forced(void) { + static uint64_t v[RAY_ENC_VEC]; + ray_enc_buf_t b = {0}; + ray_enc_choice_t c; + /* DELTA_BP at w = T: extremes alternating by lane row (row = i / L). */ + static const int Ts[3] = { 16, 32, 64 }; + for (int t = 0; t < 3; t++) { + int T = Ts[t], L = RAY_ENC_VEC / T; + uint64_t m = T == 64 ? ~0ull : ((1ull << T) - 1); + int64_t hi = T == 16 ? 32767 : T == 32 ? 2147483647ll : INT64_MAX; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(((i / L) & 1) ? hi : -hi) & m; + ray_enc_kind_t k = { (uint8_t)T, true, false }; + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_DELTA_BP, v, RAY_ENC_VEC, k, NULL, &b, &c), 0); + TEST_ASSERT_EQ_I(c.width, T); + TEST_ASSERT_TRUE(ray_enc_choose(v, RAY_ENC_VEC, k, RAY_ENC_SLOT_TOP, 0, NULL).enc != RAY_ENC_DELTA_BP); + } + /* DICT over a constant vector: the codes child is FOR_BP at width 0 (a constant child at depth 1). */ + ray_enc_kind_t k64 = { 64, true, false }; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 900000000001ull; + uint64_t dv[2] = { 11, 900000000001ull }; + ray_enc_dict_t dict = { dv, 2 }; + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_DICT, v, RAY_ENC_VEC, k64, &dict, &b, &c), 0); + TEST_ASSERT_EQ_I(b.p[0], RAY_ENC_FOR_BP); /* codes child header */ + TEST_ASSERT_EQ_I(b.p[1], 0); /* width 0 */ + /* RLE with FOR_BP values (512 runs of two, 16 distinct values). */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 1000 + (uint64_t)((i / 2) % 16); + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_RLE, v, RAY_ENC_VEC, k64, NULL, &b, &c), 0); + TEST_ASSERT_EQ_I(b.p[8], RAY_ENC_FOR_BP); /* values child */ + /* RLE with DELTA_BP ends (1024 runs of one: ends 1..1024, lane step 64). */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)i * 3; + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_RLE, v, RAY_ENC_VEC, k64, NULL, &b, &c), 0); + uint32_t vb; memcpy(&vb, b.p + 12, 4); + TEST_ASSERT_EQ_I(b.p[16 + vb], RAY_ENC_DELTA_BP); /* ends child */ + /* illegal or inapplicable */ + ray_enc_kind_t ku8 = { 8, false, false }; + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_DELTA_BP, v, 16, ku8, NULL, &b, &c), -1); /* unsigned */ + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_CONST, v, 16, k64, NULL, &b, &c), -1); /* unequal */ + TEST_ASSERT_EQ_I(forced_roundtrip(RAY_ENC_DICT, v, 16, k64, &dict, &b, &c), -1); /* not in dict */ + ray_enc_buf_free(&b); + PASS(); +} + +/* n is bounded before the stack arrays are touched; a failed write leaves the + * buffer as it was; bits above T are ignored. */ +static test_result_t test_write_bounds_rollback_masking(void) { + static uint64_t v[RAY_ENC_VEC + 1]; + ray_enc_buf_t b = {0}; + ray_enc_choice_t c; + ray_enc_kind_t k64 = { 64, true, false }; + TEST_ASSERT_TRUE(!ray_enc_write(v, -1, k64, RAY_ENC_SLOT_TOP, 0, NULL, &b, &c)); + TEST_ASSERT_TRUE(!ray_enc_write(v, RAY_ENC_VEC + 1, k64, RAY_ENC_SLOT_TOP, 0, NULL, &b, &c)); + TEST_ASSERT_TRUE(!ray_enc_write_as(RAY_ENC_RAW, v, -1, k64, NULL, &b, &c)); + TEST_ASSERT_TRUE(!ray_enc_write_as(RAY_ENC_RAW, v, RAY_ENC_VEC + 1, k64, NULL, &b, &c)); + TEST_ASSERT_EQ_I(b.len, 0); + /* rollback: a successful write first, then a failing forced write appends nothing */ + for (int i = 0; i < 16; i++) v[i] = (uint64_t)i; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_RAW, v, 16, k64, NULL, &b, &c)); + size_t len0 = b.len; + TEST_ASSERT_TRUE(len0 > 0); + TEST_ASSERT_TRUE(!ray_enc_write_as(RAY_ENC_CONST, v, 16, k64, NULL, &b, &c)); + TEST_ASSERT_EQ_I(b.len, len0); + /* sign-extended I16 input encodes like the masked input */ + ray_enc_kind_t k16 = { 16, true, false }; + uint64_t sx[64], mk[64]; + for (int i = 0; i < 64; i++) { int16_t x = (int16_t)(i * 37 - 1000); sx[i] = (uint64_t)(int64_t)x; mk[i] = (uint64_t)(uint16_t)x; } + ray_enc_buf_t b1 = {0}, b2 = {0}; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_FOR_BP, sx, 64, k16, NULL, &b1, &c)); + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_FOR_BP, mk, 64, k16, NULL, &b2, &c)); + TEST_ASSERT_EQ_I(b1.len, b2.len); + TEST_ASSERT_TRUE(memcmp(b1.p, b2.p, b1.len) == 0); + ray_enc_buf_free(&b1); ray_enc_buf_free(&b2); ray_enc_buf_free(&b); + PASS(); +} + +const test_entry_t enc_entries[] = { + { "enc/pack_roundtrip_all_widths", test_pack_roundtrip_all_widths, enc_setup, enc_teardown }, + { "enc/pack_layout_t8_w1", test_pack_layout_t8_w1, enc_setup, enc_teardown }, + { "enc/pack_layout_t16_w3", test_pack_layout_t16_w3, enc_setup, enc_teardown }, + { "enc/bitlen", test_bitlen, enc_setup, enc_teardown }, + { "enc/kind_of", test_kind_of, enc_setup, enc_teardown }, + { "enc/logical_and_order", test_logical_and_order, enc_setup, enc_teardown }, + { "enc/load_i64_nulls_fill_min", test_load_i64_nulls_fill_min, enc_setup, enc_teardown }, + { "enc/load_all_null_fills_zero", test_load_all_null_fills_zero, enc_setup, enc_teardown }, + { "enc/load_sym_w8_inband", test_load_sym_w8_inband, enc_setup, enc_teardown }, + { "enc/stats_runs_and_equal", test_stats_runs_and_equal, enc_setup, enc_teardown }, + { "enc/load_offset_start", test_load_offset_start, enc_setup, enc_teardown }, + { "enc/sizes_raw_const", test_sizes_raw_const, enc_setup, enc_teardown }, + { "enc/for_width_signed_extremes", test_for_width_signed_extremes, enc_setup, enc_teardown }, + { "enc/for_width_narrow", test_for_width_narrow, enc_setup, enc_teardown }, + { "enc/delta_width_sorted", test_delta_width_sorted, enc_setup, enc_teardown }, + { "enc/choose_const", test_choose_const, enc_setup, enc_teardown }, + { "enc/choose_rle_runs", test_choose_rle_runs, enc_setup, enc_teardown }, + { "enc/choose_for", test_choose_for, enc_setup, enc_teardown }, + { "enc/choose_delta", test_choose_delta, enc_setup, enc_teardown }, + { "enc/keep_raw_when_gain_small", test_keep_raw_when_gain_small, enc_setup, enc_teardown }, + { "enc/dict_wide_sparse_values", test_dict_wide_sparse_values, enc_setup, enc_teardown }, + { "enc/roundtrip_lengths_and_types",test_roundtrip_lengths_and_types,enc_setup, enc_teardown }, + { "enc/i64_extremes_roundtrip", test_i64_extremes_roundtrip, enc_setup, enc_teardown }, + { "enc/dict_codes_rle_nested", test_dict_codes_rle_nested, enc_setup, enc_teardown }, + { "enc/layout_for_partial", test_layout_for_partial, enc_setup, enc_teardown }, + { "enc/layout_delta_partial", test_layout_delta_partial, enc_setup, enc_teardown }, + { "enc/pack_layout_straddle", test_pack_layout_straddle, enc_setup, enc_teardown }, + { "enc/encode_sign_extended", test_encode_sign_extended, enc_setup, enc_teardown }, + { "enc/load_rejects_bad_n", test_load_rejects_bad_n, enc_setup, enc_teardown }, + { "enc/buf_free_clears_oom", test_buf_free_clears_oom, enc_setup, enc_teardown }, + { "enc/train_dict_tristate", test_train_dict_tristate, enc_setup, enc_teardown }, + { "enc/read_rle_under_dict", test_read_rle_under_dict, enc_setup, enc_teardown }, + { "enc/train_dict_native_order", test_train_dict_native_order, enc_setup, enc_teardown }, + { "enc/write_as_forced", test_write_as_forced, enc_setup, enc_teardown }, + { "enc/write_bounds_rollback_masking", test_write_bounds_rollback_masking, enc_setup, enc_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_enc_large.c b/test/test_enc_large.c new file mode 100644 index 000000000..d567aa75c --- /dev/null +++ b/test/test_enc_large.c @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 200809L +#endif + +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "store/col.h" +#include "store/enccol.h" +#include "store/encw.h" +#include "store/stream.h" +#include "store/splay.h" +#include "store/part.h" +#include "store/colrange.h" +#include "ops/colgather.h" +#include "vec/str.h" +#include +#include +#include +#include +#include + +#define LG_TMP "/tmp/rayforce_enc_large" +static void lg_setup(void) { ray_heap_init(); (void)ray_sym_init(); (void)ray_test_mkdir_p(ray_test_tmp(LG_TMP)); } +static void lg_teardown(void) { ray_test_hooks_off(); ray_sym_destroy(); ray_heap_destroy(); (void)ray_test_rm_rf(ray_test_tmp(LG_TMP)); } + +/* 65535 descriptors sharing one pooled range of the source (a 65538-byte + * pool): the source stays small, while the decoded compact pool counts each + * occurrence (spec "STR pool", rule 2). 65535 * 65537 = UINT32_MAX exactly; + * a last row of 65538 bytes makes it one byte more. The chunk (descriptors + * plus per-vector pools) exceeds 4 GiB, so `u64` sizes are exercised too. */ +static ray_t* shared_str(uint32_t last_len) { + ray_t* v = ray_vec_new(RAY_STR, 65535); + if (!v || RAY_IS_ERR(v)) return v; + v->len = 65535; + ray_t* pool = ray_alloc(65538); + if (!pool || RAY_IS_ERR(pool)) { ray_release(v); return pool; } + pool->type = RAY_U8; pool->len = 65538; + memset(ray_data(pool), 'q', 65538); + v->str_pool = pool; + ray_str_t* d = ray_data(v); + for (int i = 0; i < 65535; i++) { + memset(&d[i], 0, sizeof d[i]); + d[i].len = i == 65534 ? last_len : 65537; + memcpy(d[i].prefix, "qqqq", 4); + d[i].pool_off = 0; + } + return v; +} + +static test_result_t test_pool_exact_limit(void) { + ray_t* v = shared_str(65537); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + /* P6: the RAW per-occurrence pool at its limit is this test's subject + * (selection takes STR_DICT, whose pool holds the entry once) */ + ray_encw_test_force(RAY_ENC_RAW); + ray_err_t se = ray_col_save_bulk_gen(v, ray_test_tmp(LG_TMP "/ok"), 2); + ray_encw_test_force(-1); + ray_release(v); + TEST_ASSERT_EQ_I(se, RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(LG_TMP "/ok")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_EQ_U(ray_enccol_of(c)->hdr.str_pool_bytes, UINT32_MAX); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(m->str_pool->len, (int64_t)UINT32_MAX); + ray_release(c); + PASS(); +} + +static test_result_t test_pool_one_byte_over(void) { + ray_t* v = shared_str(65538); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + TEST_ASSERT_EQ_I(ray_col_save_bulk_gen(v, ray_test_tmp(LG_TMP "/over"), 2), RAY_ERR_RANGE); + ray_release(v); + TEST_ASSERT_TRUE(access(ray_test_tmp(LG_TMP "/over"), F_OK) != 0); + TEST_ASSERT_TRUE(access(ray_test_tmp(LG_TMP "/over.tmp"), F_OK) != 0); + PASS(); +} + +/* Streamed: the same shared-range vector in one append; the generation-2 + * stream counts the decoded pool per occurrence and fails with range at + * the crossing (the last) row; abort removes every staging file. */ +static test_result_t test_stream_crossing_last_row(void) { + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(LG_TMP), ray_sym_intern("st", 2), RAY_STR, NULL, 2), RAY_OK); + ray_t* v = shared_str(65538); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, v), RAY_ERR_RANGE); + ray_release(v); + ray_col_stream_abort(&w); + TEST_ASSERT_TRUE(access(ray_test_tmp(LG_TMP "/.stream-st.col"), F_OK) != 0); + TEST_ASSERT_TRUE(access(ray_test_tmp(LG_TMP "/.stream-st.pool"), F_OK) != 0); + PASS(); +} + +/* A row-list gather whose result pool would cross UINT32_MAX fails with + * `range` and frees its partial result (allocator accounting at baseline). + * Two generation-2 partitions of 2100 strings of 1 MiB each (2.05 GiB of + * pool per partition, within one column's limit; 4.1 GiB gathered). */ +static test_result_t test_gather_pool_range(void) { + static char big[1 << 20]; memset(big, 'q', sizeof big); + for (int p = 0; p < 2; p++) { + ray_t* v = ray_vec_new(RAY_STR, 0); + for (int i = 0; i < 2100; i++) { big[0] = (char)('a' + i % 26); v = ray_str_vec_append(v, big, sizeof big); } + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("s", 1), v); ray_release(v); + char dir[256]; snprintf(dir, sizeof dir, LG_TMP "/gp/2024.01.0%d/t", p + 1); + char symp[256]; snprintf(symp, sizeof symp, "%s", ray_test_tmp(LG_TMP "/gp/.sym")); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, ray_test_tmp(dir), symp, RAY_COMPRESS_ON), RAY_OK); + ray_release(t); + } + ray_t* t = ray_read_parted(ray_test_tmp(LG_TMP "/gp"), "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("s", 1), &s)); + static int64_t ids[4200]; /* static: no leak on an assertion */ + for (int i = 0; i < 4200; i++) ids[i] = i; + /* the source publishes its segment offsets on its first read (owned by + * the source, freed at its release): one row first, so the baseline + * holds them. P6: each partition's validated STR_DICT dictionary is a + * once-state its column keeps (a cache): one row of each partition */ + ray_t* out = NULL; + static const int64_t warm[2] = { 0, 2100 }; + TEST_ASSERT_NULL(ray_col_gather_rows(&s, warm, 2, &out)); + ray_release(out); out = NULL; + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + ray_t* e = ray_col_gather_rows(&s, ids, 4200, &out); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_STR_EQ(ray_err_code(e), "range"); + TEST_ASSERT_NULL(out); + ray_error_free(e); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + ray_col_src_release(&s); ray_release(t); + PASS(); +} + +/* A STR_DICT column whose per-occurrence pool is exactly UINT32_MAX saves + * (the generation-0 bound, Decisions: the writer keeps it for every + * encoding) and materializes with a dictionary region of two entries; one + * byte more fails with `range` under STR_DICT too (P1's range test keeps + * selection). */ +static test_result_t test_str_dict_pool_limit(void) { + const int64_t n = 65537; /* 65537 x 65535 = UINT32_MAX */ + char* a = malloc(65535); char* b2 = malloc(65535); + TEST_ASSERT_TRUE(a && b2); + memset(a, 'a', 65535); memset(b2, 'b', 65535); + ray_t* v = ray_vec_new(RAY_STR, n); + for (int64_t i = 0; i < n; i++) v = ray_str_vec_append(v, (i & 1) ? a : b2, 65535); + free(a); free(b2); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v) && v->len == n); + TEST_ASSERT_EQ_U((uint64_t)v->str_pool->len, UINT32_MAX); + ray_encw_test_force(RAY_ENC_STR_DICT); + ray_err_t e = ray_col_save_bulk_gen(v, ray_test_tmp(LG_TMP "/sd"), 2); + ray_encw_test_force(-1); + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(LG_TMP "/sd")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_EQ_U(ray_enccol_of(c)->hdr.str_pool_bytes, 2u * 65535u); + const ray_enc_sdict_t* sd = NULL; + TEST_ASSERT_NULL(ray_enccol_strdict(ray_enccol_of(c), &sd)); + TEST_ASSERT_TRUE(sd != NULL && sd->n == 2); /* the dictionary region holds two entries */ + ray_t* m = ray_enccol_materialize(c); /* borrowed: the column's cache */ + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && m->len == n); + TEST_ASSERT_EQ_I(m->str_pool->len, 2 * 65535); + size_t l; const char* p = ray_str_vec_get(m, n - 1, &l); + TEST_ASSERT_TRUE(l == 65535 && p[0] == 'b' && p[65534] == 'b'); + p = ray_str_vec_get(m, n - 2, &l); + TEST_ASSERT_TRUE(l == 65535 && p[0] == 'a' && p[65534] == 'a'); + ray_release(c); + (void)remove(ray_test_tmp(LG_TMP "/sd")); + /* one byte more, forced STR_DICT: shared_str's 65534 descriptors of + * 65537 bytes and a last of 65538 (one pooled range shared by all, so + * the decoded pool is UINT32_MAX + 1 bytes per occurrence) */ + v = shared_str(65538); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + ray_encw_test_force(RAY_ENC_STR_DICT); + e = ray_col_save_bulk_gen(v, ray_test_tmp(LG_TMP "/sd1"), 2); + ray_encw_test_force(-1); + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_ERR_RANGE); + TEST_ASSERT_TRUE(access(ray_test_tmp(LG_TMP "/sd1"), F_OK) != 0); + TEST_ASSERT_TRUE(access(ray_test_tmp(LG_TMP "/sd1.tmp"), F_OK) != 0); + PASS(); +} + +const test_entry_t large_entries[] = { + { "large/pool_exact_limit", test_pool_exact_limit, lg_setup, lg_teardown }, + { "large/pool_one_byte_over", test_pool_one_byte_over, lg_setup, lg_teardown }, + { "large/stream_crossing_last_row", test_stream_crossing_last_row, lg_setup, lg_teardown }, + { "large/gather_pool_range", test_gather_pool_range, lg_setup, lg_teardown }, + { "large/str_dict_pool_limit", test_str_dict_pool_limit, lg_setup, lg_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_enc_once.c b/test/test_enc_once.c new file mode 100644 index 000000000..f6ea9b332 --- /dev/null +++ b/test/test_enc_once.c @@ -0,0 +1,349 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) +# define _POSIX_C_SOURCE 200809L +#endif +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "core/platform.h" +#include "core/runtime.h" +#include "store/enc_once.h" +#include +#include +#include + +static void once_setup(void) { ray_heap_init(); (void)ray_sym_init(); } +static void once_teardown(void) { ray_sym_destroy(); ray_heap_destroy(); } + +typedef struct { + ray_enc_once_t once; + ray_t* slot; + _Atomic(int) calls; + int mode; /* 0 succeed, 1 transient until waiters, 2 deterministic */ + uint32_t want_waiters; +} once_ctx_t; + +static ray_t* once_fn(void* raw, ray_enc_snap_t* fail) { + once_ctx_t* c = raw; + int n = atomic_fetch_add(&c->calls, 1) + 1; + if (c->mode == 1 && n == 1) { + /* Hold the attempt until every other thread is waiting on it. */ + for (int spin = 0; spin < 50000000 && + ray_enc_once_waiters(&c->once) < c->want_waiters; spin++) + ray_enc_yield(); + ray_enc_snap_set(fail, "oom", "attempt %d failed", n); + return NULL; + } + if (c->mode == 6) { /* hold, then fail deterministically */ + for (int spin = 0; spin < 50000000 && + ray_enc_once_waiters(&c->once) < c->want_waiters; spin++) + ray_enc_yield(); + ray_enc_snap_set(fail, "corrupt", "held attempt %d", n); + return NULL; + } + if (c->mode == 9 && n == 1) return ray_error("fpenv", NULL); + if (c->mode == 3) return ray_error("corrupt", "returned error object"); + if (c->mode == 4) return NULL; /* NULL with an empty fail */ + if (c->mode == 8) { ray_enc_snap_set(fail, "cancel", "cancelled %d", n); return NULL; } + if (c->mode == 2) { + ray_t* e = ray_error("corrupt", "column /x: bad descriptor (chunk 3)"); + ray_enc_snap_take(fail, e); + return NULL; + } + int64_t v = 7; + return ray_vec_from_raw(RAY_I64, &v, 1); +} + +typedef struct { once_ctx_t* c; ray_t* got; char code[8]; char msg[256]; } once_thr_t; + +static void once_thread(void* raw) { + once_thr_t* t = raw; + ray_t* r = ray_enc_once_get(&t->c->once, &t->c->slot, once_fn, t->c); + t->got = r; + if (r && RAY_IS_ERR(r)) { + snprintf(t->code, sizeof t->code, "%s", ray_err_code(r)); + snprintf(t->msg, sizeof t->msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + ray_error_free(r); + t->got = NULL; + } + ray_heap_abandon(); +} + +static test_result_t test_once_success_shared(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + once_thr_t t[8]; ray_thread_t th[8]; + for (int i = 0; i < 8; i++) { memset(&t[i], 0, sizeof t[i]); t[i].c = &c; + TEST_ASSERT_EQ_I(ray_thread_create(&th[i], once_thread, &t[i]), RAY_OK); } + for (int i = 0; i < 8; i++) ray_thread_join(th[i]); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + for (int i = 0; i < 8; i++) TEST_ASSERT_EQ_PTR(t[i].got, c.slot); + ray_release(c.slot); + PASS(); +} + +static test_result_t test_once_many_waiters_transient(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 1; c.want_waiters = 7; + once_thr_t t[8]; ray_thread_t th[8]; + for (int i = 0; i < 8; i++) { memset(&t[i], 0, sizeof t[i]); t[i].c = &c; + TEST_ASSERT_EQ_I(ray_thread_create(&th[i], once_thread, &t[i]), RAY_OK); } + for (int i = 0; i < 8; i++) ray_thread_join(th[i]); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + for (int i = 0; i < 8; i++) { + TEST_ASSERT_FMT(strcmp(t[i].code, "oom") == 0, "thread %d code %s", i, t[i].code); + TEST_ASSERT_FMT(strcmp(t[i].msg, "attempt 1 failed") == 0, "thread %d msg %s", i, t[i].msg); + } + /* The state reset: the next caller retries and succeeds. */ + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 2); + ray_release(c.slot); + PASS(); +} + +static test_result_t test_once_deterministic_cached(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 2; + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + for (int i = 0; i < 5; i++) { + ray_error_clear(); + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "corrupt"); + TEST_ASSERT_STR_EQ(ray_error_msg(), "column /x: bad descriptor (chunk 3)"); + ray_error_free(r); + } + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); /* no leaked error objects */ + PASS(); +} + +static test_result_t test_once_transient_codes(void) { + TEST_ASSERT_TRUE(ray_enc_code_transient("oom")); + TEST_ASSERT_TRUE(ray_enc_code_transient("cancel")); + TEST_ASSERT_TRUE(ray_enc_code_transient("fpenv")); + TEST_ASSERT_FALSE(ray_enc_code_transient("corrupt")); + TEST_ASSERT_FALSE(ray_enc_code_transient("nyi")); + ray_enc_snap_t s; + ray_enc_snap_take(&s, RAY_OOM_OBJ); /* the static sentinel is safe */ + TEST_ASSERT_STR_EQ(s.code, "oom"); + TEST_ASSERT_TRUE(s.is_transient); + PASS(); +} + +static test_result_t test_once_draining_blocks_new_attempt(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + ray_enc_snap_t x; ray_enc_snap_set(&x, "oom", "X-msg"); + ray_enc_once_test_drain(&c.once, &x, 1); + once_thr_t t; memset(&t, 0, sizeof t); t.c = &c; + ray_thread_t th; + TEST_ASSERT_EQ_I(ray_thread_create(&th, once_thread, &t), RAY_OK); + /* Bounded observation: while a waiter is outstanding the caller must not + * run fn nor overwrite the snapshot. */ + struct timespec ts = { 0, 1000000 }; + for (int i = 0; i < 200; i++) { + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 0); + TEST_ASSERT_EQ_U(ray_enc_once_waiters(&c.once), 1); + nanosleep(&ts, NULL); + } + TEST_ASSERT_STR_EQ(c.once.snap.code, "oom"); + TEST_ASSERT_STR_EQ(c.once.snap.msg, "X-msg"); + ray_enc_snap_t got; + ray_enc_once_test_waiter_done(&c.once, &got); + ray_thread_join(th); + TEST_ASSERT_STR_EQ(got.code, "oom"); + TEST_ASSERT_STR_EQ(got.msg, "X-msg"); + TEST_ASSERT_TRUE(got.is_transient); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + TEST_ASSERT_TRUE(t.got != NULL && t.got == c.slot); + ray_release(c.slot); + PASS(); +} + +static test_result_t test_once_waiters_get_deterministic(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 6; c.want_waiters = 7; + once_thr_t t[8]; ray_thread_t th[8]; + for (int i = 0; i < 8; i++) { memset(&t[i], 0, sizeof t[i]); t[i].c = &c; + TEST_ASSERT_EQ_I(ray_thread_create(&th[i], once_thread, &t[i]), RAY_OK); } + for (int i = 0; i < 8; i++) ray_thread_join(th[i]); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + for (int i = 0; i < 8; i++) { + TEST_ASSERT_STR_EQ(t[i].code, "corrupt"); + TEST_ASSERT_STR_EQ(t[i].msg, "held attempt 1"); + } + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); /* still cached */ + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + ray_error_free(r); + PASS(); +} + +static test_result_t test_once_error_object_returned(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 3; + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + for (int i = 0; i < 3; i++) { + ray_error_clear(); + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "corrupt"); + TEST_ASSERT_STR_EQ(ray_error_msg(), "returned error object"); + ray_error_free(r); + } + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + PASS(); +} + +static test_result_t test_once_null_without_snapshot(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 4; + for (int i = 0; i < 3; i++) { + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "error"); + ray_error_free(r); + } + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 1); /* cached as deterministic */ + PASS(); +} + +static test_result_t test_once_transient_no_waiters_retries(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 1; c.want_waiters = 0; + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "oom"); + ray_error_free(r); + TEST_ASSERT_EQ_U(atomic_load(&c.once.state), RAY_ENC_ONCE_IDLE); + r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 2); + ray_release(c.slot); + PASS(); +} + +static test_result_t test_once_transient_no_leak(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 8; /* always cancel */ + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + for (int i = 0; i < 20; i++) { + ray_error_clear(); + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "cancel"); + ray_error_free(r); + } + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 20); + c.mode = 0; + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(c.slot); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + PASS(); +} + +/* Exercise the actual error-object -> snapshot -> error-object path, as + * used when a decoding worker rejects its own FP controls. No FP state is + * changed here: this tests classification/retry, not platform detection. */ +static test_result_t test_once_fpenv_retries(void) { + once_ctx_t c; memset(&c, 0, sizeof c); ray_enc_once_init(&c.once); + c.mode = 9; + ray_t* r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "fpenv"); + TEST_ASSERT_EQ_I(ray_err_from_obj(r), RAY_ERR_FPENV); + TEST_ASSERT_TRUE(ray_error_msg() && strstr(ray_error_msg(), "FE_TONEAREST")); + ray_error_free(r); + TEST_ASSERT_EQ_U(atomic_load(&c.once.state), RAY_ENC_ONCE_IDLE); + TEST_ASSERT_TRUE(c.slot == NULL); + r = ray_enc_once_get(&c.once, &c.slot, once_fn, &c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_PTR(r, c.slot); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 2); + TEST_ASSERT_EQ_U(atomic_load(&c.once.state), RAY_ENC_ONCE_DONE); + TEST_ASSERT_EQ_PTR(ray_enc_once_get(&c.once, &c.slot, once_fn, &c), r); + TEST_ASSERT_EQ_I(atomic_load(&c.calls), 2); + ray_release(c.slot); + PASS(); +} + +static test_result_t test_once_fpenv_snapshot(void) { + TEST_ASSERT_STR_EQ(ray_err_code_str(RAY_ERR_FPENV), "fpenv"); + ray_enc_snap_t s; + ray_enc_snap_set(&s, "fpenv", "worker %d controls unsupported", 3); + TEST_ASSERT_TRUE(s.is_transient); + ray_t* e = ray_enc_snap_error(&s); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_EQ_I(ray_err_from_obj(e), RAY_ERR_FPENV); + TEST_ASSERT_STR_EQ(ray_error_msg(), "worker 3 controls unsupported"); + ray_enc_snap_take(&s, e); + TEST_ASSERT_TRUE(s.is_transient); + TEST_ASSERT_STR_EQ(s.code, "fpenv"); + TEST_ASSERT_STR_EQ(s.msg, "worker 3 controls unsupported"); + + /* Enum-only save conversions must not lose the explanation. */ + e = ray_error(ray_err_code_str(RAY_ERR_FPENV), NULL); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_TRUE(ray_error_msg() && strstr(ray_error_msg(), "FE_TONEAREST")); + TEST_ASSERT_TRUE(strstr(ray_error_msg(), "masked exceptions") != NULL); + TEST_ASSERT_TRUE(strstr(ray_error_msg(), "no FTZ/DAZ") != NULL); + ray_enc_snap_take(&s, e); + TEST_ASSERT_TRUE(s.is_transient); + TEST_ASSERT_STR_EQ(s.code, "fpenv"); + TEST_ASSERT_TRUE(strstr(s.msg, "FE_TONEAREST") != NULL); + e = ray_enc_snap_error(&s); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_EQ_I(ray_err_from_obj(e), RAY_ERR_FPENV); + TEST_ASSERT_STR_EQ(ray_error_msg(), s.msg); + ray_error_free(e); + + /* Other constructors retain their NULL-format clearing behavior. */ + e = ray_error("domain", NULL); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_TRUE(ray_error_msg() == NULL); + ray_error_free(e); + PASS(); +} + +const test_entry_t enconce_entries[] = { + { "enconce/success_shared", test_once_success_shared, once_setup, once_teardown }, + { "enconce/many_waiters_transient",test_once_many_waiters_transient,once_setup, once_teardown }, + { "enconce/deterministic_cached", test_once_deterministic_cached, once_setup, once_teardown }, + { "enconce/transient_codes", test_once_transient_codes, once_setup, once_teardown }, + { "enconce/draining_blocks_new_attempt", test_once_draining_blocks_new_attempt, once_setup, once_teardown }, + { "enconce/waiters_get_deterministic", test_once_waiters_get_deterministic, once_setup, once_teardown }, + { "enconce/error_object_returned", test_once_error_object_returned, once_setup, once_teardown }, + { "enconce/null_without_snapshot", test_once_null_without_snapshot, once_setup, once_teardown }, + { "enconce/transient_no_waiters_retries", test_once_transient_no_waiters_retries, once_setup, once_teardown }, + { "enconce/transient_no_leak", test_once_transient_no_leak, once_setup, once_teardown }, + { "enconce/fpenv_retries", test_once_fpenv_retries, once_setup, once_teardown }, + { "enconce/fpenv_snapshot", test_once_fpenv_snapshot, once_setup, once_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_enccol.c b/test/test_enccol.c new file mode 100644 index 000000000..83583fe99 --- /dev/null +++ b/test/test_enccol.c @@ -0,0 +1,2519 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#define _POSIX_C_SOURCE 200809L +#include "test.h" +#include +#include "mem/heap.h" +#include "ops/ops.h" +#include "table/sym.h" +#include "core/runtime.h" +#include "store/col.h" +#include "store/encfmt.h" +#include "store/enc.h" +#include "store/enccol.h" +#include "vec/str.h" +#include "store/splay.h" +#include "store/csr.h" +#include "table/domain.h" +#include "table/table.h" +#include "ops/idxop.h" +#include "store/encw.h" +#include "store/part.h" +#include "store/colrange.h" +#include "core/block.h" +#include "lang/format.h" +#include "lang/eval.h" +#include "ops/colgather.h" /* ray_col_gather_span */ +#include "ops/cdfuse.h" /* ray_cd_bounded, ray_cd_bounded_all */ +#include +#include +#include +#include +#include + +#define ENCCOL_TMP "/tmp/rayforce_enccol" + +/* 256 interned symbols, so SYM test ids up to 255 lie inside the runtime domain. */ +static void enccol_setup(void) { + ray_heap_init(); (void)ray_sym_init(); (void)ray_test_mkdir_p(ray_test_tmp(ENCCOL_TMP)); + for (int i = 0; i < 256; i++) { char b[8]; int n = snprintf(b, sizeof b, "s%d", i); (void)ray_sym_intern(b, (size_t)n); } +} +static void enccol_teardown(void) { ray_test_hooks_off(); ray_sym_destroy(); ray_heap_destroy(); (void)ray_test_rm_rf(ray_test_tmp(ENCCOL_TMP)); } + +static ray_err_t save_i32_rows(const char* path, int64_t n) { + ray_t* v = ray_vec_new(RAY_I32, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int32_t*)ray_data(v))[i] = (int32_t)(i % 977); + ray_err_t e = ray_col_save_gen(v, path, 2); + ray_release(v); + return e; +} + +/* Patch `n` bytes at file offset `off`. */ +static void patch(const char* path, long off, const void* b, size_t n) { + FILE* f = fopen(path, "r+b"); + if (!f) ray_test_fatal("cannot open %s", path); + fseek(f, off, SEEK_SET); fwrite(b, 1, n, f); fclose(f); +} + +static ray_t* mmap_expect_err(const char* path, const char* code) { + ray_t* r = ray_col_mmap(path); + if (!r || !RAY_IS_ERR(r)) { if (r) ray_release(r); return ray_error("fail", "loaded"); } + if (strcmp(ray_err_code(r), code) != 0) { ray_error_free(r); return ray_error("fail", "code"); } + ray_error_free(r); + return NULL; +} + +static test_result_t test_open_returns_enccol(void) { + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + TEST_ASSERT_EQ_I(save_i32_rows(ray_test_tmp(ENCCOL_TMP "/a"), 70000), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/a")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_EQ_I(c->type, RAY_ENCCOL); + TEST_ASSERT_EQ_I(c->len, 70000); + TEST_ASSERT_EQ_I(c->attrs, 0); + ray_enccol_t* e = ray_enccol_of(c); + TEST_ASSERT_EQ_I(e->kind, RAY_ENCCOL_SINGLE); + TEST_ASSERT_EQ_I(e->type, RAY_I32); + TEST_ASSERT_EQ_I(e->n_chunks, 2); + TEST_ASSERT_EQ_I(e->null_count, 0); + ray_t* copy = ray_alloc_copy(c); /* header copy shares the payload */ + TEST_ASSERT_TRUE(copy && !RAY_IS_ERR(copy)); + TEST_ASSERT_EQ_PTR(ray_enccol_of(copy), e); + TEST_ASSERT_EQ_I(atomic_load(&e->rc), 2); + ray_release(copy); + ray_release(c); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.sys_mapped, m0.sys_mapped); /* mapping released */ + PASS(); +} + +/* A header version this build does not read: `version` (the version + * selects the reader). */ +static test_result_t test_load_version(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/r"); + uint8_t two = 2; + TEST_ASSERT_EQ_I(save_i32_rows(p, 3000), RAY_OK); + patch(p, 32 + 4, &two, 1); + TEST_ASSERT_NULL(mmap_expect_err(p, "version")); + PASS(); +} + +/* Appending a generation-0 index region would stamp "XIDX" over "XENC" + * and produce (order 2, "XIDX"), a file that no longer loads. */ +static test_result_t test_append_index_refuses_gen2(void) { + TEST_ASSERT_EQ_I(save_i32_rows(ray_test_tmp(ENCCOL_TMP "/ai"), 3000), RAY_OK); + ray_t* v = ray_vec_new(RAY_I32, 3000); v->len = 3000; + for (int64_t i = 0; i < 3000; i++) ((int32_t*)ray_data(v))[i] = (int32_t)(i % 977); + ray_t* z = ray_index_chunk_zone_compute(v, 8); + TEST_ASSERT_TRUE(z && !RAY_IS_ERR(z)); + TEST_ASSERT_EQ_I(ray_col_append_index(ray_test_tmp(ENCCOL_TMP "/ai"), ray_index_payload(z), 3000, RAY_I32), RAY_ERR_VERSION); + ray_release(z); ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/ai")); /* still loads */ + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_release(c); + PASS(); +} + +static test_result_t test_sym_requires_domain(void) { + uint8_t ids[16]; + for (int i = 0; i < 16; i++) ids[i] = (uint8_t)(i % 4); + ray_t* v = ray_sym_vec_new(RAY_SYM_W8, 16); + v->len = 16; memcpy(ray_data(v), ids, 16); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/s"), 2), RAY_OK); + ray_release(v); + ray_t* r = ray_col_mmap_splayed_dom(ray_test_tmp(ENCCOL_TMP "/s"), NULL); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "sym"); + ray_error_free(r); + PASS(); +} + +/* ray_col_load (non-mmap) on generation 2 returns the plain vector and + * leaves nothing mapped behind once it is released. */ +static test_result_t test_load_gen2_plain(void) { + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + TEST_ASSERT_EQ_I(save_i32_rows(ray_test_tmp(ENCCOL_TMP "/ln"), 3000), RAY_OK); + ray_t* r = ray_col_load(ray_test_tmp(ENCCOL_TMP "/ln")); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->type, RAY_I32); + TEST_ASSERT_EQ_I(r->len, 3000); + ray_release(r); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.sys_mapped, m0.sys_mapped); + PASS(); +} + +/* A valid open, then a refused one (a header version this build does not + * read), leave no mapping. */ +static test_result_t test_no_mapping_leak(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/lk"); + uint8_t two = 2; + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + TEST_ASSERT_EQ_I(save_i32_rows(p, 3000), RAY_OK); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_release(c); + { + TEST_ASSERT_EQ_I(save_i32_rows(p, 3000), RAY_OK); + patch(p, 32 + 4, &two, 1); /* version */ + ray_t* r = ray_col_mmap(p); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + ray_error_free(r); + } + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.sys_mapped, m0.sys_mapped); + PASS(); +} + +/* A truncated file (a partial copy, a full disk elsewhere) fails whole at + * open, `corrupt`, naming the file, at any cut: inside the headers, the + * directory, a chunk or the side data; and leaves nothing mapped. */ +static const int64_t g_tr_dv[4] = { 5, 700000000003ll, 91, 98765432109876ll }; +static test_result_t test_truncated_fails_whole(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/tr"); + int64_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = g_tr_dv[(uint32_t)((uint32_t)i * 2654435761u) >> 30]; + ray_t* v = ray_vec_from_raw(RAY_I64, d, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_TRUE(ray_enccol_of(c)->vdict_off != 0); /* side data: the last section */ + long full = (long)ray_enccol_of(c)->size; + ray_release(c); + const long cuts[] = { 40, (long)RAY_ENC_DIR_OFF + 4, full / 2, full - 8, full - 1 }; + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + for (size_t k = 0; k < sizeof cuts / sizeof cuts[0]; k++) { + v = ray_vec_from_raw(RAY_I64, d, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_release(v); + TEST_ASSERT_EQ_I(truncate(p, cuts[k]), 0); + ray_t* r = ray_col_mmap(p); + if (!r || !RAY_IS_ERR(r)) { + if (r) ray_release(r); + FAILF("cut at %ld of %ld: opened", cuts[k], full); + } + const char* msg = ray_error_msg(); + if (strcmp(ray_err_code(r), "corrupt") != 0 || !msg || !strstr(msg, p)) { + char got[512]; + snprintf(got, sizeof got, "%s: %s", ray_err_code(r), msg ? msg : "(no message)"); + ray_error_free(r); + FAILF("cut at %ld of %ld: %s", cuts[k], full, got); + } + ray_error_free(r); + } + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.sys_mapped, m0.sys_mapped); + PASS(); +} + +/* The big-endian gate (generation 2 answers nyi there, not corrupt) cannot + * be exercised end to end on a little-endian host: ray_enccol_open's + * `!ray_enc_gen2_supported()` branch is never taken (the build with + * -U__BYTE_ORDER__ checks that it compiles). What is testable here: the + * discriminator recognises "XENC" bytewise, so on any host a generation-2 file reaches ray_enccol_open + * instead of being rejected as corrupt before the gate. */ +static test_result_t test_be_gate_logic(void) { + uint8_t h[32] = {0}; + memcpy(h, "XENC", 4); h[17] = RAY_ENC_GEN; + TEST_ASSERT_EQ_I(ray_col_gen_of(h), 2); + memcpy(h, "CNEX", 4); /* byte-reversed marker is not XENC */ + TEST_ASSERT_EQ_I(ray_col_gen_of(h), RAY_ENC_GEN_CORRUPT); + PASS(); +} + +/* ---- fix round 1 ---- */ + +#define LEN_OFF ((long)offsetof(ray_t, len)) +#define MMOD_OFF ((long)offsetof(ray_t, mmod)) +#define RC_OFF ((long)offsetof(ray_t, rc)) + +/* Real writer output with a VALUE_DICT side entry loads. */ +static const int64_t g_dv[4] = { 11, 900000000001ll, 77, 123456789012345ll }; +static test_result_t test_value_dict_side(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/vd"); + int64_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = g_dv[(uint32_t)((uint32_t)i * 2654435761u) >> 30]; + ray_t* v = ray_vec_from_raw(RAY_I64, d, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_t* e = ray_enccol_of(c); + TEST_ASSERT_TRUE(e->vdict_off != 0); + TEST_ASSERT_EQ_U(e->vdict_off % 32, 0); + ray_release(c); + PASS(); +} + +/* SYM with a domain: the saved-count rule (the symfile the caller names + * must hold every id the column was saved over). */ +static ray_t* sym_col_save(const char* p) { + ray_t* v = ray_sym_vec_new(RAY_SYM_W8, 16); + v->len = 16; + for (int i = 0; i < 16; i++) ((uint8_t*)ray_data(v))[i] = (uint8_t)((i % 4) + 1); + ray_err_t e = ray_col_save_gen(v, p, 2); + ray_release(v); + return e == RAY_OK ? NULL : ray_error("fail", "save"); +} +static test_result_t test_sym_domain_rules(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/sd"); + ray_sym_domain_t* dom = ray_sym_runtime_domain(); + TEST_ASSERT_NULL(sym_col_save(p)); + ray_t* c = ray_col_mmap_splayed_dom(p, dom); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->type, RAY_SYM); + ray_release(c); + /* saved count above the domain's */ + uint32_t big = 1000000; patch(p, RC_OFF, &big, 4); + ray_t* r = ray_col_mmap_splayed_dom(p, dom); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "corrupt"); + ray_error_free(r); + PASS(); +} + +static bool csr_col_equal(const ray_t* a, const ray_t* b) { + if (!a || !b) return a == b; + return a->type == b->type && a->len == b->len && memcmp(ray_data((ray_t*)a), ray_data((ray_t*)b), (size_t)a->len * 8) == 0; +} +static bool csr_equal(const ray_csr_t* a, const ray_csr_t* b) { + return csr_col_equal(a->offsets, b->offsets) && csr_col_equal(a->targets, b->targets) && + csr_col_equal(a->rowmap, b->rowmap) && a->n_nodes == b->n_nodes && a->n_edges == b->n_edges; +} + +/* The mapping loader refuses an encoded column; the copying loader materializes it. */ +static test_result_t test_consumers_refuse(void) { + /* (a) a complete generation-0 relation maps; one file rewritten as + * generation 2 (required or optional) makes the map fail */ + { + int64_t sd[] = {0, 0, 1, 1, 2, 3}, dd[] = {1, 2, 2, 3, 3, 0}; + ray_t* sv = ray_vec_from_raw(RAY_I64, sd, 6); ray_t* dv = ray_vec_from_raw(RAY_I64, dd, 6); + ray_t* et = ray_table_new(2); + et = ray_table_add_col(et, ray_sym_intern("src", 3), sv); + et = ray_table_add_col(et, ray_sym_intern("dst", 3), dv); + ray_release(sv); ray_release(dv); + ray_rel_t* rel = ray_rel_from_edges(et, "src", "dst", 4, 4, true); + TEST_ASSERT_TRUE(rel != NULL); + const char* rd = ray_test_tmp(ENCCOL_TMP "/rel"); + TEST_ASSERT_EQ_I(ray_rel_save(rel, rd), RAY_OK); + ray_rel_free(rel); ray_release(et); + int64_t md[5] = {0, 1, 2, 0, 1}; /* plain meta, whatever the saver wrote */ + ray_t* mv = ray_vec_from_raw(RAY_I64, md, 5); + TEST_ASSERT_EQ_I(ray_col_save(mv, ray_test_tmp(ENCCOL_TMP "/rel/meta")), RAY_OK); + ray_release(mv); + ray_rel_t* base = ray_rel_load(rd); /* the generation-0 load */ + TEST_ASSERT_TRUE(base != NULL); + ray_rel_t* good = ray_rel_mmap(rd); + TEST_ASSERT_TRUE(good != NULL); + TEST_ASSERT_TRUE(good->fwd.rowmap != NULL); /* the optional file is really there */ + ray_rel_free(good); + static const char* files[] = { "fwd_offsets", "fwd_targets", "rev_offsets", "rev_targets", + "fwd_rowmap", "rev_rowmap", "meta" }; + for (size_t i = 0; i < sizeof files / sizeof *files; i++) { + char fp[256], bak[260]; + snprintf(fp, sizeof fp, "%s/%s", rd, files[i]); + snprintf(bak, sizeof bak, "%s.bak", fp); + TEST_ASSERT_EQ_I(rename(fp, bak), 0); + ray_t* orig = ray_col_load(bak); /* the original column, rewritten as generation 2 */ + TEST_ASSERT_TRUE(orig && !RAY_IS_ERR(orig)); + TEST_ASSERT_EQ_I(ray_col_save_gen(orig, fp, 2), RAY_OK); + ray_release(orig); + TEST_ASSERT_NULL(ray_rel_mmap(rd)); /* mapping refuses an encoded column */ + ray_rel_t* copied = ray_rel_load(rd); /* the copying loader materializes it */ + TEST_ASSERT_TRUE(copied != NULL); + TEST_ASSERT_TRUE(csr_equal(&copied->fwd, &base->fwd) && csr_equal(&copied->rev, &base->rev)); + ray_rel_free(copied); + TEST_ASSERT_EQ_I(rename(bak, fp), 0); + ray_rel_t* again = ray_rel_mmap(rd); + TEST_ASSERT_TRUE(again != NULL); + ray_rel_free(again); + } + ray_rel_free(base); + } + /* (c) splayed table load: one plain column, one generation-2 file */ + ray_t* tbl = ray_table_new(2); + ray_t* a = ray_vec_new(RAY_I64, 3000); a->len = 3000; + ray_t* b = ray_vec_new(RAY_I32, 3000); b->len = 3000; + for (int i = 0; i < 3000; i++) { ((int64_t*)ray_data(a))[i] = i; ((int32_t*)ray_data(b))[i] = i % 977; } + tbl = ray_table_add_col(tbl, ray_sym_intern("ca", 2), a); + tbl = ray_table_add_col(tbl, ray_sym_intern("cb", 2), b); + ray_release(a); ray_release(b); + TEST_ASSERT_EQ_I(ray_splay_save(tbl, ray_test_tmp(ENCCOL_TMP "/tb"), NULL), RAY_OK); + ray_release(tbl); + TEST_ASSERT_EQ_I(save_i32_rows(ray_test_tmp(ENCCOL_TMP "/tb/cb"), 3000), RAY_OK); /* now generation 2 */ + ray_t* r = ray_read_splayed(ray_test_tmp(ENCCOL_TMP "/tb"), NULL); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); /* the loader keeps the encoded column */ + TEST_ASSERT_NULL(ray_table_get_col_enc(r, ray_sym_intern("ca", 2))); + TEST_ASSERT_TRUE(ray_table_get_col_enc(r, ray_sym_intern("cb", 2)) != NULL); + ray_t* pcb = ray_table_get_col(r, ray_sym_intern("cb", 2)); /* the legacy getter decodes */ + TEST_ASSERT_TRUE(pcb && pcb->type == RAY_I32 && pcb->len == 3000); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(pcb))[2000], 2000 % 977); + ray_release(r); + PASS(); +} + +static uint64_t g_seed = 1; +static uint8_t g_symw = RAY_SYM_W16; /* SYM width make_col builds */ +static uint64_t rng(void) { uint64_t x = g_seed; x ^= x << 13; x ^= x >> 7; x ^= x << 17; return g_seed = x; } + +/* A column of `type` and `n` rows in shape s: 0 random, 1 small range, + * 2 runs, 3 constant, 4 sparse nulls, 5 all null. */ +static ray_t* make_col(int8_t type, int64_t n, int s) { + if (type == RAY_STR) { + ray_t* v = ray_vec_new(RAY_STR, n); + char buf[64]; + for (int64_t i = 0; i < n; i++) { + int len; + if (s == 5 || (s == 4 && i % 7 == 0)) len = 0; + else if (s == 3) len = snprintf(buf, sizeof buf, "constant string value"); + else if (s == 2) len = snprintf(buf, sizeof buf, "run %lld long tail text", (long long)(i / 300)); + else len = snprintf(buf, sizeof buf, "%llu", (unsigned long long)(rng() % (s == 1 ? 50 : 100000000000ull))); + v = ray_str_vec_append(v, buf, (size_t)len); + } + if (s >= 4) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; + } + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(g_symw, n) : ray_vec_new(type, n); + v->len = n; + uint8_t esz = ray_sym_elem_size(type, v->attrs); + uint8_t* d = ray_data(v); + for (int64_t i = 0; i < n; i++) { + uint64_t x = s == 0 ? rng() : s == 1 ? rng() % 64 : s == 2 ? (uint64_t)(i / 300) * 7919 : 12345; + bool null = s == 5 || (s == 4 && i % 7 == 0); + switch (type) { + case RAY_BOOL: d[i] = (uint8_t)(x & 1); break; + case RAY_U8: d[i] = (uint8_t)x; break; + case RAY_I16: { int16_t y = null ? NULL_I16 : (int16_t)(x % 30000); memcpy(d + i * 2, &y, 2); break; } + case RAY_I32: case RAY_DATE: case RAY_TIME: + { int32_t y = null ? NULL_I32 : (int32_t)(x % 2000000000); memcpy(d + i * 4, &y, 4); break; } + case RAY_I64: case RAY_TIMESTAMP: + { int64_t y = null ? NULL_I64 : (int64_t)(x >> 1); memcpy(d + i * 8, &y, 8); break; } + case RAY_F32: { float y = null ? NULL_F32 : (float)(int64_t)(x % 100000) / 8.0f; memcpy(d + i * 4, &y, 4); break; } + case RAY_F64: { double y = null ? NULL_F64 : (double)(int64_t)(x % 1000000) / 16.0; memcpy(d + i * 8, &y, 8); break; } + case RAY_GUID: { memset(d + i * 16, 0, 16); if (!null) { memcpy(d + i * 16, &x, 8); d[i * 16 + 15] = 1; } break; } + case RAY_SYM: ray_write_sym(d, i, null ? 0 : 1 + x % 200, RAY_SYM, v->attrs); break; + } + (void)esz; + } + if (s >= 4 && type != RAY_BOOL && type != RAY_U8) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} + +/* Decode every vector of the generation-2 file and compare with `v`. */ +static test_result_t check_decode(ray_t* v, const char* path) { + ray_t* c = ray_col_mmap(path); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "mmap %s: %s", path, c ? ray_err_code(c) : "null"); + ray_enccol_t* e = ray_enccol_of(c); + uint8_t esz = ray_enccol_esz(e); + uint8_t out[RAY_ENC_VEC * 16]; + char pool[RAY_ENC_VEC * 64]; + const char* spool = (v->type == RAY_STR && v->str_pool) ? (const char*)ray_data(v->str_pool) : NULL; + for (int64_t vec = 0; vec < ray_enc_nvecs(v->len); vec++) { + ray_t* err = ray_enccol_decode_vec(e, vec, out, pool, 0); + TEST_ASSERT_FMT(err == NULL, "vec %lld: %s %s", (long long)vec, err ? ray_err_code(err) : "", ray_error_msg() ? ray_error_msg() : ""); + int vn = ray_enc_vec_len(v->len, vec); + if (v->type == RAY_STR) { + const ray_str_t* a = (const ray_str_t*)ray_data(v) + vec * RAY_ENC_VEC; + const ray_str_t* b = (const ray_str_t*)out; + for (int i = 0; i < vn; i++) { + TEST_ASSERT_FMT(a[i].len == b[i].len, "str len row %d", i); + TEST_ASSERT_FMT(memcmp(ray_str_t_ptr(&a[i], spool), ray_str_t_ptr(&b[i], pool), a[i].len) == 0, "str bytes row %d", i); + } + } else { + const uint8_t* a = (const uint8_t*)ray_data(v) + (size_t)vec * RAY_ENC_VEC * esz; + TEST_ASSERT_FMT(memcmp(a, out, (size_t)vn * esz) == 0, "type %d vec %lld bytes differ", (int)v->type, (long long)vec); + } + } + ray_release(c); + PASS(); +} + +static test_result_t test_roundtrip_types_shapes(void) { + static const int8_t types[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, + RAY_TIMESTAMP, RAY_F32, RAY_F64, RAY_GUID, RAY_SYM, RAY_STR }; + static const uint8_t widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; + for (size_t t = 0; t < sizeof types; t++) + for (size_t w = 0; w < (types[t] == RAY_SYM ? sizeof widths : 1); w++) + for (int s = 0; s < 6; s++) { + if ((types[t] == RAY_BOOL || types[t] == RAY_U8) && s >= 4) continue; + g_symw = widths[w]; + ray_t* v = make_col(types[t], 3000, s); + g_symw = RAY_SYM_W16; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/rt"), 2), RAY_OK); + test_result_t r = check_decode(v, ray_test_tmp(ENCCOL_TMP "/rt")); + ray_release(v); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +static test_result_t test_roundtrip_lengths(void) { + static const int64_t lens[] = { 1, 1023, 1024, 1025, 65535, 65536, 65537 }; + static const int8_t types[] = { RAY_I32, RAY_F64, RAY_STR, RAY_SYM }; + static const uint8_t widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; + for (size_t t = 0; t < sizeof types; t++) + for (size_t w = 0; w < (types[t] == RAY_SYM ? sizeof widths : 1); w++) + for (size_t l = 0; l < sizeof lens / sizeof lens[0]; l++) { + g_symw = widths[w]; + ray_t* v = make_col(types[t], lens[l], 4); + g_symw = RAY_SYM_W16; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/len"), 2), RAY_OK); + test_result_t r = check_decode(v, ray_test_tmp(ENCCOL_TMP "/len")); + ray_release(v); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Signedness at the domain edges and the 127/128 boundary. */ +static test_result_t test_roundtrip_edges(void) { + int64_t d64[6] = { INT64_MIN + 1, INT64_MAX, 0, NULL_I64, -1, INT64_MAX }; + ray_t* v = ray_vec_from_raw(RAY_I64, d64, 6); v->attrs |= RAY_ATTR_HAS_NULLS; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/e"), 2), RAY_OK); + test_result_t r = check_decode(v, ray_test_tmp(ENCCOL_TMP "/e")); ray_release(v); + if (r.status != TEST_PASS) return r; + int16_t d16[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d16[i] = (int16_t)(-32767 + (i % 3) * 32767); + v = ray_vec_from_raw(RAY_I16, d16, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/e"), 2), RAY_OK); + r = check_decode(v, ray_test_tmp(ENCCOL_TMP "/e")); ray_release(v); + if (r.status != TEST_PASS) return r; + uint8_t u8[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) u8[i] = (uint8_t)(127 + (i & 1)); + v = ray_vec_from_raw(RAY_U8, u8, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/e"), 2), RAY_OK); + r = check_decode(v, ray_test_tmp(ENCCOL_TMP "/e")); ray_release(v); + return r; +} + +/* The checked-in fixtures decode to the vectors that produced them. */ +static test_result_t test_golden_decode(void) { + static const char* names[] = { "i32_for", "i64_const", "i64_delta", "i64_dict_codes_rle", "i64_dict", + "i32_nulls", "i16_all_null", "u8_raw", "bool_rle", "f64_trailer", + "f64_const", "f32_zeros", "guid_mixed", "str_mixed", "str_const", + "i64_empty", "i32_two_chunks", "str_inline", "str_pooled", "str_repeated", + "i16_delta_wT", "i32_delta_wT", "i64_delta_wT", "i64_dict_const_child", + "i64_rle_values_for", "i64_rle_ends_delta" }; + for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) { + char p[256]; snprintf(p, sizeof p, "test/data/enc/%s.bin", names[i]); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "fixture %s does not load", names[i]); + ray_enccol_t* e = ray_enccol_of(c); + uint8_t out[RAY_ENC_VEC * 16]; char pool[RAY_ENC_VEC * 64]; + for (int64_t vec = 0; vec < ray_enc_nvecs(e->len); vec++) { + ray_t* err = ray_enccol_decode_vec(e, vec, out, pool, 0); + TEST_ASSERT_FMT(err == NULL, "fixture %s vec %lld", names[i], (long long)vec); + } + ray_release(c); + } + PASS(); +} + +/* The VALUE_DICT entry is validated once whoever asks first; a transient + * failure of that validation is retried (spec "Validation": once-state). */ +typedef struct { ray_enccol_t* e; ray_t* err; } dthr_t; +static void dict_decode_thread(void* raw) { + dthr_t* t = raw; + uint8_t out[RAY_ENC_VEC * 8]; + t->err = ray_enccol_decode_vec(t->e, 0, out, NULL, 0); + if (t->err) { ray_error_free(t->err); t->err = (ray_t*)1; } + ray_heap_abandon(); +} + +static test_result_t test_dict_once_concurrent(void) { + static const int64_t vals[4] = { 11, 900000000001ll, 77, 123456789012345ll }; + ray_t* v = ray_vec_new(RAY_I64, 1024); v->len = 1024; + for (int i = 0; i < 1024; i++) ((int64_t*)ray_data(v))[i] = vals[(uint32_t)((uint32_t)i * 2654435761u) >> 30]; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/dc"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/dc")); + ray_enccol_t* e = ray_enccol_of(c); + ray_enc_desc_t d0; memcpy(&d0, e->base + 160, 48); + TEST_ASSERT_EQ_I(d0.encoding, RAY_ENC_DICT); + ray_enccol_test_fail_alloc(1); /* the validation's allocation */ + uint8_t out[RAY_ENC_VEC * 8]; + ray_t* r = ray_enccol_decode_vec(e, 0, out, NULL, 0); + ray_enccol_test_fail_alloc(0); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "oom"); + ray_error_free(r); + TEST_ASSERT_NULL(e->dict); /* not cached */ + dthr_t t[8]; ray_thread_t th[8]; + for (int i = 0; i < 8; i++) { t[i].e = e; t[i].err = NULL; ray_thread_create(&th[i], dict_decode_thread, &t[i]); } + for (int i = 0; i < 8; i++) { ray_thread_join(th[i]); TEST_ASSERT_NULL(t[i].err); } + TEST_ASSERT_NOT_NULL(e->dict); + ray_release(c); + PASS(); +} + +/* ---- Task 3b: the integer fast kernel against the reference decode ---- */ + +/* One case: values (T-bit patterns, vlen rows) encoded as `enc`, decoded + * by the fast kernel at every output it serves and by the reference path; + * nulls are rows set in `bm` (NULL: none). want_w >= 0 pins the width the + * writer chose. The fast kernel must take a sound vector. */ +static test_result_t fk_case(int8_t type, uint8_t attrs, uint8_t enc, const uint64_t* vals, int vlen, + const uint8_t* bm, int want_w, const char* what) { + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(type, attrs, &k)); + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_FMT(ray_enc_write_as(enc, vals, vlen, k, NULL, &b, &ch), "%s: write_as", what); + if (want_w >= 0) TEST_ASSERT_FMT(ch.width == want_w, "%s: width %d, want %d", what, ch.width, want_w); + int n_nulls = 0; + if (type == RAY_SYM) { for (int i = 0; i < vlen; i++) n_nulls += vals[i] == 0; } + else if (bm) { for (int i = 0; i < vlen; i++) n_nulls += (bm[i >> 3] >> (i & 7)) & 1; } + const uint8_t* bmp = n_nulls && type != RAY_SYM ? bm : NULL; + static uint8_t ref[RAY_ENC_VEC * 8 + 8], fast[RAY_ENC_VEC * 8 + 8]; + memset(ref, 0xA5, sizeof ref); memset(fast, 0x5A, sizeof fast); + int rr = ray_enccol_test_decode_body(type, attrs, enc, ch.width, n_nulls, bmp, b.p, b.len, vlen, false, 0, ref); + int fr = ray_enccol_test_decode_body(type, attrs, enc, ch.width, n_nulls, bmp, b.p, b.len, vlen, true, 0, fast); + TEST_ASSERT_FMT(rr == 1, "%s: reference %d", what, rr); + TEST_ASSERT_FMT(fr == 1, "%s: fast kernel %d", what, fr); + size_t esz = (size_t)k.T / 8; + TEST_ASSERT_FMT(memcmp(ref, fast, (size_t)vlen * esz) == 0, "%s: fast differs", what); + TEST_ASSERT_FMT(fast[(size_t)vlen * esz] == 0x5A, "%s: wrote past the vector", what); + /* the expression register widening (narrow non-SYM types) */ + if (type != RAY_SYM && k.T < 64) { + static int64_t wi[RAY_ENC_VEC + 1]; static double wf[RAY_ENC_VEC + 1]; + wi[vlen] = 77; wf[vlen] = 77.0; + TEST_ASSERT_FMT(ray_enccol_test_decode_body(type, attrs, enc, ch.width, n_nulls, bmp, b.p, b.len, vlen, true, RAY_I64, wi) == 1, "%s: wide i64", what); + TEST_ASSERT_FMT(ray_enccol_test_decode_body(type, attrs, enc, ch.width, n_nulls, bmp, b.p, b.len, vlen, true, RAY_F64, wf) == 1, "%s: wide f64", what); + for (int i = 0; i < vlen; i++) { + int64_t x = k.T == 8 ? (int64_t)ref[i] : k.T == 16 ? (int64_t)((int16_t*)ref)[i] : (int64_t)((int32_t*)ref)[i]; + bool null = bmp && ((bmp[i >> 3] >> (i & 7)) & 1); + TEST_ASSERT_FMT(wi[i] == (null ? NULL_I64 : x), "%s: wide i64 row %d", what, i); + TEST_ASSERT_FMT(null ? isnan(wf[i]) : wf[i] == (double)x, "%s: wide f64 row %d", what, i); + } + TEST_ASSERT_FMT(wi[vlen] == 77 && wf[vlen] == 77.0, "%s: wide wrote past the vector", what); + } + ray_enc_buf_free(&b); + PASS(); +} + +/* Sentinel of a signed kind as a T-bit pattern. */ +static uint64_t fk_sentinel(int T) { return T == 64 ? (uint64_t)1 << 63 : (uint64_t)1 << (T - 1); } + +static test_result_t test_fast_kernel_equal(void) { + static const struct { int8_t type; uint8_t attrs; } kinds[] = { + { RAY_U8, 0 }, { RAY_BOOL, 0 }, { RAY_I16, 0 }, { RAY_I32, 0 }, { RAY_I64, 0 }, { RAY_DATE, 0 }, { RAY_TIME, 0 }, + { RAY_SYM, RAY_SYM_W8 }, { RAY_SYM, RAY_SYM_W16 }, { RAY_SYM, RAY_SYM_W32 }, { RAY_SYM, RAY_SYM_W64 }, + }; + static const int lens[] = { 1024, 1000, 77, 1 }; + static uint64_t v[RAY_ENC_VEC]; + static uint8_t bm[RAY_ENC_VEC / 8]; + char what[160]; + g_seed = 0x3b3b; + for (size_t ki = 0; ki < sizeof kinds / sizeof kinds[0]; ki++) { + int8_t type = kinds[ki].type; uint8_t attrs = kinds[ki].attrs; + ray_enc_kind_t k; ray_enc_kind_of(type, attrs, &k); + const int T = k.T; + const uint64_t m = T == 64 ? ~0ull : (1ull << T) - 1; + const bool sym = type == RAY_SYM, sgn = k.is_signed; + int widths[5] = { 0, 1, T / 2 + 1, T - 1, T }; + for (int wi = 0; wi < 5; wi++) { + int w = widths[wi]; + if (sym && w > 29) continue; /* ids stay below the bound 1 << 30 */ + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + int n = lens[li]; + if (w > 0 && n == 1) continue; /* one row has range 0 */ + /* FOR_BP: offsets [0, span] over a base. Signed kinds keep + * the logical order and stay off the sentinel: a full-width + * signed range is [MIN + 1, MAX], span 2^T - 2, still width T. + * SYM ids are 1..2^T - 1 (0 is the null). */ + uint64_t span = w == 0 ? 0 : (w == 64 ? ~0ull : (1ull << w) - 1); + uint64_t base; + if (sym) { + uint64_t top = m < (1ull << 30) - 1 ? m : (1ull << 30) - 1; /* the largest id: below the bound */ + if (w == T) span = m - 1; + base = 1 + rng() % (top - span); + } else if (!sgn) { + base = rng() % (m - span + 1); + } else { + if (w == T) span -= 1; + __int128 lo = -(((__int128)1) << (T - 1)) + 1, hi = (((__int128)1) << (T - 1)) - 1; + uint64_t room = (uint64_t)(hi - lo + 1 - (__int128)span); /* bases b with b + span <= MAX */ + __int128 lb = lo + (__int128)(rng() % room); + if (wi & 1) lb = lo + (__int128)(rng() % (room / 2 + 1)); /* the lower half: negative */ + base = (uint64_t)lb & m; + } + for (int i = 0; i < n; i++) v[i] = (base + (span ? rng() % span : 0)) & m; + if (span && n > 1) { v[0] = base; v[n - 1] = (base + span) & m; } + snprintf(what, sizeof what, "FOR type %d attrs %d w %d n %d", type, attrs, w, n); + test_result_t r = fk_case(type, attrs, RAY_ENC_FOR_BP, v, n, NULL, n == 1024 ? w : -1, what); + if (r.status != TEST_PASS) return r; + if (sgn) { + /* nulls in the bitmap (any bits underneath), one at the sentinel */ + memset(bm, 0, sizeof bm); + for (int i = 0; i < n; i += 13) bm[i >> 3] |= (uint8_t)(1u << (i & 7)); + if (n > 5) { v[5] = fk_sentinel(T); bm[0] |= 1u << 5; } + snprintf(what, sizeof what, "FOR nulls type %d w %d n %d", type, w, n); + if ((r = fk_case(type, attrs, RAY_ENC_FOR_BP, v, n, bm, -1, what)).status != TEST_PASS) return r; + /* DELTA_BP: lane walks with steps in [s0, s0 + span]; a value on the sentinel becomes a null */ + int L = RAY_ENC_VEC / T; + uint64_t s0 = rng() & m; + memset(bm, 0, sizeof bm); + for (int i = 0; i < n; i++) { + uint64_t step = (s0 + (span ? rng() % (span + 1) : 0)) & m; + v[i] = i < L ? rng() & m : (v[i - L] + step) & m; + } + for (int i = 0; i < n; i++) if (v[i] == fk_sentinel(T)) bm[i >> 3] |= (uint8_t)(1u << (i & 7)); + snprintf(what, sizeof what, "DELTA type %d w %d n %d", type, w, n); + if ((r = fk_case(type, attrs, RAY_ENC_DELTA_BP, v, n, bm, -1, what)).status != TEST_PASS) return r; + } + } + } + } + PASS(); +} + +/* ---- Task 17a: the CONST, RLE and RAW kernels against the reference decode ---- */ + +/* One sound hook body: the reference takes it, the fast kernel takes it + * with the reference's bytes and writes nothing past vlen, and `want` (the + * T-bit pattern of each row, NULL: unchecked) is what the reference holds. + * Narrow non-SYM kinds: the widened outputs are served exactly when `wide` + * and hold the reference's values, nulls as NULL_I64 / NULL_F64. */ +static test_result_t rk_check(int8_t type, uint8_t attrs, uint8_t enc, uint8_t width, const uint8_t* body, + uint64_t len, int vlen, const uint8_t* bm, int n_nulls, bool wide, + const uint64_t* want, const char* what) { + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(type, attrs, &k)); + const uint8_t* bmp = n_nulls && ray_enc_has_bitmap(type) ? bm : NULL; + static uint8_t ref[RAY_ENC_VEC * 8 + 8], fast[RAY_ENC_VEC * 8 + 8]; + memset(ref, 0xA5, sizeof ref); memset(fast, 0x5A, sizeof fast); + int rr = ray_enccol_test_decode_body(type, attrs, enc, width, n_nulls, bmp, body, len, vlen, false, 0, ref); + int fr = ray_enccol_test_decode_body(type, attrs, enc, width, n_nulls, bmp, body, len, vlen, true, 0, fast); + TEST_ASSERT_FMT(rr == 1, "%s: reference %d", what, rr); + TEST_ASSERT_FMT(fr == 1, "%s: fast kernel %d", what, fr); + const size_t esz = (size_t)k.T / 8; + TEST_ASSERT_FMT(memcmp(ref, fast, (size_t)vlen * esz) == 0, "%s: fast differs", what); + TEST_ASSERT_FMT(fast[(size_t)vlen * esz] == 0x5A, "%s: wrote past the vector", what); + for (int i = 0; want && i < vlen; i++) { + uint64_t x = 0; memcpy(&x, ref + (size_t)i * esz, esz); + TEST_ASSERT_FMT(x == want[i], "%s: row %d holds %llx, want %llx", what, i, + (unsigned long long)x, (unsigned long long)want[i]); + } + if (type != RAY_SYM && k.T < 64) { + static int64_t wi[RAY_ENC_VEC + 1]; static double wf[RAY_ENC_VEC + 1]; + wi[vlen] = 77; wf[vlen] = 77.0; + int ri = ray_enccol_test_decode_body(type, attrs, enc, width, n_nulls, bmp, body, len, vlen, true, RAY_I64, wi); + int rf = ray_enccol_test_decode_body(type, attrs, enc, width, n_nulls, bmp, body, len, vlen, true, RAY_F64, wf); + TEST_ASSERT_FMT(ri == (wide ? 1 : 0) && rf == ri, "%s: wide %d / %d, want %d", what, ri, rf, wide ? 1 : 0); + for (int i = 0; wide && i < vlen; i++) { + int64_t x = k.T == 8 ? (int64_t)ref[i] : k.T == 16 ? (int64_t)((int16_t*)ref)[i] : (int64_t)((int32_t*)ref)[i]; + bool null = bmp && ((bmp[i >> 3] >> (i & 7)) & 1); + TEST_ASSERT_FMT(wi[i] == (null ? NULL_I64 : x), "%s: wide i64 row %d", what, i); + TEST_ASSERT_FMT(null ? isnan(wf[i]) : wf[i] == (double)x, "%s: wide f64 row %d", what, i); + } + TEST_ASSERT_FMT(wi[vlen] == 77 && wf[vlen] == 77.0, "%s: wide wrote past the vector", what); + } + PASS(); +} + +/* nr run values of kind k (T-bit patterns), adjacent ones distinct: signed + * kinds off the sentinel, SYM ids in [1, 2^30) and inside the id width; + * narrow: inside one base + [0, 15]. */ +static void rk_vals(ray_enc_kind_t k, bool sym, int nr, bool narrow, uint64_t* v) { + const uint64_t m = k.T == 64 ? ~0ull : (1ull << k.T) - 1; + const uint64_t top = sym ? (m < (1ull << 30) - 1 ? m : (1ull << 30) - 1) : m; + const uint64_t base = sym ? 1 + rng() % (top - 16) : rng() & m; + for (int i = 0; i < nr; i++) { + uint64_t x; + do { + x = narrow ? (base + rng() % 16) & m : rng() & m; + if (sym && !narrow) x = 1 + x % top; + } while ((k.is_signed && x == fk_sentinel(k.T)) || (i && x == v[i - 1])); + v[i] = x; + } +} + +/* nr run ends over vlen rows: nr - 1 distinct cuts in [1, vlen), then vlen. */ +static void rk_ends(int vlen, int nr, uint64_t* ends) { + static uint8_t cut[RAY_ENC_VEC + 1]; + memset(cut, 0, sizeof cut); + for (int got = 0; got < nr - 1;) { + int p = 1 + (int)(rng() % (uint64_t)(vlen - 1)); + if (!cut[p]) { cut[p] = 1; got++; } + } + int r = 0; + for (int p = 1; p < vlen; p++) if (cut[p]) ends[r++] = (uint64_t)p; + ends[r] = (uint64_t)vlen; +} + +/* A child of an RLE body as the writer lays it out (header, then body), + * its encoding forced. */ +static bool rk_child(ray_enc_buf_t* b, uint8_t enc, const uint64_t* v, int n, ray_enc_kind_t k) { + ray_enc_buf_t c = { 0 }; ray_enc_choice_t ch; + bool ok = ray_enc_write_as(enc, v, n, k, NULL, &c, &ch); + uint32_t bb = (uint32_t)c.len; + uint8_t h[8] = { enc, ok ? ch.width : 0, 0, 0, 0, 0, 0, 0 }; + memcpy(h + 4, &bb, 4); + ok = ok && ray_enc_buf_put(b, h, 8) && ray_enc_buf_put(b, c.p, c.len); + ray_enc_buf_free(&c); + return ok; +} +/* An RLE body of nr runs: the values child venc (RAW / FOR_BP) of kind k, + * the ends child eenc (RAW / FOR_BP / DELTA_BP) of U16 run ends. The + * writer emits DELTA_BP for signed kinds; run ends read the same as I16. */ +static bool rk_rle(ray_enc_buf_t* b, ray_enc_kind_t k, const uint64_t* vals, const uint64_t* ends, int nr, + uint8_t venc, uint8_t eenc) { + uint32_t h[2] = { (uint32_t)nr, 0 }; + ray_enc_kind_t ke = { 16, eenc == RAY_ENC_DELTA_BP, false }; + return ray_enc_buf_put(b, h, 8) && rk_child(b, venc, vals, nr, k) && rk_child(b, eenc, ends, nr, ke); +} + +/* The rows of nr runs, then the stored rows the reference holds (signed: + * the sentinel at a bitmap row; SYM: id 0 is the null itself). */ +static int rk_expand(ray_enc_kind_t k, bool sym, const uint64_t* vals, const uint64_t* ends, int nr, + const uint8_t* bm, uint64_t* rows, uint64_t* want) { + int n_nulls = 0; + for (int i = 0, p = 0; i < nr; p = (int)ends[i++]) + for (int r = p; r < (int)ends[i]; r++) { + rows[r] = vals[i]; + bool null = k.is_signed && ((bm[r >> 3] >> (r & 7)) & 1); + want[r] = null ? fk_sentinel(k.T) : vals[i]; + n_nulls += null || (sym && vals[i] == 0); + } + return n_nulls; +} + +static test_result_t test_runs_kernel_equal(void) { + static const struct { int8_t type; uint8_t attrs; } kinds[] = { + { RAY_U8, 0 }, { RAY_BOOL, 0 }, { RAY_I16, 0 }, { RAY_I32, 0 }, { RAY_I64, 0 }, { RAY_DATE, 0 }, + { RAY_TIME, 0 }, { RAY_TIMESTAMP, 0 }, + { RAY_SYM, RAY_SYM_W8 }, { RAY_SYM, RAY_SYM_W16 }, { RAY_SYM, RAY_SYM_W32 }, { RAY_SYM, RAY_SYM_W64 }, + }; + static const int lens[] = { 1024, 1000, 77, 1 }; + static const int runs[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 31, 32, 33, 63, 64, 65, + 100, 127, 128, 129, 255, 256, 257, 500, 511, 512, 513, 767, 1000, 1023, 1024 }; + /* the children: the writer's choice (0xFF), then each forced pair */ + static const uint8_t kids[][2] = { + { 0xFF, 0xFF }, { RAY_ENC_RAW, RAY_ENC_RAW }, { RAY_ENC_RAW, RAY_ENC_FOR_BP }, { RAY_ENC_RAW, RAY_ENC_DELTA_BP }, + { RAY_ENC_FOR_BP, RAY_ENC_RAW }, { RAY_ENC_FOR_BP, RAY_ENC_FOR_BP }, { RAY_ENC_FOR_BP, RAY_ENC_DELTA_BP }, + }; + static uint64_t vals[RAY_ENC_VEC], ends[RAY_ENC_VEC], rows[RAY_ENC_VEC], want[RAY_ENC_VEC]; + static uint8_t bm[RAY_ENC_VEC / 8]; + char what[200]; + long cases = 0; + g_seed = 0x17a; + for (size_t ki = 0; ki < sizeof kinds / sizeof kinds[0]; ki++) { + const int8_t type = kinds[ki].type; const uint8_t attrs = kinds[ki].attrs; + ray_enc_kind_t k; ray_enc_kind_of(type, attrs, &k); + const bool sym = type == RAY_SYM, sgn = k.is_signed; + const bool wide = !sym && k.T < 64; + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + const int n = lens[li]; + for (size_t ri = 0; ri < sizeof runs / sizeof runs[0]; ri++) { + const int nr = runs[ri]; + if (nr > n) continue; + for (int nulls = 0; nulls < ((sgn || sym) ? 2 : 1); nulls++) { + rk_vals(k, sym, nr, (ri + (size_t)nulls) & 1, vals); + rk_ends(n, nr, ends); + memset(bm, 0, sizeof bm); + if (nulls) { + /* every fifth run null (signed: the sentinel, its rows in + * the bitmap; SYM: id 0), and scattered bitmap rows */ + for (int i = 2; i < nr; i += 5) { + vals[i] = sym ? 0 : fk_sentinel(k.T); + for (int r = i ? (int)ends[i - 1] : 0; sgn && r < (int)ends[i]; r++) bm[r >> 3] |= (uint8_t)(1u << (r & 7)); + } + for (int r = 3; sgn && r < n; r += 37) bm[r >> 3] |= (uint8_t)(1u << (r & 7)); + } + const int n_nulls = rk_expand(k, sym, vals, ends, nr, bm, rows, want); + for (size_t c = 0; c < sizeof kids / sizeof kids[0]; c++) { + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + bool ok = kids[c][0] == 0xFF ? ray_enc_write_as(RAY_ENC_RLE, rows, n, k, NULL, &b, &ch) + : rk_rle(&b, k, vals, ends, nr, kids[c][0], kids[c][1]); + TEST_ASSERT_FMT(ok, "type %d: build", type); + snprintf(what, sizeof what, "RLE type %d attrs %d n %d nr %d nulls %d kids %u/%u", type, attrs, + n, nr, n_nulls, kids[c][0], kids[c][1]); + test_result_t r = rk_check(type, attrs, RAY_ENC_RLE, 0, b.p, b.len, n, bm, n_nulls, wide, want, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + cases++; + } + if (nr == 1) { + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_CONST, rows, n, k, NULL, &b, &ch)); + snprintf(what, sizeof what, "CONST type %d attrs %d n %d nulls %d", type, attrs, n, n_nulls); + test_result_t r = rk_check(type, attrs, RAY_ENC_CONST, 0, b.p, b.len, n, bm, n_nulls, wide, want, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + } + } + } + /* CONST all null: signed on the sentinel with every row in the + * bitmap, SYM id 0 */ + if (sgn || sym) { + for (int i = 0; i < n; i++) { rows[i] = sym ? 0 : fk_sentinel(k.T); want[i] = rows[i]; } + memset(bm, 0, sizeof bm); + for (int i = 0; sgn && i < n; i++) bm[i >> 3] |= (uint8_t)(1u << (i & 7)); + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_CONST, rows, n, k, NULL, &b, &ch)); + snprintf(what, sizeof what, "CONST all null type %d attrs %d n %d", type, attrs, n); + test_result_t r = rk_check(type, attrs, RAY_ENC_CONST, 0, b.p, b.len, n, bm, n, wide, want, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + } + /* RAW: random rows; with nulls, every seventh row (signed: the + * sentinel or any value under the bitmap; SYM: id 0) */ + for (int nulls = 0; nulls < ((sgn || sym) ? 2 : 1); nulls++) { + rk_vals(k, sym, n, false, rows); + memset(bm, 0, sizeof bm); + int n_nulls = 0; + for (int i = 0; i < n; i++) { + if (nulls && i % 7 == 1) { + n_nulls++; + if (sym) rows[i] = 0; + else { bm[i >> 3] |= (uint8_t)(1u << (i & 7)); if (i % 14 == 1) rows[i] = fk_sentinel(k.T); } + } + want[i] = sgn && ((bm[i >> 3] >> (i & 7)) & 1) ? fk_sentinel(k.T) : rows[i]; + } + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_RAW, rows, n, k, NULL, &b, &ch)); + snprintf(what, sizeof what, "RAW type %d attrs %d n %d nulls %d", type, attrs, n, n_nulls); + test_result_t r = rk_check(type, attrs, RAY_ENC_RAW, 0, b.p, b.len, n, bm, n_nulls, false, want, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + } + } + } + /* every run count 1..1024 over a full I16 vector, the writer's children */ + ray_enc_kind_t k16 = { 16, true, false }; + memset(bm, 0, sizeof bm); + for (int nr = 1; nr <= RAY_ENC_VEC; nr++) { + rk_vals(k16, false, nr, nr & 1, vals); + rk_ends(RAY_ENC_VEC, nr, ends); + (void)rk_expand(k16, false, vals, ends, nr, bm, rows, want); + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_RLE, rows, RAY_ENC_VEC, k16, NULL, &b, &ch)); + snprintf(what, sizeof what, "RLE I16 nr %d", nr); + test_result_t r = rk_check(RAY_I16, 0, RAY_ENC_RLE, 0, b.p, b.len, RAY_ENC_VEC, bm, 0, true, want, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + } + TEST_ASSERT_TRUE(cases > 10000); + PASS(); +} + +/* A RAW integer vector without nulls is read in place: the range read's + * data lies in the mapping and holds the generation-0 values, guarded or + * not, and counts the vector's bytes as delivered (as its decode would). + * With nulls, or any other encoding, it is decoded. (The writer trains a VALUE_DICT on the first chunk, so signed + * kinds hold their RAW vectors in the second.) */ +static test_result_t test_raw_int_view(void) { + static const struct { int8_t type; uint8_t attrs; int64_t n; bool nulls; } cs[] = { + { RAY_I64, 0, 70001, false }, { RAY_I16, 0, 70000, false }, { RAY_U8, 0, 1500, false }, + { RAY_SYM, RAY_SYM_W8, 2100, false }, { RAY_TIMESTAMP, 0, 69632, false }, { RAY_I32, 0, 70000, true }, + }; + const char* path = ray_test_tmp(ENCCOL_TMP "/rawv"); + g_seed = 0x4a7; + for (size_t ci = 0; ci < sizeof cs / sizeof cs[0]; ci++) { + const int8_t type = cs[ci].type; + const int64_t n = cs[ci].n; + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(cs[ci].attrs, n) : ray_vec_new(type, n); + v->len = n; + const uint8_t esz = ray_sym_elem_size(type, v->attrs); + uint8_t* d = ray_data(v); + for (int64_t i = 0; i < n; i++) { + uint64_t x = rng(); + switch (type) { + case RAY_U8: d[i] = (uint8_t)x; break; + case RAY_SYM: d[i] = (uint8_t)(1 + x % 255); break; + case RAY_I16: { int16_t y = (int16_t)x; if (y == NULL_I16) y = 0; memcpy(d + i * 2, &y, 2); break; } + case RAY_I32: { int32_t y = (int32_t)(uint32_t)(x >> 32); if (y == NULL_I32) y = 0; + if (cs[ci].nulls && i % 9 == 0) y = NULL_I32; + memcpy(d + i * 4, &y, 4); break; } + default: { int64_t y = (int64_t)x; if (y == NULL_I64) y = 0; memcpy(d + i * 8, &y, 8); break; } + } + } + if (cs[ci].nulls) v->attrs |= RAY_ATTR_HAS_NULLS; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, path, 2), RAY_OK); + ray_t* c = ray_col_mmap(path); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_t* e = ray_enccol_of(c); + TEST_ASSERT_NOT_NULL(e); + int raw = 0; + { + ray_col_src_t src; + TEST_ASSERT_NULL(ray_col_src_bind(c, &src)); + for (int64_t at = 0; at < n; at += RAY_ENC_VEC) { + const ray_enc_desc_t* descs = ray_enccol_descs(e, at / RAY_ENC_CHUNK); + const bool is_raw = descs[at % RAY_ENC_CHUNK / RAY_ENC_VEC].encoding == RAY_ENC_RAW; + raw += is_raw; + const bool view = is_raw && !cs[ci].nulls; + int64_t len = n - at < RAY_ENC_VEC ? n - at : RAY_ENC_VEC; + for (int64_t off = 0; off < len; off += len / 2 + 1) { /* a whole vector and its tail */ + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_enc_counters_reset(); + ray_col_range_t r; + TEST_ASSERT_NULL(ray_col_range(&src, at + off, len - off, &sc, &r)); + TEST_ASSERT_EQ_I(r.n, len - off); + const bool in_map = (const uint8_t*)r.data >= e->base && (const uint8_t*)r.data < e->base + e->size; + TEST_ASSERT_FMT(in_map == view, "type %d at %lld: in the mapping %d", type, (long long)(at + off), in_map); + TEST_ASSERT_TRUE(!view || !r.may_null); + TEST_ASSERT_TRUE(memcmp(r.data, d + (size_t)(at + off) * esz, (size_t)(len - off) * esz) == 0); + TEST_ASSERT_TRUE(type != RAY_SYM || r.dom == e->dom); + ray_col_scratch_free(&sc); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.decoded_bytes == (uint64_t)len * esz, "type %d at %lld: counted %llu", + type, (long long)(at + off), (unsigned long long)k.decoded_bytes); + } + } + ray_col_src_release(&src); + } + TEST_ASSERT_FMT(raw >= 2, "type %d: %d RAW vectors", type, raw); /* a full one and a tail */ + ray_release(c); + ray_release(v); + } + PASS(); +} + +/* ---- Task 13b: point reads and the DICT kernel against the reference decode ---- */ + +/* Element i of a generation-0 vector of `type`, widened to int64. */ +static int64_t gen0_at(int8_t type, const void* d, int i) { + switch (type) { + case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)d)[i]; + case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)d)[i]; + case RAY_I16: return ((const int16_t*)d)[i]; + default: return ((const uint8_t*)d)[i]; + } +} + +/* A DICT vector body into out (8-aligned): the codes base + u[i] (1024 of + * them) as a U32 FOR_BP child of width w. Returns its bytes. */ +static uint64_t dict_body(uint8_t* out, const uint64_t* u, int w, uint64_t base) { + uint32_t bb = (uint32_t)ray_enc_size_for(w); + memset(out, 0, 8 + (size_t)bb); + out[0] = RAY_ENC_FOR_BP; out[1] = (uint8_t)w; + memcpy(out + 4, &bb, 4); + memcpy(out + 8, &base, 8); + if (w) ray_enc_pack(u, 32, w, out + 16); + return 8 + (uint64_t)bb; +} + +/* Every row's point read of a body equals the reference decode's row + * (dict: a DICT body over dict[0, n_dict)). */ +static test_result_t point_case(int8_t type, uint8_t enc, const uint64_t* dict, uint32_t n_dict, + uint8_t width, const uint8_t* body, uint64_t avail, int vlen, const char* what) { + static uint8_t ref[RAY_ENC_VEC * 8]; + static int64_t pv[RAY_ENC_VEC]; static int8_t res[RAY_ENC_VEC]; + int rr = dict ? ray_enccol_test_decode_dict(type, dict, n_dict, 0, NULL, body, avail, vlen, false, ref) + : ray_enccol_test_decode_body(type, 0, enc, width, 0, NULL, body, avail, vlen, false, 0, ref); + TEST_ASSERT_FMT(rr == 1, "%s: reference %d", what, rr); + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(type, dict, n_dict, enc, width, 0, body, avail, vlen, pv, res), 0); + for (int i = 0; i < vlen; i++) { + TEST_ASSERT_FMT(res[i] == 1, "%s: row %d declined (%d)", what, i, res[i]); + TEST_ASSERT_FMT(pv[i] == gen0_at(type, ref, i), "%s: row %d point %lld, decode %lld", what, i, + (long long)pv[i], (long long)gen0_at(type, ref, i)); + } + PASS(); +} + +/* A strictly ascending dictionary of n values of kind k spread over the + * whole non-null range (the extremes MIN + 1 and MAX included). */ +static void dict_values(uint64_t* dv, uint32_t n, ray_enc_kind_t k) { + const uint64_t m = k.T == 64 ? ~0ull : (1ull << k.T) - 1; + __int128 lo = -(((__int128)1) << (k.T - 1)) + 1, hi = (((__int128)1) << (k.T - 1)) - 1; + for (uint32_t j = 0; j < n; j++) + dv[j] = (uint64_t)(n == 1 ? lo : lo + (hi - lo) * (__int128)j / (__int128)(n - 1)) & m; +} + +static test_result_t test_point_read_equal(void) { + static const int8_t ftypes[] = { RAY_U8, RAY_BOOL, RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, RAY_TIMESTAMP }; + static const int lens[] = { 1024, 1000, 77, 1 }; + static uint64_t v[RAY_ENC_VEC], u[RAY_ENC_VEC], dv[65536], bodyw[RAY_ENC_VEC / 2 + 4]; + char what[160]; + g_seed = 0x13b1; + /* FOR_BP: widths 0, 1, T - 1 and T, negative bases, the extremes */ + for (size_t ti = 0; ti < sizeof ftypes / sizeof ftypes[0]; ti++) { + int8_t type = ftypes[ti]; + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(type, 0, &k)); + const int T = k.T; + const uint64_t m = T == 64 ? ~0ull : (1ull << T) - 1; + int widths[4] = { 0, 1, T - 1, T }; + for (int wi = 0; wi < 4; wi++) { + int w = widths[wi]; + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + int n = lens[li]; + if (w > 0 && n == 1) continue; + uint64_t span = w == 0 ? 0 : (w == 64 ? ~0ull : (1ull << w) - 1), base; + if (!k.is_signed) { + base = rng() % (m - span + 1); + } else { + if (w == T) span -= 1; /* [MIN + 1, MAX]: off the sentinel */ + __int128 lo = -(((__int128)1) << (T - 1)) + 1, hi = (((__int128)1) << (T - 1)) - 1; + uint64_t room = (uint64_t)(hi - lo + 1 - (__int128)span); + __int128 lb = lo + (__int128)(rng() % (wi & 1 ? room / 2 + 1 : room)); /* odd: negative */ + base = (uint64_t)lb & m; + } + for (int i = 0; i < n; i++) v[i] = (base + (span ? rng() % span : 0)) & m; + if (span && n > 1) { v[0] = base; v[n - 1] = (base + span) & m; } + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_FOR_BP, v, n, k, NULL, &b, &ch)); + if (n == 1024) TEST_ASSERT_EQ_I(ch.width, w); + snprintf(what, sizeof what, "FOR type %d w %d n %d", type, ch.width, n); + test_result_t r = point_case(type, RAY_ENC_FOR_BP, NULL, 0, ch.width, b.p, b.len, n, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + } + } + } + /* DICT over a FOR_BP code child: code widths 0..16, dictionaries of 1, + * 2, 255, 256 and 65535 values, full and partial vectors */ + static const int8_t dtypes[] = { RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIMESTAMP }; + static const uint32_t sizes[] = { 1, 2, 255, 256, 65535 }; + for (size_t ti = 0; ti < sizeof dtypes / sizeof dtypes[0]; ti++) { + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(dtypes[ti], 0, &k)); + for (size_t si = 0; si < sizeof sizes / sizeof sizes[0]; si++) { + uint32_t nd = sizes[si]; + dict_values(dv, nd, k); + for (int w = 0; w <= 16; w++) + for (int li = 0; li < 3; li++) { + int n = lens[li]; + uint64_t span = 1ull << w, base = nd >= span ? rng() % (nd - span + 1) : 0; + uint64_t lim = nd >= span ? span : nd; /* codes base + u below nd */ + memset(u, 0, sizeof u); + for (int i = 0; i < n; i++) u[i] = rng() % lim; + u[0] = 0; u[n - 1] = lim - 1; + uint64_t len = dict_body((uint8_t*)bodyw, u, w, base); + snprintf(what, sizeof what, "DICT type %d dict %u w %d n %d", dtypes[ti], nd, w, n); + test_result_t r = point_case(dtypes[ti], RAY_ENC_DICT, dv, nd, 0, (const uint8_t*)bodyw, len, n, what); + if (r.status != TEST_PASS) return r; + } + } + } + PASS(); +} + + +/* The fast DICT kernel against the reference decode of one body: the same + * bytes, nothing written past the vector. */ +static test_result_t dict_kernel_case(int8_t type, const uint64_t* dv, uint32_t nd, const uint8_t* body, + uint64_t len, int n, int n_nulls, const uint8_t* bm, const char* what) { + static _Alignas(8) uint8_t ref[RAY_ENC_VEC * 8 + 8], fast[RAY_ENC_VEC * 8 + 8]; /* the kernel's alignment */ + memset(ref, 0xA5, sizeof ref); memset(fast, 0x5A, sizeof fast); + int rr = ray_enccol_test_decode_dict(type, dv, nd, n_nulls, bm, body, len, n, false, ref); + int fr = ray_enccol_test_decode_dict(type, dv, nd, n_nulls, bm, body, len, n, true, fast); + TEST_ASSERT_FMT(rr == 1, "%s: reference %d", what, rr); + TEST_ASSERT_FMT(fr == 1, "%s: fast kernel %d", what, fr); + size_t esz = ray_sym_elem_size(type, 0); + TEST_ASSERT_FMT(memcmp(ref, fast, (size_t)n * esz) == 0, "%s: fast differs", what); + TEST_ASSERT_FMT(fast[(size_t)n * esz] == 0x5A, "%s: wrote past the vector", what); + PASS(); +} + +/* The DICT kernel: code widths 0..16, dictionaries of 1, 2, 255, 256 and + * 65535 values, full and partial vectors, with and without nulls. */ +static test_result_t test_dict_kernel_equal(void) { + static const int8_t dtypes[] = { RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, RAY_TIMESTAMP }; + static const uint32_t sizes[] = { 1, 2, 255, 256, 65535 }; + static const int lens[] = { 1024, 1000, 77, 1 }; + static uint64_t u[RAY_ENC_VEC], dv[65536], bodyw[RAY_ENC_VEC / 2 + 4]; + static uint8_t bm[RAY_ENC_VEC / 8]; + char what[160]; + g_seed = 0x13b2; + for (size_t ti = 0; ti < sizeof dtypes / sizeof dtypes[0]; ti++) { + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(dtypes[ti], 0, &k)); + for (size_t si = 0; si < sizeof sizes / sizeof sizes[0]; si++) { + uint32_t nd = sizes[si]; + dict_values(dv, nd, k); + for (int w = 0; w <= 16; w++) + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + int n = lens[li]; + uint64_t span = 1ull << w, base = nd >= span ? rng() % (nd - span + 1) : 0; + uint64_t lim = nd >= span ? span : nd; + memset(u, 0, sizeof u); + for (int i = 0; i < n; i++) u[i] = rng() % lim; + u[0] = 0; u[n - 1] = lim - 1; + uint64_t len = dict_body((uint8_t*)bodyw, u, w, base); + snprintf(what, sizeof what, "DICT type %d dict %u w %d n %d", dtypes[ti], nd, w, n); + test_result_t r = dict_kernel_case(dtypes[ti], dv, nd, (const uint8_t*)bodyw, len, n, 0, NULL, what); + if (r.status != TEST_PASS) return r; + /* nulls in the bitmap fold in (any code underneath) */ + memset(bm, 0, sizeof bm); + int nn = 0; + for (int i = 0; i < n; i += 11) { bm[i >> 3] |= (uint8_t)(1u << (i & 7)); nn++; } + snprintf(what, sizeof what, "DICT nulls type %d dict %u w %d n %d", dtypes[ti], nd, w, n); + if ((r = dict_kernel_case(dtypes[ti], dv, nd, (const uint8_t*)bodyw, len, n, nn, bm, what)).status != TEST_PASS) + return r; + } + } + } + PASS(); +} + +/* Every check of the reference DICT path stands in the kernel: a code at + * the dictionary size, a child header or size off, a RAW code child, a + * dictionary value on the sentinel outside the bitmap, a dictionary entry + * one byte short. The kernel declines (the reference reports or decodes + * it); through a file, the code outside the dictionary is `corrupt` on + * every read. */ +static test_result_t test_dict_kernel_shapes(void) { + static uint64_t u[RAY_ENC_VEC], bodyw[RAY_ENC_VEC / 2 + 4]; + static _Alignas(8) uint8_t out[RAY_ENC_VEC * 8]; + static const uint64_t dv3[3] = { 10, 20, 30 }; + const uint8_t* body = (const uint8_t*)bodyw; + for (int i = 0; i < RAY_ENC_VEC; i++) u[i] = (uint64_t)(i % 3); + uint64_t len = dict_body((uint8_t*)bodyw, u, 2, 0); + TEST_ASSERT_EQ_I(ray_enccol_test_decode_dict(RAY_I64, dv3, 3, 0, NULL, body, len, RAY_ENC_VEC, true, out), 1); + /* a dictionary value on the sentinel under the bitmap: a null */ + static const uint64_t dvs[3] = { 0x8000000000000000ull, 20, 30 }; + { + static uint8_t bm[RAY_ENC_VEC / 8]; + memset(bm, 0, sizeof bm); + int nn = 0; + for (int i = 0; i < RAY_ENC_VEC; i += 3) { bm[i >> 3] |= (uint8_t)(1u << (i & 7)); nn++; } + TEST_ASSERT_EQ_I(ray_enccol_test_decode_dict(RAY_I64, dvs, 3, nn, bm, body, len, RAY_ENC_VEC, false, out), 1); + TEST_ASSERT_EQ_I(ray_enccol_test_decode_dict(RAY_I64, dvs, 3, nn, bm, body, len, RAY_ENC_VEC, true, out), 1); + TEST_ASSERT_TRUE(((int64_t*)out)[0] == NULL_I64 && ((int64_t*)out)[1] == 20); + } + /* a RAW code child decodes by the reference path only */ + { + uint8_t* p = (uint8_t*)bodyw; + memset(p, 0, 8 + RAY_ENC_VEC * 4); + uint32_t bb = RAY_ENC_VEC * 4; + p[0] = RAY_ENC_RAW; memcpy(p + 4, &bb, 4); + for (int i = 0; i < RAY_ENC_VEC; i++) { uint32_t c = (uint32_t)(i % 3); memcpy(p + 8 + 4 * i, &c, 4); } + TEST_ASSERT_EQ_I(ray_enccol_test_decode_dict(RAY_I64, dv3, 3, 0, NULL, p, 8 + bb, RAY_ENC_VEC, true, out), 0); + TEST_ASSERT_EQ_I(ray_enccol_test_decode_dict(RAY_I64, dv3, 3, 0, NULL, p, 8 + bb, RAY_ENC_VEC, false, out), 1); + } + PASS(); +} + +/* Task 17b: the CONST / RLE point read equals the reference decode on every + * row, for every integer kind, lengths 1024, 1000, 77 and 1, run counts + * 1..1024 and every legal child pair; a run whose value is outside the + * vector's statistics is `corrupt` (-1) at its rows. */ +static test_result_t test_point_read_runs(void) { + static const int8_t types[] = { RAY_U8, RAY_BOOL, RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, RAY_TIMESTAMP }; + static const int lens[] = { 1024, 1000, 77, 1 }; + static const int runs[] = { 1, 2, 7, 17, 64, 65, 257, 512, 1023, 1024 }; + static const uint8_t kids[][2] = { + { 0xFF, 0xFF }, { RAY_ENC_RAW, RAY_ENC_RAW }, { RAY_ENC_RAW, RAY_ENC_FOR_BP }, { RAY_ENC_RAW, RAY_ENC_DELTA_BP }, + { RAY_ENC_FOR_BP, RAY_ENC_RAW }, { RAY_ENC_FOR_BP, RAY_ENC_FOR_BP }, { RAY_ENC_FOR_BP, RAY_ENC_DELTA_BP }, + }; + static uint64_t vals[RAY_ENC_VEC], ends[RAY_ENC_VEC], rows[RAY_ENC_VEC]; + char what[160]; + long cases = 0; + g_seed = 0x17b; + for (size_t ti = 0; ti < sizeof types / sizeof types[0]; ti++) { + const int8_t type = types[ti]; + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(type, 0, &k)); + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + const int n = lens[li]; + for (size_t ri = 0; ri < sizeof runs / sizeof runs[0]; ri++) { + const int nr = runs[ri]; + if (nr > n) continue; + rk_vals(k, false, nr, ri & 1, vals); + rk_ends(n, nr, ends); + for (int i = 0, p = 0; i < nr; p = (int)ends[i++]) + for (int r = p; r < (int)ends[i]; r++) rows[r] = vals[i]; + for (size_t c = 0; c < sizeof kids / sizeof kids[0]; c++) { + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + bool ok = kids[c][0] == 0xFF ? ray_enc_write_as(RAY_ENC_RLE, rows, n, k, NULL, &b, &ch) + : rk_rle(&b, k, vals, ends, nr, kids[c][0], kids[c][1]); + TEST_ASSERT_FMT(ok, "type %d: build", type); + snprintf(what, sizeof what, "RLE type %d n %d nr %d kids %u/%u", type, n, nr, kids[c][0], kids[c][1]); + test_result_t r = point_case(type, RAY_ENC_RLE, NULL, 0, 0, b.p, b.len, n, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + cases++; + } + if (nr == 1) { + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_CONST, rows, n, k, NULL, &b, &ch)); + snprintf(what, sizeof what, "CONST type %d n %d", type, n); + test_result_t r = point_case(type, RAY_ENC_CONST, NULL, 0, 0, b.p, b.len, n, what); + ray_enc_buf_free(&b); + if (r.status != TEST_PASS) return r; + } + } + } + } + TEST_ASSERT_TRUE(cases > 1000); + /* I32 runs 10, 20, 30 (rows 0..99, 100..599, 600..1023) */ + const ray_enc_kind_t k32 = { 32, true, false }; + const uint64_t v3[3] = { 10, 20, 30 }, e3[3] = { 100, 600, 1024 }; + ray_enc_buf_t b = { 0 }; + TEST_ASSERT_TRUE(rk_rle(&b, k32, v3, e3, 3, RAY_ENC_RAW, RAY_ENC_RAW)); + static int64_t pv[RAY_ENC_VEC]; static int8_t res[RAY_ENC_VEC]; + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_I32, NULL, 0, RAY_ENC_RLE, 0, 0, b.p, b.len, RAY_ENC_VEC, pv, res), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) + TEST_ASSERT_FMT(res[i] == 1 && pv[i] == (i < 100 ? 10 : i < 600 ? 20 : 30), "row %d", i); + /* a run vector with nulls declines every row (the bitmap decides) */ + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_I32, NULL, 0, RAY_ENC_RLE, 0, 1, b.p, b.len, RAY_ENC_VEC, pv, res), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_FMT(res[i] == 0, "nulls: row %d %d", i, res[i]); + /* a descriptor width on a run body declines */ + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_I32, NULL, 0, RAY_ENC_RLE, 3, 0, b.p, b.len, RAY_ENC_VEC, pv, res), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_EQ_I(res[i], 0); + ray_enc_buf_free(&b); + PASS(); +} + +/* A point read never serves a row the decode would refuse: on nulls, the + * sentinel, any other codec, and every corruption it reads, it declines. */ +static test_result_t test_point_read_declines(void) { + static uint64_t v[RAY_ENC_VEC], bodyw[RAY_ENC_VEC / 2 + 4]; + static int64_t pv[RAY_ENC_VEC]; static int8_t res[RAY_ENC_VEC]; + static uint8_t ref[RAY_ENC_VEC * 8]; + ray_enc_kind_t k32 = { 32, true, false }; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(uint32_t)(int32_t)(i % 300 - 100); + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_FOR_BP, v, RAY_ENC_VEC, k32, NULL, &b, &ch)); + /* nulls in the vector: the bitmap decides */ + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_I32, NULL, 0, RAY_ENC_FOR_BP, ch.width, 3, b.p, b.len, RAY_ENC_VEC, pv, res), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_EQ_I(res[i], 0); + ray_enc_buf_free(&b); + /* RAW and DELTA_BP decline; CONST and RLE are served (Task 17b) */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(uint32_t)(int32_t)(i / 100 * 3 - 7); + static const uint8_t others[] = { RAY_ENC_RAW, RAY_ENC_CONST, RAY_ENC_DELTA_BP, RAY_ENC_RLE }; + for (size_t o = 0; o < sizeof others; o++) { + if (others[o] == RAY_ENC_CONST) for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 5; + TEST_ASSERT_TRUE(ray_enc_write_as(others[o], v, RAY_ENC_VEC, k32, NULL, &b, &ch)); + TEST_ASSERT_EQ_I(ray_enccol_test_decode_body(RAY_I32, 0, others[o], ch.width, 0, NULL, b.p, b.len, RAY_ENC_VEC, false, 0, ref), 1); + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_I32, NULL, 0, others[o], ch.width, 0, b.p, b.len, RAY_ENC_VEC, pv, res), 0); + const bool runs = others[o] == RAY_ENC_CONST || others[o] == RAY_ENC_RLE; + for (int i = 0; i < RAY_ENC_VEC; i++) { + TEST_ASSERT_FMT(res[i] == (runs ? 1 : 0), "codec %u row %d: %d", others[o], i, res[i]); + TEST_ASSERT_FMT(!runs || pv[i] == ((const int32_t*)ref)[i], "codec %u row %d", others[o], i); + } + ray_enc_buf_free(&b); + } + /* SYM and the float types are never point-read */ + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_FOR_BP, v, RAY_ENC_VEC, k32, NULL, &b, &ch)); + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_SYM, NULL, 0, RAY_ENC_FOR_BP, ch.width, 0, b.p, b.len, 8, pv, res), 0); + for (int i = 0; i < 8; i++) TEST_ASSERT_EQ_I(res[i], 0); + ray_enc_buf_free(&b); + static const uint64_t dv3[3] = { 10, 20, 30 }; + /* a RAW code child is sound, but not a body the point read takes */ + { + uint8_t* p = (uint8_t*)bodyw; + memset(p, 0, 8 + RAY_ENC_VEC * 4); + uint32_t bb = RAY_ENC_VEC * 4; + p[0] = RAY_ENC_RAW; memcpy(p + 4, &bb, 4); + for (int i = 0; i < RAY_ENC_VEC; i++) { uint32_t c = (uint32_t)(i % 3); memcpy(p + 8 + 4 * i, &c, 4); } + TEST_ASSERT_EQ_I(ray_enccol_test_decode_dict(RAY_I64, dv3, 3, 0, NULL, p, 8 + bb, RAY_ENC_VEC, false, ref), 1); + TEST_ASSERT_EQ_I(ray_enccol_test_point_body(RAY_I64, dv3, 3, RAY_ENC_DICT, 0, 0, p, 8 + bb, RAY_ENC_VEC, pv, res), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_EQ_I(res[i], 0); + } + PASS(); +} + +/* Through a loaded column: every row of a FOR_BP, DICT, CONST or RLE vector + * without nulls is served and equals the materialization; vectors with + * nulls and other codecs decline; nothing is decoded; a materialized column + * declines (its cursor reads it in place). */ +static test_result_t test_point_read_column(void) { + static const int64_t big[4] = { -900000000001ll, 11, 77, 123456789012345ll }; + const int64_t n = 70000; + ray_t* a = ray_vec_new(RAY_I32, n); a->len = n; + ray_t* d = ray_vec_new(RAY_I64, n); d->len = n; + for (int64_t i = 0; i < n; i++) { + ((int32_t*)ray_data(a))[i] = (i / 1024) % 5 == 3 && i % 97 == 0 ? NULL_I32 : (int32_t)((i * 7919) % 100000 - 50000); + ((int64_t*)ray_data(d))[i] = big[(uint32_t)((uint32_t)i * 2654435761u) >> 30]; + } + a->attrs |= RAY_ATTR_HAS_NULLS; + /* runs (Task 17b): RLE vectors of runs of 100, CONST vectors (from row + * 20480), a null in every eleventh vector */ + ray_t* q = ray_vec_new(RAY_I16, n); q->len = n; + for (int64_t i = 0; i < n; i++) + ((int16_t*)ray_data(q))[i] = (i / 1024) % 11 == 4 && i % 1024 == 9 ? NULL_I16 + : i >= 20480 && i < 40960 ? (int16_t)-3 : (int16_t)((i / 100) % 7 - 2); + q->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* src[3] = { a, d, q }; + const char* names[3] = { ENCCOL_TMP "/pa", ENCCOL_TMP "/pd", ENCCOL_TMP "/pq" }; + for (int c = 0; c < 3; c++) { + TEST_ASSERT_EQ_I(ray_col_save_gen(src[c], ray_test_tmp(names[c]), 2), RAY_OK); + ray_t* col = ray_col_mmap(ray_test_tmp(names[c])); + TEST_ASSERT_TRUE(col && !RAY_IS_ERR(col)); + ray_enccol_t* e = ray_enccol_of(col); + ray_col_src_t s; + TEST_ASSERT_NULL(ray_col_src_bind(col, &s)); + ray_enc_counters_reset(); + int64_t served = 0, declined = 0; + for (int64_t r = 0; r < n; r++) { + int64_t x = 0; ray_t* err = NULL; + int pr = ray_col_src_point_i64(&s, r, &x, &err); + TEST_ASSERT_FMT(pr >= 0 && !err, "col %d row %lld: %d", c, (long long)r, pr); + const ray_enc_desc_t dd = ray_enccol_descs(e, r / RAY_ENC_CHUNK)[r % RAY_ENC_CHUNK / RAY_ENC_VEC]; + bool want = !dd.n_nulls && (dd.encoding == RAY_ENC_FOR_BP || dd.encoding == RAY_ENC_DICT || + dd.encoding == RAY_ENC_CONST || dd.encoding == RAY_ENC_RLE); + TEST_ASSERT_FMT(pr == (want ? 1 : 0), "col %d row %lld: %d, encoding %u nulls %u", c, (long long)r, pr, + dd.encoding, dd.n_nulls); + if (pr == 1) { + served++; + TEST_ASSERT_FMT(x == gen0_at(src[c]->type, ray_data(src[c]), (int)r), "col %d row %lld", c, (long long)r); + } else declined++; + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_TRUE(served > n / 2); + if (c == 0) TEST_ASSERT_TRUE(declined >= 13 * 1024); /* the vectors with nulls, the RAW tail */ + if (c == 2) { /* every RLE and CONST vector without nulls */ + int64_t runs = 0; + for (int64_t v = 0; v * RAY_ENC_VEC < n; v++) { + const ray_enc_desc_t dd = ray_enccol_descs(e, v * RAY_ENC_VEC / RAY_ENC_CHUNK)[v % RAY_ENC_VECS_PER_CHUNK]; + runs += !dd.n_nulls && (dd.encoding == RAY_ENC_RLE || dd.encoding == RAY_ENC_CONST); + TEST_ASSERT_TRUE(dd.encoding == RAY_ENC_RLE || dd.encoding == RAY_ENC_CONST); + } + TEST_ASSERT_TRUE(runs >= 50); + } + ray_t* m = ray_enccol_materialize(col); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + int64_t x; ray_t* err = NULL; + TEST_ASSERT_EQ_I(ray_col_src_point_i64(&s, 5, &x, &err), 0); + ray_col_src_release(&s); + ray_release(col); + } + ray_release(a); ray_release(d); ray_release(q); + PASS(); +} + +/* The scratch references the column it counts for: freeing it after its + * source and column are released is safe and still counts (ASan). */ +static test_result_t test_scratch_outlives_source(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/so"); + TEST_ASSERT_EQ_I(save_i32_rows(p, 5000), RAY_OK); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_col_range_t r; + ray_enc_counters_reset(); + int64_t live = ray_enccol_test_live(); + TEST_ASSERT_NULL(ray_col_range(&s, 1024, 1024, &sc, &r)); + ray_col_src_release(&s); + ray_release(c); /* the scratch's reference keeps the column */ + TEST_ASSERT_EQ_I(ray_enccol_test_live(), live); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* not counted yet */ + ray_col_scratch_free(&sc); /* counts, then drops the last reference */ + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 1024 * 4); + TEST_ASSERT_EQ_I(ray_enccol_test_live(), live - 1); + PASS(); +} + +/* Concurrent first touch: eight threads range-read every vector of the same + * unvalidated chunk at once, each in its own order; every answer is right + * and the chunk ends validated. */ +typedef struct { ray_col_src_t* s; int seed; int bad; } ftouch_t; +/* ---- hardening: crafted input never reads out of bounds, never half-writes ---- */ + +#define CANARY 0xA5 + +static test_result_t test_payload_is_tail(void) { + /* force -1: selection. P5: a float column selects DICT, whose + * VALUE_DICT follows the payload; the float cases are forced to the + * float bodies without side data, so the payload stays the tail. + * P6: the same for STR, whose STR_DICT / FSST entries follow the + * payload; the side data being absent is this test's subject, so the + * STR cases are forced RAW. */ + static const struct { int8_t type; int s; int force; } cases[] = { + { RAY_I32, 1, -1 }, { RAY_I64, 3, -1 }, { RAY_I16, 4, -1 }, { RAY_U8, 0, -1 }, { RAY_BOOL, 2, -1 }, + { RAY_F64, 0, RAY_ENC_RAW }, { RAY_F32, 4, RAY_ENC_RAW }, { RAY_F64, 0, RAY_ENC_RLE }, + { RAY_F64, 0, RAY_ENC_ALP }, { RAY_F32, 4, RAY_ENC_ALP }, { RAY_F64, 4, RAY_ENC_ALP_RD }, + { RAY_GUID, 0, -1 }, { RAY_STR, 0, RAY_ENC_RAW }, { RAY_STR, 3, RAY_ENC_RAW }, { RAY_SYM, 1, -1 }, + }; + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + ray_t* v = make_col(cases[i].type, 1000, cases[i].s); + ray_encw_test_force(cases[i].force); + ray_err_t se = ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/tb"), 2); + ray_encw_test_force(-1); + ray_release(v); + TEST_ASSERT_EQ_I(se, RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/tb")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_EQ_U(ray_enccol_of(c)->hdr.side_off, 0); /* the payload is the file's tail */ + if (cases[i].force >= 0) { + int enc = ray_enccol_descs(ray_enccol_of(c), 0)[0].encoding; + TEST_ASSERT_FMT(enc == cases[i].force, "type %d shape %d: encoding %d, forced %d", + (int)cases[i].type, cases[i].s, enc, cases[i].force); + } + ray_release(c); + } + PASS(); +} + +/* A DICT body is refused without a usable dictionary. The explicit NULL + * guards in the codec's size / write / read bodies sit behind the + * legality check every public entry runs first, so they are not reachable + * directly; this pins the observable behaviour of the public entries. */ +static test_result_t test_dict_null_dictionary(void) { + uint64_t v[16]; uint64_t dv[2] = { 10, 20 }; + for (int i = 0; i < 16; i++) v[i] = dv[i & 1]; + ray_enc_kind_t k; TEST_ASSERT_TRUE(ray_enc_kind_of(RAY_I64, 0, &k)); + ray_enc_dict_t d = { dv, 2 }; + ray_enc_buf_t buf = {0}, buf2 = {0}; ray_enc_choice_t ch; + bool wrote = ray_enc_write_as(RAY_ENC_DICT, v, 16, k, &d, &buf, &ch); + bool wrote_null = ray_enc_write_as(RAY_ENC_DICT, v, 16, k, NULL, &buf2, &ch); + uint64_t out[16]; + int64_t good = wrote ? ray_enc_read(buf.p, buf.len, RAY_ENC_DICT, 0, 16, k, RAY_ENC_SLOT_TOP, 0, &d, out) : -2; + size_t blen = buf.len; + ray_enc_buf_free(&buf); ray_enc_buf_free(&buf2); + TEST_ASSERT_TRUE(wrote); + TEST_ASSERT_FALSE(wrote_null); + TEST_ASSERT_EQ_I(good, (int64_t)blen); + for (int i = 0; i < 16; i++) TEST_ASSERT_EQ_U(out[i], dv[i & 1]); + PASS(); +} + +/* Out-of-range vector numbers are refused by every column-global entry. */ +static test_result_t test_vec_range_checks(void) { + ray_t* v = make_col(RAY_STR, 2500, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/vr"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/vr")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_t* e = ray_enccol_of(c); + int64_t nv = ray_enc_nvecs(e->len); + TEST_ASSERT_EQ_I(nv, 3); + static const int64_t bad[] = { -1, 3, 64, 1000000 }; + int bad_ok = 1; + for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) { + uint64_t pb = 7; + ray_t* err = ray_enccol_vec_pool_bytes(e, bad[i], &pb); + if (!err || strcmp(ray_err_code(err), "range") != 0 || pb != 0) bad_ok = 0; + if (err) ray_error_free(err); + } + uint64_t pb; + ray_t* e0 = ray_enccol_vec_pool_bytes(e, nv - 1, &pb); + int good_ok = e0 == NULL; + if (e0) ray_error_free(e0); + ray_release(c); + TEST_ASSERT_TRUE(bad_ok); + TEST_ASSERT_TRUE(good_ok); + PASS(); +} + +/* ---- Task 8: materialization ---- */ + +/* Same vector saved as generation 0 and 2: the generation-0 load and the + * materialized generation-2 column are equal. */ +static test_result_t check_equivalence(ray_t* v) { + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/g0"), 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/g2"), 2), RAY_OK); + ray_t* a = ray_col_load(ray_test_tmp(ENCCOL_TMP "/g0")); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/g2")); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && c && !RAY_IS_ERR(c)); + ray_t* b = ray_enccol_materialize(c); + TEST_ASSERT_FMT(b && !RAY_IS_ERR(b), "materialize: %s", b ? ray_err_code(b) : "null"); + TEST_ASSERT_EQ_I(b->type, a->type); + TEST_ASSERT_EQ_I(b->len, a->len); + TEST_ASSERT_EQ_I(b->attrs & COL_DISK_ATTRS_MASK, a->attrs & COL_DISK_ATTRS_MASK); + if (a->type == RAY_STR) { + const ray_str_t* x = ray_data(a); const ray_str_t* y = ray_data(b); + const char* px = a->str_pool ? ray_data(a->str_pool) : NULL; + const char* py = b->str_pool ? ray_data(b->str_pool) : NULL; + for (int64_t i = 0; i < a->len; i++) { + TEST_ASSERT_FMT(x[i].len == y[i].len, "len row %lld", (long long)i); + TEST_ASSERT_FMT(memcmp(ray_str_t_ptr(&x[i], px), ray_str_t_ptr(&y[i], py), x[i].len) == 0, "row %lld", (long long)i); + if (!ray_str_is_inline(&y[i])) TEST_ASSERT_FMT(y[i].hash32 == x[i].hash32, "hash32 row %lld", (long long)i); + } + } else { + TEST_ASSERT_TRUE(memcmp(ray_data(a), ray_data(b), (size_t)a->len * ray_sym_elem_size(a->type, a->attrs)) == 0); + } + if (a->type == RAY_SYM) { + TEST_ASSERT_EQ_I(b->attrs & RAY_SYM_W_MASK, a->attrs & RAY_SYM_W_MASK); /* width class */ + TEST_ASSERT_EQ_PTR(ray_sym_vec_domain(b), ray_sym_vec_domain(a)); /* domain */ + } + TEST_ASSERT_EQ_PTR(ray_enccol_materialize(c), b); /* cached */ + ray_retain(b); + ray_release(c); /* retained column outlives the object */ + TEST_ASSERT_EQ_I(b->len, a->len); + ray_release(b); + ray_release(a); + PASS(); +} + +static test_result_t test_materialize_equivalence(void) { + static const int8_t types[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, + RAY_TIMESTAMP, RAY_F32, RAY_F64, RAY_GUID, RAY_SYM, RAY_STR }; + for (size_t t = 0; t < sizeof types; t++) + for (int s = 0; s < 6; s++) { + if ((types[t] == RAY_BOOL || types[t] == RAY_U8) && s >= 4) continue; + ray_t* v = make_col(types[t], 140000, s); /* three chunks, parallel decode */ + test_result_t r = check_equivalence(v); + ray_release(v); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Every type with nulls at the boundary lengths; SYM at every width. */ +static test_result_t test_materialize_lengths(void) { + static const int8_t types[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_DATE, RAY_TIME, + RAY_TIMESTAMP, RAY_F32, RAY_F64, RAY_GUID, RAY_SYM, RAY_STR }; + static const int64_t lens[] = { 0, 1, 1023, 1024, 1025, 65535, 65536, 65537 }; + static const uint8_t widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; + for (size_t t = 0; t < sizeof types; t++) + for (size_t l = 0; l < sizeof lens / sizeof *lens; l++) + for (int s = 0; s < 5; s += 4) /* shapes 0 (no nulls) and 4 (nulls) */ + for (size_t w = 0; w < (types[t] == RAY_SYM ? 4u : 1u); w++) { + g_symw = widths[w]; + ray_t* v = make_col(types[t], lens[l], s); + test_result_t r = check_equivalence(v); + ray_release(v); + g_symw = RAY_SYM_W16; + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Float payloads survive bit for bit: NaN payloads, -0.0, infinities, the null sentinel. */ +static test_result_t test_materialize_float_bits(void) { + static const uint64_t d64[] = { 0x7ff8000000000123ull, 0x7ff0000000000001ull, 0x8000000000000000ull, + 0x0000000000000000ull, 0x7ff0000000000000ull, 0xfff0000000000000ull, + 0xfff8000000000abcull, 0x3ff0000000000000ull }; + static const uint32_t d32[] = { 0x7fc00123u, 0x7f800001u, 0x80000000u, 0u, 0x7f800000u, 0xff800000u, 0xffc00abcu, 0x3f800000u }; + for (int k = 0; k < 2; k++) { + int64_t n = 70000; + ray_t* v = ray_vec_new(k ? RAY_F32 : RAY_F64, n); v->len = n; + for (int64_t i = 0; i < n; i++) { + if (k) memcpy((uint8_t*)ray_data(v) + i * 4, &d32[(i / 3) % 8], 4); + else memcpy((uint8_t*)ray_data(v) + i * 8, &d64[(i / 3) % 8], 8); + } + test_result_t r = check_equivalence(v); + ray_release(v); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* ---- Task 25: decoded peek and the in-place column list ---- */ + +static void peek_thread(void* arg) { + ray_t* c = arg; + for (int i = 0; i < 20000; i++) { + ray_t* d = ray_enccol_decoded_peek(c); + if (d) (void)d->len; + } +} +static void peek_mat_thread(void* arg) { (void)ray_enccol_materialize((ray_t*)arg); } + +static test_result_t test_decoded_peek(void) { + ray_t* v = make_col(RAY_I64, 5000, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/pk"), 2), RAY_OK); + ray_release(v); + ray_enc_counters_reset(); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/pk")); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(c)); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); /* a peek decodes nothing */ + ray_thread_t th[3]; + ray_thread_create(&th[0], peek_thread, c); + ray_thread_create(&th[1], peek_thread, c); + ray_thread_create(&th[2], peek_mat_thread, c); + for (int i = 0; i < 3; i++) ray_thread_join(th[i]); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(c), m); + ray_release(c); + PASS(); +} + +static test_result_t test_cols_inplace_encoded(void) { + ray_t* v = make_col(RAY_I64, 100, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/ci"), 2), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/ci")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("a", 1), v); + TEST_ASSERT_TRUE(ray_table_cols_inplace(t) != NULL); + t = ray_table_add_col(t, ray_sym_intern("b", 1), c); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + TEST_ASSERT_NULL(ray_table_cols_inplace(t)); /* an encoded slot refuses */ + ray_release(t); ray_release(c); ray_release(v); + PASS(); +} + +static test_result_t test_materialize_counts_once(void) { + ray_t* v = make_col(RAY_I64, 5000, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/m"), 2), RAY_OK); + ray_release(v); + ray_enc_counters_reset(); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/m")); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); /* load decodes nothing */ + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + ray_t* a = ray_enccol_materialize(c); ray_t* b = ray_enccol_materialize(c); + TEST_ASSERT_EQ_PTR(a, b); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + TEST_ASSERT_EQ_U(k.decoded_bytes, 5000 * 8); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(c)->decoded_bytes), 5000 * 8); /* per column */ + ray_release(c); + PASS(); +} + +/* Cancellation is transient: reported, not cached, retried. */ +static test_result_t test_cancel_retried(void) { + ray_t* v = make_col(RAY_I32, 3 * 65536, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/cn"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/cn")); + ray_request_interrupt(); + ray_t* r = ray_enccol_materialize(c); + ray_clear_interrupt(); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "cancel"); + ray_error_free(r); + r = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(c); + PASS(); +} + +/* The per-chunk poll: the interrupt arrives after chunk 0 has decoded. */ +static test_result_t test_cancel_mid_decode(void) { + ray_t* v = make_col(RAY_I32, 128 * 65536, 1); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/cm"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/cm")); + ray_enccol_test_interrupt_after(1); + ray_t* r = ray_enccol_materialize(c); + ray_enccol_test_interrupt_after(0); + ray_clear_interrupt(); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "cancel"); + ray_error_free(r); + TEST_ASSERT_TRUE(atomic_load(&ray_enccol_of(c)->decoded_bytes) < (uint64_t)128 * 65536 * 4); /* stopped early */ + r = ray_enccol_materialize(c); /* retried */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(c); + PASS(); +} + +/* A waiter on a cancelled attempt receives the attempt's "cancel". */ +typedef struct { ray_t* c; char code[8]; } cwait_t; /* code: "" on success */ +static void cancel_wait_thread(void* raw) { + cwait_t* t = raw; + ray_t* r = ray_enccol_materialize(t->c); + t->code[0] = 0; + if (r && RAY_IS_ERR(r)) { snprintf(t->code, sizeof t->code, "%s", ray_err_code(r)); ray_error_free(r); } + ray_heap_abandon(); +} +static test_result_t test_cancel_waiter(void) { + ray_t* v = make_col(RAY_I32, 128 * 65536, 1); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/cw"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/cw")); + ray_enccol_t* e = ray_enccol_of(c); + cwait_t p = { c, "" }, w = { c, "" }; + ray_thread_t tp, tw; + ray_thread_create(&tp, cancel_wait_thread, &p); + while (atomic_load(&e->once.state) != RAY_ENC_ONCE_RUNNING) ray_enc_yield(); + ray_thread_create(&tw, cancel_wait_thread, &w); + while (ray_enc_once_waiters(&e->once) < 1) ray_enc_yield(); + ray_request_interrupt(); + ray_thread_join(tp); ray_thread_join(tw); + ray_clear_interrupt(); + TEST_ASSERT_STR_EQ(p.code, "cancel"); + TEST_ASSERT_STR_EQ(w.code, "cancel"); + ray_t* r = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(c); + PASS(); +} + +/* ray_col_load_dom on a generation-2 SYM file: the loaded vector holds its own + * reference on the symfile domain (owned branch) and outlives the object. */ +static test_result_t test_load_dom_refcount(void) { + const char* p = ray_test_tmp(ENCCOL_TMP "/ld"); + TEST_ASSERT_NULL(sym_col_save(p)); + ray_sym_domain_t* dom = ray_sym_domain_new(); + for (int i = 0; i < 400; i++) { char b[12]; int n = snprintf(b, sizeof b, "d%d", i); (void)ray_sym_domain_intern(dom, b, (size_t)n); } + ray_t* b = ray_col_load_dom(p, dom); + TEST_ASSERT_TRUE(b && !RAY_IS_ERR(b)); + TEST_ASSERT_EQ_I(b->type, RAY_SYM); + TEST_ASSERT_EQ_PTR(ray_sym_vec_domain(b), dom); + ray_sym_domain_release(dom); /* ours; the vector keeps the domain alive */ + ray_t* s = ray_sym_domain_str(ray_sym_vec_domain(b), 1); + TEST_ASSERT_TRUE(s != NULL); + ray_release(b); /* last reference: frees the domain (ASan checks) */ + PASS(); +} + +static test_result_t test_oom_then_retry(void) { + ray_t* v = make_col(RAY_STR, 3000, 2); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/o"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/o")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + /* P6: the column selects STR_DICT, whose validated dictionary is a + * once-state the column keeps after the first successful validation + * (a cache, not a leak). Validate it before the baseline so the + * no-leak check counts only what one materialization attempt owns. */ + const ray_enc_sdict_t* sd = NULL; + ray_t* se = ray_enccol_strdict(ray_enccol_of(c), &sd); + TEST_ASSERT_NULL(se); + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + bool done = false; + for (int nth = 1; nth <= 16 && !done; nth++) { /* until an attempt passes every injection point */ + ray_enccol_test_fail_alloc(nth); + ray_t* r = ray_enccol_materialize(c); + ray_enccol_test_fail_alloc(0); + if (r && RAY_IS_ERR(r)) { + TEST_ASSERT_STR_EQ(ray_err_code(r), "oom"); + ray_error_free(r); + ray_mem_stats(&m1); + TEST_ASSERT_FMT(m1.bytes_allocated == m0.bytes_allocated, "nth %d: %llu vs %llu", nth, (unsigned long long)m1.bytes_allocated, (unsigned long long)m0.bytes_allocated); /* a failed attempt freed everything */ + } else done = true; + } + TEST_ASSERT_TRUE(done); + ray_t* r = ray_enccol_materialize(c); /* the success is cached */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(c); + PASS(); +} + +static test_result_t test_col_load_materializes(void) { + ray_t* v = make_col(RAY_F64, 2000, 4); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/l"), 2), RAY_OK); + ray_t* b = ray_col_load(ray_test_tmp(ENCCOL_TMP "/l")); + TEST_ASSERT_TRUE(b && !RAY_IS_ERR(b)); + TEST_ASSERT_EQ_I(b->type, RAY_F64); + TEST_ASSERT_TRUE(memcmp(ray_data(b), ray_data(v), 2000 * 8) == 0); + ray_release(b); ray_release(v); + PASS(); +} + +static ray_t* save_and_materialize(ray_t* v, const char* path, ray_t** keep) { + if (ray_col_save_gen(v, path, 2) != RAY_OK) return ray_error("io", NULL); + *keep = ray_col_mmap(path); + if (!*keep || RAY_IS_ERR(*keep)) return *keep; + return ray_enccol_materialize(*keep); +} + +/* Overwrite rows [from, to) of an 8- or 4-byte element column with its null. */ +static void null_rows(ray_t* v, int64_t from, int64_t to) { + uint8_t* d = ray_data(v); + for (int64_t i = from; i < to; i++) + switch (v->type) { + case RAY_I32: case RAY_DATE: case RAY_TIME: { int32_t x = NULL_I32; memcpy(d + i * 4, &x, 4); break; } + case RAY_I64: case RAY_TIMESTAMP: { int64_t x = NULL_I64; memcpy(d + i * 8, &x, 8); break; } + case RAY_F64: { double x = NULL_F64; memcpy(d + i * 8, &x, 8); break; } + default: break; + } +} + +static test_result_t test_synth_zone(void) { + static const int8_t types[] = { RAY_I32, RAY_I64, RAY_F64 }; + for (size_t t = 0; t < 3; t++) { + int64_t n = 2 * 65536 + 5000; /* three chunks */ + ray_t* v = make_col(types[t], n, 4); + if (types[t] == RAY_F64) { /* -0.0 / +0.0 tie across a chunk boundary */ + double* f = ray_data(v); + for (int64_t i = 0; i < n; i++) if (f[i] == 0.0 || f[i] < 0.0) f[i] = 1.0; + f[65535] = 0.0; f[65536] = -0.0; f[10] = 5.0; + f[2 * 65536 - 1] = -0.0; f[2 * 65536] = 0.0; + for (int64_t i = 0; i < n; i++) if (i != 65535 && i != 65536 && i != 2 * 65536 - 1 && i != 2 * 65536 && f[i] <= 0.0) f[i] = 1.0; + for (int64_t i = 0; i < 65535; i += 7) f[i] = 2.0; + } + ray_t* z = ray_index_attach_zone(&v); + TEST_ASSERT_TRUE(z && !RAY_IS_ERR(z)); + v = z; + ray_t* keep = NULL; + ray_t* m = save_and_materialize(v, ray_test_tmp(ENCCOL_TMP "/z"), &keep); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_ZONE); + ray_index_t* a = ray_index_payload(v->index); + ray_index_t* b = ray_index_payload(m->index); + if (types[t] == RAY_F64) { + TEST_ASSERT_TRUE(memcmp(&b->u.zone.min_f, &a->u.zone.min_f, 8) == 0); /* bit-equal: the sign of a tie */ + TEST_ASSERT_TRUE(memcmp(&b->u.zone.max_f, &a->u.zone.max_f, 8) == 0); + } else { + TEST_ASSERT_EQ_I(b->u.zone.min_i, a->u.zone.min_i); + TEST_ASSERT_EQ_I(b->u.zone.max_i, a->u.zone.max_i); + } + TEST_ASSERT_EQ_I(b->u.zone.n_nulls, a->u.zone.n_nulls); + TEST_ASSERT_EQ_I(b->built_for_len, n); + ray_release(keep); ray_release(v); + } + PASS(); +} + +/* The synthesized chunk zone's arrays equal the builder's, aggs only when + * the type is summable (NULL otherwise). */ +static test_result_t chunk_zone_equal(ray_t* b_idx, ray_t* a_idx, bool summable) { + ray_index_t* a = ray_index_payload(a_idx); + ray_index_t* b = ray_index_payload(b_idx); + uint32_t nc = a->u.chunk_zone.n_chunks; + TEST_ASSERT_EQ_I(b->u.chunk_zone.n_chunks, nc); + TEST_ASSERT_EQ_I(b->u.chunk_zone.chunk_log2, a->u.chunk_zone.chunk_log2); + TEST_ASSERT_EQ_I(b->u.chunk_zone.is_f64, a->u.chunk_zone.is_f64); + TEST_ASSERT_TRUE(memcmp(ray_data(b->u.chunk_zone.mins), ray_data(a->u.chunk_zone.mins), 8 * nc) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(b->u.chunk_zone.maxs), ray_data(a->u.chunk_zone.maxs), 8 * nc) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(b->u.chunk_zone.null_bits), ray_data(a->u.chunk_zone.null_bits), (nc + 7) / 8) == 0); + if (summable) { + TEST_ASSERT_TRUE(b->u.chunk_zone.aggs && a->u.chunk_zone.aggs); + TEST_ASSERT_TRUE(memcmp(ray_data(b->u.chunk_zone.aggs), ray_data(a->u.chunk_zone.aggs), 8 * 3 * nc) == 0); + } else { + TEST_ASSERT_TRUE(b->u.chunk_zone.aggs == NULL); + } + PASS(); +} + +/* CHUNK_ZONE synthesized at 64K chunks equals the builder's on the + * decoded vector, for integer, float and temporal columns with an all-null chunk. */ +static test_result_t test_synth_chunk_zone(void) { + static const int8_t types[] = { RAY_I64, RAY_F64, RAY_DATE, RAY_TIMESTAMP }; + for (size_t t = 0; t < 4; t++) { + int64_t n = 3 * 65536 + 17; + ray_t* v = make_col(types[t], n, 4); + null_rows(v, 65536, 2 * 65536); /* chunk 1 all null */ + ray_t* z = ray_index_attach_chunk_zone(&v, 16); + TEST_ASSERT_TRUE(z && !RAY_IS_ERR(z)); v = z; + ray_t* keep = NULL; + ray_t* m = save_and_materialize(v, ray_test_tmp(ENCCOL_TMP "/cz"), &keep); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_CHUNK_ZONE); + ray_t* ref = ray_index_chunk_zone_compute(m, 16); /* builder on the decoded data */ + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + test_result_t r = chunk_zone_equal(m->index, ref, ray_encw_type_summable(types[t])); + if (r.status != TEST_PASS) return r; + ray_release(ref); ray_release(keep); ray_release(v); + } + PASS(); +} + +static test_result_t test_unique_flag(void) { + int64_t d[100]; for (int i = 0; i < 100; i++) d[i] = i * 3; + ray_t* v = ray_vec_from_raw(RAY_I64, d, 100); + ray_t* root = ray_index_new_root(RAY_IDX_NONE, RAY_I64, 100); + ray_index_payload(root)->markers = RAY_MARK_UNIQUE; + ray_t* a = ray_index_attach_persisted(&v, root); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); v = a; + ray_t* keep = NULL; + ray_t* m = save_and_materialize(v, ray_test_tmp(ENCCOL_TMP "/u"), &keep); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + ray_enccol_t* e = ray_enccol_of(keep); + TEST_ASSERT_EQ_I(e->hdr.col_flags, RAY_ENC_FLAG_UNIQUE); + TEST_ASSERT_EQ_I(e->hdr.index_kind, 0); + TEST_ASSERT_TRUE(ray_index_has(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_NONE); + TEST_ASSERT_TRUE(ray_index_payload(m->index)->markers & RAY_MARK_UNIQUE); + ray_release(keep); ray_release(v); + PASS(); +} + +/* The matrix refuses a pair: on a file (GUID claiming UNIQUE) at load; on + * the attach itself the root is consumed exactly once (ASan would report a + * double release or a leak). */ +static test_result_t test_attach_refused(void) { + ray_t* v = make_col(RAY_GUID, 50, 0); + ray_t* root = ray_index_new_root(RAY_IDX_ZONE, RAY_GUID, v->len); + ray_t* r = ray_index_attach_persisted(&v, root); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "corrupt"); + ray_error_free(r); + TEST_ASSERT_FALSE(ray_index_has(v)); + ray_release(v); + PASS(); +} + + +/* A gen-2 load carries the same attachment a gen-0 load of the same vector + * with the same index does: ZONE and CHUNK_ZONE (integer, float, temporal; + * several chunks, nulls, an all-null chunk) plus UNIQUE on top. The gen-0 + * side is mmap'd: ray_col_load drops the index. */ +static test_result_t test_synth_matches_gen0(void) { + static const int8_t types[] = { RAY_I64, RAY_F64, RAY_DATE, RAY_TIMESTAMP }; + for (size_t t = 0; t < 4; t++) + for (int k = 0; k < 2; k++) { + int64_t n = 2 * 65536 + 5; + ray_t* v = make_col(types[t], n, 4); + null_rows(v, 65536, 2 * 65536); + ray_t* z = k ? ray_index_attach_chunk_zone(&v, 16) : ray_index_attach_zone(&v); + TEST_ASSERT_TRUE(z && !RAY_IS_ERR(z)); v = z; + ray_index_payload(v->index)->markers |= RAY_MARK_UNIQUE; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/g0"), 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/g2"), 2), RAY_OK); + ray_t* a = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/g0")); + ray_t* b = ray_col_load(ray_test_tmp(ENCCOL_TMP "/g2")); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && b && !RAY_IS_ERR(b)); + TEST_ASSERT_EQ_I(ray_index_kind(b), ray_index_kind(a)); + TEST_ASSERT_EQ_I(ray_index_kind(b), k ? RAY_IDX_CHUNK_ZONE : RAY_IDX_ZONE); + ray_index_t* ia = ray_index_payload(a->index); + ray_index_t* ib = ray_index_payload(b->index); + TEST_ASSERT_EQ_I(ib->markers & RAY_MARK_UNIQUE, ia->markers & RAY_MARK_UNIQUE); /* MMAP is residency */ + TEST_ASSERT_EQ_I(ib->built_for_len, ia->built_for_len); + if (k) { + /* gen-0 stores the builder's aggs for every integer type; gen 2 only where the directory has sums */ + bool sm = ray_encw_type_summable(types[t]); + uint32_t nc = ia->u.chunk_zone.n_chunks; + TEST_ASSERT_EQ_I(ib->u.chunk_zone.n_chunks, nc); + TEST_ASSERT_TRUE(memcmp(ray_data(ib->u.chunk_zone.mins), ray_data(ia->u.chunk_zone.mins), 8 * nc) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(ib->u.chunk_zone.maxs), ray_data(ia->u.chunk_zone.maxs), 8 * nc) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(ib->u.chunk_zone.null_bits), ray_data(ia->u.chunk_zone.null_bits), (nc + 7) / 8) == 0); + if (sm) TEST_ASSERT_TRUE(memcmp(ray_data(ib->u.chunk_zone.aggs), ray_data(ia->u.chunk_zone.aggs), 8 * 3 * nc) == 0); + else TEST_ASSERT_TRUE(ib->u.chunk_zone.aggs == NULL); + } else if (types[t] == RAY_F64) { + TEST_ASSERT_TRUE(memcmp(&ib->u.zone.min_f, &ia->u.zone.min_f, 8) == 0); + TEST_ASSERT_TRUE(memcmp(&ib->u.zone.max_f, &ia->u.zone.max_f, 8) == 0); + } else { + TEST_ASSERT_EQ_I(ib->u.zone.min_i, ia->u.zone.min_i); + TEST_ASSERT_EQ_I(ib->u.zone.max_i, ia->u.zone.max_i); + } + TEST_ASSERT_EQ_I(ib->u.zone.n_nulls * !k, ia->u.zone.n_nulls * !k); + ray_release(a); ray_release(b); ray_release(v); + } + PASS(); +} + +/* Write a table as a legacy splayed directory whose columns are generation 2. */ +static ray_err_t write_splayed_gen2(const char* dir, ray_t* tbl) { + if (ray_test_mkdir_p(dir) != 0) return RAY_ERR_IO; + int64_t nc = ray_table_ncols(tbl); + ray_t* names = ray_vec_new(RAY_STR, nc); + for (int64_t c = 0; c < nc; c++) { + ray_t* nm = ray_sym_str(ray_table_col_name(tbl, c)); + char p[512]; snprintf(p, sizeof p, "%s/%.*s", dir, (int)ray_str_len(nm), ray_str_ptr(nm)); + ray_err_t e = ray_col_save_gen(ray_table_get_col_idx(tbl, c), p, 2); + if (e != RAY_OK) { ray_release(names); return e; } + names = ray_str_vec_append(names, ray_str_ptr(nm), ray_str_len(nm)); + } + char p[512]; snprintf(p, sizeof p, "%s/.d", dir); + ray_err_t e = ray_col_save(names, p); + ray_release(names); + return e; +} + +static ray_t* tbl2(int64_t n) { + ray_t* t = ray_table_new(2); + ray_t* a = make_col(RAY_I64, n, 0); + ray_t* b = make_col(RAY_F64, n, 4); + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + t = ray_table_add_col(t, ray_sym_intern("b", 1), b); + ray_release(a); ray_release(b); + return t; +} + +/* Tables are built directly from mmap'd generation-2 columns, then loaded + * through the splayed loader, whose columns equal the generation-0 table. */ +static test_result_t test_table_core_enccol(void) { + ray_t* t = tbl2(70000); + TEST_ASSERT_EQ_I(write_splayed_gen2(ray_test_tmp(ENCCOL_TMP "/t"), t), RAY_OK); /* t: the generation-0 reference */ + ray_enc_counters_reset(); + ray_t* ca = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/t/a")); + ray_t* cb = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/t/b")); + TEST_ASSERT_FMT(ca && !RAY_IS_ERR(ca) && cb && !RAY_IS_ERR(cb), "mmap"); + TEST_ASSERT_EQ_I(ca->type, RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_table_col_nrows(ca), 70000); + ray_t* s = ray_table_new(2); + s = ray_table_add_col(s, ray_sym_intern("a", 1), ca); + s = ray_table_add_col(s, ray_sym_intern("b", 1), cb); + TEST_ASSERT_FMT(s && !RAY_IS_ERR(s), "add_col: %s", s ? ray_err_code(s) : "null"); + ray_release(ca); ray_release(cb); + TEST_ASSERT_EQ_I(ray_table_nrows(s), 70000); + TEST_ASSERT_NULL(ray_table_validate_rectangular(s, "test")); + TEST_ASSERT_TRUE(ray_table_get_col_enc_idx(s, 1) != NULL); + /* a shorter plain column makes the table ragged */ + ray_t* shortc = make_col(RAY_I32, 10, 0); + ray_retain(s); + ray_t* r = ray_table_add_col(s, ray_sym_intern("c", 1), shortc); + ray_t* e = ray_table_validate_rectangular(r, "test"); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + ray_error_free(e); + ray_release(r); ray_release(shortc); + /* copy-on-write shares the encoded object */ + ray_t* cp = ray_alloc_copy(s); + TEST_ASSERT_EQ_I(ray_table_nrows(cp), 70000); + for (int64_t c = 0; c < 2; c++) { + ray_t* enc = ray_table_get_col_enc_idx(s, c); + TEST_ASSERT_TRUE(enc != NULL); + TEST_ASSERT_EQ_PTR(ray_table_get_col_enc_idx(cp, c), enc); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(enc)->rc), 1); /* one header: shared through the cols list, not duplicated */ + } + ray_release(cp); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(s, 1)->type, RAY_F64); /* legacy getter: plain */ + ray_release(s); + /* the splayed loader returns the same values as the generation-0 table */ + ray_t* ref = t; + ray_t* ld = ray_read_splayed(ray_test_tmp(ENCCOL_TMP "/t"), NULL); + TEST_ASSERT_FMT(ld && !RAY_IS_ERR(ld), "read_splayed: %s", ld ? ray_err_code(ld) : "null"); + TEST_ASSERT_EQ_I(ray_table_nrows(ld), 70000); + for (int64_t c = 0; c < 2; c++) { + TEST_ASSERT_TRUE(ray_table_get_col_enc_idx(ld, c) != NULL); + ray_t* want = ray_table_get_col_idx(ref, c); + ray_t* got = ray_table_col_idx(ld, c); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got)); + TEST_ASSERT_EQ_I(got->type, want->type); + TEST_ASSERT_EQ_I(got->len, want->len); + TEST_ASSERT_TRUE(memcmp(ray_data(got), ray_data(want), (size_t)want->len * 8) == 0); + } + ray_release(ld); ray_release(ref); + PASS(); +} + +/* Row counts of the non-vector column shapes, without decoding. */ +static test_result_t test_table_col_nrows_shapes(void) { + ray_t* a = ray_alloc(0); a->type = -RAY_I64; a->i64 = 7; + TEST_ASSERT_EQ_I(ray_table_col_nrows(a), 0); /* an atom has no rows: its len */ + ray_release(a); + ray_t* keys = ray_vec_new(RAY_I64, 2); keys->len = 2; + ray_t* counts = ray_vec_new(RAY_I64, 2); counts->len = 2; + ((int64_t*)ray_data(counts))[0] = 30; ((int64_t*)ray_data(counts))[1] = 12; + ray_t* mc = ray_alloc(2 * sizeof(ray_t*)); + mc->type = RAY_MAPCOMMON; mc->len = 2; + ((ray_t**)ray_data(mc))[0] = keys; ((ray_t**)ray_data(mc))[1] = counts; + TEST_ASSERT_EQ_I(ray_table_col_nrows(mc), 42); + ray_release(mc); + PASS(); +} + +/* Three partitions of t(a I64, b F64); partition p is generation 2 when + * gen2_mask has bit p set, generation 0 otherwise. */ +static ray_err_t write_parted(const char* root, int gen2_mask, int64_t rows) { + for (int p = 0; p < 3; p++) { + char dir[512]; snprintf(dir, sizeof dir, "%s/2024.01.0%d/t", root, p + 1); + ray_t* t = tbl2(rows); + ray_err_t e; + if (gen2_mask & (1 << p)) e = write_splayed_gen2(dir, t); + else e = ray_splay_save(t, dir, NULL); + ray_release(t); + if (e != RAY_OK) return e; + } + return RAY_OK; +} + +static test_result_t test_parted_mixed_load(void) { + TEST_ASSERT_EQ_I(write_parted(ray_test_tmp(ENCCOL_TMP "/pdb"), 0x5, 4000), RAY_OK); /* parts 1 and 3 encoded */ + ray_enc_counters_reset(); + ray_t* t = ray_read_parted(ray_test_tmp(ENCCOL_TMP "/pdb"), "t"); + TEST_ASSERT_FMT(t && !RAY_IS_ERR(t), "parted load: %s", t ? ray_err_code(t) : "null"); + TEST_ASSERT_EQ_I(ray_table_nrows(t), 12000); + ray_t* slot = ray_table_get_col_enc(t, ray_sym_intern("a", 1)); + TEST_ASSERT_TRUE(slot && ray_enccol_is_parted(slot)); + TEST_ASSERT_EQ_I(ray_table_col_nrows(slot), 12000); /* sum of segment lens, no decode */ + ray_col_meta_t m; + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("a", 1), &m)); + TEST_ASSERT_EQ_I(m.type, RAY_PARTED_BASE + RAY_I64); + TEST_ASSERT_EQ_I(m.n_segs, 3); + TEST_ASSERT_TRUE(m.enc != NULL); + ray_t* enc = m.enc; + TEST_ASSERT_EQ_I(ray_enccol_seg(enc, 0)->type, RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_enccol_seg(enc, 1)->type, RAY_I64); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t* s2 = ray_enccol_seg_col(enc, 2); /* one segment only */ + TEST_ASSERT_TRUE(s2 && !RAY_IS_ERR(s2) && s2->type == RAY_I64); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + ray_t* w = ray_table_col(t, ray_sym_intern("a", 1)); /* plain wrapper */ + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w)); + TEST_ASSERT_EQ_I(w->type, RAY_PARTED_BASE + RAY_I64); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 2); /* segment 0 decoded, 2 cached */ + ray_t** segs = (ray_t**)ray_data(w); + TEST_ASSERT_EQ_PTR(segs[2], s2); + ray_retain(w); + ray_release(t); /* retained wrapper outlives the table */ + /* segment 0 decodes to what the same directory loads as on its own */ + ray_t* solo = ray_read_splayed(ray_test_tmp(ENCCOL_TMP "/pdb/2024.01.01/t"), NULL); + TEST_ASSERT_TRUE(solo && !RAY_IS_ERR(solo)); + ray_t* sa = ray_table_col(solo, ray_sym_intern("a", 1)); + TEST_ASSERT_TRUE(sa && !RAY_IS_ERR(sa) && sa->len == 4000 && segs[0]->len == 4000); + TEST_ASSERT_TRUE(memcmp(ray_data(sa), ray_data(segs[0]), 4000 * sizeof(int64_t)) == 0); + ray_release(solo); + ray_release(w); + PASS(); +} + +/* A parted load of generation-2 segments materializes to exactly the wrapper + * a generation-0 load of the same data produces, ragged partition included. */ +static test_result_t test_parted_equals_gen0(void) { + TEST_ASSERT_EQ_I(write_parted(ray_test_tmp(ENCCOL_TMP "/pg2"), 0x5, 3000), RAY_OK); + TEST_ASSERT_EQ_I(write_parted(ray_test_tmp(ENCCOL_TMP "/pg0"), 0x0, 3000), RAY_OK); + /* the same rows in both (rng is consumed per write): rewrite pg0 from pg2's columns */ + for (int p = 0; p < 3; p++) { + char d2[512], d0[512]; + snprintf(d2, sizeof d2, ray_test_tmp(ENCCOL_TMP "/pg2/2024.01.0%d/t"), p + 1); + snprintf(d0, sizeof d0, ray_test_tmp(ENCCOL_TMP "/pg0/2024.01.0%d/t"), p + 1); + ray_t* src = ray_read_splayed(d2, NULL); + TEST_ASSERT_TRUE(src && !RAY_IS_ERR(src)); + int64_t nc = ray_table_ncols(src); + if (p == 2) nc = 1; /* ragged: partition 3 has no column b */ + ray_t* flat = ray_table_new(nc); + for (int64_t c = 0; c < nc; c++) + flat = ray_table_add_col(flat, ray_table_col_name(src, c), ray_table_col_idx(src, c)); + TEST_ASSERT_EQ_I(ray_splay_save(flat, d0, NULL), RAY_OK); + ray_release(flat); ray_release(src); + } + remove(ray_test_tmp(ENCCOL_TMP "/pg2/2024.01.03/t/b")); + { + ray_t* names = ray_vec_new(RAY_STR, 1); names = ray_str_vec_append(names, "a", 1); + TEST_ASSERT_EQ_I(ray_col_save(names, ray_test_tmp(ENCCOL_TMP "/pg2/2024.01.03/t/.d")), RAY_OK); + ray_release(names); + } + ray_t* t2 = ray_read_parted(ray_test_tmp(ENCCOL_TMP "/pg2"), "t"); + ray_t* t0 = ray_read_parted(ray_test_tmp(ENCCOL_TMP "/pg0"), "t"); + TEST_ASSERT_TRUE(t2 && !RAY_IS_ERR(t2) && t0 && !RAY_IS_ERR(t0)); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ray_table_ncols(t2), ray_table_ncols(t0)); + for (const char* nm = "a"; nm; nm = nm[0] == 'a' ? "b" : NULL) { + int64_t id = ray_sym_intern(nm, 1); + ray_t* w2 = ray_table_col(t2, id); + ray_t* w0 = ray_table_col(t0, id); + TEST_ASSERT_TRUE(w2 && !RAY_IS_ERR(w2) && w0 && !RAY_IS_ERR(w0)); + TEST_ASSERT_EQ_I(w2->type, w0->type); + TEST_ASSERT_EQ_I(w2->attrs, w0->attrs); + TEST_ASSERT_EQ_I(w2->len, w0->len); + ray_t** s2 = (ray_t**)ray_data(w2); ray_t** s0 = (ray_t**)ray_data(w0); + for (int64_t i = 0; i < w2->len; i++) { + TEST_ASSERT_FMT((s2[i] == NULL) == (s0[i] == NULL), "col %s seg %lld: %p vs %p", nm, (long long)i, (void*)s2[i], (void*)s0[i]); + if (!s2[i]) continue; + TEST_ASSERT_EQ_I(s2[i]->type, s0[i]->type); + TEST_ASSERT_EQ_I(s2[i]->len, s0[i]->len); + TEST_ASSERT_TRUE(memcmp(ray_data(s2[i]), ray_data(s0[i]), (size_t)s2[i]->len * 8) == 0); + } + } + ray_release(t2); ray_release(t0); + PASS(); +} + +/* The statement-boundary trim drops whole-column decodes that do not fit a + * quarter of the watermark, least recently asked for first. A decode a + * caller retained is neither counted nor dropped; the column decodes again + * when next read; a budget they fit keeps them. */ +static ray_t* trim_col(const char* name, int64_t n, int64_t mul, ray_t** src) { + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = (i * mul) % 1000003 - 500000; + if (ray_col_save_gen(v, ray_test_tmp(name), 2) != RAY_OK) { ray_release(v); return NULL; } + *src = v; + return ray_col_mmap(ray_test_tmp(name)); +} +static bool trim_same(ray_t* m, ray_t* src) { + if (!m || RAY_IS_ERR(m) || m->len != src->len) return false; + return memcmp(ray_data(m), ray_data(src), (size_t)src->len * sizeof(int64_t)) == 0; +} +static void trim_with(int64_t wm) { + int64_t prev = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(wm); + ray_enccol_cache_trim(); + ray_heap_set_anon_watermark(prev); +} + +static test_result_t test_cache_trim_at_boundary(void) { + const int64_t n = 70000; + ray_t *sa = NULL, *sb = NULL; + ray_t* a = trim_col(ENCCOL_TMP "/ta", n, 7919, &sa); + ray_t* b = trim_col(ENCCOL_TMP "/tb", n, 104729, &sb); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && a->type == RAY_ENCCOL); + TEST_ASSERT_TRUE(b && !RAY_IS_ERR(b) && b->type == RAY_ENCCOL); + trim_with(1); /* nothing kept from before */ + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), 0); + + ray_t* ma = ray_enccol_materialize(a); + TEST_ASSERT_TRUE(trim_same(ma, sa)); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(a), ma); + int64_t one = (int64_t)ray_block_size(ma); + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), one); + ray_retain(ma); /* a caller keeps it: dropping frees nothing */ + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), 0); + trim_with(1); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(a), ma); + ray_release(ma); /* only the cache holds it now */ + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), one); + trim_with(1); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(a)); + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), 0); + ray_t* ma2 = ray_enccol_materialize(a); /* decodes again */ + TEST_ASSERT_TRUE(trim_same(ma2, sa)); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(a), ma2); + + /* a budget both fit keeps both; one that fits one keeps the later one */ + int64_t roomy = 4 * (2 * one + 4096), tight = 4 * (one + 4096); + trim_with(roomy); /* A: this statement */ + ray_t* mb = ray_enccol_materialize(b); /* B: the next one */ + TEST_ASSERT_TRUE(trim_same(mb, sb)); + trim_with(roomy); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(a), ma2); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(b), mb); + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), 2 * one); + trim_with(tight); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(a)); /* least recently asked for */ + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(b), mb); + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), one); + + /* no watermark keeps everything */ + ray_t* ma3 = ray_enccol_materialize(a); + TEST_ASSERT_TRUE(trim_same(ma3, sa)); + trim_with(0); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(a), ma3); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(b), mb); + + ray_release(a); ray_release(b); /* a freed column leaves the list */ + TEST_ASSERT_EQ_I(ray_enccol_cache_bytes(), 0); + ray_release(sa); ray_release(sb); + PASS(); +} + +/* (take tbl n) and the table display read an encoded column's taken or + * shown rows by range: neither leaves the column decoded whole. A plain + * read still does. */ +static test_result_t test_take_show_read_window(void) { + const int64_t n = 70000; + ray_t* tbl = ray_table_new(1); + ray_t* a = ray_vec_new(RAY_I32, n); a->len = n; + for (int64_t i = 0; i < n; i++) ((int32_t*)ray_data(a))[i] = (int32_t)(i % 977); + int64_t cb = ray_sym_intern("cb", 2); + tbl = ray_table_add_col(tbl, cb, a); + ray_release(a); + TEST_ASSERT_EQ_I(ray_splay_save(tbl, ray_test_tmp(ENCCOL_TMP "/tw"), NULL), RAY_OK); + ray_release(tbl); + TEST_ASSERT_EQ_I(save_i32_rows(ray_test_tmp(ENCCOL_TMP "/tw/cb"), n), RAY_OK); + ray_t* r = ray_read_splayed(ray_test_tmp(ENCCOL_TMP "/tw"), NULL); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_t* enc = ray_table_get_col_enc(r, cb); + TEST_ASSERT_NOT_NULL(enc); + + ray_t* k = ray_i64(-3); + ray_t* t3 = ray_take_fn(r, k); + ray_release(k); + TEST_ASSERT_TRUE(t3 && !RAY_IS_ERR(t3) && ray_table_nrows(t3) == 3); + ray_t* c3 = ray_table_col(t3, cb); + TEST_ASSERT_TRUE(c3 && c3->type == RAY_I32 && c3->len == 3); + for (int i = 0; i < 3; i++) TEST_ASSERT_EQ_I(((int32_t*)ray_data(c3))[i], (n - 3 + i) % 977); + ray_release(t3); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(enc)); + + ray_t* shown = ray_fmt(r, 1); + TEST_ASSERT_TRUE(shown && !RAY_IS_ERR(shown)); + TEST_ASSERT_TRUE(strstr(ray_str_ptr(shown), "70000 rows") != NULL); + TEST_ASSERT_TRUE(strstr(ray_str_ptr(shown), "│ 632 ") != NULL); /* the last row: 69999 % 977 */ + ray_release(shown); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(enc)); + + ray_t* plain = ray_table_col(r, cb); /* a plain read decodes */ + TEST_ASSERT_TRUE(plain && !RAY_IS_ERR(plain)); + TEST_ASSERT_EQ_PTR(ray_enccol_decoded_peek(enc), plain); + ray_release(r); + PASS(); +} + +/* Whether a whole decode would stay cached (ray_enccol_decode_kept): its + * generation-0 bytes against a quarter of the watermark, or the test + * budget; metadata only. */ +static test_result_t test_decode_kept_budget(void) { + const int64_t n = 70000; /* 560000 bytes decoded */ + ray_t* v = make_col(RAY_I64, n, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCCOL_TMP "/kb"), 2), RAY_OK); + ray_release(v); + ray_t* c = ray_col_mmap(ray_test_tmp(ENCCOL_TMP "/kb")); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + int64_t prev = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(4 * 560000); /* a quarter holds it exactly */ + TEST_ASSERT_TRUE(ray_enccol_decode_kept(c)); + ray_heap_set_anon_watermark(4 * 560000 - 4); + TEST_ASSERT_FALSE(ray_enccol_decode_kept(c)); + ray_enccol_test_kept_limit(560000); /* the test budget replaces it */ + TEST_ASSERT_TRUE(ray_enccol_decode_kept(c)); + ray_enccol_test_kept_limit(559999); + TEST_ASSERT_FALSE(ray_enccol_decode_kept(c)); + ray_enccol_test_kept_limit(0); + ray_heap_set_anon_watermark(prev); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(c)); /* nothing was read */ + ray_release(c); + PASS(); +} + +/* Distinct cells of v[0, n) as the count-distinct kernels key them (a null + * one value); integer types. */ +static int cmp_i64(const void* a, const void* b) { + int64_t x = *(const int64_t*)a, y = *(const int64_t*)b; + return x < y ? -1 : x > y; +} +static int64_t distinct_i64(int64_t* x, int64_t n) { + if (n == 0) return 0; + qsort(x, (size_t)n, sizeof *x, cmp_i64); + int64_t d = 1; + for (int64_t i = 1; i < n; i++) d += x[i] != x[i - 1]; + return d; +} +static int64_t cell_i64(ray_t* v, int64_t i) { + const void* d = ray_data(v); + switch (v->type) { + case RAY_I16: return ((const int16_t*)d)[i]; + case RAY_I32: return ((const int32_t*)d)[i]; + default: return ((const int64_t*)d)[i]; + } +} + +/* ray_col_gather_span reads rows [lo, hi) of a generation-2 column as a + * plain vector equal to those rows of the source — nulls (HAS_NULLS where + * the rows hold one), STR pools, spans that cross the 64 K-row chunks, end + * inside a vector, or hold nothing — and refuses an unaligned start; the + * bounded count-distinct kernel reads the column (as a value and as a key) + * through range reads and counts as over the plain rows. Neither leaves + * the column decoded whole. */ +static test_result_t test_gather_span_bounded_read_window(void) { + const int64_t n = 140000; + static const struct { int8_t t; int s; } C[] = { + { RAY_I64, 4 }, { RAY_I32, 1 }, { RAY_I16, 4 }, { RAY_STR, 4 }, { RAY_F64, 4 }, + }; + const int64_t spans[][2] = { + { 0, 140000 }, { 0, 51200 }, { 51200, 102400 }, { 65536, 131072 }, + { 139264, 140000 }, { 102400, 102400 }, { 51200, 52000 }, { 64512, 66000 }, + }; + ray_t* src_v[5] = { 0 }; + ray_t* enc[5] = { 0 }; + for (int k = 0; k < 5; k++) { + char p[64]; + snprintf(p, sizeof p, ENCCOL_TMP "/gs%d", k); + src_v[k] = make_col(C[k].t, n, C[k].s); + TEST_ASSERT_EQ_I(ray_col_save_gen(src_v[k], ray_test_tmp(p), 2), RAY_OK); + enc[k] = ray_col_mmap(ray_test_tmp(p)); + TEST_ASSERT_TRUE(enc[k] && !RAY_IS_ERR(enc[k]) && enc[k]->type == RAY_ENCCOL); + } + for (int k = 0; k < 5; k++) { + ray_t* v = src_v[k]; + ray_col_src_t s; + TEST_ASSERT_NULL(ray_col_src_bind(enc[k], &s)); + for (size_t q = 0; q < sizeof spans / sizeof spans[0]; q++) { + int64_t lo = spans[q][0], hi = spans[q][1]; + ray_t* out = NULL; + ray_t* err = ray_col_gather_span(&s, lo, hi, &out); + TEST_ASSERT_FMT(!err, "type %d span [%lld, %lld): %s", C[k].t, (long long)lo, (long long)hi, err ? ray_err_code(err) : ""); + TEST_ASSERT_TRUE(out && out->type == v->type && out->len == hi - lo); + bool nulls = false; + for (int64_t i = lo; i < hi; i++) nulls = nulls || ray_vec_is_null(v, i); + TEST_ASSERT_EQ_I((out->attrs & RAY_ATTR_HAS_NULLS) != 0, nulls); + for (int64_t i = 0; i < hi - lo; i++) { + TEST_ASSERT_EQ_I(ray_vec_is_null(out, i), ray_vec_is_null(v, lo + i)); + if (v->type == RAY_STR) { + size_t la = 0, lb = 0; + const char* a = ray_str_vec_get(out, i, &la); + const char* b = ray_str_vec_get(v, lo + i, &lb); + TEST_ASSERT_TRUE(la == lb && (la == 0 || memcmp(a, b, la) == 0)); + } else { + uint8_t esz = ray_sym_elem_size(v->type, v->attrs); + TEST_ASSERT_FMT(memcmp((char*)ray_data(out) + i * esz, (char*)ray_data(v) + (lo + i) * esz, esz) == 0, + "type %d row %lld", C[k].t, (long long)(lo + i)); + } + } + ray_release(out); + } + ray_t* out = NULL; + ray_t* err = ray_col_gather_span(&s, 100, 2148, &out); /* not at a vector start */ + TEST_ASSERT_TRUE(err && out == NULL); + TEST_ASSERT_STR_EQ(ray_err_code(err), "range"); + ray_error_free(err); + ray_col_src_release(&s); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(enc[k])); + } + + /* the bounded kernel over one group and over the I32 key's groups */ + int64_t* x = (int64_t*)ray_alloc_raw((size_t)n * sizeof(int64_t)); + TEST_ASSERT_NOT_NULL(x); + for (int k = 0; k < 3; k++) { + for (int64_t i = 0; i < n; i++) x[i] = cell_i64(src_v[k], i); + int64_t want = distinct_i64(x, n); + ray_t* got = ray_cd_bounded_all(enc[k], n); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && got->type == -RAY_I64); + TEST_ASSERT_EQ_I(got->i64, want); + ray_release(got); + } + TEST_ASSERT_NULL(ray_cd_bounded_all(enc[3], n)); /* STR: not served */ + ray_t* keys = ray_vec_new(RAY_I32, 64); + keys->len = 64; + for (int g = 0; g < 64; g++) ((int32_t*)ray_data(keys))[g] = g; + ray_t* got = ray_cd_bounded(NULL, enc[1], keys, NULL, 64, enc[0], NULL, n); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && got->type == RAY_I64 && got->len == 64); + for (int g = 0; g < 64; g++) { + int64_t m = 0; + for (int64_t i = 0; i < n; i++) + if (cell_i64(src_v[1], i) == g) x[m++] = cell_i64(src_v[0], i); + TEST_ASSERT_FMT(((int64_t*)ray_data(got))[g] == distinct_i64(x, m), "group %d", g); + } + ray_release(got); + ray_release(keys); + ray_free_raw(x); + for (int k = 0; k < 5; k++) { + TEST_ASSERT_NULL(ray_enccol_decoded_peek(enc[k])); + ray_release(enc[k]); + ray_release(src_v[k]); + } + PASS(); +} + +const test_entry_t enccol_entries[] = { + { "enccol/take_show_read_window", test_take_show_read_window, enccol_setup, enccol_teardown }, + { "enccol/decode_kept_budget", test_decode_kept_budget, enccol_setup, enccol_teardown }, + { "enccol/gather_span_bounded_read_window", test_gather_span_bounded_read_window, enccol_setup, enccol_teardown }, + { "enccol/cache_trim_at_boundary", test_cache_trim_at_boundary, enccol_setup, enccol_teardown }, + { "enccol/open_returns_enccol", test_open_returns_enccol, enccol_setup, enccol_teardown }, + { "enccol/load_version", test_load_version, enccol_setup, enccol_teardown }, + { "enccol/sym_requires_domain", test_sym_requires_domain, enccol_setup, enccol_teardown }, + { "enccol/append_index_gen2", test_append_index_refuses_gen2, enccol_setup, enccol_teardown }, + { "enccol/load_gen2_plain", test_load_gen2_plain, enccol_setup, enccol_teardown }, + { "enccol/no_mapping_leak", test_no_mapping_leak, enccol_setup, enccol_teardown }, + { "enccol/truncated_fails_whole", test_truncated_fails_whole, enccol_setup, enccol_teardown }, + { "enccol/value_dict_side", test_value_dict_side, enccol_setup, enccol_teardown }, + { "enccol/sym_domain_rules", test_sym_domain_rules, enccol_setup, enccol_teardown }, + { "enccol/consumers_refuse", test_consumers_refuse, enccol_setup, enccol_teardown }, + { "enccol/be_gate_logic", test_be_gate_logic, enccol_setup, enccol_teardown }, + { "enccol/roundtrip_types_shapes", test_roundtrip_types_shapes, enccol_setup, enccol_teardown }, + { "enccol/roundtrip_lengths", test_roundtrip_lengths, enccol_setup, enccol_teardown }, + { "enccol/roundtrip_edges", test_roundtrip_edges, enccol_setup, enccol_teardown }, + { "enccol/golden_decode", test_golden_decode, enccol_setup, enccol_teardown }, + { "enccol/dict_once_concurrent", test_dict_once_concurrent, enccol_setup, enccol_teardown }, + { "enccol/fast_kernel_equal", test_fast_kernel_equal, enccol_setup, enccol_teardown }, + { "enccol/runs_kernel_equal", test_runs_kernel_equal, enccol_setup, enccol_teardown }, + { "enccol/raw_int_view", test_raw_int_view, enccol_setup, enccol_teardown }, + { "enccol/point_read_equal", test_point_read_equal, enccol_setup, enccol_teardown }, + { "enccol/dict_kernel_equal", test_dict_kernel_equal, enccol_setup, enccol_teardown }, + { "enccol/dict_kernel_shapes", test_dict_kernel_shapes, enccol_setup, enccol_teardown }, + { "enccol/point_read_declines", test_point_read_declines, enccol_setup, enccol_teardown }, + { "enccol/point_read_runs", test_point_read_runs, enccol_setup, enccol_teardown }, + { "enccol/point_read_column", test_point_read_column, enccol_setup, enccol_teardown }, + { "enccol/scratch_outlives_source", test_scratch_outlives_source, enccol_setup, enccol_teardown }, + { "enccol/payload_is_tail", test_payload_is_tail, enccol_setup, enccol_teardown }, + { "enccol/dict_null_dictionary", test_dict_null_dictionary, enccol_setup, enccol_teardown }, + { "enccol/vec_range_checks", test_vec_range_checks, enccol_setup, enccol_teardown }, + { "enccol/materialize_equivalence", test_materialize_equivalence, enccol_setup, enccol_teardown }, + { "enccol/materialize_lengths", test_materialize_lengths, enccol_setup, enccol_teardown }, + { "enccol/materialize_float_bits", test_materialize_float_bits, enccol_setup, enccol_teardown }, + { "enccol/decoded_peek", test_decoded_peek, enccol_setup, enccol_teardown }, + { "enccol/cols_inplace_encoded", test_cols_inplace_encoded, enccol_setup, enccol_teardown }, + { "enccol/materialize_counts_once", test_materialize_counts_once, enccol_setup, enccol_teardown }, + { "enccol/oom_then_retry", test_oom_then_retry, enccol_setup, enccol_teardown }, + { "enccol/col_load_materializes", test_col_load_materializes, enccol_setup, enccol_teardown }, + { "enccol/cancel_retried", test_cancel_retried, enccol_setup, enccol_teardown }, + { "enccol/cancel_mid_decode", test_cancel_mid_decode, enccol_setup, enccol_teardown }, + { "enccol/cancel_waiter", test_cancel_waiter, enccol_setup, enccol_teardown }, + { "enccol/load_dom_refcount", test_load_dom_refcount, enccol_setup, enccol_teardown }, + { "enccol/synth_zone", test_synth_zone, enccol_setup, enccol_teardown }, + { "enccol/synth_chunk_zone", test_synth_chunk_zone, enccol_setup, enccol_teardown }, + { "enccol/unique_flag", test_unique_flag, enccol_setup, enccol_teardown }, + { "enccol/attach_refused", test_attach_refused, enccol_setup, enccol_teardown }, + { "enccol/synth_matches_gen0", test_synth_matches_gen0, enccol_setup, enccol_teardown }, + { "enccol/table_core", test_table_core_enccol, enccol_setup, enccol_teardown }, + { "enccol/table_col_nrows_shapes", test_table_col_nrows_shapes, enccol_setup, enccol_teardown }, + { "enccol/parted_mixed_load", test_parted_mixed_load, enccol_setup, enccol_teardown }, + { "enccol/parted_equals_gen0", test_parted_equals_gen0, enccol_setup, enccol_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_encfloat.c b/test/test_encfloat.c new file mode 100644 index 000000000..b6ff2a094 --- /dev/null +++ b/test/test_encfloat.c @@ -0,0 +1,2016 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "core/runtime.h" +#include "store/enc.h" +#include "store/encfmt.h" +#include "store/col.h" +#include "store/encw.h" +#include "store/enccol.h" +#include "store/colrange.h" +#include "store/enceval.h" +#include "store/splay.h" +#include "ops/fused_topk.h" +#include "ops/idxop.h" +#include "ops/ops.h" +#include "lang/env.h" +#include "lang/format.h" +#include "table/table.h" +#include "vec/str.h" +#include +#if defined(__SSE__) +#include +#endif +#include +#include +#include +#include + +#define FL_TMP "/tmp/rayforce_encfloat" /* always through ray_test_tmp (per-process root) */ +static void fl_setup(void) { ray_heap_init(); (void)ray_sym_init(); (void)ray_test_rm_rf(ray_test_tmp(FL_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(FL_TMP)); } +/* Buffers a test owns, freed in teardown so an early-returning assertion + * leaks nothing. */ +static ray_enc_buf_t fl_buf; +static uint64_t* fl_dict; +static uint8_t* fl_mem; /* malloc'd scratch */ +static ray_t* fl_vec; /* a test's column */ +static ray_t* fl_map; /* a test's mapped generation-2 column */ +static ray_enc_vview_t fl_vw; /* a test's vector view (about 21 KB) */ +static void fl_teardown(void) { + ray_encw_test_force(-1); + if (fl_vec) { ray_release(fl_vec); fl_vec = NULL; } + if (fl_map) { ray_release(fl_map); fl_map = NULL; } + ray_enc_buf_free(&fl_buf); fl_buf = (ray_enc_buf_t){0}; + if (fl_dict) { ray_free_raw(fl_dict); fl_dict = NULL; } + free(fl_mem); fl_mem = NULL; + ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(FL_TMP)); ray_sym_destroy(); ray_heap_destroy(); +} + +static uint64_t db(double x) { uint64_t b; memcpy(&b, &x, 8); return b; } +static uint64_t fb(float x) { uint32_t b; memcpy(&b, &x, 4); return b; } + +/* -0.0 as bit patterns: independent of the build's float flags (D10). */ +#define NEG0_64 (1ull << 63) +#define NEG0_32 (1ull << 31) + +static const ray_enc_kind_t K64F = { 64, false, true }; +static const ray_enc_kind_t K32F = { 32, false, true }; + +/* Dictionary order: numeric, -0.0 before +0.0, F32 widened. */ +static test_result_t test_float_order(void) { + TEST_ASSERT_TRUE(ray_enc_lt(db(-1.0), NEG0_64, K64F)); + TEST_ASSERT_TRUE(ray_enc_lt(NEG0_64, db(0.0), K64F)); + TEST_ASSERT_FALSE(ray_enc_lt(db(0.0), NEG0_64, K64F)); + TEST_ASSERT_FALSE(ray_enc_lt(db(0.0), db(0.0), K64F)); + TEST_ASSERT_TRUE(ray_enc_lt(db(0.0), db(1e-300), K64F)); + TEST_ASSERT_TRUE(ray_enc_lt(NEG0_32, fb(0.0f), K32F)); + TEST_ASSERT_TRUE(ray_enc_lt(fb(-2.5f), fb(1.0f), K32F)); + ray_enc_kind_t k; + TEST_ASSERT_TRUE(ray_enc_value_kind(RAY_F64, 0, &k)); + TEST_ASSERT_TRUE(k.T == 64 && k.is_float && !k.is_signed); + TEST_ASSERT_TRUE(ray_enc_value_kind(RAY_I32, 0, &k)); + TEST_ASSERT_TRUE(k.T == 32 && !k.is_float && k.is_signed); + TEST_ASSERT_FALSE(ray_enc_value_kind(RAY_STR, 0, &k)); + PASS(); +} + +/* Training keeps both zeros as distinct entries, -0.0 first. */ +static test_result_t test_float_train_dict(void) { + uint64_t v[7] = { db(2.25), db(0.0), db(-3.5), NEG0_64, db(0.0), db(2.25), NEG0_64 }; + uint64_t* d = NULL; uint32_t dn; + int rc = ray_enc_train_dict(v, 7, K64F, &d, &dn); + if (rc == 1) fl_dict = d; /* freed in teardown */ + TEST_ASSERT_EQ_I(rc, 1); + TEST_ASSERT_EQ_I(dn, 4); + TEST_ASSERT_EQ_U(d[0], db(-3.5)); TEST_ASSERT_EQ_U(d[1], NEG0_64); + TEST_ASSERT_EQ_U(d[2], db(0.0)); TEST_ASSERT_EQ_U(d[3], db(2.25)); + PASS(); +} + +/* Float CONST, RLE and DICT bodies through the integer codec, bit-exact; + * RLE values are RAW only; FOR_BP / DELTA_BP are illegal on floats. */ +static test_result_t test_float_bodies(void) { + uint64_t v[RAY_ENC_VEC], out[RAY_ENC_VEC]; + ray_enc_buf_t* bp = &fl_buf; /* freed in teardown */ + ray_enc_choice_t c; + /* CONST: all -0.0, bit-exact (never folded into +0.0) */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = NEG0_64; + TEST_ASSERT_TRUE(ray_enc_body_size(RAY_ENC_CONST, v, RAY_ENC_VEC, K64F, NULL) > 0); + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_CONST, v, RAY_ENC_VEC, K64F, NULL, bp, &c)); + memset(out, 0, sizeof out); + TEST_ASSERT_EQ_I(ray_enc_read(bp->p, bp->len, RAY_ENC_CONST, 0, RAY_ENC_VEC, K64F, RAY_ENC_SLOT_TOP, 0, NULL, out), (int64_t)bp->len); + TEST_ASSERT_TRUE(memcmp(v, out, sizeof v) == 0); + bp->len = 0; + { /* F32 CONST of -0.0 */ + ray_enc_kind_t k32 = K32F; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = NEG0_32; + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_CONST, v, RAY_ENC_VEC, k32, NULL, bp, &c)); + memset(out, 0, sizeof out); + TEST_ASSERT_EQ_I(ray_enc_read(bp->p, bp->len, RAY_ENC_CONST, 0, RAY_ENC_VEC, k32, RAY_ENC_SLOT_TOP, 0, NULL, out), (int64_t)bp->len); + for (int i = 0; i < RAY_ENC_VEC; i++) TEST_ASSERT_EQ_U(out[i] & 0xffffffffull, NEG0_32); + bp->len = 0; + } + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (i / 100) & 1 ? NEG0_64 : db(0.0); + TEST_ASSERT_TRUE(ray_enc_body_size(RAY_ENC_RLE, v, RAY_ENC_VEC, K64F, NULL) > 0); + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_RLE, v, RAY_ENC_VEC, K64F, NULL, bp, &c)); + TEST_ASSERT_EQ_I(bp->p[8], RAY_ENC_RAW); /* values child */ + TEST_ASSERT_EQ_I(ray_enc_read(bp->p, bp->len, RAY_ENC_RLE, 0, RAY_ENC_VEC, K64F, RAY_ENC_SLOT_TOP, 0, NULL, out), (int64_t)bp->len); + TEST_ASSERT_TRUE(memcmp(v, out, sizeof v) == 0); + bp->len = 0; + uint64_t dv[4] = { db(-3.5), NEG0_64, db(0.0), db(2.25) }; + ray_enc_dict_t dict = { dv, 4 }; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = dv[(i * 7) % 4]; + TEST_ASSERT_TRUE(ray_enc_body_size(RAY_ENC_DICT, v, RAY_ENC_VEC, K64F, &dict) > 0); + TEST_ASSERT_TRUE(ray_enc_write_as(RAY_ENC_DICT, v, RAY_ENC_VEC, K64F, &dict, bp, &c)); + TEST_ASSERT_EQ_I(ray_enc_read(bp->p, bp->len, RAY_ENC_DICT, 0, RAY_ENC_VEC, K64F, RAY_ENC_SLOT_TOP, 0, &dict, out), (int64_t)bp->len); + TEST_ASSERT_TRUE(memcmp(v, out, sizeof v) == 0); + bp->len = 0; + TEST_ASSERT_FALSE(ray_enc_write_as(RAY_ENC_FOR_BP, v, RAY_ENC_VEC, K64F, NULL, bp, &c)); + TEST_ASSERT_FALSE(ray_enc_write_as(RAY_ENC_DELTA_BP, v, RAY_ENC_VEC, K64F, NULL, bp, &c)); + TEST_ASSERT_EQ_I(ray_enc_body_size(RAY_ENC_FOR_BP, v, RAY_ENC_VEC, K64F, NULL), -1); + TEST_ASSERT_EQ_I(ray_enc_body_size(RAY_ENC_CONST, v, RAY_ENC_VEC, K64F, NULL), -1); + PASS(); +} + +/* The new slots: ALP ints (I64, spec erratum E-P5-1) admit DELTA_BP, RLE + * and a signed FOR_BP, ALP_RD left (U8) admits RLE and FOR_BP and not + * DELTA_BP, and the reader enforces it. */ +static test_result_t test_new_slots(void) { + uint64_t v[RAY_ENC_VEC]; + ray_enc_kind_t k64 = { 64, true, false }, k8 = { 8, false, false }; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 1000000 + 10 * (uint64_t)i; /* lane-linear: DELTA_BP w=0 */ + ray_enc_choice_t c = ray_enc_choose(v, RAY_ENC_VEC, k64, RAY_ENC_SLOT_ALP_INTS, 1, NULL); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_DELTA_BP); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)((i / 256) % 3); + c = ray_enc_choose(v, RAY_ENC_VEC, k8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_RLE); + /* four long runs of widely spread values: RLE wins in the ints slot */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = 0x0123456789abull * (uint64_t)((i / 256) * 3 + 1); + c = ray_enc_choose(v, RAY_ENC_VEC, k64, RAY_ENC_SLOT_ALP_INTS, 1, NULL); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_RLE); + /* mixed-sign integers in -1000..1000: FOR_BP in signed order, width 11 */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(int64_t)((i * 7919) % 2001 - 1000); + c = ray_enc_choose(v, RAY_ENC_VEC, k64, RAY_ENC_SLOT_ALP_INTS, 1, NULL); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(c.width, 11); + /* 3-bit values: FOR_BP w=3 in the left slot (DELTA_BP is illegal there, + * and at T = 8 its 128 eight-byte starts exceed RAW anyway) */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = (uint64_t)(i & 7); + c = ray_enc_choose(v, RAY_ENC_VEC, k8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_FOR_BP); + /* that FOR_BP body round-trips in the left slot ... */ + ray_enc_buf_t* bp = &fl_buf; /* freed in teardown */ + TEST_ASSERT_TRUE(ray_enc_write(v, RAY_ENC_VEC, k8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL, bp, &c)); + TEST_ASSERT_EQ_I(c.enc, RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(bp->p[0], RAY_ENC_FOR_BP); /* child header: enc, width */ + uint64_t out[RAY_ENC_VEC]; + TEST_ASSERT_EQ_I(ray_enc_read(bp->p, bp->len, 0, 0, RAY_ENC_VEC, k8, RAY_ENC_SLOT_ALP_RD_LEFT, 1, NULL, out), (int64_t)bp->len); + TEST_ASSERT_TRUE(memcmp(v, out, sizeof v) == 0); + PASS(); +} + +/* xorshift64 for random float data (the ALP_RD tests). */ +static uint64_t g_fseed = 7; +static uint64_t frng(void) { uint64_t x = g_fseed; x ^= x << 13; x ^= x >> 7; x ^= x << 17; return g_fseed = x; } + +static int alp_roundtrip(const uint64_t* v, int n, int T, const ray_enc_alp_cands_t* c, int64_t* size_out) { + int bi; + int64_t sz = ray_enc_alp_size(v, n, T, c, &bi); + if (sz < 0) return -1; + ray_enc_buf_t b = {0}; + if (!ray_enc_alp_write(v, n, T, c->c[bi].e, c->c[bi].f, &b)) return -2; + if ((int64_t)b.len != sz) { ray_enc_buf_free(&b); return -3; } + uint64_t out[RAY_ENC_VEC]; + int64_t u = ray_enc_alp_read(b.p, b.len, n, T, out); + ray_enc_buf_free(&b); + if (u != sz) return -4; + uint64_t m = T == 64 ? ~0ull : 0xFFFFFFFFull; + for (int i = 0; i < n; i++) if (out[i] != (v[i] & m)) return -5; + if (size_out) *size_out = sz; + return 0; +} + +/* Two-decimal prices: ALP with e - f = 2 wins by far over RAW. */ +static test_result_t test_alp_decimals(void) { + uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db((double)((i * 7919) % 100000) / 100.0); + ray_enc_alp_cands_t c; + ray_enc_alp_train(v, RAY_ENC_VEC, 64, &c); + TEST_ASSERT_TRUE(c.n >= 1); + int64_t sz; + TEST_ASSERT_EQ_I(alp_roundtrip(v, RAY_ENC_VEC, 64, &c, &sz), 0); + TEST_ASSERT_TRUE(sz * 8 <= 8192 * 7); + /* the pick is pinned: (2, 0) loses to rounding (n * 0.01 is not n / 100), + * (14, 12) is the smallest pair exact on every sample */ + TEST_ASSERT_EQ_I(c.n, 1); + TEST_ASSERT_TRUE(c.c[0].e == 14 && c.c[0].f == 12); + /* F32 tenths */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = fb((float)((i * 31) % 5000) / 10.0f); + ray_enc_alp_train(v, RAY_ENC_VEC, 32, &c); + TEST_ASSERT_TRUE(c.n >= 1); + TEST_ASSERT_EQ_I(alp_roundtrip(v, RAY_ENC_VEC, 32, &c, &sz), 0); + TEST_ASSERT_TRUE(sz * 8 <= 4096 * 7); + /* pinned: (2, 1) is exact on the 32 samples and ties keep the smaller pair */ + TEST_ASSERT_EQ_I(c.n, 1); + TEST_ASSERT_TRUE(c.c[0].e == 2 && c.c[0].f == 1); + /* training is deterministic */ + ray_enc_alp_cands_t c2; + ray_enc_alp_train(v, RAY_ENC_VEC, 32, &c2); + TEST_ASSERT_TRUE(c.n == c2.n && memcmp(c.c, c2.c, sizeof c.c[0] * (size_t)c.n) == 0); + PASS(); +} + +/* Mixed-sign two-decimal values in [-10, 10]: the signed ints child packs + * them at their real width (spec erratum E-P5-1), far below RAW. */ +static test_result_t test_alp_signed(void) { + uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db((double)((i * 7919) % 2001 - 1000) / 100.0); + ray_enc_alp_cands_t c; + ray_enc_alp_train(v, RAY_ENC_VEC, 64, &c); + TEST_ASSERT_TRUE(c.n >= 1); + int64_t sz; + TEST_ASSERT_EQ_I(alp_roundtrip(v, RAY_ENC_VEC, 64, &c, &sz), 0); + TEST_ASSERT_TRUE(sz * 8 <= 8192 * 4); + /* F32 the same */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = fb((float)((i * 7919) % 2001 - 1000) / 100.0f); + ray_enc_alp_train(v, RAY_ENC_VEC, 32, &c); + TEST_ASSERT_TRUE(c.n >= 1); + TEST_ASSERT_EQ_I(alp_roundtrip(v, RAY_ENC_VEC, 32, &c, &sz), 0); + TEST_ASSERT_TRUE(sz * 8 <= 4096 * 4); + PASS(); +} + +/* Review focus 3: edges are exact or exceptions, never wrong values. + * -0.0 and NaNs are bit patterns (D10). */ +static test_result_t test_alp_edges(void) { + static const double edge[] = { 0.0, 1e300, -1e300, 1e-300, 4.9e-324, INFINITY, -INFINITY, + 9.0e18, -9.0e18, 8.999999999999999e17, 0.1, 1.0 / 3.0, -2.5, 123456789.123 }; + static const uint64_t ebits[] = { NEG0_64, 0x7ff8000000000000ull /* canonical NaN */, + 0x7ff8000000000123ull /* payload */, 0xfff8000000000000ull /* negative */, + 0x7ff0000000000001ull /* signalling */, 0xfff00000deadbeefull }; + enum { NE = sizeof edge / sizeof edge[0], NB = sizeof ebits / sizeof ebits[0] }; + uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = i % (NE + NB) < NE ? db(edge[i % (NE + NB)]) : ebits[i % (NE + NB) - NE]; + ray_enc_alp_cands_t c = { { { 2, 0 }, { 14, 0 }, { 18, 18 }, { 0, 0 }, { 3, 1 } }, 5 }; + TEST_ASSERT_EQ_I(alp_roundtrip(v, RAY_ENC_VEC, 64, &c, NULL), 0); + for (int n = 1; n <= 1024; n = n * 3 + 1) TEST_ASSERT_EQ_I(alp_roundtrip(v, n, 64, &c, NULL), 0); + static const uint64_t fedge[] = { NEG0_32, 0, 0, 0, 0, 0, 0x7fc00000u, 0x7fc00123u, 0xffc00000u, 0x7f800001u }; + static const float fval[] = { 0.0f, 16777217.0f, 3.4e38f, 1e-38f, 0.1f, -7.25f }; + for (int i = 0; i < RAY_ENC_VEC; i++) { + int k = i % 10; + v[i] = k >= 1 && k <= 5 ? fb(fval[k]) : fedge[k]; /* k 1..5: values, else bit patterns */ + } + TEST_ASSERT_EQ_I(alp_roundtrip(v, RAY_ENC_VEC, 32, &c, NULL), 0); + /* every value an exception: still legal */ + for (int i = 0; i < 16; i++) v[i] = i & 1 ? NEG0_64 : 0x7ff8000000000123ull; + TEST_ASSERT_EQ_I(alp_roundtrip(v, 16, 64, &c, NULL), 0); + PASS(); +} + +/* ---- ALP_RD ---- */ +static int alprd_roundtrip(const uint64_t* v, int n, int T, int64_t* sz) { + int64_t s = ray_enc_alprd_size(v, n, T); + ray_enc_buf_t b = {0}; + if (!ray_enc_alprd_write(v, n, T, &b)) { ray_enc_buf_free(&b); return -1; } + if ((int64_t)b.len != s) { ray_enc_buf_free(&b); return -2; } + uint64_t out[RAY_ENC_VEC]; + int64_t u = ray_enc_alprd_read(b.p, b.len, n, T, out); + ray_enc_buf_free(&b); + if (u != s) return -3; + uint64_t m = T == 64 ? ~0ull : 0xFFFFFFFFull; + for (int i = 0; i < n; i++) if (out[i] != (v[i] & m)) return -4; + if (sz) *sz = s; + return 0; +} + +/* Review focus 4: lengths 1, 1023, 1024; F64 in [1, 2) and F32. */ +static test_result_t test_alprd_lengths(void) { + g_fseed = 7; /* the same data under any filter */ + uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db(1.0 + (double)(frng() >> 11) / 9007199254740992.0); + int64_t sz; + TEST_ASSERT_EQ_I(alprd_roundtrip(v, RAY_ENC_VEC, 64, &sz), 0); + TEST_ASSERT_TRUE(sz * 8 <= 8192 * 7); /* left parts: one sign/exponent */ + TEST_ASSERT_EQ_I(alprd_roundtrip(v, 1, 64, NULL), 0); + TEST_ASSERT_EQ_I(alprd_roundtrip(v, 1023, 64, NULL), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = frng() & 0x7FEFFFFFFFFFFFFFull; /* random non-NaN bits */ + TEST_ASSERT_EQ_I(alprd_roundtrip(v, RAY_ENC_VEC, 64, NULL), 0); /* many exceptions */ + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = fb(1.0f + (float)(frng() >> 41) / 8388608.0f); + TEST_ASSERT_EQ_I(alprd_roundtrip(v, RAY_ENC_VEC, 32, NULL), 0); + TEST_ASSERT_EQ_I(alprd_roundtrip(v, 1, 32, NULL), 0); + PASS(); +} + +/* Exception framing on a hand-built body (spec "Reject rules": ALP/ALP_RD + * exception framing; Review focus 4): T = 64, right_bits = 52, dict + * {0x3FF, 0x400}, four rows, rows 2 and 3 exceptions with raw left parts + * 0x3FE and 0x401. */ +static size_t alprd_body(uint8_t* b, const uint8_t codes[4], const uint16_t pos[2], const uint16_t lefts[2]) { + memset(b, 0, 8 + 8 + 16 + 6656 + 8 + 8); + b[0] = 52; b[1] = 2; uint16_t ne = 2; memcpy(b + 2, &ne, 2); + uint16_t dict[2] = { 0x3FF, 0x400 }; memcpy(b + 8, dict, 4); /* dict, padded to 8 */ + uint32_t bb = 8; /* left child: RAW, 4 codes + pad */ + b[16] = RAY_ENC_RAW; memcpy(b + 20, &bb, 4); memcpy(b + 24, codes, 4); + size_t at = 32 + ray_enc_packed_bytes(52); /* right parts: all zero */ + memcpy(b + at, pos, 4); at += 8; + memcpy(b + at, lefts, 4); at += 8; + return at; +} +static test_result_t test_alprd_exceptions(void) { + static uint8_t b[8 + 8 + 16 + 6656 + 8 + 8]; + uint8_t codes[4] = { 0, 1, 0, 0 }; + uint16_t pos[2] = { 2, 3 }, lefts[2] = { 0x3FE, 0x401 }; + uint64_t out[RAY_ENC_VEC]; + size_t n = alprd_body(b, codes, pos, lefts); + TEST_ASSERT_EQ_I(ray_enc_alprd_read(b, n, 4, 64, out), (int64_t)n); + TEST_ASSERT_EQ_U(out[0], 0x3FFull << 52); TEST_ASSERT_EQ_U(out[1], 0x400ull << 52); + TEST_ASSERT_EQ_U(out[2], 0x3FEull << 52); TEST_ASSERT_EQ_U(out[3], 0x401ull << 52); + PASS(); +} + +/* Bit-exact on special values (spec "P5": NaN payloads included), all as + * bit patterns (D10): NaNs with payloads and both signs, +-inf, +-0.0, + * denormals, extremes, ordinary values of both signs. */ +static test_result_t test_alprd_specials(void) { + static const uint64_t s64[] = { + 0x7ff8000000000000ull, 0x7ff8000000000123ull, 0xfff8000000000000ull, 0x7ff0000000000001ull, + 0xfff00000deadbeefull, 0x7ff0000000000000ull, 0xfff0000000000000ull, 0, NEG0_64, + 1, 0x800fffffffffffffull, 0x000fffffffffffffull, 0x8000000000000001ull, 0x7fefffffffffffffull, + 0xffefffffffffffffull, 0x0010000000000000ull, 0x3ff0000000000000ull, 0xc00921fb54442d18ull }; + static const uint64_t s32[] = { + 0x7fc00000u, 0x7fc00123u, 0xffc00000u, 0x7f800001u, 0xffbadbadu, 0x7f800000u, 0xff800000u, 0, + NEG0_32, 1, 0x807fffffu, 0x007fffffu, 0x80000001u, 0x7f7fffffu, 0xff7fffffu, 0x3f800000u, 0xc0490fdbu }; + enum { N64 = sizeof s64 / sizeof s64[0], N32 = sizeof s32 / sizeof s32[0] }; + uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = s64[(i * 7) % N64]; + TEST_ASSERT_EQ_I(alprd_roundtrip(v, RAY_ENC_VEC, 64, NULL), 0); + for (int n = 1; n <= RAY_ENC_VEC; n = n * 3 + 1) TEST_ASSERT_EQ_I(alprd_roundtrip(v, n, 64, NULL), 0); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = s32[(i * 5) % N32]; + TEST_ASSERT_EQ_I(alprd_roundtrip(v, RAY_ENC_VEC, 32, NULL), 0); + for (int n = 1; n <= RAY_ENC_VEC; n = n * 3 + 1) TEST_ASSERT_EQ_I(alprd_roundtrip(v, n, 32, NULL), 0); + PASS(); +} + +/* The choice, then a write of the chosen encoding: its length is the + * chosen size and it reads back (0, else a negative step). */ +static int choice_enc(const uint64_t* v, int n, int T, const ray_enc_dict_t* d, + const ray_enc_alp_cands_t* c, int64_t extra, ray_enc_choice_t* ch) { + *ch = ray_enc_float_choose(v, n, T, d, c, extra); + ray_enc_buf_t* bp = &fl_buf; /* freed in teardown */ + ray_enc_choice_t wc; + bp->len = 0; + if (!ray_enc_float_write(ch->enc, v, n, T, d, c, bp, &wc)) return -1; + if (wc.enc != ch->enc || (int64_t)bp->len != ch->bytes || wc.bytes != ch->bytes) return -2; + uint64_t out[RAY_ENC_VEC]; + if (ray_enc_float_read(bp->p, bp->len, ch->enc, n, T, d, out) != (int64_t)bp->len) return -3; + uint64_t m = T == 64 ? ~0ull : 0xFFFFFFFFull; + for (int i = 0; i < n; i++) if (out[i] != (v[i] & m)) return -4; + return 0; +} + +/* The choice: CONST, RLE, DICT, ALP, ALP_RD and RAW each win somewhere, + * and the chosen size is what the write produces. */ +static test_result_t test_float_choice(void) { + g_fseed = 7; + uint64_t v[RAY_ENC_VEC]; + ray_enc_alp_cands_t c; + ray_enc_choice_t ch; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db(1.5); + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, NULL, NULL, 0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_CONST); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db((double)((frng() % 1000)) * 1.0000001); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = v[(i / 128) * 128]; /* runs of 128 of awkward values */ + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, NULL, NULL, 0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_RLE); + uint64_t dv[4] = { db(-3.5), NEG0_64, db(0.0), db(2.25) }; + ray_enc_dict_t dict = { dv, 4 }; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = dv[(uint32_t)(i * 2654435761u) >> 30]; + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, &dict, NULL, 0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_DICT); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db((double)((i * 7919) % 100000) / 100.0); + ray_enc_alp_train(v, RAY_ENC_VEC, 64, &c); + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, NULL, &c, 0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_ALP); + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db(1.0 + (double)(frng() >> 11) / 9007199254740992.0); + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, NULL, &c, 0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_ALP_RD); + /* the trailer counts on both sides of the 1/8 rule: the winner stays + * up to extra = 7*raw - 8*bytes and gives way to RAW one byte later */ + const int64_t raw = ray_enc_size_raw(RAY_ENC_VEC, 64), s = ch.bytes; + const int64_t e0 = 7 * raw - 8 * s; + TEST_ASSERT_TRUE(e0 > 0); + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, NULL, &c, e0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_ALP_RD); + TEST_ASSERT_EQ_I(ch.bytes, s); /* extra is not in the body size */ + TEST_ASSERT_EQ_I(choice_enc(v, RAY_ENC_VEC, 64, NULL, &c, e0 + 1, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(ch.bytes, raw); + for (int i = 0; i < 8; i++) v[i] = frng() & 0x7FEFFFFFFFFFFFFFull; + TEST_ASSERT_EQ_I(choice_enc(v, 8, 64, NULL, &c, 0, &ch), 0); + TEST_ASSERT_EQ_I(ch.enc, RAY_ENC_RAW); + /* every encoding forced through float_write / float_read */ + static const uint8_t encs[] = { RAY_ENC_RAW, RAY_ENC_CONST, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + ray_enc_buf_t* bp = &fl_buf; /* freed in teardown */ + for (size_t k = 0; k < sizeof encs; k++) { + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = encs[k] == RAY_ENC_CONST ? NEG0_64 : dv[(i / 7) % 4]; + bp->len = 0; + TEST_ASSERT_TRUE(ray_enc_float_write(encs[k], v, RAY_ENC_VEC, 64, &dict, &c, bp, &ch)); + TEST_ASSERT_EQ_I(ch.enc, encs[k]); + TEST_ASSERT_EQ_I(ch.bytes, (int64_t)bp->len); + uint64_t out[RAY_ENC_VEC]; + TEST_ASSERT_EQ_I(ray_enc_float_read(bp->p, bp->len, encs[k], RAY_ENC_VEC, 64, &dict, out), (int64_t)bp->len); + TEST_ASSERT_TRUE(memcmp(out, v, sizeof v) == 0); + } + /* CONST does not apply to unequal values */ + bp->len = 0; + TEST_ASSERT_FALSE(ray_enc_float_write(RAY_ENC_CONST, v, RAY_ENC_VEC, 64, &dict, &c, bp, &ch)); + TEST_ASSERT_EQ_I((int64_t)bp->len, 0); + PASS(); +} + +/* ---- the column writer (Task 4); the round trips decode through the + * generation-2 reader, so they first pass with Task 5 ---- */ +static ray_t* f64_col(const double* d, int64_t n) { return ray_vec_from_raw(RAY_F64, d, n); } +/* Releases the test's column (the teardown releases it on a failed assertion). */ +static void fl_drop(void) { if (fl_vec) { ray_release(fl_vec); fl_vec = NULL; } } + +/* The top-level encoding of vector `vec` in a generation-2 file, -1 on a + * short file. */ +static int desc_enc(const char* path, int64_t vec) { + FILE* f = fopen(path, "rb"); + if (!f) return -1; + uint8_t h[96]; if (fread(h, 1, 96, f) != 96) { fclose(f); return -1; } + int64_t c = vec / 64, j = vec % 64; + uint64_t off; + if (fseek(f, 96 + c * 64, SEEK_SET) != 0 || fread(&off, 8, 1, f) != 1) { fclose(f); return -1; } + uint8_t d[48]; + if (fseek(f, (long)(off + (uint64_t)j * 48), SEEK_SET) != 0) { fclose(f); return -1; } + int r = fread(d, 1, 48, f) == 48 ? d[0] : -1; + fclose(f); + return r; +} + +/* n bytes of path at off. */ +static bool fl_read(const char* path, long off, void* b, size_t n) { + FILE* f = fopen(path, "rb"); + if (!f) return false; + bool ok = fseek(f, off, SEEK_SET) == 0 && fread(b, 1, n, f) == n; + fclose(f); + return ok; +} + +/* The (e, f) of the ALP body of vector j of chunk c (no null bitmap) as + * e * 256 + f, -1 on a short file. */ +static int fl_alp_ef(const char* path, int64_t c, int j) { + uint64_t off, poff; + if (!fl_read(path, 96 + (long)c * 64, &off, 8) || !fl_read(path, (long)(off + (uint64_t)j * 48 + 8), &poff, 8)) return -1; + uint8_t ef[2]; + return fl_read(path, (long)(off + poff), ef, 2) ? ef[0] * 256 + ef[1] : -1; +} +static bool fl_cands_have(const ray_enc_alp_cands_t* c, int ef) { + for (int i = 0; i < c->n; i++) if (c->c[i].e * 256 + c->c[i].f == ef) return true; + return false; +} + +/* Saves gen 2 (optionally forced), loads, compares the payload bit for bit. */ +static int fl_roundtrip(ray_t* v, int force, const char* path) { + ray_encw_test_force(force); + ray_err_t e = ray_col_save_gen(v, path, 2); + ray_encw_test_force(-1); + if (e != RAY_OK) return -1; + ray_t* b = ray_col_load(path); + if (!b || RAY_IS_ERR(b)) { if (b) ray_error_free(b); return -2; } + size_t esz = v->type == RAY_F32 ? 4 : 8; + int ok = b->len == v->len && memcmp(ray_data(b), ray_data(v), (size_t)v->len * esz) == 0; + ray_release(b); + return ok ? 0 : -3; +} + +/* Selection, one shape per vector of chunk 1. Chunk 0 holds two-decimal + * values: the frozen VALUE_DICT covers only them, so it does not apply to + * chunk 1, while the frozen ALP candidates (e = 2) do. A one-chunk column + * would let DICT win every vector: a first chunk has at most 65536 distinct + * values, so the dictionary always trains (P0 rule). */ +static test_result_t test_encoder_selects(void) { + const int64_t base = 65536; + static double d[65536 + 5 * 1024]; + uint64_t s = 9; + for (int64_t i = 0; i < base; i++) d[i] = (double)((i * 7919) % 100000) / 100.0; + for (int i = 0; i < 1024; i++) d[base + i] = 1.25; /* CONST */ + for (int i = 0; i < 1024; i++) d[base + 1024 + i] = 5000.0 + (double)(i / 128) * 1.0000001; /* RLE */ + for (int i = 0; i < 1024; i++) d[base + 2048 + i] = 2000.0 + (double)((i * 7919) % 100000) / 100.0; /* ALP */ + for (int i = 0; i < 1024; i++) { s ^= s << 13; s ^= s >> 7; s ^= s << 17; + d[base + 3072 + i] = 1.0 + (double)(s >> 11) / 9007199254740992.0; } /* ALP_RD */ + for (int i = 0; i < 1024; i++) { s ^= s << 13; s ^= s >> 7; s ^= s << 17; + uint64_t b = s & 0x7FEFFFFFFFFFFFFFull; memcpy(&d[base + 4096 + i], &b, 8); } /* RAW */ + fl_vec = f64_col(d, base + 5 * 1024); + const char* p = ray_test_tmp(FL_TMP "/sel"); + TEST_ASSERT_EQ_I(fl_roundtrip(fl_vec, -1, p), 0); + TEST_ASSERT_EQ_I(desc_enc(p, 64), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(desc_enc(p, 65), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(desc_enc(p, 66), RAY_ENC_ALP); + TEST_ASSERT_EQ_I(desc_enc(p, 67), RAY_ENC_ALP_RD); + TEST_ASSERT_EQ_I(desc_enc(p, 68), RAY_ENC_RAW); + fl_drop(); + PASS(); +} + +/* Canonical and non-canonical NaNs with ALP exceptions, in every forced + * encoding. -0.0 is written as its bit pattern (D10). */ +static test_result_t test_nan_payloads(void) { + static double d[2048]; + uint64_t odd = 0x7FF8000000000123ull, neg = 0xFFF8000000000000ull, nz = NEG0_64; + for (int i = 0; i < 2048; i++) { + d[i] = (double)(i % 50) / 4.0; + if (i % 17 == 0) memcpy(&d[i], &nz, 8); /* ALP exception */ + if (i % 23 == 0) d[i] = NULL_F64; /* canonical null */ + if (i % 29 == 0) memcpy(&d[i], &odd, 8); /* trailer */ + if (i % 31 == 0) memcpy(&d[i], &neg, 8); /* trailer */ + } + fl_vec = f64_col(d, 2048); + fl_vec->attrs |= RAY_ATTR_HAS_NULLS; + static const int forces[] = { -1, RAY_ENC_RAW, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + for (size_t k = 0; k < sizeof forces / sizeof forces[0]; k++) + TEST_ASSERT_FMT(fl_roundtrip(fl_vec, forces[k], ray_test_tmp(FL_TMP "/nan")) == 0, "force %d", forces[k]); + fl_drop(); + /* F32: the same with float NaN payloads */ + static float f[2048]; + uint32_t fodd = 0x7FC00042u, fnz = (uint32_t)NEG0_32; + for (int i = 0; i < 2048; i++) { + f[i] = (float)(i % 40) / 8.0f; + if (i % 19 == 0) memcpy(&f[i], &fodd, 4); + if (i % 21 == 0) f[i] = NULL_F32; + if (i % 13 == 0) memcpy(&f[i], &fnz, 4); + } + fl_vec = ray_vec_from_raw(RAY_F32, f, 2048); + fl_vec->attrs |= RAY_ATTR_HAS_NULLS; + for (size_t k = 0; k < sizeof forces / sizeof forces[0]; k++) + TEST_ASSERT_FMT(fl_roundtrip(fl_vec, forces[k], ray_test_tmp(FL_TMP "/nan32")) == 0, "f32 force %d", forces[k]); + fl_drop(); + /* forced CONST: one value plus canonical and non-canonical NaNs */ + static double cst[1024]; + for (int i = 0; i < 1024; i++) { + cst[i] = 2.5; + if (i % 9 == 0) cst[i] = NULL_F64; + if (i % 10 == 3) memcpy(&cst[i], &odd, 8); + } + fl_vec = f64_col(cst, 1024); + fl_vec->attrs |= RAY_ATTR_HAS_NULLS; + const char* p = ray_test_tmp(FL_TMP "/nanc"); + TEST_ASSERT_EQ_I(fl_roundtrip(fl_vec, RAY_ENC_CONST, p), 0); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_CONST); + fl_drop(); + PASS(); +} + +/* All-null float vectors at lengths 1, 1023, 1024 stay CONST under any + * force (the six float encodings) and under selection. */ +static test_result_t test_all_null_floats(void) { + static const int lens[] = { 1, 1023, 1024 }; + static const int forces[] = { -1, RAY_ENC_RAW, RAY_ENC_CONST, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + const char* p = ray_test_tmp(FL_TMP "/an"); + for (int t = 0; t < 2; t++) /* F64 and F32: every nullable float type */ + for (int l = 0; l < 3; l++) { + int8_t ty = t ? RAY_F32 : RAY_F64; + fl_vec = ray_vec_new(ty, lens[l]); fl_vec->len = lens[l]; + for (int i = 0; i < lens[l]; i++) { + if (t) ((float*)ray_data(fl_vec))[i] = NULL_F32; else ((double*)ray_data(fl_vec))[i] = NULL_F64; + } + fl_vec->attrs |= RAY_ATTR_HAS_NULLS; + for (size_t k = 0; k < sizeof forces / sizeof forces[0]; k++) { + TEST_ASSERT_FMT(fl_roundtrip(fl_vec, forces[k], p) == 0, "type %d len %d force %d", ty, lens[l], forces[k]); + TEST_ASSERT_FMT(desc_enc(p, 0) == RAY_ENC_CONST, "type %d len %d force %d: encoding %d", + ty, lens[l], forces[k], desc_enc(p, 0)); + } + fl_drop(); + } + PASS(); +} + +/* VALUE_DICT and ALP candidates come from the first chunk only, so a + * column whose second chunk has new values encodes them otherwise (the + * stream writer's agreement is encfloat/stream_equals_resident, Task 7). */ +static test_result_t test_first_chunk_training(void) { + int64_t n = 65536 + 4096; + fl_vec = ray_vec_new(RAY_F64, n); fl_vec->len = n; + for (int64_t i = 0; i < n; i++) ((double*)ray_data(fl_vec))[i] = i < 65536 ? (double)(i % 6) * 0.5 : 1e-7 * (double)i; + const char* p = ray_test_tmp(FL_TMP "/tr"); + TEST_ASSERT_EQ_I(fl_roundtrip(fl_vec, -1, p), 0); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_DICT); + TEST_ASSERT_TRUE(desc_enc(p, 64) != RAY_ENC_DICT); + fl_drop(); + /* ALP candidates: chunk 0 holds two-decimal values, chunk 1 + * one-decimal values, whose own training gives another (e, f). The + * candidates trained on chunk 0 still apply to them (wider ints), so + * chunk 1's ALP vector carries one of those; alone (forced ALP: its + * own chunk 0 trains), the same values take a pair outside them. */ + n = 65536 + 1024; + fl_vec = ray_vec_new(RAY_F64, n); fl_vec->len = n; + for (int64_t i = 0; i < n; i++) + ((double*)ray_data(fl_vec))[i] = i < 65536 ? (double)((i * 7919) % 100000) / 100.0 + : 3000.0 + (double)(((i - 65536) * 7919) % 10000) / 10.0; + ray_enc_alp_cands_t c0; + ray_enc_alp_train((const uint64_t*)ray_data(fl_vec), 65536, 64, &c0); + TEST_ASSERT_TRUE(c0.n > 0); + TEST_ASSERT_EQ_I(fl_roundtrip(fl_vec, -1, p), 0); + TEST_ASSERT_EQ_I(desc_enc(p, 64), RAY_ENC_ALP); + int ef1 = fl_alp_ef(p, 1, 0); + TEST_ASSERT_FMT(fl_cands_have(&c0, ef1), "chunk 1 (e, f) = (%d, %d) is not a chunk-0 candidate", ef1 >> 8, ef1 & 255); + fl_drop(); + fl_vec = ray_vec_new(RAY_F64, 1024); fl_vec->len = 1024; + for (int64_t i = 0; i < 1024; i++) ((double*)ray_data(fl_vec))[i] = 3000.0 + (double)((i * 7919) % 10000) / 10.0; + TEST_ASSERT_EQ_I(fl_roundtrip(fl_vec, RAY_ENC_ALP, p), 0); /* alone, DICT would win */ + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_ALP); + int efa = fl_alp_ef(p, 0, 0); + /* Sampler-dependent: training samples every 32nd row of the first + * chunk, so this negative check holds for today's sampler only. If the + * sampling is tuned (P5 Task 8, O1), re-derive it. */ + TEST_ASSERT_FMT(!fl_cands_have(&c0, efa), "alone (e, f) = (%d, %d) is also a chunk-0 candidate", efa >> 8, efa & 255); + fl_drop(); + /* An F32 VALUE_DICT has 4-byte elements, in dictionary order: + * -3.5, -0.0, +0.0, 2.25 (the zeros as bit patterns, D10). */ + static const uint32_t fv[4] = { 0xC0600000u, 0x80000000u, 0x00000000u, 0x40100000u }; + fl_vec = ray_vec_new(RAY_F32, 1024); fl_vec->len = 1024; + for (int i = 0; i < 1024; i++) memcpy((float*)ray_data(fl_vec) + i, &fv[(i * 7) % 4], 4); + TEST_ASSERT_EQ_I(fl_roundtrip(fl_vec, RAY_ENC_DICT, p), 0); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_DICT); + ray_enc_hdr_t eh; + TEST_ASSERT_TRUE(fl_read(p, 32, &eh, sizeof eh)); + uint8_t side[8 + 24 + 8 + 16]; + TEST_ASSERT_EQ_U(eh.side_len, sizeof side); /* one entry, 24 bytes at 32 */ + TEST_ASSERT_TRUE(fl_read(p, (long)eh.side_off, side, sizeof side)); + static const uint8_t want[sizeof side] = { + 1, 0, 0, 0, 0, 0, 0, 0, /* one entry */ + 1, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, /* VALUE_DICT, @32, 24 B */ + 4, 0, 0, 0, 0, 0, 0, 0, /* n = 4 */ + 0x00, 0x00, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40, + }; + for (size_t i = 0; i < sizeof side; i++) + TEST_ASSERT_FMT(side[i] == want[i], "side byte %zu: 0x%02x, want 0x%02x", i, side[i], want[i]); + fl_drop(); + PASS(); +} + +/* ---- the reader (Task 5) ---- */ +static void fl_patch(const char* path, long off, const void* b, size_t n) { + FILE* f = fopen(path, "r+b"); + if (!f) ray_test_fatal("cannot open %s", path); + if (fseek(f, off, SEEK_SET) != 0 || fwrite(b, 1, n, f) != n) { fclose(f); ray_test_fatal("cannot patch %s", path); } + fclose(f); +} + +/* The error code materialization gives ("" on success), its message in + * fl_msg. */ +static char fl_msg[512]; +static const char* fl_mat_code(const char* path) { + static char code[16]; + fl_msg[0] = 0; + ray_error_clear(); + ray_t* c = ray_col_mmap(path); + if (!c || RAY_IS_ERR(c)) { + snprintf(code, sizeof code, "%s", c ? ray_err_code(c) : "null"); + snprintf(fl_msg, sizeof fl_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (c) ray_error_free(c); + return code; + } + ray_t* m = ray_enccol_materialize(c); /* borrowed on success */ + snprintf(code, sizeof code, "%s", RAY_IS_ERR(m) ? ray_err_code(m) : ""); + if (RAY_IS_ERR(m)) { snprintf(fl_msg, sizeof fl_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); ray_error_free(m); } + ray_release(c); + return code; +} + +/* Range reads of the whole column at path equal v bit for bit: 0, else a + * negative step. */ +static int fl_range_equal(const char* path, ray_t* v) { + ray_t* c = ray_col_mmap(path); + if (!c || RAY_IS_ERR(c)) { if (c) ray_error_free(c); return -1; } + ray_col_src_t s; + ray_t* err = ray_col_src_bind(c, &s); + if (err) { ray_error_free(err); ray_release(c); return -2; } + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + const size_t esz = v->type == RAY_F32 ? 4 : 8; + int rc = 0; + int64_t at = 0; + while (at < v->len && rc == 0) { + ray_col_range_t r; + err = ray_col_range(&s, at, v->len - at, &sc, &r); + if (err) { ray_error_free(err); rc = -3; break; } + if (r.n <= 0) { rc = -4; break; } + if (memcmp(r.data, (const uint8_t*)ray_data(v) + (size_t)at * esz, (size_t)r.n * esz) != 0) rc = -5; + at += r.n; + } + ray_col_scratch_free(&sc); ray_col_src_release(&s); ray_release(c); + return rc; +} + +/* Every encoding round-trips through load (materialization) and range reads. */ +static test_result_t test_decode_paths(void) { + static double d[3 * 1024]; + for (int i = 0; i < 3 * 1024; i++) d[i] = (double)((i * 7919) % 100000) / 100.0; + fl_vec = f64_col(d, 3 * 1024); + const char* p = ray_test_tmp(FL_TMP "/dp"); + static const int forces[] = { RAY_ENC_RAW, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + for (size_t k = 0; k < sizeof forces / sizeof forces[0]; k++) { + if (forces[k] == RAY_ENC_DICT) continue; /* 3072 distinct values: covered in nan_payloads */ + TEST_ASSERT_FMT(fl_roundtrip(fl_vec, forces[k], p) == 0, "force %d", forces[k]); + for (int64_t j = 0; j < 3; j++) TEST_ASSERT_FMT(desc_enc(p, j) == forces[k], "force %d vector %lld", forces[k], (long long)j); + TEST_ASSERT_FMT(fl_range_equal(p, fl_vec) == 0, "force %d range read %d", forces[k], fl_range_equal(p, fl_vec)); + } + fl_drop(); + PASS(); +} + +/* The trailer's bytes count on both sides of the 1/8 gain rule at the + * writer. 1 + 52 random mantissa bits: ALP_RD of 8 + 8 + 16 + 6656 = + * 6688 B against RAW 8192, so a trailer of more than 7 * 8192 - 8 * 6688 = + * 3840 B flips the choice to RAW. 384 NaN rows (filled alike, so the + * same body): canonical, no trailer, ALP_RD; 383 with payloads, a trailer + * of 8 + 768 + 3064 = 3840 B, still ALP_RD; 384 with payloads, 3848 B, + * RAW. Left out of the choice, the trailer would give ALP_RD all three. */ +static test_result_t test_trailer_counts_in_choice(void) { + static double d[RAY_ENC_VEC]; + static const int odd[3] = { 0, 383, 384 }; + for (int k = 0; k < 3; k++) { + uint64_t s = 11; + int nan_rows = 0; + for (int i = 0; i < RAY_ENC_VEC; i++) { + s ^= s << 13; s ^= s >> 7; s ^= s << 17; + d[i] = 1.0 + (double)(s >> 12) / 4503599627370496.0; + if (i % 8 < 3) { + if (nan_rows++ < odd[k]) memcpy(&d[i], &(uint64_t){ 0x7FF8000000000100ull + (uint64_t)i }, 8); + else d[i] = NULL_F64; + } + } + ray_encw_vec_t v; ray_encw_vec_init(&v); + ray_err_t e = ray_encw_vec(RAY_F64, RAY_ATTR_HAS_NULLS, d, NULL, 0, RAY_ENC_VEC, NULL, &v); + int enc = v.desc.encoding, flags = v.desc.flags, nn = v.desc.n_nulls; + ray_encw_vec_free(&v); + TEST_ASSERT_EQ_I(e, RAY_OK); + TEST_ASSERT_EQ_I(nn, 384); + TEST_ASSERT_FMT(enc == (k == 2 ? RAY_ENC_RAW : RAY_ENC_ALP_RD), "%d payload NaNs: encoding %d", odd[k], enc); + TEST_ASSERT_EQ_I(!!(flags & RAY_ENC_DESC_TRAILER), k > 0); + } + PASS(); +} + +/* ---- float views, evaluators and their consumers (Task 6) ---- */ +static double bd(uint64_t b) { double x; memcpy(&x, &b, 8); return x; } + +/* d as a column of type ty (F32: each value narrowed, -0.0 by its bit + * pattern, D10; a NaN becomes the type's null), HAS_NULLS when a NaN is in. */ +static ray_t* fl_typed(int8_t ty, const double* d, int64_t n) { + bool nul = false; + for (int64_t i = 0; i < n; i++) nul |= d[i] != d[i]; + ray_t* v; + if (ty == RAY_F64) v = f64_col(d, n); + else { + v = ray_vec_new(RAY_F32, n); v->len = n; + float* o = (float*)ray_data(v); + for (int64_t i = 0; i < n; i++) { + if (db(d[i]) == NEG0_64) { uint32_t z = (uint32_t)NEG0_32; memcpy(&o[i], &z, 4); } + else o[i] = d[i] != d[i] ? NULL_F32 : (float)d[i]; + } + } + if (nul) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} + +/* d saved at path as generation 2, every float vector forced to enc (-1: + * selection), then mapped into fl_map. False on any failure. */ +static bool fl_view_col(int8_t ty, int enc, const double* d, int64_t n, const char* path) { + fl_drop(); + if (fl_map) { ray_release(fl_map); fl_map = NULL; } + fl_vec = fl_typed(ty, d, n); + ray_encw_test_force_float(enc); + ray_err_t e = ray_col_save_gen(fl_vec, path, 2); + ray_encw_test_force_float(-1); + fl_drop(); + if (e != RAY_OK) return false; + ray_t* c = ray_col_mmap(path); + if (!c || RAY_IS_ERR(c)) { if (c) ray_error_free(c); return false; } + fl_map = c; + return true; +} +/* path mapped again into fl_map (after a patch). */ +static bool fl_remap(const char* path) { + if (fl_map) { ray_release(fl_map); fl_map = NULL; } + ray_t* c = ray_col_mmap(path); + if (!c || RAY_IS_ERR(c)) { if (c) ray_error_free(c); return false; } + fl_map = c; + return true; +} +/* Vector vec of fl_map as a view into fl_vw: 1 / 0 / -1 (the error freed). */ +static int fl_vview(int64_t vec) { + ray_t* err = NULL; + int r = ray_enccol_vview(ray_enccol_of(fl_map), vec, &fl_vw, &err); + if (err) ray_error_free(err); + return r; +} + +/* The evaluators equal a direct scalar evaluation under the predicate + * comparator (-0.0 == +0.0), for every operator, both zeros, both null + * results, F64 and F32 (widened), over RLE and DICT views. */ +static test_result_t test_eval_f64(void) { + static double d[1024]; + const double dv[4] = { -3.5, bd(NEG0_64), 0.0, 2.25 }; + for (int i = 0; i < 1024; i++) d[i] = dv[(i / 3) % 4]; + d[100] = NULL_F64; d[513] = NULL_F64; + const double consts[] = { 0.0, bd(NEG0_64), -3.5, 2.25, 1.0, -10.0, 3.0 }; + static const int encs[] = { RAY_ENC_RLE, RAY_ENC_DICT }; + static const int8_t tys[] = { RAY_F64, RAY_F32 }; + const char* p = ray_test_tmp(FL_TMP "/ev"); + for (size_t t = 0; t < 2; t++) + for (size_t k = 0; k < 2; k++) { + TEST_ASSERT_TRUE(fl_view_col(tys[t], encs[k], d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), encs[k]); + TEST_ASSERT_EQ_I(fl_vview(0), 1); + TEST_ASSERT_EQ_I(fl_vw.enc, encs[k]); + TEST_ASSERT_EQ_I(fl_vw.k.T, tys[t] == RAY_F32 ? 32 : 64); + TEST_ASSERT_TRUE(fl_vw.k.is_float); + TEST_ASSERT_EQ_I(fl_vw.n_nulls, 2); + TEST_ASSERT_NOT_NULL(fl_vw.nullmap); + uint8_t bits[1024]; + for (uint16_t op = OP_EQ; op <= OP_GE; op++) + for (size_t ci = 0; ci < sizeof consts / sizeof consts[0]; ci++) + for (uint8_t nr = 0; nr < 2; nr++) { + memset(bits, 0xAA, sizeof bits); + TEST_ASSERT_TRUE(ray_enc_eval_cmp_f64(&fl_vw, op, consts[ci], nr, bits)); + const double c = consts[ci]; + for (int i = 0; i < 1024; i++) { + uint8_t want; + if (d[i] != d[i]) want = nr; + else switch (op) { + case OP_EQ: want = d[i] == c; break; case OP_NE: want = d[i] != c; break; + case OP_LT: want = d[i] < c; break; case OP_LE: want = d[i] <= c; break; + case OP_GT: want = d[i] > c; break; default: want = d[i] >= c; break; } + TEST_ASSERT_FMT(bits[i] == want, "type %d enc %d op %u c %g nr %u row %d: %u", + tys[t], encs[k], op, c, nr, i, bits[i]); + } + } + /* declines: a NaN constant (the null constant), an operator outside + * OP_EQ .. OP_GE; the integer evaluator declines the float view */ + TEST_ASSERT_FALSE(ray_enc_eval_cmp_f64(&fl_vw, OP_EQ, NULL_F64, 0, bits)); + TEST_ASSERT_FALSE(ray_enc_eval_cmp_f64(&fl_vw, OP_GE + 1, 0.0, 0, bits)); + TEST_ASSERT_FALSE(ray_enc_eval_cmp(&fl_vw, OP_EQ, 0, 0, bits)); + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(&fl_vw, OP_EQ, 0.0, 0), -1); /* not CONST */ + } + /* CONST: one value for every row */ + static double cst[1024]; + for (int i = 0; i < 1024; i++) cst[i] = bd(NEG0_64); + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, RAY_ENC_CONST, cst, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(fl_vview(0), 1); + uint8_t bits[1024]; + TEST_ASSERT_TRUE(ray_enc_eval_cmp_f64(&fl_vw, OP_EQ, 0.0, 0, bits)); + for (int i = 0; i < 1024; i++) TEST_ASSERT_EQ_I(bits[i], 1); + TEST_ASSERT_TRUE(ray_enc_eval_cmp_f64(&fl_vw, OP_LT, 0.0, 0, bits)); + for (int i = 0; i < 1024; i++) TEST_ASSERT_EQ_I(bits[i], 0); + PASS(); +} + +/* A nullable CONST float vector is decided whole only when the value's + * result equals null_result. */ +static test_result_t test_const_decision_f64(void) { + static double d[1024]; + for (int i = 0; i < 1024; i++) d[i] = i == 7 ? NULL_F64 : bd(NEG0_64); + const char* p = ray_test_tmp(FL_TMP "/cd"); + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, RAY_ENC_CONST, d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(fl_vview(0), 1); + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(&fl_vw, OP_LE, 0.0, 1), 1); /* -0 <= 0 and null -> 1 */ + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(&fl_vw, OP_EQ, 0.0, 0), -1); /* -0 == 0 but null -> 0 */ + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(&fl_vw, OP_GT, 0.0, 0), 0); + TEST_ASSERT_EQ_I(ray_enc_const_decision_f64(&fl_vw, OP_EQ, NULL_F64, 0), -1); /* a NaN constant */ + PASS(); +} + +/* The float RLE / DICT views make dec_floats' checks, and decline what + * decode rejects (D7); a trailer, RAW, ALP and ALP_RD decline (D6). */ +static test_result_t test_view_shapes(void) { + const long desc = 96 + 64, payload = desc + RAY_ENC_DESC_AREA; /* chunk 0, vector 0 */ + const char* p = ray_test_tmp(FL_TMP "/vc"); + static double d[1024]; + /* RLE: 16 runs of 64 rows, 1.5 .. 16.5, no nulls: [nr, rsv][values + * child header][16 values][ends child] */ + for (int i = 0; i < 1024; i++) d[i] = 1.5 + (double)(i / 64); + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, RAY_ENC_RLE, d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(fl_vview(0), 1); + TEST_ASSERT_EQ_I(fl_vw.n_runs, 16); + TEST_ASSERT_EQ_U(fl_vw.run_vals.q[3], db(4.5)); + TEST_ASSERT_EQ_I(fl_vw.run_ends.h[3], 256); + TEST_ASSERT_TRUE(fl_vw.nullmap == NULL); + uint8_t enc0; TEST_ASSERT_TRUE(fl_read(p, payload + 8, &enc0, 1)); + TEST_ASSERT_EQ_I(enc0, RAY_ENC_RAW); + uint64_t v0, nan = 0x7FF8000000000000ull; + TEST_ASSERT_TRUE(fl_read(p, payload + 16, &v0, 8)); + TEST_ASSERT_EQ_U(v0, db(1.5)); + TEST_ASSERT_STR_EQ(fl_mat_code(p), ""); + + /* nullable RLE: a run wholly in the bitmap is never read, so its + * stored value may be anything (a NaN here); decode agrees */ + for (int i = 0; i < 1024; i++) d[i] = i >= 192 && i < 256 ? NULL_F64 : 1.5 + (double)(i / 64); + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, RAY_ENC_RLE, d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_RLE); + TEST_ASSERT_EQ_I(fl_vview(0), 1); + TEST_ASSERT_NOT_NULL(fl_vw.nullmap); + int nullrun = -1; + for (uint32_t r = 0, prev = 0; r < fl_vw.n_runs; prev = fl_vw.run_ends.h[r++]) + if (prev == 192 && fl_vw.run_ends.h[r] == 256) nullrun = (int)r; + TEST_ASSERT_FMT(nullrun >= 0, "no run holds exactly the null rows (%u runs)", fl_vw.n_runs); + const long nbody = payload + 128; /* after the bitmap */ + fl_patch(p, nbody + 16 + 8 * nullrun, &nan, 8); + TEST_ASSERT_TRUE(fl_remap(p)); TEST_ASSERT_EQ_I(fl_vview(0), 1); + TEST_ASSERT_STR_EQ(fl_mat_code(p), ""); + TEST_ASSERT_EQ_I(fl_range_equal(p, (fl_vec = fl_typed(RAY_F64, d, 1024))), 0); + fl_drop(); + /* DICT: -3.5, -0.0, +0.0, 2.25; [codes child header][base][packed] */ + static const uint64_t dv[4] = { 0xC00C000000000000ull, NEG0_64, 0, 0x4002000000000000ull }; + for (int i = 0; i < 1024; i++) memcpy(&d[i], &dv[(i * 7) % 4], 8); + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, RAY_ENC_DICT, d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), RAY_ENC_DICT); + TEST_ASSERT_EQ_I(fl_vview(0), 1); + TEST_ASSERT_EQ_I(fl_vw.enc, RAY_ENC_DICT); + TEST_ASSERT_EQ_U(fl_vw.dict_n, 4); + for (int i = 0; i < 1024; i++) TEST_ASSERT_EQ_U(fl_vw.dict[fl_vw.codes[i]], dv[(i * 7) % 4]); + TEST_ASSERT_TRUE(fl_read(p, payload, &enc0, 1)); + TEST_ASSERT_EQ_I(enc0, RAY_ENC_FOR_BP); + TEST_ASSERT_STR_EQ(fl_mat_code(p), ""); + + /* a trailer (a non-canonical NaN) declines every float view (D6); the + * range read still answers */ + static const int tforces[] = { RAY_ENC_CONST, RAY_ENC_RLE, RAY_ENC_DICT }; + for (size_t k = 0; k < 3; k++) { + for (int i = 0; i < 1024; i++) d[i] = k == 0 ? 2.5 : 1.5 + (double)(i / 64); + memcpy(&d[5], &(uint64_t){ 0x7FF8000000000077ull }, 8); + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, tforces[k], d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), tforces[k]); + uint16_t fl; TEST_ASSERT_TRUE(fl_read(p, desc + 4, &fl, 2)); + TEST_ASSERT_TRUE(fl & RAY_ENC_DESC_TRAILER); + TEST_ASSERT_EQ_I(fl_vview(0), 0); + fl_vec = fl_typed(RAY_F64, d, 1024); + memcpy((double*)ray_data(fl_vec) + 5, &(uint64_t){ 0x7FF8000000000077ull }, 8); + TEST_ASSERT_FMT(fl_range_equal(p, fl_vec) == 0, "force %d", tforces[k]); + fl_drop(); + } + /* RAW, ALP and ALP_RD decline: the caller decodes */ + static const int dforces[] = { RAY_ENC_RAW, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + for (int i = 0; i < 1024; i++) d[i] = (double)((i * 7919) % 100000) / 100.0; + for (size_t k = 0; k < 3; k++) { + TEST_ASSERT_TRUE(fl_view_col(RAY_F64, dforces[k], d, 1024, p)); + TEST_ASSERT_EQ_I(desc_enc(p, 0), dforces[k]); + TEST_ASSERT_EQ_I(fl_vview(0), 0); + } + PASS(); +} + +/* ---- the view consumers over a float column (D7) ---- */ +static ray_runtime_t* g_flrt; +static void fl_rt_setup(void) { + g_flrt = ray_runtime_create(0, NULL); + (void)ray_test_rm_rf(ray_test_tmp(FL_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(FL_TMP)); +} +static void fl_rt_teardown(void) { + ray_test_hooks_off(); ray_encw_test_force(-1); + if (fl_map) { ray_release(fl_map); fl_map = NULL; } + (void)ray_test_rm_rf(ray_test_tmp(FL_TMP)); ray_runtime_destroy(g_flrt); +} +static ray_t* fl_eval(const char* src) { return ray_eval_str(ray_test_tmp(src)); } +static bool fl_eval_ok(const char* src) { + ray_t* r = fl_eval(src); + if (r && RAY_IS_ERR(r)) { fprintf(stderr, "fl_eval_ok: %s: %s\n", src, ray_error_msg()); ray_error_free(r); return false; } + if (r) ray_release(r); + return true; +} +/* Float bits of results a and b equal: F32 / F64 atoms (both hold a + * double) and vectors bit for bit, a table column by column; formatting + * prints both zeros as 0.0, so it cannot tell them apart. */ +static bool fl_bits_eq(ray_t* a, ray_t* b) { + if (a->type != b->type) return false; + if (a->type == -RAY_F64 || a->type == -RAY_F32) return memcmp(&a->f64, &b->f64, 8) == 0; + if (a->type == RAY_F64 || a->type == RAY_F32) + return a->len == b->len && memcmp(ray_data(a), ray_data(b), (size_t)a->len * (a->type == RAY_F64 ? 8 : 4)) == 0; + if (a->type == RAY_TABLE) { + if (ray_table_ncols(a) != ray_table_ncols(b)) return false; + for (int64_t c = 0; c < ray_table_ncols(a); c++) { + ray_t* ca = ray_table_get_col_idx(a, c); ray_t* cb = ray_table_get_col_idx(b, c); + if (!ca || !cb || !fl_bits_eq(ca, cb)) return false; + } + } + return true; +} + +/* q on generation 0 (table 0) and generation 2 (2) as T: equal + * types, formatted results and float bits. */ +static test_result_t flr_same(const char* name, const char* q) { + char buf[512]; ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + snprintf(buf, sizeof buf, "(set T (.db.splayed.get \"" FL_TMP "/%s%d/\"))", name, gen ? 2 : 0); + TEST_ASSERT_TRUE(fl_eval_ok(buf)); + out[gen] = fl_eval(q); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "%s: %s gen %d: %s", name, q, gen, ray_error_msg()); + } + TEST_ASSERT_FMT(out[0]->type == out[1]->type, "%s: %s: type %d vs %d", name, q, out[0]->type, out[1]->type); + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb2 = ray_fmt(out[1], 0); + bool eq = ray_str_len(fa) == ray_str_len(fb2) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb2), ray_str_len(fa)) == 0; + if (!eq) fprintf(stderr, "gen 0: %.*s\ngen 2: %.*s\n", (int)ray_str_len(fa), ray_str_ptr(fa), (int)ray_str_len(fb2), ray_str_ptr(fb2)); + bool beq = eq && fl_bits_eq(out[0], out[1]); + if (eq && !beq && (out[0]->type == -RAY_F64 || out[0]->type == -RAY_F32)) + fprintf(stderr, "gen 0: %a\ngen 2: %a\n", out[0]->f64, out[1]->f64); + ray_release(fa); ray_release(fb2); ray_release(out[0]); ray_release(out[1]); + TEST_ASSERT_FMT(eq, "%s: %s differs", name, q); + TEST_ASSERT_FMT(beq, "%s: %s: float bits differ", name, q); + PASS(); +} +#define FLR_SAME(n, q) do { test_result_t r_ = flr_same((n), (q)); if (r_.status != TEST_PASS) return r_; } while (0) +static test_result_t fl_same(const char* q) { return flr_same("vc", q); } +#define FL_SAME(q) do { test_result_t r_ = fl_same(q); if (r_.status != TEST_PASS) return r_; } while (0) + +/* -0.0 / +0.0 alternating (with 1.5, -2.0 and NaN nulls), in runs forced + * RLE and then scattered forced DICT: every consumer of a float view (group keys, first-n keys, + * take, count, in, sum, the fused filter) equals generation 0, the zeros + * grouping together. */ +static test_result_t test_view_consumers(void) { + const int64_t n = 70000; /* two chunks */ + static const int forces[] = { RAY_ENC_RLE, RAY_ENC_DICT }; + for (size_t fi = 0; fi < 2; fi++) { + ray_t* k = ray_vec_new(RAY_I64, n); + ray_t* h = ray_vec_new(RAY_I64, n); + ray_t* f = ray_vec_new(RAY_F64, n); + TEST_ASSERT_TRUE(k && h && f); + k->len = h->len = f->len = n; + const double pat[6] = { bd(NEG0_64), 0.0, 1.5, bd(NEG0_64), 0.0, -2.0 }; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(k))[i] = i; + ((int64_t*)ray_data(h))[i] = i % 3; + /* RLE: runs of 37 rows; DICT: scattered, so its codes child is + * FOR_BP (runs would make it RLE, which the view declines) */ + const int64_t at = forces[fi] == RAY_ENC_RLE ? (i / 37) % 6 : (i * 7) % 6; + ((double*)ray_data(f))[i] = i % 997 == 5 ? NULL_F64 : pat[at]; + } + f->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* tb = ray_table_new(3); + tb = ray_table_add_col(tb, ray_sym_intern("k", 1), k); ray_release(k); + tb = ray_table_add_col(tb, ray_sym_intern("h", 1), h); ray_release(h); + tb = ray_table_add_col(tb, ray_sym_intern("f", 1), f); ray_release(f); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("W", 1), tb), RAY_OK); + ray_release(tb); + TEST_ASSERT_TRUE(fl_eval_ok("(.db.splayed.set \"" FL_TMP "/vc0/\" W {compress: false})")); + ray_encw_test_force_float(forces[fi]); + bool ok = fl_eval_ok("(.db.splayed.set \"" FL_TMP "/vc2/\" W {compress: true})"); + ray_encw_test_force_float(-1); + TEST_ASSERT_TRUE(ok); + /* every vector of f is a view of the forced encoding */ + TEST_ASSERT_TRUE(fl_eval_ok("(set T (.db.splayed.get \"" FL_TMP "/vc2/\"))")); + ray_t* t = fl_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern("f", 1)); + TEST_ASSERT_NOT_NULL(encv); + for (int64_t v = 0; v < (n + 1023) / 1024; v++) { + ray_t* err = NULL; + int r = ray_enccol_vview(ray_enccol_of(encv), v, &fl_vw, &err); + if (err) ray_error_free(err); + TEST_ASSERT_FMT(r == 1 && fl_vw.enc == forces[fi], "force %d vector %lld: view %d enc %d", + forces[fi], (long long)v, r, fl_vw.enc); + } + ray_release(t); + static const char* const qs[] = { + "(select {c: (count k) s: (sum k) from: T by: f})", + "(select {c: (count k) from: T by: {f: f h: h}})", + "(select {c: (count k) from: T by: f take: 2})", + "(select {c: (count k) s: (sum k) from: T by: {f: f h: h} take: 4})", + "(select {c: (count k) from: T by: {h: h f: f} take: 5})", + "(take (at T 'f) 100)", + "(select {f: f k: k from: T where: (> k 1000) take: 50})", + "(count (select {from: T where: (== f 0.0)}))", + "(count (select {from: T where: (== f -0.0)}))", + "(count (select {from: T where: (!= f 0.0)}))", + "(count (select {from: T where: (< f 0.0)}))", + "(count (select {from: T where: (<= f -0.0)}))", + "(count (select {from: T where: (>= f -0.0)}))", + "(count (select {from: T where: (> f -1.0)}))", + "(count (select {from: T where: (in f [0.0 1.5])}))", + "(count (select {from: T where: (in f [-0.0])}))", + "(count (select {from: T where: (not (in f [-2.0]))}))", + "(sum (at T 'f))", + "(select {s: (sum f) c: (count f) from: T where: (>= k 1000)})", + "(select {s: (sum k) c: (count k) from: T where: (== f 0.0)})", + "(select {s: (sum k) from: T where: (and (== f -0.0) (> k 500))})", + "(select {s: (sum k) from: T where: (or (< f -1.0) (> f 1.0))})", + NULL, + }; + for (int i = 0; qs[i]; i++) FL_SAME(qs[i]); + /* the fused filter answers f from its views: nothing of f decoded */ + TEST_ASSERT_TRUE(fl_eval_ok("(set T (.db.splayed.get \"" FL_TMP "/vc2/\"))")); + ray_t* r = fl_eval("(select {k: k from: T where: (>= f 0.0)})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(r); + t = fl_eval("T"); + encv = ray_table_get_col_enc(t, ray_sym_intern("f", 1)); + uint64_t fdec = encv ? atomic_load(&ray_enccol_of(encv)->decoded_bytes) : 1; + ray_release(t); + TEST_ASSERT_FMT(fdec == 0, "force %d: f decoded %llu bytes", forces[fi], (unsigned long long)fdec); + TEST_ASSERT_TRUE(fl_eval_ok("(set T 0)")); + } + PASS(); +} + +/* Bytes decoded from column col of generation 2 (vc2) while q runs on a + * fresh load of it (the column's own counter), or UINT64_MAX on an error. */ +static uint64_t fl_q_decoded(const char* q, const char* col) { + if (!fl_eval_ok("(set T (.db.splayed.get \"" FL_TMP "/vc2/\"))")) return UINT64_MAX; + ray_t* r = fl_eval(q); + if (!r || RAY_IS_ERR(r)) { if (r) ray_error_free(r); return UINT64_MAX; } + ray_release(r); + ray_t* t = fl_eval("T"); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return UINT64_MAX; } + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))); + uint64_t b = encv ? atomic_load(&ray_enccol_of(encv)->decoded_bytes) : UINT64_MAX; + ray_release(t); + return b; +} + +/* compress_float.rfl's filters with the encoding forced and asserted, so + * they run on views: F64 f and F32 g, forced CONST (one value per vector, + * some nulls), RLE (runs of 3, the rfl's zs) and DICT (scattered), equal to + * generation 0, and nothing of the filtered column decoded. */ +static test_result_t test_filter_views(void) { + const int64_t n = 70000; /* two chunks */ + static const int forces[] = { RAY_ENC_CONST, RAY_ENC_RLE, RAY_ENC_DICT }; + const double dv[4] = { -3.5, bd(NEG0_64), 0.0, 2.25 }; + const double cv[3] = { bd(NEG0_64), 0.0, 2.25 }; + for (size_t fi = 0; fi < 3; fi++) { + ray_t* k = ray_vec_new(RAY_I64, n); + ray_t* f = ray_vec_new(RAY_F64, n); + TEST_ASSERT_TRUE(k && f); + k->len = f->len = n; + double* fd = (double*)ray_data(f); + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(k))[i] = i; + fd[i] = forces[fi] == RAY_ENC_CONST ? cv[(i / 1024) % 3] + : forces[fi] == RAY_ENC_RLE ? dv[(i / 3) % 4] : dv[(i * 7) % 4]; + if (i % 5000 == 7) fd[i] = NULL_F64; + } + f->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* g = fl_typed(RAY_F32, fd, n); + ray_t* tb = ray_table_new(3); + tb = ray_table_add_col(tb, ray_sym_intern("k", 1), k); ray_release(k); + tb = ray_table_add_col(tb, ray_sym_intern("f", 1), f); ray_release(f); + tb = ray_table_add_col(tb, ray_sym_intern("g", 1), g); ray_release(g); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("W", 1), tb), RAY_OK); + ray_release(tb); + TEST_ASSERT_TRUE(fl_eval_ok("(.db.splayed.set \"" FL_TMP "/vc0/\" W {compress: false})")); + ray_encw_test_force_float(forces[fi]); + bool ok = fl_eval_ok("(.db.splayed.set \"" FL_TMP "/vc2/\" W {compress: true})"); + ray_encw_test_force_float(-1); + TEST_ASSERT_TRUE(ok); + /* every vector of f and g is a view of the forced encoding */ + TEST_ASSERT_TRUE(fl_eval_ok("(set T (.db.splayed.get \"" FL_TMP "/vc2/\"))")); + ray_t* t = fl_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + for (int ci = 0; ci < 2; ci++) { + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern(ci ? "g" : "f", 1)); + TEST_ASSERT_NOT_NULL(encv); + for (int64_t v = 0; v < (n + 1023) / 1024; v++) { + ray_t* err = NULL; + int r = ray_enccol_vview(ray_enccol_of(encv), v, &fl_vw, &err); + if (err) ray_error_free(err); + TEST_ASSERT_FMT(r == 1 && fl_vw.enc == forces[fi], "force %d column %s vector %lld: view %d enc %d", + forces[fi], ci ? "g" : "f", (long long)v, r, fl_vw.enc); + } + } + ray_release(t); + static const char* const conds[] = { + "(== %s 0.0)", "(== %s -0.0)", "(< %s 0.0)", "(>= %s -0.0)", "(!= %s 0.0)", + "(> %s 1.0)", "(<= %s -3.5)", NULL, + }; + char cnd[64], q[256]; + for (int ci = 0; ci < 2; ci++) + for (int i = 0; conds[i]; i++) { + snprintf(cnd, sizeof cnd, conds[i], ci ? "g" : "f"); + snprintf(q, sizeof q, "(count (select {from: T where: %s}))", cnd); + FL_SAME(q); + snprintf(q, sizeof q, "(select {s: (sum k) c: (count k) from: T where: %s})", cnd); + FL_SAME(q); + snprintf(q, sizeof q, "(select {k: k from: T where: %s})", cnd); + uint64_t dec = fl_q_decoded(q, ci ? "g" : "f"); + TEST_ASSERT_FMT(dec == 0, "force %d %s: decoded %llu bytes", forces[fi], q, (unsigned long long)dec); + } + TEST_ASSERT_TRUE(fl_eval_ok("(set T 0)")); + } + PASS(); +} + +/* ---- the conformance battery (Task 7): every answer against generation 0 + * (the same data saved {compress: false}); every float column is built in + * C and bound (D10: -0.0 as its bit pattern, #824) ---- */ + +/* Binds table tb (consumed) as W and saves it as 0 (generation 0) + * and 2 (generation 2, every float vector forced to enc, -1: + * selection). False on any failure. */ +static bool flr_save(const char* name, ray_t* tb, int enc) { + if (!tb || RAY_IS_ERR(tb)) return false; + ray_err_t e = ray_env_set(ray_sym_intern("W", 1), tb); + ray_release(tb); + if (e != RAY_OK) return false; + char q[256]; + snprintf(q, sizeof q, "(.db.splayed.set \"" FL_TMP "/%s0/\" W {compress: false})", name); + if (!fl_eval_ok(q)) return false; + ray_encw_test_force_float(enc); + snprintf(q, sizeof q, "(.db.splayed.set \"" FL_TMP "/%s2/\" W {compress: true})", name); + bool ok = fl_eval_ok(q); + ray_encw_test_force_float(-1); + return ok && fl_eval_ok("(set W 0)"); +} +/* A table of the given columns (each consumed). */ +static ray_t* flr_table(int n, const char* const* names, ray_t* const* cols) { + ray_t* tb = ray_table_new(n); + for (int i = 0; i < n; i++) { + tb = ray_table_add_col(tb, ray_sym_intern(names[i], strlen(names[i])), cols[i]); + ray_release(cols[i]); + } + return tb; +} +static ray_t* flr_til(int64_t n) { + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = i; + return v; +} +/* Encoding of vector vec of column col of 2 (its descriptor), or -1. */ +static int flr_enc(const char* name, const char* col, int64_t vec) { + char q[256]; + snprintf(q, sizeof q, "(.db.splayed.get \"" FL_TMP "/%s2/\")", name); + ray_t* t = fl_eval(q); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return -1; } + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))); + int enc = -1; + if (encv) { + enc = ray_enccol_descs(ray_enccol_of(encv), vec / RAY_ENC_VECS_PER_CHUNK)[vec % RAY_ENC_VECS_PER_CHUNK].encoding; + } + ray_release(t); + return enc; +} +/* Rows of float column v holding -0.0 and +0.0, by bit pattern. */ +static void flr_zeros(ray_t* v, int64_t* neg, int64_t* pos) { + *neg = *pos = 0; + for (int64_t i = 0; i < v->len; i++) { + uint64_t b = 0; + if (v->type == RAY_F64) memcpy(&b, (const double*)ray_data(v) + i, 8); + else { uint32_t w; memcpy(&w, (const float*)ray_data(v) + i, 4); b = w == (uint32_t)NEG0_32 ? NEG0_64 : w; } + if (b == NEG0_64) (*neg)++; else if (b == 0) (*pos)++; + } +} +/* The live file of column col of splayed directory dir (a "/tmp" path): + * saves publish a generation through .current (#649 / #713). */ +static bool flr_live(const char* dir, const char* col, char* out, size_t cap) { + char cur[1024]; + if (ray_splay_resolve_dir(ray_test_tmp(dir), cur, sizeof cur) != RAY_OK) return false; + int n = snprintf(out, cap, "%s/%s", cur, col); + return n > 0 && (size_t)n < cap; +} +/* Files a and b hold the same bytes: 0, else a negative step. */ +static int flr_same_file(const char* a, const char* b) { + FILE* fa = fopen(a, "rb"); FILE* fb2 = fopen(b, "rb"); + int rc = 0; + uint8_t ba[65536], bb[65536]; + if (!fa || !fb2) rc = -1; + while (rc == 0) { + size_t na = fread(ba, 1, sizeof ba, fa), nb = fread(bb, 1, sizeof bb, fb2); + if (na != nb) rc = -2; + else if (memcmp(ba, bb, na) != 0) rc = -3; + else if (na == 0) break; + } + if (fa) fclose(fa); + if (fb2) fclose(fb2); + return rc; +} + +/* Review focus 1: both zeros through every float encoding, F64 and F32; + * every comparison with both literals, in, top-k, which zero min / max + * return (6000 rows, below RAY_PARALLEL_THRESHOLD: P3's ruling on the + * zero sign) and the column itself, bit for bit. */ +static test_result_t test_signed_zeros_battery(void) { + _Static_assert(RAY_PARALLEL_THRESHOLD > 6000, "the zero-sign tables must stay serial"); + /* In a release build the rayfall literal 0.0 parses as -0.0 (#850), so + * there the "0.0" and "-0.0" query literals below are the same constant + * and the distinct-literal comparisons are only partly covered; the data + * is C-built, so its zeros keep their signs in every build. */ + static const int encs[] = { -1, RAY_ENC_RAW, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + static const char* const qs[] = { + "(count (select {from: T where: (== f 0.0)}))", "(count (select {from: T where: (== f -0.0)}))", + "(count (select {from: T where: (< f 0.0)}))", "(count (select {from: T where: (<= f -0.0)}))", + "(count (select {from: T where: (> f -0.0)}))", "(count (select {from: T where: (>= f 0.0)}))", + "(count (select {from: T where: (!= f 0.0)}))", "(count (select {from: T where: (!= f -0.0)}))", + "(count (select {from: T where: (in f [0.0 -3.5])}))", "(count (select {from: T where: (in f [-0.0])}))", + "(count (select {from: T where: (not (in f [0.0]))}))", + "(select {f: f k: k from: T asc: f take: 5})", "(select {f: f k: k from: T desc: f take: 5})", + "(select {f: f k: k from: T where: (> k 1000) asc: f take: 5})", + "(select {f: f k: k from: T where: (> k 1000) desc: f take: 5})", + "(min (at T 'f))", "(max (at T 'f))", "(at T 'f)", NULL, + }; + const int64_t n = 6000; + static double d[6000]; + const double dv[4] = { -3.5, bd(NEG0_64), 0.0, 2.25 }; + for (int t = 0; t < 2; t++) /* zeros only; zeros among values */ + for (int ty = 0; ty < 2; ty++) /* F64, F32 */ + for (size_t k = 0; k < sizeof encs / sizeof encs[0]; k++) { + for (int64_t i = 0; i < n; i++) d[i] = t == 0 ? ((i % 2048) < 1024 ? bd(NEG0_64) : 0.0) : dv[(i / 3) % 4]; + ray_t* f = fl_typed(ty ? RAY_F32 : RAY_F64, d, n); + int64_t zn, zp; flr_zeros(f, &zn, &zp); + TEST_ASSERT_FMT(zn > 0 && zp > 0, "table %d type %d: %lld -0.0 and %lld +0.0 rows", t, ty, (long long)zn, (long long)zp); + char name[16]; snprintf(name, sizeof name, "z%d%d_%zu", t, ty, k); + TEST_ASSERT_TRUE(flr_save(name, flr_table(2, (const char* const[]){ "f", "k" }, (ray_t* const[]){ f, flr_til(n) }), encs[k])); + if (encs[k] >= 0) + for (int64_t v = 0; v < (n + 1023) / 1024; v++) + TEST_ASSERT_FMT(flr_enc(name, "f", v) == encs[k], "%s vector %lld: encoding %d", name, (long long)v, flr_enc(name, "f", v)); + for (int i = 0; qs[i]; i++) FLR_SAME(name, qs[i]); + } + /* CONST: a vector of -0.0, then one of +0.0 */ + for (int ty = 0; ty < 2; ty++) { + for (int64_t i = 0; i < 2048; i++) d[i] = i < 1024 ? bd(NEG0_64) : 0.0; + ray_t* f = fl_typed(ty ? RAY_F32 : RAY_F64, d, 2048); + int64_t zn, zp; flr_zeros(f, &zn, &zp); + TEST_ASSERT_TRUE(zn == 1024 && zp == 1024); + const char* name = ty ? "zc1" : "zc0"; + TEST_ASSERT_TRUE(flr_save(name, flr_table(2, (const char* const[]){ "f", "k" }, (ray_t* const[]){ f, flr_til(2048) }), RAY_ENC_CONST)); + TEST_ASSERT_EQ_I(flr_enc(name, "f", 0), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(flr_enc(name, "f", 1), RAY_ENC_CONST); + for (int i = 0; qs[i]; i++) FLR_SAME(name, qs[i]); + } + PASS(); +} + +/* Review focus 5: float sums bit-identical while vectors change encoding: + * cancellation, overflow to infinity, all -0.0, ALP decimals, and a column + * whose vectors select CONST and DICT in turn (chunk 0's dictionary holds + * every value, so DICT, its codes RLE where they run, takes the rest). The + * 70000-row tables pass RAY_PARALLEL_THRESHOLD: both generations fold their + * float partials per chunk in chunk order (#744), so the sums are the same + * bits at any worker count. */ +static test_result_t test_float_sums(void) { + static const int64_t ns[] = { 70000, 4096, 5000, 70000, 70000 }; + static const int encs[] = { -1, RAY_ENC_RAW, RAY_ENC_RLE, RAY_ENC_CONST, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + _Static_assert(70000 > RAY_PARALLEL_THRESHOLD, "the float sums run in parallel"); + for (int t = 0; t < 5; t++) + for (size_t k = 0; k < sizeof encs / sizeof encs[0]; k++) { + if (encs[k] == RAY_ENC_CONST && t != 2) continue; /* constant per vector only there */ + const int64_t n = ns[t]; + ray_t* f = ray_vec_new(RAY_F64, n); f->len = n; + double* fd = (double*)ray_data(f); + uint64_t s = 5; + for (int64_t j = 0; j < n; j++) { + s ^= s << 13; s ^= s >> 7; s ^= s << 17; + const int64_t v = j / 1024; /* t == 4: by vector */ + fd[j] = t == 0 ? ((j % 1024) < 512 ? 1e16 : 1.0) + : t == 1 ? (j % 2 == 0 ? 1.7976931348623157e308 : 1e308) + : t == 2 ? bd(NEG0_64) + : t == 3 ? (double)(j % 997) / 10.0 + : v % 4 == 0 ? 1e16 + (double)v /* CONST */ + : v % 4 == 1 ? (double)((j / 64) % 5) * 3.3 /* runs */ + : v % 4 == 2 ? (j % 3 ? -1e16 : 0.1) /* cancellation */ + : (double)(s >> 11) / 1024.0 - 4e12; /* random */ + } + char name[16]; snprintf(name, sizeof name, "s%d_%zu", t, k); + TEST_ASSERT_TRUE(flr_save(name, flr_table(1, (const char* const[]){ "f" }, (ray_t* const[]){ f }), encs[k])); + if (encs[k] >= 0) TEST_ASSERT_FMT(flr_enc(name, "f", 0) == encs[k], "%s: encoding %d", name, flr_enc(name, "f", 0)); + if (t == 4 && encs[k] < 0) { /* the vectors change encoding */ + int seen[RAY_ENC_ALP_RD + 1] = { 0 }; + for (int64_t v = 0; v < n / 1024; v++) { int e = flr_enc(name, "f", v); if (e >= 0 && e <= RAY_ENC_ALP_RD) seen[e] = 1; } + TEST_ASSERT_FMT(seen[RAY_ENC_CONST] && seen[RAY_ENC_DICT], "encodings of vectors 0-3: %d %d %d %d", + flr_enc(name, "f", 0), flr_enc(name, "f", 1), flr_enc(name, "f", 2), flr_enc(name, "f", 3)); + } + FLR_SAME(name, "(sum (at T 'f))"); + FLR_SAME(name, "(avg (at T 'f))"); + FLR_SAME(name, "(select {s: (sum f) from: T where: (> f -1e300)})"); + FLR_SAME(name, "(select {s: (sum f) a: (avg f) from: T})"); + } + PASS(); +} + +/* Float first keys are never pruned: nulls, both zeros and both infinities, + * results and order equal to generation 0 under every float encoding. */ +static test_result_t test_topk_floats(void) { + const int64_t n = 140000; + static const int encs[] = { -1, RAY_ENC_RAW, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + static const char* const qs[] = { + "(select {f: f v: v from: T asc: f take: 20})", "(select {f: f v: v from: T desc: f take: 20})", + "(select {f: f v: v from: T where: (> v 1000) asc: f take: 5})", + "(select {f: f v: v from: T where: (> v 1000) desc: f take: 5})", NULL, + }; + for (size_t k = 0; k < sizeof encs / sizeof encs[0]; k++) { + ray_t* f = ray_vec_new(RAY_F64, n); f->len = n; + double* fd = (double*)ray_data(f); + for (int64_t j = 0; j < n; j++) + fd[j] = j % 11 == 0 ? NULL_F64 : j % 7 == 0 ? bd(NEG0_64) : j % 13 == 0 ? INFINITY + : j % 17 == 0 ? -INFINITY : (double)((j * 7919) % 1000) / 4.0; + f->attrs |= RAY_ATTR_HAS_NULLS; + int64_t zn, zp; flr_zeros(f, &zn, &zp); + TEST_ASSERT_TRUE(zn > 0 && zp > 0); + char name[16]; snprintf(name, sizeof name, "tk%zu", k); + TEST_ASSERT_TRUE(flr_save(name, flr_table(2, (const char* const[]){ "f", "v" }, (ray_t* const[]){ f, flr_til(n) }), encs[k])); + if (encs[k] >= 0) TEST_ASSERT_FMT(flr_enc(name, "f", 70) == encs[k], "%s: encoding %d", name, flr_enc(name, "f", 70)); + for (int i = 0; qs[i]; i++) { + ray_fused_topk_counters_reset(); + FLR_SAME(name, qs[i]); + uint64_t ch = 1, ve = 1; ray_fused_topk_test_pruned(&ch, &ve); + TEST_ASSERT_FMT(ch == 0 && ve == 0, "%s %s: pruned %llu chunk slots, %llu vectors", name, qs[i], + (unsigned long long)ch, (unsigned long long)ve); + } + } + PASS(); +} + +/* The deepest legal float chain is depth 2 (Decisions: "Cascade depth"): + * ALP, its ints child RLE (depth 1), the RLE values child a leaf (depth 2). */ +static test_result_t test_depth_bound(void) { + uint64_t v[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) v[i] = db((double)(i / 256) * 0.5); /* ALP ints: four runs */ + ray_enc_buf_t* bp = &fl_buf; /* freed in teardown */ + TEST_ASSERT_TRUE(ray_enc_alp_write(v, RAY_ENC_VEC, 64, 1, 0, bp)); + TEST_ASSERT_EQ_I(bp->p[8], RAY_ENC_RLE); /* ints child, depth 1 */ + TEST_ASSERT_TRUE(bp->p[8 + 8 + 8] == RAY_ENC_RAW || bp->p[8 + 8 + 8] == RAY_ENC_FOR_BP); /* its values, depth 2 */ + uint64_t out[RAY_ENC_VEC]; + TEST_ASSERT_EQ_I(ray_enc_alp_read(bp->p, bp->len, RAY_ENC_VEC, 64, out), (int64_t)bp->len); + TEST_ASSERT_TRUE(memcmp(out, v, sizeof v) == 0); + PASS(); +} + +/* Float filters on CONST, RLE and DICT vectors (each forced, every vector + * checked): no materialization, and no vector decoded where the encoded + * form answers; the answers equal generation 0. */ +static test_result_t test_no_materialization(void) { + const int64_t n = 70000; + static const int encs[] = { RAY_ENC_CONST, RAY_ENC_RLE, RAY_ENC_DICT }; + const double dv[4] = { -3.5, bd(NEG0_64), 0.0, 2.25 }; + const double cv[3] = { bd(NEG0_64), 0.0, 2.25 }; + static const char* const qs[] = { + "(count (select {from: T where: (<= f 0.0)}))", "(count (select {from: T where: (== f -0.0)}))", + "(count (select {from: T where: (> f -0.0)}))", "(count (select {from: T where: (!= f 2.25)}))", NULL, + }; + for (size_t k = 0; k < sizeof encs / sizeof encs[0]; k++) { + ray_t* f = ray_vec_new(RAY_F64, n); f->len = n; + double* fd = (double*)ray_data(f); + for (int64_t i = 0; i < n; i++) + fd[i] = encs[k] == RAY_ENC_CONST ? cv[(i / 1024) % 3] /* one value per vector */ + : encs[k] == RAY_ENC_RLE ? dv[(i / 3) % 4] /* runs of 3 */ + : dv[(i * 7) % 4]; /* scattered: FOR_BP codes */ + int64_t zn, zp; flr_zeros(f, &zn, &zp); + TEST_ASSERT_TRUE(zn > 0 && zp > 0); + char name[16]; snprintf(name, sizeof name, "nm%zu", k); + TEST_ASSERT_TRUE(flr_save(name, flr_table(1, (const char* const[]){ "f" }, (ray_t* const[]){ f }), encs[k])); + for (int64_t v = 0; v < (n + 1023) / 1024; v++) + TEST_ASSERT_FMT(flr_enc(name, "f", v) == encs[k], "%s vector %lld: encoding %d", name, (long long)v, flr_enc(name, "f", v)); + char load[128]; + snprintf(load, sizeof load, "(set T (.db.splayed.get \"" FL_TMP "/%s2/\"))", name); + for (int i = 0; qs[i]; i++) { + TEST_ASSERT_TRUE(fl_eval_ok(load)); + ray_enc_counters_reset(); + TEST_ASSERT_TRUE(fl_eval_ok(qs[i])); + ray_enc_counters_t c; ray_enc_counters_get(&c); + TEST_ASSERT_FMT(c.materialized == 0 && c.decoded_bytes == 0, "%s %s: materialized %llu, decoded %llu bytes", name, qs[i], + (unsigned long long)c.materialized, (unsigned long long)c.decoded_bytes); + FLR_SAME(name, qs[i]); + } + } + PASS(); +} + +/* Chunk 0 of the stream / re-save columns: shape 0 is the brief's (i % 300) + * / 4, whose stride-32 training samples are all integers, so the trained + * ALP candidate is (0, 0) and the later two-decimal vectors take ALP_RD + * (the sampler weakness carried to Task 8); shape 1's samples carry two + * decimals, so the later vectors take the chunk-0 candidates (ALP). */ +static double flr_shape(int shape, int64_t i) { + if (i >= 65536) return (double)((i * 7919) % 100000) / 100.0 + 2000.0; + return shape == 0 ? (double)(i % 300) / 4.0 : (double)(i % 64) * 1.37 + 1000.01; +} + +/* The stream writer and the resident writer agree byte for byte on a float + * column that trains VALUE_DICT and the ALP candidates (spec "Encoding + * selection"): chunk 0 DICT, chunks 1-2 ALP. %.17g round-trips every + * double through the parser, so both writers see the same bits. */ +static test_result_t test_stream_equals_resident(void) { + for (int shape = 0; shape < 2; shape++) { + FILE* f = fopen(ray_test_tmp(FL_TMP "/in.csv"), "w"); + TEST_ASSERT_NOT_NULL(f); + fprintf(f, "f\n"); + for (int64_t i = 0; i < 140000; i++) fprintf(f, "%.17g\n", flr_shape(shape, i)); + fclose(f); + (void)ray_test_rm_rf(ray_test_tmp(FL_TMP "/cs")); (void)ray_test_rm_rf(ray_test_tmp(FL_TMP "/c0")); + TEST_ASSERT_TRUE(fl_eval_ok("(.csv.splayed {compress: true} [F64] \"" FL_TMP "/in.csv\" \"" FL_TMP "/cs/\")")); + TEST_ASSERT_TRUE(fl_eval_ok("(.csv.splayed {compress: false} [F64] \"" FL_TMP "/in.csv\" \"" FL_TMP "/c0/\")")); + ray_t* t0 = fl_eval("(.db.splayed.get \"" FL_TMP "/c0/\")"); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0)); + ray_t* col = ray_table_col(t0, ray_sym_intern("f", 1)); + /* the parser gives the written bits; both writers read through it, + * so the comparison below holds either way. The one tolerated + * difference is +0.0 read as -0.0: release builds' ray_parse_f64 + * folds the zero's sign under -fno-signed-zeros (#850). + * TODO(#850): remove this tolerance once #850 is fixed. */ + bool bits = col && !RAY_IS_ERR(col) && col->type == RAY_F64 && col->len == 140000; + int64_t bad = -1; + for (int64_t i = 0; bits && i < 140000; i++) { + uint64_t w = db(flr_shape(shape, i)), r; memcpy(&r, (const double*)ray_data(col) + i, 8); + if (!(bits = r == w || (w == 0 && r == NEG0_64)) ) bad = i; + } + if (bad >= 0) fprintf(stderr, "shape %d row %lld: wrote %a, read %a\n", shape, (long long)bad, + flr_shape(shape, bad), ((const double*)ray_data(col))[bad]); + ray_err_t e = bits ? ray_col_save_gen(col, ray_test_tmp(FL_TMP "/rs_f"), 2) : RAY_ERR_TYPE; + ray_release(t0); + TEST_ASSERT_FMT(bits, "shape %d: the parser did not give the written bits", shape); + TEST_ASSERT_EQ_I(e, RAY_OK); /* the resident writer, plain source */ + char sp[1200]; + TEST_ASSERT_TRUE(flr_live(FL_TMP "/cs/", "f", sp, sizeof sp)); + TEST_ASSERT_FMT(flr_same_file(sp, ray_test_tmp(FL_TMP "/rs_f")) == 0, "shape %d: stream and resident bytes differ", shape); + TEST_ASSERT_EQ_I(desc_enc(sp, 0), RAY_ENC_DICT); /* VALUE_DICT trained */ + if (shape == 1) { + TEST_ASSERT_EQ_I(desc_enc(sp, 64), RAY_ENC_ALP); /* ALP candidates trained */ + TEST_ASSERT_EQ_I(desc_enc(sp, 128), RAY_ENC_ALP); + } + } + PASS(); +} + +/* An encoded source re-saved (the range writer, colw_gen2_range) gives the + * bytes of the resident save of the same data: DICT column d (both zeros, + * nulls), column a DICT in chunk 0 and ALP after it, F32 twin g; by + * selection and with ALP forced. The re-save materializes nothing. */ +static test_result_t test_resave_equals_resident(void) { + const int64_t n = 140000; + static double ad[140000], dd[140000]; + const double dv[6] = { bd(NEG0_64), 0.0, 0.5, 1.0, 1.5, -2.0 }; + for (int64_t i = 0; i < n; i++) { + dd[i] = i % 4999 == 3 ? NULL_F64 : dv[(i * 7) % 6]; + ad[i] = i % 5000 == 7 ? NULL_F64 : flr_shape(1, i); + } + static const int encs[] = { -1, RAY_ENC_ALP }; + static const char* const cols[] = { "d", "a", "g" }; + for (size_t k = 0; k < 2; k++) { + ray_t* tb = flr_table(3, cols, (ray_t* const[]){ fl_typed(RAY_F64, dd, n), fl_typed(RAY_F64, ad, n), fl_typed(RAY_F32, ad, n) }); + TEST_ASSERT_TRUE(flr_save(k ? "rf" : "rs", tb, encs[k])); + const char* name = k ? "rf" : "rs"; + if (k == 0) { + TEST_ASSERT_EQ_I(flr_enc(name, "d", 0), RAY_ENC_DICT); + TEST_ASSERT_EQ_I(flr_enc(name, "d", 100), RAY_ENC_DICT); + TEST_ASSERT_EQ_I(flr_enc(name, "a", 0), RAY_ENC_DICT); + TEST_ASSERT_EQ_I(flr_enc(name, "a", 64), RAY_ENC_ALP); + } else + for (int c = 0; c < 3; c++) TEST_ASSERT_EQ_I(flr_enc(name, cols[c], 0), RAY_ENC_ALP); + char q[256]; + snprintf(q, sizeof q, "(set T (.db.splayed.get \"" FL_TMP "/%s2/\"))", name); + TEST_ASSERT_TRUE(fl_eval_ok(q)); + ray_t* t = fl_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + for (int c = 0; c < 3; c++) TEST_ASSERT_NOT_NULL(ray_table_get_col_enc(t, ray_sym_intern(cols[c], 1))); + ray_release(t); + ray_enc_counters_reset(); + ray_encw_test_force_float(encs[k]); + snprintf(q, sizeof q, "(.db.splayed.set \"" FL_TMP "/%sr/\" T {compress: true})", name); + bool ok = fl_eval_ok(q); + ray_encw_test_force_float(-1); + TEST_ASSERT_TRUE(ok); + ray_enc_counters_t ec; ray_enc_counters_get(&ec); + TEST_ASSERT_EQ_U(ec.materialized, 0); /* by range, never whole */ + TEST_ASSERT_TRUE(ec.decoded_bytes > 0); + TEST_ASSERT_TRUE(fl_eval_ok("(set T 0)")); + for (int c = 0; c < 3; c++) { + char dr[64], dz[64], pa[1200], pb[1200]; + snprintf(dr, sizeof dr, FL_TMP "/%s2/", name); snprintf(dz, sizeof dz, FL_TMP "/%sr/", name); + TEST_ASSERT_TRUE(flr_live(dr, cols[c], pa, sizeof pa)); + TEST_ASSERT_TRUE(flr_live(dz, cols[c], pb, sizeof pb)); + TEST_ASSERT_FMT(flr_same_file(pa, pb) == 0, "force %d column %s: re-save differs (%d)", encs[k], cols[c], flr_same_file(pa, pb)); + } + /* no float sum: over 64 Ki rows it varies from run to run (float_sums) */ + FLR_SAME(name, "(select {c: (count d) lo: (min a) hi: (max g) from: T where: (== d -0.0)})"); + FLR_SAME(name, "(at T 'd)"); + } + PASS(); +} + +/* P4 interplay: an F64 column with a PART index over blocks -2.5, -0.0, + * +0.0, 1.5 (the zero blocks merge; the key keeps the first row's sign), + * under each forced float encoding: materialization validates the region + * (the zero-sign rule runs on the decoded column, so -0.0 must decode + * exactly) and the zero filters equal generation 0 (which drops the PART). */ +static test_result_t test_part_zero_sign(void) { + const int64_t n = 6000; + static const int encs[] = { RAY_ENC_RAW, RAY_ENC_RLE, RAY_ENC_DICT, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + const double blk[4] = { -2.5, bd(NEG0_64), 0.0, 1.5 }; + static const char* const qs[] = { + "(sum (at (select {from: T where: (== z -0.0)}) 'v))", "(sum (at (select {from: T where: (== z 0.0)}) 'v))", + "(count (select {from: T where: (== z -0.0)}))", "(count (select {from: T where: (in z [0.0 1.5])}))", + "(count (select {from: T where: (< z 0.0)}))", "(count (select {from: T where: (>= z -0.0)}))", + "(at T 'z)", NULL, + }; + for (size_t k = 0; k < sizeof encs / sizeof encs[0]; k++) { + ray_t* z = ray_vec_new(RAY_F64, n); z->len = n; + for (int64_t i = 0; i < n; i++) ((double*)ray_data(z))[i] = blk[i / 1500]; + int64_t zn, zp; flr_zeros(z, &zn, &zp); + TEST_ASSERT_TRUE(zn == 1500 && zp == 1500); + ray_t* r = ray_index_attach_part(&z); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r), "attach: %s", r && RAY_IS_ERR(r) ? ray_error_msg() : "null"); + z = r; + TEST_ASSERT_EQ_I(ray_index_payload(z->index)->u.part.n_parts, 3); + char name[16]; snprintf(name, sizeof name, "pz%zu", k); + TEST_ASSERT_TRUE(flr_save(name, flr_table(2, (const char* const[]){ "z", "v" }, (ray_t* const[]){ z, flr_til(n) }), encs[k])); + for (int64_t v = 0; v < 6; v++) TEST_ASSERT_FMT(flr_enc(name, "z", v) == encs[k], "%s vector %lld", name, (long long)v); + /* materialization validates the region and attaches the PART */ + char q[256]; + snprintf(q, sizeof q, "(.db.splayed.get \"" FL_TMP "/%s2/\")", name); + ray_t* t = fl_eval(q); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern("z", 1)); + TEST_ASSERT_TRUE(encv && ray_enccol_of(encv)->hdr.index_kind == RAY_IDX_PART); + ray_t* m = ray_table_col(t, ray_sym_intern("z", 1)); + bool mok = m && !RAY_IS_ERR(m); + if (!mok) fprintf(stderr, "%s: %s\n", name, ray_error_msg()); + bool kind = mok && ray_index_kind(m) == RAY_IDX_PART; + ray_index_t* ix = kind ? ray_index_payload(m->index) : NULL; + bool parts = ix && ix->u.part.n_parts == 3 && ix->u.part.keys && ix->u.part.keys->type == RAY_F64; + uint64_t kb[3] = { 0 }; + if (parts) memcpy(kb, ray_data(ix->u.part.keys), sizeof kb); + bool data = mok && m->type == RAY_F64 && m->len == n; + for (int64_t i = 0; data && i < n; i++) data = memcmp((const double*)ray_data(m) + i, &blk[i / 1500], 8) == 0; + ray_release(t); + TEST_ASSERT_FMT(mok, "%s: materialize failed", name); + TEST_ASSERT_FMT(kind && parts, "%s: no three-part PART", name); + TEST_ASSERT_FMT(kb[0] == db(-2.5) && kb[1] == NEG0_64 && kb[2] == db(1.5), "%s: keys %llx %llx %llx", name, + (unsigned long long)kb[0], (unsigned long long)kb[1], (unsigned long long)kb[2]); + TEST_ASSERT_FMT(data, "%s: decoded column differs", name); + for (int i = 0; qs[i]; i++) FLR_SAME(name, qs[i]); + } + PASS(); +} + +/* The P5 exit gate: every shape x length x forced encoding x width, NaN + * payloads and both zeros included, saved and loaded bit-exact. */ +static void sweep_fill(int shape, int8_t type, int64_t n, void* out) { + uint64_t s = 0x9E3779B97F4A7C15ull + (uint64_t)shape; + for (int64_t i = 0; i < n; i++) { + s ^= s << 13; s ^= s >> 7; s ^= s << 17; + double x; + switch (shape) { + case 0: x = (double)(s % 100000) / 100.0; break; /* decimals */ + case 1: x = 1.0 + (double)(s >> 11) / 9007199254740992.0; break; /* [1, 2) */ + case 2: x = (double)(i / 300); break; /* runs */ + case 3: { static const uint64_t dv[5] = { 0xC00C000000000000ull, 0x8000000000000000ull, 0, /* -3.5, -0.0, +0.0 */ + 0x4002000000000000ull, 0x7E37E43C8800759Cull }; /* 2.25, 1e300 (bits, D10) */ + memcpy(&x, &dv[s % 5], 8); break; } + case 4: { uint64_t b = s & 0x7FEFFFFFFFFFFFFFull; memcpy(&x, &b, 8); break; } /* random bits */ + default: x = 7.75; break; /* constant */ + } + if (s % 41 == 0) x = NULL_F64; + if (s % 53 == 0) { uint64_t b = 0x7FF8000000000000ull | (s & 0xFFFF) | 1; memcpy(&x, &b, 8); } + if (s % 59 == 0) { uint64_t b = 0x8000000000000000ull; memcpy(&x, &b, 8); } /* -0.0 by bits (D10) */ + if (type == RAY_F64) memcpy((uint8_t*)out + i * 8, &x, 8); + else { + float f = (float)x; + if (x != x) { uint32_t b = 0x7FC00000u | (uint32_t)(s & 0x3FF) | 1; memcpy(&f, &b, 4); } + memcpy((uint8_t*)out + i * 4, &f, 4); + } + } +} + +static test_result_t test_sweep_bit_exact(void) { + static const int64_t lens[] = { 0, 1, 1023, 1024, 1025, 65535, 65536, 65537 }; /* spec: lengths 0 .. 65537 */ + static const int forces[] = { -1, RAY_ENC_RAW, RAY_ENC_RLE, RAY_ENC_ALP, RAY_ENC_ALP_RD }; + static const int8_t types[] = { RAY_F64, RAY_F32 }; + const char* p = ray_test_tmp(FL_TMP "/sw"); + int runs = 0; + for (size_t t = 0; t < 2; t++) + for (int shape = 0; shape < 6; shape++) + for (size_t l = 0; l < sizeof lens / sizeof lens[0]; l++) { + fl_vec = ray_vec_new(types[t], lens[l]); fl_vec->len = lens[l]; + sweep_fill(shape, types[t], lens[l], ray_data(fl_vec)); + fl_vec->attrs |= RAY_ATTR_HAS_NULLS; + for (size_t k = 0; k < sizeof forces / sizeof forces[0]; k++) { + int r = fl_roundtrip(fl_vec, forces[k], p); + TEST_ASSERT_FMT(r == 0, "type %d shape %d len %lld force %d: %d", types[t], shape, (long long)lens[l], forces[k], r); + runs++; + } + fl_drop(); + } + TEST_ASSERT_EQ_I(runs, 2 * 6 * 8 * 5); + PASS(); +} + +/* ---- Task 8b: the float fast kernel against dec_floats ---- + * Each body is decoded by the fast kernel and by the reference: the fast + * kernel takes it (every sound body but a DICT one over RAW codes, which + * the reference reads) with the reference's exact bytes, and writes + * nothing past vlen. */ +static char fe_what[160]; +static int fe_check(int8_t ty, const ray_enc_dict_t* dict, uint8_t enc, int nn, const uint8_t* bm, + const uint8_t* body, size_t len, int vlen, bool must) { + static _Alignas(64) uint8_t ref[RAY_ENC_VEC * 8 + 64], fast[RAY_ENC_VEC * 8 + 64]; + const size_t esz = ty == RAY_F32 ? 4 : 8; + memset(ref, 0xA5, sizeof ref); memset(fast, 0x5A, sizeof fast); + const uint64_t* dv = dict ? dict->v : NULL; uint32_t dn = dict ? dict->n : 0; + int rr = ray_enccol_test_decode_float(ty, dv, dn, enc, nn, bm, body, len, vlen, false, ref); + int fr = ray_enccol_test_decode_float(ty, dv, dn, enc, nn, bm, body, len, vlen, true, fast); + if (rr != 1) { snprintf(fe_what + strlen(fe_what), 40, ": ref %d", rr); return 1; } + if (must && fr != 1) { snprintf(fe_what + strlen(fe_what), 40, ": fast %d", fr); return 1; } + for (size_t i = (size_t)vlen * esz; i < sizeof fast; i++) if (fast[i] != 0x5A) { strcat(fe_what, ": wrote past vlen"); return 1; } + if (fr == 1 && memcmp(ref, fast, (size_t)vlen * esz) != 0) { strcat(fe_what, ": bytes differ"); return 1; } + return 0; +} + +/* One case: vals (T-bit patterns) written as enc, then the checks above. */ +static int fe_case(int8_t ty, uint8_t enc, const uint64_t* vals, int vlen, const uint8_t* bm, + const ray_enc_dict_t* dict, const ray_enc_alp_cands_t* c, const char* what) { + const int T = ty == RAY_F32 ? 32 : 64; + snprintf(fe_what, sizeof fe_what, "%s (T %d, enc %d, vlen %d%s)", what, T, enc, vlen, bm ? ", nulls" : ""); + ray_enc_buf_t b = { 0 }; ray_enc_choice_t ch; + if (!ray_enc_float_write(enc, vals, vlen, T, dict, c, &b, &ch)) { strcat(fe_what, ": write"); ray_enc_buf_free(&b); return 1; } + int nn = 0; + if (bm) for (int i = 0; i < vlen; i++) nn += (bm[i >> 3] >> (i & 7)) & 1; + const uint8_t* bmp = nn ? bm : NULL; + const bool take = enc != RAY_ENC_DICT || b.p[0] == RAY_ENC_FOR_BP || b.p[0] == RAY_ENC_RLE; + int bad = fe_check(ty, dict, enc, nn, bmp, b.p, b.len, vlen, take); + ray_enc_buf_free(&b); + return bad; +} + +static uint64_t fe_bits(int8_t ty, double x) { + if (ty == RAY_F64) return db(x); + float f = (float)x; uint32_t u; memcpy(&u, &f, 4); return u; +} + +static test_result_t test_fast_equals_reference(void) { + static uint64_t v[RAY_ENC_VEC], dvals[64]; + static uint8_t bm[RAY_ENC_VEC / 8]; + static const int lens[3] = { RAY_ENC_VEC, 1000, 7 }; + for (int t = 0; t < 2; t++) { + const int8_t ty = t ? RAY_F32 : RAY_F64; + const int T = t ? 32 : 64; + for (int li = 0; li < 3; li++) for (int nul = 0; nul < 2; nul++) { + const int n = lens[li]; + memset(bm, 0, sizeof bm); + if (nul) for (int i = 3; i < n; i += 11) bm[i >> 3] |= (uint8_t)(1u << (i & 7)); + const uint8_t* bmp = nul ? bm : NULL; + /* the null rows hold a NaN (any value is legal there) */ +#define FE_NULLS() do { if (nul) for (int i = 0; i < n; i++) if ((bm[i >> 3] >> (i & 7)) & 1) v[i] = T == 64 ? 0x7FF8000000000123ull : 0x7FC00123u; } while (0) + /* RAW, CONST (with -0.0), RLE of run lengths 1 .. 40 */ + for (int i = 0; i < n; i++) v[i] = frng() & (T == 64 ? 0x7FEFFFFFFFFFFFFFull : 0x7F7FFFFFu); + FE_NULLS(); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_RAW, v, n, bmp, NULL, NULL, "raw"), "%s", fe_what); + for (int i = 0; i < n; i++) v[i] = T == 64 ? NEG0_64 : NEG0_32; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_CONST, v, n, NULL, NULL, NULL, "const -0"), "%s", fe_what); + for (int i = 0, r = 0; i < n; r++) { + const int len = 1 + (r * 13) % 40; + const uint64_t x = fe_bits(ty, (double)((r * 37) % 23) - 11.5); + for (int k = 0; k < len && i < n; k++) v[i++] = x; + } + if (n == RAY_ENC_VEC) v[100] = T == 64 ? NEG0_64 : NEG0_32; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_RLE, v, n, bmp, NULL, NULL, "rle"), "%s", fe_what); + /* DICT over FOR_BP codes and over RLE codes */ + for (int k = 0; k < 40; k++) dvals[k] = fe_bits(ty, -20.0 + 0.75 * k); + ray_enc_dict_t dict = { dvals, 40 }; + for (int i = 0; i < n; i++) v[i] = dvals[(i * 7) % 40]; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_DICT, v, n, bmp, &dict, NULL, "dict for_bp codes"), "%s", fe_what); + for (int i = 0; i < n; i++) v[i] = dvals[(i / 50 * 3) % 40]; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_DICT, v, n, bmp, &dict, NULL, "dict rle codes"), "%s", fe_what); + /* ALP: decimals with exceptions (FOR_BP ints, the exact + * conversion), integers past 2^51 (F64), one repeated value + * (width 0), negative ones */ + ray_enc_alp_cands_t c = { .n = 1 }; + if (T == 64) { + c.c[0].e = 2; c.c[0].f = 0; + for (int i = 0; i < n; i++) v[i] = db((double)((i * 7919) % 100000 - 30000) / 100.0); + v[n / 2] = db(3.14159265358979); + FE_NULLS(); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP, v, n, bmp, NULL, &c, "alp decimals"), "%s", fe_what); + c.c[0].e = 0; c.c[0].f = 0; + for (int i = 0; i < n; i++) v[i] = db((double)((1LL << 53) - 2LL * (i * 31 % 977))); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP, v, n, bmp, NULL, &c, "alp past 2^51"), "%s", fe_what); + for (int i = 0; i < n; i++) v[i] = db(-((double)(1LL << 51)) + (double)(i % 5)); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP, v, n, bmp, NULL, &c, "alp at -2^51"), "%s", fe_what); + for (int i = 0; i < n; i++) v[i] = db(42.0); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP, v, n, NULL, NULL, &c, "alp width 0"), "%s", fe_what); + } else { + c.c[0].e = 0; c.c[0].f = 0; + for (int i = 0; i < n; i++) v[i] = fe_bits(ty, (double)((i * 7919) % 4001 - 2000)); + v[n / 2] = fe_bits(ty, 0.3); + FE_NULLS(); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP, v, n, bmp, NULL, &c, "alp f32"), "%s", fe_what); + } + /* +-inf in the data, so at the statistics' bounds too (and + * narrowed past them: nextafter(-inf, 0) is -max) */ + const uint64_t pinf = T == 64 ? 0x7FF0000000000000ull : 0x7F800000u; + const uint64_t ninf = T == 64 ? 0xFFF0000000000000ull : 0xFF800000u; + for (int i = 0; i < n; i++) v[i] = i % 5 == 1 ? pinf : i % 5 == 3 ? ninf : fe_bits(ty, (double)(i % 17) - 8.0); + FE_NULLS(); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_RAW, v, n, bmp, NULL, NULL, "raw +-inf"), "%s", fe_what); + for (int i = 0; i < n; i++) v[i] = pinf; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_CONST, v, n, NULL, NULL, NULL, "const +inf"), "%s", fe_what); + for (int i = 0; i < n; i++) v[i] = (i / 30) % 3 == 0 ? ninf : (i / 30) % 3 == 1 ? fe_bits(ty, 2.5) : pinf; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_RLE, v, n, bmp, NULL, NULL, "rle +-inf"), "%s", fe_what); + { + static uint64_t idv[5]; + idv[0] = ninf; idv[1] = fe_bits(ty, -1.0); idv[2] = fe_bits(ty, 0.5); idv[3] = fe_bits(ty, 7.0); idv[4] = pinf; + ray_enc_dict_t idict = { idv, 5 }; + for (int i = 0; i < n; i++) v[i] = idv[(i * 3) % 5]; + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_DICT, v, n, bmp, &idict, NULL, "dict +-inf"), "%s", fe_what); + } + { /* ALP: the infinities are exceptions */ + ray_enc_alp_cands_t ic = { .n = 1 }; + ic.c[0].e = 1; ic.c[0].f = 0; + for (int i = 0; i < n; i++) v[i] = i % 97 == 5 ? pinf : i % 97 == 50 ? ninf : fe_bits(ty, (double)(i % 200) / 10.0); + FE_NULLS(); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP, v, n, bmp, NULL, &ic, "alp +-inf"), "%s", fe_what); + } + /* ALP_RD: high-entropy mantissas, few exponents */ + for (int i = 0; i < n; i++) { + const double sc = i % 3 ? 1.0 : 4.0; + v[i] = T == 64 ? db((1.0 + (double)(frng() >> 11) / 9007199254740992.0) * sc) + : fe_bits(ty, (1.0 + (double)(frng() >> 40) / 16777216.0) * sc); + } + FE_NULLS(); + TEST_ASSERT_FMT(!fe_case(ty, RAY_ENC_ALP_RD, v, n, bmp, NULL, NULL, "alp_rd"), "%s", fe_what); +#undef FE_NULLS + } + } + PASS(); +} + +/* Caller control state must fail explicitly, and must not poison once state. */ +static test_result_t test_fp_environment(void) { +#if !defined(FE_UPWARD) + SKIP("FE_UPWARD unavailable"); +#else + fenv_t saved; + if (fegetenv(&saved) != 0) SKIP("cannot save FP environment"); + if (fesetenv(FE_DFL_ENV) != 0 || fesetround(FE_UPWARD) != 0) { + (void)fesetenv(&saved); SKIP("cannot select FE_UPWARD"); + } + const char* why = NULL; + ray_t* err = NULL; + ray_t* back = NULL; + FILE* f = NULL; + ray_encw_t w = {0}; + ray_encw_vec_t vout; ray_encw_vec_init(&vout); + _Alignas(64) uint8_t out[8192]; + char path[512], stream[512]; + const int64_t n = 2055; + if (fesetround(FE_TONEAREST) != 0) { why = "restore nearest"; goto done; } + for (int pass = 0; pass < 2; pass++) { + int8_t type = pass ? RAY_F32 : RAY_F64; + size_t esz = pass ? 4 : 8; + fl_vec = ray_vec_new(type, n); + if (!fl_vec || RAY_IS_ERR(fl_vec)) { + if (fl_vec) ray_error_free(fl_vec); + fl_vec = NULL; why = "allocate input"; goto done; + } + fl_vec->len = n; + for (int64_t i = 0; i < n; i++) { + double d = (double)((i * 73) % 10000) / 100.0; + if (pass) ((float*)ray_data(fl_vec))[i] = (float)d; + else ((double*)ray_data(fl_vec))[i] = d; + } + snprintf(path, sizeof path, "%s/fpenv-%d", ray_test_tmp(FL_TMP), pass); + snprintf(stream, sizeof stream, "%s/fpenv-stream-%d", ray_test_tmp(FL_TMP), pass); + if (fl_roundtrip(fl_vec, RAY_ENC_ALP, path) != 0 || + desc_enc(path, 0) != RAY_ENC_ALP || desc_enc(path, 2) != RAY_ENC_ALP) { + why = "nearest ALP bit roundtrip/fixture"; goto done; + } + fl_map = ray_col_mmap(path); + if (!fl_map || RAY_IS_ERR(fl_map)) { + if (fl_map) ray_error_free(fl_map); + fl_map = NULL; why = "map fresh input"; goto done; + } + ray_enccol_t* e = ray_enccol_of(fl_map); + if (!e || ray_enccol_decoded_peek(fl_map)) { why = "expected undecoded column"; goto done; } + f = fopen(stream, "wb+"); + if (!f) { why = "open stream"; goto done; } + if (ray_encw_begin(&w, f, type, 0, n, 0, 0, 0) != RAY_OK) { why = "begin stream"; goto done; } + if (fesetround(FE_UPWARD) != 0) { why = "select upward"; goto done; } + if (ray_enc_fp_env_ok()) { why = "upward admitted"; goto done; } + if (ray_encw_vec(type, 0, ray_data(fl_vec), NULL, 0, 1024, NULL, &vout) != RAY_ERR_FPENV) { + why = "vector encoder did not reject environment"; goto done; + } + if (ray_encw_chunk(&w, ray_data(fl_vec), NULL, n) != RAY_ERR_FPENV || + w.chunk_i != 0 || w.chunk.len != 0 || w.dict_v || w.alp.n != 0) { + why = "stream rejected after training/mutation"; goto done; + } + err = ray_enccol_decode_vec(e, 2, out, NULL, 0); + if (!err || ray_err_from_obj(err) != RAY_ERR_FPENV) { why = "tail decode did not report fpenv"; goto done; } + ray_error_free(err); err = NULL; + err = ray_enccol_materialize(fl_map); + if (!err || !RAY_IS_ERR(err) || ray_err_from_obj(err) != RAY_ERR_FPENV) { + if (err && !RAY_IS_ERR(err)) err = NULL; /* a successful result is borrowed */ + why = "materializer did not report fpenv"; goto done; + } + ray_error_free(err); err = NULL; + if (ray_enccol_decoded_peek(fl_map)) { why = "rejection cached decoded data"; goto done; } + if (fesetround(FE_TONEAREST) != 0) { why = "restore nearest"; goto done; } + if (ray_encw_chunk(&w, ray_data(fl_vec), NULL, n) != RAY_OK || ray_encw_finish(&w) != RAY_OK) { + why = "stream could not retry after restoring nearest"; goto done; + } + ray_encw_free(&w); w = (ray_encw_t){0}; + if (fclose(f) != 0) { f = NULL; why = "close stream"; goto done; } f = NULL; + back = ray_col_load(stream); + if (!back || RAY_IS_ERR(back) || back->len != n || + memcmp(ray_data(back), ray_data(fl_vec), (size_t)n * esz) != 0) { + why = "restored stream bit roundtrip"; goto done; + } + ray_release(back); back = NULL; + ray_t* plain = ray_enccol_materialize(fl_map); + if (!plain || RAY_IS_ERR(plain)) { err = plain; why = "same-column nearest retry"; goto done; } + if (plain->len != n || memcmp(ray_data(plain), ray_data(fl_vec), (size_t)n * esz) != 0) { + why = "same-column bit mismatch"; goto done; + } + if (fesetround(FE_UPWARD) != 0) { why = "select upward for cache hit"; goto done; } + err = ray_enccol_materialize(fl_map); + if (!err || !RAY_IS_ERR(err) || ray_err_from_obj(err) != RAY_ERR_FPENV) { + if (err && !RAY_IS_ERR(err)) err = NULL; + why = "cached materialization bypassed preflight"; goto done; + } + ray_error_free(err); err = NULL; + if (fesetround(FE_TONEAREST) != 0) { why = "restore nearest"; goto done; } + ray_release(fl_map); fl_map = NULL; fl_drop(); + } +#if defined(__SSE__) + { + unsigned saved_csr = _mm_getcsr(); + const unsigned altered[] = { 0x8000u, 0x0040u, 0x4000u }; /* FTZ, DAZ, SSE-only round-up */ + for (size_t i = 0; i < sizeof altered / sizeof altered[0]; i++) { + _mm_setcsr(saved_csr | altered[i]); + bool accepted = ray_enc_fp_env_ok(); + _mm_setcsr(saved_csr); + if (accepted) { why = "SSE control mismatch admitted"; goto done; } + } + } +#endif +done: + /* No assertion or engine cleanup while this test's nondefault state is live. */ + (void)fesetenv(&saved); + if (err && RAY_IS_ERR(err)) ray_error_free(err); + if (back) { if (RAY_IS_ERR(back)) ray_error_free(back); else ray_release(back); } + ray_encw_vec_free(&vout); ray_encw_free(&w); + if (f) fclose(f); + TEST_ASSERT_FMT(why == NULL, "%s", why ? why : ""); + PASS(); +#endif +} + +const test_entry_t encfloat_entries[] = { + { "encfloat/fp_environment", test_fp_environment, fl_setup, fl_teardown }, + { "encfloat/float_order", test_float_order, fl_setup, fl_teardown }, + { "encfloat/float_train_dict", test_float_train_dict, fl_setup, fl_teardown }, + { "encfloat/float_bodies", test_float_bodies, fl_setup, fl_teardown }, + { "encfloat/new_slots", test_new_slots, fl_setup, fl_teardown }, + { "encfloat/alp_decimals", test_alp_decimals, fl_setup, fl_teardown }, + { "encfloat/alp_signed", test_alp_signed, fl_setup, fl_teardown }, + { "encfloat/alp_edges", test_alp_edges, fl_setup, fl_teardown }, + { "encfloat/alprd_lengths", test_alprd_lengths, fl_setup, fl_teardown }, + { "encfloat/alprd_exceptions", test_alprd_exceptions, fl_setup, fl_teardown }, + { "encfloat/alprd_specials", test_alprd_specials, fl_setup, fl_teardown }, + { "encfloat/float_choice", test_float_choice, fl_setup, fl_teardown }, + { "encfloat/encoder_selects", test_encoder_selects, fl_setup, fl_teardown }, + { "encfloat/nan_payloads", test_nan_payloads, fl_setup, fl_teardown }, + { "encfloat/all_null_floats", test_all_null_floats, fl_setup, fl_teardown }, + { "encfloat/first_chunk_training", test_first_chunk_training, fl_setup, fl_teardown }, + { "encfloat/decode_paths", test_decode_paths, fl_setup, fl_teardown }, + { "encfloat/trailer_counts_in_choice", test_trailer_counts_in_choice, fl_setup, fl_teardown }, + { "encfloat/eval_f64", test_eval_f64, fl_setup, fl_teardown }, + { "encfloat/const_decision_f64", test_const_decision_f64, fl_setup, fl_teardown }, + { "encfloat/view_shapes", test_view_shapes, fl_setup, fl_teardown }, + { "encfloat/view_consumers", test_view_consumers, fl_rt_setup, fl_rt_teardown }, + { "encfloat/filter_views", test_filter_views, fl_rt_setup, fl_rt_teardown }, + { "encfloat/signed_zeros", test_signed_zeros_battery, fl_rt_setup, fl_rt_teardown }, + { "encfloat/stream_equals_resident", test_stream_equals_resident, fl_rt_setup, fl_rt_teardown }, + { "encfloat/resave_equals_resident", test_resave_equals_resident, fl_rt_setup, fl_rt_teardown }, + { "encfloat/float_sums", test_float_sums, fl_rt_setup, fl_rt_teardown }, + { "encfloat/topk_floats", test_topk_floats, fl_rt_setup, fl_rt_teardown }, + { "encfloat/depth_bound", test_depth_bound, fl_setup, fl_teardown }, + { "encfloat/no_materialization", test_no_materialization, fl_rt_setup, fl_rt_teardown }, + { "encfloat/part_zero_sign", test_part_zero_sign, fl_rt_setup, fl_rt_teardown }, + { "encfloat/sweep_bit_exact", test_sweep_bit_exact, fl_setup, fl_teardown }, + { "encfloat/fast_equals_reference", test_fast_equals_reference, fl_setup, fl_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_encfmt.c b/test/test_encfmt.c new file mode 100644 index 000000000..178533bd2 --- /dev/null +++ b/test/test_encfmt.c @@ -0,0 +1,1393 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "store/col.h" +#include "store/encfmt.h" +#include "store/encw.h" +#include "store/enccol.h" +#include "store/stream.h" +#include "vec/str.h" +#include "ops/idxop.h" +#include +#include +#include + +#define ENCFMT_TMP "/tmp/rayforce_encfmt" + +static void encfmt_setup(void) { ray_heap_init(); (void)ray_sym_init(); (void)ray_test_mkdir_p(ray_test_tmp(ENCFMT_TMP)); } +static void encfmt_teardown(void) { ray_test_hooks_off(); ray_sym_destroy(); ray_heap_destroy(); (void)ray_test_rm_rf(ray_test_tmp(ENCFMT_TMP)); } + +static void hdr_set(uint8_t h[32], uint8_t order, uint32_t aux0) { + memset(h, 0, 32); + memcpy(h, &aux0, 4); + h[17] = order; +} + +static test_result_t test_discriminator_pairs(void) { + uint8_t h[32]; + hdr_set(h, 2, RAY_ENC_XENC); TEST_ASSERT_EQ_I(ray_col_gen_of(h), 2); + hdr_set(h, 0, 0); TEST_ASSERT_EQ_I(ray_col_gen_of(h), 0); + hdr_set(h, 0, RAY_ENC_XIDX); TEST_ASSERT_EQ_I(ray_col_gen_of(h), 0); + hdr_set(h, 0, RAY_ENC_XENC); TEST_ASSERT_EQ_I(ray_col_gen_of(h), RAY_ENC_GEN_CORRUPT); + hdr_set(h, 2, RAY_ENC_XIDX); TEST_ASSERT_EQ_I(ray_col_gen_of(h), RAY_ENC_GEN_CORRUPT); + hdr_set(h, 2, 0); TEST_ASSERT_EQ_I(ray_col_gen_of(h), RAY_ENC_GEN_CORRUPT); + hdr_set(h, 0, 0x01020304u); TEST_ASSERT_EQ_I(ray_col_gen_of(h), RAY_ENC_GEN_CORRUPT); + hdr_set(h, 1, 0); TEST_ASSERT_EQ_I(ray_col_gen_of(h), RAY_ENC_GEN_VERSION); + PASS(); +} + +/* An I64 column file of 4 rows in the generation-0 layout (32 + 32 bytes), + * with its header bytes patched to a cross pair: the loader must say + * corrupt, never load it as generation 0. */ +static ray_t* write_g0_patched(const char* path, uint8_t order, uint32_t aux0) { + int64_t d[4] = { 1, 2, 3, 4 }; + ray_t* v = ray_vec_from_raw(RAY_I64, d, 4); + if (!v || RAY_IS_ERR(v)) return v; + ray_err_t e = ray_col_save(v, path); + ray_release(v); + if (e != RAY_OK) return ray_error(ray_err_code_str(e), NULL); + FILE* f = fopen(path, "r+b"); + if (!f) return ray_error("io", NULL); + bool ok = fwrite(&aux0, 4, 1, f) == 1 && fseek(f, 17, SEEK_SET) == 0 && + fwrite(&order, 1, 1, f) == 1; + if (fclose(f) != 0) ok = false; + if (!ok) return ray_error("io", NULL); + return ray_col_mmap(path); +} + +static test_result_t test_discriminator_cross_pairs(void) { + static const struct { uint8_t order; uint32_t aux0; const char* code; } cases[] = { + { 0, RAY_ENC_XENC, "corrupt" }, + { 2, RAY_ENC_XIDX, "corrupt" }, + { 2, 0, "corrupt" }, + { 0, 0x01020304u, "corrupt" }, + { 1, 0, "version" }, + }; + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + ray_t* r = write_g0_patched(ray_test_tmp(ENCFMT_TMP "/x"), cases[i].order, cases[i].aux0); + bool ok1 = r && RAY_IS_ERR(r) && strcmp(ray_err_code(r), cases[i].code) == 0; + const char* got1 = (r && RAY_IS_ERR(r)) ? ray_err_code(r) : "(loaded)"; + char got[16]; snprintf(got, sizeof got, "%s", got1); + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_FMT(ok1, "mmap case %zu: got %s want %s", i, got, cases[i].code); + r = ray_col_load(ray_test_tmp(ENCFMT_TMP "/x")); + bool ok2 = r && RAY_IS_ERR(r) && strcmp(ray_err_code(r), cases[i].code) == 0; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_FMT(ok2, "load case %zu", i); + } + PASS(); +} + +/* A nullable I64 vector whose in-memory aux[0..3] holds junk: the writer + * must not let it reach the file (it would read back as a cross pair). */ +static test_result_t test_gen0_writer_zeroes_aux(void) { + int64_t d[4] = { 1, 2, INT64_MIN, 4 }; + ray_t* v = ray_vec_from_raw(RAY_I64, d, 4); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + v->attrs |= RAY_ATTR_HAS_NULLS; + v->aux[0] = 0xDE; v->aux[1] = 0xAD; v->aux[2] = 0xBE; v->aux[3] = 0xEF; + ray_err_t e = ray_col_save(v, ray_test_tmp(ENCFMT_TMP "/j")); + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_OK); + uint8_t b[4] = { 1, 1, 1, 1 }; + FILE* f = fopen(ray_test_tmp(ENCFMT_TMP "/j"), "rb"); + TEST_ASSERT_TRUE(f != NULL); + size_t n = fread(b, 1, 4, f); + fclose(f); + TEST_ASSERT_EQ_I((int)n, 4); + TEST_ASSERT_TRUE(b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0); + ray_t* r = ray_col_load(ray_test_tmp(ENCFMT_TMP "/j")); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->len, 4); + ray_release(r); + PASS(); +} + +static test_result_t test_length_helpers(void) { + TEST_ASSERT_EQ_I(ray_enc_nchunks(0), 0); + TEST_ASSERT_EQ_I(ray_enc_nchunks(1), 1); + TEST_ASSERT_EQ_I(ray_enc_nchunks(65536), 1); + TEST_ASSERT_EQ_I(ray_enc_nchunks(65537), 2); + TEST_ASSERT_EQ_I(ray_enc_nvecs(1025), 2); + TEST_ASSERT_EQ_I(ray_enc_vec_len(1025, 0), 1024); + TEST_ASSERT_EQ_I(ray_enc_vec_len(1025, 1), 1); + TEST_ASSERT_EQ_I(ray_enc_vec_len(2048, 1), 1024); + TEST_ASSERT_EQ_U(ray_enc_pad8(9), 16); + TEST_ASSERT_EQ_U(ray_enc_pad32(33), 64); + TEST_ASSERT_EQ_I(RAY_ENC_LE, 1); + PASS(); +} + + +static uint64_t f64_bits(double d) { uint64_t b; memcpy(&b, &d, 8); return b; } + +static test_result_t test_vec_i32_for(void) { + int32_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = 5000 + (i % 64); + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I32, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_FOR_BP); + TEST_ASSERT_EQ_I(v.desc.width, 6); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 0); + TEST_ASSERT_EQ_I(v.desc.flags, 0); + TEST_ASSERT_EQ_I(v.desc.min, 5000); + TEST_ASSERT_EQ_I(v.desc.max, 5063); + TEST_ASSERT_EQ_U(v.payload.len, 8 + 1024 * 6 / 8); + TEST_ASSERT_EQ_U(v.desc.payload_bytes, v.payload.len); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_i64_nulls_bitmap_and_sum(void) { + int64_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = 7; + d[3] = NULL_I64; d[1000] = NULL_I64; d[0] = INT64_MAX; d[1] = INT64_MAX; + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I64, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.n_nulls, 2); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 2); + TEST_ASSERT_EQ_U(v.payload.p[0], 0x08); /* row 3 */ + TEST_ASSERT_EQ_U(v.payload.p[125], 0x01); /* row 1000 = byte 125 bit 0 */ + TEST_ASSERT_EQ_I(v.desc.min, 7); + TEST_ASSERT_EQ_I(v.desc.max, INT64_MAX); + /* 2*INT64_MAX + 1020*7 = 2^64 + 7138 */ + TEST_ASSERT_EQ_I(v.sum_hi, 1); + TEST_ASSERT_EQ_U(v.sum_lo, 7138); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_all_null_is_const(void) { + int16_t d[3] = { NULL_I16, NULL_I16, NULL_I16 }; + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I16, 0, d, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_STAT_ABSENT); + TEST_ASSERT_EQ_I(v.desc.min, 0); + TEST_ASSERT_EQ_I(v.desc.max, 0); + TEST_ASSERT_EQ_U(v.payload.len, 128 + 8); + TEST_ASSERT_EQ_U(v.payload.p[0], 0x07); + for (size_t i = 128; i < 136; i++) TEST_ASSERT_EQ_U(v.payload.p[i], 0); + TEST_ASSERT_FALSE(v.has_stats); + ray_encw_vec_free(&v); + PASS(); +} + +/* Canonical NaN at row 1, a NaN with another payload at row 2: both are + * nulls in the bitmap; only row 2 goes to the trailer with its raw bits. */ +static test_result_t test_vec_f64_trailer(void) { + double d[4]; uint64_t odd = 0x7FF8000000000001ull; + d[0] = 2.5; d[1] = NULL_F64; memcpy(&d[2], &odd, 8); d[3] = -1.0; + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, d, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 2); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_DESC_TRAILER); + TEST_ASSERT_EQ_U((uint64_t)v.desc.min, f64_bits(-1.0)); + TEST_ASSERT_EQ_U((uint64_t)v.desc.max, f64_bits(2.5)); + /* bitmap 128 | RAW 4*8 (nulls filled with the minimum -1.0) | trailer */ + const uint8_t* p = v.payload.p; + TEST_ASSERT_EQ_U(p[0], 0x06); + uint64_t b1; memcpy(&b1, p + 128 + 8, 8); + TEST_ASSERT_EQ_U(b1, f64_bits(-1.0)); + const uint8_t* t = p + 128 + 32; + uint16_t cnt; memcpy(&cnt, t, 2); + TEST_ASSERT_EQ_I(cnt, 1); + uint16_t pos; memcpy(&pos, t + 8, 2); + TEST_ASSERT_EQ_I(pos, 2); + uint64_t raw; memcpy(&raw, t + 16, 8); /* positions padded to 8 */ + TEST_ASSERT_EQ_U(raw, odd); + TEST_ASSERT_EQ_U(v.payload.len, 128 + 32 + 8 + 8 + 8); + ray_encw_vec_free(&v); + PASS(); +} + +/* CONST and RLE merge equal bit patterns only: -0.0 and +0.0 never merge + * (-0.0 then 1023 x +0.0 is RLE of two runs, 48 B against RAW 8192 B). */ +static test_result_t test_vec_f64_const_and_zeros(void) { + double d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = 1.5; + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_U(v.payload.len, 8); + const uint64_t neg0 = 0x8000000000000000ull; /* -0.0 as its bit pattern (D10) */ + memcpy(&d[0], &neg0, 8); + for (int i = 1; i < RAY_ENC_VEC; i++) d[i] = 0.0; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RLE); + TEST_ASSERT_EQ_U(v.payload.len, 48); + uint32_t nruns; memcpy(&nruns, v.payload.p, 4); + TEST_ASSERT_EQ_U(nruns, 2); + uint64_t out[RAY_ENC_VEC]; + TEST_ASSERT_EQ_I(ray_enc_float_read(v.payload.p, v.payload.len, RAY_ENC_RLE, RAY_ENC_VEC, 64, NULL, out), + (int64_t)v.payload.len); + TEST_ASSERT_EQ_U(out[0], neg0); /* the run values: -0.0, then +0.0 */ + for (int i = 1; i < RAY_ENC_VEC; i++) TEST_ASSERT_EQ_U(out[i], 0); + TEST_ASSERT_EQ_U((uint64_t)v.desc.min, f64_bits(-0.0)); /* first of the tied zeros */ + TEST_ASSERT_EQ_U((uint64_t)v.desc.max, f64_bits(-0.0)); + ray_encw_vec_free(&v); + PASS(); +} + +/* A CONST vector of equal values plus two non-canonical NaNs: the trailer + * counts in both estimates, (8 + tb) * 8 <= (raw + tb) * 7. */ +static test_result_t test_vec_f64_const_with_trailer(void) { + double d[8]; uint64_t odd = 0x7FF8000000000005ull; + for (int i = 0; i < 8; i++) d[i] = 4.0; + memcpy(&d[3], &odd, 8); memcpy(&d[6], &odd, 8); + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, d, NULL, 0, 8, NULL, &v), RAY_OK); + /* raw 64, tb = 8 + 8 + 16 = 32: (8+32)*8 = 320 <= (64+32)*7 = 672 */ + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_DESC_TRAILER); + TEST_ASSERT_EQ_U(v.payload.len, 128 + 8 + 32); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_forced(void) { + int32_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = 5000 + (i % 64); + ray_encw_vec_t v; ray_encw_vec_init(&v); + ray_encw_test_force(RAY_ENC_RAW); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I32, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RAW); + ray_encw_test_force(RAY_ENC_CONST); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I32, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_ERR_NYI); + ray_encw_test_force(-1); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I32, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_FOR_BP); + ray_encw_vec_free(&v); + PASS(); +} + +/* The forced hook on floats: RAW, CONST and the float encodings where + * they apply; FOR_BP and DELTA_BP are illegal at the float top level, and + * CONST on unequal values or DICT without a dictionary do not apply: all + * RAY_ERR_NYI. */ +static test_result_t test_vec_forced_float(void) { + double d[RAY_ENC_VEC]; + float f[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) { d[i] = 1.5 + (double)(i % 64); f[i] = 1.5f + (float)(i % 64); } + static const int8_t types[2] = { RAY_F64, RAY_F32 }; + for (int t = 0; t < 2; t++) { + const void* data = t ? (const void*)f : (const void*)d; + ray_encw_vec_t v; ray_encw_vec_init(&v); + ray_encw_test_force(RAY_ENC_RAW); + ray_err_t e = ray_encw_vec(types[t], 0, data, NULL, 0, RAY_ENC_VEC, NULL, &v); + int enc = v.desc.encoding; + static const int refused[] = { RAY_ENC_FOR_BP, RAY_ENC_DELTA_BP, RAY_ENC_CONST, RAY_ENC_DICT }; + ray_err_t r[4]; + for (int k = 0; k < 4; k++) { + ray_encw_test_force(refused[k]); + r[k] = ray_encw_vec(types[t], 0, data, NULL, 0, RAY_ENC_VEC, NULL, &v); /* no dictionary */ + } + ray_encw_test_force(RAY_ENC_ALP_RD); + ray_err_t erd = ray_encw_vec(types[t], 0, data, NULL, 0, RAY_ENC_VEC, NULL, &v); + int encrd = v.desc.encoding; + ray_encw_test_force(-1); + ray_encw_vec_free(&v); + TEST_ASSERT_EQ_I(e, RAY_OK); + TEST_ASSERT_EQ_I(enc, RAY_ENC_RAW); + for (int k = 0; k < 4; k++) TEST_ASSERT_FMT(r[k] == RAY_ERR_NYI, "type %d force %d: %d", types[t], refused[k], r[k]); + TEST_ASSERT_EQ_I(erd, RAY_OK); + TEST_ASSERT_EQ_I(encrd, RAY_ENC_ALP_RD); + } + PASS(); +} + +static test_result_t test_vec_guid(void) { + uint8_t g[4][16]; memset(g, 0, sizeof g); + for (int i = 0; i < 4; i++) for (int j = 0; j < 16; j++) g[i][j] = (uint8_t)(j + 1); + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_GUID, 0, g, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_U(v.payload.len, 16); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_STAT_ABSENT); + memset(g[2], 0, 16); /* in-band null */ + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_GUID, 0, g, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 1); + TEST_ASSERT_EQ_U(v.payload.len, 64); + ray_encw_vec_free(&v); + PASS(); +} + +static ray_t* str_vec3(const char* a, const char* b, const char* c) { + ray_t* s = ray_vec_new(RAY_STR, 3); + s = ray_str_vec_append(s, a, strlen(a)); + s = ray_str_vec_append(s, b, strlen(b)); + return ray_str_vec_append(s, c, strlen(c)); +} + +static test_result_t test_vec_str_raw_and_const(void) { + ray_t* s = str_vec3("", "short", "a very long string 1"); /* 0, 5, 20 bytes */ + const char* pool = s->str_pool ? (const char*)ray_data(s->str_pool) : NULL; + ray_encw_vec_t v; ray_encw_vec_init(&v); + ray_err_t rc = ray_encw_vec(RAY_STR, 0, ray_data(s), pool, 0, 3, NULL, &v); + if (rc != RAY_OK) { ray_release(s); ray_encw_vec_free(&v); } + TEST_ASSERT_EQ_I(rc, RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 1); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_STAT_ABSENT); + TEST_ASSERT_EQ_U(v.str_pooled, 20); + TEST_ASSERT_EQ_U(v.payload.len, 3 * 16 + 8 + 24); + const uint8_t* p = v.payload.p; + uint32_t len; memcpy(&len, p + 16, 4); + TEST_ASSERT_EQ_I(len, 5); + TEST_ASSERT_TRUE(memcmp(p + 20, "short\0\0\0\0\0\0\0", 12) == 0); /* zero padded */ + memcpy(&len, p + 32, 4); + TEST_ASSERT_EQ_I(len, 20); + TEST_ASSERT_TRUE(memcmp(p + 36, "a ve", 4) == 0); /* prefix */ + uint32_t off, h; memcpy(&off, p + 40, 4); memcpy(&h, p + 44, 4); + TEST_ASSERT_EQ_I(off, 0); + TEST_ASSERT_EQ_I(h, 0); /* hash32 0 */ + uint64_t pb; memcpy(&pb, p + 48, 8); + TEST_ASSERT_EQ_U(pb, 20); + TEST_ASSERT_TRUE(memcmp(p + 56, "a very long string 1", 20) == 0); + ray_release(s); + + s = str_vec3("same long string here", "same long string here", "same long string here"); + pool = (const char*)ray_data(s->str_pool); + rc = ray_encw_vec(RAY_STR, 0, ray_data(s), pool, 0, 3, NULL, &v); + if (rc != RAY_OK) { ray_release(s); ray_encw_vec_free(&v); } + TEST_ASSERT_EQ_I(rc, RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_U(v.str_pooled, 3 * 21); /* once per occurrence */ + TEST_ASSERT_EQ_U(v.payload.len, 8 + 24); + memcpy(&len, v.payload.p, 4); + TEST_ASSERT_EQ_I(len, 21); + ray_release(s); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_sym_w8_inband(void) { + uint8_t d[4] = { 0, 127, 128, 255 }; + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_SYM, RAY_SYM_W8, d, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 1); + TEST_ASSERT_EQ_I(v.desc.min, 127); /* id 0 is the null, excluded */ + TEST_ASSERT_EQ_I(v.desc.max, 255); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RAW); + TEST_ASSERT_EQ_U(v.payload.len, 8); /* no bitmap for in-band nulls */ + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_bool_rle(void) { + uint8_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = (uint8_t)((i / 100) & 1); + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_BOOL, 0, d, NULL, 0, RAY_ENC_VEC, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RLE); + TEST_ASSERT_EQ_I(v.desc.min, 0); + TEST_ASSERT_EQ_I(v.desc.max, 1); + TEST_ASSERT_EQ_I(v.sum_hi, 0); + TEST_ASSERT_EQ_U(v.sum_lo, 500); /* rows 100..199, 300..399, ... */ + ray_encw_vec_free(&v); + PASS(); +} + +#define RT(call) do { test_result_t r_ = (call); if (r_.status != TEST_PASS) return r_; } while (0) + +/* Decode the codec body of a vector payload and compare with what the + * loader fed the encoder (null slots hold the fill). */ +static test_result_t roundtrip(int8_t type, uint8_t attrs, const void* data, int n, + const ray_enc_dict_t* dict, int force, int want_enc) { + ray_encw_vec_t v; ray_encw_vec_init(&v); + ray_encw_test_force(force); + ray_err_t rc = ray_encw_vec(type, attrs, data, NULL, 0, n, dict, &v); + ray_encw_test_force(-1); + TEST_ASSERT_EQ_I(rc, RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, want_enc); + ray_enc_input_t* in = malloc(sizeof *in); + uint64_t* out = malloc(RAY_ENC_VEC * sizeof *out); + TEST_ASSERT_TRUE(in && out); + TEST_ASSERT_TRUE(ray_enc_load(data, type, attrs, 0, n, in)); + size_t off = (ray_enc_has_bitmap(type) && v.n_nulls > 0) ? 128 : 0; + int64_t used = ray_enc_read(v.payload.p + off, v.payload.len - off, v.desc.encoding, + v.desc.width, n, in->k, RAY_ENC_SLOT_TOP, 0, dict, out); + TEST_ASSERT_TRUE(used > 0); + int bad = -1; + for (int i = 0; i < n && bad < 0; i++) if (out[i] != in->bits[i]) bad = i; + TEST_ASSERT_EQ_I(bad, -1); + free(in); free(out); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_roundtrip_codecs(void) { + int32_t a[RAY_ENC_VEC]; int64_t b[RAY_ENC_VEC]; uint8_t bo[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) a[i] = 5000 + (i % 64); + a[7] = NULL_I32; a[900] = NULL_I32; + RT(roundtrip(RAY_I32, 0, a, RAY_ENC_VEC, NULL, RAY_ENC_RAW, RAY_ENC_RAW)); + RT(roundtrip(RAY_I32, 0, a, RAY_ENC_VEC, NULL, -1, RAY_ENC_FOR_BP)); + RT(roundtrip(RAY_I32, 0, a, RAY_ENC_VEC, NULL, RAY_ENC_FOR_BP, RAY_ENC_FOR_BP)); + for (int i = 0; i < RAY_ENC_VEC; i++) a[i] = 42; + RT(roundtrip(RAY_I32, 0, a, RAY_ENC_VEC, NULL, -1, RAY_ENC_CONST)); + for (int i = 0; i < RAY_ENC_VEC; i++) b[i] = 1000 + (int64_t)i * 3; + b[5] = NULL_I64; + RT(roundtrip(RAY_I64, 0, b, RAY_ENC_VEC, NULL, RAY_ENC_DELTA_BP, RAY_ENC_DELTA_BP)); + for (int i = 0; i < RAY_ENC_VEC; i++) b[i] = (int64_t)(i / 100) * 1000003; + RT(roundtrip(RAY_I64, 0, b, RAY_ENC_VEC, NULL, RAY_ENC_RLE, RAY_ENC_RLE)); + for (int i = 0; i < RAY_ENC_VEC; i++) bo[i] = (uint8_t)((i / 100) & 1); + RT(roundtrip(RAY_BOOL, 0, bo, RAY_ENC_VEC, NULL, -1, RAY_ENC_RLE)); + RT(roundtrip(RAY_U8, 0, bo, RAY_ENC_VEC, NULL, RAY_ENC_RAW, RAY_ENC_RAW)); + PASS(); +} + +static test_result_t test_vec_roundtrip_dict(void) { + int32_t a[RAY_ENC_VEC]; + static const int32_t vals[3] = { 10, 1000000, 2000000000 }; + uint64_t dv[3] = { 10, 1000000, 2000000000 }; + ray_enc_dict_t dict = { dv, 3 }; + for (int i = 0; i < RAY_ENC_VEC; i++) a[i] = vals[(i * 7) % 3 == 0 ? 0 : (i % 2) + 1]; + RT(roundtrip(RAY_I32, 0, a, RAY_ENC_VEC, &dict, -1, RAY_ENC_DICT)); + RT(roundtrip(RAY_I32, 0, a, RAY_ENC_VEC, &dict, RAY_ENC_DICT, RAY_ENC_DICT)); + /* a value outside the dictionary cannot be forced onto DICT */ + ray_encw_vec_t v; ray_encw_vec_init(&v); + a[3] = 11; + ray_encw_test_force(RAY_ENC_DICT); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I32, 0, a, NULL, 0, RAY_ENC_VEC, &dict, &v), RAY_ERR_NYI); + ray_encw_test_force(-1); + /* SYM and BOOL ignore a dictionary */ + uint8_t sy[RAY_ENC_VEC], bo[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) { sy[i] = (uint8_t)(1 + (i * 7) % 3); bo[i] = (uint8_t)(i & 1); } + uint64_t sd[3] = { 1, 2, 3 }, bd[2] = { 0, 1 }; + ray_enc_dict_t sdict = { sd, 3 }, bdict = { bd, 2 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_SYM, RAY_SYM_W8, sy, NULL, 0, RAY_ENC_VEC, &sdict, &v), RAY_OK); + TEST_ASSERT_TRUE(v.desc.encoding != RAY_ENC_DICT); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_BOOL, 0, bo, NULL, 0, RAY_ENC_VEC, &bdict, &v), RAY_OK); + TEST_ASSERT_TRUE(v.desc.encoding != RAY_ENC_DICT); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_sums_literal(void) { + ray_encw_vec_t v; ray_encw_vec_init(&v); + int32_t neg[3] = { -5, -6, 3 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_I32, 0, neg, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.sum_hi, -1); + TEST_ASSERT_EQ_U(v.sum_lo, 0xFFFFFFFFFFFFFFF8ull); /* -8 */ + int32_t tm[3] = { 1000, 2000, NULL_I32 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_TIME, 0, tm, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.sum_hi, 0); + TEST_ASSERT_EQ_U(v.sum_lo, 3000); + int32_t dt[3] = { 1, 2, 3 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_DATE, 0, dt, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.sum_hi, 0); + TEST_ASSERT_EQ_U(v.sum_lo, 0); + int64_t ts[3] = { 1, 2, 3 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_TIMESTAMP, 0, ts, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.sum_hi, 0); + TEST_ASSERT_EQ_U(v.sum_lo, 0); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_f32_trailer(void) { + float d[4]; uint32_t odd = 0x7FC00001u; + d[0] = 1.5f; d[1] = NULL_F32; memcpy(&d[2], &odd, 4); d[3] = -2.0f; + ray_encw_vec_t v; ray_encw_vec_init(&v); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F32, 0, d, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_RAW); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 2); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_DESC_TRAILER); + TEST_ASSERT_EQ_U((uint64_t)v.desc.min, f64_bits(-2.0)); /* widened to double */ + TEST_ASSERT_EQ_U((uint64_t)v.desc.max, f64_bits(1.5)); + /* bitmap 128 | RAW 4*4 | trailer: count 8, position 8, raw 8 */ + TEST_ASSERT_EQ_U(v.payload.len, 128 + 16 + 8 + 8 + 8); + const uint8_t* p = v.payload.p; + TEST_ASSERT_EQ_U(p[0], 0x06); + float fill; memcpy(&fill, p + 128 + 4, 4); + TEST_ASSERT_TRUE(fill == -2.0f); + uint16_t cnt, pos; uint32_t raw; + memcpy(&cnt, p + 144, 2); memcpy(&pos, p + 152, 2); memcpy(&raw, p + 160, 4); + TEST_ASSERT_EQ_I(cnt, 1); + TEST_ASSERT_EQ_I(pos, 2); + TEST_ASSERT_EQ_U(raw, odd); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_all_null_kinds(void) { + ray_encw_vec_t v; ray_encw_vec_init(&v); + ray_t* s = str_vec3("", "", ""); + ray_err_t rc = ray_encw_vec(RAY_STR, 0, ray_data(s), NULL, 0, 3, NULL, &v); + ray_release(s); + TEST_ASSERT_EQ_I(rc, RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 3); + TEST_ASSERT_EQ_U(v.payload.len, 8); + uint8_t g[4][16]; memset(g, 0, sizeof g); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_GUID, 0, g, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 4); + TEST_ASSERT_EQ_U(v.payload.len, 16); + double f[3] = { NULL_F64, NULL_F64, NULL_F64 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, f, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 3); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_STAT_ABSENT); + TEST_ASSERT_EQ_U(v.payload.len, 128 + 8); + /* a forced non-RAW/CONST encoding leaves an all-null vector CONST */ + ray_encw_test_force(RAY_ENC_DICT); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, f, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_GUID, 0, g, NULL, 0, 4, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + ray_encw_test_force(-1); + /* all-null with a non-canonical NaN: the raw bits go to the trailer */ + uint64_t odd = 0x7FF8000000000001ull; + double h[3]; h[0] = NULL_F64; memcpy(&h[1], &odd, 8); h[2] = NULL_F64; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_F64, 0, h, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.encoding, RAY_ENC_CONST); + TEST_ASSERT_EQ_I(v.desc.flags, RAY_ENC_STAT_ABSENT | RAY_ENC_DESC_TRAILER); + TEST_ASSERT_EQ_U(v.payload.len, 128 + 8 + 8 + 8 + 8); + uint64_t raw; memcpy(&raw, v.payload.p + 128 + 8 + 16, 8); + TEST_ASSERT_EQ_U(raw, odd); + ray_encw_vec_free(&v); + PASS(); +} + +static test_result_t test_vec_sym_w16_w32(void) { + ray_encw_vec_t v; ray_encw_vec_init(&v); + uint16_t d16[3] = { 0, 5, 1000 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_SYM, RAY_SYM_W16, d16, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 1); + TEST_ASSERT_EQ_I(v.desc.min, 5); + TEST_ASSERT_EQ_I(v.desc.max, 1000); + uint32_t d32[3] = { 7, 0, 70000 }; + TEST_ASSERT_EQ_I(ray_encw_vec(RAY_SYM, RAY_SYM_W32, d32, NULL, 0, 3, NULL, &v), RAY_OK); + TEST_ASSERT_EQ_I(v.desc.n_nulls, 1); + TEST_ASSERT_EQ_I(v.desc.min, 7); + TEST_ASSERT_EQ_I(v.desc.max, 70000); + ray_encw_vec_free(&v); + RT(roundtrip(RAY_SYM, RAY_SYM_W16, d16, 3, NULL, RAY_ENC_RAW, RAY_ENC_RAW)); + PASS(); +} + + +static uint8_t* read_file(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + long sz = -1; + if (fseek(f, 0, SEEK_END) == 0) sz = ftell(f); + if (sz < 0 || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; } + uint8_t* b = malloc((size_t)sz + 1); + if (!b) { fclose(f); return NULL; } + *n = fread(b, 1, (size_t)sz, f); + fclose(f); + if (*n != (size_t)sz) { free(b); return NULL; } + return b; +} + +static test_result_t test_file_headers(void) { + int32_t d[1025]; + for (int i = 0; i < 1025; i++) d[i] = (i % 10 == 0) ? NULL_I32 : i; + ray_t* v = ray_vec_from_raw(RAY_I32, d, 1025); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/h"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/h"), &n); + TEST_ASSERT_NOT_NULL(b); + TEST_ASSERT_EQ_I(ray_col_gen_of(b), 2); + ray_t hdr; memcpy(&hdr, b, 32); + TEST_ASSERT_EQ_I(hdr.type, RAY_I32); + TEST_ASSERT_EQ_I(hdr.len, 1025); + TEST_ASSERT_TRUE(hdr.attrs & RAY_ATTR_HAS_NULLS); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + TEST_ASSERT_TRUE(memcmp(eh.magic, "RENC", 4) == 0); + TEST_ASSERT_EQ_I(eh.header_version, 1); + TEST_ASSERT_EQ_U(eh.end_off, n); + TEST_ASSERT_EQ_U(eh.side_off, 0); + TEST_ASSERT_EQ_U(eh.index_off, 0); + ray_enc_dirent_t de; memcpy(&de, b + 96, 64); + TEST_ASSERT_EQ_U(de.offset, 96 + 64); + TEST_ASSERT_EQ_U(de.offset + de.bytes, n); + TEST_ASSERT_EQ_I(de.null_count, 103); /* rows 0,10,...,1020 */ + TEST_ASSERT_EQ_I(de.min, 1); + TEST_ASSERT_EQ_I(de.max, 1024); + free(b); + PASS(); +} + +static test_result_t test_trailing_descriptors_zero(void) { + int32_t d[1025]; + for (int i = 0; i < 1025; i++) d[i] = i; + ray_t* v = ray_vec_from_raw(RAY_I32, d, 1025); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/t"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/t"), &n); + const uint8_t* c = b + 160; /* chunk 0 descriptors */ + ray_enc_desc_t d0, d1; memcpy(&d0, c, 48); memcpy(&d1, c + 48, 48); + TEST_ASSERT_EQ_U(d0.payload_off, RAY_ENC_DESC_AREA); + TEST_ASSERT_EQ_U(d1.payload_off, ray_enc_pad8(d0.payload_off + d0.payload_bytes)); + for (int j = 2; j < 64; j++) + for (int k = 0; k < 48; k++) TEST_ASSERT_FMT(c[j * 48 + k] == 0, "desc %d byte %d", j, k); + free(b); + PASS(); +} + +/* Chunk 0 holds INT64_MIN+1, INT64_MAX and nulls; chunk 1 is all null. */ +static test_result_t test_dir_sums_extremes(void) { + int64_t len = 65536 + 10; + ray_t* v = ray_vec_new(RAY_I64, len); + v->len = len; + int64_t* d = (int64_t*)ray_data(v); + for (int64_t i = 0; i < len; i++) d[i] = NULL_I64; + d[0] = INT64_MIN + 1; d[1] = INT64_MAX; d[2] = INT64_MAX; d[5] = -3; + v->attrs |= RAY_ATTR_HAS_NULLS; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/s"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/s"), &n); + ray_enc_dirent_t e0, e1; memcpy(&e0, b + 96, 64); memcpy(&e1, b + 160, 64); + int64_t hi = 0; uint64_t lo = 0; + ray_i128_add(&hi, &lo, INT64_MIN + 1); ray_i128_add(&hi, &lo, INT64_MAX); + ray_i128_add(&hi, &lo, INT64_MAX); ray_i128_add(&hi, &lo, -3); + TEST_ASSERT_EQ_U(e0.sum_lo, lo); + TEST_ASSERT_EQ_I(e0.sum_hi, hi); + TEST_ASSERT_EQ_I(e0.null_count, 65536 - 4); + TEST_ASSERT_EQ_I(e0.min, INT64_MIN + 1); + TEST_ASSERT_EQ_I(e0.max, INT64_MAX); + TEST_ASSERT_EQ_I(e0.flags, 0); + TEST_ASSERT_EQ_I(e1.null_count, 10); + TEST_ASSERT_EQ_I(e1.flags, RAY_ENC_STAT_ABSENT); + TEST_ASSERT_EQ_I(e1.min, 0); + TEST_ASSERT_EQ_I(e1.max, 0); + TEST_ASSERT_EQ_U(e1.sum_lo, 0); + TEST_ASSERT_EQ_I(e1.sum_hi, 0); + free(b); + PASS(); +} + +/* Four wide values at hash-scattered rows (not lane-periodic, so DELTA_BP + * is wide), pinned by hand against ray_enc_choose: RAW 8192 B, FOR_BP + * w=47 6024 B, DELTA_BP w=64 8328 B, RLE ~760 runs, DICT with a FOR_BP + * w=2 codes child 8 + 8 + 256 = 272 B. DICT wins. */ +static const int64_t g_dict_vals[4] = { 11, 900000000001ll, 77, 123456789012345ll }; +static int64_t dict_val(int i) { return g_dict_vals[(uint32_t)((uint32_t)i * 2654435761u) >> 30]; } + +/* A DICT vector makes the writer emit one VALUE_DICT side entry. */ +static test_result_t test_side_value_dict(void) { + int64_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = dict_val(i); + ray_t* v = ray_vec_from_raw(RAY_I64, d, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/d"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/d"), &n); + ray_enc_desc_t d0; memcpy(&d0, b + 160, 48); + TEST_ASSERT_EQ_I(d0.encoding, RAY_ENC_DICT); /* before any offset is trusted */ + TEST_ASSERT_EQ_U(d0.payload_bytes, 272); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + TEST_ASSERT_TRUE(eh.side_off != 0); + TEST_ASSERT_EQ_U(eh.side_off % 32, 0); + TEST_ASSERT_EQ_U(eh.side_off + eh.side_len, n); + const uint8_t* s = b + eh.side_off; + uint32_t ne; memcpy(&ne, s, 4); + TEST_ASSERT_EQ_I(ne, 1); + uint16_t kind; memcpy(&kind, s + 8, 2); + TEST_ASSERT_EQ_I(kind, RAY_ENC_SIDE_VALUE_DICT); + uint64_t eoff; memcpy(&eoff, s + 16, 8); + TEST_ASSERT_EQ_U(eoff, 32); + uint32_t dn; memcpy(&dn, s + eoff, 4); + TEST_ASSERT_EQ_I(dn, 4); + int64_t first; memcpy(&first, s + eoff + 8, 8); + TEST_ASSERT_EQ_I(first, 11); /* ascending */ + free(b); + PASS(); +} + +/* A trained dictionary no vector selects is not written: a lane-periodic + * sequence of the same four values is DELTA_BP at width 0 (136 B). */ +static test_result_t test_side_unused_dict_not_written(void) { + int64_t d[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) d[i] = g_dict_vals[(i * 7) % 4]; + ray_t* v = ray_vec_from_raw(RAY_I64, d, RAY_ENC_VEC); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/nd"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/nd"), &n); + ray_enc_desc_t d0; memcpy(&d0, b + 160, 48); + TEST_ASSERT_EQ_I(d0.encoding, RAY_ENC_DELTA_BP); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + TEST_ASSERT_EQ_U(eh.side_off, 0); + TEST_ASSERT_EQ_U(eh.side_len, 0); + free(b); + PASS(); +} + +/* Spec "Materialization" step 3: the admission matrix, one predicate + * shared by the writer, the load validator and the attach. */ +static test_result_t test_admission_matrix(void) { + static const int8_t num[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, + RAY_DATE, RAY_TIME, RAY_TIMESTAMP }; + for (size_t i = 0; i < sizeof num; i++) { + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_HASH, num[i])); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_SORT, num[i])); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_BLOOM, num[i])); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_PART, num[i])); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_ZONE, num[i])); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_CHUNK_ZONE, num[i])); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_NONE, num[i])); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_DICT, num[i])); + } + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_HASH, RAY_SYM)); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_PART, RAY_SYM)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_SORT, RAY_SYM)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_BLOOM, RAY_SYM)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_ZONE, RAY_SYM)); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_HASH, RAY_STR)); + TEST_ASSERT_TRUE(ray_index_kind_admits(RAY_IDX_DICT, RAY_STR)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_PART, RAY_STR)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_BLOOM, RAY_STR)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_NONE, RAY_GUID)); + TEST_ASSERT_FALSE(ray_index_kind_admits(RAY_IDX_HASH, RAY_GUID)); + PASS(); +} + +static test_result_t test_empty_column(void) { + ray_t* v = ray_vec_new(RAY_I64, 0); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/e"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/e"), &n); + TEST_ASSERT_EQ_U(n, 96); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + TEST_ASSERT_EQ_U(eh.end_off, 96); + free(b); + PASS(); +} + +/* Compile with -DENC_GOLDEN_KEEP to regenerate the fixtures in place + * (test/data/enc); otherwise the emit test writes into the (removed) test dir. */ +#ifdef ENC_GOLDEN_KEEP +# define ENC_GOLDEN_OUT ENC_GOLDEN_DIR +#else +# define ENC_GOLDEN_OUT ENCFMT_TMP "/golden_emit" +#endif +#define ENC_GOLDEN_DIR "test/data/enc" + +static uint64_t g_rng; +static uint64_t golden_rng(void) { uint64_t x = g_rng; x ^= x << 13; x ^= x >> 7; x ^= x << 17; return g_rng = x; } + +/* Golden case i: its vector, its name, the encoding forced for every vector + * (-1 = selection) and the top-level encoding vector 0 must have, pinned by + * hand against ray_enc_choose (sizes in the comments). NULL past the last. */ +static int g_kid[4]; /* pinned child-slot encodings of vector 0 (-1 = unpinned); see golden_kids */ +static ray_t* golden_vec(int i, const char** name, int* force, int* want) { + for (int j = 0; j < 4; j++) g_kid[j] = -1; + g_rng = 0x9E3779B97F4A7C15ull + (uint64_t)i; + ray_t* v = NULL; + *force = -1; + switch (i) { + case 0: { *name = "i32_for"; *want = RAY_ENC_FOR_BP; /* w=6: 776 B */ + int32_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = 5000 + (k % 64); v = ray_vec_from_raw(RAY_I32, d, 1024); break; } + case 1: { *name = "i64_const"; *want = RAY_ENC_CONST; /* 8 B */ + v = ray_vec_new(RAY_I64, 2000); v->len = 2000; for (int k = 0; k < 2000; k++) ((int64_t*)ray_data(v))[k] = 42; break; } + case 2: { *name = "i64_delta"; *want = RAY_ENC_DELTA_BP; /* w=0: 136 B; DICT 1296 B */ + int64_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = 1700000000000ll + 1000ll * k; v = ray_vec_from_raw(RAY_I64, d, 1024); break; } + case 3: { g_kid[1] = RAY_ENC_RLE; g_kid[2] = RAY_ENC_RAW; g_kid[3] = RAY_ENC_RAW; + *name = "i64_dict_codes_rle"; *want = RAY_ENC_DICT; /* codes RLE: 104 B; top RLE 136 B */ + int64_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = (int64_t)(k / 100) * 1000003ll; v = ray_vec_from_raw(RAY_I64, d, 1024); break; } + case 4: { g_kid[1] = RAY_ENC_FOR_BP; + *name = "i64_dict"; *want = RAY_ENC_DICT; /* VALUE_DICT side entry; codes FOR w=2: 272 B */ + int64_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = dict_val(k); v = ray_vec_from_raw(RAY_I64, d, 1024); break; } + case 5: { *name = "i32_nulls"; *want = RAY_ENC_FOR_BP; /* w=10: 1288 B; DICT 1296 B */ + int32_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = (k % 10 == 0) ? NULL_I32 : k; v = ray_vec_from_raw(RAY_I32, d, 1024); v->attrs |= RAY_ATTR_HAS_NULLS; break; } + case 6: { *name = "i16_all_null"; *want = RAY_ENC_CONST; + int16_t d[3] = { NULL_I16, NULL_I16, NULL_I16 }; v = ray_vec_from_raw(RAY_I16, d, 3); v->attrs |= RAY_ATTR_HAS_NULLS; break; } + case 7: { *name = "u8_raw"; *want = RAY_ENC_RAW; + uint8_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = (uint8_t)golden_rng(); v = ray_vec_from_raw(RAY_U8, d, 1024); break; } + case 8: { *name = "bool_rle"; *want = RAY_ENC_RLE; /* top-level RLE, RAW values and ends: 64 B */ + uint8_t d[1024]; for (int k = 0; k < 1024; k++) d[k] = (uint8_t)((k / 100) & 1); v = ray_vec_from_raw(RAY_BOOL, d, 1024); break; } + /* forced RAW: the P5 choice would pick DICT (24 B against 32 B) */ + case 9: { *name = "f64_trailer"; *force = RAY_ENC_RAW; *want = RAY_ENC_RAW; + double d[4]; uint64_t odd = 0x7FF8000000000001ull; d[0] = 2.5; d[1] = NULL_F64; memcpy(&d[2], &odd, 8); d[3] = -1.0; v = ray_vec_from_raw(RAY_F64, d, 4); v->attrs |= RAY_ATTR_HAS_NULLS; break; } + case 10: { *name = "f64_const"; *want = RAY_ENC_CONST; + double d[1024]; for (int k = 0; k < 1024; k++) d[k] = 1.5; v = ray_vec_from_raw(RAY_F64, d, 1024); break; } + case 11: { *name = "f32_zeros"; *want = RAY_ENC_RAW; + float d[8] = { -0.0f, 0.0f, 1.0f, -2.0f, 0.0f, -0.0f, 3.5f, 1.0f }; v = ray_vec_from_raw(RAY_F32, d, 8); break; } + case 12: { *name = "guid_mixed"; *want = RAY_ENC_RAW; + uint8_t g[3][16]; for (int k = 0; k < 3; k++) for (int j = 0; j < 16; j++) g[k][j] = (uint8_t)(k * 16 + j + 1); + memset(g[1], 0, 16); v = ray_vec_from_raw(RAY_GUID, g, 3); break; } + /* P1's STR cases forced to their encodings (P6 selection would pick + * STR_DICT or FSST); an unused FSST table or dictionary is not written. */ + case 13: { *name = "str_mixed"; *force = RAY_ENC_RAW; *want = RAY_ENC_RAW; v = ray_vec_new(RAY_STR, 4); + v = ray_str_vec_append(v, "", 0); v = ray_str_vec_append(v, "short", 5); + v = ray_str_vec_append(v, "a very long string 1", 20); v = ray_str_vec_append(v, "a very long string 1", 20); break; } + case 14: { *name = "str_const"; *force = RAY_ENC_CONST; *want = RAY_ENC_CONST; v = ray_vec_new(RAY_STR, 3); + for (int k = 0; k < 3; k++) { v = ray_str_vec_append(v, "same long string here", 21); } + break; } + case 15: { *name = "i64_empty"; *want = -1; v = ray_vec_new(RAY_I64, 0); break; } + case 16: { *name = "i32_two_chunks"; *want = RAY_ENC_FOR_BP; + v = ray_vec_new(RAY_I32, 65537); v->len = 65537; for (int k = 0; k < 65537; k++) ((int32_t*)ray_data(v))[k] = k % 1000; break; } + case 17: { *name = "str_inline"; *force = RAY_ENC_RAW; *want = RAY_ENC_RAW; v = ray_vec_new(RAY_STR, 3); + v = ray_str_vec_append(v, "ab", 2); v = ray_str_vec_append(v, "twelve bytes", 12); v = ray_str_vec_append(v, "x", 1); break; } + case 18: { *name = "str_pooled"; *force = RAY_ENC_RAW; *want = RAY_ENC_RAW; v = ray_vec_new(RAY_STR, 2); + v = ray_str_vec_append(v, "thirteen byte", 13); v = ray_str_vec_append(v, "another pooled one", 18); break; } + case 19: { *name = "str_repeated"; *force = RAY_ENC_RAW; *want = RAY_ENC_RAW; v = ray_vec_new(RAY_STR, 4); + v = ray_str_vec_append(v, "repeated long text", 18); v = ray_str_vec_append(v, "short", 5); + v = ray_str_vec_append(v, "repeated long text", 18); v = ray_str_vec_append(v, "repeated long text", 18); break; } + /* forced encodings (spec: every encoding also forced) */ + case 20: case 21: case 22: { + int T = i == 20 ? 16 : i == 21 ? 32 : 64, L = 1024 / T; + *name = i == 20 ? "i16_delta_wT" : i == 21 ? "i32_delta_wT" : "i64_delta_wT"; + *force = RAY_ENC_DELTA_BP; *want = RAY_ENC_DELTA_BP; /* extremes by lane row: w = T */ + int8_t ty = T == 16 ? RAY_I16 : T == 32 ? RAY_I32 : RAY_I64; + v = ray_vec_new(ty, 1024); v->len = 1024; + for (int k = 0; k < 1024; k++) { + bool up = (k / L) & 1; + if (T == 16) ((int16_t*)ray_data(v))[k] = up ? 32767 : -32767; + else if (T == 32) ((int32_t*)ray_data(v))[k] = up ? 2147483647 : -2147483647; + else ((int64_t*)ray_data(v))[k] = up ? INT64_MAX : INT64_MIN + 1; + } + break; } + case 23: { g_kid[1] = RAY_ENC_FOR_BP; + *name = "i64_dict_const_child"; *force = RAY_ENC_DICT; *want = RAY_ENC_DICT; /* codes FOR w=0 at depth 1 */ + v = ray_vec_new(RAY_I64, 1024); v->len = 1024; for (int k = 0; k < 1024; k++) ((int64_t*)ray_data(v))[k] = 900000000001ll; break; } + case 24: { g_kid[1] = RAY_ENC_FOR_BP; + *name = "i64_rle_values_for"; *force = RAY_ENC_RLE; *want = RAY_ENC_RLE; /* values FOR w=4 */ + v = ray_vec_new(RAY_I64, 1024); v->len = 1024; for (int k = 0; k < 1024; k++) ((int64_t*)ray_data(v))[k] = 1000 + (k / 2) % 16; break; } + case 25: { g_kid[2] = RAY_ENC_DELTA_BP; + *name = "i64_rle_ends_delta"; *force = RAY_ENC_RLE; *want = RAY_ENC_RLE; /* ends DELTA w=0 */ + v = ray_vec_new(RAY_I64, 1024); v->len = 1024; for (int k = 0; k < 1024; k++) ((int64_t*)ray_data(v))[k] = (int64_t)k * 3; break; } + /* ends of ~790 irregular runs: RAW 1580 B, DELTA w=7 1416 B, FOR w=10 1288 B */ + case 26: { g_kid[2] = RAY_ENC_FOR_BP; + *name = "i64_rle_ends_for"; *force = RAY_ENC_RLE; *want = RAY_ENC_RLE; + v = ray_vec_new(RAY_I64, 1024); v->len = 1024; + int64_t val = 0; + for (int k = 0; k < 1024; ) { + int run = (golden_rng() % 64 == 0) ? 20 : 1; + for (int j = 0; j < run && k < 1024; j++) ((int64_t*)ray_data(v))[k++] = val; + val += 7; + } + break; } + /* three rows, dictionary of three: codes RAW 16 B beats FOR (8 + 256 B) */ + case 27: { g_kid[1] = RAY_ENC_RAW; + *name = "i64_dict_codes_raw"; *force = RAY_ENC_DICT; *want = RAY_ENC_DICT; + int64_t d[3] = { 5, 900000000001ll, -77 }; v = ray_vec_from_raw(RAY_I64, d, 3); break; } + /* P5 floats; -0.0 is written as its bit pattern (D10) */ + case 28: { *name = "f64_alp"; *force = RAY_ENC_ALP; *want = RAY_ENC_ALP; /* forced: one chunk, so DICT would win */ + double d[1024]; for (int k = 0; k < 1024; k++) d[k] = (double)((k * 7919) % 100000) / 100.0; + v = ray_vec_from_raw(RAY_F64, d, 1024); break; } + case 29: { *name = "f64_alprd_len1"; *force = RAY_ENC_ALP_RD; *want = RAY_ENC_ALP_RD; + double d[1] = { 1.0 + (double)(golden_rng() >> 11) / 9007199254740992.0 }; v = ray_vec_from_raw(RAY_F64, d, 1); break; } + case 30: { *name = "f64_alprd_len1023"; *force = RAY_ENC_ALP_RD; *want = RAY_ENC_ALP_RD; + double d[1023]; for (int k = 0; k < 1023; k++) d[k] = 1.0 + (double)(golden_rng() >> 11) / 9007199254740992.0; + v = ray_vec_from_raw(RAY_F64, d, 1023); break; } + case 31: { *name = "f64_dict_signed"; *force = RAY_ENC_DICT; *want = RAY_ENC_DICT; + static const uint64_t dv[4] = { 0xC00C000000000000ull /* -3.5 */, 0x8000000000000000ull /* -0.0 */, + 0 /* +0.0 */, 0x4002000000000000ull /* 2.25 */ }; + double d[1024]; for (int k = 0; k < 1024; k++) memcpy(&d[k], &dv[(uint32_t)((uint32_t)k * 2654435761u) >> 30], 8); + v = ray_vec_from_raw(RAY_F64, d, 1024); break; } + case 32: { *name = "f64_rle"; *force = RAY_ENC_RLE; *want = RAY_ENC_RLE; + double d[1024]; for (int k = 0; k < 1024; k++) d[k] = (double)(k / 128) * 1.0000001; + v = ray_vec_from_raw(RAY_F64, d, 1024); break; } + case 33: { *name = "f32_alp"; *force = RAY_ENC_ALP; *want = RAY_ENC_ALP; + float d[1024]; for (int k = 0; k < 1024; k++) d[k] = (float)((k * 31) % 5000) / 10.0f; + v = ray_vec_from_raw(RAY_F32, d, 1024); break; } + case 34: { *name = "f64_alp_trailer"; *force = RAY_ENC_ALP; *want = RAY_ENC_ALP; + double d[1024]; uint64_t odd = 0x7FF8000000000077ull, neg0 = 0x8000000000000000ull; + for (int k = 0; k < 1024; k++) { d[k] = (double)(k % 100) / 4.0; if (k % 50 == 7) memcpy(&d[k], &odd, 8); + if (k % 64 == 3) memcpy(&d[k], &neg0, 8); } + v = ray_vec_from_raw(RAY_F64, d, 1024); v->attrs |= RAY_ATTR_HAS_NULLS; break; } + /* P6 STR bodies */ + case 35: { *name = "str_dict"; *force = RAY_ENC_STR_DICT; *want = RAY_ENC_STR_DICT; v = ray_vec_new(RAY_STR, 1024); + static const char* const w[5] = { "", "zeta", "alpha long value one", "mu", "omega long value two" }; + for (int k = 0; k < 1024; k++) { const char* s = w[(uint32_t)((uint32_t)k * 2654435761u) % 5]; v = ray_str_vec_append(v, s, strlen(s)); } + break; } + case 36: { *name = "str_dict_codes_rle"; *force = RAY_ENC_STR_DICT; *want = RAY_ENC_STR_DICT; v = ray_vec_new(RAY_STR, 1024); + for (int k = 0; k < 1024; k++) { char b[40]; int n = snprintf(b, sizeof b, "run value number %d", k / 256); v = ray_str_vec_append(v, b, (size_t)n); } + break; } + case 37: { *name = "str_fsst"; *force = RAY_ENC_FSST; *want = RAY_ENC_FSST; v = ray_vec_new(RAY_STR, 1024); + for (int k = 0; k < 1024; k++) { char b[96]; int n = snprintf(b, sizeof b, "https://www.example.com/p/%d?q=%d", k % 97, (k * 31) % 1000); + v = ray_str_vec_append(v, b, (size_t)n); } + break; } + default: return NULL; + } + return v; +} + +/* SYM golden cases are written through the column writer directly so the + * saved SYM count does not depend on the process symbol table. */ +static ray_err_t golden_sym(int i, const char* dir, const char** name) { + static uint32_t ids[1024]; + uint8_t attrs; uint32_t count; + if (i == 0) { *name = "sym_w8_for"; attrs = RAY_SYM_W8; count = 256; /* FOR w=4: 520 B */ + for (int k = 0; k < 1024; k++) ids[k] = 100 + (uint32_t)(k % 16); } + else if (i == 1) { *name = "sym_w32_rle"; attrs = RAY_SYM_W32; count = 0xFFFFFFFFu; /* 512 runs: 3096 B < RAW 4096 */ + g_rng = 77; for (int k = 0; k < 1024; k += 2) ids[k] = ids[k + 1] = 1 + (uint32_t)(golden_rng() % 0xFFFFFFF0u); } + else return RAY_ERR_RANGE; + uint8_t buf[4096]; + for (int k = 0; k < 1024; k++) ray_write_sym(buf, k, ids[k], RAY_SYM, attrs); + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", dir, *name); + FILE* f = fopen(path, "wb+"); + if (!f) return RAY_ERR_IO; + ray_encw_t w; + ray_err_t e = ray_encw_begin(&w, f, RAY_SYM, attrs, 1024, count, 0, 0); + if (e == RAY_OK) e = ray_encw_chunk(&w, buf, NULL, 1024); + if (e == RAY_OK) e = ray_encw_finish(&w); + ray_encw_free(&w); + fclose(f); + return e; +} + +static const int g_sym_want[2] = { RAY_ENC_FOR_BP, RAY_ENC_RLE }; + +/* Encodings of vector 0 read from the file: [0] top level; RLE: [1] values, + * [2] ends; DICT: [1] codes and, when the codes are RLE, [2] their values and + * [3] their ends. -1 where the slot does not exist or the file is short. */ +static void golden_kids(const char* path, int kid[4]) { + for (int j = 0; j < 4; j++) kid[j] = -1; + size_t n; uint8_t* b = read_file(path, &n); + if (!b) return; + uint64_t off = 0; /* chunk 0 follows the directory */ + if (n >= 96 + 64) memcpy(&off, b + 96, 8); + if (off >= 160 && off + 48 <= n) { + ray_enc_desc_t d; memcpy(&d, b + off, 48); + kid[0] = d.encoding; + const uint8_t* p = b + off + d.payload_off; + const uint8_t* end = b + n; + uint32_t bb; + if (d.encoding == RAY_ENC_RLE && p + 24 <= end) { + kid[1] = p[8]; + memcpy(&bb, p + 12, 4); + if (p + 16 + bb < end) kid[2] = p[16 + bb]; + } else if (d.encoding == RAY_ENC_DICT && p + 8 <= end) { + kid[1] = p[0]; + if (p[0] == RAY_ENC_RLE && p + 32 <= end) { + kid[2] = p[16]; + memcpy(&bb, p + 20, 4); + if (p + 24 + bb < end) kid[3] = p[24 + bb]; + } + } + } + free(b); +} + +static int file_desc0_encoding(const char* path) { + int kid[4]; golden_kids(path, kid); + return kid[0]; +} + +/* Emits every case and checks vector 0's encoding against its pin. */ +static const char* golden_emit_all(const char* dir) { + static char why[256]; + (void)ray_test_mkdir_p(dir); + for (int i = 0;; i++) { + const char* name; int force, want; + ray_t* v = golden_vec(i, &name, &force, &want); + if (!v) break; + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", dir, name); + ray_encw_test_force(force); + ray_err_t e = ray_col_save_gen(v, path, 2); + ray_encw_test_force(-1); + ray_release(v); + if (e != RAY_OK) { snprintf(why, sizeof why, "%s: save %d", name, (int)e); return why; } + if (want >= 0 && file_desc0_encoding(path) != want) { + snprintf(why, sizeof why, "%s: encoding %d, pinned %d", name, file_desc0_encoding(path), want); + return why; + } + int kid[4]; golden_kids(path, kid); + for (int j = 1; j < 4; j++) + if (g_kid[j] >= 0 && kid[j] != g_kid[j]) { + snprintf(why, sizeof why, "%s: child slot %d encoding %d, pinned %d", name, j, kid[j], g_kid[j]); + return why; + } + } + for (int i = 0; i < 2; i++) { + const char* name; ray_err_t e = golden_sym(i, dir, &name); + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", dir, name); + if (e != RAY_OK || file_desc0_encoding(path) != g_sym_want[i]) { + snprintf(why, sizeof why, "%s: save %d / encoding %d", name, (int)e, file_desc0_encoding(path)); + return why; + } + } + return NULL; +} + +static const char* const g_golden_names[] = { + "i32_for", "i64_const", "i64_delta", "i64_dict_codes_rle", "i64_dict", "i32_nulls", "i16_all_null", + "u8_raw", "bool_rle", "f64_trailer", "f64_const", "f32_zeros", "guid_mixed", "str_mixed", + "str_const", "i64_empty", "i32_two_chunks", "str_inline", "str_pooled", "str_repeated", + "i16_delta_wT", "i32_delta_wT", "i64_delta_wT", "i64_dict_const_child", "i64_rle_values_for", + "i64_rle_ends_delta", "i64_rle_ends_for", "i64_dict_codes_raw", "sym_w8_for", "sym_w32_rle", + "f64_alp", "f64_alprd_len1", "f64_alprd_len1023", "f64_dict_signed", "f64_rle", "f32_alp", "f64_alp_trailer", + "str_dict", "str_dict_codes_rle", "str_fsst", NULL, +}; + +static test_result_t test_golden_emit(void) { + const char* why = golden_emit_all(ray_test_tmp(ENC_GOLDEN_OUT)); + TEST_ASSERT_FMT(why == NULL, "%s", why); + PASS(); +} + +static test_result_t test_golden_match(void) { + const char* why = golden_emit_all(ray_test_tmp(ENCFMT_TMP "/golden")); + TEST_ASSERT_FMT(why == NULL, "%s", why); + const char* const* names = g_golden_names; + for (size_t i = 0; names[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, "%s/%s.bin", ENC_GOLDEN_DIR, names[i]); + snprintf(b, sizeof b, "%s/golden/%s.bin", ray_test_tmp(ENCFMT_TMP), names[i]); + size_t na = 0, nb = 0; uint8_t* pa = read_file(a, &na); uint8_t* pb = read_file(b, &nb); + bool ok = pa && pb && na == nb && memcmp(pa, pb, na) == 0; + bool have_fixture = pa != NULL; + free(pa); free(pb); + TEST_ASSERT_FMT(have_fixture, "missing fixture %s", a); + TEST_ASSERT_FMT(ok, "%s differs from its fixture", names[i]); + } + PASS(); +} + +static test_result_t test_golden_stream(void) { + (void)ray_test_mkdir_p(ray_test_tmp(ENCFMT_TMP "/gs")); + for (int i = 0;; i++) { + const char* name; int force, want; + ray_t* v = golden_vec(i, &name, &force, &want); + if (!v) break; + ray_col_stream_t w; + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, ray_test_tmp(ENCFMT_TMP "/gs"), ray_sym_intern(name, strlen(name)), v->type, NULL, 2), RAY_OK); + ray_encw_test_force(force); + ray_err_t e = v->len ? ray_col_stream_append(&w, v) : RAY_OK; + if (e == RAY_OK) e = ray_col_stream_close(&w, false); + ray_encw_test_force(-1); + ray_col_stream_abort(&w); + ray_release(v); + TEST_ASSERT_FMT(e == RAY_OK, "%s: stream %d", name, (int)e); + char a[512], b[512]; + snprintf(a, sizeof a, "%s/%s.bin", ENC_GOLDEN_DIR, name); + snprintf(b, sizeof b, "%s/gs/%s", ray_test_tmp(ENCFMT_TMP), name); + size_t na, nb; uint8_t* pa = read_file(a, &na); uint8_t* pb = read_file(b, &nb); + bool same = pa && pb && na == nb && memcmp(pa, pb, na) == 0; + free(pa); free(pb); + TEST_ASSERT_FMT(same, "%s: stream differs from the fixture", name); + } + PASS(); +} + +/* Every checked-in fixture decodes, through the generation-2 reader, to the + * vector its generator regenerates. sym_w32_rle is excluded: its saved + * count (0xFFFFFFFF) lies above any symbol domain a test can build. */ +static test_result_t test_golden_decode_matches(void) { + for (int i = 0; i < 256; i++) { char b[8]; int n = snprintf(b, sizeof b, "s%d", i); (void)ray_sym_intern(b, (size_t)n); } + const char* why = golden_emit_all(ray_test_tmp(ENCFMT_TMP "/gdm")); /* also regenerates the SYM id table */ + TEST_ASSERT_FMT(why == NULL, "%s", why); + for (int i = 0;; i++) { + const char* name; int force, want; + ray_t* v = golden_vec(i, &name, &force, &want); + if (!v) break; + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", ENC_GOLDEN_DIR, name); + ray_t* c = ray_col_mmap(path); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "fixture %s does not load", name); + ray_enccol_t* e = ray_enccol_of(c); + TEST_ASSERT_FMT(e->len == v->len && e->type == v->type, "%s: shape", name); + uint8_t esz = ray_enccol_esz(e); + uint8_t out[RAY_ENC_VEC * 16]; char pool[RAY_ENC_VEC * 64]; + const char* spool = (v->type == RAY_STR && v->str_pool) ? (const char*)ray_data(v->str_pool) : NULL; + for (int64_t vec = 0; vec < ray_enc_nvecs(v->len); vec++) { + ray_t* err = ray_enccol_decode_vec(e, vec, out, pool, 0); + TEST_ASSERT_FMT(err == NULL, "%s vec %lld: %s", name, (long long)vec, err ? ray_err_code(err) : ""); + int vn = ray_enc_vec_len(v->len, vec); + if (v->type == RAY_STR) { + const ray_str_t* a = (const ray_str_t*)ray_data(v) + vec * RAY_ENC_VEC; + const ray_str_t* b = (const ray_str_t*)out; + for (int r = 0; r < vn; r++) { + TEST_ASSERT_FMT(a[r].len == b[r].len, "%s str len row %d", name, r); + TEST_ASSERT_FMT(memcmp(ray_str_t_ptr(&a[r], spool), ray_str_t_ptr(&b[r], pool), a[r].len) == 0, "%s str row %d", name, r); + } + } else { + const uint8_t* a = (const uint8_t*)ray_data(v) + (size_t)vec * RAY_ENC_VEC * esz; + TEST_ASSERT_FMT(memcmp(a, out, (size_t)vn * esz) == 0, "%s vec %lld differs from its input", name, (long long)vec); + } + } + ray_release(c); + ray_release(v); + } + /* SYM fixture: ids from the generator's table. */ + const char* sname; (void)golden_sym(0, ray_test_tmp(ENCFMT_TMP "/gdm"), &sname); + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", ENC_GOLDEN_DIR, sname); + ray_t* c = ray_col_mmap(path); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "fixture %s does not load", sname); + uint8_t out[RAY_ENC_VEC * 16]; + ray_t* err = ray_enccol_decode_vec(ray_enccol_of(c), 0, out, NULL, 0); + TEST_ASSERT_NULL(err); + for (int k = 0; k < 1024; k++) TEST_ASSERT_EQ_I(out[k], 100 + (k % 16)); + ray_release(c); + PASS(); +} + +/* Pooled strings (longer than 12 bytes) reach the encoder through the + * column's real pool. Row i has 1 + i % 29 bytes, so inline (<= 12) and + * pooled strings alternate; pooled rows are unique (a decimal row tag). + * Chunk 1 is read back cell by cell: a wrong per-chunk stride or a wrong + * pool would change its strings or offsets. */ +static int str_row(int64_t i, char* s) { + int k = 1 + (int)(i % 29); + if (k > 12) { char tag[16]; snprintf(tag, sizeof tag, "%07d", (int)i); memset(s, 'a' + (int)(i % 26), (size_t)k); memcpy(s, tag, 7); } + else memset(s, 'a' + (int)(i % 26), (size_t)k); + return k; +} + +static test_result_t test_str_pooled_column(void) { + int64_t len = 65536 + 40; + ray_t* v = ray_vec_new(RAY_STR, len); + char s[40]; + uint64_t pooled = 0, chunk1_pooled = 0; + for (int64_t i = 0; i < len; i++) { + int k = str_row(i, s); + v = ray_str_vec_append(v, s, (size_t)k); + if (k > 12) { pooled += (uint64_t)k; if (i >= 65536) chunk1_pooled += (uint64_t)k; } + } + /* P6: the RAW STR body is this test's subject (selection takes FSST) */ + ray_encw_test_force(RAY_ENC_RAW); + ray_err_t se = ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/sp"), 2); + ray_encw_test_force(-1); + ray_release(v); + TEST_ASSERT_EQ_I(se, RAY_OK); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/sp"), &n); + TEST_ASSERT_NOT_NULL(b); + /* every check below frees the file before it fails */ +#define SP_CHECK(c) do { if (!(c)) { free(b); FAIL("str_pooled_column: " #c); } } while (0) + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + SP_CHECK(eh.str_pool_bytes == pooled); + SP_CHECK(eh.end_off == n); + ray_enc_dirent_t e1; memcpy(&e1, b + 96 + 64, 64); + ray_enc_desc_t d0; memcpy(&d0, b + e1.offset, 48); + SP_CHECK(d0.encoding == RAY_ENC_RAW); + const uint8_t* cells = b + e1.offset + d0.payload_off; + uint64_t pb; memcpy(&pb, cells + 40 * 16, 8); + SP_CHECK(pb == chunk1_pooled); + const uint8_t* pool = cells + 40 * 16 + 8; + uint32_t want_off = 0; + for (int j = 0; j < 40; j++) { + int k = str_row(65536 + j, s); + uint32_t len_c; memcpy(&len_c, cells + j * 16, 4); + SP_CHECK(len_c == (uint32_t)k); + if (k <= 12) { + SP_CHECK(memcmp(cells + j * 16 + 4, s, (size_t)k) == 0); + } else { + uint32_t off; memcpy(&off, cells + j * 16 + 8, 4); + SP_CHECK(off == want_off); + SP_CHECK(memcmp(pool + off, s, (size_t)k) == 0); + want_off += (uint32_t)k; + } + } +#undef SP_CHECK + free(b); + PASS(); +} + +static int file_gen(const char* path) { + size_t n; uint8_t* b = read_file(path, &n); + int g = (b && n >= 32) ? ray_col_gen_of(b) : -99; + free(b); + return g; +} + +static bool files_equal(const char* a, const char* b) { + size_t na, nb; uint8_t* pa = read_file(a, &na); uint8_t* pb = read_file(b, &nb); + bool eq = pa && pb && na == nb && memcmp(pa, pb, na) == 0; + free(pa); free(pb); + return eq; +} + +static bool file_exists(const char* path) { + FILE* f = fopen(path, "rb"); + if (f) fclose(f); + return f != NULL; +} + +static ray_t* i64_ramp(int64_t len) { + ray_t* v = ray_vec_new(RAY_I64, len); + v->len = len; + for (int64_t i = 0; i < len; i++) ((int64_t*)ray_data(v))[i] = i * 3; + return v; +} + +/* Columns generation 2 cannot hold are written as generation 0. */ +static test_result_t test_gen0_fallback(void) { + ray_t* v = i64_ramp(2000); + ray_t* r = ray_index_attach_hash(&v); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/fh"), 2), RAY_OK); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(ENCFMT_TMP "/fh")), 2); /* P4: indexed columns are generation 2 */ + { + size_t n = 0; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/fh"), &n); + TEST_ASSERT_TRUE(b && n >= 96); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + free(b); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_HASH); + TEST_ASSERT_TRUE(eh.index_off != 0 && eh.index_off % 32 == 0); + } + ray_release(v); + + ray_t* l = ray_list_new(2); + l = ray_list_append(l, ray_i64(5)); + ray_err_t e = ray_col_save_gen(l, ray_test_tmp(ENCFMT_TMP "/fl"), 2); + TEST_ASSERT_EQ_I(e, ray_col_save(l, ray_test_tmp(ENCFMT_TMP "/fl0"))); + TEST_ASSERT_TRUE(files_equal(ray_test_tmp(ENCFMT_TMP "/fl"), ray_test_tmp(ENCFMT_TMP "/fl0"))); /* the gen-0 bytes */ + ray_release(l); + + v = i64_ramp(100); + v->attrs |= RAY_ATTR_HAS_LINK; /* link bit only: ineligible */ + e = ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/fk"), 2); + TEST_ASSERT_EQ_I(e, ray_col_save(v, ray_test_tmp(ENCFMT_TMP "/fk0"))); + TEST_ASSERT_TRUE(files_equal(ray_test_tmp(ENCFMT_TMP "/fk"), ray_test_tmp(ENCFMT_TMP "/fk0"))); /* the gen-0 bytes */ + v->attrs &= (uint8_t)~RAY_ATTR_HAS_LINK; + ray_release(v); + + /* a plain column of the same shape is generation 2 */ + v = i64_ramp(2000); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/fp"), 2), RAY_OK); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(ENCFMT_TMP "/fp")), 2); + /* generation 0 is explicit */ + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/f0"), 0), RAY_OK); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(ENCFMT_TMP "/f0")), 0); + /* generation 1 does not exist */ + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/f1"), 1), RAY_ERR_VERSION); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/f1"))); + ray_release(v); + PASS(); +} + +static test_result_t test_bulk_gen(void) { + ray_t* v = i64_ramp(70000); + TEST_ASSERT_EQ_I(ray_col_save_bulk_gen(v, ray_test_tmp(ENCFMT_TMP "/b2"), 2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/d2"), 2), RAY_OK); + size_t na, nb; uint8_t* a = read_file(ray_test_tmp(ENCFMT_TMP "/b2"), &na); uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/d2"), &nb); + TEST_ASSERT_TRUE(a && b && na == nb && memcmp(a, b, na) == 0); /* durability changes no bytes */ + free(a); free(b); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(ENCFMT_TMP "/b2")), 2); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/b2.tmp"))); + TEST_ASSERT_EQ_I(ray_col_save_bulk_gen(v, ray_test_tmp(ENCFMT_TMP "/b0"), 0), RAY_OK); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(ENCFMT_TMP "/b0")), 0); + TEST_ASSERT_EQ_I(ray_col_save_bulk_gen(v, ray_test_tmp(ENCFMT_TMP "/b1"), 1), RAY_ERR_VERSION); + ray_release(v); + PASS(); +} + +/* The enc header records ZONE / CHUNK_ZONE and the UNIQUE flag. */ +static test_result_t test_header_index_meta(void) { + ray_t* v = i64_ramp(70000); + ray_t* r = ray_index_attach_zone(&v); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_index_payload(v->index)->markers |= RAY_MARK_UNIQUE; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/iz"), 2), RAY_OK); + ray_release(v); + size_t n; uint8_t* b = read_file(ray_test_tmp(ENCFMT_TMP "/iz"), &n); + TEST_ASSERT_EQ_I(file_gen(ray_test_tmp(ENCFMT_TMP "/iz")), 2); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_ZONE); + TEST_ASSERT_EQ_I(eh.col_flags, RAY_ENC_FLAG_UNIQUE); + TEST_ASSERT_EQ_U(eh.index_off, 0); + free(b); + + v = i64_ramp(70000); + r = ray_index_attach_chunk_zone(&v, 16); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/ic"), 2), RAY_OK); + ray_release(v); + b = read_file(ray_test_tmp(ENCFMT_TMP "/ic"), &n); + memcpy(&eh, b + 32, 64); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_EQ_I(eh.col_flags, 0); + free(b); + PASS(); +} + +/* A ZONE root on a type the matrix does not admit is refused, nothing left behind. */ +static test_result_t test_admission_refusal(void) { + ray_t* v = i64_ramp(100); + ray_t* r = ray_index_attach_zone(&v); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + v->type = RAY_SYM; /* matrix: SYM carries no ZONE */ + ray_err_t e = ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/nyi"), 2); + v->type = RAY_I64; + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_ERR_NYI); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/nyi"))); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/nyi.tmp"))); + PASS(); +} + +/* An I/O failure returns an error and leaves neither a target nor a .tmp. */ +static test_result_t test_save_io_failure(void) { + ray_t* v = i64_ramp(100); + TEST_ASSERT_TRUE(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/nodir/x"), 2) != RAY_OK); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/nodir/x.tmp"))); + /* the rename fails: the target is an existing directory */ + (void)ray_test_mkdir_p(ray_test_tmp(ENCFMT_TMP "/isdir")); + TEST_ASSERT_TRUE(ray_col_save_gen(v, ray_test_tmp(ENCFMT_TMP "/isdir"), 2) != RAY_OK); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/isdir.tmp"))); + TEST_ASSERT_TRUE(ray_col_save_bulk_gen(v, ray_test_tmp(ENCFMT_TMP "/isdir"), 2) != RAY_OK); + TEST_ASSERT_FALSE(file_exists(ray_test_tmp(ENCFMT_TMP "/isdir.tmp"))); + ray_release(v); + PASS(); +} + +const test_entry_t encfmt_entries[] = { + { "encfmt/discriminator_pairs", test_discriminator_pairs, encfmt_setup, encfmt_teardown }, + { "encfmt/discriminator_cross_pairs", test_discriminator_cross_pairs, encfmt_setup, encfmt_teardown }, + { "encfmt/gen0_writer_zeroes_aux", test_gen0_writer_zeroes_aux, encfmt_setup, encfmt_teardown }, + { "encfmt/length_helpers", test_length_helpers, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_i32_for", test_vec_i32_for, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_i64_nulls_bitmap_and_sum",test_vec_i64_nulls_bitmap_and_sum,encfmt_setup, encfmt_teardown }, + { "encfmt/vec_all_null_is_const", test_vec_all_null_is_const, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_f64_trailer", test_vec_f64_trailer, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_f64_const_and_zeros", test_vec_f64_const_and_zeros, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_f64_const_trailer", test_vec_f64_const_with_trailer, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_forced", test_vec_forced, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_forced_float", test_vec_forced_float, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_guid", test_vec_guid, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_str_raw_and_const", test_vec_str_raw_and_const, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_sym_w8_inband", test_vec_sym_w8_inband, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_bool_rle", test_vec_bool_rle, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_roundtrip_codecs", test_vec_roundtrip_codecs, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_roundtrip_dict", test_vec_roundtrip_dict, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_sums_literal", test_vec_sums_literal, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_f32_trailer", test_vec_f32_trailer, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_all_null_kinds", test_vec_all_null_kinds, encfmt_setup, encfmt_teardown }, + { "encfmt/vec_sym_w16_w32", test_vec_sym_w16_w32, encfmt_setup, encfmt_teardown }, + { "encfmt/golden_decode_matches", test_golden_decode_matches, encfmt_setup, encfmt_teardown }, + { "encfmt/file_headers", test_file_headers, encfmt_setup, encfmt_teardown }, + { "encfmt/trailing_descriptors_zero", test_trailing_descriptors_zero, encfmt_setup, encfmt_teardown }, + { "encfmt/dir_sums_extremes", test_dir_sums_extremes, encfmt_setup, encfmt_teardown }, + { "encfmt/side_value_dict", test_side_value_dict, encfmt_setup, encfmt_teardown }, + { "encfmt/side_unused_dict", test_side_unused_dict_not_written, encfmt_setup, encfmt_teardown }, + { "encfmt/admission_matrix", test_admission_matrix, encfmt_setup, encfmt_teardown }, + { "encfmt/empty_column", test_empty_column, encfmt_setup, encfmt_teardown }, + { "encfmt/str_pooled_column", test_str_pooled_column, encfmt_setup, encfmt_teardown }, + { "encfmt/gen0_fallback", test_gen0_fallback, encfmt_setup, encfmt_teardown }, + { "encfmt/bulk_gen", test_bulk_gen, encfmt_setup, encfmt_teardown }, + { "encfmt/header_index_meta", test_header_index_meta, encfmt_setup, encfmt_teardown }, + { "encfmt/admission_refusal", test_admission_refusal, encfmt_setup, encfmt_teardown }, + { "encfmt/save_io_failure", test_save_io_failure, encfmt_setup, encfmt_teardown }, + { "encfmt/golden_emit", test_golden_emit, encfmt_setup, encfmt_teardown }, + { "encfmt/golden_match", test_golden_match, encfmt_setup, encfmt_teardown }, + { "encfmt/golden_stream", test_golden_stream, encfmt_setup, encfmt_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_encidx.c b/test/test_encidx.c new file mode 100644 index 000000000..e25b5664c --- /dev/null +++ b/test/test_encidx.c @@ -0,0 +1,3031 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#define _POSIX_C_SOURCE 200809L +#include "test.h" +#include +#include "mem/heap.h" +#include "ops/idxop.h" +#include "table/sym.h" +#include "table/domain.h" +#include "store/encidx.h" +#include "ops/hash.h" +#include "core/pool.h" +#include "ops/rowsel.h" +#include "store/enccol.h" +#include "store/encw.h" +#include "store/col.h" +#include "store/colrange.h" +#include "table/table.h" /* ray_table_col_index */ +#include "core/platform.h" /* ray_thread_create */ +#include "store/splay.h" /* ray_splay_resolve_dir */ +#include "ops/ops.h" /* ray_graph_new: the unsplit eq+range conjunction */ +#include "lang/env.h" /* ray_env_get */ +#include "mem/cow.h" /* ray_rc_sync */ +#include "lang/format.h" /* ray_fmt */ +#include +#include +#include +#include +#include +#include + +#define IDX_TMP "/tmp/rayforce_encidx" + +static void ix_setup(void) { ray_heap_init(); (void)ray_sym_init(); (void)ray_test_rm_rf(ray_test_tmp(IDX_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(IDX_TMP)); } +static void ix_teardown(void) { ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(IDX_TMP)); ray_sym_destroy(); ray_heap_destroy(); } + +static uint8_t* ix_slurp(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); + uint8_t* b = malloc((size_t)sz + 1); + *n = fread(b, 1, (size_t)sz, f); + fclose(f); + return b; +} + +/* The region of `v`'s attached index, written to a file and read back. */ +static uint8_t* ix_region(ray_t* v, const char* name, uint32_t nlen, size_t* n, ray_t** err) { + FILE* f = fopen(ray_test_tmp(IDX_TMP "/r"), "wb"); + ray_enc_idx_src_t s = { v->index, v->type, v->attrs, v->len, name, nlen }; + uint64_t bytes = 0; + *err = ray_enc_index_write(f, &s, &bytes); + fclose(f); + if (*err) return NULL; + uint8_t* b = ix_slurp(ray_test_tmp(IDX_TMP "/r"), n); + if (b && *n != bytes) { free(b); return NULL; } + return b; +} + +static int64_t rd64(const uint8_t* p) { int64_t x; memcpy(&x, p, 8); return x; } +static uint64_t ix_p32(uint64_t x) { return (x + 31) & ~(uint64_t)31; } + +static ray_t* i64_vec(const int64_t* d, int64_t n) { return ray_vec_from_raw(RAY_I64, d, n); } +/* v with an index attached by `attach`, or NULL (v released). */ +static ray_t* with_index(ray_t* v, ray_t* (*attach)(ray_t**)) { + if (!v) return NULL; + ray_t* r = attach(&v); + if (r && !RAY_IS_ERR(r)) return r; + if (r) ray_error_free(r); + ray_release(v); /* a failed attach leaves *vp owned */ + return NULL; +} + +/* A fabricated HASH root: table/gkeys/offs/rows given by the test. */ +static ray_t* fab_hash(int8_t type, int64_t len, const int64_t* tbl, uint64_t cap, const int64_t* gk, + int64_t ng, const int64_t* of, const int64_t* rw, int64_t nk) { + ray_t* root = ray_index_new_root(RAY_IDX_HASH, type, len); + ray_index_t* ix = ray_index_payload(root); + ix->u.hash.table = ray_vec_from_raw(RAY_I64, tbl, (int64_t)cap); + ix->u.hash.gkeys = ray_vec_from_raw(RAY_I64, gk, ng); + ix->u.hash.offs = ray_vec_from_raw(RAY_I64, of, ng + 1); + ix->u.hash.rows = ray_vec_from_raw(RAY_I64, rw, nk); + ix->u.hash.mask = cap - 1; ix->u.hash.n_keys = nk; ix->u.hash.n_groups = ng; + ix->u.hash.order_sym = -1; + return root; +} + +/* Write a source root; the error, or NULL with the region in *out. */ +static ray_t* fab_write(ray_t* root, int8_t type, uint8_t attrs, int64_t len, uint8_t** out, size_t* n) { + FILE* f = fopen(ray_test_tmp(IDX_TMP "/f"), "wb"); + ray_enc_idx_src_t s = { root, type, attrs, len, NULL, 0 }; + uint64_t bytes; + ray_t* e = ray_enc_index_write(f, &s, &bytes); + fclose(f); + *out = NULL; + if (e) return e; + *out = ix_slurp(ray_test_tmp(IDX_TMP "/f"), n); + return NULL; +} +static uint8_t* fab_region(ray_t* root, int8_t type, uint8_t attrs, int64_t len, size_t* n) { + uint8_t* b; + ray_t* e = fab_write(root, type, attrs, len, &b, n); + if (e) { ray_error_free(e); return NULL; } + return b; +} + +static uint64_t slot_of(int64_t k, uint64_t cap) { return ray_index_mix64((uint64_t)k) & (cap - 1); } + +/* The writer refuses `root` with nyi naming `why`, writing nothing. */ +static test_result_t ix_write_refused(ray_t* root, int8_t type, int64_t len, const char* why) { + uint8_t* b; size_t n = 0; + ray_error_clear(); + ray_t* e = fab_write(root, type, 0, len, &b, &n); + TEST_ASSERT_FMT(e != NULL, "written: %s", why); + TEST_ASSERT_STR_EQ(ray_err_code(e), "nyi"); + TEST_ASSERT_FMT(strstr(ray_error_msg(), why) != NULL, "message '%s', want '%s'", ray_error_msg(), why); + TEST_ASSERT_EQ_U(n, 0); + ray_error_free(e); + free(b); + PASS(); +} +#define WRITE_REFUSED(root, type, len, why) do { test_result_t r_ = ix_write_refused((root), (type), (len), (why)); \ + if (r_.status != TEST_PASS) return r_; } while (0) + +/* HASH on I64: root, kind area, normalized child placement, child bytes. */ +static test_result_t test_write_hash_layout(void) { + int64_t d[6] = { 5, 7, 5, 9, 7, 5 }; + ray_t* v = with_index(i64_vec(d, 6), ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(v); + size_t n; ray_t* err; + uint8_t* b = ix_region(v, NULL, 0, &n, &err); + TEST_ASSERT_NULL(err); + ray_index_t* ix = ray_index_payload(v->index); + TEST_ASSERT_EQ_I((int8_t)b[0], RAY_I64); + for (int i = 1; i < 8; i++) TEST_ASSERT_EQ_I(b[i], 0); + TEST_ASSERT_EQ_I(rd64(b + 8), 6); + ray_enc_idx_hash_t h; memcpy(&h, b + 16, 64); + uint64_t cap = ix->u.hash.mask + 1; + TEST_ASSERT_EQ_I(h.table, 96); + TEST_ASSERT_EQ_I(h.gkeys, (int64_t)ix_p32(96 + cap * 8)); + TEST_ASSERT_EQ_I(h.offs, (int64_t)ix_p32((uint64_t)h.gkeys + 3 * 8)); + TEST_ASSERT_EQ_I(h.rows, (int64_t)ix_p32((uint64_t)h.offs + 4 * 8)); + TEST_ASSERT_EQ_U(h.mask, ix->u.hash.mask); + TEST_ASSERT_EQ_I(h.n_keys, 6); + TEST_ASSERT_EQ_I(h.n_groups, 3); + TEST_ASSERT_EQ_I(h.order_name, -1); + TEST_ASSERT_EQ_U(n, ix_p32((uint64_t)h.rows + 6 * 8)); + /* the region holds the generation-1 layout of the index (I64 arrays, + * groups by first occurrence, low-bits homes), whatever its builder */ + ray_t *lt, *lg, *lo, *lr; + TEST_ASSERT_TRUE(ray_index_hash_legacy(ix, <, &lg, &lo, &lr)); + TEST_ASSERT_TRUE(memcmp(b + h.table, ray_data(lt), cap * 8) == 0); + TEST_ASSERT_TRUE(memcmp(b + h.gkeys, ray_data(lg), 3 * 8) == 0); + TEST_ASSERT_TRUE(memcmp(b + h.offs, ray_data(lo), 4 * 8) == 0); + TEST_ASSERT_TRUE(memcmp(b + h.rows, ray_data(lr), 6 * 8) == 0); + ray_release(lt); ray_release(lg); ray_release(lo); ray_release(lr); + for (size_t i = 80; i < 96; i++) TEST_ASSERT_EQ_I(b[i], 0); + free(b); ray_release(v); + PASS(); +} + +/* The name block: u32 len, u32 reserved, bytes, zero pad to 32, last. */ +static test_result_t test_write_name_block(void) { + int64_t d[4] = { 1, 1, 2, 2 }; + ray_t* v = with_index(i64_vec(d, 4), ray_index_attach_part); + TEST_ASSERT_NOT_NULL(v); + size_t n; ray_t* err; + uint8_t* b = ix_region(v, "ts", 2, &n, &err); + TEST_ASSERT_NULL(err); + ray_enc_idx_part_t p; memcpy(&p, b + 16, 40); + TEST_ASSERT_EQ_I(p.n_parts, 2); + TEST_ASSERT_EQ_I(p.keys, 96); + TEST_ASSERT_EQ_I(p.starts, (int64_t)ix_p32(96 + 2 * 8)); + TEST_ASSERT_EQ_I(p.order_name, (int64_t)ix_p32((uint64_t)p.lens + 2 * 8)); + uint32_t nl; memcpy(&nl, b + p.order_name, 4); + TEST_ASSERT_EQ_I(nl, 2); + TEST_ASSERT_TRUE(memcmp(b + p.order_name + 8, "ts", 2) == 0); + TEST_ASSERT_EQ_U(n, ix_p32((uint64_t)p.order_name + 10)); + for (size_t i = (size_t)p.order_name + 10; i < n; i++) TEST_ASSERT_EQ_I(b[i], 0); + free(b); + /* a name holding a NUL is written as -1 */ + b = ix_region(v, "t\0s", 3, &n, &err); + TEST_ASSERT_NULL(err); + memcpy(&p, b + 16, 40); + TEST_ASSERT_EQ_I(p.order_name, -1); + free(b); + /* SORT and BLOOM have no order_name: a name given is not written */ + { int64_t sd[4] = { 3, 1, 2, 0 }; + ray_t* (*nk[2])(ray_t**) = { ray_index_attach_sort, ray_index_attach_bloom }; + for (int k = 0; k < 2; k++) { + ray_t* s = with_index(i64_vec(sd, 4), nk[k]); + TEST_ASSERT_NOT_NULL(s); + size_t n0, n1; uint8_t* b0 = ix_region(s, NULL, 0, &n0, &err); + uint8_t* b1 = ix_region(s, "ts", 2, &n1, &err); + TEST_ASSERT_TRUE(b0 && b1 && n0 == n1 && memcmp(b0, b1, n0) == 0); + free(b0); free(b1); ray_release(s); + } } + /* a name over the limit is written as -1 */ + char longn[300]; memset(longn, 'x', sizeof longn); + b = ix_region(v, longn, 300, &n, &err); + TEST_ASSERT_NULL(err); + memcpy(&p, b + 16, 40); + TEST_ASSERT_EQ_I(p.order_name, -1); + free(b); ray_release(v); + PASS(); +} + +/* SORT and BLOOM layouts; unused kind-area tails are zero. */ +static test_result_t test_write_sort_bloom(void) { + int32_t d[5] = { 9, 3, 7, 1, 3 }; + ray_t* s = with_index(ray_vec_from_raw(RAY_I32, d, 5), ray_index_attach_sort); + ray_t* bl = with_index(ray_vec_from_raw(RAY_I32, d, 5), ray_index_attach_bloom); + TEST_ASSERT_TRUE(s && bl); + size_t n; ray_t* err; + uint8_t* b = ix_region(s, NULL, 0, &n, &err); + TEST_ASSERT_NULL(err); + TEST_ASSERT_EQ_I(rd64(b + 16), 96); + for (int i = 24; i < 80; i++) TEST_ASSERT_EQ_I(b[i], 0); + TEST_ASSERT_EQ_U(n, ix_p32(96 + 5 * 8)); + free(b); + b = ix_region(bl, NULL, 0, &n, &err); + TEST_ASSERT_NULL(err); + ray_enc_idx_bloom_t bb; memcpy(&bb, b + 16, 32); + ray_index_t* ix = ray_index_payload(bl->index); + TEST_ASSERT_EQ_I(bb.bits, 96); + TEST_ASSERT_EQ_U(bb.m_mask, ix->u.bloom.m_mask); + TEST_ASSERT_EQ_I(bb.k, 3); + TEST_ASSERT_EQ_I(bb.n_keys, 5); + for (int i = 48; i < 80; i++) TEST_ASSERT_EQ_I(b[i], 0); + TEST_ASSERT_EQ_U(n, ix_p32(96 + (bb.m_mask + 1) / 8)); + free(b); ray_release(s); ray_release(bl); + PASS(); +} + +/* A fabricated root with a STR child, or a kind the matrix refuses, fails + * with nyi naming the kind. */ +static test_result_t test_write_rejects(void) { + int64_t d[3] = { 1, 2, 3 }; + ray_t* v = with_index(i64_vec(d, 3), ray_index_attach_part); + ray_index_t* ix = ray_index_payload(v->index); + ray_t* keys = ix->u.part.keys; + ray_t* fake = ray_vec_new(RAY_STR, 3); + for (int i = 0; i < 3; i++) fake = ray_str_vec_append(fake, "k", 1); + ix->u.part.keys = fake; + size_t n; ray_t* err; + uint8_t* b = ix_region(v, NULL, 0, &n, &err); + TEST_ASSERT_NULL(b); + TEST_ASSERT_NOT_NULL(err); + TEST_ASSERT_STR_EQ(ray_err_code(err), "nyi"); + TEST_ASSERT_TRUE(strstr(ray_error_msg(), "PART") != NULL); + ray_error_free(err); + ix->u.part.keys = keys; + ray_release(fake); + /* SORT on SYM is not admitted */ + ray_t* root = ray_index_new_root(RAY_IDX_SORT, RAY_SYM, 3); + ray_enc_idx_src_t s = { root, RAY_SYM, RAY_SYM_W8, 3, NULL, 0 }; + FILE* f = fopen(ray_test_tmp(IDX_TMP "/r"), "wb"); + uint64_t bytes; + err = ray_enc_index_write(f, &s, &bytes); + fclose(f); + TEST_ASSERT_NOT_NULL(err); + TEST_ASSERT_STR_EQ(ray_err_code(err), "nyi"); + ray_error_free(err); + ray_release(root); ray_release(v); + /* The scalar rules the validator enforces: the writer refuses a root + * that breaks one even when every child is consistent with it. */ + int32_t bd[5] = { 9, 3, 7, 1, 3 }; + ray_t* bl = with_index(ray_vec_from_raw(RAY_I32, bd, 5), ray_index_attach_bloom); + TEST_ASSERT_NOT_NULL(bl); + ray_index_t* bx = ray_index_payload(bl->index); + bx->u.bloom.k = 0; WRITE_REFUSED(bl->index, RAY_I32, 5, "BLOOM k"); + bx->u.bloom.k = RAY_ENC_IDX_BLOOM_K_MAX + 1; WRITE_REFUSED(bl->index, RAY_I32, 5, "BLOOM k"); + bx->u.bloom.k = 3; + bx->u.bloom.n_keys = 6; WRITE_REFUSED(bl->index, RAY_I32, 5, "BLOOM n_keys"); + bx->u.bloom.n_keys = 5; + ray_release(bl); + int64_t t8[8] = { 0 }, gk3[3] = { 10, 20, 30 }, of4[4] = { 0, 1, 2, 2 }, rw2[2] = { 0, 1 }; + t8[slot_of(10, 8)] = 1; + { uint64_t q = slot_of(20, 8); while (t8[q]) q = (q + 1) & 7; t8[q] = 2; + q = slot_of(30, 8); while (t8[q]) q = (q + 1) & 7; t8[q] = 3; } + /* three groups over two keys: n_groups > n_keys */ + root = fab_hash(RAY_I64, 4, t8, 8, gk3, 3, of4, rw2, 2); + WRITE_REFUSED(root, RAY_I64, 4, "HASH n_groups"); + ray_release(root); + /* five keys over four rows: n_keys > len */ + { int64_t of3[3] = { 0, 2, 5 }, rw5[5] = { 0, 1, 2, 3, 3 }; + root = fab_hash(RAY_I64, 4, t8, 8, gk3, 2, of3, rw5, 5); + WRITE_REFUSED(root, RAY_I64, 4, "HASH n_keys"); + ray_release(root); } + /* two buckets for two groups: no empty bucket */ + { int64_t t2[2] = { 1, 2 }, of3[3] = { 0, 1, 2 }; + root = fab_hash(RAY_I64, 4, t2, 2, gk3, 2, of3, rw2, 2); + WRITE_REFUSED(root, RAY_I64, 4, "empty bucket"); + ray_release(root); } + PASS(); +} + +/* Spec "Normalized bytes": the same index built from different allocations + * writes the same region. */ +static test_result_t test_write_normalized(void) { + int64_t d[2000]; + for (int i = 0; i < 2000; i++) d[i] = (i * 7919) % 613; + ray_t* a = with_index(i64_vec(d, 2000), ray_index_attach_hash); + ray_t* junk[64]; + for (int i = 0; i < 64; i++) junk[i] = ray_vec_new(RAY_I64, 100 + i); + ray_t* c = with_index(i64_vec(d, 2000), ray_index_attach_hash); + size_t na, nc; ray_t* err; + uint8_t* ra = ix_region(a, NULL, 0, &na, &err); + uint8_t* rc = ix_region(c, NULL, 0, &nc, &err); + TEST_ASSERT_TRUE(ra && rc && na == nc && memcmp(ra, rc, na) == 0); + free(ra); free(rc); + for (int i = 0; i < 64; i++) ray_release(junk[i]); + ray_release(a); ray_release(c); + PASS(); +} + +/* Trust: a heap root's order_sym converts, a passenger root's does not. */ +static test_result_t test_trusted_order(void) { + int64_t d[4] = { 1, 1, 2, 2 }; + ray_t* v = with_index(i64_vec(d, 4), ray_index_attach_part); + ray_index_t* ix = ray_index_payload(v->index); + ix->u.part.order_sym = ray_sym_intern("ts", 2); + TEST_ASSERT_EQ_I(ray_enc_index_trusted_order(v->index), ray_sym_intern("ts", 2)); + ix->markers |= RAY_MARK_MMAP; + TEST_ASSERT_EQ_I(ray_enc_index_trusted_order(v->index), -1); + ix->markers &= (uint8_t)~RAY_MARK_MMAP; + ray_release(v); + PASS(); +} + +/* SYM PART keys are written at the width class the source names; a key id + * past that class fails before any byte is written. */ +static test_result_t test_write_sym_part(void) { + ray_t* v = ray_sym_vec_new(RAY_SYM_W16, 4); + TEST_ASSERT_NOT_NULL(v); + static const uint16_t ids[4] = { 300, 300, 700, 700 }; + memcpy(ray_data(v), ids, sizeof ids); + v->len = 4; + v = with_index(v, ray_index_attach_part); + TEST_ASSERT_NOT_NULL(v); + size_t n; ray_t* err; + uint8_t* b = ix_region(v, NULL, 0, &n, &err); + TEST_ASSERT_NULL(err); + ray_enc_idx_part_t p; memcpy(&p, b + 16, 40); + TEST_ASSERT_EQ_I(p.n_parts, 2); + uint16_t k16[2]; memcpy(k16, b + p.keys, 4); + TEST_ASSERT_EQ_I(k16[0], 300); + TEST_ASSERT_EQ_I(k16[1], 700); + TEST_ASSERT_EQ_I(p.starts, (int64_t)ix_p32(96 + 2 * 2)); + free(b); + /* a wider class widens the keys */ + ray_enc_idx_src_t s = { v->index, RAY_SYM, RAY_SYM_W64, 4, NULL, 0 }; + FILE* f = fopen(ray_test_tmp(IDX_TMP "/r"), "wb"); + uint64_t bytes = 0; + err = ray_enc_index_write(f, &s, &bytes); + fclose(f); + TEST_ASSERT_NULL(err); + b = ix_slurp(ray_test_tmp(IDX_TMP "/r"), &n); + TEST_ASSERT_TRUE(b && n == bytes); + memcpy(&p, b + 16, 40); + TEST_ASSERT_EQ_I(rd64(b + p.keys), 300); + TEST_ASSERT_EQ_I(rd64(b + p.keys + 8), 700); + free(b); + /* a narrower class would truncate: nyi, nothing written */ + s.attrs = RAY_SYM_W8; + f = fopen(ray_test_tmp(IDX_TMP "/r"), "wb"); + err = ray_enc_index_write(f, &s, &bytes); + long at = ftell(f); + fclose(f); + TEST_ASSERT_NOT_NULL(err); + TEST_ASSERT_STR_EQ(ray_err_code(err), "nyi"); + TEST_ASSERT_TRUE(strstr(ray_error_msg(), "PART") != NULL); + TEST_ASSERT_EQ_I(at, 0); + TEST_ASSERT_EQ_I(bytes, 0); + ray_error_free(err); + ray_release(v); + PASS(); +} + +/* Region bytes do not depend on the core count: the persisted HASH builder + * is canonical, so the serial build (1 worker) and the parallel build + * (4 and 8 workers, 70000 rows is past the dispatch threshold) write the + * same region. */ +static test_result_t test_write_core_count(void) { + enum { N = 70000 }; + int64_t* d = malloc(N * sizeof *d); + TEST_ASSERT_NOT_NULL(d); + for (int64_t i = 0; i < N; i++) d[i] = (int64_t)(((uint64_t)i * 2654435761u) % 40000); + uint32_t cores = ray_pool_total_workers(ray_pool_get()); + static const uint32_t ws[3] = { 1, 4, 8 }; + uint8_t* r[3] = { NULL, NULL, NULL }; + size_t n[3] = { 0, 0, 0 }; + int64_t ng[3] = { -1, -1, -1 }; + bool ok = true; + for (int w = 0; w < 3 && ok; w++) { + ray_pool_destroy(); + if (ray_pool_init_total(ws[w]) != RAY_OK) { ok = false; break; } + ray_t* v = with_index(i64_vec(d, N), ray_index_attach_hash); + if (!v) { ok = false; break; } + ng[w] = ray_index_payload(v->index)->u.hash.n_groups; + ray_t* err = NULL; + r[w] = ix_region(v, "ts", 2, &n[w], &err); + if (err) { ray_error_free(err); ok = false; } + ray_release(v); + } + ray_pool_destroy(); + ray_err_t back = ray_pool_init_total(cores); + bool same = ok && r[0] && r[1] && r[2] && n[1] == n[0] && n[2] == n[0] && + memcmp(r[1], r[0], n[0]) == 0 && memcmp(r[2], r[0], n[0]) == 0; + ray_enc_idx_view_t iv; + if (r[0]) ray_enc_index_view(r[0], n[0], RAY_IDX_HASH, RAY_I64, 0, N, &iv); + bool valid = r[0] && iv.order_len == 2; + for (int w = 0; w < 3; w++) free(r[w]); + free(d); + TEST_ASSERT_EQ_I(back, RAY_OK); + TEST_ASSERT_TRUE(ok); + TEST_ASSERT_EQ_I(ng[0], 40000); + TEST_ASSERT_EQ_I(ng[1], 40000); + TEST_ASSERT_EQ_I(ng[2], 40000); + TEST_ASSERT_TRUE(same); + TEST_ASSERT_TRUE(valid); + PASS(); +} + +/* ===== Reading a region (ray_enc_index_view) ===== */ + +/* The view of the region of v's index. */ +static void ix_view(const uint8_t* b, size_t n, ray_t* v, ray_enc_idx_view_t* out) { + ray_index_t* ix = ray_index_payload(v->index); + ray_enc_index_view(b, n, ix->kind, v->type, v->attrs, v->len, out); +} + +/* The view of a written region names its fields. */ +static test_result_t test_view_fields(void) { + int64_t d[3000]; + for (int i = 0; i < 3000; i++) d[i] = (i * 31) % 997; + ray_t* (*kinds[3])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, ray_index_attach_bloom }; + for (int k = 0; k < 3; k++) { + ray_t* v = with_index(i64_vec(d, 3000), kinds[k]); + TEST_ASSERT_NOT_NULL(v); + size_t n; ray_t* err; uint8_t* b = ix_region(v, NULL, 0, &n, &err); + TEST_ASSERT_NOT_NULL(b); + ray_enc_idx_view_t iv; + ix_view(b, n, v, &iv); + TEST_ASSERT_TRUE(iv.base == b && iv.size == n && iv.len == 3000 && iv.order_name == NULL); + free(b); ray_release(v); + } + int64_t s[3000]; + for (int i = 0; i < 3000; i++) s[i] = i / 100; + ray_t* p = with_index(i64_vec(s, 3000), ray_index_attach_part); + TEST_ASSERT_NOT_NULL(p); + size_t n; ray_t* err; uint8_t* b = ix_region(p, "ts", 2, &n, &err); + ray_enc_idx_view_t iv; + ix_view(b, n, p, &iv); + TEST_ASSERT_EQ_I(iv.order_len, 2); + TEST_ASSERT_TRUE(memcmp(iv.order_name, "ts", 2) == 0); + TEST_ASSERT_EQ_I(iv.part.n_parts, 30); + free(b); ray_release(p); + PASS(); +} +/* Review focus 1 (spec "STR indexes": forced word collisions). Real rows + * "alpha", "beta", "alpha"; a fabricated root gives both groups alpha's word + * and puts beta's group FIRST on that chain, so a probe for "alpha" meets a + * word hit whose bytes differ and must walk on (hash_probe_setup_str's + * disambiguation). The region validates, and the source root finds alpha + * past the collision; beta (whose own word is in no bucket here) and gamma + * are absent. The parsed root's half of this comparison, answering exactly + * as the source root, lands with the parse (Task 4). */ +static ray_t* swc_col(void) { + ray_t* v = ray_vec_new(RAY_STR, 3); + v = ray_str_vec_append(v, "alpha", 5); v = ray_str_vec_append(v, "beta", 4); v = ray_str_vec_append(v, "alpha", 5); + return v; +} +static test_result_t test_str_word_collision(void) { + ray_t* v = swc_col(); + int64_t w = (int64_t)ray_hash_bytes("alpha", 5); + int64_t gk[2] = { w, w }, of[3] = { 0, 1, 3 }, rw[3] = { 1, 0, 2 }; /* g0 = beta, g1 = alpha */ + int64_t t8[8] = { 0 }; + uint64_t h = slot_of(w, 8); + t8[h] = 1; t8[(h + 1) & 7] = 2; + ray_t* root = fab_hash(RAY_STR, 3, t8, 8, gk, 2, of, rw, 3); + size_t n; uint8_t* b = fab_region(root, RAY_STR, 0, 3, &n); + TEST_ASSERT_NOT_NULL(b); + ray_enc_idx_view_t iv; + ray_enc_index_view(b, n, RAY_IDX_HASH, RAY_STR, 0, 3, &iv); + TEST_ASSERT_EQ_I(iv.hash.n_groups, 2); + /* the parsed root: the source's fields and children, and nothing in + * it refers to the region (freed before the probes) */ + ray_t* proot = NULL; + TEST_ASSERT_NULL(ray_enc_index_parse(&iv, v, &proot)); + TEST_ASSERT_NOT_NULL(proot); + free(b); + { ray_index_t* sx = ray_index_payload(root); ray_index_t* px = ray_index_payload(proot); + TEST_ASSERT_EQ_I(px->kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_U(px->u.hash.mask, 7); + TEST_ASSERT_EQ_I(px->u.hash.n_groups, 2); + TEST_ASSERT_EQ_I(px->u.hash.n_keys, 3); + TEST_ASSERT_EQ_I(px->u.hash.order_sym, -1); + TEST_ASSERT_TRUE(memcmp(ray_data(px->u.hash.table), ray_data(sx->u.hash.table), 64) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(px->u.hash.gkeys), gk, 16) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(px->u.hash.offs), of, 24) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(px->u.hash.rows), rw, 24) == 0); } + ray_t* src = v; ray_retain(src); + ray_t* a = ray_index_attach_persisted(&src, root); /* consumes root */ + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); src = a; + ray_t* pv = swc_col(); + ray_t* pa = ray_index_attach_persisted(&pv, proot); /* consumes proot */ + TEST_ASSERT_TRUE(pa && !RAY_IS_ERR(pa)); pv = pa; + /* Both roots give alpha past the collision at row 0. beta is absent + * from both: the fabricated root gives beta alpha's word, so no bucket + * holds beta's own word and its probe ends at an empty bucket. */ + static const char* const probes[3] = { "alpha", "beta", "gamma" }; + static const int64_t want[3] = { 0, -1, -1 }; + for (int i = 0; i < 3; i++) { + ray_t* atom = ray_str(probes[i], strlen(probes[i])); + int64_t r0 = ray_index_find_atom(src, atom); + int64_t r1 = ray_index_find_atom(pv, atom); + TEST_ASSERT_FMT(r0 == want[i], "source probe %s: %lld, want %lld", probes[i], (long long)r0, (long long)want[i]); + TEST_ASSERT_FMT(r1 == r0, "parsed probe %s: %lld, source %lld", probes[i], (long long)r1, (long long)r0); + ray_release(atom); + } + ray_release(pv); ray_release(src); ray_release(v); + PASS(); +} + +/* Empty columns: every kind's region over zero rows is written and read. */ +static test_result_t test_view_empty(void) { + ray_t* (*kinds[4])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, + ray_index_attach_bloom, ray_index_attach_part }; + for (int k = 0; k < 4; k++) { + ray_t* v = with_index(ray_vec_new(RAY_I64, 0), kinds[k]); + TEST_ASSERT_NOT_NULL(v); + size_t n; ray_t* err; uint8_t* b = ix_region(v, NULL, 0, &n, &err); + TEST_ASSERT_NULL(err); + TEST_ASSERT_NOT_NULL(b); + ray_enc_idx_view_t iv; + ix_view(b, n, v, &iv); + free(b); ray_release(v); + } + PASS(); +} + +/* Review carry (Task 2): every byte outside the root fields, the children + * and the name bytes is zero in the writer's output (root reserved, kind + * tail, inter-child padding, the name block's reserved u32, BLOOM rsv, the + * tail), and setting any one of them is corrupt. */ +static test_result_t ix_zero_fill(ray_t* v, const char* name, uint32_t nlen) { + size_t n; ray_t* err; + uint8_t* b = ix_region(v, name, nlen, &n, &err); + TEST_ASSERT_NOT_NULL(b); + uint8_t* used = calloc(n, 1); + #define USE(o, k) do { for (uint64_t u_ = 0; u_ < (uint64_t)(k); u_++) used[(o) + u_] = 1; } while (0) + USE(0, 1); USE(8, 8); + ray_index_t* ix = ray_index_payload(v->index); + int64_t name_at = -1; + if (ix->kind == RAY_IDX_HASH) { + ray_enc_idx_hash_t h; memcpy(&h, b + 16, 64); + USE(16, 64); + USE(h.table, (h.mask + 1) * 8); USE(h.gkeys, h.n_groups * 8); + USE(h.offs, (h.n_groups + 1) * 8); USE(h.rows, h.n_keys * 8); + name_at = h.order_name; + } else { + ray_enc_idx_bloom_t bb; memcpy(&bb, b + 16, 32); + USE(16, 20); USE(16 + 24, 8); /* bits, m_mask, k; n_keys (rsv stays zero) */ + USE(bb.bits, (bb.m_mask + 1) / 8); + } + if (nlen) { + TEST_ASSERT_TRUE(name_at > 0); + USE(name_at, 4); USE(name_at + 8, nlen); + } + #undef USE + for (size_t i = 0; i < n; i++) + if (!used[i]) TEST_ASSERT_FMT(b[i] == 0, "byte %zu of %zu is %u", i, n, b[i]); + free(used); free(b); + PASS(); +} +static test_result_t test_write_zero_fill(void) { + int64_t d[7] = { 5, 7, 5, 9, 7, 5, 11 }; + ray_t* h = with_index(i64_vec(d, 7), ray_index_attach_hash); + ray_t* bl = with_index(i64_vec(d, 7), ray_index_attach_bloom); + TEST_ASSERT_TRUE(h && bl); + test_result_t r = ix_zero_fill(h, "ts", 2); + if (r.status == TEST_PASS) r = ix_zero_fill(h, NULL, 0); + if (r.status == TEST_PASS) r = ix_zero_fill(bl, NULL, 0); + ray_release(h); ray_release(bl); + return r; +} + +/* ===== Parse ===== */ + +static bool same_child(const ray_t* a, const ray_t* b, size_t esz) { + return a && b && a->type == b->type && a->len == b->len && + memcmp(ray_data((ray_t*)a), ray_data((ray_t*)b), (size_t)a->len * esz) == 0; +} + +/* Parse the validated view of v's index and compare the heap root with + * the source root field by field; name: the order_name written. */ +/* The index a region holds for source index `a`: itself, except a HASH, + * which a region stores in the generation-1 layout (ray_index_hash_legacy: + * I64 arrays, groups by first occurrence, low-bits homes). *out is a copy + * of `a` with those arrays (hold[] owns them; ix_region_view_free). */ +static const ray_index_t* ix_region_view(const ray_index_t* a, ray_index_t* out, ray_t* hold[4]) { + for (int i = 0; i < 4; i++) hold[i] = NULL; + if (a->kind != RAY_IDX_HASH) return a; + *out = *a; + if (!ray_index_hash_legacy(a, &hold[0], &hold[1], &hold[2], &hold[3])) return a; + out->u.hash.table = hold[0]; out->u.hash.gkeys = hold[1]; + out->u.hash.offs = hold[2]; out->u.hash.rows = hold[3]; + out->markers &= (uint8_t)~RAY_MARK_HASH_HIGH; + return out; +} +static void ix_region_view_free(ray_t* hold[4]) { + for (int i = 0; i < 4; i++) if (hold[i]) ray_release(hold[i]); +} +static test_result_t ix_parse_same(ray_t* v, const ray_enc_idx_view_t* iv, const char* name, const char* what) { + ray_t* root = NULL; + ray_t* e = ray_enc_index_parse(iv, v, &root); + if (e) ray_error_free(e); + TEST_ASSERT_FMT(e == NULL && root != NULL, "%s: parse failed", what); + ray_index_t a_view; ray_t* a_hold[4]; + const ray_index_t* a = ix_region_view(ray_index_payload(v->index), &a_view, a_hold); + const ray_index_t* p = ray_index_payload(root); + bool hdr = p->kind == a->kind && p->parent_type == a->parent_type && p->built_for_len == a->built_for_len; + bool mapped = (p->markers & RAY_MARK_MMAP) != 0; + int64_t want_sym = name ? ray_sym_intern(name, strlen(name)) : -1; + bool ok = false; + switch (a->kind) { + case RAY_IDX_HASH: + ok = p->u.hash.mask == a->u.hash.mask && p->u.hash.n_keys == a->u.hash.n_keys && + p->u.hash.n_groups == a->u.hash.n_groups && p->u.hash.order_sym == want_sym && + same_child(p->u.hash.table, a->u.hash.table, 8) && same_child(p->u.hash.gkeys, a->u.hash.gkeys, 8) && + same_child(p->u.hash.offs, a->u.hash.offs, 8) && same_child(p->u.hash.rows, a->u.hash.rows, 8); + break; + case RAY_IDX_SORT: + ok = same_child(p->u.sort.perm, a->u.sort.perm, 8); + break; + case RAY_IDX_BLOOM: + ok = p->u.bloom.m_mask == a->u.bloom.m_mask && p->u.bloom.k == a->u.bloom.k && + p->u.bloom.n_keys == a->u.bloom.n_keys && same_child(p->u.bloom.bits, a->u.bloom.bits, 1); + break; + default: { + const ray_t* pk = p->u.part.keys; const ray_t* ak = a->u.part.keys; + ok = p->u.part.n_parts == a->u.part.n_parts && p->u.part.order_sym == want_sym && + same_child(p->u.part.starts, a->u.part.starts, 8) && same_child(p->u.part.lens, a->u.part.lens, 8) && + pk && pk->type == ak->type && pk->len == ak->len; + if (ok && v->type == RAY_SYM) { + ok = ray_sym_vec_domain((ray_t*)pk) == ray_sym_vec_domain(v) && + ray_sym_elem_size(RAY_SYM, pk->attrs) == ray_sym_elem_size(RAY_SYM, v->attrs); + for (int64_t i = 0; ok && i < pk->len; i++) + ok = ray_read_sym(ray_data((ray_t*)pk), i, RAY_SYM, pk->attrs) == + ray_read_sym(ray_data((ray_t*)ak), i, RAY_SYM, ak->attrs); + } else if (ok) { + ok = memcmp(ray_data((ray_t*)pk), ray_data((ray_t*)ak), (size_t)pk->len * ray_sym_elem_size(pk->type, pk->attrs)) == 0; + } + break; + } + } + ray_release(root); /* before any assertion can return */ + ix_region_view_free(a_hold); + TEST_ASSERT_FMT(hdr, "%s: root header", what); + TEST_ASSERT_FMT(!mapped, "%s: parsed root marked mapped", what); + TEST_ASSERT_FMT(ok, "%s: parsed root differs from the source", what); + PASS(); +} +#define PARSE_SAME(v, iv, name, ...) do { char w_[96]; snprintf(w_, sizeof w_, __VA_ARGS__); \ + test_result_t r_ = ix_parse_same((v), (iv), (name), w_); if (r_.status != TEST_PASS) return r_; } while (0) + +/* A column of type t over n rows for the engine matrix: ascending + * value-blocks when `sorted` (PART), else mixed values with nulls, both + * zeros and NaN payloads for floats. */ +static ray_t* mx_col(int8_t t, int64_t n, bool sorted) { + ray_t* v = ray_vec_new(t, n > 0 ? n : 1); + if (!v || RAY_IS_ERR(v)) return NULL; + v->len = n; + uint8_t* p = ray_data(v); + for (int64_t i = 0; i < n; i++) { + int64_t x = sorted ? (i * 5) / n - 2 : ((i * 37) % 13) - 6; + if (t == RAY_BOOL) x = sorted ? (i * 2 >= n) : (i & 1); + if (t == RAY_U8) x = sorted ? (i * 5) / n : (i * 37) % 251; + switch (t) { + case RAY_BOOL: case RAY_U8: p[i] = (uint8_t)x; break; + case RAY_I16: { int16_t y = (int16_t)x; memcpy(p + i * 2, &y, 2); break; } + case RAY_I32: case RAY_DATE: case RAY_TIME: { int32_t y = (int32_t)x; memcpy(p + i * 4, &y, 4); break; } + case RAY_F32: { + float y = (float)x; + if (x == 0 && (sorted ? n > 0 : (i & 1))) y = -0.0f; + memcpy(p + i * 4, &y, 4); + if (!sorted && i % 17 == 5) { uint32_t q = 0x7FC00000u | (uint32_t)i; memcpy(p + i * 4, &q, 4); } + break; + } + case RAY_F64: { + double y = (double)x; + if (x == 0 && (sorted ? n > 0 : (i & 1))) y = -0.0; + memcpy(p + i * 8, &y, 8); + if (!sorted && i % 17 == 5) { uint64_t q = 0x7FF8000000000000ull | (uint64_t)i; memcpy(p + i * 8, &q, 8); } + break; + } + default: memcpy(p + i * 8, &x, 8); break; + } + } + if (!sorted) + for (int64_t i = 3; i < n; i += 11) ray_vec_set_null(v, i, true); + return v; +} + +/* Review probe, recreated: every engine-built HASH / SORT / BLOOM / PART + * over every admitted type (nulls, both zeros, NaN payloads), SYM at + * W8 / W16 / W32 and STR with "" validates. */ +static test_result_t test_view_engine_matrix(void) { + static const int8_t types[10] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, + RAY_DATE, RAY_TIME, RAY_TIMESTAMP }; + static const int64_t lens[5] = { 0, 1, 7, 100, 3000 }; + ray_t* (*kinds[4])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, + ray_index_attach_bloom, ray_index_attach_part }; + int built = 0; + ray_enc_idx_view_t iv; + for (int ti = 0; ti < 10; ti++) + for (int li = 0; li < 5; li++) + for (int k = 0; k < 4; k++) { + ray_t* v = with_index(mx_col(types[ti], lens[li], k == 3), kinds[k]); + if (!v) continue; + size_t n; ray_t* err; uint8_t* b = ix_region(v, k == 3 || k == 0 ? "ts" : NULL, 2, &n, &err); + TEST_ASSERT_FMT(b != NULL, "type %d len %lld kind %d: not written", types[ti], (long long)lens[li], k); + ix_view(b, n, v, &iv); + PARSE_SAME(v, &iv, k == 3 || k == 0 ? "ts" : NULL, "type %d len %lld kind %d", types[ti], (long long)lens[li], k); + free(b); ray_release(v); built++; + } + static const uint8_t ws[3] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32 }; + static const int64_t base[3] = { 0, 300, 70000 }; + for (int w = 0; w < 3; w++) + for (int li = 1; li < 5; li++) + for (int k = 0; k < 2; k++) { + int64_t n = lens[li]; + ray_t* v = ray_sym_vec_new(ws[w], n); + TEST_ASSERT_NOT_NULL(v); + v->len = n; + for (int64_t i = 0; i < n; i++) { + int64_t id = k ? base[w] + 1 + (i * 5) / n : (i % 11 == 3 ? 0 : base[w] + 1 + (i * 37) % 13); + ray_write_sym(ray_data(v), i, (uint64_t)id, RAY_SYM, ws[w]); + } + v = with_index(v, k ? ray_index_attach_part : ray_index_attach_hash); + TEST_ASSERT_FMT(v != NULL, "SYM width %d len %lld kind %d: not built", w, (long long)n, k); + size_t rn; ray_t* err; uint8_t* b = ix_region(v, "ts", 2, &rn, &err); + TEST_ASSERT_NOT_NULL(b); + ix_view(b, rn, v, &iv); + PARSE_SAME(v, &iv, "ts", "SYM width %d len %lld kind %d", w, (long long)n, k); + free(b); ray_release(v); built++; + } + for (int li = 0; li < 5; li++) { + static const char* const strs[5] = { "", "a", "bb", "", "ccc" }; + ray_t* v = ray_vec_new(RAY_STR, lens[li] > 0 ? lens[li] : 1); + for (int64_t i = 0; i < lens[li]; i++) v = ray_str_vec_append(v, strs[(i * 7) % 5], strlen(strs[(i * 7) % 5])); + v = with_index(v, ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(v); + size_t n; ray_t* err; uint8_t* b = ix_region(v, NULL, 0, &n, &err); + TEST_ASSERT_NOT_NULL(b); + ix_view(b, n, v, &iv); + PARSE_SAME(v, &iv, NULL, "STR len %lld", (long long)lens[li]); + free(b); ray_release(v); built++; + } + /* A HASH carried through concat (ray_index_carry_append) over several + * appends of new keys, its bucket table regrown past 8: written, then + * validated and parsed like a built one. */ + for (int t = 0; t < 3; t++) { + ray_t* v = NULL; + int64_t rows = 0; + for (int step = 0; step < 5; step++) { + int64_t m = step ? 3 + step : 6; /* rows: 6, then 4, 5, 6, 7 new keys */ + ray_t* nv; + if (t == 2) { + nv = ray_vec_new(RAY_STR, rows + m); + for (int64_t i = 0; i < rows + m; i++) { + char sb[16]; int sl = snprintf(sb, sizeof sb, "k%lld", (long long)(i < 6 ? i % 3 : i)); + nv = ray_str_vec_append(nv, sb, (size_t)sl); + } + } else { + nv = t == 0 ? ray_vec_new(RAY_I64, rows + m) : ray_sym_vec_new(RAY_SYM_W16, rows + m); + nv->len = rows + m; + for (int64_t i = 0; i < rows + m; i++) { + int64_t k = i < 6 ? i % 3 : i; /* the first 6 rows repeat; appends are new */ + if (t == 0) ((int64_t*)ray_data(nv))[i] = k * 1000 - 7; + else ray_write_sym(ray_data(nv), i, (uint64_t)(k + 1), RAY_SYM, RAY_SYM_W16); + } + } + if (!step) { + v = with_index(nv, ray_index_attach_hash); + } else { + ray_index_carry_append(v, nv); + ray_release(v); + v = nv; + } + TEST_ASSERT_FMT(v && ray_index_kind(v) == RAY_IDX_HASH, "carried HASH type %d step %d: no index", t, step); + rows += m; + } + TEST_ASSERT_TRUE(ray_index_payload(v->index)->u.hash.mask + 1 >= 32); + size_t n; ray_t* err; uint8_t* b = ix_region(v, t == 2 ? NULL : "ts", 2, &n, &err); + TEST_ASSERT_FMT(b != NULL, "carried HASH type %d: not written", t); + ix_view(b, n, v, &iv); + PARSE_SAME(v, &iv, t == 2 ? NULL : "ts", "carried HASH type %d", t); + free(b); ray_release(v); built++; + } + TEST_ASSERT_FMT(built >= 150, "only %d indexes built", built); + PASS(); +} + +/* ===== Parse round trips ===== */ + +/* Region of v's index -> validate -> parse -> attach to a fresh copy of v. */ +static ray_t* ix_roundtrip(ray_t* v, const char* name, uint32_t nlen) { + size_t n; ray_t* err; uint8_t* b = ix_region(v, name, nlen, &n, &err); + if (!b) { if (err) ray_error_free(err); return NULL; } + ray_enc_idx_view_t iv; + ray_t* fresh = ray_vec_new(v->type, v->len); + if (v->type == RAY_SYM) { ray_release(fresh); fresh = ray_sym_vec_new(v->attrs & RAY_SYM_W_MASK, v->len); ray_sym_vec_adopt_domain(fresh, v); } + fresh->len = v->len; + memcpy(ray_data(fresh), ray_data(v), (size_t)v->len * ray_sym_elem_size(v->type, v->attrs)); + ix_view(b, n, v, &iv); + ray_t* root = NULL; + ray_t* pe = ray_enc_index_parse(&iv, fresh, &root); + free(b); + if (pe) { ray_error_free(pe); ray_release(fresh); return NULL; } + ray_t* r = ray_index_attach_persisted(&fresh, root); + if (!r || RAY_IS_ERR(r)) { if (r) ray_error_free(r); ray_release(fresh); return NULL; } + return r; +} + +static test_result_t test_parse_hash_probes(void) { + int64_t d[5000]; + for (int i = 0; i < 5000; i++) d[i] = (i * 7919) % 1499; + ray_t* v = with_index(i64_vec(d, 5000), ray_index_attach_hash); + ray_t* p = ix_roundtrip(v, NULL, 0); + TEST_ASSERT_NOT_NULL(p); + ray_index_t* a = ray_index_payload(v->index); + ray_index_t* b = ray_index_payload(p->index); + TEST_ASSERT_EQ_I(b->kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_U(b->u.hash.mask, a->u.hash.mask); + TEST_ASSERT_EQ_I(b->u.hash.n_groups, a->u.hash.n_groups); + TEST_ASSERT_EQ_I(b->u.hash.order_sym, -1); + TEST_ASSERT_FALSE(b->markers & RAY_MARK_MMAP); + for (int64_t key = 0; key < 1499; key += 37) { + ray_t* sa = ray_index_hash_eq_rowsel(v, key); + ray_t* sb = ray_index_hash_eq_rowsel(p, key); + TEST_ASSERT_TRUE(sa && sb); + TEST_ASSERT_EQ_I(ray_rowsel_meta(sb)->total_pass, ray_rowsel_meta(sa)->total_pass); + ray_rowsel_release(sa); ray_rowsel_release(sb); + } + ray_release(p); ray_release(v); + PASS(); +} + +/* PART with an order name: the name interns to the same id; SYM keys keep + * the column's domain. */ +static test_result_t test_parse_part_order_sym(void) { + int64_t d[8] = { 1, 1, 1, 4, 4, 9, 9, 9 }; + ray_t* v = with_index(i64_vec(d, 8), ray_index_attach_part); + ray_t* p = ix_roundtrip(v, "ordcol_p4", 9); + TEST_ASSERT_NOT_NULL(p); + TEST_ASSERT_EQ_I(ray_index_payload(p->index)->u.part.order_sym, ray_sym_intern("ordcol_p4", 9)); + ray_release(p); ray_release(v); + for (int i = 0; i < 20; i++) { char b[8]; int n = snprintf(b, sizeof b, "q%d", i); (void)ray_sym_intern(b, (size_t)n); } + ray_t* s = ray_sym_vec_new(RAY_SYM_W8, 6); + s->len = 6; + uint8_t ids[6] = { 3, 3, 7, 7, 7, 5 }; + memcpy(ray_data(s), ids, 6); + ray_t* sp = with_index(s, ray_index_attach_part); + TEST_ASSERT_NOT_NULL(sp); + ray_t* q = ix_roundtrip(sp, NULL, 0); + TEST_ASSERT_NOT_NULL(q); + ray_t* keys = ray_index_payload(q->index)->u.part.keys; + TEST_ASSERT_EQ_I(keys->type, RAY_SYM); + TEST_ASSERT_EQ_I(keys->len, 3); + TEST_ASSERT_EQ_I(ray_read_sym(ray_data(keys), 1, RAY_SYM, keys->attrs), 7); + TEST_ASSERT_TRUE(ray_sym_vec_domain(keys) == ray_sym_vec_domain(q)); + ray_release(q); ray_release(sp); + /* a column over a private domain: the keys resolve over that domain */ + ray_sym_domain_t* dom = ray_sym_domain_new(); + TEST_ASSERT_NOT_NULL(dom); + static const char* const words[4] = { "pd_zero", "pd_one", "pd_two", "pd_three" }; + int64_t pos[4]; + for (int i = 0; i < 4; i++) pos[i] = ray_sym_domain_intern(dom, words[i], strlen(words[i])); + ray_t* f = ray_sym_vec_new(RAY_SYM_W8, 5); + f->len = 5; + uint8_t fid[5] = { (uint8_t)pos[2], (uint8_t)pos[2], (uint8_t)pos[1], (uint8_t)pos[3], (uint8_t)pos[3] }; + memcpy(ray_data(f), fid, 5); + f->sym_domain = dom; /* the vector holds the reference */ + ray_t* fp = with_index(f, ray_index_attach_part); + TEST_ASSERT_NOT_NULL(fp); + ray_t* fq = ix_roundtrip(fp, NULL, 0); + TEST_ASSERT_NOT_NULL(fq); + keys = ray_index_payload(fq->index)->u.part.keys; + TEST_ASSERT_TRUE(ray_sym_vec_domain(keys) == dom); + TEST_ASSERT_TRUE(ray_sym_vec_domain(keys) != ray_sym_runtime_domain()); + TEST_ASSERT_EQ_I(keys->len, 3); + ray_t* w1 = ray_sym_domain_str(ray_sym_vec_domain(keys), ray_read_sym(ray_data(keys), 1, RAY_SYM, keys->attrs)); + TEST_ASSERT_TRUE(w1 && ray_str_len(w1) == 6 && memcmp(ray_str_ptr(w1), "pd_one", 6) == 0); + ray_release(fq); ray_release(fp); + PASS(); +} + +/* Every allocation of the parse failing in turn: oom, no root, and + * nothing left allocated (the error path releases what it set). */ +static test_result_t ix_parse_oom_run(ray_t* v, const ray_enc_idx_view_t* iv) { + int fails = 0; + for (int64_t nth = 1; ; nth++) { + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + ray_enccol_test_fail_alloc(nth); + ray_t* root = (ray_t*)1; + ray_t* e = ray_enc_index_parse(iv, v, &root); + ray_enccol_test_fail_alloc(0); + if (!e) { + bool got = root != NULL && root != (ray_t*)1; + if (got) ray_release(root); + ray_mem_stats(&m1); + TEST_ASSERT_TRUE(got); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + break; + } + bool oom = strcmp(ray_err_code(e), "oom") == 0; + ray_error_free(e); + if (root && root != (ray_t*)1) { ray_release(root); FAILF("allocation %lld failing: a root with the error", (long long)nth); } + TEST_ASSERT_FMT(oom, "allocation %lld failing: not oom", (long long)nth); + TEST_ASSERT_NULL(root); + ray_mem_stats(&m1); + TEST_ASSERT_FMT(m1.bytes_allocated == m0.bytes_allocated, "allocation %lld failing leaks %lld bytes", + (long long)nth, (long long)(m1.bytes_allocated - m0.bytes_allocated)); + fails++; + TEST_ASSERT_TRUE(nth < 16); + } + TEST_ASSERT_TRUE(fails >= 2); /* the root and at least one child */ + PASS(); +} +static test_result_t ix_parse_oom(ray_t* v, const char* name) { + size_t n; ray_t* err; uint8_t* b = ix_region(v, name, name ? (uint32_t)strlen(name) : 0, &n, &err); + if (err) ray_error_free(err); + TEST_ASSERT_NOT_NULL(b); + ray_enc_idx_view_t iv; + ix_view(b, n, v, &iv); + if (name) (void)ray_sym_intern(name, strlen(name)); /* interned before the baseline */ + test_result_t r = ix_parse_oom_run(v, &iv); + free(b); + return r; +} +#define PARSE_OOM(v, name) do { test_result_t r_ = ix_parse_oom((v), (name)); \ + if (r_.status != TEST_PASS) return r_; } while (0) + +static test_result_t test_parse_oom_frees(void) { + int64_t d[40]; + for (int i = 0; i < 40; i++) d[i] = (i * 7) % 11; + ray_t* (*kinds[3])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, ray_index_attach_bloom }; + for (int k = 0; k < 3; k++) { + ray_t* v = with_index(i64_vec(d, 40), kinds[k]); + TEST_ASSERT_NOT_NULL(v); + PARSE_OOM(v, k == 0 ? "ts" : NULL); + ray_release(v); + } + int64_t pd[6] = { 1, 1, 3, 3, 3, 8 }; + ray_t* p = with_index(i64_vec(pd, 6), ray_index_attach_part); + TEST_ASSERT_NOT_NULL(p); + PARSE_OOM(p, "ts"); + ray_release(p); + ray_t* s = ray_sym_vec_new(RAY_SYM_W16, 5); + s->len = 5; + uint16_t ids[5] = { 4, 4, 9, 2, 2 }; + memcpy(ray_data(s), ids, sizeof ids); + ray_t* sp = with_index(s, ray_index_attach_part); + TEST_ASSERT_NOT_NULL(sp); + PARSE_OOM(sp, "ts"); + ray_release(sp); + PASS(); +} + +/* ---- the column writer emits the region (Task 5) ---- */ + +/* The region of a written column file and its enc header, or NULL when the + * file has none; *fn is the file's size (0 when unreadable), which callers + * check against end_off. */ +static uint8_t* ix_file_region(const char* path, size_t* rn, ray_enc_hdr_t* eh, uint64_t* fn) { + size_t n = 0; uint8_t* b = ix_slurp(path, &n); + memset(eh, 0, sizeof *eh); + *fn = b ? n : 0; + if (!b) return NULL; + if (n < 96) { free(b); return NULL; } + memcpy(eh, b + 32, 64); + if (!eh->index_off || eh->index_off >= n) { free(b); return NULL; } + *rn = n - eh->index_off; + uint8_t* r = malloc(*rn); + memcpy(r, b + eh->index_off, *rn); + free(b); + return r; +} + +/* A HASH-indexed column is written as generation 2 with its region. */ +static test_result_t test_file_has_region(void) { + int64_t d[3000]; + for (int i = 0; i < 3000; i++) d[i] = (i * 13) % 211; + ray_t* v = with_index(i64_vec(d, 3000), ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(v); + const char* p = ray_test_tmp(IDX_TMP "/h"); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + TEST_ASSERT_EQ_U(ray_col_file_gen(p), 2); + size_t rn = 0; ray_enc_hdr_t eh; + uint64_t fn = 0; + uint8_t* r = ix_file_region(p, &rn, &eh, &fn); + TEST_ASSERT_TRUE(fn > 0 && eh.end_off == fn); /* the header covers the whole file */ + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_U(eh.index_off % 32, 0); + size_t n2 = 0; ray_t* err = NULL; uint8_t* direct = ix_region(v, NULL, 0, &n2, &err); + bool same = direct && n2 == rn && memcmp(direct, r, rn) == 0; + free(direct); free(r); ray_release(v); + TEST_ASSERT_FMT(same, "the file's region differs from the region writer's (%zu vs %zu bytes)", rn, n2); + PASS(); +} + +/* UNIQUE is a header flag, never in the region; a stale root writes none. */ +static test_result_t test_unique_and_stale(void) { + int64_t d[100]; for (int i = 0; i < 100; i++) d[i] = i; + ray_t* v = with_index(i64_vec(d, 100), ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(v); + ray_index_payload(v->index)->markers |= RAY_MARK_UNIQUE; + size_t rn = 0, dn = 0; ray_enc_hdr_t eh; + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(IDX_TMP "/u"), 2), RAY_OK); + uint64_t fn = 0; + uint8_t* r = ix_file_region(ray_test_tmp(IDX_TMP "/u"), &rn, &eh, &fn); + TEST_ASSERT_TRUE(fn > 0 && eh.end_off == fn); /* the header covers the whole file */ + ray_t* err = NULL; uint8_t* direct = ix_region(v, NULL, 0, &dn, &err); /* markers are not on the wire */ + bool same = r && direct && rn == dn && memcmp(r, direct, rn) == 0; + free(r); free(direct); + TEST_ASSERT_TRUE(same); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_I(eh.col_flags, RAY_ENC_FLAG_UNIQUE); + ray_index_payload(v->index)->built_for_len = 99; /* stale */ + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(IDX_TMP "/s"), 2), RAY_OK); + r = ix_file_region(ray_test_tmp(IDX_TMP "/s"), &rn, &eh, &fn); + TEST_ASSERT_TRUE(fn > 0 && eh.end_off == fn); /* the header covers the whole file */ + ray_index_payload(v->index)->built_for_len = 100; + ray_release(v); + TEST_ASSERT_NULL(r); + TEST_ASSERT_EQ_U(ray_col_file_gen(ray_test_tmp(IDX_TMP "/s")), 2); + TEST_ASSERT_EQ_I(eh.index_kind, 0); + TEST_ASSERT_EQ_I(eh.col_flags, 0); + PASS(); +} + +/* Spec "Writing the index": a child of a type the slot does not allow fails + * the SAVE with nyi naming the kind, the message reaches the caller's error + * slot with the "column %s:" prefix, and nothing is published or left. */ +static test_result_t test_save_nyi_names_kind(void) { + int64_t d[3] = { 1, 2, 3 }; + ray_t* v = with_index(i64_vec(d, 3), ray_index_attach_part); + TEST_ASSERT_NOT_NULL(v); + ray_index_t* ix = ray_index_payload(v->index); + ray_t* keys = ix->u.part.keys; + ray_t* fake = ray_vec_new(RAY_STR, 3); + for (int i = 0; i < 3; i++) fake = ray_str_vec_append(fake, "k", 1); + ix->u.part.keys = fake; + const char* p = ray_test_tmp(IDX_TMP "/nyi"); + ray_error_clear(); + ray_err_t e = ray_col_save_gen(v, p, 2); + const char* m = ray_error_msg(); + char msg[256]; snprintf(msg, sizeof msg, "%s", m ? m : ""); + ix->u.part.keys = keys; + ray_release(fake); ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_ERR_NYI); + TEST_ASSERT_FMT(strstr(msg, "PART") != NULL, "message: %s", msg); + char want[300]; snprintf(want, sizeof want, "column %s: index region:", p); + TEST_ASSERT_FMT(strncmp(msg, want, strlen(want)) == 0, "message: %s", msg); + FILE* f = fopen(p, "rb"); TEST_ASSERT_NULL(f); + f = fopen(ray_test_tmp(IDX_TMP "/nyi.tmp"), "rb"); TEST_ASSERT_NULL(f); + PASS(); +} + +/* An override kind never re-labels a region root: the file records the + * override and carries no region. */ +static test_result_t test_save_override_kind(void) { + int64_t d[3000]; + for (int i = 0; i < 3000; i++) d[i] = (i * 13) % 211; + ray_t* v = with_index(i64_vec(d, 3000), ray_index_attach_sort); + TEST_ASSERT_NOT_NULL(v); + ray_col_write_t w; memset(&w, 0, sizeof w); + ray_t* err = ray_col_src_bind(v, &w.src); + TEST_ASSERT_NULL(err); + w.gen = 2; w.index_kind = RAY_IDX_CHUNK_ZONE; + ray_err_t e = ray_col_save_ctx(&w, ray_test_tmp(IDX_TMP "/o")); + ray_col_src_release(&w.src); + size_t rn; ray_enc_hdr_t eh; + uint64_t fn = 0; + uint8_t* r = ix_file_region(ray_test_tmp(IDX_TMP "/o"), &rn, &eh, &fn); + TEST_ASSERT_TRUE(fn > 0 && eh.end_off == fn); /* the header covers the whole file */ + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_OK); + TEST_ASSERT_NULL(r); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_CHUNK_ZONE); + PASS(); +} + +/* Golden index regions (spec "Golden fixtures": one per persisted kind). + * Compile with ENC_GOLDEN_KEEP to regenerate them into the fixture + * directory (relative to the repository root, where the tests run). */ +#define IDX_GOLDEN_DIR "test/data/enc" +#ifdef ENC_GOLDEN_KEEP +# define IDX_GOLDEN_OUT IDX_GOLDEN_DIR +#else +# define IDX_GOLDEN_OUT ray_test_tmp(IDX_TMP "/golden_emit") +#endif +static const char* const g_idx_golden[] = { + "idx_hash_i64", "idx_hash_str", "idx_hash_sym", "idx_sort_i32", "idx_bloom_i64", + "idx_part_i64", "idx_part_f64", "idx_part_sym", "idx_part_order", "idx_hash_unique", + "idx_dict_str", NULL, +}; + +/* SYM fixtures go through the column writer directly, like P1's golden_sym, + * so the saved count does not depend on the process symbol table. */ +static ray_err_t idx_golden_sym(const char* dir, const char* name, uint8_t kind) { + ray_t* v = ray_sym_vec_new(RAY_SYM_W8, 600); + if (!v || RAY_IS_ERR(v)) return RAY_ERR_OOM; + v->len = 600; + uint8_t* ids = (uint8_t*)ray_data(v); + for (int k = 0; k < 600; k++) + ids[k] = kind == RAY_IDX_PART ? (uint8_t)(1 + k / 100) : (uint8_t)(1 + (k * 7) % 40); + ray_t* iv = with_index(v, kind == RAY_IDX_PART ? ray_index_attach_part : ray_index_attach_hash); + if (!iv) return RAY_ERR_TYPE; + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", dir, name); + FILE* f = fopen(path, "wb+"); + if (!f) { ray_release(iv); return RAY_ERR_IO; } + ray_encw_t w; + ray_err_t e = ray_encw_begin(&w, f, RAY_SYM, RAY_SYM_W8, 600, 64, 0, 0); + ray_enc_idx_src_t s = { iv->index, RAY_SYM, RAY_SYM_W8, 600, NULL, 0 }; + if (e == RAY_OK) { ray_encw_set_index(&w, &s); e = ray_encw_chunk(&w, ray_data(iv), NULL, 600); } + if (e == RAY_OK) e = ray_encw_finish(&w); + ray_encw_free(&w); fclose(f); ray_release(iv); + return e; +} + +static const char* idx_golden_emit(const char* dir) { + static char why[256]; + (void)ray_test_mkdir_p(dir); + char path[512]; + #define GOLD(name, vec) do { ray_t* gv_ = (vec); snprintf(path, sizeof path, "%s/%s.bin", dir, name); \ + ray_err_t ge_ = gv_ ? ray_col_save_gen(gv_, path, 2) : RAY_ERR_TYPE; \ + if (gv_) ray_release(gv_); \ + if (ge_ != RAY_OK) { ray_encw_test_force(-1); snprintf(why, sizeof why, "%s: %d", name, (int)ge_); return why; } } while (0) + int64_t a[1000]; for (int i = 0; i < 1000; i++) a[i] = (i * 7919) % 317; + GOLD("idx_hash_i64", with_index(i64_vec(a, 1000), ray_index_attach_hash)); + ray_t* s = ray_vec_new(RAY_STR, 300); + for (int i = 0; i < 300; i++) { char b[32]; int n = snprintf(b, sizeof b, "string key number %d", i % 23); s = ray_str_vec_append(s, b, (size_t)n); } + ray_encw_test_force(RAY_ENC_RAW); /* P6: keep the P4 fixture's column bytes */ + GOLD("idx_hash_str", with_index(s, ray_index_attach_hash)); + ray_encw_test_force(-1); + int32_t c[700]; for (int i = 0; i < 700; i++) c[i] = (int32_t)((i * 31) % 499) - 250; + GOLD("idx_sort_i32", with_index(ray_vec_from_raw(RAY_I32, c, 700), ray_index_attach_sort)); + GOLD("idx_bloom_i64", with_index(i64_vec(a, 1000), ray_index_attach_bloom)); + int64_t p[1000]; for (int i = 0; i < 1000; i++) p[i] = i / 128 * 3; + GOLD("idx_part_i64", with_index(i64_vec(p, 1000), ray_index_attach_part)); + double f[8] = { -2.5, -0.0, 0.0, 0.0, 1.5, 1.5, 3.0, 3.0 }; + ray_encw_test_force(RAY_ENC_RAW); /* P5: keep the P4 fixture's column bytes */ + GOLD("idx_part_f64", with_index(ray_vec_from_raw(RAY_F64, f, 8), ray_index_attach_part)); + ray_encw_test_force(-1); + ray_t* o = with_index(i64_vec(p, 1000), ray_index_attach_part); + if (o) ray_index_payload(o->index)->u.part.order_sym = ray_sym_intern("ts", 2); + GOLD("idx_part_order", o); + ray_t* u = with_index(i64_vec(a, 1000), ray_index_attach_hash); + if (u) ray_index_payload(u->index)->markers |= RAY_MARK_UNIQUE; + GOLD("idx_hash_unique", u); + #undef GOLD + if (idx_golden_sym(dir, "idx_hash_sym", RAY_IDX_HASH) != RAY_OK) return "idx_hash_sym"; + if (idx_golden_sym(dir, "idx_part_sym", RAY_IDX_PART) != RAY_OK) return "idx_part_sym"; + { /* DICT (P6b): 300 rows through the column writer; the 65536-row floor + * is the writers' decision, not a validity rule (D14) */ + ray_t* ds = ray_vec_new(RAY_STR, 300); + for (int i = 0; i < 300 && ds && !RAY_IS_ERR(ds); i++) { + char b[32]; int n = snprintf(b, sizeof b, "dict entry %d", (i * 7) % 23); + ds = ray_str_vec_append(ds, b, (size_t)n); + } + if (!ds || RAY_IS_ERR(ds)) return "idx_dict_str"; + snprintf(path, sizeof path, "%s/idx_dict_str.bin", dir); + FILE* f = fopen(path, "wb+"); + ray_encw_t w; memset(&w, 0, sizeof w); + ray_encw_test_force_str(RAY_ENC_RAW); /* the subject is the region */ + ray_err_t e = f ? ray_encw_begin(&w, f, RAY_STR, 0, 300, 0, RAY_IDX_DICT, 0) : RAY_ERR_IO; + const ray_t* own = ds; + const char* pool = own->str_pool ? (const char*)ray_data(own->str_pool) : NULL; + if (e == RAY_OK) e = ray_encw_chunk(&w, ray_data(ds), pool, 300); + if (e == RAY_OK) e = ray_encw_finish(&w); + ray_encw_test_force_str(-1); + if (f) { ray_encw_free(&w); fclose(f); } + ray_release(ds); + if (e != RAY_OK) return "idx_dict_str"; + } + return NULL; +} + +static test_result_t test_idx_golden_emit(void) { + const char* why = idx_golden_emit(IDX_GOLDEN_OUT); + TEST_ASSERT_FMT(why == NULL, "%s", why); + PASS(); +} + +static test_result_t test_idx_golden_match(void) { + const char* why = idx_golden_emit(ray_test_tmp(IDX_TMP "/golden")); + TEST_ASSERT_FMT(why == NULL, "%s", why); + for (int i = 0; g_idx_golden[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, "%s/%s.bin", IDX_GOLDEN_DIR, g_idx_golden[i]); + snprintf(b, sizeof b, "%s/golden/%s.bin", ray_test_tmp(IDX_TMP), g_idx_golden[i]); + size_t na = 0, nb = 0; uint8_t* pa = ix_slurp(a, &na); uint8_t* pb = ix_slurp(b, &nb); + bool have = pa != NULL; + bool same = pa && pb && na == nb && memcmp(pa, pb, na) == 0; + free(pa); free(pb); + TEST_ASSERT_FMT(have, "missing fixture %s", a); + TEST_ASSERT_FMT(same, "%s differs from its fixture", g_idx_golden[i]); + } + PASS(); +} + +/* ---- materialization attaches the parsed index (Task 6) ---- */ + +static ray_t* ix_hash_col(int64_t n) { + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = (i * 2654435761u) % 10007; + return with_index(v, ray_index_attach_hash); +} +/* The enc header of a written column file. */ +static ray_enc_hdr_t ix_hdr(const char* path) { + ray_enc_hdr_t eh; memset(&eh, 0, sizeof eh); + size_t n; uint8_t* b = ix_slurp(path, &n); + if (b && n >= 96) memcpy(&eh, b + 32, 64); + free(b); + return eh; +} + +/* Spec "Golden fixtures": the reader decodes them. Each committed + * test/data/enc/idx_*.bin validates and parses from its own header (type, + * attrs, len, SYM bound) and loads as a column whose materialization + * attaches the same index: kind, rows, order name, UNIQUE. */ +static test_result_t test_idx_golden_read(void) { + static const struct { const char* name; uint8_t kind; const char* order; bool unique; } fx[] = { + { "idx_hash_i64", RAY_IDX_HASH, NULL, false }, { "idx_hash_str", RAY_IDX_HASH, NULL, false }, + { "idx_hash_sym", RAY_IDX_HASH, NULL, false }, { "idx_sort_i32", RAY_IDX_SORT, NULL, false }, + { "idx_bloom_i64", RAY_IDX_BLOOM, NULL, false }, { "idx_part_i64", RAY_IDX_PART, NULL, false }, + { "idx_part_f64", RAY_IDX_PART, NULL, false }, { "idx_part_sym", RAY_IDX_PART, NULL, false }, + { "idx_part_order", RAY_IDX_PART, "ts", false }, { "idx_hash_unique", RAY_IDX_HASH, NULL, true }, + { "idx_dict_str", RAY_IDX_DICT, NULL, false }, + }; + size_t nfx = sizeof fx / sizeof fx[0]; + /* the SYM fixtures record 64 symbols: a process with fewer refuses them */ + for (int i = 0; i < 64; i++) { char nb[8]; int nn = snprintf(nb, sizeof nb, "g%d", i); (void)ray_sym_intern(nb, (size_t)nn); } + for (int i = 0; g_idx_golden[i]; i++) TEST_ASSERT_TRUE((size_t)i < nfx && strcmp(fx[i].name, g_idx_golden[i]) == 0); + for (size_t i = 0; i < nfx; i++) { + char path[512]; snprintf(path, sizeof path, "%s/%s.bin", IDX_GOLDEN_DIR, fx[i].name); + /* the column: loads, materializes, attaches */ + ray_t* c = ray_col_mmap(path); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL, "%s: load", fx[i].name); + ray_error_clear(); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_FMT(m && !RAY_IS_ERR(m), "%s: %s", fx[i].name, ray_error_msg() ? ray_error_msg() : "?"); + TEST_ASSERT_FMT(ray_index_kind(m) == fx[i].kind, "%s: attached kind %d", fx[i].name, (int)ray_index_kind(m)); + ray_index_t* aix = ray_index_payload(m->index); + TEST_ASSERT_EQ_I(aix->built_for_len, m->len); + TEST_ASSERT_FALSE(aix->markers & RAY_MARK_MMAP); + TEST_ASSERT_FMT(((aix->markers & RAY_MARK_UNIQUE) != 0) == fx[i].unique, "%s: UNIQUE", fx[i].name); + /* the region alone, from the file's own header */ + size_t n = 0; uint8_t* b = ix_slurp(path, &n); + TEST_ASSERT_TRUE(b && n >= 96); + ray_t h; memcpy(&h, b, 32); + uint32_t saved; memcpy(&saved, b + offsetof(ray_t, rc), 4); + ray_enc_hdr_t eh; memcpy(&eh, b + 32, 64); + TEST_ASSERT_TRUE(eh.end_off == n && eh.index_off > 0 && eh.index_off < n); + TEST_ASSERT_EQ_I(eh.index_kind, fx[i].kind); + TEST_ASSERT_EQ_I(h.type, m->type); + TEST_ASSERT_EQ_I(h.len, m->len); + if (fx[i].kind == RAY_IDX_DICT) { /* its own reader, not ray_enc_index_view */ + const uint64_t rsz = eh.end_off - eh.index_off; + uint8_t* rb = aligned_alloc(32, (size_t)((rsz + 31) & ~(uint64_t)31)); + TEST_ASSERT_NOT_NULL(rb); + memcpy(rb, b + eh.index_off, (size_t)rsz); + free(b); + ray_enc_dict_view_t dv; + ray_enc_dict_parse(rb, &dv); + const int64_t nd = dv.n_distinct, dl = dv.len; + free(rb); + TEST_ASSERT_EQ_I(dl, 300); + TEST_ASSERT_EQ_I(nd, 23); + TEST_ASSERT_EQ_I(aix->u.dict.n_distinct, 23); + ray_release(c); + continue; + } + ray_enc_idx_view_t iv; ray_t* root = NULL; + ray_enc_index_view(b + eh.index_off, n - eh.index_off, eh.index_kind, h.type, h.attrs, h.len, &iv); + ray_t* e = ray_enc_index_parse(&iv, m, &root); + free(b); + TEST_ASSERT_FMT(e == NULL && root, "%s: parse", fx[i].name); + ray_index_t* pix = ray_index_payload(root); + bool ok = pix->kind == fx[i].kind && pix->built_for_len == h.len && pix->parent_type == h.type; + int64_t osym = pix->kind == RAY_IDX_PART ? pix->u.part.order_sym + : pix->kind == RAY_IDX_HASH ? pix->u.hash.order_sym : -1; + int64_t asym = aix->kind == RAY_IDX_PART ? aix->u.part.order_sym + : aix->kind == RAY_IDX_HASH ? aix->u.hash.order_sym : -1; + ray_release(root); + TEST_ASSERT_FMT(ok, "%s: parsed root", fx[i].name); + TEST_ASSERT_EQ_I(osym, asym); + if (fx[i].order) { + TEST_ASSERT_TRUE(osym >= 0); + ray_t* nm = ray_sym_str(osym); + TEST_ASSERT_TRUE(nm && !RAY_IS_ERR(nm) && ray_str_len(nm) == strlen(fx[i].order) && + memcmp(ray_str_ptr(nm), fx[i].order, ray_str_len(nm)) == 0); + } else { + TEST_ASSERT_FMT(osym < 0, "%s: order_sym %lld", fx[i].name, (long long)osym); + } + ray_release(c); + } + PASS(); +} + +static test_result_t test_materialize_attaches(void) { + const char* p = ray_test_tmp(IDX_TMP "/m"); + ray_t* v = ix_hash_col(70000); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + ray_enc_counters_reset(); + ray_t* m = ray_enccol_materialize(c); /* borrowed */ + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); + ray_t* sa = ray_index_hash_eq_rowsel(v, 4242); + ray_t* sb = ray_index_hash_eq_rowsel(m, 4242); + TEST_ASSERT_TRUE(sa && sb && ray_rowsel_meta(sa)->total_pass == ray_rowsel_meta(sb)->total_pass); + ray_rowsel_release(sa); ray_rowsel_release(sb); + TEST_ASSERT_FALSE(ray_index_payload(m->index)->markers & RAY_MARK_MMAP); + TEST_ASSERT_FALSE(ray_index_payload(m->index)->markers & RAY_MARK_UNIQUE); + ray_release(c); ray_release(v); + PASS(); +} + +/* Every region kind round-trips through a file: the materialized column's + * index writes the same region as the source's (the wire is normalized), + * and SORT / PART / BLOOM probes agree. */ +static test_result_t test_materialize_all_kinds(void) { + ray_t* (*const kinds[])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, + ray_index_attach_bloom, ray_index_attach_part }; + const int want[] = { RAY_IDX_HASH, RAY_IDX_SORT, RAY_IDX_BLOOM, RAY_IDX_PART }; + static int64_t d[70000]; + for (int k = 0; k < 4; k++) { + for (int i = 0; i < 70000; i++) /* PART: ascending value-blocks */ + d[i] = want[k] == RAY_IDX_PART ? (i / 700) * 3 - 50 : (int64_t)((i * 2654435761u) % 10007) - 5000; + const char* p = ray_test_tmp(IDX_TMP "/k"); + ray_t* v = with_index(i64_vec(d, 70000), kinds[k]); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + TEST_ASSERT_EQ_I(ix_hdr(p).index_kind, want[k]); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_FMT(m && !RAY_IS_ERR(m), "kind %d: %s", want[k], ray_error_msg() ? ray_error_msg() : "?"); + TEST_ASSERT_EQ_I(ray_index_kind(m), want[k]); + TEST_ASSERT_FALSE(ray_index_payload(m->index)->markers & RAY_MARK_MMAP); + size_t na = 0, nb = 0; ray_t* ea = NULL; ray_t* eb = NULL; + uint8_t* ra = ix_region(v, NULL, 0, &na, &ea); + uint8_t* rb = ix_region(m, NULL, 0, &nb, &eb); + bool same = ra && rb && na == nb && memcmp(ra, rb, na) == 0; + free(ra); free(rb); + if (ea) ray_error_free(ea); + if (eb) ray_error_free(eb); + TEST_ASSERT_FMT(same, "kind %d: the materialized index differs from the source's", want[k]); + TEST_ASSERT_EQ_I(memcmp(ray_data(m), d, sizeof d), 0); + ray_release(c); ray_release(v); + } + PASS(); +} + +/* Carry: UNIQUE comes from col_flags and is added by the materializer + * after the parse (the parse leaves it to the caller). */ +static test_result_t test_materialize_unique(void) { + int64_t d[3000]; for (int i = 0; i < 3000; i++) d[i] = 3000 - i; + ray_t* v = with_index(i64_vec(d, 3000), ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(v); + ray_index_payload(v->index)->markers |= RAY_MARK_UNIQUE; + const char* p = ray_test_tmp(IDX_TMP "/uq"); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_enc_hdr_t eh = ix_hdr(p); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_I(eh.col_flags, RAY_ENC_FLAG_UNIQUE); + /* the parse alone leaves UNIQUE clear */ + size_t n; uint8_t* b = ix_slurp(p, &n); + TEST_ASSERT_NOT_NULL(b); + ray_enc_idx_view_t iv; ray_t* root = NULL; + ray_enc_index_view(b + eh.index_off, n - eh.index_off, RAY_IDX_HASH, RAY_I64, v->attrs, 3000, &iv); + ray_t* e = ray_enc_index_parse(&iv, v, &root); + free(b); + TEST_ASSERT_TRUE(!e && root); + TEST_ASSERT_FALSE(ray_index_payload(root)->markers & RAY_MARK_UNIQUE); + ray_release(root); + /* the materializer adds it */ + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); + TEST_ASSERT_TRUE(ray_index_payload(m->index)->markers & RAY_MARK_UNIQUE); + TEST_ASSERT_FALSE(ray_index_payload(m->index)->markers & RAY_MARK_MMAP); + ray_release(c); ray_release(v); + PASS(); +} + +/* Spec "Errors": injected allocation failure DURING INDEX PARSING is oom, + * not cached, then succeeds; allocator accounting returns to baseline. The + * parse-only hook fails exactly the parse step (P1's nth-allocation hook + * would trip at the start of materialization first). */ +static test_result_t test_parse_oom_retry(void) { + const char* p = ray_test_tmp(IDX_TMP "/o"); + ray_t* v = ix_hash_col(3000); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_mem_stats_t m0, m1, m2; ray_mem_stats(&m0); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + for (int i = 0; i < 2; i++) { + ray_enccol_test_fail_index_parse(true); + ray_error_clear(); + ray_t* r = ray_enccol_materialize(c); + ray_enccol_test_fail_index_parse(false); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "oom"); + TEST_ASSERT_TRUE(ray_error_msg() && strstr(ray_error_msg(), "index parse") != NULL); + TEST_ASSERT_TRUE(strstr(ray_error_msg(), p) != NULL); + ray_error_free(r); + /* The first attempt leaves caches owned by the column object (they + * go with it, checked below); the second allocates nothing that + * outlives it. */ + if (i == 0) ray_mem_stats(&m1); + else { ray_mem_stats(&m2); TEST_ASSERT_EQ_U(m2.bytes_allocated, m1.bytes_allocated); } + } + ray_t* r = ray_enccol_materialize(c); /* not cached: the retry succeeds */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && ray_index_kind(r) == RAY_IDX_HASH); + ray_release(c); + ray_mem_stats(&m2); + TEST_ASSERT_EQ_U(m2.bytes_allocated, m0.bytes_allocated); /* the column took everything with it */ + ray_release(v); + PASS(); +} + +/* Every allocation of a HASH materialization, the parse's included, fails + * in turn: each is oom, not cached, frees what it took; the parse's carry + * the path (the nth hook reaches the parse through + * ray_enccol_test_nth_alloc_fails). The path hook fails the column at + * "materialize", before the region. */ +static test_result_t test_materialize_oom_sweep(void) { + const char* p = ray_test_tmp(IDX_TMP "/sw"); + ray_t* v = ix_hash_col(3000); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_mem_stats_t base, m0, m1; ray_mem_stats(&base); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_test_fail_index_parse(true); /* warm the column's caches */ + ray_t* w = ray_enccol_materialize(c); + ray_enccol_test_fail_index_parse(false); + TEST_ASSERT_TRUE(w && RAY_IS_ERR(w)); + ray_error_free(w); + ray_mem_stats(&m0); + bool parse_hit = false, done = false; + for (int64_t nth = 1; nth <= 400 && !done; nth++) { + ray_enccol_test_fail_alloc(nth); + ray_error_clear(); + ray_t* r = ray_enccol_materialize(c); + ray_enccol_test_fail_alloc(0); + if (r && !RAY_IS_ERR(r)) { done = true; TEST_ASSERT_EQ_I(ray_index_kind(r), RAY_IDX_HASH); break; } + TEST_ASSERT_TRUE(r != NULL); + TEST_ASSERT_FMT(strcmp(ray_err_code(r), "oom") == 0, "nth %lld: %s", (long long)nth, ray_err_code(r)); + const char* msg = ray_error_msg(); + /* every parse failure names the column (the materializer's rewrap + * of the parse's own path-less errors) */ + if (msg && strstr(msg, "index parse")) + TEST_ASSERT_FMT(strstr(msg, p) != NULL, "nth %lld: %s names no path", (long long)nth, msg); + if (msg && strstr(msg, "index parse") && strstr(msg, p)) parse_hit = true; + ray_error_free(r); + ray_mem_stats(&m1); + TEST_ASSERT_FMT(m1.bytes_allocated == m0.bytes_allocated, "nth %lld leaked %lld bytes (%s)", (long long)nth, + (long long)m1.bytes_allocated - (long long)m0.bytes_allocated, msg ? msg : "?"); + } + TEST_ASSERT_TRUE(done); + TEST_ASSERT_TRUE(parse_hit); + ray_release(c); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, base.bytes_allocated); + /* the path hook fails this column's materialization as oom, not cached */ + c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_test_fail_path("/sw"); + ray_t* r = ray_enccol_materialize(c); + ray_enccol_test_fail_path(NULL); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "oom"); + ray_error_free(r); + r = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && ray_index_kind(r) == RAY_IDX_HASH); + ray_release(c); + ray_release(v); + PASS(); +} + +/* Spec "Lifetime": a column retained from ray_table_col survives the + * table, index included. */ +static test_result_t test_retained_index_outlives_table(void) { + const char* p = ray_test_tmp(IDX_TMP "/rt"); + ray_t* v = ix_hash_col(70000); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_t* sa = ray_index_hash_eq_rowsel(v, 4242); + TEST_ASSERT_NOT_NULL(sa); + int64_t want = ray_rowsel_meta(sa)->total_pass; + ray_rowsel_release(sa); + ray_release(v); + int64_t sym = ray_sym_intern("k", 1); + int64_t live = ray_enccol_test_live(); + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + ray_t* tbl = ray_table_add_col(ray_table_new(1), sym, c); + ray_release(c); + TEST_ASSERT_TRUE(tbl && !RAY_IS_ERR(tbl)); + ray_t* col = ray_table_col(tbl, sym); /* borrowed, materialized */ + TEST_ASSERT_TRUE(col && !RAY_IS_ERR(col)); + TEST_ASSERT_EQ_I(ray_index_kind(col), RAY_IDX_HASH); + ray_retain(col); + ray_release(tbl); /* the table, the column object, the mapping */ + TEST_ASSERT_EQ_I(ray_enccol_test_live(), live); + ray_t* sb = ray_index_hash_eq_rowsel(col, 4242); + TEST_ASSERT_NOT_NULL(sb); + TEST_ASSERT_EQ_I(ray_rowsel_meta(sb)->total_pass, want); + ray_rowsel_release(sb); + ray_release(col); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + PASS(); +} + +/* Spec "Concurrency": many threads on one fresh column, one materialization. */ +typedef struct { + ray_t* tbl; int64_t sym; ray_t* index; const char* code; int which; + ray_sem_t* ready; ray_sem_t* go; /* the start barrier */ + char msg[256]; +} ix_thr_t; +/* Even threads ask for the index, odd ones for the plain column (spec + * "Concurrency": ray_table_col_index and ray_table_col). */ +static void ix_thr(void* p) { + ix_thr_t* t = p; + ray_rc_sync = true; /* thread-local: shared objects, atomic counts */ + ray_sem_signal(t->ready); /* parked: every thread starts at once */ + ray_sem_wait(t->go); + ray_t* e; + if (t->which & 1) { + ray_t* col = ray_table_col(t->tbl, t->sym); + e = (col && RAY_IS_ERR(col)) ? col : NULL; + t->index = (col && !RAY_IS_ERR(col)) ? col->index : NULL; + } else { + e = ray_table_col_index(t->tbl, t->sym, &t->index); + } + t->code = e ? (ray_err_code(e) && strcmp(ray_err_code(e), "corrupt") == 0 ? "corrupt" : "other") : ""; + snprintf(t->msg, sizeof t->msg, "%s", e && ray_error_msg() ? ray_error_msg() : ""); /* thread-local */ + if (e) ray_error_free(e); + ray_heap_abandon(); +} +static test_result_t ix_concurrent(void) { + const char* p = ray_test_tmp(IDX_TMP "/t"); + ray_t* v = ix_hash_col(70000); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + int64_t sym = ray_sym_intern("k", 1); + ray_t* tbl = ray_table_add_col(ray_table_new(1), sym, c); + ray_release(c); + ray_enc_counters_reset(); + ray_thread_t th[8]; ix_thr_t a[8]; + ray_sem_t ready, go; + if (ray_sem_init(&ready, 0) != RAY_OK) { ray_release(tbl); ray_release(v); FAIL("sem"); } + if (ray_sem_init(&go, 0) != RAY_OK) { ray_sem_destroy(&ready); ray_release(tbl); ray_release(v); FAIL("sem"); } + int nt = 0; + while (nt < 8) { + a[nt] = (ix_thr_t){ .tbl = tbl, .sym = sym, .which = nt, .ready = &ready, .go = &go }; + if (ray_thread_create(&th[nt], ix_thr, &a[nt]) != RAY_OK) break; + nt++; + } + for (int i = 0; i < nt; i++) ray_sem_wait(&ready); /* every thread parked before any starts */ + for (int i = 0; i < nt; i++) ray_sem_signal(&go); + for (int i = 0; i < nt; i++) ray_thread_join(th[i]); + ray_sem_destroy(&ready); ray_sem_destroy(&go); + if (nt < 8) { ray_release(tbl); ray_release(v); FAIL("thread create"); } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + for (int i = 0; i < 8; i++) { + TEST_ASSERT_STR_EQ(a[i].code, ""); + TEST_ASSERT_TRUE(a[i].index == a[0].index && a[i].index != NULL); + } + ray_release(tbl); ray_release(v); + PASS(); +} +static test_result_t test_concurrent_index(void) { + return ix_concurrent(); +} + + +/* ---- generation-2 queries take the persisted index (Task 6b) ---- */ + +static ray_runtime_t* g_ixrt; +static void ixr_setup(void) { g_ixrt = ray_runtime_create(0, NULL); (void)ray_test_rm_rf(ray_test_tmp(IDX_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(IDX_TMP)); } +static void ixr_teardown(void) { ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(IDX_TMP)); ray_runtime_destroy(g_ixrt); } +static ray_t* ixr_eval(const char* src) { + ray_t* r = ray_eval_str(ray_test_tmp(src)); /* every "/tmp" path moves under the process root */ + if (r && RAY_IS_ERR(r)) { fprintf(stderr, "%s: %s\n", src, ray_error_msg()); } + return r; +} +static int64_t ixr_i64(const char* src) { + ray_t* r = ixr_eval(src); + int64_t x = (r && !RAY_IS_ERR(r)) ? r->i64 : INT64_MIN; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + return x; +} + +/* The live file of column `col` in splayed directory `dir` (a "/tmp" path, + * moved under the process root): splayed saves publish a generation + * directory through .current (#649 / #713). */ +static bool ix_live_path(const char* dir, const char* col, char* out, size_t cap) { + char cur[1024]; + if (ray_splay_resolve_dir(ray_test_tmp(dir), cur, sizeof cur) != RAY_OK) return false; + int n = snprintf(out, cap, "%s/%s", cur, col); + return n > 0 && (size_t)n < cap; +} + +/* FILTER(t, (== k key) AND (>= rc 10)) over the global table `t`, as one + * unsplit conjunction (a graph run without ray_optimize, which would split + * it; only the internal graph API reaches this arm): the eq+range arm + * (test_store.c, lazy_eq_range). rc "v" is the arm's shape, rc "k" one it + * declines (the range on the equality column). Owned result. */ +static ray_t* ix_eqrange(const char* t, int64_t key, const char* rc) { + ray_t* tbl = ray_env_get(ray_sym_intern(t, strlen(t))); /* borrowed */ + if (!tbl || tbl->type != RAY_TABLE) return NULL; + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* pred = ray_and(g, ray_eq(g, ray_scan(g, "k"), ray_const_i64(g, key)), + ray_ge(g, ray_scan(g, rc), ray_const_i64(g, 10))); + ray_t* r = ray_execute(g, ray_filter(g, ray_const_table(g, tbl), pred)); + ray_graph_free(g); + return r; +} + +/* FILTER(t, (== col key)) as a bare graph (no ray_optimize): the + * OP_FILTER single-compare arm itself. Owned result. */ +static ray_t* ix_filter_eq(const char* t, const char* col, int64_t key) { + ray_t* tbl = ray_env_get(ray_sym_intern(t, strlen(t))); /* borrowed */ + if (!tbl || tbl->type != RAY_TABLE) return NULL; + ray_graph_t* g = ray_graph_new(tbl); + ray_t* r = ray_execute(g, ray_filter(g, ray_const_table(g, tbl), ray_eq(g, ray_scan(g, col), ray_const_i64(g, key)))); + ray_graph_free(g); + return r; +} + +/* Generation 2 takes generation 0's index route for every recorded kind: + * the same site counters, the same answers, and only the indexed column + * materialized. */ +static test_result_t test_consult_routes(void) { + ray_t* r = ixr_eval("(set T (table [k s b p v] (list (.idx.hash (% (* (til 100000) 7919) 100003)) " + "(.idx.sort (as 'I32 (- (% (* (til 100000) 31) 9973) 4000))) (.idx.bloom (% (* (til 100000) 17) 50021)) " + "(.attr.set 'parted (div (til 100000) 1000)) (til 100000))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cr0/\" T {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cr2/\" T {compress: true})"); if (r) ray_release(r); + /* cn: a HASH key with nulls: generation 0's EQ probe needs a null-free + * column (so generation 2 must not materialize for it), its `in` probe + * does not */ + r = ixr_eval("(set TN (table [k v] (list (.idx.hash (as 'I64 (map (fn [j] (if (== 0 (% j 100)) 0N (% (* j 7) 10007))) (til 70000)))) " + "(til 70000))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cn0/\" TN {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cn2/\" TN {compress: true})"); if (r) ray_release(r); + /* cf: F64 HASH and BLOOM: generation 0 consults neither for a float + * key, EQ or `in` (so generation 2 materializes nothing) */ + r = ixr_eval("(set TF (table [h b v] (list (.idx.hash (as 'F64 (% (til 70000) 1000))) " + "(.idx.bloom (as 'F64 (% (* (til 70000) 7) 5000))) (til 70000))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cf0/\" TF {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cf2/\" TF {compress: true})"); if (r) ray_release(r); + /* cs: a SYM HASH key with nulls, generation 2 since the rebuild: the + * null key (id 0) consults nothing on generation 0, a nonzero key and + * `in` consult the index */ + r = ixr_eval("(set SK (as 'SYM (map (fn [i] (if (== i 0) \"\" (concat \"k\" (as 'STR i)))) (til 5000))))"); + if (r) ray_release(r); + r = ixr_eval("(set TS (table [k v] (list (.idx.hash (at SK (% (* (til 70000) 7) 5000))) (til 70000))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cs0/\" TS {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cs2/\" TS {compress: true})"); if (r) ray_release(r); + { + char kp[1200]; + TEST_ASSERT_TRUE(ix_live_path(IDX_TMP "/cs2/", "k", kp, sizeof kp)); + TEST_ASSERT_EQ_U(ray_col_file_gen(kp), 2); + TEST_ASSERT_EQ_I(ix_hdr(kp).index_kind, RAY_IDX_HASH); + } + /* the eq+range conjunction: the HASH key's index slice, the same rows; + * a declined shape (the range on k itself) consults nothing and + * materializes nothing */ + for (int sh = 0; sh < 2; sh++) { + uint64_t ec[2], eh[2]; int64_t en[2]; + for (int g = 0; g < 2; g++) { + char q[200]; + snprintf(q, sizeof q, "(set X (.db.splayed.get \"" IDX_TMP "/cr%d/\"))", g * 2); + r = ixr_eval(q); if (r) ray_release(r); + uint64_t c0 = ray_idx_consults[IDX_SITE_FILTER_EQRANGE], h0 = ray_idx_hits[IDX_SITE_FILTER_EQRANGE]; + ray_enc_counters_reset(); + r = ix_eqrange("X", 4242, sh ? "k" : "v"); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_TABLE, "eq+range gen %d: %s", g * 2, + r && RAY_IS_ERR(r) ? ray_error_msg() : "no table"); + en[g] = ray_table_nrows(r); + ray_release(r); + ec[g] = ray_idx_consults[IDX_SITE_FILTER_EQRANGE] - c0; eh[g] = ray_idx_hits[IDX_SITE_FILTER_EQRANGE] - h0; + if (g) { /* k and v; nothing when declined */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == (sh ? 0u : 2u), "eq+range shape %d: %llu materializations", sh, + (unsigned long long)k.materialized); + } + } + TEST_ASSERT_TRUE(en[0] == en[1] && en[0] >= 1); + TEST_ASSERT_TRUE(ec[0] == (sh ? 0u : 1u) && eh[0] == ec[0]); /* generation 0 takes the arm, or not */ + TEST_ASSERT_TRUE(ec[1] == ec[0] && eh[1] == eh[0]); + } + /* the bare single compare on the nullable HASH key: generation 0's EQ + * probe declines a column with nulls, so generation 2 reads by range */ + { + uint64_t c[2][IDX_SITE__N]; int64_t n[2]; + for (int g = 0; g < 2; g++) { + char q[200]; + snprintf(q, sizeof q, "(set X (.db.splayed.get \"" IDX_TMP "/cn%d/\"))", g * 2); + r = ixr_eval(q); if (r) ray_release(r); + uint64_t c0[IDX_SITE__N]; memcpy(c0, ray_idx_consults, sizeof c0); + ray_enc_counters_reset(); + r = ix_filter_eq("X", "k", 42); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == RAY_TABLE, "bare eq gen %d: %s", g * 2, + r && RAY_IS_ERR(r) ? ray_error_msg() : "no table"); + n[g] = ray_table_nrows(r); + ray_release(r); + for (int s = 0; s < IDX_SITE__N; s++) c[g][s] = ray_idx_consults[s] - c0[s]; + if (g) { ray_enc_counters_t k; ray_enc_counters_get(&k); TEST_ASSERT_EQ_U(k.materialized, 0); } + } + TEST_ASSERT_TRUE(n[0] == n[1] && n[0] >= 1); + TEST_ASSERT_TRUE(c[0][IDX_SITE_FILTER_HASH] == 0 && memcmp(c[0], c[1], sizeof c[0]) == 0); + } + /* sum-of-a-projection shapes: the select gathers v by the selection, so + * each also pins that v is never materialized. `uses`: generation 0 + * consults the column's region index (its materialization on generation + * 2 is that index use); every other shape takes P3's encoded route on + * generation 2 and materializes nothing. */ + /* `probe`: an equality on the HASH, answered by probing the region where + * it is mapped (ray_enc_hash_eq_rowsel): the index is used, nothing is + * materialized */ + static const struct { const char* q; bool uses; const char* d; bool probe; } qs[] = { + { "(sum (at (select {from: X where: (== k 4242)}) 'v))", true, NULL, true }, + { "(sum (at (select {from: X where: (in k [1 2 3 4242])}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (> s 3000)}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (== b 50020)}) 'v))", true, NULL, false }, /* present: consulted, no prune */ + { "(sum (at (select {from: X where: (== b 3)}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (== p 77)}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (in p [3 77])}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (!= k 4242)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (> k 50000)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (< k 500)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (> k 999999)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (!= s 3000)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (in s [1 2 3000])}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (!= b 5)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (> b 40000)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (in b [3 50020])}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (!= p 77)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (> p 90)}) 'v))", false, NULL, false }, + { "(sum (at (select {from: X where: (== k 42)}) 'v))", false, "cn", false }, + { "(sum (at (select {from: X where: (in k [42 43])}) 'v))", true, "cn", false }, + /* SORT: every compare but NE consults the range probe */ + { "(sum (at (select {from: X where: (== s 3000)}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (< s -3000)}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (<= s -3000)}) 'v))", true, NULL, false }, + { "(sum (at (select {from: X where: (>= s 3000)}) 'v))", true, NULL, false }, + /* float keys: neither HASH nor BLOOM, EQ or `in` */ + { "(sum (at (select {from: X where: (== h 42.0)}) 'v))", false, "cf", false }, + { "(sum (at (select {from: X where: (in h [42.0 43.0])}) 'v))", false, "cf", false }, + { "(sum (at (select {from: X where: (== b 42.0)}) 'v))", false, "cf", false }, + { "(sum (at (select {from: X where: (in b [42.0 43.0])}) 'v))", false, "cf", false }, + /* SYM HASH with nulls: key 0, a nonzero key, `in` */ + /* the null key: decided on ids on the encoded route (id 0) */ + { "(sum (at (select {from: X where: (== k ')}) 'v))", false, "cs", false }, + { "(sum (at (select {from: X where: (!= k ')}) 'v))", false, "cs", false }, + { "(sum (at (select {from: X where: (== k 'k42)}) 'v))", true, "cs", true }, + { "(sum (at (select {from: X where: (in k ['k42 'k43])}) 'v))", true, "cs", false }, + { NULL, false, NULL, false }, + }; + for (int i = 0; qs[i].q; i++) { + uint64_t c[2][IDX_SITE__N], h[2][IDX_SITE__N]; int64_t n[2]; + for (int g = 0; g < 2; g++) { + char q[200]; + snprintf(q, sizeof q, "(set X (.db.splayed.get \"" IDX_TMP "/%s%d/\"))", qs[i].d ? qs[i].d : "cr", g * 2); + r = ixr_eval(q); if (r) ray_release(r); + uint64_t c0[IDX_SITE__N], h0[IDX_SITE__N]; + memcpy(c0, ray_idx_consults, sizeof c0); memcpy(h0, ray_idx_hits, sizeof h0); + ray_enc_counters_reset(); + n[g] = ixr_i64(qs[i].q); + for (int s = 0; s < IDX_SITE__N; s++) { c[g][s] = ray_idx_consults[s] - c0[s]; h[g][s] = ray_idx_hits[s] - h0[s]; } + if (g) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == (qs[i].uses && !qs[i].probe ? 1u : 0u), "%s: %llu materializations", qs[i].q, + (unsigned long long)k.materialized); + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info X 'v) 'materialized) 1 0)"), 0); + } + } + TEST_ASSERT_FMT(n[0] == n[1] && n[0] != INT64_MIN, "%s: %lld vs %lld", qs[i].q, (long long)n[0], (long long)n[1]); + uint64_t any = 0; for (int s = 0; s < IDX_SITE__N; s++) any += c[0][s]; + if (qs[i].uses) + TEST_ASSERT_FMT(any >= 1, "%s: generation 0 consults no index (the shape does not discriminate)", qs[i].q); + TEST_ASSERT_FMT(memcmp(c[0], c[1], sizeof c[0]) == 0 && memcmp(h[0], h[1], sizeof h[0]) == 0, + "%s: index sites differ between generations", qs[i].q); + } + PASS(); +} + +/* An unindexed (chunk-zone) generation-2 column keeps P2's directory + * consult: nothing is materialized for an out-of-range key. */ +static test_result_t test_consult_dir_unchanged(void) { + ray_t* r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/cz/\" (table [h] (list (til 200000))) {compress: true})"); + if (r) ray_release(r); + r = ixr_eval("(set Z (.db.splayed.get \"" IDX_TMP "/cz/\"))"); if (r) ray_release(r); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info Z 'h) 'index)"), ray_sym_intern("chunk_zone", 10)); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ixr_i64("(count (select {from: Z where: (== h 999999)}))"), 0); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + PASS(); +} + +/* Spec "Errors": a transient failure on the index route (the parse's oom) + * is the query's error, not a scan, and not cached: the next query, with + * the hook off, answers from the index. The `in` probe parses the region + * (it materializes the column); the equality probes the region where it is + * mapped (ray_enc_hash_eq_rowsel), parses nothing and answers under the + * hook. */ +static test_result_t test_index_route_oom(void) { + ray_t* r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/co/\" (table [k v] (list (.idx.hash (% (* (til 70000) 7) 10007)) (til 70000))) {compress: true})"); + if (r) ray_release(r); + r = ixr_eval("(set CO (.db.splayed.get \"" IDX_TMP "/co/\"))"); if (r) ray_release(r); + const char* q = "(count (at (select {from: CO where: (in k [42 43])}) 'v))"; + const char* qe = "(count (at (select {from: CO where: (== k 42)}) 'v))"; + int64_t want = ixr_i64("(count (where (in (% (* (til 70000) 7) 10007) [42 43])))"); + ray_enccol_test_fail_index_parse(true); + uint64_t e0 = ray_idx_hits[IDX_SITE_FILTER_HASH]; + TEST_ASSERT_EQ_I(ixr_i64(qe), 7); + TEST_ASSERT_EQ_U(ray_idx_hits[IDX_SITE_FILTER_HASH], e0 + 1); /* the region probe */ + ray_error_clear(); + r = ray_eval_str(q); + ray_enccol_test_fail_index_parse(false); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "oom"); + TEST_ASSERT_TRUE(ray_error_msg() && strstr(ray_error_msg(), "index parse") != NULL); + ray_error_free(r); + uint64_t h0 = ray_idx_hits[IDX_SITE_IN]; + TEST_ASSERT_EQ_I(ixr_i64(q), want); + TEST_ASSERT_EQ_U(ray_idx_hits[IDX_SITE_IN], h0 + 1); /* from the index */ + PASS(); +} + +/* An equality on a recorded HASH probes the region where it is mapped + * (ray_enc_hash_eq_rowsel): generation 0's answers and index counters, + * nothing materialized, the column not decoded. k: about one row per key; + * g: 100 rows per key; z: key 0 on half the rows (dense: the probe + * declines and the column materializes, as before); w: an I32 key; y: a + * SYM key. An absent key is an empty selection. */ +static test_result_t test_hash_region_probe(void) { + ray_t* r = ixr_eval("(set SY (as 'SYM (map (fn [i] (concat \"y\" (as 'STR i))) (til 2000))))"); + if (r) ray_release(r); + r = ixr_eval("(set TP (table [k g z w y v] (list (.idx.hash (% (* (til 100000) 7919) 100003)) " + "(.idx.hash (% (til 100000) 1000)) (.idx.hash (* (>= (til 100000) 50000) (til 100000))) " + "(.idx.hash (as 'I32 (- (% (* (til 100000) 31) 9973) 4000))) (.idx.hash (at SY (% (* (til 100000) 7) 2000))) " + "(til 100000))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/hp0/\" TP {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/hp2/\" TP {compress: true})"); if (r) ray_release(r); + static const struct { const char* q; int probes; uint64_t mat; } qs[] = { + { "(sum (at (select {from: X where: (== k 4242)}) 'v))", 1, 0 }, + { "(sum (at (select {from: X where: (== k 999999)}) 'v))", 1, 0 }, /* absent */ + { "(sum (at (select {from: X where: (== g 77)}) 'v))", 1, 0 }, + { "(sum (at (select {from: X where: (== g 999)}) 'v))", 1, 0 }, /* the last group */ + { "(sum (at (select {from: X where: (== z 0)}) 'v))", 0, 1 }, /* dense: declined */ + { "(sum (at (select {from: X where: (== z 77777)}) 'v))", 1, 0 }, + { "(sum (at (select {from: X where: (== w -4000)}) 'v))", 1, 0 }, + { "(sum (at (select {from: X where: (== w 5969)}) 'v))", 1, 0 }, + { "(sum (at (select {from: X where: (== y 'y42)}) 'v))", 1, 0 }, + { "(sum (at (select {from: X where: (== y 'nope)}) 'v))", 0, 0 }, /* not in the domain */ + { NULL, 0, 0 }, + }; + for (int i = 0; qs[i].q; i++) { + int64_t n[2]; uint64_t hc[2], hh[2]; + for (int gen = 0; gen < 2; gen++) { + r = ixr_eval(gen ? "(set X (.db.splayed.get \"" IDX_TMP "/hp2/\"))" : "(set X (.db.splayed.get \"" IDX_TMP "/hp0/\"))"); + if (r) ray_release(r); + uint64_t c0 = ray_idx_consults[IDX_SITE_FILTER_HASH], h0 = ray_idx_hits[IDX_SITE_FILTER_HASH]; + uint64_t p0 = ray_enc_hash_test_probes(); + ray_enc_counters_reset(); + n[gen] = ixr_i64(qs[i].q); + hc[gen] = ray_idx_consults[IDX_SITE_FILTER_HASH] - c0; hh[gen] = ray_idx_hits[IDX_SITE_FILTER_HASH] - h0; + if (gen) { + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(ray_enc_hash_test_probes() - p0 == (uint64_t)qs[i].probes, "%s: %llu region probes", qs[i].q, + (unsigned long long)(ray_enc_hash_test_probes() - p0)); + TEST_ASSERT_FMT(k.materialized == qs[i].mat, "%s: %llu materializations", qs[i].q, + (unsigned long long)k.materialized); + /* the probed column: its group's rows read back, never the + * column (100000 rows, at most 800000 bytes) */ + if (!qs[i].mat) { + const char* cn = strstr(qs[i].q, "(== ") + 4; + ray_t* xt = ray_eval_str("X"); + ray_t* xe = xt && !RAY_IS_ERR(xt) ? ray_table_get_col_enc(xt, ray_sym_intern(cn, 1)) : NULL; + uint64_t cb = xe ? atomic_load(&ray_enccol_of(xe)->decoded_bytes) : UINT64_MAX; + if (xt && !RAY_IS_ERR(xt)) ray_release(xt); + TEST_ASSERT_FMT(cb <= 800000 / 2, "%s: the key column decoded %llu bytes", qs[i].q, + (unsigned long long)cb); + } + } + } + TEST_ASSERT_FMT(n[0] == n[1] && n[0] != INT64_MIN, "%s: %lld vs %lld", qs[i].q, (long long)n[0], (long long)n[1]); + if (qs[i].probes) TEST_ASSERT_FMT(hc[1] >= 1 && hh[1] == hh[0], "%s: hash hits %llu vs %llu", qs[i].q, + (unsigned long long)hh[1], (unsigned long long)hh[0]); + } + PASS(); +} + +/* ---- index decisions in the write context; the SYM rebuild (Task 7) ---- */ + +static ray_err_t ix_save_ctx(ray_t* col, const char* path, struct ray_sym_domain_s* dom, uint8_t decision) { + ray_col_write_t w; memset(&w, 0, sizeof w); + ray_t* e = ray_col_src_bind(col, &w.src); + if (e) { ray_error_free(e); return RAY_ERR_TYPE; } + w.name = "k"; w.gen = 2; w.target_dom = dom; w.durable = false; w.index_decision = decision; + ray_err_t r = ray_col_save_ctx(&w, path); + ray_col_src_release(&w.src); + return r; +} + +/* Review focus 2: a SYM HASH saved into a target domain with another + * insertion order and width is rebuilt over the target ids. 1000 words x 5 + * rows: every group is sparse, so the eq probe answers by index + * (ray_index_hash_eq_rowsel returns NULL for dense groups, idxop.c:2404). */ +static test_result_t test_sym_rebuild_remap(void) { + char wb[16]; + ray_t* v = ray_sym_vec_new(RAY_SYM_W64, 5000); v->len = 5000; + for (int i = 0; i < 5000; i++) { int n = snprintf(wb, sizeof wb, "w%d", (i * 7) % 1000); ((int64_t*)ray_data(v))[i] = ray_sym_intern(wb, (size_t)n); } + v = with_index(v, ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(v); + ray_index_payload(v->index)->markers |= RAY_MARK_UNIQUE; /* flag only: the builder does not check it */ + int64_t ts = ray_sym_intern("ts", 2); + ray_index_payload(v->index)->u.hash.order_sym = ts; /* a heap root of this process: trusted */ + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(ray_test_tmp(IDX_TMP "/sym")); + TEST_ASSERT_NOT_NULL(dom); + for (int i = 0; i < 300; i++) { int n = snprintf(wb, sizeof wb, "pre%d", i); (void)ray_sym_domain_intern(dom, wb, (size_t)n); } + for (int i = 999; i >= 0; i--) { int n = snprintf(wb, sizeof wb, "w%d", i); (void)ray_sym_domain_intern(dom, wb, (size_t)n); } /* reversed */ + const char* ps = ray_test_tmp(IDX_TMP "/s"); + TEST_ASSERT_EQ_I(ix_save_ctx(v, ps, dom, RAY_COL_IDX_KEEP), RAY_OK); + ray_t* c = ray_col_mmap_splayed_dom(ps, dom); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->hdr.index_kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->hdr.col_flags, RAY_ENC_FLAG_UNIQUE); /* the source's UNIQUE */ + TEST_ASSERT_EQ_I(ray_enccol_of(c)->attrs & RAY_SYM_W_MASK, RAY_SYM_W16); /* 1301 entries: a wider class */ + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); + TEST_ASSERT_TRUE(ray_index_payload(m->index)->markers & RAY_MARK_UNIQUE); + TEST_ASSERT_EQ_I(ray_index_payload(m->index)->u.hash.order_sym, ts); /* the source's order name */ + for (int w = 0; w < 1000; w += 111) { + int n = snprintf(wb, sizeof wb, "w%d", w); + int64_t pos = ray_sym_domain_find(dom, wb, (size_t)n); + TEST_ASSERT_TRUE(pos > 300); + ray_t* sel = ray_index_hash_eq_rowsel(m, pos); + TEST_ASSERT_FMT(sel && ray_rowsel_meta(sel)->total_pass == 5, "word %s", wb); + ray_rowsel_release(sel); + } + /* encoded -> 2 from a fresh mapping: the rebuild materializes it exactly once */ + ray_release(c); + c = ray_col_mmap_splayed_dom(ps, dom); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ix_save_ctx(c, ray_test_tmp(IDX_TMP "/s2"), dom, RAY_COL_IDX_KEEP), RAY_OK); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + ray_release(c); + c = ray_col_mmap_splayed_dom(ray_test_tmp(IDX_TMP "/s2"), dom); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->hdr.index_kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->hdr.col_flags, RAY_ENC_FLAG_UNIQUE); + m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_TRUE(ray_index_payload(m->index)->markers & RAY_MARK_UNIQUE); + TEST_ASSERT_EQ_I(ray_index_payload(m->index)->u.hash.order_sym, ts); /* kept through the encoded re-save */ + ray_t* sel = ray_index_hash_eq_rowsel(m, ray_sym_domain_find(dom, "w7", 2)); + TEST_ASSERT_TRUE(sel && ray_rowsel_meta(sel)->total_pass == 5); + ray_rowsel_release(sel); + ray_release(c); + ray_sym_domain_release(dom); ray_release(v); + PASS(); +} + +/* A SYM PART saved at a wider target width writes its keys at the saved + * width (encw: the final attrs, not the caller's), keeps a trustworthy + * order name, and answers by the target ids. */ +static test_result_t test_sym_part_rebuild(void) { + char wb[16]; + ray_t* v = ray_sym_vec_new(RAY_SYM_W64, 600); v->len = 600; + for (int i = 0; i < 600; i++) { int n = snprintf(wb, sizeof wb, "pk%d", i / 100); ((int64_t*)ray_data(v))[i] = ray_sym_intern(wb, (size_t)n); } + v = with_index(v, ray_index_attach_part); + TEST_ASSERT_NOT_NULL(v); + ray_index_payload(v->index)->u.part.order_sym = ray_sym_intern("ts", 2); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(ray_test_tmp(IDX_TMP "/symp")); + TEST_ASSERT_NOT_NULL(dom); + for (int i = 0; i < 400; i++) { int n = snprintf(wb, sizeof wb, "pre%d", i); (void)ray_sym_domain_intern(dom, wb, (size_t)n); } + for (int i = 5; i >= 0; i--) { int n = snprintf(wb, sizeof wb, "pk%d", i); (void)ray_sym_domain_intern(dom, wb, (size_t)n); } + const char* p = ray_test_tmp(IDX_TMP "/sp"); + TEST_ASSERT_EQ_I(ix_save_ctx(v, p, dom, RAY_COL_IDX_KEEP), RAY_OK); + ray_t* c = ray_col_mmap_splayed_dom(p, dom); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->hdr.index_kind, RAY_IDX_PART); + TEST_ASSERT_EQ_I(ray_enccol_of(c)->attrs & RAY_SYM_W_MASK, RAY_SYM_W16); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_FMT(m && !RAY_IS_ERR(m), "materialize: %s", m && RAY_IS_ERR(m) ? ray_error_msg() : "null"); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_PART); + ray_index_t* ix = ray_index_payload(m->index); + TEST_ASSERT_EQ_I(ix->u.part.order_sym, ray_sym_intern("ts", 2)); /* the source's order name */ + TEST_ASSERT_EQ_I(ix->u.part.n_parts, 6); + for (int i = 0; i < 6; i++) { + int n = snprintf(wb, sizeof wb, "pk%d", i); + ray_t* sel = ray_index_part_eq_rowsel(m, ray_sym_domain_find(dom, wb, (size_t)n)); + TEST_ASSERT_FMT(sel && ray_rowsel_meta(sel)->total_pass == 100, "key %s", wb); + ray_rowsel_release(sel); + } + ray_release(c); + ray_sym_domain_release(dom); ray_release(v); + PASS(); +} + +/* An encoded non-SYM source keeps its region byte for byte, without + * materializing. */ +static test_result_t test_encoded_keep_copies(void) { + ray_t* v = ix_hash_col(70000); + const char* pa = ray_test_tmp(IDX_TMP "/a"); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, pa, 2), RAY_OK); + ray_t* c = ray_col_mmap(pa); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ix_save_ctx(c, ray_test_tmp(IDX_TMP "/b"), NULL, RAY_COL_IDX_KEEP), RAY_OK); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + size_t na = 0, nb = 0; ray_enc_hdr_t ea, eb; uint64_t fa, fb; + uint8_t* ra = ix_file_region(pa, &na, &ea, &fa); + uint8_t* rb = ix_file_region(ray_test_tmp(IDX_TMP "/b"), &nb, &eb, &fb); + bool same = ra && rb && na == nb && memcmp(ra, rb, na) == 0; + free(ra); free(rb); + TEST_ASSERT_TRUE(same); + TEST_ASSERT_EQ_I(eb.index_kind, RAY_IDX_HASH); + TEST_ASSERT_TRUE(eb.end_off == fb); + /* DROP: no region; REBUILD: materializes once and equals the copy */ + TEST_ASSERT_EQ_I(ix_save_ctx(c, ray_test_tmp(IDX_TMP "/d"), NULL, RAY_COL_IDX_DROP), RAY_OK); + TEST_ASSERT_NULL(ix_file_region(ray_test_tmp(IDX_TMP "/d"), &nb, &eb, &fb)); + TEST_ASSERT_EQ_I(eb.index_kind, 0); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ix_save_ctx(c, ray_test_tmp(IDX_TMP "/r"), NULL, RAY_COL_IDX_REBUILD), RAY_OK); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 1); + ra = ix_file_region(pa, &na, &ea, &fa); + rb = ix_file_region(ray_test_tmp(IDX_TMP "/r"), &nb, &eb, &fb); + same = ra && rb && na == nb && memcmp(ra, rb, na) == 0; /* the same builder, the same column */ + free(ra); free(rb); + TEST_ASSERT_TRUE(same && eb.index_kind == RAY_IDX_HASH); + ray_release(c); + /* a plain source on REBUILD goes by range and writes the same region */ + TEST_ASSERT_EQ_I(ix_save_ctx(v, ray_test_tmp(IDX_TMP "/rp"), NULL, RAY_COL_IDX_REBUILD), RAY_OK); + ra = ix_file_region(pa, &na, &ea, &fa); + rb = ix_file_region(ray_test_tmp(IDX_TMP "/rp"), &nb, &eb, &fb); + same = ra && rb && na == nb && memcmp(ra, rb, na) == 0; + free(ra); free(rb); + TEST_ASSERT_TRUE(same); + /* an unknown decision is a type error; generation 0 takes KEEP only */ + TEST_ASSERT_EQ_I(ix_save_ctx(v, ray_test_tmp(IDX_TMP "/x"), NULL, RAY_COL_IDX_DROP + 1), RAY_ERR_TYPE); + ray_release(v); + PASS(); +} + +/* Review minor 1: a stale SYM HASH / PART is rebuilt from the column on + * generation 2 (every SYM index is rebuilt over the target ids), without + * the stale root's UNIQUE or order name (colw_region_prepare's `!stale`): + * after a splayed save and reload, generation 2 keeps at least what + * generation 0 keeps (a rebuilt HASH; no PART). */ +static test_result_t test_sym_stale_rebuild(void) { + char wb[16]; + ray_t* g = ray_sym_vec_new(RAY_SYM_W64, 4000); g->len = 4000; + ray_t* p = ray_sym_vec_new(RAY_SYM_W64, 4000); p->len = 4000; + for (int i = 0; i < 4000; i++) { + int n = snprintf(wb, sizeof wb, "sg%d", (i * 7) % 800); + ((int64_t*)ray_data(g))[i] = ray_sym_intern(wb, (size_t)n); + n = snprintf(wb, sizeof wb, "sp%d", i / 500); + ((int64_t*)ray_data(p))[i] = ray_sym_intern(wb, (size_t)n); + } + g = with_index(g, ray_index_attach_hash); + p = with_index(p, ray_index_attach_part); + TEST_ASSERT_TRUE(g && p); + ray_index_payload(g->index)->markers |= RAY_MARK_UNIQUE; + ray_index_payload(g->index)->u.hash.order_sym = ray_sym_intern("ts", 2); /* heap roots: trusted unless stale */ + ray_index_payload(p->index)->u.part.order_sym = ray_sym_intern("ts", 2); + ray_index_payload(g->index)->built_for_len = 3999; /* stale */ + ray_index_payload(p->index)->built_for_len = 3999; + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("g", 1), g); + t = ray_table_add_col(t, ray_sym_intern("p", 1), p); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + for (int gen = 0; gen <= 2; gen += 2) { + char d[64], y[64]; + snprintf(d, sizeof d, IDX_TMP "/st%d/", gen); snprintf(y, sizeof y, IDX_TMP "/st%d.sym", gen); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, ray_test_tmp(d), ray_test_tmp(y), gen ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF), + RAY_OK); + } + ray_index_payload(g->index)->built_for_len = 4000; + ray_index_payload(p->index)->built_for_len = 4000; + ray_t* l0 = ray_read_splayed(ray_test_tmp(IDX_TMP "/st0/"), ray_test_tmp(IDX_TMP "/st0.sym")); + ray_t* l2 = ray_read_splayed(ray_test_tmp(IDX_TMP "/st2/"), ray_test_tmp(IDX_TMP "/st2.sym")); + TEST_ASSERT_TRUE(l0 && !RAY_IS_ERR(l0) && l2 && !RAY_IS_ERR(l2)); + ray_t* g0 = ray_table_get_col(l0, ray_sym_intern("g", 1)); + ray_t* p0 = ray_table_get_col(l0, ray_sym_intern("p", 1)); + ray_t* g2 = ray_table_col(l2, ray_sym_intern("g", 1)); /* materialized: attaches the region */ + ray_t* p2 = ray_table_col(l2, ray_sym_intern("p", 1)); + TEST_ASSERT_TRUE(g2 && !RAY_IS_ERR(g2) && p2 && !RAY_IS_ERR(p2)); + TEST_ASSERT_EQ_I(ray_index_kind(g0), RAY_IDX_HASH); /* generation 0 rebuilds the HASH */ + TEST_ASSERT_TRUE(ray_index_kind(p0) != RAY_IDX_PART); /* and drops the PART */ + TEST_ASSERT_EQ_I(ray_index_kind(g2), RAY_IDX_HASH); + TEST_ASSERT_EQ_I(ray_index_kind(p2), RAY_IDX_PART); + TEST_ASSERT_FALSE(ray_index_payload(g2->index)->markers & RAY_MARK_UNIQUE); /* a stale flag is not kept */ + TEST_ASSERT_EQ_I(ray_index_payload(g2->index)->u.hash.order_sym, -1); /* nor a stale order name */ + TEST_ASSERT_EQ_I(ray_index_payload(p2->index)->u.part.order_sym, -1); + TEST_ASSERT_EQ_I(ray_index_payload(g2->index)->built_for_len, 4000); + /* the rebuilt indexes answer by the file's ids */ + ray_t* cell = ray_sym_vec_cell(g2, 7); + int64_t key = ray_read_sym(ray_data(g2), 7, RAY_SYM, g2->attrs); + ray_t* sel = ray_index_hash_eq_rowsel(g2, key); + TEST_ASSERT_TRUE(cell && sel && ray_rowsel_meta(sel)->total_pass == 5); + ray_rowsel_release(sel); + key = ray_read_sym(ray_data(p2), 1000, RAY_SYM, p2->attrs); + sel = ray_index_part_eq_rowsel(p2, key); + TEST_ASSERT_TRUE(sel && ray_rowsel_meta(sel)->total_pass == 500); + ray_rowsel_release(sel); + ray_release(l0); ray_release(l2); ray_release(t); ray_release(g); ray_release(p); + PASS(); +} + +/* A stale SYM PART over values that are no longer in contiguous blocks has + * no rebuild: the save still succeeds and records no index. */ +static test_result_t test_sym_stale_part_unbuildable(void) { + char wb[16]; + ray_t* p = ray_sym_vec_new(RAY_SYM_W64, 600); p->len = 600; + for (int i = 0; i < 600; i++) { int n = snprintf(wb, sizeof wb, "q%d", i / 100); ((int64_t*)ray_data(p))[i] = ray_sym_intern(wb, (size_t)n); } + p = with_index(p, ray_index_attach_part); + TEST_ASSERT_NOT_NULL(p); + ray_index_payload(p->index)->built_for_len = 599; /* stale */ + ((int64_t*)ray_data(p))[599] = ray_sym_intern("q0", 2); /* q0 again after q5: not contiguous */ + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(ray_test_tmp(IDX_TMP "/symq")); + for (int i = 0; i < 6; i++) { int n = snprintf(wb, sizeof wb, "q%d", i); (void)ray_sym_domain_intern(dom, wb, (size_t)n); } + const char* pa = ray_test_tmp(IDX_TMP "/sq"); + TEST_ASSERT_EQ_I(ix_save_ctx(p, pa, dom, RAY_COL_IDX_KEEP), RAY_OK); + size_t n; ray_enc_hdr_t eh; uint64_t fn; + TEST_ASSERT_NULL(ix_file_region(pa, &n, &eh, &fn)); + TEST_ASSERT_EQ_I(eh.index_kind, 0); + ray_t* c = ray_col_mmap_splayed_dom(pa, dom); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_release(c); + ray_index_payload(p->index)->built_for_len = 600; + ray_sym_domain_release(dom); ray_release(p); + PASS(); +} + +/* Review important 1: the null-key compare on a SYM HASH uses no index + * (generation 0 consults none for key 0): generation 2 answers on ids as + * generation 0 does, and so does an index-using key. */ +static test_result_t test_sym_hash_null_key(void) { + ray_t* r = ixr_eval("(set SK (as 'SYM (map (fn [i] (if (== i 0) \"\" (concat \"k\" (as 'STR i)))) (til 5000))))"); + if (r) ray_release(r); + r = ixr_eval("(set TS (table [k v] (list (.idx.hash (at SK (% (* (til 70000) 7) 5000))) (til 70000))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/zn0/\" TS {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/zn2/\" TS {compress: true})"); if (r) ray_release(r); + char kp[1200]; + TEST_ASSERT_TRUE(ix_live_path(IDX_TMP "/zn2/", "k", kp, sizeof kp)); + ray_enc_hdr_t eh = ix_hdr(kp); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_HASH); + static const char* const qs[] = { + "(sum (at (select {from: X where: (== k ')}) 'v))", + "(sum (at (select {from: X where: (!= k ')}) 'v))", + "(count (select {from: X where: (== k ')}))", + NULL, + }; + for (int i = 0; qs[i]; i++) { + r = ixr_eval("(set X (.db.splayed.get \"" IDX_TMP "/zn0/\"))"); if (r) ray_release(r); + int64_t want = ixr_i64(qs[i]); + TEST_ASSERT_TRUE(want != INT64_MIN); + r = ixr_eval("(set X (.db.splayed.get \"" IDX_TMP "/zn2/\"))"); if (r) ray_release(r); + ray_enc_counters_reset(); + int64_t got = ixr_i64(qs[i]); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(got == want, "%s: %lld vs generation 0 %lld", qs[i], (long long)got, (long long)want); + TEST_ASSERT_EQ_U(k.materialized, 0); + } + TEST_ASSERT_EQ_I(ixr_i64("(count (select {from: X where: (== k ')}))"), 14); + int64_t got = ixr_i64("(sum (at (select {from: X where: (== k 'k42)}) 'v))"); + r = ixr_eval("(set X (.db.splayed.get \"" IDX_TMP "/zn0/\"))"); if (r) ray_release(r); + int64_t want = ixr_i64("(sum (at (select {from: X where: (== k 'k42)}) 'v))"); + TEST_ASSERT_TRUE(want != INT64_MIN); + TEST_ASSERT_EQ_I(got, want); + PASS(); +} + +/* DROP records no kind on either writer: a plain column (direct pointers), + * a SYM column (range reads, the rebuild skipped). Each file opens and + * materializes without an index; UNIQUE, a header flag, stays. */ +static test_result_t test_drop_records_none(void) { + ray_t* v = ix_hash_col(3000); + ray_index_payload(v->index)->markers |= RAY_MARK_UNIQUE; + const char* p = ray_test_tmp(IDX_TMP "/dp"); + TEST_ASSERT_EQ_I(ix_save_ctx(v, p, NULL, RAY_COL_IDX_DROP), RAY_OK); + size_t n; ray_enc_hdr_t eh; uint64_t fn; + TEST_ASSERT_NULL(ix_file_region(p, &n, &eh, &fn)); + TEST_ASSERT_EQ_I(eh.index_kind, 0); + TEST_ASSERT_EQ_I(eh.col_flags, RAY_ENC_FLAG_UNIQUE); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "open: %s", c && RAY_IS_ERR(c) ? ray_error_msg() : "null"); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && ray_index_kind(m) != RAY_IDX_HASH); + ray_release(c); ray_release(v); + char wb[16]; + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, 400); s->len = 400; + for (int i = 0; i < 400; i++) { int k = snprintf(wb, sizeof wb, "d%d", i % 37); ((int64_t*)ray_data(s))[i] = ray_sym_intern(wb, (size_t)k); } + s = with_index(s, ray_index_attach_hash); + TEST_ASSERT_NOT_NULL(s); + ray_sym_domain_t* dom = ray_sym_domain_open_or_create(ray_test_tmp(IDX_TMP "/symd")); + for (int i = 0; i < 37; i++) { int k = snprintf(wb, sizeof wb, "d%d", i); (void)ray_sym_domain_intern(dom, wb, (size_t)k); } + p = ray_test_tmp(IDX_TMP "/ds"); + TEST_ASSERT_EQ_I(ix_save_ctx(s, p, dom, RAY_COL_IDX_DROP), RAY_OK); + TEST_ASSERT_NULL(ix_file_region(p, &n, &eh, &fn)); + TEST_ASSERT_EQ_I(eh.index_kind, 0); + c = ray_col_mmap_splayed_dom(p, dom); + TEST_ASSERT_FMT(c && !RAY_IS_ERR(c), "open: %s", c && RAY_IS_ERR(c) ? ray_error_msg() : "null"); + m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && !ray_index_has(m)); + ray_release(c); + ray_sym_domain_release(dom); ray_release(s); + PASS(); +} + +/* A loaded HASH / SORT / BLOOM / PART column re-saved compressed keeps its + * kind and its region, byte for byte, without materializing. */ +static test_result_t test_reload_keeps_kind(void) { + static ray_t* (*const att[4])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, + ray_index_attach_bloom, ray_index_attach_part }; + static const uint8_t kinds[4] = { RAY_IDX_HASH, RAY_IDX_SORT, RAY_IDX_BLOOM, RAY_IDX_PART }; + for (int k = 0; k < 4; k++) { + ray_t* v = ray_vec_new(RAY_I64, 70000); v->len = 70000; + for (int64_t i = 0; i < 70000; i++) ((int64_t*)ray_data(v))[i] = i / 700 * 3 - 50; /* blocks: PART admits it */ + v = with_index(v, att[k]); + TEST_ASSERT_FMT(v != NULL, "kind %u", kinds[k]); + char a[64], b[64]; + snprintf(a, sizeof a, IDX_TMP "/rk%d_a", k); snprintf(b, sizeof b, IDX_TMP "/rk%d_b", k); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(a), 2), RAY_OK); + ray_t* c = ray_col_mmap(ray_test_tmp(a)); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->type == RAY_ENCCOL); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(ray_col_save_gen(c, ray_test_tmp(b), 2), RAY_OK); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + TEST_ASSERT_FMT(kc.materialized == 0, "kind %u: %llu materializations", kinds[k], (unsigned long long)kc.materialized); + size_t na = 0, nb = 0; ray_enc_hdr_t ea, eb; uint64_t fa, fb; + uint8_t* ra = ix_file_region(ray_test_tmp(a), &na, &ea, &fa); + uint8_t* rb = ix_file_region(ray_test_tmp(b), &nb, &eb, &fb); + bool same = ra && rb && na == nb && memcmp(ra, rb, na) == 0; + free(ra); free(rb); + TEST_ASSERT_FMT(same && eb.index_kind == kinds[k] && eb.end_off == fb, "kind %u: recorded %u", kinds[k], eb.index_kind); + ray_release(c); + c = ray_col_mmap(ray_test_tmp(b)); + ray_t* m = c && !RAY_IS_ERR(c) ? ray_enccol_materialize(c) : NULL; + TEST_ASSERT_FMT(m && !RAY_IS_ERR(m) && ray_index_kind(m) == kinds[k], "kind %u: the re-saved column", kinds[k]); + ray_release(c); ray_release(v); + } + PASS(); +} + +/* Review focus 3: a generation-0 passenger root's order_sym is written -1. */ +static test_result_t test_passenger_order_absent(void) { + int64_t d[8] = { 1, 1, 2, 2, 3, 3, 4, 4 }; + ray_t* v = with_index(i64_vec(d, 8), ray_index_attach_part); + TEST_ASSERT_NOT_NULL(v); + ray_index_payload(v->index)->u.part.order_sym = ray_sym_intern("ts", 2); + TEST_ASSERT_EQ_I(ray_col_save(v, ray_test_tmp(IDX_TMP "/g0")), RAY_OK); /* generation 0 */ + ray_t* g0 = ray_col_mmap(ray_test_tmp(IDX_TMP "/g0")); + TEST_ASSERT_TRUE(g0 && !RAY_IS_ERR(g0) && ray_index_kind(g0) == RAY_IDX_PART); + TEST_ASSERT_TRUE(ray_index_payload(g0->index)->markers & RAY_MARK_MMAP); + TEST_ASSERT_EQ_I(ray_col_save_gen(g0, ray_test_tmp(IDX_TMP "/g2"), 2), RAY_OK); + size_t n; ray_enc_hdr_t eh; uint64_t fn; + uint8_t* r = ix_file_region(ray_test_tmp(IDX_TMP "/g2"), &n, &eh, &fn); + TEST_ASSERT_NOT_NULL(r); + ray_enc_idx_part_t p; memcpy(&p, r + 16, 40); + TEST_ASSERT_EQ_I(p.order_name, -1); + free(r); + /* the heap root of this process converts */ + TEST_ASSERT_EQ_I(ray_col_save_gen(v, ray_test_tmp(IDX_TMP "/h2"), 2), RAY_OK); + r = ix_file_region(ray_test_tmp(IDX_TMP "/h2"), &n, &eh, &fn); + TEST_ASSERT_NOT_NULL(r); + memcpy(&p, r + 16, 40); + TEST_ASSERT_TRUE(p.order_name > 0 && (size_t)p.order_name + 10 <= n && memcmp(r + p.order_name + 8, "ts", 2) == 0); + free(r); ray_release(g0); ray_release(v); + PASS(); +} + +/* Every ADMITTED (kind, parent type) pair goes builder -> write -> validate + * -> parse -> attach, and the parsed children equal the builder's byte for + * byte (spec "Completion additions"; "PART key types: save, load, + * validation ... on BOOL, U8, I16, I32, I64, F32, F64, DATE, TIME, + * TIMESTAMP and SYM"). PART equality probes then agree on every key. */ +static int ix_children_equal_raw(const ray_index_t* a, const ray_index_t* b); +/* the builder's index `a` as a region holds it, against the parsed `b` */ +static int ix_children_equal(const ray_index_t* a, const ray_index_t* b) { + ray_index_t av; ray_t* hold[4]; + int r = ix_children_equal_raw(ix_region_view(a, &av, hold), b); + ix_region_view_free(hold); + return r; +} +static int ix_children_equal_raw(const ray_index_t* a, const ray_index_t* b) { + ray_t* ca[4]; ray_t* cb[4]; + int na = ray_index_child_blocks(a, ca, 4), nb = ray_index_child_blocks(b, cb, 4); + if (na != nb) return 0; + for (int i = 0; i < na; i++) { + if (ca[i]->type != cb[i]->type || ca[i]->len != cb[i]->len) return 0; + if (ca[i]->type == RAY_SYM) { + for (int64_t k = 0; k < ca[i]->len; k++) + if (ray_read_sym(ray_data(ca[i]), k, RAY_SYM, ca[i]->attrs) != ray_read_sym(ray_data(cb[i]), k, RAY_SYM, cb[i]->attrs)) return 0; + } else if (memcmp(ray_data(ca[i]), ray_data(cb[i]), (size_t)ca[i]->len * ray_sym_elem_size(ca[i]->type, ca[i]->attrs)) != 0) { + return 0; + } + } + return 1; +} +/* Row r of a numeric or SYM column as the int64 key the probes take. */ +static int64_t ix_key_at(ray_t* v, int64_t r) { + if (v->type == RAY_SYM) return ray_read_sym(ray_data(v), r, RAY_SYM, v->attrs); + const uint8_t* d = ray_data(v); + switch (ray_sym_elem_size(v->type, 0)) { + case 1: return d[r]; + case 2: { int16_t x; memcpy(&x, d + r * 2, 2); return x; } + case 4: { int32_t x; memcpy(&x, d + r * 4, 4); return x; } + default: { int64_t x; memcpy(&x, d + r * 8, 8); return x; } + } +} +/* A column of `type`, 4096 rows, ascending value blocks of 64 (so PART + * admits it), no nulls; SYM ids 1..64 of the runtime domain. */ +static ray_t* ix_typed_col(int8_t type) { + for (int i = 0; i < 70; i++) { char b[8]; int n = snprintf(b, sizeof b, "t%d", i); (void)ray_sym_intern(b, (size_t)n); } + ray_t* v = type == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W8, 4096) : ray_vec_new(type, 4096); + v->len = 4096; + uint8_t* d = ray_data(v); + for (int64_t i = 0; i < 4096; i++) { + int64_t k = i / 64; /* 0..63 */ + switch (type) { + case RAY_BOOL: d[i] = (uint8_t)(k >= 32); break; + case RAY_U8: d[i] = (uint8_t)k; break; + case RAY_I16: { int16_t x = (int16_t)(k - 32); memcpy(d + i * 2, &x, 2); break; } + case RAY_I32: case RAY_DATE: case RAY_TIME: { int32_t x = (int32_t)(k * 1000 - 5000); memcpy(d + i * 4, &x, 4); break; } + case RAY_F32: { float x = (float)k * 0.5f - 3.0f; memcpy(d + i * 4, &x, 4); break; } + case RAY_F64: { double x = (double)k * 0.25 - 2.0; memcpy(d + i * 8, &x, 8); break; } + case RAY_SYM: d[i] = (uint8_t)(k + 1); break; + default: { int64_t x = k * 1000003 - 7; memcpy(d + i * 8, &x, 8); break; } /* I64, TIMESTAMP */ + } + } + return v; +} +static test_result_t test_admitted_roundtrip(void) { + static const int8_t types[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, + RAY_DATE, RAY_TIME, RAY_TIMESTAMP, RAY_SYM }; + static ray_t* (*const att[4])(ray_t**) = { ray_index_attach_hash, ray_index_attach_sort, + ray_index_attach_bloom, ray_index_attach_part }; + static const uint8_t kinds[4] = { RAY_IDX_HASH, RAY_IDX_SORT, RAY_IDX_BLOOM, RAY_IDX_PART }; + int done = 0; + for (size_t t = 0; t < sizeof types; t++) + for (int k = 0; k < 4; k++) { + if (!ray_index_kind_admits((ray_idx_kind_t)kinds[k], types[t])) continue; + ray_t* v = with_index(ix_typed_col(types[t]), att[k]); + TEST_ASSERT_FMT(v != NULL, "builder kind %u type %d", kinds[k], types[t]); + ray_t* p = ix_roundtrip(v, NULL, 0); + TEST_ASSERT_FMT(p != NULL, "round trip kind %u type %d", kinds[k], types[t]); + ray_index_t* a = ray_index_payload(v->index); + ray_index_t* b = ray_index_payload(p->index); + TEST_ASSERT_FMT(a->kind == b->kind && a->built_for_len == b->built_for_len && ix_children_equal(a, b), + "children kind %u type %d", kinds[k], types[t]); + if (kinds[k] == RAY_IDX_PART && types[t] != RAY_F32 && types[t] != RAY_F64) + for (int64_t r = 0; r < 4096; r += 640) { + int64_t key = ix_key_at(v, r); + ray_t* sa = ray_index_part_eq_rowsel(v, key); + ray_t* sb = ray_index_part_eq_rowsel(p, key); + TEST_ASSERT_FMT((sa == NULL) == (sb == NULL), "part probe type %d", types[t]); + if (sa) { TEST_ASSERT_EQ_I(ray_rowsel_meta(sa)->total_pass, ray_rowsel_meta(sb)->total_pass); + ray_rowsel_release(sa); ray_rowsel_release(sb); } + } + ray_release(p); ray_release(v); + done++; + } + ray_t* s = ray_vec_new(RAY_STR, 600); + for (int i = 0; i < 600; i++) { char b[32]; int n = snprintf(b, sizeof b, "string key %d long", i % 23); s = ray_str_vec_append(s, b, (size_t)n); } + ray_t* sv = with_index(s, ray_index_attach_hash); + ray_t* sp = ix_roundtrip(sv, NULL, 0); + TEST_ASSERT_TRUE(sp && ix_children_equal(ray_index_payload(sv->index), ray_index_payload(sp->index))); + ray_release(sp); ray_release(sv); + TEST_ASSERT_EQ_I(done, 10 * 4 + 2); /* ten numeric types x four kinds, SYM HASH and PART */ + PASS(); +} + +/* Spec "Completion additions": every admitted and every rejected (kind, + * parent type) pair through the writer, the validator and the attach. */ +static test_result_t test_admission_through_all(void) { + static const int8_t types[] = { RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, + RAY_DATE, RAY_TIME, RAY_TIMESTAMP, RAY_SYM, RAY_STR, RAY_GUID }; + static const uint8_t kinds[] = { RAY_IDX_HASH, RAY_IDX_SORT, RAY_IDX_BLOOM, RAY_IDX_PART }; + int rejected = 0; + for (size_t t = 0; t < sizeof types; t++) + for (size_t k = 0; k < sizeof kinds; k++) { + bool adm = ray_index_kind_admits((ray_idx_kind_t)kinds[k], types[t]); + ray_t* root = ray_index_new_root((ray_idx_kind_t)kinds[k], types[t], 0); + ray_enc_idx_src_t s = { root, types[t], 0, 0, NULL, 0 }; + FILE* f = fopen(ray_test_tmp(IDX_TMP "/adm"), "wb"); + uint64_t bytes; + ray_t* we = ray_enc_index_write(f, &s, &bytes); + fclose(f); + if (!adm) { + rejected++; + TEST_ASSERT_FMT(we && strcmp(ray_err_code(we), "nyi") == 0, "writer kind %u type %d", kinds[k], types[t]); + ray_t* col = types[t] == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W8, 0) : ray_vec_new(types[t], 0); + ray_retain(root); + ray_t* ae = ray_index_attach_persisted(&col, root); + TEST_ASSERT_FMT(ae && RAY_IS_ERR(ae) && strcmp(ray_err_code(ae), "corrupt") == 0, "attach kind %u type %d", kinds[k], types[t]); + ray_error_free(ae); ray_release(col); + } + if (we) ray_error_free(we); + ray_release(root); + } + TEST_ASSERT_EQ_I(rejected, 13 * 4 - (10 * 4 + 3)); /* every pair test_admitted_roundtrip does not build */ + PASS(); +} + +/* Carry from Task 5 (review minor 4): a stale region root on a numeric + * column of at least one chunk records no kind of its own, so a splayed + * save records the chunk zone generation 0 builds for such a column. */ +static test_result_t test_stale_root_chunk_zone(void) { + ray_t* v = ix_hash_col(70000); + TEST_ASSERT_NOT_NULL(v); + ray_index_payload(v->index)->built_for_len = 69999; /* stale */ + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("v", 1), v); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, ray_test_tmp(IDX_TMP "/stz/"), NULL, RAY_COMPRESS_ON), RAY_OK); + char p[1200]; + TEST_ASSERT_TRUE(ix_live_path(IDX_TMP "/stz/", "v", p, sizeof p)); + TEST_ASSERT_EQ_U(ray_col_file_gen(p), 2); + size_t n; ray_enc_hdr_t eh; uint64_t fn; + TEST_ASSERT_NULL(ix_file_region(p, &n, &eh, &fn)); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_CHUNK_ZONE); + ray_index_payload(v->index)->built_for_len = 70000; + ray_release(t); ray_release(v); + PASS(); +} + +/* D1: the SYM HASH / PART a splayed save writes as generation 2 keep the + * source's UNIQUE (checked against the in-memory source), and every query + * answers as on generation 0. Generation 0's own save drops the SYM PART + * and UNIQUE (splay_build_index_col rebuilds a bare HASH), the attribute + * difference D1 accepts. */ +static test_result_t test_sym_splay_kept(void) { + ray_t* r = ixr_eval("(set SY (as 'SYM (map (fn [i] (concat \"k\" (as 'STR i))) (til 6000))))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); ray_release(r); + r = ixr_eval("(set TQ (table [p g v] (list (.attr.set 'parted (asc (take ['a 'b 'c 'd] 6000))) " + "(.attr.set 'grouped (.attr.set 'unique SY)) (til 6000))))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/sq0/\" TQ {compress: false})"); TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/sq2/\" TQ {compress: true})"); TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); ray_release(r); + r = ixr_eval("(set X0 (.db.splayed.get \"" IDX_TMP "/sq0/\"))"); TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); ray_release(r); + r = ixr_eval("(set X2 (.db.splayed.get \"" IDX_TMP "/sq2/\"))"); TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); ray_release(r); + char pp[1200], pg[1200]; + TEST_ASSERT_TRUE(ix_live_path(IDX_TMP "/sq2/", "p", pp, sizeof pp) && ix_live_path(IDX_TMP "/sq2/", "g", pg, sizeof pg)); + ray_enc_hdr_t hp = ix_hdr(pp), hg = ix_hdr(pg); + TEST_ASSERT_EQ_U(ray_col_file_gen(pp), 2); + TEST_ASSERT_EQ_U(ray_col_file_gen(pg), 2); + TEST_ASSERT_EQ_I(hp.index_kind, RAY_IDX_PART); + TEST_ASSERT_EQ_I(hg.index_kind, RAY_IDX_HASH); + TEST_ASSERT_EQ_I(hg.col_flags, RAY_ENC_FLAG_UNIQUE); + /* the attributes of the in-memory source, on generation 2 */ + static const char* const kept[] = { + "(if (== (in 'parted (.attr.get (at TQ 'p))) (in 'parted (.attr.get (at X2 'p)))) 1 0)", + "(if (== (in 'unique (.attr.get (at TQ 'g))) (in 'unique (.attr.get (at X2 'g)))) 1 0)", + "(if (== (in 'grouped (.attr.get (at TQ 'g))) (in 'grouped (.attr.get (at X2 'g)))) 1 0)", + "(if (in 'parted (.attr.get (at TQ 'p))) 1 0)", + "(if (in 'unique (.attr.get (at TQ 'g))) 1 0)", + NULL, + }; + for (int i = 0; kept[i]; i++) TEST_ASSERT_FMT(ixr_i64(kept[i]) == 1, "%s", kept[i]); + /* generation 0's loss, as D1 records it (dev's splay_build_index_col) */ + TEST_ASSERT_EQ_I(ixr_i64("(if (in 'parted (.attr.get (at X0 'p))) 1 0)"), 0); + TEST_ASSERT_EQ_I(ixr_i64("(if (in 'unique (.attr.get (at X0 'g))) 1 0)"), 0); + static const char* const qs[] = { + "(sum (at (select {from: %s where: (== p 'b)}) 'v))", + "(sum (at (select {from: %s where: (in p ['a 'd])}) 'v))", + "(sum (at (select {from: %s where: (== p 'zz)}) 'v))", + "(sum (at (select {from: %s where: (== g 'k4242)}) 'v))", + "(sum (at (select {from: %s where: (in g ['k1 'k5999 'nope])}) 'v))", + "(sum (at (select {from: %s where: (!= g 'k17)}) 'v))", + "(count (select {from: %s where: (and (== p 'c) (> v 4000))}))", + NULL, + }; + for (int i = 0; qs[i]; i++) { + char q0[200], q2[200]; + snprintf(q0, sizeof q0, qs[i], "X0"); snprintf(q2, sizeof q2, qs[i], "X2"); + int64_t a = ixr_i64(q0), b = ixr_i64(q2); + TEST_ASSERT_FMT(a == b && a != INT64_MIN, "%s: %lld vs %lld", qs[i], (long long)a, (long long)b); + } + PASS(); +} + +/* ---- end to end: save paths, converter parity (Task 8) ---- */ + +/* The formatted value of `src` (owned string), or NULL on an error. */ +static ray_t* ixr_fmt(const char* src) { + ray_t* r = ixr_eval(src); + if (!r || RAY_IS_ERR(r)) { if (r) ray_error_free(r); return NULL; } + ray_t* f = ray_fmt(r, 0); + ray_release(r); + return f; +} +static bool ixr_same_fmt(ray_t* a, ray_t* b) { + return a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && /* an error never matches */ + ray_str_len(a) == ray_str_len(b) && memcmp(ray_str_ptr(a), ray_str_ptr(b), ray_str_len(a)) == 0; +} +/* Two tables with the same column names and, column by column, the same + * formatted values (a table's own format is only its shape). */ +static bool ixr_same_table(ray_t* a, ray_t* b) { + if (!a || !b || a->type != RAY_TABLE || b->type != RAY_TABLE || ray_table_ncols(a) != ray_table_ncols(b)) return false; + bool same = true; + for (int64_t c = 0; same && c < ray_table_ncols(a); c++) { + if (ray_table_col_name(a, c) != ray_table_col_name(b, c)) return false; + ray_t* ca = ray_table_col_idx(a, c); ray_t* cb = ray_table_col_idx(b, c); + if (!ca || !cb || RAY_IS_ERR(ca) || RAY_IS_ERR(cb)) return false; + ray_t* fa = ray_fmt(ca, 0); ray_t* fb = ray_fmt(cb, 0); + same = ixr_same_fmt(fa, fb); + if (fa) { if (RAY_IS_ERR(fa)) ray_error_free(fa); else ray_release(fa); } + if (fb) { if (RAY_IS_ERR(fb)) ray_error_free(fb); else ray_release(fb); } + } + return same; +} + +/* Every index the save path persists on generation 0 is on the generation-2 + * copy, and no auto pass touched a gen-2 file. STR DICT (P6b): the + * converter persists generation 0's DICT on generation 2 (over 65536 rows, + * no HASH), recorded in the header before materialization and attached to + * the materialized column after it. */ +static test_result_t test_converter_parity(void) { + FILE* f = fopen(ray_test_tmp(IDX_TMP "/in.csv"), "w"); + TEST_ASSERT_NOT_NULL(f); + fprintf(f, "u,c,s\n"); + for (int i = 0; i < 200000; i++) fprintf(f, "%d,%d,name%d\n", (i * 7919) % 1000003, i / 10, i % 50); + fclose(f); + ray_t* r; + r = ixr_eval("(.csv.splayed {compress: false} [I64 I64 STR] \"" IDX_TMP "/in.csv\" \"" IDX_TMP "/c0/\")"); if (r) ray_release(r); + r = ixr_eval("(.csv.splayed {compress: true} [I64 I64 STR] \"" IDX_TMP "/in.csv\" \"" IDX_TMP "/c2/\")"); if (r) ray_release(r); + r = ixr_eval("(set A (.db.splayed.get \"" IDX_TMP "/c0/\"))"); if (r) ray_release(r); + r = ixr_eval("(set C (.db.splayed.get \"" IDX_TMP "/c2/\"))"); if (r) ray_release(r); + static const char* const cols[] = { "u", "c", NULL }; + for (int i = 0; cols[i]; i++) { + char q0[256], q2[256], g2[256]; + snprintf(q0, sizeof q0, "(at (.idx.info (at A '%s)) 'kind)", cols[i]); + snprintf(q2, sizeof q2, "(at (.idx.info C '%s) 'index)", cols[i]); + snprintf(g2, sizeof g2, "(at (.idx.info C '%s) 'gen)", cols[i]); + TEST_ASSERT_EQ_I(ixr_i64(g2), 2); + int64_t k0 = ixr_i64(q0); + TEST_ASSERT_TRUE(k0 != INT64_MIN); + TEST_ASSERT_EQ_I(k0, ray_sym_intern("chunk_zone", 10)); /* the kind is there */ + TEST_ASSERT_EQ_I(k0, ixr_i64(q2)); /* chunk_zone on both */ + } + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info C 's) 'gen)"), 2); + /* P6b: generation 2 persists the DICT (spec "STR dictionary index"), + * recorded before materialization and attached after it */ + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info C 's) 'materialized) 1 0)"), 0); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info C 's) 'index)"), ray_sym_intern("dict", 4)); /* recorded */ + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (at A 's)) 'kind)"), ray_sym_intern("dict", 4)); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (at C 's)) 'kind)"), ray_sym_intern("dict", 4)); /* attached */ + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info C 's) 'materialized) 1 0)"), 1); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info C 's) 'index)"), ray_sym_intern("dict", 4)); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (at C 's)) 'n_distinct)"), ixr_i64("(at (.idx.info (at A 's)) 'n_distinct)")); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (at C 's)) 'n_distinct)"), 50); + /* explicit indexes, then .db.splayed.set: generation 2 keeps the kind */ + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/e2/\" (table [u s] (list (.idx.hash (at A 'u)) (.idx.hash (at A 's)))) {compress: true})"); if (r) ray_release(r); + r = ixr_eval("(set E (.db.splayed.get \"" IDX_TMP "/e2/\"))"); if (r) ray_release(r); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info E 'u) 'gen)"), 2); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info E 'u) 'index)"), ray_sym_intern("hash", 4)); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info E 's) 'gen)"), 2); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info E 's) 'index)"), ray_sym_intern("hash", 4)); + TEST_ASSERT_EQ_I(ixr_i64("(count (select {from: E where: (== s \"name7\")}))"), 4000); + PASS(); +} + +/* Task 2 review Minor 2: the converter's DICT floor is generation 0's, + * 65536 rows. At 65535 rows neither generation has a DICT (kind 0 recorded); + * at 65536 both do (kind 7 recorded, read from the header, nothing + * materialized). */ +static test_result_t test_converter_dict_boundary(void) { + static const int rows[2] = { 65535, 65536 }; + for (int b = 0; b < 2; b++) { + char csv[128], q[600]; + snprintf(csv, sizeof csv, IDX_TMP "/b%d.csv", rows[b]); + FILE* f = fopen(ray_test_tmp(csv), "w"); + TEST_ASSERT_NOT_NULL(f); + fprintf(f, "v,s\n"); + for (int i = 0; i < rows[b]; i++) fprintf(f, "%d,name%d\n", i, (i * 7919) % 300); + fclose(f); + for (int g = 0; g <= 2; g += 2) { + snprintf(q, sizeof q, "(.csv.splayed {compress: %s} [I64 STR] \"%s\" \"" IDX_TMP "/b%d_%d/\")", + g ? "true" : "false", csv, rows[b], g); + ray_t* r = ixr_eval(q); if (r) ray_release(r); + } + snprintf(q, sizeof q, "(.db.splayed.get \"" IDX_TMP "/b%d_2/\")", rows[b]); + ray_t* t = ixr_eval(q); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_meta_t m; + ray_enc_counters_reset(); + const bool got = ray_table_col_meta(t, ray_sym_intern("s", 1), &m); + ray_enc_counters_t k; ray_enc_counters_get(&k); + ray_release(t); + TEST_ASSERT_TRUE(got); + TEST_ASSERT_FMT(m.enc != NULL, "%d rows: generation 2", rows[b]); + TEST_ASSERT_FMT(m.index_kind == (b ? RAY_IDX_DICT : RAY_IDX_NONE), "%d rows: kind %u", rows[b], m.index_kind); + TEST_ASSERT_EQ_U(k.materialized, 0); + /* generation 0 over the same file: the same decision */ + if (b) snprintf(q, sizeof q, "(at (.idx.info (at (.db.splayed.get \"" IDX_TMP "/b%d_0/\") 's)) 'kind)", rows[b]); + else snprintf(q, sizeof q, "(if (.idx.has? (at (.db.splayed.get \"" IDX_TMP "/b%d_0/\") 's)) 1 0)", rows[b]); + TEST_ASSERT_EQ_I(ixr_i64(q), b ? ray_sym_intern("dict", 4) : 0); + } + PASS(); +} + +/* Spec "Index use materializes once": a point lookup on an indexed column + * materializes at most that column. An equality on a recorded HASH now + * probes the region where it is mapped (ray_enc_hash_eq_rowsel) and + * materializes nothing; an `in` on it still materializes the column for + * its index, and only that column. */ +static test_result_t test_use_materializes_once(void) { + ray_t* r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/m2/\" (table [k v w] (list (.idx.hash (% (* (til 200000) 7919) 100003)) (til 200000) (map (fn [j] (format \"t%\" j)) (til 200000)))) {compress: true})"); + if (r) ray_release(r); + r = ixr_eval("(set M (.db.splayed.get \"" IDX_TMP "/m2/\"))"); if (r) ray_release(r); + ray_enc_counters_reset(); + int64_t got = ixr_i64("(count (at (select {v: v w: w from: M where: (== k 4242)}) 'v))"); /* the select runs the filter; count of its column, not count(select) */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_I(got, ixr_i64("(count (where (== (% (* (til 200000) 7919) 100003) 4242)))")); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info M 'v) 'materialized) 1 0)"), 0); + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info M 'k) 'materialized) 1 0)"), 0); + ray_enc_counters_reset(); + got = ixr_i64("(count (at (select {v: v w: w from: M where: (in k [4242 4243])}) 'v))"); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_I(got, ixr_i64("(count (where (in (% (* (til 200000) 7919) 100003) [4242 4243])))")); + TEST_ASSERT_EQ_U(k.materialized, 1); + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info M 'v) 'materialized) 1 0)"), 0); + TEST_ASSERT_EQ_I(ixr_i64("(if (at (.idx.info M 'k) 'materialized) 1 0)"), 1); + PASS(); +} + +/* Parted (Task 6b minor 5): a parted table consults its per-segment indexes + * on generation 2 exactly as on generation 0: every site's consults and + * hits, the answers, and one materialization per segment HASH consult on + * generation 0 (the consult-set rule), so a segment that is pruned or not + * consulted is never decoded. At this HEAD no parted shape reaches a + * segment's index on generation 0 (the parted select answers by its scan; + * a bare FILTER graph over a constant table does not stream), so the + * counters are zero on both and generation 2 materializes nothing; when + * generation 0 starts consulting a segment, the same assertions require + * generation 2 to follow. */ +static test_result_t test_parted_segment_index(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int d = 1; d <= 3; d++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.set \"" IDX_TMP "/pt%d/2024.01.0%d/t/\" (table [k v] (list (.idx.hash (%% (* (til 70000) %d) 10007)) (til 70000))) {compress: %s})", + gen, d, d + 6, gen ? "true" : "false"); + ray_t* r = ixr_eval(q); if (r) ray_release(r); + } + /* a segment of each generation, loaded alone, records / attaches its HASH */ + TEST_ASSERT_EQ_I(ixr_i64("(if (== (at (.idx.info (at (.db.splayed.get \"" IDX_TMP "/pt0/2024.01.02/t/\") 'k)) 'kind) 'hash) 1 0)"), 1); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (.db.splayed.get \"" IDX_TMP "/pt2/2024.01.02/t/\") 'k) 'index)"), ray_sym_intern("hash", 4)); + static const char* const qs[] = { + "(sum (at (select {from: PT where: (and (== date 2024.01.01) (== k 42))}) 'v))", + "(sum (at (select {from: PT where: (== k 42)}) 'v))", + "(sum (at (select {from: PT where: (in k [1 42 77])}) 'v))", + "(sum (at (select {v: v from: PT where: (and (== date 2024.01.02) (== k 7))}) 'v))", + NULL, + }; + for (int i = 0; qs[i]; i++) { + uint64_t c[2][IDX_SITE__N], h[2][IDX_SITE__N], mat[2]; + int64_t cnt[2]; + for (int g = 0; g < 2; g++) { + char q[300]; + snprintf(q, sizeof q, "(set PT (.db.parted.get \"" IDX_TMP "/pt%d\" 't))", g * 2); + ray_t* r = ixr_eval(q); if (r) ray_release(r); + uint64_t c0[IDX_SITE__N], h0[IDX_SITE__N]; + memcpy(c0, ray_idx_consults, sizeof c0); memcpy(h0, ray_idx_hits, sizeof h0); + ray_enc_counters_reset(); + cnt[g] = ixr_i64(qs[i]); + ray_enc_counters_t k; ray_enc_counters_get(&k); + mat[g] = k.materialized; + for (int s = 0; s < IDX_SITE__N; s++) { c[g][s] = ray_idx_consults[s] - c0[s]; h[g][s] = ray_idx_hits[s] - h0[s]; } + } + TEST_ASSERT_FMT(cnt[0] != INT64_MIN && cnt[0] == cnt[1], "%s: %lld vs generation 0 %lld", qs[i], (long long)cnt[1], (long long)cnt[0]); + for (int s = 0; s < IDX_SITE__N; s++) + TEST_ASSERT_FMT(c[0][s] == c[1][s] && h[0][s] == h[1][s], "%s: site %d consults %llu/%llu hits %llu/%llu", qs[i], s, + (unsigned long long)c[0][s], (unsigned long long)c[1][s], (unsigned long long)h[0][s], (unsigned long long)h[1][s]); + TEST_ASSERT_FMT(mat[0] == 0 && mat[1] == c[0][IDX_SITE_FILTER_HASH], "%s: generation 2 materialized %llu, generation 0 consulted %llu segment HASHes", + qs[i], (unsigned long long)mat[1], (unsigned long long)c[0][IDX_SITE_FILTER_HASH]); + } + PASS(); +} + +/* Spec "Indexes / UNIQUE": unique-only and HASH+UNIQUE numeric columns from a + * heap source and from a generation-0 passenger source: the flag is known + * before materialization (metadata, nothing decoded) and .attr.get matches + * generation 0 after it. */ +static test_result_t test_unique_attr_get(void) { + ray_t* r = ixr_eval("(set U (table [u h] (list (.attr.set 'unique (til 70000)) (.attr.set 'unique (.idx.hash (* (til 70000) 3))))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/u0/\" U {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/u2/\" U {compress: true})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/up/\" (.db.splayed.get \"" IDX_TMP "/u0/\") {compress: true})"); if (r) ray_release(r); /* passenger source */ + static const char* const dirs[2] = { IDX_TMP "/u2/", IDX_TMP "/up/" }; + for (int d = 0; d < 2; d++) + for (int c = 0; c < 2; c++) { + const char* col = c ? "h" : "u"; + char q[300]; + snprintf(q, sizeof q, "(.db.splayed.get \"%s\")", dirs[d]); + ray_t* t = ixr_eval(q); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_meta_t m; + ray_enc_counters_reset(); + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern(col, 1), &m)); + TEST_ASSERT_EQ_I(m.enc != NULL, 1); /* generation 2, not decoded */ + TEST_ASSERT_FMT(m.unique, "%s %s: UNIQUE known from the header", dirs[d], col); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(t); + char q0[300], q2[300]; + snprintf(q0, sizeof q0, "(.attr.get (at (.db.splayed.get \"" IDX_TMP "/u0/\") '%s))", col); + snprintf(q2, sizeof q2, "(.attr.get (at (.db.splayed.get \"%s\") '%s))", dirs[d], col); + ray_t* fa = ixr_fmt(q0); ray_t* fb = ixr_fmt(q2); + TEST_ASSERT_FMT(ixr_same_fmt(fa, fb), "%s %s: .attr.get differs (%.*s vs %.*s)", dirs[d], col, + fa ? (int)ray_str_len(fa) : 5, fa ? ray_str_ptr(fa) : "error", + fb ? (int)ray_str_len(fb) : 5, fb ? ray_str_ptr(fb) : "error"); + if (fa) ray_release(fa); + if (fb) ray_release(fb); + } + PASS(); +} + +/* Spec "Normalized bytes: the same table saved from different allocations + * and domains writes byte-identical regions": one SYM HASH / PART table, + * once from the runtime domain and once from a FILE domain with another + * insertion order, saved into one target symfile. */ +static test_result_t test_normalized_domains(void) { + ray_t* r; + r = ixr_eval("(set N (table [k p] (list (.idx.hash (at ['zeta 'alpha 'mu 'omega] (% (* (til 6000) 7) 4))) (.attr.set 'parted (at ['b 'a 'c] (div (til 6000) 2000))))))"); + if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/nd1/\" N {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/ndA/\" N \"" IDX_TMP "/target.sym\" {compress: true})"); if (r) ray_release(r); + /* the generation-0 save drops the SYM PART (D1, #838): the FILE-domain + * copy re-attaches it over its own ids */ + r = ixr_eval("(set F (.db.splayed.get \"" IDX_TMP "/nd1/\"))"); if (r) ray_release(r); + TEST_ASSERT_TRUE(ixr_i64("(if (== (at (.idx.info (at F 'k)) 'kind) 'hash) 1 0)") == 1); + r = ixr_eval("(set F (table [k p] (list (at F 'k) (.attr.set 'parted (at F 'p)))))"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/ndB/\" F \"" IDX_TMP "/target.sym\" {compress: true})"); + if (r) ray_release(r); + static const char* const cols[2] = { "k", "p" }; + for (int c = 0; c < 2; c++) { + char pa[1200], pb[1200]; + TEST_ASSERT_TRUE(ix_live_path(IDX_TMP "/ndA/", cols[c], pa, sizeof pa)); /* the published generation's file */ + TEST_ASSERT_TRUE(ix_live_path(IDX_TMP "/ndB/", cols[c], pb, sizeof pb)); + size_t na = 0, nb = 0; ray_enc_hdr_t ea, eb; uint64_t fa, fb; + uint8_t* ra = ix_file_region(pa, &na, &ea, &fa); uint8_t* rb = ix_file_region(pb, &nb, &eb, &fb); + bool same = ra && rb && na == nb && memcmp(ra, rb, na) == 0; + free(ra); free(rb); + TEST_ASSERT_FMT(same, "column %s: regions differ", cols[c]); + TEST_ASSERT_TRUE(ea.index_kind == (c ? RAY_IDX_PART : RAY_IDX_HASH) && eb.index_kind == ea.index_kind); + } + PASS(); +} + +/* Spec "Indexes / order_sym": a PART ordered by `ts`, loaded from generation + * 2, takes the index-ordered as-of route (the IDX_SITE_ASOF_ORDERED counter); + * a name naming no column disables it and the results stay generation 0's. + * The key is I64: the as-of index variant needs a right side proven + * null-free, which a SYM column never is (ray_vec_may_have_nulls), so a SYM + * key takes no index route on either generation (#842). */ +static test_result_t test_order_sym_fast_path(void) { + ray_t* r; + r = ixr_eval("(set Q (xasc (xasc (table [id ts bid] (list (% (til 3000) 3) (til 3000) (as 'F64 (til 3000)))) ['id 'ts]) ['id 'ts]))"); + if (r) ray_release(r); + r = ixr_eval("(set L (table [id ts] (list [0 1 2] [100 200 2999])))"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/os0/\" Q {compress: false})"); if (r) ray_release(r); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/os2/\" Q {compress: true})"); if (r) ray_release(r); + /* the same table with order_sym naming no column */ + ray_t* q = ray_eval_str("Q"); + TEST_ASSERT_TRUE(q && !RAY_IS_ERR(q)); + ray_t* qc = ray_table_col(q, ray_sym_intern("id", 2)); + TEST_ASSERT_EQ_I(ray_index_kind(qc), RAY_IDX_PART); + int64_t keep = ray_index_payload(qc->index)->u.part.order_sym; + TEST_ASSERT_EQ_I(keep, ray_sym_intern("ts", 2)); + ray_index_payload(qc->index)->u.part.order_sym = ray_sym_intern("no_such_col", 11); + r = ixr_eval("(.db.splayed.set \"" IDX_TMP "/osn/\" Q {compress: true})"); if (r) ray_release(r); + ray_index_payload(qc->index)->u.part.order_sym = keep; + ray_release(q); + /* os2 and osn are generation-2 files that record the PART */ + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (.db.splayed.get \"" IDX_TMP "/os2/\") 'id) 'gen)"), 2); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (.db.splayed.get \"" IDX_TMP "/os2/\") 'id) 'index)"), ray_sym_intern("part", 4)); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (.db.splayed.get \"" IDX_TMP "/osn/\") 'id) 'gen)"), 2); + TEST_ASSERT_EQ_I(ixr_i64("(at (.idx.info (.db.splayed.get \"" IDX_TMP "/osn/\") 'id) 'index)"), ray_sym_intern("part", 4)); + /* 0: the in-memory Q (heap root, order_sym ts: the ordered route in this + * process); 1: the generation-0 load (the answer reference); 2: the + * generation-2 load; 3: the generation-2 load whose name block names no + * column. */ + static const char* const srcs[4] = { "Q", "(.db.splayed.get \"" IDX_TMP "/os0/\")", + "(.db.splayed.get \"" IDX_TMP "/os2/\")", "(.db.splayed.get \"" IDX_TMP "/osn/\")" }; + ray_t* out[4]; uint64_t ordered[4]; + for (int d = 0; d < 4; d++) { + char qs[400]; + snprintf(qs, sizeof qs, "(asof-join [id ts] L %s)", srcs[d]); + uint64_t c0 = ray_idx_consults[IDX_SITE_ASOF_ORDERED]; + out[d] = ixr_eval(qs); + TEST_ASSERT_TRUE(out[d] && !RAY_IS_ERR(out[d])); + ordered[d] = ray_idx_consults[IDX_SITE_ASOF_ORDERED] - c0; + } + TEST_ASSERT_TRUE(ordered[0] >= 1); /* the heap root: the ordered route */ + TEST_ASSERT_EQ_U(ordered[2], ordered[0]); /* generation 2: the same route through the name block */ + TEST_ASSERT_EQ_U(ordered[3], 0); /* no such column: off */ + for (int d = 0; d < 4; d++) { + if (d == 1) continue; + TEST_ASSERT_FMT(ixr_same_table(out[1], out[d]), "as-of %d differs from generation 0", d); + } + for (int d = 0; d < 4; d++) ray_release(out[d]); + PASS(); +} + + +/* ===== HASH distinctness in the reachability walk (Task 10b) ===== + * + * The validator checks distinct gkeys in its reachability walk: a key equal + * to group g's has g's home, so it lies in [home, p) of g's bucket p. The + * fabrications below insert groups in order by linear probing (as a builder + * does), with a repeated key placed where only that walk, its long-distance + * re-read, its sorted fallback or the pool pass can find it. */ + +/* ---- P6b: the DICT region (spec "Index region", "Index validation") ---- */ + +/* A DICT source over 8 rows: codes 0 1 0 2 1 0 2 3, first_occ 0 1 3 7, + * entries "a", "bb", "", "dddd" (the empty entry is the in-band null). */ +static const int32_t dx_codes[8] = { 0, 1, 0, 2, 1, 0, 2, 3 }; +static const int32_t dx_focc[4] = { 0, 1, 3, 7 }; +static const uint64_t dx_offs[4] = { 0, 1, 3, 3 }; +static const char dx_bytes[] = "abbdddd"; /* 7 bytes */ +static ray_enc_dict_src_t dx_src(void) { + return (ray_enc_dict_src_t){ .len = 8, .n_distinct = 4, .codes = dx_codes, .first_occ = dx_focc, + .offs = dx_offs, .bytes = dx_bytes, .bytes_len = 7 }; +} +/* The region of s, written to a file and read back into a 32-aligned + * buffer (*n bytes; the caller frees). */ +static uint8_t* dx_region(const ray_enc_dict_src_t* s, size_t* n, ray_t** err) { + FILE* f = fopen(ray_test_tmp(IDX_TMP "/dr"), "wb"); + uint64_t nb = 0; + *err = f ? ray_enc_dict_write(f, s, &nb) : ray_error("io", NULL); + if (f) fclose(f); + if (*err) return NULL; + size_t got = 0; + uint8_t* raw = ix_slurp(ray_test_tmp(IDX_TMP "/dr"), &got); + if (!raw || got != nb) { free(raw); return NULL; } + uint8_t* b = aligned_alloc(32, (got + 31) & ~(size_t)31); + memcpy(b, raw, got); free(raw); + *n = got; + return b; +} +/* Layout: root fields, children at pad32 offsets from 96, region end. */ +static test_result_t test_dict_write_layout(void) { + ray_enc_dict_src_t s = dx_src(); + size_t n; ray_t* err; + uint8_t* b = dx_region(&s, &n, &err); + TEST_ASSERT_NULL(err); + TEST_ASSERT_NOT_NULL(b); + TEST_ASSERT_EQ_I((int8_t)b[0], RAY_STR); + TEST_ASSERT_EQ_I(rd64(b + 8), 8); + ray_enc_idx_dict_t d; memcpy(&d, b + 16, sizeof d); + TEST_ASSERT_EQ_I(d.codes, 96); + TEST_ASSERT_EQ_I(d.first_occ, ix_p32(96 + 8 * 4)); + TEST_ASSERT_EQ_I(d.offs, ix_p32(d.first_occ + 4 * 4)); + TEST_ASSERT_EQ_I(d.bytes, ix_p32(d.offs + 5 * 8)); + TEST_ASSERT_EQ_I(d.n_distinct, 4); + TEST_ASSERT_EQ_U(d.bytes_len, 7); + for (int i = 16 + 48; i < 96; i++) TEST_ASSERT_EQ_I(b[i], 0); /* kind-area tail, root padding */ + TEST_ASSERT_EQ_U(n, ix_p32((uint64_t)d.bytes + 7)); + uint64_t last; memcpy(&last, b + d.offs + 4 * 8, 8); + TEST_ASSERT_EQ_U(last, 7); /* the terminal offset */ + TEST_ASSERT_TRUE(memcmp(b + d.bytes, "abbdddd", 7) == 0); + free(b); + PASS(); +} + +/* The region validates; the view points at its children. */ +static test_result_t test_dict_view_fields(void) { + ray_enc_dict_src_t s = dx_src(); + size_t n; ray_t* err; + uint8_t* b = dx_region(&s, &n, &err); + TEST_ASSERT_NULL(err); + ray_enc_dict_view_t v; + ray_enc_dict_parse(b, &v); + TEST_ASSERT_EQ_I(v.n_distinct, 4); + TEST_ASSERT_EQ_I(v.len, 8); + TEST_ASSERT_TRUE(memcmp(v.codes, dx_codes, sizeof dx_codes) == 0); + TEST_ASSERT_TRUE(memcmp(v.first_occ, dx_focc, sizeof dx_focc) == 0); + TEST_ASSERT_EQ_U(v.offs[4], 7); + free(b); + PASS(); +} + +/* The writer refuses a source no validator would accept: nyi naming DICT. */ +static test_result_t test_dict_write_rejects(void) { + ray_enc_dict_src_t s = dx_src(); + FILE* f = fopen(ray_test_tmp(IDX_TMP "/dw"), "wb"); + uint64_t nb; + s.n_distinct = 0; + ray_t* e = ray_enc_dict_write(f, &s, &nb); + TEST_ASSERT_TRUE(e && strcmp(ray_err_code(e), "nyi") == 0 && strstr(ray_error_msg(), "DICT")); + ray_error_free(e); + s = dx_src(); s.n_distinct = 9; /* above len */ + e = ray_enc_dict_write(f, &s, &nb); + TEST_ASSERT_TRUE(e && strcmp(ray_err_code(e), "nyi") == 0); ray_error_free(e); + s = dx_src(); s.bytes_len = 2; /* the last entry starts past the bytes */ + e = ray_enc_dict_write(f, &s, &nb); + TEST_ASSERT_TRUE(e && strcmp(ray_err_code(e), "nyi") == 0); ray_error_free(e); + s = dx_src(); s.len = (int64_t)INT32_MAX + 1; + e = ray_enc_dict_write(f, &s, &nb); + TEST_ASSERT_TRUE(e && strcmp(ray_err_code(e), "nyi") == 0); ray_error_free(e); + fclose(f); + PASS(); +} + +const test_entry_t encidx_entries[] = { + { "idxval/write_hash_layout", test_write_hash_layout, ix_setup, ix_teardown }, + { "idxval/write_name_block", test_write_name_block, ix_setup, ix_teardown }, + { "idxval/write_sort_bloom", test_write_sort_bloom, ix_setup, ix_teardown }, + { "idxval/write_rejects", test_write_rejects, ix_setup, ix_teardown }, + { "idxval/write_normalized", test_write_normalized, ix_setup, ix_teardown }, + { "idxval/trusted_order", test_trusted_order, ix_setup, ix_teardown }, + { "idxval/write_sym_part", test_write_sym_part, ix_setup, ix_teardown }, + { "idxval/write_core_count", test_write_core_count, ix_setup, ix_teardown }, + { "idxval/write_zero_fill", test_write_zero_fill, ix_setup, ix_teardown }, + { "idxval/view_fields", test_view_fields, ix_setup, ix_teardown }, + { "idxval/str_word_collision", test_str_word_collision, ix_setup, ix_teardown }, + { "idxval/view_empty", test_view_empty, ix_setup, ix_teardown }, + { "idxval/view_engine_matrix", test_view_engine_matrix, ix_setup, ix_teardown }, + { "idxval/parse_hash_probes", test_parse_hash_probes, ix_setup, ix_teardown }, + { "idxval/parse_part_order_sym", test_parse_part_order_sym, ix_setup, ix_teardown }, + { "idxval/parse_oom_frees", test_parse_oom_frees, ix_setup, ix_teardown }, + { "idxval/file_has_region", test_file_has_region, ix_setup, ix_teardown }, + { "idxval/unique_and_stale", test_unique_and_stale, ix_setup, ix_teardown }, + { "idxval/save_nyi_names_kind", test_save_nyi_names_kind, ix_setup, ix_teardown }, + { "idxval/save_override_kind", test_save_override_kind, ix_setup, ix_teardown }, + { "idxval/golden_emit", test_idx_golden_emit, ix_setup, ix_teardown }, + { "idxval/golden_match", test_idx_golden_match, ix_setup, ix_teardown }, + { "idxval/materialize_attaches", test_materialize_attaches, ix_setup, ix_teardown }, + { "idxval/materialize_all_kinds", test_materialize_all_kinds, ix_setup, ix_teardown }, + { "idxval/materialize_unique", test_materialize_unique, ix_setup, ix_teardown }, + { "idxval/parse_oom_retry", test_parse_oom_retry, ix_setup, ix_teardown }, + { "idxval/materialize_oom_sweep", test_materialize_oom_sweep, ix_setup, ix_teardown }, + { "idxval/retained_index_outlives_table", test_retained_index_outlives_table, ix_setup, ix_teardown }, + { "idxval/concurrent_index", test_concurrent_index, ix_setup, ix_teardown }, + { "idxval/golden_read", test_idx_golden_read, ix_setup, ix_teardown }, + { "idxval/consult_routes", test_consult_routes, ixr_setup, ixr_teardown }, + { "idxval/consult_dir_unchanged", test_consult_dir_unchanged, ixr_setup, ixr_teardown }, + { "idxval/index_route_oom", test_index_route_oom, ixr_setup, ixr_teardown }, + { "idxval/hash_region_probe", test_hash_region_probe, ixr_setup, ixr_teardown }, + { "idxval/sym_rebuild_remap", test_sym_rebuild_remap, ix_setup, ix_teardown }, + { "idxval/sym_part_rebuild", test_sym_part_rebuild, ix_setup, ix_teardown }, + { "idxval/encoded_keep_copies", test_encoded_keep_copies, ix_setup, ix_teardown }, + { "idxval/drop_records_none", test_drop_records_none, ix_setup, ix_teardown }, + { "idxval/reload_keeps_kind", test_reload_keeps_kind, ix_setup, ix_teardown }, + { "idxval/passenger_order_absent", test_passenger_order_absent, ix_setup, ix_teardown }, + { "idxval/admitted_roundtrip", test_admitted_roundtrip, ix_setup, ix_teardown }, + { "idxval/admission_through_all", test_admission_through_all, ix_setup, ix_teardown }, + { "idxval/stale_root_chunk_zone", test_stale_root_chunk_zone, ixr_setup, ixr_teardown }, + { "idxval/sym_splay_kept", test_sym_splay_kept, ixr_setup, ixr_teardown }, + { "idxval/sym_stale_rebuild", test_sym_stale_rebuild, ixr_setup, ixr_teardown }, + { "idxval/sym_stale_part_unbuildable", test_sym_stale_part_unbuildable, ix_setup, ix_teardown }, + { "idxval/sym_hash_null_key", test_sym_hash_null_key, ixr_setup, ixr_teardown }, + { "idxval/converter_parity", test_converter_parity, ixr_setup, ixr_teardown }, + { "idxval/converter_dict_boundary", test_converter_dict_boundary, ixr_setup, ixr_teardown }, + { "idxval/use_materializes_once", test_use_materializes_once, ixr_setup, ixr_teardown }, + { "idxval/parted_segment_index", test_parted_segment_index, ixr_setup, ixr_teardown }, + { "idxval/unique_attr_get", test_unique_attr_get, ixr_setup, ixr_teardown }, + { "idxval/normalized_domains", test_normalized_domains, ixr_setup, ixr_teardown }, + { "idxval/order_sym_fast_path", test_order_sym_fast_path, ixr_setup, ixr_teardown }, + { "idxval/dict_write_layout", test_dict_write_layout, ix_setup, ix_teardown }, + { "idxval/dict_view_fields", test_dict_view_fields, ix_setup, ix_teardown }, + { "idxval/dict_write_rejects", test_dict_write_rejects, ix_setup, ix_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_encstr.c b/test/test_encstr.c new file mode 100644 index 000000000..2511a7f9e --- /dev/null +++ b/test/test_encstr.c @@ -0,0 +1,2510 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "core/runtime.h" +#include "store/enc.h" +#include "store/encfmt.h" +#include "store/fsst.h" +#include "store/col.h" +#include "store/encw.h" +#include "store/enccol.h" +#include "core/pool.h" /* the first-touch race */ +#include "core/timer.h" /* its barrier deadline */ +#include "store/encidx.h" /* ray_enc_idx_dict_t, ray_enc_dict_validate */ +#include "store/colrange.h" +#include "vec/str.h" +#include "table/table.h" +#include "lang/env.h" +#include "lang/format.h" +#include "store/splay.h" +#include "ops/idxop.h" +#include "ops/internal.h" /* ray_exec_test_str_sel */ +#include +#include +#include + +#define ST_TMP "/tmp/rayforce_encstr" /* always through ray_test_tmp (per-process root) */ +/* Buffers a test owns, freed in teardown so an early-returning assertion + * leaks nothing. */ +static ray_enc_buf_t st_buf; +static uint8_t* st_mem; /* malloc'd scratch */ +static ray_t* st_held[8]; /* objects (or errors) a test holds: st_hold */ +static ray_col_src_t st_src; /* a bound source (st_src_on) */ +static bool st_src_on; +static ray_col_scratch_t st_sc; /* a range-read scratch (st_sc_on) */ +static bool st_sc_on; +static ray_t* st_hold(ray_t* x) { + for (int i = 0; i < 8; i++) if (!st_held[i]) { st_held[i] = x; return x; } + abort(); +} +/* x is no longer held (the caller releases it, or holds `by` instead). */ +static void st_unhold(ray_t* x, ray_t* by) { + for (int i = 0; i < 8; i++) if (st_held[i] == x) { st_held[i] = by; return; } +} +/* Before the heap goes: the scratch, the source, then the held objects. */ +static void st_release_held(void) { + if (st_sc_on) { ray_col_scratch_free(&st_sc); st_sc_on = false; } + if (st_src_on) { ray_col_src_release(&st_src); st_src_on = false; } + for (int i = 7; i >= 0; i--) { + if (st_held[i] && RAY_IS_ERR(st_held[i])) ray_error_free(st_held[i]); + else if (st_held[i]) ray_release(st_held[i]); + st_held[i] = NULL; + } +} +static void st_setup(void) { + ray_heap_init(); (void)ray_sym_init(); + (void)ray_test_rm_rf(ray_test_tmp(ST_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(ST_TMP)); +} +static void st_teardown(void) { + ray_enc_buf_free(&st_buf); st_buf = (ray_enc_buf_t){0}; + free(st_mem); st_mem = NULL; + st_release_held(); + ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(ST_TMP)); ray_sym_destroy(); ray_heap_destroy(); +} + +static test_result_t test_strdict_body(void) { + uint64_t codes[RAY_ENC_VEC], out[RAY_ENC_VEC]; + for (int i = 0; i < RAY_ENC_VEC; i++) codes[i] = (uint64_t)((i / 200) % 4); + ray_enc_buf_t* b = &st_buf; + TEST_ASSERT_TRUE(ray_enc_strdict_write(codes, RAY_ENC_VEC, b)); + TEST_ASSERT_EQ_I((int64_t)b->len, ray_enc_strdict_size(codes, RAY_ENC_VEC)); + TEST_ASSERT_EQ_I(b->p[0], RAY_ENC_RLE); /* codes child: runs */ + ray_enc_strdict_read(b->p, b->len, RAY_ENC_VEC, out); + TEST_ASSERT_TRUE(memcmp(codes, out, sizeof codes) == 0); + PASS(); +} + +static const char* const g_urls[] = { + "http://example.com/a/b?c=1", "http://example.com/a/b?c=2", "https://shop.example.org/item/42", + "", "x", "http://example.com/", "a fairly long free text title with words", +}; +#define N_URLS 7 + +static void st_strings(int n, const char** s, uint32_t* len) { + for (int i = 0; i < n; i++) { s[i] = g_urls[(i * 5) % N_URLS]; len[i] = (uint32_t)strlen(s[i]); } +} + +static test_result_t test_fsst_body(void) { + const char* s[RAY_ENC_VEC]; uint32_t len[RAY_ENC_VEC]; + st_strings(RAY_ENC_VEC, s, len); + ray_fsst_table_t t; + TEST_ASSERT_EQ_I(ray_fsst_train((const uint8_t* const*)s, len, RAY_ENC_VEC, &t), 1); + TEST_ASSERT_TRUE(t.n > 0); + ray_fsst_index_t ix; ray_fsst_index_build(&t, &ix); + uint64_t sum = 0; for (int i = 0; i < RAY_ENC_VEC; i++) sum += len[i]; + uint8_t* buf = st_mem = malloc(2 * sum + 1); + TEST_ASSERT_NOT_NULL(buf); + uint64_t clen[RAY_ENC_VEC], xlen[RAY_ENC_VEC]; + uint64_t total = ray_enc_fsst_encode(&t, &ix, s, len, RAY_ENC_VEC, buf, clen); + TEST_ASSERT_TRUE(total < sum); + ray_enc_buf_t* b = &st_buf; + TEST_ASSERT_TRUE(ray_enc_fsst_write(clen, RAY_ENC_VEC, buf, total, b)); + TEST_ASSERT_EQ_I((int64_t)b->len, ray_enc_fsst_size(clen, RAY_ENC_VEC, total)); + TEST_ASSERT_EQ_I((int64_t)(b->len & 7), 0); + const uint8_t* bytes; + uint64_t c2[RAY_ENC_VEC]; + ray_enc_fsst_parse(b->p, b->len, RAY_ENC_VEC, &t, c2, xlen, &bytes); + uint64_t at = 0; + for (int i = 0; i < RAY_ENC_VEC; i++) { + TEST_ASSERT_EQ_U(c2[i], clen[i]); + TEST_ASSERT_EQ_U(xlen[i], len[i]); + char out[64]; + TEST_ASSERT_EQ_I(ray_fsst_decode(&t, bytes + at, (uint32_t)c2[i], (uint8_t*)out), (int64_t)len[i]); + TEST_ASSERT_TRUE(memcmp(out, s[i], len[i]) == 0); + at += c2[i]; + } + TEST_ASSERT_EQ_U(at, total); + PASS(); +} + +/* ray_fsst_train's verdict (D3): no string bytes trains no table. */ +static test_result_t test_fsst_train_verdict(void) { + const uint8_t* s[3] = { (const uint8_t*)"", (const uint8_t*)"", (const uint8_t*)"" }; + uint32_t len[3] = { 0, 0, 0 }; + ray_fsst_table_t t; memset(&t, 0xAB, sizeof t); + TEST_ASSERT_EQ_I(ray_fsst_train(s, len, 3, &t), 0); + TEST_ASSERT_EQ_I(t.n, 0); + TEST_ASSERT_EQ_I(ray_fsst_train(s, len, 0, &t), 0); + TEST_ASSERT_EQ_I(t.n, 0); + const uint8_t* s1[1] = { (const uint8_t*)"abc" }; uint32_t l1[1] = { 3 }; + TEST_ASSERT_EQ_I(ray_fsst_train(s1, l1, 1, &t), 1); + TEST_ASSERT_TRUE(t.n > 0); + PASS(); +} + +/* ---- the STR writer (Task 2) ---- */ +#define STP(p) ray_test_tmp(ST_TMP p) + +static ray_t* str_col(int64_t n, const char* (*gen)(int64_t, char*)) { + ray_t* v = ray_vec_new(RAY_STR, n); + char buf[256]; + for (int64_t i = 0; i < n; i++) { const char* s = gen(i, buf); v = ray_str_vec_append(v, s, strlen(s)); } + return v; +} +static const char* gen_lowcard(int64_t i, char* b) { snprintf(b, 64, "category number %lld long", (long long)(i % 37)); return b; } +static const char* gen_urls(int64_t i, char* b) { snprintf(b, 200, "https://www.example.com/path/%lld/item?id=%lld&ref=search", (long long)(i % 5000), (long long)(i * 7919 % 100003)); return b; } +static const char* gen_nullish(int64_t i, char* b) { if (i % 9 == 0) return ""; return gen_lowcard(i, b); } +/* High cardinality in the low-cardinality strings' shape: no dictionary chunk, + * but an FSST table trained on gen_lowcard compresses them. */ +static const char* gen_hc(int64_t i, char* b) { snprintf(b, 64, "category number %lld long", (long long)i); return b; } + +/* `path` is already wrapped by ray_test_tmp. */ +static int st_desc_enc(const char* path, int64_t vec, ray_enc_desc_t* out) { + FILE* f = fopen(path, "rb"); if (!f) return -1; + int64_t c = vec / 64, j = vec % 64; + uint64_t off; fseek(f, 96 + c * 64, SEEK_SET); if (fread(&off, 8, 1, f) != 1) { fclose(f); return -1; } + ray_enc_desc_t d; fseek(f, (long)(off + (uint64_t)j * 48), SEEK_SET); + int ok = fread(&d, 1, 48, f) == 48; + fclose(f); + if (!ok) return -1; + if (out) *out = d; + return d.encoding; +} +static ray_enc_hdr_t st_hdr(const char* path) { + ray_enc_hdr_t eh; memset(&eh, 0, sizeof eh); + FILE* f = fopen(path, "rb"); if (!f) return eh; + fseek(f, 32, SEEK_SET); if (fread(&eh, 1, 64, f) != 64) memset(&eh, 0, sizeof eh); + fclose(f); + return eh; +} +static ray_enc_dirent_t st_dirent(const char* path, int64_t c) { + ray_enc_dirent_t de; memset(&de, 0, sizeof de); + FILE* f = fopen(path, "rb"); if (!f) return de; + fseek(f, 96 + c * 64, SEEK_SET); if (fread(&de, 1, 64, f) != 64) memset(&de, 0, sizeof de); + fclose(f); + return de; +} + +/* Low cardinality: STR_DICT with code bounds; directory bounds present. */ +static test_result_t test_writer_strdict(void) { + ray_t* v = str_col(70000, gen_nullish); + ray_err_t e = ray_col_save_gen(v, STP("/sd"), 2); + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_OK); + ray_enc_desc_t d; + TEST_ASSERT_EQ_I(st_desc_enc(STP("/sd"), 0, &d), RAY_ENC_STR_DICT); + TEST_ASSERT_FALSE(d.flags & RAY_ENC_STAT_ABSENT); + TEST_ASSERT_TRUE(d.min >= 1 && d.max <= 37 && d.min <= d.max); /* "" (row 0) is code 0; the bounds cover non-null rows */ + TEST_ASSERT_EQ_I(st_desc_enc(STP("/sd"), 68, NULL), RAY_ENC_STR_DICT); /* chunk 1 reuses the entries */ + ray_enc_dirent_t de = st_dirent(STP("/sd"), 0); + TEST_ASSERT_FALSE(de.flags & RAY_ENC_STAT_ABSENT); + TEST_ASSERT_TRUE(de.min >= 1 && de.max <= 37 && de.min <= de.max); + ray_enc_hdr_t eh = st_hdr(STP("/sd")); + TEST_ASSERT_TRUE(eh.side_off != 0); + /* rule 1: the 37 entries over 12 bytes once; no RAW / FSST rows here */ + uint64_t want = 0; char b[64]; + for (int k = 0; k < 37; k++) { uint64_t l = (uint64_t)snprintf(b, sizeof b, "category number %d long", k); if (l > 12) want += l; } + TEST_ASSERT_EQ_U(eh.str_pool_bytes, want); + PASS(); +} + +/* URL-like strings: FSST; no statistics; the FSST_TABLE side entry. */ +static test_result_t test_writer_fsst(void) { + ray_t* v = str_col(3000, gen_urls); + ray_err_t e = ray_col_save_gen(v, STP("/fs"), 2); + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_OK); + ray_enc_desc_t d; + TEST_ASSERT_EQ_I(st_desc_enc(STP("/fs"), 0, &d), RAY_ENC_FSST); + TEST_ASSERT_TRUE(d.flags & RAY_ENC_STAT_ABSENT); + ray_enc_dirent_t de = st_dirent(STP("/fs"), 0); + TEST_ASSERT_TRUE(de.flags & RAY_ENC_STAT_ABSENT); + ray_enc_hdr_t eh = st_hdr(STP("/fs")); + uint64_t want = 0; char b[256]; + for (int64_t i = 0; i < 3000; i++) { uint64_t l = strlen(gen_urls(i, b)); if (l > 12) want += l; } + TEST_ASSERT_EQ_U(eh.str_pool_bytes, want); /* rule 2 */ + FILE* f = fopen(STP("/fs"), "rb"); TEST_ASSERT_NOT_NULL(f); + uint8_t tb[32]; fseek(f, (long)eh.side_off, SEEK_SET); + size_t got = fread(tb, 1, 32, f); fclose(f); + TEST_ASSERT_EQ_I((int)got, 32); + uint32_t ne; memcpy(&ne, tb, 4); uint16_t k0; memcpy(&k0, tb + 8, 2); + TEST_ASSERT_EQ_I(ne, 1); + TEST_ASSERT_EQ_I(k0, RAY_ENC_SIDE_FSST_TABLE); + PASS(); +} + +/* Two side entries in kind order, 32-aligned: chunk 0 is a STR_DICT chunk + * (low cardinality), chunk 1 a plain one (gen_hc, FSST). A STR_DICT chunk + * holding an all-null vector (CONST) has no code bounds. */ +static test_result_t test_writer_two_entries(void) { + int64_t n = 65536 + 4096; + ray_t* v = ray_vec_new(RAY_STR, n); + char b[256]; + for (int64_t i = 0; i < n; i++) { + const char* s = i < 1024 ? "" : i < 65536 ? gen_lowcard(i, b) : gen_hc(i, b); + v = ray_str_vec_append(v, s, strlen(s)); + } + ray_err_t e = ray_col_save_gen(v, STP("/two"), 2); + ray_release(v); + TEST_ASSERT_EQ_I(e, RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(STP("/two"), 0, NULL), RAY_ENC_CONST); /* all null */ + ray_enc_desc_t d; + TEST_ASSERT_EQ_I(st_desc_enc(STP("/two"), 1, &d), RAY_ENC_STR_DICT); + TEST_ASSERT_FALSE(d.flags & RAY_ENC_STAT_ABSENT); /* the vector keeps its bounds (D5) */ + TEST_ASSERT_EQ_I(st_desc_enc(STP("/two"), 64, NULL), RAY_ENC_FSST); + TEST_ASSERT_TRUE(st_dirent(STP("/two"), 0).flags & RAY_ENC_STAT_ABSENT); /* CONST in the chunk */ + TEST_ASSERT_TRUE(st_dirent(STP("/two"), 1).flags & RAY_ENC_STAT_ABSENT); + ray_enc_hdr_t eh = st_hdr(STP("/two")); + FILE* f = fopen(STP("/two"), "rb"); + TEST_ASSERT_NOT_NULL(f); + fseek(f, (long)eh.side_off, SEEK_SET); + uint8_t tb[64]; size_t got = fread(tb, 1, 56, f); fclose(f); + TEST_ASSERT_EQ_I((int)got, 56); + uint32_t ne; memcpy(&ne, tb, 4); + TEST_ASSERT_EQ_I(ne, 2); + uint16_t k0, k1; memcpy(&k0, tb + 8, 2); memcpy(&k1, tb + 32, 2); + TEST_ASSERT_EQ_I(k0, RAY_ENC_SIDE_STR_DICT); TEST_ASSERT_EQ_I(k1, RAY_ENC_SIDE_FSST_TABLE); + uint64_t o0, o1; memcpy(&o0, tb + 16, 8); memcpy(&o1, tb + 40, 8); + TEST_ASSERT_EQ_U(o0, 64); + TEST_ASSERT_EQ_U(o1 % 32, 0); + PASS(); +} + +/* ---- the reader (Task 3): side entries, statistics, vector-scope decode ---- */ + +/* `path` is already wrapped by ray_test_tmp. */ +static bool st_read(const char* path, long off, void* b, size_t n) { + FILE* f = fopen(path, "rb"); + if (!f) return false; + bool ok = fseek(f, off, SEEK_SET) == 0 && fread(b, 1, n, f) == n; + fclose(f); + return ok; +} +#define ST_READ(path, off, b, n) TEST_ASSERT_TRUE(st_read((path), (long)(off), (b), (n))) +static char st_msg[512]; /* the last st_mat / st_scan error's message */ +/* The error code of loading `path` and materializing it ("" when both pass). */ +static const char* st_mat(const char* path) { + static char code[16]; + st_msg[0] = 0; + ray_error_clear(); + ray_t* c = ray_col_mmap(path); + if (!c || RAY_IS_ERR(c)) { + snprintf(code, sizeof code, "%s", c ? ray_err_code(c) : "null"); + snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (c) ray_error_free(c); + return code; + } + ray_t* m = ray_enccol_materialize(c); + snprintf(code, sizeof code, "%s", RAY_IS_ERR(m) ? ray_err_code(m) : ""); + if (RAY_IS_ERR(m)) snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (RAY_IS_ERR(m)) ray_error_free(m); + ray_release(c); + return code; +} +/* The error code of loading `path` and range-reading every vector (vector + * scope: each STR_DICT / FSST vector decodes alone), "" when both pass. */ +static const char* st_scan(const char* path) { + static char code[16]; + st_msg[0] = 0; + ray_error_clear(); + ray_t* c = ray_col_mmap(path); + if (!c || RAY_IS_ERR(c)) { + snprintf(code, sizeof code, "%s", c ? ray_err_code(c) : "null"); + snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (c) ray_error_free(c); + return code; + } + ray_col_src_t src; + ray_t* err = ray_col_src_bind(c, &src); + if (!err) { + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + for (int64_t r = 0; r < src.len && !err; ) { + ray_col_range_t rv; + err = ray_col_range(&src, r, src.len - r, &sc, &rv); + if (!err) r += rv.n; + } + ray_col_scratch_free(&sc); ray_col_src_release(&src); + } + snprintf(code, sizeof code, "%s", err ? ray_err_code(err) : ""); + if (err) snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (err) ray_error_free(err); + ray_release(c); + return code; +} + +/* Range reads decode each vector alone (vector scope): chunk 0 is a + * STR_DICT chunk ("" every 9th row, in band), chunk 1 FSST. Nothing is + * materialized, and range reads leave hash32 0. */ +static test_result_t test_range_reads_str(void) { + const char* p = STP("/rr"); + ray_t* v = ray_vec_new(RAY_STR, 70000); + char b[256]; + for (int64_t i = 0; i < 70000; i++) { const char* s = i >= 65536 ? gen_hc(i, b) : gen_nullish(i, b); v = ray_str_vec_append(v, s, strlen(s)); } + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 64, NULL), RAY_ENC_FSST); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_col_src_t src; TEST_ASSERT_NULL(ray_col_src_bind(c, &src)); + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + ray_enc_counters_reset(); + bool same = true; int64_t bad = -1; + for (int64_t r = 0; r < 70000 && same; ) { + ray_col_range_t rv; + ray_t* err = ray_col_range(&src, r, 70000 - r, &sc, &rv); + if (err) { ray_error_free(err); same = false; bad = r; break; } + for (int64_t k = 0; k < rv.n && same; k++) { + size_t lb; const char* want = ray_str_vec_get(v, r + k, &lb); + const ray_str_t* d = (const ray_str_t*)rv.data + k; + if (d->len != lb || (lb && memcmp(ray_str_t_ptr(d, rv.str_pool), want, lb) != 0) || + (lb > RAY_STR_INLINE_MAX && d->hash32 != 0)) { same = false; bad = r + k; } + } + r += rv.n; + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + ray_col_scratch_free(&sc); ray_col_src_release(&src); ray_release(c); ray_release(v); + TEST_ASSERT_FMT(same, "row %lld differs", (long long)bad); + TEST_ASSERT_EQ_U(k.materialized, 0); + PASS(); +} + +/* Ruling 3-1: in vector scope a STR_DICT vector copies each distinct pooled + * entry once and its rows share the offset. One 40-byte entry on every row + * of two vectors (forced STR_DICT: selection would take CONST): each range + * read needs 40 pool bytes, every row points at them, hash32 stays 0. */ +static test_result_t test_range_shared_entry(void) { + const char* p = STP("/se"); + static const char ent[] = "a forty byte entry repeated on every row"; /* 40 bytes */ + TEST_ASSERT_EQ_U(sizeof ent - 1, 40); + ray_t* v = ray_vec_new(RAY_STR, 2048); + for (int i = 0; i < 2048; i++) v = ray_str_vec_append(v, ent, 40); + ray_encw_test_force_str(RAY_ENC_STR_DICT); + ray_err_t se = ray_col_save_gen(v, p, 2); + ray_encw_test_force_str(-1); + ray_release(v); + TEST_ASSERT_EQ_I(se, RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 1, NULL), RAY_ENC_STR_DICT); + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + uint64_t pb0 = 0, pb1 = 0; + ray_t* e0 = ray_enccol_vec_pool_bytes(ray_enccol_of(c), 0, &pb0); + ray_t* e1 = ray_enccol_vec_pool_bytes(ray_enccol_of(c), 1, &pb1); + bool sized = !e0 && !e1 && pb0 == 40 && pb1 == 40; + if (e0) ray_error_free(e0); + if (e1) ray_error_free(e1); + ray_col_src_t src; ray_t* be = ray_col_src_bind(c, &src); + if (be) { ray_error_free(be); ray_release(c); FAIL("bind"); } + ray_col_scratch_t sc; ray_col_scratch_init(&sc); + bool same = true, shared = true, nohash = true, cap40 = true; int64_t nread = 0; + for (int64_t r = 0; r < 2048; ) { + ray_col_range_t rv; + ray_t* err = ray_col_range(&src, r, 2048 - r, &sc, &rv); + if (err) { ray_error_free(err); same = false; break; } + cap40 = cap40 && sc.pool_cap == 40; + const ray_str_t* d = (const ray_str_t*)rv.data; + for (int64_t k = 0; k < rv.n; k++) { + if (d[k].len != 40 || memcmp(ray_str_t_ptr(&d[k], rv.str_pool), ent, 40) != 0) same = false; + if (d[k].pool_off != d[0].pool_off) shared = false; + if (d[k].hash32 != 0) nohash = false; + } + r += rv.n; nread += rv.n; + } + ray_col_scratch_free(&sc); ray_col_src_release(&src); ray_release(c); + TEST_ASSERT_TRUE(sized); /* the entry's bytes once per vector */ + TEST_ASSERT_EQ_I(nread, 2048); + TEST_ASSERT_TRUE(same); + TEST_ASSERT_TRUE(shared); + TEST_ASSERT_TRUE(nohash); + TEST_ASSERT_TRUE(cap40); /* the scratch pool is sized from them */ + PASS(); +} + +/* Side-entry and statistics reject rules (before any lookup / decode). */ +static test_result_t test_strdict_lookup(void) { + const char* p = STP("/sr"); + ray_t* v = str_col(5000, gen_lowcard); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + ray_enc_hdr_t eh = st_hdr(p); + const long e0 = (long)eh.side_off + 32; /* the STR_DICT entry (the only one) */ + TEST_ASSERT_FMT(strcmp(st_mat(p), "") == 0, "materialize: %s", st_msg); + uint32_t n; ST_READ(p, e0, &n, 4); + TEST_ASSERT_EQ_U(n, 37); + /* the lookup of a good file finds its codes (first occurrence) */ + { + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + int64_t c1 = 7, cx = 7; + ray_t* e1 = ray_enccol_strdict_code(ray_enccol_of(c), "category number 1 long", 22, &c1); + ray_t* e2 = ray_enccol_strdict_code(ray_enccol_of(c), "category number 99 long", 23, &cx); + ray_release(c); + TEST_ASSERT_NULL(e1); TEST_ASSERT_NULL(e2); + TEST_ASSERT_EQ_I(c1, 1); TEST_ASSERT_EQ_I(cx, -1); + } + ray_release(v); + PASS(); +} + +/* ray_encw_test_force_str wins over ray_encw_test_force on STR vectors. */ +static test_result_t test_force_str_wins(void) { + ray_t* v = str_col(3000, gen_urls); /* unequal strings: CONST does not apply */ + ray_encw_test_force(RAY_ENC_CONST); + ray_err_t e1 = ray_col_save_gen(v, STP("/fw1"), 2); + ray_encw_test_force_str(RAY_ENC_RAW); + ray_err_t e2 = ray_col_save_gen(v, STP("/fw2"), 2); + ray_encw_test_force(RAY_ENC_RAW); + ray_encw_test_force_str(RAY_ENC_FSST); + ray_err_t e3 = ray_col_save_gen(v, STP("/fw3"), 2); + ray_encw_test_force_str(-1); ray_encw_test_force(-1); + ray_release(v); + TEST_ASSERT_TRUE(e1 != RAY_OK); /* the general force alone: nyi */ + TEST_ASSERT_EQ_I(e2, RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(STP("/fw2"), 0, NULL), RAY_ENC_RAW); + TEST_ASSERT_EQ_I(e3, RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(STP("/fw3"), 0, NULL), RAY_ENC_FSST); + TEST_ASSERT_STR_EQ(st_scan(STP("/fw3")), ""); + PASS(); +} + +/* ---- Task 2b: STR code bounds reach no ordered-statistics consumer ---- */ +static ray_runtime_t* st_rt; +static void st_q_setup(void) { + st_rt = ray_runtime_create(0, NULL); + (void)ray_test_rm_rf(ray_test_tmp(ST_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(ST_TMP)); +} +static void st_q_teardown(void) { + free(st_mem); st_mem = NULL; + st_release_held(); + ray_test_hooks_off(); ray_encw_test_force_str(-1); ray_encw_test_force(-1); + (void)ray_test_rm_rf(ray_test_tmp(ST_TMP)); ray_runtime_destroy(st_rt); +} +/* The query's formatted result; NULL when it fails (message in st_msg). */ +static ray_t* st_q_fmt(const char* q) { + ray_t* r = ray_eval_str(ray_test_tmp(q)); + if (!r || RAY_IS_ERR(r)) { + snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + if (r) ray_error_free(r); + return NULL; + } + ray_t* f = ray_fmt(r, 0); ray_release(r); + return f; +} +/* Evaluate q for its effect: false when it fails (message in st_msg). */ +static bool st_q_run(const char* q) { + st_msg[0] = 0; + ray_t* r = ray_eval_str(ray_test_tmp(q)); + if (r && RAY_IS_ERR(r)) { + snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); + ray_error_free(r); + return false; + } + if (r) ray_release(r); + return true; +} +#define ST_Q_OK(q) TEST_ASSERT_FMT(st_q_run(q), "%s: %s", (q), st_msg) +/* The query's result is the boolean true. */ +static bool st_q_true(const char* q) { + ray_t* r = ray_eval_str(ray_test_tmp(q)); + bool ok = r && !RAY_IS_ERR(r) && r->type == -RAY_BOOL && r->b8; + if (r && RAY_IS_ERR(r)) { snprintf(st_msg, sizeof st_msg, "%s", ray_error_msg() ? ray_error_msg() : ""); ray_error_free(r); } + else if (r) ray_release(r); + return ok; +} +#define ST_Q_TRUE(q) TEST_ASSERT_FMT(st_q_true(q), "%s: %s", (q), st_msg) +/* The live generation's file of column `col` of the table saved at + * ST_TMP `rel` (#649 / #713: the table directory holds generations). */ +static bool st_live(const char* rel, const char* col, char* out, size_t n) { + char tmp[256], dir[512]; + snprintf(tmp, sizeof tmp, "%s%s", ST_TMP, rel); + if (ray_splay_resolve_dir(ray_test_tmp(tmp), dir, sizeof dir) != RAY_OK) return false; + return (size_t)snprintf(out, n, "%s/%s", dir, col) < n; +} + +/* The chokepoint over a three-string column (insertion order z, a, m: + * codes 0, 1, 2 are not value order), its strings nm[0..2]. */ +static test_result_t st_chokepoint(const char* const nm[3]) { + ray_t* v = ray_vec_new(RAY_STR, 70000); + for (int64_t i = 0; i < 70000; i++) { const char* x = nm[i % 3]; v = ray_str_vec_append(v, x, strlen(x)); } + ray_t* tb = ray_table_new(1); + tb = ray_table_add_col(tb, ray_sym_intern("s", 1), v); ray_release(v); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("W", 1), tb), RAY_OK); + ray_release(tb); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/g0/\" W {compress: false})"); + ray_encw_test_force_str(RAY_ENC_STR_DICT); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/g2/\" W {compress: true})"); + ray_encw_test_force_str(-1); + + /* the accessors, on the generation-2 column */ + ST_Q_OK("(set T (.db.splayed.get \"" ST_TMP "/g2/\"))"); + ray_t* t = st_hold(ray_eval_str("T")); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern("s", 1)); + TEST_ASSERT_TRUE(encv != NULL); + ray_enccol_t* e = ray_enccol_of(encv); + ray_t* be = ray_col_src_bind(encv, &st_src); + if (be) st_hold(be); + TEST_ASSERT_TRUE(be == NULL); + st_src_on = true; + ray_enc_chunk_stat_t cs; + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&st_src, 0, &cs)); + TEST_ASSERT_FALSE(cs.has_minmax); + TEST_ASSERT_TRUE(cs.min == 0 && cs.max == 0); /* no codes behind has_minmax */ + TEST_ASSERT_EQ_I(cs.rows, 65536); + int64_t mn = 7, mx = 7; uint32_t nn = 0; + TEST_ASSERT_FALSE(ray_col_src_vec_stat(&st_src, 0, &mn, &mx, &nn)); + ray_enc_col_totals_t tot; ray_enccol_dir_totals(e, &tot); + TEST_ASSERT_TRUE(tot.mm_partial); + TEST_ASSERT_TRUE(tot.min_i == INT64_MAX && tot.max_i == INT64_MIN); + int64_t lo = -1, hi = -1; + TEST_ASSERT_TRUE(ray_enccol_code_bounds(e, 0, -1, &lo, &hi)); + TEST_ASSERT_TRUE(lo == 0 && hi == 2); + lo = hi = -1; + TEST_ASSERT_TRUE(ray_enccol_code_bounds(e, 0, 0, &lo, &hi)); + TEST_ASSERT_TRUE(lo == 0 && hi == 2); + TEST_ASSERT_FALSE(ray_enccol_code_bounds(e, 5, -1, &lo, &hi)); /* past the last chunk */ + + /* the consumers answer as generation 0 does */ + static const char* const qs[] = { + "(min (at T 's))", "(max (at T 's))", + "(count (select {from: T where: (< s \"m\")}))", + "(select {s: s from: T asc: s take: 3})", + "(select {s: s from: T desc: s take: 3})", + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + ray_t* f[2] = { NULL, NULL }; + for (int g = 0; g < 2; g++) { + ST_Q_OK(g ? "(set T (.db.splayed.get \"" ST_TMP "/g2/\"))" : "(set T (.db.splayed.get \"" ST_TMP "/g0/\"))"); + f[g] = st_q_fmt(qs[i]); + if (f[g]) st_hold(f[g]); + TEST_ASSERT_FMT(f[g] != NULL, "%s gen %d: %s", qs[i], g ? 2 : 0, st_msg); + } + bool same = ray_str_len(f[0]) == ray_str_len(f[1]) && memcmp(ray_str_ptr(f[0]), ray_str_ptr(f[1]), ray_str_len(f[0])) == 0; + TEST_ASSERT_FMT(same, "%s differs from generation 0", qs[i]); + st_unhold(f[0], NULL); st_unhold(f[1], NULL); + ray_release(f[0]); ray_release(f[1]); + } + PASS(); +} + +/* Inline strings: the materializing queries need no pool. */ +static test_result_t test_stats_chokepoint(void) { + static const char* const nm[3] = { "zulu", "alpha", "mike" }; + return st_chokepoint(nm); +} + +/* The same over pooled strings (over 12 bytes), which materialize through + * the dictionary-first pool. */ +static test_result_t test_stats_chokepoint_pooled(void) { + static const char* const nm[3] = { "zulu zulu zulu zulu", "alpha alpha alpha", "mike mike mike mike" }; + return st_chokepoint(nm); +} + +/* Carry from the Task 3 review: in a STR_DICT vector's code-to-offset + * table, codes that are multiples of 2048 spread (the high bits of the + * product index the slot). One distinct 20-byte entry per row for 32768 + * rows, then a vector whose rows cycle through the codes k * 2048. */ +static test_result_t test_dict_slot_spread(void) { + const char* p = STP("/sp"); + ray_t* v = st_hold(ray_vec_new(RAY_STR, 34816)); + char b[64]; + for (int64_t i = 0; i < 34816; i++) { + int64_t k = i < 32768 ? i : ((i - 32768) % 16) * 2048; + snprintf(b, sizeof b, "entry-%012lld-xx", (long long)k); + ray_t* w = ray_str_vec_append(v, b, strlen(b)); + st_unhold(v, w); v = w; + } + ray_encw_test_force_str(RAY_ENC_STR_DICT); + ray_err_t se = ray_col_save_gen(v, p, 2); + ray_encw_test_force_str(-1); + TEST_ASSERT_EQ_I(se, RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(p, 32, NULL), RAY_ENC_STR_DICT); + ray_t* c = st_hold(ray_col_mmap(p)); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_t* be = ray_col_src_bind(c, &st_src); + if (be) st_hold(be); + TEST_ASSERT_NULL(be); + st_src_on = true; + ray_col_scratch_init(&st_sc); st_sc_on = true; + bool same = true; int64_t bad = -1; + for (int64_t r = 0; r < 34816 && same; ) { + ray_col_range_t rv; + ray_t* err = ray_col_range(&st_src, r, 34816 - r, &st_sc, &rv); + if (err) { ray_error_free(err); same = false; bad = r; break; } + for (int64_t k = 0; k < rv.n && same; k++) { + size_t lb; const char* want = ray_str_vec_get(v, r + k, &lb); + const ray_str_t* d = (const ray_str_t*)rv.data + k; + if (d->len != lb || memcmp(ray_str_t_ptr(d, rv.str_pool), want, lb) != 0) { same = false; bad = r + k; } + } + r += rv.n; + } + TEST_ASSERT_FMT(same, "row %lld differs", (long long)bad); + PASS(); +} + +/* ---- Task 4: the dictionary-first pool; the DICT index (persisted since P6b) ---- */ + +/* Two STR vectors hold the same strings, row for row. */ +static bool st_same(ray_t* a, ray_t* b) { + if (!a || !b || RAY_IS_ERR(a) || RAY_IS_ERR(b) || a->type != RAY_STR || b->type != RAY_STR || a->len != b->len) + return false; + for (int64_t i = 0; i < a->len; i++) { + size_t la, lb; + const char* pa = ray_str_vec_get(a, i, &la); + const char* pb = ray_str_vec_get(b, i, &lb); + if (la != lb || (la && memcmp(pa, pb, la) != 0)) return false; + } + return true; +} + +/* Review focus 2: the decoded pool order, element equality, hash32. Chunk + * 0 is a STR_DICT chunk; chunk 1 holds an FSST vector and a CONST vector. */ +static test_result_t test_pool_order(void) { + const char* p = STP("/po"); + int64_t n = 65536 + 2048; + ray_t* v = st_hold(ray_vec_new(RAY_STR, n)); + char b[256]; + for (int64_t i = 0; i < n; i++) { + const char* s = i < 65536 ? gen_lowcard(i, b) : i < 65536 + 1024 ? gen_urls(i, b) : "a constant long string value"; + ray_t* w = ray_str_vec_append(v, s, strlen(s)); + st_unhold(v, w); v = w; + } + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p, 2), RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + int e64 = st_desc_enc(p, 64, NULL); + TEST_ASSERT_TRUE(e64 == RAY_ENC_FSST || e64 == RAY_ENC_RAW); /* FSST trained on chunk 0 */ + TEST_ASSERT_EQ_I(st_desc_enc(p, 65, NULL), RAY_ENC_CONST); + ray_t* c = st_hold(ray_col_mmap(p)); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_t* m = ray_enccol_materialize(c); /* borrowed: the column's cache */ + if (m && RAY_IS_ERR(m)) st_hold(m); + TEST_ASSERT_FMT(m && !RAY_IS_ERR(m), "materialize: %s", ray_error_msg() ? ray_error_msg() : ""); + TEST_ASSERT_TRUE(st_same(m, v)); + TEST_ASSERT_FALSE(ray_index_has(m)); /* a bare file records no DICT (P6b) */ + const char* pool = (const char*)ray_data(m->str_pool); + TEST_ASSERT_EQ_U((uint64_t)m->str_pool->len, ray_enccol_of(c)->hdr.str_pool_bytes); + /* the dictionary region: entries over 12 bytes, once, in code order */ + const ray_enc_sdict_t* sd; + TEST_ASSERT_NULL(ray_enccol_strdict(ray_enccol_of(c), &sd)); + TEST_ASSERT_NOT_NULL(sd); + uint64_t at = 0; + for (uint32_t k = 0; k < sd->n; k++) { + const char* ep; uint32_t el; ray_enc_sdict_entry(sd, k, &ep, &el); + if (el <= RAY_STR_INLINE_MAX) continue; + TEST_ASSERT_TRUE(memcmp(pool + at, ep, el) == 0); + at += el; + } + TEST_ASSERT_EQ_U(at, sd->pooled); + TEST_ASSERT_TRUE(sd->pooled > 0); + const ray_str_t* s0 = (const ray_str_t*)ray_data(m); + for (int64_t i = 0; i < 65536; i++) /* STR_DICT rows point into the region */ + if (!ray_str_is_inline(&s0[i])) TEST_ASSERT_TRUE(s0[i].pool_off + s0[i].len <= sd->pooled); + /* the first pooled row of a non-dictionary vector starts right after it */ + int64_t r1 = 65536; + while (r1 < m->len && ray_str_is_inline(&s0[r1])) r1++; + TEST_ASSERT_TRUE(r1 < m->len); + TEST_ASSERT_EQ_U(s0[r1].pool_off, sd->pooled); + for (int64_t i = 0; i < m->len; i++) { + const ray_str_t* s = &s0[i]; + if (ray_str_is_inline(s)) continue; + uint32_t h = (uint32_t)ray_str_t_hash(s, pool); if (!h) h = 1; + TEST_ASSERT_EQ_U(s->hash32, h); + } + PASS(); +} + +/* The persisted DICT equals generation 0's before materialization (the + * region through the encoded object) and after it (the attached root, + * whose codes vector is the code tier's), with nothing decoded for it. */ +static test_result_t test_dict_equals_gen0(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/d0/\" (table [s] (list S)) {compress: false})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/d2/\" (table [s] (list S)) {compress: true})"); + ray_t* t0 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/d0/\")"))); + ray_t* t2 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/d2/\")"))); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + int64_t sym = ray_sym_intern("s", 1); + ray_t* a = ray_table_col(t0, sym); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + TEST_ASSERT_EQ_I(ray_index_kind(a), RAY_IDX_DICT); + ray_index_t* x = ray_index_payload(a->index); + ray_col_meta_t mt; + TEST_ASSERT_TRUE(ray_table_col_meta(t2, sym, &mt)); + TEST_ASSERT_EQ_I(mt.index_kind, RAY_IDX_DICT); /* recorded: metadata, no decode */ + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t2, sym)); + TEST_ASSERT_NOT_NULL(e); + ray_enc_counters_reset(); + const ray_enc_idict_t* d = NULL; + TEST_ASSERT_NULL(ray_enccol_idict(e, &d)); + TEST_ASSERT_NOT_NULL(d); + TEST_ASSERT_EQ_I(d->n_distinct, x->u.dict.n_distinct); + TEST_ASSERT_TRUE(memcmp(d->first_occ, ray_data(x->u.dict.first_occ), (size_t)d->n_distinct * 4) == 0); + for (int64_t r = 0; r < 70000; r += 1000) { /* by range, vector scope */ + const int32_t* cd = NULL; + int64_t n = 70000 - r < 1000 ? 70000 - r : 1000; + TEST_ASSERT_NULL(ray_enccol_idict_codes(e, r, n, &cd)); + TEST_ASSERT_TRUE(memcmp(cd, (const int32_t*)ray_data(x->u.dict.codes) + r, (size_t)n * 4) == 0); + } + ray_t* cv = NULL; + TEST_ASSERT_NULL(ray_enccol_idict_codes_vec(e, &cv)); + TEST_ASSERT_TRUE(cv->type == RAY_I32 && cv->len == 70000); + TEST_ASSERT_TRUE(memcmp(ray_data(cv), ray_data(x->u.dict.codes), 70000 * 4) == 0); + int64_t code = -9; + char b[64]; int bn = snprintf(b, sizeof b, "value %d of the domain", 7919 % 300); + TEST_ASSERT_NULL(ray_enccol_idict_code(e, b, (size_t)bn, &code)); + TEST_ASSERT_EQ_I(code, 1); /* row 1's string: code 1 */ + TEST_ASSERT_NULL(ray_enccol_idict_code(e, "absent", 6, &code)); + TEST_ASSERT_EQ_I(code, -1); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + /* after materialization: the attached root, sharing the code-tier vector */ + ray_t* m = ray_table_col(t2, sym); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_DICT); + ray_index_t* y = ray_index_payload(m->index); + TEST_ASSERT_TRUE(y->u.dict.codes == cv); + TEST_ASSERT_EQ_I(y->u.dict.n_distinct, x->u.dict.n_distinct); + TEST_ASSERT_TRUE(memcmp(ray_data(y->u.dict.first_occ), ray_data(x->u.dict.first_occ), 300 * 4) == 0); + TEST_ASSERT_TRUE(st_same(m, a)); + PASS(); +} + +/* HASH + all STR_DICT: HASH, no DICT. The persisted DICT (P6b, recorded + * by every save below) + UNIQUE from a heap source + * and from an encoded passenger source (a generation-2 store resaved): UNIQUE + * known before materialization (header), .attr.get equal to the source's + * after it. A generation-0 passenger source (the generation-0 store + * resaved): DICT, and UNIQUE as generation 0 keeps it, which is not at all + * for STR (the generation-0 save drops a STR column's marker-only UNIQUE, a + * pre-existing dev behaviour, #864): .attr.get equal to + * generation 0's. A short column (< 65536 rows) answers no index without + * decoding. */ +static test_result_t test_dict_variants(void) { + /* low cardinality, long strings: every chunk is a STR_DICT chunk */ + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/h2/\" (table [s] (list (.idx.hash S))) {compress: true})"); + char fh[600]; TEST_ASSERT_TRUE(st_live("/h2", "s", fh, sizeof fh)); + for (int c = 0; c < 2; c++) TEST_ASSERT_FALSE(st_dirent(fh, c).flags & RAY_ENC_STAT_ABSENT); + ray_t* t = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/h2/\")"))); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* col = ray_table_col(t, ray_sym_intern("s", 1)); + TEST_ASSERT_TRUE(col && !RAY_IS_ERR(col)); + TEST_ASSERT_EQ_I(ray_index_kind(col), RAY_IDX_HASH); /* HASH, no DICT */ + st_unhold(t, NULL); ray_release(t); + /* UNIQUE: distinct strings forced to STR_DICT (selection would pick FSST) */ + ST_Q_OK("(set U (.attr.set 'unique (as 'STR (map (fn [j] (format \"unique key %\" j)) (til 70000)))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/u0/\" (table [s] (list U)) {compress: false})"); + ray_encw_test_force_str(RAY_ENC_STR_DICT); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/u2/\" (table [s] (list U)) {compress: true})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/uq/\" (.db.splayed.get \"" ST_TMP "/u2/\") {compress: true})"); /* encoded passenger */ + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/up/\" (.db.splayed.get \"" ST_TMP "/u0/\") {compress: true})"); /* generation-0 passenger */ + ray_encw_test_force_str(-1); + static const struct { const char* dir; bool unique; const char* ref; } vs[3] = { + { "/u2", true, "U" }, + { "/uq", true, "U" }, + { "/up", false, "(at (.db.splayed.get \"" ST_TMP "/u0/\") 's)" }, + }; + for (int d = 0; d < 3; d++) { + char fl[600]; TEST_ASSERT_TRUE(st_live(vs[d].dir, "s", fl, sizeof fl)); + for (int c = 0; c < 2; c++) TEST_ASSERT_FALSE(st_dirent(fl, c).flags & RAY_ENC_STAT_ABSENT); + char q[300]; snprintf(q, sizeof q, "(.db.splayed.get \"%s%s/\")", ST_TMP, vs[d].dir); + t = st_hold(ray_eval_str(ray_test_tmp(q))); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_meta_t m; + ray_enc_counters_reset(); + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("s", 1), &m)); + TEST_ASSERT_FMT(m.unique == vs[d].unique, "%s: unique %d", vs[d].dir, (int)m.unique); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + col = ray_table_col(t, ray_sym_intern("s", 1)); + TEST_ASSERT_TRUE(col && !RAY_IS_ERR(col)); + TEST_ASSERT_EQ_I(ray_index_kind(col), RAY_IDX_DICT); + TEST_ASSERT_EQ_I(!!(ray_index_payload(col->index)->markers & RAY_MARK_UNIQUE), vs[d].unique); + TEST_ASSERT_EQ_I(ray_index_payload(col->index)->u.dict.n_distinct, 70000); + st_unhold(t, NULL); ray_release(t); + char qa[700]; /* .attr.get equal to the source's */ + snprintf(qa, sizeof qa, "(== (count (.attr.get %s)) (count (.attr.get (at (.db.splayed.get \"%s%s/\") 's))))", + vs[d].ref, ST_TMP, vs[d].dir); + ST_Q_TRUE(qa); + snprintf(qa, sizeof qa, "(all (== (.attr.get %s) (.attr.get (at (.db.splayed.get \"%s%s/\") 's))))", + vs[d].ref, ST_TMP, vs[d].dir); + ST_Q_TRUE(qa); + } + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/sh/\" (table [s] (list (take [\"a\" \"b\"] 5000))) {compress: true})"); + t = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/sh/\")"))); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_NOT_NULL(ray_table_get_col_enc(t, ray_sym_intern("s", 1))); + ray_enc_counters_reset(); + ray_t* ix = (ray_t*)1; + ray_t* ie = ray_table_col_index(t, ray_sym_intern("s", 1), &ix); + if (ie) st_hold(ie); + TEST_ASSERT_NULL(ie); + TEST_ASSERT_NULL(ix); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + PASS(); +} + +/* Vector scope through a query: a filter whose survivors are all in vector + * 1 gathers only vector 1's slices, and nothing is materialized. */ +static test_result_t test_fsst_scopes_query(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"https://www.example.com/path/%/item?id=%&ref=search\" (% j 5000) (% (* j 7919) 100003))) (til 2048))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/fq/\" (table [s v] (list S (til 2048))) {compress: true})"); + char p[600]; TEST_ASSERT_TRUE(st_live("/fq", "s", p, sizeof p)); + ray_enc_desc_t d; TEST_ASSERT_EQ_I(st_desc_enc(p, 0, &d), RAY_ENC_FSST); + ST_Q_OK("(set T (.db.splayed.get \"" ST_TMP "/fq/\"))"); + ray_enc_counters_reset(); + ST_Q_TRUE("(all (== (at (select {s: s from: T where: (>= v 1024)}) 's) (at S (+ 1024 (til 1024)))))"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + PASS(); +} + +/* ---- Task 4b: STR_DICT helpers shared by later tests ---- */ + +#define SF_ROWS 70000 + +/* "" rows: an ordinary entry; the code of "" resolves; equality with the + * generation-0 DICT holds. */ +static test_result_t test_dict_inband_nulls(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (if (== 0 (% j 5)) \"\" (format \"value % of the domain\" (% j 300)))) (til 70000))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/n0/\" (table [s] (list S)) {compress: false})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/n2/\" (table [s] (list S)) {compress: true})"); + ray_t* t0 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/n0/\")"))); + ray_t* t2 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/n2/\")"))); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + int64_t sym = ray_sym_intern("s", 1); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t2, sym)); + TEST_ASSERT_NOT_NULL(e); + int64_t code = -9; + TEST_ASSERT_NULL(ray_enccol_idict_code(e, "", 0, &code)); + TEST_ASSERT_EQ_I(code, 0); /* row 0 is "" */ + const ray_enc_idict_t* d = NULL; + TEST_ASSERT_NULL(ray_enccol_idict(e, &d)); + TEST_ASSERT_TRUE(d && d->ent->null_code == 0); + ray_t* a = ray_table_col(t0, sym); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + ray_index_t* x = ray_index_payload(a->index); + TEST_ASSERT_EQ_I(d->n_distinct, x->u.dict.n_distinct); + ray_t* cv = NULL; + TEST_ASSERT_NULL(ray_enccol_idict_codes_vec(e, &cv)); + TEST_ASSERT_TRUE(memcmp(ray_data(cv), ray_data(x->u.dict.codes), 70000 * 4) == 0); + TEST_ASSERT_TRUE(memcmp(d->first_occ, ray_data(x->u.dict.first_occ), (size_t)d->n_distinct * 4) == 0); + PASS(); +} + +/* OOM in each tier: oom, nothing cached, the retry succeeds; allocator + * accounting back at its start after each failure. */ +static test_result_t test_dict_oom_retry(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/o/\" (table [s] (list S)) {compress: true})"); + char p[600]; TEST_ASSERT_TRUE(st_live("/o", "s", p, sizeof p)); + ray_t* c = st_hold(ray_col_mmap(p)); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_t* e = ray_enccol_of(c); + const ray_enc_idict_t* d = NULL; + ray_mem_stats_t m0, m1; + ray_mem_stats(&m0); + ray_enccol_test_fail_alloc(1); + ray_t* e1 = ray_enccol_idict(e, &d); + ray_enccol_test_fail_alloc(0); + TEST_ASSERT_TRUE(e1 && strcmp(ray_err_code(e1), "oom") == 0); ray_error_free(e1); + TEST_ASSERT_NULL(d); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + TEST_ASSERT_NULL(ray_enccol_idict(e, &d)); + TEST_ASSERT_NOT_NULL(d); + ray_t* cv = NULL; + ray_mem_stats(&m0); + ray_enccol_test_fail_alloc(1); + ray_t* e2 = ray_enccol_idict_codes_vec(e, &cv); + ray_enccol_test_fail_alloc(0); + TEST_ASSERT_TRUE(e2 && strcmp(ray_err_code(e2), "oom") == 0); ray_error_free(e2); + TEST_ASSERT_NULL(cv); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_U(m1.bytes_allocated, m0.bytes_allocated); + TEST_ASSERT_NULL(ray_enccol_idict_codes_vec(e, &cv)); + TEST_ASSERT_TRUE(cv && cv->len == 70000); + /* the warm answer: rows, codes, first occurrences */ + ray_t* warm = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(warm && !RAY_IS_ERR(warm) && ray_index_kind(warm) == RAY_IDX_DICT); + TEST_ASSERT_TRUE(ray_index_payload(warm->index)->u.dict.codes == cv); + /* every injection point of a materialization on a fresh column: oom, + * nothing leaked once the column goes, and the retry equals the warm + * answer; the DICT's own points are among them (P6's sweep) */ + bool done = false; + int dict_tier = 0, dict_root = 0, dict_gate = 0; + for (int nth = 1; nth <= 64 && !done; nth++) { + ray_mem_stats(&m0); + ray_t* fc = ray_col_mmap(p); + TEST_ASSERT_TRUE(fc && !RAY_IS_ERR(fc)); + ray_error_clear(); + ray_enccol_test_fail_alloc(nth); + ray_t* r = ray_enccol_materialize(fc); + ray_enccol_test_fail_alloc(0); + if (r && RAY_IS_ERR(r)) { + const char* msg = ray_error_msg() ? ray_error_msg() : ""; + const bool oom = strcmp(ray_err_code(r), "oom") == 0; + if (strstr(msg, "index parse")) dict_gate++; + else if (strstr(msg, "DICT index")) dict_root++; + else if (strstr(msg, "DICT") && !strstr(msg, "STR_DICT")) dict_tier++; /* not the side entry */ + ray_error_free(r); + if (!oom) ray_release(fc); + TEST_ASSERT_FMT(oom, "nth %d: not oom", nth); + r = ray_enccol_materialize(fc); /* the retry */ + } else { + done = true; + } + bool same = r && !RAY_IS_ERR(r) && st_same(r, warm) && ray_index_kind(r) == RAY_IDX_DICT; + if (same) { + const ray_index_t* a = ray_index_payload(r->index); + const ray_index_t* b = ray_index_payload(warm->index); + same = a->u.dict.n_distinct == b->u.dict.n_distinct && + memcmp(ray_data(a->u.dict.codes), ray_data(b->u.dict.codes), 70000 * 4) == 0 && + memcmp(ray_data(a->u.dict.first_occ), ray_data(b->u.dict.first_occ), 300 * 4) == 0; + } + if (r && RAY_IS_ERR(r)) ray_error_free(r); + ray_release(fc); + ray_mem_stats(&m1); + TEST_ASSERT_FMT(same, "nth %d: retry differs from the warm answer", nth); + TEST_ASSERT_FMT(m1.bytes_allocated == m0.bytes_allocated, "nth %d: %llu vs %llu", nth, + (unsigned long long)m1.bytes_allocated, (unsigned long long)m0.bytes_allocated); + } + TEST_ASSERT_TRUE(done); + TEST_ASSERT_EQ_I(dict_gate, 1); /* the attach's gate */ + TEST_ASSERT_EQ_I(dict_root, 2); /* first_occ, then the root */ + TEST_ASSERT_EQ_I(dict_tier, 2); /* the entry tier, the code tier */ + PASS(); +} + + +/* ---- Task 5: STR equality and inequality in filters ---- */ + +/* ST_Q_OK for a long local query text: the message is cut */ +#define ST_Q_OK_N(q) TEST_ASSERT_FMT(st_q_run(q), "%.400s: %.400s", (q), st_msg) + +/* The generation-2 run's counters of st_same_q: materializations, decoded + * bytes, and the STR selections it answered (a first conjunct, a + * refinement). */ +typedef struct { uint64_t mat, dec, sel, refine; } st_fk_t; + +/* q (table T) on 0 and 2 (`load` formats the load of the + * table directory): equal formatted results; the generation-0 run takes + * no STR selection; the generation-2 run's counters into *k. */ +static test_result_t st_same_load(const char* name, const char* load, const char* q, st_fk_t* k) { + char buf[1024], ld[700]; + ray_t* out[2] = { NULL, NULL }; + for (int g = 0; g < 2; g++) { + snprintf(ld, sizeof ld, load, ST_TMP, name, g ? 2 : 0); + snprintf(buf, sizeof buf, "(set T %s)", ld); + ST_Q_OK_N(buf); + ray_enc_counters_reset(); + const uint64_t s0 = ray_exec_test_str_sel(0), r0 = ray_exec_test_str_sel(1); + out[g] = st_q_fmt(q); + TEST_ASSERT_FMT(out[g] != NULL, "%s gen %d: %s", q, g ? 2 : 0, st_msg); + st_hold(out[g]); + ray_enc_counters_t c; ray_enc_counters_get(&c); + const uint64_t ds = ray_exec_test_str_sel(0) - s0, dr = ray_exec_test_str_sel(1) - r0; + if (!g) TEST_ASSERT_FMT(ds == 0 && dr == 0, "%s: generation 0 took the STR selection", q); + else if (k) *k = (st_fk_t){ c.materialized, c.decoded_bytes, ds, dr }; + } + TEST_ASSERT_FMT(ray_str_len(out[0]) == ray_str_len(out[1]) && + memcmp(ray_str_ptr(out[0]), ray_str_ptr(out[1]), ray_str_len(out[0])) == 0, + "%s differs: %.*s vs %.*s", q, (int)ray_str_len(out[0]), ray_str_ptr(out[0]), + (int)ray_str_len(out[1]), ray_str_ptr(out[1])); + for (int g = 0; g < 2; g++) { st_unhold(out[g], NULL); ray_release(out[g]); } + PASS(); +} +#define ST_SPLAY_LOAD "(.db.splayed.get \"%s/%s%d/\")" +static test_result_t st_same_q(const char* name, const char* q, st_fk_t* k) { + return st_same_load(name, ST_SPLAY_LOAD, q, k); +} +#define ST_SAME(name, q, k) do { test_result_t r_ = st_same_q((name), (q), (k)); \ + if (r_.status != TEST_PASS) return r_; } while (0) +#define ST_SAME_P(name, q, k) do { test_result_t r_ = st_same_load((name), "(.db.parted.get \"%s/%s%d\" 't)", (q), (k)); \ + if (r_.status != TEST_PASS) return r_; } while (0) + +/* Table text `tbl` saved as 0 (generation 0) and 2. */ +static test_result_t st_save2(const char* name, const char* tbl) { + char q[4096]; + snprintf(q, sizeof q, "(set W %s)", tbl); ST_Q_OK_N(q); + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/%s0/\" W {compress: false})", name); ST_Q_OK_N(q); + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/%s2/\" W {compress: true})", name); ST_Q_OK_N(q); + PASS(); +} +#define ST_SAVE2(name, tbl) do { test_result_t r_ = st_save2((name), (tbl)); \ + if (r_.status != TEST_PASS) return r_; } while (0) + +/* vectors 0..63 URL-like (FSST, its table trained on them), 64..127 low + * cardinality (STR_DICT), 128.. short distinct strings (not STR_DICT); "" + * every 97th row; f a U8 flag */ +#define ST_FL_TABLE "(table [s v f] (list (as 'STR (map (fn [j] (if (== 0 (% j 97)) \"\" " \ + "(if (< j 65536) (format \"https://www.example.com/path/%/item?id=%&ref=search\" (% j 5000) (% (* j 7919) 100003)) " \ + "(if (< j 131072) (format \"cat % x\" (% j 37)) (format \"u%\" j))))) (til 140000))) (til 140000) (as 'U8 (% (til 140000) 3))))" +#define ST_FL_URL "https://www.example.com/path/1000/item?id=18763&ref=search" + +static test_result_t test_filter_strdict(void) { + /* subject: STR_DICT codes and bounds; the persisted DICT would answer (P6b) */ + ray_col_test_no_dict(true); + ST_SAVE2("fl", ST_FL_TABLE); + ray_col_test_no_dict(false); + char p[600]; TEST_ASSERT_TRUE(st_live("/fl2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_FSST); + TEST_ASSERT_EQ_I(st_desc_enc(p, 64, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_TRUE(st_desc_enc(p, 128, NULL) != RAY_ENC_STR_DICT); + st_fk_t k; + ST_SAME("fl", "(count (select {from: T where: (== s \"cat 5 x\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_EQ_U(k.sel, 1); + ST_SAME("fl", "(count (select {from: T where: (!= s \"cat 5 x\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_EQ_U(k.sel, 1); + ST_SAME("fl", "(count (select {from: T where: (== \"cat 5 x\" s)}))", &k); /* the constant first */ + TEST_ASSERT_EQ_U(k.sel, 1); + /* absent everywhere: the STR_DICT chunk decided, the FSST vectors decoded */ + ST_SAME("fl", "(count (select {from: T where: (== s \"nope\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_TRUE(k.dec > 0); + ST_SAME("fl", "(count (select {from: T where: (!= s \"nope\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + /* an FSST-chunk value; the select returns rows by range gather */ + ST_SAME("fl", "(select {v: v from: T where: (== s \"" ST_FL_URL "\")})", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + ST_SAME("fl", "(select {v: v s: s from: T where: (== s \"cat 36 x\")})", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + /* nulls (""): byte equality, both sides */ + ST_SAME("fl", "(count (select {from: T where: (== s \"\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_EQ_U(k.sel, 1); + ST_SAME("fl", "(count (select {from: T where: (!= s \"\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + PASS(); +} + +/* Only the STR_DICT chunk: code bounds decide the vectors, nothing decoded. */ +static test_result_t test_filter_decided(void) { + /* subject: STR_DICT codes and bounds; the persisted DICT would answer (P6b) */ + ray_col_test_no_dict(true); + ST_SAVE2("fd", "(table [s] (list (as 'STR (map (fn [j] (format \"cat % x\" (% j 37))) (til 70000)))))"); + ST_SAVE2("fz", "(table [s] (list (as 'STR (at [\"z\" \"a\" \"m\"] (% (til 70000) 3)))))"); + ray_col_test_no_dict(false); + char p[600]; TEST_ASSERT_TRUE(st_live("/fd2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + st_fk_t k; + ST_SAME("fd", "(count (select {from: T where: (== s \"not a category\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_EQ_U(k.dec, 0); + ST_SAME("fd", "(count (select {from: T where: (== s \"cat 3 x\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_EQ_U(k.dec, 0); /* codes compared, not strings */ + ST_SAME("fd", "(count (select {from: T where: (!= s \"cat 3 x\")}))", &k); + TEST_ASSERT_EQ_U(k.dec, 0); + /* the `z, a, m` column of compress_str.rfl: code order is not value order */ + TEST_ASSERT_TRUE(st_live("/fz2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + ST_SAME("fz", "(count (select {from: T where: (== s \"a\")}))", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + TEST_ASSERT_EQ_U(k.dec, 0); + ST_SAME("fz", "(count (select {from: T where: (== s \"b\")}))", &k); /* between codes, absent */ + TEST_ASSERT_EQ_U(k.dec, 0); + ST_SAME("fz", "(count (select {from: T where: (!= s \"m\")}))", &k); + TEST_ASSERT_EQ_U(k.dec, 0); + PASS(); +} + +/* Chained conjuncts (ruling R1): the optimizer splits the WHERE, runs the + * conjunct it ranks most selective first (opt.c filter_rank_key: a STR + * `==` ranks first, a STR `!=` after any equality and a narrow flag), and a + * later STR conjunct refines the installed selection + * (exec_pred_refine_selection), on codes. Generation-0 equal, nothing + * materialized, every query through a STR selection; `refines` marks the + * queries whose STR conjunct runs second. */ +static test_result_t test_filter_chained(void) { + /* subject: STR_DICT codes and bounds; the persisted DICT would answer (P6b) */ + ray_col_test_no_dict(true); + ST_SAVE2("fc", ST_FL_TABLE); + ray_col_test_no_dict(false); + { char p[600]; TEST_ASSERT_TRUE(st_live("/fc2", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); } + static const struct { const char* q; bool refines; } qs[] = { + /* the brief's pair: the STR equality ranks first either way */ + { "(count (select {from: T where: (and (> v 100) (== s \"cat 5 x\"))}))", false }, + { "(count (select {from: T where: (and (== s \"cat 5 x\") (> v 100))}))", false }, + { "(count (select {from: T where: (and (< v 70000) (!= s \"cat 5 x\"))}))", false }, + { "(count (select {from: T where: (and (>= v 60000) (== s \"\"))}))", false }, + /* the STR conjunct second */ + /* v < 3000 keeps three vectors of the chunk statistics: the chain + * runs over them (exec_filter_chain_prune), the STR equality + * refining that selection */ + { "(select {v: v from: T where: (and (< v 3000) (== s \"cat 5 x\"))})", true }, + { "(count (select {from: T where: (and (== f 1) (!= s \"\"))}))", true }, + { "(count (select {from: T where: (and (!= s \"\") (== f 1))}))", true }, + { "(count (select {from: T where: (and (== f 2) (!= s \"cat 5 x\"))}))", true }, + { "(count (select {from: T where: (and (== f 0) (!= s \"" ST_FL_URL "\"))}))", true }, + { "(count (select {from: T where: (and (in v [5 97 1000 70005 70006 131100 139999]) (!= s \"\"))}))", true }, + { "(select {v: v s: s from: T where: (and (in v [5 97 1000 70005 70006 131100 139999]) (!= s \"cat 6 x\"))})", true }, + { "(count (select {from: T where: (and (== s \"cat 5 x\") (!= s \"cat 6 x\"))}))", true }, + { "(count (select {from: T where: (and (== s \"cat 5 x\") (== s \"cat 6 x\"))}))", true }, + { "(count (select {from: T where: (and (== s \"cat 5 x\") (== s \"cat 5 x\"))}))", true }, + { "(count (select {from: T where: (and (== f 1) (!= s \"nope\"))}))", true }, + { "(count (select {from: T where: (and (== f 1) (> v 130000) (!= s \"\"))}))", true }, + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + st_fk_t k; + ST_SAME("fc", qs[i].q, &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: %llu materializations", qs[i].q, (unsigned long long)k.mat); + TEST_ASSERT_FMT(k.sel + k.refine >= 1, "%s: no STR selection", qs[i].q); + if (qs[i].refines) TEST_ASSERT_FMT(k.refine == 1, "%s: %llu refinements", qs[i].q, (unsigned long long)k.refine); + else TEST_ASSERT_FMT(k.sel == 1 && k.refine == 0, "%s: %llu first conjuncts, %llu refinements", qs[i].q, + (unsigned long long)k.sel, (unsigned long long)k.refine); + } + PASS(); +} + +/* Parted: two encoded partitions with their own dictionaries (a code of + * one is not a code of the other), a generation-0 partition and a ragged + * partition without the column (a synthetic all-null segment), each + * against the same partitions saved as generation 0. */ +static test_result_t test_filter_parted(void) { + static const char* const parts[4] = { + "(table [v s] (list (til 70000) (as 'STR (map (fn [j] (format \"cat % x\" (% j 37))) (til 70000)))))", + "(table [v s] (list (til 3000) (as 'STR (map (fn [j] (if (== 0 (% j 7)) \"\" (format \"cat % x\" (% (+ j 11) 41)))) (til 3000)))))", + "(table [v s] (list (til 5000) (as 'STR (map (fn [j] (format \"https://www.example.com/path/%/item?id=%&ref=search\" (% j 999) j)) (til 5000)))))", + "(table [v] (list (til 2000)))", + }; + /* subject: STR_DICT codes and bounds; the persisted DICT would answer (P6b) */ + ray_col_test_no_dict(true); + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 4; p++) { + char q[1200]; + /* the second partition (p == 1, 2024.01.02) stays generation 0 in the encoded store */ + const bool enc = gen == 2 && p != 1; + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/fp%d/2024.01.0%d/t/\" %s {compress: %s})", + gen, p + 1, parts[p], enc ? "true" : "false"); + ST_Q_OK_N(q); + } + ray_col_test_no_dict(false); + { char p[600]; TEST_ASSERT_TRUE(st_live("/fp2/2024.01.01/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); } + static const struct { const char* q; bool refines; } qs[] = { + { "(count (select {from: T where: (== s \"cat 5 x\")}))", false }, + { "(count (select {from: T where: (!= s \"cat 5 x\")}))", false }, + { "(count (select {from: T where: (== s \"cat 40 x\")}))", false }, /* partition 2 only */ + { "(count (select {from: T where: (== s \"nope\")}))", false }, + { "(count (select {from: T where: (== s \"\")}))", false }, /* partitions 2 and 4 */ + { "(count (select {from: T where: (!= s \"\")}))", false }, + { "(count (select {from: T where: (== s \"https://www.example.com/path/7/item?id=4003&ref=search\")}))", false }, + { "(sum (at (select {from: T where: (== s \"cat 5 x\")}) 'v))", false }, + { "(count (select {from: T where: (and (> v 1000) (== s \"cat 5 x\"))}))", false }, + { "(count (select {from: T where: (and (> v 1000) (!= s \"\"))}))", false }, + { "(count (select {from: T where: (and (in v [0 7 14 1000 2999 4999 69999]) (!= s \"\"))}))", true }, + { "(count (select {from: T where: (and (== v 7) (!= s \"cat 5 x\"))}))", true }, + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + st_fk_t k; + ST_SAME_P("fp", qs[i].q, &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: %llu materializations", qs[i].q, (unsigned long long)k.mat); + /* `refines`: the `in` / `==` on v runs first, the STR conjunct refines */ + if (qs[i].refines) TEST_ASSERT_FMT(k.refine == 1, "%s: %llu refinements", qs[i].q, (unsigned long long)k.refine); + else TEST_ASSERT_FMT(k.sel == 1 && k.refine == 0, "%s: %llu first conjuncts, %llu refinements", qs[i].q, + (unsigned long long)k.sel, (unsigned long long)k.refine); + } + PASS(); +} + +/* Mixed-encoding chunks (D4 / D5 nesting): chunk 0 is not a dictionary + * chunk and mixes FSST vectors (URLs) with a CONST vector (one string) and + * an all-null CONST vector; chunk 1 is a STR_DICT chunk holding an all-null + * CONST vector, so it has no directory bounds over vectors that do. */ +#define ST_MX_TABLE "(table [s v] (list (as 'STR (map (fn [j] " \ + "(if (and (>= j 3072) (< j 4096)) \"one constant string for this vector\" " \ + "(if (and (>= j 5120) (< j 6144)) \"\" " \ + "(if (< j 65536) (format \"https://www.example.com/path/%/item?id=%&ref=search\" (% j 5000) (% (* j 7919) 100003)) " \ + "(if (and (>= j 71680) (< j 72704)) \"\" (format \"cat % x\" (% j 37))))))) (til 131072))) (til 131072)))" +static test_result_t test_filter_mixed_chunks(void) { + /* subject: STR_DICT codes and bounds; the persisted DICT would answer (P6b) */ + ray_col_test_no_dict(true); + ST_SAVE2("fm", ST_MX_TABLE); + ray_col_test_no_dict(false); + char p[600]; TEST_ASSERT_TRUE(st_live("/fm2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_FSST); + TEST_ASSERT_EQ_I(st_desc_enc(p, 3, NULL), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(st_desc_enc(p, 5, NULL), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(st_desc_enc(p, 64, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 70, NULL), RAY_ENC_CONST); + TEST_ASSERT_TRUE(st_dirent(p, 0).flags & RAY_ENC_STAT_ABSENT); + TEST_ASSERT_TRUE(st_dirent(p, 1).flags & RAY_ENC_STAT_ABSENT); /* not every vector STR_DICT */ + ray_enc_desc_t d; TEST_ASSERT_EQ_I(st_desc_enc(p, 64, &d), RAY_ENC_STR_DICT); + TEST_ASSERT_FALSE(d.flags & RAY_ENC_STAT_ABSENT); /* the vector keeps its bounds */ + static const char* const lits[] = { + "cat 5 x", "", "one constant string for this vector", "nope", + "https://www.example.com/path/1000/item?id=18763&ref=search", + }; + for (size_t i = 0; i < sizeof lits / sizeof *lits; i++) + for (int ne = 0; ne < 2; ne++) { + char q[400]; st_fk_t k; + snprintf(q, sizeof q, "(count (select {from: T where: (%s s \"%s\")}))", ne ? "!=" : "==", lits[i]); + ST_SAME("fm", q, &k); + TEST_ASSERT_FMT(k.mat == 0 && k.sel == 1, "%s: %llu materializations, %llu selections", q, + (unsigned long long)k.mat, (unsigned long long)k.sel); + } + PASS(); +} + +/* A single-file column whose materialization is published is declined + * (its STR filter keeps the bool path, which reads it in place): the + * answer equals generation 0 before and after the materialization. */ +static test_result_t test_filter_materialized(void) { + /* subject: the STR_DICT path declining a published materialization; the + * persisted DICT serves a materialized column (P6b, idict_filter) */ + ray_col_test_no_dict(true); + ST_SAVE2("fx", ST_FL_TABLE); + ray_col_test_no_dict(false); + { char p[600]; TEST_ASSERT_TRUE(st_live("/fx2", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); } + static const char* const qs[] = { + "(count (select {from: T where: (== s \"cat 5 x\")}))", + "(count (select {from: T where: (!= s \"\")}))", + "(count (select {from: T where: (and (== f 1) (!= s \"cat 5 x\"))}))", + }; + for (int mat = 0; mat < 2; mat++) + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + if (!mat) { /* not materialized: the STR selection */ + st_fk_t k; + ST_SAME("fx", qs[i], &k); + TEST_ASSERT_FMT(k.sel + k.refine == 1, "%s: not through the STR selection", qs[i]); + continue; + } + /* materialize generation 2's column, then filter the same table */ + ST_Q_OK("(set T2 (.db.splayed.get \"" ST_TMP "/fx2/\"))"); + ray_t* t = st_hold(ray_eval_str("T2")); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* encv = ray_table_get_col_enc(t, ray_sym_intern("s", 1)); + TEST_ASSERT_TRUE(encv != NULL); + ray_t* m = ray_enccol_materialize(encv); /* borrowed: the column's cache */ + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_TRUE(ray_enccol_decoded_peek(encv) != NULL); + ST_Q_OK("(set T (.db.splayed.get \"" ST_TMP "/fx0/\"))"); + ray_t* a = st_q_fmt(qs[i]); + TEST_ASSERT_FMT(a != NULL, "%s gen 0: %s", qs[i], st_msg); + st_hold(a); + ST_Q_OK("(set T T2)"); + const uint64_t s0 = ray_exec_test_str_sel(0), r0 = ray_exec_test_str_sel(1); + ray_t* b = st_q_fmt(qs[i]); + TEST_ASSERT_FMT(b != NULL, "%s materialized: %s", qs[i], st_msg); + st_hold(b); + TEST_ASSERT_FMT(ray_exec_test_str_sel(0) == s0 && ray_exec_test_str_sel(1) == r0, + "%s: a published materialization took the STR selection", qs[i]); + TEST_ASSERT_FMT(ray_str_len(a) == ray_str_len(b) && memcmp(ray_str_ptr(a), ray_str_ptr(b), ray_str_len(a)) == 0, + "%s differs after materializing", qs[i]); + st_unhold(a, NULL); ray_release(a); st_unhold(b, NULL); ray_release(b); + st_unhold(t, NULL); ray_release(t); + } + PASS(); +} + +/* ---- Task 6: group-by on dictionary codes, cross-segment translation ---- */ + +/* Rewrite column `col` (the column of W) of the table saved at ST_TMP `rel` + * chunk by chunk through the writer, chunk c's STR vectors forced to + * forces[c] (-1: selection), into the live generation's file (same type, + * name and length as the file it replaces). */ +static test_result_t st_rewrite(const char* rel, const char* col, int64_t n_chunks, const int* forces) { + char path[600], tmp[620]; + TEST_ASSERT_TRUE(st_live(rel, col, path, sizeof path)); + snprintf(tmp, sizeof tmp, "%s.tmp", path); + char q[64]; snprintf(q, sizeof q, "(at W '%s)", col); + ray_t* w = st_hold(ray_eval_str(q)); + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w) && w->type == RAY_STR); + const int64_t n = w->len; + TEST_ASSERT_TRUE(n > (n_chunks - 1) * RAY_ENC_CHUNK && n <= n_chunks * RAY_ENC_CHUNK); + FILE* f = fopen(tmp, "wb+"); + TEST_ASSERT_TRUE(f != NULL); + ray_encw_t ew; + ray_err_t rc = ray_encw_begin(&ew, f, RAY_STR, 0, n, 0, 0, 0); + const char* pool = w->str_pool ? (const char*)ray_data(w->str_pool) : NULL; + for (int64_t c = 0; rc == RAY_OK && c < n_chunks; c++) { + const int64_t m = n - c * RAY_ENC_CHUNK < RAY_ENC_CHUNK ? n - c * RAY_ENC_CHUNK : RAY_ENC_CHUNK; + ray_encw_test_force_str(forces[c]); + rc = ray_encw_chunk(&ew, (const ray_str_t*)ray_data(w) + c * RAY_ENC_CHUNK, pool, m); + } + ray_encw_test_force_str(-1); + if (rc == RAY_OK) rc = ray_encw_finish(&ew); + ray_encw_free(&ew); fclose(f); + TEST_ASSERT_EQ_I(rc, RAY_OK); + TEST_ASSERT_EQ_I(rename(tmp, path), 0); + st_unhold(w, NULL); ray_release(w); + PASS(); +} +#define ST_REWRITE(rel, col, nc, forces) do { test_result_t r_ = st_rewrite((rel), (col), (nc), (forces)); \ + if (r_.status != TEST_PASS) return r_; } while (0) + +/* Review focus 7: one hash. Chunk 0 RAW (the cursor path hashes each + * ray_str_t), chunk 1 STR_DICT (the remap hashes each entry's bytes), the + * same three long strings in both: three groups, as generation 0. */ +static test_result_t test_remap_hash_parity(void) { + ST_SAVE2("hp", "(table [s v m] (list (as 'STR (at [\"first long string value\" \"second long string value\" " + "\"third long string value\"] (% (til 131072) 3))) (til 131072) (as 'U8 (% (til 131072) 2))))"); + static const int forces[2] = { RAY_ENC_RAW, RAY_ENC_STR_DICT }; + ST_REWRITE("/hp2", "s", 2, forces); + char p[600]; TEST_ASSERT_TRUE(st_live("/hp2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_RAW); + TEST_ASSERT_EQ_I(st_desc_enc(p, 64, NULL), RAY_ENC_STR_DICT); + st_fk_t k; + ST_Q_OK("(set T (.db.splayed.get \"" ST_TMP "/hp2/\"))"); + ST_Q_TRUE("(== 3 (count (select {c: (count v) from: T by: s})))"); + ST_SAME("hp", "(select {c: (count v) from: T by: s})", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + ST_SAME("hp", "(select {c: (count v) from: T by: {s: s m: m}})", &k); + TEST_ASSERT_EQ_U(k.mat, 0); + PASS(); +} + +/* Review focus 3: partitions with conflicting codes. Partition 1 meets + * "red" first, partition 2 "blue": the same string has different codes, + * the same code different strings. */ +static test_result_t test_cross_segment_codes(void) { + static const char* const parts[2] = { + "(table [s v m] (list (as 'STR (at [\"red long value\" \"blue long value\" \"green\"] (% (til 70000) 3))) (til 70000) (as 'U8 (% (til 70000) 2))))", + "(table [s v m] (list (as 'STR (at [\"blue long value\" \"red long value\" \"amber\"] (% (til 70000) 3))) (til 70000) (as 'U8 (% (til 70000) 2))))", + }; + /* subject: the STR_DICT remap; the persisted DICT would take the key (P6b) */ + ray_col_test_no_dict(true); + for (int g = 0; g <= 2; g += 2) + for (int p = 0; p < 2; p++) { + char q[1200]; + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/cs%d/2024.01.0%d/t/\" %s {compress: %s})", + g, p + 1, parts[p], g ? "true" : "false"); + ST_Q_OK_N(q); + } + ray_col_test_no_dict(false); + for (int p = 0; p < 2; p++) { + char rel[64], f[600]; + snprintf(rel, sizeof rel, "/cs2/2024.01.0%d/t", p + 1); + TEST_ASSERT_TRUE(st_live(rel, "s", f, sizeof f)); + TEST_ASSERT_EQ_I(st_hdr(f).index_kind, 0); + TEST_ASSERT_EQ_I(st_desc_enc(f, 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(f, 64, NULL), RAY_ENC_STR_DICT); + } + /* `codes`: every vector read is a STR_DICT vector and only s is read + * by range, so nothing is decoded (the remap reads codes) */ + static const struct { const char* q; bool codes; } qs[] = { + { "(count (select {from: T where: (== s \"red long value\")}))", true }, + { "(count (select {from: T where: (!= s \"blue long value\")}))", true }, + { "(select {v: v from: T where: (== s \"amber\") take: 5})", false }, + { "(select {c: (count v) from: T by: s})", true }, + { "(select {c: (count v) from: T by: s asc: s})", true }, + { "(select {c: (count v) from: T by: {s: s m: m} asc: [s m]})", false }, + /* under a selection: ids first-occurrence over the selected rows */ + { "(select {c: (count v) from: T where: (!= s \"red long value\") by: s})", false }, + { "(select {c: (count v) from: T where: (== s \"blue long value\") by: s})", false }, + { "(select {c: (count v) from: T where: (> v 69990) by: s})", false }, + { "(select {c: (count v) s: (sum v) from: T where: (and (> v 1000) (!= s \"green\")) by: s})", false }, + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + st_fk_t k; + ST_SAME_P("cs", qs[i].q, &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: %llu materializations", qs[i].q, (unsigned long long)k.mat); + if (qs[i].codes) TEST_ASSERT_FMT(k.dec == 0, "%s: %llu bytes decoded", qs[i].q, (unsigned long long)k.dec); + } + /* a computed second key materializes v (its path binds the referenced + * columns, any generation-2 type); the STR key stays codes */ + ST_SAME_P("cs", "(select {c: (count v) from: T by: {s: s r: (% v 2)} asc: [s r]})", NULL); + ST_Q_TRUE("(not (at (.idx.info T 's) 'materialized))"); + PASS(); +} + +/* Group-by under a STR_DICT filter on a column shorter than + * RAY_DICT_MIN_ROWS: the ids are first-occurrence over the selected rows + * (generation 0 groups such a column as STR, in that order). */ +static test_result_t test_groupby_selection(void) { + ST_SAVE2("gs", "(table [s v m] (list (as 'STR (map (fn [j] (if (== 0 (% j 13)) \"\" " + "(format \"group key % long text\" (% (* j 7) 23)))) (til 40000))) (til 40000) (as 'U8 (% (til 40000) 4))))"); + char p[600]; TEST_ASSERT_TRUE(st_live("/gs2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_desc_enc(p, 1, NULL), RAY_ENC_STR_DICT); + static const char* const qs[] = { + "(select {c: (count v) from: T by: s})", + "(select {c: (count v) from: T where: (!= s \"\") by: s})", + "(select {c: (count v) from: T where: (!= s \"group key 0 long text\") by: s})", + "(select {c: (count v) from: T where: (== s \"group key 5 long text\") by: s})", + "(select {c: (count v) from: T where: (> v 39000) by: s})", + "(select {c: (count v) from: T where: (and (> v 20000) (!= s \"\")) by: {s: s m: m}})", + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + st_fk_t k; + ST_SAME("gs", qs[i], &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: %llu materializations", qs[i], (unsigned long long)k.mat); + if (i == 0) TEST_ASSERT_FMT(k.dec == 0, "%s: %llu bytes decoded", qs[i], (unsigned long long)k.dec); + } + PASS(); +} + +/* Spec "Mixed STR group-by": one unparted column mixing STR_DICT, FSST, + * CONST and RAW at chunk boundaries, equal strings crossing every + * boundary, alone and inside a composite key. */ +static test_result_t test_mixed_str_groupby(void) { + /* rows 131072..132095 (vector 128) are all equal: CONST by selection; + * the URLs are near-distinct, so unforced chunk 2 is a plain chunk */ + ST_SAVE2("mx", "(table [s v m] (list (as 'STR (map (fn [j] (if (and (>= j 131072) (< j 132096)) \"shared long key text\" " + "(if (< (% j 3) 2) (at [\"shared long key text\" \"another shared key text\" \"tiny\"] (% (div j 3) 3)) " + "(format \"https://e.com/%/%\" (% j 50) j)))) (til 262144))) (til 262144) (as 'U8 (% (til 262144) 3))))"); + static const int forces[4] = { RAY_ENC_STR_DICT, RAY_ENC_FSST, -1, RAY_ENC_RAW }; + ST_REWRITE("/mx2", "s", 4, forces); + char p[600]; TEST_ASSERT_TRUE(st_live("/mx2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 64, NULL), RAY_ENC_FSST); + TEST_ASSERT_EQ_I(st_desc_enc(p, 128, NULL), RAY_ENC_CONST); + TEST_ASSERT_TRUE(st_desc_enc(p, 129, NULL) != RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 192, NULL), RAY_ENC_RAW); + static const char* const qs[] = { + "(select {c: (count v) from: T by: s asc: s})", + "(select {c: (count v) from: T by: s})", + "(select {c: (count v) from: T by: {s: s m: m} asc: [s m]})", + "(select {c: (count v) from: T by: {s: s m: m}})", + "(select {c: (count v) from: T where: (!= s \"shared long key text\") by: s asc: s})", + }; + for (size_t i = 0; i < sizeof qs / sizeof *qs; i++) { + st_fk_t k; + ST_SAME("mx", qs[i], &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: %llu materializations", qs[i], (unsigned long long)k.mat); + } + /* a computed second key materializes v (its path binds the referenced + * columns, any generation-2 type); the STR key stays codes and ranges */ + ST_SAME("mx", "(select {c: (count v) from: T by: {s: s r: (% v 3)} asc: [s r]})", NULL); + ST_Q_TRUE("(not (at (.idx.info T 's) 'materialized))"); + PASS(); +} + +/* Task 6 review Minor 3: the segment remap's allocation fails through the + * materialization fail hook: the group-by answers `oom` and leaks nothing; + * the retry answers. The column is all STR_DICT (no vector decodes), and + * after a warm run the remap is the query's only hooked allocation. */ +static test_result_t test_groupby_remap_oom(void) { + ray_t* v = st_hold(str_col(SF_ROWS, gen_lowcard)); + ray_t* tb = ray_table_new(2); + tb = ray_table_add_col(tb, ray_sym_intern("s", 1), v); + ray_t* iv = ray_vec_new(RAY_I64, SF_ROWS); + for (int64_t i = 0; i < SF_ROWS; i++) iv = ray_vec_append(iv, &i); + tb = ray_table_add_col(tb, ray_sym_intern("v", 1), iv); + ray_release(iv); + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("W", 1), tb), RAY_OK); + ray_release(tb); + /* subject: the STR_DICT remap; the persisted DICT would take the key (P6b) */ + ray_col_test_no_dict(true); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/ro/\" W {compress: true})"); + ray_col_test_no_dict(false); + char p[600]; TEST_ASSERT_TRUE(st_live("/ro", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, ray_enc_nvecs(SF_ROWS) - 1, NULL), RAY_ENC_STR_DICT); + ST_Q_OK("(set T (.db.splayed.get \"" ST_TMP "/ro/\"))"); + static const char q[] = "(select {c: (count v) from: T by: s})"; + ray_t* want = st_hold(st_q_fmt(q)); /* warm: the dictionary's once-state */ + TEST_ASSERT_NOT_NULL(want); + ST_Q_TRUE("(== 37 (count (select {c: (count v) from: T by: s})))"); + ST_Q_TRUE("(not (at (.idx.info T 's) 'materialized))"); + /* nth 2 is never reached: one hooked allocation (the counter's next + * check consumes the last step) */ + ray_enccol_test_fail_alloc(2); + ray_t* r = st_q_fmt(q); + TEST_ASSERT_NOT_NULL(r); + ray_release(r); + TEST_ASSERT_TRUE(ray_enccol_test_nth_alloc_fails()); + ray_enccol_test_fail_alloc(0); + for (int k = 0; k < 2; k++) { + ray_mem_stats_t m0, m1; ray_mem_stats(&m0); + ray_enccol_test_fail_alloc(1); + r = ray_eval_str(q); + ray_enccol_test_fail_alloc(0); + const bool oom = r && RAY_IS_ERR(r) && strcmp(ray_err_code(r), "oom") == 0; + const char* got = r && RAY_IS_ERR(r) ? ray_err_code(r) : "an answer"; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + TEST_ASSERT_FMT(oom, "round %d: %s", k, got); + ray_mem_stats(&m1); + TEST_ASSERT_FMT(m1.bytes_allocated == m0.bytes_allocated, "round %d: %llu vs %llu", k, + (unsigned long long)m1.bytes_allocated, (unsigned long long)m0.bytes_allocated); + } + r = st_hold(st_q_fmt(q)); /* the retry */ + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_TRUE(ray_str_len(r) == ray_str_len(want) && memcmp(ray_str_ptr(r), ray_str_ptr(want), ray_str_len(r)) == 0); + PASS(); +} + +/* ---- Task 7: abandonment, representation, stream identity ---- */ + +/* The whole file at `path` (malloc'd, NULL on failure); its size in *n. */ +static uint8_t* slurp_file(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + uint8_t* p = NULL; + long sz = fseek(f, 0, SEEK_END) == 0 ? ftell(f) : -1; + if (sz >= 0 && fseek(f, 0, SEEK_SET) == 0 && (p = malloc((size_t)sz + 1)) != NULL && + fread(p, 1, (size_t)sz, f) != (size_t)sz) { free(p); p = NULL; } + fclose(f); + *n = p ? (size_t)sz : 0; + return p; +} + +/* Review focus 4: past 1<<20 entries the accumulator is abandoned. Each + * random printable 24-byte string appears twice, so a chunk's dictionary + * (32768 entries) beats its plain encodings until the cap: chunks 0..31 + * are STR_DICT, chunks 32 and 33 FSST or RAW. */ +static void abandon_str(int64_t pair, char* b) { + uint64_t x = 0x9E3779B97F4A7C15ull * (uint64_t)(pair + 1); + for (int k = 0; k < 24; k++) { x ^= x << 13; x ^= x >> 7; x ^= x << 17; b[k] = (char)(33 + x % 94); } +} +static test_result_t test_abandonment(void) { + const char* p = STP("/ab"); + int64_t n = 2 * ((int64_t)RAY_ENCW_SDICT_CAP + 65536); + TEST_ASSERT_EQ_I(n, 2228224); + ray_t* v = st_hold(ray_vec_new(RAY_STR, n)); + char b[24]; + for (int64_t i = 0; i < n; i++) { + abandon_str(i / 2, b); + ray_t* v2 = ray_str_vec_append(v, b, 24); + st_unhold(v, v2); v = v2; + } + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v) && v->len == n); + TEST_ASSERT_EQ_I(ray_col_save_bulk_gen(v, p, 2), RAY_OK); + TEST_ASSERT_EQ_I(st_desc_enc(p, 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 31 * 64, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(p, 31 * 64 + 63, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_TRUE(st_desc_enc(p, 32 * 64, NULL) != RAY_ENC_STR_DICT); + TEST_ASSERT_TRUE(st_desc_enc(p, ray_enc_nvecs(n) - 1, NULL) != RAY_ENC_STR_DICT); + ray_t* c = st_hold(ray_col_mmap(p)); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + const ray_enc_sdict_t* sd; + TEST_ASSERT_NULL(ray_enccol_strdict(ray_enccol_of(c), &sd)); + TEST_ASSERT_TRUE(sd && sd->n == RAY_ENCW_SDICT_CAP); + TEST_ASSERT_FALSE(ray_enccol_may_have_index(c)); /* a bare file: no recorded kind, no UNIQUE (P6b) */ + ray_t* m = ray_enccol_materialize(c); /* borrowed: the column's cache */ + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && st_same(m, v)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_NONE); + PASS(); +} + +/* Review focus 5: equal long strings at distinct pool offsets with differing + * cached hashes are one value for CONST and for STR_DICT. */ +static test_result_t test_representation_not_value(void) { + ray_t* v = st_hold(ray_vec_new(RAY_STR, 2048)); + ray_t* u = st_hold(ray_vec_new(RAY_STR, 2048)); /* the same strings, untouched hashes */ + for (int i = 0; i < 2048; i++) { + ray_t* v2 = ray_str_vec_append(v, "the same long string value", 26); + st_unhold(v, v2); v = v2; + ray_t* u2 = ray_str_vec_append(u, "the same long string value", 26); + st_unhold(u, u2); u = u2; + } + ray_str_t* s = (ray_str_t*)ray_data(v); + TEST_ASSERT_TRUE(s[0].pool_off != s[1].pool_off); + s[1].hash32 = s[0].hash32 ^ 0x5A5A; /* a different cached hash */ + TEST_ASSERT_TRUE(s[1].hash32 != s[0].hash32); + static const struct { const char* rel; int enc; } fs[] = { + { "/rc", RAY_ENC_CONST }, { "/rd", RAY_ENC_STR_DICT }, { "/uc", RAY_ENC_CONST }, { "/ud", RAY_ENC_STR_DICT } }; + for (int k = 0; k < 4; k++) { + char rel[64]; snprintf(rel, sizeof rel, ST_TMP "%s", fs[k].rel); + ray_encw_test_force_str(fs[k].enc); + ray_err_t e = ray_col_save_gen(k < 2 ? v : u, ray_test_tmp(rel), 2); + ray_encw_test_force_str(-1); + TEST_ASSERT_EQ_I(e, RAY_OK); + } + TEST_ASSERT_EQ_I(st_desc_enc(STP("/rc"), 0, NULL), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(st_desc_enc(STP("/rc"), 1, NULL), RAY_ENC_CONST); + TEST_ASSERT_EQ_I(st_desc_enc(STP("/rd"), 0, NULL), RAY_ENC_STR_DICT); + /* the cached hash is representation: the files equal the untouched ones */ + size_t na, nb; + uint8_t* fa = slurp_file(STP("/rc"), &na); uint8_t* fb = slurp_file(STP("/uc"), &nb); + bool same = fa && fb && na == nb && memcmp(fa, fb, na) == 0; + free(fa); free(fb); + TEST_ASSERT_TRUE(same); + fa = slurp_file(STP("/rd"), &na); fb = slurp_file(STP("/ud"), &nb); + same = fa && fb && na == nb && memcmp(fa, fb, na) == 0; + free(fa); free(fb); + TEST_ASSERT_TRUE(same); + ray_t* c = st_hold(ray_col_mmap(STP("/rd"))); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + const ray_enc_sdict_t* sd; + TEST_ASSERT_NULL(ray_enccol_strdict(ray_enccol_of(c), &sd)); + TEST_ASSERT_TRUE(sd && sd->n == 1); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && st_same(m, v)); + c = st_hold(ray_col_mmap(STP("/rc"))); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m) && st_same(m, v)); + PASS(); +} + +/* The stream writer (.csv.splayed) and the resident writer write the same + * STR file, dictionary and FSST table included: the stream, the resave of + * the encoded source (range reads), and the plain in-memory vector through + * ray_col_save_gen and ray_col_save_bulk_gen (the converters' path). Order + * 0 is the brief's (low cardinality first: 64 STR_DICT, 4 FSST, 69 RAW + * vectors); order 1 puts the URLs first (an FSST table trained on them: + * 64 FSST vectors, then 73 STR_DICT). */ +static const char* se_row(int o, int64_t i, char* b) { + return (i < 70000) == (o == 0) ? gen_lowcard(i, b) : gen_urls(i, b); +} +static test_result_t test_stream_equals_resident(void) { + char b[256], q[600], csv[64], cs[64], rs[64]; + for (int o = 0; o < 2; o++) { + snprintf(csv, sizeof csv, ST_TMP "/in%d.csv", o); + snprintf(cs, sizeof cs, "/cs%d", o); snprintf(rs, sizeof rs, "/rs%d", o); + FILE* f = fopen(ray_test_tmp(csv), "w"); + TEST_ASSERT_NOT_NULL(f); + fprintf(f, "s,v\n"); + for (int64_t i = 0; i < 140000; i++) fprintf(f, "%s,%lld\n", se_row(o, i, b), (long long)i); + fclose(f); + snprintf(q, sizeof q, "(.csv.splayed {compress: true} [STR I64] \"%s\" \"" ST_TMP "%s/\")", csv, cs); + ST_Q_OK(q); + ray_enc_counters_reset(); + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "%s/\" (.db.splayed.get \"" ST_TMP "%s/\") {compress: true})", rs, cs); + ST_Q_OK(q); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + /* the encoded source is re-encoded by range reads: nothing materialized */ + TEST_ASSERT_FMT(kc.materialized == 0, "order %d: the resave materialized %llu columns", o, + (unsigned long long)kc.materialized); + ray_t* v = st_hold(ray_vec_new(RAY_STR, 140000)); + for (int64_t i = 0; i < 140000; i++) { + const char* sv = se_row(o, i, b); + ray_t* v2 = ray_str_vec_append(v, sv, strlen(sv)); + st_unhold(v, v2); v = v2; + } + TEST_ASSERT_EQ_I(ray_col_save_gen(v, STP("/pl"), 2), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_bulk_gen(v, STP("/pb"), 2), RAY_OK); + st_unhold(v, NULL); ray_release(v); + char pc[600], pr[600]; + TEST_ASSERT_TRUE(st_live(cs, "s", pc, sizeof pc)); + TEST_ASSERT_TRUE(st_live(rs, "s", pr, sizeof pr)); + /* the subject: the dictionary and the FSST table both in use */ + TEST_ASSERT_EQ_I(st_desc_enc(pc, o ? 64 : 0, NULL), RAY_ENC_STR_DICT); + TEST_ASSERT_EQ_I(st_desc_enc(pc, o ? 0 : 64, NULL), RAY_ENC_FSST); + if (o == 0) TEST_ASSERT_EQ_I(st_desc_enc(pc, 96, NULL), RAY_ENC_RAW); + size_t na; + uint8_t* pa = slurp_file(pc, &na); + TEST_ASSERT_NOT_NULL(pa); + free(st_mem); st_mem = pa; /* freed in teardown */ + /* the stream and the resave both carry the DICT (P6b): byte identity in full */ + size_t nr; uint8_t* pr2 = slurp_file(pr, &nr); + const bool rsame = pr2 && nr == na && memcmp(pa, pr2, na) == 0; + free(pr2); + TEST_ASSERT_FMT(rsame, "order %d: resave differs from the stream", o); + ray_enc_hdr_t eh; memcpy(&eh, pa + 32, sizeof eh); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_DICT); + TEST_ASSERT_TRUE(eh.index_off > 96 && eh.index_off < na); + /* the bare files carry none: each is the stream's bytes before its + * region's 32-alignment padding, its header without the region + * (index_kind 0, index_off 0, end_off the bare file's size) */ + const uint64_t cut = eh.index_off; + const char* const bare[2] = { STP("/pl"), STP("/pb") }; + for (int k = 0; k < 2; k++) { + size_t nb; uint8_t* pb = slurp_file(bare[k], &nb); + bool same = pb && nb >= 96 && nb <= cut && ray_enc_pad32(nb) == cut; + if (same) { + uint8_t* norm = malloc(nb); + same = norm != NULL; + if (same) { + memcpy(norm, pa, nb); + ray_enc_hdr_t nh = eh; nh.index_kind = 0; nh.index_off = 0; nh.end_off = nb; + memcpy(norm + 32, &nh, sizeof nh); + same = memcmp(pb, norm, nb) == 0; + for (uint64_t i = nb; same && i < cut; i++) same = pa[i] == 0; + } + free(norm); + } + free(pb); + TEST_ASSERT_FMT(same, "order %d bare writer %d differs from the stream outside the region", o, k); + } + } + PASS(); +} + +/* ---- P6b: the persisted DICT (spec "Writing the index", "STR dictionary index") ---- */ + +/* The live file's region view of column `col` of the table at ST_TMP `rel`: + * NULL with *v filled (ray_enc_dict_parse), or the error. + * *m (owned) holds the file bytes, 32-aligned. */ +static ray_t* st_dict_view(const char* rel, const char* col, uint8_t** m, ray_enc_dict_view_t* v) { + char p[600]; + *m = NULL; + if (!st_live(rel, col, p, sizeof p)) return ray_error("io", "no live file"); + ray_enc_hdr_t eh = st_hdr(p); + if (eh.index_kind != RAY_IDX_DICT) return ray_error("domain", "index_kind %u", eh.index_kind); + size_t n = 0; uint8_t* raw = slurp_file(p, &n); + if (!raw) return ray_error("io", "read"); + *m = aligned_alloc(32, (n + 31) & ~(size_t)31); + if (!*m) { free(raw); return ray_error("oom", "copy"); } + memcpy(*m, raw, n); free(raw); + ray_enc_dict_parse(*m + eh.index_off, v); + return NULL; +} + +/* Generation 0's condition, per write path: 65535 rows (none), 65536 + * (DICT), a HASH column (HASH), a bare file (none), a staged save (none on + * both generations: it builds no indexes), the test hook (none); the + * region's codes equal generation 0's. */ +static test_result_t test_idict_build_condition(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 65536))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/c65536/\" (table [s] (list S)) {compress: true})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/c65535/\" (table [s] (list (take S 65535))) {compress: true})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/ch/\" (table [s] (list (.idx.hash S))) {compress: true})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/c0/\" (table [s] (list S)) {compress: false})"); + char p[600]; + TEST_ASSERT_TRUE(st_live("/c65535", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + TEST_ASSERT_TRUE(st_live("/ch", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_HASH); + uint8_t* m = NULL; ray_enc_dict_view_t v; + ray_t* e = st_dict_view("/c65536", "s", &m, &v); + free(st_mem); st_mem = m; /* freed in teardown */ + if (e) st_hold(e); + TEST_ASSERT_NULL(e); + TEST_ASSERT_EQ_I(v.n_distinct, 300); + /* generation 0's passenger DICT over the same data */ + ray_t* t0 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/c0/\")"))); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0)); + ray_t* a = ray_table_col(t0, ray_sym_intern("s", 1)); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + TEST_ASSERT_EQ_I(ray_index_kind(a), RAY_IDX_DICT); + ray_index_t* x = ray_index_payload(a->index); + TEST_ASSERT_EQ_I(x->u.dict.n_distinct, v.n_distinct); + TEST_ASSERT_TRUE(memcmp(ray_data(x->u.dict.codes), v.codes, 65536 * 4) == 0); + TEST_ASSERT_TRUE(memcmp(ray_data(x->u.dict.first_occ), v.first_occ, 300 * 4) == 0); + /* a bare file: no DICT */ + ray_t* sv = st_hold(ray_eval_str("S")); + TEST_ASSERT_EQ_I(ray_col_save_gen(sv, STP("/bare"), 2), RAY_OK); + TEST_ASSERT_EQ_I(st_hdr(STP("/bare")).index_kind, 0); + /* a staged save (the parted converter's leaf save): generation 0 + * attaches no DICT there, so generation 2 records none */ + ray_t* tb = st_hold(ray_eval_str("(table [s] (list S))")); + TEST_ASSERT_TRUE(tb && !RAY_IS_ERR(tb)); + TEST_ASSERT_EQ_I(ray_splay_save_staged_bulk_mode(tb, STP("/sg0"), NULL, RAY_COMPRESS_OFF), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_staged_bulk_mode(tb, STP("/sg2"), NULL, RAY_COMPRESS_ON), RAY_OK); + ray_t* s0 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/sg0/\")"))); + TEST_ASSERT_TRUE(s0 && !RAY_IS_ERR(s0)); + ray_t* a0 = ray_table_col(s0, ray_sym_intern("s", 1)); + TEST_ASSERT_TRUE(a0 && !RAY_IS_ERR(a0)); + TEST_ASSERT_EQ_I(ray_index_kind(a0), RAY_IDX_NONE); + TEST_ASSERT_TRUE(st_live("/sg2", "s", p, sizeof p)); + const ray_enc_hdr_t sh = st_hdr(p); + TEST_ASSERT_TRUE(memcmp(sh.magic, "RENC", 4) == 0); /* a generation-2 file */ + TEST_ASSERT_EQ_I(sh.index_kind, 0); + /* the hook suppresses the build */ + ray_col_test_no_dict(true); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/cn/\" (table [s] (list S)) {compress: true})"); + ray_col_test_no_dict(false); + TEST_ASSERT_TRUE(st_live("/cn", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + PASS(); +} + +/* A generation-2 table whose column records a DICT, resaved through a + * path without index building, records none; resaved with index building, + * it records the same region bytes. */ +static test_result_t test_idict_not_inherited(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/n1/\" (table [s] (list S)) {compress: true})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/n2/\" (.db.splayed.get \"" ST_TMP "/n1/\") {compress: true})"); + char p1[600], p2[600]; + TEST_ASSERT_TRUE(st_live("/n1", "s", p1, sizeof p1)); + TEST_ASSERT_TRUE(st_live("/n2", "s", p2, sizeof p2)); + TEST_ASSERT_EQ_I(st_hdr(p1).index_kind, RAY_IDX_DICT); + size_t a = 0, b = 0; + uint8_t* fa = slurp_file(p1, &a); uint8_t* fb = slurp_file(p2, &b); + const bool same = fa && fb && a == b && memcmp(fa, fb, a) == 0; + free(fa); free(fb); + TEST_ASSERT_TRUE(same); + /* the column writer without the save's decision: ray_col_save_ctx with kind 0 */ + ray_t* t = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/n1/\")"))); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* enc = ray_table_get_col_enc(t, ray_sym_intern("s", 1)); + TEST_ASSERT_NOT_NULL(enc); + ray_col_write_t w; memset(&w, 0, sizeof w); + TEST_ASSERT_NULL(ray_col_src_bind(enc, &w.src)); + w.name = "s"; w.gen = 2; + const ray_err_t se = ray_col_save_ctx(&w, STP("/inh")); + ray_col_src_release(&w.src); + TEST_ASSERT_EQ_I(se, RAY_OK); + TEST_ASSERT_EQ_I(st_hdr(STP("/inh")).index_kind, 0); + TEST_ASSERT_EQ_U(st_hdr(STP("/inh")).index_off, 0); + PASS(); +} + +/* ---- P6b Task 3: the persisted DICT's reader ---- */ + +/* Real text's shape: all-"" vectors (CONST), FSST vectors, STR_DICT + * vectors and "" rows in one column, over 3 chunks. P6's runtime DICT + * never covered it; the persisted DICT equals generation 0's. Chunk 1 + * is high-cardinality text (FSST: not a dictionary chunk by the 7/8 gain + * rule) but for its all-"" vectors; chunks 0 and 2 are dictionary chunks. */ +static const char* gen_realtext(int64_t i, char* b) { + const int64_t v = i / 1024; + if (v % 7 == 3) return ""; /* an all-"" vector */ + if (i % 13 == 0) return ""; + return v / 64 == 1 ? gen_hc(i, b) : gen_lowcard(i, b); +} +static test_result_t test_idict_mixed_encodings(void) { + ray_t* v = st_hold(str_col(3 * 65536, gen_realtext)); + ray_t* tb = st_hold(ray_table_new(1)); + ray_t* tb2 = ray_table_add_col(tb, ray_sym_intern("s", 1), v); + st_unhold(tb, tb2); tb = tb2; + TEST_ASSERT_EQ_I(ray_env_set(ray_sym_intern("W", 1), tb), RAY_OK); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/mx0/\" W {compress: false})"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/mx2/\" W {compress: true})"); + char p[600]; TEST_ASSERT_TRUE(st_live("/mx2", "s", p, sizeof p)); + int encs[16] = { 0 }; + for (int64_t vv = 0; vv < 3 * 64; vv++) encs[st_desc_enc(p, vv, NULL) & 15]++; + TEST_ASSERT_FMT(encs[RAY_ENC_CONST] > 0 && encs[RAY_ENC_FSST] > 0 && encs[RAY_ENC_STR_DICT] > 0, + "CONST %d FSST %d STR_DICT %d", encs[RAY_ENC_CONST], encs[RAY_ENC_FSST], encs[RAY_ENC_STR_DICT]); + ray_t* t0 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/mx0/\")"))); + ray_t* t2 = st_hold(ray_eval_str(ray_test_tmp("(.db.splayed.get \"" ST_TMP "/mx2/\")"))); + TEST_ASSERT_TRUE(t0 && !RAY_IS_ERR(t0) && t2 && !RAY_IS_ERR(t2)); + int64_t sym = ray_sym_intern("s", 1); + ray_t* a = ray_table_col(t0, sym); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a) && ray_index_kind(a) == RAY_IDX_DICT); + ray_index_t* x = ray_index_payload(a->index); + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t2, sym)); + TEST_ASSERT_NOT_NULL(e); + const ray_enc_idict_t* d = NULL; + TEST_ASSERT_NULL(ray_enccol_idict(e, &d)); + TEST_ASSERT_TRUE(d && d->n_distinct == x->u.dict.n_distinct); + TEST_ASSERT_TRUE(memcmp(d->first_occ, ray_data(x->u.dict.first_occ), (size_t)d->n_distinct * 4) == 0); + ray_t* cv = NULL; + TEST_ASSERT_NULL(ray_enccol_idict_codes_vec(e, &cv)); + TEST_ASSERT_TRUE(memcmp(ray_data(cv), ray_data(x->u.dict.codes), (size_t)3 * 65536 * 4) == 0); + TEST_ASSERT_TRUE(d->ent->null_code != UINT32_MAX); /* "" is an entry */ + PASS(); +} + +/* ---- P6b Task 4: group-by on DICT codes ---- */ + +/* q on the in-memory table M (no index: the plain STR answer) and on the + * load `load2` (generation 2, or generation 0 with its DICT): equal + * formatted results. The reference the DICT routes answer to. */ +static test_result_t st_same_mem(const char* load2, const char* q) { + ray_t* out[2] = { NULL, NULL }; + for (int g = 0; g < 2; g++) { + if (g) ST_Q_OK_N(load2); else ST_Q_OK_N("(set T M)"); + out[g] = st_q_fmt(q); + TEST_ASSERT_FMT(out[g] != NULL, "%s %s: %s", q, g ? "gen 2" : "in memory", st_msg); + st_hold(out[g]); + } + TEST_ASSERT_FMT(ray_str_len(out[0]) == ray_str_len(out[1]) && + memcmp(ray_str_ptr(out[0]), ray_str_ptr(out[1]), ray_str_len(out[0])) == 0, + "%s: in memory %.*s vs gen 2 %.*s", q, (int)ray_str_len(out[0]), ray_str_ptr(out[0]), + (int)ray_str_len(out[1]), ray_str_ptr(out[1])); + for (int g = 0; g < 2; g++) { st_unhold(out[g], NULL); ray_release(out[g]); } + PASS(); +} +#define ST_SAME_MEM(load2, q) do { test_result_t r_ = st_same_mem((load2), (q)); \ + if (r_.status != TEST_PASS) return r_; } while (0) + +/* s's own decoded bytes (the per-column counter) on the loaded table T */ +static uint64_t st_col_decoded(const char* col) { + ray_t* t = ray_eval_str("T"); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return UINT64_MAX; } + ray_enccol_t* e = ray_enccol_of(ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col)))); + uint64_t n = e ? atomic_load(&e->decoded_bytes) : UINT64_MAX; + ray_release(t); + return n; +} + +/* q18 / q34 / q35 / composite / selection shapes on a DICT column: the + * answers equal generation 0 (by asc: unordered group output is + * unspecified), nothing materialized. Decoded bytes: the shapes that read + * no value decode nothing at all; the composite key reads u (I64) by range, + * decoding its vectors; for every shape the key column's own counter + * (e->decoded_bytes) stays 0. */ +#define ST_GB_TABLE "(table [s u f] (list (as 'STR (map (fn [j] (if (== 3 (% (div j 1024) 7)) \"\" " \ + "(if (== 1 (% (div j 1024) 5)) (format \"https://e.org/%/%\" j (* j 31)) (format \"category number % long\" (% j 37))))) (til 140000))) " \ + "(% (til 140000) 11) (as 'U8 (% (til 140000) 3))))" +#define ST_GB_LOAD2 "(set T (.db.splayed.get \"" ST_TMP "/gb2/\"))" +#define ST_GB_LOAD0 "(set T (.db.splayed.get \"" ST_TMP "/gb0/\"))" +static test_result_t test_idict_groupby(void) { + ST_SAVE2("gb", ST_GB_TABLE); + ST_Q_OK_N("(set M " ST_GB_TABLE ")"); + char p[600]; TEST_ASSERT_TRUE(st_live("/gb2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + static const struct { const char* q; bool key_only; } qs[] = { + { "(select {n: (count s) from: T by: s asc: s})", true }, /* count s by s (q34) */ + { "(select {one: 1 s: s n: (count s) from: T by: s asc: s})", true }, /* q35's shape */ + { "(select {n: (count u) from: T by: s asc: s})", true }, /* count reads no u value */ + { "(select {n: (count u) from: T by: {u: u s: s} asc: [u s]})", false }, /* composite (q18) */ + /* under a selection: count reads no u value, and the where compares + * on f's encoded vectors, so nothing decodes */ + { "(select {n: (count u) from: T where: (== f 1) by: s asc: s})", true }, + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + st_fk_t k = { 0 }; + ST_SAME("gb", qs[i].q, &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: materialized %llu", qs[i].q, (unsigned long long)k.mat); + if (qs[i].key_only) + TEST_ASSERT_FMT(k.dec == 0, "%s: decoded %llu", qs[i].q, (unsigned long long)k.dec); + else + TEST_ASSERT_FMT(k.dec > 0, "%s: u / f read without a decode", qs[i].q); + const uint64_t sd = st_col_decoded("s"); + TEST_ASSERT_FMT(sd == 0, "%s: s decoded %llu", qs[i].q, (unsigned long long)sd); + ST_SAME_MEM(ST_GB_LOAD2, qs[i].q); + } + /* an aggregate over an expression of the key, or of the key itself + * other than a plain count: the swap rule declines the codes and the + * column is read as strings. Compared with the in-memory table (no + * index), from generation 2 and from generation 0 (its DICT arm). */ + static const char* const decl[] = { + "(select {m: (max (strlen s)) from: T by: s asc: s})", + "(select {m: (sum (strlen s)) from: T by: s asc: s})", + "(select {m: (sum (strlen s)) n: (count s) from: T where: (== f 1) by: s asc: s})", + "(select {m: (first s) from: T by: s asc: s})", + "(select {n: (count u) from: T by: {s: s l: (strlen s)} asc: [s l]})", + }; + { /* generation 0 keeps its DICT (the arm under test) */ + ST_Q_OK_N(ST_GB_LOAD0); + ray_t* kd = ray_eval_str("(at (.idx.info (at T 's)) 'kind)"); + TEST_ASSERT_TRUE(kd && !RAY_IS_ERR(kd) && kd->type == -RAY_SYM && kd->i64 == ray_sym_intern("dict", 4)); + ray_release(kd); + } + for (size_t i = 0; i < sizeof decl / sizeof decl[0]; i++) { + ST_SAME_MEM(ST_GB_LOAD2, decl[i]); + ST_SAME_MEM(ST_GB_LOAD0, decl[i]); + } + ST_SAME("gb", "(select {m: (first s) from: T by: s asc: s})", NULL); + /* a count-distinct beside the key: the stashed result codes' consumer */ + ST_SAME("gb", "(select {d: (count (distinct u)) from: T by: s asc: s})", NULL); + ST_SAME_MEM(ST_GB_LOAD2, "(select {d: (count (distinct u)) from: T by: s asc: s})"); + /* the counter sees s's range decodes: the filter reads the DICT codes + * (P6b Task 5), and the output's gather of s decodes the matched URL + * vector (not STR_DICT) by range */ + ST_SAME("gb", "(select {s: s from: T where: (== s \"https://e.org/1024/31744\")})", NULL); + TEST_ASSERT_TRUE(st_col_decoded("s") > 0); + /* Task 3 review Minor 5: by: s and distinct on the DICT column equal + * generation 0 and the in-memory table (sorted) */ + static const char* const par[] = { + "(select {from: T by: s asc: s})", "(asc (distinct (at T 's)))", "(count (distinct (at T 's)))", + }; + for (size_t i = 0; i < sizeof par / sizeof par[0]; i++) { + ST_SAME("gb", par[i], NULL); + ST_SAME_MEM(ST_GB_LOAD2, par[i]); + } + PASS(); +} + +/* Parted: segments with conflicting codes (the same string, different + * codes; the same code, different strings), one segment below 65536 rows + * (no DICT, STR_DICT vectors): the answers of generation 0 and of the + * in-memory concatenation (no index), nothing materialized where the swap + * admits the key (a plain count of it included). */ +#define ST_GP_LOAD2 "(set T (.db.parted.get \"" ST_TMP "/gp2\" 't))" +static test_result_t test_idict_groupby_parted(void) { + ST_Q_OK("(set P0 (table [s v] (list (as 'STR (map (fn [j] (format \"k%\" (% j 50))) (til 70000))) (til 70000))))"); + ST_Q_OK("(set P1 (table [s v] (list (as 'STR (map (fn [j] (format \"k%\" (- 49 (% j 50)))) (til 70000))) (til 70000))))"); + ST_Q_OK("(set P2 (table [s v] (list (as 'STR (map (fn [j] (format \"z%\" (% j 7))) (til 1000))) (til 1000))))"); + ST_Q_OK("(set M (concat P0 (concat P1 P2)))"); + for (int g = 0; g <= 2; g += 2) + for (int p = 0; p < 3; p++) { + char q[512]; + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/gp%d/2024.01.0%d/t/\" P%d {compress: %s})", + g, p + 1, p, g ? "true" : "false"); + ST_Q_OK(q); + } + char p[600]; + TEST_ASSERT_TRUE(st_live("/gp2/2024.01.01/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + TEST_ASSERT_TRUE(st_live("/gp2/2024.01.02/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + TEST_ASSERT_TRUE(st_live("/gp2/2024.01.03/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + static const struct { const char* q; bool key_only; } qs[] = { + { "(select {n: (count s) from: T by: s asc: s})", true }, /* the brief's q34 shape */ + { "(select {one: 1 s: s n: (count s) from: T by: s asc: s})", true }, /* q35's */ + { "(select {n: (count v) from: T by: s asc: s})", true }, + { "(select {n: (count s) from: T where: (!= s \"k3\") by: s asc: s})", false }, + { "(select {n: (count v) from: T where: (> v 500) by: s asc: s})", false }, + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + st_fk_t k = { 0 }; + ST_SAME_P("gp", qs[i].q, &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: materialized %llu", qs[i].q, (unsigned long long)k.mat); + if (qs[i].key_only) TEST_ASSERT_FMT(k.dec == 0, "%s: decoded %llu", qs[i].q, (unsigned long long)k.dec); + ST_SAME_MEM(ST_GP_LOAD2, qs[i].q); + } + /* an aggregate over an expression of the key: declined, read as strings */ + static const char* const decl[] = { + "(select {m: (max (strlen s)) from: T by: s asc: s})", + "(select {m: (sum (strlen s)) from: T by: s asc: s})", + "(select {m: (sum (strlen s)) from: T where: (> v 500) by: s asc: s})", + }; + for (size_t i = 0; i < sizeof decl / sizeof decl[0]; i++) { + ST_SAME_P("gp", decl[i], NULL); + ST_SAME_MEM(ST_GP_LOAD2, decl[i]); + } + PASS(); +} + +/* ---- P6b Task 5: equality on DICT codes ---- */ + +/* The answer of q on T as loaded by `load` (st_q_fmt's text), or NULL with + * st_msg set. */ +static ray_t* st_ans(const char* load, const char* q) { + if (load && !st_q_run(load)) return NULL; + return st_q_fmt(q); +} + +/* vectors cycling through "" (the in-band null), URL-like strings (FSST) + * and 37 categories (STR_DICT vectors); the DICT records them all; f a U8 + * flag (a conjunct on it ranks before the STR one) */ +#define ST_FD_TABLE "(table [s v f] (list (as 'STR (map (fn [j] (if (== 3 (% (div j 1024) 7)) \"\" " \ + "(if (== 1 (% (div j 1024) 5)) (format \"https://e.org/%/%\" j (* j 31)) (format \"category number % long\" (% j 37))))) (til 140000))) " \ + "(til 140000) (as 'U8 (% (til 140000) 3))))" +#define ST_FD_LOAD2 "(set T (.db.splayed.get \"" ST_TMP "/fe2/\"))" +/* s's published materialization on the loaded table T */ +static bool st_col_mat(const char* col) { + ray_t* t = ray_eval_str("T"); + if (!t || RAY_IS_ERR(t)) { if (t) ray_error_free(t); return true; } + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern(col, strlen(col))); + bool m = !ec || ray_enccol_decoded_peek(ec) != NULL; + ray_release(t); + return m; +} +static test_result_t test_idict_filter(void) { + ST_SAVE2("fe", ST_FD_TABLE); + ST_Q_OK_N("(set M " ST_FD_TABLE ")"); + char p[600]; TEST_ASSERT_TRUE(st_live("/fe2", "s", p, sizeof p)); + TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + /* how each shape is answered: 1 the STR selection as the first + * conjunct, 2 as a refinement, 3 either (the optimizer ranks an STR + * equality beside a U8 one), 0 the fused top-k predicate. Every + * shape: s neither materialized nor decoded, answers equal to + * generation 0 and to the in-memory table. The count shapes' + * whole query materializes nothing; a top-k materializes its key v + * (as with a predicate on v alone: not the filter's doing), and its + * output is projected to v so no s value is gathered. */ + static const struct { const char* q; int how; } qs[] = { + { "(count (select {from: T where: (== s \"category number 5 long\")}))", 1 }, + { "(count (select {from: T where: (!= s \"category number 5 long\")}))", 1 }, + { "(count (select {from: T where: (!= s \"\")}))", 1 }, /* q24-q27, q31 */ + { "(count (select {from: T where: (== s \"\")}))", 1 }, /* "" is the null */ + { "(count (select {from: T where: (== s \"absent\")}))", 1 }, + { "(count (select {from: T where: (!= s \"absent\")}))", 1 }, + { "(count (select {from: T where: (== s \"https://e.org/1024/31744\")}))", 1 }, /* a row of an FSST vector */ + { "(count (select {v: v from: T where: (and (> v 1000) (!= s \"\"))}))", 1 }, /* the STR conjunct ranks first */ + { "(count (select {v: v from: T where: (and (== f 1) (!= s \"\"))}))", 2 }, /* a later conjunct */ + { "(count (select {v: v from: T where: (and (== f 1) (== s \"\"))}))", 1 }, /* ranks first */ + { "(count (select {v: v from: T where: (and (== f 2) (== s \"category number 5 long\"))}))", 3 }, + { "(count (select {v: v from: T where: (and (== f 0) (!= s \"category number 5 long\"))}))", 2 }, + { "(count (select {v: v from: T where: (and (== f 0) (== s \"absent\"))}))", 3 }, + { "(select {v: v from: T where: (!= s \"\") asc: v take: 10})", 0 }, /* top-k predicate (q25) */ + { "(select {v: v from: T where: (!= s \"\") desc: v take: 10})", 0 }, + { "(select {v: v from: T where: (== s \"\") desc: v take: 10})", 0 }, + { "(select {v: v from: T where: (== s \"category number 5 long\") desc: v take: 10})", 0 }, + { "(select {v: v from: T where: (!= s \"category number 5 long\") asc: v take: 10})", 0 }, + { "(select {v: v from: T where: (and (> v 1000) (!= s \"\")) asc: v take: 10})", 0 }, /* a later child */ + { "(select {v: v from: T where: (and (< v 100000) (== s \"\")) desc: v take: 10})", 0 }, + { "(select {v: v from: T where: (== s \"absent\") asc: v take: 10})", 0 }, + { "(select {v: v from: T where: (!= s \"absent\") asc: v take: 10})", 0 }, + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + st_fk_t k = { 0 }; + ST_SAME("fe", qs[i].q, &k); + const uint64_t sd = st_col_decoded("s"); + TEST_ASSERT_FMT(sd == 0, "%s: s decoded %llu", qs[i].q, (unsigned long long)sd); + TEST_ASSERT_FMT(!st_col_mat("s"), "%s: s materialized", qs[i].q); + if (qs[i].how) TEST_ASSERT_FMT(k.mat == 0, "%s: materialized %llu", qs[i].q, (unsigned long long)k.mat); + if (qs[i].how == 1) TEST_ASSERT_FMT(k.sel == 1 && k.refine == 0, "%s: sel %llu refine %llu", qs[i].q, + (unsigned long long)k.sel, (unsigned long long)k.refine); + if (qs[i].how == 2) TEST_ASSERT_FMT(k.refine == 1, "%s: refine %llu", qs[i].q, (unsigned long long)k.refine); + if (qs[i].how == 3) TEST_ASSERT_FMT(k.sel + k.refine == 1, "%s: no STR selection", qs[i].q); + if (qs[i].how == 0) TEST_ASSERT_FMT(k.sel == 0 && k.refine == 0, "%s: not the fused predicate", qs[i].q); + ST_SAME_MEM(ST_FD_LOAD2, qs[i].q); + } + /* the brief's shapes whose output keeps s (an output gather, not the + * filter, reads s): answers only */ + static const char* const ans[] = { + "(count (select {from: T where: (and (> v 1000) (!= s \"\"))}))", + "(count (select {from: T where: (and (== f 1) (== s \"\"))}))", + "(at (select {from: T where: (!= s \"\") asc: v take: 10}) 'v)", + "(at (select {from: T where: (== s \"\") asc: v take: 10}) 's)", + }; + for (size_t i = 0; i < sizeof ans / sizeof ans[0]; i++) { + ST_SAME("fe", ans[i], NULL); + ST_SAME_MEM(ST_FD_LOAD2, ans[i]); + } + /* nothing decoded at all: the filter alone */ + st_fk_t k = { 0 }; + ST_SAME("fe", "(count (select {from: T where: (!= s \"\")}))", &k); + TEST_ASSERT_EQ_U(k.dec, 0); + /* materialized first: the same answers, the DICT still serves (the + * STR selection takes the materialized single file on its codes) */ + static const char* const mq[] = { + "(count (select {from: T where: (== s \"category number 5 long\")}))", + "(count (select {from: T where: (!= s \"\")}))", + "(count (select {from: T where: (== s \"\")}))", + "(select {v: v from: T where: (== s \"\") desc: v take: 10})", + }; + for (size_t i = 0; i < sizeof mq / sizeof mq[0]; i++) { + ray_t* want = st_ans("(set T M)", mq[i]); + TEST_ASSERT_FMT(want != NULL, "%s in memory: %s", mq[i], st_msg); + st_hold(want); + ray_t* want0 = st_ans("(set T (.db.splayed.get \"" ST_TMP "/fe0/\"))", mq[i]); + TEST_ASSERT_FMT(want0 != NULL, "%s gen 0: %s", mq[i], st_msg); + st_hold(want0); + TEST_ASSERT_FMT(ray_str_len(want) == ray_str_len(want0) && + memcmp(ray_str_ptr(want), ray_str_ptr(want0), ray_str_len(want)) == 0, + "%s: in memory %.*s vs gen 0 %.*s", mq[i], (int)ray_str_len(want), ray_str_ptr(want), + (int)ray_str_len(want0), ray_str_ptr(want0)); + st_unhold(want0, NULL); ray_release(want0); + ST_Q_OK(ST_FD_LOAD2); + ST_Q_OK("(set Z (at T 's))"); + TEST_ASSERT_TRUE(st_col_mat("s")); + const uint64_t s0 = ray_exec_test_str_sel(0); + ray_t* got = st_q_fmt(mq[i]); + TEST_ASSERT_FMT(got != NULL, "%s materialized: %s", mq[i], st_msg); + st_hold(got); + /* the top-k shape takes the fused predicate, the others the STR selection */ + const uint64_t want_sel = strstr(mq[i], "take:") ? 0 : 1; + TEST_ASSERT_FMT(ray_exec_test_str_sel(0) - s0 == want_sel, "%s: the materialized DICT column declined", mq[i]); + TEST_ASSERT_FMT(ray_str_len(want) == ray_str_len(got) && + memcmp(ray_str_ptr(want), ray_str_ptr(got), ray_str_len(want)) == 0, + "%s: in memory and gen 0 %.*s vs materialized %.*s", mq[i], (int)ray_str_len(want), ray_str_ptr(want), + (int)ray_str_len(got), ray_str_ptr(got)); + st_unhold(got, NULL); ray_release(got); + st_unhold(want, NULL); ray_release(want); + ST_Q_OK("(set Z 0)"); + } + PASS(); +} + +/* Parted: segments with conflicting codes (the same string, different + * codes), "" rows at different codes, and one segment below 65536 rows (no + * DICT, STR_DICT vectors): generation 0 and the in-memory concatenation + * (no index) agree; a forged code in a DICT segment proves its codes are + * what the selection reads. */ +#define ST_FPT_LOAD2 "(set T (.db.parted.get \"" ST_TMP "/fpt2\" 't))" +static test_result_t test_idict_filter_parted(void) { + ST_Q_OK("(set P0 (table [s] (list (as 'STR (map (fn [j] (if (== 7 (% j 50)) \"\" (format \"k%\" (% j 50)))) (til 70000))))))"); + ST_Q_OK("(set P1 (table [s] (list (as 'STR (map (fn [j] (if (== 20 (% j 50)) \"\" (format \"k%\" (- 49 (% j 50))))) (til 70000))))))"); + ST_Q_OK("(set P2 (table [s] (list (as 'STR (map (fn [j] (if (== 3 (% j 9)) \"\" (format \"z%\" (% j 7)))) (til 1000))))))"); + ST_Q_OK("(set M (concat P0 (concat P1 P2)))"); + for (int g = 0; g <= 2; g += 2) + for (int p = 0; p < 3; p++) { + char q[512]; + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/fpt%d/2024.01.0%d/t/\" P%d {compress: %s})", + g, p + 1, p, g ? "true" : "false"); + ST_Q_OK(q); + } + char p[600]; + TEST_ASSERT_TRUE(st_live("/fpt2/2024.01.01/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + TEST_ASSERT_TRUE(st_live("/fpt2/2024.01.02/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + TEST_ASSERT_TRUE(st_live("/fpt2/2024.01.03/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, 0); + static const char* const qs[] = { + "(count (select {from: T where: (== s \"k3\")}))", + "(count (select {from: T where: (!= s \"k3\")}))", + "(count (select {from: T where: (!= s \"z1\")}))", + "(count (select {from: T where: (== s \"z1\")}))", + "(count (select {from: T where: (== s \"absent\")}))", + "(count (select {from: T where: (!= s \"absent\")}))", + "(count (select {from: T where: (== s \"\")}))", + "(count (select {from: T where: (!= s \"\")}))", + "(count (select {from: T where: (and (!= s \"k3\") (!= s \"\"))}))", + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + st_fk_t k = { 0 }; + ST_SAME_P("fpt", qs[i], &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: materialized %llu", qs[i], (unsigned long long)k.mat); + TEST_ASSERT_FMT(k.sel == 1, "%s: sel %llu", qs[i], (unsigned long long)k.sel); + ST_SAME_MEM(ST_FPT_LOAD2, qs[i]); + } + PASS(); +} + +/* Parted beside other segment kinds (review Minor 4): two DICT segments + * with conflicting codes, a generation-0 partition in the encoded store and + * a ragged partition without s (a synthetic all-null segment): the answers + * of the all-generation-0 store and of the in-memory concatenation (the + * ragged rows as ""). */ +#define ST_FPM_LOAD2 "(set T (.db.parted.get \"" ST_TMP "/fpm2\" 't))" +static test_result_t test_idict_filter_parted_mixed(void) { + ST_Q_OK("(set P0 (table [v s] (list (til 70000) (as 'STR (map (fn [j] (if (== 7 (% j 50)) \"\" (format \"k%\" (% j 50)))) (til 70000))))))"); + ST_Q_OK("(set P1 (table [v s] (list (til 3000) (as 'STR (map (fn [j] (if (== 0 (% j 7)) \"\" (format \"g%\" (% j 41)))) (til 3000))))))"); + ST_Q_OK("(set P2 (table [v] (list (til 2000))))"); + ST_Q_OK("(set P2M (table [v s] (list (til 2000) (as 'STR (map (fn [j] \"\") (til 2000))))))"); + ST_Q_OK("(set P3 (table [v s] (list (til 70000) (as 'STR (map (fn [j] (if (== 20 (% j 50)) \"\" (format \"k%\" (- 49 (% j 50))))) (til 70000))))))"); + ST_Q_OK("(set M (concat P0 (concat P1 (concat P2M P3))))"); + for (int g = 0; g <= 2; g += 2) + for (int p = 0; p < 4; p++) { + char q[512]; + /* the second partition (p == 1, 2024.01.02) stays generation 0 in the encoded store */ + const bool enc = g == 2 && p != 1; + snprintf(q, sizeof q, "(.db.splayed.set \"" ST_TMP "/fpm%d/2024.01.0%d/t/\" P%d {compress: %s})", + g, p + 1, p, enc ? "true" : "false"); + ST_Q_OK(q); + } + char p[600]; + TEST_ASSERT_TRUE(st_live("/fpm2/2024.01.01/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + TEST_ASSERT_TRUE(st_live("/fpm2/2024.01.04/t", "s", p, sizeof p)); TEST_ASSERT_EQ_I(st_hdr(p).index_kind, RAY_IDX_DICT); + static const char* const qs[] = { + "(count (select {from: T where: (== s \"k3\")}))", + "(count (select {from: T where: (!= s \"k3\")}))", + "(count (select {from: T where: (== s \"g5\")}))", /* the generation-0 partition only */ + "(count (select {from: T where: (!= s \"g5\")}))", + "(count (select {from: T where: (== s \"\")}))", /* the ragged rows included */ + "(count (select {from: T where: (!= s \"\")}))", + "(count (select {from: T where: (== s \"absent\")}))", + "(count (select {from: T where: (!= s \"absent\")}))", + "(sum (at (select {from: T where: (== s \"k3\")}) 'v))", + "(count (select {from: T where: (and (> v 1000) (== s \"\"))}))", + "(count (select {from: T where: (and (== v 7) (!= s \"k3\"))}))", + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + st_fk_t k = { 0 }; + ST_SAME_P("fpm", qs[i], &k); + TEST_ASSERT_FMT(k.mat == 0, "%s: materialized %llu", qs[i], (unsigned long long)k.mat); + TEST_ASSERT_FMT(k.sel + k.refine == 1, "%s: no STR selection", qs[i]); + ST_SAME_MEM(ST_FPM_LOAD2, qs[i]); + } + PASS(); +} + +/* An out-of-range code in the rows a filter reads: corrupt naming the + * file, in the STR selection and in a top-k predicate; rows the filter + * skips are not read. STR `in` on a DICT column answers in both + * generations (ruling Q1 predates string membership). */ +#define ST_FF_TABLE "(table [s v w] (list (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))) (til 70000) " \ + "(as 'U8 (map (fn [j] (if (< j 1000) 1 0)) (til 70000)))))" +#define ST_FF_LOAD2 "(set T (.db.splayed.get \"" ST_TMP "/ff2/\"))" +static test_result_t test_idict_filter_in(void) { + ST_SAVE2("ff", ST_FF_TABLE); + ST_Q_OK_N("(set M " ST_FF_TABLE ")"); + /* STR `in` on a DICT column answers as over the in-memory table, in both + * generations (string membership, dev #789: no longer nyi) */ + static const char* const inq[] = { + "(count (select {from: T where: (in s [\"a\" \"b\"])}))", + "(count (select {from: T where: (in s [\"value 3 of the domain\" \"b\"])}))", + }; + for (size_t i = 0; i < sizeof inq / sizeof inq[0]; i++) { + ST_SAME("ff", inq[i], NULL); + ST_SAME_MEM(ST_FF_LOAD2, inq[i]); + } + PASS(); +} + +/* The runtime DICT is gone: a bare all-STR_DICT file of 70000 rows (no + * recorded kind) materializes without a DICT, as generation 0's bare + * ray_col_save does, and ray_enccol_may_have_index is false. */ +static test_result_t test_idict_runtime_gone(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))))"); + ray_t* sv = st_hold(ray_eval_str("S")); + TEST_ASSERT_TRUE(sv && !RAY_IS_ERR(sv)); + TEST_ASSERT_EQ_I(ray_col_save_gen(sv, STP("/rt"), 2), RAY_OK); + for (int k = 0; k < 2; k++) TEST_ASSERT_FALSE(st_dirent(STP("/rt"), k).flags & RAY_ENC_STAT_ABSENT); /* all STR_DICT */ + TEST_ASSERT_EQ_I(st_hdr(STP("/rt")).index_kind, 0); + ray_t* c = st_hold(ray_col_mmap(STP("/rt"))); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + TEST_ASSERT_FALSE(ray_enccol_may_have_index(c)); + const ray_enc_idict_t* d = (const ray_enc_idict_t*)1; + TEST_ASSERT_NULL(ray_enccol_idict(ray_enccol_of(c), &d)); + TEST_ASSERT_NULL(d); + int64_t code = 0; + TEST_ASSERT_NULL(ray_enccol_idict_code(ray_enccol_of(c), "x", 1, &code)); + TEST_ASSERT_EQ_I(code, -2); + ray_t* m = ray_enccol_materialize(c); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_NONE); + PASS(); +} + +/* Review fix 4: pool workers race the first touch of both tiers on a fresh + * column. Sound file: every racer sees the one entry-tier blob, the one + * code-tier vector and the right codes (code of row i is i % 300), and the + * racers' heaps together keep exactly what one serial first touch keeps + * (the published blob and vector; no loser keeps a copy). Forged files (a + * duplicate entry: the entry tier; a late code: the code tier): every racer + * gets the one cached corrupt verdict, and no racer's heap keeps anything + * of the failed attempt. Every iteration requires every racer to have + * left the barrier with all racers arrived, so a barrier timeout (racers + * run one after another) fails instead of passing serially. */ +#define IR_SLOTS 64 +typedef struct { + ray_enccol_t* e; + int mode; /* 0 sound, 1 entry tier forged, 2 code tier forged */ + _Atomic(int) arrived; + int want; /* soft barrier: the pool's worker count */ + _Atomic(int) next; + const void* d[IR_SLOTS]; + const void* cv[IR_SLOTS]; + char msg[IR_SLOTS][128]; + int bad[IR_SLOTS]; + int64_t leak[IR_SLOTS]; /* the racer's heap delta over its window */ + int met[IR_SLOTS]; /* the racer left the barrier with every racer arrived */ + uint32_t wid[IR_SLOTS]; +} ir_race_t; +static void ir_race_task(void* ctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)lo; (void)hi; + ir_race_t* x = ctx; + const int k = atomic_fetch_add(&x->next, 1); + if (k >= IR_SLOTS) return; + x->wid[k] = wid; + atomic_fetch_add(&x->arrived, 1); + /* bounded by wall clock, not a spin count: a late wake-up (a loaded + * machine, sanitizers) still meets the barrier; only "never arrived" + * times out, and met[k] makes that fail the test */ + const int64_t deadline = ray_time_now_ms() + 2000; + for (unsigned spin = 1; atomic_load(&x->arrived) < x->want; spin++) + if (!(spin & 4095) && ray_time_now_ms() > deadline) break; + x->met[k] = atomic_load(&x->arrived) >= x->want; /* else a timeout: the racers ran serially */ + ray_mem_stats_t m0, m1; + const ray_enc_idict_t* d = NULL; + ray_t* cv = NULL; + if (x->mode == 2) { /* the entry tier holds: measure the code tier alone */ + ray_t* err = ray_enccol_idict(x->e, &d); + if (err) { x->bad[k] = 1; ray_error_free(err); return; } + x->d[k] = d; + } + ray_mem_stats(&m0); + ray_t* err = x->mode == 2 ? NULL : ray_enccol_idict(x->e, &d); + if (!err && x->mode != 2) x->d[k] = d; + if (!err) err = ray_enccol_idict_codes_vec(x->e, &cv); + if (!err) { + ray_mem_stats(&m1); + x->leak[k] = (int64_t)m1.bytes_allocated - (int64_t)m0.bytes_allocated; + } + if (err) { + snprintf(x->msg[k], sizeof x->msg[k], "%s: %s", ray_err_code(err), ray_error_msg() ? ray_error_msg() : ""); + ray_error_free(err); + ray_mem_stats(&m1); + x->leak[k] = (int64_t)m1.bytes_allocated - (int64_t)m0.bytes_allocated; + return; + } + x->cv[k] = cv; + const int32_t* all = (const int32_t*)ray_data(cv); + for (int64_t i = 0; i < cv->len; i++) if (all[i] != (int32_t)(i % 300)) { x->bad[k] = 1; break; } + const int64_t r0 = ((int64_t)k * 1000) % 69000; + const int32_t* cd = NULL; + ray_t* re = ray_enccol_idict_codes(x->e, r0, 1000, &cd); + if (re) { ray_error_free(re); x->bad[k] = 1; return; } + for (int64_t i = 0; i < 1000; i++) if (cd[i] != (int32_t)((r0 + i) % 300)) { x->bad[k] = 1; break; } +} + +static test_result_t test_idict_first_touch_race(void) { + ST_Q_OK("(set S (as 'STR (map (fn [j] (format \"value % of the domain\" (% (* j 7919) 300))) (til 70000))))"); + ST_Q_OK("(.db.splayed.set \"" ST_TMP "/ra/\" (table [s] (list S)) {compress: true})"); + char p[600]; TEST_ASSERT_TRUE(st_live("/ra", "s", p, sizeof p)); + ray_enc_hdr_t eh = st_hdr(p); + TEST_ASSERT_EQ_I(eh.index_kind, RAY_IDX_DICT); + ray_pool_t* pool = ray_pool_get(); + TEST_ASSERT_NOT_NULL(pool); + const uint32_t nw = ray_pool_total_workers(pool); + const uint32_t ntask = nw * 2 < IR_SLOTS ? nw * 2 : IR_SLOTS; + /* What one serial first touch keeps: on this thread's buddy heap (kept) + * and in direct mappings (kept_direct, process-wide). The racers' per- + * thread bytes_allocated deltas are compared with `kept`, which assumes + * every heap rounds a block alike (true: one buddy policy for all + * threads); direct mappings are process-wide, so they are compared once + * per iteration around the whole dispatch (the main thread allocates + * nothing else meanwhile). */ + int64_t kept = 0, kept_direct = 0; + { + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_mem_stats_t m0, m1; + const ray_enc_idict_t* d = NULL; ray_t* cv = NULL; + ray_mem_stats(&m0); + ray_t* err = ray_enccol_idict(ray_enccol_of(c), &d); + if (!err) err = ray_enccol_idict_codes_vec(ray_enccol_of(c), &cv); + ray_mem_stats(&m1); + ray_release(c); + if (err) ray_error_free(err); + TEST_ASSERT_TRUE(err == NULL && d && cv); + kept = (int64_t)m1.bytes_allocated - (int64_t)m0.bytes_allocated; + kept_direct = (int64_t)m1.direct_bytes - (int64_t)m0.direct_bytes; + TEST_ASSERT_TRUE(kept > 0); + } + static ir_race_t x; + bool workers_seen = false; + { + const int mode = 0; + for (int it = 0; it < 40; it++) { + ray_t* c = ray_col_mmap(p); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + memset(&x, 0, sizeof x); + x.e = ray_enccol_of(c); x.mode = mode; x.want = (int)nw; + ray_mem_stats_t dm0, dm1; + ray_mem_stats(&dm0); + ray_pool_dispatch_n(pool, ir_race_task, &x, ntask); + ray_mem_stats(&dm1); + const int64_t held_direct = (int64_t)dm1.direct_bytes - (int64_t)dm0.direct_bytes; + const int n = atomic_load(&x.next) < (int)ntask ? atomic_load(&x.next) : (int)ntask; + bool ok = n == (int)ntask; + int64_t held = 0; + for (int k = 0; k < n && ok; k++) { + ok = !x.bad[k] && x.met[k] && x.leak[k] >= 0; + held += x.leak[k]; + ok = ok && x.msg[k][0] == 0 && x.d[k] == x.d[0] && x.cv[k] == x.cv[0] && + x.cv[k] == (const void*)x.e->icodes && x.d[k] != NULL; + } + if (ok) ok = held == kept && held_direct == kept_direct; /* the one blob and vector, nothing else */ + for (int k = 1; k < n; k++) if (x.wid[k] != x.wid[0]) { workers_seen = true; break; } + ray_release(c); + TEST_ASSERT_FMT(ok, "mode %d iteration %d (%d tasks, held %lld of %lld, direct %lld of %lld): %s", mode, it, n, + (long long)held, (long long)kept, (long long)held_direct, + (long long)kept_direct, n ? x.msg[0] : ""); + } + } + if (pool->n_workers > 0) TEST_ASSERT_TRUE(workers_seen); /* the racers ran on more than one worker */ + PASS(); +} + +const test_entry_t encstr_entries[] = { + { "encstr/strdict_body", test_strdict_body, st_setup, st_teardown }, + { "encstr/fsst_body", test_fsst_body, st_setup, st_teardown }, + { "encstr/fsst_train_verdict", test_fsst_train_verdict, st_setup, st_teardown }, + { "encstr/writer_strdict", test_writer_strdict, st_setup, st_teardown }, + { "encstr/writer_fsst", test_writer_fsst, st_setup, st_teardown }, + { "encstr/writer_two_entries", test_writer_two_entries, st_setup, st_teardown }, + { "encstr/range_reads_str", test_range_reads_str, st_setup, st_teardown }, + { "encstr/range_shared_entry", test_range_shared_entry, st_setup, st_teardown }, + { "encstr/strdict_lookup", test_strdict_lookup, st_setup, st_teardown }, + { "encstr/force_str_wins", test_force_str_wins, st_setup, st_teardown }, + { "encstr/stats_chokepoint", test_stats_chokepoint, st_q_setup, st_q_teardown }, + { "encstr/stats_chokepoint_pooled", test_stats_chokepoint_pooled, st_q_setup, st_q_teardown }, + { "encstr/dict_slot_spread", test_dict_slot_spread, st_setup, st_teardown }, + { "encstr/pool_order", test_pool_order, st_setup, st_teardown }, + { "encstr/dict_equals_gen0", test_dict_equals_gen0, st_q_setup, st_q_teardown }, + { "encstr/dict_variants", test_dict_variants, st_q_setup, st_q_teardown }, + { "encstr/fsst_scopes_query", test_fsst_scopes_query, st_q_setup, st_q_teardown }, + { "encstr/dict_inband_nulls", test_dict_inband_nulls, st_q_setup, st_q_teardown }, + { "encstr/dict_oom_retry", test_dict_oom_retry, st_q_setup, st_q_teardown }, + { "encstr/filter_strdict", test_filter_strdict, st_q_setup, st_q_teardown }, + { "encstr/filter_decided", test_filter_decided, st_q_setup, st_q_teardown }, + { "encstr/filter_chained", test_filter_chained, st_q_setup, st_q_teardown }, + { "encstr/filter_parted", test_filter_parted, st_q_setup, st_q_teardown }, + { "encstr/filter_mixed_chunks", test_filter_mixed_chunks, st_q_setup, st_q_teardown }, + { "encstr/filter_materialized", test_filter_materialized, st_q_setup, st_q_teardown }, + { "encstr/remap_hash_parity", test_remap_hash_parity, st_q_setup, st_q_teardown }, + { "encstr/cross_segment_codes", test_cross_segment_codes, st_q_setup, st_q_teardown }, + { "encstr/groupby_selection", test_groupby_selection, st_q_setup, st_q_teardown }, + { "encstr/mixed_str_groupby", test_mixed_str_groupby, st_q_setup, st_q_teardown }, + { "encstr/groupby_remap_oom", test_groupby_remap_oom, st_q_setup, st_q_teardown }, + { "encstr/abandonment", test_abandonment, st_setup, st_teardown }, + { "encstr/representation_not_value", test_representation_not_value, st_setup, st_teardown }, + { "encstr/stream_equals_resident", test_stream_equals_resident, st_q_setup, st_q_teardown }, + { "encstr/idict_build_condition", test_idict_build_condition, st_q_setup, st_q_teardown }, + { "encstr/idict_not_inherited", test_idict_not_inherited, st_q_setup, st_q_teardown }, + { "encstr/idict_mixed_encodings", test_idict_mixed_encodings, st_q_setup, st_q_teardown }, + { "encstr/idict_runtime_gone", test_idict_runtime_gone, st_q_setup, st_q_teardown }, + { "encstr/idict_first_touch_race", test_idict_first_touch_race, st_q_setup, st_q_teardown }, + { "encstr/idict_groupby", test_idict_groupby, st_q_setup, st_q_teardown }, + { "encstr/idict_groupby_parted", test_idict_groupby_parted, st_q_setup, st_q_teardown }, + { "encstr/idict_filter", test_idict_filter, st_q_setup, st_q_teardown }, + { "encstr/idict_filter_parted", test_idict_filter_parted, st_q_setup, st_q_teardown }, + { "encstr/idict_filter_in", test_idict_filter_in, st_q_setup, st_q_teardown }, + { "encstr/idict_filter_parted_mixed", test_idict_filter_parted_mixed, st_q_setup, st_q_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_exec.c b/test/test_exec.c index cf5f7d719..7d52cdf19 100644 --- a/test/test_exec.c +++ b/test/test_exec.c @@ -6477,7 +6477,7 @@ static test_result_t test_expr_f64_div_zero_scalar(void) { PASS(); } -/* ---- const_expr_to_i64: F64 constant in linear expression (lines 162-167) ---- */ +/* ---- const_expr_to_i64: an F64 constant declines the linear plan ---- */ static test_result_t test_expr_group_linear_f64_const(void) { ray_heap_init(); (void)ray_sym_init(); @@ -6490,8 +6490,8 @@ static test_result_t test_expr_group_linear_f64_const(void) { ray_release(v); /* GROUP n_keys=0, SUM(const_f64(2.0) * a): - * const_expr_to_i64 is called on const_f64(2.0), c_is_f64=true, - * modf(2.0)=0 → exercises lines 162-167 */ + * const_expr_to_i64 is called on const_f64(2.0), c_is_f64=true, so it + * declines and the F64 product is summed as F64 */ ray_graph_t* g = ray_graph_new(tbl); ray_op_t* c2 = ray_const_f64(g, 2.0); ray_op_t* a_op = ray_scan(g, "a"); @@ -6505,8 +6505,9 @@ static test_result_t test_expr_group_linear_f64_const(void) { ray_t* sum_col = ray_table_get_col_idx(result, 0); TEST_ASSERT_NOT_NULL(sum_col); - /* 2*(1+2+3+4+5) = 30 */ - TEST_ASSERT_EQ_I(((int64_t*)ray_data(sum_col))[0], 30); + /* 2.0*(1+2+3+4+5) = 30.0 */ + TEST_ASSERT_EQ_I(sum_col->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(sum_col))[0], 30.0, 0.0); ray_release(result); ray_graph_free(g); @@ -6623,8 +6624,9 @@ static test_result_t test_expr_group_affine_neg_f64_const(void) { ray_t* sum_col = ray_table_get_col_idx(result, 0); TEST_ASSERT_NOT_NULL(sum_col); - /* sum(a - 5) = 5+15+25 = 45 */ - TEST_ASSERT_EQ_I(((int64_t*)ray_data(sum_col))[0], 45); + /* sum(a - 5.0) = 5+15+25 = 45.0 */ + TEST_ASSERT_EQ_I(sum_col->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(sum_col))[0], 45.0, 0.0); ray_release(result); ray_graph_free(g); @@ -6686,8 +6688,9 @@ static test_result_t test_expr_group_affine_const_add(void) { sum_col = ray_table_get_col_idx(result, 0); TEST_ASSERT_NOT_NULL(sum_col); - /* sum(a + 5.0) = 1+2+3 + 3*5 = 21 */ - TEST_ASSERT_EQ_I(((int64_t*)ray_data(sum_col))[0], 21); + /* sum(a + 5.0) = 1+2+3 + 3*5 = 21.0 */ + TEST_ASSERT_EQ_I(sum_col->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(sum_col))[0], 21.0, 0.0); ray_release(result); ray_graph_free(g); @@ -6711,8 +6714,8 @@ static test_result_t test_expr_group_affine_f64_i64(void) { ray_release(v); /* GROUP n_keys=0, SUM(a + const_f64(5.0)): - * try_affine_sumavg_input: bt=RAY_I64, c_is_f64=true, c_f=5.0 - * → exercises lines 364-369 (isfinite+modf checks for I64 base) */ + * try_affine_sumavg_input: bt=RAY_I64, c_is_f64=true, c_f=5.0 → the + * scalar route takes it as an F64 bias (agg_affine_t.f64) */ ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); ray_op_t* c5 = ray_const_f64(g, 5.0); @@ -6726,8 +6729,9 @@ static test_result_t test_expr_group_affine_f64_i64(void) { ray_t* sum_col = ray_table_get_col_idx(result, 0); TEST_ASSERT_NOT_NULL(sum_col); - /* sum(a + 5) = (10+5) + (20+5) + (30+5) = 75 */ - TEST_ASSERT_EQ_I(((int64_t*)ray_data(sum_col))[0], 75); + /* sum(a + 5.0) = (10+5) + (20+5) + (30+5) = 75.0 */ + TEST_ASSERT_EQ_I(sum_col->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(sum_col))[0], 75.0, 0.0); ray_release(result); ray_graph_free(g); @@ -6737,6 +6741,144 @@ static test_result_t test_expr_group_affine_f64_i64(void) { PASS(); } +/* ---- a FLOAT constant over an integer column: SUM and AVG are F64 ---- + * + * try_affine_sumavg_input takes a FLOAT c over a narrow integer column only + * when its type-wide bound proves exact F64 arithmetic (f64_bias_ok: the + * scalar route). I64 and a large or fractional bias must be evaluated per + * row. The linear plan declines a FLOAT constant outright. The keyed group at the end is a + * control: that route already summed (a + 5.0) as F64, and still does. */ +static test_result_t test_expr_affine_f64_bias_route(void) { + ray_heap_init(); + (void)ray_sym_init(); + + int64_t a_raw[] = {10, 20, 30}; + int64_t k_raw[] = {0, 1, 0}; + ray_t* a_vec = ray_vec_from_raw(RAY_I64, a_raw, 3); + ray_t* k_vec = ray_vec_from_raw(RAY_I64, k_raw, 3); + ray_t* ts_vec = ray_vec_from_raw(RAY_TIMESTAMP, a_raw, 3); + int16_t h_raw[] = {10, 20, 30}; + ray_t* h_vec = ray_vec_from_raw(RAY_I16, h_raw, 3); + ray_t* tbl = ray_table_new(4); + tbl = ray_table_add_col(tbl, ray_sym_intern("a", 1), a_vec); + tbl = ray_table_add_col(tbl, ray_sym_intern("k", 1), k_vec); + tbl = ray_table_add_col(tbl, ray_sym_intern("ts", 2), ts_vec); + tbl = ray_table_add_col(tbl, ray_sym_intern("h", 1), h_vec); + ray_release(a_vec); ray_release(k_vec); ray_release(ts_vec); ray_release(h_vec); + + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* add_f = ray_add(g, ray_scan(g, "a"), ray_const_f64(g, 5.0)); + ray_op_t* add_i = ray_add(g, ray_scan(g, "a"), ray_const_i64(g, 5)); + ray_op_t* add_h = ray_add(g, ray_scan(g, "h"), ray_const_f64(g, 5.0)); + ray_op_t* add_h_big = ray_add(g, ray_scan(g, "h"), + ray_const_f64(g, 9007199254740992.0)); + ray_op_t* add_h_fraction = ray_add(g, ray_scan(g, "h"), ray_const_f64(g, 0.5)); + ray_op_t* ts_f = ray_add(g, ray_scan(g, "ts"), ray_const_f64(g, 5.0)); + ray_op_t* mul_f = ray_mul(g, ray_scan(g, "a"), ray_const_f64(g, 2.0)); + ray_op_t* mul_i = ray_mul(g, ray_scan(g, "a"), ray_const_i64(g, 2)); + agg_affine_t aff; + agg_linear_t lin; + ray_t* vec = NULL; + ray_t* err = NULL; + + /* I64 values may round on conversion before the addition. */ + memset(&aff, 0, sizeof aff); + TEST_ASSERT_FALSE(try_affine_sumavg_input(g, tbl, add_f, false, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_FALSE(aff.enabled); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_FALSE(try_affine_sumavg_input(g, tbl, add_f, true, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_FALSE(aff.enabled); + /* Small whole-number biases on a narrow type have exact row and sum + * arithmetic; a fractional or very large bias does not. */ + TEST_ASSERT_TRUE(try_affine_sumavg_input(g, tbl, add_h, true, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(aff.enabled && aff.f64 && aff.bias_f64 == 5.0); + TEST_ASSERT_TRUE(vec && vec->type == RAY_I16); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_FALSE(try_affine_sumavg_input(g, tbl, add_h_big, true, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + memset(&aff, 0, sizeof aff); + TEST_ASSERT_FALSE(try_affine_sumavg_input(g, tbl, add_h_fraction, true, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + /* (ts + 5.0) is no F64 sum at all: declined either way */ + memset(&aff, 0, sizeof aff); + TEST_ASSERT_FALSE(try_affine_sumavg_input(g, tbl, ts_f, true, &vec, &aff, &err)); + TEST_ASSERT_NULL(err); + /* control: (a + 5) is an integer bias on every route */ + memset(&aff, 0, sizeof aff); + TEST_ASSERT_TRUE(try_affine_sumavg_input(g, tbl, add_i, false, &vec, &aff, &err)); + TEST_ASSERT_TRUE(aff.enabled && !aff.f64 && aff.bias_i64 == 5); + /* linear: (a * 2.0) declines, (a * 2) is planned (control) */ + TEST_ASSERT_FALSE(try_linear_sumavg_input_i64(g, tbl, mul_f, &lin, &err)); + TEST_ASSERT_NULL(err); + TEST_ASSERT_TRUE(try_linear_sumavg_input_i64(g, tbl, mul_i, &lin, &err)); + TEST_ASSERT_TRUE(lin.enabled && lin.n_terms == 1 && lin.coeff_i64[0] == 2); + ray_graph_free(g); + + /* control: keyed SUM(a + 5.0) and AVG(a + 5.0) by k stay F64 */ + g = ray_graph_new(tbl); + ray_op_t* key_arr[] = { ray_scan(g, "k") }; + uint16_t ops[] = { OP_SUM, OP_AVG }; + ray_op_t* ins[] = { ray_add(g, ray_scan(g, "a"), ray_const_f64(g, 5.0)), + ray_add(g, ray_scan(g, "a"), ray_const_f64(g, 5.0)) }; + ray_op_t* grp = ray_group(g, key_arr, 1, ops, ins, 2); + ray_t* result = ray_execute(g, grp); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + ray_t* kc = ray_table_get_col_idx(result, 0); + ray_t* sc = ray_table_get_col_idx(result, 1); + ray_t* ac = ray_table_get_col_idx(result, 2); + TEST_ASSERT_TRUE(kc && sc && ac); + TEST_ASSERT_EQ_I(sc->type, RAY_F64); + TEST_ASSERT_EQ_I(ac->type, RAY_F64); + for (int64_t i = 0; i < kc->len; i++) { + int64_t key = ((int64_t*)ray_data(kc))[i]; + /* k=0: (10+5) + (30+5) = 50.0, avg 25.0; k=1: 25.0, avg 25.0 */ + TEST_ASSERT_EQ_F(((double*)ray_data(sc))[i], key == 0 ? 50.0 : 25.0, 0.0); + TEST_ASSERT_EQ_F(((double*)ray_data(ac))[i], 25.0, 0.0); + } + ray_release(result); + ray_graph_free(g); + + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* A failed scalar buffer allocation must not fall through to the hash + * emitter, which cannot apply the F64 affine bias. */ +static test_result_t test_expr_affine_f64_bias_scalar_oom(void) { + ray_heap_init(); + (void)ray_sym_init(); + int16_t raw[] = {10, 20, 30}; + ray_t* vec = ray_vec_from_raw(RAY_I16, raw, 3); + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, ray_sym_intern("h", 1), vec); + ray_release(vec); + + for (int i = 0; i < 2; i++) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* input = ray_add(g, ray_scan(g, "h"), ray_const_f64(g, 5.0)); + uint16_t op[] = {i == 0 ? OP_SUM : OP_AVG}; + ray_op_t* ins[] = {input}; + ray_op_t* group = ray_group(g, NULL, 0, op, ins, 1); + ray_group_test_route(1); + ray_group_test_fail_scalar_alloc(1); + ray_t* result = ray_execute(g, group); + ray_group_test_fail_scalar_alloc(0); + ray_group_test_route(0); + TEST_ASSERT_TRUE(result && RAY_IS_ERR(result)); + ray_error_free(result); + ray_graph_free(g); + } + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* ---- linear_expr_add_term: update existing term (lines 183-185) ---- */ static test_result_t test_expr_group_linear_double_term(void) { ray_heap_init(); @@ -6859,7 +7001,9 @@ static test_result_t test_expr_group_nonlinear_fallback(void) { PASS(); } -/* ---- eval_const_numeric_expr: F64 SUB/MUL/MIN2/MAX2, I64 SUB/DIV/MOD/MIN2/MAX2 ---- */ +/* ---- eval_const_numeric_expr: F64 SUB/MUL/MIN2/MAX2, I64 SUB/DIV/MOD/MIN2/MAX2 ---- + * A FLOAT constant (and `/`, which is F64 even over integers) makes the sum + * F64; an integer one keeps it I64. */ static test_result_t test_expr_group_affine_const_ops(void) { ray_heap_init(); (void)ray_sym_init(); @@ -6871,7 +7015,7 @@ static test_result_t test_expr_group_affine_const_ops(void) { tbl = ray_table_add_col(tbl, na, v); ray_release(v); - /* F64 SUB: a + (const_f64(10) - const_f64(3)) → bias=7 */ + /* F64 SUB: a + (const_f64(10) - const_f64(3)) → bias=7.0 */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -6883,11 +7027,12 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 107); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 107.0, 0.0); ray_release(result); ray_graph_free(g); } - /* F64 MUL: a + (const_f64(3) * const_f64(4)) → bias=12 */ + /* F64 MUL: a + (const_f64(3) * const_f64(4)) → bias=12.0 */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -6899,7 +7044,8 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 112); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 112.0, 0.0); ray_release(result); ray_graph_free(g); } @@ -6919,7 +7065,7 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_release(result); ray_graph_free(g); } - /* I64 DIV: a + (const_i64(10) / const_i64(2)) → bias=5 */ + /* I64 DIV: a + (const_i64(10) / const_i64(2)) → bias=5.0 */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -6931,7 +7077,8 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 105); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 105.0, 0.0); ray_release(result); ray_graph_free(g); } @@ -6983,7 +7130,7 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_release(result); ray_graph_free(g); } - /* F64 MOD: a + (const_f64(10) % const_f64(3)) → bias=1 (line 118) */ + /* F64 MOD: a + (const_f64(10) % const_f64(3)) → bias=1.0 (line 118) */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -6995,11 +7142,12 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 101); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 101.0, 0.0); ray_release(result); ray_graph_free(g); } - /* F64 MIN2: a + min2(const_f64(3), const_f64(7)) → bias=3 (line 119) */ + /* F64 MIN2: a + min2(const_f64(3), const_f64(7)) → bias=3.0 (line 119) */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -7011,11 +7159,12 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 103); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 103.0, 0.0); ray_release(result); ray_graph_free(g); } - /* F64 MAX2: a + max2(const_f64(3), const_f64(7)) → bias=7 (line 120) */ + /* F64 MAX2: a + max2(const_f64(3), const_f64(7)) → bias=7.0 (line 120) */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -7027,11 +7176,12 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 107); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 107.0, 0.0); ray_release(result); ray_graph_free(g); } - /* I64 DIV: a + (const_i64(9) / const_i64(3)) → bias=3 (lines 134-137) */ + /* I64 DIV: a + (const_i64(9) / const_i64(3)) → bias=3.0 (lines 134-137) */ { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a_op = ray_scan(g, "a"); @@ -7043,7 +7193,8 @@ static test_result_t test_expr_group_affine_const_ops(void) { ray_op_t* grp = ray_group(g, NULL, 0, ops, ins, 1); ray_t* result = ray_execute(g, grp); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(result, 0)))[0], 103); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_F64); + TEST_ASSERT_EQ_F(((double*)ray_data(ray_table_get_col_idx(result, 0)))[0], 103.0, 0.0); ray_release(result); ray_graph_free(g); } @@ -8760,11 +8911,10 @@ static test_result_t test_exec_streaming_mapcommon_too_short(void) { PASS(); } -/* ---- streaming: parted segment is NULL — build_segment_table !segs[seg_idx] - * path (exec.c L1904: seg_idx >= col->len || !segs[seg_idx]). - * - * A parted column with a NULL segment pointer at index 1 triggers the - * NULL-segment guard in build_segment_table. */ +/* ---- streaming: parted segment is NULL (a partition without the column, + * ragged parted table). build_segment_table gives that partition's rows, + * from the partition-key counts, as typed nulls; the scan over the two + * segments is the flat column with nulls in the second partition's rows. */ static test_result_t test_exec_streaming_parted_null_segment(void) { ray_heap_init(); (void)ray_sym_init(); @@ -8783,7 +8933,7 @@ static test_result_t test_exec_streaming_parted_null_segment(void) { /* Valid MAPCOMMON with 2 keys */ int64_t kv_data[] = {10, 20}; - int64_t rc_data[] = {2, 0}; + int64_t rc_data[] = {2, 3}; ray_t* kv = ray_vec_from_raw(RAY_I64, kv_data, 2); ray_t* rc = ray_vec_from_raw(RAY_I64, rc_data, 2); ray_t* mc = exec_make_mapcommon(kv, rc); @@ -8798,13 +8948,19 @@ static test_result_t test_exec_streaming_parted_null_segment(void) { ray_graph_t* g = ray_graph_new(tbl); ray_op_t* scan_v = ray_scan(g, "v"); - /* Segment 0: seg_rows from pcol[0]->len=2; MAPCOMMON broadcast OK. - * Then pcol[0] itself: seg_idx=0 < col->len=2 and segs[0] non-NULL. - * Segment 1: MAPCOMMON kv has key for idx=1 (OK), pcol[1] is NULL - * → build_segment_table L1904: !segs[seg_idx] → schema error. */ + /* Segment 0: pcol[0], two rows. Segment 1: pcol[1] is NULL and the + * partition counts 3 rows, so the segment table carries three I64 + * nulls for v; the scan concatenates to five rows. */ ray_t* result = ray_execute(g, scan_v); TEST_ASSERT_NOT_NULL(result); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(result->type, RAY_I64); + TEST_ASSERT_EQ_I(result->len, 5); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(result))[0], 1); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(result))[1], 2); + TEST_ASSERT_TRUE(ray_vec_is_null(result, 2)); + TEST_ASSERT_TRUE(ray_vec_is_null(result, 4)); + ray_release(result); ray_graph_free(g); ray_release(tbl); @@ -9000,6 +9156,280 @@ static test_result_t test_exec_head_filter_pred_error(void) { PASS(); } +/* Where make_chain_table sets flag: on the first and last 100 rows, on + * every even row, or on the first 100 rows only. */ +typedef enum { CHAIN_FLAG_EDGES, CHAIN_FLAG_EVEN, CHAIN_FLAG_HEAD } chain_flag_t; + +/* n rows: id = id_base + row, amount 1, flag where `where` says. */ +static ray_t* make_chain_table(int64_t n, int64_t id_base, chain_flag_t where) { + ray_t* id = ray_vec_new(RAY_I64, n); + ray_t* amount = ray_vec_new(RAY_I64, n); + ray_t* flag = ray_vec_new(RAY_I64, n); + id->len = amount->len = flag->len = n; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(id))[i] = id_base + i; + ((int64_t*)ray_data(amount))[i] = 1; + ((int64_t*)ray_data(flag))[i] = + where == CHAIN_FLAG_EVEN ? i % 2 == 0 + : where == CHAIN_FLAG_HEAD ? i < 100 + : (i < 100 || i >= n - 100); + } + ray_t* tbl = ray_table_new(3); + tbl = ray_table_add_col(tbl, ray_sym_intern("id", 2), id); + tbl = ray_table_add_col(tbl, ray_sym_intern("amount", 6), amount); + tbl = ray_table_add_col(tbl, ray_sym_intern("flag", 4), flag); + ray_release(id); + ray_release(amount); + ray_release(flag); + return tbl; +} + +/* HEAD(limit, FILTER(term, FILTER(flag == 1, CONST(input)))) over a graph + * whose default table is `deflt`. */ +static ray_t* exec_head_filter_chain(ray_t* deflt, ray_t* input, bool running, + int64_t bound, int64_t limit) { + ray_graph_t* g = ray_graph_new(deflt); + ray_op_t* inner = ray_filter(g, ray_const_table(g, input), + ray_eq(g, ray_scan(g, "flag"), ray_const_i64(g, 1))); + ray_op_t* term = running + ? ray_gt(g, ray_sums_op(g, ray_scan(g, "amount")), ray_const_i64(g, bound)) + : ray_gt(g, ray_scan(g, "id"), ray_const_i64(g, bound)); + ray_t* result = ray_execute(g, ray_head(g, ray_filter(g, inner, term), limit)); + ray_graph_free(g); + return result; +} + +/* HEAD over a filter chain: the outer term sees the inner filter's rows. + * Flag on the first and last 100 rows: a running outer term + * (sums(amount) > 150) keeps rows 151..200 of those 200, ids 5950..5999; + * a row-local one (id > 5920) keeps the first 50 past 5920, and a + * negative limit keeps none. Over tables A (the default) and B with + * flag on even rows and B's ids from 10000, a chain on B reads B's rows. */ +static test_result_t test_exec_head_filter_chain_domain(void) { + ray_heap_init(); + (void)ray_sym_init(); + + ray_t* tbl = make_chain_table(6000, 0, CHAIN_FLAG_EDGES); + for (int running = 1; running >= 0; running--) { + ray_t* result = exec_head_filter_chain(tbl, tbl, running, + running ? 150 : 5920, 50); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 50); + ray_t* ids = ray_table_get_col(result, ray_sym_intern("id", 2)); + int64_t first = running ? 5950 : 5921; + for (int64_t i = 0; i < 50; i++) + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ids))[i], first + i); + ray_release(result); + + result = exec_head_filter_chain(tbl, tbl, running, 0, -1); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(result->type, RAY_TABLE); + TEST_ASSERT_EQ_I(ray_table_ncols(result), 3); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 0); + ray_release(result); + } + + ray_t* deflt = make_chain_table(6000, 0, CHAIN_FLAG_EVEN); + ray_t* other = make_chain_table(6000, 10000, CHAIN_FLAG_EVEN); + ray_t* result = exec_head_filter_chain(deflt, other, false, 10000, 50); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 50); + ray_t* ids = ray_table_get_col(result, ray_sym_intern("id", 2)); + for (int64_t i = 0; i < 50; i++) + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ids))[i], 10002 + 2 * i); + ray_release(result); + + ray_release(other); + ray_release(deflt); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* SELECT over FILTER(flag == 1, CONST(input)) whose columns share one + * MUL(FILLS(amount), 2) node: the node itself first, then SUMS of it, then + * ADD(node, 0) — SUMS and ADD are its two DAG consumers, which arms the + * memo (the select's own column list is not counted). Under the filter's + * selection the parallel MUL skips every block without a kept row, so a + * memo of that value would hand SUMS unwritten rows; SUMS reads every row, + * so kept row i must be 2 * (i + 1), as a serial sum. */ +static test_result_t test_exec_memo_under_selection(void) { + ray_heap_init(); + (void)ray_sym_init(); + + enum { N = 2 * RAY_PARALLEL_THRESHOLD, EDGE = 100 }; + ray_t* tbl = make_chain_table(N, 0, CHAIN_FLAG_EDGES); + + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* kept = ray_filter(g, ray_const_table(g, tbl), + ray_eq(g, ray_scan(g, "flag"), ray_const_i64(g, 1))); + ray_op_t* twice = ray_mul(g, ray_fills_op(g, ray_scan(g, "amount")), + ray_const_i64(g, 2)); + ray_op_t* cols[] = { ray_scan(g, "id"), twice, ray_sums_op(g, twice), + ray_add(g, twice, ray_const_i64(g, 0)) }; + ray_t* result = ray_execute(g, ray_select_op(g, kept, cols, 4)); + ray_graph_free(g); + + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 2 * EDGE); + const int64_t* ids = (const int64_t*)ray_data(ray_table_get_col_idx(result, 0)); + const int64_t* sums = (const int64_t*)ray_data(ray_table_get_col_idx(result, 2)); + for (int64_t i = 0; i < 2 * EDGE; i++) + TEST_ASSERT_EQ_I(sums[i], 2 * (ids[i] + 1)); + + ray_release(result); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* SELECT over FILTER(flag == 1, CONST(input)) of one order op over + * MUL(FILLS(amount), id) = id, flag on the first EDGE rows only. Under the + * filter's selection the parallel MUL writes the first block alone; the + * order op reads every row, so kept row i is N-1-i under reverse and desc + * and i under asc. Rayfall projections reach these verbs through the + * eval fallback over the kept rows, so only a C-API graph gets here. */ +static test_result_t test_exec_order_ops_under_selection(void) { + ray_heap_init(); + (void)ray_sym_init(); + + enum { N = 2 * RAY_PARALLEL_THRESHOLD, EDGE = 100 }; + ray_t* tbl = make_chain_table(N, 0, CHAIN_FLAG_HEAD); + + struct { ray_op_t* (*op)(ray_graph_t*, ray_op_t*); bool ascending; } order_ops[] = + { { ray_reverse_op, false }, { ray_asc_op, true }, { ray_desc_op, false } }; + for (int k = 0; k < 3; k++) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* kept = ray_filter(g, ray_const_table(g, tbl), + ray_eq(g, ray_scan(g, "flag"), ray_const_i64(g, 1))); + ray_op_t* ids = ray_mul(g, ray_fills_op(g, ray_scan(g, "amount")), + ray_scan(g, "id")); + ray_op_t* cols[] = { order_ops[k].op(g, ids) }; + ray_t* result = ray_execute(g, ray_select_op(g, kept, cols, 1)); + ray_graph_free(g); + + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), EDGE); + const int64_t* got = (const int64_t*)ray_data(ray_table_get_col_idx(result, 0)); + for (int64_t i = 0; i < EDGE; i++) + TEST_ASSERT_EQ_I(got[i], order_ops[k].ascending ? i : N - 1 - i); + ray_release(result); + } + + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* flag 1 0 1 0, score 60 20 45 35: the whole table's avg score is 40, + * the flag == 1 rows' 52.5. */ +static ray_t* make_room_table(void) { + const int64_t flags[] = { 1, 0, 1, 0 }, scores[] = { 60, 20, 45, 35 }; + ray_t* flag = ray_vec_new(RAY_I64, 4); + ray_t* score = ray_vec_new(RAY_I64, 4); + flag->len = score->len = 4; + memcpy(ray_data(flag), flags, sizeof flags); + memcpy(ray_data(score), scores, sizeof scores); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("flag", 4), flag); + tbl = ray_table_add_col(tbl, ray_sym_intern("score", 5), score); + ray_release(flag); + ray_release(score); + return tbl; +} + +/* SELECT over FILTER(flag == 1, CONST(input)) whose columns share one + * x = SUB(score, AVG(score)), SUMS(x) and SUM(x) in either order. SUMS + * reads x over the whole table (20 -20 5 -5, running 20 0 5 0, kept 20 5); + * SUM reads it over the kept rows (7.5 -7.5, sum 0). Neither may be + * handed the other's x. */ +static test_result_t test_exec_memo_across_row_domains(void) { + ray_heap_init(); + (void)ray_sym_init(); + + ray_t* tbl = make_room_table(); + for (int sums_first = 1; sums_first >= 0; sums_first--) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* kept = ray_filter(g, ray_const_table(g, tbl), + ray_eq(g, ray_scan(g, "flag"), ray_const_i64(g, 1))); + ray_op_t* x = ray_sub(g, ray_scan(g, "score"), ray_avg(g, ray_scan(g, "score"))); + ray_op_t* running = ray_sums_op(g, x); + ray_op_t* total = ray_sum(g, x); + ray_op_t* cols[] = { sums_first ? running : total, sums_first ? total : running }; + ray_t* result = ray_execute(g, ray_select_op(g, kept, cols, 2)); + ray_graph_free(g); + + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 2); + const double* sums = (const double*)ray_data(ray_table_get_col_idx(result, !sums_first)); + const double* sum = (const double*)ray_data(ray_table_get_col_idx(result, sums_first)); + TEST_ASSERT_EQ_F(sums[0], 20.0, 1e-9); + TEST_ASSERT_EQ_F(sums[1], 5.0, 1e-9); + TEST_ASSERT_EQ_F(sum[0], 0.0, 1e-9); + TEST_ASSERT_EQ_F(sum[1], 0.0, 1e-9); + ray_release(result); + } + + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* SUMS over a FILTER, which installs a selection and returns a table: + * rejected, with and without an outer FILTER's selection installed. The + * selection the inner FILTER installs is released either way: after a + * warm-up, repeated calls leave the heap as they found it. */ +static test_result_t test_exec_all_rows_child_selection(void) { + ray_heap_init(); + (void)ray_sym_init(); + + ray_t* tbl = make_room_table(); + for (int outer = 0; outer <= 1; outer++) { + size_t before = 0; + for (int call = 0; call < 110; call++) { + if (call == 10) { + ray_mem_stats_t st; + ray_mem_stats(&st); + before = st.bytes_allocated; + } + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* inner = ray_filter(g, ray_const_table(g, tbl), + ray_eq(g, ray_scan(g, "flag"), ray_const_i64(g, 1))); + ray_op_t* root = ray_sums_op(g, inner); + if (outer) { + ray_op_t* kept = ray_filter(g, ray_const_table(g, tbl), + ray_eq(g, ray_scan(g, "flag"), ray_const_i64(g, 1))); + ray_op_t* cols[] = { root }; + root = ray_select_op(g, kept, cols, 1); + } + ray_t* result = ray_execute(g, root); + ray_graph_free(g); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_TRUE(RAY_IS_ERR(result)); + ray_error_free(result); + } + ray_mem_stats_t st; + ray_mem_stats(&st); + TEST_ASSERT_FMT(st.bytes_allocated == before, "outer %d: %zu bytes allocated, %zu before", + outer, st.bytes_allocated, before); + } + + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* ---- OP_SELECT with failing expression column — exec.c L1613-1617. * * When a SELECT projection expression evaluates to an error, the SELECT @@ -10145,20 +10575,15 @@ static test_result_t test_expr_f64_to_narrow_cast(void) { ray_release(result); ray_graph_free(g); - /* (as 'BOOL v) on nullable F64 col — F64→BOOL CAST with NaN-handling. - * Regression for prior bug where NaN (= NULL_F64 sentinel) was treated - * as truthy because IEEE `NaN != 0.0` is true. Fixed by adding an - * explicit NaN check (`src[i] == src[i]`). - * Raw data: [1.7, 2.3, 0.0, 4.9, 0.5] but row 2 was overwritten with - * NULL_F64 sentinel via ray_vec_set_null(v, 2, true). So the seen - * input is [1.7, 2.3, NaN(null), 4.9, 0.5] → [1, 1, 0, 1, 1] → sum 4. */ + /* F64→BOOL: only zero is false, so the NaN null sentinel is true. + * Input [1.7, 2.3, NaN, 4.9, 0.5] yields five true values. */ g = ray_graph_new(tbl); col = ray_scan(g, "v"); ray_op_t* cbool = ray_cast(g, col, RAY_BOOL); s = ray_sum(g, cbool); result = ray_execute(g, s); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 4); + TEST_ASSERT_EQ_I(result->i64, 5); ray_release(result); ray_graph_free(g); @@ -11953,8 +12378,8 @@ static test_result_t test_expr_unary_i64_to_bool_cast(void) { ray_op_t* s = ray_sum(g, ca); ray_t* result = ray_execute(g, s); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - /* cast(0)=false=0, cast(5)=true=1, cast(-3)=true=1, pos3=null=0 → sum=2 */ - TEST_ASSERT_EQ_I(result->i64, 2); + /* Only zero is false; the non-zero null sentinel also casts to true. */ + TEST_ASSERT_EQ_I(result->i64, 3); ray_release(result); ray_graph_free(g); @@ -11964,6 +12389,45 @@ static test_result_t test_expr_unary_i64_to_bool_cast(void) { PASS(); } +/* Call the typed fallback directly so expression fusion cannot mask a + * regression in its null-to-BOOL or post-cast null propagation rules. */ +static test_result_t test_expr_typed_null_to_bool_cast(void) { + ray_heap_init(); + (void)ray_sym_init(); + + const int16_t h[] = {NULL_I16, 0, -1}; + const int32_t i[] = {NULL_I32, 0, -1}; + const int64_t l[] = {NULL_I64, 0, -1}; + const float e[] = {NULL_F32, 0.0f, -1.0f}; + const double f[] = {NULL_F64, 0.0, -1.0}; + const int8_t types[] = {RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64}; + const void* values[] = {h, i, l, e, f}; + ray_op_t op = {.opcode = OP_CAST, .out_type = RAY_BOOL}; + + for (size_t k = 0; k < sizeof(types) / sizeof(types[0]); k++) { + ray_t* input = ray_vec_from_raw(types[k], values[k], 3); + TEST_ASSERT_FALSE(RAY_IS_ERR(input)); + ray_vec_set_null(input, 0, true); + ray_t* result = exec_elementwise_unary(NULL, &op, input); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(result->type, RAY_BOOL); + TEST_ASSERT_EQ_I(result->len, 3); + const uint8_t* data = (const uint8_t*)ray_data(result); + TEST_ASSERT_EQ_I(data[0], 1); + TEST_ASSERT_EQ_I(data[1], 0); + TEST_ASSERT_EQ_I(data[2], 1); + TEST_ASSERT_FALSE(ray_vec_may_have_nulls(result)); + for (int64_t row = 0; row < 3; row++) + TEST_ASSERT_FALSE(ray_vec_is_null(result, row)); + ray_release(result); + ray_release(input); + } + + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* ---- exec_elementwise_binary: F64 AND/OR float-family path (lines 1906-1907) ---- * Nullable F64 col AND nullable F64 col → non-fused → binary_range float path */ static test_result_t test_expr_binary_f64_and_or(void) { @@ -14178,17 +14642,14 @@ static test_result_t test_expr_binary_sym_w32_arith(void) { ray_release(result); ray_graph_free(g); - /* BOOL comparison: sw == 2 → lp_u32 in BOOL slow path (integer src_is_i64_all) - * Also covers lp_u32 in BOOL block src_is_i64_all EQ loop */ + /* Mixed SYM/I64 equality must decline, not compare raw IDs. Do not + * pass a declined node into ray_sum (#768). Arithmetic above is unchanged. */ g = ray_graph_new(tbl); col = ray_scan(g, "sw"); c = ray_const_i64(g, 2); op = ray_eq(g, col, c); - s = ray_sum(g, op); - result = ray_execute(g, s); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 1); /* only position 1 (val=2) matches */ - ray_release(result); + TEST_ASSERT(op == NULL, "symbol/numeric equality declines"); + TEST_ASSERT(g->compile_err == NULL, "decline leaves evaluator fallback available"); ray_graph_free(g); ray_release(tbl); @@ -14257,16 +14718,13 @@ static test_result_t test_expr_binary_sym_w32_rhs(void) { ray_release(result); ray_graph_free(g); - /* BOOL: 2 == sw2 → rp_u32 in BOOL src_is_i64_all EQ loop */ + /* Reversed numeric/SYM equality has the same constructor contract. */ g = ray_graph_new(tbl); a = ray_const_i64(g, 2); col = ray_scan(g, "sw2"); op = ray_eq(g, a, col); - s = ray_sum(g, op); - result = ray_execute(g, s); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 1); /* only val=2 matches */ - ray_release(result); + TEST_ASSERT(op == NULL, "numeric/symbol equality declines"); + TEST_ASSERT(g->compile_err == NULL, "decline leaves evaluator fallback available"); ray_graph_free(g); /* SYM W32 vec-vs-vec: two W32 cols → lp_u32 + rp_u32 simultaneously */ @@ -15278,23 +15736,21 @@ static test_result_t test_expr_binary_bool_float_path_lhs(void) { TEST_ASSERT_EQ_I(result->i64, 1); ray_release(result); ray_graph_free(g); - /* EQ: 2==1→F, 3==3→T, 4==5→F, 3==3→T → sum=2 */ + /* EQ/NE no longer admit raw ID versus F64 comparisons (#768). */ g = ray_graph_new(tbl); a = ray_scan(g, "bfp_lw32"); b = ray_scan(g, "bfp_rf64"); - op = ray_eq(g, a, b); s = ray_sum(g, op); - result = ray_execute(g, s); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 2); - ray_release(result); ray_graph_free(g); + op = ray_eq(g, a, b); + TEST_ASSERT(op == NULL, "SYM/F64 equality declines"); + TEST_ASSERT(g->compile_err == NULL, "decline is not a language error"); + ray_graph_free(g); /* NE */ g = ray_graph_new(tbl); a = ray_scan(g, "bfp_lw32"); b = ray_scan(g, "bfp_rf64"); - op = ray_ne(g, a, b); s = ray_sum(g, op); - result = ray_execute(g, s); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 2); - ray_release(result); ray_graph_free(g); + op = ray_ne(g, a, b); + TEST_ASSERT(op == NULL, "SYM/F64 equality declines"); + TEST_ASSERT(g->compile_err == NULL, "decline is not a language error"); + ray_graph_free(g); /* LE: 2<=1→F, 3<=3→T, 4<=5→T, 3<=3→T → sum=3 */ g = ray_graph_new(tbl); @@ -15514,31 +15970,29 @@ static test_result_t test_expr_binary_bool_int_w32_lhs(void) { ray_t* tbl = make_two_col_table(na, vs, nb, vb); ray_release(vs); ray_release(vb); - /* EQ: 1==2→F, 3==3→T, 5==4→F, 3==3→T → sum=2 */ + /* EQ/NE decline incompatible logical types, rather than compare IDs. */ ray_graph_t* g = ray_graph_new(tbl); ray_op_t* a = ray_scan(g, "bip_lw32"); ray_op_t* b = ray_scan(g, "bip_ri64"); ray_op_t* op = ray_eq(g, a, b); - ray_op_t* s = ray_sum(g, op); - ray_t* result = ray_execute(g, s); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 2); - ray_release(result); ray_graph_free(g); + TEST_ASSERT(op == NULL, "SYM/I64 equality declines"); + TEST_ASSERT(g->compile_err == NULL, "decline is not a language error"); + ray_graph_free(g); - /* NE: 1!=2→T, 3!=3→F, 5!=4→T, 3!=3→F → sum=2 */ + /* NE has the same incompatible-type decline. */ g = ray_graph_new(tbl); a = ray_scan(g, "bip_lw32"); b = ray_scan(g, "bip_ri64"); - op = ray_ne(g, a, b); s = ray_sum(g, op); - result = ray_execute(g, s); - TEST_ASSERT_FALSE(RAY_IS_ERR(result)); - TEST_ASSERT_EQ_I(result->i64, 2); - ray_release(result); ray_graph_free(g); + op = ray_ne(g, a, b); + TEST_ASSERT(op == NULL, "SYM/I64 inequality declines"); + TEST_ASSERT(g->compile_err == NULL, "decline is not a language error"); + ray_graph_free(g); /* LT: 1<2→T, 3<3→F, 5<4→F, 3<3→F → sum=1 */ g = ray_graph_new(tbl); a = ray_scan(g, "bip_lw32"); b = ray_scan(g, "bip_ri64"); - op = ray_lt(g, a, b); s = ray_sum(g, op); - result = ray_execute(g, s); + op = ray_lt(g, a, b); + ray_op_t* s = ray_sum(g, op); + ray_t* result = ray_execute(g, s); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); TEST_ASSERT_EQ_I(result->i64, 1); ray_release(result); ray_graph_free(g); @@ -17698,6 +18152,8 @@ const test_entry_t exec_entries[] = { { "exec/expr_group_linear_cancel", test_expr_group_linear_cancel, NULL, NULL }, { "exec/expr_group_nonlinear_fallback", test_expr_group_nonlinear_fallback, NULL, NULL }, { "exec/expr_group_affine_f64_i64", test_expr_group_affine_f64_i64, NULL, NULL }, + { "exec/expr_affine_f64_bias_route", test_expr_affine_f64_bias_route, NULL, NULL }, + { "exec/expr_affine_f64_bias_scalar_oom", test_expr_affine_f64_bias_scalar_oom, NULL, NULL }, { "exec/expr_group_linear_double_term", test_expr_group_linear_double_term, NULL, NULL }, { "exec/expr_group_linear_mid_cancel", test_expr_group_linear_mid_cancel, NULL, NULL }, { "exec/expr_group_affine_neg_i64_const", test_expr_group_affine_neg_i64_const, NULL, NULL }, @@ -17739,6 +18195,11 @@ const test_entry_t exec_entries[] = { { "exec/filter_group_pred_error", test_exec_filter_group_pred_error, NULL, NULL }, { "exec/head_filter_input_error", test_exec_head_filter_input_error, NULL, NULL }, { "exec/head_filter_pred_error", test_exec_head_filter_pred_error, NULL, NULL }, + { "exec/head_filter_chain_domain", test_exec_head_filter_chain_domain, NULL, NULL }, + { "exec/memo_under_selection", test_exec_memo_under_selection, NULL, NULL }, + { "exec/order_ops_under_selection", test_exec_order_ops_under_selection, NULL, NULL }, + { "exec/memo_across_row_domains", test_exec_memo_across_row_domains, NULL, NULL }, + { "exec/all_rows_child_selection", test_exec_all_rows_child_selection, NULL, NULL }, { "exec/select_expr_col_error", test_exec_select_expr_col_error, NULL, NULL }, { "exec/streaming_large_dag", test_exec_streaming_large_dag, NULL, NULL }, { "exec/deep_binary_chain", test_exec_deep_binary_chain, NULL, NULL }, @@ -17788,6 +18249,7 @@ const test_entry_t exec_entries[] = { { "exec/expr_set_all_null_f32", test_expr_set_all_null_f32, NULL, NULL }, { "exec/expr_unary_f64_cast_default", test_expr_unary_f64_cast_default, NULL, NULL }, { "exec/expr_unary_i64_to_f64_cast", test_expr_unary_i64_to_f64_cast, NULL, NULL }, + { "exec/expr_typed_null_to_bool_cast", test_expr_typed_null_to_bool_cast, NULL, NULL }, { "exec/expr_unary_i64_to_bool_cast", test_expr_unary_i64_to_bool_cast, NULL, NULL }, { "exec/expr_binary_f64_and_or", test_expr_binary_f64_and_or, NULL, NULL }, { "exec/expr_sym_w32_fast_eq_ne", test_expr_sym_w32_fast_eq_ne, NULL, NULL }, diff --git a/test/test_expr_null.c b/test/test_expr_null.c index a7f3911b4..be350bbe4 100644 --- a/test/test_expr_null.c +++ b/test/test_expr_null.c @@ -196,7 +196,7 @@ static test_result_t test_nullfree_stream_unchanged(void) { ray_const_i64(g, 1)), ray_const_i64(g, 2)); ray_expr_t ex; - TEST_ASSERT(expr_compile(g, tbl, e, &ex), "null-free compiles"); + TEST_ASSERT(expr_compile(g, tbl, e, &ex, &(ray_t*){NULL}), "null-free compiles"); for (uint8_t i = 0; i < ex.n_ins; i++) TEST_ASSERT(ex.ins[i].null_aware == 0, "no null_aware on null-free"); for (uint8_t r2 = 0; r2 < ex.n_regs; r2++) @@ -323,7 +323,7 @@ static test_result_t test_nullfree_promotion_invariance(void) { ray_graph_t* g = ray_graph_new(tbl); ray_expr_t ex; - TEST_ASSERT(expr_compile(g, tbl, build_i64_plus_f64(g), &ex), + TEST_ASSERT(expr_compile(g, tbl, build_i64_plus_f64(g), &ex, &(ray_t*){NULL}), "null-free promotion compiles"); /* No INPUT is nullable, so the compiler marks no instruction null_aware * and no reg null_src (column-derived nullability). Single-null float @@ -917,7 +917,7 @@ static test_result_t test_scalar_broadcast_col_bails(void) { uint64_t bail_other_before = ray_expr_bail_counts[EXPR_BAIL_OTHER]; ray_expr_t ex; - bool compiled = expr_compile(gc, tbl, add, &ex); + bool compiled = expr_compile(gc, tbl, add, &ex, &(ray_t*){NULL}); TEST_ASSERT_FALSE(compiled); TEST_ASSERT_FMT(ray_expr_bail_counts[EXPR_BAIL_OTHER] > bail_other_before, "EXPR_BAIL_OTHER must increment (was %llu, now %llu)", @@ -1111,7 +1111,7 @@ static test_result_t test_fused_agg_input_allnull_group(void) { ray_op_t* mulA = ray_mul(gA, xA, ray_const_i64(gA, 2)); ray_expr_t exA; - bool compiled = expr_compile(gA, tbl, mulA, &exA); + bool compiled = expr_compile(gA, tbl, mulA, &exA, &(ray_t*){NULL}); TEST_ASSERT(compiled, "Part A: x*2 expr_compile must succeed for nullable i64"); TEST_ASSERT(ray_expr_compile_ok > ok_before, "Part A: compile_ok must increment"); @@ -1304,7 +1304,7 @@ static test_result_t test_diff_parted_nullable(void) { ray_graph_t* gc = ray_graph_new(tbl); ray_op_t* root_b = build_add_const(gc); ray_expr_t ex; - bool ok = expr_compile(gc, tbl, root_b, &ex); + bool ok = expr_compile(gc, tbl, root_b, &ex, &(ray_t*){NULL}); TEST_ASSERT(ok, "expr_compile on parted tbl succeeds"); TEST_ASSERT(ex.has_parted, "has_parted set"); TEST_ASSERT(ex.regs[ex.out_reg].nullable, @@ -1617,7 +1617,7 @@ static test_result_t test_zone_skip_keeps_nulls_fused_pred(void) { zn_op = ops[k]; ray_graph_t* g = ray_graph_new(tbl); fp_pred_t fp; - TEST_ASSERT(fp_compile_pred(g, b_zone_cmp(g), tbl, &fp) == 0, "fp compiles"); + TEST_ASSERT(fp_compile_pred(g, b_zone_cmp(g), tbl, &fp, &(ray_t*){NULL}) == 0, "fp compiles"); for (int64_t ms = 0; ms < ZN_ROWS; ms += 1024) fp_eval_pred(&fp, ms, ms + 1024, bits + ms); for (int64_t i = 0; i < ZN_ROWS; i++) @@ -1841,6 +1841,104 @@ static test_result_t test_sym_ordered_sparse_no_intern(void) { PASS(); } +/* ---- Zero divisor over null-free inputs ---------------------------------- + * A null-free program compiles every instruction with null_aware = 0; the + * plain I64 DIV / IDIV / MOD kernels used to write 0 for a zero divisor + * where the builtin and the fallback give 0Nl, and the output scan then + * found no sentinel. Pin the fused result against the fallback and + * against the expected null rows, and require HAS_NULLS on the output. + * Divisor columns of every integer width plus BOOL (the fallback's + * zero-divisor pass covered I64 / I32 only) and a constant zero. */ +static ray_t* make_zero_div_table(int8_t yt) { + int64_t xv[] = {7, -7, 5, 9, -3, 1, 4, 8}; + int64_t yv[] = {3, 0, -2, 0, 5, 1, 0, 2}; /* zero at rows 1, 3, 6 */ + ray_t* xcol = ray_vec_from_raw(RAY_I64, xv, 8); + ray_t* ycol; + if (yt == RAY_I64) { + ycol = ray_vec_from_raw(RAY_I64, yv, 8); + } else if (yt == RAY_I32) { + int32_t v[8]; for (int i = 0; i < 8; i++) v[i] = (int32_t)yv[i]; + ycol = ray_vec_from_raw(RAY_I32, v, 8); + } else if (yt == RAY_I16) { + int16_t v[8]; for (int i = 0; i < 8; i++) v[i] = (int16_t)yv[i]; + ycol = ray_vec_from_raw(RAY_I16, v, 8); + } else { + uint8_t v[8]; for (int i = 0; i < 8; i++) v[i] = yv[i] != 0; + ycol = ray_vec_from_raw(RAY_BOOL, v, 8); + } + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("x", 1), xcol); + tbl = ray_table_add_col(tbl, ray_sym_intern("y", 1), ycol); + ray_release(xcol); ray_release(ycol); + return tbl; +} + +static ray_op_t* build_zd_idiv(ray_graph_t* g) { return ray_idiv(g, ray_scan(g, "x"), ray_scan(g, "y")); } +static ray_op_t* build_zd_mod(ray_graph_t* g) { return ray_mod(g, ray_scan(g, "x"), ray_scan(g, "y")); } +static ray_op_t* build_zd_div(ray_graph_t* g) { return ray_div(g, ray_scan(g, "x"), ray_scan(g, "y")); } +static ray_op_t* build_zd_idiv0(ray_graph_t* g) { return ray_idiv(g, ray_scan(g, "x"), ray_const_i64(g, 0)); } +static ray_op_t* build_zd_mod0(ray_graph_t* g) { return ray_mod(g, ray_scan(g, "x"), ray_const_i64(g, 0)); } +/* the sentinel survives a downstream (null-aware) kernel */ +static ray_op_t* build_zd_mod_add(ray_graph_t* g) { + return ray_add(g, ray_mod(g, ray_scan(g, "x"), ray_scan(g, "y")), ray_const_i64(g, 1)); +} + +static test_result_t test_u8_mod_composition_fuses(void) { + ray_heap_init(); (void)ray_sym_init(); + int64_t xv[] = {7, -7, 5, 9, -3, 1, 4, 8}; + uint8_t yv[] = {3, 0, 2, 0, 5, 1, 0, 2}; + ray_t* xcol = ray_vec_from_raw(RAY_I64, xv, 8); + ray_t* ycol = ray_vec_from_raw(RAY_U8, yv, 8); + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("x", 1), xcol); + tbl = ray_table_add_col(tbl, ray_sym_intern("y", 1), ycol); + ray_release(xcol); ray_release(ycol); + test_result_t r = diff_run(tbl, build_zd_mod_add, true); + ray_release(tbl); ray_sym_destroy(); ray_heap_destroy(); + return r; +} + +/* Fused result: nulls exactly at the rows in want[], HAS_NULLS set, and + * equal to the forced fallback. fused: the program must compile (an I64 + * divisor does; a narrower one may take the typed executor, whose + * zero-divisor pass is then the one under test). */ +static test_result_t zd_check(ray_t* tbl, expr_builder_t b, const bool want[8], bool fused) { + test_result_t r = diff_run(tbl, b, fused); + if (r.status != TEST_PASS) return r; + ray_graph_t* g = ray_graph_new(tbl); + ray_t* v = ray_execute(g, b(g)); + TEST_ASSERT(v && !RAY_IS_ERR(v) && v->len == 8, "fused result"); + TEST_ASSERT(v->attrs & RAY_ATTR_HAS_NULLS, "HAS_NULLS on a zero-divisor result"); + for (int64_t i = 0; i < 8; i++) + TEST_ASSERT_FMT(ray_vec_is_null(v, i) == want[i], "null at row %lld: got %d want %d", + (long long)i, ray_vec_is_null(v, i), want[i]); + ray_release(v); ray_graph_free(g); + PASS(); +} + +static test_result_t test_zero_divisor_nullfree(void) { + ray_heap_init(); (void)ray_sym_init(); + const bool zero_rows[8] = {false, true, false, true, false, false, true, false}; + const bool all_rows[8] = {true, true, true, true, true, true, true, true}; + const int8_t yts[] = {RAY_I64, RAY_I32, RAY_I16, RAY_BOOL}; + test_result_t r = { TEST_PASS, NULL }; + for (size_t t = 0; t < sizeof yts / sizeof yts[0] && r.status == TEST_PASS; t++) { + ray_t* tbl = make_zero_div_table(yts[t]); + bool i64 = yts[t] == RAY_I64; + r = zd_check(tbl, build_zd_idiv, zero_rows, false); /* IDIV is not fused */ + if (r.status == TEST_PASS) r = zd_check(tbl, build_zd_mod, zero_rows, i64); + if (r.status == TEST_PASS) r = zd_check(tbl, build_zd_div, zero_rows, i64); + if (r.status == TEST_PASS) r = zd_check(tbl, build_zd_mod_add, zero_rows, i64); + if (r.status == TEST_PASS && i64) { + r = zd_check(tbl, build_zd_idiv0, all_rows, false); + if (r.status == TEST_PASS) r = zd_check(tbl, build_zd_mod0, all_rows, true); + } + ray_release(tbl); + } + ray_sym_destroy(); ray_heap_destroy(); + return r; +} + const test_entry_t expr_null_entries[] = { { "expr_null/sym_ordered_sparse_no_intern", test_sym_ordered_sparse_no_intern, NULL, NULL }, { "expr_null/sym_ordered_partitions", test_sym_ordered_partitions, NULL, NULL }, @@ -1877,6 +1975,8 @@ const test_entry_t expr_null_entries[] = { { "expr_null/diff_i64_mul", test_diff_i64_mul, NULL, NULL }, { "expr_null/diff_i64_div", test_diff_i64_div, NULL, NULL }, { "expr_null/diff_i64_mod", test_diff_i64_mod, NULL, NULL }, + { "expr_null/zero_divisor_nullfree", test_zero_divisor_nullfree, NULL, NULL }, + { "expr_null/u8_mod_composition_fuses", test_u8_mod_composition_fuses, NULL, NULL }, { "expr_null/diff_i64_min2", test_diff_i64_min2, NULL, NULL }, { "expr_null/diff_i64_max2", test_diff_i64_max2, NULL, NULL }, { "expr_null/diff_i64_neg", test_diff_i64_neg, NULL, NULL }, diff --git a/test/test_format.c b/test/test_format.c index 5fe55af06..717a0eb78 100644 --- a/test/test_format.c +++ b/test/test_format.c @@ -700,7 +700,7 @@ static test_result_t test_fmt_atom_f32(void) { TEST_ASSERT_NOT_NULL(result); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); const char* s = ray_str_ptr(result); - TEST_ASSERT_NOT_NULL(strstr(s, "2.5")); + TEST_ASSERT_STR_EQ(s, "2.5e"); ray_release(result); PASS(); } @@ -884,7 +884,7 @@ static test_result_t test_fmt_vec_f32(void) { TEST_ASSERT_NOT_NULL(result); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); const char* s = ray_str_ptr(result); - TEST_ASSERT_NOT_NULL(strstr(s, "1.5")); + TEST_ASSERT_STR_EQ(s, "[1.5e 2.5e 3.5e]"); ray_release(result); ray_release(vec); PASS(); @@ -1739,6 +1739,208 @@ static test_result_t test_fmt_pp_scalar_passthrough(void) { PASS(); } +/* ---- Test: a quoted indexed times prints its binding as written ---- + * The parser turns [i 3] after a `times` head into a marker list; the + * formatter prints that list back as [i 3], in every mode, so the quoted + * form reads as the source did and re-parses. */ +static test_result_t test_fmt_times_binding(void) { + ray_t* q = ray_eval_str("(quote (times [i 3] (set r (+ r i))))"); + TEST_ASSERT_FALSE(!q || RAY_IS_ERR(q)); + for (int mode = 0; mode <= 2; mode++) { + ray_t* s = ray_fmt(q, mode); + TEST_ASSERT_FALSE(!s || RAY_IS_ERR(s)); + TEST_ASSERT_NOT_NULL(strstr(ray_str_ptr(s), "[i 3]")); + TEST_ASSERT_NULL(strstr(ray_str_ptr(s), "times bind")); + ray_release(s); + } + ray_release(q); + PASS(); +} + +/* ---- Test: a parted table formats as its rows ---- + * A parted column is an array of per-partition segments and the partition + * key column (date) a key per partition: the formatter read them as plain + * vectors, so every type printed as `?` and the cells as the segment count. + * Every mode, and show's stream, now writes what the flat table does: + * 30 rows over 3 partitions, so the REPL display reads its tail rows from + * the last partition. */ +static size_t fmt_write_to_buf(ray_t* obj, char* buf, size_t cap) { + FILE* fp = tmpfile(); + if (!fp) return 0; + ray_t* cause = NULL; + ray_err_t e = ray_fmt_write(fp, obj, &cause); + if (cause) ray_error_free(cause); + size_t n = 0; + if (e == RAY_OK) { + rewind(fp); + n = fread(buf, 1, cap - 1, fp); + } + buf[n] = '\0'; + fclose(fp); + return n; +} + +static test_result_t test_fmt_table_parted(void) { + ray_t* r = ray_eval_str( + "(do (.sys.exec \"rm -rf /tmp/rfl_fmt_parted\")" + " (set T (table [i s t] (list (til 10) (take ['a 'b 'c] 10) (as 'STR (til 10)))))" + " (.db.splayed.set \"/tmp/rfl_fmt_parted/2024.01.01/t/\" T)" + " (.db.splayed.set \"/tmp/rfl_fmt_parted/2024.01.02/t/\" (update {i: (+ i 10) from: T}))" + " (.db.splayed.set \"/tmp/rfl_fmt_parted/2024.01.03/t/\" (update {i: (+ i 20) from: T}))" + " 0)"); + TEST_ASSERT_FALSE(!r || RAY_IS_ERR(r)); + ray_release(r); + ray_t* parted = ray_eval_str("(.db.parted.get \"/tmp/rfl_fmt_parted/\" 't)"); + TEST_ASSERT_FALSE(!parted || RAY_IS_ERR(parted)); + ray_t* flat = ray_eval_str( + "(select {from: (.db.parted.get \"/tmp/rfl_fmt_parted/\" 't) where: (>= i 0)})"); + TEST_ASSERT_FALSE(!flat || RAY_IS_ERR(flat)); + + for (int mode = 0; mode <= 2; mode++) { + ray_t* fp = ray_fmt(parted, mode); + ray_t* ff = ray_fmt(flat, mode); + TEST_ASSERT_FALSE(!fp || RAY_IS_ERR(fp)); + TEST_ASSERT_FALSE(!ff || RAY_IS_ERR(ff)); + TEST_ASSERT_STR_EQ(ray_str_ptr(fp), ray_str_ptr(ff)); + if (mode == 1) { + const char* s = ray_str_ptr(fp); + TEST_ASSERT_NOT_NULL(strstr(s, "DATE")); + TEST_ASSERT_NOT_NULL(strstr(s, "SYM")); + TEST_ASSERT_NOT_NULL(strstr(s, "STR")); + TEST_ASSERT_NOT_NULL(strstr(s, "2024.01.03")); + TEST_ASSERT_NOT_NULL(strstr(s, "30 rows (20 shown)")); + } + ray_release(fp); + ray_release(ff); + } + + char bp[16384], bf[16384]; + size_t np = fmt_write_to_buf(parted, bp, sizeof(bp)); + size_t nf = fmt_write_to_buf(flat, bf, sizeof(bf)); + TEST_ASSERT_TRUE(nf > 0); + TEST_ASSERT_EQ_I((int64_t)np, (int64_t)nf); + TEST_ASSERT_TRUE(strcmp(bp, bf) == 0); + + ray_release(flat); + ray_release(parted); + r = ray_eval_str("(.sys.exec \"rm -rf /tmp/rfl_fmt_parted\")"); + if (r) ray_release(r); + PASS(); +} + +/* ---- Test: a ragged parted table formats as the flat table with nulls ---- + * The 2024.01.02 partition has no columns b..l, so their segments for it + * are NULL. The REPL display walked the segments by their own lengths, + * skipping it: the 2024.01.03 cells moved up into the 2024.01.02 rows and + * NA landed at the end; format "%" and show flattened every column with + * `at`, which drops the partition, so b printed 5 values for 7 rows. Every + * mode, and show's stream, now writes byte for byte what the same flat + * table with typed nulls in those rows writes. The 30-row table makes the + * REPL display hide rows, its head and tail both crossing the partition. */ +static test_result_t fmt_ragged_case(int64_t mid) { + char src[2048]; + snprintf(src, sizeof(src), + "(do (.sys.exec \"rm -rf /tmp/rfl_fmt_ragged\")" + " (set RA (table [a b s t f l] (list [1 2 3] [30 20 10] ['x 'y 'x]" + " (as 'STR (list \"p\" \"q\" \"r\")) [1.5 2.5 3.5] (list (list 1 \"a\") (list 2 \"b\") (list 3 \"c\")))))" + " (set RC (table [a b s t f l] (list [6 7] [70 60] ['zz 'x]" + " (as 'STR (list \"u\" \"v\")) [6.5 7.5] (list (list 6 \"f\") (list 7 \"g\")))))" + " (set RM (+ 4 (til %lld)))" + " (.db.splayed.set \"/tmp/rfl_fmt_ragged/2024.01.01/t/\" RA)" + " (.db.splayed.set \"/tmp/rfl_fmt_ragged/2024.01.02/t/\" (table [a] (list RM)))" + " (.db.splayed.set \"/tmp/rfl_fmt_ragged/2024.01.03/t/\" RC)" + " 0)", (long long)mid); + ray_t* r = ray_eval_str(src); + TEST_ASSERT_FALSE(!r || RAY_IS_ERR(r)); + ray_release(r); + ray_t* parted = ray_eval_str("(.db.parted.get \"/tmp/rfl_fmt_ragged/\" 't)"); + TEST_ASSERT_FALSE(!parted || RAY_IS_ERR(parted)); + snprintf(src, sizeof(src), + "(do (set n %lld)" + " (set nul (fn [c v] (concat (concat (at RA c) v) (at RC c))))" + " (table [date a b s t f l] (list" + " (concat (concat (take 2024.01.01 3) (take 2024.01.02 n)) (take 2024.01.03 2))" + " (concat (concat (at RA 'a) RM) (at RC 'a))" + " (nul 'b (take 0Nl n))" + " (nul 's (as 'SYM (map (fn [x] \"\") (til n))))" + " (nul 't (as 'STR (map (fn [x] \"\") (til n))))" + " (nul 'f (take 0Nf n))" + " (nul 'l (map (fn [x] null) (til n))))))", (long long)mid); + ray_t* flat = ray_eval_str(src); + TEST_ASSERT_FALSE(!flat || RAY_IS_ERR(flat)); + + for (int mode = 0; mode <= 2; mode++) { + ray_t* fp = ray_fmt(parted, mode); + ray_t* ff = ray_fmt(flat, mode); + TEST_ASSERT_FALSE(!fp || RAY_IS_ERR(fp)); + TEST_ASSERT_FALSE(!ff || RAY_IS_ERR(ff)); + TEST_ASSERT_STR_EQ(ray_str_ptr(fp), ray_str_ptr(ff)); + if (mode == 1) { + const char* out = ray_str_ptr(fp); + TEST_ASSERT_NOT_NULL(strstr(out, "0Nl")); + TEST_ASSERT_NOT_NULL(strstr(out, "0Nf")); + TEST_ASSERT_NULL(strstr(out, "NA")); + } + ray_release(fp); + ray_release(ff); + } + char bp[16384], bf[16384]; + size_t np = fmt_write_to_buf(parted, bp, sizeof(bp)); + size_t nf = fmt_write_to_buf(flat, bf, sizeof(bf)); + TEST_ASSERT_TRUE(nf > 0); + TEST_ASSERT_EQ_I((int64_t)np, (int64_t)nf); + TEST_ASSERT_TRUE(strcmp(bp, bf) == 0); + + ray_release(flat); + ray_release(parted); + r = ray_eval_str("(.sys.exec \"rm -rf /tmp/rfl_fmt_ragged\")"); + if (r) ray_release(r); + PASS(); +} + +/* println and show print through ray_lang_print, not ray_fmt. Its null + * atoms must use the same table as ray_fmt: the GUID null printed as `null` + * there while format already wrote 0Ng (#881). */ +static size_t lang_print_to_buf(ray_t* obj, char* buf, size_t cap) { + buf[0] = '\0'; + FILE* fp = tmpfile(); + if (!fp) return 0; + ray_lang_print(fp, obj); + fflush(fp); + rewind(fp); + size_t n = fread(buf, 1, cap - 1, fp); + buf[n] = '\0'; + fclose(fp); + return n; +} + +static test_result_t test_lang_print_nulls(void) { + static const uint8_t zero[16] = {0}; + char buf[64]; + ray_t* g = ray_typed_null(-RAY_GUID); + TEST_ASSERT_FALSE(!g || RAY_IS_ERR(g)); + TEST_ASSERT_TRUE(lang_print_to_buf(g, buf, sizeof(buf)) > 0); + TEST_ASSERT_STR_EQ(buf, "0Ng"); + ray_release(g); + ray_t* gz = ray_guid(zero); + TEST_ASSERT_FALSE(!gz || RAY_IS_ERR(gz)); + TEST_ASSERT_TRUE(lang_print_to_buf(gz, buf, sizeof(buf)) > 0); + TEST_ASSERT_STR_EQ(buf, "0Ng"); + ray_release(gz); + ray_t* e = ray_typed_null(-RAY_F32); + TEST_ASSERT_FALSE(!e || RAY_IS_ERR(e)); + TEST_ASSERT_TRUE(lang_print_to_buf(e, buf, sizeof(buf)) > 0); + TEST_ASSERT_STR_EQ(buf, "0Ne"); + ray_release(e); + PASS(); +} + +static test_result_t test_fmt_table_parted_ragged(void) { + test_result_t res = fmt_ragged_case(2); + if (res.status != TEST_PASS) return res; + return fmt_ragged_case(25); +} + /* ---- Suite definition ---- */ const test_entry_t format_entries[] = { @@ -1848,5 +2050,9 @@ const test_entry_t format_entries[] = { { "format/table/list_col_null", test_fmt_raw_elem_list_null, fmt_setup, fmt_teardown }, { "format/table/na_head", test_fmt_table_na_head, fmt_setup, fmt_teardown }, { "format/table/utf8_width", test_fmt_table_utf8_width, fmt_setup, fmt_teardown }, + { "format/times_binding", test_fmt_times_binding, fmt_setup_full, fmt_teardown_full }, + { "format/table/parted", test_fmt_table_parted, fmt_setup_full, fmt_teardown_full }, + { "format/table/parted_ragged", test_fmt_table_parted_ragged, fmt_setup_full, fmt_teardown_full }, + { "format/lang_print/nulls", test_lang_print_nulls, fmt_setup_full, fmt_teardown_full }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_fsst.c b/test/test_fsst.c new file mode 100644 index 000000000..2c264211e --- /dev/null +++ b/test/test_fsst.c @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include +#include "mem/heap.h" +#include "table/sym.h" +#include "store/fsst.h" +#include +#include +#include + +static void fsst_setup(void) { ray_heap_init(); (void)ray_sym_init(); } +static void fsst_teardown(void) { ray_sym_destroy(); ray_heap_destroy(); } + +static int fsst_roundtrip_all(const ray_fsst_table_t* t, const uint8_t* const* s, + const uint32_t* l, int n, int64_t* total_enc) { + *total_enc = 0; + for (int i = 0; i < n; i++) { + uint8_t* enc = malloc(2 * (size_t)l[i] + 1); + uint8_t* dec = malloc((size_t)l[i] + 1); + int64_t e = ray_fsst_encode(t, s[i], l[i], enc); + int64_t x = ray_fsst_expanded_len(t, enc, (uint32_t)e); + int64_t d = ray_fsst_decode(t, enc, (uint32_t)e, dec); + int ok = e >= 0 && x == (int64_t)l[i] && d == (int64_t)l[i] && memcmp(dec, s[i], l[i]) == 0; + *total_enc += e; + free(enc); free(dec); + if (!ok) return i; + } + return -1; +} + +static test_result_t test_fsst_urls_compress(void) { + enum { N = 2000 }; + static char buf[N][64]; + const uint8_t* s[N]; uint32_t l[N]; + int64_t raw = 0; + for (int i = 0; i < N; i++) { + int len = snprintf(buf[i], 64, "http://www.example.com/page/%d?ref=search", i * 7); + s[i] = (const uint8_t*)buf[i]; l[i] = (uint32_t)len; raw += len; + } + ray_fsst_table_t t; + ray_fsst_train(s, l, N, &t); + TEST_ASSERT_TRUE(t.n > 0); + int64_t enc; + TEST_ASSERT_EQ_I(fsst_roundtrip_all(&t, s, l, N, &enc), -1); + TEST_ASSERT_FMT(enc * 2 < raw, "enc %lld raw %lld", (long long)enc, (long long)raw); + PASS(); +} + +static test_result_t test_fsst_all_bytes_empty_long(void) { + static uint8_t all[256], longs[5000]; + for (int i = 0; i < 256; i++) all[i] = (uint8_t)i; + for (int i = 0; i < 5000; i++) longs[i] = (uint8_t)("abcabcabd"[i % 9]); + const uint8_t* s[3] = { all, (const uint8_t*)"", longs }; + uint32_t l[3] = { 256, 0, 5000 }; + ray_fsst_table_t t; + ray_fsst_train(s, l, 3, &t); + int64_t enc; + TEST_ASSERT_EQ_I(fsst_roundtrip_all(&t, s, l, 3, &enc), -1); + PASS(); +} + +static test_result_t test_fsst_deterministic(void) { + const uint8_t* s[3] = { (const uint8_t*)"banana", (const uint8_t*)"bandana", (const uint8_t*)"cabana" }; + uint32_t l[3] = { 6, 7, 6 }; + ray_fsst_table_t a, b; + ray_fsst_train(s, l, 3, &a); + ray_fsst_train(s, l, 3, &b); + TEST_ASSERT_TRUE(memcmp(&a, &b, sizeof a) == 0); + TEST_ASSERT_EQ_I(ray_fsst_table_bytes(&a), 8 + ((a.n + 7) & ~7) + 8 * a.n); + PASS(); +} + +static test_result_t test_fsst_encode_ix_matches_encode(void) { + enum { N = 500 }; + static char buf[N][64]; + const uint8_t* s[N]; uint32_t l[N]; + for (int i = 0; i < N; i++) { + int len = snprintf(buf[i], 64, "https://host%d.example.org/a/b/%d.html", i % 7, i * 13); + s[i] = (const uint8_t*)buf[i]; l[i] = (uint32_t)len; + } + ray_fsst_table_t t; ray_fsst_train(s, l, N, &t); + ray_fsst_index_t ix; ray_fsst_index_build(&t, &ix); + for (int i = 0; i < N; i++) { + uint8_t a[2 * 64 + 1], b[2 * 64 + 1]; + int64_t ea = ray_fsst_encode(&t, s[i], l[i], a); + int64_t eb = ray_fsst_encode_ix(&t, &ix, s[i], l[i], b); + TEST_ASSERT_EQ_I(ea, eb); + TEST_ASSERT_TRUE(memcmp(a, b, (size_t)ea) == 0); + } + PASS(); +} + +static test_result_t test_fsst_train_covers_whole_input(void) { + enum { N = 4000, H = 2000 }; + static char buf[N][160]; + const uint8_t* s[N]; uint32_t l[N]; + for (int i = 0; i < N; i++) { + int len = i < H + ? snprintf(buf[i], 160, "http://alpha.example.com/catalog/item/%d?lang=en&utm=0123456789012345678901234567890123456789012345", i * 3) + : snprintf(buf[i], 160, "https://zeta.another-site.net/users/profile/%d/settings/notifications/email/digest/weekly/summary/archive", i * 5); + s[i] = (const uint8_t*)buf[i]; l[i] = (uint32_t)len; + } + ray_fsst_table_t t; ray_fsst_train(s, l, N, &t); + int64_t enc; + TEST_ASSERT_EQ_I(fsst_roundtrip_all(&t, s, l, N, &enc), -1); + int64_t raw2 = 0, enc2; + for (int i = H; i < N; i++) raw2 += l[i]; + TEST_ASSERT_EQ_I(fsst_roundtrip_all(&t, s + H, l + H, N - H, &enc2), -1); + TEST_ASSERT_FMT(enc2 * 3 < raw2 * 2, "last half enc %lld raw %lld", (long long)enc2, (long long)raw2); + PASS(); +} + +const test_entry_t fsst_entries[] = { + { "fsst/urls_compress", test_fsst_urls_compress, fsst_setup, fsst_teardown }, + { "fsst/all_bytes_empty_long", test_fsst_all_bytes_empty_long, fsst_setup, fsst_teardown }, + { "fsst/deterministic", test_fsst_deterministic, fsst_setup, fsst_teardown }, + { "fsst/encode_ix_matches_encode", test_fsst_encode_ix_matches_encode, fsst_setup, fsst_teardown }, + { "fsst/train_covers_whole_input", test_fsst_train_covers_whole_input, fsst_setup, fsst_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_fused_topk.c b/test/test_fused_topk.c index 557011df2..79a876a71 100644 --- a/test/test_fused_topk.c +++ b/test/test_fused_topk.c @@ -1411,6 +1411,38 @@ static test_result_t test_topk_and_pred(void) { PASS(); } +/* gate: a nested `and` is the flat `and` of its leaves, so it is accepted + * whenever the flat form would be: the compiler (fp_compile_pred_dag) + * already walks nested OP_AND nodes. The leaf cap and the leaf shapes + * still apply across the nesting. */ +static test_result_t test_topk_gate_nested_and(void) { + ray_t* tbl = make_i64_table(100); + const char* accepted[] = { + "(and (and (>= v 5) (< v 80)) (== g 1))", + "(and (== g 1) (and (>= v 5) (and (< v 80) (!= v 9))))", + "(and (and (> v 0) (> v 1) (> v 2) (> v 3)) (and (> v 4) (> v 5) (> v 6) (> v 7)))", + }; + for (size_t i = 0; i < sizeof(accepted) / sizeof(accepted[0]); i++) { + ray_t* e = ray_parse(accepted[i]); + TEST_ASSERT_EQ_I(ray_fused_topk_supported(e, tbl), 1); + ray_release(e); + } + const char* refused[] = { + /* nine leaves across the nesting */ + "(and (and (> v 0) (> v 1) (> v 2) (> v 3)) (and (> v 4) (> v 5) (> v 6) (> v 7) (> v 8)))", + /* a leaf the fused evaluator cannot run */ + "(and (and (>= v 5) (or (== g 1) (== g 2))) (< v 80))", + "(and (and (>= v 5) (not (== g 1))) (< v 80))", + }; + for (size_t i = 0; i < sizeof(refused) / sizeof(refused[0]); i++) { + ray_t* e = ray_parse(refused[i]); + TEST_ASSERT_EQ_I(ray_fused_topk_supported(e, tbl), 0); + ray_release(e); + } + ray_release(tbl); + PASS(); +} + /* gate: sort key column not found in table (line 288). */ static test_result_t test_topk_gate_sort_key_missing(void) { int64_t N = 50; @@ -1644,6 +1676,7 @@ const test_entry_t fused_topk_entries[] = { { "fused_topk/i16_with_nulls", test_topk_i16_with_nulls, topk_setup, topk_teardown }, /* Branch-coverage: AND predicate */ { "fused_topk/and_pred", test_topk_and_pred, topk_setup, topk_teardown }, + { "fused_topk/gate_nested_and", test_topk_gate_nested_and, topk_setup, topk_teardown }, /* Branch-coverage: gate rejections */ { "fused_topk/gate_sort_key_missing", test_topk_gate_sort_key_missing, topk_setup, topk_teardown }, { "fused_topk/gate_out_col_missing", test_topk_gate_out_col_missing, topk_setup, topk_teardown }, diff --git a/test/test_graph_builtin.c b/test/test_graph_builtin.c index d92be62a3..ff1412f19 100644 --- a/test/test_graph_builtin.c +++ b/test/test_graph_builtin.c @@ -40,6 +40,7 @@ #include #include "mem/heap.h" #include "store/csr.h" +#include "core/pool.h" #include "lang/internal.h" #include @@ -538,6 +539,41 @@ static test_result_t test_graph_pagerank_direct(void) { PASS(); } +/* A build cut short by an interrupt must report "cancel", not the "oom" + * that a NULL relation otherwise means (the parallel CSR build gives up on + * a cancelled dispatch; the threshold is lowered so the small table takes + * that path). */ +static test_result_t test_graph_build_cancel(void) { + ray_heap_init(); + (void)ray_sym_init(); + if (!ray_pool_par_dispatch_ok(ray_pool_get(), 1, 0)) { + ray_sym_destroy(); ray_heap_destroy(); + SKIP("no pool worker"); + } + + ray_t* tbl = make_i64_edge_table(); + ray_t* sym_src = ray_sym(ray_sym_intern("src", 3)); + ray_t* sym_dst = ray_sym(ray_sym_intern("dst", 3)); + ray_t* build_args[3] = { tbl, sym_src, sym_dst }; + + int64_t saved = ray_csr_par_min_edges; + ray_csr_par_min_edges = 0; + ray_request_interrupt(); + ray_t* h = ray_graph_build_fn(build_args, 3); + ray_clear_interrupt(); + ray_csr_par_min_edges = saved; + + TEST_ASSERT_TRUE(RAY_IS_ERR(h)); + TEST_ASSERT_STR_EQ(ray_err_code(h), "cancel"); + ray_error_free(h); + + ray_release(sym_src); ray_release(sym_dst); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* -------------------------------------------------------------------------- * Cancellation: a checkpointed graph algorithm run with a pending interrupt * must return a clean "cancel" error — the per-iteration checkpoint fires on @@ -2613,6 +2649,7 @@ const test_entry_t graph_builtin_entries[] = { { "graph_builtin/handle_block_copy", test_graph_handle_block_copy, NULL, NULL }, { "graph_builtin/pagerank_direct", test_graph_pagerank_direct, NULL, NULL }, { "graph_builtin/cancel", test_graph_cancel, NULL, NULL }, + { "graph_builtin/build_cancel", test_graph_build_cancel, NULL, NULL }, { "graph_builtin/build_widen_i64_w", test_graph_build_widen_i64_weight, NULL, NULL }, { "graph_builtin/atom_to_i64_narrow", test_atom_to_i64_narrow, NULL, NULL }, { "graph_builtin/pagerank_bad_iter", test_pagerank_bad_iter_type, NULL, NULL }, diff --git a/test/test_heap.c b/test/test_heap.c index c7fb16a13..7f65e51cd 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -85,6 +85,10 @@ static int munmap(void* p, size_t len) { #endif #if defined(__linux__) #include /* IN_ACCESS: when the cgroup files are read */ +#include /* RLIMIT_MEMLOCK: the heap's lock fallback */ +#include /* waitpid: its child */ +#include /* SYS_mlock2: memory locked outside the heap */ +#include #endif #include #include @@ -2875,6 +2879,7 @@ static void relieve_env_begin(relieve_env_t* e) { e->base = ray_tl_heap; e->n = 0; e->wm = ray_heap_anon_watermark(); + ray_heap_note_activity(); /* an idle stamp left by an earlier test would let (.sys.gc) decay this one's pools */ static ray_runtime_t bare; /* no cgroup directory */ e->rt = __RUNTIME; if (!__RUNTIME) __RUNTIME = &bare; @@ -3368,15 +3373,71 @@ static int64_t relieve_cancelled(void) { return -1; #endif } + +/* The bytes of file fd past its first page that are dirty in the page cache + * (cachestat): those a discard must drop unwritten. A file system with no + * writeback — tmpfs — tags none, its pages owing no write; -1 where the + * kernel cannot tell (cachestat is Linux 6.5+). */ +static int64_t relieve_dirty(int fd) { + long ps = sysconf(_SC_PAGESIZE); + uint64_t pg = ps > 0 ? (uint64_t)ps : 4096; + struct { uint64_t off, len; } range = { pg, 0 }; /* len 0: to EOF */ + struct { uint64_t cache, dirty, writeback, evicted, recently; } cs; + if (fd < 0 || syscall(451 /* __NR_cachestat */, fd, &range, &cs, 0) != 0) return -1; + return (int64_t)(cs.dirty * pg); +} + +/* Whether the file system under spill directory dir drops the dirty pages + * a punched hole covers unwritten, in this thread's cancelled writes: a + * probe file of dir, dirtied through a shared mapping and punched past its + * first page, as heap_spill_discard punches a pool, the writes cancelled + * counting at least its dirty pages just before (relieve_dirty). XFS + * writes the range back before it punches it — its pages go all the same, + * and it reads zero after, but no write is cancelled — so where this says + * no, the cancelled writes tell nothing of the discard. tmpfs says yes: + * nothing there is dirty. */ +static bool relieve_punch_cancels(const char* dir) { +#if defined(FALLOC_FL_PUNCH_HOLE) + long ps = sysconf(_SC_PAGESIZE); + size_t pg = ps > 0 ? (size_t)ps : 4096, len = 16 * pg; + char path[300]; + snprintf(path, sizeof(path), "%srayprobe_XXXXXX", dir); + int fd = mkstemp(path); + if (fd < 0) return false; + unlink(path); + bool ok = false; + char* m = posix_fallocate(fd, 0, (off_t)len) == 0 + ? mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) : MAP_FAILED; + if (m != MAP_FAILED) { + memset(m, 0x5A, len); + int64_t dirty = relieve_dirty(fd); + int64_t c0 = relieve_cancelled(); + ok = dirty >= 0 && c0 >= 0 + && fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, + (off_t)pg, (off_t)(len - pg)) == 0 + && relieve_cancelled() - c0 >= dirty; + munmap(m, len); + } + close(fd); + return ok; +#else + (void)dir; + return false; +#endif +} #endif /* An empty spill pool parked at a boundary keeps its file and its mapping * for the next statement that spills, but its pages — dead data — are - * discarded: punched out of the file, the dirty ones unwritten (the - * thread's cancelled writes count them), then reserved again, so the file - * keeps its disk blocks. A spill pool still in use keeps its data. Taken - * back, the pool serves blocks anew, no pool mapped for them. An idle event - * loop does not wake for a parked pool (ray_heap_decay_due_ms). */ + * discarded: out of RAM (mincore), punched out of the file, so they read + * zero after, not their data written back, the dirty ones unwritten where + * the file system cancels the writes a punch drops (relieve_punch_cancels: + * the thread's cancelled writes then count at least the file's dirty pages + * just before; XFS writes them back first, and none are cancelled), then + * reserved again, so the file keeps its disk blocks. A spill pool still + * in use keeps its data. Taken back, the pool serves blocks anew, no pool + * mapped for them. An idle event loop does not wake for a parked pool + * (ray_heap_decay_due_ms). */ static test_result_t test_relieve_spill_discard(void) { #if !defined(__linux__) SKIP("pages are discarded on Linux only"); @@ -3402,10 +3463,12 @@ static test_result_t test_relieve_spill_discard(void) { } if (s2) ray_free(s2); + bool cancels = layout && relieve_punch_cancels(h->swap_path); + int64_t dirty = relieve_dirty(fd); int64_t c0 = relieve_cancelled(); ray_heap_set_anon_watermark(INT64_C(1) << 40); ray_heap_relieve(); /* its own spill: no relief */ - int64_t cw = c0 >= 0 ? relieve_cancelled() - c0 : -1; + int64_t cw = c0 >= 0 && dirty >= 0 ? relieve_cancelled() - c0 : -1; int64_t n1 = ray_heap_spill_discard_count(); relieve_far(); /* the pool still parked */ bool once = ray_heap_spill_discard_count() == n1; @@ -3413,6 +3476,11 @@ static test_result_t test_relieve_spill_discard(void) { bool kept = i2 >= 0 && h->pools[i2].parked && h->pools[i2].backed && h->pool_count == 4; int res = probe ? relieve_resident(probe) : -1; + /* Punched, not written back and dropped: s2's dead data reads zero + * (read after the residency, as reading brings the pages back). */ + bool zeroed = i2 >= 0; + for (size_t i = 0; zeroed && i < ((size_t)4 << 20); i += 4096) + zeroed = ((const unsigned char*)probe)[i] == 0; struct stat st; bool reserved = fd >= 0 && fstat(fd, &st) == 0 && (int64_t)st.st_blocks * 512 >= (int64_t)st.st_size; @@ -3438,7 +3506,8 @@ static test_result_t test_relieve_spill_discard(void) { if (i2 < 0) SKIP("the spill directory cannot punch holes"); TEST_ASSERT(kept, "the emptied spill pool was parked, file and mapping kept"); if (relieve_mincore()) TEST_ASSERT(res == 0, "its pages were discarded"); - if (cw >= 0) TEST_ASSERT(cw >= (int64_t)RELIEVE_HALF, "the dirty ones unwritten"); + TEST_ASSERT(zeroed, "punched out of the file: its dead data reads zero"); + if (cw >= 0 && cancels) TEST_ASSERT(cw >= dirty, "the dirty ones unwritten"); TEST_ASSERT(reserved, "its file keeps its disk blocks"); TEST_ASSERT(live, "the spill pool in use kept its data"); TEST_ASSERT(due > 0, "an idle event loop does not wake for the parked pool"); @@ -5131,6 +5200,640 @@ static test_result_t test_anon_watermark_spill(void) { PASS(); } +/* ---- Locking the heap against swap (heap_lock) ------------------------- * + * + * The heap locks only where the RAM limit is known — heap tests run with no + * runtime of their own (relieve_env_begin's bare one) — and within the + * smaller of the watermark and half the limit: lock_env_begin sets a limit + * large enough for what the tests lock, and puts the old one back. */ + +#if defined(RAY_OS_LINUX) +typedef struct { int64_t locked, vmlck, failed, skipped; } lock_mark_t; +static lock_mark_t lock_mark(void) { + return (lock_mark_t){ ray_heap_locked_bytes(), ray_vm_locked_bytes(), + ray_heap_lock_failures(), ray_heap_lock_skipped() }; +} + +/* Whether `bytes` more can be locked here: the switch on, and + * RLIMIT_MEMLOCK — raised to its hard limit, as the binary does at startup + * (ray_os_raise_memlock) — leaving room, or CAP_IPC_LOCK past it. */ +static bool lock_room(int64_t bytes) { + bool on = ray_heap_set_lock(true); + ray_heap_set_lock(on); + if (!on) return false; /* RAY_HEAP_MLOCK=0 */ + ray_os_raise_memlock(); + if (ray_os_has_ipc_lock()) return true; + struct rlimit rl; + if (getrlimit(RLIMIT_MEMLOCK, &rl) != 0) return false; + if (rl.rlim_cur == RLIM_INFINITY) return true; + return ray_vm_locked_bytes() + bytes + RELIEVE_POOL <= (int64_t)rl.rlim_cur; +} + +static int64_t g_lock_saved_lim; +static void lock_env_begin(relieve_env_t* e) { + relieve_env_begin(e); /* the watermark far away */ + g_lock_saved_lim = __RUNTIME->ram_limit; + __RUNTIME->ram_limit = INT64_C(1) << 40; /* the bound: half of it */ +} +static void lock_env_end(relieve_env_t* e, ray_heap_t* h) { + __RUNTIME->ram_limit = g_lock_saved_lim; + relieve_env_end(e, h, NULL); +} +#endif + +/* A pool mapped under the watermark is locked against swap-out — the whole + * mapping, in the heap's count and in VmLck — but nothing is faulted in for + * it (MLOCK_ONFAULT: a page never touched is not resident), and unmapping + * the pool unlocks it. */ +static test_result_t test_lock_pool_under_watermark(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + if (!lock_room(RELIEVE_POOL)) SKIP("RLIMIT_MEMLOCK leaves no room for a pool"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + lock_mark_t m0 = lock_mark(); + ray_t* a = ray_alloc(RELIEVE_HALF); /* a pool of its own */ + lock_mark_t m1 = lock_mark(); + const char* untouched = a ? (const char*)a + (8u << 20) : NULL; + int res = untouched ? relieve_resident(untouched) : -1; + if (a) { + memset(ray_data(a), 0x5A, 1u << 20); + ray_free(a); + } + lock_env_end(&e, h); /* the pool unmapped */ + lock_mark_t m2 = lock_mark(); + if (!a) SKIP("block unavailable"); + TEST_ASSERT_EQ_I(m1.locked - m0.locked, RELIEVE_POOL); + TEST_ASSERT_EQ_I(m1.vmlck - m0.vmlck, RELIEVE_POOL); + if (relieve_mincore()) TEST_ASSERT(res == 0, "locking faulted nothing in (MLOCK_ONFAULT)"); + TEST_ASSERT_EQ_I(m2.locked, m0.locked); + TEST_ASSERT_EQ_I(m2.vmlck, m0.vmlck); + PASS(); +#endif +} + +/* Only what fits under the watermark is locked: past it, a pool or a direct + * block over a spill file, and a pool, a direct block or a large sys block + * taken from RAM because no spill file can be made, are all left unlocked. + * Under it a direct block and a sys block of a megabyte or more are locked + * as a pool is. */ +static test_result_t test_lock_not_past_watermark(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + const size_t dsz = 40u * 1024 * 1024 - 128; + const size_t big = 2u * 1024 * 1024; + if (!lock_room(2 * RELIEVE_POOL + (int64_t)dsz + (int64_t)big)) + SKIP("RLIMIT_MEMLOCK leaves no room for the blocks"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + /* Unlocked memory first, a pool and a large block, so that the bound + * alone (the locked bytes within the watermark) would leave room to lock + * past the watermark: only the watermark's own check stands then. */ + bool was = ray_heap_set_lock(false); + ray_t* pad1 = ray_alloc(RELIEVE_HALF); + ray_t* pad2 = ray_alloc(4 * dsz); + ray_heap_set_lock(was); + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + lock_mark_t m0 = lock_mark(); + ray_t* s1 = ray_alloc(RELIEVE_HALF); /* a pool over a spill file */ + ray_t* d1 = ray_alloc(dsz); /* a direct block over one */ + bool filed = s1 && relieve_pool_is_backed(h, s1) && d1 && ray_direct_file_backed(d1); + lock_mark_t m1 = lock_mark(); + /* A heap with no spill directory takes its next pool from RAM, and a + * large block; a sys block past the watermark too, with none. */ + const char* saved_dir = getenv("RAY_HEAP_SWAP"); + char saved[256] = ""; + if (saved_dir) snprintf(saved, sizeof(saved), "%s", saved_dir); + setenv("RAY_HEAP_SWAP", "/nonexistent-rayforce-spill", 1); + ray_heap_t* r = relieve_heap_new(&e); + bool ram = false; + lock_mark_t m2 = m1; + if (r) { + ray_t* b = ray_alloc(RELIEVE_HALF); + ray_t* d = ray_alloc(dsz); + int64_t c0 = ray_heap_anon_committed(); + void* sb = ray_sys_alloc(big); + ram = b && heap_find_pool(r, b) >= 0 && !relieve_pool_is_backed(r, b) + && d && !ray_direct_file_backed(d) + && sb && ray_heap_anon_committed() > c0; /* the sys block in RAM */ + m2 = lock_mark(); + if (sb) ray_sys_free(sb); + if (d) ray_free(d); + ray_heap_direct_cache_drain(); + ray_heap_destroy(); + } + if (saved_dir) setenv("RAY_HEAP_SWAP", saved, 1); + else unsetenv("RAY_HEAP_SWAP"); + ray_tl_heap = h; + if (d1) ray_free(d1); + if (s1) ray_free(s1); + /* Under the watermark: a direct block, a sys block. */ + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_direct_cache_drain(); + lock_mark_t m3 = lock_mark(); + ray_t* d2 = ray_alloc(dsz); + lock_mark_t m4 = lock_mark(); + int64_t dmap = d2 ? (int64_t)ray_direct_map_size(d2) : 0; + void* sys = ray_sys_alloc(big); + lock_mark_t m5 = lock_mark(); + if (sys) ray_sys_free(sys); + lock_mark_t m6 = lock_mark(); + if (d2) ray_free(d2); + ray_heap_direct_cache_drain(); + lock_mark_t m7 = lock_mark(); + if (a1) ray_free(a1); + if (pad2) ray_free(pad2); + if (pad1) ray_free(pad1); + ray_heap_direct_cache_drain(); + lock_env_end(&e, h); + if (!pad1 || !pad2 || !a1 || !filed || !d2 || !sys) SKIP("blocks or spill files unavailable"); + TEST_ASSERT(m1.locked == m0.locked && m1.vmlck == m0.vmlck, + "past the watermark, spill files were not locked"); + TEST_ASSERT(ram, "no spill directory: the pool, the large block and the sys block came from RAM"); + TEST_ASSERT(m2.locked == m1.locked && m2.vmlck == m1.vmlck, + "past the watermark, a pool, a direct block and a sys block from RAM were not locked"); + TEST_ASSERT_EQ_I(m4.locked - m3.locked, dmap); + TEST_ASSERT_EQ_I(m5.locked - m4.locked, (int64_t)(big + 4096)); + TEST_ASSERT_EQ_I(m5.vmlck - m3.vmlck, dmap + (int64_t)(big + 4096)); + TEST_ASSERT_EQ_I(m6.locked, m4.locked); + TEST_ASSERT_EQ_I(m7.locked, m3.locked); + PASS(); +#endif +} + +/* The bound: nothing is locked where the RAM limit is not known, nor with + * locking off (RAY_HEAP_MLOCK=0, run through the binary in + * lock_rlimit_fallback); and no more than half the RAM limit (or the watermark, + * the smaller) — a pool past it is mapped unlocked, its bytes counted as + * skipped. */ +static test_result_t test_lock_bound(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + if (!lock_room(2 * RELIEVE_POOL)) SKIP("RLIMIT_MEMLOCK leaves no room for two pools"); + relieve_env_t e; + lock_env_begin(&e); + int64_t got[4] = { -1, -1, -1, -1 }, skip[4] = { -1, -1, -1, -1 }; + bool missing = false; + /* 0: no RAM limit; 1: locking off; 2: room for one pool; 3: none */ + for (int pass = 0; pass < 4; pass++) { + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { missing = true; break; } + int64_t base = ray_heap_locked_bytes(); + __RUNTIME->ram_limit = pass == 0 ? 0 + : pass == 3 ? 2 * (base + RELIEVE_MB) + : 2 * (base + RELIEVE_POOL + RELIEVE_MB); + bool was = pass == 1 ? ray_heap_set_lock(false) : true; + lock_mark_t m0 = lock_mark(); + ray_t* a = ray_alloc(RELIEVE_HALF); + lock_mark_t m1 = lock_mark(); + if (pass == 1) ray_heap_set_lock(was); + if (!a) missing = true; + got[pass] = m1.locked - m0.locked; + skip[pass] = m1.skipped - m0.skipped; + if (a) ray_free(a); + __RUNTIME->ram_limit = INT64_C(1) << 40; + ray_heap_destroy(); + ray_tl_heap = e.base; + } + lock_env_end(&e, NULL); + if (missing) SKIP("no fresh heap, or its block unavailable"); + TEST_ASSERT(got[0] == 0, "no RAM limit known: nothing locked"); + TEST_ASSERT(got[1] == 0, "locking off: nothing locked"); + TEST_ASSERT_EQ_I(got[2], RELIEVE_POOL); + TEST_ASSERT(got[3] == 0 && skip[3] == RELIEVE_POOL, + "past half the RAM limit the pool was left unlocked, its bytes skipped"); + PASS(); +#endif +} + +/* A locked pool still hands back the pages of its free blocks when asked + * (ray_heap_release_pages; pass 5 and the idle decay alike): MADV_DONTNEED + * refuses a locked range, so the release takes MADV_DONTNEED_LOCKED, or + * before Linux 5.18 unlocks, releases and locks the range again — locked as + * before. The next block cut there holds data. */ +static test_result_t test_lock_release_pages(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + if (!lock_room(RELIEVE_POOL)) SKIP("RLIMIT_MEMLOCK leaves no room for a pool"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + lock_mark_t m0 = lock_mark(); + ray_t* a1 = ray_alloc(RELIEVE_HALF); /* the pool, locked */ + ray_t* b = ray_alloc((8u << 20) - 4096); /* order 23, from its cascade */ + lock_mark_t m1 = lock_mark(); + const char* probe = b ? (const char*)b + (4u << 20) : NULL; + int res0 = -1, res1 = -1; + if (b) { + memset(ray_data(b), 0x5A, (8u << 20) - 4096); + res0 = relieve_resident(probe); + ray_free(b); + ray_heap_release_pages(); + res1 = relieve_resident(probe); + } + lock_mark_t m2 = lock_mark(); + ray_t* c = ray_alloc((8u << 20) - 4096); + bool reused = c && (const char*)c == (const char*)b; + if (c) { + memset(ray_data(c), 0x3C, (8u << 20) - 4096); + reused = reused && ((const unsigned char*)ray_data(c))[4u << 20] == 0x3C; + ray_free(c); + } + if (a1) ray_free(a1); + lock_env_end(&e, h); + if (!a1 || !b) SKIP("blocks unavailable"); + TEST_ASSERT_EQ_I(m1.locked - m0.locked, RELIEVE_POOL); + if (relieve_mincore()) { + TEST_ASSERT(res0 == 1, "the written block was resident"); + TEST_ASSERT(res1 == 0, "the locked pool's free block handed its pages back"); + } + TEST_ASSERT(m2.locked == m1.locked && m2.vmlck == m1.vmlck && m2.failed == m1.failed, + "the pool stayed locked, nothing failed"); + TEST_ASSERT(reused, "the next block cut there holds data"); + PASS(); +#endif +} + +/* Dead memory is not kept locked: a pool parked at a boundary is unlocked — + * and locked again when an allocation takes it back — and (.sys.gc) + * unlocks the direct-block cache's blocks, which stay cached. */ +static test_result_t test_lock_dead_memory(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + const size_t dsz = 40u * 1024 * 1024 - 128; + if (!lock_room(2 * RELIEVE_POOL + (int64_t)dsz)) SKIP("RLIMIT_MEMLOCK leaves no room"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); /* a second pool */ + lock_mark_t m0 = lock_mark(); + if (a2) ray_free(a2); /* its pool empty */ + relieve_pressure(RELIEVE_MB); /* near the watermark: it parks */ + ray_heap_relieve(); + lock_mark_t m1 = lock_mark(); + int parked = relieve_parked(h); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_t* a3 = ray_alloc(RELIEVE_HALF); /* takes the parked pool back */ + lock_mark_t m2 = lock_mark(); + bool back = a3 && h->pool_count == 2 && relieve_parked(h) == 0; + /* A direct block freed into the cache stays locked until (.sys.gc). */ + ray_heap_direct_cache_drain(); + ray_t* d = ray_alloc(dsz); + int64_t dmap = d ? (int64_t)ray_direct_map_size(d) : 0; + if (d) ray_free(d); + lock_mark_t m3 = lock_mark(); + int64_t committed = ray_heap_anon_committed(); + ray_t* rc = ray_gc_fn(NULL, 0); + if (rc) ray_release(rc); + lock_mark_t m4 = lock_mark(); + bool cached = ray_heap_anon_committed() == committed; + ray_heap_direct_cache_drain(); + lock_mark_t m5 = lock_mark(); + if (a3) ray_free(a3); + if (a1) ray_free(a1); + lock_env_end(&e, h); + if (!a1 || !a2 || !d) SKIP("blocks unavailable"); + TEST_ASSERT(parked == 1, "the empty pool was parked"); + TEST_ASSERT_EQ_I(m0.locked - m1.locked, RELIEVE_POOL); + TEST_ASSERT_EQ_I(m0.vmlck - m1.vmlck, RELIEVE_POOL); + TEST_ASSERT(back, "an allocation took the parked pool back"); + TEST_ASSERT_EQ_I(m2.locked, m0.locked); + TEST_ASSERT_EQ_I(m3.locked - m2.locked, dmap); + TEST_ASSERT_EQ_I(m4.locked, m2.locked); + TEST_ASSERT_EQ_I(m4.vmlck, m2.vmlck); + TEST_ASSERT(cached, "(.sys.gc) left the block cached"); + TEST_ASSERT_EQ_I(m5.locked, m2.locked); + PASS(); +#endif +} + +/* A locked pool unmapped — an empty one handed back before a large block + * crosses the watermark (heap_make_room) — comes off the locked bytes. */ +static test_result_t test_lock_unmap(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + const size_t dsz = 40u * 1024 * 1024 - 128; + if (!lock_room(2 * RELIEVE_POOL)) SKIP("RLIMIT_MEMLOCK leaves no room for two pools"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); + if (a2) ray_free(a2); /* its pool empty, still mapped */ + lock_mark_t m0 = lock_mark(); + uint32_t pools0 = h->pool_count; + ray_heap_set_anon_watermark(ray_heap_anon_committed()); + ray_t* d = ray_alloc(dsz); /* past it: the empty pool goes first */ + lock_mark_t m1 = lock_mark(); + uint32_t pools1 = h->pool_count; + if (d) ray_free(d); + if (a1) ray_free(a1); + lock_env_end(&e, h); + if (!a1 || !a2 || !d) SKIP("blocks unavailable"); + TEST_ASSERT(pools0 == 2 && pools1 == 1, "the empty pool was unmapped"); + TEST_ASSERT_EQ_I(m0.locked - m1.locked, RELIEVE_POOL); + TEST_ASSERT_EQ_I(m0.vmlck - m1.vmlck, RELIEVE_POOL); + PASS(); +#endif +} + +/* What was unlocked while out of service is locked again when it comes + * back: a direct block the cache kept through (.sys.gc), taken again; and a + * parked pool put back by ray_heap_release_pages (the idle decay and a + * heap merge alike), locked after its pages went. */ +static test_result_t test_lock_back_in_service(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + const size_t dsz = 40u * 1024 * 1024 - 128; + if (!lock_room(2 * RELIEVE_POOL + (int64_t)dsz)) SKIP("RLIMIT_MEMLOCK leaves no room"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + ray_t* a1 = ray_alloc(RELIEVE_HALF); /* the heap's first pool, for (.sys.gc)'s result */ + ray_heap_direct_cache_drain(); + ray_t* d = ray_alloc(dsz); + int64_t dmap = d ? (int64_t)ray_direct_map_size(d) : 0; + const void* dbase = d; + if (d) ray_free(d); /* cached, locked */ + lock_mark_t m0 = lock_mark(); + ray_t* rc = ray_gc_fn(NULL, 0); /* unlocked, still cached */ + if (rc) ray_release(rc); + lock_mark_t m1 = lock_mark(); + ray_t* d2 = ray_alloc(dsz); /* the same block, back in service */ + lock_mark_t m2 = lock_mark(); + bool same = d2 && (const void*)d2 == dbase; + if (d2) ray_free(d2); + ray_heap_direct_cache_drain(); + /* A parked pool, unlocked; put back by ray_heap_release_pages. */ + ray_t* a2 = ray_alloc(RELIEVE_HALF); + if (a2) ray_free(a2); + relieve_pressure(RELIEVE_MB); + ray_heap_relieve(); + lock_mark_t m3 = lock_mark(); + int parked = relieve_parked(h); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_release_pages(); + lock_mark_t m4 = lock_mark(); + int parked_after = relieve_parked(h); + /* Parked again, then put back by the idle decay. */ + relieve_pressure(RELIEVE_MB); + ray_heap_relieve(); + lock_mark_t m5 = lock_mark(); + int parked2 = relieve_parked(h); + ray_heap_set_anon_watermark(INT64_C(1) << 40); + ray_heap_set_decay_ms(0); + ray_heap_note_activity(); + int64_t swept = ray_heap_decay(); + ray_heap_set_decay_ms(RAY_HEAP_DECAY_MS_TEST_DEFAULT); + lock_mark_t m6 = lock_mark(); + if (a1) ray_free(a1); + lock_env_end(&e, h); + if (!d || !a1 || !a2) SKIP("blocks unavailable"); + TEST_ASSERT_EQ_I(m0.locked - m1.locked, dmap); + TEST_ASSERT(same, "the cached block was taken again"); + TEST_ASSERT_EQ_I(m2.locked - m1.locked, dmap); + TEST_ASSERT_EQ_I(m2.vmlck - m1.vmlck, dmap); + TEST_ASSERT(parked == 1 && parked_after == 0, "the pool was parked, then put back"); + TEST_ASSERT_EQ_I(m4.locked - m3.locked, RELIEVE_POOL); + TEST_ASSERT_EQ_I(m4.vmlck - m3.vmlck, RELIEVE_POOL); + TEST_ASSERT(parked2 == 1 && m4.locked - m5.locked == RELIEVE_POOL, "parked again, unlocked"); + TEST_ASSERT(swept >= 0, "the decay ran"); + TEST_ASSERT_EQ_I(m6.locked - m5.locked, RELIEVE_POOL); + TEST_ASSERT_EQ_I(m6.vmlck - m5.vmlck, RELIEVE_POOL); + PASS(); +#endif +} + +/* A direct block too large for the cache (more than a sixteenth of the + * budget: the path of the GB-scale scratch blocks) is unmapped when freed, + * and comes off the locked bytes. */ +static test_result_t test_lock_big_direct(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + const size_t big = (size_t)1 << 30; /* never written: address space only */ + if (!lock_room((int64_t)big)) SKIP("RLIMIT_MEMLOCK leaves no room for 1 GB"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_direct_cache_drain(); + /* The watermark past the block, its sixteenth (the cache's budget) short of it. */ + ray_heap_set_anon_watermark(ray_heap_anon_committed() + (INT64_C(3) << 30)); + lock_mark_t m0 = lock_mark(); + int64_t c0 = ray_heap_anon_committed(); + ray_t* d = ray_alloc(big); + lock_mark_t m1 = lock_mark(); + int64_t dmap = d ? (int64_t)ray_direct_map_size(d) : 0; + bool fits = d && (int64_t)ray_direct_map_size(d) > ray_heap_anon_watermark() / 16; + if (d) ray_free(d); + lock_mark_t m2 = lock_mark(); + int64_t c2 = ray_heap_anon_committed(); + lock_env_end(&e, NULL); + if (!d) SKIP("1 GB block unavailable"); + TEST_ASSERT(fits, "the block is larger than the cache's budget"); + TEST_ASSERT_EQ_I(m1.locked - m0.locked, dmap); + TEST_ASSERT_EQ_I(c2, c0); + TEST_ASSERT_EQ_I(m2.locked, m0.locked); + TEST_ASSERT_EQ_I(m2.vmlck, m0.vmlck); + PASS(); +#endif +} + +/* A lock the pre-check lets through but the kernel refuses — the limit + * taken by memory locked outside the heap — is counted once; the next + * mappings are not tried again (each try takes the mapping lock and walks + * every mapping), only counted as skipped, until the locked bytes fall or + * the limit changes. */ +static test_result_t test_lock_refusal_remembered(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + if (geteuid() == 0 || ray_os_has_ipc_lock()) SKIP("CAP_IPC_LOCK: past any RLIMIT_MEMLOCK"); + if (!lock_room(4 * RELIEVE_POOL)) SKIP("RLIMIT_MEMLOCK leaves no room"); + struct rlimit saved; + if (getrlimit(RLIMIT_MEMLOCK, &saved) != 0) SKIP("RLIMIT_MEMLOCK unreadable"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + /* The soft limit two pools above what is locked now, and memory locked + * outside the heap — invisible to its count — taking all but a megabyte + * of that. */ + int64_t now = ray_vm_locked_bytes(); + struct rlimit low = saved; + low.rlim_cur = (rlim_t)(now + 2 * RELIEVE_POOL); + size_t eat = (size_t)(2 * RELIEVE_POOL - RELIEVE_MB); + void* outside = mmap(NULL, eat, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + bool set = outside != MAP_FAILED && setrlimit(RLIMIT_MEMLOCK, &low) == 0; + bool ate = set && syscall(SYS_mlock2, outside, eat, 1 /* MLOCK_ONFAULT */) == 0; + lock_mark_t m0 = lock_mark(); + ray_t* a1 = ate ? ray_alloc(RELIEVE_HALF) : NULL; /* refused by the kernel */ + lock_mark_t m1 = lock_mark(); + ray_t* a2 = ate ? ray_alloc(RELIEVE_HALF) : NULL; /* not tried */ + lock_mark_t m2 = lock_mark(); + if (outside != MAP_FAILED) munmap(outside, eat); + if (set) setrlimit(RLIMIT_MEMLOCK, &saved); + if (a2) ray_free(a2); + if (a1) ray_free(a1); + lock_env_end(&e, h); + if (!ate) SKIP("could not take the limit from outside the heap"); + TEST_ASSERT(a1 && a2, "the pools were mapped, unlocked"); + TEST_ASSERT(m1.failed == m0.failed + 1 && m1.locked == m0.locked, + "the kernel's refusal was counted, nothing locked"); + TEST_ASSERT(m2.failed == m1.failed && m2.skipped - m1.skipped == RELIEVE_POOL, + "the next pool was not tried again, its bytes skipped"); + PASS(); +#endif +} + +/* A watermark lowered under what is locked — by an embedding, say — is met + * at the next boundary: the cached direct blocks are unlocked first (dead + * memory), then pools, until the locked bytes fit. */ +static test_result_t test_lock_trim(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + const size_t dsz = 40u * 1024 * 1024 - 128; + if (!lock_room(2 * RELIEVE_POOL + (int64_t)dsz)) SKIP("RLIMIT_MEMLOCK leaves no room"); + relieve_env_t e; + lock_env_begin(&e); + ray_heap_t* h = relieve_heap_new(&e); + if (!h) { lock_env_end(&e, NULL); SKIP("no fresh heap"); } + ray_heap_direct_cache_drain(); + int64_t base = ray_heap_locked_bytes(); + ray_t* a1 = ray_alloc(RELIEVE_HALF); + ray_t* a2 = ray_alloc(RELIEVE_HALF); + ray_t* d = ray_alloc(dsz); + int64_t dmap = d ? (int64_t)ray_direct_map_size(d) : 0; + if (d) ray_free(d); /* cached, locked */ + lock_mark_t m1 = lock_mark(); + ray_heap_set_anon_watermark(base + RELIEVE_POOL + RELIEVE_MB); /* room for one */ + ray_heap_relieve(); + lock_mark_t m2 = lock_mark(); + bool live = a1 && a2 && d; + if (a2) ray_free(a2); + if (a1) ray_free(a1); + ray_heap_direct_cache_drain(); + lock_env_end(&e, h); + if (!live) SKIP("blocks unavailable"); + TEST_ASSERT_EQ_I(m1.locked - base, 2 * RELIEVE_POOL + dmap); + TEST_ASSERT_EQ_I(m2.locked - base, RELIEVE_POOL); + TEST_ASSERT_EQ_I(m1.vmlck - m2.vmlck, RELIEVE_POOL + dmap); + PASS(); +#endif +} + +/* The binary raises RLIMIT_MEMLOCK's soft limit to its hard one at startup + * (ray_os_raise_memlock), and where the limit leaves no room the heap works + * on unlocked, the bytes counted as skipped — no system call made for them. + * Run through ./rayforce with the limit set before exec, so the lowered + * limit dies with the child and no thread of this process is forked with a + * heap. Root, or CAP_IPC_LOCK, is past any limit: nothing to check then. */ +#if defined(RAY_OS_LINUX) +/* ./rayforce with RLIMIT_MEMLOCK soft/hard set, running `script`; its first + * output line into out[]; false if it did not run. */ +static bool lock_cli_run(const char* script, rlim_t soft, rlim_t hard, bool off, + char* out, size_t n) { + int fd[2]; + if (pipe(fd) != 0) return false; + pid_t pid = fork(); + if (pid < 0) { close(fd[0]); close(fd[1]); return false; } + if (pid == 0) { + struct rlimit rl = { soft, hard }; + dup2(fd[1], 1); + close(fd[0]); + close(fd[1]); + if (setrlimit(RLIMIT_MEMLOCK, &rl) != 0) _exit(64); + if (off) { + char* envp[] = { (char*)"RAY_HEAP_MLOCK=0", NULL }; + execle("./rayforce", "./rayforce", "-c", "1", script, (char*)NULL, envp); + } else { + unsetenv("RAY_HEAP_MLOCK"); /* whatever the suite runs under */ + execl("./rayforce", "./rayforce", "-c", "1", script, (char*)NULL); + } + _exit(65); + } + close(fd[1]); + size_t len = 0; + ssize_t r; + while (len + 1 < n && (r = read(fd[0], out + len, n - 1 - len)) != 0) { + if (r < 0) { if (errno == EINTR) continue; break; } + len += (size_t)r; + } + out[len] = 0; + close(fd[0]); + int status = 0; + pid_t w; + do w = waitpid(pid, &status, 0); while (w < 0 && errno == EINTR); + return w == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0; +} +#endif + +static test_result_t test_lock_rlimit_fallback(void) { +#if !defined(RAY_OS_LINUX) + SKIP("the heap locks against swap on Linux only"); +#else + if (geteuid() == 0 || ray_os_has_ipc_lock()) SKIP("CAP_IPC_LOCK: past any RLIMIT_MEMLOCK"); + if (access("./rayforce", X_OK) != 0) SKIP("no ./rayforce to run"); + struct rlimit rl; + if (getrlimit(RLIMIT_MEMLOCK, &rl) != 0) SKIP("RLIMIT_MEMLOCK unreadable"); + char script[64]; + snprintf(script, sizeof(script), "/tmp/rf_lock_fallback_%d.rfl", (int)getpid()); + int sf = open(script, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (sf < 0) SKIP("cannot write the script"); + const char* text = + "(set x (til 1000000))\n" + "(set m (.sys.mem))\n" + "(println (format \"% % % %\" (get m 'locked-bytes) (get m 'lock-failed)" + " (get m 'lock-skipped) (sum x)))\n"; + ssize_t wr = write(sf, text, strlen(text)); + close(sf); + if (wr != (ssize_t)strlen(text)) { unlink(script); SKIP("cannot write the script"); } + char out0[256], out1[256]; + /* No room at all: hard and soft 0. */ + bool ran0 = lock_cli_run(script, 0, 0, false, out0, sizeof(out0)); + /* Soft 0 under the hard limit: the binary raises it. */ + bool room = rl.rlim_max == RLIM_INFINITY || rl.rlim_max >= (rlim_t)(4 * RELIEVE_POOL); + bool ran1 = room && lock_cli_run(script, 0, rl.rlim_max, false, out1, sizeof(out1)); + /* The same with RAY_HEAP_MLOCK=0: nothing locked, nothing skipped. */ + char out2[256]; + bool ran2 = room && lock_cli_run(script, 0, rl.rlim_max, true, out2, sizeof(out2)); + unlink(script); + long long l2 = -1, f2 = -1, s2 = -1, x2 = -1; + if (ran2) sscanf(out2, "%lld %lld %lld %lld", &l2, &f2, &s2, &x2); + long long l0 = -1, f0 = -1, s0 = -1, x0 = -1, l1 = -1, f1 = -1, s1 = -1, x1 = -1; + if (ran0) sscanf(out0, "%lld %lld %lld %lld", &l0, &f0, &s0, &x0); + if (ran1) sscanf(out1, "%lld %lld %lld %lld", &l1, &f1, &s1, &x1); + TEST_ASSERT(ran0, "./rayforce ran with RLIMIT_MEMLOCK 0"); + TEST_ASSERT(x0 == 499999500000LL, "unlocked, the heap worked as ever"); + TEST_ASSERT(l0 == 0 && s0 > 0, "nothing locked, the bytes counted as skipped"); + TEST_ASSERT(f0 == 0, "no lock tried past the limit"); + if (!room) SKIP("the hard RLIMIT_MEMLOCK leaves no room: the raise not checked"); + TEST_ASSERT(ran1, "./rayforce ran with the soft limit at 0"); + TEST_ASSERT(x1 == 499999500000LL && l1 > 0, + "the soft limit raised to the hard one, the heap locked"); + TEST_ASSERT(ran2 && x2 == 499999500000LL && l2 == 0 && f2 == 0 && s2 == 0, + "RAY_HEAP_MLOCK=0: nothing locked, nothing tried"); + PASS(); +#endif +} + /* ---- Slab byte-budget caps -------------------------------------------- * * * Verify that ray_heap_init computes slab_cap[] correctly from the default @@ -5563,6 +6266,17 @@ const test_entry_t heap_entries[] = { { "heap/relieve_park", test_relieve_park, heap_setup, heap_teardown }, { "heap/direct_cache_concurrent", test_direct_cache_concurrent_replacement, heap_setup, heap_teardown }, { "heap/anon_watermark_spill", test_anon_watermark_spill, heap_setup, heap_teardown }, + { "heap/lock_pool_under_watermark", test_lock_pool_under_watermark, heap_setup, heap_teardown }, + { "heap/lock_not_past_watermark", test_lock_not_past_watermark, heap_setup, heap_teardown }, + { "heap/lock_release_pages", test_lock_release_pages, heap_setup, heap_teardown }, + { "heap/lock_bound", test_lock_bound, heap_setup, heap_teardown }, + { "heap/lock_dead_memory", test_lock_dead_memory, heap_setup, heap_teardown }, + { "heap/lock_trim", test_lock_trim, heap_setup, heap_teardown }, + { "heap/lock_unmap", test_lock_unmap, heap_setup, heap_teardown }, + { "heap/lock_back_in_service", test_lock_back_in_service, heap_setup, heap_teardown }, + { "heap/lock_big_direct", test_lock_big_direct, heap_setup, heap_teardown }, + { "heap/lock_refusal_remembered", test_lock_refusal_remembered, heap_setup, heap_teardown }, + { "heap/lock_rlimit_fallback", test_lock_rlimit_fallback, heap_setup, heap_teardown }, { "heap/slab_byte_budget", test_slab_byte_budget, heap_setup, heap_teardown }, { "heap/slab_gc_drains_wide", test_slab_gc_drains_wide, heap_setup, heap_teardown }, { "heap/retain_atom_obj", test_retain_owned_refs_atom_obj, heap_setup, heap_teardown }, diff --git a/test/test_idx_uses.c b/test/test_idx_uses.c new file mode 100644 index 000000000..004582cf5 --- /dev/null +++ b/test/test_idx_uses.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + + +#include "test.h" +#include +#include "core/runtime.h" +#include "lang/eval.h" +#include "ops/idxop.h" + +static void iu_setup(void) { ray_runtime_create(0, NULL); } +static void iu_teardown(void) { ray_runtime_destroy(__RUNTIME); } + +static test_result_t test_idx_uses_counts_hash_lookup(void) { + ray_t* s = ray_eval_str("(set t (table [k v] (list (til 100000) (til 100000))))"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + s = ray_eval_str("(set t (update {from: t k: (.idx.hash k)}))"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + s = ray_eval_str("(.idx.uses t)"); /* reset */ + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + s = ray_eval_str("(select {from: t where: (== k 777)})"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + ray_t* r = ray_eval_str("(.idx.uses t)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->type, RAY_DICT); + TEST_ASSERT_EQ_I(ray_dict_len(r), 1); + ray_t* again = ray_eval_str("(.idx.uses t)"); /* reset happened */ + TEST_ASSERT_TRUE(again && !RAY_IS_ERR(again)); + TEST_ASSERT_EQ_I(ray_dict_len(again), 0); + ray_release(r); ray_release(again); + PASS(); +} + +/* A sorted column that also carries a HASH index, filtered by a range, is + * answered by the sorted-range rowsel, which never reads col->index. */ +static test_result_t test_idx_uses_ignores_sorted_range(void) { + ray_t* s = ray_eval_str("(set t (table [k v] (list (til 300000) (til 300000))))"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + s = ray_eval_str("(set t (update {from: t k: (.idx.hash k)}))"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + ray_t* tt = ray_eval_str("t"); + TEST_ASSERT_TRUE(tt && !RAY_IS_ERR(tt)); + ray_t* k = ray_table_get_col(tt, ray_sym_intern("k", 1)); + if (k && (k->attrs & RAY_ATTR_HAS_INDEX)) k->attrs |= RAY_ATTR_SORTED; /* til is ascending: verified by construction */ + bool ok = k && (k->attrs & RAY_ATTR_HAS_INDEX) && ray_attr_is_sorted(k); + ray_release(tt); + TEST_ASSERT_TRUE(ok); + s = ray_eval_str("(.idx.uses t)"); /* reset, arms counting */ + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); ray_release(s); + uint64_t hits = ray_idx_hits[IDX_SITE_FILTER_RANGE]; + s = ray_eval_str("(select {from: t where: (>= k 100000)})"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); + TEST_ASSERT_EQ_I(ray_table_nrows(s), 200000); ray_release(s); + TEST_ASSERT_TRUE(ray_idx_hits[IDX_SITE_FILTER_RANGE] > hits); /* took the sorted-range path */ + ray_t* r = ray_eval_str("(.idx.uses t)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_dict_len(r), 0); + ray_release(r); + PASS(); +} + +static test_result_t test_idx_uses_rejects_non_table(void) { + ray_t* r = ray_eval_str("(.idx.uses 5)"); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + ray_error_free(r); + PASS(); +} + +const test_entry_t idx_uses_entries[] = { + { "idx_uses/counts_hash_lookup", test_idx_uses_counts_hash_lookup, iu_setup, iu_teardown }, + { "idx_uses/ignores_sorted_range", test_idx_uses_ignores_sorted_range, iu_setup, iu_teardown }, + { "idx_uses/rejects_non_table", test_idx_uses_rejects_non_table, iu_setup, iu_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_ipc.c b/test/test_ipc.c index bbfc1f628..237afded0 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -1062,7 +1062,7 @@ static void ipc_rm_journal(const char* jbase) { } static test_result_t test_ipc_journal_path(void) { - const char* jbase = "/tmp/rayforce_test_ipc_journal"; + const char* jbase = ray_test_tmp("/tmp/rayforce_test_ipc_journal"); /* Remove stale files */ ipc_rm_journal(jbase); @@ -1464,7 +1464,7 @@ static test_result_t test_ipc_send_verbose_large_result(void) { * setting srv.restricted = true triggers the restricted journal path. */ static test_result_t test_ipc_journal_restricted(void) { - const char* jbase = "/tmp/rayforce_test_ipc_jrestr"; + const char* jbase = ray_test_tmp("/tmp/rayforce_test_ipc_jrestr"); ipc_rm_journal(jbase); ray_err_t jerr = ray_journal_open(jbase, RAY_JOURNAL_ASYNC); diff --git a/test/test_join_buildside.c b/test/test_join_buildside.c index a39b94155..1ddcbb5fe 100644 --- a/test/test_join_buildside.c +++ b/test/test_join_buildside.c @@ -1251,9 +1251,186 @@ static test_result_t test_jb_nf_differential(void) { return result; } +/* Identity LEFT gathers must retain ownership and fall back on expansion. */ +static test_result_t test_jb_left_identity(void) { + ray_heap_init(); + (void)ray_sym_init(); + const int64_t keys[] = {1, 2, 3}; + const int64_t rhs[] = {1, 3}; + ray_t* lt = jb_table1("lk", keys, 3); + ray_t* rt = jb_table1("rk", rhs, 2); + ray_t* payload = ray_vec_from_raw(RAY_I64, keys, 3); + ray_vec_set_null(payload, 1, true); + lt = ray_table_add_col(lt, ray_sym_intern("payload", 7), payload); + ray_release(payload); + ray_t* strings = ray_vec_new(RAY_STR, 3); + strings = ray_str_vec_append(strings, "alpha", 5); + strings = ray_str_vec_append(strings, "beta", 4); + strings = ray_str_vec_append(strings, "gamma", 5); + lt = ray_table_add_col(lt, ray_sym_intern("strings", 7), strings); + ray_release(strings); + ray_t* got = jb_join(lt, "lk", rt, "rk", 1); + TEST_ASSERT(got && !RAY_IS_ERR(got), "identity left join"); + ray_t* src = ray_table_col_idx(lt, 1); + ray_t* out = ray_table_col_idx(got, 1); + TEST_ASSERT(out == src, "identity left output shares its source"); + TEST_ASSERT(ray_vec_is_null(out, 1), "shared null metadata"); + ray_retain(out); + int64_t value = 99; + ray_t* changed = ray_vec_set(out, 0, &value); + TEST_ASSERT(changed && !RAY_IS_ERR(changed), "copy on write"); + TEST_ASSERT(changed != src, "mutation detaches shared output"); + TEST_ASSERT(*(int64_t*)ray_vec_get(src, 0) == 1, "source remains unchanged"); + ray_release(changed); + ray_release(lt); + TEST_ASSERT(*(int64_t*)ray_vec_get(out, 2) == 3, "output survives source release"); + ray_t* out_strings = ray_table_col_idx(got, 2); + size_t str_len = 0; + const char* str = ray_str_vec_get(out_strings, 2, &str_len); + TEST_ASSERT(str && str_len == 5 && memcmp(str, "gamma", 5) == 0, + "shared string pool survives source release"); + ray_release(got); + ray_release(rt); + + const int64_t duplicates[] = {1, 1, 3}; + lt = jb_table1("lk", keys, 3); + rt = jb_table1("rk", duplicates, 3); + got = jb_join(lt, "lk", rt, "rk", 1); + TEST_ASSERT(got && !RAY_IS_ERR(got), "duplicate left join"); + TEST_ASSERT(ray_table_nrows(got) == 4, "duplicates expand rows"); + TEST_ASSERT(ray_table_col_idx(got, 0) != ray_table_col_idx(lt, 0), + "expanded output must gather"); + ray_release(got); + ray_release(lt); + ray_release(rt); + + const int64_t n = RAY_PARALLEL_THRESHOLD + 5000; + int64_t* large_keys = malloc((size_t)n * sizeof(*large_keys)); + TEST_ASSERT(large_keys, "large identity fixture allocation"); + for (int64_t i = 0; i < n; i++) large_keys[i] = i; + lt = jb_table1("lk", large_keys, n); + /* Keep the build side below radix dispatch: radix partitioning may + * reorder pairs and must fail the explicit identity check. */ + rt = jb_table1("rk", large_keys, 3); + free(large_keys); + got = jb_join(lt, "lk", rt, "rk", 1); + TEST_ASSERT(got && !RAY_IS_ERR(got), "large identity left join"); + TEST_ASSERT(ray_table_nrows(got) == n, "large identity row count"); + TEST_ASSERT(ray_table_col_idx(got, 0) == ray_table_col_idx(lt, 0), + "large identity shares its source"); + TEST_ASSERT(*(int64_t*)ray_vec_get(ray_table_col_idx(got, 0), n - 1) == n - 1, + "large identity preserves final row"); + ray_release(got); + ray_release(lt); + ray_release(rt); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* Slice-header COW does not detach the underlying parent payload. */ +static test_result_t test_jb_left_identity_slice(void) { + ray_heap_init(); + (void)ray_sym_init(); + const int64_t keys[] = {1, 2}; + const int64_t values[] = {10, 20, 30, 40}; + ray_t* lt = jb_table1("lk", keys, 2); + ray_t* rt = jb_table1("rk", keys, 2); + ray_t* parent = ray_vec_from_raw(RAY_I64, values, 4); + ray_t* slice = ray_vec_slice(parent, 1, 2); + TEST_ASSERT(slice && !RAY_IS_ERR(slice), "slice fixture"); + lt = ray_table_add_col(lt, ray_sym_intern("payload", 7), slice); + ray_release(slice); + ray_t* got = jb_join(lt, "lk", rt, "rk", 1); + TEST_ASSERT(got && !RAY_IS_ERR(got), "identity join with slice payload"); + ray_t* src = ray_table_col_idx(lt, 1); + ray_t* out = ray_table_col_idx(got, 1); + ray_retain(out); + int64_t value = 99; + ray_t* changed = ray_vec_set(out, 0, &value); + TEST_ASSERT(changed && !RAY_IS_ERR(changed), "owned output mutation"); + TEST_ASSERT(*(int64_t*)ray_vec_get(changed, 0) == 99, "changed value"); + TEST_ASSERT(*(int64_t*)ray_vec_get(src, 0) == 20, "source slice unchanged"); + TEST_ASSERT(*(int64_t*)ray_vec_get(out, 0) == 20, "original join unchanged"); + for (int64_t i = 0; i < 4; i++) + TEST_ASSERT(*(int64_t*)ray_vec_get(parent, i) == values[i], + "source parent unchanged"); + TEST_ASSERT(!(out->attrs & RAY_ATTR_SLICE), "slice output is gathered"); + TEST_ASSERT(ray_table_col_idx(got, 0) == ray_table_col_idx(lt, 0), + "ordinary column still shares in mixed representation table"); + ray_release(changed); + ray_release(lt); + ray_release(parent); + TEST_ASSERT(*(int64_t*)ray_vec_get(out, 1) == 30, "gathered slice lifetime"); + ray_release(got); + ray_release(rt); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* Equal cardinality cannot prove identity: radix output is partition ordered. */ +static test_result_t test_jb_left_identity_radix(void) { + ray_heap_init(); + (void)ray_sym_init(); + const int64_t n = RAY_PARALLEL_THRESHOLD + 5000; + int64_t* keys = malloc((size_t)n * sizeof(*keys)); + int64_t* values = malloc((size_t)n * sizeof(*values)); + TEST_ASSERT(keys && values, "radix fixture allocation"); + for (int64_t i = 0; i < n; i++) { keys[i] = i; values[i] = 7 * i + 11; } + ray_t* lt = jb_table1("lk", keys, n); + ray_t* rt = jb_table1("rk", keys, n); + ray_t* right_ids = ray_vec_from_raw(RAY_I64, keys, n); + rt = ray_table_add_col(rt, ray_sym_intern("right_id", 8), right_ids); + ray_release(right_ids); + ray_t* payload = ray_vec_from_raw(RAY_I64, values, n); + lt = ray_table_add_col(lt, ray_sym_intern("payload", 7), payload); + ray_release(payload); + free(keys); + free(values); + ray_t* got = jb_join(lt, "lk", rt, "rk", 1); + TEST_ASSERT(got && !RAY_IS_ERR(got), "radix left join"); + TEST_ASSERT(ray_table_nrows(got) == n, "equal output cardinality"); + ray_t* out_key = ray_table_col_idx(got, 0); + ray_t* out_value = ray_table_col_idx(got, 1); + ray_t* out_right_id = ray_table_col_idx(got, 2); + uint8_t* seen = calloc((size_t)n, 1); + TEST_ASSERT(seen, "radix membership allocation"); + bool reordered = false; + for (int64_t i = 0; i < n; i++) { + int64_t key = *(int64_t*)ray_vec_get(out_key, i); + TEST_ASSERT(key >= 0 && key < n && !seen[key], "unique output key"); + seen[key] = 1; + reordered |= key != i; + TEST_ASSERT(*(int64_t*)ray_vec_get(out_right_id, i) == key, + "left and right payloads remain matched after reorder"); + TEST_ASSERT(*(int64_t*)ray_vec_get(out_value, i) == 7 * key + 11, + "payload follows its original row through radix reorder"); + } + free(seen); + TEST_ASSERT(reordered, "fixture exercises a nonidentity radix mapping"); + TEST_ASSERT(out_key != ray_table_col_idx(lt, 0), "reordered keys gathered"); + TEST_ASSERT(out_value != ray_table_col_idx(lt, 1), "reordered payload gathered"); + for (int64_t i = 0; i < n; i++) { + TEST_ASSERT(*(int64_t*)ray_vec_get(ray_table_col_idx(lt, 0), i) == i, + "source keys unchanged"); + TEST_ASSERT(*(int64_t*)ray_vec_get(ray_table_col_idx(lt, 1), i) == 7 * i + 11, + "source payload unchanged"); + } + ray_release(got); + ray_release(lt); + ray_release(rt); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* ── Entry table ─────────────────────────────────────────────────────────── */ const test_entry_t join_buildside_entries[] = { + { "join_buildside/left_identity_slice", test_jb_left_identity_slice, NULL, NULL }, + { "join_buildside/left_identity_radix", test_jb_left_identity_radix, NULL, NULL }, + { "join_buildside/left_identity", test_jb_left_identity, NULL, NULL }, { "join_buildside/force_fallback_ordinary", test_jb_force_fallback_ordinary, NULL, NULL }, { "join_buildside/auto_fallback_dup", test_jb_auto_fallback_dup, NULL, NULL }, { "join_buildside/baseline_radix_inner", test_jb_baseline_radix_inner, NULL, NULL }, diff --git a/test/test_journal.c b/test/test_journal.c index 8cce0ac2d..f398afff9 100644 --- a/test/test_journal.c +++ b/test/test_journal.c @@ -146,7 +146,7 @@ static void cleanup_base(const char* base) { } #else snprintf(path, sizeof(path), "rm -f '%s'.*.log 2>/dev/null", base); - (void)system(path); + if (system(path) != 0) { /* nothing to remove */ } #endif } @@ -200,7 +200,7 @@ static test_result_t test_journal_validate_empty(void) { /* 1c. Validate non-existent file — must return RAY_ERR_IO. */ static test_result_t test_journal_validate_no_file(void) { - ray_err_t e = ray_journal_validate("/tmp/jrn_nosuchfile_xyzzy.log", NULL, NULL); + ray_err_t e = ray_journal_validate(ray_test_tmp("/tmp/jrn_nosuchfile_xyzzy.log"), NULL, NULL); TEST_ASSERT_EQ_I(e, RAY_ERR_IO); PASS(); } @@ -388,7 +388,7 @@ static test_result_t test_journal_validate_growing_payload(void) { static test_result_t test_journal_replay_no_file(void) { int64_t chunks = 99, errs = 99; ray_jreplay_status_t status = RAY_JREPLAY_OK; - ray_err_t e = ray_journal_replay("/tmp/jrn_nosuch_replay.log", + ray_err_t e = ray_journal_replay(ray_test_tmp("/tmp/jrn_nosuch_replay.log"), &chunks, &errs, &status); TEST_ASSERT_EQ_I(e, RAY_ERR_IO); TEST_ASSERT_EQ_I(status, RAY_JREPLAY_IO); @@ -706,15 +706,18 @@ static test_result_t test_journal_open_long_base_releases_lock(void) { SKIP("deep-mkdir fixture not portable (PATH_MAX / MAX_PATH)"); #endif char dir[2048]; - const char* root = "/tmp/jrn_test_longbase"; /* 22 chars */ + const char* root = ray_test_tmp("/tmp/jrn_test_longbase"); const char* comp = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; /* 50 chars */ int off = snprintf(dir, sizeof(dir), "%s", root); - /* 22 + 19 * 51 = 991; a 27-char leaf makes the base 1019 bytes. */ - for (int i = 0; i < 19; i++) off += snprintf(dir + off, sizeof(dir) - (size_t)off, "/%s", comp); + /* the root plus 18 * 51 stays under 1000 bytes; a leaf of 'b' fills the base to 1019 bytes */ + for (int i = 0; i < 18; i++) off += snprintf(dir + off, sizeof(dir) - (size_t)off, "/%s", comp); + TEST_ASSERT_TRUE(off < 1000); TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); char base[2048]; - int blen = snprintf(base, sizeof(base), "%s/bbbbbbbbbbbbbbbbbbbbbbbbbbb", dir); - TEST_ASSERT_EQ_I(blen, 1019); + int blen = snprintf(base, sizeof(base), "%s/", dir); + while (blen < 1019) base[blen++] = 'b'; + base[blen] = '\0'; + TEST_ASSERT_EQ_I((int)strlen(base), 1019); TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_ERR_DOMAIN); TEST_ASSERT_FALSE(ray_journal_is_open()); @@ -1975,7 +1978,7 @@ static test_result_t test_ops_open_rank(void) { /* 22h. ray_log_open_fn: args[0] = NULL — !args[0] branch. */ static test_result_t test_ops_open_null_mode(void) { - ray_t* str_arg = ray_str("/tmp/jrn_ops_test", 17); + ray_t* str_arg = ray_str(ray_test_tmp("/tmp/jrn_ops_test"), strlen(ray_test_tmp("/tmp/jrn_ops_test"))); ray_t* args[2] = { NULL, str_arg }; ray_t* r = ray_log_open_fn(args, 2); TEST_ASSERT_NOT_NULL(r); @@ -1988,7 +1991,7 @@ static test_result_t test_ops_open_null_mode(void) { /* 22i. ray_log_open_fn: args[0] = integer — type != -RAY_SYM. */ static test_result_t test_ops_open_int_mode(void) { ray_t* int_arg = ray_i64(1); - ray_t* str_arg = ray_str("/tmp/jrn_ops_test", 17); + ray_t* str_arg = ray_str(ray_test_tmp("/tmp/jrn_ops_test"), strlen(ray_test_tmp("/tmp/jrn_ops_test"))); ray_t* args[2] = { int_arg, str_arg }; ray_t* r = ray_log_open_fn(args, 2); TEST_ASSERT_NOT_NULL(r); @@ -2032,7 +2035,7 @@ static test_result_t test_ops_open_sym_base(void) { static test_result_t test_ops_open_bad_mode(void) { int64_t bogus_id = ray_sym_intern("bogus", 5); ray_t* sym_mode = ray_sym(bogus_id); - ray_t* str_base = ray_str("/tmp/jrn_ops_test", 17); + ray_t* str_base = ray_str(ray_test_tmp("/tmp/jrn_ops_test"), strlen(ray_test_tmp("/tmp/jrn_ops_test"))); ray_t* args[2] = { sym_mode, str_base }; ray_t* r = ray_log_open_fn(args, 2); TEST_ASSERT_NOT_NULL(r); diff --git a/test/test_lang.c b/test/test_lang.c index fa80c1085..f774db5e8 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -30,6 +30,7 @@ #include "mem/heap.h" #include "store/part.h" #include "store/splay.h" +#include "store/enccol.h" #include "table/domain.h" #include "table/sym.h" #include "lang/internal.h" @@ -576,6 +577,48 @@ static test_result_t test_eval_nested_arith(void) { PASS(); } +/* An existing cache epoch makes row-binding work observable without a timer + * or new production instrumentation. A per-row fallback rebinds two names + * for every row; a whole-vector call changes only a bounded scope. */ +static test_result_t test_query_minmax_bulk_bound(void) { + ray_t* setup = ray_eval_str("(do (set MM_LEFT971 (til 1024))" + " (set MM_T971 (table [left971 right971] (list MM_LEFT971 (- 1023 MM_LEFT971)))) 1)"); + bool setup_ok = setup && !RAY_IS_ERR(setup); + if (setup) { if (RAY_IS_ERR(setup)) ray_error_free(setup); else ray_release(setup); } + TEST_ASSERT_TRUE(setup_ok); + const char* exprs[] = { + "(at (select {r: (min left971 right971) from: MM_T971}) 'r)", + "(at (select {r: (max left971 right971) from: MM_T971}) 'r)", + "(at (select {r: (min left971 200) from: MM_T971}) 'r)", + "(at (select {r: (max 0Nl right971) from: MM_T971}) 'r)", + "(at (select {r: (min 0Nl left971) from: MM_T971}) 'r)" + }; + for (int c = 0; c < 5; c++) { + uint64_t before = g_frame_epoch; + ray_t* out = ray_eval_str(exprs[c]); + uint64_t frames = g_frame_epoch - before; + bool shape = out && !RAY_IS_ERR(out) && out->type == RAY_I64 && ray_len(out) == 1024; + bool values = shape; + bool null_mark = c != 4 || (shape && (out->attrs & RAY_ATTR_HAS_NULLS)); + if (shape) { + const int64_t* data = (const int64_t*)ray_data(out); + for (int64_t i = 0; i < 1024; i++) { + int64_t other = 1023 - i; + int64_t want = c == 0 ? (i < other ? i : other) + : c == 1 ? (i > other ? i : other) + : c == 2 ? (i < 200 ? i : 200) : c == 3 ? other : INT64_MIN; + if (data[i] != want) values = false; + } + } + if (out) { if (RAY_IS_ERR(out)) ray_error_free(out); else ray_release(out); } + TEST_ASSERT_TRUE(shape); + TEST_ASSERT_TRUE(values); + TEST_ASSERT_TRUE(null_mark); + TEST_ASSERT_TRUE(frames < 64); + } + PASS(); +} + /* ---- Test: eval subtraction ---- */ static test_result_t test_eval_sub(void) { ray_t* result = ray_eval_str("(- 10 3)"); @@ -1525,6 +1568,223 @@ static test_result_t test_eval_select_where_in_sym(void) { PASS(); } +/* ---- Test: unary arithmetic lowers only on its builtin's types (#854) ---- + * compile_expr_dag lowers `neg`/`abs`/`exp`/`log`/`sqrt`/`ceil`/`floor`/ + * `round` over a column only when the column's type is one the builtin + * computes on the kernels' terms; any other column declines (NULL) so the + * evaluator applies the builtin itself. The kernels read a DATE, TIME or + * TIMESTAMP lane as its raw counts, SYM as interned ids, and ran the integer + * lanes of ceil/floor/round as doubles. Over an integer column (BOOL, U8, + * I16, I32, I64) ceil and floor lower to the column's own scan, and round + * to a cast to F64, the builtins' answers. */ +static bool unary_arith_lowers(const char* verb, const char* col) { + bool temporal_or_sym = !strcmp(col, "d") || !strcmp(col, "t") || + !strcmp(col, "ts") || !strcmp(col, "s"); + if (!strcmp(verb, "neg") || !strcmp(verb, "abs")) + return !temporal_or_sym && strcmp(col, "b") && strcmp(col, "u"); + if (!strcmp(verb, "exp") || !strcmp(verb, "log") || !strcmp(verb, "sqrt")) + return !temporal_or_sym; + return !temporal_or_sym; /* ceil / floor / round */ +} + +static bool unary_arith_int_col(const char* col) { + return !strcmp(col, "b") || !strcmp(col, "u") || !strcmp(col, "h") || + !strcmp(col, "i") || !strcmp(col, "l"); +} + +static test_result_t test_eval_select_unary_arith_dag_admission(void) { + ray_t* tbl = ray_eval_str( + "(table [d t ts b u h i l f s] (list [2024.01.01 2024.01.02] " + "[10:00:00.000 11:00:00.000] " + "[2024.01.01D10:00:00.000000000 2024.01.02D10:00:00.000000000] " + "[true false] (as 'U8 [1 2]) (as 'I16 [1 -2]) (as 'I32 [1 -2]) [1 -2] " + "[1.5 -2.5] ['a 'b]))"); + TEST_ASSERT_NOT_NULL(tbl); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + TEST_ASSERT_EQ_I(tbl->type, RAY_TABLE); + + static const char* const verbs[] = { + "neg", "abs", "exp", "log", "sqrt", "ceil", "floor", "round", + }; + static const char* const cols[] = { + "d", "t", "ts", "b", "u", "h", "i", "l", "f", "s", + }; + for (size_t v = 0; v < sizeof verbs / sizeof *verbs; v++) { + for (size_t c = 0; c < sizeof cols / sizeof *cols; c++) { + char src[32]; + snprintf(src, sizeof src, "(%s %s)", verbs[v], cols[c]); + ray_t* expr = ray_parse(src); + TEST_ASSERT_NOT_NULL(expr); + TEST_ASSERT_FALSE(RAY_IS_ERR(expr)); + ray_graph_t* g = ray_graph_new(tbl); + TEST_ASSERT_NOT_NULL(g); + ray_op_t* op = compile_expr_dag(g, expr); + bool want = unary_arith_lowers(verbs[v], cols[c]); + TEST_ASSERT_FMT((op != NULL) == want, "%s: lowered=%d, want %d", + src, op != NULL, want); + if (op && v >= 5 && unary_arith_int_col(cols[c])) { + /* ceil / floor: the scan itself; round: a cast to F64 */ + bool is_round = !strcmp(verbs[v], "round"); + TEST_ASSERT_FMT(op->opcode == (is_round ? OP_CAST : OP_SCAN), + "%s: opcode %d", src, (int)op->opcode); + TEST_ASSERT_FMT(is_round ? op->out_type == RAY_F64 + : op->out_type > 0, + "%s: out_type %d", src, (int)op->out_type); + } + ray_graph_free(g); + ray_release(expr); + } + } + ray_release(tbl); + + /* Over a column with nulls the lowered identity keeps the column's type + * and its HAS_NULLS mark; round maps the null to 0Nf. */ + static const char* const qs[] = { + "(do (set Tn (table [v] (list (as 'I32 [1 0N 3])))) (at (select {x: (floor v) from: Tn}) 'x))", + "(do (set Tn (table [v] (list (as 'I16 [1 0N 3])))) (at (select {x: (ceil v) from: Tn}) 'x))", + "(do (set Tn (table [v] (list [1 0N 3]))) (at (select {x: (round v) from: Tn}) 'x))", + }; + static const int8_t want_t[] = { RAY_I32, RAY_I16, RAY_F64 }; + for (size_t q = 0; q < sizeof qs / sizeof *qs; q++) { + ray_t* r = ray_eval_str(qs[q]); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_FMT(r->type == want_t[q], "%s: type %d", qs[q], (int)r->type); + TEST_ASSERT_EQ_I(r->len, 3); + TEST_ASSERT_TRUE(r->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(ray_vec_is_null(r, 1)); + TEST_ASSERT_FALSE(ray_vec_is_null(r, 0)); + if (want_t[q] == RAY_F64) + TEST_ASSERT_TRUE(((double*)ray_data(r))[2] == 3.0); + ray_release(r); + } + PASS(); +} + +/* ---- Test: an empty-operand type probe that fails leaves nothing behind ---- + * An empty operand makes the atomic mappers probe `fn` on a fabricated + * zero atom to learn the result type. A probe the builtin rejects — + * `(/ empty_DATE 2)`, `(neg empty_DATE)` — used to leak its error object + * and leave its message behind. select's empty-result probe evaluates an + * elementwise projection over the empty columns, and a whole-column + * failure there (`(+ d)`, `(neg d 1)`, `(pow d 2 3)`: the wrong arity) is + * swallowed by query.c itself, not inside a mapper. Repeated, through the + * builtins and through select, nothing stays allocated and no message is + * left over; the valid probe is the control. */ +static test_result_t test_eval_empty_probe_error_ownership(void) { + ray_t* setup = ray_eval_str("(set _EP (table [d] (list (as 'DATE []))))"); + TEST_ASSERT_NOT_NULL(setup); + TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); + ray_release(setup); + static const char* const exprs[] = { + "(+ (at _EP 'd) 2)", /* valid: control */ + "(/ (at _EP 'd) 2)", /* binary, rejected */ + "(div (at _EP 'd) 2)", + "(neg (at _EP 'd))", /* unary, rejected */ + "(at (select {x: (/ d 2) from: _EP}) 'x)", /* select's probe */ + "(at (select {x: (neg d) from: _EP}) 'x)", + "(at (select {x: (+ d) from: _EP}) 'x)", /* whole-column failure, */ + "(at (select {x: (neg d 1) from: _EP}) 'x)", /* swallowed in query.c */ + "(at (select {x: (pow d 2 3) from: _EP}) 'x)", + }; + for (size_t e = 0; e < sizeof(exprs) / sizeof(exprs[0]); e++) { + /* warm up: first-use allocations (symbols, caches) are not a leak */ + for (int i = 0; i < 4; i++) { + ray_t* r = ray_eval_str(exprs[e]); + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + } + ray_error_clear(); + ray_mem_stats_t s0, s1; + ray_mem_stats(&s0); + for (int i = 0; i < 1000; i++) { + ray_t* r = ray_eval_str(exprs[e]); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "%s: %s", exprs[e], ray_error_msg()); + TEST_ASSERT_FMT(ray_len(r) == 0, "%s: %lld rows", exprs[e], (long long)ray_len(r)); + ray_release(r); + } + ray_mem_stats(&s1); + TEST_ASSERT_FMT(s1.bytes_allocated <= s0.bytes_allocated, + "%s: %zu bytes left allocated after 1000 probes", + exprs[e], s1.bytes_allocated - s0.bytes_allocated); + const char* msg = ray_error_msg(); /* NULL when no message is set */ + TEST_ASSERT_FMT(!msg || !msg[0], "%s: stale message \"%s\"", + exprs[e], msg ? msg : ""); + } + ray_t* drop = ray_eval_str("(set _EP 0)"); + if (drop && !RAY_IS_ERR(drop)) ray_release(drop); + PASS(); +} + +/* ---- Test: temporal modulo by an integer literal lowers to the DAG ---- + * `(% temporal n)` keeps the left type in the builtin (ray_mod_fn), and + * the DAG's MOD kernel computes the same floor modulo on the raw counts, + * so compile_expr_dag lowers a temporal column by a non-null, nonzero + * integer literal to MOD cast back to the column's type. A zero or null + * literal, a float literal, a divisor column, a temporal literal on the + * left and the other verbs decline (NULL) to the builtin. */ +static test_result_t test_eval_select_temporal_mod_dag_admission(void) { + ray_t* tbl = ray_eval_str( + "(table [d t ts i l] (list [2024.01.01 2024.01.02] " + "[10:00:00.000 11:00:00.000] " + "[2024.01.01D10:00:00.000000000 2024.01.02D10:00:00.000000000] " + "(as 'I32 [2 3]) [2 3]))"); + TEST_ASSERT_NOT_NULL(tbl); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + + static const char* const cols[] = { "d", "t", "ts" }; + static const int8_t col_t[] = { RAY_DATE, RAY_TIME, RAY_TIMESTAMP }; + static const char* const lowers[] = { + "2", "-3", "2i", "2h", "true", "5000000000", + }; + static const char* const declines[] = { + "0", "0i", "false", "0N", "2.5", "0.0", "i", "l", "d", + "2024.01.02", + }; + for (size_t c = 0; c < sizeof cols / sizeof *cols; c++) { + for (size_t k = 0; k < sizeof lowers / sizeof *lowers + sizeof declines / sizeof *declines; k++) { + bool want = k < sizeof lowers / sizeof *lowers; + const char* rhs = want ? lowers[k] : declines[k - sizeof lowers / sizeof *lowers]; + char src[64]; + snprintf(src, sizeof src, "(%% %s %s)", cols[c], rhs); + ray_t* expr = ray_parse(src); + TEST_ASSERT_NOT_NULL(expr); + TEST_ASSERT_FALSE(RAY_IS_ERR(expr)); + ray_graph_t* g = ray_graph_new(tbl); + TEST_ASSERT_NOT_NULL(g); + ray_op_t* op = compile_expr_dag(g, expr); + TEST_ASSERT_FMT((op != NULL) == want, "%s: lowered=%d, want %d", + src, op != NULL, want); + if (op) { + TEST_ASSERT_FMT(op->opcode == OP_CAST && op->out_type == col_t[c], + "%s: opcode %d out_type %d", src, + (int)op->opcode, (int)op->out_type); + ray_op_t* m = &g->nodes[op->in_id[0]]; + TEST_ASSERT_FMT(m->opcode == OP_MOD, "%s: input opcode %d", + src, (int)m->opcode); + } + ray_graph_free(g); + ray_release(expr); + } + } + static const char* const other[] = { + "(% 2024.01.01 2)", "(/ d 2)", "(div d 2)", "(+ d 1)", "(* t 2)", "(pow ts 2)", + }; + for (size_t k = 0; k < sizeof other / sizeof *other; k++) { + ray_t* expr = ray_parse(other[k]); + TEST_ASSERT_NOT_NULL(expr); + TEST_ASSERT_FALSE(RAY_IS_ERR(expr)); + ray_graph_t* g = ray_graph_new(tbl); + TEST_ASSERT_NOT_NULL(g); + ray_op_t* op = compile_expr_dag(g, expr); + TEST_ASSERT_FMT(op == NULL, "%s: lowered", other[k]); + ray_graph_free(g); + ray_release(expr); + } + ray_release(tbl); + PASS(); +} + /* ---- Test: OP_IN type-mismatch must not leak via atom probe ---- * Deterministic regression: interns a sym so we know its numeric * ID N, builds an i64 column containing exactly N, then runs @@ -3493,8 +3753,8 @@ static test_result_t test_eval_insert_parted_e2e_impl(const char* root) { old_tail[i] = segs[1]; TEST_ASSERT_EQ_I(segs[0]->len, 2); TEST_ASSERT_EQ_I(segs[1]->len, 2); - TEST_ASSERT_EQ_U(segs[0]->mmod, 1); - TEST_ASSERT_EQ_U(segs[1]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs[0], 1); + TEST_ASSERT_LOADED_MMOD(segs[1], 1); } ray_t* base_sym_col = lang_parted_insert_col(before, "ticker"); @@ -3625,7 +3885,7 @@ static test_result_t test_eval_insert_parted_e2e_impl(const char* root) { ray_t** segs = (ray_t**)ray_data(col); TEST_ASSERT_EQ_PTR(segs[0], hist_seg[i]); TEST_ASSERT_EQ_I(segs[0]->len, 2); - TEST_ASSERT_EQ_U(segs[0]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs[0], 1); TEST_ASSERT_EQ_I(segs[1]->len, 5); TEST_ASSERT_EQ_U(segs[1]->mmod, 0); TEST_ASSERT_EQ_I(segs[2]->len, 2); @@ -3695,7 +3955,7 @@ static test_result_t test_eval_insert_parted_e2e_impl(const char* root) { TEST_ASSERT_EQ_PTR(future_sym[0], live_sym[0]); TEST_ASSERT_EQ_PTR(future_sym[1], live_sym[1]); TEST_ASSERT_EQ_PTR(future_sym[2], live_sym[2]); - TEST_ASSERT_EQ_U(future_sym[0]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(future_sym[0], 1); TEST_ASSERT_EQ_U(future_sym[1]->mmod, 0); TEST_ASSERT_EQ_U(future_sym[2]->mmod, 0); TEST_ASSERT_EQ_U(future_sym[3]->mmod, 0); @@ -3755,8 +4015,8 @@ static test_result_t test_eval_insert_parted_e2e_impl(const char* root) { ray_t* cold_id = lang_parted_insert_col(cold, "id"); TEST_ASSERT_NOT_NULL(cold_id); ray_t** cold_id_segs = (ray_t**)ray_data(cold_id); - TEST_ASSERT_EQ_U(cold_id_segs[0]->mmod, 1); - TEST_ASSERT_EQ_U(cold_id_segs[1]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(cold_id_segs[0], 1); + TEST_ASSERT_LOADED_MMOD(cold_id_segs[1], 1); ray_release(cold); ray_release(future); @@ -3872,8 +4132,8 @@ static test_result_t test_eval_insert_parted_rollover_impl(const char* root) { TEST_ASSERT_EQ_PTR(ray_sym_vec_domain(live_ticker[pidx]), live_dom); TEST_ASSERT_EQ_PTR(ray_sym_vec_domain(live_venue[pidx]), live_dom); } - TEST_ASSERT_EQ_U(live_ticker[0]->mmod, 1); - TEST_ASSERT_EQ_U(live_venue[0]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(live_ticker[0], 1); + TEST_ASSERT_LOADED_MMOD(live_venue[0], 1); for (int64_t pidx = 1; pidx < 3; pidx++) { TEST_ASSERT_EQ_U(live_ticker[pidx]->mmod, 0); TEST_ASSERT_EQ_U(live_venue[pidx]->mmod, 0); @@ -3955,8 +4215,8 @@ static test_result_t test_eval_insert_parted_rollover_impl(const char* root) { for (int64_t pidx = 0; pidx < 3; pidx++) { TEST_ASSERT_EQ_PTR(ray_sym_vec_domain(cold_ticker[pidx]), cold_dom); TEST_ASSERT_EQ_PTR(ray_sym_vec_domain(cold_venue[pidx]), cold_dom); - TEST_ASSERT_EQ_U(cold_ticker[pidx]->mmod, 1); - TEST_ASSERT_EQ_U(cold_venue[pidx]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(cold_ticker[pidx], 1); + TEST_ASSERT_LOADED_MMOD(cold_venue[pidx], 1); } TEST_ASSERT_EQ_I(ray_sym_domain_count(cold_dom), disk_syms_persisted); TEST_ASSERT_EQ_I(ray_sym_domain_find(cold_dom, "omni", 4), omni_pos); @@ -3981,7 +4241,7 @@ static test_result_t test_eval_insert_parted_rollover_impl(const char* root) { ray_t* cold_id_col = lang_parted_insert_col(cold, "id"); TEST_ASSERT_NOT_NULL(cold_id_col); ray_t** cold_id = (ray_t**)ray_data(cold_id_col); - TEST_ASSERT_EQ_U(cold_id[2]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(cold_id[2], 1); TEST_ASSERT_EQ_I(((int64_t*)ray_data(cold_id[2]))[0], 7); TEST_ASSERT_EQ_I(((int64_t*)ray_data(cold_id[2]))[1], 8); @@ -4153,8 +4413,8 @@ static test_result_t test_eval_insert_parted_errors_impl(const char* root) { ray_t** segs = (ray_t**)ray_data(col); TEST_ASSERT_EQ_I(segs[0]->len, 2); TEST_ASSERT_EQ_I(segs[1]->len, 2); - TEST_ASSERT_EQ_U(segs[0]->mmod, 1); - TEST_ASSERT_EQ_U(segs[1]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs[0], 1); + TEST_ASSERT_LOADED_MMOD(segs[1], 1); } char day3[1200]; @@ -4386,8 +4646,8 @@ static test_result_t test_eval_insert_parted_physical_types_impl( historical[i] = segs[0]; TEST_ASSERT_EQ_I(segs[0]->len, 1); TEST_ASSERT_EQ_I(segs[1]->len, 1); - TEST_ASSERT_EQ_U(segs[0]->mmod, 1); - TEST_ASSERT_EQ_U(segs[1]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs[0], 1); + TEST_ASSERT_LOADED_MMOD(segs[1], 1); } /* A fully validated exact-schema zero-vector batch is pointer-identical @@ -4433,7 +4693,7 @@ static test_result_t test_eval_insert_parted_physical_types_impl( lang_parted_wide_types[i]); ray_t** segs = (ray_t**)ray_data(wrapper); TEST_ASSERT_EQ_PTR(segs[0], historical[i]); - TEST_ASSERT_EQ_U(segs[0]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs[0], 1); TEST_ASSERT_EQ_I(segs[0]->len, 1); TEST_ASSERT_EQ_I(segs[1]->type, lang_parted_wide_types[i]); TEST_ASSERT_EQ_I(segs[1]->len, 3); @@ -5077,10 +5337,10 @@ static test_result_t test_sort_embedded_nul(void) { static test_result_t test_eval_read_write_csv(void) { /* Create a table, write it to CSV, read it back */ ray_t* result = ray_eval_str( - "(do (set t (table ['a 'b] (list [1 2 3] [10 20 30]))) " + ray_test_tmp("(do (set t (table ['a 'b] (list [1 2 3] [10 20 30]))) " "(.csv.write t \"/tmp/test_rayfall.csv\") " "(set t2 (.csv.read \"/tmp/test_rayfall.csv\")) " - "(count t2))"); + "(count t2))")); TEST_ASSERT_NOT_NULL(result); TEST_ASSERT_FALSE(RAY_IS_ERR(result)); TEST_ASSERT_EQ_I(result->type, -RAY_I64); @@ -5502,6 +5762,40 @@ static test_result_t test_dotted_missing_key(void) { PASS(); } +/* A dotted read looks the whole name up flat before it walks the dicts, and + * the global table answers that lookup from a filter of the names it has + * ever held. A dotted name bound flat must still win over the walk, from + * the top level and from compiled code, and the walk must take over again + * once the flat slot is deleted. */ +static test_result_t test_dotted_flat_binding_wins(void) { + ray_eval_str("(set __fb.k 1)"); + ray_eval_str("(set __fb_read (fn [] __fb.k))"); + ASSERT_EQ("__fb.k", "1"); + ASSERT_EQ("(__fb_read)", "1"); + + static const char name[] = "__fb.k"; + int64_t id = ray_sym_intern(name, sizeof(name) - 1); + TEST_ASSERT_TRUE(ray_sym_is_dotted(id)); + ray_t* two = ray_i64(2); + TEST_ASSERT_EQ_I(ray_env_bind_flat(id, two), RAY_OK); + ray_release(two); + ASSERT_EQ("__fb.k", "2"); + ASSERT_EQ("(__fb_read)", "2"); + + TEST_ASSERT_EQ_I(ray_env_bind_flat(id, NULL), RAY_OK); + ASSERT_EQ("__fb.k", "1"); + ASSERT_EQ("(__fb_read)", "1"); + + /* Many globals, then reads that never had a flat slot. */ + ray_eval_str("(set __fb_many (fn [n] (times [i n] (set __fb.k i))))"); + ray_eval_str("(__fb_many 300)"); + ASSERT_EQ("(__fb_read)", "299"); + ray_t* r = ray_eval_str("__fb.missing"); + TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + ray_error_free(r); + PASS(); +} + static test_result_t test_dotted_del_removes_key(void) { ray_eval_str("(set __dns.x 5)"); ray_eval_str("(set __dns.y 10)"); @@ -9133,6 +9427,89 @@ static test_result_t test_builtin_enlist_fn(void) { PASS(); } +/* Mixed enlist promotion is only defined for I64/F64 atoms. Check every + * argument position and ordering, including values whose payload resembles + * an integer but whose logical type must be preserved. */ +static test_result_t test_builtin_enlist_mixed_atoms(void) { + const uint8_t guid[16] = {1, 2, 3, 4}; + const int64_t nested[] = {-2, 3}; + ray_t* other[] = { + ray_i32(-1), ray_i16(-1), ray_u8(255), ray_f32(1.25f), + ray_bool(true), ray_date(8766), ray_time(1234), + ray_timestamp(1234), ray_timespan(1234), + ray_sym(ray_sym_intern("enlist_guard", 12)), ray_str("s", 1), + ray_guid(guid), ray_typed_null(-RAY_I32), + ray_vec_from_raw(RAY_I64, nested, 2) + }; + static const uint8_t order[][3] = { + {0, 1, 2}, {0, 2, 1}, {1, 0, 2}, + {1, 2, 0}, {2, 0, 1}, {2, 1, 0} + }; + ray_t* integer = ray_i64(2); + ray_t* floating = ray_f64(1.5); + bool preserved = true; + for (size_t k = 0; k < sizeof(other) / sizeof(other[0]); k++) { + ray_t* values[] = {integer, floating, other[k]}; + for (size_t j = 0; j < sizeof(order) / sizeof(order[0]); j++) { + ray_t* args[] = {values[order[j][0]], values[order[j][1]], + values[order[j][2]]}; + ray_t* r = ray_enlist_fn(args, 3); + if (!r || RAY_IS_ERR(r)) { + preserved = false; + if (r) ray_error_free(r); + continue; + } + if (r->type != RAY_LIST || r->len != 3) { + preserved = false; + } else { + ray_t** cells = (ray_t**)ray_data(r); + for (int i = 0; i < 3; i++) + if (cells[i] != args[i]) preserved = false; + } + ray_release(r); + } + } + for (size_t k = 0; k < sizeof(other) / sizeof(other[0]); k++) + ray_release(other[k]); + ray_release(integer); + ray_release(floating); + TEST_ASSERT_TRUE(preserved); + PASS(); +} + +static test_result_t test_builtin_enlist_promotion_payload(void) { + ray_t* values[] = {ray_i64(5), ray_f64(2.5), ray_f64(-3.0)}; + ray_t* null_value = ray_typed_null(-RAY_I64); + const double expected[] = {5.0, 2.5, -3.0}; + bool correct = true; + for (int null_at = -1; null_at < 3; null_at++) { + ray_t* args[] = {values[0], values[1], values[2]}; + if (null_at >= 0) args[null_at] = null_value; + ray_t* r = ray_enlist_fn(args, 3); + if (!r || RAY_IS_ERR(r)) { + correct = false; + if (r) ray_error_free(r); + continue; + } + if (r->type != RAY_F64 || r->len != 3) { + correct = false; + } else { + const double* data = (const double*)ray_data(r); + if (!!(r->attrs & RAY_ATTR_HAS_NULLS) != (null_at >= 0)) + correct = false; + for (int i = 0; i < 3; i++) { + if (!!ray_vec_is_null(r, i) != (i == null_at)) correct = false; + if (i != null_at && data[i] != expected[i]) correct = false; + } + } + ray_release(r); + } + for (int i = 0; i < 3; i++) ray_release(values[i]); + ray_release(null_value); + TEST_ASSERT_TRUE(correct); + PASS(); +} + /* ── builtins.c coverage: ray_resolve_fn ───────────────────────────────────── * ray_resolve_fn replaces I64 sym-ID columns with SYM columns in a table. * Call it with a plain I64 atom (non-table path: return as-is). */ @@ -9258,7 +9635,7 @@ static test_result_t test_select_releases_input_table(void) { static test_result_t test_select_derived_key_file_chunks(void) { ray_t* r = ray_eval_str( - "(do (set __dk_i (til 20000)) " + ray_test_tmp("(do (set __dk_i (til 20000)) " " (set __dk_hosts (map (fn [k] (format \"h%.example.com\" k)) (til 37))) " " (set __dk_mk (fn [k] ((fn [j] (if (== 0 (% j 11)) \"\" (if (== 0 (% j 7)) " " (format \"https://www.%/p/%\" (at __dk_hosts (% (* 31 j) 37)) (% j 13)) " @@ -9277,7 +9654,7 @@ static test_result_t test_select_derived_key_file_chunks(void) { " (if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref))))) " " ref: ref v: v where: (!= ref \"\")}) by: p c: (count ref) sv: (sum v) mn: (min ref)}))) " " (set __dk_fp (fn [r] (ser (xasc (xasc (table [k c sv mn] (list (at (value r) 0) (at r 'c) (at r 'sv) (at r 'mn))) 'mn) 'c)))) " - " (count (distinct (at __dk_F 'ref))))"); + " (count (distinct (at __dk_F 'ref))))")); TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); TEST_ASSERT_EQ_I(r->i64, 414); /* vocabulary of 414 values */ @@ -9293,7 +9670,7 @@ static test_result_t test_select_derived_key_file_chunks(void) { ray_derived_key_chunk_set_for_test(7); /* 60 chunks, the last one short */ ray_t* same7 = ray_eval_str("(all (== (__dk_fp (__dk_keyq __dk_F)) (__dk_fp __dk_r7)))"); ray_derived_key_chunk_set_for_test(0); - ray_t* cleanup = ray_eval_str("(.sys.exec \"rm -rf /tmp/rf_test_dk_chunks/\")"); + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_dk_chunks/\")")); ray_release(cleanup); TEST_ASSERT_NOT_NULL(same); @@ -9340,6 +9717,729 @@ static test_result_t test_select_derived_key_file_chunks(void) { PASS(); } +/* On a compressed (generation 2) column the derived-key grouping reads the + * key by range: it must answer as the row path does and leave the column's + * whole-column decode cache empty. */ +static test_result_t test_select_derived_key_gen2_no_decode(void) { + ray_t* r = ray_eval_str( + ray_test_tmp("(do (set __dg_i (til 70000)) " + " (set __dg_hosts (map (fn [k] (format \"h%.example.com\" k)) (til 37))) " + " (set __dg_mk (fn [k] ((fn [j] (if (== 0 (% j 11)) \"\" (if (== 0 (% j 7)) " + " (format \"https://www.%/p/%\" (at __dg_hosts (% (* 31 j) 37)) (% j 13)) " + " (format \"http://%/a/%\" (at __dg_hosts (% (* 31 j) 37)) (% j 17))))) (% k 500)))) " + " (set __dg_T (table [ref v] (list (as 'SYMBOL (map __dg_mk __dg_i)) (as 'F64 (% (* __dg_i 7) 101))))) " + " (.sys.exec \"rm -rf /tmp/rf_test_dk_gen2/; mkdir -p /tmp/rf_test_dk_gen2\") " + " (.db.splayed.set \"/tmp/rf_test_dk_gen2/t/\" __dg_T \"/tmp/rf_test_dk_gen2/t.sym\" {compress: true}) " + " (set __dg_F (.db.splayed.get \"/tmp/rf_test_dk_gen2/t/\" \"/tmp/rf_test_dk_gen2/t.sym\")) " + " (set __dg_key (fn [ref] (let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " + " (let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " + " (if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref))))))) " + " (set __dg_fp (fn [r] (ser (xasc (xasc (table [k c mn] (list (at (value r) 0) (at r 'c) (at r 'mn))) 'mn) 'c)))) " + " 0)")); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + + ray_t* F = ray_eval_str("__dg_F"); + TEST_ASSERT_NOT_NULL(F); TEST_ASSERT_FALSE(RAY_IS_ERR(F)); + ray_t* E = ray_table_get_col_enc(F, ray_sym_intern("ref", 3)); + TEST_ASSERT_NOT_NULL(E); /* the column is stored encoded */ + ray_enccol_t* e = ray_enccol_of(E); + TEST_ASSERT_NOT_NULL(e); + TEST_ASSERT_TRUE(e->decoded == NULL); + + ray_t* got = ray_eval_str("(do (set __dg_r (select {from: __dg_F by: (let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " + "(let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " + "(if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref))))) " + "c: (count ref) mn: (min ref) where: (!= ref \"\")})) (count __dg_r))"); + TEST_ASSERT_NOT_NULL(got); TEST_ASSERT_FALSE(RAY_IS_ERR(got)); + TEST_ASSERT_TRUE(got->i64 > 0); + ray_release(got); + bool undecoded = e->decoded == NULL; /* read before the oracle decodes it */ + + ray_t* same = ray_eval_str("(all (== (__dg_fp __dg_r) (__dg_fp (select {from: (select {from: __dg_T p: (__dg_key ref) " + "ref: ref where: (!= ref \"\")}) by: p c: (count ref) mn: (min ref)}))))"); + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_dk_gen2/\")")); + ray_release(cleanup); + TEST_ASSERT_TRUE(undecoded); + TEST_ASSERT_NOT_NULL(same); TEST_ASSERT_FALSE(RAY_IS_ERR(same)); + TEST_ASSERT_EQ_I(same->type, -RAY_BOOL); + TEST_ASSERT_TRUE(same->b8); + ray_release(same); + ray_release(F); + PASS(); +} + +/* A compressed (generation 2) column whose whole decode would not stay + * cached (ray_enccol_decode_kept, under a test budget: every column, or for + * the composite key, whose keys the row map reads decoded, the two 8-byte + * ones) is read by range by the computed keys and the count-distinct paths: + * a by-dict value over it is evaluated a range at a time (50 vectors: the + * ranges cross the 64 K-row chunks), a renamed one is grouped as its slot, a + * computed key beside a distinct output is evaluated by range, the global + * count distinct of its scan and the grouped count distincts are counted by + * the bounded kernel. Every query answers as over the plain table — nulls, + * SYM keys of three widths, empty results — and none leaves such a column + * decoded whole. */ +static test_result_t test_select_gen2_ranged_no_decode(void) { + ray_t* r = ray_eval_str( + ray_test_tmp("(do (set __gr_i (til 140000)) " + " (set __gr_h (% (* __gr_i 2654435761) 1000003)) " + " (set __gr_nz (at [0N 0 0 0 0 0 0] (% __gr_i 7))) " + " (set __gr_et (+ 2013.07.01D00:00:00.000000000 (+ (at [0 0 0 0 0 0 0 0 0 0 0 0 0N] (% __gr_i 13)) (* 1000000000 (% (* __gr_h 13) 86400))))) " + " (set __gr_u (+ __gr_nz (+ 1000000000 (% (+ (* __gr_h 7919) __gr_i) 9000)))) " + " (set __gr_r (as 'I32 (+ (at [0 0 0 0 0 0 0 0 0 0N] (% __gr_i 10)) (sqrt (as 'F64 (% (* __gr_h __gr_h) 2500)))))) " + " (set __gr_s8 (at (as 'SYMBOL (map (fn [k] (if (< k 3) \"\" (format \"m%\" k))) (til 40))) (% (* (% __gr_h 997) 3) 40))) " + " (set __gr_s16 (at (as 'SYMBOL (map (fn [k] (if (== k 0) \"\" (format \"p%\" k))) (til 3000))) (% (* (% (* __gr_h __gr_h) 1009) 13) 3000))) " + " (set __gr_s32 (as 'SYMBOL (map (fn [k] (format \"w%\" k)) (% __gr_h 70001)))) " + " (set __gr_T (table [u et r s8 s16 s32] (list __gr_u __gr_et __gr_r __gr_s8 __gr_s16 __gr_s32))) " + " (.sys.exec \"rm -rf /tmp/rf_test_gen2_ranged/\") " + " (.db.splayed.set \"/tmp/rf_test_gen2_ranged/t/\" __gr_T \"/tmp/rf_test_gen2_ranged/t.sym\" {compress: true}) " + " (set __gr_F (.db.splayed.get \"/tmp/rf_test_gen2_ranged/t/\" \"/tmp/rf_test_gen2_ranged/t.sym\")) " + " (set __gr_nv (fn [v] (if (== (type v) 'SYM) (as 'STR v) v))) " + " (set __gr_fp (fn [x] (if (== (type x) 'TABLE) (ser (xasc (table (cols x) (map (fn [c] (__gr_nv (at x c))) (cols x))) (cols x))) x))) " + " 0)")); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "setup: %s", ray_error_msg() ? ray_error_msg() : ""); + ray_release(r); + ray_t* F = ray_eval_str("__gr_F"); + TEST_ASSERT_NOT_NULL(F); TEST_ASSERT_FALSE(RAY_IS_ERR(F)); + static const char* const C[] = { "u", "et", "r", "s8", "s16", "s32" }; + enum { NC = sizeof C / sizeof C[0] }; + ray_t* E[NC]; + for (int c = 0; c < NC; c++) { + E[c] = ray_table_get_col_enc(F, ray_sym_intern(C[c], strlen(C[c]))); + TEST_ASSERT_FMT(E[c] != NULL, "column %s is not stored encoded", C[c]); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(E[c])); + } + static const struct { const char* q; int64_t kept; } Q[] = { +#define GR_ALL 1 + { "(select {from: %s by: {u: u m: (minute et) s: s16} c: (count u)})", GR_ALL }, + { "(select {from: %s by: {m: (minute et) s: s8} c: (count u)})", GR_ALL }, + { "(select {from: %s by: {s: s32 h: (+ (hour et) r)} c: (count u)})", GR_ALL }, + { "(select {from: %s by: (minute et) d: (count (distinct u))})", GR_ALL }, + { "(count (distinct (at %s 'u)))", GR_ALL }, + { "(count (distinct (at %s 'r)))", GR_ALL }, + { "(count (distinct (at %s 's16)))", GR_ALL }, + { "(count (distinct (at %s 's32)))", GR_ALL }, + { "(select {from: %s by: r d: (count (distinct u))})", GR_ALL }, + { "(select {from: %s by: r c: (count u) a: (avg u) d: (count (distinct u))})", GR_ALL }, + { "(select {from: %s by: s8 d: (count (distinct u)) where: (!= s8 \"\")})", GR_ALL }, + { "(select {from: %s by: s16 d: (count (distinct u)) where: (!= s16 \"\")})", GR_ALL }, + { "(select {from: %s by: r d: (count (distinct u)) where: (< u -5)})", GR_ALL }, + { "(select {from: %s by: {u: u m: (minute et)} c: (count u) where: (< u -5)})", GR_ALL }, + { "(select {from: %s by: [r s8] d: (count (distinct u)) where: (!= s8 \"\")})", 600000 }, + { "(select {from: %s by: [r s8] d: (count (distinct u))})", 600000 }, +#undef GR_ALL + }; + ray_key_range_rows_set_for_test(50 * RAY_MORSEL_ELEMS); + const char* why = NULL; + size_t at = 0; + int64_t wm = ray_heap_anon_watermark(); + for (; at < sizeof Q / sizeof Q[0] && !why; at++) { + ray_heap_set_anon_watermark(1); /* no decode kept from the query before */ + ray_enccol_cache_trim(); + ray_heap_set_anon_watermark(wm); + ray_enccol_test_kept_limit(Q[at].kept); + char qf[1024], qt[1024], q[2600]; + snprintf(qf, sizeof qf, Q[at].q, "__gr_F"); + snprintf(qt, sizeof qt, Q[at].q, "__gr_T"); + snprintf(q, sizeof q, "(do (set __gr_a (__gr_fp %s)) (set __gr_b (__gr_fp %s)) (if (== (count __gr_a) (count __gr_b)) (all (== __gr_a __gr_b)) false))", qf, qt); + ray_t* same = ray_eval_str(q); + if (!same || RAY_IS_ERR(same)) why = "error"; + else if (same->type != -RAY_BOOL || !same->b8) why = "answers differ"; + if (same) ray_release(same); + for (int c = 0; c < NC && !why; c++) + if (!ray_enccol_decode_kept(E[c]) && ray_enccol_decoded_peek(E[c])) why = C[c]; + } + ray_key_range_rows_set_for_test(0); + ray_enccol_test_kept_limit(0); + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_gen2_ranged/\")")); + ray_release(cleanup); + ray_release(F); + TEST_ASSERT_FMT(!why, "query %zu %s: %s", at - 1, Q[at - 1].q, why ? why : ""); + PASS(); +} + +/* ---- The exact top-N-by-count grouping (ops/query.c select_topk_hh) ---- + * 200 K rows over 110 K groups: thirteen heavy ones (800-900 rows, four tied + * at 850 and two at 820, so a cut of 4, 6 or 10 falls inside a tie), the + * rest of one or two rows; u a wide I64 with null keys, et a timestamp with + * nulls (a null minute), s a 3000-symbol column with empty (null) symbols, + * s8 / x narrow keys a dense plan takes, v a count input with nulls. The + * rows are permuted so first rows are spread. __tk_eq: the same columns, + * the same values in the same order (symbols as text). */ +static const char* const TK_SETUP = + "(do (set __tk_n 200000) (set __tk_i (til __tk_n)) " + " (set __tk_o (% (* __tk_i 7919) __tk_n)) " + " (set __tk_hc [900 880 860 850 850 850 850 840 830 820 820 810 805]) " + " (set __tk_H (sum __tk_hc)) " + " (set __tk_isH (as 'I64 (< __tk_o __tk_H))) " + " (set __tk_g (+ (* __tk_isH (bin (- (sums __tk_hc) __tk_hc) __tk_o)) " + " (* (- 1 __tk_isH) (+ 1000 (% (* (- __tk_o __tk_H) 13) 110000))))) " + " (set __tk_nul (fn [x m] (at (concat x [0N]) (+ __tk_i (* m (- __tk_n __tk_i)))))) " + " (set __tk_u (__tk_nul (+ 400000000000000000 (* (div __tk_g 3) 1000003)) (as 'I64 (== (% __tk_g 7) 3)))) " + " (set __tk_et (+ 2013.07.01D00:00:00.000000000 (+ (* 60000000000 (__tk_nul (% __tk_g 1440) " + " (as 'I64 (== (% __tk_g 11) 7)))) (* 1000000000 (% __tk_i 60))))) " + " (set __tk_s (at (as 'SYMBOL (map (fn [k] (if (< k 300) \"\" (format \"p%\" k))) (til 3000))) (% __tk_g 3000))) " + " (set __tk_s8 (at (as 'SYMBOL (map (fn [k] (format \"m%\" k)) (til 40))) (% __tk_g 40))) " + " (set __tk_x (as 'I32 (% __tk_g 50))) " + " (set __tk_v (__tk_nul __tk_i (as 'I64 (== (% __tk_i 5) 0)))) " + " (set __tk_T (table [u et s s8 x v] (list __tk_u __tk_et __tk_s __tk_s8 __tk_x __tk_v))) " + " (set __tk_nv (fn [v] (if (== (type v) 'SYM) (as 'STR v) v))) " + " (set __tk_eq (fn [A B] (and (== (count A) (count B)) (== (count (cols A)) (count (cols B))) " + " (all (== (cols A) (cols B))) " + " (all (map (fn [c] (all (== (ser (__tk_nv (at A c))) (ser (__tk_nv (at B c)))))) (cols A)))))) " + " 0)"; + +/* Query q answered with the path armed (from 1000 rows) and with it off: + * NULL when both give the same table, else why; *route the path's route + * (0: the path did not run). */ +static const char* tk_compare(const char* q, int64_t* route) { + char e[2048]; + int64_t s0[10], s1[10]; + ray_group_topk_stats_for_test(s0); + ray_group_topk_min_rows_set_for_test(1000); + snprintf(e, sizeof e, "(set __tk_a %s)", q); + ray_t* a = ray_eval_str(e); + ray_group_topk_stats_for_test(s1); + ray_group_topk_min_rows_set_for_test(INT64_MAX); + snprintf(e, sizeof e, "(set __tk_b %s)", q); + ray_t* b = ray_eval_str(e); + ray_group_topk_min_rows_set_for_test(0); + *route = s1[0] + s1[1] + s1[2] + s1[8] != s0[0] + s0[1] + s0[2] + s0[8] ? s1[3] : 0; + const char* why = NULL; + if (!a || RAY_IS_ERR(a) || !b || RAY_IS_ERR(b)) why = "error"; + if (a) ray_release(a); + if (b) ray_release(b); + if (!why) { + ray_t* same = ray_eval_str("(and (> (count __tk_a) 0) (__tk_eq __tk_a __tk_b))"); + if (!same || RAY_IS_ERR(same) || same->type != -RAY_BOOL || !same->b8) why = "answers differ"; + if (same) ray_release(same); + } + return why; +} + +/* The top groups by count, taken in two passes, are the grouping's cut — + * keys, counts, which tied groups are kept at the N-th count and their + * order (first row) — over the table in memory, splayed plain and splayed + * compressed (generation 2: read by range), with null keys, a computed + * key (minute over a timestamp with nulls, integer arithmetic), several + * count outputs, the output written before the clauses; ranges of 64 K + * rows, so the passes run on the pool over several ranges. Narrow keys a + * dense plan would take (key order, not first rows) are left to it. */ +static test_result_t test_select_topk_count_exact(void) { + ray_t* r = ray_eval_str(TK_SETUP); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "setup: %s", ray_error_msg() ? ray_error_msg() : ""); + ray_release(r); + r = ray_eval_str(ray_test_tmp("(do (.sys.exec \"rm -rf /tmp/rf_test_topk/\") " + " (.db.splayed.set \"/tmp/rf_test_topk/p/\" __tk_T \"/tmp/rf_test_topk/p.sym\" {compress: false}) " + " (.db.splayed.set \"/tmp/rf_test_topk/c/\" __tk_T \"/tmp/rf_test_topk/c.sym\" {compress: true}) " + " (set __tk_P (.db.splayed.get \"/tmp/rf_test_topk/p/\" \"/tmp/rf_test_topk/p.sym\")) " + " (set __tk_C (.db.splayed.get \"/tmp/rf_test_topk/c/\" \"/tmp/rf_test_topk/c.sym\")) " + " (at (.idx.info __tk_C 'u) 'gen))")); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "save: %s", ray_error_msg() ? ray_error_msg() : ""); + TEST_ASSERT_EQ_I(r->i64, 2); + ray_release(r); + static const struct { const char* q; int route; } Q[] = { + { "(select {from: %s by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 4})", 1 }, + { "(select {from: %s by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 6})", 1 }, + { "(select {from: %s by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 10})", 1 }, + { "(select {from: %s by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 1})", 1 }, + { "(select {from: %s by: u c: (count u) desc: c take: 6})", 1 }, + { "(select {from: %s by: [u s] c: (count v) d: (count u) desc: d take: 4})", 1 }, + { "(select {from: %s by: {k: (- u 7) s: s} c: (count s) desc: c take: 5})", 1 }, + { "(select {from: %s by: {k: (+ (div u 1000003) 1) s: s} c: (count s) desc: c take: 5})", 3 }, + { "(select {c: (count u) from: %s by: [s u] desc: c take: 3})", 1 }, + { "(select {from: %s by: {w: u m: (minute et)} n: (count et) desc: n take: 12})", 1 }, + { "(select {from: %s by: [x s8] c: (count u) desc: c take: 5})", 3 }, + { "(select {from: %s by: x c: (count u) desc: c take: 5})", 3 }, + { "(select {from: %s by: s8 c: (count u) desc: c take: 5})", 3 }, + { "(select {from: %s by: [u s] c: (count u) take: 5})", 0 }, + { "(select {from: %s by: [u s] c: (count u) asc: c take: 5})", 0 }, + }; + static const char* const TB[] = { "__tk_T", "__tk_P", "__tk_C" }; + ray_key_range_rows_set_for_test(64 * RAY_MORSEL_ELEMS); + ray_group_topk_mem_gate_set_for_test(1); /* past the budget: the path runs */ + const char* why = NULL; + size_t at = 0, tb = 0; + int64_t route = 0; + for (; at < sizeof Q / sizeof Q[0] && !why; at++) + for (tb = 0; tb < (Q[at].route == 1 ? 3u : 1u) && !why; tb++) { /* the others over memory */ + char q[1024]; + snprintf(q, sizeof q, Q[at].q, TB[tb]); + why = tk_compare(q, &route); + if (!why && route != Q[at].route) why = "route"; + } + ray_key_range_rows_set_for_test(0); + ray_group_topk_mem_gate_set_for_test(0); + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_topk/\")")); + ray_release(cleanup); + TEST_ASSERT_FMT(!why, "query %zu over %s: %s (route %lld)", at - 1, TB[tb - 1], why ? why : "", (long long)route); + PASS(); +} + +/* The guards of the two-pass path: fewer groups than the take (every group + * found: E = 0), every group tied (2000 groups of 100 rows: all candidates, + * answered; 100 K groups of 2 rows: the grouping answers), the check + * failing (four counters a worker, one + * range: T <= E, the grouping answers — the candidates alone would miss the + * heavy groups), near-unique keys (pass A stops at an eighth of the rows), + * and a hash cut to 3 bits: eight hash values hold every key, so pass B + * separates the 2600 groups under them by their key values; cut to 5 bits, + * the candidate cut drops hashes holding heavy groups and E_eff sends the + * query to the grouping. */ +static test_result_t test_select_topk_count_guards(void) { + ray_t* r = ray_eval_str(TK_SETUP); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "setup: %s", ray_error_msg() ? ray_error_msg() : ""); + ray_release(r); + r = ray_eval_str( + "(do (set __tk_F (table [u] (list (+ 400000000000000000 (* 1000000007 (% (div __tk_i 7) 5)))))) " + " (set __tk_A2 (table [u w] (list (+ 400000000000000000 (* 1000003 (% (* __tk_i 7919) 2000))) (% __tk_i 3)))) " + " (set __tk_A3 (table [u w] (list (+ 400000000000000000 (* 1000003 (% (* __tk_i 7919) 100000))) (% __tk_i 3)))) " + " (set __tk_U (table [a b] (list (* __tk_i 1000003) (as 'I32 (% (* __tk_i 2654435761) 2147483629))))) " + " (set __tk_W (table [u s] (list (+ 400000000000000000 (* 1000003 (% __tk_g 2600))) " + " (at (as 'SYMBOL (map (fn [k] (format \"w%\" k)) (til 40))) (% (% __tk_g 2600) 40))))) " + " 0)"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + static const struct { const char* q; int64_t range, counters; int bits; int route; } Q[] = { + { "(select {from: __tk_F by: u c: (count u) desc: c take: 10})", 64, 0, 0, 1 }, + { "(select {from: __tk_A2 by: u c: (count w) desc: c take: 10})", 64, 0, 0, 1 }, + { "(select {from: __tk_A3 by: u c: (count w) desc: c take: 10})", 256, 0, 0, 2 }, + { "(select {from: __tk_T by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 10})", 256, 4, 0, 2 }, + { "(select {from: __tk_T by: u c: (count u) desc: c take: 3})", 256, 4, 0, 2 }, + { "(select {from: __tk_U by: [a b] c: (count a) desc: c take: 10})", 64, 0, 0, 4 }, + { "(select {from: __tk_W by: [u s] c: (count u) desc: c take: 10})", 64, 0, 3, 1 }, + { "(select {from: __tk_W by: [u s] c: (count u) desc: c take: 10})", 64, 0, 5, 2 }, + { "(select {from: __tk_W by: {s: s u: u} c: (count s) desc: c take: 12})", 64, 0, 3, 1 }, + }; + const char* why = NULL; + size_t at = 0; + int64_t route = 0, st[10] = {0}; + bool merged = true; + ray_group_topk_mem_gate_set_for_test(1); /* past the budget: the path runs */ + for (; at < sizeof Q / sizeof Q[0] && !why; at++) { + ray_key_range_rows_set_for_test(Q[at].range * RAY_MORSEL_ELEMS); + ray_group_topk_counters_set_for_test(Q[at].counters); + ray_group_topk_hash_bits_set_for_test(Q[at].bits); + why = tk_compare(Q[at].q, &route); + ray_group_topk_stats_for_test(st); + if (!why && route != Q[at].route) why = "route"; + if (!why && Q[at].bits == 3) merged &= st[7] > st[6] && st[6] <= 8; + } + ray_key_range_rows_set_for_test(0); + ray_group_topk_counters_set_for_test(0); + ray_group_topk_hash_bits_set_for_test(0); + ray_group_topk_mem_gate_set_for_test(0); + TEST_ASSERT_FMT(!why, "query %zu %s: %s (route %lld)", at - 1, Q[at - 1].q, why ? why : "", (long long)route); + TEST_ASSERT_TRUE(merged); /* keys under one hash, told apart */ + r = ray_eval_str("(count __tk_a)"); /* the last answer: the 2600 groups' top 12 */ + TEST_ASSERT_EQ_I(r->i64, 12); + ray_release(r); + r = ray_eval_str("(count (select {from: __tk_F by: u c: (count u) desc: c take: 10}))"); + TEST_ASSERT_EQ_I(r->i64, 5); + ray_release(r); + + /* the pass B tables within their budget: 2000 candidates of one key + * (32-byte slots) fit 4 MB over the workers and are answered, with one + * table at most a worker's share; under 64 KB a worker could not hold + * them and the grouping answers, pass B not run */ + ray_pool_t* pool = ray_pool_get(); + int64_t W = pool ? (int64_t)ray_pool_total_workers(pool) : 1; + static const struct { int64_t budget; int route; } XB[] = { { (int64_t)4 << 20, 1 }, { (int64_t)64 << 10, 2 } }; + int64_t xb[2] = {0}; + ray_group_topk_mem_gate_set_for_test(1); + ray_key_range_rows_set_for_test(64 * RAY_MORSEL_ELEMS); + for (at = 0; at < 2 && !why; at++) { + ray_group_topk_ex_budget_set_for_test(XB[at].budget); + why = tk_compare("(select {from: __tk_A2 by: u c: (count w) desc: c take: 10})", &route); + ray_group_topk_stats_for_test(st); + xb[at] = st[9]; + if (!why && route != XB[at].route) why = "route"; + } + ray_group_topk_ex_budget_set_for_test(0); + + /* a by-dict name of an input column other than {x: x} is the grouping's + * error ("alias shadows"), so the path does not take it: the same error + * either way, the path not run */ + static const char* const SH[] = { + "(select {from: __tk_T by: {u: s} c: (count v) desc: c take: 3})", + "(select {from: __tk_T by: {u: (- u 1) m: (minute et)} c: (count v) desc: c take: 3})", + }; + int64_t runs0[10], runs1[10]; + ray_group_topk_stats_for_test(runs0); + ray_group_topk_min_rows_set_for_test(1000); + bool shadow_err = true; + for (size_t i = 0; i < 2; i++) { + ray_t* e = ray_eval_str(SH[i]); + shadow_err &= e && RAY_IS_ERR(e); + if (e) ray_release(e); + } + ray_group_topk_stats_for_test(runs1); + ray_group_topk_min_rows_set_for_test(0); + ray_group_topk_mem_gate_set_for_test(0); + ray_key_range_rows_set_for_test(0); + TEST_ASSERT_FMT(!why, "pass B budget %zu: %s (route %lld)", at - 1, why ? why : "", (long long)route); + TEST_ASSERT_TRUE(xb[0] > 0 && xb[0] * W <= XB[0].budget); + TEST_ASSERT_EQ_I(xb[1], 0); + TEST_ASSERT_TRUE(shadow_err); + TEST_ASSERT_EQ_I(runs1[0] + runs1[1] + runs1[2] + runs1[8], runs0[0] + runs0[1] + runs0[2] + runs0[8]); + PASS(); +} + +/* The memory gate: the two passes run only when the grouping would outgrow + * the memory budget (ray_heap_mem_budget). 200 K rows of an 8-byte key, a + * computed one and a 2-byte symbol plus the count, 26 bytes each, are a + * grouping of about 5 MB: a 64 GB budget leaves it to the grouping (route + * 5), a 16 MB one, under four times that, takes the two passes (route 1); + * both answer as the grouping. */ +static test_result_t test_select_topk_count_mem_gate(void) { + ray_t* r = ray_eval_str(TK_SETUP); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FMT(!RAY_IS_ERR(r), "setup: %s", ray_error_msg() ? ray_error_msg() : ""); + ray_release(r); + static const struct { int64_t budget; int route; } B[] = { + { (int64_t)64 << 30, 5 }, + { (int64_t)16 << 20, 1 }, + { (int64_t)64 << 30, 5 }, + }; + const char* q = "(select {from: __tk_T by: {u: u m: (minute et) s: s} c: (count u) desc: c take: 6})"; + int64_t prev = ray_heap_mem_budget() != ray_sys_ram_limit() ? ray_heap_mem_budget() : 0; + ray_key_range_rows_set_for_test(64 * RAY_MORSEL_ELEMS); + const char* why = NULL; + size_t at = 0; + int64_t route = 0; + for (; at < sizeof B / sizeof B[0] && !why; at++) { + ray_heap_set_anon_watermark(B[at].budget); + why = tk_compare(q, &route); + if (!why && route != B[at].route) why = "route"; + } + ray_heap_set_anon_watermark(prev); + ray_key_range_rows_set_for_test(0); + TEST_ASSERT_FMT(!why, "budget %zu: %s (route %lld)", at - 1, why ? why : "", (long long)route); + PASS(); +} + +/* The two-pass grouping with every key empty stores no key bytes: it answers + * as the unarmed grouping cut afterwards (a sanitizer build checks the + * pointer arithmetic over the empty key store). */ +static test_result_t test_select_derived_key_two_pass_empty_keys(void) { + ray_t* r = ray_eval_str( + "(do (set __de_T (table [ref] (list (as 'SYMBOL (map (fn [j] (format \"s%\" (% j 300))) (til 90000)))))) " + " (set __de_in (select {from: __de_T by: (substr ref 20 5) c: (count ref)})) " + " (set __de_a (select {from: (select {from: __de_T by: (substr ref 20 5) c: (count ref)}) where: (> c 100)})) " + " (all (== (ser __de_a) (ser (select {from: __de_in where: (> c 100)})))))"); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->type, -RAY_BOOL); + TEST_ASSERT_TRUE(r->b8); + ray_release(r); + PASS(); +} + +/* A filter that reads only the grouped column runs over its distinct values + * after the grouping: every form answers as the same grouping of the table + * filtered first, and one that reads another column keeps the row filter. */ +static test_result_t test_select_derived_key_where_on_values(void) { + ray_t* r = ray_eval_str( + ray_test_tmp("(do (set __dw_i (til 70000)) " + " (set __dw_hosts (map (fn [k] (format \"h%.example.com\" k)) (til 37))) " + " (set __dw_mk (fn [k] ((fn [j] (if (== 0 (% j 6)) \"\" (if (== 0 (% j 7)) " + " (format \"https://www.%/p/%\" (at __dw_hosts (% (* 31 j) 37)) (% j 13)) " + " (if (== 0 (% j 5)) (at __dw_hosts (% (* 31 j) 37)) " + " (format \"http://%/a/%\" (at __dw_hosts (% (* 31 j) 37)) (% j 17)))))) (% k 500)))) " + " (set __dw_T (table [ref v] (list (as 'SYMBOL (map __dw_mk __dw_i)) (% (* __dw_i 7) 101)))) " + " (.sys.exec \"rm -rf /tmp/rf_test_dk_where/\") " + " (.db.splayed.set \"/tmp/rf_test_dk_where/t/\" __dw_T \"/tmp/rf_test_dk_where/t.sym\" {compress: true}) " + " (set __dw_F (.db.splayed.get \"/tmp/rf_test_dk_where/t/\" \"/tmp/rf_test_dk_where/t.sym\")) " + " (set __dw_fp (fn [r] (ser (xasc (xasc (table [k c l mn] (list (at (value r) 0) (at r 'c) (at r 'l) (at r 'mn))) 'mn) 'c)))) " + " 0)")); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); ray_release(r); + static const char* const W[] = { + "(!= ref \"\")", + "(like ref \"http*\")", + "(not (nil? ref))", + "(and (!= ref \"\") (> (strlen ref) 24))", + "(nil? ref)", + "(> v 50)", + }; + for (size_t w = 0; w < sizeof(W) / sizeof(W[0]); w++) { + char q[4096]; + const char* key = "(let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " + "(let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " + "(if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref)))))"; + snprintf(q, sizeof q, + "(all (== (__dw_fp (select {from: __dw_F by: %s c: (count ref) l: (avg (strlen ref)) mn: (min ref) where: %s})) " + "(__dw_fp (select {from: (select {from: __dw_T ref: ref v: v where: %s}) by: %s c: (count ref) l: (avg (strlen ref)) mn: (min ref)}))))", + key, W[w], W[w], key); + ray_t* same = ray_eval_str(q); + TEST_ASSERT_NOT_NULL(same); + TEST_ASSERT_FMT(!RAY_IS_ERR(same), "filter %s: error", W[w]); + TEST_ASSERT_FMT(same->type == -RAY_BOOL && same->b8, "filter %s: answers differ", W[w]); + ray_release(same); + } + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_dk_where/\")")); + ray_release(cleanup); + PASS(); +} + +/* The derived-key grouping keys on a 64-bit hash of the key and compares + * the bytes on every hash match. With the hash cut to two bits (four + * values over hundreds of keys) every group shares its hash with dozens of + * others: each answer must still be exactly the full-hash one — the + * per-value aggregates (count, avg/sum of strlen, min/max), the having cut + * an enclosing where arms, and the per-row key of a grouping that also + * reads another column — and agree with the row path. */ +static test_result_t test_select_derived_key_hash_collisions(void) { + ray_t* r = ray_eval_str( + ray_test_tmp("(do (set __dh_i (til 80000)) " + " (set __dh_hosts (map (fn [k] (format \"h%.example.com\" k)) (til 37))) " + " (set __dh_mk (fn [k] ((fn [j] (if (== 0 (% j 11)) \"\" (if (== 0 (% j 7)) " + " (format \"https://www.%/p/%\" (at __dh_hosts (% (* 31 j) 37)) (% j 13)) " + " (if (== 0 (% j 5)) (format \"plain%.x\" j) " + " (format \"http://%/a/%\" (at __dh_hosts (% (* 31 j) 37)) (% j 17)))))) (% (* k 7919) 3000)))) " + " (set __dh_T (table [ref v] (list (as 'SYMBOL (map __dh_mk __dh_i)) (% __dh_i 101)))) " + " (.sys.exec \"rm -rf /tmp/rf_test_dh/\") " + " (.db.splayed.set \"/tmp/rf_test_dh/\" __dh_T) " + " (set __dh_F (.db.splayed.get \"/tmp/rf_test_dh/\")) " + " (set __dh_q1 (fn [t] (select {from: t by: (let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " + " (let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " + " (if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref))))) " + " c: (count ref) l: (avg (strlen ref)) mn: (min ref) mx: (max ref) sl: (sum (strlen ref)) where: (!= ref \"\")}))) " + " (set __dh_o1 (fn [t] (select {from: t by: (let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " + " (let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " + " (if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref))))) " + " c: (count ref) l: (avg (strlen ref)) mn: (min ref) mx: (max ref) sl: (sum (strlen ref)) sv: (sum v) where: (!= ref \"\")}))) " + " (set __dh_q2 (fn [t] (select {from: t by: (substr ref 1 9) c: (count ref) l: (avg (strlen ref)) mn: (min ref) mx: (max ref)}))) " + " (set __dh_q3 (fn [t] (select {from: (select {from: t by: (let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " + " (let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " + " (if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref))))) " + " l: (avg (strlen ref)) c: (count ref) mn: (min ref) where: (!= ref \"\")}) where: (> c 900) desc: l})) ) " + " (set __dh_q4 (fn [t] (select {from: t by: (let p (str-find ref \"://\") (substr ref (+ p 4) 9)) c: (count ref) s: (sum v) mn: (min ref)}))) " + " (set __dh_fp (fn [r] (ser (xasc (xasc (xasc (table [k c mn] (list (as 'STR (at (value r) 0)) (at r 'c) (as 'STR (at r 'mn)))) 'mn) 'k) 'c)))) " + " (set __dh_q5 (fn [t] (select {from: t by: (substr ref 1 (+ 3 (% (strlen ref) 5))) c: (count ref) mn: (min ref)}))) " + " (set __dh_all (fn [] (list (ser (__dh_q1 __dh_F)) (ser (__dh_q2 __dh_F)) (ser (__dh_q3 __dh_F)) (ser (__dh_q4 __dh_F)) (ser (__dh_q1 __dh_T)) (ser (__dh_q5 __dh_F))))) " + " (set __dh_same (fn [] (do (set __dh_now (__dh_all)) (all (map (fn [k] (if (== (count (at __dh_now k)) (count (at __dh_base k))) (all (== (at __dh_now k) (at __dh_base k))) false)) (til 6)))))) " + " (count (distinct (at __dh_F 'ref))))")); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 1487); /* vocabulary of 1487 values */ + ray_release(r); + + ray_t* base = ray_eval_str("(set __dh_base (__dh_all))"); + TEST_ASSERT_NOT_NULL(base); TEST_ASSERT_FALSE(RAY_IS_ERR(base)); + ray_release(base); + /* the full-hash answers agree with the row path */ + ray_t* ora = ray_eval_str("(and (== (__dh_fp (__dh_q1 __dh_F)) (__dh_fp (__dh_o1 __dh_F))) " + "(== (count (__dh_q3 __dh_F)) (count (select {from: (__dh_o1 __dh_F) where: (> c 900)}))))"); + TEST_ASSERT_NOT_NULL(ora); TEST_ASSERT_FALSE(RAY_IS_ERR(ora)); + TEST_ASSERT_TRUE(ora->b8); + ray_release(ora); + ray_t* groups = ray_eval_str("(count (__dh_q1 __dh_F))"); + TEST_ASSERT_NOT_NULL(groups); TEST_ASSERT_FALSE(RAY_IS_ERR(groups)); + TEST_ASSERT_TRUE(groups->i64 > 100); + ray_release(groups); + + ray_derived_key_hash_bits_set_for_test(2); /* four hash values */ + ray_t* same2 = ray_eval_str("(__dh_same)"); + ray_derived_key_chunk_set_for_test(7); /* and many chunks */ + ray_t* same7 = ray_eval_str("(__dh_same)"); + ray_derived_key_hash_bits_set_for_test(0); + + /* A private in-memory domain (a scan's dictionary): no mapped prefix, + * so every value's bytes come through the domain on the calling + * thread — the grouping, the having cut and the kept groups' min. */ + ray_t* original = ray_eval_str("__dh_T"); + TEST_ASSERT_NOT_NULL(original); TEST_ASSERT_FALSE(RAY_IS_ERR(original)); + ray_t* refs = ray_table_get_col_idx(original, 0); + ray_sym_domain_t* domain = ray_sym_domain_new(); TEST_ASSERT_NOT_NULL(domain); + ray_t* private = ray_sym_vec_new(RAY_SYM_W32, refs->len); + TEST_ASSERT_NOT_NULL(private); TEST_ASSERT_FALSE(RAY_IS_ERR(private)); + private->sym_domain = domain; private->len = refs->len; + for (int64_t i = 0; i < refs->len; i++) { + ray_t* s = ray_sym_vec_cell(refs, i); + int64_t id = ray_sym_domain_intern(domain, ray_str_ptr(s), ray_str_len(s)); + TEST_ASSERT_TRUE(id >= 0); + ((uint32_t*)ray_data(private))[i] = (uint32_t)id; + if (!id) private->attrs |= RAY_ATTR_HAS_NULLS; + } + ray_t* table = ray_table_new(0); + table = ray_table_add_col(table, ray_sym_intern("ref", 3), private); + table = ray_table_add_col(table, ray_sym_intern("v", 1), ray_table_get_col_idx(original, 1)); + TEST_ASSERT_NOT_NULL(table); TEST_ASSERT_FALSE(RAY_IS_ERR(table)); + ray_env_set(ray_sym_intern("__dh_private", 12), table); + ray_release(private); ray_release(table); ray_release(original); + ray_derived_key_hash_bits_set_for_test(2); + ray_t* priv = ray_eval_str("(and (all (== (__dh_fp (__dh_q1 __dh_private)) (__dh_fp (__dh_q1 __dh_F)))) " + "(and (all (== (__dh_fp (__dh_q3 __dh_private)) (__dh_fp (__dh_q3 __dh_F)))) " + "(all (== (__dh_fp (__dh_q5 __dh_private)) (__dh_fp (__dh_q5 __dh_F))))))"); + ray_derived_key_hash_bits_set_for_test(0); + TEST_ASSERT_NOT_NULL(priv); TEST_ASSERT_FALSE(RAY_IS_ERR(priv)); + TEST_ASSERT_TRUE(priv->b8); + ray_release(priv); + ray_derived_key_chunk_set_for_test(0); + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_dh/\")")); + ray_release(cleanup); + TEST_ASSERT_NOT_NULL(same2); TEST_ASSERT_FALSE(RAY_IS_ERR(same2)); + TEST_ASSERT_TRUE(same2->b8); + TEST_ASSERT_NOT_NULL(same7); TEST_ASSERT_FALSE(RAY_IS_ERR(same7)); + TEST_ASSERT_TRUE(same7->b8); + ray_release(same2); + ray_release(same7); + PASS(); +} + +/* Under an armed count cut (an enclosing `where: (> c N)`) the derived-key + * grouping runs in two passes: the rows summed by key hash alone, then the + * exact aggregates of the keys under the hashes that pass, the cut applied + * again to the exact counts. Each answer must be the one-pass grouping's + * (the same groups in the same order: the unarmed grouping cut afterwards) + * and the row path's — for a cut some keys pass, one every key passes and + * one no key passes. With the hash cut to two bits every pass-A bucket + * merges hundreds of keys and passes the cut while most of its keys do + * not: the keys under one hash are told apart by their bytes, and only + * those past the cut are emitted. Three keys: the per-value program's view + * of the value (pass B reads it back off the value), one with a literal + * arm, and one only the chunk DAG computes, which is no view of the + * value for the upper-case values (pass B computes those again). */ +#define D2_KEY0 "(let p (str-find ref \"://\") (let s (substr ref (+ p 4) -1) " \ + "(let r (if (== (str-find s \"www.\") 0) (substr s 5 -1) s) (let sl (str-find r \"/\") " \ + "(if (and (within p [4 5]) (== (substr ref 1 4) \"http\") (not (nil? sl))) (substr r 1 sl) ref)))))" +#define D2_KEY1 "(if (== (str-find ref \"https\") 0) \"secure\" (substr ref 1 (+ 9 (% (strlen ref) 5))))" +#define D2_KEY2 "(lower (substr ref 1 12))" +#define D2_AGGS "c: (count ref) l: (avg (strlen ref)) sl: (sum (strlen ref)) mn: (min ref) mx: (max ref)" +static const char* const d2_keys[] = { D2_KEY0, D2_KEY1, D2_KEY2 }; + +/* One armed query by key ki over table t (inner where w, or none): the + * two-pass grouping ran, emitted what it returned, and agrees with the + * one-pass grouping (in order) and with the row path. *k: the rows + * returned. */ +static bool d2_case(const char* t, int ki, const char* w, int64_t n, int64_t* k) { + char q[4096]; + int64_t s0[5], s1[5]; + ray_derived_key_two_pass_stats_for_test(s0); + snprintf(q, sizeof(q), "(set __d2_r (select {from: (select {from: %s by: %s " D2_AGGS "%s%s}) " + "where: (> c %lld)}))", t, d2_keys[ki], w ? " where: " : "", w ? w : "", (long long)n); + ray_t* r = ray_eval_str(q); + if (!r || RAY_IS_ERR(r)) { if (r) ray_error_free(r); return false; } + ray_release(r); + ray_derived_key_two_pass_stats_for_test(s1); + /* against the unarmed one-pass grouping and the row path (both + * evaluated once, at the full hash), cut afterwards */ + const char* wv = w ? "w" : "n"; + snprintf(q, sizeof(q), "(and (all (== (__d2_cv __d2_r) (__d2_cv (select {from: __d2_b%s%s%d where: (> c %lld)})))) " + "(all (== (__d2_fp __d2_r) (__d2_fp (select {from: __d2_O%s%d where: (> c %lld)})))))", + wv, t + strlen(t) - 1, ki, (long long)n, wv, ki, (long long)n); + ray_t* same = ray_eval_str(q); + bool ok = same && !RAY_IS_ERR(same) && same->type == -RAY_BOOL && same->b8; + if (same) { if (RAY_IS_ERR(same)) ray_error_free(same); else ray_release(same); } + ray_t* cnt = ray_eval_str("(count __d2_r)"); + *k = cnt && !RAY_IS_ERR(cnt) ? cnt->i64 : -1; + if (cnt) { if (RAY_IS_ERR(cnt)) ray_error_free(cnt); else ray_release(cnt); } + return ok && s1[0] == s0[0] + 1 && s1[1] == *k; +} + +static test_result_t test_select_derived_key_two_pass(void) { + ray_t* r = ray_eval_str( + ray_test_tmp("(do (set __d2_i (til 80000)) " + " (set __d2_hosts (map (fn [k] (format \"h%.example.com\" k)) (til 37))) " + " (set __d2_mk (fn [k] ((fn [j] (if (== 0 (% j 11)) \"\" (if (== 0 (% j 7)) " + " (format \"https://www.%/p/%\" (at __d2_hosts (% (* 31 j) 37)) (% j 13)) " + " (if (== 0 (% j 13)) (format \"HTTP://WWW.%/Q/%\" (at __d2_hosts (% (* 31 j) 37)) (% j 3)) " + " (if (== 0 (% j 5)) (format \"plain%.x\" j) " + " (format \"http://%/a/%\" (at __d2_hosts (% (* 31 j) 37)) (% j 17))))))) (% (* k 7919) 3000)))) " + " (set __d2_T (table [ref v] (list (as 'SYMBOL (map __d2_mk __d2_i)) (% __d2_i 101)))) " + " (.sys.exec \"rm -rf /tmp/rf_test_d2/\") " + " (.db.splayed.set \"/tmp/rf_test_d2/\" __d2_T) " + " (set __d2_F (.db.splayed.get \"/tmp/rf_test_d2/\")) " + " (set __d2_cvt (fn [r] (table [k c l sl mn mx] (list (as 'STR (at (value r) 0)) (at r 'c) (at r 'l) " + " (at r 'sl) (as 'STR (at r 'mn)) (as 'STR (at r 'mx)))))) " + " (set __d2_cv (fn [r] (ser (__d2_cvt r)))) " + " (set __d2_fp (fn [r] (ser (xasc (__d2_cvt r) 'k)))) " + " (count (distinct (at __d2_F 'ref))))")); + TEST_ASSERT_NOT_NULL(r); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 1558); /* vocabulary of 1558 values */ + ray_release(r); + /* per key: the unarmed one-pass groupings (__d2_b{n,w}{F,T}k), the row + * path (__d2_O{n,w}k), the group count and the least and most rows */ + int64_t all[3], cmin[3], cmax[3]; + for (int ki = 0; ki < 3; ki++) { + char q[4096]; + snprintf(q, sizeof(q), "(do (set __d2_u (fn [t] (select {from: t by: %s " D2_AGGS "}))) " + "(set __d2_uw (fn [t] (select {from: t by: %s " D2_AGGS " where: (!= ref \"\")}))) " + "(set __d2_bnF%d (__d2_u __d2_F)) (set __d2_bwF%d (__d2_uw __d2_F)) " + "(set __d2_bnT%d (__d2_u __d2_T)) (set __d2_bwT%d (__d2_uw __d2_T)) " + "(set __d2_On%d (select {from: (select {from: __d2_T p: %s ref: ref}) by: p " D2_AGGS "})) " + "(set __d2_Ow%d (select {from: (select {from: __d2_T p: %s ref: ref where: (!= ref \"\")}) by: p " D2_AGGS "})) " + "(list (count __d2_bnF%d) (min (at __d2_bnF%d 'c)) (max (at __d2_bnF%d 'c))))", + d2_keys[ki], d2_keys[ki], ki, ki, ki, ki, ki, d2_keys[ki], ki, d2_keys[ki], ki, ki, ki); + ray_t* v = ray_eval_str(q); + TEST_ASSERT_NOT_NULL(v); TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + TEST_ASSERT_EQ_I(ray_len(v), 3); + ray_t* a0 = ray_list_get(v, 0); ray_t* a1 = ray_list_get(v, 1); ray_t* a2 = ray_list_get(v, 2); + TEST_ASSERT_NOT_NULL(a0); TEST_ASSERT_NOT_NULL(a1); TEST_ASSERT_NOT_NULL(a2); + all[ki] = a0->i64; cmin[ki] = a1->i64; cmax[ki] = a2->i64; + ray_release(v); + TEST_ASSERT_TRUE(all[ki] > 300); + TEST_ASSERT_TRUE(cmin[ki] > 1); /* every key passes a cut of 1 */ + TEST_ASSERT_TRUE(cmax[ki] > 900); + } + + /* the first failing line, reported once the seams are reset */ + int bad = 0; + #define D2_CHECK(x) do { if (!(x) && !bad) bad = __LINE__; } while (0) + static const char* const tabs[] = { "__d2_F", "__d2_T" }; + int64_t k = -1, st[5]; + for (int bits = 0; bits <= 2 && !bad; bits += 2) { + ray_derived_key_hash_bits_set_for_test(bits); /* full hash, then four hash values */ + for (int ki = 0; ki < 3 && !bad; ki++) { + for (int ti = 0; ti < 2 && !bad; ti++) { + /* some keys pass */ + D2_CHECK(d2_case(tabs[ti], ki, NULL, 900, &k)); + D2_CHECK(k > 0 && k < all[ki]); + ray_derived_key_two_pass_stats_for_test(st); + if (bits) { + /* the buckets merged keys: a group per key under them, most cut */ + D2_CHECK(st[2] > 0 && st[2] <= 4); + D2_CHECK(st[3] > 0); + D2_CHECK(k < st[2] + st[3]); + } + D2_CHECK(d2_case(tabs[ti], ki, "(!= ref \"\")", 900, &k)); + D2_CHECK(k > 0 && k < all[ki]); + /* every key passes */ + D2_CHECK(d2_case(tabs[ti], ki, NULL, 1, &k)); + D2_CHECK(k == all[ki]); + /* no key passes; under two bits every bucket still does */ + D2_CHECK(d2_case(tabs[ti], ki, NULL, cmax[ki], &k)); + D2_CHECK(k == 0); + ray_derived_key_two_pass_stats_for_test(st); + if (bits) D2_CHECK(st[2] > 0); + } + } + } + if (!bad) { + ray_derived_key_chunk_set_for_test(7); /* and many chunks */ + for (int ki = 0; ki < 3 && !bad; ki++) { + D2_CHECK(d2_case("__d2_F", ki, NULL, 900, &k)); + D2_CHECK(k > 0 && k < all[ki]); + D2_CHECK(d2_case("__d2_T", ki, "(!= ref \"\")", 900, &k)); + } + } + #undef D2_CHECK + ray_derived_key_chunk_set_for_test(0); + ray_derived_key_hash_bits_set_for_test(0); + ray_t* cleanup = ray_eval_str(ray_test_tmp("(.sys.exec \"rm -rf /tmp/rf_test_d2/\")")); + ray_release(cleanup); + if (bad) FAILF("check at line %d failed", bad); + PASS(); +} + static test_result_t test_builtin_group_empty_and_list(void) { /* Empty group */ ASSERT_EQ("(count (key (group [])))", "0"); @@ -9684,7 +10784,9 @@ static test_result_t test_read_procfs_reports_zero_size(void) { * spill file rather than merely exhausting RAM. * * Drives the bound by moving the watermark to just above what is already - * committed, which makes the budget small and the error immediate. */ + * committed, which makes the budget its floor (64 MB) and the error quick; + * then below it, as when memory is short: the budget must stay that floor, + * not fall to 0 — "no bound" — and an endless stream must still error. */ static test_result_t test_read_unsized_stream_is_bounded(void) { #if defined(RAY_OS_WINDOWS) SKIP("no /dev/zero"); @@ -9700,8 +10802,9 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { int64_t saved = ray_heap_anon_watermark(); ray_heap_set_anon_watermark(0); bool was_default = (saved == ray_heap_anon_watermark()); - /* budget = (watermark - committed) / 4, so this leaves ~1 MB. */ + /* budget = max((watermark - committed) / 4, 64 MB): here the floor. */ ray_heap_set_anon_watermark(ray_heap_anon_committed() + 4 * 1024 * 1024); + int64_t near_budget = ray_unsized_read_budget(); ray_t* arg = ray_str("/dev/zero", 9); ray_t* got = ray_read_file_fn(arg); @@ -9709,21 +10812,42 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { ray_heap_set_anon_watermark(was_default ? 0 : saved); + TEST_ASSERT_EQ_I(near_budget, INT64_C(64) << 20); TEST_ASSERT_NOT_NULL(got); TEST_ASSERT(RAY_IS_ERR(got), "an endless stream must error, not grow without end"); TEST_ASSERT_STR_EQ(ray_err_code(got), "io"); ray_error_free(got); + /* Past the watermark — committed above it, memory short — the bound + * must hold all the more. It used to come back 0, which the readers + * take for "no bound": checked before reading, so that a 0 fails here + * instead of reading /dev/zero without end. */ + int64_t committed = ray_heap_anon_committed(); + ray_heap_set_anon_watermark(committed > 2 ? committed / 2 : 1); + int64_t past_budget = ray_unsized_read_budget(); + ray_t* past = NULL; + if (past_budget > 0) { + ray_t* parg = ray_str("/dev/zero", 9); + past = ray_read_file_fn(parg); + ray_release(parg); + } + ray_heap_set_anon_watermark(was_default ? 0 : saved); + TEST_ASSERT_EQ_I(past_budget, INT64_C(64) << 20); + TEST_ASSERT_NOT_NULL(past); + TEST_ASSERT(RAY_IS_ERR(past), "past the watermark an endless stream must still error"); + TEST_ASSERT_STR_EQ(ray_err_code(past), "io"); + ray_error_free(past); + /* A *sized* file larger than the same budget must still read: the * ceiling exists to terminate an endless stream, and a reported size is * a finite claim the filesystem backs. Bounding this path would turn a * large-file read that previously allocated and spilled into a hard * error, and would make success depend on live process state. */ - const char* big = "/tmp/rf_read_big_sized.bin"; + const char* big = ray_test_tmp("/tmp/rf_read_big_sized.bin"); FILE* bf = fopen(big, "wb"); TEST_ASSERT_NOT_NULL(bf); static char chunk[65536]; - for (int i = 0; i < 32; i++) /* 2 MB, well over the ~1 MB budget */ + for (int i = 0; i < 512; i++) /* 32 MB: unsized, the 64 MB budget would refuse it (3x peak) */ TEST_ASSERT(fwrite(chunk, 1, sizeof(chunk), bf) == sizeof(chunk), "write big file"); fclose(bf); @@ -9734,7 +10858,7 @@ static test_result_t test_read_unsized_stream_is_bounded(void) { ray_heap_set_anon_watermark(was_default ? 0 : saved); remove(big); TEST_ASSERT(!RAY_IS_ERR(bread), "a sized file must not be refused by the unsized budget"); - TEST_ASSERT_EQ_I(ray_str_len(bread), 2 * 1024 * 1024); + TEST_ASSERT_EQ_I(ray_str_len(bread), 32 * 1024 * 1024); ray_release(bread); /* The bound must not have disturbed ordinary reads once restored. */ @@ -9777,7 +10901,103 @@ static test_result_t test_exec_capture_is_bounded(void) { #endif } +/* Index maintenance must preserve externally visible bindings after misses, + * compaction, reinsertion, value-cache invalidation and runtime recreation. */ +static test_result_t test_env_write_index_lifecycle(void) { + for (int round = 0; round < 2; round++) { + if (round) { ray_runtime_destroy(__RUNTIME); ray_runtime_create(0, NULL); } + enum { NAMES = 96 }; + int64_t names[NAMES], expected[NAMES] = {0}; + bool present[NAMES] = {false}; + char name[64]; + for (int i = 0; i < NAMES; i++) { + snprintf(name, sizeof(name), "write_index_%d_%d", round, i); + names[i] = ray_sym_intern(name, strlen(name)); + } + uint64_t rng = UINT64_C(0xd72f409d118af9b3); + for (int step = 0; step < 4096; step++) { + rng = rng * UINT64_C(6364136223846793005) + 1; + int at = (int)((rng >> 32) % NAMES); + bool remove = ((rng >> 56) & 3) == 0; + ray_t* value = remove ? NULL : ray_i64(step + 1); + TEST_ASSERT_EQ_I(ray_env_set(names[at], value), RAY_OK); + if (value) ray_release(value); + present[at] = !remove; + expected[at] = step + 1; + for (int i = 0; i < NAMES; i++) { + ray_t* got = ray_env_get_global(names[i]); + TEST_ASSERT_EQ_I(got != NULL, present[i]); + if (got) TEST_ASSERT_EQ_I(got->i64, expected[i]); + } + } + /* Cache value pointers before a write, then require the new value. */ + int64_t id = names[0]; + for (int step = 0; step < 3; step++) { + ray_t* value = ray_i64(100 + step); + TEST_ASSERT_EQ_I(ray_env_set(id, value), RAY_OK); + ray_release(value); + uint8_t rows = 0; + ray_t* resolved = ray_env_resolve_compiled(id, &rows); + TEST_ASSERT_NOT_NULL(resolved); + TEST_ASSERT_EQ_I(resolved->i64, 100 + step); + ray_release(resolved); + } + /* Exact flat dotted builtin names also have cached value pointers. */ + id = ray_sym_intern(".write.index.test", 17); + for (int step = 0; step < 3; step++) { + ray_t* value = ray_i64(200 + step); + TEST_ASSERT_EQ_I(ray_env_bind_flat(id, value), RAY_OK); + ray_release(value); + uint8_t rows = 0; + ray_t* resolved = ray_env_resolve_compiled(id, &rows); + TEST_ASSERT_NOT_NULL(resolved); + TEST_ASSERT_EQ_I(resolved->i64, 200 + step); + ray_release(resolved); + } + } + PASS(); +} + +static test_result_t test_env_write_index_flags_and_capacity(void) { + int64_t plus = ray_sym_intern("+", 1); + ray_t* value = ray_i64(99); + TEST_ASSERT_EQ_I(ray_env_set(plus, value), RAY_OK); + TEST_ASSERT_EQ_I(ray_env_bind(plus, value), RAY_OK); /* must stay user-defined */ + ray_release(value); + int64_t ids[1024]; + ray_t* vals[1024]; + int32_t count = ray_env_list_user(ids, vals, 1024); + bool found = false; + for (int32_t i = 0; i < count; i++) + if (ids[i] == plus) { found = true; TEST_ASSERT_EQ_I(vals[i]->i64, 99); } + TEST_ASSERT_TRUE(found); + value = ray_i64(7); + int64_t first = -1, rejected = -1; + for (int i = 0; i < 2048; i++) { + char name[64]; + snprintf(name, sizeof(name), "write_index_capacity_%d", i); + int64_t id = ray_sym_intern(name, strlen(name)); + ray_err_t err = ray_env_set(id, value); + if (err != RAY_OK) { + TEST_ASSERT_EQ_I(err, RAY_ERR_OOM); + rejected = id; + break; + } + if (first < 0) first = id; + } + TEST_ASSERT_TRUE(first >= 0 && rejected >= 0); + TEST_ASSERT_EQ_I(ray_env_set(first, value), RAY_OK); /* rebind while full */ + TEST_ASSERT_EQ_I(ray_env_set(first, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_env_set(rejected, value), RAY_OK); /* reuse after shift */ + TEST_ASSERT_EQ_I(ray_env_get_global(rejected)->i64, 7); + TEST_ASSERT_EQ_I(ray_env_get_global(plus)->i64, 99); + ray_release(value); + PASS(); +} + const test_entry_t lang_entries[] = { + { "lang/env/write_index_lifecycle", test_env_write_index_lifecycle, lang_setup, lang_teardown }, + { "lang/env/write_index_flags_capacity", test_env_write_index_flags_and_capacity, lang_setup, lang_teardown }, { "lang/env/scope_frame_grows", test_env_scope_frame_grows, lang_setup, lang_teardown }, { "lang/query/wide_table_over_64_cols", test_query_wide_table_over_64_cols, lang_setup, lang_teardown }, { "lang/fn_unary", test_fn_unary, lang_setup, lang_teardown }, @@ -9796,6 +11016,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/literal", test_eval_literal, lang_setup, lang_teardown }, { "lang/eval/add", test_eval_add, lang_setup, lang_teardown }, { "lang/eval/nested_arith", test_eval_nested_arith, lang_setup, lang_teardown }, + { "lang/query/minmax_bulk_bound", test_query_minmax_bulk_bound, lang_setup, lang_teardown }, { "lang/eval/sub", test_eval_sub, lang_setup, lang_teardown }, { "lang/eval/div", test_eval_div, lang_setup, lang_teardown }, { "lang/eval/cmp", test_eval_cmp, lang_setup, lang_teardown }, @@ -9849,6 +11070,9 @@ const test_entry_t lang_entries[] = { { "lang/eval/select_all", test_eval_select_all, lang_setup, lang_teardown }, { "lang/eval/select_where", test_eval_select_where, lang_setup, lang_teardown }, { "lang/eval/select_where_in_sym", test_eval_select_where_in_sym, lang_setup, lang_teardown }, + { "lang/eval/select_unary_arith_dag_admission", test_eval_select_unary_arith_dag_admission, lang_setup, lang_teardown }, + { "lang/eval/select_temporal_mod_dag_admission", test_eval_select_temporal_mod_dag_admission, lang_setup, lang_teardown }, + { "lang/eval/empty_probe_error_ownership", test_eval_empty_probe_error_ownership, lang_setup, lang_teardown }, { "lang/eval/select_where_in_i64", test_eval_select_where_in_i64, lang_setup, lang_teardown }, { "lang/eval/select_where_in_mixed_numeric", test_eval_select_where_in_mixed_numeric, lang_setup, lang_teardown }, { "lang/eval/select_where_in_nulls", test_eval_select_where_in_nulls, lang_setup, lang_teardown }, @@ -9961,6 +11185,7 @@ const test_entry_t lang_entries[] = { { "lang/dotted/update_in_place", test_dotted_update_in_place, lang_setup, lang_teardown }, { "lang/dotted/wrong_type_parent", test_dotted_wrong_type_parent, lang_setup, lang_teardown }, { "lang/dotted/missing_key", test_dotted_missing_key, lang_setup, lang_teardown }, + { "lang/dotted/flat_binding_wins", test_dotted_flat_binding_wins, lang_setup, lang_teardown }, { "lang/dotted/del_removes_key", test_dotted_del_removes_key, lang_setup, lang_teardown }, { "lang/dotted/del_nested", test_dotted_del_nested, lang_setup, lang_teardown }, { "lang/dotted/del_cascade", test_dotted_del_cascade, lang_setup, lang_teardown }, @@ -10182,6 +11407,8 @@ const test_entry_t lang_entries[] = { { "lang/builtin/idiv_fn", test_builtin_idiv_fn, lang_setup, lang_teardown }, { "lang/builtin/concat_fn", test_builtin_concat_fn, lang_setup, lang_teardown }, { "lang/builtin/enlist_fn", test_builtin_enlist_fn, lang_setup, lang_teardown }, + { "lang/builtin/enlist_mixed_atoms", test_builtin_enlist_mixed_atoms, lang_setup, lang_teardown }, + { "lang/builtin/enlist_promotion_payload", test_builtin_enlist_promotion_payload, lang_setup, lang_teardown }, { "lang/builtin/resolve_fn", test_builtin_resolve_fn, lang_setup, lang_teardown }, { "lang/builtin/nil_rfl", test_builtin_nil_rfl, lang_setup, lang_teardown }, { "lang/builtin/where_rfl", test_builtin_where_rfl, lang_setup, lang_teardown }, @@ -10190,6 +11417,15 @@ const test_entry_t lang_entries[] = { { "lang/builtin/group_guid_rfl", test_builtin_group_guid_rfl, lang_setup, lang_teardown }, { "lang/builtin/group_empty_list", test_builtin_group_empty_and_list, lang_setup, lang_teardown }, { "lang/select/derived_key_file_chunks", test_select_derived_key_file_chunks, lang_setup, lang_teardown }, + { "lang/select/derived_key_hash_collisions", test_select_derived_key_hash_collisions, lang_setup, lang_teardown }, + { "lang/select/derived_key_where_on_values", test_select_derived_key_where_on_values, lang_setup, lang_teardown }, + { "lang/select/derived_key_two_pass_empty_keys", test_select_derived_key_two_pass_empty_keys, lang_setup, lang_teardown }, + { "lang/select/derived_key_two_pass", test_select_derived_key_two_pass, lang_setup, lang_teardown }, + { "lang/select/derived_key_gen2_no_decode", test_select_derived_key_gen2_no_decode, lang_setup, lang_teardown }, + { "lang/select/gen2_ranged_no_decode", test_select_gen2_ranged_no_decode, lang_setup, lang_teardown }, + { "lang/select/topk_count_exact", test_select_topk_count_exact, lang_setup, lang_teardown }, + { "lang/select/topk_count_guards", test_select_topk_count_guards, lang_setup, lang_teardown }, + { "lang/select/topk_count_mem_gate", test_select_topk_count_mem_gate, lang_setup, lang_teardown }, { "lang/select/releases_input_table", test_select_releases_input_table, lang_setup, lang_teardown }, { "lang/temporal/extract_builtins_fn", test_temporal_extract_builtins_fn, lang_setup, lang_teardown }, { "lang/temporal/extract_time_atom", test_temporal_extract_time_atom, lang_setup, lang_teardown }, diff --git a/test/test_link.c b/test/test_link.c index 7f1c8d560..485803a91 100644 --- a/test/test_link.c +++ b/test/test_link.c @@ -31,7 +31,6 @@ #include "table/table.h" #include "lang/eval.h" #include "lang/env.h" -#define _POSIX_C_SOURCE 200809L #include "ops/linkop.h" #include "ops/idxop.h" @@ -578,6 +577,39 @@ static test_result_t test_link_alter_set_failed_no_leak(void) { PASS(); } +/* ─── alter set through a dotted name: in place only when sole ────── */ + +static test_result_t test_link_alter_set_dotted_in_place(void) { + /* A chain of dicts each held once is amended in place: the leaf the + * name resolves to is the same block before and after (#821 — every + * call used to copy the whole vector). Once the head is aliased the + * write must copy, so the alias keeps the old value. */ + ray_t* setup = ray_eval_str("(set PD (dict [cash v] (list 100 (til 4))))"); + if (setup && !RAY_IS_ERR(setup)) ray_release(setup); + int64_t s_pdv = ray_sym_intern("PD.v", 4); + + ray_t* before = ray_env_get(s_pdv); + TEST_ASSERT_NOT_NULL(before); + ray_t* r = ray_eval_str("(alter 'PD.v set 1 50)"); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + ray_t* after = ray_env_get(s_pdv); + TEST_ASSERT_TRUE(after == before); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(after))[1], 50); + + r = ray_eval_str("(set PE PD)"); + if (r && !RAY_IS_ERR(r)) ray_release(r); + r = ray_eval_str("(alter 'PD.v set 2 60)"); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + ray_t* copied = ray_env_get(s_pdv); + TEST_ASSERT_TRUE(copied != before); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(copied))[2], 60); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(before))[2], 2); + + PASS(); +} + /* ─── alter set's cow-failure cleanup helper, both branches ───────── */ extern ray_t* ray_alter_set_cow_fail(ray_t* original_var, ray_t* cow_result, @@ -917,7 +949,7 @@ static ray_err_t write_link_partition(const char* part_dir, const int64_t* qtys, int64_t n_qty, int64_t custs_sym) { char dir[1024]; - snprintf(dir, sizeof(dir), TMP_LINK_PART_DB "/%s/" TMP_LINK_PART_TBL, part_dir); + snprintf(dir, sizeof(dir), "%s/%s/" TMP_LINK_PART_TBL, ray_test_tmp(TMP_LINK_PART_DB), part_dir); if (ray_test_mkdir_p(dir) != 0) return RAY_ERR_IO; ray_t* ridcol = ray_vec_from_raw(RAY_I64, (void*)rids, n_rid); @@ -952,7 +984,7 @@ static ray_err_t write_link_partition(const char* part_dir, static test_result_t test_link_parted_load_propagates(void) { int64_t custs_sym = setup_custs_dim(); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); int64_t r1[] = { 0, 1, 2 }; int64_t q1[] = { 10, 20, 30 }; @@ -962,9 +994,9 @@ static test_result_t test_link_parted_load_propagates(void) { int64_t q2[] = { 40, 50 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.02", r2, 2, q2, 2, custs_sym), RAY_OK); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_LINK_PART_DB "/.sym"), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_LINK_PART_DB "/.sym")), RAY_OK); - ray_t* parted = ray_read_parted(TMP_LINK_PART_DB, TMP_LINK_PART_TBL); + ray_t* parted = ray_read_parted(ray_test_tmp(TMP_LINK_PART_DB), TMP_LINK_PART_TBL); TEST_ASSERT_NOT_NULL(parted); TEST_ASSERT_FALSE(RAY_IS_ERR(parted)); @@ -1018,7 +1050,7 @@ static test_result_t test_link_parted_load_propagates(void) { ray_release(ages1); ray_release(parted); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); PASS(); } @@ -1030,7 +1062,7 @@ static test_result_t test_link_attach_rejects_parted_target(void) { /* Build a parted table on disk and load via ray_read_parted so we have a * real RAY_TABLE-with-RAY_PARTED-cols handle to point at. */ int64_t custs_sym = setup_custs_dim(); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); int64_t r1[] = { 0, 1, 2 }; int64_t q1[] = { 10, 20, 30 }; @@ -1038,9 +1070,9 @@ static test_result_t test_link_attach_rejects_parted_target(void) { int64_t r2[] = { 2, 1 }; int64_t q2[] = { 40, 50 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.02", r2, 2, q2, 2, custs_sym), RAY_OK); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_LINK_PART_DB "/.sym"), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_LINK_PART_DB "/.sym")), RAY_OK); - ray_t* parted = ray_read_parted(TMP_LINK_PART_DB, TMP_LINK_PART_TBL); + ray_t* parted = ray_read_parted(ray_test_tmp(TMP_LINK_PART_DB), TMP_LINK_PART_TBL); TEST_ASSERT_NOT_NULL(parted); TEST_ASSERT_FALSE(RAY_IS_ERR(parted)); @@ -1063,7 +1095,7 @@ static test_result_t test_link_attach_rejects_parted_target(void) { ray_release(w); ray_release(v); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); PASS(); } @@ -1093,16 +1125,16 @@ static test_result_t test_link_deref_rejects_parted_after_rebind(void) { ray_release(good); /* Build a parted table on disk and rebind `custs` to it. */ - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); int64_t r1[] = { 0, 1 }; int64_t q1[] = { 10, 20 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.01", r1, 2, q1, 2, custs_sym), RAY_OK); int64_t r2[] = { 1, 0 }; int64_t q2[] = { 30, 40 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.02", r2, 2, q2, 2, custs_sym), RAY_OK); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_LINK_PART_DB "/.sym"), RAY_OK); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_LINK_PART_DB "/.sym")), RAY_OK); - ray_t* parted = ray_read_parted(TMP_LINK_PART_DB, TMP_LINK_PART_TBL); + ray_t* parted = ray_read_parted(ray_test_tmp(TMP_LINK_PART_DB), TMP_LINK_PART_TBL); TEST_ASSERT_NOT_NULL(parted); TEST_ASSERT_FALSE(RAY_IS_ERR(parted)); @@ -1116,7 +1148,7 @@ static test_result_t test_link_deref_rejects_parted_after_rebind(void) { ray_release(w); ray_release(v); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); PASS(); } @@ -1153,15 +1185,15 @@ static test_result_t test_link_dotted_resolve_propagates_parted_error(void) { ray_release(good); /* Rebind custs to a parted table on disk. */ - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); int64_t r1[] = { 0, 1 }; int64_t q1[] = { 10, 20 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.01", r1, 2, q1, 2, custs_sym), RAY_OK); int64_t r2[] = { 1, 0 }; int64_t q2[] = { 30, 40 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.02", r2, 2, q2, 2, custs_sym), RAY_OK); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_LINK_PART_DB "/.sym"), RAY_OK); - ray_t* parted = ray_read_parted(TMP_LINK_PART_DB, TMP_LINK_PART_TBL); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_LINK_PART_DB "/.sym")), RAY_OK); + ray_t* parted = ray_read_parted(ray_test_tmp(TMP_LINK_PART_DB), TMP_LINK_PART_TBL); TEST_ASSERT_NOT_NULL(parted); TEST_ASSERT_FALSE(RAY_IS_ERR(parted)); ray_env_set(custs_sym, parted); @@ -1178,7 +1210,7 @@ static test_result_t test_link_dotted_resolve_propagates_parted_error(void) { ray_release(w); ray_release(v); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); PASS(); } @@ -1210,15 +1242,15 @@ static test_result_t test_link_vm_eval_propagates_parted_error(void) { ray_release(good); /* Rebind custs to a parted table. */ - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); int64_t r1[] = { 0, 1 }; int64_t q1[] = { 10, 20 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.01", r1, 2, q1, 2, custs_sym), RAY_OK); int64_t r2[] = { 1, 0 }; int64_t q2[] = { 30, 40 }; TEST_ASSERT_EQ_I(write_link_partition("2024.01.02", r2, 2, q2, 2, custs_sym), RAY_OK); - TEST_ASSERT_EQ_I(ray_sym_save(TMP_LINK_PART_DB "/.sym"), RAY_OK); - ray_t* parted = ray_read_parted(TMP_LINK_PART_DB, TMP_LINK_PART_TBL); + TEST_ASSERT_EQ_I(ray_sym_save(ray_test_tmp(TMP_LINK_PART_DB "/.sym")), RAY_OK); + ray_t* parted = ray_read_parted(ray_test_tmp(TMP_LINK_PART_DB), TMP_LINK_PART_TBL); TEST_ASSERT_NOT_NULL(parted); TEST_ASSERT_FALSE(RAY_IS_ERR(parted)); ray_env_set(custs_sym, parted); @@ -1231,7 +1263,7 @@ static test_result_t test_link_vm_eval_propagates_parted_error(void) { ray_release(w); ray_release(v); - (void)ray_test_rm_rf(TMP_LINK_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_LINK_PART_DB)); PASS(); } @@ -1256,6 +1288,7 @@ const test_entry_t link_entries[] = { { "link/deref_unknown_field", test_link_deref_unknown_field, link_setup, link_teardown }, { "link/save_no_link_no_sidecar", test_link_save_no_link_no_sidecar, link_setup, link_teardown }, { "link/alter_set_failed_no_leak", test_link_alter_set_failed_no_leak, link_setup, link_teardown }, + { "link/alter_set_dotted_in_place", test_link_alter_set_dotted_in_place, link_setup, link_teardown }, { "link/alter_set_cow_fail_null", test_link_alter_set_cow_fail_null, link_setup, link_teardown }, { "link/alter_set_cow_fail_error", test_link_alter_set_cow_fail_error, link_setup, link_teardown }, { "link/slice_inherits", test_link_slice_inherits, link_setup, link_teardown }, diff --git a/test/test_meta.c b/test/test_meta.c index de8f1a286..c617dad57 100644 --- a/test/test_meta.c +++ b/test/test_meta.c @@ -39,7 +39,7 @@ static void meta_setup(void) { } static void meta_teardown(void) { - unlink(TMP_META_PATH); + unlink(ray_test_tmp(TMP_META_PATH)); ray_sym_destroy(); ray_heap_destroy(); } @@ -54,11 +54,11 @@ static test_result_t test_meta_save_load_roundtrip(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(schema)); /* Save */ - ray_err_t err = ray_meta_save_d(schema, TMP_META_PATH); + ray_err_t err = ray_meta_save_d(schema, ray_test_tmp(TMP_META_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load back */ - ray_t* loaded = ray_meta_load_d(TMP_META_PATH); + ray_t* loaded = ray_meta_load_d(ray_test_tmp(TMP_META_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -79,7 +79,7 @@ static test_result_t test_meta_save_load_roundtrip(void) { /* ---- test_meta_save_null_returns_error --------------------------------- */ static test_result_t test_meta_save_null_returns_error(void) { - ray_err_t err = ray_meta_save_d(NULL, TMP_META_PATH); + ray_err_t err = ray_meta_save_d(NULL, ray_test_tmp(TMP_META_PATH)); TEST_ASSERT((err) != (RAY_OK), "err != RAY_OK"); PASS(); @@ -89,7 +89,7 @@ static test_result_t test_meta_save_null_returns_error(void) { static test_result_t test_meta_save_err_ptr_returns_error(void) { ray_t* bad = ray_error("type", NULL); - ray_err_t err = ray_meta_save_d(bad, TMP_META_PATH); + ray_err_t err = ray_meta_save_d(bad, ray_test_tmp(TMP_META_PATH)); TEST_ASSERT((err) != (RAY_OK), "err != RAY_OK"); ray_release(bad); @@ -99,7 +99,7 @@ static test_result_t test_meta_save_err_ptr_returns_error(void) { /* ---- test_meta_load_nonexistent --------------------------------------- */ static test_result_t test_meta_load_nonexistent(void) { - ray_t* loaded = ray_meta_load_d("/tmp/rayforce_no_such_file_meta.d"); + ray_t* loaded = ray_meta_load_d(ray_test_tmp("/tmp/rayforce_no_such_file_meta.d")); /* Should return NULL or error pointer for missing file */ TEST_ASSERT_TRUE(loaded == NULL || RAY_IS_ERR(loaded)); diff --git a/test/test_morsel.c b/test/test_morsel.c index 0fea30093..9d35776b2 100644 --- a/test/test_morsel.c +++ b/test/test_morsel.c @@ -384,12 +384,12 @@ static test_result_t test_morsel_mmap_advise(void) { TEST_ASSERT_NOT_NULL(vec); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_MORSEL_COL); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_MORSEL_COL)); TEST_ASSERT_EQ_I(err, RAY_OK); ray_release(vec); /* Load via mmap -> mmod == 1 */ - ray_t* mapped = ray_col_mmap(TMP_MORSEL_COL); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_MORSEL_COL)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_U(mapped->mmod, 1); @@ -412,7 +412,7 @@ static test_result_t test_morsel_mmap_advise(void) { TEST_ASSERT_EQ_I(count, 8); ray_release(mapped); - unlink(TMP_MORSEL_COL); + unlink(ray_test_tmp(TMP_MORSEL_COL)); PASS(); } diff --git a/test/test_numparse.c b/test/test_numparse.c index 70e199645..7ccb867e7 100644 --- a/test/test_numparse.c +++ b/test/test_numparse.c @@ -181,6 +181,45 @@ static test_result_t test_numparse_f64_basic(void) { PASS(); } +/* The sign of zero survives the parse bit-for-bit in every build flavour. + * `0.0 == -0.0` is true, so this test compares the bit patterns: a plain + * zero must be 0x0000000000000000 and a negated one 0x8000000000000000. + * The release flavour's -fno-signed-zeros once folded both to -0.0 + * (#850); the debug flavour never did, so under `make test` this pins the + * contract and a `make release` + od check is what shows the bug. */ +static uint64_t f64_bits(double d) { + uint64_t b; + memcpy(&b, &d, sizeof b); + return b; +} + +static test_result_t test_numparse_f64_signed_zero(void) { + double d; + TEST_ASSERT_EQ_U(ray_parse_f64("0", 1, &d), 1); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(0)); + TEST_ASSERT_EQ_U(ray_parse_f64("0.0", 3, &d), 3); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(0)); + TEST_ASSERT_EQ_U(ray_parse_f64("+0", 2, &d), 2); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(0)); + TEST_ASSERT_EQ_U(ray_parse_f64("0e5", 3, &d), 3); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(0)); + TEST_ASSERT_EQ_U(ray_parse_f64("-0", 2, &d), 2); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(1) << 63); + TEST_ASSERT_EQ_U(ray_parse_f64("-0.0", 4, &d), 4); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(1) << 63); + /* A value below the denormal range is a zero too, and keeps its sign. */ + TEST_ASSERT_EQ_U(ray_parse_f64("1e-400", 6, &d), 6); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(0)); + TEST_ASSERT_EQ_U(ray_parse_f64("-1e-400", 7, &d), 7); + TEST_ASSERT_EQ_U(f64_bits(d), UINT64_C(1) << 63); + /* Non-zero values are unaffected by the bit-level sign. */ + TEST_ASSERT_EQ_U(ray_parse_f64("-1.5", 4, &d), 4); + TEST_ASSERT_EQ_U(f64_bits(d), f64_bits(-1.5)); + TEST_ASSERT_EQ_U(ray_parse_f64("-1e300", 6, &d), 6); + TEST_ASSERT_EQ_U(f64_bits(d), f64_bits(-1e300)); + PASS(); +} + static test_result_t test_numparse_f64_special(void) { /* STAGE 2 (single-null float model) re-baseline: the F64 domain is * {finite} ∪ {0Nf}; ±Inf and NaN are NOT values. ray_parse_f64 still @@ -354,6 +393,7 @@ const test_entry_t numparse_entries[] = { { "numparse/swar_8digits", test_numparse_swar_8digits, NULL, NULL }, { "numparse/swar_4digits", test_numparse_swar_4digits, NULL, NULL }, { "numparse/i64_basic", test_numparse_i64_basic, NULL, NULL }, + { "numparse/f64_signed_zero", test_numparse_f64_signed_zero, NULL, NULL }, { "numparse/i64_swar_paths", test_numparse_i64_swar_paths, NULL, NULL }, { "numparse/i64_overflow", test_numparse_i64_overflow, NULL, NULL }, { "numparse/i64_silent_wrap",test_numparse_i64_silent_wrap, NULL, NULL }, diff --git a/test/test_opt.c b/test/test_opt.c index c4f0d3a11..db1509348 100644 --- a/test/test_opt.c +++ b/test/test_opt.c @@ -59,6 +59,579 @@ static ray_t* make_test_table(void) { return tbl; } +/* Admission uses logical types, not the integer representation of symbol IDs. */ +static test_result_t test_sym_compare_admission(void) { + ray_heap_init(); + (void)ray_sym_init(); + ray_graph_t* g = ray_graph_new(NULL); + TEST_ASSERT(g != NULL, "graph"); + ray_t* atom = ray_sym(ray_sym_intern("alpha", 5)); + ray_op_t* n = ray_const_atom(g, atom); + ray_release(atom); + TEST_ASSERT(n != NULL, "symbol constant"); + uint32_t sym_id = n->id; + uint32_t bad[4]; + n = ray_const_i64(g, 1); TEST_ASSERT(n != NULL, "integer constant"); bad[0] = n->id; + n = ray_const_bool(g, true); TEST_ASSERT(n != NULL, "bool constant"); bad[1] = n->id; + n = ray_const_f64(g, 1.0); TEST_ASSERT(n != NULL, "float constant"); bad[2] = n->id; + n = ray_const_i64(g, NULL_I64); TEST_ASSERT(n != NULL, "typed null"); bad[3] = n->id; + for (int op = 0; op < 2; op++) { + for (int i = 0; i < 4; i++) { + for (int reverse = 0; reverse < 2; reverse++) { + uint32_t a = reverse ? bad[i] : sym_id; + uint32_t b = reverse ? sym_id : bad[i]; + ray_op_t* out = op ? ray_ne(g, &g->nodes[a], &g->nodes[b]) + : ray_eq(g, &g->nodes[a], &g->nodes[b]); + TEST_ASSERT(out == NULL, "mixed symbol pair must decline"); + TEST_ASSERT(ray_binop(g, op ? OP_NE : OP_EQ, + &g->nodes[a], &g->nodes[b]) == NULL, + "generic comparison must also decline"); + } + } + } + TEST_ASSERT(g->compile_err == NULL, "decline is not a language error"); + uint32_t good[3]; + n = ray_const_str(g, "alpha", 5); TEST_ASSERT(n != NULL, "text literal"); good[0] = n->id; + ray_t* text = ray_vec_new(RAY_STR, 1); + TEST_ASSERT(text && !RAY_IS_ERR(text), "text vector"); + text = ray_str_vec_append(text, "alpha", 5); + TEST_ASSERT(text && !RAY_IS_ERR(text), "text cell"); + n = ray_const_vec(g, text); ray_release(text); + TEST_ASSERT(n != NULL, "text-vector constant"); good[1] = n->id; + atom = ray_sym(0); n = ray_const_atom(g, atom); ray_release(atom); + TEST_ASSERT(n != NULL, "null symbol"); good[2] = n->id; + for (int op = 0; op < 2; op++) { + for (int i = 0; i < 3; i++) { + for (int reverse = 0; reverse < 2; reverse++) { + uint32_t a = reverse ? good[i] : sym_id; + uint32_t b = reverse ? sym_id : good[i]; + TEST_ASSERT(ray_binop(g, op ? OP_NE : OP_EQ, + &g->nodes[a], &g->nodes[b]) != NULL, + "symbol/text admission retained"); + } + } + } + n = ray_scan(g, "unbound"); TEST_ASSERT(n != NULL, "unbound scan"); + uint32_t unknown = n->id; + TEST_ASSERT_EQ_I(n->out_type, 0); + TEST_ASSERT(ray_eq(g, &g->nodes[sym_id], &g->nodes[unknown]) == NULL, + "unknown source needs evaluator fallback"); + TEST_ASSERT(ray_ne(g, &g->nodes[unknown], &g->nodes[sym_id]) == NULL, + "reverse unknown source needs fallback"); + TEST_ASSERT(ray_eq(g, &g->nodes[unknown], &g->nodes[good[0]]) != NULL, + "text literal is not a real symbol operand"); + TEST_ASSERT(ray_ne(g, &g->nodes[good[0]], &g->nodes[unknown]) != NULL, + "reverse text literal keeps existing admission"); + ray_graph_free(g); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* Direct proof fixtures intentionally do not execute or optimize malformed DAGs. */ +static test_result_t test_subset_proof_pointwise(void) { + ray_heap_init(); + ray_t* tbl = make_test_table(); + int64_t labels[10]; + for (int i = 0; i < 10; i++) labels[i] = ray_sym_intern("abc", 3); + ray_t* strings = ray_vec_from_raw(RAY_SYM, labels, 10); + tbl = ray_table_add_col(tbl, ray_sym_intern("label", 5), strings); + ray_release(strings); + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* x = ray_scan(g, "v1"); + ray_op_t* c = ray_const_i64(g, 2); + ray_op_t* add = ray_add(g, x, c); + ray_op_t* cmp = ray_gt(g, add, c); + ray_op_t* shared = ray_and(g, cmp, cmp); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, shared->id)); + ray_op_t* scalar = ray_add(g, c, c); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, scalar->id)); + ray_op_t* text = ray_const_str(g, "ab*", 3); + ray_op_t* strcol = ray_scan(g, "label"); + ray_op_t* upper = ray_upper(g, strcol); + ray_op_t* like = ray_like(g, upper, text); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, like->id)); + ray_op_t* ilike = ray_ilike(g, strcol, text); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, ilike->id)); + ray_op_t* args[] = {strcol, text}; + ray_op_t* concat = ray_concat(g, args, 2); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, concat->id)); + ray_op_t* length = ray_strlen(g, text); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, length->id)); + /* Same table object still has alternate-source provenance. */ + uint16_t tid = ray_graph_add_table(g, tbl); + ray_op_t* foreign = ray_scan_table(g, tid, "v1"); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, foreign->id)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(NULL, 0)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, RAY_OP_NONE)); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +static test_result_t test_subset_proof_membership_roles(void) { + ray_heap_init(); + ray_t* tbl = make_test_table(); + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* x = ray_scan(g, "v1"); + ray_op_t* c = ray_const_i64(g, 1); + int64_t raw[] = {1, 2, 3}; + ray_t* v = ray_vec_from_raw(RAY_I64, raw, 3); + ray_op_t* set = ray_const_vec(g, v); + ray_release(v); + ray_op_t* in = ray_in(g, x, set); + ray_op_t* notin = ray_not_in(g, x, set); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, in->id)); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, notin->id)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, set->id)); + ray_op_t* misuse = ray_eq(g, x, set); + ray_op_t* both = ray_and(g, in, misuse); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, both->id)); + /* Set success in one edge/call must never certify a vector value edge. */ + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, in->id)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, misuse->id)); + ray_op_t* scalar_in = ray_in(g, c, set); + ray_op_t* column_set = ray_in(g, x, x); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, scalar_in->id)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, column_set->id)); + v = ray_vec_from_raw(RAY_I64, raw, 1); + ray_op_t* onevec = ray_const_vec(g, v); + ray_release(v); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, onevec->id)); + v = ray_vec_new(RAY_I64, 0); + ray_op_t* empty = ray_const_vec(g, v); + ray_release(v); + ray_op_t* empty_in = ray_in(g, x, empty); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, empty_in->id)); + v = ray_list_new(0); + ray_op_t* list = ray_const_vec(g, v); + ray_release(v); + ray_op_t* list_in = ray_in(g, x, list); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, list_in->id)); + ray_op_t* table = ray_const_table(g, tbl); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, table->id)); + /* ray_is_atom also accepts positive object types: those are not data. */ + ray_op_ext_t* ce = find_ext(g, c->id); + int8_t saved_type = ce->literal->type; + ce->literal->type = RAY_UNARY; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, c->id)); + ce->literal->type = saved_type; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, c->id)); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +static test_result_t test_subset_proof_hidden_crossrow(void) { + ray_heap_init(); + ray_t* tbl = make_test_table(); + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* zero = ray_const_i64(g, 0); /* ID 0 is a required third child */ + TEST_ASSERT_EQ_I(zero->id, 0); + ray_op_t* x = ray_scan(g, "v1"); + ray_op_t* safe = ray_gt(g, x, zero); + ray_op_t* choose = ray_if(g, safe, x, zero); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, choose->id)); + ray_op_ext_t* e = find_ext(g, choose->id); + e->third_in = RAY_OP_NONE; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, choose->id)); + e->third_in = 0; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, choose->id)); + ray_op_t* scalar_cond = ray_const_bool(g, true); + ray_op_t* ambiguous = ray_if(g, scalar_cond, x, zero); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, ambiguous->id)); + ray_op_t* avg = ray_avg(g, x); + ray_op_t* running = ray_sums_op(g, x); + ray_op_t* badavg = ray_gt(g, x, avg); + ray_op_t* badrun = ray_gt(g, running, zero); + ray_op_t* nest = ray_and(g, safe, safe); + ray_op_t* whole = ray_and(g, nest, badavg); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, whole->id)); + whole = ray_and(g, badrun, nest); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, whole->id)); + e->third_in = badrun->id; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, choose->id)); + e->third_in = badavg->id; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, choose->id)); + ray_op_t* filter = ray_filter(g, x, safe); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, filter->id)); + ray_op_t* text = ray_const_str(g, "x", 1); + ray_op_t* args[] = {text, text, badrun}; + ray_op_t* concat = ray_concat(g, args, 3); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, concat->id)); + /* Even safe long CONCAT is refused: no recorded tail allocation size. */ + args[2] = text; + concat = ray_concat(g, args, 3); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, concat->id)); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +static test_result_t test_subset_proof_malformed_and_cycles(void) { + ray_heap_init(); + ray_t* tbl = make_test_table(); + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* x = ray_scan(g, "v1"); + ray_op_t* c = ray_const_i64(g, 1); + ray_op_t* pred = ray_gt(g, x, c); + uint32_t pid = pred->id; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, pid)); + x->flags |= OP_FLAG_DEAD; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + x->flags &= ~OP_FLAG_DEAD; + x->flags |= OP_FLAG_INVALID_SCAN; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + x->flags &= ~OP_FLAG_INVALID_SCAN; + pred->arity = 1; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + pred->arity = 2; + pred->in_id[1] = g->node_count; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + pred->in_id[1] = pid; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); /* self cycle */ + pred->in_id[1] = c->id; + ray_op_t* neg = ray_neg(g, pred); + pred->in_id[1] = neg->id; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); /* two-node cycle */ + pred->in_id[1] = c->id; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, pid)); + uint32_t saved_id = x->id; + x->id = c->id; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + x->id = saved_id; + ray_op_ext_t* xe = find_ext(g, x->id); + uint16_t source = UINT16_MAX; + memcpy(xe->base.pad, &source, sizeof(source)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + source = 0; + memcpy(xe->base.pad, &source, sizeof(source)); + /* Unused input slots may be zero; only required edges are traversed. */ + x->in_id[0] = x->in_id[1] = 0; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, pid)); + ray_t* literal = find_ext(g, c->id)->literal; + find_ext(g, c->id)->literal = NULL; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + find_ext(g, c->id)->literal = literal; + uint32_t ext_count = g->ext_count; + g->ext_count = 0; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, pid)); + g->ext_count = ext_count; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, pid)); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +static test_result_t test_subset_proof_budgets(void) { + ray_heap_init(); + ray_t* tbl = make_test_table(); + ray_graph_t* g = ray_graph_new(tbl); + uint32_t root = ray_scan(g, "v1")->id; + for (int i = 0; i < 63; i++) root = ray_neg(g, &g->nodes[root])->id; + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, root)); + root = ray_neg(g, &g->nodes[root])->id; + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, root)); + while (g->node_count < 4096) (void)ray_const_i64(g, 1); + TEST_ASSERT_TRUE(ray_expr_subset_invariant(g, 0)); + (void)ray_const_i64(g, 1); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(g, 0)); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* Deterministic subset oracle: generator choices below are NOT the trait's + * whitelist. Only the dedicated SUM self-control bypasses admission. */ +static void subset_drop(ray_t* v) { + if (v && RAY_IS_ERR(v)) ray_error_free(v); + else ray_release(v); +} + +static bool subset_ok(ray_t* v) { return v && !RAY_IS_ERR(v); } + +/* Copy every column, without asking filtering/selection code for the oracle. */ +static ray_t* subset_table(ray_t* src, const int* rows, int n) { + static const char* names[] = {"rid", "x", "y", "b"}; + ray_t* t = ray_table_new(4); + if (!subset_ok(t)) return t; + for (int c = 0; c < 4; c++) { + ray_t* v = ray_vec_new(c == 3 ? RAY_BOOL : RAY_I64, n); + if (!subset_ok(v)) { subset_drop(t); return v; } + v->len = n; + v->attrs &= ~RAY_ATTR_HAS_NULLS; + ray_t* from = src ? ray_table_col_idx(src, c) : NULL; /* borrowed */ + if (src && !subset_ok(from)) { ray_error_free(from); subset_drop(v); subset_drop(t); return NULL; } + for (int j = 0; j < n; j++) { + int i = rows ? rows[j] : j; + if (c == 3) { + ((uint8_t*)ray_data(v))[j] = src ? ((uint8_t*)ray_data(from))[i] : i % 2; + } else { + int64_t x = src ? ((int64_t*)ray_data(from))[i] : + c == 0 ? 100 + i : c == 1 ? i % 7 - 3 : (i * 3) % 7 - 3; + if (!src && ((c == 1 && (i == 1 || i == 8)) || (c == 2 && i == 4))) x = NULL_I64; + ((int64_t*)ray_data(v))[j] = x; + if (x == NULL_I64) v->attrs |= RAY_ATTR_HAS_NULLS; + } + } + int64_t name = ray_sym_intern(names[c], strlen(names[c])); + if (name < 0) { subset_drop(v); subset_drop(t); return NULL; } + t = ray_table_add_col(t, name, v); /* consumes table, retains vector */ + subset_drop(v); + if (!subset_ok(t)) return t; + } + return t; +} + +static bool subset_rids(ray_t* t, ray_t* u, const int* rows, int n) { + if (ray_table_nrows(u) != n) return false; + ray_t* a = ray_table_col_idx(t, 0); + ray_t* b = ray_table_col_idx(u, 0); + if (!subset_ok(a) || !subset_ok(b) || b->type != RAY_I64 || b->len != n) return false; + for (int j = 0; j < n; j++) + if (((int64_t*)ray_data(a))[rows[j]] != ((int64_t*)ray_data(b))[j]) return false; + return true; +} + +static bool subset_shape(ray_t* v, int n, bool scalar_recipe) { + if (!subset_ok(v)) return false; + if (v->type == -RAY_BOOL) return RAY_ATOM_IS_NULL(v) || v->b8 <= 1; + /* Scalar-only binary evaluation may return a one-cell BOOL vector. + * Broadcast it only for recipes known to have no row-valued input; + * a literal/row-valued one-cell vector is not proof of scalar shape. */ + if (v->type != RAY_BOOL || (v->len != n && !(scalar_recipe && v->len == 1))) return false; + for (int64_t i = 0; i < v->len; i++) if (((uint8_t*)ray_data(v))[i] > 1) return false; + return true; +} + +/* Logical cell codes: null=2, false=0, true=1. Never read null atom payload. */ +static int subset_cell(ray_t* v, int i) { + return v->type == -RAY_BOOL ? (RAY_ATOM_IS_NULL(v) ? 2 : v->b8) : ((uint8_t*)ray_data(v))[v->len == 1 ? 0 : i]; +} + +static bool subset_equal(ray_t* a, ray_t* b, const int* rows, int n, int* bad) { + for (int j = 0; j < n; j++) { + int x = subset_cell(a, rows[j]), y = subset_cell(b, j); + if (x > 2 || y > 2 || x != y) { *bad = j; return false; } + } + return true; +} + +typedef ray_op_t* (*subset_binary_t)(ray_graph_t*, ray_op_t*, ray_op_t*); + +/* One small topological recipe, with seeded source/operator choices. IDs, not + * node pointers, survive growth. Repeated indices preserve DAG sharing. Finite + * inputs <=3 and arithmetic depth<=3 bound magnitude by 6561. */ +static bool subset_recipe(ray_graph_t* g, uint32_t seed, int root, uint32_t* out) { + static subset_binary_t arith[] = {ray_add, ray_sub, ray_mul}; + static subset_binary_t cmp[] = {ray_eq, ray_ne, ray_lt, ray_le, ray_gt, ray_ge}; + uint32_t ids[37] = {0}; + uint32_t rng = seed; + for (int i = 0; i <= root; i++) { + ray_op_t* p = NULL; + ray_t* tmp = NULL; +#define SP_NODE(k) (&g->nodes[ids[(k)]]) + rng = rng * 1664525u + 1013904223u; /* fixed unsigned draw per node */ + switch (i) { + case 0: p = ray_scan(g, "x"); break; + case 1: p = ray_scan(g, "y"); break; + case 2: p = ray_scan(g, "b"); break; + case 3: p = ray_const_i64(g, (int64_t)(rng % 7) - 3); break; + case 4: p = ray_const_i64(g, NULL_I64); break; + case 5: case 6: p = ray_const_bool(g, i == 6); break; + case 7: + tmp = ray_typed_null(-RAY_BOOL); + if (subset_ok(tmp)) p = ray_const_atom(g, tmp); + break; + case 8: { + int64_t set[] = {-3, 0, 3, NULL_I64}; + tmp = ray_vec_from_raw(RAY_I64, set, seed % 3 == 0 ? 0 : seed % 3 == 1 ? 3 : 4); + if (subset_ok(tmp)) { + tmp->attrs &= ~RAY_ATTR_HAS_NULLS; + if (tmp->len == 4) tmp->attrs |= RAY_ATTR_HAS_NULLS; + p = ray_const_vec(g, tmp); + } + break; + } + case 9: p = arith[rng % 3](g, SP_NODE(rng % 2), SP_NODE(3)); break; + case 10: case 11: p = arith[rng % 3](g, SP_NODE(i - 1), SP_NODE(i - 1)); break; + case 12: case 13: case 14: case 15: case 16: case 17: + p = cmp[i - 12](g, SP_NODE(11), SP_NODE((rng & 1) ? 3 : 4)); break; + case 18: p = ray_and(g, SP_NODE(12), SP_NODE(13)); break; + case 19: p = ray_or(g, SP_NODE(14), SP_NODE(15)); break; + case 20: p = ray_not(g, SP_NODE(19)); break; + case 21: p = ray_if(g, SP_NODE(2), SP_NODE(9), SP_NODE(1)); break; + case 22: p = ray_gt(g, SP_NODE(21), SP_NODE(4)); break; + case 23: p = ray_if(g, SP_NODE(18), SP_NODE(22), SP_NODE(20)); break; + case 24: p = ray_and(g, SP_NODE(23), SP_NODE(23)); break; + case 25: p = ray_in(g, SP_NODE(0), SP_NODE(8)); break; + case 26: p = ray_sum(g, SP_NODE(0)); break; + case 27: p = ray_gt(g, SP_NODE(0), SP_NODE(26)); break; + case 28: p = ray_sums_op(g, SP_NODE(0)); break; + case 29: p = ray_gt(g, SP_NODE(28), SP_NODE(3)); break; + case 30: { + uint16_t tid = ray_graph_add_table(g, g->table); + if (tid == UINT16_MAX) return false; + p = ray_scan_table(g, tid, "x"); break; + } + case 31: p = ray_gt(g, SP_NODE(30), SP_NODE(3)); break; + case 32: p = ray_and(g, SP_NODE(18), SP_NODE(27)); break; + case 33: p = ray_if(g, SP_NODE(2), SP_NODE(29), SP_NODE(18)); break; + case 34: p = ray_eq(g, SP_NODE(4), SP_NODE(4)); break; + case 35: p = ray_ne(g, SP_NODE(4), SP_NODE(3)); break; + case 36: p = ray_lt(g, SP_NODE(4), SP_NODE(3)); break; + } +#undef SP_NODE + subset_drop(tmp); + if (!p) return false; + ids[i] = p->id; + if (p->opcode == OP_CONST && !subset_ok(find_ext(g, p->id)->literal)) return false; + } + *out = ids[root]; + return true; +} + +typedef struct { ray_t* t[2]; ray_t* v[2]; ray_graph_t* g; } subset_fixture_t; + +static test_result_t subset_property_body(subset_fixture_t* f) { + static const int roots[] = {2, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 34, 35, 36}; + static const int negatives[] = {27, 29, 31, 32, 33}; + static const int masks[5][17] = { + {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}, {0}, {8}, + {0,2,4,6,8,10,12,14,16}, {1,3,4,8,12,15} + }; + static const int sizes[] = {17, 0, 1, 9, 6}; + unsigned coverage = 0, executed = 0, declined = 0; + f->t[0] = subset_table(NULL, NULL, 17); + TEST_ASSERT_TRUE(subset_ok(f->t[0])); + for (int c = 0; c < 6; c++) { + uint32_t seed = 904u + (uint32_t)c; + for (int r = 0; r < 20; r++) { + bool admitted = false; + for (int m = 0; m < 5; m++) { + f->t[1] = subset_table(f->t[0], masks[m], sizes[m]); + TEST_ASSERT_TRUE(subset_ok(f->t[1])); + TEST_ASSERT_TRUE(subset_rids(f->t[0], f->t[1], masks[m], sizes[m])); + for (int side = 0; side < 2; side++) { + f->g = ray_graph_new(f->t[side]); + TEST_ASSERT_NOT_NULL(f->g); + uint32_t id; + TEST_ASSERT_FMT(subset_recipe(f->g, seed, roots[r], &id), + "seed=%u root=%d mask=%d side=%d recipe failed: %s", seed, roots[r], m, side, + ray_error_msg() ? ray_error_msg() : "no error message"); + bool accept = ray_expr_subset_invariant(f->g, id); + if (side == 0) admitted = accept; + else TEST_ASSERT_EQ_I(accept, admitted); + if (accept) { + f->v[side] = ray_execute(f->g, &f->g->nodes[id]); + TEST_ASSERT_FMT(subset_shape(f->v[side], side ? sizes[m] : 17, (roots[r] >= 5 && roots[r] <= 7) || roots[r] >= 34), + "seed=%u root=%d mask=%d side=%d invalid BOOL result type=%d attrs=%u payload=%lld err=%s", + seed, roots[r], m, side, f->v[side] ? f->v[side]->type : 0, + f->v[side] ? (unsigned)f->v[side]->attrs : 0, + subset_ok(f->v[side]) ? (long long)f->v[side]->i64 : 0, + ray_error_msg() ? ray_error_msg() : "none"); + } + ray_graph_free(f->g); f->g = NULL; + } + if (admitted) { + int bad = -1; + TEST_ASSERT_FMT(subset_equal(f->v[0], f->v[1], masks[m], sizes[m], &bad), + "seed=%u root=%d mask=%d cell=%d rid=%d full=%d subset=%d", seed, roots[r], m, bad, + bad < 0 ? -1 : 100 + masks[m][bad], + bad < 0 ? -1 : subset_cell(f->v[0], masks[m][bad]), + bad < 0 ? -1 : subset_cell(f->v[1], bad)); + /* Pin scalar/null behavior and the engine's null ordering, + * independently of two executions agreeing with each other. */ + if (r >= 1 && r <= 3) + TEST_ASSERT_EQ_I(subset_cell(f->v[0], 0), r == 1 ? 0 : r == 2 ? 1 : 2); + if (r >= 17) TEST_ASSERT_EQ_I(subset_cell(f->v[0], 0), 1); + coverage |= 1u << r; executed++; + } else declined++; + for (int side = 0; side < 2; side++) { subset_drop(f->v[side]); f->v[side] = NULL; } + subset_drop(f->t[1]); f->t[1] = NULL; + } + if (r < 4) TEST_ASSERT_TRUE(admitted); /* scan + scalar/broadcast/null controls */ + } + } + TEST_ASSERT_FMT(executed > 0 && coverage == (1u << 20) - 1, + "coverage=%x executed=%u declined=%u", coverage, executed, declined); + for (int i = 0; i < 5; i++) { + uint32_t id; + f->g = ray_graph_new(f->t[0]); + TEST_ASSERT_NOT_NULL(f->g); + TEST_ASSERT_TRUE(subset_recipe(f->g, 904, negatives[i], &id)); + TEST_ASSERT_FALSE(ray_expr_subset_invariant(f->g, id)); + ray_graph_free(f->g); f->g = NULL; + } + /* Independent known-nonlocal oracle: full SUM=0, subset SUM=3. + * Deliberately bypass the trait ONLY here, on well-typed graphs. */ + subset_drop(f->t[0]); f->t[0] = subset_table(NULL, NULL, 3); + TEST_ASSERT_TRUE(subset_ok(f->t[0])); + ray_t* x = ray_table_col_idx(f->t[0], 1); + int64_t values[] = {1, -3, 2}; + memcpy(ray_data(x), values, sizeof(values)); x->attrs &= ~RAY_ATTR_HAS_NULLS; + const int pick[] = {0, 2}; + f->t[1] = subset_table(f->t[0], pick, 2); + TEST_ASSERT_TRUE(subset_ok(f->t[1])); + TEST_ASSERT_TRUE(subset_rids(f->t[0], f->t[1], pick, 2)); + ray_t* rid = ray_table_col_idx(f->t[1], 0); + ((int64_t*)ray_data(rid))[0]++; + TEST_ASSERT_FALSE(subset_rids(f->t[0], f->t[1], pick, 2)); + ((int64_t*)ray_data(rid))[0]--; + ((int64_t*)ray_data(rid))[1]++; + TEST_ASSERT_FALSE(subset_rids(f->t[0], f->t[1], pick, 2)); + ((int64_t*)ray_data(rid))[1]--; + for (int side = 0; side < 2; side++) { + uint32_t id; + f->g = ray_graph_new(f->t[side]); + TEST_ASSERT_NOT_NULL(f->g); + TEST_ASSERT_TRUE(subset_recipe(f->g, 904, 27, &id)); + f->v[side] = ray_execute(f->g, &f->g->nodes[id]); + TEST_ASSERT_TRUE(subset_shape(f->v[side], side ? 2 : 3, false)); + ray_graph_free(f->g); f->g = NULL; + } + for (int j = 0; j < 2; j++) { + TEST_ASSERT_EQ_I(subset_cell(f->v[0], pick[j]), 1); + TEST_ASSERT_EQ_I(subset_cell(f->v[1], j), 0); + } + int bad = -1; + TEST_ASSERT_FALSE(subset_equal(f->v[0], f->v[1], pick, 2, &bad)); + TEST_ASSERT_EQ_I(bad, 0); + /* Comparator sensitivity without relying on admission or engine mutation. */ + subset_drop(f->v[1]); + uint8_t flipped[] = {1, 1}; + f->v[1] = ray_vec_from_raw(RAY_BOOL, flipped, 2); + TEST_ASSERT_TRUE(subset_shape(f->v[1], 2, false)); + TEST_ASSERT_TRUE(subset_equal(f->v[0], f->v[1], pick, 2, &bad)); + ((uint8_t*)ray_data(f->v[1]))[1] = 0; + TEST_ASSERT_FALSE(subset_equal(f->v[0], f->v[1], pick, 2, &bad)); + TEST_ASSERT_EQ_I(bad, 1); + PASS(); +} + +static test_result_t test_subset_property(void) { + subset_fixture_t f = {0}; + ray_heap_init(); + test_result_t result; + if (ray_sym_init() != RAY_OK) result = (test_result_t){TEST_FAIL, "subset sym init"}; + else result = subset_property_body(&f); + if (f.g) ray_graph_free(f.g); + for (int i = 0; i < 2; i++) { subset_drop(f.v[i]); subset_drop(f.t[i]); } + ray_sym_destroy(); + ray_heap_destroy(); + return result; +} + /* * Test: filter with AND-combined predicates in "wrong" order. * @@ -2633,7 +3206,84 @@ static test_result_t test_type_infer_unary(void) { PASS(); } +/* A source-domain-dependent predicate is a boundary, not a rankable cheap + * comparison. The equality on AVG would otherwise sort ahead of a range. */ +static test_result_t test_filter_domain_barriers(void) { + ray_heap_init(); + (void)ray_sym_init(); + ray_t* tbl = make_test_table(); + ray_graph_t* g = ray_graph_new(tbl); + uint32_t input = ray_const_table(g, tbl)->id; + uint32_t scan = ray_scan(g, "v1")->id; + uint32_t threshold = ray_const_i64(g, 50)->id; + uint32_t scalar = ray_const_f64(g, 80.0)->id; + uint32_t pointwise = ray_gt(g, &g->nodes[scan], &g->nodes[threshold])->id; + uint32_t avg = ray_avg(g, &g->nodes[scan])->id; + uint32_t nonlocal = ray_eq(g, &g->nodes[avg], &g->nodes[scalar])->id; + uint32_t inner = ray_filter(g, &g->nodes[input], &g->nodes[pointwise])->id; + ray_op_t* root = ray_filter(g, &g->nodes[inner], &g->nodes[nonlocal]); + root = ray_optimize(g, root); + TEST_ASSERT_NOT_NULL(root); + TEST_ASSERT_EQ_I(root->opcode, OP_FILTER); + TEST_ASSERT_EQ_I(root->in_id[1], nonlocal); + TEST_ASSERT_EQ_I(g->nodes[inner].in_id[1], pointwise); + ray_graph_free(g); + + /* No extracting a safe inner limb of an unsafe whole conjunction. */ + g = ray_graph_new(tbl); + input = ray_const_table(g, tbl)->id; + scan = ray_scan(g, "v1")->id; + threshold = ray_const_i64(g, 50)->id; + scalar = ray_const_f64(g, 80.0)->id; + pointwise = ray_gt(g, &g->nodes[scan], &g->nodes[threshold])->id; + avg = ray_avg(g, &g->nodes[scan])->id; + nonlocal = ray_eq(g, &g->nodes[avg], &g->nodes[scalar])->id; + uint32_t conjunction = ray_and(g, &g->nodes[pointwise], &g->nodes[nonlocal])->id; + root = ray_filter(g, &g->nodes[input], &g->nodes[conjunction]); + root = ray_optimize(g, root); + TEST_ASSERT_NOT_NULL(root); + int filters = 0; + for (uint32_t i = 0; i < g->node_count; i++) + if (!(g->nodes[i].flags & OP_FLAG_DEAD) && g->nodes[i].opcode == OP_FILTER) + filters++; + TEST_ASSERT_EQ_I(filters, 1); + TEST_ASSERT_EQ_I(g->nodes[root->in_id[1]].opcode, OP_AND); + ray_graph_free(g); + + /* Positive route control: don't repair this by disabling all splitting. */ + g = ray_graph_new(tbl); + input = ray_const_table(g, tbl)->id; + scan = ray_scan(g, "v1")->id; + uint32_t scan2 = ray_scan(g, "id1")->id; + threshold = ray_const_i64(g, 50)->id; + uint32_t one = ray_const_i64(g, 1)->id; + pointwise = ray_gt(g, &g->nodes[scan], &g->nodes[threshold])->id; + uint32_t other = ray_eq(g, &g->nodes[scan2], &g->nodes[one])->id; + conjunction = ray_and(g, &g->nodes[pointwise], &g->nodes[other])->id; + root = ray_filter(g, &g->nodes[input], &g->nodes[conjunction]); + root = ray_optimize(g, root); + TEST_ASSERT_NOT_NULL(root); + filters = 0; + for (uint32_t i = 0; i < g->node_count; i++) + if (!(g->nodes[i].flags & OP_FLAG_DEAD) && g->nodes[i].opcode == OP_FILTER) + filters++; + TEST_ASSERT_EQ_I(filters, 2); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + const test_entry_t opt_entries[] = { + { "opt/sym_compare_admission", test_sym_compare_admission, NULL, NULL }, + { "opt/subset_property", test_subset_property, NULL, NULL }, + { "opt/filter_domain_barriers", test_filter_domain_barriers, NULL, NULL }, + { "opt/subset_proof_pointwise", test_subset_proof_pointwise, NULL, NULL }, + { "opt/subset_proof_membership_roles", test_subset_proof_membership_roles, NULL, NULL }, + { "opt/subset_proof_hidden_crossrow", test_subset_proof_hidden_crossrow, NULL, NULL }, + { "opt/subset_proof_malformed_and_cycles", test_subset_proof_malformed_and_cycles, NULL, NULL }, + { "opt/subset_proof_budgets", test_subset_proof_budgets, NULL, NULL }, { "opt/filter_reorder_type", test_filter_reorder_by_type, NULL, NULL }, { "opt/filter_and_split", test_filter_and_split, NULL, NULL }, { "opt/filter_reorder_dag", test_filter_reorder_dag, NULL, NULL }, diff --git a/test/test_parquet.c b/test/test_parquet.c index 6dbad7054..1ca0c1cc8 100644 --- a/test/test_parquet.c +++ b/test/test_parquet.c @@ -8,6 +8,8 @@ #include "mem/heap.h" #include "mem/sys.h" #include "table/sym.h" +#include "table/table.h" +#include "table/domain.h" /* ray_sym_domain_path: a column's own symbol file */ #include "store/part.h" #include "store/splay.h" #include "ops/idxop.h" @@ -19,6 +21,7 @@ #include #include #include +#include #if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) #include #include /* the skeptic probes' child imports */ @@ -319,8 +322,8 @@ static test_result_t test_pq_parallel(void) { static void pq_remove_native(const char* dir, const char** columns, int n) { char path[512]; for (int i = 0; i < n; i++) { snprintf(path,sizeof(path),"%s/%s",dir,columns[i]); unlink(path); } - const char* special[] = {".d",".sym",".sym.lk"}; - for (int i = 0; i < 3; i++) { snprintf(path,sizeof(path),"%s/%s",dir,special[i]); unlink(path); } + const char* special[] = {".d",".sym",".sym.lk",".sym.ix"}; + for (int i = 0; i < 4; i++) { snprintf(path,sizeof(path),"%s/%s",dir,special[i]); unlink(path); } rmdir(dir); } /* The direct import picks its pass layout from memory; RAY_PQ_PASS_COLS @@ -815,7 +818,7 @@ static void* pq_small_stack_worker(void* result) { } #endif /* Direct path: 7 uneven row groups merge into the whole-column zone; the - * unclustered column with nulls gets a hash. */ + * unclustered column with nulls keeps its zone (no converter HASH). */ static test_result_t test_pq_splayed_inline_indexes(void) { const char* names[] = {"x","y"}; for (int run = 0; run < 4; run++) { @@ -843,13 +846,49 @@ static test_result_t test_pq_splayed_inline_indexes(void) { if (w->u.chunk_zone.null_bits) TEST_ASSERT_EQ_I(memcmp(ray_data(g->u.chunk_zone.null_bits),ray_data(w->u.chunk_zone.null_bits),(size_t)((g->u.chunk_zone.n_chunks+7)/8)),0); ray_release(want); ray_release(plain); - TEST_ASSERT_EQ_I(ray_index_kind(ray_table_get_col_idx(table,1)),RAY_IDX_HASH); + /* index policy: the converter persists no HASH of its own */ + { ray_col_meta_t m1; TEST_ASSERT_TRUE(ray_table_col_meta_idx(table,1,&m1)); + TEST_ASSERT_EQ_I(m1.index_kind,RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_EQ_I(ray_index_kind(ray_table_get_col_idx(table,1)),RAY_IDX_CHUNK_ZONE); } ray_release(table); pq_remove_native(dir,names,2); ray_pool_destroy(); } PASS(); } +/* Smoke test: the parted Parquet conversion persists no HASH in any segment. + * zones.parquet's row groups (30-40K rows) are below one chunk, so the auto + * heuristic cannot fire here; the policy itself is pinned by + * store/staged_bulk_no_hash, which exercises the save this route uses. The + * pin is still live: forcing an explicit hash onto each decoded batch in + * pq_write_reader makes it fail ("column 1 segment 0"). */ +static test_result_t test_pq_parted_no_segment_hash(void) { + char root[160]; + snprintf(root, sizeof(root), "%s", ray_test_tmp("/tmp/rayforce-pq-nohash")); + (void)ray_test_rm_rf(root); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_t* r = ray_parquet_parted_typed(FIX "zones.parquet", root, "t", NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); TEST_ASSERT_EQ_I(r->i64, 200000); ray_release(r); + ray_t* t = ray_read_parted(root, "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + int nparted = 0; + for (int64_t c = 0; c < ray_table_ncols(t); c++) { + ray_t* w = ray_table_get_col_idx(t, c); + TEST_ASSERT_TRUE(w != NULL); + if (!RAY_IS_PARTED(w->type)) continue; /* the virtual partition-key column */ + nparted++; + ray_t** segs = (ray_t**)ray_data(w); + for (int64_t s = 0; s < w->len; s++) + TEST_ASSERT_FMT(!segs[s] || ray_index_kind(segs[s]) != RAY_IDX_HASH, + "column %lld segment %lld", (long long)c, (long long)s); + } + TEST_ASSERT_TRUE(nparted >= 2); + ray_release(t); + ray_pool_destroy(); + (void)ray_test_rm_rf(root); + PASS(); +} + static test_result_t test_pq_small_stack(void) { #if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) ray_pool_destroy(); @@ -869,7 +908,6 @@ static test_result_t test_pq_small_stack(void) { #if defined(__linux__) #include #include -#include /* A row group's chunk ends with a flush of the bytes its stream still * buffers (glibc writes whole blocks of a large write at once and keeps the * tail). The file size limit here falls inside that tail of the first @@ -2013,7 +2051,7 @@ static void pqx_snappy(pq_buf* o, const uint8_t* s, size_t n) { i += len; lit = i; } else i++; } - pqx_lit(o, s + lit, n - lit); + if (n > lit) pqx_lit(o, s + lit, n - lit); /* no literal of no data (s may be NULL) */ } /* pqx_page's checksums (PQX_CRC, PQX_CRCFLIP): 0 none; 1 each page's * CRC-32 in its header (PageHeader 4); 2 that, and a dictionary page's @@ -3630,6 +3668,202 @@ static test_result_t test_pq_worker_messages(void) { TEST_ASSERT_EQ_I(bad, 0); PASS(); } +/* The entries of a symbol file (its header count), -1 if it cannot be read. */ +static int64_t pq_symfile_count(const char* path) { + FILE* f = fopen(path, "rb"); + uint8_t head[12]; + int64_t count = -1; + if (f && fread(head, 1, 12, f) == 12) memcpy(&count, head + 4, 8); + if (f) fclose(f); + return count; +} +/* An import under symfile 'column: its column symbol files too. */ +static void pq_remove_symcol(const char* dir, const char** columns, int n) { + char path[512]; + const char* sfx[] = {"", ".ix", ".lk"}; + for (int i = 0; i < n; i++) + for (int k = 0; k < 3; k++) { snprintf(path, sizeof(path), "%s/.%s.sym%s", dir, columns[i], sfx[k]); unlink(path); } + pq_remove_native(dir, columns, n); +} +/* {types: [...] symfile: 'column}, with compress: true when asked. */ +static ray_t* pq_symcol_opts(ray_t* types, const char* layout, bool compress) { + int64_t keys[3] = {ray_sym_intern("types",5), ray_sym_intern("symfile",7), ray_sym_intern("compress",8)}; + int n = compress ? 3 : 2; + ray_t* values = ray_list_new(n); + ray_retain(types); + ((ray_t**)ray_data(values))[0] = types; + ((ray_t**)ray_data(values))[1] = ray_sym(ray_sym_intern(layout, strlen(layout))); + if (compress) ((ray_t**)ray_data(values))[2] = ray_bool(true); + values->len = n; + return ray_dict_new(ray_vec_from_raw(RAY_SYM, keys, n), values); +} +/* The distinct strings of column c of the shared import at `dir` (its + * positions in the one .sym), with "" counted once: what that column's own + * symbol file holds. */ +static int64_t pq_col_distinct(const char* dir, int c) { + char sym[200]; snprintf(sym, sizeof(sym), "%s/.sym", dir); + int64_t words = pq_symfile_count(sym); + ray_t* t = ray_read_splayed(dir, sym); + if (words <= 0 || !t || RAY_IS_ERR(t)) { if (t && RAY_IS_ERR(t)) ray_error_free(t); else if (t) ray_release(t); return -1; } + uint8_t* seen = (uint8_t*)ray_sys_alloc((size_t)words); + int64_t n = 1; /* "" at position 0 */ + ray_t* col = ray_table_get_col_idx(t, c); + if (seen && col) { + memset(seen, 0, (size_t)words); + seen[0] = 1; + for (int64_t r = 0; r < col->len; r++) { + int64_t pos = ray_read_sym(ray_data(col), r, RAY_SYM, col->attrs); + if (pos >= 0 && pos < words && !seen[pos]) { seen[pos] = 1; n++; } + } + } else n = -1; + if (seen) ray_sys_free(seen); + ray_release(t); + return n; +} +/* symfile 'column: each symbol column its own symbol file, `.s.sym` and + * `.t.sym`, and no `.sym`. Every row's string is the shared import's; each + * file holds its column's distinct strings and "" (t's vocabulary meets + * s's: the shared file holds the common strings once, the column files once + * each); in every way the import runs: direct in one pass and column by + * column, grouped (a grouped import over each column's own dictionary), on + * one worker and four, generation 2 too, and (debug builds) mixed: s direct + * from its seeded dictionaries, t grouped. 'shared is the default's + * layout; any other value is refused, and so is 'column for .parquet.parted. */ +static test_result_t test_pq_symfile_column(void) { + pq_sym_env_clear(); + char src[160], dir[160], ref[160], path[220]; + snprintf(src, sizeof(src), "/tmp/rayforce-pq-symcol-%d.parquet", (int)getpid()); + snprintf(dir, sizeof(dir), "/tmp/rayforce-pq-symcol-%d", (int)getpid()); + snprintf(ref, sizeof(ref), "/tmp/rayforce-pq-symcol-%d-ref", (int)getpid()); + const char* names[] = {"x","s","t"}; + int64_t tids[] = {ray_sym_intern("I32",3), ray_sym_intern("SYM",3), ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM, tids, 3); + int bad = 0; + for (int data = 0; data < 2; data++) { + /* data 1: s dictionary-encoded and low-cardinality (pq_sym_mixed_modes' + * file), for the mixed import */ + pq_synth_t = data ? pq_synth_highcard : NULL; pq_synth_dict = data ? 1u << 1 : 0; + pq_synth_fn fn = data ? pq_synth_lowcard : pq_synth_mixed; + int64_t rows = 20000; + TEST_ASSERT_TRUE(pq_synth(src, rows, data ? 4 : 9, fn)); + TEST_ASSERT_EQ_I(pq_pool(1), RAY_OK); + ray_t* res = ray_parquet_splayed_typed(src, ref, types); /* the shared layout */ + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + int64_t want_s = pq_col_distinct(ref, 1), want_t = pq_col_distinct(ref, 2); + int64_t words = pq_sym_count(ref); + TEST_ASSERT_TRUE(want_s > 1 && want_t > 1 && words > 1); + if (!data) TEST_ASSERT_TRUE(want_s + want_t - 1 > words); /* the columns share strings */ + char ramv[32] = ""; +#if defined(DEBUG) + if (data) { + /* the memory that mixes them, as pq_sym_mixed_modes finds it */ + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + pq_set_symmode("direct"); + res = pq_traced_import(src, dir, types, trace, cap); + pq_set_symmode(NULL); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + pq_remove_native(dir, names, 3); + double bs = pq_trace_line_num(trace, "parquet symcol: col=s ", "vocab_bytes"); + snprintf(ramv, sizeof(ramv), "%lld", (long long)((int64_t)bs * 64)); + ray_sys_free(trace); + } +#endif + for (int run = 0; run < 6; run++) { + /* 0 one pass, 1 column by column, 2 grouped, 3 grouped on four + * workers, 4 generation 2, 5 mixed (debug builds, data 1) */ + if (run == 5 && !ramv[0]) continue; + TEST_ASSERT_EQ_I(pq_pool(run == 3 ? 4 : 1), RAY_OK); + if (run == 1) pq_set_layout("1"); + if (run == 2 || run == 3) pq_set_symmode("grouped"); + if (run == 5) pq_set_env("RAY_PQ_SYM_RAM", ramv); + ray_t* opts = pq_symcol_opts(types, "column", run == 4); + size_t cap = (size_t)1 << 16; + char* trace = (char*)ray_sys_alloc(cap); + TEST_ASSERT_TRUE(trace != NULL); + res = pq_traced_import(src, dir, opts, trace, cap); + pq_sym_env_clear(); + ray_release(opts); + if (!res || RAY_IS_ERR(res)) { + fprintf(stderr, " %d/%d: import failed: %s\n", data, run, res ? ray_err_code(res) : "null"); + if (res) ray_error_free(res); + snprintf(path, sizeof(path), "%s.parquet-partial", dir); + pq_remove_symcol(path, names, 3); + ray_sys_free(trace); + bad++; continue; + } + TEST_ASSERT_EQ_I(res->i64, rows); ray_release(res); + if (run == 5 && !(pq_trace_line_has(trace, "parquet symcol: col=s ", " mode=direct") && + pq_trace_line_has(trace, "parquet symcol: col=t ", " mode=grouped") && + strstr(trace, "parquet symseed:"))) { + fprintf(stderr, " %d/%d: not mixed\n", data, run); bad++; + } + if ((run == 2 || run == 3) && !pq_trace_line_has(trace, "parquet symcol: col=s ", " mode=grouped")) bad++; + ray_sys_free(trace); + struct stat st; + snprintf(path, sizeof(path), "%s/.sym", dir); + if (stat(path, &st) == 0) { fprintf(stderr, " %d/%d: a shared .sym\n", data, run); bad++; } + snprintf(path, sizeof(path), "%s/.s.sym", dir); + int64_t ns = pq_symfile_count(path); + snprintf(path, sizeof(path), "%s/.t.sym", dir); + int64_t nt = pq_symfile_count(path); + if (ns != want_s || nt != want_t) { + fprintf(stderr, " %d/%d: s %lld (want %lld), t %lld (want %lld)\n", data, run, + (long long)ns, (long long)want_s, (long long)nt, (long long)want_t); + bad++; + } + if (!pq_synth_check(dir, rows, fn)) { fprintf(stderr, " %d/%d: rows differ\n", data, run); bad++; } + /* the two columns over two domains, each its own file */ + ray_t* t = ray_read_splayed(dir, NULL); + if (t && !RAY_IS_ERR(t)) { + ray_t* a = ray_table_get_col_idx(t, 1); + ray_t* b = ray_table_get_col_idx(t, 2); + const char* pa = a ? ray_sym_domain_path(ray_sym_vec_domain(a)) : NULL; + const char* pb = b ? ray_sym_domain_path(ray_sym_vec_domain(b)) : NULL; + if (!pa || !pb || !strstr(pa, "/.s.sym") || !strstr(pb, "/.t.sym")) bad++; + ray_release(t); + } else { if (t) ray_error_free(t); bad++; } + pq_remove_symcol(dir, names, 3); + } + pq_remove_native(ref, names, 3); + unlink(src); + } + pq_synth_t = NULL; pq_synth_dict = 0; + /* 'shared: the default's single file */ + TEST_ASSERT_TRUE(pq_synth(src, 2000, 2, pq_synth_mixed)); + ray_t* opts = pq_symcol_opts(types, "shared", false); + ray_t* res = ray_parquet_splayed_typed(src, dir, opts); + ray_release(opts); + TEST_ASSERT_FALSE(!res || RAY_IS_ERR(res)); ray_release(res); + TEST_ASSERT_TRUE(pq_sym_count(dir) > 1); + snprintf(path, sizeof(path), "%s/.s.sym", dir); + struct stat st; + TEST_ASSERT_TRUE(stat(path, &st) != 0); + pq_remove_native(dir, names, 3); + /* any other value, and 'column for a parted import */ + opts = pq_symcol_opts(types, "bogus", false); + res = ray_parquet_splayed_typed(src, dir, opts); + ray_release(opts); + TEST_ASSERT_TRUE(res && RAY_IS_ERR(res)); + TEST_ASSERT_STR_EQ(ray_err_code(res), "domain"); + ray_error_free(res); + TEST_ASSERT_TRUE(stat(dir, &st) != 0); + opts = pq_symcol_opts(types, "column", false); + res = ray_parquet_parted_typed(src, dir, "hits", opts); + ray_release(opts); + TEST_ASSERT_TRUE(res && RAY_IS_ERR(res)); + TEST_ASSERT_STR_EQ(ray_err_code(res), "domain"); + ray_error_free(res); + snprintf(path, sizeof(path), "%s.parquet-partial", dir); + TEST_ASSERT_TRUE(stat(dir, &st) != 0 && stat(path, &st) != 0); + unlink(src); + ray_release(types); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +} + const test_entry_t parquet_entries[] = { {"parquet/sk4_grouped_message",test_pq_sk4_grouped_message,pq_setup,pq_teardown}, {"parquet/worker_messages",test_pq_worker_messages,pq_lang_setup,pq_lang_teardown}, @@ -3658,6 +3892,7 @@ const test_entry_t parquet_entries[] = { {"parquet/sym_grouped_collisions",test_pq_sym_grouped_collisions,pq_setup,pq_teardown}, {"parquet/sym_grouped_layout",test_pq_sym_grouped_layout,pq_setup,pq_teardown}, {"parquet/sym_mixed_modes",test_pq_sym_mixed_modes,pq_setup,pq_teardown}, + {"parquet/symfile_column",test_pq_symfile_column,pq_setup,pq_teardown}, {"parquet/sym_grouped_failures",test_pq_sym_grouped_failures,pq_setup,pq_teardown}, {"parquet/dict_page_size",test_pq_dict_page_size,pq_setup,pq_teardown}, {"parquet/import_no_growth",test_pq_import_no_growth,pq_setup,pq_teardown}, @@ -3674,6 +3909,7 @@ const test_entry_t parquet_entries[] = { {"parquet/chunk_flush_error",test_pq_chunk_flush_error,pq_setup,pq_teardown}, #endif {"parquet/splayed_inline_indexes",test_pq_splayed_inline_indexes,pq_setup,pq_teardown}, + {"parquet/parted_no_segment_hash",test_pq_parted_no_segment_hash,pq_setup,pq_teardown}, {"parquet/parallel",test_pq_parallel,pq_setup,pq_teardown}, {"parquet/range",test_pq_range,pq_setup,pq_teardown}, {NULL,NULL,NULL,NULL} diff --git a/test/test_parted_ragged.c b/test/test_parted_ragged.c new file mode 100644 index 000000000..37af79c26 --- /dev/null +++ b/test/test_parted_ragged.c @@ -0,0 +1,834 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* Ragged parted tables (#724): a partition lacking a tail column reads as + * that column's nulls, so every column has the table's row count. Answers + * on generation 0, generation 2 and mixed ragged tables equal those of the + * same table written with explicit nulls in the missing rows. */ + +#define _POSIX_C_SOURCE 200809L +#include "test.h" +#include +#include "mem/heap.h" +#include "core/runtime.h" +#include "lang/eval.h" +#include "table/sym.h" +#include "table/table.h" +#include "store/enccol.h" +#include "store/encw.h" +#include "vec/str.h" +#include "store/part.h" +#include "store/serde.h" +#include "store/splay.h" +#include "store/col.h" +#include +#include + +#define PR_TMP "/tmp/rayforce_parted_ragged" + +static void pr_setup(void) { ray_runtime_create(0, NULL); (void)ray_test_rm_rf(ray_test_tmp(PR_TMP)); (void)ray_test_mkdir_p(ray_test_tmp(PR_TMP)); } +static void pr_teardown(void) { ray_test_hooks_off(); (void)ray_test_rm_rf(ray_test_tmp(PR_TMP)); ray_runtime_destroy(__RUNTIME); } + +static void drop_out(ray_t* o) { if (!o) return; if (RAY_IS_ERR(o)) ray_error_free(o); else ray_release(o); } + +static bool ev_ok(const char* src) { + ray_t* r = ray_eval_str(src); + bool ok = r && !RAY_IS_ERR(r); + drop_out(r); + return ok; +} + +/* Same serialized value and same printed form. */ +static bool same_value(ray_t* x, ray_t* y) { + if (!x || !y || RAY_IS_ERR(x) || RAY_IS_ERR(y)) return false; + ray_t* sx = ray_ser(x); ray_t* sy = ray_ser(y); + bool same = sx && sy && !RAY_IS_ERR(sx) && !RAY_IS_ERR(sy) && sx->len == sy->len && + memcmp(ray_data(sx), ray_data(sy), (size_t)sx->len) == 0; + if (sx && !RAY_IS_ERR(sx)) ray_release(sx); + if (sy && !RAY_IS_ERR(sy)) ray_release(sy); + if (!same) return false; + ray_t* fx = ray_fmt(x, 0); ray_t* fy = ray_fmt(y, 0); + same = fx && fy && ray_str_len(fx) == ray_str_len(fy) && + memcmp(ray_str_ptr(fx), ray_str_ptr(fy), ray_str_len(fx)) == 0; + if (fx) ray_release(fx); + if (fy) ray_release(fy); + return same; +} + +/* Three partitions of t under `root`; bit p of `gen2` writes partition p as + * generation 2. `ragged` writes the last partition with column a alone; + * otherwise it carries the other columns' nulls explicitly (the reference). */ +static bool write_db(const char* root, unsigned gen2, bool ragged) { + static const char* const parts[3] = { + "(table [a b s f str d flag] (list [1 2 3] [10 20 30] ['x 'y 'x] [1.5 2.5 3.5] [\"p\" \"q\" \"r\"] " + "[2024.01.01 2024.01.02 2024.01.03] [true false true]))", + "(table [a b s f str d flag] (list [4 5] [40 50] ['y 'z] [4.5 5.5] [\"s\" \"t\"] " + "[2024.02.01 2024.02.02] [false true]))", + "(table [a b s f str d flag] (list [6 7 8 9] (take [0Nl] 4) (take ['] 4) (take [0Nf] 4) " + "(take [\"\"] 4) (take [0Nd] 4) (take [false] 4)))", + }; + for (int p = 0; p < 3; p++) { + char q[1024]; + const char* tbl = (ragged && p == 2) ? "(table [a] (list [6 7 8 9]))" : parts[p]; + snprintf(q, sizeof q, "(.db.splayed.set \"%s/2024.01.0%d/t/\" %s {compress: %s})", + root, p + 1, tbl, ((gen2 >> p) & 1) ? "true" : "false"); + if (!ev_ok(q)) return false; + } + return true; +} + +static ray_t* load_db(const char* root) { + ray_t* t = ray_read_parted(root, "t"); + return (t && !RAY_IS_ERR(t)) ? t : NULL; +} + +static void bind_t(ray_t* t) { ray_env_set(ray_sym_intern("t", 1), t); } + +static const char* const queries[] = { + "(select {s: (sum b) from: t})", + "(select {c: (count a) by: b from: t where: (> a 0)})", + "(select {b: b from: t where: (>= date 2024.01.02)})", + "(select {b: b s: s from: t where: (== date 2024.01.03)})", + "(select {s: (sum b) from: t where: (== date 2024.01.03)})", + "(select {date: date a: a b: b s: s f: f str: str d: d flag: flag from: t})", + "(select {from: t where: (> a 4)})", + "(select {s: (sum f) m: (max d) n: (count s) x: (min b) by: date from: t})", + "(select {c: (count a) by: s from: t})", + "(select {c: (count a) by: str from: t})", + "(select {c: (count a) by: flag from: t})", + "(select {x: (+ a b) y: (* f 2) from: t})", + "(xasc (select {a: a b: b from: t}) 'b)", + "(xdesc (select {a: a d: d from: t}) 'd)", + "(select {s: (sum a) from: t where: (> b 15)})", + "(select {a: a from: t where: (== s 'x)})", + "(select {c: (count (distinct b)) by: date from: t})", + "(select {r: (sums b) from: t})", + "(at t 'b)", + "(at t 's)", + "(at t 'str)", + "(at t 'flag)", + "(sum (at t 'b))", + "(count (at t 'f))", + NULL, +}; + +/* Every query answers on the ragged table exactly as on the reference. */ +static test_result_t ragged_matches(unsigned gen2) { + char rr[128], rf[128]; + snprintf(rr, sizeof rr, ray_test_tmp(PR_TMP "/rag_%u"), gen2); + snprintf(rf, sizeof rf, ray_test_tmp(PR_TMP "/ref_%u"), gen2); + TEST_ASSERT_TRUE(write_db(rr, gen2, true)); + TEST_ASSERT_TRUE(write_db(rf, gen2, false)); + ray_t* tr = load_db(rr); + ray_t* tf = load_db(rf); + TEST_ASSERT_TRUE(tr && tf); + for (int i = 0; queries[i]; i++) { + bind_t(tf); + ray_t* want = ray_eval_str(queries[i]); + bind_t(tr); + ray_t* got = ray_eval_str(queries[i]); + bool ok = want && !RAY_IS_ERR(want); + bool same = same_value(want, got); + drop_out(want); drop_out(got); + TEST_ASSERT_FMT(ok, "gen2 %u: %s: reference answers", gen2, queries[i]); + TEST_ASSERT_FMT(same, "gen2 %u: %s: ragged equals reference", gen2, queries[i]); + } + bind_t(NULL); + ray_release(tr); ray_release(tf); + PASS(); +} + +static test_result_t test_ragged_gen0(void) { return ragged_matches(0); } +static test_result_t test_ragged_gen2(void) { return ragged_matches(7); } +static test_result_t test_ragged_mixed(void) { + test_result_t r = ragged_matches(3); /* the ragged partition is generation 0 */ + if (r.status != TEST_PASS) return r; + return ragged_matches(4); /* only the ragged partition is generation 2 */ +} + +/* The issue's repro: pinned answers, not only reference equality. */ +static test_result_t test_issue_repro(void) { + TEST_ASSERT_TRUE(write_db(ray_test_tmp(PR_TMP "/repro"), 0, true)); + ray_t* t = load_db(ray_test_tmp(PR_TMP "/repro")); + TEST_ASSERT_NOT_NULL(t); + bind_t(t); + ray_t* r = ray_eval_str("(at (select {s: (sum b) from: t}) 's)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64 && r->len == 1); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(r))[0], 150); + drop_out(r); + /* the four rows of 2024.01.03 group under the null key */ + r = ray_eval_str("(at (select {c: (count a) by: b from: t where: (> a 0)}) 'c)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64 && r->len == 6); + int64_t total = 0, four = 0; + for (int64_t i = 0; i < r->len; i++) { total += ((int64_t*)ray_data(r))[i]; four += ((int64_t*)ray_data(r))[i] == 4; } + TEST_ASSERT_EQ_I(total, 9); + TEST_ASSERT_EQ_I(four, 1); + drop_out(r); + r = ray_eval_str("(at (select {c: (count a) by: b from: t where: (> a 0)}) 'b)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64 && r->len == 6); + int64_t nulls = 0; + for (int64_t i = 0; i < r->len; i++) nulls += ((int64_t*)ray_data(r))[i] == NULL_I64; + TEST_ASSERT_EQ_I(nulls, 1); + drop_out(r); + /* the filter keeps 2024.01.02 and 2024.01.03 only */ + r = ray_eval_str("(at (select {b: b from: t where: (>= date 2024.01.02)}) 'b)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64); + TEST_ASSERT_EQ_I(r->len, 6); + static const int64_t want[6] = { 40, 50, NULL_I64, NULL_I64, NULL_I64, NULL_I64 }; + for (int i = 0; i < 6; i++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(r))[i], want[i]); + drop_out(r); + bind_t(NULL); + ray_release(t); + PASS(); +} + +/* A loaded ragged column has a segment per partition, each with its + * partition's MAPCOMMON row count; ray_parted_nrows is the table's rows. */ +static test_result_t test_segments_full(void) { + for (unsigned gen2 = 0; gen2 < 8; gen2 += 4) { + char root[128]; snprintf(root, sizeof root, ray_test_tmp(PR_TMP "/seg_%u"), gen2); + TEST_ASSERT_TRUE(write_db(root, gen2 | 1, true)); + ray_t* t = load_db(root); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_EQ_I(ray_table_nrows(t), 9); + ray_t* mc = ray_table_col_idx(t, 0); + TEST_ASSERT_TRUE(mc && mc->type == RAY_MAPCOMMON); + const int64_t* counts = (const int64_t*)ray_data(((ray_t**)ray_data(mc))[1]); + for (int64_t c = 1; c < ray_table_ncols(t); c++) { + ray_t* slot = ray_table_get_col_enc_idx(t, c); + ray_t* w = slot ? NULL : ray_table_col_idx(t, c); + TEST_ASSERT_EQ_I(ray_table_col_nrows(slot ? slot : w), 9); + if (w) TEST_ASSERT_EQ_I(ray_parted_nrows(w), 9); + for (int32_t p = 0; p < 3; p++) { + ray_t* seg = slot ? ray_enccol_seg(slot, p) : ((ray_t**)ray_data(w))[p]; + TEST_ASSERT_FMT(seg != NULL, "gen2 %u col %lld seg %d present", gen2, (long long)c, p); + TEST_ASSERT_EQ_I(ray_table_col_nrows(seg), counts[p]); + } + } + ray_release(t); + } + PASS(); +} + +/* A 2-row partition beside a 1M-row partition lacking b: every answer is + * the null-filled reference's (a read past the 2-row b would not be). */ +static test_result_t test_large_ragged(void) { + for (unsigned gen2 = 0; gen2 < 4; gen2++) { + char rr[128], rf[128], q[512]; + snprintf(rr, sizeof rr, ray_test_tmp(PR_TMP "/lrag_%u"), gen2); + snprintf(rf, sizeof rf, ray_test_tmp(PR_TMP "/lref_%u"), gen2); + for (int k = 0; k < 2; k++) { + const char* root = k ? rf : rr; + snprintf(q, sizeof q, "(.db.splayed.set \"%s/2024.01.01/t/\" (table [a b] (list [1 2] [10 20])) {compress: %s})", + root, (gen2 & 1) ? "true" : "false"); + TEST_ASSERT_TRUE(ev_ok(q)); + snprintf(q, sizeof q, "(.db.splayed.set \"%s/2024.01.02/t/\" %s {compress: %s})", root, + k ? "(table [a b] (list (til 1000000) (take [0Nl] 1000000)))" : "(table [a] (list (til 1000000)))", + (gen2 & 2) ? "true" : "false"); + TEST_ASSERT_TRUE(ev_ok(q)); + } + ray_t* tr = load_db(rr); + ray_t* tf = load_db(rf); + TEST_ASSERT_TRUE(tr && tf); + static const char* const lq[] = { + "(select {s: (sum b) c: (count b) m: (max b) from: t})", + "(select {c: (count a) by: b from: t})", + "(select {s: (sum a) from: t where: (> b 0)})", + "(select {b: b from: t where: (< a 3)})", + "(select {s: (sum b) by: date from: t})", + NULL, + }; + for (int i = 0; lq[i]; i++) { + bind_t(tf); + ray_t* want = ray_eval_str(lq[i]); + bind_t(tr); + ray_t* got = ray_eval_str(lq[i]); + bool same = same_value(want, got); + drop_out(want); drop_out(got); + TEST_ASSERT_FMT(same, "gen2 %u: %s", gen2, lq[i]); + } + bind_t(tr); + ray_t* s = ray_eval_str("(at (select {s: (sum b) from: t}) 's)"); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s) && s->type == RAY_I64 && s->len == 1); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(s))[0], 30); + drop_out(s); + bind_t(NULL); + ray_release(tr); ray_release(tf); + } + PASS(); +} + +/* A hand-built parted column with a missing (NULL) segment, which + * ray_read_parted never produces: the executor reads the missing partition + * as its rows of nulls (the partition-key counts give them), never past the + * column's end. Every query answers as over the same table with that + * segment an all-null vector of the partition's rows. */ +static ray_t* pr_fmt_q(const char* q) { + ray_t* r = ray_eval_str(q); + if (!r || RAY_IS_ERR(r)) { drop_out(r); return NULL; } + ray_t* f = ray_fmt(r, 0); + drop_out(r); + return f; +} +static test_result_t test_missing_segment_nulls(void) { + TEST_ASSERT_TRUE(write_db(ray_test_tmp(PR_TMP "/hand"), 0, false)); + ray_t* src = load_db(ray_test_tmp(PR_TMP "/hand")); + TEST_ASSERT_NOT_NULL(src); + ray_t* b = ray_table_col(src, ray_sym_intern("b", 1)); + TEST_ASSERT_TRUE(b && RAY_IS_PARTED(b->type) && b->len == 3); + ray_t* seg2 = ((ray_t**)ray_data(b))[2]; + TEST_ASSERT_TRUE(seg2 && !RAY_IS_ERR(seg2) && seg2->type != RAY_ENCCOL); + ray_t* w[2]; + for (int k = 0; k < 2; k++) { /* 0: the missing segment; 1: its nulls */ + w[k] = ray_alloc(3 * sizeof(ray_t*)); + TEST_ASSERT_NOT_NULL(w[k]); + w[k]->type = b->type; w[k]->len = 3; w[k]->attrs = 0; memset(w[k]->aux, 0, 16); + ray_t** ws = (ray_t**)ray_data(w[k]); + for (int i = 0; i < 3; i++) { + ws[i] = i == 2 ? NULL : ((ray_t**)ray_data(b))[i]; + if (ws[i]) ray_retain(ws[i]); + } + if (k == 1) { + ray_t* nv = ray_vec_new(seg2->type, seg2->len); + TEST_ASSERT_TRUE(nv && !RAY_IS_ERR(nv)); + nv->len = seg2->len; + for (int64_t r = 0; r < nv->len; r++) ray_vec_set_null(nv, r, true); + ws[2] = nv; + } + } + ray_t* t[2]; + for (int k = 0; k < 2; k++) { + t[k] = ray_table_new(3); + t[k] = ray_table_add_col(t[k], ray_table_col_name(src, 0), ray_table_col_idx(src, 0)); + t[k] = ray_table_add_col(t[k], ray_sym_intern("a", 1), ray_table_col(src, ray_sym_intern("a", 1))); + t[k] = ray_table_add_col(t[k], ray_sym_intern("b", 1), w[k]); + ray_release(w[k]); + TEST_ASSERT_TRUE(t[k] && !RAY_IS_ERR(t[k])); + } + static const char* const hq[] = { + "(select {s: (sum b) from: t})", + "(select {c: (count a) by: b from: t asc: b})", + "(select {b: b from: t where: (>= date 2024.01.02)})", + "(select {a: a b: b from: t})", + NULL, + }; + for (int i = 0; hq[i]; i++) { + ray_t* f[2]; + for (int k = 0; k < 2; k++) { bind_t(t[k]); f[k] = pr_fmt_q(hq[i]); } + bool same = f[0] && f[1] && ray_str_len(f[0]) == ray_str_len(f[1]) && + memcmp(ray_str_ptr(f[0]), ray_str_ptr(f[1]), ray_str_len(f[0])) == 0; + for (int k = 0; k < 2; k++) if (f[k]) ray_release(f[k]); + TEST_ASSERT_FMT(same, "%s: the missing segment does not read as its nulls", hq[i]); + } + bind_t(NULL); + ray_release(t[0]); ray_release(t[1]); ray_release(src); + PASS(); +} + +/* A non-null column of `type` over n rows (LIST: I64 atoms). */ +static ray_t* typed_col(int8_t type, int64_t n) { + if (type == RAY_LIST) { + ray_t* l = ray_list_new(n); + for (int64_t i = 0; i < n; i++) { ray_t* a = ray_i64(i + 1); l = ray_list_append(l, a); ray_release(a); } + return l; + } + if (type == RAY_STR) { + ray_t* v = ray_vec_new(RAY_STR, n); + for (int64_t i = 0; i < n; i++) v = ray_str_vec_append(v, "v", 1); + return v; + } + if (type == RAY_SYM) { + ray_t* v = ray_vec_new(RAY_SYM, n); + for (int64_t i = 0; i < n; i++) { int64_t id = ray_sym_intern("k", 1); v = ray_vec_append(v, &id); } + return v; + } + ray_t* v = ray_vec_new(type, n); + v->len = n; + uint8_t* d = (uint8_t*)ray_data(v); + size_t esz = ray_elem_size(type); + memset(d, 0, (size_t)n * esz); + for (int64_t i = 0; i < n; i++) d[(size_t)i * esz] = 1; /* 1 (true for BOOL): never a sentinel */ + if (type == RAY_F64) for (int64_t i = 0; i < n; i++) ((double*)d)[i] = (double)i + 0.5; + if (type == RAY_F32) for (int64_t i = 0; i < n; i++) ((float*)d)[i] = (float)i + 0.5f; + return v; +} + +/* Is cell i of the filled segment the type's null fill? */ +static bool fill_cell_ok(ray_t* seg, int64_t i) { + const void* d = ray_data(seg); + switch (seg->type) { + case RAY_F64: { double x = ((const double*)d)[i]; return x != x; } + case RAY_F32: { float x = ((const float*)d)[i]; return x != x; } + case RAY_I64: case RAY_TIMESTAMP: return ((const int64_t*)d)[i] == NULL_I64; + case RAY_I32: case RAY_DATE: case RAY_TIME: return ((const int32_t*)d)[i] == NULL_I32; + case RAY_I16: return ((const int16_t*)d)[i] == NULL_I16; + case RAY_BOOL: case RAY_U8: return ((const uint8_t*)d)[i] == 0; + case RAY_SYM: return ray_read_sym(d, i, RAY_SYM, seg->attrs) == 0; + case RAY_STR: case RAY_GUID: { + static const uint8_t zero[16] = {0}; + return memcmp((const uint8_t*)d + i * 16, zero, 16) == 0; + } + case RAY_LIST: return ((ray_t* const*)d)[i] == RAY_NULL_OBJ; + default: return false; + } +} + +/* Every column type a partition can lack fills with its null (the non-nullable + * BOOL / U8 with 0, LIST with the null object): HAS_NULLS on exactly the + * nullable vector types, the table's row count, ray_vec_is_null on every + * nullable cell. Generation 0 and generation 2 (where the type saves). + * Every type generation 2 stores reads as a lazy all-null segment (a + * RAY_ENCCOL) whose materialization is that fill; LIST stays a heap fill. */ +static test_result_t test_fill_every_type(void) { + static const int8_t types[] = { + RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, RAY_DATE, RAY_TIME, + RAY_TIMESTAMP, RAY_SYM, RAY_STR, RAY_GUID, RAY_LIST, + }; + for (int gen = 0; gen < 2; gen++) { + for (size_t k = 0; k < sizeof types / sizeof types[0]; k++) { + int8_t ty = types[k]; + char root[160], dir[200], symp[200]; + snprintf(root, sizeof root, ray_test_tmp(PR_TMP "/ty_%d_%d"), gen, (int)ty); + snprintf(symp, sizeof symp, "%s/.sym", root); + for (int p = 0; p < 2; p++) { + snprintf(dir, sizeof dir, "%s/2024.01.0%d/t", root, p + 1); + int64_t n = p == 0 ? 3 : 5; + ray_t* t = ray_table_new(2); + ray_t* a = typed_col(RAY_I64, n); + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + ray_release(a); + if (p == 0) { + ray_t* x = typed_col(ty, n); + TEST_ASSERT_TRUE(x && !RAY_IS_ERR(x) && x->len == n); + t = ray_table_add_col(t, ray_sym_intern("x", 1), x); + ray_release(x); + } + ray_err_t e = ray_splay_save_mode(t, dir, symp, gen ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF); + ray_release(t); + TEST_ASSERT_FMT(e == RAY_OK, "gen %d type %d partition %d: save %d", gen, (int)ty, p, (int)e); + } + ray_enc_counters_reset(); + ray_t* t = ray_read_parted(root, "t"); + TEST_ASSERT_FMT(t && !RAY_IS_ERR(t), "gen %d type %d: load", gen, (int)ty); + ray_t* slot = ray_table_get_col_enc(t, ray_sym_intern("x", 1)); + ray_t* w = slot ? NULL : ray_table_col(t, ray_sym_intern("x", 1)); + TEST_ASSERT_EQ_I(ray_table_col_nrows(slot ? slot : w), 8); + ray_t* seg = slot ? ray_enccol_seg(slot, 1) : ((ray_t**)ray_data(w))[1]; + bool lazy = ty != RAY_LIST; + TEST_ASSERT_FMT(seg && seg->type == (lazy ? RAY_ENCCOL : ty) && ray_table_col_nrows(seg) == 5, + "gen %d type %d: filled segment", gen, (int)ty); + bool nullable = ty != RAY_BOOL && ty != RAY_U8 && ty != RAY_LIST; + /* null presence answers without a decode (directory null counts) */ + TEST_ASSERT_FMT(ray_table_col_has_nulls(t, ray_sym_intern("x", 1)) == nullable, + "gen %d type %d: column has nulls", gen, (int)ty); + ray_enc_counters_t cn; ray_enc_counters_get(&cn); + TEST_ASSERT_FMT(cn.materialized == 0, "gen %d type %d: nothing decoded at open", gen, (int)ty); + ray_t* plain = lazy ? ray_enccol_seg_col(slot, 1) : seg; + TEST_ASSERT_FMT(plain && !RAY_IS_ERR(plain) && plain->type == ty && plain->len == 5, + "gen %d type %d: materialized fill", gen, (int)ty); + TEST_ASSERT_FMT(((plain->attrs & RAY_ATTR_HAS_NULLS) != 0) == nullable, "gen %d type %d: HAS_NULLS", gen, (int)ty); + for (int64_t i = 0; i < 5; i++) { + TEST_ASSERT_FMT(fill_cell_ok(plain, i), "gen %d type %d: cell %lld", gen, (int)ty, (long long)i); + if (nullable && ty != RAY_SYM) TEST_ASSERT_TRUE(ray_vec_is_null(plain, i)); + } + if (ty == RAY_SYM) { /* id 0 resolves over the db's domain */ + ray_t* s0 = slot ? ray_enccol_seg_col(slot, 0) : ((ray_t**)ray_data(w))[0]; + TEST_ASSERT_TRUE(s0 && !RAY_IS_ERR(s0) && s0->type == RAY_SYM); + TEST_ASSERT_TRUE(plain->sym_domain == s0->sym_domain); + } + /* the column reads whole: present rows, then the fill */ + bind_t(t); + ray_t* c = ray_eval_str("(count (at t 'x))"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->i64 == 8); + drop_out(c); + bind_t(NULL); + ray_release(t); + } + } + PASS(); +} + +/* The all-null image at chunk and vector boundaries: it opens (every + * structural check of a file load), materializes to nulls, and its mapping + * is released exactly once (the mapped-bytes total returns to its start). */ +static test_result_t test_null_image_shapes(void) { + static const int64_t lens[] = { 0, 1, 1023, 1025, 65536, 65537, 131072, 200000 }; + static const int8_t types[] = { RAY_I64, RAY_STR, RAY_BOOL, RAY_SYM, RAY_F64, RAY_GUID }; + for (size_t k = 0; k < sizeof types / sizeof types[0]; k++) { + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + int8_t ty = types[k]; + int64_t n = lens[li]; + int64_t fn = n < 65536 ? n : 65536; + ray_t* fill = ty == RAY_SYM ? ray_sym_vec_new(RAY_SYM_W8, fn) : ray_vec_new(ty, fn); + TEST_ASSERT_TRUE(fill && !RAY_IS_ERR(fill)); + fill->len = fn; + size_t esz = ray_sym_elem_size(ty, fill->attrs); + memset(ray_data(fill), 0, (size_t)fn * esz); + if (ty == RAY_I64) for (int64_t i = 0; i < fn; i++) ((int64_t*)ray_data(fill))[i] = NULL_I64; + if (ty == RAY_F64) for (int64_t i = 0; i < fn; i++) ((double*)ray_data(fill))[i] = NULL_F64; + if (ty != RAY_BOOL && fn > 0) fill->attrs |= RAY_ATTR_HAS_NULLS; /* as the heap fill */ + ray_mem_stats_t m0, m1; + ray_mem_stats(&m0); + void* img = NULL; size_t size = 0; + TEST_ASSERT_EQ_I(ray_encw_null_image(ty, fill->attrs, n, 0, ray_data(fill), &img, &size), RAY_OK); + ray_release(fill); + ray_t* v = ray_enccol_open(img, size, "null image", NULL, false); + TEST_ASSERT_FMT(v && !RAY_IS_ERR(v), "type %d len %lld: opens", (int)ty, (long long)n); + TEST_ASSERT_EQ_I((int64_t)ray_enccol_own_bytes(v), (int64_t)size); + ray_col_meta_t m; + ray_enccol_meta(v, &m); + TEST_ASSERT_EQ_I(m.null_count, (ty == RAY_BOOL) ? 0 : n); + ray_t* pv = ray_enccol_materialize(v); + TEST_ASSERT_FMT(pv && !RAY_IS_ERR(pv) && pv->type == ty && pv->len == n, + "type %d len %lld: materializes", (int)ty, (long long)n); + for (int64_t i = 0; i < n; i++) { + bool ok = ty == RAY_BOOL ? ((uint8_t*)ray_data(pv))[i] == 0 + : ty == RAY_SYM ? ray_read_sym(ray_data(pv), i, RAY_SYM, pv->attrs) == 0 + : ty == RAY_STR ? ((ray_str_t*)ray_data(pv))[i].len == 0 + : ray_vec_is_null(pv, i); + if (!ok) TEST_ASSERT_FMT(ok, "type %d len %lld: row %lld null", (int)ty, (long long)n, (long long)i); + } + ray_release(v); + ray_mem_stats(&m1); + TEST_ASSERT_EQ_I((int64_t)m1.sys_mapped, (int64_t)m0.sys_mapped); + } + } + PASS(); +} + +/* Whole-file bytes, owned by the caller (ray_free_raw); NULL when unreadable. */ +static uint8_t* file_bytes(const char* path, size_t* n) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t* b = len >= 0 ? ray_alloc_raw((size_t)len + 1) : NULL; + size_t got = b ? fread(b, 1, (size_t)len, f) : 0; + fclose(f); + if (!b || got != (size_t)len) { ray_free_raw(b); return NULL; } + *n = (size_t)len; + return b; +} + +static bool files_equal(const char* x, const char* y) { + size_t nx = 0, ny = 0; + uint8_t* bx = file_bytes(x, &nx); + uint8_t* by = file_bytes(y, &ny); + bool eq = bx && by && nx == ny && memcmp(bx, by, nx) == 0; + ray_free_raw(bx); ray_free_raw(by); + return eq; +} + +/* The lazy segment's image is the file the generation-2 writer writes for + * the heap fill it stands for (same header attrs, HAS_NULLS included): the + * materialized segment, saved at generation 2, reproduces it byte for byte. */ +static test_result_t test_null_image_is_writer_output(void) { + static const int8_t types[] = { + RAY_BOOL, RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, RAY_DATE, RAY_TIME, + RAY_TIMESTAMP, RAY_STR, RAY_GUID, + }; + static const int64_t lens[] = { 5, 65536, 70000 }; + for (size_t k = 0; k < sizeof types / sizeof types[0]; k++) { + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + int8_t ty = types[k]; + int64_t n = lens[li]; + char root[160], dir[200], img_path[200], out[200]; + snprintf(root, sizeof root, ray_test_tmp(PR_TMP "/wo_%d_%lld"), (int)ty, (long long)n); + for (int p = 0; p < 2; p++) { + snprintf(dir, sizeof dir, "%s/2024.01.0%d/t", root, p + 1); + ray_t* t = ray_table_new(2); + ray_t* a = typed_col(RAY_I64, p == 0 ? 3 : n); + t = ray_table_add_col(t, ray_sym_intern("a", 1), a); + ray_release(a); + if (p == 0) { ray_t* x = typed_col(ty, 3); t = ray_table_add_col(t, ray_sym_intern("x", 1), x); ray_release(x); } + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, dir, NULL, RAY_COMPRESS_OFF), RAY_OK); + ray_release(t); + } + ray_t* t = ray_read_parted(root, "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* seg = ray_enccol_seg(ray_table_get_col_enc(t, ray_sym_intern("x", 1)), 1); + ray_enccol_t* e = ray_enccol_of(seg); + TEST_ASSERT_NOT_NULL(e); + snprintf(img_path, sizeof img_path, "%s/image", root); + FILE* f = fopen(img_path, "wb"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I((int64_t)fwrite(e->base, 1, (size_t)e->size, f), (int64_t)e->size); + fclose(f); + ray_t* plain = ray_enccol_materialize(seg); + TEST_ASSERT_TRUE(plain && !RAY_IS_ERR(plain)); + snprintf(out, sizeof out, "%s/writer", root); + TEST_ASSERT_EQ_I(ray_col_save_gen(plain, out, 2), RAY_OK); + TEST_ASSERT_FMT(files_equal(img_path, out), "type %d len %lld: image is the writer's file", + (int)ty, (long long)n); + ray_release(t); + } + } + PASS(); +} + +/* A lazy null segment is not an encoded source for generation inheritance: + * a table holding it saves, with no compress option over a fresh or + * generation-0 destination, as generation 0 byte for byte what the plain + * heap fill saves (the 9ca0dee2 eager behaviour); compress true still + * writes generation 2. */ +static test_result_t test_lazy_inherits_gen0(void) { + TEST_ASSERT_TRUE(write_db(ray_test_tmp(PR_TMP "/inh"), 0, true)); + ray_t* src = load_db(ray_test_tmp(PR_TMP "/inh")); + TEST_ASSERT_NOT_NULL(src); + static const char* const cols[] = { "b", "s", "f", "str", "d", "flag" }; + for (size_t i = 0; i < sizeof cols / sizeof cols[0]; i++) { + int64_t id = ray_sym_intern(cols[i], strlen(cols[i])); + ray_t* seg = ray_enccol_seg(ray_table_get_col_enc(src, id), 2); + TEST_ASSERT_TRUE(seg && seg->type == RAY_ENCCOL); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ABSENT, seg, NULL, cols[i], strlen(cols[i])), 0); + TEST_ASSERT_TRUE(ray_col_resolve_needs_dest(RAY_COMPRESS_ABSENT, seg)); + TEST_ASSERT_EQ_I(ray_col_resolve_gen(RAY_COMPRESS_ON, seg, NULL, cols[i], strlen(cols[i])), 2); + ray_t* plain = ray_enccol_materialize(seg); + TEST_ASSERT_TRUE(plain && !RAY_IS_ERR(plain)); + for (int mode = 0; mode < 2; mode++) { /* absent, then compress true */ + char dl[200], dp[200], fl[260], fp[260]; + ray_t* tl = ray_table_new(1); + tl = ray_table_add_col(tl, id, seg); + ray_t* tp = ray_table_new(1); + tp = ray_table_add_col(tp, id, plain); + snprintf(dl, sizeof dl, ray_test_tmp(PR_TMP "/inh_lazy_%zu_%d"), i, mode); + snprintf(dp, sizeof dp, ray_test_tmp(PR_TMP "/inh_plain_%zu_%d"), i, mode); + ray_compress_t m = mode ? RAY_COMPRESS_ON : RAY_COMPRESS_ABSENT; + char symp[200]; + snprintf(symp, sizeof symp, "%s/.sym", ray_test_tmp(PR_TMP "/inh")); + TEST_ASSERT_EQ_I(ray_splay_save_mode(tl, dl, symp, m), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(tp, dp, symp, m), RAY_OK); + ray_release(tl); ray_release(tp); + snprintf(fl, sizeof fl, "%s/%s", dl, cols[i]); + snprintf(fp, sizeof fp, "%s/%s", dp, cols[i]); + TEST_ASSERT_FMT(ray_col_file_gen(fl) == (mode ? 2 : 0), "%s mode %d: generation %d", cols[i], mode, + (int)ray_col_file_gen(fl)); + if (!mode) TEST_ASSERT_FMT(files_equal(fl, fp), "%s: generation 0 bytes equal the heap fill's", cols[i]); + } + } + ray_release(src); + PASS(); +} + +/* Resident set size in bytes (Linux /proc), 0 when unavailable. */ +static int64_t rss_bytes(void) { + FILE* f = fopen("/proc/self/statm", "r"); + if (!f) return 0; + long long pages = 0, res = 0; + int got = fscanf(f, "%lld %lld", &pages, &res); + fclose(f); + return got == 2 ? (int64_t)res * 4096 : 0; +} + +/* A 20M-row partition lacking an I64 and a STR column opens in O(chunks) + * bytes, not O(rows) (the eager fill held 160 MB + 320 MB on the heap), + * and nothing decodes until a query reads the column. */ +static test_result_t test_lazy_open(void) { + const int64_t N = 20000000; + const char* root = ray_test_tmp(PR_TMP "/lazy"); + char q[512]; + snprintf(q, sizeof q, "(.db.splayed.set \"%s/2024.01.01/t/\" (table [a b str] (list [1 2 3] [10 20 30] " + "[\"p\" \"q\" \"r\"])) {compress: false})", root); + TEST_ASSERT_TRUE(ev_ok(q)); + snprintf(q, sizeof q, "(.db.splayed.set \"%s/2024.01.02/t/\" (table [a] (list (til %lld))) {compress: false})", + root, (long long)N); + TEST_ASSERT_TRUE(ev_ok(q)); + ray_heap_gc(); + ray_mem_stats_t m0, m1; + ray_mem_stats(&m0); + int64_t rss0 = rss_bytes(); + ray_enc_counters_reset(); + ray_t* t = load_db(root); + TEST_ASSERT_NOT_NULL(t); + ray_mem_stats(&m1); + int64_t rss1 = rss_bytes(); + /* committed RAM: buddy pools, direct mmaps and sys allocs */ + int64_t heap = (int64_t)m1.sys_current - (int64_t)m0.sys_current; + TEST_ASSERT_FMT(heap < (16 << 20), "committed growth at open %lld bytes", (long long)heap); + TEST_ASSERT_FMT(rss1 - rss0 < (16 << 20), "RSS growth at open %lld bytes", (long long)(rss1 - rss0)); + static const char* const missing[] = { "b", "str" }; + for (int i = 0; i < 2; i++) { + ray_t* slot = ray_table_get_col_enc(t, ray_sym_intern(missing[i], strlen(missing[i]))); + TEST_ASSERT_NOT_NULL(slot); + ray_t* seg = ray_enccol_seg(slot, 1); + TEST_ASSERT_TRUE(seg && seg->type == RAY_ENCCOL && seg->len == N); + TEST_ASSERT_FMT(ray_enccol_own_bytes(seg) < (8u << 20), "%s image %zu bytes", + missing[i], ray_enccol_own_bytes(seg)); + } + ray_enc_counters_t c; + ray_enc_counters_get(&c); + TEST_ASSERT_EQ_I((int64_t)c.materialized, 0); + bind_t(t); + /* a query that does not reference the column */ + ray_t* r = ray_eval_str("(at (select {s: (sum a) from: t}) 's)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(r))[0], 6 + (N - 1) * N / 2); + drop_out(r); + ray_enc_counters_get(&c); + TEST_ASSERT_EQ_I((int64_t)c.materialized, 0); + /* a pruned query that excludes the ragged partition */ + r = ray_eval_str("(at (select {s: (sum b) from: t where: (== date 2024.01.01)}) 's)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(r))[0], 60); + drop_out(r); + ray_enc_counters_get(&c); + TEST_ASSERT_EQ_I((int64_t)c.materialized, 0); + /* a query that reads the column: the partition's rows are nulls */ + r = ray_eval_str("(at (select {s: (sum b) from: t}) 's)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_I64); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(r))[0], 60); + drop_out(r); + r = ray_eval_str("(count (select {b: b from: t where: (== b 0Nl)}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, N); + drop_out(r); + bind_t(NULL); + ray_release(t); + PASS(); +} + +/* Saving what a lazy segment holds writes its nulls in either generation: + * the flattened column, the pruned partition alone, and the segment object + * itself through the column writer. Each reloads equal to the same save + * from the explicit-null reference. */ +static test_result_t test_lazy_save(void) { + static const char* const sq[] = { + "(select {a: a b: b s: s f: f str: str d: d flag: flag from: t})", + "(select {a: a b: b s: s f: f str: str d: d flag: flag from: t where: (== date 2024.01.03)})", + NULL, + }; + for (unsigned gen2 = 0; gen2 < 8; gen2 += 7) { + char rr[128], rf[128]; + snprintf(rr, sizeof rr, ray_test_tmp(PR_TMP "/srag_%u"), gen2); + snprintf(rf, sizeof rf, ray_test_tmp(PR_TMP "/sref_%u"), gen2); + TEST_ASSERT_TRUE(write_db(rr, gen2, true)); + TEST_ASSERT_TRUE(write_db(rf, gen2, false)); + ray_t* tr = load_db(rr); + ray_t* tf = load_db(rf); + TEST_ASSERT_TRUE(tr && tf); + for (int i = 0; sq[i]; i++) { + for (int out_gen = 0; out_gen < 2; out_gen++) { + ray_t* got[2] = { NULL, NULL }; + for (int k = 0; k < 2; k++) { + char q[768]; + bind_t(k ? tf : tr); + snprintf(q, sizeof q, "(.db.splayed.set \"%s/out_%d_%d_%d/\" %s {compress: %s})", + k ? rf : rr, i, out_gen, k, sq[i], out_gen ? "true" : "false"); + TEST_ASSERT_FMT(ev_ok(q), "gen2 %u: save %s", gen2, sq[i]); + snprintf(q, sizeof q, "(.db.splayed.get \"%s/out_%d_%d_%d/\")", k ? rf : rr, i, out_gen, k); + got[k] = ray_eval_str(q); + } + bool same = same_value(got[1], got[0]); + drop_out(got[0]); drop_out(got[1]); + TEST_ASSERT_FMT(same, "gen2 %u out gen %d: %s reloads equal", gen2, out_gen, sq[i]); + } + } + /* the lazy segment itself, saved by the column writer */ + ray_t* slot = ray_table_get_col_enc(tr, ray_sym_intern("b", 1)); + TEST_ASSERT_NOT_NULL(slot); + ray_t* seg = ray_enccol_seg(slot, 2); + TEST_ASSERT_TRUE(seg && seg->type == RAY_ENCCOL); + for (int out_gen = 0; out_gen < 2; out_gen++) { + char path[200]; + snprintf(path, sizeof path, "%s/seg_b_%d", rr, out_gen); + TEST_ASSERT_EQ_I(ray_col_save_gen(seg, path, out_gen ? 2 : 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_file_gen(path), out_gen ? 2 : 0); + ray_t* v = ray_col_load(path); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + ray_t* pv = v->type == RAY_ENCCOL ? ray_enccol_materialize(v) : v; + TEST_ASSERT_TRUE(pv && !RAY_IS_ERR(pv) && pv->type == RAY_I64 && pv->len == 4); + for (int64_t r = 0; r < 4; r++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(pv))[r], NULL_I64); + ray_release(v); + } + bind_t(NULL); + ray_release(tr); ray_release(tf); + } + PASS(); +} + +/* The pruning key is a validated physical slot, not necessarily slot 0. + * Reorder a reader-created table through normal retaining table APIs, keeping + * encoded slots encoded. Explicit projections normalize output column order. */ +static test_result_t test_partition_key_position(void) { + for (unsigned gen2 = 0; gen2 <= 7; gen2 += 7) { + char root[512]; + snprintf(root, sizeof root, "%s/key_position_%u", ray_test_tmp(PR_TMP), gen2); + TEST_ASSERT_TRUE(write_db(root, gen2, false)); + ray_t* src = load_db(root); + TEST_ASSERT_NOT_NULL(src); + int64_t nc = ray_table_ncols(src); + TEST_ASSERT_TRUE(nc > 1); + ray_col_meta_t m; + TEST_ASSERT_TRUE(ray_table_col_meta_idx(src, 0, &m) && m.type == RAY_MAPCOMMON); + ray_enc_counters_reset(); + ray_t* reordered = ray_table_new(nc); + TEST_ASSERT_TRUE(reordered && !RAY_IS_ERR(reordered)); + for (int64_t j = 1; j <= nc; j++) { + int64_t c = j % nc; /* original key moves last */ + ray_t* slot = ray_table_get_col_enc_idx(src, c); + if (!slot) slot = ray_table_col_idx(src, c); + TEST_ASSERT_TRUE(slot && !RAY_IS_ERR(slot)); + reordered = ray_table_add_col(reordered, ray_table_col_name(src, c), slot); + TEST_ASSERT_TRUE(reordered && !RAY_IS_ERR(reordered)); + } + TEST_ASSERT_TRUE(ray_table_col_meta_idx(reordered, nc - 1, &m) && m.type == RAY_MAPCOMMON); + TEST_ASSERT_EQ_I(m.len, 9); /* public metadata rows stay meaningful */ + ray_enc_counters_t counters; + ray_enc_counters_get(&counters); + TEST_ASSERT_EQ_I((int64_t)counters.materialized, 0); + static const char* const q[] = { + "(select {date: date a: a b: b from: t where: (> a 0)})", + "(select {date: date a: a b: b from: t where: (>= date 2024.01.02)})", + NULL, + }; + for (int i = 0; q[i]; i++) { + bind_t(src); ray_t* want = ray_eval_str(q[i]); + bind_t(reordered); ray_t* got = ray_eval_str(q[i]); + bool same = same_value(want, got); + drop_out(want); drop_out(got); + TEST_ASSERT_FMT(same, "gen2 %u, key-last: %s", gen2, q[i]); + } + bind_t(NULL); + ray_release(reordered); ray_release(src); + } + PASS(); +} + +const test_entry_t parted_ragged_entries[] = { + { "parted_ragged/key_position", test_partition_key_position, pr_setup, pr_teardown }, + { "parted_ragged/fill_every_type", test_fill_every_type, pr_setup, pr_teardown }, + { "parted_ragged/issue_repro", test_issue_repro, pr_setup, pr_teardown }, + { "parted_ragged/gen0", test_ragged_gen0, pr_setup, pr_teardown }, + { "parted_ragged/gen2", test_ragged_gen2, pr_setup, pr_teardown }, + { "parted_ragged/mixed", test_ragged_mixed, pr_setup, pr_teardown }, + { "parted_ragged/segments_full", test_segments_full, pr_setup, pr_teardown }, + { "parted_ragged/large", test_large_ragged, pr_setup, pr_teardown }, + { "parted_ragged/missing_segment_nulls", test_missing_segment_nulls, pr_setup, pr_teardown }, + { "parted_ragged/null_image_shapes", test_null_image_shapes, pr_setup, pr_teardown }, + { "parted_ragged/null_image_writer", test_null_image_is_writer_output, pr_setup, pr_teardown }, + { "parted_ragged/lazy_inherits_gen0", test_lazy_inherits_gen0, pr_setup, pr_teardown }, + { "parted_ragged/lazy_open", test_lazy_open, pr_setup, pr_teardown }, + { "parted_ragged/lazy_save", test_lazy_save, pr_setup, pr_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_platform.c b/test/test_platform.c index 6be7c5525..0175bdda9 100644 --- a/test/test_platform.c +++ b/test/test_platform.c @@ -37,6 +37,9 @@ #include #include #include +#ifdef RAY_OS_LINUX +#include +#endif /* ---- test_vm_alloc_free ------------------------------------------------ */ @@ -167,6 +170,122 @@ static test_result_t test_cgroup_stat_flush(void) { /* ---- Suite definition -------------------------------------------------- */ +#ifdef RAY_OS_LINUX +/* Writes `text` to root/rel, creating its directories. */ +static void cgq_put(const char* root, const char* rel, const char* text) { + char path[512]; + snprintf(path, sizeof(path), "%s/%s", root, rel); + for (char* p = path + strlen(root) + 1; *p; p++) + if (*p == '/') { *p = 0; (void)mkdir(path, 0700); *p = '/'; } + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) return; + ssize_t n = write(fd, text, strlen(text)); + (void)n; + close(fd); +} + +/* The quota of a fake /proc + /sys under a fresh directory. */ +static int64_t cgq_quota(const char* tag, const char* cgroup, const char* mountinfo, + const char* const* files) { + char root[128], cmd[300]; + snprintf(root, sizeof(root), "/tmp/rayforce_cgq_%d_%s", (int)getpid(), tag); + snprintf(cmd, sizeof(cmd), "rm -rf %s", root); + if (system(cmd) != 0) return -2; + (void)mkdir(root, 0700); + cgq_put(root, "proc/self/cgroup", cgroup); + if (mountinfo) cgq_put(root, "proc/self/mountinfo", mountinfo); + for (int i = 0; files[i]; i += 2) cgq_put(root, files[i], files[i + 1]); + ray_os_cgroup_test_root(root); + int64_t q = ray_os_cgroup_cpu_quota(); + ray_os_cgroup_test_root(NULL); + if (system(cmd) != 0) return -3; + return q; +} +#endif + +/* The CPU quota is found through the mount the hierarchy is visible at: + * its mount point and the subtree it shows (/proc/self/mountinfo), for v2 + * and for a v1 cpu controller wherever mounted; the smallest over the + * cgroup and its visible ancestors; the conventional mounts without + * mountinfo. */ +static test_result_t test_cgroup_cpu_quota(void) { + int64_t real = ray_os_cgroup_cpu_quota(); + TEST_ASSERT(real >= 0, "a quota is never negative"); +#ifdef RAY_OS_LINUX + const char* v2mi = "30 25 0:26 / /sys/fs/cgroup rw,nosuid shared:9 - cgroup2 cgroup2 rw\n"; + const char* const canon[] = { "sys/fs/cgroup/a/b/cpu.max", "150000 100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("v2", "0::/a/b\n", v2mi, canon), 1500); + /* the v2 subtree /tenant mounted at /sys/fs/cgroup: /tenant/job lives at + * /sys/fs/cgroup/job, and the unlimited visible root does not count */ + const char* const sub[] = { "sys/fs/cgroup/job/cpu.max", "150000 100000\n", + "sys/fs/cgroup/cpu.max", "max 100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("sub", "0::/tenant/job\n", + "30 25 0:26 /tenant /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n", sub), 1500); + /* a membership outside the visible subtree has no readable quota */ + TEST_ASSERT_EQ_I(cgq_quota("out", "0::/other/job\n", + "30 25 0:26 /tenant /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n", sub), 0); + /* several views of the hierarchy: the one holding the membership counts, + * whatever comes first in mountinfo */ + const char* const lim[] = { "sys/fs/cgroup/limited/cpu.max", "150000 100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("multi", "0::/limited\n", + "30 25 0:26 /other /unrelated rw - cgroup2 cgroup2 rw\n" + "31 25 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n", lim), 1500); + /* a narrow view and a full one: the ancestor quota only the full view + * shows is the tighter one */ + const char* const both[] = { "narrow/leaf/cpu.max", "150000 100000\n", + "sys/fs/cgroup/org/tenant/leaf/cpu.max", "150000 100000\n", + "sys/fs/cgroup/org/cpu.max", "50000 100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("views", "0::/org/tenant/leaf\n", + "30 25 0:26 /org/tenant /narrow rw - cgroup2 cgroup2 rw\n" + "31 25 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n", both), 500); + /* a v1 cpu controller mounted off the conventional place */ + const char* const v1[] = { "cgroup/cpu/x/cpu.cfs_quota_us", "50000\n", + "cgroup/cpu/x/cpu.cfs_period_us", "100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("v1", "4:cpu,cpuacct:/x\n", + "40 25 0:30 / /cgroup/cpu rw - cgroup cgroup rw,cpu,cpuacct\n", v1), 500); + /* a tighter ancestor wins (a quarter of a CPU, in millicpus) */ + const char* const anc[] = { "sys/fs/cgroup/a/b/cpu.max", "300000 100000\n", + "sys/fs/cgroup/a/cpu.max", "25000 100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("anc", "0::/a/b\n", v2mi, anc), 250); + const char* const none[] = { "sys/fs/cgroup/a/b/cpu.max", "max 100000\n", NULL }; + TEST_ASSERT_EQ_I(cgq_quota("none", "0::/a/b\n", v2mi, none), 0); + /* no mountinfo: the conventional /sys/fs/cgroup */ + TEST_ASSERT_EQ_I(cgq_quota("nomi", "0::/a/b\n", NULL, canon), 1500); + TEST_ASSERT_EQ_I(ray_os_cgroup_cpu_quota(), real); +#else + TEST_ASSERT_EQ_I(real, 0); +#endif + PASS(); +} + +/* A kernel whose CPU mask is wider than a cpu_set_t rejects the fixed + * buffer (EINVAL); the count retries with a larger one instead of falling + * back to every online CPU. */ +static test_result_t test_cpu_set_count_wide_mask(void) { + uint32_t n = ray_cpu_set_count(); + TEST_ASSERT(n >= 1, "at least one CPU"); +#ifdef RAY_OS_LINUX + cpu_set_t set, two; + CPU_ZERO(&set); + if (sched_getaffinity(0, sizeof(set), &set) != 0) + SKIP("the kernel's CPU mask is wider than a cpu_set_t: no fixed-size snapshot"); + TEST_ASSERT_EQ_I(n, CPU_COUNT(&set)); + if (CPU_COUNT(&set) < 3) SKIP("needs at least 3 CPUs"); + /* two CPUs of the mask, so the fallback (every online CPU) differs */ + CPU_ZERO(&two); + for (int c = 0, k = 0; c < CPU_SETSIZE && k < 2; c++) + if (CPU_ISSET(c, &set)) { CPU_SET(c, &two); k++; } + int rc = sched_setaffinity(0, sizeof(two), &two); + ray_cpu_set_test_min_bytes(4 * sizeof(cpu_set_t)); + uint32_t wide = ray_cpu_set_count(); + ray_cpu_set_test_min_bytes(0); + (void)sched_setaffinity(0, sizeof(set), &set); + TEST_ASSERT_EQ_I(rc, 0); + TEST_ASSERT_EQ_I(wide, 2); +#endif + PASS(); +} + const test_entry_t platform_entries[] = { { "platform/vm_alloc_free", test_vm_alloc_free, NULL, NULL }, { "platform/vm_alloc_aligned", test_vm_alloc_aligned, NULL, NULL }, @@ -174,6 +293,8 @@ const test_entry_t platform_entries[] = { { "platform/thread_create_join", test_thread_create_join, NULL, NULL }, { "platform/cgroup_mem_limit", test_cgroup_mem_limit, NULL, NULL }, { "platform/cgroup_stat_flush", test_cgroup_stat_flush, NULL, NULL }, + { "platform/cgroup_cpu_quota", test_cgroup_cpu_quota, NULL, NULL }, + { "platform/cpu_set_count_wide_mask", test_cpu_set_count_wide_mask, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_pool.c b/test/test_pool.c index d6dc1ae2a..d315062a7 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -21,6 +21,9 @@ * SOFTWARE. */ +#if defined(__linux__) && !defined(_GNU_SOURCE) +#define _GNU_SOURCE /* CPU_SET / sched_setaffinity: the CPU-set sizing test */ +#endif #if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) #define _POSIX_C_SOURCE 200809L #endif @@ -1110,33 +1113,32 @@ static test_result_t test_dispatch_n_max_ring_cap_clamp(void) { /* -------------------------------------------------------------------------- * Test: ray_pool_dispatch with total_elems large enough that n_tasks would - * exceed MAX_RING_CAP, exercising the post-growth clamp on lines 246-249 - * (rebalances grain so all elements still get covered). + * exceed MAX_RING_CAP: the ring stops growing at the ceiling and the tasks + * past it run in a further round of the SAME grain (a widened grain would + * move task starts off the TASK_GRAIN boundaries callers index by). * * total_elems = 70000 * TASK_GRAIN (= 70000 * 8192 = 573M). We pass a - * no-op fn so the cost is just the dispatch overhead — even at 65536 - * tasks we're under a second. + * no-op fn so the cost is just the dispatch overhead. * -------------------------------------------------------------------------- */ -static test_result_t test_dispatch_max_ring_cap_clamp(void) { +static test_result_t test_dispatch_max_ring_rounds(void) { ray_heap_init(); ray_pool_t pool; TEST_ASSERT_EQ_I(ray_pool_create(&pool, 1), RAY_OK); pool_count_ctx_t ctx = {0}; - /* TASK_GRAIN = 8 * 1024 = 8192. 70000 * 8192 = 573_440_000 elements, - * which would naively want 70000 tasks. After clamp → 65536 tasks with - * a slightly larger grain so total_elems is still fully covered. */ + /* TASK_GRAIN = 8 * 1024 = 8192. 70000 * 8192 = 573_440_000 elements + * want 70000 tasks: 65536 in the first round, 4464 in the second. */ int64_t grain = 8192; int64_t total = 70000LL * grain; ray_pool_dispatch(&pool, pool_count_fn, &ctx, total); /* Ring should grow to MAX_RING_CAP and stop there */ TEST_ASSERT_EQ_U(pool.task_cap, 65536u); - /* Calls clamped to MAX_RING_CAP */ - TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 65536); - /* All elements covered (grain rebalanced) */ + /* One call per TASK_GRAIN, none dropped or widened */ + TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 70000); + /* All elements covered */ TEST_ASSERT_EQ_I(atomic_load(&ctx.elem_sum), total); ray_pool_free(&pool); @@ -1144,6 +1146,46 @@ static test_result_t test_dispatch_max_ring_cap_clamp(void) { PASS(); } +/* -------------------------------------------------------------------------- + * Test: a cancelled multi-round dispatch stops at the round boundary. + * + * Every ticket of a cancelled window is skipped, so the rounds past the + * cancel point would be pure publish/wake/skip overhead (over a hundred + * rounds when the ring is stuck at RAY_POOL_INIT_TASKS). The round loop + * checks the flag before each round: with it set at entry no window is + * published at all, so the ticket high-water mark does not move and fn + * never runs. Covers both ray_pool_dispatch and ray_pool_dispatch_n. + * -------------------------------------------------------------------------- */ + +static test_result_t test_dispatch_cancelled_skips_rounds(void) { + ray_heap_init(); + + ray_pool_t pool; + TEST_ASSERT_EQ_I(ray_pool_create(&pool, 1), RAY_OK); + + pool_count_ctx_t ctx = {0}; + uint64_t limit0 = atomic_load(&pool.task_limit); + atomic_store(&pool.cancelled, 1); + + ray_pool_dispatch(&pool, pool_count_fn, &ctx, 70000LL * 8192); + TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 0); + TEST_ASSERT_EQ_U(atomic_load(&pool.task_limit), limit0); + + ray_pool_dispatch_n(&pool, pool_count_fn, &ctx, 70000u); + TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 0); + TEST_ASSERT_EQ_U(atomic_load(&pool.task_limit), limit0); + + /* Cleared again, the same dispatch runs every task once. */ + atomic_store(&pool.cancelled, 0); + ray_pool_dispatch(&pool, pool_count_fn, &ctx, 70000LL * 8192); + TEST_ASSERT_EQ_I(atomic_load(&ctx.calls), 70000); + TEST_ASSERT_EQ_I(atomic_load(&ctx.elem_sum), 70000LL * 8192); + + ray_pool_free(&pool); + ray_heap_destroy(); + PASS(); +} + /* -------------------------------------------------------------------------- * Test: ray_pool_destroy on uninitialized state is a no-op. * @@ -1260,6 +1302,7 @@ static _Atomic(uint32_t) pool_once_hits[POOL_ONCE_MAX]; /* per-ticket hit coun typedef struct { int64_t grain; /* elements per ticket: 1 (dispatch_n) or TASK_GRAIN */ + int64_t total; /* elements in the window (last ticket may be short) */ uint32_t n; /* tickets in the window */ uint32_t block; /* ticket that waits for every other one; UINT32_MAX = none */ _Atomic(uint32_t) done; /* tickets finished */ @@ -1279,15 +1322,20 @@ static void pool_once_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t e * other ticket done), never on a timer. */ if (t == c->block) while (atomic_load_explicit(&c->done, memory_order_acquire) + 1 < c->n) RAY_CPU_RELAX(); - if (t < POOL_ONCE_MAX && end - start <= c->grain) + /* A ticket counts only as its exact range [t*grain, min((t+1)*grain, + * total)): callers index per-task state by start / TASK_GRAIN (fused + * WHERE rowsel builders, per-task histograms) and rely on it. */ + int64_t want_end = start + c->grain < c->total ? start + c->grain : c->total; + if (t < POOL_ONCE_MAX && start % c->grain == 0 && end == want_end) atomic_fetch_add_explicit(&pool_once_hits[t], 1, memory_order_relaxed); atomic_fetch_add_explicit(&c->done, 1, memory_order_release); } -static void pool_once_reset(pool_once_ctx_t* c, uint32_t n, int64_t grain) { +static void pool_once_reset(pool_once_ctx_t* c, uint32_t n, int64_t grain, int64_t total) { for (uint32_t t = 0; t < n; t++) atomic_store_explicit(&pool_once_hits[t], 0, memory_order_relaxed); c->grain = grain; + c->total = total; c->n = n; atomic_store_explicit(&c->done, 0, memory_order_relaxed); } @@ -1303,8 +1351,10 @@ static int64_t pool_once_bad(uint32_t n) { * and the cross-dispatch invariant (window fully claimed: cursors equal). */ static test_result_t pool_once_window(ray_pool_t* pool, pool_once_ctx_t* c, uint32_t n, bool elem_form, uint64_t* tickets) { - pool_once_reset(c, n, elem_form ? POOL_ONCE_GRAIN : 1); - if (elem_form) ray_pool_dispatch(pool, pool_once_fn, c, (int64_t)n * POOL_ONCE_GRAIN); + /* element windows end ragged on every third shape (short last ticket) */ + int64_t total = elem_form ? (int64_t)n * POOL_ONCE_GRAIN - (int64_t)(n % 3) * 1000 : n; + pool_once_reset(c, n, elem_form ? POOL_ONCE_GRAIN : 1, total); + if (elem_form) ray_pool_dispatch(pool, pool_once_fn, c, total); else ray_pool_dispatch_n(pool, pool_once_fn, c, n); *tickets += n; TEST_ASSERT_EQ_U(atomic_load(&c->done), n); @@ -1345,8 +1395,11 @@ static test_result_t pool_once_battery(ray_pool_t* pool) { POOL_ONCE_RUN(pool, &c, 1000, true, &tickets); } - /* more tasks than the ring can ever hold: several dispatch_n rounds */ + /* more tasks than the ring can ever hold: several rounds through both + * entry points. An element dispatch must still hand out whole + * TASK_GRAIN tickets, never a re-derived wider grain (#792). */ POOL_ONCE_RUN(pool, &c, POOL_ONCE_MAX, false, &tickets); + POOL_ONCE_RUN(pool, &c, POOL_ONCE_MAX, true, &tickets); /* Accounting: in steal mode every ticket was claimed from an own range * or stolen, nothing else; the cursor path never touches the counters. */ @@ -1709,7 +1762,7 @@ static test_result_t test_epoll_hup_no_errfn(void) { * Only a write to the pipe — no selector-array mutation from here. */ if (have_wake) { char b = 'x'; - (void)write(wake_pipe[1], &b, 1); + if (write(wake_pipe[1], &b, 1) != 1) { /* the loop then exits on its timeout */ } epoll_sleep_ms(30); close(wake_pipe[1]); /* wake_pipe[0] is owned by the poll selector; destroy will clean it */ @@ -1742,7 +1795,97 @@ static test_result_t test_auto_all_logical_cpus(void) { if (rc == RAY_OK) ray_pool_free(&local); if (saved) { setenv("RAYFORCE_CORES", saved, 1); free(saved); } TEST_ASSERT_EQ_I(rc, RAY_OK); - TEST_ASSERT_EQ_I(total, ray_thread_count()); + /* every CPU the process may run on (taskset or a cpuset narrows the + * set on Linux), or fewer under a cgroup CPU quota (millicpus) */ + int expect = (int)ray_cpu_set_count(); + int64_t quota = ray_os_cgroup_cpu_quota(); + if (quota > 0 && (quota + 999) / 1000 < expect) expect = (int)((quota + 999) / 1000); + TEST_ASSERT_EQ_I(total, expect); + PASS(); +} +#endif + +#if defined(__linux__) +/* "cores workers" from a child rayforce run under `prefix`, or false. */ +static bool cq_child(const char* prefix, const char* script, long* cores, long* workers) { + char cmd[512], out[512]; + snprintf(cmd, sizeof(cmd), "env -u RAYFORCE_CORES %s ./rayforce -f %s 2>/dev/null", prefix, script); + FILE* p = popen(cmd, "r"); + if (!p) return false; + size_t n = fread(out, 1, sizeof(out) - 1, p); + out[n] = 0; + if (pclose(p) != 0) return false; + while (n && (out[n - 1] == '\n' || out[n - 1] == ' ')) out[--n] = 0; + char* last = strrchr(out, '\n'); + return sscanf(last ? last + 1 : out, "%ld %ld", cores, workers) == 2; +} +#endif + +/* A child under a CPU quota of 1.5 CPUs (a systemd user scope, as docker + * --cpus would set) sizes its default pool to 2 threads, or fewer when a + * quota above the scope is tighter: the same child in a scope without a + * quota gives that bound. cores still counts every allowed CPU. Skipped + * where no systemd user manager makes scopes, and without ./rayforce (the + * TSan job builds only the test binary). */ +static test_result_t test_cpu_quota_child(void) { +#if !defined(__linux__) + SKIP("cgroup CPU quotas are Linux-only"); +#else + if (access("./rayforce", X_OK) != 0) SKIP("needs the ./rayforce binary"); + if (system("command -v systemd-run >/dev/null 2>&1 && " + "systemd-run --user --scope -q true >/dev/null 2>&1") != 0) + SKIP("no systemd user manager to make a scope with a CPU quota"); + char script[128]; + snprintf(script, sizeof(script), "/tmp/rayforce_cq_%d.rfl", (int)getpid()); + FILE* f = fopen(script, "w"); + TEST_ASSERT_TRUE(f != NULL); + fputs("(set i (.sys.info))\n(println (format \"% %\" (at i 'cores) (at i 'workers)))\n", f); + fclose(f); + long c0 = 0, w0 = 0, c1 = 0, w1 = 0; + bool ok0 = cq_child("systemd-run --user --scope -q", script, &c0, &w0); + bool ok1 = cq_child("systemd-run --user --scope -q -p CPUQuota=150%", script, &c1, &w1); + unlink(script); + TEST_ASSERT_TRUE(ok0); + TEST_ASSERT_TRUE(ok1); + TEST_ASSERT_EQ_I(c1, c0); + TEST_ASSERT_EQ_I(w1, w0 < 2 ? w0 : 2); + PASS(); +#endif +} + +#if defined(__linux__) +#include +/* The default pool follows the CPUs the process may run on: with the + * calling thread narrowed to two of them (as taskset does for a process), + * a default pool has two threads, main included. Under a cgroup CPU quota + * of less than two CPUs it has fewer. */ +static test_result_t test_auto_follows_cpu_set(void) { + cpu_set_t before, two; + CPU_ZERO(&before); + if (sched_getaffinity(0, sizeof(before), &before) != 0) + SKIP("the kernel's CPU mask is wider than a cpu_set_t: no fixed-size snapshot"); + if (CPU_COUNT(&before) < 3) SKIP("needs at least 3 CPUs"); + CPU_ZERO(&two); + for (int c = 0, k = 0; c < CPU_SETSIZE && k < 2; c++) + if (CPU_ISSET(c, &before)) { CPU_SET(c, &two); k++; } + const char* current = getenv("RAYFORCE_CORES"); + char* saved = current ? strdup(current) : NULL; + TEST_ASSERT_TRUE(!current || saved); + unsetenv("RAYFORCE_CORES"); + int set_rc = sched_setaffinity(0, sizeof(two), &two); + uint32_t seen = ray_cpu_set_count(); + ray_pool_t local; + ray_err_t rc = set_rc == 0 ? ray_pool_create(&local, 0) : RAY_ERR_IO; + uint32_t total = rc == RAY_OK ? ray_pool_total_workers(&local) : 0; + if (rc == RAY_OK) ray_pool_free(&local); + (void)sched_setaffinity(0, sizeof(before), &before); + if (saved) { setenv("RAYFORCE_CORES", saved, 1); free(saved); } + TEST_ASSERT_EQ_I(set_rc, 0); + TEST_ASSERT_EQ_I(seen, 2); + TEST_ASSERT_EQ_I(rc, RAY_OK); + int64_t quota = ray_os_cgroup_cpu_quota(); + int expect = (quota > 0 && (quota + 999) / 1000 < 2) ? 1 : 2; + TEST_ASSERT_EQ_I(total, expect); PASS(); } #endif @@ -1848,10 +1991,17 @@ static void pf_walk_gaps(void* ctx, uint32_t w, int64_t s, int64_t e) { } } +/* The file's length, not 0 ("to the end"): Linux 5.4 computes the pages a + * whole-file FADV_DONTNEED covers as end - start + 1 with end = ~0, which + * wraps to 0, so it never sees that pages were left and never drains the + * other CPUs' LRU caches to drop them — the last pages each worker brought + * in (up to a pagevec, 15, per CPU) stay cached. */ static bool pf_evict_one(const char* path) { int fd = open(path, O_RDONLY); if (fd < 0) return false; - bool ok = fdatasync(fd) == 0 && posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED) == 0; + struct stat st; + bool ok = fstat(fd, &st) == 0 && fdatasync(fd) == 0 && + posix_fadvise(fd, 0, st.st_size, POSIX_FADV_DONTNEED) == 0; close(fd); return ok; } @@ -1872,6 +2022,13 @@ static bool pf_none_resident(const uint8_t* p, size_t n) { return true; } +/* Resident pages of [p, p+n), probed one by one. */ +static int64_t pf_resident_pages(const uint8_t* p, size_t n) { + int64_t k = 0; + for (size_t off = 0; off < n; off += 4096) k += ray_vm_resident(p + off, 1); + return k; +} + /* Pages this process has read stay mapped and are not evicted: drop both * columns' mappings, evict the files, map them again and re-register. */ /* Finish every read before eviction. mincore reports an in-flight page as @@ -1899,14 +2056,8 @@ static bool pf_reset(uint8_t** base, size_t* size, uint8_t** bbase, size_t* bsiz if (!*base || !*bbase) return false; scan->base[0] = *base; scan->base[1] = *bbase; - return pf_none_resident(*base, *size) && pf_none_resident(*bbase, *bsize); -} - -/* Resident pages of [p, p+n), probed one by one. */ -static int64_t pf_resident_pages(const uint8_t* p, size_t n) { - int64_t k = 0; - for (size_t off = 0; off < n; off += 4096) k += ray_vm_resident(p + off, 1); - return k; + /* Every page: what an eviction leaves is a few pages here and there. */ + return !pf_resident_pages(*base, *size) && !pf_resident_pages(*bbase, *bsize); } /* Bounded wait (~10 s) for `want` pages of [p, p+n) to be resident. */ @@ -2253,8 +2404,10 @@ static int pq_open_cold(const char* name, const uint8_t** p, size_t* n) { ray_release(col); /* M holds it */ uintptr_t a = (uintptr_t)*p & ~(uintptr_t)4095; posix_madvise((void*)a, (uintptr_t)*p + *n - a, POSIX_MADV_RANDOM); - /* Opening reads the header, and the kernel the pages after it. */ - return pf_none_resident(*p + (512 << 10), *n - (512 << 10)) ? 0 : 1; + /* Opening reads the header, and the kernel the pages after it, and the + * last pages of the file. Every page between is probed: an eviction + * that falls short leaves a few pages here and there. */ + return pf_resident_pages(*p + (512 << 10), *n - (1024 << 10)) ? 1 : 0; } static long pq_majflt(void) { @@ -2403,6 +2556,10 @@ const test_entry_t pool_entries[] = { #if defined(__linux__) || defined(__APPLE__) { "pool/auto_all_logical_cpus", test_auto_all_logical_cpus, NULL, NULL }, #endif +#if defined(__linux__) + { "pool/auto_follows_cpu_set", test_auto_follows_cpu_set, NULL, NULL }, +#endif + { "pool/cpu_quota_child", test_cpu_quota_child, NULL, NULL }, { "pool/parallel_sum", test_parallel_sum, NULL, NULL }, { "pool/dispatch_reclaims_worker_blocks", test_dispatch_reclaims_worker_blocks, NULL, NULL }, { "pool/parallel_add", test_parallel_add, NULL, NULL }, @@ -2431,7 +2588,8 @@ const test_entry_t pool_entries[] = { { "pool/ray_cancel_global", test_ray_cancel_global, NULL, NULL }, { "pool/workers_participate", test_dispatch_workers_participate, NULL, NULL }, { "pool/dispatch_n_max_ring", test_dispatch_n_max_ring_cap_clamp, NULL, NULL }, - { "pool/dispatch_max_ring", test_dispatch_max_ring_cap_clamp, NULL, NULL }, + { "pool/dispatch_max_ring", test_dispatch_max_ring_rounds, NULL, NULL }, + { "pool/dispatch_cancel_rounds", test_dispatch_cancelled_skips_rounds, NULL, NULL }, { "pool/destroy_when_uninit", test_destroy_when_uninit, NULL, NULL }, { "pool/dispatch_n_multi_grow", test_dispatch_n_multi_grow, NULL, NULL }, { "pool/dispatch_n_exact_cap", test_dispatch_n_exact_cap, NULL, NULL }, diff --git a/test/test_public_api.c b/test/test_public_api.c index af8201e72..2eceed452 100644 --- a/test/test_public_api.c +++ b/test/test_public_api.c @@ -646,6 +646,65 @@ static test_result_t test_public_get_error_trace_cleared_on_eval(void) { PASS(); } +/* (raise x) stays O(1): it records x for `try` and formats nothing. An + * uncaught x is rendered only on demand, bounded, for an error printer; + * `try` consumes it and every top-level ray_eval_str clears it. */ +extern const char* ray_error_msg(void); +extern bool ray_raise_render(char* buf, size_t cap); +static test_result_t test_public_raise_render(void) { + char buf[64]; + + ray_t* err = ray_eval_str("(raise \"order 7 rejected\")"); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + TEST_ASSERT_STR_EQ(ray_err_code(err), "domain"); + TEST_ASSERT_NULL(ray_error_msg()); /* nothing formatted at raise */ + TEST_ASSERT_TRUE(ray_raise_render(buf, sizeof buf)); + TEST_ASSERT_STR_EQ(buf, "order 7 rejected"); + ray_error_free(err); + + err = ray_eval_str("((fn [] (raise [1 2 3])))"); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + TEST_ASSERT_TRUE(ray_raise_render(buf, sizeof buf)); + TEST_ASSERT_STR_EQ(buf, "[1 2 3]"); + ray_error_free(err); + + /* A table is summarised, not drawn. */ + err = ray_eval_str("(raise (table [a] (list [1 2])))"); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + TEST_ASSERT_TRUE(ray_raise_render(buf, sizeof buf)); + TEST_ASSERT_STR_EQ(buf, "
"); + ray_error_free(err); + + /* Large values render bounded, marked "..". */ + err = ray_eval_str("(raise (til 1000000))"); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + TEST_ASSERT_TRUE(ray_raise_render(buf, 16)); + TEST_ASSERT_EQ_I((int)strlen(buf), 15); + TEST_ASSERT_STR_EQ(buf + 13, ".."); + ray_error_free(err); + + /* A string longer than the buffer is cut, not over-read. */ + err = ray_eval_str("(raise \"abcdefghijklmnopqrstuvwxyz\")"); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); + TEST_ASSERT_TRUE(ray_raise_render(buf, 8)); + TEST_ASSERT_STR_EQ(buf, "abcde.."); + ray_error_free(err); + + /* The next top-level evaluation clears a pending value. */ + ray_t* r = ray_eval_str("(+ 1 2)"); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + ray_release(r); + TEST_ASSERT_FALSE(ray_raise_render(buf, sizeof buf)); + + /* try consumes the value and still hands the handler the raw value. */ + r = ray_eval_str("(try (raise 41) (fn [e] (+ e 1)))"); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 42); + ray_release(r); + TEST_ASSERT_FALSE(ray_raise_render(buf, sizeof buf)); + PASS(); +} + static test_result_t test_public_nullability_matrix(void) { ray_t* ordinary[] = { ray_sym(0), @@ -724,6 +783,7 @@ const test_entry_t public_api_entries[] = { { "public/eval_restricted_allows_arith", test_public_eval_restricted_allows_arith, public_api_setup, public_api_teardown }, { "public/get_error_trace_populated", test_public_get_error_trace_populated, public_api_setup, public_api_teardown }, { "public/get_error_trace_cleared_on_eval",test_public_get_error_trace_cleared_on_eval,public_api_setup, public_api_teardown }, + { "public/raise_render", test_public_raise_render, public_api_setup, public_api_teardown }, { "public/nullability_matrix", test_public_nullability_matrix, public_api_setup, public_api_teardown }, { NULL, NULL, NULL, NULL }, diff --git a/test/test_repl.c b/test/test_repl.c index 5397c2070..1dcffc3f0 100644 --- a/test/test_repl.c +++ b/test/test_repl.c @@ -48,6 +48,7 @@ #include "core/ipc.h" #include "core/sock.h" #include "core/platform.h" +#include "core/pool.h" /* ray_pool_default_total: the -c warning test */ #include "core/runtime.h" #include "mem/sys.h" @@ -280,6 +281,58 @@ static test_result_t test_repl_run_file_eval_error(void) { PASS(); } +/* Run tmp_rfl_path() through ray_repl_run_file with stderr captured into + * out (NUL-terminated, up to cap-1 bytes) and stdout muted. Returns rc. */ +static int run_file_capture_stderr(char* out, size_t cap) { + char path[96]; + snprintf(path, sizeof path, "/tmp/ray_test_repl_err_%d", (int)getpid()); + fflush(stdout); + fflush(stderr); + int saved_out = dup(fileno(stdout)); + int saved_err = dup(fileno(stderr)); + int devnull = open("/dev/null", O_WRONLY); + int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600); + if (devnull >= 0) dup2(devnull, fileno(stdout)); + if (fd >= 0) dup2(fd, fileno(stderr)); + + int rc = ray_repl_run_file(tmp_rfl_path()); + + fflush(stdout); + fflush(stderr); + if (saved_out >= 0) { dup2(saved_out, fileno(stdout)); close(saved_out); } + if (saved_err >= 0) { dup2(saved_err, fileno(stderr)); close(saved_err); } + if (devnull >= 0) close(devnull); + size_t n = 0; + if (fd >= 0) { + lseek(fd, 0, SEEK_SET); + ssize_t r = read(fd, out, cap - 1); + if (r > 0) n = (size_t)r; + close(fd); + } + out[n] = '\0'; + unlink(path); + return rc; +} + +/* An uncaught (raise x) prints x after the error code, on the plain path + * (top level) and on the traced path (inside a lambda). */ +static test_result_t test_repl_run_file_raise_prints_value(void) { + char out[4096]; + + TEST_ASSERT_EQ_I(write_rfl("(raise \"order 7 rejected\")\n"), 0); + int rc = run_file_capture_stderr(out, sizeof out); + TEST_ASSERT_EQ_I(rc, 1); + TEST_ASSERT_NOT_NULL(strstr(out, "error: domain: order 7 rejected")); + + TEST_ASSERT_EQ_I(write_rfl("(set f (fn [] (raise [1 2 3])))\n(f)\n"), 0); + rc = run_file_capture_stderr(out, sizeof out); + TEST_ASSERT_EQ_I(rc, 1); + TEST_ASSERT_NOT_NULL(strstr(out, "domain: [1 2 3]")); + + unlink_rfl(); + PASS(); +} + /* Empty file: ray_repl_run_file shortcircuits (nread == 0 path) and * returns 0 without calling parse/eval. */ static test_result_t test_repl_run_file_empty(void) { @@ -2320,6 +2373,20 @@ static test_result_t test_repl_run_piped_overflow_inner_drain(void) { * close the master from the parent — slave's read returns EIO (-1), so * ray_term_getc returns -1, sz <= 0 && sz != -2 → break (line 959). */ #ifndef RAY_OS_WINDOWS +/* A child that outlives the PTY master: its stderr off the PTY. Once the + * master is closed nobody can read what the child writes there, and its + * leak check at exit writes there all the same — after a fork it warns + * that the parent's threads, still in its thread registry, were not + * suspended. Older sanitizer runtimes (GCC 9) treat the failed write as + * fatal and kill the process from the leak checker's tracer (SIGKILL). + * The child's verdict is still its exit status. */ +static void pty_child_stderr_off(void) { + int fd = open("/dev/null", O_WRONLY); + if (fd < 0) return; + dup2(fd, STDERR_FILENO); + close(fd); +} + static int run_pty_nopoll_master_close(void) { int master_fd = -1; @@ -2331,6 +2398,7 @@ static int run_pty_nopoll_master_close(void) * ray_term_getc sees EIO and returns ≤0, triggering the break at * line 959 in the no-poll loop. */ signal(SIGHUP, SIG_IGN); + pty_child_stderr_off(); ray_runtime_create(0, NULL); /* No poll — uses blocking fallback loop. */ ray_repl_t* repl = ray_repl_create(NULL); @@ -2451,7 +2519,7 @@ static int run_pty_remote_ctrlD(uint16_t server_port) * at lines 858-866 rather than exiting the REPL. */ { char ctrlD = 4; /* ASCII EOT / Ctrl-D */ - write(master_fd, &ctrlD, 1); + if (write(master_fd, &ctrlD, 1) != 1) { /* the checks below then fail */ } } usleep(200 * 1000); @@ -2534,6 +2602,7 @@ static int run_pty_remote_master_close(uint16_t server_port) /* Ignore SIGHUP so the child survives the PTY master close long * enough for ray_term_getc to see EIO and take the sz<=0 path. */ signal(SIGHUP, SIG_IGN); + pty_child_stderr_off(); ray_runtime_create(0, NULL); ray_poll_t* poll = ray_poll_create(); ray_repl_t* repl = ray_repl_create(poll); @@ -2606,7 +2675,7 @@ static test_result_t test_repl_pty_remote_master_close(void) { } int rc = run_pty_remote_master_close(s.port); repl_stop_server(&s); - TEST_ASSERT_FMT(rc == 0 || rc == -1 || rc == -2 || rc == -9, + TEST_ASSERT_FMT(rc == 0 || rc == -1 || rc == -2, "unexpected child exit: %d", rc); #endif PASS(); @@ -2908,7 +2977,7 @@ static int run_pty_ctrl_c_during_lazy_materialize(void) { usleep(10 * 1000); } - (void)write(master_fd, ":q\n", 3); + if (write(master_fd, ":q\n", 3) != 3) { /* the wait below then times out */ } int status = 0; for (int i = 0; i < 30; i++) { pid_t r = waitpid(pid, &status, WNOHANG); @@ -2935,41 +3004,93 @@ static test_result_t test_repl_pty_ctrl_c_during_lazy_materialize(void) { } #if defined(__linux__) -/* Run the real launcher in piped REPL mode and count its live task threads. - * /proc/self/task observes the exact process-wide total, so this catches both +/* Share command capture and subprocess-status handling across launcher tests. */ +static int run_cli_capture(const char* command, char* output, size_t capacity, + int* status_out) { + if (!command || !output || capacity < 2 || !status_out) return -1; + FILE* pipe = popen(command, "r"); + if (!pipe) return -2; + size_t used = fread(output, 1, capacity - 1, pipe); + output[used] = '\0'; + *status_out = pclose(pipe); + return *status_out == -1 ? -3 : 0; +} + +/* /proc/self/task observes the exact process-wide total, so this catches both * the ordinary off-by-one and the -c 1 collision with the pool's auto mode. */ -static int run_cli_task_count(unsigned cores, long* out_count) { - char command[256]; +static int run_cli_task_count(const char* cores, long* out_count, bool* warned) { + char command[256], output[1024]; + int status; snprintf(command, sizeof(command), "printf '(count (.fs.list \"/proc/self/task\"))\\n'" - " | ./rayforce -c %u -i", cores); - - FILE* pipe = popen(command, "r"); - if (!pipe) return -1; - - char line[128]; - bool have_line = fgets(line, sizeof(line), pipe) != NULL; - int status = pclose(pipe); - if (!have_line || status == -1 || !WIFEXITED(status) || - WEXITSTATUS(status) != 0) - return -2; - + " | ./rayforce -c %s -i 2>&1", cores); + if (run_cli_capture(command, output, sizeof(output), &status) != 0 || + !WIFEXITED(status) || WEXITSTATUS(status) != 0 || + strstr(output, "ray_pool_init_total") != NULL || + strstr(output, "heap-ID pool exhausted") != NULL) + return -1; + /* a -c past the CPUs the process may use is warned of on stderr first */ + char* at = output; + if (warned) *warned = strncmp(at, "warning:", 8) == 0; + while (strncmp(at, "warning:", 8) == 0) { + char* nl = strchr(at, '\n'); + if (!nl) return -2; + at = nl + 1; + } char* end = NULL; - long count = strtol(line, &end, 10); - if (end == line) return -3; + long count = strtol(at, &end, 10); + if (end == at) return -2; *out_count = count; return 0; } static test_result_t test_repl_cli_cores_are_total(void) { long count = 0; - int rc = run_cli_task_count(1, &count); + bool warned = false; + int rc = run_cli_task_count("1", &count, &warned); TEST_ASSERT_FMT(rc == 0, "-c 1 launcher probe failed: %d", rc); TEST_ASSERT_FMT(count == 1, "-c 1 created %ld total threads", count); + TEST_ASSERT_FALSE(warned); - rc = run_cli_task_count(3, &count); + rc = run_cli_task_count("3", &count, NULL); TEST_ASSERT_FMT(rc == 0, "-c 3 launcher probe failed: %d", rc); TEST_ASSERT_FMT(count == 3, "-c 3 created %ld total threads", count); + + rc = run_cli_task_count("007", &count, NULL); + TEST_ASSERT_FMT(rc == 0, "-c 007 launcher probe failed: %d", rc); + TEST_ASSERT_FMT(count == 7, "-c 007 created %ld total threads", count); + + /* obeyed; warned of exactly when it passes the CPUs the process may use + * (the child runs under the same mask and quota) */ + rc = run_cli_task_count("1023", &count, &warned); + TEST_ASSERT_FMT(rc == 0, "-c 1023 launcher probe failed: %d", rc); + TEST_ASSERT_FMT(count == 1023, "-c 1023 created %ld total threads", count); + TEST_ASSERT_TRUE(warned == (1023 > ray_pool_default_total())); + PASS(); +} + +static test_result_t test_repl_cli_cores_reject_malformed(void) { + const struct { const char* args; const char* token; } bad[] = { + { "-c -1", "-1" }, + { "-c +4", "+4" }, + { "-c 1024", "1024" }, + { "-t 1abc", "1abc" }, + { "-Q 0abc", "0abc" }, + }; + for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) { + char command[256], output[512]; + int status; + snprintf(command, sizeof command, + "./rayforce %s &1", bad[i].args); + int rc = run_cli_capture(command, output, sizeof(output), &status); + TEST_ASSERT_FMT(rc == 0 && WIFEXITED(status) && + WEXITSTATUS(status) == 2, + "%s exited with status %d and output %s", bad[i].args, + status, output); + TEST_ASSERT_FMT(strstr(output, "error:") != NULL && + strstr(output, bad[i].token) != NULL, + "%s was not clearly rejected: %s", bad[i].args, output); + } PASS(); } #endif @@ -2979,12 +3100,14 @@ static test_result_t test_repl_cli_cores_are_total(void) { const test_entry_t repl_entries[] = { #if defined(__linux__) { "repl/cli/cores_are_total", test_repl_cli_cores_are_total, NULL, NULL }, + { "repl/cli/cores_reject_malformed", test_repl_cli_cores_reject_malformed, NULL, NULL }, #endif /* file-batch entrypoint — ray_repl_run_file */ { "repl/run_file/happy", test_repl_run_file_happy, repl_setup, repl_teardown }, { "repl/run_file/multi_form", test_repl_run_file_multi_form, repl_setup, repl_teardown }, { "repl/run_file/parse_error", test_repl_run_file_parse_error, repl_setup, repl_teardown }, { "repl/run_file/eval_error", test_repl_run_file_eval_error, repl_setup, repl_teardown }, + { "repl/run_file/raise_prints_value", test_repl_run_file_raise_prints_value, repl_setup, repl_teardown }, { "repl/run_file/empty", test_repl_run_file_empty, repl_setup, repl_teardown }, { "repl/run_file/comments_only", test_repl_run_file_comments_only, repl_setup, repl_teardown }, { "repl/run_file/nonexistent", test_repl_run_file_nonexistent, repl_setup, repl_teardown }, diff --git a/test/test_rowsel.c b/test/test_rowsel.c index 8a28a0a3e..c3a89e79e 100644 --- a/test/test_rowsel.c +++ b/test/test_rowsel.c @@ -523,6 +523,111 @@ static test_result_t test_rowsel_emit_equiv(void) { PASS(); } +/* rowsel_emit_runs and rowsel_emit_uniform produce the segments + * rowsel_emit_segment makes of the same bools: runs of lengths 1-40 with + * pseudo-random pass flags (NONE, ALL and MIX outcomes, a short last + * morsel), and uniform segments of either value. */ +static test_result_t test_rowsel_emit_runs_equiv(void) { + ray_heap_init(); + int64_t nrows = (int64_t)RAY_MORSEL_ELEMS * 9 + 300; + uint32_t n_segs = (uint32_t)((nrows + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS); + rowsel_builder_t a, b; + rowsel_builder_init(&a, n_segs); + rowsel_builder_init(&b, n_segs); + uint64_t x = 88172645463325252ull; + for (uint32_t s = 0; s < n_segs; s++) { + int64_t lo = (int64_t)s * RAY_MORSEL_ELEMS; + int64_t n = (lo + RAY_MORSEL_ELEMS <= nrows) ? RAY_MORSEL_ELEMS : (nrows - lo); + uint8_t bools[RAY_MORSEL_ELEMS]; + if (s == 3 || s == 4) { /* uniform: ALL, then NONE */ + uint8_t d = s == 3; + memset(bools, d, (size_t)n); + rowsel_emit_segment(&a, s, bools, n); + rowsel_emit_uniform(&b, s, d, n); + continue; + } + uint16_t ends[RAY_MORSEL_ELEMS]; + uint8_t pass[RAY_MORSEL_ELEMS]; + uint32_t nr = 0; + int64_t i = 0; + while (i < n) { + x ^= x << 13; x ^= x >> 7; x ^= x << 17; + int64_t len = 1 + (int64_t)(x % 40); + if (i + len > n) len = n - i; + /* segment 0 all fail, 1 all pass, the rest mixed */ + uint8_t p = s == 0 ? 0 : s == 1 ? 1 : (uint8_t)((x >> 20) & 1); + memset(bools + i, p, (size_t)len); + i += len; + ends[nr] = (uint16_t)i; pass[nr] = p; nr++; + } + rowsel_emit_segment(&a, s, bools, n); + rowsel_emit_runs(&b, s, ends, pass, nr, n); + } + ray_t* ref = rowsel_builder_finish(&a, 1, nrows); + ray_t* got = rowsel_builder_finish(&b, 1, nrows); + TEST_ASSERT_NOT_NULL(ref); + TEST_ASSERT_NOT_NULL(got); + TEST_ASSERT(ray_rowsel_meta(got)->total_pass == ray_rowsel_meta(ref)->total_pass, "total_pass"); + TEST_ASSERT(memcmp(ray_rowsel_flags(got), ray_rowsel_flags(ref), n_segs) == 0, "flags"); + TEST_ASSERT(ray_rowsel_flags(ref)[0] == RAY_SEL_NONE && ray_rowsel_flags(ref)[1] == RAY_SEL_ALL && + ray_rowsel_flags(ref)[2] == RAY_SEL_MIX && ray_rowsel_flags(ref)[3] == RAY_SEL_ALL && + ray_rowsel_flags(ref)[4] == RAY_SEL_NONE, "outcomes"); + TEST_ASSERT(memcmp(ray_rowsel_offsets(got), ray_rowsel_offsets(ref), (size_t)(n_segs + 1) * sizeof(uint32_t)) == 0, "offsets"); + int64_t ic = ray_rowsel_offsets(ref)[n_segs]; + TEST_ASSERT(memcmp(ray_rowsel_idx(got), ray_rowsel_idx(ref), (size_t)ic * sizeof(uint16_t)) == 0, "idx"); + ray_rowsel_release(ref); + ray_rowsel_release(got); + ray_heap_destroy(); + PASS(); +} + +/* ray_rowsel_head keeps the first `limit` rows of a selection, in order: + * whole segments before the cut as they are, the cut segment MIX (an ALL + * one too), NONE after it. Segments: MIX, ALL, NONE, a partial MIX. */ +static test_result_t test_rowsel_head(void) { + ray_heap_init(); + int64_t nrows = (int64_t)RAY_MORSEL_ELEMS * 3 + 7; + ray_t* pred = ray_vec_new(RAY_BOOL, nrows); + TEST_ASSERT_NOT_NULL(pred); + uint8_t* p = (uint8_t*)ray_data(pred); + for (int64_t i = 0; i < nrows; i++) { + uint32_t seg = (uint32_t)(i / RAY_MORSEL_ELEMS); + p[i] = (seg == 0) ? (uint8_t)(i % 3 == 0) + : (seg == 1) ? 1 + : (seg == 2) ? 0 + : (uint8_t)(i % 2 == 0); + } + pred->len = nrows; + ray_t* sel = ray_rowsel_from_pred(pred); + TEST_ASSERT_NOT_NULL(sel); + int64_t total = ray_rowsel_meta(sel)->total_pass; + int64_t k0 = (RAY_MORSEL_ELEMS + 2) / 3; /* rows kept in seg 0 */ + + static int64_t all[RAY_MORSEL_ELEMS * 4], got[RAY_MORSEL_ELEMS * 4]; + TEST_ASSERT_EQ_I(reconstruct(sel, all), total); + int64_t limits[] = { 0, 1, 5, k0, k0 + 10, k0 + RAY_MORSEL_ELEMS, + k0 + RAY_MORSEL_ELEMS + 2, total - 1 }; + for (size_t t = 0; t < sizeof(limits) / sizeof(limits[0]); t++) { + int64_t lim = limits[t]; + ray_t* h = ray_rowsel_head(sel, lim); + TEST_ASSERT_NOT_NULL(h); + TEST_ASSERT_EQ_I(ray_rowsel_meta(h)->nrows, nrows); + TEST_ASSERT_EQ_I(ray_rowsel_meta(h)->total_pass, lim); + TEST_ASSERT_EQ_I(reconstruct(h, got), lim); + for (int64_t i = 0; i < lim; i++) TEST_ASSERT_EQ_I(got[i], all[i]); + if (lim == k0 + RAY_MORSEL_ELEMS) /* cut at a segment end */ + TEST_ASSERT_EQ_I(ray_rowsel_flags(h)[1], RAY_SEL_ALL); + if (lim == k0 + 10) /* cut inside an ALL */ + TEST_ASSERT_EQ_I(ray_rowsel_flags(h)[1], RAY_SEL_MIX); + TEST_ASSERT_EQ_I(ray_rowsel_flags(h)[3], lim > k0 + RAY_MORSEL_ELEMS ? RAY_SEL_MIX : RAY_SEL_NONE); + ray_rowsel_release(h); + } + ray_rowsel_release(sel); + ray_release(pred); + ray_heap_destroy(); + PASS(); +} + /* ────────────────────────────────────────────────────────────────── * Suite registration * ────────────────────────────────────────────────────────────────── */ @@ -541,6 +646,8 @@ const test_entry_t rowsel_entries[] = { { "rowsel/refine_null_existing", test_rowsel_refine_null_existing, NULL, NULL }, { "rowsel/intersect_mixed_reused_block", test_rowsel_intersect_mixed_reused_block, NULL, NULL }, { "rowsel/emit_equiv", test_rowsel_emit_equiv, NULL, NULL }, + { "rowsel/emit_runs_equiv", test_rowsel_emit_runs_equiv, NULL, NULL }, + { "rowsel/head", test_rowsel_head, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_runtime.c b/test/test_runtime.c index c3a11cddd..d6bbcb447 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -33,6 +33,7 @@ #include "core/platform.h" /* ray_os_cgroup_mem_limit */ #include "mem/heap.h" /* ray_heap_anon_watermark */ #include "lang/format.h" /* ray_fmt for eval_err */ +#include "lang/eval.h" /* ray_raise_render */ #include #include #include @@ -675,10 +676,30 @@ static test_result_t test_build_sys_args_edges(void) { PASS(); } +static test_result_t test_build_sys_args_mem_flag(void) { + char* cases[][4] = { + { "rayforce", "script.rfl", "-m", "4G" }, + { "rayforce", "script.rfl", "--mem", "512M" }, + { "rayforce", "-m", "4G", "script.rfl" }, + { "rayforce", "--mem", "512M", "script.rfl" }, + }; + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + ray_t* d = ray_build_sys_args(4, cases[i]); + TEST_ASSERT_FALSE(RAY_IS_ERR(d)); + ray_t* file = args_top(d, "file"); + TEST_ASSERT_EQ_I(file->type, -RAY_STR); + TEST_ASSERT_EQ_I(strcmp(ray_str_ptr(file), "script.rfl"), 0); + ray_release(file); + ray_release(d); + } + PASS(); +} + static test_result_t test_build_sys_args_rejects_malformed_numbers(void) { char* cases[][3] = { { "rayforce", "-c", "2abc" }, { "rayforce", "-c", "999999999999999999999999" }, + { "rayforce", "-c", "1024" }, { "rayforce", "-t", "1abc" }, { "rayforce", "-Q", "0abc" }, }; @@ -1125,6 +1146,54 @@ static test_result_t test_timer_callback_error(void) { PASS(); } +/* A callback that raises prints the raised value after the code, as the + * REPL does; a value left pending by an earlier evaluation is not + * reported against the callback's own error. */ +static test_result_t test_timer_callback_raise(void) { + ray_poll_t* poll = (ray_poll_t*)ray_runtime_get_poll(); + TEST_ASSERT_NOT_NULL(poll); + + /* A stale uncaught raise from a "previous line". */ + ray_t* stale = ray_eval_str("(raise \"stale value\")"); + TEST_ASSERT_TRUE(RAY_IS_ERR(stale)); + ray_error_free(stale); + + char path[96]; + snprintf(path, sizeof path, "/tmp/ray_test_timer_err_%d", (int)getpid()); + fflush(stderr); + int saved = dup(STDERR_FILENO); + int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600); + TEST_ASSERT_TRUE(fd >= 0); + dup2(fd, STDERR_FILENO); + + ray_t* id = ray_eval_str( + "(.time.timer.set 1 1 (fn [t] (raise \"order 7 rejected\")))"); + ray_t* id2 = ray_eval_str( + "(.time.timer.set 2 1 (fn [t] (* t \"oops\")))"); + ray_timers_pump_for((ray_timers_t*)poll->timers, 60); + + fflush(stderr); + if (saved >= 0) { dup2(saved, STDERR_FILENO); close(saved); } + char out[2048]; + lseek(fd, 0, SEEK_SET); + ssize_t n = read(fd, out, sizeof out - 1); + out[n > 0 ? n : 0] = '\0'; + close(fd); + unlink(path); + + TEST_ASSERT_FALSE(RAY_IS_ERR(id)); + TEST_ASSERT_FALSE(RAY_IS_ERR(id2)); + TEST_ASSERT_NOT_NULL(strstr(out, "error: domain: order 7 rejected")); + TEST_ASSERT_NOT_NULL(strstr(out, "error: type")); + TEST_ASSERT_NULL(strstr(out, "stale value")); + /* The raised value does not linger past the report. */ + char buf[32]; + TEST_ASSERT_FALSE(ray_raise_render(buf, sizeof buf)); + ray_release(id); + ray_release(id2); + PASS(); +} + /* ray_timers_pump_for guard rails: NULL ptr + non-positive budget. */ static test_result_t test_timer_pump_for_guards(void) { /* Both early-return; nothing crashes. */ @@ -1366,6 +1435,7 @@ const test_entry_t runtime_entries[] = { { "runtime/build_sys_args_defaults", test_build_sys_args_defaults, sys_setup, sys_teardown }, { "runtime/build_sys_args_flags_user", test_build_sys_args_flags_and_user, sys_setup, sys_teardown }, { "runtime/build_sys_args_edges", test_build_sys_args_edges, sys_setup, sys_teardown }, + { "runtime/build_sys_args_mem_flag", test_build_sys_args_mem_flag, sys_setup, sys_teardown }, { "runtime/build_sys_args_rejects_malformed_numbers", test_build_sys_args_rejects_malformed_numbers, sys_setup, sys_teardown }, { "runtime/sys_args_builtin", test_sys_args_builtin, sys_setup, sys_teardown }, { "runtime/syscov_rc", test_syscov_rc, sys_setup, sys_teardown }, @@ -1380,6 +1450,7 @@ const test_entry_t runtime_entries[] = { { "runtime/timer_heap_tie_break", test_timer_heap_tie_break, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_forever_rearm", test_timer_forever_rearm, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_callback_error", test_timer_callback_error, sys_setup_with_poll, sys_teardown_with_poll }, + { "runtime/timer_callback_raise", test_timer_callback_raise, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_pump_for_guards", test_timer_pump_for_guards, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/timer_create_destroy_paths", test_timer_create_destroy_paths, sys_setup_with_poll, sys_teardown_with_poll }, { "runtime/syscov_env", test_syscov_env, sys_setup, sys_teardown }, diff --git a/test/test_scan_range.c b/test/test_scan_range.c new file mode 100644 index 000000000..31c42fd60 --- /dev/null +++ b/test/test_scan_range.c @@ -0,0 +1,6480 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include +#include "mem/heap.h" +#include "ops/ops.h" +#include "table/sym.h" +#include "table/domain.h" +#include "table/table.h" +#include "core/runtime.h" +#include "core/platform.h" +#include "core/pool.h" +#include "lang/eval.h" +#include "lang/env.h" +#include "lang/format.h" +#include "lang/parse.h" +#include "store/col.h" +#include "store/colrange.h" +#include "store/enccol.h" +#include "store/encfmt.h" +#include "store/encw.h" /* ray_encw_test_force */ +#include "store/splay.h" +#include "store/part.h" +#include "vec/str.h" +#include "vec/vec.h" +#include "ops/internal.h" +#include "ops/rowsel.h" +#include "ops/idxop.h" +#include "ops/fused_pred.h" +#include "ops/fused_topk.h" +#include +#include +#include +#include +#include +#include + +/* Every path below goes through ray_test_tmp (a per-process root). */ +/* Written as "/tmp/..." in the sources: every use goes through + * ray_test_tmp (sr_root, sr_eval*, the helpers), which rewrites it under the + * process's own root, so concurrent suites never share it. */ +#define SR_TMP "/tmp/rayforce_scanrange" +static const char* sr_root(void) { return ray_test_tmp(SR_TMP); } + +/* Heap-only fixtures (Tasks 1-2: vectors saved and mapped directly). */ +static void sr_setup(void) { ray_heap_init(); (void)ray_sym_init(); (void)ray_test_rm_rf(sr_root()); (void)ray_test_mkdir_p(sr_root()); } +static void sr_teardown(void) { ray_test_hooks_off(); ray_sym_destroy(); ray_heap_destroy(); (void)ray_test_rm_rf(sr_root()); } + +/* Runtime fixtures without the shared table (parted loads, Rayfall saves). */ +static ray_runtime_t* g_srt; +static void sr_rt_setup(void) { g_srt = ray_runtime_create(0, NULL); (void)ray_test_rm_rf(sr_root()); (void)ray_test_mkdir_p(sr_root()); } +static void sr_rt_teardown(void) { ray_test_hooks_off(); (void)ray_test_rm_rf(sr_root()); ray_runtime_destroy(g_srt); } + +/* Evaluate Rayfall that must succeed; "/tmp" paths inside are moved. */ +static void sr_eval_ok(const char* src) { + ray_t* r = ray_eval_str(ray_test_tmp(src)); + if (r && RAY_IS_ERR(r)) { fprintf(stderr, "sr_eval_ok: %s: %s\n", src, ray_error_msg()); ray_error_free(r); abort(); } + if (r) ray_release(r); +} +static void sr_evalf_ok(const char* fmt, ...) { + char buf[2048]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + sr_eval_ok(buf); +} +/* Fixtures for the later P2 tests in this suite. */ +__attribute__((unused)) static ray_t* sr_eval(const char* src) { return ray_eval_str(ray_test_tmp(src)); } +__attribute__((unused)) static void sr_drop(ray_t* o) { if (!o) return; if (RAY_IS_ERR(o)) ray_error_free(o); else ray_release(o); } + +/* Cold computed-key fallback: source identities alone cannot detect a + * temporary gen0 flatten. The all-heap cumulative allocation scope below + * additionally rejects copying the 64 unused I32 columns (10,240,000 bytes + * of payload alone). This is not a historical peak/scratch-space budget. */ +static ray_t *sr_cold_table, *sr_cold_result; +static bool sr_cold_tracing; +static void sr_cold_teardown(void) { + if (sr_cold_tracing) { + ray_mem_trace_t ignored; + ray_mem_trace_end(&ignored); + sr_cold_tracing = false; + } + ray_enccol_test_parted_mode(0); + sr_drop(sr_cold_result); sr_cold_result = NULL; + sr_drop(sr_cold_table); sr_cold_table = NULL; + sr_rt_teardown(); +} + +typedef struct { + int64_t names[66]; + ray_t* slots[66]; + ray_t* segs[66][8]; + ray_t* decoded[2]; + ray_t* decoded_segs[2][8]; +} sr_cold_source_t; + +/* All observations here borrow; the owned sr_cold_table keeps them alive. + * Do not use ray_table_get_col / ray_enccol_seg_col on the source. */ +static test_result_t sr_cold_snapshot(sr_cold_source_t* src, int gen) { + TEST_ASSERT_EQ_I(ray_table_nrows(sr_cold_table), 40000); + for (int c = 0; c < 66; c++) { + char name[16]; + if (c < 2) snprintf(name, sizeof name, "%s", c ? "lo" : "k"); + else snprintf(name, sizeof name, "c%d", c - 2); + src->names[c] = ray_sym_intern(name, strlen(name)); + ray_t* slot = src->slots[c] = ray_table_slot(sr_cold_table, src->names[c]); + int base = c < 2 ? RAY_I64 : RAY_I32; + TEST_ASSERT_FMT(slot, "gen%d missing slot %s", gen, name); + if (gen == 2) { + TEST_ASSERT_EQ_I(slot->type, RAY_ENCCOL); + TEST_ASSERT_TRUE(ray_enccol_is_parted(slot)); + TEST_ASSERT_EQ_I(ray_enccol_of(slot)->type, base); + TEST_ASSERT_EQ_I(ray_enccol_of(slot)->len, 40000); + TEST_ASSERT_EQ_I(ray_enccol_of(slot)->wrapper->len, 8); + TEST_ASSERT_FMT(!ray_enccol_decoded_peek(slot), "gen2 %s wrapper not cold", name); + } else { + TEST_ASSERT_EQ_I(slot->type, RAY_PARTED_BASE + base); + TEST_ASSERT_EQ_I(slot->len, 8); + } + for (int p = 0; p < 8; p++) { + ray_t* seg = src->segs[c][p] = ray_table_parted_seg(sr_cold_table, src->names[c], p); + TEST_ASSERT_FMT(seg, "gen%d %s missing partition %d", gen, name, p); + if (gen == 2) { + TEST_ASSERT_EQ_I(seg->type, RAY_ENCCOL); + TEST_ASSERT_FALSE(ray_enccol_is_parted(seg)); + TEST_ASSERT_FALSE(ray_enccol_is_synthetic(seg)); + TEST_ASSERT_EQ_I(ray_col_gen_of(ray_enccol_of(seg)->base), 2); + TEST_ASSERT_EQ_I(ray_enccol_of(seg)->type, base); + TEST_ASSERT_EQ_I(ray_enccol_of(seg)->len, 5000); + TEST_ASSERT_FMT(!ray_enccol_decoded_peek(seg), "gen2 %s partition %d not cold", name, p); + } else { + TEST_ASSERT_EQ_I(seg->type, base); + TEST_ASSERT_EQ_I(seg->len, 5000); + TEST_ASSERT_EQ_U(seg->mmod, 1); /* explicit uncompressed save, not equivalence default */ + } + } + TEST_ASSERT_NULL(ray_table_parted_seg(sr_cold_table, src->names[c], 8)); + } + PASS(); +} + +static test_result_t sr_cold_after(sr_cold_source_t* src, int gen, bool repeat) { + for (int c = 0; c < 66; c++) { + ray_t* slot = ray_table_slot(sr_cold_table, src->names[c]); + TEST_ASSERT_EQ_PTR(slot, src->slots[c]); + ray_t* dec = gen == 2 ? ray_enccol_decoded_peek(slot) : NULL; + if (gen == 2 && c < 2) { + TEST_ASSERT_NOT_NULL(dec); + TEST_ASSERT_EQ_I(dec->type, RAY_PARTED_BASE + RAY_I64); + TEST_ASSERT_EQ_I(dec->len, 8); + if (repeat) TEST_ASSERT_EQ_PTR(dec, src->decoded[c]); + else src->decoded[c] = dec; + } else TEST_ASSERT_NULL(dec); + for (int p = 0; p < 8; p++) { + ray_t* seg = ray_table_parted_seg(sr_cold_table, src->names[c], p); + TEST_ASSERT_EQ_PTR(seg, src->segs[c][p]); + ray_t* d = gen == 2 ? ray_enccol_decoded_peek(seg) : NULL; + if (gen == 2 && c < 2) { + TEST_ASSERT_NOT_NULL(d); + TEST_ASSERT_EQ_I(d->type, RAY_I64); + TEST_ASSERT_EQ_I(d->len, 5000); + TEST_ASSERT_EQ_PTR(((ray_t**)ray_data(dec))[p], d); + if (repeat) TEST_ASSERT_EQ_PTR(d, src->decoded_segs[c][p]); + else src->decoded_segs[c][p] = d; + } else TEST_ASSERT_FMT(!d, "unused column %d partition %d decoded", c, p); + } + } + PASS(); +} + +static test_result_t cold_fallback_pruning(int gen, int dict) { + /* Construction tables are call-local; no table binding is retained. + * Explicit options override the suite's save defaults. */ + sr_eval_ok("(set SRcoldMk (fn [p] (table " + "(concat ['k 'lo] (as 'SYMBOL (map (fn [j] (format \"c%\" j)) (til 64)))) " + "(concat (list (as 'I64 (+ (* p 5000) (til 5000))) (as 'I64 (% (til 5000) 10))) " + "(map (fn [j] (as 'I32 (+ j (til 5000)))) (til 64))))))"); + for (int p = 0; p < 8; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/cold%d/2024.01.0%d/t/\" (SRcoldMk %d) {compress: %s})", + gen, p + 1, p, gen ? "true" : "false"); + sr_eval_ok("(set SRcoldMk 0)"); + + for (int mode = 0; mode <= 1; mode++) { + ray_enccol_test_parted_mode(mode); + ray_parted_cache_prune(); + int64_t live_before = ray_enccol_test_live(); + sr_evalf_ok("(set SRcoldP (.db.parted.get \"" SR_TMP "/cold%d/\" 't))", gen); + sr_cold_table = sr_eval("SRcoldP"); + TEST_ASSERT_TRUE(sr_cold_table && !RAY_IS_ERR(sr_cold_table)); + uint32_t refs_before = ray_atomic_load(&sr_cold_table->rc); + sr_cold_source_t src = {0}; + test_result_t check = sr_cold_snapshot(&src, gen); + if (check.status != TEST_PASS) return check; + const char* q = dict + ? "(do (set SRcoldQ (select {c: (count k) by: {kk: (reverse lo)} from: SRcoldP})) (count SRcoldQ))" + : "(do (set SRcoldQ (select {c: (count k) by: (reverse lo) from: SRcoldP})) (count SRcoldQ))"; + ray_enc_counters_reset(); + /* Stop before inspecting either a result or error. No assert + * or early return occurs inside this process-global scope. */ + sr_cold_tracing = ray_mem_trace_begin(); + if (!sr_cold_tracing) FAIL("could not begin cold allocation trace"); + sr_cold_result = sr_eval(q); + ray_mem_trace_t traffic; + ray_mem_trace_end(&traffic); + sr_cold_tracing = false; + TEST_ASSERT_FMT(sr_cold_result && !RAY_IS_ERR(sr_cold_result), + "cold gen%d mode%d dict%d: %s", gen, mode, dict, ray_error_msg()); + TEST_ASSERT_EQ_I(sr_cold_result->type, -RAY_I64); + TEST_ASSERT_EQ_I(sr_cold_result->i64, 10); + TEST_ASSERT_FMT(traffic.allocated_bytes < 8u * 1024u * 1024u, + "gen%d mode%d dict%d allocated %llu bytes (budget <8MiB)", gen, mode, dict, + (unsigned long long)traffic.allocated_bytes); + sr_drop(sr_cold_result); sr_cold_result = NULL; + ray_enc_counters_t counters; + ray_enc_counters_get(&counters); + /* Only successful single segment materializations count; + * the two parted wrapper publications do not add two. */ + TEST_ASSERT_EQ_U(counters.materialized, gen == 2 ? 16 : 0); + check = sr_cold_after(&src, gen, false); + if (check.status != TEST_PASS) return check; + sr_cold_result = sr_eval("SRcoldQ"); + TEST_ASSERT_TRUE(sr_cold_result && !RAY_IS_ERR(sr_cold_result)); + TEST_ASSERT_EQ_I(ray_table_nrows(sr_cold_result), 10); + /* Result-only get_col is allowed to force; source peeks above + * and below must never force materialization. */ + ray_t* counts = ray_table_get_col(sr_cold_result, ray_sym_intern("c", 1)); + TEST_ASSERT_TRUE(counts && !RAY_IS_ERR(counts)); + TEST_ASSERT_EQ_I(counts->type, RAY_I64); + TEST_ASSERT_EQ_I(counts->len, 10); + for (int i = 0; i < 10; i++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(counts))[i], 4000); + sr_drop(sr_cold_result); sr_cold_result = NULL; + sr_eval_ok("(set SRcoldQ 0)"); + TEST_ASSERT_EQ_U(ray_atomic_load(&sr_cold_table->rc), refs_before); + sr_cold_result = sr_eval(q); + TEST_ASSERT_TRUE(sr_cold_result && !RAY_IS_ERR(sr_cold_result)); + TEST_ASSERT_EQ_I(sr_cold_result->i64, 10); + ray_enc_counters_get(&counters); + TEST_ASSERT_EQ_U(counters.materialized, gen == 2 ? 16 : 0); + check = sr_cold_after(&src, gen, true); + if (check.status != TEST_PASS) return check; + sr_drop(sr_cold_result); sr_cold_result = NULL; + sr_eval_ok("(set SRcoldQ 0)"); + TEST_ASSERT_EQ_U(ray_atomic_load(&sr_cold_table->rc), refs_before); + sr_eval_ok("(set SRcoldP 0)"); + sr_drop(sr_cold_table); sr_cold_table = NULL; + /* The loader deliberately caches partition sub-tables. Prune only + * unused entries; leaked outside references would keep them alive. */ + ray_parted_cache_prune(); + TEST_ASSERT_EQ_I(ray_enccol_test_live(), live_before); + /* Reload next time; cold assertions deliberately fail if a + * loader ever shares already-published segment caches. */ + } + PASS(); +} + +static test_result_t test_cold_fallback_gen0_bare(void) { + return cold_fallback_pruning(0, 0); +} + +static test_result_t test_cold_fallback_gen0_dict(void) { + return cold_fallback_pruning(0, 1); +} + +static test_result_t test_cold_fallback_gen2_bare(void) { + return cold_fallback_pruning(2, 0); +} + +static test_result_t test_cold_fallback_gen2_dict(void) { + return cold_fallback_pruning(2, 1); +} + +static ray_t* sr_i32(int64_t n, int64_t null_every) { + ray_t* v = ray_vec_new(RAY_I32, n); v->len = n; + for (int64_t i = 0; i < n; i++) + ((int32_t*)ray_data(v))[i] = (null_every && i % null_every == 0) ? NULL_I32 : (int32_t)(i * 3 - 7); + if (null_every) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} +static ray_t* sr_f64(int64_t n, int64_t null_every) { + ray_t* v = ray_vec_new(RAY_F64, n); v->len = n; + for (int64_t i = 0; i < n; i++) + ((double*)ray_data(v))[i] = (null_every && i % null_every == 0) ? NULL_F64 : (double)i * 0.25 - 3.0; + if (null_every) v->attrs |= RAY_ATTR_HAS_NULLS; + return v; +} + +/* Save `v` as generation 2 under the root as and map it back. */ +static ray_t* sr_gen2(ray_t* v, const char* name) { + char p[512]; snprintf(p, sizeof p, "%s/%s", sr_root(), name); + if (ray_col_save_gen(v, p, 2) != RAY_OK) return NULL; + return ray_col_mmap(p); +} + +/* A piece function that copies every piece of source 0 (4-byte or 8-byte + * elements) into out[b - lo .. e - lo) and records the piece count and the + * attrs / pool of the last piece. */ +typedef struct { char* out; int64_t lo; uint8_t esz; int pieces; int64_t max_piece; + uint8_t attrs; const char* pool; const void* first_data; } sr_walk_t; +static void sr_piece(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sr_walk_t* w = ctx; + memcpy(w->out + (size_t)(b - w->lo) * w->esz, p[0].data, (size_t)(e - b) * w->esz); + if (!w->pieces) w->first_data = p[0].data; + w->pieces++; + if (e - b > w->max_piece) w->max_piece = e - b; + w->attrs = p[0].attrs; w->pool = p[0].str_pool; +} + +static test_result_t test_walk_gen0_zero_copy(void) { + ray_t* v = sr_i32(20000, 5); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(v, &s)); + TEST_ASSERT_EQ_PTR(ray_col_src_ready(&s), v); /* plain: ready as is */ + TEST_ASSERT_EQ_PTR(ray_col_src_base(&s), ray_data(v)); + ray_col_src_t* srcs[1] = { &s }; + const void* plain[1] = { ray_col_src_base(&s) }; + static char out[20000 * 4]; + sr_walk_t w = { out, 1000, 4, 0, 0, 0, NULL, NULL }; + TEST_ASSERT_NULL(ray_col_walk(srcs, plain, 1, 1000, 9192, false, &w, 0, sr_piece)); + TEST_ASSERT_EQ_I(w.pieces, 1); /* one piece, zero copy */ + TEST_ASSERT_EQ_PTR(w.first_data, (int32_t*)ray_data(v) + 1000); + ray_col_cursor_t c; ray_col_cursor_init(&c, &s); + const ray_col_range_t* rv; + TEST_ASSERT_NULL(ray_col_cursor_at(&c, 1500, &rv)); + TEST_ASSERT_EQ_PTR(rv->data, (int32_t*)ray_data(v) + 1500); /* plain: pointer identity */ + ray_col_cursor_free(&c); ray_col_src_release(&s); ray_release(v); + PASS(); +} + +static test_result_t test_walk_gen2_vectors(void) { + ray_t* v = sr_i32(20000, 5); + ray_t* c = sr_gen2(v, "a"); + TEST_ASSERT_TRUE(c && c->type == RAY_ENCCOL); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + TEST_ASSERT_TRUE(ray_col_src_encoded(&s)); + TEST_ASSERT_NULL(ray_col_src_ready(&s)); /* not materialized */ + ray_col_src_t* srcs[1] = { &s }; + const void* plain[1] = { NULL }; + static char out[20000 * 4]; + sr_walk_t w = { out, 2048, 4, 0, 0, 0, NULL, NULL }; + ray_enc_counters_reset(); + TEST_ASSERT_NULL(ray_col_walk(srcs, plain, 1, 2048, 10240, false, &w, 0, sr_piece)); + TEST_ASSERT_EQ_I(w.pieces, 8); /* one per vector */ + TEST_ASSERT_EQ_I(w.max_piece, 1024); + TEST_ASSERT_TRUE(memcmp(out, (int32_t*)ray_data(v) + 2048, 8192 * 4) == 0); /* sentinels in data */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 8192 * 4); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +/* Carry 6 / finding I7: once the column is materialized, cursors and the + * walk read the published vector; nothing is decoded again. */ +static test_result_t test_walk_decoded_cache(void) { + ray_t* v = sr_i32(20000, 5); + ray_t* c = sr_gen2(v, "dc"); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_t* pl = NULL; + TEST_ASSERT_NULL(ray_col_src_plain(&s, &pl)); /* one materialization */ + TEST_ASSERT_EQ_PTR(ray_col_src_ready(&s), pl); + TEST_ASSERT_EQ_PTR(ray_col_src_base(&s), ray_data(pl)); /* published: read in place */ + ray_enc_counters_reset(); + ray_col_cursor_t cur; ray_col_cursor_init(&cur, &s); + const ray_col_range_t* rv; + TEST_ASSERT_NULL(ray_col_cursor_at(&cur, 3000, &rv)); + TEST_ASSERT_EQ_PTR(rv->data, (int32_t*)ray_data(pl) + 3000); /* zero copy from the published vector */ + ray_col_cursor_free(&cur); + ray_col_src_t* srcs[1] = { &s }; + const void* plain[1] = { NULL }; /* a caller that did not check: still no decode */ + static char out[20000 * 4]; + sr_walk_t w = { out, 0, 4, 0, 0, 0, NULL, NULL }; + TEST_ASSERT_NULL(ray_col_walk(srcs, plain, 1, 0, 20000, false, &w, 0, sr_piece)); + TEST_ASSERT_TRUE(memcmp(out, ray_data(v), 20000 * 4) == 0); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +/* Review focus 1: unaligned bounds over a plain and a generation-2 source + * at once: pieces end at the generation-2 vector ends, and both sources' + * pointers address the same rows. */ +typedef struct { const int32_t* ref0; const int32_t* ref2; int bad; int pieces; } sr_two_t; +static void sr_two(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sr_two_t* t = ctx; + t->pieces++; + for (int64_t r = b; r < e; r++) { + if (((const int32_t*)p[0].data)[r - b] != t->ref0[r]) t->bad++; + if (((const int32_t*)p[1].data)[r - b] != t->ref2[r]) t->bad++; + } +} +static test_result_t test_walk_unaligned_mixed(void) { + ray_t* a = sr_i32(20000, 0); + ray_t* bv = sr_i32(20000, 7); + ray_t* c = sr_gen2(bv, "u"); + ray_col_src_t s0, s2; + TEST_ASSERT_NULL(ray_col_src_bind(a, &s0)); + TEST_ASSERT_NULL(ray_col_src_bind(c, &s2)); + ray_col_src_t* srcs[2] = { &s0, &s2 }; + const void* plain[2] = { ray_data(a), NULL }; + for (int64_t lo = 0; lo < 20000; lo += 1777) { + int64_t hi = lo + 5000 < 20000 ? lo + 5000 : 20000; + sr_two_t t = { (const int32_t*)ray_data(a), (const int32_t*)ray_data(bv), 0, 0 }; + TEST_ASSERT_NULL(ray_col_walk(srcs, plain, 2, lo, hi, false, &t, 0, sr_two)); + TEST_ASSERT_FMT(t.bad == 0, "lo=%lld", (long long)lo); + int64_t want = (hi - 1) / 1024 - lo / 1024 + 1; /* vectors touched */ + TEST_ASSERT_EQ_I(t.pieces, want); + } + ray_col_src_release(&s0); ray_col_src_release(&s2); + ray_release(c); ray_release(a); ray_release(bv); + PASS(); +} + +static test_result_t test_walk_str_pool_from_view(void) { + ray_t* v = ray_vec_new(RAY_STR, 5000); + char buf[64]; + for (int i = 0; i < 5000; i++) { + int n = (i % 3 == 0) ? snprintf(buf, sizeof buf, "s%d", i) + : snprintf(buf, sizeof buf, "a pooled string of row %d", i); + v = ray_str_vec_append(v, buf, (size_t)n); + } + ray_t* c = sr_gen2(v, "s"); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_cursor_t cur; ray_col_cursor_init(&cur, &s); + const ray_str_t* x = (const ray_str_t*)ray_data(v); + const char* px = v->str_pool ? (const char*)ray_data(v->str_pool) : NULL; + for (int64_t r = 900; r < 4900; r++) { + const ray_col_range_t* rv; + TEST_ASSERT_NULL(ray_col_cursor_at(&cur, r, &rv)); + const ray_str_t* y = (const ray_str_t*)rv->data + (r - rv->start); + TEST_ASSERT_EQ_I(y->len, x[r].len); + TEST_ASSERT_TRUE(memcmp(ray_str_t_ptr(y, rv->str_pool), ray_str_t_ptr(&x[r], px), y->len) == 0); + } + ray_col_cursor_free(&cur); ray_col_src_release(&s); + /* A plain STR source read in place carries its column's pool. */ + ray_col_src_t sp; TEST_ASSERT_NULL(ray_col_src_bind(v, &sp)); + ray_col_src_t* srcs[1] = { &sp }; + const void* plain[1] = { ray_data(v) }; + static char out[5000 * sizeof(ray_str_t)]; + sr_walk_t w = { out, 100, (uint8_t)sizeof(ray_str_t), 0, 0, 0, NULL, NULL }; + TEST_ASSERT_NULL(ray_col_walk(srcs, plain, 1, 100, 4100, false, &w, 0, sr_piece)); + TEST_ASSERT_EQ_I(w.pieces, 1); + TEST_ASSERT_EQ_PTR(w.pool, px); + ray_col_src_release(&sp); ray_release(c); ray_release(v); + PASS(); +} + +/* Review focus 2: a parted SYM source whose segments have different saved + * width classes (W8 and W16): each piece carries its own segment's attrs, + * and the values equal the materialized wrapper's. */ +typedef struct { ray_t* plain; int bad; uint8_t widths[2]; } sr_sym_t; +static void sr_sym(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sr_sym_t* t = ctx; + ray_t** segs = (ray_t**)ray_data(t->plain); /* not-a-table: a parted wrapper */ + for (int64_t r = b; r < e; r++) { + ray_t* seg = r < 1500 ? segs[0] : segs[1]; + int64_t want = ray_read_sym(ray_data(seg), r < 1500 ? r : r - 1500, RAY_SYM, seg->attrs); + if (ray_read_sym(p[0].data, r - b, RAY_SYM, p[0].attrs) != want) t->bad++; + } + t->widths[b < 1500 ? 0 : 1] = p[0].attrs & RAY_SYM_W_MASK; +} +static test_result_t test_walk_sym_widths(void) { + char dir[512], sym[512]; + snprintf(sym, sizeof sym, "%s/pw/.sym", sr_root()); + for (int p = 0; p < 2; p++) { + int64_t n = 1500, distinct = p ? 300 : 20; /* W8 (< 256 ids) then W16 */ + ray_t* s = ray_sym_vec_new(RAY_SYM_W64, n); s->len = n; + for (int64_t i = 0; i < n; i++) { + char b2[16]; int nb = snprintf(b2, sizeof b2, "w%lld", (long long)(i % distinct)); + ((int64_t*)ray_data(s))[i] = ray_sym_intern(b2, (size_t)nb); + } + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); ray_release(s); + snprintf(dir, sizeof dir, "%s/pw/2024.01.0%d/t", sr_root(), p + 1); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, dir, sym, RAY_COMPRESS_ON), RAY_OK); + ray_release(t); + } + snprintf(dir, sizeof dir, "%s/pw", sr_root()); + ray_t* t = ray_read_parted(dir, "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("s", 1), &s)); + ray_col_src_t* srcs[1] = { &s }; + const void* pl[1] = { NULL }; + ray_t* plain = ray_table_col(t, ray_sym_intern("s", 1)); /* reference: the materialized wrapper */ + TEST_ASSERT_TRUE(plain && !RAY_IS_ERR(plain)); + sr_sym_t st = { plain, 0, { 0, 0 } }; + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, 1, 1000, 2500, false, &st, 0, sr_sym)); /* crosses the segment boundary */ + TEST_ASSERT_EQ_I(st.bad, 0); + TEST_ASSERT_TRUE(st.widths[0] != st.widths[1]); + ray_col_src_release(&s); ray_release(t); + PASS(); +} + +/* Finding I5: a ragged generation-0 parted table (partition 3 lacks v) + * reads its synthetic all-null segment through the walk, never + * materialized, with the eager fill's values (NULL_I32 rows). */ +static test_result_t test_walk_ragged_parted(void) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/rg/2024.01.0%d/t/\" %s {compress: false})", p + 1, + p == 2 ? "(table [a] (list (til 3000)))" + : "(table [a v] (list (til 3000) (as 'I32 (map (fn [j] (if (== 0 (% j 9)) 0N j)) (til 3000)))))"); + char root[512]; snprintf(root, sizeof root, "%s/rg", sr_root()); + ray_t* t = ray_read_parted(root, "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("v", 1), &s)); + TEST_ASSERT_TRUE(ray_col_src_encoded(&s) && s.parted); /* RAY_ENCCOL_PARTED: synthetic segment */ + TEST_ASSERT_NULL(ray_col_src_ready(&s)); + static char out[9000 * 4]; + ray_col_src_t* srcs[1] = { &s }; + const void* pl[1] = { NULL }; + sr_walk_t w = { out, 0, 4, 0, 0, 0, NULL, NULL }; + ray_enc_counters_reset(); + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, 1, 0, 9000, false, &w, 0, sr_piece)); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t* ref = ray_table_col(t, ray_sym_intern("v", 1)); /* the eager reference (materializes now) */ + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + ray_t** segs = (ray_t**)ray_data(ref); /* not-a-table: a parted wrapper */ + for (int64_t r = 0; r < 9000; r++) { + int32_t want = ((const int32_t*)ray_data(segs[r / 3000]))[r % 3000]; + TEST_ASSERT_FMT(((const int32_t*)out)[r] == want, "row %lld", (long long)r); + } + for (int64_t r = 6000; r < 9000; r++) TEST_ASSERT_EQ_I(((const int32_t*)out)[r], NULL_I32); + ray_col_src_release(&s); ray_release(t); + PASS(); +} + +/* Sparse ascending rows: each touched vector is decoded once. The last + * vector of a 10000-row column holds 784 rows. */ +static test_result_t test_cursor_reuses_vector(void) { + ray_t* v = sr_i32(10000, 0); + ray_t* c = sr_gen2(v, "c"); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_cursor_t cur; ray_col_cursor_init(&cur, &s); + ray_enc_counters_reset(); + static const int64_t rows[] = { 0, 17, 1023, 1024, 1500, 7168, 7169, 9216, 9999 }; + for (size_t i = 0; i < sizeof rows / sizeof rows[0]; i++) { + const ray_col_range_t* rv; + TEST_ASSERT_NULL(ray_col_cursor_at(&cur, rows[i], &rv)); + TEST_ASSERT_EQ_I(((const int32_t*)rv->data)[rows[i] - rv->start], ((int32_t*)ray_data(v))[rows[i]]); + } + ray_col_cursor_free(&cur); /* counted when the scratch goes */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, (3 * 1024 + 784) * 4); /* vectors 0, 1, 7 and 9 (784 rows) */ + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +/* Contiguous mode: one piece, floats copied, nulls (NaN) preserved. */ +static test_result_t test_walk_contiguous_floats(void) { + ray_t* v = sr_f64(20000, 13); + ray_t* c = sr_gen2(v, "f"); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_src_t* srcs[1] = { &s }; + const void* plain[1] = { NULL }; + static char out[20000 * 8]; + sr_walk_t w = { out, 1000, 8, 0, 0, 0, NULL, NULL }; + TEST_ASSERT_NULL(ray_col_walk(srcs, plain, 1, 1000, 9192, true, &w, 0, sr_piece)); + TEST_ASSERT_EQ_I(w.pieces, 1); + TEST_ASSERT_TRUE(memcmp(out, (double*)ray_data(v) + 1000, 8192 * 8) == 0); /* bit-identical, NaN payloads too */ + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +static test_result_t test_scan_fail_lowest_key(void) { + ray_scan_fail_t f; ray_scan_fail_init(&f); + TEST_ASSERT_FALSE(ray_scan_failed(&f)); + TEST_ASSERT_NULL(ray_scan_fail_error(&f)); + ray_scan_fail_note(&f, 16384, ray_error("corrupt", "col /x: chunk 2 late")); + ray_scan_fail_note(&f, 8192, ray_error("corrupt", "col /x: chunk 1 early")); + ray_scan_fail_note(&f, 24576, ray_error("oom", "later")); + TEST_ASSERT_TRUE(ray_scan_failed(&f)); + ray_error_clear(); + ray_t* e = ray_scan_fail_error(&f); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_STR_EQ(ray_err_code(e), "corrupt"); + TEST_ASSERT_TRUE(strstr(ray_error_msg(), "chunk 1 early") != NULL); + ray_error_free(e); + PASS(); +} + +static test_result_t test_raw_is_null(void) { + int32_t i32[3] = { 1, NULL_I32, 0 }; + double f64[2] = { 0.0, NULL_F64 }; + uint16_t sym[2] = { 0, 7 }; + TEST_ASSERT_FALSE(ray_raw_is_null(RAY_I32, 0, i32, 0)); + TEST_ASSERT_TRUE(ray_raw_is_null(RAY_I32, 0, i32, 1)); + TEST_ASSERT_TRUE(ray_raw_is_null(RAY_F64, 0, f64, 1)); + TEST_ASSERT_TRUE(ray_raw_is_null(RAY_SYM, RAY_SYM_W16, sym, 0)); + TEST_ASSERT_FALSE(ray_raw_is_null(RAY_SYM, RAY_SYM_W16, sym, 1)); + uint8_t u8[1] = { 0 }; + TEST_ASSERT_FALSE(ray_raw_is_null(RAY_U8, 0, u8, 0)); + PASS(); +} + +/* ---- Fix round 1: envelope determinism, cancel, parted lookup, gaps ---- */ + +/* Two threads note keys concurrently: the lowest always wins, whichever + * thread holds it. */ +typedef struct { ray_scan_fail_t* f; int64_t base; _Atomic(int)* go; } sr_noter_t; +static void sr_noter(void* raw) { + sr_noter_t* t = raw; + while (!atomic_load(t->go)) RAY_CPU_RELAX(); + for (int64_t k = 40; k >= 0; k--) { + int64_t key = (t->base + 2 * k) * 8192; + ray_scan_fail_note(t->f, key, ray_error("corrupt", "key %lld", (long long)key)); + } + ray_heap_abandon(); +} +static test_result_t test_scan_fail_concurrent(void) { + for (int it = 0; it < 200; it++) { + ray_scan_fail_t f; ray_scan_fail_init(&f); + _Atomic(int) go = 0; + sr_noter_t a = { &f, it & 1, &go }, b = { &f, !(it & 1), &go }; /* key 0 alternates threads */ + ray_thread_t ta, tb; + TEST_ASSERT_EQ_I(ray_thread_create(&ta, sr_noter, &a), RAY_OK); + TEST_ASSERT_EQ_I(ray_thread_create(&tb, sr_noter, &b), RAY_OK); + atomic_store(&go, 1); + ray_thread_join(ta); ray_thread_join(tb); + ray_error_clear(); + ray_t* e = ray_scan_fail_error(&f); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_FMT(strcmp(ray_error_msg(), "key 0") == 0, "it=%d msg=%s", it, ray_error_msg()); + ray_error_free(e); + } + PASS(); +} + +/* The early-return rule: a task skips only when a lower key failed, so a + * skipped task never hides a lower failure. */ +static test_result_t test_scan_fail_skip(void) { + ray_scan_fail_t f; ray_scan_fail_init(&f); + TEST_ASSERT_FALSE(ray_scan_fail_skip(&f, 0)); + ray_scan_fail_note(&f, 8192, ray_error("corrupt", "mid")); + TEST_ASSERT_TRUE(ray_scan_fail_skip(&f, 16384)); + TEST_ASSERT_FALSE(ray_scan_fail_skip(&f, 8192)); + TEST_ASSERT_FALSE(ray_scan_fail_skip(&f, 0)); /* below the lowest: still runs */ + ray_scan_fail_note(&f, 0, ray_error("oom", "low")); + ray_error_clear(); + ray_t* e = ray_scan_fail_error(&f); + TEST_ASSERT_STR_EQ(ray_err_code(e), "oom"); + ray_error_free(e); + PASS(); +} + +/* Cancel through the pool: the tasks the pool skips note nothing, and the + * finish reports `cancel`; a noted failure stands; no cancel, no error. */ +typedef struct { ray_scan_fail_t f; _Atomic(int64_t) ran; int64_t fail_at; } sr_disp_t; +static void sr_disp_task(void* ctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)wid; (void)hi; + sr_disp_t* d = ctx; + if (ray_scan_fail_skip(&d->f, lo)) return; + atomic_fetch_add(&d->ran, 1); + if (lo == d->fail_at) ray_scan_fail_note(&d->f, lo, ray_error("corrupt", "task %lld", (long long)lo)); +} +static test_result_t test_scan_fail_cancel(void) { + ray_pool_t* pool = ray_pool_get(); + TEST_ASSERT_NOT_NULL(pool); + sr_disp_t d; ray_scan_fail_init(&d.f); atomic_store(&d.ran, 0); d.fail_at = -1; + ray_pool_dispatch_n(pool, sr_disp_task, &d, 64); + TEST_ASSERT_EQ_I(atomic_load(&d.ran), 64); + TEST_ASSERT_NULL(ray_scan_fail_finish(&d.f, pool)); + ray_cancel(); /* the pool skips every task */ + ray_scan_fail_init(&d.f); atomic_store(&d.ran, 0); + ray_pool_dispatch_n(pool, sr_disp_task, &d, 64); + ray_t* e = ray_scan_fail_finish(&d.f, pool); + ray_cancel_reset(); + TEST_ASSERT_EQ_I(atomic_load(&d.ran), 0); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_STR_EQ(ray_err_code(e), "cancel"); + ray_error_free(e); + ray_request_interrupt(); /* the interrupt alone also cancels */ + ray_scan_fail_init(&d.f); + e = ray_scan_fail_finish(&d.f, NULL); + ray_scan_fail_note(&d.f, 3, ray_error("corrupt", "noted")); /* a noted failure stands */ + ray_t* e2 = ray_scan_fail_finish(&d.f, pool); + ray_clear_interrupt(); /* before any assert: none leaks */ + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_STR_EQ(ray_err_code(e), "cancel"); + ray_error_free(e); + TEST_ASSERT_TRUE(e2 && RAY_IS_ERR(e2)); + TEST_ASSERT_STR_EQ(ray_err_code(e2), "corrupt"); + ray_error_free(e2); + PASS(); +} + +/* A hand-built plain parted wrapper of nseg I64 segments of seglen rows + * (value = global row). */ +static ray_t* sr_parted_i64(int64_t nseg, int64_t seglen) { + ray_t* w = ray_alloc((size_t)nseg * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + RAY_I64; w->len = nseg; + for (int64_t i = 0; i < nseg; i++) { + ray_t* v = ray_vec_new(RAY_I64, seglen); v->len = seglen; + for (int64_t j = 0; j < seglen; j++) ((int64_t*)ray_data(v))[j] = i * seglen + j; + ((ray_t**)ray_data(w))[i] = v; + } + return w; +} +typedef struct { int64_t pieces, bad; } sr_seq_t; +static void sr_seq(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sr_seq_t* t = ctx; + t->pieces++; + for (int64_t r = b; r < e; r++) if (((const int64_t*)p[0].data)[r - b] != r) t->bad++; +} +static double sr_now(void) { struct timespec ts; timespec_get(&ts, TIME_UTC); return (double)ts.tv_sec + ts.tv_nsec * 1e-9; } +/* Best of 3 full walks; checks values and the piece count. */ +static double sr_walk_parted(ray_t* obj, int64_t nseg, int* ok) { + ray_col_src_t s; *ok = 0; + if (ray_col_src_bind(obj, &s)) return 0; + ray_col_src_t* srcs[1] = { &s }; + const void* pl[1] = { ray_col_src_base(&s) }; /* parted: NULL */ + double best = 1e9; int good = pl[0] == NULL; + for (int k = 0; k < 3; k++) { + sr_seq_t t = { 0, 0 }; + double t0 = sr_now(); + ray_t* e = ray_col_walk(srcs, pl, 1, 0, s.len, false, &t, 0, sr_seq); + double dt = sr_now() - t0; + if (e) { ray_error_free(e); good = 0; } + if (t.bad || t.pieces != nseg) good = 0; + if (dt < best) best = dt; + } + ray_col_src_release(&s); + *ok = good; + return best; +} +/* 10,000 small segments: a full walk is linear in rows (segment found by + * binary search over prefix offsets, not by a scan from the first). */ +static test_result_t test_walk_parted_10k(void) { + int ok; + ray_t* w1 = sr_parted_i64(1000, 10); + ray_t* w10 = sr_parted_i64(10000, 10); + double t1 = sr_walk_parted(w1, 1000, &ok); TEST_ASSERT_TRUE(ok); + double t10 = sr_walk_parted(w10, 10000, &ok); TEST_ASSERT_TRUE(ok); + TEST_ASSERT_FMT(t10 < 40 * t1 + 0.005, "1k %.3f ms, 10k %.3f ms", t1 * 1e3, t10 * 1e3); /* linear ~10x; quadratic ~100x */ + ray_t* ep = ray_enccol_parted_new(w10); /* the RAY_ENCCOL_PARTED form */ + TEST_ASSERT_TRUE(ep && !RAY_IS_ERR(ep)); + double te = sr_walk_parted(ep, 10000, &ok); TEST_ASSERT_TRUE(ok); + TEST_ASSERT_FMT(te < 40 * t1 + 0.005, "1k %.3f ms, enc 10k %.3f ms", t1 * 1e3, te * 1e3); + /* Cursor jumps (backwards too) find the right segment. */ + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(ep, &s)); + ray_col_cursor_t c; ray_col_cursor_init(&c, &s); + static const int64_t rows[] = { 99999, 0, 50005, 9, 10, 77777 }; + for (size_t i = 0; i < sizeof rows / sizeof rows[0]; i++) { + const ray_col_range_t* v; + TEST_ASSERT_NULL(ray_col_cursor_at(&c, rows[i], &v)); + TEST_ASSERT_EQ_I(((const int64_t*)v->data)[rows[i] - v->start], rows[i]); + TEST_ASSERT_EQ_I(v->start + v->n, (rows[i] / 10 + 1) * 10); /* clipped at the segment */ + } + ray_col_cursor_free(&c); ray_col_src_release(&s); + ray_release(ep); ray_release(w10); ray_release(w1); + PASS(); +} + +/* A NULL source is skipped (zero piece); more sources than the stack + * holds take the heap arrays. */ +typedef struct { int64_t pieces; int bad; uint32_t n; const int32_t* ref; } sr_many_t; +static void sr_many(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; + sr_many_t* t = ctx; + t->pieces++; + if (p[0].data != NULL) t->bad++; + for (uint32_t i = 1; i < t->n; i++) + for (int64_t r = b; r < e; r++) + if (((const int32_t*)p[i].data)[r - b] != t->ref[r]) t->bad++; +} +static test_result_t test_walk_null_and_many_sources(void) { + ray_t* v = sr_i32(5000, 4); + ray_t* c = sr_gen2(v, "m"); + ray_col_src_t sp, se; + TEST_ASSERT_NULL(ray_col_src_bind(v, &sp)); + TEST_ASSERT_NULL(ray_col_src_bind(c, &se)); + enum { NS = 20 }; /* > the walk's stack arrays */ + ray_col_src_t* srcs[NS]; const void* pl[NS]; + srcs[0] = NULL; pl[0] = NULL; + for (int i = 1; i < NS; i++) { + srcs[i] = (i & 1) ? &se : &sp; + pl[i] = (i & 1) ? NULL : ray_col_src_base(&sp); + } + sr_many_t t = { 0, 0, NS, (const int32_t*)ray_data(v) }; + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, NS, 100, 4100, false, &t, 0, sr_many)); + TEST_ASSERT_EQ_I(t.bad, 0); + TEST_ASSERT_EQ_I(t.pieces, 4100 / 1024 - 100 / 1024 + 1); + ray_col_src_release(&sp); ray_col_src_release(&se); ray_release(c); ray_release(v); + PASS(); +} + +/* Errors: a non-float cursor source in contiguous mode is nyi; a cursor + * outside the source is a range error. */ +static test_result_t test_walk_contig_nyi_and_cursor_range(void) { + ray_t* v = sr_i32(5000, 0); + ray_t* c = sr_gen2(v, "n"); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_src_t* srcs[1] = { &s }; + const void* pl[1] = { NULL }; + static char out[5000 * 4]; + sr_walk_t w = { out, 0, 4, 0, 0, 0, NULL, NULL }; + ray_t* e = ray_col_walk(srcs, pl, 1, 0, 4000, true, &w, 0, sr_piece); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_STR_EQ(ray_err_code(e), "nyi"); + ray_error_free(e); + TEST_ASSERT_EQ_I(w.pieces, 0); + e = ray_col_walk(srcs, pl, 1, 0, RAY_COL_BLOCK_ROWS + 1, true, &w, 0, sr_piece); + TEST_ASSERT_STR_EQ(ray_err_code(e), "range"); /* contiguous block bound */ + ray_error_free(e); + ray_col_cursor_t cur; ray_col_cursor_init(&cur, &s); + const ray_col_range_t* rv = (const ray_col_range_t*)1; + e = ray_col_cursor_at(&cur, 5000, &rv); + TEST_ASSERT_STR_EQ(ray_err_code(e), "range"); + TEST_ASSERT_NULL(rv); + ray_error_free(e); + e = ray_col_cursor_at(&cur, -1, &rv); + TEST_ASSERT_STR_EQ(ray_err_code(e), "range"); + ray_error_free(e); + ray_col_cursor_free(&cur); ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +/* A plain slice reads in place, at the slice's rows. */ +static test_result_t test_walk_plain_slice(void) { + ray_t* v = sr_i32(5000, 3); + ray_t* sl = ray_vec_slice(v, 700, 3000); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(sl, &s)); + TEST_ASSERT_EQ_PTR(ray_col_src_base(&s), (int32_t*)ray_data(v) + 700); + ray_col_src_t* srcs[2] = { &s, &s }; + const void* pl[2] = { ray_col_src_base(&s), NULL }; /* in place and by cursor */ + sr_two_t t = { (const int32_t*)ray_data(v) + 700, (const int32_t*)ray_data(v) + 700, 0, 0 }; + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, 2, 10, 2990, false, &t, 0, sr_two)); + TEST_ASSERT_EQ_I(t.bad, 0); + TEST_ASSERT_EQ_I(t.pieces, 1); /* the cursor view runs to the slice end */ + ray_col_src_release(&s); ray_release(sl); ray_release(v); + PASS(); +} + +/* A materialized RAY_ENCCOL_PARTED (ragged table) walks the published + * wrapper: nothing is decoded, values as the eager fill. */ +static test_result_t test_walk_materialized_parted(void) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/mp/2024.01.0%d/t/\" %s {compress: false})", p + 1, + p == 1 ? "(table [a] (list (til 3000)))" + : "(table [a v] (list (til 3000) (as 'I32 (map (fn [j] (if (== 0 (% j 7)) 0N j)) (til 3000)))))"); + char root[512]; snprintf(root, sizeof root, "%s/mp", sr_root()); + ray_t* t = ray_read_parted(root, "t"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t, ray_sym_intern("v", 1), &s)); + TEST_ASSERT_TRUE(ray_col_src_encoded(&s) && s.parted); + ray_t* ref = ray_table_col(t, ray_sym_intern("v", 1)); /* materializes the wrapper */ + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + TEST_ASSERT_EQ_PTR(ray_col_src_ready(&s), ref); + TEST_ASSERT_NULL(ray_col_src_base(&s)); /* parted: no single base */ + ray_enc_counters_reset(); + static char out[9000 * 4]; + ray_col_src_t* srcs[1] = { &s }; + const void* pl[1] = { NULL }; + sr_walk_t w = { out, 0, 4, 0, 0, 0, NULL, NULL }; + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, 1, 0, 9000, false, &w, 0, sr_piece)); + TEST_ASSERT_EQ_I(w.pieces, 3); /* one per segment */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t** segs = (ray_t**)ray_data(ref); + for (int64_t r = 0; r < 9000; r++) + TEST_ASSERT_EQ_I(((const int32_t*)out)[r], ((const int32_t*)ray_data(segs[r / 3000]))[r % 3000]); + ray_col_src_release(&s); ray_release(t); + PASS(); +} + +/* Contiguous mode over a plain parted F64 source (segment 0 null-free, + * segment 1 with nulls): a block inside one segment is that segment's view + * (no copy, its own may_null); a block across both is copied and its + * may_null is the OR of the views. */ +typedef struct { const void* data; bool may_null; int pieces; double first; } sr_contig_t; +static void sr_contig(void* ctx, uint32_t wid, int64_t b, int64_t e, const ray_col_piece_t* p) { + (void)wid; (void)b; (void)e; + sr_contig_t* t = ctx; + t->pieces++; t->data = p[0].data; t->may_null = p[0].may_null; t->first = ((const double*)p[0].data)[0]; +} +static test_result_t test_walk_contig_views(void) { + ray_t* s0 = sr_f64(3000, 0); + ray_t* s1 = sr_f64(3000, 5); + ray_t* w = ray_alloc(2 * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + RAY_F64; w->len = 2; + ((ray_t**)ray_data(w))[0] = s0; ((ray_t**)ray_data(w))[1] = s1; + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(w, &s)); + TEST_ASSERT_TRUE(s.may_null); + ray_col_src_t* srcs[1] = { &s }; + const void* pl[1] = { NULL }; + sr_contig_t t = { 0 }; + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, 1, 500, 2500, true, &t, 0, sr_contig)); + TEST_ASSERT_EQ_I(t.pieces, 1); + TEST_ASSERT_EQ_PTR(t.data, (double*)ray_data(s0) + 500); /* one view covers it: no copy */ + TEST_ASSERT_FALSE(t.may_null); + t = (sr_contig_t){ 0 }; + TEST_ASSERT_NULL(ray_col_walk(srcs, pl, 1, 2500, 3500, true, &t, 0, sr_contig)); + TEST_ASSERT_EQ_I(t.pieces, 1); + TEST_ASSERT_TRUE(t.data != (double*)ray_data(s0) + 2500); /* copied */ + TEST_ASSERT_TRUE(t.first == ((double*)ray_data(s0))[2500]); + TEST_ASSERT_TRUE(t.may_null); /* OR of the two views */ + ray_col_src_release(&s); ray_release(w); + PASS(); +} + +/* ---- Task 2: directory statistics and the read-ahead byte range ---- */ + +static test_result_t test_chunk_stat_matches_data(void) { + int64_t n = 3 * 65536 + 100; + ray_t* v = sr_i32(n, 11); + ray_t* c = sr_gen2(v, "st"); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + for (int64_t ch = 0; ch < 4; ch++) { + ray_enc_chunk_stat_t st; + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&s, ch, &st)); + int64_t lo = ch * 65536, hi = lo + 65536 < n ? lo + 65536 : n; + int64_t mn = INT64_MAX, mx = INT64_MIN, sum = 0; uint32_t nn = 0; + for (int64_t i = lo; i < hi; i++) { + int32_t x = ((int32_t*)ray_data(v))[i]; + if (x == NULL_I32) { nn++; continue; } + if (x < mn) mn = x; + if (x > mx) mx = x; + sum += x; + } + TEST_ASSERT_EQ_I(st.rows, hi - lo); + TEST_ASSERT_TRUE(st.has_minmax); + TEST_ASSERT_EQ_I(st.min, mn); TEST_ASSERT_EQ_I(st.max, mx); + TEST_ASSERT_EQ_U(st.null_count, nn); + TEST_ASSERT_EQ_U(st.sum_lo, (uint64_t)sum); /* the exact sum, sign-extended */ + TEST_ASSERT_EQ_I(st.sum_hi, sum < 0 ? -1 : 0); + } + ray_enc_chunk_stat_t st; + TEST_ASSERT_FALSE(ray_col_src_chunk_stat(&s, 4, &st)); /* past the last chunk */ + TEST_ASSERT_FALSE(ray_col_src_chunk_stat(&s, -1, &st)); + ray_col_src_t p; TEST_ASSERT_NULL(ray_col_src_bind(v, &p)); /* plain: no statistics */ + TEST_ASSERT_FALSE(ray_col_src_chunk_stat(&p, 0, &st)); + ray_col_src_release(&p); ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +static test_result_t test_byte_range_from_directory(void) { + int64_t n = 4 * 65536; + ray_t* v = sr_i32(n, 0); + ray_t* c = sr_gen2(v, "br"); + ray_enccol_t* e = ray_enccol_of(c); + ray_enc_dirent_t d1, d2; /* directory entries 1 and 2 */ + memcpy(&d1, e->base + RAY_ENC_DIR_OFF + 1 * sizeof(ray_enc_dirent_t), sizeof d1); + memcpy(&d2, e->base + RAY_ENC_DIR_OFF + 2 * sizeof(ray_enc_dirent_t), sizeof d2); + uint64_t off, len; + ray_enccol_byte_range(e, 65536 + 5, 2 * 65536 + 10, &off, &len); /* chunks 1 and 2 */ + TEST_ASSERT_EQ_U(off, d1.offset); + TEST_ASSERT_EQ_U(off + len, d2.offset + d2.bytes); + ray_enccol_byte_range(e, 65536, 2 * 65536, &off, &len); /* exactly chunk 1 */ + TEST_ASSERT_EQ_U(off, d1.offset); + TEST_ASSERT_EQ_U(len, d1.bytes); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_col_src_advise(&s, 0, n); /* a hint only: must not fault or fail */ + ray_col_src_advise(&s, 7, 8); + ray_col_src_advise(&s, 5, 5); /* empty: nothing */ + ray_col_src_release(&s); + /* Plain mmapped, its slice, a heap vector: hints only, never a fault. */ + char p0[512]; snprintf(p0, sizeof p0, "%s/br0", sr_root()); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p0, 0), RAY_OK); + ray_t* m = ray_col_mmap(p0); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + ray_t* sl = ray_vec_slice(m, 1000, 70000); + TEST_ASSERT_TRUE(sl && !RAY_IS_ERR(sl)); + ray_col_src_t sm, ss, sh; + TEST_ASSERT_NULL(ray_col_src_bind(m, &sm)); + TEST_ASSERT_NULL(ray_col_src_bind(sl, &ss)); + TEST_ASSERT_NULL(ray_col_src_bind(v, &sh)); + ray_col_src_advise(&sm, 3, n); + ray_col_src_advise(&ss, 0, 70000); + ray_col_src_advise(&sh, 0, n); + ray_col_src_release(&sm); ray_col_src_release(&ss); ray_col_src_release(&sh); + ray_release(sl); ray_release(m); + /* A parted wrapper: each touched segment, across segment boundaries. */ + ray_t* w = sr_parted_i64(4, 1000); + ray_col_src_t sp; TEST_ASSERT_NULL(ray_col_src_bind(w, &sp)); + ray_col_src_advise(&sp, 500, 2500); + ray_col_src_advise(&sp, 0, 4000); + ray_col_src_release(&sp); ray_release(w); + ray_release(c); ray_release(v); + PASS(); +} + +/* ---- Task 2 fix round 1: statistics on nulls, wide sums, floats; exact + * byte ranges; the advise spans themselves ---- */ + +/* 128-bit accumulate of a sign-extended int64 (manual carry). */ +static void sr_add128(uint64_t* lo, int64_t* hi, int64_t x) { + uint64_t n = *lo + (uint64_t)x; + *hi += (x < 0 ? -1 : 0) + (n < *lo ? 1 : 0); + *lo = n; +} + +/* Chunk 1 of an I32 column is entirely null: no min/max, every row null. */ +static test_result_t test_chunk_stat_all_null(void) { + int64_t n = 2 * 65536 + 10; + ray_t* v = sr_i32(n, 0); + for (int64_t i = 65536; i < 2 * 65536; i++) ((int32_t*)ray_data(v))[i] = NULL_I32; + v->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* c = sr_gen2(v, "an"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + ray_enc_chunk_stat_t st; + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&s, 1, &st)); + TEST_ASSERT_EQ_I(st.rows, 65536); + TEST_ASSERT_FALSE(st.has_minmax); + TEST_ASSERT_EQ_U(st.null_count, 65536); + TEST_ASSERT_EQ_I(st.min, 0); TEST_ASSERT_EQ_I(st.max, 0); + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&s, 0, &st)); /* its neighbours keep theirs */ + TEST_ASSERT_TRUE(st.has_minmax); + TEST_ASSERT_EQ_U(st.null_count, 0); + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&s, 2, &st)); + TEST_ASSERT_TRUE(st.has_minmax); + TEST_ASSERT_EQ_I(st.rows, 10); + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +/* I64 sums wider than 64 bits: chunk 0 near INT64_MAX (sum_hi > 0), chunk + * 1 near -INT64_MAX (sum_hi far below -1), chunk 2 small negatives + * (sum_hi == -1), chunk 3 a partial mix with nulls; against a 128-bit + * reference. */ +static test_result_t test_chunk_stat_wide_sums(void) { + int64_t n = 3 * 65536 + 300; + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + int64_t* d = (int64_t*)ray_data(v); + for (int64_t i = 0; i < n; i++) { + int64_t ch = i / 65536, j = i % 65536; + d[i] = ch == 0 ? INT64_MAX - j : ch == 1 ? -INT64_MAX + j : ch == 2 ? -1 - j + : (j % 3 == 0 ? NULL_I64 : INT64_MAX - 7 * j); + } + v->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* c = sr_gen2(v, "ws"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + int64_t want_hi_sign[4] = { 1, -2, -1, 1 }; /* > 0, < -1, == -1, > 0 */ + for (int64_t ch = 0; ch < 4; ch++) { + int64_t lo = ch * 65536, hi = lo + 65536 < n ? lo + 65536 : n; + uint64_t slo = 0; int64_t shi = 0; uint32_t nn = 0; + int64_t mn = INT64_MAX, mx = INT64_MIN; + for (int64_t i = lo; i < hi; i++) { + if (d[i] == NULL_I64) { nn++; continue; } + sr_add128(&slo, &shi, d[i]); + if (d[i] < mn) mn = d[i]; + if (d[i] > mx) mx = d[i]; + } + ray_enc_chunk_stat_t st; + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&s, ch, &st)); + TEST_ASSERT_EQ_I(st.rows, hi - lo); + TEST_ASSERT_TRUE(st.has_minmax); + TEST_ASSERT_EQ_I(st.min, mn); TEST_ASSERT_EQ_I(st.max, mx); + TEST_ASSERT_EQ_U(st.null_count, nn); + TEST_ASSERT_EQ_U(st.sum_lo, slo); + TEST_ASSERT_EQ_I(st.sum_hi, shi); + if (want_hi_sign[ch] == 1) TEST_ASSERT_TRUE(st.sum_hi > 0); + if (want_hi_sign[ch] == -2) TEST_ASSERT_TRUE(st.sum_hi < -1); + if (want_hi_sign[ch] == -1) TEST_ASSERT_EQ_I(st.sum_hi, -1); + } + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +/* F64: min and max carry the doubles' bits. */ +static test_result_t test_chunk_stat_f64(void) { + int64_t n = 2 * 65536 + 77; + ray_t* v = sr_f64(n, 9); + double* d = (double*)ray_data(v); + for (int64_t i = 65536; i < n; i++) if (i % 9) d[i] = -d[i] * 1.5; /* negatives in chunks 1, 2 */ + ray_t* c = sr_gen2(v, "fs"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + for (int64_t ch = 0; ch < 3; ch++) { + int64_t lo = ch * 65536, hi = lo + 65536 < n ? lo + 65536 : n; + double mn = 0, mx = 0; bool have = false; uint32_t nn = 0; + for (int64_t i = lo; i < hi; i++) { + if (d[i] != d[i]) { nn++; continue; } + if (!have || d[i] < mn) mn = d[i]; + if (!have || d[i] > mx) mx = d[i]; + have = true; + } + ray_enc_chunk_stat_t st; + TEST_ASSERT_TRUE(ray_col_src_chunk_stat(&s, ch, &st)); + TEST_ASSERT_EQ_I(st.rows, hi - lo); + TEST_ASSERT_TRUE(st.has_minmax); + TEST_ASSERT_EQ_U(st.null_count, nn); + double smn, smx; + memcpy(&smn, &st.min, sizeof smn); memcpy(&smx, &st.max, sizeof smx); + TEST_ASSERT_FMT(smn == mn && smx == mx, "chunk %lld: [%g, %g] want [%g, %g]", + (long long)ch, smn, smx, mn, mx); + } + ray_col_src_release(&s); ray_release(c); ray_release(v); + PASS(); +} + +static void sr_dirent(const ray_enccol_t* e, int64_t c, ray_enc_dirent_t* d) { + memcpy(d, e->base + RAY_ENC_DIR_OFF + (size_t)c * sizeof *d, sizeof *d); +} + +/* Exact byte ranges over a column with a partial last chunk. */ +static test_result_t test_byte_range_edges(void) { + int64_t n = 3 * 65536 + 100; + ray_t* v = sr_i32(n, 13); + ray_t* c = sr_gen2(v, "be"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_t* e = ray_enccol_of(c); + TEST_ASSERT_EQ_I(e->n_chunks, 4); + ray_enc_dirent_t d[4]; + for (int k = 0; k < 4; k++) sr_dirent(e, k, &d[k]); + static const struct { int64_t lo, hi; int c0, c1; } cases[] = { + { 3 * 65536 + 99, 3 * 65536 + 100, 3, 3 }, /* [n-1, n) */ + { 0, 3 * 65536 + 100, 0, 3 }, /* [0, n) */ + { 0, 10, 0, 0 }, /* starts at chunk 0 */ + { 0, 65537, 0, 1 }, /* chunk 0 into chunk 1 */ + { 3 * 65536 + 50, 3 * 65536 + 51, 3, 3 }, /* one row of the partial last chunk */ + { 65535, 65536, 0, 0 }, /* the last row of chunk 0 */ + }; + for (size_t k = 0; k < sizeof cases / sizeof cases[0]; k++) { + uint64_t off, len; + ray_enccol_byte_range(e, cases[k].lo, cases[k].hi, &off, &len); + TEST_ASSERT_EQ_U(off, d[cases[k].c0].offset); + TEST_ASSERT_EQ_U(len, d[cases[k].c1].offset + d[cases[k].c1].bytes - d[cases[k].c0].offset); + } + ray_release(c); ray_release(v); + PASS(); +} + +/* The advise spans: page-aligned start (host page size, at most a page + * before the requested bytes), inside the mapping, ending exactly where + * the requested bytes end. */ +#define SR_SPANS 8 +typedef struct { uintptr_t a[SR_SPANS]; size_t l[SR_SPANS]; } sr_spans_t; +static int sr_spans(const ray_col_src_t* s, int64_t lo, int64_t hi, sr_spans_t* o) { + return ray_col_src_test_advise_spans(s, lo, hi, o->a, o->l, SR_SPANS); +} +static bool sr_span_ok(uintptr_t a, size_t l, uintptr_t map_lo, uintptr_t map_hi, + uintptr_t want_lo, uintptr_t want_hi) { + size_t pg = ray_vm_page_size(); + return pg >= 4096 && (pg & (pg - 1)) == 0 && a % pg == 0 && a >= map_lo && a + l <= map_hi + && a <= want_lo && a + l == want_hi && want_lo - a < pg; /* ends exactly at the bytes */ +} +static test_result_t test_advise_spans(void) { + int64_t n = 3 * 65536 + 100; + ray_t* v = sr_i32(n, 0); + /* Generation 2: a partial range inside chunks 1-2, the partial last chunk. */ + ray_t* c = sr_gen2(v, "as"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c)); + ray_enccol_t* e = ray_enccol_of(c); + ray_enc_dirent_t d1, d2, d3; + sr_dirent(e, 1, &d1); sr_dirent(e, 2, &d2); sr_dirent(e, 3, &d3); + uintptr_t b = (uintptr_t)e->base, bend = b + e->size; + ray_col_src_t s; TEST_ASSERT_NULL(ray_col_src_bind(c, &s)); + sr_spans_t sp; + TEST_ASSERT_EQ_I(sr_spans(&s, 65536 + 5, 2 * 65536 + 10, &sp), 1); + TEST_ASSERT_TRUE(sr_span_ok(sp.a[0], sp.l[0], b, bend, b + d1.offset, b + d2.offset + d2.bytes)); + TEST_ASSERT_EQ_I(sr_spans(&s, n - 1, n, &sp), 1); + TEST_ASSERT_TRUE(sr_span_ok(sp.a[0], sp.l[0], b, bend, b + d3.offset, b + d3.offset + d3.bytes)); + TEST_ASSERT_EQ_I(sr_spans(&s, n - 1, n + 1000, &sp), 1); /* clamped at the source end */ + TEST_ASSERT_EQ_I(sr_spans(&s, 9, 9, &sp), 0); /* empty */ + ray_col_src_release(&s); + /* Generation 0: a slice of a mapped column. */ + char p0[512]; snprintf(p0, sizeof p0, "%s/as0", sr_root()); + TEST_ASSERT_EQ_I(ray_col_save_gen(v, p0, 0), RAY_OK); + ray_t* m = ray_col_mmap(p0); + TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); + if (m->mmod == 1) { /* mapped (not an equivalence pass) */ + ray_t* sl = ray_vec_slice(m, 1000, 70000); + TEST_ASSERT_TRUE(sl && !RAY_IS_ERR(sl)); + ray_col_src_t ss; TEST_ASSERT_NULL(ray_col_src_bind(sl, &ss)); + uintptr_t mb = (uintptr_t)m, md = (uintptr_t)ray_data(m), mend = md + (uintptr_t)n * 4; + TEST_ASSERT_EQ_I(sr_spans(&ss, 5, 60000, &sp), 1); + TEST_ASSERT_TRUE(sr_span_ok(sp.a[0], sp.l[0], mb, mend, md + 1005 * 4, md + 61000 * 4)); + ray_col_src_release(&ss); ray_release(sl); + } + ray_col_src_t sh; TEST_ASSERT_NULL(ray_col_src_bind(v, &sh)); /* heap: no span */ + TEST_ASSERT_EQ_I(sr_spans(&sh, 0, n, &sp), 0); + ray_col_src_release(&sh); + /* Parted: a mapped generation-0 segment, a generation-2 segment, a heap + * segment, a second mapping of segment 0's file; [500, 2500) touches the + * tail of 0, all of 1, the head of 2. */ + ray_t* s0v = sr_i32(1000, 0); ray_t* s1v = sr_i32(1000, 0); + char q0[512], q1[512]; + snprintf(q0, sizeof q0, "%s/asp0", sr_root()); snprintf(q1, sizeof q1, "%s/asp1", sr_root()); + TEST_ASSERT_EQ_I(ray_col_save_gen(s0v, q0, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save_gen(s1v, q1, 2), RAY_OK); + ray_t* g0 = ray_col_mmap(q0); ray_t* g1 = ray_col_mmap(q1); ray_t* g3 = ray_col_mmap(q0); + TEST_ASSERT_TRUE(g0 && !RAY_IS_ERR(g0) && g1 && !RAY_IS_ERR(g1) && g1->type == RAY_ENCCOL); + TEST_ASSERT_TRUE(g3 && !RAY_IS_ERR(g3)); + ray_t* w = ray_alloc(4 * sizeof(ray_t*)); + w->type = RAY_PARTED_BASE + RAY_I32; w->len = 4; + ((ray_t**)ray_data(w))[0] = g0; ((ray_t**)ray_data(w))[1] = g1; ((ray_t**)ray_data(w))[2] = s0v; + ((ray_t**)ray_data(w))[3] = g3; + ray_retain(s0v); + ray_t* ep = ray_enccol_parted_new(w); + TEST_ASSERT_TRUE(ep && !RAY_IS_ERR(ep)); + ray_col_src_t sp3; TEST_ASSERT_NULL(ray_col_src_bind(ep, &sp3)); + ray_enccol_t* e1 = ray_enccol_of(g1); + ray_enc_dirent_t f0; sr_dirent(e1, 0, &f0); + int ns = sr_spans(&sp3, 500, 2500, &sp); + int want = g0->mmod == 1 ? 2 : 1; + TEST_ASSERT_EQ_I(ns, want); + int k = 0; + if (g0->mmod == 1) { + uintptr_t gd = (uintptr_t)ray_data(g0); + TEST_ASSERT_TRUE(sr_span_ok(sp.a[0], sp.l[0], (uintptr_t)g0, gd + 4000, gd + 2000, gd + 4000)); + k = 1; + } + uintptr_t b1 = (uintptr_t)e1->base; + TEST_ASSERT_TRUE(sr_span_ok(sp.a[k], sp.l[k], b1, b1 + e1->size, b1 + f0.offset, b1 + f0.offset + f0.bytes)); + if (g0->mmod == 1) { /* ends inside segment 0 */ + uintptr_t gd = (uintptr_t)ray_data(g0); + TEST_ASSERT_EQ_I(sr_spans(&sp3, 100, 600, &sp), 1); + TEST_ASSERT_TRUE(sr_span_ok(sp.a[0], sp.l[0], (uintptr_t)g0, gd + 4000, gd + 400, gd + 2400)); + uintptr_t g3d = (uintptr_t)ray_data(g3); /* rows local to segment 3 */ + TEST_ASSERT_EQ_I(sr_spans(&sp3, 3200, 3600, &sp), 1); + TEST_ASSERT_TRUE(sr_span_ok(sp.a[0], sp.l[0], (uintptr_t)g3, g3d + 4000, g3d + 800, g3d + 2400)); + } + ray_col_src_advise(&sp3, 0, 4000); /* the real hint: no fault */ + ray_col_src_release(&sp3); + ray_release(ep); ray_release(w); ray_release(s1v); ray_release(s0v); + ray_release(m); ray_release(c); ray_release(v); + PASS(); +} + +/* ---- runtime-level helpers shared by Tasks 3-16 ---------------------- */ +#define SR_G0 SR_TMP "/g0/" +#define SR_G2 SR_TMP "/g2/" +/* 200000 rows (four chunks, the last partial), saved as generation 0 and 2 + * from the source table S (T is rebound by every load): + * k I64 = row; g I16 = row % 7; v I32 (null every 10th) = 3*row - 7; + * f F64 (null every 13th) = row; d DATE = row % 900; s SYM five values; + * b BOOL = row % 3 == 0; u U8 = row % 200; + * h I64 = (row * 7919) % 1000003 (unclustered, no nulls: the lazy hash shape); + * e F32 (null every 17th) = row / 2. */ +/* Bind `name` to an F32 vector of n rows: row * scale, null every + * null_every-th row (0: none). Rayfall has no F32 cast. */ +static void sr_bind_f32(const char* name, int64_t n, int64_t null_every, float scale) { + ray_t* v = ray_vec_new(RAY_F32, n); v->len = n; + for (int64_t i = 0; i < n; i++) + ((float*)ray_data(v))[i] = (null_every && i % null_every == 0) ? NULL_F32 : (float)i * scale; + if (null_every) v->attrs |= RAY_ATTR_HAS_NULLS; + ray_env_set(ray_sym_intern(name, strlen(name)), v); + ray_release(v); +} +static void srr_setup(void) { + sr_rt_setup(); + sr_eval_ok("(set i (til 200000))"); + sr_bind_f32("ef", 200000, 17, 0.5); + sr_eval_ok("(set S (table [k g v f d s b u h e] (list i (as 'I16 (% i 7)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 10)) 0N (- (* 3 j) 7))) i)) " + "(as 'F64 (map (fn [j] (if (== 0 (% j 13)) 0N j)) i)) (as 'DATE (% i 900)) " + "(take ['a 'b 'c 'd 'e] 200000) (== 0 (% i 3)) (as 'U8 (% i 200)) (% (* i 7919) 1000003) " + "ef)))"); + sr_eval_ok("(.db.splayed.set \"" SR_G2 "\" S {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_G0 "\" S {compress: false})"); +} +static void srr_teardown(void) { ray_idx_lazy_clear(); sr_rt_teardown(); } + +static ray_t* sr_load(int gen) { + ray_t* t = sr_eval(gen ? "(.db.splayed.get \"" SR_G2 "\")" : "(.db.splayed.get \"" SR_G0 "\")"); + return (t && !RAY_IS_ERR(t)) ? t : NULL; +} + +/* Run `q` (the table written as T) against a fresh load of each generation: + * equal formatted results; the generation-2 run materializes exactly + * `want_mat` columns (UINT64_MAX: not checked). */ +static test_result_t sr_same_on(const char* t0, const char* t2, const char* q, uint64_t want_mat) { + ray_t* out[2] = { NULL, NULL }; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? t2 : t0); + ray_enc_counters_reset(); + out[gen] = sr_eval(q); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "gen %d: %s: %s", gen, q, + out[gen] ? ray_error_msg() : "null"); + if (gen && want_mat != UINT64_MAX) { /* UINT64_MAX: answers only */ + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.materialized == want_mat, "%s: %llu materializations, want %llu", + q, (unsigned long long)k.materialized, (unsigned long long)want_mat); + } + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && + memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, + "%s differs:\n%.*s\nvs\n%.*s", q, (int)ray_str_len(fa), ray_str_ptr(fa), + (int)ray_str_len(fb), ray_str_ptr(fb)); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + PASS(); +} +static test_result_t sr_same(const char* q, uint64_t want_mat) { + return sr_same_on("(.db.splayed.get \"" SR_G0 "\")", "(.db.splayed.get \"" SR_G2 "\")", q, want_mat); +} +#define SR_SAME(q, m) do { test_result_t r_ = sr_same((q), (m)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* Selection from a fused predicate, compared segment by segment, over the + * tables saved at dirs[0] (generation 0) and dirs[1] (generation 2). */ +static test_result_t sr_sel_same_at(const char* const dirs[2], ray_op_t* (*build)(ray_graph_t*)) { + ray_t* blk[2] = { NULL, NULL }; bool all[2] = { false, false }; + for (int gen = 0; gen < 2; gen++) { + char q[600]; + snprintf(q, sizeof q, "(.db.splayed.get \"%s\")", dirs[gen]); + ray_t* t = sr_eval(q); + if (t && RAY_IS_ERR(t)) { ray_error_free(t); t = NULL; } + TEST_ASSERT_NOT_NULL(t); + ray_enc_counters_reset(); + ray_graph_t* g = ray_graph_new(t); + ray_op_t* pred = build(g); + blk[gen] = exec_pred_to_selection(g, pred, ray_table_nrows(t), &all[gen]); + TEST_ASSERT_FMT(!(blk[gen] && RAY_IS_ERR(blk[gen])), "gen %d: %s", gen, ray_error_msg()); + TEST_ASSERT_TRUE(blk[gen] || all[gen]); /* the fused path took it */ + if (gen) { ray_enc_counters_t k; ray_enc_counters_get(&k); TEST_ASSERT_EQ_U(k.materialized, 0); } + ray_graph_free(g); ray_release(t); + } + TEST_ASSERT_EQ_I(all[0], all[1]); + if (blk[0]) { + ray_rowsel_t* a = ray_rowsel_meta(blk[0]); ray_rowsel_t* b = ray_rowsel_meta(blk[1]); + TEST_ASSERT_EQ_I(a->total_pass, b->total_pass); + TEST_ASSERT_EQ_I(a->n_segs, b->n_segs); + TEST_ASSERT_TRUE(memcmp(ray_rowsel_flags(blk[0]), ray_rowsel_flags(blk[1]), a->n_segs) == 0); + TEST_ASSERT_TRUE(memcmp(ray_rowsel_offsets(blk[0]), ray_rowsel_offsets(blk[1]), (a->n_segs + 1) * 4) == 0); + uint32_t nidx = ray_rowsel_offsets(blk[0])[a->n_segs]; + TEST_ASSERT_TRUE(memcmp(ray_rowsel_idx(blk[0]), ray_rowsel_idx(blk[1]), (size_t)nidx * 2) == 0); + ray_rowsel_release(blk[0]); ray_rowsel_release(blk[1]); + } + PASS(); +} +static test_result_t sr_sel_same(ray_op_t* (*build)(ray_graph_t*)) { + static const char* const dirs[2] = { SR_G0, SR_G2 }; + return sr_sel_same_at(dirs, build); +} + +static ray_op_t* pred_v_gt(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "v"), ray_const_i64(g, 100000)); } +static ray_op_t* pred_k_band(ray_graph_t* g) { return ray_and(g, ray_ge(g, ray_scan(g, "k"), ray_const_i64(g, 1000)), + ray_lt(g, ray_scan(g, "k"), ray_const_i64(g, 150000))); } +static ray_op_t* pred_f_lt(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "f"), ray_const_f64(g, 77777.5)); } +static ray_op_t* pred_mixed(ray_graph_t* g) { return ray_and(g, ray_eq(g, ray_scan(g, "g"), ray_const_i64(g, 3)), + ray_gt(g, ray_add(g, ray_scan(g, "v"), ray_scan(g, "u")), ray_const_i64(g, 500))); } + +static test_result_t test_expr_select_equal(void) { + test_result_t r; + if ((r = sr_sel_same(pred_v_gt)).status != TEST_PASS) return r; + if ((r = sr_sel_same(pred_k_band)).status != TEST_PASS) return r; + if ((r = sr_sel_same(pred_f_lt)).status != TEST_PASS) return r; /* nullable F64 */ + if ((r = sr_sel_same(pred_mixed)).status != TEST_PASS) return r; /* two encoded registers */ + PASS(); +} + +/* Element-wise fused output: (+ k v) as a whole vector, generation 0 vs 2. */ +static test_result_t test_expr_elementwise_equal(void) { + ray_t* res[2]; + for (int gen = 0; gen < 2; gen++) { + ray_t* t = sr_load(gen); + TEST_ASSERT_NOT_NULL(t); + ray_enc_counters_reset(); + ray_graph_t* g = ray_graph_new(t); + ray_op_t* e = ray_add(g, ray_scan(g, "k"), ray_scan(g, "v")); + res[gen] = ray_execute(g, ray_optimize(g, e)); + TEST_ASSERT_TRUE(res[gen] && !RAY_IS_ERR(res[gen])); + if (gen) { ray_enc_counters_t k; ray_enc_counters_get(&k); TEST_ASSERT_EQ_U(k.materialized, 0); } + ray_graph_free(g); ray_release(t); + } + TEST_ASSERT_EQ_I(res[0]->type, res[1]->type); + TEST_ASSERT_EQ_I(res[0]->len, res[1]->len); + TEST_ASSERT_EQ_I(res[0]->attrs & RAY_ATTR_HAS_NULLS, res[1]->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(memcmp(ray_data(res[0]), ray_data(res[1]), (size_t)res[0]->len * 8) == 0); + ray_release(res[0]); ray_release(res[1]); + PASS(); +} + +/* Review focus 3: a fused morsel that starts mid-vector. The hook + * ray_expr_test_eval_range runs the morsel evaluator over [1000, 1100) + * directly (the pool only cuts unaligned tasks above its ring cap), for a + * nullable I32 and a nullable F64 column, generation 0 against 2. */ +static test_result_t sr_mid_one(ray_op_t* (*build)(ray_graph_t*)) { + uint8_t out[2][100]; + memset(out[0], 0xA5, sizeof out[0]); /* unwritten bytes cannot compare equal */ + memset(out[1], 0x5A, sizeof out[1]); + for (int gen = 0; gen < 2; gen++) { + ray_t* t = sr_load(gen); + ray_graph_t* g = ray_graph_new(t); + ray_expr_t ex; + ray_t* cerr = NULL; + TEST_ASSERT_TRUE(expr_compile(g, t, build(g), &ex, &cerr)); + TEST_ASSERT_NULL(cerr); + TEST_ASSERT_EQ_I(ex.out_type, RAY_BOOL); + ray_t* err = NULL; + ray_expr_test_eval_range(&ex, 1000, 1100, out[gen], &err); + TEST_ASSERT_NULL(err); + ray_graph_free(g); ray_release(t); + } + TEST_ASSERT_TRUE(memcmp(out[0], out[1], 100) == 0); + PASS(); +} +static ray_op_t* mid_v(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "v"), ray_const_i64(g, 2500)); } +static ray_op_t* mid_f(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "f"), ray_const_f64(g, 1040.0)); } +static ray_op_t* mid_vf(ray_graph_t* g) { return ray_and(g, mid_v(g), ray_ne(g, ray_scan(g, "f"), ray_const_f64(g, 1050.0))); } +static test_result_t test_expr_nulls_midvector(void) { + test_result_t r; + if ((r = sr_mid_one(mid_v)).status != TEST_PASS) return r; /* v: null every 10th row */ + if ((r = sr_mid_one(mid_f)).status != TEST_PASS) return r; /* f: null every 13th row */ + if ((r = sr_mid_one(mid_vf)).status != TEST_PASS) return r; /* two encoded registers */ + PASS(); +} + +/* Finding C2: (count (select {from: T where: })) is answered by + * try_count_simple_compare on range reads (ClickBench q2's shape), never + * materializing. */ +static test_result_t test_count_fast_path(void) { + uint64_t f0 = ray_query_test_count_fast(); + SR_SAME("(count (select {from: T where: (== g 3)}))", 0); /* I16 */ + SR_SAME("(count (select {from: T where: (> k 150000)}))", 0); /* I64 */ + SR_SAME("(count (select {from: T where: (!= u 7)}))", 0); /* U8 */ + SR_SAME("(count (select {from: T where: (< d 100)}))", 0); /* DATE, integer literal */ + SR_SAME("(count (select {from: T where: (== s 'c)}))", 0); /* file-domain SYM */ + SR_SAME("(count (select {from: T where: (== s 'zz)}))", 0); /* absent symbol */ + TEST_ASSERT_EQ_U(ray_query_test_count_fast() - f0, 12); /* 6 shapes x 2 generations */ + PASS(); +} + +/* Task 17i: the count fast path's tasks decode into a fixed vector lent + * from their own stack, so a worker's first decode takes nothing from its + * heap (a fresh worker heap maps a whole pool on its first allocation: + * ClickBench q2's first run). The answers equal generation 0's. */ +static test_result_t test_count_fast_lent_scratch(void) { + uint64_t f0 = ray_query_test_count_fast(), a0 = ray_col_test_fixed_allocs(); + SR_SAME("(count (select {from: T where: (== g 3)}))", 0); /* I16 */ + SR_SAME("(count (select {from: T where: (> k 150000)}))", 0); /* I64 */ + SR_SAME("(count (select {from: T where: (!= u 7)}))", 0); /* U8 */ + SR_SAME("(count (select {from: T where: (== s 'c)}))", 0); /* file-domain SYM */ + TEST_ASSERT_EQ_U(ray_query_test_count_fast() - f0, 8); + TEST_ASSERT_FMT(ray_col_test_fixed_allocs() == a0, "%llu fixed vectors from the heap", + (unsigned long long)(ray_col_test_fixed_allocs() - a0)); + PASS(); +} + +/* ...and a group's tasks decode their first two encoded sources into + * fixed vectors lent from their cursor sets (ClickBench q8's shape, and + * a key beside an input): no fixed vector from the heap, the answers + * generation 0's. */ +static test_result_t test_group_lent_scratch(void) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + uint64_t a0 = ray_col_test_fixed_allocs(); + SR_SAME("(select {g: g c: (count g) from: T where: (!= g 3) by: g desc: c take: 10})", UINT64_MAX); + SR_SAME("(select {s: (sum u) from: T by: g})", UINT64_MAX); + TEST_ASSERT_FMT(ray_col_test_fixed_allocs() == a0, "%llu fixed vectors from the heap", + (unsigned long long)(ray_col_test_fixed_allocs() - a0)); + /* Fix round 1: six encoded sources in one set (a key, five inputs): + * the first two are lent, the rest take their vectors from the heap, + * and no cursor is lent past the set's vectors (ASan). */ + SR_SAME("(select {a: (sum u) b: (sum v) c: (max f) d: (min k) e: (sum h) from: T by: g})", UINT64_MAX); + TEST_ASSERT_FMT(ray_col_test_fixed_allocs() > a0, "six encoded sources, no fixed vector from the heap"); + PASS(); +} + +/* The fast path's SYM compare, on an in-memory (runtime-domain) table and + * over a file domain at both generations, with nulls and an absent + * literal: EQ / NE take the fast path and equal the general path (`and + * ... true` declines the fast path); the ordered compares decline (#738: + * symbols order by string, never by raw id). */ +static test_result_t test_count_fast_sym_nulls(void) { + sr_eval_ok("(set N (table [s] (list (take (as 'SYM (list \"zq\" \"aq\" \"\" \"mq\")) 30001))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/n0/\" N {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/n2/\" N {compress: true})"); + static const char* eqs[] = { "(== s 'mq)", "(!= s 'mq)", "(== s 'qqq)", "(!= s 'qqq)" }; + static const char* ords[] = { + "(< s 'mq)", "(<= s 'mq)", "(> s 'aq)", "(>= s 'aq)", + "(< s 'qqq)", "(<= s 'qqq)", "(> s 'qqq)", "(>= s 'qqq)", + }; + static const char* const loads[] = { + "(set T N)", /* runtime domain */ + "(set T (.db.splayed.get \"" SR_TMP "/n0/\"))", + "(set T (.db.splayed.get \"" SR_TMP "/n2/\"))", + }; + for (int l = 0; l < 3; l++) { + sr_eval_ok(loads[l]); + for (size_t i = 0; i < sizeof eqs / sizeof eqs[0]; i++) { + char q[256]; + uint64_t f0 = ray_query_test_count_fast(); + snprintf(q, sizeof q, "(count (select {from: T where: %s}))", eqs[i]); + ray_t* a = sr_eval(q); + TEST_ASSERT_FMT(ray_query_test_count_fast() - f0 == 1, "load %d %s: not the fast path", l, eqs[i]); + snprintf(q, sizeof q, "(count (select {from: T where: (and %s true)}))", eqs[i]); + ray_t* b = sr_eval(q); + TEST_ASSERT_TRUE(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b)); + TEST_ASSERT_FMT(a->i64 == b->i64, "load %d %s: fast %lld, general %lld", l, eqs[i], + (long long)a->i64, (long long)b->i64); + ray_release(a); ray_release(b); + } + for (size_t i = 0; i < sizeof ords / sizeof ords[0]; i++) { + char q[256]; + uint64_t f0 = ray_query_test_count_fast(); + snprintf(q, sizeof q, "(count (select {from: T where: %s}))", ords[i]); + ray_t* a = sr_eval(q); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + TEST_ASSERT_FMT(ray_query_test_count_fast() == f0, "load %d %s: took the fast path", l, ords[i]); + ray_release(a); + } + } + PASS(); +} + +/* The reuse rule: a generation-2 column whose materialization is already + * published compiles to a plain register over that vector (no range + * reads) and is not decoded again. */ +static test_result_t test_expr_reuses_materialized(void) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", SR_G2); + ray_t* s = sr_eval("(at T 'v)"); /* forced at the top: materializes v */ + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); + ray_release(s); + ray_t* t = sr_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* ev = ray_table_get_col_enc(t, ray_sym_intern("v", 1)); + TEST_ASSERT_NOT_NULL(ev); + ray_t* dec = ray_enccol_decoded_peek(ev); + TEST_ASSERT_NOT_NULL(dec); + ray_enc_counters_reset(); + ray_graph_t* g = ray_graph_new(t); + ray_expr_t ex; + ray_t* err = NULL; + TEST_ASSERT_TRUE(expr_compile(g, t, ray_add(g, ray_scan(g, "k"), ray_scan(g, "v")), &ex, &err)); + TEST_ASSERT_NULL(err); + int seen = 0; + for (uint8_t r = 0; r < ex.n_regs; r++) { + if (ex.regs[r].kind != REG_SCAN) continue; + if (ex.regs[r].col_type == RAY_I32) { /* v */ + TEST_ASSERT_FALSE(ex.regs[r].enc); + TEST_ASSERT_TRUE(ex.regs[r].data == ray_data(dec)); + seen++; + } else { /* k: not materialized */ + TEST_ASSERT_TRUE(ex.regs[r].enc && !ex.regs[r].data); + seen++; + } + } + TEST_ASSERT_EQ_I(seen, 2); + ray_t* out = expr_eval_full(&ex, ray_table_nrows(t)); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out)); + ray_release(out); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_graph_free(g); ray_release(t); + PASS(); +} + +/* The element-wise and the group call sites of expr_eval_full (on a + * generation-2 table neither run decodes k or v, so the fused path is the + * one taken; the group key g is read whole), and an interrupt is + * `cancel`. */ +static test_result_t test_expr_error_sites(void) { + static const char* const qs[] = { + "(select {z: (+ k v) from: T})", + "(select {z: (max (* k v)) by: g from: T})", + }; + for (int i = 0; i < 2; i++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", SR_G2); + ray_t* r = sr_eval(qs[i]); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(r); + ray_t* t = sr_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + for (int c = 0; c < 2; c++) { + ray_t* ev = ray_table_get_col_enc(t, ray_sym_intern(c ? "v" : "k", 1)); + TEST_ASSERT_FMT(ev && !ray_enccol_decoded_peek(ev), "%s: column %s decoded", qs[i], c ? "v" : "k"); + } + ray_release(t); + } + /* cancel: an interrupted dispatch is `cancel`, not a partial selection */ + ray_t* t = sr_load(1); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + bool all = false; + ray_request_interrupt(); + ray_t* sel = exec_pred_to_selection(g, pred_v_gt(g), ray_table_nrows(t), &all); + ray_clear_interrupt(); + TEST_ASSERT_TRUE(sel && RAY_IS_ERR(sel)); + TEST_ASSERT_STR_EQ(ray_err_code(sel), "cancel"); + ray_error_free(sel); + ray_graph_free(g); ray_release(t); + PASS(); +} + +/* ---- Task 3b: decode speed (counters, native compares, register widening) ---- */ + +/* Decoded-byte totals are flushed per scratch, not per vector: after a + * query they are what one decode of every row read gives (pinned). */ +static test_result_t test_decoded_bytes_pinned(void) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", SR_G2); + ray_enc_counters_reset(); + ray_t* r = sr_eval("(count (select {from: T where: (== g 3)}))"); /* the count fast path, I16 */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(r); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); /* P3 Task 3b: counted on its views */ + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t* t = sr_eval("T"); + ray_t* eg = ray_table_get_col_enc(t, ray_sym_intern("g", 1)); + TEST_ASSERT_NOT_NULL(eg); + uint64_t col0 = atomic_load(&ray_enccol_of(eg)->decoded_bytes); + TEST_ASSERT_EQ_U(col0, 0); /* per column too */ + ray_enc_counters_reset(); + r = sr_eval("(select {z: (+ k v) from: T})"); /* fused: I64 and nullable I32 registers */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(r); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 200000 * (8 + 4)); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_enc_counters_reset(); + r = sr_eval("(select {z: (+ g 1) from: T})"); /* the widened I16 register */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_release(r); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 200000 * 2); + TEST_ASSERT_EQ_U(atomic_load(&ray_enccol_of(eg)->decoded_bytes), col0 + 200000 * 2); + ray_release(t); + PASS(); +} + +/* The native-width count kernels against the widening reference, all six + * compares, literals inside the type, at its bounds and outside it, over + * one span longer than 65535 rows. */ +static test_result_t test_count_native_kernels(void) { + enum { n = 200003 }; + static int16_t x16[n]; static int32_t x32[n]; static uint8_t x8[n]; + uint64_t s = 0x9e3779b97f4a7c15ull; + for (int64_t i = 0; i < n; i++) { + s ^= s << 13; s ^= s >> 7; s ^= s << 17; + x16[i] = (int16_t)(uint16_t)s; x32[i] = (int32_t)(uint32_t)(s >> 16); x8[i] = (uint8_t)(s >> 40); + } + x16[7] = INT16_MIN; x16[8] = INT16_MAX; x32[7] = INT32_MIN; x32[8] = INT32_MAX; x8[7] = 0; x8[8] = 255; + static const int64_t lit16[] = { 0, 5, -77, INT16_MIN, INT16_MAX, INT16_MIN - 1, INT16_MAX + 1, 100000, -100000, INT64_MIN + 1, INT64_MAX }; + static const int64_t lit32[] = { 0, 5, -77, INT32_MIN, INT32_MAX, (int64_t)INT32_MIN - 1, (int64_t)INT32_MAX + 1, 5000000000ll, -5000000000ll }; + static const int64_t lit8[] = { 0, 1, 200, 255, 256, -1, 1000 }; + static const int64_t lens[] = { 200003, 65535, 65536, 1000, 1, 0 }; + for (int op = 1; op <= 6; op++) { + for (size_t li = 0; li < sizeof lens / sizeof lens[0]; li++) { + int64_t m = lens[li]; + for (size_t i = 0; i < sizeof lit16 / sizeof lit16[0]; i++) { + int64_t a = ray_query_test_count_compare(RAY_I16, x16, m, lit16[i], op, false); + int64_t b = ray_query_test_count_compare(RAY_I16, x16, m, lit16[i], op, true); + TEST_ASSERT_FMT(a == b, "I16 op %d lit %lld n %lld: %lld vs %lld", op, (long long)lit16[i], (long long)m, (long long)a, (long long)b); + } + for (size_t i = 0; i < sizeof lit32 / sizeof lit32[0]; i++) { + for (int t = 0; t < 3; t++) { + int8_t ty = t == 0 ? RAY_I32 : t == 1 ? RAY_DATE : RAY_TIME; + int64_t a = ray_query_test_count_compare(ty, x32, m, lit32[i], op, false); + int64_t b = ray_query_test_count_compare(ty, x32, m, lit32[i], op, true); + TEST_ASSERT_FMT(a == b, "type %d op %d lit %lld n %lld: %lld vs %lld", ty, op, (long long)lit32[i], (long long)m, (long long)a, (long long)b); + } + } + for (size_t i = 0; i < sizeof lit8 / sizeof lit8[0]; i++) { + for (int t = 0; t < 2; t++) { + int8_t ty = t ? RAY_BOOL : RAY_U8; + int64_t a = ray_query_test_count_compare(ty, x8, m, lit8[i], op, false); + int64_t b = ray_query_test_count_compare(ty, x8, m, lit8[i], op, true); + TEST_ASSERT_FMT(a == b, "type %d op %d lit %lld n %lld: %lld vs %lld", ty, op, (long long)lit8[i], (long long)m, (long long)a, (long long)b); + } + } + } + } + /* the all-true / all-false answers are exact counts */ + TEST_ASSERT_EQ_I(ray_query_test_count_compare(RAY_I16, x16, n, 40000, 3, false), n); /* < above the type */ + TEST_ASSERT_EQ_I(ray_query_test_count_compare(RAY_I16, x16, n, 40000, 5, false), 0); /* > above the type */ + TEST_ASSERT_EQ_I(ray_query_test_count_compare(RAY_I32, x32, n, -5000000000ll, 6, false), n); + PASS(); +} + +/* The same through queries: both generations, the fast path against the + * general one (`and ... true` declines the fast path), nulls included (a + * nullable column declines the fast path: the answers still agree). */ +static test_result_t test_count_native_queries(void) { + sr_eval_ok("(set i (til 70001))"); + sr_eval_ok("(set N (table [x y xn yn z] (list (as 'I16 (- (% (* i 7919) 65535) 32767)) " + "(as 'I32 (- (% (* i 1000003) 4294967295) 2147483647)) " + "(as 'I16 (map (fn [j] (if (== 0 (% j 11)) 0N (- (% j 3000) 1500))) i)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 7)) 0N (* j 9))) i)) (as 'U8 (% i 251)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/c0/\" N {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/c2/\" N {compress: true})"); + static const char* ops[] = { "==", "!=", "<", "<=", ">", ">=" }; + static const char* cols[] = { "x", "y", "xn", "z" }; + static const char* lits[] = { "0", "-1500", "32767", "-32768", "40000", "2147483647", "-2147483649", "251" }; + static const char* const loads[] = { "(set T (.db.splayed.get \"" SR_TMP "/c0/\"))", + "(set T (.db.splayed.get \"" SR_TMP "/c2/\"))" }; + int64_t first[4][6][8]; + for (int l = 0; l < 2; l++) { + sr_eval_ok(loads[l]); + for (int c = 0; c < 4; c++) + for (int o = 0; o < 6; o++) + for (int k = 0; k < 8; k++) { + char q[256]; + uint64_t f0 = ray_query_test_count_fast(); + snprintf(q, sizeof q, "(count (select {from: T where: (%s %s %s)}))", ops[o], cols[c], lits[k]); + ray_t* a = sr_eval(q); + bool fast = ray_query_test_count_fast() - f0 == 1; + snprintf(q, sizeof q, "(count (select {from: T where: (and (%s %s %s) true)}))", ops[o], cols[c], lits[k]); + ray_t* b = sr_eval(q); + TEST_ASSERT_FMT(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b), "gen %d %s", l * 2, q); + TEST_ASSERT_FMT(a->i64 == b->i64, "gen %d (%s %s %s): fast %lld, general %lld", l * 2, ops[o], cols[c], lits[k], + (long long)a->i64, (long long)b->i64); + TEST_ASSERT_FMT(fast == (c != 2), "gen %d (%s %s %s): fast path %d", l * 2, ops[o], cols[c], lits[k], fast); + if (l == 0) first[c][o][k] = a->i64; + else TEST_ASSERT_FMT(first[c][o][k] == a->i64, "(%s %s %s): gen 0 %lld, gen 2 %lld", ops[o], cols[c], lits[k], + (long long)first[c][o][k], (long long)a->i64); + ray_release(a); ray_release(b); + } + } + PASS(); +} + +/* Narrow registers widened straight from the packed vector: I16 and I32 + * with nulls, element-wise and as a filter, both generations equal. */ +static test_result_t test_expr_widened_registers(void) { + uint64_t h0 = ray_col_test_wide_hits(); + SR_SAME("(select {z: (+ g 1) from: T})", 0); /* I16, no nulls */ + TEST_ASSERT_FMT(ray_col_test_wide_hits() - h0 == 196, "(+ g 1): %llu of 196 vectors widened in place", + (unsigned long long)(ray_col_test_wide_hits() - h0)); /* gen 2 only; every vector FOR_BP */ + SR_SAME("(select {z: (* v 2) from: T})", 0); /* I32, null every 10th */ + SR_SAME("(count (select {from: T where: (> (+ g 1) 3)}))", 0); + SR_SAME("(select {z: (* (+ v 1) 0.5) from: T})", 0); /* an F64 program over I32 */ + sr_eval_ok("(set i (til 70001))"); + sr_eval_ok("(set W (table [xn yn] (list (as 'I16 (map (fn [j] (if (== 0 (% j 11)) 0N (- (% j 3000) 1500))) i)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 7)) 0N (* j -9))) i)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w0/\" W {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w2/\" W {compress: true})"); + static const char* qs[] = { "(select {z: (+ xn 1) from: T})", "(select {z: (* yn 2) from: T})", + "(select {z: (+ xn yn) from: T})", "(select {z: (* xn 0.25) from: T})" }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_TMP "/w2/" : SR_TMP "/w0/"); + ray_enc_counters_reset(); + uint64_t h0 = ray_col_test_wide_hits(); + out[gen] = sr_eval(qs[i]); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "%s gen %d", qs[i], gen); + uint64_t hits = ray_col_test_wide_hits() - h0; + if (gen) { + ray_enc_counters_t k; ray_enc_counters_get(&k); TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_FMT(hits > 0, "%s: no vector widened in place", qs[i]); + } else { + TEST_ASSERT_EQ_U(hits, 0); /* generation 0 reads in place */ + } + } + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[1], 0); + TEST_ASSERT_FMT(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0, "%s differs", qs[i]); + ray_release(fa); ray_release(fb); ray_release(out[0]); ray_release(out[1]); + } + PASS(); +} + +/* ---- Task 4: parted fused expressions over encoded segments ---- */ + +/* Three partitions of [x y] under `root`: bit p of gen2 writes partition p + * compressed; ragged: partition 3 has only x; nullref: partition 3 carries + * y as explicit nulls (the reference for the ragged table). */ +static void sr_parted_xy(const char* root, unsigned gen2, bool ragged, bool nullref) { + for (int p = 0; p < 3; p++) { + const char* tbl = (ragged && p == 2) ? "(table [x] (list (til 70000)))" + : (nullref && p == 2) ? "(table [x y] (list (til 70000) (take [0Nl] 70000)))" + : "(table [x y] (list (til 70000) (% (til 70000) 97)))"; + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.0%d/t/\" %s {compress: %s})", root, p + 1, tbl, + ((gen2 >> p) & 1) ? "true" : "false"); + } +} +/* (+ x y) over a parted table through the parted evaluator + * (expr_eval_full_parted). ray_execute of the bare graph streams the + * partitions one flat segment table at a time (build_segment_table) and + * never reaches it; a projecting select keeps the table parted, so the + * element-wise arm sees parted registers. Returns the z column. */ +static ray_t* sr_parted_add(const char* root, uint64_t* mat) { + sr_evalf_ok("(set T (.db.parted.get \"%s\" 't))", root); + ray_enc_counters_reset(); + ray_t* q = sr_eval("(select {z: (+ x y) from: T})"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (mat) *mat = k.materialized; + if (!q || RAY_IS_ERR(q)) return q; + ray_t* v = ray_table_get_col(q, ray_sym_intern("z", 1)); + if (v) ray_retain(v); + ray_release(q); + return v; +} +static bool sr_vec_eq(ray_t* a, ray_t* b) { + return a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && a->type == b->type && a->len == b->len && + (a->attrs & RAY_ATTR_HAS_NULLS) == (b->attrs & RAY_ATTR_HAS_NULLS) && + memcmp(ray_data(a), ray_data(b), (size_t)a->len * ray_sym_elem_size(a->type, a->attrs)) == 0; +} +/* Segments generation 2, 0, 2 against an all-generation-0 copy; and a + * ragged generation-0 table against its explicit-null reference. Equal + * vectors, nothing materialized. */ +static test_result_t test_expr_parted_segments(void) { + sr_parted_xy(SR_TMP "/pp2", 5, false, false); + sr_parted_xy(SR_TMP "/pp0", 0, false, false); + sr_parted_xy(SR_TMP "/prg", 0, true, false); + sr_parted_xy(SR_TMP "/pref", 0, false, true); + uint64_t m2 = 99, mr = 99; + ray_t* a = sr_parted_add(SR_TMP "/pp2", &m2); + ray_t* b = sr_parted_add(SR_TMP "/pp0", NULL); + ray_t* c = sr_parted_add(SR_TMP "/prg", &mr); + ray_t* d = sr_parted_add(SR_TMP "/pref", NULL); + TEST_ASSERT_TRUE(sr_vec_eq(a, b)); + TEST_ASSERT_EQ_U(m2, 0); + TEST_ASSERT_TRUE(sr_vec_eq(c, d)); /* ragged: synthetic nulls read by range */ + TEST_ASSERT_EQ_U(mr, 0); + /* one column with generation-2 segments and a synthetic null segment */ + sr_parted_xy(SR_TMP "/pmx", 3, true, false); + sr_parted_xy(SR_TMP "/pmxref", 3, false, true); + uint64_t mm = 99; + ray_t* e = sr_parted_add(SR_TMP "/pmx", &mm); + ray_t* f = sr_parted_add(SR_TMP "/pmxref", NULL); + TEST_ASSERT_TRUE(sr_vec_eq(e, f)); + TEST_ASSERT_EQ_U(mm, 0); + sr_drop(e); sr_drop(f); + /* a segment another consumer already materialized is read in place + * (published), the others by range: same vector, no new decode */ + sr_evalf_ok("(set T (.db.parted.get \"%s\" 't))", SR_TMP "/pp2"); + ray_t* t = sr_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* ey = ray_table_get_col_enc(t, ray_sym_intern("y", 1)); + TEST_ASSERT_TRUE(ey && ey->type == RAY_ENCCOL && ray_enccol_is_parted(ey)); + ray_t* s0 = ray_enccol_seg_col(ey, 0); + TEST_ASSERT_TRUE(s0 && !RAY_IS_ERR(s0)); + TEST_ASSERT_NOT_NULL(ray_enccol_decoded_peek(ray_enccol_seg(ey, 0))); + TEST_ASSERT_NULL(ray_enccol_decoded_peek(ey)); /* the column is not published */ + ray_enc_counters_reset(); + ray_t* q = sr_eval("(select {z: (+ x y) from: T})"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(q && !RAY_IS_ERR(q)); + TEST_ASSERT_EQ_U(k.materialized, 0); + /* only the unpublished generation-2 segments are decoded by range: + * x in partitions 1 and 3, y in partition 3 (y's partition 1 is read + * from its published vector) */ + TEST_ASSERT_EQ_U(k.decoded_bytes, 3 * 70000 * 8); + TEST_ASSERT_TRUE(sr_vec_eq(ray_table_get_col(q, ray_sym_intern("z", 1)), b)); + ray_release(q); ray_release(t); + sr_drop(a); sr_drop(b); sr_drop(c); sr_drop(d); + PASS(); +} + +/* Compile (+ x y) over parted table t and evaluate it through the parted + * evaluator directly (nrows rows). */ +static ray_t* sr_parted_eval(ray_t* t, int64_t nrows) { + ray_graph_t* g = ray_graph_new(t); + ray_expr_t ex; ray_t* cerr = NULL; + ray_t* v; + if (expr_compile(g, t, ray_add(g, ray_scan(g, "x"), ray_scan(g, "y")), &ex, &cerr)) + v = expr_eval_full(&ex, nrows); + else + v = cerr ? cerr : ray_error("nyi", "sr_parted_eval: not compiled"); + ray_graph_free(g); + return v; +} +/* A cancel ends the segment loop: two dispatched partitions (70000 rows, + * their tasks skipped by the cancelled pool) and a third one small enough + * to run inline; the answer is `cancel`, never the third's values. */ +static test_result_t test_expr_parted_cancel(void) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/pcn/2024.01.0%d/t/\" %s {compress: true})", p + 1, + p == 2 ? "(table [x y] (list (til 1000) (% (til 1000) 97)))" + : "(table [x y] (list (til 70000) (% (til 70000) 97)))"); + sr_eval_ok("(set T (.db.parted.get \"" SR_TMP "/pcn\" 't))"); + ray_t* t = sr_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* v = sr_parted_eval(t, 141000); /* the run: all three segments */ + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v) && v->len == 141000); + ray_release(v); + ray_request_interrupt(); + v = sr_parted_eval(t, 141000); + ray_clear_interrupt(); + TEST_ASSERT_TRUE(v && RAY_IS_ERR(v)); + TEST_ASSERT_STR_EQ(ray_err_code(v), "cancel"); + ray_error_free(v); + ray_release(t); + PASS(); +} + +/* Parted registers whose segments differ in length (a hand-built table: + * x splits 3000 + 5000, y 5000 + 3000) are a `length` error, never + * clipped or read past a segment end. */ +static test_result_t test_expr_parted_seg_lengths(void) { + ray_t* wx = sr_parted_i64(2, 4000); ray_t* wy = sr_parted_i64(2, 4000); + ray_t** sx = (ray_t**)ray_data(wx); ray_t** sy = (ray_t**)ray_data(wy); + ray_release(sx[0]); ray_release(sx[1]); ray_release(sy[0]); ray_release(sy[1]); + sx[0] = ray_vec_new(RAY_I64, 3000); sx[0]->len = 3000; memset(ray_data(sx[0]), 0, 3000 * 8); + sx[1] = ray_vec_new(RAY_I64, 5000); sx[1]->len = 5000; memset(ray_data(sx[1]), 0, 5000 * 8); + sy[0] = ray_vec_new(RAY_I64, 5000); sy[0]->len = 5000; memset(ray_data(sy[0]), 0, 5000 * 8); + sy[1] = ray_vec_new(RAY_I64, 3000); sy[1]->len = 3000; memset(ray_data(sy[1]), 0, 3000 * 8); + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("x", 1), wx); + t = ray_table_add_col(t, ray_sym_intern("y", 1), wy); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* v = sr_parted_eval(t, 8000); + TEST_ASSERT_TRUE(v && RAY_IS_ERR(v)); + TEST_ASSERT_STR_EQ(ray_err_code(v), "length"); + ray_error_free(v); + ray_release(t); ray_release(wx); ray_release(wy); + PASS(); +} + +/* The directory gate decides whole chunks: a predicate true for no row of + * chunks 1-3 reads none of them; inside chunk 0 the vectors' descriptors + * decide vectors 1-63 (Task 17b), so only vector 0 is read. k = row is + * DELTA_BP, which has no view (P3 Task 3: a viewed vector would be + * answered as an encoded leaf, decoding nothing), so vector 0 decodes. */ +static test_result_t test_zone_dir_skips(void) { + ray_t* t = sr_load(2); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + ray_enc_counters_reset(); + bool all = false; + ray_t* s = exec_pred_to_selection(g, ray_lt(g, ray_scan(g, "k"), ray_const_i64(g, 1000)), ray_table_nrows(t), &all); + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); + TEST_ASSERT_EQ_I(ray_rowsel_meta(s)->total_pass, 1000); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 1024 * 8); /* chunk 0's vector 0 only (DELTA_BP: no view) */ + /* why vector 0 decodes: DELTA_BP, which the view declines */ + { + ray_t* ek = ray_table_get_col_enc(t, ray_sym_intern("k", 1)); + TEST_ASSERT_NOT_NULL(ek); + const ray_enc_desc_t* d = ray_enccol_descs(ray_enccol_of(ek), 0); + TEST_ASSERT_EQ_I(d[0].encoding, RAY_ENC_DELTA_BP); + ray_enc_vview_t* vb = malloc(sizeof *vb); + ray_t* verr = NULL; + TEST_ASSERT_EQ_I(ray_enccol_vview(ray_enccol_of(ek), 0, vb, &verr), 0); /* declined: read by range */ + free(vb); + } + ray_rowsel_release(s); ray_graph_free(g); ray_release(t); + /* the count fast path decides chunks the same way; vector 0 (DELTA_BP) + * has no view, so it is read (P3 Task 3b counts viewed vectors only) */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + ray_t* c = sr_eval("(count (select {from: T where: (< k 1000)}))"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->i64 == 1000); + ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 1024 * 8); + sr_drop(c); + PASS(); +} + +/* Review focus 3: the null rule. v has a null every 10th row, so no + * chunk is decided all-pass for >, and every chunk can be decided + * all-fail for > above its maximum. Results equal generation 0. */ +static test_result_t test_zone_dir_nulls(void) { + test_result_t r; + if ((r = sr_sel_same(pred_v_gt)).status != TEST_PASS) return r; + SR_SAME("(count (select {from: T where: (> v 1000000)}))", 0); /* every chunk all-fail */ + SR_SAME("(count (select {from: T where: (< v 1000000)}))", 0); /* nulls pass < : mixed */ + SR_SAME("(count (select {from: T where: (>= d 899)}))", 0); + PASS(); +} + +/* Rows of a graph FILTER over table t, with the materializations it made. + * The node runs through exec_node, not ray_execute: the lazy filter returns + * t with g->selection installed, and ray_execute's final compaction would + * gather (today: materialize) every column of t. */ +static int64_t sr_filter_rows(ray_t* t, ray_op_t* (*build)(ray_graph_t*), uint64_t* mat) { + ray_graph_t* g = ray_graph_new(t); + ray_op_t* root = ray_filter(g, ray_const_table(g, t), build(g)); + ray_enc_counters_reset(); + ray_t* r = exec_node(g, root); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (mat) *mat = k.materialized; + int64_t n = (r && !RAY_IS_ERR(r)) ? (g->selection ? ray_rowsel_meta(g->selection)->total_pass : ray_table_nrows(r)) : -1; + sr_drop(r); ray_graph_free(g); + return n; +} +static ray_op_t* cpred_v_gt(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "v"), ray_const_i64(g, 100)); } +static ray_op_t* cpred_g_eq(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "g"), ray_const_i64(g, 3)); } +static ray_op_t* cpred_h_out(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, 1000004)); } +static ray_op_t* cpred_h_eq(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, 7919)); } +static ray_op_t* cpred_h_rng(ray_graph_t* g) { return ray_and(g, ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, 7919)), + ray_ge(g, ray_scan(g, "k"), ray_const_i64(g, 0))); } + +/* Finding C1: the OP_FILTER consults on a generation-2 column read the + * directory: same rows as generation 0, nothing materialized; a key outside + * the zone's range is answered as an index hit on both generations. */ +static test_result_t test_filter_consult_dir(void) { + ray_op_t* (*preds[])(ray_graph_t*) = { cpred_v_gt, cpred_g_eq, cpred_h_out, cpred_h_rng }; + for (size_t i = 0; i < sizeof preds / sizeof preds[0]; i++) { + int64_t n[2]; uint64_t hits[2]; + for (int gen = 0; gen < 2; gen++) { + ray_t* t = sr_load(gen); + TEST_ASSERT_NOT_NULL(t); + uint64_t h0 = ray_idx_hits[IDX_SITE_FILTER_ZONE]; + uint64_t mat = 0; + n[gen] = sr_filter_rows(t, preds[i], &mat); + hits[gen] = ray_idx_hits[IDX_SITE_FILTER_ZONE] - h0; + if (gen) TEST_ASSERT_FMT(mat == 0, "predicate %zu: %llu materializations", i, (unsigned long long)mat); + ray_release(t); + } + TEST_ASSERT_FMT(n[0] >= 0 && n[0] == n[1], "predicate %zu: %lld vs %lld rows", i, (long long)n[0], (long long)n[1]); + TEST_ASSERT_EQ_U(hits[0], hits[1]); + } + PASS(); +} + +/* PI lazy hash on a generation-2 column: the first RAY_IDX_LAZY_BUILD_PROBES - 1 + * point lookups scan by range and materialize nothing; the next one builds + * (materializing exactly the probed column once); later probes reuse it. + * Every answer equals generation 0's. */ +static test_result_t test_lazy_hash_enc(void) { + ray_idx_lazy_clear(); + ray_t* t0 = sr_load(0); + int64_t want = sr_filter_rows(t0, cpred_h_eq, NULL); + ray_release(t0); + TEST_ASSERT_EQ_I(want, 1); + ray_idx_lazy_clear(); + ray_t* t = sr_load(2); /* one load: one encoded object */ + for (int p = 1; p < RAY_IDX_LAZY_BUILD_PROBES; p++) { + uint64_t mat = 9; + TEST_ASSERT_EQ_I(sr_filter_rows(t, cpred_h_eq, &mat), want); + TEST_ASSERT_FMT(mat == 0, "probe %d materialized %llu", p, (unsigned long long)mat); + } + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + uint64_t mat = 0; + TEST_ASSERT_EQ_I(sr_filter_rows(t, cpred_h_eq, &mat), want); /* the build */ + TEST_ASSERT_EQ_U(mat, 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + TEST_ASSERT_EQ_I(sr_filter_rows(t, cpred_h_eq, &mat), want); /* reuse */ + TEST_ASSERT_EQ_U(mat, 0); + ray_release(t); + ray_idx_lazy_clear(); + PASS(); +} + +/* The IN consult and the eq+range conjunction on generation 2, and the + * .idx.uses count of a directory answer. A set outside the chunk zone's + * range is a zone hit on both generations; a set inside it is a pending + * lazy probe (nothing materialized). An eq+range list whose other + * conjuncts do not fit the shape never probes h's lazy hash (generation 0 + * decodes the conjuncts and declines before the probe; generation 2 decides + * that from metadata), a fitting one does. */ +static ray_t* sr_i64_set(int64_t a, int64_t b) { + ray_t* v = ray_vec_new(RAY_I64, 2); + ((int64_t*)ray_data(v))[0] = a; ((int64_t*)ray_data(v))[1] = b; + v->len = 2; + return v; +} +static ray_op_t* cpred_h_in_out(ray_graph_t* g) { + ray_t* v = sr_i64_set(1000004, 1000005); + ray_op_t* o = ray_in(g, ray_scan(g, "h"), ray_const_vec(g, v)); + ray_release(v); + return o; +} +static ray_op_t* cpred_h_in(ray_graph_t* g) { + ray_t* v = sr_i64_set(7919, 15838); + ray_op_t* o = ray_in(g, ray_scan(g, "h"), ray_const_vec(g, v)); + ray_release(v); + return o; +} +static ray_op_t* cpred_h_eq_g(ray_graph_t* g) { return ray_and(g, ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, 7919)), + ray_eq(g, ray_scan(g, "g"), ray_const_i64(g, 3))); } +static ray_op_t* cpred_h_rng_v(ray_graph_t* g) { return ray_and(g, ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, 7919)), + ray_ge(g, ray_scan(g, "v"), ray_const_i64(g, 0))); } +static test_result_t test_filter_consult_enc_shapes(void) { + ray_op_t* (*preds[])(ray_graph_t*) = { cpred_h_in_out, cpred_h_in, cpred_h_eq_g, cpred_h_rng_v, cpred_h_rng }; + const int64_t want_entries[] = { 0, 1, 0, 0, 1 }; /* lazy memos after one run */ + /* the consults decode nothing; the `in` scan that answers a pending + * probe range-reads its column */ + const uint64_t want_mat[] = { 0, 0, 0, 0, 0 }; + for (size_t i = 0; i < sizeof preds / sizeof preds[0]; i++) { + int64_t n[2]; uint64_t hits[2]; + for (int gen = 0; gen < 2; gen++) { + ray_idx_lazy_clear(); + ray_t* t = sr_load(gen); + TEST_ASSERT_NOT_NULL(t); + uint64_t h0 = ray_idx_hits[IDX_SITE_FILTER_ZONE]; + uint64_t mat = 0; + n[gen] = sr_filter_rows(t, preds[i], &mat); + hits[gen] = ray_idx_hits[IDX_SITE_FILTER_ZONE] - h0; + if (gen) TEST_ASSERT_FMT(mat == want_mat[i], "predicate %zu: %llu materializations", i, (unsigned long long)mat); + TEST_ASSERT_FMT(ray_idx_lazy_entries() == want_entries[i], "predicate %zu gen %d: %lld lazy entries", + i, gen, (long long)ray_idx_lazy_entries()); + ray_release(t); + } + TEST_ASSERT_FMT(n[0] >= 0 && n[0] == n[1], "predicate %zu: %lld vs %lld rows", i, (long long)n[0], (long long)n[1]); + TEST_ASSERT_EQ_U(hits[0], hits[1]); + if (i == 0) TEST_ASSERT_EQ_U(hits[1], 1); + } + ray_idx_lazy_clear(); + /* a directory answer counts under its column */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + sr_eval_ok("(do (.idx.uses T) null)"); + ray_t* c = sr_eval("(count (at (select {h: h from: T where: (== h 1000004)}) 'h))"); + TEST_ASSERT_TRUE(c && !RAY_IS_ERR(c) && c->i64 == 0); + sr_drop(c); + ray_t* u = sr_eval("(at (.idx.uses T) 'h)"); + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u) && u->i64 == 1); + sr_drop(u); + PASS(); +} + +/* A pending probe on a generation-2 column is a memo of its encoded + * payload that holds no reference: the table's release frees the column + * (and its mapping) at once, and the memo goes with it; any header copy of + * the column meets the same memo. */ +static test_result_t test_lazy_memo_goes_with_table(void) { + ray_idx_lazy_clear(); + int64_t live0 = ray_enccol_test_live(); + ray_t* t = sr_load(2); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_TRUE(ray_enccol_test_live() > live0); + TEST_ASSERT_EQ_I(sr_filter_rows(t, cpred_h_eq, NULL), 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 1); + TEST_ASSERT_EQ_I(sr_filter_rows(t, cpred_h_eq, NULL), 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 1); /* one memo, its work grows */ + ray_release(t); + TEST_ASSERT_EQ_I(ray_enccol_test_live(), live0); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 0); + PASS(); +} + +/* ---- Fix round 1 ---------------------------------------------------- */ + +/* Review I1: a column under 65536 rows records ZONE (not CHUNK_ZONE), so the + * OP_FILTER single-compare consult answers it from ray_enc_zone_class. A + * 1000-row table, a = row (I64), f = row (F64, 0.0 first): ALL, NONE and + * undecided compares, the F64 ones against -0.0 (== +0.0), give these rows + * on both generations through a graph FILTER and through select; generation + * 2 materializes nothing at the consult, and the zone hits are equal. */ +#define SR_Z0 SR_TMP "/z0/" +#define SR_Z2 SR_TMP "/z2/" +static ray_op_t* zp_a_ge0(ray_graph_t* g) { return ray_ge(g, ray_scan(g, "a"), ray_const_i64(g, 0)); } +static ray_op_t* zp_a_gt999(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "a"), ray_const_i64(g, 999)); } +static ray_op_t* zp_a_ge499(ray_graph_t* g) { return ray_ge(g, ray_scan(g, "a"), ray_const_i64(g, 499)); } +static ray_op_t* zp_a_ne1000(ray_graph_t* g){ return ray_ne(g, ray_scan(g, "a"), ray_const_i64(g, 1000)); } +static ray_op_t* zp_a_eq1000(ray_graph_t* g){ return ray_eq(g, ray_scan(g, "a"), ray_const_i64(g, 1000)); } +static ray_op_t* zp_f_ge_nz(ray_graph_t* g) { return ray_ge(g, ray_scan(g, "f"), ray_const_f64(g, -0.0)); } +static ray_op_t* zp_f_lt_nz(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "f"), ray_const_f64(g, -0.0)); } +static ray_op_t* zp_f_le_nz(ray_graph_t* g) { return ray_le(g, ray_scan(g, "f"), ray_const_f64(g, -0.0)); } +static ray_op_t* zp_f_gt_nz(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "f"), ray_const_f64(g, -0.0)); } +static ray_op_t* zp_f_gt998(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "f"), ray_const_f64(g, 998.5)); } +static test_result_t test_zone_class_dir_small(void) { + /* under 65536 rows a save records only a zone the column carries (the + * converters attach one to every such column) */ + sr_eval_ok("(set Z (table [a f] (list (.idx.zone (til 1000)) (.idx.zone (as 'F64 (til 1000))))))"); + sr_eval_ok("(.db.splayed.set \"" SR_Z0 "\" Z {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_Z2 "\" Z {compress: true})"); + static const struct { ray_op_t* (*build)(ray_graph_t*); const char* where; int64_t rows; uint64_t hit; } cs[] = { + { zp_a_ge0, "(>= a 0)", 1000, 1 }, /* ALL */ + { zp_a_gt999, "(> a 999)", 0, 1 }, /* NONE */ + { zp_a_ge499, "(>= a 499)", 501, 0 }, /* undecided: the scan */ + { zp_a_ne1000, "(!= a 1000)", 1000, 1 }, /* ALL */ + { zp_a_eq1000, "(== a 1000)", 0, 1 }, /* NONE */ + { zp_f_ge_nz, "(>= f -0.0)", 1000, 1 }, /* ALL: 0.0 >= -0.0 */ + { zp_f_lt_nz, "(< f -0.0)", 0, 1 }, /* NONE */ + { zp_f_le_nz, "(<= f -0.0)", 1, 0 }, /* undecided: row 0 equals */ + { zp_f_gt_nz, "(> f -0.0)", 999, 0 }, /* undecided */ + { zp_f_gt998, "(> f 998.5)", 1, 0 }, /* undecided */ + }; + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + for (int gen = 0; gen < 2; gen++) { + ray_t* t = sr_eval(gen ? "(.db.splayed.get \"" SR_Z2 "\")" : "(.db.splayed.get \"" SR_Z0 "\")"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_col_meta_t m; + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("a", 1), &m)); + TEST_ASSERT_EQ_I(m.index_kind, RAY_IDX_ZONE); + TEST_ASSERT_TRUE(gen ? m.enc != NULL : m.enc == NULL); + TEST_ASSERT_TRUE(ray_table_col_meta(t, ray_sym_intern("f", 1), &m)); + TEST_ASSERT_EQ_I(m.index_kind, RAY_IDX_ZONE); + uint64_t h0 = ray_idx_hits[IDX_SITE_FILTER_ZONE]; + uint64_t mat = 9; + int64_t n = sr_filter_rows(t, cs[i].build, &mat); + uint64_t hit = ray_idx_hits[IDX_SITE_FILTER_ZONE] - h0; + TEST_ASSERT_FMT(n == cs[i].rows, "%s gen %d: %lld rows, want %lld", cs[i].where, gen, + (long long)n, (long long)cs[i].rows); + TEST_ASSERT_FMT(hit == cs[i].hit, "%s gen %d: %llu zone hits", cs[i].where, gen, (unsigned long long)hit); + if (gen) TEST_ASSERT_FMT(mat == 0, "%s: %llu materializations", cs[i].where, (unsigned long long)mat); + ray_release(t); + /* the same through select (the projection reads a or f after the filter) */ + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_Z2 : SR_Z0); + char q[160]; + snprintf(q, sizeof q, "(count (at (select {a: a from: T where: %s}) 'a))", cs[i].where); + ray_t* r = sr_eval(q); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->i64 == cs[i].rows, "%s gen %d: select gave %lld", + q, gen, r && !RAY_IS_ERR(r) ? (long long)r->i64 : -1LL); + sr_drop(r); + } + } + PASS(); +} + +/* Review minor 1: .idx.uses keys a directory answer by the encoded payload, + * as the lazy cache does: an answer through a header copy of the column (a + * second table sharing the payload) shows in the original table's uses. */ +static ray_op_t* cpred_h_out2(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, -5)); } +static test_result_t test_uses_shared_payload(void) { + ray_t* t = sr_load(2); + TEST_ASSERT_NOT_NULL(t); + ray_t* enc = ray_table_get_col_enc(t, ray_sym_intern("h", 1)); + TEST_ASSERT_NOT_NULL(enc); + ray_enccol_ref(ray_enccol_of(enc)); /* the reference the new header holds */ + ray_t* cp = ray_enccol_wrap(ray_enccol_of(enc)); /* a second header, one payload */ + TEST_ASSERT_TRUE(cp && !RAY_IS_ERR(cp) && cp != enc && ray_enccol_of(cp) == ray_enccol_of(enc)); + ray_t* t2 = ray_table_add_col(ray_table_new(1), ray_sym_intern("h", 1), cp); + ray_release(cp); + TEST_ASSERT_TRUE(t2 && !RAY_IS_ERR(t2)); + TEST_ASSERT_TRUE(ray_table_get_col_enc(t2, ray_sym_intern("h", 1)) != enc); + ray_t* u = ray_idx_uses_fn(t); /* arms the counters, resets them */ + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u)); + ray_release(u); + uint64_t mat = 9; + TEST_ASSERT_EQ_I(sr_filter_rows(t2, cpred_h_out2, &mat), 0); /* a zone exclusion on the copy */ + TEST_ASSERT_EQ_U(mat, 0); + u = ray_idx_uses_fn(t); + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u) && ray_dict_len(u) == 1); + ray_t* key = ray_sym(ray_sym_intern("h", 1)); + ray_t* hv = ray_dict_get(u, key); + TEST_ASSERT_TRUE(hv && !RAY_IS_ERR(hv) && hv->i64 == 1); + sr_drop(hv); ray_release(key); ray_release(u); + ray_release(t2); ray_release(t); + PASS(); +} + +/* Review minor 5: compare literals on chunk boundaries of k (= row; chunk 1 + * is rows 65536..131071), through the fused selection, with absolute counts + * and the vectors decoded: a decided chunk 1 decodes nothing; in an + * undecided one the descriptors decide every vector but the one holding the + * literal (Task 17b), so one vector is decoded. A wrong boundary in + * zone_cmp_core shows without a generation-0 comparison. */ +static test_result_t test_zone_dir_boundaries(void) { + static const struct { uint16_t op; int64_t lit; int64_t rows; bool decoded; } cs[] = { + { OP_EQ, 65536, 1, true }, { OP_EQ, 131071, 1, true }, + { OP_NE, 65536, 199999, true }, { OP_NE, 131071, 199999, true }, + { OP_LT, 65536, 65536, false }, { OP_LT, 131071, 131071, true }, /* chunk min: chunk 1 all-fail */ + { OP_LE, 65536, 65537, true }, { OP_LE, 131071, 131072, false }, /* chunk max: chunk 1 all-pass */ + { OP_GT, 65536, 134463, true }, { OP_GT, 131071, 68928, false }, /* chunk max: chunk 1 all-fail */ + { OP_GE, 65536, 134464, false }, { OP_GE, 131071, 68929, true }, /* chunk min: chunk 1 all-pass */ + }; + ray_t* t = sr_load(2); + TEST_ASSERT_NOT_NULL(t); + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + ray_graph_t* g = ray_graph_new(t); + ray_op_t* k = ray_scan(g, "k"); + ray_op_t* c = ray_const_i64(g, cs[i].lit); + ray_op_t* p = cs[i].op == OP_EQ ? ray_eq(g, k, c) : cs[i].op == OP_NE ? ray_ne(g, k, c) + : cs[i].op == OP_LT ? ray_lt(g, k, c) : cs[i].op == OP_LE ? ray_le(g, k, c) + : cs[i].op == OP_GT ? ray_gt(g, k, c) : ray_ge(g, k, c); + ray_enc_counters_reset(); + bool all = false; + ray_t* s = exec_pred_to_selection(g, p, ray_table_nrows(t), &all); + TEST_ASSERT_FMT(!(s && RAY_IS_ERR(s)) && (s || all), "case %zu: no selection", i); + int64_t n = s ? ray_rowsel_meta(s)->total_pass : ray_table_nrows(t); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + TEST_ASSERT_FMT(n == cs[i].rows, "case %zu (op %u, %lld): %lld rows, want %lld", i, cs[i].op, + (long long)cs[i].lit, (long long)n, (long long)cs[i].rows); + TEST_ASSERT_FMT(kc.decoded_bytes == (cs[i].decoded ? 1024u * 8u : 0u), "case %zu: %llu bytes decoded", + i, (unsigned long long)kc.decoded_bytes); + TEST_ASSERT_EQ_U(kc.materialized, 0); + if (s) ray_rowsel_release(s); + ray_graph_free(g); + } + ray_release(t); + PASS(); +} + +/* ---- Task 6: fused predicates on range reads ------------------------- */ + +/* Compile a fused predicate over t0 and t2 and compare bits per morsel, + * aligned and then shifted by 500 rows (a window straddles a vector + * boundary: fp_eval_pred_rs splits it); nothing is materialized. */ +static int64_t g_fp_pass; /* passing rows of the aligned sweep */ +static test_result_t sr_fp_same_on(ray_t* t0, ray_t* t2, ray_op_t* (*build)(ray_graph_t*)) { + g_fp_pass = 0; + TEST_ASSERT_NOT_NULL(t0); TEST_ASSERT_NOT_NULL(t2); + ray_graph_t* g0 = ray_graph_new(t0); ray_graph_t* g2 = ray_graph_new(t2); + fp_pred_t p0, p2; + memset(&p0, 0, sizeof p0); memset(&p2, 0, sizeof p2); + ray_t* e0 = NULL; ray_t* e2 = NULL; + TEST_ASSERT_EQ_I(fp_compile_pred(g0, build(g0), t0, &p0, &e0), 0); + TEST_ASSERT_NULL(e0); + ray_enc_counters_reset(); + TEST_ASSERT_EQ_I(fp_compile_pred(g2, build(g2), t2, &p2, &e2), 0); + TEST_ASSERT_NULL(e2); + bool any_enc = false; /* generation 2 reads by range */ + for (uint8_t i = 0; i < p2.n_children; i++) any_enc |= p2.children[i].enc; + TEST_ASSERT_TRUE(any_enc); + fp_scratch_t sc; fp_scratch_init(&sc); + uint8_t a[RAY_MORSEL_ELEMS], b[RAY_MORSEL_ELEMS]; + int64_t n = ray_table_nrows(t0); + for (int64_t off = 0; off <= 500; off += 500) { + for (int64_t ms = off; ms < n; ms += RAY_MORSEL_ELEMS) { + int64_t me = ms + RAY_MORSEL_ELEMS < n ? ms + RAY_MORSEL_ELEMS : n; + fp_eval_pred(&p0, ms, me, a); + ray_t* e = fp_eval_pred_rs(&p2, ms, me, b, &sc); + TEST_ASSERT_NULL(e); + TEST_ASSERT_FMT(memcmp(a, b, (size_t)(me - ms)) == 0, "morsel at %lld", (long long)ms); + if (off == 0) for (int64_t i = 0; i < me - ms; i++) g_fp_pass += b[i]; + } + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + fp_scratch_free(&sc); fp_pred_cleanup(&p0); fp_pred_cleanup(&p2); + ray_graph_free(g0); ray_graph_free(g2); + PASS(); +} +static test_result_t sr_fp_same(ray_op_t* (*build)(ray_graph_t*)) { + ray_t* t0 = sr_load(0); ray_t* t2 = sr_load(2); + test_result_t r = sr_fp_same_on(t0, t2, build); + if (t0) ray_release(t0); + if (t2) ray_release(t2); + return r; +} +static ray_op_t* fpp_s_eq(ray_graph_t* g) { + ray_t* lit = ray_sym(ray_sym_intern("c", 1)); + ray_op_t* o = ray_eq(g, ray_scan(g, "s"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* fpp_v_le(ray_graph_t* g) { return ray_le(g, ray_scan(g, "v"), ray_const_i64(g, 4000)); } +static ray_op_t* fpp_d_ge(ray_graph_t* g) { + ray_t* lit = ray_date(10); /* DATE takes a DATE literal only */ + ray_op_t* o = ray_ge(g, ray_scan(g, "d"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* fpp_and3(ray_graph_t* g) { + return ray_and(g, ray_and(g, fpp_d_ge(g), fpp_s_eq(g)), + ray_gt(g, ray_scan(g, "f"), ray_const_f64(g, 120000.0))); +} +static ray_op_t* fpp_g_in(ray_graph_t* g) { + ray_t* set = ray_vec_new(RAY_I64, 2); set->len = 2; + ((int64_t*)ray_data(set))[0] = 2; ((int64_t*)ray_data(set))[1] = 5; + ray_op_t* o = ray_in(g, ray_scan(g, "g"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* fpp_s_like(ray_graph_t* g) { + ray_t* pat = ray_str("[bd]*", 5); + ray_op_t* o = ray_like(g, ray_scan(g, "s"), ray_const_atom(g, pat)); ray_release(pat); return o; +} +static test_result_t test_fp_range_equal(void) { + test_result_t r; + if ((r = sr_fp_same(fpp_s_eq)).status != TEST_PASS) return r; /* file-domain SYM */ + if ((r = sr_fp_same(fpp_v_le)).status != TEST_PASS) return r; /* nullable: typed compare */ + if ((r = sr_fp_same(fpp_and3)).status != TEST_PASS) return r; /* three children */ + if ((r = sr_fp_same(fpp_g_in)).status != TEST_PASS) return r; /* FP_IN arm */ + if ((r = sr_fp_same(fpp_s_like)).status != TEST_PASS) return r; /* FP_LIKE arm, file-domain LUT */ + PASS(); +} + +/* The directory gate decides whole chunks before a decode: k < 70000 + * passes chunk 0 and fails chunks 2-3 from their extrema; in chunk 1 the + * descriptors decide every vector but vector 68 (rows 69632..70655, Task + * 17b), the only one decoded. */ +static ray_op_t* fpp_k_lt(ray_graph_t* g) { return ray_lt(g, ray_scan(g, "k"), ray_const_i64(g, 70000)); } +static test_result_t test_fp_range_dir_gate(void) { + test_result_t r; + if ((r = sr_fp_same(fpp_k_lt)).status != TEST_PASS) return r; + ray_t* t = sr_load(2); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + fp_pred_t p; ray_t* e = NULL; + TEST_ASSERT_EQ_I(fp_compile_pred(g, fpp_k_lt(g), t, &p, &e), 0); + TEST_ASSERT_TRUE(p.children[0].enc); + ray_enc_counters_reset(); + fp_scratch_t sc; fp_scratch_init(&sc); + uint8_t b[RAY_MORSEL_ELEMS]; + int64_t n = ray_table_nrows(t), pass = 0; + for (int64_t ms = 0; ms < n; ms += RAY_MORSEL_ELEMS) { + int64_t me = ms + RAY_MORSEL_ELEMS < n ? ms + RAY_MORSEL_ELEMS : n; + TEST_ASSERT_NULL(fp_eval_pred_rs(&p, ms, me, b, &sc)); + for (int64_t i = 0; i < me - ms; i++) pass += b[i]; + } + fp_scratch_free(&sc); + TEST_ASSERT_EQ_I(pass, 70000); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 1024 * 8); + TEST_ASSERT_EQ_U(k.materialized, 0); + fp_pred_cleanup(&p); ray_graph_free(g); ray_release(t); + PASS(); +} + +/* A generation-2 column another consumer materialized is read as a plain + * child over the published vector (no second decode), beside an encoded + * child read by range. */ +static ray_op_t* fpp_v_k(ray_graph_t* g) { return ray_and(g, fpp_v_le(g), fpp_k_lt(g)); } +static test_result_t test_fp_range_ready_child(void) { + ray_t* t0 = sr_load(0); ray_t* t2 = sr_load(2); + TEST_ASSERT_NOT_NULL(t0); TEST_ASSERT_NOT_NULL(t2); + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("v", 1), &s)); + ray_t* col = NULL; + TEST_ASSERT_NULL(ray_col_src_plain(&s, &col)); /* publishes v's materialization */ + ray_col_src_release(&s); + ray_graph_t* g = ray_graph_new(t2); + fp_pred_t p; ray_t* e = NULL; + TEST_ASSERT_EQ_I(fp_compile_pred(g, fpp_v_k(g), t2, &p, &e), 0); + TEST_ASSERT_EQ_I(p.n_children, 2); + for (uint8_t i = 0; i < p.n_children; i++) { + bool is_v = p.children[i].typed_compare; /* v is nullable: the typed leg */ + TEST_ASSERT_EQ_I(p.children[i].enc, !is_v); + if (is_v) TEST_ASSERT_NOT_NULL(p.children[i].col_obj); + } + fp_pred_cleanup(&p); ray_graph_free(g); + test_result_t r = sr_fp_same_on(t0, t2, fpp_v_k); /* asserts no new materialization */ + ray_release(t0); ray_release(t2); + return r; +} + +/* A materialization published after the compile: the child stays encoded + * (enc was decided at compile), so the per-morsel bind reads the published + * vector in place. k < 70000 leaves chunk 1 undecided by the directory + * gate: without the in-place read its 64 vectors are decoded again. */ +static test_result_t test_fp_range_late_materialized(void) { + ray_t* t0 = sr_load(0); ray_t* t2 = sr_load(2); + TEST_ASSERT_NOT_NULL(t0); TEST_ASSERT_NOT_NULL(t2); + ray_graph_t* g0 = ray_graph_new(t0); ray_graph_t* g2 = ray_graph_new(t2); + fp_pred_t p0, p2; ray_t* e = NULL; + TEST_ASSERT_EQ_I(fp_compile_pred(g0, fpp_k_lt(g0), t0, &p0, &e), 0); + TEST_ASSERT_EQ_I(fp_compile_pred(g2, fpp_k_lt(g2), t2, &p2, &e), 0); + TEST_ASSERT_NULL(e); + TEST_ASSERT_TRUE(p2.children[0].enc); /* compiled before the publish */ + ray_col_src_t s; TEST_ASSERT_NULL(ray_table_col_src(t2, ray_sym_intern("k", 1), &s)); + ray_t* col = NULL; + TEST_ASSERT_NULL(ray_col_src_plain(&s, &col)); /* publishes k's materialization */ + ray_col_src_release(&s); + TEST_ASSERT_NOT_NULL(col); + ray_enc_counters_reset(); + fp_scratch_t sc; fp_scratch_init(&sc); + uint8_t a[RAY_MORSEL_ELEMS], b[RAY_MORSEL_ELEMS]; + int64_t n = ray_table_nrows(t0), pass = 0; + for (int64_t off = 0; off <= 500; off += 500) { + for (int64_t ms = off; ms < n; ms += RAY_MORSEL_ELEMS) { + int64_t me = ms + RAY_MORSEL_ELEMS < n ? ms + RAY_MORSEL_ELEMS : n; + fp_eval_pred(&p0, ms, me, a); + TEST_ASSERT_NULL(fp_eval_pred_rs(&p2, ms, me, b, &sc)); + TEST_ASSERT_FMT(memcmp(a, b, (size_t)(me - ms)) == 0, "morsel at %lld", (long long)ms); + if (off == 0) for (int64_t i = 0; i < me - ms; i++) pass += b[i]; + } + } + fp_scratch_free(&sc); + TEST_ASSERT_EQ_I(pass, 70000); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + fp_pred_cleanup(&p0); fp_pred_cleanup(&p2); + ray_graph_free(g0); ray_graph_free(g2); + ray_release(t0); ray_release(t2); + PASS(); +} + +/* An AND stops at the first child that fails the whole window: k == 500 + * (ordered first: an 8-byte EQ) passes in vector 0 only, so v <= 4000 is + * read for that one vector (4 KB). Without the stop v is decoded in every + * window (nullable v takes the typed compare, which the directory gate does + * not decide); k decodes vector 0 only (the gate decides chunks 1-3, the + * descriptors chunk 0's other vectors, Task 17b). */ +static ray_op_t* fpp_k_eq_v(ray_graph_t* g) { + return ray_and(g, ray_eq(g, ray_scan(g, "k"), ray_const_i64(g, 500)), fpp_v_le(g)); +} +static test_result_t test_fp_range_and_stops(void) { + test_result_t r; + if ((r = sr_fp_same(fpp_k_eq_v)).status != TEST_PASS) return r; + TEST_ASSERT_EQ_I(g_fp_pass, 1); + ray_t* t = sr_load(2); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + fp_pred_t p; ray_t* e = NULL; + TEST_ASSERT_EQ_I(fp_compile_pred(g, fpp_k_eq_v(g), t, &p, &e), 0); + TEST_ASSERT_EQ_I(p.n_children, 2); + TEST_ASSERT_TRUE(p.children[0].enc && p.children[0].op == FP_EQ && p.children[0].col_esz == 8); + TEST_ASSERT_TRUE(p.children[1].enc); + ray_enc_counters_reset(); + fp_scratch_t sc; fp_scratch_init(&sc); + uint8_t b[RAY_MORSEL_ELEMS]; + int64_t n = ray_table_nrows(t); + for (int64_t ms = 0; ms < n; ms += RAY_MORSEL_ELEMS) { + int64_t me = ms + RAY_MORSEL_ELEMS < n ? ms + RAY_MORSEL_ELEMS : n; + TEST_ASSERT_NULL(fp_eval_pred_rs(&p, ms, me, b, &sc)); + } + fp_scratch_free(&sc); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.decoded_bytes, 1024 * 8 + 1024 * 4); /* k and v: vector 0 */ + TEST_ASSERT_EQ_U(k.materialized, 0); + fp_pred_cleanup(&p); ray_graph_free(g); ray_release(t); + PASS(); +} + +/* STR children read through the view's pool: typed compares (EQ, LT on + * the bytes; empty cells are null, below every value) and LIKE. 4000 + * rows: four vectors, the last partial. */ +static ray_t* sr_str_tbl(int gen) { + char dir[512], sym[512]; + snprintf(dir, sizeof dir, "%s/str%d", sr_root(), gen); + snprintf(sym, sizeof sym, "%s/str%d.sym", sr_root(), gen); + ray_t* v = ray_vec_new(RAY_STR, 4000); + char buf[64]; + for (int i = 0; i < 4000; i++) { + int n = i % 7 == 0 ? 0 + : i % 3 == 0 ? snprintf(buf, sizeof buf, "s%05d", i) + : snprintf(buf, sizeof buf, "a pooled string of row %05d", i); + v = ray_str_vec_append(v, buf, (size_t)n); + } + if (ray_vec_is_null(v, 0)) v->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("t", 1), v); ray_release(v); + ray_err_t rc = ray_splay_save_mode(t, dir, sym, gen ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF); + ray_release(t); + if (rc != RAY_OK) return NULL; + t = ray_read_splayed(dir, sym); /* mapped: generation 2 stays encoded */ + return (t && !RAY_IS_ERR(t)) ? t : NULL; +} +static ray_op_t* fpp_t_eq(ray_graph_t* g) { + ray_t* lit = ray_str("s00039", 6); /* 39 % 3 == 0, 39 % 7 != 0: a cell */ + ray_op_t* o = ray_eq(g, ray_scan(g, "t"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* fpp_t_lt(ray_graph_t* g) { + ray_t* lit = ray_str("s01000", 6); + ray_op_t* o = ray_lt(g, ray_scan(g, "t"), ray_const_atom(g, lit)); ray_release(lit); return o; +} +static ray_op_t* fpp_t_like(ray_graph_t* g) { + ray_t* pat = ray_str("*row 0*1", 8); + ray_op_t* o = ray_like(g, ray_scan(g, "t"), ray_const_atom(g, pat)); ray_release(pat); return o; +} +static test_result_t test_fp_range_str(void) { + ray_op_t* (*cases[])(ray_graph_t*) = { fpp_t_eq, fpp_t_lt, fpp_t_like }; + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + ray_t* t0 = sr_str_tbl(0); ray_t* t2 = sr_str_tbl(2); + test_result_t r = sr_fp_same_on(t0, t2, cases[i]); + if (t0) ray_release(t0); + if (t2) ray_release(t2); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(g_fp_pass > 0, "case %zu matches no row", i); /* never vacuous */ + } + PASS(); +} + +/* ---- Task 7: top-k and take scans on range reads -------------------- */ + +/* SR_SAME through the fused top-k / take: both generations take it. */ +static test_result_t sr_fused_same(const char* q, uint64_t want_mat) { + ray_fused_topk_counters_reset(); + test_result_t r = sr_same(q, want_mat); + if (r.status != TEST_PASS) return r; + uint64_t ran = 0, declined = 0; + ray_fused_topk_counters(&ran, &declined); + TEST_ASSERT_FMT(ran == 2 && declined == 0, "%s: fused ran %llu, declined %llu", q, + (unsigned long long)ran, (unsigned long long)declined); + PASS(); +} +#define SR_FUSED_SAME(q, m) do { test_result_t r_ = sr_fused_same((q), (m)); if (r_.status != TEST_PASS) return r_; } while (0) + +/* Top-k: results equal generation 0; nothing is materialized: the sort + * keys are read by range into the heaps (fpk_rk_t) and the projected + * columns are gathered by row list (P3 Task 6). */ +static test_result_t test_topk_materializes_keys(void) { + SR_FUSED_SAME("(select {k: k from: T where: (> v 1000) desc: k take: 5})", 0); /* k: key and output */ + SR_FUSED_SAME("(select {g: g k: k from: T where: (> v 1000) asc: [g k] take: 7})", 0); /* two keys */ + SR_FUSED_SAME("(select {f: f from: T where: (== g 3) desc: k take: 3})", 0); /* key k; f gathered */ + SR_FUSED_SAME("(select {k: k from: T where: (< v 50) take: 4})", 0); /* take scan: k gathered */ + SR_FUSED_SAME("(select {k: k from: T where: (< v 50) take: -4})", 0); /* take from the end */ + PASS(); +} + +/* An interrupted top-k or take scan is `cancel`. */ +static test_result_t test_topk_take_cancel(void) { + /* cancel: an interrupted scan is `cancel`, not a partial answer. + * Generation 0: a generation-2 sort key's materialization would answer + * the cancel before the scan runs. */ + ray_t* t = sr_load(0); + TEST_ASSERT_NOT_NULL(t); + ray_t* w = ray_parse("(> v 400000)"); + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w)); + int64_t ks = ray_sym_intern("k", 1); + uint8_t asc = 0; + for (int i = 0; i < 2; i++) { + ray_request_interrupt(); + ray_t* r = i ? ray_fused_topk_select(t, w, &ks, &asc, 1, 5, &ks, NULL, 1) + : ray_fused_take_select(t, w, 4, &ks, NULL, 1); + ray_clear_interrupt(); + TEST_ASSERT_FMT(r && RAY_IS_ERR(r), "%s: not an error", i ? "top-k" : "take"); + TEST_ASSERT_STR_EQ(ray_err_code(r), "cancel"); + ray_error_free(r); + } + ray_release(w); ray_release(t); + PASS(); +} + +/* `in` / `not-in` selections (exec_in_to_selection) range-read a + * generation-2 column: the same selection as generation 0, nothing + * materialized, for an integer set, a nullable column under not-in, an F64 + * column and a file-domain SYM set with a literal absent from the domain. */ +static ray_op_t* fpp_v_notin(ray_graph_t* g) { + /* v = 3*row - 7: 293 and 2993 would be rows 100 and 1000, both null + * (row % 10 == 0), so this set matches no row; not-in keeps every + * non-null row (the SIMD small-set path) */ + ray_t* set = sr_i64_set(293, 2993); + ray_op_t* o = ray_not_in(g, ray_scan(g, "v"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* fpp_v_notin_big(ray_graph_t* g) { + /* ten needles (the hashed path, past IN_SIMD_SET): rows 1-9 are + * non-null members, 293 is a null row's would-be value; not-in must + * still drop every null row */ + ray_t* set = ray_vec_new(RAY_I64, 10); set->len = 10; + for (int j = 0; j < 9; j++) ((int64_t*)ray_data(set))[j] = 3 * (j + 1) - 7; + ((int64_t*)ray_data(set))[9] = 293; + ray_op_t* o = ray_not_in(g, ray_scan(g, "v"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* fpp_f_notin(ray_graph_t* g) { + ray_t* set = ray_vec_new(RAY_F64, 2); set->len = 2; /* f = row, null every 13th */ + ((double*)ray_data(set))[0] = 12.0; ((double*)ray_data(set))[1] = 26.0; /* 26 is a null row */ + ray_op_t* o = ray_not_in(g, ray_scan(g, "f"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* fpp_w_in(ray_graph_t* g) { /* W16 SYM: 300 distinct */ + ray_t* set = ray_vec_new(RAY_SYM, 3); set->len = 3; + ((int64_t*)ray_data(set))[0] = ray_sym_intern("7", 1); + ((int64_t*)ray_data(set))[1] = ray_sym_intern("299", 3); + ((int64_t*)ray_data(set))[2] = ray_sym_intern("nope", 4); + ray_op_t* o = ray_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* fpp_f_in(ray_graph_t* g) { + ray_t* set = ray_vec_new(RAY_F64, 3); set->len = 3; + ((double*)ray_data(set))[0] = 12.0; ((double*)ray_data(set))[1] = 13.0; ((double*)ray_data(set))[2] = 150001.0; + ray_op_t* o = ray_in(g, ray_scan(g, "f"), ray_const_vec(g, set)); ray_release(set); return o; +} +static ray_op_t* fpp_s_in(ray_graph_t* g) { + ray_t* set = ray_vec_new(RAY_SYM, 3); set->len = 3; + ((int64_t*)ray_data(set))[0] = ray_sym_intern("e", 1); + ((int64_t*)ray_data(set))[1] = ray_sym_intern("zzq", 3); /* absent from the file domain */ + ((int64_t*)ray_data(set))[2] = ray_sym_intern("b", 1); + ray_op_t* o = ray_in(g, ray_scan(g, "s"), ray_const_vec(g, set)); ray_release(set); return o; +} +static test_result_t test_in_selection(void) { + test_result_t r; + if ((r = sr_sel_same(fpp_g_in)).status != TEST_PASS) return r; /* (in g [2 5]) */ + if ((r = sr_sel_same(fpp_v_notin)).status != TEST_PASS) return r; + if ((r = sr_sel_same(fpp_v_notin_big)).status != TEST_PASS) return r; + if ((r = sr_sel_same(fpp_f_in)).status != TEST_PASS) return r; + if ((r = sr_sel_same(fpp_f_notin)).status != TEST_PASS) return r; + if ((r = sr_sel_same(fpp_s_in)).status != TEST_PASS) return r; + /* a SYM column of 300 distinct ids is W16: the view's width class */ + sr_eval_ok("(set W (table [s k] (list (as 'SYM (as 'STR (% (til 70000) 300))) (til 70000))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w0/\" W {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w2/\" W {compress: true})"); + static const char* const wdirs[2] = { SR_TMP "/w0/", SR_TMP "/w2/" }; + if ((r = sr_sel_same_at(wdirs, fpp_w_in)).status != TEST_PASS) return r; + SR_SAME("(count (select {from: T where: (in s ['a 'e])}))", 0); + SR_SAME("(count (select {from: T where: (not-in g [0 1 2])}))", 0); + /* the OP_FILTER IN consult (Task 5) then the fused selection: nothing decoded */ + int64_t want = 0; + for (int64_t i = 0; i < 200000; i++) want += (i % 7 == 2 || i % 7 == 5); + for (int gen = 0; gen < 2; gen++) { + ray_t* t = sr_load(gen); + uint64_t mat = 9; + TEST_ASSERT_EQ_I(sr_filter_rows(t, fpp_g_in, &mat), want); + if (gen) TEST_ASSERT_EQ_U(mat, 0); + ray_release(t); + } + PASS(); +} + +/* A generation-2 column already materialized elsewhere is read in place + * by the `in` selection: nothing decoded again. */ +static test_result_t test_in_selection_reuses_materialized(void) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", SR_G2); + ray_t* s = sr_eval("(at T 'g)"); /* forced at the top: materializes g */ + TEST_ASSERT_TRUE(s && !RAY_IS_ERR(s)); + ray_release(s); + ray_t* t = sr_eval("T"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_NOT_NULL(ray_enccol_decoded_peek(ray_table_get_col_enc(t, ray_sym_intern("g", 1)))); + ray_enc_counters_reset(); + ray_graph_t* g = ray_graph_new(t); + bool all = false; + ray_t* sel = exec_pred_to_selection(g, fpp_g_in(g), ray_table_nrows(t), &all); + TEST_ASSERT_TRUE(sel && !RAY_IS_ERR(sel)); + TEST_ASSERT_EQ_I(ray_rowsel_meta(sel)->total_pass, 57143); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + ray_rowsel_release(sel); + ray_graph_free(g); ray_release(t); + PASS(); +} + +/* An interrupted `in` selection is `cancel`, not a partial answer. */ +static test_result_t test_in_selection_cancel(void) { + for (int gen = 0; gen < 2; gen++) { + ray_t* t = sr_load(gen); + TEST_ASSERT_NOT_NULL(t); + ray_graph_t* g = ray_graph_new(t); + ray_op_t* pred = fpp_g_in(g); + bool all = false; + ray_request_interrupt(); + ray_t* s = exec_pred_to_selection(g, pred, ray_table_nrows(t), &all); + ray_clear_interrupt(); + TEST_ASSERT_FMT(s && RAY_IS_ERR(s), "gen %d: not an error", gen); + TEST_ASSERT_STR_EQ(ray_err_code(s), "cancel"); + ray_error_free(s); + ray_graph_free(g); ray_release(t); + } + PASS(); +} + +/* ---- Task 9: reductions over a scan; (at tbl 'col) on an encoded slot ---- */ + +static test_result_t test_reduce_scan(void) { + SR_SAME("(sum (at T 'k))", 0); + SR_SAME("(avg (at T 'v))", 0); + SR_SAME("(min (at T 'd))", 0); + SR_SAME("(max (at T 'f))", 0); + SR_SAME("(sum (at T 'u))", 0); + SR_SAME("(first (at T 'v))", 0); + SR_SAME("(last (at T 'f))", 0); + /* stddev is not lazy-aware (it materializes its argument and computes + * in two passes, unlike the one-pass OP_STDDEV): the column is read */ + SR_SAME("(stddev (at T 'g))", 1); + SR_SAME("(sum (at T 'f))", 0); /* nullable F64 over 200000 rows (integral values: exact in any order) */ + SR_SAME("(stddev (at T 'f))", 1); + SR_SAME("(count (at T 'v))", 0); /* count over the lazy: no force */ + SR_SAME("(at T 'k)", 1); /* a value handed to the user is a plain column */ + PASS(); +} + +/* Every served op and type over the lazy, and the shapes that keep reading + * the column: same answers as generation 0. */ +static test_result_t test_reduce_scan_ops(void) { + static const char* const q0[] = { + "(last (at T 'v))", "(first (at T 'f))", "(first (at T 'd))", "(last (at T 'd))", + "(first (at T 'g))", "(last (at T 'b))", "(first (at T 'u))", "(first (at T 'k))", + "(last (at T 'k))", "(min (at T 'b))", "(max (at T 'g))", "(min (at T 'v))", + "(max (at T 'v))", "(min (at T 'f))", "(min (at T 'k))", "(max (at T 'h))", + "(prod (at T 'b))", "(prod (at T 'g))", "(prod (at T 'f))", "(all (at T 'b))", + "(any (at T 'b))", "(all (at T 'u))", "(any (at T 'v))", "(all (at T 'f))", + "(avg (at T 'f))", "(avg (at T 'd))", "(avg (at T 'b))", "(sum (at T 'b))", + "(sum (at T 'g))", "(sum (at T 'h))", "(avg (at T 'h))", "(count (at T 's))", + "(count (at T 'd))", "(sum (at T 'e))", "(avg (at T 'e))", "(min (at T 'e))", "(max (at T 'e))", + "(first (at T 'e))", "(last (at T 'e))", "(prod (at T 'e))", "(any (at T 'e))", NULL }; + for (int i = 0; q0[i]; i++) SR_SAME(q0[i], 0); + /* F32: the answers' types are the vector builtins' (F64 for every one) */ + static const char* const qf[] = { "(sum (at T 'e))", "(avg (at T 'e))", "(min (at T 'e))", "(max (at T 'e))", + "(first (at T 'e))", "(last (at T 'e))", NULL }; + for (int i = 0; qf[i]; i++) { + int8_t ty[2]; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_G2 : SR_G0); + ray_t* r = sr_eval(qf[i]); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ty[gen] = r->type; + sr_drop(r); + } + TEST_ASSERT_FMT(ty[0] == ty[1] && ty[0] == -RAY_F64, "%s: types %d / %d", qf[i], ty[0], ty[1]); + } + /* a reduction after a selection reads the selected rows, not the column */ + SR_SAME("(select {s: (sum v) m: (min f) from: T where: (> k 150000)})", 0); /* the scalar route on range reads (Task 10; was 2) */ + /* not served by the range reduction: the column is materialized once */ + SR_SAME("(min (at T 's))", 1); + SR_SAME("(count (distinct (at T 'g)))", 1); + SR_SAME("(sum (reverse (at T 'k)))", 1); + SR_SAME("(first (asc (at T 'v)))", 1); + SR_SAME("(at T ['k 'v])", 2); /* a list of plain columns, never of lazies */ + SR_SAME("(sum (+ 1 (at T 'k)))", 1); + SR_SAME("(get T 'g)", 1); + /* a column reference promoted to its scan by the other lazy-aware ops */ + SR_SAME("(count (distinct (at T 's)))", 1); + SR_SAME("(first (upper (at T 's)))", 1); + SR_SAME("(last (msum 3 (at T 'k)))", 1); + SR_SAME("(sum ((fn [t] (at t 'k)) T))", 0); /* returned from a lambda, still a reference */ + SR_SAME("(sum (at T 'k))", 0); + SR_SAME("(do (set c (at T 'v)) (+ (sum c) (count c)))", 1); /* a bound value is forced */ + PASS(); +} + +/* A builtin that rejects the column's type rejects the lazy with the + * message it gives the column. */ +static test_result_t test_reduce_scan_type_errors(void) { + static const char* const q[] = { "(sum (at T 'd))", "(sum (at T 's))", "(avg (at T 's))", + "(prod (at T 'd))", "(all (at T 'd))", "(any (at T 's))", NULL }; + for (int i = 0; q[i]; i++) { + char msg[2][256]; const char* code[2]; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_G2 : SR_G0); + ray_error_clear(); + ray_enc_counters_reset(); + ray_t* r = sr_eval(q[i]); + TEST_ASSERT_FMT(r && RAY_IS_ERR(r), "gen %d: %s: not an error", gen, q[i]); + code[gen] = ray_err_code(r); + snprintf(msg[gen], sizeof msg[gen], "%s", ray_error_msg()); + ray_error_free(r); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (gen) TEST_ASSERT_FMT(k.materialized == 0, "%s materialized", q[i]); + } + TEST_ASSERT_STR_EQ(code[0], code[1]); + TEST_ASSERT_FMT(strcmp(msg[0], msg[1]) == 0, "%s: '%s' vs '%s'", q[i], msg[0], msg[1]); + } + PASS(); +} + +/* All-null columns, wide integer sums (the low word wraps, avg reads the + * exact 128-bit total) and an empty table. */ +static test_result_t test_reduce_scan_edges(void) { + sr_eval_ok("(set i (til 70000))"); + sr_eval_ok("(set E (table [n x z w] (list (as 'I32 (take [0N] 70000)) (as 'F64 (take [0N] 70000)) " + "(* i 131762457669) (- 0 (* i 131762457669)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/e0/\" E {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/e2/\" E {compress: true})"); + static const char* const q[] = { + "(sum (at T 'n))", "(avg (at T 'n))", "(min (at T 'n))", "(max (at T 'n))", "(first (at T 'n))", + "(last (at T 'n))", "(prod (at T 'n))", "(all (at T 'n))", "(any (at T 'n))", "(count (at T 'n))", + "(sum (at T 'x))", "(avg (at T 'x))", "(min (at T 'x))", "(max (at T 'x))", "(first (at T 'x))", + "(last (at T 'x))", "(sum (at T 'z))", "(avg (at T 'z))", "(min (at T 'z))", "(max (at T 'z))", + "(sum (at T 'w))", "(avg (at T 'w))", "(min (at T 'w))", "(prod (at T 'z))", NULL }; + for (int i = 0; q[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/e0/\")", "(.db.splayed.get \"" SR_TMP "/e2/\")", q[i], 0); + if (r.status != TEST_PASS) return r; + } + /* the last non-null value is the first row of the last 1024-row view, + * nulls after it */ + sr_eval_ok("(set L (table [l lf] (list (map (fn [j] (if (> j 69632) 0N j)) i) " + "(as 'F64 (map (fn [j] (if (> j 69632) 0N j)) i)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/l0/\" L {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/l2/\" L {compress: true})"); + static const char* const ql[] = { "(last (at T 'l))", "(last (at T 'lf))", "(first (at T 'l))", NULL }; + for (int i = 0; ql[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/l0/\")", "(.db.splayed.get \"" SR_TMP "/l2/\")", ql[i], 0); + if (r.status != TEST_PASS) return r; + } + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/z0e/\" (take E 0) {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/z2e/\" (take E 0) {compress: true})"); + static const char* const qe[] = { "(sum (at T 'z))", "(avg (at T 'n))", "(min (at T 'x))", "(max (at T 'z))", + "(first (at T 'n))", "(last (at T 'x))", "(count (at T 'z))", NULL }; + for (int i = 0; qe[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/z0e/\")", "(.db.splayed.get \"" SR_TMP "/z2e/\")", qe[i], 0); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Finding C3: whole-column sum / avg / min / max of a CHUNK_ZONE column are + * answered from the directory (generation 0 answers them from its zone): + * nothing decoded at all. */ +static test_result_t test_reduce_dir_answers(void) { + static const char* const q[] = { "(sum (at T 'k))", "(avg (at T 'v))", "(min (at T 'd))", + "(max (at T 'u))", "(avg (at T 'k))", "(sum (at T 'g))", + "(min (at T 'f))", "(max (at T 'f))", "(min (at T 'b))", + "(max (at T 'v))", "(count (at T 'k))", NULL }; + for (int i = 0; q[i]; i++) { + SR_SAME(q[i], 0); + sr_eval_ok("(set T (.db.splayed.get \"" SR_G0 "\"))"); + ray_t* r0 = sr_eval(q[i]); + TEST_ASSERT_TRUE(r0 && !RAY_IS_ERR(r0)); + ray_t* f0 = ray_fmt(r0, 0); + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + /* twice on the same load: the second reads the cached directory totals */ + for (int rep = 0; rep < 2; rep++) { + ray_enc_counters_reset(); + ray_t* r = sr_eval(q[i]); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.decoded_bytes == 0, "%s decoded %llu bytes", q[i], (unsigned long long)k.decoded_bytes); + ray_t* f2 = ray_fmt(r, 0); + TEST_ASSERT_FMT(ray_str_len(f0) == ray_str_len(f2) && memcmp(ray_str_ptr(f0), ray_str_ptr(f2), ray_str_len(f0)) == 0, + "%s run %d: %.*s vs %.*s", q[i], rep, (int)ray_str_len(f0), ray_str_ptr(f0), (int)ray_str_len(f2), ray_str_ptr(f2)); + ray_release(f2); + sr_drop(r); + } + ray_release(f0); sr_drop(r0); + } + /* no directory answer: read by range, nothing materialized */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + ray_t* r = sr_eval("(sum (at T 'f))"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 200000 * 8); + sr_drop(r); + PASS(); +} + +/* Ruling Q1: a RAW float vector without nulls is read in place (nothing + * decoded). */ +static test_result_t test_raw_float_view(void) { + sr_eval_ok("(set i (til 140000))"); + sr_bind_f32("yf", 140000, 0, 0.25f); + sr_eval_ok("(set R (table [x y] (list (as 'F64 (% i 1000)) yf)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/r0/\" R {compress: false})"); + /* P5: the RAW float view is this test's subject */ + ray_encw_test_force_float(RAY_ENC_RAW); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/r2/\" R {compress: true})"); + ray_encw_test_force_float(-1); + static const char* const q[] = { "(sum (at T 'x))", "(sum (at T 'y))", "(avg (at T 'y))", "(prod (at T 'x))", + "(any (at T 'y))", "(first (at T 'x))", "(last (at T 'y))", NULL }; + for (int i = 0; q[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/r0/\")", "(.db.splayed.get \"" SR_TMP "/r2/\")", q[i], 0); + if (r.status != TEST_PASS) return r; + } + sr_eval_ok("(set T (.db.splayed.get \"" SR_TMP "/r2/\"))"); + for (int rep = 0; rep < 2; rep++) { + ray_enc_counters_reset(); + ray_t* r = sr_eval("(sum (at T 'x))"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + sr_drop(r); + } + PASS(); +} + +/* Finding I11: (at P 'v) on a parted generation-2 table forces to the value + * generation 0's parted_to_flat_vec gives; sum over it reduces by range. */ +static test_result_t test_at_parted_value(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/ap%d/2024.01.0%d/t/\" " + "(table [v] (list (as 'I32 (map (fn [j] (if (== 0 (%% j 11)) 0N j)) (til 70000))))) {compress: %s})", + gen, p + 1, gen ? "true" : "false"); + ray_t* a = sr_eval("(at (.db.parted.get \"" SR_TMP "/ap0\" 't) 'v)"); + ray_enc_counters_reset(); + ray_t* s2 = sr_eval("(sum (at (.db.parted.get \"" SR_TMP "/ap2\" 't) 'v))"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_t* s0 = sr_eval("(sum (at (.db.parted.get \"" SR_TMP "/ap0\" 't) 'v))"); + ray_t* b = sr_eval("(at (.db.parted.get \"" SR_TMP "/ap2\" 't) 'v)"); + TEST_ASSERT_TRUE(sr_vec_eq(a, b)); /* type, length, HAS_NULLS, payload */ + TEST_ASSERT_TRUE(s0 && s2 && !RAY_IS_ERR(s0) && !RAY_IS_ERR(s2) && s0->i64 == s2->i64); + sr_drop(a); sr_drop(b); sr_drop(s0); sr_drop(s2); + static const char* const q[] = { "(first (at T 'v))", "(last (at T 'v))", "(min (at T 'v))", "(max (at T 'v))", + "(avg (at T 'v))", "(count (at T 'v))", "(prod (at T 'v))", "(any (at T 'v))", NULL }; + for (int i = 0; q[i]; i++) { + test_result_t r = sr_same_on("(.db.parted.get \"" SR_TMP "/ap0\" 't)", "(.db.parted.get \"" SR_TMP "/ap2\" 't)", q[i], 0); + if (r.status != TEST_PASS) return r; + } + /* ruling I5: a ragged generation-0 table's synthetic null segment reads + * by range and answers as its explicit-null reference */ + sr_parted_xy(SR_TMP "/arg", 0, true, false); + sr_parted_xy(SR_TMP "/aref", 0, false, true); + sr_parted_xy(SR_TMP "/amx", 3, true, false); + static const char* const qr[] = { "(sum (at T 'y))", "(avg (at T 'y))", "(min (at T 'y))", "(max (at T 'y))", + "(first (at T 'y))", "(last (at T 'y))", "(count (at T 'y))", NULL }; + for (int i = 0; qr[i]; i++) { + test_result_t r = sr_same_on("(.db.parted.get \"" SR_TMP "/aref\" 't)", "(.db.parted.get \"" SR_TMP "/arg\" 't)", qr[i], 0); + if (r.status != TEST_PASS) return r; + r = sr_same_on("(.db.parted.get \"" SR_TMP "/aref\" 't)", "(.db.parted.get \"" SR_TMP "/amx\" 't)", qr[i], 0); + if (r.status != TEST_PASS) return r; + } + ray_t* fa = sr_eval("(at (.db.parted.get \"" SR_TMP "/aref\" 't) 'y)"); + ray_t* fb = sr_eval("(at (.db.parted.get \"" SR_TMP "/arg\" 't) 'y)"); + ray_t* fc = sr_eval("(at (.db.parted.get \"" SR_TMP "/amx\" 't) 'y)"); + TEST_ASSERT_TRUE(sr_vec_eq(fa, fb)); + TEST_ASSERT_TRUE(sr_vec_eq(fa, fc)); + sr_drop(fa); sr_drop(fb); sr_drop(fc); + PASS(); +} + +/* ---- Task 10: the scalar aggregate route (a select of aggregates, no by:) ---- */ +static test_result_t test_scalar_route(void) { + SR_SAME("(select {s: (sum v) c: (count k) from: T})", 0); + SR_SAME("(select {s: (sum v) c: (count k) a: (avg f) from: T where: (> g 2)})", 0); + SR_SAME("(select {mn: (min d) mx: (max k) from: T where: (== b true)})", 0); + SR_SAME("(select {s: (sum k) from: T where: (< k 70000)})", 0); /* under a selection: the generic loop */ + SR_SAME("(select {s: (sum (+ k 5)) from: T})", 0); /* affine plan */ + SR_SAME("(select {s: (sum (+ k g)) a: (avg (+ k g)) from: T})", 0); /* linear: declined, fused expr */ + SR_SAME("(select {s: (sum (* f g)) from: T where: (> k 10)})", 0); /* prod: declined, fused expr */ + SR_SAME("(select {l: (avg (strlen s)) from: T where: (> g 0)})", 0); /* SYM strlen */ + SR_SAME("(select {s: (sum k) a: (avg k) from: T})", 0); /* one-base shortcut */ + /* finding C3: the one-base shortcut answers from the directory */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + ray_t* r = sr_eval("(select {s: (sum k) a: (avg k) from: T})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + TEST_ASSERT_EQ_U(kc.decoded_bytes, 0); + sr_drop(r); + PASS(); +} + +#include "ops/agg_engine.h" /* agg_route_stats: the route hook */ + +/* The scalar route's staged shapes beyond the brief's lines. */ +static test_result_t test_scalar_route_shapes(void) { + /* finding C3 with the shortcut itself: two affine bases over one column */ + SR_SAME("(select {s: (sum (+ k 5)) a: (avg (+ k 5)) from: T})", 0); + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + ray_t* r = sr_eval("(select {s: (sum (+ k 5)) a: (avg (+ k 5)) from: T})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + TEST_ASSERT_EQ_U(kc.decoded_bytes, 0); + sr_drop(r); + /* finding C3 at planning: a select of whole-column aggregates answers + * from the directory where generation 0 answers from its CHUNK_ZONE */ + static const char* const qm = "(select {s: (sum v) c: (count k) a: (avg g) mn: (min d) mx: (max k) from: T})"; + SR_SAME(qm, 0); + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + r = sr_eval(qm); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_enc_counters_get(&kc); + TEST_ASSERT_EQ_U(kc.decoded_bytes, 0); + sr_drop(r); + /* a nullable column's avg / min / max at planning */ + static const char* const qn = "(select {a: (avg v) mn: (min v) mx: (max v) c: (count v) from: T})"; + SR_SAME(qn, 0); + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + r = sr_eval(qn); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_enc_counters_get(&kc); + TEST_ASSERT_EQ_U(kc.decoded_bytes, 0); + sr_drop(r); + /* float extremes are not answered there (the zone declines them) */ + SR_SAME("(select {mn: (min f) mx: (max e) from: T})", 0); + /* SYM extremes in the domain's order (never by raw ids), widths per piece */ + SR_SAME("(select {mn: (min s) mx: (max s) fs: (first s) ls: (last s) from: T where: (> g 0)})", 0); + /* serial FIRST / LAST, PROD, the second moments, BOOL / U8 inputs */ + SR_SAME("(select {f: (first v) l: (last f) p: (prod g) from: T where: (> k 199990)})", 0); + SR_SAME("(select {vr: (var g) sd: (stddev v) al: (all b) an: (any u) from: T where: (> g 0)})", 0); + SR_SAME("(select {mn: (min e) mx: (max e) s: (sum e) from: T where: (> g 3)})", 0); /* F32 */ + SR_SAME("(select {mn: (min d) mx: (max d) a: (avg d) from: T where: (> g 3)})", 0); /* DATE */ + /* a holistic input reads its plain column (R-RANDOM): only k */ + SR_SAME("(select {m: (med k) s: (sum v) from: T where: (> g 0)})", 1); + PASS(); +} + +/* The tight F64 kernel sums by explicit lanes (row mod 8, combined in one + * fixed order) on both generations: a serial run (fewer rows than the + * parallel threshold: one task, a deterministic order) over non-integral + * values (whose sum depends on the order: a plain row-order sum differs) + * gives generation 0's bits from zero-copy pieces, and exactly the lane + * reference computed here. The kernel pins its lanes on every target a + * GCC-compatible compiler builds (group.c, SC_F64_PIN), so this holds + * under the release build's -fassociative-math too. */ +static test_result_t test_scalar_route_f64_bits(void) { + const int64_t n = 60000; + sr_eval_ok("(set i (til 60000))"); + sr_eval_ok("(set R (table [x] (list (* (as 'F64 (% (* i 7919) 1000003)) 0.37))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sf0/\" R {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sf2/\" R {compress: true})"); + volatile double lane[8] = { 0 }; + for (int64_t r = 0; r < n; r++) lane[r & 7] += (double)((r * 7919) % 1000003) * 0.37; + volatile double ab = (lane[0] + lane[1]), cd = (lane[2] + lane[3]); + volatile double ef = (lane[4] + lane[5]), gh = (lane[6] + lane[7]); + volatile double lo = ab + cd, hi = ef + gh; + double ref = lo + hi; + static const char* const q[] = { "(select {s: (sum x) from: T})", + "(select {s: (sum (+ x 0.5)) from: T})", + "(select {a: (avg (+ x 0.25)) from: T})", NULL }; + for (int i = 0; q[i]; i++) { + double v[2]; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_TMP "/sf2/" : SR_TMP "/sf0/"); + ray_enc_counters_reset(); + char buf[256]; + snprintf(buf, sizeof buf, "(first (first (value %s)))", q[i]); + ray_t* r = sr_eval(buf); + TEST_ASSERT_FMT(r && !RAY_IS_ERR(r) && r->type == -RAY_F64, "%s: gen %d", q[i], gen); + v[gen] = r->f64; + sr_drop(r); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (gen) TEST_ASSERT_EQ_U(k.materialized, 0); + } + TEST_ASSERT_FMT(memcmp(&v[0], &v[1], sizeof v[0]) == 0, "%s: %.17g vs %.17g", q[i], v[0], v[1]); + if (i == 0) TEST_ASSERT_FMT(memcmp(&v[0], &ref, sizeof ref) == 0, "lanes: %.17g vs reference %.17g", v[0], ref); + } + PASS(); +} + +/* Fix round 2: the lanes' combine order is the fixed tree, never a fold: + * x[0] = 2^53 and x[1..7] = 1.0 (every other row 0) sum to exactly + * 2^53 + 6 (lane 0's 2^53 + 1 rounds to 2^53, the other pairs are exact); + * a left fold gives 2^53. Both generations, serially. */ +static test_result_t test_scalar_route_f64_combine(void) { + const int64_t n = 60000; + ray_t* xv = ray_vec_new(RAY_F64, n); xv->len = n; + double* x = (double*)ray_data(xv); + for (int64_t r = 0; r < n; r++) x[r] = r == 0 ? 9007199254740992.0 : r < 8 ? 1.0 : 0.0; + ray_env_set(ray_sym_intern("cxv", 3), xv); ray_release(xv); + sr_eval_ok("(set CX (table [x] (list cxv)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/cx0/\" CX {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/cx2/\" CX {compress: true})"); + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_TMP "/cx2/" : SR_TMP "/cx0/"); + ray_t* r = sr_eval("(first (first (value (select {s: (sum x) from: T}))))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == -RAY_F64); + TEST_ASSERT_FMT(r->f64 == 9007199254740998.0, "gen %d: %.17g", gen, r->f64); + sr_drop(r); + } + PASS(); +} + +/* Fix round 2: a piece starting at a row not a multiple of 8 realigns + * through the head loop; the cut sum equals the whole block's and the lane + * reference, on lane-weighted data where any lane mix-up changes the bits. + * (The engine's tasks and pieces start 1024-aligned: the hook drives the + * staged piece function directly.) */ +static test_result_t test_scalar_route_f64_unaligned(void) { + const int64_t n = 5000; + static const double m[8] = { -11, 11, -1, 1, 11, 1, -13, 1 }; + static double d[5000]; + static const int64_t row0s[] = { 0, 3, 1021 }; + static const int64_t cuts[] = { 5, 13, 1000, 1027, 2049, 4099 }; + for (size_t k = 0; k < sizeof row0s / sizeof row0s[0]; k++) { + int64_t row0 = row0s[k]; + volatile double lane[8] = { 0 }; + for (int64_t r = 0; r < n; r++) { + d[r] = 0.37 * (double)(((r + row0) * 7919) % 1000003) * m[(r + row0) & 7]; + lane[(r + row0) & 7] += d[r]; + } + volatile double ab = lane[0] + lane[1], cd = lane[2] + lane[3]; + volatile double ef = lane[4] + lane[5], gh = lane[6] + lane[7]; + volatile double lo = ab + cd, hi = ef + gh; + double ref = lo + hi, whole, cut; + ray_group_test_f64_lanes(d, row0, n, cuts, (int)(sizeof cuts / sizeof cuts[0]), &whole, &cut); + TEST_ASSERT_FMT(memcmp(&whole, &ref, sizeof ref) == 0, "row0 %lld: whole %.17g vs ref %.17g", + (long long)row0, whole, ref); + TEST_ASSERT_FMT(memcmp(&cut, &ref, sizeof ref) == 0, "row0 %lld: cut %.17g vs ref %.17g", + (long long)row0, cut, ref); + } + PASS(); +} + +/* The route hook: 1 takes the legacy ladder instead of the v2 engine; the + * answers are the same; ray_test_hooks_off disarms it. */ +static test_result_t test_group_route_hook(void) { + sr_eval_ok("(set T (.db.splayed.get \"" SR_G0 "\"))"); + const char* q = "(select {s: (sum v) c: (count k) from: T by: g})"; + ray_t* out[4]; + agg_route_stats_t st[4]; + for (int route = 0; route < 4; route++) { + ray_group_test_route(route); + agg_route_reset(); + out[route] = sr_eval(q); + st[route] = agg_route_stats(); + TEST_ASSERT_TRUE(out[route] && !RAY_IS_ERR(out[route])); + } + ray_test_hooks_off(); + TEST_ASSERT_EQ_U(st[0].routes[AGG_ROUTE_LEGACY], 0); + for (int route = 1; route < 4; route++) { + TEST_ASSERT_TRUE(st[route].routes[AGG_ROUTE_LEGACY] > 0); + ray_t* fa = ray_fmt(out[0], 0); ray_t* fb = ray_fmt(out[route], 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && + memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + ray_release(fa); ray_release(fb); + } + agg_route_reset(); + ray_t* r = sr_eval(q); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_U(agg_route_stats().routes[AGG_ROUTE_LEGACY], 0); /* disarmed */ + sr_drop(r); + for (int route = 0; route < 4; route++) sr_drop(out[route]); + /* 2 skips the direct array: over generation 2 both the direct array + * and the legacy radix route read by range (no materialization) */ + uint64_t mat[3]; + for (int route = 1; route <= 2; route++) { + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_group_test_route(route); + ray_enc_counters_reset(); + r = sr_eval(q); + ray_enc_counters_t k; ray_enc_counters_get(&k); + ray_group_test_route(0); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + sr_drop(r); + mat[route] = k.materialized; + } + TEST_ASSERT_EQ_U(mat[1], 0); + TEST_ASSERT_EQ_U(mat[2], 0); + /* 3 skips the slice-group route: the armed hint folds into a selection */ + sr_eval_ok("(set KS (as 'SYM (at ['aa 'bb 'cc 'dd 'ee 'ff 'gg 'hh] (% (til 4000) 8))))"); + sr_eval_ok("(set TI (table [s f] (list (.attr.set 'grouped KS) (as 'F64 (% (til 4000) 64)))))"); + const char* qs = "(select {sv: (sum f) from: TI by: s asc: s where: (in s ['aa 'cc])})"; + ray_t* so[2]; + uint64_t sl[2]; + for (int i = 0; i < 2; i++) { + ray_group_test_route(i ? 3 : 0); + agg_route_reset(); + so[i] = sr_eval(qs); + sl[i] = agg_route_stats().routes[AGG_ROUTE_SLICES]; + ray_group_test_route(0); + TEST_ASSERT_TRUE(so[i] && !RAY_IS_ERR(so[i]) && ray_table_nrows(so[i]) == 2); + } + TEST_ASSERT_TRUE(sl[0] > 0); + TEST_ASSERT_EQ_U(sl[1], 0); + ray_t* fa = ray_fmt(so[0], 0); ray_t* fb = ray_fmt(so[1], 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && + memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + ray_release(fa); ray_release(fb); sr_drop(so[0]); sr_drop(so[1]); + PASS(); +} + +/* Fix round 1 (I1): a SYM input wider than W8 (3000 symbols: W16) is read + * at each piece's width, with and without a selection; an encoded STR + * strlen input is declined to the plain path (it materializes). */ +static test_result_t test_scalar_route_wide_sym(void) { + const int64_t n = 200000; + ray_t* sv = ray_sym_vec_new(RAY_SYM_W64, n); sv->len = n; + ray_t* tv = ray_vec_new(RAY_STR, n); tv->len = 0; + for (int64_t i = 0; i < n; i++) { + char b[24]; int nb = snprintf(b, sizeof b, "sym%lld", (long long)((i * 7) % 3000)); + ((int64_t*)ray_data(sv))[i] = ray_sym_intern(b, (size_t)nb); + tv = ray_str_vec_append(tv, b, (size_t)nb); + } + ray_env_set(ray_sym_intern("wsv", 3), sv); ray_release(sv); + ray_env_set(ray_sym_intern("wtv", 3), tv); ray_release(tv); + sr_eval_ok("(set WS (table [s t g] (list wsv wtv (as 'I16 (% (til 200000) 7)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/ws0/\" WS {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/ws2/\" WS {compress: true})"); + const char* t0 = "(.db.splayed.get \"" SR_TMP "/ws0/\")"; + const char* t2 = "(.db.splayed.get \"" SR_TMP "/ws2/\")"; + sr_evalf_ok("(set T %s)", t2); + ray_t* T = sr_eval("T"); + ray_col_meta_t m; + TEST_ASSERT_TRUE(T && ray_table_col_meta(T, ray_sym_intern("s", 1), &m) && m.enc && + (m.attrs & RAY_SYM_W_MASK) == RAY_SYM_W16); + sr_drop(T); + static const struct { const char* q; uint64_t mat; } qs[] = { + { "(select {mn: (min s) mx: (max s) l: (sum (strlen s)) from: T})", 0 }, + { "(select {mn: (min s) mx: (max s) l: (avg (strlen s)) f: (first s) from: T where: (> g 2)})", 0 }, + { "(select {l: (sum (strlen s)) from: T where: (> g 0)})", 0 }, + { "(select {l: (sum (strlen t)) c: (count g) from: T where: (> g 2)})", 1 }, /* STR: declined, t materializes */ + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + test_result_t r = sr_same_on(t0, t2, qs[i].q, qs[i].mat); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Fix round 1 (I2): plain inputs bound beside staged ones in one context: + * an expression input, and a column an earlier query materialized. */ +static test_result_t test_scalar_route_mixed(void) { + SR_SAME("(select {s: (sum (+ k g)) m: (max v) from: T where: (> g 0)})", 0); + SR_SAME("(select {s: (sum (* f g)) m: (min d) a: (avg v) from: T where: (> k 10)})", 0); + SR_SAME("(select {s: (sum (+ k g)) a: (avg (* f 2.0)) l: (last v) from: T})", 0); + /* k materialized before the query: read in place beside staged v */ + sr_eval_ok("(set T2M (.db.splayed.get \"" SR_G2 "\"))"); + ray_t* t = sr_eval("T2M"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* kcol = ray_table_col(t, ray_sym_intern("k", 1)); + TEST_ASSERT_TRUE(kcol && !RAY_IS_ERR(kcol)); + sr_drop(t); + static const char* const q[] = { /* not sum / avg of k: a ready bare k would be a linear plan */ + "(select {mx: (max k) s: (sum v) a: (avg g) from: T where: (> g 0)})", + "(select {mn: (min k) l: (last k) m: (max v) from: T where: (> g 2)})", + NULL }; + for (int i = 0; q[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_G0 "\")", "T2M", q[i], 0); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* ---- Task 11: the direct-array group route and its key prescan ---- */ +static test_result_t test_da_route(void) { + ray_group_test_route(1); /* skip v2: the legacy ladder chooses DA for a small key range */ + SR_SAME("(select {s: (sum v) c: (count k) from: T by: g})", 0); + SR_SAME("(select {s: (sum f) mx: (max d) from: T where: (> k 1000) by: g})", 0); + SR_SAME("(select {c: (count k) a: (avg v) from: T by: {g: g b: b}})", 0); /* composite gid */ + SR_SAME("(select {c: (count k) from: T by: u})", 0); /* U8 key, 200 groups */ + ray_group_test_route(0); + PASS(); +} + +/* The direct-array route's shapes beyond the brief's lines. */ +static test_result_t test_da_route_shapes(void) { + ray_group_test_route(1); + /* a SYM key: slots over the domain's ids (never ordered by raw id) */ + SR_SAME("(select {c: (count k) s: (sum v) from: T by: s})", 0); + /* SYM inputs (domain order, widths per piece), strlen, FIRST / LAST */ + SR_SAME("(select {mn: (min s) mx: (max s) l: (avg (strlen s)) f: (first v) z: (last f) from: T by: g})", 0); + /* PROD, second moments, ALL / ANY, F32 / DATE / BOOL / U8 inputs */ + SR_SAME("(select {p: (prod b) vr: (var v) sd: (stddev f) al: (all b) an: (any u) from: T where: (> g 0) by: u})", 0); + SR_SAME("(select {mn: (min e) mx: (max d) s: (sum e) a: (avg u) from: T by: {b: b g: g}})", 0); + /* a selection whose directory superset range does not fit the slot + * budget: the exact range by a scan, the route generation 0 takes */ + SR_SAME("(select {c: (count k) s: (sum v) from: T where: (< h 262000) by: h})", 0); + /* a computed key beside a staged one (the key expression reads k plain) */ + SR_SAME("(select {c: (count k) s: (sum v) from: T by: {g: g m: (% k 3)}})", 1); + /* the directory prescan decodes no key: u is read once, by the + * accumulation (COUNT reads no input) */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + ray_t* r = sr_eval("(select {c: (count k) from: T by: u})"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + ray_enc_counters_t kc; ray_enc_counters_get(&kc); + TEST_ASSERT_EQ_U(kc.decoded_bytes, 200000); + sr_drop(r); + /* binary aggregates: both inputs staged, the y-side read by pieces */ + SR_SAME("(select {p: (pearson_corr f k) c: (cov k f) w: (wavg k f) ws: (wsum f h) from: T by: g})", 0); + SR_SAME("(select {p: (pearson_corr k h) w: (wavg g f) from: T where: (> k 1000) by: {g: g b: b}})", 0); + /* strlen of symbols of lengths 1-3 (a piece read at the wrong row + * gives a different length) and binary aggregates over a second table */ + sr_eval_ok("(set Y (table [g w x y] (list (as 'I16 (% i 7)) (as 'SYM (as 'STR (% (* i 7) 400))) " + "(* (as 'F64 i) 0.5) (% (* i 7919) 1003))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/y0/\" Y {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/y2/\" Y {compress: true})"); + static const char* const qy[] = { + "(select {l: (avg (strlen w)) s: (sum (strlen w)) from: T by: g})", + "(select {l: (sum (strlen w)) from: T where: (> y 10) by: g})", + /* strlen beside min / max: the accumulation's general arm (a + * strlen under min / max is an expression, not a strlen input) */ + "(select {l: (sum (strlen w)) a: (avg (strlen w)) m: (min y) x: (max x) from: T by: g})", + "(select {p: (pearson_corr x y) c: (cov y x) w: (wavg y x) ws: (wsum x y) from: T by: g})", + NULL }; + for (int q = 0; qy[q]; q++) { + test_result_t t = sr_same_on("(.db.splayed.get \"" SR_TMP "/y0/\")", "(.db.splayed.get \"" SR_TMP "/y2/\")", + qy[q], 0); + if (t.status != TEST_PASS) { ray_group_test_route(0); return t; } + } + ray_group_test_route(0); + PASS(); +} + +/* Partitioned generation-2 tables (exec_group_parted gives each partition's + * segments to the route), and a ragged generation-0 table whose missing + * column is a synthetic null segment, answer as their references. Answers + * only: the parted dispatch's own segment reads are Task 14's. */ +static test_result_t test_da_route_parted(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/dp%d/2024.01.0%d/t/\" " + "(table [g v] (list (as 'I16 (%% (til 70000) 7)) (as 'I32 (map (fn [j] (if (== 0 (%% j 11)) 0N j)) (til 70000))))) " + "{compress: %s})", gen, p + 1, gen ? "true" : "false"); + for (int p = 0; p < 3; p++) { + const char* tbl = p == 2 ? "(table [g] (list (as 'I16 (% (til 70000) 7))))" + : "(table [g v] (list (as 'I16 (% (til 70000) 7)) (til 70000)))"; + const char* ref = p == 2 ? "(table [g v] (list (as 'I16 (% (til 70000) 7)) (take [0Nl] 70000)))" : tbl; + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/drg/2024.01.0%d/t/\" %s {compress: false})", p + 1, tbl); + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/drf/2024.01.0%d/t/\" %s {compress: false})", p + 1, ref); + } + ray_group_test_route(1); + static const char* const q[] = { "(select {s: (sum v) c: (count v) mx: (max v) from: T by: g})", + "(select {a: (avg v) f: (first v) from: T where: (> v 100) by: g})", NULL }; + for (int i = 0; q[i]; i++) { + test_result_t r = sr_same_on("(.db.parted.get \"" SR_TMP "/dp0\" 't)", "(.db.parted.get \"" SR_TMP "/dp2\" 't)", q[i], UINT64_MAX); + if (r.status == TEST_PASS) + r = sr_same_on("(.db.parted.get \"" SR_TMP "/drf\" 't)", "(.db.parted.get \"" SR_TMP "/drg\" 't)", q[i], UINT64_MAX); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + ray_group_test_route(0); + PASS(); +} + +/* The sparse-dynamic count route (a top-N by count over one key, reached + * when the direct array declines): staged keys and inputs by range. */ +static test_result_t test_sp_dyn_route(void) { + static const char* const q2[] = { + "(select {c: (count k) from: T by: s desc: c take: 3})", /* SYM, count only */ + "(select {c: (count k) s: (sum k) a: (avg g) from: T by: u desc: c take: 3})", /* sums, first pass */ + "(select {c: (count k) s: (sum k) from: T by: s desc: c take: 3})", /* SYM: the sum pass */ + "(select {c: (count k) s: (sum h) from: T where: (> g 0) by: s desc: c take: 2})", + NULL }; + ray_group_test_route(2); /* skip v2 and the direct array */ + for (int i = 0; q2[i]; i++) SR_SAME(q2[i], 0); + /* binary aggregates never take the sparse-dynamic count (SUM / AVG / + * COUNT only): the hash route, on plain columns, answers as generation 0 */ + SR_SAME("(select {c: (count k) p: (pearson_corr f k) w: (wavg k f) from: T by: s desc: c take: 3})", UINT64_MAX); + ray_group_test_route(1); + SR_SAME("(select {c: (count k) from: T by: h desc: c take: 3})", 0); /* the DA range does not fit */ + /* the parallel fill (262144 rows or more) walks the key */ + sr_eval_ok("(set W (table [s x] (list (take ['a 'b 'c 'd 'e 'f 'g] 300000) (til 300000))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w0/\" W {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w2/\" W {compress: true})"); + ray_group_test_route(2); + test_result_t t = sr_same_on("(.db.splayed.get \"" SR_TMP "/w0/\")", "(.db.splayed.get \"" SR_TMP "/w2/\")", + "(select {c: (count x) from: T by: s desc: c take: 3})", 0); + if (t.status != TEST_PASS) { ray_group_test_route(0); return t; } + ray_group_test_route(0); + PASS(); +} + +/* ---- Task 12: the legacy radix group route ---- */ +static test_result_t test_radix_route(void) { + ray_group_test_route(2); /* skip v2 and DA: legacy radix */ + SR_SAME("(select {c: (count k) s: (sum v) from: T by: k})", 0); /* 200000 groups */ + SR_SAME("(select {c: (count k) from: T where: (> v 1000) by: {k: k s: s}})", 0); /* SYM in a composite key */ + SR_SAME("(select {a: (avg f) from: T by: d})", 0); + SR_SAME("(select {m: (med v) from: T by: g})", 1); /* holistic input materializes */ + ray_group_test_route(0); + PASS(); +} + +/* The legacy radix route's shapes beyond the brief's lines: the v2 + * sibling (null-free inputs, no SYM key) with a survivor list (R-SPARSE) + * and a rowsel, every streaming op, binary aggregates, nullable keys, a + * holistic input beside staged ones, wide keys, and a pre-materialized + * column read in place. */ +static test_result_t test_radix_route_shapes(void) { + static const struct { const char* q; uint64_t mat; } qs[] = { + /* v2: whole scan, survivor list (< half the rows), rowsel */ + { "(select {c: (count k) s: (sum k) a: (avg g) from: T by: {g: g u: u}})", 0 }, + { "(select {c: (count k) s: (sum h) from: T where: (> k 140000) by: {g: g u: u}})", 0 }, + { "(select {s: (sum h) a: (avg u) from: T where: (> k 50000) by: {d: d b: b}})", 0 }, + /* phase 1: a SYM key under a rowsel, every streaming op, strlen */ + { "(select {s: (sum v) mx: (max f) mn: (min d) from: T where: (> g 2) by: s})", 0 }, + { "(select {f: (first v) l: (last f) vr: (var v) p: (prod b) mn: (min s) mx: (max s) " + "n: (sum (strlen s)) e: (avg e) sd: (stddev g) from: T by: {g: g b: b}})", 0 }, + { "(select {p: (pearson_corr f k) w: (wavg k f) c: (cov h g) from: T by: {g: g u: u}})", 0 }, + /* nullable keys: I32, F64, and in a composite */ + { "(select {c: (count k) s: (sum h) from: T by: v})", 0 }, + { "(select {c: (count k) from: T where: (> k 100) by: f})", 0 }, + { "(select {c: (count k) a: (avg e) from: T by: {v: v g: g}})", 0 }, + /* holistic: exactly its input materializes, the others are read by range */ + { "(select {m: (med v) s: (sum f) c: (count k) from: T by: g})", 1 }, + { "(select {m: (med v) a: (avg h) from: T where: (> k 1000) by: {g: g b: b}})", 1 }, + { "(select {q: (med f) x: (med v) from: T by: s})", 2 }, + }; + ray_group_test_route(2); + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + test_result_t r = sr_same(qs[i].q, qs[i].mat); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + /* a STR key: grouped on its query-wide string-domain ids (strdom.c), so + * no key materializes and the inputs are read by range; only the + * holistic input (med) materializes */ + sr_eval_ok("(set Z (table [t g v f] (list (as 'STR (% i 50)) (as 'I16 (% i 7)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 10)) 0N j)) i)) (as 'F64 i))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/z0/\" Z {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/z2/\" Z {compress: true})"); + static const struct { const char* q; uint64_t mat; } qz[] = { + { "(select {s: (sum v) c: (count g) a: (avg f) from: T by: t})", 0 }, + { "(select {s: (sum v) m: (max f) from: T where: (> g 1) by: {t: t g: g}})", 0 }, + { "(select {m: (med f) s: (sum v) from: T by: t})", 1 }, + }; + for (size_t i = 0; i < sizeof qz / sizeof qz[0]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/z0/\")", "(.db.splayed.get \"" SR_TMP "/z2/\")", + qz[i].q, qz[i].mat); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + /* k materialized before the query: read in place beside staged inputs */ + sr_eval_ok("(set T2M (.db.splayed.get \"" SR_G2 "\"))"); + ray_t* t = sr_eval("T2M"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* kcol = ray_table_col(t, ray_sym_intern("k", 1)); + TEST_ASSERT_TRUE(kcol && !RAY_IS_ERR(kcol)); + sr_drop(t); + /* h materialized too: the v2 survivor list (R-SPARSE) reads a plain + * input in place at each run's first row */ + t = sr_eval("T2M"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* hcol = ray_table_col(t, ray_sym_intern("h", 1)); + TEST_ASSERT_TRUE(hcol && !RAY_IS_ERR(hcol)); + sr_drop(t); + static const char* const q2m[] = { + "(select {c: (count v) s: (sum v) from: T by: k})", + "(select {c: (count v) s: (sum f) from: T by: {k: k g: g}})", + "(select {c: (count k) s: (sum h) from: T where: (> k 140000) by: {g: g u: u}})", + NULL }; + for (int i = 0; q2m[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_G0 "\")", "T2M", q2m[i], 0); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + /* a non-inline wide key (GUID) beside a fixed one: the keys stay plain + * and unwalked, the inputs are read by range */ + sr_eval_ok("(set Q (table [q g v] (list (take (guid 37) 200000) (as 'I16 (% i 7)) i)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/q0/\" Q {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/q2/\" Q {compress: true})"); + test_result_t rq = sr_same_on("(.db.splayed.get \"" SR_TMP "/q0/\")", "(.db.splayed.get \"" SR_TMP "/q2/\")", + "(select {s: (sum v) c: (count v) from: T by: {q: q g: g}})", 2); + ray_group_test_route(0); + if (rq.status != TEST_PASS) return rq; + PASS(); +} + +/* Fix round 1 (I3): the single-key sparse paths of the legacy route (the + * emit-filter key-range scatter, the sparse i64 table and its heavy-hitter + * sum pass) read staged keys and inputs by pieces, and their fallback to + * the fat-entry routes takes them staged: nothing materializes. */ +static test_result_t test_radix_route_sparse(void) { + static const char* const qs[] = { + /* the sparse i64 table, sum arm */ + "(select {c: (count k) s: (sum h) from: T by: k})", + "(select {s: (sum h) a: (avg k) from: T by: h})", + "(select {s: (sum h) from: T by: u})", + "(select {c: (count k) s: (sum k) from: T where: (> k 100) by: h})", + "(select {c: (count k) s: (sum h) a: (avg u) from: T by: s})", /* SYM key, by piece width */ + /* the emit-filter key range under a sparse selection: bounds by a scan */ + "(select {c: (count k) s: (sum h) from: T where: (< k 1000) by: h desc: c take: 3})", + "(select {c: (count k) s: (sum u) a: (avg h) from: T where: (> k 180000) by: h desc: c take: 3})", + /* the emit-filter sparse table (a SYM key never takes the key range): + * the count arm, then the heavy hitters' sums */ + "(select {c: (count k) s: (sum h) from: T where: (< k 5) by: s desc: c take: 2})", + NULL }; + ray_group_test_route(2); + for (int i = 0; qs[i]; i++) { + test_result_t r = sr_same(qs[i], 0); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + /* keys the dense count declines (negative, or past its cap) reach the + * emit-filter key range without a selection: n's bounds come from the + * directory, m's span takes the second (marker) sum pass, w's does not + * fit (the sparse table), p / q are I32 with negatives (the range reads + * them unsigned, so their directory bounds are not used), t is I16 + * (the two-byte key arm) */ + sr_eval_ok("(set N (table [n m w p q t x] (list (- (% (* i 7919) 1000003) 500000) " + "(* (- (% i 1000) 500) 40000) (* (- (% i 1000) 500) 1000000) " + "(as 'I32 (- (% i 1000) 2000)) (as 'I32 (- (% i 1000) 500)) " + "(as 'I16 (- (% (* i 7919) 60001) 30000)) i)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/n0/\" N {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/n2/\" N {compress: true})"); + static const char* const qn[] = { + "(select {c: (count x) s: (sum x) from: T by: n desc: c take: 3})", + "(select {c: (count x) s: (sum x) a: (avg x) from: T by: m desc: c take: 3})", + "(select {c: (count x) s: (sum x) from: T by: w desc: c take: 3})", + "(select {c: (count x) s: (sum x) from: T by: p desc: c take: 3})", + "(select {c: (count x) s: (sum x) from: T by: q desc: c take: 3})", + "(select {c: (count x) s: (sum x) from: T where: (> x 1000) by: m desc: c take: 3})", + "(select {s: (sum x) a: (avg n) from: T by: w})", + "(select {c: (count x) s: (sum x) from: T by: t})", + "(select {c: (count x) s: (sum x) from: T by: t desc: c take: 3})", + NULL }; + for (int i = 0; qn[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/n0/\")", "(.db.splayed.get \"" SR_TMP "/n2/\")", + qn[i], 0); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + /* the fallback: an emit-filter sparse table over more than 2^21 rows + * goes to the fat-entry routes, which read the key and input staged */ + sr_eval_ok("(set jf (til 2200000))"); + sr_eval_ok("(set F (table [w x] (list (* (% jf 1000) 1000000) jf)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/f0/\" F {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/f2/\" F {compress: true})"); + test_result_t t = sr_same_on("(.db.splayed.get \"" SR_TMP "/f0/\")", "(.db.splayed.get \"" SR_TMP "/f2/\")", + "(select {c: (count x) s: (sum x) from: T by: w desc: c take: 3})", 0); + if (t.status != TEST_PASS) { ray_group_test_route(0); return t; } + /* Fix round 2: a non-null F64 input read from a staged piece (the f64 + * arm rebases its row like the integer arms), under the sparse table's + * sum pass and the emit-filter's heavy-hitter pass */ + sr_eval_ok("(set P (table [h w x] (list (% (* i 7919) 1000003) (* (% i 1000) 1000000) (as 'F64 i))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/p0/\" P {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/p2/\" P {compress: true})"); + static const char* const qp[] = { + "(select {s: (sum x) a: (avg x) from: T by: h})", + "(select {c: (count x) from: T by: w desc: c take: 3})", + "(select {c: (count x) from: T where: (> x 1000) by: w desc: c take: 3})", + "(select {c: (count x) s: (sum x) from: T where: (> x 1000) by: w desc: c take: 3})", + NULL }; + for (int i = 0; qp[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/p0/\")", "(.db.splayed.get \"" SR_TMP "/p2/\")", + qp[i], 0); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + /* A plain (materialized) key and a plain input beside staged columns: + * the plain one is read at the absolute row, the staged at the piece's */ + sr_eval_ok("(set T2M (.db.splayed.get \"" SR_G2 "\"))"); + ray_t* tm = sr_eval("T2M"); + TEST_ASSERT_TRUE(tm && !RAY_IS_ERR(tm)); + ray_t* kc = ray_table_col(tm, ray_sym_intern("k", 1)); + ray_t* hc = ray_table_col(tm, ray_sym_intern("h", 1)); + TEST_ASSERT_TRUE(kc && !RAY_IS_ERR(kc) && hc && !RAY_IS_ERR(hc)); + sr_drop(tm); + static const char* const qm[] = { + "(select {c: (count u) s: (sum u) from: T by: k})", /* plain key, staged input */ + "(select {c: (count k) s: (sum h) from: T by: u})", /* plain inputs, staged key */ + NULL }; + for (int i = 0; qm[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_G0 "\")", "T2M", qm[i], 0); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + ray_group_test_route(0); + PASS(); +} + +/* Below the parallel threshold the serial builder (group_rows_range) and + * the serial holistic reprobe read by pieces too (worker 0). */ +static test_result_t test_radix_route_serial(void) { + sr_eval_ok("(set j (til 50000))"); + sr_eval_ok("(set SM (table [k g v s f t] (list j (as 'I16 (% j 7)) " + "(as 'I32 (map (fn [x] (if (== 0 (% x 10)) 0N x)) j)) (take ['a 'b 'c 'd] 50000) " + "(as 'F64 (map (fn [x] (if (== 0 (% x 13)) 0N x)) j)) (as 'STR (% j 30)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sm0/\" SM {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sm2/\" SM {compress: true})"); + static const struct { const char* q; uint64_t mat; } qs[] = { + { "(select {c: (count k) s: (sum v) a: (avg f) from: T by: {g: g s: s}})", 0 }, + { "(select {c: (count k) s: (sum v) from: T where: (> k 100) by: v})", 0 }, + { "(select {m: (med v) s: (sum f) from: T by: s})", 1 }, + { "(select {m: (med f) from: T where: (> g 2) by: {g: g s: s}})", 1 }, + { "(select {s: (sum v) c: (count k) from: T by: t})", 0 }, /* STR key: string-domain ids */ + { "(select {m: (med v) a: (avg f) from: T by: {t: t g: g}})", 1 }, + }; + ray_group_test_route(2); + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/sm0/\")", "(.db.splayed.get \"" SR_TMP "/sm2/\")", + qs[i].q, qs[i].mat); + if (r.status != TEST_PASS) { ray_group_test_route(0); return r; } + } + ray_group_test_route(0); + PASS(); +} + +/* ---- Task 13: the v2 aggregate engine reads by pieces ---- */ + +static test_result_t test_v2_routes(void) { + agg_route_reset(); + SR_SAME("(select {s: (sum v) c: (count k) from: T by: g})", 0); /* dense */ + SR_SAME("(select {s: (sum f) a: (avg v) from: T where: (> k 5000) by: g})", 0); /* dense, sel */ + SR_SAME("(select {c: (count k) from: T by: {g: g s: s}})", 0); /* multi key */ + agg_test_no_wide_dense(true); /* a wide dense slab would take it: keep the radix route */ + SR_SAME("(select {c: (count k) mn: (min v) from: T by: h})", 0); /* high cardinality: radix */ + agg_test_no_wide_dense(false); + SR_SAME("(select {c: (count k) from: T where: (== b true) by: d})", 0); + SR_SAME("(select {x: (max f) from: T by: {d: d u: u}})", 0); + agg_route_stats_t rs = agg_route_stats(); + TEST_ASSERT_TRUE(rs.routes[AGG_ROUTE_V2_DENSE] + rs.routes[AGG_ROUTE_V2_SERIAL_DENSE] > 0); + TEST_ASSERT_TRUE(rs.routes[AGG_ROUTE_V2_RADIX] + rs.routes[AGG_ROUTE_V2_TABLESTACK] > 0); + PASS(); +} + +/* Review focus 1: a 200001-row table on 3 workers gives dense blocks of + * 66667 rows, none vector-aligned. */ +static test_result_t test_v2_dense_unaligned(void) { + sr_eval_ok("(set Q (table [g v] (list (as 'I16 (% (til 200001) 5)) (til 200001))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/q2/\" Q {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/q0/\" Q {compress: false})"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(3), RAY_OK); + ray_t* a = sr_eval("(select {s: (sum v) from: (.db.splayed.get \"" SR_TMP "/q0/\") by: g})"); + ray_enc_counters_reset(); + ray_t* b = sr_eval("(select {s: (sum v) from: (.db.splayed.get \"" SR_TMP "/q2/\") by: g})"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b)); + ray_t* fa = ray_fmt(a, 0); ray_t* fb = ray_fmt(b, 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + TEST_ASSERT_EQ_U(k.materialized, 0); + ray_release(fa); ray_release(fb); ray_release(a); ray_release(b); + PASS(); +} +/* Task 13b: decodes per column of one generation-2 group-by. Rows of + * column `name` of table T decoded during query q, over the column's rows + * (1.0: every vector decoded exactly once). */ +static double sr_col_decodes(const char* name, uint64_t before) { + ray_t* t = sr_eval("T"); + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern(name, strlen(name))); + double r = -1; + if (ec) { + ray_enccol_t* e = ray_enccol_of(ec); + r = (double)(atomic_load(&e->decoded_bytes) - before) / ((double)e->len * ray_enccol_esz(e)); + } + sr_drop(t); + return r; +} +static uint64_t sr_col_decoded(const char* name) { + ray_t* t = sr_eval("T"); + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern(name, strlen(name))); + uint64_t r = ec ? atomic_load(&ray_enccol_of(ec)->decoded_bytes) : 0; + sr_drop(t); + return r; +} + +/* The samplers of the dense and table-stack plans read their sampled keys + * without decoding vectors (point reads): the key decodes as often as the + * aggregate input walked beside it. A task walks its consecutive blocks + * through one cursor set, so a vector is decoded once per task that reads + * it: at most one extra vector per task (the one its range starts inside). + * The same answers as generation 0. */ +static test_result_t test_v2_decode_once(void) { + sr_eval_ok("(set jd (til 600001))"); + sr_eval_ok("(set DQ (table [k v ts] (list (as 'I32 (% (* jd 7919) 1000)) jd (* (% (* jd 104729) 2000) 100003))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/dq2/\" DQ {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/dq0/\" DQ {compress: false})"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + static const struct { const char* key; const char* q; int route; } qs[] = { + { "k", "(select {s: (sum v) c: (count v) from: T by: k})", AGG_ROUTE_V2_DENSE }, + { "ts", "(select {s: (sum v) c: (count v) from: T by: ts})", AGG_ROUTE_V2_TABLESTACK }, + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/dq0/\")", "(.db.splayed.get \"" SR_TMP "/dq2/\")", + qs[i].q, 0); + if (r.status != TEST_PASS) return r; + sr_eval_ok("(set T (.db.splayed.get \"" SR_TMP "/dq2/\"))"); + uint64_t k0 = sr_col_decoded(qs[i].key), v0 = sr_col_decoded("v"); + agg_route_reset(); + ray_t* res = sr_eval(qs[i].q); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + ray_release(res); + agg_route_stats_t st = agg_route_stats(); + TEST_ASSERT_FMT(st.routes[qs[i].route] == 1, "%s: route %d not taken", qs[i].q, qs[i].route); + if (qs[i].route == AGG_ROUTE_V2_DENSE) TEST_ASSERT_EQ_I(st.dense_strategy, AGG_DENSE_TASK_LOCAL); + double kd = sr_col_decodes(qs[i].key, k0), vd = sr_col_decodes("v", v0); + TEST_ASSERT_FMT(kd == vd, "%s: key decoded %.4fx, input %.4fx", qs[i].q, kd, vd); + uint32_t tasks = qs[i].route == AGG_ROUTE_V2_DENSE ? st.dense_tasks : st.ts_tasks; + TEST_ASSERT_TRUE(tasks > 1); + double cap = 1.0 + (double)tasks * RAY_ENC_VEC / 600001.0; + TEST_ASSERT_FMT(vd >= 1.0 && vd <= cap, "%s: input decoded %.4fx over %u tasks (at most %.4fx)", + qs[i].q, vd, tasks, cap); + } + PASS(); +} + +static bool sr_same_text(ray_t* a, ray_t* b); + +/* q over the tables t0 / t2: the same answer, the same routes, dense + * strategy and dense-plan availability (agg_route_stats). */ +static test_result_t sr_same_route(const char* t0, const char* t2, const char* q) { + agg_route_stats_t st[2]; + ray_t* out[2] = { NULL, NULL }; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? t2 : t0); + agg_route_reset(); + out[gen] = sr_eval(q); + st[gen] = agg_route_stats(); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "gen %d: %s: %s", gen, q, out[gen] ? ray_error_msg() : "null"); + } + for (int r = 0; r < AGG_ROUTE_COUNT; r++) + TEST_ASSERT_FMT(st[0].routes[r] == st[1].routes[r], "%s: route %d taken %llu / %llu times", q, r, + (unsigned long long)st[0].routes[r], (unsigned long long)st[1].routes[r]); + TEST_ASSERT_FMT(st[0].dense_strategy == st[1].dense_strategy, "%s: dense strategy %d / %d", q, + (int)st[0].dense_strategy, (int)st[1].dense_strategy); + TEST_ASSERT_FMT(st[0].dense_plan_available == st[1].dense_plan_available, "%s: dense plan %d / %d", q, + (int)st[0].dense_plan_available, (int)st[1].dense_plan_available); + TEST_ASSERT_FMT(st[0].dense_local_slots == st[1].dense_local_slots, "%s: dense slots %llu / %llu", q, + (unsigned long long)st[0].dense_local_slots, (unsigned long long)st[1].dense_local_slots); + TEST_ASSERT_TRUE(sr_same_text(out[0], out[1])); + ray_release(out[0]); ray_release(out[1]); + PASS(); +} + +/* The selection prescan's key bounds read only the chunks whose + * directory statistics can move them, and equal the full scan's: chunk 0 + * holds the lowest minimum and chunk 1 the highest maximum on unselected + * rows, chunk 2's lowest selected key (2) lies below both of their + * selected keys, the other chunks lie inside; a nullable key with an + * all-null chunk and a chunk with nulls; filters of one row, of no row + * and of an all-null chunk only. Route, plan and answer as generation 0. */ +static test_result_t test_v2_sel_bounds(void) { + const int64_t n = 10 * 65536 + 1234; + ray_t* k = ray_vec_new(RAY_I64, n); k->len = n; + ray_t* kn = ray_vec_new(RAY_I64, n); kn->len = n; + ray_t* s = ray_vec_new(RAY_I64, n); s->len = n; + int64_t* kd = ray_data(k); int64_t* knd = ray_data(kn); int64_t* sd = ray_data(s); + for (int64_t i = 0; i < n; i++) { kd[i] = 10 + (i * 7919) % 11; sd[i] = 1; } + kd[0] = -5; sd[0] = 0; kd[1] = 50; sd[1] = 0; /* chunk 0: the lowest minimum, unselected */ + kd[65536] = 1000000; sd[65536] = 0; /* chunk 1: the highest maximum, unselected */ + kd[131072 + 5] = 2; /* chunk 2: the lowest selected key */ + kd[131072 + 6] = 1; sd[131072 + 6] = 0; kd[131072 + 7] = 30; sd[131072 + 7] = 0; + for (int64_t i = 0; i < n; i++) + knd[i] = (i >= 4 * 65536 && i < 5 * 65536) || (i >= 5 * 65536 && i < 6 * 65536 && i % 100 == 0) ? NULL_I64 : kd[i]; + kn->attrs |= RAY_ATTR_HAS_NULLS; + ray_env_set(ray_sym_intern("bk", 2), k); ray_env_set(ray_sym_intern("bkn", 3), kn); ray_env_set(ray_sym_intern("bs", 2), s); + ray_release(k); ray_release(kn); ray_release(s); + sr_eval_ok("(set SB (table [k kn s v w] (list bk bkn bs (til 656594) (% (til 656594) 3))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sb2/\" SB {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sb0/\" SB {compress: false})"); + static const char* const qs[] = { + "(select {c: (count v) s: (sum v) from: T where: (== s 1) by: k})", + "(select {c: (count v) s: (sum v) from: T where: (== s 1) by: kn})", + "(select {c: (count v) s: (sum v) from: T where: (== s 1) by: {k: k w: w}})", + "(select {c: (count v) s: (sum v) from: T where: (== v 77) by: k})", /* one row */ + "(select {c: (count v) s: (sum v) from: T where: (== v -1) by: k})", /* no row */ + "(select {c: (count v) s: (sum v) from: T where: (and (>= v 262144) (< v 327680)) by: kn})", /* the all-null chunk */ + "(select {c: (count v) s: (sum v) from: T where: (and (>= v 131072) (< v 196608)) by: k})", /* one chunk */ + NULL }; + for (int i = 0; qs[i]; i++) { + test_result_t r = sr_same_route("(.db.splayed.get \"" SR_TMP "/sb0/\")", "(.db.splayed.get \"" SR_TMP "/sb2/\")", qs[i]); + if (r.status != TEST_PASS) return r; + } + /* the mirror of round 2 on the maximum: chunk 0 holds the lowest minimum + * and the highest maximum, both on unselected rows (its selected keys are + * 10..20); chunk 1's statistics are [10, 500] with 500 selected, so only + * its maximum reaches outside the bounds round 1 found */ + { + const int64_t m = 4 * 65536; + ray_t* k2 = ray_vec_new(RAY_I64, m); k2->len = m; + ray_t* s2 = ray_vec_new(RAY_I64, m); s2->len = m; + int64_t* k2d = ray_data(k2); int64_t* s2d = ray_data(s2); + for (int64_t i = 0; i < m; i++) { k2d[i] = 10 + (i * 7919) % 11; s2d[i] = 1; } + k2d[0] = -5; s2d[0] = 0; k2d[1] = 100000; s2d[1] = 0; + k2d[65536 + 3] = 500; + ray_env_set(ray_sym_intern("bk2", 3), k2); ray_env_set(ray_sym_intern("bs2", 3), s2); + ray_release(k2); ray_release(s2); + sr_eval_ok("(set SM (table [k s v] (list bk2 bs2 (til 262144))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sm2/\" SM {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sm0/\" SM {compress: false})"); + test_result_t r = sr_same_route("(.db.splayed.get \"" SR_TMP "/sm0/\")", "(.db.splayed.get \"" SR_TMP "/sm2/\")", + "(select {c: (count v) s: (sum v) from: T where: (== s 1) by: k})"); + if (r.status != TEST_PASS) return r; + } + /* the dense plan of the first: chunks 0, 1 and 2 are read for its bounds, + * not all ten (a full prescan reads the key once more than the pass) */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_TMP "/sb2/\"))"); + uint64_t k0 = sr_col_decoded("k"); + agg_route_reset(); + ray_t* res = sr_eval(qs[0]); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + ray_release(res); + TEST_ASSERT_TRUE(agg_route_stats().dense_plan_available); + double kdec = sr_col_decodes("k", k0); + TEST_ASSERT_FMT(kdec < 1.5, "key decoded %.3fx", kdec); + PASS(); +} + +/* Task 17b: a selection prescan over a mixed key set. The SYM key is read + * exactly first; the staged I64 key k then takes the directory path as a + * key set of its own (chunk pruning as above: g has 3 values), or, when the + * SYM key's range alone exceeds the dense limit (h: about 13 000 selected + * rows over 50 021 ids), is not read for bounds at all. Route, plan, + * slots and answer as generation 0. */ +static test_result_t test_v2_sel_bounds_split(void) { + const int64_t n = 10 * 65536 + 1234; + ray_t* k = ray_vec_new(RAY_I64, n); k->len = n; + int64_t* kd = ray_data(k); + for (int64_t i = 0; i < n; i++) kd[i] = 10 + (i * 7919) % 11; + kd[0] = -5; kd[65536] = 1000000; /* chunks 0 and 1: the extremes, unselected */ + /* m: every chunk's directory reaches past the selected rows' keys + * (rows c * 65536 + 1 and + 2, never selected by v % 50 == 0), so the + * directory path would read every chunk */ + ray_t* mk = ray_vec_new(RAY_I64, n); mk->len = n; + int64_t* md = ray_data(mk); + for (int64_t i = 0; i < n; i++) md[i] = i % 11; + for (int64_t c = 0; c * 65536 + 2 < n; c++) { md[c * 65536 + 1] = -1000 - c; md[c * 65536 + 2] = 1000 + c; } + ray_env_set(ray_sym_intern("pk", 2), k); ray_release(k); + ray_env_set(ray_sym_intern("pm", 2), mk); ray_release(mk); + sr_eval_ok("(set pi (til 656594))"); + sr_eval_ok("(set SP (table [k m g h v s] (list pk pm (as 'SYM (as 'STR (% pi 3))) " + "(as 'SYM (as 'STR (% (* pi 7919) 50021))) pi (!= 0 (% pi 65536)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sp2/\" SP {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sp0/\" SP {compress: false})"); + static const struct { const char* q; bool dense; } qs[] = { + { "(select {c: (count v) s: (sum v) from: T where: s by: [g k]})", true }, + { "(select {c: (count v) s: (sum v) from: T where: s by: [k g]})", true }, + { "(select {c: (count v) s: (sum v) from: T where: (== 0 (% v 50)) by: [k h]})", false }, + { "(select {c: (count v) s: (sum v) from: T where: (== 0 (% v 50)) by: [h k]})", false }, + { "(select {c: (count v) s: (sum v) from: T where: (== 0 (% v 50)) by: [m h]})", false }, + { "(select {c: (count v) s: (sum v) from: T where: (== 0 (% v 50)) by: [h m]})", false }, + { NULL, false }, + }; + for (int i = 0; qs[i].q; i++) { + test_result_t r = sr_same_route("(.db.splayed.get \"" SR_TMP "/sp0/\")", "(.db.splayed.get \"" SR_TMP "/sp2/\")", qs[i].q); + if (r.status != TEST_PASS) return r; + sr_eval_ok("(set T (.db.splayed.get \"" SR_TMP "/sp2/\"))"); + const char* key = strstr(qs[i].q, "m h") || strstr(qs[i].q, "h m") ? "m" : "k"; + uint64_t k0 = sr_col_decoded(key), v0 = sr_col_decoded("v"); + agg_route_reset(); + ray_t* res = sr_eval(qs[i].q); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + ray_release(res); + /* the pass reads k once; a full prescan would read it once more */ + double kdec = sr_col_decodes(key, k0), vdec = sr_col_decodes("v", v0); + TEST_ASSERT_FMT(agg_route_stats().dense_plan_available == qs[i].dense, "%s: dense plan %d", qs[i].q, + (int)agg_route_stats().dense_plan_available); + TEST_ASSERT_FMT(kdec < 1.5 && vdec >= 1.0, "%s: k decoded %.4fx, v %.4fx", qs[i].q, kdec, vdec); + } + PASS(); +} + +/* Task 17b fix round 1: the dense-impossible shortcut of the split prescan + * at its boundary. g (SYM) holds one new symbol per row (two rows per + * symbol in the nullable table), so its selected ids span exactly the + * selected symbols; k (staged I64) is 5 on every selected row (the + * nullable table: one null, so its range is 2). The other keys' product + * equals n_sel (the selection plan is dense, as on generation 0) or + * exceeds it (no selection plan, k not read for bounds). Route, plan and + * slots as generation 0: an early verdict at the boundary would differ. */ +static test_result_t test_v2_sel_bounds_boundary(void) { + sr_eval_ok("(set bi (til 200000))"); + sr_eval_ok("(set BB (table [g k v] (list (as 'SYM (as 'STR (+ 100000 bi))) (take [5] 200000) bi)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/bb2/\" BB {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/bb0/\" BB {compress: false})"); + sr_eval_ok("(set BN (table [g k v] (list (as 'SYM (as 'STR (+ 100000 (div bi 2)))) " + "(map (fn [j] (if (== j 7) 0Nl 5)) bi) bi)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/bn2/\" BN {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/bn0/\" BN {compress: false})"); + /* k_bounds: k is read for the selection bounds (the other keys' product + * is at most n_sel). When the selection plan fails the group plans over + * the table, so the route stats alone cannot show the verdict. */ + static const struct { const char* t; const char* q; bool k_bounds; } qs[] = { + /* 5000 rows, g spans 5000 ids: product == n_sel */ + { "bb", "(select {c: (count v) from: T where: (< v 5000) by: [g k]})", true }, + { "bb", "(select {c: (count v) from: T where: (< v 5000) by: [k g]})", true }, + /* 5000 rows, g spans 5001 ids (row 1 left out): product == n_sel + 1 */ + { "bb", "(select {c: (count v) from: T where: (and (<= v 5000) (!= v 1)) by: [g k]})", false }, + { "bb", "(select {c: (count v) from: T where: (and (<= v 5000) (!= v 1)) by: [k g]})", false }, + /* nullable k (range 2): 5000 rows, g spans 2500 ids: 2 x 2500 == n_sel */ + { "bn", "(select {c: (count v) from: T where: (< v 5000) by: [g k]})", true }, + /* 5000 rows (0, 3..5001), g spans 2501 ids: 2 x 2501 > n_sel, but g + * alone fits, so k is read and the plan fails on the product (the + * chunk-extremes probe of P3 Task 14b does not run: the chunk + * holding g's extremes holds every selected row, more than its + * quarter) */ + { "bn", "(select {c: (count v) from: T where: (and (<= v 5001) (!= v 1) (!= v 2)) by: [g k]})", true }, + { NULL, NULL, false }, + }; + for (int i = 0; qs[i].q; i++) { + char t0[128], t2[128]; + snprintf(t0, sizeof t0, "(.db.splayed.get \"" SR_TMP "/%s0/\")", qs[i].t); + snprintf(t2, sizeof t2, "(.db.splayed.get \"" SR_TMP "/%s2/\")", qs[i].t); + test_result_t r = sr_same_route(t0, t2, qs[i].q); + if (r.status != TEST_PASS) return r; + sr_evalf_ok("(set T %s)", t2); + uint64_t k0 = sr_col_decoded("k"); + ray_t* res = sr_eval(qs[i].q); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + ray_release(res); + /* the compact fallback gathers the five vectors of the selected + * rows of k (P3 Task 6; before, it read all 200000 I64); the bounds + * prescan, when it reads k (k_bounds), reads its CONST vectors on + * their runs (P3 Task 3b; before, it decoded the five vectors once + * more), all but bn's vector 0, whose null (row 7) gives it a + * bitmap: no run view, so it is decoded */ + const bool nullk = strcmp(qs[i].t, "bn") == 0; + const uint64_t want = 5 * RAY_ENC_VEC * 8 + (qs[i].k_bounds && nullk ? RAY_ENC_VEC * 8 : 0); + TEST_ASSERT_FMT(sr_col_decoded("k") - k0 == want, "%s: %llu bytes of k decoded, want %llu", qs[i].q, + (unsigned long long)(sr_col_decoded("k") - k0), (unsigned long long)want); + } + PASS(); +} + +/* Every consumer kind that sizes memory from the directory statistics: + * the dense plan unfiltered (the directory prescan) and filtered (the + * selection bounds), the direct array, the sparse emit-filter range; each + * answers as generation 0. */ +static test_result_t test_v2_consumers(void) { + /* k: j*7 % 1000 in chunks 0-2, % 5001 in chunk 3 with a null every + * 100 rows (so the samplers' point reads decline there); g: % 50, % 101; + * n: a wide I64 key (the + * sparse range), + 400000 in chunk 3 */ + sr_eval_ok("(set jf (til 262144))"); + sr_eval_ok("(set ja (til 196608))"); + sr_eval_ok("(set jb (+ 196608 (til 65536)))"); + sr_eval_ok("(set FC (table [k g n v] (list (concat (% (* ja 7) 1000) (map (fn [j] (if (== 0 (% j 100)) 0N (% (* j 7) 5001))) jb)) " + "(as 'I16 (concat (% (* ja 7) 50) (% (* jb 7) 101))) " + "(concat (- (% (* ja 7919) 1000003) 500000) (+ 400000 (% (* jb 7919) 1000003))) jf)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fc0/\" FC {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fc2/\" FC {compress: true})"); + static const struct { const char* col; int64_t x; int route; const char* q; } cs[] = { + { "k", 999, 0, "(select {s: (sum v) c: (count v) from: T by: k})" }, /* dense, directory prescan */ + { "k", 999, 0, "(select {s: (sum v) c: (count v) from: T where: (> v 0) by: k})" }, /* dense, selection bounds */ + { "g", 49, 1, "(select {s: (sum v) c: (count v) from: T by: g})" }, /* the direct array */ + { "n", 500003, 2, "(select {c: (count v) s: (sum v) from: T by: n desc: c take: 3})" }, /* the sparse range */ + }; + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + ray_group_test_route(cs[i].route); + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/fc0/\")", "(.db.splayed.get \"" SR_TMP "/fc2/\")", cs[i].q, 0); + ray_group_test_route(0); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* P3 Task 6b fix round 2: the run arm of the batched point read + * (points_runs). k is an RLE key (runs of 5) and a CONST one (one value + * per vector). A filter keeping every 97th row reads k at about 10 rows + * per vector: point reads in the selection bounds and the compact gather. + * The answers are generation 0's and k decodes nothing. */ +static test_result_t test_v2_run_points(void) { + sr_eval_ok("(set ja (til 196608))"); + sr_eval_ok("(set jb (+ 196608 (til 65536)))"); + static const struct { const char* name; const char* k; int enc; } cs[] = { + { "fr", "(concat (% (* (div ja 5) 7) 1000) (% (* (div jb 5) 7) 5001))", RAY_ENC_RLE }, + { "fk", "(concat (% (div ja 1024) 1000) (+ 4000 (% (div jb 1024) 64)))", -1 }, + }; + static const char* const qs[] = { + "(select {c: (count v) from: T where: (== 0 (% v 97)) by: k})", + "(select {c: (count v) s: (sum v) from: T where: (== 0 (% v 97)) by: k desc: c take: 5})", + NULL, + }; + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + sr_evalf_ok("(set FQ (table [k v] (list %s (til 262144))))", cs[i].k); + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/%s0/\" FQ {compress: false})", cs[i].name); + ray_encw_test_force(cs[i].enc); + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/%s2/\" FQ {compress: true})", cs[i].name); + ray_encw_test_force(-1); + char t0[256], t2[256]; + snprintf(t0, sizeof t0, "(.db.splayed.get \"" SR_TMP "/%s0/\")", cs[i].name); + snprintf(t2, sizeof t2, "(.db.splayed.get \"" SR_TMP "/%s2/\")", cs[i].name); + /* every vector of k in chunk 3 is the arm's codec */ + { + ray_t* t = sr_eval(t2); + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern("k", 1)); + TEST_ASSERT_NOT_NULL(ec); + const ray_enc_desc_t* d = ray_enccol_descs(ray_enccol_of(ec), 3); + for (int j = 0; j < RAY_ENC_VECS_PER_CHUNK; j++) + TEST_ASSERT_FMT(d[j].encoding == (i ? RAY_ENC_CONST : RAY_ENC_RLE), "%s vector %d: %d", cs[i].name, j, d[j].encoding); + sr_drop(t); + } + for (int q = 0; qs[q]; q++) { + test_result_t r = sr_same_on(t0, t2, qs[q], 0); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(sr_col_decoded("k") == 0, "%s %s: %llu bytes of k decoded", cs[i].name, qs[q], + (unsigned long long)sr_col_decoded("k")); + } + } + PASS(); +} + +/* P3 Task 6b: point reads. A selective filter (every 97th row: a few + * rows per vector) groups by k, whose selected rows are point-read + * (FOR_BP, no nulls) by the dense plan's selection bounds and by the + * compact gather; the first-n passes (an unordered take) too. The answer + * is generation 0's and nothing is materialized. */ +static test_result_t test_v2_points(void) { + sr_eval_ok("(set ja (til 196608))"); + sr_eval_ok("(set jb (+ 196608 (til 65536)))"); + sr_eval_ok("(set FP (table [k v] (list (concat (% (* ja 7) 1000) (% (* jb 7) 5001)) (til 262144))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fp0/\" FP {compress: false})"); + ray_encw_test_force(RAY_ENC_FOR_BP); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fp2/\" FP {compress: true})"); + ray_encw_test_force(-1); + static const char* const qs[] = { + "(select {c: (count v) from: T where: (== 0 (% v 97)) by: k})", + "(select {c: (count v) s: (sum v) from: T where: (== 0 (% v 97)) by: k desc: c take: 5})", + "(select {c: (count v) from: T by: k take: 5})", /* first-n: pass 2 reads every vector */ + NULL, + }; + for (int i = 0; qs[i]; i++) { + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/fp0/\")", "(.db.splayed.get \"" SR_TMP "/fp2/\")", qs[i], 0); + if (r.status != TEST_PASS) return r; + if (i < 2) TEST_ASSERT_FMT(sr_col_decoded("k") == 0, "%s: %llu bytes of k decoded", qs[i], (unsigned long long)sr_col_decoded("k")); + } + PASS(); +} + +/* Task 17b fix round 1: the split prescan. A mixed key set (SYM g + * scanned exactly, staged I64 k through the directory path as a set of + * its own): the answers are generation 0's. */ +static test_result_t test_v2_split(void) { + sr_eval_ok("(set jf (til 262144))"); + sr_eval_ok("(set ja (til 196608))"); + sr_eval_ok("(set jb (+ 196608 (til 65536)))"); + sr_eval_ok("(set FS (table [k g v] (list (concat (% (* ja 7) 1000) (map (fn [j] (if (== 0 (% j 100)) 0N (% (* j 7) 5001))) jb)) " + "(as 'SYM (as 'STR (% jf 3))) jf)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fs0/\" FS {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fs2/\" FS {compress: true})"); + static const char* const qs[] = { + "(select {s: (sum v) c: (count v) from: T where: (> v 0) by: [g k]})", + "(select {s: (sum v) c: (count v) from: T where: (> v 0) by: [k g]})", + NULL, + }; + for (int i = 0; qs[i]; i++) { + test_result_t r = sr_same_route("(.db.splayed.get \"" SR_TMP "/fs0/\")", "(.db.splayed.get \"" SR_TMP "/fs2/\")", qs[i]); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Fix round 3: the serial dense path. One chunk of 60000 rows, under + * RAY_PARALLEL_THRESHOLD, so the group-by sizes its dense plan from the + * directory and then takes the serial path, which reads the key's whole + * materialization (agg_keys_unstage -> ray_col_src_plain). Key k is + * j * 7 % 5001 (FOR_BP); kn the same with a null every 100 rows; each + * answers as generation 0 on the serial dense route. A buffered + * aggregate (med) is admitted to v2 only as an indexed shape: its keys are + * unstaged before any plan, and it answers as generation 0, small (one + * chunk) and large (four chunks, with a pool). */ +static test_result_t test_v2_serial_dense(void) { + sr_eval_ok("(set js (til 60000))"); + sr_eval_ok("(set FS (table [k kn v] (list (% (* js 7) 5001) " + "(map (fn [j] (if (== 0 (% j 100)) 0N (% (* j 7) 5001))) js) js)))"); + sr_eval_ok("(set jm (til 262144))"); + sr_eval_ok("(set FM (table [k v] (list (% (* jm 7) 5001) jm)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fs0/\" FS {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fs2/\" FS {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fm0/\" FM {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/fm2/\" FM {compress: true})"); + static const struct { const char* tbl; const char* col; int64_t chunk; bool raise; int64_t x; int route; const char* q; } cs[] = { + { "fs", "k", 0, false, 999, AGG_ROUTE_V2_SERIAL_DENSE, "(select {s: (sum v) c: (count v) from: T by: k})" }, + { "fs", "kn", 0, false, 999, AGG_ROUTE_V2_SERIAL_DENSE, "(select {s: (sum v) c: (count v) from: T by: kn})" }, + { "fs", "k", 0, true, 4000, AGG_ROUTE_V2_SERIAL_DENSE, "(select {s: (sum v) c: (count v) from: T by: k})" }, + { "fs", "k", 0, false, 999, AGG_ROUTE_V2_SERIAL_DENSE, "(select {s: (sum v) c: (count v) from: T by: k take: 4})" }, + { "fs", "k", 0, false, 999, AGG_ROUTE_V2_INDEXED, "(select {m: (med v) c: (count v) from: T by: k})" }, + { "fm", "k", 2, false, 999, AGG_ROUTE_V2_INDEXED, "(select {m: (med v) c: (count v) from: T by: k})" }, + }; + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + char t0[256], t2[256]; + snprintf(t0, sizeof t0, "(.db.splayed.get \"" SR_TMP "/%s0/\")", cs[i].tbl); + snprintf(t2, sizeof t2, "(.db.splayed.get \"" SR_TMP "/%s2/\")", cs[i].tbl); + agg_route_reset(); + test_result_t r = sr_same_on(t0, t2, cs[i].q, UINT64_MAX); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(agg_route_stats().routes[cs[i].route] > 0, "%s: not route %d", cs[i].q, cs[i].route); + } + PASS(); +} + +/* The selected rows' key bounds of every key width (I64, I32 with nulls + * and negatives, I16 with negatives, DATE, BOOL, U8, SYM): a filtered group-by answers as the same + * group-by over the filtered table (both ordered by the key: the two + * routes emit groups in different orders), in both generations. */ +static test_result_t test_v2_sel_key_types(void) { + sr_eval_ok("(set KT (table [a n g d b u s h] (list (+ 5000000000 (% (* i 13) 500)) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 10)) 0N (+ 70000 (% j 300)))) i)) (as 'I16 (- (% i 7) 3)) " + "(as 'DATE (+ 20000 (% i 900))) (== 0 (% i 3)) (as 'U8 (+ 50 (% i 200))) (take ['a 'b 'c 'd 'e] 200000) " + "(% (* i 7919) 1000003))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/kt2/\" KT {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/kt0/\" KT {compress: false})"); + static const char* const keys[] = { "a", "n", "g", "d", "b", "u", "s", NULL }; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T (.db.splayed.get \"%s\"))", gen ? SR_TMP "/kt2/" : SR_TMP "/kt0/"); + for (int i = 0; keys[i]; i++) { + char a[256], b[256]; + snprintf(a, sizeof a, "(select {c: (count h) s: (sum h) from: T where: (> h 500000) by: %s asc: %s})", keys[i], keys[i]); + snprintf(b, sizeof b, "(select {c: (count h) s: (sum h) from: (select {from: T where: (> h 500000)}) by: %s asc: %s})", + keys[i], keys[i]); + agg_route_reset(); + ray_t* ra = sr_eval(a); + agg_route_stats_t sa = agg_route_stats(); + agg_route_reset(); + ray_t* rb = sr_eval(b); + agg_route_stats_t sb = agg_route_stats(); + TEST_ASSERT_FMT(sr_same_text(ra, rb), "gen %d: %s differs from the filtered table's", gen * 2, a); + TEST_ASSERT_FMT(sa.dense_plan_available && sb.dense_plan_available, "gen %d: %s: no dense plan", gen * 2, a); + /* the unfiltered plan sizes a SYM key from its domain, not its ids */ + TEST_ASSERT_FMT(i == 6 || sa.dense_local_slots == sb.dense_local_slots, "gen %d: %s: %llu slots, the filtered table's %llu", + gen * 2, a, (unsigned long long)sa.dense_local_slots, (unsigned long long)sb.dense_local_slots); + ray_release(ra); ray_release(rb); + } + } + PASS(); +} + +/* The pool this test resized is restored even when an assert fails first + * (finding M11; test/test_parquet.c:262 resizes the pool the same way). */ +static void srr_pool_teardown(void) { ray_pool_destroy(); (void)ray_pool_init_total(0); srr_teardown(); } + +/* Review focus 2: a SYM key over two partitions of different width classes. */ +static test_result_t test_v2_sym_key_parted(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 2; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/sp%d/2024.01.0%d/t/\" " + "(table [s v] (list (as 'SYMBOL (map (fn [j] (format \"w%%\" (%% j %d))) (til 70000))) (til 70000))) " + "\"" SR_TMP "/sp%d/.sym\" {compress: %s})", gen, p + 1, p ? 300 : 20, gen, gen ? "true" : "false"); + ray_t* a = sr_eval("(select {c: (count v) s: (sum v) from: (.db.parted.get \"" SR_TMP "/sp0\" 't) by: s})"); + ray_enc_counters_reset(); + ray_t* b = sr_eval("(select {c: (count v) s: (sum v) from: (.db.parted.get \"" SR_TMP "/sp2\" 't) by: s})"); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_TRUE(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b)); + ray_t* fa = ray_fmt(a, 0); ray_t* fb = ray_fmt(b, 0); + TEST_ASSERT_TRUE(ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0); + TEST_ASSERT_EQ_U(k.materialized, 0); /* the cardinality sample reads segment 0 of s by range */ + TEST_ASSERT_EQ_I(ray_table_nrows(b), 300); + ray_release(fa); ray_release(fb); ray_release(a); ray_release(b); + PASS(); +} + +/* Findings I5, I6, I8: parted group-bys on encoded segments go + * per-partition (each sub-table holds encoded segment slots); the partition + * key keeps today's path; a ragged generation-0 table answers as its + * explicit-null reference. Nothing materializes. */ +static ray_t* sr_q(const char* q, uint64_t* mat) { + ray_enc_counters_reset(); + ray_t* r = sr_eval(q); + ray_enc_counters_t k; ray_enc_counters_get(&k); + if (mat) *mat = k.materialized; + return r; +} +static bool sr_same_text(ray_t* a, ray_t* b) { + if (!a || !b || RAY_IS_ERR(a) || RAY_IS_ERR(b)) return false; + ray_t* fa = ray_fmt(a, 0); ray_t* fb = ray_fmt(b, 0); + bool same = ray_str_len(fa) == ray_str_len(fb) && memcmp(ray_str_ptr(fa), ray_str_ptr(fb), ray_str_len(fa)) == 0; + ray_release(fa); ray_release(fb); + return same; +} +static test_result_t test_v2_parted_routes(void) { + sr_parted_xy(SR_TMP "/vp2", 7, false, false); /* every partition generation 2 */ + sr_parted_xy(SR_TMP "/vp0", 0, false, false); + sr_parted_xy(SR_TMP "/vrg", 0, true, false); + sr_parted_xy(SR_TMP "/vrf", 0, false, true); + static const char* const q[] = { + "(select {s: (sum x) c: (count x) from: (.db.parted.get \"%s\" 't) by: y})", /* low cardinality: per partition */ + "(select {s: (sum x) from: (.db.parted.get \"%s\" 't) by: date})", /* the partition key (MAPCOMMON) */ + "(select {m: (max x) from: (.db.parted.get \"%s\" 't) where: (> x 100) by: y})", + NULL, + }; + for (int i = 0; q[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, q[i], SR_TMP "/vp0"); snprintf(b, sizeof b, q[i], SR_TMP "/vp2"); + int64_t pp0 = ray_group_perpart_runs(); + uint64_t m = 9; + ray_t* r0 = sr_q(a, NULL); ray_t* r2 = sr_q(b, &m); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "%s", q[i]); + /* exec_group_parted's cardinality sample reads the key's segment 0 + * by range; the per-partition v2 runs materialize nothing. */ + TEST_ASSERT_FMT(m == 0, "%s: %llu materializations", q[i], (unsigned long long)m); + if (i != 1) TEST_ASSERT_TRUE(ray_group_perpart_runs() - pp0 >= 2); /* both generations per partition */ + sr_drop(r0); sr_drop(r2); + snprintf(a, sizeof a, q[i], SR_TMP "/vrf"); snprintf(b, sizeof b, q[i], SR_TMP "/vrg"); + r0 = sr_q(a, NULL); r2 = sr_q(b, &m); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "ragged: %s", q[i]); + TEST_ASSERT_EQ_U(m, 0); + sr_drop(r0); sr_drop(r2); + } + PASS(); +} + +/* Task 14: a 3-partition table with a high-cardinality key (u: unique per + * row) and low ones (m; g, whose second value first appears at row 3000, + * past the first vector and its scratch), generation 0 and generation 2. */ +static void sr_parted_keys(const char* root, int gen) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.0%d/t/\" " + "(table [u m x f g] (list (+ %d (til 70000)) (%% (til 70000) 5) (til 70000) (as 'F64 (%% (til 70000) 13)) " + "(div (til 70000) 3000))) {compress: %s})", + root, p + 1, p * 70000, gen ? "true" : "false"); +} +static test_result_t test_parted_concat_in_place(void) { + sr_parted_keys(SR_TMP "/kc0", 0); + sr_parted_keys(SR_TMP "/kc2", 2); + static const char* const q[] = { + "(select {u: u c: (count u) from: (.db.parted.get \"%s\" 't) by: u desc: c take: 10})", /* q16's shape */ + "(select {s: (sum x) a: (avg f) from: (.db.parted.get \"%s\" 't) by: u})", + "(select {c: (count x) from: (.db.parted.get \"%s\" 't) by: {u: u m: m}})", + NULL, + }; + for (int i = 0; q[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, q[i], SR_TMP "/kc0"); snprintf(b, sizeof b, q[i], SR_TMP "/kc2"); + int64_t s0 = ray_group_segstream_runs(); + uint64_t m = 9; + ray_t* r0 = sr_q(a, NULL); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 1, "gen 0 in place: %s", q[i]); + ray_t* r2 = sr_q(b, &m); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 2, "gen 2 in place: %s", q[i]); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "%s", q[i]); + TEST_ASSERT_FMT(m == 0, "%s: %llu materializations", q[i], (unsigned long long)m); + sr_drop(r0); sr_drop(r2); + } + PASS(); +} + +/* The same answers as the flatten: the in-place route is checked against + * the flat route forced by an expression aggregate the in-place concat + * does not take (z), projected away. A where clause would not force it: a + * parted table's filter hands the group a filtered parted table. */ +static test_result_t test_parted_concat_matches_flat(void) { + sr_parted_keys(SR_TMP "/kf0", 0); + int64_t s0 = ray_group_segstream_runs(); + ray_t* a = sr_eval("(select {s: (sum x) a: (avg f) mn: (min m) from: (.db.parted.get \"" SR_TMP "/kf0\" 't) by: u})"); + TEST_ASSERT_TRUE(ray_group_segstream_runs() - s0 == 1); + ray_t* b = sr_eval("(select {u: u s: s a: a mn: mn from: (select {s: (sum x) a: (avg f) mn: (min m) z: (sum (+ x 0)) " + "from: (.db.parted.get \"" SR_TMP "/kf0\" 't) by: u})})"); + TEST_ASSERT_TRUE(ray_group_segstream_runs() - s0 == 1); + TEST_ASSERT_TRUE(sr_same_text(a, b)); + sr_drop(a); sr_drop(b); + PASS(); +} + +/* Sample and first-key reads of generation-2 segments never materialize. */ +static test_result_t test_parted_sample_reads(void) { + sr_parted_keys(SR_TMP "/ks0", 0); + sr_parted_keys(SR_TMP "/ks2", 2); + static const char* const q[] = { + "(select {c: (count x) from: (.db.parted.get \"%s\" 't) by: m})", /* sample: low cardinality */ + "(select {c: (count x) from: (.db.parted.get \"%s\" 't) by: u take: 5})", /* unordered take: first keys */ + "(select {c: (count x) from: (.db.parted.get \"%s\" 't) by: m take: 3})", /* per partition: grp_first_keys_scan */ + "(select {c: (count x) from: (.db.parted.get \"%s\" 't) by: g take: 3})", /* first keys past the first vector */ + NULL, + }; + for (int i = 0; q[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, q[i], SR_TMP "/ks0"); snprintf(b, sizeof b, q[i], SR_TMP "/ks2"); + uint64_t m = 9; + int64_t s0 = ray_group_segstream_runs(), f0 = ray_group_firstkeys_runs(); + ray_t* r0 = sr_q(a, NULL); ray_t* r2 = sr_q(b, &m); + /* low cardinality goes per partition, not in place; the unordered + * take keeps the flatten on generation 0 and runs in place over + * generation 2's keys (its first-n passes read the parted sources, + * P3 Task 6b) */ + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == (i == 1 ? 1 : 0), "in place: %s", q[i]); + /* the per-partition takes keep the first keys read up front (a wrong + * read declines to the concat: same answer, so the route is pinned) */ + TEST_ASSERT_FMT(ray_group_firstkeys_runs() - f0 == (i >= 2 ? 2 : 0), "first keys: %s", q[i]); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "%s", q[i]); + TEST_ASSERT_FMT(m == 0, "%s: %llu materializations", q[i], (unsigned long long)m); + sr_drop(r0); sr_drop(r2); + } + PASS(); +} + +/* The strategies that read keys or inputs at stored rows or whole (R-RANDOM) + * run an in-place concat over a flat copy of the table read by range: the + * indexed route (first / last) and the serial route (a small table). + * Answers equal the flatten's (forced by an expression aggregate, projected + * away); nothing materializes. */ +static void sr_parted_small(const char* root, int gen) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.0%d/t/\" " + "(table [u m x f] (list (+ %d (til 3000)) (%% (til 3000) 5) (til 3000) (as 'F64 (%% (til 3000) 13)))) {compress: %s})", + root, p + 1, p * 3000, gen ? "true" : "false"); +} +static test_result_t test_parted_in_place_random(void) { + sr_parted_keys(SR_TMP "/kr0", 0); + sr_parted_keys(SR_TMP "/kr2", 2); + sr_parted_small(SR_TMP "/kq0", 0); + sr_parted_small(SR_TMP "/kq2", 2); + static const struct { const char* root; const char* q; const char* flat; agg_route_t route; } c[] = { + { "/kr", "(select {a: (first x) b: (last f) from: (.db.parted.get \"" SR_TMP "%s%d\" 't) by: u})", + "(select {u: u a: a b: b from: (select {a: (first x) b: (last f) z: (sum (+ x 0)) from: (.db.parted.get \"" SR_TMP "%s%d\" 't) by: u})})", + AGG_ROUTE_V2_INDEXED }, + { "/kq", "(select {s: (sum x) a: (avg f) from: (.db.parted.get \"" SR_TMP "%s%d\" 't) by: u})", + "(select {u: u s: s a: a from: (select {s: (sum x) a: (avg f) z: (sum (+ x 0)) from: (.db.parted.get \"" SR_TMP "%s%d\" 't) by: u})})", + AGG_ROUTE_V2_SERIAL_DENSE }, + }; + for (size_t i = 0; i < sizeof c / sizeof c[0]; i++) { + char a[600], b[600], f[600]; + snprintf(a, sizeof a, c[i].q, c[i].root, 0); snprintf(b, sizeof b, c[i].q, c[i].root, 2); + snprintf(f, sizeof f, c[i].flat, c[i].root, 0); + int64_t s0 = ray_group_segstream_runs(); + uint64_t m = 9; + agg_route_reset(); + ray_t* r0 = sr_q(a, NULL); + agg_route_stats_t st = agg_route_stats(); + TEST_ASSERT_FMT(st.routes[c[i].route] >= 1, "route: %s", a); + ray_t* r2 = sr_q(b, &m); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 2, "in place: %s", a); + ray_t* rf = sr_eval(f); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 2, "flattened: %s", f); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "%s", a); + TEST_ASSERT_FMT(sr_same_text(r0, rf), "flatten: %s", a); + TEST_ASSERT_FMT(m == 0, "%s: %llu materializations", b, (unsigned long long)m); + sr_drop(r0); sr_drop(r2); sr_drop(rf); + } + PASS(); +} + +/* Fix round 1, I1: a factorized-expand shaped parted table (_src key, + * _count weights). Over the flatten, v2 declines the shape (its _count + * probe) and exec_group's shortcut answers from _count; the in-place + * concat must decline it too. The shortcut's answer: one row per _src in + * table order, every aggregate the row's _count. */ +static test_result_t test_parted_factorized_count(void) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/fc0/2024.01.0%d/t/\" " + "(table [_src _count v] (list (+ %d (til 50000)) (+ 1 (%% (til 50000) 3)) (til 50000))) {compress: false})", + p + 1, p * 50000); + sr_eval_ok("(set P (.db.parted.get \"" SR_TMP "/fc0\" 't))"); + static const char* const q[] = { + "(select {c: (count v) s: (sum _count) from: P by: _src})", + "(select {c: (count _count) from: P by: _src})", + NULL, + }; + for (int i = 0; q[i]; i++) { + int64_t s0 = ray_group_segstream_runs(); + char b[256]; + snprintf(b, sizeof b, "(set R %s)", q[i]); + sr_eval_ok(b); + TEST_ASSERT_FMT(ray_group_segstream_runs() == s0, "not in place: %s", q[i]); + ray_t* a = sr_eval("(at R 'c)"); + ray_t* w = sr_eval("(at P '_count)"); + TEST_ASSERT_FMT(sr_same_text(a, w), "%s: c is the row's _count", q[i]); + ray_t* k = sr_eval("(at R '_src)"); + ray_t* t = sr_eval("(til 150000)"); + TEST_ASSERT_FMT(sr_same_text(k, t), "%s: table order", q[i]); + ray_t* n = sr_eval("(sum (at R 'c))"); + TEST_ASSERT_FMT(n && !RAY_IS_ERR(n) && n->i64 == 299997, "%s: weighted count", q[i]); + sr_drop(a); sr_drop(w); sr_drop(k); sr_drop(t); sr_drop(n); + } + PASS(); +} + +/* Fix round 1, I2: the cardinality sample partition is the narrowest (250 + * symbols: W8) and a later one wider (1000 and 5000 symbols: W16): the + * stand-in, the dense plan and the flat copy take the widest segment's + * width, not the first's. */ +static test_result_t test_parted_sym_narrow_first(void) { + static const int nsym[3] = { 250, 1000, 5000 }; + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/sn%d/2024.01.0%d/t/\" " + "(table [s u v] (list (as 'SYMBOL (map (fn [j] (format \"n%%\" (%% j %d))) (til 22000))) (+ %d (til 22000)) (til 22000))) " + "\"" SR_TMP "/sn%d/.sym\" {compress: %s})", gen, p + 1, nsym[p], p * 22000, gen, gen ? "true" : "false"); + static const char* const q[] = { + "(select {c: (count v) t: (sum v) from: (.db.parted.get \"" SR_TMP "/sn%d\" 't) by: s})", + "(select {c: (count v) t: (sum v) from: (.db.parted.get \"" SR_TMP "/sn%d\" 't) by: {s: s u: u}})", + NULL, + }; + static const char* const fq[] = { + "(select {s: s c: c t: t from: (select {c: (count v) t: (sum v) z: (sum (+ v 0)) from: (.db.parted.get \"" SR_TMP "/sn0\" 't) by: s})})", + "(select {s: s u: u c: c t: t from: (select {c: (count v) t: (sum v) z: (sum (+ v 0)) from: (.db.parted.get \"" SR_TMP "/sn0\" 't) by: {s: s u: u}})})", + }; + for (int i = 0; q[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, q[i], 0); snprintf(b, sizeof b, q[i], 2); + int64_t s0 = ray_group_segstream_runs(); + uint64_t m = 9; + ray_t* r0 = sr_q(a, NULL); ray_t* r2 = sr_q(b, &m); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 2, "in place: %s", q[i]); + ray_t* rf = sr_eval(fq[i]); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 2, "flattened: %s", fq[i]); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "%s", q[i]); + TEST_ASSERT_FMT(sr_same_text(r0, rf), "flatten: %s", q[i]); + TEST_ASSERT_FMT(m == 0, "%s: %llu materializations", q[i], (unsigned long long)m); + TEST_ASSERT_EQ_I(ray_table_nrows(r0), i ? 66000 : 5000); + sr_drop(r0); sr_drop(r2); sr_drop(rf); + } + PASS(); +} + +/* Fix round 1, minor 3: nulls in a flattened and an in-place input keep + * HAS_NULLS (a sum skips them). u pairs rows; f is null every 7th row. + * The reference is the same rows grouped as one in-memory table. */ +static test_result_t test_parted_flatten_nulls(void) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/fn0/2024.01.0%d/t/\" " + "(table [u x f] (list (div (+ %d (til 30000)) 2) (til 30000) " + "(as 'F64 (map (fn [j] (if (== 0 (%% j 7)) 0N j)) (til 30000))))) {compress: false})", + p + 1, p * 30000); + sr_eval_ok("(set M (table [u x f] (list (div (til 90000) 2) (% (til 90000) 30000) " + "(as 'F64 (map (fn [j] (if (== 0 (% (% j 30000) 7)) 0N (% j 30000))) (til 90000))))))"); + ray_t* ref = sr_eval("(select {s: (sum f) from: M by: u})"); + int64_t s0 = ray_group_segstream_runs(); + ray_t* in = sr_eval("(select {s: (sum f) from: (.db.parted.get \"" SR_TMP "/fn0\" 't) by: u})"); + TEST_ASSERT_TRUE(ray_group_segstream_runs() - s0 == 1); + ray_t* fl = sr_eval("(select {u: u s: s from: (select {s: (sum f) z: (sum (+ x 0)) from: (.db.parted.get \"" SR_TMP "/fn0\" 't) by: u})})"); + TEST_ASSERT_TRUE(ray_group_segstream_runs() - s0 == 1); + TEST_ASSERT_TRUE(sr_same_text(ref, in)); + TEST_ASSERT_TRUE(sr_same_text(ref, fl)); + sr_drop(ref); sr_drop(in); sr_drop(fl); + PASS(); +} + +/* Carry from Task 13: a SYM key over partitions of different width + * classes, grouped in place. Partition 2 is saved first (20 symbols: W8), + * partition 1 after it over 1000 symbols (W16); partition 1 is the + * cardinality sample (1000 groups over 20000 rows: the concat). */ +static test_result_t test_parted_sym_widths_in_place(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 1; p >= 0; p--) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/sw%d/2024.01.0%d/t/\" " + "(table [s v] (list (as 'SYMBOL (map (fn [j] (format \"q%%\" (%% j %d))) (til 70000))) (til 70000))) " + "\"" SR_TMP "/sw%d/.sym\" {compress: %s})", gen, p + 1, p ? 20 : 1000, gen, gen ? "true" : "false"); + static const char* const q[] = { + "(select {c: (count v) t: (sum v) from: (.db.parted.get \"" SR_TMP "/sw%d\" 't) by: s})", + "(select {c: (count v) t: (sum v) from: (.db.parted.get \"" SR_TMP "/sw%d\" 't) by: s desc: t take: 7})", /* sums are distinct: no ties */ + NULL, + }; + for (int i = 0; q[i]; i++) { + char a[512], b[512]; + snprintf(a, sizeof a, q[i], 0); snprintf(b, sizeof b, q[i], 2); + int64_t s0 = ray_group_segstream_runs(); + uint64_t m = 9; + ray_t* r0 = sr_q(a, NULL); ray_t* r2 = sr_q(b, &m); + TEST_ASSERT_FMT(ray_group_segstream_runs() - s0 == 2, "in place: %s", q[i]); + TEST_ASSERT_FMT(sr_same_text(r0, r2), "%s", q[i]); + TEST_ASSERT_FMT(m == 0, "%s: %llu materializations", q[i], (unsigned long long)m); + TEST_ASSERT_EQ_I(ray_table_nrows(r0), i ? 7 : 1000); + /* the flatten (forced by an expression aggregate) answers the same */ + char f[600]; + snprintf(f, sizeof f, "(select {s: s c: c t: t from: (select {c: (count v) t: (sum v) z: (sum (+ v 0)) " + "from: (.db.parted.get \"" SR_TMP "/sw0\" 't) by: s%s})})", i ? " desc: t take: 7" : ""); + s0 = ray_group_segstream_runs(); + ray_t* rf = sr_eval(f); + TEST_ASSERT_FMT(ray_group_segstream_runs() == s0, "flattened: %s", f); + TEST_ASSERT_FMT(sr_same_text(r0, rf), "flatten: %s", q[i]); + sr_drop(r0); sr_drop(r2); sr_drop(rf); + } + PASS(); +} + +/* Table W: a column for every v2 strategy's shape (200000 rows). + * sk skewed key, 200000-slot range, mostly 0 (shared dense: max n) + * t 1000 sparse groups (table stack) h near-unique (radix) + * c1, c2 composite whose raw range product overflows (compacted dense) + * nk nullable I32 key of 50 values f nullable F64 with fractions */ +static void sr_w_tables(void) { + sr_eval_ok("(set W (table [k g s f n sk t c1 c2 nk h d u] (list i (as 'I16 (% i 7)) " + "(take ['a 'b 'c 'd 'e] 200000) " + "(as 'F64 (map (fn [j] (if (== 0 (% j 13)) 0N (* j 0.37))) i)) (as 'I32 (- 0 i)) " + "(map (fn [j] (if (== 0 (% j 100)) j 0)) i) (* (% i 1000) 1000003) " + "(* (% i 100) 1000) (* (% i 50) 1000) " + "(as 'I32 (map (fn [j] (if (== 0 (% j 10)) 0N (% j 50))) i)) (% (* i 7919) 1000003) " + "(as 'DATE (% i 900)) (as 'U8 (% i 200)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w0/\" W {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w2/\" W {compress: true})"); +} +#define SR_W0 "(.db.splayed.get \"" SR_TMP "/w0/\")" +#define SR_W2 "(.db.splayed.get \"" SR_TMP "/w2/\")" + +/* The F64 column `col` of q's result, generation 0 against 2: equal bits. */ +static test_result_t sr_f64_bits_same(const char* q, const char* col) { + ray_t* out[2]; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? SR_W2 : SR_W0); + out[gen] = sr_eval(q); + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "gen %d: %s", gen, q); + } + ray_t* a = ray_table_get_col(out[0], ray_sym_intern(col, strlen(col))); + ray_t* b = ray_table_get_col(out[1], ray_sym_intern(col, strlen(col))); + TEST_ASSERT_TRUE(a && b && a->type == RAY_F64 && b->type == RAY_F64 && a->len == b->len && a->len > 0); + TEST_ASSERT_FMT(memcmp(ray_data(a), ray_data(b), (size_t)a->len * 8) == 0, "%s: %s bits differ", q, col); + ray_release(out[0]); ray_release(out[1]); + PASS(); +} + +/* Every v2 strategy over staged keys and inputs: equal answers, nothing + * materialized, and the strategy the line names is the one that ran. */ +static test_result_t test_v2_route_shapes(void) { + sr_w_tables(); + /* The strategy choice weighs replicated slabs against partition traffic + * per worker (1 worker: no partitions; 8: {nk s} partitions), so the + * routes are pinned at 3 workers; srr_pool_teardown restores the pool. */ + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(3), RAY_OK); + enum { R_LOCAL = 1, R_PART, R_SHARED, R_RADIX, R_TS, R_SH }; + static const struct { const char* q; int route; } qs[] = { + { "(select {mx: (max n) from: T by: sk})", R_SHARED }, + { "(select {c: (count k) s: (sum f) a: (avg g) from: T by: t})", R_TS }, + { "(select {c: (count k) mx: (max f) from: T where: (> k 1000) by: t})", R_TS }, + { "(select {c: (count k) s: (sum g) from: T where: (> k 1000) by: h})", R_RADIX }, + { "(select {p: (pearson_corr f g) c: (count k) from: T by: {h: h g: g}})", R_RADIX }, + { "(select {c: (count k) s: (sum f) from: T by: {c1: c1 c2: c2}})", R_LOCAL }, + { "(select {c: (count k) s: (sum f) mn: (min n) from: T by: nk})", R_LOCAL }, + { "(select {s: (sum f) v: (var n) from: T where: (> g 2) by: s})", R_LOCAL }, + { "(select {x: (max f) c: (count k) from: T where: (> k 1000) by: {d: d u: u}})", R_PART }, + { "(select {x: (sum f) p: (pearson_corr f n) from: T by: {d: d u: u}})", R_PART }, + { "(select {c: (count k) a: (avg nk) from: T by: {nk: nk s: s}})", R_LOCAL }, + { "(select {p: (pearson_corr f g) w: (wavg g f) from: T by: g})", R_LOCAL }, /* binary inputs */ + }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) { + agg_route_reset(); + test_result_t r = sr_same_on(SR_W0, SR_W2, qs[i].q, 0); + if (r.status != TEST_PASS) return r; + agg_route_stats_t rs = agg_route_stats(); /* the generation-2 run */ + bool ok = false; + switch (qs[i].route) { + case R_LOCAL: ok = rs.routes[AGG_ROUTE_V2_DENSE] && rs.dense_strategy == AGG_DENSE_TASK_LOCAL; break; + case R_PART: ok = rs.routes[AGG_ROUTE_V2_DENSE] && rs.dense_strategy == AGG_DENSE_PARTITIONED; break; + case R_SHARED: ok = rs.routes[AGG_ROUTE_V2_DENSE] && rs.dense_strategy == AGG_DENSE_SHARED; break; + case R_RADIX: ok = rs.routes[AGG_ROUTE_V2_RADIX] > 0; break; + case R_TS: ok = rs.routes[AGG_ROUTE_V2_TABLESTACK] > 0; break; + } + TEST_ASSERT_FMT(ok, "%s: not on route %d (dense strategy %d)", qs[i].q, qs[i].route, (int)rs.dense_strategy); + } + /* the small hash (the radix strategy's allocation fallback), forced: + * staged keys are grouped by key words, merged and emitted from them. + * Its group order follows the workers' ranges, so the lines sort. */ + static const char* const qsh[] = { + "(select {from: (select {c: (count k) s: (sum f) from: T by: t}) asc: t})", + "(select {from: (select {c: (count k) mx: (max f) from: T where: (> k 1000) by: {t: t s: s}}) asc: t})", + "(select {from: (select {c: (count k) s: (sum g) from: T by: {nk: nk h: h}}) asc: h})", + NULL }; + agg_test_force_smallhash(true); + for (int i = 0; qsh[i]; i++) { + agg_route_reset(); + test_result_t r = sr_same_on(SR_W0, SR_W2, qsh[i], 0); + if (r.status != TEST_PASS) { agg_test_force_smallhash(false); return r; } + TEST_ASSERT_FMT(agg_route_stats().routes[AGG_ROUTE_V2_SMALLHASH] > 0, "%s: not small hash", qsh[i]); + } + agg_test_force_smallhash(false); + /* random strategies take plain columns: the serial path (below the + * parallel threshold), the indexed driver (median), first-N */ + sr_eval_ok("(set W5 (take W 50000))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w50/\" W5 {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/w52/\" W5 {compress: true})"); + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/w50/\")", "(.db.splayed.get \"" SR_TMP "/w52/\")", + "(select {c: (count k) s: (sum f) from: T by: {g: g s: s}})", UINT64_MAX); + if (r.status != TEST_PASS) return r; + if ((r = sr_same_on(SR_W0, SR_W2, "(select {m: (med f) c: (count k) from: T by: g})", UINT64_MAX)).status != TEST_PASS) return r; + if ((r = sr_same_on(SR_W0, SR_W2, "(select {c: (count k) s: (sum n) from: T by: h take: 5})", UINT64_MAX)).status != TEST_PASS) return r; + /* k materialized before the query: read in place beside staged inputs */ + sr_eval_ok("(set W2M " SR_W2 ")"); + ray_t* t = sr_eval("W2M"); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* tcol = ray_table_col(t, ray_sym_intern("t", 1)); + TEST_ASSERT_TRUE(tcol && !RAY_IS_ERR(tcol)); + sr_drop(t); + if ((r = sr_same_on(SR_W0, "W2M", "(select {c: (count k) s: (sum f) from: T by: t})", 0)).status != TEST_PASS) return r; + PASS(); +} + +/* A SYM key over a shared symfile larger than the table: its codes are + * positions in a 400000-symbol domain, so the dense plan bounds the key from + * the directory statistics. Those exclude the null rows, whose code is 0, + * far below the used codes [90000, 139000]: the bounds must still span it + * (139001 slots, within the row count, so the plan stays dense). */ +static test_result_t test_v2_sym_shared_dom(void) { + sr_eval_ok("(set A (table [s v] (list (as 'SYMBOL (map (fn [j] (format \"y%\" j)) (til 400000))) (til 400000))))"); + sr_eval_ok("(set B (table [s v] (list (as 'SYMBOL (map (fn [j] (if (== 0 (% j 11)) \"\" " + "(format \"y%\" (+ 90000 (* 1000 (% j 50)))))) (til 150000))) (til 150000))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sda/\" A \"" SR_TMP "/sd.sym\" {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sd0/\" B \"" SR_TMP "/sd.sym\" {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sd2/\" B \"" SR_TMP "/sd.sym\" {compress: true})"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(3), RAY_OK); /* dense at any core count */ + static const char* const qs[] = { + "(select {c: (count v) s: (sum v) from: T by: s})", + "(select {c: (count v) mx: (max v) from: T where: (> v 1000) by: s})", + NULL }; + for (int i = 0; qs[i]; i++) { + agg_route_reset(); + test_result_t r = sr_same_on("(.db.splayed.get \"" SR_TMP "/sd0/\" \"" SR_TMP "/sd.sym\")", + "(.db.splayed.get \"" SR_TMP "/sd2/\" \"" SR_TMP "/sd.sym\")", qs[i], 0); + if (r.status != TEST_PASS) return r; + agg_route_stats_t rs = agg_route_stats(); + TEST_ASSERT_FMT(rs.routes[AGG_ROUTE_V2_DENSE] > 0, "%s: not dense (plan %d)", qs[i], (int)rs.dense_plan_available); + ray_t* out = sr_eval(qs[i]); /* T is the generation-2 table */ + TEST_ASSERT_FMT(out && !RAY_IS_ERR(out) && ray_table_nrows(out) == 51, "%s: groups", qs[i]); + sr_drop(out); + } + PASS(); +} + +/* Float sums keep their bits across generations on every strategy: the + * aggregates fold row by row into their states, in row order, whatever + * the pieces. */ +static test_result_t test_v2_f64_bits(void) { + sr_w_tables(); + static const char* const qs[] = { + "(select {s: (sum f) from: T by: g})", /* task-local dense */ + "(select {s: (sum f) from: T where: (> k 77) by: g})", /* dense, selection */ + "(select {s: (sum f) from: T by: {d: d u: u}})", /* partitioned */ + "(select {s: (sum f) from: T by: h})", /* radix */ + "(select {s: (sum f) from: T by: t})", /* table stack */ + "(select {s: (sum f) from: T where: (> k 77) by: t})", + NULL }; + /* (the small hash folds worker partials whose rows follow the pool's + * scheduling: its float bits vary run to run in either generation) */ + for (int i = 0; qs[i]; i++) { + test_result_t r = sr_f64_bits_same(qs[i], "s"); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* The shared dense slab's own dispatch: a skewed key (mostly 0) over 197108 + * rows takes the shared dense strategy. */ +static test_result_t test_v2_shared_route(void) { + sr_eval_ok("(set X (table [sk n] (list (map (fn [j] (if (== 0 (% j 100)) j 0)) (til 197108)) " + "(as 'I32 (- 0 (til 197108))))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/xsh/\" X {compress: true})"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(3), RAY_OK); + static const char* const q = "(select {mx: (max n) from: B by: sk})"; + sr_eval_ok("(set B (.db.splayed.get \"" SR_TMP "/xsh/\"))"); + agg_route_reset(); + ray_t* ok = sr_eval(q); + TEST_ASSERT_TRUE(ok && !RAY_IS_ERR(ok)); + sr_drop(ok); + TEST_ASSERT_EQ_I((int)agg_route_stats().dense_strategy, AGG_DENSE_SHARED); + PASS(); +} + +/* ---- Task 14b: group keys decoded once per run ---- */ + +/* RQ: 600000 rows; k a near-unique wide I64 key (j*7919 mod 600011 is + * injective over the rows, times 1000003: a range far past the rows, so + * no dense plan), m = j % 7, v = j, f = j / 8, p = j*7919 mod 500009 (a + * wide dense key: the partitioned strategy); saved splayed (rq0, rq2) + * and as three 200000-row partitions (rp0, rp2). */ +static void sr_radix_tables(void) { + sr_eval_ok("(set jr (til 600000))"); + sr_eval_ok("(set RQ (table [k m v f p] (list (* (% (* jr 7919) 600011) 1000003) (% jr 7) jr (/ (as 'F64 jr) 8.0) " + "(% (* jr 7919) 500009))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/rq0/\" RQ {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/rq2/\" RQ {compress: true})"); + for (int p = 0; p < 3; p++) + for (int gen = 0; gen <= 2; gen += 2) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/rp%d/2024.01.0%d/t/\" (take (drop RQ %d) 200000) {compress: %s})", + gen, p + 1, p * 200000, gen ? "true" : "false"); +} + +/* Bytes decoded so far of column `name` of T: its own count, or the sum + * over a parted column's encoded segments; *full: the column's + * generation-0 bytes. */ +static uint64_t sr_col_dec_any(const char* name, uint64_t* full) { + ray_t* t = sr_eval("T"); + ray_t* ec = ray_table_get_col_enc(t, ray_sym_intern(name, strlen(name))); + uint64_t r = 0; + *full = 0; + if (ec) { + ray_enccol_t* e = ray_enccol_of(ec); + if (e->kind == RAY_ENCCOL_SINGLE) { + r = atomic_load(&e->decoded_bytes); + *full = (uint64_t)e->len * ray_enccol_esz(e); + } else for (int64_t i = 0; e->wrapper && i < e->wrapper->len; i++) { + ray_t* sg = ray_enccol_seg(ec, i); + if (!sg || sg->type != RAY_ENCCOL) continue; + ray_enccol_t* se = ray_enccol_of(sg); + r += atomic_load(&se->decoded_bytes); + *full += (uint64_t)se->len * ray_enccol_esz(se); + } + } + sr_drop(t); + return r; +} + +/* q16's shape, a two-input aggregate and two keys on the v2 radix route, + * and a wide dense key on the partitioned strategy (its histogram reads the + * key, its scatter the input), + * splayed and parted generation 2: each column q reads decodes once per + * run (the key once across the count and the scatter, the parted key's + * bounds and its cardinality sample from its segments' directories, the + * second key's compaction not attempted when it cannot fit), within 5% of + * its bytes (the samplers' point reads, the vectors a chunk starts + * inside); the answers and routes are generation 0's. The 1.05 bound + * holds because k here is FOR_BP, which the samplers' point reads serve: + * a key whose vectors are mostly RLE (the ClickBench UserID) decodes + * 1.052-1.055 per run, the table-stack precheck's sampled rows each + * decoding a vector (the point read does not serve RLE). */ +static test_result_t test_v2_radix_decode_once(void) { + sr_radix_tables(); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + static const struct { const char* q; const char* cols[3]; bool partitioned; } qs[] = { + { "(select {k: k c: (count k) from: T by: k desc: c take: 10})", { "k", NULL }, false }, + { "(select {c: (count v) s: (sum v) from: T by: k})", { "k", "v", NULL }, false }, + { "(select {c: (count v) s: (sum v) from: T by: {k: k m: m}})", { "k", "m", "v" }, false }, + { "(select {c: (count v) s: (sum v) from: T by: p})", { "p", "v", NULL }, true }, + }; + static const char* const t2[] = { "(.db.splayed.get \"" SR_TMP "/rq2/\")", "(.db.parted.get \"" SR_TMP "/rp2\" 't)" }; + static const char* const t0[] = { "(.db.splayed.get \"" SR_TMP "/rq0/\")", "(.db.parted.get \"" SR_TMP "/rp0\" 't)" }; + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) + for (int s = 0; s < 2; s++) { + test_result_t r = sr_same_route(t0[s], t2[s], qs[i].q); + if (r.status != TEST_PASS) return r; + sr_evalf_ok("(set T %s)", t2[s]); + sr_drop(sr_eval(qs[i].q)); /* binds and loads once: the pin is per run */ + uint64_t before[3], full[3]; + for (int c = 0; c < 3 && qs[i].cols[c]; c++) before[c] = sr_col_dec_any(qs[i].cols[c], &full[c]); + agg_route_reset(); + ray_t* res = sr_eval(qs[i].q); + agg_route_stats_t st = agg_route_stats(); + TEST_ASSERT_FMT(res && !RAY_IS_ERR(res), "%s: %s", qs[i].q, ray_error_msg() ? ray_error_msg() : ""); + sr_drop(res); + if (qs[i].partitioned) + TEST_ASSERT_FMT(st.routes[AGG_ROUTE_V2_DENSE] == 1 && st.dense_strategy == AGG_DENSE_PARTITIONED, + "%s (%s): not the partitioned dense route", qs[i].q, s ? "parted" : "splayed"); + else + TEST_ASSERT_FMT(st.routes[AGG_ROUTE_V2_RADIX] == 1, "%s (%s): not the radix route", qs[i].q, s ? "parted" : "splayed"); + for (int c = 0; c < 3 && qs[i].cols[c]; c++) { + uint64_t f; + double x = (double)(sr_col_dec_any(qs[i].cols[c], &f) - before[c]) / (double)full[c]; + TEST_ASSERT_FMT(full[c] > 0 && x >= 1.0 && x <= 1.05, "%s (%s): %s decoded %.4fx", qs[i].q, + s ? "parted" : "splayed", qs[i].cols[c], x); + } + } + /* Staging that would not fit the last-level cache keeps the two passes: + * the key decodes twice (count and scatter), the input once (the + * scatter alone reads it; each pass re-reads the vector its chunks start + * inside); the same answer. */ + ray_cache_llc_set_for_test(4096); + static const char* const q2 = "(select {c: (count v) s: (sum v) from: T by: k})"; + test_result_t r = sr_same_route(t0[0], t2[0], q2); + if (r.status != TEST_PASS) { ray_cache_llc_set_for_test(0); return r; } + sr_evalf_ok("(set T %s)", t2[0]); + uint64_t fk, fv, k0 = sr_col_dec_any("k", &fk), v0 = sr_col_dec_any("v", &fv); + agg_route_reset(); + ray_t* res = sr_eval(q2); + agg_route_stats_t st = agg_route_stats(); + ray_cache_llc_set_for_test(0); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + sr_drop(res); + TEST_ASSERT_TRUE(st.routes[AGG_ROUTE_V2_RADIX] == 1); + double xk = (double)(sr_col_dec_any("k", &fk) - k0) / (double)fk, xv = (double)(sr_col_dec_any("v", &fv) - v0) / (double)fv; + TEST_ASSERT_FMT(xk >= 2.0 && xk <= 2.1 && xv >= 1.0 && xv <= 1.05, "two passes: k %.4fx, v %.4fx", xk, xv); + PASS(); +} + +/* Byte-equal answers (.csv.write) of generation 0 and 2 over the radix + * route: one and two keys, a SYM key beside a wide one, F64 sums (their + * bits: the records of a partition keep input order), q16's top 10, and a + * ragged parted table (partition 3 lacks v and f: synthetic null + * segments) against its generation-0 twin. */ +static bool sr_csv_of(const char* q, const char* path, char** out, size_t* n) { + char e[1024]; + snprintf(e, sizeof e, "(.csv.write %s \"%s\")", q, path); + ray_t* r = sr_eval(e); + bool ok = r && !RAY_IS_ERR(r); + sr_drop(r); + FILE* f = ok ? fopen(path, "rb") : NULL; + if (!f) return false; + fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET); + *out = malloc((size_t)len + 1); + *n = fread(*out, 1, (size_t)len, f); + fclose(f); + return *n == (size_t)len; +} +static test_result_t sr_csv_same(const char* t0, const char* t2, const char* q) { + char p0[512], p2[512]; + snprintf(p0, sizeof p0, "%s/a0.csv", sr_root()); snprintf(p2, sizeof p2, "%s/a2.csv", sr_root()); + char* b[2] = { NULL, NULL }; + size_t n[2] = { 0, 0 }; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? t2 : t0); + if (!sr_csv_of(q, gen ? p2 : p0, &b[gen], &n[gen])) { free(b[0]); free(b[1]); FAIL("csv"); } + } + bool same = n[0] == n[1] && n[0] > 0 && memcmp(b[0], b[1], n[0]) == 0; + free(b[0]); free(b[1]); + TEST_ASSERT_FMT(same, "%s: generation 0 and 2 differ (%zu / %zu bytes)", q, n[0], n[1]); + PASS(); +} +static test_result_t test_v2_radix_answers(void) { + sr_radix_tables(); + sr_eval_ok("(set RS (table [s k v f] (list (as 'SYMBOL (map (fn [j] (format \"w%\" (% j 50))) jr)) " + "(* (% (* jr 7919) 600011) 1000003) jr (/ (as 'F64 jr) 8.0))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/rs0/\" RS {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/rs2/\" RS {compress: true})"); + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/rr%d/2024.01.0%d/t/\" (select {%s from: (take (drop RQ %d) 200000)}) {compress: %s})", + gen, p + 1, p == 2 ? "k: k m: m" : "k: k m: m v: v f: f", p * 200000, gen ? "true" : "false"); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + static const char* const qs[] = { + "(select {c: (count v) s: (sum v) a: (sum f) from: T by: k})", + "(select {c: (count v) a: (sum f) mx: (max v) from: T by: {k: k m: m}})", + "(select {k: k c: (count k) from: T by: k desc: c take: 10})", + "(select {c: (count v) a: (sum f) from: T where: (> v 1000) by: k})", + NULL, + }; + static const char* const t2[] = { "(.db.splayed.get \"" SR_TMP "/rq2/\")", "(.db.parted.get \"" SR_TMP "/rp2\" 't)" }; + static const char* const t0[] = { "(.db.splayed.get \"" SR_TMP "/rq0/\")", "(.db.parted.get \"" SR_TMP "/rp0\" 't)" }; + for (int i = 0; qs[i]; i++) + for (int s = 0; s < 2; s++) { + agg_route_reset(); + test_result_t r = sr_csv_same(t0[s], t2[s], qs[i]); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(agg_route_stats().routes[AGG_ROUTE_V2_RADIX] == 2, "%s: not radix on both", qs[i]); + } + agg_route_reset(); + test_result_t r = sr_csv_same("(.db.splayed.get \"" SR_TMP "/rs0/\")", "(.db.splayed.get \"" SR_TMP "/rs2/\")", + "(select {c: (count v) a: (sum f) from: T by: {s: s k: k}})"); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_TRUE(agg_route_stats().routes[AGG_ROUTE_V2_RADIX] == 2); + agg_route_reset(); + r = sr_csv_same("(.db.parted.get \"" SR_TMP "/rr0\" 't)", "(.db.parted.get \"" SR_TMP "/rr2\" 't)", + "(select {c: (count v) s: (sum v) a: (sum f) from: T by: k})"); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_TRUE(agg_route_stats().routes[AGG_ROUTE_V2_RADIX] == 2); + PASS(); +} + +/* Fix round 1: the record order of a radix partition. RO: 600000 rows, + * 40000 groups of 15 rows each spread over the whole table (k = (j * + * 7919 mod 40000) * 1000003, a wide key: radix), s a SYM of the group, f = j / 7.0 + * (an inexact sum: its bits follow the order the records arrive in). At + * 2 and 8 workers, `by k` and `by {s k}` answer byte for byte the same + * (.csv.write) on generation 0, on generation 2 through the fused pass + * (the key decodes once), and on generation 2 through the two passes + * (forced by a 4 KiB last-level cache: the key decodes twice); the fused + * pass also on three partitions. A phase 2 that walked a partition's + * chunk runs in any other order changes the sums. */ +static test_result_t test_v2_radix_record_order(void) { + sr_eval_ok("(set jo (til 600000))"); + sr_eval_ok("(set RO (table [s k f] (list (as 'SYMBOL (map (fn [j] (format \"w%\" (% (% (* j 7919) 40000) 50))) jo)) " + "(* (% (* jo 7919) 40000) 1000003) (/ (as 'F64 jo) 7.0))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/ro0/\" RO {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/ro2/\" RO {compress: true})"); + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/rop/2024.01.0%d/t/\" (take (drop RO %d) 200000) {compress: true})", + p + 1, p * 200000); + static const char* const qs[] = { + "(select {c: (count f) a: (sum f) from: T by: k})", + "(select {c: (count f) a: (sum f) from: T by: {s: s k: k}})", + }; + /* layouts: generation 0, fused generation 2, two-pass generation 2, fused parted generation 2 */ + static const char* const tb[] = { + "(.db.splayed.get \"" SR_TMP "/ro0/\")", "(.db.splayed.get \"" SR_TMP "/ro2/\")", + "(.db.splayed.get \"" SR_TMP "/ro2/\")", "(.db.parted.get \"" SR_TMP "/rop\" 't)", + }; + static const char* const tn[] = { "gen 0", "gen 2 fused", "gen 2 two passes", "gen 2 parted fused" }; + static const int workers[] = { 2, 8 }; + char path[512]; + snprintf(path, sizeof path, "%s/ro.csv", sr_root()); + for (int w = 0; w < 2; w++) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(workers[w]), RAY_OK); + for (int i = 0; i < 2; i++) { + char* ref = NULL; size_t nref = 0; + for (int l = 0; l < 4; l++) { + sr_evalf_ok("(set T %s)", tb[l]); + sr_drop(sr_eval(qs[i])); /* binds and loads once */ + uint64_t fk, k0 = sr_col_dec_any("k", &fk); + if (l == 2) ray_cache_llc_set_for_test(4096); + agg_route_reset(); + char* b = NULL; size_t n = 0; + bool ok = sr_csv_of(qs[i], path, &b, &n); + agg_route_stats_t st = agg_route_stats(); + ray_cache_llc_set_for_test(0); + double xk = l ? (double)(sr_col_dec_any("k", &fk) - k0) / (double)fk : 0.0; + bool route = st.routes[AGG_ROUTE_V2_RADIX] == 1 && + (l == 0 || (l == 2 ? xk >= 2.0 && xk <= 2.2 : xk >= 1.0 && xk <= 1.05)); + bool same = ok && (l == 0 || (n == nref && memcmp(b, ref, n) == 0)); + if (l == 0 && ok) { ref = b; nref = n; } else free(b); + if (!ok || !route || !same) { + free(ref); + TEST_ASSERT_FMT(ok, "%s, %d workers, %s: csv", qs[i], workers[w], tn[l]); + TEST_ASSERT_FMT(route, "%s, %d workers, %s: radix %llu, key decoded %.4fx", qs[i], workers[w], tn[l], + (unsigned long long)st.routes[AGG_ROUTE_V2_RADIX], xk); + TEST_ASSERT_FMT(same, "%s, %d workers: %s differs from gen 0 (%zu / %zu bytes)", qs[i], workers[w], tn[l], n, nref); + } + } + free(ref); + } + } + PASS(); +} + +/* Task 17i: the fused pass stages only the sources it decodes; a plain + * column and the positions are read in place by its scatter. RC: 300000 + * rows, k a wide encoded I64, s an encoded SYM, g an I16, m, v and f encoded; the + * computed key (+ m 1) and inputs (* v 3), (* f 2.0) are plain, and so + * are g and s once their materializations are published (`at`), as the + * keys of every width the scatter widens in place. Each shape answers + * byte for byte (.csv.write) as generation 0 at 2 and 4 workers, splayed + * and on three partitions, on the radix route with the compact fused + * phase 1 (whole records under a where: sel mode); on partitions the + * route is checked for the shape without a plain column or a where (a + * computed column takes the per-partition route there, a where the two + * passes). */ +static test_result_t test_v2_radix_compact_staging(void) { + sr_eval_ok("(set jc (til 300000))"); + sr_eval_ok("(set RC (table [s k m g v f w x y z] (list (as 'SYMBOL (map (fn [j] (format \"w%\" (% j 70))) jc)) " + "(* (% (* jc 7919) 600011) 1000003) (% jc 5) (as 'I16 (- (% jc 9) 4)) jc (/ (as 'F64 jc) 9.0) " + "(* (% jc 40000) 1000003) (/ (as 'F64 (% (* jc 31) 1009)) 7.0) " + "(as 'I32 (- (% (* jc 13) 2003) 1000)) (as 'I16 (- (% (* jc 17) 401) 200)))))"); + for (int gen = 0; gen <= 2; gen += 2) { + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/rc%d/\" RC {compress: %s})", gen, gen ? "true" : "false"); + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/rcp%d/2024.01.0%d/t/\" (take (drop RC %d) 100000) {compress: %s})", + gen, p + 1, p * 100000, gen ? "true" : "false"); + } + static const struct { const char* q; uint8_t p1; bool parted_route; bool pub; bool splayed_only; } qs[] = { + { "(select {c: (count v) a: (sum f) x: (sum (* v 3)) from: T by: {k: k j: (+ m 1)}})", AGG_RADIX_P1_FUSED_COMPACT, false, false, false }, + { "(select {x: (sum (* v 3)) y: (sum (* f 2.0)) mx: (max v) from: T by: {s: s k: k}})", AGG_RADIX_P1_FUSED_COMPACT, false, false, false }, + { "(select {c: (count v) a: (sum f) mx: (max v) from: T by: {s: s k: k}})", AGG_RADIX_P1_FUSED_COMPACT, true, false, false }, + { "(select {c: (count v) a: (sum f) y: (sum g) from: T by: {g: g k: k s: s}})", AGG_RADIX_P1_FUSED_COMPACT, false, true, false }, + { "(select {c: (count v) a: (sum f) from: T where: (> v 1000) by: {s: s k: k}})", AGG_RADIX_P1_FUSED_RECORDS, false, false, false }, + /* Fix round 1: two-input aggregates first, in the middle and last, + * beside inputs of other widths (F64 x, I32 y, I16 z): each input + * staged at its own field (the record's order). Splayed only: a + * parted table's two-input aggregates are wrong on generation 0 + * itself (and on the base), a separate defect. */ + { "(select {c: (pearson_corr x y) s: (sum z) mx: (max z) from: T by: w})", AGG_RADIX_P1_FUSED_COMPACT, false, false, true }, + { "(select {s: (sum z) c: (wsum y x) mx: (max y) from: T by: w})", AGG_RADIX_P1_FUSED_COMPACT, false, false, true }, + { "(select {s: (sum z) a: (sum y) c: (cov z y) from: T by: w})", AGG_RADIX_P1_FUSED_COMPACT, false, false, true }, + { "(select {a: (wavg z x) b: (scov y z) c: (sum x) d: (pearson_corr x z) from: T by: {w: w s: s}})", AGG_RADIX_P1_FUSED_COMPACT, false, false, true }, + }; + static const char* const t0[] = { "(.db.splayed.get \"" SR_TMP "/rc0/\")", "(.db.parted.get \"" SR_TMP "/rcp0\" 't)" }; + static const char* const t2[] = { "(.db.splayed.get \"" SR_TMP "/rc2/\")", "(.db.parted.get \"" SR_TMP "/rcp2\" 't)" }; + static const int workers[] = { 2, 4 }; + char path[512]; + snprintf(path, sizeof path, "%s/rc.csv", sr_root()); + for (int w = 0; w < 2; w++) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(workers[w]), RAY_OK); + for (size_t i = 0; i < sizeof qs / sizeof qs[0]; i++) + for (int l = 0; l < (qs[i].pub || qs[i].splayed_only ? 1 : 2); l++) { + char* b[2] = { NULL, NULL }; + size_t n[2] = { 0, 0 }; + agg_route_stats_t st = { 0 }; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? t2[l] : t0[l]); + if (qs[i].pub) { sr_eval_ok("(set z (+ (at T 'g) 0))"); sr_eval_ok("(set z (first (at T 's)))"); } + agg_route_reset(); + bool ok = sr_csv_of(qs[i].q, path, &b[gen], &n[gen]); + st = agg_route_stats(); + if (!ok) { free(b[0]); free(b[1]); FAIL("csv"); } + } + bool same = n[0] == n[1] && n[0] > 0 && memcmp(b[0], b[1], n[0]) == 0; + free(b[0]); free(b[1]); + TEST_ASSERT_FMT(same, "%s (%s, %d workers): generation 0 and 2 differ (%zu / %zu bytes)", qs[i].q, + l ? "parted" : "splayed", workers[w], n[0], n[1]); + if (l && !qs[i].parted_route) continue; + TEST_ASSERT_FMT(st.routes[AGG_ROUTE_V2_RADIX] == 1 && st.radix_phase1 == qs[i].p1, + "%s (%s, %d workers): radix %llu, phase 1 %u, want %u", qs[i].q, + l ? "parted" : "splayed", workers[w], + (unsigned long long)st.routes[AGG_ROUTE_V2_RADIX], st.radix_phase1, qs[i].p1); + } + } + PASS(); +} + +/* The parted directory consumer (design (b)): a parted key's dense bounds + * come from its segments' statistics. Three partitions of 70000 rows; + * k = j*7 % 1000, except partition 2's chunk 0, j*7 % 5001 with a null + * every 100 rows. 1000 groups take the in-place concat; the answer is + * generation 0's. */ +static void sr_mixed_parted(const char* root, int gen) { + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.0%d/t/\" (table [k v] (list %s (til 70000))) {compress: %s})", + root, p + 1, + p == 1 ? "(map (fn [j] (if (< j 65536) (if (== 0 (% j 100)) 0N (% (* j 7) 5001)) (% (* j 7) 1000))) (til 70000))" + : "(% (* (til 70000) 7) 1000)", + gen ? "true" : "false"); +} +static test_result_t test_idx_info_table(void) { + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_enc_counters_reset(); + ray_t* d = sr_eval("(.idx.info T 'k)"); + TEST_ASSERT_TRUE(d && !RAY_IS_ERR(d)); + ray_t* g = sr_eval("(at (.idx.info T 'k) 'gen)"); + TEST_ASSERT_EQ_I(g->i64, 2); + ray_t* m = sr_eval("(at (.idx.info T 'k) 'materialized)"); + TEST_ASSERT_FALSE(m->b8); + ray_t* e = sr_eval("(sum (value (at (.idx.info T 'g) 'enc)))"); /* every vector has one encoding */ + TEST_ASSERT_TRUE(e && !RAY_IS_ERR(e) && e->i64 == 196); /* 200000 rows: 196 vectors */ + ray_t* rb = sr_eval("(at (.idx.info T 'k) 'raw_bytes)"); + TEST_ASSERT_EQ_I(rb->i64, 200000 * 8); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_EQ_U(k.materialized, 0); + TEST_ASSERT_EQ_U(k.decoded_bytes, 0); + sr_eval_ok("(sum (at T 'g))"); /* range reads: still not materialized */ + ray_t* m2 = sr_eval("(at (.idx.info T 'g) 'materialized)"); + TEST_ASSERT_FALSE(m2->b8); + sr_eval_ok("(set gg (at T 'g))"); /* set forces the lazy: materializes */ + sr_eval_ok("(count gg)"); + ray_t* m3 = sr_eval("(at (.idx.info T 'g) 'materialized)"); + TEST_ASSERT_TRUE(m3->b8); + ray_t* g0 = sr_eval("(at (.idx.info (.db.splayed.get \"" SR_G0 "\") 'k) 'gen)"); + TEST_ASSERT_EQ_I(g0->i64, 0); + /* ruling I5: a ragged generation-0 parted column reports generation 0 */ + sr_parted_xy(SR_TMP "/irg", 0, true, false); + ray_t* gr = sr_eval("(at (.idx.info (.db.parted.get \"" SR_TMP "/irg\" 't) 'y) 'gen)"); + TEST_ASSERT_TRUE(gr && !RAY_IS_ERR(gr) && gr->i64 == 0); + sr_drop(d); sr_drop(g); sr_drop(m); sr_drop(e); sr_drop(rb); + sr_drop(m2); sr_drop(m3); sr_drop(g0); sr_drop(gr); + PASS(); +} + +/* The reported number of `src` (an integer-valued rayfall expression). */ +static int64_t ii_i64(const char* src) { + ray_t* r = sr_eval(src); + int64_t v = (r && !RAY_IS_ERR(r)) ? r->i64 : INT64_MIN; + sr_drop(r); + return v; +} +static bool ii_err(const char* src, const char* code, const char* needle) { + ray_t* r = sr_eval(src); + bool ok = r && RAY_IS_ERR(r) && strcmp(ray_err_code(r), code) == 0 && + ray_error_msg() && strstr(ray_error_msg(), needle); + sr_drop(r); + return ok; +} + +/* STR pool bytes, parted sums and segments, a mixed parted column, the + * index key and the argument errors of (.idx.info table 'col). */ +static test_result_t test_idx_info_report(void) { + /* STR: len * 16 plus the pool, in both generations, and the pool counts */ + sr_eval_ok("(set ST (table [s] (list (as 'STR (map (fn [j] (format \"a-long-string-value-%\" (% j 977))) (til 70000))))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/is2/\" ST {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/is0/\" ST {compress: false})"); + sr_eval_ok("(set S2 (.db.splayed.get \"" SR_TMP "/is2/\"))"); + sr_eval_ok("(set S0 (.db.splayed.get \"" SR_TMP "/is0/\"))"); + int64_t r2 = ii_i64("(at (.idx.info S2 's) 'raw_bytes)"); + int64_t r0 = ii_i64("(at (.idx.info S0 's) 'raw_bytes)"); + int64_t e0 = ii_i64("(at (.idx.info S0 's) 'encoded_bytes)"); + TEST_ASSERT_TRUE(r0 > 70000 * 16); /* the pool is counted */ + /* P6 D15: generation 2's raw_bytes is len * 16 + str_pool_bytes, the + * materialized column's bytes; the 977 strings are STR_DICT entries, + * whose decoded pool holds each once (gen 0's holds every occurrence) */ + int64_t dict_pool = 0; + for (int j = 0; j < 977; j++) dict_pool += 20 + (j < 10 ? 1 : j < 100 ? 2 : 3); /* "a-long-string-value-" + j */ + TEST_ASSERT_EQ_I(r2, 70000 * 16 + dict_pool); + TEST_ASSERT_TRUE(r2 < r0); + TEST_ASSERT_EQ_I(e0, r0); /* plain: encoded is raw */ + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info S2 's) 'gen)"), 2); + TEST_ASSERT_TRUE(ii_i64("(at (.idx.info S2 's) 'encoded_bytes)") > 0); + + /* parted, every segment generation 2: sums over the segments */ + sr_parted_xy(SR_TMP "/ip2", 7, false, false); + sr_eval_ok("(set P2 (.db.parted.get \"" SR_TMP "/ip2\" 't))"); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P2 'x) 'gen)"), 2); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P2 'x) 'segments)"), 3); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P2 'x) 'raw_bytes)"), 3 * 70000 * 8); + TEST_ASSERT_EQ_I(ii_i64("(sum (value (at (.idx.info P2 'x) 'enc)))"), 3 * 69); + int64_t seg = 0; + for (int p = 1; p <= 3; p++) { + char q[256]; + snprintf(q, sizeof q, "(at (.idx.info (.db.splayed.get \"" SR_TMP "/ip2/2024.01.0%d/t/\") 'x) 'encoded_bytes)", p); + seg += ii_i64(q); + } + TEST_ASSERT_TRUE(seg > 0); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P2 'x) 'encoded_bytes)"), seg); + + /* parted, every segment plain: raw and encoded are the segment sums */ + sr_parted_xy(SR_TMP "/ip0", 0, false, false); + sr_eval_ok("(set P0 (.db.parted.get \"" SR_TMP "/ip0\" 't))"); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P0 'x) 'gen)"), 0); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P0 'x) 'segments)"), 3); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P0 'x) 'raw_bytes)"), 3 * 70000 * 8); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info P0 'x) 'encoded_bytes)"), 3 * 70000 * 8); + + /* mixed: two compressed segments and a synthetic one report generation 2; + * the synthetic stand-in adds raw bytes but no file bytes */ + sr_parted_xy(SR_TMP "/imx", 3, true, false); + sr_eval_ok("(set PM (.db.parted.get \"" SR_TMP "/imx\" 't))"); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info PM 'y) 'gen)"), 2); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info PM 'y) 'raw_bytes)"), 3 * 70000 * 8); + TEST_ASSERT_EQ_I(ii_i64("(sum (value (at (.idx.info PM 'y) 'enc)))"), 2 * 69); + /* ragged all-plain: synthetic stand-in contributes no file bytes */ + sr_parted_xy(SR_TMP "/irg0", 0, true, false); + sr_eval_ok("(set PR (.db.parted.get \"" SR_TMP "/irg0\" 't))"); + TEST_ASSERT_EQ_I(ii_i64("(at (.idx.info PR 'y) 'encoded_bytes)"), 2 * 70000 * 8); + TEST_ASSERT_EQ_I(ii_i64("(sum (value (at (.idx.info PR 'y) 'enc)))"), 0); + + /* the index key: generation 2 is the recorded kind, generation 0 the attached index */ + sr_eval_ok("(set T (.db.splayed.get \"" SR_G2 "\"))"); + ray_t* ik = sr_eval("(at (.idx.info T 'k) 'index)"); + TEST_ASSERT_TRUE(ik && !RAY_IS_ERR(ik) && ik->type == -RAY_SYM && + strcmp(ray_str_ptr(ray_sym_str(ik->i64)), "chunk_zone") == 0); + sr_drop(ik); + sr_eval_ok("(set IH (table [a] (list (.idx.hash [1 2 3 1]))))"); + ray_t* hk = sr_eval("(at (at (.idx.info IH 'a) 'index) 'kind)"); + TEST_ASSERT_TRUE(hk && !RAY_IS_ERR(hk) && hk->type == -RAY_SYM && + strcmp(ray_str_ptr(ray_sym_str(hk->i64)), "hash") == 0); + sr_drop(hk); + ray_t* nk = sr_eval("(at (.idx.info (table [a] (list [1 2 3])) 'a) 'index)"); + TEST_ASSERT_TRUE(nk == RAY_NULL_OBJ); + + /* argument errors */ + TEST_ASSERT_TRUE(ii_err("(.idx.info T 'k 'k)", "arity", "expected")); + TEST_ASSERT_TRUE(ii_err("(.idx.info)", "arity", "expected")); + TEST_ASSERT_TRUE(ii_err("(.idx.info [1 2 3] 'k)", "type", "table")); + TEST_ASSERT_TRUE(ii_err("(.idx.info T \"k\")", "type", "symbol")); + TEST_ASSERT_TRUE(ii_err("(.idx.info T 'nope)", "domain", "no such column")); + PASS(); +} + +static test_result_t test_v2_parted_segment(void) { + sr_mixed_parted(SR_TMP "/fp0", 0); + sr_mixed_parted(SR_TMP "/fp2", 2); + static const char* const q = "(select {s: (sum v) c: (count v) from: T by: k})"; + int64_t s0 = ray_group_segstream_runs(); + test_result_t r = sr_same_route("(.db.parted.get \"" SR_TMP "/fp0\" 't)", "(.db.parted.get \"" SR_TMP "/fp2\" 't)", q); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_TRUE(ray_group_segstream_runs() - s0 == 2); /* both in place */ + static const char* const qi = "(select {s: (sum v) c: (count v) from: T by: i})"; + for (int p = 0; p < 3; p++) + for (int gen = 0; gen <= 2; gen += 2) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/fi%d/2024.01.0%d/t/\" (table [i v] (list (as 'I32 (%% (* (til 70000) 7) 1000)) " + "(til 70000))) {compress: %s})", gen, p + 1, gen ? "true" : "false"); + return sr_same_route("(.db.parted.get \"" SR_TMP "/fi0\" 't)", "(.db.parted.get \"" SR_TMP "/fi2\" 't)", qi); +} + +/* The ClickBench scan-only set of the P2 gate (the plan's Task 17 + * SCAN_ONLY), each written over the battery tables' columns with the same + * operators, key widths and clauses: k and h stand for the I64 columns + * (WatchID, UserID), v for the nullable I32 (ClientIP), g and u for the + * narrow integers, d for EventDate and s for the SYM columns. q18, q39, + * the compact fallback and the conjunctive count were pinned in sr_gaps + * until each stopped materializing (P3 Tasks 6 and 6b, Task 15b); the P3 + * gate (Task 12) moved them here, at zero. */ +#define SR_Q18 "(select {c: (count h) from: T by: {h: h s: s} take: 10})" +#define SR_Q35 "(select {one: 1 s: s c: (count s) from: T by: s desc: c take: 10})" +#define SR_Q39 "(take (select {s: s p: (count s) from: T where: (and (== g 3) (>= d 100) (<= d 400) " \ + "(== b false) (!= u 0)) by: s desc: p take: 1010}) -10)" +#define SR_COMPACT_GROUP "(select {c: (count k) from: T where: (< k 1000) by: g})" +#define SR_AND_COUNT "(count (select {from: T where: (and (== g 3) (!= u 0))}))" +static const char* const sr_clickbench_scan[] = { + "(count T)", /* q1 */ + "(count (select {from: T where: (!= u 0)}))", /* q2 */ + "(table [a b c] (list (list (sum (at T 'g))) (list (count T)) (list (avg (at T 'v)))))", /* q3 */ + "(avg (at T 'h))", /* q4 */ + "(table [a b] (list (list (min (at T 'd))) (list (max (at T 'd)))))", /* q7 */ + "(select {u: u c: (count u) from: T where: (!= u 0) by: u desc: c take: 10})", /* q8 */ + "(select {h: h c: (count h) from: T by: h desc: c take: 10})", /* q16 */ + "(select {c: (count h) from: T by: {h: h s: s} desc: c take: 10})", /* q17 */ + "(select {c: (count v) s: (sum g) a: (avg u) from: T by: {k: k v: v} desc: c take: 10})", /* q33 */ + "(select {s: s c: (count s) from: T by: s desc: c take: 10})", /* q34 */ + SR_Q35, /* q35 */ + /* q18: a group-by take without an order runs the first-n pre-pass + * (agg_first_n_run) over the keys' sources: rows read through task + * cursors, the sample point-read, the groups' rows gathered by range + * (P3 Task 6b); on a parted table in place over the segments */ + SR_Q18, /* q18 */ + /* q39: the conjunction's later filter refines a selective first one by + * compacting its predicate column (exec_node OP_FILTER -> sel_compact), + * and the v2 group over fewer survivors than the parallel threshold + * compacts its key (AGG_RUN_COMPACT_FALLBACK -> agg_build_compact): + * both gather by range since P3 Task 6, per segment on a parted table */ + SR_Q39, /* q39 */ + /* the v2 compact fallback alone: a filtered group-by under the parallel + * threshold gathers its key and input by range (agg_build_compact) */ + SR_COMPACT_GROUP, + /* a conjunctive where: is counted off its selection (Task 15b) */ + SR_AND_COUNT, + /* q41: TraficSourceID IN (-1, 6) later in a chain of == conjuncts: on a + * parted table the `in` conjunct reads each segment by range and is + * intersected with the selection (exec_in_parted_selection, P3 Task 12) */ + "(select {h: h d: d c: (count h) from: T where: (and (== g 3) (>= d 100) (<= d 400) (== b false) " + "(in u [1 6]) (!= h 0)) by: {h: h d: d} desc: c take: 10})", /* q41 */ + NULL, +}; + +/* Each shape answers as over generation 0 with `want` materializations on + * the generation-2 table (dirs t0 / t2, written as T); at_first_exec is + * latched only by ray_execute (scalar and filtered grouped shapes + * pre-execute through exec_node, P1 Task 33), so it is checked only where + * it latched (M8). */ +static test_result_t sr_battery(const char* t0, const char* t2, const char* const* shapes, uint64_t want, + const char* skip) { + for (int i = 0; shapes[i]; i++) { + if (skip && strcmp(shapes[i], skip) == 0) continue; + test_result_t r = sr_same_on(t0, t2, shapes[i], want); + if (r.status != TEST_PASS) return r; + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(k.at_first_exec == 0 || k.at_first_exec == UINT64_MAX, + "%s: %llu materializations before execution", shapes[i], + (unsigned long long)k.at_first_exec); + } + PASS(); +} + +/* A shape and its materialization count on generation 2. */ +typedef struct { const char* q; uint64_t mat; } sr_gap_t; + +/* Review focus 5: every scan-only shape, planning included, leaves the + * materialization counter at zero on a generation-2 table; the binding + * assert is the final count (sr_same). Then the ClickBench scan-only set + * (the former gaps among it, at zero) and the row-returning filter: both + * ray_execute of a bare FILTER (the API caller, Task 5) and a language + * select that returns the filtered table compact the selection through + * sel_compact, which gathers every column by range (P3 Task 6): nothing + * materializes, as when counting the same filter (the first shape). */ +static test_result_t test_no_materialization(void) { + static const char* const shapes[] = { + "(count (select {from: T where: (!= g 0)}))", + "(count (select {from: T where: (> v 1000)}))", + "(select {c: (count k) from: T where: (and (>= k 1000) (< k 150000) (== b true))})", + "(select {s: (sum v) a: (avg f) mn: (min d) mx: (max u) from: T})", + "(sum (at T 'v))", + "(avg (at T 'f))", + "(min (at T 'd))", + "(select {s: (sum v) c: (count k) from: T by: g})", + "(select {c: (count k) from: T where: (> v 100) by: {g: g s: s}})", + "(select {c: (count k) from: T by: k})", + "(select {c: (count k) from: T where: (== h 1000004)})", + "(select {s: (sum (+ k 5)) t: (sum (* f 2.0)) from: T where: (< g 4)})", + "(select {l: (avg (strlen s)) from: T})", + NULL, + }; + const char* t0 = "(.db.splayed.get \"" SR_G0 "\")"; + const char* t2 = "(.db.splayed.get \"" SR_G2 "\")"; + test_result_t r = sr_battery(t0, t2, shapes, 0, NULL); + if (r.status == TEST_PASS) r = sr_battery(t0, t2, sr_clickbench_scan, 0, NULL); + if (r.status != TEST_PASS) return r; + + uint64_t mat[2] = { 0, 0 }; + int64_t rows[2] = { -1, -1 }; + for (int lang = 0; lang < 2; lang++) { + ray_t* t = sr_load(1); + TEST_ASSERT_NOT_NULL(t); + if (lang) { + ray_env_set(ray_sym_intern("T", 1), t); + ray_enc_counters_reset(); + ray_t* q = sr_eval("(select {from: T where: (> v 100)})"); + TEST_ASSERT_TRUE(q && !RAY_IS_ERR(q) && q->type == RAY_TABLE); + rows[lang] = ray_table_nrows(q); + sr_drop(q); + } else { + ray_graph_t* g = ray_graph_new(t); + ray_op_t* root = ray_filter(g, ray_const_table(g, t), cpred_v_gt(g)); + ray_enc_counters_reset(); + ray_t* q = ray_execute(g, ray_optimize(g, root)); + TEST_ASSERT_TRUE(q && !RAY_IS_ERR(q) && q->type == RAY_TABLE); + rows[lang] = ray_table_nrows(q); + sr_drop(q); ray_graph_free(g); + } + ray_enc_counters_t k; ray_enc_counters_get(&k); + mat[lang] = k.materialized; + ray_release(t); + } + TEST_ASSERT_EQ_I(rows[0], rows[1]); + TEST_ASSERT_FMT(mat[0] == 0, "ray_execute of a bare FILTER: %llu materializations, want 0", + (unsigned long long)mat[0]); + TEST_ASSERT_FMT(mat[1] == 0, "select of the same filter: %llu materializations, want 0", + (unsigned long long)mat[1]); + PASS(); +} + +/* The parted battery tables: three partitions of eight columns, written as + * generation 0 (np0) and generation 2 (np2). */ +static void sr_np_tables(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/np%d/2024.01.0%d/t/\" " + "(table [k g v d s b u h] (list (+ (til 70000) %d) (as 'I16 (%% (til 70000) 7)) " + "(as 'I32 (map (fn [j] (if (== 0 (%% j 10)) 0N (- (* 3 j) 7))) (til 70000))) " + "(as 'DATE (%% (til 70000) 900)) (take ['a 'b 'c 'd 'e] 70000) (== 0 (%% (til 70000) 3)) " + "(as 'U8 (%% (til 70000) 200)) (%% (* (+ (til 70000) %d) 7919) 1000003))) " + "\"" SR_TMP "/np%d/.sym\" {compress: %s})", + gen, p + 1, p * 70000, p * 70000, gen, gen ? "true" : "false"); +} +#define SR_NP0 "(.db.parted.get \"" SR_TMP "/np0\" 't)" +#define SR_NP2 "(.db.parted.get \"" SR_TMP "/np2\" 't)" + +/* The parted arm of the gate: the same shapes over three partitions of a + * generation-2 parted table (the in-place routes) against generation 0. */ +static test_result_t test_no_materialization_parted(void) { + sr_np_tables(); + static const char* const shapes[] = { + "(count (select {from: T where: (!= g 0)}))", + "(sum (at T 'v))", + "(select {s: (sum v) c: (count k) from: T by: g})", + "(select {c: (count k) from: T where: (> v 100) by: {g: g s: s}})", + "(select {c: (count k) from: T by: k})", + /* q41's `in` conjunct where the optimizer puts it first, and after a + * conjunct that keeps most rows (the chain's full-width step): + * each segment by range (exec_in_parted_selection, P3 Task 12) */ + "(count (select {from: T where: (in u [1 6])}))", + "(select {c: (count h) from: T where: (and (!= g 0) (in u [1 6])) by: d desc: c take: 10})", + NULL, + }; + const char* t0 = SR_NP0; + const char* t2 = SR_NP2; + test_result_t r = sr_battery(t0, t2, shapes, 0, NULL); + if (r.status == TEST_PASS) r = sr_battery(t0, t2, sr_clickbench_scan, 0, NULL); + return r; +} + +/* Task 17e (#769): a parted select that groups after a where: gathers the + * selected rows of the columns its by: and outputs read, not of every + * column. The ClickBench q11, q14 and q23 shapes (a count(distinct) + * output, so the where: runs as its own filter: the materialize path) and + * q12 (an implicit group under an outer projection: the eval-level group) + * over the parted battery tables gather exactly their own columns on + * generation 2, by range since P3 Task 6 (nothing materializes, and the + * columns they never read decode nothing), the where:-only columns read in + * place by the filter. Shapes whose reads cannot be named keep every + * column and answer as before: a lambda output, the implicit-all group + * (first of every column), a computed key; and an all-pass filter, a + * filter that passes nothing, and a nested group whose consumer names + * columns answer as generation 0. */ +static test_result_t test_parted_eval_group_keep(void) { + sr_np_tables(); + /* each shape's materializations, and the columns it never reads: they + * decode nothing, so the keep set still narrows the compaction */ + static const struct { const char* q; uint64_t mat; const char* unread; } own[] = { + /* q11: key s, distinct h; v in the where: only */ + { "(select {s: s u: (count (distinct h)) from: T where: (> v 3) by: s desc: u take: 10})", 0, "kgdbu" }, + /* q12: the inner implicit group feeds an outer that reads g, s, h */ + { "(select {c: (count h) from: (select {from: T where: (!= u 0) by: {g: g s: s h: h}}) " + "by: {g: g s: s} desc: c take: 10})", 0, "kvdb" }, + /* q14: key g, distinct k; u in the where: only */ + { "(select {g: g u: (count (distinct k)) from: T where: (!= u 0) by: g desc: u take: 10})", 0, "vdsbh" }, + /* q23: four outputs over s, h, k; g and v in the where: only */ + { "(select {s: s u: (count h) t: (count k) c: (count s) d: (count (distinct h)) from: T " + "where: (and (!= g 1) (> v 3)) by: s desc: c take: 10})", 0, "dbu" }, + /* an all-pass filter flattens the same columns */ + { "(select {g: g u: (count (distinct k)) m: (max d) from: T where: (>= u 0) by: g})", 9, "" }, + { NULL, 0, NULL }, + }; + for (int i = 0; own[i].q; i++) { + test_result_t r = sr_same_on(SR_NP0, SR_NP2, own[i].q, own[i].mat); + if (r.status != TEST_PASS) return r; + for (const char* c = own[i].unread; *c; c++) { /* T: the generation-2 table */ + char nm[2] = { *c, 0 }; + uint64_t full = 0, dec = sr_col_dec_any(nm, &full); + TEST_ASSERT_FMT(full > 0 && dec == 0, "%s: unread column %s decoded %llu bytes", own[i].q, nm, + (unsigned long long)dec); + } + } + static const char* const all[] = { + "(select {s: s u: (count (distinct h)) w: ((fn [x] (count x)) k) from: T where: (> v 3) by: s})", + "(select {from: T where: (> v 3) by: [g s]})", + "(select {from: T where: (> v 3) by: g})", + "(select {u: (count (distinct h)) from: T where: (> v 3) by: (% k 3)})", + "(select {g: g u: (count (distinct k)) from: T where: (> u 250) by: g})", + "(select {m: (max u) from: (select {from: T where: (> v 3) by: {g: g s: s}}) by: g})", + NULL, + }; + for (int i = 0; all[i]; i++) { + test_result_t r = sr_same_on(SR_NP0, SR_NP2, all[i], UINT64_MAX); + if (r.status != TEST_PASS) return r; + } + /* Fix round 1: an implicit group under an outer projection hint keeps + * every column when it sorts or takes (only from/where/by narrow it, + * as filt_compact_keep requires): the sort column, an outer lambda's + * dynamic read and a quoted name are not in proj_keep. Expected values + * are 80a28e49's answers over the generation-0 tables; both + * generations must give them. */ + static const struct { const char* q; const char* want; } base_ans[] = { + { "(at (select {g: g from: (select {from: T where: (> v 3) by: [g s] desc: d take: 3})}) 'g)", "[2 6 3]" }, + { "(sum (at (select {g: g from: (select {from: T where: (> v 3) by: [g s] desc: d})}) 'g))", "105" }, + { "(count (select {g: g from: (select {from: T where: (> v 3) by: [g s] desc: d})}))", "35" }, + { "(at (select {g: g from: (select {from: T where: (> v 3) by: {g: g s: s} asc: k take: 3})}) 'g)", "[4 5 6]" }, + { "(at (select {g: g from: (select {from: T where: (> v 3) by: [g s] asc: [u k] take: 3})}) 'g)", "[4 5 6]" }, + { "(at (select {c: (count (distinct g)) from: (select {from: T where: (> v 3) by: [g s] desc: d take: 3})}) 'c)", "[3]" }, + { "(do (set fu (fn [z] (+ z u))) " + "(at (select {m: (sum (fu g)) from: (select {from: T where: (> v 3) by: [g s] take: 5})}) 'm))", "[46]" }, + { "(at (select {m: (sum 'u) from: (select {from: T where: (> v 3) by: [g s] take: 5})}) 'm)", "[30]" }, + /* the narrowed shape (from/where/by only) answers as before */ + { "(at (select {g: g from: (select {from: T where: (> v 3) by: [g s]})}) 'g)", + "[4 5 6 0 1 2 4 5 6 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 3 4 5 6 0 1 2 3 3 6 2]" }, + { NULL, NULL }, + }; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? SR_NP2 : SR_NP0); + for (int i = 0; base_ans[i].q; i++) { + ray_t* got = sr_eval(base_ans[i].q); + ray_t* want = sr_eval(base_ans[i].want); + bool same = sr_same_text(got, want); + ray_t* fg = (got && !RAY_IS_ERR(got)) ? ray_fmt(got, 0) : NULL; + TEST_ASSERT_FMT(same, "gen %d: %s: %.*s, base %s", gen ? 2 : 0, base_ans[i].q, + fg ? (int)ray_str_len(fg) : 5, fg ? ray_str_ptr(fg) : (got ? ray_err_code(got) : "null"), + base_ans[i].want); + if (fg) ray_release(fg); + sr_drop(got); ray_release(want); + } + } + PASS(); +} + +/* Gap 5 (Task 15b): a count over a conjunctive filter is answered from the + * selection, gathering no column, on splayed and parted tables of either + * generation. Each count equals the row count of the select the shortcut + * stands for (the gathering select, read through `at`), on both + * generations; conjunctions with nullable columns, SYM equality and SYM + * order (#738), three conjuncts and an all-false one are covered. The + * single-compare shortcut is untouched (test_count_fast_path). */ +static test_result_t sr_count_and_on(const char* t0, const char* t2, const char* w, uint64_t want_mat) { + char q[512], ref[512]; + snprintf(q, sizeof q, "(count (select {from: T where: %s}))", w); + snprintf(ref, sizeof ref, "(count (at (select {from: T where: %s}) 'k))", w); + test_result_t r = sr_same_on(t0, t2, q, want_mat); + if (r.status != TEST_PASS) return r; + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? t2 : t0); + ray_t* a = sr_eval(q); + ray_t* b = sr_eval(ref); + TEST_ASSERT_FMT(a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && a->type == -RAY_I64 && + b->type == -RAY_I64 && a->i64 == b->i64, + "gen %d %s: %lld, the select has %lld rows", gen, w, + (long long)(a && !RAY_IS_ERR(a) ? a->i64 : -1), + (long long)(b && !RAY_IS_ERR(b) ? b->i64 : -1)); + sr_drop(a); sr_drop(b); + } + PASS(); +} +/* A conjunction the shortcut must leave to the select (Fix round 1): the + * count equals the gathering select's row count, or both fail with the same + * error, on both generations. */ +static test_result_t sr_count_and_declines(const char* t0, const char* t2, const char* w) { + char q[512], ref[512]; + snprintf(q, sizeof q, "(count (select {from: T where: %s}))", w); + snprintf(ref, sizeof ref, "(count (at (select {from: T where: %s}) 'k))", w); + for (int gen = 0; gen < 2; gen++) { + sr_evalf_ok("(set T %s)", gen ? t2 : t0); + ray_error_clear(); + ray_t* a = sr_eval(q); + char am[256]; snprintf(am, sizeof am, "%s", (a && RAY_IS_ERR(a) && ray_error_msg()) ? ray_error_msg() : ""); + char ac[64]; snprintf(ac, sizeof ac, "%s", (a && RAY_IS_ERR(a)) ? ray_err_code(a) : ""); + ray_error_clear(); + ray_t* b = sr_eval(ref); + bool ae = !a || RAY_IS_ERR(a), be = !b || RAY_IS_ERR(b); + if (ae || be) { + TEST_ASSERT_FMT(ae && be && a && b && strcmp(ac, ray_err_code(b)) == 0 && + strcmp(am, ray_error_msg() ? ray_error_msg() : "") == 0, + "gen %d %s: \"%s: %s\", the select \"%s: %s\"", gen, w, ac, am, + be && b ? ray_err_code(b) : "-", be && ray_error_msg() ? ray_error_msg() : ""); + } else { + TEST_ASSERT_FMT(a->type == -RAY_I64 && b->type == -RAY_I64 && a->i64 == b->i64, + "gen %d %s: %lld, the select has %lld rows", gen, w, + (long long)a->i64, (long long)b->i64); + } + sr_drop(a); sr_drop(b); + } + PASS(); +} +/* Conjuncts outside the whitelist: constants nested in `or` / `and`, an + * aggregate (the select's chained filters refine its input), arithmetic, + * `if`, a non-bool conjunct (the select's error text), an ordered SYM + * compare, a quoted symbol naming a column, and `in`. */ +static const char* const sr_and_declined[] = { + "(and (> k 2) (or 0.0 (> g 1)))", + "(and (> k 2) (or (> g 1) 0.0))", + "(and (> k 2) (and (> g 1) 1.5))", + "(and (> k 2) (> k (avg k)))", + "(and (> k 2) (> (+ k 1) 5))", + "(and (> k 2) (if true (> g 1) (> g 2)))", + "(and (> k 2) (+ 1 (* 0 k)))", + "(and (< s 'c) (== b true))", /* SYM order is by string (#738) */ + "(and (== s 'b) (> k 1000))", /* 'b names a column: a column compare */ + "(and (> k 2) (in g [1 2]))", + NULL, +}; + +static test_result_t test_count_and(void) { + static const char* const splayed[] = { + "(and (== g 3) (!= u 0))", + "(and (> v 100) (< f 150000.0))", /* nullable I32 and F64 */ + "(and (== g 3) (>= d 100) (<= d 400))", + "(and (== g 3) (== g 4))", /* all false */ + "(and (> k 199990) (== b true) (!= v 0))", + NULL, + }; + const char* t0 = "(.db.splayed.get \"" SR_G0 "\")"; + const char* t2 = "(.db.splayed.get \"" SR_G2 "\")"; + for (int i = 0; splayed[i]; i++) { + test_result_t r = sr_count_and_on(t0, t2, splayed[i], 0); + if (r.status != TEST_PASS) return r; + } + /* A file-domain SYM equality is scan-only since P3 Task 4: the fused + * program compares the column's own ids against the constant + * translated into its domain, so nothing is materialized. */ + static const sr_gap_t sym[] = { + { "(and (== s 'c) (> k 1000))", 0 }, + { NULL, 0 }, + }; + for (int i = 0; sym[i].q; i++) { + test_result_t r = sr_count_and_on(t0, t2, sym[i].q, sym[i].mat); + if (r.status != TEST_PASS) return r; + } + for (int i = 0; sr_and_declined[i]; i++) { + test_result_t r = sr_count_and_declines(t0, t2, sr_and_declined[i]); + if (r.status != TEST_PASS) return r; + } + sr_np_tables(); + for (int i = 0; sr_and_declined[i]; i++) { + test_result_t r = sr_count_and_declines(SR_NP0, SR_NP2, sr_and_declined[i]); + if (r.status != TEST_PASS) return r; + } + static const char* const parted[] = { + "(and (== g 3) (!= u 0))", + "(and (> v 100) (< v 150000))", /* nullable I32 */ + "(and (== g 3) (== g 4))", + "(and (>= k 69990) (< k 70010) (!= v 0))", /* across a partition edge */ + NULL, + }; + for (int i = 0; parted[i]; i++) { + test_result_t r = sr_count_and_on(SR_NP0, SR_NP2, parted[i], 0); + if (r.status != TEST_PASS) return r; + } + /* parted: the same, per encoded segment (one domain for every segment) */ + static const sr_gap_t sym_parted[] = { + { "(and (== s 'c) (> k 1000))", 0 }, + { NULL, 0 }, + }; + for (int i = 0; sym_parted[i].q; i++) { + test_result_t r = sr_count_and_on(SR_NP0, SR_NP2, sym_parted[i].q, sym_parted[i].mat); + if (r.status != TEST_PASS) return r; + } + PASS(); +} + +/* Gap 4 (Task 15b): a constant output beside a parted group-by groups the + * table in place (the segment-streaming route of Task 14) and broadcasts + * the constant over the result rows; the table is never flattened. Each + * shape answers as over generation 0, gathers nothing on generation 2, + * runs in place on both, and equals the same group-by without its constant + * outputs with the constants added (their type and length included). The + * generation-2 count is the proof that nothing flattened (a flatten reads + * every segment of every column); the in-place counter shows the constant + * leaves the bare group-by's route unchanged on both generations. */ +static test_result_t test_const_beside_parted_group(void) { + sr_np_tables(); + static const struct { const char* q; const char* bare; const char* checks; uint64_t mat; } shapes[] = { + { SR_Q35, "(select {s: s c: (count s) from: T by: s desc: c take: 10})", + "(and (== (type (at R 'one)) 'I64) (all (== (at R 'one) (take 1 (count R)))))", 0 }, + { "(select {one: 1 f: 2.5 sy: 'x st: \"ab\" dt: 2024.01.02 bo: true c: (count k) from: T by: g})", + "(select {c: (count k) from: T by: g})", + "(and (== (type (at R 'f)) 'F64) (== (type (at R 'sy)) 'SYM) (== (type (at R 'st)) 'STR) " + "(== (type (at R 'dt)) 'DATE) (== (type (at R 'bo)) 'B8) (== (count (at R 'st)) 7) " + "(all (== (at R 'f) (take 2.5 7))) (all (== (at R 'sy) (take 'x 7))))", 0 }, + { "(select {one: 1 c: (count k) from: T where: (!= u 0) by: s})", + "(select {c: (count k) from: T where: (!= u 0) by: s})", + "(all (== (at R 'one) (take 1 5)))", 0 }, + /* no group: the compact fallback gathers the key and input by + * range (SR_COMPACT_GROUP, P3 Task 6), with or without the + * constant */ + { "(select {one: 1 c: (count k) from: T where: (== g 9) by: s})", + "(select {c: (count k) from: T where: (== g 9) by: s})", + "(and (== (type (at R 'one)) 'I64) (== 0 (count (at R 'one))))", 0 }, + { "(select {c: (sum v) one: 1 from: T by: k desc: c take: 5})", + "(select {c: (sum v) from: T by: k desc: c take: 5})", + "(all (== (at R 'one) (take 1 5)))", 0 }, + { "(select {one: (+ 1 2) c: (count k) from: T by: g})", /* a scalar expression */ + "(select {c: (count k) from: T by: g})", + "(and (== (type (at R 'one)) 'LIST) (== 7 (count (at R 'one))) (== 3 (first (at R 'one))))", 0 }, + }; + for (size_t i = 0; i < sizeof shapes / sizeof shapes[0]; i++) { + int64_t s0 = ray_group_segstream_runs(); + test_result_t r = sr_same_on(SR_NP0, SR_NP2, shapes[i].bare, shapes[i].mat); + if (r.status != TEST_PASS) return r; + int64_t s1 = ray_group_segstream_runs(); + r = sr_same_on(SR_NP0, SR_NP2, shapes[i].q, shapes[i].mat); + if (r.status != TEST_PASS) return r; + /* the constant leaves the route as it is without it */ + TEST_ASSERT_FMT(ray_group_segstream_runs() - s1 == s1 - s0, "%s: not the bare group's route", shapes[i].q); + sr_eval_ok("(set T " SR_NP2 ")"); + sr_evalf_ok("(set R %s)", shapes[i].q); + sr_evalf_ok("(set B %s)", shapes[i].bare); + ray_t* ok = sr_eval(shapes[i].checks); + TEST_ASSERT_FMT(ok && ok->type == -RAY_BOOL && ok->b8, "%s: constant columns", shapes[i].q); + sr_drop(ok); + /* the other columns are the bare group-by's */ + ray_t* eq = sr_eval("(all (map (fn [c] (and (== (count (at R c)) (count (at B c))) (all (== (at R c) (at B c))))) (key B)))"); + TEST_ASSERT_FMT(eq && eq->type == -RAY_BOOL && eq->b8, "%s: differs from %s", shapes[i].q, shapes[i].bare); + sr_drop(eq); + } + PASS(); +} + +/* Issue #767: a per-partition group-by divides avg and var/dev by the + * input's non-null count (it divided by the row count). Three partitions + * of 35000 rows, an I64 key of five values (the per-partition route), a + * nullable F64 and a nullable I64, against the same rows in memory, with + * and without a where, a constant beside the group, and groups whose every + * input is null (null averages, as in memory); generation 0 and 2. */ +static test_result_t test_parted_nullable_stats(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/ns%d/2024.01.0%d/t/\" " + "(table [g x y] (list (%% (til 35000) 5) " + "(as 'F64 (map (fn [i] (if (== 0 (%% i 4)) 0N (* 1.0 i))) (til 35000))) " + "(map (fn [i] (if (== 0 (%% i 3)) 0N i)) (til 35000)))) " + "\"" SR_TMP "/ns%d/.sym\" {compress: %s})", gen, p + 1, gen, gen ? "true" : "false"); + sr_eval_ok("(set jj (concat (til 35000) (concat (til 35000) (til 35000))))"); + sr_eval_ok("(set M (table [g x y] (list (% jj 5) (as 'F64 (map (fn [i] (if (== 0 (% i 4)) 0N (* 1.0 i))) jj)) " + "(map (fn [i] (if (== 0 (% i 3)) 0N i)) jj))))"); + static const char* const qs[] = { + "(select {a: (avg x) b: (avg y) from: T by: g asc: g})", + "(select {v: (var x) w: (var y) vp: (var_pop x) wp: (var_pop y) from: T by: g asc: g})", + "(select {d: (dev x) e: (dev y) s: (stddev x) t: (stddev y) sp: (stddev_pop y) from: T by: g asc: g})", + "(select {a: (avg x) b: (avg y) v: (var x) d: (dev y) from: T where: (> y 100) by: g asc: g})", + "(select {one: 1 a: (avg x) v: (var y) from: T by: g asc: g})", + "(select {a: (avg x) v: (var x) d: (dev x) c: (count x) from: T where: (== 0 (% y 4)) by: g asc: g})", + NULL, + }; + for (int gen = 0; gen <= 2; gen += 2) { + char tp[256]; + snprintf(tp, sizeof tp, "(.db.parted.get \"" SR_TMP "/ns%d\" 't)", gen); + for (int i = 0; qs[i]; i++) { + int64_t r0 = ray_group_perpart_runs(); + int64_t n0 = ray_group_perpart_nn_slots(); + test_result_t r = sr_same_on("M", tp, qs[i], UINT64_MAX); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(ray_group_perpart_runs() > r0, "gen %d %s: not the per-partition route", gen, qs[i]); + TEST_ASSERT_FMT(ray_group_perpart_nn_slots() > n0, "gen %d %s: nullable input counted by rows", gen, qs[i]); + } + } + /* Fix round 2: a null-free input (g, and z, no null) keeps the row + * count: no non-null count slot is built, and the answers still equal + * memory's. A nullable one beside it builds only its own. */ + sr_eval_ok("(set M (table [g x y z] (list (% jj 5) (as 'F64 (map (fn [i] (if (== 0 (% i 4)) 0N (* 1.0 i))) jj)) " + "(map (fn [i] (if (== 0 (% i 3)) 0N i)) jj) (as 'F64 jj))))"); + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/nz%d/2024.01.0%d/t/\" " + "(table [g x y z] (list (%% (til 35000) 5) " + "(as 'F64 (map (fn [i] (if (== 0 (%% i 4)) 0N (* 1.0 i))) (til 35000))) " + "(map (fn [i] (if (== 0 (%% i 3)) 0N i)) (til 35000)) (as 'F64 (til 35000)))) " + "\"" SR_TMP "/nz%d/.sym\" {compress: %s})", gen, p + 1, gen, gen ? "true" : "false"); + static const struct { const char* q; int64_t nn; } zs[] = { + { "(select {a: (avg z) b: (avg g) v: (var z) d: (dev g) from: T by: g asc: g})", 0 }, + { "(select {a: (avg z) v: (var_pop z) from: T where: (> z 100.0) by: g asc: g})", 0 }, + { "(select {a: (avg z) b: (avg x) from: T by: g asc: g})", 3 }, /* x's slot, per partition */ + { NULL, 0 }, + }; + for (int gen = 0; gen <= 2; gen += 2) { + char tp[256]; + snprintf(tp, sizeof tp, "(.db.parted.get \"" SR_TMP "/nz%d\" 't)", gen); + for (int i = 0; zs[i].q; i++) { + int64_t r0 = ray_group_perpart_runs(); + int64_t n0 = ray_group_perpart_nn_slots(); + test_result_t r = sr_same_on("M", tp, zs[i].q, UINT64_MAX); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(ray_group_perpart_runs() > r0, "gen %d %s: not the per-partition route", gen, zs[i].q); + /* sr_same_on runs the query once on the parted table */ + TEST_ASSERT_FMT(ray_group_perpart_nn_slots() - n0 == zs[i].nn, "gen %d %s: %lld non-null count slots, want %lld", + gen, zs[i].q, (long long)(ray_group_perpart_nn_slots() - n0), (long long)zs[i].nn); + } + } + PASS(); +} + +/* Task 17d: a per-partition AVG over an expression builds a non-null + * count slot when the expression can yield null. strlen maps the empty + * STR/SYM value to null (#888), so its AVG counts only non-empty inputs. + * A cast of a null-free integer to F64 is null-free. Answers agree over + * the same rows in memory, generation 0 and generation 2. */ +static test_result_t test_parted_expr_null_free(void) { + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/ne%d/2024.01.0%d/t/\" " + "(table [g s y z] (list (%% (til 35000) 5) " + "(map (fn [i] (if (== 0 (%% i 4)) \"\" (if (== 0 (%% i 3)) \"abcdef\" \"ab\"))) (til 35000)) " + "(map (fn [i] (if (== 0 (%% i 6)) (as 'SYM \"\") (if (== 0 (%% i 5)) 'xyz 'q))) (til 35000)) " + "(til 35000))) " + "\"" SR_TMP "/ne%d/.sym\" {compress: %s})", gen, p + 1, gen, gen ? "true" : "false"); + sr_eval_ok("(set jj (concat (til 35000) (concat (til 35000) (til 35000))))"); + sr_eval_ok("(set M (table [g s y z] (list (% jj 5) " + "(map (fn [i] (if (== 0 (% i 4)) \"\" (if (== 0 (% i 3)) \"abcdef\" \"ab\"))) jj) " + "(map (fn [i] (if (== 0 (% i 6)) (as 'SYM \"\") (if (== 0 (% i 5)) 'xyz 'q))) jj) jj)))"); + static const struct { const char* q; int64_t nn; } qs[] = { + { "(select {a: (avg (strlen s)) from: T by: g asc: g})", 3 }, + { "(select {a: (avg (strlen y)) b: (sum (strlen s)) c: (count s) from: T by: g asc: g})", 3 }, + { "(select {a: (avg (strlen s)) from: T where: (!= s \"\") by: g asc: g})", 3 }, + { "(select {a: (avg (as 'F64 z)) b: (avg (as 'I64 g)) from: T by: g asc: g})", 0 }, + { "(select {a: (avg (+ 1 (strlen s))) from: T by: g asc: g})", 3 }, /* one slot per partition */ + { "(select {v: (var (strlen s)) from: T by: g asc: g})", 3 }, + { NULL, 0 }, + }; + for (int gen = 0; gen <= 2; gen += 2) { + char tp[256]; + snprintf(tp, sizeof tp, "(.db.parted.get \"" SR_TMP "/ne%d\" 't)", gen); + for (int i = 0; qs[i].q; i++) { + int64_t r0 = ray_group_perpart_runs(); + int64_t n0 = ray_group_perpart_nn_slots(); + test_result_t r = sr_same_on("M", tp, qs[i].q, UINT64_MAX); + if (r.status != TEST_PASS) return r; + TEST_ASSERT_FMT(ray_group_perpart_runs() > r0, "gen %d %s: not the per-partition route", gen, qs[i].q); + TEST_ASSERT_FMT(ray_group_perpart_nn_slots() - n0 == qs[i].nn, "gen %d %s: %lld non-null count slots, want %lld", + gen, qs[i].q, (long long)(ray_group_perpart_nn_slots() - n0), (long long)qs[i].nn); + } + } + /* Explicit reference: an empty string contributes neither a length + * nor a count to AVG, on both storage generations. */ + int64_t lsum[5] = { 0 }, lcnt[5] = { 0 }; + for (int p = 0; p < 3; p++) + for (int64_t i = 0; i < 35000; i++) { + lsum[i % 5] += i % 4 == 0 ? 0 : i % 3 == 0 ? 6 : 2; + if (i % 4 != 0) lcnt[i % 5]++; + } + for (int gen = 0; gen <= 2; gen += 2) { + sr_evalf_ok("(set T (.db.parted.get \"" SR_TMP "/ne%d\" 't))", gen); + int64_t r0 = ray_group_perpart_runs(); + ray_t* a = sr_eval("(at (select {a: (avg (strlen s)) from: T by: g asc: g}) 'a)"); + TEST_ASSERT_FMT(ray_group_perpart_runs() > r0, "gen %d: not the per-partition route", gen); + TEST_ASSERT_FMT(a && !RAY_IS_ERR(a) && a->type == RAY_F64 && a->len == 5, "gen %d: avg (strlen s)", gen); + for (int k = 0; k < 5; k++) + TEST_ASSERT_FMT(((double*)ray_data(a))[k] == (double)lsum[k] / (double)lcnt[k], + "gen %d group %d: %.17g, base %.17g", gen, k, ((double*)ray_data(a))[k], + (double)lsum[k] / (double)lcnt[k]); + sr_drop(a); + } + PASS(); +} + +/* Task 17g: strlen SUM/AVG over generation-2 STR agrees with generation + * 0 and the same rows in memory: scalar, direct-array, legacy radix, + * selection, mixed staged SYM and per-partition routes. Encoded STR + * currently materializes once. AVG skips empty STR/SYM values (#888); + * the explicit reference below checks that rule, not just agreement. */ +static int64_t sr_strlen_len(int64_t r) { + switch (r % 3) { + case 0: return (r / 3) % 2 ? 0 : 4; + case 1: return r % 5; + default: return (r / 7) % 3 == 0 ? 0 : 7; + } +} +static test_result_t strlen_runtime_sym_gen2_case(int64_t n, bool byte_key) { + const int64_t repeats = n / 6; + const int8_t key_type = byte_key ? RAY_U8 : RAY_I32; + const int64_t kid = ray_sym_intern("k", 1); + const int64_t sid = ray_sym_intern("s", 1); + const int64_t zid = ray_sym_intern("z", 1); + const int64_t nid = ray_sym_intern("n", 1); + const int64_t tid = ray_sym_intern("T", 1); + const int64_t ids[6] = { 0, 0, ray_sym_intern("a", 1), + ray_sym_intern("bb", 2), ray_sym_intern("ccc", 3), + ray_sym_intern("dddd", 4) }; + const uint32_t bound = ray_sym_count(); + ray_t *sv = NULL, *kv = NULL, *enc = NULL, *tbl = NULL, *res = NULL; + const char* why = "interned IDs"; + int qi = -1; + char path[512]; + snprintf(path, sizeof path, "%s/strlen-runtime-sym", sr_root()); + for (int j = 2; j < 6; j++) + if (ids[j] <= 0 || (uint64_t)ids[j] >= bound) goto done; + + why = "source allocation"; + sv = ray_sym_vec_new(RAY_SYM_W64, n); + kv = ray_vec_new(key_type, n); + if (!sv || RAY_IS_ERR(sv) || !kv || RAY_IS_ERR(kv)) goto done; + sv->len = kv->len = n; + sv->attrs |= RAY_ATTR_HAS_NULLS; + for (int64_t r = 0; r < n; r++) { + ((int64_t*)ray_data(sv))[r] = ids[r % 6]; + if (byte_key) ((uint8_t*)ray_data(kv))[r] = (uint8_t)(1 + r % 2); + else ((int32_t*)ray_data(kv))[r] = (int32_t)(r % 2); + } + + /* No assertion may leave an open FILE or live writer allocation. */ + why = "open writer"; + FILE* f = fopen(path, "wb+"); + if (!f) goto done; + ray_encw_t w; + ray_err_t rc = ray_encw_begin(&w, f, RAY_SYM, RAY_SYM_W64, + n, bound, 0, 0); + for (int64_t off = 0; rc == RAY_OK && off < n; off += 65536) { + int64_t rows = n - off < 65536 ? n - off : 65536; + rc = ray_encw_chunk(&w, (const int64_t*)ray_data(sv) + off, NULL, rows); + } + if (rc == RAY_OK) rc = ray_encw_finish(&w); + ray_encw_free(&w); + int close_rc = fclose(f); + why = "write/finish/close"; + if (rc != RAY_OK || close_rc != 0) goto done; + sr_drop(sv); sv = NULL; + + /* Direct mmap intentionally preserves the runtime domain: no splayed + * loader, .sym file, domain rebind, or forged header. */ + why = "map runtime W64 SYM"; + enc = ray_col_mmap(path); + if (!enc || RAY_IS_ERR(enc) || enc->type != RAY_ENCCOL) goto done; + ray_enccol_t* e = ray_enccol_of(enc); + if (!e || e->type != RAY_SYM || e->len != n || + (e->attrs & RAY_SYM_W_MASK) != RAY_SYM_W64 || + e->dom != ray_sym_runtime_domain() || + ray_enccol_decoded_peek(enc) != NULL) goto done; + + why = "table allocation/binding"; + tbl = ray_table_new(2); + if (!tbl || RAY_IS_ERR(tbl)) goto done; + tbl = ray_table_add_col(tbl, kid, kv); + if (!tbl || RAY_IS_ERR(tbl)) goto done; + tbl = ray_table_add_col(tbl, sid, enc); + if (!tbl || RAY_IS_ERR(tbl)) goto done; + if (ray_env_set(tid, tbl) != RAY_OK) goto done; + /* add_col retains columns, env_set retains tbl. Keep enc's owning ref + * through both queries; result-column pointers below are borrowed. */ + sr_drop(kv); kv = NULL; + sr_drop(tbl); tbl = NULL; + + static const char* qs[] = { + "(select {z: (sum (strlen s)) n: (count k) from: T by: k asc: k})", + "(select {z: (avg (strlen s)) n: (count k) from: T by: k asc: k})", + }; + ray_group_test_route(0); + for (qi = 0; qi < 2; qi++) { + why = "source decoded before query"; + if (ray_enccol_decoded_peek(enc) != NULL) goto done; + ray_enc_counters_reset(); + res = sr_eval(qs[qi]); + ray_enc_counters_t c; + ray_enc_counters_get(&c); + why = "query/counters/cache"; + if (!res || RAY_IS_ERR(res) || res->type != RAY_TABLE || + c.materialized != 0 || c.at_first_exec != 0 || + ray_enccol_decoded_peek(enc) != NULL) goto done; + /* These are result columns only; do not access T.s. */ + ray_t* k = ray_table_col(res, kid); + ray_t* z = ray_table_col(res, zid); + ray_t* cnt = ray_table_col(res, nid); + why = "result column lookup"; + if (!k || RAY_IS_ERR(k) || !z || RAY_IS_ERR(z) || !cnt || RAY_IS_ERR(cnt)) { + /* Normal columns are borrowed; only lookup errors are owned. */ + if (k && RAY_IS_ERR(k)) ray_error_free(k); + if (z && RAY_IS_ERR(z)) ray_error_free(z); + if (cnt && RAY_IS_ERR(cnt)) ray_error_free(cnt); + goto done; + } + why = "result column types/lengths/null cells"; + if (k->type != key_type || z->type != (qi == 0 ? RAY_I64 : RAY_F64) || + cnt->type != RAY_I64 || k->len != 2 || z->len != 2 || cnt->len != 2) + goto done; + /* HAS_NULLS is a conservative gate: require non-null cells, not a + * minimal hint bit on a correctly populated result. */ + for (int64_t row = 0; row < 2; row++) + if (ray_vec_is_null(k, row) || ray_vec_is_null(z, row) || + ray_vec_is_null(cnt, row)) goto done; + why = "keys/counts/strlen aggregate values"; + int64_t k0 = byte_key ? ((uint8_t*)ray_data(k))[0] : ((int32_t*)ray_data(k))[0]; + int64_t k1 = byte_key ? ((uint8_t*)ray_data(k))[1] : ((int32_t*)ray_data(k))[1]; + if (k0 != (byte_key ? 1 : 0) || k1 != (byte_key ? 2 : 1) || + ((int64_t*)ray_data(cnt))[0] != 3 * repeats || + ((int64_t*)ray_data(cnt))[1] != 3 * repeats) goto done; + if (qi == 0) { + if (((int64_t*)ray_data(z))[0] != 4 * repeats || + ((int64_t*)ray_data(z))[1] != 6 * repeats) goto done; + } else { + /* Null IDs contribute to COUNT(k), not to AVG's divisor. */ + if (((double*)ray_data(z))[0] != 2.0 || + ((double*)ray_data(z))[1] != 3.0) goto done; + } + sr_drop(res); res = NULL; + } + why = NULL; +done: + ray_group_test_route(0); + sr_drop(res); sr_drop(tbl); sr_drop(enc); sr_drop(kv); sr_drop(sv); + /* T's retained table/column references are released by sr_rt_teardown; + * the runtime must outlive those and all local SYM/encoded references. */ + TEST_ASSERT_FMT(why == NULL, "runtime SYM strlen query %d: %s", qi, + why ? why : "ok"); + PASS(); +} + +static test_result_t test_strlen_runtime_sym_gen2(void) { + return strlen_runtime_sym_gen2_case(1032, false); +} + +static test_result_t test_parallel_strlen_runtime_sym_gen2(void) { + ray_pool_t* pool = ray_pool_get(); + if (!pool || ray_pool_total_workers(pool) < 2) SKIP("no pool worker"); + /* Two full chunks and a tail; default parallel admission remains active. */ + return strlen_runtime_sym_gen2_case(132000, false); +} + +static test_result_t test_strlen_runtime_sym_bytekey(void) { + /* Nonzero U8 keys avoid unrelated byte-null policy; one-byte piece loads. */ + return strlen_runtime_sym_gen2_case(1032, true); +} + +static test_result_t test_strlen_str_gen2_routes(void) { + const int64_t n = 70000; + static const char abc[] = "abcdefg"; + ray_t* sv = ray_vec_new(RAY_STR, n); sv->len = 0; + int64_t gsum[3] = { 0 }, gcnt[3] = { 0 }, tsum = 0, tcnt = 0; + for (int64_t r = 0; r < n; r++) { + int64_t l = sr_strlen_len(r); + sv = ray_str_vec_append(sv, abc, (size_t)l); + gsum[r % 3] += l; tsum += l; + if (l != 0) { gcnt[r % 3]++; tcnt++; } + } + ray_env_set(ray_sym_intern("slv", 3), sv); ray_release(sv); + sr_eval_ok("(set i (til 70000))"); + sr_eval_ok("(set M (table [g h s y] (list (% i 3) (% (* i 7919) 50021) slv (as 'SYM slv))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sl0/\" M {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/sl2/\" M {compress: true})"); + const char* t0 = "(.db.splayed.get \"" SR_TMP "/sl0/\")"; + const char* t2 = "(.db.splayed.get \"" SR_TMP "/sl2/\")"; + /* the reference itself on the scalar and direct-array routes: an empty + * string is null and is excluded from the AVG divisor (#888) */ + for (int k3 = 0; k3 < 6; k3++) { + int gen = k3 % 3; + ray_group_test_route(k3 / 3); + sr_evalf_ok("(set T %s)", gen == 0 ? "M" : gen == 1 ? t0 : t2); + ray_t* a = sr_eval("(at (select {a: (avg (strlen s)) from: T by: g asc: g}) 'a)"); + TEST_ASSERT_FMT(a && !RAY_IS_ERR(a) && a->type == RAY_F64 && a->len == 3, "route %d source %d: grouped avg", k3 / 3, gen); + for (int k = 0; k < 3; k++) + TEST_ASSERT_FMT(fabs(((double*)ray_data(a))[k] - (double)gsum[k] / (double)gcnt[k]) < 1e-9, + "route %d source %d group %d: %.17g, want %.17g", k3 / 3, gen, k, ((double*)ray_data(a))[k], + (double)gsum[k] / (double)gcnt[k]); + sr_drop(a); + ray_t* s = sr_eval("(first (at (select {a: (avg (strlen s)) from: T}) 'a))"); + ray_group_test_route(0); + TEST_ASSERT_FMT(s && !RAY_IS_ERR(s) && s->type == -RAY_F64 && + fabs(s->f64 - (double)tsum / (double)tcnt) < 1e-9, "source %d: scalar avg", gen); + sr_drop(s); + } + static const struct { const char* q; uint64_t mat; } qs[] = { + { "(select {a: (avg (strlen s)) b: (sum (strlen s)) c: (count s) from: T by: g asc: g})", 1 }, + { "(select {a: (avg (strlen s)) b: (sum (strlen s)) c: (count s) from: T})", 1 }, + { "(select {a: (avg (strlen s)) from: T where: (> g 0)})", 1 }, + { "(select {a: (avg (strlen s)) b: (sum (strlen s)) from: T where: (!= g 1) by: g asc: g})", 1 }, + { "(select {a: (avg (strlen s)) l: (avg (strlen y)) b: (sum (strlen y)) from: T by: g asc: g})", 1 }, + { "(select {a: (avg (strlen s)) c: (count g) from: T by: h asc: h})", 1 }, /* wide key */ + { "(select {mn: (min (strlen s)) mx: (max (strlen s)) a: (avg (strlen s)) from: T by: g asc: g})", 1 }, + { NULL, 0 }, + }; + for (int route = 0; route <= 2; route++) { + for (int i = 0; qs[i].q; i++) { + ray_group_test_route(route); + agg_route_reset(); + test_result_t r = sr_same_on(t0, t2, qs[i].q, qs[i].mat); + if (r.status == TEST_PASS) r = sr_same_on("M", t2, qs[i].q, UINT64_MAX); + agg_route_stats_t st = agg_route_stats(); + ray_group_test_route(0); + if (r.status != TEST_PASS) return r; + if (route) TEST_ASSERT_FMT(st.routes[AGG_ROUTE_LEGACY] > 0, "route %d %s: not the legacy ladder", + route, qs[i].q); + } + } + /* per partition: three partitions of the same rows */ + for (int gen = 0; gen <= 2; gen += 2) + for (int p = 0; p < 3; p++) + sr_evalf_ok("(.db.splayed.set \"" SR_TMP "/slp%d/2024.01.0%d/t/\" M \"" SR_TMP "/slp%d/.sym\" " + "{compress: %s})", gen, p + 1, gen, gen ? "true" : "false"); + sr_eval_ok("(set M3 (table [g h s y] (list (concat (concat (% i 3) (% i 3)) (% i 3)) " + "(concat (concat (at M 'h) (at M 'h)) (at M 'h)) (concat (concat slv slv) slv) " + "(concat (concat (at M 'y) (at M 'y)) (at M 'y)))))"); + for (int gen = 0; gen <= 2; gen += 2) { + char tp[256]; + snprintf(tp, sizeof tp, "(.db.parted.get \"" SR_TMP "/slp%d\" 't)", gen); + for (int i = 0; qs[i].q; i++) { + int64_t r0 = ray_group_perpart_runs(); + test_result_t r = sr_same_on("M3", tp, qs[i].q, UINT64_MAX); + if (r.status != TEST_PASS) return r; + if (strstr(qs[i].q, "by: g")) + TEST_ASSERT_FMT(ray_group_perpart_runs() > r0, "gen %d %s: not the per-partition route", gen, qs[i].q); + } + } + PASS(); +} + +/* Task 17d: a ragged generation-0 table's synthetic null segment is + * decided from its statistics, never decoded. A compare over the column + * fills its rows from the all-null rule (the predicate and the count of a + * select); the in-place group reads the plain segments where they are and + * the stand-in as a fill of nulls. Answers equal the explicit-null + * reference, nothing is decoded or materialized. */ +static test_result_t test_ragged_gen0_no_decode(void) { + sr_parted_xy(SR_TMP "/rnd", 0, true, false); + sr_parted_xy(SR_TMP "/rnf", 0, false, true); + /* skips: the stand-in's 70000 rows are 69 morsels, each decided by the + * all-null rule (the real partitions' y spans 0..96 in every chunk, so + * no other morsel is decided); fill: the group's null fill, 70000 I64 */ + static const char* const q[] = { + "(count (select {from: T where: (!= y 0)}))", + "(count (select {from: T where: (== y 5)}))", + "(count (select {from: T where: (< y 3)}))", + "(count (select {from: T where: (<= y 3)}))", + "(count (select {from: T where: (> y 3)}))", + "(count (select {from: T where: (>= y 3)}))", + "(count (select {from: T where: (and (> x 100) (!= y 7))}))", + "(select {s: (sum x) from: T where: (< y 50)})", + "(select {c: (count y) from: T where: (!= y 0) by: y desc: c take: 5})", + "(select {c: (count x) s: (sum x) from: T by: y asc: y take: 3})", + "(select {s: (sum y) c: (count y) from: T by: x desc: s take: 3})", + "(select {s: (sum x) from: T by: y desc: s take: 4})", + /* a null constant: the zone rule leaves every morsel mixed (ZT_MIXED), + * the stand-in included; the compare reads the stand-in's nulls (its + * materialization: the decode pins do not apply to these three) */ + "(count (select {from: T where: (== y 0Nl)}))", + "(count (select {from: T where: (!= y 0Nl)}))", + "(count (select {from: T where: (and (> x 100) (== y 0Nl))}))", + NULL, + }; + static const int64_t skips[] = { 69, 69, 69, 69, 69, 69, 0, 69, 0, 0, 0, 0, 0, 0, 0 }; + static const int64_t fill[] = { 0, 0, 0, 0, 0, 0, 0, 0, 560000, 560000, 560000, 560000, 0, 0, 0 }; + for (int i = 0; q[i]; i++) { + sr_eval_ok("(set T (.db.parted.get \"" SR_TMP "/rnf\" 't))"); + ray_t* r0 = sr_eval(q[i]); + sr_eval_ok("(set T (.db.parted.get \"" SR_TMP "/rnd\" 't))"); + ray_enc_counters_reset(); + int64_t z0 = ray_expr_test_zone_skips(), f0 = ray_group_null_fill_bytes(); + ray_t* r1 = sr_eval(q[i]); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(sr_same_text(r0, r1), "ragged: %s", q[i]); + TEST_ASSERT_FMT(i >= 12 || (k.decoded_bytes == 0 && k.materialized == 0), "%s: %llu bytes decoded, %llu materialized", + q[i], (unsigned long long)k.decoded_bytes, (unsigned long long)k.materialized); + int64_t dz = ray_expr_test_zone_skips() - z0, df = ray_group_null_fill_bytes() - f0; + TEST_ASSERT_FMT(dz == skips[i], "%s: %lld morsels decided from statistics, want %lld", q[i], + (long long)dz, (long long)skips[i]); + TEST_ASSERT_FMT(df == fill[i], "%s: %lld bytes of null fill, want %lld", q[i], (long long)df, (long long)fill[i]); + sr_drop(r0); sr_drop(r1); + } + /* Fix round 1: the all-null rules trust only a synthetic stand-in. The + * same nulls saved encoded (the reference's third partition, generation + * 2) are decoded, and so validated, though their directory says every + * row is null: no morsel is decided by the rule, and the answer is the + * same. */ + sr_parted_xy(SR_TMP "/rne", 4, false, true); + for (int i = 0; i < 6; i++) { + sr_eval_ok("(set T (.db.parted.get \"" SR_TMP "/rnf\" 't))"); + ray_t* r0 = sr_eval(q[i]); + sr_eval_ok("(set T (.db.parted.get \"" SR_TMP "/rne\" 't))"); + ray_enc_counters_reset(); + int64_t z0 = ray_expr_test_zone_skips(); + ray_t* r1 = sr_eval(q[i]); + ray_enc_counters_t k; ray_enc_counters_get(&k); + TEST_ASSERT_FMT(sr_same_text(r0, r1), "saved nulls: %s", q[i]); + /* P3 Task 3: the all-null rule decides no morsel; the predicate's + * vectors are viewed instead of decoded (an encoded leaf), and a + * view makes every check that decode would: nothing is decoded or + * materialized */ + TEST_ASSERT_FMT(ray_expr_test_zone_skips() == z0 && k.decoded_bytes == 0 && k.materialized == 0, + "saved nulls %s: %lld morsels decided, %llu bytes decoded, %llu materialized", q[i], + (long long)(ray_expr_test_zone_skips() - z0), (unsigned long long)k.decoded_bytes, + (unsigned long long)k.materialized); + sr_drop(r0); sr_drop(r1); + } + PASS(); +} + +/* Fix round 1 of Task 17d: the group's null fill for a ragged stand-in is + * transient memory of rows x width, so one query builds at most the group's + * transient budget (AGG_COMPACT_BITMAP_BUDGET) of it. A stand-in of more + * rows than that holds of I64 is grouped by the piece walk instead: no fill + * byte, nothing materialized, the explicit-null reference's answers, on the + * in-place group and per partition (each query's route pinned). The budget + * is the query's, shared by its columns: two stand-ins that each fit but not + * together get one fill, the other is walked. */ +static test_result_t sr_fill_route(const char* ref, const char* dut, const char* q, bool in_place, + int64_t want_fill) { + sr_evalf_ok("(set T (.db.parted.get \"%s\" 't))", ref); + ray_t* r0 = sr_eval(q); + sr_evalf_ok("(set T (.db.parted.get \"%s\" 't))", dut); + ray_enc_counters_reset(); + int64_t f0 = ray_group_null_fill_bytes(), s0 = ray_group_segstream_runs(), p0 = ray_group_perpart_runs(); + ray_t* r1 = sr_eval(q); + ray_enc_counters_t k; ray_enc_counters_get(&k); + int64_t ds = ray_group_segstream_runs() - s0, dp = ray_group_perpart_runs() - p0; + TEST_ASSERT_FMT(sr_same_text(r0, r1), "ragged: %s", q); + TEST_ASSERT_FMT(ray_group_null_fill_bytes() - f0 == want_fill, "%s: %lld bytes of null fill, want %lld", q, + (long long)(ray_group_null_fill_bytes() - f0), (long long)want_fill); + TEST_ASSERT_FMT(k.materialized == 0, "%s: %llu materialized", q, (unsigned long long)k.materialized); + TEST_ASSERT_FMT(in_place ? (ds == 1 && dp == 0) : (ds == 0 && dp == 1), "%s: in place %lld, per partition %lld", + q, (long long)ds, (long long)dp); + sr_drop(r0); sr_drop(r1); + PASS(); +} +static test_result_t test_ragged_fill_bounded(void) { + const int64_t big = (int64_t)(AGG_COMPACT_BITMAP_BUDGET / sizeof(int64_t)) + 65536; + for (int ref = 0; ref < 2; ref++) { + const char* root = ref ? SR_TMP "/rbf" : SR_TMP "/rbd"; + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.01/t/\" (table [x k y] (list (%% (til 70000) 7) (til 70000) " + "(%% (til 70000) 97))) {compress: false})", root); + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.02/t/\" %s {compress: false})", root, + ref ? "(table [x k y] (list (% (til 4259840) 7) (til 4259840) (take [0Nl] 4259840)))" + : "(table [x k] (list (% (til 4259840) 7) (til 4259840)))"); + } + TEST_ASSERT_FMT(big == 4259840, "budget rows %lld: update the partition size", (long long)big); + /* a key of few groups is grouped per partition; a key of a group per + * row in place */ + static const struct { const char* q; bool in_place; } q[] = { + { "(select {s: (sum y) c: (count y) from: T by: x asc: x})", false }, + { "(select {s: (sum y) c: (count y) a: (avg y) from: T by: x asc: x})", false }, + { "(select {c: (count x) s: (sum x) from: T by: y asc: y take: 3})", false }, + { "(select {s: (sum x) from: T by: y desc: s take: 4})", false }, + { "(select {s: (sum y) c: (count y) from: T by: k desc: s take: 3})", true }, + { "(select {c: (count y) from: T by: k desc: c take: 3})", true }, + { NULL, false }, + }; + test_result_t r; + for (int i = 0; q[i].q; i++) + if ((r = sr_fill_route(SR_TMP "/rbf", SR_TMP "/rbd", q[i].q, q[i].in_place, 0)).status != TEST_PASS) return r; + /* two stand-ins of 3M I64 rows (24 MB each, 48 MB together) */ + const int64_t two = 3000000; + TEST_ASSERT_TRUE(two * 8 <= (int64_t)AGG_COMPACT_BITMAP_BUDGET && 2 * two * 8 > (int64_t)AGG_COMPACT_BITMAP_BUDGET); + for (int ref = 0; ref < 2; ref++) { + const char* root = ref ? SR_TMP "/r2f" : SR_TMP "/r2d"; + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.01/t/\" (table [x k y z] (list (%% (til 70000) 7) (til 70000) " + "(%% (til 70000) 97) (%% (til 70000) 89))) {compress: false})", root); + sr_evalf_ok("(.db.splayed.set \"%s/2024.01.02/t/\" %s {compress: false})", root, + ref ? "(table [x k y z] (list (% (til 3000000) 7) (til 3000000) (take [0Nl] 3000000) (take [0Nl] 3000000)))" + : "(table [x k] (list (% (til 3000000) 7) (til 3000000)))"); + } + static const struct { const char* q; bool in_place; } q2[] = { + { "(select {s: (sum y) t: (sum z) from: T by: x asc: x})", false }, + { "(select {s: (sum y) t: (sum z) c: (count z) from: T by: k desc: s take: 3})", true }, + { NULL, false }, + }; + for (int i = 0; q2[i].q; i++) + if ((r = sr_fill_route(SR_TMP "/r2f", SR_TMP "/r2d", q2[i].q, q2[i].in_place, two * 8)).status != TEST_PASS) + return r; + PASS(); +} + +/* Task 17b: vectors decided from their 1024-row descriptors where the + * 64K-row directory leaves the chunk undecided. a (I16): every fourth + * vector runs of 64 rows of 0 and 7 (RLE, statistics [0, 7]), the others + * all 0 (CONST); every chunk is [0, 7], so no chunk is decided. c (I32): + * every third vector 5 with one null, the others 9. The count fast path, + * the expression gate and the fused predicate skip (or fill) the decided + * vectors and decode only the 49 RLE vectors of a, once each (P3: the + * count fast path counts them on their runs, decoding none); the answers + * are generation 0's. */ +#define VD_N 200000 +#define VD_RLE 49 /* vectors v % 4 == 1 of 196 */ +static void sr_vd_tables(void) { + ray_t* a = ray_vec_new(RAY_I16, VD_N); a->len = VD_N; + ray_t* b = ray_vec_new(RAY_I64, VD_N); b->len = VD_N; + ray_t* c = ray_vec_new(RAY_I32, VD_N); c->len = VD_N; + for (int64_t i = 0; i < VD_N; i++) { + const int64_t v = i / RAY_ENC_VEC; + ((int16_t*)ray_data(a))[i] = v % 4 == 1 ? (int16_t)((i / 64) % 2 * 7) : 0; + ((int64_t*)ray_data(b))[i] = i; + ((int32_t*)ray_data(c))[i] = v % 3 == 0 ? (i % RAY_ENC_VEC == 17 ? NULL_I32 : 5) : 9; + } + c->attrs |= RAY_ATTR_HAS_NULLS; + ray_env_set(ray_sym_intern("vda", 3), a); ray_release(a); + ray_env_set(ray_sym_intern("vdb", 3), b); ray_release(b); + ray_env_set(ray_sym_intern("vdc", 3), c); ray_release(c); + sr_eval_ok("(set VD (table [a b c] (list vda vdb vdc)))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/vd2/\" VD {compress: true})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/vd0/\" VD {compress: false})"); +} +static ray_op_t* vd_a_ne0(ray_graph_t* g) { return ray_ne(g, ray_scan(g, "a"), ray_const_i64(g, 0)); } +static ray_op_t* vd_a_gt3(ray_graph_t* g) { return ray_gt(g, ray_scan(g, "a"), ray_const_i64(g, 3)); } +static ray_op_t* vd_a_eq0(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "a"), ray_const_i64(g, 0)); } +static ray_op_t* vd_c_eq5(ray_graph_t* g) { return ray_eq(g, ray_scan(g, "c"), ray_const_i64(g, 5)); } +static test_result_t test_vec_stat_decide(void) { + sr_vd_tables(); + const char* t0 = "(.db.splayed.get \"" SR_TMP "/vd0/\")"; + const char* t2 = "(.db.splayed.get \"" SR_TMP "/vd2/\")"; + const uint64_t rle_bytes = (uint64_t)VD_RLE * RAY_ENC_VEC * 2; + /* the count fast path */ + static const char* const cq[] = { + "(count (select {from: T where: (!= a 0)}))", "(count (select {from: T where: (== a 0)}))", + "(count (select {from: T where: (> a 3)}))", "(count (select {from: T where: (<= a 0)}))", + "(count (select {from: T where: (< 3 a)}))", NULL, + }; + for (int i = 0; cq[i]; i++) { + test_result_t r = sr_same_on(t0, t2, cq[i], 0); + if (r.status != TEST_PASS) return r; + sr_evalf_ok("(set T %s)", t2); + uint64_t a0 = sr_col_decoded("a"), f0 = ray_query_test_count_fast(); + ray_t* res = sr_eval(cq[i]); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + sr_drop(res); + TEST_ASSERT_FMT(ray_query_test_count_fast() - f0 == 1, "%s: not the count fast path", cq[i]); + /* P3 Task 3b: the undecided RLE vectors count on their runs */ + TEST_ASSERT_FMT(sr_col_decoded("a") - a0 == 0, "%s: %llu bytes of a decoded, want 0", cq[i], + (unsigned long long)(sr_col_decoded("a") - a0)); + } + /* the expression gate (a select over the predicate) */ + /* c: the 66 vectors of 5 (the last one 320 rows) hold a null, so they + * stay undecided; the 130 vectors of 9 are decided. (== c 9) is decided + * on every vector. The OR is checked for its answer only. P3 Task 3: + * the undecided vectors (a's RLE runs, c's nullable CONST 5) are + * answered as encoded leaves on their views, so neither decodes (the + * a / c flags below now pin 0 bytes; c5_bytes stays for the record). */ + const uint64_t c5_bytes = 65 * RAY_ENC_VEC * 4 + 320 * 4; + static const struct { const char* q; int64_t a, c, skips; } eq[] = { + { "(select {s: (sum b) from: T where: (!= a 0)})", 0, 0, 147 }, + { "(select {s: (sum b) c: (count b) from: T where: (> a 3)})", 0, 0, 147 }, + { "(select {s: (sum b) from: T where: (== c 5)})", 0, 0, 130 }, + { "(select {s: (sum b) from: T where: (!= c 9)})", 0, 0, 130 }, + /* (== c 9) first (196 decided); then (== a 0) refines its selection + * on the segments it keeps, answered by the encoded leaves on their + * views, which count no zone decision (P3 Task 6b: a chained filter + * over an encoded column evaluates only the kept segments; before, + * it was evaluated over every morsel, 147 decided) */ + { "(select {s: (sum b) from: T where: (and (== a 0) (== c 9))})", 0, 0, 196 }, + { "(select {s: (sum b) from: T where: (or (> a 3) (== c 5))})", -1, -1, -1 }, + { NULL, 0, 0, 0 }, + }; + for (int i = 0; eq[i].q; i++) { + test_result_t r = sr_same_on(t0, t2, eq[i].q, UINT64_MAX); + if (r.status != TEST_PASS) return r; + sr_evalf_ok("(set T %s)", t2); + uint64_t a0 = sr_col_decoded("a"), c0 = sr_col_decoded("c"); + int64_t z0 = ray_expr_test_zone_skips(); + ray_t* res = sr_eval(eq[i].q); + TEST_ASSERT_TRUE(res && !RAY_IS_ERR(res)); + sr_drop(res); + if (eq[i].skips < 0) continue; + uint64_t da = sr_col_decoded("a") - a0, dc = sr_col_decoded("c") - c0; + int64_t dz = ray_expr_test_zone_skips() - z0; + TEST_ASSERT_FMT(da == (eq[i].a ? rle_bytes : 0) && dc == (eq[i].c ? c5_bytes : 0) && dz == eq[i].skips, + "%s: a %llu, c %llu bytes decoded, %lld morsels decided", eq[i].q, + (unsigned long long)da, (unsigned long long)dc, (long long)dz); + } + /* the fused predicate, morsel by morsel */ + ray_op_t* (*const fb[])(ray_graph_t*) = { vd_a_ne0, vd_a_gt3, vd_a_eq0, vd_c_eq5 }; + ray_t* g0t = sr_eval(t0); ray_t* g2t = sr_eval(t2); + for (size_t i = 0; i < sizeof fb / sizeof fb[0]; i++) { + ray_graph_t* g0 = ray_graph_new(g0t); ray_graph_t* g2 = ray_graph_new(g2t); + fp_pred_t p0, p2; + memset(&p0, 0, sizeof p0); memset(&p2, 0, sizeof p2); + ray_t* e0 = NULL; ray_t* e2 = NULL; + TEST_ASSERT_EQ_I(fp_compile_pred(g0, fb[i](g0), g0t, &p0, &e0), 0); + TEST_ASSERT_EQ_I(fp_compile_pred(g2, fb[i](g2), g2t, &p2, &e2), 0); + TEST_ASSERT_TRUE(!e0 && !e2 && p2.n_children == 1 && p2.children[0].enc); + fp_scratch_t sc; fp_scratch_init(&sc); + uint8_t x[RAY_MORSEL_ELEMS], y[RAY_MORSEL_ELEMS]; + ray_enc_counters_reset(); + for (int64_t ms = 0; ms < VD_N; ms += RAY_MORSEL_ELEMS) { + int64_t me = ms + RAY_MORSEL_ELEMS < VD_N ? ms + RAY_MORSEL_ELEMS : VD_N; + fp_eval_pred(&p0, ms, me, x); + TEST_ASSERT_NULL(fp_eval_pred_rs(&p2, ms, me, y, &sc)); + TEST_ASSERT_FMT(memcmp(x, y, (size_t)(me - ms)) == 0, "fused %zu: morsel at %lld", i, (long long)ms); + } + fp_scratch_free(&sc); + ray_enc_counters_t k; ray_enc_counters_get(&k); + /* c is nullable: its typed compare reads every vector (no gate); + * a's RLE vectors are answered on their views (P3 Task 3) */ + const uint64_t want = i < 3 ? 0 : (uint64_t)VD_N * 4; + TEST_ASSERT_FMT(k.decoded_bytes == want, "fused %zu: %llu bytes decoded, want %llu", i, + (unsigned long long)k.decoded_bytes, (unsigned long long)want); + fp_pred_cleanup(&p0); fp_pred_cleanup(&p2); + ray_graph_free(g0); ray_graph_free(g2); + } + sr_drop(g0t); sr_drop(g2t); + PASS(); +} + +/* Chunk pruning of a conjunctive filter chain over generation 2 + * (exec_filter_chain_prune): the outermost filter decides each comparison + * or `in` conjunct from the chunk directory, then from the vectors' + * descriptors, and the chain runs as chained filters over the rows no + * conjunct excludes. 200000 rows (three full chunks and a short fourth, + * 196 vectors, the last one 320 rows); c is sorted (1000 rows per value), + * x is the row, h a scattered I64, n an I64 with a null every 7 rows, f a + * sorted F64 with a NaN null every 11 rows, d a DATE and t a TIMESTAMP + * that cycle within every 1000 rows, k a HASH-indexed column, m the row + * as an I64 with a null every 11 rows. Every + * answer equals generation 0's; `segs` is the exact number of vectors the + * pruning dropped (0: the chain is not pruned), and a pruned query decodes + * nothing outside the vectors it keeps. */ +static test_result_t test_chain_zone_prune(void) { + sr_eval_ok("(set i (til 200000))"); + sr_eval_ok("(set Z (table [x c d h n f t r k m] (list i (as 'I32 (div i 1000)) (as 'DATE (div (% i 1000) 10)) " + "(% (* i 7919) 1000003) (as 'I64 (map (fn [j] (if (== 0 (% j 7)) 0N (% j 50))) i)) " + "(as 'F64 (map (fn [j] (if (== 0 (% j 11)) 0N j)) i)) " + "(as 'TIMESTAMP (* (div (% i 1000) 10) 86400000000000)) (as 'I16 (% i 3)) " + "(.idx.hash (% (* i 31) 100003)) (as 'I64 (map (fn [j] (if (== 0 (% j 11)) 0N j)) i)))))"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/zp0/\" Z {compress: false})"); + sr_eval_ok("(.db.splayed.set \"" SR_TMP "/zp2/\" Z {compress: true})"); + static const struct { const char* q; uint64_t segs; } qs[] = { + /* c == 70: rows 70000..70999, vectors 68 and 69 */ + { "(select {x: x h: h from: T where: (and (== c 70) (> h 500000))})", 194 }, + /* exactly chunk 1: its statistics decide both bounds all-pass */ + { "(select {s: (sum x) c: (count x) from: T where: (and (>= x 65536) (< x 131072) (> h 500000))})", 132 }, + /* exactly vector 1, and the short last vector */ + { "(select {s: (sum x) c: (count x) from: T where: (and (>= x 1024) (< x 2048) (> h 0))})", 195 }, + { "(select {s: (sum h) c: (count x) from: T where: (and (>= x 199900) (> h 0))})", 195 }, + /* nothing matches */ + { "(select {s: (sum x) c: (count x) from: T where: (and (== c 5000) (> h 0))})", 196 }, + /* everything, and three quarters: not pruned */ + { "(select {s: (sum x) c: (count x) from: T where: (and (>= c 0) (> h 500000))})", 0 }, + { "(select {s: (sum x) c: (count x) from: T where: (and (< c 150) (> h 0))})", 0 }, + /* a null ranks below every value: (< n 10) holds on the nulls */ + { "(select {s: (sum x) c: (count x) from: T where: (and (== c 70) (< n 10))})", 194 }, + /* a null literal and a null `in` member select the null rows: no + * statistic decides them (only c < 3 prunes, vectors 0..2 kept) */ + { "(select {s: (sum x) c: (count x) from: T where: (and (== n 0Nl) (< c 3))})", 193 }, + { "(select {s: (sum x) c: (count x) from: T where: (and (in n [0Nl 500]) (< c 3))})", 193 }, + { "(select {s: (sum x) c: (count x) from: T where: (and (in c [3 70 150]) (> h 0))})", 190 }, + /* nulls rank below every value: m and f climb with the row, so every + * chunk past the first holds no value below 100 but holds nulls, + * which pass `<` (nothing is pruned) */ + { "(select {s: (sum x) c: (count x) from: T where: (and (< m 100) (> h 0))})", 0 }, + { "(select {s: (sum x) c: (count x) from: T where: (and (< f 100.5) (> h 0))})", 0 }, + /* floats: NaN nulls fail >, the vectors below 150000.5 are dropped */ + { "(select {s: (sum x) c: (count x) from: T where: (and (> f 150000.5) (== r 1))})", 146 }, + /* a TIMESTAMP literal on a DATE column is converted by the kernel: + * never decided on raw values (only c < 3 prunes) */ + { "(select {s: (sum x) c: (count x) from: T where: (and (> d 2000.01.01D12:00:00.000000000) (< c 3))})", 193 }, + { "(select {s: (sum x) c: (count x) from: T where: (and (< t 2000.01.03) (< c 3))})", 193 }, + { "(select {s: (sum x) c: (count x) from: T where: (and (within d [2000.01.05 2000.01.06]) (< c 3))})", 193 }, + /* grouped, as the Q41 shape */ + { "(select {v: (count h) from: T where: (and (== c 70) (== r 1) (in d [2000.01.03 2000.01.04])) by: d desc: v})", 194 }, + /* a conjunct that reads other rows: the chain is left alone */ + { "(select {s: (sum x) c: (count x) from: T where: (and (== c 70) (> h (avg h)))})", 0 }, + /* a recorded HASH the index route uses: left to it */ + { "(select {s: (sum x) c: (count x) from: T where: (and (== k 4242) (< c 3))})", 0 }, + /* an `or` is no pruning conjunct */ + { "(select {s: (sum x) c: (count x) from: T where: (and (or (== c 70) (== c 150)) (> h 0))})", 0 }, + { NULL, 0 }, + }; + for (int i = 0; qs[i].q; i++) { + ray_t* out[2] = { NULL, NULL }; + uint64_t dc[2], ds[2]; + ray_enc_counters_t k; + for (int gen = 0; gen < 2; gen++) { + sr_eval_ok(gen ? "(set T (.db.splayed.get \"" SR_TMP "/zp2/\"))" : "(set T (.db.splayed.get \"" SR_TMP "/zp0/\"))"); + uint64_t c0, s0, c1, s1; + ray_exec_test_zone_prune(&c0, &s0); + ray_enc_counters_reset(); + out[gen] = sr_eval(qs[i].q); + ray_enc_counters_get(&k); + ray_exec_test_zone_prune(&c1, &s1); + dc[gen] = c1 - c0; ds[gen] = s1 - s0; + TEST_ASSERT_FMT(out[gen] && !RAY_IS_ERR(out[gen]), "%s gen %d: %s", qs[i].q, gen * 2, + out[gen] ? ray_error_msg() : "no result"); + } + TEST_ASSERT_FMT(sr_same_text(out[0], out[1]), "%s: generations differ", qs[i].q); + TEST_ASSERT_FMT(dc[0] == 0 && ds[0] == 0, "%s: generation 0 pruned", qs[i].q); + TEST_ASSERT_FMT(dc[1] == (qs[i].segs ? 1u : 0u) && ds[1] == qs[i].segs, + "%s: %llu chains pruned, %llu vectors dropped, want %llu", qs[i].q, + (unsigned long long)dc[1], (unsigned long long)ds[1], (unsigned long long)qs[i].segs); + /* at most four 8-byte columns over the kept vectors and two more */ + if (qs[i].segs) + TEST_ASSERT_FMT(k.materialized == 0 && k.decoded_bytes <= (196 - qs[i].segs + 2) * 4 * 8 * 1024, + "%s: %llu decoded bytes, %llu materialized", qs[i].q, + (unsigned long long)k.decoded_bytes, (unsigned long long)k.materialized); + sr_drop(out[0]); sr_drop(out[1]); + } + PASS(); +} + +const test_entry_t scanrange_entries[] = { + { "scanrange/walk_gen0_zero_copy", test_walk_gen0_zero_copy, sr_setup, sr_teardown }, + { "scanrange/walk_gen2_vectors", test_walk_gen2_vectors, sr_setup, sr_teardown }, + { "scanrange/walk_decoded_cache", test_walk_decoded_cache, sr_setup, sr_teardown }, + { "scanrange/walk_unaligned_mixed", test_walk_unaligned_mixed, sr_setup, sr_teardown }, + { "scanrange/walk_str_pool_from_view", test_walk_str_pool_from_view, sr_setup, sr_teardown }, + { "scanrange/walk_sym_widths", test_walk_sym_widths, sr_rt_setup, sr_rt_teardown }, + { "scanrange/walk_ragged_parted", test_walk_ragged_parted, sr_rt_setup, sr_rt_teardown }, + { "scanrange/cursor_reuses_vector", test_cursor_reuses_vector, sr_setup, sr_teardown }, + { "scanrange/walk_contiguous_floats", test_walk_contiguous_floats, sr_setup, sr_teardown }, + { "scanrange/scan_fail_lowest_key", test_scan_fail_lowest_key, sr_setup, sr_teardown }, + { "scanrange/raw_is_null", test_raw_is_null, sr_setup, sr_teardown }, + { "scanrange/scan_fail_concurrent", test_scan_fail_concurrent, sr_setup, sr_teardown }, + { "scanrange/scan_fail_skip", test_scan_fail_skip, sr_setup, sr_teardown }, + { "scanrange/scan_fail_cancel", test_scan_fail_cancel, sr_rt_setup, sr_rt_teardown }, + { "scanrange/walk_parted_10k", test_walk_parted_10k, sr_setup, sr_teardown }, + { "scanrange/walk_null_and_many", test_walk_null_and_many_sources, sr_setup, sr_teardown }, + { "scanrange/walk_contig_nyi_range", test_walk_contig_nyi_and_cursor_range, sr_setup, sr_teardown }, + { "scanrange/walk_plain_slice", test_walk_plain_slice, sr_setup, sr_teardown }, + { "scanrange/walk_materialized_parted", test_walk_materialized_parted, sr_rt_setup, sr_rt_teardown }, + { "scanrange/walk_contig_views", test_walk_contig_views, sr_setup, sr_teardown }, + { "scanrange/chunk_stat_matches_data", test_chunk_stat_matches_data, sr_setup, sr_teardown }, + { "scanrange/byte_range_from_directory", test_byte_range_from_directory, sr_setup, sr_teardown }, + { "scanrange/chunk_stat_all_null", test_chunk_stat_all_null, sr_setup, sr_teardown }, + { "scanrange/chunk_stat_wide_sums", test_chunk_stat_wide_sums, sr_setup, sr_teardown }, + { "scanrange/chunk_stat_f64", test_chunk_stat_f64, sr_setup, sr_teardown }, + { "scanrange/byte_range_edges", test_byte_range_edges, sr_setup, sr_teardown }, + { "scanrange/advise_spans", test_advise_spans, sr_setup, sr_teardown }, + { "scanrange/expr_select_equal", test_expr_select_equal, srr_setup, srr_teardown }, + { "scanrange/expr_elementwise_equal", test_expr_elementwise_equal, srr_setup, srr_teardown }, + { "scanrange/expr_nulls_midvector", test_expr_nulls_midvector, srr_setup, srr_teardown }, + { "scanrange/count_fast_path", test_count_fast_path, srr_setup, srr_teardown }, + { "scanrange/count_fast_lent_scratch", test_count_fast_lent_scratch, srr_setup, srr_teardown }, + { "scanrange/group_lent_scratch", test_group_lent_scratch, srr_setup, srr_pool_teardown }, + { "scanrange/count_fast_sym_nulls", test_count_fast_sym_nulls, sr_rt_setup, sr_rt_teardown }, + { "scanrange/expr_reuses_materialized", test_expr_reuses_materialized, srr_setup, srr_teardown }, + { "scanrange/expr_error_sites", test_expr_error_sites, srr_setup, srr_teardown }, + { "scanrange/decoded_bytes_pinned", test_decoded_bytes_pinned, srr_setup, srr_teardown }, + { "scanrange/count_native_kernels", test_count_native_kernels, sr_setup, sr_teardown }, + { "scanrange/count_native_queries", test_count_native_queries, sr_rt_setup, sr_rt_teardown }, + { "scanrange/expr_widened_registers", test_expr_widened_registers, srr_setup, srr_teardown }, + { "scanrange/expr_parted_segments", test_expr_parted_segments, srr_setup, srr_teardown }, + { "scanrange/expr_parted_cancel", test_expr_parted_cancel, sr_rt_setup, sr_rt_teardown }, + { "scanrange/expr_parted_seg_lengths", test_expr_parted_seg_lengths, sr_rt_setup, sr_rt_teardown }, + { "scanrange/zone_dir_skips", test_zone_dir_skips, srr_setup, srr_teardown }, + { "scanrange/zone_dir_nulls", test_zone_dir_nulls, srr_setup, srr_teardown }, + { "scanrange/filter_consult_dir", test_filter_consult_dir, srr_setup, srr_teardown }, + { "scanrange/lazy_hash_enc", test_lazy_hash_enc, srr_setup, srr_teardown }, + { "scanrange/filter_consult_enc_shapes", test_filter_consult_enc_shapes, srr_setup, srr_teardown }, + { "scanrange/lazy_memo_goes_with_table", test_lazy_memo_goes_with_table, srr_setup, srr_teardown }, + { "scanrange/zone_class_dir_small", test_zone_class_dir_small, sr_rt_setup, sr_rt_teardown }, + { "scanrange/uses_shared_payload", test_uses_shared_payload, srr_setup, srr_teardown }, + { "scanrange/zone_dir_boundaries", test_zone_dir_boundaries, srr_setup, srr_teardown }, + { "scanrange/fp_range_equal", test_fp_range_equal, srr_setup, srr_teardown }, + { "scanrange/fp_range_dir_gate", test_fp_range_dir_gate, srr_setup, srr_teardown }, + { "scanrange/fp_range_ready_child", test_fp_range_ready_child, srr_setup, srr_teardown }, + { "scanrange/fp_range_str", test_fp_range_str, sr_rt_setup, sr_rt_teardown }, + { "scanrange/fp_range_late_materialized", test_fp_range_late_materialized, srr_setup, srr_teardown }, + { "scanrange/fp_range_and_stops", test_fp_range_and_stops, srr_setup, srr_teardown }, + { "scanrange/topk_materializes_keys", test_topk_materializes_keys, srr_setup, srr_teardown }, + { "scanrange/topk_take_cancel", test_topk_take_cancel, srr_setup, srr_teardown }, + { "scanrange/in_selection", test_in_selection, srr_setup, srr_teardown }, + { "scanrange/in_selection_reuses_materialized", test_in_selection_reuses_materialized, srr_setup, srr_teardown }, + { "scanrange/in_selection_cancel", test_in_selection_cancel, srr_setup, srr_teardown }, + { "scanrange/reduce_scan", test_reduce_scan, srr_setup, srr_teardown }, + { "scanrange/reduce_scan_ops", test_reduce_scan_ops, srr_setup, srr_teardown }, + { "scanrange/reduce_scan_type_errors", test_reduce_scan_type_errors, srr_setup, srr_teardown }, + { "scanrange/reduce_scan_edges", test_reduce_scan_edges, srr_setup, srr_teardown }, + { "scanrange/reduce_dir_answers", test_reduce_dir_answers, srr_setup, srr_teardown }, + { "scanrange/at_parted_value", test_at_parted_value, srr_setup, srr_teardown }, + { "scanrange/raw_float_view", test_raw_float_view, srr_setup, srr_teardown }, + { "scanrange/scalar_route", test_scalar_route, srr_setup, srr_teardown }, + { "scanrange/scalar_route_shapes", test_scalar_route_shapes, srr_setup, srr_teardown }, + { "scanrange/scalar_route_f64_bits", test_scalar_route_f64_bits, srr_setup, srr_teardown }, + { "scanrange/group_route_hook", test_group_route_hook, srr_setup, srr_teardown }, + { "scanrange/scalar_route_wide_sym", test_scalar_route_wide_sym, srr_setup, srr_teardown }, + { "scanrange/scalar_route_mixed", test_scalar_route_mixed, srr_setup, srr_teardown }, + { "scanrange/scalar_route_f64_combine", test_scalar_route_f64_combine, srr_setup, srr_teardown }, + { "scanrange/scalar_route_f64_unaligned", test_scalar_route_f64_unaligned, srr_setup, srr_teardown }, + { "scanrange/da_route", test_da_route, srr_setup, srr_teardown }, + { "scanrange/da_route_shapes", test_da_route_shapes, srr_setup, srr_teardown }, + { "scanrange/da_route_parted", test_da_route_parted, srr_setup, srr_teardown }, + { "scanrange/sp_dyn_route", test_sp_dyn_route, srr_setup, srr_teardown }, + { "scanrange/radix_route", test_radix_route, srr_setup, srr_teardown }, + { "scanrange/radix_route_shapes", test_radix_route_shapes, srr_setup, srr_teardown }, + { "scanrange/radix_route_sparse", test_radix_route_sparse, srr_setup, srr_teardown }, + { "scanrange/radix_route_serial", test_radix_route_serial, srr_setup, srr_teardown }, + { "scanrange/v2_routes", test_v2_routes, srr_setup, srr_teardown }, + { "scanrange/v2_dense_unaligned", test_v2_dense_unaligned, srr_setup, srr_pool_teardown }, + { "scanrange/v2_sym_key_parted", test_v2_sym_key_parted, srr_setup, srr_teardown }, + { "scanrange/v2_parted_routes", test_v2_parted_routes, srr_setup, srr_teardown }, + { "scanrange/parted_concat_in_place", test_parted_concat_in_place, srr_setup, srr_teardown }, + { "scanrange/parted_concat_matches_flat", test_parted_concat_matches_flat, srr_setup, srr_teardown }, + { "scanrange/parted_sample_reads", test_parted_sample_reads, srr_setup, srr_teardown }, + { "scanrange/parted_sym_widths_in_place", test_parted_sym_widths_in_place, srr_setup, srr_teardown }, + { "scanrange/parted_in_place_random", test_parted_in_place_random, srr_setup, srr_teardown }, + { "scanrange/parted_factorized_count", test_parted_factorized_count, srr_setup, srr_teardown }, + { "scanrange/parted_sym_narrow_first", test_parted_sym_narrow_first, srr_setup, srr_teardown }, + { "scanrange/parted_flatten_nulls", test_parted_flatten_nulls, srr_setup, srr_teardown }, + { "scanrange/v2_route_shapes", test_v2_route_shapes, srr_setup, srr_pool_teardown }, + { "scanrange/v2_sym_shared_dom", test_v2_sym_shared_dom, srr_setup, srr_pool_teardown }, + { "scanrange/v2_shared_route", test_v2_shared_route, srr_setup, srr_pool_teardown }, + { "scanrange/v2_f64_bits", test_v2_f64_bits, srr_setup, srr_teardown }, + { "scanrange/v2_decode_once", test_v2_decode_once, srr_setup, srr_pool_teardown }, + { "scanrange/v2_sel_bounds", test_v2_sel_bounds, srr_setup, srr_teardown }, + { "scanrange/v2_consumers", test_v2_consumers, srr_setup, srr_teardown }, + { "scanrange/v2_points", test_v2_points, srr_setup, srr_teardown }, + { "scanrange/v2_run_points", test_v2_run_points, srr_setup, srr_teardown }, + { "scanrange/v2_serial_dense", test_v2_serial_dense, srr_setup, srr_teardown }, + { "scanrange/v2_sel_key_types", test_v2_sel_key_types, srr_setup, srr_teardown }, + { "scanrange/v2_radix_decode_once", test_v2_radix_decode_once, sr_rt_setup, srr_pool_teardown }, + { "scanrange/v2_radix_answers", test_v2_radix_answers, sr_rt_setup, srr_pool_teardown }, + { "scanrange/v2_radix_record_order", test_v2_radix_record_order, sr_rt_setup, srr_pool_teardown }, + { "scanrange/v2_radix_compact_staging", test_v2_radix_compact_staging, sr_rt_setup, srr_pool_teardown }, + { "scanrange/v2_parted_segment", test_v2_parted_segment, sr_rt_setup, srr_teardown }, + { "scanrange/idx_info_table", test_idx_info_table, srr_setup, srr_teardown }, + { "scanrange/idx_info_report", test_idx_info_report, srr_setup, srr_teardown }, + { "scanrange/no_materialization", test_no_materialization, srr_setup, srr_teardown }, + { "scanrange/no_materialization_parted", test_no_materialization_parted, srr_setup, srr_teardown }, + { "scanrange/parted_eval_group_keep", test_parted_eval_group_keep, srr_setup, srr_teardown }, + { "scanrange/count_and", test_count_and, srr_setup, srr_teardown }, + { "scanrange/parted_nullable_stats", test_parted_nullable_stats, srr_setup, srr_teardown }, + { "scanrange/parted_expr_null_free", test_parted_expr_null_free, srr_setup, srr_teardown }, + { "scanrange/strlen_str_gen2_routes", test_strlen_str_gen2_routes, sr_rt_setup, sr_rt_teardown }, + { "scanrange/strlen_runtime_sym_gen2", test_strlen_runtime_sym_gen2, sr_rt_setup, sr_rt_teardown }, + { "scanrange/strlen_runtime_sym_bytekey", test_strlen_runtime_sym_bytekey, sr_rt_setup, sr_rt_teardown }, + { "scanrange/parallel_strlen_runtime_sym_gen2", test_parallel_strlen_runtime_sym_gen2, sr_rt_setup, sr_rt_teardown }, + { "scanrange/ragged_gen0_no_decode", test_ragged_gen0_no_decode, srr_setup, srr_teardown }, + { "scanrange/ragged_fill_bounded", test_ragged_fill_bounded, srr_setup, srr_teardown }, + { "scanrange/vec_stat_decide", test_vec_stat_decide, sr_rt_setup, sr_rt_teardown }, + { "scanrange/chain_zone_prune", test_chain_zone_prune, sr_rt_setup, sr_rt_teardown }, + { "scanrange/v2_sel_bounds_split", test_v2_sel_bounds_split, sr_rt_setup, sr_rt_teardown }, + { "scanrange/v2_sel_bounds_boundary", test_v2_sel_bounds_boundary, sr_rt_setup, sr_rt_teardown }, + { "scanrange/v2_split", test_v2_split, sr_rt_setup, sr_rt_teardown }, + { "scanrange/const_beside_parted_group", test_const_beside_parted_group, srr_setup, srr_teardown }, + { "scanrange/cold_fallback_gen0_bare", test_cold_fallback_gen0_bare, sr_rt_setup, sr_cold_teardown }, + { "scanrange/cold_fallback_gen0_dict", test_cold_fallback_gen0_dict, sr_rt_setup, sr_cold_teardown }, + { "scanrange/cold_fallback_gen2_bare", test_cold_fallback_gen2_bare, sr_rt_setup, sr_cold_teardown }, + { "scanrange/cold_fallback_gen2_dict", test_cold_fallback_gen2_dict, sr_rt_setup, sr_cold_teardown }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_sort.c b/test/test_sort.c index a14ac3488..b3b4e6da6 100644 --- a/test/test_sort.c +++ b/test/test_sort.c @@ -40,10 +40,12 @@ #include #include "mem/heap.h" #include "ops/ops.h" +#include "ops/internal.h" #include "table/sym.h" #include "lang/internal.h" #include #include +#include /* ─── Helpers ────────────────────────────────────────────────────── */ @@ -1511,9 +1513,475 @@ static test_result_t test_sort_sym_w8_gather(void) { PASS(); } +/* Both sides of the comparison budget must retain the typed SYM-first + * route. Signed secondary values and a late secondary inversion exercise + * its raw-i64 compare and the borrowed-rank path after many symbol runs. */ +static test_result_t test_sorted_sym_i64_probe(void) { + ray_heap_init(); ray_sym_init(); + int64_t* ids = calloc(2048, sizeof(*ids)); + TEST_ASSERT_NOT_NULL(ids); + for (int i = 2047; i >= 0; i--) { + char name[32]; int len = snprintf(name, sizeof(name), "typed-%04d", i); + ids[i] = ray_sym_intern(name, (size_t)len); + } + int64_t sn = ray_sym_intern("s", 1), tn = ray_sym_intern("t", 1); + int64_t rn = ray_sym_intern("row", 3); + int64_t key_ids[] = {sn, tn}; + ray_t* keys = ray_vec_from_raw(RAY_SYM, key_ids, 2); + const int8_t types[] = {RAY_I64, RAY_TIMESTAMP}; + for (int type = 0; type < 2; type++) { + for (int busy = 0; busy < 2; busy++) { + int64_t runs = busy ? 2048 : 100, run_rows = busy ? 100 : 2000; + int64_t n = runs * run_rows; + for (int inversion = 0; inversion < 2; inversion++) { + ray_t* sym = ray_vec_new(RAY_SYM, n); + ray_t* time = ray_vec_new(types[type], n); + ray_t* row = ray_vec_new(RAY_I64, n); + sym->len = time->len = row->len = n; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(sym))[i] = ids[i / run_rows]; + ((int64_t*)ray_data(time))[i] = (i % run_rows - run_rows / 2) * 1000000; + ((int64_t*)ray_data(row))[i] = i; + } + if (inversion) ((int64_t*)ray_data(time))[n - 1] = ((int64_t*)ray_data(time))[n - 2] - 1; + ray_t* table = ray_table_new(3); + table = ray_table_add_col(table, sn, sym); + table = ray_table_add_col(table, tn, time); + table = ray_table_add_col(table, rn, row); + ray_t* result = ray_xasc_fn(table, keys); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), n); + ray_t* os = ray_table_get_col(result, sn); + ray_t* ot = ray_table_get_col(result, tn); + ray_t* orow = ray_table_get_col(result, rn); + for (int64_t i = 0; i < n; i++) { + int64_t r = inversion && i >= n - 2 ? (i == n - 2 ? n - 1 : n - 2) : i; + TEST_ASSERT_EQ_I(((int64_t*)ray_data(orow))[i], r); + TEST_ASSERT_EQ_I(ray_read_sym(ray_data(os), i, os->type, os->attrs), ids[r / run_rows]); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ot))[i], ((int64_t*)ray_data(time))[r]); + } + ray_release(result); ray_release(table); + ray_release(sym); ray_release(time); ray_release(row); + } + } + } + free(ids); ray_release(keys); + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* A large late-used constant/low-transition key must finish the probe, + * rather than resolving an entire intern prefix merely for passing 64K. */ +static test_result_t test_sorted_large_constant_symbols(void) { + ray_heap_init(); ray_sym_init(); + for (int i = 0; i < 70000; i++) { + char name[40]; int len = snprintf(name, sizeof(name), "constant-padding-%d", i); + ray_sym_intern(name, (size_t)len); + } + int64_t z = ray_sym_intern("constant-z", 10); + int64_t a = ray_sym_intern("constant-a", 10); + TEST_ASSERT_TRUE(a > 65536); + int64_t sn = ray_sym_intern("s", 1), tn = ray_sym_intern("t", 1); + int64_t rn = ray_sym_intern("row", 3); + int64_t key_ids[] = {tn, sn}; + ray_t* one_key = make_sym_atom(sn); + ray_t* two_keys = ray_vec_from_raw(RAY_SYM, key_ids, 2); + const int64_t n = RAY_PARALLEL_THRESHOLD + 1; + for (int desc = 0; desc < 2; desc++) { + for (int kind = 0; kind < 3; kind++) { + ray_t* sym = ray_vec_new(RAY_SYM, n); + ray_t* time = ray_vec_new(RAY_I64, n); + ray_t* row = ray_vec_new(RAY_I64, n); + sym->len = time->len = row->len = n; + for (int64_t i = 0; i < n; i++) { + bool first = kind == 2 ? i % 2 == 0 : i < n / 2; + ((int64_t*)ray_data(sym))[i] = kind == 0 ? a : (first ? (desc ? z : a) : (desc ? a : z)); + ((int64_t*)ray_data(time))[i] = desc ? n - 1 - i : i; + ((int64_t*)ray_data(row))[i] = i; + } + ray_t* table = ray_table_new(3); + table = ray_table_add_col(table, sn, sym); + table = ray_table_add_col(table, tn, time); + table = ray_table_add_col(table, rn, row); + ray_t* keys = kind == 2 ? two_keys : one_key; + ray_t* result = desc ? ray_xdesc_fn(table, keys) : ray_xasc_fn(table, keys); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + if (kind != 2) TEST_ASSERT_TRUE(result == table); + TEST_ASSERT_EQ_I(ray_table_nrows(result), n); + ray_t* result_rows = ray_table_get_col(result, rn); + ray_t* result_syms = ray_table_get_col(result, sn); + for (int64_t i = 0; i < n; i++) { + TEST_ASSERT_EQ_I(((int64_t*)ray_data(result_rows))[i], i); + TEST_ASSERT_EQ_I(ray_read_sym(ray_data(result_syms), i, result_syms->type, result_syms->attrs), ((int64_t*)ray_data(sym))[i]); + } + ray_release(result); ray_release(table); + ray_release(sym); ray_release(time); ray_release(row); + } + } + ray_release(one_key); ray_release(two_keys); + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* The query/partition helper is also callable with an unbounded key + * count. All keys tie, forcing it to visit the entire heap-backed list. */ +static test_result_t test_sorted_many_repeated_keys(void) { + ray_heap_init(); ray_sym_init(); + const int64_t n_keys = 300000; + int64_t id = ray_sym_intern("repeated-key", 12); + int64_t values[] = {id, id}; + ray_t* sym = ray_vec_from_raw(RAY_SYM, values, 2); + ray_t** cols = calloc((size_t)n_keys, sizeof(*cols)); + TEST_ASSERT_NOT_NULL(cols); + for (int64_t k = 0; k < n_keys; k++) cols[k] = sym; + TEST_ASSERT_TRUE(ray_key_cols_sorted(cols, n_keys, 0, 2)); + TEST_ASSERT_TRUE(ray_key_cols_sorted(cols, n_keys, 1, 2)); + free(cols); ray_release(sym); + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* A late inversion must lend prepared ranks to the real sort without + * freeing them too early; early/small cases avoid precheck rank setup. + * Row identities independently verify stability of the repeated keys. */ +static test_result_t test_unsorted_symbol_rank_reuse(void) { + ray_heap_init(); ray_sym_init(); + int64_t z = ray_sym_intern("reuse-z", 7); + int64_t a = ray_sym_intern("reuse-a", 7); + int64_t ts_name = ray_sym_intern("reuse-time", 10); + int64_t sym_name = ray_sym_intern("reuse-sym", 9); + int64_t row_name = ray_sym_intern("reuse-row", 9); + int64_t key_ids[] = {ts_name, sym_name}; + ray_t* keys = ray_vec_from_raw(RAY_SYM, key_ids, 2); + for (int desc = 0; desc < 2; desc++) { + for (int kind = 0; kind < 3; kind++) { + int64_t n = kind == 0 ? 8 : 200000; + int64_t block = kind == 0 ? n : 100; + int64_t inversion = (kind == 2 ? n - block : 0) + block / 2 - 1; + ray_t* sym = ray_vec_new(RAY_SYM, n); + ray_t* time = ray_vec_new(RAY_I64, n); + ray_t* row = ray_vec_new(RAY_I64, n); + sym->len = time->len = row->len = n; + for (int64_t i = 0; i < n; i++) { + bool first = i % block < block / 2; + ((int64_t*)ray_data(sym))[i] = first ? (desc ? z : a) : (desc ? a : z); + ((int64_t*)ray_data(time))[i] = (desc ? n - 1 - i : i) / block; + ((int64_t*)ray_data(row))[i] = i; + } + int64_t* sv = ray_data(sym); + int64_t swap = sv[inversion]; + sv[inversion] = sv[inversion + 1]; sv[inversion + 1] = swap; + ray_t* table = ray_table_new(3); + table = ray_table_add_col(table, ts_name, time); + table = ray_table_add_col(table, sym_name, sym); + table = ray_table_add_col(table, row_name, row); + ray_t* result = desc ? ray_xdesc_fn(table, keys) : ray_xasc_fn(table, keys); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), n); + ray_t* out_sym = ray_table_get_col(result, sym_name); + ray_t* out_row = ray_table_get_col(result, row_name); + for (int64_t i = 0; i < n; i++) { + bool first = i % block < block / 2; + int64_t expected_sym = first ? (desc ? z : a) : (desc ? a : z); + int64_t expected_row = i == inversion ? i + 1 : (i == inversion + 1 ? i - 1 : i); + TEST_ASSERT_EQ_I(ray_read_sym(ray_data(out_sym), i, out_sym->type, out_sym->attrs), expected_sym); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(out_row))[i], expected_row); + } + ray_release(result); ray_release(table); + ray_release(sym); ray_release(time); ray_release(row); + } + } + ray_release(keys); + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* The optional LUT must not turn a sparse but sorted column into a + * declined shortcut. Intern padding BEFORE the used names. */ +static test_result_t test_sorted_symbol_sparse_fallback(void) { + ray_heap_init(); + ray_sym_init(); + for (int i = 0; i < 70000; i++) { + char name[40]; + int len = snprintf(name, sizeof(name), "unused-rank-padding-%d", i); + ray_sym_intern(name, (size_t)len); + } + int64_t z = ray_sym_intern("late-z", 6); + int64_t a = ray_sym_intern("late-a", 6); + TEST_ASSERT_TRUE(a > 65536 && z > 65536); + int64_t values[] = {a, a, a, a, z, z, z, z}; + ray_t* sym = ray_vec_from_raw(RAY_SYM, values, 8); + ray_t* hdr = NULL; + TEST_ASSERT_TRUE(build_enum_rank(sym, 8, &hdr) == NULL); + TEST_ASSERT_TRUE(hdr == NULL); /* density guard, not allocation failure */ + TEST_ASSERT_TRUE(ray_key_cols_sorted(&sym, 1, 0, 8)); + TEST_ASSERT_FALSE(ray_key_cols_sorted(&sym, 1, 1, 8)); + int64_t name = ray_sym_intern("sparse-key", 10); + ray_t* keys = make_sym_atom(name); + ray_t* table = ray_table_new(1); + table = ray_table_add_col(table, name, sym); + ray_t* result = ray_xasc_fn(table, keys); + TEST_ASSERT_TRUE(result == table); /* shortcut retained, not a full sort */ + ray_release(result); + int64_t* data = ray_data(sym); + for (int i = 0; i < 8; i++) data[i] = i < 4 ? z : a; + TEST_ASSERT_TRUE(ray_key_cols_sorted(&sym, 1, 1, 8)); + result = ray_xdesc_fn(table, keys); + TEST_ASSERT_TRUE(result == table); + ray_release(result); + data[7] = z; + TEST_ASSERT_FALSE(ray_key_cols_sorted(&sym, 1, 1, 8)); + ray_release(table); + ray_release(keys); + ray_release(sym); + + /* Within the LUT budget, repeated constant segments still need only + * the equal-ID scan; ray_key_cols_sorted must not build dense ranks. */ + ray_t* constant = ray_vec_new(RAY_SYM, 10000); + constant->len = 10000; + data = ray_data(constant); + for (int i = 0; i < 10000; i++) data[i] = a; + for (int i = 0; i < 20; i++) + TEST_ASSERT_TRUE(ray_key_cols_sorted(&constant, 1, i % 2, 10000)); + ray_release(constant); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* Lexical rank checks must not compare raw intern order. Exercise the + * generic and specialized key orders, both directions, and a late inversion + * beyond a dispatch boundary. The runner's pool supplies parallel coverage. */ +static test_result_t test_sorted_symbol_rank_check(void) { + ray_heap_init(); + ray_sym_init(); + int64_t z = ray_sym_intern("rank-z", 6); + int64_t a = ray_sym_intern("rank-a", 6); + TEST_ASSERT_TRUE(z < a); + const int64_t n = 200000; + ray_t* sym = ray_vec_new(RAY_SYM, n); + ray_t* time = ray_vec_new(RAY_I64, n); + sym->len = time->len = n; + int64_t* sv = ray_data(sym); + int64_t* tv = ray_data(time); + ray_t* cols[] = {time, sym}; + for (int direction = 0; direction < 2; direction++) { + for (int64_t i = 0; i < n; i++) { + int64_t j = direction ? n - 1 - i : i; + tv[i] = j / 2; + sv[i] = j % 2 ? z : a; + } + TEST_ASSERT_TRUE(ray_key_cols_sorted(cols, 2, direction, n)); + TEST_ASSERT_FALSE(ray_key_cols_sorted(cols, 2, !direction, n)); + /* Swap a same-time symbol pair late in the column. */ + int64_t v = sv[n - 2]; sv[n - 2] = sv[n - 1]; sv[n - 1] = v; + TEST_ASSERT_FALSE(ray_key_cols_sorted(cols, 2, direction, n)); + cols[0] = sym; cols[1] = time; + for (int64_t i = 0; i < n; i++) { + int64_t j = direction ? n - 1 - i : i; + sv[i] = j < n / 2 ? a : z; + tv[i] = j % (n / 2); + } + TEST_ASSERT_TRUE(ray_key_cols_sorted(cols, 2, direction, n)); + tv[n - 1] = direction ? n : -1; + TEST_ASSERT_FALSE(ray_key_cols_sorted(cols, 2, direction, n)); + cols[0] = time; cols[1] = sym; + } + /* Symbol nulls must still decline the shortcut, even for one row. */ + int64_t null_id = 0; + ray_t* nullable = ray_vec_from_raw(RAY_SYM, &null_id, 1); + TEST_ASSERT_FALSE(ray_key_cols_sorted(&nullable, 1, 0, 1)); + ray_release(nullable); + ray_release(time); + ray_release(sym); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + +/* A valid TIME slice makes the incorrect 64-bit read reproducible without + * relying on allocation padding: packed adjacent backing pairs look ordered, + * while the two logical 32-bit TIME cells are descending. Exercise both users + * of sorted_check_fn, and aligned/non-8-byte-aligned zero-copy views. */ +static test_result_t test_time_key_width(void) { + ray_runtime_t* rt = ray_runtime_create(0, NULL); + TEST_ASSERT_NOT_NULL(rt); + for (int negative = 0; negative < 2; negative++) { + for (int64_t offset = 0; offset < 2; offset++) { + int32_t raw[5] = {42, 42, 42, 42, 42}; + raw[offset] = negative ? -1000 : 2000; + raw[offset + 1] = negative ? -2000 : 1000; + raw[offset + 2] = negative ? -1000 : 3000; + raw[offset + 3] = negative ? -1000 : 2000; + ray_t* parent = ray_vec_from_raw(RAY_TIME, raw, offset + 4); + TEST_ASSERT_TRUE(parent && !RAY_IS_ERR(parent)); + ray_t* times = ray_vec_slice(parent, offset, 2); + TEST_ASSERT_TRUE(times && !RAY_IS_ERR(times)); + TEST_ASSERT_TRUE((times->attrs & RAY_ATTR_SLICE) != 0); + ray_t* syms = ray_eval_str("[a a]"); + TEST_ASSERT_TRUE(syms && !RAY_IS_ERR(syms) && syms->type == RAY_SYM && syms->len == 2); + ray_t* cols[] = {syms, times}; + TEST_ASSERT_FALSE(ray_key_cols_sorted(cols, 2, 0, 2)); + TEST_ASSERT_TRUE(ray_key_cols_sorted(cols, 2, 1, 2)); + ray_t* table = ray_table_new(2); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("s", 1), syms); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("t", 1), times); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + ray_t* keys = ray_eval_str("[s t]"); + TEST_ASSERT_TRUE(keys && !RAY_IS_ERR(keys)); + ray_t* out = ray_xasc_fn(table, keys); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out)); + ray_t* got = ray_table_col(out, ray_sym_intern("t", 1)); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && got->type == RAY_TIME && got->len == 2); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(got))[0], raw[offset + 1]); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(got))[1], raw[offset]); + ray_t* sorted_cols[] = {syms, got}; + TEST_ASSERT_TRUE(ray_key_cols_sorted(sorted_cols, 2, 0, 2)); + TEST_ASSERT_FALSE(ray_key_cols_sorted(sorted_cols, 2, 1, 2)); + TEST_ASSERT_TRUE(memcmp(ray_data(parent), raw, (size_t)(offset + 4) * sizeof(int32_t)) == 0); + ray_release(out); ray_release(keys); ray_release(table); + ray_release(syms); ray_release(times); ray_release(parent); + } + } + ray_runtime_destroy(rt); + PASS(); +} + +/* The sole logical inversion straddles the usual 8192-row morsel edge. + * Every adjacent pair in the wider backing view still looks increasing. + * The test also runs correctly without background workers; eligibility does + * not claim that every configured worker physically participated. */ +static test_result_t test_time_key_width_parallel(void) { + ray_runtime_t* rt = ray_runtime_create(0, NULL); + TEST_ASSERT_NOT_NULL(rt); + const int64_t n = RAY_PARALLEL_THRESHOLD + 1; + const int64_t edge = (int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS; + TEST_ASSERT_TRUE(edge > 0 && edge < n); + int32_t* raw = malloc((size_t)(2 * n) * sizeof(int32_t)); + TEST_ASSERT_NOT_NULL(raw); + for (int64_t i = 0; i < 2 * n; i++) raw[i] = (int32_t)i; + raw[edge - 1] = (int32_t)edge; raw[edge] = (int32_t)(edge - 1); + ray_t* parent = ray_vec_from_raw(RAY_TIME, raw, 2 * n); + free(raw); + TEST_ASSERT_TRUE(parent && !RAY_IS_ERR(parent)); + ray_t* times = ray_vec_slice(parent, 0, n); + TEST_ASSERT_TRUE(times && !RAY_IS_ERR(times) && (times->attrs & RAY_ATTR_SLICE)); + char expr[64]; + snprintf(expr, sizeof(expr), "(take [a] %lld)", (long long)n); + ray_t* syms = ray_eval_str(expr); + TEST_ASSERT_TRUE(syms && !RAY_IS_ERR(syms) && syms->type == RAY_SYM && syms->len == n); + ray_t* cols[] = {syms, times}; + TEST_ASSERT_FALSE(ray_key_cols_sorted(cols, 2, 0, n)); + ray_t* table = ray_table_new(2); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("s", 1), syms); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("t", 1), times); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + ray_t* keys = ray_eval_str("[s t]"); + TEST_ASSERT_TRUE(keys && !RAY_IS_ERR(keys)); + ray_t* out = ray_xasc_fn(table, keys); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out)); + ray_t* got = ray_table_col(out, ray_sym_intern("t", 1)); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && got->type == RAY_TIME && got->len == n); + const int32_t* data = ray_data(got); + for (int64_t i = 0; i < n; i++) TEST_ASSERT_EQ_I(data[i], i); + ray_t* sorted_cols[] = {syms, got}; + TEST_ASSERT_TRUE(ray_key_cols_sorted(sorted_cols, 2, 0, n)); + TEST_ASSERT_FALSE(ray_key_cols_sorted(sorted_cols, 2, 1, n)); + const int32_t* input = ray_data(parent); + for (int64_t i = 0; i < 2 * n; i++) { + int32_t expected = i == edge - 1 ? (int32_t)edge : + i == edge ? (int32_t)(edge - 1) : (int32_t)i; + TEST_ASSERT_EQ_I(input[i], expected); + } + ray_release(out); ray_release(keys); ray_release(table); + ray_release(syms); ray_release(times); ray_release(parent); + ray_runtime_destroy(rt); + PASS(); +} + +/* More than one morsel of unequal symbol boundaries spends the table + * preparation budget. A late within-run TIME inversion must still reach + * the same width-correct worker scan after ranks are prepared. */ +static test_result_t test_time_key_width_rank_budget(void) { + ray_runtime_t* rt = ray_runtime_create(0, NULL); + TEST_ASSERT_NOT_NULL(rt); + const int64_t n = RAY_PARALLEL_THRESHOLD + 1; + ray_t* syms = ray_vec_new(RAY_SYM, n); + ray_t* times = ray_vec_new(RAY_TIME, n); + ray_t* rows = ray_vec_new(RAY_I64, n); + TEST_ASSERT_TRUE(syms && !RAY_IS_ERR(syms)); + TEST_ASSERT_TRUE(times && !RAY_IS_ERR(times)); + TEST_ASSERT_TRUE(rows && !RAY_IS_ERR(rows)); + syms->len = times->len = rows->len = n; + int64_t* sd = ray_data(syms); + int32_t* td = ray_data(times); + int64_t* rd = ray_data(rows); + int64_t sid = 0; + for (int64_t i = 0; i < n; i++) { + if ((i % 32) == 0) { + char name[32]; + int len = snprintf(name, sizeof(name), "time-width-%04lld", (long long)(i / 32)); + sid = ray_sym_intern(name, (size_t)len); + } + sd[i] = sid; td[i] = (int32_t)((i % 32 - 16) * 1000); rd[i] = i; + } + ray_t* cols[] = {syms, times}; + TEST_ASSERT_TRUE(ray_key_cols_sorted(cols, 2, 0, n)); + int32_t tmp = td[n - 3]; td[n - 3] = td[n - 2]; td[n - 2] = tmp; + TEST_ASSERT_FALSE(ray_key_cols_sorted(cols, 2, 0, n)); + ray_t* table = ray_table_new(3); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("s", 1), syms); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("t", 1), times); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + table = ray_table_add_col(table, ray_sym_intern("r", 1), rows); + TEST_ASSERT_TRUE(table && !RAY_IS_ERR(table)); + ray_t* keys = ray_eval_str("[s t]"); + TEST_ASSERT_TRUE(keys && !RAY_IS_ERR(keys)); + ray_t* out = ray_xasc_fn(table, keys); + TEST_ASSERT_TRUE(out && !RAY_IS_ERR(out)); + ray_t* os = ray_table_col(out, ray_sym_intern("s", 1)); + ray_t* ot = ray_table_col(out, ray_sym_intern("t", 1)); + ray_t* rr = ray_table_col(out, ray_sym_intern("r", 1)); + TEST_ASSERT_TRUE(os && !RAY_IS_ERR(os) && os->len == n); + TEST_ASSERT_TRUE(ot && !RAY_IS_ERR(ot) && ot->type == RAY_TIME && ot->len == n); + TEST_ASSERT_TRUE(rr && !RAY_IS_ERR(rr) && rr->type == RAY_I64 && rr->len == n); + for (int64_t i = 0; i < n; i++) { + int64_t id = i == n - 3 ? n - 2 : i == n - 2 ? n - 3 : i; + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ot))[i], (i % 32 - 16) * 1000); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(rr))[i], id); + TEST_ASSERT_EQ_I(ray_read_sym(ray_data(os), i, RAY_SYM, os->attrs), sd[i]); + TEST_ASSERT_EQ_I(td[i], (id % 32 - 16) * 1000); + TEST_ASSERT_EQ_I(rd[i], i); + } + ray_t* sorted[] = {os, ot}; + TEST_ASSERT_TRUE(ray_key_cols_sorted(sorted, 2, 0, n)); + ray_release(out); ray_release(keys); ray_release(table); + ray_release(syms); ray_release(times); ray_release(rows); + ray_runtime_destroy(rt); + PASS(); +} + /* ─── Entry table ────────────────────────────────────────────────── */ const test_entry_t sort_entries[] = { + { "sort/time_key_width_rank_budget", test_time_key_width_rank_budget, NULL, NULL }, + { "sort/time_key_width_parallel", test_time_key_width_parallel, NULL, NULL }, + { "sort/time_key_width", test_time_key_width, NULL, NULL }, + { "sort/sorted_sym_i64_probe", test_sorted_sym_i64_probe, NULL, NULL }, + { "sort/sorted_large_constant_symbols", test_sorted_large_constant_symbols, NULL, NULL }, + { "sort/sorted_many_repeated_keys", test_sorted_many_repeated_keys, NULL, NULL }, + { "sort/unsorted_symbol_rank_reuse", test_unsorted_symbol_rank_reuse, NULL, NULL }, + { "sort/sorted_symbol_sparse_fallback", test_sorted_symbol_sparse_fallback, NULL, NULL }, + { "sort/sorted_symbol_rank_check", test_sorted_symbol_rank_check, NULL, NULL }, /* xrank tests */ { "sort/xrank_basic", test_xrank_basic, NULL, NULL }, { "sort/xrank_single_group", test_xrank_single_group, NULL, NULL }, diff --git a/test/test_splay.c b/test/test_splay.c index 6c12a2a92..f48a68d06 100644 --- a/test/test_splay.c +++ b/test/test_splay.c @@ -82,10 +82,10 @@ static void rm_rf(const char* path) { * Chunks of 20k rows with >4k new strings each take the parallel batch. */ static test_result_t test_csv_splayed_symfile_order(void) { TEST_ASSERT_NOT_NULL(ray_pool_get()); - const char* dir = TMP_SPLAY_BASE "/csvorder"; - const char* csv = TMP_SPLAY_BASE "/csvorder.csv"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/csvorder"); + const char* csv = ray_test_tmp(TMP_SPLAY_BASE "/csvorder.csv"); rm_rf(dir); - mkdir(TMP_SPLAY_BASE, 0755); + mkdir(ray_test_tmp(TMP_SPLAY_BASE), 0755); enum { NROWS = 60000, CHUNK = 20000, NA = 13000, NB = 9000 }; FILE* f = fopen(csv, "wb"); @@ -164,10 +164,10 @@ static test_result_t test_csv_splayed_symfile_order(void) { * not treat it so, and merged two rows, losing a value.) */ static test_result_t test_csv_splayed_quote_mode_per_file(void) { TEST_ASSERT_NOT_NULL(ray_pool_get()); - const char* dir = TMP_SPLAY_BASE "/csvquote"; - const char* csv = TMP_SPLAY_BASE "/csvquote.csv"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/csvquote"); + const char* csv = ray_test_tmp(TMP_SPLAY_BASE "/csvquote.csv"); rm_rf(dir); - mkdir(TMP_SPLAY_BASE, 0755); + mkdir(ray_test_tmp(TMP_SPLAY_BASE), 0755); enum { NROWS = 60000, CHUNK = 20000, LONE = 45007 }; FILE* f = fopen(csv, "wb"); @@ -233,7 +233,7 @@ static test_result_t test_save_null_dir(void) { * 2. ray_splay_save: NULL tbl → RAY_ERR_TYPE * ========================================================================= */ static test_result_t test_save_null_tbl(void) { - ray_err_t err = ray_splay_save(NULL, TMP_SPLAY_BASE "/t", NULL); + ray_err_t err = ray_splay_save(NULL, ray_test_tmp(TMP_SPLAY_BASE "/t"), NULL); TEST_ASSERT_EQ_I(err, RAY_ERR_TYPE); PASS(); } @@ -273,23 +273,23 @@ static test_result_t assert_save_rejects_unsafe_col_name(const char* dir, static test_result_t test_save_rejects_dot_col_name(void) { return assert_save_rejects_unsafe_col_name( - TMP_SPLAY_BASE "/dot_col", ".hidden", 7); + ray_test_tmp(TMP_SPLAY_BASE "/dot_col"), ".hidden", 7); } static test_result_t test_save_rejects_slash_col_name(void) { return assert_save_rejects_unsafe_col_name( - TMP_SPLAY_BASE "/slash_col", "a/b", 3); + ray_test_tmp(TMP_SPLAY_BASE "/slash_col"), "a/b", 3); } static test_result_t test_save_rejects_backslash_col_name(void) { return assert_save_rejects_unsafe_col_name( - TMP_SPLAY_BASE "/backslash_col", "a\\b", 3); + ray_test_tmp(TMP_SPLAY_BASE "/backslash_col"), "a\\b", 3); } static test_result_t test_save_rejects_nul_col_name(void) { static const char bad_name[] = { 'a', '\0', 'b' }; return assert_save_rejects_unsafe_col_name( - TMP_SPLAY_BASE "/nul_col", bad_name, sizeof(bad_name)); + ray_test_tmp(TMP_SPLAY_BASE "/nul_col"), bad_name, sizeof(bad_name)); } /* ========================================================================= @@ -317,7 +317,7 @@ static test_result_t test_load_null_dir(void) { * ========================================================================= */ static test_result_t test_load_missing_schema(void) { /* Directory exists but contains no .d file */ - const char* dir = TMP_SPLAY_BASE "/no_schema"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/no_schema"); rm_rf(dir); (void)ray_test_mkdir_p(dir); @@ -336,7 +336,7 @@ static test_result_t test_load_missing_schema(void) { * col-load-fail branch (lines 195-199). * ========================================================================= */ static test_result_t test_load_missing_col_file(void) { - const char* dir = TMP_SPLAY_BASE "/miss_col"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/miss_col"); rm_rf(dir); int64_t id_a = ray_sym_intern("aa", 2); @@ -378,7 +378,7 @@ static test_result_t test_load_missing_col_file(void) { * This hits lines 46-54 of validate_sym_columns with nc > 0 and no SYM. * ========================================================================= */ static test_result_t test_validate_sym_no_sym_cols(void) { - const char* dir = TMP_SPLAY_BASE "/nosym_ok"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/nosym_ok"); rm_rf(dir); int64_t id_x = ray_sym_intern("xval", 4); @@ -391,7 +391,7 @@ static test_result_t test_validate_sym_no_sym_cols(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); /* Save with sym_path so the sym file is written */ - const char* sym_path = TMP_SPLAY_BASE "/nosym_ok_sym"; + const char* sym_path = ray_test_tmp(TMP_SPLAY_BASE "/nosym_ok_sym"); ray_err_t err = ray_splay_save(tbl, dir, sym_path); TEST_ASSERT_EQ_I(err, RAY_OK); @@ -438,8 +438,8 @@ static test_result_t test_validate_sym_no_sym_cols(void) { * coverage from our suite. * ========================================================================= */ static test_result_t test_validate_sym_corrupt(void) { - const char* dir = TMP_SPLAY_BASE "/sym_corrupt"; - const char* sym_path = TMP_SPLAY_BASE "/sym_corrupt_sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/sym_corrupt"); + const char* sym_path = ray_test_tmp(TMP_SPLAY_BASE "/sym_corrupt_sym"); rm_rf(dir); unlink(sym_path); @@ -510,7 +510,7 @@ static test_result_t test_validate_sym_corrupt(void) { * is reserved for actual SYM columns without a domain). * ========================================================================= */ static test_result_t test_load_bad_sym_path(void) { - const char* dir = TMP_SPLAY_BASE "/bad_sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/bad_sym"); rm_rf(dir); int64_t id_k = ray_sym_intern("k1", 2); @@ -572,7 +572,7 @@ static test_result_t test_load_bad_sym_path(void) { * branch and the "nyi fallback" path for types that don't support mmap. * ========================================================================= */ static test_result_t test_read_splayed_roundtrip(void) { - const char* dir = TMP_SPLAY_BASE "/mmap_rt"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/mmap_rt"); rm_rf(dir); int64_t id_p = ray_sym_intern("price", 5); @@ -618,7 +618,7 @@ static test_result_t test_read_splayed_roundtrip(void) { * never reach the sym-save branch. * ========================================================================= */ static test_result_t test_save_sym_error(void) { - const char* dir = TMP_SPLAY_BASE "/sym_err_save"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/sym_err_save"); rm_rf(dir); int64_t id_v = ray_sym_intern("v", 1); @@ -655,7 +655,7 @@ static test_result_t test_save_sym_error(void) { * single I64 value pointing at a sym whose string begins with '.'. * ========================================================================= */ static test_result_t test_load_corrupt_col_name_in_schema(void) { - const char* dir = TMP_SPLAY_BASE "/corrupt_name"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/corrupt_name"); rm_rf(dir); int64_t id_ok = ray_sym_intern("okname", 6); @@ -731,7 +731,7 @@ static test_result_t test_load_dir_path_too_long(void) { * path-length check before attempting to open the (nonexistent) file. * ========================================================================= */ static test_result_t test_load_col_path_too_long(void) { - const char* dir = "/tmp/rft_ln"; + const char* dir = ray_test_tmp("/tmp/rft_ln"); rm_rf(dir); /* Build a column name that is 1017 chars: dir (11) + "/" (1) + name (1017) @@ -788,7 +788,7 @@ static test_result_t test_load_col_path_too_long(void) { * with tbl having nc=0, schema_ncols=0. Hits lines 46,49,53,54. * ========================================================================= */ static test_result_t test_validate_sym_zero_col_table(void) { - const char* dir = TMP_SPLAY_BASE "/zero_col"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/zero_col"); rm_rf(dir); /* Build a zero-column table */ @@ -825,8 +825,8 @@ static test_result_t test_validate_sym_zero_col_table(void) { * reach the bulk symfile flush. * ========================================================================= */ static test_result_t test_save_bulk_with_sym_path(void) { - const char* dir = TMP_SPLAY_BASE "/bulk_sym"; - const char* sym_path = TMP_SPLAY_BASE "/bulk_sym.sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/bulk_sym"); + const char* sym_path = ray_test_tmp(TMP_SPLAY_BASE "/bulk_sym.sym"); rm_rf(dir); unlink(sym_path); @@ -863,8 +863,8 @@ static test_result_t test_save_bulk_with_sym_path(void) { } static test_result_t test_save_staged_bulk_defers_sym_flush(void) { - const char* dir = TMP_SPLAY_BASE "/staged_bulk_sym"; - const char* sym_path = TMP_SPLAY_BASE "/staged_bulk_sym.sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/staged_bulk_sym"); + const char* sym_path = ray_test_tmp(TMP_SPLAY_BASE "/staged_bulk_sym.sym"); rm_rf(dir); unlink(sym_path); @@ -918,7 +918,7 @@ static test_result_t test_save_dir_path_too_long(void) { #endif /* Construct the nested path in a buffer */ char long_dir[2048]; - const char* base = "/tmp/rft_deep_save"; /* 18 chars */ + const char* base = ray_test_tmp("/tmp/rft_deep_save"); /* 18 chars */ const char* comp = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; /* 50 chars */ int nlevels = 20; @@ -959,7 +959,7 @@ static test_result_t test_save_dir_path_too_long(void) { ray_release(col); ray_release(tbl); /* Cleanup entire nested tree from the base */ - (void)ray_test_rm_rf("/tmp/rft_deep_save"); + (void)ray_test_rm_rf(ray_test_tmp("/tmp/rft_deep_save")); PASS(); } @@ -971,7 +971,7 @@ static test_result_t test_save_dir_path_too_long(void) { * The column must pass the name-safety check (no /, \, ., not empty). * ========================================================================= */ static test_result_t test_save_col_path_too_long(void) { - const char* dir = "/tmp/rft_sv"; + const char* dir = ray_test_tmp("/tmp/rft_sv"); rm_rf(dir); /* dir = 11 chars; "/" = 1 char; need name_len >= 1012 to make total >= 1024 */ @@ -1011,7 +1011,7 @@ static test_result_t test_save_col_path_too_long(void) { * Use setenv("RAY_CSV_TRACE","1",1) before the call and unsetenv after. * ========================================================================= */ static test_result_t test_trace_valid_dir(void) { - const char* dir = TMP_SPLAY_BASE "/trace_valid"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/trace_valid"); rm_rf(dir); int64_t id_t = ray_sym_intern("tval", 4); @@ -1044,7 +1044,7 @@ static test_result_t test_trace_valid_dir(void) { * fprintf (schema load failed branch). * ========================================================================= */ static test_result_t test_trace_missing_schema(void) { - const char* dir = TMP_SPLAY_BASE "/trace_noschema"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/trace_noschema"); rm_rf(dir); /* Create dir without .d file */ (void)ray_test_mkdir_p(dir); @@ -1066,7 +1066,7 @@ static test_result_t test_trace_missing_schema(void) { * → hits lines 221-223 fprintf (col load failed branch). * ========================================================================= */ static test_result_t test_trace_missing_col(void) { - const char* dir = TMP_SPLAY_BASE "/trace_misscol"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/trace_misscol"); rm_rf(dir); int64_t id_a = ray_sym_intern("ta", 2); @@ -1109,7 +1109,7 @@ static test_result_t test_trace_missing_col(void) { * an empty sym table and no symfile. * ========================================================================= */ static test_result_t test_trace_fresh_load(void) { - const char* dir = TMP_SPLAY_BASE "/trace_missym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/trace_missym"); rm_rf(dir); int64_t id_c = ray_sym_intern("tc", 2); @@ -1151,7 +1151,7 @@ static test_result_t test_save_schema_write_fails(void) { * read-only attribute is ignored for directories. */ SKIP("read-only directories are not enforced on Windows"); #endif - const char* dir = TMP_SPLAY_BASE "/no_write_schema"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/no_write_schema"); rm_rf(dir); (void)ray_test_mkdir_p(dir); @@ -1219,8 +1219,8 @@ static test_result_t test_save_schema_write_fails(void) { * remaining caller of the heap STR deep-copy path. * ========================================================================= */ static test_result_t test_load_str_pool_heap(void) { - const char* dir_pool = TMP_SPLAY_BASE "/str_pool"; - const char* dir_inl = TMP_SPLAY_BASE "/str_inline"; + const char* dir_pool = ray_test_tmp(TMP_SPLAY_BASE "/str_pool"); + const char* dir_inl = ray_test_tmp(TMP_SPLAY_BASE "/str_inline"); rm_rf(dir_pool); rm_rf(dir_inl); @@ -1296,7 +1296,7 @@ static test_result_t test_load_str_pool_heap(void) { * gate for the STR-schema change. * ========================================================================= */ static test_result_t test_selfdescribing_schema_fresh_process(void) { - const char* dir = TMP_SPLAY_BASE "/selfdesc"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/selfdesc"); rm_rf(dir); int64_t id_a = ray_sym_intern("alpha", 5); @@ -1346,8 +1346,8 @@ static test_result_t test_selfdescribing_schema_fresh_process(void) { * sym_path is supplied; (c) .d is the commit marker — written last. * ========================================================================= */ static test_result_t test_save_sweeps_stale_and_skips_sym(void) { - const char* dir = TMP_SPLAY_BASE "/sweep"; - const char* symp = TMP_SPLAY_BASE "/sweep_sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/sweep"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/sweep_sym"); rm_rf(dir); unlink(symp); @@ -1400,7 +1400,7 @@ static test_result_t test_save_sweeps_stale_and_skips_sym(void) { * re-set fully heals it. * ========================================================================= */ static test_result_t test_torn_write_heals(void) { - const char* dir = TMP_SPLAY_BASE "/torn"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/torn"); rm_rf(dir); int64_t id_x = ray_sym_intern("x", 1); @@ -1443,8 +1443,8 @@ static test_result_t test_torn_write_heals(void) { * now closed by construction rather than by dictionary dumping). * ========================================================================= */ static test_result_t test_nested_sym_list_symfile(void) { - const char* dir = TMP_SPLAY_BASE "/nested_sym"; - const char* symp = TMP_SPLAY_BASE "/nested_sym_symfile"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/nested_sym"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/nested_sym_symfile"); rm_rf(dir); unlink(symp); @@ -1502,48 +1502,6 @@ static test_result_t test_nested_sym_list_symfile(void) { PASS(); } -/* ========================================================================= - * 32. Ragged column lengths -> loud corrupt (the detectable half of the - * in-place overwrite crash window): hand-shorten one column file's - * row count by rewriting it from a narrower vec. - * ========================================================================= */ -static test_result_t test_ragged_columns_corrupt(void) { - const char* dir = TMP_SPLAY_BASE "/ragged"; - rm_rf(dir); - - int64_t id_a = ray_sym_intern("a", 1); - int64_t id_b = ray_sym_intern("b", 1); - int64_t raw3[] = {1, 2, 3}; - ray_t* col_a = ray_vec_from_raw(RAY_I64, raw3, 3); - ray_t* col_b = ray_vec_from_raw(RAY_I64, raw3, 3); - ray_t* tbl = ray_table_new(3); - tbl = ray_table_add_col(tbl, id_a, col_a); - tbl = ray_table_add_col(tbl, id_b, col_b); - TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); - TEST_ASSERT_EQ_I(ray_splay_save(tbl, dir, NULL), RAY_OK); - - /* shorten b on disk (simulates old-generation leftover) */ - int64_t raw2[] = {9, 9}; - ray_t* shorter = ray_vec_from_raw(RAY_I64, raw2, 2); - char bpath[512]; - snprintf(bpath, sizeof(bpath), "%s/b", dir); - extern ray_err_t ray_col_save(ray_t* vec, const char* path); - TEST_ASSERT_EQ_I(ray_col_save(shorter, bpath), RAY_OK); - - ray_t* r = ray_splay_load(dir, NULL); - TEST_ASSERT_NOT_NULL(r); - TEST_ASSERT_TRUE(RAY_IS_ERR(r)); - TEST_ASSERT_STR_EQ(ray_err_code(r), "corrupt"); - ray_release(r); - - ray_release(shorter); - ray_release(col_a); - ray_release(col_b); - ray_release(tbl); - rm_rf(dir); - PASS(); -} - /* ========================================================================= * 33. Untrusted disk attrs are masked: a crafted column file with runtime- * only attr bits (HAS_INDEX / HAS_LINK / SLICE) set and garbage in the @@ -1554,7 +1512,7 @@ static test_result_t test_ragged_columns_corrupt(void) { * error — but never crash under ASan. * ========================================================================= */ static test_result_t test_untrusted_attrs_masked(void) { - const char* dir = TMP_SPLAY_BASE "/untrusted_attrs"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/untrusted_attrs"); rm_rf(dir); int64_t id_a = ray_sym_intern("a", 1); @@ -1653,7 +1611,7 @@ static test_result_t test_sym_col_name_allowed(void) { /* (a) issue #280: an I64 column literally named "sym", no SYM columns * -> saves and round-trips; no ".sym" symfile is written. */ { - const char* dir = TMP_SPLAY_BASE "/symcol_i64"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/symcol_i64"); rm_rf(dir); int64_t id_sym = ray_sym_intern("sym", 3); ray_t* col = ray_vec_from_raw(RAY_I64, raw, 3); @@ -1688,7 +1646,7 @@ static test_result_t test_sym_col_name_allowed(void) { /* (b) a SYM-typed column named "sym" coexists with the ".sym" symfile * and round-trips (the canonical q "sym" ticker column). */ { - const char* dir = TMP_SPLAY_BASE "/symcol_sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/symcol_sym"); rm_rf(dir); int64_t id_sym = ray_sym_intern("sym", 3); int64_t aapl = ray_sym_intern("AAPL", 4); @@ -1731,7 +1689,7 @@ static test_result_t test_sym_col_name_allowed(void) { /* (c) explicit sym_path that lands ON a column file (SYM columns * present) is rejected before any write. */ { - const char* dir = TMP_SPLAY_BASE "/symcol_collide"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/symcol_collide"); rm_rf(dir); int64_t id_s = ray_sym_intern("s", 1); int64_t id_px = ray_sym_intern("px", 2); @@ -1760,7 +1718,7 @@ static test_result_t test_sym_col_name_allowed(void) { /* (d) explicit sym_path whose ".lk" lock lands on a column file is * rejected too: symfile "px" -> lock "px.lk" vs a column "px.lk". */ { - const char* dir = TMP_SPLAY_BASE "/symcol_collide_lk"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/symcol_collide_lk"); rm_rf(dir); int64_t id_s = ray_sym_intern("s", 1); int64_t id_lk = ray_sym_intern("px.lk", 5); @@ -1789,11 +1747,11 @@ static test_result_t test_sym_col_name_allowed(void) { /* (e) NO false positive: a column "px" with the symfile in a DIFFERENT * directory saves fine even though a SYM column exists. */ { - const char* dir = TMP_SPLAY_BASE "/symcol_nocollide"; - const char* symp = TMP_SPLAY_BASE "/symcol_nocollide_dom"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/symcol_nocollide"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/symcol_nocollide_dom"); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/symcol_nocollide_dom.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/symcol_nocollide_dom.lk")); int64_t id_s = ray_sym_intern("s", 1); int64_t id_px = ray_sym_intern("px", 2); int64_t aapl = ray_sym_intern("AAPL", 4); @@ -1813,7 +1771,7 @@ static test_result_t test_sym_col_name_allowed(void) { ray_release(tbl); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/symcol_nocollide_dom.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/symcol_nocollide_dom.lk")); } PASS(); } @@ -1824,11 +1782,11 @@ static test_result_t test_sym_col_name_allowed(void) { * process dictionary; column width derives from the vocabulary. * ========================================================================= */ static test_result_t test_per_table_symfile_vocabulary(void) { - const char* dir = TMP_SPLAY_BASE "/vocab"; - const char* symp = TMP_SPLAY_BASE "/vocab_sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/vocab"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/vocab_sym"); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/vocab_sym.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/vocab_sym.lk")); /* Bloat the global dictionary with unrelated session symbols — the * v2 dump would have persisted all of them. */ @@ -1894,7 +1852,7 @@ static test_result_t test_per_table_symfile_vocabulary(void) { ray_release(tbl); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/vocab_sym.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/vocab_sym.lk")); PASS(); } @@ -1906,11 +1864,11 @@ static test_result_t test_per_table_symfile_vocabulary(void) { * the heap and mmap loaders. * ========================================================================= */ static test_result_t test_restart_reload_divergent_global(void) { - const char* dir = TMP_SPLAY_BASE "/restart"; - const char* symp = TMP_SPLAY_BASE "/restart_sym"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/restart"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/restart_sym"); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/restart_sym.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/restart_sym.lk")); int64_t id_s = ray_sym_intern("s", 1); int64_t v1 = ray_sym_intern("rst_aa", 6); @@ -1954,7 +1912,7 @@ static test_result_t test_restart_reload_divergent_global(void) { rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/restart_sym.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/restart_sym.lk")); PASS(); } @@ -1965,13 +1923,13 @@ static test_result_t test_restart_reload_divergent_global(void) { * append-only across the two saves (first table's positions stable). * ========================================================================= */ static test_result_t test_shared_symfile_domain_identity(void) { - const char* dir1 = TMP_SPLAY_BASE "/share_a"; - const char* dir2 = TMP_SPLAY_BASE "/share_b"; - const char* symp = TMP_SPLAY_BASE "/share_sym"; + const char* dir1 = ray_test_tmp(TMP_SPLAY_BASE "/share_a"); + const char* dir2 = ray_test_tmp(TMP_SPLAY_BASE "/share_b"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/share_sym"); rm_rf(dir1); rm_rf(dir2); unlink(symp); - unlink(TMP_SPLAY_BASE "/share_sym.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/share_sym.lk")); int64_t id_s = ray_sym_intern("s", 1); int64_t va = ray_sym_intern("shr_aa", 6); @@ -2039,7 +1997,7 @@ static test_result_t test_shared_symfile_domain_identity(void) { rm_rf(dir1); rm_rf(dir2); unlink(symp); - unlink(TMP_SPLAY_BASE "/share_sym.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/share_sym.lk")); PASS(); } @@ -2051,11 +2009,11 @@ static test_result_t test_shared_symfile_domain_identity(void) { * written and the load failed with the loud "sym" error. * ========================================================================= */ static test_result_t test_empty_sym_table_roundtrip(void) { - const char* dir = TMP_SPLAY_BASE "/empty_sym"; - const char* symp = TMP_SPLAY_BASE "/empty_sym_symfile"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/empty_sym"); + const char* symp = ray_test_tmp(TMP_SPLAY_BASE "/empty_sym_symfile"); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/empty_sym_symfile.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/empty_sym_symfile.lk")); int64_t id_s = ray_sym_intern("s", 1); ray_t* col = ray_sym_vec_new(RAY_SYM_W8, 4); @@ -2102,7 +2060,7 @@ static test_result_t test_empty_sym_table_roundtrip(void) { ray_release(tbl); rm_rf(dir); unlink(symp); - unlink(TMP_SPLAY_BASE "/empty_sym_symfile.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/empty_sym_symfile.lk")); PASS(); } @@ -2116,7 +2074,7 @@ static test_result_t test_empty_sym_table_roundtrip(void) { * intern state cannot influence resolution in either order. * ========================================================================= */ static test_result_t test_resolution_order_independence(void) { - const char* root = TMP_SPLAY_BASE "/ordroot"; + const char* root = ray_test_tmp(TMP_SPLAY_BASE "/ordroot"); rm_rf(root); char live[600], part[600], symp[600]; snprintf(live, sizeof(live), "%s/live", root); @@ -2227,11 +2185,11 @@ static test_result_t test_resolution_order_independence(void) { * dir/.sym precedence rule the explicit argument wins over. * ========================================================================= */ static test_result_t test_resolution_explicit_wins(void) { - const char* dir = TMP_SPLAY_BASE "/explwin"; - const char* osym = TMP_SPLAY_BASE "/explwin_other"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/explwin"); + const char* osym = ray_test_tmp(TMP_SPLAY_BASE "/explwin_other"); rm_rf(dir); unlink(osym); - unlink(TMP_SPLAY_BASE "/explwin_other.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/explwin_other.lk")); int64_t id_s = ray_sym_intern("s", 1); ray_t* a_dir = ray_str(dir, strlen(dir)); @@ -2325,7 +2283,7 @@ static test_result_t test_resolution_explicit_wins(void) { ray_release(tb); rm_rf(dir); unlink(osym); - unlink(TMP_SPLAY_BASE "/explwin_other.lk"); + unlink(ray_test_tmp(TMP_SPLAY_BASE "/explwin_other.lk")); PASS(); } @@ -2358,7 +2316,7 @@ static test_result_t test_splayed_has_nulls_roundtrip(void) { for (int i = 0; i < n_types; i++) { int8_t t = types[i]; - const char* dir = TMP_SPLAY_BASE "/hasnulls_rt"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/hasnulls_rt"); rm_rf(dir); ray_t* col = (t == RAY_SYM) ? ray_sym_vec_new(RAY_SYM_W8, 4) @@ -2409,7 +2367,7 @@ static test_result_t test_splayed_has_nulls_roundtrip(void) { * is deterministic (unsupported nested data), so it also proves that a * preflight/write error cannot advance the table-level manifest. */ static test_result_t test_splay_atomic_generation_publish(void) { - const char* dir = TMP_SPLAY_BASE "/atomic_generation"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/atomic_generation"); char manifest[512]; int n = snprintf(manifest, sizeof(manifest), "%s/.current", dir); TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(manifest)); @@ -2539,10 +2497,38 @@ static int generation_dir_count(const char* dir) { } #ifndef _WIN32 +/* A failed first write clears what it created in the table directory, but + * only unlinks a link found there, never what the link points to. */ +static test_result_t test_failed_first_write_unlinks_symlink(void) { + const char* dir = TMP_SPLAY_BASE "/first_write_symlink"; + const char* victim = TMP_SPLAY_BASE "/first_write_symlink_victim"; + const char* victim_file = TMP_SPLAY_BASE "/first_write_symlink_victim/keep"; + rm_rf(dir); + rm_rf(victim); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(victim), 0); + FILE* f = fopen(victim_file, "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs("keep", f); + fclose(f); + ray_splay_write_t write; + TEST_ASSERT_EQ_I(ray_splay_write_begin(dir, &write), RAY_OK); + char link_path[1024]; + int n = snprintf(link_path, sizeof(link_path), "%s/outside", dir); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(link_path)); + TEST_ASSERT_EQ_I(symlink(victim, link_path), 0); + TEST_ASSERT_EQ_I(ray_splay_write_finish(&write, RAY_ERR_IO, false), RAY_ERR_IO); + TEST_ASSERT_EQ_I(access(victim_file, F_OK), 0); + struct stat st; + TEST_ASSERT_TRUE(lstat(link_path, &st) != 0); + rm_rf(dir); + rm_rf(victim); + PASS(); +} + static test_result_t test_generation_prune_unlinks_symlink(void) { - const char* dir = TMP_SPLAY_BASE "/generation_symlink"; - const char* victim = TMP_SPLAY_BASE "/generation_symlink_victim"; - const char* victim_file = TMP_SPLAY_BASE "/generation_symlink_victim/keep"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_symlink"); + const char* victim = ray_test_tmp(TMP_SPLAY_BASE "/generation_symlink_victim"); + const char* victim_file = ray_test_tmp(TMP_SPLAY_BASE "/generation_symlink_victim/keep"); rm_rf(dir); rm_rf(victim); @@ -2587,12 +2573,62 @@ static test_result_t test_generation_prune_unlinks_symlink(void) { rm_rf(victim); PASS(); } + +/* The entry under .generations may itself be a link. Pruning it must unlink + * the link, not empty the directory it points to: opendir on the entry would + * follow it, where the per-entry lstat inside a generation does not apply. */ +static test_result_t test_generation_prune_unlinks_symlink_entry(void) { + const char* dir = TMP_SPLAY_BASE "/generation_symlink_entry"; + const char* victim = TMP_SPLAY_BASE "/generation_symlink_entry_victim"; + const char* victim_file = TMP_SPLAY_BASE "/generation_symlink_entry_victim/keep"; + rm_rf(dir); + rm_rf(victim); + + ray_t* one = generation_pair(1); + ray_t* two = generation_pair(2); + ray_t* three = generation_pair(3); + ray_t* four = generation_pair(4); + TEST_ASSERT_FALSE(RAY_IS_ERR(one)); + TEST_ASSERT_FALSE(RAY_IS_ERR(two)); + TEST_ASSERT_FALSE(RAY_IS_ERR(three)); + TEST_ASSERT_FALSE(RAY_IS_ERR(four)); + + TEST_ASSERT_EQ_I(ray_splay_save(one, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(two, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(three, dir, NULL), RAY_OK); + + TEST_ASSERT_EQ_I(ray_test_mkdir_p(victim), 0); + FILE* f = fopen(victim_file, "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs("keep", f); + fclose(f); + + char link_path[1024]; + int n = snprintf(link_path, sizeof(link_path), "%s/.generations/outside", dir); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(link_path)); + TEST_ASSERT_EQ_I(symlink(victim, link_path), 0); + + /* The next publish prunes every generation entry but the new one. */ + TEST_ASSERT_EQ_I(ray_splay_save(four, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(access(victim_file, F_OK), 0); + struct stat st; + TEST_ASSERT_TRUE(lstat(link_path, &st) != 0); + TEST_ASSERT_EQ_I(generation_dir_count(dir), 1); + + ray_release(four); + ray_release(three); + ray_release(two); + ray_release(one); + rm_rf(dir); + rm_rf(victim); + PASS(); +} #endif /* Force actual filesystem failures after the first column and after all * columns respectively. No invalid object or preflight shortcut is involved. */ static test_result_t test_generation_io_failures(void) { - const char* dir = TMP_SPLAY_BASE "/generation_io"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_io"); rm_rf(dir); ray_t* old = generation_pair(1); ray_t* next = generation_pair(9); @@ -2657,7 +2693,7 @@ static test_result_t test_generation_io_failures(void) { /* Only the selected generation is kept. A table mapped before a replacement * stays readable after its files are removed; a new read sees the new one. */ static test_result_t test_generation_keeps_only_current(void) { - const char* dir = TMP_SPLAY_BASE "/generation_readers"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_readers"); rm_rf(dir); ray_t* old = generation_pair(1); ray_t* next = generation_pair(9); @@ -2723,7 +2759,7 @@ static void dir_listing(const char* dir, char* out, size_t out_sz) { * first write's columns and their sidecars go at the first publish; the * symfile and the lock file stay. */ static test_result_t test_generation_first_write_removed(void) { - const char* dir = TMP_SPLAY_BASE "/generation_first_write"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_first_write"); rm_rf(dir); int64_t s_id = ray_sym_intern("s", 1); ray_t* t = generation_pair(1); @@ -2738,7 +2774,7 @@ static test_result_t test_generation_first_write_removed(void) { snprintf(sym, sizeof(sym), "%s/.sym", dir); TEST_ASSERT_EQ_I(ray_splay_save(t, dir, sym), RAY_OK); /* A sidecar of a first-write column goes with it. */ - FILE* f = fopen(TMP_SPLAY_BASE "/generation_first_write/x.link", "wb"); + FILE* f = fopen(ray_test_tmp(TMP_SPLAY_BASE "/generation_first_write/x.link"), "wb"); TEST_ASSERT_NOT_NULL(f); fputs("other", f); fclose(f); @@ -2766,23 +2802,23 @@ static test_result_t test_generation_first_write_removed(void) { * database root of new/../db/) loses only the columns its schema named: * not a partition, not a file named like no column of it. */ static test_result_t test_generation_first_write_keeps_others(void) { - const char* dir = TMP_SPLAY_BASE "/generation_shared_root"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_shared_root"); rm_rf(dir); - TEST_ASSERT_EQ_I(ray_test_mkdir_p(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t"), 0); - FILE* f = fopen(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t/keep", "wb"); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(ray_test_tmp(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t")), 0); + FILE* f = fopen(ray_test_tmp(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t/keep"), "wb"); TEST_ASSERT_NOT_NULL(f); fclose(f); ray_t* one = generation_pair(1); ray_t* two = generation_pair(2); TEST_ASSERT_EQ_I(ray_splay_save(one, dir, NULL), RAY_OK); - f = fopen(TMP_SPLAY_BASE "/generation_shared_root/notes", "wb"); + f = fopen(ray_test_tmp(TMP_SPLAY_BASE "/generation_shared_root/notes"), "wb"); TEST_ASSERT_NOT_NULL(f); fclose(f); TEST_ASSERT_EQ_I(ray_splay_save(two, dir, NULL), RAY_OK); char listing[512]; dir_listing(dir, listing, sizeof(listing)); TEST_ASSERT_STR_EQ(listing, ".current .generations .write.lock 2026.10.05 notes"); - TEST_ASSERT_EQ_I(access(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t/keep", F_OK), 0); + TEST_ASSERT_EQ_I(access(ray_test_tmp(TMP_SPLAY_BASE "/generation_shared_root/2026.10.05/t/keep"), F_OK), 0); TEST_ASSERT_TRUE(generation_matches(dir, true, 2)); ray_release(two); ray_release(one); @@ -2834,8 +2870,8 @@ static void generation_flip_child(const char* dir, const char* tmpl, int flips) * again and reads the selected one: no read fails while another process * publishes and prunes. */ static test_result_t test_generation_reader_races(void) { - const char* dir = TMP_SPLAY_BASE "/generation_race"; - const char* tmpl = TMP_SPLAY_BASE "/generation_race_tmpl"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_race"); + const char* tmpl = ray_test_tmp(TMP_SPLAY_BASE "/generation_race_tmpl"); rm_rf(dir); rm_rf(tmpl); ray_t* t = generation_pair(1); @@ -2847,7 +2883,7 @@ static test_result_t test_generation_reader_races(void) { TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, resolved, sizeof(resolved)), RAY_OK); snprintf(g0, sizeof(g0), "%s/.generations/g-0", dir); TEST_ASSERT_EQ_I(rename(resolved, g0), 0); - FILE* f = fopen(TMP_SPLAY_BASE "/generation_race/.current", "wb"); + FILE* f = fopen(ray_test_tmp(TMP_SPLAY_BASE "/generation_race/.current"), "wb"); TEST_ASSERT_NOT_NULL(f); fputs(".generations/g-0\n", f); fclose(f); @@ -3053,14 +3089,14 @@ static test_result_t test_generation_reader_interrupted(void) { #endif static test_result_t test_generation_invalid_manifest(void) { - const char* dir = TMP_SPLAY_BASE "/generation_manifest"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_manifest"); rm_rf(dir); ray_t* t = generation_pair(1); TEST_ASSERT_EQ_I(ray_splay_save(t, dir, NULL), RAY_OK); const char* invalid[] = {"", ".generations/../x\n", ".generations/g-1/..\n", ".generations/g-1\njunk\n", ".generations/\n"}; for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); i++) { - FILE* f = fopen(TMP_SPLAY_BASE "/generation_manifest/.current", "wb"); + FILE* f = fopen(ray_test_tmp(TMP_SPLAY_BASE "/generation_manifest/.current"), "wb"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_TRUE(fputs(invalid[i], f) >= 0); TEST_ASSERT_EQ_I(fclose(f), 0); @@ -3079,7 +3115,7 @@ static test_result_t test_generation_invalid_manifest(void) { } static test_result_t test_generation_writer_exit(void) { - const char* dir = TMP_SPLAY_BASE "/generation_exit"; + const char* dir = ray_test_tmp(TMP_SPLAY_BASE "/generation_exit"); rm_rf(dir); ray_t* old = generation_pair(1); ray_t* next = generation_pair(9); @@ -3158,12 +3194,14 @@ static bool splay_legacy_hash_file(ray_t* col, const char* path) { return ok; } -/* A save builds its hash indexes in the column files. An unclustered - * numeric column the save hashes on its own holds exactly the bytes the - * in-memory build appended before (as a single batch here, which sizes its +/* A save writes its hash indexes into the column files. A save builds no + * hash of its own (index policy: only explicit .idx.hash indexes persist), + * so the numeric columns carry an explicit one: each file holds exactly the + * bytes the in-memory build appends (a single batch here, which sizes its * arrays up front: the reference is built the old way, many batches); a - * SYM column's explicit hash, rebuilt over the file's positions, answers - * lookups. With the pool's per-column tasks and serially. */ + * SYM column's explicit hash, rebuilt over the file's positions in place, + * answers lookups. With the pool's per-column tasks and serially; + * generation 0 (the file bytes are compared). */ static test_result_t test_save_hash_in_place(void) { ray_pool_t* pool = ray_pool_get(); const char* d_auto = TMP_SPLAY_BASE "/hash_auto"; @@ -3192,13 +3230,17 @@ static test_result_t test_save_hash_in_place(void) { } ray_t* sh = s; ray_retain(sh); TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&sh))); + ray_t* ah = a; ray_retain(ah); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&ah))); + ray_t* th = t; ray_retain(th); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&th))); int64_t na = ray_sym_intern("a", 1), nt = ray_sym_intern("t", 1), ns = ray_sym_intern("s", 1); ray_t* t1 = ray_table_new(3); - t1 = ray_table_add_col(t1, na, a); - t1 = ray_table_add_col(t1, nt, t); + t1 = ray_table_add_col(t1, na, ah); + t1 = ray_table_add_col(t1, nt, th); t1 = ray_table_add_col(t1, ns, sh); rm_rf(d_auto); unlink(y_auto); - TEST_ASSERT_EQ_I(ray_splay_save(t1, d_auto, y_auto), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t1, d_auto, y_auto, RAY_COMPRESS_OFF), RAY_OK); if (plan == 1) atomic_store(&ray_parallel_flag, 0); static const char* cols[2] = { "a", "t" }; ray_t* vecs[2] = { a, t }; @@ -3225,16 +3267,129 @@ static test_result_t test_save_hash_in_place(void) { ray_release(back); ray_release(t1); ray_release(a); ray_release(t); ray_release(s); - ray_release(sh); + ray_release(sh); ray_release(ah); ray_release(th); } rm_rf(d_auto); unlink(y_auto); TEST_ASSERT_EQ_I(bad, 0); PASS(); } +/* The per-column layout (RAY_SYMFILE_COLUMN): each SYM column's vocabulary + * in its own symfile next to the column file, `/..sym`, and no + * shared one. Loads resolve each column over its own FILE domain (two + * domains in one table), in front of any symfile the caller names; a + * partition refuses one; a damaged one fails loudly. Generations 0 and 2. */ +static int64_t symfile_count(const char* path) { + FILE* f = fopen(path, "rb"); + int64_t cnt = -1; + if (f && fseek(f, 4, SEEK_SET) == 0 && fread(&cnt, 8, 1, f) != 1) cnt = -1; + if (f) fclose(f); + return cnt; +} +static bool path_ends_with(const char* p, const char* tail) { + size_t n = p ? strlen(p) : 0, k = strlen(tail); + return n >= k && memcmp(p + n - k, tail, k) == 0; +} +static test_result_t test_per_column_symfiles(void) { + int64_t s_a = ray_sym_intern("a", 1), s_b = ray_sym_intern("b", 1), s_n = ray_sym_intern("n", 1); + int64_t v[4] = { ray_sym_intern("pc_one", 6), ray_sym_intern("pc_two", 6), + ray_sym_intern("pc_three", 8), ray_sym_intern("pc_four", 7) }; + enum { R = 6 }; + static const int ia[R] = { 0, 1, 0, 2, 1, 0 }, ib[R] = { 1, 3, 1, 1, 0, 3 }; + ray_t* ca = ray_sym_vec_new(RAY_SYM_W64, R); + ray_t* cb = ray_sym_vec_new(RAY_SYM_W64, R); + ray_t* cn = ray_vec_new(RAY_I64, R); + TEST_ASSERT_FALSE(RAY_IS_ERR(ca)); TEST_ASSERT_FALSE(RAY_IS_ERR(cb)); TEST_ASSERT_FALSE(RAY_IS_ERR(cn)); + ca->len = cb->len = cn->len = R; + for (int i = 0; i < R; i++) { + ((int64_t*)ray_data(ca))[i] = v[ia[i]]; + ((int64_t*)ray_data(cb))[i] = v[ib[i]]; + ((int64_t*)ray_data(cn))[i] = i; + } + ray_t* t = ray_table_new(3); + t = ray_table_add_col(t, s_a, ca); + t = ray_table_add_col(t, s_b, cb); + t = ray_table_add_col(t, s_n, cn); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + /* an unrelated shared symfile, named to the loader: the columns' own win */ + const char* odir = ray_test_tmp(TMP_SPLAY_BASE "/pcol_other"); + char osym[512]; snprintf(osym, sizeof osym, "%s/.sym", odir); + rm_rf(odir); + { + ray_t* oc = ray_sym_vec_new(RAY_SYM_W64, 1); + TEST_ASSERT_FALSE(RAY_IS_ERR(oc)); + oc->len = 1; ((int64_t*)ray_data(oc))[0] = ray_sym_intern("pc_unrelated", 12); + ray_t* ot = ray_table_add_col(ray_table_new(1), s_a, oc); + TEST_ASSERT_EQ_I(ray_splay_save(ot, odir, osym), RAY_OK); + ray_release(oc); ray_release(ot); + } + for (int gen = 0; gen < 2; gen++) { + const char* dir = ray_test_tmp(gen ? TMP_SPLAY_BASE "/pcol2" : TMP_SPLAY_BASE "/pcol0"); + rm_rf(dir); + char shared[512], pa[512], pb[512], pn[512]; + snprintf(shared, sizeof shared, "%s/.sym", dir); + snprintf(pa, sizeof pa, "%s/.a.sym", dir); + snprintf(pb, sizeof pb, "%s/.b.sym", dir); + snprintf(pn, sizeof pn, "%s/.n.sym", dir); + TEST_ASSERT_EQ_I(ray_splay_save_layout(t, dir, shared, gen ? RAY_COMPRESS_ON : RAY_COMPRESS_OFF, + RAY_SYMFILE_COLUMN), RAY_OK); + struct stat st; + TEST_ASSERT_TRUE(stat(shared, &st) != 0); /* no shared symfile */ + TEST_ASSERT_TRUE(stat(pn, &st) != 0); /* none for a non-SYM column */ + TEST_ASSERT_EQ_I(symfile_count(pa), 4); /* "", one, two, three */ + TEST_ASSERT_EQ_I(symfile_count(pb), 4); /* "", two, four, one */ + for (int how = 0; how < 3; how++) { + ray_t* l = how == 0 ? ray_read_splayed(dir, NULL) + : how == 1 ? ray_splay_load(dir, NULL) : ray_read_splayed(dir, osym); + TEST_ASSERT_FALSE(RAY_IS_ERR(l)); + ray_t* la = ray_table_get_col_idx(l, 0); + ray_t* lb = ray_table_get_col_idx(l, 1); + TEST_ASSERT_TRUE(la && lb && la->type == RAY_SYM && lb->type == RAY_SYM); + struct ray_sym_domain_s* da = ray_sym_vec_domain(la); + struct ray_sym_domain_s* db = ray_sym_vec_domain(lb); + TEST_ASSERT_TRUE(da != db); + TEST_ASSERT_TRUE(da != ray_sym_runtime_domain() && db != ray_sym_runtime_domain()); + TEST_ASSERT_TRUE(path_ends_with(ray_sym_domain_path(da), "/.a.sym")); + TEST_ASSERT_TRUE(path_ends_with(ray_sym_domain_path(db), "/.b.sym")); + for (int i = 0; i < R; i++) { + ray_t* xa = ray_sym_vec_cell(la, i); + ray_t* xb = ray_sym_vec_cell(lb, i); + ray_t* ea = ray_sym_str(v[ia[i]]); + ray_t* eb = ray_sym_str(v[ib[i]]); + TEST_ASSERT_TRUE(xa && xb && ea && eb); + TEST_ASSERT_EQ_I((int64_t)ray_str_len(xa), (int64_t)ray_str_len(ea)); + TEST_ASSERT_MEM_EQ(ray_str_len(ea), ray_str_ptr(xa), ray_str_ptr(ea)); + TEST_ASSERT_EQ_I((int64_t)ray_str_len(xb), (int64_t)ray_str_len(eb)); + TEST_ASSERT_MEM_EQ(ray_str_len(eb), ray_str_ptr(xb), ray_str_ptr(eb)); + } + ray_release(l); + } + /* a partition's segments share one domain: a column symfile is refused */ + ray_t* pr = ray_read_splayed_dom(dir, NULL); + TEST_ASSERT_TRUE(pr && RAY_IS_ERR(pr)); + TEST_ASSERT_STR_EQ(ray_err_code(pr), "nyi"); + ray_error_free(pr); + /* a damaged column symfile fails the load, loudly */ + FILE* f = fopen(pb, "r+b"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(ftruncate(fileno(f), 3), 0); + fclose(f); + ray_t* bad = ray_read_splayed(dir, NULL); + TEST_ASSERT_TRUE(bad && RAY_IS_ERR(bad)); + TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); + ray_error_free(bad); + rm_rf(dir); + } + rm_rf(odir); + ray_release(ca); ray_release(cb); ray_release(cn); ray_release(t); + PASS(); +} + const test_entry_t splay_entries[] = { #ifndef _WIN32 { "splay/generation_prune_unlinks_symlink", test_generation_prune_unlinks_symlink, splay_setup, splay_teardown }, + { "splay/generation_prune_unlinks_symlink_entry", test_generation_prune_unlinks_symlink_entry, splay_setup, splay_teardown }, + { "splay/failed_first_write_unlinks_symlink", test_failed_first_write_unlinks_symlink, splay_setup, splay_teardown }, #endif { "splay/generation_io_failures", test_generation_io_failures, splay_setup, splay_teardown }, { "splay/generation_keeps_only_current", test_generation_keeps_only_current, splay_setup, splay_teardown }, @@ -3281,7 +3436,6 @@ const test_entry_t splay_entries[] = { { "splay/save_sweeps_stale", test_save_sweeps_stale_and_skips_sym, splay_setup, splay_teardown }, { "splay/torn_write_heals", test_torn_write_heals, splay_setup, splay_teardown }, { "splay/nested_sym_list_symfile", test_nested_sym_list_symfile, splay_setup, splay_teardown }, - { "splay/ragged_columns_corrupt", test_ragged_columns_corrupt, splay_setup, splay_teardown }, { "splay/untrusted_attrs_masked", test_untrusted_attrs_masked, splay_setup, splay_teardown }, { "splay/sym_col_name_allowed", test_sym_col_name_allowed, splay_setup, splay_teardown }, { "splay/per_table_symfile_vocab", test_per_table_symfile_vocabulary, splay_setup, splay_teardown }, @@ -3293,5 +3447,6 @@ const test_entry_t splay_entries[] = { { "splay/csv_symfile_order", test_csv_splayed_symfile_order, splay_setup, splay_teardown }, { "splay/csv_quote_mode_per_file", test_csv_splayed_quote_mode_per_file, splay_setup, splay_teardown }, { "splay/save_hash_in_place", test_save_hash_in_place, splay_setup, splay_teardown }, + { "splay/per_column_symfiles", test_per_column_symfiles, splay_setup, splay_teardown }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_srccheck.c b/test/test_srccheck.c new file mode 100644 index 000000000..cee0336e4 --- /dev/null +++ b/test/test_srccheck.c @@ -0,0 +1,531 @@ +/* + * Copyright (c) 2025-2026 Anton Kundenko + * All rights reserved. + + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "test.h" +#include "table/table.h" +#include "vec/vec.h" +#include +#include +#include +#include +#include +#include + +/* Line number of the first occurrence of any needle (0 if none). */ +static int first_hit(const char* path, const char* const* needles) { + FILE* f = fopen(path, "rb"); + if (!f) return 0; + char line[4096]; int ln = 0; + while (fgets(line, sizeof line, f)) { + ln++; + for (int i = 0; needles[i]; i++) + if (strstr(line, needles[i])) { fclose(f); return ln; } + } + fclose(f); + return 0; +} + +typedef struct { char bad[512]; int nbad; int nseen; bool saw_table; } srccheck_acc_t; + +static void walk(const char* dir, const char* rel, srccheck_acc_t* acc, + void (*fn)(const char*, const char*, srccheck_acc_t*)) { + DIR* d = opendir(dir); + if (!d) return; + struct dirent* e; + while ((e = readdir(d))) { + if (e->d_name[0] == '.') continue; + char p[1024], r[1024]; + if (snprintf(p, sizeof p, "%s/%s", dir, e->d_name) >= (int)sizeof p || + snprintf(r, sizeof r, "%s/%s", rel, e->d_name) >= (int)sizeof r) { /* never skip a file unseen */ + if (!acc->nbad) snprintf(acc->bad, sizeof acc->bad, "a path under %.400s is too long to check", rel); + acc->nbad++; + continue; + } + struct stat st; + if (stat(p, &st) != 0) continue; + if (S_ISDIR(st.st_mode)) { walk(p, r, acc, fn); continue; } + size_t n = strlen(p); + if (n > 2 && (strcmp(p + n - 2, ".c") == 0 || strcmp(p + n - 2, ".h") == 0)) fn(p, r, acc); + } + closedir(d); +} + +static void check_getters(const char* p, const char* rel, srccheck_acc_t* acc) { + static const char* const needles[] = { "ray_table_get_col(", "ray_table_get_col_idx(", NULL }; + acc->nseen++; + if (strcmp(rel, "src/table/table.c") == 0) { acc->saw_table = true; return; } + int ln = first_hit(p, needles); + if (ln) { + if (!acc->nbad && snprintf(acc->bad, sizeof acc->bad, "%s:%d uses a legacy getter", rel, ln) < 0) acc->bad[0] = 0; /* a long message is cut */ + acc->nbad++; + } +} + +/* The suite runs from the repository root; accept a build directory one level + * below it as well. */ +static test_result_t test_no_legacy_getters(void) { + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char dir[64]; snprintf(dir, sizeof dir, "%s/src", root); + srccheck_acc_t acc = { "", 0, 0, false }; + walk(dir, "src", &acc, check_getters); + TEST_ASSERT_FMT(acc.saw_table && acc.nseen > 50, "source tree not scanned (%d files)", acc.nseen); + TEST_ASSERT_FMT(acc.nbad == 0, "%s (%d files)", acc.bad, acc.nbad); + PASS(); +} + +/* Every [1] slot read outside table.c is marked: a dict / lambda / list / + * MAPCOMMON slot (not-a-table), or a table slot through which no column of + * an encoded table is read: an ownership edge, or a table proven to hold no + * encoded slot (plain-table). */ +static bool raw_list_hit(const char* line) { + if (strstr(line, "slots[1]")) return true; + const char* p = line; + while ((p = strstr(p, "(ray_t**)ray_data(")) != NULL) { + const char* q = strchr(p, ')'); /* closes the cast */ + q = q ? strchr(q + 1, ')') : NULL; /* closes ray_data( */ + if (q && q[1] == ')' && q[2] == '[' && q[3] == '1' && q[4] == ']') return true; + p++; + } + return false; +} + +static void check_raw_list(const char* p, const char* rel, srccheck_acc_t* acc) { + if (strcmp(rel, "src/table/table.c") == 0) return; + FILE* f = fopen(p, "rb"); + if (!f) return; + char line[4096]; int ln = 0; + while (fgets(line, sizeof line, f)) { + ln++; + if (!raw_list_hit(line)) continue; + if (strstr(line, "/* not-a-table */") || strstr(line, "/* plain-table */")) continue; + if (!acc->nbad) snprintf(acc->bad, sizeof acc->bad, "%s:%d reads slot [1] unmarked", rel, ln); + acc->nbad++; + } + fclose(f); +} + +static test_result_t test_no_raw_column_list(void) { + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char dir[64]; snprintf(dir, sizeof dir, "%s/src", root); + srccheck_acc_t acc = { "", 0, 0, false }; + walk(dir, "src", &acc, check_raw_list); + TEST_ASSERT_FMT(acc.nbad == 0, "%s (%d sites)", acc.bad, acc.nbad); + PASS(); +} + +/* The generation-2 materializer attaches through the persisted-attach + * predicate only (spec "Source checks"). */ +static test_result_t test_materializer_attach(void) { + static const char* const needles[] = { "ray_index_attach_built", NULL }; + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char path[128]; snprintf(path, sizeof path, "%s/src/store/enccol.c", root); + TEST_ASSERT_EQ_I(first_hit(path, needles), 0); + snprintf(path, sizeof path, "%s/src/store/encidx.c", root); /* the index-region parse */ + TEST_ASSERT_TRUE(stat(path, &st) == 0); + TEST_ASSERT_EQ_I(first_hit(path, needles), 0); + PASS(); +} + +static test_result_t test_cols_inplace_plain(void) { + TEST_ASSERT_TRUE(ray_table_cols_inplace(NULL) == NULL); + ray_t* v = ray_vec_new(RAY_I64, 0); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + TEST_ASSERT_TRUE(ray_table_cols_inplace(v) == NULL); /* not a table */ + ray_release(v); + ray_t* t = ray_table_new(0); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + ray_t* c = ray_table_cols_inplace(t); + TEST_ASSERT_TRUE(c != NULL && !RAY_IS_ERR(c)); + ray_release(t); + PASS(); +} + +/* Every "/tmp" path a test names lives under this process's own root, so + * two suites on one host never share a file: plain paths, paths inside a + * Rayfall or shell line, the bare root; an already-moved path and a path + * that merely contains "/tmp" elsewhere are left alone. The root exists. */ +static test_result_t test_tmp_paths_per_process(void) { + char root[64]; + snprintf(root, sizeof root, "/tmp/rayforce_t.%ld", (long)getpid()); + char want[256]; + snprintf(want, sizeof want, "%s/rayforce_x/a", root); + TEST_ASSERT_STR_EQ(ray_test_tmp("/tmp/rayforce_x/a"), want); + TEST_ASSERT_STR_EQ(ray_test_tmp(want), want); + snprintf(want, sizeof want, "(.db.splayed.set \"%s/t\" T) rm -rf %s/u; cd %s", root, root, root); + TEST_ASSERT_STR_EQ(ray_test_tmp("(.db.splayed.set \"/tmp/t\" T) rm -rf /tmp/u; cd /tmp"), want); + TEST_ASSERT_STR_EQ(ray_test_tmp("/var/tmp/x /tmpx rf_tmp/y"), "/var/tmp/x /tmpx rf_tmp/y"); + TEST_ASSERT_TRUE(ray_test_tmp("/tmp/rayforce_x/a") == ray_test_tmp("/tmp/rayforce_x/a")); + struct stat st; + TEST_ASSERT_TRUE(stat(root, &st) == 0 && S_ISDIR(st.st_mode)); + PASS(); +} + +/* P2: every request for a bound source's plain column is either guarded to + * a ready source or a declared random-access site. The definition and the + * declaration (colrange.c / colrange.h) are skipped. A `random:` marker + * names one of the audited classes (Task 15's table), so a new site cannot + * pass under an invented or misspelled reason. */ +static const char* const plain_classes[] = { + "index probe", "sort", "top-k sort key", + "holistic aggregate", "wide key", "indexed v2 strategy", "first-n", "slice group", + "STR strlen", "join", "datalog", "pivot", "window", "user value", + "unstage: scalar holistic or wide input", "unstage: v2 whole-column strategy", + NULL, +}; +static bool plain_marker_ok(const char* line) { + if (strstr(line, "/* ready-only */")) return true; + const char* m = strstr(line, "/* random: "); + if (!m) return false; + m += strlen("/* random: "); + const char* end = strstr(m, " */"); + if (!end) return false; + for (int i = 0; plain_classes[i]; i++) { + size_t n = strlen(plain_classes[i]); + if ((size_t)(end - m) == n && strncmp(m, plain_classes[i], n) == 0) return true; + } + return false; +} + +/* One source line requests a plain column without a marker on that line. */ +static bool plain_line_bad(const char* line) { + return strstr(line, "ray_col_src_plain(") && !plain_marker_ok(line); +} + +/* Unmarked request lines in `text`, as the tree check counts them in a + * file. */ +static int plain_text_bad(const char* text) { + char line[4096]; int bad = 0; + while (*text) { + const char* nl = strchr(text, '\n'); + size_t n = nl ? (size_t)(nl - text) : strlen(text); + if (n >= sizeof line) n = sizeof line - 1; + memcpy(line, text, n); line[n] = 0; + if (plain_line_bad(line)) bad++; + text += nl ? n + 1 : n; + } + return bad; +} + +static void check_plain_requests(const char* p, const char* rel, srccheck_acc_t* acc) { + acc->nseen++; + if (strcmp(rel, "src/table/table.c") == 0) acc->saw_table = true; + if (strcmp(rel, "src/store/colrange.c") == 0 || strcmp(rel, "src/store/colrange.h") == 0) return; + FILE* f = fopen(p, "rb"); + if (!f) return; + char line[4096]; int ln = 0; + while (fgets(line, sizeof line, f)) { + ln++; + if (!plain_line_bad(line)) continue; + if (!acc->nbad) snprintf(acc->bad, sizeof acc->bad, "%s:%d unmarked ray_col_src_plain", rel, ln); + acc->nbad++; + } + fclose(f); +} + +static test_result_t test_plain_requests_marked(void) { + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char dir[64]; snprintf(dir, sizeof dir, "%s/src", root); + srccheck_acc_t acc = { "", 0, 0, false }; + walk(dir, "src", &acc, check_plain_requests); + TEST_ASSERT_FMT(acc.saw_table && acc.nseen > 50, "source tree not scanned (%d files)", acc.nseen); + TEST_ASSERT_FMT(acc.nbad == 0, "%s (%d sites)", acc.bad, acc.nbad); + PASS(); +} + +/* The marker check itself: the accepted forms, and the near misses. */ +static test_result_t test_plain_marker_forms(void) { + TEST_ASSERT_TRUE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* ready-only */")); + TEST_ASSERT_TRUE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: wide key */")); + TEST_ASSERT_TRUE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: top-k sort key */")); + /* the P3 gather classes are gone: those sites gather by range now */ + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: top-k gather (P3) */")); + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: selection gather (P3) */")); + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c);")); + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: */")); + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: wide keys */")); + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* random: a route that reads whole columns */")); + TEST_ASSERT_FALSE(plain_marker_ok("x = ray_col_src_plain(s, &c); /* ready: never decodes */")); + /* The check is a text match on each line, not a parse: */ + /* a marker on the following line does not mark the call; */ + TEST_ASSERT_EQ_I(plain_text_bad("x = ray_col_src_plain(s, &c);\n/* random: wide key */\n"), 1); + /* a call written in a // comment counts as a call; */ + TEST_ASSERT_EQ_I(plain_text_bad("// ray_col_src_plain(s, &c) reads the column whole\n"), 1); + /* one marker covers every call on its line. */ + TEST_ASSERT_EQ_I(plain_text_bad("a = ray_col_src_plain(s, &c); b = ray_col_src_plain(t, &d); /* ready-only */\n"), 0); + TEST_ASSERT_EQ_I(plain_text_bad("a = ray_col_src_plain(s, &c); b = ray_col_src_plain(t, &d);\n"), 1); + PASS(); +} + +/* P3 Task 6b: the first-n pre-pass (agg_first_n_run) reads its keys at + * rows through their sources and gathers its groups' rows by range: its + * body neither unstages a key nor requests a plain column. The other + * whole-column strategies (indexed, serial) keep their marked sites. */ +static test_result_t test_firstn_reads_by_range(void) { + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char path[128]; snprintf(path, sizeof path, "%s/src/ops/agg_engine.c", root); + FILE* f = fopen(path, "rb"); + TEST_ASSERT_TRUE(f != NULL); + char line[4096]; int ln = 0, body = 0, bad = 0, lines = 0; + while (fgets(line, sizeof line, f)) { + ln++; + if (!body && strncmp(line, "static ray_t* agg_first_n_run(", 30) == 0 && !strchr(line, ';')) body = ln; + if (!body) continue; + lines++; + if (strstr(line, "agg_keys_unstage(") || strstr(line, "ray_col_src_plain(")) { if (!bad) bad = ln; } + if (line[0] == '}') break; + } + fclose(f); + TEST_ASSERT_FMT(body && lines > 50, "agg_first_n_run not found (%d lines)", lines); + TEST_ASSERT_FMT(bad == 0, "src/ops/agg_engine.c:%d: agg_first_n_run reads a key whole", bad); + PASS(); +} + +/* P1's transitional whole-table decode (carry 4) stays removed. */ +static void check_no_table_decode(const char* p, const char* rel, srccheck_acc_t* acc) { + static const char* const needles[] = { "TABLE_DECODE_OR_RETURN", NULL }; + acc->nseen++; + if (strcmp(rel, "src/table/table.c") == 0) acc->saw_table = true; + int ln = first_hit(p, needles); + if (ln) { + if (!acc->nbad && snprintf(acc->bad, sizeof acc->bad, "%s:%d names TABLE_DECODE_OR_RETURN", rel, ln) < 0) acc->bad[0] = 0; /* a long message is cut */ + acc->nbad++; + } +} +static test_result_t test_no_table_decode_or_return(void) { + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char dir[64]; snprintf(dir, sizeof dir, "%s/src", root); + srccheck_acc_t acc = { "", 0, 0, false }; + walk(dir, "src", &acc, check_no_table_decode); + TEST_ASSERT_FMT(acc.saw_table && acc.nseen > 50, "source tree not scanned (%d files)", acc.nseen); + TEST_ASSERT_FMT(acc.nbad == 0, "%s (%d files)", acc.bad, acc.nbad); + PASS(); +} + +/* P3's gate (Task 12): the P3 random-access classes are gone, every one of + * those sites gathers by range, and none comes back: no audited class names + * a P3 deferral, and no `random:` marker in the source carries "(P3)". */ +static bool p3_marker_line(const char* line) { + for (const char* m = strstr(line, "random:"); m; m = strstr(m + 1, "random:")) { + const char* end = strstr(m, "*/"); + const char* p3 = strstr(m, "(P3)"); + if (p3 && (!end || p3 < end)) return true; + } + return false; +} +static void check_no_p3_markers(const char* p, const char* rel, srccheck_acc_t* acc) { + acc->nseen++; + if (strcmp(rel, "src/table/table.c") == 0) acc->saw_table = true; + FILE* f = fopen(p, "rb"); + if (!f) return; + char line[4096]; int ln = 0; + while (fgets(line, sizeof line, f)) { + ln++; + if (!p3_marker_line(line)) continue; + if (!acc->nbad) snprintf(acc->bad, sizeof acc->bad, "%s:%d a (P3) random-access marker", rel, ln); + acc->nbad++; + } + fclose(f); +} +static test_result_t test_no_p3_markers(void) { + for (int i = 0; plain_classes[i]; i++) + TEST_ASSERT_FMT(!strstr(plain_classes[i], "(P3)"), "plain_classes names \"%s\"", plain_classes[i]); + /* the line check itself */ + TEST_ASSERT_TRUE(p3_marker_line("x = ray_col_src_plain(s, &c); /* random: top-k gather (P3) */")); + TEST_ASSERT_TRUE(p3_marker_line("/* ready-only */ y(); /* random: selection gather (P3) */")); + TEST_ASSERT_TRUE(p3_marker_line(" * random: a wide gather (P3), until the views land")); + TEST_ASSERT_FALSE(p3_marker_line("x = ray_col_src_plain(s, &c); /* random: wide key */")); + TEST_ASSERT_FALSE(p3_marker_line("/* random: sort */ /* gathers by range since (P3) Task 6 */")); + TEST_ASSERT_FALSE(p3_marker_line("/* gathers by range since (P3) Task 6 */")); + struct stat st; + const char* root = stat("src/table/table.c", &st) == 0 ? "." : ".."; + char dir[64]; snprintf(dir, sizeof dir, "%s/src", root); + srccheck_acc_t acc = { "", 0, 0, false }; + walk(dir, "src", &acc, check_no_p3_markers); + TEST_ASSERT_FMT(acc.saw_table && acc.nseen > 50, "source tree not scanned (%d files)", acc.nseen); + TEST_ASSERT_FMT(acc.nbad == 0, "%s (%d lines)", acc.bad, acc.nbad); + PASS(); +} + +/* `text` with comments and string / character literals blanked to spaces + * (newlines kept, so line numbers hold). Caller frees. */ +static char* code_only(const char* text) { + size_t n = strlen(text); + char* o = malloc(n + 1); + if (!o) return NULL; + memcpy(o, text, n + 1); + for (size_t i = 0; i < n; ) { + if (text[i] == '/' && text[i + 1] == '*') { + size_t j = i + 2; + while (j < n && !(text[j] == '*' && text[j + 1] == '/')) j++; + j = j < n ? j + 2 : n; + for (size_t k = i; k < j; k++) if (o[k] != '\n') o[k] = ' '; + i = j; + } else if (text[i] == '/' && text[i + 1] == '/') { + while (i < n && text[i] != '\n') o[i++] = ' '; + } else if (text[i] == '"' || text[i] == '\'') { + char q = text[i]; + size_t j = i + 1; + while (j < n && text[j] != q && text[j] != '\n') j += text[j] == '\\' && j + 1 < n ? 2 : 1; + j = j < n && text[j] == q ? j + 1 : j; + for (size_t k = i; k < j; k++) if (o[k] != '\n') o[k] = ' '; + i = j; + } else { + i++; + } + } + return o; +} + +static bool src_ident_char(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; +} + +/* A floating identifier: a token equal to a floating type or macro, a + * token containing a classifier or magnitude / sign helper (so + * __builtin_signbit, isnanf, fabsl, _Float64x match too), or a compiler + * builtin naming an infinity or NaN (__builtin_inf, __builtin_nanf). */ +static bool float_ident(const char* t, size_t n) { + static const char* const exact[] = { "double", "float", "NAN", "INFINITY", NULL }; + static const char* const inside[] = { "signbit", "isnan", "isinf", "isfinite", "isnormal", "fpclassify", + "fabs", "copysign", "HUGE_VAL", "_Float", NULL }; + static const char* const builtin[] = { "inf", "nan", "huge_val", NULL }; + char tok[256]; + if (n >= sizeof tok) n = sizeof tok - 1; + memcpy(tok, t, n); tok[n] = 0; + for (int k = 0; exact[k]; k++) if (strcmp(tok, exact[k]) == 0) return true; + for (int k = 0; inside[k]; k++) if (strstr(tok, inside[k])) return true; + if (strncmp(tok, "__builtin_", 10) == 0) + for (int k = 0; builtin[k]; k++) if (strncmp(tok + 10, builtin[k], strlen(builtin[k])) == 0) return true; + return false; +} + +/* Line of the first floating construct in the code of `text` (comments and + * literals skipped), 0 if none: a floating identifier (float_ident), or a + * floating literal (a decimal number with '.' or an exponent, a hex number + * with '.' or a 'p' exponent). */ +static int float_code_hit(const char* text) { + char* c = code_only(text); + if (!c) return -1; + int line = 1, hit = 0; + for (size_t i = 0; c[i] && !hit; ) { + if (c[i] == '\n') { line++; i++; continue; } + bool num = (c[i] >= '0' && c[i] <= '9') || (c[i] == '.' && c[i + 1] >= '0' && c[i + 1] <= '9'); + if (src_ident_char(c[i]) && !num) { + size_t j = i; + while (src_ident_char(c[j])) j++; + if (float_ident(c + i, j - i)) hit = line; + i = j; + } else if (num) { + bool hex = c[i] == '0' && (c[i + 1] == 'x' || c[i + 1] == 'X'); + bool fl = false; + size_t j = i; + while (src_ident_char(c[j]) || c[j] == '.') { + char ch = c[j]; + if (ch == '.') fl = true; + if (hex ? (ch == 'p' || ch == 'P') : (j > i && (ch == 'e' || ch == 'E'))) { + fl = true; + if (c[j + 1] == '+' || c[j + 1] == '-') j++; + } + j++; + } + if (fl) hit = line; + i = j; + } else { + i++; + } + } + free(c); + return hit; +} + +static char* src_slurp(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET); + char* t = n >= 0 ? malloc((size_t)n + 1) : NULL; + if (t) { size_t r = fread(t, 1, (size_t)n, f); t[r] = 0; } + fclose(f); + return t; +} + +/* The index-region validator, writer and parse decide float rules on bits: + * release builds use -fno-signed-zeros, under which a zero's sign test + * or a compare against zero may fold away (P4 Task 3 review). The check + * reads code only: a comment or message may say "10.0" or "doubles". */ +static test_result_t test_encidx_float_bits(void) { + /* the matcher itself */ + TEST_ASSERT_EQ_I(float_code_hit("/* 10.0 doubles, signbit( */ int x;"), 0); + TEST_ASSERT_EQ_I(float_code_hit("int a; // 0.0 double isnan\nint b;"), 0); + TEST_ASSERT_EQ_I(float_code_hit("f(\"0.0 double float\", 'x', '\\'');"), 0); + TEST_ASSERT_EQ_I(float_code_hit("int doubles = 10, my_double = 0x1Eu, d2 = 07;"), 0); + TEST_ASSERT_EQ_I(float_code_hit("if (signbit(x)) return;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("int a;\n double y;"), 2); + TEST_ASSERT_EQ_I(float_code_hit("/* x */\n/* y */ b = a < 0.0;"), 2); + TEST_ASSERT_EQ_I(float_code_hit("b = a < 10.0;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("x = 1e3;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("x = .5f;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("x = 0x1p3;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("char q = '\"'; float z;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("s = \"a\\\"b\"; isnan(z);"), 1); + TEST_ASSERT_EQ_I(float_code_hit("/* __builtin_signbit( __builtin_isnan( */ int x;"), 0); + TEST_ASSERT_EQ_I(float_code_hit("// __builtin_inf() __builtin_nan(\"\")\nint x;"), 0); + TEST_ASSERT_EQ_I(float_code_hit("if (__builtin_signbit(x)) return;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("int a;\nb = __builtin_isnan(x);"), 2); + TEST_ASSERT_EQ_I(float_code_hit("x = __builtin_inf();"), 1); + TEST_ASSERT_EQ_I(float_code_hit("x = __builtin_nan(\"\");"), 1); + TEST_ASSERT_EQ_I(float_code_hit("y = fabs(x) + copysign(a, b);"), 1); + TEST_ASSERT_EQ_I(float_code_hit("y = HUGE_VAL; _Float64 z;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("y = NAN;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("y = INFINITY;"), 1); + TEST_ASSERT_EQ_I(float_code_hit("int nan_count = __builtin_popcountll(x), infos;"), 0); + struct stat st; + const char* root = stat("src/store/encidx.c", &st) == 0 ? "." : ".."; + char p[128]; snprintf(p, sizeof p, "%s/src/store/encidx.c", root); + char* text = src_slurp(p); + TEST_ASSERT_NOT_NULL(text); + int ln = float_code_hit(text); + free(text); + TEST_ASSERT_FMT(ln == 0, "src/store/encidx.c:%d compares floating values", ln); + PASS(); +} + +const test_entry_t srccheck_entries[] = { + { "srccheck/no_legacy_getters", test_no_legacy_getters, NULL, NULL }, + { "srccheck/no_raw_column_list", test_no_raw_column_list, NULL, NULL }, + { "srccheck/materializer_attach", test_materializer_attach, NULL, NULL }, + { "srccheck/cols_inplace_plain", test_cols_inplace_plain, NULL, NULL }, + { "srccheck/tmp_paths_per_process", test_tmp_paths_per_process, NULL, NULL }, + { "srccheck/plain_requests_marked", test_plain_requests_marked, NULL, NULL }, + { "srccheck/plain_marker_forms", test_plain_marker_forms, NULL, NULL }, + { "srccheck/no_table_decode_or_return", test_no_table_decode_or_return, NULL, NULL }, + { "srccheck/firstn_reads_by_range", test_firstn_reads_by_range, NULL, NULL }, + { "srccheck/no_p3_markers", test_no_p3_markers, NULL, NULL }, + { "srccheck/encidx_float_bits", test_encidx_float_bits, NULL, NULL }, + { NULL, NULL, NULL, NULL }, +}; diff --git a/test/test_store.c b/test/test_store.c index 164b0b109..4aefe7bad 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -32,6 +32,7 @@ #include #include #include "mem/heap.h" +#include "mem/cow.h" /* ray_rc_sync: the lazy-hash probe threads */ #include "ops/ops.h" #include "store/col.h" #include "ops/idxop.h" @@ -53,6 +54,7 @@ #include #include "ops/hash.h" /* ray_hash_bytes: the import dictionary's full hashes */ #include "vec/str.h" +#include "vec/vec.h" /* ray_vec_may_have_nulls */ #ifndef RAY_OS_WINDOWS #include @@ -101,16 +103,16 @@ static test_result_t test_col_save_derives_has_nulls(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); vec->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; /* the forgetful producer */ - TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)), RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_TRUE((loaded->attrs & RAY_ATTR_HAS_NULLS) != 0); TEST_ASSERT_TRUE(ray_vec_is_null(loaded, 1)); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_TRUE((mapped->attrs & RAY_ATTR_HAS_NULLS) != 0); @@ -120,8 +122,8 @@ static test_result_t test_col_save_derives_has_nulls(void) { /* A null-free column stays null-free: the scan only ever sets. */ int64_t clean[] = {1, 2, 3}; ray_t* cvec = ray_vec_from_raw(RAY_I64, clean, 3); - TEST_ASSERT_EQ_I(ray_col_save(cvec, TMP_COL_PATH), RAY_OK); - ray_t* cl = ray_col_load(TMP_COL_PATH); + TEST_ASSERT_EQ_I(ray_col_save(cvec, ray_test_tmp(TMP_COL_PATH)), RAY_OK); + ray_t* cl = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(cl); TEST_ASSERT_TRUE((cl->attrs & RAY_ATTR_HAS_NULLS) == 0); ray_release(cl); @@ -139,11 +141,11 @@ static test_result_t test_col_mmap_i64(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); /* Save to file */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load via mmap */ - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); @@ -161,7 +163,7 @@ static test_result_t test_col_mmap_i64(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -173,10 +175,10 @@ static test_result_t test_col_mmap_f64(void) { TEST_ASSERT_NOT_NULL(vec); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); @@ -191,7 +193,7 @@ static test_result_t test_col_mmap_f64(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -203,10 +205,10 @@ static test_result_t test_col_mmap_f32(void) { TEST_ASSERT_NOT_NULL(vec); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_F32); @@ -216,7 +218,7 @@ static test_result_t test_col_mmap_f32(void) { TEST_ASSERT(loaded_data[i] == raw[i], "f32 load value mismatch"); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_U(mapped->mmod, 1); @@ -228,7 +230,7 @@ static test_result_t test_col_mmap_f32(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -239,10 +241,10 @@ static test_result_t test_col_mmap_cow(void) { ray_t* vec = ray_vec_from_raw(RAY_I64, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_U(mapped->mmod, 1); @@ -267,7 +269,7 @@ static test_result_t test_col_mmap_cow(void) { ray_release(copy); ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -278,10 +280,10 @@ static test_result_t test_col_mmap_refcount(void) { ray_t* vec = ray_vec_from_raw(RAY_I64, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_U(mapped->rc, 1); @@ -302,33 +304,14 @@ static test_result_t test_col_mmap_refcount(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_mmap_corrupt --------------------------------------------- */ - -static test_result_t test_col_mmap_corrupt(void) { - /* Write a 16-byte file (too small for a valid column header) */ - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - uint8_t junk[16] = {0}; - fwrite(junk, 1, 16, f); - fclose(f); - - ray_t* result = ray_col_mmap(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); - TEST_ASSERT_STR_EQ(ray_err_code(result), "corrupt"); - ray_release(result); - - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } /* ---- test_col_mmap_nofile ---------------------------------------------- */ static test_result_t test_col_mmap_nofile(void) { - ray_t* result = ray_col_mmap("/tmp/rayforce_nonexistent_file_xyz.dat"); + ray_t* result = ray_col_mmap(ray_test_tmp("/tmp/rayforce_nonexistent_file_xyz.dat")); TEST_ASSERT_TRUE(RAY_IS_ERR(result)); TEST_ASSERT_STR_EQ(ray_err_code(result), "io"); ray_release(result); @@ -340,7 +323,7 @@ static test_result_t test_col_mmap_nofile(void) { static test_result_t test_splay_open_roundtrip(void) { /* Clean up any leftover splay dir */ - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); /* Build a 3-column table: I64, F64, I32 */ ray_t* tbl = ray_table_new(4); @@ -370,11 +353,11 @@ static test_result_t test_splay_open_roundtrip(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); /* Save to splay directory */ - ray_err_t err = ray_splay_save(tbl, TMP_SPLAY_DIR, NULL); + ray_err_t err = ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); /* Open via mmap (zero-copy) */ - ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -390,9 +373,9 @@ static test_result_t test_splay_open_roundtrip(void) { TEST_ASSERT_NOT_NULL(lb); TEST_ASSERT_NOT_NULL(lc); - TEST_ASSERT_EQ_U(la->mmod, 1); - TEST_ASSERT_EQ_U(lb->mmod, 1); - TEST_ASSERT_EQ_U(lc->mmod, 1); + TEST_ASSERT_LOADED_MMOD(la, 1); + TEST_ASSERT_LOADED_MMOD(lb, 1); + TEST_ASSERT_LOADED_MMOD(lc, 1); /* Verify data */ int64_t* da = (int64_t*)ray_data(la); @@ -412,14 +395,14 @@ static test_result_t test_splay_open_roundtrip(void) { ray_release(tbl); /* Cleanup */ - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); PASS(); } /* ---- test_splay_str_column_roundtrip ----------------------------------- */ static test_result_t test_splay_str_column_roundtrip(void) { - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); ray_t* tbl = ray_table_new(2); TEST_ASSERT_NOT_NULL(tbl); @@ -447,10 +430,10 @@ static test_result_t test_splay_str_column_roundtrip(void) { tbl = ray_table_add_col(tbl, id_name, names); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); - ray_err_t err = ray_splay_save(tbl, TMP_SPLAY_DIR, NULL); + ray_err_t err = ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(ray_table_ncols(loaded), 2); @@ -460,14 +443,14 @@ static test_result_t test_splay_str_column_roundtrip(void) { ray_t* loaded_names = ray_table_get_col(loaded, id_name); TEST_ASSERT_NOT_NULL(loaded_ids); TEST_ASSERT_NOT_NULL(loaded_names); - TEST_ASSERT_EQ_U(loaded_ids->mmod, 1); - TEST_ASSERT_EQ_U(loaded_names->mmod, 1); + TEST_ASSERT_LOADED_MMOD(loaded_ids, 1); + TEST_ASSERT_LOADED_MMOD(loaded_names, 1); TEST_ASSERT_EQ_I(loaded_names->type, RAY_STR); TEST_ASSERT_NOT_NULL(loaded_names->str_pool); /* The pool owns the mapping it shares with the column (mmod 3), so a * selection that keeps the pool keeps the region — the column's own * free no longer takes the bytes with it. */ - TEST_ASSERT_EQ_U(loaded_names->str_pool->mmod, 3); + TEST_ASSERT_LOADED_MMOD(loaded_names->str_pool, 3); /* Empty STR roundtrips as the canonical null and retains metadata. */ TEST_ASSERT_TRUE(loaded_names->attrs & RAY_ATTR_HAS_NULLS); TEST_ASSERT_TRUE(ray_vec_is_null(loaded_names, 2)); @@ -485,7 +468,7 @@ static test_result_t test_splay_str_column_roundtrip(void) { ray_release(names); ray_release(tbl); - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); PASS(); } @@ -499,7 +482,7 @@ static test_result_t test_splay_str_column_roundtrip(void) { * ---------------------------------------------------------------------- */ static test_result_t test_splay_short_strv_roundtrip(void) { - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); int64_t id_short = ray_sym_intern("short", 5); int64_t id_empty = ray_sym_intern("empty", 5); @@ -515,10 +498,10 @@ static test_result_t test_splay_short_strv_roundtrip(void) { tbl = ray_table_add_col(tbl, id_short, shorts); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); - ray_err_t err = ray_splay_save(tbl, TMP_SPLAY_DIR, NULL); + ray_err_t err = ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(ray_table_ncols(loaded), 1); @@ -542,10 +525,10 @@ static test_result_t test_splay_short_strv_roundtrip(void) { tbl2 = ray_table_add_col(tbl2, id_empty, empty); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl2)); - err = ray_splay_save(tbl2, TMP_SPLAY_DIR, NULL); + err = ray_splay_save(tbl2, ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); - loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(ray_table_ncols(loaded), 1); @@ -561,13 +544,13 @@ static test_result_t test_splay_short_strv_roundtrip(void) { ray_release(tbl); ray_release(tbl2); - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); PASS(); } /* ---- test_splay_dict_column_roundtrip --------------------------------- */ static test_result_t test_splay_dict_column_roundtrip(void) { - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); int64_t ids_raw[] = {1, 2}; ray_t* ids = ray_vec_from_raw(RAY_I64, ids_raw, 2); @@ -599,8 +582,8 @@ static test_result_t test_splay_dict_column_roundtrip(void) { tbl = ray_table_add_col(tbl, sched_id, sched); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); - TEST_ASSERT_EQ_I(ray_splay_save(tbl, TMP_SPLAY_DIR, NULL), RAY_OK); - ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + TEST_ASSERT_EQ_I(ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_DIR), NULL), RAY_OK); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); ray_t* loaded_sched = ray_table_get_col(loaded, sched_id); @@ -622,13 +605,13 @@ static test_result_t test_splay_dict_column_roundtrip(void) { ray_release(tbl); ray_release(ids); ray_release(sched); - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); PASS(); } /* ---- test_splay_empty_list_column_roundtrip --------------------------- */ static test_result_t test_splay_empty_list_column_roundtrip(void) { - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); ray_t* ids = ray_vec_new(RAY_I64, 0); ray_t* who = ray_vec_new(RAY_SYM, 0); @@ -645,9 +628,9 @@ static test_result_t test_splay_empty_list_column_roundtrip(void) { tbl = ray_table_add_col(tbl, ray_sym_intern("sched", 5), sched); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); - const char* sym_path = TMP_SPLAY_DIR "/.sym"; - TEST_ASSERT_EQ_I(ray_splay_save(tbl, TMP_SPLAY_DIR, sym_path), RAY_OK); - ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, sym_path); + const char* sym_path = ray_test_tmp(TMP_SPLAY_DIR "/.sym"); + TEST_ASSERT_EQ_I(ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_DIR), sym_path), RAY_OK); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), sym_path); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(ray_table_ncols(loaded), 3); @@ -671,14 +654,14 @@ static test_result_t test_splay_empty_list_column_roundtrip(void) { ray_release(ids); ray_release(who); ray_release(sched); - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); PASS(); } /* A deterministic unsupported column must be rejected before an earlier * column can replace the committed generation. */ static test_result_t test_splay_save_preflight_preserves_generation(void) { - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); int64_t k_id = ray_sym_intern("k", 1); int64_t v_id = ray_sym_intern("v", 1); @@ -690,7 +673,7 @@ static test_result_t test_splay_save_preflight_preserves_generation(void) { good = ray_table_add_col(good, k_id, old_k); good = ray_table_add_col(good, v_id, old_v); TEST_ASSERT_FALSE(RAY_IS_ERR(good)); - TEST_ASSERT_EQ_I(ray_splay_save(good, TMP_SPLAY_DIR, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save(good, ray_test_tmp(TMP_SPLAY_DIR), NULL), RAY_OK); int64_t new_k_raw[] = {9, 10}; int64_t dk_raw[] = {1, 2}; @@ -703,9 +686,9 @@ static test_result_t test_splay_save_preflight_preserves_generation(void) { bad = ray_table_add_col(bad, v_id, old_v); ray_table_set_col_idx(bad, 1, unsupported); TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); - TEST_ASSERT_EQ_I(ray_splay_save(bad, TMP_SPLAY_DIR, NULL), RAY_ERR_NYI); + TEST_ASSERT_EQ_I(ray_splay_save(bad, ray_test_tmp(TMP_SPLAY_DIR), NULL), RAY_ERR_NYI); - ray_t* loaded = ray_read_splayed(TMP_SPLAY_DIR, NULL); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_DIR), NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); ray_t* loaded_k = ray_table_get_col(loaded, k_id); @@ -719,7 +702,7 @@ static test_result_t test_splay_save_preflight_preserves_generation(void) { ray_release(good); ray_release(old_v); ray_release(old_k); - (void)ray_test_rm_rf(TMP_SPLAY_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_DIR)); PASS(); } @@ -852,9 +835,9 @@ static test_result_t test_parted_release(void) { static test_result_t test_part_open(void) { /* Setup: create a 2-partition db with 2 columns each */ - (void)ray_test_rm_rf(TMP_PART_DB); - (void)ray_test_mkdir_p(TMP_PART_DB "/2024.01.01/" TMP_TABLE_NAME); - (void)ray_test_mkdir_p(TMP_PART_DB "/2024.01.02/" TMP_TABLE_NAME); + (void)ray_test_rm_rf(ray_test_tmp(TMP_PART_DB)); + (void)ray_test_mkdir_p(ray_test_tmp(TMP_PART_DB "/2024.01.01/" TMP_TABLE_NAME)); + (void)ray_test_mkdir_p(ray_test_tmp(TMP_PART_DB "/2024.01.02/" TMP_TABLE_NAME)); /* Partition 1: 3 rows */ int64_t raw_a1[] = {10, 20, 30}; @@ -867,7 +850,7 @@ static test_result_t test_part_open(void) { int64_t name_b = ray_sym_intern("b", 1); tbl1 = ray_table_add_col(tbl1, name_a, a1); tbl1 = ray_table_add_col(tbl1, name_b, b1); - ray_err_t err = ray_splay_save(tbl1, TMP_PART_DB "/2024.01.01/" TMP_TABLE_NAME, NULL); + ray_err_t err = ray_splay_save(tbl1, ray_test_tmp(TMP_PART_DB "/2024.01.01/" TMP_TABLE_NAME), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); /* Partition 2: 5 rows */ @@ -879,11 +862,11 @@ static test_result_t test_part_open(void) { ray_t* tbl2 = ray_table_new(3); tbl2 = ray_table_add_col(tbl2, name_a, a2); tbl2 = ray_table_add_col(tbl2, name_b, b2); - err = ray_splay_save(tbl2, TMP_PART_DB "/2024.01.02/" TMP_TABLE_NAME, NULL); + err = ray_splay_save(tbl2, ray_test_tmp(TMP_PART_DB "/2024.01.02/" TMP_TABLE_NAME), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); /* Save symfile */ - err = ray_sym_save(TMP_PART_DB "/.sym"); + err = ray_sym_save(ray_test_tmp(TMP_PART_DB "/.sym")); TEST_ASSERT_EQ_I(err, RAY_OK); /* Cleanup in-memory tables */ @@ -891,7 +874,7 @@ static test_result_t test_part_open(void) { ray_release(a2); ray_release(b2); ray_release(tbl2); /* Open via ray_read_parted */ - ray_t* parted = ray_read_parted(TMP_PART_DB, TMP_TABLE_NAME); + ray_t* parted = ray_read_parted(ray_test_tmp(TMP_PART_DB), TMP_TABLE_NAME); TEST_ASSERT_NOT_NULL(parted); TEST_ASSERT_FALSE(RAY_IS_ERR(parted)); @@ -938,9 +921,9 @@ static test_result_t test_part_open(void) { /* Verify segment 0 has 3 rows, mmod=1 (mmap'd) */ ray_t** segs_a = (ray_t**)ray_data(col_a); TEST_ASSERT_EQ_I(segs_a[0]->len, 3); - TEST_ASSERT_EQ_U(segs_a[0]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs_a[0], 1); TEST_ASSERT_EQ_I(segs_a[1]->len, 5); - TEST_ASSERT_EQ_U(segs_a[1]->mmod, 1); + TEST_ASSERT_LOADED_MMOD(segs_a[1], 1); /* Verify data in segment 0 */ int64_t* data_a0 = (int64_t*)ray_data(segs_a[0]); @@ -955,7 +938,7 @@ static test_result_t test_part_open(void) { /* Release — should unmap all segments */ ray_release(parted); - (void)ray_test_rm_rf(TMP_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_PART_DB)); PASS(); } @@ -963,11 +946,11 @@ static test_result_t test_part_open(void) { /* ray_parted_tables lists the splayed-table subdirectories of the first * partition as a sorted SYM vector usable with ray_read_parted. */ static test_result_t test_parted_tables(void) { - (void)ray_test_rm_rf(TMP_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_PART_DB)); /* Two tables (trades, quotes) across two partitions. */ const char* dirs[] = { - TMP_PART_DB "/2024.01.01/trades", TMP_PART_DB "/2024.01.01/quotes", - TMP_PART_DB "/2024.01.02/trades", TMP_PART_DB "/2024.01.02/quotes", + ray_test_tmp(TMP_PART_DB "/2024.01.01/trades"), ray_test_tmp(TMP_PART_DB "/2024.01.01/quotes"), + ray_test_tmp(TMP_PART_DB "/2024.01.02/trades"), ray_test_tmp(TMP_PART_DB "/2024.01.02/quotes"), }; int64_t a[] = {1, 2, 3}; for (int i = 0; i < 4; i++) { @@ -982,7 +965,7 @@ static test_result_t test_parted_tables(void) { } /* Sorted SYM vector: quotes, trades. */ - ray_t* names = ray_parted_tables(TMP_PART_DB); + ray_t* names = ray_parted_tables(ray_test_tmp(TMP_PART_DB)); TEST_ASSERT_NOT_NULL(names); TEST_ASSERT_FALSE(RAY_IS_ERR(names)); TEST_ASSERT_EQ_I(names->type, RAY_SYM); @@ -993,24 +976,24 @@ static test_result_t test_parted_tables(void) { ray_release(names); /* A returned name feeds straight back into ray_read_parted. */ - ray_t* tbl = ray_read_parted(TMP_PART_DB, "trades"); + ray_t* tbl = ray_read_parted(ray_test_tmp(TMP_PART_DB), "trades"); TEST_ASSERT_NOT_NULL(tbl); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); ray_release(tbl); /* An existing-but-empty root (no partition dirs) lists no tables — * an empty SYM vector, not an error. */ - (void)ray_test_rm_rf(TMP_PART_DB "_np"); - (void)ray_test_mkdir_p(TMP_PART_DB "_np"); - ray_t* empty = ray_parted_tables(TMP_PART_DB "_np"); + (void)ray_test_rm_rf(ray_test_tmp(TMP_PART_DB "_np")); + (void)ray_test_mkdir_p(ray_test_tmp(TMP_PART_DB "_np")); + ray_t* empty = ray_parted_tables(ray_test_tmp(TMP_PART_DB "_np")); TEST_ASSERT_NOT_NULL(empty); TEST_ASSERT_FALSE(RAY_IS_ERR(empty)); TEST_ASSERT_EQ_I(empty->type, RAY_SYM); TEST_ASSERT_EQ_I(empty->len, 0); ray_release(empty); - (void)ray_test_rm_rf(TMP_PART_DB "_np"); + (void)ray_test_rm_rf(ray_test_tmp(TMP_PART_DB "_np")); - (void)ray_test_rm_rf(TMP_PART_DB); + (void)ray_test_rm_rf(ray_test_tmp(TMP_PART_DB)); PASS(); } @@ -1139,10 +1122,10 @@ static test_result_t test_col_large_nullable_roundtrip(void) { TEST_ASSERT_TRUE((vec->attrs & RAY_ATTR_HAS_NULLS) != 0); /* --- Round-trip via ray_col_load --- */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -1168,7 +1151,7 @@ static test_result_t test_col_large_nullable_roundtrip(void) { ray_release(loaded); /* --- Round-trip via ray_col_mmap --- */ - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); @@ -1191,7 +1174,7 @@ static test_result_t test_col_large_nullable_roundtrip(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -1217,11 +1200,11 @@ static test_result_t test_col_save_load_str(void) { TEST_ASSERT_EQ_I(list->len, 3); /* Save */ - ray_err_t err = ray_col_save(list, TMP_COL_PATH); + ray_err_t err = ray_col_save(list, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -1251,7 +1234,7 @@ static test_result_t test_col_save_load_str(void) { ray_release(s1); ray_release(s2); ray_release(list); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -1274,11 +1257,11 @@ static test_result_t test_col_save_load_list(void) { TEST_ASSERT_EQ_I(list->len, 2); /* Save */ - ray_err_t err = ray_col_save(list, TMP_COL_PATH); + ray_err_t err = ray_col_save(list, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -1308,7 +1291,7 @@ static test_result_t test_col_save_load_list(void) { ray_release(v0); ray_release(v1); ray_release(list); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -1334,11 +1317,11 @@ static test_result_t test_col_save_load_table(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); /* Save */ - ray_err_t err = ray_col_save(tbl, TMP_COL_PATH); + ray_err_t err = ray_col_save(tbl, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -1375,7 +1358,7 @@ static test_result_t test_col_save_load_table(void) { ray_release(col_a); ray_release(col_b); ray_release(tbl); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -1385,19 +1368,19 @@ static test_result_t test_col_save_load_table(void) { static test_result_t test_file_open_close(void) { /* Open for write+create, then close */ - unlink(TMP_FILEIO_PATH); - ray_fd_t fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_WRITE | RAY_OPEN_CREATE); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); + ray_fd_t fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_WRITE | RAY_OPEN_CREATE); TEST_ASSERT((fd) != (RAY_FD_INVALID), "fd != RAY_FD_INVALID"); ray_file_close(fd); /* Open for read (file now exists) */ - fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_READ); + fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_READ); TEST_ASSERT((fd) != (RAY_FD_INVALID), "fd != RAY_FD_INVALID"); ray_file_close(fd); /* Open nonexistent for read (no create) → fail */ - unlink(TMP_FILEIO_PATH); - fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_READ); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); + fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_READ); TEST_ASSERT_EQ_I(fd, RAY_FD_INVALID); /* NULL path → fail */ @@ -1410,8 +1393,8 @@ static test_result_t test_file_open_close(void) { /* ---- test_file_lock_unlock --------------------------------------------- */ static test_result_t test_file_lock_unlock(void) { - unlink(TMP_FILEIO_PATH); - ray_fd_t fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_WRITE | RAY_OPEN_CREATE); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); + ray_fd_t fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_WRITE | RAY_OPEN_CREATE); TEST_ASSERT((fd) != (RAY_FD_INVALID), "fd != RAY_FD_INVALID"); /* Exclusive lock + unlock */ @@ -1432,15 +1415,15 @@ static test_result_t test_file_lock_unlock(void) { TEST_ASSERT_EQ_I(ray_file_unlock(RAY_FD_INVALID), RAY_OK); ray_file_close(fd); - unlink(TMP_FILEIO_PATH); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); PASS(); } /* ---- test_file_sync_op ------------------------------------------------- */ static test_result_t test_file_sync_op(void) { - unlink(TMP_FILEIO_PATH); - ray_fd_t fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_WRITE | RAY_OPEN_CREATE); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); + ray_fd_t fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_WRITE | RAY_OPEN_CREATE); TEST_ASSERT((fd) != (RAY_FD_INVALID), "fd != RAY_FD_INVALID"); /* fsync on valid fd */ @@ -1451,7 +1434,7 @@ static test_result_t test_file_sync_op(void) { TEST_ASSERT_EQ_I(ray_file_sync(RAY_FD_INVALID), RAY_ERR_IO); ray_file_close(fd); - unlink(TMP_FILEIO_PATH); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); PASS(); } @@ -1460,35 +1443,35 @@ static test_result_t test_file_sync_op(void) { #define TMP_FILEIO_PATH2 "/tmp/rayforce_test_fileio2.dat" static test_result_t test_file_rename_op(void) { - unlink(TMP_FILEIO_PATH); - unlink(TMP_FILEIO_PATH2); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); + unlink(ray_test_tmp(TMP_FILEIO_PATH2)); /* Create source file */ - ray_fd_t fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_WRITE | RAY_OPEN_CREATE); + ray_fd_t fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_WRITE | RAY_OPEN_CREATE); TEST_ASSERT((fd) != (RAY_FD_INVALID), "fd != RAY_FD_INVALID"); ray_file_close(fd); /* Rename */ - ray_err_t err = ray_file_rename(TMP_FILEIO_PATH, TMP_FILEIO_PATH2); + ray_err_t err = ray_file_rename(ray_test_tmp(TMP_FILEIO_PATH), ray_test_tmp(TMP_FILEIO_PATH2)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Old path should not exist, new should */ - fd = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_READ); + fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_READ); TEST_ASSERT_EQ_I(fd, RAY_FD_INVALID); - fd = ray_file_open(TMP_FILEIO_PATH2, RAY_OPEN_READ); + fd = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH2), RAY_OPEN_READ); TEST_ASSERT((fd) != (RAY_FD_INVALID), "fd != RAY_FD_INVALID"); ray_file_close(fd); /* Rename nonexistent → error */ - err = ray_file_rename("/tmp/rayforce_nonexistent_xyz", TMP_FILEIO_PATH2); + err = ray_file_rename(ray_test_tmp("/tmp/rayforce_nonexistent_xyz"), ray_test_tmp(TMP_FILEIO_PATH2)); TEST_ASSERT_EQ_I(err, RAY_ERR_IO); /* NULL args → error */ - TEST_ASSERT_EQ_I(ray_file_rename(NULL, TMP_FILEIO_PATH2), RAY_ERR_IO); - TEST_ASSERT_EQ_I(ray_file_rename(TMP_FILEIO_PATH, NULL), RAY_ERR_IO); + TEST_ASSERT_EQ_I(ray_file_rename(NULL, ray_test_tmp(TMP_FILEIO_PATH2)), RAY_ERR_IO); + TEST_ASSERT_EQ_I(ray_file_rename(ray_test_tmp(TMP_FILEIO_PATH), NULL), RAY_ERR_IO); - unlink(TMP_FILEIO_PATH2); + unlink(ray_test_tmp(TMP_FILEIO_PATH2)); PASS(); } @@ -1855,7 +1838,7 @@ static test_result_t test_stream_inline_zone(void) { int64_t n = 200000; ray_t* v = zone_test_col(n, 0, 0); ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("z", 1), RAY_I64, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("z", 1), RAY_I64, NULL, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w, 0), RAY_OK); for (int64_t off = 0; off < n; off += 70000) { int64_t cnt = n - off < 70000 ? n - off : 70000; @@ -1864,8 +1847,6 @@ static test_result_t test_stream_inline_zone(void) { ray_release(s); } TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); - TEST_ASSERT_FALSE(w.wants_hash); - TEST_ASSERT_NULL(w.index); char path[200]; snprintf(path, sizeof(path), "%s/z", dir); ray_t* back = ray_col_mmap(path); TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); @@ -1944,12 +1925,11 @@ static test_result_t test_stream_sentinel_publishes_has_nulls(void) { ((int64_t*)ray_data(s1))[7] = INT64_MIN; s2->attrs |= RAY_ATTR_HAS_NULLS; ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("n", 1), RAY_I64, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("n", 1), RAY_I64, NULL, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, s1), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, s2), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); - if (w.index) { ray_release(w.index); w.index = NULL; } char path[200]; snprintf(path, sizeof(path), "%s/n", dir); ray_t* back = ray_col_mmap(path); TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); @@ -2023,7 +2003,7 @@ static test_result_t test_stream_sym_chunks(void) { } c1->attrs |= RAY_ATTR_HAS_NULLS; ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("d", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("d", 1), RAY_SYM, dom, 0), RAY_OK); TEST_ASSERT_NULL(w.lut_id); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c1), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c2), RAY_OK); @@ -2054,7 +2034,7 @@ static test_result_t test_stream_sym_chunks(void) { ((int64_t*)ray_data(rt))[i] = id[1 + (i * 7) % (K - 1)]; } ((uint32_t*)ray_data(c3))[n - 1] = 0; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("r", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("r", 1), RAY_SYM, dom, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c3), RAY_OK); TEST_ASSERT_NULL(w.lut_id); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, rt), RAY_OK); @@ -2106,7 +2086,7 @@ static test_result_t test_stream_sym_from_str(void) { if (!dom[k]) { TEST_ASSERT_EQ_I(k, 1); break; } /* no import dictionary here */ TEST_ASSERT_EQ_I(ray_sym_domain_intern(dom[k], "", 0), 0); ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern(k ? "i" : "f", 1), RAY_SYM, dom[k]), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern(k ? "i" : "f", 1), RAY_SYM, dom[k], 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, col), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); back[k] = (uint32_t*)ray_sys_alloc((size_t)n * sizeof(uint32_t)); @@ -2164,7 +2144,7 @@ static test_result_t test_stream_sym_foreign(void) { TEST_ASSERT_NOT_NULL(c); for (int64_t i = 0; i < n; i++) ((uint32_t*)ray_data(c))[i] = (uint32_t)at2[(i * 3) % K]; ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("f", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("f", 1), RAY_SYM, dom, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, c), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); int64_t at[K]; @@ -2215,7 +2195,7 @@ static test_result_t test_stream_sym_lut_stale(void) { rt->len = n; for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(rt))[i] = x; ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("l", 1), RAY_SYM, dom), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("l", 1), RAY_SYM, dom, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, rt), RAY_OK); TEST_ASSERT_NOT_NULL(w.lut_id); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); @@ -2252,7 +2232,7 @@ static test_result_t test_stream_index_write_failure_drops_index(void) { pid_t pid = fork(); TEST_ASSERT_TRUE(pid >= 0); if (!pid) { ray_col_stream_t w; - if (ray_col_stream_open(&w, dir, ray_sym_intern("c", 1), RAY_I64, NULL) != RAY_OK) _exit(2); + if (ray_col_stream_open(&w, dir, ray_sym_intern("c", 1), RAY_I64, NULL, 0) != RAY_OK) _exit(2); if (ray_col_stream_index_begin(&w, 0) != RAY_OK) _exit(2); if (ray_col_stream_append(&w, v) != RAY_OK) _exit(2); struct rlimit limit; @@ -2280,7 +2260,7 @@ static test_result_t test_stream_index_write_failure_drops_index(void) { #endif } -/* Exactly 65536 rows: one chunk, a zone, never a hash candidate. */ +/* Exactly 65536 rows: one chunk, a zone. */ static test_result_t test_stream_inline_zone_one_chunk(void) { char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-one-%d", (int)getpid()); TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); @@ -2288,11 +2268,10 @@ static test_result_t test_stream_inline_zone_one_chunk(void) { ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = (i * 7919) % 1000003; /* unclustered */ ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("o", 1), RAY_I64, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("o", 1), RAY_I64, NULL, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, v), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); - TEST_ASSERT_FALSE(w.wants_hash); char path[200]; snprintf(path, sizeof(path), "%s/o", dir); ray_t* back = ray_col_mmap(path); TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); @@ -2305,38 +2284,26 @@ static test_result_t test_stream_inline_zone_one_chunk(void) { static bool store_files_same(const char* a, const char* b); static ray_err_t store_hash_append_legacy(const char* path); -/* Unclustered I64 over four chunks: no inline index, the zone is kept and - * wants_hash set; ray_splay_hash_column then appends a hash. */ -static test_result_t test_stream_hash_candidate(void) { - char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-hash-%d", (int)getpid()); - TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); +/* Index policy: the staged bulk save (parted Parquet partitions, fresh + * .csv.parted leaves) persists no HASH for an unclustered I64 column of + * 300000 rows, the shape the splayed converter hashes today. A guard that + * passes today (the staged path builds no index); vacuous when the legacy + * getter decodes a generation-2 column in the equivalence pass. */ +static test_result_t test_staged_bulk_no_hash(void) { + char dir[160]; snprintf(dir, sizeof(dir), "%s", ray_test_tmp("/tmp/rayforce-staged-nohash")); + (void)ray_test_rm_rf(dir); int64_t n = 300000; ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = (i * 7919) % 1000003; - ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("h", 1), RAY_I64, NULL), RAY_OK); - TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w, 0), RAY_OK); - TEST_ASSERT_EQ_I(ray_col_stream_append(&w, v), RAY_OK); - TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); - TEST_ASSERT_TRUE(w.wants_hash); - TEST_ASSERT_NOT_NULL(w.index); - char path[200]; snprintf(path, sizeof(path), "%s/h", dir); - ray_t* back = ray_col_mmap(path); - TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); - TEST_ASSERT_FALSE(back->attrs & RAY_ATTR_HAS_INDEX); - ray_release(back); - TEST_ASSERT_EQ_I(ray_splay_hash_column(path, w.index), RAY_OK); - ray_release(w.index); w.index = NULL; - back = ray_col_mmap(path); + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("u", 1), v); + ray_release(v); + TEST_ASSERT_EQ_I(ray_splay_save_staged_bulk(t, dir, NULL), RAY_OK); + ray_release(t); + ray_t* back = ray_read_splayed(dir, NULL); TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); - TEST_ASSERT_EQ_I(ray_index_kind(back), RAY_IDX_HASH); + TEST_ASSERT_TRUE(ray_index_kind(ray_table_get_col_idx(back, 0)) != RAY_IDX_HASH); ray_release(back); - /* the file is the one the in-memory build appended before */ - char ref[200]; snprintf(ref, sizeof(ref), "%s/ref", dir); - TEST_ASSERT_EQ_I(ray_col_save_bulk(v, ref), RAY_OK); - TEST_ASSERT_EQ_I(store_hash_append_legacy(ref), RAY_OK); - TEST_ASSERT_TRUE(store_files_same(path, ref)); - ray_release(v); (void)ray_test_rm_rf(dir); PASS(); } @@ -2414,11 +2381,90 @@ static ray_err_t store_hash_build(const char* path) { return err; } +/* The route a splayed save takes for an explicit hash (splay.c, + * splay_hash_append): built in place, or where that does not apply + * (RAY_ERR_NYI) built in memory and appended. Converters persist no + * auto-built hash (index policy), so no store entry point re-reads a file + * to hash it; the in-memory fallback is exercised here. */ +static ray_err_t store_hash_routed(const char* path) { + ray_t* col = ray_col_mmap(path); + if (!col || RAY_IS_ERR(col)) { if (col) ray_error_free(col); return RAY_ERR_IO; } + ray_err_t err = ray_col_build_hash_index(path, col, NULL); + if (err == RAY_ERR_NYI) { + ray_t* hi = ray_idx_hash_fn(col); + if (!hi || RAY_IS_ERR(hi)) { if (hi) ray_error_free(hi); err = RAY_ERR_OOM; } + else { + err = (hi->attrs & RAY_ATTR_HAS_INDEX) + ? ray_col_append_index(path, ray_index_payload(hi->index), hi->len, hi->type) + : RAY_ERR_IO; + ray_release(hi); + } + } + ray_release(col); + return err; +} + static int64_t store_file_size(const char* path) { struct stat st; return stat(path, &st) == 0 ? (int64_t)st.st_size : -1; } +/* A truncated generation-1 file (a partial copy, a full disk elsewhere) + * fails at load and at map, whatever its cut: a vector cut in its header + * or its data, a STR column cut in its pool, a LIST cut in an element. The + * extents are checked; the values are taken as written. */ +static ray_t* store_trunc_case(int k) { + if (k == 0) { + ray_t* v = ray_vec_new(RAY_I64, 1000); + v->len = 1000; + for (int64_t i = 0; i < 1000; i++) ((int64_t*)ray_data(v))[i] = i * 7; + return v; + } + if (k == 1) { + ray_t* v = ray_vec_new(RAY_STR, 64); + for (int i = 0; i < 64; i++) { + char b[64]; + int n = snprintf(b, sizeof b, "a pooled string value number %d", i); + v = ray_str_vec_append(v, b, (size_t)n); + } + return v; + } + ray_t* l = ray_list_new(3); + ray_t* a = ray_i64(42); + ray_t* s = ray_str("a string in a list, long enough", 31); + ray_t* v = store_trunc_case(0); + l = ray_list_append(l, a); l = ray_list_append(l, s); l = ray_list_append(l, v); + ray_release(a); ray_release(s); ray_release(v); + return l; +} +static test_result_t test_col_truncated_fails(void) { + const char* p = ray_test_tmp(TMP_COL_PATH); + for (int k = 0; k < 3; k++) { + ray_t* v = store_trunc_case(k); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + TEST_ASSERT_EQ_I(ray_col_save(v, p), RAY_OK); + int64_t full = store_file_size(p); + const int64_t cuts[] = { 16, 40, full / 2, full - 1 }; + for (size_t c = 0; c < sizeof cuts / sizeof cuts[0]; c++) { + TEST_ASSERT_EQ_I(ray_col_save(v, p), RAY_OK); + TEST_ASSERT_EQ_I(truncate(p, (off_t)cuts[c]), 0); + for (int how = 0; how < (k == 2 ? 1 : 2); how++) { /* a LIST has no map */ + ray_t* r = how ? ray_col_mmap(p) : ray_col_load(p); + if (!r || !RAY_IS_ERR(r)) { + if (r) ray_release(r); + ray_release(v); + FAILF("case %d cut at %lld of %lld: %s opened", k, (long long)cuts[c], + (long long)full, how ? "map" : "load"); + } + ray_error_free(r); + } + } + ray_release(v); + } + unlink(p); + PASS(); +} + /* Does `dir` take the in-place build (Linux, a filesystem whose fallocate * holds the blocks)? Probed with a small column. */ static bool store_in_place(const char* dir) { @@ -2436,7 +2482,7 @@ static bool store_in_place(const char* dir) { * build appended — numeric, temporal, float with nulls, SYM ids, every key * distinct or few — with one batch and with many (the counting pass), and * the index loads and answers. Where the in-place build does not apply, - * the same through ray_splay_hash_column's in-memory route. */ + * the same through the in-memory route (store_hash_routed). */ static test_result_t test_col_build_hash_index_bytes(void) { (void)ray_pool_get(); char name[16]; @@ -2464,7 +2510,7 @@ static test_result_t test_col_build_hash_index_bytes(void) { if (!v || RAY_IS_ERR(v)) { bad++; continue; } if (ray_col_save_bulk(v, a) != RAY_OK || ray_col_save_bulk(v, b) != RAY_OK) bad++; int64_t payload = store_file_size(a); - ray_err_t e = in_place ? store_hash_build(a) : ray_splay_hash_column(a, NULL); + ray_err_t e = in_place ? store_hash_build(a) : store_hash_routed(a); if (e != RAY_OK || store_hash_append_legacy(b) != RAY_OK) bad++; if (!store_files_same(a, b) || store_file_size(a) <= payload) bad++; ray_t* m = ray_col_mmap(a); @@ -2517,8 +2563,8 @@ static test_result_t test_col_build_hash_index_refusals(void) { int64_t plain = store_file_size(q); TEST_ASSERT_EQ_I(store_hash_build(q), RAY_ERR_NYI); TEST_ASSERT_EQ_I(store_file_size(q), plain); - /* ray_splay_hash_column takes the in-memory path for it */ - TEST_ASSERT_EQ_I(ray_splay_hash_column(q, NULL), RAY_OK); + /* the routed build takes the in-memory path for it */ + TEST_ASSERT_EQ_I(store_hash_routed(q), RAY_OK); m = ray_col_mmap(q); TEST_ASSERT_TRUE(m && !RAY_IS_ERR(m)); TEST_ASSERT_EQ_I(ray_index_kind(m), RAY_IDX_HASH); @@ -2530,7 +2576,7 @@ static test_result_t test_col_build_hash_index_refusals(void) { /* On a filesystem the in-place build does not trust (copy-on-write, * network, user — or any platform but Linux) it leaves the file alone, and - * ray_splay_hash_column builds the index in memory and appends it: the same + * the routed build makes the index in memory and appends it: the same * bytes. Debug builds pretend the filesystem is untrusted. */ static test_result_t test_col_build_hash_index_untrusted_fs(void) { #if defined(RAY_OS_LINUX) && !defined(DEBUG) @@ -2550,7 +2596,7 @@ static test_result_t test_col_build_hash_index_untrusted_fs(void) { int64_t payload = store_file_size(a); ray_err_t direct = store_hash_build(a); int64_t after = store_file_size(a); - ray_err_t routed = ray_splay_hash_column(a, NULL); + ray_err_t routed = store_hash_routed(a); #if defined(DEBUG) unsetenv("RAY_HASH_INJECT"); #endif @@ -2614,10 +2660,26 @@ static test_result_t test_col_build_hash_index_fs_types(void) { #endif } +/* A SYM column of 300000 rows over `keys` interned symbols, carrying an + * explicit hash index (.idx.hash). */ +static ray_t* store_cancel_sym_col(int64_t keys) { + char name[16]; + for (int64_t i = 0; i <= keys; i++) { /* SYM ids below the interned count */ + int l = snprintf(name, sizeof(name), "hc%lld", (long long)i); + if (ray_sym_intern(name, (size_t)l) < 0) return NULL; + } + ray_t* v = store_hash_col(RAY_SYM, 300000, keys, 0); + if (!v || RAY_IS_ERR(v)) return v; + ray_t* h = ray_idx_hash_fn(v); + ray_release(v); + return h; +} + /* A region that cannot be allocated or mapped this time (debug builds * inject either) does not cost the column its hash index: the in-place - * build gives way (NYI, the file at its payload) and ray_splay_hash_column - * and a splayed save build it in memory and append it — the same bytes. */ + * build gives way (NYI, the file at its payload) and the routed build + * and a splayed save of an explicit SYM hash build it in memory and append + * it — the same bytes. */ static test_result_t test_col_build_hash_index_refused(void) { #if defined(DEBUG) char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-hidx-ref2-%d", (int)getpid()); @@ -2637,7 +2699,7 @@ static test_result_t test_col_build_hash_index_refused(void) { TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", steps[s], 1), 0); ray_err_t direct = store_hash_build(a); int64_t after = store_file_size(a); - ray_err_t routed = ray_splay_hash_column(a, NULL); + ray_err_t routed = store_hash_routed(a); unsetenv("RAY_HASH_INJECT"); if (direct != RAY_ERR_NYI || after != payload || routed != RAY_OK) bad++; if (store_hash_append_legacy(b) != RAY_OK || !store_files_same(a, b)) bad++; @@ -2647,16 +2709,22 @@ static test_result_t test_col_build_hash_index_refused(void) { } if (plan == 1) ray_heap_set_anon_watermark(0); } - /* a splayed save under the same refusal still hashes the column */ + /* a generation-0 splayed save of an explicit SYM hash under the same + * refusal still hashes the column (converters persist no auto-built + * hash: index policy, so the explicit index is the save's hash build) */ int64_t name = ray_sym_intern("k", 1); ray_t* t = ray_table_new(1); - t = ray_table_add_col(t, name, v); + ray_t* sv = store_cancel_sym_col(2003); + TEST_ASSERT_TRUE(sv && !RAY_IS_ERR(sv) && (sv->attrs & RAY_ATTR_HAS_INDEX)); + t = ray_table_add_col(t, name, sv); + ray_release(sv); char sd[200]; snprintf(sd, sizeof(sd), "%s/t", dir); + char yp[220]; snprintf(yp, sizeof(yp), "%s/t.sym", dir); /* the SYM columns' symfile */ TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "map", 1), 0); - ray_err_t se = ray_splay_save(t, sd, NULL); + ray_err_t se = ray_splay_save_mode(t, sd, yp, RAY_COMPRESS_OFF); unsetenv("RAY_HASH_INJECT"); TEST_ASSERT_EQ_I(se, RAY_OK); - ray_t* back = ray_read_splayed(sd, NULL); + ray_t* back = ray_read_splayed(sd, yp); TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); if (ray_index_kind(ray_table_get_col(back, name)) != RAY_IDX_HASH) bad++; ray_release(back); @@ -2708,9 +2776,156 @@ static test_result_t test_col_build_hash_index_truncate(void) { #endif } +/* A cancel skips the finish tasks not yet started and the dispatch returns + * normally (#716): close_all must report it and publish no column. */ +static test_result_t test_stream_close_all_cancel(void) { + ray_pool_t* pool = ray_pool_get(); + if (!pool || pool->n_workers == 0) SKIP("the finish runs in line without pool workers"); + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-cancel-%d", (int)getpid()); + (void)ray_test_rm_rf(dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + ray_col_stream_t w[2]; + memset(w, 0, sizeof(w)); + ray_t* v = store_hash_col(RAY_I64, 1000, 97, 0); + for (int c = 0; c < 2; c++) { + TEST_ASSERT_EQ_I(ray_col_stream_open(&w[c], dir, ray_sym_intern(c ? "y" : "x", 1), RAY_I64, NULL, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w[c], v), RAY_OK); + } + ray_request_interrupt(); + ray_err_t e = ray_col_stream_close_all(w, 2, false, NULL); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + for (int c = 0; c < 2; c++) { + char p[200]; snprintf(p, sizeof(p), "%s/%s", dir, c ? "y" : "x"); + TEST_ASSERT_TRUE(access(p, F_OK) != 0); + } + ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +#if defined(DEBUG) && defined(RAY_OS_LINUX) +/* Two explicitly hashed SYM columns, saved as generation 0 (the save + * rebuilds an explicit SYM hash over the file-local ids in place, + * splay_hash_append): the debug build's "build" injection raises an + * interrupt inside the first hash build, once every column file is written. + * Converters build no hash of their own (index policy). */ +static ray_t* store_cancel_table(void) { + ray_t* t = ray_table_new(2); + for (int c = 0; c < 2; c++) { + ray_t* v = store_cancel_sym_col(c ? 7919 : 5003); + t = ray_table_add_col(t, ray_sym_intern(c ? "b" : "a", 1), v); + ray_release(v); + } + return t; +} +#endif + +/* A cancel that lands once the columns are written (here: in the hash + * build, the last phase before .d) still stops a save: over an existing + * table the previous generation stays current, and a first write leaves + * no table (a directory made beforehand keeps what else it holds). */ +static test_result_t test_splay_save_cancel_late(void) { +#if defined(DEBUG) && defined(RAY_OS_LINUX) + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-save-cancel-%d", (int)getpid()); + (void)ray_test_rm_rf(dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char sd[200]; snprintf(sd, sizeof(sd), "%s/t", dir); + char yp[220]; snprintf(yp, sizeof(yp), "%s/t.sym", dir); /* the SYM columns' symfile */ + int64_t small[3] = {1, 2, 3}; + ray_t* t = ray_table_new(2); + for (int c = 0; c < 2; c++) { + ray_t* v = ray_vec_from_raw(RAY_I64, small, 3); + t = ray_table_add_col(t, ray_sym_intern(c ? "b" : "a", 1), v); + ray_release(v); + } + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, sd, yp, RAY_COMPRESS_OFF), RAY_OK); + ray_release(t); + t = store_cancel_table(); + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "build", 1), 0); + ray_err_t e = ray_splay_save_mode(t, sd, yp, RAY_COMPRESS_OFF); + unsetenv("RAY_HASH_INJECT"); + bool cancelled = ray_interrupted(); + ray_clear_interrupt(); + ray_release(t); + TEST_ASSERT_TRUE(cancelled); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + ray_t* back = ray_read_splayed(sd, yp); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_EQ_I(ray_table_nrows(back), 3); + ray_release(back); + (void)ray_test_rm_rf(sd); + char schema[240], keep[240], col[240]; + snprintf(schema, sizeof(schema), "%s/.d", sd); + snprintf(keep, sizeof(keep), "%s/keep.txt", sd); + snprintf(col, sizeof(col), "%s/a", sd); + t = store_cancel_table(); + for (int premade = 0; premade < 2; premade++) { + if (premade) { + TEST_ASSERT_EQ_I(ray_test_mkdir_p(sd), 0); + FILE* f = fopen(keep, "w"); TEST_ASSERT_NOT_NULL(f); fputs("foreign\n", f); fclose(f); + } + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "build", 1), 0); + e = ray_splay_save_mode(t, sd, yp, RAY_COMPRESS_OFF); + unsetenv("RAY_HASH_INJECT"); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + TEST_ASSERT_TRUE(access(schema, F_OK) != 0); + TEST_ASSERT_TRUE(access(col, F_OK) != 0); + TEST_ASSERT_TRUE(premade ? access(keep, F_OK) == 0 : access(sd, F_OK) != 0); + } + ray_release(t); + (void)ray_test_rm_rf(dir); + PASS(); +#else + SKIP("needs a debug build on Linux"); +#endif +} + +/* The same cancel skips the dispatch that persists the deferred zones: + * what it would have written is released, not left behind a save. */ +static test_result_t test_splay_save_cancel_leaks(void) { +#if defined(DEBUG) && defined(RAY_OS_LINUX) + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-save-cleak-%d", (int)getpid()); + (void)ray_test_rm_rf(dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + if (!store_in_place(dir)) { (void)ray_test_rm_rf(dir); SKIP("no in-place build on this filesystem"); } + char sd[200]; snprintf(sd, sizeof(sd), "%s/t", dir); + char yp[220]; snprintf(yp, sizeof(yp), "%s/t.sym", dir); /* the SYM columns' symfile */ + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(2), RAY_OK); /* one worker */ + ray_t* t = store_cancel_table(); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, sd, yp, RAY_COMPRESS_OFF), RAY_OK); + size_t base = 0; + int bad = 0; + for (int k = 0; k < 5; k++) { + TEST_ASSERT_EQ_I(setenv("RAY_HASH_INJECT", "build", 1), 0); + if (ray_splay_save_mode(t, sd, yp, RAY_COMPRESS_OFF) != RAY_ERR_CANCEL) bad++; + unsetenv("RAY_HASH_INJECT"); + ray_clear_interrupt(); + ray_mem_stats_t st; ray_mem_stats(&st); + if (k == 1) base = st.bytes_allocated; + if (k == 4 && st.bytes_allocated > base + 256) { + fprintf(stderr, " save_cancel_leaks heap %+lld B\n", + (long long)st.bytes_allocated - (long long)base); + bad++; + } + } + ray_release(t); + ray_pool_destroy(); + (void)ray_test_rm_rf(dir); + TEST_ASSERT_EQ_I(bad, 0); + PASS(); +#else + SKIP("needs a debug build on Linux"); +#endif +} + /* The marker goes on last: a process that ends with the whole region * written but before the marker (debug builds end it right there, in a - * child) leaves a file that does not claim an index. The column is under + * child) leaves a file that does not claim an index: it loads as the plain + * column. The column is under * the parallel threshold: the child has no pool workers. */ static test_result_t test_col_build_hash_index_marker_last(void) { #if defined(DEBUG) && defined(RAY_OS_LINUX) @@ -2744,9 +2959,12 @@ static test_result_t test_col_build_hash_index_marker_last(void) { TEST_ASSERT_EQ_I((int64_t)fread(&mr, 1, 4, f), 4); fclose(f); TEST_ASSERT_TRUE(mr != 0); /* the finished file's marker */ TEST_ASSERT_TRUE(mp != mr); - ray_t* back = ray_col_mmap(p); /* longer than its payload, unclaimed: refused */ - TEST_ASSERT_TRUE(back && RAY_IS_ERR(back)); - ray_error_free(back); + ray_t* back = ray_col_mmap(p); /* the unclaimed region is not read: the plain column */ + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_FALSE(back->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_EQ_I(back->len, v->len); + TEST_ASSERT_TRUE(memcmp(ray_data(back), ray_data(v), (size_t)v->len * 8) == 0); + ray_release(back); ray_release(v); (void)ray_test_rm_rf(dir); PASS(); @@ -2859,13 +3077,569 @@ static test_result_t test_col_build_hash_index_interrupt(void) { PASS(); } -/* Wave width of the hash phase: a pure function of RAM budget and shape. */ -static test_result_t test_stream_hash_wave(void) { - TEST_ASSERT_EQ_I(ray_col_stream_hash_wave(0, 100, 5), 1); - TEST_ASSERT_EQ_I(ray_col_stream_hash_wave(1LL << 30, 0, 5), 5); - TEST_ASSERT_EQ_I(ray_col_stream_hash_wave(1LL << 30, 1LL << 40, 5), 1); - TEST_ASSERT_EQ_I(ray_col_stream_hash_wave(1LL << 40, 1000, 3), 3); - TEST_ASSERT_EQ_I(ray_col_stream_hash_wave(4LL * 58 * 1000 * 2, 1000, 5), 2); +/* A column carrying a HASH (as an older converter's store did) keeps it + * through a load and a resave that requests no index: the save cannot tell + * it from an explicit .idx.hash. Generation 0 is pinned (compress off). */ +static int store_slot_kind(ray_t* t, int64_t c) { + ray_col_meta_t m; + return ray_table_col_meta_idx(t, c, &m) ? (int)m.index_kind : -1; +} +static test_result_t test_resave_keeps_hash(void) { + char dirs[2][160]; + snprintf(dirs[0], sizeof(dirs[0]), "%s", ray_test_tmp("/tmp/rayforce-resave-hash0")); + snprintf(dirs[1], sizeof(dirs[1]), "%s", ray_test_tmp("/tmp/rayforce-resave-hash1")); + for (int i = 0; i < 2; i++) (void)ray_test_rm_rf(dirs[i]); + int64_t n = 300000; + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = (i * 7919) % 1000003; + ray_t* h = ray_idx_hash_fn(v); + ray_release(v); + TEST_ASSERT_TRUE(h && !RAY_IS_ERR(h) && (h->attrs & RAY_ATTR_HAS_INDEX)); + ray_t* t = ray_table_new(1); + t = ray_table_add_col(t, ray_sym_intern("u", 1), h); + ray_release(h); + TEST_ASSERT_EQ_I(ray_splay_save_mode(t, dirs[0], NULL, RAY_COMPRESS_OFF), RAY_OK); + ray_release(t); + ray_t* a = ray_read_splayed(dirs[0], NULL); + TEST_ASSERT_TRUE(a && !RAY_IS_ERR(a)); + TEST_ASSERT_EQ_I(store_slot_kind(a, 0), RAY_IDX_HASH); + TEST_ASSERT_EQ_I(ray_splay_save_mode(a, dirs[1], NULL, RAY_COMPRESS_OFF), RAY_OK); + ray_release(a); + ray_t* b = ray_read_splayed(dirs[1], NULL); + TEST_ASSERT_TRUE(b && !RAY_IS_ERR(b)); + TEST_ASSERT_EQ_I(store_slot_kind(b, 0), RAY_IDX_HASH); + ray_release(b); + for (int i = 0; i < 2; i++) (void)ray_test_rm_rf(dirs[i]); + PASS(); +} + +/* ---- lazy in-memory HASH (index policy PI Task 4) ------------------------ + * A converted table persists a CHUNK_ZONE, not a HASH. An equality or `in` + * probe on an integer column whose zone cannot prune builds a HASH in + * memory on first use, held in a process-wide cache that the save path never + * sees. Generation 2 is covered too (Ruling C1): the hash is built from the + * materialized plain column and dropped with the encoded object. Every + * path goes through ray_test_tmp; these run in the equivalence pass as well, + * where lz_make's save is generation 2. */ +static ray_runtime_t* g_lzrt; +static void lz_setup(void) { + g_lzrt = ray_runtime_create(0, NULL); + (void)ray_test_rm_rf(ray_test_tmp("/tmp/rayforce_lazy")); +} +static void lz_teardown(void) { + ray_idx_lazy_test_fail_build(NULL); + ray_idx_lazy_clear(); + (void)ray_test_rm_rf(ray_test_tmp("/tmp/rayforce_lazy")); + ray_runtime_destroy(g_lzrt); +} +static void lz_ok(const char* src) { + ray_t* r = ray_eval_str(ray_test_tmp(src)); + if (r && RAY_IS_ERR(r)) { fprintf(stderr, "%s: %s\n", src, ray_error_msg()); ray_error_free(r); abort(); } + if (r) ray_release(r); +} +static ray_t* lz_eval(const char* src) { return ray_eval_str(ray_test_tmp(src)); } +/* A converted-like table: an unclustered I64 column h of 300000 rows whose + * file carries a CHUNK_ZONE only (what the converters write), beside a + * clustered one v. `opts` is appended to the save (generation choice). */ +static void lz_make_opts(const char* opts) { + char src[256]; + lz_ok("(set i (til 300000))"); + snprintf(src, sizeof src, + "(.db.splayed.set \"/tmp/rayforce_lazy/a/\" (table [h v] (list (%% (* i 7919) 1000003) i))%s)", opts); + lz_ok(src); + lz_ok("(set A (.db.splayed.get \"/tmp/rayforce_lazy/a/\"))"); +} +static void lz_make(void) { lz_make_opts(""); } +/* The table slot's recorded index kind, never decoding (metadata). */ +static int lz_slot_kind(const char* var, const char* col, ray_t** enc_out) { + ray_t* t = ray_env_get(ray_sym_intern(var, strlen(var))); + ray_col_meta_t m; + int64_t c = -1; + for (int64_t k = 0; t && k < ray_table_ncols(t); k++) + if (ray_table_col_name(t, k) == ray_sym_intern(col, strlen(col))) c = k; + if (c < 0 || !ray_table_col_meta_idx(t, c, &m)) return -1; + if (enc_out) *enc_out = m.enc; + return (int)m.index_kind; +} + +/* Run the point lookup (== h 7919) on `var` n times; true when every + * answer is the one row v = 1. */ +static bool lz_probe_n(const char* var, int n) { + char src[128]; + snprintf(src, sizeof src, "(at (select {v: v from: %s where: (== h 7919)}) 'v)", var); + for (int k = 0; k < n; k++) { + ray_t* r = lz_eval(src); + bool ok = r && !RAY_IS_ERR(r) && r->len == 1 && ((int64_t*)ray_data(r))[0] == 1; + if (r && RAY_IS_ERR(r)) ray_error_free(r); else if (r) ray_release(r); + if (!ok) return false; + } + return true; +} +/* The table column var.col (borrowed: the table holds it). */ +static ray_t* lz_col(const char* var, const char* col) { + ray_t* t = ray_env_get(ray_sym_intern(var, strlen(var))); + ray_t* c = t ? ray_table_col(t, ray_sym_intern(col, strlen(col))) : NULL; + return c && !RAY_IS_ERR(c) ? c : NULL; +} + +/* The first RAY_IDX_LAZY_BUILD_PROBES - 1 probes scan (their rows are + * counted, nothing is built); the next one builds, and later probes reuse it. + * Every answer is the same. */ +static test_result_t test_lazy_first_use(void) { + lz_make(); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + lz_ok("(do (.idx.uses A) null)"); + for (int k = 1; k < RAY_IDX_LAZY_BUILD_PROBES; k++) { + TEST_ASSERT_TRUE(lz_probe_n("A", 1)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "h")), (int64_t)k * 300000); + } + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), 0); + ray_t* u = lz_eval("(.idx.uses A)"); + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u) && ray_dict_len(u) == 0); /* the scans used no index */ + ray_release(u); + TEST_ASSERT_TRUE(lz_probe_n("A", 1)); /* this one builds */ + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "h")), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), 300000LL * (8 + 58)); + u = lz_eval("(at (.idx.uses A) 'h)"); + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u) && u->i64 == 1); /* attributed to the column */ + ray_release(u); + ray_t* r = lz_eval("(at (select {v: v from: A where: (in h [7919 15838])}) 'v)"); /* rows 1 and 2 */ + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->len == 2 && + ((int64_t*)ray_data(r))[0] == 1 && ((int64_t*)ray_data(r))[1] == 2); + ray_release(r); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); /* reused, not rebuilt */ + u = lz_eval("(at (.idx.uses A) 'h)"); + TEST_ASSERT_TRUE(u && !RAY_IS_ERR(u) && u->i64 == 1); /* the in probe used it */ + ray_release(u); + /* the table's column is untouched: its slot records a zone, as does the + * column a reader gets */ + TEST_ASSERT_EQ_I(lz_slot_kind("A", "h", NULL), RAY_IDX_CHUNK_ZONE); + ray_t* k = lz_eval("(at (.idx.info (at A 'h)) 'kind)"); + TEST_ASSERT_TRUE(k && !RAY_IS_ERR(k) && k->i64 == ray_sym_intern("chunk_zone", 10)); + ray_release(k); + PASS(); +} + +/* One unsplit AND (a graph run without the optimizer): (== h 15838) + * (>= v 0) (<= v hi) over A; the rows, which hold row 2 alone. */ +static ray_t* lz_eq_range(ray_t* tbl, int64_t hi) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* pred = ray_and(g, ray_and(g, ray_eq(g, ray_scan(g, "h"), ray_const_i64(g, 15838)), + ray_ge(g, ray_scan(g, "v"), ray_const_i64(g, 0))), + ray_le(g, ray_scan(g, "v"), ray_const_i64(g, hi))); + ray_t* r = ray_execute(g, ray_filter(g, ray_const_table(g, tbl), pred)); + ray_graph_free(g); + return r; +} + +/* An eq-plus-range conjunction (an unsplit AND: a graph run without the + * optimizer) probes the lazy hash for its equality. The range keeps + * every row: a range that keeps only a few chunks of a generation-2 v + * prunes the chain from v's chunk statistics first (exec_filter_chain_prune) + * and answers the same rows by its scan. */ +static test_result_t test_lazy_eq_range(void) { + lz_make(); + ray_t* tbl = ray_env_get(ray_sym_intern("A", 1)); + TEST_ASSERT_TRUE(tbl && tbl->type == RAY_TABLE); + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES - 1)); /* scans: pending */ + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + uint64_t hits0 = ray_idx_hits[IDX_SITE_FILTER_EQRANGE]; + for (int pass = 0; pass < 2; pass++) { + ray_t* r = lz_eq_range(tbl, pass ? 5 : 300000); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->type == RAY_TABLE && ray_table_nrows(r) == 1); + ray_t* v = ray_table_col(r, ray_sym_intern("v", 1)); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v) && ((int64_t*)ray_data(v))[0] == 2); + ray_release(r); + if (!pass) { + TEST_ASSERT_EQ_I(ray_idx_hits[IDX_SITE_FILTER_EQRANGE], hits0 + 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + } + } + PASS(); +} + +/* Never persisted: a resave of the probed table records a zone, not a hash. */ +static test_result_t test_lazy_not_persisted(void) { + lz_make(); + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + lz_ok("(.db.splayed.set \"/tmp/rayforce_lazy/b/\" A)"); + lz_ok("(set B (.db.splayed.get \"/tmp/rayforce_lazy/b/\"))"); + TEST_ASSERT_EQ_I(lz_slot_kind("B", "h", NULL), RAY_IDX_CHUNK_ZONE); + ray_t* k = lz_eval("(at (.idx.info (at B 'h)) 'kind)"); + TEST_ASSERT_TRUE(k && !RAY_IS_ERR(k) && k->i64 == ray_sym_intern("chunk_zone", 10)); + ray_release(k); + PASS(); +} + +/* The RAM budget bounds it: below the cost nothing is built, results equal, + * and the decline is remembered for the column (no retry per query). */ +static test_result_t test_lazy_budget(void) { + lz_make(); + int64_t saved = __RUNTIME->ram_limit; + __RUNTIME->ram_limit = 4LL * (8 + 58) * 300000 - 1; /* one byte below the bound */ + ray_t* r = lz_eval("(at (select {v: v from: A where: (== h 7919)}) 'v)"); + __RUNTIME->ram_limit = saved; + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->len == 1 && ((int64_t*)ray_data(r))[0] == 1); + ray_release(r); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "h")), -1); /* declined */ + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES)); /* budget back: declined stays */ + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + PASS(); +} + +/* A clustered column (zone pruning works) gets no lazy index, and neither + * does a query that is not a point lookup. */ +static test_result_t test_lazy_not_wanted(void) { + lz_make(); + for (int k = 0; k < RAY_IDX_LAZY_BUILD_PROBES; k++) lz_ok("(select {h: h from: A where: (== v 7919)})"); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "v")), -1); /* not even pending */ + lz_ok("(select {h: h from: A where: (> h 7919)})"); + lz_ok("(select {s: (sum h) from: A})"); + lz_ok("(select {c: (count v) from: A by: h})"); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + PASS(); +} + +/* A key outside the column's zone range matches nothing: the zone answers, + * no scan work is counted and nothing is built, however often it is asked. + * An `in` set wholly outside the range likewise; one in range scans. */ +static test_result_t lazy_out_of_range(const char* opts) { + lz_make_opts(opts); + uint64_t z0 = ray_idx_hits[IDX_SITE_FILTER_ZONE]; + for (int k = 0; k < RAY_IDX_LAZY_BUILD_PROBES + 1; k++) { + ray_t* r = lz_eval("(count (select {v: v from: A where: (== h 2000000)}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 0); + ray_release(r); + r = lz_eval("(count (select {v: v from: A where: (in h [2000000 -5])}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 0); + ray_release(r); + } + TEST_ASSERT_EQ_I(ray_idx_hits[IDX_SITE_FILTER_ZONE], z0 + 2 * (RAY_IDX_LAZY_BUILD_PROBES + 1)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "h")), -1); + /* in range: 0 is row 0 */ + ray_t* r = lz_eval("(at (select {v: v from: A where: (== h 0)}) 'v)"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->len == 1 && ((int64_t*)ray_data(r))[0] == 0); + ray_release(r); + r = lz_eval("(count (select {v: v from: A where: (in h [2000000 7919])}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 1); + ray_release(r); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "h")), 2 * 300000); /* both scanned */ + PASS(); +} +static test_result_t test_lazy_out_of_range(void) { return lazy_out_of_range(""); } +static test_result_t test_lazy_out_of_range_gen2(void) { return lazy_out_of_range(" {compress: true}"); } + +/* Mappings of files under the lazy tests' root that were unlinked: a + * pruned store generation some object still pins. 0 off Linux. */ +static int lz_deleted_mappings(void) { + int n = 0; +#ifdef __linux__ + FILE* f = fopen("/proc/self/maps", "r"); + if (!f) return 0; + char line[1024]; + const char* root = ray_test_tmp("/tmp/rayforce_lazy"); + while (fgets(line, sizeof line, f)) + if (strstr(line, root) && strstr(line, "(deleted)")) n++; + fclose(f); +#endif + return n; +} + +/* A table reloaded per request (a server re-reading a store after each + * publish) leaves its old column to the cache alone: that entry is dropped + * on the next probe, so the cache holds one entry, the heap and the mapped + * bytes stay flat, and the pruned generations' files are not pinned. */ +static test_result_t test_lazy_reload_bounded(void) { + lz_make(); + ray_mem_stats_t st; + size_t mapped1 = 0, alloc1 = 0; + for (int round = 0; round < 3; round++) { + if (round) { + lz_ok("(.db.splayed.set \"/tmp/rayforce_lazy/a/\" A)"); /* a new generation */ + lz_ok("(set A (.db.splayed.get \"/tmp/rayforce_lazy/a/\"))"); + } + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), 300000LL * (8 + 58)); + ray_mem_stats(&st); + if (round == 0) { mapped1 = st.sys_mapped; alloc1 = st.bytes_allocated; } + } + TEST_ASSERT_FMT(st.sys_mapped <= mapped1, "mapped %zu after 3 loads, %zu after 1", st.sys_mapped, mapped1); + TEST_ASSERT_FMT(st.bytes_allocated <= alloc1 + (1u << 20), "heap %zu after 3 loads, %zu after 1", + st.bytes_allocated, alloc1); + TEST_ASSERT_EQ_I(lz_deleted_mappings(), 0); + /* the table goes: its entry goes with the next probe of any column */ + lz_ok("(set A null)"); + ray_t* other = ray_vec_new(RAY_I64, 1); + other->len = 1; ((int64_t*)ray_data(other))[0] = 7; + ray_t* o = NULL; + TEST_ASSERT_NULL(ray_idx_lazy_hash(other, &o)); + TEST_ASSERT_NULL(o); + ray_release(other); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), 0); + TEST_ASSERT_EQ_I(lz_deleted_mappings(), 0); + PASS(); +} + +/* The filter's answer `sel` equals the scan oracle `orc` (a vector + * expression that no filter-index site sees): same length, same I64 values. */ +static bool lz_same(const char* sel, const char* orc) { + ray_t* a = lz_eval(sel); + ray_t* b = lz_eval(orc); + bool ok = a && b && !RAY_IS_ERR(a) && !RAY_IS_ERR(b) && a->len == b->len && + ray_elem_size(a->type) == 8 && ray_elem_size(b->type) == 8 && + memcmp(ray_data(a), ray_data(b), (size_t)a->len * 8) == 0; + if (!ok) fprintf(stderr, "lz_same: %s vs %s\n", sel, orc); + if (a && RAY_IS_ERR(a)) ray_error_free(a); else if (a) ray_release(a); + if (b && RAY_IS_ERR(b)) ray_error_free(b); else if (b) ray_release(b); + return ok; +} + +/* TIMESTAMP, the other 8-byte type the cost test admits, waits and builds + * like I64; equality and `in` answer the scan's rows throughout. */ +static test_result_t test_lazy_timestamp(void) { + lz_ok("(set i (til 300000))"); + lz_ok("(.db.splayed.set \"/tmp/rayforce_lazy/ts/\" (table [t v] (list (+ 2020.01.01D00:00:00.000000000 (% (* i 7919) 1000003)) i)))"); + lz_ok("(set T (.db.splayed.get \"/tmp/rayforce_lazy/ts/\"))"); + ray_t* tc = lz_col("T", "t"); + TEST_ASSERT_TRUE(tc && tc->type == RAY_TIMESTAMP && ray_index_kind(tc) == RAY_IDX_CHUNK_ZONE); + const char* sel = "(at (select {v: v from: T where: (== t 2020.01.01D00:00:00.000007919)}) 'v)"; + const char* orc = "(at (at T 'v) (where (== (at T 't) 2020.01.01D00:00:00.000007919)))"; + for (int k = 1; k < RAY_IDX_LAZY_BUILD_PROBES; k++) { + TEST_ASSERT_TRUE(lz_same(sel, orc)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + } + TEST_ASSERT_TRUE(lz_same(sel, orc)); /* builds */ + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + TEST_ASSERT_TRUE(lz_same(sel, orc)); + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: T where: (in t [2020.01.01D00:00:00.000007919 2020.01.01D00:00:00.000015838])}) 'v)", + "(at (at T 'v) (where (in (at T 't) [2020.01.01D00:00:00.000007919 2020.01.01D00:00:00.000015838])))")); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + PASS(); +} + +/* A column with nulls never builds (the probe sites gate on nulls): the + * scan answers every time and no work is counted. */ +static test_result_t test_lazy_nulls_never(void) { + lz_ok("(set i (til 300000))"); + lz_ok("(.db.splayed.set \"/tmp/rayforce_lazy/n/\" (table [h v] (list (concat [0Nl] (% (* (til 299999) 7919) 1000003)) i)))"); + lz_ok("(set N (.db.splayed.get \"/tmp/rayforce_lazy/n/\"))"); + TEST_ASSERT_TRUE(ray_vec_may_have_nulls(lz_col("N", "h"))); + for (int k = 0; k < RAY_IDX_LAZY_BUILD_PROBES + 1; k++) { + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: N where: (== h 7919)}) 'v)", + "(at (at N 'v) (where (== (at N 'h) 7919)))")); + if (k % 16 == 0) + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: N where: (in h [7919 15838])}) 'v)", + "(at (at N 'v) (where (in (at N 'h) [7919 15838])))")); + } + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 0); + PASS(); +} + +/* A slice of the table and a filtered sub-table carry no chunk zone of the + * column: never built, never pending, answers equal the scan's. */ +static test_result_t test_lazy_derived_never(void) { + lz_make(); + lz_ok("(set S (take A 200000))"); + lz_ok("(set F (select {from: A where: (< v 200000)}))"); + for (int k = 0; k < RAY_IDX_LAZY_BUILD_PROBES + 1; k++) { + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: S where: (== h 7919)}) 'v)", + "(at (at S 'v) (where (== (at S 'h) 7919)))")); + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: F where: (== h 7919)}) 'v)", + "(at (at F 'v) (where (== (at F 'h) 7919)))")); + } + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_entries(), 0); + PASS(); +} + +/* After an update (to a new table or in place) and an insert, the filter + * answers the changed rows: the cached copy of the old column is never + * served for the new one. */ +static test_result_t test_lazy_after_mutation(void) { + lz_make(); + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + lz_ok("(set A2 (update {h: 7919 where: (== v 5) from: A}))"); + for (int k = 0; k < RAY_IDX_LAZY_BUILD_PROBES + 1; k++) + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: A2 where: (== h 7919)}) 'v)", + "(at (at A2 'v) (where (== (at A2 'h) 7919)))")); + TEST_ASSERT_TRUE(lz_probe_n("A", 1)); /* A itself unchanged */ + lz_ok("(update {h: 7919 where: (== v 6) from: 'A})"); + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: A where: (== h 7919)}) 'v)", + "(at (at A 'v) (where (== (at A 'h) 7919)))")); + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: A where: (in h [7919 15838])}) 'v)", + "(at (at A 'v) (where (in (at A 'h) [7919 15838])))")); + ray_t* r = lz_eval("(count (select {v: v from: A where: (== h 7919)}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 2); /* rows 1 and 6 */ + ray_release(r); + lz_ok("(insert 'A (list 7919 300000))"); + TEST_ASSERT_TRUE(lz_same("(at (select {v: v from: A where: (== h 7919)}) 'v)", + "(at (at A 'v) (where (== (at A 'h) 7919)))")); + r = lz_eval("(count (select {v: v from: A where: (== h 7919)}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 3); /* and the inserted row */ + ray_release(r); + PASS(); +} + +/* Generation 2: the hash comes from the materialized column, the slot keeps + * its encoded object and zone, and the entry goes with the object. */ +static test_result_t test_lazy_gen2(void) { + lz_make_opts(" {compress: true}"); + ray_t* enc = NULL; + TEST_ASSERT_EQ_I(lz_slot_kind("A", "h", &enc), RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_NOT_NULL(enc); /* generation 2 */ + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES - 1)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_TRUE(lz_probe_n("A", 1)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + ray_t* r = lz_eval("(count (select {v: v from: A where: (in h [7919 15838 3])}))"); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r) && r->i64 == 2); + ray_release(r); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + enc = NULL; + TEST_ASSERT_EQ_I(lz_slot_kind("A", "h", &enc), RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_NOT_NULL(enc); /* still encoded */ + lz_ok("(.db.splayed.set \"/tmp/rayforce_lazy/b/\" A)"); + lz_ok("(set B (.db.splayed.get \"/tmp/rayforce_lazy/b/\"))"); + TEST_ASSERT_EQ_I(lz_slot_kind("B", "h", NULL), RAY_IDX_CHUNK_ZONE); + lz_ok("(set B null)"); + lz_ok("(set A null)"); /* the object goes: so does its entry */ + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), 0); + PASS(); +} + +/* A wanted column of n rows with a chunk zone of 4096-row chunks (owned). */ +static ray_t* lz_zoned_vec(int64_t n, int64_t salt) { + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = ((i + salt) * 7919) % 1000003; + ray_t* z = ray_index_attach_chunk_zone(&v, 12); + (void)z; + return v; +} + +/* Memos (pending or declined columns) never push out a built index: with + * every slot taken, the oldest memo goes first. */ +static test_result_t test_lazy_memo_evicts_memo(void) { + ray_t* b = lz_zoned_vec(50000, 0); + TEST_ASSERT_TRUE(ray_idx_lazy_hash_wanted(b)); + ray_t* o = NULL; + for (int k = 0; k < RAY_IDX_LAZY_BUILD_PROBES; k++) { + if (o) ray_release(o); + o = NULL; + TEST_ASSERT_NULL(ray_idx_lazy_hash(b, &o)); + } + TEST_ASSERT_NOT_NULL(o); /* built */ + ray_release(o); + ray_t* m[80]; + for (int k = 0; k < 80; k++) { /* more memos than slots */ + m[k] = lz_zoned_vec(50000, k + 1); + ray_t* mo = NULL; + TEST_ASSERT_NULL(ray_idx_lazy_hash(m[k], &mo)); + TEST_ASSERT_NULL(mo); /* pending */ + } + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + ray_t* lk = ray_idx_lazy_lookup(b); + TEST_ASSERT_NOT_NULL(lk); + ray_release(lk); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(m[0]), -1); /* the oldest memo went */ + TEST_ASSERT_EQ_I(ray_idx_lazy_work(m[79]), 50000); + ray_idx_lazy_clear(); + for (int k = 0; k < 80; k++) ray_release(m[k]); + ray_release(b); + PASS(); +} + +/* An interrupted build cancels the query (it does not go on to scan) and is + * not remembered against the column: the next probe builds. A build that + * runs out of memory is best effort: the scan answers and the column is + * declined. */ +static test_result_t test_lazy_cancel(void) { + lz_make(); + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES - 1)); + ray_idx_lazy_test_fail_build("cancel"); + ray_t* r = lz_eval("(select {v: v from: A where: (== h 7919)})"); + ray_idx_lazy_test_fail_build(NULL); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_STR_EQ(ray_err_code(r), "cancel"); + ray_error_free(r); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_TRUE(ray_idx_lazy_work(lz_col("A", "h")) > 0); /* still pending */ + TEST_ASSERT_TRUE(lz_probe_n("A", 1)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + PASS(); +} +static test_result_t test_lazy_oom(void) { + lz_make(); + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES - 1)); + ray_idx_lazy_test_fail_build("oom"); + bool ok = lz_probe_n("A", 1); /* the scan answers */ + ray_idx_lazy_test_fail_build(NULL); + TEST_ASSERT_TRUE(ok); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + TEST_ASSERT_EQ_I(ray_idx_lazy_work(lz_col("A", "h")), -1); /* declined */ + TEST_ASSERT_TRUE(lz_probe_n("A", RAY_IDX_LAZY_BUILD_PROBES)); + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 0); + PASS(); +} + +/* Two threads probing the same column at once keep one hash: the loser of + * the build race finds the winner's entry under the lock and drops its own. */ +typedef struct { ray_t* col; _Atomic int* go; ray_t* out; ray_t* err; } lz_thr_t; +static void lz_probe_thread(void* raw) { + lz_thr_t* t = raw; + ray_rc_sync = true; /* shared objects: atomic counts, as a worker */ + atomic_fetch_add(t->go, 1); + while (atomic_load(t->go) < 2) { } + t->err = ray_idx_lazy_hash(t->col, &t->out); + if (t->err) { ray_error_free(t->err); t->err = (ray_t*)1; } + ray_heap_abandon(); +} +static test_result_t test_lazy_concurrent(void) { + int64_t n = 50000; /* below the parallel build: no pool */ + ray_t* v = ray_vec_new(RAY_I64, n); v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = (i * 7919) % 1000003; + ray_t* z = ray_index_attach_chunk_zone(&v, 12); /* 13 chunks of 4096 rows */ + TEST_ASSERT_FALSE(RAY_IS_ERR(z)); + TEST_ASSERT_TRUE(ray_idx_lazy_hash_wanted(v)); + for (int round = 0; round < 8; round++) { + ray_idx_lazy_clear(); + for (int k = 1; k < RAY_IDX_LAZY_BUILD_PROBES; k++) { /* pending: the scans' work */ + ray_t* o = NULL; + TEST_ASSERT_NULL(ray_idx_lazy_hash(v, &o)); + TEST_ASSERT_NULL(o); + } + _Atomic int go = 0; + lz_thr_t t[2]; ray_thread_t th[2]; + for (int k = 0; k < 2; k++) { + t[k] = (lz_thr_t){ .col = v, .go = &go, .out = NULL, .err = NULL }; + TEST_ASSERT_EQ_I(ray_thread_create(&th[k], lz_probe_thread, &t[k]), RAY_OK); + } + for (int k = 0; k < 2; k++) ray_thread_join(th[k]); + TEST_ASSERT_TRUE(!t[0].err && !t[1].err && t[0].out && t[1].out); + TEST_ASSERT_EQ_PTR(t[0].out, t[1].out); /* one indexed copy */ + TEST_ASSERT_EQ_I(ray_idx_lazy_count(), 1); + TEST_ASSERT_EQ_I(ray_idx_lazy_bytes(), n * (8 + 58)); + ray_t* lk = ray_idx_lazy_lookup(v); /* retained */ + TEST_ASSERT_EQ_PTR(lk, t[0].out); + ray_release(lk); + TEST_ASSERT_EQ_I(ray_index_kind(t[0].out), RAY_IDX_HASH); + TEST_ASSERT_EQ_I(ray_index_kind(v), RAY_IDX_CHUNK_ZONE); /* the column is untouched */ + ray_release(t[0].out); ray_release(t[1].out); + } + ray_idx_lazy_clear(); + ray_release(v); PASS(); } @@ -2965,7 +3739,7 @@ static test_result_t test_stream_finish_failure_publishes_nothing(void) { ray_t* b = ray_vec_new(RAY_I64, n); b->len = n; for (int64_t i = 0; i < n; i++) { ((int64_t*)ray_data(a))[i] = i; - ((int64_t*)ray_data(b))[i] = (i * 7919) % 1000003; /* a hash candidate */ + ((int64_t*)ray_data(b))[i] = (i * 7919) % 1000003; /* unclustered */ } ray_t* s = dict_test_col(100000, 3000, false); ray_t* cols[3] = { a, b, s }; @@ -2973,7 +3747,7 @@ static test_result_t test_stream_finish_failure_publishes_nothing(void) { const char* names[3] = { "fa", "fb", "fs" }; ray_col_stream_t w[3]; for (int c = 0; c < 3; c++) { - TEST_ASSERT_EQ_I(ray_col_stream_open(&w[c], dir, ray_sym_intern(names[c], 2), types[c], NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w[c], dir, ray_sym_intern(names[c], 2), types[c], NULL, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w[c], 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w[c], cols[c]), RAY_OK); } @@ -2985,7 +3759,6 @@ static test_result_t test_stream_finish_failure_publishes_nothing(void) { for (int c = 0; c < 3; c++) { char path[200]; snprintf(path, sizeof(path), "%s/%s", dir, names[c]); TEST_ASSERT_TRUE(access(path, F_OK) != 0); - TEST_ASSERT_NULL(w[c].index); ray_col_stream_abort(&w[c]); /* converters abort after a failed close */ } TEST_ASSERT_FALSE(stream_dir_has_tmp(dir)); @@ -2994,6 +3767,44 @@ static test_result_t test_stream_finish_failure_publishes_nothing(void) { PASS(); } +/* A cancelled pool retires the finish tasks it has not run: close_all + * reports the cancellation and publishes nothing (it used to return OK with + * every column file missing), and publish refuses a writer whose finish + * never ran. Deterministic: the cancel flag is up before the dispatch, so + * the pool skips every task. */ +static test_result_t test_stream_cancel_publishes_nothing(void) { + ray_pool_t* pool = ray_pool_get(); + if (!ray_pool_par_dispatch_ok(pool, 3, 2)) SKIP("needs a worker pool"); + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-cancel-%d", (int)getpid()); + (void)ray_test_rm_rf(dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + int64_t n = 70000; + ray_t* a = ray_vec_new(RAY_I64, n); a->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(a))[i] = i * 3; + const char* names[3] = { "ca", "cb", "cc" }; + uint8_t gens[3] = { 0, 2, 0 }; + ray_col_stream_t w[3]; + for (int c = 0; c < 3; c++) { + TEST_ASSERT_EQ_I(ray_col_stream_open(&w[c], dir, ray_sym_intern(names[c], 2), RAY_I64, NULL, gens[c]), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w[c], a), RAY_OK); + } + /* an open writer: publish refuses, the staging file stays private */ + TEST_ASSERT_EQ_I(ray_col_stream_publish(&w[0], false), RAY_ERR_DOMAIN); + ray_request_interrupt(); + ray_err_t e = ray_col_stream_close_all(w, 3, false, NULL); + ray_clear_interrupt(); + TEST_ASSERT_EQ_I(e, RAY_ERR_CANCEL); + for (int c = 0; c < 3; c++) { + char path[200]; snprintf(path, sizeof(path), "%s/%s", dir, names[c]); + TEST_ASSERT_TRUE(access(path, F_OK) != 0); + ray_col_stream_abort(&w[c]); + } + TEST_ASSERT_FALSE(stream_dir_has_tmp(dir)); + ray_release(a); + (void)ray_test_rm_rf(dir); + PASS(); +} + /* STR column of 100000 rows with empty strings: inline dict, HAS_NULLS set. */ static test_result_t test_stream_inline_dict(void) { char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-dict-%d", (int)getpid()); @@ -3001,7 +3812,7 @@ static test_result_t test_stream_inline_dict(void) { int64_t n = 100000; ray_t* v = dict_test_col(n, 3000, false); ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("s", 1), RAY_STR, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("s", 1), RAY_STR, NULL, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_index_begin(&w, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, v), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); @@ -3081,9 +3892,9 @@ static test_result_t test_file_rename_new_emulated(void) { /* ---- test_file_shared_lock_concurrent ---------------------------------- */ static test_result_t test_file_shared_lock_concurrent(void) { - unlink(TMP_FILEIO_PATH); - ray_fd_t fd1 = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_READ | RAY_OPEN_WRITE | RAY_OPEN_CREATE); - ray_fd_t fd2 = ray_file_open(TMP_FILEIO_PATH, RAY_OPEN_READ); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); + ray_fd_t fd1 = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_READ | RAY_OPEN_WRITE | RAY_OPEN_CREATE); + ray_fd_t fd2 = ray_file_open(ray_test_tmp(TMP_FILEIO_PATH), RAY_OPEN_READ); TEST_ASSERT((fd1) != (RAY_FD_INVALID), "fd1 != RAY_FD_INVALID"); TEST_ASSERT((fd2) != (RAY_FD_INVALID), "fd2 != RAY_FD_INVALID"); @@ -3097,7 +3908,7 @@ static test_result_t test_file_shared_lock_concurrent(void) { ray_file_unlock(fd2); ray_file_close(fd1); ray_file_close(fd2); - unlink(TMP_FILEIO_PATH); + unlink(ray_test_tmp(TMP_FILEIO_PATH)); PASS(); } @@ -3119,11 +3930,11 @@ static test_result_t test_sym_col_bounds_reject(void) { data[0] = 0; data[1] = 1; data[2] = 0; data[3] = 1; /* Save — should embed sym count in header rc field */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load back — should succeed since all indices < sym_count */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_SYM); @@ -3132,23 +3943,23 @@ static test_result_t test_sym_col_bounds_reject(void) { /* Now craft a column with an out-of-range index */ data[2] = (uint8_t)(sc + 10); /* beyond sym table */ - err = ray_col_save(vec, TMP_COL_PATH); + err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Load should fail with RAY_ERR_CORRUPT */ - ray_t* bad = ray_col_load(TMP_COL_PATH); + ray_t* bad = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); /* Same test via mmap */ - bad = ray_col_mmap(TMP_COL_PATH); + bad = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -3172,7 +3983,7 @@ static test_result_t test_sym_col_count_mismatch(void) { data[0] = 0; data[1] = 1; data[2] = 2; /* Save with current sym count */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); ray_release(vec); @@ -3185,18 +3996,18 @@ static test_result_t test_sym_col_count_mismatch(void) { TEST_ASSERT((new_sc) < (sc), "new_sc < sc"); /* Load should fail: saved sym count > current sym count (fast-reject) */ - ray_t* bad = ray_col_load(TMP_COL_PATH); + ray_t* bad = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); /* Same via mmap */ - bad = ray_col_mmap(TMP_COL_PATH); + bad = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -3221,10 +4032,10 @@ static test_result_t test_sym_col_valid_roundtrip(void) { data[4] = (uint16_t)id1; /* Save + load roundtrip */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_SYM); @@ -3241,7 +4052,7 @@ static test_result_t test_sym_col_valid_roundtrip(void) { ray_release(loaded); /* Save + mmap roundtrip */ - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->type, RAY_SYM); @@ -3253,7 +4064,7 @@ static test_result_t test_sym_col_valid_roundtrip(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -3263,8 +4074,8 @@ static test_result_t test_sym_col_valid_roundtrip(void) { #define TMP_SYM_PATH "/tmp/rayforce_test_splay_sym_file" static test_result_t test_splay_load_with_sym(void) { - (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); - unlink(TMP_SYM_PATH); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_SYM_DIR)); + unlink(ray_test_tmp(TMP_SYM_PATH)); /* Intern symbols and build a table with a RAY_SYM column */ int64_t id_name = ray_sym_intern("name", 4); @@ -3291,7 +4102,7 @@ static test_result_t test_splay_load_with_sym(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); /* Save splay + sym */ - ray_err_t err = ray_splay_save(tbl, TMP_SPLAY_SYM_DIR, TMP_SYM_PATH); + ray_err_t err = ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_SYM_DIR), ray_test_tmp(TMP_SYM_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Reset sym table, then load via ray_splay_load with sym_path */ @@ -3299,7 +4110,7 @@ static test_result_t test_splay_load_with_sym(void) { (void)ray_sym_init(); TEST_ASSERT_EQ_U(ray_sym_count(), 1); /* "" reserved */ - ray_t* loaded = ray_splay_load(TMP_SPLAY_SYM_DIR, TMP_SYM_PATH); + ray_t* loaded = ray_splay_load(ray_test_tmp(TMP_SPLAY_SYM_DIR), ray_test_tmp(TMP_SYM_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(ray_table_ncols(loaded), 2); @@ -3312,17 +4123,17 @@ static test_result_t test_splay_load_with_sym(void) { ray_release(col_name); ray_release(col_age); ray_release(tbl); - (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); - unlink(TMP_SYM_PATH); - unlink(TMP_SYM_PATH ".lk"); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_SYM_DIR)); + unlink(ray_test_tmp(TMP_SYM_PATH)); + unlink(ray_test_tmp(TMP_SYM_PATH ".lk")); PASS(); } /* ---- test_splay_load_sym_missing_corrupt ------------------------------- */ static test_result_t test_splay_load_sym_missing_corrupt(void) { - (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); - unlink(TMP_SYM_PATH); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_SYM_DIR)); + unlink(ray_test_tmp(TMP_SYM_PATH)); /* Intern symbols and build a table with a RAY_SYM column */ int64_t id_col = ray_sym_intern("scol", 4); @@ -3338,7 +4149,7 @@ static test_result_t test_splay_load_sym_missing_corrupt(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); /* Save splay + sym */ - ray_err_t err = ray_splay_save(tbl, TMP_SPLAY_SYM_DIR, TMP_SYM_PATH); + ray_err_t err = ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_SYM_DIR), ray_test_tmp(TMP_SYM_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Reset sym table — simulate loading without sym */ @@ -3351,23 +4162,23 @@ static test_result_t test_splay_load_sym_missing_corrupt(void) { * no resolvable domain must never resolve against incidental state * (sym-domain spec, Load §3; replaces the old validate_sym_columns * "corrupt" which keyed off the global table being empty). */ - ray_t* loaded = ray_splay_load(TMP_SPLAY_SYM_DIR, NULL); + ray_t* loaded = ray_splay_load(ray_test_tmp(TMP_SPLAY_SYM_DIR), NULL); TEST_ASSERT_TRUE(RAY_IS_ERR(loaded)); TEST_ASSERT_STR_EQ(ray_err_code(loaded), "sym"); ray_release(loaded); ray_release(col); ray_release(tbl); - (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); - unlink(TMP_SYM_PATH); - unlink(TMP_SYM_PATH ".lk"); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_SYM_DIR)); + unlink(ray_test_tmp(TMP_SYM_PATH)); + unlink(ray_test_tmp(TMP_SYM_PATH ".lk")); PASS(); } /* ---- test_read_splayed_bad_sym_fatal ----------------------------------- */ static test_result_t test_read_splayed_bad_sym_fatal(void) { - (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_SYM_DIR)); /* Build a simple table (no RAY_SYM columns needed) */ int64_t id_x = ray_sym_intern("x", 1); @@ -3377,7 +4188,7 @@ static test_result_t test_read_splayed_bad_sym_fatal(void) { tbl = ray_table_add_col(tbl, id_x, col_x); TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); - ray_err_t err = ray_splay_save(tbl, TMP_SPLAY_SYM_DIR, NULL); + ray_err_t err = ray_splay_save(tbl, ray_test_tmp(TMP_SPLAY_SYM_DIR), NULL); TEST_ASSERT_EQ_I(err, RAY_OK); /* ray_read_splayed with a nonexistent sym_path on a SYMBOL-FREE @@ -3386,7 +4197,7 @@ static test_result_t test_read_splayed_bad_sym_fatal(void) { * where the domain would live, not a promise it exists). The loud * "sym" error is reserved for actual SYM columns without a domain * (test_splay_load_sym_missing_corrupt above). */ - ray_t* loaded = ray_read_splayed(TMP_SPLAY_SYM_DIR, "/tmp/rayforce_nonexistent_sym_xyz"); + ray_t* loaded = ray_read_splayed(ray_test_tmp(TMP_SPLAY_SYM_DIR), ray_test_tmp("/tmp/rayforce_nonexistent_sym_xyz")); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(ray_table_nrows(loaded), 3); @@ -3394,7 +4205,7 @@ static test_result_t test_read_splayed_bad_sym_fatal(void) { ray_release(col_x); ray_release(tbl); - (void)ray_test_rm_rf(TMP_SPLAY_SYM_DIR); + (void)ray_test_rm_rf(ray_test_tmp(TMP_SPLAY_SYM_DIR)); PASS(); } @@ -4025,10 +4836,10 @@ static test_result_t test_serde_obj_save_load(void) { ray_t* v = ray_vec_from_raw(RAY_I64, raw, 4); TEST_ASSERT_FALSE(RAY_IS_ERR(v)); - ray_err_t err = ray_obj_save(v, TMP_SERDE_PATH); + ray_err_t err = ray_obj_save(v, ray_test_tmp(TMP_SERDE_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* back = ray_obj_load(TMP_SERDE_PATH); + ray_t* back = ray_obj_load(ray_test_tmp(TMP_SERDE_PATH)); TEST_ASSERT_NOT_NULL(back); TEST_ASSERT_FALSE(RAY_IS_ERR(back)); TEST_ASSERT_EQ_I(back->type, RAY_I64); TEST_ASSERT_EQ_I(back->len, 4); @@ -4037,7 +4848,7 @@ static test_result_t test_serde_obj_save_load(void) { ray_release(back); ray_release(v); - unlink(TMP_SERDE_PATH); + unlink(ray_test_tmp(TMP_SERDE_PATH)); PASS(); } @@ -4045,32 +4856,32 @@ static test_result_t test_serde_obj_save_load(void) { static test_result_t test_serde_obj_load_errors(void) { /* Non-existent file */ { - ray_t* r = ray_obj_load("/tmp/rayforce_nonexistent_42.rfl"); + ray_t* r = ray_obj_load(ray_test_tmp("/tmp/rayforce_nonexistent_42.rfl")); TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_release(r); } /* Empty file */ { - FILE* f = fopen("/tmp/rayforce_empty_test.rfl", "wb"); + FILE* f = fopen(ray_test_tmp("/tmp/rayforce_empty_test.rfl"), "wb"); TEST_ASSERT_NOT_NULL(f); fclose(f); - ray_t* r = ray_obj_load("/tmp/rayforce_empty_test.rfl"); + ray_t* r = ray_obj_load(ray_test_tmp("/tmp/rayforce_empty_test.rfl")); TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_release(r); - unlink("/tmp/rayforce_empty_test.rfl"); + unlink(ray_test_tmp("/tmp/rayforce_empty_test.rfl")); } /* Bad data (no valid header) */ { - FILE* f = fopen("/tmp/rayforce_bad_test.rfl", "wb"); + FILE* f = fopen(ray_test_tmp("/tmp/rayforce_bad_test.rfl"), "wb"); TEST_ASSERT_NOT_NULL(f); uint8_t junk[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C}; fwrite(junk, 1, sizeof(junk), f); fclose(f); - ray_t* r = ray_obj_load("/tmp/rayforce_bad_test.rfl"); + ray_t* r = ray_obj_load(ray_test_tmp("/tmp/rayforce_bad_test.rfl")); TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_release(r); - unlink("/tmp/rayforce_bad_test.rfl"); + unlink(ray_test_tmp("/tmp/rayforce_bad_test.rfl")); } PASS(); } @@ -5646,10 +6457,10 @@ static test_result_t test_col_save_load_bool_u8_i16(void) { TEST_ASSERT_NOT_NULL(vec); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_BOOL); @@ -5660,14 +6471,14 @@ static test_result_t test_col_save_load_bool_u8_i16(void) { TEST_ASSERT_TRUE(ld[2]); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->type, RAY_BOOL); TEST_ASSERT_EQ_I(mapped->len, 5); ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); } /* RAY_U8 */ { @@ -5675,10 +6486,10 @@ static test_result_t test_col_save_load_bool_u8_i16(void) { ray_t* vec = ray_vec_from_raw(RAY_U8, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_U8); TEST_ASSERT_EQ_I(loaded->len, 3); @@ -5688,7 +6499,7 @@ static test_result_t test_col_save_load_bool_u8_i16(void) { TEST_ASSERT_EQ_I(ld[2], 30); ray_release(loaded); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); } /* RAY_I16 */ { @@ -5696,10 +6507,10 @@ static test_result_t test_col_save_load_bool_u8_i16(void) { ray_t* vec = ray_vec_from_raw(RAY_I16, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_I16); TEST_ASSERT_EQ_I(loaded->len, 3); @@ -5709,7 +6520,7 @@ static test_result_t test_col_save_load_bool_u8_i16(void) { TEST_ASSERT_EQ_I(ld[2], 200); ray_release(loaded); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); } PASS(); } @@ -5722,45 +6533,45 @@ static test_result_t test_col_save_load_date_time_timestamp(void) { int32_t raw[] = {100, 200, 300}; ray_t* vec = ray_vec_from_raw(RAY_DATE, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_DATE); TEST_ASSERT_EQ_I(loaded->len, 3); ray_release(loaded); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); } /* RAY_TIME */ { int64_t raw[] = {0, 3600000000000LL, 7200000000000LL}; ray_t* vec = ray_vec_from_raw(RAY_TIME, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_TIME); TEST_ASSERT_EQ_I(loaded->len, 3); ray_release(loaded); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); } /* RAY_TIMESTAMP */ { int64_t raw[] = {1000000000000LL, 2000000000000LL}; ray_t* vec = ray_vec_from_raw(RAY_TIMESTAMP, raw, 2); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_TIMESTAMP); TEST_ASSERT_EQ_I(loaded->len, 2); ray_release(loaded); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); } PASS(); } @@ -5783,10 +6594,10 @@ static test_result_t test_col_sym_w32_roundtrip(void) { uint32_t* data = (uint32_t*)ray_data(vec); data[0] = 0; data[1] = 1; data[2] = 2; - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_SYM); @@ -5801,16 +6612,16 @@ static test_result_t test_col_sym_w32_roundtrip(void) { /* Out-of-range W32 index should be rejected on load */ data[1] = sc + 100; - err = ray_col_save(vec, TMP_COL_PATH); + err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* bad = ray_col_load(TMP_COL_PATH); + ray_t* bad = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -5821,24 +6632,24 @@ static test_result_t test_col_save_load_empty(void) { TEST_ASSERT_NOT_NULL(vec); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_I64); TEST_ASSERT_EQ_I(loaded->len, 0); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->len, 0); ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -5846,7 +6657,7 @@ static test_result_t test_col_save_load_empty(void) { /* Covers col_validate_mapped: invalid type in header triggers "nyi" error. */ static test_result_t test_col_validate_mapped_bad_type(void) { /* Write a 32-byte file with type=RAY_ERROR (127) in byte 18 */ - FILE* f = fopen(TMP_COL_PATH, "wb"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "wb"); TEST_ASSERT_NOT_NULL(f); uint8_t hdr[32]; memset(hdr, 0, 32); @@ -5863,97 +6674,13 @@ static test_result_t test_col_validate_mapped_bad_type(void) { fclose(f); /* Both load and mmap should fail; mmap uses col_validate_mapped */ - ray_t* result = ray_col_mmap(TMP_COL_PATH); + ray_t* result = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(result)); /* "nyi" from col_validate_mapped invalid type branch */ TEST_ASSERT_STR_EQ(ray_err_code(result), "nyi"); ray_release(result); - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_validate_mapped_neg_len ------------------------------------- */ -/* Covers col_validate_mapped: negative len in header => "corrupt". */ -static test_result_t test_col_validate_mapped_neg_len(void) { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - uint8_t hdr[32]; - memset(hdr, 0, 32); - hdr[17] = RAY_COL_FORMAT_MAJOR; /* `order` = major version — pass the gate */ - hdr[18] = RAY_I64; /* valid type */ - hdr[19] = 0; - hdr[20] = 1; /* rc = 1 */ - /* len = -1 at bytes 24-31 as little-endian int64 */ - int64_t neg = -1; - memcpy(hdr + 24, &neg, 8); - fwrite(hdr, 1, 32, f); - fclose(f); - - ray_t* result = ray_col_mmap(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); - TEST_ASSERT_STR_EQ(ray_err_code(result), "corrupt"); - ray_release(result); - - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_validate_mapped_data_truncated ----------------------------- */ -/* Covers col_validate_mapped: data region extends beyond file => "corrupt". */ -static test_result_t test_col_validate_mapped_data_truncated(void) { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - uint8_t hdr[40]; /* 32-byte header + 8 bytes of data (but claim 10 I64 elems) */ - memset(hdr, 0, 40); - hdr[17] = RAY_COL_FORMAT_MAJOR; /* `order` = major version — pass the gate */ - hdr[18] = RAY_I64; /* esz = 8 */ - hdr[20] = 1; /* rc = 1 */ - int64_t len = 10; /* 10 * 8 = 80 bytes needed, but only 8 written => truncated */ - memcpy(hdr + 24, &len, 8); - fwrite(hdr, 1, 40, f); /* 40 bytes total, needs 32+80=112 */ - fclose(f); - - ray_t* result = ray_col_mmap(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); - TEST_ASSERT_STR_EQ(ray_err_code(result), "corrupt"); - ray_release(result); - - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_mmap_size_mismatch ---------------------------------------- */ -/* Covers ray_col_mmap: file size != expected (32 + data + bitmap) => "io". */ -static test_result_t test_col_mmap_size_mismatch(void) { - /* Save a valid I64 column, then append a junk byte to break the size check */ - int64_t raw[] = {1, 2, 3}; - ray_t* vec = ray_vec_from_raw(RAY_I64, raw, 3); - TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); - TEST_ASSERT_EQ_I(err, RAY_OK); - ray_release(vec); - - /* Append one extra byte to break the exact-size check in ray_col_mmap */ - FILE* f = fopen(TMP_COL_PATH, "ab"); - TEST_ASSERT_NOT_NULL(f); - uint8_t extra = 0xAB; - fwrite(&extra, 1, 1, f); - fclose(f); - - /* ray_col_load should still succeed (it re-validates differently) */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_NOT_NULL(loaded); - TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); - ray_release(loaded); - - /* ray_col_mmap should fail: size mismatch */ - ray_t* result = ray_col_mmap(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); - TEST_ASSERT_STR_EQ(ray_err_code(result), "io"); - ray_release(result); - - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -5982,10 +6709,10 @@ static test_result_t test_col_recursive_atoms(void) { /* is_str_list returns false (mixed types) => goes through col_save_list * which calls col_write_recursive with atom elements */ - ray_err_t err = ray_col_save(list, TMP_COL_PATH); + ray_err_t err = ray_col_save(list, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_LIST); @@ -6005,7 +6732,7 @@ static test_result_t test_col_recursive_atoms(void) { ray_release(a_str); ray_release(a_bool); ray_release(list); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -6038,10 +6765,10 @@ static test_result_t test_col_recursive_sym_in_list(void) { list = ray_list_append(list, sym_vec); TEST_ASSERT_FALSE(RAY_IS_ERR(list)); - ray_err_t err = ray_col_save(list, TMP_COL_PATH); + ray_err_t err = ray_col_save(list, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_LIST); @@ -6062,7 +6789,7 @@ static test_result_t test_col_recursive_sym_in_list(void) { ray_release(loaded); ray_release(sym_vec); ray_release(list); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); (void)sc; PASS(); } @@ -6088,11 +6815,11 @@ static test_result_t test_col_sym_w64_negative_index(void) { * that won't be validated, then patch the file. */ /* Simpler: save valid column first to establish file, then corrupt index */ data[2] = 0; /* make it valid for save */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* Now patch byte at offset 32 + 2*8 = 48 to be 0xFF (represents -1 as int64 MSB) */ - FILE* f = fopen(TMP_COL_PATH, "r+b"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "r+b"); TEST_ASSERT_NOT_NULL(f); /* data[2] is at offset 32 + 16 bytes = 48; set it to -1 */ fseek(f, 32 + 16, SEEK_SET); @@ -6101,18 +6828,18 @@ static test_result_t test_col_sym_w64_negative_index(void) { fclose(f); /* Load should fail with "corrupt" since p[i] < 0 in W64 branch */ - ray_t* bad = ray_col_load(TMP_COL_PATH); + ray_t* bad = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); - bad = ray_col_mmap(TMP_COL_PATH); + bad = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); (void)sc; PASS(); } @@ -6146,11 +6873,11 @@ static test_result_t test_col_str_pool_roundtrip(void) { TEST_ASSERT_NOT_NULL(vec->str_pool); TEST_ASSERT_TRUE(vec->str_pool->len > 0); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* --- Round-trip via ray_col_load (deep-copy str pool) --- */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_STR); @@ -6166,7 +6893,7 @@ static test_result_t test_col_str_pool_roundtrip(void) { ray_release(loaded); /* --- Round-trip via ray_col_mmap (zero-copy, pool->mmod=2) --- */ - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->type, RAY_STR); @@ -6178,7 +6905,7 @@ static test_result_t test_col_str_pool_roundtrip(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -6198,14 +6925,14 @@ static test_result_t test_col_str_legacy_hash_repair(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); vec = ray_str_vec_append(vec, other, strlen(other)); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)), RAY_OK); /* [32-byte column header][16-byte descriptors]; hash32 is descriptor * bytes 12..15. These model arbitrary nonzero legacy padding. */ static const uint32_t garbage[] = { 0x11111111u, 0x22222222u, 0x33333333u }; - FILE* f = fopen(TMP_COL_PATH, "r+b"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "r+b"); TEST_ASSERT_NOT_NULL(f); for (int i = 0; i < 3; i++) { TEST_ASSERT_EQ_I(fseek(f, 32L + (long)i * 16L + 12L, SEEK_SET), 0); @@ -6218,7 +6945,7 @@ static test_result_t test_col_str_legacy_hash_repair(void) { TEST_ASSERT_EQ_U(fwrite(&legacy_rc, 1, sizeof(legacy_rc), f), sizeof(legacy_rc)); TEST_ASSERT_EQ_I(fclose(f), 0); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); ray_str_t* ld = (ray_str_t*)ray_data(loaded); @@ -6235,7 +6962,7 @@ static test_result_t test_col_str_legacy_hash_repair(void) { ray_release(groups); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); ray_str_t* md = (ray_str_t*)ray_data(mapped); @@ -6253,7 +6980,7 @@ static test_result_t test_col_str_legacy_hash_repair(void) { ray_release(mapped); /* MAP_PRIVATE repair must not rewrite the persisted legacy bytes. */ - f = fopen(TMP_COL_PATH, "rb"); + f = fopen(ray_test_tmp(TMP_COL_PATH), "rb"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_EQ_I(fseek(f, 32L + 12L, SEEK_SET), 0); uint32_t persisted = 0; @@ -6263,7 +6990,7 @@ static test_result_t test_col_str_legacy_hash_repair(void) { TEST_ASSERT_EQ_U(persisted, garbage[0]); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -6358,7 +7085,7 @@ static test_result_t test_stream_str_hash_persisted(void) { if (!ray_str_is_inline(&vd[i])) vd[i].hash32 = 0; } ray_col_stream_t w; - TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("s", 1), RAY_STR, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_open(&w, dir, ray_sym_intern("s", 1), RAY_STR, NULL, 0), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_append(&w, v), RAY_OK); TEST_ASSERT_EQ_I(ray_col_stream_close(&w, false), RAY_OK); @@ -6693,17 +7420,19 @@ static test_result_t test_parted_restored_mtime(void) { } /* Both generations remain intact: their file signatures cannot substitute - * for comparing the resolved directory. Also prove the sweep drops refs. */ + * for comparing the resolved directory. Also prove the sweep drops refs. + * Saved as generation 0: the asserts read plain segments' payloads and + * reference counts. */ static test_result_t test_parted_generation_and_sweep(void) { (void)ray_test_rm_rf(TMP_PARTED_ROOT); ray_t* a = parted_remount_part(10); ray_t* b = parted_remount_part(20); - TEST_ASSERT_EQ_I(ray_splay_save(a, TMP_PARTED_ROOT "/1/t", NULL), RAY_OK); - TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "/2/t", NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(a, TMP_PARTED_ROOT "/1/t", NULL, RAY_COMPRESS_OFF), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(b, TMP_PARTED_ROOT "/2/t", NULL, RAY_COMPRESS_OFF), RAY_OK); ray_t* m1 = ray_read_parted(TMP_PARTED_ROOT, "t"); TEST_ASSERT_TRUE(m1 && !RAY_IS_ERR(m1)); ray_t** s1 = (ray_t**)ray_data(ray_table_get_col_idx(m1, 1)); - TEST_ASSERT_EQ_I(ray_splay_save(b, TMP_PARTED_ROOT "/1/t/.generations/g-1", NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(b, TMP_PARTED_ROOT "/1/t/.generations/g-1", NULL, RAY_COMPRESS_OFF), RAY_OK); FILE* f = fopen(TMP_PARTED_ROOT "/1/t/.current", "wb"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_TRUE(fputs(".generations/g-1\n", f) >= 0); @@ -6725,7 +7454,9 @@ static test_result_t test_parted_generation_and_sweep(void) { } /* The limit applies across roots/tables even when every view remains live. - * Eviction only drops the cache's reference, so the oldest view still reads. */ + * Eviction only drops the cache's reference, so the oldest view still reads. + * Saved as generation 0: the asserts read plain segments' payloads and + * reference counts. */ static test_result_t test_parted_cache_limit(void) { (void)ray_test_rm_rf(TMP_PARTED_ROOT); ray_t* src = parted_remount_part(10); @@ -6734,7 +7465,7 @@ static test_result_t test_parted_cache_limit(void) { char path[128], name[24]; snprintf(name, sizeof(name), "t%d", i); snprintf(path, sizeof(path), "%s/1/%s", TMP_PARTED_ROOT, name); - TEST_ASSERT_EQ_I(ray_splay_save_bulk(src, path, NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_bulk_mode(src, path, NULL, RAY_COMPRESS_OFF), RAY_OK); views[i] = ray_read_parted(TMP_PARTED_ROOT, name); TEST_ASSERT_TRUE(views[i] && !RAY_IS_ERR(views[i])); } @@ -6773,10 +7504,11 @@ static void parted_mount_thread(void* arg) { ray_heap_abandon(); } +/* Saved as generation 0: the mount threads read a plain segment's payload. */ static test_result_t test_parted_concurrent_mounts(void) { (void)ray_test_rm_rf(TMP_PARTED_ROOT); ray_t* src = parted_remount_part(10); - TEST_ASSERT_EQ_I(ray_splay_save(src, TMP_PARTED_ROOT "/1/t", NULL), RAY_OK); + TEST_ASSERT_EQ_I(ray_splay_save_mode(src, TMP_PARTED_ROOT "/1/t", NULL, RAY_COMPRESS_OFF), RAY_OK); atomic_int ready = 0; atomic_bool go = false; parted_thread_t ctx[4]; @@ -6848,11 +7580,11 @@ static test_result_t test_col_format_version_roundtrip(void) { int32_t raw[] = {11, 22, 33, 44}; ray_t* vec = ray_vec_from_raw(RAY_I32, raw, 4); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)), RAY_OK); /* On disk: aux[0..15] all zero (no magic); byte 17 (order) == major. */ { - FILE* f = fopen(TMP_COL_PATH, "rb"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "rb"); TEST_ASSERT_NOT_NULL(f); uint8_t hd[18]; TEST_ASSERT_EQ_U(fread(hd, 1, 18, f), 18); @@ -6862,7 +7594,7 @@ static test_result_t test_col_format_version_roundtrip(void) { } /* save -> load (deep copy): values intact, runtime aux reconstructed. */ - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_I32); TEST_ASSERT_EQ_I(loaded->len, 4); @@ -6874,7 +7606,7 @@ static test_result_t test_col_format_version_roundtrip(void) { ray_release(loaded); /* save -> mmap (zero-copy): values intact, runtime aux reconstructed. */ - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_U(mapped->mmod, 1); TEST_ASSERT_EQ_I(mapped->len, 4); @@ -6885,7 +7617,7 @@ static test_result_t test_col_format_version_roundtrip(void) { ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -6902,46 +7634,46 @@ static test_result_t test_col_format_bad_version(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); /* (a) generation 0 (legacy/unstamped order byte) => loads, value intact. */ - TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)), RAY_OK); { - FILE* f = fopen(TMP_COL_PATH, "r+b"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "r+b"); TEST_ASSERT_NOT_NULL(f); uint8_t zero = 0; TEST_ASSERT_EQ_I(fseek(f, 17, SEEK_SET), 0); /* order byte */ TEST_ASSERT_EQ_U(fwrite(&zero, 1, 1, f), 1); fclose(f); } - ray_t* r1 = ray_col_load(TMP_COL_PATH); + ray_t* r1 = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(r1)); TEST_ASSERT_EQ_I(r1->len, 3); TEST_ASSERT_EQ_I(((int64_t*)ray_data(r1))[2], 3); ray_release(r1); - ray_t* r2 = ray_col_mmap(TMP_COL_PATH); + ray_t* r2 = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_FALSE(RAY_IS_ERR(r2)); TEST_ASSERT_EQ_I(r2->len, 3); ray_release(r2); /* (b) an unrecognized generation => "version" (both load + mmap). */ - TEST_ASSERT_EQ_I(ray_col_save(vec, TMP_COL_PATH), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)), RAY_OK); { - FILE* f = fopen(TMP_COL_PATH, "r+b"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "r+b"); TEST_ASSERT_NOT_NULL(f); uint8_t bad_ver = (uint8_t)(RAY_COL_FORMAT_MAJOR + 1); TEST_ASSERT_EQ_I(fseek(f, 17, SEEK_SET), 0); /* order byte */ TEST_ASSERT_EQ_U(fwrite(&bad_ver, 1, 1, f), 1); fclose(f); } - ray_t* r3 = ray_col_load(TMP_COL_PATH); + ray_t* r3 = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(r3)); TEST_ASSERT_STR_EQ(ray_err_code(r3), "version"); ray_release(r3); - ray_t* r4 = ray_col_mmap(TMP_COL_PATH); + ray_t* r4 = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(r4)); TEST_ASSERT_STR_EQ(ray_err_code(r4), "version"); ray_release(r4); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -6956,24 +7688,24 @@ static test_result_t test_col_str_empty_roundtrip(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); TEST_ASSERT_EQ_I(vec->len, 0); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_STR); TEST_ASSERT_EQ_I(loaded->len, 0); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->len, 0); ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -6990,10 +7722,10 @@ static test_result_t test_col_str_inline_only_roundtrip(void) { vec = ray_str_vec_append(vec, "bb", 2); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->len, 2); @@ -7003,14 +7735,14 @@ static test_result_t test_col_str_inline_only_roundtrip(void) { TEST_ASSERT_TRUE(memcmp(g, "bb", 2) == 0); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->len, 2); ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7029,10 +7761,10 @@ static test_result_t test_col_slice_save(void) { TEST_ASSERT_TRUE(slice->attrs & RAY_ATTR_SLICE); TEST_ASSERT_EQ_I(slice->len, 3); - ray_err_t err = ray_col_save(slice, TMP_COL_PATH); + ray_err_t err = ray_col_save(slice, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_I64); @@ -7047,7 +7779,7 @@ static test_result_t test_col_slice_save(void) { ray_release(slice); ray_release(parent); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7061,24 +7793,24 @@ static test_result_t test_col_sym_empty_roundtrip(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); TEST_ASSERT_EQ_I(vec->len, 0); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_SYM); TEST_ASSERT_EQ_I(loaded->len, 0); ray_release(loaded); - ray_t* mapped = ray_col_mmap(TMP_COL_PATH); + ray_t* mapped = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(mapped); TEST_ASSERT_FALSE(RAY_IS_ERR(mapped)); TEST_ASSERT_EQ_I(mapped->len, 0); ray_release(mapped); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7096,13 +7828,13 @@ static test_result_t test_col_sym_saved_count_reject(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); vec->len = 1; ((uint8_t*)ray_data(vec))[0] = 0; - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); /* rc field (saved sym count) is at offsetof(ray_t, rc). For the on-disk * layout it sits at byte 20 (after mmod/order/type/attrs). Overwrite it * with a count far larger than the live table. */ - FILE* f = fopen(TMP_COL_PATH, "r+b"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "r+b"); TEST_ASSERT_NOT_NULL(f); fseek(f, 20, SEEK_SET); uint32_t huge = sc + 1000000u; @@ -7110,13 +7842,13 @@ static test_result_t test_col_sym_saved_count_reject(void) { fclose(f); /* mmap path uses col_validate_mapped's saved-count branch. */ - ray_t* bad = ray_col_mmap(TMP_COL_PATH); + ray_t* bad = ray_col_mmap(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); ray_release(bad); ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7135,10 +7867,10 @@ static test_result_t test_col_str_list_empty_string(void) { list = ray_list_append(list, s2); TEST_ASSERT_FALSE(RAY_IS_ERR(list)); - ray_err_t err = ray_col_save(list, TMP_COL_PATH); + ray_err_t err = ray_col_save(list, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_LIST); @@ -7154,121 +7886,7 @@ static test_result_t test_col_str_list_empty_string(void) { ray_release(s1); ray_release(s2); ray_release(list); - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_str_list_corrupt ------------------------------------------ */ -/* Covers col_load_str_list corruption guards: - * line 173: count > remaining/4 => "corrupt" - * line 185: slen > remaining => "corrupt" - * We hand-craft STRL-magic files and load them via ray_col_load. */ -static test_result_t test_col_str_list_corrupt(void) { - const uint32_t STRL = 0x4C525453U; /* "STRL" */ - - /* (a) count claims 1000 elements but no data follows => count > rem/4 */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - fwrite(&STRL, 4, 1, f); - int64_t count = 1000; - fwrite(&count, 8, 1, f); /* nothing after => remaining == 0 */ - fclose(f); - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - /* (b) count=1, slen=99 but only 3 content bytes => slen > remaining */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - fwrite(&STRL, 4, 1, f); - int64_t count = 1; - fwrite(&count, 8, 1, f); - uint32_t slen = 99; - fwrite(&slen, 4, 1, f); - fwrite("abc", 1, 3, f); /* only 3 bytes, not 99 */ - fclose(f); - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - /* (c) truncated: magic + only 3 bytes (< 8 for count) => "corrupt" */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - fwrite(&STRL, 4, 1, f); - fwrite("xy", 1, 2, f); - fclose(f); - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_str_validate_corrupt -------------------------------------- */ -/* Covers col_validate_str_region corruption guards reachable from a forged - * STR column file loaded via ray_col_mmap: - * line 767: pool->type != RAY_U8 => "corrupt" - * line 778: pool_off out of range => "corrupt" - * Build a real STR column with one pooled string, then surgically corrupt - * the on-disk bytes. */ -static test_result_t test_col_str_validate_corrupt(void) { - ray_t* vec = ray_vec_new(RAY_STR, 1); - TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - const char* s0 = "a-pooled-string-over-twelve-bytes"; - vec = ray_str_vec_append(vec, s0, strlen(s0)); - TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - TEST_ASSERT_TRUE(vec->str_pool && vec->str_pool->len > 0); - - /* Save once; on-disk layout: [32B col hdr][16B ray_str_t elem] - * [32B pool hdr][pool bytes]. col hdr=32, data_size=16, so the - * pool header starts at offset 48; its type byte sits at 48+18=66. */ - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); - TEST_ASSERT_EQ_I(err, RAY_OK); - - /* (a) Corrupt the pool header type (offset 66) to a non-U8 value. */ - { - FILE* f = fopen(TMP_COL_PATH, "r+b"); - TEST_ASSERT_NOT_NULL(f); - fseek(f, 48 + 18, SEEK_SET); /* pool header type byte */ - uint8_t bad_type = RAY_I64; - fwrite(&bad_type, 1, 1, f); - fclose(f); - ray_t* bad = ray_col_mmap(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - /* Re-save a clean copy, then corrupt the element pool_off so it points - * past the pool. ray_str_t layout: len(4) prefix(4) pool_off(4) pad(4). - * Element sits at offset 32; pool_off field at 32 + 8 = 40. */ - err = ray_col_save(vec, TMP_COL_PATH); - TEST_ASSERT_EQ_I(err, RAY_OK); - { - FILE* f = fopen(TMP_COL_PATH, "r+b"); - TEST_ASSERT_NOT_NULL(f); - fseek(f, 32 + 8, SEEK_SET); /* pool_off field of element 0 */ - uint32_t huge_off = 0x7FFFFFFFu; - fwrite(&huge_off, 4, 1, f); - fclose(f); - ray_t* bad = ray_col_mmap(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - ray_release(vec); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7295,10 +7913,10 @@ static test_result_t test_col_recursive_list_in_list(void) { outer = ray_list_append(outer, ivec); TEST_ASSERT_FALSE(RAY_IS_ERR(outer)); - ray_err_t err = ray_col_save(outer, TMP_COL_PATH); + ray_err_t err = ray_col_save(outer, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_LIST); @@ -7326,7 +7944,7 @@ static test_result_t test_col_recursive_list_in_list(void) { ray_release(inner); ray_release(ivec); ray_release(outer); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7362,10 +7980,10 @@ static test_result_t test_col_recursive_table(void) { wrap = ray_list_append(wrap, tbl); TEST_ASSERT_FALSE(RAY_IS_ERR(wrap)); - ray_err_t err = ray_col_save(wrap, TMP_COL_PATH); + ray_err_t err = ray_col_save(wrap, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_EQ_I(loaded->type, RAY_LIST); @@ -7390,7 +8008,7 @@ static test_result_t test_col_recursive_table(void) { ray_release(namecol); ray_release(tbl); ray_release(wrap); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7426,7 +8044,7 @@ static test_result_t test_col_recursive_container_guards(void) { /* TABLE with atom columns: recursive on-disk decoding must hit the same * shared table invariant as the serde decoder. */ { - FILE* f = fopen(TMP_COL_PATH, "wb"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "wb"); TEST_ASSERT_NOT_NULL(f); int64_t name_a = ray_sym_intern("bad_a", 5); int64_t name_b = ray_sym_intern("bad_b", 5); @@ -7443,39 +8061,15 @@ static test_result_t test_col_recursive_container_guards(void) { fclose(f); TEST_ASSERT_TRUE(ok); - ray_t* bad = ray_col_load(TMP_COL_PATH); + ray_t* bad = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_ERR_CODE_MSG(bad, "domain", "column must be list/vector-like"); ray_error_free(bad); } - /* TABLE with ragged vector columns. */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - int64_t name_a = ray_sym_intern("bad_a", 5); - int64_t name_b = ray_sym_intern("bad_b", 5); - int64_t a[] = { 1, 2 }; - int64_t b[] = { 3 }; - bool ok = test_write_u32(f, TEST_COL_TABLE_MAGIC) && - test_write_i8(f, (int8_t)RAY_TABLE) && - test_write_i64(f, 2) && - test_write_i64(f, 2) && - test_write_i64(f, name_a) && - test_write_i64_vec(f, a, 2) && - test_write_i64(f, name_b) && - test_write_i64_vec(f, b, 1); - fclose(f); - TEST_ASSERT_TRUE(ok); - - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_ERR_CODE_MSG(bad, "domain", "ragged columns"); - ray_error_free(bad); - } - /* DICT with two keys and one value, nested inside a generic list so it is * decoded by col_read_recursive. */ { - FILE* f = fopen(TMP_COL_PATH, "wb"); + FILE* f = fopen(ray_test_tmp(TMP_COL_PATH), "wb"); TEST_ASSERT_NOT_NULL(f); int64_t keys[] = { 7, 8 }; int64_t vals[] = { 1 }; @@ -7488,71 +8082,12 @@ static test_result_t test_col_recursive_container_guards(void) { fclose(f); TEST_ASSERT_TRUE(ok); - ray_t* bad = ray_col_load(TMP_COL_PATH); + ray_t* bad = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_ERR_CODE_MSG(bad, "domain", "key/value count mismatch"); ray_error_free(bad); } - unlink(TMP_COL_PATH); - PASS(); -} - -/* ---- test_col_recursive_read_corrupt ------------------------------------ */ -/* Covers col_read_recursive corruption guards: - * line 398/402: LIST with truncated count / count < 0 => "corrupt" - * line 417: TABLE header < 16 bytes => "corrupt" - * Forge LIST/TABLE-magic files and load them. */ -static test_result_t test_col_recursive_read_corrupt(void) { - const uint32_t LISTM = 0x4754534CU; /* "LSTG" */ - const uint32_t TABLEM = 0x4C425454U; /* "TTBL" */ - - /* (a) LIST magic + type byte RAY_LIST but truncated count (<8 bytes). */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - fwrite(&LISTM, 4, 1, f); - int8_t t = RAY_LIST; - fwrite(&t, 1, 1, f); - fwrite("xy", 1, 2, f); /* only 2 bytes, need 8 for count */ - fclose(f); - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - /* (b) LIST magic + RAY_LIST + negative count => "corrupt". */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - fwrite(&LISTM, 4, 1, f); - int8_t t = RAY_LIST; - fwrite(&t, 1, 1, f); - int64_t neg = -5; - fwrite(&neg, 8, 1, f); - fclose(f); - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - /* (c) TABLE magic + RAY_TABLE type but header < 16 bytes. */ - { - FILE* f = fopen(TMP_COL_PATH, "wb"); - TEST_ASSERT_NOT_NULL(f); - fwrite(&TABLEM, 4, 1, f); - int8_t t = RAY_TABLE; - fwrite(&t, 1, 1, f); - fwrite("only-8b!", 1, 8, f); /* need 16 for ncols+nrows */ - fclose(f); - ray_t* bad = ray_col_load(TMP_COL_PATH); - TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); - TEST_ASSERT_STR_EQ(ray_err_code(bad), "corrupt"); - ray_release(bad); - } - - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7568,12 +8103,12 @@ static test_result_t test_col_link_sidecar_whitespace(void) { int64_t raw[] = {0, 1, 2}; ray_t* vec = ray_vec_from_raw(RAY_I64, raw, 3); TEST_ASSERT_FALSE(RAY_IS_ERR(vec)); - ray_err_t err = ray_col_save(vec, TMP_COL_PATH); + ray_err_t err = ray_col_save(vec, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_OK); ray_release(vec); char link_path[1100]; - snprintf(link_path, sizeof link_path, "%s.link", TMP_COL_PATH); + snprintf(link_path, sizeof link_path, "%s.link", ray_test_tmp(TMP_COL_PATH)); /* (a) sidecar with trailing newline / spaces / tab => trimmed, link set. */ { @@ -7583,7 +8118,7 @@ static test_result_t test_col_link_sidecar_whitespace(void) { fwrite(body, 1, strlen(body), lf); fclose(lf); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_TRUE(loaded->attrs & RAY_ATTR_HAS_LINK); @@ -7599,7 +8134,7 @@ static test_result_t test_col_link_sidecar_whitespace(void) { fwrite(body, 1, strlen(body), lf); fclose(lf); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_FALSE(loaded->attrs & RAY_ATTR_HAS_LINK); @@ -7611,7 +8146,7 @@ static test_result_t test_col_link_sidecar_whitespace(void) { FILE* lf = fopen(link_path, "wb"); TEST_ASSERT_NOT_NULL(lf); fclose(lf); - ray_t* loaded = ray_col_load(TMP_COL_PATH); + ray_t* loaded = ray_col_load(ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); TEST_ASSERT_FALSE(loaded->attrs & RAY_ATTR_HAS_LINK); @@ -7619,7 +8154,7 @@ static test_result_t test_col_link_sidecar_whitespace(void) { } unlink(link_path); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7637,11 +8172,11 @@ static test_result_t test_col_save_nyi_type(void) { TEST_ASSERT_NOT_NULL(d); TEST_ASSERT_FALSE(RAY_IS_ERR(d)); - ray_err_t err = ray_col_save(d, TMP_COL_PATH); + ray_err_t err = ray_col_save(d, ray_test_tmp(TMP_COL_PATH)); TEST_ASSERT_EQ_I(err, RAY_ERR_NYI); ray_release(d); - unlink(TMP_COL_PATH); + unlink(ray_test_tmp(TMP_COL_PATH)); PASS(); } @@ -7652,7 +8187,6 @@ const test_entry_t store_entries[] = { { "store/col_mmap_f32", test_col_mmap_f32, store_setup, store_teardown }, { "store/col_mmap_cow", test_col_mmap_cow, store_setup, store_teardown }, { "store/col_mmap_refcount", test_col_mmap_refcount, store_setup, store_teardown }, - { "store/col_mmap_corrupt", test_col_mmap_corrupt, store_setup, store_teardown }, { "store/col_mmap_nofile", test_col_mmap_nofile, store_setup, store_teardown }, { "store/splay_open_roundtrip", test_splay_open_roundtrip, store_setup, store_teardown }, { "store/splay_str_column_roundtrip", test_splay_str_column_roundtrip, store_setup, store_teardown }, @@ -7675,9 +8209,6 @@ const test_entry_t store_entries[] = { { "store/col_sym_w32_roundtrip", test_col_sym_w32_roundtrip, store_setup, store_teardown }, { "store/col_save_load_empty", test_col_save_load_empty, store_setup, store_teardown }, { "store/col_validate_bad_type", test_col_validate_mapped_bad_type, store_setup, store_teardown }, - { "store/col_validate_neg_len", test_col_validate_mapped_neg_len, store_setup, store_teardown }, - { "store/col_validate_data_trunc", test_col_validate_mapped_data_truncated, store_setup, store_teardown }, - { "store/col_mmap_size_mismatch", test_col_mmap_size_mismatch, store_setup, store_teardown }, { "store/col_recursive_atoms", test_col_recursive_atoms, store_setup, store_teardown }, { "store/col_recursive_sym_in_list", test_col_recursive_sym_in_list, store_setup, store_teardown }, { "store/col_sym_w64_neg_index", test_col_sym_w64_negative_index, store_setup, store_teardown }, @@ -7707,12 +8238,9 @@ const test_entry_t store_entries[] = { { "store/col_sym_empty_roundtrip", test_col_sym_empty_roundtrip, store_setup, store_teardown }, { "store/col_sym_saved_count_reject", test_col_sym_saved_count_reject, store_setup, store_teardown }, { "store/col_str_list_empty_string", test_col_str_list_empty_string, store_setup, store_teardown }, - { "store/col_str_list_corrupt", test_col_str_list_corrupt, store_setup, store_teardown }, - { "store/col_str_validate_corrupt", test_col_str_validate_corrupt, store_setup, store_teardown }, { "store/col_recursive_list_in_list", test_col_recursive_list_in_list, store_setup, store_teardown }, { "store/col_recursive_table", test_col_recursive_table, store_setup, store_teardown }, { "store/col_recursive_container_guards", test_col_recursive_container_guards, store_setup, store_teardown }, - { "store/col_recursive_read_corrupt", test_col_recursive_read_corrupt, store_setup, store_teardown }, { "store/col_link_sidecar_whitespace", test_col_link_sidecar_whitespace, store_setup, store_teardown }, { "store/col_save_nyi_type", test_col_save_nyi_type, store_setup, store_teardown }, { "store/file_open_close", test_file_open_close, store_setup, store_teardown }, @@ -7737,20 +8265,42 @@ const test_entry_t store_entries[] = { { "store/stream_sym_lut_stale", test_stream_sym_lut_stale, store_setup, store_teardown }, { "store/stream_index_write_failure", test_stream_index_write_failure_drops_index, store_setup, store_teardown }, { "store/stream_inline_zone_one_chunk", test_stream_inline_zone_one_chunk, store_setup, store_teardown }, - { "store/stream_hash_candidate", test_stream_hash_candidate, store_setup, store_teardown }, { "store/col_build_hash_index_bytes", test_col_build_hash_index_bytes, store_setup, store_teardown }, { "store/col_build_hash_index_refusals", test_col_build_hash_index_refusals, store_setup, store_teardown }, { "store/col_build_hash_index_untrusted_fs", test_col_build_hash_index_untrusted_fs, store_setup, store_teardown }, { "store/col_build_hash_index_fs_types", test_col_build_hash_index_fs_types, store_setup, store_teardown }, { "store/col_build_hash_index_refused", test_col_build_hash_index_refused, store_setup, store_teardown }, { "store/col_build_hash_index_truncate", test_col_build_hash_index_truncate, store_setup, store_teardown }, + { "store/stream_close_all_cancel", test_stream_close_all_cancel, store_setup, store_teardown }, + { "store/splay_save_cancel_late", test_splay_save_cancel_late, store_setup, store_teardown }, + { "store/splay_save_cancel_leaks", test_splay_save_cancel_leaks, store_setup, store_teardown }, + { "store/col_truncated_fails", test_col_truncated_fails, store_setup, store_teardown }, { "store/col_build_hash_index_marker_last", test_col_build_hash_index_marker_last, store_setup, store_teardown }, { "store/col_build_hash_index_rollback", test_col_build_hash_index_rollback, store_setup, store_teardown }, { "store/col_build_hash_index_interrupt", test_col_build_hash_index_interrupt, store_setup, store_teardown }, { "store/stream_inline_dict", test_stream_inline_dict, store_setup, store_teardown }, - { "store/stream_hash_wave", test_stream_hash_wave, store_setup, store_teardown }, + { "store/staged_bulk_no_hash", test_staged_bulk_no_hash, store_setup, store_teardown }, + { "store/resave_keeps_hash", test_resave_keeps_hash, store_setup, store_teardown }, + { "idxlazy/first_use", test_lazy_first_use, lz_setup, lz_teardown }, + { "idxlazy/eq_range", test_lazy_eq_range, lz_setup, lz_teardown }, + { "idxlazy/not_persisted", test_lazy_not_persisted, lz_setup, lz_teardown }, + { "idxlazy/budget", test_lazy_budget, lz_setup, lz_teardown }, + { "idxlazy/not_wanted", test_lazy_not_wanted, lz_setup, lz_teardown }, + { "idxlazy/gen2", test_lazy_gen2, lz_setup, lz_teardown }, + { "idxlazy/reload_bounded", test_lazy_reload_bounded, lz_setup, lz_teardown }, + { "idxlazy/timestamp", test_lazy_timestamp, lz_setup, lz_teardown }, + { "idxlazy/nulls_never", test_lazy_nulls_never, lz_setup, lz_teardown }, + { "idxlazy/derived_never", test_lazy_derived_never, lz_setup, lz_teardown }, + { "idxlazy/after_mutation", test_lazy_after_mutation, lz_setup, lz_teardown }, + { "idxlazy/out_of_range", test_lazy_out_of_range, lz_setup, lz_teardown }, + { "idxlazy/out_of_range_gen2", test_lazy_out_of_range_gen2, lz_setup, lz_teardown }, + { "idxlazy/concurrent", test_lazy_concurrent, lz_setup, lz_teardown }, + { "idxlazy/memo_evicts_memo", test_lazy_memo_evicts_memo, lz_setup, lz_teardown }, + { "idxlazy/cancel", test_lazy_cancel, lz_setup, lz_teardown }, + { "idxlazy/oom", test_lazy_oom, lz_setup, lz_teardown }, { "store/stream_region_bytes", test_stream_region_bytes_match, store_setup, store_teardown }, { "store/stream_finish_failure", test_stream_finish_failure_publishes_nothing, store_setup, store_teardown }, + { "store/stream_cancel_publishes_nothing", test_stream_cancel_publishes_nothing, store_setup, store_teardown }, { "store/file_rename_new", test_file_rename_new, store_setup, store_teardown }, { "store/file_rename_new_emulated", test_file_rename_new_emulated, store_setup, store_teardown }, { "store/file_shared_lock", test_file_shared_lock_concurrent, store_setup, store_teardown }, diff --git a/test/test_sym.c b/test/test_sym.c index 49a7fcc75..d2d219f78 100644 --- a/test/test_sym.c +++ b/test/test_sym.c @@ -230,7 +230,7 @@ static test_result_t test_sym_bulk(void) { /* ---- sym_save_load_roundtrip ------------------------------------------- */ static test_result_t test_sym_save_load_roundtrip(void) { - const char* sym_path = "/tmp/test_sym_roundtrip.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_roundtrip.sym"); /* Intern some symbols */ int64_t id_hello = ray_sym_intern("hello", 5); @@ -286,7 +286,7 @@ static test_result_t test_sym_save_load_roundtrip(void) { * stable across repeated save/load cycles because the table itself is * append-only (a later snapshot is always a superset of an earlier one). */ static test_result_t test_sym_save_rewrite_stable_ids(void) { - const char* sym_path = "/tmp/test_sym_append.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_append.sym"); /* Intern initial batch */ int64_t id_a = ray_sym_intern("alpha", 5); @@ -349,7 +349,7 @@ static test_result_t test_sym_save_rewrite_stable_ids(void) { /* ---- sym_load_corrupt -------------------------------------------------- */ static test_result_t test_sym_load_corrupt(void) { - const char* sym_path = "/tmp/test_sym_corrupt.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_corrupt.sym"); /* Write garbage data */ FILE* f = fopen(sym_path, "wb"); @@ -377,7 +377,7 @@ static test_result_t test_sym_load_corrupt(void) { /* ---- sym_load_truncated ------------------------------------------------ */ static test_result_t test_sym_load_truncated(void) { - const char* sym_path = "/tmp/test_sym_trunc.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_trunc.sym"); /* Intern and save valid sym file */ ray_sym_intern("abc", 3); @@ -737,7 +737,7 @@ static test_result_t test_sym_rebuild_segments_contract(void) { * succeed: segment sub-interning during load would otherwise shift * subsequent disk positions and trip the id==pos check. */ static test_result_t test_sym_load_legacy_dotted(void) { - const char* sym_path = "/tmp/test_sym_legacy_dotted.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_legacy_dotted.sym"); remove(sym_path); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); @@ -794,7 +794,7 @@ static test_result_t test_sym_load_legacy_dotted(void) { * interaction between segment sub-interning and the disk-position == * sym_id invariant that ray_sym_load/ray_sym_save rely on. */ static test_result_t test_sym_save_load_dotted(void) { - const char* sym_path = "/tmp/test_sym_dotted.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_dotted.sym"); remove(sym_path); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); @@ -859,7 +859,7 @@ static test_result_t test_sym_save_load_dotted(void) { /* ---- sym_load_missing_file --------------------------------------------- */ static test_result_t test_sym_load_missing(void) { - ray_err_t err = ray_sym_load("/tmp/nonexistent_sym_file_xyz.sym"); + ray_err_t err = ray_sym_load(ray_test_tmp("/tmp/nonexistent_sym_file_xyz.sym")); TEST_ASSERT((err) != (RAY_OK), "err != RAY_OK"); TEST_ASSERT_EQ_U(ray_sym_count(), 1); /* "" only */ @@ -1121,7 +1121,7 @@ static test_result_t test_sym_load_null_path(void) { /* ray_sym_load rejects a valid STRL file that contains something other than * a RAY_LIST (e.g. a RAY_I64 vector). */ static test_result_t test_sym_load_non_list(void) { - const char* sym_path = "/tmp/test_sym_nonlist.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_nonlist.sym"); remove(sym_path); /* Write a RAY_I64 vector instead of a RAY_LIST. */ @@ -1153,7 +1153,7 @@ static test_result_t test_sym_load_non_list(void) { /* ray_sym_load rejects a file that has fewer entries than what was * previously persisted (stale / truncated on disk). */ static test_result_t test_sym_load_shorter_snapshot_ok(void) { - const char* sym_path = "/tmp/test_sym_stale.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_stale.sym"); remove(sym_path); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); @@ -1205,7 +1205,7 @@ static test_result_t test_sym_load_shorter_snapshot_ok(void) { /* ray_sym_load rejects a reload where the first (already-loaded) entry * has a different string than what is in memory. */ static test_result_t test_sym_load_prefix_mismatch(void) { - const char* sym_path = "/tmp/test_sym_mismatch.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_mismatch.sym"); remove(sym_path); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); @@ -1248,7 +1248,7 @@ static test_result_t test_sym_load_prefix_mismatch(void) { * in-memory id != its disk position. This happens when a transient * symbol already occupies the slot. */ static test_result_t test_sym_load_id_mismatch(void) { - const char* sym_path = "/tmp/test_sym_idmismatch.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_idmismatch.sym"); remove(sym_path); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); @@ -1287,7 +1287,7 @@ static test_result_t test_sym_load_id_mismatch(void) { * whatever is at the path (single-writer contract). A foreign/garbage * file is simply healed by the atomic rename. */ static test_result_t test_sym_save_overwrites_foreign_file(void) { - const char* sym_path = "/tmp/test_sym_save_notlist.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_save_notlist.sym"); remove(sym_path); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); @@ -1527,7 +1527,7 @@ static bool write_strl_raw(const char* path, /* ray_sym_load rejects a STRL file whose 8-byte count field is negative * (disk_count < 0 check at sym.c line 1327). Covers lines 1328-1332. */ static test_result_t test_sym_load_neg_disk_count(void) { - const char* sym_path = "/tmp/test_sym_negcnt.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_negcnt.sym"); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); remove(sym_path); remove(lk_path); @@ -1556,7 +1556,7 @@ static test_result_t test_sym_load_neg_disk_count(void) { * File layout: magic + count=1 + slen=99 + 0 bytes of string data. * After reading slen=99: remaining==0, which is < 99 → error. */ static test_result_t test_sym_load_slen_overflow(void) { - const char* sym_path = "/tmp/test_sym_slen_ovf.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_slen_ovf.sym"); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); remove(sym_path); remove(lk_path); @@ -1588,7 +1588,7 @@ static test_result_t test_sym_load_slen_overflow(void) { * 3. Build a STRL with the same 3 entries but entry 1 changed ("zzz"). * 4. Load again → position check at i=1 fails. */ static test_result_t test_sym_load_prefix_mismatch_strl(void) { - const char* sym_path = "/tmp/test_sym_pfx_mm.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_pfx_mm.sym"); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); remove(sym_path); remove(lk_path); @@ -1634,7 +1634,7 @@ static test_result_t test_sym_load_prefix_mismatch_strl(void) { * * File: magic + count=1 + entry[0]="" + one extra 0x00 byte at the end. */ static test_result_t test_sym_load_trailing_junk(void) { - const char* sym_path = "/tmp/test_sym_trail.sym"; + const char* sym_path = ray_test_tmp("/tmp/test_sym_trail.sym"); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", sym_path); remove(sym_path); remove(lk_path); @@ -1730,7 +1730,7 @@ static test_result_t test_sym_cache_segs_many_dots(void) { * - saved_errno != EROFS && errno != EROFS is TRUE → returns RAY_ERR_IO */ static test_result_t test_sym_load_no_parent_dir(void) { - ray_err_t err = ray_sym_load("/tmp/no_such_dir_sym_xq7/sym.sym"); + ray_err_t err = ray_sym_load(ray_test_tmp("/tmp/no_such_dir_sym_xq7/sym.sym")); TEST_ASSERT_EQ_I(err, RAY_ERR_IO); PASS(); } @@ -1773,7 +1773,7 @@ static test_result_t test_sym_save_replaces_divergent_file(void) { 0x05, 0x00, 0x00, 0x00, /* entry 1: slen=5 */ 'a', 'p', 'p', 'l', 'e' /* "apple" */ }; - const char* path = "/tmp/sym_test_diverge_id.sym"; + const char* path = ray_test_tmp("/tmp/sym_test_diverge_id.sym"); char lk_path[4096]; snprintf(lk_path, sizeof(lk_path), "%s.lk", path); bool ok = write_strl_raw(path, strl_buf, sizeof(strl_buf)); @@ -1855,8 +1855,8 @@ static bool write_lazy_strl_64mb(const char* path) { * ----------------------------------------------------------------------- */ static test_result_t test_sym_lazy_load_basic(void) { /* skip if running as root: 64MB sparse files need a writable /tmp */ - const char* path1 = "/tmp/test_sym_lazy1.sym"; - const char* path2 = "/tmp/test_sym_lazy2.sym"; + const char* path1 = ray_test_tmp("/tmp/test_sym_lazy1.sym"); + const char* path2 = ray_test_tmp("/tmp/test_sym_lazy2.sym"); char lk1[4096], lk2[4096]; snprintf(lk1, sizeof(lk1), "%s.lk", path1); snprintf(lk2, sizeof(lk2), "%s.lk", path2); @@ -1909,7 +1909,7 @@ static test_result_t test_sym_lazy_load_basic(void) { static test_result_t test_sym_save_tmp_blocked(void) { if (geteuid() == 0) PASS(); /* root bypasses file permissions */ - const char* path = "/tmp/test_sym_tmpblk.sym"; + const char* path = ray_test_tmp("/tmp/test_sym_tmpblk.sym"); char tmp_path[4096], lk_path[4096]; snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path); snprintf(lk_path, sizeof(lk_path), "%s.lk", path); @@ -2786,6 +2786,17 @@ static test_result_t test_sym_serde_vec_unterminated(void) { PASS(); } +/* Ruling 8-2: the symbol lock shares a 64-byte line with neither the + * table nor the init flag. */ +static test_result_t test_sym_lock_own_line(void) { + uintptr_t l = ray_sym_test_lock_addr(); + uintptr_t t = ray_sym_test_table_addr(); + TEST_ASSERT_EQ_U(l % 64, 0); + TEST_ASSERT_TRUE(l + 64 <= t || t + ray_sym_test_table_size() <= l); + TEST_ASSERT_TRUE(ray_sym_test_inited_addr() / 64 != l / 64); + PASS(); +} + const test_entry_t sym_entries[] = { { "sym/init_destroy", test_sym_init_destroy, sym_setup, sym_teardown }, { "sym/intern_basic", test_sym_intern_basic, sym_setup, sym_teardown }, @@ -2909,6 +2920,7 @@ const test_entry_t sym_entries[] = { { "sym/serde/vec_high_cardinality", test_sym_serde_vec_high_cardinality, sym_setup, sym_teardown }, { "sym/serde/vec_single", test_sym_serde_vec_single, sym_setup, sym_teardown }, { "sym/serde/vec_empty", test_sym_serde_vec_empty, sym_setup, sym_teardown }, + { "sym/lock_own_line", test_sym_lock_own_line, sym_setup, sym_teardown }, { "sym/serde/vec_unterminated", test_sym_serde_vec_unterminated, sym_setup, sym_teardown }, { NULL, NULL, NULL, NULL }, diff --git a/test/test_text_null.c b/test/test_text_null.c index 2d2bf42e8..c5eb77b6a 100644 --- a/test/test_text_null.c +++ b/test/test_text_null.c @@ -250,8 +250,8 @@ static test_result_t test_sym_expr_admission(void) { ray_op_t* cmp = ray_eq(g, ray_scan(g, "k"), ray_const_str(g, "beta", 4)); ray_op_t* val = ray_isnull(g, ray_scan(g, "k")); ray_expr_t expr; - TEST_ASSERT_EQ_I(expr_compile(g, tbl, cmp, &expr), 1); - TEST_ASSERT_EQ_I(expr_compile(g, tbl, val, &expr), !nullable); + TEST_ASSERT_EQ_I(expr_compile(g, tbl, cmp, &expr, &(ray_t*){NULL}), 1); + TEST_ASSERT_EQ_I(expr_compile(g, tbl, val, &expr, &(ray_t*){NULL}), !nullable); ray_graph_free(g); ray_release(tbl); } diff --git a/test/test_types.c b/test/test_types.c index 70893ab44..6374df241 100644 --- a/test/test_types.c +++ b/test/test_types.c @@ -53,6 +53,9 @@ static test_result_t test_type_sizes_known_types(void) { TEST_ASSERT_EQ_U(ray_type_sizes[RAY_DATE], 4); TEST_ASSERT_EQ_U(ray_type_sizes[RAY_TIME], 4); TEST_ASSERT_EQ_U(ray_type_sizes[RAY_TIMESTAMP], 8); + TEST_ASSERT_EQ_U(ray_type_sizes[RAY_TIMESPAN], 8); + TEST_ASSERT_TRUE(RAY_TIMESPAN != RAY_SEL); + TEST_ASSERT_TRUE(RAY_TIMESPAN != RAY_ENCCOL); TEST_ASSERT_EQ_U(ray_type_sizes[RAY_GUID], 16); PASS(); @@ -94,6 +97,7 @@ static test_result_t test_type_sizes_pointer_types(void) { /* SEL has no fixed element size */ TEST_ASSERT_EQ_U(ray_type_sizes[RAY_SEL], 0); + TEST_ASSERT_EQ_U(ray_type_sizes[RAY_ENCCOL], 0); PASS(); } @@ -195,9 +199,60 @@ static test_result_t test_fn_name_builtin(void) { PASS(); } +static test_result_t test_timespan_storage_tag(void) { + ray_t* atom = ray_timespan(NULL_I64); + TEST_ASSERT_FALSE(RAY_IS_ERR(atom)); + TEST_ASSERT_TRUE(RAY_ATOM_IS_NULL(atom)); + ray_release(atom); + int64_t raw[] = {NULL_I64, INT64_MAX, -INT64_MAX, 0}; + ray_t* vector = ray_vec_from_raw(RAY_TIMESPAN, raw, 4); + TEST_ASSERT_FALSE(RAY_IS_ERR(vector)); + TEST_ASSERT_TRUE(ray_is_vec(vector)); + TEST_ASSERT_TRUE(ray_vec_is_null(vector, 0)); + TEST_ASSERT_FALSE(ray_vec_is_null(vector, 1)); + TEST_ASSERT_FALSE(ray_vec_is_null(vector, 2)); + ray_release(vector); + const int8_t internal[] = {RAY_SEL, RAY_ENCCOL}; + for (size_t i = 0; i < sizeof(internal); i++) { + ray_t* bad = ray_vec_new(internal[i], 1); + TEST_ASSERT_TRUE(RAY_IS_ERR(bad)); + ray_error_free(bad); + } + PASS(); +} + +static test_result_t test_timespan_dag_difference(void) { + int64_t values[] = {INT64_C(86400000000000), 0, NULL_I64}; + ray_t* source = ray_vec_from_raw(RAY_TIMESTAMP, values, 3); + ray_t* epoch = ray_timestamp(0); + TEST_ASSERT_FALSE(RAY_IS_ERR(source)); + TEST_ASSERT_FALSE(RAY_IS_ERR(epoch)); + ray_graph_t* graph = ray_graph_new(NULL); + TEST_ASSERT_NOT_NULL(graph); + ray_op_t* left = ray_const_vec(graph, source); + ray_op_t* right = ray_const_atom(graph, epoch); + ray_op_t* difference = ray_sub(graph, left, right); + ray_release(source); + ray_release(epoch); + TEST_ASSERT_NOT_NULL(difference); + TEST_ASSERT_EQ_I(difference->out_type, RAY_TIMESPAN); + ray_t* result = ray_execute(graph, difference); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(result->type, RAY_TIMESPAN); + TEST_ASSERT_EQ_I(result->len, 3); + TEST_ASSERT_EQ_I(((const int64_t*)ray_data(result))[0], values[0]); + TEST_ASSERT_EQ_I(((const int64_t*)ray_data(result))[1], 0); + TEST_ASSERT_TRUE(ray_vec_is_null(result, 2)); + ray_release(result); + ray_graph_free(graph); + PASS(); +} + /* ---- Suite definition -------------------------------------------------- */ const test_entry_t types_entries[] = { + { "types/timespan_dag_difference", test_timespan_dag_difference, types_runtime_setup, types_runtime_teardown }, + { "types/timespan_storage_tag", test_timespan_storage_tag, types_runtime_setup, types_runtime_teardown }, { "types/sizes_known_types", test_type_sizes_known_types, NULL, NULL }, { "types/elem_size_macro", test_elem_size_macro, NULL, NULL }, { "types/sizes_pointer_types", test_type_sizes_pointer_types, NULL, NULL }, diff --git a/test/test_vec.c b/test/test_vec.c index 986e537e7..eedef65e8 100644 --- a/test/test_vec.c +++ b/test/test_vec.c @@ -25,6 +25,8 @@ #include #include "mem/heap.h" #include "vec/vec.h" +#include "vec/growth.h" +#include "ops/idxop.h" #include "vec/str.h" #include "vec/embedding.h" #include "table/sym.h" @@ -2406,7 +2408,314 @@ static test_result_t test_vec_slice_guards(void) { /* ---- Suite definition -------------------------------------------------- */ +/* A bulk append must not round payload and then let the heap round the + * header-inclusive allocation a second time. Compare allocation capacity, + * not a process-wide high-water mark or whole-query incidental objects. */ +static test_result_t test_vec_growth_raw_block_sizing(void) { + const int64_t n = 333004; + ray_t* source = ray_vec_new(RAY_I64, n); + ray_t* dst = ray_vec_new(RAY_I64, 0); + ray_t* fresh = ray_vec_new(RAY_I64, n); + TEST_ASSERT_NOT_NULL(source); + TEST_ASSERT_NOT_NULL(dst); + TEST_ASSERT_NOT_NULL(fresh); + TEST_ASSERT_FALSE(RAY_IS_ERR(source)); + TEST_ASSERT_FALSE(RAY_IS_ERR(dst)); + TEST_ASSERT_FALSE(RAY_IS_ERR(fresh)); + source->len = n; + int64_t* values = (int64_t*)ray_data(source); + for (int64_t i = 0; i < n; i++) values[i] = i - 12345; + dst = ray_vec_append_raw(dst, values, n); + TEST_ASSERT_NOT_NULL(dst); + TEST_ASSERT_FALSE(RAY_IS_ERR(dst)); + const size_t grown_bytes = ray_block_data_bytes(dst); + const size_t fresh_bytes = ray_block_data_bytes(fresh); + const bool values_ok = dst->len == n && + memcmp(ray_data(dst), values, (size_t)n * sizeof(int64_t)) == 0; + const bool buddy = !ray_is_direct(dst) && !ray_is_direct(fresh); + ray_release(source); + ray_release(dst); + ray_release(fresh); + TEST_ASSERT_TRUE(values_ok); + TEST_ASSERT_TRUE(buddy); + TEST_ASSERT_FMT(grown_bytes == fresh_bytes, + "grown payload capacity %zu, fresh %zu", grown_bytes, fresh_bytes); + PASS(); +} + +/* Pure arithmetic checks never try to allocate the extreme sizes. */ +static test_result_t test_vec_growth_arithmetic(void) { + const size_t widths[] = { 1, 2, 4, 8, 16 }; + const size_t limit = ray_cell_growth_limit(); + size_t bytes = 123; + for (size_t i = 0; i < sizeof(widths) / sizeof(widths[0]); i++) { + size_t w = widths[i]; + TEST_ASSERT_TRUE(ray_cell_growth_bytes(17, 23, w, &bytes)); + TEST_ASSERT_EQ_I(bytes, 40 * w); + TEST_ASSERT_TRUE(ray_cell_growth_bytes(0, 0, w, &bytes)); + TEST_ASSERT_EQ_I(bytes, 0); + TEST_ASSERT_FALSE(ray_cell_growth_bytes(-1, 1, w, &bytes)); + TEST_ASSERT_FALSE(ray_cell_growth_bytes(1, -1, w, &bytes)); + TEST_ASSERT_FALSE(ray_cell_growth_bytes(INT64_MAX, 1, w, &bytes)); + TEST_ASSERT_FALSE(ray_cell_growth_bytes((int64_t)(limit / w), 1, w, &bytes)); + for (unsigned k = 6; k <= 24; k++) { + size_t payload = ((size_t)1 << k) - 32; + size_t n = payload / w; + TEST_ASSERT_TRUE(ray_cell_growth_bytes((int64_t)n, 0, w, &bytes)); + size_t request = 0; + TEST_ASSERT_TRUE(ray_cell_growth_request(0, bytes, &request)); + TEST_ASSERT_EQ_I(request, bytes); + TEST_ASSERT_EQ_I(ray_order_for_size(request), k); + } + } + TEST_ASSERT_FALSE(ray_cell_growth_bytes(0, 1, 0, &bytes)); + TEST_ASSERT_FALSE(ray_cell_growth_bytes(INT64_MAX, 0, 16, &bytes)); + TEST_ASSERT_FALSE(ray_cell_growth_request(0, limit + 1, &bytes)); + TEST_ASSERT_FALSE(ray_cell_growth_request(limit + 1, 1, &bytes)); + size_t large = limit / 2 + 1; + TEST_ASSERT_TRUE(ray_cell_growth_request(large, large + 1, &bytes)); + TEST_ASSERT_EQ_I(bytes, limit); +#if SIZE_MAX > UINT32_MAX + large = (size_t)(UINT64_C(1) << 40); /* above the largest buddy order */ + TEST_ASSERT_TRUE(ray_cell_growth_request(large, large + 8, &bytes)); + TEST_ASSERT_EQ_I(bytes, large * 2); +#endif + PASS(); +} + +/* Model every reserve boundary for a one-cell append sequence. The model + * uses the allocator's documented size rules, not an elapsed-time threshold. + * Removing direct doubling takes thousands of page-sized steps, not <=64. */ +static test_result_t test_vec_growth_geometry(void) { + const size_t target = (size_t)40 * 1024 * 1024; + size_t room = 0, copied = 0; + unsigned reserves = 0; + while (room < target) { + size_t required = room + sizeof(int64_t), request = 0; + TEST_ASSERT_TRUE(ray_cell_growth_request(room, required, &request)); + copied += room; + uint8_t order = ray_order_for_size(request); + size_t next = order < RAY_HEAP_POOL_ORDER + ? ((size_t)1 << order) - 32 + : ((request + RAY_DIRECT_HDR + 32 + 4095) & ~(size_t)4095) - RAY_DIRECT_HDR - 32; + TEST_ASSERT_TRUE(next >= required); + room = next; + reserves++; + TEST_ASSERT_TRUE(reserves <= 64); + } + TEST_ASSERT_TRUE(copied < 2 * room); + PASS(); +} + +static test_result_t test_vec_growth_direct_reserve(void) { + /* This size goes directly to a page-rounded mapping, not a buddy pool. */ + const int64_t n = ((int64_t)1 << 21) + 1024; + ray_t* v = ray_vec_new(RAY_I64, n); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + const size_t old_room = ray_block_data_bytes(v); + const int64_t old_len = (int64_t)(old_room / sizeof(int64_t)); + v->len = old_len; + int64_t* data = (int64_t*)ray_data(v); + for (int64_t i = 0; i < old_len; i++) data[i] = i ^ 0x55; + int64_t first = -777; + v = ray_vec_append_raw(v, &first, 1); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + const size_t new_room = ray_block_data_bytes(v); + ray_t* after_reserve = v; + bool stable = true; + for (int64_t i = 0; i < 1024; i++) { + v = ray_vec_append_raw(v, &i, 1); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + if (v != after_reserve) stable = false; + } + bool values_ok = v->len == old_len + 1025; + data = (int64_t*)ray_data(v); + for (int64_t i = 0; i < old_len; i++) + if (data[i] != (i ^ 0x55)) values_ok = false; + if (data[old_len] != first) values_ok = false; + for (int64_t i = 0; i < 1024; i++) + if (data[old_len + 1 + i] != i) values_ok = false; + ray_release(v); + TEST_ASSERT_TRUE(new_room >= 2 * old_room); + TEST_ASSERT_TRUE(stable); + TEST_ASSERT_TRUE(values_ok); + PASS(); +} + +/* Raw storage uses physical element widths, including all four SYM + * encodings. The raw API does not translate domains or infer null hints. */ +static test_result_t test_vec_growth_raw_widths(void) { + const int8_t types[] = { RAY_U8, RAY_I16, RAY_I32, RAY_I64, RAY_F32, RAY_F64, RAY_GUID }; + const uint8_t sym_widths[] = { RAY_SYM_W8, RAY_SYM_W16, RAY_SYM_W32, RAY_SYM_W64 }; + for (size_t k = 0; k < sizeof(types) / sizeof(types[0]) + sizeof(sym_widths); k++) { + bool sym = k >= sizeof(types) / sizeof(types[0]); + uint8_t sw = sym ? sym_widths[k - sizeof(types) / sizeof(types[0])] : 0; + ray_t* v = sym ? ray_sym_vec_new(sw, 0) : ray_vec_new(types[k], 0); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + const int64_t n = 97; + size_t width = ray_sym_elem_size(v->type, v->attrs); + _Alignas(16) uint8_t raw[97 * 16]; + memset(raw, 0, sizeof raw); + if (sym) { + for (int64_t i = 0; i < n; i++) + ray_write_sym(raw, i, (uint64_t)(i % 13), RAY_SYM, v->attrs); + } else { + for (size_t i = 0; i < (size_t)n * width; i++) raw[i] = (uint8_t)(i * 17 + 1); + } + uint8_t attrs = v->attrs; + v = ray_vec_append_raw(v, raw, n); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + bool ok = v->len == n && (v->attrs & RAY_SYM_W_MASK) == (attrs & RAY_SYM_W_MASK) && + memcmp(ray_data(v), raw, (size_t)n * width) == 0; + ray_release(v); + TEST_ASSERT_TRUE(ok); + } + PASS(); +} + +/* Failed size checks/zero batches precede COW and index mutation. A real + * growth detaches only the mutated copy's stale index; the retained old + * snapshot stays usable. Raw callers still propagate nullable hints. */ +static test_result_t test_vec_growth_indexed_snapshot(void) { + const int64_t original[] = { 7, 3, 7, 9, 3, 1 }; + int64_t more[97]; + for (int64_t i = 0; i < 97; i++) more[i] = i == 48 ? NULL_I64 : i + 100; + for (int order = 0; order < 2; order++) { + ray_t* v = ray_vec_from_raw(RAY_I64, original, 6); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_hash(&v))); + ray_t* old = v; + ray_t* index = v->index; + ray_retain(old); + TEST_ASSERT_EQ_I(ray_atomic_load(&old->rc), 2); + TEST_ASSERT(ray_vec_append_raw(v, NULL, 0) == v, "zero append must be an ownership no-op"); + ray_t* error = ray_vec_append_raw(v, more, INT64_MAX); + bool rejected = error && RAY_IS_ERR(error); + if (rejected) ray_error_free(error); + TEST_ASSERT_TRUE(rejected); + TEST_ASSERT_EQ_I(ray_atomic_load(&old->rc), 2); + TEST_ASSERT_TRUE(ray_index_has(old)); + TEST_ASSERT(old->index == index, "failed reserve replaced index"); + v = ray_vec_append_raw(v, more, 97); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + v->attrs |= RAY_ATTR_HAS_NULLS; /* caller propagation, not raw append */ + bool ok = v != old && v->len == 103 && old->len == 6 && + !ray_index_has(v) && ray_index_has(old) && old->index == index && + memcmp(ray_data(old), original, sizeof original) == 0 && + memcmp(ray_data(v), original, sizeof original) == 0 && + memcmp((int64_t*)ray_data(v) + 6, more, sizeof more) == 0 && + ray_vec_is_null(v, 54); + if (order) { ray_release(old); ray_release(v); } + else { ray_release(v); ray_release(old); } + TEST_ASSERT_TRUE(ok); + } + PASS(); +} + +static test_result_t test_vec_growth_list_refs(void) { + for (int order = 0; order < 2; order++) { + ray_t* item = ray_i64(42); + ray_t* v = ray_list_new(4); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + for (int i = 0; i < 4; i++) v = ray_list_append(v, item); + ray_t* old = v; + ray_retain(old); + v = ray_list_insert_at(v, 1, item); /* COW and a full four-cell block */ + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + for (int i = 0; i < 128; i++) { + v = ray_list_append(v, item); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + } + bool ok = old != v && old->len == 4 && v->len == 133 && + ray_atomic_load(&item->rc) == 138; + for (int64_t i = 0; i < old->len; i++) + if (((ray_t**)ray_data(old))[i] != item) ok = false; + for (int64_t i = 0; i < v->len; i++) + if (((ray_t**)ray_data(v))[i] != item) ok = false; + if (order) { + ray_release(old); + if (ray_atomic_load(&item->rc) != 134) ok = false; + ray_release(v); + } else { + ray_release(v); + if (ray_atomic_load(&item->rc) != 5) ok = false; + ray_release(old); + } + if (ray_atomic_load(&item->rc) != 1) ok = false; + ray_release(item); + TEST_ASSERT_TRUE(ok); + } + PASS(); +} + +static bool growth_string_is(ray_t* v, int64_t i, const char* wanted) { + size_t len = 0, n = strlen(wanted); + const char* p = ray_str_vec_get(v, i, &len); + return len == n && (n == 0 || (p && memcmp(p, wanted, n) == 0)); +} + +static test_result_t test_vec_growth_str_refs(void) { + const char* a = "a-long-string-for-a-shared-pool"; + const char* b = "another-long-string-for-the-pool"; + for (int order = 0; order < 2; order++) { + ray_t* v = ray_vec_new(RAY_STR, 2); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + v = ray_str_vec_append(v, a, strlen(a)); + v = ray_str_vec_append(v, b, strlen(b)); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + ray_t* old = v; + ray_t* old_pool = v->str_pool; + ray_retain(old); + for (int i = 0; i < 33; i++) { + const char* text = i % 3 == 0 ? "" : i % 3 == 1 ? "tiny" : a; + v = ray_str_vec_append(v, text, strlen(text)); + TEST_ASSERT_NOT_NULL(v); + TEST_ASSERT_FALSE(RAY_IS_ERR(v)); + } + bool ok = old != v && old->len == 2 && v->len == 35 && + old_pool != v->str_pool && ray_atomic_load(&old_pool->rc) == 1 && + ray_atomic_load(&v->str_pool->rc) == 1 && + growth_string_is(old, 0, a) && growth_string_is(old, 1, b) && + growth_string_is(v, 0, a) && growth_string_is(v, 1, b) && + !ray_vec_has_nulls(old) && ray_vec_has_nulls(v); + for (int i = 0; i < 33; i++) { + const char* text = i % 3 == 0 ? "" : i % 3 == 1 ? "tiny" : a; + if (!growth_string_is(v, i + 2, text)) ok = false; + } + if (order) { + ray_release(old); + if (!growth_string_is(v, 0, a)) ok = false; + ray_release(v); + } else { + ray_release(v); + if (!growth_string_is(old, 1, b)) ok = false; + ray_release(old); + } + TEST_ASSERT_TRUE(ok); + } + PASS(); +} + const test_entry_t vec_entries[] = { + { "vec/growth_list_refs", test_vec_growth_list_refs, vec_setup, vec_teardown }, + { "vec/growth_str_refs", test_vec_growth_str_refs, vec_setup, vec_teardown }, + { "vec/growth_raw_widths", test_vec_growth_raw_widths, vec_setup, vec_teardown }, + { "vec/growth_indexed_snapshot", test_vec_growth_indexed_snapshot, vec_setup, vec_teardown }, + { "vec/growth_arithmetic", test_vec_growth_arithmetic, vec_setup, vec_teardown }, + { "vec/growth_geometry", test_vec_growth_geometry, vec_setup, vec_teardown }, + { "vec/growth_direct_reserve", test_vec_growth_direct_reserve, vec_setup, vec_teardown }, + { "vec/growth_raw_block_sizing", test_vec_growth_raw_block_sizing, vec_setup, vec_teardown }, { "vec/new", test_vec_new, vec_setup, vec_teardown }, { "vec/new_invalid", test_vec_new_invalid, vec_setup, vec_teardown }, { "vec/append", test_vec_append, vec_setup, vec_teardown }, diff --git a/test/test_window.c b/test/test_window.c index 2965ba9e5..5fbd1a316 100644 --- a/test/test_window.c +++ b/test/test_window.c @@ -16,6 +16,7 @@ #include "test.h" #include +#include "core/pool.h" #include "mem/heap.h" #include "ops/ops.h" #include "table/sym.h" @@ -1342,6 +1343,60 @@ static test_result_t test_window_radix_path(void) { /* ─── Very large table: parallel radix + parallel partition path ────── */ +/* LAG/LEAD write boundary nulls from distinct partition tasks. Both output + * types must keep payloads and post-join HAS_NULLS metadata correct. The + * name also selects this fixture in the existing TSan 'parallel' sweep. */ +static test_result_t test_window_parallel_null_flags(void) { + ray_pool_t* pool = ray_pool_get(); + if (!pool || ray_pool_total_workers(pool) < 2) SKIP("no pool worker"); + ray_heap_init(); (void)ray_sym_init(); + const int64_t n = 9000, partitions = 100; + for (int dtype = 0; dtype < 2; dtype++) { + ray_t* gv = ray_vec_new(RAY_I64, n); gv->len = n; + ray_t* vv = ray_vec_new(dtype ? RAY_F64 : RAY_I64, n); vv->len = n; + int64_t* gd = (int64_t*)ray_data(gv); + void* vd = ray_data(vv); + for (int64_t i = 0; i < n; i++) { + gd[i] = i % partitions; + if (dtype) ((double*)vd)[i] = (double)i; + else ((int64_t*)vd)[i] = i; + } + ray_t* tbl = ray_table_new(2); + tbl = ray_table_add_col(tbl, ray_sym_intern("g", 1), gv); + tbl = ray_table_add_col(tbl, ray_sym_intern("v", 1), vv); + ray_release(gv); ray_release(vv); + for (int lead = 0; lead < 2; lead++) { + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* t = ray_const_table(g, tbl); + ray_op_t* w = build_whole_window(g, t, "g", "v", + lead ? RAY_WIN_LEAD : RAY_WIN_LAG, "v", 1); + ray_t* result = ray_execute(g, w); + TEST_ASSERT_TRUE(result && !RAY_IS_ERR(result)); + ray_t* rc = win_result_col(result, 2); + TEST_ASSERT_EQ_I(rc->type, dtype ? RAY_F64 : RAY_I64); + TEST_ASSERT_EQ_I(rc->len, n); + TEST_ASSERT_TRUE(rc->attrs & RAY_ATTR_HAS_NULLS); + const void* rd = ray_data(rc); + int64_t nulls = 0; + for (int64_t i = 0; i < n; i++) { + bool is_null = lead ? i >= n - partitions : i < partitions; + TEST_ASSERT_EQ_I(ray_vec_is_null(rc, i), is_null); + nulls += is_null; + if (!is_null) { + int64_t want = lead ? i + partitions : i - partitions; + if (dtype) TEST_ASSERT_TRUE(((const double*)rd)[i] == (double)want); + else TEST_ASSERT_EQ_I(((const int64_t*)rd)[i], want); + } + } + TEST_ASSERT_EQ_I(nulls, partitions); + ray_release(result); ray_graph_free(g); + } + ray_release(tbl); + } + ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + static test_result_t test_window_parallel_path(void) { ray_heap_init(); (void)ray_sym_init(); @@ -4317,6 +4372,7 @@ const test_entry_t window_entries[] = { { "window/multikey_partition", test_window_multikey_partition, NULL, NULL }, { "window/multiple_funcs", test_window_multiple_funcs, NULL, NULL }, { "window/radix_path", test_window_radix_path, NULL, NULL }, + { "window/parallel_null_flags", test_window_parallel_null_flags, NULL, NULL }, { "window/parallel_path", test_window_parallel_path, NULL, NULL }, { "window/order_desc", test_window_order_desc, NULL, NULL }, { "window/date_partition", test_window_date_partition, NULL, NULL }, diff --git a/test/wasm/layout_check.c b/test/wasm/layout_check.c new file mode 100644 index 000000000..6e2ebb9c8 --- /dev/null +++ b/test/wasm/layout_check.c @@ -0,0 +1,9 @@ +/* wasm32 layout check (make check-wasm32-layout): every generation-2 wire + * struct has the same size and offsets on a 32-bit target. Compiled with + * clang --target=wasm32 -ffreestanding -fsyntax-only; the static asserts + * in the headers are the test. */ +#define RAY_ENC_IDX_WIRE_ONLY 1 +#include "store/encfmt.h" +#include "store/encidx.h" +_Static_assert(sizeof(void*) == 4, "this check runs on a 32-bit target"); +int ray_wasm_layout_ok = 1; diff --git a/test/wasm/stub/string.h b/test/wasm/stub/string.h new file mode 100644 index 000000000..482e8c65e --- /dev/null +++ b/test/wasm/stub/string.h @@ -0,0 +1,6 @@ +/* Declarations the wire headers need, for the freestanding wasm32 layout + * check only (test/wasm/layout_check.c). */ +#include +void* memcpy(void* d, const void* s, size_t n); +void* memset(void* d, int c, size_t n); +int memcmp(const void* a, const void* b, size_t n);