diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d0878f41..426878bc4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,17 @@ jobs: if: matrix.target == 'debug' run: make test + # The suite with every assert() compiled out (-DNDEBUG). Our own builds keep + # asserts on, but CMake Release, distro packagers and `zig cc` define NDEBUG; + # work placed inside an assert then silently vanishes (#652: an NDEBUG build + # registered no builtins). This leg keeps the code correct either way. + ndebug: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Test with NDEBUG + run: make test-ndebug + # Coverage-guided fuzz smoke pass over the untrusted-input decoders # (parser, numeric scanners, wire-frame decoder). A healthy corpus finds # nothing new in a minute, so any crash here is a genuine regression. @@ -107,12 +118,15 @@ jobs: # check sets currently surface only false positives (GNU computed-goto # label addresses, caller-guaranteed non-null params, defensive # redundant-null-check heuristics), so this reports without gating. - # cppcheck runs whole-tree here (fast); the heavier clang-tidy pass + # cppcheck runs whole-tree here over one pinned configuration (see + # CPPCHECK_DEFS in the Makefile); the heavier clang-tidy pass # (`make tidy`) runs locally and in the nightly workflow. Flip to a - # blocking gate once the baseline is annotated clean. + # blocking gate once the baseline is annotated clean. The timeout keeps a + # regression in analysis time from holding a runner for hours. static-analysis: runs-on: ubuntu-latest continue-on-error: true + timeout-minutes: 30 steps: - uses: actions/checkout@v4 - name: Install cppcheck @@ -127,14 +141,15 @@ 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, fuzz-smoke, tsan] + needs: [build-and-test, ndebug, fuzz-smoke, tsan] if: always() runs-on: ubuntu-latest steps: - name: Verify all required jobs passed run: | bt='${{ needs.build-and-test.result }}' + nd='${{ needs.ndebug.result }}' fz='${{ needs.fuzz-smoke.result }}' ts='${{ needs.tsan.result }}' - echo "build-and-test: $bt fuzz-smoke: $fz tsan: $ts" - [ "$bt" = "success" ] && [ "$fz" = "success" ] && [ "$ts" = "success" ] || exit 1 + echo "build-and-test: $bt ndebug: $nd fuzz-smoke: $fz tsan: $ts" + [ "$bt" = "success" ] && [ "$nd" = "success" ] && [ "$fz" = "success" ] && [ "$ts" = "success" ] || exit 1 diff --git a/.gitignore b/.gitignore index 18d136b76..ef87b0142 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,7 @@ rayforce.cov .playwright-mcp/ site/ .venv-docs/ +__pycache__/ # Benchmark binaries built into the repo root (the bench/ source dir is # unaffected — it has no hyphen). diff --git a/Makefile b/Makefile index f6c170f30..34bc67986 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,11 @@ 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) WARNS = -Wall -Wextra -Werror -Wstrict-prototypes -Wno-unused-parameter @@ -140,6 +145,13 @@ HARDENED_CFLAGS = -fPIC $(WARNS) -std=$(STD) -O3 -march=$(RAY_MARCH) -g \ -funroll-loops -fno-math-errno -fassociative-math -ffp-contract=fast \ -fno-signed-zeros -fno-trapping-math -falign-functions=64 +# ndebug: the debug/test flavour with -DNDEBUG, so every assert() compiles +# away. Our own builds keep asserts on, but packagers, CMake Release and +# `zig cc` define NDEBUG; code with work inside an assert then silently +# skips it (#652: no builtins were registered). `make test-ndebug` runs +# the whole suite that way. +NDEBUG_CFLAGS = $(DEBUG_CFLAGS) -DNDEBUG + CFLAGS = $(DEBUG_CFLAGS) LDFLAGS = $(DEBUG_LDFLAGS) @@ -161,6 +173,9 @@ TSAN_MAIN_OBJ = $(MAIN_SRC:.c=.tsan.o) TSAN_TEST_OBJ = $(TEST_SRC:.c=.tsan.o) HARD_LIB_OBJ = $(LIB_SRC:.c=.hard.o) 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) # Auto-generated header dependencies (one .d per .o, see DEPFLAGS). # The fragments are -included at the very END of this file — including @@ -170,7 +185,8 @@ DEPS = $(LIB_OBJ:.o=.d) $(MAIN_OBJ:.o=.d) $(TEST_OBJ:.o=.d) \ $(REL_LIB_OBJ:.o=.d) $(REL_MAIN_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) + $(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) # Default target (pinned so an -included .d fragment can't steal it). .DEFAULT_GOAL := default @@ -193,6 +209,16 @@ default: debug %.hard.o: %.c $(CC) -c $(HARDENED_CFLAGS) $(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) + # Main binary for debug/test (some tests spawn ./$(TARGET) as a server). $(TARGET): $(LIB_OBJ) $(MAIN_OBJ) $(CC) $(CFLAGS) -o $(TARGET) $(LIB_OBJ) $(MAIN_OBJ) $(LIBS) $(LDFLAGS) @@ -246,6 +272,13 @@ test: $(LIB_OBJ) $(MAIN_OBJ) $(TEST_OBJ) $(CC) $(CFLAGS) -o $(TARGET).test $(LIB_OBJ) $(TEST_OBJ) $(LIBS) $(LDFLAGS) -Itest RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test $(TEST_ARGS) +# The suite with every assert() compiled out (see NDEBUG_CFLAGS). Relinks +# ./$(TARGET) in the same flavour, as `test` does, for the IPC-diff tests. +test-ndebug: $(NDEBUG_LIB_OBJ) $(NDEBUG_MAIN_OBJ) $(NDEBUG_TEST_OBJ) + $(CC) $(NDEBUG_CFLAGS) -o $(TARGET) $(NDEBUG_LIB_OBJ) $(NDEBUG_MAIN_OBJ) $(LIBS) $(DEBUG_LDFLAGS) + $(CC) $(NDEBUG_CFLAGS) -o $(TARGET).test $(NDEBUG_LIB_OBJ) $(NDEBUG_TEST_OBJ) $(LIBS) $(DEBUG_LDFLAGS) -Itest + RAYFORCE_CORES=$(TEST_CORES) ./$(TARGET).test $(TEST_ARGS) + # ─── ThreadSanitizer ──────────────────────────────────────────────── # Data-race detection for the lock-free pool/heap paths, which the # default ASan build cannot see (ASan and TSan are mutually exclusive, @@ -344,7 +377,7 @@ compdb: # these targets are Linux-only by design; CI gates them to ubuntu. FUZZ_RUNTIME ?= 60 FUZZ_OPTS = -rss_limit_mb=4096 -timeout=10 -max_len=65536 -print_final_stats=1 -FUZZ_TARGETS = parse numparse de eval csv journal +FUZZ_TARGETS = parse numparse de eval csv journal parquet # Escape hatch for hosts where clang auto-selects a gcc toolchain dir that # lacks libstdc++ (e.g. a partially-installed newer gcc shadowing the real # one). Normally empty; set on such a box, e.g. @@ -368,6 +401,10 @@ build_fuzz/fuzz_%: fuzz/fuzz_%.c $(FUZZ_LIB_OBJ) $(CLANGXX) -fsanitize=fuzzer,address,undefined $(FUZZ_LDEXTRA) \ -o $@ build_fuzz/$*.o $(FUZZ_LIB_OBJ) $(LIBS) +# Reuse instrumented objects across fuzz targets and linker retries. +.SECONDARY: $(FUZZ_LIB_OBJ) +.PRECIOUS: build_fuzz/fuzz_% + fuzz-%: build_fuzz/fuzz_% @mkdir -p fuzz/corpus/$* @dict=$(DICT_$*); \ @@ -375,6 +412,7 @@ fuzz-%: build_fuzz/fuzz_% seeds=$$( [ -d fuzz/seeds/$* ] && echo fuzz/seeds/$* ); \ set -x; \ ASAN_OPTIONS=detect_leaks=1:abort_on_error=1 \ + UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 \ ./build_fuzz/fuzz_$* fuzz/corpus/$* $$seeds \ $$dictopt $(FUZZ_OPTS) -max_total_time=$(FUZZ_RUNTIME) @@ -399,6 +437,16 @@ tidy: clang-tidy --quiet $(FILES) -- $(TIDY_FLAGS) # cppcheck is a second-opinion linter — advisory only, never a gate. +# +# CPPCHECK_DEFS pins ONE preprocessor configuration: the gcc / x86-64 / Linux +# debug build CI compiles. Given no -D, cppcheck enumerates the #ifdef +# combinations it finds (platform, DEBUG, endianness, fuzzing) and analyses +# each file up to 12 times — most files hit that cap, which is what made +# the whole-tree pass take ~50 minutes. Undefined macros stay undefined, so +# the Windows/macOS/WASM branches are not analysed here; every Linux file is. +CPPCHECK_DEFS = -D__linux__ -D__GNUC__ -D__x86_64__ -D__SIZEOF_INT128__=16 \ + -D__ORDER_LITTLE_ENDIAN__=1234 -D__BYTE_ORDER__=1234 -D__GLIBC__ -DDEBUG + cppcheck: @command -v cppcheck >/dev/null || { echo "cppcheck: not found"; exit 1; } cppcheck --enable=warning,portability --inline-suppr --error-exitcode=1 \ @@ -406,7 +454,7 @@ cppcheck: --suppress=missingIncludeSystem \ --suppress=assignBoolToPointer \ --suppress=nullPointerRedundantCheck \ - --std=c17 -q $(INCLUDES) src/ + --std=c17 -q $(CPPCHECK_DEFS) $(INCLUDES) src/ # assignBoolToPointer: cppcheck misparses the GNU computed-goto label # address `&&label` (a void*) as a logical-AND yielding a bool. # nullPointerRedundantCheck: a heuristic that fires on the codebase's @@ -417,7 +465,8 @@ cppcheck: clean: -rm -f $(LIB_OBJ) $(MAIN_OBJ) $(TEST_OBJ) $(REL_LIB_OBJ) $(REL_MAIN_OBJ) -rm -f $(FUZZ_LIB_OBJ) $(TSAN_LIB_OBJ) $(TSAN_MAIN_OBJ) $(TSAN_TEST_OBJ) \ - $(HARD_LIB_OBJ) $(HARD_MAIN_OBJ) + $(HARD_LIB_OBJ) $(HARD_MAIN_OBJ) \ + $(NDEBUG_LIB_OBJ) $(NDEBUG_MAIN_OBJ) $(NDEBUG_TEST_OBJ) -rm -f $(DEPS) -rm -f $(TARGET) $(TARGET).test lib$(TARGET).a -rm -f $(TARGET).tsan $(TARGET).test.tsan @@ -428,7 +477,7 @@ clean: -rm -f cov-*.profraw default.profraw coverage.profdata -rm -rf coverage_html -.PHONY: default debug release lib dist test coverage compdb tsan tsan-test hardened fuzz-smoke tidy cppcheck clean +.PHONY: default debug release lib dist test test-ndebug 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/bench/parquet_load/results/2026-09-30-full-baseline.json b/bench/parquet_load/results/2026-09-30-full-baseline.json new file mode 100644 index 000000000..525e3a5b4 --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-full-baseline.json @@ -0,0 +1,192 @@ +{ + "parquet": "/tmp/rayforce-clickbench-full.parquet", + "csv": "/tmp/rayforce-clickbench-full.csv", + "schema": "/home/hetoku/data/work/ClickBench/rayforce/create.rfl", + "cpu": "x86_64", + "logical_cpus": 28, + "input_bytes": { + "csv": 78462321894, + "parquet": 14779976446 + }, + "page_cache": "OS-managed; no cache eviction", + "timing": "process + native indexes + reopen + output fsync", + "results": [ + { + "kind": "csv", + "cores": 28, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 112.20130286399217, + "process_seconds": 112.12, + "peak_rss_kib": 57853476, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 111.79427186300745, + "process_seconds": 111.64, + "peak_rss_kib": 54960308, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 108.55062488399562, + "process_seconds": 108.47, + "peak_rss_kib": 55387880, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "csv", + "cores": 28, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 125.60159180300252, + "process_seconds": 125.52, + "peak_rss_kib": 59516320, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "csv", + "cores": 28, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 123.01205844699871, + "process_seconds": 122.83, + "peak_rss_kib": 58392464, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 100.22642820300825, + "process_seconds": 100.14, + "peak_rss_kib": 55450524, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "csv", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 145.03412295099406, + "process_seconds": 144.94, + "peak_rss_kib": 56970088, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 104.45399783599714, + "process_seconds": 104.37, + "peak_rss_kib": 52489196, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 99.68813424799009, + "process_seconds": 99.58, + "peak_rss_kib": 48723944, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "csv", + "cores": 8, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 125.43565527698956, + "process_seconds": 125.28, + "peak_rss_kib": 56344680, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "csv", + "cores": 8, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 135.2072667439934, + "process_seconds": 135.09, + "peak_rss_kib": 59701964, + "native_bytes": 59042332197, + "verified": true + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 73.56849755599978, + "process_seconds": 73.47, + "peak_rss_kib": 55747412, + "native_bytes": 59042332197, + "verified": true + } + ], + "medians": [ + { + "cores": 28, + "csv": 123.01205844699871, + "parquet": 108.55062488399562, + "csv_over_parquet": 1.1332229416316812 + }, + { + "cores": 8, + "csv": 135.2072667439934, + "parquet": 99.68813424799009, + "csv_over_parquet": 1.3563025104637207 + } + ], + "dataset": "ClickBench complete Athena hits.parquet", + "full_100m_dataset": true, + "dataset_url": "https://datasets.clickhouse.com/hits_compatible/athena/hits.parquet", + "row_groups": 226, + "cells_per_import": 10499737185, + "binary_sha256": "6d2b4d2e65d94b0627b1441227e21d6cb9e37a46640d6cc04faacec45c2a6d1d", + "phase": "before dictionary contention and lifetime fixes", + "verification": "Every column name, type and row value; numeric payload bytes and symbol string bytes. Index presence/size reflected in identical output sizes.", + "cpu_model": "Intel Core i7-14700", + "physical_cores": 20, + "ram_gib": 62, + "storage": "Samsung SSD 990 PRO 2TB, /dev/nvme0n1p3", + "swap": "16 GiB zram plus approximately 4 GiB disk swap; swapping observed, predominantly zram", + "input_preparation": "Reference SQL CLI 1.1.3 export of the same Parquet, UTC, headerless CSV; preparation excluded from load timing", + "base_commit": "95b0b91c2be60954e11ad106f0bf24c8f340b948", + "dirty_worktree": true, + "parquet_sha256": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f", + "schema_sha256": "2e62ea68186f0afd6dfd5b98c372371c56e8d7b8510eeda21404a46d219b6625", + "kernel": "6.17.9-76061709-generic" +} diff --git a/bench/parquet_load/results/2026-09-30-full-queries.json b/bench/parquet_load/results/2026-09-30-full-queries.json new file mode 100644 index 000000000..c8eb346c2 --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-full-queries.json @@ -0,0 +1,1122 @@ +{ + "input": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "input_bytes": 14779976446, + "input_sha256": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f", + "binary_sha256": "3efe1db444730918af49610cb26a313729f54bc3ccc3f15fb61173f84ae0b86b", + "harness_sha256": "50459e3b31c757d9b5ba2c86f4f41979bd27b7c6e3ba0111eba6df37adf44fd6", + "cores": 28, + "timeout_seconds": 180, + "address_space_gib": 48, + "cache": "OS-managed", + "source_types": [ + "I64", + "I16", + "SYM", + "I16", + "I64", + "I32", + "I32", + "I32", + "I32", + "I64", + "I16", + "I16", + "I16", + "SYM", + "SYM", + "I16", + "I16", + "I32", + "I16", + "I32", + "I16", + "I16", + "I16", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "I16", + "SYM", + "SYM", + "I32", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "I16", + "I16", + "I64", + "I16", + "I16", + "I32", + "I16", + "SYM", + "I32", + "I16", + "I16", + "I16", + "I64", + "SYM", + "I32", + "I16", + "I16", + "I16", + "I16", + "I16", + "SYM", + "I64", + "I16", + "I16", + "I16", + "I16", + "I16", + "I32", + "I32", + "I32", + "I16", + "SYM", + "SYM", + "SYM", + "SYM", + "I16", + "I32", + "I32", + "I32", + "I32", + "I32", + "I32", + "I16", + "SYM", + "I64", + "SYM", + "SYM", + "I16", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "I16", + "I64", + "I64", + "I32" + ], + "method": "fresh process per query; query timing excludes result CSV; not official ClickBench score", + "results": [ + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.032673436999175465, + "query": 1, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count WatchID)})", + "sql": "SELECT COUNT(*) FROM hits;", + "verified": true, + "query_ms": 7.01396, + "process_seconds": 0.01, + "peak_rss_kib": 17692, + "user_seconds": 0.0, + "system_seconds": 0.0, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1175057039999956 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.2683191349997287, + "query": 2, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count AdvEngineID) where: (!= AdvEngineID 0)})", + "sql": "SELECT COUNT(*) FROM hits WHERE AdvEngineID <> 0;", + "verified": true, + "query_ms": 204.132, + "process_seconds": 0.24, + "peak_rss_kib": 809404, + "user_seconds": 0.75, + "system_seconds": 0.38, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16871459600042726 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.2193246930000896, + "query": 3, + "translations": [], + "rayfall": "(select {from: hits sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth)})", + "sql": "SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits;", + "verified": true, + "query_ms": 151.13, + "process_seconds": 0.16, + "peak_rss_kib": 362092, + "user_seconds": 1.87, + "system_seconds": 0.12, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16938673899949208 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.16927873300028295, + "query": 4, + "translations": [], + "rayfall": "(select {from: hits avg_user: (avg UserID)})", + "sql": "SELECT AVG(UserID) FROM hits;", + "verified": true, + "query_ms": 119.627, + "process_seconds": 0.14, + "peak_rss_kib": 682536, + "user_seconds": 1.39, + "system_seconds": 0.12, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16868103300021176 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.0862364539998453, + "query": 5, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct UserID))})", + "sql": "SELECT COUNT(DISTINCT UserID) FROM hits;", + "verified": true, + "query_ms": 2904.79, + "process_seconds": 3.03, + "peak_rss_kib": 6116436, + "user_seconds": 7.15, + "system_seconds": 2.57, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3201441929995781 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.636844963999465, + "query": 6, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct SearchPhrase))})", + "sql": "SELECT COUNT(DISTINCT SearchPhrase) FROM hits;", + "verified": true, + "query_ms": 3515.53, + "process_seconds": 3.63, + "peak_rss_kib": 5015856, + "user_seconds": 7.23, + "system_seconds": 2.38, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.42278736699972796 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.11888047400043433, + "query": 7, + "translations": [], + "rayfall": "(select {from: hits min_date: (min EventDate) max_date: (max EventDate)})", + "sql": "SELECT MIN(EventDate), MAX(EventDate) FROM hits;", + "verified": true, + "query_ms": 53.0071, + "process_seconds": 0.07, + "peak_rss_kib": 308912, + "user_seconds": 0.48, + "system_seconds": 0.07, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16921935900063545 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.2696314140002869, + "query": 8, + "translations": [], + "rayfall": "(select {from: hits by: AdvEngineID c: (count AdvEngineID) where: (!= AdvEngineID 0) desc: c})", + "sql": "SELECT AdvEngineID, COUNT(*) FROM hits WHERE AdvEngineID <> 0 GROUP BY AdvEngineID ORDER BY COUNT(*) DESC;", + "verified": true, + "query_ms": 182.945, + "process_seconds": 0.21, + "peak_rss_kib": 812140, + "user_seconds": 0.4, + "system_seconds": 0.25, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11885891299971263 + }, + "rows": 18, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.4764334809997308, + "query": 9, + "translations": [], + "rayfall": "(select {from: hits by: RegionID u: (count (distinct UserID)) desc: u take: 10})", + "sql": "SELECT RegionID, COUNT(DISTINCT UserID) AS u FROM hits GROUP BY RegionID ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 1384.57, + "process_seconds": 1.43, + "peak_rss_kib": 6926048, + "user_seconds": 9.54, + "system_seconds": 2.47, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3713379549999445 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.5292287949996535, + "query": 10, + "translations": [], + "rayfall": "(select {from: hits by: RegionID sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth) u: (count (distinct UserID)) desc: c take: 10})", + "sql": "SELECT RegionID, SUM(AdvEngineID), COUNT(*) AS c, AVG(ResolutionWidth), COUNT(DISTINCT UserID) FROM hits GROUP BY RegionID ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 1382.89, + "process_seconds": 1.51, + "peak_rss_kib": 5336584, + "user_seconds": 5.91, + "system_seconds": 1.77, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4203704640003707 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.8701075039998614, + "query": 11, + "translations": [], + "rayfall": "(select {from: hits by: MobilePhoneModel u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 733.724, + "process_seconds": 0.81, + "peak_rss_kib": 3022380, + "user_seconds": 2.94, + "system_seconds": 0.95, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16869230500014964 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.022505696000735, + "query": 12, + "translations": [], + "rayfall": "(select {from: hits by: [MobilePhone MobilePhoneModel] u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhone, MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhone, MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 893.902, + "process_seconds": 0.98, + "peak_rss_kib": 3698328, + "user_seconds": 3.59, + "system_seconds": 1.1, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.22000219500023377 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.1792442360001587, + "query": 13, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2024.16, + "process_seconds": 2.12, + "peak_rss_kib": 3265200, + "user_seconds": 7.08, + "system_seconds": 2.1, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4208563599995614 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.534363941000265, + "query": 14, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase u: (count (distinct UserID)) where: (!= SearchPhrase \"\") desc: u take: 10})", + "sql": "SELECT SearchPhrase, COUNT(DISTINCT UserID) AS u FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 2357.09, + "process_seconds": 2.5, + "peak_rss_kib": 5481532, + "user_seconds": 11.15, + "system_seconds": 2.38, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6216029769993838 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.1307125350003844, + "query": 15, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID SearchPhrase] c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2006.2, + "process_seconds": 2.12, + "peak_rss_kib": 4048532, + "user_seconds": 8.42, + "system_seconds": 2.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4177891509998517 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.0806677390000914, + "query": 16, + "translations": [], + "rayfall": "(select {from: hits by: UserID c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, COUNT(*) FROM hits GROUP BY UserID ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 938.572, + "process_seconds": 1.02, + "peak_rss_kib": 8771328, + "user_seconds": 7.46, + "system_seconds": 2.68, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3722146430000066 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.735092545999578, + "query": 17, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 2579.2, + "process_seconds": 2.7, + "peak_rss_kib": 10622144, + "user_seconds": 15.27, + "system_seconds": 3.95, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.7237132390000625 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.89088568400075, + "query": 18, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 2713.1, + "process_seconds": 2.84, + "peak_rss_kib": 10422976, + "user_seconds": 15.9, + "system_seconds": 3.97, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6786461920000875 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-2461439046089301801' != 2323351816766552216", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.7023713649996353, + "query": 19, + "translations": [ + "minute from explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {UserID: UserID m: (% (div EventTime 60) 60) SearchPhrase: SearchPhrase} c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, (EventTime // 60) % 60 AS m, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, m, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 3480.24, + "process_seconds": 3.64, + "peak_rss_kib": 18957088, + "user_seconds": 23.56, + "system_seconds": 6.73, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.2790825350002706 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.1693231109993576, + "query": 20, + "translations": [], + "rayfall": "(select {from: hits UserID: UserID where: (== UserID 435090932899640449)})", + "sql": "SELECT UserID FROM hits WHERE UserID = 435090932899640449;", + "verified": true, + "query_ms": 137.209, + "process_seconds": 0.15, + "peak_rss_kib": 634984, + "user_seconds": 1.5, + "system_seconds": 0.22, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.21612607299994124 + }, + "rows": 4, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.6358436889995573, + "query": 21, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count URL) where: (like URL \"*google*\")})", + "sql": "SELECT COUNT(*) FROM hits WHERE URL LIKE '%google%';", + "verified": true, + "query_ms": 1559.45, + "process_seconds": 1.59, + "peak_rss_kib": 4444112, + "user_seconds": 22.38, + "system_seconds": 0.79, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.7728282220004985 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 9.217540763000216, + "query": 22, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) c: (count URL) where: (and (like URL \"*google*\") (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), COUNT(*) AS c FROM hits WHERE URL LIKE '%google%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 8896.65, + "process_seconds": 9.16, + "peak_rss_kib": 12892692, + "user_seconds": 31.63, + "system_seconds": 7.22, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.726833200999863 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 8, column 0: '\u043a\u0443\u043f\u0438\u0442\u044c \u0442\u0440\u0443\u0434\u043e\u0432\u0430\u043d\u0456 \u0440\u0435\u0437\u044e\u043c\u0435 \u043c\u0435\u0440\u0442\u043d\u044b\u0439 \u0434\u0438\u043d\u0430 \u043a\u0430\u0431\u0438\u043d\u0441\u043a\u0438\u0439 \u043b\u0435\u0436\u0438\u0442 \u0437\u0430\u0434\u043d\u0435\u0435 \u0443\u0441\u0442\u0430\u043d' != '\u0432\u0441\u043f\u043e\u043c\u043d\u044e \u043e \u043d\u0430\u0437\u0432\u0430\u043d\u044b \u043c\u043e\u043d\u0441\u0442\u044d\u0440'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 10.87954522200016, + "query": 23, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) min_title: (min Title) c: (count URL) u: (count (distinct UserID)) where: (and (like Title \"*Google*\") (not (like URL \"*.google.*\")) (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), MIN(Title), COUNT(*) AS c, COUNT(DISTINCT UserID) FROM hits WHERE Title LIKE '%Google%' AND URL NOT LIKE '%.google.%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 10496.0, + "process_seconds": 10.84, + "peak_rss_kib": 20671592, + "user_seconds": 48.2, + "system_seconds": 10.03, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.4270604120001735 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 7.976218296000297, + "query": 24, + "translations": [], + "rayfall": "(select {from: hits where: (like URL \"*google*\") asc: EventTime take: 10})", + "sql": "SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 7911.38, + "process_seconds": 7.96, + "peak_rss_kib": 22998172, + "user_seconds": 140.25, + "system_seconds": 3.32, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 4.906071673000042 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.378196034999746, + "query": 25, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: EventTime take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 2260.66, + "process_seconds": 2.37, + "peak_rss_kib": 5160752, + "user_seconds": 10.92, + "system_seconds": 1.93, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.2672994619997553 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '\u043d\u043e\u0447\u043d\u043e \u043a\u0438\u0442\u0430\u044f \u0436\u0435\u043d\u0449\u0438\u043d\u044b' != 'galaxy s4 zoom \u0444\u0438\u043b\u044c\u043c'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.9782494459996087, + "query": 26, + "translations": [], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase where: (!= SearchPhrase \"\") asc: SearchPhrase take: 10})", + "sql": "SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 1859.78, + "process_seconds": 1.95, + "peak_rss_kib": 3223408, + "user_seconds": 7.12, + "system_seconds": 1.57, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.21663296800034004 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.3804124799999045, + "query": 27, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: [EventTime SearchPhrase] take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 2255.35, + "process_seconds": 2.36, + "peak_rss_kib": 5214672, + "user_seconds": 10.6, + "system_seconds": 1.99, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.2668733969994719 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.353305478000038, + "query": 28, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: CounterID l: (avg (strlen URL)) c: (count URL) where: (!= URL \"\")}) where: (> c 100000) desc: l take: 25})", + "sql": "SELECT CounterID, AVG(STRLEN(URL)) AS l, COUNT(*) AS c FROM hits WHERE URL <> '' GROUP BY CounterID HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": true, + "query_ms": 6276.61, + "process_seconds": 6.34, + "peak_rss_kib": 10957428, + "user_seconds": 27.34, + "system_seconds": 4.74, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6220391669994569 + }, + "rows": 25, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 10.398864037000749, + "query": 29, + "translations": [ + "match SQL URL regexp protocol, nonempty host and newline semantics" + ], + "rayfall": "(xcol (select {from: (select {from: hits by: (let p (str-find Referer \"://\") (let s (substr Referer (+ p 4) -1) (let sl (str-find s \"/\") (if (and (or (== (substr Referer 1 7) \"http://\") (== (substr Referer 1 8) \"https://\")) (> sl 0) (nil? (str-find (substr s (+ sl 2) -1) \"\\n\"))) (if (and (== (str-find s \"www.\") 0) (> sl 4)) (substr s 5 (- sl 4)) (substr s 1 sl)) Referer)))) l: (avg (strlen Referer)) c: (count Referer) min_ref: (min Referer) where: (!= Referer \"\")}) where: (> c 100000) desc: l take: 25}) [k l c min_ref])", + "sql": "SELECT REGEXP_REPLACE(Referer, '^https?://(?:www\\.)?([^/]+)/.*$', '\\1') AS k, AVG(STRLEN(Referer)) AS l, COUNT(*) AS c, MIN(Referer) FROM hits WHERE Referer <> '' GROUP BY k HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": true, + "query_ms": 10084.5, + "process_seconds": 10.37, + "peak_rss_kib": 10847900, + "user_seconds": 52.84, + "system_seconds": 7.29, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 3.7886769229999118 + }, + "rows": 25, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.32033905499974935, + "query": 30, + "translations": [], + "rayfall": "(select {from: hits s0: (sum ResolutionWidth) s1: (sum (+ ResolutionWidth 1)) s2: (sum (+ ResolutionWidth 2)) s3: (sum (+ ResolutionWidth 3)) s4: (sum (+ ResolutionWidth 4)) s5: (sum (+ ResolutionWidth 5)) s6: (sum (+ ResolutionWidth 6)) s7: (sum (+ ResolutionWidth 7)) s8: (sum (+ ResolutionWidth 8)) s9: (sum (+ ResolutionWidth 9)) s10: (sum (+ ResolutionWidth 10)) s11: (sum (+ ResolutionWidth 11)) s12: (sum (+ ResolutionWidth 12)) s13: (sum (+ ResolutionWidth 13)) s14: (sum (+ ResolutionWidth 14)) s15: (sum (+ ResolutionWidth 15)) s16: (sum (+ ResolutionWidth 16)) s17: (sum (+ ResolutionWidth 17)) s18: (sum (+ ResolutionWidth 18)) s19: (sum (+ ResolutionWidth 19)) s20: (sum (+ ResolutionWidth 20)) s21: (sum (+ ResolutionWidth 21)) s22: (sum (+ ResolutionWidth 22)) s23: (sum (+ ResolutionWidth 23)) s24: (sum (+ ResolutionWidth 24)) s25: (sum (+ ResolutionWidth 25)) s26: (sum (+ ResolutionWidth 26)) s27: (sum (+ ResolutionWidth 27)) s28: (sum (+ ResolutionWidth 28)) s29: (sum (+ ResolutionWidth 29)) s30: (sum (+ ResolutionWidth 30)) s31: (sum (+ ResolutionWidth 31)) s32: (sum (+ ResolutionWidth 32)) s33: (sum (+ ResolutionWidth 33)) s34: (sum (+ ResolutionWidth 34)) s35: (sum (+ ResolutionWidth 35)) s36: (sum (+ ResolutionWidth 36)) s37: (sum (+ ResolutionWidth 37)) s38: (sum (+ ResolutionWidth 38)) s39: (sum (+ ResolutionWidth 39)) s40: (sum (+ ResolutionWidth 40)) s41: (sum (+ ResolutionWidth 41)) s42: (sum (+ ResolutionWidth 42)) s43: (sum (+ ResolutionWidth 43)) s44: (sum (+ ResolutionWidth 44)) s45: (sum (+ ResolutionWidth 45)) s46: (sum (+ ResolutionWidth 46)) s47: (sum (+ ResolutionWidth 47)) s48: (sum (+ ResolutionWidth 48)) s49: (sum (+ ResolutionWidth 49)) s50: (sum (+ ResolutionWidth 50)) s51: (sum (+ ResolutionWidth 51)) s52: (sum (+ ResolutionWidth 52)) s53: (sum (+ ResolutionWidth 53)) s54: (sum (+ ResolutionWidth 54)) s55: (sum (+ ResolutionWidth 55)) s56: (sum (+ ResolutionWidth 56)) s57: (sum (+ ResolutionWidth 57)) s58: (sum (+ ResolutionWidth 58)) s59: (sum (+ ResolutionWidth 59)) s60: (sum (+ ResolutionWidth 60)) s61: (sum (+ ResolutionWidth 61)) s62: (sum (+ ResolutionWidth 62)) s63: (sum (+ ResolutionWidth 63)) s64: (sum (+ ResolutionWidth 64)) s65: (sum (+ ResolutionWidth 65)) s66: (sum (+ ResolutionWidth 66)) s67: (sum (+ ResolutionWidth 67)) s68: (sum (+ ResolutionWidth 68)) s69: (sum (+ ResolutionWidth 69)) s70: (sum (+ ResolutionWidth 70)) s71: (sum (+ ResolutionWidth 71)) s72: (sum (+ ResolutionWidth 72)) s73: (sum (+ ResolutionWidth 73)) s74: (sum (+ ResolutionWidth 74)) s75: (sum (+ ResolutionWidth 75)) s76: (sum (+ ResolutionWidth 76)) s77: (sum (+ ResolutionWidth 77)) s78: (sum (+ ResolutionWidth 78)) s79: (sum (+ ResolutionWidth 79)) s80: (sum (+ ResolutionWidth 80)) s81: (sum (+ ResolutionWidth 81)) s82: (sum (+ ResolutionWidth 82)) s83: (sum (+ ResolutionWidth 83)) s84: (sum (+ ResolutionWidth 84)) s85: (sum (+ ResolutionWidth 85)) s86: (sum (+ ResolutionWidth 86)) s87: (sum (+ ResolutionWidth 87)) s88: (sum (+ ResolutionWidth 88)) s89: (sum (+ ResolutionWidth 89))})", + "sql": "SELECT SUM(ResolutionWidth), SUM(ResolutionWidth + 1), SUM(ResolutionWidth + 2), SUM(ResolutionWidth + 3), SUM(ResolutionWidth + 4), SUM(ResolutionWidth + 5), SUM(ResolutionWidth + 6), SUM(ResolutionWidth + 7), SUM(ResolutionWidth + 8), SUM(ResolutionWidth + 9), SUM(ResolutionWidth + 10), SUM(ResolutionWidth + 11), SUM(ResolutionWidth + 12), SUM(ResolutionWidth + 13), SUM(ResolutionWidth + 14), SUM(ResolutionWidth + 15), SUM(ResolutionWidth + 16), SUM(ResolutionWidth + 17), SUM(ResolutionWidth + 18), SUM(ResolutionWidth + 19), SUM(ResolutionWidth + 20), SUM(ResolutionWidth + 21), SUM(ResolutionWidth + 22), SUM(ResolutionWidth + 23), SUM(ResolutionWidth + 24), SUM(ResolutionWidth + 25), SUM(ResolutionWidth + 26), SUM(ResolutionWidth + 27), SUM(ResolutionWidth + 28), SUM(ResolutionWidth + 29), SUM(ResolutionWidth + 30), SUM(ResolutionWidth + 31), SUM(ResolutionWidth + 32), SUM(ResolutionWidth + 33), SUM(ResolutionWidth + 34), SUM(ResolutionWidth + 35), SUM(ResolutionWidth + 36), SUM(ResolutionWidth + 37), SUM(ResolutionWidth + 38), SUM(ResolutionWidth + 39), SUM(ResolutionWidth + 40), SUM(ResolutionWidth + 41), SUM(ResolutionWidth + 42), SUM(ResolutionWidth + 43), SUM(ResolutionWidth + 44), SUM(ResolutionWidth + 45), SUM(ResolutionWidth + 46), SUM(ResolutionWidth + 47), SUM(ResolutionWidth + 48), SUM(ResolutionWidth + 49), SUM(ResolutionWidth + 50), SUM(ResolutionWidth + 51), SUM(ResolutionWidth + 52), SUM(ResolutionWidth + 53), SUM(ResolutionWidth + 54), SUM(ResolutionWidth + 55), SUM(ResolutionWidth + 56), SUM(ResolutionWidth + 57), SUM(ResolutionWidth + 58), SUM(ResolutionWidth + 59), SUM(ResolutionWidth + 60), SUM(ResolutionWidth + 61), SUM(ResolutionWidth + 62), SUM(ResolutionWidth + 63), SUM(ResolutionWidth + 64), SUM(ResolutionWidth + 65), SUM(ResolutionWidth + 66), SUM(ResolutionWidth + 67), SUM(ResolutionWidth + 68), SUM(ResolutionWidth + 69), SUM(ResolutionWidth + 70), SUM(ResolutionWidth + 71), SUM(ResolutionWidth + 72), SUM(ResolutionWidth + 73), SUM(ResolutionWidth + 74), SUM(ResolutionWidth + 75), SUM(ResolutionWidth + 76), SUM(ResolutionWidth + 77), SUM(ResolutionWidth + 78), SUM(ResolutionWidth + 79), SUM(ResolutionWidth + 80), SUM(ResolutionWidth + 81), SUM(ResolutionWidth + 82), SUM(ResolutionWidth + 83), SUM(ResolutionWidth + 84), SUM(ResolutionWidth + 85), SUM(ResolutionWidth + 86), SUM(ResolutionWidth + 87), SUM(ResolutionWidth + 88), SUM(ResolutionWidth + 89) FROM hits;", + "verified": true, + "query_ms": 258.047, + "process_seconds": 0.29, + "peak_rss_kib": 889616, + "user_seconds": 1.29, + "system_seconds": 0.2, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.2697608049993505 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.734423310999773, + "query": 31, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2598.96, + "process_seconds": 2.71, + "peak_rss_kib": 6257368, + "user_seconds": 13.17, + "system_seconds": 2.37, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3673329819994251 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 9, column 1: '-265917476' != -1125673878", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.9371025769996777, + "query": 32, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2797.71, + "process_seconds": 2.92, + "peak_rss_kib": 7718408, + "user_seconds": 14.77, + "system_seconds": 2.93, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.46808635399975174 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5581899925183342605' != 7700775615610109149", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.3387494640001023, + "query": 33, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2186.55, + "process_seconds": 2.33, + "peak_rss_kib": 25678944, + "user_seconds": 20.83, + "system_seconds": 10.3, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.5768059649999486 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '7224410078130478461' != 6655575552203051303", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.143074780000461, + "query": 34, + "translations": [], + "rayfall": "(select {from: hits by: URL c: (count URL) desc: c take: 10})", + "sql": "SELECT URL, COUNT(*) AS c FROM hits GROUP BY URL ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 4889.62, + "process_seconds": 5.13, + "peak_rss_kib": 9863732, + "user_seconds": 19.44, + "system_seconds": 4.34, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.5787234890003674 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.797803178000322, + "query": 35, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: URL c: (count URL) desc: c take: 10}) one: 1 URL: URL c: c})", + "sql": "SELECT 1, URL, COUNT(*) AS c FROM hits GROUP BY 1, URL ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 5536.27, + "process_seconds": 5.79, + "peak_rss_kib": 9895772, + "user_seconds": 20.81, + "system_seconds": 4.98, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.6279665179999938 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.7765034100002595, + "query": 36, + "translations": [ + "align computed-group-key output column order" + ], + "rayfall": "(select {from: hits by: {ClientIP: ClientIP ip1: (- ClientIP 1) ip2: (- ClientIP 2) ip3: (- ClientIP 3)} c: (count ClientIP) desc: c take: 10})", + "sql": "SELECT ClientIP, COUNT(*) AS c, ClientIP - 1, ClientIP - 2, ClientIP - 3 FROM hits GROUP BY ClientIP, ClientIP - 1, ClientIP - 2, ClientIP - 3 ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 700.089, + "process_seconds": 0.75, + "peak_rss_kib": 7253280, + "user_seconds": 6.67, + "system_seconds": 2.66, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.36959509900043486 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.047331691999716, + "query": 37, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= URL \"\")) desc: views take: 10})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND URL <> '' GROUP BY URL ORDER BY PageViews DESC LIMIT 10;", + "verified": true, + "query_ms": 5750.98, + "process_seconds": 6.0, + "peak_rss_kib": 12385152, + "user_seconds": 21.51, + "system_seconds": 4.86, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16572407300009218 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.9391296900003, + "query": 38, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: Title views: (count Title) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= Title \"\")) desc: views take: 10})", + "sql": "SELECT Title, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND Title <> '' GROUP BY Title ORDER BY PageViews DESC LIMIT 10;", + "verified": true, + "query_ms": 3722.95, + "process_seconds": 3.91, + "peak_rss_kib": 8878868, + "user_seconds": 21.77, + "system_seconds": 3.84, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16621865599972807 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.2015939640004945, + "query": 39, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (!= IsLink 0) (== IsDownload 0)) desc: views take: [1000 10]})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND IsLink <> 0 AND IsDownload = 0 GROUP BY URL ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 5903.86, + "process_seconds": 6.16, + "peak_rss_kib": 12395032, + "user_seconds": 21.15, + "system_seconds": 4.88, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16580058199997438 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: 'http://guide.trashbox' != 'http://stalker-pub-20087898675494,960948/#page_type%3D0%26pz%3D0%26rleurl%3D//ad.adrive_type=0&view_type=2d#schenie_spire/?SECTIONAL,\u0430\u0432\u0442\u043e\u0441\u0430\u043b\u043e\u043d/pages/0001216/0001216629%26bid%3D158197%26width%3Dhttp://allanet'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 11.634474593999585, + "query": 40, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: {TraficSourceID: TraficSourceID SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID Src: (if (and (== SearchEngineID 0) (== AdvEngineID 0)) Referer \"\") Dst: URL} views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0)) desc: views take: [1000 10]})", + "sql": "SELECT TraficSourceID, SearchEngineID, AdvEngineID, CASE WHEN (SearchEngineID = 0 AND AdvEngineID = 0) THEN Referer ELSE '' END AS Src, URL AS Dst, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 GROUP BY TraficSourceID, SearchEngineID, AdvEngineID, Src, Dst ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 11189.4, + "process_seconds": 11.58, + "peak_rss_kib": 21232008, + "user_seconds": 42.23, + "system_seconds": 8.94, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.27019121300054394 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-1' != 0", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.1303934119996484, + "query": 41, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [URLHash EventDate] views: (count URLHash) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (in TraficSourceID [-1 6]) (== RefererHash 3594120000172545465)) desc: views take: [100 10]})", + "sql": "SELECT URLHash, EventDate, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND TraficSourceID IN (-1, 6) AND RefererHash = 3594120000172545465 GROUP BY URLHash, EventDate ORDER BY PageViews DESC LIMIT 10 OFFSET 100;", + "verified": true, + "query_ms": 2022.02, + "process_seconds": 2.11, + "peak_rss_kib": 8419396, + "user_seconds": 7.81, + "system_seconds": 1.86, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11527313100032188 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5520570504648279068' != 2054727273000865689", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.186941363999722, + "query": 42, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [WindowClientWidth WindowClientHeight] views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (== DontCountHits 0) (== URLHash 2868770270353813622)) desc: views take: [10000 10]})", + "sql": "SELECT WindowClientWidth, WindowClientHeight, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND DontCountHits = 0 AND URLHash = 2868770270353813622 GROUP BY WindowClientWidth, WindowClientHeight ORDER BY PageViews DESC LIMIT 10 OFFSET 10000;", + "verified": true, + "query_ms": 2053.26, + "process_seconds": 2.15, + "peak_rss_kib": 8768560, + "user_seconds": 8.77, + "system_seconds": 1.78, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11697740300041914 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '1667' != 1145", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.729300231999332, + "query": 43, + "translations": [ + "date predicates in explicit Unix days", + "minute buckets in explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {M: (xbar EventTime 60)} views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15900 15901]) (== IsRefresh 0) (== DontCountHits 0)) asc: M take: [1000 10]})", + "sql": "SELECT (EventTime // 60) * 60 AS M, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15900 AND EventDate <= 15901 AND IsRefresh = 0 AND DontCountHits = 0 GROUP BY (EventTime // 60) * 60 ORDER BY (EventTime // 60) * 60 LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 1563.68, + "process_seconds": 1.69, + "peak_rss_kib": 6728256, + "user_seconds": 7.72, + "system_seconds": 1.32, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1189288959994883 + }, + "rows": 10, + "mismatch": null + } + ] +} diff --git a/bench/parquet_load/results/2026-09-30-full-query-baseline.json b/bench/parquet_load/results/2026-09-30-full-query-baseline.json new file mode 100644 index 000000000..675c2c41e --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-full-query-baseline.json @@ -0,0 +1,918 @@ +{ + "input": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "input_bytes": 14779976446, + "input_sha256": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f", + "binary_sha256": "c937de4742ccc4c1b9a7718fde7e461908fe6cc303664efcdfe7b8c7b7cda1de", + "harness_sha256": "43321ce378dcba977b0d84ff401618292f8735bfb8c08e599200a146b8cec264", + "cores": 28, + "timeout_seconds": 180, + "address_space_gib": 48, + "cache": "OS-managed", + "method": "fresh process per query; query timing excludes result CSV; not official ClickBench score", + "results": [ + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03328534199954447, + "query": 1, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count WatchID)})", + "sql": "SELECT COUNT(*) FROM hits;", + "verified": true, + "query_ms": 7.08045, + "process_seconds": 0.02, + "peak_rss_kib": 17896, + "user_seconds": 0.0, + "system_seconds": 0.0, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16678115500053536 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.4704088350008533, + "query": 2, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count AdvEngineID) where: (!= AdvEngineID 0)})", + "sql": "SELECT COUNT(*) FROM hits WHERE AdvEngineID <> 0;", + "verified": true, + "query_ms": 350.567, + "process_seconds": 0.42, + "peak_rss_kib": 1399960, + "user_seconds": 0.9, + "system_seconds": 0.53, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11827315600021393 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.1680108559994551, + "query": 3, + "translations": [], + "rayfall": "(select {from: hits sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth)})", + "sql": "SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits;", + "verified": true, + "query_ms": 135.633, + "process_seconds": 0.15, + "peak_rss_kib": 361572, + "user_seconds": 1.54, + "system_seconds": 0.06, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16566995799985307 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.1691691460000584, + "query": 4, + "translations": [], + "rayfall": "(select {from: hits avg_user: (avg UserID)})", + "sql": "SELECT AVG(UserID) FROM hits;", + "verified": true, + "query_ms": 106.343, + "process_seconds": 0.12, + "peak_rss_kib": 679988, + "user_seconds": 1.3, + "system_seconds": 0.09, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16909983599998668 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.1388994049993926, + "query": 5, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct UserID))})", + "sql": "SELECT COUNT(DISTINCT UserID) FROM hits;", + "verified": true, + "query_ms": 2970.81, + "process_seconds": 3.12, + "peak_rss_kib": 6111684, + "user_seconds": 7.15, + "system_seconds": 3.24, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.31696160399951623 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.40217867299998, + "query": 6, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct SearchPhrase))})", + "sql": "SELECT COUNT(DISTINCT SearchPhrase) FROM hits;", + "verified": true, + "query_ms": 5210.42, + "process_seconds": 5.35, + "peak_rss_kib": 9404532, + "user_seconds": 9.99, + "system_seconds": 2.79, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4235815100000764 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.11805872399963846, + "query": 7, + "translations": [], + "rayfall": "(select {from: hits min_date: (min EventDate) max_date: (max EventDate)})", + "sql": "SELECT MIN(EventDate), MAX(EventDate) FROM hits;", + "verified": true, + "query_ms": 49.5342, + "process_seconds": 0.07, + "peak_rss_kib": 309164, + "user_seconds": 0.3, + "system_seconds": 0.05, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16845499399914843 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.42058218700003636, + "query": 8, + "translations": [], + "rayfall": "(select {from: hits by: AdvEngineID c: (count AdvEngineID) where: (!= AdvEngineID 0) desc: c})", + "sql": "SELECT AdvEngineID, COUNT(*) FROM hits WHERE AdvEngineID <> 0 GROUP BY AdvEngineID ORDER BY COUNT(*) DESC;", + "verified": true, + "query_ms": 305.648, + "process_seconds": 0.37, + "peak_rss_kib": 1404784, + "user_seconds": 0.66, + "system_seconds": 0.34, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16914371900020342 + }, + "rows": 18, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.5286647499997343, + "query": 9, + "translations": [], + "rayfall": "(select {from: hits by: RegionID u: (count (distinct UserID)) desc: u take: 10})", + "sql": "SELECT RegionID, COUNT(DISTINCT UserID) AS u FROM hits GROUP BY RegionID ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 1426.13, + "process_seconds": 1.49, + "peak_rss_kib": 6979620, + "user_seconds": 9.35, + "system_seconds": 2.59, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.37034994999976334 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.0326254190003965, + "query": 10, + "translations": [], + "rayfall": "(select {from: hits by: RegionID sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth) u: (count (distinct UserID)) desc: c take: 10})", + "sql": "SELECT RegionID, SUM(AdvEngineID), COUNT(*) AS c, AVG(ResolutionWidth), COUNT(DISTINCT UserID) FROM hits GROUP BY RegionID ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 1828.47, + "process_seconds": 1.97, + "peak_rss_kib": 6935396, + "user_seconds": 6.46, + "system_seconds": 2.09, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4216643670006306 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.0884199019992593, + "query": 11, + "translations": [], + "rayfall": "(select {from: hits by: MobilePhoneModel u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 2843.16, + "process_seconds": 3.07, + "peak_rss_kib": 7600456, + "user_seconds": 8.02, + "system_seconds": 2.05, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1658214079998288 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.1894680499999595, + "query": 12, + "translations": [], + "rayfall": "(select {from: hits by: [MobilePhone MobilePhoneModel] u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhone, MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhone, MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 2932.43, + "process_seconds": 3.17, + "peak_rss_kib": 7923620, + "user_seconds": 8.88, + "system_seconds": 2.14, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16605956599960336 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 4.446989922999819, + "query": 13, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 4326.05, + "process_seconds": 4.43, + "peak_rss_kib": 9354896, + "user_seconds": 12.24, + "system_seconds": 2.21, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.41845333099990967 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.807053839999753, + "query": 14, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase u: (count (distinct UserID)) where: (!= SearchPhrase \"\") desc: u take: 10})", + "sql": "SELECT SearchPhrase, COUNT(DISTINCT UserID) AS u FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 5505.14, + "process_seconds": 5.75, + "peak_rss_kib": 11829104, + "user_seconds": 17.6, + "system_seconds": 3.19, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6245498130001579 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 4.648584576999383, + "query": 15, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID SearchPhrase] c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 4483.3, + "process_seconds": 4.62, + "peak_rss_kib": 9666596, + "user_seconds": 13.86, + "system_seconds": 2.25, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.41877485500026523 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.2262750830004734, + "query": 16, + "translations": [], + "rayfall": "(select {from: hits by: UserID c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, COUNT(*) FROM hits GROUP BY UserID ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 1075.49, + "process_seconds": 1.2, + "peak_rss_kib": 8809624, + "user_seconds": 6.94, + "system_seconds": 6.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.369186150999667 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.201602898000601, + "query": 17, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 5064.16, + "process_seconds": 5.17, + "peak_rss_kib": 12785300, + "user_seconds": 22.61, + "system_seconds": 3.69, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.7213904640002511 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.0552245729995775, + "query": 18, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 4914.32, + "process_seconds": 5.03, + "peak_rss_kib": 12688620, + "user_seconds": 22.7, + "system_seconds": 3.67, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.670424785999785 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-2461439046089301801' != 1428604792192303429", + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 3.5502483379996193, + "query": 19, + "translations": [ + "minute from explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {UserID: UserID m: (% (div EventTime 60) 60) SearchPhrase: SearchPhrase} c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, (EventTime // 60) % 60 AS m, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, m, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 3.53, + "peak_rss_kib": 31482616, + "user_seconds": 35.21, + "system_seconds": 35.12 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.16613202200005617, + "query": 20, + "translations": [], + "rayfall": "(select {from: hits UserID: UserID where: (== UserID 435090932899640449)})", + "sql": "SELECT UserID FROM hits WHERE UserID = 435090932899640449;", + "verified": true, + "query_ms": 133.086, + "process_seconds": 0.15, + "peak_rss_kib": 636560, + "user_seconds": 1.57, + "system_seconds": 0.08, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16707965499972488 + }, + "rows": 4, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.301032219000263, + "query": 21, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count URL) where: (like URL \"*google*\")})", + "sql": "SELECT COUNT(*) FROM hits WHERE URL LIKE '%google%';", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.25, + "peak_rss_kib": 12749212, + "user_seconds": 19.13, + "system_seconds": 4.31 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 6.3130491820002135, + "query": 22, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) c: (count URL) where: (and (like URL \"*google*\") (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), COUNT(*) AS c FROM hits WHERE URL LIKE '%google%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 6.28, + "peak_rss_kib": 15378372, + "user_seconds": 23.79, + "system_seconds": 4.52 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 9.684250721999888, + "query": 23, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) min_title: (min Title) c: (count URL) u: (count (distinct UserID)) where: (and (like Title \"*Google*\") (not (like URL \"*.google.*\")) (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), MIN(Title), COUNT(*) AS c, COUNT(DISTINCT UserID) FROM hits WHERE Title LIKE '%Google%' AND URL NOT LIKE '%.google.%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 9.67, + "peak_rss_kib": 20752816, + "user_seconds": 34.1, + "system_seconds": 8.1 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 2.741317023999727, + "query": 24, + "translations": [], + "rayfall": "(select {from: hits where: (like URL \"*google*\") asc: EventTime take: 10})", + "sql": "SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 2.71, + "peak_rss_kib": 31776108, + "user_seconds": 43.31, + "system_seconds": 10.74 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.6426952319998236, + "query": 25, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: EventTime take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 3531.95, + "process_seconds": 3.6, + "peak_rss_kib": 10439984, + "user_seconds": 11.9, + "system_seconds": 2.13, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.2699823359998845 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 2, column 0: 'galaxy s4 zoom \u0444\u0438\u043b\u044c\u043c' != '\u0444\u0438\u043b\u044c\u043c \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u0431\u0438\u0437\u043d\u0435\u0441\u0430 \u0441\u0435\u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.987415011999474, + "query": 26, + "translations": [], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase where: (!= SearchPhrase \"\") asc: SearchPhrase take: 10})", + "sql": "SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 2849.13, + "process_seconds": 2.96, + "peak_rss_kib": 7627040, + "user_seconds": 9.25, + "system_seconds": 1.62, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.2197323750006035 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.640393693000078, + "query": 27, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: [EventTime SearchPhrase] take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 3516.9, + "process_seconds": 3.58, + "peak_rss_kib": 10493404, + "user_seconds": 12.35, + "system_seconds": 2.04, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.26986020599997573 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.353923423999731, + "query": 28, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: CounterID l: (avg (strlen URL)) c: (count URL) where: (!= URL \"\")}) where: (> c 100000) desc: l take: 25})", + "sql": "SELECT CounterID, AVG(STRLEN(URL)) AS l, COUNT(*) AS c FROM hits WHERE URL <> '' GROUP BY CounterID HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.31, + "peak_rss_kib": 12477232, + "user_seconds": 20.14, + "system_seconds": 4.31 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 2.5928762149997056, + "query": 29, + "translations": [ + "match SQL URL regexp protocol, nonempty host and newline semantics" + ], + "rayfall": "(xcol (select {from: (select {from: hits by: (let p (str-find Referer \"://\") (let s (substr Referer (+ p 4) -1) (let sl (str-find s \"/\") (if (and (or (== (substr Referer 1 7) \"http://\") (== (substr Referer 1 8) \"https://\")) (> sl 0) (nil? (str-find (substr s (+ sl 2) -1) \"\\n\"))) (if (and (== (str-find s \"www.\") 0) (> sl 4)) (substr s 5 (- sl 4)) (substr s 1 sl)) Referer)))) l: (avg (strlen Referer)) c: (count Referer) min_ref: (min Referer) where: (!= Referer \"\")}) where: (> c 100000) desc: l take: 25}) [k l c min_ref])", + "sql": "SELECT REGEXP_REPLACE(Referer, '^https?://(?:www\\.)?([^/]+)/.*$', '\\1') AS k, AVG(STRLEN(Referer)) AS l, COUNT(*) AS c, MIN(Referer) FROM hits WHERE Referer <> '' GROUP BY k HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 2.54, + "peak_rss_kib": 31991564, + "user_seconds": 42.2, + "system_seconds": 8.91 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.5219473319993995, + "query": 30, + "translations": [], + "rayfall": "(select {from: hits s0: (sum ResolutionWidth) s1: (sum (+ ResolutionWidth 1)) s2: (sum (+ ResolutionWidth 2)) s3: (sum (+ ResolutionWidth 3)) s4: (sum (+ ResolutionWidth 4)) s5: (sum (+ ResolutionWidth 5)) s6: (sum (+ ResolutionWidth 6)) s7: (sum (+ ResolutionWidth 7)) s8: (sum (+ ResolutionWidth 8)) s9: (sum (+ ResolutionWidth 9)) s10: (sum (+ ResolutionWidth 10)) s11: (sum (+ ResolutionWidth 11)) s12: (sum (+ ResolutionWidth 12)) s13: (sum (+ ResolutionWidth 13)) s14: (sum (+ ResolutionWidth 14)) s15: (sum (+ ResolutionWidth 15)) s16: (sum (+ ResolutionWidth 16)) s17: (sum (+ ResolutionWidth 17)) s18: (sum (+ ResolutionWidth 18)) s19: (sum (+ ResolutionWidth 19)) s20: (sum (+ ResolutionWidth 20)) s21: (sum (+ ResolutionWidth 21)) s22: (sum (+ ResolutionWidth 22)) s23: (sum (+ ResolutionWidth 23)) s24: (sum (+ ResolutionWidth 24)) s25: (sum (+ ResolutionWidth 25)) s26: (sum (+ ResolutionWidth 26)) s27: (sum (+ ResolutionWidth 27)) s28: (sum (+ ResolutionWidth 28)) s29: (sum (+ ResolutionWidth 29)) s30: (sum (+ ResolutionWidth 30)) s31: (sum (+ ResolutionWidth 31)) s32: (sum (+ ResolutionWidth 32)) s33: (sum (+ ResolutionWidth 33)) s34: (sum (+ ResolutionWidth 34)) s35: (sum (+ ResolutionWidth 35)) s36: (sum (+ ResolutionWidth 36)) s37: (sum (+ ResolutionWidth 37)) s38: (sum (+ ResolutionWidth 38)) s39: (sum (+ ResolutionWidth 39)) s40: (sum (+ ResolutionWidth 40)) s41: (sum (+ ResolutionWidth 41)) s42: (sum (+ ResolutionWidth 42)) s43: (sum (+ ResolutionWidth 43)) s44: (sum (+ ResolutionWidth 44)) s45: (sum (+ ResolutionWidth 45)) s46: (sum (+ ResolutionWidth 46)) s47: (sum (+ ResolutionWidth 47)) s48: (sum (+ ResolutionWidth 48)) s49: (sum (+ ResolutionWidth 49)) s50: (sum (+ ResolutionWidth 50)) s51: (sum (+ ResolutionWidth 51)) s52: (sum (+ ResolutionWidth 52)) s53: (sum (+ ResolutionWidth 53)) s54: (sum (+ ResolutionWidth 54)) s55: (sum (+ ResolutionWidth 55)) s56: (sum (+ ResolutionWidth 56)) s57: (sum (+ ResolutionWidth 57)) s58: (sum (+ ResolutionWidth 58)) s59: (sum (+ ResolutionWidth 59)) s60: (sum (+ ResolutionWidth 60)) s61: (sum (+ ResolutionWidth 61)) s62: (sum (+ ResolutionWidth 62)) s63: (sum (+ ResolutionWidth 63)) s64: (sum (+ ResolutionWidth 64)) s65: (sum (+ ResolutionWidth 65)) s66: (sum (+ ResolutionWidth 66)) s67: (sum (+ ResolutionWidth 67)) s68: (sum (+ ResolutionWidth 68)) s69: (sum (+ ResolutionWidth 69)) s70: (sum (+ ResolutionWidth 70)) s71: (sum (+ ResolutionWidth 71)) s72: (sum (+ ResolutionWidth 72)) s73: (sum (+ ResolutionWidth 73)) s74: (sum (+ ResolutionWidth 74)) s75: (sum (+ ResolutionWidth 75)) s76: (sum (+ ResolutionWidth 76)) s77: (sum (+ ResolutionWidth 77)) s78: (sum (+ ResolutionWidth 78)) s79: (sum (+ ResolutionWidth 79)) s80: (sum (+ ResolutionWidth 80)) s81: (sum (+ ResolutionWidth 81)) s82: (sum (+ ResolutionWidth 82)) s83: (sum (+ ResolutionWidth 83)) s84: (sum (+ ResolutionWidth 84)) s85: (sum (+ ResolutionWidth 85)) s86: (sum (+ ResolutionWidth 86)) s87: (sum (+ ResolutionWidth 87)) s88: (sum (+ ResolutionWidth 88)) s89: (sum (+ ResolutionWidth 89))})", + "sql": "SELECT SUM(ResolutionWidth), SUM(ResolutionWidth + 1), SUM(ResolutionWidth + 2), SUM(ResolutionWidth + 3), SUM(ResolutionWidth + 4), SUM(ResolutionWidth + 5), SUM(ResolutionWidth + 6), SUM(ResolutionWidth + 7), SUM(ResolutionWidth + 8), SUM(ResolutionWidth + 9), SUM(ResolutionWidth + 10), SUM(ResolutionWidth + 11), SUM(ResolutionWidth + 12), SUM(ResolutionWidth + 13), SUM(ResolutionWidth + 14), SUM(ResolutionWidth + 15), SUM(ResolutionWidth + 16), SUM(ResolutionWidth + 17), SUM(ResolutionWidth + 18), SUM(ResolutionWidth + 19), SUM(ResolutionWidth + 20), SUM(ResolutionWidth + 21), SUM(ResolutionWidth + 22), SUM(ResolutionWidth + 23), SUM(ResolutionWidth + 24), SUM(ResolutionWidth + 25), SUM(ResolutionWidth + 26), SUM(ResolutionWidth + 27), SUM(ResolutionWidth + 28), SUM(ResolutionWidth + 29), SUM(ResolutionWidth + 30), SUM(ResolutionWidth + 31), SUM(ResolutionWidth + 32), SUM(ResolutionWidth + 33), SUM(ResolutionWidth + 34), SUM(ResolutionWidth + 35), SUM(ResolutionWidth + 36), SUM(ResolutionWidth + 37), SUM(ResolutionWidth + 38), SUM(ResolutionWidth + 39), SUM(ResolutionWidth + 40), SUM(ResolutionWidth + 41), SUM(ResolutionWidth + 42), SUM(ResolutionWidth + 43), SUM(ResolutionWidth + 44), SUM(ResolutionWidth + 45), SUM(ResolutionWidth + 46), SUM(ResolutionWidth + 47), SUM(ResolutionWidth + 48), SUM(ResolutionWidth + 49), SUM(ResolutionWidth + 50), SUM(ResolutionWidth + 51), SUM(ResolutionWidth + 52), SUM(ResolutionWidth + 53), SUM(ResolutionWidth + 54), SUM(ResolutionWidth + 55), SUM(ResolutionWidth + 56), SUM(ResolutionWidth + 57), SUM(ResolutionWidth + 58), SUM(ResolutionWidth + 59), SUM(ResolutionWidth + 60), SUM(ResolutionWidth + 61), SUM(ResolutionWidth + 62), SUM(ResolutionWidth + 63), SUM(ResolutionWidth + 64), SUM(ResolutionWidth + 65), SUM(ResolutionWidth + 66), SUM(ResolutionWidth + 67), SUM(ResolutionWidth + 68), SUM(ResolutionWidth + 69), SUM(ResolutionWidth + 70), SUM(ResolutionWidth + 71), SUM(ResolutionWidth + 72), SUM(ResolutionWidth + 73), SUM(ResolutionWidth + 74), SUM(ResolutionWidth + 75), SUM(ResolutionWidth + 76), SUM(ResolutionWidth + 77), SUM(ResolutionWidth + 78), SUM(ResolutionWidth + 79), SUM(ResolutionWidth + 80), SUM(ResolutionWidth + 81), SUM(ResolutionWidth + 82), SUM(ResolutionWidth + 83), SUM(ResolutionWidth + 84), SUM(ResolutionWidth + 85), SUM(ResolutionWidth + 86), SUM(ResolutionWidth + 87), SUM(ResolutionWidth + 88), SUM(ResolutionWidth + 89) FROM hits;", + "verified": true, + "query_ms": 402.159, + "process_seconds": 0.46, + "peak_rss_kib": 1456428, + "user_seconds": 1.45, + "system_seconds": 0.35, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.270388840999658 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 4.398490037000556, + "query": 31, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 4270.13, + "process_seconds": 4.35, + "peak_rss_kib": 11402116, + "user_seconds": 14.71, + "system_seconds": 2.46, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4223289579995253 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 9, column 1: '-265917476' != -1125673878", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 4.548407165999379, + "query": 32, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 4447.28, + "process_seconds": 4.52, + "peak_rss_kib": 12565532, + "user_seconds": 16.46, + "system_seconds": 2.77, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.470218436000323 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5581899925183342605' != 7430821073251343496", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.6888607160008178, + "query": 33, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2525.59, + "process_seconds": 2.68, + "peak_rss_kib": 26849556, + "user_seconds": 23.06, + "system_seconds": 9.77, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.4810918140001377 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '7224410078130478461' != 8566928176839891583", + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.255612147000647, + "query": 34, + "translations": [], + "rayfall": "(select {from: hits by: URL c: (count URL) desc: c take: 10})", + "sql": "SELECT URL, COUNT(*) AS c FROM hits GROUP BY URL ORDER BY c DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.2, + "peak_rss_kib": 12776952, + "user_seconds": 19.04, + "system_seconds": 3.96 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.253833794999991, + "query": 35, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: URL c: (count URL) desc: c take: 10}) one: 1 URL: URL c: c})", + "sql": "SELECT 1, URL, COUNT(*) AS c FROM hits GROUP BY 1, URL ORDER BY c DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.21, + "peak_rss_kib": 12901544, + "user_seconds": 18.78, + "system_seconds": 3.91 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.7736502080006176, + "query": 36, + "translations": [ + "align computed-group-key output column order" + ], + "rayfall": "(select {from: hits by: {ClientIP: ClientIP ip1: (- ClientIP 1) ip2: (- ClientIP 2) ip3: (- ClientIP 3)} c: (count ClientIP) desc: c take: 10})", + "sql": "SELECT ClientIP, COUNT(*) AS c, ClientIP - 1, ClientIP - 2, ClientIP - 3 FROM hits GROUP BY ClientIP, ClientIP - 1, ClientIP - 2, ClientIP - 3 ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 662.876, + "process_seconds": 0.73, + "peak_rss_kib": 7094612, + "user_seconds": 6.79, + "system_seconds": 2.45, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3703878790001909 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.656682338999417, + "query": 37, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= URL \"\")) desc: views take: 10})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND URL <> '' GROUP BY URL ORDER BY PageViews DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.63, + "peak_rss_kib": 13928648, + "user_seconds": 20.51, + "system_seconds": 4.28 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.150060204000511, + "query": 38, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: Title views: (count Title) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= Title \"\")) desc: views take: 10})", + "sql": "SELECT Title, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND Title <> '' GROUP BY Title ORDER BY PageViews DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.14, + "peak_rss_kib": 13538876, + "user_seconds": 18.59, + "system_seconds": 5.04 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 5.804852301999745, + "query": 39, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (!= IsLink 0) (== IsDownload 0)) desc: views take: [1000 10]})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND IsLink <> 0 AND IsDownload = 0 GROUP BY URL ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": false, + "diagnostic": "error: range: str_vec_append: pool offset exceeds 4294967295 bytes\n", + "process_seconds": 5.76, + "peak_rss_kib": 14276344, + "user_seconds": 21.06, + "system_seconds": 4.45 + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 2.844032495999272, + "query": 40, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: {TraficSourceID: TraficSourceID SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID Src: (if (and (== SearchEngineID 0) (== AdvEngineID 0)) Referer \"\") Dst: URL} views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0)) desc: views take: [1000 10]})", + "sql": "SELECT TraficSourceID, SearchEngineID, AdvEngineID, CASE WHEN (SearchEngineID = 0 AND AdvEngineID = 0) THEN Referer ELSE '' END AS Src, URL AS Dst, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 GROUP BY TraficSourceID, SearchEngineID, AdvEngineID, Src, Dst ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 2.83, + "peak_rss_kib": 31829532, + "user_seconds": 42.42, + "system_seconds": 10.34 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.6837512299998707, + "query": 41, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [URLHash EventDate] views: (count URLHash) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (in TraficSourceID [-1 6]) (== RefererHash 3594120000172545465)) desc: views take: [100 10]})", + "sql": "SELECT URLHash, EventDate, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND TraficSourceID IN (-1, 6) AND RefererHash = 3594120000172545465 GROUP BY URLHash, EventDate ORDER BY PageViews DESC LIMIT 10 OFFSET 100;", + "verified": true, + "query_ms": 2589.9, + "process_seconds": 2.66, + "peak_rss_kib": 10474972, + "user_seconds": 7.73, + "system_seconds": 2.47, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11676255700058391 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5520570504648279068' != 2054727273000865689", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.9943100970003798, + "query": 42, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [WindowClientWidth WindowClientHeight] views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (== DontCountHits 0) (== URLHash 2868770270353813622)) desc: views take: [10000 10]})", + "sql": "SELECT WindowClientWidth, WindowClientHeight, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND DontCountHits = 0 AND URLHash = 2868770270353813622 GROUP BY WindowClientWidth, WindowClientHeight ORDER BY PageViews DESC LIMIT 10 OFFSET 10000;", + "verified": true, + "query_ms": 2891.42, + "process_seconds": 2.96, + "peak_rss_kib": 12236048, + "user_seconds": 9.85, + "system_seconds": 2.64, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11599820500032365 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '1667' != 1239", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.234604500000387, + "query": 43, + "translations": [ + "date predicates in explicit Unix days", + "minute buckets in explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {M: (xbar EventTime 60)} views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15900 15901]) (== IsRefresh 0) (== DontCountHits 0)) asc: M take: [1000 10]})", + "sql": "SELECT (EventTime // 60) * 60 AS M, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15900 AND EventDate <= 15901 AND IsRefresh = 0 AND DontCountHits = 0 GROUP BY (EventTime // 60) * 60 ORDER BY (EventTime // 60) * 60 LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 2119.17, + "process_seconds": 2.22, + "peak_rss_kib": 8630272, + "user_seconds": 8.65, + "system_seconds": 1.82, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1154094809999151 + }, + "rows": 10, + "mismatch": null + } + ] +} diff --git a/bench/parquet_load/results/2026-09-30-full-query-pushdown-four.json b/bench/parquet_load/results/2026-09-30-full-query-pushdown-four.json new file mode 100644 index 000000000..7381d3afa --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-full-query-pushdown-four.json @@ -0,0 +1,217 @@ +{ + "input": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "input_bytes": 14779976446, + "input_sha256": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f", + "binary_sha256": "25094fe59905832820882003104700081fa28559325bb9b4e812a7f7c478ec24", + "harness_sha256": "50459e3b31c757d9b5ba2c86f4f41979bd27b7c6e3ba0111eba6df37adf44fd6", + "cores": 28, + "timeout_seconds": 180, + "address_space_gib": 48, + "cache": "OS-managed", + "source_types": [ + "I64", + "I16", + "SYM", + "I16", + "I64", + "I32", + "I32", + "I32", + "I32", + "I64", + "I16", + "I16", + "I16", + "SYM", + "SYM", + "I16", + "I16", + "I32", + "I16", + "I32", + "I16", + "I16", + "I16", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "I16", + "SYM", + "SYM", + "I32", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "I16", + "I16", + "I64", + "I16", + "I16", + "I32", + "I16", + "SYM", + "I32", + "I16", + "I16", + "I16", + "I64", + "SYM", + "I32", + "I16", + "I16", + "I16", + "I16", + "I16", + "SYM", + "I64", + "I16", + "I16", + "I16", + "I16", + "I16", + "I32", + "I32", + "I32", + "I16", + "SYM", + "SYM", + "SYM", + "SYM", + "I16", + "I32", + "I32", + "I32", + "I32", + "I32", + "I32", + "I16", + "SYM", + "I64", + "SYM", + "SYM", + "I16", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "I16", + "I64", + "I64", + "I32" + ], + "method": "fresh process per query; query timing excludes result CSV; not official ClickBench score", + "results": [ + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.5262515869999334, + "query": 19, + "translations": [ + "minute from explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {UserID: UserID m: (% (div EventTime 60) 60) SearchPhrase: SearchPhrase} c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, (EventTime // 60) % 60 AS m, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, m, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 3332.85, + "process_seconds": 3.49, + "peak_rss_kib": 18687644, + "user_seconds": 22.46, + "system_seconds": 6.48, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.2248879929993564 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 7.699325904000034, + "query": 24, + "translations": [], + "rayfall": "(select {from: hits where: (like URL \"*google*\") asc: EventTime take: 10})", + "sql": "SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 7633.79, + "process_seconds": 7.68, + "peak_rss_kib": 22979104, + "user_seconds": 137.32, + "system_seconds": 3.3, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 5.3373970440006815 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 48.23443983700054, + "query": 29, + "translations": [ + "match SQL URL regexp protocol, nonempty host and newline semantics" + ], + "rayfall": "(xcol (select {from: (select {from: hits by: (let p (str-find Referer \"://\") (let s (substr Referer (+ p 4) -1) (let sl (str-find s \"/\") (if (and (or (== (substr Referer 1 7) \"http://\") (== (substr Referer 1 8) \"https://\")) (> sl 0) (nil? (str-find (substr s (+ sl 2) -1) \"\\n\"))) (if (and (== (str-find s \"www.\") 0) (> sl 4)) (substr s 5 (- sl 4)) (substr s 1 sl)) Referer)))) l: (avg (strlen Referer)) c: (count Referer) min_ref: (min Referer) where: (!= Referer \"\")}) where: (> c 100000) desc: l take: 25}) [k l c min_ref])", + "sql": "SELECT REGEXP_REPLACE(Referer, '^https?://(?:www\\.)?([^/]+)/.*$', '\\1') AS k, AVG(STRLEN(Referer)) AS l, COUNT(*) AS c, MIN(Referer) FROM hits WHERE Referer <> '' GROUP BY k HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": true, + "query_ms": 47398.7, + "process_seconds": 48.19, + "peak_rss_kib": 38091648, + "user_seconds": 74.99, + "system_seconds": 72.57, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 3.780003896999915 + }, + "rows": 25, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 12.148970331999408, + "query": 40, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: {TraficSourceID: TraficSourceID SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID Src: (if (and (== SearchEngineID 0) (== AdvEngineID 0)) Referer \"\") Dst: URL} views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0)) desc: views take: [1000 10]})", + "sql": "SELECT TraficSourceID, SearchEngineID, AdvEngineID, CASE WHEN (SearchEngineID = 0 AND AdvEngineID = 0) THEN Referer ELSE '' END AS Src, URL AS Dst, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 GROUP BY TraficSourceID, SearchEngineID, AdvEngineID, Src, Dst ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 11702.9, + "process_seconds": 12.12, + "peak_rss_kib": 21186924, + "user_seconds": 43.94, + "system_seconds": 9.36, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.26594505899993237 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-1' != 1", + "rows": 10, + "mismatch": null + } + ] +} diff --git a/bench/parquet_load/results/2026-09-30-full-query-typed.json b/bench/parquet_load/results/2026-09-30-full-query-typed.json new file mode 100644 index 000000000..e0df4c325 --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-full-query-typed.json @@ -0,0 +1,1092 @@ +{ + "input": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "input_bytes": 14779976446, + "input_sha256": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f", + "binary_sha256": "60509b28e4dbb20b2cd59215857048783d3a5004a7ca4b6665cd83783a97e66e", + "harness_sha256": "50459e3b31c757d9b5ba2c86f4f41979bd27b7c6e3ba0111eba6df37adf44fd6", + "cores": 28, + "timeout_seconds": 180, + "address_space_gib": 48, + "cache": "OS-managed", + "source_types": [ + "I64", + "I16", + "SYM", + "I16", + "I64", + "I32", + "I32", + "I32", + "I32", + "I64", + "I16", + "I16", + "I16", + "SYM", + "SYM", + "I16", + "I16", + "I32", + "I16", + "I32", + "I16", + "I16", + "I16", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "I16", + "SYM", + "SYM", + "I32", + "I16", + "I16", + "SYM", + "I16", + "I16", + "I16", + "I16", + "I16", + "I64", + "I16", + "I16", + "I32", + "I16", + "SYM", + "I32", + "I16", + "I16", + "I16", + "I64", + "SYM", + "I32", + "I16", + "I16", + "I16", + "I16", + "I16", + "SYM", + "I64", + "I16", + "I16", + "I16", + "I16", + "I16", + "I32", + "I32", + "I32", + "I16", + "SYM", + "SYM", + "SYM", + "SYM", + "I16", + "I32", + "I32", + "I32", + "I32", + "I32", + "I32", + "I16", + "SYM", + "I64", + "SYM", + "SYM", + "I16", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "SYM", + "I16", + "I64", + "I64", + "I32" + ], + "method": "fresh process per query; query timing excludes result CSV; not official ClickBench score", + "results": [ + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03285814099945128, + "query": 1, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count WatchID)})", + "sql": "SELECT COUNT(*) FROM hits;", + "verified": true, + "query_ms": 7.17354, + "process_seconds": 0.01, + "peak_rss_kib": 17436, + "user_seconds": 0.0, + "system_seconds": 0.0, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1686293669999941 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.26937904999977036, + "query": 2, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count AdvEngineID) where: (!= AdvEngineID 0)})", + "sql": "SELECT COUNT(*) FROM hits WHERE AdvEngineID <> 0;", + "verified": true, + "query_ms": 181.787, + "process_seconds": 0.21, + "peak_rss_kib": 812440, + "user_seconds": 0.71, + "system_seconds": 0.16, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11854833400047937 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.16690540299987333, + "query": 3, + "translations": [], + "rayfall": "(select {from: hits sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth)})", + "sql": "SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits;", + "verified": true, + "query_ms": 119.112, + "process_seconds": 0.13, + "peak_rss_kib": 363376, + "user_seconds": 1.43, + "system_seconds": 0.06, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16916533099993103 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.16913814500003355, + "query": 4, + "translations": [], + "rayfall": "(select {from: hits avg_user: (avg UserID)})", + "sql": "SELECT AVG(UserID) FROM hits;", + "verified": true, + "query_ms": 127.184, + "process_seconds": 0.14, + "peak_rss_kib": 679932, + "user_seconds": 1.61, + "system_seconds": 0.11, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16767160300059913 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.9885153080003874, + "query": 5, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct UserID))})", + "sql": "SELECT COUNT(DISTINCT UserID) FROM hits;", + "verified": true, + "query_ms": 2855.4, + "process_seconds": 2.97, + "peak_rss_kib": 6108032, + "user_seconds": 7.18, + "system_seconds": 2.52, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3173252990000037 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.393589824000628, + "query": 6, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct SearchPhrase))})", + "sql": "SELECT COUNT(DISTINCT SearchPhrase) FROM hits;", + "verified": true, + "query_ms": 3289.56, + "process_seconds": 3.37, + "peak_rss_kib": 4991116, + "user_seconds": 6.89, + "system_seconds": 2.13, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.41761202499947103 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.118920345999868, + "query": 7, + "translations": [], + "rayfall": "(select {from: hits min_date: (min EventDate) max_date: (max EventDate)})", + "sql": "SELECT MIN(EventDate), MAX(EventDate) FROM hits;", + "verified": true, + "query_ms": 80.4467, + "process_seconds": 0.09, + "peak_rss_kib": 309540, + "user_seconds": 0.7, + "system_seconds": 0.07, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11774654199962242 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.21748708599989186, + "query": 8, + "translations": [], + "rayfall": "(select {from: hits by: AdvEngineID c: (count AdvEngineID) where: (!= AdvEngineID 0) desc: c})", + "sql": "SELECT AdvEngineID, COUNT(*) FROM hits WHERE AdvEngineID <> 0 GROUP BY AdvEngineID ORDER BY COUNT(*) DESC;", + "verified": true, + "query_ms": 170.021, + "process_seconds": 0.2, + "peak_rss_kib": 811856, + "user_seconds": 0.42, + "system_seconds": 0.18, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11551216699990619 + }, + "rows": 18, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.427861496999867, + "query": 9, + "translations": [], + "rayfall": "(select {from: hits by: RegionID u: (count (distinct UserID)) desc: u take: 10})", + "sql": "SELECT RegionID, COUNT(DISTINCT UserID) AS u FROM hits GROUP BY RegionID ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 1351.66, + "process_seconds": 1.4, + "peak_rss_kib": 6932152, + "user_seconds": 9.41, + "system_seconds": 2.53, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3704714180003066 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.4800228880003488, + "query": 10, + "translations": [], + "rayfall": "(select {from: hits by: RegionID sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth) u: (count (distinct UserID)) desc: c take: 10})", + "sql": "SELECT RegionID, SUM(AdvEngineID), COUNT(*) AS c, AVG(ResolutionWidth), COUNT(DISTINCT UserID) FROM hits GROUP BY RegionID ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 1360.65, + "process_seconds": 1.46, + "peak_rss_kib": 5372760, + "user_seconds": 6.13, + "system_seconds": 1.67, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.41803293300017685 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.8233189889997448, + "query": 11, + "translations": [], + "rayfall": "(select {from: hits by: MobilePhoneModel u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 742.374, + "process_seconds": 0.81, + "peak_rss_kib": 3002396, + "user_seconds": 3.04, + "system_seconds": 0.91, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16581912599940551 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.0250660430001517, + "query": 12, + "translations": [], + "rayfall": "(select {from: hits by: [MobilePhone MobilePhoneModel] u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhone, MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhone, MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 890.169, + "process_seconds": 0.97, + "peak_rss_kib": 3733552, + "user_seconds": 3.68, + "system_seconds": 1.05, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.17014461500002653 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.028344398000627, + "query": 13, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 1925.57, + "process_seconds": 2.01, + "peak_rss_kib": 3232392, + "user_seconds": 6.57, + "system_seconds": 1.99, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3673564290002105 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.478881611000361, + "query": 14, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase u: (count (distinct UserID)) where: (!= SearchPhrase \"\") desc: u take: 10})", + "sql": "SELECT SearchPhrase, COUNT(DISTINCT UserID) AS u FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 2325.74, + "process_seconds": 2.44, + "peak_rss_kib": 5384136, + "user_seconds": 10.54, + "system_seconds": 2.26, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.5731919769996239 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.279291371999534, + "query": 15, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID SearchPhrase] c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2156.89, + "process_seconds": 2.25, + "peak_rss_kib": 4039180, + "user_seconds": 8.96, + "system_seconds": 1.92, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4199801090007895 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.0288888869999937, + "query": 16, + "translations": [], + "rayfall": "(select {from: hits by: UserID c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, COUNT(*) FROM hits GROUP BY UserID ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 931.109, + "process_seconds": 1.01, + "peak_rss_kib": 8764412, + "user_seconds": 7.56, + "system_seconds": 2.47, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.36759308699947724 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.685129579999739, + "query": 17, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 2519.86, + "process_seconds": 2.63, + "peak_rss_kib": 10672356, + "user_seconds": 15.23, + "system_seconds": 3.99, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6750024019993361 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.68330172900005, + "query": 18, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 2528.99, + "process_seconds": 2.64, + "peak_rss_kib": 10373816, + "user_seconds": 15.2, + "system_seconds": 3.58, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6236823599992931 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-2461439046089301801' != 4074991852422418208", + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 7.667828233000364, + "query": 19, + "translations": [ + "minute from explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {UserID: UserID m: (% (div EventTime 60) 60) SearchPhrase: SearchPhrase} c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, (EventTime // 60) % 60 AS m, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, m, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 7.63, + "peak_rss_kib": 34249680, + "user_seconds": 32.68, + "system_seconds": 7.48 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.21987188799994328, + "query": 20, + "translations": [], + "rayfall": "(select {from: hits UserID: UserID where: (== UserID 435090932899640449)})", + "sql": "SELECT UserID FROM hits WHERE UserID = 435090932899640449;", + "verified": true, + "query_ms": 146.746, + "process_seconds": 0.16, + "peak_rss_kib": 638556, + "user_seconds": 1.8, + "system_seconds": 0.1, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.169922444999429 + }, + "rows": 4, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 5.899256118000267, + "query": 21, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count URL) where: (like URL \"*google*\")})", + "sql": "SELECT COUNT(*) FROM hits WHERE URL LIKE '%google%';", + "verified": true, + "query_ms": 5817.87, + "process_seconds": 5.86, + "peak_rss_kib": 9878836, + "user_seconds": 22.91, + "system_seconds": 4.62, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.7694512199996097 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 8.418335289000424, + "query": 22, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) c: (count URL) where: (and (like URL \"*google*\") (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), COUNT(*) AS c FROM hits WHERE URL LIKE '%google%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 8110.68, + "process_seconds": 8.37, + "peak_rss_kib": 12919224, + "user_seconds": 29.72, + "system_seconds": 6.35, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.7226683449998745 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 8, column 0: '\u043a\u0443\u043f\u0438\u0442\u044c \u0442\u0440\u0443\u0434\u043e\u0432\u0430\u043d\u0456 \u0440\u0435\u0437\u044e\u043c\u0435 \u043c\u0435\u0440\u0442\u043d\u044b\u0439 \u0434\u0438\u043d\u0430 \u043a\u0430\u0431\u0438\u043d\u0441\u043a\u0438\u0439 \u043b\u0435\u0436\u0438\u0442 \u0437\u0430\u0434\u043d\u0435\u0435 \u0443\u0441\u0442\u0430\u043d' != '\u0432\u0441\u043f\u043e\u043c\u043d\u044e \u043e \u043d\u0430\u0437\u0432\u0430\u043d\u044b \u043c\u043e\u043d\u0441\u0442\u044d\u0440'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 11.0331131060002, + "query": 23, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) min_title: (min Title) c: (count URL) u: (count (distinct UserID)) where: (and (like Title \"*Google*\") (not (like URL \"*.google.*\")) (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), MIN(Title), COUNT(*) AS c, COUNT(DISTINCT UserID) FROM hits WHERE Title LIKE '%Google%' AND URL NOT LIKE '%.google.%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 10673.0, + "process_seconds": 10.99, + "peak_rss_kib": 20721556, + "user_seconds": 49.81, + "system_seconds": 10.22, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.3773101179995137 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 7.865829481000219, + "query": 24, + "translations": [], + "rayfall": "(select {from: hits where: (like URL \"*google*\") asc: EventTime take: 10})", + "sql": "SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 7.83, + "peak_rss_kib": 34115560, + "user_seconds": 33.52, + "system_seconds": 7.47 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.4869001139995817, + "query": 25, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: EventTime take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 2338.67, + "process_seconds": 2.46, + "peak_rss_kib": 5124308, + "user_seconds": 10.43, + "system_seconds": 1.95, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.2671937679997427 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '\u043d\u043e\u0447\u043d\u043e \u043a\u0438\u0442\u0430\u044f \u0436\u0435\u043d\u0449\u0438\u043d\u044b' != '\u0444\u0438\u043b\u044c\u043c \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u0431\u0438\u0437\u043d\u0435\u0441\u0430 \u0441\u0435\u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.02908010200008, + "query": 26, + "translations": [], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase where: (!= SearchPhrase \"\") asc: SearchPhrase take: 10})", + "sql": "SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 1917.46, + "process_seconds": 2.01, + "peak_rss_kib": 3205052, + "user_seconds": 7.07, + "system_seconds": 1.64, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.216437138999936 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.5329202829998394, + "query": 27, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: [EventTime SearchPhrase] take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 2374.61, + "process_seconds": 2.49, + "peak_rss_kib": 5131940, + "user_seconds": 10.5, + "system_seconds": 1.98, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.27328733800004557 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.404320011999516, + "query": 28, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: CounterID l: (avg (strlen URL)) c: (count URL) where: (!= URL \"\")}) where: (> c 100000) desc: l take: 25})", + "sql": "SELECT CounterID, AVG(STRLEN(URL)) AS l, COUNT(*) AS c FROM hits WHERE URL <> '' GROUP BY CounterID HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": true, + "query_ms": 6314.53, + "process_seconds": 6.37, + "peak_rss_kib": 10962276, + "user_seconds": 27.54, + "system_seconds": 4.96, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.6204261269995186 + }, + "rows": 25, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 7.662334202000238, + "query": 29, + "translations": [ + "match SQL URL regexp protocol, nonempty host and newline semantics" + ], + "rayfall": "(xcol (select {from: (select {from: hits by: (let p (str-find Referer \"://\") (let s (substr Referer (+ p 4) -1) (let sl (str-find s \"/\") (if (and (or (== (substr Referer 1 7) \"http://\") (== (substr Referer 1 8) \"https://\")) (> sl 0) (nil? (str-find (substr s (+ sl 2) -1) \"\\n\"))) (if (and (== (str-find s \"www.\") 0) (> sl 4)) (substr s 5 (- sl 4)) (substr s 1 sl)) Referer)))) l: (avg (strlen Referer)) c: (count Referer) min_ref: (min Referer) where: (!= Referer \"\")}) where: (> c 100000) desc: l take: 25}) [k l c min_ref])", + "sql": "SELECT REGEXP_REPLACE(Referer, '^https?://(?:www\\.)?([^/]+)/.*$', '\\1') AS k, AVG(STRLEN(Referer)) AS l, COUNT(*) AS c, MIN(Referer) FROM hits WHERE Referer <> '' GROUP BY k HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 7.61, + "peak_rss_kib": 34272760, + "user_seconds": 31.97, + "system_seconds": 7.3 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.3707293289999143, + "query": 30, + "translations": [], + "rayfall": "(select {from: hits s0: (sum ResolutionWidth) s1: (sum (+ ResolutionWidth 1)) s2: (sum (+ ResolutionWidth 2)) s3: (sum (+ ResolutionWidth 3)) s4: (sum (+ ResolutionWidth 4)) s5: (sum (+ ResolutionWidth 5)) s6: (sum (+ ResolutionWidth 6)) s7: (sum (+ ResolutionWidth 7)) s8: (sum (+ ResolutionWidth 8)) s9: (sum (+ ResolutionWidth 9)) s10: (sum (+ ResolutionWidth 10)) s11: (sum (+ ResolutionWidth 11)) s12: (sum (+ ResolutionWidth 12)) s13: (sum (+ ResolutionWidth 13)) s14: (sum (+ ResolutionWidth 14)) s15: (sum (+ ResolutionWidth 15)) s16: (sum (+ ResolutionWidth 16)) s17: (sum (+ ResolutionWidth 17)) s18: (sum (+ ResolutionWidth 18)) s19: (sum (+ ResolutionWidth 19)) s20: (sum (+ ResolutionWidth 20)) s21: (sum (+ ResolutionWidth 21)) s22: (sum (+ ResolutionWidth 22)) s23: (sum (+ ResolutionWidth 23)) s24: (sum (+ ResolutionWidth 24)) s25: (sum (+ ResolutionWidth 25)) s26: (sum (+ ResolutionWidth 26)) s27: (sum (+ ResolutionWidth 27)) s28: (sum (+ ResolutionWidth 28)) s29: (sum (+ ResolutionWidth 29)) s30: (sum (+ ResolutionWidth 30)) s31: (sum (+ ResolutionWidth 31)) s32: (sum (+ ResolutionWidth 32)) s33: (sum (+ ResolutionWidth 33)) s34: (sum (+ ResolutionWidth 34)) s35: (sum (+ ResolutionWidth 35)) s36: (sum (+ ResolutionWidth 36)) s37: (sum (+ ResolutionWidth 37)) s38: (sum (+ ResolutionWidth 38)) s39: (sum (+ ResolutionWidth 39)) s40: (sum (+ ResolutionWidth 40)) s41: (sum (+ ResolutionWidth 41)) s42: (sum (+ ResolutionWidth 42)) s43: (sum (+ ResolutionWidth 43)) s44: (sum (+ ResolutionWidth 44)) s45: (sum (+ ResolutionWidth 45)) s46: (sum (+ ResolutionWidth 46)) s47: (sum (+ ResolutionWidth 47)) s48: (sum (+ ResolutionWidth 48)) s49: (sum (+ ResolutionWidth 49)) s50: (sum (+ ResolutionWidth 50)) s51: (sum (+ ResolutionWidth 51)) s52: (sum (+ ResolutionWidth 52)) s53: (sum (+ ResolutionWidth 53)) s54: (sum (+ ResolutionWidth 54)) s55: (sum (+ ResolutionWidth 55)) s56: (sum (+ ResolutionWidth 56)) s57: (sum (+ ResolutionWidth 57)) s58: (sum (+ ResolutionWidth 58)) s59: (sum (+ ResolutionWidth 59)) s60: (sum (+ ResolutionWidth 60)) s61: (sum (+ ResolutionWidth 61)) s62: (sum (+ ResolutionWidth 62)) s63: (sum (+ ResolutionWidth 63)) s64: (sum (+ ResolutionWidth 64)) s65: (sum (+ ResolutionWidth 65)) s66: (sum (+ ResolutionWidth 66)) s67: (sum (+ ResolutionWidth 67)) s68: (sum (+ ResolutionWidth 68)) s69: (sum (+ ResolutionWidth 69)) s70: (sum (+ ResolutionWidth 70)) s71: (sum (+ ResolutionWidth 71)) s72: (sum (+ ResolutionWidth 72)) s73: (sum (+ ResolutionWidth 73)) s74: (sum (+ ResolutionWidth 74)) s75: (sum (+ ResolutionWidth 75)) s76: (sum (+ ResolutionWidth 76)) s77: (sum (+ ResolutionWidth 77)) s78: (sum (+ ResolutionWidth 78)) s79: (sum (+ ResolutionWidth 79)) s80: (sum (+ ResolutionWidth 80)) s81: (sum (+ ResolutionWidth 81)) s82: (sum (+ ResolutionWidth 82)) s83: (sum (+ ResolutionWidth 83)) s84: (sum (+ ResolutionWidth 84)) s85: (sum (+ ResolutionWidth 85)) s86: (sum (+ ResolutionWidth 86)) s87: (sum (+ ResolutionWidth 87)) s88: (sum (+ ResolutionWidth 88)) s89: (sum (+ ResolutionWidth 89))})", + "sql": "SELECT SUM(ResolutionWidth), SUM(ResolutionWidth + 1), SUM(ResolutionWidth + 2), SUM(ResolutionWidth + 3), SUM(ResolutionWidth + 4), SUM(ResolutionWidth + 5), SUM(ResolutionWidth + 6), SUM(ResolutionWidth + 7), SUM(ResolutionWidth + 8), SUM(ResolutionWidth + 9), SUM(ResolutionWidth + 10), SUM(ResolutionWidth + 11), SUM(ResolutionWidth + 12), SUM(ResolutionWidth + 13), SUM(ResolutionWidth + 14), SUM(ResolutionWidth + 15), SUM(ResolutionWidth + 16), SUM(ResolutionWidth + 17), SUM(ResolutionWidth + 18), SUM(ResolutionWidth + 19), SUM(ResolutionWidth + 20), SUM(ResolutionWidth + 21), SUM(ResolutionWidth + 22), SUM(ResolutionWidth + 23), SUM(ResolutionWidth + 24), SUM(ResolutionWidth + 25), SUM(ResolutionWidth + 26), SUM(ResolutionWidth + 27), SUM(ResolutionWidth + 28), SUM(ResolutionWidth + 29), SUM(ResolutionWidth + 30), SUM(ResolutionWidth + 31), SUM(ResolutionWidth + 32), SUM(ResolutionWidth + 33), SUM(ResolutionWidth + 34), SUM(ResolutionWidth + 35), SUM(ResolutionWidth + 36), SUM(ResolutionWidth + 37), SUM(ResolutionWidth + 38), SUM(ResolutionWidth + 39), SUM(ResolutionWidth + 40), SUM(ResolutionWidth + 41), SUM(ResolutionWidth + 42), SUM(ResolutionWidth + 43), SUM(ResolutionWidth + 44), SUM(ResolutionWidth + 45), SUM(ResolutionWidth + 46), SUM(ResolutionWidth + 47), SUM(ResolutionWidth + 48), SUM(ResolutionWidth + 49), SUM(ResolutionWidth + 50), SUM(ResolutionWidth + 51), SUM(ResolutionWidth + 52), SUM(ResolutionWidth + 53), SUM(ResolutionWidth + 54), SUM(ResolutionWidth + 55), SUM(ResolutionWidth + 56), SUM(ResolutionWidth + 57), SUM(ResolutionWidth + 58), SUM(ResolutionWidth + 59), SUM(ResolutionWidth + 60), SUM(ResolutionWidth + 61), SUM(ResolutionWidth + 62), SUM(ResolutionWidth + 63), SUM(ResolutionWidth + 64), SUM(ResolutionWidth + 65), SUM(ResolutionWidth + 66), SUM(ResolutionWidth + 67), SUM(ResolutionWidth + 68), SUM(ResolutionWidth + 69), SUM(ResolutionWidth + 70), SUM(ResolutionWidth + 71), SUM(ResolutionWidth + 72), SUM(ResolutionWidth + 73), SUM(ResolutionWidth + 74), SUM(ResolutionWidth + 75), SUM(ResolutionWidth + 76), SUM(ResolutionWidth + 77), SUM(ResolutionWidth + 78), SUM(ResolutionWidth + 79), SUM(ResolutionWidth + 80), SUM(ResolutionWidth + 81), SUM(ResolutionWidth + 82), SUM(ResolutionWidth + 83), SUM(ResolutionWidth + 84), SUM(ResolutionWidth + 85), SUM(ResolutionWidth + 86), SUM(ResolutionWidth + 87), SUM(ResolutionWidth + 88), SUM(ResolutionWidth + 89) FROM hits;", + "verified": true, + "query_ms": 304.964, + "process_seconds": 0.34, + "peak_rss_kib": 871368, + "user_seconds": 2.26, + "system_seconds": 0.2, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.26947500799997215 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.7838111269993533, + "query": 31, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2636.5, + "process_seconds": 2.75, + "peak_rss_kib": 6231292, + "user_seconds": 13.57, + "system_seconds": 2.39, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.4192620639996676 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 9, column 1: '-265917476' != -1125673878", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.9858776829996714, + "query": 32, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2833.2, + "process_seconds": 2.96, + "peak_rss_kib": 7641968, + "user_seconds": 14.53, + "system_seconds": 3.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.46834887500062905 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5581899925183342605' != 7710841973835142119", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.389293037999778, + "query": 33, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 2179.15, + "process_seconds": 2.33, + "peak_rss_kib": 25482032, + "user_seconds": 22.33, + "system_seconds": 11.44, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.4814380010002424 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 1, column 0: '6655575552203051303' != 8566928176839891583", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.154720368999733, + "query": 34, + "translations": [], + "rayfall": "(select {from: hits by: URL c: (count URL) desc: c take: 10})", + "sql": "SELECT URL, COUNT(*) AS c FROM hits GROUP BY URL ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 5853.29, + "process_seconds": 6.11, + "peak_rss_kib": 9858940, + "user_seconds": 22.16, + "system_seconds": 5.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.5296903449998354 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.257792037000399, + "query": 35, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: URL c: (count URL) desc: c take: 10}) one: 1 URL: URL c: c})", + "sql": "SELECT 1, URL, COUNT(*) AS c FROM hits GROUP BY 1, URL ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 5970.01, + "process_seconds": 6.23, + "peak_rss_kib": 9882808, + "user_seconds": 22.37, + "system_seconds": 5.22, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 1.4792627910001102 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.7208392429993182, + "query": 36, + "translations": [ + "align computed-group-key output column order" + ], + "rayfall": "(select {from: hits by: {ClientIP: ClientIP ip1: (- ClientIP 1) ip2: (- ClientIP 2) ip3: (- ClientIP 3)} c: (count ClientIP) desc: c take: 10})", + "sql": "SELECT ClientIP, COUNT(*) AS c, ClientIP - 1, ClientIP - 2, ClientIP - 3 FROM hits GROUP BY ClientIP, ClientIP - 1, ClientIP - 2, ClientIP - 3 ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 657.655, + "process_seconds": 0.71, + "peak_rss_kib": 7111424, + "user_seconds": 6.8, + "system_seconds": 2.76, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.3698341770004845 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.5596344850000605, + "query": 37, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= URL \"\")) desc: views take: 10})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND URL <> '' GROUP BY URL ORDER BY PageViews DESC LIMIT 10;", + "verified": true, + "query_ms": 6280.06, + "process_seconds": 6.54, + "peak_rss_kib": 12411068, + "user_seconds": 22.87, + "system_seconds": 5.07, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16522627999984252 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 3.8381257620003453, + "query": 38, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: Title views: (count Title) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= Title \"\")) desc: views take: 10})", + "sql": "SELECT Title, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND Title <> '' GROUP BY Title ORDER BY PageViews DESC LIMIT 10;", + "verified": true, + "query_ms": 3613.33, + "process_seconds": 3.8, + "peak_rss_kib": 8897564, + "user_seconds": 19.96, + "system_seconds": 3.73, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16749053799958347 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 6.304879209000319, + "query": 39, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (!= IsLink 0) (== IsDownload 0)) desc: views take: [1000 10]})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND IsLink <> 0 AND IsDownload = 0 GROUP BY URL ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 5996.62, + "process_seconds": 6.26, + "peak_rss_kib": 12401472, + "user_seconds": 21.19, + "system_seconds": 4.84, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1683041830001457 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: 'http://guide.trashbox' != 'http://omsk/evential/housession%3D%26CompPath%3D728%26height%3D90%26ad%3D1216629/0/index.ru/count=473095172777/page_type=&q=cache/wm/203159'", + "rows": 10, + "mismatch": null + }, + { + "status": "execution_failed", + "returncode": 1, + "wall_seconds": 7.765887487000327, + "query": 40, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: {TraficSourceID: TraficSourceID SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID Src: (if (and (== SearchEngineID 0) (== AdvEngineID 0)) Referer \"\") Dst: URL} views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0)) desc: views take: [1000 10]})", + "sql": "SELECT TraficSourceID, SearchEngineID, AdvEngineID, CASE WHEN (SearchEngineID = 0 AND AdvEngineID = 0) THEN Referer ELSE '' END AS Src, URL AS Dst, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 GROUP BY TraficSourceID, SearchEngineID, AdvEngineID, Src, Dst ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": false, + "diagnostic": "error: oom\n", + "process_seconds": 7.74, + "peak_rss_kib": 34194352, + "user_seconds": 33.75, + "system_seconds": 7.48 + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.180324629000097, + "query": 41, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [URLHash EventDate] views: (count URLHash) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (in TraficSourceID [-1 6]) (== RefererHash 3594120000172545465)) desc: views take: [100 10]})", + "sql": "SELECT URLHash, EventDate, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND TraficSourceID IN (-1, 6) AND RefererHash = 3594120000172545465 GROUP BY URLHash, EventDate ORDER BY PageViews DESC LIMIT 10 OFFSET 100;", + "verified": true, + "query_ms": 2035.77, + "process_seconds": 2.14, + "peak_rss_kib": 8482144, + "user_seconds": 6.88, + "system_seconds": 1.96, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11707251999996515 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5520570504648279068' != 2054727273000865689", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 2.185746731999643, + "query": 42, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [WindowClientWidth WindowClientHeight] views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (== DontCountHits 0) (== URLHash 2868770270353813622)) desc: views take: [10000 10]})", + "sql": "SELECT WindowClientWidth, WindowClientHeight, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND DontCountHits = 0 AND URLHash = 2868770270353813622 GROUP BY WindowClientWidth, WindowClientHeight ORDER BY PageViews DESC LIMIT 10 OFFSET 10000;", + "verified": true, + "query_ms": 2049.66, + "process_seconds": 2.14, + "peak_rss_kib": 8735444, + "user_seconds": 8.64, + "system_seconds": 1.89, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11872322900035215 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '1667' != 1452", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.7300817039995309, + "query": 43, + "translations": [ + "date predicates in explicit Unix days", + "minute buckets in explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {M: (xbar EventTime 60)} views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15900 15901]) (== IsRefresh 0) (== DontCountHits 0)) asc: M take: [1000 10]})", + "sql": "SELECT (EventTime // 60) * 60 AS M, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15900 AND EventDate <= 15901 AND IsRefresh = 0 AND DontCountHits = 0 GROUP BY (EventTime // 60) * 60 ORDER BY (EventTime // 60) * 60 LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 1557.96, + "process_seconds": 1.7, + "peak_rss_kib": 6767744, + "user_seconds": 7.8, + "system_seconds": 1.52, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11727731599967228 + }, + "rows": 10, + "mismatch": null + } + ] +} diff --git a/bench/parquet_load/results/2026-09-30-full.json b/bench/parquet_load/results/2026-09-30-full.json new file mode 100644 index 000000000..288ae556b --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-full.json @@ -0,0 +1,300 @@ +{ + "parquet": "/tmp/rayforce-clickbench-full.parquet", + "csv": "/tmp/rayforce-clickbench-full.csv", + "schema": "/home/hetoku/data/work/ClickBench/rayforce/create.rfl", + "cpu": "x86_64", + "logical_cpus": 28, + "input_bytes": { + "csv": 78462321894, + "parquet": 14779976446 + }, + "page_cache": "OS-managed; no cache eviction", + "timing": "process + native indexes + reopen + output fsync", + "results": [ + { + "kind": "csv", + "cores": 28, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 113.32752734700625, + "process_seconds": 113.24, + "peak_rss_kib": 58674540, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 599.04, + "process_system_seconds": 287.14, + "major_faults": 2448231, + "minor_faults": 27747440, + "input_blocks": 241227928, + "output_blocks": 115319640 + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 77.41400360800617, + "process_seconds": 77.34, + "peak_rss_kib": 58581912, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 210.29, + "process_system_seconds": 150.54, + "major_faults": 530459, + "minor_faults": 24301105, + "input_blocks": 114317128, + "output_blocks": 115473000 + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 80.61949596100021, + "process_seconds": 80.54, + "peak_rss_kib": 58469252, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 210.43, + "process_system_seconds": 137.23, + "major_faults": 356313, + "minor_faults": 24175337, + "input_blocks": 113687256, + "output_blocks": 115523840 + }, + { + "kind": "csv", + "cores": 28, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 112.24722117799683, + "process_seconds": 112.15, + "peak_rss_kib": 59119740, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 594.12, + "process_system_seconds": 347.46, + "major_faults": 3569677, + "minor_faults": 27814692, + "input_blocks": 246783216, + "output_blocks": 115319464 + }, + { + "kind": "csv", + "cores": 28, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 106.6181592560024, + "process_seconds": 106.54, + "peak_rss_kib": 59318048, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 594.21, + "process_system_seconds": 223.63, + "major_faults": 1134039, + "minor_faults": 27823707, + "input_blocks": 229310416, + "output_blocks": 115319608 + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 77.77213038300397, + "process_seconds": 77.68, + "peak_rss_kib": 59003488, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 216.55, + "process_system_seconds": 105.61, + "major_faults": 62650, + "minor_faults": 23789527, + "input_blocks": 113585648, + "output_blocks": 115527440 + }, + { + "kind": "csv", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 124.11329531900992, + "process_seconds": 124.02, + "peak_rss_kib": 59616944, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 321.51, + "process_system_seconds": 102.06, + "major_faults": 1145575, + "minor_faults": 26138488, + "input_blocks": 229296072, + "output_blocks": 115319520 + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 88.2713585869933, + "process_seconds": 88.15, + "peak_rss_kib": 58371056, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 143.36, + "process_system_seconds": 92.03, + "major_faults": 1154374, + "minor_faults": 24736231, + "input_blocks": 118918200, + "output_blocks": 115462408 + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 77.76736017299118, + "process_seconds": 77.69, + "peak_rss_kib": 59143740, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 137.17, + "process_system_seconds": 77.66, + "major_faults": 58103, + "minor_faults": 23787563, + "input_blocks": 113325312, + "output_blocks": 115443744 + }, + { + "kind": "csv", + "cores": 8, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 132.35653024299245, + "process_seconds": 132.29, + "peak_rss_kib": 59492452, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 323.56, + "process_system_seconds": 98.4, + "major_faults": 1163092, + "minor_faults": 26129262, + "input_blocks": 229021576, + "output_blocks": 115319512 + }, + { + "kind": "csv", + "cores": 8, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 102.04142670599686, + "process_seconds": 101.97, + "peak_rss_kib": 59679044, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 327.29, + "process_system_seconds": 95.66, + "major_faults": 1080103, + "minor_faults": 26129965, + "input_blocks": 228740432, + "output_blocks": 115319512 + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 84.28511497400177, + "process_seconds": 84.19, + "peak_rss_kib": 59029200, + "native_bytes": 59042332197, + "verified": true, + "process_user_seconds": 142.96, + "process_system_seconds": 81.79, + "major_faults": 382624, + "minor_faults": 23802495, + "input_blocks": 112813320, + "output_blocks": 115441768 + } + ], + "medians": [ + { + "cores": 28, + "csv": 112.24722117799683, + "parquet": 77.77213038300397, + "csv_over_parquet": 1.4432833538854288 + }, + { + "cores": 8, + "csv": 124.11329531900992, + "parquet": 84.28511497400177, + "csv_over_parquet": 1.4725410928998957 + } + ], + "dataset": "ClickBench complete Athena hits.parquet", + "full_100m_dataset": true, + "dataset_url": "https://datasets.clickhouse.com/hits_compatible/athena/hits.parquet", + "parquet_sha256": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f", + "row_groups": 226, + "cells_per_import": 10499737185, + "binary_sha256": "0aa293660e2c32cfd92fce29c6ac336bf9495ab8143c54532cfc0954ab5added", + "schema_sha256": "2e62ea68186f0afd6dfd5b98c372371c56e8d7b8510eeda21404a46d219b6625", + "base_commit": "95b0b91c2be60954e11ad106f0bf24c8f340b948", + "dirty_worktree": true, + "cpu_model": "Intel Core i7-14700", + "physical_cores": 20, + "cpu_affinity": "0-27; unpinned", + "ram_gib": 62, + "storage": "Samsung SSD 990 PRO 2TB, /dev/nvme0n1p3", + "kernel": "6.17.9-76061709-generic", + "swap": "16 GiB zram plus approximately 4 GiB disk swap; swapping observed, predominantly zram", + "compiler": "GCC 11.4.0, release Makefile flags including -O3 -march=native", + "input_preparation": "Reference SQL CLI 1.1.3 CLI, UTC, headerless CSV exported from the same full Parquet; download/export excluded", + "export_sql": "SET TimeZone='UTC'; SET threads=8; COPY (SELECT * REPLACE (strftime(to_timestamp(\"EventTime\"), '%Y-%m-%d %H:%M:%S') AS \"EventTime\", strftime(DATE '1970-01-01' + \"EventDate\", '%Y-%m-%d') AS \"EventDate\", strftime(to_timestamp(\"ClientEventTime\"), '%Y-%m-%d %H:%M:%S') AS \"ClientEventTime\", strftime(to_timestamp(\"LocalEventTime\"), '%Y-%m-%d %H:%M:%S') AS \"LocalEventTime\") FROM read_parquet('/tmp/rayforce-clickbench-full.parquet')) TO '/tmp/rayforce-clickbench-full.csv' (HEADER false, DELIMITER ',');\n", + "verification": "Every native column name/order, type and value compared with the baseline CSV table. Numeric payload bytes and actual symbol string bytes; independent native-file verifier, outside load timing.", + "verifier_sha256": "32b5543e7331e5986963593c459b3862b4f5c8c52757ccb0f944b5957884e458", + "validation": { + "asan_ubsan_suite": "3971 of 3971 passed", + "concurrent_domain_suite": "43 of 43 passed", + "parquet_suite": "13 of 13 passed", + "reference_rows": 99997497, + "reference_columns": 105, + "highcard_group_test": "An existing test assumed stable unordered group output and failed identically on the earlier binary at 9/28 execution threads. It now requests asc: k and checks every key/count; focused runs with RAYFORCE_CORES=8 and 28 pass. No grouping runtime code changed." + }, + "changes": [ + "OS mutex replaces the shared symbol-domain spinlock", + "Concurrent batch commits recheck distinct misses and retain bulk arena allocation", + "Completed Parquet import dictionary is released before native index construction" + ], + "baseline_medians": [ + { + "cores": 28, + "csv": 123.01205844699871, + "parquet": 108.55062488399562, + "csv_over_parquet": 1.1332229416316812 + }, + { + "cores": 8, + "csv": 135.2072667439934, + "parquet": 99.68813424799009, + "csv_over_parquet": 1.3563025104637207 + } + ], + "notes": [ + "Three repetitions per format/core count, alternating format order; fresh processes and output directories.", + "Input page cache is OS-managed; neither privileged cache eviction nor CPU pinning.", + "All cases use the same ClickBench native schema and index builder; all native outputs have identical size.", + "These are durable conversion measurements, not a 43-query ClickBench score." + ] +} diff --git a/bench/parquet_load/results/2026-09-30-parted-baseline-pair.json b/bench/parquet_load/results/2026-09-30-parted-baseline-pair.json new file mode 100644 index 000000000..8d4d8281d --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-parted-baseline-pair.json @@ -0,0 +1,64 @@ +{ + "parquet": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "csv": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.csv", + "schema": "/home/hetoku/data/work/ClickBench/rayforce/create.rfl", + "cpu": "x86_64", + "logical_cpus": 28, + "layout": "parted", + "binary_sha256": "c937de4742ccc4c1b9a7718fde7e461908fe6cc303664efcdfe7b8c7b7cda1de", + "partitioning": "source order, at most 65536 rows; Parquet also breaks at row-group boundaries", + "input_bytes": { + "csv": 78462321894, + "parquet": 14779976446 + }, + "page_cache": "OS-managed; no cache eviction", + "timing": "process + native indexes + reopen + output fsync", + "results": [ + { + "kind": "csv", + "layout": "parted", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 303.6384903200001, + "process_seconds": 224.54, + "peak_rss_kib": 37541480, + "native_bytes": 47354093389, + "verified": true, + "process_user_seconds": 255.63, + "process_system_seconds": 81.6, + "major_faults": 3830379, + "minor_faults": 11222902, + "input_blocks": 229056896, + "output_blocks": 93676816 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 815.9703892640005, + "process_seconds": 730.66, + "peak_rss_kib": 33051748, + "native_bytes": 47357381941, + "verified": true, + "process_user_seconds": 126.08, + "process_system_seconds": 98.64, + "major_faults": 2967948, + "minor_faults": 7423998, + "input_blocks": 120732632, + "output_blocks": 93743936 + } + ], + "medians": [ + { + "cores": 8, + "csv": 303.6384903200001, + "parquet": 815.9703892640005, + "csv_over_parquet": 0.37211949638746067 + } + ] +} diff --git a/bench/parquet_load/results/2026-09-30-parted-full.json b/bench/parquet_load/results/2026-09-30-parted-full.json new file mode 100644 index 000000000..dbe8aae5c --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-parted-full.json @@ -0,0 +1,291 @@ +{ + "parquet": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "csv": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.csv", + "schema": "/home/hetoku/data/work/ClickBench/rayforce/create.rfl", + "cpu": "x86_64", + "logical_cpus": 28, + "layout": "parted", + "binary_sha256": "3efe1db444730918af49610cb26a313729f54bc3ccc3f15fb61173f84ae0b86b", + "partitioning": "source order, at most 262144 rows; Parquet also breaks at row-group boundaries", + "input_bytes": { + "csv": 78462321894, + "parquet": 14779976446 + }, + "page_cache": "OS-managed; no cache eviction", + "timing": "process + native indexes + reopen + output fsync", + "results": [ + { + "kind": "csv", + "layout": "parted", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 256.1393452430002, + "process_seconds": 236.07, + "peak_rss_kib": 51785808, + "native_bytes": 47319348589, + "verified": true, + "process_user_seconds": 257.92, + "process_system_seconds": 85.05, + "major_faults": 3336774, + "minor_faults": 10056438, + "input_blocks": 213493984, + "output_blocks": 92714256, + "partitions": 382 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 112.99082919500052, + "process_seconds": 83.62, + "peak_rss_kib": 35725252, + "native_bytes": 47323067877, + "verified": true, + "process_user_seconds": 98.7, + "process_system_seconds": 23.06, + "major_faults": 139810, + "minor_faults": 7120349, + "input_blocks": 58546752, + "output_blocks": 92804640, + "partitions": 501 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 8, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 124.39995268499933, + "process_seconds": 97.98, + "peak_rss_kib": 35071760, + "native_bytes": 47323067877, + "verified": true, + "process_user_seconds": 99.4, + "process_system_seconds": 57.48, + "major_faults": 1461602, + "minor_faults": 7120975, + "input_blocks": 79590920, + "output_blocks": 92804640, + "partitions": 501 + }, + { + "kind": "csv", + "layout": "parted", + "cores": 8, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 241.07698825099942, + "process_seconds": 217.41, + "peak_rss_kib": 51542864, + "native_bytes": 47319348589, + "verified": true, + "process_user_seconds": 254.72, + "process_system_seconds": 63.79, + "major_faults": 2242212, + "minor_faults": 10057706, + "input_blocks": 202636992, + "output_blocks": 92714256, + "partitions": 382 + }, + { + "kind": "csv", + "layout": "parted", + "cores": 8, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 239.34283111900004, + "process_seconds": 218.66, + "peak_rss_kib": 52336028, + "native_bytes": 47319348589, + "verified": true, + "process_user_seconds": 255.2, + "process_system_seconds": 74.86, + "major_faults": 3212641, + "minor_faults": 10061161, + "input_blocks": 206734472, + "output_blocks": 92714256, + "partitions": 382 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 8, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 118.80678529500074, + "process_seconds": 92.03, + "peak_rss_kib": 35805068, + "native_bytes": 47323067877, + "verified": true, + "process_user_seconds": 99.98, + "process_system_seconds": 23.47, + "major_faults": 140335, + "minor_faults": 7121620, + "input_blocks": 58306856, + "output_blocks": 92804640, + "partitions": 501 + }, + { + "kind": "csv", + "layout": "parted", + "cores": 28, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 236.88698803100124, + "process_seconds": 215.13, + "peak_rss_kib": 51078224, + "native_bytes": 47319348589, + "verified": true, + "process_user_seconds": 382.01, + "process_system_seconds": 109.4, + "major_faults": 3025829, + "minor_faults": 11729286, + "input_blocks": 208714032, + "output_blocks": 92714256, + "partitions": 382 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 28, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 117.48756107499867, + "process_seconds": 90.82, + "peak_rss_kib": 39592376, + "native_bytes": 47323067877, + "verified": true, + "process_user_seconds": 121.86, + "process_system_seconds": 65.68, + "major_faults": 1118690, + "minor_faults": 7153556, + "input_blocks": 69838432, + "output_blocks": 92804640, + "partitions": 501 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 28, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 127.42098893000002, + "process_seconds": 99.36, + "peak_rss_kib": 42207784, + "native_bytes": 47323067877, + "verified": true, + "process_user_seconds": 117.36, + "process_system_seconds": 78.46, + "major_faults": 1493905, + "minor_faults": 7128859, + "input_blocks": 79802256, + "output_blocks": 92804640, + "partitions": 501 + }, + { + "kind": "csv", + "layout": "parted", + "cores": 28, + "repeat": 1, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 233.3979752840005, + "process_seconds": 212.99, + "peak_rss_kib": 52319624, + "native_bytes": 47319348589, + "verified": true, + "process_user_seconds": 378.37, + "process_system_seconds": 100.75, + "major_faults": 2668055, + "minor_faults": 11758658, + "input_blocks": 204614032, + "output_blocks": 92714256, + "partitions": 382 + }, + { + "kind": "csv", + "layout": "parted", + "cores": 28, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 232.56430443799945, + "process_seconds": 209.35, + "peak_rss_kib": 49401268, + "native_bytes": 47319348589, + "verified": true, + "process_user_seconds": 377.77, + "process_system_seconds": 97.22, + "major_faults": 2432490, + "minor_faults": 11818318, + "input_blocks": 198964792, + "output_blocks": 92714256, + "partitions": 382 + }, + { + "kind": "parquet", + "layout": "parted", + "cores": 28, + "repeat": 2, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 113.43578072499986, + "process_seconds": 86.58, + "peak_rss_kib": 42490876, + "native_bytes": 47323067877, + "verified": true, + "process_user_seconds": 124.48, + "process_system_seconds": 35.05, + "major_faults": 144832, + "minor_faults": 7162751, + "input_blocks": 63020152, + "output_blocks": 92804640, + "partitions": 501 + } + ], + "medians": [ + { + "cores": 8, + "csv": 241.07698825099942, + "parquet": 118.80678529500074, + "csv_over_parquet": 2.0291516823083646 + }, + { + "cores": 28, + "csv": 233.3979752840005, + "parquet": 117.48756107499867, + "csv_over_parquet": 1.9865760523789402 + } + ], + "input_sha256": { + "parquet": "a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f" + }, + "environment": { + "cpu_model": "Intel Core i7-14700", + "physical_cores": 20, + "logical_cpus": 28, + "ram_kib": 65633836, + "kernel": "6.17.9-76061709-generic", + "architecture": "x86_64", + "compiler": "GCC 11.4.0", + "storage": "local NVMe", + "cpu_pinning": false, + "swap": "16 GiB zram plus approximately 4 GiB disk swap" + }, + "harness_sha256": "68da5354ce7276664fbc7c0f8d61a7eeab0a1e86a0f9a7de60cb9eefbe0555e6", + "verifier_sha256": "5314002441122604d847e7c9febb14ca6cab841a7521e7213b34709b8556c1f6", + "validation": "Every source-order cell and native type compared with the retained full CSV splayed reference, resolving symbol dictionaries independently; verification excluded from timing.", + "measured_build_note": "Pinned binary retained under build/parquet-recovery/rayforce-completion. Later write-failure/publication hardening is validated separately; these timings remain attributed to the pinned build." +} diff --git a/bench/parquet_load/results/2026-09-30-parted-sync-diagnostic.json b/bench/parquet_load/results/2026-09-30-parted-sync-diagnostic.json new file mode 100644 index 000000000..bfd9c8d76 --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-parted-sync-diagnostic.json @@ -0,0 +1,40 @@ +{ + "parquet": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.parquet", + "csv": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits.csv", + "schema": "/home/hetoku/data/work/ClickBench/rayforce/create.rfl", + "cpu": "x86_64", + "logical_cpus": 28, + "layout": "parted", + "binary_sha256": "3efe1db444730918af49610cb26a313729f54bc3ccc3f15fb61173f84ae0b86b", + "partitioning": "source order, at most 65536 rows; Parquet also breaks at row-group boundaries", + "input_bytes": { + "csv": 78462321894, + "parquet": 14779976446 + }, + "page_cache": "OS-managed; no cache eviction", + "timing": "process + native indexes + reopen + output fsync", + "results": [ + { + "kind": "parquet", + "layout": "parted", + "cores": 8, + "repeat": 0, + "rows": 99997497, + "columns": 105, + "durable_load_seconds": 231.19439260599938, + "process_seconds": 146.54, + "peak_rss_kib": 34636300, + "native_bytes": 47357381941, + "verified": true, + "process_user_seconds": 101.15, + "process_system_seconds": 27.74, + "major_faults": 342772, + "minor_faults": 7424529, + "input_blocks": 57467768, + "output_blocks": 93743936 + } + ], + "medians": [], + "harness_sha256": "68da5354ce7276664fbc7c0f8d61a7eeab0a1e86a0f9a7de60cb9eefbe0555e6", + "comparison_note": "Single matched-cap diagnostic, not a repeated median; baseline is 2026-09-30-parted-baseline-pair.json." +} diff --git a/bench/parquet_load/results/2026-09-30-sample-queries.json b/bench/parquet_load/results/2026-09-30-sample-queries.json new file mode 100644 index 000000000..f61b222da --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-sample-queries.json @@ -0,0 +1,1015 @@ +{ + "input": "/home/hetoku/data/work/rayforce/build/parquet-recovery/data/hits-1m.parquet", + "input_bytes": 115676812, + "binary_sha256": "c937de4742ccc4c1b9a7718fde7e461908fe6cc303664efcdfe7b8c7b7cda1de", + "cores": 8, + "timeout_seconds": 180, + "address_space_gib": 0, + "cache": "OS-managed", + "method": "fresh process per query; query timing excludes result CSV; not official ClickBench score", + "results": [ + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03260474300032001, + "query": 1, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count WatchID)})", + "sql": "SELECT COUNT(*) FROM hits;", + "verified": true, + "query_ms": 0.681218, + "process_seconds": 0.01, + "peak_rss_kib": 14832, + "user_seconds": 0.0, + "system_seconds": 0.0, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03533250400005272 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06638165399999707, + "query": 2, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count AdvEngineID) where: (!= AdvEngineID 0)})", + "sql": "SELECT COUNT(*) FROM hits WHERE AdvEngineID <> 0;", + "verified": true, + "query_ms": 15.5464, + "process_seconds": 0.03, + "peak_rss_kib": 92996, + "user_seconds": 0.05, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03490731500005495 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03316104100031225, + "query": 3, + "translations": [], + "rayfall": "(select {from: hits sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth)})", + "sql": "SELECT SUM(AdvEngineID), COUNT(*), AVG(ResolutionWidth) FROM hits;", + "verified": true, + "query_ms": 11.5273, + "process_seconds": 0.02, + "peak_rss_kib": 88360, + "user_seconds": 0.04, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03337854499977766 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03248177299974486, + "query": 4, + "translations": [], + "rayfall": "(select {from: hits avg_user: (avg UserID)})", + "sql": "SELECT AVG(UserID) FROM hits;", + "verified": true, + "query_ms": 7.8836, + "process_seconds": 0.01, + "peak_rss_kib": 87788, + "user_seconds": 0.03, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.035013696999612876 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.032912103999933606, + "query": 5, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct UserID))})", + "sql": "SELECT COUNT(DISTINCT UserID) FROM hits;", + "verified": true, + "query_ms": 13.8766, + "process_seconds": 0.02, + "peak_rss_kib": 134104, + "user_seconds": 0.03, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.032588984000085475 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06489298900032736, + "query": 6, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count (distinct SearchPhrase))})", + "sql": "SELECT COUNT(DISTINCT SearchPhrase) FROM hits;", + "verified": true, + "query_ms": 33.2459, + "process_seconds": 0.04, + "peak_rss_kib": 164604, + "user_seconds": 0.06, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03465900099990904 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.034257132000220736, + "query": 7, + "translations": [], + "rayfall": "(select {from: hits min_date: (min EventDate) max_date: (max EventDate)})", + "sql": "SELECT MIN(EventDate), MAX(EventDate) FROM hits;", + "verified": true, + "query_ms": 12.1838, + "process_seconds": 0.02, + "peak_rss_kib": 87032, + "user_seconds": 0.04, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.0671332430001712 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.034565074000056484, + "query": 8, + "translations": [], + "rayfall": "(select {from: hits by: AdvEngineID c: (count AdvEngineID) where: (!= AdvEngineID 0) desc: c})", + "sql": "SELECT AdvEngineID, COUNT(*) FROM hits WHERE AdvEngineID <> 0 GROUP BY AdvEngineID ORDER BY COUNT(*) DESC;", + "verified": true, + "query_ms": 9.38527, + "process_seconds": 0.02, + "peak_rss_kib": 89092, + "user_seconds": 0.03, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03439570199998343 + }, + "rows": 5, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03323243700015155, + "query": 9, + "translations": [], + "rayfall": "(select {from: hits by: RegionID u: (count (distinct UserID)) desc: u take: 10})", + "sql": "SELECT RegionID, COUNT(DISTINCT UserID) AS u FROM hits GROUP BY RegionID ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 16.2953, + "process_seconds": 0.02, + "peak_rss_kib": 147580, + "user_seconds": 0.06, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03345208399969124 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.0657427779997306, + "query": 10, + "translations": [], + "rayfall": "(select {from: hits by: RegionID sum_adv: (sum AdvEngineID) c: (count AdvEngineID) avg_res: (avg ResolutionWidth) u: (count (distinct UserID)) desc: c take: 10})", + "sql": "SELECT RegionID, SUM(AdvEngineID), COUNT(*) AS c, AVG(ResolutionWidth), COUNT(DISTINCT UserID) FROM hits GROUP BY RegionID ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 23.6477, + "process_seconds": 0.03, + "peak_rss_kib": 202444, + "user_seconds": 0.08, + "system_seconds": 0.03, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06584566699984862 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.0667065510001521, + "query": 11, + "translations": [], + "rayfall": "(select {from: hits by: MobilePhoneModel u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 31.5713, + "process_seconds": 0.05, + "peak_rss_kib": 194168, + "user_seconds": 0.07, + "system_seconds": 0.03, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.035771407000083855 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06651968699998179, + "query": 12, + "translations": [], + "rayfall": "(select {from: hits by: [MobilePhone MobilePhoneModel] u: (count (distinct UserID)) where: (!= MobilePhoneModel \"\") desc: u take: 10})", + "sql": "SELECT MobilePhone, MobilePhoneModel, COUNT(DISTINCT UserID) AS u FROM hits WHERE MobilePhoneModel <> '' GROUP BY MobilePhone, MobilePhoneModel ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 31.9316, + "process_seconds": 0.04, + "peak_rss_kib": 195844, + "user_seconds": 0.09, + "system_seconds": 0.03, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06523755299986078 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 9, column 0: '6' != 5", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06460759300034624, + "query": 13, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 37.2502, + "process_seconds": 0.05, + "peak_rss_kib": 171352, + "user_seconds": 0.07, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.033640192999882856 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06566988299982768, + "query": 14, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase u: (count (distinct UserID)) where: (!= SearchPhrase \"\") desc: u take: 10})", + "sql": "SELECT SearchPhrase, COUNT(DISTINCT UserID) AS u FROM hits WHERE SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY u DESC LIMIT 10;", + "verified": true, + "query_ms": 38.8757, + "process_seconds": 0.05, + "peak_rss_kib": 194472, + "user_seconds": 0.09, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.033346544000323775 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06456915399985519, + "query": 15, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID SearchPhrase] c: (count SearchPhrase) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, SearchPhrase, COUNT(*) AS c FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 32.1608, + "process_seconds": 0.04, + "peak_rss_kib": 174860, + "user_seconds": 0.09, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.033649916000285884 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03278648000014073, + "query": 16, + "translations": [], + "rayfall": "(select {from: hits by: UserID c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, COUNT(*) FROM hits GROUP BY UserID ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 12.1321, + "process_seconds": 0.02, + "peak_rss_kib": 116284, + "user_seconds": 0.04, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11715913700027158 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.0676059899997199, + "query": 17, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 39.7357, + "process_seconds": 0.05, + "peak_rss_kib": 218596, + "user_seconds": 0.1, + "system_seconds": 0.05, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.0652938590001213 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06701849299997775, + "query": 18, + "translations": [], + "rayfall": "(select {from: hits by: [UserID SearchPhrase] c: (count UserID) take: 10})", + "sql": "SELECT UserID, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 38.8264, + "process_seconds": 0.05, + "peak_rss_kib": 219008, + "user_seconds": 0.12, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03350632499996209 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-2461439046089301801' != 1985154588147699698", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.9701556270001674, + "query": 19, + "translations": [ + "minute from explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {UserID: UserID m: (% (div EventTime 60) 60) SearchPhrase: SearchPhrase} c: (count UserID) desc: c take: 10})", + "sql": "SELECT UserID, (EventTime // 60) % 60 AS m, SearchPhrase, COUNT(*) FROM hits GROUP BY UserID, m, SearchPhrase ORDER BY COUNT(*) DESC LIMIT 10;", + "verified": true, + "query_ms": 882.225, + "process_seconds": 0.92, + "peak_rss_kib": 4976952, + "user_seconds": 2.26, + "system_seconds": 0.49, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06867870499991113 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 8, column 0: '502693359570399458' != 1508127196834704092", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.035891683000045305, + "query": 20, + "translations": [], + "rayfall": "(select {from: hits UserID: UserID where: (== UserID 435090932899640449)})", + "sql": "SELECT UserID FROM hits WHERE UserID = 435090932899640449;", + "verified": true, + "query_ms": 11.9049, + "process_seconds": 0.02, + "peak_rss_kib": 86892, + "user_seconds": 0.01, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03574813999966864 + }, + "rows": 0, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.1659568670002045, + "query": 21, + "translations": [ + "express scalar count/column access through lazy select" + ], + "rayfall": "(select {from: hits n: (count URL) where: (like URL \"*google*\")})", + "sql": "SELECT COUNT(*) FROM hits WHERE URL LIKE '%google%';", + "verified": true, + "query_ms": 116.346, + "process_seconds": 0.14, + "peak_rss_kib": 649716, + "user_seconds": 0.24, + "system_seconds": 0.1, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.035483609000038996 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.165077397999994, + "query": 22, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) c: (count URL) where: (and (like URL \"*google*\") (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), COUNT(*) AS c FROM hits WHERE URL LIKE '%google%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 134.654, + "process_seconds": 0.15, + "peak_rss_kib": 745616, + "user_seconds": 0.28, + "system_seconds": 0.09, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06575170099995375 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.31800406499996825, + "query": 23, + "translations": [], + "rayfall": "(select {from: hits by: SearchPhrase min_url: (min URL) min_title: (min Title) c: (count URL) u: (count (distinct UserID)) where: (and (like Title \"*Google*\") (not (like URL \"*.google.*\")) (!= SearchPhrase \"\")) desc: c take: 10})", + "sql": "SELECT SearchPhrase, MIN(URL), MIN(Title), COUNT(*) AS c, COUNT(DISTINCT UserID) FROM hits WHERE Title LIKE '%Google%' AND URL NOT LIKE '%.google.%' AND SearchPhrase <> '' GROUP BY SearchPhrase ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 269.735, + "process_seconds": 0.3, + "peak_rss_kib": 1255072, + "user_seconds": 0.58, + "system_seconds": 0.21, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11789890599993669 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 4, column 0: '\u0432\u0435\u0434\u043e\u043c\u043e\u0441\u043a\u0432\u0438\u0442\u0430\u043b\u0438\u044f \u0441\u0442\u0440\u0430\u0446\u0438\u0438' != '\u043a\u043e\u043f\u0442\u0438\u043c\u0438\u0437\u0430\u043d\u043e\u0441\u0442\u0438\u043d\u0438\u0446\u044b'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.9220583179999267, + "query": 24, + "translations": [], + "rayfall": "(select {from: hits where: (like URL \"*google*\") asc: EventTime take: 10})", + "sql": "SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 863.339, + "process_seconds": 0.9, + "peak_rss_kib": 4969516, + "user_seconds": 2.31, + "system_seconds": 0.47, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.16551272500009873 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06682163300001775, + "query": 25, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: EventTime take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime LIMIT 10;", + "verified": true, + "query_ms": 33.4569, + "process_seconds": 0.04, + "peak_rss_kib": 197332, + "user_seconds": 0.1, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06713466399969548 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 5, column 0: '\u043a\u043e\u043f\u0442\u0438\u043c\u0438\u043a\u0432\u0438\u0434\u0432\u0438\u0447 \u0444\u0430\u0440\u0448\u0438\u0440\u043e\u043a\u0441\u0438\u043d' != '\u0432\u0440\u0430\u0433\u0430\u043d\u0440\u043e\u0433 \u0438\u0437 \u043c\u0443\u043b\u044c\u0442\u0438\u043a\u0438 \u0438\u0437 \u0431\u0430\u043a\u043b\u0430\u0436\u0430\u043d\u043e\u0432'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06499345800011724, + "query": 26, + "translations": [], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase where: (!= SearchPhrase \"\") asc: SearchPhrase take: 10})", + "sql": "SELECT SearchPhrase FROM hits WHERE SearchPhrase <> '' ORDER BY SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 26.4849, + "process_seconds": 0.04, + "peak_rss_kib": 149608, + "user_seconds": 0.07, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03349423100007698 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06479307300014625, + "query": 27, + "translations": [ + "retain EventTime projected by the ClickBench Rayforce query" + ], + "rayfall": "(select {from: hits SearchPhrase: SearchPhrase EventTime: EventTime where: (!= SearchPhrase \"\") asc: [EventTime SearchPhrase] take: 10})", + "sql": "SELECT SearchPhrase, EventTime FROM hits WHERE SearchPhrase <> '' ORDER BY EventTime, SearchPhrase LIMIT 10;", + "verified": true, + "query_ms": 26.8134, + "process_seconds": 0.03, + "peak_rss_kib": 196940, + "user_seconds": 0.07, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06758827299972836 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.16726439900003243, + "query": 28, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: CounterID l: (avg (strlen URL)) c: (count URL) where: (!= URL \"\")}) where: (> c 100000) desc: l take: 25})", + "sql": "SELECT CounterID, AVG(STRLEN(URL)) AS l, COUNT(*) AS c FROM hits WHERE URL <> '' GROUP BY CounterID HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": true, + "query_ms": 123.913, + "process_seconds": 0.14, + "peak_rss_kib": 679156, + "user_seconds": 0.26, + "system_seconds": 0.1, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06638393100001849 + }, + "rows": 2, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.0683989470003326, + "query": 29, + "translations": [ + "match SQL URL regexp protocol, nonempty host and newline semantics" + ], + "rayfall": "(xcol (select {from: (select {from: hits by: (let p (str-find Referer \"://\") (let s (substr Referer (+ p 4) -1) (let sl (str-find s \"/\") (if (and (or (== (substr Referer 1 7) \"http://\") (== (substr Referer 1 8) \"https://\")) (> sl 0) (nil? (str-find (substr s (+ sl 2) -1) \"\\n\"))) (if (and (== (str-find s \"www.\") 0) (> sl 4)) (substr s 5 (- sl 4)) (substr s 1 sl)) Referer)))) l: (avg (strlen Referer)) c: (count Referer) min_ref: (min Referer) where: (!= Referer \"\")}) where: (> c 100000) desc: l take: 25}) [k l c min_ref])", + "sql": "SELECT REGEXP_REPLACE(Referer, '^https?://(?:www\\.)?([^/]+)/.*$', '\\1') AS k, AVG(STRLEN(Referer)) AS l, COUNT(*) AS c, MIN(Referer) FROM hits WHERE Referer <> '' GROUP BY k HAVING COUNT(*) > 100000 ORDER BY l DESC LIMIT 25;", + "verified": true, + "query_ms": 985.587, + "process_seconds": 1.02, + "peak_rss_kib": 4956436, + "user_seconds": 2.73, + "system_seconds": 0.62, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.1681792200001837 + }, + "rows": 2, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.03274509600032616, + "query": 30, + "translations": [], + "rayfall": "(select {from: hits s0: (sum ResolutionWidth) s1: (sum (+ ResolutionWidth 1)) s2: (sum (+ ResolutionWidth 2)) s3: (sum (+ ResolutionWidth 3)) s4: (sum (+ ResolutionWidth 4)) s5: (sum (+ ResolutionWidth 5)) s6: (sum (+ ResolutionWidth 6)) s7: (sum (+ ResolutionWidth 7)) s8: (sum (+ ResolutionWidth 8)) s9: (sum (+ ResolutionWidth 9)) s10: (sum (+ ResolutionWidth 10)) s11: (sum (+ ResolutionWidth 11)) s12: (sum (+ ResolutionWidth 12)) s13: (sum (+ ResolutionWidth 13)) s14: (sum (+ ResolutionWidth 14)) s15: (sum (+ ResolutionWidth 15)) s16: (sum (+ ResolutionWidth 16)) s17: (sum (+ ResolutionWidth 17)) s18: (sum (+ ResolutionWidth 18)) s19: (sum (+ ResolutionWidth 19)) s20: (sum (+ ResolutionWidth 20)) s21: (sum (+ ResolutionWidth 21)) s22: (sum (+ ResolutionWidth 22)) s23: (sum (+ ResolutionWidth 23)) s24: (sum (+ ResolutionWidth 24)) s25: (sum (+ ResolutionWidth 25)) s26: (sum (+ ResolutionWidth 26)) s27: (sum (+ ResolutionWidth 27)) s28: (sum (+ ResolutionWidth 28)) s29: (sum (+ ResolutionWidth 29)) s30: (sum (+ ResolutionWidth 30)) s31: (sum (+ ResolutionWidth 31)) s32: (sum (+ ResolutionWidth 32)) s33: (sum (+ ResolutionWidth 33)) s34: (sum (+ ResolutionWidth 34)) s35: (sum (+ ResolutionWidth 35)) s36: (sum (+ ResolutionWidth 36)) s37: (sum (+ ResolutionWidth 37)) s38: (sum (+ ResolutionWidth 38)) s39: (sum (+ ResolutionWidth 39)) s40: (sum (+ ResolutionWidth 40)) s41: (sum (+ ResolutionWidth 41)) s42: (sum (+ ResolutionWidth 42)) s43: (sum (+ ResolutionWidth 43)) s44: (sum (+ ResolutionWidth 44)) s45: (sum (+ ResolutionWidth 45)) s46: (sum (+ ResolutionWidth 46)) s47: (sum (+ ResolutionWidth 47)) s48: (sum (+ ResolutionWidth 48)) s49: (sum (+ ResolutionWidth 49)) s50: (sum (+ ResolutionWidth 50)) s51: (sum (+ ResolutionWidth 51)) s52: (sum (+ ResolutionWidth 52)) s53: (sum (+ ResolutionWidth 53)) s54: (sum (+ ResolutionWidth 54)) s55: (sum (+ ResolutionWidth 55)) s56: (sum (+ ResolutionWidth 56)) s57: (sum (+ ResolutionWidth 57)) s58: (sum (+ ResolutionWidth 58)) s59: (sum (+ ResolutionWidth 59)) s60: (sum (+ ResolutionWidth 60)) s61: (sum (+ ResolutionWidth 61)) s62: (sum (+ ResolutionWidth 62)) s63: (sum (+ ResolutionWidth 63)) s64: (sum (+ ResolutionWidth 64)) s65: (sum (+ ResolutionWidth 65)) s66: (sum (+ ResolutionWidth 66)) s67: (sum (+ ResolutionWidth 67)) s68: (sum (+ ResolutionWidth 68)) s69: (sum (+ ResolutionWidth 69)) s70: (sum (+ ResolutionWidth 70)) s71: (sum (+ ResolutionWidth 71)) s72: (sum (+ ResolutionWidth 72)) s73: (sum (+ ResolutionWidth 73)) s74: (sum (+ ResolutionWidth 74)) s75: (sum (+ ResolutionWidth 75)) s76: (sum (+ ResolutionWidth 76)) s77: (sum (+ ResolutionWidth 77)) s78: (sum (+ ResolutionWidth 78)) s79: (sum (+ ResolutionWidth 79)) s80: (sum (+ ResolutionWidth 80)) s81: (sum (+ ResolutionWidth 81)) s82: (sum (+ ResolutionWidth 82)) s83: (sum (+ ResolutionWidth 83)) s84: (sum (+ ResolutionWidth 84)) s85: (sum (+ ResolutionWidth 85)) s86: (sum (+ ResolutionWidth 86)) s87: (sum (+ ResolutionWidth 87)) s88: (sum (+ ResolutionWidth 88)) s89: (sum (+ ResolutionWidth 89))})", + "sql": "SELECT SUM(ResolutionWidth), SUM(ResolutionWidth + 1), SUM(ResolutionWidth + 2), SUM(ResolutionWidth + 3), SUM(ResolutionWidth + 4), SUM(ResolutionWidth + 5), SUM(ResolutionWidth + 6), SUM(ResolutionWidth + 7), SUM(ResolutionWidth + 8), SUM(ResolutionWidth + 9), SUM(ResolutionWidth + 10), SUM(ResolutionWidth + 11), SUM(ResolutionWidth + 12), SUM(ResolutionWidth + 13), SUM(ResolutionWidth + 14), SUM(ResolutionWidth + 15), SUM(ResolutionWidth + 16), SUM(ResolutionWidth + 17), SUM(ResolutionWidth + 18), SUM(ResolutionWidth + 19), SUM(ResolutionWidth + 20), SUM(ResolutionWidth + 21), SUM(ResolutionWidth + 22), SUM(ResolutionWidth + 23), SUM(ResolutionWidth + 24), SUM(ResolutionWidth + 25), SUM(ResolutionWidth + 26), SUM(ResolutionWidth + 27), SUM(ResolutionWidth + 28), SUM(ResolutionWidth + 29), SUM(ResolutionWidth + 30), SUM(ResolutionWidth + 31), SUM(ResolutionWidth + 32), SUM(ResolutionWidth + 33), SUM(ResolutionWidth + 34), SUM(ResolutionWidth + 35), SUM(ResolutionWidth + 36), SUM(ResolutionWidth + 37), SUM(ResolutionWidth + 38), SUM(ResolutionWidth + 39), SUM(ResolutionWidth + 40), SUM(ResolutionWidth + 41), SUM(ResolutionWidth + 42), SUM(ResolutionWidth + 43), SUM(ResolutionWidth + 44), SUM(ResolutionWidth + 45), SUM(ResolutionWidth + 46), SUM(ResolutionWidth + 47), SUM(ResolutionWidth + 48), SUM(ResolutionWidth + 49), SUM(ResolutionWidth + 50), SUM(ResolutionWidth + 51), SUM(ResolutionWidth + 52), SUM(ResolutionWidth + 53), SUM(ResolutionWidth + 54), SUM(ResolutionWidth + 55), SUM(ResolutionWidth + 56), SUM(ResolutionWidth + 57), SUM(ResolutionWidth + 58), SUM(ResolutionWidth + 59), SUM(ResolutionWidth + 60), SUM(ResolutionWidth + 61), SUM(ResolutionWidth + 62), SUM(ResolutionWidth + 63), SUM(ResolutionWidth + 64), SUM(ResolutionWidth + 65), SUM(ResolutionWidth + 66), SUM(ResolutionWidth + 67), SUM(ResolutionWidth + 68), SUM(ResolutionWidth + 69), SUM(ResolutionWidth + 70), SUM(ResolutionWidth + 71), SUM(ResolutionWidth + 72), SUM(ResolutionWidth + 73), SUM(ResolutionWidth + 74), SUM(ResolutionWidth + 75), SUM(ResolutionWidth + 76), SUM(ResolutionWidth + 77), SUM(ResolutionWidth + 78), SUM(ResolutionWidth + 79), SUM(ResolutionWidth + 80), SUM(ResolutionWidth + 81), SUM(ResolutionWidth + 82), SUM(ResolutionWidth + 83), SUM(ResolutionWidth + 84), SUM(ResolutionWidth + 85), SUM(ResolutionWidth + 86), SUM(ResolutionWidth + 87), SUM(ResolutionWidth + 88), SUM(ResolutionWidth + 89) FROM hits;", + "verified": true, + "query_ms": 9.48387, + "process_seconds": 0.01, + "peak_rss_kib": 88856, + "user_seconds": 0.02, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06787995500008037 + }, + "rows": 1, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06784629599997061, + "query": 31, + "translations": [], + "rayfall": "(select {from: hits by: [SearchEngineID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT SearchEngineID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY SearchEngineID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 41.621, + "process_seconds": 0.06, + "peak_rss_kib": 236868, + "user_seconds": 0.13, + "system_seconds": 0.02, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06504938399984894 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 8, column 1: '1332033259' != 711074589", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06497586400018918, + "query": 32, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) where: (!= SearchPhrase \"\") desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits WHERE SearchPhrase <> '' GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 40.5428, + "process_seconds": 0.05, + "peak_rss_kib": 269392, + "user_seconds": 0.13, + "system_seconds": 0.03, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06560278599999947 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '5581899925183342605' != 5633746978711227448", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06755740900007368, + "query": 33, + "translations": [], + "rayfall": "(select {from: hits by: [WatchID ClientIP] c: (count ClientIP) sum_ref: (sum IsRefresh) avg_res: (avg ResolutionWidth) desc: c take: 10})", + "sql": "SELECT WatchID, ClientIP, COUNT(*) AS c, SUM(IsRefresh), AVG(ResolutionWidth) FROM hits GROUP BY WatchID, ClientIP ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 33.8268, + "process_seconds": 0.04, + "peak_rss_kib": 296776, + "user_seconds": 0.14, + "system_seconds": 0.06, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06633718000011868 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '9110818468285196899' != 5499138540414678913", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.2179268529998808, + "query": 34, + "translations": [], + "rayfall": "(select {from: hits by: URL c: (count URL) desc: c take: 10})", + "sql": "SELECT URL, COUNT(*) AS c FROM hits GROUP BY URL ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 146.505, + "process_seconds": 0.17, + "peak_rss_kib": 687912, + "user_seconds": 0.29, + "system_seconds": 0.12, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06782714400014811 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.21579583499988075, + "query": 35, + "translations": [], + "rayfall": "(select {from: (select {from: hits by: URL c: (count URL) desc: c take: 10}) one: 1 URL: URL c: c})", + "sql": "SELECT 1, URL, COUNT(*) AS c FROM hits GROUP BY 1, URL ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 145.496, + "process_seconds": 0.16, + "peak_rss_kib": 696848, + "user_seconds": 0.33, + "system_seconds": 0.11, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06788168899993252 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.032378891999996995, + "query": 36, + "translations": [ + "align computed-group-key output column order" + ], + "rayfall": "(select {from: hits by: {ClientIP: ClientIP ip1: (- ClientIP 1) ip2: (- ClientIP 2) ip3: (- ClientIP 3)} c: (count ClientIP) desc: c take: 10})", + "sql": "SELECT ClientIP, COUNT(*) AS c, ClientIP - 1, ClientIP - 2, ClientIP - 3 FROM hits GROUP BY ClientIP, ClientIP - 1, ClientIP - 2, ClientIP - 3 ORDER BY c DESC LIMIT 10;", + "verified": true, + "query_ms": 10.5293, + "process_seconds": 0.01, + "peak_rss_kib": 115752, + "user_seconds": 0.04, + "system_seconds": 0.01, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.0330269800001588 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.2149387360000219, + "query": 37, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= URL \"\")) desc: views take: 10})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND URL <> '' GROUP BY URL ORDER BY PageViews DESC LIMIT 10;", + "verified": true, + "query_ms": 149.98, + "process_seconds": 0.17, + "peak_rss_kib": 726068, + "user_seconds": 0.3, + "system_seconds": 0.09, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06774576299994806 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.21505474900004629, + "query": 38, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: Title views: (count Title) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== DontCountHits 0) (== IsRefresh 0) (!= Title \"\")) desc: views take: 10})", + "sql": "SELECT Title, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND DontCountHits = 0 AND IsRefresh = 0 AND Title <> '' GROUP BY Title ORDER BY PageViews DESC LIMIT 10;", + "verified": true, + "query_ms": 184.638, + "process_seconds": 0.2, + "peak_rss_kib": 1051728, + "user_seconds": 0.31, + "system_seconds": 0.13, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.03452004900009342 + }, + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.16491602199994304, + "query": 39, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: URL views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (!= IsLink 0) (== IsDownload 0)) desc: views take: [1000 10]})", + "sql": "SELECT URL, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND IsLink <> 0 AND IsDownload = 0 GROUP BY URL ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 121.094, + "process_seconds": 0.13, + "peak_rss_kib": 727812, + "user_seconds": 0.24, + "system_seconds": 0.09, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.0667391110000608 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: 'http://stalker-pub-20087898675494,960948/#page_type%3D260117152337&spn=1395,9455989.ya.ru/world.ru/a-album/login-9708b4f43421&op_style=0&sale/page6/#overinaeshskiy-r_n/kastroi-baza-dlia-zhienskaia-moda-planet.ee/gardigan-o-radiorecord.ru/izh/kanye_komments' != 'http://radio/places/2021DC&GID=5666.html%3Fmodel=573&op'", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 1.0167839159998948, + "query": 40, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: {TraficSourceID: TraficSourceID SearchEngineID: SearchEngineID AdvEngineID: AdvEngineID Src: (if (and (== SearchEngineID 0) (== AdvEngineID 0)) Referer \"\") Dst: URL} views: (count URL) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0)) desc: views take: [1000 10]})", + "sql": "SELECT TraficSourceID, SearchEngineID, AdvEngineID, CASE WHEN (SearchEngineID = 0 AND AdvEngineID = 0) THEN Referer ELSE '' END AS Src, URL AS Dst, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 GROUP BY TraficSourceID, SearchEngineID, AdvEngineID, Src, Dst ORDER BY PageViews DESC LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 936.222, + "process_seconds": 0.97, + "peak_rss_kib": 4944772, + "user_seconds": 2.31, + "system_seconds": 0.53, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.11932442199986326 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '1' != -1", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06823556899962568, + "query": 41, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [URLHash EventDate] views: (count URLHash) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (in TraficSourceID [-1 6]) (== RefererHash 3594120000172545465)) desc: views take: [100 10]})", + "sql": "SELECT URLHash, EventDate, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND TraficSourceID IN (-1, 6) AND RefererHash = 3594120000172545465 GROUP BY URLHash, EventDate ORDER BY PageViews DESC LIMIT 10 OFFSET 100;", + "verified": true, + "query_ms": 30.4928, + "process_seconds": 0.04, + "peak_rss_kib": 261404, + "user_seconds": 0.12, + "system_seconds": 0.03, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.0678401440000016 + }, + "tie_validation": "rank sequence, full-row oracle membership and multiplicity", + "initial_order_difference": "row 0, column 0: '-2735287073132848640' != -4931472208533333253", + "rows": 10, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06685122099997898, + "query": 42, + "translations": [ + "date predicates in explicit Unix days" + ], + "rayfall": "(select {from: hits by: [WindowClientWidth WindowClientHeight] views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15887 15917]) (== IsRefresh 0) (== DontCountHits 0) (== URLHash 2868770270353813622)) desc: views take: [10000 10]})", + "sql": "SELECT WindowClientWidth, WindowClientHeight, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15887 AND EventDate <= 15917 AND IsRefresh = 0 AND DontCountHits = 0 AND URLHash = 2868770270353813622 GROUP BY WindowClientWidth, WindowClientHeight ORDER BY PageViews DESC LIMIT 10 OFFSET 10000;", + "verified": true, + "query_ms": 36.6131, + "process_seconds": 0.05, + "peak_rss_kib": 300080, + "user_seconds": 0.13, + "system_seconds": 0.04, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.06525526299992634 + }, + "rows": 0, + "mismatch": null + }, + { + "status": "verified", + "returncode": 0, + "wall_seconds": 0.06773741999995764, + "query": 43, + "translations": [ + "date predicates in explicit Unix days", + "minute buckets in explicit Unix seconds" + ], + "rayfall": "(select {from: hits by: {M: (xbar EventTime 60)} views: (count WatchID) where: (and (== CounterID 62) (within EventDate [15900 15901]) (== IsRefresh 0) (== DontCountHits 0)) asc: M take: [1000 10]})", + "sql": "SELECT (EventTime // 60) * 60 AS M, COUNT(*) AS PageViews FROM hits WHERE CounterID = 62 AND EventDate >= 15900 AND EventDate <= 15901 AND IsRefresh = 0 AND DontCountHits = 0 GROUP BY (EventTime // 60) * 60 ORDER BY (EventTime // 60) * 60 LIMIT 10 OFFSET 1000;", + "verified": true, + "query_ms": 31.2928, + "process_seconds": 0.04, + "peak_rss_kib": 262180, + "user_seconds": 0.12, + "system_seconds": 0.04, + "oracle": { + "status": "executed", + "returncode": 0, + "wall_seconds": 0.0668575590002547 + }, + "rows": 10, + "mismatch": null + } + ] +} diff --git a/bench/parquet_load/results/2026-09-30-validation.json b/bench/parquet_load/results/2026-09-30-validation.json new file mode 100644 index 000000000..a624372dc --- /dev/null +++ b/bench/parquet_load/results/2026-09-30-validation.json @@ -0,0 +1,109 @@ +{ + "date": "2026-09-30", + "scope": "Native flat Parquet adapter and full ClickBench evidence; broader P2\u2013P6 roadmap remains partial", + "platform": "Linux x86_64, Intel Core i7-14700", + "sanitizers": { + "passed": 3978, + "failed": 0, + "skipped": 0, + "command": "make test -j8", + "log": "build/parquet-recovery/test-final-full.log" + }, + "scalar_decoder": { + "passed": 14, + "failed": 0, + "method": "Recompile src/io/parquet.c with -U__SSE2__ and ASan/UBSan; link against sanitized library/test objects; run -f parquet", + "log": "build/parquet-recovery/test-parquet-scalar.log" + }, + "fuzz": { + "returncode": 0, + "executed_inputs": 9600493, + "seconds": 601, + "peak_rss_mib": 1053, + "sanitizer_findings": 0, + "command": "setarch x86_64 -R env ASAN_OPTIONS=detect_leaks=1:abort_on_error=1 build_fuzz/fuzz_parquet fuzz/corpus/parquet fuzz/seeds/parquet -rss_limit_mb=4096 -timeout=10 -max_len=16384 -print_final_stats=1 -artifact_prefix=build/parquet-recovery/fuzz/ -max_total_time=600", + "build": "make build_fuzz/fuzz_parquet -j8 FUZZ_LDEXTRA=-L/usr/lib/gcc/x86_64-linux-gnu/11", + "log": "build/parquet-recovery/fuzz-parquet-final.log", + "setup_notes": [ + "Initial Clang link needed the installed GCC 11 C++ library search path.", + "Initial startup segfaulted before processing input; an empty-input replay passed, and the sustained run used the existing reduced-ASLR workaround.", + "No ASan, UBSan or LSan diagnostics appeared in the successful full-run log." + ], + "limits": "Serial decoder/pruning harness, at most 256 batches of 257 rows per input; does not cover parallel scheduling or native publication." + }, + "full_dataset": { + "rows": 99997497, + "columns": 105, + "cells_per_load": 10499737185, + "direct_queries_verified": 43, + "partitioned_cases_verified": 12, + "query_report": "2026-09-30-full-queries.json", + "load_report": "2026-09-30-parted-full.json", + "measured_binary_sha256": "3efe1db444730918af49610cb26a313729f54bc3ccc3f15fb61173f84ae0b86b" + }, + "failure_injection": { + "old_binary": { + "returncode": 0, + "published": true, + "stdout": "", + "stderr": "", + "file_size_limit": 64 + }, + "fixed_sanitized_binary": { + "returncode": 1, + "published": false, + "staging_retained": true, + "stdout": "", + "stderr": "error: io: parquet: native partition write failed\n", + "file_size_limit": 64 + }, + "fixed_release_binary": { + "returncode": 1, + "published": false, + "staging_retained": true, + "stdout": "", + "stderr": "error: io: parquet: native partition write failed\n", + "file_size_limit": 64 + } + }, + "harness_regressions": { + "passed": true, + "checks": [ + "load/query completed cases retained", + "partial output archived", + "changed source/settings rejected", + "native numeric corruption rejected", + "native dictionary-text corruption rejected" + ], + "command": "python3 scripts/parquet-harness-selftest.py build/parquet-recovery/data/hits-1m.parquet --rayforce ./rayforce --native-verifier build/parquet-recovery/verify-native --work-dir build/parquet-recovery/harness-resume-tests", + "log": "build/parquet-recovery/test-harness-resume.log" + }, + "release": { + "command": "make -B release -j8 TARGET=build/parquet-recovery/rayforce-final", + "path": "build/parquet-recovery/rayforce-final", + "bytes": 5371656, + "sha256": "c279da830779bb186dff5d700f389cc216762dd9758dcb5aa73da1ba2f096d61", + "needed_libraries": [ + "libm.so.6", + "libc.so.6", + "ld-linux-x86-64.so.2" + ], + "native_smoke": { + "rows": 1000, + "columns": 105, + "splayed_verified": true, + "parted_verified": true + }, + "changes_since_measured_build": [ + "Propagate buffered column fclose failures before rename.", + "Publish new CSV/Parquet destinations with exclusive rename.", + "Disable Parquet import writes in fuzz builds only." + ] + }, + "docs": { + "passed": true, + "command": "mkdocs build --strict --site-dir build/parquet-recovery/site", + "log": "build/parquet-recovery/docs-build.log" + }, + "remaining_plan": "docs/parquet-completion-plan.md" +} diff --git a/bench/parquet_load/results/2026-09-30.json b/bench/parquet_load/results/2026-09-30.json new file mode 100644 index 000000000..4b4948d6a --- /dev/null +++ b/bench/parquet_load/results/2026-09-30.json @@ -0,0 +1,291 @@ +{ + "parquet": "/tmp/rayforce-clickbench-8rg.parquet", + "csv": "/tmp/rayforce-clickbench-8rg.csv", + "schema": "/home/hetoku/data/work/ClickBench/rayforce/create.rfl", + "page_cache": "OS-managed; no cache eviction", + "timing": "process + native indexes + reopen + output fsync", + "results": [ + { + "kind": "csv", + "cores": 1, + "repeat": 0, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 8.619528122988413, + "process_seconds": 8.53, + "peak_rss_kib": 3532424, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 1, + "repeat": 0, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 4.6923914270009845, + "process_seconds": 4.63, + "peak_rss_kib": 3326132, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 1, + "repeat": 1, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 4.789084106989321, + "process_seconds": 4.73, + "peak_rss_kib": 3325860, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 1, + "repeat": 1, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 8.65201945300214, + "process_seconds": 8.56, + "peak_rss_kib": 3532692, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 1, + "repeat": 2, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 8.74717317300383, + "process_seconds": 8.52, + "peak_rss_kib": 3532348, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 1, + "repeat": 2, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 4.6113874959992245, + "process_seconds": 4.55, + "peak_rss_kib": 3327384, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 8, + "repeat": 0, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.7667662469903007, + "process_seconds": 2.69, + "peak_rss_kib": 3849720, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 0, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 1.638353346992517, + "process_seconds": 1.57, + "peak_rss_kib": 3723756, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 1, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 1.661491525999736, + "process_seconds": 1.6, + "peak_rss_kib": 3694116, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 8, + "repeat": 1, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.575383318006061, + "process_seconds": 2.49, + "peak_rss_kib": 3851152, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 8, + "repeat": 2, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.6272437120060204, + "process_seconds": 2.52, + "peak_rss_kib": 3850644, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 8, + "repeat": 2, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 1.728464215004351, + "process_seconds": 1.66, + "peak_rss_kib": 3723888, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 28, + "repeat": 0, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.309884261994739, + "process_seconds": 2.21, + "peak_rss_kib": 4058276, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 0, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.0614602970017586, + "process_seconds": 2.0, + "peak_rss_kib": 4032552, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 1, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.1139418789971387, + "process_seconds": 2.05, + "peak_rss_kib": 4041272, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 28, + "repeat": 1, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.218596715989406, + "process_seconds": 2.15, + "peak_rss_kib": 4058092, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "csv", + "cores": 28, + "repeat": 2, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.361339034003322, + "process_seconds": 2.26, + "peak_rss_kib": 4057912, + "native_bytes": 2195585704, + "verified": true + }, + { + "kind": "parquet", + "cores": 28, + "repeat": 2, + "rows": 3266382, + "columns": 105, + "durable_load_seconds": 2.0892868819937576, + "process_seconds": 2.03, + "peak_rss_kib": 4038620, + "native_bytes": 2195585704, + "verified": true + } + ], + "medians": [ + { + "cores": 1, + "csv": 8.65201945300214, + "parquet": 4.6923914270009845, + "csv_over_parquet": 1.8438400946725464 + }, + { + "cores": 8, + "csv": 2.6272437120060204, + "parquet": 1.661491525999736, + "csv_over_parquet": 1.5812561610419178 + }, + { + "cores": 28, + "csv": 2.309884261994739, + "parquet": 2.0892868819937576, + "csv_over_parquet": 1.1055850117579213 + } + ], + "date": "2026-09-30", + "cpu": "Intel Core i7-14700", + "logical_cpus": 28, + "ram_gib": 62, + "source_url": "https://datasets.clickhouse.com/hits_compatible/athena/hits.parquet", + "original_row_groups": 8, + "rows": 3266382, + "columns": 105, + "compared_cells_per_import": 342970110, + "full_100m_dataset": false, + "repeats_per_case": 3, + "alternating_order": true, + "csv_preparation": "Reference SQL CLI 1.1.3 export of the same original Parquet rows; headerless CSV; SET TimeZone='UTC'; format raw Unix seconds/days as ISO timestamps/dates", + "build": "release, -O3 -march=native; no third-party libraries", + "binary_sha256": "e7ccf08863a33b17dfdf1cb01202160dcddc6fccb3f306f1c08a2d5ae7eed201", + "baseline_commit": "95b0b91c2be60954e11ad106f0bf24c8f340b948", + "worktree_changes": true, + "input_bytes": { + "parquet": 594562209, + "csv": 2722297967 + }, + "source_parquet_sha256": "8806e5d33f823ec8ce0195836111cdc55277d6b22133dfd7261d055a3004095c", + "validation": { + "asan_ubsan_suite": { + "passed": 3970, + "failed": 0 + }, + "multigroup_oracle_queries": { + "passed": 12, + "cores": 28, + "rows": 3266382 + }, + "typed_parted_growing_dictionary": { + "cores": [ + 1, + 8, + 28 + ], + "rows": 44009, + "row_groups": 7, + "all_cells_match": true + }, + "csv_prepare_option_verified": true, + "final_release_sha256": "6d2b4d2e65d94b0627b1441227e21d6cb9e37a46640d6cc04faacec45c2a6d1d" + }, + "timed_binary_note": "The recorded binary measured CSV and splayed Parquet imports. Subsequent fixes affect only typed partitioned conversion; its final build is recorded under validation." +} diff --git a/bench/parquet_load/verify-native.c b/bench/parquet_load/verify-native.c new file mode 100644 index 000000000..e95afd6ca --- /dev/null +++ b/bench/parquet_load/verify-native.c @@ -0,0 +1,140 @@ +/* Exact, bounded-memory comparison for the fixed-width ClickBench native schema. + * No runtime symbol interning: check each distinct symbol mapping by its bytes, + * then compare IDs through that mapping. Derived indexes are not data payload. + * Build: cc -O3 -Iinclude bench/parquet_load/verify-native.c -o verify-native + * Usage: verify-native LEFT RIGHT COLUMN ... + * verify-native --parted TABLE LEFT_SPLAYED RIGHT_PARTED COLUMN ... + */ +#define _POSIX_C_SOURCE 200809L +#include "rayforce.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void fail(const char* message) { fprintf(stderr,"%s\n",message); exit(1); } +typedef struct { unsigned char* data; size_t size; } mapping; +static mapping map_file(const char* root, const char* name) { + char path[4096]; + if (snprintf(path,sizeof(path),"%s/%s",root,name) >= (int)sizeof(path)) fail("path too long"); + int fd = open(path,O_RDONLY); struct stat st; + if (fd < 0 || fstat(fd,&st) || st.st_size < 32) fail(path); + mapping m = {mmap(NULL,(size_t)st.st_size,PROT_READ,MAP_PRIVATE,fd,0),(size_t)st.st_size}; + close(fd); if (m.data == MAP_FAILED) fail("mmap failed"); return m; +} +static void unmap_file(mapping m) { munmap(m.data,m.size); } +static uint32_t u32(const void* p) { uint32_t x; memcpy(&x,p,4); return x; } +static uint64_t u64(const void* p) { uint64_t x; memcpy(&x,p,8); return x; } +typedef struct { mapping file; uint64_t count; size_t* offsets; } domain; +static domain read_domain(const char* root) { + domain d = {.file=map_file(root,".sym")}; + if (u32(d.file.data) != 0x4c525453) fail("unexpected symbol file magic"); + d.count = u64(d.file.data+4); + if (d.count > (d.file.size-12)/4) fail("invalid symbol count"); + d.offsets = malloc(d.count*sizeof(*d.offsets)); + if (!d.offsets) fail("offset allocation failed"); + size_t off=12; + for (uint64_t i=0;i d.file.size-4) fail("truncated symbol length"); + d.offsets[i]=off; uint32_t len=u32(d.file.data+off); off+=4; + if (len > d.file.size-off) fail("truncated symbol bytes"); + off+=len; + } + if (off != d.file.size) fail("unexpected symbol file suffix"); + return d; +} +static int symbol_equal(domain* a, uint64_t x, domain* b, uint64_t y) { + const unsigned char* p=a->file.data+a->offsets[x]; + const unsigned char* q=b->file.data+b->offsets[y]; + uint32_t n=u32(p); return n==u32(q) && !memcmp(p+4,q+4,n); +} +static size_t width(const ray_t* h) { + static const size_t sizes[]={0,1,1,2,4,8,4,8,4,4,8,16}; + if (h->type==RAY_SYM) return (size_t)1 << (h->attrs&3); + if (h->type<1 || h->type>RAY_GUID) fail("unsupported column type"); + return sizes[h->type]; +} +static uint64_t id(const unsigned char* p,size_t w) { + uint64_t v=0; memcpy(&v,p,w); return v; +} +static int part_order(const void* a,const void* b) { + int64_t x=*(const int64_t*)a,y=*(const int64_t*)b; + return (x>y)-(x2 && !strcmp(argv[1],"--parted")) { table=argv[2]; argv+=2; argc-=2; } + if (argc<4) fail("usage: verify-native LEFT RIGHT COLUMN ..."); + int64_t* parts=NULL; size_t nparts=1; + if(table) { + DIR* d=opendir(argv[2]); if(!d) fail("cannot open parted root"); + struct dirent* ent; nparts=0; + while((ent=readdir(d))) { + if(ent->d_name[0]=='.') continue; + char* end; errno=0; long long p=strtoll(ent->d_name,&end,10); + if(errno || *end || p<0 || end==ent->d_name) fail("invalid partition name"); + int64_t* grown=realloc(parts,(nparts+1)*sizeof(*parts)); + if(!grown) fail("partition allocation failed"); + parts=grown; parts[nparts++]=p; + } + closedir(d); if(!nparts) fail("no partitions"); + qsort(parts,nparts,sizeof(*parts),part_order); + for(size_t p=0;p=(int)sizeof(leaf)) fail("partition path too long"); + mapping schema_b=map_file(leaf,".d"); + if(schema_a.size!=schema_b.size || memcmp(schema_a.data,schema_b.data,schema_a.size)) fail("column names/order mismatch"); + unmap_file(schema_b); + int64_t rows=-1; + for(int c=3;c=0 && rows!=y.len) || + (total>=0 && total!=x.len) || offset>x.len || y.len>x.len-offset) fail("column schema mismatch"); + total=x.len; rows=y.len; size_t wx=width(&x),wy=width(&y); + if ((uint64_t)total>(a.size-32)/wx || (uint64_t)rows>(b.size-32)/wy) fail("truncated column"); + if (x.type==RAY_SYM) { + for(int64_t r=0;r=left.count || j>=right.count) fail("symbol outside domain"); + if(translated[j]!=i) { + if(!symbol_equal(&left,i,&right,j)) { + fprintf(stderr,"symbol mismatch column %s row %lld\n",argv[c],(long long)r); return 1; + } + translated[j]=i; + } + } + } else if(memcmp(a.data+32+(size_t)offset*wx,b.data+32,(size_t)rows*wx)) { + fprintf(stderr,"value mismatch column %s\n",argv[c]); return 1; + } + if(!table) { printf("verified %s %lld\n",argv[c],(long long)rows); fflush(stdout); } + unmap_file(a); unmap_file(b); + } + offset+=rows; + if(table) { printf("verified partition %zu rows %lld\n",part,(long long)rows); fflush(stdout); } + } + if(offset!=total) fail("total row count mismatch"); + printf("VERIFIED %lld rows %d columns %zu partitions\n",(long long)total,argc-3,nparts); + free(parts);unmap_file(schema_a); + free(translated);free(left.offsets);free(right.offsets);unmap_file(left.file);unmap_file(right.file); + return 0; +} diff --git a/docs/docs/architecture/offloading.md b/docs/docs/architecture/offloading.md index 8e1753f9f..26e8f2ea0 100644 --- a/docs/docs/architecture/offloading.md +++ b/docs/docs/architecture/offloading.md @@ -146,4 +146,4 @@ When adding new element-wise operations to Rayforce, they must be added to the ` - **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. -- **Container memory detection** — on Linux, `sysconf(_SC_PHYS_PAGES)` reports host physical RAM, not the container's cgroup memory limit. A future release will read `/sys/fs/cgroup/memory.max` when available. +- **Container memory detection** — on Linux the anon watermark (spill threshold) is capped by the cgroup memory limit (`memory.max` / `memory.limit_in_bytes`, nearest ancestor included), but `.sys.info` → `total-mem` still reports host physical RAM. diff --git a/docs/docs/architecture/pipeline.md b/docs/docs/architecture/pipeline.md index a18921ceb..a2a8f438a 100644 --- a/docs/docs/architecture/pipeline.md +++ b/docs/docs/architecture/pipeline.md @@ -201,6 +201,8 @@ This three-tier scheme means that fully-passing or fully-failing morsels (which 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. +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). + ### 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). @@ -221,6 +223,9 @@ Grouped aggregates run on the parallel aggregation engine, which picks a strateg - **Radix** — unbounded integer or symbol keys (many-million-group inputs) are hash-partitioned and reduced per partition. - **Shared directory** — float, string, GUID, and list keys use a shared parallel key directory. +Without an explicit ordering clause, full grouped results can follow the selected +strategy's group order. Use `asc:` or `desc:` when result positions matter. + Arithmetic over aggregates (`(- (max v1) (min v2))`, `(pow (pearson_corr a b) 2)`) is decomposed at compile time: the aggregates run as hidden slots inside the same group pass, and the outer expression is evaluated once over the grouped result. This applies to any number of keys and to binary aggregates. Ordered top-N clauses (`desc: c take: 10`, `asc: m take: 5`) are selected inside the strategies: radix partitions and dense finishes finalize the ordering aggregate to one value per group in parallel, keep a bounded candidate set each, take the threshold from the union, and emit only the kept groups (ties included), so a 10M-group query never materializes 10M output rows. Routes that emit every group trim afterwards with the same decision. An unordered `take: N` emits the first N groups in first-seen order; on the dense task-local path that is a selection of the N smallest first rows. The radix full path restores first-seen order with a scatter, count and compaction that are all dispatched across the pool. diff --git a/docs/docs/guides/memory.md b/docs/docs/guides/memory.md index ba1780ea8..b160e38cb 100644 --- a/docs/docs/guides/memory.md +++ b/docs/docs/guides/memory.md @@ -8,7 +8,7 @@ Rayforce uses a custom memory subsystem — no calls to `malloc` or `free` ever - **Slab cache** — Small allocations (common for atoms and short vectors) are served from pre-sized slab pools, avoiding buddy-tree overhead. - **COW ref counting** — Vectors use copy-on-write semantics via `ray_retain`/`ray_release`. Shared vectors are only copied when mutated. Note that `ray_retain`/`ray_release`/`ray_cow` are no-ops on `RAY_ERROR` objects, so an error block must be reclaimed with `ray_error_free()` rather than `ray_release()`. - **Arena allocator** — For bulk short-lived blocks (e.g., intermediate query results). Arena objects carry an `RAY_ATTR_ARENA` flag that makes retain/release no-ops. The entire arena is freed at once when work completes. -- **Out-of-core spill** — There is no enforced memory ceiling. The heap tracks how much anonymous (RAM) memory it has committed; once an allocation would push that past the **anon watermark** (total physical RAM by default), it is backed by a preallocated disk file instead of anonymous RAM. File-backed pages are always reclaimable to disk, so they can't trigger the OOM killer — the working set spills and the query completes (slowly) rather than being killed. This never rejects work. Total physical RAM is detected at startup for this threshold and for reporting (see `.sys.info` → `total-mem`). +- **Out-of-core spill** — There is no enforced memory ceiling. The heap tracks how much anonymous (RAM) memory it has committed; once an allocation would push that past the **anon watermark** (by default total physical RAM, or the container's cgroup memory limit when that is smaller — `docker run --memory`, systemd `MemoryMax=`; `-m SIZE` overrides it), it is backed by a preallocated disk file instead of anonymous RAM. File-backed pages are always reclaimable to disk, so they can't trigger the OOM killer — the working set spills and the query completes (slowly) rather than being killed. This never rejects work. Total physical RAM is detected at startup for this threshold and for reporting (see `.sys.info` → `total-mem`). For a deep dive into the allocator internals, see [Memory Model](../architecture/memory.md). @@ -232,8 +232,10 @@ disk-full error. **The anon watermark.** So the heap tracks the anonymous (RAM-resident) bytes it has committed, and when a new pool or large allocation would push that past the -watermark — total physical RAM by default — it backs that allocation with a disk -spill file **instead of** anonymous RAM. This never rejects work; it just routes +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), or the `-m SIZE` flag when given — 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 completes (slowly) instead of being terminated. The progress bar's `used / total` diff --git a/docs/docs/guides/storage.md b/docs/docs/guides/storage.md index 19efc763f..03c4bad7d 100644 --- a/docs/docs/guides/storage.md +++ b/docs/docs/guides/storage.md @@ -211,3 +211,468 @@ Splayed table loading can also use mmap internally. For most analytics workloads - [**Core C API**](../c-api/core.md) — Working with `ray_t` objects, vectors, and tables in C - [**Memory Model**](../architecture/memory.md) — Buddy allocator, arenas, COW, and per-VM heaps - [**Getting Started Tutorial**](../getting-started/tutorial.md) — Hands-on introduction to Rayfall + +## Parquet input + +Rayforce's Parquet reader is implemented in C, including the Thrift Compact +Protocol parser and Snappy decoder. It adds no library dependencies. The same +batch decoder serves materialized reads, streaming callbacks, and native +conversion. + +```lisp +;; Footer inventory: one row per column chunk; no data pages decoded. +(.parquet.meta "hits.parquet") + +;; Materialize only these columns, then use normal queries. +(set hits (.parquet.read [CounterID URL] "hits.parquet")) +(select {from: hits by: CounterID n: (count CounterID)}) + +;; A reusable lazy source: select infers the columns and eligible filters. +(set source (.parquet.scan "hits.parquet")) +(select {from: source n: (count WatchID)}) +(select {from: source URL: URL where: (== CounterID 62)}) + +;; Inclusive signed-integer range: prune disjoint row groups, then filter +;; surviving rows exactly. The filter column need not be projected. +(.parquet.read + {columns: [URL] range: {column: CounterID min: 62 max: 62}} + "hits.parquet") + +;; Process at most 65,536 rows per callback. Returns the number of rows +;; delivered; callback results are discarded and errors stop the scan. +(.parquet.each [CounterID URL] "hits.parquet" + (fn [batch] (show (select {from: batch by: CounterID n: (count CounterID)})))) + +;; Convert in batches into an existing parent's NEW native database root. +;; Returns the imported row count. Open the result with normal native I/O. +(.parquet.splayed "hits.parquet" "/tmp/hits-splayed") +(set flat (.db.splayed.get "/tmp/hits-splayed")) +(.parquet.parted "hits.parquet" "/tmp/hits-native" 'hits) +(set stored (.db.parted.get "/tmp/hits-native" 'hits)) +``` + +Both `.parquet.read` and `.parquet.each` accept an optional column symbol +vector or an options dictionary before the path. Supported options are +`columns`, `types`, `strict`, and `range: {column: name min: lo max: hi}`. Bounds are I64 atoms; +range filtering currently supports signed integer columns only. Missing or +unusable row-group bounds fall back to decoding. A range is an exact filter, +not just a pruning hint. A scan with no matching rows may deliver an empty +schema-bearing batch. + +`types` is a positional vector covering the complete file schema, including +unprojected columns. It uses the native import type rules described below. +For example, `{types: [UNIX_DATE UNIX_SECONDS SYM]}` reads two unannotated +integer temporal columns and dictionary-encodes a text column. Each read owns +a private symbol dictionary shared by its workers; returned vectors retain it +after the reader closes. This avoids the STR vector's 4 GiB pooled-byte limit, +but the dictionary and materialized rows still consume memory. + +Lazy sources accept the same type overrides: + +```clj +(set events (.parquet.scan {types: [UNIX_DATE UNIX_SECONDS SYM]} "events.parquet")) +(select {from: events by: s n: (count s)}) +``` + +The lazy descriptor accepts `types` and `strict`; projections and predicates belong +in the query. Schema conversions are validated when a query opens the file. + +`strict: true` rejects decoded nonnull values that would become native nulls +(including empty text, NaNs, and sentinel integers after type conversion), and +validates UTF-8 for annotated text. Actual Parquet nulls remain supported. +Widening an integer type can preserve a value otherwise reserved as null. +Strict mode validates decoded values; projections, footer-only counts, and +pruning do not certify unvisited payloads. The default retains native null +semantics. This option does not add separate null bitmaps or retain timezone +annotations. + +`.parquet.read` retains the entire result. `.parquet.each` releases each batch +after the callback; a callback may retain it, but that increases memory use. +Grouping, ordering, distinct, and limits inside a callback apply to that batch. +Global answers inside callbacks require explicitly combining partial results. +Alternatively, use `.parquet.scan` as a `select` source: it reopens the file for +each query, infers projections for statically understood expressions, and +extracts signed-integer comparisons (`==`, `<`, `<=`, `>`, `>=`, including +conjunctions, reversed operands, and literal inclusive `within` bounds). +Upper-bound comparisons retain nulls, which Rayforce orders before numbers. +When a pushed predicate accepts nulls, the reader decodes all candidate pages +instead of pruning with nonnull statistics or Bloom filters. Explicit +`.parquet.read` ranges continue to exclude nulls. +A standalone `like` predicate filters each decoded batch before materializing +the result. Filtered text enters a private symbol dictionary only after it +survives the reader predicate. Dynamic expressions fall back to carrying +all columns. Predicates with aggregates or other vector-dependent expressions +are evaluated by the ordinary query engine without early filtering. + +Simple global `count`, integer `sum`/`avg`, and supported numeric/temporal +`min`/`max` expressions use the native streaming accumulators. An unfiltered +count uses footer row counts without decoding pages. Filtered streaming +aggregates support row-local signed-integer comparisons or a standalone `like`. +For integer comparisons, one column uses reader pruning and residual comparisons +run on each batch. Other queries, +including grouping, distinct and ordering, materialize the inferred columns +and candidate rows before ordinary query execution, preserving global query +semantics. These queries are not bounded-memory scans. The lazy descriptor is +intended for `select`; materialize it explicitly with `.parquet.read` for other +table operations. + +### Supported input and limits + +- One local, unencrypted file with a flat schema. +- Uncompressed and raw Snappy column chunks. +- Data pages v1 and v2; PLAIN and dictionary encoding, including the legacy + dictionary tag and dictionary-to-plain fallback within a chunk; RLE-encoded + BOOLEAN values (the v2 default of common writers). Zero-row row groups are + skipped. +- RLE/bit-packed definition levels and dictionary IDs; page CRC32 validation + when a checksum is present on a decoded page. Pruned pages are not read for + checksum validation. +- BOOLEAN, INT32, INT64, FLOAT, DOUBLE, and BYTE_ARRAY physical types. Strings + become STR vectors. Nullable booleans become I16 so nulls are representable. +- UTF8, DATE, signed integers, UINT8/16/32, and millisecond/microsecond/nanosecond + TIMESTAMP annotations. Narrow signed annotations may use a wider native type + to preserve values otherwise reserved as a null sentinel. UINT64, decimal, + INT96, nested/repeated data, fixed byte arrays, and other annotations are + rejected. BYTE_ARRAY bytes are preserved; annotated UTF8 is validated when + `strict: true` is enabled. +- Parquet dates/timestamps are converted from the Unix epoch to Rayforce's + 2000 epoch. Timestamp timezone annotations are not retained as separate + metadata. Unannotated integer columns remain integers. +- Existing Rayforce null semantics apply: empty strings, NaNs, and native + integer null sentinels are represented as nulls. Their original distinction + from Parquet nulls is not preserved. This is not a lossless interchange path + for those values. Enable `strict: true` to reject these collisions instead. +- Timestamps outside the native nanosecond range (a 9999-12-31 "end of time" + sentinel, for example) are clamped to the nearest representable instant, so + comparisons keep their meaning; the stored value differs from the file. + `strict: true` rejects them, naming the column. +- At most 4,096 columns, a 64 MiB footer, and 64 MiB per compressed or + decompressed page. Batches of long strings are made smaller: each row + group's batch size is lowered so a STR column's decoded string pool stays + near 64 MiB, estimated from the column chunk's uncompressed size and its + longest dictionary entry. A pool past its 4 GiB capacity returns an error. Oversized values return errors. Total scratch memory depends on the selected column count + and page/dictionary sizes; there is no query-wide memory budget yet. + +Projection avoids decoding other columns, except an unprojected range-filter +column. Signed integer ranges use row-group min/max and page column/offset +indexes. Excluded row intervals are applied across columns even when their +page boundaries differ: whole excluded pages bypass decompression; partially +covered pages are decoded to advance their cursors correctly. Integer equality +also probes standard split-block Bloom filters using a native, seed-zero XXH64 +implementation specialized to INT32/INT64. Missing, unsupported or malformed +optional indexes fall back to scanning. See the Apache +[page-index](https://parquet.apache.org/docs/file-format/pageindex/) and +[Bloom-filter](https://parquet.apache.org/docs/file-format/bloomfilter/) specifications. + +Materialized reads and lazy queries dispatch independent row groups through the +existing worker pool. Streaming aggregates merge native partial accumulators in +source order, including residual integer comparisons; unfiltered counts still +use only the footer. Materialized output also preserves source order. Callbacks +in `.parquet.each` run in order on the calling thread; their column decoding can +run in parallel for batches of at least 4,096 rows. `-c 1` uses one execution +participant; other core settings use the configured pool without a four-core cap. +Buffers and output vectors use Rayforce's block allocator. Required PLAIN signed +integers use SSE2 copy/null detection where available, with a scalar fallback. +Repeated dictionary runs fill native blocks in bulk. Snappy back references use +bounded block copies. Packed dictionary IDs remain scalar. A standalone `like` +predicate can filter decoded batches; string Bloom probes, fully deferred output +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. +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`, +`UNIX_MILLIS`, `UNIX_MICROS`, or `UNIX_NANOS`; no epoch is guessed. Annotated +Parquet dates/timestamps retain their declared units with `DATE`/`TIMESTAMP`. +For example, a file containing an integer ID, unannotated Unix seconds and text: + +```lisp +(.parquet.splayed [I64 UNIX_SECONDS SYM] "events.parquet" "/tmp/events") +(.parquet.parted [I64 UNIX_SECONDS SYM] "events.parquet" "/tmp/events-db" 'events) + +;; CSV supports the same two destination layouts. An explicit name vector +;; means headerless input. Its DATE/TIMESTAMP fields are formatted text. +(.csv.splayed [id time text] [I64 TIMESTAMP SYM] "events.csv" "/tmp/events-csv") +(.csv.parted [id time text] [I64 TIMESTAMP SYM] "events.csv" 65536 "/tmp/events-csv-db" 'events) +``` + +For fixed-width and `SYM` splayed output, workers decode column chunks across +row groups directly into disjoint ranges of the final column files. Parquet +string dictionary IDs map directly to native file-domain symbol IDs. The file +mapping is shared, while decode buffers and cursors remain private to each task. +The loader builds the same native indexes as the CSV splayed loader. Files and +the staging directory are synced before publication, avoiding a directory sync +for every individual column rename. + +Splayed `STR` output uses bounded temporary native batches and merges their +string pools in source order. This requires temporary disk space and an extra +write pass. A native STR pool has 32-bit offsets: use `SYM` or partitioned output +when a column's pooled bytes exceed 4 GiB. CSV splayed STR import now uses the +same streaming column writer, without materializing the entire CSV. + +Partitioned conversion dispatches row groups independently and assigns numeric +partition IDs in source order, with at most 65,536 rows per partition by default. +An import options dictionary can replace the positional type vector: +`{types: [I64 SYM] rows: 262144 strict: true}`. `types` and `strict` are optional; +`rows` accepts 1 through 1,048,576. Row-group boundaries also end partitions. +Larger batches require more memory. Partitions holding long strings are +smaller than `rows`, since a partition is one decode batch and batches keep +STR pools near 64 MiB. Splayed imports accept the same options to control their decode batches. +The importer writes +exact native numeric zone indexes while each decoded batch is resident (F32 +currently excluded). STR pools stay local to each partition. Typed SYM imports +use a shared file dictionary. Group decoding and independent partition writes +remain parallel; the dictionary is flushed once after workers finish. Column +files are then synced, followed by each leaf and partition directory, before +the staged root is published. This avoids syncing a directory after every +individual column rename while preserving durability at publication. + +Parquet conversions write to `.parquet-partial` and publish the +result after successful writes. Existing destinations or staging directories +are rejected; failed staging data is retained for inspection. The destination's +parent must already exist. Column names must be safe native filenames; parted +imports also reject an input `part` column. These imports are not resumable. +Publication uses the host's exclusive rename primitive so a destination +created during the import cannot be overwritten. Linux uses +[`RENAME_NOREPLACE`](https://man7.org/linux/man-pages/man2/renameat2.2.html); +macOS uses [`RENAME_EXCL`](https://developer.apple.com/documentation/foundation/urlresourcevalues/volumesupportsexclusiverenaming). +An unsupported host or filesystem returns an error and retains the staging +directory; it does not fall back to an overwrite-capable rename. + +CSV parted imports into a new root use `.csv-partial` and publish +after the final shared dictionary flush. Failed staging directories are kept +and rejected on retry. Imports into an existing CSV root retain the existing +per-partition update behavior. CSV bulk writes require an external file and +directory sync before they can be considered durable. + +### ClickBench development checks + +The ClickBench Athena `hits.parquet` footer inspected on 2026-09-30 contains +99,997,497 rows, 105 columns, and 226 row groups. All 23,730 column chunks use +Snappy and have statistics; none have page indexes or Bloom filters. +`EventTime` and `EventDate` are unannotated/ordinary integers in that dataset: +benchmark queries must explicitly convert Unix seconds and Unix days to native +temporal types. Those benchmark-specific conversions do not belong in the +format reader. + +The following developer tools use Python's standard library; remote range +fetches use the `curl` executable. The reference SQL engine is an external test +oracle only. Pass its executable +with `--oracle`; it must accept `-c`, `-csv`, and `-json` and support +`read_parquet`, `COPY`, and the SQL expressions in the scripts. The full +query census also requires `--oracle-queries`, a file containing the 43 +corresponding SQL queries, one per line. These tools are development-only +and are not runtime dependencies. + +```bash +# Inventory the original footer and copy original pages for a bounded sample. +python3 scripts/parquet-inspect.py \ + https://datasets.clickhouse.com/hits_compatible/athena/hits.parquet \ + --sample /tmp/hits-sample.parquet --groups 1 + +# Compare every sample cell to the reference SQL engine and every native batch to the source. +python3 scripts/parquet-verify.py /tmp/hits-sample.parquet --oracle /path/to/reference-sql + +# Compare representative lazy query shapes with the external oracle. +python3 scripts/parquet-query-verify.py /tmp/hits-sample.parquet --cores 4 \ + --oracle /path/to/reference-sql + +# Warm scan timings: all columns, projection, footer count, streaming aggregates. +make release +python3 scripts/parquet-bench.py /tmp/hits-sample.parquet --cores 1 4 + +# Regression suite; fixtures are checked in, with a standard-library generator. +make test TEST_FILTER=parquet +``` + +The first original row group (450,560 rows) was checked across all 105 columns: +47,308,800 cells matched the reference SQL engine, and all seven converted native partitions +matched the decoded source. Twelve representative lazy query shapes also +matched the oracle, including grouping, distinct counts, top-k and empty +filtered aggregates. + +The full 99,997,497-row input subsequently passed all **43 ClickBench query +shapes** against the reference SQL engine on 2026-09-30, using explicit SYM text types, 28 workers, +and a recorded 48 GiB process address-space ceiling. The per-query scripts, +translations, timings, peak RSS and oracle outcomes are recorded in +`bench/parquet_load/results/2026-09-30-full-queries.json`. Tied LIMIT alternatives +are checked for rank, full-row membership and multiplicity. Reproduce with: + +```bash +python3 scripts/parquet-clickbench.py /path/to/hits.parquet \ + --symbol-text --cores 28 --address-space-gib 48 --timeout 180 \ + --work-dir /path/to/new-query-results +``` + +This is a correctness census with one process per query, not an official +ClickBench score. General grouped/sorted queries still materialize candidate +rows; passing this dataset does not establish bounded memory for arbitrary data. + +Both `parquet-clickbench.py` and `parquet-load-bench.py` accept `--resume` for +runs created with their checkpoint support. Repeat the original command with +that flag and the same work directory. A durable `run.json` records the build, +harness, settings and source identity; incompatible runs are rejected. The +query census fingerprints the input contents, while the load harness checks +file identity, size and modification/change timestamps for its much larger +CSV input and retained reference. Completed cases are retained; unfinished +outputs move into `interrupted-*` directories and their cases restart with new +timings. Remove a deliberate `stop` marker before continuing. Older runs +without `run.json` require a new directory. This resumes benchmark cases, not +an individual native import. + +Earlier single-row-group scan measurements on an Intel Core i7-14700, release build with +`-march=native`, using that sample (median of five runs after one warmup): + +| Operation | 1 core | 4 cores | +| --- | ---: | ---: | +| Scan all 105 columns | 424.0 ms | 236.6 ms | +| Scan nine projected columns | 105.3 ms | 81.6 ms | +| Footer count | 0.112 ms | 0.112 ms | +| Stream three aggregates over two columns | 8.20 ms | 8.50 ms | + +The wide scan benefits from parallel decoding; the small aggregate projection +does not in this measurement. These are sample scan timings, not a published +43-query ClickBench score or a cold-storage benchmark. + +### Comparing the ClickBench load stage + +`scripts/parquet-load-bench.py` reads the actual type vector from +`../ClickBench/rayforce/create.rfl` and runs its `.csv.splayed` load against +`.parquet.splayed` with the same native schema. It maps the Athena file's raw +integer dates/timestamps using explicit Unix units and stores all text as SYM, +matching ClickBench. An optional external reference SQL export prepares a headerless +CSV containing the identical rows, with UTC timestamps. Export and download are +outside the measured load stage; no external library is linked to Rayforce. + +```bash +make release +python3 scripts/parquet-load-bench.py /tmp/hits-sample.parquet /tmp/hits-sample.csv \ + --prepare-csv --oracle /path/to/reference-sql --cores 1 8 28 --repeats 3 \ + --work-dir /tmp/rayforce-load-comparison +``` + +Use a sample with several **original row groups** (`--groups 8` when extracting) +to exercise group parallelism. The script uses fresh processes and destinations, +alternates CSV/Parquet order across repetitions, and includes index creation, +reopening, and output fsync in wall time. It compares every resulting value and +column type with the first CSV import before reporting a successful run. +Peak RSS, output sizes, individual times and medians are written to +`results.json`. Inputs use the OS page cache; this is not a cache-evicted storage +benchmark. The benchmark work directory must be new and retains the reference +CSV native table and logs. + +For the full dataset, use the bounded-memory verifier. It compares every +numeric payload and resolves symbol IDs by their actual bytes, without +interning both vocabularies into the runtime. Verification is outside timing. + +```bash +cc -O3 -Iinclude bench/parquet_load/verify-native.c -o /tmp/verify-native +curl --fail --location --output /tmp/hits.parquet \ + https://datasets.clickhouse.com/hits_compatible/athena/hits.parquet +python3 scripts/parquet-load-bench.py /tmp/hits.parquet /tmp/hits.csv \ + --prepare-csv --oracle /path/to/reference-sql --cores 28 8 --repeats 3 \ + --native-verifier /tmp/verify-native --work-dir /tmp/rayforce-full-load +``` + +An existing verified native CSV table can be supplied with `--reference`. +`--kinds parquet` or `--kinds csv` measures only that input format against the +reference. Creating a `stop` file in the work directory asks the runner to stop +after saving the current verified result. + +Before the full-dataset contention fixes, the first eight **original** +ClickBench row groups contained +3,266,382 rows × 105 columns. On an Intel Core i7-14700 (28 logical CPUs), +three repetitions per case produced these median durable load times: + +| Execution participants | CSV → splayed | Parquet → splayed | CSV / Parquet | +| ---: | ---: | ---: | ---: | +| 1 | 8.652 s | 4.692 s | 1.84× | +| 8 | 2.627 s | 1.661 s | 1.58× | +| 28 | 2.310 s | 2.089 s | 1.11× | + +All 342,970,110 cells and native column types matched the CSV reference for +every Parquet import. Both formats produced 2,195,585,704 bytes of indexed +native storage. Eight participants were faster than 28 for this sample; +the implementation imposes no fixed core cap. The input files were 594,562,209 +bytes of Parquet and 2,722,297,967 bytes of CSV. This earlier load-stage +comparison used a 3.27M-row sample. Raw runs, +peak RSS, source checksum and environment are recorded in +`bench/parquet_load/results/2026-09-30.json` in the repository. + +### Full ClickBench load proof + +The complete original file was measured on 2026-09-30: **99,997,497 rows, +105 columns, 226 row groups**. The same Intel Core i7-14700 has 20 physical +cores and 28 logical CPUs, 62 GiB RAM and NVMe storage. These are medians of +three durable loads per format and execution-participant count, including +native index construction, reopening and output fsync: + +| Execution participants | CSV → splayed | Parquet → splayed | CSV / Parquet | +| ---: | ---: | ---: | ---: | +| 8 | 124.113 s | 84.285 s | 1.47× | +| 28 | 112.247 s | 77.772 s | 1.44× | + +Every measured output was checked across all **10,499,737,185 cells**, column +names/order and native types against the verified CSV reference. Both inputs +produce **59,042,332,197 bytes** of indexed native storage. The inputs are +14,779,976,446 bytes of original Parquet and 78,462,321,894 bytes of matching +CSV. Download and the external oracle's CSV export are outside load timing. + +Profiling found contention on the shared symbol-domain spinlock and frequent +fallback from batched to individual symbol insertion when concurrent chunks +changed the dictionary. The domain now uses an OS mutex, rechecks distinct +misses while preserving bulk arena allocation, and the Parquet importer drops +its completed ingestion dictionary before reopening for index construction. +Row groups and columns continue to use the configured worker pool. + +Before these changes, full-data Parquet medians were 99.688 seconds at eight +participants and 108.551 seconds at 28. Extra workers were making it slower. +The load still contains shared dictionary work, native index construction and +59 GB of output writes, so additional workers do not produce linear scaling. +Inputs use the OS page cache, with no cache eviction or CPU pinning. The host +has 16 GiB zram plus about 4 GiB disk swap; swapping was observed, mainly zram. +The results describe this host under these conditions. + +Raw before/after runs, CPU time, page faults, I/O counters, peak RSS, input and +binary checksums, export SQL and validation details are in +`bench/parquet_load/results/2026-09-30-full.json` and +`bench/parquet_load/results/2026-09-30-full-baseline.json`. + +### Full partitioned load proof + +The subsequent partitioned comparison used the same 99,997,497 rows and 105 +columns, a 262,144-row partition cap, and three repetitions per format at both +eight and 28 execution participants. All **12 outputs** passed comparison of +every cell and native column type against the retained full CSV splayed +reference. The medians include process startup, native indexes, reopening, +and output file/directory sync; verification runs after timing stops. + +| Execution participants | CSV → partitioned | Parquet → partitioned | CSV / Parquet | +| ---: | ---: | ---: | ---: | +| 8 | 241.077 s | 118.807 s | 2.03× | +| 28 | 233.398 s | 117.488 s | 1.99× | + +Both outputs preserve source row order. CSV produces 382 partitions; Parquet +produces 501 because source row-group boundaries also terminate partitions. +Their native sizes are 47,319,348,589 and 47,323,067,877 bytes, respectively. +Across these runs, CSV peak RSS was 47.1–49.9 GiB and Parquet peak RSS was +33.4–40.5 GiB. These are observed peaks, not configured memory bounds. + +Increasing participants from eight to 28 improved the median by about 3.2% +for CSV and 1.1% for Parquet on this host. It does not establish linear CPU +scaling: the workload also includes shared dictionaries, memory pressure, +index construction, and approximately 47 GB of durable output per run. +The same OS-managed page cache and unpinned CPU setup applies. No tests or +diagnostic queries ran concurrently with these measurements. + +The raw cases, verification outcomes, source/build identities and resource +counters are in `bench/parquet_load/results/2026-09-30-parted-full.json`. +The measured release is retained separately from later write-failure and +exclusive-publication hardening. The earlier splayed results above remain +measurements of their recorded build. + +A separate, single-run 65,536-row-cap diagnostic measured 231.194 seconds +after grouping staging syncs, versus the earlier 815.970-second run. This +is not a repeated median; its report is +`bench/parquet_load/results/2026-09-30-parted-sync-diagnostic.json`. diff --git a/docs/docs/language/functions.md b/docs/docs/language/functions.md index 7580b8e64..ced66c164 100644 --- a/docs/docs/language/functions.md +++ b/docs/docs/language/functions.md @@ -69,7 +69,7 @@ All comparison operators are **atomic** and return boolean results. |---|---|---|---| | `and` | binary | Logical AND | `(and true false)` → `false` | | `or` | binary | Logical OR | `(or true false)` → `true` | -| `not` | unary | Logical NOT | `(not true)` → `false` | +| `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 @@ -456,6 +456,8 @@ not collide between two processes writing into the same table, use `guid`. | `format` | variadic | Format value to string (% is placeholder) | `(format "val=%" 42)` → `"val=42"` | | `.csv.read` | variadic | Load CSV file into table | `(.csv.read "data.csv")` | | `.csv.write` | variadic | Write table to CSV file | `(.csv.write trades "out.csv")` | +| [`.parquet.read`](../namespaces/parquet.md#parquet-read) | variadic | Read a Parquet file into a table | `(.parquet.read [id price] "trades.parquet")` | +| [`.parquet.scan`](../namespaces/parquet.md#parquet-scan) | variadic | Create a lazy Parquet source for `select` | `(.parquet.scan "trades.parquet")` | | `read` | unary | Read file contents as string, to EOF | `(read "file.txt")` | | `read-bytes` | unary | Read file contents as a `U8` byte vector, to EOF | `(read-bytes "file.bin")` | | `write` | binary | Write a string to a file | `(write "file.txt" "content")` | diff --git a/docs/docs/language/repl.md b/docs/docs/language/repl.md index 3b66f8c40..6ed0ded87 100644 --- a/docs/docs/language/repl.md +++ b/docs/docs/language/repl.md @@ -19,6 +19,16 @@ 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. +### Environment Variables + +The thread pool reads these once, when it is created (process start, or the first parallel operation): + +| Variable | Default | Description | +|---|---|---| +| `RAYFORCE_CORES` | unset | Number of background worker threads when no `-c` is given (the main thread is one more). Unset keeps the default of every online logical CPU; the test harness sets it to keep spawned processes small. An explicit `-c N` overrides it. | +| `RAY_POOL_STEAL` | `1` | How workers claim tasks. `1`: each worker owns a contiguous slice of the table and steals halves of other workers' remaining slices once its own is done — sequential access and a stable row-to-worker mapping. `0`: every worker claims the next task from one shared cursor. Results are identical; set `0` only to A/B the two schedulers. | +| `RAY_POOL_TRACE` | unset | `1` prints a per-worker histogram to stderr when the pool is destroyed (at exit): tasks each worker ran from its own slice versus stolen ones, and the number of steals. Use it to see how evenly work splits across workers on a given machine. | + ## REPL Commands All commands start with `:` and are handled before expression evaluation. diff --git a/docs/docs/namespaces/csv.md b/docs/docs/namespaces/csv.md index 29b00307b..6ada89292 100644 --- a/docs/docs/namespaces/csv.md +++ b/docs/docs/namespaces/csv.md @@ -44,7 +44,7 @@ Examples: (set t (.csv.read [sym price qty date] [SYMBOL F64 I64 DATE] "/tmp/rayforce-trades-headerless.csv")) ``` -The reader memory-maps the input, splits it into chunks, parses chunks in parallel, then merges column types and symbol-intern tables. Speedup is near-linear with core count on files of 100 MB+. +The reader memory-maps the input, splits it into chunks, parses chunks in parallel, then merges column types and symbol-intern tables. Scaling depends on parsing, dictionary work, memory pressure, and output I/O; see the [measured load comparisons](../guides/storage.md#full-clickbench-load-proof). ## `.csv.write` { #csv-write } @@ -64,7 +64,7 @@ Signatures: - `(.csv.splayed [types] "src.csv" "out_dir")` - `(.csv.splayed [names] [types] "src.csv" "out_dir")` -Streams `src.csv` chunk-by-chunk through the parser into a splayed directory at `out_dir` (one column file per field, plus a `sym` symbol-table file). 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` — zero-copy mmap, so the bytes stay on disk. Use this when the CSV is too large to fit in memory but you want to query it like an in-memory table. @@ -85,7 +85,7 @@ Signatures (with optional rows-per-part): - `(.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. -Streams the CSV into a partitioned table under `db_root/tbl_name/`, creating subdirectories per partition. Returns the parted table loaded back from disk. +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. Constraints on `tbl_name`: must not start with `.`, must not contain `/` or `\\` or `..`. diff --git a/docs/docs/namespaces/index.md b/docs/docs/namespaces/index.md index 4312a61dc..1f7170ff1 100644 --- a/docs/docs/namespaces/index.md +++ b/docs/docs/namespaces/index.md @@ -17,6 +17,7 @@ Rayfall's builtins are organised under dotted namespaces. Names beginning with ` | [`.log.*`](log.md) | Write-ahead log: open, write, sync, snapshot, roll, replay, validate. | | [`.mem.*`](mem.md) | Value sizing and scoped time/allocation measurement. | | [`.os.*`](os.md) | Process environment: `getenv`, `setenv`. | +| [`.parquet.*`](parquet.md) | Parquet metadata, reads, lazy queries, callbacks, and native imports. | | [`.repl.*`](repl.md) | Interactive REPL control — attach the local REPL to a remote server. | | [`.sys.*`](sys.md) | System info and shell-style commands: build, info, mem, prof, querylog, gc, exec, listen, timeit, env, cmd. | | [`.time.*`](time.md) | Monotonic clock and timer scheduler. | @@ -30,6 +31,7 @@ When the server is started with `-U `, the following dotted builtins a - `.ipc.open`, `.ipc.close`, `.ipc.send`, `.ipc.post` - `.log.open`, `.log.replay`, `.log.roll`, `.log.snapshot`, `.log.close`, `.log.purge` - `.os.getenv`, `.os.setenv` +- `.parquet.meta`, `.parquet.read`, `.parquet.scan`, `.parquet.each`, `.parquet.splayed`, `.parquet.parted` - `.repl.connect`, `.repl.disconnect` - `.sys.exec`, `.sys.cmd`, `.sys.listen`, `.sys.querylog.enable` - `.time.timer.set`, `.time.timer.del` diff --git a/docs/docs/namespaces/ipc.md b/docs/docs/namespaces/ipc.md index bab98bab9..619f6c0b7 100644 --- a/docs/docs/namespaces/ipc.md +++ b/docs/docs/namespaces/ipc.md @@ -13,25 +13,37 @@ Connect to a Rayforce server (`./rayforce -p `) and exchange messages over | Function | Arity | Flags | Description | |---|---|---|---| | [`.ipc.open`](#ipc-open) | variadic | restricted | Open a TCP connection (optional connect timeout); return an i64 handle. | -| [`.ipc.send`](#ipc-send) | binary | restricted | Send a message synchronously; return the server's result. | +| [`.ipc.send`](#ipc-send) | variadic | restricted | Send a message synchronously (optional deadline); return the server's result. | | [`.ipc.post`](#ipc-post) | binary | restricted | Send a message asynchronously (fire-and-forget); return the null object. | | [`.ipc.close`](#ipc-close) | unary | restricted | Close a connection handle. | | [`.ipc.handle`](#ipc-handle) | variadic | — | The current connection's handle inside a server-side hook; `-1` otherwise. | ## `.ipc.open` { #ipc-open } -Signature: `(.ipc.open "host:port")` or `(.ipc.open "host:port:user:password")`, with an optional trailing connect timeout in milliseconds: `(.ipc.open "host:port" 2000)`. +Signature: `(.ipc.open "host:port")` or `(.ipc.open "host:port:user:password")`, with an optional second argument: a connect timeout in milliseconds, `(.ipc.open "host:port" 2000)`, or an options dict, `(.ipc.open "host:port" (dict [timeout keepalive] [2000 30000]))`. Returns: an `i64` handle. Negative handles never escape — errors are surfaced as Rayfall error objects: - `type` — address argument is not a string, or the timeout argument is not an integer. - `rank` — called with fewer than 1 or more than 2 arguments. -- `domain` — malformed address (missing port, port out of `(0, 65535]`, oversized host/user/password), or a negative timeout. +- `domain` — malformed address (missing port, port out of `(0, 65535]`, oversized host/user/password), a negative timeout, an unknown option key, or an out-of-range option value. - `access` — server requires auth and you didn't supply credentials, **or** the password is wrong. - `io` — connection refused / network error, or `connection timed out` when the connect did not complete within the timeout. The optional timeout bounds **both** the TCP connect and the handshake I/O. A blocking `connect()` ignores socket send/receive timeouts, so without an explicit bound a dead or packet-filtered peer would otherwise hang for the operating-system default (often minutes). When omitted, a default budget of 5 seconds applies. +Options dict keys (all optional; keys must be symbols): + +| Key | Value | Absent means | +|---|---|---| +| `timeout` | Connect + handshake budget in ms, as the bare-integer form. | 5 seconds. | +| `compress` | Threshold in bytes: `0N` never compresses, `0` always does, `n` compresses payloads larger than `n`. | Loopback links never compress; others use 2,000. | +| `keepalive` | Dead-peer budget in ms, or `0N` to turn detection off. `0` is rejected. | Detection on, 60-second budget. | + +**Dead-peer detection.** A peer can become unreachable without closing the socket: a suspended host, a NAT or firewall that silently drops the flow, or a machine that loses power. No reset ever arrives. Without detection the handle stays open forever, and `.ipc.on.close` never fires. To prevent that, outbound connections enable TCP keepalive: after half the budget of silence the kernel starts probing, and it declares the peer dead about one budget after the peer last sent anything. The connection is then torn down like any other failure: a pending `.ipc.send` returns `io` and `.ipc.on.close` fires. A peer that is alive answers the probes from its kernel, even while it is busy evaluating, so a long query is never cut off. + +Keepalive only probes while none of our data is waiting for acknowledgement. Passing an explicit `keepalive` budget also bounds how long sent data may stay unacknowledged (`TCP_USER_TIMEOUT` on Linux), which catches a peer that vanishes mid-request. The cost is that a live peer which stops **reading** for that long also counts as dead: a large request to a server busy with something else, for example. The default does not set this bound. In that case a peer that vanishes with our data in flight is dropped by the operating system's retransmission limit, which is about 15 minutes on Linux. The budget is applied in whole seconds for the probe schedule. Platforms without these socket options skip them. + The handshake exchanges a 2-byte `{wire_version, auth_flag}` greeting. A wire-version mismatch closes the connection before any payload is exchanged. ```text @@ -43,11 +55,14 @@ The handshake exchanges a 2-byte `{wire_version, auth_flag}` greeting. A wire-ve ;; Fail fast if the peer doesn't answer within 2 seconds (set h (.ipc.open "127.0.0.1:5000" 2000)) + +;; Declare the peer dead after ~10s of silence or unacknowledged data +(set h (.ipc.open "127.0.0.1:5000" (dict [keepalive] [10000]))) ``` ## `.ipc.send` { #ipc-send } -Signature: `(.ipc.send h msg)`. Sends `msg` synchronously — blocks until the peer replies. +Signature: `(.ipc.send h msg)` or `(.ipc.send h msg timeout-ms)`. Sends `msg` synchronously — blocks until the peer replies, or until the optional deadline expires. The receiving side's behaviour depends on `msg`'s type: @@ -56,7 +71,9 @@ The receiving side's behaviour depends on `msg`'s type: | `STR` | Parsed as Rayfall, evaluated, result returned. | | anything else | Passed straight into `ray_eval` — identity for plain data, execution for an expression list. | -Errors: `type` (`h` not an `i64`/`i32`, or `msg` not serialisable), `io` (handle does not name an open connection). Server-side errors are returned as error objects too — `.ipc.send` does not raise them, the caller decides what to do. +Errors: `type` (`h` not an `i64`/`i32`, `msg` not serialisable, or the timeout not an integer), `domain` (timeout `0` or negative), `rank` (not 2 or 3 arguments), `io` (handle does not name an open connection, or the deadline expired). Server-side errors are returned as error objects too — `.ipc.send` does not raise them, the caller decides what to do. + +**Deadline.** With a timeout, the whole round trip (writing the request and waiting for the reply) must finish within `timeout-ms`, or `.ipc.send` returns `io` (`ipc send timed out after N ms; connection closed`). `0N` means no deadline, the same as leaving the argument out. On expiry the connection is **closed** and `.ipc.on.close` fires. A reply carries no request id, so a reply that arrived later would otherwise be taken as the answer to the next `.ipc.send` on the handle. Reconnect with `.ipc.open`. Before closing, the peer is sent the same best-effort cancel as Ctrl-C, so a server still evaluating the request stops. Use a deadline where you know the call's latency budget: a cheap poll can have a tight one, while a long query should have a loose one or none. For a peer that disappears without closing the connection, see dead-peer detection under [`.ipc.open`](#ipc-open). While waiting for its response, `.ipc.send` keeps servicing the connection: an async message pushed by the peer in the meantime is dispatched (evaluated, or routed through `.ipc.on.async`) before the round-trip returns, and a sync request arriving from the peer is answered. Frames are never silently swallowed by the wait. @@ -67,6 +84,9 @@ While waiting for its response, `.ipc.send` keeps servicing the connection: an a ;; Expression form — dict stays unevaluated until the server processes it (.ipc.send h (list select {from: trades by: sym total: (sum qty)})) +;; Give up (and drop the connection) if no answer within 5 seconds +(.ipc.send h "(count trades)" 5000) + ;; Plain data round-trips (.ipc.send h 42) ;; => 42 (.ipc.send h (til 1000)) ;; => the same vector diff --git a/docs/docs/namespaces/log.md b/docs/docs/namespaces/log.md index 7a366e971..9b44be8aa 100644 --- a/docs/docs/namespaces/log.md +++ b/docs/docs/namespaces/log.md @@ -18,7 +18,7 @@ The journal is intentionally minimal: there's no per-entry timestamp or transact | [`.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)`. | -| [`.log.close`](#log-close) | variadic | restricted | Flush and close the active journal. | +| [`.log.close`](#log-close) | nullary | restricted | Flush and close the active journal. | | [`.log.purge`](#log-purge) | nullary | restricted | Close the active journal and delete all its files. | ## `.log.open` { #log-open } @@ -32,7 +32,9 @@ Returns the null object on success. Opens the journal **for append only** — it does not load a snapshot or replay the existing log. Resuming an existing journal therefore does not re-apply its entries; recover state explicitly with [`.log.replay`](#log-replay) (or let the `-l`/`-L` startup path do it for you). This keeps "open to keep writing" distinct from "recover prior state". -Errors: `rank` (arity != 2), `type` (mode not a sym / base not a string), `domain` (unknown mode), `io` (open failed). +A journal has one writer. While it is open, the process holds an exclusive lock on `.lk`; a second process that opens the same base — with `.log.open`, `-l` or `-L` — fails with `io` and logs `journal is open in another process`. The lock is released by `.log.close`, `.log.purge` or process exit. + +Errors: `rank` (arity != 2), `type` (mode not a sym / base not a string), `domain` (unknown mode), `io` (open failed, or another process has the journal open). ```lisp (.log.open 'async "/tmp/rayforce-journal") @@ -103,7 +105,7 @@ Signature: `(.log.close)`. Flushes and closes the active journal. Returns null. ## `.log.purge` { #log-purge } -Signature: `(.log.purge)`. Closes the active journal (if open) and deletes its **entire** on-disk footprint: the active `.log`, every rolled `..log` archive, the `.qdb` snapshot, and a stray `.qdb.tmp`. Takes no path argument — it acts on the current journal, the same one `.log.open` / `.log.write` / `.log.close` operate on (the base survives `.log.close`, so purge works after a close). Returns null on success; errors with `domain` if no journal has been opened in this process. Best-effort delete: a missing file is not an error. +Signature: `(.log.purge)`. Closes the active journal (if open) and deletes its **entire** on-disk footprint: the active `.log`, every rolled `..log` archive, the `.qdb` snapshot, a stray `.qdb.tmp` and the `.lk` lock file. It fails with `io` while another process has the journal open. Takes no path argument — it acts on the current journal, the same one `.log.open` / `.log.write` / `.log.close` operate on (the base survives `.log.close`, so purge works after a close). Returns null on success; errors with `domain` if no journal has been opened in this process. Best-effort delete: a missing file is not an error. ``` (.log.close) diff --git a/docs/docs/namespaces/parquet.md b/docs/docs/namespaces/parquet.md new file mode 100644 index 000000000..46103ed2e --- /dev/null +++ b/docs/docs/namespaces/parquet.md @@ -0,0 +1,111 @@ +# `.parquet.*` — Parquet input and native conversion + +Read or query a local Parquet file, process it in batches, or convert it to +Rayforce's native splayed or partitioned layout. The reader and Snappy decoder +are implemented in C without third-party library dependencies. + +!!! note "Restricted under `-U`" + All six functions are restricted for IPC peers under a `-U` server and + return an `access` error. Querying a previously created lazy descriptor is + also restricted. Local scripts and the REPL are unaffected. + +## Reference + +| Function | Arguments | Returns | +| --- | --- | --- | +| [`.parquet.meta`](#parquet-meta) | `path` | Column-chunk metadata table | +| [`.parquet.read`](#parquet-read) | optional projection/options, `path` | Materialized table | +| [`.parquet.scan`](#parquet-scan) | optional options, `path` | Reusable lazy `select` source | +| [`.parquet.each`](#parquet-each) | optional projection/options, `path`, callback | Number of rows delivered | +| [`.parquet.splayed`](#parquet-splayed) | optional types/options, `path`, destination | Imported row count | +| [`.parquet.parted`](#parquet-parted) | optional types/options, `path`, root, table name | Imported row count | + +Paths are nonempty strings. Type overrides are positional SYM vectors covering +the entire source schema. Supported formats, type conversions, strict fidelity +checks, pruning, and memory limits are described in the +[Parquet storage guide](../guides/storage.md#parquet-input). + +## `.parquet.meta` { #parquet-meta } + +Read footer metadata without decoding data pages. The returned table has one +row per column chunk, including its row group, type, codec, compressed and +uncompressed sizes, and the presence of statistics or optional indexes. + +```lisp +(.parquet.meta "events.parquet") +``` + +## `.parquet.read` { #parquet-read } + +Materialize all columns, a projection vector, or a read configured with +`columns`, `types`, `strict`, and an inclusive signed-integer `range`. + +```lisp +(.parquet.read "events.parquet") +(.parquet.read [id text] "events.parquet") +(.parquet.read + {columns: [text] range: {column: id min: 10 max: 20}} + "events.parquet") +``` + +The whole result remains in memory. Typed `SYM` text uses a private dictionary +that remains valid for as long as returned vectors retain it. + +## `.parquet.scan` { #parquet-scan } + +Create a descriptor for `select`. Each query reopens the file and infers eligible +projections and predicates. Options are `types` and `strict`; put filters in +the query itself. Creation does not read or validate the file. + +```lisp +(set events (.parquet.scan "events.parquet")) +(select {from: events n: (count id)}) +(select {from: events text: text where: (within id [10 20])}) +``` + +Simple global aggregates can stream. Grouping, distinct and ordering currently +materialize candidate rows and selected columns before ordinary query execution. + +## `.parquet.each` { #parquet-each } + +Call a function with consecutive batches of at most 65,536 rows. Read options +match `.parquet.read`. Callbacks run in source order on the calling thread; +their return values are discarded, and an error stops the scan. The result is +the total number of rows delivered after reader filtering. + +```lisp +(.parquet.each [id text] "events.parquet" (fn [batch] (show batch))) +``` + +Each callback sees one batch: a grouped count inside it is local to that batch. +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, +a source containing an integer ID and text can be imported as: + +```lisp +(.parquet.splayed [I64 SYM] "events.parquet" "/tmp/events-native") +(set events (.db.splayed.get "/tmp/events-native")) +``` + +## `.parquet.parted` { #parquet-parted } + +Convert into `root//`, preserving source row +order. The default maximum partition size is 65,536 rows. `rows` accepts +1 through 1,048,576; source row-group boundaries also end partitions. + +```lisp +(.parquet.parted {types: [I64 SYM] rows: 262144} + "events.parquet" "/tmp/events-db" 'events) +(set events (.db.parted.get "/tmp/events-db" 'events)) +``` + +Both native conversions require an existing parent directory and a new +destination. They write to `.parquet-partial`, sync the completed +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. diff --git a/docs/docs/storage/index.md b/docs/docs/storage/index.md index 62b721165..4d41952e7 100644 --- a/docs/docs/storage/index.md +++ b/docs/docs/storage/index.md @@ -64,6 +64,60 @@ The symbol table is a dotfile (`.sym`, lock `.sym.lk`), so it never collides with a user column — a table may have an ordinary column named `sym` (the canonical ticker column), as shown above. +### Atomic table replacement + +When an existing splayed table is replaced, Rayforce writes the new schema and +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. + +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 +location and grows append-only. + +Publication keeps the selected generation and one previous generation, then +removes older staged directories best-effort. A failed unpublished generation is +removed immediately where the platform allows it; on Windows an open mapped file +can defer that cleanup until a later publish. At the first manifest publish, +the legacy root `.d` is retired so older binaries fail loudly instead of reading +obsolete root files. + +The `.write.lock` writer lock is local-filesystem coordination. Do not rely on +it for NFS-backed shared writers. + +The first write of a table directory, one without `.d` or `.current`, writes in +place. When it fails, the writer removes what it produced there and, once the +directory holds nothing else, the directory itself and every directory it +created above it, so no schema-less partition is left behind. A directory that +existed before the write is handled the same way, whether an operator pre-made +it or an earlier first write was killed: files that were there before the lock +was taken and that the write did not rewrite stay, since a directory without a +schema is not always a dead table. A partition directory left empty this way +is still a partition; `.db.parted.fill` gives it the missing tables. + +`ray_splay_save` (including `.db.splayed.set`) syncs primary data and directory +entries before acknowledging publication. Inline indexes are rebuildable +accelerators written with a marker-last protocol. The bulk C API and CSV import +retain their no-fsync contract: publication is atomic for readers, but is not a +power-loss durability guarantee. An I/O error after the manifest rename (during +the final directory sync) has an uncertain commit outcome; reopen the table to +inspect the selected generation. + +This protects publication of one splayed table. Coordinating a consistent +snapshot across multiple tables or date partitions still belongs to the caller. + ### C API | Function | Description | diff --git a/docs/docs/storage/ipc.md b/docs/docs/storage/ipc.md index 0dc8cfdee..e8e2bc168 100644 --- a/docs/docs/storage/ipc.md +++ b/docs/docs/storage/ipc.md @@ -114,6 +114,8 @@ The format is `"host:port"` for unauthenticated connections, or `"host:port:user | String | Parsed as Rayfall code and evaluated; result returned | | Any other value | Evaluated directly (identity for data, execution for expressions); result returned | +An optional third argument sets a deadline in milliseconds: `(.ipc.send h "(+ 1 2)" 5000)`. If the reply has not arrived by then, the connection is closed and an `io` error is returned. See [`.ipc.send`](../namespaces/ipc.md#ipc-send). + #### String queries ```text diff --git a/docs/parquet-completion-plan.md b/docs/parquet-completion-plan.md new file mode 100644 index 000000000..3568b2a67 --- /dev/null +++ b/docs/parquet-completion-plan.md @@ -0,0 +1,268 @@ +# Parquet completion plan + +Status: in progress, 2026-09-30. No third-party implementation or runtime +libraries. An external reference SQL engine is a development oracle only. Existing local work +and the measured full ClickBench splayed baseline are preserved. + +Current checkpoint: **P1's full-size evidence gates are complete**: all 43 +direct queries and all 12 partitioned load cases verified. P3's ClickBench +correctness gate is also complete. Final failure-path, fuzz, scalar and tooling +validation passed. The broader capabilities listed under P2–P6 remain +partial; see the explicit open list at the end. + +## P1: Establish the remaining end-to-end evidence + +- Extend the load harness to CSV and Parquet parted output. Compare every + cell with the retained, verified full CSV splayed reference, resolving each + output's symbol dictionary independently and respecting partition row order. +- Measure full 99,997,497-row loads at 8 and 28 workers, three repetitions, + including indexes, reopen and durable writes. Retain raw timings, resource + counters, schema, binary identity and correctness results. +- Run all 43 ClickBench query shapes against direct Parquet. Record individual + failures rather than stopping at the first unsupported query. Record any + necessary translations explicitly, including raw Unix temporal units. +- Check results against the reference SQL engine, accounting for SQL's unspecified tie ordering + and unordered LIMIT. Do not mark execution-only results as verified. +- Fix correctness failures before treating timings as performance evidence. + +Completion requires full-size parted load evidence and an explicit outcome for +every query: verified, incorrect, unsupported, timeout or resource failure. +The full direct-query correctness gate requires 43 verified queries; recording +failures is useful progress, not completion of that gate. + +## P2: Bound memory and improve import scaling + +- Profile dictionary insertion, dictionary flushing, decode, native indexes + and durable output separately at 1, 8 and 28 workers. +- Add an overall scratch-memory budget and admission/backpressure for row-group + work; account for page buffers, dictionaries and materialized results. +- Reduce shared symbol-domain work without changing symbol identity or row + order. Preserve batched insertion and block allocation. +- Build native index summaries during decoding, or reuse Parquet summaries + only where types, null semantics and index granularity are compatible. + Recompute when metadata is absent, untrusted or too coarse. +- Remove the additional splayed STR write pass where possible; handle the + native 32-bit string-pool limit explicitly. + +Acceptance: all-cell equivalence, bounded scratch under a configured budget, +and repeated full-load improvement against P1 and the existing splayed baseline. +Separate physical/logical CPU scaling and storage/memory limits in the report. + +## P3: Complete direct-query execution for the benchmark + +- Support explicit source type overrides, including raw temporal units and + dictionary-backed text, without materializing the entire file up front. +- Add string/dictionary predicates, safe additional predicate combinations, + and filter-first/output-later decoding. Measure bytes and pages avoided. +- Stream grouped aggregates and distinct with memory accounting; add spilling + before claiming bounded-memory execution for arbitrary cardinality or sorts. +- Broaden table-operation integration beyond select where a lazy source has + well-defined semantics. Preserve conservative fallback for dynamic expressions. + +Acceptance: all 43 full ClickBench queries verified; compare query latency, +peak memory and decoded bytes with the P1 record. Page-index/Bloom speedups +need representative indexed inputs because the ClickBench file has neither. + +## P4: Make import layouts operationally useful + +- Configurable rows per partition and date/key partitioning for CSV and Parquet. +- Checkpoint/resume with source identity and completed-part validation. +- Define append and schema-evolution behavior, then implement it with explicit + compatibility checks and recoverable publication. +- Test interruption, failed writes, restart and destination collision handling. + +Acceptance: deterministic row coverage/order for sequential partitions; +correct key routing for keyed partitions; resumed output equivalent to a fresh +import; no publication of incomplete output. + +## P5: Expand format coverage and fidelity + +- Native implementations of additional codecs and delta/byte-stream-split + encodings, prioritized by concrete input files. Each codec is a separate + reviewed change with malformed-input and cross-producer fixtures. +- Explicit mappings for decimal, fixed byte arrays, UINT64 and remaining + logical types; design nested LIST/MAP/STRUCT representation before decoding. +- Validate UTF-8 and define timezone-annotation retention. +- Resolve native null/value collisions before claiming lossless conversion. + This requires a storage/type-model decision, not a silent reader workaround. +- Add multi-file datasets, schema reconciliation and partition discovery; + remote sources follow a defined range-read and caching interface. + +Acceptance: an interoperability matrix, exact supported-value round trips or +documented rejection, and no added third-party library dependencies. + +## P6: Harden and document + +- Fuzz footer/page/encoding/index parsers and run sustained corruption tests. +- Exercise cancellation and allocation/write failures across parallel paths. +- Validate supported operating systems and architectures, including scalar + decoder fallbacks. Run sanitizers and focused leak checks. +- Publish reproducible load/query commands, raw measurements, supported + features and remaining limits. No performance claim without a matching run. + +## Evidence already complete + +- Full ClickBench CSV versus Parquet splayed import, 105 columns, three runs + at both 8 and 28 workers; every cell checked. +- Results: `bench/parquet_load/results/2026-09-30-full.json`. +- Final previous implementation passed 3,971 sanitizer tests. + +## Work log + +- 2026-09-30: P1 started. Existing load harness only supports splayed; query + oracle covers 12 shapes. Full input and verified CSV reference remain local. +- 2026-09-30, reboot recovery: recovered the interrupted session from its local + log. Source changes and the full splayed measurement report survived; the + input, CSV reference, sample query results and in-flight parted run under + `/tmp` did not. The current harness now handles parted all-cell verification + and all 43 direct-query shapes, including tie-aware oracle checks. +- Recovery work and raw logs now live under `build/parquet-recovery/` (ignored + by git, persistent across reboot). Restoring the exact Athena input from the + URL and SHA-256 recorded in `bench/parquet_load/results/2026-09-30-full.json`. +- Fixed repeated dictionary persistence: private Parquet imports flush the + shared domain after workers join; fresh CSV parted imports stage the root, + decode directly into its domain and flush once before rename. Existing CSV + roots keep flush-before-column behavior. Bulk CSV output still requires + external fsync for durability, as performed by the load harness. +- Added regressions for independently reopened symbols across parallel groups, + failed/stale CSV staging, trailing-slash destinations and existing-root + symbol replacement. ASan/UBSan: 3,974/3,974 passed. After final staging sync + and path checks: CSV 71/71 and Parquet 14/14 passed. Release build passed. +- Restored the full input: 14,779,976,446 bytes; SHA-256 matches + `a390f6cb782f6aaef278c72fc1dd86c4f30bc843ebab3c159e9bd4d45ddb079f`. + The recovery driver is now `build/parquet-recovery/continue.py`, with an atomic + `status.json` checkpoint and a log per phase. It runs a 1M-row query census, + reconstructs and verifies the full CSV splayed reference, measures all-cell + checked parted loads at 8/28 workers (three repetitions per format), then + runs the full 43-query census. Queries have a recorded 48-GiB address-space + ceiling and 180-second full-input timeout; resource failures remain failures. + The fixed release binary and its SHA-256 are retained alongside the logs. + Recovered full-size P1 evidence is pending; previous timing reports remain + historical evidence and P2–P6 are not marked complete. +- Recovered query discrepancies: duplicate tied rows now get an oracle + multiplicity check; Q29's Rayfall translation matches the SQL regexp's + newline/protocol/nonempty-host behavior; computed `by: {alias: expression}` + keys compile through the query DAG so `if` chooses a branch per row. + The latter also fixes ordinary in-memory queries. Regressions cover nested + conditions, prefiltering and references to earlier computed aliases. +- Final recovery validation: ASan/UBSan **3,975/3,975 passed**; the one-million-row + ClickBench sample has **43/43 queries verified** against the reference SQL engine, including + exact full-row membership and multiplicity for tied alternatives. Report: + `bench/parquet_load/results/2026-09-30-sample-queries.json`. Separate verifier + self-checks reject invented rows, wrong ranks and excess duplicate rows. +- The restored 99,997,497-row CSV splayed reference was checked against a full + Parquet import across all 105 columns. One recovered CSV parted case + overlapped diagnostics and was interrupted during external fsync; it is + excluded from performance evidence. The continuation checks its data, then + runs fresh measurements in `build/parquet-recovery/parted-final/` and the + full query census in `build/parquet-recovery/full-queries-final/`. Their + status is recorded in `build/parquet-recovery/status.json`; full-input + completion has not yet been claimed. Both benchmark harnesses now publish + their per-case result checkpoints by atomic replacement. +- The recovered CSV parted output passed every-cell comparison: + **99,997,497 rows × 105 columns, 1,526 partitions**. Fresh `parted-final` + measurements are running; the corrected full-input query census is queued + after them, without concurrent tests or diagnostic queries. +- Full-size direct-query baseline: **30/43 verified**. Nine queries hit the + 4 GiB STR pool limit; four exhausted the recorded 48 GiB address-space + allowance. Explicit `types` on reads/scans, backed by private refcounted + symbol domains, raised this to **39/43**. Results are preserved in + `bench/parquet_load/results/2026-09-30-full-query-baseline.json` and + `2026-09-30-full-query-typed.json`. +- Projection now recognizes arithmetic, conditionals and safe local bindings; + it falls back when a user lambda shadows a builtin. Inclusive integer + `within` predicates and standalone `like` filter before materialization. + Text is interned only after surviving a reader filter. The remaining four + full queries passed on the next build. Their focused report is + `2026-09-30-full-query-pushdown-four.json`; this combined evidence is not yet + the single-build 43-query gate. Private dictionaries now also use the + existing chunked derived-key evaluator, avoiding persistent intermediate + runtime symbols. +- First fresh partitioned pair at eight workers passed every-cell comparison: + CSV **303.638 s**, Parquet **815.970 s** (one run each, not medians). Repeated + per-column directory syncs were removed from private Parquet writes. Files + and directories are synced after workers join, before publication. A matched + 65,536-row diagnostic and a three-repeat 8/28-worker comparison at a + 262,144-row cap are queued on the frozen build. Row-group boundaries still + terminate Parquet partitions; reports record this difference. +- Native import options now accept `rows` (1..1,048,576), `types`, and `strict`. + Strict mode rejects decoded nonnull values that collide with native nulls + and malformed annotated UTF-8, without changing the default storage model. + Reader/scan options accept `strict` too. Regressions cover real nulls, + sentinel widening, both plain/dictionary paths, invalid UTF-8 classes, + custom partition sizes and refusal to publish a failed strict import. +- The current evidence driver is `build/parquet-recovery/finish-evidence.py`; + its atomic `progress.json` supersedes the older recovery status for ongoing + work. It gates on sanitizers, requires all 43 full queries to verify, then + runs the load measurements serially. The pinned release is + `build/parquet-recovery/rayforce-completion`. +- Added a native libFuzzer target (`fuzz/fuzz_parquet.c`) for footer, page, + encoding and optional index parsing, seeded with the small format fixtures. + Its sustained run is pending after performance measurements. +- Frozen build `3efe1db444730918af49610cb26a313729f54bc3ccc3f15fb61173f84ae0b86b` + passed **3,976/3,976 ASan/UBSan tests** and **43/43 full-input queries** with + the same 48 GiB address-space ceiling. The complete report is + `bench/parquet_load/results/2026-09-30-full-queries.json`. Q29 dropped from + 47.399 s / 38,091,648 KiB RSS to 10.085 s / 10,847,900 KiB RSS in the focused + and final runs, respectively, after enabling chunked expression evaluation + over the private dictionary. These are individual diagnostic timings. +- Write-failure review found success-path `fclose` results ignored by the + generic native column writer, including nested/list/table cases. Added error + propagation before rename and a Linux `RLIMIT_FSIZE` regression asserting + that both bulk and durable saves preserve an existing destination on a + buffered flush failure. Validation is queued after timings; this error-path + hardening is newer than the frozen benchmark binary. +- Matched 65,536-row Parquet diagnostic completed and passed all-cell + verification: **231.194 s** durable total, **146.540 s** process, versus the + earlier single run's 815.970 s / 730.660 s. OS page cache was managed normally; + this is a diagnostic comparison, not a repeated median. The 12-case + CSV/Parquet comparison at 8/28 workers and a 262,144-row cap is running. +- Added durable run manifests and `--resume` to both development harnesses. + They reject changed builds/settings/sources, preserve completed cases and + archive interrupted outputs before restarting a case. This does not add + native-import checkpoint/resume. A real small-input integration check is + queued after the timed runs, fuzzing and final sanitizer/scalar checks. + Copies of the harness actually used by the running load measurements are + retained in each work directory as `harness-used.py`; the resume additions + were made after those processes started. +- Added exclusive publication for new CSV and Parquet destinations: a final + rename cannot replace a concurrently created empty directory. Linux/macOS + use their no-replacement rename flags; Windows omits replacement permission. + Unsupported hosts/filesystems fail with staging retained. The destination + collision regression is queued with the final store checks. This hardening + also follows the frozen performance build. + +- The 12-case partitioned comparison completed: every output passed comparison + of all **10,499,737,185 cells** and native types. Durable medians at eight + workers are CSV **241.077 s**, Parquet **118.807 s** (**2.03×**); at 28 workers, + CSV **233.398 s**, Parquet **117.488 s** (**1.99×**). The cap is 262,144 rows; + CSV creates 382 partitions and Parquet 501 because row-group boundaries also + terminate partitions. Report: `2026-09-30-parted-full.json`. The matched-cap + diagnostic is `2026-09-30-parted-sync-diagnostic.json`. +- Final ASan/UBSan suite: **3,978/3,978 passed**. The same Parquet suite with + the SIMD translation unit compiled for its scalar fallback: **14/14 passed**. + Both native write-failure and exclusive-publication regressions pass. + An end-to-end 64-byte file-size-limit check reproduces incomplete publication + on the preserved old binary; the fixed binary returns an I/O error, retains + staging, and does not publish the destination. +- Real small-input restart integration checks pass for both harnesses, + including rejection of changed source/settings and retention of completed + cases. The native verifier rejects altered numeric data and dictionary text. + The final optimized rebuild also passes all-cell checks for both splayed + and partitioned imports of 1,000 rows × 105 columns. A dedicated `.parquet` + namespace reference is linked from the documentation navigation. + +- Sustained libFuzzer validation completed **9,600,493 inputs in 601 seconds** + with no ASan/UBSan/LSan findings; peak fuzzer RSS was 1,053 MiB. The successful + run used `setarch -R`, following the existing sanitizer/ASLR workaround. + Clang needed this host's GCC 11 C++ library search path for the development + fuzzer; the final product still links only libc, libm and the system loader. + The optimized binary also rejects the injected write failure before + publication. Raw validation details are recorded in + `bench/parquet_load/results/2026-09-30-validation.json`. + +Still open: a reader-wide memory budget/admission policy; arbitrary-cardinality +group/sort spilling; key/date partitions and crash-resumable imports; append and +schema evolution; additional concrete codecs/encodings, nested/multifile/remote +formats; broader platform and failure-injection validation. Passing ClickBench +does not imply these capabilities or completion of P2–P6. diff --git a/fuzz/README.md b/fuzz/README.md index 400af99b3..844d343cb 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -14,6 +14,7 @@ runtime). | `fuzz_eval` | `ray_eval_str` | full parse → eval pipeline (sandboxed) | | `fuzz_csv` | `ray_read_csv*` | CSV reader (input via memfd) | | `fuzz_journal` | `ray_journal_validate` / `ray_journal_replay` | journal framing walk + replay | +| `fuzz_parquet` | `ray_parquet_open` / `ray_parquet_next` | footer, page, encoding and optional index parsers | The journal log is a sequence of IPC frames verbatim, so the `de` corpus also hardens journal replay's decode step. @@ -87,3 +88,11 @@ crash-XXXX appears (CI artifact or local run) Error assertions in `.rfl` regression tests match the 7-byte error **code** (e.g. `!- parse`, `!- domain`), not the detailed message — the message is not part of the value rendered for comparison. + +`make fuzz-parquet FUZZ_RUNTIME=600` exercises the native Parquet footer, +page, dictionary, definition-level and optional index parsers under ASan/UBSan. +Its seeds are ordinary small Parquet files, including both page versions, +Snappy, checksums, malformed optional indexes and fidelity edge cases. The +driver consumes at most 256 batches of 257 rows per input to bound work from +forged row counts. It covers decoded/pruned reader paths; it does not certify +import publication, parallel scheduling or every supported producer. diff --git a/fuzz/fuzz_parquet.c b/fuzz/fuzz_parquet.c new file mode 100644 index 000000000..be24db1ed --- /dev/null +++ b/fuzz/fuzz_parquet.c @@ -0,0 +1,36 @@ +/* Copyright (c) 2026 Anton Kundenko. MIT license; see LICENSE. + * Native footer/page/encoding/index parser. Seeds are ordinary Parquet files. + * Bound the amount of output consumed so forged row counts cannot turn one + * input into unbounded materialization. The reader still checks each page it + * visits, including dictionary IDs, levels and decoded lengths. */ +#include "common.h" +#include "io/parquet.h" + +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + ray_fuzz_init(); + if (size < 12 || size > 1024*1024) return 0; + char path[64]; + int fd = ray_fuzz_memfd(data,size,path,sizeof(path)); + if (fd < 0) return 0; + ray_parquet_t* reader = NULL; + ray_t* err = ray_parquet_open(path,NULL,257,&reader); + if (err) ray_release(err); + else { + /* Exercise indexed pruning too. A missing/unsupported x column is + * an expected error and leaves the cursor available for plain scan. */ + if (size&1) { + err = ray_parquet_range(reader,ray_sym_intern("x",1),2,7); + if (err) ray_release(err); + } + for (int batch = 0; batch < 256; batch++) { + ray_t* table = ray_parquet_next(reader); + if (!table) break; + bool failed = RAY_IS_ERR(table); + ray_release(table); + if (failed) break; + } + } + ray_parquet_close(reader); + close(fd); + return 0; +} diff --git a/fuzz/seeds/parquet/all-null.parquet b/fuzz/seeds/parquet/all-null.parquet new file mode 100644 index 000000000..37bb59d59 Binary files /dev/null and b/fuzz/seeds/parquet/all-null.parquet differ diff --git a/fuzz/seeds/parquet/bloom-bad.parquet b/fuzz/seeds/parquet/bloom-bad.parquet new file mode 100644 index 000000000..830137134 Binary files /dev/null and b/fuzz/seeds/parquet/bloom-bad.parquet differ diff --git a/fuzz/seeds/parquet/bloom.parquet b/fuzz/seeds/parquet/bloom.parquet new file mode 100644 index 000000000..72491096f Binary files /dev/null and b/fuzz/seeds/parquet/bloom.parquet differ diff --git a/fuzz/seeds/parquet/bool.parquet b/fuzz/seeds/parquet/bool.parquet new file mode 100644 index 000000000..65da91796 Binary files /dev/null and b/fuzz/seeds/parquet/bool.parquet differ diff --git a/fuzz/seeds/parquet/empty.parquet b/fuzz/seeds/parquet/empty.parquet new file mode 100644 index 000000000..031d34d45 Binary files /dev/null and b/fuzz/seeds/parquet/empty.parquet differ diff --git a/fuzz/seeds/parquet/flat-0-v1.parquet b/fuzz/seeds/parquet/flat-0-v1.parquet new file mode 100644 index 000000000..cc1c6b96c Binary files /dev/null and b/fuzz/seeds/parquet/flat-0-v1.parquet differ diff --git a/fuzz/seeds/parquet/flat-0-v2.parquet b/fuzz/seeds/parquet/flat-0-v2.parquet new file mode 100644 index 000000000..91fb7922b Binary files /dev/null and b/fuzz/seeds/parquet/flat-0-v2.parquet differ diff --git a/fuzz/seeds/parquet/flat-1-v1.parquet b/fuzz/seeds/parquet/flat-1-v1.parquet new file mode 100644 index 000000000..fe2957dac Binary files /dev/null and b/fuzz/seeds/parquet/flat-1-v1.parquet differ diff --git a/fuzz/seeds/parquet/flat-1-v2.parquet b/fuzz/seeds/parquet/flat-1-v2.parquet new file mode 100644 index 000000000..7567c7163 Binary files /dev/null and b/fuzz/seeds/parquet/flat-1-v2.parquet differ diff --git a/fuzz/seeds/parquet/indexed-null.parquet b/fuzz/seeds/parquet/indexed-null.parquet new file mode 100644 index 000000000..481c37b40 Binary files /dev/null and b/fuzz/seeds/parquet/indexed-null.parquet differ diff --git a/fuzz/seeds/parquet/indexed-v1-bad.parquet b/fuzz/seeds/parquet/indexed-v1-bad.parquet new file mode 100644 index 000000000..61728c9ab Binary files /dev/null and b/fuzz/seeds/parquet/indexed-v1-bad.parquet differ diff --git a/fuzz/seeds/parquet/indexed-v1.parquet b/fuzz/seeds/parquet/indexed-v1.parquet new file mode 100644 index 000000000..a3dfceb12 Binary files /dev/null and b/fuzz/seeds/parquet/indexed-v1.parquet differ diff --git a/fuzz/seeds/parquet/indexed-v2-bad.parquet b/fuzz/seeds/parquet/indexed-v2-bad.parquet new file mode 100644 index 000000000..64b41cc22 Binary files /dev/null and b/fuzz/seeds/parquet/indexed-v2-bad.parquet differ diff --git a/fuzz/seeds/parquet/indexed-v2.parquet b/fuzz/seeds/parquet/indexed-v2.parquet new file mode 100644 index 000000000..42b19efa8 Binary files /dev/null and b/fuzz/seeds/parquet/indexed-v2.parquet differ diff --git a/fuzz/seeds/parquet/legacy.parquet b/fuzz/seeds/parquet/legacy.parquet new file mode 100644 index 000000000..c98687dc4 Binary files /dev/null and b/fuzz/seeds/parquet/legacy.parquet differ diff --git a/fuzz/seeds/parquet/no-statistics.parquet b/fuzz/seeds/parquet/no-statistics.parquet new file mode 100644 index 000000000..3f5c8e64f Binary files /dev/null and b/fuzz/seeds/parquet/no-statistics.parquet differ diff --git a/fuzz/seeds/parquet/projection.parquet b/fuzz/seeds/parquet/projection.parquet new file mode 100644 index 000000000..294f3c5a0 Binary files /dev/null and b/fuzz/seeds/parquet/projection.parquet differ diff --git a/fuzz/seeds/parquet/sentinels.parquet b/fuzz/seeds/parquet/sentinels.parquet new file mode 100644 index 000000000..45e61d922 Binary files /dev/null and b/fuzz/seeds/parquet/sentinels.parquet differ diff --git a/fuzz/seeds/parquet/simd-sentinels.parquet b/fuzz/seeds/parquet/simd-sentinels.parquet new file mode 100644 index 000000000..50e069bb3 Binary files /dev/null and b/fuzz/seeds/parquet/simd-sentinels.parquet differ diff --git a/fuzz/seeds/parquet/strict-collisions-0.parquet b/fuzz/seeds/parquet/strict-collisions-0.parquet new file mode 100644 index 000000000..fa45b2b42 Binary files /dev/null and b/fuzz/seeds/parquet/strict-collisions-0.parquet differ diff --git a/fuzz/seeds/parquet/strict-collisions-1.parquet b/fuzz/seeds/parquet/strict-collisions-1.parquet new file mode 100644 index 000000000..489764210 Binary files /dev/null and b/fuzz/seeds/parquet/strict-collisions-1.parquet differ diff --git a/fuzz/seeds/parquet/strict-good.parquet b/fuzz/seeds/parquet/strict-good.parquet new file mode 100644 index 000000000..91b8bf022 Binary files /dev/null and b/fuzz/seeds/parquet/strict-good.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-0.parquet b/fuzz/seeds/parquet/strict-utf8-0.parquet new file mode 100644 index 000000000..e47b34c20 Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-0.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-1.parquet b/fuzz/seeds/parquet/strict-utf8-1.parquet new file mode 100644 index 000000000..944aa9136 Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-1.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-2.parquet b/fuzz/seeds/parquet/strict-utf8-2.parquet new file mode 100644 index 000000000..fbe71250b Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-2.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-3.parquet b/fuzz/seeds/parquet/strict-utf8-3.parquet new file mode 100644 index 000000000..ea9c3b505 Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-3.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-4.parquet b/fuzz/seeds/parquet/strict-utf8-4.parquet new file mode 100644 index 000000000..075ec5f55 Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-4.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-5.parquet b/fuzz/seeds/parquet/strict-utf8-5.parquet new file mode 100644 index 000000000..b9c9606ae Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-5.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-6.parquet b/fuzz/seeds/parquet/strict-utf8-6.parquet new file mode 100644 index 000000000..ab966e173 Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-6.parquet differ diff --git a/fuzz/seeds/parquet/strict-utf8-7.parquet b/fuzz/seeds/parquet/strict-utf8-7.parquet new file mode 100644 index 000000000..884c4b039 Binary files /dev/null and b/fuzz/seeds/parquet/strict-utf8-7.parquet differ diff --git a/fuzz/seeds/parquet/unix.parquet b/fuzz/seeds/parquet/unix.parquet new file mode 100644 index 000000000..9a67b49e0 Binary files /dev/null and b/fuzz/seeds/parquet/unix.parquet differ diff --git a/fuzz/seeds/parquet/v2-uncompressed.parquet b/fuzz/seeds/parquet/v2-uncompressed.parquet new file mode 100644 index 000000000..eabe9e0f4 Binary files /dev/null and b/fuzz/seeds/parquet/v2-uncompressed.parquet differ diff --git a/include/rayforce.h b/include/rayforce.h index 7b23814f7..a683794e1 100644 --- a/include/rayforce.h +++ b/include/rayforce.h @@ -64,6 +64,10 @@ int ray_version_major(void); int ray_version_minor(void); int ray_version_patch(void); const char* ray_version_string(void); +/* The commit this library was built from, as its build saw it ("unknown" + * outside a git checkout). A compile-time constant: safe to call before + * any runtime exists. */ +const char* ray_git_commit(void); /* ===== Type Constants ===== */ @@ -358,6 +362,8 @@ void ray_free_raw(void* p); /* ===== System memory ===== */ int64_t ray_sys_total_ram(void); /* total physical RAM in bytes (informational) */ +int64_t ray_sys_ram_limit(void); /* RAM this process may use: min(physical RAM, + * container/cgroup limit); the default anon watermark */ /* ===== Interrupt API ===== * Long-running queries poll ray_interrupted() at morsel granularity @@ -648,6 +654,8 @@ int64_t ray_sym_intern_runtime(const char* str, size_t len); int64_t ray_sym_find(const char* str, size_t len); ray_t* ray_sym_str(int64_t id); uint32_t ray_sym_count(void); +/* Bytes of string storage the global symbol table holds (its arena). */ +size_t ray_sym_bytes(void); /* Borrow a snapshot of the sym → string array. Returns a pointer to * the underlying ray_t** strings table along with its length; valid @@ -841,6 +849,10 @@ int64_t ray_ipc_connect(const char* host, uint16_t port, int timeout_ms); void ray_ipc_close(int64_t handle); ray_t* ray_ipc_send(int64_t handle, ray_t* msg); +/* As ray_ipc_send, bounded: timeout_ms > 0 caps the whole round trip. + * On expiry the connection is closed (on.close fires) and an `io` error + * is returned; timeout_ms <= 0 waits indefinitely, like ray_ipc_send. */ +ray_t* ray_ipc_send_timeout(int64_t handle, ray_t* msg, int64_t timeout_ms); ray_err_t ray_ipc_send_async(int64_t handle, ray_t* msg); ray_t* ray_ipc_send_verbose(int64_t handle, ray_t* msg); diff --git a/mkdocs.yml b/mkdocs.yml index f70922102..bfce5679a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -135,6 +135,7 @@ nav: - .mc — Multicast: multicast-usage.md - .mem — Measurement: docs/namespaces/mem.md - .os — Process env: docs/namespaces/os.md + - .parquet — Parquet input: docs/namespaces/parquet.md - .repl — REPL control: docs/namespaces/repl.md - .sys — System info: docs/namespaces/sys.md - .time — Clock & timers: docs/namespaces/time.md diff --git a/scripts/parquet-bench.py b/scripts/parquet-bench.py new file mode 100644 index 000000000..d2bfe436f --- /dev/null +++ b/scripts/parquet-bench.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Time dependency-free Parquet scans on a bounded ClickBench sample. + +Build Rayforce in release mode first. Reports in-process warm medians, excluding +one warmup per case. This does not replace the full ClickBench workload. +""" +import argparse +import json +import statistics +import subprocess +import tempfile +from pathlib import Path + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('parquet',type=Path) + ap.add_argument('--rayforce',type=Path,default=Path('./rayforce')) + ap.add_argument('--cores',type=int,nargs='+',default=[1,4]) + ap.add_argument('--repeats',type=int,default=5) + a = ap.parse_args() + if a.repeats < 1 or any(c < 1 for c in a.cores): ap.error('repeats and cores must be positive') + path = json.dumps(str(a.parquet.resolve())) + cases = { + 'scan_all_105_columns': f'(.parquet.each {path} (fn [b] (count b)))', + 'scan_9_columns': f'(.parquet.each [CounterID AdvEngineID ResolutionWidth UserID RegionID EventDate EventTime URL Title] {path} (fn [b] (count b)))', + 'lazy_footer_count': '(select {from: source n: (count WatchID)})', + 'lazy_stream_aggregates': '(select {from: source s: (sum JavaEnable) lo: (min EventTime) hi: (max EventTime)})', + } + report = [] + with tempfile.TemporaryDirectory(prefix='rayforce-parquet-bench-') as tmp: + script = Path(tmp)/'bench.rfl' + for cores in a.cores: + for name, expr in cases.items(): + lines = [f'(set source (.parquet.scan {path}))',expr] + lines += [f'(println (timeit {expr}))']*a.repeats + lines.append('(exit 0)'); script.write_text('\n'.join(lines)+'\n') + run = subprocess.run([str(a.rayforce.resolve()),'-c',str(cores),str(script)],check=True,capture_output=True,text=True) + times = [float(x) for x in run.stdout.splitlines() if x.strip()] + if len(times) != a.repeats: raise RuntimeError(f'unexpected benchmark output: {run.stdout}') + report.append({'case':name,'cores':cores,'median_ms':statistics.median(times),'runs_ms':times}) + print(json.dumps({'source':str(a.parquet.resolve()),'warmup_runs':1,'results':report},indent=2)) + +if __name__ == '__main__': + main() diff --git a/scripts/parquet-clickbench.py b/scripts/parquet-clickbench.py new file mode 100644 index 000000000..c8fa3c6a2 --- /dev/null +++ b/scripts/parquet-clickbench.py @@ -0,0 +1,299 @@ +#!/usr/bin/env python3 +"""Full ClickBench direct-Parquet census, with an external reference SQL oracle. + +Standard library only. One fresh process per query; retain scripts, CSVs, +logs, query time and process RSS. This is a diagnostic census, not the official +ClickBench score. Tied/unordered LIMIT alternatives need rank and full-row +membership checks. Temporal values stay in the source's Unix units. +""" +import argparse +import csv +import datetime +import hashlib +import json +import math +import os +from pathlib import Path +from parquet_checkpoint import archive_partial, digest, open_run, save +import re +import resource +import signal +import shutil +import subprocess +import time + + +def file_sha256(path): + digest = hashlib.sha256() + with Path(path).open('rb') as f: + for chunk in iter(lambda: f.read(8 * 1024 * 1024), b''): + digest.update(chunk) + return digest.hexdigest() + + +def translate(number, ray, sql): + changes = [] + if number in (1, 2, 5, 6, 21): + bodies = {1: 'n: (count WatchID)', + 2: 'n: (count AdvEngineID) where: (!= AdvEngineID 0)', + 5: 'n: (count (distinct UserID))', + 6: 'n: (count (distinct SearchPhrase))', + 21: 'n: (count URL) where: (like URL "*google*")'} + ray = '(select {from: hits ' + bodies[number] + '})' + changes.append('express scalar count/column access through lazy select') + if number == 19: + ray = ray.replace('(minute EventTime)', '(% (div EventTime 60) 60)') + sql = sql.replace('extract(minute FROM EventTime)', '(EventTime // 60) % 60') + changes.append('minute from explicit Unix seconds') + if number in (25, 27): + sql = sql.replace('SELECT SearchPhrase FROM', 'SELECT SearchPhrase, EventTime FROM') + changes.append('retain EventTime projected by the ClickBench Rayforce query') + if number == 29: + # Match the SQL regexp exactly: its dot does not match a newline in + # the path, the protocol must be http(s), and the hostname is nonempty. + # For www./ the optional prefix must backtrack, leaving host www. + key = ('(let p (str-find Referer "://") ' + '(let s (substr Referer (+ p 4) -1) ' + '(let sl (str-find s "/") ' + '(if (and (or (== (substr Referer 1 7) "http://") ' + '(== (substr Referer 1 8) "https://")) (> sl 0) ' + '(nil? (str-find (substr s (+ sl 2) -1) "\\n"))) ' + '(if (and (== (str-find s "www.") 0) (> sl 4)) ' + '(substr s 5 (- sl 4)) (substr s 1 sl)) Referer))))') + start = ray.index('by: ') + len('by: ') + end = ray.index(' l: ', start) + ray = ray[:start] + key + ray[end:] + changes.append('match SQL URL regexp protocol, nonempty host and newline semantics') + if number == 36: + sql = sql.replace('SELECT ClientIP, ClientIP - 1, ClientIP - 2, ClientIP - 3, COUNT(*) AS c', + 'SELECT ClientIP, COUNT(*) AS c, ClientIP - 1, ClientIP - 2, ClientIP - 3') + changes.append('align computed-group-key output column order') + if number >= 37: + def days(match): + return str((datetime.date.fromisoformat(match[0].strip("'").replace('.', '-')) - + datetime.date(1970, 1, 1)).days) + ray = re.sub(r'2013\.07\.\d\d', days, ray) + sql = re.sub(r"'2013-07-\d\d'", days, sql) + changes.append('date predicates in explicit Unix days') + if number == 43: + ray = ray.replace('(xbar EventTime 60000000000)', '(xbar EventTime 60)') + sql = sql.replace("DATE_TRUNC('minute', EventTime)", '(EventTime // 60) * 60') + changes.append('minute buckets in explicit Unix seconds') + return ray, sql, changes + + +def run(command, log, timeout, address_space_gib=0): + def limits(): + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + if address_space_gib: + size = address_space_gib * 1024**3 + resource.setrlimit(resource.RLIMIT_AS, (size, size)) + start = time.monotonic() + with log.open('w') as output: + process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT, + start_new_session=True, preexec_fn=limits) + try: + code = process.wait(timeout=timeout) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {'status': 'timeout', 'wall_seconds': time.monotonic()-start} + return {'status': 'executed' if code == 0 else 'execution_failed', + 'returncode': code, 'wall_seconds': time.monotonic()-start} + + +def compare(actual, expected): + # Oracle CSV header spellings differ; compare positional output. Averages + # alone accept rounding tolerance; strings that look numeric remain strings. + if len(actual) != len(expected): + return False, 'row count differs' + for i, (a, b) in enumerate(zip(actual, expected)): + if len(a) != len(b): + return False, 'column count differs' + for c, (x, y) in enumerate(zip(a, b)): + if x == y: + continue + if isinstance(y, float): + try: + if math.isclose(float(x), y, rel_tol=1e-12, abs_tol=1e-12): + continue + except ValueError: + pass + elif y is not None and x == str(y): + continue + return False, f'row {i}, column {c}: {x!r} != {y!r}' + return True, None + + +def verify_ties(a, stem, ray, sql, setup, headers, actual, expected): + """Check rank keys, full-row membership, and multiplicity independently. + + Never accept a different result merely because LIMIT admits ties. The + expected rank sequence includes OFFSET. Unordered Q18 needs membership. + Duplicate rows may be valid (e.g. repeated SearchPhrase/EventTime pairs). + Require enough matching source rows for every repeated output tuple. + """ + if len(actual) != len(expected) or not actual: + return False + # Distinct near-equal float tuples must not both claim the same oracle row. + if any(isinstance(x, float) for r in expected for x in r) and len(set(map(tuple, actual))) != len(actual): + return False + order = re.findall(r'(?:asc|desc):\s*(\[[^]]+\]|\w+)', ray) + if order: + keys = order[-1].strip('[]').split() + if any(k not in headers for k in keys): + return False + indices = [headers.index(k) for k in keys] + if not compare([[r[i] for i in indices] for r in actual], + [[r[i] for i in indices] for r in expected])[0]: + return False + elif 'ORDER BY' in sql: + return False + base = re.split(r'\s+(?:ORDER BY|LIMIT)\s+', sql, flags=re.I)[0].rstrip(';') + names = [f'c{i}' for i in range(len(headers))] + comparisons = [] + for i, name in enumerate(names): + if isinstance(expected[0][i], float): + comparisons.append(f'abs(try_cast(a.{name} AS DOUBLE)-r.{name}) <= ' + f'1e-12 * greatest(1, abs(r.{name}))') + else: + comparisons.append(f"coalesce(a.{name}, '') = coalesce(cast(r.{name} AS VARCHAR), '')") + path = "'" + str(stem.with_suffix('.csv')).replace("'", "''") + "'" + query = (setup + f'WITH r({",".join(names)}) AS ({base}), ' + f'a0({",".join(names)}) AS (SELECT * FROM read_csv({path}, header=true, all_varchar=true)), ' + f'a AS (SELECT *, count(*) OVER (PARTITION BY {",".join(names)}) AS copies FROM a0) ' + 'SELECT count(*) AS matches FROM a WHERE ' + f'(SELECT count(*) FROM r WHERE {" AND ".join(comparisons)}) >= a.copies;') + stem.with_suffix('.ties.sql').write_text(query+'\n') + output = stem.with_suffix('.ties.json') + status = run([a.oracle, '-json', '-c', query], output, a.timeout) + if status['status'] != 'executed': + return False + return json.loads(output.read_text())[0]['matches'] == len(actual) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('parquet', type=Path) + p.add_argument('--rayforce', type=Path, default=Path('./rayforce')) + p.add_argument('--clickbench', type=Path, default=Path('../ClickBench')) + p.add_argument('--oracle', required=True, help='reference SQL CLI executable') + p.add_argument('--oracle-queries', type=Path, required=True, help='reference SQL file: 43 ClickBench queries, one per line') + p.add_argument('--cores', type=int, default=os.cpu_count()) + p.add_argument('--timeout', type=int, default=180) + p.add_argument('--address-space-gib', type=int, default=0, + help='optional process virtual-memory ceiling, explicitly recorded') + p.add_argument('--queries', type=int, nargs='+', default=list(range(1, 44))) + p.add_argument('--symbol-text', action='store_true', + help='decode text into private SYM dictionaries; keep temporal source integers') + p.add_argument('--work-dir', type=Path, required=True) + p.add_argument('--resume', action='store_true', help='continue an unchanged checkpointed census') + a = p.parse_args() + if a.cores < 1 or a.timeout < 1 or any(q not in range(1, 44) for q in a.queries): + p.error('invalid cores, timeout or query numbers') + if len(set(a.queries)) != len(a.queries): p.error('query numbers must not contain duplicates') + root = a.work_dir.resolve() + if a.resume: + if not root.is_dir(): p.error('--resume requires an existing work directory') + else: root.mkdir(exist_ok=False) + ray_queries = (a.clickbench/'rayforce/queries.sql').read_text().splitlines() + sql_queries = a.oracle_queries.read_text().splitlines() + if len(ray_queries) != 43 or len(sql_queries) != 43: + raise RuntimeError('expected 43 one-line queries per ClickBench adapter') + options = '' + source_types = None + if a.symbol_text: + schema = (a.clickbench/'rayforce/create.rfl').read_text() + match = re.search(r'\(set hits-types \[([^]]+)\]', schema, re.S) + if not match: raise RuntimeError('cannot find ClickBench types') + source_types = ['I64' if t == 'TIMESTAMP' else 'I32' if t == 'DATE' else t + for t in match.group(1).split()] + options = '{types: [' + ' '.join(source_types) + ']} ' + report = {'input': str(a.parquet.resolve()), 'input_bytes': a.parquet.stat().st_size, + 'input_sha256': file_sha256(a.parquet), + 'binary_sha256': hashlib.sha256(a.rayforce.read_bytes()).hexdigest(), + 'harness_sha256': file_sha256(__file__), + 'cores': a.cores, 'timeout_seconds': a.timeout, + 'address_space_gib': a.address_space_gib, 'cache': 'OS-managed', + 'source_types': source_types, + 'method': 'fresh process per query; query timing excludes result CSV; not official ClickBench score', + 'results': []} + identity = {k:v for k,v in report.items() if k != 'results'} + identity.update(queries=a.queries,ray_queries_sha256=digest(a.clickbench/'rayforce/queries.sql'), + sql_queries_sha256=digest(a.oracle_queries), + checkpoint_sha256=digest(Path(__file__).with_name('parquet_checkpoint.py')), + oracle_sha256=digest(shutil.which(a.oracle) or a.oracle)) + previous = open_run(root,a.resume,identity) + if previous: report = previous + completed = {x['query'] for x in report['results']} + if len(completed) != len(report['results']): raise RuntimeError('duplicate query checkpoints') + if not completed <= set(a.queries): raise RuntimeError('unexpected query checkpoint') + for number in a.queries: + if number in completed: continue + ray, sql, changes = translate(number, ray_queries[number-1], sql_queries[number-1]) + stem = root/f'q{number:02d}' + archive_partial(root,list(root.glob(stem.name+'.*'))) + output = stem.with_suffix('.csv') + script = stem.with_suffix('.rfl') + script.write_text(f'(set hits (.parquet.scan {options}{json.dumps(str(a.parquet.resolve()))}))\n' + f'(println (timeit (set result {ray})))\n' + f'(.csv.write result {json.dumps(str(output))})\n(exit 0)\n') + timing = stem.with_suffix('.time') + print(f'Q{number:02d} Rayforce', flush=True) + result = run(['/usr/bin/time', '-f', '%e %M %U %S', '-o', str(timing), + str(a.rayforce.resolve()), '-c', str(a.cores), str(script)], + stem.with_suffix('.log'), a.timeout, a.address_space_gib) + result.update(query=number, translations=changes, rayfall=ray, sql=sql, verified=False) + log_text = stem.with_suffix('.log').read_text() + try: + result['query_ms'] = float(log_text.splitlines()[0]) + except (ValueError, IndexError): + result['diagnostic'] = log_text[-2000:] + if timing.exists(): + lines = timing.read_text().splitlines() + tokens = lines[-1].split() if lines else [] + if len(tokens) == 4: + result.update(process_seconds=float(tokens[0]), peak_rss_kib=int(tokens[1]), + user_seconds=float(tokens[2]), system_seconds=float(tokens[3])) + if result['status'] == 'executed' and output.exists(): + print(f'Q{number:02d} reference SQL engine', flush=True) + source = "'" + str(a.parquet.resolve()).replace("'", "''") + "'" + setup = f"SET threads={a.cores}; SET memory_limit='32GB'; CREATE VIEW hits AS SELECT * FROM read_parquet({source}); " + oracle_sql = setup + sql + stem.with_suffix('.sql').write_text(oracle_sql+'\n') + oracle_path = stem.with_suffix('.oracle.json') + oracle = run([a.oracle, '-json', '-c', oracle_sql], oracle_path, a.timeout) + result['oracle'] = oracle + if oracle['status'] == 'executed': + rows = json.loads(oracle_path.read_text().strip() or '[]') + expected = [list(row.values()) for row in rows] + with output.open(newline='') as f: + reader = csv.reader(f); headers = next(reader); actual = list(reader) + matched, mismatch = compare(actual, expected) + if not matched and ('LIMIT' in sql or number == 8): + matched = verify_ties(a, stem, ray, sql, setup, headers, actual, expected) + if matched: + result['tie_validation'] = 'rank sequence, full-row oracle membership and multiplicity' + result['initial_order_difference'] = mismatch + mismatch = None + result.update(verified=matched, rows=len(actual), mismatch=mismatch) + if matched: + result['status'] = 'verified' + else: + # A diagnostic flag, not an assertion that the result is + # valid: tie-aware membership validation is still required. + result['status'] = 'mismatch' + result['ordering_may_be_ambiguous'] = 'LIMIT' in sql or number == 8 + else: + result['status'] = 'oracle_failed' + elif result['status'] == 'executed': + result['status'] = 'missing_output' + report['results'].append(result) + save(root/'results.json',report) + print(f'Q{number:02d}: {result["status"]}', flush=True) + if (root/'stop').exists(): + break + + +if __name__ == '__main__': + main() diff --git a/scripts/parquet-harness-selftest.py b/scripts/parquet-harness-selftest.py new file mode 100644 index 000000000..20b687013 --- /dev/null +++ b/scripts/parquet-harness-selftest.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Exercise benchmark restart gates with real small imports and query oracles.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import struct +import subprocess +import sys +import time + + +def fingerprint(path): return hashlib.sha256(path.read_bytes()).hexdigest() + + +def run(command, stop_after_first=None, fail=False): + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, start_new_session=True) + if stop_after_first: + # run.json is durable before the first timed import/query starts. + deadline = time.monotonic()+60 + while not (stop_after_first/'run.json').exists() and process.poll() is None: + if time.monotonic() > deadline: + os.killpg(process.pid,signal.SIGKILL); process.communicate() + raise RuntimeError('checkpoint startup timed out') + time.sleep(.001) + (stop_after_first/'stop').touch() + try: output, _ = process.communicate(timeout=120) + except subprocess.TimeoutExpired: + os.killpg(process.pid,signal.SIGKILL); output, _ = process.communicate() + raise RuntimeError('harness self-test timed out:\n'+output) + if (process.returncode != 0) != fail: raise RuntimeError(output) + return output + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('source',type=Path,help='ClickBench Parquet input') + p.add_argument('--rayforce',type=Path,required=True) + p.add_argument('--native-verifier',type=Path,required=True) + p.add_argument('--oracle',required=True,help='reference SQL CLI executable') + p.add_argument('--oracle-queries', type=Path, required=True, help='reference SQL file: 43 ClickBench queries, one per line') + p.add_argument('--work-dir',type=Path,required=True) + a=p.parse_args(); root=a.work_dir.resolve(); root.mkdir(exist_ok=False) + pq=root/'small.parquet'; csv=root/'small.csv' + quote=lambda s: "'"+str(s).replace("'","''")+"'" + subprocess.run([a.oracle,'-c',f'COPY (SELECT * FROM read_parquet({quote(a.source.resolve())}) LIMIT 1000) TO {quote(pq)} (FORMAT PARQUET, COMPRESSION SNAPPY)'],check=True) + load=root/'loads' + command=[sys.executable,'scripts/parquet-load-bench.py',str(pq),str(csv),'--prepare-csv', + '--rayforce',str(a.rayforce.resolve()),'--native-verifier',str(a.native_verifier.resolve()), + '--oracle',a.oracle,'--cores','1','2','--repeats','1','--work-dir',str(load)] + run(command,load) + before=json.loads((load/'results.json').read_text()); assert len(before['results'])==1 + (load/'stop').unlink() + partial=load/'parquet-1-0.parquet-partial'; partial.mkdir(); (partial/'sentinel').write_text('retain me') + run(command+['--resume']) + after=json.loads((load/'results.json').read_text()) + assert len(after['results'])==4 and all(x['verified'] for x in after['results']) + assert after['results'][0]==before['results'][0] + assert len(list(load.glob('interrupted-*/parquet-1-0.parquet-partial/sentinel')))==1 + # Verify the verifier against damaged copies of the retained reference. + reference=Path(after['reference']); damaged=root/'damaged-native' + shutil.copytree(reference,damaged) + names=sorted(p.name for p in reference.iterdir() if p.is_file() and not p.name.startswith('.')) + verify=[str(a.native_verifier.resolve()),str(reference),str(damaged),*names] + column=damaged/'WatchID'; original=column.read_bytes() + changed=bytearray(original); changed[32]^=1; column.write_bytes(changed) + assert 'value mismatch' in run(verify,fail=True) + column.write_bytes(original) + symbols=damaged/'.sym'; changed=bytearray(symbols.read_bytes()); offset=12 + while offset len(self.data)-self.pos: raise ValueError('truncated compact value') + p = self.pos; self.pos += n + return self.data[p:self.pos] + def var(self): + n = 0 + for shift in range(0,70,7): + b = self.take(1)[0] + if shift == 63 and b > 1: raise ValueError('varint overflow') + n |= (b & 127) << shift + if not b & 128: return n + raise ValueError('varint overflow') + def integer(self): + v = self.var(); return (v >> 1) ^ -(v & 1) + def value(self, t, depth=0): + if depth > 32: raise ValueError('compact nesting limit') + if t in (1,2): return t == 1 + if t == 3: return self.take(1)[0] + if t in (4,5,6): return self.integer() + if t == 7: return self.take(8) + if t == 8: return self.take(self.var()) + if t in (9,10): + h = self.take(1)[0]; n = h >> 4 + if n == 15: n = self.var() + if n > len(self.data)-self.pos: raise ValueError('invalid list length') + et = h & 15 + return et, [self.take(1)[0] == 1 if et in (1,2) else self.value(et,depth+1) for _ in range(n)] + if t == 12: + out = []; fid = 0 + while True: + h = self.take(1)[0] + if not h: return out + fid = fid + (h >> 4) if h >> 4 else self.integer() + out.append((fid, h & 15, self.value(h & 15,depth+1))) + raise ValueError(f'unsupported compact type {t}') + +def var(n): + out = bytearray() + while n > 127: out.append((n & 127) | 128); n >>= 7 + return bytes(out + bytes([n])) + +def encode(t, v): + if t in (1,2): return b'' + if t == 3: return bytes([v]) + if t in (4,5,6): return var((v << 1) ^ (v >> 63)) + if t == 7: return v + if t == 8: return var(len(v)) + v + if t in (9,10): + et, items = v; n = len(items) + return bytes([(min(n,15)<<4)|et]) + (var(n) if n >= 15 else b'') + b''.join(bytes([1 if x else 2]) if et in (1,2) else encode(et,x) for x in items) + if t == 12: + out = bytearray(); last = 0 + for fid,ft,fv in v: + delta = fid-last + out += bytes([(delta<<4)|ft]) if 0 < delta < 16 else bytes([ft])+encode(4,fid) + out += encode(ft,fv); last = fid + return bytes(out + b'\0') + raise ValueError(t) + +def get(fields, fid, default=None): + return next((v for i,t,v in fields if i == fid), default) + +def put(fields, fid, val): + return [(i,t,val if i == fid else v) for i,t,v in fields] + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source'); parser.add_argument('--sample',type=Path) + parser.add_argument('--groups',type=int,default=1) + a = parser.parse_args() + remote = a.source.startswith(('https://','http://')) + if remote: + headers = subprocess.run(['curl','--fail','--silent','--show-error','--head',a.source],check=True,capture_output=True).stdout.decode() + sizes = [line.split(':',1)[1].strip() for line in headers.splitlines() if line.lower().startswith('content-length:')] + if not sizes: raise ValueError('server did not provide Content-Length') + size = int(sizes[-1]) + else: size = Path(a.source).stat().st_size + def read(start, n): + if start < 0 or n < 0 or start+n > size: raise ValueError('range outside file') + if remote: + data = subprocess.run(['curl','--fail','--silent','--show-error','--range',f'{start}-{start+n-1}', + '--max-filesize',str(n),a.source],check=True,capture_output=True).stdout + else: + with open(a.source,'rb') as f: f.seek(start); data = f.read(n) + if len(data) != n: raise ValueError('short/oversized range response') + return data + tail = read(size-8,8) + if tail[4:] != b'PAR1': raise ValueError('not an unencrypted Parquet file') + footer_len = struct.unpack(' 64*1024*1024: raise ValueError('footer exceeds 64 MiB') + reader = Compact(read(size-8-footer_len,footer_len)); meta = reader.value(12) + schema = get(meta,2)[1]; groups = get(meta,4)[1] + codecs = collections.Counter(); encodings = collections.Counter(); stats = pages = blooms = 0 + for group in groups: + for chunk in get(group,1)[1]: + md = get(chunk,3) + codecs[get(md,4)] += 1; encodings[str(get(md,2)[1])] += 1 + stats += get(md,12) is not None + pages += get(chunk,4) is not None and get(chunk,6) is not None + blooms += get(md,14) is not None + print(json.dumps({'source':a.source,'bytes':size,'rows':get(meta,3),'columns':len(schema)-1, + 'row_groups':len(groups),'created_by':get(meta,6,b'').decode(),'codec_counts':dict(codecs), + 'encoding_counts':dict(encodings),'chunks_with_statistics':stats,'chunks_with_page_indexes':pages, + 'chunks_with_bloom_filters':blooms},indent=2)) + if a.sample: + if not 1 <= a.groups <= len(groups): raise ValueError('invalid group count') + selected=[]; total=0 + # Exclusive output prevents accidental overwrite of a sample. + with a.sample.open('xb') as out: + out.write(b'PAR1') + for group in groups[:a.groups]: + chunks=[] + for chunk in get(group,1)[1]: + md = get(chunk,3) + if get(chunk,1) is not None: raise ValueError('external column file') + offset=min(get(md,9),get(md,11,get(md,9))); length=get(md,7) + new_offset=out.tell(); out.write(read(offset,length)) + delta=new_offset-offset + for fid in (9,10,11): + if get(md,fid) is not None: md=put(md,fid,get(md,fid)+delta) + # Drop source index/bloom references; sample has no copied index regions. + md=[x for x in md if x[0] not in (14,15)] + chunks.append([(2,6,new_offset),(3,12,md)]) + group=put(group,1,(12,chunks)) + group=[x for x in group if x[0] not in (5,6,7)] + selected.append(group); total+=get(group,3) + meta=put(put(meta,3,total),4,(12,selected)); footer=encode(12,meta) + out.write(footer); out.write(struct.pack(' the identical native schema. + +Standard library only. Inputs must contain the same rows in the same order. +CSV is headerless, with ISO dates/timestamps, as in ClickBench/rayforce/load.rfl. +The published Athena Parquet uses unannotated Unix seconds/days; these units +are explicit in the import schema. Download/export are outside load timing. +Every measured load includes process startup, native indexes, reopening, and +fsync of all output files/directories. Inputs use the OS page cache (no privileged +cache drop). Each output is checked against the first CSV import, then removed. +""" +import argparse +import hashlib +import json +import os +import platform +import re +import shutil +import statistics +import subprocess +import tempfile +import time +from pathlib import Path +from parquet_checkpoint import archive_partial, digest, file_identity, open_run, save + + +def sync_tree(root): + for parent, dirs, files in os.walk(root, topdown=False): + for name in files: + fd = os.open(Path(parent)/name, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + fd = os.open(parent, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + fd = os.open(root.parent, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('parquet', type=Path); p.add_argument('csv', type=Path) + p.add_argument('--rayforce', type=Path, default=Path('./rayforce')) + p.add_argument('--clickbench', type=Path, default=Path('../ClickBench')) + p.add_argument('--cores', type=int, nargs='+', default=[1,8,28]) + p.add_argument('--repeats', type=int, default=3) + p.add_argument('--reference', type=Path, help='existing verified native CSV reference; retained') + p.add_argument('--kinds', choices=['csv','parquet'], nargs='+', default=['csv','parquet']) + p.add_argument('--prepare-csv', action='store_true', help='export identical rows with external reference SQL engine before timing; CSV must not exist') + p.add_argument('--oracle', help='reference SQL CLI executable') + p.add_argument('--native-verifier', type=Path, help='bounded-memory verifier built from bench/parquet_load/verify-native.c') + p.add_argument('--layout', choices=['splayed','parted'], default='splayed') + p.add_argument('--partition-rows', type=int, default=65536, + help='maximum rows per partition (Parquet also splits at row-group boundaries)') + p.add_argument('--work-dir', type=Path, required=True) + p.add_argument('--resume', action='store_true', help='continue an unchanged checkpointed run; retain completed verified cases') + a = p.parse_args() + if a.prepare_csv and not a.resume and not a.oracle: p.error('--prepare-csv requires --oracle') + if a.repeats < 1 or any(c < 1 for c in a.cores): p.error('positive repeats/cores required') + if len(set(a.cores)) != len(a.cores) or len(set(a.kinds)) != len(a.kinds): p.error('cores and kinds must not contain duplicates') + if not 1 <= a.partition_rows <= 1048576: p.error('partition rows must be 1..1048576') + if a.layout == 'parted' and (not a.reference or not a.native_verifier): + p.error('parted requires --reference (verified splayed) and --native-verifier') + root = a.work_dir.resolve() + if a.resume: + if not root.is_dir(): p.error('--resume requires an existing work directory') + else: root.mkdir(exist_ok=False) + binary = str(a.rayforce.resolve()); create = (a.clickbench/'rayforce/create.rfl').resolve() + # Read the actual benchmark schema, not a separately maintained type list. + schema = create.read_text(); m = re.search(r'\(set hits-types \[([^]]+)\]',schema,re.S) + if not m: raise RuntimeError('cannot find ClickBench type vector') + types = m.group(1).split() + names = re.search(r'\(set hits-names \[([^]]+)\]',schema,re.S).group(1).split() + parquet_types = ['UNIX_SECONDS' if t == 'TIMESTAMP' else 'UNIX_DATE' if t == 'DATE' else t for t in types] + quote = lambda x: json.dumps(str(x)) + if a.prepare_csv and not a.resume: + if a.csv.exists(): raise FileExistsError(a.csv) + names = re.search(r'\(set hits-names \[([^]]+)\]',schema,re.S).group(1).split() + ident = lambda x: '"'+x.replace('"','""')+'"' + sqlstr = lambda x: "'"+str(x).replace("'","''")+"'" + replacements = [] + for name, typ in zip(names,types): + col = ident(name) + if typ == 'TIMESTAMP': replacements.append(f"strftime(to_timestamp({col}), '%Y-%m-%d %H:%M:%S') AS {col}") + if typ == 'DATE': replacements.append(f"strftime(DATE '1970-01-01' + {col}, '%Y-%m-%d') AS {col}") + sql = ("SET TimeZone='UTC'; SET threads=8; COPY (SELECT * REPLACE ("+', '.join(replacements)+ + f") FROM read_parquet({sqlstr(a.parquet.resolve())})) TO {sqlstr(a.csv.resolve())} (HEADER false, DELIMITER ',');") + (root/'prepare.sql').write_text(sql+'\n') + subprocess.run([a.oracle,'-c',sql],check=True) + reference = a.reference.resolve() if a.reference else None + identity = {'parquet':file_identity(a.parquet),'csv':file_identity(a.csv), + 'schema_sha256':digest(create),'binary_sha256':digest(binary), + 'harness_sha256':digest(__file__),'checkpoint_sha256':digest(Path(__file__).with_name('parquet_checkpoint.py')), + 'layout':a.layout,'partition_rows':a.partition_rows,'cores':a.cores, + 'repeats':a.repeats,'kinds':a.kinds,'reference':str(reference) if reference else None, + 'verifier_sha256':digest(a.native_verifier) if a.native_verifier else None} + if reference: + identity['reference_files'] = [file_identity(reference/name) for name in ['.d',*names] if (reference/name).exists()] + if (reference/'.sym').exists(): identity['reference_files'].append(file_identity(reference/'.sym')) + previous = open_run(root,a.resume,identity) + results = previous['results'] if previous else [] + expected_rows = results[0]['rows'] if results else None + if previous and not reference: reference = Path(previous['reference']) + reference_identity = lambda: [file_identity(reference/name) for name in ['.d','.sym',*names] if (reference/name).exists()] + if previous and previous.get('reference_identity') != reference_identity(): + raise RuntimeError('resume reference files changed') + completed = {(x['kind'],x['cores'],x['repeat']) for x in results if x['verified']} + if len(completed) != len(results): raise RuntimeError('invalid or duplicate checkpoint cases') + planned = {(k,c,r) for k in a.kinds for c in a.cores for r in range(a.repeats)} + if not completed <= planned: raise RuntimeError('unexpected checkpoint case') + report = previous + if a.kinds != ['csv','parquet'] and reference is None: + p.error('--reference is required when measuring only one input format') + for cores in a.cores: + for repeat in range(a.repeats): + for kind in (a.kinds if repeat % 2 == 0 else list(reversed(a.kinds))): + if (kind,cores,repeat) in completed: continue + dest = root/f'{kind}-{cores}-{repeat}'; script = root/'load.rfl'; timing = root/'process.time' + archive_partial(root,[dest,Path(str(dest)+'.parquet-partial'),Path(str(dest)+'.csv-partial'), + root/f'{kind}-{cores}-{repeat}.log',root/f'{kind}-{cores}-{repeat}.verify.log']) + if a.layout == 'parted': + if kind == 'csv': + expr = f"(.csv.parted hits-names hits-types {quote(a.csv.resolve())} {a.partition_rows} {quote(dest)} 'hits)" + else: + expr = f"(.parquet.parted {{types: [{' '.join(parquet_types)}] rows: {a.partition_rows}}} {quote(a.parquet.resolve())} {quote(dest)} 'hits)" + expr += f"\n(set hits (.db.parted.get {quote(dest)} 'hits))" + elif kind == 'csv': + expr = f'(set hits (.csv.splayed hits-names hits-types {quote(a.csv.resolve())} {quote(dest)}))' + else: + expr = f'(.parquet.splayed [{" ".join(parquet_types)}] {quote(a.parquet.resolve())} {quote(dest)})\n(set hits (.db.splayed.get {quote(dest)}))' + script.write_text(f'(load {quote(create)})\n{expr}\n(println (count hits))\n(exit 0)\n') + print(f'loading {kind} cores={cores} repeat={repeat}',flush=True) + start = time.perf_counter() + run = subprocess.run(['/usr/bin/time','-f','%e %M %U %S %F %R %I %O','-o',str(timing),binary,'-c',str(cores),str(script)],capture_output=True,text=True) + (root/f'{kind}-{cores}-{repeat}.log').write_text(run.stdout+run.stderr) + if run.returncode: raise RuntimeError(f'load failed: {run.stderr[-2000:]}') + rows = int(run.stdout.strip()); sync_tree(dest) + elapsed = time.perf_counter()-start + process, rss, user, system, major, minor, reads, writes = timing.read_text().split() + if expected_rows is None: expected_rows = rows + if rows != expected_rows: raise RuntimeError('row count mismatch') + print(f'loaded {kind}: {rows} rows in {elapsed:.3f}s; verifying',flush=True) + size = sum(f.stat().st_size for f in dest.rglob('*') if f.is_file()) + if reference is None: + reference = dest + else: + verify = root/'verify.rfl' + verify.write_text(f'''(set left (.db.splayed.get {quote(reference)})) +(set right (.db.splayed.get {quote(dest)})) +(if (not (all (== (cols left) (cols right)))) (raise "column names mismatch")) +(map (fn [c] (do + (set x (at left c)) (set y (at right c)) + (if (!= (type x) (type y)) (raise "column type mismatch")) + (if (not (all (== x y))) (do (println c) (raise "column mismatch"))) +)) (cols left)) +(println "VERIFIED") +(exit 0) +''') + command = ([str(a.native_verifier.resolve()),*(['--parted','hits'] if a.layout == 'parted' else []),str(reference),str(dest),*names] if a.native_verifier else + [binary,'-c',str(cores),str(verify)]) + verification_log = root/f'{kind}-{cores}-{repeat}.verify.log' + with verification_log.open('w') as output: + check = subprocess.run(command,stdout=output,stderr=subprocess.STDOUT,text=True) + checked = verification_log.read_text() + if check.returncode or 'VERIFIED' not in checked: raise RuntimeError(f'output verification failed: {checked[-2000:]}') + shutil.rmtree(dest) + result = {'kind':kind,'layout':a.layout,'cores':cores,'repeat':repeat,'rows':rows,'columns':len(types), + 'durable_load_seconds':elapsed,'process_seconds':float(process),'peak_rss_kib':int(rss),'native_bytes':size,'verified':True, + 'process_user_seconds':float(user),'process_system_seconds':float(system), + 'major_faults':int(major),'minor_faults':int(minor), + 'input_blocks':int(reads),'output_blocks':int(writes)} + results.append(result); print(json.dumps(result),flush=True) + report = {'parquet':str(a.parquet.resolve()),'csv':str(a.csv.resolve()),'schema':str(create),'cpu':platform.processor(),'logical_cpus':os.cpu_count(), + 'layout':a.layout,'binary_sha256':hashlib.sha256(Path(binary).read_bytes()).hexdigest(), + 'reference':str(reference),'harness_sha256':identity['harness_sha256'], + 'reference_identity':reference_identity(), + 'partitioning':f'source order, at most {a.partition_rows} rows; Parquet also breaks at row-group boundaries' if a.layout == 'parted' else None, + 'input_bytes':{'csv':a.csv.stat().st_size,'parquet':a.parquet.stat().st_size}, + 'page_cache':'OS-managed; no cache eviction','timing':'process + native indexes + reopen + output fsync', + 'results':results,'medians':[]} + for c in a.cores: + entries = {k:[v['durable_load_seconds'] for v in results if v['cores']==c and v['kind']==k] for k in ('csv','parquet')} + if all(entries.values()): + med = {k:statistics.median(v) for k,v in entries.items()} + report['medians'].append({'cores':c,**med,'csv_over_parquet':med['csv']/med['parquet']}) + save(root/'results.json',report) + if (root/'stop').exists(): + print('Stopped after verified case: work directory contains stop file',flush=True) + return + print(json.dumps(report['medians'],indent=2)) + +if __name__ == '__main__': main() diff --git a/scripts/parquet-query-verify.py b/scripts/parquet-query-verify.py new file mode 100644 index 000000000..a3bffda41 --- /dev/null +++ b/scripts/parquet-query-verify.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Check lazy Parquet queries on a ClickBench sample against external reference SQL engine. + +Python standard library only. Queries cover representative shapes from +../ClickBench/rayforce/queries.sql, with deterministic group ordering and raw +integer dates (the Parquet source has no DATE annotation). This is a focused +correctness check, not the complete 43-query ClickBench score. +""" +import argparse +import csv +import io +import json +import math +import subprocess +import tempfile +from pathlib import Path + +# name, Rayfall query body, SQL projection/body after SELECT +QUERIES = [ + ('count', 'n: (count WatchID)', 'count(*) AS n FROM hits'), + ('aggregates', 's: (sum AdvEngineID) n: (count AdvEngineID) a: (avg ResolutionWidth)', + 'sum(AdvEngineID) AS s, count(*) AS n, avg(ResolutionWidth) AS a FROM hits'), + ('wide_avg', 'a: (avg UserID)', 'avg(UserID) AS a FROM hits'), + ('extrema', 'lo: (min EventDate) hi: (max EventDate)', 'min(EventDate) AS lo, max(EventDate) AS hi FROM hits'), + ('group', 'by: AdvEngineID n: (count AdvEngineID) where: (!= AdvEngineID 0) asc: AdvEngineID', + 'AdvEngineID, count(*) AS n FROM hits WHERE AdvEngineID <> 0 GROUP BY AdvEngineID ORDER BY AdvEngineID'), + ('distinct_group', 'by: RegionID n: (count (distinct UserID)) asc: RegionID', + 'RegionID, count(DISTINCT UserID) AS n FROM hits GROUP BY RegionID ORDER BY RegionID'), + ('range', 'n: (count WatchID) s: (sum JavaEnable) where: (and (>= CounterID 17) (<= CounterID 20))', + 'count(*) AS n, coalesce(sum(JavaEnable),0) AS s FROM hits WHERE CounterID BETWEEN 17 AND 20'), + ('equality', 'n: (count WatchID) where: (== CounterID 38)', 'count(*) AS n FROM hits WHERE CounterID=38'), + ('residual', 'n: (count WatchID) where: (and (== CounterID 38) (== IsRefresh 0))', + 'count(*) AS n FROM hits WHERE CounterID=38 AND IsRefresh=0'), + ('empty_residual', 'n: (count WatchID) where: (and (== CounterID 62) (== IsRefresh 0))', + 'count(*) AS n FROM hits WHERE CounterID=62 AND IsRefresh=0'), + ('like', 'n: (count URL) where: (like URL "*google*")', "count(*) AS n FROM hits WHERE URL LIKE '%google%'"), + ('topk', 'UserID: UserID desc: UserID take: 10', 'UserID FROM hits ORDER BY UserID DESC LIMIT 10'), +] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('parquet', type=Path) + ap.add_argument('--rayforce', type=Path, default=Path('./rayforce')) + ap.add_argument('--oracle', required=True, help='reference SQL CLI executable') + ap.add_argument('--cores', type=int, default=4) + args = ap.parse_args() + path = args.parquet.resolve() + def sql(value): return "'" + str(value).replace("'", "''") + "'" + with tempfile.TemporaryDirectory(prefix='rayforce-parquet-query-') as tmp: + tmp = Path(tmp) + script = tmp/'queries.rfl' + lines = [f'(set hits (.parquet.scan {json.dumps(str(path))}))'] + for name, body, _ in QUERIES: + lines.append(f'(.csv.write (select {{from: hits {body}}}) {json.dumps(str(tmp/(name+".csv")))})') + lines.append('(exit 0)') + script.write_text('\n'.join(lines)+'\n') + subprocess.run([str(args.rayforce.resolve()),str(script),'-c',str(args.cores)], check=True) + report = [] + for name, _, body in QUERIES: + command = f'CREATE VIEW hits AS SELECT * FROM read_parquet({sql(path)}); SELECT {body};' + oracle = subprocess.run([args.oracle,'-csv','-c',command],check=True,capture_output=True,text=True).stdout + right = list(csv.reader(io.StringIO(oracle))) + with (tmp/(name+'.csv')).open(newline='') as f: left = list(csv.reader(f)) + if not left or not right or set(left[0]) != set(right[0]) or len(left) != len(right): + raise RuntimeError(f'{name}: schema/row count mismatch: {left[:2]} vs {right[:2]}') + order = [right[0].index(k) for k in left[0]] + for row, (actual, expected) in enumerate(zip(left[1:],right[1:])): + for col, idx in enumerate(order): + a, b = actual[col], expected[idx] + if a == b: continue + # Only averages use tolerance; integer results remain exact. + if left[0][col] == 'a' and math.isclose(float(a),float(b),rel_tol=1e-12,abs_tol=1e-12): continue + raise RuntimeError(f'{name}: row {row}, {left[0][col]}: {a!r} != {b!r}') + report.append({'query':name,'rows':len(left)-1,'matched':True}) + print(json.dumps({'cores':args.cores,'queries':report},indent=2)) + +if __name__ == '__main__': + main() diff --git a/scripts/parquet-verify.py b/scripts/parquet-verify.py new file mode 100644 index 000000000..d4147fc6a --- /dev/null +++ b/scripts/parquet-verify.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Compare every ClickBench Parquet cell against an external reference SQL executable. + +No Python packages are required. This is development tooling, not a Rayforce +build/runtime dependency. Intended for a bounded ClickBench sample (integer +and text columns); CSV text comparison is not a general floating-point oracle. +""" +import argparse +import csv +import itertools +import json +import subprocess +import tempfile +import time +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('parquet',type=Path) + parser.add_argument('--rayforce',type=Path,default=Path('./rayforce')) + parser.add_argument('--oracle',required=True,help='reference SQL CLI executable') + a = parser.parse_args() + source = a.parquet.resolve(); rayforce = a.rayforce.resolve() + def sql(s): return "'" + str(s).replace("'","''") + "'" + with tempfile.TemporaryDirectory(prefix='rayforce-parquet-verify-') as tmp: + tmp = Path(tmp); rf = tmp/'rayforce.csv'; oracle = tmp/'oracle.csv'; native = tmp/'native' + script = tmp/'verify.rfl' + script.write_text(f'''(set source {json.dumps(str(source))}) +(set hits (.parquet.read source)) +(.csv.write hits {json.dumps(str(rf))}) +(println (.parquet.parted source {json.dumps(str(native))} 'hits)) +(set p 0) +(.parquet.each source (fn [batch] (do + (set saved (.db.splayed.get (format {json.dumps(str(native)+'/%/hits')} p))) + (if (not (all (map (fn [c] (all (== (as 'STR (at batch c)) (as 'STR (at saved c))))) (cols batch)))) (raise "native mismatch")) + (set p (+ p 1)) +))) +(exit 0) +''') + start = time.perf_counter() + subprocess.run([str(rayforce),str(script)],check=True) + rayforce_seconds = time.perf_counter()-start + subprocess.run([a.oracle,'-c',f"COPY (SELECT * FROM read_parquet({sql(source)})) TO {sql(oracle)} (HEADER, DELIMITER ',');"],check=True) + csv.field_size_limit(64*1024*1024) + count = 0 + with rf.open(newline='') as fa, oracle.open(newline='') as fb: + left, right = csv.reader(fa), csv.reader(fb) + columns = next(left); expected = next(right) + if columns != expected: raise RuntimeError('schema mismatch') + for row,(x,y) in enumerate(itertools.zip_longest(left,right)): + if x != y: + if x is None or y is None: raise RuntimeError(f'row count mismatch at row {row}') + col = next((c for c,(u,v) in enumerate(zip(x,y)) if u != v),0) + raise RuntimeError(f'cell mismatch: row={row}, column={columns[col]!r}, rayforce={x[col]!r}, oracle={y[col]!r}') + count += 1 + print(json.dumps({'rows':count,'columns':len(columns),'matching_cells':count*len(columns), + 'native_partitions_match':True,'read_export_convert_verify_seconds':rayforce_seconds},indent=2)) + +if __name__ == '__main__': main() diff --git a/scripts/parquet_checkpoint.py b/scripts/parquet_checkpoint.py new file mode 100644 index 000000000..a417d248a --- /dev/null +++ b/scripts/parquet_checkpoint.py @@ -0,0 +1,59 @@ +"""Crash-safe checkpoints for development benchmarks (standard library only).""" +import hashlib +import json +import os +from pathlib import Path +import time + + +def file_identity(path): + path = Path(path).resolve() + st = path.stat() + return {'path': str(path), 'bytes': st.st_size, 'mtime_ns': st.st_mtime_ns, + 'ctime_ns': st.st_ctime_ns, + 'device': st.st_dev, 'inode': st.st_ino} + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as f: + for chunk in iter(lambda: f.read(8*1024*1024), b''): h.update(chunk) + return h.hexdigest() + + +def save(path, value): + path = Path(path) + temp = path.with_name(path.name+'.tmp') + with temp.open('w') as f: + json.dump(value, f, indent=2); f.write('\n'); f.flush(); os.fsync(f.fileno()) + temp.replace(path) + fd = os.open(path.parent, os.O_RDONLY) + try: os.fsync(fd) + finally: os.close(fd) + + +def open_run(root, resume, identity): + """Require unchanged inputs/options/build before reusing completed cases.""" + manifest = root/'run.json' + if resume: + if not manifest.exists(): + raise RuntimeError('no resumable run.json; use a new work directory for this older run') + previous = json.loads(manifest.read_text()) + if previous != identity: + changed = sorted(k for k in previous.keys() | identity.keys() if previous.get(k) != identity.get(k)) + raise RuntimeError('resume identity changed: '+', '.join(changed)) + else: + save(manifest, identity) + result = root/'results.json' + return json.loads(result.read_text()) if resume and result.exists() else None + + +def archive_partial(root, paths): + """Retain interrupted outputs; never reuse their incomplete timings.""" + existing = [Path(p) for p in paths if Path(p).exists() or Path(p).is_symlink()] + if not existing: return + archive = root/('interrupted-'+str(time.time_ns())) + archive.mkdir() + for path in existing: + if path.parent != root: raise RuntimeError('partial artifact outside the run directory') + path.rename(archive/path.name) diff --git a/src/core/crc32.c b/src/core/crc32.c new file mode 100644 index 000000000..0cbe27a91 --- /dev/null +++ b/src/core/crc32.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. + */ + +#include "core/crc32.h" + +/* CRC-32 (IEEE 802.3, reflected, poly 0xEDB88320), as used by the AOF + * frames and Parquet page checksums. A constant table instead of lazy + * init: callers may run concurrently on first use, and a racy one-time + * init could let a thread CRC against a half-written table. */ + +static const uint32_t CRC32_TABLE[256] = { + 0x00000000u, 0x77073096u, 0xEE0E612Cu, 0x990951BAu, 0x076DC419u, 0x706AF48Fu, 0xE963A535u, 0x9E6495A3u, + 0x0EDB8832u, 0x79DCB8A4u, 0xE0D5E91Eu, 0x97D2D988u, 0x09B64C2Bu, 0x7EB17CBDu, 0xE7B82D07u, 0x90BF1D91u, + 0x1DB71064u, 0x6AB020F2u, 0xF3B97148u, 0x84BE41DEu, 0x1ADAD47Du, 0x6DDDE4EBu, 0xF4D4B551u, 0x83D385C7u, + 0x136C9856u, 0x646BA8C0u, 0xFD62F97Au, 0x8A65C9ECu, 0x14015C4Fu, 0x63066CD9u, 0xFA0F3D63u, 0x8D080DF5u, + 0x3B6E20C8u, 0x4C69105Eu, 0xD56041E4u, 0xA2677172u, 0x3C03E4D1u, 0x4B04D447u, 0xD20D85FDu, 0xA50AB56Bu, + 0x35B5A8FAu, 0x42B2986Cu, 0xDBBBC9D6u, 0xACBCF940u, 0x32D86CE3u, 0x45DF5C75u, 0xDCD60DCFu, 0xABD13D59u, + 0x26D930ACu, 0x51DE003Au, 0xC8D75180u, 0xBFD06116u, 0x21B4F4B5u, 0x56B3C423u, 0xCFBA9599u, 0xB8BDA50Fu, + 0x2802B89Eu, 0x5F058808u, 0xC60CD9B2u, 0xB10BE924u, 0x2F6F7C87u, 0x58684C11u, 0xC1611DABu, 0xB6662D3Du, + 0x76DC4190u, 0x01DB7106u, 0x98D220BCu, 0xEFD5102Au, 0x71B18589u, 0x06B6B51Fu, 0x9FBFE4A5u, 0xE8B8D433u, + 0x7807C9A2u, 0x0F00F934u, 0x9609A88Eu, 0xE10E9818u, 0x7F6A0DBBu, 0x086D3D2Du, 0x91646C97u, 0xE6635C01u, + 0x6B6B51F4u, 0x1C6C6162u, 0x856530D8u, 0xF262004Eu, 0x6C0695EDu, 0x1B01A57Bu, 0x8208F4C1u, 0xF50FC457u, + 0x65B0D9C6u, 0x12B7E950u, 0x8BBEB8EAu, 0xFCB9887Cu, 0x62DD1DDFu, 0x15DA2D49u, 0x8CD37CF3u, 0xFBD44C65u, + 0x4DB26158u, 0x3AB551CEu, 0xA3BC0074u, 0xD4BB30E2u, 0x4ADFA541u, 0x3DD895D7u, 0xA4D1C46Du, 0xD3D6F4FBu, + 0x4369E96Au, 0x346ED9FCu, 0xAD678846u, 0xDA60B8D0u, 0x44042D73u, 0x33031DE5u, 0xAA0A4C5Fu, 0xDD0D7CC9u, + 0x5005713Cu, 0x270241AAu, 0xBE0B1010u, 0xC90C2086u, 0x5768B525u, 0x206F85B3u, 0xB966D409u, 0xCE61E49Fu, + 0x5EDEF90Eu, 0x29D9C998u, 0xB0D09822u, 0xC7D7A8B4u, 0x59B33D17u, 0x2EB40D81u, 0xB7BD5C3Bu, 0xC0BA6CADu, + 0xEDB88320u, 0x9ABFB3B6u, 0x03B6E20Cu, 0x74B1D29Au, 0xEAD54739u, 0x9DD277AFu, 0x04DB2615u, 0x73DC1683u, + 0xE3630B12u, 0x94643B84u, 0x0D6D6A3Eu, 0x7A6A5AA8u, 0xE40ECF0Bu, 0x9309FF9Du, 0x0A00AE27u, 0x7D079EB1u, + 0xF00F9344u, 0x8708A3D2u, 0x1E01F268u, 0x6906C2FEu, 0xF762575Du, 0x806567CBu, 0x196C3671u, 0x6E6B06E7u, + 0xFED41B76u, 0x89D32BE0u, 0x10DA7A5Au, 0x67DD4ACCu, 0xF9B9DF6Fu, 0x8EBEEFF9u, 0x17B7BE43u, 0x60B08ED5u, + 0xD6D6A3E8u, 0xA1D1937Eu, 0x38D8C2C4u, 0x4FDFF252u, 0xD1BB67F1u, 0xA6BC5767u, 0x3FB506DDu, 0x48B2364Bu, + 0xD80D2BDAu, 0xAF0A1B4Cu, 0x36034AF6u, 0x41047A60u, 0xDF60EFC3u, 0xA867DF55u, 0x316E8EEFu, 0x4669BE79u, + 0xCB61B38Cu, 0xBC66831Au, 0x256FD2A0u, 0x5268E236u, 0xCC0C7795u, 0xBB0B4703u, 0x220216B9u, 0x5505262Fu, + 0xC5BA3BBEu, 0xB2BD0B28u, 0x2BB45A92u, 0x5CB36A04u, 0xC2D7FFA7u, 0xB5D0CF31u, 0x2CD99E8Bu, 0x5BDEAE1Du, + 0x9B64C2B0u, 0xEC63F226u, 0x756AA39Cu, 0x026D930Au, 0x9C0906A9u, 0xEB0E363Fu, 0x72076785u, 0x05005713u, + 0x95BF4A82u, 0xE2B87A14u, 0x7BB12BAEu, 0x0CB61B38u, 0x92D28E9Bu, 0xE5D5BE0Du, 0x7CDCEFB7u, 0x0BDBDF21u, + 0x86D3D2D4u, 0xF1D4E242u, 0x68DDB3F8u, 0x1FDA836Eu, 0x81BE16CDu, 0xF6B9265Bu, 0x6FB077E1u, 0x18B74777u, + 0x88085AE6u, 0xFF0F6A70u, 0x66063BCAu, 0x11010B5Cu, 0x8F659EFFu, 0xF862AE69u, 0x616BFFD3u, 0x166CCF45u, + 0xA00AE278u, 0xD70DD2EEu, 0x4E048354u, 0x3903B3C2u, 0xA7672661u, 0xD06016F7u, 0x4969474Du, 0x3E6E77DBu, + 0xAED16A4Au, 0xD9D65ADCu, 0x40DF0B66u, 0x37D83BF0u, 0xA9BCAE53u, 0xDEBB9EC5u, 0x47B2CF7Fu, 0x30B5FFE9u, + 0xBDBDF21Cu, 0xCABAC28Au, 0x53B39330u, 0x24B4A3A6u, 0xBAD03605u, 0xCDD70693u, 0x54DE5729u, 0x23D967BFu, + 0xB3667A2Eu, 0xC4614AB8u, 0x5D681B02u, 0x2A6F2B94u, 0xB40BBE37u, 0xC30C8EA1u, 0x5A05DF1Bu, 0x2D02EF8Du, +}; + +/* Slicing-by-8: seven more tables derived from the first, built once at + * load time (a constructor runs before any thread exists, so there is no + * first-use race). ~3x the byte loop: Parquet page checksums are on by + * default in several writers and cost most of a read without it. */ +static uint32_t CRC32_SLICE[8][256]; + +__attribute__((constructor)) static void crc32_slice_init(void) { + for (int i = 0; i < 256; i++) CRC32_SLICE[0][i] = CRC32_TABLE[i]; + for (int t = 1; t < 8; t++) + for (int i = 0; i < 256; i++) { + uint32_t c = CRC32_SLICE[t-1][i]; + CRC32_SLICE[t][i] = (c >> 8) ^ CRC32_TABLE[c & 0xFF]; + } +} + +uint32_t ray_crc32(uint32_t seed, const void* data, size_t n) { + const uint8_t* p = (const uint8_t*)data; + uint32_t c = seed ^ 0xFFFFFFFFu; + for (; n >= 8; p += 8, n -= 8) { + uint32_t lo = c ^ ((uint32_t)p[0] | (uint32_t)p[1] << 8 | + (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24); + uint32_t hi = (uint32_t)p[4] | (uint32_t)p[5] << 8 | + (uint32_t)p[6] << 16 | (uint32_t)p[7] << 24; + c = CRC32_SLICE[7][lo & 0xFF] ^ CRC32_SLICE[6][(lo >> 8) & 0xFF] ^ + CRC32_SLICE[5][(lo >> 16) & 0xFF] ^ CRC32_SLICE[4][lo >> 24] ^ + CRC32_SLICE[3][hi & 0xFF] ^ CRC32_SLICE[2][(hi >> 8) & 0xFF] ^ + CRC32_SLICE[1][(hi >> 16) & 0xFF] ^ CRC32_SLICE[0][hi >> 24]; + } + while (n--) c = CRC32_TABLE[(c ^ *p++) & 0xFF] ^ (c >> 8); + return c ^ 0xFFFFFFFFu; +} diff --git a/src/core/crc32.h b/src/core/crc32.h new file mode 100644 index 000000000..9c65e8a71 --- /dev/null +++ b/src/core/crc32.h @@ -0,0 +1,34 @@ +/* + * 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_CRC32_H +#define RAY_CRC32_H + +#include +#include + +/* CRC-32 (IEEE, reflected, poly 0xEDB88320) of n bytes, continuing from + * `seed` (0 for a fresh checksum; pass a previous result to extend it). */ +uint32_t ray_crc32(uint32_t seed, const void* data, size_t n); + +#endif /* RAY_CRC32_H */ diff --git a/src/core/ipc.c b/src/core/ipc.c index c25935101..279a8be54 100644 --- a/src/core/ipc.c +++ b/src/core/ipc.c @@ -27,6 +27,7 @@ #include "core/ipc.h" #include "core/mcast.h" +#include "core/timer.h" #include "mem/heap.h" #include "mem/sys.h" #include "ops/ops.h" @@ -457,14 +458,16 @@ static int hook_call_auth(ray_poll_t* poll, int64_t handle, * on write-readiness the way ray_sock_send already does, so the direct write * that follows starts on a frame boundary. Fast-path returns 0 when nothing * is queued (the common, non-subscriber case). Returns -1 on socket error. */ -static int conn_tx_drain_blocking(ray_poll_t* poll, ray_selector_t* sel) +static int conn_tx_drain_blocking(ray_poll_t* poll, ray_selector_t* sel, + int64_t deadline_ms) { if (!sel || !sel->tx.buf) return 0; while (sel->tx.buf) { ray_poll_buf_t* buf = sel->tx.buf; int64_t rem = buf->size - buf->offset; if (rem > 0 && - ray_sock_send(sel->fd, buf->data + buf->offset, (size_t)rem) < 0) + ray_sock_send_until(sel->fd, buf->data + buf->offset, (size_t)rem, + deadline_ms) < 0) return -1; sel->tx.buf = buf->next; buf->next = NULL; @@ -1154,7 +1157,7 @@ static ray_t* ipc_read_payload(ray_poll_t* poll, ray_selector_t* sel) * half-sent push. A drain error means the peer is gone — skip the * write and let the poll/pump layer deregister it. */ if (cur && cur->data == (void*)cd && - conn_tx_drain_blocking(poll, cur) == 0) + conn_tx_drain_blocking(poll, cur, -1) == 0) { ray_ipc_conn_data_t* rcd = (ray_ipc_conn_data_t*)cur->data; send_response((ray_sock_t)cur->fd, result, @@ -1409,13 +1412,15 @@ static size_t conn_threshold(ray_selector_t* sel) } static int64_t conn_write_msg(ray_sock_t fd, ray_t* msg, uint8_t msgtype, - uint8_t extra_flags, size_t threshold) + uint8_t extra_flags, size_t threshold, + int64_t deadline_ms) { ray_err_t err = RAY_OK; ray_poll_frame_t* frame = conn_frame_msg(msg, msgtype, extra_flags, threshold, &err); if (!frame) return -1; - int64_t rc = ray_sock_send(fd, frame->data, (size_t)frame->size); + int64_t rc = ray_sock_send_until(fd, frame->data, (size_t)frame->size, + deadline_ms); ray_poll_frame_release(frame); return rc < 0 ? -1 : 0; } @@ -1446,12 +1451,13 @@ int64_t ray_ipc_connect(const char* host, uint16_t port, int timeout_ms) { return ray_ipc_connect_opts(host, port, user, password, timeout_ms, - RAY_IPC_COMPRESS_AUTO); + RAY_IPC_COMPRESS_AUTO, RAY_IPC_KEEPALIVE_AUTO); } int64_t ray_ipc_connect_opts(const char* host, uint16_t port, const char* user, const char* password, - int timeout_ms, size_t compress_threshold) + int timeout_ms, size_t compress_threshold, + int keepalive_ms) { /* The connection lives in the active poll's selector table — its * selector id IS the handle. No poll, no handle namespace: refuse @@ -1531,6 +1537,14 @@ int64_t ray_ipc_connect_opts(const char* host, uint16_t port, setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &z, sizeof(z)); } #endif + /* The handshake timeouts are gone, so from here on only keepalive + * notices a peer that vanished without closing (#589). Best-effort: + * failing to arm it leaves the link no worse than before. */ + if (keepalive_ms == RAY_IPC_KEEPALIVE_AUTO) + ray_sock_set_keepalive(fd, RAY_IPC_KEEPALIVE_DEFAULT_MS, false); + else if (keepalive_ms > 0) + ray_sock_set_keepalive(fd, keepalive_ms, true); + /* Handshake + auth done (blocking socket). Hand the fd over to the * poll: nonblocking, parked on a header read, same read pump as an * inbound connection — which is exactly what makes pushed frames @@ -1585,9 +1599,31 @@ void ray_ipc_close(int64_t handle) * deposited — dispatching (not swallowing) any frames that arrive in * between: a pushed ASYNC gets evaluated, a nested SYNC request from * the peer gets evaluated and answered. Full-duplex, either side of - * the wire. */ -static ray_t* sync_send(int64_t handle, ray_t* msg, uint8_t extra_flags) + * the wire. + * + * timeout_ms > 0 bounds the whole round trip, write included (#589). + * On expiry the connection is closed — on.close fires — because a RESP + * carries no request id: a reply that arrived later would be taken as + * the answer to the NEXT send on the handle. A write cut off by the + * deadline has left a partial frame on the stream, which is unusable for + * the same reason. Before closing, the peer is sent the same urgent-data + * cancel as Ctrl-C, so it stops evaluating a query nobody will read. */ +static ray_t* sync_expire(ray_poll_t* poll, int64_t id, int64_t timeout_ms) +{ + ray_selector_t* sel = ray_poll_get(poll, id); + if (sel) { + ray_sock_send_oob((ray_sock_t)sel->fd, '!'); + ray_poll_deregister(poll, id); + } + return ray_error("io", "ipc send timed out after %lld ms; connection closed", + (long long)timeout_ms); +} + +static ray_t* sync_send(int64_t handle, ray_t* msg, uint8_t extra_flags, + int64_t timeout_ms) { + int64_t deadline = timeout_ms > 0 ? ray_time_now_ms() + timeout_ms : -1; + bool owned = false; if (ray_is_lazy(msg)) { ray_retain(msg); @@ -1613,10 +1649,14 @@ static ray_t* sync_send(int64_t handle, ray_t* msg, uint8_t extra_flags) /* Drain any half-sent multicast frame queued to this fd before writing the * sync request, so its bytes can't interleave into the pending frame. */ - if (conn_tx_drain_blocking(poll, sel) < 0 || + errno = 0; + if (conn_tx_drain_blocking(poll, sel, deadline) < 0 || conn_write_msg((ray_sock_t)sel->fd, msg, RAY_IPC_MSG_SYNC, - extra_flags, conn_threshold(sel)) < 0) { + extra_flags, conn_threshold(sel), deadline) < 0) { + int e = errno; if (owned) ray_release(msg); + if (deadline >= 0 && e == ETIMEDOUT) + return sync_expire(poll, sel->id, timeout_ms); return ray_error("io", "ipc send failed"); } if (owned) ray_release(msg); @@ -1651,7 +1691,15 @@ static ray_t* sync_send(int64_t handle, ray_t* msg, uint8_t extra_flags) * defensive: treat as closed. */ return ray_error("io", "connection closed"); } - int w = ray_sock_wait_readable_intr((ray_sock_t)sel->fd, -1); + /* The deadline is checked after the pump, so a reply that is + * already here when it expires is still delivered. */ + int wait_ms = -1; + if (deadline >= 0) { + int64_t left = deadline - ray_time_now_ms(); + if (left <= 0) return sync_expire(poll, id, timeout_ms); + wait_ms = left > INT_MAX ? INT_MAX : (int)left; + } + int w = ray_sock_wait_readable_intr((ray_sock_t)sel->fd, wait_ms); if (w == -2) { /* Interrupted by a signal. If it was a cancel request (Ctrl-C), * forward it to the server as TCP urgent data — the server is busy @@ -1674,7 +1722,12 @@ static ray_t* sync_send(int64_t handle, ray_t* msg, uint8_t extra_flags) ray_t* ray_ipc_send(int64_t handle, ray_t* msg) { - return sync_send(handle, msg, 0); + return sync_send(handle, msg, 0, 0); +} + +ray_t* ray_ipc_send_timeout(int64_t handle, ray_t* msg, int64_t timeout_ms) +{ + return sync_send(handle, msg, 0, timeout_ms); } size_t ray_ipc_handle_threshold(int64_t handle) @@ -1700,10 +1753,10 @@ ray_err_t ray_ipc_send_async(int64_t handle, ray_t* msg) } ray_poll_t* poll; ray_selector_t* sel = conn_resolve(&poll, handle); - ray_err_t rc = (!sel || conn_tx_drain_blocking(poll, sel) < 0 || + ray_err_t rc = (!sel || conn_tx_drain_blocking(poll, sel, -1) < 0 || conn_write_msg((ray_sock_t)sel->fd, msg, RAY_IPC_MSG_ASYNC, 0, - conn_threshold(sel)) < 0) + conn_threshold(sel), -1) < 0) ? RAY_ERR_IO : RAY_OK; if (owned) ray_release(msg); return rc; @@ -1898,7 +1951,7 @@ ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg) * instead of bare result. Same wire path as ray_ipc_send otherwise. */ ray_t* ray_ipc_send_verbose(int64_t handle, ray_t* msg) { - return sync_send(handle, msg, RAY_IPC_FLAG_VERBOSE); + return sync_send(handle, msg, RAY_IPC_FLAG_VERBOSE, 0); } /* ===== .ipc.open options ===== */ @@ -1924,10 +1977,12 @@ static int opts_i64(ray_t* d, const char* name, int64_t* out, ray_t** err) } ray_t* ray_ipc_parse_open_opts(ray_t* arg, int* timeout_ms, - size_t* compress_threshold) + size_t* compress_threshold, + int* keepalive_ms) { *timeout_ms = 0; *compress_threshold = RAY_IPC_COMPRESS_AUTO; + *keepalive_ms = RAY_IPC_KEEPALIVE_AUTO; if (!arg) return NULL; /* Backwards-compatible form: a bare integer is the connect timeout. */ @@ -1973,10 +2028,11 @@ ray_t* ray_ipc_parse_open_opts(ray_t* arg, int* timeout_ms, return ray_error("type", ".ipc.open: option keys must be symbols, got %s", ray_type_name(keys->type)); } - bool known = (n == 7 && memcmp(p, "timeout", 7) == 0) - || (n == 8 && memcmp(p, "compress", 8) == 0); + bool known = (n == 7 && memcmp(p, "timeout", 7) == 0) + || (n == 8 && memcmp(p, "compress", 8) == 0) + || (n == 9 && memcmp(p, "keepalive", 9) == 0); if (!known) - return ray_error("domain", ".ipc.open: unknown option `%.*s` (expected `timeout` or `compress`)", + return ray_error("domain", ".ipc.open: unknown option `%.*s` (expected `timeout`, `compress` or `keepalive`)", (int)n, p ? p : ""); } } @@ -2001,5 +2057,16 @@ ray_t* ray_ipc_parse_open_opts(ray_t* arg, int* timeout_ms, else if (cv < 0) return ray_error("domain", ".ipc.open compress threshold must be >= 0 or 0N (never), got %lld", (long long)cv); else *compress_threshold = (size_t)cv; } + + int64_t kv = 0; + got = opts_i64(arg, "keepalive", &kv, &err); + if (got < 0) return err; + if (got == 1) { + /* 0N = off. n > 0 = dead-peer budget in ms. 0 is refused rather + * than guessed at: it could mean "off" or "immediately". */ + if (kv == NULL_I64) *keepalive_ms = RAY_IPC_KEEPALIVE_OFF; + else if (kv <= 0) return ray_error("domain", ".ipc.open keepalive must be > 0 or 0N (off), got %lld", (long long)kv); + else *keepalive_ms = (kv > INT_MAX) ? INT_MAX : (int)kv; + } return NULL; } diff --git a/src/core/ipc.h b/src/core/ipc.h index a961c40f3..8a8f60842 100644 --- a/src/core/ipc.h +++ b/src/core/ipc.h @@ -44,6 +44,25 @@ * concrete threshold when the connection is established. */ #define RAY_IPC_COMPRESS_AUTO ((size_t)-2) +/* ===== Dead-peer detection (#589) ===== + * + * Outbound connections get kernel keepalive by default, so a peer that + * vanishes without closing (suspended host, NAT/firewall that silently + * drops the flow) is torn down and `.ipc.on.close` fires, instead of the + * connection hanging forever. See ray_sock_set_keepalive for how the + * budget maps onto the socket options. + * + * RAY_IPC_KEEPALIVE_AUTO keepalive at RAY_IPC_KEEPALIVE_DEFAULT_MS, no + * unacknowledged-data bound + * RAY_IPC_KEEPALIVE_OFF no keepalive + * n > 0 keepalive at budget n ms, plus the + * unacknowledged-data bound (TCP_USER_TIMEOUT) — + * the caller asked for n, so a peer that stops + * reading for n ms counts as dead too. */ +#define RAY_IPC_KEEPALIVE_DEFAULT_MS 60000 +#define RAY_IPC_KEEPALIVE_AUTO 0 +#define RAY_IPC_KEEPALIVE_OFF (-1) + /* Compression policy for one link: loopback and UNIX-domain peers never * compress (no bandwidth to buy with the CPU), everything else keeps the * compiled-in default. An unknown peer keeps the default. */ @@ -123,26 +142,36 @@ int64_t ray_ipc_listen_at(ray_poll_t* poll, const char* host, uint16_t port); int64_t ray_ipc_connect(const char* host, uint16_t port, const char* user, const char* password, int timeout_ms); -/* As ray_ipc_connect, with an explicit compression threshold for the new - * link. RAY_IPC_COMPRESS_AUTO keeps the locality-derived default. */ +/* As ray_ipc_connect, with an explicit compression threshold and + * keepalive budget for the new link. RAY_IPC_COMPRESS_AUTO keeps the + * locality-derived default; keepalive_ms is RAY_IPC_KEEPALIVE_AUTO, + * RAY_IPC_KEEPALIVE_OFF, or a budget in ms (see above). */ int64_t ray_ipc_connect_opts(const char* host, uint16_t port, const char* user, const char* password, - int timeout_ms, size_t compress_threshold); + int timeout_ms, size_t compress_threshold, + int keepalive_ms); /* Parse .ipc.open's optional second argument: an integer timeout in - * milliseconds, or a dict with optional `timeout` and `compress`. - * `compress` is a threshold in bytes — 0N never compresses, 0 always - * does, n compresses payloads larger than n; absent leaves - * RAY_IPC_COMPRESS_AUTO. Returns NULL on success, or an error object + * milliseconds, or a dict with optional `timeout`, `compress` and + * `keepalive`. `compress` is a threshold in bytes — 0N never + * compresses, 0 always does, n compresses payloads larger than n; absent + * leaves RAY_IPC_COMPRESS_AUTO. `keepalive` is a dead-peer budget in + * ms — 0N turns it off, n > 0 sets it; absent leaves + * RAY_IPC_KEEPALIVE_AUTO. Returns NULL on success, or an error object * the caller returns as-is. */ ray_t* ray_ipc_parse_open_opts(ray_t* arg, int* timeout_ms, - size_t* compress_threshold); + size_t* compress_threshold, + int* keepalive_ms); /* The compression threshold in force on an open handle, or * RAY_IPC_COMPRESS_AUTO if the handle does not resolve. */ size_t ray_ipc_handle_threshold(int64_t handle); void ray_ipc_close(int64_t handle); ray_t* ray_ipc_send(int64_t handle, ray_t* msg); +/* As ray_ipc_send, bounded: timeout_ms > 0 caps the whole round trip. + * On expiry the connection is closed (on.close fires) and an `io` error + * is returned; timeout_ms <= 0 waits indefinitely, like ray_ipc_send. */ +ray_t* ray_ipc_send_timeout(int64_t handle, ray_t* msg, int64_t timeout_ms); ray_err_t ray_ipc_send_async(int64_t handle, ray_t* msg); ray_err_t ray_ipc_try_send_async(int64_t handle, ray_t* msg); diff --git a/src/core/platform.c b/src/core/platform.c index 5251a6712..e6cd89d42 100644 --- a/src/core/platform.c +++ b/src/core/platform.c @@ -369,6 +369,97 @@ static uint64_t cache_sysfs_llc_bytes(void) { } #endif +/* -------------------------------------------------------------------------- + * Container memory limit (Linux cgroups) + * + * A process limited below host RAM (`docker run --memory`, `systemd-run -p + * MemoryMax=`) is OOM-killed by its cgroup long before sysconf's physical + * RAM figure is reached, so the heap's spill threshold must see that limit + * (issue #688). cgroup v2 publishes it as memory.max ("max" = unlimited) + * under the cgroup named by /proc/self/cgroup; v1 as memory.limit_in_bytes + * under the memory controller mount, where "unlimited" is LLONG_MAX rounded + * down to a page. A limit may sit on an ancestor (a slice above the scope), + * so every directory up to the mount root is read and the smallest wins. + * Inside a cgroup namespace the reported path is "/" and the root files are + * the container's own, which the same walk covers. + * -------------------------------------------------------------------------- */ +#if defined(RAY_OS_LINUX) +/* One cgroup limit file → bytes, or 0 when missing, unreadable or unlimited. */ +static int64_t cgroup_read_limit(const char* path) { + FILE* f = fopen(path, "r"); + if (!f) return 0; + char buf[64]; + buf[0] = 0; + if (!fgets(buf, sizeof(buf), f)) buf[0] = 0; + fclose(f); + if (strncmp(buf, "max", 3) == 0) return 0; + char* end = NULL; + unsigned long long v = strtoull(buf, &end, 10); + if (end == buf || v == 0 || v >= (1ULL << 62)) return 0; /* v1 "unlimited" ~ 2^63 */ + return (int64_t)v; +} + +/* Smallest limit found in `root`/`cgpath`/`file` and every ancestor. */ +static int64_t cgroup_walk_limit(const char* root, const char* cgpath, const char* file) { + char dir[512]; + if (snprintf(dir, sizeof(dir), "%s%s", root, cgpath) >= (int)sizeof(dir)) return 0; + size_t rootlen = strlen(root); + int64_t limit = 0; + for (;;) { + char path[640]; + snprintf(path, sizeof(path), "%s/%s", dir, file); + int64_t v = cgroup_read_limit(path); + if (v > 0 && (limit == 0 || v < limit)) limit = v; + if (strlen(dir) <= rootlen) break; /* mount root checked */ + char* slash = strrchr(dir, '/'); + if (!slash || (size_t)(slash - dir) < rootlen) break; + *slash = 0; /* parent directory */ + } + return limit; +} + +/* True when the comma-separated controller list names "memory". */ +static bool cgroup_has_memory(const char* ctrls) { + while (*ctrls) { + size_t n = strcspn(ctrls, ","); + if (n == 6 && strncmp(ctrls, "memory", 6) == 0) return true; + ctrls += n; + if (*ctrls == ',') ctrls++; + } + return false; +} + +int64_t ray_os_cgroup_mem_limit(void) { + FILE* f = fopen("/proc/self/cgroup", "r"); + if (!f) return 0; + int64_t limit = 0; + char line[512]; + while (fgets(line, sizeof(line), f)) { + /* "::" — v2 is "0::/path". */ + 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; + if (*ctrls == 0) + v = cgroup_walk_limit("/sys/fs/cgroup", cgpath, "memory.max"); + else if (cgroup_has_memory(ctrls)) + v = cgroup_walk_limit("/sys/fs/cgroup/memory", cgpath, "memory.limit_in_bytes"); + else + continue; + if (v > 0 && (limit == 0 || v < limit)) limit = v; + } + fclose(f); + return limit; +} +#else +int64_t ray_os_cgroup_mem_limit(void) { return 0; } +#endif + static uint64_t cache_llc_probe(void) { static uint64_t cached = UINT64_MAX; if (cached != UINT64_MAX) return cached; @@ -639,6 +730,8 @@ uint32_t ray_physical_core_count(void) { return ray_thread_count(); } +int64_t ray_os_cgroup_mem_limit(void) { return 0; } + /* Sum of every level-3 cache instance reported by the processor topology * (each SYSTEM_LOGICAL_PROCESSOR_INFORMATION cache record is one instance). * 0 when the query fails. */ @@ -800,6 +893,7 @@ ray_err_t ray_thread_join(ray_thread_t t) { } uint32_t ray_thread_count(void) { return 1; } +int64_t ray_os_cgroup_mem_limit(void) { return 0; } static uint64_t cache_llc_probe(void) { return 0; } /* Semaphore — counter-only. Single-threaded so wait never blocks (the diff --git a/src/core/platform.h b/src/core/platform.h index e2d137856..e89292829 100644 --- a/src/core/platform.h +++ b/src/core/platform.h @@ -180,6 +180,11 @@ uint32_t ray_physical_core_count(void); * 0 when the platform cannot report it. Bounds replicated per-task state * whose random-access working set must stay cache-resident to scale. */ uint64_t ray_cache_llc_bytes(void); +/* Memory limit imposed on this process by its container / cgroup (bytes): + * the smallest cgroup v2 memory.max or v1 memory.limit_in_bytes found on + * 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); #ifdef DEBUG /* Pin ray_cache_llc_bytes to `bytes` (0 = probe again). */ void ray_cache_llc_set_for_test(uint64_t bytes); diff --git a/src/core/pool.c b/src/core/pool.c index 904600fdb..4c3fd9403 100644 --- a/src/core/pool.c +++ b/src/core/pool.c @@ -29,6 +29,7 @@ #include "mem/sys.h" #include #include +#include #include /* Per-worker query-statistics slab (see core/qstats.h). Zero-initialised; @@ -72,6 +73,217 @@ static inline bool pool_claim(ray_pool_t* pool, uint64_t* out_idx) { } } +/* -------------------------------------------------------------------------- + * Range + steal claiming (pool->steal, RAY_POOL_STEAL=1 — the default) + * + * The dispatcher splits every window [base, base+n) into W contiguous ticket + * ranges, one per worker (main is worker 0), and stores each as a head:tail + * word in slots[w].range (see ray_pool_slot_t for the encoding and why the + * halves are absolute tickets). Owner and thieves agree through that one + * word only: + * + * owner CAS (h, t) -> (h+1, t) claims ticket h, keeps running in order + * thief CAS (h, t) -> (h, t-k) takes [t-k, t), k = ceil((t-h)/2) >= 1 + * + * Both compare the whole pair, so when owner and thief race on the last + * ticket exactly one CAS lands and the other sees an empty range. Half- + * at-least-one guarantees a range nobody runs — a worker that was not woken + * (only n-1 helpers are signalled), is still starting, or is simply slow — + * is drained entirely by thieves. + * + * The word is stored without a CAS in two places only, both when it is + * provably empty and uncontended: by the dispatcher at window open (pending + * == 0 means every range is head == tail, and a thief never CASes an empty + * word), and by a thief installing the chunk it has just cut into its own + * slot (nobody but the owner adds to an owner's word). Those two can race + * with each other: a worker still scanning for victims when the next window + * opens may cut a chunk before the dispatcher has reached ITS slot, and the + * dispatcher's share store would then overwrite the installed chunk — or + * the install would overwrite the share. win_state closes it: it is odd + * from before the first range store until after the last one; a thief that + * reads it odd after its cut runs the chunk privately (no install), and a + * thief that reads it even has, by that acquire, seen its own share land. + * A chunk pins its window (pending > 0), so the parity it reads can only be + * that of the window the chunk came from. + * + * Publish order: ring fill, pending, range words (release each), then the + * even win_state. A claim CAS acquires the word, so whoever runs a ticket + * — however late it woke — sees the ring slots and pending of that window. + * Nothing is ever reset, so the cross-dispatch reset race of pool_claim's + * predecessor cannot reappear here either. + * -------------------------------------------------------------------------- */ + +#define RANGE_PACK(h, t) (((uint64_t)(uint32_t)(t) << 32) | (uint32_t)(h)) +#define RANGE_HEAD(w) ((uint32_t)(w)) +#define RANGE_TAIL(w) ((uint32_t)((w) >> 32)) + +/* Run one claimed ticket (or skip it when cancelled) and retire it. */ +static inline void pool_exec(ray_pool_t* pool, uint32_t worker_id, uint32_t ticket) { + if (RAY_UNLIKELY(atomic_load_explicit(&pool->cancelled, memory_order_relaxed))) { + atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); + return; + } + ray_pool_task_t* t = &pool->tasks[ticket & (pool->task_cap - 1)]; + int64_t _qs_t0; uint32_t _qs_m = ray_qstats_task_begin(&_qs_t0); + t->fn(t->ctx, worker_id, t->start, t->end); + ray_qstats_task_end(_qs_m, worker_id, t->end - t->start, _qs_t0); + atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); +} + +/* Owner claim: the head of own range, in order. False when it is empty. */ +static inline bool pool_range_take(ray_pool_slot_t* s, uint32_t* out) { + uint64_t cur = atomic_load_explicit(&s->range, memory_order_acquire); + for (;;) { + uint32_t h = RANGE_HEAD(cur), t = RANGE_TAIL(cur); + if (h == t) return false; + if (atomic_compare_exchange_weak_explicit(&s->range, &cur, RANGE_PACK(h + 1, t), + memory_order_acq_rel, memory_order_acquire)) { + *out = h; + return true; + } + /* CAS failed: a thief cut the tail — `cur` is current, retry. */ + } +} + +/* Victim order hook: the k-th victim (k in [1, W)) of worker w. Plain + * round-robin from w+1 for now; a NUMA-aware order (same-node workers + * first, then the rest) plugs in here without touching the protocol. */ +static inline uint32_t pool_victim(const ray_pool_t* pool, uint32_t w, uint32_t k) { + uint32_t W = ray_pool_total_workers(pool); + uint32_t v = w + k; + return v >= W ? v - W : v; +} + +/* Cut the upper half (at least one ticket) off the first non-empty victim + * range in victim order. Two passes: a chunk that is between its cut and + * its install is invisible for a moment, and a worker that goes to sleep on + * that moment would leave the thief alone with it. */ +static bool pool_steal(ray_pool_t* pool, uint32_t w, uint32_t* c0, uint32_t* c1) { + uint32_t W = ray_pool_total_workers(pool); + for (int pass = 0; pass < 2; pass++) { + for (uint32_t k = 1; k < W; k++) { + ray_pool_slot_t* v = &pool->slots[pool_victim(pool, w, k)]; + uint64_t cur = atomic_load_explicit(&v->range, memory_order_relaxed); + for (;;) { + uint32_t h = RANGE_HEAD(cur), t = RANGE_TAIL(cur); + uint32_t rem = t - h; + if (rem == 0) break; + uint32_t take = (rem + 1) >> 1; + if (atomic_compare_exchange_weak_explicit(&v->range, &cur, + RANGE_PACK(h, t - take), memory_order_acq_rel, + memory_order_relaxed)) { + *c0 = t - take; + *c1 = t; + return true; + } + } + } + RAY_CPU_RELAX(); + } + return false; +} + +/* Drain own range, then steal until a full victim scan finds nothing. + * `prog` is the main thread's progress pump (false on workers). Tickets + * are attributed when they run: those inside the chunk last installed here + * (or run privately) count as stolen, the rest came with the share — so + * own + stolen over all slots is exactly the tickets executed. */ +static void pool_run_steal(ray_pool_t* pool, uint32_t w, bool prog) { + ray_pool_slot_t* s = &pool->slots[w]; + uint32_t ch0 = 0, ch1 = 0; /* installed chunk [ch0, ch1), empty at entry */ + for (;;) { + uint32_t tk; + while (pool_range_take(s, &tk)) { + if ((uint32_t)(tk - ch0) < (uint32_t)(ch1 - ch0)) s->stolen++; else s->own++; + pool_exec(pool, w, tk); + if (prog) ray_progress_pump(); + } + + uint32_t c0, c1; + if (!pool_steal(pool, w, &c0, &c1)) return; + s->steals++; + + /* Install the chunk as own range so others can halve it in turn — + * unless the window is still being published (odd win_state: the + * dispatcher may be about to store this worker's share here) or + * own range is not empty (that share already landed after the scan + * started). win_state is read FIRST: its acquire is what makes a + * share the dispatcher stored visible to the own-range load, so an + * even value and an empty word together mean no share is coming. + * Either way the chunk is run privately, in order, and the loop + * comes back to own range afterwards. */ + if (!(atomic_load_explicit(&pool->win_state, memory_order_acquire) & 1)) { + uint64_t mine = atomic_load_explicit(&s->range, memory_order_acquire); + if (RANGE_HEAD(mine) == RANGE_TAIL(mine)) { + ch0 = c0; ch1 = c1; + atomic_store_explicit(&s->range, RANGE_PACK(c0, c1), memory_order_release); + continue; + } + } + s->stolen += c1 - c0; + for (; c0 != c1; c0++) { + pool_exec(pool, w, c0); + if (prog) ray_progress_pump(); + } + } +} + +/* Split tickets [base, base+n) into W contiguous ranges — the first n % W + * workers take one ticket more — and publish them. Caller has filled the + * ring and stored `pending`; see the ordering note above. */ +static void pool_publish_ranges(ray_pool_t* pool, uint64_t base, uint32_t n) { + uint32_t W = ray_pool_total_workers(pool); + uint32_t q = n / W, r = n % W; + atomic_fetch_add_explicit(&pool->win_state, 1, memory_order_release); /* odd */ + uint64_t at = base; + for (uint32_t w = 0; w < W; w++) { + uint64_t len = q + (w < r ? 1u : 0u); + atomic_store_explicit(&pool->slots[w].range, + RANGE_PACK((uint32_t)at, (uint32_t)(at + len)), + memory_order_release); + at += len; + } + atomic_fetch_add_explicit(&pool->win_state, 1, memory_order_release); /* even */ +} + +/* Main thread in steal mode: own range, steal, and keep stealing while it + * waits — a worker that was not woken has its range drained from here, so + * completion never depends on a signal count. Progress is pumped as in the + * cursor path: per ticket, and once per 1024 spins. */ +static void pool_main_run_steal(ray_pool_t* pool, bool prog) { + unsigned spin_count = 0; + for (;;) { + pool_run_steal(pool, 0, prog); + if (atomic_load_explicit(&pool->pending, memory_order_acquire) == 0) break; + for (int i = 0; i < 16; i++) { + RAY_CPU_RELAX(); + if (++spin_count % 1024 == 0) { sched_yield(); if (prog) ray_progress_pump(); } + } + } +} + +/* RAY_POOL_TRACE: how the tickets split between own ranges and steals. */ +static void pool_trace_dump(const ray_pool_t* pool) { + uint32_t W = ray_pool_total_workers(pool); + uint64_t own = 0, stolen = 0, steals = 0; + for (uint32_t w = 0; w < W; w++) { + own += pool->slots[w].own; + stolen += pool->slots[w].stolen; + steals += pool->slots[w].steals; + } + fprintf(stderr, "pool: steal=%u workers=%u windows=%llu tickets=%llu own=%llu stolen=%llu steals=%llu\n", + pool->steal, W, + (unsigned long long)(atomic_load_explicit(&pool->win_state, memory_order_relaxed) / 2), + (unsigned long long)(own + stolen), (unsigned long long)own, + (unsigned long long)stolen, (unsigned long long)steals); + for (uint32_t w = 0; w < W; w++) { + const ray_pool_slot_t* s = &pool->slots[w]; + fprintf(stderr, "pool: w%-3u own %12llu stolen %12llu steals %8llu\n", w, + (unsigned long long)s->own, (unsigned long long)s->stolen, + (unsigned long long)s->steals); + } +} + static void worker_loop(void* arg) { worker_ctx_t wctx = *(worker_ctx_t*)arg; ray_sys_free(arg); @@ -93,6 +305,11 @@ static void worker_loop(void* arg) { if (atomic_load_explicit(&pool->shutdown, memory_order_acquire)) break; + if (pool->steal) { + pool_run_steal(pool, wctx.worker_id, false); + continue; + } + /* Claim and execute tasks until the window is drained */ uint64_t idx; while (pool_claim(pool, &idx)) { @@ -162,6 +379,17 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, atomic_init(&pool->task_limit, 0); atomic_init(&pool->pending, 0); atomic_init(&pool->cancelled, 0); + atomic_init(&pool->win_state, 0); + + /* Claiming mode and tracing, read once here so one binary can be A/B'd: + * RAY_POOL_STEAL=0 keeps the shared cursor, anything else (or unset) + * selects per-worker ranges with stealing. */ + { + const char* e = getenv("RAY_POOL_STEAL"); + pool->steal = (e && *e) ? (strtol(e, NULL, 10) != 0) : 1; + e = getenv("RAY_POOL_TRACE"); + pool->trace = (e && *e && strtol(e, NULL, 10) != 0); + } if (auto_size) { /* Auto-size to ncpu-1. The RAYFORCE_CORES env var overrides this @@ -196,12 +424,31 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, pool->tasks = (ray_pool_task_t*)ray_sys_alloc(pool->task_cap * sizeof(ray_pool_task_t)); if (!pool->tasks) return RAY_ERR_OOM; + /* One claim slot per worker, main included, each on its own cache line + * (ray_sys_alloc only guarantees its header alignment, hence the manual + * round-up). Allocated in both modes so the trace and tests can read + * the counters regardless of the switch. */ + { + size_t W = (size_t)n_workers + 1; + pool->slots_raw = ray_sys_alloc(W * sizeof(ray_pool_slot_t) + 64); + if (!pool->slots_raw) { + ray_sys_free(pool->tasks); + return RAY_ERR_OOM; + } + pool->slots = (ray_pool_slot_t*)(((uintptr_t)pool->slots_raw + 63) & ~(uintptr_t)63); + for (size_t w = 0; w < W; w++) { + atomic_init(&pool->slots[w].range, 0); + pool->slots[w].own = pool->slots[w].stolen = pool->slots[w].steals = 0; + } + } + atomic_store_explicit(&pool->task_claim, 0, memory_order_relaxed); atomic_store_explicit(&pool->task_limit, 0, memory_order_relaxed); atomic_store_explicit(&pool->pending, 0, memory_order_relaxed); ray_err_t err = ray_sem_init(&pool->work_ready, 0); if (err != RAY_OK) { + ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return err; } @@ -211,6 +458,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, pool->threads = (ray_thread_t*)ray_sys_alloc(n_workers * sizeof(ray_thread_t)); if (!pool->threads) { ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return RAY_ERR_OOM; } @@ -218,6 +466,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, if (!pool->worker_heaps) { ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return RAY_ERR_OOM; } @@ -238,6 +487,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return RAY_ERR_OOM; } @@ -257,6 +507,7 @@ static ray_err_t ray_pool_create_impl(ray_pool_t* pool, uint32_t n_workers, ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); return err; } @@ -288,9 +539,12 @@ void ray_pool_free(ray_pool_t* pool) { ray_thread_join(pool->threads[i]); } + if (pool->trace && pool->slots) pool_trace_dump(pool); + ray_sys_free(pool->worker_heaps); ray_sys_free(pool->threads); ray_sem_destroy(&pool->work_ready); + ray_sys_free(pool->slots_raw); ray_sys_free(pool->tasks); memset(pool, 0, sizeof(*pool)); } @@ -340,7 +594,9 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, /* 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; the window's slots never alias a still-live slot. */ + * == 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) */ @@ -357,9 +613,17 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } /* pending must be visible before the window opens; the task_limit - * store-release publishes the ring fill AND pending to claimers. */ + * 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); - atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_release); + 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); + } /* Mark parallel region: workers are about to run, cross-heap * freelist modification is unsafe until spin-wait completes. */ @@ -388,7 +652,9 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } /* 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, @@ -405,11 +671,9 @@ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); if (prog) ray_progress_pump(); } - } - /* Spin-wait for workers to finish remaining tasks. - * No semaphore — avoids surplus-signal bug between consecutive dispatches. */ - { + /* Spin-wait for workers to finish remaining tasks. + * No semaphore — avoids surplus-signal bug between consecutive dispatches. */ unsigned spin_count = 0; while (atomic_load_explicit(&pool->pending, memory_order_acquire) > 0) { RAY_CPU_RELAX(); @@ -448,7 +712,13 @@ static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } atomic_store_explicit(&pool->pending, n_tasks, memory_order_relaxed); - atomic_store_explicit(&pool->task_limit, base + n_tasks, memory_order_release); + 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); + } atomic_store_explicit(&ray_parallel_flag, 1, memory_order_release); ray_rc_sync = true; @@ -471,7 +741,9 @@ static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, } /* 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, @@ -488,10 +760,8 @@ static void dispatch_n_round(ray_pool_t* pool, ray_pool_fn fn, void* ctx, atomic_fetch_sub_explicit(&pool->pending, 1, memory_order_acq_rel); if (prog) ray_progress_pump(); } - } - /* Spin-wait for workers to finish remaining tasks */ - { + /* 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(); @@ -549,6 +819,20 @@ void ray_pool_dispatch_n(ray_pool_t* pool, ray_pool_fn fn, void* ctx, static ray_pool_t g_pool; static _Atomic(uint32_t) g_pool_init_state = 0; /* 0=uninit, 1=initializing, 2=ready */ +/* RAY_POOL_TRACE on the singleton: the CLI never destroys it, so the + * histogram is printed from an atexit hook if the pool is still live then + * (ray_pool_free prints it itself otherwise). Workers may still be parked + * at that point; they are idle, so the counters are quiescent. */ +static void pool_trace_atexit(void) { + if (atomic_load_explicit(&g_pool_init_state, memory_order_acquire) == 2) + pool_trace_dump(&g_pool); +} + +static void pool_trace_arm(void) { + static bool armed = false; + if (!armed && g_pool.trace) { armed = true; atexit(pool_trace_atexit); } +} + 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; @@ -559,6 +843,7 @@ ray_pool_t* ray_pool_get(void) { memory_order_acquire)) { ray_err_t err = ray_pool_create(&g_pool, 0); if (err == RAY_OK) { + pool_trace_arm(); atomic_store_explicit(&g_pool_init_state, 2, memory_order_release); return &g_pool; } @@ -611,6 +896,7 @@ static ray_err_t ray_pool_init_impl(uint32_t n_workers, bool auto_size) { } ray_err_t err = ray_pool_create_impl(&g_pool, n_workers, auto_size); if (err == RAY_OK) { + pool_trace_arm(); atomic_store_explicit(&g_pool_init_state, 2, memory_order_release); } else { atomic_store_explicit(&g_pool_init_state, 0, memory_order_release); diff --git a/src/core/pool.h b/src/core/pool.h index f9914df02..c914ff0fd 100644 --- a/src/core/pool.h +++ b/src/core/pool.h @@ -46,6 +46,26 @@ typedef struct { int64_t end; } ray_pool_task_t; +/* Per-worker claim slot of the range+steal scheduler (RAY_POOL_STEAL=1). + * + * `range` holds the worker's unclaimed tickets as head (low 32 bits) and + * tail (high 32 bits) in ONE word, so the owner's head claim and a thief's + * tail cut are both a CAS against the whole pair and can never both win the + * same ticket. The halves are absolute ticket numbers mod 2^32 (never + * window-relative offsets): a stale CAS that happens to match a later + * window's word then takes real, unclaimed tickets of THAT window, with the + * right ring slots (slot = low bits of the ticket, task_cap <= 2^16), so the + * ABA across windows is benign — the same reasoning that keeps task_claim + * monotonic. The three counters are owner-written statistics (printed at + * destroy when RAY_POOL_TRACE is set). One cache line per worker: the + * owner CASes `range` every ticket, thieves touch it only when they steal. */ +typedef struct { + _Alignas(64) _Atomic(uint64_t) range; /* head:32 | tail:32, absolute tickets */ + uint64_t own; /* tickets run out of the worker's own share */ + uint64_t stolen; /* tickets run that were cut from other workers' tails */ + uint64_t steals; /* successful steal operations */ +} ray_pool_slot_t; + /* Thread pool */ struct ray_pool { ray_thread_t* threads; /* worker thread handles [n_workers] */ @@ -78,6 +98,24 @@ struct ray_pool { _Atomic(uint64_t) task_claim; /* next ticket to claim (bounded CAS) */ _Atomic(uint64_t) task_limit; /* published end of current window */ + /* Range+steal scheduler (RAY_POOL_STEAL, read once at creation; 1 by + * default). Each window [base, base+n) is split into one contiguous + * ticket range per worker (main included), kept in slots[w].range; a + * worker claims from its head and, once empty, halves the tail of the + * other workers' ranges in a fixed victim order. task_limit stays the + * monotonic high-water mark the window is carved from; task_claim is + * advanced with it only as bookkeeping. `win_state` is odd while the + * dispatcher is writing the range words of a window and even once they + * are all out — a thief that cut a chunk while the window was still + * being published runs it privately instead of installing it in its + * own slot, which the dispatcher may be about to overwrite with that + * worker's share. 0 = shared cursor, the pre-range behaviour. */ + uint32_t steal; + uint32_t trace; /* RAY_POOL_TRACE: histogram at destroy */ + ray_pool_slot_t* slots; /* [n_workers+1], 64-byte aligned */ + void* slots_raw; /* the allocation behind `slots` */ + _Atomic(uint64_t) win_state; /* 2*windows + (publishing ? 1 : 0) */ + /* Barrier */ _Atomic(uint32_t) pending; /* decremented by each task completion */ ray_sem_t work_ready; /* workers sleep here */ @@ -122,6 +160,19 @@ ray_err_t ray_pool_create(ray_pool_t* pool, uint32_t n_workers); /* Shutdown and free all resources */ void ray_pool_free(ray_pool_t* pool); +/* ORDER CONTRACT. The tasks of one window may run in ANY order and on any + * worker: concurrently, a later task before an earlier one, and one worker + * may run tasks from anywhere in the window (with ranges+stealing a worker + * 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). */ + /* Dispatch fn over [0, total_elems) partitioned into morsel-sized tasks. * Blocks until all tasks complete. Main thread participates as worker 0. */ void ray_pool_dispatch(ray_pool_t* pool, ray_pool_fn fn, void* ctx, int64_t total_elems); diff --git a/src/core/runtime.c b/src/core/runtime.c index 8295cdee0..0c7d23c04 100644 --- a/src/core/runtime.c +++ b/src/core/runtime.c @@ -260,10 +260,11 @@ static ray_runtime_t* runtime_create_impl(const char* sym_path, ray_vm_init(rt->vms[0], 0); __VM = rt->vms[0]; - /* Detect total physical RAM (informational — surfaced via .sys.mem and + /* Detect total physical RAM (informational — surfaced via .sys.info and * used as a sanity bound for the sym-file pre-load check below). There is * NO enforced memory ceiling: the heap is out-of-core and spills to a - * file-backed mapping when anonymous mmap is refused (see heap_add_pool). */ + * file-backed mapping once its anon footprint reaches the watermark (see + * heap_add_pool), whose default is ram_limit below. */ #ifdef RAY_OS_WINDOWS MEMORYSTATUSEX ms; ms.dwLength = sizeof(ms); @@ -279,6 +280,14 @@ static ray_runtime_t* runtime_create_impl(const char* sym_path, else rt->total_ram = (int64_t)(4ULL << 30); #endif + /* A container / cgroup limit below host RAM is where the OOM killer + * actually fires, so the spill threshold defaults to the smaller of the + * two (#688). An explicit -m / ray_heap_set_anon_watermark still wins. */ + rt->ram_limit = rt->total_ram; + { + int64_t cg = ray_os_cgroup_mem_limit(); + if (cg > 0 && cg < rt->ram_limit) rt->ram_limit = cg; + } /* __RUNTIME must be visible before ray_sym_load so the sym-load size * check and ray_error() both operate against the live runtime. */ @@ -374,6 +383,10 @@ int64_t ray_sys_total_ram(void) { return __RUNTIME ? __RUNTIME->total_ram : 0; } +int64_t ray_sys_ram_limit(void) { + return __RUNTIME ? __RUNTIME->ram_limit : 0; +} + int8_t ray_obj_type(ray_t* v) { return v ? v->type : 0; } diff --git a/src/core/runtime.h b/src/core/runtime.h index d23655916..a7eb32caa 100644 --- a/src/core/runtime.h +++ b/src/core/runtime.h @@ -118,6 +118,7 @@ typedef struct ray_runtime_s { ray_vm_t **vms; int32_t n_vms; int64_t total_ram; /* total physical RAM, bytes */ + int64_t ram_limit; /* min(total_ram, cgroup limit) — default anon watermark */ void *poll; /* opaque ray_poll_t* — see ray_runtime_(set|get)_poll */ void *sys_args; /* opaque ray_t* dict — see ray_runtime_(set|get)_sys_args */ } ray_runtime_t; diff --git a/src/core/sock.c b/src/core/sock.c index 18f0c502c..c04894f15 100644 --- a/src/core/sock.c +++ b/src/core/sock.c @@ -26,6 +26,8 @@ #endif #include "core/sock.h" +#include "core/timer.h" +#include #include #include #include @@ -161,6 +163,45 @@ ray_sock_t ray_sock_accept(ray_sock_t srv) return fd; } +int ray_sock_set_keepalive(ray_sock_t s, int budget_ms, bool user_timeout) +{ + int on = budget_ms > 0 ? 1 : 0; + if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on)) < 0) + return -1; + if (!on) return 0; + + int idle = budget_ms / 2000; /* seconds */ + int intvl = budget_ms / 6000; + int cnt = 3; + if (idle < 1) idle = 1; + if (intvl < 1) intvl = 1; +#if defined(TCP_KEEPIDLE) + setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, (const char*)&idle, sizeof(idle)); +#elif defined(TCP_KEEPALIVE) /* macOS spelling */ + setsockopt(s, IPPROTO_TCP, TCP_KEEPALIVE, (const char*)&idle, sizeof(idle)); +#endif +#ifdef TCP_KEEPINTVL + setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, (const char*)&intvl, sizeof(intvl)); +#endif +#ifdef TCP_KEEPCNT + setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, (const char*)&cnt, sizeof(cnt)); +#endif + + if (user_timeout) { +#if defined(TCP_USER_TIMEOUT) + unsigned int ut = (unsigned int)budget_ms; + setsockopt(s, IPPROTO_TCP, TCP_USER_TIMEOUT, (const char*)&ut, sizeof(ut)); +#elif defined(TCP_RXT_CONNDROPTIME) /* macOS */ + int ut = budget_ms < 1000 ? 1 : budget_ms / 1000; + setsockopt(s, IPPROTO_TCP, TCP_RXT_CONNDROPTIME, (const char*)&ut, sizeof(ut)); +#elif defined(TCP_MAXRT) /* Windows */ + int ut = budget_ms < 1000 ? 1 : budget_ms / 1000; + setsockopt(s, IPPROTO_TCP, TCP_MAXRT, (const char*)&ut, sizeof(ut)); +#endif + } + return 0; +} + /* Connect an already-created socket `fd` to one resolved address. With * timeout_ms > 0 the connect is driven non-blocking + poll (a blocking * connect() ignores SO_*TIMEO) and the same budget is then applied as the @@ -277,6 +318,12 @@ ray_sock_t ray_sock_connect(const char* host, uint16_t port, int timeout_ms) } int64_t ray_sock_send(ray_sock_t s, const void* buf, size_t len) +{ + return ray_sock_send_until(s, buf, len, -1); +} + +int64_t ray_sock_send_until(ray_sock_t s, const void* buf, size_t len, + int64_t deadline_ms) { const uint8_t* p = (const uint8_t*)buf; size_t rem = len; @@ -291,11 +338,17 @@ int64_t ray_sock_send(ray_sock_t s, const void* buf, size_t len) if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) { /* Wait for write-readiness before retry */ + int wait_ms = -1; + if (deadline_ms >= 0) { + int64_t left = deadline_ms - ray_time_now_ms(); + if (left <= 0) { errno = ETIMEDOUT; return -1; } + wait_ms = left > INT_MAX ? INT_MAX : (int)left; + } struct pollfd pfd = { .fd = s, .events = POLLOUT }; #ifdef RAY_OS_WINDOWS - WSAPoll(&pfd, 1, -1); + WSAPoll(&pfd, 1, wait_ms); #else - poll(&pfd, 1, -1); + poll(&pfd, 1, wait_ms); #endif continue; } diff --git a/src/core/sock.h b/src/core/sock.h index d400dbef6..c11aae48c 100644 --- a/src/core/sock.h +++ b/src/core/sock.h @@ -50,6 +50,12 @@ ray_sock_t ray_sock_accept(ray_sock_t srv); * RAY_INVALID_SOCK is returned. */ ray_sock_t ray_sock_connect(const char* host, uint16_t port, int timeout_ms); int64_t ray_sock_send(ray_sock_t s, const void* buf, size_t len); +/* As ray_sock_send, but gives up once the monotonic clock + * (ray_time_now_ms) reaches deadline_ms, returning -1 with errno + * ETIMEDOUT. The frame may then be partly written, so the caller must + * treat the stream as unusable. deadline_ms < 0 = no deadline. */ +int64_t ray_sock_send_until(ray_sock_t s, const void* buf, size_t len, + int64_t deadline_ms); int64_t ray_sock_recv(ray_sock_t s, void* buf, size_t len); /* Block until s is readable (or hung up). timeout_ms < 0 = no timeout. * Returns 1 readable, 0 timed out, -1 error. */ @@ -64,6 +70,24 @@ void ray_sock_set_oob_owner(ray_sock_t s); int ray_sock_take_oob(ray_sock_t s); void ray_sock_close(ray_sock_t s); ray_err_t ray_sock_set_nonblocking(ray_sock_t s); +/* Dead-peer detection for an established TCP connection (#589). + * budget_ms > 0 turns on kernel keepalive tuned so that a silent peer is + * declared dead about budget_ms after the last thing it sent: the first + * probe goes out at budget_ms/2 of idle, then three more at budget_ms/6 + * (whole seconds, at least 1 each — the kernel's granularity). Keepalive + * only probes while nothing is in flight, so a live peer that is merely + * slow to read or to answer is never affected. + * + * user_timeout additionally bounds how long sent data may stay + * unacknowledged (TCP_USER_TIMEOUT on Linux, the nearest equivalent + * elsewhere). That also catches a peer that vanishes with our data in + * flight, but it fires on a live peer that stops reading for budget_ms + * too (a zero receive window), so it is opt-in only. + * + * budget_ms <= 0 turns keepalive off. Best-effort: an option the + * platform lacks is skipped. Returns 0, or -1 if keepalive itself could + * not be enabled. */ +int ray_sock_set_keepalive(ray_sock_t s, int budget_ms, bool user_timeout); ray_err_t ray_sock_set_blocking(ray_sock_t s); /* ===== Link locality ===== diff --git a/src/core/types.c b/src/core/types.c index e811bac12..0599fcb24 100644 --- a/src/core/types.c +++ b/src/core/types.c @@ -55,3 +55,8 @@ int ray_version_major(void) { return RAY_VERSION_MAJOR; } int ray_version_minor(void) { return RAY_VERSION_MINOR; } int ray_version_patch(void) { return RAY_VERSION_PATCH; } const char* ray_version_string(void) { return RAY_VERSION_STRING_; } + +#ifndef RAYFORCE_GIT_COMMIT +#define RAYFORCE_GIT_COMMIT "unknown" +#endif +const char* ray_git_commit(void) { return RAYFORCE_GIT_COMMIT; } diff --git a/src/io/csv.c b/src/io/csv.c index f4d583ef7..a5c7f7f2f 100644 --- a/src/io/csv.c +++ b/src/io/csv.c @@ -42,6 +42,7 @@ #include "mem/sys.h" #include "core/numparse.h" #include "core/pool.h" +#include "core/profile.h" /* ray_profile_now_ns: RAY_CSV_TRACE phase stamps */ #include "core/platform.h" /* ray_vm_map_fd_ro / ray_vm_unmap_file (tracked) */ #include "lang/format.h" #include "ops/hash.h" @@ -49,6 +50,7 @@ #include "store/col.h" #include "store/fileio.h" #include "store/splay.h" +#include "store/stream.h" #include "table/sym.h" #include "table/domain.h" #include "vec/str.h" @@ -1370,6 +1372,97 @@ static int64_t build_row_offsets_limited(const char* buf, size_t buf_size, return n; } +/* Row starts of the next `max_rows` rows from `off`: the parallel window + * scan when it applies, else the serial limited scan — the pairing the + * streaming import loop uses, so both see identical row boundaries. + * *avg_row is refined from each chunk. */ +static int64_t csv_scan_rows_chunk(const char* buf, size_t file_size, + size_t off, int64_t max_rows, + size_t* avg_row, bool data_has_quotes, + int64_t** offs, ray_t** hdr, size_t* next) { + int64_t cnt = build_row_offsets_window(buf, file_size, off, max_rows, + *avg_row, data_has_quotes, + offs, hdr, next); + if (cnt == -2) + cnt = build_row_offsets_limited(buf, file_size, off, max_rows, + data_has_quotes, offs, hdr, next); + if (cnt > 0 && *next > off) *avg_row = (*next - off) / (size_t)cnt; + return cnt; +} + +#define CSV_SAMPLE_SCAN_ROWS (1 << 20) + +/* Type-inference sample for the streaming importers, chosen exactly as + * .csv.read chooses it: CSV_SAMPLE_ROWS rows at indices + * si * (n - 1) / (CSV_SAMPLE_ROWS - 1) over all n data rows, or every row + * when n is no larger. The streaming paths never hold all row offsets, so + * this costs a counting pass and a picking pass over the row boundaries — + * but it is what keeps .csv.splayed / .csv.parted inferring the same column + * types as .csv.read for the same file (SYM vs STR is a sample-cardinality + * decision, so any other sample can disagree). Fed to + * csv_infer_types_from_offsets with n_rows == the sample size, every row + * given is used. Same contract as build_row_offsets_limited: the row + * count, 0 on allocation failure, -1 if interrupted. */ +static int64_t csv_streaming_sample(const char* buf, size_t file_size, + size_t data_offset, bool data_has_quotes, + int64_t** offsets_out, ray_t** hdr_out) { + *offsets_out = NULL; + *hdr_out = NULL; + if (data_offset >= file_size) return 0; + + /* Pass 1: count rows. */ + int64_t total = 0; + size_t avg_row = 64; + for (size_t off = data_offset; off < file_size; ) { + int64_t* o = NULL; ray_t* h = NULL; size_t next = off; + int64_t cnt = csv_scan_rows_chunk(buf, file_size, off, + CSV_SAMPLE_SCAN_ROWS, &avg_row, + data_has_quotes, &o, &h, &next); + scratch_free(h); + if (cnt < 0) return -1; + if (cnt == 0 || next <= off) break; + total += cnt; + off = next; + } + + if (total <= CSV_SAMPLE_ROWS) + return build_row_offsets_limited(buf, file_size, data_offset, + CSV_SAMPLE_ROWS, data_has_quotes, + offsets_out, hdr_out, NULL); + + ray_t* hdr = NULL; + int64_t* picked = (int64_t*)scratch_alloc(&hdr, + (size_t)CSV_SAMPLE_ROWS * sizeof(int64_t)); + if (!picked) return 0; + + /* Pass 2: pick the sample rows' offsets. */ + int64_t si = 0, base = 0; + int64_t target = 0; /* index of sample row si */ + for (size_t off = data_offset; off < file_size && si < CSV_SAMPLE_ROWS; ) { + int64_t* o = NULL; ray_t* h = NULL; size_t next = off; + int64_t cnt = csv_scan_rows_chunk(buf, file_size, off, + CSV_SAMPLE_SCAN_ROWS, &avg_row, + data_has_quotes, &o, &h, &next); + if (cnt < 0) { scratch_free(h); scratch_free(hdr); return -1; } + if (cnt == 0 || next <= off) { scratch_free(h); break; } + while (si < CSV_SAMPLE_ROWS && target < base + cnt) { + picked[si++] = o[target - base]; + if (si < CSV_SAMPLE_ROWS) + target = si * (total - 1) / (CSV_SAMPLE_ROWS - 1); + } + scratch_free(h); + base += cnt; + off = next; + } + if (si != CSV_SAMPLE_ROWS) { /* file changed under the map? */ + scratch_free(hdr); + return 0; + } + *offsets_out = picked; + *hdr_out = hdr; + return si; +} + /* -------------------------------------------------------------------------- * Per-column local dedupe — the parallel front half of the sym intern. * @@ -2498,7 +2591,9 @@ static int csv_hash_elem_size(int8_t t) { * * Returns 1 to attach, 0 to skip. */ /* Payload-level core of the hash-upgrade decision. Its only caller is the - * .csv.splayed index builder (ray_splay_build_indexes): indexing is a + * .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 @@ -2983,12 +3078,10 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size, col_data[c] = dst; } - /* No index attach here. This function feeds the streaming csv→splayed / - * →parted writers: every column it produces is immediately serialised to - * disk and thrown away, and store/splay.c decides and persists the real - * index (chunk-zone / dict, upgraded to hash by - * ray_csv_hash_upgrade_check) at conversion time. Building an in-memory - * index per 1M-row chunk here was pure waste. */ + /* Index policy belongs to each destination writer: splayed stream writers + * build theirs inline while the column is written; parted attaches + * persisted zones to each final partition while it is resident. + * Intermediate chunks need none. */ ray_t* tbl = ray_table_new(ncols); if (!tbl || RAY_IS_ERR(tbl)) { @@ -3527,156 +3620,14 @@ ray_t* ray_read_csv_opts(const char* path, char delimiter, bool header, col_types_in, n_types, NULL, 0); } -typedef struct { - FILE* fp; - char path[1024]; - char tmp_path[1024]; - int8_t type; - uint8_t attrs; - int64_t rows; - bool had_nulls; - /* SYM columns: the target symfile's domain (shared, borrowed from - * the caller). Cells are encoded as positions in it — the freshly - * parsed chunk vecs are runtime-domain, so each cell's string is - * find-or-appended into the domain (the flip, Task 7b). Width is - * fixed at W32: a streaming writer can't know the final vocabulary - * before the last chunk, and W32 covers any STRL count. */ - struct ray_sym_domain_s* dom; - /* runtime id -> domain position, direct-mapped: the chunk vecs are - * runtime-domain and a column's values repeat across rows and chunks, - * so a value is interned into the symfile's domain (a locked probe) the - * first time it is met and looked up here after. */ - int64_t* lut_id; /* [CSV_SPLAYED_LUT] runtime id per slot, -1 empty */ - uint32_t* lut_pos; /* [CSV_SPLAYED_LUT] position per slot */ -} csv_splayed_col_writer_t; -#define CSV_SPLAYED_LUT_BITS 19 -#define CSV_SPLAYED_LUT (1u << CSV_SPLAYED_LUT_BITS) - -static ray_err_t csv_splayed_writer_open(csv_splayed_col_writer_t* w, - const char* dir, int64_t name_id, - int8_t type, - struct ray_sym_domain_s* dom) { - memset(w, 0, sizeof(*w)); - w->type = type; - w->attrs = (type == RAY_SYM) ? RAY_SYM_W32 : 0; - w->dom = dom; - if (type == RAY_SYM && !dom) return RAY_ERR_IO; - - ray_t* name_atom = ray_sym_str(name_id); - if (!name_atom) return RAY_ERR_CORRUPT; - const char* name = ray_str_ptr(name_atom); - size_t name_len = ray_str_len(name_atom); - if (name_len == 0 || name[0] == '.' || - memchr(name, '/', name_len) || memchr(name, '\\', name_len) || - memchr(name, '\0', name_len)) - return RAY_ERR_DOMAIN; - - int n = snprintf(w->path, sizeof(w->path), "%s/%.*s", - dir, (int)name_len, name); - if (n < 0 || (size_t)n >= sizeof(w->path)) return RAY_ERR_RANGE; - n = snprintf(w->tmp_path, sizeof(w->tmp_path), "%s.tmp", w->path); - if (n < 0 || (size_t)n >= sizeof(w->tmp_path)) return RAY_ERR_RANGE; - - w->fp = fopen(w->tmp_path, "wb+"); - if (!w->fp) return RAY_ERR_IO; - ray_t zero = {0}; - if (fwrite(&zero, 1, 32, w->fp) != 32) return RAY_ERR_IO; - if (type == RAY_SYM) { - /* best effort: without the cache every cell probes the domain */ - w->lut_id = (int64_t*)ray_alloc_raw((size_t)CSV_SPLAYED_LUT * sizeof(int64_t)); - w->lut_pos = (uint32_t*)ray_alloc_raw((size_t)CSV_SPLAYED_LUT * sizeof(uint32_t)); - if (!w->lut_id || !w->lut_pos) { - ray_free_raw(w->lut_id); ray_free_raw(w->lut_pos); - w->lut_id = NULL; w->lut_pos = NULL; - } else { - memset(w->lut_id, 0xff, (size_t)CSV_SPLAYED_LUT * sizeof(int64_t)); - } - } - return RAY_OK; -} - -static void csv_splayed_writer_drop_lut(csv_splayed_col_writer_t* w) { - ray_free_raw(w->lut_id); ray_free_raw(w->lut_pos); - w->lut_id = NULL; w->lut_pos = NULL; -} - -static ray_err_t csv_splayed_writer_append(csv_splayed_col_writer_t* w, - ray_t* col) { - if (!w->fp || !col || RAY_IS_ERR(col)) return RAY_ERR_TYPE; - int64_t n = col->len; - if (n < 0) return RAY_ERR_CORRUPT; - - if (w->type == RAY_SYM) { - /* Encode cells as positions in the target symfile's domain: - * resolve each cell through the chunk vec's own domain and - * find-or-append into the target (distinct work rides the - * write). The domain is flushed before the column files are - * committed (close), preserving the sym-first crash ordering. - * A runtime-domain chunk vec goes through the id -> position - * cache: only a value's first encounter pays the domain probe. */ - bool direct = ray_sym_vec_domain(col) == w->dom; - bool cached = ray_sym_vec_domain(col) == ray_sym_runtime_domain() && w->lut_id; - const void* cd = ray_data(col); - uint32_t buf[8192]; - for (int64_t off = 0; off < n; ) { - int64_t cnt = n - off; - if (cnt > (int64_t)(sizeof(buf) / sizeof(buf[0]))) - cnt = (int64_t)(sizeof(buf) / sizeof(buf[0])); - for (int64_t i = 0; i < cnt; i++) { - int64_t pos; - if (direct) { - /* Already encoded over the target domain. */ - pos = ray_read_sym(cd, off + i, RAY_SYM, col->attrs); - } else if (cached) { - int64_t id = ray_read_sym(cd, off + i, RAY_SYM, col->attrs); - uint32_t slot = (uint32_t)(((uint64_t)id * 0x9E3779B97F4A7C15ull) >> (64 - CSV_SPLAYED_LUT_BITS)); - if (w->lut_id[slot] == id) { - pos = w->lut_pos[slot]; - } else { - ray_t* s = ray_sym_str(id); - if (!s) return RAY_ERR_CORRUPT; - pos = ray_sym_domain_intern(w->dom, ray_str_ptr(s), ray_str_len(s)); - if (pos < 0) return RAY_ERR_OOM; - w->lut_id[slot] = id; w->lut_pos[slot] = (uint32_t)pos; - } - } else { - ray_t* s = ray_sym_vec_cell(col, off + i); - if (!s) return RAY_ERR_CORRUPT; - pos = ray_sym_domain_intern(w->dom, ray_str_ptr(s), ray_str_len(s)); - if (pos < 0) return RAY_ERR_OOM; - } - buf[i] = (uint32_t)pos; - /* Position 0 of any symfile is the empty string (domain.c - * enforces that reservation on open), so a re-encoded cell is - * the canonical SYM null exactly when its position is 0. - * Testing the value WRITTEN keeps the on-disk HAS_NULLS honest - * without trusting the chunk vec's attrs — and this arm is why - * streamed SYM columns used to lose the bit entirely: only the - * non-SYM arm below propagated it (issue #416). */ - if (pos == 0) w->had_nulls = true; - } - if (fwrite(buf, sizeof(uint32_t), (size_t)cnt, w->fp) != (size_t)cnt) - return RAY_ERR_IO; - off += cnt; - } - } else { - uint8_t esz = ray_sym_elem_size(w->type, 0); - size_t bytes = (size_t)n * (size_t)esz; - if (bytes && fwrite(ray_data(col), 1, bytes, w->fp) != bytes) - return RAY_ERR_IO; - if (col->attrs & RAY_ATTR_HAS_NULLS) w->had_nulls = true; - } - w->rows += n; - return RAY_OK; -} - /* Append task: column `start` of the chunk table into its writer. The * first failure is kept (a later task cannot clear it). */ typedef struct { - csv_splayed_col_writer_t* writers; + ray_col_stream_t* writers; ray_t* tbl; int ncols; _Atomic(ray_err_t) err; + int64_t* col_ns; /* RAY_CSV_TRACE: per-column append time, or NULL */ } csv_splayed_append_ctx_t; static void csv_splayed_append_task(void* raw, uint32_t wid, int64_t start, int64_t end) { @@ -3684,59 +3635,30 @@ static void csv_splayed_append_task(void* raw, uint32_t wid, int64_t start, int6 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); - ray_err_t e = csv_splayed_writer_append(&a->writers[start], col); + 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 (e != RAY_OK) { ray_err_t ok = RAY_OK; atomic_compare_exchange_strong_explicit(&a->err, &ok, e, memory_order_relaxed, memory_order_relaxed); } } -static ray_err_t csv_splayed_writer_close(csv_splayed_col_writer_t* w) { - csv_splayed_writer_drop_lut(w); - if (!w->fp) return RAY_OK; - ray_err_t err = RAY_OK; - - if (err == RAY_OK) { - ray_t hdr = {0}; - hdr.type = w->type; - hdr.attrs = w->attrs; - hdr.len = w->rows; - /* SYM: header rc = the symfile's count (the loader's O(1) - * fast-reject against the FILE domain). */ - hdr.rc = (w->type == RAY_SYM) - ? (uint32_t)ray_sym_domain_count(w->dom) : 0; - if (w->had_nulls) hdr.attrs |= RAY_ATTR_HAS_NULLS; - /* Stamp the on-disk format major version into `order` so the - * streamed column file shares the exact identity ray_col_save - * writes — the loaders validate it. aux stays zero (it was - * zero-initialized above) — reserved for postponed index data. */ - ray_col_stamp_format(&hdr); - if (fseek(w->fp, 0, SEEK_SET) != 0 || - fwrite(&hdr, 1, 32, w->fp) != 32) - err = RAY_ERR_IO; - } - - if (fclose(w->fp) != 0 && err == RAY_OK) err = RAY_ERR_IO; - w->fp = NULL; - if (err == RAY_OK) err = ray_file_rename(w->tmp_path, w->path); - if (err != RAY_OK) remove(w->tmp_path); - return err; -} - -static void csv_splayed_writer_abort(csv_splayed_col_writer_t* w) { - csv_splayed_writer_drop_lut(w); - if (w->fp) fclose(w->fp); - w->fp = NULL; - remove(w->tmp_path); -} - -ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool header, +static ray_err_t csv_save_splayed_to_dir(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) { + const char* dir, int64_t rows_per_chunk, + const char* sym_path) { if (ray_interrupted()) return RAY_ERR_CANCEL; - if (!path || !dir) return RAY_ERR_DOMAIN; + if (!path || !dir || !sym_path) return RAY_ERR_DOMAIN; if (rows_per_chunk <= 0) rows_per_chunk = CSV_PART_ROWS_DEFAULT; + /* RAY_CSV_TRACE: phase timings to stderr, as csv.parted prints them. */ + bool trace = getenv("RAY_CSV_TRACE") != NULL; + int64_t tr_t0 = ray_profile_now_ns(); + int64_t tr_scan = 0, tr_parse = 0, tr_append = 0, tr_chunks = 0; + int64_t tr_col_ns[CSV_MAX_COLS]; + memset(tr_col_ns, 0, sizeof(tr_col_ns)); +#define TR_MS(ns) ((double)(ns) / 1e6) int fd = open(path, O_RDONLY); if (fd < 0) return RAY_ERR_IO; @@ -3834,12 +3756,10 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool } else if (!col_types_in) { ray_t* sample_offsets_hdr = NULL; int64_t* sample_offsets = NULL; - int64_t sample_n = build_row_offsets_limited(buf, file_size, data_offset, - CSV_SAMPLE_ROWS, - data_has_quotes, - &sample_offsets, - &sample_offsets_hdr, - NULL); + int64_t sample_n = csv_streaming_sample(buf, file_size, data_offset, + data_has_quotes, + &sample_offsets, + &sample_offsets_hdr); if (sample_n < 0) { ray_vm_unmap_file(buf, file_size); return RAY_ERR_CANCEL; @@ -3854,33 +3774,6 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool } } - for (int c = 0; c < ncols; c++) { - if (resolved_types[c] == RAY_STR) { - ray_t* tbl = ray_read_csv_named_opts(path, delimiter, header, - col_types_in, n_types, - col_names_in, n_names); - if (!tbl || RAY_IS_ERR(tbl)) { - ray_vm_unmap_file(buf, file_size); - return tbl ? ray_err_from_obj(tbl) : RAY_ERR_IO; - } - /* Splay save owns the symfile now: dir/.sym is the table's - * domain (distinct-merge + position encoding); symbol-free - * tables write none. The dotfile name leaves "sym" free as a - * user column. */ - char sym_path[1024]; - int n = snprintf(sym_path, sizeof(sym_path), "%s/.sym", dir); - if (n < 0 || (size_t)n >= sizeof(sym_path)) { - ray_release(tbl); - ray_vm_unmap_file(buf, file_size); - return RAY_ERR_RANGE; - } - err = ray_splay_save_bulk(tbl, dir, sym_path); - ray_release(tbl); - ray_vm_unmap_file(buf, file_size); - return err; - } - } - /* `INT` schema columns: resolve to a concrete narrowest width over the * whole file before opening the fixed-width streaming column writers. */ if (!csv_resolve_auto_streamed(buf, file_size, data_offset, ncols, @@ -3917,12 +3810,6 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool for (int c = 0; c < ncols; c++) if (resolved_types[c] == RAY_SYM) any_sym = true; if (any_sym) { - char sym_path[1024]; - int n = snprintf(sym_path, sizeof(sym_path), "%s/.sym", dir); - if (n < 0 || (size_t)n >= sizeof(sym_path)) { - ray_vm_unmap_file(buf, file_size); - return RAY_ERR_RANGE; - } sym_dom = ray_sym_domain_open_or_create(sym_path); if (!sym_dom) { ray_vm_unmap_file(buf, file_size); @@ -3943,13 +3830,14 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool } } - csv_splayed_col_writer_t writers[CSV_MAX_COLS]; + ray_col_stream_t writers[CSV_MAX_COLS]; memset(writers, 0, sizeof(writers)); for (int c = 0; c < ncols; c++) { - err = csv_splayed_writer_open(&writers[c], dir, col_name_ids[c], + err = ray_col_stream_open(&writers[c], dir, col_name_ids[c], resolved_types[c], sym_dom); + if (err == RAY_OK) err = ray_col_stream_index_begin(&writers[c], 0); if (err != RAY_OK) { - for (int j = 0; j < c; j++) csv_splayed_writer_abort(&writers[j]); + for (int j = 0; j <= c; j++) ray_col_stream_abort(&writers[j]); if (sym_dom) ray_sym_domain_release(sym_dom); ray_vm_unmap_file(buf, file_size); return err; @@ -3959,11 +3847,13 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool size_t chunk_offset = data_offset; bool wrote_any = false; size_t avg_row_bytes = 64; /* refined from every chunk scanned */ + int64_t tr_setup = ray_profile_now_ns() - tr_t0; while (chunk_offset < file_size || !wrote_any) { ray_t* row_offsets_hdr = NULL; int64_t* row_offsets = NULL; size_t next_offset = chunk_offset; int64_t cnt = 0; + int64_t tr_c0 = ray_profile_now_ns(); if (chunk_offset < file_size) { /* Parallel scan over a byte window sized from the rows seen so * far; the serial walk remains the fallback and the semantics. */ @@ -3986,6 +3876,7 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool } } + int64_t tr_c1 = ray_profile_now_ns(); ray_t* tbl = csv_materialize_rows(buf, file_size, row_offsets, cnt, ncols, delimiter, col_name_ids, resolved_types, sym_dom); @@ -3996,6 +3887,7 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool if (tbl) ray_release(tbl); break; } + int64_t tr_c2 = ray_profile_now_ns(); /* One task per column: each writer owns its file, its cache and * its symfile domain (the domain probe takes the domain lock, the @@ -4003,7 +3895,8 @@ ray_err_t ray_csv_save_splayed_named_opts(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, + .col_ns = trace ? tr_col_ns : NULL }; ray_pool_t* wpool = ray_pool_get(); if (ray_pool_par_dispatch_ok(wpool, ncols, 2)) ray_pool_dispatch_n(wpool, csv_splayed_append_task, &actx, (uint32_t)ncols); @@ -4012,6 +3905,11 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool err = actx.err; } ray_release(tbl); + int64_t tr_c3 = ray_profile_now_ns(); + tr_scan += tr_c1 - tr_c0; tr_parse += tr_c2 - tr_c1; tr_append += tr_c3 - tr_c2; tr_chunks++; + if (trace) + fprintf(stderr, "csv.splayed: chunk=%" PRId64 " rows=%" PRId64 " scan=%.1fms parse=%.1fms append=%.1fms\n", + tr_chunks, cnt, TR_MS(tr_c1 - tr_c0), TR_MS(tr_c2 - tr_c1), TR_MS(tr_c3 - tr_c2)); if (err != RAY_OK) break; wrote_any = true; /* The chunk's bytes are done with: drop them from the mapping so a @@ -4029,15 +3927,67 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool /* Flush the symfile BEFORE committing column files (writer_close * renames tmp → final): columns must never reference positions the * symfile doesn't persist (sym-first crash ordering). */ + int64_t tr_loop_end = ray_profile_now_ns(); + if (trace) { + fprintf(stderr, "csv.splayed: file=%s ncols=%d chunks=%" PRId64 " setup=%.1fms scan=%.1fms parse=%.1fms append=%.1fms loop=%.1fms\n", + path, ncols, tr_chunks, TR_MS(tr_setup), TR_MS(tr_scan), TR_MS(tr_parse), TR_MS(tr_append), + TR_MS(tr_loop_end - tr_t0 - tr_setup)); + /* the three columns whose append tasks took the longest in total: + * the critical path of every chunk's column dispatch */ + for (int k = 0; k < 3 && k < ncols; k++) { + int best = -1; + for (int c = 0; c < ncols; c++) + if (tr_col_ns[c] > 0 && (best < 0 || tr_col_ns[c] > tr_col_ns[best])) best = c; + if (best < 0) break; + ray_t* na = ray_sym_str(col_name_ids[best]); + fprintf(stderr, "csv.splayed: append_top%d col=%s type=%d total=%.1fms\n", k + 1, + na ? ray_str_ptr(na) : "?", (int)resolved_types[best], TR_MS(tr_col_ns[best])); + tr_col_ns[best] = -tr_col_ns[best]; + } + } if (err == RAY_OK && sym_dom) { err = ray_sym_domain_flush(sym_dom, false); } + int64_t tr_flush_end = ray_profile_now_ns(); + if (trace) fprintf(stderr, "csv.splayed: symfile_flush=%.1fms\n", TR_MS(tr_flush_end - tr_loop_end)); - for (int c = 0; c < ncols; c++) { - ray_err_t cerr = (err == RAY_OK) ? csv_splayed_writer_close(&writers[c]) - : RAY_ERR_IO; - if (err == RAY_OK && cerr != RAY_OK) err = cerr; - if (err != RAY_OK) csv_splayed_writer_abort(&writers[c]); + /* Every column finishes as a pool task (STR pool merge, dictionary / + * 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) 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(); + if (trace) { + int64_t mx = 0; int mxc = -1; + for (int c = 0; c < ncols; c++) if (tr_col_ns[c] > mx) { mx = tr_col_ns[c]; mxc = c; } + ray_t* na = mxc >= 0 ? ray_sym_str(col_name_ids[mxc]) : NULL; + fprintf(stderr, "csv.splayed: finish+publish=%.1fms longest_finish=%s %.1fms\n", + TR_MS(tr_close_end - tr_flush_end), + na ? ray_str_ptr(na) : "-", TR_MS(mx)); + } + + /* 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. */ + 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)); } /* .d LAST — the commit marker. All column files are renamed into @@ -4067,17 +4017,38 @@ ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool ray_release(schema); } } + 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)); +#undef TR_MS if (sym_dom) ray_sym_domain_release(sym_dom); ray_vm_unmap_file(buf, file_size); return err; } -ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool header, +ray_err_t ray_csv_save_splayed_named_opts(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) { + 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); + 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); + return ray_splay_write_finish(&write, err, false); +} + +static ray_err_t csv_save_parted_impl(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* root, const char* table_name, - int64_t rows_per_part) { + int64_t rows_per_part, bool staged) { 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; @@ -4185,12 +4156,10 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool } else if (!col_types_in) { ray_t* sample_offsets_hdr = NULL; int64_t* sample_offsets = NULL; - int64_t sample_n = build_row_offsets_limited(buf, file_size, data_offset, - CSV_SAMPLE_ROWS, - data_has_quotes, - &sample_offsets, - &sample_offsets_hdr, - NULL); + int64_t sample_n = csv_streaming_sample(buf, file_size, data_offset, + data_has_quotes, + &sample_offsets, + &sample_offsets_hdr); if (sample_n < 0) { ray_vm_unmap_file(buf, file_size); return RAY_ERR_CANCEL; @@ -4222,6 +4191,18 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool int64_t part = 0; size_t chunk_offset = data_offset; bool wrote_any = false; + /* Hold the append domain across partitions. Without this reference each + * save destroys its lookup table and reparses/reindexes the entire growing + * vocabulary on the next partition. */ + ray_sym_domain_t* import_domain = NULL; + for (int c = 0; c < ncols; c++) if (resolved_types[c] == RAY_SYM) { + char sym_path[1024]; + int n = snprintf(sym_path,sizeof(sym_path),"%s/.sym",root); + if (n < 0 || (size_t)n >= sizeof(sym_path)) err = RAY_ERR_RANGE; + else if (!(import_domain = ray_sym_domain_open_or_create(sym_path))) err = RAY_ERR_IO; + break; + } + if (err != RAY_OK) { ray_vm_unmap_file(buf,file_size); return err; } while (chunk_offset < file_size || !wrote_any) { ray_t* row_offsets_hdr = NULL; int64_t* row_offsets = NULL; @@ -4244,7 +4225,7 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool ray_t* tbl = csv_materialize_rows(buf, file_size, row_offsets, cnt, ncols, delimiter, col_name_ids, resolved_types, - NULL); + import_domain); if (!tbl || RAY_IS_ERR(tbl)) { err = (tbl && RAY_IS_ERR(tbl)) ? ray_err_from_obj(tbl) : RAY_ERR_OOM; @@ -4256,6 +4237,21 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool break; } + /* 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); + 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); + if (indexed && RAY_IS_ERR(indexed)) { + err = ray_err_from_obj(indexed); ray_release(indexed); ray_release(col); + break; + } + ray_table_set_col_idx(tbl,c,col); ray_release(col); + } + if (err != RAY_OK) { ray_release(tbl); scratch_free(row_offsets_hdr); break; } + char leaf[1024]; int n = snprintf(leaf, sizeof(leaf), "%s/%" PRId64 "/%s", root, part, table_name); if (n < 0 || (size_t)n >= sizeof(leaf)) { @@ -4278,7 +4274,8 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool err = RAY_ERR_RANGE; break; } - err = ray_splay_save_bulk(tbl, leaf, root_sym); + err = staged ? ray_splay_save_staged_bulk(tbl, leaf, root_sym) + : ray_splay_save_bulk(tbl, leaf, root_sym); ray_release(tbl); scratch_free(row_offsets_hdr); if (err != RAY_OK) { @@ -4293,15 +4290,92 @@ ray_err_t ray_csv_save_parted_named_opts(const char* path, char delimiter, bool part++; } - /* root/.sym is maintained per-partition by ray_splay_save_bulk - * (distinct-merge + flush before each partition's columns) — no - * whole-dictionary dump at the end anymore. */ + /* Staged imports write the growing vocabulary once, after all partitions. + * Existing roots retain the flush-before-column live-write protocol. */ + if (err == RAY_OK && staged && import_domain) + err = ray_sym_domain_flush(import_domain, false); + if (import_domain) ray_sym_domain_release(import_domain); ray_vm_unmap_file(buf, file_size); if (trace) fprintf(stderr, "csv.parted: done err=%s\n", ray_err_code_str(err)); return err; } +/* `root` without trailing separators, and the staging directory a new + * root is imported into. Shared with the builtin so its errors can name + * the directory. Returns RAY_OK or RAY_ERR_RANGE (path too long). */ +ray_err_t ray_csv_parted_paths(const char* root, char* dest, size_t dest_size, + char* staging, size_t staging_size) { + size_t len = strlen(root); + while (len > 1 && (root[len-1] == '/' || root[len-1] == '\\')) len--; + if (len >= dest_size) return RAY_ERR_RANGE; + memcpy(dest,root,len); dest[len] = 0; + int n = snprintf(staging,staging_size,"%s.csv-partial",dest); + if (n < 0 || (size_t)n >= staging_size) return RAY_ERR_RANGE; + return RAY_OK; +} + +ray_err_t ray_csv_save_parted_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* root, const char* table_name, + int64_t rows_per_part) { + if (!path || !root || !*root || !table_name || !*table_name || + table_name[0] == '.' || strchr(table_name,'/') || strchr(table_name,'\\')) + return RAY_ERR_DOMAIN; + if (ray_interrupted()) return RAY_ERR_CANCEL; + char dest[1024], staging[1100]; + ray_err_t perr = ray_csv_parted_paths(root,dest,sizeof(dest),staging,sizeof(staging)); + if (perr != RAY_OK) return perr; + 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); + /* 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. */ + FILE* in = fopen(path,"rb"); + if (!in) return RAY_ERR_IO; + fclose(in); + /* Keep mkdir-p's parent creation, but claim the staging root exclusively. + * A failed import remains available for diagnosis and is never reused. */ + char* slash = strrchr(dest,'/'); + if (slash && slash != dest) { + *slash = 0; + ray_err_t e = ray_mkdir_p(dest); + *slash = '/'; + if (e != RAY_OK) return e; + } +#ifdef RAY_OS_WINDOWS + if (!CreateDirectoryA(staging,NULL)) return RAY_ERR_IO; +#else + 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); + 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 + * does not match, an empty or unreadable source) leaves at most + * the symfile, and keeping that would only block the root. */ + char probe[1200]; + snprintf(probe,sizeof(probe),"%s/0",staging); + if (stat(probe,&st) != 0) { + snprintf(probe,sizeof(probe),"%s/.sym",staging); + remove(probe); +#ifdef RAY_OS_WINDOWS + RemoveDirectoryA(staging); +#else + rmdir(staging); +#endif + } + return err; + } + if (ray_interrupted()) return RAY_ERR_CANCEL; + if (stat(dest,&st) == 0) return RAY_ERR_IO; + return ray_file_rename_new(staging,dest); +} + /* -------------------------------------------------------------------------- * ray_read_csv — convenience wrapper with default options * -------------------------------------------------------------------------- */ diff --git a/src/io/csv.h b/src/io/csv.h index 9b31bdaa1..5b6cc343e 100644 --- a/src/io/csv.h +++ b/src/io/csv.h @@ -74,6 +74,10 @@ ray_t* ray_read_csv_opts(const char* path, char delimiter, bool header, ray_t* ray_read_csv_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); +/* `root` without trailing separators, and the `.csv-partial` staging + * directory a new parted root is imported into. */ +ray_err_t ray_csv_parted_paths(const char* root, char* dest, size_t dest_size, + char* staging, size_t staging_size); ray_err_t ray_csv_save_parted_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, diff --git a/src/io/parquet.c b/src/io/parquet.c new file mode 100644 index 000000000..c9ca37476 --- /dev/null +++ b/src/io/parquet.c @@ -0,0 +1,2446 @@ +/* Copyright (c) 2026 Anton Kundenko. MIT license; see LICENSE. + * Native Parquet reader. Format references (not implementation dependencies): + * parquet.apache.org/docs/file-format, Apache Thrift Compact Protocol, and + * google/snappy format_description.txt. No third-party code or libraries. + */ +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif +#include "parquet.h" +#include "core/platform.h" +#include "core/pool.h" +#include "core/crc32.h" +#include "mem/heap.h" +#include "table/sym.h" +#include "table/domain.h" +#include "vec/str.h" +#include "vec/vec.h" +#include "ops/idxop.h" +#include "ops/hash.h" +#include "ops/glob.h" +#include "ops/agg_registry.h" +#include "store/splay.h" +#include "store/stream.h" +#include "store/col.h" +#include "store/fileio.h" +#include "lang/eval.h" +#include "lang/internal.h" +#include +#include +#include +#include +#include +#ifndef RAY_OS_WINDOWS +#include +#endif +#if defined(__SSE2__) +#include +#endif + +#define PQ_BATCH 65536 +#define PQ_MAX_PART_ROWS 1048576 +#define PQ_MAX_COLS 4096 +#define PQ_MAX_PAGE (64u * 1024u * 1024u) +/* Decoded STR batches: the reader sizes each row group's batches to keep a + * column's string pool near PQ_POOL_TARGET (pq_group_batch); PQ_POOL_MAX is + * the pool's real capacity (32-bit offsets), the backstop when a group's + * metadata underestimates its strings. */ +#define PQ_POOL_TARGET (64u * 1024u * 1024u) +#define PQ_POOL_MAX ((uint64_t)UINT32_MAX) +#define PQ_MAX_FOOTER (64u * 1024u * 1024u) +#define PQ_EPOCH_DAYS 10957 +#define PQ_EPOCH_NS INT64_C(946684800000000000) + +/* A compact-protocol value is a borrowed, bounded span into the mapping. */ +typedef struct { const uint8_t *p, *end; uint8_t type; } pq_span; +typedef struct { const uint8_t *p, *end; bool bad; } pq_cur; +static uint32_t pq_u32(const uint8_t* p) { + return (uint32_t)p[0] | (uint32_t)p[1]<<8 | (uint32_t)p[2]<<16 | (uint32_t)p[3]<<24; +} +static uint64_t pq_u64(const uint8_t* p) { return pq_u32(p) | (uint64_t)pq_u32(p+4)<<32; } +static uint8_t pq_byte(pq_cur* c) { + if (c->p == c->end) { c->bad = true; return 0; } + return *c->p++; +} +static bool pq_take(pq_cur* c, uint64_t n, const uint8_t** out) { + if (n > (uint64_t)(c->end - c->p)) { c->bad = true; return false; } + if (out) *out = c->p; + c->p += (size_t)n; + return true; +} +static uint64_t pq_var(pq_cur* c) { + uint64_t v = 0; + for (unsigned s = 0; s < 64; s += 7) { + uint8_t b = pq_byte(c); + if (c->bad || (s == 63 && b > 1)) { c->bad = true; return 0; } + v |= (uint64_t)(b & 127) << s; + if (!(b & 128)) return v; + } + c->bad = true; return 0; +} +static int64_t pq_int(pq_cur* c) { + uint64_t u = pq_var(c); + return (int64_t)(u >> 1) ^ -(int64_t)(u & 1); +} +static uint64_t pq_list(pq_cur* c, uint8_t* type) { + uint8_t h = pq_byte(c); *type = h & 15; + uint64_t n = h >> 4; + if (n == 15) n = pq_var(c); + /* Every collection element occupies at least one byte. */ + if (!*type || *type > 12 || n > (uint64_t)(c->end-c->p)) c->bad = true; + return n; +} +static bool pq_skip(pq_cur* c, uint8_t t, unsigned depth, bool collection) { + if (depth > 32 || c->bad) { c->bad = true; return false; } + switch (t) { + case 1: case 2: + if (collection) { uint8_t b = pq_byte(c); if (b != 1 && b != 2) c->bad = true; } + break; + case 3: pq_byte(c); break; + case 4: case 5: case 6: pq_var(c); break; + case 7: pq_take(c, 8, NULL); break; + case 8: { uint64_t n = pq_var(c); pq_take(c, n, NULL); break; } + case 9: case 10: { + uint8_t et; uint64_t n = pq_list(c, &et); + for (uint64_t i = 0; i < n && !c->bad; i++) pq_skip(c, et, depth+1, true); + break; + } + case 11: { + uint64_t n = pq_var(c); + if (n > (uint64_t)(c->end-c->p)/2) { c->bad = true; break; } + uint8_t h = n ? pq_byte(c) : 0; + for (uint64_t i = 0; i < n && !c->bad; i++) { + pq_skip(c, h>>4, depth+1, true); pq_skip(c, h&15, depth+1, true); + } + break; + } + case 12: + while (!c->bad) { + uint8_t h = pq_byte(c); + if (!h) break; + if (!(h>>4)) pq_int(c); + pq_skip(c, h&15, depth+1, false); + } + break; + default: c->bad = true; + } + return !c->bad; +} +static bool pq_fields(pq_span s, pq_span* out, size_t n) { + memset(out, 0, n*sizeof(*out)); + if (s.type != 12) return false; + pq_cur c = {s.p, s.end, false}; int64_t id = 0; + while (!c.bad) { + uint8_t h = pq_byte(&c); + if (!h) return !c.bad && c.p == c.end; + id = h>>4 ? id + (h>>4) : pq_int(&c); + if (id <= 0 || id > INT16_MAX) return false; + const uint8_t* p = c.p; + if (!pq_skip(&c, h&15, 0, false)) return false; + if ((uint64_t)id < n) { + if (out[id].type) return false; + out[id] = (pq_span){p, c.p, h&15}; + } + } + return false; +} +static bool pq_num(pq_span s, int64_t* v) { + if (s.type < 4 || s.type > 6) return false; + pq_cur c = {s.p, s.end, false}; *v = pq_int(&c); + return !c.bad && c.p == c.end && + (s.type != 4 || (*v >= INT16_MIN && *v <= INT16_MAX)) && + (s.type != 5 || (*v >= INT32_MIN && *v <= INT32_MAX)); +} +static int64_t pq_get(pq_span s, int64_t fallback) { + int64_t v; return pq_num(s, &v) ? v : fallback; +} +static bool pq_binary(pq_span s, const uint8_t** p, size_t* n) { + if (s.type != 8) return false; + pq_cur c = {s.p, s.end, false}; uint64_t len = pq_var(&c); + if (c.bad || !pq_take(&c, len, p) || c.p != c.end) return false; + *n = (size_t)len; return true; +} +static bool pq_element(pq_cur* c, uint8_t t, pq_span* s) { + const uint8_t* start = c->p; + if (!pq_skip(c, t, 0, true)) return false; + *s = (pq_span){start, c->p, t}; return true; +} +static ray_t* pq_error(const char* msg) { return ray_error("parquet", "%s", msg); } + +bool ray_parquet_snappy(const uint8_t* src, size_t len, uint8_t* dst, size_t size) { + pq_cur c = {src, src+len, false}; uint64_t expected = pq_var(&c); size_t at = 0; + if (c.bad || expected != size) return false; + while (c.p < c.end && at < size) { + uint8_t tag = pq_byte(&c); size_t n, off; + if (!(tag&3)) { + n = tag>>2; + if (n < 60) n++; + else { + unsigned nb = (unsigned)n-59; const uint8_t* p; + if (!pq_take(&c, nb, &p)) return false; + uint32_t x = 0; + for (unsigned i = 0; i < nb; i++) x |= (uint32_t)p[i] << (8*i); + n = (size_t)x+1; + } + const uint8_t* p; + if (n > size-at || !pq_take(&c, n, &p)) return false; + memcpy(dst+at, p, n); at += n; + } else { + if ((tag&3) == 1) { n = 4+((tag>>2)&7); off = ((size_t)(tag&224)<<3) | pq_byte(&c); } + else { + const uint8_t* p; unsigned nb = (tag&3) == 2 ? 2 : 4; + if (!pq_take(&c, nb, &p)) return false; + off = nb == 2 ? (size_t)p[0] | (size_t)p[1]<<8 : pq_u32(p); + n = 1+(tag>>2); + } + if (c.bad || !off || off > at || n > size-at) return false; + /* Copy only initialized, nonoverlapping spans. Small offsets grow + * geometrically, allowing libc's vector copy even for repeats. */ + size_t copied = 0; + while (copied < n) { + size_t step = n-copied < off ? n-copied : off; + memcpy(dst+at+copied,dst+at+copied-off,step); + copied += step; + if (copied >= off) off += off; + } + at += n; + } + } + return !c.bad && at == size && c.p == c.end; +} + +/* Hybrid RLE/bit-packed streams, resumed across batch boundaries. */ +typedef struct { + pq_cur c; + uint64_t left, bit; + const uint8_t* packed; + uint32_t value; + unsigned width; +} pq_rle; +static bool pq_rle_next(pq_rle* r, uint32_t* out) { + if (!r->left) { + uint64_t h = pq_var(&r->c); + if (r->c.bad || !h || r->width > 32) return false; + if (h&1) { + uint64_t groups = h>>1; + if (!groups || groups > INT32_MAX/8) return false; + r->left = groups*8; r->bit = 0; + if (!pq_take(&r->c, groups*r->width, &r->packed)) return false; + } else { + r->left = h>>1; r->packed = NULL; r->value = 0; + if (r->left > INT32_MAX) return false; + for (unsigned i = 0; i < (r->width+7)/8; i++) r->value |= (uint32_t)pq_byte(&r->c)<<(8*i); + if (r->c.bad || (r->width < 32 && r->value >= (UINT32_C(1)<width))) return false; + } + } + if (r->packed) { + uint64_t v = 0; unsigned shift = (unsigned)(r->bit&7); + unsigned nb = (shift+r->width+7)/8; + for (unsigned i = 0; i < nb; i++) v |= (uint64_t)r->packed[r->bit/8+i]<<(8*i); + *out = (uint32_t)((v>>shift) & (r->width == 32 ? UINT32_MAX : (UINT32_C(1)<width)-1)); + r->bit += r->width; + } else *out = r->value; + r->left--; return true; +} +static bool pq_rle_done(const pq_rle* r) { + return !r->c.bad && r->c.p == r->c.end && (!r->left || (r->packed && r->left < 8)); +} + +typedef struct { + int64_t name; + int physical, optional, converted, type; + int64_t scale; /* TIMESTAMP multiplier to ns */ + bool native_symbol, strict; + ray_sym_domain_t* import_domain; /* borrowed from import or scan owner */ +} pq_schema; +typedef struct { const uint8_t* p; uint32_t n; } pq_string; +typedef struct { + const char* strings[8192]; + size_t lengths[8192]; + uint32_t hashes[8192]; + int64_t ids[8192], positions[8192]; +} pq_symbol_scratch; +typedef struct { + pq_span metadata; + pq_cur chunk, values; + pq_rle defs, ids; + uint8_t *page, *dict; + size_t page_cap, dict_cap; + pq_string* strings; + int64_t* symbol_ids; + pq_symbol_scratch* symbols; + int64_t dict_count, page_left, chunk_left, page_nulls, expected_nulls, pages_skipped; + uint64_t bool_bit; + int codec, encoding; + bool have_dict, optional; + bool bool_rle; /* BOOLEAN values RLE-encoded (encoding 3), in `ids` */ +} pq_column; +/* A cursor is used by one decoder at a time. Flush each PLAIN batch before + * advancing pages, so dictionary decoding may reuse the same heap scratch. */ +static pq_symbol_scratch* pq_symbols(pq_column* c) { + if (!c->symbols) c->symbols = ray_alloc_raw(sizeof(*c->symbols)); + return c->symbols; +} +typedef struct { int64_t lo, hi; } pq_interval; +struct ray_parquet { + uint8_t* map; + size_t size, data_end; + pq_schema* schema; + pq_span* groups; + int32_t *selected; + pq_column* cursors; + ray_sym_domain_t* scan_domain; + ray_t* text_pattern; + int64_t text_pos; + int64_t ncols, ngroups, nselected, noutput, rows, group, group_left, batch_rows; + int64_t group_batch; /* batch_rows, capped for this group's STR columns */ + int64_t filter_pos, filter_lo, filter_hi, skipped; + pq_interval* excluded; + int64_t nexcluded, exclude_pos, group_rows, bloom_skipped, parallel_batches; + bool failed, emitted, borrowed, filter_nulls; +}; +static bool pq_reserve(uint8_t** buf, size_t* cap, size_t n) { + if (n > PQ_MAX_PAGE) return false; + if (!n) n = 1; + if (n <= *cap) return true; + size_t nc = *cap ? *cap : 4096; + while (nc < n) nc *= 2; + void* p = ray_realloc_raw(*buf, nc); + if (!p) return false; + *buf = p; *cap = nc; return true; +} +static bool pq_utf8(const uint8_t* p, size_t n) { + for (size_t i = 0; i < n;) { + uint32_t c = p[i++]; unsigned more; uint32_t min; + if (c < 0x80) continue; + if (c >= 0xc2 && c <= 0xdf) { more = 1; min = 0x80; c &= 31; } + else if (c >= 0xe0 && c <= 0xef) { more = 2; min = 0x800; c &= 15; } + else if (c >= 0xf0 && c <= 0xf4) { more = 3; min = 0x10000; c &= 7; } + else return false; + if (more > n-i) return false; + while (more--) { uint8_t b = p[i++]; if ((b&0xc0) != 0x80) return false; c = (c<<6)|(b&63); } + if (c < min || c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff)) return false; + } + return true; +} +static bool pq_schema_type(pq_schema* s, pq_span* f) { + int64_t phys, rep; + if (!pq_num(f[1], &phys) || !pq_num(f[3], &rep) || rep < 0 || rep > 1 || f[5].type) return false; + s->physical = (int)phys; s->optional = (int)rep; + s->converted = (int)pq_get(f[6], -1); s->scale = 1; + switch (phys) { + case 0: s->type = rep ? RAY_I16 : RAY_BOOL; break; + case 1: s->type = RAY_I32; break; + case 2: s->type = RAY_I64; break; + case 4: s->type = RAY_F32; break; + case 5: s->type = RAY_F64; break; + case 6: s->type = RAY_STR; break; + default: return false; + } + int conv = s->converted; + if (f[10].type) { + pq_span logical[20]; + if (!pq_fields(f[10], logical, 20)) return false; + int found = 0; + for (int i = 1; i < 20; i++) if (logical[i].type) { if (found) return false; found = i; } + if (found == 1) conv = 0; + else if (found == 6) conv = 6; + else if (found == 10) { + pq_span ints[3]; int64_t bits; + if (!pq_fields(logical[10], ints, 3) || ints[1].type != 3 || ints[1].end-ints[1].p != 1) return false; + bits = *ints[1].p; + if (bits != 8 && bits != 16 && bits != 32 && bits != 64) return false; + if (ints[2].type != 1 && ints[2].type != 2) return false; + conv = (ints[2].type == 1 ? 15 : 11) + (bits == 8 ? 0 : bits == 16 ? 1 : bits == 32 ? 2 : 3); + } else if (found == 8) { + pq_span ts[3], unit[4]; + if (!pq_fields(logical[8], ts, 3) || (ts[1].type != 1 && ts[1].type != 2) || + !pq_fields(ts[2], unit, 4) || phys != 2) return false; + int units = !!unit[1].type + !!unit[2].type + !!unit[3].type; + if (units != 1) return false; + s->scale = unit[1].type ? 1000000 : unit[2].type ? 1000 : 1; + conv = -2; s->type = RAY_TIMESTAMP; + } else return false; + } + if (conv == 0) { if (phys != 6) return false; } + else if (conv == 6) { if (phys != 1) return false; s->type = RAY_DATE; } + else if (conv == 9 || conv == 10) { + if (phys != 2) return false; + s->type = RAY_TIMESTAMP; s->scale = conv == 9 ? 1000000 : 1000; + } else if (conv >= 11 && conv <= 18) { + if (conv == 14) return false; /* UINT64 has no lossless native counterpart. */ + if (phys != (conv == 18 ? 2 : 1)) return false; + if (conv == 13) s->type = RAY_I64; + else if (conv == 11 || conv == 15) s->type = RAY_I16; + /* I16 annotation stays I32: preserve -32768 without a sentinel collision. */ + } else if (conv != -1 && conv != -2) return false; + s->converted = conv; + return true; +} +void ray_parquet_close(ray_parquet_t* r) { + if (!r) return; + if (r->cursors) for (int64_t i = 0; i < r->nselected; i++) { + ray_free_raw(r->cursors[i].page); ray_free_raw(r->cursors[i].dict); + ray_free_raw(r->cursors[i].strings); ray_free_raw(r->cursors[i].symbol_ids); + ray_free_raw(r->cursors[i].symbols); + } + ray_free_raw(r->cursors); ray_free_raw(r->selected); ray_free_raw(r->excluded); + if (!r->borrowed) { + if (r->scan_domain) ray_sym_domain_release(r->scan_domain); + if (r->text_pattern) ray_release(r->text_pattern); + ray_free_raw(r->schema); ray_free_raw(r->groups); + if (r->map) ray_vm_unmap_file(r->map, r->size); + } + ray_free_raw(r); +} +ray_t* ray_parquet_open(const char* path, ray_t* columns, int64_t batch_rows, ray_parquet_t** out) { + *out = NULL; + if (batch_rows < 1 || batch_rows > PQ_BATCH) return pq_error("batch size must be 1..65536"); + if (columns && (columns->type != RAY_SYM || !columns->len)) return pq_error("columns must be a nonempty symbol vector"); + ray_parquet_t* r = ray_calloc_raw(sizeof(*r)); + if (!r) return ray_error("oom", NULL); + const char* err = "invalid Parquet footer"; + r->batch_rows = batch_rows; r->group = -1; r->filter_pos = -1; + r->map = ray_vm_map_file(path, &r->size); + if (!r->map) { ray_parquet_close(r); return ray_error("io", "parquet: cannot map %s", path); } + if (r->size < 12 || memcmp(r->map, "PAR1", 4) || memcmp(r->map+r->size-4, "PAR1", 4)) goto fail; + uint32_t flen = pq_u32(r->map+r->size-8); + if (flen > r->size-12 || flen > PQ_MAX_FOOTER) goto fail; + r->data_end = r->size-8-flen; + pq_span f[10]; + if (!pq_fields((pq_span){r->map+r->data_end,r->map+r->size-8,12}, f, 10) || + pq_get(f[1], -1) < 1 || !pq_num(f[3], &r->rows) || r->rows < 0 || f[2].type != 9 || f[4].type != 9 || f[8].type || f[9].type) goto fail; + pq_cur sc = {f[2].p,f[2].end,false}; uint8_t st; + uint64_t ns = pq_list(&sc, &st); + if (sc.bad || st != 12 || ns < 2 || ns > PQ_MAX_COLS+1) goto fail; + r->ncols = (int64_t)ns-1; + r->schema = ray_calloc_raw((size_t)r->ncols*sizeof(*r->schema)); + if (!r->schema) { err = "schema allocation failed"; goto fail; } + pq_span root, sf[11]; + if (!pq_element(&sc, 12, &root) || !pq_fields(root,sf,11) || pq_get(sf[5],-1) != r->ncols || sf[1].type) goto fail; + err = "unsupported or malformed schema (only flat primitive columns are supported)"; + for (int64_t i = 0; i < r->ncols; i++) { + pq_span se; const uint8_t* name; size_t len; + if (!pq_element(&sc,12,&se) || !pq_fields(se,sf,11) || !pq_binary(sf[4],&name,&len) || + !len || len > 1024 || memchr(name,0,len) || !pq_schema_type(&r->schema[i],sf)) goto fail; + r->schema[i].name = ray_sym_intern((const char*)name,len); + if (r->schema[i].name < 0) goto fail; + for (int64_t j = 0; j < i; j++) if (r->schema[j].name == r->schema[i].name) goto fail; + } + if (sc.p != sc.end) goto fail; + pq_cur gc = {f[4].p,f[4].end,false}; uint8_t gt; + uint64_t ng = pq_list(&gc,>); + if (gc.bad || gt != 12 || ng > PQ_MAX_FOOTER/sizeof(pq_span)) goto fail; + r->ngroups = (int64_t)ng; + r->groups = ray_calloc_raw((size_t)(ng ? ng : 1)*sizeof(*r->groups)); + if (!r->groups) goto fail; + int64_t total = 0; + err = "invalid row group metadata"; + for (uint64_t i = 0; i < ng; i++) { + pq_span gf[8]; int64_t nr; + if (!pq_element(&gc,12,&r->groups[i]) || !pq_fields(r->groups[i],gf,8) || + !pq_num(gf[3],&nr) || nr < 0 || nr > r->rows-total || gf[1].type != 9) goto fail; + pq_cur chunks = {gf[1].p,gf[1].end,false}; uint8_t chunk_type; + if (pq_list(&chunks,&chunk_type) != (uint64_t)r->ncols || chunks.bad || chunk_type != 12) goto fail; + total += nr; + } + if (gc.p != gc.end || total != r->rows) goto fail; + r->nselected = columns ? columns->len : r->ncols; + r->noutput = r->nselected; + if (r->nselected > r->ncols) goto fail; + r->selected = ray_alloc_raw((size_t)r->ncols*sizeof(*r->selected)); + r->cursors = ray_calloc_raw((size_t)r->ncols*sizeof(*r->cursors)); + if (!r->selected || !r->cursors) goto fail; + err = "unknown or duplicate projection column"; + for (int64_t i = 0; i < r->nselected; i++) { + ray_t* cs = columns ? ray_sym_vec_cell(columns,i) : NULL; + int64_t name = columns ? (cs ? ray_sym_find(ray_str_ptr(cs),ray_str_len(cs)) : -1) : r->schema[i].name; + int64_t j = 0; + while (j < r->ncols && r->schema[j].name != name) j++; + if (j == r->ncols) goto fail; + for (int64_t k = 0; k < i; k++) if (r->selected[k] == j) goto fail; + r->selected[i] = (int32_t)j; + } + *out = r; return NULL; +fail: + ray_parquet_close(r); return pq_error(err); +} + +ray_t* ray_parquet_range(ray_parquet_t* r, int64_t column, int64_t lo, int64_t hi) { + if (!r || r->group != -1 || r->emitted || r->filter_pos >= 0 || lo > hi) + return pq_error("range must be configured once before scanning, with lo <= hi"); + int64_t c = 0; + while (c < r->ncols && r->schema[c].name != column) c++; + if (c == r->ncols) return pq_error("unknown range column"); + pq_schema* s = &r->schema[c]; + if ((s->type != RAY_I16 && s->type != RAY_I32 && s->type != RAY_I64) || + (s->converted != -1 && (s->converted < 15 || s->converted > 18))) + return pq_error("range requires a signed integer column"); + int64_t pos = 0; + while (pos < r->nselected && r->selected[pos] != c) pos++; + if (pos == r->nselected) r->selected[r->nselected++] = (int32_t)c; + r->filter_pos = pos; r->filter_lo = lo; r->filter_hi = hi; + return NULL; +} +int64_t ray_parquet_groups_skipped(const ray_parquet_t* r) { return r ? r->skipped : 0; } + +static bool pq_disjoint(ray_parquet_t* r, pq_span metadata) { + pq_span mf[17], stats[10]; + if (!pq_fields(metadata,mf,17) || !pq_fields(mf[12],stats,10)) return false; + const uint8_t *minp, *maxp; size_t minn, maxn; + /* Legacy bounds have signed ordering. Modern bounds for the eligible + * signed integer types have the same ordering. Missing bounds => scan. */ + pq_span low = stats[6].type ? stats[6] : stats[2]; + pq_span high = stats[5].type ? stats[5] : stats[1]; + if (!pq_binary(low,&minp,&minn) || !pq_binary(high,&maxp,&maxn)) return false; + int physical = r->schema[r->selected[r->filter_pos]].physical; + size_t width = physical == 1 ? 4 : 8; + if (minn != width || maxn != width) return false; + int64_t lo = width == 4 ? (int32_t)pq_u32(minp) : (int64_t)pq_u64(minp); + int64_t hi = width == 4 ? (int32_t)pq_u32(maxp) : (int64_t)pq_u64(maxp); + return lo <= hi && (hi < r->filter_lo || lo > r->filter_hi); +} + +/* Optional metadata is advisory: unsupported or malformed indexes never + * exclude rows. Only the signed integer ordering admitted by range() is used. */ +static bool pq_bounds_disjoint(ray_parquet_t* r, pq_span low, pq_span high) { + const uint8_t *a, *b; size_t an, bn; + size_t width = r->schema[r->selected[r->filter_pos]].physical == 1 ? 4 : 8; + if (!pq_binary(low,&a,&an) || !pq_binary(high,&b,&bn) || an != width || bn != width) return false; + int64_t lo = width == 4 ? (int32_t)pq_u32(a) : (int64_t)pq_u64(a); + int64_t hi = width == 4 ? (int32_t)pq_u32(b) : (int64_t)pq_u64(b); + return lo <= hi && (hi < r->filter_lo || lo > r->filter_hi); +} +static bool pq_index_span(ray_parquet_t* r, pq_span off, pq_span len, pq_span* out) { + int64_t o, n; + if (!pq_num(off,&o) || !pq_num(len,&n) || o < 4 || n <= 0 || n > PQ_MAX_FOOTER || + (uint64_t)o > r->data_end || (uint64_t)n > r->data_end-(size_t)o) return false; + *out = (pq_span){r->map+o,r->map+o+n,12}; return true; +} +/* XXH64, seed zero, specialized to the 4/8 byte PLAIN integer encodings. + * Derived from the public algorithm specification; no library implementation. */ +static uint64_t pq_rot(uint64_t x, unsigned n) { return (x<>(64-n)); } +static uint64_t pq_integer_hash(uint64_t x, unsigned width) { + const uint64_t p1 = UINT64_C(11400714785074694791), p2 = UINT64_C(14029467366897019727); + const uint64_t p3 = UINT64_C(1609587929392839161), p4 = UINT64_C(9650029242287828579); + uint64_t h = UINT64_C(2870177450012600261)+width; + if (width == 8) { h ^= pq_rot(x*p2,31)*p1; h = pq_rot(h,27)*p1+p4; } + else { h ^= (uint64_t)(uint32_t)x*p1; h = pq_rot(h,23)*p2+p3; } + h ^= h>>33; h *= p2; h ^= h>>29; h *= p3; return h ^ (h>>32); +} +static bool pq_bloom_absent(ray_parquet_t* r, pq_span metadata) { + if (r->filter_lo != r->filter_hi) return false; + pq_span m[17], f[5]; int64_t offset; + if (!pq_fields(metadata,m,17) || !pq_num(m[14],&offset) || offset < 4 || + (uint64_t)offset >= r->data_end) return false; + size_t avail = r->data_end-(size_t)offset; + if (avail > PQ_MAX_PAGE+1024) avail = PQ_MAX_PAGE+1024; + int64_t length; + if (m[15].type) { + if (!pq_num(m[15],&length) || length <= 0 || (uint64_t)length > avail) return false; + avail = (size_t)length; + } + pq_cur c = {r->map+offset,r->map+offset+avail,false}; + const uint8_t* start = c.p; + if (!pq_skip(&c,12,0,false) || !pq_fields((pq_span){start,c.p,12},f,5)) return false; + int64_t n = pq_get(f[1],-1); + if (n < 32 || n > PQ_MAX_PAGE || n%32 || (uint64_t)n > (uint64_t)(c.end-c.p)) return false; + if (m[15].type && n != c.end-c.p) return false; + /* Each supported union is exactly {1: empty struct}. Unknown variants + * (including future compression/hash strategies) require a normal scan. */ + for (int i = 2; i <= 4; i++) { + static const uint8_t supported[] = {0x1c,0,0}; + if (f[i].type != 12 || f[i].end-f[i].p != 3 || memcmp(f[i].p,supported,3)) return false; + } + unsigned width = r->schema[r->selected[r->filter_pos]].physical == 1 ? 4 : 8; + if (width == 4 && (r->filter_lo < INT32_MIN || r->filter_lo > INT32_MAX)) return true; + uint64_t h = pq_integer_hash((uint64_t)r->filter_lo,width); + const uint8_t* block = c.p+(((h>>32)*(uint64_t)(n/32))>>32)*32; + static const uint32_t salt[8] = {0x47b6137b,0x44974d91,0x8824ad5b,0xa2b7289d,0x705495c7,0x2df1424b,0x9efc4947,0x5c6bfb31}; + for (int i = 0; i < 8; i++) + if (!(pq_u32(block+4*i) & (UINT32_C(1)<<(((uint32_t)h*salt[i])>>27)))) return true; + return false; +} +static void pq_page_intervals(ray_parquet_t* r, pq_span chunk) { + pq_span cf[10], os, cs, of[3], f[9]; + if (!r->group_rows || !pq_fields(chunk,cf,10) || + !pq_index_span(r,cf[4],cf[5],&os) || !pq_index_span(r,cf[6],cf[7],&cs) || + !pq_fields(os,of,3) || !pq_fields(cs,f,9) || of[1].type != 9 || + f[1].type != 9 || f[2].type != 9 || f[3].type != 9 || pq_get(f[4],-1) < 0 || pq_get(f[4],3) > 2) return; + pq_cur loc = {of[1].p,of[1].end,false}, nulls = {f[1].p,f[1].end,false}; + pq_cur min = {f[2].p,f[2].end,false}, max = {f[3].p,f[3].end,false}; + uint8_t lt, nt, at, bt; + uint64_t n = pq_list(&loc,<), nn = pq_list(&nulls,&nt), na = pq_list(&min,&at), nb = pq_list(&max,&bt); + if (loc.bad || nulls.bad || min.bad || max.bad || !n || n > PQ_MAX_FOOTER/sizeof(pq_interval) || + n != nn || n != na || n != nb || lt != 12 || nt != 1 || at != 8 || bt != 8) return; + pq_interval* ranges = ray_alloc_raw((size_t)n*sizeof(*ranges)); + if (!ranges) return; /* Optional optimization. */ + int64_t expected_row = 0, nranges = 0; + const pq_column* col = &r->cursors[r->filter_pos]; + const uint8_t* expected_page = NULL; + for (uint64_t i = 0; i < n; i++) { + pq_span ls, lf[4], low, high, hf[10], dh[9]; + if (!pq_element(&loc,12,&ls) || !pq_fields(ls,lf,4) || + !pq_element(&min,8,&low) || !pq_element(&max,8,&high)) goto invalid; + uint8_t isnull = pq_byte(&nulls); + int64_t off = pq_get(lf[1],-1), bytes = pq_get(lf[2],-1), row = pq_get(lf[3],-1); + if ((isnull != 1 && isnull != 2) || row != expected_row || off < 4 || bytes <= 0 || + (uint64_t)off > r->data_end || (uint64_t)bytes > r->data_end-(size_t)off) goto invalid; + const uint8_t* p = r->map+off; + if (p < col->chunk.p || p+bytes > col->chunk.end || (expected_page && p != expected_page)) goto invalid; + if (!i) { + pq_span mf[17]; + if (!pq_fields(col->metadata,mf,17) || off != pq_get(mf[9],-1)) goto invalid; + } + pq_cur page = {p,p+bytes,false}; + if (!pq_skip(&page,12,0,false) || !pq_fields((pq_span){p,page.p,12},hf,10)) goto invalid; + int64_t kind = pq_get(hf[1],-1), count; + if ((kind != 0 && kind != 3) || pq_get(hf[3],-1) != page.end-page.p || + !pq_fields(hf[kind == 0 ? 5 : 8],dh,9) || !pq_num(dh[1],&count) || count <= 0 || + count > r->group_rows-row) goto invalid; + expected_row += count; expected_page = page.end; + if (isnull == 1 || pq_bounds_disjoint(r,low,high)) { + if (nranges && ranges[nranges-1].hi == row) ranges[nranges-1].hi += count; + else ranges[nranges++] = (pq_interval){row,row+count}; + } + } + if (expected_row != r->group_rows || expected_page != col->chunk.end || loc.p != loc.end || + nulls.bad || nulls.p != nulls.end || min.p != min.end || max.p != max.end) goto invalid; + r->excluded = ranges; r->nexcluded = nranges; return; +invalid: + ray_free_raw(ranges); +} + +static bool pq_group_columns(ray_parquet_t* r, int64_t g, pq_span* cols, int64_t* rows, pq_span* filter_chunk) { + pq_span gf[8]; + if (!pq_fields(r->groups[g],gf,8) || !pq_num(gf[3],rows) || gf[1].type != 9) return false; + pq_cur c = {gf[1].p,gf[1].end,false}; uint8_t type; + if (pq_list(&c,&type) != (uint64_t)r->ncols || c.bad || type != 12) return false; + for (int64_t i = 0; i < r->ncols; i++) { + pq_span ch, cf[10], mf[17]; + if (!pq_element(&c,12,&ch) || !pq_fields(ch,cf,10) || cf[1].type || cf[8].type || cf[9].type || + !pq_fields(cf[3],mf,17) || pq_get(mf[1],-1) != r->schema[i].physical || + pq_get(mf[5],-1) != *rows || mf[3].type != 9) return false; + pq_cur path = {mf[3].p,mf[3].end,false}; uint8_t pt; pq_span ps; const uint8_t* p; size_t n; + if (pq_list(&path,&pt) != 1 || pt != 8 || !pq_element(&path,pt,&ps) || + !pq_binary(ps,&p,&n) || path.p != path.end) return false; + const char* name = ray_str_ptr(ray_sym_str(r->schema[i].name)); + if (!name || strlen(name) != n || memcmp(name,p,n)) return false; + cols[i] = cf[3]; + if (filter_chunk && i == r->selected[r->filter_pos]) *filter_chunk = ch; + } + return c.p == c.end; +} +/* Longest entry in a BYTE_ARRAY column chunk's dictionary page, 0 when it + * has none (or it cannot be read here; the decoder reports that later). + * Every dictionary-encoded row copies one entry into the batch pool, and + * the chunk's uncompressed size (dictionary + indices) says nothing about + * how many times a long entry repeats. */ +static int64_t pq_dict_max_len(ray_parquet_t* r, pq_span meta) { + pq_span mf[17]; + if (!pq_fields(meta,mf,17)) return 0; + int64_t dict = pq_get(mf[11],-1), codec = pq_get(mf[4],-1); + if (dict < 4 || (uint64_t)dict >= r->data_end) return 0; + pq_cur c = {r->map+dict,r->map+r->data_end,false}; + const uint8_t* start = c.p; + if (!pq_skip(&c,12,0,false)) return 0; + pq_span f[10]; + if (!pq_fields((pq_span){start,c.p,12},f,10) || pq_get(f[1],-1) != 2) return 0; + int64_t raw = pq_get(f[2],-1), size = pq_get(f[3],-1); + if (raw < 0 || raw > PQ_MAX_PAGE || size < 0 || size > PQ_MAX_PAGE || + (uint64_t)size > (uint64_t)(c.end-c.p)) return 0; + const uint8_t* p = c.p; uint8_t* buf = NULL; + if (codec == 1) { + buf = ray_alloc_raw((size_t)(raw ? raw : 1)); + if (!buf || !ray_parquet_snappy(c.p,(size_t)size,buf,(size_t)raw)) { ray_free_raw(buf); return 0; } + p = buf; + } else if (raw != size) return 0; + int64_t max = 0; + for (const uint8_t* q = p, *end = p+raw; end-q >= 4; ) { + uint32_t len = pq_u32(q); q += 4; + if (len > (uint64_t)(end-q)) break; + if ((int64_t)len > max) max = len; + q += len; + } + ray_free_raw(buf); + return max; +} + +/* Rows per batch for row group g: batch_rows, lowered so each selected STR + * column's pool stays near PQ_POOL_TARGET. Bytes per row are bounded by + * the larger of the chunk's uncompressed bytes per value (PLAIN pages hold + * every value's bytes; a 4 MB file of 11 KB documents decodes 86 MB of + * strings, and one fixed 65,536-row batch would hold all of it) and the + * longest dictionary entry (dictionary pages; each row may repeat it). + * PQ_POOL_MAX remains the hard limit. Deterministic from the file, so the + * partitioned writer can count partitions with it before decoding. */ +static int64_t pq_group_batch(ray_parquet_t* r, int64_t g) { + int64_t batch = r->batch_rows, rows; + pq_span* cols = ray_alloc_raw((size_t)r->ncols*sizeof(*cols)); + if (!cols) return batch; + if (pq_group_columns(r,g,cols,&rows,NULL)) { + for (int64_t i = 0; i < r->nselected; i++) { + const pq_schema* sc = &r->schema[r->selected[i]]; + if (sc->physical != 6 || sc->type != RAY_STR || sc->import_domain) continue; + pq_span mf[17]; + if (!pq_fields(cols[r->selected[i]],mf,17)) continue; + int64_t values = pq_get(mf[5],-1), bytes = pq_get(mf[6],-1); + if (values <= 0 || bytes <= 0) continue; + int64_t per_row = bytes/values + 1; + int64_t longest = pq_dict_max_len(r,cols[r->selected[i]]) + 1; + if (longest > per_row) per_row = longest; + int64_t cap = (int64_t)PQ_POOL_TARGET/per_row; + if (cap < 1) cap = 1; + if (cap < batch) batch = cap; + } + } + ray_free_raw(cols); + return batch; +} +static const char* pq_start_group(ray_parquet_t* r) { + pq_span* cols = ray_alloc_raw((size_t)r->ncols*sizeof(*cols)); + if (!cols) return "row group allocation failed"; + pq_span filter_chunk = {0}; + ray_free_raw(r->excluded); r->excluded = NULL; r->nexcluded = r->exclude_pos = 0; + if (!pq_group_columns(r,r->group,cols,&r->group_left,r->filter_pos >= 0 ? &filter_chunk : NULL)) { ray_free_raw(cols); return "invalid column chunk metadata"; } + /* A zero-row group has nothing to decode. Writers still emit its + * chunks, with a dictionary page and data_page_offset 0, which the + * chunk checks below would reject. */ + if (r->group_left == 0) { ray_free_raw(cols); return NULL; } + r->group_batch = pq_group_batch(r,r->group); + /* Bounds and Bloom filters describe non-null values. A WHERE accepting + * nulls must decode these groups/pages, including native null sentinels + * in required columns. Explicit read ranges still exclude nulls. */ + if (r->filter_pos >= 0 && !r->filter_nulls && pq_disjoint(r,cols[r->selected[r->filter_pos]])) { + r->group_left = 0; r->skipped++; ray_free_raw(cols); return NULL; + } + if (r->filter_pos >= 0 && !r->filter_nulls && pq_bloom_absent(r,cols[r->selected[r->filter_pos]])) { + r->group_left = 0; r->skipped++; r->bloom_skipped++; ray_free_raw(cols); return NULL; + } + r->group_rows = r->group_left; + const char* err = NULL; + for (int64_t i = 0; i < r->nselected; i++) { + pq_column* c = &r->cursors[i]; pq_span mf[17]; + c->metadata = cols[r->selected[i]]; + if (!pq_fields(c->metadata,mf,17)) { err = "invalid column metadata"; break; } + int64_t offset = pq_get(mf[9],-1), dict = pq_get(mf[11],-1), bytes = pq_get(mf[7],-1); + int64_t codec = pq_get(mf[4],-1); + if (codec != 0 && codec != 1) { err = "unsupported compression codec (supported: uncompressed, Snappy)"; break; } + if (dict >= 0) { if (dict > offset) { err = "dictionary follows data"; break; } offset = dict; } + if (offset < 4 || bytes < 0 || (uint64_t)offset > r->data_end || (uint64_t)bytes > r->data_end-(size_t)offset) { + err = "column chunk outside file data"; break; + } + c->chunk = (pq_cur){r->map+offset,r->map+offset+bytes,false}; + c->codec = (int)codec; c->page_left = 0; c->chunk_left = r->group_left; + c->have_dict = false; c->dict_count = 0; c->optional = r->schema[r->selected[i]].optional; + ray_free_raw(c->strings); c->strings = NULL; + ray_free_raw(c->symbol_ids); c->symbol_ids = NULL; + } + if (!err && r->filter_pos >= 0 && !r->filter_nulls) pq_page_intervals(r,filter_chunk); + ray_free_raw(cols); return err; +} +static bool pq_unpack(pq_column* c, const uint8_t* p, size_t n, size_t decoded, bool compressed, const uint8_t** out) { + if (decoded > PQ_MAX_PAGE) return false; + if (!compressed || !c->codec) { if (n != decoded) return false; *out = p; return true; } + if (!pq_reserve(&c->page,&c->page_cap,decoded)) return false; + if (!ray_parquet_snappy(p,n,c->page,decoded)) return false; + *out = c->page; return true; +} +static bool pq_dictionary(pq_column* c, pq_schema* s, const uint8_t* data, size_t n, int64_t count) { + if (c->have_dict || count < 0 || (uint64_t)count > PQ_MAX_PAGE/sizeof(pq_string)) return false; + if (!pq_reserve(&c->dict,&c->dict_cap,n)) return false; + if (n) memcpy(c->dict,data,n); + c->dict_count = count; c->have_dict = true; + if (s->physical == 6) { + c->strings = ray_calloc_raw((size_t)(count ? count : 1)*sizeof(*c->strings)); + if (!c->strings) return false; + pq_cur p = {c->dict,c->dict+n,false}; + for (int64_t i = 0; i < count; i++) { + const uint8_t* len; const uint8_t* str; + if (!pq_take(&p,4,&len)) return false; + uint32_t size = pq_u32(len); + if (!pq_take(&p,size,&str)) return false; + if (s->strict && s->converted == 0 && !pq_utf8(str,size)) return false; + c->strings[i] = (pq_string){str,size}; + } + if (p.p != p.end) return false; + if (s->import_domain) { + c->symbol_ids = ray_alloc_raw((size_t)(count ? count : 1)*sizeof(*c->symbol_ids)); + if (!c->symbol_ids) return false; + pq_symbol_scratch* scratch = pq_symbols(c); + if (!scratch) return false; + const char** strings = scratch->strings; size_t* lengths = scratch->lengths; + uint32_t* hashes = scratch->hashes; + for (int64_t off = 0; off < count; off += 8192) { + int64_t n = count-off < 8192 ? count-off : 8192; + for (int64_t i = 0; i < n; i++) { + strings[i] = (const char*)c->strings[off+i].p; lengths[i] = c->strings[off+i].n; + hashes[i] = (uint32_t)ray_hash_bytes(strings[i],lengths[i]); + } + if (!ray_sym_domain_intern_batch(s->import_domain,n,strings,lengths,hashes,c->symbol_ids+off)) return false; + } + } + return true; + } + size_t width = s->physical == 1 || s->physical == 4 ? 4 : 8; + return s->physical != 0 && (uint64_t)count*width == n; +} +static const char* pq_page(pq_column* c, pq_schema* s, int64_t* skip) { + while (c->chunk.p < c->chunk.end) { + const uint8_t* start = c->chunk.p; + if (!pq_skip(&c->chunk,12,0,false)) return "invalid page header"; + pq_span f[10]; + if (!pq_fields((pq_span){start,c->chunk.p,12},f,10)) return "invalid page fields"; + int64_t kind = pq_get(f[1],-1), raw = pq_get(f[2],-1), size = pq_get(f[3],-1); + if (raw < 0 || raw > PQ_MAX_PAGE || size < 0 || size > PQ_MAX_PAGE) return "invalid or oversized page (limit 64 MiB)"; + const uint8_t* payload; + if (!pq_take(&c->chunk,(uint64_t)size,&payload)) return "truncated page"; + if (skip && (kind == 0 || kind == 3)) { + pq_span h[9]; int64_t count; + if (!pq_fields(f[kind == 0 ? 5 : 8],h,9) || !pq_num(h[1],&count) || + count <= 0 || count > c->chunk_left) return "invalid skipped page row count"; + if (count <= *skip) { + *skip -= count; c->chunk_left -= count; c->pages_skipped++; + if (!c->chunk_left && c->chunk.p != c->chunk.end) return "excess column pages"; + if (!*skip) return NULL; + continue; + } + } + if (f[4].type) { + int64_t expected; + if (!pq_num(f[4],&expected)) return "invalid page checksum"; + /* Ordinary CRC-32 over the compressed page body. */ + if (ray_crc32(0,payload,(size_t)size) != (uint32_t)expected) return "page checksum mismatch"; + } + if (kind == 1) continue; /* legacy index page */ + const uint8_t* data = NULL; pq_span h[9]; int64_t count, encoding; + c->bool_bit = 0; c->bool_rle = false; c->page_nulls = 0; c->expected_nulls = -1; + if (kind == 2) { + if (!pq_fields(f[7],h,9) || !pq_num(h[1],&count) || + (pq_get(h[2],-1) != 0 && pq_get(h[2],-1) != 2) || + !pq_unpack(c,payload,(size_t)size,(size_t)raw,true,&data) || + !pq_dictionary(c,s,data,(size_t)raw,count)) return "invalid dictionary page"; + continue; + } + if (kind == 0) { + if (!pq_fields(f[5],h,9) || !pq_num(h[1],&count) || !pq_num(h[2],&encoding) || + (c->optional && pq_get(h[3],-1) != 3) || + !pq_unpack(c,payload,(size_t)size,(size_t)raw,true,&data)) return "invalid v1 data page"; + c->values = (pq_cur){data,data+raw,false}; + if (c->optional) { + const uint8_t* p; const uint8_t* levels; + if (!pq_take(&c->values,4,&p) || !pq_take(&c->values,pq_u32(p),&levels)) return "truncated definition levels"; + c->defs = (pq_rle){.c={levels,c->values.p,false},.width=1}; + } + } else if (kind == 3) { + int64_t dl, rl, nulls, nr; + if (!pq_fields(f[8],h,9) || !pq_num(h[1],&count) || !pq_num(h[2],&nulls) || + !pq_num(h[3],&nr) || nr != count || nulls < 0 || nulls > count || + (!c->optional && nulls) || !pq_num(h[4],&encoding) || !pq_num(h[5],&dl) || + !pq_num(h[6],&rl) || dl < 0 || rl != 0 || dl > size || dl > raw || + (!c->optional && dl) || (h[7].type && h[7].type != 1 && h[7].type != 2)) return "invalid v2 data page"; + c->defs = (pq_rle){.c={payload,payload+dl,false},.width=1}; + if (!pq_unpack(c,payload+dl,(size_t)(size-dl),(size_t)(raw-dl),h[7].type != 2,&data)) return "invalid v2 compressed values"; + c->values = (pq_cur){data,data+raw-dl,false}; + c->expected_nulls = nulls; + } else return "unsupported page type"; + if (count <= 0 || count > c->chunk_left) return "invalid page row count"; + if (encoding == 3 && s->physical == 0) { + /* RLE booleans (the v2 default of common writers): a 4-byte + * little-endian length, then a bit-width-1 hybrid stream. */ + const uint8_t* lp; const uint8_t* body; + if (!pq_take(&c->values,4,&lp) || !pq_take(&c->values,pq_u32(lp),&body) || + c->values.p != c->values.end) return "invalid RLE boolean data"; + c->ids = (pq_rle){.c={body,c->values.end,false},.width=1}; + c->bool_rle = true; c->encoding = 0; c->page_left = count; + return NULL; + } + if (encoding != 0 && encoding != 2 && encoding != 8) return "unsupported value encoding (supported: plain, dictionary, RLE booleans)"; + c->encoding = (int)encoding; c->page_left = count; + if (encoding) { + if (!c->have_dict || s->physical == 0) return "missing or invalid dictionary"; + unsigned width = pq_byte(&c->values); + if (c->values.bad || width > 32) return "invalid dictionary bit width"; + c->ids = (pq_rle){.c=c->values,.width=width}; + } + return NULL; + } + return "missing data page"; +} + +#define PQ_PUT_FAIL "value conversion or allocation failed" +/* Convert one value into row `row`; NULL, or the reason it failed. */ +static const char* pq_put_value(ray_t** vp, int64_t row, pq_schema* s, const uint8_t* p, uint32_t len) { + ray_t* v = *vp; + switch (s->physical) { + case 0: + if (v->type == RAY_BOOL) ((uint8_t*)ray_data(v))[row] = *p; + else ((int16_t*)ray_data(v))[row] = *p; + break; + case 1: case 2: { + int64_t x = s->physical == 1 ? (int32_t)pq_u32(p) : (int64_t)pq_u64(p); + if (s->physical == 1 && s->converted >= 11 && s->converted <= 13) x = pq_u32(p); + if ((s->converted == 11 && x > UINT8_MAX) || + (s->converted == 12 && x > UINT16_MAX) || + (s->converted == 15 && (x < INT8_MIN || x > INT8_MAX)) || + (s->converted == 16 && (x < INT16_MIN || x > INT16_MAX))) return PQ_PUT_FAIL; + if (s->type == RAY_DATE && __builtin_sub_overflow(x,PQ_EPOCH_DAYS,&x)) return PQ_PUT_FAIL; + int64_t raw = x; + if (s->type == RAY_TIMESTAMP && + (__builtin_sub_overflow(x,PQ_EPOCH_NS/s->scale,&x) || __builtin_mul_overflow(x,s->scale,&x))) { + /* Outside the native nanosecond range, e.g. a 9999-12-31 "end + * of time" sentinel at ms precision. Clamp to the nearest + * representable instant so comparisons keep their meaning (a + * null would sort below every timestamp and read as expired); + * strict mode rejects the value instead. */ + if (s->strict) return "timestamp outside the native nanosecond range (strict mode)"; + x = raw >= PQ_EPOCH_NS/s->scale ? INT64_MAX : INT64_MIN+1; + } + if (s->type == RAY_I16) { + if (x < INT16_MIN || x > INT16_MAX) return PQ_PUT_FAIL; + ((int16_t*)ray_data(v))[row] = (int16_t)x; + } else if (s->type == RAY_I64 || s->type == RAY_TIMESTAMP) ((int64_t*)ray_data(v))[row] = x; + else { + if (x < INT32_MIN || x > INT32_MAX) return PQ_PUT_FAIL; + ((int32_t*)ray_data(v))[row] = (int32_t)x; + } + break; + } + case 4: { uint32_t u = pq_u32(p); memcpy((float*)ray_data(v)+row,&u,4); break; } + case 5: { uint64_t u = pq_u64(p); memcpy((double*)ray_data(v)+row,&u,8); break; } + case 6: { + if (s->strict && s->converted == 0 && !pq_utf8(p,len)) return PQ_PUT_FAIL; + ray_t* next = ray_str_vec_set(v,row,(const char*)p,len); + if (!next || RAY_IS_ERR(next)) { if (next) ray_release(next); return PQ_PUT_FAIL; } + *vp = v = next; break; + } + default: return PQ_PUT_FAIL; + } + uint8_t attrs = v->attrs; + v->attrs |= RAY_ATTR_HAS_NULLS; + if (!ray_vec_is_null(v,row)) v->attrs = attrs; + else if (s->strict) return PQ_PUT_FAIL; + return NULL; +} +/* PLAIN signed integers can go straight into native blocks. SSE2 handles + * copy and sentinel detection together; scalar code also handles big endian. */ +static void pq_plain_int(ray_t* v, int64_t row, const uint8_t* p, int64_t n) { + int64_t i = 0; + size_t width = v->type == RAY_I32 ? 4 : 8; + uint8_t* dst = (uint8_t*)ray_data(v)+(size_t)row*width; +#if defined(__SSE2__) + __m128i sentinel = width == 4 ? _mm_set1_epi32(INT32_MIN) : _mm_set_epi32(INT32_MIN,0,INT32_MIN,0); + for (; i+16/(int64_t)width <= n; i += 16/(int64_t)width) { + __m128i x = _mm_loadu_si128((const __m128i*)(p+(size_t)i*width)); + _mm_storeu_si128((__m128i*)(dst+(size_t)i*width),x); + int mask = _mm_movemask_epi8(_mm_cmpeq_epi32(x,sentinel)); + if ((width == 4 && mask) || (width == 8 && ((mask&255) == 255 || (mask>>8) == 255))) + v->attrs |= RAY_ATTR_HAS_NULLS; + } +#endif + for (; i < n; i++) { + if (width == 4) { + int32_t x = (int32_t)pq_u32(p+(size_t)i*4); memcpy(dst+(size_t)i*4,&x,4); + if (x == INT32_MIN) v->attrs |= RAY_ATTR_HAS_NULLS; + } else { + int64_t x = (int64_t)pq_u64(p+(size_t)i*8); memcpy(dst+(size_t)i*8,&x,8); + if (x == INT64_MIN) v->attrs |= RAY_ATTR_HAS_NULLS; + } + } +} +/* Native dictionary ids go directly to file-domain symbol positions. PLAIN + * pages intern bounded batches before their decompression buffer is reused. */ +static const char* pq_decode_symbols(pq_column* c, pq_schema* s, ray_t** out, int64_t rows) { + pq_symbol_scratch* scratch = pq_symbols(c); + if (!scratch) return "symbol scratch allocation failed"; + ray_t* v = ray_sym_vec_new(RAY_SYM_W32,rows); + if (!v || RAY_IS_ERR(v)) { if (v) ray_release(v); return "symbol vector allocation failed"; } + v->sym_domain = s->import_domain; ray_sym_domain_retain(v->sym_domain); + v->len = rows; *out = v; uint32_t* dst = ray_data(v); + const char** strings = scratch->strings; size_t* lengths = scratch->lengths; + uint32_t* hashes = scratch->hashes; + int64_t* ids = scratch->ids; int64_t* positions = scratch->positions; + for (int64_t at = 0; at < rows;) { + if (ray_interrupted()) return "scan interrupted"; + if (!c->page_left) { const char* err = pq_page(c,s,NULL); if (err) return err; } + int64_t n = rows-at < c->page_left ? rows-at : c->page_left, count = 0; + if (n > 8192) n = 8192; + for (int64_t i = 0; i < n; i++) { + if (!c->optional && c->encoding && c->ids.left && !c->ids.packed) { + uint32_t id = c->ids.value; + if (id >= c->dict_count || !c->symbol_ids) return "invalid symbol dictionary index"; + int64_t pos = c->symbol_ids[id]; + if (pos < 0 || (uint64_t)pos >= UINT32_MAX) return "symbol domain exceeds W32"; + if (!pos && s->strict) return "nonnull empty text collides with native null"; + int64_t count = n-i < (int64_t)c->ids.left ? n-i : (int64_t)c->ids.left; + for (int64_t j = 0; j < count; j++) dst[at+i+j] = (uint32_t)pos; + if (!pos) v->attrs |= RAY_ATTR_HAS_NULLS; + c->ids.left -= (uint64_t)count; i += count-1; continue; + } + uint32_t present = 1; + if (c->optional && (!pq_rle_next(&c->defs,&present) || present > 1)) return "invalid definition levels"; + if (!present) { dst[at+i] = 0; v->attrs |= RAY_ATTR_HAS_NULLS; c->page_nulls++; continue; } + if (c->encoding) { + uint32_t id; + if (!pq_rle_next(&c->ids,&id) || id >= c->dict_count || !c->symbol_ids) return "invalid symbol dictionary index"; + int64_t pos = c->symbol_ids[id]; + if (pos < 0 || (uint64_t)pos >= UINT32_MAX) return "symbol domain exceeds W32"; + if (!pos && s->strict) return "nonnull empty text collides with native null"; + dst[at+i] = (uint32_t)pos; + if (!pos) v->attrs |= RAY_ATTR_HAS_NULLS; + } else { + const uint8_t *lp, *p; + if (!pq_take(&c->values,4,&lp)) return "truncated string length"; + uint32_t len = pq_u32(lp); + if (!pq_take(&c->values,len,&p)) return "truncated string data"; + if (s->strict && (!len || (s->converted == 0 && !pq_utf8(p,len)))) + return "nonnull text is empty or invalid UTF-8"; + strings[count] = (const char*)p; lengths[count] = len; + hashes[count] = (uint32_t)ray_hash_bytes(p,len); positions[count++] = at+i; + } + } + if (count) { + if (!ray_sym_domain_intern_batch(s->import_domain,count,strings,lengths,hashes,ids)) return "symbol domain allocation failed"; + for (int64_t i = 0; i < count; i++) { + if (ids[i] < 0 || (uint64_t)ids[i] >= UINT32_MAX) return "symbol domain exceeds W32"; + dst[positions[i]] = (uint32_t)ids[i]; if (!ids[i]) v->attrs |= RAY_ATTR_HAS_NULLS; + } + } + at += n; c->page_left -= n; c->chunk_left -= n; + if (!c->page_left) { + if (c->optional && !pq_rle_done(&c->defs)) return "excess definition levels"; + if (c->expected_nulls >= 0 && c->page_nulls != c->expected_nulls) return "v2 null count mismatch"; + if (c->encoding) { if (!pq_rle_done(&c->ids)) return "excess dictionary indices"; } + else if (c->values.p != c->values.end) return "excess string values"; + if (!c->chunk_left && c->chunk.p != c->chunk.end) return "excess column pages"; + } + } + return NULL; +} +static const char* pq_decode(pq_column* c, pq_schema* s, ray_t** out, int64_t rows) { + if (s->import_domain) return pq_decode_symbols(c,s,out,rows); + ray_t* v = ray_vec_new((int8_t)s->type,rows); + if (!v || RAY_IS_ERR(v)) { if (v) ray_release(v); return "vector allocation failed"; } + v->len = rows; *out = v; + if (v->type == RAY_STR) memset(ray_data(v),0,(size_t)rows*sizeof(ray_str_t)); + for (int64_t i = 0; i < rows; i++) { + if (!(i&1023) && ray_interrupted()) return "scan interrupted"; + if (!c->page_left) { const char* err = pq_page(c,s,NULL); if (err) return err; } + if (!c->optional && c->encoding && c->ids.left && !c->ids.packed) { + uint32_t id = c->ids.value; + if (id >= c->dict_count) return "dictionary index out of range"; + int64_t n = rows-i < c->page_left ? rows-i : c->page_left; + if ((uint64_t)n > c->ids.left) n = (int64_t)c->ids.left; + if (n > 4096) n = 4096; + const uint8_t* p = s->physical == 6 ? c->strings[id].p : + c->dict+(size_t)id*((s->physical == 1 || s->physical == 4) ? 4 : 8); + uint32_t len = s->physical == 6 ? c->strings[id].n : 0; + if (len > PQ_MAX_PAGE || (s->physical == 6 && v->str_pool && (uint64_t)v->str_pool->len+len > PQ_POOL_MAX)) return PQ_PUT_FAIL; + const char* perr = pq_put_value(&v,i,s,p,len); + if (perr) return perr; + *out = v; + /* Convert once, fill native values. STR descriptors may safely + * share the same immutable bytes within this batch's pool. */ + if (ray_elem_size(v->type) == 2) { + int16_t* dst = ray_data(v); int16_t x = dst[i]; + for (int64_t j = 1; j < n; j++) dst[i+j] = x; + } else if (ray_elem_size(v->type) == 4) { + uint32_t* dst = ray_data(v); uint32_t x; memcpy(&x,dst+i,4); + for (int64_t j = 1; j < n; j++) memcpy(dst+i+j,&x,4); + } else if (ray_elem_size(v->type) == 8) { + uint64_t* dst = ray_data(v); uint64_t x; memcpy(&x,dst+i,8); + for (int64_t j = 1; j < n; j++) memcpy(dst+i+j,&x,8); + } else { + size_t width = ray_elem_size(v->type); uint8_t* dst = ray_data(v); + for (int64_t j = 1; j < n; j++) memcpy(dst+(size_t)(i+j)*width,dst+(size_t)i*width,width); + } + c->ids.left -= (uint64_t)n; c->page_left -= n-1; c->chunk_left -= n-1; i += n-1; + } else if (!c->optional && !c->encoding && + ((s->physical == 1 && s->type == RAY_I32 && (s->converted == -1 || s->converted == 17)) || + (s->physical == 2 && s->type == RAY_I64))) { + int64_t n = rows-i < c->page_left ? rows-i : c->page_left; + if (n > 4096) n = 4096; /* Keep cancellation responsive. */ + const uint8_t* p; + if (!pq_take(&c->values,(uint64_t)n*(s->physical == 1 ? 4 : 8),&p)) return "truncated numeric data"; + pq_plain_int(v,i,p,n); + if (s->strict && (v->attrs & RAY_ATTR_HAS_NULLS)) return "nonnull integer collides with native null"; + c->page_left -= n-1; c->chunk_left -= n-1; i += n-1; + } else { + uint32_t present = 1; + if (c->optional && (!pq_rle_next(&c->defs,&present) || present > 1)) return "invalid definition levels"; + if (!present) { + if (ray_vec_set_null_checked(v,i,true) != RAY_OK) return "unrepresentable null"; + c->page_nulls++; + } else { + const uint8_t* p; uint32_t len = 0; uint8_t b = 0; + if (c->encoding) { + uint32_t id; + if (!pq_rle_next(&c->ids,&id) || id >= c->dict_count) return "dictionary index out of range"; + if (s->physical == 6) { p = c->strings[id].p; len = c->strings[id].n; } + else p = c->dict+(size_t)id*((s->physical == 1 || s->physical == 4) ? 4 : 8); + } else if (c->bool_rle) { + uint32_t bit; + if (!pq_rle_next(&c->ids,&bit)) return "truncated RLE boolean data"; + b = (uint8_t)bit; p = &b; + } else if (s->physical == 0) { + if (c->bool_bit/8 >= (uint64_t)(c->values.end-c->values.p)) return "truncated boolean data"; + b = (c->values.p[c->bool_bit/8]>>(c->bool_bit&7))&1; c->bool_bit++; p = &b; + } else if (s->physical == 6) { + const uint8_t* lp; + if (!pq_take(&c->values,4,&lp)) return "truncated string length"; + len = pq_u32(lp); + if (!pq_take(&c->values,len,&p)) return "truncated string data"; + } else if (!pq_take(&c->values,(s->physical == 1 || s->physical == 4) ? 4 : 8,&p)) return "truncated numeric data"; + if (s->physical == 6 && v->str_pool && (uint64_t)v->str_pool->len+len > PQ_POOL_MAX) return "batch string pool exceeds 4 GiB"; + if (len > PQ_MAX_PAGE) return PQ_PUT_FAIL; + const char* perr = pq_put_value(&v,i,s,p,len); + if (perr) return perr; + *out = v; + } + } + c->page_left--; c->chunk_left--; + if (!c->page_left) { + if (c->optional && !pq_rle_done(&c->defs)) return "excess definition levels"; + if (c->expected_nulls >= 0 && c->page_nulls != c->expected_nulls) return "v2 null count mismatch"; + if (c->encoding) { if (!pq_rle_done(&c->ids)) return "excess dictionary indices"; } + else if (c->bool_rle) { if (!pq_rle_done(&c->ids)) return "excess RLE boolean data"; } + else if (s->physical == 0) { if ((c->bool_bit+7)/8 != (uint64_t)(c->values.end-c->values.p)) return "excess boolean data"; } + else if (c->values.p != c->values.end) return "excess plain data"; + if (!c->chunk_left && c->chunk.p != c->chunk.end) return "excess column pages"; + } + } + return NULL; +} +static const char* pq_discard(pq_column* c, pq_schema* s, int64_t rows) { + while (rows) { + if (ray_interrupted()) return "scan interrupted"; + if (!c->page_left) { + const char* err = pq_page(c,s,&rows); + if (err) return err; + if (!rows) break; + } + int64_t n = rows < c->page_left ? rows : c->page_left; + if (n > PQ_BATCH) n = PQ_BATCH; + ray_t* discard = NULL; + const char* err = pq_decode(c,s,&discard,n); + if (discard) ray_release(discard); + if (err) return err; + rows -= n; + } + return NULL; +} +typedef struct { + ray_parquet_t* reader; + ray_t** columns; + const char** errors; + int64_t rows; +} pq_work; +static const char* pq_decode_column(ray_parquet_t* r, int64_t i, ray_t** out, int64_t rows) { + pq_schema schema = r->schema[r->selected[i]]; + /* Filter before interning: rejected text must not grow the query domain. */ + if (r->filter_pos >= 0 || r->text_pattern) schema.import_domain = NULL; + return pq_decode(&r->cursors[i],&schema,out,rows); +} +static const char* pq_intern_selected(pq_column* c, ray_t** vector, ray_sym_domain_t* domain) { + pq_symbol_scratch* scratch = pq_symbols(c); + if (!scratch) return "symbol scratch allocation failed"; + ray_t* src = *vector; + ray_t* dst = ray_sym_vec_new(RAY_SYM_W32,src->len); + if (!dst || RAY_IS_ERR(dst)) { if (dst) ray_release(dst); return "symbol allocation failed"; } + dst->sym_domain = domain; ray_sym_domain_retain(domain); dst->len = src->len; + const char** strings = scratch->strings; size_t* lengths = scratch->lengths; + uint32_t* hashes = scratch->hashes; int64_t* ids = scratch->ids; + for (int64_t at = 0; at < src->len; at += 8192) { + int64_t n = src->len-at < 8192 ? src->len-at : 8192; + for (int64_t i = 0; i < n; i++) { + strings[i] = ray_str_vec_get(src,at+i,&lengths[i]); + hashes[i] = (uint32_t)ray_hash_bytes(strings[i],lengths[i]); + } + if (!ray_sym_domain_intern_batch(domain,n,strings,lengths,hashes,ids)) { + ray_release(dst); return "symbol domain allocation failed"; + } + for (int64_t i = 0; i < n; i++) { + if (ids[i] < 0 || (uint64_t)ids[i] >= UINT32_MAX) { ray_release(dst); return "symbol domain exceeds W32"; } + ((uint32_t*)ray_data(dst))[at+i] = (uint32_t)ids[i]; + if (!ids[i]) dst->attrs |= RAY_ATTR_HAS_NULLS; + } + } + ray_release(src); *vector = dst; return NULL; +} +static void pq_decode_task(void* ptr, uint32_t worker, int64_t start, int64_t end) { + (void)worker; + pq_work* w = ptr; ray_parquet_t* r = w->reader; + for (int64_t i = start; i < end; i++) if (!w->columns[i]) + w->errors[i] = pq_decode_column(r,i,&w->columns[i],w->rows); +} +int64_t ray_parquet_pages_skipped(const ray_parquet_t* r) { + int64_t n = 0; + if (r) for (int64_t i = 0; i < r->nselected; i++) n += r->cursors[i].pages_skipped; + return n; +} +int64_t ray_parquet_bloom_skipped(const ray_parquet_t* r) { return r ? r->bloom_skipped : 0; } +int64_t ray_parquet_parallel_batches(const ray_parquet_t* r) { return r ? r->parallel_batches : 0; } + +ray_t* ray_parquet_next(ray_parquet_t* r) { + if (!r || r->failed) return pq_error("reader is closed or failed"); + if (ray_interrupted()) { r->failed = true; return ray_error("cancel","parquet scan interrupted"); } + const char* err = NULL; + int64_t rows; + for (;;) { + while (!r->group_left && r->group+1 < r->ngroups) { + r->group++; + err = pq_start_group(r); + if (err) { r->failed = true; return pq_error(err); } + } + if (!r->group_left && r->emitted) return NULL; + int64_t cap = r->group_batch > 0 ? r->group_batch : r->batch_rows; + rows = r->group_left < cap ? r->group_left : cap; + if (r->group_left && r->exclude_pos < r->nexcluded) { + pq_interval range = r->excluded[r->exclude_pos]; + int64_t at = r->group_rows-r->group_left; + if (at == range.lo) { + for (int64_t i = 0; i < r->nselected; i++) { + pq_schema schema = r->schema[r->selected[i]]; schema.import_domain = NULL; + err = pq_discard(&r->cursors[i],&schema,range.hi-range.lo); + if (err) { r->failed = true; return pq_error(err); } + } + r->group_left -= range.hi-range.lo; r->exclude_pos++; + continue; + } + if (rows > range.lo-at) rows = range.lo-at; + } + break; + } + ray_t* tbl = ray_table_new(r->noutput); + if (!tbl || RAY_IS_ERR(tbl)) return tbl ? tbl : ray_error("oom",NULL); + ray_t** cols = ray_calloc_raw((size_t)r->nselected*sizeof(*cols)); + uint8_t* keep = NULL; + const char** errors = NULL; + int64_t bad_col = -1; + if (!cols) { ray_release(tbl); r->failed = true; return ray_error("oom",NULL); } + ray_pool_t* pool = rows >= 4096 && r->nselected > 1 ? ray_pool_get() : NULL; + if (ray_pool_par_dispatch_ok(pool,rows,4096)) { + errors = ray_calloc_raw((size_t)r->nselected*sizeof(*errors)); + if (!errors) { err = "task allocation failed"; goto fail; } + pq_work work = {r,cols,errors,rows}; + ray_pool_dispatch_n(pool,pq_decode_task,&work,(uint32_t)r->nselected); + r->parallel_batches++; + for (int64_t i = 0; i < r->nselected; i++) { + if (errors[i] || !cols[i]) { err = errors[i] ? errors[i] : "scan interrupted"; bad_col = i; goto fail; } + } + } else for (int64_t i = 0; i < r->nselected; i++) { + err = pq_decode_column(r,i,&cols[i],rows); + if (err) { bad_col = i; goto fail; } + } + int64_t kept = rows; + if (r->filter_pos >= 0 && rows) { + keep = ray_alloc_raw((size_t)rows); + if (!keep) { err = "selection allocation failed"; goto fail; } + ray_t* f = cols[r->filter_pos]; kept = 0; + for (int64_t i = 0; i < rows; i++) { + int64_t value = f->type == RAY_I16 ? ((int16_t*)ray_data(f))[i] : + f->type == RAY_I32 ? ((int32_t*)ray_data(f))[i] : ((int64_t*)ray_data(f))[i]; + keep[i] = ray_vec_is_null(f,i) ? r->filter_nulls : value >= r->filter_lo && value <= r->filter_hi; + kept += keep[i]; + } + } + if (r->text_pattern && rows) { + if (!keep) keep = ray_alloc_raw((size_t)rows); + if (!keep) { err = "selection allocation failed"; goto fail; } + const char* pat = ray_str_ptr(r->text_pattern); size_t pn = ray_str_len(r->text_pattern); + ray_glob_compiled_t compiled = ray_glob_compile(pat,pn); + kept = 0; + for (int64_t i = 0; i < rows; i++) { + size_t len; const char* str = ray_str_vec_get(cols[r->text_pos],i,&len); + keep[i] = compiled.shape == RAY_GLOB_SHAPE_NONE ? ray_glob_match(str,len,pat,pn) : + ray_glob_match_compiled(&compiled,str,len); + kept += keep[i]; + } + } + for (int64_t c = 0; c < r->noutput; c++) { + ray_t* v = cols[c]; + if (kept != rows) { + size_t esz = ray_sym_elem_size(v->type,v->attrs); uint8_t* data = ray_data(v); int64_t dst = 0; + for (int64_t i = 0; i < rows; i++) if (keep[i]) { + if (dst != i) memcpy(data+(size_t)dst*esz,data+(size_t)i*esz,esz); + dst++; + } + v->len = kept; + } + if (v->type == RAY_STR && r->schema[r->selected[c]].import_domain) { + err = pq_intern_selected(&r->cursors[c],&cols[c],r->schema[r->selected[c]].import_domain); + if (err) goto fail; + v = cols[c]; + } + tbl = ray_table_add_col(tbl,r->schema[r->selected[c]].name,v); + if (!tbl || RAY_IS_ERR(tbl)) { err = "table allocation failed"; goto fail; } + } + r->group_left -= rows; r->emitted = true; + for (int64_t c = 0; c < r->nselected; c++) ray_release(cols[c]); + ray_free_raw(cols); ray_free_raw(keep); ray_free_raw(errors); + return tbl; +fail: + for (int64_t c = 0; c < r->nselected; c++) if (cols[c]) ray_release(cols[c]); + ray_free_raw(cols); ray_free_raw(keep); ray_free_raw(errors); + if (tbl) ray_release(tbl); + r->failed = true; + if (ray_interrupted()) return ray_error("cancel","parquet scan interrupted"); + if (bad_col >= 0) { + ray_t* name = ray_sym_str(r->schema[r->selected[bad_col]].name); + return ray_error("parquet","%s (column %s)",err,name ? ray_str_ptr(name) : "?"); + } + return pq_error(err); +} + +/* Optional Rayfall scan settings: {columns: [x y] range: {column: k min: 1 max: 9}}. + * The C cursor also exposes the same range directly, without language objects. */ +static ray_t* pq_option(ray_t* options, const char* name) { + ray_t* key = ray_sym(ray_sym_intern(name,strlen(name))); + if (!key || RAY_IS_ERR(key)) return key; + ray_t* result = ray_dict_get(options,key); ray_release(key); return result; +} +static ray_t* pq_import_types(ray_parquet_t* r, ray_t* types); +static ray_t* pq_strict_option(ray_parquet_t* r, ray_t* options) { + ray_t* strict = pq_option(options,"strict"); + if (!strict) return NULL; + bool valid = strict->type == -RAY_BOOL; + if (valid) for (int64_t c = 0; c < r->ncols; c++) r->schema[c].strict = strict->b8 != 0; + ray_release(strict); + return valid ? NULL : pq_error("strict must be a boolean"); +} +static ray_t* pq_scan_types(ray_parquet_t* r, ray_t* types) { + if (types && types->type != RAY_SYM) return pq_error("types must be a symbol vector"); + ray_t* err = pq_import_types(r,types); + if (err) return err; + for (int64_t c = 0; c < r->ncols; c++) if (r->schema[c].native_symbol) { + if (!r->scan_domain) r->scan_domain = ray_sym_domain_new(); + if (!r->scan_domain) return ray_error("oom",NULL); + r->schema[c].import_domain = r->scan_domain; + } + return NULL; +} +static ray_t* pq_open_options(const char* path, ray_t* options, ray_parquet_t** out) { + if (!options || options->type != RAY_DICT) return ray_parquet_open(path,options,PQ_BATCH,out); + *out = NULL; + ray_t* keys = ray_dict_keys(options); + if (!keys || keys->type != RAY_SYM) return pq_error("scan 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,"columns") && strcmp(k,"range") && strcmp(k,"types") && strcmp(k,"strict"))) return pq_error("unknown scan option"); + } + ray_t* columns = pq_option(options,"columns"); + ray_t* range = pq_option(options,"range"); + ray_t* types = pq_option(options,"types"); + ray_t* err = NULL; + if ((columns && RAY_IS_ERR(columns)) || (range && RAY_IS_ERR(range))) { err = pq_error("invalid scan options"); goto done; } + err = ray_parquet_open(path,columns,PQ_BATCH,out); + if (!err) err = pq_scan_types(*out,types); + if (!err) err = pq_strict_option(*out,options); + if (err || !range) goto done; + if (range->type != RAY_DICT) { err = pq_error("range must be {column: name min: lo max: hi}"); goto done; } + ray_t* name = pq_option(range,"column"); ray_t* lo = pq_option(range,"min"); ray_t* hi = pq_option(range,"max"); + if (!name || !lo || !hi || name->type != -RAY_SYM || lo->type != -RAY_I64 || hi->type != -RAY_I64) + err = pq_error("range expects a symbol column and two I64 bounds"); + else err = ray_parquet_range(*out,name->i64,lo->i64,hi->i64); + if (name) ray_release(name); + if (lo) ray_release(lo); + if (hi) ray_release(hi); +done: + if (columns) ray_release(columns); + if (range) ray_release(range); + if (types) ray_release(types); + if (err && *out) { ray_parquet_close(*out); *out = NULL; } + return err; +} + +/* Row-group tasks share only immutable mapping/schema data. Each task owns its + * cursors, page buffers, dictionary and selection. The parent outlives the join. */ +static ray_parquet_t* pq_group_reader(const ray_parquet_t* parent, int64_t group) { + ray_parquet_t* r = ray_calloc_raw(sizeof(*r)); + if (!r) return NULL; + r->borrowed = true; r->map = parent->map; r->size = parent->size; r->data_end = parent->data_end; + r->schema = parent->schema; r->groups = parent->groups; r->ncols = parent->ncols; + r->ngroups = group+1; r->group = group-1; r->batch_rows = parent->batch_rows; + r->nselected = parent->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->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)); + if (!r->selected || !r->cursors) { ray_parquet_close(r); return NULL; } + memcpy(r->selected,parent->selected,(size_t)r->nselected*sizeof(*r->selected)); + return r; +} +static ray_pool_t* pq_group_pool(ray_parquet_t* r) { + ray_pool_t* pool = r->ngroups > 1 ? ray_pool_get() : NULL; + return ray_pool_par_dispatch_ok(pool,r->ngroups,2) ? pool : NULL; +} +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); + 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); + ray_t* v = ray_str_vec_append(vectors[c],p,n); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom",NULL); + vectors[c] = v; + } + } else { + ray_t* v = ray_vec_append_raw(vectors[c],ray_data(src),nr); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom",NULL); + vectors[c] = v; + } + vectors[c]->attrs |= src->attrs & RAY_ATTR_HAS_NULLS; + } + return NULL; +} +static ray_t* pq_materialize(ray_parquet_t* r); +typedef struct { ray_parquet_t* parent; int64_t first; ray_t** tables; } pq_read_work; +static void pq_read_group(void* ptr, uint32_t worker, int64_t start, int64_t end) { + (void)worker; pq_read_work* w = ptr; + for (int64_t i = start; i < end; i++) { + ray_parquet_t* r = pq_group_reader(w->parent,w->first+i); + w->tables[i] = r ? pq_materialize(r) : ray_error("oom",NULL); + } +} +static ray_t* pq_materialize(ray_parquet_t* r) { + ray_t* err = NULL; + ray_t** vectors = ray_calloc_raw((size_t)r->noutput*sizeof(*vectors)); + if (!vectors) { ray_parquet_close(r); return ray_error("oom",NULL); } + for (int64_t c = 0; c < r->noutput; c++) { + pq_schema* schema = &r->schema[r->selected[c]]; + vectors[c] = schema->import_domain ? ray_sym_vec_new(RAY_SYM_W32,0) : ray_vec_new((int8_t)schema->type,0); + if (!vectors[c] || RAY_IS_ERR(vectors[c])) { + err = vectors[c] ? vectors[c] : ray_error("oom",NULL); vectors[c] = NULL; goto done; + } + if (schema->import_domain) { + vectors[c]->sym_domain = schema->import_domain; + ray_sym_domain_retain(schema->import_domain); + } + } + ray_pool_t* pool = pq_group_pool(r); + if (pool) { + /* Bound temporary materialized output to one wave, retain source order. */ + uint32_t width = ray_pool_total_workers(pool); + if (width > RAY_POOL_INIT_TASKS) width = RAY_POOL_INIT_TASKS; + ray_t** tables = ray_calloc_raw((size_t)width*sizeof(*tables)); + if (!tables) { err = ray_error("oom",NULL); goto done; } + for (int64_t first = 0; first < r->ngroups && !err; first += width) { + uint32_t n = r->ngroups-first < width ? (uint32_t)(r->ngroups-first) : width; + memset(tables,0,(size_t)n*sizeof(*tables)); + pq_read_work work = {r,first,tables}; + ray_pool_dispatch_n(pool,pq_read_group,&work,n); + for (uint32_t i = 0; i < n; i++) { + ray_t* batch = tables[i]; + if (!err) { + if (!batch) err = ray_error("cancel","parquet scan interrupted"); + else if (RAY_IS_ERR(batch)) { err = batch; batch = NULL; } + else err = pq_append_table(vectors,batch,r->noutput); + } + if (batch) ray_release(batch); + } + } + ray_free_raw(tables); + if (err) goto done; + } else for (;;) { + ray_t* batch = ray_parquet_next(r); + if (!batch) break; + if (RAY_IS_ERR(batch)) { err = batch; goto done; } + err = pq_append_table(vectors,batch,r->noutput); + ray_release(batch); + if (err) goto done; + } + err = ray_table_new(r->noutput); + for (int64_t c = 0; c < r->noutput && err && !RAY_IS_ERR(err); c++) + err = ray_table_add_col(err,r->schema[r->selected[c]].name,vectors[c]); +done: + for (int64_t c = 0; c < r->noutput; c++) if (vectors[c]) ray_release(vectors[c]); + ray_free_raw(vectors); ray_parquet_close(r); + return err ? err : ray_error("oom",NULL); +} + +ray_t* ray_parquet_read(const char* path, ray_t* columns) { + ray_parquet_t* r = NULL; + ray_t* err = pq_open_options(path,columns,&r); + return err ? err : pq_materialize(r); +} + +ray_t* ray_parquet_metadata(const char* path) { + ray_parquet_t* r = NULL; ray_t* err = ray_parquet_open(path,NULL,PQ_BATCH,&r); + if (err) return err; + const char* names[] = {"row_group","column","physical_type","ray_type","codec","rows","compressed_bytes","uncompressed_bytes","statistics","page_index","bloom_filter"}; + enum { N = 11 }; + ray_t* v[N] = {0}; pq_span* cols = NULL; + int64_t count = r->ngroups*r->ncols; + if ((uint64_t)count > PQ_MAX_FOOTER/(N*sizeof(int64_t))) { + ray_parquet_close(r); return pq_error("metadata result exceeds 64 MiB"); + } + for (int i = 0; i < N; i++) { + v[i] = i == 1 || i == 3 ? ray_sym_vec_new(RAY_SYM_W64,count) : ray_vec_new(RAY_I64,count); + if (!v[i] || RAY_IS_ERR(v[i])) { err = v[i]; v[i] = NULL; goto done; } + v[i]->len = count; + } + cols = ray_alloc_raw((size_t)r->ncols*sizeof(*cols)); + if (!cols) goto done; + for (int64_t g = 0; g < r->ngroups; g++) { + int64_t nr; + if (!pq_group_columns(r,g,cols,&nr,NULL)) { err = pq_error("invalid row group metadata"); goto done; } + pq_span gf[8]; + if (!pq_fields(r->groups[g],gf,8)) { err = pq_error("invalid row group"); goto done; } + pq_cur cc = {gf[1].p,gf[1].end,false}; uint8_t ct; pq_list(&cc,&ct); + for (int64_t c = 0; c < r->ncols; c++) { + int64_t row = g*r->ncols+c; pq_span mf[17], ch, cf[10]; + if (!pq_fields(cols[c],mf,17) || !pq_element(&cc,12,&ch) || !pq_fields(ch,cf,10)) { + err = pq_error("invalid column metadata"); goto done; + } + const char* tn = ray_type_name((int8_t)r->schema[c].type); + int64_t cells[N] = {g,r->schema[c].name,r->schema[c].physical,ray_sym_intern(tn,strlen(tn)), + pq_get(mf[4],-1),nr,pq_get(mf[7],-1),pq_get(mf[6],-1),!!mf[12].type, + !!cf[4].type && !!cf[6].type,!!mf[14].type}; + for (int i = 0; i < N; i++) ((int64_t*)ray_data(v[i]))[row] = cells[i]; + } + } + err = ray_table_new(N); + for (int i = 0; i < N && err && !RAY_IS_ERR(err); i++) + err = ray_table_add_col(err,ray_sym_intern(names[i],strlen(names[i])),v[i]); +done: + for (int i = 0; i < N; i++) if (v[i]) ray_release(v[i]); + ray_free_raw(cols); ray_parquet_close(r); + return err ? err : ray_error("oom",NULL); +} + +static bool pq_safe_name(const char* s) { + if (!s || !*s || *s == '.') return false; + for (; *s; s++) if (*s == '/' || *s == '\\' || *s == ':') return false; + return true; +} +/* Import schemas are positional, like CSV schemas. Unannotated integer dates + * and timestamps require explicit UNIX_* units rather than guessing epochs. */ +static ray_t* pq_import_types(ray_parquet_t* r, ray_t* types) { + if (!types) return NULL; + if (types->type == RAY_DICT) { + ray_t* keys = ray_dict_keys(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"); + } + ray_t* err = pq_strict_option(r,types); + ray_t* rows = pq_option(types,"rows"); + 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* 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); + if (schema) ray_release(schema); + return err; + } + if (types->type != RAY_SYM || types->len != r->ncols) return pq_error("import types must match the Parquet columns"); + for (int64_t c = 0; c < r->ncols; c++) { + ray_t* atom = ray_sym_vec_cell(types,c); const char* name = atom ? ray_str_ptr(atom) : NULL; + pq_schema* s = &r->schema[c]; + if (!name) return pq_error("invalid import type"); + if (!strcmp(name,"SYM") && s->type == RAY_STR) { s->native_symbol = true; continue; } + if (!strcmp(name,ray_type_name((int8_t)s->type))) continue; + bool integer = (s->type == RAY_I16 || s->type == RAY_I32 || s->type == RAY_I64); + if (!integer) return pq_error("unsupported import type conversion"); + if (!strcmp(name,"I16")) s->type = RAY_I16; + else if (!strcmp(name,"I32")) s->type = RAY_I32; + else if (!strcmp(name,"I64")) s->type = RAY_I64; + else if (!strcmp(name,"UNIX_DATE")) s->type = RAY_DATE; + else { + int64_t scale = !strcmp(name,"UNIX_SECONDS") ? 1000000000 : + !strcmp(name,"UNIX_MILLIS") ? 1000000 : !strcmp(name,"UNIX_MICROS") ? 1000 : + !strcmp(name,"UNIX_NANOS") ? 1 : 0; + if (!scale) return pq_error("unsupported import type; raw integer timestamps require explicit UNIX_* units"); + s->type = RAY_TIMESTAMP; s->scale = scale; + } + } + return NULL; +} +typedef struct { + ray_parquet_t* parent; + const char *root, *table; + int64_t *offsets; + ray_t** errors; + bool durable; +} pq_native_work; +/* These partitions are private to the import staging directory. Persist the + * 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) { + 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. + * The non-durable callers (the splayed spool and parted partitions) write + * private leaves under the import's staging root, published by renaming + * 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); + 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; } + char path[1600]; + for (int64_t c = 0; c < r->ncols; c++) { + 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); + 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; } + schema = next; + } + if (e == RAY_OK) { + int n = snprintf(path,sizeof(path),"%s/.d",leaf); + e = n < 0 || (size_t)n >= sizeof(path) ? RAY_ERR_RANGE : + durable ? ray_col_save(schema,path) : ray_col_save_bulk(schema,path); + } + ray_release(schema); return e; +} +static ray_t* pq_write_reader(ray_parquet_t* r, const char* root, const char* table, + int64_t part, bool durable) { + char sym[1200]; snprintf(sym,sizeof(sym),"%s/.sym",root); + for (;;) { + ray_t* batch = ray_parquet_next(r); + 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); + 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); + if (e && RAY_IS_ERR(e)) { ray_release(col); ray_release(batch); return e; } + ray_table_set_col_idx(batch,c,col); ray_release(col); + } + char leaf[1400]; + int n = snprintf(leaf,sizeof(leaf),"%s/%lld/%s",root,(long long)part++,table); + /* 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); + ray_release(batch); + if (e != RAY_OK) return ray_error(ray_err_code_str(e),"parquet: native partition write failed"); + } +} +static void pq_write_group(void* ptr, uint32_t worker, int64_t start, int64_t end) { + (void)worker; pq_native_work* w = ptr; + for (int64_t g = start; g < end; g++) { + ray_parquet_t* r = pq_group_reader(w->parent,g); + if (!r) { w->errors[g] = ray_error("oom",NULL); continue; } + w->errors[g] = pq_write_reader(r,w->root,w->table,w->offsets[g],w->durable); + ray_parquet_close(r); + } +} +static ray_t* pq_write_groups(ray_parquet_t* r, const char* root, const char* table, + bool durable, int64_t* parts) { + *parts = 0; + int64_t ng = r->ngroups; + int64_t* offsets = ray_alloc_raw((size_t)(ng+1)*sizeof(*offsets)); + ray_t** errors = ray_calloc_raw((size_t)(ng+1)*sizeof(*errors)); + ray_t* err = NULL; + if (!offsets || !errors) { err = ray_error("oom",NULL); goto done; } + for (int64_t g = 0; g < ng; g++) { + pq_span fields[8]; + if (!pq_fields(r->groups[g],fields,8)) { err = pq_error("invalid row group"); goto done; } + int64_t rows = pq_get(fields[3],-1); + if (rows < 0) { err = pq_error("invalid row group row count"); goto done; } + offsets[g] = *parts; + int64_t n = rows ? 1+(rows-1)/pq_group_batch(r,g) : 1; + if (*parts > INT64_MAX-n) { err = pq_error("too many partitions"); goto done; } + *parts += n; + } + if (!ng) { *parts = 1; err = pq_write_reader(r,root,table,0,durable); goto done; } + pq_native_work work = {r,root,table,offsets,errors,durable}; + ray_pool_t* pool = pq_group_pool(r); + if (pool) { + /* dispatch uses a bounded ring; tasks claim groups dynamically. */ + ray_pool_dispatch_n(pool,pq_write_group,&work,(uint32_t)ng); + } else pq_write_group(&work,0,0,ng); + for (int64_t g = 0; g < ng; g++) if (errors[g]) { + if (!err) err = errors[g]; else ray_release(errors[g]); + } + if (!err && ray_interrupted()) err = ray_error("cancel","parquet conversion interrupted"); +done: + ray_free_raw(offsets); ray_free_raw(errors); return err; +} +/* The destination without trailing separators, as .csv.parted takes it: + * "out/" must stage in "out.parquet-partial", not "out/.parquet-partial". */ +static bool pq_dest(const char* in, char* out, size_t size) { + size_t len = in ? strlen(in) : 0; + while (len > 1 && (in[len-1] == '/' || in[len-1] == '\\')) len--; + if (!len || len >= size) return false; + memcpy(out,in,len); out[len] = 0; + return true; +} +static ray_t* pq_stage(ray_parquet_t* r, const char* root, char* staging, size_t size, bool parted) { + struct stat st; + int n = snprintf(staging,size,"%s.parquet-partial",root); + if (n < 0 || (size_t)n >= size || stat(root,&st) == 0) + return pq_error("destination exists or path is too long"); + for (int64_t c = 0; c < r->ncols; c++) { + const char* name = ray_str_ptr(ray_sym_str(r->schema[c].name)); + if (!pq_safe_name(name) || (parted && !strcmp(name,"part"))) + return pq_error("column name is unsafe or conflicts with native partition key 'part'"); + } +#ifdef RAY_OS_WINDOWS + bool created = CreateDirectoryA(staging,NULL) != 0; +#else + bool created = mkdir(staging,0755) == 0; +#endif + return created ? NULL : ray_error("parquet","cannot create staging directory %s (the parent must exist; one left by an earlier failed import is not overwritten, remove it to retry)",staging); +} +static ray_t* pq_publish(const char* staging, const char* root, int64_t rows) { + struct stat st; + if (ray_interrupted()) return ray_error("cancel","parquet conversion interrupted"); + char child[1100]; + int n = snprintf(child,sizeof(child),"%s/.d",staging); + if (n < 0 || (size_t)n >= sizeof(child) || ray_file_sync_dir(child) != RAY_OK) + return pq_error("cannot sync staging directory; native destination not published"); + if (stat(root,&st) == 0 || ray_file_rename_new(staging,root) != RAY_OK) + return pq_error("cannot publish native destination; staging directory retained"); + if (ray_file_sync_dir(root) != RAY_OK) return pq_error("native destination published but directory sync failed"); + return ray_i64(rows); +} +static ray_t* pq_sync_partitions(ray_parquet_t* r, const char* root, const char* table, int64_t parts) { + char path[1600], leaf[1400]; + for (int64_t part = 0; part < parts; part++) { + if (ray_interrupted()) return ray_error("cancel","parquet conversion interrupted"); + int n = snprintf(leaf,sizeof(leaf),"%s/%lld/%s",root,(long long)part,table); + if (n < 0 || (size_t)n >= sizeof(leaf)) return pq_error("partition path is too long"); + for (int64_t c = 0; c <= r->ncols; c++) { + const char* name = c == r->ncols ? ".d" : ray_str_ptr(ray_sym_str(r->schema[c].name)); + n = snprintf(path,sizeof(path),"%s/%s",leaf,name); + if (n < 0 || (size_t)n >= sizeof(path)) return pq_error("column path is too long"); + ray_fd_t fd = ray_file_open(path,RAY_OPEN_READ | RAY_OPEN_WRITE); + if (fd == RAY_FD_INVALID) return pq_error("cannot open staged column for sync"); + ray_err_t e = ray_file_sync(fd); ray_file_close(fd); + if (e != RAY_OK) return ray_error(ray_err_code_str(e),"parquet: staged column sync failed"); + } + /* path names .d, so sync its parent (leaf), then leaf's parent + * (partition). pq_publish persists the staging root before rename. */ + if (ray_file_sync_dir(path) != RAY_OK || ray_file_sync_dir(leaf) != RAY_OK) + return pq_error("cannot sync partition directories"); + } + return NULL; +} +ray_t* ray_parquet_parted_typed(const char* path, const char* root, const char* table, ray_t* types) { +#ifdef RAY_FUZZING + return ray_error("restricted","Parquet imports disabled under fuzzing"); +#endif + if (!pq_safe_name(table)) return pq_error("invalid destination table name"); + char dest[1024]; + if (!pq_dest(root,dest,sizeof(dest))) return pq_error("invalid or too long destination path"); + root = dest; + ray_parquet_t* r = NULL; ray_t* err = ray_parquet_open(path,NULL,PQ_BATCH,&r); + if (err) return err; + char staging[1100], sym[1200]; int64_t parts; + ray_sym_domain_t* domain = NULL; + err = pq_import_types(r,types); + 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 + * into the shared, synchronized file domain, as in direct splayed loads. */ + for (int64_t c = 0; c < r->ncols; c++) if (r->schema[c].native_symbol) { + if (!domain) { + snprintf(sym,sizeof(sym),"%s/.sym",staging); + domain = ray_sym_domain_open_or_create(sym); + if (!domain || ray_sym_domain_intern(domain,"",0) != 0) { + err = ray_error("oom",NULL); goto done; + } + } + r->schema[c].import_domain = domain; + } + err = pq_write_groups(r,staging,table,true,&parts); + if (!err && domain) { + /* Every partition header must be covered by the final vocabulary + * before publication, including symbols added by other group tasks. */ + ray_err_t e = ray_sym_domain_flush(domain,true); + if (e != RAY_OK) err = ray_error(ray_err_code_str(e),"parquet: cannot flush symbol file"); + } + if (!err) err = pq_sync_partitions(r,staging,table,parts); + if (!err) err = pq_publish(staging,root,r->rows); +done: + if (domain) ray_sym_domain_release(domain); + ray_parquet_close(r); return err; +} +ray_t* ray_parquet_parted(const char* path, const char* root, const char* table) { + return ray_parquet_parted_typed(path,root,table,NULL); +} +static bool pq_remove_dir(const char* path) { +#ifdef RAY_OS_WINDOWS + return RemoveDirectoryA(path) != 0; +#else + return rmdir(path) == 0; +#endif +} +typedef struct { + ray_parquet_t* parent; + ray_col_stream_t* writers; + int64_t* offsets; + _Atomic uint32_t* nulls; + _Atomic uint32_t* locks; + ray_t** errors; +} pq_direct_work; +static void pq_write_direct_group(void* ptr, uint32_t worker, int64_t start, int64_t end) { + (void)worker; pq_direct_work* w = ptr; + for (int64_t task = start; task < end; task++) { + int64_t g = task/w->parent->ncols, c = task%w->parent->ncols; + ray_parquet_t* r = pq_group_reader(w->parent,g); + if (!r) { w->errors[task] = ray_error("oom",NULL); continue; } + /* A task is one column chunk, so both groups and columns can occupy + * workers. Narrow schemas still get one task per row group. */ + r->selected[0] = (int32_t)c; r->nselected = r->noutput = 1; + int64_t row = w->offsets[g]; + ray_col_stream_t local = {0}; + local.type = w->writers[c].type; local.dom = w->writers[c].dom; + size_t size = local.type == RAY_SYM ? 4 : ray_elem_size(local.type); + local.fp = fopen(w->writers[c].tmp_path,"r+b"); + if (!local.fp) { w->errors[task] = pq_error("cannot open native column"); ray_parquet_close(r); continue; } + int64_t offset = 32+row*(int64_t)size; +#ifdef RAY_OS_WINDOWS + bool seek = _fseeki64(local.fp,offset,SEEK_SET) == 0; +#else + bool seek = fseeko(local.fp,(off_t)offset,SEEK_SET) == 0; +#endif + if (!seek) w->errors[task] = pq_error("cannot seek native output range"); + if (!w->errors[task]) { + ray_err_t ie = ray_col_stream_index_begin(&local,row); + if (ie != RAY_OK) w->errors[task] = ray_error(ray_err_code_str(ie),"parquet: zone accumulator"); + } + while (!w->errors[task]) { + 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)); + 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; } + } + /* Fold this row group's chunk partials into the column's zone. */ + if (local.zone && !w->errors[task]) { + while (atomic_exchange_explicit(&w->locks[c],1,memory_order_acquire)) RAY_CPU_RELAX(); + ray_err_t me = ray_col_stream_index_merge(&w->writers[c],&local); + atomic_store_explicit(&w->locks[c],0,memory_order_release); + if (me != RAY_OK && !w->errors[task]) w->errors[task] = ray_error(ray_err_code_str(me),"parquet: zone merge"); + } + /* Unmerged accumulator (task error): ray_col_stream_abort would + * fclose local.fp a second time, so free the zone directly. */ + if (local.zone) { ray_zone_acc_free(local.zone); ray_free_raw(local.zone); local.zone = NULL; } + if (fclose(local.fp) && !w->errors[task]) w->errors[task] = pq_error("native column close failed"); + if (local.had_nulls) atomic_store_explicit(&w->nulls[c],1,memory_order_relaxed); + if (!w->errors[task] && row != w->offsets[g+1]) w->errors[task] = pq_error("row group ended before its assigned output range"); + ray_parquet_close(r); + } +} + +static ray_t* pq_write_direct(ray_parquet_t* r, ray_col_stream_t* writers) { + int64_t tasks = r->ngroups*r->ncols; + if (tasks > UINT32_MAX) return pq_error("too many column chunk tasks"); + int64_t* offsets = ray_calloc_raw((size_t)(r->ngroups+1)*sizeof(*offsets)); + _Atomic uint32_t* nulls = ray_calloc_raw((size_t)r->ncols*sizeof(*nulls)); + _Atomic uint32_t* locks = ray_calloc_raw((size_t)r->ncols*sizeof(*locks)); + ray_t** errors = ray_calloc_raw((size_t)(tasks+1)*sizeof(*errors)); + ray_t* err = NULL; + if (!offsets || !nulls || !locks || !errors) { err = ray_error("oom",NULL); goto done; } + for (int64_t c = 0; c < r->ncols; c++) { + size_t size = writers[c].type == RAY_SYM ? 4 : ray_elem_size(writers[c].type); + if (r->rows > (INT64_MAX-32)/(int64_t)size) { err = pq_error("native column exceeds file offset range"); goto done; } + if (fflush(writers[c].fp)) { err = pq_error("cannot flush column header"); goto done; } + atomic_init(&nulls[c],0); atomic_init(&locks[c],0); + if (r->schema[c].native_symbol) r->schema[c].import_domain = writers[c].dom; + } + for (int64_t g = 0; g < r->ngroups; g++) { + pq_span fields[8]; + if (!pq_fields(r->groups[g],fields,8)) { err = pq_error("invalid row group"); goto done; } + offsets[g+1] = offsets[g]+pq_get(fields[3],0); + } + pq_direct_work work = {r,writers,offsets,nulls,locks,errors}; + ray_pool_t* pool = ray_pool_get(); + 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); + for (int64_t g = 0; g < tasks; g++) if (errors[g]) { + if (!err) err = errors[g]; else ray_release(errors[g]); + } + if (!err && ray_interrupted()) err = ray_error("cancel","parquet conversion interrupted"); + for (int64_t c = 0; c < r->ncols; c++) { + writers[c].rows = r->rows; + writers[c].had_nulls = atomic_load_explicit(&nulls[c],memory_order_relaxed) != 0; + } +done: + for (int64_t c = 0; c < r->ncols; c++) r->schema[c].import_domain = NULL; + ray_free_raw(offsets); ray_free_raw(nulls); ray_free_raw(locks); ray_free_raw(errors); return err; +} +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"); +#endif + char dest[1024]; + if (!pq_dest(dir,dest,sizeof(dest))) return pq_error("invalid or too long destination path"); + dir = dest; + ray_parquet_t* r = NULL; ray_t* err = ray_parquet_open(path,NULL,PQ_BATCH,&r); + if (err) return err; + 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; + 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); + 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; } + } + 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); + if (e != RAY_OK) goto io_fail; + } + for (int64_t c = 0; c < r->ncols; c++) { + e = ray_col_stream_index_begin(&writers[c],0); + if (e != RAY_OK) goto io_fail; + } + bool direct = true; + for (int64_t c = 0; c < r->ncols; c++) if (writers[c].type == RAY_STR) direct = false; + if (direct) { + err = pq_write_direct(r,writers); + if (err) goto done; + goto finish_columns; + } + /* Parallel decode spools bounded native batches to disk. Their ordered + * merge never retains an entire row group or the full input in RAM. */ + snprintf(spool,sizeof(spool),"%s/.groups",staging); + e = ray_mkdir(spool); if (e != RAY_OK) goto io_fail; + err = pq_write_groups(r,spool,"batch",false,&parts); + if (err) goto done; + for (int64_t part = 0; part < parts; part++) { + if (ray_interrupted()) { e = RAY_ERR_CANCEL; goto io_fail; } + snprintf(leaf,sizeof(leaf),"%s/%lld/batch",spool,(long long)part); + 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)); + if (e != RAY_OK) break; + } + ray_release(batch); + if (e != RAY_OK) goto io_fail; + /* Remove only files created by this import, after their mappings close. */ + for (int64_t c = 0; c <= r->ncols; c++) { + const char* name = c == r->ncols ? ".d" : ray_str_ptr(ray_sym_str(r->schema[c].name)); + snprintf(file,sizeof(file),"%s/%s",leaf,name); + if (remove(file)) { e = RAY_ERR_IO; goto io_fail; } + } + if (!pq_remove_dir(leaf)) { e = RAY_ERR_IO; goto io_fail; } + snprintf(leaf,sizeof(leaf),"%s/%lld",spool,(long long)part); + if (!pq_remove_dir(leaf)) { e = RAY_ERR_IO; goto io_fail; } + } + if (!pq_remove_dir(spool)) { e = RAY_ERR_IO; goto io_fail; } +finish_columns: + if (domain) { e = ray_sym_domain_flush(domain,true); if (e != RAY_OK) goto io_fail; } + /* All columns are still under a private staging directory. Commit + * their final images together below, after the hash re-read. 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 the hash re-read of the + * integer columns; reopening needs only the file-backed vocabulary. */ + if (domain) { + ray_sym_domain_release(domain); domain = NULL; + for (int64_t c = 0; c < opened; c++) writers[c].dom = NULL; + } + ray_col_stream_hash_all(writers,r->ncols,NULL); + 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++) { + ray_t* name = ray_sym_str(r->schema[c].name); + ray_t* next = ray_str_vec_append(schema,ray_str_ptr(name),ray_str_len(name)); + if (!next || RAY_IS_ERR(next)) { ray_release(schema); err = next ? next : ray_error("oom",NULL); goto done; } + schema = next; + } + snprintf(file,sizeof(file),"%s/.d",staging); + e = ray_col_save_bulk(schema,file); ray_release(schema); + if (e != RAY_OK) goto io_fail; + /* The column files already carry their index regions. Flush the final + * file images before the directory becomes visible under its published name. */ + for (int64_t c = 0; c <= r->ncols; c++) { + snprintf(file,sizeof(file),"%s/.d",staging); + const char* path = c == r->ncols ? file : writers[c].path; + ray_fd_t fd = ray_file_open(path,RAY_OPEN_READ | RAY_OPEN_WRITE); + if (fd == RAY_FD_INVALID) { e = RAY_ERR_IO; goto io_fail; } + e = ray_file_sync(fd); ray_file_close(fd); + if (e != RAY_OK) goto io_fail; + } + e = ray_file_sync_dir(file); + if (e != RAY_OK) goto io_fail; + err = pq_publish(staging,dir,r->rows); + goto done; +io_fail: + 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_t* ray_parquet_splayed(const char* path, const char* dir) { + return ray_parquet_splayed_typed(path,dir,NULL); +} +static const char* pq_path_arg(ray_t* arg) { + if (!arg || arg->type != -RAY_STR) return NULL; + const char* p = ray_str_ptr(arg); size_t n = ray_str_len(arg); + return p && n && !memchr(p,0,n) ? p : NULL; +} +ray_t* ray_parquet_metadata_fn(ray_t* path) { + const char* p = pq_path_arg(path); + return p ? ray_parquet_metadata(p) : ray_error("type","parquet.meta: path must be a nonempty string"); +} +ray_t* ray_parquet_read_fn(ray_t** args, int64_t n) { + if (n != 1 && n != 2) return ray_error("arity","parquet.read: [columns] path"); + const char* p = pq_path_arg(args[n-1]); + 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 && 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 != 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]; + const char* table = pq_path_arg(name); + return p && root && table ? ray_parquet_parted_typed(p,root,table,n == 4 ? args[0] : NULL) : ray_error("type","parquet.parted: expected paths and table name"); +} +ray_t* ray_parquet_each_fn(ray_t** args, int64_t n) { + if (n != 2 && n != 3) return ray_error("arity","parquet.each: [columns] path callback"); + const char* p = pq_path_arg(args[n-2]); ray_t* fn = args[n-1]; + if (!p || (fn->type != RAY_LAMBDA && fn->type != RAY_UNARY && fn->type != RAY_VARY)) + return ray_error("type","parquet.each: expected path and callable"); + ray_parquet_t* r = NULL; ray_t* err = pq_open_options(p,n == 3 ? args[0] : NULL,&r); + if (err) return err; + int64_t rows = 0; + for (;;) { + ray_t* batch = ray_parquet_next(r); + if (!batch) break; + if (RAY_IS_ERR(batch)) { err = batch; break; } + rows += ray_table_nrows(batch); + ray_t* result = call_fn1(fn,batch); ray_release(batch); + if (!result || RAY_IS_ERR(result)) { err = result ? result : ray_error("oom",NULL); break; } + ray_release(result); + } + ray_parquet_close(r); return err ? err : ray_i64(rows); +} + +/* Reopenable lazy source. The descriptor contains data only, never a raw + * pointer; select checks restricted mode again before opening the file. */ +ray_t* ray_parquet_scan_fn(ray_t** args, int64_t n) { + if (n < 1 || n > 2) return ray_error("arity","parquet.scan: [options] path"); + ray_t* path = args[n-1]; + if (!pq_path_arg(path)) return ray_error("type","parquet.scan: path must be a nonempty string"); + if (n == 2) { + ray_t* opts = args[0]; + ray_t* keys = opts->type == RAY_DICT ? ray_dict_keys(opts) : NULL; + if (!keys || keys->type != RAY_SYM) return pq_error("lazy scan options must be {types: [...]}"); + for (int64_t i = 0; i < keys->len; i++) { + ray_t* k = ray_sym_vec_cell(keys,i); + if (!k || (strcmp(ray_str_ptr(k),"types") && strcmp(ray_str_ptr(k),"strict"))) return pq_error("unknown lazy scan option"); + } + } + int64_t names[] = {ray_sym_intern(".parquet.source",15),ray_sym_intern(".parquet.options",16)}; + ray_t* keys = ray_vec_from_raw(RAY_SYM,names,n); + ray_t* vals = ray_list_new(n); + if (!keys || RAY_IS_ERR(keys) || !vals || RAY_IS_ERR(vals)) { + if (keys) ray_release(keys); + if (vals) ray_release(vals); + 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; } + return ray_dict_new(keys,vals); +} +static const char* pq_symbol_name(ray_t* x) { + return x && x->type == -RAY_SYM ? ray_str_ptr(ray_sym_str(x->i64)) : NULL; +} +static const char* pq_builtin_name(ray_t* x) { + const char* name = pq_symbol_name(x); + ray_t* value = name ? ray_env_get(x->i64) : NULL; + return value && value->type == RAY_LAMBDA ? NULL : name; +} +static bool pq_reserved(const char* k) { + return !strcmp(k,"from") || !strcmp(k,"where") || !strcmp(k,"by") || + !strcmp(k,"asc") || !strcmp(k,"desc") || !strcmp(k,"take") || !strcmp(k,"nearest"); +} +static int64_t pq_column_id(ray_parquet_t* r, ray_t* x) { + if (x && x->type == -RAY_SYM) + for (int64_t c = 0; c < r->ncols; c++) if (r->schema[c].name == x->i64) return c; + return -1; +} +/* Only statically transparent expressions permit projection. Unknown calls, + * lambdas and dynamic evaluation may reference columns through local scope. */ +static bool pq_references(ray_parquet_t* r, ray_t* e, uint8_t* keep, unsigned depth) { + if (!e || depth > 64) return false; + if (e->type == -RAY_SYM) { + int64_t c = pq_column_id(r,e); if (c >= 0) keep[c] = 1; + return true; + } + if (e->type == RAY_SYM) { + for (int64_t i = 0; i < e->len; i++) { + ray_t* cell = ray_sym_vec_cell(e,i); + const char* name = cell ? ray_str_ptr(cell) : NULL; + if (!name) return false; + for (int64_t c = 0; c < r->ncols; c++) + if (!strcmp(name,ray_str_ptr(ray_sym_str(r->schema[c].name)))) keep[c] = 1; + } + return true; + } + if (e->type == RAY_DICT) { + ray_t* vals = ray_dict_vals(e); + if (!vals || vals->type != RAY_LIST) return false; + for (int64_t i = 0; i < vals->len; i++) + if (!pq_references(r,ray_list_get(vals,i),keep,depth+1)) return false; + return true; + } + if (e->type == RAY_LIST) { + if (!e->len) return true; + const char* fn = pq_builtin_name(ray_list_get(e,0)); + static const char* const transparent[] = { + "+","-","*","/","mod","%","div","==","!=","<","<=",">",">=","and","or","not", + "sum","count","avg","min","max","first","last","distinct","all","any", + "abs","sqrt","floor","ceil","round","log","exp","like","within","in", + "strlen","lower","upper","year","month","day","hour","minute","second","xbar", + "if","nil?","substr","str-find" + }; + if (fn && !strcmp(fn,"let")) { + if (e->len != 4) return false; + const char* binding = pq_symbol_name(ray_list_get(e,1)); + if (!binding || !strcmp(binding,"let")) return false; + for (size_t i = 0; i < sizeof(transparent)/sizeof(*transparent); i++) + if (!strcmp(binding,transparent[i])) return false; + return pq_references(r,ray_list_get(e,2),keep,depth+1) && + pq_references(r,ray_list_get(e,3),keep,depth+1); + } + bool known = false; + for (size_t i = 0; fn && i < sizeof(transparent)/sizeof(*transparent); i++) + if (!strcmp(fn,transparent[i])) { known = true; break; } + if (!known) return false; + /* A source column shadows a function name in query scope. */ + if (pq_column_id(r,ray_list_get(e,0)) >= 0) return false; + for (int64_t i = 1; i < e->len; i++) + if (!pq_references(r,ray_list_get(e,i),keep,depth+1)) return false; + return true; + } + return e->type < RAY_TABLE; +} +/* A pushable WHERE must be entirely row-local comparisons. In particular, + * prefiltering an aggregate/vector-dependent predicate changes its meaning. */ +static bool pq_query_range(ray_parquet_t* r, ray_t* e, int64_t* column, int64_t* lo, int64_t* hi, unsigned depth) { + if (!e || e->type != RAY_LIST || e->len < 3 || depth > 64) return false; + const char* fn = pq_builtin_name(ray_list_get(e,0)); + if (!fn || pq_column_id(r,ray_list_get(e,0)) >= 0) return false; + if (!strcmp(fn,"and")) { + for (int64_t i = 1; i < e->len; i++) + if (!pq_query_range(r,ray_list_get(e,i),column,lo,hi,depth+1)) return false; + return true; + } + if (e->len != 3) return false; + ray_t* a = ray_list_get(e,1); ray_t* b = ray_list_get(e,2); + int64_t c = pq_column_id(r,a); bool reverse = false; + if (c < 0) { c = pq_column_id(r,b); b = a; reverse = true; } + bool within = !strcmp(fn,"within") && !reverse && b->type == RAY_I64 && b->len == 2; + if (c < 0 || (!within && (b->type != -RAY_I64 || b->i64 == INT64_MIN))) return false; + pq_schema* s = &r->schema[c]; + if ((s->type != RAY_I16 && s->type != RAY_I32 && s->type != RAY_I64) || + (s->converted != -1 && (s->converted < 15 || s->converted > 18))) return false; + int64_t l = INT64_MIN, h = INT64_MAX, x = within ? 0 : b->i64; + if (within) { + l = ((int64_t*)ray_data(b))[0]; h = ((int64_t*)ray_data(b))[1]; + if (l == INT64_MIN || h == INT64_MIN || l > h) return false; + } else if (!strcmp(fn,"==")) l = h = x; + else if (!strcmp(fn,reverse ? ">=" : "<=")) h = x; + else if (!strcmp(fn,reverse ? ">" : "<")) h = x-1; + else if (!strcmp(fn,reverse ? "<=" : ">=")) l = x; + else if (!strcmp(fn,reverse ? "<" : ">")) { if (x == INT64_MAX) return false; l = x+1; } + else return false; + if (*column < 0) *column = c; + if (*column == c) { if (l > *lo) *lo = l; if (h < *hi) *hi = h; } + return true; +} +/* The existing aggregation registry supplies the same null and type rules as + * native group execution. This narrow plan has one global group and bounded + * state; expressions, grouping and ordering retain the general query path. */ +typedef struct { + int64_t name, pos; + const agg_vtable_t* kernel; + void* state; + bool count; +} pq_aggregate; +static bool pq_exact_range(ray_parquet_t* r, ray_t* where) { + if (!where) return true; + if (r->filter_pos < 0 || where->type != RAY_LIST) return false; + const char* fn = pq_symbol_name(ray_list_get(where,0)); + if (fn && !strcmp(fn,"and")) { + for (int64_t i = 1; i < where->len; i++) if (!pq_exact_range(r,ray_list_get(where,i))) return false; + return true; + } + int64_t c = r->selected[r->filter_pos]; + return where->len == 3 && (pq_column_id(r,ray_list_get(where,1)) == c || pq_column_id(r,ray_list_get(where,2)) == c); +} +typedef struct { int64_t pos, lo, hi; } pq_predicate; +static bool pq_predicates(ray_parquet_t* r, ray_t* where, pq_predicate* predicates, int64_t* n) { + if (!where) return true; + if (where->type != RAY_LIST) return false; + const char* fn = pq_symbol_name(ray_list_get(where,0)); + if (fn && !strcmp(fn,"and")) { + for (int64_t i = 1; i < where->len; i++) + if (!pq_predicates(r,ray_list_get(where,i),predicates,n)) return false; + return true; + } + int64_t column = -1, lo = INT64_MIN, hi = INT64_MAX, pos = 0; + if (*n == PQ_MAX_COLS || !pq_query_range(r,where,&column,&lo,&hi,0) || column < 0) return false; + while (pos < r->noutput && r->selected[pos] != column) pos++; + 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) { + 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); + 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 : + x >= predicates[p].lo && x <= predicates[p].hi; + } + 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); + 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; +} +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); + 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_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); + } + ray_release(batch); + } +} +typedef struct { + ray_parquet_t* parent; + int64_t first, n, np; + pq_aggregate *templates, **states; + const uint32_t* gids; + const pq_predicate* predicates; + ray_t** errors; +} pq_aggregate_work; +static void pq_aggregate_group(void* ptr, uint32_t worker, int64_t start, int64_t end) { + (void)worker; pq_aggregate_work* w = ptr; + for (int64_t i = start; i < end; i++) { + ray_parquet_t* r = pq_group_reader(w->parent,w->first+i); + pq_aggregate* aggs = ray_calloc_raw((size_t)w->n*sizeof(*aggs)); + w->states[i] = aggs; + if (!r || !aggs) { w->errors[i] = ray_error("oom",NULL); ray_parquet_close(r); continue; } + for (int64_t a = 0; a < w->n; a++) { + aggs[a] = w->templates[a]; aggs[a].state = ray_alloc_raw(aggs[a].kernel->state_size); + if (!aggs[a].state) { w->errors[i] = ray_error("oom",NULL); break; } + aggs[a].kernel->init(aggs[a].state); + } + if (!w->errors[i]) w->errors[i] = pq_accumulate(r,aggs,w->n,w->gids,w->predicates,w->np); + ray_parquet_close(r); + } +} +static ray_t* pq_aggregate_groups(ray_parquet_t* r, pq_aggregate* aggs, int64_t n, + const uint32_t* gids, const pq_predicate* predicates, int64_t np) { + ray_pool_t* pool = pq_group_pool(r); + if (!pool) return pq_accumulate(r,aggs,n,gids,predicates,np); + uint32_t width = ray_pool_total_workers(pool); + if (width > RAY_POOL_INIT_TASKS) width = RAY_POOL_INIT_TASKS; + pq_aggregate** states = ray_calloc_raw((size_t)width*sizeof(*states)); + ray_t** errors = ray_calloc_raw((size_t)width*sizeof(*errors)); + ray_t* err = NULL; + if (!states || !errors) { err = ray_error("oom",NULL); goto done; } + for (int64_t first = 0; first < r->ngroups && !err; first += width) { + uint32_t count = r->ngroups-first < width ? (uint32_t)(r->ngroups-first) : width; + memset(states,0,(size_t)count*sizeof(*states)); memset(errors,0,(size_t)count*sizeof(*errors)); + pq_aggregate_work work = {r,first,n,np,aggs,states,gids,predicates,errors}; + ray_pool_dispatch_n(pool,pq_aggregate_group,&work,count); + for (uint32_t i = 0; i < count; i++) { + if (errors[i]) { if (!err) err = errors[i]; else ray_release(errors[i]); } + if (!states[i]) { if (!err) err = ray_error("cancel","parquet scan interrupted"); continue; } + for (int64_t a = 0; a < n; a++) { + if (!err) aggs[a].kernel->merge(aggs[a].state,states[i][a].state,NULL); + ray_free_raw(states[i][a].state); + } + ray_free_raw(states[i]); + } + } +done: + ray_free_raw(states); ray_free_raw(errors); return err; +} +static ray_t* pq_stream_aggregates(ray_parquet_t* r, ray_t* query, ray_t* where) { + /* A configured standalone LIKE is already fully applied by the reader. + * Otherwise range() proves row-local integer comparisons; other columns + * remain residual filters. Keep the aggregate row even for zero matches. */ + if (where && r->filter_pos < 0 && !r->text_pattern) return NULL; + bool residual = !r->text_pattern && !pq_exact_range(r,where); + pq_predicate predicates[PQ_MAX_COLS]; int64_t np = 0; + if (residual && !pq_predicates(r,where,predicates,&np)) return NULL; + ray_t* keys = ray_dict_keys(query); ray_t* vals = ray_dict_vals(query); + if (!keys || keys->type != RAY_SYM || !vals || vals->type != RAY_LIST || keys->len > PQ_MAX_COLS) return NULL; + pq_aggregate* aggs = ray_calloc_raw((size_t)keys->len*sizeof(*aggs)); + if (!aggs) return ray_error("oom",NULL); + int64_t n = 0; bool all_count = true; + ray_t* result = NULL; uint32_t* gids = NULL; + 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) goto done; + if (!strcmp(k,"from") || !strcmp(k,"where")) continue; + if (pq_reserved(k)) goto done; + ray_t* e = ray_list_get(vals,i); + if (!e || e->type != RAY_LIST || e->len != 2) goto done; + const char* fn = pq_builtin_name(ray_list_get(e,0)); + int64_t col = pq_column_id(r,ray_list_get(e,1)); + if (!fn || col < 0 || pq_column_id(r,ray_list_get(e,0)) >= 0) goto done; + uint16_t op = !strcmp(fn,"count") ? OP_COUNT : !strcmp(fn,"sum") ? OP_SUM : + !strcmp(fn,"avg") ? OP_AVG : !strcmp(fn,"min") ? OP_MIN : !strcmp(fn,"max") ? OP_MAX : 0; + int8_t type = (int8_t)r->schema[col].type; + /* Compact dictionary ids are not raw STR slots or runtime SYM ids. + * Count is representation-independent; lexical extrema use the + * general executor, which resolves the attached domain. */ + if (r->schema[col].native_symbol) { + if (op != OP_COUNT) goto done; + type = RAY_I32; + } + /* Floating summation order can differ between engines. Keep that + * execution choice in the general planner; integer averages are exact. */ + if (!op || ((op == OP_SUM || op == OP_AVG) && type != RAY_I16 && type != RAY_I32 && type != RAY_I64)) goto done; + const agg_vtable_t* kernel = agg_resolve(op,type); + if (!kernel || kernel->kind != ACC_STREAMING || !kernel->finalize_value || !kernel->update_batch || !kernel->merge) goto done; + int64_t pos = 0; + while (pos < r->noutput && r->selected[pos] != col) pos++; + if (pos == r->noutput) goto done; + aggs[n] = (pq_aggregate){ray_sym_intern(k,strlen(k)),pos,kernel,NULL,op == OP_COUNT}; + if (op != OP_COUNT) all_count = false; + n++; + } + if (!n) goto done; + for (int64_t a = 0; a < n; a++) { + aggs[a].state = ray_alloc_raw(aggs[a].kernel->state_size); + if (!aggs[a].state) { result = ray_error("oom",NULL); goto done; } + aggs[a].kernel->init(aggs[a].state); + } + if (!(all_count && !where)) { + gids = ray_calloc_raw(PQ_BATCH*sizeof(*gids)); + if (!gids) { result = ray_error("oom",NULL); goto done; } + result = pq_aggregate_groups(r,aggs,n,gids,predicates,np); + if (result) goto done; + } + result = ray_table_new(n); + if (!result) result = ray_error("oom",NULL); + if (RAY_IS_ERR(result)) goto done; + for (int64_t a = 0; a < n; a++) { + ray_t* v = ray_vec_new(aggs[a].kernel->out_type,1); + if (!v || RAY_IS_ERR(v)) { ray_release(result); result = v ? v : ray_error("oom",NULL); goto done; } + v->len = 1; + if (all_count && !where) ((int64_t*)ray_data(v))[0] = r->rows; + else if (aggs[a].kernel->finalize_value(aggs[a].state,ray_data(v))) v->attrs |= RAY_ATTR_HAS_NULLS; + result = ray_table_add_col(result,aggs[a].name,v); ray_release(v); + if (!result) result = ray_error("oom",NULL); + if (RAY_IS_ERR(result)) break; + } +done: + for (int64_t a = 0; a < n; a++) ray_free_raw(aggs[a].state); + ray_free_raw(aggs); ray_free_raw(gids); + return result; +} +ray_t* ray_parquet_select_source(ray_t* source, ray_t* query, bool* complete) { + *complete = false; + if (!source || source->type != RAY_DICT || ray_dict_len(source) < 1 || ray_dict_len(source) > 2) return NULL; + ray_t* path = pq_option(source,".parquet.source"); + if (!path) return NULL; + if (ray_eval_get_restricted()) { ray_release(path); return ray_error("access","restricted"); } + const char* p = pq_path_arg(path); + if (!p) { ray_release(path); return pq_error("invalid lazy source path"); } + ray_parquet_t* r = NULL; + ray_t* err = ray_parquet_open(p,NULL,PQ_BATCH,&r); ray_release(path); + if (err) return err; + ray_t* options = pq_option(source,".parquet.options"); + if (options) { + ray_t* types = options->type == RAY_DICT ? pq_option(options,"types") : NULL; + err = options->type == RAY_DICT ? pq_scan_types(r,types) : pq_error("invalid lazy scan options"); + if (!err) err = pq_strict_option(r,options); + if (types) ray_release(types); + ray_release(options); + if (err) { ray_parquet_close(r); return err; } + } + uint8_t* keep = ray_calloc_raw((size_t)r->ncols); + if (!keep) { ray_parquet_close(r); return ray_error("oom",NULL); } + ray_t* keys = ray_dict_keys(query); ray_t* vals = ray_dict_vals(query); + bool project = keys && keys->type == RAY_SYM && vals && vals->type == RAY_LIST; + bool explicit = false; + for (int64_t i = 0; project && i < keys->len; i++) { + ray_t* key = ray_sym_vec_cell(keys,i); const char* k = key ? ray_str_ptr(key) : NULL; + if (!k) { project = false; break; } + if (!strcmp(k,"from")) continue; + if (!pq_reserved(k)) explicit = true; + project = pq_references(r,ray_list_get(vals,i),keep,0); + } + if (project && explicit) { + int64_t n = 0; + for (int64_t c = 0; c < r->ncols; c++) if (keep[c]) r->selected[n++] = (int32_t)c; + /* Keep a column for row cardinality when outputs contain only constants. */ + if (!n) { r->selected[0] = 0; n = 1; } + r->nselected = r->noutput = n; + } + ray_free_raw(keep); + ray_t* where = pq_option(query,"where"); + int64_t col = -1, lo = INT64_MIN, hi = INT64_MAX; + if (pq_query_range(r,where,&col,&lo,&hi,0) && col >= 0 && lo <= hi) { + err = ray_parquet_range(r,r->schema[col].name,lo,hi); + /* Query bounds use INT64_MIN only for an absent lower bound: literal + * nulls are rejected by pq_query_range. Rayforce nulls sort first. */ + if (!err) r->filter_nulls = lo == INT64_MIN; + } + /* A standalone LIKE is row-local. Retain the ordinary WHERE as well so + * all later query stages use the same language semantics. */ + if (!err && where && where->type == RAY_LIST && where->len == 3) { + const char* fn = pq_builtin_name(ray_list_get(where,0)); + int64_t c = pq_column_id(r,ray_list_get(where,1)); + ray_t* pat = ray_list_get(where,2); + if (fn && !strcmp(fn,"like") && pq_column_id(r,ray_list_get(where,0)) < 0 && + c >= 0 && r->schema[c].type == RAY_STR && pat && pat->type == -RAY_STR) { + for (int64_t i = 0; i < r->nselected; i++) if (r->selected[i] == c) { + r->text_pos = i; r->text_pattern = pat; ray_retain(pat); break; + } + } + } + ray_t* streamed = err ? NULL : pq_stream_aggregates(r,query,where); + if (where) ray_release(where); + if (err) { ray_parquet_close(r); return err; } + if (streamed) { *complete = true; ray_parquet_close(r); return streamed; } + return pq_materialize(r); +} diff --git a/src/io/parquet.h b/src/io/parquet.h new file mode 100644 index 000000000..b9e1b98fd --- /dev/null +++ b/src/io/parquet.h @@ -0,0 +1,58 @@ +#ifndef RAY_PARQUET_H +#define RAY_PARQUET_H + +#include + +/* Flat Parquet reader. All implementation and codecs are dependency-free. + * A reader owns its mapping and reusable page buffers. next() returns an + * OWNED table, independent of the reader; NULL means EOF. Errors are owned. + * columns is a borrowed SYM vector (NULL = all). No file data is decoded at + * open. batch_rows bounds rows per returned table, not compressed page size. + * Public reader calls stay on the opening thread. next() may dispatch + * independent column cursors to the native pool and joins before returning. */ +typedef struct ray_parquet ray_parquet_t; +ray_t* ray_parquet_open(const char* path, ray_t* columns, int64_t batch_rows, + ray_parquet_t** out); +ray_t* ray_parquet_next(ray_parquet_t* reader); +/* Inclusive integer range; applies exact filtering as well as conservative + * row-group/page pruning and equality Bloom probes. Configure once, before + * next(). Filter column need not be projected. Signed integer columns only. */ +ray_t* ray_parquet_range(ray_parquet_t* reader, int64_t column, int64_t lo, int64_t hi); +int64_t ray_parquet_groups_skipped(const ray_parquet_t* reader); +/* Counters are cumulative; pages count physical column data pages bypassed + * during interval pruning. bloom_skipped is a subset of groups_skipped. */ +int64_t ray_parquet_pages_skipped(const ray_parquet_t* reader); +int64_t ray_parquet_bloom_skipped(const ray_parquet_t* reader); +int64_t ray_parquet_parallel_batches(const ray_parquet_t* reader); +void ray_parquet_close(ray_parquet_t* reader); +ray_t* ray_parquet_metadata(const char* path); +/* options: NULL, projected SYM column names, or {columns, types, range, strict}. + * types covers the full file schema. SYM text uses a private refcounted domain. */ +ray_t* ray_parquet_read(const char* path, ray_t* options); +/* Native imports return an owned row-count atom/error and publish a NEW + * destination after writes complete. Typed schemas are positional SYM vectors; + * SYM encodes text, integer widths are checked, and raw integer temporal values + * require explicit UNIX_DATE/UNIX_SECONDS/UNIX_MILLIS/UNIX_MICROS/UNIX_NANOS. + * Annotated DATE/TIMESTAMP retain their declared units. NULL uses file types. + * An options dictionary may supply types, rows (1..1048576) and strict. Strict + * mode rejects decoded null/value collisions and invalid annotated UTF-8. */ +ray_t* ray_parquet_splayed_typed(const char* path, const char* dir, ray_t* types); +ray_t* ray_parquet_parted_typed(const char* path, const char* root, const char* table, ray_t* types); +ray_t* ray_parquet_splayed(const char* path, const char* dir); +ray_t* ray_parquet_parted(const char* path, const char* root, const char* table); + +/* Raw Snappy block (Parquet framing). Exact input/output lengths required. + * Exposed internally for codec regression tests. */ +bool ray_parquet_snappy(const uint8_t* src, size_t len, uint8_t* dst, size_t size); + +/* Returns NULL for a non-Parquet source; otherwise an owned table/error. + * complete=true means a streaming aggregate already answered the query. */ +ray_t* ray_parquet_select_source(ray_t* source, ray_t* query, bool* complete); +ray_t* ray_parquet_scan_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_read_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_metadata_fn(ray_t* path); +ray_t* ray_parquet_splayed_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_parted_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_each_fn(ray_t** args, int64_t n); + +#endif diff --git a/src/lang/eval.c b/src/lang/eval.c index 4e1b53429..a5f1d89c3 100644 --- a/src/lang/eval.c +++ b/src/lang/eval.c @@ -3071,6 +3071,17 @@ vm_error_cleanup: { * to any `.`-prefixed name are refused by ray_env_set, so user code * can't drift them apart. Only 2-level namespaces are in use; the * assert below guards against silent breakage if that changes. */ +/* Builtin registration runs once at startup with no caller to report to, so + * a failure is fatal. It is checked explicitly and never inside assert(): + * an -DNDEBUG build compiles an assert away, work and all — the binds below + * once lived inside one, and such a build started with no builtins (#652). */ +static void reg_check(bool ok, const char* name, const char* what) { + if (ok) return; + fprintf(stderr, "rayforce: cannot register builtin %s: %s\n", + name ? name : "(namespace)", what); + abort(); +} + /* Get-or-create a child dict by key on `parent`. ray_dict_get * returns an owned ref (or NULL if missing), so we either reuse it * (after type-checking) or build a fresh subdict and upsert it. @@ -3086,9 +3097,10 @@ static ray_t* dict_get_or_create_subdict(ray_t* parent, ray_t* key, if (existing) ray_release(existing); ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 4); ray_t* vals = ray_list_new(4); - assert(keys && !RAY_IS_ERR(keys) && vals && !RAY_IS_ERR(vals)); + reg_check(keys && !RAY_IS_ERR(keys) && vals && !RAY_IS_ERR(vals), + NULL, "out of memory"); ray_t* child = ray_dict_new(keys, vals); - assert(child && !RAY_IS_ERR(child)); + reg_check(child && !RAY_IS_ERR(child), NULL, "out of memory"); ray_retain(child); /* caller retains; dict_upsert below also retains */ parent = ray_dict_upsert(parent, key, child); *out_child = child; @@ -3112,9 +3124,10 @@ static void reg_bind(const char* name, ray_t* obj) { } else { ray_t* keys = ray_sym_vec_new(RAY_SYM_W64, 4); ray_t* vals = ray_list_new(4); - assert(keys && !RAY_IS_ERR(keys) && vals && !RAY_IS_ERR(vals)); + reg_check(keys && !RAY_IS_ERR(keys) && vals && !RAY_IS_ERR(vals), + name, "out of memory"); root = ray_dict_new(keys, vals); - assert(root && !RAY_IS_ERR(root)); + reg_check(root && !RAY_IS_ERR(root), name, "out of memory"); } /* 2. For each intermediate segment, descend into (or create) @@ -3159,12 +3172,13 @@ static void reg_bind(const char* name, ray_t* obj) { * highlighting) enumerates every reserved builtin by name. * ray_env_bind_flat skips the dotted-walk so this doesn't * re-upsert into the same dict we just built. */ - assert(ray_env_bind(root_sym, chain[0]) == RAY_OK); + reg_check(ray_env_bind(root_sym, chain[0]) == RAY_OK, name, + "binding its namespace root failed"); ray_release(chain[0]); - assert(ray_env_bind_flat(sym, obj) == RAY_OK); + reg_check(ray_env_bind_flat(sym, obj) == RAY_OK, name, "binding failed"); return; } - assert(ray_env_bind(sym, obj) == RAY_OK); + reg_check(ray_env_bind(sym, obj) == RAY_OK, name, "binding failed"); } static void register_binary(const char* name, uint8_t attrs, ray_binary_fn fn) { @@ -3397,6 +3411,12 @@ static void ray_register_builtins(void) { register_vary(".csv.splayed", RAY_FN_RESTRICTED, ray_read_csv_splayed_fn); register_vary(".csv.parted", RAY_FN_RESTRICTED, ray_read_csv_parted_fn); register_vary(".csv.write", RAY_FN_RESTRICTED, ray_write_csv_fn); + register_vary(".parquet.scan", RAY_FN_RESTRICTED, ray_parquet_scan_fn); + register_unary(".parquet.meta", RAY_FN_RESTRICTED, ray_parquet_metadata_fn); + register_vary(".parquet.read", RAY_FN_RESTRICTED, ray_parquet_read_fn); + register_vary(".parquet.each", RAY_FN_RESTRICTED, ray_parquet_each_fn); + register_vary(".parquet.splayed", RAY_FN_RESTRICTED, ray_parquet_splayed_fn); + register_vary(".parquet.parted", RAY_FN_RESTRICTED, ray_parquet_parted_fn); register_binary("as", RAY_FN_NONE, ray_cast_fn); register_unary("type", RAY_FN_NONE, ray_type_fn); register_unary("read", RAY_FN_RESTRICTED, ray_read_file_fn); @@ -3514,7 +3534,7 @@ static void ray_register_builtins(void) { /* IPC client primitives under `.ipc.*` */ register_vary( ".ipc.open", RAY_FN_RESTRICTED, ray_hopen_fn); register_unary( ".ipc.close", RAY_FN_RESTRICTED, ray_hclose_fn); - register_binary(".ipc.send", RAY_FN_RESTRICTED, ray_hsend_fn); + register_vary( ".ipc.send", RAY_FN_RESTRICTED, ray_hsend_fn); register_binary(".ipc.post", RAY_FN_RESTRICTED, ray_hpost_fn); /* Current connection handle inside any `.ipc.on.*` hook, -1 otherwise. * Variadic for the `(.ipc.handle)` / `(.ipc.handle 0)` convention. */ diff --git a/src/lang/format.c b/src/lang/format.c index dd56ce50b..6c054f6d1 100644 --- a/src/lang/format.c +++ b/src/lang/format.c @@ -46,8 +46,16 @@ typedef struct { * Once set, every append is a no-op and fmt_to_str * returns an error instead of a string. */ const char* err_msg;/* why err was set, surfaced by fmt_to_str */ + FILE* sink; /* when set, full content is written here and the + * buffer emptied as it passes FMT_SINK_FLUSH bytes; + * only for modes that never read back what they + * appended (mode 2) */ + bool io_err; /* err was a failed write to sink */ + bool flushed; /* some output already reached sink */ } fmt_buf_t; +#define FMT_SINK_FLUSH ((int64_t)1 << 20) + /* The fmt_* append helpers are all void and have no caller to return an error * to, so a growth failure (the 2GiB int32 buffer ceiling, or a ray_alloc that * fails under memory pressure) sets the sticky `err` flag instead of writing @@ -60,6 +68,9 @@ typedef struct { static void fmt_init(fmt_buf_t* b) { b->err = false; b->err_msg = NULL; + b->sink = NULL; + b->io_err = false; + b->flushed = false; 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"; @@ -90,6 +101,14 @@ static void fmt_ensure(fmt_buf_t* b, int64_t extra) { * negative extra, need = len + extra < len <= cap, so the fast path would * otherwise return first and leave the bad length to a wild memcpy. */ if (extra < 0) { b->err = true; b->err_msg = "invalid negative format length"; return; } + if (b->sink && b->len > 0 && (int64_t)b->len + extra > FMT_SINK_FLUSH) { + if (fwrite(b->buf, 1, (size_t)b->len, b->sink) != (size_t)b->len) { + b->err = true; b->io_err = true; b->err_msg = "cannot write formatted output"; + return; + } + b->len = 0; + b->flushed = true; + } int64_t need = (int64_t)b->len + extra; if (need <= (int64_t)b->cap) return; if (need > (int64_t)INT32_MAX) { @@ -782,7 +801,9 @@ 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, ' '); } -/* Maximum pre-formatted cells: FMT_TABLE_MAX_WIDTH * FMT_TABLE_MAX_HEIGHT = 200 */ +/* 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). */ #define FMT_CELL_BUF_SIZE 64 typedef struct { @@ -790,6 +811,133 @@ typedef struct { int32_t len; } fmt_cell_t; +/* Table in full into a sink-backed buffer (show). A first pass measures + * 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, + 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); + *s = tmp->buf; + *len = tmp->len; /* whole cell: tmp grows, unlike the REPL's fixed grid */ +} + +static void fmt_stream_rule(fmt_buf_t* b, const int32_t* w, int64_t n, + const char* left, const char* mid, const char* right) { + fmt_puts(b, left); + for (int64_t ci = 0; ci < n; ci++) { + for (int32_t j = 0; j < w[ci]; j++) fmt_puts(b, G_H); + fmt_puts(b, ci < n - 1 ? mid : right); + } +} + +/* Widest a streamed column is padded to, in display columns. A longer cell + * is written whole, unpadded, past the border of its own row: padding every + * row to the longest cell made the output rows x longest cell (one 10 KB + * value in 10k rows wrote 100 MB of spaces). */ +#define FMT_SHOW_PAD_MAX 256 + +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); + if (ncols <= 0) { fmt_puts(b, ""); return; } + + 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*)); + fmt_buf_t tmp; + fmt_init(&tmp); + if (!wblk || !nblk || 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); + + 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); + 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; + for (int64_t ri = 0; ri < nrows && cell_w < FMT_SHOW_PAD_MAX; ri++) { + const char* cs; int32_t cl; + fmt_stream_cell(&tmp, col, ri, &cs, &cl); + if (tmp.err) { b->err = true; b->err_msg = "out of memory formatting a table"; goto done; } + int32_t dw = fmt_utf8_width(cs, cl); + if (dw > cell_w) cell_w = dw; + } + if (cell_w > FMT_SHOW_PAD_MAX) cell_w = FMT_SHOW_PAD_MAX; + if (cell_w > w) w = cell_w; + widths[ci] = w + 2; /* one space of padding on each side */ + } + + int32_t total = (int32_t)(ncols - 1); + for (int64_t ci = 0; ci < ncols; ci++) total += widths[ci]; + char footer[128]; + int footer_len = snprintf(footer, sizeof(footer), + " %" PRId64 " rows (%" PRId64 " shown) %" PRId64 " columns (%" PRId64 " shown)", + nrows, nrows, ncols, ncols); + if (total < footer_len) { widths[ncols - 1] += footer_len - total; total = footer_len; } + + fmt_stream_rule(b, widths, ncols, G_TL, G_TT, G_TR); + fmt_putc(b, '\n'); + fmt_puts(b, G_V); + for (int64_t ci = 0; ci < ncols; ci++) { + if (names[ci]) fmt_centered(b, ray_str_ptr(names[ci]), (int32_t)ray_str_len(names[ci]), widths[ci]); + else fmt_centered(b, "?", 1, widths[ci]); + fmt_puts(b, G_V); + } + 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); + fmt_centered(b, tname, (int32_t)strlen(tname), widths[ci]); + fmt_puts(b, G_V); + } + fmt_putc(b, '\n'); + fmt_stream_rule(b, widths, ncols, G_LT, G_X, G_RT); + for (int64_t ri = 0; ri < nrows && !b->err; ri++) { + fmt_putc(b, '\n'); + 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); + 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); + /* a cell past FMT_SHOW_PAD_MAX gets no padding (p <= 0) */ + for (int32_t p = widths[ci] - fmt_utf8_width(cs, cl) - 1; p > 0; p--) fmt_putc(b, ' '); + fmt_puts(b, G_V); + } + } + fmt_putc(b, '\n'); + fmt_stream_rule(b, widths, ncols, G_LT, G_BT, G_RT); + fmt_putc(b, '\n'); + fmt_puts(b, G_V); + fmt_putn(b, footer, footer_len); + for (int32_t i = footer_len; i < total; i++) fmt_putc(b, ' '); + fmt_puts(b, G_V); + fmt_putc(b, '\n'); + fmt_puts(b, G_BL); + for (int32_t i = 0; i < total; i++) fmt_puts(b, G_H); + fmt_puts(b, G_BR); + +done: + if (nblk) { + ray_t** nm = (ray_t**)ray_data(nblk); + for (int64_t ci = 0; ci < ncols; ci++) if (nm[ci]) ray_release(nm[ci]); + ray_free(nblk); + } + if (wblk) ray_free(wblk); + fmt_destroy(&tmp); +} + 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); @@ -819,6 +967,7 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { } /* Full mode (1) and show mode (2) */ + if (mode == 2 && b->sink) { fmt_table_stream(b, tbl); return; } int64_t table_width = ncols; int64_t table_height = nrows; @@ -883,6 +1032,14 @@ static void fmt_table(fmt_buf_t* b, ray_t* tbl, int mode) { heap_tlen_blk = ray_alloc((size_t)(table_width * (int64_t)sizeof(int32_t))); heap_refs_blk = ray_alloc((size_t)(table_width * (int64_t)sizeof(ray_t*))); heap_cells_blk = ray_alloc((size_t)(table_width * table_height * (int64_t)sizeof(fmt_cell_t))); + if (!heap_widths_blk || !heap_names_blk || !heap_nlen_blk || !heap_types_blk || + !heap_tlen_blk || !heap_refs_blk || !heap_cells_blk) { + ray_t* blks[7] = { heap_widths_blk, heap_names_blk, heap_nlen_blk, heap_types_blk, + heap_tlen_blk, heap_refs_blk, heap_cells_blk }; + for (int k = 0; k < 7; k++) if (blks[k]) ray_free(blks[k]); + b->err = true; b->err_msg = "out of memory formatting a table"; + return; + } col_widths = (int32_t*)ray_data(heap_widths_blk); col_names = (const char**)ray_data(heap_names_blk); @@ -1304,3 +1461,26 @@ void ray_fmt_pp_print(FILE* fp, ray_t* obj) { ray_release(s); } } + +/* 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) { + fmt_buf_t b; + fmt_init(&b); + if (b.err) return RAY_ERR_OOM; + b.sink = fp; + 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; + 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 + * the value a second time. */ + if (e == RAY_ERR_OOM && b.flushed) { + fputs("\nerror: out of memory\n", fp); + e = RAY_ERR_IO; + } + fmt_destroy(&b); + return e; +} diff --git a/src/lang/format.h b/src/lang/format.h index 5c8ae2721..26461165c 100644 --- a/src/lang/format.h +++ b/src/lang/format.h @@ -49,6 +49,12 @@ void ray_fmt_pp_print(FILE* fp, ray_t* obj); /* Format and write to FILE* */ 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); + /* Display settings */ void ray_fmt_set_precision(int digits); void ray_fmt_set_width(int cols); diff --git a/src/lang/internal.h b/src/lang/internal.h index 0a28a7dbf..405060def 100644 --- a/src/lang/internal.h +++ b/src/lang/internal.h @@ -105,9 +105,15 @@ static inline int is_temporal(ray_t* x) { * DATE = days since epoch -> ns, TIME = ms since midnight -> ns, TIMESTAMP = ns */ static inline int64_t temporal_as_ns(ray_t* x) { if (x->type == -RAY_TIMESTAMP) return x->i64; - if (x->type == -RAY_DATE) return (int64_t)x->i32 * 86400000000000LL; - if (x->type == -RAY_TIME) return (int64_t)x->i32 * 1000000LL; - return 0; + int64_t unit = x->type == -RAY_DATE ? 86400000000000LL + : x->type == -RAY_TIME ? 1000000LL : 0; + if (!unit) return 0; + /* Saturating: a date outside the TIMESTAMP range still orders past + * every timestamp, instead of overflowing. */ + int64_t ns; + if (__builtin_mul_overflow((int64_t)x->i32, unit, &ns)) + return x->i32 < 0 ? INT64_MIN + 1 : INT64_MAX; + return ns; } /* Extract integer value from any integer atom as int64_t */ @@ -215,13 +221,23 @@ static inline ray_t* make_typed_int(int8_t atom_type, int64_t val) { * ══════════════════════════════════════════ */ /* Logical -- coerce to truthiness (0/nil/false = falsy, else truthy). - * Null forms (RAY_NULL singleton and typed null atoms) are falsy. */ + * Null forms (RAY_NULL singleton and typed null atoms) are falsy, and so is + * a zero of any numeric or temporal type: only I64 and F64 zeros used to + * be, so `(if (as 'i32 0) 1 2)` took the then-branch. */ static inline int is_truthy(ray_t* x) { if (RAY_IS_NULL(x) || RAY_ATOM_IS_NULL(x)) return 0; - if (x->type == -RAY_BOOL) return x->b8; - if (x->type == -RAY_I64) return x->i64 != 0; - if (x->type == -RAY_F64) return x->f64 != 0.0; - return 1; /* non-null objects are truthy */ + switch (x->type) { + case -RAY_BOOL: return x->b8 != 0; + case -RAY_U8: return x->u8 != 0; + case -RAY_I16: return x->i16 != 0; + case -RAY_I32: return x->i32 != 0; + case -RAY_I64: case -RAY_DATE: case -RAY_TIME: case -RAY_TIMESTAMP: + return x->i64 != 0; + case -RAY_F32: case -RAY_F64: /* F32 atoms are stored widened */ + return x->f64 != 0.0 && x->f64 == x->f64; + default: + return 1; /* non-null objects are truthy */ + } } /* ══════════════════════════════════════════ @@ -354,7 +370,11 @@ static inline int store_typed_elem(ray_t* vec, int64_t i, ray_t* elem) { case RAY_I16: ((int16_t*)ray_data(vec))[i] = NULL_I16; break; default: { - int esz = ray_elem_size(vec->type); + /* A SYM cell is 1, 2, 4 or 8 bytes by the vector's width; + * ray_elem_size(SYM) is the 8 of the widest, which cleared + * the next cells of a narrow column and wrote past its end. */ + int esz = vec->type == RAY_SYM ? ray_sym_elem_size(vec->type, vec->attrs) + : ray_elem_size(vec->type); memset((char*)ray_data(vec) + i * esz, 0, esz); break; } @@ -651,7 +671,7 @@ ray_t* ray_ser_fn(ray_t* val); ray_t* ray_de_fn(ray_t* val); ray_t* ray_hopen_fn(ray_t** args, int64_t n); ray_t* ray_hclose_fn(ray_t* x); -ray_t* ray_hsend_fn(ray_t* handle, ray_t* msg); +ray_t* ray_hsend_fn(ray_t** args, int64_t n); ray_t* ray_hpost_fn(ray_t* handle, ray_t* msg); ray_t* ray_ipc_handle_fn(ray_t** args, int64_t n); ray_t* ray_ipc_txlimit_fn(ray_t** args, int64_t n); @@ -692,6 +712,12 @@ ray_t* ray_timeit_fn(ray_t** args, int64_t n); ray_t* ray_exit_fn(ray_t* arg); ray_t* ray_read_csv_fn(ray_t** args, int64_t n); ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_read_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_scan_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_metadata_fn(ray_t* path); +ray_t* ray_parquet_each_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_splayed_fn(ray_t** args, int64_t n); +ray_t* ray_parquet_parted_fn(ray_t** args, int64_t n); ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n); ray_t* ray_write_csv_fn(ray_t** args, int64_t n); ray_t* ray_cast_fn(ray_t* type_sym, ray_t* val); diff --git a/src/mem/heap.c b/src/mem/heap.c index 02e41fe55..4d6634923 100644 --- a/src/mem/heap.c +++ b/src/mem/heap.c @@ -340,7 +340,7 @@ void ray_mem_trace_end(ray_mem_trace_t* out) { * When a new anon mapping would push this past the watermark, it is routed to a * spill file instead — this never rejects work, it just picks disk over RAM. */ static _Atomic(int64_t) g_anon_committed = 0; -static _Atomic(int64_t) g_anon_watermark = 0; /* 0 = default to physical RAM */ +static _Atomic(int64_t) g_anon_watermark = 0; /* 0 = default to ray_sys_ram_limit() */ static _Atomic(int64_t) g_anon_peak = 0; /* high-water of g_anon_committed */ /* Commit `bytes` of anonymous (RAM-resident) footprint and advance the peak @@ -359,10 +359,12 @@ static void heap_anon_commit(int64_t bytes) { } /* Threshold above which anon allocations spill to disk. Default keeps our - * anon footprint within physical RAM (swap + page cache stay as headroom). */ + * anon footprint within the RAM the process may actually use — physical RAM, + * or the container's cgroup limit when that is smaller (#688); swap + page + * cache stay as headroom. */ static int64_t heap_anon_watermark(void) { int64_t wm = atomic_load_explicit(&g_anon_watermark, memory_order_relaxed); - return wm > 0 ? wm : ray_sys_total_ram(); + return wm > 0 ? wm : ray_sys_ram_limit(); } /* True if committing `bytes` more anonymous RAM would cross the watermark. */ static bool heap_anon_would_exceed(size_t bytes) { @@ -1200,8 +1202,8 @@ static void ray_detach_owned_refs(ray_t* v) { * anonymous mmap was refused. Mirrors heap_add_pool's swap fallback but at the * exact size — a direct block needs no pool alignment (it is located by its * stored map_size, not by pool-base masking), so a plain mmap suffices. - * Returns the mapped base and the fd/path to close+unlink at free; NULL on - * failure. */ + * Returns the mapped base and the fd to close at free (*out_path is NULL: the + * file is already unlinked); NULL on failure. */ static void* heap_direct_map_file(ray_heap_t* h, size_t map_size, int* out_fd, char** out_path) { #if !RAY_HEAP_FILE_SPILL @@ -1234,8 +1236,14 @@ static void* heap_direct_map_file(ray_heap_t* h, size_t map_size, /* Count as committed working set — a RAM substitute with preallocated * blocks (matches heap_add_pool's swap-pool accounting). */ ray_sys_track_add((int64_t)map_size); + /* Unlink now that the mapping holds the inode, as heap_add_pool does: + * the kernel reclaims the blocks on munmap or at process exit. Left + * until ray_free, a process that exited or was killed holding the block + * left the whole file on disk. */ + unlink(path); + ray_sys_free(path); *out_fd = fd; - *out_path = path; + *out_path = NULL; return mapped; #endif /* RAY_HEAP_FILE_SPILL */ } @@ -2775,10 +2783,12 @@ void ray_heap_merge(ray_heap_t* src) { dst->pools[dst->pool_count++] = src->pools[i]; } else { /* Pool overflow: only triggers at RAY_MAX_POOLS (512 pools = 16GB+). - * Fix ownership so blocks free to the correct heap. */ - ray_pool_hdr_t* hdr = (ray_pool_hdr_t*)src->pools[i].base; - hdr->heap_id = dst->id; - assert(0 && "ray_heap_merge: pool overflow at RAY_MAX_POOLS"); + * dst cannot track the pool, so it could never be released — + * fatal in every build. Explicit rather than assert(0): under + * -DNDEBUG that compiled away and the pool leaked silently (#652). */ + fprintf(stderr, "rayforce: ray_heap_merge: pool overflow at " + "RAY_MAX_POOLS (%d)\n", (int)RAY_MAX_POOLS); + abort(); } } src->pool_count = 0; diff --git a/src/mem/heap.h b/src/mem/heap.h index 84a258285..7c42d8497 100644 --- a/src/mem/heap.h +++ b/src/mem/heap.h @@ -331,7 +331,8 @@ static inline bool ray_direct_file_backed(const ray_t* v) { /* Anonymous (RAM-resident, OOM-killable) pool + direct bytes currently * committed by the heap. Allocations that would push this past the anon - * watermark (default: total physical RAM) are backed by a disk spill file + * watermark (default: physical RAM, or the container's cgroup memory limit + * when that is smaller — ray_sys_ram_limit) are backed by a disk spill file * instead — file-backed pages are always reclaimable, so they cannot trigger * the OOM killer. ray_heap_set_anon_watermark overrides the threshold (0 * restores the default); intended for diagnostics and tests. */ @@ -340,7 +341,7 @@ int64_t ray_heap_anon_committed(void); * peak RAM an operator actually demanded (pools + direct; excludes spill). */ int64_t ray_heap_anon_peak(void); /* Current anon watermark in bytes (the effective spill threshold; resolves 0 - * to total physical RAM). */ + * to ray_sys_ram_limit()). */ int64_t ray_heap_anon_watermark(void); void ray_heap_set_anon_watermark(int64_t bytes); /* Release every block held by the direct-allocation reuse cache back to diff --git a/src/ops/agg_engine.c b/src/ops/agg_engine.c index 984faff60..836ba4edc 100644 --- a/src/ops/agg_engine.c +++ b/src/ops/agg_engine.c @@ -17,6 +17,7 @@ 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 */ static _Thread_local agg_route_stats_t route_stats; void agg_route_reset(void) { memset(&route_stats, 0, sizeof(route_stats)); } @@ -26,7 +27,8 @@ void agg_route_record(agg_route_t route) { static const char* const names[AGG_ROUTE_COUNT] = { "group: none", "group: legacy", "group: slices", "group: parted", "group: v2 serial dense", "group: v2 serial hash", "group: v2 dense", - "group: v2 radix", "group: v2 hash", "group: v2 smallhash", "group: v2 indexed" + "group: v2 radix", "group: v2 hash", "group: v2 smallhash", "group: v2 indexed", + "group: v2 tablestack" }; route_stats.routes[route]++; ray_profile_tick(names[route]); @@ -2987,10 +2989,16 @@ static ray_t* exec_group_v2_parallel_smallhash( * so each can be grouped+accumulated fully in parallel with NO cross-partition * merge — eliminating the serial Phase-B bottleneck of the hash path. * - * Phase 1 (parallel over rows): scatter each row's INDEX into a per-(worker, - * partition) growable int64 buffer keyed by the hash partition. - * Phase 2 (parallel over partitions): gather all workers' index buffers for - * partition p; build a small open-addressing hash over those rows + * Phase 1 (parallel over fixed input chunks): two-pass radix partitioning + * with exact offsets. Pass 1 counts, per (chunk, partition), the + * rows hashing to each partition; a prefix sum turns the counts into + * each (chunk, partition)'s exact slot range inside ONE payload + * array allocated once; pass 2 reads back each row's partition id + * (stored by pass 1) and writes its packed record at its slot. + * Partition p's records are contiguous and in ascending input + * order (chunk order, then row order). + * Phase 2 (parallel over partitions): walk partition p's contiguous + * records; build a small open-addressing hash over those rows * (keys disjoint from other partitions); assign partition-local gids * (first_row = MIN row), init each agg state on first key sight, * batch-update each agg from a gathered value column. @@ -3012,31 +3020,38 @@ static uint32_t agg_radix_part_count(uint32_t nworkers, int64_t nrows) { return n; } -/* Growable contiguous PAYLOAD buffer (per worker, per partition). Phase 1 - * scatters one fixed-size record per row instead of a bare row index: the - * record packs [n_keys×int64 widened keys][agg input value(s) at native esz] - * [row_idx int64]. Phase 2 then groups+accumulates each partition by walking - * its records SEQUENTIALLY — hash/equality compare the contiguous packed keys - * and accumulation reads values from the contiguous record — trading a one-time - * scatter cost for cache-friendly Phase-2 reads (the memory-bound hot spot was - * agg_tuple_eq re-reading scattered key columns on every distinct insert). */ -typedef struct { char* buf; uint32_t n, cap; } agg_pay_buf_t; /* n = #records */ - -/* Reserve room for one more record of `rec` bytes; returns dest ptr or NULL. */ -static char* agg_pay_reserve(agg_pay_buf_t* b, size_t rec, uint32_t cap0) { - if (b->n == b->cap) { - if (b->cap > UINT32_MAX / 2) return NULL; - /* First allocation jumps straight to the caller's expected row count - * (uniform-hash estimate). Growing 1->2->4->... instead re-copies the - * whole payload ~2x across tens of thousands of per-(worker,partition) - * buffers — the memmove was 23% of ClickBench q17. */ - uint32_t nc = b->cap ? b->cap * 2 : (cap0 ? cap0 : 1); - char* nb = ray_realloc_raw(b->buf, (size_t)nc * rec); - if (!nb) return NULL; - b->buf = nb; b->cap = nc; - } - return b->buf + (size_t)b->n++ * rec; -} +/* PAYLOAD layout. Phase 1 scatters one fixed-size record per row instead of a + * bare row index: the record packs [n_keys×int64 widened keys][agg input + * value(s) at native esz][row_idx int64]. Phase 2 then groups+accumulates each + * partition by walking its records SEQUENTIALLY — hash/equality compare the + * contiguous packed keys and accumulation reads values from the contiguous + * record — trading a one-time scatter cost for cache-friendly Phase-2 reads + * (the memory-bound hot spot was agg_tuple_eq re-reading scattered key columns + * on every distinct insert). + * + * All records live in ONE array of input_count records, partition-major: + * partition p owns records [part_start[p], part_start[p+1]). Inside p, the + * slots are carved per input chunk in chunk order, so a partition's records + * appear in ascending input order no matter which worker ran which chunk. + * The allocation count is O(1) in the worker count: no per-(worker, + * partition) buffers to grow, and nothing for the dispatcher to free one by + * one. */ + +/* Input rows per phase-1 chunk, at least. Chunks are the unit of both the + * counting and the scatter pass, and the count matrix holds one uint32 per + * (chunk, partition), so chunks are few (a handful per worker) but never so + * small that the per-chunk partition row dwarfs the rows it counts. */ +#define AGG_RADIX_CHUNK_MIN_ROWS 16384 +/* ...but an input of at least this many rows per worker still gives every + * 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 +/* 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) +/* Partitions per prefix-sum task (one cache-line-friendly band of each + * chunk's count row). */ +#define AGG_RADIX_PREFIX_BAND 64 /* Per-partition result slot (filled by Phase 2). */ typedef struct { @@ -3154,11 +3169,21 @@ typedef struct { uint32_t part_bits; /* log2(n_parts): hash bits consumed by * partition selection; phase 2 shifts * them out before slot indexing */ - uint32_t pay_prime; /* expected rows per (worker,partition) - * buffer — first-allocation capacity */ - agg_pay_buf_t* bufs; /* [nw * n_parts] payload records */ + /* Phase-1 chunking of the input space [0, n_in) (selected-row space in + * sel mode): chunk c covers [c*chunk_rows, min((c+1)*chunk_rows, n_in)). */ + int64_t n_in; + int64_t chunk_rows; + uint32_t n_chunks; + /* [n_chunks * n_parts]: pass 1 stores per-(chunk, partition) row counts; + * the prefix pass turns them into each chunk's offset inside partition + * p's slot range; pass 2 uses its chunk's row as write cursors. */ + uint32_t* cnt; + int64_t* part_start; /* [n_parts + 1] record index of p's slots */ + char* pay; /* [n_in * rec] payload records */ + uint16_t* pid; /* [n_in] partition of each input position + * (pass 1 writes, pass 2 reads) */ agg_radix_part_t* parts; /* [n_parts] */ - int phase1_oom; /* set by any Phase-1 worker on push failure */ + _Atomic(int) part_overflow; /* a partition exceeds UINT32_MAX rows */ /* Per-row payload record layout (bytes), computed once by the caller: * [0 .. n_keys*8) packed keys (each widened via agg_read_key_i64) * [val_off[a] ..] agg a's input value at native esz (if val_data[a]) @@ -3176,12 +3201,6 @@ typedef struct { * the decoded original row. */ ray_t* sel; const int64_t* sel_prefix; - /* Per-WORKER key-staging row: [nw * n_keys] int64. The scatter reads all - * keys into its worker's slice to compute the partition hash, THEN copies - * them into the reserved record (the record's partition is not known until - * the hash is computed, so the keys can't be written straight to it). One - * carve for the whole dispatch (caller-owned) — never a per-row alloc. */ - int64_t* kv_scratch; } agg_radix_ctx_t; /* Avalanche finalizer shared by the radix scatter (partition selection) and @@ -3197,26 +3216,39 @@ static inline uint64_t agg_radix_fmix64(uint64_t h) { return h; } -/* Scatter one ORIGINAL row r's packed payload record into the worker's per- - * partition buffer. Returns 0 or -1 on push OOM (sets phase1_oom). */ -static inline int agg_radix_scatter_one(agg_radix_ctx_t* c, agg_pay_buf_t* my, - int64_t* kv, int64_t r, - int64_t 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. + * + * 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 + * address no longer waits on the key load -> FNV -> fmix chain, so the + * 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; - /* kv: this worker's key-staging slice (c->kv_scratch + wid*n_keys), sized - * for any key count — no fixed [16] cap. */ - 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); - kv[k] = v; - h ^= (uint64_t)v; h *= 1099511628211ULL; + 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); + h ^= (uint64_t)v; 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; } - h = agg_radix_fmix64(h); - uint32_t p = (uint32_t)(h & (c->n_parts - 1)); - char* rec = agg_pay_reserve(&my[p], c->rec, c->pay_prime); - if (!rec) { c->phase1_oom = 1; return -1; } + uint32_t p = c->pid[pos]; + char* rec = c->pay + (size_t)(c->part_start[p] + cur[p]++) * c->rec; int64_t* kdst = (int64_t*)rec; - for (uint32_t k = 0; k < n_keys; k++) kdst[k] = kv[k]; + 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; for (uint32_t a = 0; a < n_aggs; a++) { if (c->val_data[a]) { uint8_t ez = c->val_esz[a]; @@ -3229,57 +3261,78 @@ static inline int agg_radix_scatter_one(agg_radix_ctx_t* c, agg_pay_buf_t* my, } if (c->needs_row) memcpy(rec + c->row_off, &input_order, sizeof(input_order)); - return 0; } -/* Scatter this worker's [start,end) rows, staging each row's keys through kv. - * static inline so each caller below inlines its own copy: when the stack - * array is passed, kv's alloca provenance reaches the per-row kv[k]=v stage - * unmerged and the compiler scalarizes/register-promotes it (parent codegen); - * a heap slice stays compiler-opaque (may alias key_data/rec/bufs). - * RAY_INLINE (always_inline) so both call sites below get their own copy — - * an out-of-line body would merge the two provenances into one pointer param - * and re-pessimize the stack path. */ -RAY_INLINE void agg_radix_scatter_range(agg_radix_ctx_t* c, agg_pay_buf_t* my, - int64_t* kv, int64_t start, int64_t end) { +/* 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) { + 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)); if (c->sel) { - /* Chunk-decode this worker's slice of selected rows; scatter each. */ int64_t rows[AGG_SEL_CHUNK]; - agg_sel_cursor_t cur; - agg_sel_cursor_init(&cur, c->sel, c->sel_prefix, start, end); - int64_t input_order = start; + agg_sel_cursor_t sc; + agg_sel_cursor_init(&sc, c->sel, c->sel_prefix, start, end); + int64_t pos = start; int64_t cn; - while ((cn = agg_sel_cursor_next(&cur, rows)) > 0) + while ((cn = agg_sel_cursor_next(&sc, rows)) > 0) for (int64_t i = 0; i < cn; i++) - if (agg_radix_scatter_one(c, my, kv, rows[i], - input_order++) != 0) return; + agg_radix_visit(c, cur, rows[i], pos++, scatter); return; } for (int64_t r = start; r < end; r++) - if (agg_radix_scatter_one(c, my, kv, r, r) != 0) return; + agg_radix_visit(c, cur, r, r, scatter); } -/* Phase 1: scatter one packed payload record per row into per-(worker, - * partition) contiguous buffers, keyed by the tuple-hash partition. */ -static void agg_radix_scatter_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { +/* 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); +} + +/* 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; - agg_pay_buf_t* my = &c->bufs[(size_t)wid * c->n_parts]; - /* Key-staging row for this worker. The common bounded case (n_keys <= 16) - * stages through a STACK array: a compiler-opaque heap slice defeated the - * scalarization/register-promotion of the per-row kv[k]=v stage (flat - * retired instructions, IPC 0.71->0.58, scatter self-time tripled — see - * task-9-rca.md). Branch ONCE here (not per row) so each inlined copy of - * agg_radix_scatter_range gets its argument's provenance unmerged: the - * stack call restores parent codegen (and drops the secondary false-sharing - * term); wide keys (>16) fall back to the per-worker heap slice. */ - if (c->n_keys <= 16) { - int64_t kv_stk[16]; - agg_radix_scatter_range(c, my, kv_stk, start, end); - } else { - agg_radix_scatter_range(c, my, &c->kv_scratch[(size_t)wid * c->n_keys], start, end); + 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) { + (void)wid; + for (int64_t ch = start; ch < end; ch++) + agg_radix_chunk_pass((agg_radix_ctx_t*)vctx, ch, true); +} + /* Phase 2: group + accumulate one partition by walking its packed payload * records SEQUENTIALLY. Keys here are disjoint from every other partition, so * a partition-local open-addressing hash suffices. Hash/equality compare the @@ -3296,10 +3349,8 @@ static void agg_radix_group_fn(void* vctx, uint32_t wid, int64_t start, int64_t uint32_t p = (uint32_t)pi; agg_radix_part_t* pr = &c->parts[p]; - /* Total rows hashing to p across all workers. */ - int64_t total = 0; - for (uint32_t w = 0; w < c->nw; w++) - total += c->bufs[(size_t)w * c->n_parts + p].n; + /* 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). */ @@ -3350,10 +3401,9 @@ static void agg_radix_group_fn(void* vctx, uint32_t wid, int64_t start, int64_t } int64_t ng = 0, ri = 0; - for (uint32_t w = 0; w < c->nw; w++) { - agg_pay_buf_t* b = &c->bufs[(size_t)w * c->n_parts + p]; - const char* rec = b->buf; - for (uint32_t i = 0; i < b->n; i++, rec += c->rec) { + { + const char* rec = c->pay + (size_t)c->part_start[p] * 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; if (c->needs_row) memcpy(&r, rec + c->row_off, sizeof(r)); @@ -3900,105 +3950,22 @@ static void agg_ord_fill_fn(void* raw, uint32_t wid, int64_t start, int64_t end) memset(c->pairs + start, 0xFF, (size_t)(end - start) * sizeof(agg_radix_order_t)); } -static ray_t* exec_group_v2_parallel_radix( - ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t nrows, +/* Largest group count whose first-seen order is restored by sorting the + * groups rather than by the input-sized order map (see agg_parts_emit). */ +#define AGG_ORDER_SORT_MAX_GROUPS 16384 + +/* Phase 3 of every partition-producing strategy (radix, table stack): order + * the per-partition groups by first logical input position (or select the + * bounded / top-N subset), emit the key columns from the packed per-group + * keys and finalize the aggregates. Consumes `parts` (destroyed + freed on + * every path) and `d` (freed on every path). */ +static ray_t* agg_parts_emit(ray_op_ext_t* ext, agg_desc_t* d, + agg_radix_part_t* parts, uint32_t n_parts, ray_pool_t* pool, uint32_t nw, ray_t** key_cols, int64_t* key_syms, 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) { - ray_op_ext_t* ext = find_ext(g, op->id); + int64_t input_count, int64_t group_limit, const ray_group_emit_filter_t* efp) { uint32_t n_keys = ext->n_keys, n_aggs = ext->n_aggs; - ray_pool_t* pool = ray_pool_get(); - 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); - 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; - - /* Every group records its earliest source row so emitted order does not - * depend on the number of radix partitions used by this execution. */ - bool needs_row = true; - - /* Per-row payload record layout: [packed keys][agg values][row_idx?]. - * val_off/val2_off are per-dispatch (filled once here, read by workers). - * The same carve tails a per-worker key-staging block (nw*n_keys int64, - * both 8-byte) so kv_scratch shares off_hdr's lifetime — one free, no extra - * exit sites. Only phases 1-2 read either; both freed once phase 2 joins. */ - ray_t* off_hdr; - size_t* val_off = (size_t*)scratch_calloc(&off_hdr, - 2u * (size_t)n_aggs * sizeof(size_t) + (size_t)nw * (size_t)n_keys * sizeof(int64_t)); - if (!val_off) { agg_desc_free(&d); return ray_error("oom", NULL); } - size_t* val2_off = val_off + n_aggs; - int64_t* kv_scratch = (int64_t*)(val2_off + n_aggs); /* [nw * n_keys] */ - 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 */ - - uint32_t n_parts = agg_radix_part_count(nw, sel ? n_sel : nrows); - size_t nbuf = (size_t)nw * n_parts; - agg_pay_buf_t* bufs = ray_calloc_raw((size_t)(nbuf) * (sizeof(agg_pay_buf_t))); - agg_radix_part_t* parts = ray_calloc_raw((size_t)n_parts * sizeof(agg_radix_part_t)); - if (!bufs || !parts) { - ray_free_raw(bufs); ray_free_raw(parts); - 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); - } - - agg_radix_ctx_t ctx = { - .key_cols = key_cols, .key_data = key_data, .n_keys = n_keys, - .vts = vts, .off = off, .block = block, .n_aggs = n_aggs, - .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, - .nw = nw, .n_parts = n_parts, - .part_bits = (uint32_t)__builtin_ctz(n_parts), - /* Uniform-hash expectation with 25% slack; ≥8 so tiny buffers don't - * immediately re-double. */ - .pay_prime = (uint32_t)((uint64_t)(sel ? n_sel : nrows) - / ((uint64_t)nw * n_parts) * 5 / 4 + 8), - .bufs = bufs, .parts = parts, .phase1_oom = 0, - .rec = rec, .row_off = row_off, .needs_row = needs_row, - .sel = sel, .sel_prefix = sel_prefix, - .val_off = val_off, .val2_off = val2_off, - .kv_scratch = kv_scratch, - }; - - /* Phase 1: scatter. Sel mode dispatches over selected-row space [0,n_sel); - * each worker decodes its slice of selected rows to ORIGINAL indices. */ - ray_pool_dispatch(pool, agg_radix_scatter_fn, &ctx, sel ? n_sel : nrows); - ray_profile_tick("radix: scattered rows"); - - /* Phase 2: per-partition group+accumulate. */ - int oom = ctx.phase1_oom; - if (!oom) - ray_pool_dispatch_n(pool, agg_radix_group_fn, &ctx, n_parts); - if (!oom) - for (uint32_t p = 0; p < n_parts; p++) - if (parts[p].oom) { oom = 1; break; } - - ray_profile_tick("radix: reduced partitions"); - - /* Phases 1+2 done (both dispatches joined); val_off/val2_off no longer read. */ - scratch_free(off_hdr); - - if (oom) { - agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - 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); - } - + const int64_t* agg_syms = d->agg_syms; /* Phase 3: restore stable first-seen order across partitions. */ int64_t ng = 0; for (uint32_t p = 0; p < n_parts; p++) ng += parts[p].ng; @@ -4006,7 +3973,6 @@ static ray_t* exec_group_v2_parallel_radix( /* Place each group directly at its first logical input position, then * compact those occupied positions in one linear pass. This restores * first-seen order without a comparison sort or a routing threshold. */ - int64_t input_count = sel ? n_sel : nrows; /* Bounded emit under a HEAD(GROUP) limit hint: when only the first * `group_limit` groups are wanted, selecting them directly is O(ng) with a @@ -4030,9 +3996,8 @@ static ray_t* exec_group_v2_parallel_radix( route_stats.topn_kept = kept; } else if (rc == 1) { agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); return ray_error("oom", NULL); } /* rc == 2: no scalar order for this aggregate — full path below. */ @@ -4046,21 +4011,45 @@ static ray_t* exec_group_v2_parallel_radix( parts, n_parts, input_count, n_emit, &rc); if (!sel_pairs) { agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); return rc == 1 ? ray_error("oom", NULL) : ray_error("group", "failed to order radix groups"); } pairs = sel_pairs; + } else if (ng <= AGG_ORDER_SORT_MAX_GROUPS && ng * 32 <= input_count) { + /* Few groups over many rows (every low-cardinality group-by): sort + * the (first_row, group) pairs — first rows are distinct across + * groups, so the order is total and identical to the map below — + * instead of filling, scattering into and compacting an order map + * of one word per INPUT row (32 MB and three passes for ten groups + * over 4M rows). */ + pairs = ray_alloc_raw((size_t)(ng > 0 ? ng : 1) * sizeof(agg_radix_order_t)); + ray_t* sk_hdr = NULL; + int64_t* skeys = pairs ? (int64_t*)scratch_alloc(&sk_hdr, + (size_t)(ng > 0 ? ng : 1) * sizeof(int64_t)) : NULL; + if (!pairs || !skeys) { + ray_free_raw(pairs); scratch_free(sk_hdr); + agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); + ray_free_raw(parts); + agg_desc_free(d); + return ray_error("oom", NULL); + } + int64_t m = 0; + for (uint32_t p = 0; p < n_parts; p++) + for (int64_t gg = 0; gg < parts[p].ng; gg++, m++) { + skeys[m] = parts[p].first_row[gg]; + pairs[m].idx = ((int64_t)p << 32) | (uint32_t)gg; + } + agg_sort_pairs_by_key(pairs, skeys, ng); + scratch_free(sk_hdr); } else { pairs = ray_alloc_raw( (size_t)(input_count > 0 ? input_count : 1) * sizeof(agg_radix_order_t)); if (!pairs) { agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); return ray_error("oom", NULL); } /* -1 fill: on a 10M-row input this is an 80MB first touch of fresh @@ -4147,9 +4136,8 @@ static ray_t* exec_group_v2_parallel_radix( if (!order_ok) { ray_free_raw(pairs); agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); return ray_error("group", "failed to order radix groups"); } } /* end full-order path */ @@ -4159,9 +4147,8 @@ static ray_t* exec_group_v2_parallel_radix( if (!result || RAY_IS_ERR(result)) { ray_free_raw(pairs); agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); return result ? result : ray_error("oom", NULL); } @@ -4210,9 +4197,8 @@ static ray_t* exec_group_v2_parallel_radix( scratch_free(kouts_hdr); ray_free_raw(pairs); agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); ray_release(result); return kerr; } for (uint32_t k = 0; k < n_keys; k++) { @@ -4230,9 +4216,8 @@ static ray_t* exec_group_v2_parallel_radix( if (!outs) { ray_free_raw(pairs); agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - agg_desc_free(&d); + ray_free_raw(parts); + agg_desc_free(d); ray_release(result); return ray_error("oom", NULL); } int64_t* kparams = (int64_t*)(outs + n_aggs); @@ -4246,9 +4231,8 @@ static ray_t* exec_group_v2_parallel_radix( for (uint32_t b = 0; b < a; b++) ray_release(outs[b]); ray_free_raw(pairs); agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - scratch_free(outs_hdr); agg_desc_free(&d); + ray_free_raw(parts); + scratch_free(outs_hdr); agg_desc_free(d); ray_release(result); return out ? out : ray_error("oom", NULL); } out->len = n_emit; @@ -4318,12 +4302,1209 @@ static ray_t* exec_group_v2_parallel_radix( /* Finalize is done reading every partition's buffered group state → destroy * exactly once before freeing the partition slabs. */ agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); - for (size_t i = 0; i < nbuf; i++) ray_free_raw(bufs[i].buf); - ray_free_raw(bufs); ray_free_raw(parts); - scratch_free(outs_hdr); agg_desc_free(&d); + ray_free_raw(parts); + scratch_free(outs_hdr); agg_desc_free(d); return result; } +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, + 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) { + ray_op_ext_t* ext = find_ext(g, op->id); + uint32_t n_keys = ext->n_keys, n_aggs = ext->n_aggs; + ray_pool_t* pool = ray_pool_get(); + 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); + 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; + + /* Every group records its earliest source row so emitted order does not + * depend on the number of radix partitions used by this execution. */ + bool needs_row = true; + + /* Per-row payload record layout: [packed keys][agg values][row_idx?]. + * val_off/val2_off are per-dispatch (filled once here, read by workers); + * 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)); + if (!val_off) { agg_desc_free(&d); return ray_error("oom", NULL); } + size_t* val2_off = val_off + n_aggs; + 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 */ + + int64_t n_in = sel ? n_sel : nrows; + if (n_in < 0) n_in = 0; + uint32_t n_parts = agg_radix_part_count(nw, n_in); + /* Partition ids are stored as uint16 between the passes. Only inputs + * past 2^32 rows ask for more partitions; they get larger ones. */ + if (n_parts > 65536) n_parts = 65536; + + /* Phase-1 chunks: a few per worker so claiming balances uneven rows, + * bounded by the count-matrix budget and by a minimum chunk size, and + * small enough that a chunk's per-partition count fits uint32. */ + uint64_t want = (uint64_t)nw * AGG_RADIX_CHUNKS_PER_WORKER; + uint64_t by_budget = AGG_RADIX_COUNT_BUDGET / ((uint64_t)n_parts * sizeof(uint32_t)); + if (want > by_budget) want = by_budget; + if (want < nw) want = nw; + uint64_t by_rows = ((uint64_t)n_in + AGG_RADIX_CHUNK_MIN_ROWS - 1) / AGG_RADIX_CHUNK_MIN_ROWS; + if (by_rows < nw && (uint64_t)n_in >= (uint64_t)nw * AGG_RADIX_CHUNK_FLOOR_ROWS) + by_rows = nw; + if (want > by_rows) want = by_rows; + uint64_t by_width = (uint64_t)n_in / ((uint64_t)1 << 30) + 1; + if (want < by_width) want = by_width; + 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; + 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. */ + 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) { + ray_free_raw(parts); ray_free_raw(cnt); ray_free_raw(part_start); + ray_free_raw(pid); 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); + } + part_start[0] = 0; + + agg_radix_ctx_t ctx = { + .key_cols = key_cols, .key_data = key_data, .n_keys = n_keys, + .vts = vts, .off = off, .block = block, .n_aggs = n_aggs, + .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, + .nw = nw, .n_parts = n_parts, + .part_bits = (uint32_t)__builtin_ctz(n_parts), + .n_in = n_in, .chunk_rows = chunk_rows, .n_chunks = n_chunks, + .cnt = cnt, .part_start = part_start, .pay = pay, .pid = pid, + .parts = parts, + .rec = rec, .row_off = row_off, .needs_row = needs_row, + .sel = sel, .sel_prefix = sel_prefix, + .val_off = val_off, .val2_off = val2_off, + }; + atomic_init(&ctx.part_overflow, 0); + + /* 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); + 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)) + ray_pool_dispatch_n(pool, agg_radix_prefix_fn, &ctx, n_bands); + else + agg_radix_prefix_fn(&ctx, 0, 0, n_bands); + cancelled = pool_cancelled(pool); + } + 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]; + /* Pass 2: every record to its exact slot. */ + ray_pool_dispatch_n(pool, agg_radix_scatter_fn, &ctx, n_chunks); + cancelled = pool_cancelled(pool); + } + 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_profile_tick("radix: reduced partitions"); + + /* Phases 1+2 done (every dispatch joined); val_off/val2_off and the + * payload records are no longer read — groups keep copies of their keys. */ + scratch_free(off_hdr); + 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 (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); +} + +/* ══════════════════════════════════════════════════════════════════════ + * Table-stack group-by (int/SYM keys, ACC_STREAMING aggs only). + * + * The radix strategy above scatters EVERY input row into a payload record + * before any aggregation happens, so a 4M-row group-by over ten sparse keys + * pays the full scatter (~100 MB of records) to produce ten groups. This + * strategy pre-aggregates first and scatters only when pre-aggregation + * provably stops paying: + * + * Gate: a sample of the grouped rows (the SELECTED rows under a + * pushed filter) gives a Chao1 distinct estimate and the share + * of rows whose key the sample saw once. The strategy takes + * the query only when the estimated groups fit one table of at + * most AGG_TS_MAX_BITS slots, that singleton share is bounded + * (Chao1 under-counts a long tail behind a hot head), the + * tables of all workers fit the last-level cache together, AND + * every phase-1 task is expected to fold several rows per + * group; otherwise it + * declines (returns NULL) and the caller runs the radix scatter, + * whose L1-local per-partition probes beat cache-missing table + * probes once rows per group per task drop below a handful + * (measured: 50k+ groups over 4M rows on 24 threads ran 0.55- + * 0.85x of radix on the table stack, <= 15k groups 1.2-6x). + * Phase 1 (one logical task per contiguous input range; tasks are claimed + * by whichever worker is free, but the task -> range map is fixed + * so the merge order, and with it every floating-point result, is + * independent of scheduling): each task owns a stack of + * open-addressing tables. Slot = hash >> (64 - log2 cap) + * (TOP-BIT placement), so for any power-of-two table the entries + * of merge partition p (the top log2(n_parts) hash bits) live in + * one contiguous slot range — the merge below range-scans the + * task tables directly, no scatter copy of their entries. The + * hash lives inline in the entry; a one-byte tag array answers + * "empty?" and most "not this key" from L1. + * A table grows by doubling up to AGG_TS_MAX_BITS; a full table + * at that size is PUSHED onto the task's stack and a fresh one + * started (no rehash past cache size, no scatter). Every time + * a table fills, the task compares the distinct entries it took + * against the rows it absorbed: at >= AGG_TS_SWITCH_PCT percent + * distinct the input is nearly all-distinct in this range (the + * sample estimate was wrong), so the task switches to RAW + * SCATTER — the remaining rows go as packed records into + * per-partition buckets (chunked bump allocation, lazily + * created) and are aggregated by the merge. + * Phase 2 (one task per merge partition): fold, in task order, every + * table's slot range for p and every task's bucket p into one + * partition-local hash; the result is the same agg_radix_part_t + * the radix strategy produces, so the shared agg_parts_emit + * handles ordering (first-seen), bounded emit, native top-N and + * the parallel key/aggregate emit unchanged. + * ══════════════════════════════════════════════════════════════════════ */ + +#define AGG_TS_CHUNK 4096 /* rows per probe + accumulate batch */ +#define AGG_TS_MIN_BITS 13 /* smallest table: 8192 slots */ +#define AGG_TS_MAX_BITS 15 /* largest table: 32768 slots, then stack */ +#define AGG_TS_LOAD_NUM 3 /* fill tables to 3/4 */ +#define AGG_TS_SWITCH_ROWS 16384 /* rows a table must absorb before its + * distinct ratio decides anything */ +#define AGG_TS_SWITCH_PCT 50 /* distinct/rows (%) at which a filled + * table switches its task to raw scatter */ +#define AGG_TS_TASK_ROWS 16384 /* minimum rows per phase-1 task */ +#define AGG_TS_TASKS_PER_WORKER 2 +#define AGG_TS_BUCKET_FIRST ((size_t)8 << 10) /* first bucket chunk (bytes) */ +#define AGG_TS_BUCKET_NEXT ((size_t)64 << 10) /* largest bucket chunk (bytes) */ +#define AGG_TS_SAMPLE 8192 /* single rows sampled for the gate + sizing */ +#define AGG_TS_GATE_UNSEEN_PCT 66 /* reject when more than this share of the + * sampled rows carry a key seen once */ +#define AGG_TS_GATE_GROUPS 24576 /* estimated groups must fit one full + * AGG_TS_MAX_BITS table */ +#define AGG_TS_GATE_REPEAT 4 /* ...and each task must expect this + * many rows per group */ + +/* Entry layout at ent + slot * estride: + * [0, 8) uint64 key hash (| 1, never 0 when occupied) + * [8, 16) int64 first logical input position + * [16, 16 + 8*n_keys) packed keys (agg_read_key_i64 widened) + * [state_off, ...) AoS aggregate states (off[a] inside) */ +#define AGG_TS_KEY_OFF 16 +typedef struct agg_ts_table { + uint8_t* tag; /* [cap] 0 = empty, else hash bits 48..55 | 1 */ + char* ent; /* [cap * estride] */ + uint32_t bits; + int64_t cap; + int64_t ng; /* occupied slots */ + int64_t rows; /* rows aggregated into this table */ + struct agg_ts_table* prev; /* older, full table of the same task */ +} agg_ts_table_t; + +/* Scatter bucket chunk: records follow the header (24 bytes → 8-aligned). */ +typedef struct agg_ts_chunk { + struct agg_ts_chunk* next; + int64_t n; /* records used */ + int64_t cap; /* records that fit */ +} agg_ts_chunk_t; + +typedef struct { + agg_ts_chunk_t* head; + agg_ts_chunk_t* tail; + int64_t n; /* records in the bucket */ + size_t bytes; /* size of the last chunk (doubles per chunk) */ +} agg_ts_bucket_t; + +typedef struct { + agg_ts_table_t* top; /* current table; prev links the stack */ + agg_ts_bucket_t* buckets; /* [n_parts], allocated on the switch */ + int64_t rows; /* rows consumed by this task */ + int64_t entries; /* entries across the task's tables */ + int64_t scattered; /* rows that went to buckets */ + uint32_t n_tables; + bool scatter; /* raw scatter mode */ + int oom; +} agg_ts_task_t; + +typedef struct { + ray_t** key_cols; + const void** key_data; + uint32_t n_keys; + const agg_vtable_t** vts; + const size_t* off; + size_t block; + uint32_t n_aggs; + const void** val_data; const int8_t* val_types; const bool* val_hasnull; const uint8_t* val_esz; + const void** val2_data; const int8_t* val2_types; const bool* val2_hasnull; const uint8_t* val2_esz; + /* Table-stride view of the aggregates: states live inside the entries. */ + agg_valdesc_t vd; + const size_t* ent_off; /* [n_aggs] state_off + off[a] */ + size_t estride; + size_t state_off; + /* Scatter record layout (same as the radix payload): [keys][vals][pos]. */ + size_t rec; + size_t row_off; + const size_t* val_off; + const size_t* val2_off; + uint32_t n_parts; + uint32_t part_bits; + uint32_t init_bits; + int64_t n_in; + int64_t task_rows; + uint32_t n_tasks; + agg_ts_task_t* tasks; /* [n_tasks] */ + agg_radix_part_t* parts; /* [n_parts] */ + int64_t merge_cand; /* total entries + scattered rows (phase 2 sizing) */ + ray_t* sel; + const int64_t* sel_prefix; +} agg_ts_ctx_t; + +/* Same FNV-1a + fmix64 as the radix scatter; bit 0 forced on so 0 can mark + * an empty slot (top-bit placement and partition bits are unaffected). */ +static inline uint64_t agg_ts_hash(const int64_t* keys, uint32_t n_keys) { + uint64_t h = 1469598103934665603ULL; + for (uint32_t k = 0; k < n_keys; k++) { h ^= (uint64_t)keys[k]; h *= 1099511628211ULL; } + return agg_radix_fmix64(h) | 1u; +} + +/* Tag byte: hash bits 48..55 (below the slot/partition bits), never 0. */ +static inline uint8_t agg_ts_tag(uint64_t h) { return (uint8_t)((h >> 48) | 1u); } + +static inline uint64_t agg_ts_ent_hash(const agg_ts_table_t* t, size_t estride, int64_t slot) { + uint64_t h; memcpy(&h, t->ent + (size_t)slot * estride, sizeof(h)); return h; +} + +static agg_ts_table_t* agg_ts_table_new(uint32_t bits, size_t estride) { + agg_ts_table_t* t = ray_alloc_raw(sizeof(agg_ts_table_t)); + if (!t) return NULL; + int64_t cap = (int64_t)1 << bits; + t->tag = ray_calloc_raw((size_t)cap); + t->ent = ray_alloc_raw((size_t)cap * estride); + if (!t->tag || !t->ent) { + ray_free_raw(t->tag); ray_free_raw(t->ent); ray_free_raw(t); + return NULL; + } + t->bits = bits; t->cap = cap; t->ng = 0; t->rows = 0; t->prev = NULL; + return t; +} + +static void agg_ts_table_free(agg_ts_table_t* t) { + while (t) { + agg_ts_table_t* prev = t->prev; + ray_free_raw(t->tag); ray_free_raw(t->ent); ray_free_raw(t); + t = prev; + } +} + +/* Double a table in place of itself (same stack position). Top-bit + * placement keeps the relative order of the entries; the states are plain + * bytes (streaming accumulators own no memory) so a memcpy moves them. */ +static agg_ts_table_t* agg_ts_table_grow(agg_ts_table_t* t, size_t estride) { + agg_ts_table_t* n = agg_ts_table_new(t->bits + 1, estride); + if (!n) return NULL; + uint64_t nmask = (uint64_t)n->cap - 1; + uint32_t shift = 64 - n->bits; + for (int64_t s = 0; s < t->cap; s++) { + if (!t->tag[s]) continue; + uint64_t h = agg_ts_ent_hash(t, estride, s); + uint64_t d = h >> shift; + while (n->tag[d]) d = (d + 1) & nmask; + n->tag[d] = t->tag[s]; + memcpy(n->ent + (size_t)d * estride, t->ent + (size_t)s * estride, estride); + } + n->ng = t->ng; n->rows = t->rows; n->prev = t->prev; + ray_free_raw(t->tag); ray_free_raw(t->ent); ray_free_raw(t); + return n; +} + +static void agg_ts_bucket_free(agg_ts_bucket_t* b) { + agg_ts_chunk_t* ch = b->head; + while (ch) { agg_ts_chunk_t* nx = ch->next; ray_free_raw(ch); ch = nx; } + b->head = b->tail = NULL; b->n = 0; b->bytes = 0; +} + +static void agg_ts_task_free(agg_ts_task_t* ts, uint32_t n_parts) { + agg_ts_table_free(ts->top); ts->top = NULL; + if (ts->buckets) { + for (uint32_t p = 0; p < n_parts; p++) agg_ts_bucket_free(&ts->buckets[p]); + ray_free_raw(ts->buckets); ts->buckets = NULL; + } +} + +/* Reserve one record slot in bucket b (lazy, chunked bump allocation). */ +static inline char* agg_ts_bucket_push(agg_ts_bucket_t* b, size_t rec) { + agg_ts_chunk_t* ch = b->tail; + if (!ch || ch->n == ch->cap) { + /* Chunks double from AGG_TS_BUCKET_FIRST to AGG_TS_BUCKET_NEXT, so a + * sparse stream (tasks x partitions of them) wastes at most about + * what it holds while a dense one soon bumps 64 KB at a time. */ + size_t bytes = ch ? b->bytes * 2 : AGG_TS_BUCKET_FIRST; + if (bytes > AGG_TS_BUCKET_NEXT) bytes = AGG_TS_BUCKET_NEXT; + b->bytes = bytes; + int64_t cap = (int64_t)((bytes - sizeof(agg_ts_chunk_t)) / rec); + if (cap < 1) cap = 1; + agg_ts_chunk_t* nc = ray_alloc_raw(sizeof(agg_ts_chunk_t) + (size_t)cap * rec); + if (!nc) return NULL; + nc->next = NULL; nc->n = 0; nc->cap = cap; + if (ch) ch->next = nc; else b->head = nc; + b->tail = nc; ch = nc; + } + b->n++; + return (char*)(ch + 1) + (size_t)ch->n++ * rec; +} + +/* Make room in the task's current table for up to `n` new entries at the + * configured load: grow below the size cap, push at the cap, or switch the + * task to raw scatter when the filled table shows the input is too distinct + * for pre-aggregation to pay. Returns false on OOM. */ +static bool agg_ts_reserve(agg_ts_ctx_t* c, agg_ts_task_t* ts, int64_t n) { + agg_ts_table_t* t = ts->top; + while (!t || t->ng + n > (t->cap >> 2) * AGG_TS_LOAD_NUM) { + if (t && t->rows >= AGG_TS_SWITCH_ROWS && + t->ng * 100 >= t->rows * AGG_TS_SWITCH_PCT) { + ts->scatter = true; + return true; + } + if (!t) { + t = agg_ts_table_new(c->init_bits, c->estride); + if (!t) return false; + ts->n_tables++; + } else if (t->bits < AGG_TS_MAX_BITS) { + agg_ts_table_t* grown = agg_ts_table_grow(t, c->estride); + if (!grown) return false; /* t is intact; the task free releases it */ + t = grown; + } else { + agg_ts_table_t* nt = agg_ts_table_new(AGG_TS_MAX_BITS, c->estride); + if (!nt) return false; + nt->prev = t; t = nt; + ts->n_tables++; + } + ts->top = t; + } + 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) { + 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->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++) { + 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); + 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]) { + 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); + } + } + int64_t pos = pos0 + i; + memcpy(rec + c->row_off, &pos, sizeof(pos)); + } + ts->rows += n; ts->scattered += n; + return; + } + + agg_ts_table_t* t = ts->top; + 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++) { + 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); + uint64_t h = agg_ts_hash(keys, n_keys); + uint8_t tag = agg_ts_tag(h); + uint64_t slot = h >> shift; + for (;;) { + uint8_t st = t->tag[slot]; + if (!st) { + char* e = t->ent + (size_t)slot * estride; + t->tag[slot] = tag; + int64_t pos = pos0 + i; /* positions ascend within a task: + * the first sight IS the minimum */ + memcpy(e, &h, sizeof(h)); + memcpy(e + sizeof(uint64_t), &pos, sizeof(pos)); + memcpy(e + AGG_TS_KEY_OFF, keys, key_bytes); + for (uint32_t a = 0; a < n_aggs; a++) + c->vts[a]->init(e + c->ent_off[a]); + t->ng++; + break; + } + if (st == tag) { + const char* e = t->ent + (size_t)slot * estride; + uint64_t eh; memcpy(&eh, e, sizeof(eh)); + if (eh == h && memcmp(e + AGG_TS_KEY_OFF, keys, key_bytes) == 0) break; + } + slot = (slot + 1) & mask; + } + gid[i] = (uint32_t)slot; + } + if (rows) { + if (agg_sel_accum_chunk(&c->vd, sc, t->ent, gid, rows, n) != 0) { ts->oom = 1; return; } + } else { + 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]; + 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]; + 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 { + ray_valid_t valid = { NULL, c->val_types[a], false }; + c->vts[a]->update_batch(states, estride, gid, NULL, &valid, n, NULL); + } + } + } + t->rows += n; ts->rows += n; +} + +/* 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; + 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)); + uint32_t* gid = keys ? ray_alloc_raw(AGG_TS_CHUNK * sizeof(uint32_t)) : NULL; + if (!keys || !gid) { + for (int64_t ti = start; ti < end; ti++) c->tasks[ti].oom = 1; + ray_free_raw(gid); scratch_free(kb_hdr); + return; + } + for (int64_t ti = start; ti < end; ti++) { + agg_ts_task_t* ts = &c->tasks[ti]; + int64_t lo = ti * c->task_rows; + int64_t hi = lo + c->task_rows; + if (hi > c->n_in) hi = c->n_in; + 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_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); + pos += cn; + } + agg_sel_scratch_free(&sc); + } else { + 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); + } + } + for (agg_ts_table_t* tab = ts->top; tab; tab = tab->prev) ts->entries += tab->ng; + } + ray_free_raw(gid); scratch_free(kb_hdr); +} + +/* Partition-local merge table (phase 2): hash-indexed gid, grow-on-demand + * group arrays in the agg_radix_part_t layout. */ +typedef struct { + uint64_t* mh; /* [htcap] key hash | 1, 0 = empty */ + int32_t* mg; /* [htcap] slot -> gid */ + int64_t htcap; + char* states; /* [gcap * block] */ + int64_t* first_row; /* [gcap] */ + int64_t* keys; /* [gcap * n_keys] */ + int64_t gcap, ng; +} agg_ts_merge_t; + +static bool agg_ts_merge_init(agg_ts_merge_t* m, int64_t expect, size_t block, uint32_t n_keys) { + int64_t htcap = 64; + while (htcap < expect * 4) htcap <<= 1; + int64_t gcap = expect < 256 ? expect : 256; + if (gcap < 16) gcap = 16; + m->mh = ray_calloc_raw((size_t)htcap * sizeof(uint64_t)); + m->mg = ray_alloc_raw((size_t)htcap * sizeof(int32_t)); + m->states = ray_alloc_raw((size_t)gcap * block); + m->first_row = ray_alloc_raw((size_t)gcap * sizeof(int64_t)); + m->keys = ray_alloc_raw((size_t)gcap * (size_t)(n_keys ? n_keys : 1) * sizeof(int64_t)); + m->htcap = htcap; m->gcap = gcap; m->ng = 0; + return m->mh && m->mg && m->states && m->first_row && m->keys; +} + +static void agg_ts_merge_free(agg_ts_merge_t* m, bool keep_groups) { + ray_free_raw(m->mh); ray_free_raw(m->mg); m->mh = NULL; m->mg = NULL; + if (!keep_groups) { + ray_free_raw(m->states); ray_free_raw(m->first_row); ray_free_raw(m->keys); + m->states = NULL; m->first_row = NULL; m->keys = NULL; + } +} + +/* Slot index inside the merge table: bits above the forced bit 0 (the top + * bits are the partition, constant inside one table). */ +#define AGG_TS_MSLOT(h, mask) (((h) >> 1) & (mask)) + +static bool agg_ts_merge_rehash(agg_ts_merge_t* m) { + int64_t ncap = m->htcap * 2; + uint64_t* nh = ray_calloc_raw((size_t)ncap * sizeof(uint64_t)); + int32_t* ng = ray_alloc_raw((size_t)ncap * sizeof(int32_t)); + if (!nh || !ng) { ray_free_raw(nh); ray_free_raw(ng); return false; } + uint64_t nmask = (uint64_t)ncap - 1; + for (int64_t s = 0; s < m->htcap; s++) { + uint64_t h = m->mh[s]; + if (!h) continue; + uint64_t d = AGG_TS_MSLOT(h, nmask); + while (nh[d]) d = (d + 1) & nmask; + nh[d] = h; ng[d] = m->mg[s]; + } + ray_free_raw(m->mh); ray_free_raw(m->mg); + m->mh = nh; m->mg = ng; m->htcap = ncap; + return true; +} + +/* Find or create the group of (h, keys) in the merge table; `pos` is the + * candidate's first logical position (kept as the MIN). Returns the gid, + * -1 on OOM. */ +static inline int64_t agg_ts_merge_gid(agg_ts_merge_t* m, agg_ts_ctx_t* c, + uint64_t h, const int64_t* keys, int64_t pos) { + uint32_t n_keys = c->n_keys; + size_t key_bytes = (size_t)n_keys * sizeof(int64_t); + uint64_t mask = (uint64_t)m->htcap - 1; + uint64_t slot = AGG_TS_MSLOT(h, mask); + for (;;) { + uint64_t sh = m->mh[slot]; + if (!sh) break; + int32_t gg = m->mg[slot]; + if (sh == h && memcmp(m->keys + (size_t)gg * n_keys, keys, key_bytes) == 0) { + if (pos < m->first_row[gg]) m->first_row[gg] = pos; + return gg; + } + slot = (slot + 1) & mask; + } + if ((m->ng + 1) * 2 > m->htcap) { /* keep the load under 1/2 */ + if (!agg_ts_merge_rehash(m)) return -1; + mask = (uint64_t)m->htcap - 1; + slot = AGG_TS_MSLOT(h, mask); + while (m->mh[slot]) slot = (slot + 1) & mask; + } + if (m->ng == m->gcap) { + int64_t ncap = m->gcap * 2; + void* ns = ray_realloc_raw(m->states, (size_t)ncap * c->block); + if (!ns) return -1; + m->states = ns; + void* nf = ray_realloc_raw(m->first_row, (size_t)ncap * sizeof(int64_t)); + if (!nf) return -1; + m->first_row = nf; + void* nk = ray_realloc_raw(m->keys, (size_t)ncap * (size_t)(n_keys ? n_keys : 1) * sizeof(int64_t)); + if (!nk) return -1; + m->keys = nk; + m->gcap = ncap; + } + int64_t gg = m->ng++; + m->mh[slot] = h; m->mg[slot] = (int32_t)gg; + m->first_row[gg] = pos; + memcpy(m->keys + (size_t)gg * n_keys, keys, key_bytes); + for (uint32_t a = 0; a < c->n_aggs; a++) + c->vts[a]->init(m->states + (size_t)gg * c->block + c->off[a]); + return gg; +} + +/* Slot range of partition p in a table: [lo, lo + n) plus the run of + * occupied slots that linear probing pushed past it (wrapping). Visits + * every occupied slot of the range and of that run; the body filters by + * partition (entries displaced INTO the range from the previous partition + * and the run's own tail belong elsewhere). */ +#define AGG_TS_RANGE_FOREACH(tab, p, part_bits, SLOT, BODY) do { \ + agg_ts_table_t* tab_ = (tab); \ + uint64_t mask_ = (uint64_t)tab_->cap - 1; \ + uint32_t span_ = tab_->bits - (part_bits); \ + int64_t lo_ = (int64_t)(p) << span_, n_ = (int64_t)1 << span_; \ + int64_t s_ = lo_, end_ = lo_ + n_; \ + for (; s_ < end_; s_++) { \ + if (!tab_->tag[s_]) continue; \ + int64_t SLOT = s_; BODY \ + } \ + for (int64_t k_ = 0; k_ < tab_->cap && tab_->tag[(uint64_t)s_ & mask_]; \ + k_++, s_++) { int64_t SLOT = (int64_t)((uint64_t)s_ & mask_); BODY } \ + } while (0) + +/* Phase 2: merge partition p from every task, in task order (tables oldest + * first, then the task's scattered records in input order). Frees each + * bucket it consumed; tables are shared by all partitions and outlive the + * dispatch. */ +static void agg_ts_merge_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + agg_ts_ctx_t* c = (agg_ts_ctx_t*)vctx; + uint32_t n_keys = c->n_keys, n_aggs = c->n_aggs; + uint32_t pshift = 64 - c->part_bits; + ray_t* ptr_hdr = NULL; + /* Per-call scratch: gid batch, one gather buffer per aggregate side, and + * a small array to walk a stack oldest-first. */ + char** gv = (char**)scratch_calloc(&ptr_hdr, + (size_t)(2u * (n_aggs ? n_aggs : 1)) * sizeof(char*)); + uint32_t* gid = gv ? ray_alloc_raw(AGG_TS_CHUNK * sizeof(uint32_t)) : NULL; + bool ok = gv && gid; + char** gy = gv ? gv + (n_aggs ? n_aggs : 1) : NULL; + for (uint32_t a = 0; ok && a < n_aggs; a++) { + if (c->val_data[a]) { gv[a] = ray_alloc_raw((size_t)AGG_TS_CHUNK * (c->val_esz[a] ? c->val_esz[a] : 1)); ok = gv[a] != NULL; } + if (ok && c->val2_data[a]) { gy[a] = ray_alloc_raw((size_t)AGG_TS_CHUNK * (c->val2_esz[a] ? c->val2_esz[a] : 1)); ok = gy[a] != NULL; } + } + uint32_t depth_cap = 16; + agg_ts_table_t** stack = ok ? ray_alloc_raw(depth_cap * sizeof(agg_ts_table_t*)) : NULL; + ok = ok && stack; + int64_t expect = c->merge_cand / c->n_parts + 1; + + for (int64_t pi = start; pi < end; pi++) { + uint32_t p = (uint32_t)pi; + agg_radix_part_t* pr = &c->parts[p]; + if (!ok) { pr->oom = 1; continue; } + + agg_ts_merge_t m; + if (!agg_ts_merge_init(&m, expect, c->block, n_keys)) { + agg_ts_merge_free(&m, false); pr->oom = 1; continue; + } + bool poom = false; + for (uint32_t ti = 0; ti < c->n_tasks && !poom; ti++) { + agg_ts_task_t* ts = &c->tasks[ti]; + /* Tables oldest first. */ + uint32_t depth = 0; + for (agg_ts_table_t* tab = ts->top; tab; tab = tab->prev) { + if (depth == depth_cap) { + void* ns = ray_realloc_raw((void*)stack, (size_t)depth_cap * 2 * sizeof(agg_ts_table_t*)); + if (!ns) { poom = true; break; } + stack = ns; depth_cap *= 2; + } + stack[depth++] = tab; + } + if (poom) break; + for (uint32_t di = depth; di-- > 0 && !poom; ) { + agg_ts_table_t* tab = stack[di]; + AGG_TS_RANGE_FOREACH(tab, p, c->part_bits, s, { + if (poom) break; + const char* e = tab_->ent + (size_t)s * c->estride; + uint64_t h; memcpy(&h, e, sizeof(h)); + if ((uint32_t)(h >> pshift) == p) { + int64_t pos; memcpy(&pos, e + sizeof(uint64_t), sizeof(pos)); + int64_t gg = agg_ts_merge_gid(&m, c, h, + (const int64_t*)(e + AGG_TS_KEY_OFF), pos); + if (gg < 0) { poom = true; break; } + for (uint32_t a = 0; a < n_aggs; a++) + c->vts[a]->merge(m.states + (size_t)gg * c->block + c->off[a], + e + c->ent_off[a], NULL); + } + }); + } + if (poom || !ts->buckets) continue; + /* Scattered records of this task, in input order, in batches. */ + agg_ts_bucket_t* b = &ts->buckets[p]; + for (agg_ts_chunk_t* ch = b->head; ch && !poom; ch = ch->next) { + const char* rec = (const char*)(ch + 1); + for (int64_t base = 0; base < ch->n && !poom; base += AGG_TS_CHUNK) { + int64_t bn = ch->n - base; if (bn > AGG_TS_CHUNK) bn = AGG_TS_CHUNK; + for (int64_t i = 0; i < bn; i++, rec += c->rec) { + const int64_t* keys = (const int64_t*)rec; + int64_t pos; memcpy(&pos, rec + c->row_off, sizeof(pos)); + for (uint32_t a = 0; a < n_aggs; a++) { + if (gv[a]) memcpy(gv[a] + (size_t)i * c->val_esz[a], rec + c->val_off[a], c->val_esz[a]); + if (gy[a]) memcpy(gy[a] + (size_t)i * c->val2_esz[a], rec + c->val2_off[a], c->val2_esz[a]); + } + int64_t gg = agg_ts_merge_gid(&m, c, agg_ts_hash(keys, n_keys), keys, pos); + if (gg < 0) { poom = true; break; } + gid[i] = (uint32_t)gg; + } + if (poom) break; + for (uint32_t a = 0; a < n_aggs; a++) { + char* states = m.states + c->off[a]; + if (c->vts[a]->update_batch2) { + 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->block, gid, gv[a], gy[a], &vx, &vy, bn, NULL); + } else if (c->val_data[a]) { + ray_valid_t valid = { gv[a], c->val_types[a], c->val_hasnull[a] }; + c->vts[a]->update_batch(states, c->block, gid, gv[a], &valid, bn, NULL); + } else { + ray_valid_t valid = { NULL, c->val_types[a], false }; + c->vts[a]->update_batch(states, c->block, gid, NULL, &valid, bn, NULL); + } + } + } + } + agg_ts_bucket_free(b); /* consumed by this partition only */ + } + if (poom) { agg_ts_merge_free(&m, false); pr->oom = 1; continue; } + agg_ts_merge_free(&m, true); + pr->states = m.states; pr->first_row = m.first_row; pr->keys = m.keys; pr->ng = m.ng; + } + ray_free_raw(stack); + for (uint32_t a = 0; a < n_aggs && gv; a++) { ray_free_raw(gv[a]); ray_free_raw(gy[a]); } + ray_free_raw(gid); scratch_free(ptr_hdr); +} + +/* Gate sample: AGG_TS_SAMPLE_TASKS slices of AGG_TS_SAMPLE_PER single rows, + * each slice hashed into its own small open-addressing set by one pool + * task (the reads are cache misses at scattered positions, and with a + * selection each position costs a cursor placement; serial they were + * 1-2 ms, more than a short radix query can afford). The slices are + * merged into one count set afterwards. */ +#define AGG_TS_SAMPLE_TASKS 16 +#define AGG_TS_SAMPLE_PER (AGG_TS_SAMPLE / AGG_TS_SAMPLE_TASKS) +#define AGG_TS_SAMPLE_SETCAP (AGG_TS_SAMPLE_PER * 4) +/* Serial pre-check on the calling thread before the parallel sample, in + * two stages over scattered single rows. Stage 1: AGG_TS_PRE_SAMPLE rows; + * at most AGG_TS_PRE_REPEATS repeated keys among them declines outright + * (the birthday estimate n^2 / (2 repeats) is then >= 128k groups, five + * times the admission cap), so a near-unique key costs a few hundred + * reads and no dispatch. Stage 2 runs only when stage 1 is ambiguous + * (AGG_TS_PRE_REPEATS < repeats < AGG_TS_PRE_CLEAR, a birthday estimate + * between ~4k and ~65k groups): AGG_TS_PRE_SAMPLE2 rows in all, and a + * birthday estimate of at least AGG_TS_PRE_DECLINE_X times the cap + * declines — a 50k-group key repeats ~10 times among 1024 rows (declined + * at <= 14, ~88% of the time), a key at the cap ~21 times (declined ~5%), + * one at 15k ~35 times (never), so the 2x-5x-the-cap band rarely pays for + * the parallel sample while low cardinalities pay only stage 1. */ +#define AGG_TS_PRE_SAMPLE 512 +#define AGG_TS_PRE_REPEATS 1 +#define AGG_TS_PRE_CLEAR 32 +#define AGG_TS_PRE_SAMPLE2 1024 +#define AGG_TS_PRE_DECLINE_X 1.5 +typedef struct { + ray_t** key_cols; + const void** key_data; + uint32_t n_keys; + int64_t n_in; + int64_t step; + ray_t* sel; + const int64_t* sel_prefix; + uint64_t* hs; /* [tasks * SETCAP] key hash | 1, 0 = empty */ + uint16_t* cnt; /* [tasks * SETCAP] */ + int64_t* keys; /* [tasks * n_keys] packed-key scratch */ + int64_t* n; /* [tasks] rows sampled */ +} agg_ts_sample_ctx_t; + +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; + 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* 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++) { + 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, 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); + 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++; + } + c->n[t] = n; + } +} + +/* Serial pre-check on the calling thread, before any allocation or + * dispatch: AGG_TS_PRE_SAMPLE scattered single rows (selected rows under a + * filter); true when at most AGG_TS_PRE_REPEATS keys repeat among them, + * i.e. the key is near-unique and the strategy must decline. */ +/* A selected row of the segment holding ORIGINAL position `pos`, read + * straight from the selection: the row itself in an ALL segment, a + * pseudo-random entry (by `salt`) of a MIX segment's index slice — one + * cache line for the slice and one for the key, where a cursor placement + * by selected ordinal costs a prefix search plus a decode. False for a + * NONE segment. */ +static inline bool agg_ts_sel_row_at(const uint8_t* flags, const uint32_t* offsets, + const uint16_t* idx, int64_t pos, uint64_t salt, + int64_t* row) { + uint32_t seg = (uint32_t)(pos / RAY_MORSEL_ELEMS); + uint8_t f = flags[seg]; + if (f == RAY_SEL_NONE) return false; + if (f == RAY_SEL_ALL) { *row = pos; return true; } + uint32_t len = offsets[seg + 1] - offsets[seg]; + if (len == 0) return false; + const uint16_t* slice = idx + offsets[seg]; + *row = (int64_t)seg * RAY_MORSEL_ELEMS + slice[salt % len]; + 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) { + (void)sel_prefix; + enum { PRECAP = AGG_TS_PRE_SAMPLE2 * 4 }; + int64_t n_in = sel ? n_sel : nrows; + if (n_in < AGG_TS_SAMPLE) return false; + const uint8_t* sflags = sel ? ray_rowsel_flags(sel) : NULL; + const uint32_t* soffsets = sel ? ray_rowsel_offsets(sel) : NULL; + const uint16_t* sidx = sel ? ray_rowsel_idx(sel) : NULL; + 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*))); + 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]); + 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 + * one (spread over the whole input), stage 2 fills in the rest. A + * position whose segment has no selected row is skipped, so a decision + * needs at least half the intended rows; otherwise the full gate, which + * samples by selected ordinal, decides. */ + 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; + int64_t d = 0, n = 0; + bool declined = false; + for (int64_t phase = 0; phase < ratio && !declined; phase++) { + for (int64_t j = 0; j < AGG_TS_PRE_SAMPLE; j++) { + int64_t i = j * ratio + phase; + uint64_t jit = ray_hash_i64(i + 7919); + int64_t pos = i * pstep + (int64_t)(jit % (uint64_t)pstep); + 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); + 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); + if (!phs[at]) { phs[at] = h; d++; } + n++; + } + if (n < AGG_TS_PRE_SAMPLE / 2) break; /* too few selected: full gate decides */ + int64_t repeats = n - d; + if (phase == 0) { + if (repeats <= AGG_TS_PRE_REPEATS) declined = true; + else if (repeats >= AGG_TS_PRE_CLEAR) break; /* clearly low: no stage 2 */ + } + } + if (!declined && n >= AGG_TS_PRE_SAMPLE2 / 2) { + int64_t repeats = n - d; + 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; + } + scratch_free(pk_hdr); + return declined; +} + +/* Chao1 estimate of the distinct key count from AGG_TS_SAMPLE SINGLE rows + * at evenly spaced positions (hashed jitter inside each stride). One row + * per position, never a run of neighbours: real tables are often sorted + * or sessionised, so a key with millions of distinct values still repeats + * in short runs of consecutive rows, and a sample that reads neighbours + * counts those runs as repeats — the estimate collapses and a group-by + * with millions of groups is admitted (measured 1.3-1.9x slower than the + * radix scatter). Rows far apart only repeat when the key really is + * frequent. With a selection the sample is drawn from the SELECTED rows + * (ordinals decoded through the selection cursor): the grouped keys are + * those rows, and a sample of the whole table can look low-cardinality + * while the surviving rows are near-unique (a `where: (!= phrase "")` + * over a column that is mostly empty). Chao1 is a lower bound for skewed + * abundances, so *unseen_pct also reports the Good-Turing share of rows + * 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, + uint32_t n_keys, int64_t nrows, + ray_t* sel, const int64_t* sel_prefix, int64_t n_sel, + int* unseen_pct) { + enum { CAP = 16384, PRECAP = AGG_TS_PRE_SAMPLE * 4 }; + int64_t n_in = sel ? n_sel : nrows; + *unseen_pct = 0; + if (n_in < AGG_TS_SAMPLE) return (double)n_in; + size_t nk = n_keys ? n_keys : 1; + size_t set_bytes = (size_t)AGG_TS_SAMPLE_TASKS * AGG_TS_SAMPLE_SETCAP; + ray_t* hdr = NULL; + uint64_t* hs = (uint64_t*)scratch_calloc(&hdr, + set_bytes * sizeof(uint64_t) + set_bytes * sizeof(uint16_t) + + (size_t)AGG_TS_SAMPLE_TASKS * nk * sizeof(int64_t) + + (size_t)AGG_TS_SAMPLE_TASKS * sizeof(int64_t) + + CAP * sizeof(uint64_t) + CAP * sizeof(uint16_t)); + if (!hs) return (double)n_in; + uint16_t* cnt = (uint16_t*)(hs + set_bytes); + int64_t* keys = (int64_t*)(cnt + set_bytes); + int64_t* ns = keys + (size_t)AGG_TS_SAMPLE_TASKS * nk; + 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, + .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 (ray_pool_par_dispatch_ok(pool, AGG_TS_SAMPLE, 1)) + ray_pool_dispatch_n(pool, agg_ts_sample_fn, &ctx, AGG_TS_SAMPLE_TASKS); + else + agg_ts_sample_fn(&ctx, 0, 0, AGG_TS_SAMPLE_TASKS); + /* Merge the slices' counts into one set. */ + int64_t d = 0, n = 0; + for (int t = 0; t < AGG_TS_SAMPLE_TASKS; t++) { + n += ns[t]; + const uint64_t* th = hs + (size_t)t * AGG_TS_SAMPLE_SETCAP; + const uint16_t* tc = cnt + (size_t)t * AGG_TS_SAMPLE_SETCAP; + for (int i = 0; i < AGG_TS_SAMPLE_SETCAP; i++) { + uint64_t h = th[i]; + if (!h) continue; + uint64_t at = h & (CAP - 1); + while (ghs[at] && ghs[at] != h) at = (at + 1) & (CAP - 1); + if (!ghs[at]) { ghs[at] = h; d++; } + gcnt[at] = (uint16_t)(gcnt[at] + tc[i]); + } + } + int64_t f1 = 0, f2 = 0; + for (int64_t i = 0; i < CAP; i++) { + if (gcnt[i] == 1) f1++; else if (gcnt[i] == 2) f2++; + } + scratch_free(hdr); + if (n <= 0) return (double)n_in; + *unseen_pct = (int)(f1 * 100 / n); + if (d == n) return 9.2e18; + return (double)d + (f2 > 0 ? (double)f1 * (double)f1 / (2.0 * (double)f2) + : (double)f1 * (double)(f1 - 1) / 2.0); +} + +/* Declines (returns NULL, nothing recorded or allocated) when the sample + * 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, + 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) { + ray_op_ext_t* ext = find_ext(g, op->id); + uint32_t n_keys = ext->n_keys, n_aggs = ext->n_aggs; + ray_pool_t* pool = ray_pool_get(); + uint32_t nw = ray_pool_total_workers(pool); + + /* 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_profile_tick("tablestack: gate declined"); + return NULL; + } + + agg_desc_t d; + if (!agg_desc_init(&d, g, ext, tbl, key_cols)) return ray_error("oom", NULL); + + int64_t n_in = sel ? n_sel : nrows; + if (n_in < 0) n_in = 0; + /* Logical tasks: a few per worker, never fewer rows than a table is + * worth; the task -> range map depends on (rows, workers) only. */ + uint64_t want = (uint64_t)n_in / AGG_TS_TASK_ROWS; + uint64_t max_tasks = nw > 1 ? (uint64_t)nw * AGG_TS_TASKS_PER_WORKER : 1; + if (want > max_tasks) want = max_tasks; + if (want < 1) want = 1; + uint32_t n_tasks = (uint32_t)want; + int64_t task_rows = (n_in + n_tasks - 1) / n_tasks; + if (task_rows < 1) task_rows = 1; + + /* Gate + initial table size from one sample of the grouped rows (the + * selected rows under a pushed filter). */ + 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); + 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++; + /* Every worker probes its own table at random: the entries the tables + * in flight touch (plus their tag arrays) must stay in the last-level + * cache together or each probe misses to DRAM (the same bound the dense + * task-local slabs use; an unreported cache assumes 32 MB). Wide + * aggregate states shrink the admitted group count accordingly. */ + uint64_t llc_bytes = ray_cache_llc_bytes(); + double cache_budget = (llc_bytes ? (double)llc_bytes : 32.0 * 1048576.0) * 0.75; + double table_bytes = est * (double)estride + (double)((int64_t)1 << init_bits); + /* Chao1 under-estimates a long tail behind a repeated head (a few hot + * keys supply the pairs its formula divides by while the tail stays + * unseen): when more than AGG_TS_GATE_UNSEEN_PCT of the sampled rows + * carry a key the sample saw once, most rows would open a new entry in + * their task's table whatever the estimate says — decline. */ + if (est > (double)AGG_TS_GATE_GROUPS || est * AGG_TS_GATE_REPEAT > (double)task_rows || + unseen_pct > AGG_TS_GATE_UNSEEN_PCT || + table_bytes * (double)nw > cache_budget) { + agg_desc_free(&d); + ray_profile_tick("tablestack: gate declined"); + return NULL; + } + agg_route_record(AGG_ROUTE_V2_TABLESTACK); + + /* Record layout (scatter) + entry layout (tables), one carve. */ + ray_t* off_hdr; + size_t* val_off = (size_t*)scratch_calloc(&off_hdr, + 3u * (size_t)(n_aggs ? n_aggs : 1) * sizeof(size_t)); + if (!val_off) { agg_desc_free(&d); return ray_error("oom", NULL); } + size_t* val2_off = val_off + (n_aggs ? n_aggs : 1); + 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]; } + } + size_t row_off = rec_cur; rec_cur += 8; + size_t rec = (rec_cur + 7u) & ~(size_t)7u; + for (uint32_t a = 0; a < n_aggs; a++) ent_off[a] = state_off + off[a]; + + /* Merge partitions: enough for the pool, a power of two no larger than + * the smallest table (its slot range per partition must be >= 1). */ + uint32_t n_parts = 64; + while (n_parts < 8u * nw && n_parts < 1024u) n_parts <<= 1; + + agg_ts_task_t* tasks = ray_calloc_raw((size_t)n_tasks * sizeof(agg_ts_task_t)); + agg_radix_part_t* parts = ray_calloc_raw((size_t)n_parts * sizeof(agg_radix_part_t)); + bool alloc_ok = tasks && parts; + /* Each task's first table is carved HERE, on the calling thread that + * also frees it after the merge: an allocation made by a worker and + * freed by another thread is parked on the owner's foreign list, and + * tens of such tables per query would shift the heap the next query + * runs on. Growth and pushed tables (rarer) still come from workers. */ + for (uint32_t t = 0; alloc_ok && t < n_tasks; t++) { + tasks[t].top = agg_ts_table_new(init_bits, estride); + if (!tasks[t].top) alloc_ok = false; else tasks[t].n_tables = 1; + } + if (!alloc_ok) { + if (tasks) for (uint32_t t = 0; t < n_tasks; t++) agg_ts_table_free(tasks[t].top); + ray_free_raw(tasks); ray_free_raw(parts); + 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); + } + + 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, + .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 }, + .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), + .init_bits = init_bits, + .n_in = n_in, .task_rows = task_rows, .n_tasks = n_tasks, + .tasks = tasks, .parts = parts, + .sel = sel, .sel_prefix = sel_prefix, + }; + + ray_pool_dispatch_n(pool, agg_ts_phase1_fn, &ctx, n_tasks); + bool cancelled = pool_cancelled(pool); + 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++) { + if (tasks[t].oom) oom = 1; + if (tasks[t].scatter) scatter_tasks++; + tables += tasks[t].n_tables; + cand += tasks[t].entries + tasks[t].scattered; + } + ctx.merge_cand = cand; + route_stats.ts_tasks = n_tasks; + route_stats.ts_scatter_tasks = scatter_tasks; + route_stats.ts_tables = tables; + ray_profile_tick("tablestack: aggregated tasks"); + + if (!cancelled && !oom) { + ray_pool_dispatch_n(pool, agg_ts_merge_fn, &ctx, n_parts); + cancelled = pool_cancelled(pool); + for (uint32_t p = 0; p < n_parts; p++) if (parts[p].oom) { oom = 1; break; } + } + for (uint32_t t = 0; t < n_tasks; t++) agg_ts_task_free(&tasks[t], n_parts); + ray_free_raw(tasks); + scratch_free(off_hdr); + ray_profile_tick("tablestack: merged partitions"); + + if (cancelled || oom) { + agg_radix_parts_destroy(parts, n_parts, vts, off, block, n_aggs); + ray_free_raw(parts); + agg_desc_free(&d); + 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, n_in, group_limit, efp); +} + static ray_t* agg_build_compact(ray_graph_t* g, ray_op_t* op, ray_t* tbl, int64_t* idx, int64_t n_sel); @@ -4988,6 +6169,419 @@ static ray_t* exec_group_v2_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, return r; } +/* ══════════════════════════════════════════════════════════════════════ + * First-N groups for an unordered `take: N`. + * + * With a HEAD(GROUP) limit hint and an input large enough for the parallel + * strategies, every route exec_group_v2_run_inner can take for an int/SYM- + * keyed streaming group emits the groups in first-seen order and keeps the N + * with the smallest first row (task-local dense selects them in + * agg_dense_finish, radix in agg_radix_select_first_n or its first-seen + * restore; the shared and partitioned dense strategies are gated off by the + * limit). Those N groups are the first N distinct key tuples in (selected) + * row order, so they can be found before aggregating anything: + * + * 1. a serial scan from the first selected row collects the first N + * distinct key tuples into a small hash set; + * 2. a parallel pass collects, in row order, every selected row whose key + * is in the set, and the unchanged strategy dispatch aggregates just + * those rows (a compact table of the keys and aggregate inputs), so each + * aggregate covers ALL rows of its group; + * 3. the re-run gets the same limit (all N groups), so its routes keep + * first-seen order too; the order is still checked against the set's + * ranks and put right if a route ever disagrees. + * + * Admitted aggregates are the ones whose value does not depend on the order + * rows are folded in: count of any input, and sum/avg/min/max over integer + * and temporal inputs (a float sum regroups the additions). The pre-pass + * gives up — the caller runs the full aggregation and only the probe is + * 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 */ + +bool ray_agg_first_n = true; +static _Thread_local bool firstn_nested; /* inside the pre-pass's own group run */ + +typedef struct { + int64_t* keys; /* cap * n_keys */ + int32_t* rank; /* cap; -1 marks an empty slot */ + uint64_t* bloom; /* 1 << bbits bits over the members' hashes */ + uint32_t n_keys; + uint32_t bits; /* cap = 1 << bits */ + uint32_t bbits; + int64_t n; /* tuples inserted; rank = insertion order */ +} agg_firstn_set_t; + +/* Tuple hash, folded one key at a time so a morsel can be hashed one key + * COLUMN at a time (agg_firstn_hash_block) with the same result. */ +#define AGG_FIRSTN_SEED 0x9E3779B97F4A7C15ULL +#define AGG_FIRSTN_MIX(h, v) \ + do { (h) = ((h) ^ (uint64_t)(v)) * 0x9E3779B97F4A7C15ULL; (h) ^= (h) >> 32; } while (0) +#define AGG_FIRSTN_FINAL(h) ((h) * 0xD6E8FEB86659FD93ULL) + +static inline uint64_t agg_firstn_hash(const int64_t* kv, uint32_t n_keys) { + uint64_t h = AGG_FIRSTN_SEED; + for (uint32_t k = 0; k < n_keys; k++) AGG_FIRSTN_MIX(h, kv[k]); + return AGG_FIRSTN_FINAL(h); +} + +/* Rank of the tuple (hash `hv`), or -1 when absent. With `insert`, an absent + * tuple is added with the next rank (the caller keeps the set a quarter full). */ +static inline int64_t agg_firstn_probe(agg_firstn_set_t* s, const int64_t* kv, + uint64_t hv, bool insert) { + uint64_t mask = ((uint64_t)1 << s->bits) - 1; + for (uint64_t i = hv >> (64 - s->bits);; i = (i + 1) & mask) { + int32_t r = s->rank[i]; + int64_t* sk = s->keys + i * s->n_keys; + if (r < 0) { + if (!insert) return -1; + for (uint32_t k = 0; k < s->n_keys; k++) sk[k] = kv[k]; + s->rank[i] = (int32_t)s->n; + s->n++; + return -1; + } + uint32_t k = 0; + while (k < s->n_keys && sk[k] == kv[k]) k++; + if (k == s->n_keys) return r; + } +} + +/* 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, + int64_t b, int64_t n) { + switch (col->type) { + 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 (col->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(col, data, b + i)); + break; + } +} + +#define AGG_FIRSTN_LOCAL 1024 /* matches a task keeps before spilling */ + +typedef struct { + agg_firstn_set_t* set; + ray_t** key_cols; + const void** key_data; + uint32_t n_keys; + int64_t nrows; + ray_t* sel; /* rowsel or NULL */ + uint32_t n_segs, tasks; + int64_t* counts; /* per task: matches; then the write offset */ + 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 */ +} agg_firstn_ctx_t; + +/* One task: the selected rows of its morsel segments whose key tuple is in + * the set, in row order. Each morsel is hashed one key column at a time; the + * bloom bit rejects almost every row before any per-row key read. */ +static void agg_firstn_task(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; + agg_firstn_set_t* set = c->set; + uint32_t n_keys = c->n_keys; + uint64_t hb[RAY_MORSEL_ELEMS]; + int64_t* kv = c->kvs + (int64_t)t * n_keys; + const uint8_t* fl = c->sel ? ray_rowsel_flags(c->sel) : NULL; + const uint32_t* of = c->sel ? ray_rowsel_offsets(c->sel) : NULL; + const uint16_t* ix = c->sel ? ray_rowsel_idx(c->sel) : NULL; + int64_t* out = c->out ? c->out + c->counts[t] : c->local + (int64_t)t * AGG_FIRSTN_LOCAL; + int64_t out_cap = c->out ? INT64_MAX : AGG_FIRSTN_LOCAL; + uint32_t bshift = 64 - set->bbits; + int64_t n = 0; + for (int64_t seg = s0; 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; + 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, c->key_cols[k], c->key_data[k], b, len); + 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; j++) { + int64_t i = mix ? (int64_t)ix[j] : j; + uint64_t hv = AGG_FIRSTN_FINAL(hb[i]); + uint64_t bit = hv >> bshift; + if (!((set->bloom[bit >> 6] >> (bit & 63)) & 1)) continue; + for (uint32_t k = 0; k < n_keys; k++) + kv[k] = agg_read_key_i64(c->key_cols[k], c->key_data[k], b + i); + if (agg_firstn_probe(set, kv, hv, false) < 0) continue; + if (n < out_cap) out[n] = b + i; + n++; + } + } + if (!c->out) c->counts[t] = n; +} + +static void agg_firstn_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + for (int64_t t = start; t < end; t++) agg_firstn_task((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++) + 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: break; + default: return false; + } + for (uint32_t a = 0; a < ext->n_aggs; a++) { + uint16_t aop = ext->agg_ops[a]; + if (aop != OP_COUNT && aop != OP_SUM && aop != OP_AVG && aop != OP_MIN && aop != OP_MAX) + return false; + if (ext->agg_ins2 && ext->agg_ins2[a] != RAY_OP_NONE) return false; + bool has_in = ext->agg_ins && ext->agg_ins[a] != RAY_OP_NONE; + 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; + if (aop == OP_COUNT) continue; + switch (col->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 */ + } + } + return true; +} + +/* 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_op_ext_t* ext = find_ext(g, op->id); + ray_pool_t* pool = ray_pool_get(); + int64_t eff_n = sel ? n_sel : nrows; + /* 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; + + uint32_t n_keys = ext->n_keys; + uint32_t bits = 4; + while (((int64_t)1 << bits) < group_limit * 4) bits++; + uint32_t bbits = bits + 6 > 16 ? bits + 6 : 16; + int64_t cap = (int64_t)1 << bits; + ray_t* res = NULL; + ray_t* kv_hdr = NULL; + /* one carve: the probe tuple, then the key data pointers */ + int64_t* kv = (int64_t*)scratch_alloc(&kv_hdr, (size_t)n_keys * 2 * sizeof(int64_t)); + agg_firstn_set_t set = { .n_keys = n_keys, .bits = bits, .bbits = bbits, .n = 0 }; + set.keys = ray_alloc_raw((size_t)cap * n_keys * sizeof(int64_t)); + set.rank = ray_alloc_raw((size_t)cap * sizeof(int32_t)); + set.bloom = ray_calloc_raw(((size_t)1 << bbits) / 8); + int64_t* counts = NULL; + int64_t* local = NULL; + int64_t* kvs = NULL; + int64_t* idx = NULL; + int64_t* perm = NULL; + ray_t* compact = NULL; + ray_t* sub = 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); + for (uint32_t k = 0; k < n_keys; k++) key_data[k] = ray_data(key_cols[k]); + 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 */ + { + 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; + for (int64_t seg = 0; seg < n_segs && set.n < group_limit && scanned < budget; 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 < n_keys; k++) + kv[k] = agg_read_key_i64(key_cols[k], key_data[k], row); + agg_firstn_probe(&set, kv, agg_firstn_hash(kv, n_keys), true); + } + } + if (set.n < group_limit) goto done; /* few groups or long runs: full run */ + } + for (int64_t i = 0; i < cap; i++) { + if (set.rank[i] < 0) continue; + uint64_t bit = agg_firstn_hash(set.keys + i * n_keys, n_keys) >> (64 - bbits); + set.bloom[bit >> 6] |= (uint64_t)1 << (bit & 63); + } + + /* the share of rows the N groups hold, from evenly spaced source rows */ + { + int64_t samples = nrows < AGG_FIRSTN_SAMPLES ? nrows : AGG_FIRSTN_SAMPLES; + int64_t step = nrows / samples, hits = 0; + for (int64_t i = 0; i < samples; i++) { + for (uint32_t k = 0; k < n_keys; k++) + 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; + } + + /* 2. the selected rows of those groups, in row order: each task keeps its + * first AGG_FIRSTN_LOCAL matches; a second pass writes them all only when + * some task had more. */ + uint32_t tasks = 1; + if (ray_pool_par_dispatch_ok(pool, eff_n, RAY_PARALLEL_THRESHOLD)) { + uint32_t want = ray_pool_total_workers(pool) * 4; + if (want > RAY_POOL_INIT_TASKS) want = RAY_POOL_INIT_TASKS; + tasks = want < n_segs ? want : n_segs; + if (tasks < 1) tasks = 1; + } + counts = ray_alloc_raw((size_t)tasks * sizeof(int64_t)); + local = ray_alloc_raw((size_t)tasks * AGG_FIRSTN_LOCAL * sizeof(int64_t)); + kvs = ray_alloc_raw((size_t)tasks * n_keys * sizeof(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); + else agg_firstn_fn(&c, 0, 0, 1); + if (agg_cancelled()) { res = ray_error("cancel", NULL); goto done; } + int64_t m = 0; + bool spilled = false; + for (uint32_t t = 0; t < tasks; 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 */ + 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); + else agg_firstn_fn(&c, 0, 0, 1); + if (agg_cancelled()) { res = ray_error("cancel", NULL); goto done; } + } else { + int64_t off = 0; + for (uint32_t t = 0; t < tasks; t++) { + memcpy(idx + off, local + (int64_t)t * AGG_FIRSTN_LOCAL, (size_t)counts[t] * sizeof(int64_t)); + off += counts[t]; + } + } + + compact = agg_build_compact(g, op, tbl, idx, m); + if (!compact || RAY_IS_ERR(compact)) { + res = compact ? compact : ray_error("oom", NULL); compact = NULL; goto done; + } + /* The same bounded emit as the full run: every route keeps first-seen + * order under a limit, and the limit is the whole group count here. The + * nested run must not re-enter the pre-pass. */ + firstn_nested = true; + sub = exec_group_v2_run(g, op, compact, m, NULL, NULL, 0, set.n, NULL); + firstn_nested = false; + 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 || + 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; + } + if (identity) { res = sub; sub = NULL; } + else { + ray_t* pv = ray_vec_new(RAY_I64, set.n); + if (!pv || RAY_IS_ERR(pv)) { res = pv ? pv : ray_error("oom", NULL); goto done; } + memcpy(ray_data(pv), perm, (size_t)set.n * sizeof(int64_t)); + pv->len = set.n; + res = ray_at_fn(sub, pv); + ray_release(pv); + if (!res) res = ray_error("oom", NULL); + } + if (!RAY_IS_ERR(res)) { + route_stats.first_n++; + ray_profile_tick("group: first-N keys"); + } + +done: + if (sub) ray_release(sub); + if (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); + if (kv_hdr) scratch_free(kv_hdr); + return res; +} + 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, @@ -5045,6 +6639,12 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, scratch_free(kc_hdr); return result; } + /* Unordered take: N — find the N groups first, aggregate only them. */ + 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; } + } + /* 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); } @@ -5262,11 +6862,20 @@ static ray_t* exec_group_v2_run_inner(ray_graph_t* g, ray_op_t* op, ray_t* tbl, agg_vo_free(&vo); agg_dense_plan_free(&dp); scratch_free(kc_hdr); return r; } if (keys_intsym) { - agg_route_record(AGG_ROUTE_V2_RADIX); - /* Sparse ranges and excessive dense worker traffic use radix. */ - ray_t* r = exec_group_v2_parallel_radix(g, op, tbl, nrows, - key_cols, key_syms, vts, off, block, sel, sel_prefix, n_sel, - group_limit, efp); + /* 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. */ + 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, + group_limit, efp) + : NULL; + if (!r) { /* declined by its sample gate (or disabled) */ + agg_route_record(AGG_ROUTE_V2_RADIX); + r = exec_group_v2_parallel_radix(g, op, tbl, nrows, + 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; } /* Hash fallback (F64 / STR keys): not a chunked strategy — compact. */ @@ -5421,7 +7030,10 @@ ray_t* exec_group_v2(ray_graph_t* g, ray_op_t* op, ray_t* tbl, * groups themselves; the other routes trim their full result. */ ray_group_emit_filter_t ef = ray_group_emit_filter_active(); const ray_group_emit_filter_t* efp = ef.enabled ? &ef : NULL; - if (!g || !g->selection) + /* exec_group_v2_run reads g's op extensions unconditionally; a NULL + * graph is an error here, not a request for an unfiltered run. */ + if (!g) return ray_error("nyi", NULL); + if (!g->selection) return exec_group_v2_run(g, op, tbl, ray_table_nrows(tbl), NULL, NULL, 0, group_limit, efp); diff --git a/src/ops/agg_engine.h b/src/ops/agg_engine.h index e31af91a5..6029e234f 100644 --- a/src/ops/agg_engine.h +++ b/src/ops/agg_engine.h @@ -10,6 +10,15 @@ * the query (see agg_v2_can_handle). Enabled by default. */ extern bool ray_agg_engine_v2; +/* Test/feature knob: let an unordered grouped `take: N` find its N groups + * before aggregating and fold only their rows (agg_first_n_run). On by default. */ +extern bool ray_agg_first_n; + +/* Test/feature knob: int/SYM-key parallel groups that are not dense pre- + * aggregate into per-task top-bit tables (table stack) and scatter only + * all-distinct tails; off = the former radix scatter of every row. */ +extern bool ray_agg_tablestack; + /* Admission is pure: inspecting a plan must not change execution diagnostics. */ typedef enum { AGG_V2_ADMITTED, @@ -39,6 +48,7 @@ typedef enum { AGG_ROUTE_V2_HASH, AGG_ROUTE_V2_SMALLHASH, AGG_ROUTE_V2_INDEXED, + AGG_ROUTE_V2_TABLESTACK, AGG_ROUTE_COUNT, } agg_route_t; @@ -66,6 +76,10 @@ typedef struct { uint64_t key_domain_evals; /* computed keys evaluated once per distinct symbol */ bool topn_native; /* last v2 run selected the emit filter's top-N itself */ int64_t topn_kept; /* groups kept by that selection (ties included) */ + uint64_t first_n; /* unordered take: N answered by the first-N pre-pass */ + 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 */ } agg_route_stats_t; void agg_route_reset(void); void agg_route_note_key_domain(void); diff --git a/src/ops/builtins.c b/src/ops/builtins.c index 9b2fb31bf..57c5fe104 100644 --- a/src/ops/builtins.c +++ b/src/ops/builtins.c @@ -59,6 +59,7 @@ static inline double clear_neg_zero(double v) { #include #include #include +#include #include "mem/heap.h" /* ray_heap_anon_watermark/committed — read budget */ #if !defined(RAY_OS_WINDOWS) #include @@ -327,6 +328,11 @@ ray_t* ray_show_fn(ray_t** args, int64_t n) { /* args are pre-materialized by eval — see ray_println_fn. */ for (int64_t i = 0; i < n; i++) { if (!args[i] || RAY_IS_ERR(args[i])) { fprintf(stdout, "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]); + 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); @@ -685,19 +691,8 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) { const char* sym = csv_default_sym_path(dir, sym_path, sizeof(sym_path)); if (!sym) return ray_error("io", NULL); - /* The streaming writer emits raw columns; append chunk-zone indexes to the - * just-written files, then reload so the returned table carries them - * (mmap'd in place). Conversion is the ONLY place a CSV load decides an - * index: `.csv.read` returns an index-free in-memory table, and callers - * that want one on it ask explicitly (.idx.hash / the attrs verbs). - * Without this pass, a converted store would have no block-skip at all. */ - ray_t* tbl = ray_read_splayed(dir, sym); - if (tbl && !RAY_IS_ERR(tbl) && tbl->type == RAY_TABLE) { - ray_splay_build_indexes(dir, tbl); - ray_release(tbl); - tbl = ray_read_splayed(dir, sym); - } - return tbl; + /* The writer builds indexes before publishing its generation. */ + return ray_read_splayed(dir, sym); } ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) { @@ -766,11 +761,30 @@ ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) { } } + /* A new root is staged in .csv-partial, which a failed import + * leaves behind for diagnosis and which then blocks the root. Name it + * in the error rather than returning a bare `io`. */ + char dest[1024], staging[1100]; + bool stale = false; + if (ray_csv_parted_paths(root, dest, sizeof(dest), staging, sizeof(staging)) == RAY_OK) { + struct stat st; + stale = stat(dest, &st) != 0 && stat(staging, &st) == 0; + } + if (stale) + 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); - if (err != RAY_OK) return ray_error(ray_err_code_str(err), NULL); + if (err != RAY_OK) { + struct stat st; + if (stat(dest, &st) != 0 && stat(staging, &st) == 0) + return ray_error(ray_err_code_str(err), "csv.parted: import failed; partial output retained in %s", + staging); + return ray_error(ray_err_code_str(err), NULL); + } ray_t* out = ray_read_parted(root, table_name); if (getenv("RAY_CSV_TRACE") && out && RAY_IS_ERR(out)) { diff --git a/src/ops/cmp.c b/src/ops/cmp.c index ef9da147f..fbbe083de 100644 --- a/src/ops/cmp.c +++ b/src/ops/cmp.c @@ -371,5 +371,35 @@ ray_t* ray_not_fn(ray_t* x) { r->len = n; return r; } + /* Element-wise for numeric and temporal vectors too, as the compiled + * `not` is: true where the cell is zero or null. It used to answer one + * truth value for the whole vector, so a query evaluated through the + * interpreter disagreed with the same query compiled. */ + if (ray_is_vec(x) && (x->type == RAY_U8 || x->type == RAY_I16 || + x->type == RAY_I32 || x->type == RAY_I64 || + x->type == RAY_F32 || x->type == RAY_F64 || + x->type == RAY_DATE || x->type == RAY_TIME || + x->type == RAY_TIMESTAMP)) { + int64_t n = x->len; + ray_t* r = ray_vec_new(RAY_BOOL, n); + if (RAY_IS_ERR(r)) return r; + uint8_t* dr = (uint8_t*)ray_data(r); + const void* src = ray_data(x); + for (int64_t i = 0; i < n; i++) { + bool z; + switch (x->type) { + case RAY_U8: z = ((const uint8_t*)src)[i] == 0; break; + case RAY_I16: z = ((const int16_t*)src)[i] == 0; break; + case RAY_I32: case RAY_DATE: case RAY_TIME: + z = ((const int32_t*)src)[i] == 0; break; + case RAY_F32: z = ((const float*)src)[i] == 0.0f; break; + case RAY_F64: z = ((const double*)src)[i] == 0.0; break; + default: z = ((const int64_t*)src)[i] == 0; break; + } + dr[i] = z || ray_vec_is_null(x, i); + } + r->len = n; + return r; + } return make_bool(is_truthy(x) ? 0 : 1); } diff --git a/src/ops/embedding.c b/src/ops/embedding.c index 855cb67f7..bff2da6cd 100644 --- a/src/ops/embedding.c +++ b/src/ops/embedding.c @@ -569,7 +569,10 @@ ray_t* ray_hnsw_load_fn(ray_t* path) { memcpy(buf, p, len); buf[len] = '\0'; ray_hnsw_t* idx = ray_hnsw_load(buf); - if (!idx) return ray_error("io", NULL); + if (!idx) + return ray_error("io", "hnsw-load: index '%s' is invalid or incomplete; " + "restore a compatible copy or rebuild it", + buf); ray_t* h = hnsw_wrap(idx); if (!h || RAY_IS_ERR(h)) { ray_hnsw_free(idx); return h; } return h; diff --git a/src/ops/exec.c b/src/ops/exec.c index daa2fe30c..bb3c5fefe 100644 --- a/src/ops/exec.c +++ b/src/ops/exec.c @@ -129,6 +129,36 @@ ray_t* materialize_mapcommon_head(ray_t* mc, int64_t n) { return flat; } +/* Materialize the rows `idx[0..n)` (ascending) of a MAPCOMMON column. */ +ray_t* materialize_mapcommon_gather(ray_t* mc, const int64_t* idx, int64_t n) { + ray_t** mc_ptrs = (ray_t**)ray_data(mc); + ray_t* kv = mc_ptrs[0]; + ray_t* rc = mc_ptrs[1]; + int64_t n_parts = kv->len; + int8_t kv_type = kv->type; + size_t esz = (size_t)ray_sym_elem_size(kv_type, kv->attrs); + const char* kdata = (const char*)ray_data(kv); + const int64_t* counts = (const int64_t*)ray_data(rc); + + ray_t* flat = ray_vec_new(kv_type, n); + if (!flat || RAY_IS_ERR(flat)) return ray_error("oom", NULL); + flat->len = n; + /* raw SYM cell ids — adopt the keys carrier's domain (see above) */ + if (kv_type == RAY_SYM) ray_sym_vec_adopt_domain(flat, kv); + + char* out = (char*)ray_data(flat); + int64_t part_idx = 0; + int64_t part_end = n_parts > 0 ? counts[0] : 0; + for (int64_t i = 0; i < n; i++) { + while (part_idx < n_parts - 1 && idx[i] >= part_end) { + part_idx++; + part_end += counts[part_idx]; + } + memcpy(out + (size_t)i * esz, kdata + (size_t)part_idx * esz, esz); + } + return flat; +} + /* Materialize MAPCOMMON through a boolean filter predicate. */ ray_t* materialize_mapcommon_filter(ray_t* mc, ray_t* pred, int64_t pass_count) { ray_t** mc_ptrs = (ray_t**)ray_data(mc); @@ -1595,6 +1625,52 @@ static int idx_filter_in_decode(ray_graph_t* g, ray_op_t* pred_op, return 1; } +/* True when a GROUP node groups by at least one key. */ +static inline bool group_has_keys(ray_graph_t* g, ray_op_t* group_op) { + ray_op_ext_t* gx = find_ext(g, group_op->id); + return gx && gx->n_keys > 0; +} + +/* True when every leaf of the op tree under `id` is a constant or, with + * `reduced`, sits under a reduction. */ +static bool op_tree_leaves(ray_graph_t* g, uint32_t id, bool reduced, int depth) { + if (id >= g->node_count || depth > 64) return false; + ray_op_t* n = &g->nodes[id]; + switch (n->opcode) { + case OP_CONST: return true; + case OP_SCAN: return false; + case OP_SUM: case OP_PROD: case OP_ALL: case OP_ANY: + 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: + if (reduced) return true; + break; + default: break; + } + if (n->arity == 0) return false; + for (uint32_t i = 0; i < n->arity && i < 2; i++) + if (!op_tree_leaves(g, n->in_id[i], reduced, depth + 1)) return false; + if (n->opcode == OP_IF) { /* the else branch rides in the ext */ + ray_op_ext_t* x = find_ext(g, id); + if (!x || !op_tree_leaves(g, x->third_in, reduced, depth + 1)) return false; + } + return true; +} + +/* True when the op tree under `id` carries none of the input's rows: every + * leaf is a constant or sits under a reduction. Tells a scalar-only SELECT + * column (`(+ (sum x) 0)`) from a one-row one, which the column lengths + * cannot on a one-row table (#675). */ +static bool op_tree_is_scalar(ray_graph_t* g, uint32_t id) { + return op_tree_leaves(g, id, true, 0); +} + +/* True when the op tree under `id` reads no column at all, not even under a + * reduction: a literal, or an expression over literals. */ +static bool op_tree_is_const(ray_graph_t* g, uint32_t id) { + return op_tree_leaves(g, id, false, 0); +} + /* Execute a pushed-down filter interposed as a GROUP's inputs[0] * (GROUP predicate pushdown, opt.c Task-3). * @@ -2381,6 +2457,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_release(group_result); return pred; } + if (group_result->type == RAY_TABLE) { + pred = ray_where_mask_coerce(pred, ray_table_nrows(group_result), "where"); + if (!pred || RAY_IS_ERR(pred)) { + ray_release(group_result); + return pred ? pred : ray_error("oom", NULL); + } + } ray_t* result = exec_filter(g, op, group_result, pred); ray_release(pred); @@ -2792,6 +2875,27 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_t* pred = exec_node(g, op_child(g, op, 1)); if (!pred || RAY_IS_ERR(pred)) { ray_release(input); return pred; } + /* Over a table every predicate value goes through the one + * where: rule (ray_where_mask_coerce): a scalar (`(== (count x) + * 5)`, a scalar conjunct of an `and`) or a one-element BOOL is + * spread over the rows; any other vector is a type error. + * Before this, an I64 column fell through to the eager + * exec_filter, which read it as one byte per row (#678). */ + if (input->type == RAY_TABLE && + !(pred->type == RAY_BOOL && pred->len == ray_table_nrows(input))) { + int64_t tn = ray_table_nrows(input); + if (ray_is_atom(pred) && ray_pred_atom_type_ok(pred->type) && + is_truthy(pred)) { + ray_release(pred); /* every row passes: selection unchanged */ + return input; + } + pred = ray_where_mask_coerce(pred, tn, "where"); + if (!pred || RAY_IS_ERR(pred)) { + ray_release(input); + return pred ? pred : ray_error("oom", NULL); + } + } + /* Lazy filter: convert predicate to a rowsel (morsel-local * index list) and install on g->selection instead of * materializing a compacted table. Only for TABLE inputs — @@ -2944,7 +3048,11 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { * materializing that expression over ALL rows — so the * scattered gate matches the projection-side compaction * factor (4x), not the plain-gather tradeoff (16x). */ - if (gx && meta && nrows > 0 && + /* A keyless group (an all-aggregate select) is one row and + * its aggregates read the selection themselves; compacted, + * a no-match where: handed exec_group an empty table and it + * came back with no row (#679, the HEAD arm likewise). */ + if (gx && gx->n_keys > 0 && meta && nrows > 0 && meta->total_pass * (contig ? 2 : 4) <= nrows) { int64_t keep[32]; bool has_expr = false; @@ -3119,7 +3227,13 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { if (res && RAY_IS_ERR(res)) return res; if (res) { owned_tbl = res; tbl = res; } /* NULL → lazy path; g->selection installed, tbl unchanged */ - } else if (g->selection && tbl->type == RAY_TABLE) { + } else if (g->selection && tbl->type == RAY_TABLE && + group_has_keys(g, child_op)) { + /* 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: + * handed exec_group an empty table, which has no rows to + * reduce and came back with no row at all (#679). */ int needs = 0; int64_t nc = ray_table_ncols(tbl); for (int64_t c = 0; c < nc; c++) { @@ -3574,10 +3688,12 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { ray_release(input); return vec ? vec : ray_error("nyi", NULL); } - /* Broadcast scalar atoms to full column vectors */ + /* A scalar atom becomes a one-element column, widened + * below only if another column carries the input's + * rows. Broadcast here, it posed as such a column and + * widened the scalars beside it (#698). */ if (vec->type < 0) { - int64_t nr = ray_table_nrows(input); - ray_t* col = broadcast_scalar(vec, nr); + ray_t* col = ray_enlist_fn(&vec, 1); ray_release(vec); vec = col; if (!vec || RAY_IS_ERR(vec)) { @@ -3600,6 +3716,66 @@ static ray_t* exec_node_inner(ray_graph_t* g, ray_op_t* op) { } } + /* A scalar column, an atom enlisted above or one computed as a + * one-element vector (`(+ (sum x) 0)`, an `if` whose parts are + * all scalar), is broadcast when another column has the input's + * rows. Left alone, the table took its row count from whichever + * column came first and its columns disagreed in length. When + * every column is a scalar the one-row result stays. */ + int64_t nr_in = ray_table_nrows(input); + if (result && !RAY_IS_ERR(result)) { + int64_t rc = ray_table_ncols(result); + 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); + /* a parted column counts its rows across segments */ + if (cv && cv->type > 0 && ray_parted_nrows(cv) == nr_in) { has_full = true; break; } + } + } else { + /* On a one-row input a scalar and a row column have the + * same length: read the ops instead, so a scalar-only + * select under a failing where: is still one row. */ + for (uint32_t c = 0; c < n_cols && !has_full; c++) + if (!op_tree_is_scalar(g, columns[c])) has_full = true; + } + /* A select of literals alone (`{s: 1}`) reduces nothing and + * keeps the input's rows. Beside an aggregate a literal is + * one more scalar, as in a keyless group. */ + if (!has_full) { + bool all_const = true; + for (uint32_t c = 0; c < n_cols && all_const; c++) + if (!op_tree_is_const(g, columns[c])) all_const = false; + has_full = all_const; + } + /* Every column a scalar: the reductions inside them already + * walked the where: selection (exec_reduction), so the + * one-row result is final. Left installed, the selection + * (built for the input's rows) met the one-row result in + * ray_execute_inner's final gather (#675). */ + if (!has_full && g->selection) { + ray_release(g->selection); + g->selection = NULL; + } + /* A LIST here is an atom enlist has no vector for (F32). */ + for (int64_t c = 0; nr_in != 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_t* n_obj = make_i64(nr_in); + ray_t* wide = n_obj ? ray_take_fn(cv, n_obj) : ray_error("oom", NULL); + if (n_obj) ray_release(n_obj); + if (!wide || RAY_IS_ERR(wide)) { + ray_release(result); + g->table = saved_table; + ray_release(input); + return wide ? wide : ray_error("oom", NULL); + } + ray_table_set_col_idx(result, c, wide); + ray_release(wide); + } + } + g->table = saved_table; ray_release(input); return result; @@ -4060,7 +4236,13 @@ ray_t* ray_execute(ray_graph_t* g, ray_op_t* root) { * would reset the elapsed clock and fire premature "final" ticks. */ ray_t* scan_err = validate_scan_columns(g); if (scan_err) return scan_err; - return ray_execute_inner(g, root); + /* Never NULL: callers test RAY_IS_ERR, which is false for NULL, and then + * dereference. The inner paths hand NULL back unchanged when a node, + * a compaction or a merge fails to allocate (the flat path's + * `return result`, the streaming path's seg_tbl / partial / merged + * returns); `(times ...)` would then crash in loop_count. */ + ray_t* result = ray_execute_inner(g, root); + return result ? result : ray_error("oom", NULL); } /* Flatten one parted/mapcommon column into a dense vector (mirrors the diff --git a/src/ops/expr.c b/src/ops/expr.c index a35192083..dbb7ce744 100644 --- a/src/ops/expr.c +++ b/src/ops/expr.c @@ -622,6 +622,16 @@ static bool expr_op_generates_null(uint16_t op, int8_t ot, int8_t t1, bool binar return false; } +/* A CAST may target a temporal type (the DAG retags a bucketed temporal + * column, see the xbar branch of compile_expr_dag). TIMESTAMP is an I64 + * lane and DATE / TIME are I32 lanes: the kernels, and the capability table, + * dispatch on the lane type. */ +static inline int8_t expr_cast_lane_type(int8_t t) { + if (t == RAY_TIMESTAMP) return RAY_I64; + if (t == RAY_DATE || t == RAY_TIME) return RAY_I32; + return t; +} + /* Which (opcode, dst-type, src1-type) shapes have null-aware kernel * variants? Landing per-family: * Task 5: CAST shapes + F64 arithmetic (IEEE-propagating, no variant needed) @@ -630,6 +640,8 @@ static bool expr_op_generates_null(uint16_t op, int8_t ot, int8_t t1, bool binar * F64 MIN2/MAX2 (non-IEEE-propagating, variant added) */ static bool expr_null_capable(uint8_t op, int8_t dt, int8_t t1) { if (op == OP_CAST) { + dt = expr_cast_lane_type(dt); + t1 = expr_cast_lane_type(t1); if (dt == RAY_F64 && t1 != RAY_F64) return true; /* i64→f64: NaN map */ if (dt == RAY_I64 && t1 == RAY_F64) return true; /* f64→i64: NaN→NULL_I64 */ if (dt == RAY_I64 && t1 != RAY_F64) return true; /* narrow widen: sentinel map */ @@ -1446,6 +1458,10 @@ static void expr_exec_binary(uint8_t opcode, uint8_t null_aware, int8_t dt, void * the mark_i64_overflow_as_null post-pass (INT64_MIN result → null). */ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* dp, int8_t t1, const void* ap, int64_t n) { + if (opcode == OP_CAST) { + dt = expr_cast_lane_type(dt); + t1 = expr_cast_lane_type(t1); + } if (dt == RAY_F64) { double* d = (double*)dp; if (t1 == RAY_F64) { @@ -1478,6 +1494,19 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* case OP_CAST: memcpy(d, a, (size_t)n * sizeof(double)); break; default: break; } + } else if (t1 == RAY_I32) { + /* A narrowing CAST leaves an I32 / I16 / 1-byte lane behind; + * read it at its own width, not as int64. */ + const int32_t* a = (const int32_t*)ap; + for (int64_t j = 0; j < n; j++) + d[j] = (null_aware && a[j] == NULL_I32) ? NULL_F64 : (double)a[j]; + } else if (t1 == RAY_I16) { + const int16_t* a = (const int16_t*)ap; + for (int64_t j = 0; j < n; j++) + d[j] = (null_aware && a[j] == NULL_I16) ? NULL_F64 : (double)a[j]; + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + const uint8_t* a = (const uint8_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (double)a[j]; } else { /* CAST i64→f64: with null_aware map NULL_I64 → NULL_F64 */ const int64_t* a = (const int64_t*)ap; if (null_aware) @@ -1518,8 +1547,8 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* case OP_CAST: memcpy(d, a, (size_t)n * sizeof(int64_t)); break; default: break; } - } else if (t1 == RAY_BOOL) { - /* CAST bool→i64 — BOOL scratch is 1 byte per elem (0/1). */ + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + /* CAST bool/u8→i64 — a 1-byte lane. */ const uint8_t* a = (const uint8_t*)ap; for (int64_t j = 0; j < n; j++) d[j] = a[j]; } else if (t1 == RAY_I32 || t1 == RAY_DATE || t1 == RAY_TIME) { @@ -1570,6 +1599,20 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* if (t1 == RAY_F64) { const double* a = (const double*)ap; for (int64_t j = 0; j < n; j++) d[j] = (a[j] != a[j]) ? 1 : 0; + } else if ((t1 == RAY_I32 || t1 == RAY_I16) && !null_aware) { + /* A narrowing CAST of a null-free source truncates: a value + * that lands on the sentinel is still a value. */ + memset(d, 0, (size_t)n); + } else if (t1 == RAY_I32) { + /* A narrowing CAST leaves an I32 / I16 / 1-byte lane: read it + * at its own width, with its own null sentinel. */ + const int32_t* a = (const int32_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (a[j] == NULL_I32) ? 1 : 0; + } else if (t1 == RAY_I16) { + const int16_t* a = (const int16_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (a[j] == NULL_I16) ? 1 : 0; + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + memset(d, 0, (size_t)n); /* no null in a byte lane */ } else { const int64_t* a = (const int64_t*)ap; for (int64_t j = 0; j < n; j++) d[j] = (a[j] == NULL_I64) ? 1 : 0; @@ -1586,16 +1629,44 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* const double* a = (const double*)ap; for (int64_t j = 0; j < n; j++) d[j] = (a[j] != 0.0 && a[j] == a[j]) ? 1 : 0; + } else if (t1 == RAY_I32) { + const int32_t* a = (const int32_t*)ap; + for (int64_t j = 0; j < n; j++) + d[j] = (a[j] != 0 && a[j] != NULL_I32) ? 1 : 0; + } else if (t1 == RAY_I16) { + const int16_t* a = (const int16_t*)ap; + for (int64_t j = 0; j < n; j++) + d[j] = (a[j] != 0 && a[j] != NULL_I16) ? 1 : 0; + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + const uint8_t* a = (const uint8_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = a[j] ? 1 : 0; } else { const int64_t* a = (const int64_t*)ap; for (int64_t j = 0; j < n; j++) d[j] = (a[j] != 0 && a[j] != NULL_I64) ? 1 : 0; } - } else { - const uint8_t* a = (const uint8_t*)ap; - switch (opcode) { - case OP_NOT: for (int64_t j = 0; j < n; j++) d[j] = !a[j]; break; - default: break; + } else if (opcode == OP_NOT) { + /* The source lane keeps its producer's width: a REG_SCAN of a + * BOOL column is widened to I64 (register-widening invariant), + * a comparison result is a 1-byte BOOL scratch, a narrowing + * CAST leaves I32/I16, a float lane is F64. Read it at that + * width (#693: the I64-widened BOOL column read as bytes gave + * `!0` = true for every lane but the first). */ + if (t1 == RAY_F64) { + const double* a = (const double*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (a[j] == 0.0) ? 1 : 0; + } else if (t1 == RAY_I64) { + const int64_t* a = (const int64_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (a[j] == 0) ? 1 : 0; + } else if (t1 == RAY_I32) { + const int32_t* a = (const int32_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (a[j] == 0) ? 1 : 0; + } else if (t1 == RAY_I16) { + const int16_t* a = (const int16_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (a[j] == 0) ? 1 : 0; + } else { + const uint8_t* a = (const uint8_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = !a[j]; } } } else if (dt == RAY_I32) { @@ -1627,6 +1698,15 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* d[j] = ray_cast_f64_to_i32_null(a[j]); else for (int64_t j = 0; j < n; j++) d[j] = ray_cast_f64_to_i32_null(a[j]); + } else if (t1 == RAY_I32) { + memcpy(d, ap, (size_t)n * sizeof(int32_t)); + } else if (t1 == RAY_I16) { + const int16_t* a = (const int16_t*)ap; + for (int64_t j = 0; j < n; j++) + d[j] = (null_aware && a[j] == NULL_I16) ? NULL_I32 : (int32_t)a[j]; + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + const uint8_t* a = (const uint8_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = a[j]; } else { const int64_t* a = (const int64_t*)ap; if (null_aware) @@ -1653,6 +1733,15 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* d[j] = ray_cast_f64_to_i16_null(a[j]); else for (int64_t j = 0; j < n; j++) d[j] = ray_cast_f64_to_i16_null(a[j]); + } else if (t1 == RAY_I32) { + const int32_t* a = (const int32_t*)ap; + for (int64_t j = 0; j < n; j++) + d[j] = (null_aware && a[j] == NULL_I32) ? NULL_I16 : (int16_t)a[j]; + } else if (t1 == RAY_I16) { + memcpy(d, ap, (size_t)n * sizeof(int16_t)); + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + const uint8_t* a = (const uint8_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = a[j]; } else { const int64_t* a = (const int64_t*)ap; if (null_aware) @@ -1666,6 +1755,14 @@ static void expr_exec_unary(uint8_t opcode, uint8_t null_aware, int8_t dt, void* if (t1 == RAY_F64) { const double* a = (const double*)ap; for (int64_t j = 0; j < n; j++) d[j] = ray_cast_f64_to_u8_null(a[j]); + } else if (t1 == RAY_I32) { + const int32_t* a = (const int32_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (uint8_t)a[j]; + } else if (t1 == RAY_I16) { + const int16_t* a = (const int16_t*)ap; + for (int64_t j = 0; j < n; j++) d[j] = (uint8_t)a[j]; + } else if (t1 == RAY_BOOL || t1 == RAY_U8) { + memcpy(d, ap, (size_t)n); } else { const int64_t* a = (const int64_t*)ap; for (int64_t j = 0; j < n; j++) d[j] = (uint8_t)a[j]; @@ -2742,8 +2839,8 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { } out_off += n; } - } else if (in_type == RAY_I64 && out_type == RAY_BOOL) { - if (opc == OP_CAST) { + } 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. */ while (ray_morsel_next(&m)) { @@ -2755,19 +2852,85 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { out_off += n; } } - } else if (in_type == RAY_BOOL && opc == OP_NOT) { + } else if (opc == OP_NOT) { + /* `not` is true for zero, and for a null as in the eval path (a null + * is not true). Every numeric source width: BOOL / U8 bytes, I16, + * I32 and the DATE / TIME lanes, I64 and TIMESTAMP, F32, F64. */ + int8_t it = expr_cast_lane_type(in_type); + if (it != RAY_F64 && it != RAY_F32 && it != RAY_I64 && it != RAY_I32 && + it != RAY_I16 && it != RAY_U8 && it != RAY_BOOL) { + ray_release(result); + return ray_error("type", "not: expects a numeric argument, got %s", + ray_type_name(in_type)); + } while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; - uint8_t* src = (uint8_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]; + if (it == RAY_F64) { + const double* src = (const double*)m.morsel_ptr; + for (int64_t i = 0; i < n; i++) dst[i] = !(src[i] != 0.0 && src[i] == src[i]); + } else if (it == RAY_F32) { + const float* src = (const float*)m.morsel_ptr; + for (int64_t i = 0; i < n; i++) dst[i] = !(src[i] != 0.0f && src[i] == src[i]); + } else if (it == RAY_I64) { + const int64_t* src = (const int64_t*)m.morsel_ptr; + for (int64_t i = 0; i < n; i++) dst[i] = src[i] == 0 || src[i] == NULL_I64; + } else if (it == RAY_I32) { + const int32_t* src = (const int32_t*)m.morsel_ptr; + for (int64_t i = 0; i < n; i++) dst[i] = src[i] == 0 || src[i] == NULL_I32; + } else if (it == RAY_I16) { + const int16_t* src = (const int16_t*)m.morsel_ptr; + for (int64_t i = 0; i < n; i++) dst[i] = src[i] == 0 || src[i] == NULL_I16; + } else { + const uint8_t* src = (const uint8_t*)m.morsel_ptr; + for (int64_t i = 0; i < n; i++) dst[i] = !src[i]; + } + out_off += n; + } + } else if (opc == OP_CAST && (out_type == RAY_I32 || out_type == RAY_I16 || + out_type == RAY_U8 || out_type == RAY_BOOL) && + (expr_cast_lane_type(in_type) == RAY_I32 || in_type == RAY_I16 || + in_type == RAY_U8 || in_type == RAY_BOOL) && + expr_cast_lane_type(in_type) != expr_cast_lane_type(out_type)) { + /* Narrow to narrow: the arms below widen a narrow source to I64 or + * F64 only, and wrote 8-byte doubles into these narrower targets. */ + int8_t it = expr_cast_lane_type(in_type); + size_t osz = ray_elem_size(out_type); + while (ray_morsel_next(&m)) { + int64_t n = m.morsel_len; + char* dst = (char*)ray_data(result) + (size_t)out_off * osz; + for (int64_t i = 0; i < n; i++) { + int64_t v = it == RAY_I32 ? (int64_t)((const int32_t*)m.morsel_ptr)[i] + : it == RAY_I16 ? (int64_t)((const int16_t*)m.morsel_ptr)[i] + : (int64_t)((const uint8_t*)m.morsel_ptr)[i]; + 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); + } out_off += n; } } else if (opc == OP_CAST) { + /* A temporal target or source is its lane type (TIMESTAMP ≡ I64, + * DATE / TIME ≡ I32); an equal-lane cast is a retag copy. */ + int8_t it = expr_cast_lane_type(in_type); + int8_t ot = expr_cast_lane_type(out_type); + if (it == ot) { + size_t esz = ray_elem_size(ot); + while (ray_morsel_next(&m)) { + int64_t n = m.morsel_len; + memcpy((char*)ray_data(result) + (size_t)out_off * esz, + m.morsel_ptr, (size_t)n * esz); + out_off += n; + } + } else /* CAST from narrow integer types (I32/I16/U8/BOOL) to I64/F64. - * in_type is loop-invariant; select the typed read outside the loop. */ - if (in_type == RAY_I32 || in_type == RAY_DATE || in_type == RAY_TIME) { - if (out_type == RAY_I64) { + * The lane types are loop-invariant; select the typed read outside + * the loop. */ + if (it == RAY_I32) { + if (ot == RAY_I64) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; int32_t* src = (int32_t*)m.morsel_ptr; @@ -2784,8 +2947,8 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { out_off += n; } } - } else if (in_type == RAY_I16) { - if (out_type == RAY_I64) { + } else if (it == RAY_I16) { + if (ot == RAY_I64) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; int16_t* src = (int16_t*)m.morsel_ptr; @@ -2802,8 +2965,8 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { out_off += n; } } - } else if (in_type == RAY_U8 || in_type == RAY_BOOL) { - if (out_type == RAY_I64) { + } else if (it == RAY_U8 || it == RAY_BOOL) { + if (ot == RAY_I64) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; uint8_t* src = (uint8_t*)m.morsel_ptr; @@ -2820,9 +2983,9 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { out_off += n; } } - } else if (in_type == RAY_I64) { + } else if (it == RAY_I64) { /* Narrowing I64 → I32/I16/U8/BOOL: truncate. */ - if (out_type == RAY_I32) { + if (ot == RAY_I32) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; int64_t* src = (int64_t*)m.morsel_ptr; @@ -2830,7 +2993,7 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { for (int64_t i = 0; i < n; i++) dst[i] = (int32_t)src[i]; out_off += n; } - } else if (out_type == RAY_I16) { + } else if (ot == RAY_I16) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; int64_t* src = (int64_t*)m.morsel_ptr; @@ -2838,22 +3001,22 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { for (int64_t i = 0; i < n; i++) dst[i] = (int16_t)src[i]; out_off += n; } - } else if (out_type == RAY_U8 || out_type == RAY_BOOL) { + } else if (ot == RAY_U8 || ot == RAY_BOOL) { 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); /* BOOL: collapse non-zero to 1; U8: low byte. */ - if (out_type == RAY_BOOL) + if (ot == RAY_BOOL) for (int64_t i = 0; i < n; i++) dst[i] = src[i] ? 1 : 0; else for (int64_t i = 0; i < n; i++) dst[i] = (uint8_t)src[i]; out_off += n; } } - } else if (in_type == RAY_F64) { + } else if (it == RAY_F64) { /* Narrowing F64 → I32/I16/U8/BOOL: float truncation. */ - if (out_type == RAY_I32) { + if (ot == RAY_I32) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; double* src = (double*)m.morsel_ptr; @@ -2861,7 +3024,7 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { for (int64_t i = 0; i < n; i++) dst[i] = ray_cast_f64_to_i32_null(src[i]); out_off += n; } - } else if (out_type == RAY_I16) { + } else if (ot == RAY_I16) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; double* src = (double*)m.morsel_ptr; @@ -2869,12 +3032,12 @@ ray_t* exec_elementwise_unary(ray_graph_t* g, ray_op_t* op, ray_t* input) { for (int64_t i = 0; i < n; i++) dst[i] = ray_cast_f64_to_i16_null(src[i]); out_off += n; } - } else if (out_type == RAY_U8 || out_type == RAY_BOOL) { + } else if (ot == RAY_U8 || ot == RAY_BOOL) { while (ray_morsel_next(&m)) { int64_t n = m.morsel_len; double* src = (double*)m.morsel_ptr; uint8_t* dst = (uint8_t*)((char*)ray_data(result) + out_off); - if (out_type == RAY_BOOL) + 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. */ @@ -3027,7 +3190,14 @@ static void binary_range(ray_op_t* op, int8_t out_type, * (!= MobilePhoneModel "") = 15 ms vs ~1 ms on the typed-pointer * path). Specialise on column width here so the inner loop reduces * to a typed pointer dereference + compare + store. */ - if (out_type == RAY_BOOL && !l_scalar && r_scalar && + /* The scalar must be integer-family too: a float scalar (an aggregate + * such as (avg col), or any computed F64 atom / 1-elem vec) was decoded + * into r_f64 by the caller and r_i64 is still 0, so this kernel would + * compare every row against 0 (#694). Float scalars take the generic + * BOOL path below, which promotes both sides to double. */ + bool r_scalar_float = rhs->type == -RAY_F64 || rhs->type == -RAY_F32 || + rhs->type == RAY_F64 || rhs->type == RAY_F32; + if (out_type == RAY_BOOL && !l_scalar && r_scalar && !r_scalar_float && (op->opcode == OP_EQ || op->opcode == OP_NE || op->opcode == OP_LT || op->opcode == OP_LE || op->opcode == OP_GT || op->opcode == OP_GE) && diff --git a/src/ops/filter.c b/src/ops/filter.c index cc298a2ff..090f89a86 100644 --- a/src/ops/filter.c +++ b/src/ops/filter.c @@ -281,6 +281,68 @@ static void fidx_fill_fn(void* ctxp, uint32_t wid, int64_t start, int64_t end) { } } +static ray_t* where_mask_fill(int64_t tn, uint8_t on) { + ray_t* v = ray_vec_new(RAY_BOOL, tn); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + v->len = tn; + if (tn > 0) memset(ray_data(v), on, (size_t)tn); + return v; +} + +/* The one rule for a `where:` value, applied wherever a predicate meets a + * table of `tn` rows (OP_FILTER, the take: head filter, the eval fallback, + * the count-select and the update/delete mask paths): + * + * - a BOOL vector of tn rows is the mask; + * - a scalar with a truth value (bool, numeric, temporal — is_truthy, so + * zero and null are false) holds for every row or none; a one-element + * BOOL over tn != 1 rows likewise; + * - any other vector — a numeric, temporal, symbol or string column — is + * a type error, and a BOOL vector of another length a length error. + * Before this a bare I64 column reached the filter kernels, which read + * a mask as one byte per row (#678). + * + * Consumes `pred`; returns an owned BOOL vector of tn rows or an error. */ +ray_t* ray_where_mask_coerce(ray_t* pred, int64_t tn, const char* label) { + if (!pred || RAY_IS_ERR(pred)) return pred; + if (ray_is_atom(pred)) { + if (!ray_pred_atom_type_ok(pred->type)) { + int8_t pt = pred->type; + ray_release(pred); + return ray_error("type", "%s: a scalar predicate must be boolean or numeric, got %s", + label, ray_type_name(pt)); + } + uint8_t on = is_truthy(pred) ? 1 : 0; + ray_release(pred); + return where_mask_fill(tn, on); + } + if (ray_is_lazy(pred)) { + pred = ray_lazy_materialize(pred); + if (!pred || RAY_IS_ERR(pred)) return pred ? pred : ray_error("oom", NULL); + } + if (pred->type == RAY_BOOL) { + if (pred->len == tn) return pred; + if (pred->len == 1 && tn != 1) { + uint8_t on = ((const uint8_t*)ray_data(pred))[0]; + ray_release(pred); + return where_mask_fill(tn, on); + } + int64_t got = pred->len; + ray_release(pred); + return ray_error("length", "%s: WHERE mask length %lld does not match row count %lld", + label, (long long)got, (long long)tn); + } + /* Any other vector — a numeric, temporal, symbol or string column — is + * no mask (query_coverage.rfl, where_eval_fallback.rfl pin this); the + * filter kernels read a mask as one byte per row, so an I64 column let + * through here kept the rows whose low byte of every eighth value was + * set (#678). */ + int8_t pt = pred->type; + ray_release(pred); + return ray_error("type", "%s: WHERE must produce a bool mask or truthy scalar, got %s", + label, ray_type_name(pt)); +} + ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { (void)g; (void)op; @@ -293,6 +355,13 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { * ray_type_sizes out of bounds. */ if (pred->type < 0) return ray_error("length", "filter: predicate must be a BOOL vector matching the input length, got an atom"); + /* The morsel sweeps below read the mask as one byte per row; any other + * vector type must be coerced by ray_where_mask_coerce before it gets + * here (an I64 column read this way kept the rows whose low byte of + * every eighth value was set, #678). */ + if (pred->type != RAY_BOOL) + return ray_error("type", "filter: predicate must be a BOOL vector, got %s", + ray_type_name(pred->type)); /* A plain contiguous BOOL predicate over a large input takes the * parallel chunked count/fill; anything else (lazy / morsel-backed @@ -581,6 +650,21 @@ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred) { ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { 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 + * (ray_where_mask_coerce): a scalar or one-element BOOL is spread over + * the rows, any other vector (a numeric or symbol column) is a type + * error. The checks below used to pass an atom and + * any non-BOOL vector through as "keep the whole table" — so + * `where: x take: 2` over an I64 column returned every row. */ + if (input->type == RAY_TABLE && + !(pred->type == RAY_BOOL && pred->len == ray_table_nrows(input))) { + ray_retain(pred); + ray_t* m = ray_where_mask_coerce(pred, ray_table_nrows(input), "where"); + if (!m || RAY_IS_ERR(m)) return m ? m : ray_error("oom", NULL); + ray_t* r = exec_filter_head(input, m, limit); + ray_release(m); + return r; + } /* Pass-through must hand back an OWNED ref: the exec.c caller * releases its own input ref and returns this value as the node * result, so a bare `input` would leave the result dangling once @@ -593,7 +677,17 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { int64_t ncols = ray_table_ncols(input); int64_t nrows = ray_table_nrows(input); - if (limit <= 0 || ncols <= 0) return ray_table_new(0); + if (ncols <= 0) return ray_table_new(0); + if (limit <= 0) { + /* No rows, but the table's columns: an empty table without them + * made `(at r 'x)` fail on `take: 0`. */ + ray_t* zero = make_i64(0); + ray_t* r = zero ? ray_take_fn(input, zero) : NULL; + if (zero) ray_release(zero); + if (r && !RAY_IS_ERR(r)) return r; + if (r) ray_error_free(r); + limit = 0; /* a parted table takes no `take`: gather no rows */ + } if (limit > nrows) limit = nrows; /* VLA guard */ @@ -602,7 +696,7 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { /* Collect up to `limit` matching row indices, stopping early */ ray_t* idx_hdr = NULL; int64_t* match_idx = (int64_t*)scratch_alloc(&idx_hdr, - (size_t)limit * sizeof(int64_t)); + (size_t)(limit > 0 ? limit : 1) * sizeof(int64_t)); if (!match_idx) return ray_error("oom", NULL); int64_t found = 0; @@ -626,9 +720,19 @@ ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit) { ray_t* col = ray_table_get_col_idx(input, c); int64_t name_id = ray_table_col_name(input, c); if (!col) continue; + if (col->type == RAY_MAPCOMMON) { + ray_t* mc = materialize_mapcommon_gather(col, match_idx, found); + if (!mc || RAY_IS_ERR(mc)) { + scratch_free(idx_hdr); + ray_release(tbl); + return mc; + } + tbl = ray_table_add_col(tbl, name_id, mc); + ray_release(mc); + continue; + } int8_t out_type = RAY_IS_PARTED(col->type) ? (int8_t)RAY_PARTED_BASETYPE(col->type) : col->type; - if (out_type == RAY_MAPCOMMON) continue; uint8_t out_attrs = 0; if (out_type == RAY_SYM) { if (RAY_IS_PARTED(col->type)) { @@ -811,6 +915,13 @@ ray_t* sel_compact(ray_graph_t* g, ray_t* tbl, ray_t* sel, continue; ray_t* col = ray_table_get_col_idx(tbl, c); if (!col) continue; + if (col->type == RAY_MAPCOMMON) { + 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; /* RAY_LIST == 0; ray_vec_new rejects type <= 0, so a LIST diff --git a/src/ops/fused_topk.c b/src/ops/fused_topk.c index 6553e7ddc..581835bb6 100644 --- a/src/ops/fused_topk.c +++ b/src/ops/fused_topk.c @@ -675,13 +675,16 @@ ray_t* ray_fused_topk_select(ray_t* tbl, /* ───── Fused filter + positional take ──────────────────────────────── * Chunks of FTK_CHUNK_ROWS rows, numbered from the end the answer comes * from (row 0 for the first K, the last row for the last |K|), one pool - * task per chunk in that order — the workers sweep the table from that - * end together. Each worker appends passing rows to its own list until - * it holds |K|; those |K| bound the answer, so it publishes the |K|-th - * row as the cutoff: no row beyond it can be among the first |K| passing - * rows of the table, and every later chunk returns at once. The lists - * are merged by row id at the end and the |K| nearest the scanned end - * are gathered. + * task per chunk. Each worker keeps the |K| passing rows nearest that + * end it has seen, in scan order; once it holds |K| they bound the + * answer, so it publishes its |K|-th row as the cutoff: no row beyond it + * can be among the first |K| passing rows of the table, and every chunk + * past it returns at once. The pool makes no promise about the order + * tasks run in (see pool.h), so a worker whose list is full may still be + * handed a chunk that lies BEFORE the rows it holds — it scans it and + * lets nearer rows displace the farthest; only the cutoff, which is + * sound whatever the order, skips work. The lists are merged by row id + * at the end and the |K| nearest the scanned end are gathered. * ──────────────────────────────────────────────────────────────────── */ #define FTK_CHUNK_ROWS (64 * 1024) @@ -712,13 +715,34 @@ static void ftk_publish(ftk_ctx_t* c, int64_t row) { } } +/* Admit `row` to the worker's list of the |K| nearest passing rows, kept in + * scan order. Rows arrive in scan order within a chunk, but a later chunk + * may lie before an earlier one, so a full list still takes a nearer row: + * it is inserted in place and the farthest drops off. False when the list + * is full and `row` is not nearer than its last entry — then nothing after + * it in this chunk is either. */ +static inline bool ftk_push(const ftk_ctx_t* c, int64_t* my, int32_t* pn, int64_t row) { + int32_t n = *pn, k = (int32_t)c->k; + if (n == k) { + if (c->from_end ? row <= my[k - 1] : row >= my[k - 1]) return false; + n--; /* the farthest drops off */ + } + int32_t i = n; + while (i > 0 && (c->from_end ? my[i - 1] < row : my[i - 1] > row)) { + my[i] = my[i - 1]; + i--; + } + my[i] = row; + *pn = n + 1; + return true; +} + static void ftk_task_fn(void* raw, uint32_t worker_id, int64_t start, int64_t end) { (void)end; ftk_ctx_t* c = (ftk_ctx_t*)raw; int32_t k = (int32_t)c->k; int64_t* my = &c->rows[(size_t)worker_id * (size_t)k]; int32_t n = c->rows_n[worker_id]; - if (n >= k) return; /* this worker's list is complete */ /* chunk `start` counted from the scanned end */ int64_t lo, hi; @@ -734,24 +758,25 @@ static void ftk_task_fn(void* raw, uint32_t worker_id, int64_t start, int64_t en if (ftk_beyond(c, c->from_end ? hi - 1 : lo)) return; uint8_t bits[RAY_MORSEL_ELEMS]; + bool more = true; /* false: list full, rest of chunk is farther */ if (!c->from_end) { - for (int64_t row = lo; row < hi && n < k; ) { + for (int64_t row = lo; row < hi && more; ) { 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); - for (int64_t r = 0; r < mend - row && n < k; r++) - if (bits[r]) my[n++] = row + r; + for (int64_t r = 0; r < mend - row && more; r++) + if (bits[r]) more = ftk_push(c, my, &n, row + r); row = mend; } } else { - for (int64_t mend = hi; mend > lo && n < k; ) { + for (int64_t mend = hi; mend > lo && more; ) { 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); - for (int64_t r = mend - row - 1; r >= 0 && n < k; r--) - if (bits[r]) my[n++] = row + r; + for (int64_t r = mend - row - 1; r >= 0 && more; r--) + if (bits[r]) more = ftk_push(c, my, &n, row + r); mend = row; } } diff --git a/src/ops/graph.c b/src/ops/graph.c index 7efba810b..f78059738 100644 --- a/src/ops/graph.c +++ b/src/ops/graph.c @@ -437,7 +437,13 @@ static bool type_is_temporal(int8_t t) { return t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP; } +/* GUID has no numeric promotion: two GUID branches keep the type, and a + * GUID beside anything else has no column type. promote() used to fall + * through to BOOL for it, and the fill then read the 16-byte cells as + * bytes (#691). -1 for the mixed case so ray_if declines the node and + * the projection falls back to the interpreter. */ static int8_t promote_if_type(int8_t a, int8_t b) { + if (a == RAY_GUID || b == RAY_GUID) return a == b ? RAY_GUID : -1; if (a == b && type_is_temporal(a)) return a; return promote(a, b); } @@ -473,12 +479,112 @@ ray_op_t* ray_cast(ray_graph_t* g, ray_op_t* a, int8_t target_type) { * Binary element-wise ops * -------------------------------------------------------------------------- */ -/* Generic binary op constructor — opcode-driven, no switch/case needed by caller */ +/* DATE, TIME and TIMESTAMP compare on one nanosecond scale, as the eval path + * does (temporal_as_ns): a DATE lane holds days, a TIME milliseconds, a + * TIMESTAMP nanoseconds, and the comparison kernels compare raw lane values. + * When the two sides are different temporal types and one is a literal, the + * literal is rewritten in the other side's units: exactly for a TIMESTAMP + * side, rounded as the operator needs for a DATE or TIME side + * (x*u > L <=> x > floor(L/u), x*u >= L <=> x >= ceil(L/u), ...), clamped to + * the lane. The column keeps its own units, so its fast paths, index routing + * and partition pruning still apply, and no cell is scaled (a DATE far from + * 2000 overflows nanoseconds). An equality the column's units cannot express + * holds for no row (`!=` for every row), and is written as a comparison with + * the lane's maximum that has that answer. Two non-literal sides are + * declined, and the caller falls back to the eval path. */ +static int8_t cmp_temporal_type(ray_graph_t* g, ray_op_t* x) { + int8_t t = x->out_type; + if (RAY_IS_PARTED(t)) t = (int8_t)RAY_PARTED_BASETYPE(t); + if (t == RAY_DATE || t == RAY_TIME || t == RAY_TIMESTAMP) return t; + /* 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) + return RAY_DATE; + } + return 0; +} + +static int64_t cmp_temporal_unit(int8_t t) { + return t == RAY_DATE ? 86400000000000LL : t == RAY_TIME ? 1000000LL : 1; +} + +/* The temporal atom of a literal node, or NULL. */ +static ray_t* cmp_temporal_literal_of(ray_graph_t* g, ray_op_t* x) { + if (x->opcode != OP_CONST) return NULL; + ray_op_ext_t* ext = find_ext(g, x->id); + ray_t* lit = ext ? ext->literal : NULL; + if (!lit || !ray_is_atom(lit)) return NULL; + return (lit->type == -RAY_DATE || lit->type == -RAY_TIME || + lit->type == -RAY_TIMESTAMP) ? lit : NULL; +} + +/* `lit` as a literal of type `ct` for `col *op lit`. A null literal becomes + * ct's null. An `==` / `!=` that ct's units cannot express turns *op into + * `>` / `<=` against ct's largest value: false, resp. true, for every row. */ +static ray_t* cmp_temporal_rewrite(ray_t* lit, int8_t ct, uint16_t* op) { + uint16_t opcode = *op; + if (RAY_ATOM_IS_NULL(lit)) return ray_typed_null((int8_t)-ct); + int8_t lt = (int8_t)-lit->type; + int64_t v = lt == RAY_TIMESTAMP ? lit->i64 : (int64_t)lit->i32; + int64_t ns; + if (__builtin_mul_overflow(v, cmp_temporal_unit(lt), &ns)) + ns = v < 0 ? INT64_MIN + 1 : INT64_MAX; /* saturate */ + if (ns == INT64_MIN) ns = INT64_MIN + 1; /* not the null sentinel */ + int64_t u = cmp_temporal_unit(ct); + int64_t q = ns / u, r = ns % u; + if (r != 0) { + switch (opcode) { + case OP_GT: case OP_LE: if (r < 0) q--; break; /* floor */ + case OP_GE: case OP_LT: if (r > 0) q++; break; /* ceiling */ + default: /* ==, != between units */ + *op = opcode == OP_EQ ? OP_GT : OP_LE; + return ct == RAY_DATE ? ray_date(INT32_MAX) : ray_time(INT32_MAX); + } + } + if (ct == RAY_TIMESTAMP) return ray_timestamp(q); + if (q > INT32_MAX) q = INT32_MAX; + if (q < (int64_t)INT32_MIN + 1) q = (int64_t)INT32_MIN + 1; + return ct == RAY_DATE ? ray_date(q) : ray_time(q); +} + +static uint16_t cmp_flip(uint16_t opcode) { + switch (opcode) { + case OP_LT: return OP_GT; + case OP_LE: return OP_GE; + case OP_GT: return OP_LT; + case OP_GE: return OP_LE; + default: return opcode; + } +} + +static ray_op_t* make_cmp(ray_graph_t* g, uint16_t opcode, ray_op_t* a, ray_op_t* b) { + 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); + uint32_t a_id = a->id, b_id = b->id; + ray_t* bl = cmp_temporal_literal_of(g, b); + ray_t* al = bl ? NULL : cmp_temporal_literal_of(g, a); + if (!bl && !al) return NULL; + /* Rewrite in `col OP lit` orientation; a literal on the left flips. */ + uint16_t op = bl ? opcode : cmp_flip(opcode); + ray_t* nl = cmp_temporal_rewrite(bl ? bl : al, bl ? ta : tb, &op); + if (!nl || RAY_IS_ERR(nl)) return NULL; + ray_op_t* c = ray_const_atom(g, nl); + ray_release(nl); + if (!c) return NULL; + return bl ? make_binary(g, op, &g->nodes[a_id], c, RAY_BOOL) + : make_binary(g, cmp_flip(op), c, &g->nodes[b_id], RAY_BOOL); +} + ray_op_t* ray_binop(ray_graph_t* g, uint16_t opcode, ray_op_t* a, ray_op_t* b) { int8_t out; switch (opcode) { 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_GT: case OP_GE: + return make_cmp(g, opcode, a, b); + case OP_AND: case OP_OR: out = RAY_BOOL; break; case OP_DIV: case OP_POW: out = RAY_F64; break; @@ -496,12 +602,12 @@ ray_op_t* ray_idiv(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binar ray_op_t* ray_mod(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_MOD, a, b, promote(a->out_type, b->out_type)); } ray_op_t* ray_pow_op(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_POW, a, b, RAY_F64); } -ray_op_t* ray_eq(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_EQ, a, b, RAY_BOOL); } -ray_op_t* ray_ne(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_NE, a, b, RAY_BOOL); } -ray_op_t* ray_lt(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_LT, a, b, RAY_BOOL); } -ray_op_t* ray_le(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_LE, a, b, RAY_BOOL); } -ray_op_t* ray_gt(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_GT, a, b, RAY_BOOL); } -ray_op_t* ray_ge(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_GE, a, b, RAY_BOOL); } +ray_op_t* ray_eq(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_cmp(g, OP_EQ, a, b); } +ray_op_t* ray_ne(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_cmp(g, OP_NE, a, b); } +ray_op_t* ray_lt(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_cmp(g, OP_LT, a, b); } +ray_op_t* ray_le(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_cmp(g, OP_LE, a, b); } +ray_op_t* ray_gt(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_cmp(g, OP_GT, a, b); } +ray_op_t* ray_ge(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_cmp(g, OP_GE, a, b); } ray_op_t* ray_and(ray_graph_t* g, ray_op_t* a, ray_op_t* b){ return make_binary(g, OP_AND, a, b, RAY_BOOL); } ray_op_t* ray_or(ray_graph_t* g, ray_op_t* a, ray_op_t* b) { return make_binary(g, OP_OR, a, b, RAY_BOOL); } ray_op_t* ray_min2(ray_graph_t* g, ray_op_t* a, ray_op_t* b){ return make_binary(g, OP_MIN2, a, b, promote(a->out_type, b->out_type)); } @@ -509,12 +615,49 @@ ray_op_t* ray_max2(ray_graph_t* g, ray_op_t* a, ray_op_t* b){ return make_binary ray_op_t* ray_in(ray_graph_t* g, ray_op_t* col, ray_op_t* set){ return make_binary(g, OP_IN, col, set, RAY_BOOL); } ray_op_t* ray_not_in(ray_graph_t* g, ray_op_t* col, ray_op_t* set){ return make_binary(g, OP_NOT_IN, col, set, RAY_BOOL); } +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; +} + +/* Is node `id` a bare null atom literal (`0N`, `0Nf`, `0Ni`, ...)? */ +static bool if_const_null_atom(ray_graph_t* g, uint32_t id) { + ray_op_t* b = &g->nodes[id]; + if (b->opcode != OP_CONST) return false; + ray_op_ext_t* bx = find_ext(g, id); + return bx && bx->literal && ray_is_atom(bx->literal) && + RAY_ATOM_IS_NULL(bx->literal); +} + ray_op_t* ray_if(ray_graph_t* g, ray_op_t* cond, ray_op_t* then_val, ray_op_t* else_val) { /* 3-input node: cond, then, else — needs ext node */ uint32_t cond_id = cond->id; uint32_t then_id = then_val->id; uint32_t else_id = else_val->id; - int8_t out_type = promote_if_type(then_val->out_type, else_val->out_type); + int8_t tt = then_val->out_type; + int8_t et = else_val->out_type; + int8_t out_type = promote_if_type(tt, et); + /* A temporal branch beside a null literal keeps the temporal type + * (#673): `(if c d 0N)` is a DATE column with nulls, not the I64 that + * promote() makes of DATE + I64, and `(if c ts 0Nd)` a TIMESTAMP one, + * not the I64 the two widths fold to. Same rule as the text null + * below: the literal is then swapped for the typed null. A non-null + * value beside a temporal still promotes, as before. */ + if (type_is_temporal(tt) && et != tt && et != RAY_STR && et != RAY_SYM && + et != RAY_GUID && if_const_null_atom(g, else_id)) + out_type = tt; + else if (type_is_temporal(et) && tt != et && tt != RAY_STR && tt != RAY_SYM && + tt != RAY_GUID && if_const_null_atom(g, then_id)) + out_type = et; + if (out_type < 0) return NULL; + /* A LIST column scans as the untyped node (out_type 0), which promote() + * also folds to BOOL and the fill then reads the cell pointers as bytes. + * No fill exists for ragged cells: decline so the projection falls back. */ + if (if_branch_is_list_scan(g, then_val) || if_branch_is_list_scan(g, else_val)) + return NULL; /* IF preserves string types: promote() handles RAY_STR (wins over SYM); * SYM override only applies when neither side is RAY_STR */ if (out_type != RAY_STR && @@ -522,6 +665,31 @@ ray_op_t* ray_if(ray_graph_t* g, ray_op_t* cond, ray_op_t* then_val, ray_op_t* e out_type = RAY_SYM; uint32_t est = cond->est_rows; + /* A null literal such as `0N` or `0Nf` beside a text branch is the text + * null. Left as a number, the fills wrote its payload as a symbol id + * (NaN bits for 0Nf, INT64_MIN for 0N): a crash, or a symbol that is + * not null. Swap it for the text null of the result type. Beside a + * temporal branch it is the temporal null the same way: the fills read + * a DATE/TIME null from i32 and a TIMESTAMP null from i64, so the + * literal must carry the result's own sentinel. */ + bool text_out = out_type == RAY_STR || out_type == RAY_SYM; + if (text_out || type_is_temporal(out_type)) { + for (int side = 0; side < 2; side++) { + uint32_t bid = side ? else_id : then_id; + ray_op_t* b = &g->nodes[bid]; + if (b->out_type == out_type || + (text_out && (b->out_type == RAY_STR || b->out_type == RAY_SYM))) + continue; + if (!if_const_null_atom(g, bid)) continue; + ray_t* tn = ray_typed_null((int8_t)-out_type); + if (!tn || RAY_IS_ERR(tn)) return NULL; + ray_op_t* nc = ray_const_atom(g, tn); + ray_release(tn); + if (!nc) return NULL; + if (side) else_id = nc->id; else then_id = nc->id; + } + } + ray_op_ext_t* ext = graph_alloc_ext_node(g); if (!ext) return NULL; diff --git a/src/ops/group.c b/src/ops/group.c index 5226285f2..9a74defb9 100644 --- a/src/ops/group.c +++ b/src/ops/group.c @@ -8304,6 +8304,9 @@ static bool try_strlen_sumavg_input(ray_graph_t* g, ray_t* tbl, * group-aggregation loops can read row-wise without out-of-bounds access. */ static ray_t* materialize_broadcast_input(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". */ + if (src->type == -RAY_STR) return broadcast_scalar(src, nrows); int8_t out_type = ray_is_atom(src) ? (int8_t)-src->type : src->type; if (out_type <= 0 || out_type >= RAY_TYPE_COUNT) return NULL; @@ -8319,6 +8322,8 @@ static ray_t* materialize_broadcast_input(ray_t* src, int64_t nrows) { char* d = (char*)ray_data(out); for (int64_t i = 0; i < nrows; i++) memcpy(d + (size_t)i * esz, s, esz); + /* copied STR descriptors still point into the source's pool */ + if (out_type == RAY_STR) col_propagate_str_pool(out, src); return out; } @@ -11939,6 +11944,36 @@ static ray_t* exec_group_run(ray_graph_t* g, ray_op_t* op, ray_t* tbl, ray_t* vec = exec_node(g, key_op); g->table = saved_table; if (vec && !RAY_IS_ERR(vec)) { + /* A key that evaluates to one value (a constant, or a `let` + * whose body is one) is that value on every row: one group. + * It came back as an atom or a one-element vector and was + * read as a full column, past its end — random groups, or a + * crash on the workers. Another length is no row-aligned + * key at all. */ + int64_t tn = ray_table_nrows(tbl); + bool scalar = ray_is_atom(vec) || (ray_is_vec(vec) && vec->len == 1 && tn != 1); + if (scalar) { + ray_t* wide; + if (vec->type == -RAY_STR) { + wide = broadcast_scalar(vec, tn); + } else { + ray_t* n_obj = make_i64(tn); + wide = n_obj ? ray_take_fn(vec, n_obj) : ray_error("oom", NULL); + if (n_obj) ray_release(n_obj); + } + ray_release(vec); + vec = wide; + } else if (ray_is_vec(vec) && vec->len != tn) { + int64_t got = vec->len; + ray_release(vec); + vec = ray_error("length", "by: key has %lld values for %lld rows", + (long long)got, (long long)tn); + } + if (!vec || RAY_IS_ERR(vec)) { + for (uint32_t j = 0; j < k; j++) + if (key_owned[j] && key_vecs[j]) ray_release(key_vecs[j]); + return vec ? vec : ray_error("oom", NULL); + } key_vecs[k] = vec; key_owned[k] = 1; } diff --git a/src/ops/idxop.c b/src/ops/idxop.c index cc9f9a36e..3ac15fc06 100644 --- a/src/ops/idxop.c +++ b/src/ops/idxop.c @@ -745,11 +745,15 @@ static ray_t* prepare_attach_ex(ray_t** vp, const char* what, return ray_error("type", "%s: cannot index a slice; materialize first", what); if (v->attrs & RAY_ATTR_HAS_INDEX) { ray_index_drop(&v); + if (!v) return ray_error("oom", NULL); /* keep *vp intact */ if (RAY_IS_ERR(v)) return v; *vp = v; } v = ray_cow(v); - if (!v || RAY_IS_ERR(v)) return v; + /* Never hand back NULL: every caller tests only RAY_IS_ERR and then + * dereferences, so a failed copy must surface as an error. */ + if (!v) return ray_error("oom", NULL); + if (RAY_IS_ERR(v)) return v; *vp = v; /* Numeric vectors carry any index kind; STR carries only RAY_IDX_DICT * (codes live alongside the descriptors — the column representation is @@ -900,6 +904,183 @@ ray_t* ray_index_chunk_zone_compute(ray_t* v, uint8_t chunk_log2) { return idx; /* standalone RAY_INDEX object — caller releases */ } +/* ── Incremental chunk zone ───────────────────────────────────────────────── + * The stream writers see a column in slices; per chunk the zone needs only + * running min / max, a null flag and (integers) the exact 128-bit sum and + * non-null count, so any slice size and any starting row work, and two + * accumulators over disjoint row ranges merge chunk by chunk. Arrays are + * indexed by GLOBAL chunk (row >> 16) so a Parquet task that starts at row + * 5 M carries a few empty leading chunks and merges by index. */ +#define ZONE_ACC_LOG2 16 + +bool ray_zone_acc_supported(int8_t type) { return numeric_elem_size(type) != 0; } + +static ray_err_t zone_acc_grow(ray_zone_acc_t* a, uint32_t want) { + if (want <= a->n_chunks) return RAY_OK; + if (want <= a->cap) { a->n_chunks = want; return RAY_OK; } + uint32_t cap = a->cap ? a->cap : 16; + while (cap < want) cap *= 2; + size_t old = a->cap; +#define ZONE_GROW(field, T, init) do { \ + T* p = (T*)ray_realloc_raw(a->field, (size_t)cap * sizeof(T)); \ + if (!p) return RAY_ERR_OOM; \ + for (size_t i = old; i < cap; i++) p[i] = (init); \ + a->field = p; } while (0) + if (a->is_f64) { ZONE_GROW(fmins, double, INFINITY); ZONE_GROW(fmaxs, double, -INFINITY); } + else { + ZONE_GROW(mins, int64_t, INT64_MAX); ZONE_GROW(maxs, int64_t, INT64_MIN); + ZONE_GROW(sum_lo, uint64_t, 0); ZONE_GROW(sum_hi, int64_t, 0); ZONE_GROW(nn, int64_t, 0); + } + ZONE_GROW(nulls, uint8_t, 0); +#undef ZONE_GROW + a->cap = cap; + a->n_chunks = want; + return RAY_OK; +} + +ray_err_t ray_zone_acc_init(ray_zone_acc_t* a, int8_t type, int64_t start_row) { + memset(a, 0, sizeof(*a)); + a->esz = numeric_elem_size(type); + if (a->esz == 0 || start_row < 0) return RAY_ERR_TYPE; + a->type = type; + a->is_f64 = (type == RAY_F64 || type == RAY_F32); + a->next_row = start_row; + return RAY_OK; +} + +void ray_zone_acc_free(ray_zone_acc_t* a) { + ray_free_raw(a->mins); ray_free_raw(a->maxs); ray_free_raw(a->fmins); ray_free_raw(a->fmaxs); + ray_free_raw(a->nulls); ray_free_raw(a->sum_lo); ray_free_raw(a->sum_hi); ray_free_raw(a->nn); + memset(a, 0, sizeof(*a)); +} + +ray_err_t ray_zone_acc_add(ray_zone_acc_t* a, ray_t* v) { + if (!a->type || !v || RAY_IS_ERR(v) || v->type != a->type) return RAY_ERR_TYPE; + int64_t n = v->len; + if (n <= 0) return RAY_OK; + int64_t csz = 1LL << ZONE_ACC_LOG2; + int64_t last = a->next_row + n - 1; + ray_err_t err = zone_acc_grow(a, (uint32_t)(last >> ZONE_ACC_LOG2) + 1); + if (err != RAY_OK) return err; + const uint8_t* base = (const uint8_t*)ray_data(v); + int64_t i = 0; + while (i < n) { + if (RAY_UNLIKELY(ray_interrupted())) return RAY_ERR_CANCEL; + int64_t row = a->next_row + i; + uint32_t g = (uint32_t)(row >> ZONE_ACC_LOG2); + int64_t e = ((int64_t)g + 1) * csz - a->next_row; if (e > n) e = n; + bool any_null = false; + if (a->is_f64) { + double mn = a->fmins[g], mx = a->fmaxs[g]; + for (; i < e; i++) { + double val; + if (a->esz == 4) { float t; memcpy(&t, base + i * 4, 4); val = (double)t; } + else memcpy(&val, base + i * 8, 8); + if (isnan(val)) { any_null = true; continue; } + if (val < mn) mn = val; + if (val > mx) mx = val; + } + a->fmins[g] = mn; a->fmaxs[g] = mx; + } else { + int64_t mn = a->mins[g], mx = a->maxs[g], nn = a->nn[g], hi = a->sum_hi[g]; + uint64_t lo = a->sum_lo[g]; + for (; i < e; i++) { + /* Null = the type's sentinel VALUE, whatever the slice header + * says (col.c #495: the persisted bit derives from the payload). */ + int64_t val = 0; + bool is_null = false; + switch (a->esz) { + case 1: val = (int64_t)base[i]; break; + case 2: { int16_t t; memcpy(&t, base + i * 2, 2); val = t; is_null = (t == NULL_I16); break; } + case 4: { int32_t t; memcpy(&t, base + i * 4, 4); val = t; is_null = (t == NULL_I32); break; } + default: { int64_t t; memcpy(&t, base + i * 8, 8); val = t; is_null = (t == NULL_I64); break; } + } + if (is_null) { any_null = true; continue; } + if (val < mn) mn = val; + if (val > mx) mx = val; + ray_i128_add(&hi, &lo, val); + nn++; + } + a->mins[g] = mn; a->maxs[g] = mx; a->nn[g] = nn; a->sum_hi[g] = hi; a->sum_lo[g] = lo; + } + if (any_null) { a->nulls[g] = 1; a->saw_null = true; } + } + a->next_row += n; + return RAY_OK; +} + +ray_err_t ray_zone_acc_merge(ray_zone_acc_t* dst, const ray_zone_acc_t* src) { + if (!dst->type || dst->type != src->type) return RAY_ERR_TYPE; + ray_err_t err = zone_acc_grow(dst, src->n_chunks); + if (err != RAY_OK) return err; + for (uint32_t g = 0; g < src->n_chunks; g++) { + if (dst->is_f64) { + if (src->fmins[g] < dst->fmins[g]) dst->fmins[g] = src->fmins[g]; + if (src->fmaxs[g] > dst->fmaxs[g]) dst->fmaxs[g] = src->fmaxs[g]; + } else { + if (src->mins[g] < dst->mins[g]) dst->mins[g] = src->mins[g]; + if (src->maxs[g] > dst->maxs[g]) dst->maxs[g] = src->maxs[g]; + dst->nn[g] += src->nn[g]; + ray_i128_add128(&dst->sum_hi[g], &dst->sum_lo[g], src->sum_hi[g], src->sum_lo[g]); + } + dst->nulls[g] |= src->nulls[g]; + } + if (src->saw_null) dst->saw_null = true; + if (src->next_row > dst->next_row) dst->next_row = src->next_row; + return RAY_OK; +} + +ray_t* ray_zone_acc_finish(ray_zone_acc_t* a, int64_t len) { + int64_t csz = 1LL << ZONE_ACC_LOG2; + if (!a->type || len < csz) { ray_zone_acc_free(a); return NULL; } + uint32_t n_chunks = (uint32_t)((len + csz - 1) / csz); + ray_err_t err = zone_acc_grow(a, n_chunks); /* chunks never touched stay empty */ + if (err != RAY_OK) { ray_zone_acc_free(a); return ray_error("oom", "chunk_zone: arrays alloc"); } + ray_t* idx = ray_index_alloc(RAY_IDX_CHUNK_ZONE, a->type, len); + if (!idx || RAY_IS_ERR(idx)) { ray_zone_acc_free(a); return idx; } + ray_index_t* ix = ray_index_payload(idx); + ix->u.chunk_zone.n_chunks = n_chunks; + ix->u.chunk_zone.chunk_log2 = ZONE_ACC_LOG2; + ix->u.chunk_zone.is_f64 = a->is_f64; + int8_t arr_type = a->is_f64 ? RAY_F64 : RAY_I64; + ray_t* mins = ray_vec_new(arr_type, n_chunks); + ray_t* maxs = ray_vec_new(arr_type, n_chunks); + int64_t nb_len = (n_chunks + 7) / 8; + ray_t* nbits = ray_vec_new(RAY_U8, nb_len); + ray_t* aggs = a->is_f64 ? NULL : ray_vec_new(RAY_I64, 3 * (int64_t)n_chunks); + if (!mins || RAY_IS_ERR(mins) || !maxs || RAY_IS_ERR(maxs) || !nbits || RAY_IS_ERR(nbits) || + (!a->is_f64 && (!aggs || RAY_IS_ERR(aggs)))) { + if (mins && !RAY_IS_ERR(mins)) ray_release(mins); + if (maxs && !RAY_IS_ERR(maxs)) ray_release(maxs); + if (nbits && !RAY_IS_ERR(nbits)) ray_release(nbits); + if (aggs && !RAY_IS_ERR(aggs)) ray_release(aggs); + ray_release(idx); ray_zone_acc_free(a); + return ray_error("oom", "chunk_zone: arrays alloc"); + } + mins->len = n_chunks; maxs->len = n_chunks; nbits->len = nb_len; + memset(ray_data(nbits), 0, (size_t)nb_len); + if (a->is_f64) { + memcpy(ray_data(mins), a->fmins, (size_t)n_chunks * 8); + memcpy(ray_data(maxs), a->fmaxs, (size_t)n_chunks * 8); + } else { + memcpy(ray_data(mins), a->mins, (size_t)n_chunks * 8); + memcpy(ray_data(maxs), a->maxs, (size_t)n_chunks * 8); + aggs->len = 3 * (int64_t)n_chunks; + int64_t* ag = (int64_t*)ray_data(aggs); + for (uint32_t g = 0; g < n_chunks; g++) { + ag[g] = (int64_t)a->sum_lo[g]; + ag[n_chunks + g] = a->nn[g]; + ag[2 * (int64_t)n_chunks + g] = a->sum_hi[g]; + } + } + uint8_t* nb = (uint8_t*)ray_data(nbits); + for (uint32_t g = 0; g < n_chunks; g++) if (a->nulls[g]) nb[g >> 3] |= (uint8_t)(1u << (g & 7)); + ix->u.chunk_zone.mins = mins; ix->u.chunk_zone.maxs = maxs; + ix->u.chunk_zone.null_bits = nbits; ix->u.chunk_zone.aggs = aggs; + ray_zone_acc_free(a); + return idx; +} + /* ── RAY_IDX_DICT: per-column string dictionary (codes + first-occ rows) ── * Deduplicates `v`'s strings into dense int32 codes; first_occ[c] is the row of * code c's first occurrence (so code -> string resolves through `v` itself). @@ -983,6 +1164,126 @@ ray_t* ray_index_attach_dict(ray_t** vp) { return attach_finalize(v, idx); } +/* ── Incremental STR dictionary ───────────────────────────────────────────── + * Codes are assigned in first-occurrence order, exactly as + * ray_index_dict_compute assigns them over the whole column, so the result + * is the same index. Distinct strings are copied once into a private pool; + * the column itself is on disk by then. There is no cardinality cap: the + * accumulator holds 4 B/row of codes plus one copy of each distinct string, + * less than the whole-column ray_index_dict_compute (codes + slots + + * first_occ), and a high-cardinality dictionary still serves distinct. */ +ray_err_t ray_dict_acc_init(ray_dict_acc_t* a) { + memset(a, 0, sizeof(*a)); + a->mask = 1023; + a->slot = (uint32_t*)ray_calloc_raw((size_t)(a->mask + 1) * sizeof(uint32_t)); + return a->slot ? RAY_OK : RAY_ERR_OOM; +} + +void ray_dict_acc_free(ray_dict_acc_t* a) { + ray_free_raw(a->codes); ray_free_raw(a->first_occ); ray_free_raw(a->offs); + ray_free_raw(a->lens); ray_free_raw(a->pool); ray_free_raw(a->slot); + bool dead = a->dead; + memset(a, 0, sizeof(*a)); + a->dead = dead; +} + +static ray_err_t dict_acc_rehash(ray_dict_acc_t* a) { + uint64_t ncap = (a->mask + 1) * 2; + uint32_t* ns = (uint32_t*)ray_calloc_raw((size_t)ncap * sizeof(uint32_t)); + if (!ns) return RAY_ERR_OOM; + for (int64_t c = 0; c < a->n_distinct; c++) { + uint64_t s = ray_hash_bytes(a->lens[c] ? a->pool + a->offs[c] : "", a->lens[c]) & (ncap - 1); + while (ns[s]) s = (s + 1) & (ncap - 1); + ns[s] = (uint32_t)c + 1; + } + ray_free_raw(a->slot); a->slot = ns; a->mask = ncap - 1; + 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; } + 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; + int32_t* p = (int32_t*)ray_realloc_raw(a->codes, (size_t)cap * sizeof(int32_t)); + 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; + } + 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; + } + } + a->codes[a->n_rows + i] = code; + } + 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; } + 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); + if (!codes || RAY_IS_ERR(codes) || !first_occ || RAY_IS_ERR(first_occ) || !idx || RAY_IS_ERR(idx)) { + if (codes && !RAY_IS_ERR(codes)) ray_release(codes); + if (first_occ && !RAY_IS_ERR(first_occ)) ray_release(first_occ); + if (idx && !RAY_IS_ERR(idx)) ray_release(idx); + ray_dict_acc_free(a); + return ray_error("oom", NULL); + } + codes->len = len; memcpy(ray_data(codes), a->codes, (size_t)len * 4); + first_occ->len = a->n_distinct; memcpy(ray_data(first_occ), a->first_occ, (size_t)a->n_distinct * 4); + ray_index_t* ix = ray_index_payload(idx); + ix->u.dict.codes = codes; ix->u.dict.first_occ = first_occ; ix->u.dict.n_distinct = a->n_distinct; + ray_dict_acc_free(a); + return idx; +} + /* ── Inline on-disk index region (zero-copy mmap) ─────────────────────────── * An attached index is persisted at the (32-aligned) tail of its column file as * a run of contiguous 32-byte-aligned ray_t blocks: @@ -1085,6 +1386,47 @@ void ray_index_inline_write(uint8_t* dst, const ray_index_t* ix) { } } +bool ray_index_inline_write_file(FILE* f, const ray_index_t* ix) { + static const uint8_t zeros[32] = {0}; + _Alignas(32) uint8_t head[IDX_ALIGN32(32 + (int64_t)sizeof(ray_index_t))]; + memset(head, 0, sizeof(head)); + ray_t blkhdr; + memset(&blkhdr, 0, 32); + blkhdr.type = RAY_INDEX; blkhdr.len = (int64_t)sizeof(ray_index_t); + blkhdr.mmod = 1; blkhdr.rc = 1; + blkhdr.order = RAY_IDX_FORMAT_MAJOR; + memcpy(head, &blkhdr, 32); + ray_index_t* on = (ray_index_t*)(head + 32); + memcpy(on, ix, sizeof(ray_index_t)); + on->markers |= RAY_MARK_MMAP; + + ray_t** src_slots[4]; + ray_t** on_slots[4]; + int nch = idx_child_slots((ray_index_t*)ix, src_slots); + idx_child_slots(on, on_slots); + int64_t off = (int64_t)sizeof(head); + for (int i = 0; i < nch; i++) { + ray_t* c = *src_slots[i]; + if (!c || RAY_IS_ERR(c)) { *on_slots[i] = NULL; continue; } + *on_slots[i] = (ray_t*)(intptr_t)off; /* region-relative offset */ + off += idx_blk_bytes(c); + } + if (fwrite(head, 1, sizeof(head), f) != sizeof(head)) return false; + for (int i = 0; i < nch; i++) { + ray_t* c = *src_slots[i]; + if (!c || RAY_IS_ERR(c)) continue; + ray_t chdr; + memcpy(&chdr, c, 32); + chdr.mmod = 1; chdr.rc = 1; + if (fwrite(&chdr, 1, 32, f) != 32) return false; + size_t dbytes = (size_t)c->len * ray_elem_size(c->type); + if (dbytes && fwrite(ray_data(c), 1, dbytes, f) != dbytes) return false; + size_t pad = (size_t)idx_blk_bytes(c) - 32 - dbytes; + if (pad && fwrite(zeros, 1, pad, f) != pad) return false; + } + return true; +} + /* Map an mmap'd inline region in place: patch child offsets to absolute * pointers and return the RAY_INDEX object (already RAY_MARK_MMAP). `region` * points at the start of the index region within the column's file mapping. diff --git a/src/ops/idxop.h b/src/ops/idxop.h index 609895a9f..87d16c374 100644 --- a/src/ops/idxop.h +++ b/src/ops/idxop.h @@ -45,6 +45,7 @@ * vector get this for free (fresh vectors start at attrs==0, no index). */ +#include /* FILE: ray_index_inline_write_file */ #include #include "mem/heap.h" /* RAY_ATTR_HAS_INDEX */ @@ -277,6 +278,38 @@ ray_t* ray_index_attach_chunk_zone(ray_t** vp, uint8_t chunk_log2); * compute an index for persistence without COWing a shared column. */ ray_t* ray_index_chunk_zone_compute(ray_t* v, uint8_t chunk_log2); +/* ===== Incremental chunk-zone accumulator ===== */ + +typedef struct { + int8_t type; /* column type; 0 = inactive */ + uint8_t is_f64; /* F32 / F64 column: fmins/fmaxs used, no sums */ + int esz; /* element size in bytes */ + int64_t next_row; /* global row the next ray_zone_acc_add starts at */ + uint32_t n_chunks; /* chunks in use so far, indexed by global chunk */ + uint32_t cap; /* chunks allocated */ + int64_t* mins; int64_t* maxs; /* integer zones */ + double* fmins; double* fmaxs; /* float zones */ + bool saw_null; /* the column holds a sentinel/NaN; the writer must + * publish HAS_NULLS (col.c #495 rule) */ + uint8_t* nulls; /* one byte per chunk: 1 = any null in chunk */ + uint64_t* sum_lo; int64_t* sum_hi; int64_t* nn; /* integer zones only */ +} ray_zone_acc_t; + +/* true when `type` gets a chunk zone (the ten numeric/temporal types). */ +bool ray_zone_acc_supported(int8_t type); +/* Start accumulating rows of `type` from global row `start_row`. */ +ray_err_t ray_zone_acc_init(ray_zone_acc_t* a, int8_t type, int64_t start_row); +/* Rows [next_row, next_row + v->len) are v; v->type must equal a->type. */ +/* A non-OK return (OOM, CANCEL) leaves the accumulator partial: free/discard it. */ +ray_err_t ray_zone_acc_add(ray_zone_acc_t* a, ray_t* v); +/* dst += src, chunk by chunk; both must have the same type. src is untouched. */ +ray_err_t ray_zone_acc_merge(ray_zone_acc_t* dst, const ray_zone_acc_t* src); +/* The standalone RAY_IDX_CHUNK_ZONE index for a column of `len` rows + * (chunk_log2 16), identical to ray_index_chunk_zone_compute(col, 16); + * NULL when len < 65536. Frees the accumulator either way. */ +ray_t* ray_zone_acc_finish(ray_zone_acc_t* a, int64_t len); +void ray_zone_acc_free(ray_zone_acc_t* a); + /* 128-bit two's-complement accumulation of int64 values: (hi, lo) += v. * The engine's integer avg sums this way — exact for any column, and the * same bits whatever the morsel split — and the chunk-zone metadata keeps @@ -319,6 +352,29 @@ bool ray_zone_int_sum128(ray_t* x, int64_t* hi_out, uint64_t* lo_out, int64_t* n ray_t* ray_index_dict_compute(ray_t* v); ray_t* ray_index_attach_dict(ray_t** vp); +/* ===== Incremental STR dictionary ===== */ + +typedef struct { + 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 */ + uint32_t* lens; /* per distinct: byte length */ + char* pool; uint64_t pool_len; uint64_t pool_cap; + uint32_t* slot; uint64_t mask; /* code + 1, 0 = empty */ + bool dead; /* row count overflowed int32 codes: nothing is kept */ +} ray_dict_acc_t; +ray_err_t ray_dict_acc_init(ray_dict_acc_t* a); +/* Appends every row of STR vector v. There is no cardinality cap: the + * result matches ray_index_dict_compute for any number of distinct strings. + * Only a row count past INT32_MAX (codes are int32) frees the accumulator, + * 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); +/* 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_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); @@ -329,6 +385,10 @@ ray_t* ray_index_attach_built(ray_t** vp, ray_t* idx); * in place and return the RAY_INDEX object (flagged RAY_MARK_MMAP). */ int64_t ray_index_inline_size(const ray_index_t* ix); void ray_index_inline_write(uint8_t* dst, const ray_index_t* ix); +/* The same bytes as ray_index_inline_write, streamed to `f` block by block + * straight from the child vecs: no region-sized staging buffer (a 100 M-row + * hash region is ~4.5 GB) and one copy fewer. false on a short write. */ +bool ray_index_inline_write_file(FILE* f, const ray_index_t* ix); ray_t* ray_index_inline_map(uint8_t* region, int64_t region_size); /* Drop any attached index from *vp. No-op if none. Restores the diff --git a/src/ops/internal.h b/src/ops/internal.h index f4381f88e..a43d05632 100644 --- a/src/ops/internal.h +++ b/src/ops/internal.h @@ -992,6 +992,9 @@ void partitioned_gather(ray_pool_t* pool, const int64_t* idx, int64_t n, /* ── filter.c ── */ ray_t* exec_filter(ray_graph_t* g, ray_op_t* op, ray_t* input, ray_t* pred); ray_t* exec_filter_head(ray_t* input, ray_t* pred, int64_t limit); +/* The one `where:` rule (see filter.c): consumes `pred`, returns an owned + * BOOL mask of `tn` rows or an error. `label` prefixes the error. */ +ray_t* ray_where_mask_coerce(ray_t* pred, int64_t tn, const char* label); /* Typed membership kernel (verdict-LUT / SIMD / pool-parallel); NULL when * the col/set shape is unsupported — caller falls back to its own path. */ ray_t* ray_in_vec_exec(ray_t* col, ray_t* set, bool negate); @@ -1657,6 +1660,7 @@ ray_t* exec_str_find(ray_graph_t* g, ray_op_t* op); ray_t* materialize_mapcommon(ray_t* mc); ray_t* materialize_mapcommon_head(ray_t* mc, int64_t n); ray_t* materialize_mapcommon_filter(ray_t* mc, ray_t* pred, int64_t pass_count); +ray_t* materialize_mapcommon_gather(ray_t* mc, const int64_t* idx, int64_t n); ray_t* broadcast_scalar(ray_t* atom, int64_t nrows); ray_t* exec_node(ray_graph_t* g, ray_op_t* op); @@ -1806,4 +1810,18 @@ void ray_group_winners(ray_group_winner_fn fn, void* context, const int64_t* row /* Gather winning group rows, retaining source domains and native types. */ ray_t* ray_group_gather(ray_t* column, const int64_t* rows, int64_t count); + +/* A scalar `where:` predicate holds for every row or none. It needs a truth + * value: booleans, numbers and temporals have one (zero and null are false); + * a symbol or a string does not. */ +static inline bool ray_pred_atom_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; + } +} + #endif /* RAY_EXEC_INTERNAL_H */ diff --git a/src/ops/journal.c b/src/ops/journal.c index 2495014cc..34074284c 100644 --- a/src/ops/journal.c +++ b/src/ops/journal.c @@ -218,7 +218,8 @@ ray_t* ray_log_sync_fn(ray_t** args, int64_t n) { } ray_t* ray_log_close_fn(ray_t** args, int64_t n) { - (void)args; (void)n; + (void)args; + if (n != 0) return ray_error("arity", ".log.close takes no arguments"); return err_to_ray(ray_journal_close(), "io"); } diff --git a/src/ops/ops.h b/src/ops/ops.h index d24ce6ae5..b86822ec1 100644 --- a/src/ops/ops.h +++ b/src/ops/ops.h @@ -589,6 +589,13 @@ typedef struct ray_graph { * value of that table's length, so the memo neither serves nor stores * while g->table differs. */ ray_t* memo_table; + + /* Set when an `if` refuses its operands (a text result with a numeric + * branch, a condition with no truth value). Such an error is the + * expression's answer: a caller with an interpreter fallback must not + * retry, since the interpreter's `if` tests one truth value and would + * write the then-branch to every row. */ + bool if_refused; } ray_graph_t; /* ===== Morsel Iterator ===== */ diff --git a/src/ops/opt.c b/src/ops/opt.c index 1a9432e55..dbf2152a9 100644 --- a/src/ops/opt.c +++ b/src/ops/opt.c @@ -664,6 +664,10 @@ static bool fold_filter_const_predicate(ray_graph_t* g, ray_op_t* node) { ray_op_ext_t* pred_ext = find_ext(g, pred->id); if (!pred_ext || !pred_ext->literal || !ray_is_atom(pred_ext->literal)) return false; + /* Only a constant with a truth value folds. atom_to_numeric reads a + * symbol's id, so `where: 'abc` folded to "keep every row"; left in + * place, the filter raises the scalar-predicate type error (#678). */ + if (pred_ext->literal->type == -RAY_SYM) return false; bool keep_rows = false; if (!atom_to_bool(pred_ext->literal, &keep_rows)) return false; @@ -676,6 +680,14 @@ static bool fold_filter_const_predicate(ray_graph_t* g, ray_op_t* node) { return true; } + /* Over a table the filter's job is the selection it installs: the + * aggregate paths run it for that alone, then group the table under + * g->selection. A take-0 in its place installed none, so a false + * `where:` grouped every row. Leave the filter; it turns the false + * constant into an empty selection. */ + ray_op_t* src = op_child(g, node, 0); + if (src && src->out_type == RAY_TABLE) return false; + ray_op_ext_t* ext = ensure_ext_node(g, node->id); if (!ext) return false; ext->base = *node; diff --git a/src/ops/pivot.c b/src/ops/pivot.c index 9d25bcc30..c75d18b80 100644 --- a/src/ops/pivot.c +++ b/src/ops/pivot.c @@ -22,12 +22,14 @@ */ #include +#include #include "ops/internal.h" #include "ops/hash.h" #include "ops/idxop.h" #include "ops/rowsel.h" #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) */ /* Resolved string atom (borrowed) of a SYM-scalar broadcast input * (atom -RAY_SYM, or a 1-elem RAY_SYM_W{8,16,32,64} vec used as @@ -896,7 +898,7 @@ static bool if_type_eager_ok(int8_t bt, int8_t out) { * it to an unwritten result buffer). */ case RAY_F64: case RAY_I64: case RAY_I32: case RAY_I16: case RAY_U8: case RAY_BOOL: - case RAY_TIMESTAMP: case RAY_TIME: case RAY_DATE: + case RAY_TIMESTAMP: case RAY_TIME: case RAY_DATE: case RAY_GUID: return true; default: return false; } @@ -940,6 +942,10 @@ static ray_t* exec_if_selected(ray_graph_t* g, ray_op_t* op, ray_t* cond_v) { * few rows. Touching only the selected rows costs less and holds only * their bytes. Same threshold as the projection's pre-compaction. */ bool sparse_sel = outer_sel && selected * 4 <= nrows; + /* The SYM text build below writes a fresh pool for every row of the + * table, which the filtered result then keeps: only worth it when the + * selection keeps nearly every row. */ + bool near_full_sel = !outer_sel || selected * 10 >= nrows * 9; bool eager_possible = (op->out_type != RAY_STR && if_branch_trivial(g, then_op) && @@ -950,7 +956,17 @@ static ray_t* exec_if_selected(ray_graph_t* g, ray_op_t* op, ray_t* cond_v) { * the eager arm picks descriptors over one pass */ (op->out_type == RAY_STR && !sparse_sel && then_op->out_type == RAY_STR && else_op->out_type == RAY_STR && - if_branch_cheap(g, then_op, 0) && if_branch_cheap(g, else_op, 0)); + if_branch_cheap(g, then_op, 0) && if_branch_cheap(g, else_op, 0)) || + /* a SYM column or literal against a SYM or STR + * one, over enough rows to split: the eager arm + * resolves each row's text on the pool + * (if_str_text_build). Below that the selected + * arm's per-row scatter costs less. */ + (op->out_type == RAY_STR && near_full_sel && nrows >= RAY_PARALLEL_THRESHOLD && + (then_op->out_type == RAY_SYM || else_op->out_type == RAY_SYM) && + (then_op->out_type == RAY_SYM || then_op->out_type == RAY_STR) && + (else_op->out_type == RAY_SYM || else_op->out_type == RAY_STR) && + if_branch_trivial(g, then_op) && if_branch_trivial(g, else_op)); { ray_pool_t* rp = ray_pool_get(); if (rp && rp->n_workers > 0 && eager_possible) @@ -1129,6 +1145,21 @@ static void if_fill_range(const if_fill_ctx_t* c, int64_t i0, int64_t i1) { dst[i] = cond_p[i] ? tv : ev; } break; } + case RAY_GUID: { + /* 16-byte cells: copy the chosen side's cell. A GUID atom keeps + * its bytes in obj; a one-element vector is row 0. */ + uint8_t* dst = (uint8_t*)c->dst; + const uint8_t* tb = ray_is_atom(c->then_v) ? (const uint8_t*)ray_data(c->then_v->obj) + : (const uint8_t*)ray_data(c->then_v); + const uint8_t* eb = ray_is_atom(c->else_v) ? (const uint8_t*)ray_data(c->else_v->obj) + : (const uint8_t*)ray_data(c->else_v); + for (int64_t i = i0; i < i1; i++) { + const uint8_t* src = cond_p[i] + ? tb + (c->then_scalar ? 0 : i) * 16 + : eb + (c->else_scalar ? 0 : i) * 16; + memcpy(dst + i * 16, src, 16); + } + break; } default: break; } } @@ -1168,9 +1199,272 @@ static void if_str_desc_fn(void* vctx, uint32_t worker_id, int64_t start, int64_ } } -static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { +/* Truthiness of one cell of an `if` condition vector, the rule is_truthy + * applies to an atom: null and zero are false, anything else is true. */ +static uint8_t if_cond_cell(ray_t* c, int64_t i) { + const void* d = ray_data(c); + switch (c->type) { + case RAY_BOOL: case RAY_U8: + return ((const uint8_t*)d)[i] != 0; + default: break; + } + if (ray_vec_is_null(c, i)) return 0; + switch (c->type) { + case RAY_I16: return ((const int16_t*)d)[i] != 0; + case RAY_I32: case RAY_DATE: case RAY_TIME: + return ((const int32_t*)d)[i] != 0; + case RAY_I64: case RAY_TIMESTAMP: + return ((const int64_t*)d)[i] != 0; + case RAY_F32: { float f = ((const float*)d)[i]; return f != 0.0f && f == f; } + case RAY_F64: { double f = ((const double*)d)[i]; return f != 0.0 && f == f; } + default: return 0; /* refused by if_cond_type_ok first */ + } +} + +/* Truthiness of an atom condition: is_truthy's rule (lang/internal.h, which + * this file cannot include), kept in step with it. */ +static uint8_t if_cond_atom(ray_t* x) { + if (RAY_ATOM_IS_NULL(x)) return 0; + switch (x->type) { + case -RAY_BOOL: return x->b8 != 0; + case -RAY_U8: return x->u8 != 0; + case -RAY_I16: return x->i16 != 0; + case -RAY_I32: return x->i32 != 0; + case -RAY_I64: case -RAY_DATE: case -RAY_TIME: case -RAY_TIMESTAMP: + return x->i64 != 0; + case -RAY_F32: case -RAY_F64: + return x->f64 != 0.0 && x->f64 == x->f64; + default: + return 1; + } +} + +/* A condition vector needs a truth value per cell: booleans, numbers and + * temporals have one. Text, GUID and boxed lists do not. */ +static bool if_cond_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; + } +} + +/* STR output with a SYM side (the other a SYM or STR vector, or a + * broadcast scalar): each row takes its chosen side's text into a fresh + * descriptor; texts past the inline width go to one pool laid out in row + * order. A SYM cell is read through a snapshot taken here, serially, + * before any worker runs — the runtime table's string array + * (ray_sym_strings_borrow) or a FILE domain's raw vocabulary + * (ray_sym_domain_raw_pin) — so nothing is interned or materialised and + * both passes run on the pool. A cell neither snapshot can read (a + * FILE-domain position appended after the file was mapped, an id past the + * table) makes the build decline; the caller then appends serially. */ +enum { IF_TXT_SCALAR = 1, IF_TXT_STR, IF_TXT_SYM_RT, IF_TXT_SYM_FILE }; + +typedef struct { + uint8_t kind; + const char* sp; /* scalar text */ + uint32_t sl; + const ray_str_t* desc; /* STR vector */ + const char* bytes; + const void* sym; /* SYM vector cells */ + int8_t sym_type; + uint8_t sym_attrs; + ray_t** rt_strings; /* runtime-domain snapshot */ + uint32_t rt_count; + struct ray_sym_domain_s* dom; /* FILE domain, pinned */ + ray_sym_domain_raw_t raw; +} if_txt_side_t; + +static bool if_txt_side_init(if_txt_side_t* s, ray_t* v, bool scalar, int64_t len) { + memset(s, 0, sizeof(*s)); + if (scalar) { + const char* sp = ""; + size_t sl = 0; + if (v->type == -RAY_STR) { + sp = ray_str_ptr(v); sl = ray_str_len(v); + } else if (v->type == RAY_STR) { + sp = ray_str_vec_get(v, 0, &sl); + if (!sp) { sp = ""; sl = 0; } + } else if (v->type == -RAY_SYM || RAY_IS_SYM(v->type)) { + ray_t* a = sym_scalar_str(v); + sp = a ? ray_str_ptr(a) : ""; + sl = a ? ray_str_len(a) : 0; + } else { + return false; + } + if (sl > UINT32_MAX) return false; + s->kind = IF_TXT_SCALAR; s->sp = sp; s->sl = (uint32_t)sl; + return true; + } + if (v->len < len) return false; + if (v->type == RAY_STR) { + s->kind = IF_TXT_STR; + str_resolve(v, &s->desc, &s->bytes); + return true; + } + if (!RAY_IS_SYM(v->type)) return false; + s->sym = ray_data(v); + s->sym_type = v->type; + s->sym_attrs = v->attrs; + struct ray_sym_domain_s* dom = ray_sym_vec_domain(v); + if (dom == ray_sym_runtime_domain()) { + ray_sym_strings_borrow(&s->rt_strings, &s->rt_count); + if (!s->rt_strings) return false; + s->kind = IF_TXT_SYM_RT; + return true; + } + if (!ray_sym_domain_raw_pin(dom, &s->raw)) return false; + s->dom = dom; + s->kind = IF_TXT_SYM_FILE; + return true; +} + +static void if_txt_side_free(if_txt_side_t* s) { + if (s->kind == IF_TXT_SYM_FILE) ray_sym_domain_raw_unpin(s->dom); + s->kind = 0; +} + +/* Text of row r on this side; false for a cell the snapshot cannot read. */ +static inline bool if_txt_get(const if_txt_side_t* s, int64_t r, + const char** sp, uint32_t* sl) { + switch (s->kind) { + case IF_TXT_SCALAR: + *sp = s->sp; *sl = s->sl; + return true; + case IF_TXT_STR: { + const ray_str_t* d = &s->desc[r]; + *sl = d->len; + *sp = d->len == 0 ? "" : ray_str_is_inline(d) ? d->data : s->bytes + d->pool_off; + return true; + } + case IF_TXT_SYM_RT: { + int64_t id = ray_read_sym(s->sym, r, s->sym_type, s->sym_attrs); + if (id < 0 || id >= (int64_t)s->rt_count || !s->rt_strings[id]) return false; + ray_t* a = s->rt_strings[id]; + *sp = ray_str_ptr(a); *sl = (uint32_t)ray_str_len(a); + return true; + } + case IF_TXT_SYM_FILE: { + int64_t pos = ray_read_sym(s->sym, r, s->sym_type, s->sym_attrs); + if (pos < 0 || pos >= s->raw.count) return false; + size_t l = 0; + *sp = ray_sym_domain_raw_str(&s->raw, pos, &l); + *sl = (uint32_t)l; + return true; + } + default: + return false; + } +} + +typedef struct { + const uint8_t* cond; + const if_txt_side_t* t; + const if_txt_side_t* e; + uint32_t* off; /* pooled length per row, then its pool offset */ + ray_str_t* dst; + char* pool; + _Atomic(int) miss; +} if_txt_ctx_t; + +static void if_txt_len_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + if_txt_ctx_t* c = (if_txt_ctx_t*)vctx; + for (int64_t r = start; r < end; r++) { + const char* sp; uint32_t sl; + if (!if_txt_get(c->cond[r] ? c->t : c->e, r, &sp, &sl)) { + atomic_store_explicit(&c->miss, 1, memory_order_relaxed); + return; + } + c->off[r] = sl > RAY_STR_INLINE_MAX ? sl : 0; + } +} + +static void if_txt_fill_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + if_txt_ctx_t* c = (if_txt_ctx_t*)vctx; + for (int64_t r = start; r < end; r++) { + const char* sp = ""; uint32_t sl = 0; + if (!if_txt_get(c->cond[r] ? c->t : c->e, r, &sp, &sl)) { sp = ""; sl = 0; } + ray_str_t* d = &c->dst[r]; + memset(d, 0, sizeof(*d)); + d->len = sl; + if (sl <= RAY_STR_INLINE_MAX) { + if (sl) memcpy(d->data, sp, sl); + } else { + memcpy(d->prefix, sp, 4); + d->pool_off = c->off[r]; + memcpy(c->pool + c->off[r], sp, sl); + } + } +} + +/* Fills `result` (STR, len rows) and returns it, or NULL with `result` + * untouched when the build does not apply. */ +static ray_t* if_str_text_build(ray_t* result, const uint8_t* cond, int64_t len, + ray_t* then_v, bool then_scalar, + ray_t* else_v, bool else_scalar) { + bool t_sym = then_v->type == -RAY_SYM || RAY_IS_SYM(then_v->type); + bool e_sym = else_v->type == -RAY_SYM || RAY_IS_SYM(else_v->type); + if (!t_sym && !e_sym) return NULL; + if (len <= 0) return NULL; + + if_txt_side_t t, e; + if (!if_txt_side_init(&t, then_v, then_scalar, len)) { + if_txt_side_free(&t); + return NULL; + } + if (!if_txt_side_init(&e, else_v, else_scalar, len)) { + if_txt_side_free(&t); if_txt_side_free(&e); + return NULL; + } + ray_t* off_hdr = NULL; + uint32_t* off = (uint32_t*)scratch_alloc(&off_hdr, (size_t)len * sizeof(uint32_t)); + if (!off) { if_txt_side_free(&t); if_txt_side_free(&e); return NULL; } + + if_txt_ctx_t c = { .cond = cond, .t = &t, .e = &e, .off = off, + .dst = (ray_str_t*)ray_data(result), .pool = NULL }; + atomic_init(&c.miss, 0); + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, len, RAY_PARALLEL_THRESHOLD); + if (par) ray_pool_dispatch(pool, if_txt_len_fn, &c, len); + else if_txt_len_fn(&c, 0, 0, len); + + uint64_t run = 0; + bool ok = atomic_load_explicit(&c.miss, memory_order_relaxed) == 0; + if (ok) { + for (int64_t r = 0; r < len; r++) { + uint32_t l = off[r]; + off[r] = (uint32_t)run; + run += l; + if (run > UINT32_MAX) { ok = false; break; } + } + } + ray_t* np = NULL; + if (ok && run > 0) { + np = ray_alloc((size_t)run); + if (!np || RAY_IS_ERR(np)) { np = NULL; ok = false; } + else { np->type = RAY_U8; np->len = (int64_t)run; c.pool = (char*)ray_data(np); } + } + if (ok) { + if (par) ray_pool_dispatch(pool, if_txt_fill_fn, &c, len); + else if_txt_fill_fn(&c, 0, 0, len); + result->str_pool = np; + } + scratch_free(off_hdr); + if_txt_side_free(&t); + if_txt_side_free(&e); + return ok ? result : NULL; +} + +/* `cond_in`: the condition exec_if already evaluated (ownership passes + * here), or NULL to evaluate it. */ +static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op, ray_t* cond_in) { /* cond = inputs[0], then = inputs[1], else_id stored in ext->third_in */ - ray_t* cond_v = exec_node(g, op_child(g, op, 0)); + ray_t* cond_v = cond_in ? cond_in : exec_node(g, op_child(g, op, 0)); ray_t* then_v = exec_node(g, op_child(g, op, 1)); ray_op_ext_t* ext = find_ext(g, op->id); @@ -1192,21 +1486,40 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { return else_v; } - /* A scalar condition has one cell, and the fills below index it per row — - * reading past it, so `(if false f 1.0)` returned a mixture of both - * branches. Expand it once so every consumer sees a full-length mask; - * the selected arm declines a scalar condition outright, which is why - * this only ever mattered here. */ - if (ray_is_atom(cond_v)) { - int64_t n = ray_is_atom(then_v) ? (ray_is_atom(else_v) ? 1 : else_v->len) - : then_v->len; - uint8_t on = cond_v->b8 ? 1 : 0; + /* The fills below read the condition as one BOOL byte per row. A scalar + * condition has one cell, and indexing it per row read past it, so + * `(if false f 1.0)` returned a mixture of both branches. A reduction + * in the condition, such as `(> (count x) 3)`, reaches here as a + * one-element vector rather than an atom and is the same scalar against + * vector branches. A condition of another type, such as `(count x)` or + * an I64 column, was read byte by byte. Every such condition becomes a + * full-length BOOL mask, with is_truthy's rule per cell; the + * selected arm declines all of them, which is why only this arm + * mattered. */ + int64_t branch_len = 1; + if (!ray_is_atom(then_v) && then_v->len > branch_len) branch_len = then_v->len; + if (!ray_is_atom(else_v) && else_v->len > branch_len) branch_len = else_v->len; + if (!ray_is_atom(cond_v) && !if_cond_type_ok(cond_v->type)) { + int8_t ct = cond_v->type; + g->if_refused = true; + ray_release(cond_v); ray_release(then_v); ray_release(else_v); + return ray_error("type", "if: condition must be boolean, numeric or temporal, got %s", + ray_type_name(ct)); + } + bool cond_bcast = ray_is_atom(cond_v) || (cond_v->len == 1 && branch_len > 1); + if (cond_bcast || cond_v->type != RAY_BOOL) { + int64_t n = cond_bcast ? branch_len : cond_v->len; ray_t* mask = ray_vec_new(RAY_BOOL, n); if (!mask || RAY_IS_ERR(mask)) { ray_release(cond_v); ray_release(then_v); ray_release(else_v); return mask ? mask : ray_error("oom", NULL); } - memset(ray_data(mask), on, (size_t)n); + uint8_t* m = (uint8_t*)ray_data(mask); + if (cond_bcast) + memset(m, ray_is_atom(cond_v) ? if_cond_atom(cond_v) + : if_cond_cell(cond_v, 0), (size_t)n); + else + for (int64_t i = 0; i < n; i++) m[i] = if_cond_cell(cond_v, i); mask->len = n; ray_release(cond_v); cond_v = mask; @@ -1234,6 +1547,14 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { uint8_t* cond_p = (uint8_t*)ray_data(cond_v); if (out_type == RAY_STR) { + if (if_str_text_build(result, cond_p, len, then_v, then_scalar, + else_v, else_scalar)) { + ray_release(cond_v); ray_release(then_v); ray_release(else_v); + return result; + } + /* A SYM side the text build could not read (a symbol appended to + * its domain after the snapshot) is resolved row by row below, from + * the branches already materialised. */ /* Two STR vectors: the result is descriptors only. Each row takes * its side's 16-byte descriptor; pooled strings keep pointing into * their pool. One shared pool (or one side inline-only) is reused @@ -1437,7 +1758,40 @@ static ray_t* exec_if_eager(ray_graph_t* g, ray_op_t* op) { return result; } +static bool if_type_is_text(int8_t t) { return t == RAY_STR || t == RAY_SYM; } + +/* A branch that can stand in a text result: a text column or literal, a + * boxed list, an untyped node, or a null literal such as `0N`, which the + * fills write as the text null. */ +static bool if_branch_text_ok(ray_graph_t* g, ray_op_t* b) { + if (!b) return true; + int8_t t = b->out_type; + if (t <= 0 || t == RAY_LIST || if_type_is_text(t)) return true; + if (b->opcode == OP_CONST) { + ray_op_ext_t* ext = find_ext(g, b->id); + if (ext && ext->literal && ray_is_atom(ext->literal) && + RAY_ATOM_IS_NULL(ext->literal)) + return true; + } + return false; +} + ray_t* exec_if(ray_graph_t* g, ray_op_t* op) { + /* A text result with a non-text branch has no column type: the fills + * read the numbers as string descriptors or symbol ids and returned + * garbage, e.g. `(if (< x 3) s x)` with s SYM and x I64. */ + if (if_type_is_text(op->out_type)) { + ray_op_t* then_op = op_child(g, op, 1); + ray_op_ext_t* ext = find_ext(g, op->id); + ray_op_t* else_op = ext ? op_node(g, ext->third_in) : NULL; + int8_t tt = then_op ? then_op->out_type : 0; + int8_t et = else_op ? else_op->out_type : 0; + if (!if_branch_text_ok(g, then_op) || !if_branch_text_ok(g, else_op)) { + g->if_refused = true; + return ray_error("type", "if: branches mix %s and %s", + ray_type_name(tt), ray_type_name(et)); + } + } ray_t* cond_v = exec_node(g, op_child(g, op, 0)); if (!cond_v || RAY_IS_ERR(cond_v)) return cond_v; @@ -1447,8 +1801,8 @@ ray_t* exec_if(ray_graph_t* g, ray_op_t* op) { return selected; } - ray_release(cond_v); - return exec_if_eager(g, op); + /* the condition is handed on, not evaluated twice */ + return exec_if_eager(g, op, cond_v); } /* Fold the null-mask words [nullw, nullw+null_words) into a running hash. diff --git a/src/ops/query.c b/src/ops/query.c index 028c53bc2..3da90cc8c 100644 --- a/src/ops/query.c +++ b/src/ops/query.c @@ -26,11 +26,13 @@ */ #include "lang/internal.h" +#include "io/parquet.h" #include "lang/eval.h" #include "lang/env.h" #include "ops/ops.h" #include "ops/internal.h" #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 */ @@ -351,6 +353,39 @@ static bool dag_temporal_arith_needs_eval(const char* name, size_t len, return len == 1 && (name[0] == '+' || name[0] == '-' || name[0] == '*'); } +/* A comparison between a temporal and a float has no meaning — the eval + * path rejects it (`cannot compare timestamp and f64`, cmp.c). The DAG + * kernel promoted both sides to double, where a TIMESTAMP near 2024 has a + * 128 ns ULP: against the F64 mean of the column, (> ts (avg ts)) read + * every row as equal to the mean (#694). Integer scalars stay on the + * exact int64 kernel, as they always did. */ +static bool dag_cmp_rejects_temporal_float(const char* fname, size_t fname_len, + int8_t lt, int8_t rt) { + bool cmp = (fname_len == 1 && (fname[0] == '>' || fname[0] == '<')) || + (fname_len == 2 && fname[1] == '=' && + (fname[0] == '>' || fname[0] == '<' || + fname[0] == '=' || fname[0] == '!')); + if (!cmp) return false; + if (RAY_IS_PARTED(lt)) lt = (int8_t)RAY_PARTED_BASETYPE(lt); + if (RAY_IS_PARTED(rt)) rt = (int8_t)RAY_PARTED_BASETYPE(rt); + bool lf = lt == RAY_F64 || lt == RAY_F32; + bool rf = rt == RAY_F64 || rt == RAY_F32; + return (dag_type_is_temporal(lt) && rf) || (lf && dag_type_is_temporal(rt)); +} + +/* A column operand of `and` / `or` must be boolean: the kernel read an I64 + * 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 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) + 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)); + return false; +} + static bool dag_unary_numeric_name(const char* name, size_t len) { if (len == 3) return memcmp(name, "sin", 3) == 0 || @@ -1499,12 +1534,42 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { uint32_t col_id = col->id; ray_op_t* bucket = compile_expr_dag(g, elems[2]); if (!bucket) return NULL; + uint32_t bucket_id = bucket->id; col = &g->nodes[col_id]; - /* xbar(x, b) = x - (x % b) (stays in integer domain) */ + /* xbar(x, b) = x - (x % b) (stays in integer domain). + * + * A temporal column keeps its type (ray_xbar_fn returns the + * column's type, #669): `promote` folds TIMESTAMP into I64 and + * DATE / TIME into I32, so the bucketed result is cast back to + * the column's type — same width, so the cast is a retag (or a + * narrowing from an I64 bucket for DATE / TIME). The eval path + * rejects a float bucket on a temporal column; declining here + * sends the projection to it for the same error. A TIME bucket + * on a TIMESTAMP column is in milliseconds (ray_xbar_fn scales + * 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 temporal = dag_type_is_temporal(col_t) ? col_t : 0; + if (temporal) { + int8_t bt = bucket->out_type; + if (RAY_IS_PARTED(bt)) bt = (int8_t)RAY_PARTED_BASETYPE(bt); + if (bt == RAY_F64 || bt == RAY_F32) return NULL; + if (temporal == RAY_TIMESTAMP && bt == RAY_TIME) { + ray_op_t* scale = ray_const_i64(g, 1000000LL); + if (!scale) return NULL; + bucket = &g->nodes[bucket_id]; + bucket = ray_mul(g, bucket, scale); + if (!bucket) return NULL; + bucket_id = bucket->id; + col = &g->nodes[col_id]; + } + } ray_op_t* m = ray_mod(g, col, bucket); if (!m) return NULL; col = &g->nodes[col_id]; - return ray_sub(g, col, m); + ray_op_t* r = ray_sub(g, col, m); + if (!r || !temporal) return r; + return ray_cast(g, r, temporal); } /* (if cond then else) — 4 elements (fn + 3 args). Compiles @@ -1807,6 +1872,7 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { for (int64_t i = 0; i < k; i++) { ray_op_t* a = compile_expr_dag(g, elems[i + 1]); if (!a) return NULL; + if (!dag_bool_operand_ok(g, a, is_and)) return NULL; arg_ids[i] = a->id; } dag_binary_ctor ctor = is_and ? ray_and : ray_or; @@ -1863,6 +1929,10 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_op_t* right = compile_expr_dag(g, elems[2]); if (!right) return NULL; left = &g->nodes[left_id]; + if ((ctor == ray_and || ctor == ray_or) && + (!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)) @@ -1877,6 +1947,15 @@ ray_op_t* compile_expr_dag(ray_graph_t* g, ray_t* expr) { ray_type_name((int8_t)-right->out_type)); return NULL; } + if (g->if_arm_depth == 0 && + dag_cmp_rejects_temporal_float(fname, fname_len, + left->out_type, right->out_type)) { + 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)); + return NULL; + } if (fname_len == 3 && memcmp(fname, "pow", 3) == 0 && (!dag_pow_type_admitted(left->out_type) || !dag_pow_type_admitted(right->out_type))) @@ -1976,37 +2055,6 @@ static ray_t* bind_all_columns(ray_t* tbl) { return prev; } -static bool query_atom_truthy(ray_t* v, bool* out) { - if (!v || !ray_is_atom(v) || RAY_ATOM_IS_NULL(v)) return false; - switch (v->type) { - case -RAY_BOOL: - *out = v->b8 != 0; - return true; - case -RAY_U8: - *out = v->u8 != 0; - return true; - case -RAY_I16: - *out = v->i16 != 0; - return true; - case -RAY_I32: - case -RAY_DATE: - case -RAY_TIME: - *out = v->i32 != 0; - return true; - case -RAY_I64: - case -RAY_SYM: - case -RAY_TIMESTAMP: - *out = v->i64 != 0; - return true; - case -RAY_F32: - case -RAY_F64: - *out = v->f64 != 0.0; - return true; - default: - return false; - } -} - 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); @@ -2021,33 +2069,8 @@ static ray_t* eval_where_mask(ray_t* where_expr, ray_t* tbl, const char* label) if (RAY_IS_ERR(mask)) return mask; - int64_t nrows = ray_table_nrows(tbl); - if (mask->type == RAY_BOOL) { - if (mask->len != nrows) { - int64_t got = mask->len; - ray_release(mask); - return ray_error("length", - "%s: WHERE mask length %lld does not match row count %lld", - label, (long long)got, (long long)nrows); - } - return mask; - } - - bool keep = false; - if (query_atom_truthy(mask, &keep)) { - ray_release(mask); - ray_t* out = ray_vec_new(RAY_BOOL, nrows); - if (!out || RAY_IS_ERR(out)) return out ? out : ray_error("oom", NULL); - out->len = nrows; - memset(ray_data(out), keep ? 1 : 0, (size_t)nrows); - return out; - } - - int8_t got_type = mask->type; - ray_release(mask); - return ray_error("type", - "%s: WHERE must produce a bool mask or truthy scalar, got %s", - label, ray_type_name(got_type)); + /* the one where: rule — same as the compiled OP_FILTER path */ + return ray_where_mask_coerce(mask, ray_table_nrows(tbl), label); } static ray_op_t* compile_where_predicate(ray_graph_t* g, ray_t* tbl, @@ -2057,6 +2080,14 @@ static ray_op_t* compile_where_predicate(ray_graph_t* g, ray_t* tbl, if (out_err) *out_err = NULL; ray_op_t* pred = compile_expr_dag(g, where_expr); if (pred) return pred; + /* A predicate the compiler rejected outright (`(and x ...)` over an + * I64 column) is an error, not a fallback: the interpreter's `and` is + * a scalar truth test, which would have kept every row. */ + if (g->compile_err) { + if (out_err) *out_err = graph_take_compile_err(g); + else { ray_release(g->compile_err); g->compile_err = NULL; } + return NULL; + } ray_t* mask = eval_where_mask(where_expr, tbl, label); if (!mask || RAY_IS_ERR(mask)) { @@ -2359,6 +2390,29 @@ static int expr_contains_call_named(ray_t* expr, const char* name, size_t name_l static ray_t* query_materialize_parted_col(ray_t* col); static bool table_has_parted_columns(ray_t* tbl); +static ray_t* query_materialize_parted_table(ray_t* tbl); + +/* A projection that is a bare, unquoted column name of `tbl` IS that column. + * The eval fallback otherwise evaluates it per row and collects the cells; + * before the collector collapsed SYM atoms, `name: name` beside a projection + * the DAG declines (temporal arithmetic, say) came back as a LIST of boxed + * sym atoms, and a join on it matched nothing (rayforce-py#24). Taking the + * column directly is what the DAG path does for the same expression, keeps + * every column kind (a LIST column included) as it is, and skips the per-row + * walk. Owned ref, or NULL when the expression is not such a name or + * the column is not a plain full-length vector (parted / mapcommon / slice + * columns keep the per-row read, which handles them cell by cell). */ +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) + return NULL; + ray_retain(col); + return col; +} /* True when a projection's TOP-LEVEL call is a "whole-column verb": a * length-changing / reordering builtin (distinct, asc, desc, reverse) that @@ -3136,6 +3190,66 @@ static int64_t derived_key_name(ray_t* by_expr) { } return ray_sym_intern("key", 3); } +/* The column of a computed group key `v` over `tbl`, caller owns it. The + * caller has pushed a query scope binding `tbl`'s columns; a partitioned + * column the key reads is bound flattened for the evaluation and restored + * after. Compiled as a projection where it can be: group-key expressions + * have the same row-wise semantics as projections, and eval-level `if` + * tests whole-vector truthiness and would choose one branch for every + * input row. */ +static ray_t* group_key_eval(ray_t* v, ray_t* tbl) { + /* Exact-size carve: collect_col_refs dedups against real table + * columns, so ray_table_ncols(tbl) is a hard upper bound. */ + int64_t ncols_max = ray_table_ncols(tbl); + if (ncols_max < 1) ncols_max = 1; + ray_t* refs_hdr = NULL; + int64_t* ref_syms = (int64_t*)scratch_alloc(&refs_hdr, + (size_t)ncols_max * (sizeof(int64_t) + sizeof(ray_t*))); + if (!ref_syms) return ray_error("oom", NULL); + ray_t** materialized_refs = (ray_t**)(ref_syms + ncols_max); + int n_refs = collect_col_refs(v, tbl, ref_syms, (int)ncols_max, 0); + 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]); + if (ref_col && (RAY_IS_PARTED(ref_col->type) || + ref_col->type == RAY_MAPCOMMON)) { + ray_t* flat = query_materialize_parted_col(ref_col); + if (!flat || RAY_IS_ERR(flat)) { + col_vec = flat ? flat : ray_error("oom", NULL); + break; + } + materialized_refs[ri] = flat; + ray_env_set_query_local(ref_syms[ri], flat); + } + } + if (!col_vec) { + ray_graph_t* key_graph = ray_graph_new(tbl); + if (!key_graph) col_vec = ray_error("oom", NULL); + else { + ray_op_t* key_op = compile_expr_dag(key_graph, v); + if (key_op) { + key_op = ray_optimize(key_graph, key_op); + col_vec = ray_execute(key_graph, key_op); + if (!col_vec) col_vec = ray_error("domain", "by-dict key execution failed"); + } + ray_graph_free(key_graph); + } + if (!col_vec) col_vec = ray_eval(v); + if (ray_is_lazy(col_vec)) + col_vec = ray_lazy_materialize(col_vec); + } + 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); + ray_release(materialized_refs[ri]); + } + } + scratch_free(refs_hdr); + return col_vec; +} + #define DERIVED_KEY_MAX_DOMAIN (64LL * 1024 * 1024) /* The distinct-symbol evaluation, in chunks and over STR. * @@ -3147,14 +3261,17 @@ static int64_t derived_key_name(ray_t* by_expr) { * 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 raw vocabulary bytes, CHUNK rows at a time: every + * 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, - * exactly the ids the SYM evaluation would have produced for them. - * Applies only when the expression's result over the SYM column is SYM - * (so the interned result has the type the caller expects) and the - * column's vocabulary is readable through the raw snapshot. Any other - * shape returns NULL and the caller takes the one-shot SYM evaluation. */ + * 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 @@ -3191,6 +3308,8 @@ typedef struct { 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; @@ -3200,7 +3319,20 @@ static void dk_chunk_scan_fn(void* vctx, uint32_t wid, int64_t start, int64_t en 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 (pos >= 0 && pos < c->raw->count) { + 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; @@ -3232,6 +3364,43 @@ static void dk_chunk_fill_fn(void* vctx, uint32_t wid, int64_t start, int64_t en } } +/* 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; + } + } + return true; +} + 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) { @@ -3242,27 +3411,12 @@ static ray_t* derived_key_chunk_strs(const void* dv, uint8_t dattrs, int64_t lo, if (!mem) return NULL; dk_chunk_ctx_t c; memset(&c, 0, sizeof(c)); - c.dv = dv; c.dattrs = dattrs; c.lo = lo; c.raw = raw; c.ptr = (const char**)mem; c.len = (uint32_t*)(mem + ptr_sz); c.off = (uint32_t*)(mem + ptr_sz + u32_sz); - atomic_store_explicit(&c.late, 0, memory_order_relaxed); - + if (!dk_chunk_views(dv, dattrs, lo, n, raw, dom, c.ptr, c.len)) { scratch_free(aux_hdr); return NULL; } ray_pool_t* pool = ray_pool_get(); bool par = ray_pool_par_dispatch_ok(pool, n, RAY_PARALLEL_THRESHOLD); - if (par) 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 (c.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) { scratch_free(aux_hdr); return NULL; } - c.ptr[i] = a ? ray_str_ptr(a) : ""; - c.len[i] = (uint32_t)sl; - } - } uint64_t total = 0; for (int64_t i = 0; i < n; i++) { if (c.len[i] <= RAY_STR_INLINE_MAX) continue; @@ -3288,14 +3442,256 @@ static ray_t* derived_key_chunk_strs(const void* dv, uint8_t dattrs, int64_t lo, return sv; } -/* ---- chunk result interning: each distinct string of the chunk's key - * vector is interned once, all of them under one lock, and its id spread - * over the rows that hold it. The hashes are the intern table's own - * (ray_hash_bytes), computed on the workers; the dedupe is an - * open-addressing table over the distinct ordinals, on scratch. */ +/* ---- 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; @@ -3304,74 +3700,56 @@ static void dk_hash_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { 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]; - c->hash[i] = (uint32_t)ray_hash_bytes(ray_str_t_ptr(d, c->pool), d->len); + 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, int64_t* out) { - const ray_str_t* desc = NULL; - const char* pool = NULL; - str_resolve(kc, &desc, &pool); - int64_t slots = 1024; - while (slots < 2 * n) slots <<= 1; +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; - size_t hash_sz = (size_t)n * sizeof(uint32_t); - size_t rep_sz = (size_t)n * sizeof(int32_t); - size_t tab_sz = (size_t)slots * sizeof(int32_t); - size_t dstr_sz = (size_t)n * sizeof(const char*); - size_t dlen_sz = (size_t)n * sizeof(size_t); - size_t dhsh_sz = (size_t)n * sizeof(uint32_t); - size_t did_sz = (size_t)n * sizeof(int64_t); - /* One carve; the 8-byte arrays go first so every field stays aligned. */ - char* mem = (char*)scratch_alloc(&hdr, hash_sz + rep_sz + tab_sz + dstr_sz + dlen_sz + dhsh_sz + did_sz); + char* mem = (char*)scratch_alloc(&hdr, (size_t)n * (sizeof(const char*) + 2 * sizeof(uint32_t))); if (!mem) return false; - const char** dstr = (const char**)mem; mem += dstr_sz; - size_t* dlen = (size_t*)mem; mem += dlen_sz; - int64_t* did = (int64_t*)mem; mem += did_sz; - uint32_t* hash = (uint32_t*)mem; mem += hash_sz; - int32_t* rep = (int32_t*)mem; mem += rep_sz; - int32_t* tab = (int32_t*)mem; mem += tab_sz; - uint32_t* dhsh = (uint32_t*)mem; - memset(tab, 0xff, tab_sz); - - dk_hash_ctx_t hc = { .desc = desc, .pool = pool, .hash = hash }; + 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; +} - uint64_t mask = (uint64_t)slots - 1; - int64_t nd = 0; +/* 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++) { - uint32_t h = hash[i]; - const ray_str_t* d = &desc[i]; - const char* sp = ray_str_t_ptr(d, pool); - uint64_t s = ((uint64_t)h * 0x9E3779B97F4A7C15ull >> 32) & mask; - for (;;) { - int32_t r = tab[s]; - if (r < 0) { - tab[s] = (int32_t)nd; - rep[i] = (int32_t)nd; - dstr[nd] = sp; dlen[nd] = d->len; dhsh[nd] = h; - nd++; - break; - } - if (dhsh[r] == h && dlen[r] == d->len && - (d->len == 0 || memcmp(dstr[r], sp, d->len) == 0)) { - rep[i] = r; - break; - } - s = (s + 1) & mask; - } - } - /* Key strings are values, not names: interned without the dotted- - * segment caching that a name with '.' in it gets (a host or URL would - * otherwise intern every one of its segments too). */ - if (ray_sym_intern_batch_no_split(dhsh, dstr, dlen, nd, did) < 0) { scratch_free(hdr); return false; } - for (int64_t i = 0; i < n; i++) out[i] = did[rep[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 true; + return ok; } /* ---- the spread pass of derived_key_over_sym_domain: each row takes the @@ -3383,11 +3761,28 @@ typedef struct { const int32_t* pos; const int64_t* key; /* spread: key per slot; NULL = write the slot */ int64_t* out; + bool sparse; /* a selection: an unslotted id (-1) takes slot 0 */ } dk_rows_ctx_t; static void dk_spread_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { (void)wid; const dk_rows_ctx_t* c = (const dk_rows_ctx_t*)vctx; + if (c->sparse) { + /* rows outside the selection have no slot: they take slot 0 (the + * grouping never reads them — it honours the same selection) */ + if (c->key) { + for (int64_t r = start; r < end; r++) { + int32_t s = c->pos[ray_read_sym(c->cd, r, RAY_SYM, c->attrs)]; + c->out[r] = c->key[s >= 0 ? s : 0]; + } + } else { + for (int64_t r = start; r < end; r++) { + int32_t s = c->pos[ray_read_sym(c->cd, r, RAY_SYM, c->attrs)]; + c->out[r] = s >= 0 ? s : 0; + } + } + return; + } if (c->key) { for (int64_t r = start; r < end; r++) c->out[r] = c->key[c->pos[ray_read_sym(c->cd, r, RAY_SYM, c->attrs)]]; @@ -3396,11 +3791,469 @@ static void dk_spread_fn(void* vctx, uint32_t wid, int64_t start, int64_t end) { c->out[r] = c->pos[ray_read_sym(c->cd, r, RAY_SYM, c->attrs)]; } } + +/* ---- the rows of a selection, in row order (every row when sel is NULL): + * a cursor over the rowsel's morsel flags — a NONE morsel is skipped, an + * ALL morsel is a row range, a MIX morsel its index list. */ +typedef struct { + ray_t* sel; + int64_t nrows; + int64_t seg, n_segs; + const uint8_t* flags; + const uint32_t* offs; + const uint16_t* idx; + int64_t base; + int64_t r, end; /* a range: the next row and its end */ + int64_t k, kend; /* an index list: the next entry and its end */ + int mode; /* 0 = between morsels, 1 = range, 2 = indices */ +} dk_sel_it_t; + +static void dk_sel_it_init(dk_sel_it_t* it, ray_t* sel, int64_t nrows) { + memset(it, 0, sizeof(*it)); + it->sel = sel; it->nrows = nrows; it->seg = -1; + if (!sel) { it->mode = 1; it->r = 0; it->end = nrows; return; } + ray_rowsel_t* m = ray_rowsel_meta(sel); + it->n_segs = m->n_segs; + it->flags = ray_rowsel_flags(sel); + it->offs = ray_rowsel_offsets(sel); + it->idx = ray_rowsel_idx(sel); +} + +/* The next selected row, or -1 past the last. */ +static inline int64_t dk_sel_it_next(dk_sel_it_t* it) { + for (;;) { + if (it->mode == 1) { if (it->r < it->end) return it->r++; } + else if (it->mode == 2) { if (it->k < it->kend) return it->base + it->idx[it->k++]; } + if (!it->sel || ++it->seg >= it->n_segs) { it->mode = 0; return -1; } + uint8_t f = it->flags[it->seg]; + it->base = it->seg * RAY_MORSEL_ELEMS; + if (f == RAY_SEL_NONE) { it->mode = 0; continue; } + if (f == RAY_SEL_ALL) { + it->mode = 1; it->r = it->base; + it->end = it->base + RAY_MORSEL_ELEMS; + if (it->end > it->nrows) it->end = it->nrows; + } else { + it->mode = 2; it->k = it->offs[it->seg]; it->kend = it->offs[it->seg + 1]; + } + } +} + +/* ---- the key as a per-value program ------------------------------------ + * The chunk DAG runs every operator of the key as a pass of its own over + * the chunk: a dispatch, a result vector and a barrier per operator — two + * dozen of them for a URL-host key, the `if` merges among them. When every + * operator is one whose STR-column semantics restate per value, the key is + * compiled instead into a straight-line program over three register kinds + * (a string view — bytes of the value itself or of a literal —, an I64, a + * BOOL) and run on the workers, a batch of values at a time (each + * instruction across the batch): no chunk-sized intermediate, and the + * result is a view of the value or a literal, hashed where it is computed. + * Each operator keeps the chunk DAG's semantics over STR: + * - the empty string is the null string: nil? is true, strlen is null; + * - str-find: the 0-based offset of the first match of the compiled + * search pattern (ray_strpat_find, as exec_str_find), else null; + * - substr: 1-based; a start below 1 counts from 1, a negative or overlong + * length runs to the end, a start past the end gives "", a null start + * or length gives "" (substr_view_fn); + * - + - * give null for a null operand and wrap otherwise; + * - I64 comparisons read null as INT64_MIN; strings compare by bytes; + * - within is (and (>= x lo) (<= x hi)) over a literal two-I64 range; + * - if/cond pick an arm. Both arms are computed, as the DAG computes + * them: every operator here is total and pure. + * Anything else — another operator, a symbol literal, a number that is + * not an I64, mixed kinds — returns -1 and the key stays with the DAG. */ +enum { DKP_STR = 0, DKP_I64, DKP_BOOL }; +enum { + DKO_COL, DKO_LSTR, DKO_LIT, + DKO_EQ, DKO_NE, DKO_LT, DKO_LE, DKO_GT, DKO_GE, DKO_SEQ, DKO_SNE, + DKO_ADD, DKO_SUB, DKO_MUL, DKO_AND, DKO_OR, DKO_NOT, + DKO_NILS, DKO_NILI, DKO_IF, DKO_FIND, DKO_SUBSTR, DKO_STRLEN, +}; +#define DKP_MAX_INS 128 +#define DKP_MAX_PATS 16 +#define DKP_MAX_LET 32 +typedef struct { + uint8_t op, kind; + uint16_t a, b, c; + int64_t imm; /* I64 / BOOL literal; pattern index of a FIND */ + const char* sp; /* STR literal bytes */ + uint32_t sl; +} dkp_ins_t; +typedef struct { + int n, col, npat, res, nex; + uint8_t ex[DKP_MAX_INS]; /* the non-literal instructions, in order */ + dkp_ins_t ins[DKP_MAX_INS]; + ray_strpat_t pat[DKP_MAX_PATS]; +} dkp_prog_t; +typedef struct { const char* p; int64_t v; } dkp_reg_t; /* STR: bytes, length */ + +static int dkp_emit(dkp_prog_t* P, int op, int kind, int a, int b, int c) { + if (P->n >= DKP_MAX_INS) return -1; + dkp_ins_t* x = &P->ins[P->n]; + memset(x, 0, sizeof(*x)); + x->op = (uint8_t)op; x->kind = (uint8_t)kind; + x->a = (uint16_t)a; x->b = (uint16_t)b; x->c = (uint16_t)c; + return P->n++; +} + +static int dkp_lit(dkp_prog_t* P, int kind, int64_t v) { + int r = dkp_emit(P, DKO_LIT, kind, 0, 0, 0); + if (r >= 0) P->ins[r].imm = v; + return r; +} + +static bool dkp_sym_is(ray_t* e, const char* name) { + if (!e || e->type != -RAY_SYM) return false; + ray_t* s = ray_sym_str(e->i64); + size_t n = strlen(name); + return s && ray_str_len(s) == n && memcmp(ray_str_ptr(s), name, n) == 0; +} + +/* Compile e; returns its register, or -1 when the program cannot hold it. + * bsym/breg are the let bindings in scope, innermost last (the DAG + * compiler's lookup order: let binding, then the column). */ +static int dkp_compile(dkp_prog_t* P, ray_t* e, int64_t col, int64_t* bsym, int* breg, int nb) { + if (!e) return -1; + #define DKP_K(r) (P->ins[(r)].kind) + switch (e->type) { + case -RAY_SYM: + if (e->attrs & ATTR_QUOTED) return -1; + for (int i = nb - 1; i >= 0; i--) if (bsym[i] == e->i64) return breg[i]; + if (e->i64 != col) return -1; + if (P->col < 0) P->col = dkp_emit(P, DKO_COL, DKP_STR, 0, 0, 0); + return P->col; + case -RAY_I64: return dkp_lit(P, DKP_I64, e->i64); + case -RAY_BOOL: return dkp_lit(P, DKP_BOOL, e->b8 ? 1 : 0); + case -RAY_STR: { + size_t l = ray_str_len(e); + if (l > UINT32_MAX) return -1; + int r = dkp_emit(P, DKO_LSTR, DKP_STR, 0, 0, 0); + if (r >= 0) { P->ins[r].sp = ray_str_ptr(e); P->ins[r].sl = (uint32_t)l; } + return r; + } + case RAY_LIST: break; + default: return -1; + } + int64_t n = ray_len(e); + if (n < 1) return -1; + ray_t** el = (ray_t**)ray_data(e); + ray_t* h = el[0]; + if (!h || h->type != -RAY_SYM || (h->attrs & ATTR_QUOTED)) return -1; + ray_t* hs = ray_sym_str(h->i64); + if (!hs) return -1; + const char* hp = ray_str_ptr(hs); + size_t hl = ray_str_len(hs); + #define DKP_IS(lit) (hl == sizeof(lit) - 1 && memcmp(hp, lit, hl) == 0) + #define DKP_ARG(i) dkp_compile(P, el[(i)], col, bsym, breg, nb) + + if (DKP_IS("let")) { + if (n != 4 || !el[1] || el[1]->type != -RAY_SYM || nb >= DKP_MAX_LET) return -1; + int v = DKP_ARG(2); + if (v < 0) return -1; + bsym[nb] = el[1]->i64; + breg[nb] = v; + 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 (DKP_IS("cond")) { + /* right to left into an if chain; the last clause is the else */ + int acc = -1; + for (int64_t i = n - 1; i >= 1; i--) { + ray_t* cl = el[i]; + if (!cl || cl->type != RAY_LIST || ray_len(cl) != 2) return -1; + ray_t** cp = (ray_t**)ray_data(cl); + if (dkp_sym_is(cp[0], "else")) { + if (i != n - 1) return -1; + acc = dkp_compile(P, cp[1], col, bsym, breg, nb); + if (acc < 0) return -1; + continue; + } + if (acc < 0) return -1; + int c = dkp_compile(P, cp[0], col, bsym, breg, nb); + int t = dkp_compile(P, cp[1], col, bsym, breg, nb); + 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("and") || DKP_IS("or")) { + if (n < 2 || n > 65) return -1; + int op = DKP_IS("and") ? DKO_AND : DKO_OR; + int acc = DKP_ARG(1); + if (acc < 0 || DKP_K(acc) != DKP_BOOL) return -1; + for (int64_t i = 2; i < n; i++) { + int r = DKP_ARG(i); + if (r < 0 || DKP_K(r) != DKP_BOOL) return -1; + acc = dkp_emit(P, op, DKP_BOOL, acc, r, 0); + if (acc < 0) return -1; + } + return acc; + } + if (DKP_IS("not")) { + if (n != 2) return -1; + int a = DKP_ARG(1); + if (a < 0 || DKP_K(a) != DKP_BOOL) return -1; + return dkp_emit(P, DKO_NOT, DKP_BOOL, a, 0, 0); + } + if (DKP_IS("nil?")) { + if (n != 2) return -1; + int a = DKP_ARG(1); + if (a < 0 || DKP_K(a) == DKP_BOOL) return -1; + return dkp_emit(P, DKP_K(a) == DKP_STR ? DKO_NILS : DKO_NILI, DKP_BOOL, a, 0, 0); + } + if (DKP_IS("strlen")) { + if (n != 2) return -1; + int a = DKP_ARG(1); + if (a < 0 || DKP_K(a) != DKP_STR) return -1; + return dkp_emit(P, DKO_STRLEN, DKP_I64, a, 0, 0); + } + if (DKP_IS("str-find")) { + if (n != 3 || !el[2] || el[2]->type != -RAY_STR || P->npat >= DKP_MAX_PATS) return -1; + int a = DKP_ARG(1); + if (a < 0 || DKP_K(a) != DKP_STR) return -1; + if (!ray_strpat_compile(ray_str_ptr(el[2]), ray_str_len(el[2]), &P->pat[P->npat])) return -1; + int r = dkp_emit(P, DKO_FIND, DKP_I64, a, 0, 0); + if (r >= 0) P->ins[r].imm = P->npat++; + return r; + } + if (DKP_IS("substr")) { + if (n != 4) return -1; + int a = DKP_ARG(1), b = DKP_ARG(2), c = DKP_ARG(3); + if (a < 0 || b < 0 || c < 0 || DKP_K(a) != DKP_STR || DKP_K(b) != DKP_I64 || + DKP_K(c) != DKP_I64) return -1; + return dkp_emit(P, DKO_SUBSTR, DKP_STR, a, b, c); + } + if (DKP_IS("within")) { + ray_t* rg = n == 3 ? el[2] : NULL; + if (!rg || !ray_is_vec(rg) || rg->type != RAY_I64 || rg->len != 2 || + (rg->attrs & RAY_ATTR_SLICE)) return -1; + int x = DKP_ARG(1); + if (x < 0 || DKP_K(x) != DKP_I64) return -1; + const int64_t* rv = (const int64_t*)ray_data(rg); + int lo = dkp_lit(P, DKP_I64, rv[0]); + int hi = dkp_lit(P, DKP_I64, rv[1]); + if (lo < 0 || hi < 0) return -1; + int ge = dkp_emit(P, DKO_GE, DKP_BOOL, x, lo, 0); + int le = dkp_emit(P, DKO_LE, DKP_BOOL, x, hi, 0); + if (ge < 0 || le < 0) return -1; + return dkp_emit(P, DKO_AND, DKP_BOOL, ge, le, 0); + } + int bop = DKP_IS("==") ? DKO_EQ : DKP_IS("!=") ? DKO_NE : DKP_IS("<") ? DKO_LT : + DKP_IS("<=") ? DKO_LE : DKP_IS(">") ? DKO_GT : DKP_IS(">=") ? DKO_GE : + DKP_IS("+") ? DKO_ADD : DKP_IS("-") ? DKO_SUB : DKP_IS("*") ? DKO_MUL : -1; + if (bop < 0 || n != 3) return -1; + int a = DKP_ARG(1), b = DKP_ARG(2); + if (a < 0 || b < 0 || DKP_K(a) != DKP_K(b)) return -1; + if (DKP_K(a) == DKP_STR) { + if (bop != DKO_EQ && bop != DKO_NE) return -1; + return dkp_emit(P, bop == DKO_EQ ? DKO_SEQ : DKO_SNE, DKP_BOOL, a, b, 0); + } + if (DKP_K(a) != DKP_I64) return -1; + return dkp_emit(P, bop, bop >= DKO_ADD ? DKP_I64 : DKP_BOOL, a, b, 0); + #undef DKP_ARG + #undef DKP_IS + #undef DKP_K +} + +/* The program of a key over the column col_sym whose result is a string, + * or false. */ +static bool dkp_build(dkp_prog_t* P, ray_t* by_expr, int64_t col_sym) { + memset(P, 0, sizeof(*P)); + P->col = -1; + int64_t bsym[DKP_MAX_LET]; + int breg[DKP_MAX_LET]; + int r = dkp_compile(P, by_expr, col_sym, bsym, breg, 0); + + P->res = r; + for (int k = 0; k < P->n; k++) + if (P->ins[k].op != DKO_LIT && P->ins[k].op != DKO_LSTR) P->ex[P->nex++] = (uint8_t)k; + return r >= 0 && P->ins[r].kind == DKP_STR; +} + +/* The first occurrence of a literal search pattern — what ray_strpat_find + * returns for a pattern without `?` or classes (memmem there) — found by + * memchr on its first byte: the values are short, and memmem's setup + * outweighs the scan over a URL-sized haystack. */ +static inline int64_t dkp_find_literal(const char* s, size_t sn, const char* nd, size_t nl) { + if (nl == 0) return 0; + if (nl > sn) return NULL_I64; + const char* hay = s; + size_t rem = sn; + while (rem >= nl) { + const char* hit = (const char*)memchr(hay, nd[0], rem - nl + 1); + if (!hit) return NULL_I64; + if (memcmp(hit + 1, nd + 1, nl - 1) == 0) return (int64_t)(hit - s); + rem -= (size_t)(hit - hay) + 1; + hay = hit + 1; + } + return NULL_I64; +} + +/* One batch of m (<= DKP_BATCH) values through the program: each + * instruction over the whole batch before the next one (register k of + * value t is R[k * DKP_BATCH + t]), so the dispatch is paid per batch, not + * per value. Literal registers were filled once by the caller. */ +#define DKP_BATCH 64 +static void dkp_run_batch(const dkp_prog_t* P, dkp_reg_t* R, const char* const* sp, + const uint32_t* sl, int m) { + for (int j = 0; j < P->nex; j++) { + int k = P->ex[j]; + const dkp_ins_t* x = &P->ins[k]; + dkp_reg_t* o = R + (size_t)k * DKP_BATCH; + const dkp_reg_t* a = R + (size_t)x->a * DKP_BATCH; + const dkp_reg_t* b = R + (size_t)x->b * DKP_BATCH; + const dkp_reg_t* c = R + (size_t)x->c * DKP_BATCH; + switch (x->op) { + case DKO_COL: + for (int t = 0; t < m; t++) { o[t].p = sp[t]; o[t].v = sl[t]; } + break; + case DKO_EQ: for (int t = 0; t < m; t++) o[t].v = a[t].v == b[t].v; break; + case DKO_NE: for (int t = 0; t < m; t++) o[t].v = a[t].v != b[t].v; break; + case DKO_LT: for (int t = 0; t < m; t++) o[t].v = a[t].v < b[t].v; break; + case DKO_LE: for (int t = 0; t < m; t++) o[t].v = a[t].v <= b[t].v; break; + case DKO_GT: for (int t = 0; t < m; t++) o[t].v = a[t].v > b[t].v; break; + case DKO_GE: for (int t = 0; t < m; t++) o[t].v = a[t].v >= b[t].v; break; + case DKO_SEQ: + case DKO_SNE: { + int64_t want = x->op == DKO_SEQ; + for (int t = 0; t < m; t++) { + bool eq = a[t].v == b[t].v && + (a[t].v == 0 || memcmp(a[t].p, b[t].p, (size_t)a[t].v) == 0); + o[t].v = eq ? want : !want; + } + break; + } + case DKO_ADD: + for (int t = 0; t < m; t++) + o[t].v = (a[t].v == NULL_I64 || b[t].v == NULL_I64) ? NULL_I64 + : (int64_t)((uint64_t)a[t].v + (uint64_t)b[t].v); + break; + case DKO_SUB: + for (int t = 0; t < m; t++) + o[t].v = (a[t].v == NULL_I64 || b[t].v == NULL_I64) ? NULL_I64 + : (int64_t)((uint64_t)a[t].v - (uint64_t)b[t].v); + break; + case DKO_MUL: + for (int t = 0; t < m; t++) + o[t].v = (a[t].v == NULL_I64 || b[t].v == NULL_I64) ? NULL_I64 + : (int64_t)((uint64_t)a[t].v * (uint64_t)b[t].v); + break; + case DKO_AND: for (int t = 0; t < m; t++) o[t].v = a[t].v & b[t].v; break; + case DKO_OR: for (int t = 0; t < m; t++) o[t].v = a[t].v | b[t].v; break; + case DKO_NOT: for (int t = 0; t < m; t++) o[t].v = !a[t].v; break; + case DKO_NILS: for (int t = 0; t < m; t++) o[t].v = a[t].v == 0; break; + case DKO_NILI: for (int t = 0; t < m; t++) o[t].v = a[t].v == NULL_I64; break; + case DKO_IF: for (int t = 0; t < m; t++) o[t] = a[t].v ? b[t] : c[t]; break; + case DKO_FIND: { + const ray_strpat_t* pt = &P->pat[x->imm]; + if (pt->literal) { + for (int t = 0; t < m; t++) + o[t].v = dkp_find_literal(a[t].p, (size_t)a[t].v, pt->pat, pt->pat_len); + } else { + for (int t = 0; t < m; t++) { + size_t pos = 0; + o[t].v = ray_strpat_find(pt, a[t].p, (size_t)a[t].v, &pos) ? (int64_t)pos : NULL_I64; + } + } + break; + } + case DKO_SUBSTR: + for (int t = 0; t < m; t++) { + int64_t st = b[t].v, ln = c[t].v, l = a[t].v; + o[t].p = a[t].p; o[t].v = 0; + if (st == NULL_I64 || ln == NULL_I64) continue; + st -= 1; + if (st < 0) st = 0; + if (st >= l) continue; + if (ln < 0 || ln > l - st) ln = l - st; + if (ln <= 0) continue; + o[t].p = a[t].p + st; + o[t].v = ln; + } + break; + case DKO_STRLEN: for (int t = 0; t < m; t++) o[t].v = a[t].v ? a[t].v : NULL_I64; break; + default: break; + } + } +} + +/* 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; + +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->sp[i + t] = p; + c->sl[i + t] = l; + c->hash[i + t] = (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) { + 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); + scratch_free(hdr); + return ok; +} + 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 || dom == ray_sym_runtime_domain() || du <= 0) return NULL; - ray_sym_domain_raw_t raw; - if (!ray_sym_domain_raw_pin(dom, &raw)) return NULL; + if (!dom || du <= 0) 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. */ @@ -3413,7 +4266,12 @@ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom ray_graph_t* gp = ray_graph_new(probe); if (gp) { ray_op_t* kop = compile_expr_dag(gp, by_expr); - if (kop) sym_out = kop->out_type; + /* 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); @@ -3425,10 +4283,30 @@ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom 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). */ + { + struct ray_sym_domain_s* kdom = ray_sym_domain_new(); + if (!kdom) { ray_release(key_dom); goto unpin_null; } + key_dom->sym_domain = kdom; /* the vector takes the ref */ + } + 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); 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; + } 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); @@ -3447,13 +4325,13 @@ static ray_t* derived_key_str_chunks(ray_t* by_expr, int64_t col_sym, ray_t* dom 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, kd + lo)) { ray_release(kc); goto fail; } + 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): take them cell by cell as runtime ids. */ - for (int64_t i = 0; i < n; i++) - kd[lo + i] = sym_cell_runtime_id(kc, i); + * 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; @@ -3570,6 +4448,8 @@ typedef struct { 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; @@ -3581,7 +4461,11 @@ static void dkv_len_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { 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->raw_ok && pos < c->raw.count) { + 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 { @@ -3594,34 +4478,75 @@ static void dkv_len_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { /* 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 rewrite's output order follows H, and a derived-key grouping - * on the row path comes out in the same order at every core count (the - * first-seen order of the key values, which follows the positions of the - * values they come from). Positions are distinct, so the order is the - * rank of each position among those present: a bitmap over the domain, - * block popcounts, then a scatter. Returns a new table, or NULL (H kept). */ + * 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 + * 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). */ +typedef struct { + const void* cd; + uint8_t attrs; + int64_t dom_count; + uint64_t* bits; + const int64_t* wrank; + const int64_t* hnd; + void* ncd; + uint8_t nattrs; + int64_t* nnd; + atomic_int bad; +} dkv_order_ctx_t; + +static void dkv_order_mark_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)wid; + dkv_order_ctx_t* c = (dkv_order_ctx_t*)vctx; + for (int64_t i = lo; i < hi; i++) { + int64_t pos = ray_read_sym(c->cd, i, RAY_SYM, c->attrs); + if (pos < 0 || pos >= c->dom_count) { + atomic_store_explicit(&c->bad, 1, memory_order_relaxed); + return; + } + atomic_fetch_or_explicit((_Atomic(uint64_t)*)&c->bits[pos >> 6], + (uint64_t)1 << (pos & 63), memory_order_relaxed); + } +} + +static void dkv_order_scatter_fn(void* vctx, uint32_t wid, int64_t lo, int64_t hi) { + (void)wid; + const dkv_order_ctx_t* c = (const dkv_order_ctx_t*)vctx; + for (int64_t i = lo; i < hi; i++) { + int64_t pos = ray_read_sym(c->cd, i, RAY_SYM, c->attrs); + int64_t w = pos >> 6; + int64_t r = c->wrank[w] + __builtin_popcountll(c->bits[w] & (((uint64_t)1 << (pos & 63)) - 1)); + ray_write_sym(c->ncd, r, (uint64_t)pos, RAY_SYM, c->nattrs); + c->nnd[r] = c->hnd[i]; + } +} + 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); int64_t du = ray_table_nrows(H); if (dom_count <= 0 || du <= 1) return NULL; int64_t nw = (dom_count + 63) / 64; - int64_t nb = (nw + 63) / 64; /* rank blocks of 64 words */ ray_t *bh = NULL, *rh = NULL; - uint64_t* bits = (uint64_t*)scratch_calloc(&bh, (size_t)nw * sizeof(uint64_t)); - int64_t* rank = (int64_t*)scratch_alloc(&rh, (size_t)(nb + 1) * sizeof(int64_t)); - if (!bits || !rank) { scratch_free(bh); scratch_free(rh); return NULL; } - const void* cd = ray_data(Hc); - for (int64_t i = 0; i < du; i++) { - int64_t pos = ray_read_sym(cd, i, RAY_SYM, Hc->attrs); - if (pos < 0 || pos >= dom_count) { scratch_free(bh); scratch_free(rh); return NULL; } - bits[pos >> 6] |= (uint64_t)1 << (pos & 63); - } + uint64_t* bits = (uint64_t*)scratch_calloc(&bh, (size_t)nw * sizeof(uint64_t)); + int64_t* wrank = (int64_t*)scratch_alloc(&rh, (size_t)nw * sizeof(int64_t)); + if (!bits || !wrank) { scratch_free(bh); scratch_free(rh); return NULL; } + dkv_order_ctx_t c; + memset(&c, 0, sizeof(c)); + c.cd = ray_data(Hc); c.attrs = Hc->attrs; c.dom_count = dom_count; + c.bits = bits; c.wrank = wrank; + atomic_store_explicit(&c.bad, 0, memory_order_relaxed); + ray_pool_t* pool = ray_pool_get(); + bool par = ray_pool_par_dispatch_ok(pool, du, RAY_PARALLEL_THRESHOLD); + if (par) ray_pool_dispatch(pool, dkv_order_mark_fn, &c, du); + else dkv_order_mark_fn(&c, 0, 0, du); + if (atomic_load_explicit(&c.bad, memory_order_relaxed)) { scratch_free(bh); scratch_free(rh); return NULL; } int64_t run = 0; - for (int64_t b = 0; b < nb; b++) { - rank[b] = run; - int64_t w1 = (b + 1) * 64 < nw ? (b + 1) * 64 : nw; - for (int64_t w = b * 64; w < w1; w++) run += __builtin_popcountll(bits[w]); + for (int64_t w = 0; w < nw; w++) { + wrank[w] = run; + run += __builtin_popcountll(bits[w]); } ray_t* nc = ray_sym_vec_new(Hc->attrs & RAY_SYM_W_MASK, du); ray_t* nn = ray_vec_new(RAY_I64, du); @@ -3633,18 +4558,12 @@ static ray_t* dkv_order_by_position(ray_t* H, int64_t dom_count) { } ray_sym_vec_adopt_domain(nc, Hc); nc->len = du; nn->len = du; - void* ncd = ray_data(nc); - int64_t* nnd = (int64_t*)ray_data(nn); - const int64_t* hnd = (const int64_t*)ray_data(Hn); - for (int64_t i = 0; i < du; i++) { - int64_t pos = ray_read_sym(cd, i, RAY_SYM, Hc->attrs); - int64_t w = pos >> 6; - int64_t r = rank[w >> 6]; - for (int64_t x = (w >> 6) * 64; x < w; x++) r += __builtin_popcountll(bits[x]); - r += __builtin_popcountll(bits[w] & (((uint64_t)1 << (pos & 63)) - 1)); - ray_write_sym(ncd, r, (uint64_t)pos, RAY_SYM, nc->attrs); - nnd[r] = hnd[i]; - } + c.ncd = ray_data(nc); + c.nattrs = nc->attrs; + c.nnd = (int64_t*)ray_data(nn); + c.hnd = (const int64_t*)ray_data(Hn); + if (par) ray_pool_dispatch(pool, dkv_order_scatter_fn, &c, du); + else dkv_order_scatter_fn(&c, 0, 0, du); if (Hc->attrs & RAY_ATTR_HAS_NULLS) nc->attrs |= RAY_ATTR_HAS_NULLS; scratch_free(bh); scratch_free(rh); ray_t* out = ray_table_new(2); @@ -3671,7 +4590,7 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex 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); - if (!dom || dom == ray_sym_runtime_domain()) return NULL; + if (!dom) return NULL; /* Every output is one of the decomposable aggregates over C; sort/take * clauses may only name output aliases. */ @@ -3741,6 +4660,7 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex } } + 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; } @@ -3762,6 +4682,11 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex .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)) @@ -3790,6 +4715,7 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex 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; @@ -3855,11 +4781,62 @@ static ray_t* derived_key_vocab_aggs(ray_t* tbl, ray_t* by_expr, ray_t* where_ex 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); + } + scratch_free(shdr); scratch_free(ihdr); + } agg_route_note_key_domain(); return O; } -static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { +/* `sel` (a rowsel over tbl, or NULL): only the rows it selects decide + * which distinct symbols are evaluated — the grouping that consumes the key + * honours the same selection, so a symbol that occurs in no selected row + * is never evaluated (nor its key interned). */ +static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl, ray_t* sel) { if (!by_expr || by_expr->type != RAY_LIST || !tbl) return NULL; int64_t ref_syms[2]; int nref = collect_col_refs(by_expr, tbl, ref_syms, 2, 0); @@ -3870,6 +4847,14 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { int64_t nrows = ray_table_nrows(tbl); if (!C || C->type != RAY_SYM || !ray_is_vec(C) || C->len != nrows || nrows < 4096) return NULL; + int64_t sel_rows = nrows; + if (sel) { + /* a rowsel block (ray_rowsel_new: an untyped block, its meta first) */ + ray_rowsel_t* sm = ray_rowsel_meta(sel); + if (!sm || sm->nrows != nrows) return NULL; + sel_rows = sm->total_pass; + if (sel_rows < 4096) return NULL; + } struct ray_sym_domain_s* dom = ray_sym_vec_domain(C); int64_t dn = dom ? ray_sym_domain_count(dom) : 0; /* The slot table is dn ints: refuse a domain far wider than the table @@ -3882,7 +4867,7 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { * A 128k-slot open-addressing set on scratch — no dn-sized memory. */ const void* cd = ray_data(C); { - const int64_t probe_rows = nrows < 65536 ? nrows : 65536; + const int64_t probe_rows = sel_rows < 65536 ? sel_rows : 65536; int64_t PROBE_SLOTS = 1024; /* power of two, load <= 1/2 */ while (PROBE_SLOTS < 2 * probe_rows) PROBE_SLOTS <<= 1; ray_t* set_hdr = NULL; @@ -3890,8 +4875,12 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { if (!set) return NULL; memset(set, 0xff, (size_t)PROBE_SLOTS * sizeof(int64_t)); int64_t seen = 0; + dk_sel_it_t pit; + dk_sel_it_init(&pit, sel, nrows); for (int64_t r = 0; r < probe_rows; r++) { - int64_t id = ray_read_sym(cd, r, C->type, C->attrs); + int64_t row = dk_sel_it_next(&pit); + if (row < 0) break; + int64_t id = ray_read_sym(cd, row, C->type, C->attrs); if (id < 0 || id >= dn) { seen = probe_rows; break; } uint64_t h = (((uint64_t)id * 0x9E3779B97F4A7C15ull) >> 32) & (uint64_t)(PROBE_SLOTS - 1); while (set[h] >= 0 && set[h] != id) h = (h + 1) & (uint64_t)(PROBE_SLOTS - 1); @@ -3912,13 +4901,17 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { ray_t* dom_vec = ray_sym_vec_new(ray_sym_dict_width(dn), dn); if (!dom_vec || RAY_IS_ERR(dom_vec)) { if (dom_vec) ray_error_free(dom_vec); scratch_free(pos_hdr); return NULL; } ray_sym_vec_adopt_domain(dom_vec, C); - int64_t du = 0, du_max = nrows / 2; + int64_t du = 0, du_max = sel_rows / 2; if (du_max > INT32_MAX) du_max = INT32_MAX; /* slots are int32 */ - /* Slots in first-seen row order: the interned key ids follow the slot - * order, and with them the order the groups come out in — the same - * order the row-wise evaluation gives. */ + /* Slots in first-seen row order (over the selected rows): the interned + * key ids follow the slot order, and with them the order the groups + * come out in — the same order the row-wise evaluation gives. */ bool ok = true; - for (int64_t r = 0; r < nrows; r++) { + dk_sel_it_t it; + dk_sel_it_init(&it, sel, nrows); + for (;;) { + int64_t r = dk_sel_it_next(&it); + if (r < 0) break; int64_t id = ray_read_sym(cd, r, C->type, C->attrs); if (id < 0 || id >= dn) { ok = false; break; } if (pos[id] < 0) { @@ -3933,6 +4926,7 @@ static ray_t* derived_key_over_sym_domain(ray_t* by_expr, ray_t* tbl) { dk_rows_ctx_t rc; memset(&rc, 0, sizeof(rc)); rc.cd = cd; rc.attrs = C->attrs; rc.dn = dn; + rc.sparse = sel != NULL; ray_pool_t* rpool = ray_pool_get(); bool rows_par = ray_pool_par_dispatch_ok(rpool, nrows, RAY_PARALLEL_THRESHOLD); @@ -4106,7 +5100,7 @@ static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, if (cell && !RAY_IS_ERR(cell) && ray_is_lazy(cell)) cell = ray_lazy_materialize(cell); if (cell && !RAY_IS_ERR(cell)) { int8_t t = cell->type; - if (t < 0 && t != -RAY_SYM && t != -RAY_STR && t != -RAY_GUID) vt = (int8_t)(-t); + if (t < 0 && t != -RAY_SYM && t != -RAY_STR) vt = (int8_t)(-t); ray_release(cell); } else if (cell) ray_error_free(cell); } @@ -4167,8 +5161,28 @@ static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, if (gi == 0) { int8_t t = cell->type; - int collapsable = (t < 0 && t != -RAY_SYM && t != -RAY_STR && t != -RAY_GUID); - if (collapsable) { + int collapsable = (t < 0); + if (collapsable && t == -RAY_STR) { + /* STR has no typed-store arm: collect through the string + * pool, appending one cell per row (len == rows so far). */ + result = ray_vec_new(RAY_STR, n_groups); + if (!result || RAY_IS_ERR(result)) { + g_active_query_table = _aqt; + ray_env_pop_scope(); ray_release(cell); + scratch_free(refs_hdr); + return result ? result : ray_error("oom", NULL); + } + const char* sp = ray_str_ptr(cell); + result = ray_str_vec_append(result, sp ? sp : "", sp ? ray_str_len(cell) : 0); + if (!result || RAY_IS_ERR(result)) { + g_active_query_table = _aqt; + ray_env_pop_scope(); ray_release(cell); + scratch_free(refs_hdr); + return result ? result : ray_error("oom", NULL); + } + direct_typed = 1; typed_t = t; + ray_release(cell); + } else if (collapsable) { int8_t vt = (int8_t)(-t); result = ray_vec_new(vt, n_groups); if (!result || RAY_IS_ERR(result)) { @@ -4204,7 +5218,23 @@ static ray_t* nonagg_eval_per_group_core(ray_t* expr, ray_t* tbl, } if (direct_typed) { - if (cell->type == typed_t && store_typed_elem(result, gi, cell) == 0) { + int stored = 0; + if (cell->type == typed_t) { + if (typed_t == -RAY_STR) { + const char* sp = ray_str_ptr(cell); + ray_t* nv = ray_str_vec_append(result, sp ? sp : "", sp ? ray_str_len(cell) : 0); + if (!nv || RAY_IS_ERR(nv)) { + g_active_query_table = _aqt; + ray_env_pop_scope(); ray_release(cell); + scratch_free(refs_hdr); + return nv ? nv : ray_error("oom", NULL); + } + result = nv; stored = 1; + } else { + stored = (store_typed_elem(result, gi, cell) == 0); + } + } + if (stored) { ray_release(cell); } else { /* Demote: convert typed vec [0..gi-1] to list, append cell, continue as list. */ @@ -4369,8 +5399,30 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { if (row == 0) { int8_t t = cell->type; - int collapsable = (t < 0 && t != -RAY_SYM && t != -RAY_STR && t != -RAY_GUID); - if (collapsable) { + int collapsable = (t < 0); + if (collapsable && t == -RAY_STR) { + /* STR has no typed-store arm: collect through the string + * pool, appending one cell per row (len == rows so far). */ + result = ray_vec_new(RAY_STR, nrows); + if (!result || RAY_IS_ERR(result)) { + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; + ray_env_pop_scope(); + ray_release(cell); + scratch_free(refs_hdr); + return result ? result : ray_error("oom", NULL); + } + const char* sp = ray_str_ptr(cell); + result = ray_str_vec_append(result, sp ? sp : "", sp ? ray_str_len(cell) : 0); + if (!result || RAY_IS_ERR(result)) { + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; + ray_env_pop_scope(); + ray_release(cell); + scratch_free(refs_hdr); + return result ? result : ray_error("oom", NULL); + } + direct_typed = 1; typed_t = t; + ray_release(cell); + } else if (collapsable) { result = ray_vec_new((int8_t)-t, nrows); if (!result || RAY_IS_ERR(result)) { g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; @@ -4407,7 +5459,24 @@ static ray_t* eval_expr_per_row(ray_t* expr, ray_t* tbl, int64_t nrows) { } if (direct_typed) { - if (cell->type == typed_t && store_typed_elem(result, row, cell) == 0) { + int stored = 0; + if (cell->type == typed_t) { + if (typed_t == -RAY_STR) { + const char* sp = ray_str_ptr(cell); + ray_t* nv = ray_str_vec_append(result, sp ? sp : "", sp ? ray_str_len(cell) : 0); + if (!nv || RAY_IS_ERR(nv)) { + g_active_query_table = _aqt; g_active_query_row = _aqr; g_active_query_row_tbl = _aqrt; g_active_query_row_depth = _aqrd; + ray_env_pop_scope(); + ray_release(cell); + scratch_free(refs_hdr); + return nv ? nv : ray_error("oom", NULL); + } + result = nv; stored = 1; + } else { + stored = (store_typed_elem(result, row, cell) == 0); + } + } + if (stored) { ray_release(cell); } else { ray_t* list_col = typed_vec_to_list(result, row, nrows); @@ -4486,7 +5555,7 @@ static ray_t* empty_agg_column(ray_t* fn_name, ray_t* src) { if (v && !RAY_IS_ERR(v) && ray_is_lazy(v)) v = ray_lazy_materialize(v); if (v && !RAY_IS_ERR(v)) { int8_t t = v->type; - if (t < 0 && t != -RAY_SYM && t != -RAY_STR && t != -RAY_GUID) out = ray_vec_new((int8_t)(-t), 0); + if (t < 0 && t != -RAY_SYM && t != -RAY_STR) out = ray_vec_new((int8_t)(-t), 0); ray_release(v); } else if (v) ray_error_free(v); ray_release(empty); @@ -4828,54 +5897,157 @@ static void cdpg_buf_par_fn(void* vctx, uint32_t worker_id, } #undef CDPG_BUF_INSERT -/* Parallel idx_buf construction from row_gid. Builds the - * groupwise inverted index used by per-group-slice consumers - * (count_distinct_per_group_buf, nonagg_eval_per_group_buf, etc.) +/* Per-group row slices (grp_cnt / offsets / idx_buf) from row_gid, for + * the per-group-slice consumers (count_distinct_per_group_buf, + * nonagg_eval_per_group_buf, ...). A row whose gid is negative belongs to + * no group; with a selection only the rows it keeps are visited. * - * Two passes: - * Pass 1 (cnt_fn): per-task histograms of row_gid → grp_cnt buckets - * (kept in task-local rows so no atomics needed). - * Pass 2 (scat_fn): per-task scatter into idx_buf using the cumulative - * per-(task,group) cursor pre-computed by the caller. - * - * On 5 M-row Q11 with 84 groups the serial loop was 8-10 ms; this - * parallel form takes ~0.5 ms at 28 workers and drops Q11/Q14-class - * queries by an order of magnitude when the per-group dedup is also - * parallelised. */ + * Tasks are contiguous runs of morsels, one per worker (fewer when the + * histograms would outgrow SLICE_HIST_CELLS), cut so each holds about the + * same number of visited rows. Pass 1 counts each task's rows per group + * into its own histogram row; a row-wise prefix turns the rows into + * cursors; pass 2 scatters. Tasks run in row order within a group, so the + * rows of a group come out ascending. The histograms are sized by the + * worker count, not the table: one row per 8192-row task had made them + * (and the prefix over them) grow with the table (#710). */ +#define SLICE_SERIAL_ROWS (1 << 17) /* fewer visited rows: one task */ +#define SLICE_HIST_CELLS (1 << 23) /* bound on n_tasks * n_groups */ + typedef struct { const int64_t* row_gid; - int64_t* hist; /* [n_tasks * n_groups] */ - int64_t* cursor; /* [n_tasks * n_groups] */ - int64_t* idx_buf; + int64_t nrows; int64_t n_groups; - int64_t grain; /* rows per task (for task_id derivation) */ -} idxbuf_par_ctx_t; + int64_t* hist; /* [n_tasks * n_groups]: counts, then cursors */ + int64_t* idx_buf; /* pass 2 only */ + const int64_t* seg_lo; /* [n_tasks + 1]: each task's morsels */ + const uint8_t* sel_flg; /* NULL: every row */ + const uint32_t* sel_offs; + const uint16_t* sel_idx; +} slice_build_ctx_t; + +static inline void slice_build_task(const slice_build_ctx_t* c, int64_t t, bool scatter) { + int64_t* h = c->hist + t * c->n_groups; + const int64_t* row_gid = c->row_gid; + int64_t* out = c->idx_buf; + for (int64_t seg = c->seg_lo[t]; seg < c->seg_lo[t + 1]; seg++) { + int64_t s_lo = seg * RAY_MORSEL_ELEMS; + uint8_t f = c->sel_flg ? c->sel_flg[seg] : RAY_SEL_ALL; + if (f == RAY_SEL_NONE) continue; + if (f == RAY_SEL_ALL) { + int64_t s_hi = s_lo + RAY_MORSEL_ELEMS; + if (s_hi > c->nrows) s_hi = c->nrows; + for (int64_t r = s_lo; r < s_hi; r++) { + int64_t gi = row_gid[r]; + if (gi < 0) continue; + if (scatter) out[h[gi]++] = r; + else h[gi]++; + } + continue; + } + for (uint32_t i = c->sel_offs[seg]; i < c->sel_offs[seg + 1]; i++) { + int64_t r = s_lo + c->sel_idx[i]; + int64_t gi = row_gid[r]; + if (gi < 0) continue; + if (scatter) out[h[gi]++] = r; + else h[gi]++; + } + } +} -static void idxbuf_hist_fn(void* vctx, uint32_t worker_id, - int64_t start, int64_t end) { +static void slice_count_fn(void* vctx, uint32_t worker_id, int64_t t0, int64_t t1) { (void)worker_id; - idxbuf_par_ctx_t* ctx = (idxbuf_par_ctx_t*)vctx; - int64_t task_id = start / ctx->grain; - int64_t* hist = ctx->hist + task_id * ctx->n_groups; - const int64_t* row_gid = ctx->row_gid; - for (int64_t r = start; r < end; r++) { - int64_t gi = row_gid[r]; - if (gi >= 0) hist[gi]++; - } + for (int64_t t = t0; t < t1; t++) slice_build_task((const slice_build_ctx_t*)vctx, t, false); } -static void idxbuf_scat_fn(void* vctx, uint32_t worker_id, - int64_t start, int64_t end) { +static void slice_scatter_fn(void* vctx, uint32_t worker_id, int64_t t0, int64_t t1) { (void)worker_id; - idxbuf_par_ctx_t* ctx = (idxbuf_par_ctx_t*)vctx; - int64_t task_id = start / ctx->grain; - int64_t* cur = ctx->cursor + task_id * ctx->n_groups; - const int64_t* row_gid = ctx->row_gid; - int64_t* idx_buf = ctx->idx_buf; - for (int64_t r = start; r < end; r++) { - int64_t gi = row_gid[r]; - if (gi >= 0) idx_buf[cur[gi]++] = r; + for (int64_t t = t0; t < t1; t++) slice_build_task((const slice_build_ctx_t*)vctx, t, true); +} + +/* Build the slices into grp_cnt / offsets (caller's [n_groups] arrays) and + * *idx_hdr, using pos[n_groups] as scratch. sel may be NULL. Returns + * false on allocation failure. */ +static bool slice_build(const int64_t* row_gid, int64_t nrows, ray_t* sel, + int64_t n_groups, int64_t* grp_cnt, int64_t* offsets, + int64_t* pos, ray_t** idx_hdr) { + *idx_hdr = NULL; + int64_t n_segs = (nrows + RAY_MORSEL_ELEMS - 1) / RAY_MORSEL_ELEMS; + slice_build_ctx_t c = { .row_gid = row_gid, .nrows = nrows, .n_groups = n_groups }; + int64_t visited = nrows; + if (sel) { + ray_rowsel_t* sm = ray_rowsel_meta(sel); + if ((int64_t)sm->n_segs < n_segs) n_segs = sm->n_segs; + c.sel_flg = ray_rowsel_flags(sel); + c.sel_offs = ray_rowsel_offsets(sel); + c.sel_idx = ray_rowsel_idx(sel); + visited = sm->total_pass; + } + ray_pool_t* pool = ray_pool_get(); + int64_t n_tasks = 1; + if (pool && visited >= SLICE_SERIAL_ROWS && n_groups > 0 && + ray_pool_par_dispatch_ok(pool, visited, SLICE_SERIAL_ROWS)) { + n_tasks = ray_pool_total_workers(pool); + if (n_tasks * n_groups > SLICE_HIST_CELLS) n_tasks = SLICE_HIST_CELLS / n_groups; + if (n_tasks > n_segs) n_tasks = n_segs; + if (n_tasks < 2) n_tasks = 1; + } + ray_t* hist_hdr = NULL; + ray_t* seg_hdr = NULL; + int64_t* hist = (int64_t*)scratch_calloc(&hist_hdr, + (size_t)n_tasks * (size_t)(n_groups > 0 ? n_groups : 1) * sizeof(int64_t)); + int64_t* seg_lo = (int64_t*)scratch_alloc(&seg_hdr, (size_t)(n_tasks + 1) * sizeof(int64_t)); + if (!hist || !seg_lo) { + if (hist_hdr) scratch_free(hist_hdr); + if (seg_hdr) scratch_free(seg_hdr); + return false; + } + /* cut the morsels into n_tasks runs of about visited / n_tasks rows */ + seg_lo[0] = 0; + if (n_tasks > 1 && c.sel_flg) { + int64_t t = 1, acc = 0; + for (int64_t seg = 0; seg < n_segs && t < n_tasks; seg++) { + uint8_t f = c.sel_flg[seg]; + if (f == RAY_SEL_ALL) { + int64_t s_hi = (seg + 1) * RAY_MORSEL_ELEMS; + acc += (s_hi > nrows ? nrows : s_hi) - seg * RAY_MORSEL_ELEMS; + } else if (f != RAY_SEL_NONE) { + acc += c.sel_offs[seg + 1] - c.sel_offs[seg]; + } + while (t < n_tasks && acc * n_tasks >= visited * t) seg_lo[t++] = seg + 1; + } + while (t < n_tasks) seg_lo[t++] = n_segs; + } else { + for (int64_t t = 1; t < n_tasks; t++) seg_lo[t] = n_segs * t / n_tasks; + } + seg_lo[n_tasks] = n_segs; + c.hist = hist; + c.seg_lo = seg_lo; + + if (n_tasks > 1) ray_pool_dispatch_n(pool, slice_count_fn, &c, (uint32_t)n_tasks); + else slice_count_fn(&c, 0, 0, 1); + + /* row-wise prefix: totals per group, offsets, then each task's cursor */ + memset(grp_cnt, 0, (size_t)n_groups * sizeof(int64_t)); + for (int64_t t = 0; t < n_tasks; t++) { + const int64_t* h = hist + t * n_groups; + for (int64_t gi = 0; gi < n_groups; gi++) grp_cnt[gi] += h[gi]; } + int64_t total = 0; + for (int64_t gi = 0; gi < n_groups; gi++) { offsets[gi] = total; total += grp_cnt[gi]; } + if (n_groups > 0) memcpy(pos, offsets, (size_t)n_groups * sizeof(int64_t)); + for (int64_t t = 0; t < n_tasks; t++) { + int64_t* h = hist + t * n_groups; + for (int64_t gi = 0; gi < n_groups; gi++) { int64_t k = h[gi]; h[gi] = pos[gi]; pos[gi] += k; } + } + + *idx_hdr = ray_alloc((size_t)(total > 0 ? total : 1) * sizeof(int64_t)); + if (!*idx_hdr) { scratch_free(hist_hdr); scratch_free(seg_hdr); return false; } + c.idx_buf = (int64_t*)ray_data(*idx_hdr); + if (n_tasks > 1) ray_pool_dispatch_n(pool, slice_scatter_fn, &c, (uint32_t)n_tasks); + else slice_scatter_fn(&c, 0, 0, 1); + scratch_free(hist_hdr); + scratch_free(seg_hdr); + return true; } static ray_t* query_materialize_parted_col(ray_t* col) { @@ -6496,7 +7668,26 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ return 0; } + /* 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; + } + int64_t rhs = count_atom_i64(rhs_expr); + if (rhs_ns) { + /* Days or milliseconds to nanoseconds, saturating: a date beyond + * the TIMESTAMP range still compares past every cell. */ + int64_t unit = rhs_expr->type == -RAY_DATE ? 86400000000000LL : 1000000LL; + if (__builtin_mul_overflow((int64_t)rhs_expr->i32, unit, &rhs)) + rhs = rhs_expr->i32 < 0 ? INT64_MIN + 1 : INT64_MAX; + } /* SYM cells are positions in the COLUMN's domain; the literal atom * carries a runtime id — re-express it (sym-domain Phase 2; no-op * for runtime-domain columns). Absent ⇒ -1: never equals any cell @@ -6532,6 +7723,17 @@ static int try_count_simple_compare(ray_t* tbl, ray_t* where_expr, int64_t* out_ return 1; } +/* A where: value that is not already a BOOL mask of `tn` rows goes through + * the one where: rule (ray_where_mask_coerce): a scalar (`false`, + * `(== (count x) 5)`) is spread over the rows, any other vector (a numeric + * or symbol column) is a type error. Consumes + * `m`. */ +static ray_t* where_mask_spread(ray_t* m, int64_t tn, const char* label) { + if (!m || RAY_IS_ERR(m)) return m; + if (m->type == RAY_BOOL && m->len == tn) return m; + return ray_where_mask_coerce(m, tn, label); +} + 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; @@ -6607,6 +7809,12 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { return ray_error("oom", NULL); } ray_op_t* pred = compile_expr_dag(g, where_expr); + if (!pred && g->compile_err) { + ray_t* cerr = graph_take_compile_err(g); + ray_graph_free(g); + ray_release(tbl); + return cerr; + } if (!pred) { ray_t* pred_vec = eval_where_mask(where_expr, tbl, "select count"); if (!pred_vec || RAY_IS_ERR(pred_vec)) { @@ -6676,6 +7884,12 @@ ray_t* ray_try_count_select_expr(ray_t* expr, int* handled) { return pred_vec ? pred_vec : ray_error("type", "select count: WHERE predicate evaluation failed"); } int64_t tbl_nrows = ray_table_nrows(tbl); + pred_vec = where_mask_spread(pred_vec, tbl_nrows, "select count"); + if (!pred_vec || RAY_IS_ERR(pred_vec)) { + ray_graph_free(g); + ray_release(tbl); + return pred_vec ? pred_vec : ray_error("oom", NULL); + } if (pred_vec->type != RAY_BOOL || pred_vec->len != tbl_nrows) { int8_t pred_t = pred_vec->type; /* capture BEFORE free */ ray_release(pred_vec); @@ -7121,6 +8335,30 @@ static ray_t* select_fallback_bind_alias(ray_t* tbl, int64_t kid, ray_t* col) { return ray_table_add_col(tbl, kid, col); } +/* The one value an aggregate-only projection produced, as a column of n + * rows. An atom is broadcast; a one-element vector (the interpreter's + * shape for some scalar results, like exec.c's for `(+ (sum x) 0)`) is + * widened the way OP_SELECT widens it. Any other vector is the + * projection's own column and passes through unchanged, so a row-long + * global or a lambda call that returns a row-aligned result keeps its + * length. Consumes `v`. */ +static ray_t* select_fallback_broadcast(ray_t* v, int64_t n) { + if (!v || RAY_IS_ERR(v)) return v; + if (ray_is_atom(v)) { + ray_t* out = atom_broadcast_vec(v, n); + if (!out) out = ray_error("type", "select: cannot broadcast a %s value to a column", + ray_type_name(v->type)); + ray_release(v); + return out; + } + if (v->type <= 0 || !ray_is_vec(v) || v->len != 1 || n == 1) return v; + ray_t* n_obj = make_i64(n); + ray_t* wide = n_obj ? ray_take_fn(v, n_obj) : ray_error("oom", NULL); + if (n_obj) ray_release(n_obj); + ray_release(v); + return wide; +} + static bool select_alias_skip_form(ray_t* head) { if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; ray_t* s = ray_sym_str(head->i64); @@ -7132,6 +8370,57 @@ static bool select_alias_skip_form(ray_t* head) { (l == 5 && memcmp(p, "quote", 5) == 0); } +/* expr_contains_agg for the eval fallback's one-value rule: an aggregate + * inside a lambda, let or quote form does not count. A lambda call is a + * per-row projection on the fallback (`((fn [c] (sum c)) 'ts)` sums one + * cell per row, parted_f64_agg.rfl) and its body folds its own formal, + * not a column, so it is neither evaluated once nor pre-reduced. */ +static int select_fallback_has_agg(ray_t* expr) { + if (!expr || expr->type != RAY_LIST) return 0; + int64_t n = ray_len(expr); + if (n == 0) return 0; + ray_t** el = (ray_t**)ray_data(expr); + if (select_alias_skip_form(el[0])) return 0; + if (is_agg_expr(expr)) return 1; + for (int64_t i = 0; i < n; i++) + if (select_fallback_has_agg(el[i])) return 1; + return 0; +} + +/* 1 when the leaves of `expr` are atom literals and the names in `scalars`, + * the earlier outputs already known to be one value; `*via` is set when a + * name was among them. A column, a global, a vector literal or a lambda, + * let or quote form may carry rows, and answers 0. */ +static int select_fallback_scalar_leaves(ray_t* expr, const int64_t* scalars, + int64_t ns, int* via) { + if (!expr) return 0; + if (ray_is_atom(expr)) { + if (expr->type != -RAY_SYM || (expr->attrs & ATTR_QUOTED)) return 1; + for (int64_t i = 0; i < ns; i++) + if (scalars[i] == expr->i64) { *via = 1; return 1; } + return 0; + } + if (expr->type != RAY_LIST) return 0; + int64_t n = ray_len(expr); + if (n == 0) return 0; + ray_t** el = (ray_t**)ray_data(expr); + if (el[0]->type != -RAY_SYM || select_alias_skip_form(el[0])) return 0; + for (int64_t i = 1; i < n; i++) + if (!select_fallback_scalar_leaves(el[i], scalars, ns, via)) return 0; + return 1; +} + +/* 1 when `expr`, an output with no aggregate in it, is one value for the + * whole select: an atom literal, or an expression over earlier one-value + * outputs (`y: (+ m 1)` after `m: (max i)`). A call over literals alone + * (`(til 8)`) may build a column of the input's length and stays a row + * projection. */ +static int select_fallback_scalar_proj(ray_t* expr, const int64_t* scalars, int64_t ns) { + int via = 0; + return select_fallback_scalar_leaves(expr, scalars, ns, &via) && + (via || ray_is_atom(expr)); +} + static bool select_alias_head_is_agg(ray_t* head) { if (!head || head->type != -RAY_SYM || (head->attrs & ATTR_QUOTED)) return false; if (resolve_agg_opcode(head->i64) != 0) return true; @@ -7289,8 +8578,66 @@ static ray_t* select_alias_map_list(ray_t* expr, int64_t from, select_alias_map_ ray_release(e2); } } - if (!out) { ray_retain(expr); return expr; } - return out; + if (!out) { ray_retain(expr); return expr; } + return out; +} + +/* ── Eval-fallback pre-reduction of aggregates ──────────────────────────── + * A projection that mixes a row column with an aggregate in one expression + * (`(+ i (max i))`, `(if (> i (avg i)) 1 0)`) is scattered per row by the + * eval fallback, where every column is bound to one cell: the aggregate + * then folds that cell alone and `(max i)` reads as `i`. Before the + * scatter, every maximal aggregate call in the expression is evaluated once + * over the whole table (eval_expr_whole_column, earlier outputs already + * bound as columns) and its value spliced into a rewritten copy of the + * expression, so the per-row pass combines each row with the value the DAG + * path would have broadcast. A value the evaluator would not take as + * itself — a symbol (a name, or a literal the active-query rule maps to a + * column) or a list (a call) — is wrapped in `(quote …)`; a one-element + * vector is the scalar it stands for, as select_fallback_broadcast reads + * it. Lambda, let and quote forms are left alone: a lambda's body folds + * its own formal per row, not a column. The user's AST is never mutated + * (select_alias_map_list copies a list only once a child changes). + * Returns an owned expression, or an error. */ +typedef struct { ray_t* tbl; } select_fallback_prereduce_ctx_t; + +static ray_t* select_fallback_prereduce(ray_t* expr, void* vctx) { + select_fallback_prereduce_ctx_t* c = (select_fallback_prereduce_ctx_t*)vctx; + if (!expr || expr->type != RAY_LIST || expr->len < 1) { ray_retain(expr); return expr; } + ray_t** el = (ray_t**)ray_data(expr); + if (select_alias_skip_form(el[0])) { ray_retain(expr); return expr; } + if (!is_agg_expr(expr)) + return select_alias_map_list(expr, el[0]->type == RAY_LIST ? 0 : 1, + select_fallback_prereduce, c); + ray_t* v = eval_expr_whole_column(expr, c->tbl); + if (!v || RAY_IS_ERR(v)) return v ? v : ray_error("oom", NULL); + if (v->type > 0 && v->type != RAY_LIST && ray_is_vec(v) && v->len == 1) { + int allocated = 0; + ray_t* a = collection_elem(v, 0, &allocated); + if (a && !RAY_IS_ERR(a) && !allocated) ray_retain(a); + ray_release(v); + if (!a || RAY_IS_ERR(a)) return a ? a : ray_error("oom", NULL); + v = a; + } + if (v->type == -RAY_SYM) { + /* a literal copy (ray_quote_fn's shape): no name resolution, and + * collect_col_refs does not take it for a column of the same name */ + ray_t* q = ray_sym(v->i64); + ray_release(v); + if (!q || RAY_IS_ERR(q)) return q ? q : ray_error("oom", NULL); + q->attrs |= ATTR_QUOTED; + v = q; + } else if (v->type != RAY_LIST) { + return v; + } + ray_t* head = ray_sym(ray_sym_intern("quote", 5)); + ray_t* wrap = head && !RAY_IS_ERR(head) ? ray_list_new(2) : NULL; + if (wrap && !RAY_IS_ERR(wrap)) wrap = ray_list_append(wrap, head); + if (wrap && !RAY_IS_ERR(wrap)) wrap = ray_list_append(wrap, v); + if (head && !RAY_IS_ERR(head)) ray_release(head); + ray_release(v); + if (!wrap || RAY_IS_ERR(wrap)) return wrap ? wrap : ray_error("oom", NULL); + return wrap; } typedef struct { @@ -7667,6 +9014,110 @@ ray_t* ray_select(ray_t** args, int64_t n) { return ray_select_impl(args, n, false); } +/* The hidden name a bare computed by: key is grouped under (#707). */ +#define SELECT_COMPUTED_KEY "__by_key" + +/* A bare computed by: key (`by: (% v 3)`) groups on the DAG path only beside + * plain aggregates. Any other output (a `distinct` aggregate, a row + * expression) would send it to the eval-level grouping, which is slower + * (10-20% at 10M rows); the by-dict form `{k: (% v 3)}` materializes the key + * once and keeps the DAG path's speed for every output shape. So + * that is the query this plans: the same dict with by: as a one-key by-dict + * under a hidden name, from: the table already evaluated, and a sort key + * naming the derived key column redirected to the hidden one. The caller + * renames the hidden column to `*key_name`, the name the DAG path gives a + * computed key. NULL when the shape needs no rewrite. */ +static ray_t* select_plan_computed_key(ray_t* dict, ray_t* tbl, int64_t* key_name) { + ray_t* by_expr = dict_get(dict, "by"); + if (!by_expr || by_expr->type != RAY_LIST || ray_len(by_expr) < 1) 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])); + int64_t nd = ray_dict_len(dict); + int64_t hidden = ray_sym_intern(SELECT_COMPUTED_KEY, strlen(SELECT_COMPUTED_KEY)); + int64_t kname = derived_key_name(by_expr); + bool needs_eval = false; + 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++) if (kid == rid[r]) clause = true; + if (clause) continue; + if (kid == kname) kname = ray_sym_intern("key", 3); + ray_t* v = ((ray_t**)ray_data(vals))[i]; + /* the routing's own test for an output the DAG group cannot serve */ + if (is_single_group_key_projection(by_expr, v)) continue; + if (is_group_dag_agg_expr(v)) continue; + if (is_decomposable_agg_compound(v, tbl)) continue; + needs_eval = true; + } + if (!needs_eval || ray_table_get_col(tbl, hidden)) return NULL; + + ray_t* bk = ray_vec_new(RAY_SYM, 1); + ray_t* bv = ray_list_new(1); + if (bk && !RAY_IS_ERR(bk)) { ((int64_t*)ray_data(bk))[0] = hidden; bk->len = 1; } + if (bv && !RAY_IS_ERR(bv)) bv = ray_list_append(bv, by_expr); + ray_t* by_dict = ray_dict_new(bk, bv); + if (!by_dict || RAY_IS_ERR(by_dict)) return by_dict ? by_dict : ray_error("oom", NULL); + + ray_t* engine = dict; + ray_retain(engine); + ray_t* k_by = ray_sym(rid[2]); + engine = k_by && !RAY_IS_ERR(k_by) ? ray_dict_upsert(engine, k_by, by_dict) : engine; + if (k_by) ray_release(k_by); + ray_release(by_dict); + ray_t* k_from = ray_sym(rid[0]); + if (engine && !RAY_IS_ERR(engine) && k_from && !RAY_IS_ERR(k_from)) + engine = ray_dict_upsert(engine, k_from, tbl); + if (k_from) ray_release(k_from); + /* asc:/desc: name result columns: the derived key is the hidden one */ + for (int r = 4; r <= 5 && engine && !RAY_IS_ERR(engine); r++) { + ray_t* sv = dict_get(engine, reserved[r]); + ray_t* nv = NULL; + if (sv && sv->type == -RAY_SYM && sv->i64 == kname) { + nv = ray_sym(hidden); + if (nv && !RAY_IS_ERR(nv)) nv->attrs = sv->attrs; + } else if (sv && sv->type == RAY_SYM) { + int64_t n = ray_len(sv); + bool hit = false; + for (int64_t j = 0; j < n; j++) if (sym_cell_runtime_id(sv, j) == kname) hit = true; + if (hit) { + nv = ray_vec_new(RAY_SYM, n); + if (nv && !RAY_IS_ERR(nv)) { + for (int64_t j = 0; j < n; j++) { + int64_t id = sym_cell_runtime_id(sv, j); + ((int64_t*)ray_data(nv))[j] = id == kname ? hidden : id; + } + nv->len = n; + } + } + } + if (!nv) continue; + if (RAY_IS_ERR(nv)) { ray_release(engine); return nv; } + ray_t* k_s = ray_sym(rid[r]); + if (!k_s || RAY_IS_ERR(k_s)) { ray_release(nv); ray_release(engine); return k_s ? k_s : ray_error("oom", NULL); } + engine = ray_dict_upsert(engine, k_s, nv); + ray_release(k_s); + ray_release(nv); + } + if (!engine || RAY_IS_ERR(engine)) return engine ? engine : ray_error("oom", NULL); + *key_name = kname; + return engine; +} + +/* 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); + if (!r || RAY_IS_ERR(r) || r->type != RAY_TABLE) return r; + int64_t hidden = ray_sym_intern(SELECT_COMPUTED_KEY, strlen(SELECT_COMPUTED_KEY)); + int64_t nc = ray_table_ncols(r); + for (int64_t c = 0; c < nc; c++) + if (ray_table_col_name(r, c) == hidden) { ray_table_set_col_name(r, c, key_name); break; } + return r; +} + static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (n < 1) return ray_error("arity", "select: expects a query dict, got %lld args", (long long)n); ray_t* dict = args[0]; @@ -7719,6 +9170,13 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { if (emit_filter_set) ray_group_emit_filter_set(prev_emit_filter); if (RAY_IS_ERR(tbl)) return tbl; + if (tbl->type == RAY_DICT) { + bool complete; + ray_t* scan = ray_parquet_select_source(tbl,dict,&complete); + if (scan) { ray_release(tbl); tbl = scan; } + if (complete) return tbl; + if (RAY_IS_ERR(tbl)) return tbl; + } 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)); } if (!aliases_resolved) { @@ -7735,6 +9193,18 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } + { + int64_t key_name = -1; + 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_release(engine); + ray_release(tbl); + return select_name_computed_key(r, key_name); + } + } + ray_t* temporal_result = try_temporal_group_materialize(dict, tbl); if (temporal_result) { ray_release(tbl); return temporal_result; } @@ -8528,58 +9998,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { sv_data[i] = k->i64; continue; } - /* Exact-size carve: collect_col_refs dedups against real table - * columns, so ray_table_ncols(tbl) is a hard upper bound — no - * silent truncation past the former [16] cap. Scoped to this - * loop iteration only (tbl may gain a column each pass via - * ray_table_add_col below), freed before every exit. */ - int64_t ncols_max = ray_table_ncols(tbl); - if (ncols_max < 1) ncols_max = 1; - ray_t* refs_hdr = NULL; - int64_t* ref_syms = (int64_t*)scratch_alloc(&refs_hdr, - (size_t)ncols_max * (sizeof(int64_t) + sizeof(ray_t*))); - if (!ref_syms) { - fail_err = ray_error("oom", NULL); - failed = true; break; - } - ray_t** materialized_refs = (ray_t**)(ref_syms + ncols_max); - int n_refs = collect_col_refs(v, tbl, ref_syms, (int)ncols_max, 0); - for (int ri = 0; ri < n_refs; ri++) materialized_refs[ri] = NULL; - for (int ri = 0; ri < n_refs; ri++) { - ray_t* ref_col = ray_table_get_col(tbl, ref_syms[ri]); - if (ref_col && (RAY_IS_PARTED(ref_col->type) || - ref_col->type == RAY_MAPCOMMON)) { - ray_t* flat = query_materialize_parted_col(ref_col); - if (!flat || RAY_IS_ERR(flat)) { - fail_err = flat ? flat : ray_error("oom", NULL); - failed = true; break; - } - materialized_refs[ri] = flat; - ray_env_set_query_local(ref_syms[ri], flat); - } - } - if (failed) { - 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); - ray_release(materialized_refs[ri]); - } - } - scratch_free(refs_hdr); - break; - } - ray_t* col_vec = ray_eval(v); - if (ray_is_lazy(col_vec)) - col_vec = ray_lazy_materialize(col_vec); - 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); - ray_release(materialized_refs[ri]); - } - } - scratch_free(refs_hdr); + ray_t* col_vec = group_key_eval(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; @@ -10026,8 +11445,70 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result; } - /* eval_group path supports only simple scalar / [col] by-forms; - * computed keys shouldn't land here. */ + /* A computed key (`by: (% v 3)`) or a literal one lands here when + * an output is not a plain aggregate (a `distinct` aggregate, a + * row expression). Evaluate it over the selected rows, as a + * by-dict value is evaluated, into a hidden column and + * group on that; the source columns stay as they are for the + * 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) { + 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); + ray_env_pop_scope(); + } + if (kv && !RAY_IS_ERR(kv) && ray_is_atom(kv)) { + ray_t* wide = atom_broadcast_vec(kv, kn); + ray_release(kv); + kv = wide ? wide : ray_error("type", "by: cannot broadcast the key"); + } + if (kv && !RAY_IS_ERR(kv) && (!ray_is_vec(kv) || ray_len(kv) != kn)) { + int64_t got = ray_len(kv); + ray_release(kv); + kv = ray_error("length", "by: key has %lld rows, the table %lld", + (long long)got, (long long)kn); + } + if (!kv || RAY_IS_ERR(kv)) { + if (eval_tbl != tbl) ray_release(eval_tbl); + ray_release(tbl); + 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)) { + ray_release(kv); + if (eval_tbl != tbl) ray_release(eval_tbl); + ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return ray_error("domain", "by: the input has a column named __by_key"); + } + ray_retain(eval_tbl); /* add_col consumes it: copy, never edit the input */ + ray_t* keyed = ray_table_add_col(eval_tbl, by_key_sym, kv); + ray_release(kv); + if (eval_tbl != tbl) ray_release(eval_tbl); + if (!keyed || RAY_IS_ERR(keyed)) { + ray_release(tbl); + 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) { + 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 (kid == key_out_name) { key_out_name = ray_sym_intern("key", 3); break; } + } + } + /* eval_group path supports only scalar / [col] by-forms and the + * computed key materialized above. */ if (by_key_sym < 0) { if (eval_tbl != tbl) ray_release(eval_tbl); ray_release(tbl); @@ -10577,7 +12058,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { 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 key_vec ? key_vec : ray_error("oom", NULL); } - result = ray_table_add_col(result, by_key_sym, key_vec); + result = ray_table_add_col(result, key_out_name, key_vec); ray_release(key_vec); } @@ -10816,6 +12297,20 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { table_is_parted = 0; } + /* A single key expression whose every aggregate reads the one SYM + * column it derives from is decided over that column's distinct + * values (derived_key_vocab_aggs), which applies the WHERE itself: + * try it before the filter below runs over every row for nothing. */ + if (!parted_bydict_deferred && by_expr->type == RAY_LIST) { + ray_t* vres = derived_key_vocab_aggs(tbl, by_expr, where_expr, dict_elems, dict_n, + from_id, by_id, where_id, take_id, + asc_id, desc_id, nearest_id); + if (vres) { + ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); + return vres; + } + } + /* WHERE + BY handling. Two paths: * * (A) Fused path — applicable when there are no non-agg @@ -10957,19 +12452,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } else { /* Single key expression. Over a lone SYM column evaluate it per * distinct symbol and feed the spread key as a constant node, - * named the way the eval-level path names a computed key. When - * every aggregate reads that column too, the whole grouping is - * decided over the distinct values (derived_key_vocab_aggs). */ - { - ray_t* vres = derived_key_vocab_aggs(tbl, by_expr, where_expr, dict_elems, dict_n, - from_id, by_id, where_id, take_id, - asc_id, desc_id, nearest_id); - if (vres) { - ray_graph_free(g); ray_release(tbl); scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); - return vres; - } - } - ray_t* dom_key = derived_key_over_sym_domain(by_expr, tbl); + * 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) { key_ops[0] = ray_const_vec(g, dom_key); ray_release(dom_key); @@ -11387,7 +12873,7 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { ray_t* cv = ray_table_get_col_idx(filtered_tbl, c); ray_env_set_query_local(cn, cv); } - ray_t* computed_key = derived_key_over_sym_domain(by_expr, filtered_tbl); + ray_t* computed_key = derived_key_over_sym_domain(by_expr, filtered_tbl, NULL); if (!computed_key) computed_key = ray_eval(by_expr); ray_env_pop_scope(); if (!computed_key || RAY_IS_ERR(computed_key)) { @@ -12045,7 +13531,17 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { } } if (use_eval_fallback) { - if (g->compile_err) { ray_release(g->compile_err); g->compile_err = NULL; } + /* A projection the compiler rejected outright is an error, + * not a fallback: scattered per row, (> ts (avg ts)) would + * average one cell and compare it with itself. */ + if (g->compile_err) { + ray_t* cerr = graph_take_compile_err(g); + if (nearest_handle_owned) ray_release(nearest_handle_owned); + if (nearest_query_owned) ray_free_raw(nearest_query_owned); + ray_graph_free(g); ray_release(tbl); + scratch_free(colops_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return cerr; + } /* The fallback evaluates projections directly over `tbl`, * bypassing the DAG's ray_execute — so a WHERE clause (wired * into `root` as ray_filter) would be silently ignored. @@ -12075,6 +13571,31 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } } + /* The per-row reader has no arm for segmented columns, so a + * projection over a .db.parted.get table raised `type` here. + * Flatten a parted / mapcommon table once, as update does, so + * every projection below sees plain vectors. */ + if (table_has_parted_columns(tbl)) { + ray_t* flat = query_materialize_parted_table(tbl); + if (!flat || RAY_IS_ERR(flat)) { + if (nearest_handle_owned) ray_release(nearest_handle_owned); + if (nearest_query_owned) ray_free_raw(nearest_query_owned); + ray_graph_free(g); ray_release(tbl); + scratch_free(colops_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return flat ? flat : ray_error("oom", NULL); + } + ray_release(tbl); + tbl = flat; + ray_graph_free(g); + g = ray_graph_new(tbl); + if (!g) { + if (nearest_handle_owned) ray_release(nearest_handle_owned); + if (nearest_query_owned) ray_free_raw(nearest_query_owned); + ray_release(tbl); + scratch_free(colops_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); + } + } ray_t* result = ray_table_new(0); if (!result || RAY_IS_ERR(result)) { if (nearest_handle_owned) ray_release(nearest_handle_owned); @@ -12084,6 +13605,48 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return result ? result : ray_error("oom", NULL); } int64_t nrows = ray_table_nrows(tbl); + /* A projection with an aggregate in it and no column ref + * outside the aggregate's argument (expr_contains_agg && + * !expr_refs_row_column) is one value for the whole select. + * Scattered per row it saw a one-cell slice + * of every column, so `(max i)` beside a projection the DAG + * declines came back as `i` itself (#692). Such a + * projection is evaluated once over the whole table and the + * value broadcast as the DAG path broadcasts it (exec.c + * OP_SELECT): to nrows beside a projection that flows a row + * column through, and to one row when no projection does + * (case (a) above: an all-aggregate select is one row). + * A literal, or an expression over earlier one-value + * outputs, carries no rows either (#698); a select of + * literals alone keeps the input's rows. */ + int any_row_proj = 0, any_agg = 0; + ray_t* scal_hdr = NULL; + int64_t* scalars = (int64_t*)scratch_alloc(&scal_hdr, + (size_t)(dict_n / 2 + 1) * sizeof(int64_t)); + if (!scalars) { + ray_release(result); + if (nearest_handle_owned) ray_release(nearest_handle_owned); + if (nearest_query_owned) ray_free_raw(nearest_query_owned); + ray_graph_free(g); ray_release(tbl); + scratch_free(colops_hdr); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); + } + int64_t n_scalars = 0; + for (int64_t i = 0; i + 1 < dict_n && !any_row_proj; 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* e = dict_elems[i + 1]; + int has_agg = select_fallback_has_agg(e); + any_agg |= has_agg; + any_row_proj = has_agg ? expr_refs_row_column(e, tbl) + : !select_fallback_scalar_proj(e, scalars, n_scalars); + if (!any_row_proj) scalars[n_scalars++] = kid; + } + scratch_free(scal_hdr); + if (!any_agg) any_row_proj = 1; + int64_t bcast_len = any_row_proj ? nrows : 1; int64_t out_len = -1; /* length of the first materialized column */ for (int64_t i = 0; i + 1 < dict_n; i += 2) { int64_t kid = dict_elems[i]->i64; @@ -12092,10 +13655,52 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { kid == nearest_id) continue; /* Whole-column verbs (distinct/asc/desc/reverse) consume the * entire column and must be evaluated once, not scattered - * per-row; everything else keeps the row-by-row semantics. */ - ray_t* col = is_whole_column_projection(dict_elems[i + 1]) - ? eval_expr_whole_column(dict_elems[i + 1], tbl) - : eval_expr_per_row(dict_elems[i + 1], tbl, nrows); + * per-row; so must a one-value projection (an aggregate, + * alone or under scalar arithmetic / a scalar `if`), whose + * value is then broadcast. Everything else — literals, + * lambda calls, and a row column mixed with an aggregate + * in one expression — keeps the row-by-row semantics. + * With no row projection at all nothing is scattered: an + * 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); + int one_value = !whole_verb && + (!any_row_proj || + (select_fallback_has_agg(expr) && !expr_refs_row_column(expr, tbl))); + /* A row column mixed with an aggregate in one + * expression: its aggregates are reduced once over + * the whole table before the scatter, which would + * otherwise fold a single cell (`(+ i (max i))` came + * back as `(* 2 i)`; select_fallback_prereduce). */ + ray_t* reduced = NULL; + if (!whole_verb && !one_value && select_fallback_has_agg(expr)) { + select_fallback_prereduce_ctx_t pc = { tbl }; + reduced = select_fallback_prereduce(expr, &pc); + if (reduced && !RAY_IS_ERR(reduced)) expr = reduced; + } + ray_t* col; + if (reduced && RAY_IS_ERR(reduced)) { + col = reduced; + } else { + col = select_fallback_passthrough_col(expr, tbl, nrows); + if (!col) { + /* An expression over earlier one-value outputs + * with no aggregate of its own reads them at + * row 0, as the row path reads a cell: they are + * bound as one-row columns, and over the whole + * column `(til m)` saw `[6]`, not 6 (#698). */ + int at_row0 = one_value && !whole_verb && + !ray_is_atom(expr) && + !select_fallback_has_agg(expr); + col = at_row0 ? eval_expr_per_row(expr, tbl, 1) + : (whole_verb || one_value) + ? eval_expr_whole_column(expr, tbl) + : eval_expr_per_row(expr, tbl, nrows); + if (one_value) col = select_fallback_broadcast(col, bcast_len); + } + if (reduced) ray_release(reduced); + } if (!col || RAY_IS_ERR(col)) { ray_t* err = col ? col : ray_error("domain", "select: failed to evaluate output column expression"); ray_release(result); @@ -12124,8 +13729,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * the remaining expressions are evaluated over, in place * of a source column of the same name. A column of * another length (`distinct`) cannot be a row of that - * table and stays unbound. */ - if (col_len == nrows) { + * table and stays unbound. In an all-aggregate select + * the one-row value is what a later projection reads + * (`{m: (max ts) y: (+ m 1)}`), and nothing scatters it. */ + if (col_len == bcast_len) { ray_t* bound = select_fallback_bind_alias(tbl, kid, col); if (!bound || RAY_IS_ERR(bound)) { ray_release(col); @@ -12232,9 +13839,11 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { * HINT, which the v2 radix engine uses to emit only N groups instead of * materializing all of them. The hint is advisory: HEAD still trims and * apply_sort_take still runs at the end, so correctness never depends on - * it. NOT pushed with a group-by: negative (tail) and range takes, which - * both need the full group set; and any asc:/desc: shape, which reorders - * the groups first (that shape also owns the desc+take emit-filter + * it. A range take [start amount] with start >= 0 pushes start+amount the + * same way (apply_sort_take then slices the range out of those groups). + * NOT pushed with a group-by: negative (tail) takes and ranges counted + * from the end, which need the full group set; and any asc:/desc: shape, + * which reorders the groups first (that shape also owns the desc+take emit-filter * 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 @@ -12282,6 +13891,10 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { else { const int32_t* r32 = (const int32_t*)rv; take_pre.a = r32[0]; take_pre.b = r32[1]; } ray_release(tv); + /* [start amount] from the front reads only the first + * start+amount groups: push that bound like an atom take. */ + if (take_pre.a >= 0 && take_pre.b > 0 && take_pre.a <= INT64_MAX - take_pre.b) + root = ray_head(g, root, take_pre.a + take_pre.b); } else take_range = tv; /* apply after DAG execution */ } else { int8_t tv_t = tv->type; /* capture BEFORE free */ @@ -13153,107 +14766,16 @@ static ray_t* ray_select_impl(ray_t** args, int64_t n, bool aliases_resolved) { int64_t* idx_buf = NULL; ray_t* idx_hdr = NULL; if (needs_slice_idx) { - /* Parallel histogram + scatter when the row count is - * large enough to amortise dispatch overhead. For - * 5 M-row Q11 the serial loop was 8-10 ms; the - * parallel path drops it to ~0.5 ms at 28 workers. */ - ray_pool_t* idx_pool = ray_pool_get(); - int64_t total = 0; - int parallel_idx_done = 0; - if (idx_pool && nrows >= 200000 && - ray_pool_total_workers(idx_pool) >= 2 && - n_groups > 0 && n_groups <= 65536) - { - int64_t grain = (int64_t)RAY_DISPATCH_MORSELS * - RAY_MORSEL_ELEMS; - int64_t n_tasks = (nrows + grain - 1) / grain; - if (n_tasks > 65536) { - n_tasks = 65536; - grain = (nrows + n_tasks - 1) / n_tasks; - } - ray_t* hist_hdr = NULL; - ray_t* cur_hdr = NULL; - int64_t* hist = (int64_t*)scratch_calloc(&hist_hdr, - (size_t)n_tasks * (size_t)n_groups * - sizeof(int64_t)); - int64_t* cur = (int64_t*)scratch_alloc(&cur_hdr, - (size_t)n_tasks * (size_t)n_groups * - sizeof(int64_t)); - if (hist && cur) { - idxbuf_par_ctx_t pctx = { - .row_gid = row_gid, - .hist = hist, - .cursor = cur, - .idx_buf = NULL, - .n_groups = n_groups, - .grain = grain, - }; - ray_pool_dispatch(idx_pool, idxbuf_hist_fn, - &pctx, nrows); - - /* Prefix: per-group total + per-task cursor. */ - for (int64_t gi = 0; gi < n_groups; gi++) { - int64_t cum = total; - for (int64_t t = 0; t < n_tasks; t++) { - int64_t c = hist[t * n_groups + gi]; - cur[t * n_groups + gi] = cum; - cum += c; - } - grp_cnt[gi] = cum - total; - offsets[gi] = total; - total = cum; - } - - idx_hdr = ray_alloc((size_t)total * - sizeof(int64_t)); - if (!idx_hdr) { - scratch_free(hist_hdr); scratch_free(cur_hdr); - ray_free(gk_hdr); ray_free(rg_hdr); - ray_free(cnt_hdr); ray_free(off_hdr); - ray_free(pos_hdr); - RELEASE_SCAN_KEY(); - ray_release(result); ray_release(tbl); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); - } - idx_buf = (int64_t*)ray_data(idx_hdr); - pctx.idx_buf = idx_buf; - ray_pool_dispatch(idx_pool, idxbuf_scat_fn, - &pctx, nrows); - parallel_idx_done = 1; - } - if (hist_hdr) scratch_free(hist_hdr); - if (cur_hdr) scratch_free(cur_hdr); - } - - if (!parallel_idx_done) { - memset(grp_cnt, 0, (size_t)n_groups * sizeof(int64_t)); - for (int64_t r = 0; r < nrows; r++) - if (row_gid[r] >= 0) grp_cnt[row_gid[r]]++; - - total = 0; - for (int64_t gi = 0; gi < n_groups; gi++) - total += grp_cnt[gi]; - idx_hdr = ray_alloc((size_t)total * sizeof(int64_t)); - if (!idx_hdr) { - ray_free(gk_hdr); ray_free(rg_hdr); ray_free(cnt_hdr); - ray_free(off_hdr); ray_free(pos_hdr); - RELEASE_SCAN_KEY(); - ray_release(result); ray_release(tbl); - scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); - } - idx_buf = (int64_t*)ray_data(idx_hdr); - - offsets[0] = 0; - for (int64_t gi = 1; gi < n_groups; gi++) - offsets[gi] = offsets[gi - 1] + grp_cnt[gi - 1]; - - memcpy(pos, offsets, - (size_t)n_groups * sizeof(int64_t)); - for (int64_t r = 0; r < nrows; r++) { - int64_t gi = row_gid[r]; - if (gi >= 0) idx_buf[pos[gi]++] = r; - } + if (!slice_build(row_gid, nrows, saved_selection, n_groups, + grp_cnt, offsets, pos, &idx_hdr)) { + ray_free(gk_hdr); ray_free(rg_hdr); + ray_free(cnt_hdr); ray_free(off_hdr); + ray_free(pos_hdr); + RELEASE_SCAN_KEY(); + ray_release(result); ray_release(tbl); + scratch_free(sel_slots_hdr); DICT_VIEW_CLOSE(dv); return ray_error("oom", NULL); } + idx_buf = (int64_t*)ray_data(idx_hdr); } ray_t* scatter_err = NULL; @@ -13598,7 +15120,9 @@ static void xbar_par_fn(void* vctx, uint32_t worker_id, int64_t a = in[i]; int64_t q = a / b; if ((a ^ b) < 0 && q * b != a) q--; - o[i] = q * b; + /* Unsigned wrap: only the null sentinel (INT64_MIN) rounds + * below INT64_MIN, and the caller rewrites it as null. */ + o[i] = (int64_t)((uint64_t)q * (uint64_t)b); } } } else if (c->out_type == RAY_I32 || c->out_type == RAY_DATE || @@ -14007,16 +15531,21 @@ static int update_where_index_rows(ray_t* tbl, ray_t* where_expr, /* Legacy-shaped mask evaluation (DAG, then eval with column bindings). */ static ray_t* update_where_mask_vec(ray_t* tbl, ray_t* where_expr) { ray_t* mask_vec = NULL; + bool rejected = false; ray_graph_t* g = ray_graph_new(tbl); if (g) { ray_op_t* pred = compile_expr_dag(g, where_expr); if (pred) { pred = ray_optimize(g, pred); mask_vec = ray_execute(g, pred); + } else if (g->compile_err) { + /* rejected outright, not declined: no interpreter retry */ + mask_vec = graph_take_compile_err(g); + rejected = true; } ray_graph_free(g); } - if (!mask_vec || RAY_IS_ERR(mask_vec)) { + if (!rejected && (!mask_vec || RAY_IS_ERR(mask_vec))) { int64_t ncols = ray_table_ncols(tbl); ray_env_push_query_scope(); for (int64_t c = 0; c < ncols; c++) @@ -14026,6 +15555,8 @@ static ray_t* update_where_mask_vec(ray_t* tbl, ray_t* where_expr) { } if (!mask_vec) return ray_error("type", "update: `where:` predicate evaluation failed"); if (RAY_IS_ERR(mask_vec)) return mask_vec; + mask_vec = where_mask_spread(mask_vec, ray_table_nrows(tbl), "update"); + if (!mask_vec || RAY_IS_ERR(mask_vec)) return mask_vec ? mask_vec : ray_error("oom", NULL); if (mask_vec->type != RAY_BOOL || mask_vec->len != ray_table_nrows(tbl)) { int8_t mask_t = mask_vec->type; ray_release(mask_vec); @@ -14034,30 +15565,204 @@ static ray_t* update_where_mask_vec(ray_t* tbl, ray_t* where_expr) { return mask_vec; } +/* A scalar computed as a one-element vector rather than an atom, such as + * `(+ (sum x) 0)` or an `if` whose parts are all scalar, becomes that atom + * when the column has another length, so the atom broadcast below applies + * to it. Left as a vector it replaced the column with one row. */ +static ray_t* update_scalar_vec(ray_t* v, int64_t nrows) { + if (!v || RAY_IS_ERR(v) || v->type <= 0 || v->type == RAY_LIST || + !ray_is_vec(v) || v->len != 1 || nrows == 1) + return v; + int alloc = 0; + ray_t* a = collection_elem(v, 0, &alloc); + if (!a || RAY_IS_ERR(a)) return v; + if (!alloc) ray_retain(a); + ray_release(v); + return a; +} + +/* The cell an atom writes into a column of type ct (esz bytes wide). GUID + * keeps its 16 bytes in ->obj, an I64 atom into F64 is converted, and an + * F32 atom holds its value widened in ->f64, so copying ->i64 wrote the + * low half of a double: zeros for most values. */ +static void update_atom_cell(const ray_t* a, int8_t ct, size_t esz, uint8_t elem[16]) { + memset(elem, 0, 16); + if (ct == RAY_GUID) { + if (a->obj) memcpy(elem, ray_data(a->obj), 16); + } else if (ct == RAY_F64 && a->type == -RAY_I64) { + double p = (double)a->i64; memcpy(elem, &p, sizeof p); + } else if (ct == RAY_F32 && (a->type == -RAY_F32 || a->type == -RAY_F64)) { + float f = (float)a->f64; memcpy(elem, &f, sizeof f); + } else { + memcpy(elem, &a->i64, esz); + } +} + +/* One cell of an update-by result. A STR cell goes through the string + * pool: store_typed_elem has no STR arm and left the cell empty, so a + * string per group came out as "". Returns the column, or an error. */ +/* Rank of a numeric column type for update by:'s promotion of a group + * result of another type; 0 for a non-numeric type. */ +static int update_by_num_rank(int8_t t) { + switch (t) { + case RAY_BOOL: return 1; + case RAY_U8: return 2; + case RAY_I16: return 3; + case RAY_I32: return 4; + case RAY_I64: return 5; + case RAY_F32: return 6; + case RAY_F64: return 7; + default: return 0; + } +} + +/* A copy of the numeric column `col` as type `to` (every row converted + * through store_typed_elem, nulls carried). Owned. */ +static ray_t* update_by_promote(ray_t* col, int8_t to) { + int64_t n = ray_len(col); + ray_t* nc = ray_vec_new(to, n); + if (!nc || RAY_IS_ERR(nc)) return nc ? nc : ray_error("oom", NULL); + nc->len = n; + for (int64_t r = 0; r < n; r++) { + int alloc = 0; + ray_t* cell = collection_elem(col, r, &alloc); + if (!cell || RAY_IS_ERR(cell)) { ray_release(nc); return cell ? cell : ray_error("oom", NULL); } + store_typed_elem(nc, r, cell); + if (alloc) ray_release(cell); + } + return nc; +} + +static ray_t* update_by_store(ray_t* col, int64_t row, ray_t* cell) { + if (col->type == RAY_STR) { + const char* sp = ""; + size_t sl = 0; + if (cell->type == -RAY_STR && !RAY_ATOM_IS_NULL(cell)) { + sp = ray_str_ptr(cell); + sl = ray_str_len(cell); + } + return ray_str_vec_set(col, row, sp, sl); + } + store_typed_elem(col, row, cell); + return col; +} + +/* True iff `expr` reads a column of `tbl` anywhere in its subtree — unlike + * expr_refs_row_column it looks inside aggregates too. */ +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; + 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; + } + return 0; + } + if (expr->type == RAY_LIST) { + ray_t** elems = (ray_t**)ray_data(expr); + int64_t n = ray_len(expr); + for (int64_t i = 1; i < n; i++) + if (expr_refs_any_column(elems[i], tbl)) return 1; + } + return 0; +} + +/* True iff `expr` contains an aggregate over a column of `tbl`: the one + * shape a per-row pass cannot evaluate, since the aggregate would see one + * cell. An aggregate over a global or a literal is the same value on + * every row and is fine per row. */ +static int expr_contains_agg_over_column(ray_t* expr, ray_t* tbl) { + if (!expr || expr->type != RAY_LIST) return 0; + if (is_agg_expr(expr)) return expr_refs_any_column(expr, tbl); + ray_t** elems = (ray_t**)ray_data(expr); + int64_t n = ray_len(expr); + for (int64_t i = 0; i < n; i++) + if (expr_contains_agg_over_column(elems[i], tbl)) return 1; + return 0; +} + +/* Whether a DAG error must stand rather than hand the expression to the + * interpreter: only when an `if` refused its operands (g->if_refused). The + * interpreter's `if` tests one truth value, so retrying there wrote the + * then-branch to every matched row. Other DAG failures, such as an + * operation the DAG does not take, keep the fallback. */ +static bool update_dag_err_final(ray_t* out, bool if_refused) { + return if_refused && out && RAY_IS_ERR(out); +} + +/* Evaluate an update expression over `sub`: the DAG first, then the + * interpreter. The interpreter pass binds whole columns and evaluates once + * — its vector builtins are elementwise, and aggregates and whole-column + * verbs need the whole column — except for an `if` that reads a column in + * row position (expr_refs_row_column): the interpreter's `if` tests ONE + * truth value, so a whole-column pass wrote the then-branch to every row; + * that goes per row — unless it also aggregates, which per row would see + * one cell: that is an error (#692). When both paths fail, the planner's error (a misspelt + * column: `schema: column 'x' not found`) wins over the interpreter's less + * specific one. Owned; a one-element vector is its atom. */ static ray_t* update_eval_on(ray_t* sub, ray_t* expr) { ray_t* out = NULL; + ray_t* cerr = NULL; + bool if_refused = false; ray_graph_t* g = ray_graph_new(sub); if (g) { ray_op_t* op = compile_expr_dag(g, expr); if (op) { op = ray_optimize(g, op); out = ray_execute(g, op); + } else { + cerr = graph_take_compile_err(g); } + if_refused = g->if_refused; ray_graph_free(g); } + if (update_dag_err_final(out, if_refused)) { + if (cerr) ray_error_free(cerr); + return out; + } if (!out || RAY_IS_ERR(out)) { - if (out) ray_error_free(out); - int64_t ncols = ray_table_ncols(sub); - ray_env_push_query_scope(); - for (int64_t c = 0; c < ncols; c++) - ray_env_set_query_local(ray_table_col_name(sub, c), ray_table_get_col_idx(sub, c)); - out = ray_eval(expr); - ray_env_pop_scope(); + /* Keep the planner's error — from compile, or from executing what + * it compiled (a scan of a misspelt column: `schema: column 'x' + * not found`) — to report if the interpreter fails as well. */ + if (out) { if (cerr) ray_error_free(cerr); cerr = out; out = NULL; } + int64_t nrows = ray_table_nrows(sub); + /* The interpreter's vector builtins are elementwise over whole + * columns, and whole-column verbs (.idx.hash, distinct, ...) and + * aggregates need the whole column; only `if` is not — it tests one + * truth value — so an `if` over a column goes per row. */ + int per_row = expr_contains_call_named(expr, "if", 2) && expr_refs_row_column(expr, sub); + if (per_row && expr_contains_agg_over_column(expr, sub)) { + /* Per row, an aggregate over a column sees one cell: + * `(if (> i (avg i)) ..)` would compare each row with itself. + * Keep this an error until the fallback can reduce aggregates + * first (#692). (An aggregate over a global or a literal is the + * same value on every row and goes through.) */ + if (cerr) ray_error_free(cerr); + return ray_error("nyi", "update: an if over a column that also aggregates is not supported without the planner"); + } + if (!per_row) { + int64_t ncols = ray_table_ncols(sub); + ray_env_push_query_scope(); + for (int64_t c = 0; c < ncols; c++) + ray_env_set_query_local(ray_table_col_name(sub, c), ray_table_get_col_idx(sub, c)); + out = ray_eval(expr); + ray_env_pop_scope(); + } else { + out = eval_expr_per_row(expr, sub, nrows); + } + if ((!out || RAY_IS_ERR(out)) && cerr) { + if (out) ray_error_free(out); + return cerr; + } } + if (cerr) ray_error_free(cerr); /* error objects bypass the refcount */ if (!out) return ray_error("type", "update: failed to evaluate column update expression"); if (RAY_IS_ERR(out)) return out; if (ray_is_lazy(out)) out = ray_lazy_materialize(out); - return out; + return update_scalar_vec(out, ray_table_nrows(sub)); } static bool update_numeric_promo(int8_t ct, int8_t et) { @@ -14133,15 +15838,9 @@ static ray_t* update_scatter(ray_t** slots, int64_t c, const int64_t* rows, int6 uint8_t* d = (uint8_t*)ray_data(col); if (val->type < 0) { /* Atom broadcast: one encoded cell, written k times. */ - uint8_t elem[16] = {0}; + uint8_t elem[16]; bool is_null = RAY_ATOM_IS_NULL(val); - if (ct == RAY_GUID) { - if (val->obj) memcpy(elem, ray_data(val->obj), 16); - } else if (ct == RAY_F64 && val->type == -RAY_I64) { - double p = (double)val->i64; memcpy(elem, &p, sizeof p); - } else { - memcpy(elem, &val->i64, esz); - } + update_atom_cell(val, ct, esz, elem); for (int64_t i = 0; i < k; i++) { if (is_null) ray_vec_set_null(col, rows[i], true); else { @@ -14235,7 +15934,18 @@ static ray_t* update_where_inplace(ray_t* tbl, int64_t inplace_sym, ray_t* dict, break; } } - if (!rowwise) { + /* A dict entry naming no column adds one; that is the general path's + * job (this one writes existing columns in place and dropped it). */ + bool adds_col = false; + for (int64_t d = 0; d + 1 < updf_n && !adds_col; d += 2) { + int64_t kid = updf[d]->i64; + if (kid == from_id || kid == where_id || kid == by_id) continue; + bool found = false; + for (int64_t i = 0; i < nu; i++) + if (ray_table_col_name(tbl, ucol[i]) == kid) { found = true; break; } + if (!found) adds_col = true; + } + if (!rowwise || adds_col) { scratch_free(ucol_hdr); scratch_free(uexpr_hdr); scratch_free(uval_hdr); DICT_VIEW_CLOSE(updf); return NULL; @@ -14521,21 +16231,27 @@ ray_t* ray_update(ray_t** args, int64_t n) { * so preserve it when any gathered row is null. */ if (copied_null) sub_col->attrs |= RAY_ATTR_HAS_NULLS; + /* STR descriptors of pooled strings point into the + * source's pool: share it, or every string past the + * inline size reads as "" inside the group. */ + if (ct == RAY_STR) + col_propagate_str_pool(sub_col, full_col); sub_tbl = ray_table_add_col(sub_tbl, cn, sub_col); ray_release(sub_col); 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; } } - /* Evaluate expression on sub-table via DAG */ - ray_graph_t* ug = ray_graph_new(sub_tbl); - ray_op_t* expr_op = compile_expr_dag(ug, agg_expr); - if (!expr_op) { ray_t* cerr = graph_take_compile_err(ug); ray_graph_free(ug); ray_release(sub_tbl); ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return cerr ? cerr : ray_error("domain", "update by: failed to compile aggregate expression"); } - expr_op = ray_optimize(ug, expr_op); - ray_t* agg_result = ray_execute(ug, expr_op); - ray_graph_free(ug); + /* Evaluate expression on the sub-table: DAG first, then the + * eval-level fallback with the group's columns bound (an + * aggregate the DAG declines, e.g. over temporal + - *, + * used to fail here with "failed to compile"). */ + ray_t* agg_result = update_eval_on(sub_tbl, agg_expr); ray_release(sub_tbl); if (RAY_IS_ERR(agg_result)) { ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return agg_result; } + /* A one-element result is the group's scalar, broadcast like + * an atom; it failed the length check on groups of 2+ rows. */ + agg_result = update_scalar_vec(agg_result, gsize); /* Determine output type from first group */ if (first_group) { @@ -14557,15 +16273,41 @@ ray_t* ray_update(ray_t** args, int64_t n) { * shape — a vector whose length is neither 1 nor the group * size — has no row-aligned meaning, so decline loudly rather * than leave the memset zeros in place (silent data loss). */ + /* A group result of another type than the column was cast + * into it silently (2.5 stored as 2, a TIMESTAMP as a TIME). + * Promote the column to the wider numeric type; reject any + * other mismatch loudly. */ + { + int8_t rt = ray_is_atom(agg_result) ? (int8_t)-agg_result->type : agg_result->type; + if (rt != out_type && rt > 0) { + int rr = update_by_num_rank(rt), orr = update_by_num_rank(out_type); + if (!rr || !orr) { + ray_release(agg_result); ray_release(out_col); + UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); + return ray_error("type", "update by: group result type %s does not match %s", ray_type_name(rt), ray_type_name(out_type)); + } + if (rr > orr) { + ray_t* promoted = update_by_promote(out_col, rt); + if (RAY_IS_ERR(promoted)) { ray_release(agg_result); ray_release(out_col); UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); return promoted; } + ray_release(out_col); + out_col = promoted; + out_type = rt; + } + } + } int64_t* idxs = (int64_t*)ray_data(idx_vec); + ray_t* store_err = NULL; if (ray_is_atom(agg_result)) { - for (int64_t r = 0; r < gsize; r++) - store_typed_elem(out_col, idxs[r], agg_result); + for (int64_t r = 0; r < gsize && !store_err; r++) { + ray_t* nc = update_by_store(out_col, idxs[r], agg_result); + if (RAY_IS_ERR(nc)) store_err = nc; else out_col = nc; + } } else if (ray_is_vec(agg_result) && ray_len(agg_result) == gsize) { - for (int64_t r = 0; r < gsize; r++) { + for (int64_t r = 0; r < gsize && !store_err; r++) { int alloc = 0; ray_t* cell = collection_elem(agg_result, r, &alloc); - store_typed_elem(out_col, idxs[r], cell); + ray_t* nc = update_by_store(out_col, idxs[r], cell); + if (RAY_IS_ERR(nc)) store_err = nc; else out_col = nc; if (alloc) ray_release(cell); } } else { @@ -14575,6 +16317,11 @@ ray_t* ray_update(ray_t** args, int64_t n) { return ray_error("length", "update by: expression result length %lld does not match group size %lld", (long long)got, (long long)gsize); } ray_release(agg_result); + if (store_err) { + ray_release(out_col); + UPDATE_BY_CLEANUP_COLS(); ray_release(groups); ray_release(tbl); DICT_VIEW_CLOSE(updv); + return store_err; + } } upd_names[upd_i] = kid; @@ -14640,17 +16387,22 @@ ray_t* ray_update(ray_t** args, int64_t n) { if (where_expr) { /* Try DAG compilation first, fall back to eval-level */ ray_t* mask_vec = NULL; + bool rejected = false; ray_graph_t* g = ray_graph_new(tbl); if (g) { ray_op_t* pred = compile_expr_dag(g, where_expr); if (pred) { pred = ray_optimize(g, pred); mask_vec = ray_execute(g, pred); + } else if (g->compile_err) { + /* rejected outright, not declined: no interpreter retry */ + mask_vec = graph_take_compile_err(g); + rejected = true; } ray_graph_free(g); } /* Fallback: eval-level predicate evaluation */ - if (!mask_vec || RAY_IS_ERR(mask_vec)) { + if (!rejected && (!mask_vec || RAY_IS_ERR(mask_vec))) { /* Bind column names to column vectors in env, then eval */ int64_t ncols2 = ray_table_ncols(tbl); ray_env_push_query_scope(); @@ -14663,6 +16415,8 @@ ray_t* ray_update(ray_t** args, int64_t n) { ray_env_pop_scope(); } if (!mask_vec || RAY_IS_ERR(mask_vec)) { ray_release(tbl); return mask_vec ? mask_vec : ray_error("type", "update: `where:` predicate evaluation failed"); } + mask_vec = where_mask_spread(mask_vec, nrows, "update"); + if (!mask_vec || RAY_IS_ERR(mask_vec)) { ray_release(tbl); return mask_vec ? mask_vec : ray_error("oom", NULL); } if (mask_vec->type != RAY_BOOL || mask_vec->len != nrows) { int8_t mask_t = mask_vec->type; /* capture BEFORE free */ ray_release(mask_vec); @@ -14711,32 +16465,14 @@ ray_t* ray_update(ray_t** args, int64_t n) { ray_t* new_col = ray_vec_new(ct, nrows); if (RAY_IS_ERR(new_col)) { ray_release(result); ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); return new_col; } - /* Evaluate expression via DAG, fallback to eval-level */ - ray_t* expr_vec = NULL; - { - ray_graph_t* ug = ray_graph_new(tbl); - if (ug) { - ray_op_t* expr_op = compile_expr_dag(ug, update_expr); - if (expr_op) { - expr_op = ray_optimize(ug, expr_op); - expr_vec = ray_execute(ug, expr_op); - } - ray_graph_free(ug); - } - } - if (!expr_vec || RAY_IS_ERR(expr_vec)) { - /* Fallback: eval with column bindings */ - int64_t ncols_e = ray_table_ncols(tbl); - ray_env_push_query_scope(); - for (int64_t c2 = 0; c2 < ncols_e; c2++) { - int64_t cn = ray_table_col_name(tbl, c2); - ray_t* col2 = ray_table_get_col_idx(tbl, c2); - ray_env_set_query_local(cn, col2); - } - expr_vec = ray_eval(update_expr); - ray_env_pop_scope(); - } + /* 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(new_col); ray_release(result); ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); return expr_vec ? expr_vec : ray_error("type", "update: failed to evaluate column update expression"); } + if (expr_vec->type >= 0 && ray_len(expr_vec) != nrows) { + int64_t got = ray_len(expr_vec); + ray_release(expr_vec); ray_release(new_col); ray_release(result); ray_release(mask_vec); ray_release(tbl); + DICT_VIEW_CLOSE(updw); return ray_error("length", "update: column has %lld values for %lld rows", (long long)got, (long long)nrows); + } /* WHERE update: expression result replaces ONLY masked rows. * When type differs (e.g., I64 col, F64 expr from (* col 1.1)), @@ -14837,15 +16573,8 @@ ray_t* ray_update(ray_t** args, int64_t n) { * GUID (16 B), whose payload lives in ->obj — copying * ray_elem_size(ct) bytes from ->i64 would over-read an * 8-byte buffer and write the wrong source for GUID. */ - uint8_t elem[16] = {0}; - if (ct == RAY_GUID) { - if (expr_vec->obj) memcpy(elem, ray_data(expr_vec->obj), 16); - } else if (ct == RAY_F64 && expr_vec->type == -RAY_I64) { - double promoted = (double)expr_vec->i64; - memcpy(elem, &promoted, sizeof promoted); - } else { - memcpy(elem, &expr_vec->i64, ray_elem_size(ct)); - } + uint8_t elem[16]; + update_atom_cell(expr_vec, ct, ray_elem_size(ct), elem); for (int64_t r = 0; r < nrows; r++) { bcast = ray_vec_append(bcast, elem); if (RAY_IS_ERR(bcast)) { ray_release(expr_vec); ray_release(new_col); ray_release(result); ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); return bcast; } @@ -14975,6 +16704,55 @@ ray_t* ray_update(ray_t** args, int64_t n) { if (RAY_IS_ERR(result)) { ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); return result; } } + /* New columns (in the dict, not in the table): the expression's + * value on the matched rows and null on the rest — false / 0x00 for + * BOOL and U8, which have no null. The loop above walks the table's + * columns only, so these used to be dropped without a word. */ + for (int64_t d = 0; d + 1 < dict_n; d += 2) { + int64_t kid = dict_elems[d]->i64; + if (kid == from_id || kid == where_id) continue; + bool exists = false; + for (int64_t c = 0; c < ncols; c++) + if (ray_table_col_name(tbl, c) == kid) { exists = true; break; } + if (exists) continue; + ray_t* v = update_eval_on(tbl, dict_elems[d + 1]); + if (v && !RAY_IS_ERR(v) && ray_is_atom(v)) { + ray_t* wide; + if (v->type == -RAY_STR) { + wide = broadcast_scalar(v, nrows); + } else { + ray_t* n_obj = make_i64(nrows); + wide = n_obj ? ray_take_fn(v, n_obj) : ray_error("oom", NULL); + if (n_obj) ray_release(n_obj); + } + ray_release(v); + v = wide; + } + if (v && !RAY_IS_ERR(v) && !ray_is_vec(v)) { + int8_t vt = v->type; + ray_release(v); + v = ray_error("type", "update: a new column under where: must be a typed vector, got %s", + ray_type_name(vt)); + } else if (v && !RAY_IS_ERR(v) && v->len != nrows) { + int64_t got = v->len; + ray_release(v); + v = ray_error("length", "update: new column has %lld values for %lld rows", + (long long)got, (long long)nrows); + } + if (v && !RAY_IS_ERR(v)) v = ray_cow(v); + if (!v || RAY_IS_ERR(v)) { + ray_release(result); ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); + return v ? v : ray_error("oom", NULL); + } + ray_t* nul = ray_typed_null((int8_t)-v->type); + for (int64_t r = 0; r < nrows && nul && !RAY_IS_ERR(nul); r++) + if (!mask[r]) store_typed_elem(v, r, nul); + if (nul && !RAY_IS_ERR(nul)) ray_release(nul); + result = ray_table_add_col(result, kid, v); + ray_release(v); + if (RAY_IS_ERR(result)) { ray_release(mask_vec); ray_release(tbl); DICT_VIEW_CLOSE(updw); return result; } + } + ray_release(mask_vec); if (inplace_sym >= 0 && result && !RAY_IS_ERR(result)) { ray_env_set(inplace_sym, result); @@ -15017,31 +16795,16 @@ ray_t* ray_update(ray_t** args, int64_t n) { result = ray_table_add_col(result, col_name, orig_col); ray_release(orig_col); } else { - ray_t* expr_vec = NULL; - { - ray_graph_t* ug = ray_graph_new(tbl); - if (ug) { - ray_op_t* expr_op = compile_expr_dag(ug, update_expr); - if (expr_op) { - expr_op = ray_optimize(ug, expr_op); - expr_vec = ray_execute(ug, expr_op); - } - ray_graph_free(ug); - } - } - if (!expr_vec || RAY_IS_ERR(expr_vec)) { - /* Fallback: eval with column bindings */ - int64_t ncols_f = ray_table_ncols(tbl); - ray_env_push_query_scope(); - for (int64_t cf = 0; cf < ncols_f; cf++) { - int64_t cn = ray_table_col_name(tbl, cf); - ray_t* colf = ray_table_get_col_idx(tbl, cf); - ray_env_set_query_local(cn, colf); - } - expr_vec = ray_eval(update_expr); - ray_env_pop_scope(); - } + /* 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"); } + if (expr_vec->type >= 0 && ray_len(expr_vec) != ray_table_nrows(tbl)) { + /* A column of another length has no row-aligned meaning; it + * used to be added as-is and left the table ragged. */ + int64_t got = ray_len(expr_vec); + ray_release(expr_vec); ray_release(result); ray_release(tbl); + DICT_VIEW_CLOSE(upda); return ray_error("length", "update: column has %lld values for %lld rows", (long long)got, (long long)ray_table_nrows(tbl)); + } /* Broadcast scalar atom to full column vector if needed */ if (expr_vec->type < 0) { @@ -15084,15 +16847,8 @@ ray_t* ray_update(ray_t** args, int64_t n) { /* Wide enough for every fixed-width type incl. GUID (16 B, * payload in ->obj); ray_elem_size(ct) bytes from ->i64 * would over-read an 8-byte buffer for GUID. */ - uint8_t elem[16] = {0}; - if (ct == RAY_GUID) { - if (expr_vec->obj) memcpy(elem, ray_data(expr_vec->obj), 16); - } else if (ct == RAY_F64 && expr_vec->type == -RAY_I64) { - double promoted = (double)expr_vec->i64; - memcpy(elem, &promoted, sizeof promoted); - } else { - memcpy(elem, &expr_vec->i64, ray_elem_size(ct)); - } + uint8_t elem[16]; + update_atom_cell(expr_vec, ct, ray_elem_size(ct), elem); for (int64_t r = 0; r < nrows; r++) { bcast = ray_vec_append(bcast, elem); if (RAY_IS_ERR(bcast)) { ray_release(expr_vec); ray_release(result); ray_release(tbl); DICT_VIEW_CLOSE(upda); return bcast; } @@ -15195,15 +16951,23 @@ ray_t* ray_update(ray_t** args, int64_t n) { } if (exists) continue; - /* New column: evaluate expression and add */ + /* New column: evaluate expression and add. DAG first, then the + * eval-level fallback with column bindings — the same sequence an + * update of an EXISTING column takes (update_eval_on). This site + * used to fail outright when the DAG declined the expression + * (temporal + - *), so `x: (+ ts 1)` worked as a select and as an + * existing-column update but not as a new column. */ ray_t* update_expr = dict_elems[d + 1]; - ray_graph_t* ug = ray_graph_new(tbl); - ray_op_t* expr_op = compile_expr_dag(ug, update_expr); - if (!expr_op) { ray_t* cerr = graph_take_compile_err(ug); ray_release(result); ray_release(tbl); ray_graph_free(ug); DICT_VIEW_CLOSE(upda); return cerr ? cerr : ray_error("domain", "update: failed to compile new column expression"); } - expr_op = ray_optimize(ug, expr_op); - ray_t* expr_vec = ray_execute(ug, expr_op); - ray_graph_free(ug); - if (RAY_IS_ERR(expr_vec)) { ray_release(result); ray_release(tbl); DICT_VIEW_CLOSE(upda); return expr_vec; } + 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 new column expression"); } + if (expr_vec->type >= 0 && ray_len(expr_vec) != ray_table_nrows(tbl)) { + /* A column of another length has no row-aligned meaning; it + * used to be added as-is and left the table ragged (the where: + * arm checks the same). */ + int64_t got = ray_len(expr_vec); + ray_release(expr_vec); ray_release(result); ray_release(tbl); + DICT_VIEW_CLOSE(upda); return ray_error("length", "update: new column has %lld values for %lld rows", (long long)got, (long long)ray_table_nrows(tbl)); + } /* Broadcast scalar to column */ if (expr_vec->type < 0) { @@ -15221,12 +16985,8 @@ ray_t* ray_update(ray_t** args, int64_t n) { } else { /* elem holds any fixed-width payload incl. GUID's 16 B (in * ->obj); copying from ->i64 would be wrong/over-read for GUID. */ - uint8_t elem[16] = {0}; - if (ct == RAY_GUID) { - if (expr_vec->obj) memcpy(elem, ray_data(expr_vec->obj), 16); - } else { - memcpy(elem, &expr_vec->i64, ray_elem_size(ct)); - } + uint8_t elem[16]; + update_atom_cell(expr_vec, ct, ray_elem_size(ct), elem); for (int64_t r = 0; r < nrows; r++) { bcast = ray_vec_append(bcast, elem); if (RAY_IS_ERR(bcast)) { ray_release(expr_vec); ray_release(result); ray_release(tbl); DICT_VIEW_CLOSE(upda); return bcast; } @@ -15300,6 +17060,25 @@ static bool table_has_parted_columns(ray_t* tbl) { return false; } +/* A fresh table with every parted / mapcommon column of `tbl` flattened + * (query_materialize_parted_col); plain columns are shared. 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)); + if (!flat_col || RAY_IS_ERR(flat_col)) { + ray_release(flat_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)) return flat_tbl ? flat_tbl : ray_error("oom", NULL); + } + return flat_tbl; +} + typedef struct { ray_t* mapcommon; /* borrowed */ ray_t* key_values; /* borrowed */ diff --git a/src/ops/rowsel.c b/src/ops/rowsel.c index 0dc883587..a3d56cd09 100644 --- a/src/ops/rowsel.c +++ b/src/ops/rowsel.c @@ -33,6 +33,8 @@ #include #include #include +#include +#include /* ────────────────────────────────────────────────────────────────── * Allocation helpers @@ -262,10 +264,14 @@ void rowsel_builder_init(rowsel_builder_t* b, uint32_t n_segs) { b->idx_len = 0; b->total_pass = 0; /* All three allocs must succeed — raw allocator is fatal-by-contract - * (no recovery path in Rayforce; same as ray_alloc failure callers). */ - assert(b->seg_flags && "rowsel_builder_init: OOM on seg_flags"); - assert(b->seg_off && "rowsel_builder_init: OOM on seg_off"); - assert(b->idx && "rowsel_builder_init: OOM on idx"); + * (no recovery path in Rayforce; same as ray_alloc failure callers). + * Checked explicitly: an assert would compile away under -DNDEBUG and + * leave the NULL for the next line to dereference (#652). */ + if (!b->seg_flags || !b->seg_off || !b->idx) { + fprintf(stderr, "rayforce: rowsel_builder_init: out of memory " + "(%u segments)\n", (unsigned)n_segs); + abort(); + } /* seg_off[0] is already 0 from ray_calloc_raw; kept explicit for clarity. */ b->seg_off[0] = 0; } diff --git a/src/ops/string.c b/src/ops/string.c index bf01958dd..389175147 100644 --- a/src/ops/string.c +++ b/src/ops/string.c @@ -680,6 +680,16 @@ ray_t* exec_ilike(ray_graph_t* g, ray_op_t* op) { ray_t* exec_string_unary(ray_graph_t* g, ray_op_t* op) { ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; + /* A literal (`(trim " ab")`) arrives as an atom, whose len field + * aliases its payload: the loop below read that many rows past it. + * The builtin answers an atom as one value. */ + if (input->type < 0) { + ray_t* r = op->opcode == OP_UPPER ? ray_upper_fn(input) + : op->opcode == OP_LOWER ? ray_lower_fn(input) + : ray_trim_fn(input); + ray_release(input); + return r; + } int64_t len = input->len; bool is_str = (input->type == RAY_STR); @@ -800,6 +810,12 @@ void ray_sym_strlen_into(ray_t* input, ray_t* result) { ray_t* exec_strlen(ray_graph_t* g, ray_op_t* op) { ray_t* input = exec_node(g, op_child(g, op, 0)); if (!input || RAY_IS_ERR(input)) return input; + /* An atom's len aliases its payload; see exec_string_unary. */ + if (input->type < 0) { + ray_t* r = ray_strlen_fn(input); + ray_release(input); + return r; + } int64_t len = input->len; ray_t* result = ray_vec_new(RAY_I64, len); @@ -1165,6 +1181,14 @@ ray_t* exec_substr(ray_graph_t* g, ray_op_t* op) { ray_t* len_v = exec_node(g, op_node(g, ext->third_in)); if (!len_v || RAY_IS_ERR(len_v)) { ray_release(input); ray_release(start_v); return len_v; } + /* An atom's len aliases its payload; see exec_string_unary. */ + if (input->type < 0) { + ray_t* args[3] = { input, start_v, len_v }; + ray_t* r = ray_substr_fn(args, 3); + ray_release(input); ray_release(start_v); ray_release(len_v); + return r; + } + int64_t nrows = input->len; bool is_str = (input->type == RAY_STR); @@ -1290,6 +1314,14 @@ ray_t* exec_replace(ray_graph_t* g, ray_op_t* op) { ray_t* to_v = exec_node(g, op_node(g, ext->third_in)); if (!to_v || RAY_IS_ERR(to_v)) { ray_release(input); ray_release(from_v); return to_v; } + /* An atom's len aliases its payload; see exec_string_unary. */ + if (input->type < 0) { + ray_t* args[3] = { input, from_v, to_v }; + ray_t* r = ray_replace_fn(args, 3); + ray_release(input); ray_release(from_v); ray_release(to_v); + return r; + } + /* from_v and to_v should be string constants (SYM atoms) */ const char* from_str = ray_str_ptr(from_v); size_t from_len = ray_str_len(from_v); @@ -1459,6 +1491,12 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { total += sl; } else if (t == -RAY_STR) { total += ray_str_len(args[a]); + } else if (t == -RAY_SYM) { + /* A symbol literal or a scalar such as (first s): RAY_IS_SYM + * matches SYM vectors only, so its text was left out and + * (concat 'ab 'cd) came back null. */ + ray_t* st = ray_sym_str(args[a]->i64); + if (st) total += ray_str_len(st); } } char sbuf[8192]; @@ -1494,6 +1532,11 @@ ray_t* exec_concat(ray_graph_t* g, ray_op_t* op) { const char* sp = ray_str_ptr(args[a]); size_t sl = ray_str_len(args[a]); if (sp && bi + sl < buf_cap) { memcpy(buf + bi, sp, sl); bi += sl; } + } else if (t == -RAY_SYM) { + ray_t* st = ray_sym_str(args[a]->i64); + const char* sp = st ? ray_str_ptr(st) : NULL; + size_t sl = st ? ray_str_len(st) : 0; + if (sp && bi + sl < buf_cap) { memcpy(buf + bi, sp, sl); bi += sl; } } } if (out_str) { diff --git a/src/ops/system.c b/src/ops/system.c index 922b45ba8..720146b31 100644 --- a/src/ops/system.c +++ b/src/ops/system.c @@ -197,11 +197,6 @@ ray_t* ray_set_splayed_fn(ray_t** args, int64_t n) { ray_err_t err = ray_splay_save(tbl, dir, sym_path); if (err != RAY_OK) return ray_error(ray_err_code_str(err), NULL); - /* Build + persist accelerator indexes (STR dictionaries, numeric chunk-zone - * min/max) inline at each column file's tail so mmap loads get the fast - * paths — same pass .csv.splayed runs. */ - ray_splay_build_indexes(dir, tbl); - ray_retain(tbl); return tbl; } @@ -1287,6 +1282,10 @@ ray_t* ray_memstat_fn(ray_t** args, int64_t n) { { "sort-perpart-runs", 17, ray_sort_perpart_runs() }, { "window-perpart-runs", 19, ray_window_perpart_runs() }, { "join-perpart-runs", 17, ray_join_perpart_runs() }, + /* the global symbol table: entries and the bytes of their strings, + * so a test can assert that a query leaves it where it found it */ + { "sym-count", 9, (int64_t)ray_sym_count() }, + { "sym-bytes", 9, (int64_t)ray_sym_bytes() }, }; for (size_t i = 0; i < sizeof(rows)/sizeof(rows[0]); i++) { int64_t s = ray_sym_intern(rows[i].name, rows[i].nlen); @@ -1740,11 +1739,13 @@ ray_t* ray_hopen_fn(ray_t** args, int64_t n) { /* Optional second argument: an integer connect timeout in * milliseconds (0 = use default), or an options dict carrying - * `timeout` and/or `compress` (#541). */ + * `timeout`, `compress` (#541) and/or `keepalive` (#589). */ int timeout_ms = 0; size_t compress = RAY_IPC_COMPRESS_AUTO; + int keepalive = RAY_IPC_KEEPALIVE_AUTO; if (n == 2) { - ray_t* err = ray_ipc_parse_open_opts(args[1], &timeout_ms, &compress); + ray_t* err = ray_ipc_parse_open_opts(args[1], &timeout_ms, &compress, + &keepalive); if (err) return err; } @@ -1802,7 +1803,8 @@ ray_t* ray_hopen_fn(ray_t** args, int64_t n) { const char* pw_ptr = (n_parts >= 4) ? password : NULL; const char* us_ptr = (n_parts >= 4) ? user : NULL; - int64_t h = ray_ipc_connect_opts(host, (uint16_t)port, us_ptr, pw_ptr, timeout_ms, compress); + int64_t h = ray_ipc_connect_opts(host, (uint16_t)port, us_ptr, pw_ptr, timeout_ms, + compress, keepalive); if (h == -2) return ray_error("access", "server requires authentication"); if (h == -3) return ray_error("access", "authentication failed"); if (h == -4) return ray_error("io", "wire version mismatch: %s:%d", host, port); @@ -1822,15 +1824,41 @@ ray_t* ray_hclose_fn(ray_t* x) { return RAY_NULL_OBJ; } -/* (hsend handle msg) → result */ -ray_t* ray_hsend_fn(ray_t* handle, ray_t* msg) { +/* (.ipc.send handle msg [timeout-ms]) → result + * + * The optional timeout bounds the whole round trip (#589). On expiry the + * connection is closed — a late reply would otherwise answer the next + * send — and an `io` error is returned. 0N means no deadline, as if the + * argument were absent. */ +ray_t* ray_hsend_fn(ray_t** args, int64_t n) { + if (n < 2 || n > 3) + return ray_error("rank", ".ipc.send expects 2 or 3 arguments: handle msg [timeout-ms]"); + ray_t* handle = args[0]; + ray_t* msg = args[1]; if (!ray_is_atom(handle) || (handle->type != -RAY_I64 && handle->type != -RAY_I32)) return ray_error("type", ".ipc.send expects an i64 or i32 handle, got %s", ray_type_name(handle->type)); int64_t h = (handle->type == -RAY_I64) ? handle->i64 : handle->i32; + + int64_t timeout_ms = 0; + if (n == 3) { + ray_t* t = args[2]; + if (!ray_is_atom(t) || (t->type != -RAY_I64 && t->type != -RAY_I32)) + return ray_error("type", ".ipc.send timeout must be an integer (ms), got %s", ray_type_name(t->type)); + int64_t tv = (t->type == -RAY_I64) ? t->i64 + : (t->i32 == NULL_I32 ? NULL_I64 : (int64_t)t->i32); + if (tv != NULL_I64) { + /* 0 is refused rather than guessed at: "no deadline" or + * "already expired"? */ + if (tv <= 0) + return ray_error("domain", ".ipc.send timeout must be > 0 or 0N (none), got %lld", (long long)tv); + timeout_ms = tv; + } + } + /* Validate message is serializable (reject builtins, etc.) */ if (ray_serde_size(msg) <= 0) return ray_error("type", "message not serializable"); - return ray_ipc_send(h, msg); + return ray_ipc_send_timeout(h, msg, timeout_ms); } /* (.ipc.post handle msg) → null on local send, error on failure. diff --git a/src/ops/temporal.c b/src/ops/temporal.c index 8e216c17f..16e5ab157 100644 --- a/src/ops/temporal.c +++ b/src/ops/temporal.c @@ -600,6 +600,14 @@ ray_t* exec_extract(ray_graph_t* g, ray_op_t* op) { if (!ext) { ray_release(input); return ray_error("nyi", NULL); } int64_t field = ext->sym; + /* A literal (`(year 2020.01.01)`) arrives as an atom, whose len field + * aliases its value: the date became a vector of 7305 rows. The atom + * path of the builtin answers it as one value. */ + if (input->type < 0) { + ray_t* r = ray_temporal_extract(input, (int)field); + ray_release(input); + return r; + } int64_t len = input->len; int8_t in_type = input->type; @@ -816,6 +824,12 @@ ray_t* exec_date_trunc(ray_graph_t* g, ray_op_t* op) { if (!ext) { ray_release(input); return ray_error("nyi", NULL); } int64_t field = ext->sym; + /* An atom's len aliases its value; see exec_extract. */ + if (input->type < 0) { + ray_t* r = ray_temporal_truncate(input, (int)field); + ray_release(input); + return r; + } int64_t len = input->len; int8_t in_type = input->type; diff --git a/src/store/aof.c b/src/store/aof.c index e85831ae6..656a033fd 100644 --- a/src/store/aof.c +++ b/src/store/aof.c @@ -39,6 +39,7 @@ #define _GNU_SOURCE #include "store/aof.h" +#include "core/crc32.h" #include "store/fileio.h" #include "mem/sys.h" @@ -84,54 +85,6 @@ struct ray_aof_s { bool dirty; /* appends since the last commit frame */ }; -/* ── CRC32 (IEEE reflected, poly 0xEDB88320), compile-time table ────── - * A constant table instead of lazy init: ray_aof_open and ray_aof_scan - * may run concurrently on first use, and a racy one-time init could let - * a thread CRC against a half-written table — worst case reporting - * committed data corrupt during recovery on a weak-memory machine. */ - -static const uint32_t AOF_CRC_TABLE[256] = { - 0x00000000u, 0x77073096u, 0xEE0E612Cu, 0x990951BAu, 0x076DC419u, 0x706AF48Fu, 0xE963A535u, 0x9E6495A3u, - 0x0EDB8832u, 0x79DCB8A4u, 0xE0D5E91Eu, 0x97D2D988u, 0x09B64C2Bu, 0x7EB17CBDu, 0xE7B82D07u, 0x90BF1D91u, - 0x1DB71064u, 0x6AB020F2u, 0xF3B97148u, 0x84BE41DEu, 0x1ADAD47Du, 0x6DDDE4EBu, 0xF4D4B551u, 0x83D385C7u, - 0x136C9856u, 0x646BA8C0u, 0xFD62F97Au, 0x8A65C9ECu, 0x14015C4Fu, 0x63066CD9u, 0xFA0F3D63u, 0x8D080DF5u, - 0x3B6E20C8u, 0x4C69105Eu, 0xD56041E4u, 0xA2677172u, 0x3C03E4D1u, 0x4B04D447u, 0xD20D85FDu, 0xA50AB56Bu, - 0x35B5A8FAu, 0x42B2986Cu, 0xDBBBC9D6u, 0xACBCF940u, 0x32D86CE3u, 0x45DF5C75u, 0xDCD60DCFu, 0xABD13D59u, - 0x26D930ACu, 0x51DE003Au, 0xC8D75180u, 0xBFD06116u, 0x21B4F4B5u, 0x56B3C423u, 0xCFBA9599u, 0xB8BDA50Fu, - 0x2802B89Eu, 0x5F058808u, 0xC60CD9B2u, 0xB10BE924u, 0x2F6F7C87u, 0x58684C11u, 0xC1611DABu, 0xB6662D3Du, - 0x76DC4190u, 0x01DB7106u, 0x98D220BCu, 0xEFD5102Au, 0x71B18589u, 0x06B6B51Fu, 0x9FBFE4A5u, 0xE8B8D433u, - 0x7807C9A2u, 0x0F00F934u, 0x9609A88Eu, 0xE10E9818u, 0x7F6A0DBBu, 0x086D3D2Du, 0x91646C97u, 0xE6635C01u, - 0x6B6B51F4u, 0x1C6C6162u, 0x856530D8u, 0xF262004Eu, 0x6C0695EDu, 0x1B01A57Bu, 0x8208F4C1u, 0xF50FC457u, - 0x65B0D9C6u, 0x12B7E950u, 0x8BBEB8EAu, 0xFCB9887Cu, 0x62DD1DDFu, 0x15DA2D49u, 0x8CD37CF3u, 0xFBD44C65u, - 0x4DB26158u, 0x3AB551CEu, 0xA3BC0074u, 0xD4BB30E2u, 0x4ADFA541u, 0x3DD895D7u, 0xA4D1C46Du, 0xD3D6F4FBu, - 0x4369E96Au, 0x346ED9FCu, 0xAD678846u, 0xDA60B8D0u, 0x44042D73u, 0x33031DE5u, 0xAA0A4C5Fu, 0xDD0D7CC9u, - 0x5005713Cu, 0x270241AAu, 0xBE0B1010u, 0xC90C2086u, 0x5768B525u, 0x206F85B3u, 0xB966D409u, 0xCE61E49Fu, - 0x5EDEF90Eu, 0x29D9C998u, 0xB0D09822u, 0xC7D7A8B4u, 0x59B33D17u, 0x2EB40D81u, 0xB7BD5C3Bu, 0xC0BA6CADu, - 0xEDB88320u, 0x9ABFB3B6u, 0x03B6E20Cu, 0x74B1D29Au, 0xEAD54739u, 0x9DD277AFu, 0x04DB2615u, 0x73DC1683u, - 0xE3630B12u, 0x94643B84u, 0x0D6D6A3Eu, 0x7A6A5AA8u, 0xE40ECF0Bu, 0x9309FF9Du, 0x0A00AE27u, 0x7D079EB1u, - 0xF00F9344u, 0x8708A3D2u, 0x1E01F268u, 0x6906C2FEu, 0xF762575Du, 0x806567CBu, 0x196C3671u, 0x6E6B06E7u, - 0xFED41B76u, 0x89D32BE0u, 0x10DA7A5Au, 0x67DD4ACCu, 0xF9B9DF6Fu, 0x8EBEEFF9u, 0x17B7BE43u, 0x60B08ED5u, - 0xD6D6A3E8u, 0xA1D1937Eu, 0x38D8C2C4u, 0x4FDFF252u, 0xD1BB67F1u, 0xA6BC5767u, 0x3FB506DDu, 0x48B2364Bu, - 0xD80D2BDAu, 0xAF0A1B4Cu, 0x36034AF6u, 0x41047A60u, 0xDF60EFC3u, 0xA867DF55u, 0x316E8EEFu, 0x4669BE79u, - 0xCB61B38Cu, 0xBC66831Au, 0x256FD2A0u, 0x5268E236u, 0xCC0C7795u, 0xBB0B4703u, 0x220216B9u, 0x5505262Fu, - 0xC5BA3BBEu, 0xB2BD0B28u, 0x2BB45A92u, 0x5CB36A04u, 0xC2D7FFA7u, 0xB5D0CF31u, 0x2CD99E8Bu, 0x5BDEAE1Du, - 0x9B64C2B0u, 0xEC63F226u, 0x756AA39Cu, 0x026D930Au, 0x9C0906A9u, 0xEB0E363Fu, 0x72076785u, 0x05005713u, - 0x95BF4A82u, 0xE2B87A14u, 0x7BB12BAEu, 0x0CB61B38u, 0x92D28E9Bu, 0xE5D5BE0Du, 0x7CDCEFB7u, 0x0BDBDF21u, - 0x86D3D2D4u, 0xF1D4E242u, 0x68DDB3F8u, 0x1FDA836Eu, 0x81BE16CDu, 0xF6B9265Bu, 0x6FB077E1u, 0x18B74777u, - 0x88085AE6u, 0xFF0F6A70u, 0x66063BCAu, 0x11010B5Cu, 0x8F659EFFu, 0xF862AE69u, 0x616BFFD3u, 0x166CCF45u, - 0xA00AE278u, 0xD70DD2EEu, 0x4E048354u, 0x3903B3C2u, 0xA7672661u, 0xD06016F7u, 0x4969474Du, 0x3E6E77DBu, - 0xAED16A4Au, 0xD9D65ADCu, 0x40DF0B66u, 0x37D83BF0u, 0xA9BCAE53u, 0xDEBB9EC5u, 0x47B2CF7Fu, 0x30B5FFE9u, - 0xBDBDF21Cu, 0xCABAC28Au, 0x53B39330u, 0x24B4A3A6u, 0xBAD03605u, 0xCDD70693u, 0x54DE5729u, 0x23D967BFu, - 0xB3667A2Eu, 0xC4614AB8u, 0x5D681B02u, 0x2A6F2B94u, 0xB40BBE37u, 0xC30C8EA1u, 0x5A05DF1Bu, 0x2D02EF8Du, -}; - -static uint32_t aof_crc32(uint32_t seed, const uint8_t* p, size_t n) { - uint32_t c = seed ^ 0xFFFFFFFFu; - for (size_t i = 0; i < n; i++) - c = AOF_CRC_TABLE[(c ^ p[i]) & 0xFF] ^ (c >> 8); - return c ^ 0xFFFFFFFFu; -} - /* ── Explicit little-endian framing (the header documents LE; the code * must deliver LE on every architecture, not native order) ────────── */ @@ -152,8 +105,8 @@ static uint32_t aof_get_u32le(const uint8_t* p) { static uint32_t aof_record_crc(uint32_t len, const uint8_t* payload) { uint8_t len_le[4]; aof_put_u32le(len_le, len); - uint32_t c = aof_crc32(0, len_le, 4); - return aof_crc32(c, payload, len); + uint32_t c = ray_crc32(0, len_le, 4); + return ray_crc32(c, payload, len); } /* ── Segment enumeration ───────────────────────────────────────────── */ diff --git a/src/store/col.c b/src/store/col.c index 295a17364..4763ef6b2 100644 --- a/src/store/col.c +++ b/src/store/col.c @@ -21,6 +21,12 @@ * SOFTWARE. */ +#if defined(__APPLE__) +# define _DARWIN_C_SOURCE +#elif !defined(_WIN32) +# define _GNU_SOURCE /* ftruncate, fileno */ +#endif + #include "col.h" #include "core/platform.h" #include "mem/heap.h" @@ -37,6 +43,11 @@ #include #include #include +#ifdef RAY_OS_WINDOWS +#include +#else +#include +#endif /* -------------------------------------------------------------------------- * validate_sym_bounds -- check all indices in a RAY_SYM column are < sym_count @@ -682,54 +693,77 @@ static void try_load_link_sidecar(ray_t* vec, const char* path) { * ray_col_save -- write a vector to a column file * -------------------------------------------------------------------------- */ -/* Append an inline index region to an EXISTING column file (no data rewrite): +/* Rationale: the region goes at the real payload end (STR includes its pool, + * so never recompute from len*esz); the marker is stamped LAST so a torn + * append never looks indexed; the flush is not an fsync because the index is + * a rebuildable accelerator. + * Append an inline index region to an EXISTING column file (no data rewrite): * pad the payload to 32, write the region, then stamp the aux[0..3] marker. * Used by the streaming .csv.splayed builder, which writes raw columns first. * `col_len`/`col_type` describe the on-disk column (payload = 32 + len*esz). */ +/* Cut a column file back to `len` bytes: undoes a partial index append. */ +bool ray_col_truncate(FILE* f, int64_t len) { + if (fflush(f) != 0) return false; +#ifdef RAY_OS_WINDOWS + return _chsize_s(_fileno(f), len) == 0; +#else + return ftruncate(fileno(f), (off_t)len) == 0; +#endif +} + +ray_err_t ray_col_write_index_region(FILE* f, const void* ix_v, int64_t* payload_end_out) { + const ray_index_t* ix = (const ray_index_t*)ix_v; + if (!f || !ix) return RAY_ERR_DOMAIN; + if (fseek(f, 0, SEEK_END) != 0) return RAY_ERR_IO; +#ifdef RAY_OS_WINDOWS + int64_t fsz = (int64_t)_ftelli64(f); +#else + int64_t fsz = (int64_t)ftello(f); +#endif + if (fsz < 32) return RAY_ERR_CORRUPT; + int64_t payload_end = fsz; + if (payload_end_out) *payload_end_out = payload_end; + int64_t region_off = (payload_end + 31) & ~(int64_t)31; + int64_t pad = region_off - payload_end; + static const uint8_t zeros[32] = {0}; + if (pad > 0 && fwrite(zeros, 1, (size_t)pad, f) != (size_t)pad) return RAY_ERR_IO; + /* Streamed block by block from the index itself: no region-sized + * staging buffer to fault in and copy (4.5 GB for a 100 M-row hash). */ + if (!ray_index_inline_write_file(f, ix)) return RAY_ERR_IO; + /* The region must be on the file before any marker claims it. */ + return fflush(f) == 0 ? RAY_OK : RAY_ERR_IO; +} + +void ray_col_stamp_index(ray_t* hdr) { + memset(hdr->aux, 0, 16); + uint32_t mg = COL_IDX_AUX_MAGIC; + memcpy(hdr->aux, &mg, 4); +} + ray_err_t ray_col_append_index(const char* path, const void* ix_v, int64_t col_len, int8_t col_type) { - const ray_index_t* ix = (const ray_index_t*)ix_v; - if (!path || !ix) return RAY_ERR_DOMAIN; + if (!path || !ix_v) return RAY_ERR_DOMAIN; (void)col_len; (void)col_type; - FILE* f = fopen(path, "r+b"); if (!f) return RAY_ERR_IO; - /* Already-indexed guard: the marker is stamped into aux[0..3] LAST, so its - * presence means a complete prior append. */ 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; + if (fread(&cur_mg, 1, 4, f) == 4 && 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) { + if (fseek(f, 0, SEEK_SET) != 0) err = RAY_ERR_IO; + else { + uint32_t mg = COL_IDX_AUX_MAGIC; + if (fwrite(&mg, 1, 4, f) != 4) err = RAY_ERR_IO; + } } - /* Append at the actual payload end — generic across formats: numeric is - * [header][data]; STR is [header][descriptors][pool]. Don't recompute it - * from col_len*esz (that ignores the str_pool). */ - if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return RAY_ERR_IO; } - long fsz = ftell(f); - if (fsz < 32) { fclose(f); return RAY_ERR_CORRUPT; } - int64_t payload_end = fsz; - - int64_t region_off = (payload_end + 31) & ~(int64_t)31; - int64_t pad = region_off - payload_end; - static const uint8_t zeros[32] = {0}; - if (pad > 0 && fwrite(zeros, 1, (size_t)pad, f) != (size_t)pad) { fclose(f); return RAY_ERR_IO; } - - int64_t rsize = ray_index_inline_size(ix); - uint8_t* rbuf = (uint8_t*)ray_calloc_raw((size_t)(1) * ((size_t)rsize)); - if (!rbuf) { fclose(f); return RAY_ERR_OOM; } - ray_index_inline_write(rbuf, ix); - size_t rw = fwrite(rbuf, 1, (size_t)rsize, f); - ray_free_raw(rbuf); - if (rw != (size_t)rsize) { fclose(f); return RAY_ERR_IO; } - - /* Stamp the marker into aux[0..3] (file offset 0). */ - if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return RAY_ERR_IO; } - uint32_t mg = COL_IDX_AUX_MAGIC; - if (fwrite(&mg, 1, 4, f) != 4) { fclose(f); return RAY_ERR_IO; } - /* The index is a derived accelerator (rebuildable); flush is enough — no - * fsync needed, and the marker is written LAST so a torn append never - * leaves a half-region that looks indexed. */ - if (fclose(f) != 0) return RAY_ERR_IO; - return RAY_OK; + if (err == RAY_OK) return fclose(f) == 0 ? RAY_OK : RAY_ERR_IO; + /* Without the marker the loader requires the exact payload length, hence + * the rollback. Best effort: the marker was never written, so restoring the length is + * all it takes; a payload_end of 0 means the region never started. */ + if (payload_end) (void)ray_col_truncate(f, payload_end); + fclose(f); + return err; } /* Does the payload hold the type's null sentinel anywhere? Sequential @@ -785,7 +819,7 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { FILE* f = fopen(tmp_path, "wb"); if (!f) return RAY_ERR_IO; ray_err_t err = col_save_str_list(vec, f); - fclose(f); + if (fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; if (err != RAY_OK) { remove(tmp_path); return err; } goto fsync_and_rename; } @@ -795,7 +829,7 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { FILE* f = fopen(tmp_path, "wb"); if (!f) return RAY_ERR_IO; ray_err_t err = col_save_list(vec, f); - fclose(f); + if (fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; if (err != RAY_OK) { remove(tmp_path); return err; } goto fsync_and_rename; } @@ -805,7 +839,7 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { FILE* f = fopen(tmp_path, "wb"); if (!f) return RAY_ERR_IO; ray_err_t err = col_save_table(vec, f); - fclose(f); + if (fclose(f) != 0 && err == RAY_OK) err = RAY_ERR_IO; if (err != RAY_OK) { remove(tmp_path); return err; } goto fsync_and_rename; } @@ -926,9 +960,7 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { /* Stamp the "index present" marker into the reserved aux (after all * other aux manipulation, which zeroes it for the common cases). */ if (persist_index) { - memset(header.aux, 0, 16); - uint32_t mg = COL_IDX_AUX_MAGIC; - memcpy(header.aux, &mg, 4); + ray_col_stamp_index(&header); } size_t written = fwrite(&header, 1, 32, f); @@ -1029,7 +1061,7 @@ static ray_err_t col_save_impl(ray_t* vec, const char* path, bool durable) { if (rw != (size_t)rsize) { fclose(f); remove(tmp_path); return RAY_ERR_IO; } } - fclose(f); + if (fclose(f) != 0) { remove(tmp_path); return RAY_ERR_IO; } } fsync_and_rename:; @@ -1112,8 +1144,10 @@ ray_err_t ray_col_save_bulk(ray_t* vec, const char* path) { * process dictionary. Header rc = domain count at save time (the O(1) * fast-reject the loader checks against the FILE domain's count). * Caller contract: every distinct symbol of the column was interned into - * `target` and the domain was FLUSHED before this call (crash ordering: - * sym → columns → .d) — an absent symbol here is RAY_ERR_CORRUPT. + * `target`. Live-table writes must FLUSH the domain before this call (crash + * ordering: sym → columns → .d). An import into a private staging directory + * may defer that flush until all workers join, but must persist the complete + * domain before publishing the root. An absent symbol is RAY_ERR_CORRUPT. * -------------------------------------------------------------------------- */ ray_err_t ray_col_save_sym_encoded(ray_t* vec, const char* path, diff --git a/src/store/col.h b/src/store/col.h index 615ce5390..61b3da3ab 100644 --- a/src/store/col.h +++ b/src/store/col.h @@ -26,6 +26,7 @@ #include #include +#include struct ray_sym_domain_s; @@ -95,8 +96,9 @@ ray_t* ray_col_mmap(const char* path); /* Write a RAY_SYM column re-encoded as positions in `target` (width = * ray_sym_dict_width(domain count); header rc = domain count at save). * Caller must have interned the column's distinct symbols into `target` - * and FLUSHED the domain first (crash ordering: sym before columns) — - * a cell whose symbol is absent from `target` is RAY_ERR_CORRUPT. */ + * and FLUSHED the domain first for live-table writes. Private import staging + * may defer the flush until workers join, before publishing the root. + * A cell whose symbol is absent from `target` is RAY_ERR_CORRUPT. */ ray_err_t ray_col_save_sym_encoded(ray_t* vec, const char* path, struct ray_sym_domain_s* target, bool durable); @@ -116,5 +118,16 @@ ray_t* ray_col_mmap_splayed_dom(const char* path, struct ray_sym_domain_s* do ray_err_t ray_col_append_index(const char* path, const void* ix, int64_t col_len, int8_t col_type); +/* Seek f to its end, pad to 32 bytes and write ix's inline region there; + * flushes. Does not touch the header. The caller stamps the marker with + * ray_col_stamp_index or rolls the file back on error. */ +ray_err_t ray_col_write_index_region(FILE* f, const void* ix_v, int64_t* payload_end_out); + +/* Flush f and cut it to `len` bytes: undoes a partial index region. */ +bool ray_col_truncate(FILE* f, int64_t len); + +/* Put the "index present" marker into a 32-byte header image. */ +void ray_col_stamp_index(ray_t* hdr); + #endif /* RAY_COL_H */ diff --git a/src/store/fileio.c b/src/store/fileio.c index 978d03560..5283c3435 100644 --- a/src/store/fileio.c +++ b/src/store/fileio.c @@ -21,6 +21,12 @@ * SOFTWARE. */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) +#define _DARWIN_C_SOURCE +#endif #include "fileio.h" #include @@ -86,6 +92,15 @@ ray_err_t ray_file_lock_ex(ray_fd_t fd) { return RAY_OK; } +ray_err_t ray_file_trylock_ex(ray_fd_t fd) { + if (fd == RAY_FD_INVALID) return RAY_ERR_IO; + OVERLAPPED ov = {0}; + if (!LockFileEx(fd, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, + 0, MAXDWORD, MAXDWORD, &ov)) + return RAY_ERR_IO; + return RAY_OK; +} + ray_err_t ray_file_lock_sh(ray_fd_t fd) { if (fd == RAY_FD_INVALID) return RAY_ERR_IO; OVERLAPPED ov = {0}; @@ -125,6 +140,11 @@ ray_err_t ray_file_rename(const char* old_path, const char* new_path) { return RAY_OK; } +ray_err_t ray_file_rename_new(const char* old_path, const char* new_path) { + if (!old_path || !new_path) return RAY_ERR_IO; + return MoveFileExA(old_path,new_path,MOVEFILE_WRITE_THROUGH) ? RAY_OK : RAY_ERR_IO; +} + ray_err_t ray_mkdir(const char* path) { if (!path) return RAY_ERR_IO; if (!CreateDirectoryA(path, NULL)) { @@ -167,6 +187,10 @@ ray_err_t ray_mkdir_p(const char* path) { #include #include #include +#if defined(RAY_OS_LINUX) +#include +#define RAY_RENAME_NOREPLACE 1u /* RENAME_NOREPLACE, linux/fs.h */ +#endif ray_fd_t ray_file_open(const char* path, int flags) { if (!path) return RAY_FD_INVALID; @@ -194,6 +218,12 @@ ray_err_t ray_file_lock_ex(ray_fd_t fd) { return RAY_OK; } +ray_err_t ray_file_trylock_ex(ray_fd_t fd) { + if (fd == RAY_FD_INVALID) return RAY_ERR_IO; + if (flock(fd, LOCK_EX | LOCK_NB) != 0) return RAY_ERR_IO; + return RAY_OK; +} + ray_err_t ray_file_lock_sh(ray_fd_t fd) { if (fd == RAY_FD_INVALID) return RAY_ERR_IO; if (flock(fd, LOCK_SH) != 0) return RAY_ERR_IO; @@ -242,6 +272,41 @@ ray_err_t ray_file_rename(const char* old_path, const char* new_path) { return RAY_OK; } +ray_err_t ray_file_rename_new_emulated(const char* old_path, const char* new_path) { + if (!old_path || !new_path) return RAY_ERR_IO; + struct stat st; + if (lstat(old_path, &st) != 0) return RAY_ERR_IO; + if (S_ISDIR(st.st_mode)) { + /* mkdir claims the name or fails if anything holds it; rename then + * replaces only that empty placeholder, and fails (ENOTEMPTY / + * EEXIST) if anything was put into it meanwhile. */ + if (mkdir(new_path, 0700) != 0) return RAY_ERR_IO; + if (rename(old_path, new_path) != 0) { rmdir(new_path); return RAY_ERR_IO; } + return RAY_OK; + } + /* link fails if the name exists; then drop the old name. */ + if (link(old_path, new_path) != 0) return RAY_ERR_IO; + if (unlink(old_path) != 0) { unlink(new_path); return RAY_ERR_IO; } + return RAY_OK; +} + +ray_err_t ray_file_rename_new(const char* old_path, const char* new_path) { + if (!old_path || !new_path) return RAY_ERR_IO; +#if defined(RAY_OS_LINUX) && defined(SYS_renameat2) + /* Through syscall(): the renameat2 wrapper and RENAME_NOREPLACE came in + * glibc 2.28, and the engine links against older glibc (2.17). */ + if (syscall(SYS_renameat2, AT_FDCWD, old_path, AT_FDCWD, new_path, + RAY_RENAME_NOREPLACE) == 0) return RAY_OK; + /* EINVAL: this filesystem does not implement RENAME_NOREPLACE (some + * network and FUSE filesystems); ENOSYS: kernel older than 3.15. */ + if (errno != EINVAL && errno != ENOSYS) return RAY_ERR_IO; +#elif defined(RAY_OS_MACOS) + if (renamex_np(old_path,new_path,RENAME_EXCL) == 0) return RAY_OK; + if (errno != ENOTSUP) return RAY_ERR_IO; +#endif + return ray_file_rename_new_emulated(old_path, new_path); +} + ray_err_t ray_mkdir(const char* path) { if (!path) return RAY_ERR_IO; if (mkdir(path, 0755) != 0 && errno != EEXIST) return RAY_ERR_IO; diff --git a/src/store/fileio.h b/src/store/fileio.h index c6f954c82..c98b3d180 100644 --- a/src/store/fileio.h +++ b/src/store/fileio.h @@ -47,10 +47,22 @@ ray_fd_t ray_file_open(const char* path, int flags); void ray_file_close(ray_fd_t fd); ray_err_t ray_file_lock_ex(ray_fd_t fd); ray_err_t ray_file_lock_sh(ray_fd_t fd); +/* Exclusive lock without waiting: RAY_ERR_IO when another holder has it. */ +ray_err_t ray_file_trylock_ex(ray_fd_t fd); ray_err_t ray_file_unlock(ray_fd_t fd); ray_err_t ray_file_sync(ray_fd_t fd); ray_err_t ray_file_sync_dir(const char* path); ray_err_t ray_file_rename(const char* old_path, const char* new_path); +/* Publish a new path without replacing any existing destination, including + * an empty directory. Uses the host's no-replace rename; where the host or + * filesystem lacks one, ray_file_rename_new_emulated (never a racy + * check-then-rename). */ +ray_err_t ray_file_rename_new(const char* old_path, const char* new_path); +/* No-replace rename from portable primitives. A directory: mkdir claims + * the name atomically, then rename replaces only that empty placeholder + * (an empty directory is briefly visible at new_path). A file: link, then + * unlink. POSIX only; exposed for tests. */ +ray_err_t ray_file_rename_new_emulated(const char* old_path, const char* new_path); ray_err_t ray_mkdir(const char* path); ray_err_t ray_mkdir_p(const char* path); /* like `mkdir -p` */ diff --git a/src/store/hnsw.c b/src/store/hnsw.c index 05ed802d7..3f1ab14c2 100644 --- a/src/store/hnsw.c +++ b/src/store/hnsw.c @@ -558,16 +558,21 @@ ray_hnsw_t* ray_hnsw_build(const float* vectors, int64_t n_nodes, int32_t dim, return NULL; } const float* vec = vectors + i * dim; - int32_t node_level = idx->node_level[i]; + int32_t node_level = (uint8_t)idx->node_level[i]; - /* Pass 1: Greedy descent from top layer to node_level+1 */ + /* Only levels up to the current entry point have already been + * populated; higher levels belong to nodes inserted later. */ int64_t ep = idx->entry_point; - for (int32_t l = idx->n_layers - 1; l > node_level; l--) { + int32_t ep_level = (uint8_t)idx->node_level[ep]; + for (int32_t l = ep_level; l > node_level; l--) { ep = hnsw_greedy_closest(idx, vec, ep, l); } /* Pass 2: Insert into layers [node_level ... 0] */ for (int32_t l = node_level; l >= 0; l--) { + /* This node is the first inserted node on each newly created + * upper layer, so there are no neighbors to search there yet. */ + if (l > ep_level) continue; ray_hnsw_layer_t* layer = &idx->layers[l]; int64_t M_max_l = layer->M_max; int64_t M_keep = (l == 0) ? idx->M_max0 : M; @@ -908,21 +913,34 @@ bool ray_hnsw_vec_size_valid(int64_t n_nodes, int32_t dim) { return (uint64_t)n_nodes <= SIZE_MAX / sizeof(float) / (uint64_t)dim; } -/* Validate the graph topology before making the loaded index available to - * search. All ids in these files are untrusted: a bad neighbor used to - * reach hnsw_greedy_closest() or hnsw_search_layer() becomes an unchecked - * offset into idx->vectors. The node_ids mapping is equally important — a - * duplicate, missing, or wrong-level entry can make a valid-looking layer - * resolve the wrong neighbor block. +/* Validate and repair the graph topology before making the loaded index + * available to search. All ids in these files are untrusted: a bad neighbor + * used to reach hnsw_greedy_closest() or hnsw_search_layer() becomes an + * unchecked offset into idx->vectors. The node_ids mapping is equally + * important — a duplicate, missing, or wrong-level entry can make a + * valid-looking layer resolve the wrong neighbor block. Legacy lower-layer + * links are removed in place and reported through repaired_links; every other + * inconsistency fails. */ -static bool hnsw_persisted_layers_valid(const ray_hnsw_t* idx) { - if (!idx || !idx->node_level || idx->n_nodes <= 0 || idx->n_layers <= 0) +static bool hnsw_validate_and_repair_persisted_layers(ray_hnsw_t* idx, + int64_t* repaired_links) { + if (repaired_links) *repaired_links = 0; + if (!idx || !idx->node_level || idx->n_nodes <= 0 || idx->n_layers <= 0 || + idx->n_layers > HNSW_MAX_LAYERS) return false; + if (idx->entry_point < 0 || (uint64_t)idx->entry_point >= (uint64_t)idx->n_nodes) + return false; + + bool entry_on_top_layer = false; for (int64_t id = 0; id < idx->n_nodes; id++) { - if (idx->node_level[id] < 0 || idx->node_level[id] >= idx->n_layers) + int8_t level = idx->node_level[id]; + if (level < 0 || level >= idx->n_layers) return false; + if (id == idx->entry_point) + entry_on_top_layer = level == idx->n_layers - 1; } + if (!entry_on_top_layer) return false; uint8_t* seen = (uint8_t*)ray_sys_alloc((size_t)idx->n_nodes); if (!seen) return false; @@ -933,7 +951,9 @@ static bool hnsw_persisted_layers_valid(const ray_hnsw_t* idx) { int64_t expected = 0; for (int64_t id = 0; id < idx->n_nodes; id++) if (idx->node_level[id] >= l) expected++; - if (layer->n_nodes != expected || !layer->node_ids || !layer->neighbors) { + int64_t expected_M = l == 0 ? idx->M_max0 : idx->M; + if (layer->n_nodes != expected || layer->M_max != expected_M || + !layer->node_ids || !layer->neighbors) { valid = false; break; } @@ -948,10 +968,32 @@ static bool hnsw_persisted_layers_valid(const ray_hnsw_t* idx) { seen[id] = 1; } - size_t nb_count = (size_t)layer->n_nodes * (size_t)layer->M_max; - for (size_t i = 0; i < nb_count && valid; i++) { - int64_t id = layer->neighbors[i]; - if (id != -1 && (id < 0 || id >= idx->n_nodes)) valid = false; + for (int64_t i = 0; i < layer->n_nodes && valid; i++) { + bool empty_seen = false; + int64_t* neighbors = + &layer->neighbors[(size_t)i * (size_t)layer->M_max]; + int64_t kept = 0; + for (int64_t j = 0; j < layer->M_max; j++) { + int64_t id = neighbors[j]; + if (id == -1) { + empty_seen = true; + continue; + } + if (empty_seen || id < 0 || id >= idx->n_nodes) { + valid = false; + break; + } + /* Older builders could persist the entry point as a one-way + * edge even when it was absent from this upper layer. Such an + * edge was unusable; drop it while preserving valid neighbors. */ + if (idx->node_level[id] < l) { + if (repaired_links) (*repaired_links)++; + continue; + } + neighbors[kept++] = id; + } + while (valid && kept < layer->M_max) + neighbors[kept++] = -1; } } @@ -1052,11 +1094,11 @@ static ray_hnsw_t* hnsw_load_impl(const char* dir, bool use_mmap) { fclose(f); } - if (!hnsw_persisted_layers_valid(idx)) { + int64_t repaired_links = 0; + if (!hnsw_validate_and_repair_persisted_layers(idx, &repaired_links)) { ray_hnsw_free(idx); return NULL; } - /* Read vectors */ snprintf(path, sizeof(path), "%s/hnsw_vectors.bin", dir); f = fopen(path, "rb"); @@ -1072,6 +1114,13 @@ static ray_hnsw_t* hnsw_load_impl(const char* dir, bool use_mmap) { } fclose(f); + if (repaired_links > 0) { + fprintf(stderr, + "hnsw: WARN repaired %lld legacy cross-layer neighbor link%s " + "while loading %s; rebuild the index to restore search recall\n", + (long long)repaired_links, repaired_links == 1 ? "" : "s", dir); + } + return idx; } diff --git a/src/store/journal.c b/src/store/journal.c index 2d3a3932c..bf84c7ecb 100644 --- a/src/store/journal.c +++ b/src/store/journal.c @@ -44,6 +44,7 @@ #ifndef RAY_OS_WINDOWS # include # include +# include #endif #define RAY_JOURNAL_PATH_MAX 1024 @@ -58,6 +59,8 @@ static struct { char log_path[RAY_JOURNAL_PATH_MAX]; bool in_replay; int64_t log_gen; /* live log's generation id, 0 = legacy/unknown */ + ray_fd_t lock_fd; /* .lk, held while the journal is open */ + char lock_path[RAY_JOURNAL_PATH_MAX]; /* the held .lk */ } g_journal = { .mode = RAY_JOURNAL_OFF, .fp = NULL, @@ -65,8 +68,95 @@ static struct { .log_path = {0}, .in_replay = false, .log_gen = 0, + .lock_fd = RAY_FD_INVALID, }; +/* One writer per journal base. The journal is single-writer (an entry is + * two writes, a roll renames the live log, a snapshot writes a fixed temp + * name), so this process holds an exclusive lock on .lk while it has + * the journal open, and a second opener fails instead of interleaving. + * .log.purge removes the lock file while holding it; a lock taken on a file + * that was removed meanwhile is dropped and taken again on the new one, so + * two openers can never hold locks on different files. A lock still held + * for another base (a roll that failed to reopen its log) is dropped first. + * *missing, when given, tells that the lock file could not be created + * because its directory is gone. */ +static void journal_unlock(void); +static ray_err_t journal_lock(const char* base, bool* missing) { + if (missing) *missing = false; + char path[RAY_JOURNAL_PATH_MAX]; + int n = snprintf(path, sizeof(path), "%s.lk", base); + if (n <= 0 || (size_t)n >= sizeof(path)) return RAY_ERR_DOMAIN; + if (g_journal.lock_fd != RAY_FD_INVALID) { + if (strcmp(g_journal.lock_path, path) == 0) return RAY_OK; + journal_unlock(); + } + int open_err = 0; + for (int attempt = 0; attempt < 8; attempt++) { + /* Open for writing: flock emulated over byte-range locks (NFS, SMB) + * takes an exclusive lock only on a writable fd. A lock file that + * is not ours to write (another user's) is still locked through a + * read-only fd, so it serialises with that user's process. */ + ray_fd_t fd = ray_file_open(path, RAY_OPEN_READ | RAY_OPEN_WRITE | RAY_OPEN_CREATE); + if (fd == RAY_FD_INVALID) { + int e = errno; + if (e == EACCES || e == EROFS) { + fd = ray_file_open(path, RAY_OPEN_READ); + /* Removed between the two opens: try again. */ + if (fd == RAY_FD_INVALID && errno == ENOENT) { open_err = e; continue; } + } + if (fd == RAY_FD_INVALID) { + /* Only a missing directory means nobody can hold it. */ + if (missing) *missing = e == ENOENT; + fprintf(stderr, "log: ERROR cannot open %s: %s\n", path, strerror(e)); + return RAY_ERR_IO; + } + } +#ifndef RAY_OS_WINDOWS + /* A program started with .sys.exec must not keep the lock alive + * after this process exits. */ + (void)fcntl(fd, F_SETFD, FD_CLOEXEC); +#endif + if (ray_file_trylock_ex(fd) != RAY_OK) { +#ifdef RAY_OS_WINDOWS + bool held = true; +#else + int e = errno; + bool held = e == EWOULDBLOCK || e == EAGAIN; +#endif + ray_file_close(fd); + if (held) + fprintf(stderr, "log: ERROR journal %s is open in another process\n", base); +#ifndef RAY_OS_WINDOWS + else + fprintf(stderr, "log: ERROR cannot lock %s: %s\n", path, strerror(e)); +#endif + return RAY_ERR_IO; + } +#ifndef RAY_OS_WINDOWS + struct stat held, named; + if (fstat(fd, &held) != 0 || stat(path, &named) != 0 || + held.st_ino != named.st_ino || held.st_dev != named.st_dev) { + ray_file_close(fd); /* purged under us: retry */ + continue; + } +#endif + g_journal.lock_fd = fd; + memcpy(g_journal.lock_path, path, (size_t)n + 1); + return RAY_OK; + } + if (open_err) + fprintf(stderr, "log: ERROR cannot open %s: %s\n", path, strerror(open_err)); + return RAY_ERR_IO; +} + +static void journal_unlock(void) { + if (g_journal.lock_fd == RAY_FD_INVALID) return; + (void)ray_file_unlock(g_journal.lock_fd); + ray_file_close(g_journal.lock_fd); + g_journal.lock_fd = RAY_FD_INVALID; +} + /* ── helpers ──────────────────────────────────────────────────────── */ static bool path_join_ext(char* dst, size_t dstsz, const char* base, const char* ext) { @@ -641,24 +731,46 @@ ray_err_t ray_journal_open_append(const char* base, ray_journal_mode_t mode) { size_t blen = strlen(base); if (blen + 5 >= sizeof(g_journal.base)) return RAY_ERR_DOMAIN; + ray_err_t le = journal_lock(base, NULL); + if (le != RAY_OK) return le; memcpy(g_journal.base, base, blen + 1); g_journal.mode = mode; - if (!path_join_ext(g_journal.log_path, sizeof(g_journal.log_path), base, ".log")) + if (!path_join_ext(g_journal.log_path, sizeof(g_journal.log_path), base, ".log")) { + journal_unlock(); return RAY_ERR_DOMAIN; + } - return open_log_for_append(); + ray_err_t oe = open_log_for_append(); + if (oe != RAY_OK) journal_unlock(); + return oe; } ray_err_t ray_journal_open(const char* base, ray_journal_mode_t mode) { if (!base || !*base) return RAY_ERR_DOMAIN; if (g_journal.fp) return RAY_ERR_DOMAIN; /* already open */ + /* Lock before replaying, so a second process fails before it applies + * a log another process is still writing. */ + ray_err_t le = journal_lock(base, NULL); + if (le != RAY_OK) return le; ray_err_t re = ray_journal_recover(base); - if (re != RAY_OK) return re; - return ray_journal_open_append(base, mode); + if (re != RAY_OK) { journal_unlock(); return re; } + /* The append step fails before it reaches the lock it already holds + * (base too long for .log): release ours. */ + ray_err_t oe = ray_journal_open_append(base, mode); + if (oe != RAY_OK) journal_unlock(); + return oe; } +static ray_err_t journal_close_fp(void); + ray_err_t ray_journal_close(void) { + ray_err_t r = journal_close_fp(); + journal_unlock(); + return r; +} + +static ray_err_t journal_close_fp(void) { if (!g_journal.fp) return RAY_OK; /* Check both fflush and fclose return — buffered ENOSPC slips * through silently otherwise and the "best-effort durability at @@ -686,11 +798,18 @@ ray_err_t ray_journal_purge(void) { * nothing to act on, and (unlike .log.close) we cannot derive a path. */ if (!g_journal.base[0]) return RAY_ERR_DOMAIN; + /* Hold the journal's lock while its files are removed: another process + * that has it open is still writing them. Only when the directory is + * gone, so nobody can hold it, purge goes on without the lock. */ + bool missing = false; + ray_err_t lock_result = journal_lock(g_journal.base, &missing); + if (lock_result != RAY_OK && !missing) return lock_result; + /* Close the active log FIRST: never unlink a path out from under * buffered writes (and Windows refuses to unlink an open file). */ if (g_journal.fp) { - ray_err_t close_result = ray_journal_close(); - if (close_result != RAY_OK) return close_result; + ray_err_t close_result = journal_close_fp(); + if (close_result != RAY_OK) { journal_unlock(); return close_result; } } ray_err_t result = RAY_OK; @@ -745,7 +864,16 @@ ray_err_t ray_journal_purge(void) { closedir(d); } - /* 3. Reset: the journal is gone, so a later .log.open starts clean. */ + /* 3. The lock file last, while it is still held (see journal_lock). + * Windows cannot remove a file that is open, so it stays there. */ +#ifndef RAY_OS_WINDOWS + if (g_journal.lock_fd != RAY_FD_INVALID && + path_join_ext(path, sizeof(path), g_journal.base, ".lk")) + purge_one(path, &result); +#endif + + /* 4. Reset: the journal is gone, so a later .log.open starts clean. */ + journal_unlock(); g_journal.mode = RAY_JOURNAL_OFF; g_journal.base[0] = '\0'; g_journal.log_path[0] = '\0'; diff --git a/src/store/part.c b/src/store/part.c index e536a7e7a..1a7109c8f 100644 --- a/src/store/part.c +++ b/src/store/part.c @@ -344,6 +344,9 @@ ray_t* ray_read_parted(const char* db_root, const char* table_name) { db_root, part_dirs[p], table_name); goto fail_tables; } + /* Resolve the generation before refreshing the shared symbol domain. + * ray_read_splayed_dom reopens the cached domain by path, so symbols + * appended by a concurrent publisher are visible before columns load. */ part_tables[p] = ray_read_splayed_dom(path, dom); if (!part_tables[p] || RAY_IS_ERR(part_tables[p])) { if (trace) @@ -566,8 +569,11 @@ static ray_err_t collect_table_dirs(const char* pdir, char*** out_names, struct dirent* ent; while ((ent = readdir(d)) != NULL) { if (ent->d_name[0] == '.') continue; /* ".", "..", and the ".sym" dotfile */ - char dpath[1024]; - int dn = snprintf(dpath, sizeof(dpath), "%s/%s/.d", pdir, ent->d_name); + char tdir[1024], resolved[1024], dpath[1100]; + int dn = snprintf(tdir, sizeof(tdir), "%s/%s", pdir, ent->d_name); + if (dn < 0 || (size_t)dn >= sizeof(tdir)) continue; + if (ray_splay_resolve_dir(tdir, resolved, sizeof(resolved)) != RAY_OK) continue; + dn = snprintf(dpath, sizeof(dpath), "%s/.d", resolved); if (dn < 0 || (size_t)dn >= sizeof(dpath)) continue; struct stat st; if (stat(dpath, &st) != 0 || !S_ISREG(st.st_mode)) continue; /* not a table */ @@ -606,8 +612,11 @@ static ray_err_t collect_table_dirs(const char* pdir, char*** out_names, /* Does partition `part` contain splayed table `tname` (i.e. a `.d` schema)? */ static bool partition_has_table(const char* db_root, const char* part, const char* tname) { - char dpath[1024]; - int n = snprintf(dpath, sizeof(dpath), "%s/%s/%s/.d", db_root, part, tname); + char tdir[1024], resolved[1024], dpath[1100]; + int n = snprintf(tdir, sizeof(tdir), "%s/%s/%s", db_root, part, tname); + if (n < 0 || (size_t)n >= sizeof(tdir)) return false; + if (ray_splay_resolve_dir(tdir, resolved, sizeof(resolved)) != RAY_OK) return false; + n = snprintf(dpath, sizeof(dpath), "%s/.d", resolved); if (n < 0 || (size_t)n >= sizeof(dpath)) return false; struct stat st; return stat(dpath, &st) == 0 && S_ISREG(st.st_mode); diff --git a/src/store/serde.c b/src/store/serde.c index ecfa2c103..d4a58652a 100644 --- a/src/store/serde.c +++ b/src/store/serde.c @@ -237,6 +237,8 @@ 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; + return 1 + 1 + 8; case RAY_TIMESTAMP: case RAY_F64: return 1 + 1 + 8; case RAY_GUID: return 1 + 1 + 16; @@ -317,24 +319,43 @@ int64_t ray_serde_size(ray_t* obj) { case RAY_LIST: { int64_t size = 1 + 1 + 8; ray_t** elems = (ray_t**)ray_data(obj); - for (int64_t i = 0; i < obj->len; i++) - size += ray_serde_size(elems[i]); + for (int64_t i = 0; i < obj->len; i++) { + int64_t child = ray_serde_size(elems[i]); + if (child <= 0) return child; + size += child; + } return size; } case RAY_TABLE: { /* type + attrs + schema(recursive) + cols(recursive RAY_LIST) */ ray_t** slots = (ray_t**)ray_data(obj); - return 1 + 1 + schema_names_serde_size(slots[0]) + ray_serde_size(slots[1]); + int64_t schema = schema_names_serde_size(slots[0]); + if (schema <= 0) return schema; + int64_t cols = ray_serde_size(slots[1]); + if (cols <= 0) return cols; + return 1 + 1 + schema + cols; } case RAY_DICT: { /* type + attrs + keys(recursive) + vals(recursive) */ ray_t** slots = (ray_t**)ray_data(obj); - return 1 + 1 + ray_serde_size(slots[0]) + ray_serde_size(slots[1]); + int64_t keys = ray_serde_size(slots[0]); + if (keys <= 0) return keys; + int64_t vals = ray_serde_size(slots[1]); + if (vals <= 0) return vals; + return 1 + 1 + keys + vals; } case RAY_LAMBDA: { ray_t** slots = (ray_t**)ray_data(obj); - int64_t size = 1 + 1 + ray_serde_size(slots[0]) + ray_serde_size(slots[1]); - if (LAMBDA_CLOSURE(obj)) size += ray_serde_size(LAMBDA_CLOSURE(obj)); + int64_t params = ray_serde_size(slots[0]); + if (params <= 0) return params; + int64_t body = ray_serde_size(slots[1]); + if (body <= 0) return body; + int64_t size = 1 + 1 + params + body; + if (LAMBDA_CLOSURE(obj)) { + int64_t closure = ray_serde_size(LAMBDA_CLOSURE(obj)); + if (closure <= 0) return closure; + size += closure; + } return size; } case RAY_UNARY: @@ -382,13 +403,14 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { } int8_t type = obj->type; - buf[0] = (uint8_t)type; - buf++; /* Atoms — format: type(1) + flags(1) + value-bytes. `flags` bit 0 * 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; + buf[0] = (uint8_t)type; + buf++; uint8_t aflags = (uint8_t)(obj->aux[0] & 1); if (type == -RAY_SYM && (obj->attrs & ATTR_QUOTED)) aflags |= ATTR_QUOTED; @@ -459,6 +481,8 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { /* Vectors and compound types */ int64_t c; + buf[0] = (uint8_t)type; + buf++; /* Attrs byte: preserve HAS_NULLS; clear SLICE / ARENA (internal flags). */ uint8_t wire_attrs = obj->attrs & (RAY_ATTR_HAS_NULLS); @@ -575,8 +599,11 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { buf += 8; ray_t** elems = (ray_t**)ray_data(obj); c = 0; - for (int64_t i = 0; i < obj->len; i++) - c += ray_ser_raw(buf + c, elems[i]); + for (int64_t i = 0; i < obj->len; i++) { + int64_t child = ray_ser_raw(buf + c, elems[i]); + if (child <= 0) return child; + c += child; + } return 1 + 1 + 8 + c; } @@ -586,7 +613,10 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { buf++; ray_t** slots = (ray_t**)ray_data(obj); c = ser_schema_names(buf, slots[0]); /* schema names as RAY_SYM vector */ - c += ray_ser_raw(buf + c, slots[1]); /* cols (RAY_LIST) */ + if (c <= 0) return c; + int64_t cols = ray_ser_raw(buf + c, slots[1]); /* cols (RAY_LIST) */ + if (cols <= 0) return cols; + c += cols; return 1 + 1 + c; } @@ -595,7 +625,10 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { buf++; ray_t** slots = (ray_t**)ray_data(obj); c = ray_ser_raw(buf, slots[0]); - c += ray_ser_raw(buf + c, slots[1]); + if (c <= 0) return c; + int64_t vals = ray_ser_raw(buf + c, slots[1]); + if (vals <= 0) return vals; + c += vals; return 1 + 1 + c; } @@ -604,9 +637,15 @@ int64_t ray_ser_raw(uint8_t* buf, ray_t* obj) { buf++; ray_t** slots = (ray_t**)ray_data(obj); c = ray_ser_raw(buf, slots[0]); /* params */ - c += ray_ser_raw(buf + c, slots[1]); /* body */ - if (LAMBDA_CLOSURE(obj)) - c += ray_ser_raw(buf + c, LAMBDA_CLOSURE(obj)); + if (c <= 0) return c; + int64_t body = ray_ser_raw(buf + c, slots[1]); /* body */ + if (body <= 0) return body; + c += body; + if (LAMBDA_CLOSURE(obj)) { + int64_t closure = ray_ser_raw(buf + c, LAMBDA_CLOSURE(obj)); + if (closure <= 0) return closure; + c += closure; + } return 1 + 1 + c; } diff --git a/src/store/splay.c b/src/store/splay.c index 4fe29bc10..32c00ae39 100644 --- a/src/store/splay.c +++ b/src/store/splay.c @@ -1,3 +1,6 @@ +#if !defined(_WIN32) && !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 200809L +#endif /* * Copyright (c) 2025-2026 Anton Kundenko * All rights reserved. @@ -32,6 +35,7 @@ #include "table/table.h" #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" @@ -40,8 +44,11 @@ #include #include #include +#include #include #include +#include +#include /* -------------------------------------------------------------------------- * Splayed table: directory of column files + .d schema file @@ -145,9 +152,177 @@ static void splay_sweep_stale(ray_t* tbl, const char* dir) { closedir(d); } -static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_path, - bool durable) { - if (!tbl || RAY_IS_ERR(tbl)) return RAY_ERR_TYPE; +/* A published splayed table may contain more than one physical generation. + * The small text manifest is the only mutable table-level pointer: data files + * are written below .generations/ first, then .current is replaced with + * one filesystem rename. Readers that predate this format continue to use + * the legacy directory when .current is absent. */ +static _Atomic unsigned long splay_generation_seq; + +static ray_err_t splay_current_dir(const char* dir, char* out, size_t out_sz, + bool* active) { + char manifest[1024]; + int n = snprintf(manifest, sizeof(manifest), "%s/.current", dir); + if (n < 0 || (size_t)n >= sizeof(manifest) || !out || !active) + return RAY_ERR_RANGE; + *active = false; + + FILE* f = fopen(manifest, "rb"); + if (!f) { + if (errno == ENOENT) return RAY_OK; /* legacy splayed directory */ + return RAY_ERR_IO; + } + + char rel[512]; + size_t len = fread(rel, 1, sizeof(rel), f); + bool failed = ferror(f) != 0; + int closed = fclose(f); + if (failed || closed != 0 || len == 0 || len >= sizeof(rel)) { + return RAY_ERR_CORRUPT; + } + if (rel[len - 1] == '\n') len--; + rel[len] = '\0'; + if (strncmp(rel, ".generations/", 13) != 0 || + len <= 13 || memchr(rel, '\0', len)) + return RAY_ERR_CORRUPT; + for (size_t i = 13; i < len; i++) + if (!((rel[i] >= '0' && rel[i] <= '9') || rel[i] == 'g' || rel[i] == '-')) + return RAY_ERR_CORRUPT; + + n = snprintf(out, out_sz, "%s/%s", dir, rel); + if (n < 0 || (size_t)n >= out_sz) return RAY_ERR_RANGE; + *active = true; + return RAY_OK; +} + +ray_err_t ray_splay_resolve_dir(const char* dir, char* out, size_t out_sz) { + if (!dir || !out || !out_sz) return RAY_ERR_IO; + bool active; + ray_err_t err = splay_current_dir(dir, out, out_sz, &active); + if (err != RAY_OK || active) return err; + int n = snprintf(out, out_sz, "%s", dir); + return n < 0 || (size_t)n >= out_sz ? RAY_ERR_RANGE : RAY_OK; +} + +static ray_err_t splay_publish_generation(const char* dir, const char* gen, + bool durable) { + char manifest[1024], tmp[1024]; + int n = snprintf(manifest, sizeof(manifest), "%s/.current", dir); + if (n < 0 || (size_t)n >= sizeof(manifest)) return RAY_ERR_RANGE; + /* The exclusively created generation owns this temporary file. */ + n = snprintf(tmp, sizeof(tmp), "%s/%s/.current.tmp", dir, gen); + if (n < 0 || (size_t)n >= sizeof(tmp)) return RAY_ERR_RANGE; + + FILE* f = fopen(tmp, "wb"); + if (!f) return RAY_ERR_IO; + size_t len = strlen(gen); + bool ok = fwrite(gen, 1, len, f) == len && fputc('\n', f) != EOF; + if (ok && fflush(f) != 0) ok = false; + if (fclose(f) != 0) ok = false; + if (!ok) { + (void)remove(tmp); + return RAY_ERR_IO; + } + + ray_fd_t fd = ray_file_open(tmp, RAY_OPEN_READ | RAY_OPEN_WRITE); + if (fd == RAY_FD_INVALID) { + (void)remove(tmp); + return RAY_ERR_IO; + } + ray_err_t err = durable ? ray_file_sync(fd) : RAY_OK; + ray_file_close(fd); + if (err != RAY_OK || ray_file_rename(tmp, manifest) != RAY_OK) { + (void)remove(tmp); + return RAY_ERR_IO; + } + return durable ? ray_file_sync_dir(manifest) : RAY_OK; +} + +static ray_err_t splay_has_file(const char* dir, const char* name, bool* exists) { + char path[1024]; + int n = snprintf(path, sizeof(path), "%s/%s", dir, name); + if (n < 0 || (size_t)n >= sizeof(path)) return RAY_ERR_RANGE; + struct stat st; + *exists = stat(path, &st) == 0; + return *exists || errno == ENOENT ? RAY_OK : RAY_ERR_IO; +} + +static void splay_remove_tree_best_effort(const char* path) { + DIR* d = opendir(path); + if (!d) { + (void)unlink(path); + return; + } + struct dirent* entry; + while ((entry = readdir(d))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + char child[1024]; + int n = snprintf(child, sizeof(child), "%s/%s", path, entry->d_name); + if (n < 0 || (size_t)n >= sizeof(child)) continue; + struct stat st; +#ifdef RAY_OS_WINDOWS + if (stat(child, &st) != 0) continue; +#else + if (lstat(child, &st) != 0) continue; +#endif + if (S_ISDIR(st.st_mode)) splay_remove_tree_best_effort(child); + else (void)unlink(child); + } + closedir(d); + (void)rmdir(path); +} + +static bool splay_generation_is_current(const ray_splay_write_t* write) { + char current[1024]; + bool active = false; + return write && write->staged && write->dir[0] && + splay_current_dir(write->root, current, sizeof(current), &active) == RAY_OK && + active && strcmp(current, write->dir) == 0; +} + +static void splay_retire_legacy_schema(const char* root) { + char schema[1024], retired[1024]; + int n = snprintf(schema, sizeof(schema), "%s/.d", root); + int m = snprintf(retired, sizeof(retired), "%s/.legacy.d", root); + if (n < 0 || (size_t)n >= sizeof(schema) || + m < 0 || (size_t)m >= sizeof(retired)) + return; + if (access(schema, F_OK) != 0) return; + (void)unlink(retired); + if (rename(schema, retired) != 0) + (void)unlink(schema); +} + +static void splay_prune_generations(const char* root, const char* current, + const char* previous) { + char generations[1024]; + int n = snprintf(generations, sizeof(generations), "%s/.generations", root); + if (n < 0 || (size_t)n >= sizeof(generations)) return; + DIR* d = opendir(generations); + if (!d) return; + + struct dirent* entry; + while ((entry = readdir(d))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + char rel[256], full[1024]; + int rn = snprintf(rel, sizeof(rel), ".generations/%s", entry->d_name); + int fn = snprintf(full, sizeof(full), "%s/%s", root, rel); + if (rn < 0 || (size_t)rn >= sizeof(rel) || + fn < 0 || (size_t)fn >= sizeof(full)) + continue; + if ((current && strcmp(rel, current) == 0) || + (previous && strcmp(full, previous) == 0)) + continue; + splay_remove_tree_best_effort(full); + } + closedir(d); +} + +static ray_err_t splay_validate_save(ray_t* tbl, const char* dir, + const char* sym_path) { + if (!tbl || RAY_IS_ERR(tbl) || tbl->type != RAY_TABLE) return RAY_ERR_TYPE; if (!dir) return RAY_ERR_IO; ray_err_t name_err = splay_validate_persisted_names(tbl); @@ -201,6 +376,14 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa } } + return RAY_OK; +} + +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); + 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 * caller hasn't pre-created the date partition. */ @@ -254,7 +437,7 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa } } - ray_err_t sym_err = ray_sym_domain_flush(dom, durable); + 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; @@ -263,13 +446,7 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa int64_t ncols = ray_table_ncols(tbl); - /* 2. Column files (and the schema names they correspond to). - * NOTE: overwriting an existing dir rewrites columns in place; a crash - * mid-loop leaves old .d + a mix of old/new column files. Ragged - * lengths are caught at load (column-length check); equal-length - * mixed-generation rows are inherent to in-place overwrite and would - * need staged writes — out of scope (fresh-dir crashes degrade to a - * visibly missing table via the .d-last commit marker). */ + /* 2. Write the column files in the caller's unpublished directory. */ ray_t* schema = ray_vec_new(RAY_STR, ncols > 0 ? ncols : 1); if (!schema || RAY_IS_ERR(schema)) { if (schema) ray_release(schema); @@ -300,9 +477,7 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa : (durable ? ray_col_save(col, path) : ray_col_save_bulk(col, path)); if (err != RAY_OK) { - /* No new .d is written. Preflight prevents deterministic format - * failures here; an I/O error or crash can still leave an - * existing directory with mixed-generation column files. */ + /* No new .d or .current is published on failure. */ ray_release(schema); if (dom) ray_sym_domain_release(dom); return err; @@ -316,6 +491,12 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa } if (dom) ray_sym_domain_release(dom); + /* 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. */ + if (build_indexes) + ray_splay_build_indexes(dir, tbl); + /* 3. .d LAST — the commit marker. */ { char path[1024]; @@ -336,6 +517,352 @@ static ray_err_t splay_save_impl(ray_t* tbl, const char* dir, const char* sym_pa return RAY_OK; } +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); +} + +#ifdef RAY_OS_WINDOWS +#define SPLAY_IS_SEP(c) ((c) == '/' || (c) == '\\') +#else +#define SPLAY_IS_SEP(c) ((c) == '/') +#endif + +/* Record the shallowest component of `root` that does not exist yet, so a + * failed first write can remove the directories it created. Nothing is + * recorded when a ".." follows it: root would then lie outside it. */ +static void splay_find_missing(const char* root, char* out, size_t out_sz) { + out[0] = '\0'; + size_t len = strlen(root); + if (len >= out_sz) return; + char buf[1024]; + memcpy(buf, root, len + 1); + struct stat st; + size_t i = 1; + for (; i <= len; i++) { + if (i < len && !SPLAY_IS_SEP(buf[i])) continue; + char saved = buf[i]; + buf[i] = '\0'; + bool missing = stat(buf, &st) != 0 && errno == ENOENT; + buf[i] = saved; + if (missing) break; + } + if (i > len) return; + for (size_t j = i; j < len; j++) + if (SPLAY_IS_SEP(root[j]) && root[j + 1] == '.' && root[j + 2] == '.' && + (root[j + 3] == '\0' || SPLAY_IS_SEP(root[j + 3]))) + return; + memcpy(out, root, i); + out[i] = '\0'; +} + +/* An in-place write goes to a directory that may have been there before this + * writer: an operator pre-made it, or an earlier first write was killed and + * left its lock file and partial columns. Nothing says what else it holds + * (a database root has no .d either), so a failed write removes only what + * this writer produced: every entry whose inode was not in the directory + * when the lock was taken. Column files are renamed into place, so a + * leftover this writer rewrote has a new inode and goes with the rest. + * Taken under the lock, right after it. */ +static int splay_ino_cmp(const void* a, const void* b) { + uint64_t x = *(const uint64_t*)a, y = *(const uint64_t*)b; + return x < y ? -1 : x > y; +} + +static void splay_snapshot_root(ray_splay_write_t* write) { + write->before = NULL; + write->nbefore = 0; + write->before_known = false; + DIR* d = opendir(write->root); + if (!d) return; + size_t cap = 0; + bool ok = true; + struct dirent* entry; + while ((entry = readdir(d))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + char child[1100]; + int n = snprintf(child, sizeof(child), "%s/%s", write->root, entry->d_name); + if (n < 0 || (size_t)n >= sizeof(child)) { ok = false; break; } + struct stat st; + if (stat(child, &st) != 0) { + if (errno == ENOENT) continue; /* removed while listing */ + ok = false; + break; + } + if (write->nbefore == cap) { + cap = cap ? cap * 2 : 16; + uint64_t* grown = ray_realloc_raw(write->before, cap * sizeof(uint64_t)); + if (!grown) { ok = false; break; } + write->before = grown; + } + write->before[write->nbefore++] = (uint64_t)st.st_ino; + } + closedir(d); + if (ok && write->nbefore > 1) + qsort(write->before, write->nbefore, sizeof(uint64_t), splay_ino_cmp); + write->before_known = ok; +} + +static bool splay_was_there(const ray_splay_write_t* write, uint64_t ino) { + size_t lo = 0, hi = write->nbefore; + while (lo < hi) { + size_t mid = lo + (hi - lo) / 2; + if (write->before[mid] < ino) lo = mid + 1; + else hi = mid; + } + return lo < write->nbefore && write->before[lo] == ino; +} + +/* A failed first write removes the table directory and every directory begin + * created above it, so no partition without a schema is left behind. The + * lock holder first empties the table directory of what it produced, all + * but its lock file: everything, when begin created the directory; else + * what the snapshot does not know. Without a snapshot nothing goes. */ +static void splay_clear_created(const ray_splay_write_t* write) { + bool all = write->created[0]; + if (!all && !write->before_known) return; + DIR* d = opendir(write->root); + if (!d) return; + struct dirent* entry; + while ((entry = readdir(d))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0 || + strcmp(entry->d_name, ".write.lock") == 0) + continue; + char child[1100]; + int n = snprintf(child, sizeof(child), "%s/%s", write->root, entry->d_name); + if (n < 0 || (size_t)n >= sizeof(child)) continue; + if (!all) { + struct stat st; + if (stat(child, &st) != 0 || splay_was_there(write, (uint64_t)st.st_ino)) + continue; + } + splay_remove_tree_best_effort(child); + } + closedir(d); +} + +/* Nothing but the lock file left? */ +static bool splay_root_is_bare(const ray_splay_write_t* write) { + DIR* d = opendir(write->root); + if (!d) return false; + bool bare = true; + struct dirent* entry; + while (bare && (entry = readdir(d))) { + if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 && + strcmp(entry->d_name, ".write.lock") != 0) + bare = false; + } + closedir(d); + return bare; +} + +/* Then the lock file goes, last: a waiter on it finds it unlinked and starts + * over, and a writer that creates a new one keeps the directory, which is + * then removed only while empty, like every directory above it. A directory + * that still holds anything else keeps its lock file too. Without the lock + * (begin failed before taking it) nothing but empty directories goes, and + * the lock file only when nobody can hold it. Directories above a table + * directory that was there before the write are not this writer's. */ +static void splay_remove_created(const ray_splay_write_t* write, bool unlink_lock) { + if (!splay_root_is_bare(write)) return; + if (unlink_lock) { + char lock[1100]; + int n = snprintf(lock, sizeof(lock), "%s/.write.lock", write->root); + if (n > 0 && (size_t)n < sizeof(lock)) (void)unlink(lock); + } + if (rmdir(write->root) != 0 || !write->created[0]) return; + size_t stop = strlen(write->created); + char path[1024]; + memcpy(path, write->root, strlen(write->root) + 1); + for (;;) { + size_t k = strlen(path); + while (k > 0 && !SPLAY_IS_SEP(path[k - 1])) k--; + if (k == 0 || k - 1 < stop) break; + path[k - 1] = '\0'; + if (rmdir(path) != 0) break; + } +} + +ray_err_t ray_splay_write_finish(ray_splay_write_t* write, ray_err_t result, + bool durable) { + char previous[1024]; + bool had_previous = false; + if (result == RAY_OK && write->staged) { + if (splay_current_dir(write->root, previous, sizeof(previous), + &had_previous) != RAY_OK) + had_previous = false; + /* ray_file_sync_dir syncs the PARENT of its argument. */ + char schema[1100]; + snprintf(schema, sizeof(schema), "%s/.d", write->dir); + if (durable && (ray_file_sync_dir(schema) != RAY_OK || + ray_file_sync_dir(write->dir) != RAY_OK)) + result = RAY_ERR_IO; + if (result == RAY_OK) + result = splay_publish_generation(write->root, write->generation, durable); + if (result == RAY_OK) { + splay_retire_legacy_schema(write->root); + splay_prune_generations(write->root, write->generation, + had_previous ? previous : NULL); + } + } + if (result != RAY_OK && write->staged && write->dir[0] && + !splay_generation_is_current(write)) { + splay_remove_tree_best_effort(write->dir); + } + /* The lock holder clears what it produced in the table directory; + * without the lock only the empty directories begin created go. The + * schema check is repeated here, under the lock: `created` was recorded + * before the lock was taken, and a stat error in begin must not clear a + * table another writer published meanwhile. */ + bool locked = write->locked; + bool drop_created = result != RAY_OK && !write->staged && + (locked || write->created[0]); + if (drop_created && locked) { + bool schema = false, current = false; + if (splay_has_file(write->root, ".d", &schema) != RAY_OK || + splay_has_file(write->root, ".current", ¤t) != RAY_OK || + schema || current) + drop_created = false; + else + splay_clear_created(write); + } + if (write->before) { + ray_free_raw(write->before); + write->before = NULL; + write->nbefore = 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 + * unlinked and starts over (see ray_splay_write_begin). */ + if (drop_created) splay_remove_created(write, unlink_lock); +#endif + if (write->lock != RAY_FD_INVALID) { + if (write->locked) (void)ray_file_unlock(write->lock); + ray_file_close(write->lock); + write->lock = RAY_FD_INVALID; + write->locked = false; + } +#ifdef RAY_OS_WINDOWS + /* Windows cannot delete the open lock file. */ + if (drop_created) splay_remove_created(write, unlink_lock); +#endif + return result; +} + +ray_err_t ray_splay_write_begin(const char* dir, ray_splay_write_t* write) { + memset(write, 0, sizeof(*write)); + write->lock = RAY_FD_INVALID; + if (!dir || !*dir) return RAY_ERR_IO; + int n = snprintf(write->root, sizeof(write->root), "%s", dir); + if (n < 0 || (size_t)n >= sizeof(write->root)) return RAY_ERR_RANGE; + size_t len = strlen(write->root); + while (len > 1 && write->root[len - 1] == '/') write->root[--len] = '\0'; + + char path[1024]; + n = snprintf(path, sizeof(path), "%s/.write.lock", write->root); + if (n < 0 || (size_t)n >= sizeof(path)) return RAY_ERR_RANGE; + ray_err_t err = RAY_ERR_IO; + for (int attempt = 0; attempt < 8 && !write->locked; attempt++) { + splay_find_missing(write->root, write->created, sizeof(write->created)); + err = ray_mkdir_p(write->root); + if (err != RAY_OK) { +#ifndef RAY_OS_WINDOWS + /* A failed first write of a sibling removed a new parent + * between our mkdirs: create it again. */ + if (errno == ENOENT) continue; +#endif + return ray_splay_write_finish(write, err, false); + } + write->lock = ray_file_open(path, RAY_OPEN_READ | RAY_OPEN_WRITE | RAY_OPEN_CREATE); + if (write->lock == RAY_FD_INVALID) { + err = RAY_ERR_IO; + if (errno == ENOENT) continue; + return ray_splay_write_finish(write, err, false); + } + err = ray_file_lock_ex(write->lock); + if (err != RAY_OK) { + /* A wait cut short (EINTR) is retried without waiting. When + * that fails for any reason but another holder, locking itself + * is broken, so nobody holds this lock file either and a + * directory created for it can go with it (see finish); + * otherwise it stays, as it would admit a second writer. */ + if (ray_file_trylock_ex(write->lock) == RAY_OK) { + err = RAY_OK; + } else { +#ifndef RAY_OS_WINDOWS + write->unlink_lock = errno != EWOULDBLOCK && errno != EAGAIN && + write->created[0]; +#endif + return ray_splay_write_finish(write, err, false); + } + } + write->locked = true; +#ifndef RAY_OS_WINDOWS + /* A failed first write removes the directory with its lock file + * while holding the lock; a waiter then holds a lock on a file + * nobody else can find. Drop it and start over. */ + struct stat held, named; + if (fstat(write->lock, &held) != 0 || stat(path, &named) != 0 || + held.st_ino != named.st_ino || held.st_dev != named.st_dev) { + (void)ray_file_unlock(write->lock); + ray_file_close(write->lock); + write->lock = RAY_FD_INVALID; + write->locked = false; + err = RAY_ERR_IO; + } +#endif + } + if (!write->locked) return ray_splay_write_finish(write, err, false); + + bool schema, current; + err = splay_has_file(write->root, ".d", &schema); + 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; + if (!write->staged) { + splay_snapshot_root(write); + memcpy(write->dir, write->root, len + 1); + return RAY_OK; + } + n = snprintf(path, sizeof(path), "%s/.generations", write->root); + if (n < 0 || (size_t)n >= sizeof(path)) + return ray_splay_write_finish(write, RAY_ERR_RANGE, false); + err = ray_mkdir_p(path); + if (err != RAY_OK) return ray_splay_write_finish(write, err, false); + + for (;;) { + unsigned long seq = atomic_fetch_add(&splay_generation_seq, 1); + snprintf(write->generation, sizeof(write->generation), ".generations/g-%lu-%lu-%lu", + (unsigned long)time(NULL), (unsigned long)getpid(), seq); + n = snprintf(write->dir, sizeof(write->dir), "%s/%s", write->root, write->generation); + if (n < 0 || (size_t)n >= sizeof(write->dir)) + return ray_splay_write_finish(write, RAY_ERR_RANGE, false); +#ifdef RAY_OS_WINDOWS + if (CreateDirectoryA(write->dir, NULL)) break; + if (GetLastError() != ERROR_ALREADY_EXISTS) +#else + if (mkdir(write->dir, 0755) == 0) break; + if (errno != EEXIST) +#endif + return ray_splay_write_finish(write, RAY_ERR_IO, false); + /* Never reuse an existing generation, including after PID reuse. */ + } + return RAY_OK; +} + +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); + if (err != RAY_OK) return err; + ray_splay_write_t write; + err = ray_splay_write_begin(dir, &write); + if (err != RAY_OK) return err; + err = ray_splay_write_table(tbl, write.dir, 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); } @@ -344,6 +871,10 @@ 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); } +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); +} + /* -------------------------------------------------------------------------- * splay_load_impl — shared implementation for ray_splay_load / ray_read_splayed * @@ -488,6 +1019,13 @@ static ray_t* splay_load_dom_impl(const char* dir, ray_sym_domain_t* dom, * unopenable/invalid file → loud error. */ static ray_t* splay_load_impl(const char* dir, const char* sym_path, bool use_mmap) { + char resolved[1024]; + ray_err_t err = ray_splay_resolve_dir(dir, resolved, sizeof(resolved)); + if (err != RAY_OK) + return ray_error(ray_err_code_str(err), "cannot resolve splayed generation"); + /* Resolve first: a newly published generation can reference symbols + * appended since a previous domain open. Opening afterwards refreshes + * the cached domain before any of those column codes are validated. */ ray_sym_domain_t* dom = NULL; if (sym_path) { struct stat st; @@ -499,7 +1037,7 @@ static ray_t* splay_load_impl(const char* dir, const char* sym_path, "record, or missing \"\" at position 0)", sym_path); } } - ray_t* tbl = splay_load_dom_impl(dir, dom, use_mmap); + ray_t* tbl = splay_load_dom_impl(resolved, dom, use_mmap); if (dom) ray_sym_domain_release(dom); /* columns hold their own refs */ return tbl; } @@ -720,5 +1258,47 @@ ray_t* ray_read_splayed(const char* dir, const char* sym_path) { } ray_t* ray_read_splayed_dom(const char* dir, struct ray_sym_domain_s* dom) { - return splay_load_dom_impl(dir, dom, true); + char resolved[1024]; + ray_err_t err = ray_splay_resolve_dir(dir, resolved, sizeof(resolved)); + if (err != RAY_OK) + return ray_error(ray_err_code_str(err), "cannot resolve splayed generation"); + ray_sym_domain_t* fresh = NULL; + const char* path = dom ? ray_sym_domain_path(dom) : NULL; + if (path) { + fresh = ray_sym_domain_open(path); + if (!fresh) return ray_error("corrupt", "cannot refresh splayed symfile"); + dom = fresh; + } + ray_t* tbl = splay_load_dom_impl(resolved, dom, true); + if (fresh) ray_sym_domain_release(fresh); + return 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; } + ray_err_t err = RAY_ERR_IO; + int64_t t1 = trace ? ray_profile_now_ns() : 0; + ray_t* hi = ray_idx_hash_fn(col); + int64_t t2 = trace ? ray_profile_now_ns() : 0; + if (hi && !RAY_IS_ERR(hi) && (hi->attrs & RAY_ATTR_HAS_INDEX)) { + err = ray_col_append_index(path, ray_index_payload(hi->index), hi->len, hi->type); + if (trace) { + const ray_index_t* hx = ray_index_payload(hi->index); + fprintf(stderr, "splayed hash: file=%s rows=%" PRId64 " keys=%" PRId64 " groups=%" PRId64 + " mmap=%.1fms build=%.1fms write=%.1fms\n", + path, hi->len, hx->u.hash.n_keys, hx->u.hash.n_groups, + (double)(t1 - t0) / 1e6, (double)(t2 - t1) / 1e6, (double)(ray_profile_now_ns() - t2) / 1e6); + } + ray_release(hi); + } else if (hi) { + if (RAY_IS_ERR(hi)) ray_error_free(hi); else ray_release(hi); + } + 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 59c5e78f7..03813b9dd 100644 --- a/src/store/splay.h +++ b/src/store/splay.h @@ -25,9 +25,37 @@ #define RAY_SPLAY_H #include +#include "store/fileio.h" struct ray_sym_domain_s; +/* Internal publication protocol shared by the table and streaming CSV writers. + * begin serializes writers; finish publishes only on success and always unlocks. + * Publication keeps the current generation and one previous generation; older + * staged directories are removed best-effort after each successful publish. */ +typedef struct { + ray_fd_t lock; + bool locked; + bool unlink_lock; /* lock failed with nobody holding it: remove the file */ + bool staged; + uint64_t* before; /* in-place: inodes in root when the lock was taken */ + size_t nbefore; + bool before_known; + char root[1024]; + char created[1024]; /* shallowest directory of root begin created */ + char dir[1024]; + char generation[256]; +} ray_splay_write_t; + +ray_err_t ray_splay_write_begin(const char* dir, 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); +/* Resolve once and retain the returned path for the entire read. */ +ray_err_t ray_splay_resolve_dir(const char* dir, char* out, size_t out_sz); + /* Splayed table I/O. * * sym_path names the table's symfile (domain): save distinct-merges the @@ -37,15 +65,24 @@ struct ray_sym_domain_s; * with no resolvable symfile is a loud "sym" error. */ ray_err_t ray_splay_save(ray_t* tbl, const char* dir, const char* sym_path); 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); ray_t* ray_splay_load(const char* dir, const char* sym_path); ray_t* ray_read_splayed(const char* dir, const char* sym_path); -/* Append chunk-zone index regions to a freshly-streamed splayed store's column - * files so later mmap loads get block-skip. Best-effort, per numeric column. */ +/* Append chunk-zone index regions to the column files of a splayed store + * written from a resident table, so later mmap loads get block-skip. Used by + * `.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); -/* Partition loader entry: the parted reader opens root/sym ONCE and - * passes the shared domain to every partition's columns. */ +/* Loader accepting a shared FILE domain. It resolves the generation first, + * then refreshes the cached domain to include any externally appended symbols. */ ray_t* ray_read_splayed_dom(const char* dir, struct ray_sym_domain_s* dom); #endif /* RAY_SPLAY_H */ diff --git a/src/store/stream.c b/src/store/stream.c new file mode 100644 index 000000000..884bd1456 --- /dev/null +++ b/src/store/stream.c @@ -0,0 +1,463 @@ +/* Copyright (c) 2026 Anton Kundenko. MIT license; see LICENSE. + * Shared by CSV and Parquet native conversion. */ +#include "stream.h" +#include "ops/hash.h" +#include "store/col.h" +#include "store/fileio.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" +#include +#include + +#define COL_STREAM_LUT_BITS 19 +#define COL_STREAM_LUT (1u << COL_STREAM_LUT_BITS) + +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) { + memset(w, 0, sizeof(*w)); + w->type = type; + w->attrs = (type == RAY_SYM) ? RAY_SYM_W32 : 0; + w->dom = dom; + if (type == RAY_SYM && !dom) return RAY_ERR_IO; + + ray_t* name_atom = ray_sym_str(name_id); + if (!name_atom) return RAY_ERR_CORRUPT; + const char* name = ray_str_ptr(name_atom); + size_t name_len = ray_str_len(name_atom); + if (name_len == 0 || name[0] == '.' || + memchr(name, '/', name_len) || memchr(name, '\\', name_len) || + memchr(name, '\0', name_len)) + return RAY_ERR_DOMAIN; + + int n = snprintf(w->path, sizeof(w->path), "%s/%.*s", + dir, (int)name_len, name); + if (n < 0 || (size_t)n >= sizeof(w->path)) return RAY_ERR_RANGE; + n = snprintf(w->tmp_path, sizeof(w->tmp_path), "%s/.stream-%.*s.col", dir, (int)name_len, name); + if (n < 0 || (size_t)n >= sizeof(w->tmp_path)) return RAY_ERR_RANGE; + n = snprintf(w->pool_path, sizeof(w->pool_path), "%s/.stream-%.*s.pool", dir, (int)name_len, name); + if (n < 0 || (size_t)n >= sizeof(w->pool_path)) return RAY_ERR_RANGE; + + w->fp = fopen(w->tmp_path, "wb+"); + if (!w->fp) return RAY_ERR_IO; + ray_t zero = {0}; + if (fwrite(&zero, 1, 32, w->fp) != 32) return RAY_ERR_IO; + if (type == RAY_SYM) { + /* best effort: without the cache every cell probes the domain */ + w->lut_id = (int64_t*)ray_alloc_raw((size_t)COL_STREAM_LUT * sizeof(int64_t)); + w->lut_pos = (uint32_t*)ray_alloc_raw((size_t)COL_STREAM_LUT * sizeof(uint32_t)); + if (!w->lut_id || !w->lut_pos) { + ray_free_raw(w->lut_id); ray_free_raw(w->lut_pos); + w->lut_id = NULL; w->lut_pos = NULL; + } else { + memset(w->lut_id, 0xff, (size_t)COL_STREAM_LUT * sizeof(int64_t)); + } + } + return RAY_OK; +} + +static void ray_col_stream_drop_lut(ray_col_stream_t* w) { + ray_free_raw(w->lut_id); ray_free_raw(w->lut_pos); + w->lut_id = NULL; w->lut_pos = NULL; +} + +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->type == RAY_STR) { + 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); + if (err != RAY_OK) { ray_free_raw(w->dict); w->dict = NULL; } + return err; + } + if (!ray_zone_acc_supported(w->type)) return RAY_OK; + w->zone = (ray_zone_acc_t*)ray_alloc_raw(sizeof(*w->zone)); + if (!w->zone) return RAY_ERR_OOM; + ray_err_t err = ray_zone_acc_init(w->zone, w->type, start_row); + if (err != RAY_OK) { ray_free_raw(w->zone); w->zone = NULL; } + return err; +} + +ray_err_t ray_col_stream_index_merge(ray_col_stream_t* dst, ray_col_stream_t* src) { + if (!src->zone) return RAY_OK; + ray_err_t err = dst->zone ? ray_zone_acc_merge(dst->zone, src->zone) : RAY_ERR_DOMAIN; + ray_zone_acc_free(src->zone); ray_free_raw(src->zone); src->zone = NULL; + return err; +} + +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, + ray_t* col) { + if (!w->fp || !col || RAY_IS_ERR(col) || (col->type != w->type && !(w->type == RAY_SYM && col->type == RAY_STR)) || (col->attrs & RAY_ATTR_SLICE)) return RAY_ERR_TYPE; + int64_t n = col->len; + if (n < 0 || n > INT64_MAX-w->rows) return RAY_ERR_RANGE; + + if (w->type == RAY_SYM && col->type == RAY_STR) { + /* Import strings directly into the file domain, avoiding a second + * global runtime dictionary and a runtime-id-to-file-id pass. */ + enum { BATCH = 8192 }; + const char* strings[BATCH]; size_t lengths[BATCH]; + uint32_t hashes[BATCH], positions[BATCH]; int64_t ids[BATCH]; + for (int64_t off = 0; off < n; off += BATCH) { + if (ray_interrupted()) return RAY_ERR_CANCEL; + int64_t count = n-off < BATCH ? n-off : BATCH; + for (int64_t i = 0; i < count; i++) { + strings[i] = ray_str_vec_get(col,off+i,&lengths[i]); + hashes[i] = (uint32_t)ray_hash_bytes(strings[i],lengths[i]); + } + if (!ray_sym_domain_intern_batch(w->dom,count,strings,lengths,hashes,ids)) return 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; + positions[i] = (uint32_t)ids[i]; if (!ids[i]) w->had_nulls = true; + } + if (fwrite(positions,sizeof(*positions),(size_t)count,w->fp) != (size_t)count) return RAY_ERR_IO; + } + } else if (w->type == RAY_STR) { + uint64_t bytes = col->str_pool ? (uint64_t)col->str_pool->len : 0; + if (bytes > UINT32_MAX-w->pool_bytes) return RAY_ERR_RANGE; + const ray_str_t* src = ray_data(col); + ray_str_t buf[1024]; + for (int64_t off = 0; off < n;) { + if (ray_interrupted()) return RAY_ERR_CANCEL; + int64_t count = n-off < 1024 ? n-off : 1024; + memcpy(buf,src+off,(size_t)count*sizeof(*buf)); + for (int64_t i = 0; i < count; i++) { + if (buf[i].len > RAY_STR_INLINE_MAX) { + if (buf[i].pool_off > bytes || buf[i].len > bytes-buf[i].pool_off) return RAY_ERR_CORRUPT; + buf[i].pool_off += (uint32_t)w->pool_bytes; + } + if (!buf[i].len) w->had_nulls = true; + } + if (fwrite(buf,sizeof(*buf),(size_t)count,w->fp) != (size_t)count) return RAY_ERR_IO; + off += count; + } + if (bytes) { + if (!w->pool_fp) w->pool_fp = fopen(w->pool_path,"wb+"); + if (!w->pool_fp || fwrite(ray_data(col->str_pool),1,(size_t)bytes,w->pool_fp) != bytes) return RAY_ERR_IO; + } + w->pool_bytes += bytes; + } else if (w->type == RAY_SYM) { + /* Encode cells as positions in the target symfile's domain: + * resolve each cell through the chunk vec's own domain and + * find-or-append into the target (distinct work rides the + * write). The domain is flushed before the column files are + * committed (close), preserving the sym-first crash ordering. + * A runtime-domain chunk vec goes through the id -> position + * cache: only a value's first encounter pays the domain probe. */ + bool direct = ray_sym_vec_domain(col) == w->dom; + bool cached = ray_sym_vec_domain(col) == ray_sym_runtime_domain() && w->lut_id; + const void* cd = ray_data(col); + uint32_t buf[8192]; + for (int64_t off = 0; off < n; ) { + int64_t cnt = n - off; + if (cnt > (int64_t)(sizeof(buf) / sizeof(buf[0]))) + cnt = (int64_t)(sizeof(buf) / sizeof(buf[0])); + for (int64_t i = 0; i < cnt; i++) { + int64_t pos; + if (direct) { + /* Already encoded over the target domain. */ + pos = ray_read_sym(cd, off + i, RAY_SYM, col->attrs); + } else if (cached) { + int64_t id = ray_read_sym(cd, off + i, RAY_SYM, col->attrs); + uint32_t slot = (uint32_t)(((uint64_t)id * 0x9E3779B97F4A7C15ull) >> (64 - COL_STREAM_LUT_BITS)); + if (w->lut_id[slot] == id) { + pos = w->lut_pos[slot]; + } else { + ray_t* s = ray_sym_str(id); + if (!s) return RAY_ERR_CORRUPT; + pos = ray_sym_domain_intern(w->dom, ray_str_ptr(s), ray_str_len(s)); + if (pos < 0) return RAY_ERR_OOM; + w->lut_id[slot] = id; w->lut_pos[slot] = (uint32_t)pos; + } + } else { + ray_t* s = ray_sym_vec_cell(col, off + i); + if (!s) return RAY_ERR_CORRUPT; + pos = ray_sym_domain_intern(w->dom, ray_str_ptr(s), ray_str_len(s)); + if (pos < 0) return RAY_ERR_OOM; + } + buf[i] = (uint32_t)pos; + /* Position 0 of any symfile is the empty string (domain.c + * enforces that reservation on open), so a re-encoded cell is + * the canonical SYM null exactly when its position is 0. + * Testing the value WRITTEN keeps the on-disk HAS_NULLS honest + * without trusting the chunk vec's attrs — and this arm is why + * streamed SYM columns used to lose the bit entirely: only the + * non-SYM arm below propagated it (issue #416). */ + if (pos == 0) w->had_nulls = true; + } + if (fwrite(buf, sizeof(uint32_t), (size_t)cnt, w->fp) != (size_t)cnt) + return RAY_ERR_IO; + off += cnt; + } + } else { + uint8_t esz = ray_sym_elem_size(w->type, 0); + size_t bytes = (size_t)n * (size_t)esz; + if (bytes && fwrite(ray_data(col), 1, bytes, w->fp) != bytes) + return RAY_ERR_IO; + if (col->attrs & RAY_ATTR_HAS_NULLS) w->had_nulls = true; + } + if (w->zone && col->type == w->type) { + ray_err_t err = ray_zone_acc_add(w->zone, col); + if (err != RAY_OK) return err; + } + if (w->dict && col->type == RAY_STR) { + ray_err_t err = ray_dict_acc_add(w->dict, col); + if (err != RAY_OK) return err; + } + w->rows += n; + return RAY_OK; +} + +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; + ray_err_t err = RAY_OK; + + if (w->type == RAY_STR) { + ray_t pool_header = {0}; pool_header.type = RAY_U8; pool_header.len = (int64_t)w->pool_bytes; + if (fwrite(&pool_header,1,32,w->fp) != 32) err = RAY_ERR_IO; + if (err == RAY_OK && w->pool_fp) { + uint8_t* buffer = ray_alloc_raw(65536); + if (!buffer) err = RAY_ERR_OOM; + else { + if (fseek(w->pool_fp,0,SEEK_SET)) err = RAY_ERR_IO; + uint64_t left = w->pool_bytes; + while (left && err == RAY_OK) { + size_t n = left < 65536 ? (size_t)left : 65536; + if (ray_interrupted()) err = RAY_ERR_CANCEL; + else if (fread(buffer,1,n,w->pool_fp) != n || fwrite(buffer,1,n,w->fp) != n) err = RAY_ERR_IO; + left -= n; + } + ray_free_raw(buffer); + } + } + } + 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); + + /* 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. */ + 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 + * loaded column and the zone agree on every cell. */ + if (w->zone && w->zone->saw_null) w->had_nulls = true; + if (err == RAY_OK && (w->zone || w->dict)) { + ray_t* idx = w->zone ? ray_zone_acc_finish(w->zone, w->rows) + : ray_dict_acc_finish(w->dict, w->rows); + 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) { + 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); + } + } + } + + if (err == RAY_OK) { + ray_t hdr = {0}; + hdr.type = w->type; + hdr.attrs = w->attrs; + hdr.len = w->rows; + /* SYM: header rc = the symfile's count (the loader's O(1) + * fast-reject against the FILE domain). */ + hdr.rc = (w->type == RAY_SYM) + ? (uint32_t)ray_sym_domain_count(w->dom) : 0; + if (w->had_nulls) hdr.attrs |= RAY_ATTR_HAS_NULLS; + /* Stamp the on-disk format major version into `order` so the + * streamed column file shares the exact identity ray_col_save + * writes — the loaders validate it. aux stays zero unless an + * index region was written above, in which case the stamp sets it. */ + ray_col_stamp_format(&hdr); + if (inline_index) ray_col_stamp_index(&hdr); + if (fseek(w->fp, 0, SEEK_SET) != 0 || + fwrite(&hdr, 1, 32, w->fp) != 32) + err = RAY_ERR_IO; + } + + if (fclose(w->fp) != 0 && err == RAY_OK) err = RAY_ERR_IO; + w->fp = NULL; + if (err == RAY_OK && durable) { + ray_fd_t fd = ray_file_open(w->tmp_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) { remove(w->tmp_path); stream_drop_index(w); } + else w->finished = true; + return err; +} + +ray_err_t ray_col_stream_publish(ray_col_stream_t* w, bool durable) { + if (!w->finished) return 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); + if (err != RAY_OK) { remove(w->tmp_path); stream_drop_index(w); } + return err; +} + +ray_err_t ray_col_stream_close(ray_col_stream_t* w, bool durable) { + ray_err_t err = ray_col_stream_finish(w, durable); + if (err == RAY_OK) err = ray_col_stream_publish(w, durable); + return err; +} + +typedef struct { + ray_col_stream_t* w; + int64_t* col_ns; + bool durable; + _Atomic(ray_err_t) err; +} stream_finish_ctx_t; + +static void stream_finish_task(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; (void)end; + stream_finish_ctx_t* a = (stream_finish_ctx_t*)raw; + int64_t t0 = a->col_ns ? ray_profile_now_ns() : 0; + ray_err_t e = ray_col_stream_finish(&a->w[start], a->durable); + if (a->col_ns) a->col_ns[start] = ray_profile_now_ns() - t0; + 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); + } +} + +ray_err_t ray_col_stream_close_all(ray_col_stream_t* w, int64_t n, bool durable, + int64_t* col_ns) { + if (n <= 0) return RAY_OK; + /* 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 }; + 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; + /* 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; + if (err == RAY_OK && cerr != RAY_OK) err = cerr; + if (err != RAY_OK) ray_col_stream_abort(&w[c]); + } + 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); + } + } + if (!cand) /* OOM on the candidate list: the columns keep their zones */ + 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_abort(ray_col_stream_t* w) { + ray_col_stream_drop_lut(w); + stream_drop_index(w); + w->finished = false; + if (w->fp) fclose(w->fp); + w->fp = NULL; + if (w->pool_fp) fclose(w->pool_fp); + w->pool_fp = NULL; + if (w->tmp_path[0]) remove(w->tmp_path); + if (w->pool_path[0]) remove(w->pool_path); +} diff --git a/src/store/stream.h b/src/store/stream.h new file mode 100644 index 000000000..28d359f65 --- /dev/null +++ b/src/store/stream.h @@ -0,0 +1,78 @@ +/* Copyright (c) 2026 Anton Kundenko. MIT license; see LICENSE. */ +#ifndef RAY_STORE_STREAM_H +#define RAY_STORE_STREAM_H +#include +#include +#include "ops/idxop.h" +/* One column, appended in bounded batches. SYM target domain is borrowed. + * Close commits the column; caller flushes its symbol domain first and writes + * the table schema last. STR pools spool to disk, with native 32-bit offsets. */ +typedef struct { + FILE* fp; + FILE* pool_fp; + uint64_t pool_bytes; + char pool_path[1024]; + char path[1024]; + char tmp_path[1024]; + int8_t type; + uint8_t attrs; + int64_t rows; + bool had_nulls; + /* SYM columns: the target symfile's domain (shared, borrowed from + * the caller). Cells are encoded as positions in it — the freshly + * parsed chunk vecs are runtime-domain, so each cell's string is + * find-or-appended into the domain (the flip, Task 7b). Width is + * fixed at W32: a streaming writer can't know the final vocabulary + * before the last chunk, and W32 covers any STRL count. */ + struct ray_sym_domain_s* dom; + /* runtime id -> domain position, direct-mapped: the chunk vecs are + * runtime-domain and a column's values repeat across rows and chunks, + * so a value is interned into the symfile's domain (a locked probe) the + * first time it is met and looked up here after. */ + int64_t* lut_id; /* [COL_STREAM_LUT] runtime id per slot, -1 empty */ + 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 finished; /* finish done: the tmp file is complete, not yet renamed */ +} ray_col_stream_t; + +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); +/* 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); +/* Fold src's zone into dst's (parallel Parquet tasks). Frees src's zone. */ +ray_err_t ray_col_stream_index_merge(ray_col_stream_t* dst, ray_col_stream_t* src); +/* On error only ray_col_stream_abort is valid (payload bytes were written + * before the index feed). */ +ray_err_t ray_col_stream_append(ray_col_stream_t* w, ray_t* column); +ray_err_t ray_col_stream_close(ray_col_stream_t* w, bool durable); +/* close in two halves, so a converter can finish all its columns as pool + * tasks (pool merge, index region, header, fclose, fsync) and publish them + * serially. finish touches only the writer's own files and never dispatches, + * so it is safe inside a pool task; publish is the rename (+ dir sync). On a + * 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); +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. + * `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); +/* 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/domain.c b/src/table/domain.c index a7d13f77a..d6139a254 100644 --- a/src/table/domain.c +++ b/src/table/domain.c @@ -35,10 +35,10 @@ * Append-only; positions are permanent; ray_sym_domain_flush persists * base+tail atomically under the symfile's flock. * - * Concurrency: one global spinlock guards the cache list, FILE-domain + * Concurrency: one global mutex guards the cache list, FILE-domain * refcounts, appends, the lazily built reverse index and the runtime-id - * LUT build. Domain opens, interns (save merges / live inserts — all - * inside sequential eval) and first-find index builds are rare. The + * 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 * atomically published (count, atoms) pair — appends publish a slot * write with a release store of the count, growth REPLACES the array @@ -57,6 +57,7 @@ #endif #include "domain.h" +#include "core/profile.h" /* phase ticks of the batch intern */ #include "core/platform.h" /* ray_vm_map_file / ray_vm_unmap_file */ #include "mem/heap.h" #include "mem/sys.h" /* domain buffers are process-global → mmap-backed, not buddy */ @@ -73,6 +74,11 @@ #include #include #include +#if defined(RAY_OS_WINDOWS) +#include +#elif !defined(RAY_OS_WASM) +#include +#endif #ifndef PATH_MAX # define PATH_MAX 4096 #endif @@ -204,15 +210,23 @@ ray_sym_domain_t* ray_sym_runtime_domain(void) { static ray_sym_domain_t* g_domains = NULL; -static _Atomic(int) g_dom_lock = 0; +#if defined(RAY_OS_WINDOWS) +static SRWLOCK g_dom_lock = SRWLOCK_INIT; static inline void dom_lock(void) { - while (atomic_exchange_explicit(&g_dom_lock, 1, memory_order_acquire)) { - RAY_CPU_RELAX(); - } + AcquireSRWLockExclusive(&g_dom_lock); } static inline void dom_unlock(void) { - atomic_store_explicit(&g_dom_lock, 0, memory_order_release); + ReleaseSRWLockExclusive(&g_dom_lock); } +#elif defined(RAY_OS_WASM) +/* The WASM runtime is single-threaded. */ +static inline void dom_lock(void) {} +static inline void dom_unlock(void) {} +#else +static pthread_mutex_t g_dom_lock = PTHREAD_MUTEX_INITIALIZER; +static inline void dom_lock(void) { pthread_mutex_lock(&g_dom_lock); } +static inline void dom_unlock(void) { pthread_mutex_unlock(&g_dom_lock); } +#endif /* ---- FILE domain construction / destruction ------------------------------- */ @@ -671,6 +685,17 @@ ray_sym_domain_t* ray_sym_domain_open_or_create(const char* path) { return dom_open_impl(path, true); } +ray_sym_domain_t* ray_sym_domain_new(void) { + ray_sym_domain_t* d = ray_sys_alloc(sizeof(*d)); + if (!d) return NULL; + d->kind = DOM_FILE; + d->rc = 1; + 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; } + return d; +} + void ray_sym_domain_retain(ray_sym_domain_t* dom) { if (!dom || dom->immortal) return; dom_lock(); @@ -984,14 +1009,18 @@ typedef struct { int64_t* uniq; /* [n_miss] first occurrences, per partition segment */ int64_t* part_off; /* [n_part + 1] */ int64_t* uniq_n; /* [n_part] distinct misses per partition */ - int64_t* bytes_p; /* [n_part] arena bytes the partition's atoms need */ - void** region; /* [n_part] arena region per partition */ + int64_t* tab; /* one block: every partition's dedupe table */ + int64_t* tab_off; /* [n_part + 1] partition table extents in tab */ + /* the append: new strings k = 0..total-1 in batch order */ + int64_t* ui; /* [total] batch index of new string k */ + 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) */ /* 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; int part_shift; - _Atomic(bool) oom; } dom_batch_ctx_t; static void dom_batch_probe_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { @@ -1041,14 +1070,13 @@ static void dom_batch_dedupe_fn(void* raw, uint32_t wid, int64_t start, int64_t int64_t lo = b->part_off[p], hi = b->part_off[p + 1]; int64_t cnt = hi - lo; if (cnt == 0) { b->uniq_n[p] = 0; continue; } - uint64_t cap = 16; - while ((uint64_t)cnt * 2 > cap) cap <<= 1; - int64_t* tab = (int64_t*)ray_sys_alloc((size_t)cap * sizeof(int64_t)); - if (!tab) { atomic_store_explicit(&b->oom, true, memory_order_relaxed); b->uniq_n[p] = 0; continue; } + /* the partition's slice of the shared table block (sized by the + * caller: a power of two at least twice the partition's misses) */ + uint64_t cap = (uint64_t)(b->tab_off[p + 1] - b->tab_off[p]); + int64_t* tab = b->tab + b->tab_off[p]; memset(tab, 0xff, (size_t)cap * sizeof(int64_t)); /* -1 = empty */ uint64_t mask = cap - 1; int64_t k = 0; - int64_t bytes = 0; for (int64_t j = lo; j < hi; j++) { int64_t i = b->miss[j]; uint32_t h = b->hashes[i]; @@ -1068,55 +1096,50 @@ static void dom_batch_dedupe_fn(void* raw, uint32_t wid, int64_t start, int64_t } else { tab[slot] = i; b->uniq[lo + k++] = i; - bytes += (int64_t)ray_arena_str_bytes(b->lens[i]); } } b->uniq_n[p] = k; - b->bytes_p[p] = bytes; - ray_sys_free(tab); } } -/* Append the partition's distinct strings: build the atoms in the - * partition's arena region at the positions the caller assigned (batch - * order), publish them in the reverse index (CAS on the empty slot keeps - * concurrent partitions from claiming one slot twice) and resolve the - * partition's repeats. Runs under the domain lock; the count is - * published by the caller once every partition is done. */ -static void dom_batch_insert_fn(void* raw, uint32_t wid, int64_t start, int64_t end) { +/* Append the batch's new strings k0..k1 (positions base + k, assigned in + * batch order by the caller): build each atom at its offset in the one + * arena region, store it at its position (a contiguous run per task — no + * two tasks write the same cache line of the atom array) and publish it in + * the reverse index (CAS on the empty slot keeps the probes of the other + * tasks correct). */ +static void dom_batch_insert_fn(void* raw, uint32_t wid, int64_t k0, int64_t k1) { (void)wid; dom_batch_ctx_t* b = (dom_batch_ctx_t*)raw; - for (int64_t p = start; p < end; p++) { - int64_t lo = b->part_off[p]; - int64_t hi = lo + b->uniq_n[p]; - char* at = (char*)b->region[p]; - for (int64_t j = lo; j < hi; j++) { - int64_t i = b->uniq[j]; - int64_t pos = b->out_pos[i]; /* assigned in batch order */ - ray_t* s = ray_arena_str_at(at, b->strs[i], b->lens[i]); - at += ray_arena_str_bytes(b->lens[i]); - b->atoms_w[pos] = s; - 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; - for (;;) { - uint64_t cur = 0; - if (atomic_compare_exchange_strong_explicit((_Atomic(uint64_t)*)&b->buckets[slot], - &cur, e, memory_order_relaxed, memory_order_relaxed)) - break; - slot = (slot + 1) & b->mask; - } - } - for (int64_t j = lo; j < b->part_off[p + 1]; j++) { - int64_t i = b->miss[j]; - int64_t v = b->out_pos[i]; - if (v < -1) b->out_pos[i] = b->out_pos[-(v + 2)]; + for (int64_t k = k0; k < k1; k++) { + 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; + 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; + for (;;) { + uint64_t cur = 0; + if (atomic_compare_exchange_strong_explicit((_Atomic(uint64_t)*)&b->buckets[slot], + &cur, e, memory_order_relaxed, memory_order_relaxed)) + break; + slot = (slot + 1) & b->mask; } } } -/* Serial fallback for the misses: find-or-append one by one under the lock - * (the domain changed under us, or the parallel path ran out of memory). */ +/* 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; + dom_batch_ctx_t* b = (dom_batch_ctx_t*)raw; + for (int64_t j = j0; j < j1; j++) { + int64_t i = b->miss[j]; + int64_t v = b->out_pos[i]; + if (v < -1) b->out_pos[i] = b->out_pos[-(v + 2)]; + } +} + 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) { @@ -1165,6 +1188,7 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, b.count = atomic_load_explicit(&dom->count, memory_order_acquire); dom->batch_inflight++; dom_unlock(); + ray_profile_tick("dom batch: index ready"); if (!ray_sym_domain_raw_pin(dom, &b.raw)) b.raw.count = 0; b.strs = strs; b.lens = lens; b.hashes = hashes; b.out_pos = out_pos; @@ -1174,10 +1198,15 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, if (par) ray_pool_dispatch(pool, dom_batch_probe_fn, &b, n); else dom_batch_probe_fn(&b, 0, 0, n); - /* Misses, grouped by hash partition. */ + /* Misses, grouped by hash partition: no more partitions than workers*4 + * or than the batch fills with a few thousand misses each. Every + * partition dedupes its misses in its slice of ONE table block — a + * batch costs one page-granular allocation for the tables, not one per + * partition (and no mapping churn on the workers). */ int n_part = 1; if (par) { int64_t want = (int64_t)ray_pool_total_workers(pool) * 4; + if (want > n / 4096) want = n / 4096; while (n_part < want && n_part < 1024) n_part <<= 1; } b.part_shift = 31; @@ -1196,9 +1225,8 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, b.uniq = (int64_t*)ray_sys_alloc((size_t)n_miss * sizeof(int64_t)); b.part_off = (int64_t*)ray_sys_alloc((size_t)(n_part + 1) * sizeof(int64_t)); b.uniq_n = (int64_t*)ray_sys_alloc((size_t)n_part * sizeof(int64_t)); - b.bytes_p = (int64_t*)ray_sys_alloc((size_t)n_part * sizeof(int64_t)); - b.region = (void**)ray_sys_alloc((size_t)n_part * sizeof(void*)); - bool ok = b.miss && b.uniq && b.part_off && b.uniq_n && b.bytes_p && b.region; + b.tab_off = (int64_t*)ray_sys_alloc((size_t)(n_part + 1) * sizeof(int64_t)); + bool ok = b.miss && b.uniq && b.part_off && b.uniq_n && b.tab_off; if (ok) { memset(b.part_off, 0, (size_t)(n_part + 1) * sizeof(int64_t)); for (int64_t i = 0; i < n; i++) @@ -1210,13 +1238,21 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, for (int64_t i = 0; i < n; i++) if (out_pos[i] < 0) b.miss[fill[hashes[i] >> b.part_shift]++] = i; } - 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 (atomic_load_explicit(&b.oom, memory_order_relaxed)) { - /* Undo the repeat marks; the serial path resolves everything. */ - for (int64_t i = 0; i < n; i++) if (out_pos[i] < -1) out_pos[i] = -1; - ok = false; + /* table extents: a power of two at least twice the partition's misses */ + int64_t tcap = 0; + for (int p = 0; p < n_part; p++) { + int64_t cnt = b.part_off[p + 1] - b.part_off[p]; + int64_t cap = 0; + if (cnt > 0) { cap = 16; while (cnt * 2 > cap) cap <<= 1; } + b.tab_off[p] = tcap; + tcap += cap; } + 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); + ray_profile_tick("dom batch: misses deduped"); } dom_lock(); @@ -1224,6 +1260,30 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, 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); + if (ok && !unchanged) { + /* Concurrent column chunks commonly append between the probe and + * commit. Keep the deduplication and arena batching: recheck only + * distinct misses against the current index, then commit the new + * subset in bulk. Falling back to one allocation/insertion per + * cell here makes additional import workers spend their time + * waiting for this lock. */ + int64_t total = 0; + for (int p = 0; p < n_part; p++) { + int64_t lo = b.part_off[p], keep = 0; + for (int64_t j = 0; j < b.uniq_n[p]; j++) { + int64_t i = b.uniq[lo+j]; + int64_t pos = dom_probe_locked(dom, hashes[i], strs[i], lens[i]); + if (pos >= 0) out_pos[i] = pos; + else b.uniq[lo+keep++] = i; + } + b.uniq_n[p] = keep; total += keep; + } + b.count = atomic_load_explicit(&dom->count, memory_order_relaxed); + if ((double)(b.count + total) > 0.7 * (double)(dom->bucket_mask + 1)) + ok = dom_build_index_locked(dom, total); + b.buckets = dom->buckets; b.mask = dom->bucket_mask; + unchanged = ok; + } if (unchanged) { int64_t total = 0; for (int p = 0; p < n_part; p++) total += b.uniq_n[p]; @@ -1246,26 +1306,44 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, } } } + if (ok && total > 0) { + b.ui = (int64_t*)ray_sys_alloc((size_t)total * 2 * sizeof(int64_t)); + if (!b.ui) ok = false; + else b.uoff = b.ui + total; + } if (ok) { - /* One arena region per partition; positions in partition order. - * Nothing is published until every partition has built its - * atoms, so a failed reservation costs only arena space. */ /* New strings take positions in batch order (first occurrence), - * so the symfile does not depend on how the batch was split. */ + * so the symfile does not depend on how the batch was split; + * their atoms go into ONE arena region, each at the offset the + * strings before it leave. Nothing is published until every + * atom is built, so a failed reservation costs only arena + * space. */ int64_t pos = base; - for (int64_t i = 0; i < n; i++) - if (out_pos[i] == -1) out_pos[i] = pos++; - for (int p = 0; p < n_part; p++) { - b.region[p] = NULL; - if (b.bytes_p[p] > 0) { - b.region[p] = ray_arena_alloc_raw(dom->arena, (size_t)b.bytes_p[p]); - if (!b.region[p]) { ok = false; break; } - } + size_t bytes = 0; + for (int64_t i = 0; i < n; i++) { + if (out_pos[i] != -1) continue; + int64_t k = pos - base; + if (k < total) { b.ui[k] = i; b.uoff[k] = (int64_t)bytes; } + bytes += ray_arena_str_bytes(lens[i]); + out_pos[i] = pos++; + } + if (pos - base != total) ok = false; + if (ok && bytes > 0) { + b.region = (char*)ray_arena_alloc_raw(dom->arena, bytes); + if (!b.region) ok = false; } if (ok) { + b.base = base; b.atoms_w = atomic_load_explicit(&dom->atoms, memory_order_relaxed); - if (par) ray_pool_dispatch_n(pool, dom_batch_insert_fn, &b, (uint32_t)n_part); - else dom_batch_insert_fn(&b, 0, 0, n_part); + 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); + } + 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); + ray_profile_tick("dom batch: inserted"); atomic_store_explicit(&dom->count, pos, memory_order_release); /* Same invalidation as dom_append_locked: the runtime LUT * no longer covers the vocabulary. */ @@ -1291,13 +1369,15 @@ bool ray_sym_domain_intern_batch(ray_sym_domain_t* dom, int64_t n, if (!unchanged || !ok) ok = dom_batch_append_serial_locked(dom, n, strs, lens, hashes, out_pos); dom_unlock(); + ray_profile_tick("dom batch: done"); 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.bytes_p); - ray_sys_free(b.region); + ray_sys_free(b.tab_off); + ray_sys_free(b.tab); + ray_sys_free(b.ui); return ok; } @@ -1317,6 +1397,7 @@ const char* ray_sym_domain_path(ray_sym_domain_t* dom) { 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 */ + if (!dom->path) return RAY_ERR_DOMAIN; dom_lock(); int64_t count = atomic_load_explicit(&dom->count, memory_order_relaxed); diff --git a/src/table/domain.h b/src/table/domain.h index b9ce66105..de7c8ba94 100644 --- a/src/table/domain.h +++ b/src/table/domain.h @@ -45,6 +45,8 @@ * open / append and owned by the domain (borrowed by * callers, exactly like ray_sym_str), making * ray_sym_domain_str a lock-free array read. + * ray_sym_domain_new creates a private in-memory instance of + * this dictionary, with no backing path or cache entry. * * Position-0 reservation: position 0 of every non-empty FILE domain is * the canonical empty/null symbol "" (mirrors global id 0). Group kernels @@ -99,6 +101,11 @@ ray_sym_domain_t* ray_sym_domain_open(const char* path); * open-or-create entry point. */ ray_sym_domain_t* ray_sym_domain_open_or_create(const char* path); +/* New private, refcounted in-memory dictionary. Supports the same concurrent + * append and resolution operations as FILE domains, without a cache entry or + * backing file. Attached vectors keep it alive. flush returns RAY_ERR_DOMAIN. */ +ray_sym_domain_t* ray_sym_domain_new(void); + /* No-ops on the runtime singleton. */ void ray_sym_domain_retain(ray_sym_domain_t* dom); void ray_sym_domain_release(ray_sym_domain_t* dom); diff --git a/src/table/sym.c b/src/table/sym.c index 7c55cdf1c..cd1e5fde4 100644 --- a/src/table/sym.c +++ b/src/table/sym.c @@ -999,6 +999,15 @@ uint32_t ray_sym_count(void) { return count; } +/* Bytes the table's string arena holds (every interned name's atom). */ +size_t ray_sym_bytes(void) { + if (!atomic_load_explicit(&g_sym_inited, memory_order_acquire)) return 0; + sym_lock(); + size_t bytes = g_sym.arena ? ray_arena_total_used(g_sym.arena) : 0; + sym_unlock(); + return bytes; +} + /* -------------------------------------------------------------------------- * ray_sym_strings_borrow * diff --git a/test/data/parquet/all-null.parquet b/test/data/parquet/all-null.parquet new file mode 100644 index 000000000..37bb59d59 Binary files /dev/null and b/test/data/parquet/all-null.parquet differ diff --git a/test/data/parquet/bloom-bad.parquet b/test/data/parquet/bloom-bad.parquet new file mode 100644 index 000000000..830137134 Binary files /dev/null and b/test/data/parquet/bloom-bad.parquet differ diff --git a/test/data/parquet/bloom.parquet b/test/data/parquet/bloom.parquet new file mode 100644 index 000000000..72491096f Binary files /dev/null and b/test/data/parquet/bloom.parquet differ diff --git a/test/data/parquet/bool-rle-v1.parquet b/test/data/parquet/bool-rle-v1.parquet new file mode 100644 index 000000000..0eedd8135 Binary files /dev/null and b/test/data/parquet/bool-rle-v1.parquet differ diff --git a/test/data/parquet/bool-rle-v2.parquet b/test/data/parquet/bool-rle-v2.parquet new file mode 100644 index 000000000..fd4d35617 Binary files /dev/null and b/test/data/parquet/bool-rle-v2.parquet differ diff --git a/test/data/parquet/bool.parquet b/test/data/parquet/bool.parquet new file mode 100644 index 000000000..65da91796 Binary files /dev/null and b/test/data/parquet/bool.parquet differ diff --git a/test/data/parquet/empty-group.parquet b/test/data/parquet/empty-group.parquet new file mode 100644 index 000000000..101f38aa3 Binary files /dev/null and b/test/data/parquet/empty-group.parquet differ diff --git a/test/data/parquet/empty.parquet b/test/data/parquet/empty.parquet new file mode 100644 index 000000000..031d34d45 Binary files /dev/null and b/test/data/parquet/empty.parquet differ diff --git a/test/data/parquet/flat-0-v1.parquet b/test/data/parquet/flat-0-v1.parquet new file mode 100644 index 000000000..cc1c6b96c Binary files /dev/null and b/test/data/parquet/flat-0-v1.parquet differ diff --git a/test/data/parquet/flat-0-v2.parquet b/test/data/parquet/flat-0-v2.parquet new file mode 100644 index 000000000..91fb7922b Binary files /dev/null and b/test/data/parquet/flat-0-v2.parquet differ diff --git a/test/data/parquet/flat-1-v1.parquet b/test/data/parquet/flat-1-v1.parquet new file mode 100644 index 000000000..fe2957dac Binary files /dev/null and b/test/data/parquet/flat-1-v1.parquet differ diff --git a/test/data/parquet/flat-1-v2.parquet b/test/data/parquet/flat-1-v2.parquet new file mode 100644 index 000000000..7567c7163 Binary files /dev/null and b/test/data/parquet/flat-1-v2.parquet differ diff --git a/test/data/parquet/generate.py b/test/data/parquet/generate.py new file mode 100644 index 000000000..277a04e6a --- /dev/null +++ b/test/data/parquet/generate.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Rebuild small Parquet fixtures using Python's standard library only. + +Independent format writer for reader tests: no Arrow/Thrift/Snappy libraries. +Not installed, linked, or invoked by Rayforce or the normal test suite. +""" +import struct +from pathlib import Path + +STOP, TRUE, FALSE, BYTE, I16, I32, I64, DOUBLE, BINARY, LIST, SET, MAP, STRUCT = range(13) + +def var(n): + out = bytearray() + while n > 127: + out.append((n & 127) | 128) + n >>= 7 + return bytes(out + bytes([n])) + +def value(t, v): + if t in (TRUE, FALSE): return b'' + if t == BYTE: return bytes([v & 255]) + if t in (I16, I32, I64): return var((v << 1) ^ (v >> 63)) + if t == BINARY: + v = v.encode() if isinstance(v, str) else v + return var(len(v)) + v + if t == LIST: + et, items = v + h = bytes([(min(len(items), 15) << 4) | et]) + return h + (var(len(items)) if len(items) >= 15 else b'') + b''.join(bytes([TRUE if x else FALSE]) if et == TRUE else value(et, x) for x in items) + if t == STRUCT: + out, last = b'', 0 + for fid, ft, fv in v: + d = fid-last + out += bytes([(d << 4) | ft]) if 0 < d < 16 else bytes([ft]) + value(I16, fid) + out += value(ft, fv) + last = fid + return out + b'\0' + raise ValueError(t) + +def fields(items): return value(STRUCT, items) + +def snappy(data): + """Literal-only valid block; back references are covered by C codec tests.""" + if not data: return b'\0' + n = len(data)-1 + if n < 60: tag = bytes([n << 2]) + else: + nb = max(1, (n.bit_length()+7)//8) + tag = bytes([(59+nb) << 2]) + n.to_bytes(nb, 'little') + return var(len(data)) + tag + data + +def rle(values, width): + return b''.join(var(2) + x.to_bytes((width+7)//8, 'little') for x in values) + +def packed(values, width): + if not values: return b'' + padded = values + [0] * (-len(values) % 8) + bits = sum(v << (i*width) for i,v in enumerate(padded)) + return var((len(padded)//8)*2+1) + bits.to_bytes(len(padded)*width//8, 'little') + +def plain(pt, values): + if pt == 0: return bytes(sum(bool(x) << j for j,x in enumerate(values[i:i+8])) for i in range(0,len(values),8)) + if pt == 6: + encoded = [x if isinstance(x,bytes) else x.encode() for x in values] + return b''.join(struct.pack('>(64-n))) & mask + p1,p2,p3,p4=11400714785074694791,14029467366897019727,1609587929392839161,9650029242287828579 + h=2870177450012600261+width + if width==8: + h ^= (rot(((x&mask)*p2)&mask,31)*p1)&mask + h=(rot(h,27)*p1+p4)&mask + else: + h ^= ((x&0xffffffff)*p1)&mask + h=(rot(h,23)*p2+p3)&mask + h ^= h>>33; h=(h*p2)&mask; h ^= h>>29; h=(h*p3)&mask + return h ^ (h>>32) + +class Page(bytes): + def __new__(cls, data, uncompressed): + obj = super().__new__(cls, data) + obj.uncompressed = uncompressed + return obj + +def page(kind, header, body, codec=1, prefix=b'', compressed=True, crc=False): + import zlib # stdlib, fixture checksums only + payload = prefix + (snappy(body) if codec and compressed else body) + f = [(1,I32,kind),(2,I32,len(prefix)+len(body)),(3,I32,len(payload))] + if crc: + chk = zlib.crc32(payload) + f.append((4,I32,chk if chk < 2**31 else chk-2**32)) + f.append(({0:5,2:7,3:8}[kind],STRUCT,header)) + header_bytes = fields(f) + return Page(header_bytes+payload,len(header_bytes)+len(prefix)+len(body)) + +def write(path, specs, groups, codec=1, v2=False, dictionary=True, crc=False, legacy=False, statistics=True, compress_v2=True, indexes=False, bloom=False, bad_index=False, bad_bloom=False, mismatched=False, corrupt_column=None, rle_ids=False, rle_bools=False, all_dict=False): + data = bytearray(b'PAR1') + schema = [[(3,I32,0),(4,BINARY,'schema'),(5,I32,len(specs))]] + for name,pt,optional,converted in specs: + s = [(1,I32,pt),(3,I32,int(optional)),(4,BINARY,name)] + if converted is not None: s.append((6,I32,converted)) + schema.append(s) + rowgroups=[] + for group in groups: + cols=[]; rgsize=0 + for ci, ((name,pt,optional,converted), values) in enumerate(zip(specs,group)): + pages=[]; start=len(data); dict_off=None + if not values: + # A zero-row group as common writers emit it: an empty + # dictionary page, no data page, data_page_offset 0. + pages.append(page(2,[(1,I32,0),(2,I32,0)],b'',codec,crc=crc)) + chunk=pages[0]; data+=chunk + md=[(1,I32,pt),(2,LIST,(I32,[0,3])),(3,LIST,(BINARY,[name])),(4,I32,codec),(5,I64,0),(6,I64,pages[0].uncompressed),(7,I64,len(chunk)),(9,I64,0),(11,I64,start)] + cols.append([(2,I64,start),(3,STRUCT,md)]); rgsize+=pages[0].uncompressed + continue + # Three pages force dictionary->plain fallback and independent + # page boundaries between columns; last page is always PLAIN. + cuts=[0,max(1,len(values)//3),max(2,2*len(values)//3),len(values)] + if mismatched and ci: cuts=[0,2,7,len(values)] + cuts=sorted(set(min(x,len(values)) for x in cuts)) + vocab=list(dict.fromkeys(x for x in values if x is not None)) + use_dict=dictionary and pt!=0 and bool(vocab) + if use_dict: + dict_off=start + pages.append(page(2,[(1,I32,len(vocab)),(2,I32,2 if legacy else 0)],plain(pt,vocab),codec,crc=crc)) + data_off=start+sum(map(len,pages)) + for k,(lo,hi) in enumerate(zip(cuts,cuts[1:])): + vals=values[lo:hi]; valid=[x for x in vals if x is not None] + enc=(2 if legacy else 8) if use_dict and (all_dict or k fallback + oi=fields([(1,LIST,(STRUCT,locs))]) + ix=fields([(1,LIST,(TRUE,nulls)),(2,LIST,(BINARY,lows)),(3,LIST,(BINARY,highs)),(4,I32,0)]) + cc += [(4,I64,len(data)),(5,I32,len(oi)),(6,I64,len(data)+len(oi)),(7,I32,len(ix))] + data += oi+ix + if bloom and pt in (1,2): + words=[0]*64 # Eight blocks exercise the high-hash block choice. + salt=[0x47b6137b,0x44974d91,0x8824ad5b,0xa2b7289d,0x705495c7,0x2df1424b,0x9efc4947,0x5c6bfb31] + for v in valid: + h=integer_hash(v,4 if pt==1 else 8); block=((h>>32)*8)>>32 + for j,k in enumerate(salt): words[block*8+j] |= 1 << (((h*k)&0xffffffff)>>27) + union=[(2 if bad_bloom else 1,STRUCT,[])] + bf=fields([(1,I32,256),(2,STRUCT,union),(3,STRUCT,union),(4,STRUCT,union)])+struct.pack('<64I',*words) + md += [(14,I64,len(data)),(15,I32,len(bf))]; data+=bf + cols.append(cc) + rowgroups.append([(1,LIST,(STRUCT,cols)),(2,I64,rgsize),(3,I64,len(group[0]))]) + footer=fields([(1,I32,1),(2,LIST,(STRUCT,schema)),(3,I64,sum(len(g[0]) for g in groups)),(4,LIST,(STRUCT,rowgroups)),(6,BINARY,'rayforce fixture writer')]) + path.write_bytes(data+footer+struct.pack(' u 100))})) +(< (* 8 (count Fsp)) Nsp) -- true +(set SA (select {from: (select {from: Tsp by: k c: (count u) d: (count (distinct u)) mn: (min s) where: (and (like s "*needle*") (> u 100))}) asc: k})) +(set SB (select {from: (select {from: Fsp by: k c: (count u) d: (count (distinct u)) mn: (min s)}) asc: k})) +(== (count SA) (count SB)) -- true +(all (== (at SA 'c) (at SB 'c))) -- true +(all (== (at SA 'd) (at SB 'd))) -- true +(all (== (at SA 'mn) (at SB 'mn))) -- true +(set Gsp (select {from: Tsp where: (< r 16384)})) +(set GA (select {from: (select {from: Tsp by: k c: (count u) d: (count (distinct u)) where: (< r 16384)}) asc: k})) +(set GB (select {from: (select {from: Gsp by: k c: (count u) d: (count (distinct u))}) asc: k})) +(all (== (at GA 'd) (at GB 'd))) -- true +(sum (at GA 'd)) -- 16384 +;; a where: keeping no row at all +(count (select {from: Tsp by: k d: (count (distinct u)) where: (> u 5000)})) -- 0 +;; With no where: and under a where: keeping many rows the slices are built +;; in parallel, one histogram row per task, the tasks cut by the rows they +;; visit. Oracle independent of the slices: distinct (k, u) pairs counted +;; per k by the grouping itself. +(set CDO (fn [t] (select {from: (select {from: (select {from: t by: [k u]}) by: k d: (count u)}) asc: k}))) +(set CDS (fn [t] (select {from: (select {from: t by: k c: (count u) d: (count (distinct u))}) asc: k}))) +(set PA (CDS Tsp)) +(set PB (CDO Tsp)) +(all (== (at PA 'd) (at PB 'd))) -- true +(sum (at PA 'c)) -- 300000 +(set PW (select {from: (select {from: Tsp by: k c: (count u) d: (count (distinct u)) where: (< r 200000)}) asc: k})) +(set PV (CDO (select {from: Tsp where: (< r 200000)}))) +(all (== (at PW 'd) (at PV 'd))) -- true +(sum (at PW 'c)) -- 200000 +(set QW (select {from: (select {from: Tsp by: k c: (count u) d: (count (distinct u)) where: (> u 100)}) asc: k})) +(set QV (CDO (select {from: Tsp where: (> u 100)}))) +(all (== (at QW 'd) (at QV 'd))) -- true +(sum (at QW 'c)) -- (count (select {from: Tsp where: (> u 100)})) diff --git a/test/rfl/agg/parted_f64_agg.rfl b/test/rfl/agg/parted_f64_agg.rfl index 71d53fd86..da76aa4a7 100644 --- a/test/rfl/agg/parted_f64_agg.rfl +++ b/test/rfl/agg/parted_f64_agg.rfl @@ -135,13 +135,20 @@ (.db.splayed.set "/tmp/rfl_agg_pts/1/t/" Tts1) (.db.splayed.set "/tmp/rfl_agg_pts/2/t/" Tts2) (set Pts (.db.parted.get "/tmp/rfl_agg_pts/" 't)) -(select {r: ((fn [c] (sum c)) 'ts) from: Pts}) !- type +;; The whole-column gate. (A per-row lambda in a select projection, +;; `((fn [c] (sum c)) 'ts)`, sums one cell at a time and is no gate: it +;; only raised `type` here because the fallback could not read a parted +;; column at all — it returns the cells over a flat table, and now over a +;; parted one too.) +(sum (at Pts 'ts)) !- type +(count (select {r: ((fn [c] (sum c)) 'ts) from: Pts})) -- 5 (set Tl1 (table [l] (list (list [1 2] [3 4])))) (set Tl2 (table [l] (list (list [5 6])))) (.db.splayed.set "/tmp/rfl_agg_plist/1/t/" Tl1) (.db.splayed.set "/tmp/rfl_agg_plist/2/t/" Tl2) (set Pl (.db.parted.get "/tmp/rfl_agg_plist/" 't)) -(select {r: ((fn [c] (sum (first (list c)))) 'l) from: Pl}) !- type +(sum (at Pl 'l)) !- type +(count (select {r: ((fn [c] (sum (first (list c)))) 'l) from: Pl})) -- 3 ;; ─── 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") diff --git a/test/rfl/fused/fused_take_early_stop.rfl b/test/rfl/fused/fused_take_early_stop.rfl index afd1895f5..66e0c8bec 100644 --- a/test/rfl/fused/fused_take_early_stop.rfl +++ b/test/rfl/fused/fused_take_early_stop.rfl @@ -57,3 +57,20 @@ tcnt -- 1 (at (select {b: a z: b from: TA where: (== c 0) asc: a take: 2}) 'z) -- [1 2] (at (select {b: a z: b from: TA asc: a take: 2}) 'z) -- [1 2] (at (select {b: b z: b from: TA where: (== c 0) take: 2}) 'z) -- [30 10] + +;; Chunks may run in any order (pool.h, ORDER CONTRACT): a worker whose list +;; filled from a late chunk must still scan an earlier one it is handed. +;; Matches that start late in the table / deep in a chunk, and K beyond a +;; chunk's worth of matches, in both directions. +(at (select {x: x from: TK where: (> x 999990) take: 3}) 'x) -- [999991 999992 999993] +(at (select {x: x from: TK where: (and (== c 7) (> x 900000)) take: 3}) 'x) -- [900007 901007 902007] +(at (select {x: x from: TK where: (and (== c 7) (< x 100000)) take: -3}) 'x) -- [97007 98007 99007] +(at (select {x: x from: TK where: (< x 9) take: -3}) 'x) -- [6 7 8] +(set FC (at (select {x: x from: TK where: (and (== c 7) (> x 500000)) take: 300}) 'x)) +(count FC) -- 300 +(sum FC) -- 194852100 +(last FC) -- 799007 +(set FD (at (select {x: x from: TK where: (and (== c 7) (< x 500000)) take: -300}) 'x)) +(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] diff --git a/test/rfl/graph/graph_builtin_branches.rfl b/test/rfl/graph/graph_builtin_branches.rfl index 4717f3f52..044ce8a69 100644 --- a/test/rfl/graph/graph_builtin_branches.rfl +++ b/test/rfl/graph/graph_builtin_branches.rfl @@ -38,6 +38,15 @@ ;; Weighted 6-node DAG (same as graph_basic.rfl) (set WEdges (table [src dst w] (list [0 0 1 1 2 2 3 4] [1 2 2 3 3 4 5 5] [1.0 4.0 2.0 5.0 1.0 3.0 2.0 1.0]))) (set Wg (.graph.build WEdges 'src 'dst 'w)) +;; Graph handles are process-local and must not be serialized as plain i64s. +(ser Wg) !- domain +(ser (list Wg)) !- domain +(ser (dict ['g] (list Wg))) !- domain +(ser (table [g] (list (list (list Wg))))) !- domain +(ser ((fn [] (let captured Wg) (fn [] captured)))) !- domain +(nil? (.log.open 'async "/tmp/rfl_graph_serde_handle")) -- true +(.log.write Wg) !- domain +(nil? (.log.purge)) -- true ;; ==================================================================== ;; ray_graph_build_fn — rank errors (line 157) diff --git a/test/rfl/group/derived_key_sym_domain.rfl b/test/rfl/group/derived_key_sym_domain.rfl index be9f6df1f..8f6ccd544 100644 --- a/test/rfl/group/derived_key_sym_domain.rfl +++ b/test/rfl/group/derived_key_sym_domain.rfl @@ -111,3 +111,263 @@ (set FN (.db.splayed.get "/tmp/rfl_dkey_filen/")) (all (== (FP (KEYQ FN)) (FP ON))) -- true (.sys.exec "rm -rf /tmp/rfl_dkey_file/ /tmp/rfl_dkey_filen/") -- 0 + +;; ── the key as a per-value program ───────────────────────────────────── +;; Over a FILE-domain column a key made of let / if / cond / and / or / not +;; / comparisons / + - * / str-find / substr / strlen / within / nil? runs +;; as a straight-line program once per distinct value, on the workers; +;; any other operator keeps the chunk DAG. Reference for every key: the +;; same expression computed row by row with `map` over the column's +;; strings, then a plain grouping by that column. 70000 rows so both the +;; vocabulary rewrite (aggregates over the key column only) and the +;; per-row spread (an aggregate over another column) run. +(set U ["http://www.abc.com/x" "" "abc" "android-app://q/z" "http://www./" "https://www.x" "http:/a/b" "http://a" "://x/y" "ftp://h/x" "https://www.h.org/a/b" "http://h.org/" "www.x/y" "http" "https:///z" "HTTP://UP.ORG/a" "http://h.org/www./x" "https://ww.h.org/q" "http://www.www.h/" "http://s?te.org/o#o"]) +(set mkv (fn [j] (if (< j (count U)) (at U j) (if (== 0 (% j 7)) (format "http://www.site%.org/p/%" (% j 41) j) (if (== 1 (% j 7)) (format "https://site%.org/q?x=%" (% j 41) j) (if (== 2 (% j 7)) (format "http://site%.org" (% j 41)) (if (== 3 (% j 7)) (format "android-app://com.app%/x" (% j 13)) (if (== 4 (% j 7)) (format "https://www.site%.org/" (% j 41)) (if (== 5 (% j 7)) (format "site%.org/path" (% j 41)) (format "http://Site%.org/a/b#%" (% j 41) j)))))))))) +(set NP 70000) +(set ip (til NP)) +(set refp (as 'SYMBOL (map (fn [k] (if (== 0 (% k 97)) null (mkv (% (* k 7919) 640)))) ip))) +(set vp (% (* ip 31) 1000)) +(set TP (table [ref v] (list refp vp))) +(.sys.exec "rm -rf /tmp/rfl_dkey_prog/") -- 0 +(.db.splayed.set "/tmp/rfl_dkey_prog/" TP) +(set FT (.db.splayed.get "/tmp/rfl_dkey_prog/")) +(count (distinct (at FT 'ref))) -- 423 +(set SP (as 'STR (at TP 'ref))) +;; a key of the value alone, per row through the distinct values (the Q29 +;; key and the two-column key below are mapped over every row) +(set DSP (distinct SP)) +(set ISP (find DSP SP)) +(set rowk (fn [f] (at (map f DSP) ISP))) +;; reference grouping over a materialised key column; fingerprint by key text +(set refg (fn [K] (select {from: (table [k ref v] (list (as 'SYMBOL K) refp vp)) by: k c: (count ref) sv: (sum v)}))) +(set fpk (fn [r] (ser (xasc (table [k c] (list (as 'STR (at (value r) 0)) (at r 'c))) 'k)))) +(set fpks (fn [r] (ser (xasc (table [k c sv] (list (as 'STR (at (value r) 0)) (at r 'c) (at r 'sv))) 'k)))) + +;; the URL-host key: http / https / www / no slash / empty / non-http / nulls +(set kq29 (fn [x] (do (let p (str-find x "://")) (let s (substr x (+ p 4) -1)) (let r (if (== (str-find s "www.") 0) (substr s 5 -1) s)) (let sl (str-find r "/")) (if (and (and (>= p 4) (<= p 5)) (== (substr x 1 4) "http") (not (nil? sl))) (substr r 1 sl) x)))) +(set K29 (map kq29 SP)) +(set O29 (refg K29)) +(set R29 (select {from: FT 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 O29w (select {from: (table [k ref] (list (as 'SYMBOL K29) refp)) by: k c: (count ref) l: (avg (strlen ref)) mn: (min ref) where: (!= ref "")})) +(== (count R29) (count O29w)) -- true +(all (== (fpk R29) (fpk O29w))) -- true +(set FPL (fn [r] (ser (xasc (table [k l mn] (list (as 'STR (at (value r) 0)) (at r 'l) (as 'STR (at r 'mn)))) 'k)))) +(all (== (FPL R29) (FPL O29w))) -- true +(at (cols R29) 0) -- 'p +;; the same key with an aggregate over another column: per-row spread +(set R29s (select {from: FT 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) sv: (sum v)})) +(== (count R29s) (count O29)) -- true +(all (== (fpks R29s) (fpks O29))) -- true +;; an operator outside the program (abs) leaves the key to the chunk DAG: same groups +(set R29d (select {from: FT 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)})) +(all (== (fpks R29d) (fpks O29))) -- true + +;; cond, string literals in the arms, offsets past the end +(set R2 (select {from: FT by: (cond ((== (substr ref 1 5) "https") "secure") ((== (substr ref 1 4) "http") (substr ref 8 4)) (else (substr ref 1 3))) c: (count ref) sv: (sum v)})) +(set O2 (refg (rowk (fn [x] (if (== (substr x 1 5) "https") "secure" (if (== (substr x 1 4) "http") (substr x 8 4) (substr x 1 3))))))) +(all (== (fpks R2) (fpks O2))) -- true +;; null arithmetic: strlen of the empty value is null, so is the length below +(set R3 (select {from: FT by: (if (or (nil? (str-find ref "/")) (> (strlen ref) 24)) (substr ref 1 (- (strlen ref) 2)) ref) c: (count ref)})) +(set O3 (refg (rowk (fn [x] (if (or (nil? (str-find x "/")) (> (strlen x) 24)) (substr x 1 (- (strlen x) 2)) x))))) +(all (== (fpk R3) (fpk O3))) -- true +;; comparisons of nullable offsets, a product as the start +(set R4 (select {from: FT by: (if (!= (str-find ref "?") (str-find ref "#")) (substr ref (* 2 (str-find ref "o")) 3) "none") c: (count ref)})) +(set O4 (refg (rowk (fn [x] (if (!= (str-find x "?") (str-find x "#")) (substr x (* 2 (str-find x "o")) 3) "none"))))) +(all (== (fpk R4) (fpk O4))) -- true +;; a search pattern with a wildcard +(set R5 (select {from: FT by: (substr ref (+ 1 (str-find ref "s?te")) 6) c: (count ref)})) +(set O5 (refg (rowk (fn [x] (substr x (+ 1 (str-find x "s?te")) 6))))) +(all (== (fpk R5) (fpk O5))) -- true +;; the key is an earlier binding, not the last operator +(set R6 (select {from: FT by: (let a (substr ref 1 3) (let b (str-find ref "x") a)) c: (count ref)})) +(all (== (fpk R6) (fpk (refg (rowk (fn [x] (substr x 1 3))))))) -- true +;; n-ary and, not, nil? over the value itself +(set R7 (select {from: FT by: (if (and (not (nil? ref)) (<= (strlen ref) 12) (>= (strlen ref) 3)) "short" (substr ref (- (strlen ref) 3) 4)) c: (count ref)})) +(set O7 (refg (rowk (fn [x] (if (and (not (nil? x)) (<= (strlen x) 12) (>= (strlen x) 3)) "short" (substr x (- (strlen x) 3) 4)))))) +(all (== (fpk R7) (fpk O7))) -- true +;; another column in the key: never per value +(set R8 (select {from: FT by: (if (> v 500) (substr ref 1 4) ref) c: (count ref)})) +(set O8 (refg (map (fn [k] (if (> (at vp k) 500) (substr (at SP k) 1 4) (at SP k))) ip))) +(all (== (fpk R8) (fpk O8))) -- true +;; an operator outside the program (upper): the chunk DAG, same groups +(set R9 (select {from: FT by: (upper (substr ref 1 4)) c: (count ref)})) +(set O9 (refg (rowk (fn [x] (upper (substr x 1 4)))))) +(all (== (fpk R9) (fpk O9))) -- true +;; a vocabulary past the parallel threshold (73k distinct values): the +;; program, the partitioned dedupe and the position ordering run on the +;; workers; the chunk DAG's interning (abs again) too +(set NB 80000) +(set mkb (fn [k] (if (== 0 (% k 13)) "" (if (== 0 (% k 11)) (format "android-app://app%/x%" (% k 7) k) (if (== 0 (% k 5)) (format "https://www.h%.org/p/%" (% k 97) k) (if (== 0 (% k 3)) (format "http://h%.org" k) (format "http://h%.org/q/%" (% k 97) k))))))) +(set refb (as 'SYMBOL (map mkb (til NB)))) +(.sys.exec "rm -rf /tmp/rfl_dkey_progb/") -- 0 +(.db.splayed.set "/tmp/rfl_dkey_progb/" (table [ref] (list refb))) +(set FB (.db.splayed.get "/tmp/rfl_dkey_progb/")) +(> (count (distinct (at FB 'ref))) 65536) -- true +(set KB (as 'SYMBOL (map kq29 (as 'STR refb)))) +(set OB (select {from: (table [k ref] (list KB refb)) by: k c: (count ref) l: (avg (strlen ref)) mn: (min ref) where: (!= ref "")})) +(set RB (select {from: FB 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 "")})) +(== (count RB) (count OB)) -- true +(all (== (FPL RB) (FPL OB))) -- true +(all (== (fpk RB) (fpk OB))) -- true +(set RBd (select {from: FB 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) l: (avg (strlen ref)) mn: (min ref) where: (!= ref "")})) +(all (== (fpk RBd) (fpk OB))) -- true +;; unsorted, both evaluations give the groups in the same order +(all (== (as 'STR (at RB 'p)) (as 'STR (at RBd 'p)))) -- true +(.sys.exec "rm -rf /tmp/rfl_dkey_progb/") -- 0 + +;; ── only the selected rows' values are evaluated ─────────────────────── +;; Under a where: the per-value evaluation visits the distinct values of +;; the SELECTED rows alone (the grouping honours the same selection); a +;; value that occurs in no selected row is never evaluated. Same groups +;; as the key materialised row by row and filtered, over the file-backed +;; table and in memory; a sparse selection (one row in ten) and a dense one. +(set KW (fn [t w] (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) sv: (sum v) where: (> v w)}))) +(set OW (fn [w] (select {from: (table [k ref v] (list (as 'SYMBOL K29) refp vp)) by: k c: (count ref) sv: (sum v) where: (> v w)}))) +(all (== (fpks (KW FT 900)) (fpks (OW 900)))) -- true +(all (== (fpks (KW TP 900)) (fpks (OW 900)))) -- true +(all (== (fpks (KW FT 100)) (fpks (OW 100)))) -- true +(all (== (fpks (KW TP 100)) (fpks (OW 100)))) -- true +(== (count (KW FT 900)) (count (OW 900))) -- true +(<= (count (KW FT 900)) (count (KW FT 100))) -- true + +;; ── derived keys leave the global symbol table alone ─────────────────── +;; Whether the column's ids are FILE positions (FT) or runtime ids (TP), +;; the values are read in place and the final key strings are interned +;; into a domain owned by the key column: a query grows the runtime table +;; ((.sys.mem) 'sym-count) by nothing — per-row spread with a selection, +;; vocabulary rewrite, and the chunk DAG alike. The snapshot is taken +;; 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 +(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)}))) +(set WARM (list (KW FT 900) (KW TP 900) (KV FT) (KV TP) (KD FT) (KD TP))) +(set NG1 (nogrow (fn [] (KW FT 900)))) +(at NG1 0) -- 0 +(set NG2 (nogrow (fn [] (KW TP 900)))) +(at NG2 0) -- 0 +(all (== (fpks (at NG2 1)) (fpks (OW 900)))) -- true +(set NG3 (nogrow (fn [] (KV TP)))) +(at NG3 0) -- 0 +(all (== (fpk (at NG3 1)) (fpk O29w))) -- true +(all (== (FPL (at NG3 1)) (FPL O29w))) -- true +(set NG4 (nogrow (fn [] (KV FT)))) +(at NG4 0) -- 0 +(set NG5 (nogrow (fn [] (KD TP)))) +(at NG5 0) -- 0 +(all (== (fpks (at NG5 1)) (fpks O29))) -- true +(set NG6 (nogrow (fn [] (KD FT)))) +(at NG6 0) -- 0 +;; the key column is a symbol column over its own domain; it outlives the +;; query and compares by text against runtime symbols +(type (at (at NG3 1) 'p)) -- 'SYM +(set KP (at (at NG2 1) 'p)) +(set NG2 0) +(== (count (distinct (as 'STR KP))) (count KP)) -- true +(> (sum (as 'I64 (== KP 'abc))) 0) -- true + +;; ── unsorted output is a function of the query and its rows alone ────── +;; The keys of an execution are numbered in the order they are first met +;; over the selected rows — never by anything that ran earlier in the +;; session: a query that follows another selection of the same expression +;; comes out exactly as it does on its own, on the per-row spread (an +;; aggregate over another column) and on the vocabulary rewrite, over the +;; file-backed table and in memory. The first selection (https referers) +;; meets a strict subset of the second's keys, in another order. +(set KEYS (fn [r] (as 'STR (at (value r) 0)))) +(set SA (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) sv: (sum v) where: (like ref "https://*")}))) +(set SB (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) sv: (sum v) where: (!= ref "")}))) +(set VA (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)) where: (like ref "https://*")}))) +(set VB (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)) where: (!= ref "")}))) +(< (count (SA FT)) (count (SB FT))) -- true +;; the order of each, alone +(set CB (KEYS (SB FT))) +(set CA (KEYS (SA FT))) +;; the same, after the other selection +(set W (SA FT)) +(all (== CB (KEYS (SB FT)))) -- true +(all (== CA (KEYS (SA FT)))) -- true +(set W (SB FT)) +(all (== CA (KEYS (SA FT)))) -- true +(all (== CB (KEYS (SB FT)))) -- true +;; the vocabulary rewrite +(set VCB (KEYS (VB FT))) +(set W (VA FT)) +(all (== VCB (KEYS (VB FT)))) -- true +;; in memory +(set MB (KEYS (SB TP))) +(set W (SA TP)) +(all (== MB (KEYS (SB TP)))) -- true +(set MVB (KEYS (VB TP))) +(set W (VA TP)) +(all (== MVB (KEYS (VB TP)))) -- true +;; the subset's keys do not lead the full selection's order +(all (== (take CB (count CA)) CA)) -- false +(.sys.exec "rm -rf /tmp/rfl_dkey_prog/") -- 0 + +;; ── an `if` inside a by-DICT key ─────────────────────────────────────── +;; It selects per row, exactly as in a projection or a bare by:. The +;; by-dict used to evaluate its keys with the tree-walking `if`, which +;; tests ONE truth value — a vector condition is truthy, so every row got +;; the then-branch and the else-branch never reached a group. Oracle: the +;; key built row by row (map over row indices, the scalar `if`), then a +;; plain group-by on the materialised column. 80000 rows so the +;; column-wise `if` runs pooled (past 65536) with and without a dense +;; where:; nulls in both condition columns and in the symbol branch. +(set M 80000) +(set j (til M)) +(set se (as 'I16 (% (* j 7) 5))) +(set ae (as 'I16 (% (* j 11) 3))) +(set rf (as 'SYMBOL (map (fn [k] (if (== 0 (% k 19)) "" (format "https://ref%.example.com/path/%" (% k 211) (% k 7)))) j))) +(set ur (as 'SYMBOL (map (fn [k] (format "u%" (% k 7))) j))) +(set w (% j 10)) +(set TD0 (table [se ae rf ur w] (list se ae rf ur w))) +(set TD (update {ae: 0Nh where: (== 0 (% (til M) 17)) from: (update {se: 0Nh where: (== 0 (% (til M) 13)) from: TD0})})) +(count TD) -- 80000 +(set KOR (fn [t] (as 'STR (map (fn [k] (if (and (== (at (at t 'se) k) 0) (== (at (at t 'ae) k) 0)) (as 'STR (at (at t 'rf) k)) "")) (til (count t)))))) +(set KO2 (fn [t] (as 'STR (map (fn [k] (if (> (at (at t 'w) k) 4) (as 'STR (at (at t 'rf) k)) (as 'STR (at (at t 'ur) k)))) (til (count t)))))) +(set OT (fn [t ks] (table [se ae src dst w] (list (at t 'se) (at t 'ae) ks (at t 'ur) (at t 'w))))) +(set OTD (OT TD (KOR TD))) +(set OTD2 (OT TD (KO2 TD))) +(set ORD (fn [o] (select {from: o by: [se ae src dst] c: (count dst) sw: (sum w)}))) +(set FPD (fn [r] (ser (xasc (table [se ae src dst c sw] (list (at r 'se) (at r 'ae) (as 'STR (at r 'src)) (as 'STR (at r 'dst)) (at r 'c) (at r 'sw))) [se ae src dst])))) +;; SYM column against a string literal +(set QD (fn [t] (select {from: t by: {se: se ae: ae src: (if (and (== se 0) (== ae 0)) rf "") dst: ur} c: (count ur) sw: (sum w)}))) +(set RD (QD TD)) +(set OD (ORD OTD)) +(== (count RD) (count OD)) -- true +(all (== (FPD RD) (FPD OD))) -- true +;; the else-branch reaches the groups +(> (count (select {from: RD where: (== src "")})) 0) -- true +(> (count (select {from: RD where: (!= src "")})) 0) -- true +;; two symbol columns as the branches +(set QD2 (fn [t] (select {from: t by: {se: se ae: ae src: (if (> w 4) rf ur) dst: ur} c: (count ur) sw: (sum w)}))) +(all (== (FPD (QD2 TD)) (FPD (ORD OTD2)))) -- true +;; where: dense (90%, still pooled), sparse (10%), empty +(set QW (fn [t p] (select {from: t by: {se: se ae: ae src: (if (and (== se 0) (== ae 0)) rf "") dst: ur} c: (count ur) sw: (sum w) where: (p w)}))) +(set OW (fn [p] (ORD (select {from: OTD where: (p w)})))) +(set PD (fn [x] (!= x 3))) +(set PS (fn [x] (== x 3))) +(all (== (FPD (QW TD PD)) (FPD (OW PD)))) -- true +(all (== (FPD (QW TD PS)) (FPD (OW PS)))) -- true +(count (QW TD (fn [x] (> x 100)))) -- 0 +;; the same table read back from disk: the symbol columns' ids live in FILE domains +(.sys.exec "rm -rf /tmp/rfl_dkey_bydict/") -- 0 +(.db.splayed.set "/tmp/rfl_dkey_bydict/" TD) +(set FD (.db.splayed.get "/tmp/rfl_dkey_bydict/")) +(all (== (FPD (QD FD)) (FPD OD))) -- true +(all (== (FPD (QD2 FD)) (FPD (ORD OTD2)))) -- true +(all (== (FPD (QW FD PD)) (FPD (OW PD)))) -- true +(all (== (FPD (QW FD PS)) (FPD (OW PS)))) -- true +(.sys.exec "rm -rf /tmp/rfl_dkey_bydict/") -- 0 +;; below the pool threshold the column-wise `if` takes its per-row arm: same groups +(set TS (take TD 3000)) +(all (== (FPD (QD TS)) (FPD (ORD (OT TS (KOR TS)))))) -- true +;; a condition that reduces to one value is a scalar test, not a per-row +;; one: every row takes the then-branch, as before +(set RSC (select {from: TS by: {src: (if (> (count w) 3) rf "")} c: (count w)})) +(set OSC (select {from: TS by: rf c: (count w)})) +(== (count RSC) (count OSC)) -- true +(all (== (asc (at RSC 'c)) (asc (at OSC 'c)))) -- true diff --git a/test/rfl/group/derived_key_vocab_aggs.rfl b/test/rfl/group/derived_key_vocab_aggs.rfl index d55740411..6c958ae0f 100644 --- a/test/rfl/group/derived_key_vocab_aggs.rfl +++ b/test/rfl/group/derived_key_vocab_aggs.rfl @@ -30,11 +30,34 @@ (all (== (as 'STR (at (select {from: R asc: c}) 'mn)) (as 'STR (at (select {from: O asc: c}) 'mn)))) -- true (all (== (as 'STR (at (select {from: R asc: c}) 'mx)) (as 'STR (at (select {from: O asc: c}) 'mx)))) -- true (all (== (as 'STR (at (select {from: R asc: c}) 'p)) (as 'STR (at (select {from: O asc: c}) 'p)))) -- true -;; the same table in memory (runtime domain) takes the row path and agrees +;; the same table in memory (the column's ids are runtime ids, read from +;; the table's own atoms) takes the same route and agrees (set RM (key T)) (== (count RM) (count R)) -- true (same RM R 'c) -- true (same RM R 'l) -- true +;; ── the key values never enter the global symbol table ───────────────── +;; The key strings go into a domain of the key column's own, released with +;; the result: the runtime table ((.sys.mem) 'sym-count) is exactly as +;; large after the query as before it, over the file-backed table and over +;; 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 +(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 +(same (at NG 1) O 'c) -- true +(set NGM (nogrow (fn [] (key T)))) +(at NGM 0) -- 0 +(same (at NGM 1) O 'l) -- true +;; the key column stays a symbol column, resolvable through its own domain +(type (at (at NG 1) 'p)) -- 'SYM +(count (distinct (as 'STR (at (at NGM 1) 'p)))) -- 80 +;; and the result survives its source: the domain lives with the column +(set KEEP (at (at NGM 1) 'p)) +(set NGM 0) +(count (distinct (as 'STR KEEP))) -- 80 ;; no where: the null group is there, its avg is the null float, its min the empty symbol (set R2 (select {from: F by: (substr ref 1 4) c: (count ref) l: (avg (strlen ref)) mn: (min ref)})) (set O2 (select {from: F by: (substr ref 1 4) c: (count ref) l: (avg (strlen ref)) mn: (min ref) sv: (sum v)})) diff --git a/test/rfl/group/group_key_types.rfl b/test/rfl/group/group_key_types.rfl index aca43f3fc..a0ff799a0 100644 --- a/test/rfl/group/group_key_types.rfl +++ b/test/rfl/group/group_key_types.rfl @@ -201,3 +201,26 @@ (set Rsw8b (select {c: (count v) from: Tsw8b by: [k1 k2]})) (>= (count Rsw8b) 3) -- true (.sys.exec "rm -f /tmp/rfl_grp_sw8.csv") -- 0 + +;; A key that evaluates to one value — a literal, or a `let` whose body is +;; one — is that value on every row: one group. It came back as an atom or +;; a one-element vector and was read as a full column past its end, giving +;; random groups on one core and a crash on the workers. +(set Tconst (table [ref v] (list (as 'SYM (% (til 70000) 300)) (til 70000)))) +(set Rconst (select {from: Tconst by: (let a ref "const") c: (count ref) s: (sum v)})) +(at Rconst 'ref) -- ["const"] +(at Rconst 'c) -- [70000] +(at Rconst 's) -- [2449965000] +(at (select {from: Tconst by: "const" c: (count ref)}) 'c) -- [70000] +(at (select {from: Tconst by: (let a ref 7) c: (count ref)}) 'c) -- [70000] +(at (select {from: Tconst by: (let a ref 2020.01.01) c: (count ref)}) 'ref) -- [2020.01.01] +(at (select {from: Tconst by: (let a ref 7) c: (count ref) where: (> v 69990)}) 'c) -- [9] +(at (select {from: (table [ref v] (list (as 'SYM (% (til 70) 3)) (til 70))) by: (let a ref "const") c: (count ref)}) 'c) -- [70] +(at (select {from: (table [ref v] (list ['a] [1])) by: "const" c: (count ref)}) 'c) -- [1] + +;; A STR atom as an aggregate input is that value in every group; it had no +;; broadcast case and the query failed with "oom" (or worse). +(set TSa (table [x s] (list (til 6) ['a 'b 'c 'a 'b 'c]))) +(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"] diff --git a/test/rfl/group/group_tablestack.rfl b/test/rfl/group/group_tablestack.rfl new file mode 100644 index 000000000..3fc6cab85 --- /dev/null +++ b/test/rfl/group/group_tablestack.rfl @@ -0,0 +1,123 @@ +;; group_tablestack.rfl — the table-stack strategy (src/ops/agg_engine.c, +;; exec_group_v2_parallel_tablestack): parallel int/SYM-key groups whose keys +;; are too sparse for the dense direct-index plan and whose sampled +;; cardinality is low pre-aggregate into per-task top-bit tables and merge by +;; partition; a task whose table fills with mostly-distinct keys switches to +;; raw scatter, and an input whose sample (of the selected rows under a +;; where:) shows high cardinality declines to the radix scatter. Keys are +;; spread with `* 1000003` so the dense plan bails (same trick as +;; group_radix_rightsize). +;; Every expected value below is closed-form: row r carries key index +;; (9 r) mod 10 (7919 mod 10 = 9), so group g' (first seen at row g') holds +;; the rows r = g' + 10 m, m in [0, 20000). + +(set N 200000) +(set i (til N)) +(set T10 (table [k j v] (list (* (% (* i 7919) 10) 1000003) (% i 7) i))) + +;; ── ten sparse keys: no task ever scatters; exact sums, first-seen order ── +(set R10 (select {from: T10 s: (sum v) c: (count v) mn: (min v) mx: (max v) by: k})) +(count R10) -- 10 +(at R10 'k) -- [0 9000027 8000024 7000021 6000018 5000015 4000012 3000009 2000006 1000003] +(at R10 'c) -- [20000 20000 20000 20000 20000 20000 20000 20000 20000 20000] +(at R10 'mn) -- [0 1 2 3 4 5 6 7 8 9] +(at R10 'mx) -- [199990 199991 199992 199993 199994 199995 199996 199997 199998 199999] +(at R10 's) -- [1999900000 1999920000 1999940000 1999960000 1999980000 2000000000 2000020000 2000040000 2000060000 2000080000] +(sum (at R10 's)) -- 19999900000 + +;; ── pushed WHERE: the selected-row space is chunked per task ───────────── +(set W10 (select {from: T10 s: (sum v) c: (count v) by: k where: (< v 100000)})) +(at W10 'k) -- [0 9000027 8000024 7000021 6000018 5000015 4000012 3000009 2000006 1000003] +(at W10 'c) -- [10000 10000 10000 10000 10000 10000 10000 10000 10000 10000] +(at W10 's) -- [499950000 499960000 499970000 499980000 499990000 500000000 500010000 500020000 500030000 500040000] + +;; ── composite key (sparse int + small int): 70 groups ──────────────────── +(set M10 (select {from: T10 c: (count v) by: [k j]})) +(count M10) -- 70 +(sum (at M10 'c)) -- 200000 +(at (select {from: M10 n: (count c) by: k}) 'n) -- [7 7 7 7 7 7 7 7 7 7] + +;; ── SYM + sparse int composite ─────────────────────────────────────────── +(set vocab (as 'SYM (map (fn [x] (format "ts%" x)) (til 3)))) +(set Ts (table [s k v] (list (at vocab (% i 3)) (* (% (* i 7919) 10) 1000003) i))) +(set Rs (select {from: Ts c: (count v) sv: (sum v) by: [s k]})) +(count Rs) -- 30 +(sum (at Rs 'c)) -- 200000 +(sum (at Rs 'sv)) -- 19999900000 + +;; ── native top-N over the merged partitions ────────────────────────────── +(at (select {from: T10 s: (sum v) by: k desc: s take: 3}) 'k) -- [1000003 2000006 3000009] +(at (select {from: T10 s: (sum v) by: k desc: s take: 3}) 's) -- [2000080000 2000060000 2000040000] + +;; ── medium cardinality: 5000 keys, forty rows each, one table per task ─── +(set T50 (table [k v] (list (* (% (* i 7919) 5000) 1000003) i))) +(set R50 (select {from: T50 c: (count v) s: (sum v) by: k})) +(count R50) -- 5000 +(min (at R50 'c)) -- 40 +(max (at R50 'c)) -- 40 +(sum (at R50 's)) -- 19999900000 +;; first-seen order: the first row of each group ascends with the output row. +(set F50 (select {from: T50 f: (first v) by: k})) +(all (== (at F50 'f) (asc (at F50 'f)))) -- true + +;; ── skewed input: 950000 rows over ten hot keys (75%) and 2000 middle keys +;; (25%, ~120 rows each), then 50000 all-distinct rows. The sample +;; estimates a few thousand groups (the middle layer supplies the pairs +;; Chao1 divides by) and only ~5% of rows are singletons, so the table +;; stack is taken; the last task fills a 32768-slot table at a low +;; distinct ratio (push), then fills the next one with distinct keys only +;; (switch to raw scatter) ──────────────────────────────────────────────── +(set N2 1000000) +(set j (til 950000)) +(set flag (div (% j 8) 6)) +(set hot (* (% (* j 7919) 10) 1000003)) +(set mid (* (+ 10 (% (div j 8) 2000)) 1000003)) +(set head (+ (* (- 1 flag) hot) (* flag mid))) +(set Tk (table [k v] (list (raze (list head (* (+ (til 50000) 2010) 1000003))) (til N2)))) +(set Rk (select {from: Tk c: (count v) s: (sum v) by: k})) +(count Rk) -- 52010 +(sum (at Rk 'c)) -- 1000000 +(asc (distinct (at Rk 'c))) -- [1 118 120 71250] +(at (at Rk 'k) (til 12)) -- [0 9000027 8000024 7000021 6000018 5000015 10000030 2000006 1000003 11000033 4000012 3000009] +(at (select {from: Tk s: (sum v) c: (count v) by: k where: (== k 0)}) 's) -- [33843037500] +(at (select {from: Tk s: (sum v) c: (count v) by: k where: (== k 0)}) 'c) -- [71250] +(at (select {from: Tk s: (sum v) c: (count v) by: k where: (== k 10000030)}) 's) -- [56640780] +(at (select {from: Tk s: (sum v) c: (count v) by: k where: (== k 10000030)}) 'c) -- [120] +(at (select {from: Tk s: (sum v) by: k where: (== k 2010006030)}) 's) -- [950000] +(set Fk (select {from: Tk f: (first v) by: k})) +(all (== (at Fk 'f) (asc (at Fk 'f)))) -- true +(all (== (at (select {from: Tk c: (count v) by: k where: (>= v 950000)}) 'k) (* (+ (til 50000) 2010) 1000003))) -- true +;; selected rows: even v reaches five hot keys, the middle layer and half the tail +(count (select {from: Tk c: (count v) by: k where: (== (% v 2) 0)})) -- 27005 +(set Tk 0) (set Rk 0) (set Fk 0) (set j 0) (set flag 0) (set hot 0) (set mid 0) (set head 0) + +;; ── sorted key repeating in runs of five rows (one group per five rows): +;; the gate samples single scattered rows, sees no repeats and declines +;; to radix — the merged result is exact either way ────────────────────── +(set Tr (table [k v] (list (* (div i 5) 1000003) i))) +(set Rr (select {from: Tr c: (count v) s: (sum v) by: k})) +(count Rr) -- 40000 +(asc (distinct (at Rr 'c))) -- [5] +(all (== (at Rr 'k) (* (til 40000) 1000003))) -- true +(all (== (at Rr 's) (+ (* 25 (til 40000)) 10))) -- true +(count (select {from: Tr c: (count v) by: k where: (< (% v 10) 3)})) -- 20000 +(set Tr 0) (set Rr 0) + +;; ── all-distinct keys: the sample gate declines to the radix scatter; one +;; group per row, emitted in input order ───────────────────────────────── +(set Th (table [k v] (list (* i 1000003) i))) +(set Rh (select {from: Th c: (count v) s: (sum v) by: k})) +(count Rh) -- 200000 +(max (at Rh 'c)) -- 1 +(all (== (at Rh 'k) (* (til N) 1000003))) -- true +(all (== (at Rh 's) (til N))) -- true +;; the same with a filter that keeps every third row +(set Wh (select {from: Th c: (count v) by: k where: (== (% v 3) 0)})) +(count Wh) -- 66667 +(all (== (at Wh 'k) (* (* 3 (til 66667)) 1000003))) -- true + +;; ── negative keys and a narrow key type ────────────────────────────────── +(set Tn (table [k v] (list (- (* (% (* i 7919) 10) 1000003) 5000000) (as 'I32 (% (* i 7919) 3000)) ))) +(set Rn (select {from: Tn c: (count k) by: v})) +(count Rn) -- 3000 +(at (select {from: Tn mn: (min k) mx: (max k) by: k}) 'k) -- [-5000000 4000027 3000024 2000021 1000018 15 -999988 -1999991 -2999994 -3999997] diff --git a/test/rfl/group/take_unordered_dense.rfl b/test/rfl/group/take_unordered_dense.rfl index 7a842aea6..a95aebe72 100644 --- a/test/rfl/group/take_unordered_dense.rfl +++ b/test/rfl/group/take_unordered_dense.rfl @@ -19,3 +19,61 @@ (set r3 (select {from: t f: (first v) by: {k: k j: (% v 3)} take: 7})) (count r3) -- 7 (all (== (at r3 'f) (asc (at r3 'f)))) -- true + +;; ─── first N groups found before aggregating ──────────────────────────────── +;; Over a large input an unordered take: N finds its N groups first (the first +;; N distinct key tuples in row order) and aggregates only their rows. Every +;; answer must be the first N groups of the full grouped result in first-seen +;; order (ascending first row f), each aggregate over ALL rows of its group. +(set eqt (fn [x y] (and (all (== (cols x) (cols y))) (== (count x) (count y)) (all (map (fn [c] (and (== (type (at x c)) (type (at y c))) (all (== (at x c) (at y c))))) (cols x)))))) +(set n2 300000) +(set i2 (til n2)) +;; u: 50000 groups of 6 rows (rows j, j+50000, ...); s/w repeat with u, so +;; [u s] and [u s w] are 50000 groups of 6 too; nu has a null key at row 0 +(set F (table [i u s w y d ts nu v g fl h] (list i2 (% (* i2 7919) 50000) (as 'SYM (as 'STR (% i2 5))) (as 'I32 (% i2 10)) (as 'SYM (as 'STR (% (* i2 7919) 50000))) (as 'DATE (% (* i2 31) 20000)) (as 'TIMESTAMP (* 1000 (% (* i2 13) 60000))) (at (concat [0N] (til 4999)) (% (* i2 7919) 5000)) (at (concat [0N] (til 1000)) (% i2 1001)) (as 'SYM (as 'STR (% i2 97))) (* 0.5 (as 'F64 i2)) (div i2 2)))) +(eqt (select {from: F by: [u s] c: (count u) f: (min i) take: 10}) (take (xasc (select {from: F by: [u s] c: (count u) f: (min i)}) 'f) 10)) -- true +(at (select {from: F by: [u s] c: (count u) take: 10}) 'c) -- [6 6 6 6 6 6 6 6 6 6] +(eqt (select {from: F by: u c: (count u) sv: (sum v) av: (avg v) mn: (min v) mx: (max v) f: (min i) take: 10}) (take (xasc (select {from: F by: u c: (count u) sv: (sum v) av: (avg v) mn: (min v) mx: (max v) f: (min i)}) 'f) 10)) -- true +(eqt (select {from: F by: y c: (count v) sv: (sum v) f: (min i) take: 10}) (take (xasc (select {from: F by: y c: (count v) sv: (sum v) f: (min i)}) 'f) 10)) -- true +(eqt (select {from: F by: [u s w] c: (count u) sv: (sum v) f: (min i) take: 10}) (take (xasc (select {from: F by: [u s w] c: (count u) sv: (sum v) f: (min i)}) 'f) 10)) -- true +(eqt (select {from: F where: (> v 500) by: [u s] c: (count u) sv: (sum v) f: (min i) take: 10}) (take (xasc (select {from: F where: (> v 500) by: [u s] c: (count u) sv: (sum v) f: (min i)}) 'f) 10)) -- true +(at (select {from: F where: (> v 500) by: [u s] f: (min i) take: 3}) 'f) -- [502 503 504] +(eqt (select {from: F by: [u s] c: (count u) mx: (max v) f: (min i) take: 600}) (take (xasc (select {from: F by: [u s] c: (count u) mx: (max v) f: (min i)}) 'f) 600)) -- true +;; groups of two consecutive rows: 2000 matches in the first task spill to a +;; second collecting pass +(eqt (select {from: F by: h c: (count v) sv: (sum v) f: (min i) take: 1000}) (take (xasc (select {from: F by: h c: (count v) sv: (sum v) f: (min i)}) 'f) 1000)) -- true +(eqt (select {from: F by: [i s] c: (count u) mx: (max v) f: (min i) take: 1000}) (take (xasc (select {from: F by: [i s] c: (count u) mx: (max v) f: (min i)}) 'f) 1000)) -- true +(eqt (select {from: F by: d c: (count v) mn: (min ts) f: (min i) take: 5}) (take (xasc (select {from: F by: d c: (count v) mn: (min ts) f: (min i)}) 'f) 5)) -- true +(eqt (select {from: F by: ts c: (count v) av: (avg w) f: (min i) take: 7}) (take (xasc (select {from: F by: ts c: (count v) av: (avg w) f: (min i)}) 'f) 7)) -- true +(eqt (select {from: F by: nu c: (count v) sv: (sum v) f: (min i) take: 10}) (take (xasc (select {from: F by: nu c: (count v) sv: (sum v) f: (min i)}) 'f) 10)) -- true +(at (at (select {from: F by: nu c: (count v) take: 10}) 'nu) 0) -- 0Nl +(eqt (select {from: F by: [nu w] c: (count v) sv: (sum v) f: (min i) take: 10}) (take (xasc (select {from: F by: [nu w] c: (count v) sv: (sum v) f: (min i)}) 'f) 10)) -- true +;; the range form [start amount] reads the first start+amount groups +(eqt (select {from: F by: [u s] c: (count u) f: (min i) take: [3 5]}) (take (xasc (select {from: F by: [u s] c: (count u) f: (min i)}) 'f) [3 5])) -- true +(eqt (select {from: F by: [u s] c: (count u) f: (min i) take: [49998 5]}) (take (xasc (select {from: F by: [u s] c: (count u) f: (min i)}) 'f) [49998 5])) -- true +(count (select {from: F by: [u s] c: (count u) take: [60000 5]})) -- 0 +(count (select {from: F by: [u s] c: (count u) take: 0})) -- 0 +;; more wanted than there are groups: all of them, in first-seen order +(eqt (select {from: F by: w c: (count u) f: (min i) take: 100}) (xasc (select {from: F by: w c: (count u) f: (min i)}) 'f)) -- true +(count (select {from: (take F 0) by: u c: (count u) take: 10})) -- 0 +(count (select {from: F where: (> v 100000) by: u c: (count u) take: 10})) -- 0 +;; shapes the pre-pass leaves to the full aggregation answer the same way +(eqt (select {from: F by: g c: (count u) f: (min i) take: 10}) (take (xasc (select {from: F by: g c: (count u) f: (min i)}) 'f) 10)) -- true +(eqt (select {from: F by: u c: (count u) fv: (first v) f: (min i) take: 10}) (take (xasc (select {from: F by: u c: (count u) fv: (first v) f: (min i)}) 'f) 10)) -- true +(at (select {from: F by: u sf: (sum fl) take: 3}) 'u) -- [0 7919 15838] +;; a splayed (mapped) copy answers exactly like the in-memory table +(.sys.exec "rm -rf rf_test_firstn_take rf_test_firstn_parted") -- 0 +(.db.splayed.set "rf_test_firstn_take/" F) +(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 +(.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 (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/integration/conditionals.rfl b/test/rfl/integration/conditionals.rfl index 497b208cb..81c55c1f8 100644 --- a/test/rfl/integration/conditionals.rfl +++ b/test/rfl/integration/conditionals.rfl @@ -18,3 +18,20 @@ (set x 5) (if (< x 0) 'neg (if (== x 0) 'zero 'pos)) -- 'pos (set x -3) (if (< x 0) 'neg (if (== x 0) 'zero 'pos)) -- 'neg (set x 0) (if (< x 0) 'neg (if (== x 0) 'zero 'pos)) -- 'zero +;; ========== TRUTHINESS PER TYPE ========== +;; A zero of any numeric or temporal type is false, as is null. Only I64 +;; and F64 zeros used to be: an I32, I16 or U8 zero took the +;; then-branch, and `not` / `and` / `or` read it the same way. +(if (as 'i32 0) 1 2) -- 2 +(if (as 'i32 3) 1 2) -- 1 +(if (as 'i16 0) 1 2) -- 2 +(if (as 'u8 0) 1 2) -- 2 +(if (as 'u8 9) 1 2) -- 1 +(if (as 'date 0) 1 2) -- 2 +(if 0Ni 1 2) -- 2 +(if 0Nf 1 2) -- 2 +(if 256 1 2) -- 1 +(if 'a 1 2) -- 1 +(not (as 'i32 0)) -- true +(not (as 'i16 5)) -- false +(or (as 'u8 0) false) -- false diff --git a/test/rfl/integration/fused_group_parity.rfl b/test/rfl/integration/fused_group_parity.rfl index 2835f5353..dc00d40d0 100644 --- a/test/rfl/integration/fused_group_parity.rfl +++ b/test/rfl/integration/fused_group_parity.rfl @@ -224,31 +224,14 @@ (at (at (select {name: name n: n from: Tld where: (>= n 0) asc: name take: 3}) 'name) 2) -- 'zebra (.sys.exec "rm -f rf_test_local_dict_sym.csv") -- 0 -;; ────────────── Mixed-temporal compare must NOT fire fused ─────── +;; ────────────── Mixed-temporal compare ──────────────────────────── ;; DATE storage is int32 days-from-epoch; TIMESTAMP is int64 ns- -;; from-epoch. A raw-unit fused comparator would compare the two -;; integer fields directly — meaningless when the units differ. -;; The fused predicate gate refuses cross-temporal compares so the -;; unfused engine handles them. -;; -;; Caveat for this test (carried over from the round-5 review): the -;; unfused engine in rayforce *also* compares temporals by their -;; raw stored ints today, so the result is the same in both paths -;; for any single concrete (op, lhs-class, rhs-class, value) tuple -;; we can pick. In other words, this test pins down "the gate -;; routes the cross-temporal shape to the unfused path and the -;; result is whatever the unfused path produces" — it does NOT -;; distinguish raw-fused-result from a hypothetical normalised -;; result, because no such normalised result exists in the engine -;; today. A stronger regression here would require an engine-side -;; fix that adds proper temporal normalisation in cmp.c, which is -;; out of scope for this branch and tracked separately. +;; from-epoch. The compiler rewrites the DATE literal as a TIMESTAMP +;; constant before the predicate is built, so the fused and unfused +;; paths see a same-typed compare and keep the rows on or after +;; 2013.07.15. This line used to pin the raw-int answer (3). (set Tts (table [t v] (list (as 'TIMESTAMP [2013.07.01D00:00:00.000000 2013.07.15D00:00:00.000000 2013.07.31D00:00:00.000000]) [1 2 3]))) -;; The shape compiles and runs — that's what we're verifying here. -;; The exact count (3) reflects current engine semantics for a -;; cross-temporal compare; the value isn't the regression target, -;; the "doesn't crash / doesn't get a corrupted fused answer" is. -(count (select {c: (count v) from: Tts where: (>= t 2013.07.15) by: t})) -- 3 +(count (select {c: (count v) from: Tts where: (>= t 2013.07.15) by: t})) -- 2 ;; Same-typed DATE compare still works — verifies the gate allows ;; the supported same-class shape and didn't over-reject. diff --git a/test/rfl/io/csv_parted_staging.rfl b/test/rfl/io/csv_parted_staging.rfl new file mode 100644 index 000000000..0b37bba2d --- /dev/null +++ b/test/rfl/io/csv_parted_staging.rfl @@ -0,0 +1,33 @@ +;; csv_parted_staging.rfl — `.csv.parted` into a NEW root stages in +;; `.csv-partial` and keeps it after a failure, for diagnosis. +;; A mistyped source path must not leave that directory behind (it would +;; block every later import into the root), and a staging directory that +;; is left behind must be named in the error, not reported as a bare `io`. + +(.sys.exec "rm -rf rf_test_pstage rf_test_pstage.csv-partial rf_test_pstage2 rf_test_pstage2.csv-partial") -- 0 +(.sys.exec "printf 'a,b\\n1,x\\n2,y\\n' > rf_test_pstage.csv") -- 0 + +;; unreadable source: fails, and claims nothing +(.csv.parted "rf_test_pstage_missing.csv" "rf_test_pstage" 'tbl) !- io +(.sys.exec "test -e rf_test_pstage.csv-partial") -- 1 +;; a failure before the first partition (wrong type vector, empty source, +;; a directory as source) also leaves nothing behind +(.csv.parted [I64] "rf_test_pstage.csv" "rf_test_pstage" 'tbl) !- length +(.sys.exec "test -e rf_test_pstage.csv-partial") -- 1 +(.sys.exec ": > rf_test_pstage_empty.csv") -- 0 +(.csv.parted "rf_test_pstage_empty.csv" "rf_test_pstage" 'tbl) !- io +(.sys.exec "test -e rf_test_pstage.csv-partial") -- 1 +(.sys.exec "mkdir -p rf_test_pstage_dir") -- 0 +(.csv.parted "rf_test_pstage_dir" "rf_test_pstage" 'tbl) !- io +(.sys.exec "test -e rf_test_pstage.csv-partial") -- 1 +;; ...so the next import into the same root succeeds +(count (.csv.parted "rf_test_pstage.csv" "rf_test_pstage" 'tbl)) -- 2 + +;; a leftover staging directory still blocks the root (the C test +;; runtime/syscov_csv_parted_stale_staging checks that the error names it) +(.sys.exec "mkdir rf_test_pstage2.csv-partial") -- 0 +(.csv.parted "rf_test_pstage.csv" "rf_test_pstage2" 'tbl) !- io +(.sys.exec "rm -rf rf_test_pstage2.csv-partial") -- 0 +(count (.csv.parted "rf_test_pstage.csv" "rf_test_pstage2/" 'tbl)) -- 2 + +(.sys.exec "rm -rf rf_test_pstage rf_test_pstage2 rf_test_pstage_dir rf_test_pstage*.csv") -- 0 diff --git a/test/rfl/io/csv_splayed.rfl b/test/rfl/io/csv_splayed.rfl index 15c8a5b8b..ed1fe3d09 100644 --- a/test/rfl/io/csv_splayed.rfl +++ b/test/rfl/io/csv_splayed.rfl @@ -1,3 +1,4 @@ +;; @requires: posix ;; Coverage for src/io/csv.c splayed-writer paths, src/store/col.c str-pool ;; copy on load, and the GUID column writer. ;; @@ -136,9 +137,8 @@ (at (at Rnull 'b) 11) -- 12.5 ;; ════════════════════════════════════════════════════════════════ -;; 3. STR column via explicit schema — exercises ray_splay_save_bulk -;; fallback inside ray_csv_save_splayed_named_opts (col.c writes the -;; STR + adjacent str_pool inline), and col_copy_str_pool on load. +;; 3. Explicit STR schema streams descriptors and rebases pooled offsets. +;; The shared column writer appends the adjacent pool at commit. ;; ;; The schema-overridden form takes (.csv.splayed [names] [types] csv dir), ;; same dispatcher as ray_read_csv_splayed_fn. diff --git a/test/rfl/journal/ops_journal_wrappers.rfl b/test/rfl/journal/ops_journal_wrappers.rfl index 9592562fd..8d9f8633b 100644 --- a/test/rfl/journal/ops_journal_wrappers.rfl +++ b/test/rfl/journal/ops_journal_wrappers.rfl @@ -43,6 +43,7 @@ ;; left a journal open would make our .log.open fail with "already open". ;; Close defensively first (no-op + RAY_OK if already closed). (nil? (.log.close)) -- true +(.log.close 1) !- arity (.sys.exec "rm -f /tmp/rfl_ops_journal_wrap.log /tmp/rfl_ops_journal_wrap.qdb /tmp/rfl_ops_journal_wrap.qdb.tmp /tmp/rfl_ops_journal_wrap.*.log") ;; ════════════════════════════════════════════════════════════════════════ diff --git a/test/rfl/ops/pivot_coverage.rfl b/test/rfl/ops/pivot_coverage.rfl index 2378d0142..29695a4d6 100644 --- a/test/rfl/ops/pivot_coverage.rfl +++ b/test/rfl/ops/pivot_coverage.rfl @@ -478,19 +478,44 @@ RTTime -- [09:30:00.000 10:00:00.000 11:00:00.000] (at (at (select {s: (if cond s1 s2) from: T1StrB}) 's) 0) -- "worldv" ;; ==================================================================== -;; Section 22: exec_if — 1-row I64+STR table; fallback else path -;; Covers pivot.c line 116 (else { sp = ""; sl = 0; }) -;; and line 139: triggered when then/else scalar is a -;; non-STR, non-SYM type (e.g. I64) in a STR-output if. +;; Section 22: exec_if — a text branch with a numeric branch +;; A STR or SYM result has no cell for an I64: the fills read +;; the numbers as descriptors or symbol ids. One row happened +;; to come back as the I64 branch; two rows gave ["" "b"] for +;; cond [true false], n1 [7 8], s2 ["a" "b"]. It is a type +;; error now, whatever the row count. ;; ==================================================================== (set T1I64StrA (table [cond n1 s2] (list [true] [0] (list "worldv")))) -(count (at (select {s: (if cond n1 s2) from: T1I64StrA}) 's)) -- 1 -(at (at (select {s: (if cond n1 s2) from: T1I64StrA}) 's) 0) -- 0 +(select {s: (if cond n1 s2) from: T1I64StrA}) !- type (set T1I64StrB (table [cond s1 n2] (list [false] (list "hellov") [0]))) -(count (at (select {s: (if cond s1 n2) from: T1I64StrB}) 's)) -- 1 -(at (at (select {s: (if cond s1 n2) from: T1I64StrB}) 's) 0) -- 0 +(select {s: (if cond s1 n2) from: T1I64StrB}) !- type + +(set T2I64Str (table [cond n1 s2] (list [true false] [7 8] (list "a" "b")))) +(select {s: (if cond n1 s2) from: T2I64Str}) !- type +(set T2I64Sym (table [x s] (list (til 6) (as 'SYM ["a" "b" "c" "d" "e" "f"])))) +(select {k: (if (< x 3) s x) from: T2I64Sym}) !- type +(select {k: (if (< x 3) s 5) from: T2I64Sym}) !- type +(select {k: (if (< (count x) 3) s x) from: T2I64Sym}) !- type +;; A null literal is not a number here: it stands for the text null and +;; must keep working beside a text branch, in every place an `if` compiles. +(as 'STR (at (select {k: (if (< x 2) s 0N) from: T2I64Sym}) 'k)) -- ["a" "b" "" "" "" ""] +(as 'STR (at (select {k: (if (> x 3) 'q 0N) from: T2I64Sym}) 'k)) -- ["" "" "" "" "q" "q"] +(as 'STR (at (select {k: (cond ((> x 4) s) (else 0N)) from: T2I64Sym}) 'k)) -- ["" "" "" "" "" "f"] +(count (select {c: (count x) from: T2I64Sym by: {g: (if (> x 3) s 0N)}})) -- 3 +(count (select {from: T2I64Sym where: (== (if (> x 3) s 0N) 'e)})) -- 1 +(as 'STR (at (update {s: (if (> x 3) s 0N) from: T2I64Sym}) 's)) -- ["" "" "" "" "e" "f"] +;; ...and it is a real null, whatever the literal's type: the fills wrote +;; the literal's payload as a symbol id, so 0N gave a symbol that is not +;; null, 0Nf (NaN bits) crashed the symbol lookup, and 0Nh named whichever +;; symbol had that id. +(nil? (at (select {k: (if (< x 2) s 0N) from: T2I64Sym}) 'k)) -- [false false true true true true] +(nil? (at (select {k: (if (< x 2) s 0Nf) from: T2I64Sym}) 'k)) -- [false false true true true true] +(set many (as 'SYM (as 'STR (+ 500000 (til 40000))))) +(nil? (at (select {k: (if (< x 2) s 0Nh) from: T2I64Sym}) 'k)) -- [false false true true true true] +(nil? (at (select {k: (if (> x 3) 'q 0Nf) from: T2I64Sym}) 'k)) -- [true true true true false false] +(at (select {k: (if (> x 3) n 0Nf) from: (table [x n] (list (til 6) (list "a" "b" "c" "d" "e" "f")))}) 'k) -- ["" "" "" "" "e" "f"] ;; ==================================================================== ;; Section 23: exec_if — STR output, SYM *atom* then-branch @@ -781,6 +806,54 @@ RTimedead -- [09:30:00.000 11:00:00.000] (at (select {r: (if false f 1.0) from: TZ}) 'r) -- [1.0 1.0 1.0] (at (select {r: (if true f 1.0) from: TZ}) 'r) -- [1.5 2.5 3.5] +;; A reduction in the condition reaches the eager fill as a one-element BOOL +;; vector, not an atom. It was indexed per row too, so only the first row +;; followed the condition and the rest read past the cell. +(set TR (table [x s] (list (til 6) (as 'SYM ["a" "b" "c" "d" "e" "f"])))) +(at (select {k: (if (> (count x) 3) s "") from: TR}) 'k) -- ["a" "b" "c" "d" "e" "f"] +(at (select {k: (if (< (count x) 3) s "") from: TR}) 'k) -- ["" "" "" "" "" ""] +(at (select {k: (if (> (sum x) 3) x 0) from: TR}) 'k) -- [0 1 2 3 4 5] +(at (select {k: (if (< (sum x) 3) x 7) from: TR}) 'k) -- [7 7 7 7 7 7] +(at (select {k: (if (> (max x) 3) 1.5 x) from: TR}) 'k) -- [1.5 1.5 1.5 1.5 1.5 1.5] +(at (select {k: (if (< (max x) 3) 1.5 x) from: TR}) 'k) -- [0.0 1.0 2.0 3.0 4.0 5.0] + +;; A condition of another type follows the interpreter's truthiness (zero +;; I64 or F64 and null are false) per cell. It was read as raw bytes, so +;; `(if (+ (count x) 250) ...)` took the else-branch on row 0 and read past +;; the cell on later rows, and an I64 column picked only rows 0 and 8. +(set TN (table [x f] (list (til 12) (+ 0.0 (til 12))))) +(at (select {k: (if (+ (count x) 244) x 0) from: TN}) 'k) -- (til 12) +(at (select {k: (if (- (count x) 12) x 7) from: TN}) 'k) -- (take 7 12) +(at (select {k: (if (count x) x 0) from: TN}) 'k) -- (til 12) +(at (select {k: (if (max f) x 0) from: TN}) 'k) -- (til 12) +(at (select {k: (if x x 100) from: TN}) 'k) -- (concat 100 (+ 1 (til 11))) +(at (select {k: (if f 1 0) from: TN}) 'k) -- (concat 0 (take 1 11)) +(at (select {k: (if (count x) x 0) from: (table [x] (list (til 256)))}) 'k) -- (til 256) + +;; Per condition type: null and zero are false, anything else true, the +;; rule of the scalar `if`. A wider column was read one byte per row, so an +;; all-ones I64 condition was true on rows 0 and 8 only, I32 on every fourth +;; row, I16 on every other one. Text has no truth value and is refused. +(at (select {r: (if c 10 20) from: (table [c] (list (take 1 9)))}) 'r) -- (take 10 9) +(at (select {r: (if c 10 20) from: (table [c] (list (as 'i32 [1 0 1 0 1 0 1 0 1])))}) 'r) -- [10 20 10 20 10 20 10 20 10] +(at (select {r: (if c 10 20) from: (table [c] (list (as 'i16 [1 0 1 0 1 0 1 0 1])))}) 'r) -- [10 20 10 20 10 20 10 20 10] +(at (select {r: (if c 10 20) from: (table [c] (list (as 'u8 [1 0 1 0 1 0 1 0 1])))}) 'r) -- [10 20 10 20 10 20 10 20 10] +(at (select {r: (if c 10 20) from: (table [c] (list [0 1 256 0N]))}) 'r) -- [20 10 10 20] +(at (select {r: (if c 10 20) from: (table [c] (list (concat (as 'i32 [0 7]) 0Ni)))}) 'r) -- [20 10 20] +(at (select {r: (if c 10 20) from: (table [c] (list [0.0 1.5 0Nf -2.0]))}) 'r) -- [20 10 20 10] +(at (select {r: (if c 10 20) from: (table [c] (list (as 'date [0 1 2])))}) 'r) -- [20 10 10] +(select {r: (if c 10 20) from: (table [c] (list ['a 'b 'c]))}) !- type +(select {r: (if c 10 20) from: (table [c] (list (list "a" "b" "c")))}) !- type + +;; The same on enough rows for the fill to run on the worker pool. +(set TP (table [x s] (list (til 200000) (as 'SYM (% (til 200000) 7))))) +(sum (at (select {k: (if (> (count x) 3) x 0) from: TP}) 'k)) -- 19999900000 +(sum (at (select {k: (if (< (count x) 3) x 0) from: TP}) 'k)) -- 0 +(sum (at (select {k: (if (+ (count x) 0) x 0) from: TP}) 'k)) -- 19999900000 +(sum (at (select {k: (if (% x 2) x 0) from: TP}) 'k)) -- 10000000000 +(at (select {k: (if (> (count x) 3) s "") from: TP}) 'k) -- (as 'STR (at TP 's)) +(count (distinct (at (select {k: (if (< (count x) 3) s "") from: TP}) 'k))) -- 1 + ;; ── the null symbol needs no width handling ─────────────────────────── ;; SYM has no typed null and no `0Ns` literal (parse.c): the empty symbol `'` diff --git a/test/rfl/query/bydict_conditionals.rfl b/test/rfl/query/bydict_conditionals.rfl new file mode 100644 index 000000000..a3c5419c8 --- /dev/null +++ b/test/rfl/query/bydict_conditionals.rfl @@ -0,0 +1,22 @@ +;; Computed dictionary group keys use row-wise query conditionals. +;; Evaluating `if` as a general special form treats its vector as truthy. +(set BC (table [engine adv ref url] (list [0 2 0 2] [0 0 1 1] ["first" "second" "third" "fourth"] ["u" "u" "u" "u"]))) +(set BCG (select {from: BC by: {src: (if (and (== engine 0) (== adv 0)) ref "")} n: (count url) asc: src})) +(count BCG) -- 2 +(at (at BCG 'src) 0) -- "" +(at (at BCG 'src) 1) -- "first" +(all (== (at BCG 'n) [3 1])) -- true + +;; Prefiltered and nested conditions preserve the selected row positions. +(set BCF (select {from: BC by: {src: (if (== engine 0) (if (== adv 0) ref "paid") "search")} n: (count url) where: (> adv 0) asc: src})) +(count BCF) -- 2 +(at (at BCF 'src) 0) -- "paid" +(at (at BCF 'src) 1) -- "search" +(all (== (at BCF 'n) [1 1])) -- true + +;; Later aliases can reference an earlier computed key. +(set BCA (select {from: BC by: {src: (if (== engine 0) ref "") size: (strlen src)} n: (count url) asc: size})) +(nil? (at (at BCA 'size) 0)) -- true +(at (at BCA 'size) 1) -- 5 +(at (at BCA 'size) 2) -- 5 +(sum (at BCA 'n)) -- 4 diff --git a/test/rfl/query/eval_fallback_parted.rfl b/test/rfl/query/eval_fallback_parted.rfl new file mode 100644 index 000000000..a4c4b8265 --- /dev/null +++ b/test/rfl/query/eval_fallback_parted.rfl @@ -0,0 +1,30 @@ +;; eval_fallback_parted.rfl — a projection the DAG declines (temporal + - *) +;; over a partitioned table is answered by the eval-level fallback (review of +;; #690). +;; +;; The fallback evaluated projections straight over the parted table; its +;; per-row reader has no arm for segmented columns, so `x: (+ d 1)` over a +;; .db.parted.get table raised `type` while the same query over a flat table +;; worked. Parted columns are now flattened before the fallback runs, as +;; `update` already does. +;; @requires: posix + +(.sys.exec "rm -rf /tmp/rfl_evalfb_parted") +(set T (table [i str d name] (list [1 2 3 4] (list "a" "" "ccc" "dd") [2001.01.01 2002.01.01 2003.01.01 2004.01.01] [Alice Bob Carol Dan]))) +(.db.splayed.set "/tmp/rfl_evalfb_parted/2024.01.01/t/" T "/tmp/rfl_evalfb_parted/.sym") +(.db.splayed.set "/tmp/rfl_evalfb_parted/2024.01.02/t/" T "/tmp/rfl_evalfb_parted/.sym") +(set P (.db.parted.get "/tmp/rfl_evalfb_parted/" 't)) + +;; ─── control: a compiled projection over the parted table ─────────────────── +(count (select {i: i from: P})) -- 8 + +;; ─── temporal arithmetic alone, and beside passthroughs of every kind ──────── +(at (select {x: (+ d 1) from: P}) 'x) -- (+ (at P 'd) 1) +(at (select {i: i x: (+ d 1) from: P}) 'i) -- [1 2 3 4 1 2 3 4] +(type (at (select {name: name x: (+ d 1) from: P}) 'name)) -- 'SYM +(at (select {name: name x: (+ d 1) from: P}) 'name) -- [Alice Bob Carol Dan Alice Bob Carol Dan] +(type (at (select {str: str x: (+ d 1) from: P}) 'str)) -- 'STR +(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] +(.sys.exec "rm -rf /tmp/rfl_evalfb_parted") diff --git a/test/rfl/query/eval_fallback_sym_computed.rfl b/test/rfl/query/eval_fallback_sym_computed.rfl new file mode 100644 index 000000000..1ea386eb5 --- /dev/null +++ b/test/rfl/query/eval_fallback_sym_computed.rfl @@ -0,0 +1,34 @@ +;; eval_fallback_sym_computed.rfl — a projection that evaluates to sym atoms +;; in the eval-level fallback is collected as a SYM vector, as the DAG path +;; returns for the same expression (follow-up to eval_fallback_sym_passthrough). +;; +;; The fallback's per-row cell collector collapsed every scalar kind but SYM / +;; STR / GUID into a typed vector; a sym-valued expression — `(if ...)` over +;; quoted symbols, or a quoted column name `'name` — came back as a LIST of +;; boxed sym atoms. SYM atoms now collapse like the other scalars. + +(set t (table [name ts i] (list [Alice Bob Carol] [2001.01.01D01:01:01.000000000 2002.02.02D02:02:02.000000000 2003.03.03D03:03:03.000000000] [1 2 3]))) + +;; ─── control: the DAG path ────────────────────────────────────────────────── +(type (at (select {from: t n: (if (> i 1) 'hi 'lo) x: (+ i 1)}) 'n)) -- 'SYM +(type (at (select {from: t n: 'name x: (+ i 1)}) 'n)) -- 'SYM + +;; ─── the fallback (temporal arithmetic beside it) ─────────────────────────── +(type (at (select {from: t n: (if (> i 1) 'hi 'lo) x: (+ ts 1)}) 'n)) -- 'SYM +(at (select {from: t n: (if (> i 1) 'hi 'lo) x: (+ ts 1)}) 'n) -- [lo hi hi] +(type (at (select {from: t n: 'name x: (+ ts 1)}) 'n)) -- 'SYM +(at (select {from: t n: 'name x: (+ ts 1)}) 'n) -- [Alice Bob Carol] + +;; a mixed-type projection still demotes to LIST rather than mis-typing +(type (at (select {from: t n: (if (> i 1) 'hi 0) x: (+ ts 1)}) 'n)) -- 'LIST + +;; ─── per-group fallback: a sym-valued non-aggregate output ────────────────── +(set g (table [k name ts] (list [a a b] [Alice Bob Carol] [2001.01.01D01:01:01.000000000 2002.02.02D02:02:02.000000000 2003.03.03D03:03:03.000000000]))) +(type (at (select {from: g by: k n: (first name) x: (first (+ ts 1))}) 'n)) -- 'SYM +(at (select {from: g by: k n: (first name) x: (first (+ ts 1))}) 'n) -- [Alice Carol] + +;; ─── a plain grouped select whose output is a sym cell ────────────────────── +;; `(at name 0)` is no aggregate, so it takes the per-group collector too; it +;; used to come back LIST and is SYM now, like the DAG's `(first name)`. +(type (at (select {from: g by: k n: (at name 0)}) 'n)) -- 'SYM +(at (select {from: g by: k n: (at name 0)}) 'n) -- [Alice Carol] diff --git a/test/rfl/query/eval_fallback_sym_passthrough.rfl b/test/rfl/query/eval_fallback_sym_passthrough.rfl new file mode 100644 index 000000000..d87ee8bc3 --- /dev/null +++ b/test/rfl/query/eval_fallback_sym_passthrough.rfl @@ -0,0 +1,44 @@ +;; eval_fallback_sym_passthrough.rfl — a SYM column projected beside a +;; projection the DAG declines (temporal + - *) keeps its SYM type. +;; +;; Temporal arithmetic makes compile_expr_dag return NULL, so the whole select +;; lands in the eval-level projection fallback. That path used to evaluate a +;; bare column name per row and collect the cells, and its cell collector never +;; collapses SYM / STR / GUID atoms into a typed vector — so `name: name` came +;; back as a LIST of boxed sym atoms and an inner-join on it matched nothing +;; (rayforce-py#24). A bare column name now takes the column itself. + +(set t (table [name s ts d tm i] (list [Alice Bob Carol] (list "a" "b" "c") [2001.01.01D01:01:01.000000000 2002.02.02D02:02:02.000000000 2003.03.03D03:03:03.000000000] [2001.01.01 2002.02.02 2003.03.03] [01:01:01.000 02:02:02.000 03:03:03.000] [1 2 3]))) + +;; ─── control: an I64 computed column compiles, SYM survives ───────────────── +(type (at (select {from: t name: name x: (+ i 1)}) 'name)) -- 'SYM + +;; ─── temporal arithmetic beside a SYM passthrough ─────────────────────────── +(type (at (select {from: t name: name x: (+ ts 1)}) 'name)) -- 'SYM +(type (at (select {from: t name: name x: (+ d 1)}) 'name)) -- 'SYM +(type (at (select {from: t name: name x: (+ tm 1)}) 'name)) -- 'SYM +(type (at (select {from: t name: name x: (- ts ts)}) 'name)) -- 'SYM +(at (select {from: t name: name x: (+ ts 1)}) 'name) -- [Alice Bob Carol] + +;; the computed column itself is unaffected +(at (select {from: t name: name x: (- ts ts)}) 'x) -- (- (at t 'ts) (at t 'ts)) + +;; aliasing, projection order and a where: clause make no difference +(type (at (select {from: t n: name x: (+ ts 1)}) 'n)) -- 'SYM +(type (at (select {from: t x: (+ ts 1) name: name}) 'name)) -- 'SYM +(type (at (select {from: t name: name x: (+ ts 1) where: (> i 1)}) 'name)) -- 'SYM +(at (select {from: t name: name x: (+ ts 1) where: (> i 1)}) 'name) -- [Bob Carol] + +;; other passthrough column kinds keep their type too +(type (at (select {from: t s: s x: (+ ts 1)}) 's)) -- 'STR +(at (select {from: t s: s x: (+ ts 1)}) 's) -- (list "a" "b" "c") +(type (at (select {from: t i: i x: (+ ts 1)}) 'i)) -- 'I64 +(type (at (select {from: t ts: ts x: (+ ts 1)}) 'ts)) -- 'TIMESTAMP + +;; ─── the downstream symptom: a join on the projected column ───────────────── +(set t2 (table [name last] (list [Alice Bob Carol] [Cooper Belcher Bells]))) +(at (inner-join [name] (select {from: t name: name x: (+ ts 1)}) t2) 'last) -- [Cooper Belcher Bells] + +;; ─── a lexical local shadows a column of the same name, as on the DAG ─────── +((fn [name] (at (select {from: t w: name x: (+ ts 1)}) 'w)) 'shadow) -- [shadow shadow shadow] +((fn [name] (at (select {from: t w: name}) 'w)) 'shadow) -- [shadow shadow shadow] diff --git a/test/rfl/query/eval_fallback_wide_computed.rfl b/test/rfl/query/eval_fallback_wide_computed.rfl new file mode 100644 index 000000000..6e549289b --- /dev/null +++ b/test/rfl/query/eval_fallback_wide_computed.rfl @@ -0,0 +1,34 @@ +;; eval_fallback_wide_computed.rfl — a STR- or GUID-valued projection in the +;; eval-level fallback is collected as a STR / GUID vector, as it is when the +;; same projection compiles (review of #690). +;; +;; The fallback's per-row cell collector collapsed scalars into a typed vector +;; except STR and GUID, so `(if (> i 2) str "zz")` alone was STR but became a +;; LIST of boxed atoms as soon as a projection the DAG declines (temporal +;; + - *) sat beside it: a column's type depended on its neighbour. + +(set T (table [i str d g] (list [1 2 3 4] (list "a" "" "ccc" "dd") [2001.01.01 2002.01.01 2003.01.01 2004.01.01] (guid 4)))) + +;; ─── control: the compiled path ───────────────────────────────────────────── +(type (at (select {w: (if (> i 2) str "zz") from: T}) 'w)) -- 'STR +(type (at (select {w: g from: T}) 'w)) -- 'GUID + +;; ─── STR beside a temporal projection ─────────────────────────────────────── +(type (at (select {w: (if (> i 2) str "zz") x: (+ d 1) from: T}) 'w)) -- 'STR +(at (select {w: (if (> i 2) str "zz") x: (+ d 1) from: T}) 'w) -- (list "zz" "zz" "ccc" "dd") +;; a string past the 12-byte inline size goes through the pool +(at (select {w: (if (> i 2) str "a-string-longer-than-twelve") x: (+ d 1) from: T}) 'w) -- (list "a-string-longer-than-twelve" "a-string-longer-than-twelve" "ccc" "dd") +;; a quoted STR column name +(type (at (select {w: 'str x: (+ d 1) from: T}) 'w)) -- 'STR + +;; ─── GUID beside a temporal projection ────────────────────────────────────── +(type (at (select {w: (if (> i 2) g g) x: (+ d 1) from: T}) 'w)) -- 'GUID +(at (select {w: (if (> i 2) g g) x: (+ d 1) from: T}) 'w) -- (at T 'g) + +;; ─── mixed types still demote to LIST ─────────────────────────────────────── +(type (at (select {w: (if (> i 2) str 0) x: (+ d 1) from: T}) 'w)) -- 'LIST + +;; ─── per-group fallback ───────────────────────────────────────────────────── +(set G (table [k str d] (list [a a b b] (list "a" "" "ccc" "dd") [2001.01.01 2002.01.01 2003.01.01 2004.01.01]))) +(type (at (select {from: G by: k w: (first str) x: (first (+ d 1))}) 'w)) -- 'STR +(at (select {from: G by: k w: (first str) x: (first (+ d 1))}) 'w) -- (list "a" "ccc") diff --git a/test/rfl/query/guid_fallback_collapse.rfl b/test/rfl/query/guid_fallback_collapse.rfl new file mode 100644 index 000000000..37bd2314d --- /dev/null +++ b/test/rfl/query/guid_fallback_collapse.rfl @@ -0,0 +1,43 @@ +;; Select eval fallback: a per-row / per-group projection that produces GUID +;; atoms is collapsed into a GUID column, not left as a LIST of GUID atoms. +;; `(+ ts 1)` beside the projection keeps the whole select on the eval +;; fallback (the DAG declines the temporal arithmetic), so every shape below +;; reaches eval_expr_per_row / nonagg_eval_per_group_core in query.c. +(set GV (as 'GUID (list "11111111-1111-4111-8111-111111111111" "22222222-2222-4222-8222-222222222222" "33333333-3333-4333-8333-333333333333" "44444444-4444-4444-8444-444444444444"))) +(set G0 (as 'GUID "00000000-0000-0000-0000-000000000000")) +(set G1 (at GV 0)) +(set T (table [i g ts s] (list [1 2 3 4] GV (+ 2024.01.01D00:00:00.000000000 (* 10 (til 4))) [a a b b]))) + +;; ─── ungrouped per-row scatter ───────────────────────────────────── +(type (at (select {w: (if (> i 2) g g) x: (+ ts 1) from: T}) 'w)) -- 'GUID +(at (select {w: (if (> i 2) g g) x: (+ ts 1) from: T}) 'w) -- GV +(at (select {w: (if (> i 2) g (at GV (- 3 i))) x: (+ ts 1) from: T}) 'w) -- (as 'GUID (list "33333333-3333-4333-8333-333333333333" "22222222-2222-4222-8222-222222222222" "33333333-3333-4333-8333-333333333333" "44444444-4444-4444-8444-444444444444")) +;; a GUID atom global in one branch +(type (at (select {w: (if (> i 2) g G1) x: (+ ts 1) from: T}) 'w)) -- 'GUID +(at (select {w: (if (> i 2) g G1) x: (+ ts 1) from: T}) 'w) -- (as 'GUID (list "11111111-1111-4111-8111-111111111111" "11111111-1111-4111-8111-111111111111" "33333333-3333-4333-8333-333333333333" "44444444-4444-4444-8444-444444444444")) +;; GUID null atoms collapse too and stay null in the column +(type (at (select {w: (if (> i 2) g G0) x: (+ ts 1) from: T}) 'w)) -- 'GUID +(nil? (at (select {w: (if (> i 2) g G0) x: (+ ts 1) from: T}) 'w)) -- [true true false false] +(nil? (at (select {w: (if (> i 2) G0 G0) x: (+ ts 1) from: T}) 'w)) -- [true true true true] +(type (at (select {w: (if (> i 2) G0 G0) x: (+ ts 1) from: T}) 'w)) -- 'GUID +;; a lambda projection +(type (at (select {w: ((fn [x y] (if (> y 2) x G1)) g i) x: (+ ts 1) from: T}) 'w)) -- 'GUID +;; mixed GUID / numeric rows have no common column type: still a LIST +(type (at (select {w: (if (> i 2) g i) x: (+ ts 1) from: T}) 'w)) -- 'LIST +(at (select {w: (if (> i 2) g i) x: (+ ts 1) from: T}) 'w) -- (list 1 2 (at GV 2) (at GV 3)) + +;; ─── grouped: derived output evaluated once per group ────────────── +(type (at (select {w: (if (> (sum i) 3) (first g) G1) x: (+ (first ts) 1) by: s from: T}) 'w)) -- 'GUID +(at (select {w: (if (> (sum i) 3) (first g) G1) x: (+ (first ts) 1) by: s from: T}) 'w) -- (as 'GUID (list "11111111-1111-4111-8111-111111111111" "33333333-3333-4333-8333-333333333333")) +(type (at (select {w: (if (> (sum i) 3) (first g) (sum i)) x: (+ (first ts) 1) by: s from: T}) 'w)) -- 'LIST +;; grouped: non-aggregate lambda evaluated per group slice +(type (at (select {w: ((fn [x] (last x)) g) by: s from: T}) 'w)) -- 'GUID +(at (select {w: ((fn [x] (last x)) g) by: s from: T}) 'w) -- (as 'GUID (list "22222222-2222-4222-8222-222222222222" "44444444-4444-4444-8444-444444444444")) +(nil? (at (select {w: ((fn [x] (if (> (count x) 1) G0 (first x))) g) by: s from: T}) 'w)) -- [true true] +(type (at (select {w: ((fn [x] (if (> (count x) 1) G0 (first x))) g) by: s from: T}) 'w)) -- 'GUID + +;; ─── the collapsed column is a real GUID column downstream ───────── +(count (distinct (at (select {w: (if (> i 2) g G1) x: (+ ts 1) from: T}) 'w))) -- 3 +(type (at (select {w: (if (> i 2) g g) x: (+ ts 1) from: T asc: w}) 'w)) -- 'GUID +(count (select {w: (if (> i 2) g G1) x: (+ ts 1) from: T where: (== i 3)})) -- 1 +(type (at (update {w: ((fn [x y] (if (> y 2) x G1)) g i) from: T}) 'w)) -- 'GUID diff --git a/test/rfl/query/highcard_group.rfl b/test/rfl/query/highcard_group.rfl index c44489ae8..9fe296685 100644 --- a/test/rfl/query/highcard_group.rfl +++ b/test/rfl/query/highcard_group.rfl @@ -1,15 +1,19 @@ -;; High-cardinality group-by pinning tests for the partition-major build -;; (docs/superpowers/specs/2026-08-15-high-card-group-scaling.md, Part A). -;; 300K rows forces the parallel radix_v2 path even under RAYFORCE_CORES=2; +;; @requires: posix +;; High-cardinality group-by checks across the parallel dense/radix routes. +;; The selected route depends on worker count and cache size. Unordered +;; full-group output need not have the same order across those routes; ;; keys are arithmetic so every expected value is closed-form. ;; ~100K distinct I64 keys, 3 rows each: count per group is exactly 3. (set HK (table [k] (list (% (til 300000) 100000)))) (count (select {c: (count k) by: k from: HK})) -- 100000 (sum (at (select {c: (count k) by: k from: HK}) 'c)) -- 300000 -;; stable first-seen order: first group is key 0, last is key 99999 -(at (at (select {c: (count k) by: k from: HK}) 'k) 0) -- 0 -(at (at (select {c: (count k) by: k from: HK}) 'k) 99999) -- 99999 +;; Check every key/count, and request ordering for positional assertions. +(set HKR (select {c: (count k) by: k from: HK asc: k})) +(all (== (at HKR 'k) (til 100000))) -- true +(all (== (at HKR 'c) 3)) -- true +(at (at HKR 'k) 0) -- 0 +(at (at HKR 'k) 99999) -- 99999 ;; top-N by count with ties: every count == 3, keep semantics unchanged (count (select {c: (count k) by: k from: HK desc: c take: 10})) -- 10 diff --git a/test/rfl/query/if_temporal_null.rfl b/test/rfl/query/if_temporal_null.rfl new file mode 100644 index 000000000..15edc2c42 --- /dev/null +++ b/test/rfl/query/if_temporal_null.rfl @@ -0,0 +1,68 @@ +;; `if` with a temporal branch and a bare null literal keeps the temporal +;; type (issue #673). +;; +;; `0N` is an I64 literal and promote() folds DATE + I64 to I64 (TIME to I64, +;; TIMESTAMP to I64), so `(if c d 0N)` came back as an I64 column of day +;; numbers with I64 nulls. ray_if (src/ops/graph.c) now gives a temporal +;; branch beside a null literal the temporal type and swaps the literal for +;; the typed null, the same way it already does for a null literal beside a +;; text branch (#668). A non-null number beside a temporal still promotes. + +(set TD (table [x d t ts] (list (til 4) (as 'DATE [1 2 3 4]) (as 'TIME [1 2 3 4]) (as 'TIMESTAMP [1 2 3 4])))) + +;; ── the explicit typed null is the oracle ─────────────────────────────────── +(type (at (select {k: (if (> x 1) d 0Nd) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) d 0Nd) from: TD}) 'k) -- [0Nd 0Nd 2000.01.04 2000.01.05] + +;; ── DATE / TIME / TIMESTAMP beside 0N, both orders ────────────────────────── +(type (at (select {k: (if (> x 1) d 0N) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) d 0N) from: TD}) 'k) -- [0Nd 0Nd 2000.01.04 2000.01.05] +(type (at (select {k: (if (> x 1) 0N d) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) 0N d) from: TD}) 'k) -- [2000.01.02 2000.01.03 0Nd 0Nd] +(type (at (select {k: (if (> x 1) t 0N) from: TD}) 'k)) -- 'TIME +(at (select {k: (if (> x 1) t 0N) from: TD}) 'k) -- [0Nt 0Nt 00:00:00.003 00:00:00.004] +(type (at (select {k: (if (> x 1) 0N t) from: TD}) 'k)) -- 'TIME +(type (at (select {k: (if (> x 1) ts 0N) from: TD}) 'k)) -- 'TIMESTAMP +(at (select {k: (if (> x 1) ts 0N) from: TD}) 'k) -- [0Np 0Np 2000.01.01D00:00:00.000000003 2000.01.01D00:00:00.000000004] +(type (at (select {k: (if (> x 1) 0N ts) from: TD}) 'k)) -- 'TIMESTAMP + +;; ── other null literal widths: 0Nf (F64) and 0Ni (I32) ────────────────────── +(type (at (select {k: (if (> x 1) d 0Nf) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) d 0Nf) from: TD}) 'k) -- [0Nd 0Nd 2000.01.04 2000.01.05] +(type (at (select {k: (if (> x 1) 0Nf ts) from: TD}) 'k)) -- 'TIMESTAMP +(type (at (select {k: (if (> x 1) d 0Ni) from: TD}) 'k)) -- 'DATE +(type (at (select {k: (if (> x 1) t 0Ni) from: TD}) 'k)) -- 'TIME + +;; ── the nulls are nulls, not day numbers ──────────────────────────────────── +(nil? (at (select {k: (if (> x 1) d 0N) from: TD}) 'k)) -- [true true false false] +(nil? (at (select {k: (if (> x 1) ts 0N) from: TD}) 'k)) -- [true true false false] +(nil? (at (select {k: (if (> x 1) 0Nf t) from: TD}) 'k)) -- [false false true true] + +;; ── cond, update, where:, by: go through the same node ────────────────────── +(type (at (select {k: (cond ((> x 1) d) (else 0N)) from: TD}) 'k)) -- 'DATE +(at (select {k: (cond ((> x 1) d) (else 0N)) from: TD}) 'k) -- [0Nd 0Nd 2000.01.04 2000.01.05] +(type (at (update {k: (if (> x 1) d 0N) from: TD}) 'k)) -- 'DATE +(at (update {k: (if (> x 1) ts 0N) from: TD}) 'k) -- [0Np 0Np 2000.01.01D00:00:00.000000003 2000.01.01D00:00:00.000000004] +(at (select {x: x from: TD where: (nil? (if (> x 1) d 0N))}) 'x) -- [0 1] +(type (at (select {n: (count x) from: TD by: {k: (if (> x 1) d 0N)}}) 'k)) -- 'DATE + +;; ── literal-only and nested branches ──────────────────────────────────────── +(type (at (select {k: (if (> x 1) 2024.01.01 0N) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) 2024.01.01 0N) from: TD}) 'k) -- [0Nd 0Nd 2024.01.01 2024.01.01] +(type (at (select {k: (if (> x 1) 0Nd 0N) from: TD}) 'k)) -- 'DATE +(type (at (select {k: (if (> x 1) (if (> x 2) d 0N) 0Nf) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) (if (> x 2) d 0N) 0Nf) from: TD}) 'k) -- [0Nd 0Nd 0Nd 2000.01.05] + +;; ── unchanged: a non-null number beside a temporal still promotes ─────────── +(type (at (select {k: (if (> x 1) d 5) from: TD}) 'k)) -- 'I64 +(at (select {k: (if (> x 1) d 5) from: TD}) 'k) -- [5 5 3 4] +;; a null literal of another temporal type is a null of the branch's type +(type (at (select {k: (if (> x 1) d 0Nt) from: TD}) 'k)) -- 'DATE +(at (select {k: (if (> x 1) d 0Nt) from: TD}) 'k) -- [0Nd 0Nd 2000.01.04 2000.01.05] +(type (at (select {k: (if (> x 1) ts 0Nd) from: TD}) 'k)) -- 'TIMESTAMP +(at (select {k: (if (> x 1) ts 0Nd) from: TD}) 'k) -- [0Np 0Np 2000.01.01D00:00:00.000000003 2000.01.01D00:00:00.000000004] +(nil? (at (select {k: (if (> x 1) ts 0Nd) from: TD}) 'k)) -- [true true false false] +(type (at (select {k: (if (> x 1) 0Np t) from: TD}) 'k)) -- 'TIME +(nil? (at (select {k: (if (> x 1) 0Np t) from: TD}) 'k)) -- [false false true true] +;; two typed temporal nulls: the then side wins +(type (at (select {k: (if (> x 1) 0Nd 0Np) from: TD}) 'k)) -- 'DATE diff --git a/test/rfl/query/legacy_strl_predicates.rfl b/test/rfl/query/legacy_strl_predicates.rfl index f0cb2fbf2..3982eaaa5 100644 --- a/test/rfl/query/legacy_strl_predicates.rfl +++ b/test/rfl/query/legacy_strl_predicates.rfl @@ -24,8 +24,10 @@ ;; == over the list column raises instead of silently matching nothing (select {from: TS where: (== s "keep me")}) !- type -;; scalar subject in where: loud length error, not an aliased-length oom -(select {from: TS where: (like "keep me" "*keep*")}) !- length +;; scalar subject in where: one value for every row, not an aliased-length +;; oom — true keeps every row, false none +(get (select {from: TS where: (like "keep me" "*keep*")}) 'v) -- [1 2 3] +(count (select {from: TS where: (like "drop" "*keep*")})) -- 0 ;; ilike over a numeric column raises instead of matching nothing (select {from: TS where: (ilike v "*1*")}) !- type diff --git a/test/rfl/query/narrow_lane_casts.rfl b/test/rfl/query/narrow_lane_casts.rfl new file mode 100644 index 000000000..149f07a1e --- /dev/null +++ b/test/rfl/query/narrow_lane_casts.rfl @@ -0,0 +1,57 @@ +;; A narrowing cast leaves an I32, I16 or one-byte lane in the compiled +;; expression; the next conversion read that lane as int64. +;; (+ (as 'I32 i) 1.5) came back as [8.59e+09 1.72e+10 1.5 1.5]. +;; Oracle: the same expression outside a select. +(set iv [1 2 3 4 -5 0]) +(set TC (table [i] (list iv))) +(at (select {x: (+ (as 'I32 i) 1.5) from: TC}) 'x) -- (+ (as 'I32 iv) 1.5) +(at (select {x: (+ (as 'I16 i) 1.5) from: TC}) 'x) -- (+ (as 'I16 iv) 1.5) +(at (select {x: (+ (as 'U8 i) 1.5) from: TC}) 'x) -- (+ (as 'U8 iv) 1.5) +(at (select {x: (* (as 'I32 i) 2) from: TC}) 'x) -- (* (as 'I32 iv) 2) +(at (select {x: (as 'F64 (as 'I32 i)) from: TC}) 'x) -- (as 'F64 (as 'I32 iv)) +(at (select {x: (as 'I16 (as 'I32 i)) from: TC}) 'x) -- (as 'I16 (as 'I32 iv)) +(at (select {x: (as 'I32 (as 'I16 i)) from: TC}) 'x) -- (as 'I32 (as 'I16 iv)) +(at (select {x: (as 'U8 (as 'I32 i)) from: TC}) 'x) -- (as 'U8 (as 'I32 iv)) +(at (select {x: (as 'I64 (as 'U8 i)) from: TC}) 'x) -- (as 'I64 (as 'U8 iv)) +(at (select {i: i from: TC where: (> (as 'I32 i) 2.5)}) 'i) -- [3 4] + +;; every narrow source into every narrow target, compiled +(at (select {x: (as 'I32 (as 'U8 i)) from: TC}) 'x) -- (as 'I32 (as 'U8 iv)) +(at (select {x: (as 'I16 (as 'U8 i)) from: TC}) 'x) -- (as 'I16 (as 'U8 iv)) +(at (select {x: (as 'U8 (as 'I16 i)) from: TC}) 'x) -- (as 'U8 (as 'I16 iv)) +(at (select {x: (as 'I32 (as 'I32 i)) from: TC}) 'x) -- (as 'I32 iv) +(at (select {x: (as 'I16 (as 'I16 i)) from: TC}) 'x) -- (as 'I16 iv) +(at (select {x: (as 'U8 (as 'U8 i)) from: TC}) 'x) -- (as 'U8 iv) +;; nulls through the narrow lanes, compiled +(set ivn [1 0N 3 4 -5 0]) +(set TCN (table [i] (list ivn))) +(at (select {x: (+ (as 'I32 i) 1.5) from: TCN}) 'x) -- (+ (as 'I32 ivn) 1.5) +(at (select {x: (+ (as 'I16 i) 1.5) from: TCN}) 'x) -- (+ (as 'I16 ivn) 1.5) +(at (select {x: (as 'I32 (as 'I16 i)) from: TCN}) 'x) -- (as 'I32 (as 'I16 ivn)) + +;; a cast to U8 of a nullable column runs in the element-wise fallback, which +;; wrote 8-byte doubles into the narrower target of a narrow-to-narrow cast +;; (a heap overrun past the result). +(set nv (at [0Nl -2 -1 0 1 2] (% (til 2000) 6))) +(set TV (table [v] (list nv))) +(sum (as 'I64 (at (select {r: (as 'BOOL (as 'U8 v)) from: TV}) 'r))) -- (sum (as 'I64 (as 'BOOL (as 'U8 nv)))) +(at (select {r: (as 'I16 (as 'I32 v)) from: TV}) 'r) -- (as 'I16 (as 'I32 nv)) +(at (select {r: (as 'U8 (as 'I16 v)) from: TV}) 'r) -- (as 'U8 (as 'I16 nv)) +(at (select {r: (as 'I16 (as 'U8 v)) from: TV}) 'r) -- (as 'I16 (as 'U8 nv)) +(at (select {r: (as 'I32 (as 'U8 v)) from: TV}) 'r) -- (as 'I32 (as 'U8 nv)) +(count (til 100000)) -- 100000 + +;; `nil?` over a narrow lane read it as int64 and found no null +(set vn [1 0N 3 0N 5]) +(set TI (table [v] (list vn))) +(at (select {n: (nil? (as 'I32 v)) from: TI}) 'n) -- (nil? (as 'I32 vn)) +(at (select {n: (nil? (as 'I16 v)) from: TI}) 'n) -- (nil? (as 'I16 vn)) +(at (select {n: (nil? (as 'U8 v)) from: TI}) 'n) -- (nil? (as 'U8 vn)) +(at (select {n: (nil? (as 'DATE v)) from: TI}) 'n) -- (nil? (as 'DATE vn)) +(count (select {v: v from: TI where: (nil? (as 'I32 v))})) -- 2 +;; a null-free value that truncates onto the narrow sentinel is not null +(set vb [-32768 32768 -2147483648 2147483648 65535]) +(set TB (table [v] (list vb))) +(at (select {n: (nil? (as 'I16 v)) from: TB}) 'n) -- (nil? (as 'I16 vb)) +(at (select {n: (nil? (as 'I32 v)) from: TB}) 'n) -- (nil? (as 'I32 vb)) +(count (select {v: v from: TB where: (nil? (as 'I32 v))})) -- 0 diff --git a/test/rfl/query/not_bool_column.rfl b/test/rfl/query/not_bool_column.rfl new file mode 100644 index 000000000..08a230c2d --- /dev/null +++ b/test/rfl/query/not_bool_column.rfl @@ -0,0 +1,62 @@ +;; #693: compiled `not` over a BOOL column in a select projection. +;; +;; A REG_SCAN of a BOOL column is widened to an I64 lane (register-widening +;; invariant in expr.c), but the BOOL-output unary kernel read the NOT +;; source as bytes: lane 0 saw the low byte of the first int64, lanes 1..7 +;; saw its zero padding, so [true false true false] came back as +;; [false true true true]. The fix reads the source at its own lane width. + +(set T (table [b] (list [true false true false]))) +(at (select {n: (not b) from: T}) 'n) -- [false true false true] +(at (select {n: (not (not b)) from: T}) 'n) -- [true false true false] +(at (select {n: (and b (not b)) from: T}) 'n) -- [false false false false] +(at (select {n: b from: T where: (not b)}) 'n) -- [false false] +(count (select {n: b from: T where: (not b)})) -- 2 + +;; all-true input: every lane must flip +(set T4 (table [b] (list [true true true true]))) +(at (select {n: (not b) from: T4}) 'n) -- [false false false false] + +;; lengths around the 8-byte lane boundary +(set T8 (table [b] (list [true false true false true false true false]))) +(at (select {n: (not b) from: T8}) 'n) -- [false true false true false true false true] +(set T9 (table [b] (list [true false true false true false true false true]))) +(at (select {n: (not b) from: T9}) 'n) -- [false true false true false true false true false] +(set T17 (table [b] (list [true false true false true false true false true false true false true false true false true]))) +(at (select {n: (not b) from: T17}) 'n) -- [false true false true false true false true false true false true false true false true false] + +;; computed-bool source (1-byte scratch) was already correct; keep it covered +(set TI (table [i] (list (til 6)))) +(at (select {n: (not (> i 2)) from: TI}) 'n) -- [true true true false false false] + +;; same kernel: (as 'BOOL ...) over a comparison result / narrow cast +(at (select {n: (as 'BOOL (> i 2)) from: TI}) 'n) -- [false false false true true true] +(at (select {n: (as 'BOOL (as 'I32 i)) from: TI}) 'n) -- [false true true true true true] +(at (select {n: (as 'BOOL (as 'I16 i)) from: TI}) 'n) -- [false true true true true true] + +;; `not` over a nullable non-BOOL column runs in the element-wise fallback +;; (the compiled kernel declines a null-aware NOT). That fallback had a NOT +;; for BOOL input only and left the result unwritten for any other width. +;; A null is not true, so `not` of it is true, as in the eval path. +(set iN [1 0N 0 3 0 5 6 0 0N 9]) +(set fN [1.0 0Nf 0.0 3.0 0.0 5.0 6.0 0.0 0Nf 9.0]) +(set TNN (table [k iN fN] (list (til 10) iN fN))) +(at (select {n: (not iN) from: TNN}) 'n) -- [false true true false true false false true true false] +(at (select {n: (not fN) from: TNN}) 'n) -- [false true true false true false false true true false] +(at (select {k: k from: TNN where: (not iN)}) 'k) -- [1 2 4 7 8] +(at (select {n: (not (as 'I32 iN)) from: TNN}) 'n) -- [false true true false true false false true true false] +(set TN16 (table [h] (list (as 'I16 iN)))) +(at (select {n: (not h) from: TN16}) 'n) -- [false true true false true false false true true false] +(set TN32 (table [w] (list (as 'I32 iN)))) +(at (select {n: (not w) from: TN32}) 'n) -- [false true true false true false false true true false] +;; `not` has no meaning for symbols +(select {n: (not s) from: (table [s] (list (as 'SYMBOL ["a" "" "b"])))}) !- type +;; the eval path's `not` is element-wise over numeric vectors too +(not iN) -- [false true true false true false false true true false] +(not fN) -- [false true true false true false false true true false] +(not [true false]) -- [false true] +(not 0) -- true +;; a vector result, so an `if` on `(not vec)` tests a vector, which is truthy +;; whatever its cells: the same as for a BOOL vector before this change +(if (not [1 2]) 'a 'b) -- 'a +(if (not [true true]) 'a 'b) -- 'a diff --git a/test/rfl/query/query_emit_filter_coverage.rfl b/test/rfl/query/query_emit_filter_coverage.rfl index 181309760..b9d5f9ef2 100644 --- a/test/rfl/query/query_emit_filter_coverage.rfl +++ b/test/rfl/query/query_emit_filter_coverage.rfl @@ -179,3 +179,38 @@ ;; return 0 → expr_affine_of_sym returns 0 → dep_candidate=false (set TGt2 (table [k u] (list [1 2 3 4] [10 20 30 40]))) (count (select {c: (count u) from: TGt2 by: {k: k m: (+ k 1.0)}})) -- 4 + +;; A where: predicate that reduces to one value holds for every row or none. +;; A false scalar conjunct of an `and` kept every row (the one-element +;; predicate failed the row-count check and the refine read "all pass"), a +;; false scalar alone failed with a selection mismatch, and a constant false +;; under a grouping or an aggregate grouped every row. +(set TSc (table [x s] (list (til 6) ['a 'b 'c 'a 'b 'c]))) +(at (select {from: TSc where: (and (> x 1) (== (strlen "abc") 4))}) 'x) -- (til 0) +(at (select {from: TSc where: (and (> x 1) (== (count x) 5))}) 'x) -- (til 0) +(at (select {from: TSc where: (and (> x 1) (== (count x) 6))}) 'x) -- [2 3 4 5] +(count (select {from: TSc where: (== (count x) 5)})) -- 0 +(count (select {from: TSc where: (== (count x) 6)})) -- 6 +(count (select {c: (count x) from: TSc by: s where: (and (> x 1) (== (strlen "abc") 4))})) -- 0 +(count (select {c: (count x) from: TSc by: s where: (== 1 2)})) -- 0 +(count (select {c: (count x) from: TSc by: s where: false})) -- 0 +(at (select {c: (count x) from: TSc where: (and (> x 1) false)}) 'c) -- [0] +(at (select {c: (count x) from: TSc by: s where: true}) 'c) -- [2 2 2] +(at (select {from: TSc where: (or (> x 3) true)}) 'x) -- (til 6) +;; ...with take: too, where the filter gathers only the first rows: an atom +;; predicate passed the whole table through (a false `where:` with `take: 3` +;; returned every row) and a one-element BOOL read as a one-row mask. +(set TSt (table [x s] (list (til 10) (as 'SYM (% (til 10) 3))))) +(at (select {from: TSt where: false take: 3}) 'x) -- (til 0) +(at (select {from: TSt where: (and (> x 1) false) take: 3}) 'x) -- (til 0) +(at (select {from: TSt where: 0N take: 3}) 'x) -- (til 0) +(at (select {from: TSt where: (== (count x) 10) take: 5}) 'x) -- [0 1 2 3 4] +(at (select {from: TSt where: true take: 3}) 'x) -- [0 1 2] +;; take 0 keeps the table's columns +(key (select {from: TSt where: (> x 1) take: 0})) -- ['x 's] +;; a symbol or string has no truth value +(select {from: TSt where: "abc"}) !- type +;; update where: takes a scalar predicate the same way +(at (update {x: 100 from: TSt where: false}) 'x) -- (til 10) +(at (update {x: 100 from: TSt where: (== (count x) 10)}) 'x) -- (take 100 10) +(count (select {from: TSt where: (== (count x) 9)})) -- 0 diff --git a/test/rfl/query/query_update_coverage.rfl b/test/rfl/query/query_update_coverage.rfl index 4e6a3d0d1..f225b3bfb 100644 --- a/test/rfl/query/query_update_coverage.rfl +++ b/test/rfl/query/query_update_coverage.rfl @@ -576,3 +576,95 @@ (at (at (update {v: 0Nl from: (table [k v] (list [1 2 3] [10 20 30])) where: (== k 1)}) 'v) 1) -- 20 (at (at (update {v: 0Nf from: (table [k v] (list [1 2 3] [10.0 20.0 30.0])) where: (== k 1)}) 'v) 1) -- 20.0 (nil? (at (at (update {v: 0Nl from: (table [k v] (list [1 2 3] [10 20 30])) where: (== k 1)}) 'v) 0)) -- true + +;; A scalar computed as a one-element vector (arithmetic over a reduction, +;; or an `if` whose parts are all scalar) broadcasts like an atom. It used +;; to replace the column with one row, so the table shrank to one row, or +;; under `where:` wrote zeros into the matched rows. +(set TU (table [x s] (list (til 6) ['a 'b 'c 'd 'e 'f]))) +(at (update {x: (if true 7 0) from: TU}) 'x) -- [7 7 7 7 7 7] +(at (update {x: (+ (sum x) 0) from: TU}) 'x) -- [15 15 15 15 15 15] +(at (update {z: (+ (max x) 1) from: TU}) 'z) -- [6 6 6 6 6 6] +(at (update {x: (+ (sum x) 0) from: TU where: (> x 2)}) 'x) -- (at (update {x: (sum x) from: TU where: (> x 2)}) 'x) +(at (update {x: (if true 7 0) from: TU where: (> x 2)}) 'x) -- [0 1 2 7 7 7] +(at (update {s: (if true 'q 'r) from: TU}) 's) -- ['q 'q 'q 'q 'q 'q] +(at (update {x: (+ (sum x) 1) from: (table [x] (list [5]))}) 'x) -- [6] +;; Under `where:` the update keeps the compiled expression's own error. It +;; used to fall back to the interpreter, whose `if` tests one truth value: +;; the then-branch went to every matched row with no error. +(set TW (table [x s] (list (til 4) ['ab 'cd 'ef 'gh]))) +(as 'STR (at (update {s: (if (> x 2) s 0N) from: TW where: (> x 0)}) 's)) -- ["ab" "" "" "gh"] +(update {s: (if (> x 1) 'q x) from: TW where: (> x 0)}) !- type +(update {s: (if s 1 2) from: TW where: (> x 0)}) !- type +(set TWI (table [x s] (list (til 6) ['a 'b 'c 'd 'e 'f]))) +(update {s: (if (> x 3) s 0N) from: 'TWI where: (> x 2)}) +(as 'STR (at TWI 's)) -- ["a" "b" "c" "" "e" "f"] + +;; An F32 atom keeps its value widened; the broadcast copied the low half of +;; the double and wrote zeros. +(set F32V (fn [x] (at (select {from: (table [v] (list x)) v: (as 'F32 v)}) 'v))) +(set TF (table [x f] (list (til 3) (F32V [1.5 2.5 3.5])))) +(at (update {f: (as 'F32 (+ (sum f) 0)) from: TF}) 'f) -- (F32V [7.5 7.5 7.5]) +(at (update {f: (as 'F32 (+ (sum f) 0)) from: TF where: (> x 0)}) 'f) -- (F32V [1.5 7.5 7.5]) +(at (update {g: (as 'F32 (+ (sum f) 0)) from: TF}) 'g) -- (F32V [7.5 7.5 7.5]) + +;; By group, a one-element result is the group's scalar. +(at (update {k: (+ (sum x) 0) from: (table [x g] (list (til 5) [0 0 0 1 2])) by: g}) 'k) -- [3 3 3 3 4] +(at (update {k: (if (> (count x) 1) 'many 'one) from: (table [x g] (list (til 5) [0 0 0 1 2])) by: g}) 'k) -- ['many 'many 'many 'one 'one] +;; ...but only an `if` refusing its operands is final. Other DAG failures +;; inside an `if`, such as a global list or a cast of a null literal, still +;; fall back to the interpreter, which handles them. +(set GL (list 1 2 3)) +(set TQ (table [x a] (list (til 4) (as 'I32 [1 2 3 4])))) +(at (update {x: (if true (count GL) x) from: TQ where: (> x 1)}) 'x) -- [0 1 3 3] +(at (update {x: (if (> (count GL) 2) 9 x) from: TQ where: (> x 1)}) 'x) -- [0 1 9 9] +(at (update {x: (if true (count GL) x) from: TQ}) 'x) -- [3 3 3 3] +(at (update {a: (if true (as 'I32 0N) a) from: TQ where: (> x 1)}) 'a) -- (concat (as 'I32 [1 2]) (take 0Ni 2)) +(at (update {x: (if (> (count x) 2) 1 (neg 0N)) from: TQ where: (> x 1)}) 'x) -- [0 1 1 1] +(as 'STR (at (update {s: (if (> x 1) s 0Nf) from: TW where: (> x 0)}) 's)) -- ["ab" "" "ef" "gh"] + +;; By group, a STR cell is written through the string pool; it came out "". +(set TGS (table [x g t] (list (til 5) [0 0 0 1 2] (list "a" "bb" "c" "dd" "e")))) +(at (update {k: (if (> (count x) 1) (first t) (last t)) from: TGS by: g}) 'k) -- ["a" "a" "a" "dd" "e"] +(at (update {t: "zz" from: TGS by: g}) 't) -- ["zz" "zz" "zz" "zz" "zz"] +(at (update {k: (first t) from: TGS by: g}) 'k) -- ["a" "a" "a" "dd" "e"] +;; The per-group sub-table shares the STR column's string pool: without it +;; every string past the inline size read as "" inside the group, and a +;; string op on it aborted on the missing pool. +(set TLS (table [x g t] (list (til 5) [0 0 1 1 2] (list "first-long-pooled-string-aaaa" "second-long-pooled-string-bbb" "short" "x" "third-long-pooled-string-ccc")))) +(at (update {t: (first t) from: TLS by: g}) 't) -- ["first-long-pooled-string-aaaa" "first-long-pooled-string-aaaa" "short" "short" "third-long-pooled-string-ccc"] +(at (update {t: t from: TLS by: g}) 't) -- (at TLS 't) +(at (update {k: (upper t) from: TLS by: g}) 'k) -- (upper (at TLS 't)) + +;; Under where: a new column takes the expression on the matched rows and null +;; on the rest (false / 0x00 for BOOL and U8, which have no null). Both the +;; copy path and the in-place path walked the table's columns only and dropped +;; it without an error. +(set TWn (table [x s] (list (til 4) ['ab 'cd 'ef 'gh]))) +(key (update {k: (+ x 1) from: TWn where: (> x 1)})) -- ['x 's 'k] +(at (update {k: (+ x 1) from: TWn where: (> x 1)}) 'k) -- [0N 0N 3 4] +(as 'STR (at (update {k: s from: TWn where: (> x 1)}) 'k)) -- ["" "" "ef" "gh"] +(nil? (at (update {k: s from: TWn where: (> x 1)}) 'k)) -- [true true false false] +(at TWn 's) -- ['ab 'cd 'ef 'gh] +(at (update {k: 7 from: TWn where: (> x 1)}) 'k) -- [0N 0N 7 7] +(at (update {k: "zz" from: TWn where: (> x 1)}) 'k) -- ["" "" "zz" "zz"] +(at (update {k: (> x 1) from: TWn where: (> x 1)}) 'k) -- [false false true true] +(at (update {k: (as 'U8 x) from: TWn where: (> x 1)}) 'k) -- (as 'U8 [0 0 2 3]) +(update {k: (+ x 1) from: 'TWn where: (> x 1)}) +(at TWn 'k) -- [0N 0N 3 4] +(update {b: (> x 2) from: 'TWn where: (> x 1)}) +(at TWn 'b) -- [false false false true] +;; ...on a FILE-domain SYM column too, whose cells are 1, 2 or 4 bytes: the +;; null write cleared 8 bytes per unmatched row, wiping the next cells and +;; writing past the end of the column. +(.sys.exec "rm -rf /tmp/rfl_upd_newcol_sym") +(.db.splayed.set "/tmp/rfl_upd_newcol_sym/t/" (table [x s] (list (til 6) ['ab 'cd 'ef 'gh 'ab 'ij]))) +(set SWn (.db.splayed.get "/tmp/rfl_upd_newcol_sym/t/")) +(as 'STR (at (update {k: s from: SWn where: (> x 1)}) 'k)) -- ["" "" "ef" "gh" "ab" "ij"] +(as 'STR (at (update {k: s from: SWn where: (in x [1 2])}) 'k)) -- ["" "cd" "ef" "" "" ""] +(.db.splayed.set "/tmp/rfl_upd_newcol_sym/w8/" (table [x s] (list (til 200000) (as 'SYM (as 'STR (% (til 200000) 200)))))) +(set SW8 (.db.splayed.get "/tmp/rfl_upd_newcol_sym/w8/")) +(sum (nil? (at (update {k: s from: SW8 where: (< x 10)}) 'k))) -- 199990 +(at (at (update {k: s from: SW8 where: (< x 10)}) 'k) 7) -- (at (at SW8 's) 7) +(update {k: (list 1 2 3 4 5 6) from: SWn where: (> x 1)}) !- type +(.sys.exec "rm -rf /tmp/rfl_upd_newcol_sym") -- 0 diff --git a/test/rfl/query/scalar_select_where_take.rfl b/test/rfl/query/scalar_select_where_take.rfl new file mode 100644 index 000000000..5844ec870 --- /dev/null +++ b/test/rfl/query/scalar_select_where_take.rfl @@ -0,0 +1,100 @@ +;; scalar_select_where_take.rfl — issues #675 and #679. +;; +;; #675: a select whose outputs are all scalar expressions wrapping +;; aggregates (`(+ (sum x) 0)`) is one row. Under where: the reductions +;; inside the projection already walk the selection (exec_reduction), so +;; OP_SELECT must drop it instead of leaving it for ray_execute_inner's +;; final gather, which met the one-row result with a selection built for +;; the input's rows ("sel_compact: selection nrows mismatch"). +;; +;; #679: an all-aggregate select (keyless GROUP) with a no-match where: and +;; a positive take: came back empty. HEAD(GROUP) compacted the selection +;; into a 0-row table before exec_group, which has no scalar path for an +;; empty input; the keyless group now keeps the selection lazy, as the +;; plain OP_GROUP path does, and take: applies to the (one) output row. + +;; ─── #675: scalar outputs under where: ─────────────────────────────── +(set T675 (table [x] (list (til 4)))) + +(at (select {k: (+ (sum x) 0) from: T675 where: (> x 1)}) 'k) -- [5] +(count (select {k: (+ (sum x) 0) from: T675 where: (> x 1)})) -- 1 +;; no where: unchanged +(at (select {k: (+ (sum x) 0) from: T675}) 'k) -- [6] +;; a row column beside the scalar: the scalar is broadcast to the survivors +(at (select {k: (+ (sum x) 0) y: x from: T675 where: (> x 1)}) 'k) -- [5 5] +(at (select {k: (+ (sum x) 0) y: x from: T675 where: (> x 1)}) 'y) -- [2 3] +;; two scalar outputs +(at (select {k: (+ (sum x) 0) m: (* (max x) 10) from: T675 where: (> x 1)}) 'm) -- [30] +;; scalar `if` over an aggregate +(at (select {k: (if (> (sum x) 4) 1 0) from: T675 where: (> x 1)}) 'k) -- [1] +;; where: matching nothing / everything +(at (select {k: (+ (sum x) 0) from: T675 where: (> x 10)}) 'k) -- [0] +(at (select {k: (+ (sum x) 0) from: T675 where: (> x -1)}) 'k) -- [6] +;; take: applies to the output rows: one row stays one row +(at (select {k: (+ (sum x) 0) from: T675 where: (> x 1) take: 3}) 'k) -- [5] +(at (select {k: (+ (sum x) 0) from: T675 where: (> x 1) take: 1}) 'k) -- [5] +(at (select {k: (+ (sum x) 0) from: T675 where: (> x 1) take: -1}) 'k) -- [5] +;; with by: the same form is per group (order unspecified: check the set) +(count (select {k: (+ (sum x) 0) from: T675 where: (> x 0) by: (% x 2)})) -- 2 +(sum (at (select {k: (+ (sum x) 0) from: T675 where: (> x 0) by: (% x 2)}) 'k)) -- 6 +(at (select {k: (+ (sum x) 0) from: T675 where: (> x 1) by: x}) 'k) -- [2 3] + +;; ─── #675 on a parted table ────────────────────────────────────────── +(.sys.exec "rm -rf /tmp/rfl_q675_parted") +(set T675a (table [x d] (list [1 2 3] [2024.01.01 2024.01.01 2024.01.01]))) +(set T675b (table [x d] (list [10 20] [2024.01.02 2024.01.02]))) +(.db.splayed.set "/tmp/rfl_q675_parted/2024.01.01/t/" T675a) +(.db.splayed.set "/tmp/rfl_q675_parted/2024.01.02/t/" T675b) +(set P675 (.db.parted.get "/tmp/rfl_q675_parted/" 't)) +(count P675) -- 5 +(at (select {k: (+ (sum x) 0) from: P675 where: (== date 2024.01.02)}) 'k) -- [30] +(at (select {k: (+ (sum x) 0) from: P675 where: (== d 2024.01.02)}) 'k) -- [30] +(count (select {k: (+ (sum x) 0) from: P675 where: (== d 2024.01.02)})) -- 1 +(at (select {k: (+ (sum x) 0) from: P675 where: (> x 1)}) 'k) -- [35] +(at (select {k: (+ (sum x) 0) from: P675}) 'k) -- [36] +(at (select {c: (count x) from: P675 where: (> x 100) take: 3}) 'c) -- [0] +(at (select {c: (count x) from: P675 where: (> x 5) take: 1}) 'c) -- [2] +(.sys.exec "rm -rf /tmp/rfl_q675_parted") + +;; ─── #679: scalar aggregate, no-match where:, take: ────────────────── +(set T679 (table [x y] (list [0 256 0 1 0 0] (til 6)))) + +(at (select {c: (count y) from: T679 where: (> y 100)}) 'c) -- [0] +(at (select {c: (count y) from: T679 where: (> y 100) take: 3}) 'c) -- [0] +(at (select {c: (count y) from: T679 where: (> y 100) take: 1}) 'c) -- [0] +(at (select {c: (count y) from: T679 where: (> y 100) take: -3}) 'c) -- [0] +(at (select {c: (count y) from: T679 where: (> y 100) take: [0 3]}) 'c) -- [0] +;; take: 0 is zero output rows +(at (select {c: (count y) from: T679 where: (> y 100) take: 0}) 'c) -- [] +;; take: on a non-empty match counts every survivor, not take: rows +(at (select {c: (count y) from: T679 where: (> y 2) take: 1}) 'c) -- [3] +(at (select {c: (count y) from: T679 where: (> y 2) take: 3}) 'c) -- [3] +(at (select {c: (count y) from: T679 take: 3}) 'c) -- [6] +;; several aggregates +(at (select {c: (count y) s: (sum y) m: (max y) from: T679 where: (> y 100) take: 3}) 's) -- [0] +(at (select {c: (count y) s: (sum y) m: (max y) from: T679 where: (> y 100) take: 3}) 'm) -- [0Nl] +(at (select {c: (count y) s: (sum y) m: (max y) from: T679 where: (> y 2) take: 2}) 's) -- [12] +;; other no-match predicates +(at (select {c: (count y) from: T679 where: (== x 256) take: 3}) 'c) -- [1] +(at (select {c: (count y) from: T679 where: (in x [7 8]) take: 3}) 'c) -- [0] +(at (select {c: (count y) from: T679 where: (and (> y 100) (< y 1000)) take: 3}) 'c) -- [0] +;; the #675 form with a no-match where: and take: +(at (select {c: (+ (count y) 0) from: T679 where: (> y 100) take: 3}) 'c) -- [0] +;; by: with no match is still no groups +(count (select {c: (count y) from: T679 where: (> y 100) by: x take: 3})) -- 0 +(count (select {c: (count y) from: T679 where: (> y 2) by: x take: 1})) -- 1 + +;; ─── review follow-ups ─────────────────────────────────────────────── +;; #675 on a one-row table: a scalar and a row column have the same length, +;; so the ops decide; a failing where: still leaves one row +(at (select {k: (+ (sum x) 0) from: (table [x] (list [5])) where: (> x 10)}) 'k) -- [0] +(at (select {k: (+ (sum x) 0) from: (table [x] (list [5])) where: (> x 1)}) 'k) -- [5] +(at (select {k: (if (> (sum x) 1) 1 0) from: (table [x] (list [5])) where: (> x 10)}) 'k) -- [0] +(at (select {k: x from: (table [x] (list [5])) where: (> x 10)}) 'k) -- [] +(at (select {k: (+ x 1) from: (table [x] (list [5])) where: (> x 10)}) 'k) -- [] +;; #679 for an aggregate of an expression: the keyless group keeps its +;; selection lazy on the plain path too +(at (select {c: (sum (* y 2)) from: T679 where: (> y 100)}) 'c) -- [0] +(at (select {c: (sum (* y 2)) from: T679 where: (> y 100) take: 1}) 'c) -- [0] +(at (select {c: (sum (* y 2)) from: T679 where: (> y 2)}) 'c) -- [24] +(at (select {c: (max (+ y 1)) from: T679 where: (> y 100)}) 'c) -- [0Nl] diff --git a/test/rfl/query/select_agg_eval_fallback.rfl b/test/rfl/query/select_agg_eval_fallback.rfl new file mode 100644 index 000000000..fe2fd210c --- /dev/null +++ b/test/rfl/query/select_agg_eval_fallback.rfl @@ -0,0 +1,74 @@ +;; An aggregate projected beside a projection the DAG declines (issue #692). +;; +;; A temporal `+ - *` makes compile_expr_dag decline the projection, so the +;; whole select lands in the eval fallback (src/ops/query.c, the loop over +;; eval_expr_whole_column / eval_expr_per_row). There every non-whole-column +;; projection was scattered per row, and an aggregate saw a one-cell slice of +;; each column: `(max i)` came back as `i` itself. A projection with no +;; column ref outside an aggregate (expr_refs_row_column == 0) is now +;; evaluated once over the whole table and broadcast the way the DAG path +;; broadcasts it: to the row count beside a row projection, one row when +;; every projection is such a value. +;; +;; Oracle: the DAG path with a plain (non-temporal) row projection beside it. + +(set T (table [i ts] (list [1 2 3 4] (+ 2024.01.01D00:00:00.000000000 (* 10 (til 4)))))) + +;; ── the DAG rule this must match: an aggregate beside a row column broadcasts ─ +(at (select {m: (max i) x: i from: T}) 'm) -- [4 4 4 4] +(at (select {m: (+ (max i) 1) x: i from: T}) 'm) -- [5 5 5 5] + +;; ── aggregate beside a declined (temporal) projection ─────────────────────── +(at (select {m: (max i) x: (+ ts 1) from: T}) 'm) -- [4 4 4 4] +(at (select {x: (+ ts 1) m: (max i) from: T}) 'm) -- [4 4 4 4] +(at (select {m: (sum i) x: (+ ts 1) from: T}) 'm) -- [10 10 10 10] +(at (select {m: (count i) x: (+ ts 1) from: T}) 'm) -- [4 4 4 4] +(at (select {m: (max i) x: (+ ts 1) from: T}) 'x) -- (+ (at T 'ts) 1) +(count (select {m: (max i) x: (+ ts 1) from: T})) -- 4 + +;; ── the aggregate nested under arithmetic, or under a scalar `if` ─────────── +(at (select {m: (+ (max i) 1) x: (+ ts 1) from: T}) 'm) -- [5 5 5 5] +(at (select {k: (if (> (count i) 3) 1 0) x: (+ ts 1) from: T}) 'k) -- [1 1 1 1] +(at (select {m: (count (distinct i)) x: (+ ts 1) from: T}) 'm) -- [4 4 4 4] + +;; ── the declined projection is itself the aggregate ────────────────────────── +(at (select {s: (+ (max ts) 1) x: i from: T}) 's) -- (take (+ (max (at T 'ts)) 1) 4) + + +;; ── where: filters before the aggregate sees the column ────────────────────── +(at (select {m: (max i) x: (+ ts 1) from: T where: (> i 1)}) 'm) -- [4 4 4] +(at (select {m: (min i) x: (+ ts 1) from: T where: (> i 1)}) 'm) -- [2 2 2] +(count (select {m: (max i) x: (+ ts 1) from: T where: (> i 10)})) -- 0 + +;; ── a later projection reads the broadcast value ───────────────────────────── +(at (select {m: (max i) y: (+ m 1) x: (+ ts 1) from: T}) 'y) -- [5 5 5 5] + +;; ── every projection an aggregate: one row, as the DAG path returns ───────── +(count (select {m: (max i) s: (+ (max ts) 1) from: T})) -- 1 +(at (select {m: (max i) s: (+ (max ts) 1) from: T}) 'm) -- [4] +(at (select {m: (max i) s: (+ (max ts) 1) from: T}) 's) -- (list (+ (max (at T 'ts)) 1)) +(count (select {s: (+ (max ts) 1) from: T})) -- 1 + +;; ── a later projection over an earlier aggregate is one value too (#698) ───── +(count (select {m: (max i) y: (+ m 1) from: T})) -- 1 +(count (select {m: (max ts) y: (+ m 1) from: T})) -- 1 +(at (select {m: (max i) y: (+ m 1) from: T}) 'y) -- [5] +(at (select {m: (max ts) y: (+ m 1) from: T}) 'y) -- (list (+ (max (at T 'ts)) 1)) +;; beside a row projection it is broadcast with the aggregate +(at (select {m: (max ts) y: (+ m 1) x: i from: T}) 'y) -- (take (+ (max (at T 'ts)) 1) 4) + +;; ── projections without an aggregate keep the row-by-row path ──────────────── +(at (select {l: 7 x: (+ ts 1) from: T}) 'l) -- [7 7 7 7] +(at (select {k: ((fn [a] (if (> a 2) 1 0)) i) x: (+ ts 1) from: T}) 'k) -- [0 0 1 1] +;; a literal beside an aggregate is one more scalar (#698), on both paths +(count (select {l: 7 s: (+ (max ts) 1) from: T})) -- 1 +(count (select {l: 7 s: (+ (max i) 1) from: T})) -- 1 +(at (select {l: 7 s: (+ (max ts) 1) from: T}) 'l) -- [7] +;; literals alone keep the input's rows +(count (select {l: 7 from: T})) -- 4 +;; a call over literals may build a column; it stays a row projection +(count (select {t: (til 4) s: (+ (max ts) 1) from: T})) -- 4 +(count (select {t: (til 4) s: (max i) from: T})) -- 4 + +;; ── a length-changing verb beside an aggregate is still ragged ─────────────── +(select {a: (distinct i) m: (max i) from: (table [i] (list [1 2 2 3]))}) !- length diff --git a/test/rfl/query/select_agg_row_mix_fallback.rfl b/test/rfl/query/select_agg_row_mix_fallback.rfl new file mode 100644 index 000000000..813154f3b --- /dev/null +++ b/test/rfl/query/select_agg_row_mix_fallback.rfl @@ -0,0 +1,66 @@ +;; A row column mixed with an aggregate in ONE projection, on the eval fallback. +;; +;; A temporal `+ - *` makes compile_expr_dag decline a projection, so the whole +;; select lands in the eval fallback (src/ops/query.c, the loop over +;; eval_expr_whole_column / eval_expr_per_row). A projection with a column +;; ref outside its aggregate (`(+ i (max i))`, `(if (> i (avg i)) 1 0)`) is +;; scattered per row there, and every column is bound to one cell: the +;; aggregate folded that cell alone, so `(max i)` read as `i` and +;; `(+ i (max i))` came back as `(* 2 i)`. Every maximal aggregate call in +;; such a projection is now reduced once over the whole table before the +;; scatter and spliced into a rewritten copy of the expression +;; (select_fallback_prereduce), so each row combines with the value the DAG +;; path broadcasts. +;; +;; Oracle: the DAG path with a plain (non-temporal) row projection beside it. + +(set T (table [i ts s n] (list [1 2 3 4] (+ 2024.01.01D00:00:00.000000000 (* 10 (til 4))) (quote [a b c d]) (list "p" "q" "r" "s")))) + +;; ── the DAG rule this must match ───────────────────────────────────────────── +(at (select {m: (+ i (max i)) x: i from: T}) 'm) -- [5 6 7 8] +(at (select {m: (if (> i (avg i)) 1 0) x: i from: T}) 'm) -- [0 0 1 1] + +;; ── arithmetic over a row column and an aggregate ──────────────────────────── +(at (select {m: (+ i (max i)) x: (+ ts 1) from: T}) 'm) -- [5 6 7 8] +(at (select {x: (+ ts 1) m: (+ i (max i)) from: T}) 'm) -- [5 6 7 8] +(at (select {m: (* i (avg i)) x: (+ ts 1) from: T}) 'm) -- [2.5 5.0 7.5 10.0] +(at (select {m: (- i (/ (sum i) (count i))) x: (+ ts 1) from: T}) 'm) -- [-1.5 -0.5 0.5 1.5] +(at (select {m: (+ i (count (distinct i))) x: (+ ts 1) from: T}) 'm) -- [5 6 7 8] +(at (select {m: (+ i (max i)) x: (+ ts 1) from: T}) 'x) -- (+ (at T 'ts) 1) +(count (select {m: (+ i (max i)) x: (+ ts 1) from: T})) -- 4 + +;; ── a scalar `if` whose condition reads the row and an aggregate ───────────── +(at (select {m: (if (> i (avg i)) 1 0) x: (+ ts 1) from: T}) 'm) -- [0 0 1 1] +(at (select {m: (if (> i (avg i)) (max i) (min i)) x: (+ ts 1) from: T}) 'm) -- [1 1 4 4] + +;; ── a nested aggregate is reduced as a whole ───────────────────────────────── +(at (select {m: (+ i (max (- i (min i)))) x: (+ ts 1) from: T}) 'm) -- [4 5 6 7] + +;; ── a symbol- or string-valued aggregate is spliced as a literal ───────────── +(at (select {m: (== s (first s)) x: (+ ts 1) from: T}) 'm) -- [true false false false] +(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.yyyy (max i)) x: (+ ts 1) from: T}) 'm) -- [2020 2020 2020 2020] + +;; ── where: filters before the aggregate is reduced ─────────────────────────── +(at (select {m: (- i (min i)) x: (+ ts 1) from: T where: (> i 1)}) 'm) -- [0 1 2] +(at (select {m: (+ i (max i)) x: (+ ts 1) from: T where: (> i (avg i))}) 'm) -- [7 8] +(count (select {m: (+ i (max i)) x: (+ ts 1) from: T where: (> i 10)})) -- 0 + +;; ── the aggregate reads an earlier output; a later output reads the mix ────── +(at (select {d: (* i 2) m: (+ i (max d)) x: (+ ts 1) from: T}) 'm) -- [9 10 11 12] +(at (select {d: (* i 2) m: (+ i (max d)) y: (- m 1) x: (+ ts 1) from: T}) 'y) -- [8 9 10 11] + +;; ── a lambda call's argument is reduced; a lambda body is left alone ───────── +;; (a lambda call is a per-row projection on the fallback, #690: its body +;; folds the formal it was given, one cell, so (max a) there is a itself) +(at (select {m: (+ i ((fn [a] (* a 2)) (max i))) x: (+ ts 1) from: T}) 'm) -- [9 10 11 12] +(at (select {m: ((fn [a] (- a (max a))) i) x: (+ ts 1) from: T}) 'm) -- [0 0 0 0] +(at (select {k: ((fn [a] (if (> a 2) 1 0)) i) x: (+ ts 1) from: T}) 'k) -- [0 0 1 1] + +;; ── what already held: an aggregate alone broadcasts, all-aggregate is one row ─ +(at (select {m: (max i) x: (+ ts 1) from: T}) 'm) -- [4 4 4 4] +(at (select {m: (count (distinct i)) x: (+ ts 1) from: T}) 'm) -- [4 4 4 4] +(count (select {m: (max i) s: (+ (max ts) 1) from: T})) -- 1 diff --git a/test/rfl/query/select_whole_column_projection.rfl b/test/rfl/query/select_whole_column_projection.rfl index 3bd8c6000..b7cb3dfaf 100644 --- a/test/rfl/query/select_whole_column_projection.rfl +++ b/test/rfl/query/select_whole_column_projection.rfl @@ -35,3 +35,28 @@ ;; ── ragged result rejected: a length-changing column beside a full column ──── (select {a: (distinct v) b: v from: T}) !- length + +;; A scalar that reaches the projection as a one-element vector rather than +;; an atom (arithmetic over a reduction, or an `if` whose parts are all +;; scalar) broadcasts like an atom next to a full column. The table used to +;; take its row count from the first column, so these came back with 1 row +;; and columns of different lengths. +(set TB (table [x] (list (til 6)))) +(count (select {k: (+ (sum x) 0) y: x from: TB})) -- 6 +(at (select {k: (+ (sum x) 0) y: x from: TB}) 'k) -- [15 15 15 15 15 15] +(at (select {k: (if true 7 0) y: x from: TB}) 'k) -- [7 7 7 7 7 7] +(at (select {y: x k: (if (> (count x) 3) 1 0) from: TB}) 'k) -- [1 1 1 1 1 1] +(at (select {k: (if true 7 0) y: x from: TB where: (> x 2)}) 'k) -- [7 7 7] +;; every column a scalar: the one-row result stays +(count (select {k: (+ (sum x) 0) from: TB})) -- 1 +(count (select {k: (+ (sum x) 0) y: x from: (table [x] (list (til 0)))})) -- 0 + +;; The same over a parted table, whose columns count rows across partitions. +(.sys.exec "rm -rf /tmp/rfl_scalar_bcast_parted") +(.db.splayed.set "/tmp/rfl_scalar_bcast_parted/1/t/" (table [x] (list (til 4)))) +(.db.splayed.set "/tmp/rfl_scalar_bcast_parted/2/t/" (table [x] (list (+ 10 (til 3))))) +(set TPB (.db.parted.get "/tmp/rfl_scalar_bcast_parted/" 't)) +(at (select {k: (+ (sum x) 0) y: x from: TPB}) 'k) -- (take 39 7) +(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 diff --git a/test/rfl/query/temporal_cmp_float.rfl b/test/rfl/query/temporal_cmp_float.rfl new file mode 100644 index 000000000..1d5cf7b32 --- /dev/null +++ b/test/rfl/query/temporal_cmp_float.rfl @@ -0,0 +1,110 @@ +;; temporal_cmp_float.rfl — comparing a temporal column with a float inside +;; a query is the same type error as outside one (#694). +;; +;; avg of a temporal column is F64 (canonical admission). Outside a query +;; (> ts (avg ts)) is "cannot compare timestamp and f64" (cmp.c); inside a +;; select the generic DAG kernel promoted both sides to double, where a +;; TIMESTAMP near 2024 has a 128 ns ULP: every row compared equal to the +;; mean, so (> ts (avg ts)) was all false and (== ts (avg ts)) all true. +;; The compiler now rejects a temporal-vs-float compare with the builtin +;; error (the per-row fallback would average one cell and compare it with +;; itself). Same-typed temporal compares stay on the exact int64 kernel. +(set T (table [i ts] (list [1 2 3 4] (+ 2024.01.01D00:00:00.000000000 (* 10 (til 4)))))) + +;; the aggregate is F64 in and out of a query +(type (avg (at T 'ts))) -- 'f64 +(type (at (select {m: (avg ts) from: T}) 'm)) -- 'F64 + +;; temporal vs the F64 aggregate: both paths raise the type error +(> (at T 'ts) (avg (at T 'ts))) !- type +(select {c: (> ts (avg ts)) from: T}) !- type +(select {c: (< ts (avg ts)) from: T}) !- type +(select {c: (>= ts (avg ts)) from: T}) !- type +(select {c: (<= ts (avg ts)) from: T}) !- type +(select {c: (== ts (avg ts)) from: T}) !- type +(select {c: (!= ts (avg ts)) from: T}) !- type +(select {c: (> (avg ts) ts) from: T}) !- type +(select {from: T where: (> ts (avg ts))}) !- type +(select {c: (if (> ts (avg ts)) 1 0) from: T}) !- type +(update {c: (> ts (avg ts)) from: T}) !- type +(select {c: (> ts (med ts)) from: T}) !- type + +;; temporal vs a float literal, DATE and TIME too +(> (at T 'ts) 1.5) !- type +(select {c: (> ts 1.5) from: T}) !- type +(select {from: T where: (< ts 1.5)}) !- type +(set Ttm (table [d t] (list (as 'DATE [10 20]) (as 'TIME [1000 2000])))) +(select {c: (> d 1.5) from: Ttm}) !- type +(select {c: (> t 1.5) from: Ttm}) !- type +(select {c: (> d (avg d)) from: Ttm}) !- type + +;; same temporal type on both sides stays exact (rows 10 ns apart near 2024) +(at (select {c: (> ts 2024.01.01D00:00:00.000000015) from: T}) 'c) -- [false false true true] +(at (select {c: (>= ts (max ts)) from: T}) 'c) -- [false false false true] +(at (select {c: (== ts (first ts)) from: T}) 'c) -- [true false false false] +(at (select {c: (!= ts 2024.01.01D00:00:00.000000010) from: T}) 'c) -- [true false true true] +(count (select {from: T where: (> ts 2024.01.01D00:00:00.000000015)})) -- 2 +;; integer scalars keep the exact int64 kernel +(at (select {c: (> ts 757382400000000015) from: T}) 'c) -- [false false true true] +(at (select {c: (> i (avg i)) from: T}) 'c) -- [false false true true] + +;; Different temporal types compare on one nanosecond scale, as the eval path +;; does (temporal_as_ns): a DATE is days, a TIME milliseconds, a TIMESTAMP +;; nanoseconds. The compiled comparison compared raw lane values, so a +;; TIMESTAMP column against a DATE literal compared nanoseconds with days. +;; Oracle: the same comparison evaluated outside a select. +(set tsx (+ 2024.01.01D00:00:00.000000000 (* (til 10) 43200000000000))) +(set dx (+ 2024.01.01 (til 10))) +(set tmx (+ 00:00:00.000 (* (til 10) 7200000))) +(set TX (table [ts d tm] (list tsx dx tmx))) +(at (select {c: (> ts 2024.01.03) from: TX}) 'c) -- (> tsx 2024.01.03) +(at (select {c: (>= ts 2024.01.03) from: TX}) 'c) -- (>= tsx 2024.01.03) +(at (select {c: (< ts 2024.01.03) from: TX}) 'c) -- (< tsx 2024.01.03) +(at (select {c: (<= ts 2024.01.03) from: TX}) 'c) -- (<= tsx 2024.01.03) +(at (select {c: (== ts 2024.01.03) from: TX}) 'c) -- (== tsx 2024.01.03) +(at (select {c: (!= ts 2024.01.03) from: TX}) 'c) -- (!= tsx 2024.01.03) +(count (select {from: TX where: (> ts 2024.01.03)})) -- 5 +(count (select {from: TX where: (> d 2024.01.03D12:00:00.000000000)})) -- 7 +(at (select {c: (> d 2024.01.03D12:00:00.000000000) from: TX}) 'c) -- (> dx 2024.01.03D12:00:00.000000000) +(at (select {c: (> d 06:00:00.000) from: TX}) 'c) -- (> dx 06:00:00.000) +(at (select {c: (> tm 2024.01.01D06:00:00.000000000) from: TX}) 'c) -- (> tmx 2024.01.01D06:00:00.000000000) +;; column against column, and a literal on the left +(at (select {c: (> ts d) from: TX}) 'c) -- (> tsx dx) +(at (select {c: (>= ts d) from: TX}) 'c) -- (>= tsx dx) +(at (select {c: (< 2024.01.03 ts) from: TX}) 'c) -- (< 2024.01.03 tsx) +;; within with DATE bounds over a TIMESTAMP column +(count (select {from: TX where: (within ts [2024.01.02 2024.01.04])})) -- 5 +;; a null DATE cell, and a null DATE literal, order below every value +(set dn (concat (take dx 3) [0Nd])) +(set TN (table [d] (list dn))) +(at (select {c: (> d 2024.01.02D00:00:00.000000000) from: TN}) 'c) -- (> dn 2024.01.02D00:00:00.000000000) +(at (select {c: (< d 2024.01.02D00:00:00.000000000) from: TN}) 'c) -- (< dn 2024.01.02D00:00:00.000000000) +(at (select {c: (> ts 0Nd) from: TX}) 'c) -- (> tsx 0Nd) +;; past the parallel threshold +(set tsy (+ 2024.01.01D00:00:00.000000000 (* (til 100000) 1000000000))) +(count (select {from: (table [ts] (list tsy)) where: (> ts 2024.01.02)})) -- (sum (as 'I64 (> tsy 2024.01.02))) +;; a side that is an aggregate of another temporal type: not a literal, so the +;; select is evaluated by the eval path, which compares on the ns scale +(at (select {c: (> ts (first d)) from: TX}) 'c) -- (> tsx (first dx)) +(at (select {c: (< (max d) ts) from: TX}) 'c) -- (< (max dx) tsx) +(count (select {ts: ts from: TX where: (> ts (min d))})) -- (sum (as 'I64 (> tsx (min dx)))) +;; dates beyond the TIMESTAMP range order past every timestamp +(count (select {ts: ts from: TX where: (< ts 9999.12.31)})) -- 10 +(count (select {from: TX where: (< ts 9999.12.31)})) -- 10 +(count (select {ts: ts from: TX where: (> ts 1600.01.01)})) -- 10 +(count (select {from: TX where: (> ts 1600.01.01)})) -- 10 +(< 2024.01.01D00:00:00.000000000 9999.12.31) -- true +(set dbig (concat dx [9999.12.31])) +(count (select {d: d from: (table [d] (list dbig)) where: (> d 2024.01.03D12:00:00.000000000)})) -- 8 +;; an equality a DATE column cannot express holds for no row, != for every row +(set dnul (concat dx [0Nd])) +(at (select {c: (== d 2024.01.03D12:00:00.000000000) from: (table [d] (list dnul))}) 'c) -- (== dnul 2024.01.03D12:00:00.000000000) +(at (select {c: (!= d 2024.01.03D12:00:00.000000000) from: (table [d] (list dnul))}) 'c) -- (!= dnul 2024.01.03D12:00:00.000000000) +(at (select {c: (!= 2024.01.03D12:00:00.000000000 d) from: (table [d] (list dnul))}) 'c) -- (!= 2024.01.03D12:00:00.000000000 dnul) +(at (select {c: (== d 2024.01.03D00:00:00.000000000) from: (table [d] (list dnul))}) 'c) -- (== dnul 2024.01.03D00:00:00.000000000) +;; two literals: rewritten to one type before folding, so no rounding +(at (select {c: (== 2024.01.02 2024.01.02D00:00:00.000000001) n: ts from: TX}) 'c) -- (take false 10) +(at (select {c: (< 2024.01.02 2024.01.02D00:00:00.000000001) n: ts from: TX}) 'c) -- (take true 10) +;; a null literal of the other temporal type is that type's null +(at (select {c: (== d 0Np) from: (table [d] (list dnul))}) 'c) -- (== dnul 0Np) +(at (select {c: (> d 0Np) from: (table [d] (list dnul))}) 'c) -- (> dnul 0Np) diff --git a/test/rfl/query/temporal_cmp_parted.rfl b/test/rfl/query/temporal_cmp_parted.rfl new file mode 100644 index 000000000..7e3ca2c79 --- /dev/null +++ b/test/rfl/query/temporal_cmp_parted.rfl @@ -0,0 +1,17 @@ +;; @requires: posix (fixtures under /tmp, cleaned through a POSIX shell via .sys.exec) +;; A date-partitioned table's `date` key against a TIMESTAMP literal. The key +;; holds days; the literal is rewritten in days, rounded as the operator needs, +;; so partition pruning and the row filter agree with the same data in memory. +(.sys.exec "rm -rf /tmp/rfl_tcmp_parted/") -- 0 +(.db.splayed.set "/tmp/rfl_tcmp_parted/2024.01.01/t/" (table [v] (list (til 4))) "/tmp/rfl_tcmp_parted/.sym") +(.db.splayed.set "/tmp/rfl_tcmp_parted/2024.01.02/t/" (table [v] (list (til 4))) "/tmp/rfl_tcmp_parted/.sym") +(.db.splayed.set "/tmp/rfl_tcmp_parted/2024.01.03/t/" (table [v] (list (til 4))) "/tmp/rfl_tcmp_parted/.sym") +(set P (.db.parted.get "/tmp/rfl_tcmp_parted/" 't)) +(count (select {v: v from: P where: (>= date 2024.01.02D00:00:00.000000000)})) -- 8 +(count (select {v: v from: P where: (> date 2024.01.01D12:00:00.000000000)})) -- 8 +(count (select {v: v from: P where: (< date 2024.01.03D00:00:00.000000001)})) -- 12 +(count (select {v: v from: P where: (<= date 2024.01.02D23:59:59.999999999)})) -- 8 +(count (select {v: v from: P where: (== date 2024.01.02D00:00:00.000000000)})) -- 4 +(count (select {v: v from: P where: (== date 2024.01.02D06:00:00.000000000)})) -- 0 +(count (select {from: P where: (>= date 2024.01.02D00:00:00.000000000)})) -- 8 +(.sys.exec "rm -rf /tmp/rfl_tcmp_parted/") -- 0 diff --git a/test/rfl/query/update_fallback_semantics.rfl b/test/rfl/query/update_fallback_semantics.rfl new file mode 100644 index 000000000..072916325 --- /dev/null +++ b/test/rfl/query/update_fallback_semantics.rfl @@ -0,0 +1,66 @@ +;; update_fallback_semantics.rfl — an `update` expression the DAG declines +;; (temporal + - *) is evaluated with the same row semantics as the compiled +;; 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))` +;; 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 +;; the planner's `schema` error. The fallback now evaluates per row when the +;; expression reads a column in row position and once otherwise (aggregates, +;; constants), checks the length, promotes numeric group results and rejects +;; the rest loudly, and prefers the planner's compile error when both fail. + +(set t (table [k ts tm i name] (list [a a b b b] (+ 2024.01.01D00:00:00.000000000 (* 10 (til 5))) (as 'TIME (* 1000 (til 5))) [1 2 3 4 5] [Al Bo Ca Da Ed]))) + +;; ─── 1. a new or replaced column of the wrong length is rejected ──────────── +(update {n: (til 3) from: t}) !- length +(update {i: (til 3) from: t}) !- length +;; a LIST result too (LIST is type 0, not an atom) +(update {n: (list 1 2) from: t}) !- length +(update {n: (list 1 2) from: t where: (> i 1)}) !- type +(update {i: (list 1 2) from: t}) !- length +(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 (+ 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] +;; 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] +;; 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 (+ 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 {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] +(set GL [1 2 3 4]) +(at (update {x: (if (> i 2) (count GL) (- 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 +;; 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 + +;; ─── 5. a misspelt column reports the planner's schema error ──────────────── +(update {x: (+ nosuch 1) from: t}) !- schema +;; (when the planner declines silently — a temporal operand — there is no +;; planner error and the interpreter's `name` error stands, as in select) +(update {x: (+ nosuch ts) from: t}) !- name diff --git a/test/rfl/query/update_temporal_arith_fallback.rfl b/test/rfl/query/update_temporal_arith_fallback.rfl new file mode 100644 index 000000000..8f9238536 --- /dev/null +++ b/test/rfl/query/update_temporal_arith_fallback.rfl @@ -0,0 +1,28 @@ +;; update_temporal_arith_fallback.rfl — `update` of a NEW column, and `update +;; by:`, whose expression the DAG declines (temporal + - *) fall back to +;; eval-level evaluation like an update of an existing column already does. +;; +;; Both sites returned "failed to compile ... expression" instead, while the +;; same expression worked as `select` and as an update of an existing column +;; (follow-up to eval_fallback_sym_passthrough). + +(set t (table [name ts i] (list [Alice Bob Carol] [2001.01.01D01:01:01.000000000 2002.02.02D02:02:02.000000000 2003.03.03D03:03:03.000000000] [1 2 3]))) + +;; ─── control: existing column, and a compiled new column ──────────────────── +(type (at (update {from: t ts: (+ ts 1)}) 'ts)) -- 'TIMESTAMP +(type (at (update {from: t x: (+ i 1)}) 'x)) -- 'I64 + +;; ─── new column with temporal arithmetic ──────────────────────────────────── +(type (at (update {from: t x: (+ ts 1)}) 'x)) -- 'TIMESTAMP +(at (update {from: t x: (+ ts 1)}) 'x) -- (+ (at t 'ts) 1) +(at (update {from: t x: (- ts ts)}) 'x) -- (- (at t 'ts) (at t 'ts)) +;; the other columns are untouched +(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 + +;; ─── 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]))) +(type (at (update {from: g by: k m: (max (+ ts 1))}) 'm)) -- 'TIMESTAMP +(at (update {from: g by: k m: (max (+ ts 1))}) 'm) -- [2002.02.02D02:02:02.000000001 2002.02.02D02:02:02.000000001 2003.03.03D03:03:03.000000001] diff --git a/test/rfl/query/where_pred_shape_678.rfl b/test/rfl/query/where_pred_shape_678.rfl new file mode 100644 index 000000000..f0b2ece41 --- /dev/null +++ b/test/rfl/query/where_pred_shape_678.rfl @@ -0,0 +1,120 @@ +;; #678: a `where:` value that is not a BOOL vector gave shape-dependent +;; answers. A bare I64 column reached the filter kernels, which read a mask +;; as one byte per row (plain select: [] on a 6-row table, 16666 of 200000 +;; rows on a 200k probe), while the count-only / aggregate shapes kept every +;; row; `where: x take: k` returned the whole table; a symbol literal +;; `'abc` was folded to "keep every row" by the optimizer, while a computed +;; symbol scalar and `update ... where: 'abc` were type errors. +;; +;; One rule now applies at every site (ray_where_mask_coerce in filter.c): +;; - a BOOL vector of row-count length is the mask; +;; - a scalar with a truth value (bool / numeric / temporal; zero and null +;; are false) holds for every row or none; +;; - any other vector (numeric, temporal, symbol, string) is a type error, +;; as query_coverage.rfl and where_eval_fallback.rfl already pin. +;; The tick `'x` resolves to column x inside a query (literal_col_ref.rfl), +;; so it behaves as the column; `(quote x)` stays the literal symbol 'x and +;; is a type error like `'abc`. + +(set T (table [x y s b f] (list [0 256 0N 1 0 0] (til 6) [a b c d e f] [true false true false true false] [0.0 1.5 0Nf 2.0 0.0 0.0]))) + +;; (a) an I64 column is no mask: a type error on every shape, never a partial +;; byte-read mask +(select {from: T where: x}) !- type +(count (select {from: T where: x})) !- type +(select {c: (count y) from: T where: x}) !- type +(select {c: (sum y) from: T where: x}) !- type +(select {from: T where: x take: 1}) !- type +(select {from: T where: x asc: y}) !- type +(select {c: (count y) from: T where: x by: s}) !- type +(select {from: T where: (and x (> y 2))}) !- type +(select {c: (count y) from: T where: (and x (> y 2))}) !- type +(update {y: 99 from: T where: x}) !- type +(delete {from: T where: x}) !- type + +;; (a') F64 and narrower integer columns, the same +(select {from: T where: f}) !- type +(select {c: (count y) from: T where: f}) !- type +(update {y: 99 from: T where: f}) !- type +(select {from: T where: (as 'I32 x)}) !- type +(select {from: T where: (as 'I16 x)}) !- type + +;; (b) the tick form of a column name is that column +(select {from: T where: 'x}) !- type +(select {c: (count y) from: T where: 'x}) !- type +(at (select {from: T where: 'b}) 'y) -- [0 2 4] +(at (select {c: (count y) from: T where: 'b}) 'c) -- [3] + +;; (c) a symbol literal has no truth value: a type error on every shape +(select {from: T where: 'abc}) !- type +(select {c: (count y) from: T where: 'abc}) !- type +(select {c: (count y) from: T where: 'abc by: s}) !- type +(count (select {from: T where: 'abc})) !- type +(select {from: T where: (quote x)}) !- type +(select {from: T where: "str"}) !- type +(update {y: 99 from: T where: 'abc}) !- type +(delete {from: T where: 'abc}) !- type + +;; (d) a computed scalar: numeric by its truth value, symbol a type error +(at (select {from: T where: (first [1 2])}) 'y) -- [0 1 2 3 4 5] +(at (select {from: T where: (first [0 2])}) 'y) -- [] +(at (select {c: (count y) from: T where: (first [0 2])}) 'c) -- [0] +(select {from: T where: (first s)}) !- type +(update {y: 99 from: T where: (first s)}) !- type + +;; (e) BOOL scalar +(at (select {from: T where: true}) 'y) -- [0 1 2 3 4 5] +(at (select {from: T where: false}) 'y) -- [] +(at (select {c: (count y) from: T where: false}) 'c) -- [0] +(at (update {y: 99 from: T where: false}) 'y) -- [0 1 2 3 4 5] + +;; (f) BOOL column +(at (select {from: T where: b}) 'y) -- [0 2 4] +(at (select {c: (count y) from: T where: b}) 'c) -- [3] +(at (select {from: T where: b take: 2}) 'y) -- [0 2] +(at (update {y: 99 from: T where: b}) 'y) -- [99 1 99 3 99 5] +(at (delete {from: T where: b}) 'y) -- [1 3 5] + +;; a SYM column is not a mask either (its ids were read as bytes before) +(select {from: T where: s}) !- type +(select {c: (count y) from: T where: s}) !- type +(update {y: 99 from: T where: s}) !- type + +;; a BOOL vector of the wrong length is a length error, not a partial mask +(select {from: T where: [true false]}) !- length +(select {from: T where: [1 2]}) !- type + +;; (g) the 200k shape from the report: the plain select used to keep 16666 +;; rows (the low byte of every eighth value), the count shape all 200000 +(set N 200000) +(set B (table [x y] (list (% (til N) 3) (til N)))) +(select {from: B where: x}) !- type +(select {c: (count y) from: B where: x}) !- type +(select {from: B where: x take: 10}) !- type +(count (select {from: B where: (!= x 0)})) -- 133333 +(at (select {c: (count y) from: B where: (!= x 0)}) 'c) -- [133333] + +;; ─── review follow-ups ─────────────────────────────────────────────── +;; `and` / `or` over a non-boolean column is the same type error on every +;; shape: select splits an `and` into one filter per conjunct, update and +;; `or` compile the whole expression, and the compiled kernel used to read +;; an I64 operand by its bytes +(update {y: 99 from: T where: (and x (> y 2))}) !- type +(delete {from: T where: (and x (> y 2))}) !- type +(select {from: T where: (or x (> y 4))}) !- type +(update {y: 99 from: T where: (or x (> y 4))}) !- type +(select {c: (count y) from: T where: (or x (> y 4))}) !- type +(select {w: (and x (> y 2)) from: T}) !- type +(at (select {from: T where: (and b (> y 1))}) 'y) -- [2 4] +(at (update {y: 99 from: T where: (and b (> y 1))}) 'y) -- [0 1 99 3 99 5] +(at (select {from: T where: (or b (> y 4))}) 'y) -- [0 2 4 5] +;; the eval fallback (a projection the DAG declines) takes the same rule +(set TF (table [x y ts] (list [0 256 0N 1 0 0] (til 6) (+ 2024.01.01D00:00:00.000000000 (* 10 (til 6)))))) +(select {k: (+ ts 1) from: TF where: x}) !- type +(select {k: (+ ts 1) from: TF where: 'abc}) !- type +(at (select {k: (+ ts 1) y: y from: TF where: (first [0 2])}) 'y) -- [] +(at (select {k: (+ ts 1) y: y from: TF where: (first [1 2])}) 'y) -- [0 1 2 3 4 5] +(at (select {k: (+ ts 1) y: y from: TF where: (> y 3)}) 'y) -- [4 5] +;; the count-only path +(count (select {from: TF where: (first [0 2])})) -- 0 +(count (select {from: TF where: x})) !- type diff --git a/test/rfl/query/xbar_temporal_key_type.rfl b/test/rfl/query/xbar_temporal_key_type.rfl new file mode 100644 index 000000000..00c9822f4 --- /dev/null +++ b/test/rfl/query/xbar_temporal_key_type.rfl @@ -0,0 +1,78 @@ +;; xbar_temporal_key_type.rfl — `(xbar )` compiled by the +;; DAG keeps the column's type (issue #669). +;; +;; The DAG lowers xbar to `col - (col % bucket)`; its arithmetic promotion turns +;; a TIMESTAMP operand into I64 and DATE / TIME into I32, so every DAG path +;; (projection, bare `by:`, by-dict key, parted by-dict key) used to return raw +;; integers where the interpreter's xbar returns the column's type. The DAG +;; now casts the bucketed result back to the column's type. Every golden here +;; is the interpreter's own xbar over the same column, so the DAG and the +;; interpreter are held to the same values AND the same type. + +(set t (table [ts d tm x] (list (as 'TIMESTAMP (* 1000000000 (til 300))) (as 'DATE (til 300)) (as 'TIME (* 1000 (til 300))) (til 300)))) + +;; ─── by-dict key ───────────────────────────────────────────────────────────── +(type (at (select {from: t by: {M: (xbar ts 60000000000)} c: (count x)}) 'M)) -- 'TIMESTAMP +(type (at (select {from: t by: {M: (xbar d 7)} c: (count x)}) 'M)) -- 'DATE +(type (at (select {from: t by: {M: (xbar tm 7000)} c: (count x)}) 'M)) -- 'TIME +(at (select {from: t by: {M: (xbar ts 60000000000)} c: (count x)}) 'M) -- (distinct (xbar (at t 'ts) 60000000000)) +(at (select {from: t by: {M: (xbar d 7)} c: (count x)}) 'M) -- (distinct (xbar (at t 'd) 7)) +(at (select {from: t by: {M: (xbar tm 7000)} c: (count x)}) 'M) -- (distinct (xbar (at t 'tm) 7000)) +;; the aggregate beside the key is unaffected +(at (select {from: t by: {M: (xbar ts 60000000000)} c: (count x)}) 'c) -- [60 60 60 60 60] + +;; ─── projection ────────────────────────────────────────────────────────────── +(type (at (select {k: (xbar ts 60000000000) from: t}) 'k)) -- 'TIMESTAMP +(type (at (select {k: (xbar d 7) from: t}) 'k)) -- 'DATE +(type (at (select {k: (xbar tm 7000) from: t}) 'k)) -- 'TIME +(at (select {k: (xbar ts 60000000000) from: t}) 'k) -- (xbar (at t 'ts) 60000000000) +(at (select {k: (xbar d 7) from: t}) 'k) -- (xbar (at t 'd) 7) +(at (select {k: (xbar tm 7000) from: t}) 'k) -- (xbar (at t 'tm) 7000) + +;; ─── bare `by:` (no interpreter fallback: the key MUST compile) ───────────── +;; (group order is unspecified for a computed bare key: compare sorted) +(type (at (select {from: t by: (xbar ts 60000000000) c: (count x)}) 'ts)) -- 'TIMESTAMP +(type (at (select {from: t by: (xbar d 7) c: (count x)}) 'd)) -- 'DATE +(type (at (select {from: t by: (xbar tm 7000) c: (count x)}) 'tm)) -- 'TIME +(asc (at (select {from: t by: (xbar ts 60000000000) c: (count x)}) 'ts)) -- (asc (distinct (xbar (at t 'ts) 60000000000))) +(asc (at (select {from: t by: (xbar d 7) c: (count x)}) 'd)) -- (asc (distinct (xbar (at t 'd) 7))) + +;; ─── WHERE predicate over a bucketed temporal column ───────────────────────── +(at (select {x: x from: t where: (== (xbar ts 60000000000) 2000.01.01D00:02:00.000000000)}) 'x) -- (+ 120 (til 60)) + +;; ─── bucket forms the interpreter accepts ──────────────────────────────────── +;; narrow integer bucket +(type (at (select {k: (xbar ts (as 'I32 60000000)) from: t}) 'k)) -- 'TIMESTAMP +(at (select {k: (xbar ts (as 'I32 60000000)) from: t}) 'k) -- (xbar (at t 'ts) (as 'I32 60000000)) +;; TIME bucket on a TIMESTAMP column is a millisecond bucket (scaled to ns) +(at (select {k: (xbar ts 00:01:00.000) from: t}) 'k) -- (xbar (at t 'ts) 00:01:00.000) +(at (select {from: t by: {M: (xbar ts 00:01:00.000)} c: (count x)}) 'M) -- (distinct (xbar (at t 'ts) 00:01:00.000)) +;; same-type temporal bucket +(at (select {k: (xbar d 2000.01.08) from: t}) 'k) -- (xbar (at t 'd) 2000.01.08) +;; a float bucket is a type error on a temporal column, in a query as outside one +(select {k: (xbar ts 2.5) from: t}) !- type +(select {from: t by: {M: (xbar ts 2.5)} c: (count x)}) !- type + +;; ─── nulls stay null, in the column's type ─────────────────────────────────── +(set tn (table [ts d x] (list [2000.01.01D00:00:00.000000000 0Np 2000.01.01D00:01:30.000000000] [2000.01.01 0Nd 2000.01.09] [1 2 3]))) +(at (select {k: (xbar ts 60000000000) from: tn}) 'k) -- [2000.01.01D00:00:00.000000000 0Np 2000.01.01D00:01:00.000000000] +(at (select {k: (xbar d 7) from: tn}) 'k) -- [2000.01.01 0Nd 2000.01.08] +(asc (at (select {from: tn by: {M: (xbar ts 60000000000)} c: (count x)}) 'M)) -- (asc (distinct (xbar (at tn 'ts) 60000000000))) +(asc (at (select {from: tn by: {M: (xbar d 7)} c: (count x)}) 'M)) -- (asc (distinct (xbar (at tn 'd) 7))) + +;; ─── parted by-dict key (per-partition streaming kernel) ───────────────────── +(set N 400) +(set PTS (as 'TIMESTAMP (* 1000000000 (til N)))) +(set PD (as 'DATE (til N))) +(set PV (as 'F64 (til N))) +(set P1 (table [ts d v] (list PTS PD PV))) +(.sys.exec "rm -rf /tmp/rfl_xbar_tkt") +(.db.splayed.set "/tmp/rfl_xbar_tkt/1/t/" P1) +(.db.splayed.set "/tmp/rfl_xbar_tkt/2/t/" P1) +(set Pw (.db.parted.get "/tmp/rfl_xbar_tkt/" 't)) +(type (at (select {sv: (sum v) by: {tb: (xbar ts 200000000000)} from: Pw asc: tb}) 'tb)) -- 'TIMESTAMP +(at (select {sv: (sum v) by: {tb: (xbar ts 200000000000)} from: Pw asc: tb}) 'tb) -- (distinct (xbar PTS 200000000000)) +(type (at (select {sv: (sum v) by: {tb: (xbar d 200)} from: Pw asc: tb}) 'tb)) -- 'DATE +(at (select {sv: (sum v) by: {tb: (xbar d 200)} from: Pw asc: tb}) 'tb) -- (distinct (xbar PD 200)) +(at (select {sv: (sum v) by: {tb: (xbar d 200)} from: Pw asc: tb}) 'sv) -- [39800.0 119800.0] +(.sys.exec "rm -rf /tmp/rfl_xbar_tkt") diff --git a/test/rfl/regress/issue_674.rfl b/test/rfl/regress/issue_674.rfl new file mode 100644 index 000000000..3ece7fc67 --- /dev/null +++ b/test/rfl/regress/issue_674.rfl @@ -0,0 +1,14 @@ +;; #674: (as 'STR ...) in a select projection returned a LIST of boxed string +;; atoms (the eval fallback did not collapse STR cells). Fixed by the STR +;; collapse in the fallback collector (#690); pinned here. +(set T674 (table [x s] (list (til 4) [a b a b]))) +(type (at (select {k: (as 'STR (% x 5)) from: T674}) 'k)) -- 'STR +(at (select {k: (as 'STR (% x 5)) from: T674}) 'k) -- (as 'STR (% (til 4) 5)) +(type (at (select {k: (as 'STR x) from: T674}) 'k)) -- 'STR +(type (at (select {k: (as 'STR s) from: T674}) 'k)) -- 'STR +(type (at (select {k: (as 'STR (% x 5)) from: T674 where: (> x 0)}) 'k)) -- 'STR +(type (at (update {k: (as 'STR (% x 5)) from: T674}) 'k)) -- 'STR +;; grouped: one STR vector per group, the shape a plain column takes under by: +(type (at (select {k: (as 'STR (% x 5)) by: s from: T674}) 'k)) -- 'LIST +(at (select {k: (as 'STR (% x 5)) by: s from: T674}) 'k) -- (list (as 'STR (list "0" "2")) (as 'STR (list "1" "3"))) +(type (at (select {k: (as 'STR (first x)) by: s from: T674}) 'k)) -- 'STR diff --git a/test/rfl/regress/issue_691.rfl b/test/rfl/regress/issue_691.rfl new file mode 100644 index 000000000..8e55613a4 --- /dev/null +++ b/test/rfl/regress/issue_691.rfl @@ -0,0 +1,25 @@ +;; #691: a compiled `if` whose branches are GUID columns kept promote()'s +;; fallthrough type (B8) and the fill read the 16-byte cells as bytes. +(set T691 (table [i g] (list [1 2 3 4] (guid 4)))) +(set G691 (at T691 'g)) +(set G1 (first (guid 1))) +(type (at (select {w: (if (> i 2) g g) from: T691}) 'w)) -- 'GUID +(all (== (at (select {w: (if (> i 2) g g) from: T691}) 'w) G691)) -- true +(type (at (select {w: (if true g g) from: T691}) 'w)) -- 'GUID +(type (at (select {w: (if (> i 2) g g) from: T691 where: (> i 1)}) 'w)) -- 'GUID +(type (at (update {w: (if (> i 2) g g) from: T691}) 'w)) -- 'GUID +(type (at (select {w: (cond ((> i 2) g) (else g)) from: T691}) 'w)) -- 'GUID +;; scalar GUID branch (an env-bound atom compiles as a const) +(set W691 (at (select {w: (if (> i 2) g G1) from: T691}) 'w)) +(type W691) -- 'GUID +(== (at W691 0) G1) -- true +(== (at W691 1) G1) -- true +(== (at W691 2) (at G691 2)) -- true +(== (at W691 3) (at G691 3)) -- true +;; mixed GUID / numeric branches have no column type: the DAG declines +;; instead of reading GUID bytes as integers +(type (at (select {w: (if (> i 2) g i) from: T691}) 'w)) -- 'LIST +;; a LIST column scans as the untyped node and fell into the same B8 fill +(set TL (table [i l] (list [1 2 3 4] (list [1 2] [3] [4 5 6] [7])))) +(type (at (select {w: (if (> i 2) l l) from: TL}) 'w)) -- 'LIST +(at (select {w: (if (> i 2) l l) from: TL}) 'w) -- (list [1 2] [3] [4 5 6] [7]) diff --git a/test/rfl/regress/issue_694.rfl b/test/rfl/regress/issue_694.rfl new file mode 100644 index 000000000..56692f012 --- /dev/null +++ b/test/rfl/regress/issue_694.rfl @@ -0,0 +1,46 @@ +;; #694 — an integer column compared with a float scalar computed inside the +;; select (an aggregate, or arithmetic on one) compared every row against 0: +;; the integer-column fast path in binary_range read the scalar as int64 +;; without checking it was one. Literals and the reversed operand order were +;; never affected; both are kept as guards. +(set t (table [i] (list [1 2 3 4 5]))) + +(at (select {c: (> i (avg i)) from: t}) 'c) -- [false false false true true] +(at (select {c: (< i (avg i)) from: t}) 'c) -- [true true false false false] +(at (select {c: (== i (avg i)) from: t}) 'c) -- [false false true false false] +(at (select {c: (!= i (avg i)) from: t}) 'c) -- [true true false true true] +(at (select {c: (>= i (avg i)) from: t}) 'c) -- [false false true true true] +(at (select {c: (<= i (avg i)) from: t}) 'c) -- [true true true false false] +(at (select {i: i from: t where: (> i (avg i))}) 'i) -- [4 5] +(at (select {c: (> i (/ (sum i) 5)) from: t}) 'c) -- [false false false true true] +(at (select {c: (> i (first [3.5])) from: t}) 'c) -- [false false false true true] +(at (update {c: (> i (avg i)) from: t}) 'c) -- [false false false true true] + +;; narrower integer columns take the same kernel +(set t32 (table [j] (list (as 'i32 [1 2 3 4 5])))) +(at (select {c: (> j (avg j)) from: t32}) 'c) -- [false false false true true] +(at (select {j: j from: t32 where: (> j (avg j))}) 'j) -- [4 5] +(set t16 (table [h] (list (as 'i16 [1 2 3 4 5])))) +(at (select {c: (> h (avg h)) from: t16}) 'c) -- [false false false true true] +(set tb (table [b] (list [true false true false true]))) +(at (select {c: (== b (avg b)) from: tb}) 'c) -- [false false false false false] + +;; guards: a float literal, a global, and the reversed order were already right +(at (select {c: (> i 3.0) from: t}) 'c) -- [false false false true true] +(set thr 3.5) +(at (select {c: (> i thr) from: t}) 'c) -- [false false false true true] +(at (select {c: (> (avg i) i) from: t}) 'c) -- [true true false false false] +(at (select {c: (+ i (avg i)) from: t}) 'c) -- [4.0 5.0 6.0 7.0 8.0] + +;; `(count (select {from: t where: (op col lit)}))` takes a counting fast path +;; that compared the column with the literal's raw integer value: a float +;; literal decoded to 0, and a DATE or TIME literal against a TIMESTAMP +;; column compared days or milliseconds with nanoseconds. +(set TC4 (table [i d ts] (list [1 2 3 4] [2024.01.01 2024.01.02 2024.01.03 2024.01.04] (+ 2024.01.01D00:00:00.000000000 (* (til 4) 43200000000000))))) +(count (select {from: TC4 where: (> i 2.5)})) -- 2 +(count (select {from: TC4 where: (< i 2.5)})) -- 2 +(count (select {from: TC4 where: (== i 2.0)})) -- 1 +(count (select {from: TC4 where: (> ts 2024.01.02)})) -- 1 +(count (select {from: TC4 where: (>= ts 2024.01.02)})) -- 2 +(count (select {from: TC4 where: (> d 2024.01.02D12:00:00.000000000)})) -- 2 +(count (select {from: TC4 where: (> d 2024.01.02)})) -- 2 diff --git a/test/rfl/regress/issue_698.rfl b/test/rfl/regress/issue_698.rfl new file mode 100644 index 000000000..06208b4b0 --- /dev/null +++ b/test/rfl/regress/issue_698.rfl @@ -0,0 +1,84 @@ +;; #698 — a select with a bare aggregate beside a scalar expression over +;; aggregates came back with one row per input row. The mixed outputs route +;; through OP_SELECT, which broadcast the aggregate's atom to the input's rows +;; as soon as it was computed; the broadcast column then counted as one that +;; carries the input's rows, and the one-element `(+ (sum x) 1)` was +;; broadcast beside it. No output reads a row, so the result is one row. +(set T (table [x] (list (til 8)))) + +(count (select {s: (sum x) k: (+ (sum x) 1) from: T})) -- 1 +(at (select {s: (sum x) k: (+ (sum x) 1) from: T}) 's) -- [28] +(at (select {s: (sum x) k: (+ (sum x) 1) from: T}) 'k) -- [29] +(at (select {k: (+ (sum x) 1) s: (sum x) from: T}) 's) -- [28] +(at (select {s: (sum x) m: (max x) k: (* (min x) 2) from: T}) 'm) -- [7] +;; a scalar `if` over an aggregate beside a bare one +(at (select {s: (sum x) k: (if (> (sum x) 4) 1 0) from: T}) 'k) -- [1] +;; atoms of other types: a symbol and a float +(set S (table [g v] (list ['a 'b 'c] [1.5 2.5 3.5]))) +(at (select {f: (first g) c: (+ (count g) 0) from: S}) 'f) -- ['a] +(at (select {a: (avg v) c: (+ (count g) 0) from: S}) 'a) -- [2.5] + +;; a literal beside an aggregate carries no rows either +(count (select {s: 1 y: (sum x) from: T})) -- 1 +(at (select {s: 1 y: (sum x) from: T}) 's) -- [1] +(count (select {s: 1 k: (+ (sum x) 1) from: T})) -- 1 + +;; under where: the reductions walk the selection; still one row +(at (select {s: (sum x) k: (+ (sum x) 1) from: T where: (> x 3)}) 's) -- [22] +(at (select {s: (sum x) k: (+ (sum x) 1) from: T where: (> x 3)}) 'k) -- [23] +(at (select {s: (sum x) k: (+ (sum x) 1) from: T where: (> x 100)}) 'k) -- [1] +(at (select {s: (sum x) k: (+ (sum x) 1) from: T where: (> x 3) take: 3}) 's) -- [22] +;; an empty input reduces to one row as well +(set E (select {x: x from: T where: (> x 100)})) +(at (select {s: (sum x) k: (+ (sum x) 1) from: E}) 'k) -- [1] +;; a one-row input +(at (select {s: (sum x) k: (+ (sum x) 1) from: (table [x] (list [5]))}) 'k) -- [6] +(at (select {s: (sum x) k: (+ (sum x) 1) from: (table [x] (list [5])) where: (> x 10)}) 'k) -- [1] + +;; guards: an output reading rows still broadcasts the scalars beside it +(count (select {s: (sum x) y: x from: T})) -- 8 +(at (select {s: (sum x) y: x from: T where: (> x 5)}) 's) -- [13 13] +(at (select {s: (sum x) k: (+ (sum x) 1) y: x from: T where: (> x 5)}) 'k) -- [14 14] +(at (select {s: 1 y: x from: T where: (> x 5)}) 's) -- [1 1] +;; a select of literals alone keeps the input's rows +(count (select {s: 1 from: T})) -- 8 +(count (select {s: 1 from: T where: (> x 5)})) -- 2 +(count (select {s: 1 from: E})) -- 0 +(count (select {s: 1 t: 'a from: T})) -- 8 + +;; a one-row literal select under a failing where: is no row, as on any input +(count (select {s: 1 from: (table [x] (list [5])) where: (> x 10)})) -- 0 + +;; scalars of any atom type widen beside a row column; these were broadcast +;; by a str/i64/f64/bool/sym-only routine and failed with a type error +(set D (table [d x] (list [2024.01.01 2024.01.03] [1 2]))) +(at (select {m: (max d) y: x from: D}) 'm) -- [2024.01.03 2024.01.03] +(at (select {m: (max d) k: (+ (sum x) 1) from: D}) 'm) -- [2024.01.03] +(at (select {m: (max (as 'I32 x)) y: x from: D}) 'm) -- (as 'I32 [2 2]) +(at (select {m: (avg (as 'F64 [0N 0N])) y: x from: D}) 'm) -- [0Nf 0Nf] + +;; a later output over an earlier aggregate reads its value, not a one-row +;; column (the eval fallback; `type` and `til` are not compiled) +(set T6 (table [x] (list (til 6)))) +(at (select {m: (max x) t: (type m) from: T6}) 't) -- ['i64] +(at (select {m: (count x) y: (til m) from: T6}) 'y) -- (list (til 6)) +(at (select {m: (max x) y: (+ m 1) z: (* y 2) from: T6}) 'z) -- [12] +;; beside a row column it is read per row, as before +(at (select {m: (max x) t: (type m) w: x from: T6}) 't) -- (take 'i64 6) + +;; a one-element vector literal is a scalar like an atom: alone it keeps the +;; input's rows, as it already did beside an atom literal +(count (select {a: [7] from: T6})) -- 6 +(count (select {a: [7] b: 1 from: T6})) -- 6 +(count (select {a: [7] s: (sum x) from: T6})) -- 1 + +;; ─── on a parted table ─────────────────────────────────────────────── +(.sys.exec "rm -rf /tmp/rfl_q698_parted") +(.db.splayed.set "/tmp/rfl_q698_parted/2024.01.01/t/" (table [x] (list [1 2 3]))) +(.db.splayed.set "/tmp/rfl_q698_parted/2024.01.02/t/" (table [x] (list [10 20]))) +(set P (.db.parted.get "/tmp/rfl_q698_parted/" 't)) +(count (select {s: (sum x) k: (+ (sum x) 1) from: P})) -- 1 +(at (select {s: (sum x) k: (+ (sum x) 1) from: P}) 'k) -- [37] +(at (select {s: (sum x) k: (+ (sum x) 1) from: P where: (> x 2)}) 's) -- [33] +(count (select {s: (sum x) y: x from: P})) -- 5 +(.sys.exec "rm -rf /tmp/rfl_q698_parted") diff --git a/test/rfl/regress/issue_707.rfl b/test/rfl/regress/issue_707.rfl new file mode 100644 index 000000000..eb40d7fee --- /dev/null +++ b/test/rfl/regress/issue_707.rfl @@ -0,0 +1,62 @@ +;; #707 — a select grouped by a computed key (`by: (% v 3)`) failed with +;; "nyi: eval-level groupby requires scalar key" whenever an output was not a +;; plain aggregate: a `distinct` aggregate or a row expression sends the +;; select to the eval-level grouping, which only read a key from a named +;; column. The key is now evaluated over the selected rows into a hidden +;; column; the result names it as the DAG path names a computed key. +(set T (table [s v] (list (take ['abc1 'abd2 'xyz3 'xya4] 40) (til 40)))) +;; the oracle: the same key materialized as a column first +(set U (update {k: (substr s 0 2) m: (% v 3) p: (% v 2) from: T})) + +(count (select {c: (count (distinct v)) from: T by: (substr s 0 2)})) -- 2 +(at (select {c: (count (distinct v)) from: T by: (substr s 0 2) asc: s}) 'c) -- (at (select {c: (count (distinct v)) from: U by: k asc: k}) 'c) +(at (select {c: (count (distinct v)) from: T by: (substr s 0 2) asc: s}) 's) -- ['ab 'xy] +(at (select {c: (count (distinct v)) from: T by: (% v 3) asc: v}) 'c) -- [14 13 13] +(at (select {c: (count (distinct v)) from: T by: (% v 3) asc: v}) 'v) -- [0 1 2] +(at (select {c: (sum (distinct v)) from: T by: (% v 3) asc: v}) 'c) -- (at (select {c: (sum (distinct v)) from: U by: m asc: m}) 'c) +(at (select {c: (count (distinct v)) n: (count v) from: T by: (% v 3) asc: v}) 'n) -- [14 13 13] +;; a row expression beside the key +(at (select {c: (+ v 1) from: T by: (% v 3) asc: v}) 'c) -- (at (select {c: (+ v 1) from: U by: m asc: m}) 'c) +(at (select {d: (distinct v) from: T by: (% v 2) asc: v}) 'd) -- (at (select {d: (distinct v) from: U by: p asc: p}) 'd) + +;; where: filters the rows the key is computed over +(at (select {c: (count (distinct v)) from: T where: (> v 5) by: (substr s 0 2) asc: s}) 'c) -- (at (select {c: (count (distinct v)) from: U where: (> v 5) by: k asc: k}) 'c) +(at (select {c: (count (distinct v)) from: T where: (> v 30) by: (% v 3) asc: v}) 'c) -- [3 3 3] +(count (select {c: (count (distinct v)) from: T where: (> v 100) by: (% v 3)})) -- 0 + +;; the key column's name: the expression's column, or `key` when an output +;; spells the same or the expression names no column +(key (select {c: (count (distinct v)) from: T by: (% v 3)})) -- ['v 'c] +(key (select {v: (count (distinct v)) from: T by: (% v 3)})) -- ['key 'v] +(key (select {c: (count (distinct v)) from: T by: (+ (% v 3) 1)})) -- ['key 'c] +;; the source column the key is derived from is left intact for the outputs +(at (select {mx: (max (distinct v)) from: T by: (% v 3) asc: v}) 'mx) -- [39 37 38] +;; the input table is not modified +(key T) -- ['s 'v] + +;; a sort key naming the derived key column sorts by the key, not the source +(at (select {c: (count (distinct v)) from: T by: (% v 3) desc: v}) 'v) -- [2 1 0] +(at (select {c: (count (distinct v)) from: T by: (% v 3) asc: [c v]}) 'v) -- [1 2 0] +(at (select {c: (count (distinct v)) from: T by: (% v 3) desc: v take: 1}) 'c) -- [13] + +;; plain aggregates keep the DAG path and its naming +(key (select {c: (count v) from: T by: (% v 3)})) -- ['v 'c] +(at (select {c: (count v) from: T by: (% v 3) asc: v}) 'c) -- [14 13 13] + +;; a literal key is one group +(at (select {c: (count (distinct v)) from: T by: 1}) 'c) -- [40] +;; the key is computed row-wise, as a by-dict value is: `if` per row +(at (select {c: (count (distinct v)) from: T by: (if (> v 4) 1 0) asc: key}) 'c) -- [5 35] + +;; ─── on a parted table ─────────────────────────────────────────────── +(.sys.exec "rm -rf /tmp/rfl_q707_parted") +(.db.splayed.set "/tmp/rfl_q707_parted/2024.01.01/t/" (table [v] (list [1 2 3 4]))) +(.db.splayed.set "/tmp/rfl_q707_parted/2024.01.02/t/" (table [v] (list [5 6 7 7]))) +(set P (.db.parted.get "/tmp/rfl_q707_parted/" 't)) +(at (select {c: (count (distinct v)) from: P by: (% v 2) asc: v}) 'c) -- (at (select {c: (count (distinct v)) from: P by: {m: (% v 2)} asc: m}) 'c) +(at (select {c: (count (distinct v)) from: P by: (% v 2) asc: v}) 'c) -- [3 4] +(at (select {c: (count (distinct v)) from: P where: (> v 2) by: (% v 2) asc: v}) 'c) -- [2 3] +(.sys.exec "rm -rf /tmp/rfl_q707_parted") + +;; the hidden key column's name is refused rather than shadowed +(select {c: (count (distinct v)) from: (table [__by_key v] (list [1 2] [3 4])) by: (% v 2)}) !- domain diff --git a/test/rfl/storage/atomic_generations.rfl b/test/rfl/storage/atomic_generations.rfl new file mode 100644 index 000000000..731eb772a --- /dev/null +++ b/test/rfl/storage/atomic_generations.rfl @@ -0,0 +1,54 @@ +;; Replacements must be visible through every public storage entry point. +(.sys.exec "rm -rf /tmp/rf_test_atomic_generations") -- 0 +(set agRoot "/tmp/rf_test_atomic_generations") +(set agLeaf (format "%/2026.09.28/t" agRoot)) +(set agOld (table ['x 'y] (list [1 2] [10 20]))) +(set agNew (table ['x 'y] (list [3 4] [30 40]))) +(.db.splayed.set agLeaf agOld) +(.db.splayed.set agLeaf agNew) +(sum (at (.db.splayed.get agLeaf) 'x)) -- 7 +(sum (at (.db.parted.get agRoot 't) 'x)) -- 7 +;; The first generation publish retires the legacy schema so old binaries +;; cannot silently read the stale root files. +(.sys.exec "test ! -f /tmp/rf_test_atomic_generations/2026.09.28/t/.d") -- 0 +;; Discovery must use the active schema without the legacy root .d. +(.db.parted.tables agRoot) -- ['t] + +;; Schema narrowing must not make the partition reader use the old .d. +(.db.splayed.set agLeaf (table ['x] (list [5 6]))) +(count (key (.db.parted.get agRoot 't))) -- 2 +(sum (at (.db.parted.get agRoot 't) 'x)) -- 11 + +;; The streaming (numeric) CSV writer must publish a new generation too. +(.csv.write agNew (format "%/new.csv" agRoot)) +(set agCSV (.csv.splayed (format "%/new.csv" agRoot) agLeaf)) +(sum (at agCSV 'x)) -- 7 +(sum (at (.db.splayed.get agLeaf) 'y)) -- 70 +(sum (at (.db.parted.get agRoot 't) 'y)) -- 70 + +;; Its materializing STR fallback uses the same protocol and root symfile. +(set agText (table ['x 'text 'sym] (list [7 8] ["alpha" "beta"] ['A 'B]))) +(.csv.write agText (format "%/text.csv" agRoot)) +(set agCSV (.csv.splayed [I64 STR SYMBOL] (format "%/text.csv" agRoot) (format "%/text" agRoot))) +(set agText (table ['x 'text 'sym] (list [9 10] ["gamma" "delta"] ['C 'D]))) +(.csv.write agText (format "%/text.csv" agRoot)) +(set agCSV (.csv.splayed [I64 STR SYMBOL] (format "%/text.csv" agRoot) (format "%/text" agRoot))) +(at agCSV 'x) -- [9 10] +(at agCSV 'text) -- ["gamma" "delta"] +(at agCSV 'sym) -- ['C 'D] + +;; Persist indexes in the generation being published, not in legacy files. +(set agIndexed (table ['k 'v] (list (.attr.set 'grouped ['a 'b]) [1 2]))) +(.db.splayed.set (format "%/indexed" agRoot) agIndexed) +(.db.splayed.set (format "%/indexed" agRoot) agIndexed) +(.idx.has? (at (.db.splayed.get (format "%/indexed" agRoot)) 'k)) -- true +(set agStrings (table ['k] (list (.attr.set 'grouped ["aa" "bb"])))) +(.db.splayed.set (format "%/indexed_str" agRoot) agStrings) +(.db.splayed.set (format "%/indexed_str" agRoot) agStrings) +(.idx.has? (at (.db.splayed.get (format "%/indexed_str" agRoot)) 'k)) -- true +;; Retention is bounded to current + previous generation. +(.db.splayed.set agLeaf (table ['x] (list [11 12]))) +(.db.splayed.set agLeaf (table ['x] (list [13 14]))) +(.db.splayed.set agLeaf (table ['x] (list [15 16]))) +(.sys.exec "test $(find /tmp/rf_test_atomic_generations/2026.09.28/t/.generations -mindepth 1 -maxdepth 1 -type d | wc -l) -le 2") -- 0 +(.sys.exec "rm -rf /tmp/rf_test_atomic_generations") -- 0 diff --git a/test/rfl/strop/standalone_string_ops.rfl b/test/rfl/strop/standalone_string_ops.rfl index a6392ec43..160baa716 100644 --- a/test/rfl/strop/standalone_string_ops.rfl +++ b/test/rfl/strop/standalone_string_ops.rfl @@ -46,3 +46,26 @@ (substr [1 2 3] 1 1) !- type (replace ["a"] 1 "x") !- type + +;; A string literal reaches the compiled string ops as an atom, whose len +;; field aliases its payload: the ops read that many rows past it. An update +;; with (strlen "abc") or (trim " ab") crashed, (upper (first s)) beside a +;; column returned hundreds of garbage rows, and substr / replace asked for +;; petabytes. +(set TsL (table [x s t] (list (til 4) ['ab 'cd 'ef 'gh] (list "ab" "cd" "ef" "gh")))) +(at (update {y: (strlen "abc") from: TsL}) 'y) -- [3 3 3 3] +(at (update {x: (strlen "abc") from: TsL}) 'x) -- [3 3 3 3] +(at (update {y: (trim " ab") from: TsL}) 'y) -- ["ab" "ab" "ab" "ab"] +(at (update {y: (upper "ab") from: TsL}) 'y) -- ["AB" "AB" "AB" "AB"] +(at (update {y: (lower 'AB) from: TsL}) 'y) -- ['ab 'ab 'ab 'ab] +(at (select {a: (upper (first s)) b: x from: TsL}) 'a) -- ['AB 'AB 'AB 'AB] +(at (select {a: (upper (first t)) b: x from: TsL}) 'a) -- ["AB" "AB" "AB" "AB"] +(at (update {y: (substr "abcdef" 1 3) from: TsL}) 'y) -- ["abc" "abc" "abc" "abc"] +(at (update {y: (replace "abcabc" "b" "x") from: TsL}) 'y) -- ["axcaxc" "axcaxc" "axcaxc" "axcaxc"] +;; concat reads a symbol literal or scalar's text: only SYM vectors were read, +;; so (concat 'ab 'cd) in a query came back null and (concat (first s) "x") +;; dropped the symbol. +(at (select {y: (concat 'ab 'cd) z: x from: TsL}) 'y) -- ['abcd 'abcd 'abcd 'abcd] +(at (select {y: (concat (first s) "x") z: x from: TsL}) 'y) -- ['abx 'abx 'abx 'abx] +(at (select {y: (concat s 'zz) from: TsL}) 'y) -- ['abzz 'cdzz 'efzz 'ghzz] +(at (select {y: (concat t 'q) from: TsL}) 'y) -- ["abq" "cdq" "efq" "ghq"] diff --git a/test/rfl/symbol/file_domain_if.rfl b/test/rfl/symbol/file_domain_if.rfl index 0a2bfd6cc..356d71555 100644 --- a/test/rfl/symbol/file_domain_if.rfl +++ b/test/rfl/symbol/file_domain_if.rfl @@ -55,4 +55,44 @@ ;; the empty symbol (a null cell) survives the translation on either side (set A6 (select {from: F k: (if (> v 50) ref 'x)})) (== (count (select {from: A6 where: (== k "")})) (count (select {from: T where: (and (> v 50) (== ref ""))}))) -- true -(.sys.exec "rm -rf /tmp/rfl_fdom_if/") -- 0 + +;; a symbol column against a string literal or a string column answers +;; STR, each row's text taken from its side — on the pool past the +;; parallel threshold, the FILE domain's vocabulary read in place and the +;; in-memory column's text read from the symbol table, nothing interned. +;; Nulls ("" cells) on the symbol side. Oracle: the scalar `if` row by row. +(.sys.exec "rm -rf /tmp/rfl_fdom_if_x/") -- 0 +(set rs (as 'STR ref2)) +(set TX (table [ref s v] (list ref rs v))) +(.db.splayed.set "/tmp/rfl_fdom_if_x/" TX) +(set FX (.db.splayed.get "/tmp/rfl_fdom_if_x/")) +(set O1 (as 'STR (map (fn [k] (if (> (at v k) 50) (as 'STR (at ref k)) "")) i))) +(set C1 (select {from: F k: (if (> v 50) ref "")})) +(type (at C1 'k)) -- 'STR +(all (== (at C1 'k) O1)) -- true +(all (== (at (select {from: T k: (if (> v 50) ref "")}) 'k) O1)) -- true +(set O2 (as 'STR (map (fn [k] (if (== 0 (% (at v k) 3)) (at rs k) (as 'STR (at ref k)))) i))) +(all (== (at (select {from: FX k: (if (== 0 (% v 3)) s ref)}) 'k) O2)) -- true +(all (== (at (select {from: TX k: (if (== 0 (% v 3)) s ref)}) 'k) O2)) -- true +(set O3 (as 'STR (map (fn [k] (if (> (at v k) 20) "abc" (at rs k))) i))) +(all (== (at (select {from: FX k: (if (> v 20) 'abc s)}) 'k) O3)) -- true +;; under a dense where: (pooled over the table, then filtered), a sparse +;; one (row by row over the passing rows) and an empty one +(set OW (fn [p] (at (select {from: (table [k v] (list O1 v)) where: (p v)}) 'k))) +(all (== (at (select {from: F k: (if (> v 50) ref "") where: (> v 10)}) 'k) (OW (fn [x] (> x 10))))) -- true +(all (== (at (select {from: F k: (if (> v 50) ref "") where: (== v 77)}) 'k) (OW (fn [x] (== x 77))))) -- true +(count (select {from: F k: (if (> v 50) ref "") where: (> v 1000)})) -- 0 +;; a partitioned table after a live insert of a new symbol: the domain +;; holds positions past its mapped file, so the `if` takes the selected arm +;; up front. Oracle: the scalar `if` row by row. +(.sys.exec "rm -rf /tmp/rfl_fdom_if_p/") -- 0 +(.db.splayed.set "/tmp/rfl_fdom_if_p/1/t/" TX "/tmp/rfl_fdom_if_p/.sym") +(set PT (.db.parted.get "/tmp/rfl_fdom_if_p/" 't)) +(insert 'PT 2 (list (as 'SYMBOL ["fdom_if_novel" "fdom_if_novel"]) ["s1" "s2"] [99 7])) +(set PR (as 'STR (at PT 'ref))) +(set PV (at PT 'v)) +(set OP1 (as 'STR (map (fn [k] (if (> (at PV k) 50) (at PR k) "")) (til (count PT))))) +(all (== (at (select {from: PT k: (if (> v 50) ref "")}) 'k) OP1)) -- true +(last (at (select {from: PT k: (if (> v 50) ref "")}) 'k)) -- "" +(at (at (select {from: PT k: (if (> v 50) ref "")}) 'k) (- (count PT) 2)) -- "fdom_if_novel" +(.sys.exec "rm -rf /tmp/rfl_fdom_if/ /tmp/rfl_fdom_if_x/ /tmp/rfl_fdom_if_p/") -- 0 diff --git a/test/rfl/system/ipc_diff.rfl b/test/rfl/system/ipc_diff.rfl index 31f627bd5..7e53ed584 100644 --- a/test/rfl/system/ipc_diff.rfl +++ b/test/rfl/system/ipc_diff.rfl @@ -72,6 +72,13 @@ ;; ── string ops ───────────────────────────────────────────────────── (like "hello" "h*") -- (.ipc.send h "(like \"hello\" \"h*\")") +;; ── process-local handles ────────────────────────────────────────── +;; Graph handles carry heap pointers in i64 atoms plus RAY_ATTR_GRAPH. +;; They must be rejected by the shared serde path before IPC can leak +;; the address or silently demote a nested handle to a bare integer. +(.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 + ;; ── 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/ipc_open_opts.rfl b/test/rfl/system/ipc_open_opts.rfl index 0ef7b6d22..fe875bfa8 100644 --- a/test/rfl/system/ipc_open_opts.rfl +++ b/test/rfl/system/ipc_open_opts.rfl @@ -1,10 +1,12 @@ ;; ipc_open_opts.rfl — `.ipc.open`'s second argument (#541). ;; ;; It stays an integer connect timeout, or becomes an options dict with -;; optional `timeout` and `compress`. `compress` is a threshold in bytes, -;; not a flag: 0N never compresses, 0 always does, n compresses payloads -;; larger than n. Absent means auto — loopback and UNIX-domain links -;; default to never compressing, everything else to the built-in 2000. +;; optional `timeout`, `compress` and `keepalive`. `compress` is a +;; threshold in bytes, not a flag: 0N never compresses, 0 always does, n +;; compresses payloads larger than n. Absent means auto — loopback and +;; UNIX-domain links default to never compressing, everything else to the +;; built-in 2000. `keepalive` is a dead-peer budget in ms (#589): 0N +;; turns detection off, absent keeps it on at the 60s default. ;; ;; Nothing is bound on 19974, so a well-formed call reaches connect and ;; fails with `io`; a malformed one is rejected before that, with `type` @@ -20,6 +22,10 @@ (.ipc.open "127.0.0.1:19974" (dict [compress] [0])) !- io (.ipc.open "127.0.0.1:19974" (dict [compress] [5000])) !- io (.ipc.open "127.0.0.1:19974" (dict [timeout compress] [200 0N])) !- io +;; keepalive (#589): a dead-peer budget in ms, 0N = off +(.ipc.open "127.0.0.1:19974" (dict [keepalive] [30000])) !- io +(.ipc.open "127.0.0.1:19974" (dict [keepalive] [0N])) !- io +(.ipc.open "127.0.0.1:19974" (dict [timeout keepalive] [200 5000])) !- io ;; an empty dict is valid — everything defaults (.ipc.open "127.0.0.1:19974" (dict [] [])) !- io @@ -32,6 +38,11 @@ (.ipc.open "127.0.0.1:19974" (dict [compress] ["lots"])) !- type (.ipc.open "127.0.0.1:19974" (dict [compress] [-5])) !- domain (.ipc.open "127.0.0.1:19974" (dict [timeout] [-1])) !- domain +;; 0 could mean "off" or "immediately"; neither is guessed +(.ipc.open "127.0.0.1:19974" (dict [keepalive] [0])) !- domain +(.ipc.open "127.0.0.1:19974" (dict [keepalive] [-1])) !- domain +(.ipc.open "127.0.0.1:19974" (dict [keepalive] ["1m"])) !- type +(.ipc.open "127.0.0.1:19974" (dict [keepalve] [1000])) !- domain ;; a second argument that is neither an integer nor a dict (.ipc.open "127.0.0.1:19974" "soon") !- type diff --git a/test/rfl/system/ipc_send_timeout.rfl b/test/rfl/system/ipc_send_timeout.rfl new file mode 100644 index 000000000..986931e5a --- /dev/null +++ b/test/rfl/system/ipc_send_timeout.rfl @@ -0,0 +1,22 @@ +;; ipc_send_timeout.rfl — `.ipc.send`'s optional third argument (#589). +;; +;; `(.ipc.send h msg ms)` bounds the round trip; on expiry the connection +;; is closed and `io` is returned. 0N means no deadline. 0 is refused: +;; it could mean "none" or "already expired". +;; +;; 999999 names no connection, so a well-formed call reaches handle +;; resolution and fails with `io`; a malformed one is rejected before +;; that, with `type`, `domain` or `rank`. The C suite (ipc/send_deadline) +;; covers expiry against a live socket. + +(.ipc.send 999999 42) !- io +(.ipc.send 999999 42 100) !- io +(.ipc.send 999999 42 0N) !- io + +(.ipc.send 999999 42 0) !- domain +(.ipc.send 999999 42 -5) !- domain +(.ipc.send 999999 42 "soon") !- type +(.ipc.send 999999 42 1.5) !- type + +(.ipc.send 999999) !- rank +(.ipc.send 999999 42 100 1) !- rank diff --git a/test/rfl/system/load_home.rfl b/test/rfl/system/load_home.rfl index febcad8e4..3365ee73f 100644 --- a/test/rfl/system/load_home.rfl +++ b/test/rfl/system/load_home.rfl @@ -24,7 +24,8 @@ (.sys.exec "cd /tmp/rfl_lh/proj && RAYFORCE_HOME=/tmp/rfl_lh/home/ $OLDPWD/rayforce main.rfl &1 | grep -q '^/tmp/rfl_lh/home/lib/a.rfl|'") -- 0 ;; without a home the same script fails, naming only the working-directory path -(.sys.exec "cd /tmp/rfl_lh/proj && $OLDPWD/rayforce main.rfl &1 | grep -q 'error: io: load \"lib/a.rfl\": No such file or directory$'") -- 0 +;; explicitly unset the home so this case cannot inherit the runner's setting +(.sys.exec "unset RAYFORCE_HOME; cd /tmp/rfl_lh/proj && $OLDPWD/rayforce main.rfl &1 | grep -q 'error: io: load \"lib/a.rfl\": No such file or directory$'") -- 0 ;; missing in both places: both attempts are named (.sys.exec "printf '(load \"lib/zz.rfl\")\n' > /tmp/rfl_lh/proj/miss.rfl; cd /tmp/rfl_lh/proj && RAYFORCE_HOME=/tmp/rfl_lh/home $OLDPWD/rayforce miss.rfl &1 | grep -q 'error: io: load \"lib/zz.rfl\": No such file or directory (also tried \"/tmp/rfl_lh/home/lib/zz.rfl\")'") -- 0 diff --git a/test/rfl/system/parquet.rfl b/test/rfl/system/parquet.rfl new file mode 100644 index 000000000..722ca6e26 --- /dev/null +++ b/test/rfl/system/parquet.rfl @@ -0,0 +1,211 @@ +;; @requires: posix +;; Native Parquet frontend, query execution, projected streaming, and ranges. +(set pq (.parquet.read "test/data/parquet/flat-1-v2.parquet")) +(count pq) -- 18 +(sum (at pq 'x)) -- 74 +(sum (at pq 'wide)) -- 1872 +(min (at pq 'day)) -- 2000.01.01 +(count (select {from: pq where: (> x 4)})) -- 8 +(count (.parquet.read [name] "test/data/parquet/flat-0-v1.parquet")) -- 18 +(count (.parquet.meta "test/data/parquet/flat-1-v1.parquet")) -- 14 +(.parquet.each [x] "test/data/parquet/flat-1-v2.parquet" (fn [batch] (sum (at batch 'x)))) -- 18 +(set pq-r (.parquet.read {columns: [name] range: {column: x min: 4 max: 7}} "test/data/parquet/flat-1-v2.parquet")) +(count pq-r) -- 6 +(count (cols pq-r)) -- 1 +(count (.parquet.read {range: {column: x min: 40 max: 70}} "test/data/parquet/flat-1-v2.parquet")) -- 0 +(.parquet.each {columns: [name] range: {column: x min: 4 max: 7}} "test/data/parquet/flat-1-v2.parquet" (fn [batch] (count batch))) -- 6 +(.parquet.read [missing] "test/data/parquet/flat-1-v1.parquet") !- parquet +(.parquet.read [x x] "test/data/parquet/flat-1-v1.parquet") !- parquet +(.parquet.read {range: {column: name min: 1 max: 2}} "test/data/parquet/flat-1-v1.parquet") !- parquet +(.parquet.read "missing-rayforce.parquet") !- io +(.parquet.read 1) !- type +(.parquet.read) !- arity +(.parquet.each "test/data/parquet/flat-1-v1.parquet" (fn [batch] (at batch 'missing))) !- domain +;; Reopenable source: whole-query grouping, sorting, repeated scans and pushdown. +(set pqs (.parquet.scan "test/data/parquet/flat-1-v2.parquet")) +(count (select {from: pqs})) -- 18 +(sum (at (select {from: pqs x: x}) 'x)) -- 74 +(count (cols (select {from: pqs name: name where: (and (>= x 4) (<= x 7))}))) -- 1 +(count (select {from: pqs name: name where: (and (>= x 4) (<= x 7))})) -- 6 +(sum (at (select {from: pqs s: (sum wide)}) 's)) -- 1872 +(sum (at (select {from: pqs by: x n: (count wide)}) 'n)) -- 18 +(sum (at (select {from: pqs x: x desc: x take: 3}) 'x)) -- 26 +(count (select {from: pqs x: x where: (< x 4)})) -- 8 +(count (select {from: pqs x: x where: (> 4 x)})) -- 8 +(count (select {from: pqs x: x where: (or (== x 1) (== x 9))})) -- 4 +(== (count (select {from: pqs x: x where: (> x (avg x))})) (count (select {from: pq x: x where: (> x (avg x))}))) -- true +(count (select {from: pqs x: x where: (and (> x 7) (< x 3))})) -- 0 +(count (select {from: pqs x: x where: (== x 4)})) -- 2 +(count (select {from: (.parquet.scan "test/data/parquet/empty.parquet") x: x})) -- 0 +(select {from: (.parquet.scan "missing-rayforce.parquet") x: x}) !- io + +;; Unknown functions may capture columns; disable projection for those calls. +(set pq-capture (fn [unused] wide)) +(sum (at (select {from: pqs value: (pq-capture x)}) 'value)) -- 1872 +;; Literal-only output still preserves source cardinality. +(count (select {from: pqs value: 1})) -- 18 +(count (select {from: pqs by: [x wide] n: (count wide)})) -- 9 + +;; Corrupt unreferenced string payload proves inferred projection avoids decoding it. +(sum (at (select {from: (.parquet.scan "test/data/parquet/projection.parquet") x: x}) 'x)) -- 37 +(.parquet.read "test/data/parquet/projection.parquet") !- parquet +;; Stream global integer aggregates across batches using native accumulators. +(set pq-big (.parquet.scan "test/data/parquet/parallel.parquet")) +(sum (at (select {from: pq-big n: (count x)}) 'n)) -- 70003 +(sum (at (select {from: pq-big s: (sum x)}) 's)) -- 2450175003 +(sum (at (select {from: pq-big a: (avg x)}) 'a)) -- 35001.0 +(sum (at (select {from: pq-big lo: (min y)}) 'lo)) -- 0 +(sum (at (select {from: pq-big n: (count x) where: (and (>= x 65530) (<= x 65540))}) 'n)) -- 11 +(sum (at (select {from: pq-big s: (sum x) where: (and (>= x 65530) (<= x 65540))}) 's)) -- 720885 +(sum (at (select {from: pq-big a: (avg x) where: (and (>= x 65530) (<= x 65540))}) 'a)) -- 65535.0 +;; Multiple predicate columns must retain the residual predicate. +(sum (at (select {from: pqs n: (count wide) where: (and (>= x 4) (< wide 105))}) 'n)) -- 4 +(sum (at (select {from: pqs n: (count x) where: (> x 100)}) 'n)) -- 0 +(sum (at (select {from: (.parquet.scan "test/data/parquet/empty.parquet") n: (count x)}) 'n)) -- 0 +(sum (at (select {from: (.parquet.scan "test/data/parquet/all-null.parquet") s: (sum x)}) 's)) -- 0 +(all (== (as 'STR (at (select {from: pqs a: (avg x)}) 'a)) (as 'STR (at (select {from: pq a: (avg x)}) 'a)))) -- true +;; A footer-only count never touches the deliberately corrupted payload. +(sum (at (select {from: (.parquet.scan "test/data/parquet/projection.parquet") n: (count name)}) 'n)) -- 9 +;; Streaming residual comparisons preserve the empty global aggregate row. +(sum (at (select {from: pqs n: (count wide) where: (and (>= x 4) (> wide 1000))}) 'n)) -- 0 + +;; Independent row groups preserve order, nulls, pruning and partial-state merges. +(set pq-groups (.parquet.scan "test/data/parquet/row-groups.parquet")) +(sum (at (select {from: pq-groups s: (sum x)}) 's)) -- 968374036 +(sum (at (select {from: pq-groups a: (avg x)}) 'a)) -- 22004.0 +(sum (at (select {from: pq-groups s: (sum x) where: (and (>= x 4999) (<= x 39012) (< y 100000))}) 's)) -- 558839820 +(sum (at (select {from: pq-groups n: (count y) where: (and (>= x 4999) (<= x 39012) (< y 100000))}) 'n)) -- 28771 +(sum (at (select {from: pq-groups s: (sum x) where: (and (>= x 4999) (< y 0))}) 's)) -- 73539505 +(set pq-groups-eager (.parquet.read "test/data/parquet/row-groups.parquet")) +;; Worker readers must inherit null acceptance for their primary predicate. +(== (count (select {from: pq-groups where: (< y 0)})) (count (select {from: pq-groups-eager where: (< y 0)}))) -- true +(== (sum (at (select {from: pq-groups s: (sum x) where: (< y 0)}) 's)) (sum (at (select {from: pq-groups-eager s: (sum x) where: (< y 0)}) 's))) -- true +(count (.parquet.read {columns: [s] range: {column: x min: 4999 max: 39012}} "test/data/parquet/row-groups.parquet")) -- 34014 +;; Upper-bound predicates retain nulls through page/group pruning and aggregates. +(set pq-null (.parquet.read "test/data/parquet/indexed-null.parquet")) +(set pqs-null (.parquet.scan "test/data/parquet/indexed-null.parquet")) +(== (count (select {from: pqs-null where: (< x 5)})) (count (select {from: pq-null where: (< x 5)}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (< x 5)}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (< x 5)}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (< x 5)}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (< x 5)}) 's))) -- true +(== (count (select {from: pqs-null where: (<= x 5)})) (count (select {from: pq-null where: (<= x 5)}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (<= x 5)}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (<= x 5)}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (<= x 5)}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (<= x 5)}) 's))) -- true +(== (count (select {from: pqs-null where: (> 5 x)})) (count (select {from: pq-null where: (> 5 x)}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (> 5 x)}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (> 5 x)}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (> 5 x)}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (> 5 x)}) 's))) -- true +(== (count (select {from: pqs-null where: (>= 5 x)})) (count (select {from: pq-null where: (>= 5 x)}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (>= 5 x)}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (>= 5 x)}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (>= 5 x)}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (>= 5 x)}) 's))) -- true +(== (count (select {from: pqs-null where: (< x 0)})) (count (select {from: pq-null where: (< x 0)}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (< x 0)}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (< x 0)}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (< x 0)}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (< x 0)}) 's))) -- true +(== (count (select {from: pqs-null where: (<= x -9223372036854775807)})) (count (select {from: pq-null where: (<= x -9223372036854775807)}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (<= x -9223372036854775807)}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (<= x -9223372036854775807)}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (<= x -9223372036854775807)}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (<= x -9223372036854775807)}) 's))) -- true +(== (count (select {from: pqs-null where: (and (< x 5) (<= x 4))})) (count (select {from: pq-null where: (and (< x 5) (<= x 4))}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (and (< x 5) (<= x 4))}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (and (< x 5) (<= x 4))}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (and (< x 5) (<= x 4))}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (and (< x 5) (<= x 4))}) 's))) -- true +(== (count (select {from: pqs-null where: (and (>= x 4) (< x 5))})) (count (select {from: pq-null where: (and (>= x 4) (< x 5))}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (and (>= x 4) (< x 5))}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (and (>= x 4) (< x 5))}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (and (>= x 4) (< x 5))}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (and (>= x 4) (< x 5))}) 's))) -- true +(== (count (select {from: pqs-null where: (and (>= row 0) (< x 5))})) (count (select {from: pq-null where: (and (>= row 0) (< x 5))}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (and (>= row 0) (< x 5))}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (and (>= row 0) (< x 5))}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (and (>= row 0) (< x 5))}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (and (>= row 0) (< x 5))}) 's))) -- true +(== (count (select {from: pqs-null where: (and (< x 5) (>= row 0))})) (count (select {from: pq-null where: (and (< x 5) (>= row 0))}))) -- true +(== (sum (at (select {from: pqs-null n: (count row) where: (and (< x 5) (>= row 0))}) 'n)) (sum (at (select {from: pq-null n: (count row) where: (and (< x 5) (>= row 0))}) 'n))) -- true +(== (sum (at (select {from: pqs-null s: (sum row) where: (and (< x 5) (>= row 0))}) 's)) (sum (at (select {from: pq-null s: (sum row) where: (and (< x 5) (>= row 0))}) 's))) -- true +(count (select {from: pqs-null where: (< x 5)})) -- 7 +(sum (at (select {from: pqs-null s: (sum row) where: (< x 0)}) 's)) -- 24 +(count (select {from: (.parquet.scan "test/data/parquet/all-null.parquet") where: (< x 0)})) -- 9 +(sum (at (select {from: (.parquet.scan "test/data/parquet/all-null.parquet") n: (count x) where: (<= x 0)}) 'n)) -- 9 +;; Required source values can map to native null sentinels, too. +(count (select {from: (.parquet.scan "test/data/parquet/sentinels.parquet") where: (< i -2147483648)})) -- 1 +(sum (at (select {from: (.parquet.scan "test/data/parquet/sentinels.parquet") n: (count i) where: (< l -9223372036854775807)}) 'n)) -- 1 + +;; Native conversion entry points validate schemas and argument shapes. +(.parquet.splayed) !- arity +(.parquet.splayed 1 "unused") !- type +(.parquet.splayed [I32] "test/data/parquet/unix.parquet" "unused") !- parquet +(.parquet.splayed [DATE TIMESTAMP SYM] "test/data/parquet/unix.parquet" "unused") !- parquet +(.parquet.parted [DATE TIMESTAMP SYM] "test/data/parquet/unix.parquet" "unused" 'hits) !- parquet + +;; Explicit types use private dictionaries that survive reader closure. +(set pq-typed (.parquet.read {types: [UNIX_DATE UNIX_SECONDS SYM]} "test/data/parquet/unix.parquet")) +(type (at pq-typed 's)) -- 'SYM +(min (at pq-typed 'day)) -- 2000.01.01 +(min (at pq-typed 'ts)) -- 2000.01.01D00:00:00.000000000 +(all (== (as 'STR (at pq-typed 's)) (at (.parquet.read "test/data/parquet/unix.parquet") 's))) -- true +(set pq-typed-source (.parquet.scan {types: [I32 I64 SYM]} "test/data/parquet/row-groups.parquet")) +(set pq-typed-result (select {from: pq-typed-source s: s where: (and (>= x 4999) (<= x 39012))})) +(count pq-typed-result) -- 34014 +(type (at pq-typed-result 's)) -- 'SYM +(all (== (as 'STR (at pq-typed-result 's)) (at (.parquet.read {columns: [s] range: {column: x min: 4999 max: 39012}} "test/data/parquet/row-groups.parquet") 's))) -- true +(sum (at (select {from: pq-typed-source n: (count s) where: (and (>= x 4999) (< y 100000))}) 'n)) -- 29156 +(count (select {from: pq-typed-source by: s n: (count x)})) -- 44009 +(type (at (.parquet.read {types: [I32 I64 SYM] columns: [s] range: {column: x min: 10 max: 19}} "test/data/parquet/row-groups.parquet") 's)) -- 'SYM +(.parquet.read {types: [I32]} "test/data/parquet/unix.parquet") !- parquet +(.parquet.scan {columns: [s]} "test/data/parquet/unix.parquet") !- parquet +(.parquet.scan) !- arity +(.parquet.scan 1) !- type +(select {from: (.parquet.scan {types: [DATE TIMESTAMP SYM]} "test/data/parquet/unix.parquet")}) !- parquet + +;; Transparent expressions retain projection, and inclusive ranges retain null rules. +(sum (at (select {from: (.parquet.scan "test/data/parquet/projection.parquet") x: (let tmp (div x 1) (% tmp 100))}) 'x)) -- 37 +(sum (at (select {from: (.parquet.scan "test/data/parquet/projection.parquet") x: (if (> x 3) x 0)}) 'x)) -- 33 +(count (select {from: pqs where: (within x [4 7])})) -- 6 +(sum (at (select {from: pqs n: (count wide) where: (and (within x [4 7]) (< wide 105))}) 'n)) -- 4 +(count (select {from: pqs where: (within x [7 4])})) -- 0 +;; LIKE is applied before materialization, including empty/null and complex patterns. +(count (select {from: pqs where: (like name "*a*")})) -- 12 +(count (select {from: pqs where: (like name "[ab]*")})) -- 8 +(count (select {from: pqs where: (like name "")})) -- 4 +(count (select {from: pqs where: (like name "*")})) -- 18 +(count (select {from: pqs where: (like name "no match")})) -- 0 +(count (select {from: pqs n: (count name) where: (like name "no match")})) -- 1 +(sum (at (select {from: pqs n: (count name) where: (like name "no match")}) 'n)) -- 0 +(sum (at (select {from: pqs s: (sum wide) where: (like name "no match")}) 's)) -- 0 +(sum (at (select {from: pqs n: (count name) where: (like name "*a*")}) 'n)) -- 12 +(sum (at (select {from: pq-typed-source n: (count s) where: (like s "no match")}) 'n)) -- 0 +(count (select {from: pq-typed-source where: (like s "*row 10*")})) -- 1111 +(all (== (as 'STR (at (select {from: pq-typed-source s: s where: (like s "*row 10*")}) 's)) (at (select {from: (.parquet.read "test/data/parquet/row-groups.parquet") s: s where: (like s "*row 10*")}) 's))) -- true +;; A user lambda replacing a familiar builtin can capture other columns. +(set pq-original-lower lower) +(set lower (fn [unused] wide)) +(sum (at (select {from: pqs result: (lower x)}) 'result)) -- 1872 +(set lower pq-original-lower) + +;; Strict mode rejects actual values that would become native nulls; true nulls survive. +(count (.parquet.read {strict: true} "test/data/parquet/strict-good.parquet")) -- 3 +(count (.parquet.read {types: [I32 SYM] strict: true} "test/data/parquet/strict-good.parquet")) -- 3 +(.parquet.read {strict: 1} "test/data/parquet/strict-good.parquet") !- parquet +(.parquet.read {columns: [i] strict: true} "test/data/parquet/strict-collisions-0.parquet") !- parquet +(.parquet.read {columns: [j] strict: true} "test/data/parquet/strict-collisions-0.parquet") !- parquet +(.parquet.read {columns: [f] strict: true} "test/data/parquet/strict-collisions-0.parquet") !- parquet +(.parquet.read {columns: [s] strict: true} "test/data/parquet/strict-collisions-0.parquet") !- parquet +(.parquet.read {columns: [i] strict: true} "test/data/parquet/strict-collisions-1.parquet") !- parquet +(.parquet.read {columns: [j] strict: true} "test/data/parquet/strict-collisions-1.parquet") !- parquet +(.parquet.read {columns: [f] strict: true} "test/data/parquet/strict-collisions-1.parquet") !- parquet +(.parquet.read {columns: [s] strict: true types: [I32 I64 F64 SYM]} "test/data/parquet/strict-collisions-1.parquet") !- parquet +(min (at (.parquet.read {columns: [i] strict: true types: [I64 I64 F64 STR]} "test/data/parquet/strict-collisions-0.parquet") 'i)) -- -2147483648 +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-0.parquet") !- parquet +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-1.parquet") !- parquet +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-2.parquet") !- parquet +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-3.parquet") !- parquet +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-4.parquet") !- parquet +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-5.parquet") !- parquet +(.parquet.read {strict: true} "test/data/parquet/strict-utf8-6.parquet") !- parquet +(.parquet.read {strict: true types: [SYM]} "test/data/parquet/strict-utf8-7.parquet") !- parquet +(select {from: (.parquet.scan {strict: true} "test/data/parquet/strict-collisions-0.parquet") i: i}) !- parquet +(.parquet.parted {rows: 0} "test/data/parquet/flat-1-v2.parquet" "unused" 'hits) !- parquet +(.parquet.parted {rows: 1048577} "test/data/parquet/flat-1-v2.parquet" "unused" 'hits) !- parquet +(.sys.exec "rm -rf /tmp/rfl_parquet_rows /tmp/rfl_parquet_strict /tmp/rfl_parquet_strict.parquet-partial") +(.parquet.parted {rows: 3} "test/data/parquet/flat-1-v2.parquet" "/tmp/rfl_parquet_rows" 'hits) -- 18 +(count (.db.parted.get "/tmp/rfl_parquet_rows" 'hits)) -- 18 +(count (.db.splayed.get "/tmp/rfl_parquet_rows/5/hits")) -- 3 +(.parquet.parted {strict: true} "test/data/parquet/strict-collisions-0.parquet" "/tmp/rfl_parquet_strict" 'hits) !- parquet +(.db.parted.get "/tmp/rfl_parquet_strict" 'hits) !- io +(.sys.exec "rm -rf /tmp/rfl_parquet_rows /tmp/rfl_parquet_strict.parquet-partial") +(.parquet.parted {rows: 100000 strict: true} "test/data/parquet/parallel.parquet" "/tmp/rfl_parquet_rows" 'hits) -- 70003 +(count (.db.splayed.get "/tmp/rfl_parquet_rows/0/hits")) -- 70003 +(sum (at (.db.splayed.get "/tmp/rfl_parquet_rows/0/hits") 'x)) -- 2450175003 +(.sys.exec "rm -rf /tmp/rfl_parquet_rows") diff --git a/test/rfl/system/parquet_writer_shapes.rfl b/test/rfl/system/parquet_writer_shapes.rfl new file mode 100644 index 000000000..455e70f47 --- /dev/null +++ b/test/rfl/system/parquet_writer_shapes.rfl @@ -0,0 +1,70 @@ +;; @requires: posix +;; Parquet shapes common writers emit by default that the reader once +;; rejected (PR 657 review): RLE-encoded booleans (the v2 default), a +;; zero-row row group, and long strings past one 64 MiB batch pool. + +;; RLE booleans, v1 and v2 pages, with nulls: 40 rows, 4 null, 22 true +(set b1 (.parquet.read "test/data/parquet/bool-rle-v1.parquet")) +(set b2 (.parquet.read "test/data/parquet/bool-rle-v2.parquet")) +(count b1) -- 40 +(count (select {from: b1 where: (== b true)})) -- 22 +(count (select {from: b2 where: (== b true)})) -- 22 +(count (select {from: b2 where: (nil? b)})) -- 4 +;; nullable booleans decode to I16 (BOOL has no null) +(at (at b2 'b) 4) -- 0 +(at (at b2 'b) 39) -- 1 + +;; a zero-row group between two populated ones +(set eg (.parquet.read "test/data/parquet/empty-group.parquet")) +(count eg) -- 5 +(sum (at eg 'x)) -- 13 +(at (at eg 's) 3) -- "four" +(.sys.exec "rm -rf rf_test_pq_eg_parted") -- 0 +(.parquet.parted "test/data/parquet/empty-group.parquet" "rf_test_pq_eg_parted" 'e) -- 5 +(count (select {from: (.db.parted.get "rf_test_pq_eg_parted" 'e)})) -- 5 +(.sys.exec "rm -rf rf_test_pq_eg_parted") -- 0 + +;; 8000 rows x 9000-byte strings (~72 MB decoded): the reader splits the +;; row group into batches whose string pools stay near 64 MiB. +(.sys.exec "python3 test/data/parquet/generate.py --long-strings rf_test_pq_long.parquet") -- 0 +(set lg (.parquet.read "rf_test_pq_long.parquet")) +(count lg) -- 8000 +(sum (at lg 'id)) -- 31996000 +(sum (map count (at lg 'doc))) -- 72000000 +(set nb 0) +(.parquet.each "rf_test_pq_long.parquet" (fn [batch] (set nb (+ nb 1)))) -- 8000 +(> nb 1) -- true +(.sys.exec "rm -f rf_test_pq_long.parquet") -- 0 + +;; a destination with a trailing separator stages beside it, as +;; .csv.parted does, not inside it as "/.parquet-partial" +(.sys.exec "rm -rf rf_test_pq_slash rf_test_pq_slash.parquet-partial") -- 0 +(.parquet.splayed "test/data/parquet/empty-group.parquet" "rf_test_pq_slash/") -- 5 +(count (.db.splayed.get "rf_test_pq_slash")) -- 5 +(.sys.exec "test -e rf_test_pq_slash/.parquet-partial") -- 1 +;; a leftover staging directory blocks the destination (the error names it) +(.sys.exec "rm -rf rf_test_pq_slash && mkdir rf_test_pq_slash.parquet-partial") -- 0 +(.parquet.splayed "test/data/parquet/empty-group.parquet" "rf_test_pq_slash") !- parquet +(.sys.exec "rm -rf rf_test_pq_slash rf_test_pq_slash.parquet-partial") -- 0 + +;; ms timestamps outside the nanosecond range (a 9999-12-31 "end of time" +;; sentinel, a 1000-01-01 date) clamp to the nearest representable instant, +;; so comparisons keep their meaning: a 9999 validity end is not "expired". +;; Strict mode rejects them. +(set tr (.parquet.read "test/data/parquet/timestamp-range.parquet")) +(count tr) -- 4 +(count (select {from: tr where: (nil? ts)})) -- 0 +(count (select {from: tr where: (> ts 2100.01.01D00:00:00.000000000)})) -- 1 +(count (select {from: tr where: (< ts 1900.01.01D00:00:00.000000000)})) -- 1 +(.parquet.read {strict: true} "test/data/parquet/timestamp-range.parquet") !- parquet + +;; the same pool bound for dictionary pages: 10,000 rows repeating 20 +;; distinct 10 KB entries (~100 MB decoded). The chunk is small, but every +;; row copies an entry into the pool, so batches must be sized by the +;; longest entry (~6,700 rows), not left at the default 65,536. +(.sys.exec "python3 test/data/parquet/generate.py --dict-strings rf_test_pq_dict.parquet") -- 0 +(set nd 0) +(.parquet.each "rf_test_pq_dict.parquet" (fn [batch] (set nd (+ nd 1)))) -- 10000 +nd -- 2 +(count (distinct (at (.parquet.read "rf_test_pq_dict.parquet") 's))) -- 20 +(.sys.exec "rm -f rf_test_pq_dict.parquet") -- 0 diff --git a/test/rfl/system/part.rfl b/test/rfl/system/part.rfl index 0af053193..d6a3f808f 100644 --- a/test/rfl/system/part.rfl +++ b/test/rfl/system/part.rfl @@ -481,5 +481,86 @@ (.db.parted.get "/tmp/rfl_part_intovf/" 't) !- corrupt (.sys.exec "rm -rf /tmp/rfl_part_intord /tmp/rfl_part_intovf") +;; ────────────── partition column on no-match where: and under take: ────────────── +;; The result keeps the partition column whether or not a row matched, and +;; take: gathers it for the rows it keeps (an empty partition in between). +(.sys.exec "rm -rf /tmp/rfl_part_keep") +(.db.splayed.set "/tmp/rfl_part_keep/2024.01.01/t/" (table [ts v] (list (til 5) (til 5)))) +(.db.splayed.set "/tmp/rfl_part_keep/2024.01.02/t/" (table [ts v] (list (til 0) (til 0)))) +(.db.splayed.set "/tmp/rfl_part_keep/2024.01.03/t/" (table [ts v] (list (til 5) (+ 10 (til 5))))) +(set PK (.db.parted.get "/tmp/rfl_part_keep/" 't)) +(key (select {from: PK where: (> ts 100)})) -- [date ts v] +(type (at (select {from: PK where: (> ts 100)}) 'date)) -- 'DATE +(key (select {from: PK where: false})) -- [date ts v] +(key (select {v: v date: date from: PK where: (> ts 100)})) -- [v date] +(at (select {from: PK where: (> ts 2) take: 3}) 'date) -- [2024.01.01 2024.01.01 2024.01.03] +(at (select {from: PK where: (> ts 3) take: 5}) 'date) -- [2024.01.01 2024.01.03] +(at (select {d: date from: PK where: (== v 13) take: 1}) 'd) -- [2024.01.03] +(key (select {from: PK where: (> ts 2) take: 0})) -- [date ts v] +(count (select {from: PK where: (> ts 2) take: 0})) -- 0 +(.sys.exec "rm -rf /tmp/rfl_part_keep") +(.db.splayed.set "/tmp/rfl_part_keep/1/t/" (table [ts v] (list (til 5) (til 5)))) +(.db.splayed.set "/tmp/rfl_part_keep/7/t/" (table [ts v] (list (til 5) (til 5)))) +(set PKI (.db.parted.get "/tmp/rfl_part_keep/" 't)) +(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") + +;; ────────────── failed first write of a partition ────────────── +;; A first write writes in place; when it fails (here the symbol file sits +;; under a regular file) it removes the directories it created, so the +;; partition scan does not trip over a directory without a schema. +(.sys.exec "rm -rf /tmp/rfl_part_fail && mkdir -p /tmp/rfl_part_fail && touch /tmp/rfl_part_fail/file") +(set FW (table [a s] (list [1 2] ['x 'y]))) +(.db.splayed.set "/tmp/rfl_part_fail/db/1/t/" FW "/tmp/rfl_part_fail/db/.sym") +(.db.splayed.set "/tmp/rfl_part_fail/db/2/t/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(.sys.exec "test -e /tmp/rfl_part_fail/db/2") -- 1 +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +;; every directory the write created goes, the ones that were there stay +(.db.splayed.set "/tmp/rfl_part_fail/db/1/u/x/y/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(.sys.exec "test -e /tmp/rfl_part_fail/db/1/u") -- 1 +(.sys.exec "test -d /tmp/rfl_part_fail/db/1/t") -- 0 +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +;; a path that climbs out of the new directory with .. names one that was +;; there: nothing of it is removed +(.db.splayed.set "/tmp/rfl_part_fail/new/../db/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +(.sys.exec "test -e /tmp/rfl_part_fail/db/.sym") -- 0 +;; a failed rewrite of a published table keeps the table +(.db.splayed.set "/tmp/rfl_part_fail/db/1/t/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +;; a table directory that was there before the write is removed too when +;; a failed first write leaves nothing but what it produced behind: one an +;; operator pre-made, or one a killed first write left with its lock file +(.sys.exec "mkdir -p /tmp/rfl_part_fail/db/1/u") +(.db.splayed.set "/tmp/rfl_part_fail/db/1/u/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(.sys.exec "test -e /tmp/rfl_part_fail/db/1/u") -- 1 +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +(.sys.exec "mkdir -p /tmp/rfl_part_fail/db/1/u && touch /tmp/rfl_part_fail/db/1/u/.write.lock") +(.db.splayed.set "/tmp/rfl_part_fail/db/1/u/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(.sys.exec "test -e /tmp/rfl_part_fail/db/1/u") -- 1 +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +;; a file that was there before the write and that the write did not reach +;; is not the writer's to remove: a directory without a schema is not +;; always a dead table (the database root has none either) +(.sys.exec "mkdir -p /tmp/rfl_part_fail/db/1/u && touch /tmp/rfl_part_fail/db/1/u/.write.lock /tmp/rfl_part_fail/db/1/u/a") +(.db.splayed.set "/tmp/rfl_part_fail/db/1/u/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(.sys.exec "test -e /tmp/rfl_part_fail/db/1/u/a") -- 0 +(.sys.exec "rm -rf /tmp/rfl_part_fail/db/1/u") +;; a retry after a kill that succeeds publishes over the leftovers +(.sys.exec "mkdir -p /tmp/rfl_part_fail/db/1/u && touch /tmp/rfl_part_fail/db/1/u/.write.lock /tmp/rfl_part_fail/db/1/u/zz") +(.db.splayed.set "/tmp/rfl_part_fail/db/1/u/" FW "/tmp/rfl_part_fail/db/.sym") +(.sys.exec "test -e /tmp/rfl_part_fail/db/1/u/zz") -- 1 +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 'u)) -- 2 +;; only the table directory goes: a partition directory that was there +;; before the write stays, and stays an empty partition +(.sys.exec "mkdir -p /tmp/rfl_part_fail/db/2/t") +(.db.splayed.set "/tmp/rfl_part_fail/db/2/t/" FW "/tmp/rfl_part_fail/file/.sym") !- io +(.sys.exec "test -e /tmp/rfl_part_fail/db/2/t") -- 1 +(.sys.exec "test -d /tmp/rfl_part_fail/db/2") -- 0 +(.sys.exec "rmdir /tmp/rfl_part_fail/db/2") +(count (.db.parted.get "/tmp/rfl_part_fail/db/" 't)) -- 2 +(.sys.exec "rm -rf /tmp/rfl_part_fail") + ;; ────────────── teardown ────────────── (.sys.exec "rm -rf /tmp/rfl_part_date /tmp/rfl_part_int /tmp/rfl_part_sym /tmp/rfl_part_single /tmp/rfl_part_empty /tmp/rfl_part_missing /tmp/rfl_part_three /tmp/rfl_part_cd /tmp/rfl_part_cd_sym /tmp/rfl_part_minute /tmp/rfl_part_like /tmp/rfl_part_mc /tmp/rfl_part_mb") diff --git a/test/rfl/system/reserved_namespace.rfl b/test/rfl/system/reserved_namespace.rfl index 69a451442..4a881d429 100644 --- a/test/rfl/system/reserved_namespace.rfl +++ b/test/rfl/system/reserved_namespace.rfl @@ -10,7 +10,7 @@ (.sys.gc) -- 0 (.sys.gc 0) !- arity (count (.sys.info)) -- 5 -(count (.sys.mem)) -- 16 +(count (.sys.mem)) -- 18 (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/system_branch_cov2.rfl b/test/rfl/system/system_branch_cov2.rfl index eaf7ebdde..bc867d819 100644 --- a/test/rfl/system/system_branch_cov2.rfl +++ b/test/rfl/system/system_branch_cov2.rfl @@ -107,7 +107,7 @@ ;; ray_memstat_fn (.sys.mem) (lines 703-728) ;; ══════════════════════════════════════════════════════════════════════ (type (.sys.mem)) -- 'DICT -(count (.sys.mem)) -- 16 +(count (.sys.mem)) -- 18 (type (value (.sys.mem))) -- 'LIST ;; ══════════════════════════════════════════════════════════════════════ diff --git a/test/rfl/temporal/dag_extract_trunc.rfl b/test/rfl/temporal/dag_extract_trunc.rfl index cf7e559c6..e32860bfa 100644 --- a/test/rfl/temporal/dag_extract_trunc.rfl +++ b/test/rfl/temporal/dag_extract_trunc.rfl @@ -243,3 +243,14 @@ (at (at (select {y: ts.year from: TyMHn}) 'y) 1) -- 0Np (at (at (select {m: ts.month from: TyMHn}) 'm) 1) -- 0Np (at (at (select {h: ts.hour from: TyMHn}) 'h) 1) -- 0Np + +;; A date or timestamp literal reaches the compiled extract/truncate as an +;; atom, whose len field aliases its value: (year 2020.01.01) became a vector +;; of 7305 rows (the days since 2000.01.01), and an update with it turned a +;; 4-row table into a 7305-row one. +(set TyL (table [x] (list (til 4)))) +(at (update {y: (year 2020.01.01) from: TyL}) 'y) -- [2020 2020 2020 2020] +(count (update {x: (if true (year 2020.01.01) x) from: TyL})) -- 4 +(at (update {x: (if true (year 2020.01.01) x) from: TyL}) 'x) -- [2020 2020 2020 2020] +(at (select {m: (month 2020.03.15) y: x from: TyL}) 'm) -- [3 3 3 3] +(at (select {d: (day 2020.03.15) y: x from: TyL}) 'd) -- [15 15 15 15] diff --git a/test/test_agg_contract.c b/test/test_agg_contract.c index 3f61880c3..134b1555e 100644 --- a/test/test_agg_contract.c +++ b/test/test_agg_contract.c @@ -21,10 +21,12 @@ static void contract_setup(void) { contract_runtime = ray_runtime_create(0, NULL); contract_cores = ray_pool_total_workers(ray_pool_get()); ray_agg_engine_v2 = true; + ray_agg_first_n = true; agg_route_reset(); } static void contract_teardown(void) { ray_agg_engine_v2 = true; + ray_agg_first_n = true; ray_runtime_destroy(contract_runtime); if (ray_pool_total_workers(ray_pool_get()) != contract_cores) { ray_pool_destroy(); @@ -288,7 +290,13 @@ static test_result_t test_derived_key_per_symbol_route(void) { "(set s (as 'SYMBOL (map (fn [k] (format \"h%.x\" (% k 16))) i))) " "(set v (as 'F64 (% i 7))) " "(set T (table [s v] (list s v))) " - "(set T3 (take T 3000))"; + "(set T3 (take T 3000)) " + /* u: one row in four repeats 16 values, the rest are unique — a + * near-unique column as a whole (3/4 + distinct in the probe), a + * 16-value one over the rows `(== w 0)` selects */ + "(set j (til 16384)) " + "(set u (as 'SYMBOL (map (fn [k] (if (== 0 (% k 4)) (format \"h%.x\" (% k 16)) (format \"u%.y\" k))) j))) " + "(set TU (table [u w v] (list u (% j 4) (as 'F64 (% j 7)))))"; ray_t* r = ray_eval_str(setup); TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); ray_release(r); const struct { const char* q; uint64_t evals; } cases[] = { @@ -297,6 +305,12 @@ static test_result_t test_derived_key_per_symbol_route(void) { { "(select {from: T by: (differ s) c: (count v)})", 0 }, { "(select {from: T by: (if (> v 3) (substr s 0 2) s) c: (count v)})", 0 }, { "(select {from: T3 by: (substr s 0 2) c: (count v)})", 0 }, + /* the selection decides: near-unique over every row, repetitive + * over the selected rows */ + { "(select {from: TU by: (substr u 0 2) c: (count v)})", 0 }, + { "(select {from: TU by: (substr u 0 2) c: (count v) where: (== w 0)})", 1 }, + /* a selection below the row floor keeps the row path */ + { "(select {from: TU by: (substr u 0 2) c: (count v) where: (and (== w 0) (< v 2))})", 0 }, }; for (size_t c = 0; c < sizeof(cases)/sizeof(cases[0]); c++) { agg_route_reset(); @@ -325,10 +339,10 @@ static test_result_t test_group_routes_and_bool_outputs(void) { { 32, 0, AGG_ROUTE_V2_SERIAL_DENSE }, { 32, 1, AGG_ROUTE_V2_SERIAL_HASH }, { RAY_PARALLEL_THRESHOLD, 0, AGG_ROUTE_V2_DENSE }, - { RAY_PARALLEL_THRESHOLD, 1, AGG_ROUTE_V2_RADIX }, + { RAY_PARALLEL_THRESHOLD, 1, AGG_ROUTE_V2_TABLESTACK }, /* 4 sparse keys */ { RAY_PARALLEL_THRESHOLD, 2, AGG_ROUTE_V2_DENSE }, { RAY_PARALLEL_THRESHOLD, 3, AGG_ROUTE_V2_DENSE }, - { RAY_PARALLEL_THRESHOLD, 4, AGG_ROUTE_V2_RADIX }, + { RAY_PARALLEL_THRESHOLD, 4, AGG_ROUTE_V2_RADIX }, /* all-distinct sparse keys */ }; for (size_t c = 0; c < sizeof(cases)/sizeof(cases[0]); c++) { int64_t n = cases[c].n; @@ -1886,8 +1900,136 @@ static test_result_t test_dense_native_topn(void) { PASS(); } +/* Sparse int keys below the dense plan: the table-stack strategy takes a + * low-cardinality input (one table per task, no scatter) and declines an + * all-distinct one to radix at its sample gate. A skewed input whose + * sample looks low-cardinality but whose last task is all-distinct exercises + * the stack push and the adaptive switch to raw scatter inside that task. + * Every shape agrees with the radix scatter (knob off) and the serial fold + * on every integer aggregate, in the same first-seen order. */ +static test_result_t test_tablestack_routes(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_t* setup = ray_eval_str( + "(set tsk_i (til 262144)) " + "(set tsk_low (table [k v] (list (* (% (* tsk_i 7919) 10) 1000003) tsk_i))) " + "(set tsk_mid (table [k v] (list (* (% (* tsk_i 7919) 5000) 1000003) tsk_i))) " + "(set tsk_j (til 1048576)) " + "(set tsk_hi (table [k v] (list (* tsk_j 1000003) tsk_j))) " + /* rows [0, 983040): ten hot keys (75%) + 2000 middle keys (25%, rows + * 8m+6 and 8m+7 share key m mod 2000); rows [983040, 1048576): all + * distinct. The middle layer gives the gate's Chao1 the pairs it + * divides by, so the estimate stays in the thousands and the + * distinct tail (6% of the rows) is left to the tasks. */ + "(set tsk_h (til 983040)) " + "(set tsk_f (div (% tsk_h 8) 6)) " + "(set tsk_sk (table [k v] (list (raze (list " + "(+ (* (- 1 tsk_f) (* (% (* tsk_h 7919) 10) 1000003)) (* tsk_f (* (+ 10 (% (div tsk_h 8) 2000)) 1000003))) " + "(* (+ (til 65536) 2010) 1000003))) tsk_j)))" + /* phrases: q0 on 87% of the rows; the rest draw from 200000 phrases, + * 30% of them from a hot head of 1000 */ + "(set tsk_pv (as 'SYM (map (fn [x] (format \"q%\" x)) (til 200000)))) " + "(set tsk_pp (% (* tsk_j 7919) 200000)) " + "(set tsk_ph1 (div (% tsk_j 10) 7)) " + "(set tsk_pp (+ (* tsk_ph1 (% tsk_pp 1000)) (* (- 1 tsk_ph1) tsk_pp))) " + "(set tsk_ph (table [g p v] (list (% tsk_j 7) (at tsk_pv (* (div (% tsk_j 100) 87) (+ 1 (% tsk_pp 199999)))) tsk_j))) " + /* sorted key repeating in runs of five: 209716 groups */ + "(set tsk_run (table [k v] (list (* (div tsk_j 5) 1000003) tsk_j)))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + const struct { const char* q; int64_t groups; agg_route_t route; int scatter; int extra_tables; const char* cols[3]; } cases[] = { + { "(select {from:tsk_low by:k s:(sum v) c:(count v) mn:(min v) mx:(max v)})", 10, AGG_ROUTE_V2_TABLESTACK, 0, 0, { "k", "s", "mx" } }, + { "(select {from:tsk_low by:k s:(sum v) c:(count v) where:(< v 200000)})", 10, AGG_ROUTE_V2_TABLESTACK, 0, 0, { "k", "s", "c" } }, + { "(select {from:tsk_mid by:k s:(sum v) c:(count v)})", 5000, AGG_ROUTE_V2_TABLESTACK, 0, 0, { "k", "s", "c" } }, + { "(select {from:tsk_hi by:k s:(sum v) c:(count v)})", 1048576, AGG_ROUTE_V2_RADIX, 0, 0, { "k", "s", "c" } }, + /* Mostly-empty SYM phrase column: a sample of the whole table looks + * low-cardinality (87% one key), but the rows surviving the filter + * are near-unique — the gate samples the SELECTED rows and declines. */ + { "(select {from:tsk_ph by:[g p] c:(count v) where:(!= p 'q0)})", 73815, AGG_ROUTE_V2_RADIX, 0, 0, { "g", "p", "c" } }, + /* A key that repeats only in RUNS of consecutive rows (sorted + * input): a sample of neighbouring rows would see repeats and + * admit 200k groups; single scattered rows see none and decline. */ + { "(select {from:tsk_run by:k s:(sum v) c:(count v)})", 209716, AGG_ROUTE_V2_RADIX, 0, 0, { "k", "s", "c" } }, + { "(select {from:tsk_run by:k s:(sum v) c:(count v) where:(< (% v 10) 3)})", 104858, AGG_ROUTE_V2_RADIX, 0, 0, { "k", "s", "c" } }, + /* 8 tasks of 131072 rows; the last one holds ~2010 keys in its + * first half, grows to 32768 slots over the distinct second half, + * fills it at 28% distinct (push) and fills the pushed table with + * distinct keys only (switch). */ + { "(select {from:tsk_sk by:k s:(sum v) c:(count v)})", 67546, AGG_ROUTE_V2_TABLESTACK, 1, 1, { "k", "s", "c" } }, + /* selected (even rows reach five hot keys, every middle key and + * half the tail): the last task fills the 32768-slot table at 44% + * (push) and the remaining ~9200 keys fit the pushed table. */ + { "(select {from:tsk_sk by:k s:(sum v) c:(count v) where:(== (% v 2) 0)})", 34773, AGG_ROUTE_V2_TABLESTACK, 0, 1, { "k", "s", "c" } }, + }; + for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) { + ray_agg_tablestack = true; + agg_route_reset(); + ray_t* r = ray_eval_str(cases[c].q); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + agg_route_stats_t stats = agg_route_stats(); + TEST_ASSERT_FMT(stats.routes[cases[c].route] == 1, "case %zu route", c); + TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_LEGACY], 0); + TEST_ASSERT_EQ_I(ray_table_nrows(r), cases[c].groups); + if (cases[c].route == AGG_ROUTE_V2_TABLESTACK) { + TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_V2_RADIX], 0); + TEST_ASSERT_EQ_I(stats.ts_tasks, 8); + TEST_ASSERT_FMT(stats.ts_scatter_tasks == (uint32_t)cases[c].scatter, + "case %zu scatter tasks %u", c, stats.ts_scatter_tasks); + TEST_ASSERT_FMT(stats.ts_tables == stats.ts_tasks + (uint64_t)cases[c].extra_tables, + "case %zu tables %llu", c, (unsigned long long)stats.ts_tables); + } else { + TEST_ASSERT_EQ_I(stats.routes[AGG_ROUTE_V2_TABLESTACK], 0); + } + ray_env_set(ray_sym_intern("tsk_a", 5), r); ray_release(r); + ray_agg_tablestack = false; + agg_route_reset(); + r = ray_eval_str(cases[c].q); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(agg_route_stats().routes[AGG_ROUTE_V2_RADIX], 1); + ray_env_set(ray_sym_intern("tsk_b", 5), r); ray_release(r); + ray_agg_tablestack = true; + /* Same groups in the same (first-seen) order with the same values. */ + for (int k = 0; k < 3; k++) { + char expr[128]; + snprintf(expr, sizeof(expr), "(all (== (at tsk_a '%s) (at tsk_b '%s)))", + cases[c].cols[k], cases[c].cols[k]); + ray_t* same = ray_eval_str(expr); + TEST_ASSERT_NOT_NULL(same); TEST_ASSERT_FALSE(RAY_IS_ERR(same)); + TEST_ASSERT_FMT(same->u8, "case %zu column %d differs from radix", c, k); + ray_release(same); + } + } + /* Serial oracle: one core folds every row in order (serial hash path). */ + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(1), RAY_OK); + ray_t* ser = ray_eval_str("(select {from:tsk_sk by:k s:(sum v) c:(count v)})"); + TEST_ASSERT_NOT_NULL(ser); TEST_ASSERT_FALSE(RAY_IS_ERR(ser)); + ray_env_set(ray_sym_intern("tsk_s", 5), ser); ray_release(ser); + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(4), RAY_OK); + ray_t* par = ray_eval_str("(select {from:tsk_sk by:k s:(sum v) c:(count v)})"); + TEST_ASSERT_NOT_NULL(par); TEST_ASSERT_FALSE(RAY_IS_ERR(par)); + ray_env_set(ray_sym_intern("tsk_p", 5), par); ray_release(par); + const char* sorted[] = { + "(all (== (at (xasc tsk_s 'k) 'k) (at (xasc tsk_p 'k) 'k)))", + "(all (== (at (xasc tsk_s 'k) 's) (at (xasc tsk_p 'k) 's)))", + "(all (== (at (xasc tsk_s 'k) 'c) (at (xasc tsk_p 'k) 'c)))", + }; + for (int k = 0; k < 3; k++) { + ray_t* same = ray_eval_str(sorted[k]); + TEST_ASSERT_NOT_NULL(same); TEST_ASSERT_FALSE(RAY_IS_ERR(same)); + TEST_ASSERT_FMT(same->u8, "serial oracle column %d differs", k); + ray_release(same); + } + ray_release(ray_eval_str("(set tsk_i 0) (set tsk_j 0) (set tsk_h 0) (set tsk_f 0) (set tsk_low 0) (set tsk_mid 0) " + "(set tsk_hi 0) (set tsk_sk 0) (set tsk_a 0) (set tsk_b 0) (set tsk_s 0) (set tsk_p 0) " + "(set tsk_pv 0) (set tsk_pp 0) (set tsk_ph1 0) (set tsk_ph 0) (set tsk_run 0)")); + PASS(); +} + /* Unordered take: N on a bounded key stays on the dense task-local path and - * emits the first N groups in first-seen order. */ + * emits the first N groups in first-seen order. The first-N pre-pass would + * answer this shape before the dense route runs, so it is switched off for + * the route assertions and switched back on for the same answer. */ static test_result_t test_dense_unordered_take(void) { ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(8), RAY_OK); @@ -1895,26 +2037,125 @@ static test_result_t test_dense_unordered_take(void) { "(set ut_i (til 400000)) " "(set ut_t (table [k v] (list (as 'I32 (% (* ut_i 7919) 50000)) ut_i)))"); TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); - agg_route_reset(); - ray_t* r = ray_eval_str("(select {from:ut_t c:(count v) by:k take:10})"); - TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); - agg_route_stats_t stats = agg_route_stats(); - 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_EQ_I(ray_table_nrows(r), 10); - /* rows 0..9 start groups (i*7919) % 50000, emitted in that order */ - 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)); - for (int64_t i = 0; i < 10; i++) { - TEST_ASSERT_EQ_I(k[i], (int32_t)((i * 7919) % 50000)); - TEST_ASSERT_EQ_I(c[i], 8); + for (int pass = 0; pass < 2; pass++) { + ray_agg_first_n = pass == 1; + agg_route_reset(); + ray_t* r = ray_eval_str("(select {from:ut_t c:(count v) by:k take:10})"); + TEST_ASSERT_NOT_NULL(r); TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + agg_route_stats_t stats = agg_route_stats(); + if (pass == 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_EQ_I(stats.first_n, 0); + } else { + TEST_ASSERT_EQ_I(stats.first_n, 1); + } + TEST_ASSERT_EQ_I(ray_table_nrows(r), 10); + /* rows 0..9 start groups (i*7919) % 50000, emitted in that order */ + 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)); + for (int64_t i = 0; i < 10; i++) { + TEST_ASSERT_EQ_I(k[i], (int32_t)((i * 7919) % 50000)); + TEST_ASSERT_EQ_I(c[i], 8); + } + ray_release(r); } - ray_release(r); ray_release(ray_eval_str("(set ut_t 0) (set ut_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; + if (a->type != RAY_TABLE || b->type != RAY_TABLE) return false; + int64_t nc = ray_table_ncols(a), nr = ray_table_nrows(a); + if (nc != ray_table_ncols(b) || nr != ray_table_nrows(b)) return false; + for (int64_t c = 0; c < nc; c++) { + if (ray_table_col_name(a, c) != ray_table_col_name(b, c)) return false; + ray_t* x = ray_table_get_col_idx(a, c); + ray_t* y = ray_table_get_col_idx(b, c); + if (!x || !y || x->type != y->type || x->len != y->len) return false; + if (x->type == RAY_SYM) { + for (int64_t r = 0; r < nr; r++) { + ray_t* sx = ray_sym_vec_cell(x, r); + ray_t* sy = ray_sym_vec_cell(y, r); + if (!sx || !sy || ray_str_len(sx) != ray_str_len(sy) || + memcmp(ray_str_ptr(sx), ray_str_ptr(sy), ray_str_len(sx)) != 0) + return false; + } + } else if (memcmp(ray_data(x), ray_data(y), (size_t)nr * col_esz(x)) != 0) { + return false; + } + } + return true; +} + +/* Unordered take: N over a large input: the first-N pre-pass answers every + * admitted shape with exactly the table the full aggregation returns (same + * groups in the same first-seen order, every aggregate over all rows of its + * group), and leaves every other shape to the full aggregation. */ +static test_result_t test_first_n_take(void) { + ray_pool_destroy(); + TEST_ASSERT_EQ_I(ray_pool_init_total(8), RAY_OK); + ray_t* setup = ray_eval_str( + "(set fn_i (til 300000)) " + "(set fn_t (table [i u s w y d ts nu v g fl h] (list fn_i (% (* fn_i 7919) 50000) " + "(as 'SYM (as 'STR (% fn_i 5))) (as 'I32 (% fn_i 10)) " + "(as 'SYM (as 'STR (% (* fn_i 7919) 50000))) (as 'DATE (% (* fn_i 31) 20000)) " + "(as 'TIMESTAMP (* 1000 (% (* fn_i 13) 60000))) " + "(at (concat [0N] (til 4999)) (% (* fn_i 7919) 5000)) " + "(at (concat [0N] (til 1000)) (% fn_i 1001)) " + "(as 'SYM (as 'STR (% fn_i 97))) (* 0.5 (as 'F64 fn_i)) (div fn_i 2)))) " + "(set fn_small (take fn_t 1000))"); + TEST_ASSERT_NOT_NULL(setup); TEST_ASSERT_FALSE(RAY_IS_ERR(setup)); ray_release(setup); + static const struct { const char* q; uint64_t fast; } shapes[] = { + { "(select {from:fn_t by:[u s] c:(count u) take:10})", 1 }, + { "(select {from:fn_t by:u c:(count u) sv:(sum v) av:(avg v) mn:(min v) mx:(max v) take:10})", 1 }, + { "(select {from:fn_t by:y c:(count v) sv:(sum v) take:10})", 1 }, + { "(select {from:fn_t by:[u s w] c:(count u) sv:(sum v) take:10})", 1 }, + { "(select {from:fn_t where:(> v 500) by:[u s] c:(count u) sv:(sum v) take:10})", 1 }, + { "(select {from:fn_t by:[u s] c:(count u) mx:(max v) take:600})", 1 }, + { "(select {from:fn_t by:[i s] c:(count u) mx:(max v) take:1000})", 1 }, + /* 2000 matching rows in the first task: the matches spill to a second pass */ + { "(select {from:fn_t by:h c:(count v) sv:(sum v) take:1000})", 1 }, + { "(select {from:fn_t by:d c:(count v) mn:(min ts) mx:(max d) take:5})", 1 }, + { "(select {from:fn_t by:ts c:(count v) av:(avg w) take:7})", 1 }, + { "(select {from:fn_t by:nu c:(count v) sv:(sum v) take:10})", 1 }, + { "(select {from:fn_t by:[nu w] c:(count v) take:10})", 1 }, + { "(select {from:fn_t by:[u s] c:(count u) take:[3 5]})", 1 }, + { "(select {from:fn_t by:u c:(count fl) take:4})", 1 }, + /* left to the full aggregation */ + { "(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 }, + { "(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++) { + ray_agg_first_n = false; + ray_t* old = ray_eval_str(shapes[q].q); + ray_agg_first_n = true; + agg_route_reset(); + ray_t* got = ray_eval_str(shapes[q].q); + uint64_t ran = agg_route_stats().first_n; + TEST_ASSERT_FMT(old && !RAY_IS_ERR(old) && got && !RAY_IS_ERR(got), "%s: error", shapes[q].q); + TEST_ASSERT_FMT(ran == shapes[q].fast, "%s: first-N ran %d times, expected %d", + shapes[q].q, (int)ran, (int)shapes[q].fast); + TEST_ASSERT_FMT(first_n_same_table(old, got), "%s: result differs from the full aggregation", + shapes[q].q); + ray_release(old); ray_release(got); + } + ray_release(ray_eval_str("(set fn_t 0) (set fn_small 0) (set fn_i 0)")); + PASS(); +} + const test_entry_t agg_contract_entries[] = { { "agg_contract/empty_inference_errors", test_empty_inference_errors, contract_setup, contract_teardown }, { "agg_contract/nth_bounds", test_nth_bounds, contract_setup, contract_teardown }, @@ -1932,8 +2173,10 @@ const test_entry_t agg_contract_entries[] = { { "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 }, + { "agg_contract/tablestack_routes", test_tablestack_routes, contract_setup, contract_teardown }, { "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/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 3adb1a8ba..1ea8436fe 100644 --- a/test/test_agg_engine.c +++ b/test/test_agg_engine.c @@ -1973,6 +1973,189 @@ static test_result_t test_diff_group_determinism_workers(void) { return res; } +/* ══════════════════════════════════════════════════════════════════════ + * RADIX vs a SEQUENTIAL REFERENCE: values, keys and emit order, bit for bit. + * + * The radix route partitions every input chunk's rows into one payload array + * at exact offsets, so each partition holds its rows in ascending input + * order whatever the worker count. Group emit order is first-seen order and + * every aggregate — the F64 SUM included, whose bits depend on the order its + * terms are added — must equal a plain left-to-right pass over the rows. + * + * The reference below is that pass, computed here with no engine code: + * groups numbered in first-seen order, I64 sum/count/min and an F64 sum + * accumulated in row order. Each shape runs at several pool sizes, with and + * without a selection, and must take the radix route every time. + * ══════════════════════════════════════════════════════════════════════ */ + +/* Columns: a = sparse I64 (wide range → radix), b = sparse I32 with nulls, + * c = I16, s = SYM (W16), v = I64, f = F64. */ +static ray_t* rx_make_table(int64_t n) { + ray_t* a = ray_vec_new(RAY_I64, n); a->len = n; + ray_t* b = ray_vec_new(RAY_I32, n); b->len = n; + ray_t* c = ray_vec_new(RAY_I16, n); c->len = n; + ray_t* s = ray_sym_vec_new(RAY_SYM_W16, n); s->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; + int64_t syms[97]; + for (int j = 0; j < 97; j++) { + char buf[16]; int m = snprintf(buf, sizeof(buf), "rx%d", j); + syms[j] = ray_sym_intern(buf, (size_t)m); + } + int64_t groups = n / 3 > 1 ? n / 3 : 1; + for (int64_t i = 0; i < n; i++) { + int64_t g = (i * 7919) % groups; /* scrambled first sight */ + ((int64_t*)ray_data(a))[i] = g * 1000003 - 500000000; + ((int32_t*)ray_data(b))[i] = (int32_t)(((i * 31) % 40000) * 40009 - 800000000); + ((int16_t*)ray_data(c))[i] = (int16_t)(i % 7 - 3); + ray_write_sym(ray_data(s), i, (uint64_t)syms[(i * 13) % 97], RAY_SYM, s->attrs); + ((int64_t*)ray_data(v))[i] = (i * 7) % 1001 - 500; + ((double*)ray_data(f))[i] = (double)((i * 13) % 997) * 0.1 + 0.001; + } + for (int64_t i = 0; i < n; i += 9) ray_vec_set_null(b, i, true); + ray_t* tbl = ray_table_new(6); + tbl = ray_table_add_col(tbl, ray_sym_intern("a", 1), a); ray_release(a); + tbl = ray_table_add_col(tbl, ray_sym_intern("b", 1), b); ray_release(b); + tbl = ray_table_add_col(tbl, ray_sym_intern("c", 1), c); ray_release(c); + tbl = ray_table_add_col(tbl, ray_sym_intern("s", 1), s); ray_release(s); + tbl = ray_table_add_col(tbl, ray_sym_intern("v", 1), v); ray_release(v); + tbl = ray_table_add_col(tbl, ray_sym_intern("f", 1), f); ray_release(f); + return tbl; +} + +static ray_op_t* rx_group(ray_graph_t* g, const char* k0, const char* k1) { + ray_op_t* v = ray_scan(g, "v"); ray_op_t* f = ray_scan(g, "f"); + uint16_t ops[] = { OP_SUM, OP_COUNT, OP_MIN, OP_SUM }; + ray_op_t* ins[] = { v, v, v, f }; + ray_op_t* keys[2] = { ray_scan(g, k0), k1 ? ray_scan(g, k1) : NULL }; + return ray_group(g, keys, k1 ? 2 : 1, ops, ins, 4); +} +static ray_op_t* gb_rx_a(ray_graph_t* g) { return rx_group(g, "a", NULL); } +static ray_op_t* gb_rx_b(ray_graph_t* g) { return rx_group(g, "b", NULL); } +static ray_op_t* gb_rx_ca(ray_graph_t* g) { return rx_group(g, "c", "a"); } +static ray_op_t* gb_rx_sa(ray_graph_t* g) { return rx_group(g, "s", "a"); } + +typedef struct { int64_t k[2]; int64_t sum, cnt, min; double fsum; } rx_ref_t; + +/* Sequential reference over the rows passing `mask` (NULL = all), in row + * order. Returns the group count; *out receives groups in first-seen order. */ +static int64_t rx_reference(ray_t* tbl, const char* k0, const char* k1, + const uint8_t* mask, rx_ref_t** out) { + int64_t n = ray_table_nrows(tbl); + ray_t* c0 = ray_table_get_col(tbl, ray_sym_intern(k0, strlen(k0))); + ray_t* c1 = k1 ? ray_table_get_col(tbl, ray_sym_intern(k1, strlen(k1))) : NULL; + const int64_t* v = ray_data(ray_table_get_col(tbl, ray_sym_intern("v", 1))); + const double* f = ray_data(ray_table_get_col(tbl, ray_sym_intern("f", 1))); + int64_t cap = 1; + while (cap < 2 * n) cap <<= 1; + int64_t* slot = malloc((size_t)cap * sizeof(int64_t)); + rx_ref_t* g = malloc((size_t)(n > 0 ? n : 1) * sizeof(rx_ref_t)); + for (int64_t i = 0; i < cap; i++) slot[i] = -1; + int64_t ng = 0; + for (int64_t r = 0; r < n; r++) { + if (mask && !mask[r]) continue; + int64_t k[2] = { col_read_i64(c0, r), c1 ? col_read_i64(c1, r) : 0 }; + uint64_t h = (uint64_t)k[0] * 0x9E3779B97F4A7C15ULL ^ (uint64_t)k[1] * 0xC2B2AE3D27D4EB4FULL; + int64_t at = (int64_t)((h ^ (h >> 29)) & (uint64_t)(cap - 1)); + while (slot[at] >= 0 && (g[slot[at]].k[0] != k[0] || g[slot[at]].k[1] != k[1])) + at = (at + 1) & (cap - 1); + if (slot[at] < 0) { + slot[at] = ng; + g[ng] = (rx_ref_t){ { k[0], k[1] }, 0, 0, INT64_MAX, 0.0 }; + ng++; + } + rx_ref_t* e = &g[slot[at]]; + e->sum += v[r]; e->cnt++; + if (v[r] < e->min) e->min = v[r]; + e->fsum += f[r]; + } + free(slot); + *out = g; + return ng; +} + +static test_result_t rx_expect_reference(ray_t* out, const rx_ref_t* ref, + int64_t ng, int n_keys) { + TEST_ASSERT_FMT(out && !RAY_IS_ERR(out), "radix group failed"); + TEST_ASSERT_FMT(ray_table_nrows(out) == ng, "groups %lld != reference %lld", + (long long)ray_table_nrows(out), (long long)ng); + TEST_ASSERT_EQ_I(ray_table_ncols(out), n_keys + 4); + ray_t* sum = ray_table_get_col_idx(out, n_keys); + ray_t* cnt = ray_table_get_col_idx(out, n_keys + 1); + ray_t* mn = ray_table_get_col_idx(out, n_keys + 2); + ray_t* fs = ray_table_get_col_idx(out, n_keys + 3); + TEST_ASSERT_EQ_I(fs->type, RAY_F64); + for (int64_t r = 0; r < ng; r++) { + for (int k = 0; k < n_keys; k++) + TEST_ASSERT_FMT(col_read_i64(ray_table_get_col_idx(out, k), r) == ref[r].k[k], + "row %lld key %d out of first-seen order", (long long)r, k); + TEST_ASSERT_FMT(((int64_t*)ray_data(sum))[r] == ref[r].sum, "row %lld sum", (long long)r); + TEST_ASSERT_FMT(((int64_t*)ray_data(cnt))[r] == ref[r].cnt, "row %lld count", (long long)r); + TEST_ASSERT_FMT(((int64_t*)ray_data(mn))[r] == ref[r].min, "row %lld min", (long long)r); + double got = ((double*)ray_data(fs))[r]; + TEST_ASSERT_FMT(memcmp(&got, &ref[r].fsum, sizeof(double)) == 0, + "row %lld f64 sum %.17g != sequential %.17g", + (long long)r, got, ref[r].fsum); + } + PASS(); +} + +static test_result_t test_radix_matches_sequential_reference(void) { + ray_heap_init(); (void)ray_sym_init(); + ray_agg_engine_v2 = true; + static const struct { + const char* k0; const char* k1; group_builder_t build; + } shapes[] = { + { "a", NULL, gb_rx_a }, /* sparse I64 */ + { "b", NULL, gb_rx_b }, /* nullable I32 */ + { "c", "a", gb_rx_ca }, /* multi-key I16 + I64 */ + { "s", "a", gb_rx_sa }, /* SYM + I64 */ + }; + /* {pool size, rows}: the 16-way run has enough chunks × partitions to + * take the parallel prefix sum. */ + static const struct { uint32_t workers; int64_t rows; int shapes; } runs[] = { + { 2, 100000, 4 }, { 3, 100000, 4 }, { 8, 100000, 4 }, { 16, 1100000, 1 }, + }; + test_result_t res = (test_result_t){ TEST_PASS, NULL }; + for (size_t w = 0; w < sizeof(runs) / sizeof(runs[0]) && res.status == TEST_PASS; w++) { + ray_pool_destroy(); + ray_pool_init_total(runs[w].workers); + int64_t n = runs[w].rows; + ray_t* tbl = rx_make_table(n); + uint8_t* mask = malloc((size_t)n); + for (int64_t i = 0; i < n; i++) mask[i] = (i % 5) != 2 && (i / 4096) % 7 != 3; + for (int s = 0; s < runs[w].shapes && res.status == TEST_PASS; s++) { + for (int selected = 0; selected < 2 && res.status == TEST_PASS; selected++) { + rx_ref_t* ref = NULL; + int64_t ng = rx_reference(tbl, shapes[s].k0, shapes[s].k1, + selected ? mask : NULL, &ref); + agg_route_reset(); + ray_t* out; + if (selected) { + out = run_group_with_sel(tbl, shapes[s].build, mask, n, true); + } else { + ray_graph_t* g = ray_graph_new(tbl); + out = ray_execute(g, shapes[s].build(g)); + if (out && ray_is_lazy(out)) out = ray_lazy_materialize(out); + ray_graph_free(g); + } + if (agg_route_stats().routes[AGG_ROUTE_V2_RADIX] != 1) + res = (test_result_t){ TEST_FAIL, "shape did not take the radix route" }; + else + res = rx_expect_reference(out, ref, ng, shapes[s].k1 ? 2 : 1); + if (out) ray_release(out); + free(ref); + } + } + free(mask); + ray_release(tbl); + } + ray_pool_destroy(); + ray_pool_init(0); + ray_sym_destroy(); ray_heap_destroy(); + return res; +} + /* ══════════════════════════════════════════════════════════════════════ * PEARSON r-vs-r² DISCOVERY + v2/old differential. * @@ -2248,6 +2431,7 @@ const test_entry_t agg_engine_entries[] = { { "diff_group_radix_median", test_diff_group_radix_median, NULL, NULL }, { "diff_group_radix_top2", test_diff_group_radix_top2, NULL, NULL }, { "diff_group_determinism_workers", test_diff_group_determinism_workers, NULL, NULL }, + { "radix_matches_sequential_reference", test_radix_matches_sequential_reference, NULL, NULL }, { "sel_i64_sum", test_sel_i64_sum, NULL, NULL }, { "sel_i64_count", test_sel_i64_count, NULL, NULL }, { "sel_i64_four", test_sel_i64_four, NULL, NULL }, diff --git a/test/test_csv.c b/test/test_csv.c index 3f0156246..edc81a559 100644 --- a/test/test_csv.c +++ b/test/test_csv.c @@ -27,9 +27,14 @@ #include "mem/heap.h" #include "core/qstats.h" #include "io/csv.h" +#include "store/splay.h" #include "table/sym.h" +#include "ops/idxop.h" +#include "core/runtime.h" #include #include +#include +#include static char tmp_csv_path[64]; static const char* tmp_csv(void) { @@ -1859,7 +1864,342 @@ static test_result_t test_csv_sym_id_order(void) { PASS(); } +static test_result_t test_csv_native_pooled_batches(void) { + ray_heap_init(); (void)ray_sym_init(); + FILE* fp = fopen(TMP_CSV,"wb"); TEST_ASSERT_NOT_NULL(fp); + fprintf(fp,"id,text\n1,first long pooled string\n2,second long pooled string\n3,\n4,fourth long pooled string\n5,last long pooled string\n"); fclose(fp); + char dir[128]; snprintf(dir,sizeof(dir),"/tmp/rayforce-csv-stream-%d",(int)getpid()); + const int8_t types[] = {RAY_I32,RAY_STR}; + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,2,NULL,0,dir,2),RAY_OK); + ray_t* table = ray_read_splayed(dir,NULL); TEST_ASSERT_FALSE(RAY_IS_ERR(table)); + TEST_ASSERT_EQ_I(ray_table_nrows(table),5); + const char* expected[] = {"first long pooled string","second long pooled string","","fourth long pooled string","last long pooled string"}; + for (int i = 0; i < 5; i++) { + size_t len; const char* text = ray_str_vec_get(ray_table_get_col_idx(table,1),i,&len); + TEST_ASSERT_EQ_I(len,strlen(expected[i])); TEST_ASSERT_TRUE(!memcmp(text,expected[i],len)); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(table,0)))[i],i+1); + } + ray_release(table); + const char* files[] = {"id","text",".d"}; char path[160]; + for (int i = 0; i < 3; i++) { snprintf(path,sizeof(path),"%s/%s",dir,files[i]); unlink(path); } + rmdir(dir); unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +/* Recursive remove for the import tests' output trees. */ +static void csv_test_rm_rf(const char* path) { + DIR* d = opendir(path); + if (d) { + struct dirent* ent; + char sub[1024]; + while ((ent = readdir(d)) != NULL) { + if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) continue; + snprintf(sub, sizeof(sub), "%s/%s", path, ent->d_name); + csv_test_rm_rf(sub); + } + closedir(d); + rmdir(path); + } else { + unlink(path); + } +} + +/* The streaming importers must infer the same column types as .csv.read. + * SYM vs STR is decided from a sample's cardinality, so it depends on + * which rows are sampled: here the first 4096 notes are all distinct + * (a leading-rows sample says STR) while the file as a whole has ~4100 + * distinct notes over 200k rows (.csv.read's file-wide sample says SYM). */ +static test_result_t test_csv_streaming_infers_like_read(void) { + ray_heap_init(); (void)ray_sym_init(); + FILE* f = fopen(TMP_CSV, "wb"); TEST_ASSERT_NOT_NULL(f); + fputs("id,note\n", f); + for (int i = 0; i < 200000; i++) { + if (i < 4096) fprintf(f, "%d,unique note %d\n", i, i); + else fprintf(f, "%d,repeat %d\n", i, i % 10); + } + fclose(f); + + ray_t* mem = ray_read_csv_named_opts(TMP_CSV, ',', true, NULL, 0, NULL, 0); + TEST_ASSERT_TRUE(mem && !RAY_IS_ERR(mem)); + int8_t want = ray_table_get_col_idx(mem, 1)->type; + ray_release(mem); + TEST_ASSERT_EQ_I(want, RAY_SYM); + + char dir[128]; + snprintf(dir, sizeof(dir), "/tmp/rayforce-csv-infer-%d", (int)getpid()); + csv_test_rm_rf(dir); + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV, ',', true, NULL, 0, + NULL, 0, dir, 0), RAY_OK); + char sym[160]; + snprintf(sym, sizeof(sym), "%s/.sym", dir); + ray_t* t = ray_read_splayed(dir, sym); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(t, 1)->type, want); + ray_release(t); + csv_test_rm_rf(dir); + + char leaf[192]; + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV, ',', true, NULL, 0, + NULL, 0, dir, "t", 150000), RAY_OK); + snprintf(leaf, sizeof(leaf), "%s/1/t", dir); + t = ray_read_splayed(leaf, sym); + TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(t, 1)->type, want); + ray_release(t); + csv_test_rm_rf(dir); + + unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + PASS(); +} + +static test_result_t test_csv_parted_zones(void) { + ray_heap_init(); (void)ray_sym_init(); + char root[128],leaf[160],path[200]; + snprintf(root,sizeof(root),"/tmp/rayforce-csv-zones-%d",(int)getpid()); + FILE* f=fopen(TMP_CSV,"w"); TEST_ASSERT_TRUE(f != NULL); + fputs("x,y,s\n",f); + for(int i=0;i<65539;i++) fprintf(f,"%d,%d,value-%d\n",i,65538-i,i%257); + fclose(f); + int8_t types[]={RAY_I32,RAY_I64,RAY_SYM}; + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV,',',true,types,3,NULL,0,root,"hits",65536),RAY_OK); + for(int p=0;p<2;p++) { + snprintf(leaf,sizeof(leaf),"%s/%d/hits",root,p); + snprintf(path,sizeof(path),"%s/.sym",root); + ray_t* t=ray_read_splayed(leaf,path); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_nrows(t),p ? 3 : 65536); + for(int c=0;c<2;c++) { + ray_t* v=ray_table_get_col_idx(t,c); + TEST_ASSERT_TRUE(v->attrs & RAY_ATTR_HAS_INDEX); + const ray_index_t* ix=ray_index_payload(v->index); TEST_ASSERT_TRUE(ix != NULL); + TEST_ASSERT_EQ_I(ix->kind,p ? RAY_IDX_ZONE : RAY_IDX_CHUNK_ZONE); + int64_t lo=c ? (p ? 0 : 3) : (p ? 65536 : 0); + int64_t hi=c ? (p ? 2 : 65538) : (p ? 65538 : 65535); + TEST_ASSERT_EQ_I(p ? ix->u.zone.min_i : ((int64_t*)ray_data(ix->u.chunk_zone.mins))[0],lo); + TEST_ASSERT_EQ_I(p ? ix->u.zone.max_i : ((int64_t*)ray_data(ix->u.chunk_zone.maxs))[0],hi); + } + ray_t* x=ray_table_get_col_idx(t,0); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(x))[0],p ? 65536 : 0); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(x))[x->len-1],p ? 65538 : 65535); + ray_t* s=ray_table_get_col_idx(t,2); + for(int64_t i=0;ilen;i++) { + char expected[32]; snprintf(expected,sizeof(expected),"value-%lld",(long long)((i+p*65536)%257)); + ray_t* cell=ray_sym_vec_cell(s,i); + TEST_ASSERT_TRUE(cell != NULL); + TEST_ASSERT_TRUE(!strcmp(ray_str_ptr(cell),expected)); + } + ray_release(t); + const char* names[]={"x","y","s",".d"}; + for(int c=0;c<4;c++) { snprintf(path,sizeof(path),"%s/%s",leaf,names[c]); unlink(path); } + rmdir(leaf); snprintf(path,sizeof(path),"%s/%d",root,p); rmdir(path); + } + snprintf(path,sizeof(path),"%s/.sym",root); unlink(path); rmdir(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]; + snprintf(root,sizeof(root),"/tmp/rayforce-csv-staging-%d",(int)getpid()); + snprintf(partial,sizeof(partial),"%s.csv-partial",root); + FILE* f = fopen(TMP_CSV,"w"); TEST_ASSERT_TRUE(f != NULL); + fputs("s\nfirst\nsecond\nthird\n",f); fclose(f); + int8_t invalid[] = {RAY_TABLE}, types[] = {RAY_SYM}; + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV,',',true,types,1,NULL,0,root,"../escape",2),RAY_ERR_DOMAIN); + TEST_ASSERT_TRUE(access(partial,F_OK) != 0); + /* A failure before the first partition leaves no staging behind. */ + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV,',',true,invalid,1,NULL,0,root,"hits",2),RAY_ERR_TYPE); + TEST_ASSERT_TRUE(access(root,F_OK) != 0); + TEST_ASSERT_TRUE(access(partial,F_OK) != 0); + /* Retained staging (an import that failed mid-write) blocks the root. */ + TEST_ASSERT_EQ_I(mkdir(partial,0755),0); + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV,',',true,types,1,NULL,0,root,"hits",2),RAY_ERR_IO); + TEST_ASSERT_EQ_I(rmdir(partial),0); + /* A trailing slash still stages beside the requested destination. */ + snprintf(path,sizeof(path),"%s/",root); + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV,',',true,types,1,NULL,0,path,"hits",2),RAY_OK); + TEST_ASSERT_TRUE(access(partial,F_OK) != 0); + /* Existing-root saves must persist new symbols before replacing columns. */ + f = fopen(TMP_CSV,"w"); TEST_ASSERT_TRUE(f != NULL); + fputs("s\nlater-a\nlater-b\nlater-c\n",f); fclose(f); + TEST_ASSERT_EQ_I(ray_csv_save_parted_named_opts(TMP_CSV,',',true,types,1,NULL,0,root,"hits",2),RAY_OK); + for (int p = 0; p < 2; p++) { + char sym[200],leaf[200]; + snprintf(sym,sizeof(sym),"%s/.sym",root); snprintf(leaf,sizeof(leaf),"%s/%d/hits",root,p); + ray_t* t = ray_read_splayed(leaf,sym); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + ray_t* col = ray_table_get_col_idx(t,0); + for (int64_t i = 0; i < col->len; i++) { + char expected[] = "later-a"; expected[6] += (char)(p*2+i); + TEST_ASSERT_TRUE(!strcmp(ray_str_ptr(ray_sym_vec_cell(col,i)),expected)); + } + ray_release(t); + } + TEST_ASSERT_EQ_I(ray_test_rm_rf(root),0); + 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); +} +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()); + FILE* f=fopen(TMP_CSV,"w"); TEST_ASSERT_TRUE(f != NULL); + fputs("a,b,s,n\n",f); + for(long long i=0;i<300000;i++) { + if (i%13==0) fprintf(f,"%lld,%lld,v%lld,\n",i,(i*7919)%1000003,i%500); + else fprintf(f,"%lld,%lld,v%lld,%lld\n",i,(i*7919)%1000003,i%500,i); + } + fclose(f); + int8_t types[]={RAY_I64,RAY_I64,RAY_STR,RAY_I64}; + 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)); + TEST_ASSERT_EQ_I(ray_table_nrows(t),300000); + ray_t* a=ray_table_get_col_idx(t,0); + TEST_ASSERT_EQ_I(ray_index_kind(a),RAY_IDX_CHUNK_ZONE); + const ray_index_t* ix=ray_index_payload(a->index); + 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); + 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); + /* nullable column: zone equals a from-scratch compute over the loaded data */ + ray_t* nc=ray_table_get_col_idx(t,3); + TEST_ASSERT_EQ_I(ray_index_kind(nc),RAY_IDX_CHUNK_ZONE); + const ray_index_t* nz=ray_index_payload(nc->index); + TEST_ASSERT_TRUE(((uint8_t*)ray_data(nz->u.chunk_zone.null_bits))[0] & 1); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(nz->u.chunk_zone.mins))[0],1); + ray_t* plain=ray_vec_from_raw(RAY_I64,ray_data(nc),nc->len); + TEST_ASSERT_TRUE(plain && !RAY_IS_ERR(plain)); + ray_t* ref=ray_index_chunk_zone_compute(plain,16); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + const ray_index_t* rz=ray_index_payload(ref); + TEST_ASSERT_EQ_I(nz->u.chunk_zone.n_chunks,rz->u.chunk_zone.n_chunks); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.mins,rz->u.chunk_zone.mins,8)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.maxs,rz->u.chunk_zone.maxs,8)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.null_bits,rz->u.chunk_zone.null_bits,1)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.aggs,rz->u.chunk_zone.aggs,8)); + ray_release(ref); ray_release(plain); + ray_release(t); + csv_test_rm_rf(dir); + unlink(TMP_CSV); ray_sym_destroy(); ray_heap_destroy(); + 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. */ +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; + while (ok) { + char x[65536], y[65536]; + size_t nx = fread(x, 1, sizeof(x), fa), ny = fread(y, 1, sizeof(y), fb); + if (nx != ny || memcmp(x, y, nx)) ok = false; + if (nx == 0) break; + } + if (fa) fclose(fa); + 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 */ + ray_runtime_t* rt = ray_runtime_create(0, NULL); + TEST_ASSERT_NOT_NULL(rt); + char dirs[2][128]; + snprintf(dirs[0],sizeof(dirs[0]),"/tmp/rayforce-csv-wave0-%d",(int)getpid()); + snprintf(dirs[1],sizeof(dirs[1]),"/tmp/rayforce-csv-wave1-%d",(int)getpid()); + FILE* f=fopen(TMP_CSV,"w"); TEST_ASSERT_TRUE(f != NULL); + fputs("a,b,c,d,k\n",f); + for(long long i=0;i<300000;i++) + fprintf(f,"%lld,%lld,%lld,%lld,%lld\n",(i*7919)%1000003,(i*7919+104729)%1000003, + (i*7919+2*104729)%1000003,(i*7919+3*104729)%1000003,i); + fclose(f); + 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 */ + 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); + ray_release(t); + } + const char* names[]={"a","b","c","d","k"}; + for (int c=0;c<5;c++) { + char p0[200], p1[200]; + snprintf(p0,sizeof(p0),"%s/%s",dirs[0],names[c]); + snprintf(p1,sizeof(p1),"%s/%s",dirs[1],names[c]); + TEST_ASSERT_TRUE(csv_files_equal(p0,p1)); + } + csv_test_rm_rf(dirs[0]); csv_test_rm_rf(dirs[1]); + unlink(TMP_CSV); ray_runtime_destroy(rt); + PASS(); +} + +/* A literal INT64_MIN in a parse chunk without empty cells is a number to the + * parser (no HAS_NULLS on that slice) but a null once the column header ORs + * the slice flags; the streamed zone must follow the loaded column (#495). */ +static test_result_t test_csv_splayed_sentinel_literal(void) { + ray_heap_init(); (void)ray_sym_init(); + char dir[128]; snprintf(dir,sizeof(dir),"/tmp/rayforce-csv-sent-%d",(int)getpid()); + FILE* f=fopen(TMP_CSV,"w"); TEST_ASSERT_TRUE(f != NULL); + fputs("lit2\n",f); + for(long long i=0;i<300000;i++) { + if (i==7) fputs("-9223372036854775808\n",f); + else if (i>=200000 && i%50==0) fputs("\n",f); + else fprintf(f,"%lld\n",i/1000); + } + fclose(f); + int8_t types[]={RAY_I64}; + TEST_ASSERT_EQ_I(ray_csv_save_splayed_named_opts(TMP_CSV,',',true,types,1,NULL,0,dir,100000),RAY_OK); + ray_t* t=ray_read_splayed(dir,NULL); TEST_ASSERT_TRUE(t && !RAY_IS_ERR(t)); + ray_t* c=ray_table_get_col_idx(t,0); + TEST_ASSERT_EQ_I(c->len,300000); + TEST_ASSERT_TRUE(c->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_EQ_I(ray_index_kind(c),RAY_IDX_CHUNK_ZONE); + ray_t* plain=ray_vec_from_raw(RAY_I64,ray_data(c),c->len); + TEST_ASSERT_TRUE(plain && !RAY_IS_ERR(plain)); + plain->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* ref=ray_index_chunk_zone_compute(plain,16); + TEST_ASSERT_TRUE(ref && !RAY_IS_ERR(ref)); + const ray_index_t* nz=ray_index_payload(c->index); + const ray_index_t* rz=ray_index_payload(ref); + TEST_ASSERT_EQ_I(nz->u.chunk_zone.n_chunks,rz->u.chunk_zone.n_chunks); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.mins,rz->u.chunk_zone.mins,8)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.maxs,rz->u.chunk_zone.maxs,8)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.null_bits,rz->u.chunk_zone.null_bits,1)); + TEST_ASSERT_TRUE(csv_vec_bytes_eq(nz->u.chunk_zone.aggs,rz->u.chunk_zone.aggs,8)); + int64_t zs=0, znn=0, ws=0, wnn=0; + TEST_ASSERT_TRUE(ray_zone_int_sum(c,&zs,&znn)); + const int64_t* d=(const int64_t*)ray_data(c); + for (int64_t i=0;ilen;i++) { if (ray_vec_is_null(c,i)) continue; ws+=d[i]; wnn++; } + TEST_ASSERT_EQ_I(zs,ws); + TEST_ASSERT_EQ_I(znn,wnn); + TEST_ASSERT_EQ_I(wnn,300000-1-(100000/50)); + ray_release(ref); ray_release(plain); + 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_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/splayed_inline_indexes", test_csv_splayed_inline_indexes, NULL, NULL }, + { "csv/splayed_hash_waves", test_csv_splayed_hash_waves, 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 }, { "csv/roundtrip_f64", test_csv_roundtrip_f64, NULL, NULL }, @@ -1915,5 +2255,6 @@ const test_entry_t csv_entries[] = { { "csv/progress_monotonic", test_csv_progress_never_goes_backwards, NULL, NULL }, { "csv/scan_boundary_matrix", test_csv_scan_boundary_matrix, NULL, NULL }, { "csv/sym_id_order", test_csv_sym_id_order, NULL, NULL }, + { "csv/streaming_infers_like_read", test_csv_streaming_infers_like_read, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_domain.c b/test/test_domain.c index 7da142c70..3a80d850b 100644 --- a/test/test_domain.c +++ b/test/test_domain.c @@ -506,6 +506,75 @@ static test_result_t test_domain_intern_batch(void) { PASS(); } +enum { DOM_CONCURRENT_TASKS = 32, DOM_CONCURRENT_BATCH = 8192, + DOM_CONCURRENT_VOCAB = 32768, DOM_CONCURRENT_STRING = 32 }; +typedef struct { + ray_sym_domain_t* domain; + char* vocabulary; + int64_t* positions; + bool ok[DOM_CONCURRENT_TASKS]; +} domain_concurrent_batch_t; + +static void domain_concurrent_batch_task(void* raw, uint32_t wid, int64_t start, int64_t end) { + (void)wid; + domain_concurrent_batch_t* ctx = raw; + const char* strings[DOM_CONCURRENT_BATCH]; + size_t lengths[DOM_CONCURRENT_BATCH]; + uint32_t hashes[DOM_CONCURRENT_BATCH]; + for (int64_t task = start; task < end; task++) { + for (int i = 0; i < DOM_CONCURRENT_BATCH; i++) { + int v = (task*1024 + i%4096)%DOM_CONCURRENT_VOCAB; + strings[i] = ctx->vocabulary + v*DOM_CONCURRENT_STRING; + lengths[i] = strlen(strings[i]); + hashes[i] = (uint32_t)ray_hash_bytes(strings[i], lengths[i]); + } + ctx->ok[task] = ray_sym_domain_intern_batch(ctx->domain, DOM_CONCURRENT_BATCH, + strings, lengths, hashes, ctx->positions + task*DOM_CONCURRENT_BATCH); + } +} + +/* Overlapping batches grow the shared index while other workers probe it. + * Every task has repeats, and adjacent tasks share most of their vocabulary. + * 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"); + domain_concurrent_batch_t ctx = {0}; + ctx.domain = ray_sym_domain_open_or_create(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); + for (int v = 0; v < DOM_CONCURRENT_VOCAB; v++) + snprintf(ctx.vocabulary + v*DOM_CONCURRENT_STRING, DOM_CONCURRENT_STRING, + "parallel-%05d-%08x", v, (unsigned)v*7919u); + for (int pass = 0; pass < 2; pass++) { + ray_pool_dispatch_n(ray_pool_get(), domain_concurrent_batch_task, &ctx, DOM_CONCURRENT_TASKS); + TEST_ASSERT_EQ_I(ray_sym_domain_count(ctx.domain), DOM_CONCURRENT_VOCAB+1); + for (int task = 0; task < DOM_CONCURRENT_TASKS; task++) { + TEST_ASSERT_TRUE(ctx.ok[task]); + for (int i = 0; i < DOM_CONCURRENT_BATCH; i++) { + int v = (task*1024 + i%4096)%DOM_CONCURRENT_VOCAB; + const char* expected = ctx.vocabulary + v*DOM_CONCURRENT_STRING; + int64_t pos = ctx.positions[task*DOM_CONCURRENT_BATCH+i]; + TEST_ASSERT(pos > 0 && pos <= DOM_CONCURRENT_VOCAB, "concurrent position in range"); + ray_t* actual = ray_sym_domain_str(ctx.domain, pos); + TEST_ASSERT_NOT_NULL(actual); + TEST_ASSERT_EQ_U(ray_str_len(actual), strlen(expected)); + TEST_ASSERT_MEM_EQ(strlen(expected), ray_str_ptr(actual), expected); + TEST_ASSERT_EQ_I(ray_sym_domain_find(ctx.domain, expected, strlen(expected)), pos); + } + } + 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); + 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"); + PASS(); +} + /* Task 7b: open_or_create on a missing file yields an empty writable * domain; "" is seeded at position 0 by the first intern; flush creates * the file; verify-base-unchanged makes a racing writer LOUD. */ @@ -2103,7 +2172,27 @@ static test_result_t test_domain_dict_upsert_file_keys(void) { /* ---- registration -------------------------------------------------------- */ +static test_result_t test_domain_private(void) { + ray_sym_domain_t* a = ray_sym_domain_new(); + ray_sym_domain_t* b = ray_sym_domain_new(); + TEST_ASSERT_NOT_NULL(a); TEST_ASSERT_NOT_NULL(b); + TEST_ASSERT_TRUE(a != b); + TEST_ASSERT_NULL(ray_sym_domain_path(a)); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(a,"private-a",9),1); + TEST_ASSERT_EQ_I(ray_sym_domain_intern(b,"private-b",9),1); + TEST_ASSERT_EQ_I(ray_sym_domain_find(b,"private-a",9),-1); + TEST_ASSERT_EQ_I(ray_sym_domain_flush(a,true),RAY_ERR_DOMAIN); + ray_t* v = ray_sym_vec_new(RAY_SYM_W32,1); + TEST_ASSERT_NOT_NULL(v); + v->len = 1; v->sym_domain = a; ray_sym_domain_retain(a); + ((uint32_t*)ray_data(v))[0] = 1; + ray_sym_domain_release(a); ray_sym_domain_release(b); + TEST_ASSERT_TRUE(!strcmp(ray_str_ptr(ray_sym_vec_cell(v,0)),"private-a")); + ray_release(v); + PASS(); +} const test_entry_t domain_entries[] = { + { "domain/private", test_domain_private, domain_setup, domain_teardown }, { "domain/runtime_identity", test_domain_runtime_identity, domain_setup, domain_teardown }, { "domain/runtime_delegation", test_domain_runtime_delegation, domain_setup, domain_teardown }, { "domain/vec_new_attach", test_domain_vec_new_attach, domain_setup, domain_teardown }, @@ -2136,6 +2225,7 @@ const test_entry_t domain_entries[] = { { "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_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 091e2c52f..587601091 100644 --- a/test/test_embedding.c +++ b/test/test_embedding.c @@ -35,6 +35,7 @@ #include "lang/eval.h" #include "lang/internal.h" #include "lang/format.h" +#include "core/platform.h" #include "store/hnsw.h" #include "store/fileio.h" #include @@ -42,8 +43,13 @@ #include #include #include +#ifndef RAY_OS_WINDOWS +#include +#include +#endif extern ray_runtime_t* __RUNTIME; +extern const char* ray_error_msg(void); /* Small epsilon for F64 comparisons. */ #define EPS 1e-6 @@ -1032,6 +1038,130 @@ static test_result_t test_hnsw_load_rejects_bad_neighbor(void) { PASS(); } +/* Older builders could persist a one-way edge to a lower-level node in an + * 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"; + float vecs[128 * 2]; + for (int i = 0; i < 128; i++) { + vecs[i * 2] = (float)i; + vecs[i * 2 + 1] = (float)(i % 7); + } + + ray_hnsw_t* idx = ray_hnsw_build(vecs, 128, 2, RAY_HNSW_L2, 4, 50); + TEST_ASSERT_NOT_NULL(idx); + if (idx->n_layers <= 1) { + ray_hnsw_free(idx); + TEST_ASSERT_TRUE(false); + } + + int64_t low_level_id = -1; + for (int64_t i = 0; i < idx->n_nodes; i++) { + if (idx->node_level[i] == 0) { + low_level_id = i; + break; + } + } + if (low_level_id < 0) { + ray_hnsw_free(idx); + TEST_ASSERT_TRUE(false); + } + int64_t injected_layers = 0; + for (int32_t l = 1; l < idx->n_layers; l++) { + ray_hnsw_layer_t* layer = &idx->layers[l]; + int64_t slot = -1; + for (int64_t i = 0; i < layer->n_nodes && slot < 0; i++) { + for (int64_t j = 0; j < layer->M_max; j++) { + if (layer->neighbors[i * layer->M_max + j] != -1) { + slot = i * layer->M_max + j; + break; + } + } + } + if (slot >= 0) { + layer->neighbors[slot] = low_level_id; + injected_layers++; + } + } + TEST_ASSERT_TRUE(injected_layers > 0); + int64_t valid_entry = idx->entry_point; + int32_t valid_M_max0 = idx->M_max0; + + ray_err_t neighbor_err = ray_hnsw_save(idx, neighbor_dir); + + idx->entry_point = low_level_id; + ray_err_t entry_err = ray_hnsw_save(idx, entry_dir); + + idx->entry_point = valid_entry; + idx->M_max0 = valid_M_max0 - 1; + ray_err_t width_err = ray_hnsw_save(idx, width_dir); + ray_hnsw_free(idx); + TEST_ASSERT_EQ_I(neighbor_err, RAY_OK); + TEST_ASSERT_EQ_I(entry_err, RAY_OK); + TEST_ASSERT_EQ_I(width_err, RAY_OK); +#ifndef RAY_OS_WINDOWS + char warning_path[96]; + snprintf(warning_path, sizeof(warning_path), "/tmp/ray_hnsw_warning_%ld.log", + (long)getpid()); + int warning_fd = open(warning_path, O_RDWR | O_CREAT | O_TRUNC, 0600); + TEST_ASSERT_TRUE(warning_fd >= 0); + fflush(stderr); + int saved_stderr = dup(STDERR_FILENO); + TEST_ASSERT_TRUE(saved_stderr >= 0); + TEST_ASSERT_EQ_I(dup2(warning_fd, STDERR_FILENO), STDERR_FILENO); + ray_hnsw_t* loaded = ray_hnsw_load(neighbor_dir); + ray_hnsw_t* mapped = ray_hnsw_mmap(neighbor_dir); + fflush(stderr); + TEST_ASSERT_EQ_I(dup2(saved_stderr, STDERR_FILENO), STDERR_FILENO); + close(saved_stderr); + + char warning[512]; + TEST_ASSERT_EQ_I(lseek(warning_fd, 0, SEEK_SET), 0); + ssize_t warning_len = read(warning_fd, warning, sizeof(warning) - 1); + TEST_ASSERT_TRUE(warning_len >= 0); + warning[warning_len] = '\0'; + close(warning_fd); + unlink(warning_path); + char expected_count[64]; + snprintf(expected_count, sizeof(expected_count), "repaired %lld legacy", + (long long)injected_layers); + TEST_ASSERT_TRUE(strstr(warning, expected_count) != NULL); + TEST_ASSERT_TRUE(strstr(warning, "rebuild the index") != NULL); +#else + ray_hnsw_t* loaded = ray_hnsw_load(neighbor_dir); + ray_hnsw_t* mapped = ray_hnsw_mmap(neighbor_dir); +#endif + + TEST_ASSERT_NOT_NULL(loaded); + for (int32_t l = 1; l < loaded->n_layers; l++) { + ray_hnsw_layer_t* layer = &loaded->layers[l]; + for (int64_t i = 0; i < layer->n_nodes; i++) { + for (int64_t j = 0; j < layer->M_max; j++) { + int64_t id = layer->neighbors[i * layer->M_max + j]; + TEST_ASSERT_TRUE(id == -1 || loaded->node_level[id] >= l); + } + } + } + float query[2] = {0.0f, 0.0f}; + int64_t result_id; + double result_dist; + TEST_ASSERT_EQ_I(ray_hnsw_search(loaded, query, 2, 1, 50, &result_id, + &result_dist), + 1); + ray_hnsw_free(loaded); + + TEST_ASSERT_NOT_NULL(mapped); + ray_hnsw_free(mapped); + TEST_ASSERT_NULL(ray_hnsw_load(entry_dir)); + TEST_ASSERT_NULL(ray_hnsw_mmap(entry_dir)); + TEST_ASSERT_NULL(ray_hnsw_load(width_dir)); + TEST_ASSERT_NULL(ray_hnsw_mmap(width_dir)); + PASS(); +} + /* Trigger the maxheap_sift_down / results-replacement path in hnsw_search_layer. * * The replacement branch (lines 342-344) fires when: @@ -1668,6 +1798,16 @@ static test_result_t test_hnsw_load_type_errors(void) { r = ray_hnsw_load_fn(scalar); TEST_ASSERT_TRUE(RAY_IS_ERR(r)); ray_release(scalar); + + ray_t* missing = ray_str("/tmp/ray_hnsw_missing_index_error_detail", 40); + TEST_ASSERT_NOT_NULL(missing); + r = ray_hnsw_load_fn(missing); + TEST_ASSERT_TRUE(RAY_IS_ERR(r)); + const char* msg = ray_error_msg(); + TEST_ASSERT_NOT_NULL(msg); + TEST_ASSERT_TRUE(strstr(msg, "rebuild it") != NULL); + ray_error_free(r); + ray_release(missing); PASS(); } @@ -2030,6 +2170,7 @@ const test_entry_t embedding_entries[] = { { "embedding/hnsw_build_overflow_rejected", test_hnsw_build_overflow_rejected, emb_setup, emb_teardown }, { "embedding/hnsw_vec_size_valid_guard", test_hnsw_vec_size_valid_guard, emb_setup, emb_teardown }, { "embedding/hnsw_load_rejects_bad_neighbor", test_hnsw_load_rejects_bad_neighbor, emb_setup, emb_teardown }, + { "embedding/hnsw_load_repairs_legacy_layer_edge", test_hnsw_load_repairs_legacy_layer_edge, emb_setup, emb_teardown }, { "embedding/hnsw_search_sift_down", test_hnsw_search_sift_down, emb_setup, emb_teardown }, /* rerank coverage (S7) */ @@ -2078,4 +2219,3 @@ const test_entry_t embedding_entries[] = { { NULL, NULL, NULL, NULL }, }; - diff --git a/test/test_exec.c b/test/test_exec.c index 52c346358..4712b5e28 100644 --- a/test/test_exec.c +++ b/test/test_exec.c @@ -7835,11 +7835,11 @@ static test_result_t test_exec_profiling_span_end(void) { PASS(); } -/* ---- broadcast_scalar nrows<=0 unknown type error (exec.c L501) ---- - * ray_typed_null(-RAY_DATE) creates an atom with type=-RAY_DATE, which - * is not handled by broadcast_scalar nrows<=0 → returns ray_error. - * SELECT propagates the error; ray_execute returns an error result. */ -static test_result_t test_exec_broadcast_scalar_empty_unknown_type(void) { +/* ---- OP_SELECT: a DATE constant over an empty table (#698) ---- + * A select of literals alone keeps the input's rows: zero, typed DATE. + * The atom was broadcast by a routine that knew only str/i64/f64/bool/sym + * and failed with a type error. */ +static test_result_t test_exec_select_date_const_empty(void) { ray_heap_init(); (void)ray_sym_init(); @@ -7850,8 +7850,6 @@ static test_result_t test_exec_broadcast_scalar_empty_unknown_type(void) { tbl = ray_table_add_col(tbl, name_x, empty_vec); ray_release(empty_vec); - /* -RAY_DATE atom → hits else return ray_error("type", NULL) in - * broadcast_scalar's nrows<=0 branch */ ray_t* date_atom = ray_typed_null(-RAY_DATE); TEST_ASSERT_NOT_NULL(date_atom); TEST_ASSERT_FALSE(RAY_IS_ERR(date_atom)); @@ -7862,11 +7860,12 @@ static test_result_t test_exec_broadcast_scalar_empty_unknown_type(void) { ray_op_t* sel = ray_select_op(g, ray_const_table(g, tbl), cols, 1); ray_t* result = ray_execute(g, sel); - /* Should be an error: broadcast_scalar returns error for unknown type */ TEST_ASSERT_NOT_NULL(result); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 0); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 0)->type, RAY_DATE); - if (result && !RAY_IS_ERR(result)) ray_release(result); + ray_release(result); ray_release(date_atom); ray_graph_free(g); ray_release(tbl); @@ -7875,10 +7874,10 @@ static test_result_t test_exec_broadcast_scalar_empty_unknown_type(void) { PASS(); } -/* ---- broadcast_scalar nrows>0 unknown type error (exec.c L525) ---- - * Same as above but with a non-empty table (nrows>0). broadcast_scalar - * skips nrows<=0 path and reaches the later else return ray_error. */ -static test_result_t test_exec_broadcast_scalar_nonzero_unknown_type(void) { +/* ---- OP_SELECT: a DATE constant beside a row column (#698) ---- + * Same as above on the 10-row table with a scanned column beside it: the + * constant widens to every row and stays null. */ +static test_result_t test_exec_select_date_const_beside_col(void) { ray_heap_init(); ray_t* tbl = make_exec_table(); /* 10-row table */ @@ -7893,11 +7892,16 @@ static test_result_t test_exec_broadcast_scalar_nonzero_unknown_type(void) { ray_op_t* sel = ray_select_op(g, ray_const_table(g, tbl), cols, 2); ray_t* result = ray_execute(g, sel); - /* broadcast_scalar returns error for unknown atom type → error propagates */ TEST_ASSERT_NOT_NULL(result); - TEST_ASSERT_TRUE(RAY_IS_ERR(result)); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 10); + ray_t* dcol = ray_table_get_col_idx(result, 1); + TEST_ASSERT_EQ_I(dcol->type, RAY_DATE); + TEST_ASSERT_EQ_I(dcol->len, 10); + TEST_ASSERT_TRUE(ray_vec_is_null(dcol, 0)); + TEST_ASSERT_TRUE(ray_vec_is_null(dcol, 9)); - if (result && !RAY_IS_ERR(result)) ray_release(result); + ray_release(result); ray_release(date_atom); ray_graph_free(g); ray_release(tbl); @@ -7906,6 +7910,38 @@ static test_result_t test_exec_broadcast_scalar_nonzero_unknown_type(void) { PASS(); } +/* ---- OP_SELECT: an F32 constant beside a row column (#698) ---- + * enlist has no F32 vector and boxes the atom in a one-element LIST; the + * widening must still give it the input's rows, not a ragged table. */ +static test_result_t test_exec_select_f32_const_beside_col(void) { + ray_heap_init(); + ray_t* tbl = make_exec_table(); /* 10-row table */ + + ray_t* f_atom = ray_f32(1.5f); + TEST_ASSERT_NOT_NULL(f_atom); + TEST_ASSERT_FALSE(RAY_IS_ERR(f_atom)); + + ray_graph_t* g = ray_graph_new(tbl); + ray_op_t* cst = ray_const_atom(g, f_atom); + ray_op_t* v1 = ray_scan(g, "v1"); + ray_op_t* cols[] = { v1, cst }; + ray_op_t* sel = ray_select_op(g, ray_const_table(g, tbl), cols, 2); + + ray_t* result = ray_execute(g, sel); + TEST_ASSERT_NOT_NULL(result); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); + TEST_ASSERT_EQ_I(ray_table_nrows(result), 10); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(result, 1)->len, 10); + + ray_release(result); + ray_release(f_atom); + ray_graph_free(g); + ray_release(tbl); + ray_sym_destroy(); + ray_heap_destroy(); + PASS(); +} + /* ---- OP_SELECT c>=10 name_buf path (exec.c L1637) ---- * A SELECT with 10+ expression columns exercises name_buf[n++] = digit * for the tens place. Verifies coverage of the `c >= 10` branch. */ @@ -17650,8 +17686,9 @@ const test_entry_t exec_entries[] = { { "exec/broadcast_scalar_empty_bool", test_exec_broadcast_scalar_empty_bool, NULL, NULL }, { "exec/broadcast_scalar_empty_sym", test_exec_broadcast_scalar_empty_sym, NULL, NULL }, { "exec/profiling_span_end", test_exec_profiling_span_end, NULL, NULL }, - { "exec/broadcast_scalar_empty_unknown", test_exec_broadcast_scalar_empty_unknown_type, NULL, NULL }, - { "exec/broadcast_scalar_nzero_unknown", test_exec_broadcast_scalar_nonzero_unknown_type, NULL, NULL }, + { "exec/select_date_const_empty", test_exec_select_date_const_empty, NULL, NULL }, + { "exec/select_date_const_beside_col", test_exec_select_date_const_beside_col, NULL, NULL }, + { "exec/select_f32_const_beside_col", test_exec_select_f32_const_beside_col, NULL, NULL }, { "exec/select_10_expr_cols", test_exec_select_10_expr_cols, NULL, NULL }, { "exec/streaming_concat_scan", test_exec_streaming_concat_scan, NULL, NULL }, { "exec/streaming_all_segments_pruned", test_exec_streaming_all_segments_pruned, NULL, NULL }, diff --git a/test/test_heap.c b/test/test_heap.c index 975eb7f66..0b7149a42 100644 --- a/test/test_heap.c +++ b/test/test_heap.c @@ -77,6 +77,7 @@ static int munmap(void* p, size_t len) { } #else #include +#include /* fstat: spill-file link count */ #endif #include #include @@ -2672,6 +2673,16 @@ static test_result_t test_anon_watermark_spill(void) { bool a_file = a ? ray_direct_file_backed(a) : true; /* expect anon (RAM) */ ray_t* b = ray_alloc(sz); bool b_file = b ? ray_direct_file_backed(b) : false; /* expect spill file */ + /* The spill file is unlinked as soon as it is mapped: a process that + * exits or is killed while holding the block leaves nothing on disk. */ + bool b_unlinked = true; +#if !defined(_WIN32) + if (b && b_file) { + struct stat st; + int fd = ((const ray_direct_hdr_t*)((const char*)b - RAY_DIRECT_HDR))->swap_fd; + b_unlinked = fstat(fd, &st) == 0 && st.st_nlink == 0; + } +#endif /* A spilled block must be as usable as an anon one: write a pattern near * the start and end of each and read it back (MAP_SHARED round-trip). */ @@ -2700,6 +2711,7 @@ static test_result_t test_anon_watermark_spill(void) { TEST_ASSERT_NOT_NULL(b); TEST_ASSERT(!a_file, "first alloc under watermark stays in anonymous RAM"); TEST_ASSERT(b_file, "second alloc over watermark spills to a disk file"); + TEST_ASSERT(b_unlinked, "the spill file has no name left while the block is live"); TEST_ASSERT(rw_ok, "both anon and spilled blocks round-trip written data"); /* Counter returns to baseline once both are freed. */ diff --git a/test/test_ipc.c b/test/test_ipc.c index aa1752f06..bbfc1f628 100644 --- a/test/test_ipc.c +++ b/test/test_ipc.c @@ -70,6 +70,7 @@ #include "core/platform.h" #include "core/runtime.h" #include "core/poll.h" +#include "core/timer.h" #include "store/serde.h" #include "mem/sys.h" #include "store/journal.h" @@ -88,6 +89,7 @@ extern ray_t* ray_hpost_fn(ray_t* handle, ray_t* msg); #include #include +#include #include #include @@ -2123,7 +2125,8 @@ static test_result_t test_ipc_open_opts_int_timeout(void) { ray_t* a = ray_i64(250); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(a, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(a, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_I(timeout, 250); TEST_ASSERT_EQ_U(thr, RAY_IPC_COMPRESS_AUTO); @@ -2137,7 +2140,8 @@ static test_result_t test_ipc_open_opts_dict_timeout(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_I(timeout, 400); TEST_ASSERT_EQ_U(thr, RAY_IPC_COMPRESS_AUTO); @@ -2153,7 +2157,8 @@ static test_result_t test_ipc_open_opts_compress_null_never(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_U(thr, RAY_IPC_COMPRESS_NEVER); TEST_ASSERT_EQ_I(timeout, 0); /* unset -> default budget */ @@ -2168,7 +2173,8 @@ static test_result_t test_ipc_open_opts_compress_threshold(void) { ray_t* d = mk_opts(keys, vals, 2); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_U(thr, 5000); TEST_ASSERT_EQ_I(timeout, 75); @@ -2184,7 +2190,8 @@ static test_result_t test_ipc_open_opts_compress_zero_always(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 99; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_U(thr, 0); ray_release(vals[0]); @@ -2199,7 +2206,8 @@ static test_result_t test_ipc_open_opts_unknown_key(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(vals[0]); @@ -2213,7 +2221,8 @@ static test_result_t test_ipc_open_opts_bad_value_type(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(vals[0]); @@ -2227,7 +2236,8 @@ static test_result_t test_ipc_open_opts_negative_rejected(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(vals[0]); @@ -2236,7 +2246,7 @@ static test_result_t test_ipc_open_opts_negative_rejected(void) { const char* k2[] = { "timeout" }; ray_t* v2[] = { ray_i64(-1) }; ray_t* d2 = mk_opts(k2, v2, 1); - err = ray_ipc_parse_open_opts(d2, &timeout, &thr); + err = ray_ipc_parse_open_opts(d2, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(v2[0]); @@ -2251,7 +2261,8 @@ static test_result_t test_ipc_open_opts_timeout_null_is_default(void) { ray_t* d = mk_opts(keys, vals, 1); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_I(timeout, 0); ray_release(vals[0]); @@ -2266,7 +2277,8 @@ static test_result_t test_ipc_open_opts_empty_dict(void) { ray_t* d = ray_dict_new(k, v); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_I(timeout, 0); TEST_ASSERT_EQ_U(thr, RAY_IPC_COMPRESS_AUTO); @@ -2292,7 +2304,8 @@ static test_result_t test_ipc_open_opts_string_keys_rejected(void) { int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(d); @@ -2313,7 +2326,8 @@ static test_result_t test_ipc_open_opts_list_sym_keys(void) { int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_NULL(err); TEST_ASSERT_EQ_U(thr, 4096); ray_release(d); @@ -2334,7 +2348,8 @@ static test_result_t test_ipc_open_opts_list_sym_keys_unknown(void) { int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(d); @@ -2345,13 +2360,275 @@ static test_result_t test_ipc_open_opts_wrong_arg_type(void) { ray_t* a = ray_str("nope", 4); int timeout = -1; size_t thr = 0; - ray_t* err = ray_ipc_parse_open_opts(a, &timeout, &thr); + int ka = 0; + ray_t* err = ray_ipc_parse_open_opts(a, &timeout, &thr, &ka); TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_error_free(err); ray_release(a); PASS(); } +/* ---- .ipc.open keepalive (#589) ---------------------------------------- + * `keepalive` is a dead-peer budget in ms: absent = on at the default + * budget, 0N = off, n > 0 = on at n (plus the unacknowledged-data bound). + * 0 is ambiguous ("off"? "immediately"?) and refused. */ + +static test_result_t test_ipc_open_opts_keepalive_parse(void) { + int timeout = -1; + size_t thr = 0; + int ka = 12345; + + /* absent -> auto */ + ray_t* e = ray_i64(100); + TEST_ASSERT_NULL(ray_ipc_parse_open_opts(e, &timeout, &thr, &ka)); + TEST_ASSERT_EQ_I(ka, RAY_IPC_KEEPALIVE_AUTO); + ray_release(e); + + const char* keys[] = { "keepalive" }; + ray_t* vals[] = { ray_i64(NULL_I64) }; + ray_t* d = mk_opts(keys, vals, 1); + TEST_ASSERT_NULL(ray_ipc_parse_open_opts(d, &timeout, &thr, &ka)); + TEST_ASSERT_EQ_I(ka, RAY_IPC_KEEPALIVE_OFF); + ray_release(vals[0]); ray_release(d); + + vals[0] = ray_i64(30000); + d = mk_opts(keys, vals, 1); + TEST_ASSERT_NULL(ray_ipc_parse_open_opts(d, &timeout, &thr, &ka)); + TEST_ASSERT_EQ_I(ka, 30000); + ray_release(vals[0]); ray_release(d); + + int64_t bad[] = { 0, -5 }; + for (int i = 0; i < 2; i++) { + vals[0] = ray_i64(bad[i]); + d = mk_opts(keys, vals, 1); + ray_t* err = ray_ipc_parse_open_opts(d, &timeout, &thr, &ka); + TEST_ASSERT_TRUE(err && RAY_IS_ERR(err)); + TEST_ASSERT_EQ_I(ray_err_from_obj(err), RAY_ERR_DOMAIN); + ray_error_free(err); + ray_release(vals[0]); ray_release(d); + } + PASS(); +} + +#if defined(__linux__) +#include +static int sockopt_int(int fd, int level, int name) { + int v = -1; + socklen_t l = sizeof(v); + if (getsockopt(fd, level, name, &v, &l) < 0) return -1; + return v; +} + +/* The options must actually land on the outbound socket, and survive the + * post-handshake reset of the connect-budget timeouts. */ +static test_result_t test_ipc_keepalive_sockopts(void) { + ray_test_server_t srv; + RAY_TEST_SERVER_START(srv); + ray_poll_t* poll = ray_ipc_active_poll(); + + /* default: keepalive at 60s (probe at 30s idle, then every 10s x3), + * and no unacknowledged-data bound. */ + int64_t h = ray_ipc_connect("127.0.0.1", srv.port, NULL, NULL, 0); + TEST_ASSERT((h) >= (0), "default connect"); + int fd = (int)ray_poll_get(poll, h)->fd; + TEST_ASSERT_EQ_I(sockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE), 1); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_KEEPIDLE), 30); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_KEEPINTVL), 10); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_KEEPCNT), 3); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_USER_TIMEOUT), 0); + ray_ipc_close(h); + + /* explicit budget: keepalive at that budget plus TCP_USER_TIMEOUT. + * Sub-second components round up to the kernel's 1s floor. */ + h = ray_ipc_connect_opts("127.0.0.1", srv.port, NULL, NULL, 0, + RAY_IPC_COMPRESS_AUTO, 4000); + TEST_ASSERT((h) >= (0), "budget connect"); + fd = (int)ray_poll_get(poll, h)->fd; + TEST_ASSERT_EQ_I(sockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE), 1); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_KEEPIDLE), 2); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_KEEPINTVL), 1); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_USER_TIMEOUT), 4000); + + /* the link still works with them set */ + ray_t* msg = ray_str("(+ 1 2)", 7); + ray_t* r = ray_ipc_send(h, msg); + ray_release(msg); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 3); + ray_release(r); + ray_ipc_close(h); + + /* off */ + h = ray_ipc_connect_opts("127.0.0.1", srv.port, NULL, NULL, 0, + RAY_IPC_COMPRESS_AUTO, RAY_IPC_KEEPALIVE_OFF); + TEST_ASSERT((h) >= (0), "off connect"); + fd = (int)ray_poll_get(poll, h)->fd; + TEST_ASSERT_EQ_I(sockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE), 0); + TEST_ASSERT_EQ_I(sockopt_int(fd, IPPROTO_TCP, TCP_USER_TIMEOUT), 0); + ray_ipc_close(h); + + ray_test_server_stop(&srv); + PASS(); +} +#endif + +/* ---- .ipc.send deadline (#589) ----------------------------------------- + * A peer that completes the handshake and then never answers: the shape + * of a half-open link, or of a server stuck in a long evaluation. It + * optionally drains what it is sent, and records whether the client + * closed its end. SO_RCVTIMEO bounds it, so a client that never closes + * fails the test instead of hanging it. POSIX socket calls: not on + * Windows. */ +#ifndef RAY_OS_WINDOWS +typedef struct { + ray_sock_t lfd; + uint16_t port; + bool drain; /* false: never read past the handshake */ + volatile int saw_eof; + ray_thread_t tid; +} silent_peer_t; + +static void silent_peer_thread(void* arg) { + silent_peer_t* p = (silent_peer_t*)arg; + ray_sock_t c = ray_sock_accept(p->lfd); + if (c == RAY_INVALID_SOCK) return; + ray_sock_set_blocking(c); + struct timeval tv = { 5, 0 }; + setsockopt((int)c, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + uint8_t hs[2]; + if (recv((int)c, hs, 2, MSG_WAITALL) == 2) { + uint8_t resp[2] = { RAY_SERDE_WIRE_VERSION, 0x00 }; + send((int)c, resp, 2, 0); + if (!p->drain) ray_test_sleep_ms(1500); /* window fills meanwhile */ + uint8_t buf[65536]; + for (;;) { + ssize_t n = recv((int)c, buf, sizeof(buf), 0); + if (n == 0) { p->saw_eof = 1; break; } + if (n < 0) { + if (errno == ECONNRESET) p->saw_eof = 1; + break; + } + } + } + ray_sock_close(c); +} + +static int silent_peer_start(silent_peer_t* p, bool drain) { + memset(p, 0, sizeof(*p)); + p->drain = drain; + p->lfd = ray_sock_listen(0); + if (p->lfd == RAY_INVALID_SOCK) return -1; + p->port = ray_test_listen_port(p->lfd); + ray_thread_create(&p->tid, silent_peer_thread, p); + return 0; +} + +static void silent_peer_stop(silent_peer_t* p) { + ray_thread_join(p->tid); + ray_sock_close(p->lfd); +} + +/* No reply within the deadline: io error, the connection is closed (so a + * late reply can never answer a later send), and on.close fires. */ +static test_result_t test_ipc_send_deadline_expires(void) { + silent_peer_t peer; + TEST_ASSERT_EQ_I(silent_peer_start(&peer, true), 0); + + int64_t h = ray_ipc_connect("127.0.0.1", peer.port, NULL, NULL, 2000); + TEST_ASSERT((h) >= (0), "connect"); + + ray_t* r = ray_eval_str( + "(do (set _dl_fired 0)" + " (set .ipc.on.close (fn [x] (set _dl_fired (+ _dl_fired 1)))) null)"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "install hook"); + ray_release(r); + + ray_t* msg = ray_i64(42); + int64_t t0 = ray_time_now_ms(); + r = ray_ipc_send_timeout(h, msg, 200); + int64_t took = ray_time_now_ms() - t0; + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_err_from_obj(r), RAY_ERR_IO); + ray_error_free(r); + TEST_ASSERT(took >= 200 && took < 2000, "expired on its deadline"); + + /* The handle is gone: a later send cannot pick up a stale reply. */ + r = ray_ipc_send(h, msg); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + ray_error_free(r); + ray_release(msg); + + r = ray_eval_str("_dl_fired"); + TEST_ASSERT(r && !RAY_IS_ERR(r), "read counter"); + TEST_ASSERT_EQ_I(r->i64, 1); + ray_release(r); + r = ray_eval_str("(set .ipc.on.close null)"); + if (r) ray_release(r); + + silent_peer_stop(&peer); + TEST_ASSERT_EQ_I(peer.saw_eof, 1); /* our end really closed */ + PASS(); +} + +/* The deadline covers the write too: a peer that never reads fills the + * socket buffers, and the send must not block past its deadline there. */ +static test_result_t test_ipc_send_deadline_covers_write(void) { + silent_peer_t peer; + TEST_ASSERT_EQ_I(silent_peer_start(&peer, false), 0); + + int64_t h = ray_ipc_connect("127.0.0.1", peer.port, NULL, NULL, 2000); + TEST_ASSERT((h) >= (0), "connect"); + + /* 64 MB: far past loopback socket buffering. */ + int64_t n = 8 * 1024 * 1024; + ray_t* big = ray_vec_new(RAY_I64, n); + TEST_ASSERT_NOT_NULL(big); + big->len = n; + memset(ray_data(big), 0x5a, (size_t)n * sizeof(int64_t)); + + int64_t t0 = ray_time_now_ms(); + ray_t* r = ray_ipc_send_timeout(h, big, 300); + int64_t took = ray_time_now_ms() - t0; + ray_release(big); + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_err_from_obj(r), RAY_ERR_IO); + ray_error_free(r); + TEST_ASSERT(took >= 300 && took < 1400, "write gave up on its deadline"); + + ray_t* msg = ray_i64(1); + r = ray_ipc_send(h, msg); /* handle closed */ + TEST_ASSERT_TRUE(r && RAY_IS_ERR(r)); + ray_error_free(r); + ray_release(msg); + + silent_peer_stop(&peer); + TEST_ASSERT_EQ_I(peer.saw_eof, 1); + PASS(); +} +#endif + +/* A reply inside the deadline is returned as usual, and the handle stays + * open for the next send. */ +static test_result_t test_ipc_send_deadline_met(void) { + ray_test_server_t srv; + RAY_TEST_SERVER_START(srv); + int64_t h = ray_ipc_connect("127.0.0.1", srv.port, NULL, NULL, 0); + TEST_ASSERT((h) >= (0), "connect"); + + for (int i = 0; i < 2; i++) { + ray_t* msg = ray_str("(+ 1 2)", 7); + ray_t* r = ray_ipc_send_timeout(h, msg, 5000); + ray_release(msg); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(r->i64, 3); + ray_release(r); + } + + ray_ipc_close(h); + ray_test_server_stop(&srv); + PASS(); +} + /* A compressed frame must survive a real socket round trip. * * Since #541 a loopback link never compresses, so every existing @@ -2366,7 +2643,8 @@ static test_result_t test_ipc_compressed_roundtrip(void) { RAY_TEST_SERVER_START(srv); /* threshold 0 = compress everything, overriding the loopback default */ - int64_t h = ray_ipc_connect_opts("127.0.0.1", srv.port, NULL, NULL, 0, 0); + int64_t h = ray_ipc_connect_opts("127.0.0.1", srv.port, NULL, NULL, 0, 0, + RAY_IPC_KEEPALIVE_AUTO); TEST_ASSERT((h) >= (0), "connected with compression forced"); TEST_ASSERT_EQ_U(ray_ipc_handle_threshold(h), 0); @@ -2815,6 +3093,15 @@ const test_entry_t ipc_entries[] = { { "ipc/mcast_local_not_compressed", test_ipc_mcast_local_not_compressed, ipc_setup, ipc_teardown }, { "ipc/frame_async_at_threshold", test_ipc_frame_async_at_threshold, ipc_setup, ipc_teardown }, { "ipc/compressed_roundtrip", test_ipc_compressed_roundtrip, ipc_setup, ipc_teardown }, + { "ipc/open_opts/keepalive_parse", test_ipc_open_opts_keepalive_parse, ipc_setup, ipc_teardown }, +#if defined(__linux__) + { "ipc/keepalive_sockopts", test_ipc_keepalive_sockopts, ipc_setup, ipc_teardown }, +#endif +#ifndef RAY_OS_WINDOWS + { "ipc/send_deadline/expires", test_ipc_send_deadline_expires, ipc_setup, ipc_teardown }, + { "ipc/send_deadline/covers_write", test_ipc_send_deadline_covers_write, ipc_setup, ipc_teardown }, +#endif + { "ipc/send_deadline/met", test_ipc_send_deadline_met, ipc_setup, ipc_teardown }, /* wire-level characterization (refactor guard) */ { "ipc/wire/resp_header_fields", test_ipc_wire_resp_header_fields, ipc_setup, ipc_teardown }, diff --git a/test/test_journal.c b/test/test_journal.c index 9904893f6..8cce0ac2d 100644 --- a/test/test_journal.c +++ b/test/test_journal.c @@ -26,6 +26,7 @@ #include "test.h" #include #include "store/journal.h" +#include "store/fileio.h" #include "store/serde.h" #include "lang/eval.h" #include "lang/env.h" @@ -134,6 +135,7 @@ static void cleanup_base(const char* base) { snprintf(path, sizeof(path), "%s.log", base); unlink(path); snprintf(path, sizeof(path), "%s.qdb", base); unlink(path); snprintf(path, sizeof(path), "%s.qdb.tmp", base); unlink(path); + snprintf(path, sizeof(path), "%s.lk", base); unlink(path); /* Archived rolls have the form base..log — remove with glob via shell. */ #if defined(_WIN32) snprintf(path, sizeof(path), "%s.*.log", base); /* no POSIX shell here */ @@ -696,6 +698,41 @@ static test_result_t test_journal_open_double_open(void) { PASS(); } +/* 3c2. A base that fits the lock path but not .log (1019-1020 bytes) + * fails in the append step after ray_journal_open took the lock; the + * lock must not stay held by the failed open. */ +static test_result_t test_journal_open_long_base_releases_lock(void) { +#if defined(__APPLE__) || defined(_WIN32) + 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* 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); + 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); + + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_ERR_DOMAIN); + TEST_ASSERT_FALSE(ray_journal_is_open()); + + /* flock is per open file description: a second fd in this process + * gets EWOULDBLOCK while the failed open still holds the lock. */ + char lk[2064]; + snprintf(lk, sizeof(lk), "%s.lk", base); + ray_fd_t fd = ray_file_open(lk, RAY_OPEN_READ | RAY_OPEN_WRITE | RAY_OPEN_CREATE); + TEST_ASSERT_TRUE(fd != RAY_FD_INVALID); + ray_err_t le = ray_file_trylock_ex(fd); + (void)ray_file_unlock(fd); + ray_file_close(fd); + (void)ray_test_rm_rf(root); + TEST_ASSERT_EQ_I(le, RAY_OK); + PASS(); +} + /* 3d. open with existing .log (clean) replays it -> opens for append. * Covers the RAY_JREPLAY_OK switch case (lines 438-442). */ static test_result_t test_journal_open_replays_existing_log(void) { @@ -2407,6 +2444,230 @@ static test_result_t test_journal_purge_after_close(void) { PASS(); } +/* L1-L3 (#687): one writer per journal base. The lock is an exclusive + * flock on .lk; a second open file description (as another process + * would have) cannot take it while the journal is open, through a roll, + * and is refused by open and purge while someone else holds it. */ +#if !defined(_WIN32) +#include +/* Whether another holder could take the lock on .lk right now. */ +static int jrn_lock_free(const char* base) { + char path[1100]; + snprintf(path, sizeof(path), "%s.lk", base); + int fd = open(path, O_RDWR | O_CREAT, 0644); + if (fd < 0) return -1; + int ok = flock(fd, LOCK_EX | LOCK_NB) == 0; + close(fd); + return ok; +} +#endif + +static test_result_t test_journal_lock_held_while_open(void) { +#if defined(_WIN32) + SKIP("flock probe is POSIX-only"); +#else + char base[256]; make_base(base, sizeof(base), "lock_held"); + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_EQ_I(jrn_lock_free(base), 0); + TEST_ASSERT_EQ_I(ray_journal_roll(), RAY_OK); + TEST_ASSERT_EQ_I(jrn_lock_free(base), 0); /* a roll keeps it */ + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + TEST_ASSERT_EQ_I(jrn_lock_free(base), 1); + TEST_ASSERT_EQ_I(ray_journal_open_append(base, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_EQ_I(jrn_lock_free(base), 0); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + cleanup_base(base); + PASS(); +#endif +} + +static test_result_t test_journal_lock_refuses_second_opener(void) { +#if defined(_WIN32) + SKIP("flock probe is POSIX-only"); +#else + char base[256]; make_base(base, sizeof(base), "lock_refuse"); + char path[300]; snprintf(path, sizeof(path), "%s.lk", base); + int other = open(path, O_RDWR | O_CREAT, 0644); + TEST_ASSERT_TRUE(other >= 0); + TEST_ASSERT_EQ_I(flock(other, LOCK_EX | LOCK_NB), 0); /* "another process" */ + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_ERR_IO); + TEST_ASSERT_FALSE(ray_journal_is_open()); + TEST_ASSERT_EQ_I(ray_journal_open_append(base, RAY_JOURNAL_ASYNC), RAY_ERR_IO); + TEST_ASSERT_FALSE(ray_journal_is_open()); + close(other); /* releases it */ + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + cleanup_base(base); + PASS(); +#endif +} + +static test_result_t test_journal_purge_refused_while_locked(void) { +#if defined(_WIN32) + SKIP("flock probe is POSIX-only"); +#else + char base[256]; make_base(base, sizeof(base), "lock_purge"); + char lpath[270]; log_path(lpath, sizeof(lpath), base); + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_TRUE(purge_write_one(7)); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + char path[300]; snprintf(path, sizeof(path), "%s.lk", base); + int other = open(path, O_RDWR | O_CREAT, 0644); + TEST_ASSERT_TRUE(other >= 0); + TEST_ASSERT_EQ_I(flock(other, LOCK_EX | LOCK_NB), 0); + TEST_ASSERT_EQ_I(ray_journal_purge(), RAY_ERR_IO); /* someone writes it */ + TEST_ASSERT_EQ_I(access(lpath, F_OK), 0); + close(other); + TEST_ASSERT_EQ_I(ray_journal_purge(), RAY_OK); + TEST_ASSERT_EQ_I(access(lpath, F_OK), -1); + TEST_ASSERT_EQ_I(jrn_lock_free(base), 1); + cleanup_base(base); + PASS(); +#endif +} + +#if !defined(_WIN32) +/* A base inside a fresh directory, so a test can remove the directory. */ +static void make_dir_base(char* dir, size_t dsz, char* base, size_t bsz, const char* prefix) { + snprintf(dir, dsz, "/tmp/jrn_test_%s_XXXXXX", prefix); + if (!mkdtemp(dir)) dir[0] = '\0'; + snprintf(base, bsz, "%s/base", dir); +} + +static void remove_dir_base(const char* dir, const char* base) { + cleanup_base(base); + rmdir(dir); +} +#endif + +/* A roll that cannot reopen its log keeps the lock of its base; opening + * another base then takes that base's lock instead of reusing the old one. */ +static test_result_t test_journal_lock_follows_base(void) { +#if defined(_WIN32) + SKIP("flock probe is POSIX-only"); +#else + char dir[256], base1[300]; + make_dir_base(dir, sizeof(dir), base1, sizeof(base1), "lock_base"); + TEST_ASSERT_TRUE(dir[0] != '\0'); + TEST_ASSERT_EQ_I(ray_journal_open(base1, RAY_JOURNAL_ASYNC), RAY_OK); + remove_dir_base(dir, base1); + TEST_ASSERT_TRUE(ray_journal_roll() != RAY_OK); + TEST_ASSERT_FALSE(ray_journal_is_open()); + char base2[256]; make_base(base2, sizeof(base2), "lock_base2"); + TEST_ASSERT_EQ_I(ray_journal_open(base2, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_EQ_I(jrn_lock_free(base2), 0); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + TEST_ASSERT_EQ_I(jrn_lock_free(base2), 1); + cleanup_base(base2); + PASS(); +#endif +} + +/* The lock fd is close-on-exec: a program started with .sys.exec must not + * keep the journal locked after this process exits. */ +static test_result_t test_journal_lock_not_inherited(void) { +#if !defined(__linux__) + SKIP("reads /proc/self/fd"); +#else + char base[256]; make_base(base, sizeof(base), "lock_exec"); + char lk[300]; snprintf(lk, sizeof(lk), "%s.lk", base); + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + int found = 0, cloexec = 0; + for (int fd = 3; fd < 1024; fd++) { + char link[64], target[400]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + ssize_t n = readlink(link, target, sizeof(target) - 1); + if (n <= 0) continue; + target[n] = '\0'; + if (strcmp(target, lk) != 0) continue; + found = 1; + cloexec = (fcntl(fd, F_GETFD) & FD_CLOEXEC) != 0; + } + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + cleanup_base(base); + TEST_ASSERT_EQ_I(found, 1); + TEST_ASSERT_EQ_I(cloexec, 1); + PASS(); +#endif +} + +/* A lock file this process cannot write (another user's) still guards the + * journal: purge is refused while its holder has it locked. */ +static test_result_t test_journal_purge_refused_readonly_lock(void) { +#if defined(_WIN32) + SKIP("flock probe is POSIX-only"); +#else + char base[256]; make_base(base, sizeof(base), "lock_ro"); + char lpath[270]; log_path(lpath, sizeof(lpath), base); + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_TRUE(purge_write_one(7)); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + char path[300]; snprintf(path, sizeof(path), "%s.lk", base); + TEST_ASSERT_EQ_I(chmod(path, 0444), 0); + int other = open(path, O_RDONLY); + TEST_ASSERT_TRUE(other >= 0); + TEST_ASSERT_EQ_I(flock(other, LOCK_EX | LOCK_NB), 0); + TEST_ASSERT_EQ_I(ray_journal_purge(), RAY_ERR_IO); + TEST_ASSERT_EQ_I(access(lpath, F_OK), 0); + close(other); + TEST_ASSERT_EQ_I(ray_journal_purge(), RAY_OK); + TEST_ASSERT_EQ_I(access(lpath, F_OK), -1); + cleanup_base(base); + PASS(); +#endif +} + +/* A base too long for open_append, reached through open after it took the + * lock: the failed open releases the lock. */ +static test_result_t test_journal_open_releases_lock_on_long_base(void) { +#if defined(_WIN32) + SKIP("flock probe is POSIX-only"); +#else + char dir[256], base[1100]; + make_dir_base(dir, sizeof(dir), base, sizeof(base), "lock_long"); + TEST_ASSERT_TRUE(dir[0] != '\0'); + /* The lengths below are what the kernel sees: on macOS /tmp is a + * symlink to /private/tmp, and a path that fits only before that + * expansion fails with ENAMETOOLONG instead of reaching open_append. */ + char path[1100]; + if (!realpath(dir, path)) snprintf(path, sizeof(path), "%s", dir); + while (strlen(path) + 201 < 1010) { + size_t n = strlen(path); + path[n] = '/'; + memset(path + n + 1, 'a', 200); + path[n + 201] = '\0'; + TEST_ASSERT_EQ_I(mkdir(path, 0755), 0); + } + size_t n = strlen(path); + path[n] = '/'; + memset(path + n + 1, 'b', 1019 - n - 1); + path[1019] = '\0'; + TEST_ASSERT_EQ_I(ray_journal_open(path, RAY_JOURNAL_ASYNC), RAY_ERR_DOMAIN); + TEST_ASSERT_FALSE(ray_journal_is_open()); + TEST_ASSERT_EQ_I(jrn_lock_free(path), 1); + char cmd[1200]; + snprintf(cmd, sizeof(cmd), "rm -rf %s", dir); + TEST_ASSERT_EQ_I(system(cmd), 0); + PASS(); +#endif +} + +/* Purge stays best-effort when the journal's directory is gone. */ +static test_result_t test_journal_purge_without_dir(void) { +#if defined(_WIN32) + SKIP("POSIX directory fixture"); +#else + char dir[256], base[300]; + make_dir_base(dir, sizeof(dir), base, sizeof(base), "purge_nodir"); + TEST_ASSERT_TRUE(dir[0] != '\0'); + TEST_ASSERT_EQ_I(ray_journal_open(base, RAY_JOURNAL_ASYNC), RAY_OK); + TEST_ASSERT_EQ_I(ray_journal_close(), RAY_OK); + remove_dir_base(dir, base); + TEST_ASSERT_EQ_I(ray_journal_purge(), RAY_OK); + PASS(); +#endif +} + /* P3. ops wrapper: (.log.purge) returns null on success and a `domain` * error when no journal base is known. */ static test_result_t test_journal_purge_ops_wrapper(void) { @@ -2462,6 +2723,7 @@ const test_entry_t journal_entries[] = { { "journal/open_close_basic", test_journal_open_close_basic, jrn_setup, jrn_teardown }, { "journal/open_bad_base", test_journal_open_bad_base, jrn_setup, jrn_teardown }, { "journal/open_double_open", test_journal_open_double_open, jrn_setup, jrn_teardown }, + { "journal/open_long_base_releases_lock", test_journal_open_long_base_releases_lock, jrn_setup, jrn_teardown }, { "journal/open_replays_existing_log", test_journal_open_replays_existing_log, jrn_setup, jrn_teardown }, { "journal/open_badtail_log", test_journal_open_badtail_log, jrn_setup, jrn_teardown }, /* Write bytes */ @@ -2536,6 +2798,15 @@ const test_entry_t journal_entries[] = { { "journal/purge_full", test_journal_purge_full, jrn_setup, jrn_teardown }, { "journal/purge_after_close", test_journal_purge_after_close, jrn_setup, jrn_teardown }, { "journal/purge_ops_wrapper", test_journal_purge_ops_wrapper, jrn_setup, jrn_teardown }, + /* #687: one writer per journal base */ + { "journal/lock_held_while_open", test_journal_lock_held_while_open, jrn_setup, jrn_teardown }, + { "journal/lock_refuses_second_opener", test_journal_lock_refuses_second_opener, jrn_setup, jrn_teardown }, + { "journal/purge_refused_while_locked", test_journal_purge_refused_while_locked, jrn_setup, jrn_teardown }, + { "journal/lock_follows_base", test_journal_lock_follows_base, jrn_setup, jrn_teardown }, + { "journal/lock_not_inherited", test_journal_lock_not_inherited, jrn_setup, jrn_teardown }, + { "journal/purge_without_dir", test_journal_purge_without_dir, jrn_setup, jrn_teardown }, + { "journal/open_releases_lock_on_long_base", test_journal_open_releases_lock_on_long_base, jrn_setup, jrn_teardown }, + { "journal/purge_refused_readonly_lock", test_journal_purge_refused_readonly_lock, jrn_setup, jrn_teardown }, /* #420: snapshot/roll crash window must not double-apply */ { "journal/crash_window_no_double_apply", test_journal_crash_window_no_double_apply, jrn_setup, jrn_teardown }, { NULL, NULL, NULL, NULL }, diff --git a/test/test_lang.c b/test/test_lang.c index afbdf69d0..4907e194b 100644 --- a/test/test_lang.c +++ b/test/test_lang.c @@ -6516,6 +6516,16 @@ static bool restricted_expr_returns_access(const char* expr) { return access; } +static test_result_t test_eval_restricted_parquet(void) { + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "(.parquet.splayed \"missing\" \"unused\")")); + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "(.parquet.scan \"test/data/parquet/flat-1-v2.parquet\")")); + TEST_ASSERT_TRUE(restricted_expr_returns_access( + "(select {from: {.parquet.source: \"test/data/parquet/flat-1-v2.parquet\"} x: x})")); + PASS(); +} + /* Restricted builtins must be rejected at the actual invocation boundary, * including compiled lambda bytecode. Invalid filesystem arguments are * deliberate: before the fix they return os/type instead of access without @@ -7778,6 +7788,222 @@ static test_result_t test_builtin_show_fn(void) { PASS(); } +/* Run (show x) with stdout redirected to a temporary file. Returns show's + * result; *text_out receives the printed bytes in a ray_alloc'd block the + * caller frees (NULL on failure). */ +static ray_t* show_capture(ray_t* x, ray_t** text_out) { + *text_out = NULL; + FILE* tmp = tmpfile(); + if (!tmp) return NULL; + fflush(stdout); + int saved = dup(fileno(stdout)); + dup2(fileno(tmp), fileno(stdout)); + ray_t* args[1] = { x }; + ray_t* r = ray_show_fn(args, 1); + fflush(stdout); + dup2(saved, fileno(stdout)); + close(saved); + long size = ftell(tmp); + if (size < 0) { fclose(tmp); return r; } + ray_t* blk = ray_alloc((size_t)size + 1); + if (blk) { + char* buf = (char*)ray_data(blk); + rewind(tmp); + size_t n = fread(buf, 1, (size_t)size, tmp); + buf[n] = '\0'; + *text_out = blk; + } + fclose(tmp); + return r; +} + +/* A plain scan: under ASan each strstr call re-measures the whole haystack, + * which makes a strstr loop quadratic on megabytes of output. */ +static int64_t count_substr(const char* s, const char* needle) { + int64_t n = 0; + size_t nl = strlen(needle), sl = strlen(s); + for (size_t i = 0; i + nl <= sl; ) { + if (memcmp(s + i, needle, nl) == 0) { n++; i += nl; } else i++; + } + return n; +} + +/* (show T) prints every column and row of a table: only the REPL display + * truncates to FMT_TABLE_MAX_WIDTH x FMT_TABLE_MAX_HEIGHT. */ +static test_result_t test_builtin_show_table_unlimited(void) { + ray_t* t = ray_eval_str( + "(table [a b c d e f g h i j k l m] (list (til 25) (til 25) (til 25)" + " (til 25) (til 25) (til 25) (til 25) (til 25) (til 25) (til 25)" + " (til 25) (til 25) (til 25)))"); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + + ray_t* text = NULL; + ray_t* r = show_capture(t, &text); + TEST_ASSERT_EQ_PTR(r, RAY_NULL_OBJ); + TEST_ASSERT_NOT_NULL(text); + const char* buf = (const char*)ray_data(text); + TEST_ASSERT_NOT_NULL(strstr(buf, "25 rows (25 shown) 13 columns (13 shown)")); + TEST_ASSERT_EQ_I(count_substr(buf, "I64"), 13); /* one type cell per column */ + TEST_ASSERT_NOT_NULL(strstr(buf, "│ 24 ")); + ray_free(text); + ray_release(t); + PASS(); +} + +/* A table far beyond the REPL limits is written in full, row by row, and its + * rows line up with the header (widths come from every cell, not a sample). */ +static test_result_t test_builtin_show_table_streamed(void) { + enum { N = 50000 }; + ray_t* k = ray_vec_new(RAY_I64, N); + ray_t* v = ray_vec_new(RAY_I64, N); + TEST_ASSERT_NOT_NULL(k); + TEST_ASSERT_NOT_NULL(v); + k->len = N; v->len = N; + for (int64_t i = 0; i < N; i++) { + ((int64_t*)ray_data(k))[i] = i; + ((int64_t*)ray_data(v))[i] = i * 1000000; + } + ray_t* t = ray_table_new(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); + ray_release(k); + ray_release(v); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + + ray_t* text = NULL; + ray_t* r = show_capture(t, &text); + TEST_ASSERT_EQ_PTR(r, RAY_NULL_OBJ); + TEST_ASSERT_NOT_NULL(text); + const char* buf = (const char*)ray_data(text); + TEST_ASSERT_NOT_NULL(strstr(buf, "50000 rows (50000 shown) 2 columns (2 shown)")); + /* the last column is widened to fit the footer, so match row prefixes */ + TEST_ASSERT_NOT_NULL(strstr(buf, "\n│ 0 │ 0 ")); + TEST_ASSERT_NOT_NULL(strstr(buf, "\n│ 25000 │ 25000000000 ")); + TEST_ASSERT_NOT_NULL(strstr(buf, "\n│ 49999 │ 49999000000 ")); + /* 50000 data rows + name row + type row + footer row */ + TEST_ASSERT_EQ_I(count_substr(buf, "\n│"), 50003); + ray_free(text); + ray_release(t); + PASS(); +} + +/* Table cells are written whole. The REPL's fixed 64-byte cell grid cut + * them at byte 63, losing the tail and the closing quote, and a cut inside + * a multi-byte character left invalid UTF-8 and a misaligned border. */ +static test_result_t test_builtin_show_table_long_cells(void) { + ray_t* t = ray_eval_str( + "(table [s u] (list" + " (list \"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-tail-end-marker\" \"x\")" + " (list \"a\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9" + "\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9" + "\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9" + "\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9\xc3\xa9z\" \"y\")))"); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + + ray_t* text = NULL; + ray_t* r = show_capture(t, &text); + TEST_ASSERT_EQ_PTR(r, RAY_NULL_OBJ); + TEST_ASSERT_NOT_NULL(text); + const char* buf = (const char*)ray_data(text); + TEST_ASSERT_NOT_NULL(strstr(buf, "XYZ-tail-end-marker\" ")); + /* 36 two-byte characters: the cut at byte 63 fell inside one */ + TEST_ASSERT_NOT_NULL(strstr(buf, "\xc3\xa9\xc3\xa9z\" ")); + /* every line of the table has the same display width */ + int32_t width = -1; + for (const char* line = buf; *line; ) { + const char* end = strchr(line, '\n'); + if (!end) end = line + strlen(line); + int32_t w = 0; + for (const char* c = line; c < end; c++) w += ((unsigned char)*c & 0xC0) != 0x80; + if (end > line) { + if (width < 0) width = w; + TEST_ASSERT_EQ_I(w, width); + } + line = *end ? end + 1 : end; + } + ray_free(text); + ray_release(t); + PASS(); +} + +/* One long cell does not pad every other row of its column: a column is + * padded to at most FMT_SHOW_PAD_MAX display columns, and a longer cell is + * written whole past its border. Padding every row to the longest cell + * made the output rows x longest cell. */ +static test_result_t test_builtin_show_table_long_cell_unpadded(void) { + enum { N = 3000, LONG = 10000 }; + ray_t* k = ray_vec_new(RAY_I64, N); + ray_t* s = ray_vec_new(RAY_STR, 0); + TEST_ASSERT_NOT_NULL(k); + TEST_ASSERT_NOT_NULL(s); + k->len = N; + ray_t* lblk = ray_alloc(LONG + 1); + TEST_ASSERT_NOT_NULL(lblk); + char* lng = (char*)ray_data(lblk); + memset(lng, 'x', LONG); + lng[LONG] = '\0'; + for (int64_t i = 0; i < N; i++) { + ((int64_t*)ray_data(k))[i] = i; + char cell[32]; + int cl = snprintf(cell, sizeof(cell), "v%lld", (long long)i); + s = i == 0 ? ray_str_vec_append(s, lng, LONG) : ray_str_vec_append(s, cell, (size_t)cl); + TEST_ASSERT_FALSE(RAY_IS_ERR(s)); + } + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("k", 1), k); + t = ray_table_add_col(t, ray_sym_intern("s", 1), s); + ray_release(k); + ray_release(s); + TEST_ASSERT_NOT_NULL(t); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + + ray_t* text = NULL; + ray_t* r = show_capture(t, &text); + TEST_ASSERT_EQ_PTR(r, RAY_NULL_OBJ); + TEST_ASSERT_NOT_NULL(text); + const char* buf = (const char*)ray_data(text); + size_t n = strlen(buf); + /* the long value is there whole */ + TEST_ASSERT_NOT_NULL(strstr(buf, lng)); + /* every other row is padded to the cap, not to the long cell: well + * under rows x (cap + border) + the long cell itself */ + TEST_ASSERT_FMT(n < (size_t)N * (256 * 3 + 64) + LONG * 2, + "show wrote %zu bytes for %d rows", n, N); + TEST_ASSERT_FMT(n < (size_t)N * 400, "show wrote %zu bytes for %d short rows", n, N); + TEST_ASSERT_EQ_I(count_substr(buf, "\n│"), N + 3); + TEST_ASSERT_NOT_NULL(strstr(buf, "│ \"v2999\" ")); + ray_free(text); + ray_free(lblk); + ray_release(t); + PASS(); +} + +/* show prints any value in full: a vector far past the REPL width limit + * comes out whole, streamed through the output buffer. */ +static test_result_t test_builtin_show_vector_full(void) { + enum { N = 200000 }; + ray_t* v = ray_vec_new(RAY_I64, N); + TEST_ASSERT_NOT_NULL(v); + v->len = N; + for (int64_t i = 0; i < N; i++) ((int64_t*)ray_data(v))[i] = i; + ray_t* text = NULL; + ray_t* r = show_capture(v, &text); + TEST_ASSERT_EQ_PTR(r, RAY_NULL_OBJ); + TEST_ASSERT_NOT_NULL(text); + const char* buf = (const char*)ray_data(text); + size_t n = strlen(buf); + TEST_ASSERT_TRUE(strncmp(buf, "[0 1 2 3 ", 9) == 0); + TEST_ASSERT_TRUE(n > 9 && strcmp(buf + n - 9, " 199999]\n") == 0); + TEST_ASSERT_EQ_I(count_substr(buf, " "), 199999); + TEST_ASSERT_NULL(strstr(buf, "..")); + ray_free(text); + ray_release(v); + PASS(); +} + /* (timeit expr) — returns elapsed ms as F64. */ static test_result_t test_builtin_timeit_fn(void) { /* timeit calls ray_eval(args[0]) — pass a parsed expression. */ @@ -8808,6 +9034,34 @@ static test_result_t test_select_derived_key_file_chunks(void) { ray_release(same); ray_release(cols); ray_release(same7); + + /* Scan-owned dictionaries have no mmap prefix. Their stable atoms must + * use the same bounded chunk evaluator as a file domain's appended tail. */ + ray_t* original = ray_eval_str("__dk_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("__dk_private",12),table); + ray_release(private); ray_release(table); ray_release(original); + ray_derived_key_chunk_set_for_test(7); + same = ray_eval_str("(all (== (__dk_fp (__dk_keyq __dk_private)) (__dk_fp __dk_r7)))"); + ray_derived_key_chunk_set_for_test(0); + TEST_ASSERT_NOT_NULL(same); TEST_ASSERT_FALSE(RAY_IS_ERR(same)); TEST_ASSERT_TRUE(same->b8); + ray_release(same); PASS(); } @@ -9530,6 +9784,7 @@ const test_entry_t lang_entries[] = { { "lang/eval/table_list_col_time", test_eval_table_list_col_time, lang_setup, lang_teardown }, { "lang/eval/table_list_col_f64_promote", test_eval_table_list_col_f64_i64_promote, lang_setup, lang_teardown }, { "lang/eval/cond_and_branches", test_eval_cond_and_branches, lang_setup, lang_teardown }, + { "lang/eval/restricted_parquet", test_eval_restricted_parquet, lang_setup, lang_teardown }, { "lang/eval/restricted_fn", test_eval_restricted_fn, lang_setup, lang_teardown }, { "lang/eval/restricted_lambda_bypass", test_eval_restricted_lambda_bypass, lang_setup, lang_teardown }, { "lang/eval/restricted_server_state_ops", test_eval_restricted_server_state_ops, lang_setup, lang_teardown }, @@ -9627,6 +9882,11 @@ const test_entry_t lang_entries[] = { /* S1/S2 builtins + temporal */ { "lang/builtin/print", test_builtin_print_fn, lang_setup, lang_teardown }, { "lang/builtin/show", test_builtin_show_fn, lang_setup, lang_teardown }, + { "lang/builtin/show_table_unlimited", test_builtin_show_table_unlimited, lang_setup, lang_teardown }, + { "lang/builtin/show_table_streamed", test_builtin_show_table_streamed, lang_setup, lang_teardown }, + { "lang/builtin/show_table_long_cells", test_builtin_show_table_long_cells, lang_setup, lang_teardown }, + { "lang/builtin/show_table_long_cell_unpadded", test_builtin_show_table_long_cell_unpadded, lang_setup, lang_teardown }, + { "lang/builtin/show_vector_full", test_builtin_show_vector_full, lang_setup, lang_teardown }, { "lang/builtin/timeit", test_builtin_timeit_fn, lang_setup, lang_teardown }, { "lang/builtin/load_file", test_builtin_load_file_fn, lang_setup, lang_teardown }, { "lang/builtin/read_bytes", test_builtin_read_bytes_fn, lang_setup, lang_teardown }, diff --git a/test/test_mcast.c b/test/test_mcast.c index e71e174bf..2401fe12a 100644 --- a/test/test_mcast.c +++ b/test/test_mcast.c @@ -959,14 +959,16 @@ static test_result_t test_ipc_connect_compress_override(void) { TEST_ASSERT_EQ_U(ray_ipc_handle_threshold(h_auto), RAY_IPC_COMPRESS_NEVER); /* Explicit threshold wins over the locality default... */ - int64_t h_on = ray_ipc_connect_opts("127.0.0.1", port, NULL, NULL, 0, 2000); + int64_t h_on = ray_ipc_connect_opts("127.0.0.1", port, NULL, NULL, 0, 2000, + RAY_IPC_KEEPALIVE_AUTO); TEST_ASSERT((h_on) >= (0), "override connected"); TEST_ASSERT_EQ_U(ray_ipc_handle_threshold(h_on), 2000); /* ...in both directions: NEVER stays NEVER on a link that would * otherwise have compressed. */ int64_t h_off = ray_ipc_connect_opts("127.0.0.1", port, NULL, NULL, 0, - RAY_IPC_COMPRESS_NEVER); + RAY_IPC_COMPRESS_NEVER, + RAY_IPC_KEEPALIVE_AUTO); TEST_ASSERT((h_off) >= (0), "never connected"); TEST_ASSERT_EQ_U(ray_ipc_handle_threshold(h_off), RAY_IPC_COMPRESS_NEVER); diff --git a/test/test_parquet.c b/test/test_parquet.c new file mode 100644 index 000000000..76e1d9a33 --- /dev/null +++ b/test/test_parquet.c @@ -0,0 +1,529 @@ +/* Copyright (c) 2026 Anton Kundenko. MIT license; see LICENSE. */ +#include "test.h" +#include "io/parquet.h" +#include "core/pool.h" +#include "mem/heap.h" +#include "table/sym.h" +#include "store/part.h" +#include "store/splay.h" +#include "ops/idxop.h" +#include +#include +#include +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) +#include +#endif + +static void pq_setup(void) { ray_heap_init(); (void)ray_sym_init(); } +static void pq_teardown(void) { ray_sym_destroy(); ray_heap_destroy(); } +#define FIX "test/data/parquet/" + +static test_result_t test_pq_snappy(void) { + uint8_t dst[256]; + /* Literal 'ab' followed by overlapping copies: all three copy tags. */ + const uint8_t b[] = {20,4,'a','b',1,2,14,2,0,39,2,0,0,0}; + TEST_ASSERT_TRUE(ray_parquet_snappy(b,sizeof(b),dst,20)); + for (int i = 0; i < 20; i++) TEST_ASSERT_EQ_I(dst[i],i&1 ? 'b' : 'a'); + for (size_t i = 0; i < sizeof(b); i++) TEST_ASSERT_FALSE(ray_parquet_snappy(b,i,dst,20)); + TEST_ASSERT_FALSE(ray_parquet_snappy(b,sizeof(b),dst,19)); + uint8_t invalid[] = {4,1,0}; + TEST_ASSERT_FALSE(ray_parquet_snappy(invalid,sizeof(invalid),dst,4)); + invalid[2] = 3; + TEST_ASSERT_FALSE(ray_parquet_snappy(invalid,sizeof(invalid),dst,4)); + const uint8_t empty[] = {0}; + TEST_ASSERT_TRUE(ray_parquet_snappy(empty,1,dst,0)); + /* Exhaust every offset for a 128-byte prefix and all COPY_2 lengths. + * Includes disjoint and overlapping copies with nonperiodic prefixes. */ + for (int off = 1; off <= 128; off++) for (int n = 1; n <= 64; n++) { + uint8_t encoded[140], expected[192]; size_t at = 0; + encoded[at++] = (uint8_t)((128+n)|128); encoded[at++] = 1; + encoded[at++] = 240; encoded[at++] = 127; + for (int i = 0; i < 128; i++) encoded[at++] = expected[i] = (uint8_t)(i*31+i/7); + encoded[at++] = (uint8_t)(((n-1)<<2)|2); encoded[at++] = (uint8_t)off; encoded[at++] = 0; + for (int i = 0; i < n; i++) expected[128+i] = expected[128+i-off]; + TEST_ASSERT_TRUE(ray_parquet_snappy(encoded,at,dst,128+n)); + TEST_ASSERT_TRUE(!memcmp(expected,dst,128+n)); + } + PASS(); +} +static test_result_t test_pq_matrix(void) { + const char* names[] = {FIX "flat-0-v1.parquet",FIX "flat-0-v2.parquet",FIX "flat-1-v1.parquet",FIX "flat-1-v2.parquet",FIX "legacy.parquet",FIX "v2-uncompressed.parquet",FIX "no-statistics.parquet"}; + int64_t expect[] = {1,NULL_I32,3,4,5,NULL_I32,7,8,9}; + const char* strings[] = {"alpha","a long string over twelve bytes","","","alpha","beta","gamma","delta","z"}; + for (int file = 0; file < 7; file++) for (int batch = 1; batch <= 11; batch++) { + ray_parquet_t* r = NULL; + ray_t* err = ray_parquet_open(names[file],NULL,batch,&r); + TEST_ASSERT_NULL(err); TEST_ASSERT_NOT_NULL(r); + int64_t total = 0; ray_t* kept = NULL; + for (;;) { + ray_t* t = ray_parquet_next(r); + if (!t) break; + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_ncols(t),7); + int64_t nr = ray_table_nrows(t); + TEST_ASSERT_TRUE(nr <= batch); + for (int64_t row = 0; row < nr; row++) { + int j = (int)((total+row)%9); + ray_t* x = ray_table_get_col_idx(t,0); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(x))[row],expect[j]); + size_t len; const char* str = ray_str_vec_get(ray_table_get_col_idx(t,1),row,&len); + TEST_ASSERT_EQ_I(len,strlen(strings[j])); + TEST_ASSERT_TRUE(memcmp(str,strings[j],len) == 0); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(t,3)))[row],100+j); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(t,4)))[row],j); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(t,5)))[row],j*1000); + } + total += nr; + if (!kept) kept = t; else ray_release(t); + } + TEST_ASSERT_EQ_I(total,18); + ray_parquet_close(r); + /* Results retain no pointers into the reader's mapping or scratch. */ + size_t len; const char* str = ray_str_vec_get(ray_table_get_col_idx(kept,1),0,&len); + TEST_ASSERT_EQ_I(len,5); TEST_ASSERT_TRUE(memcmp(str,"alpha",5) == 0); + ray_release(kept); + } + PASS(); +} +static test_result_t test_pq_read_meta(void) { + ray_t* m = ray_parquet_metadata(FIX "flat-1-v1.parquet"); + TEST_ASSERT_FALSE(RAY_IS_ERR(m)); TEST_ASSERT_EQ_I(ray_table_nrows(m),14); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(m,4)))[0],1); + ray_release(m); + int64_t names[] = {ray_sym_intern("name",4),ray_sym_intern("x",1)}; + ray_t* cols = ray_vec_from_raw(RAY_SYM,names,2); + ray_t* t = ray_parquet_read(FIX "flat-1-v2.parquet",cols); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_ncols(t),2); TEST_ASSERT_EQ_I(ray_table_nrows(t),18); + TEST_ASSERT_EQ_I(ray_table_col_name(t,0),names[0]); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(t,1)))[17],9); + ray_release(t); ray_release(cols); + t = ray_parquet_read(FIX "empty.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_nrows(t),0); TEST_ASSERT_EQ_I(ray_table_ncols(t),7); ray_release(t); + t = ray_parquet_read(FIX "all-null.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_nrows(t),9); + for (int c = 0; c < 2; c++) for (int i = 0; i < 9; i++) TEST_ASSERT_TRUE(ray_vec_is_null(ray_table_get_col_idx(t,c),i)); + ray_release(t); + t = ray_parquet_read(FIX "sentinels.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + for (int c = 0; c < 4; c++) TEST_ASSERT_TRUE(ray_vec_is_null(ray_table_get_col_idx(t,c),0)); + ray_release(t); + t = ray_parquet_read(FIX "bool.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + for (int i = 0; i < 10; i++) TEST_ASSERT_EQ_I(((uint8_t*)ray_data(ray_table_get_col_idx(t,0)))[i],!(i&1)); + ray_release(t); + PASS(); +} +static test_result_t test_pq_corrupt(void) { + FILE* f = fopen(FIX "flat-1-v2.parquet","rb"); TEST_ASSERT_NOT_NULL(f); + uint8_t bytes[16384]; size_t n = fread(bytes,1,sizeof(bytes),f); fclose(f); + TEST_ASSERT_TRUE(n < sizeof(bytes)); + char path[100]; snprintf(path,sizeof(path),"/tmp/rayforce-pq-corrupt-%d.parquet",(int)getpid()); + /* Every truncation must fail without reading outside the mapped file. */ + for (size_t i = 0; i < n; i++) { + f = fopen(path,"wb"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_EQ_I(fwrite(bytes,1,i,f),i); fclose(f); + ray_t* err = ray_parquet_read(path,NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_release(err); + } + /* Corrupt each byte in the first page: checksum/header failures propagate. */ + for (size_t i = 4; i < 30; i++) { + bytes[i] ^= 0x80; + f = fopen(path,"wb"); TEST_ASSERT_NOT_NULL(f); TEST_ASSERT_EQ_I(fwrite(bytes,1,n,f),n); fclose(f); + ray_t* err = ray_parquet_read(path,NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); ray_release(err); bytes[i] ^= 0x80; + } + unlink(path); + int64_t badname = ray_sym_intern("missing",7); + ray_t* cols = ray_vec_from_raw(RAY_SYM,&badname,1); ray_parquet_t* r = NULL; + ray_t* err = ray_parquet_open(FIX "flat-1-v1.parquet",cols,16,&r); + TEST_ASSERT_TRUE(RAY_IS_ERR(err)); TEST_ASSERT_NULL(r); ray_release(err); ray_release(cols); + PASS(); +} +static test_result_t test_pq_native(void) { + char root[128]; snprintf(root,sizeof(root),"/tmp/rayforce-pq-native-%d",(int)getpid()); + ray_t* n = ray_parquet_parted(FIX "flat-1-v2.parquet",root,"hits"); + TEST_ASSERT_FALSE(RAY_IS_ERR(n)); TEST_ASSERT_EQ_I(n->i64,18); ray_release(n); + ray_t* t = ray_read_parted(root,"hits"); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_nrows(t),18); + ray_t* x = ray_table_get_col(t,ray_sym_intern("x",1)); + ray_t* seg = ((ray_t**)ray_data(x))[0]; + TEST_ASSERT_TRUE(ray_index_kind(seg) != 0); + ray_release(t); + /* Never overwrite an existing native destination. */ + n = ray_parquet_parted(FIX "flat-1-v2.parquet",root,"hits"); + TEST_ASSERT_TRUE(RAY_IS_ERR(n)); ray_release(n); + const char* names[] = {"x","name","flag","wide","day","ts","f",".d"}; + for (int p = 0; p < 2; p++) { + char path[200]; + for (int c = 0; c < 8; c++) { snprintf(path,sizeof(path),"%s/%d/hits/%s",root,p,names[c]); unlink(path); } + snprintf(path,sizeof(path),"%s/%d/hits",root,p); rmdir(path); + snprintf(path,sizeof(path),"%s/%d",root,p); rmdir(path); + } + rmdir(root); + PASS(); +} +static test_result_t test_pq_range(void) { + int64_t name = ray_sym_intern("name",4), x = ray_sym_intern("x",1); + ray_t* cols = ray_vec_from_raw(RAY_SYM,&name,1); + for (int pass = 0; pass < 3; pass++) { + ray_parquet_t* r = NULL; + ray_t* err = ray_parquet_open(pass == 2 ? FIX "no-statistics.parquet" : FIX "flat-1-v2.parquet",cols,2,&r); + TEST_ASSERT_NULL(err); + err = ray_parquet_range(r,x,pass ? 40 : 4,pass ? 70 : 7); + TEST_ASSERT_NULL(err); + int64_t count = 0; + for (;;) { + ray_t* t = ray_parquet_next(r); + if (!t) break; + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_ncols(t),1); + count += ray_table_nrows(t); ray_release(t); + } + TEST_ASSERT_EQ_I(count,pass ? 0 : 6); + TEST_ASSERT_EQ_I(ray_parquet_groups_skipped(r),pass == 1 ? 2 : 0); + ray_parquet_close(r); + } + ray_release(cols); + PASS(); +} +static test_result_t test_pq_indexes(void) { + int64_t names[] = {ray_sym_intern("name",4),ray_sym_intern("wide",4)}; + int64_t x = ray_sym_intern("x",1); + ray_t* cols = ray_vec_from_raw(RAY_SYM,names,2); + const char* files[] = {"indexed-v1.parquet","indexed-v2.parquet","indexed-v1-bad.parquet","indexed-v2-bad.parquet"}; + for (int file = 0; file < 4; file++) for (int batch = 1; batch <= 11; batch++) { + char path[128]; snprintf(path,sizeof(path),FIX "%s",files[file]); + ray_parquet_t* r = NULL; + TEST_ASSERT_NULL(ray_parquet_open(path,cols,batch,&r)); + TEST_ASSERT_NULL(ray_parquet_range(r,x,4,5)); + int64_t count = 0; + for (;;) { + ray_t* t = ray_parquet_next(r); if (!t) break; + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + ray_t* wide = ray_table_get_col_idx(t,1); + for (int64_t row = 0; row < wide->len; row++,count++) { + TEST_ASSERT_EQ_I(((int64_t*)ray_data(wide))[row],103+count%2); + size_t n; const char* p = ray_str_vec_get(ray_table_get_col_idx(t,0),row,&n); + TEST_ASSERT_EQ_I(n,count%2 ? 5 : 0); + if (n) TEST_ASSERT_TRUE(!memcmp(p,"alpha",5)); + } + ray_release(t); + } + TEST_ASSERT_EQ_I(count,4); + TEST_ASSERT_EQ_I(ray_parquet_groups_skipped(r),0); + if (file < 2) TEST_ASSERT_TRUE(ray_parquet_pages_skipped(r) > 0); + else TEST_ASSERT_EQ_I(ray_parquet_pages_skipped(r),0); + ray_parquet_close(r); + } + ray_release(cols); + ray_parquet_t* r = NULL; + TEST_ASSERT_NULL(ray_parquet_open(FIX "indexed-null.parquet",NULL,2,&r)); + TEST_ASSERT_NULL(ray_parquet_range(r,x,0,10)); + int64_t count = 0; + for (;;) { + ray_t* t = ray_parquet_next(r); if (!t) break; + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + ray_t* v = ray_table_get_col_idx(t,1); + for (int64_t i = 0; i < v->len; i++,count++) TEST_ASSERT_EQ_I(((int64_t*)ray_data(v))[i],3+count); + ray_release(t); + } + TEST_ASSERT_EQ_I(count,3); TEST_ASSERT_TRUE(ray_parquet_pages_skipped(r) >= 2); + ray_parquet_close(r); + PASS(); +} +static test_result_t test_pq_bloom(void) { + int64_t x = ray_sym_intern("x",1), wide = ray_sym_intern("wide",4); + for (int bad = 0; bad < 2; bad++) for (int col = 0; col < 2; col++) for (int val = 1; val <= 9; val++) { + ray_parquet_t* r = NULL; + TEST_ASSERT_NULL(ray_parquet_open(bad ? FIX "bloom-bad.parquet" : FIX "bloom.parquet",NULL,2,&r)); + int64_t target = col ? 99+val : val; + TEST_ASSERT_NULL(ray_parquet_range(r,col ? wide : x,target,target)); + int64_t count = 0; + for (;;) { + ray_t* t = ray_parquet_next(r); if (!t) break; + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); count += ray_table_nrows(t); ray_release(t); + } + bool absent = !col && (val == 2 || val == 6); + TEST_ASSERT_EQ_I(count,absent ? 0 : 2); + TEST_ASSERT_EQ_I(ray_parquet_bloom_skipped(r),!bad && absent ? 2 : 0); + ray_parquet_close(r); + } + PASS(); +} +static test_result_t test_pq_parallel(void) { + ray_t* sentinels = ray_parquet_read(FIX "simd-sentinels.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(sentinels)); + for (int col = 0; col < 2; col++) { + ray_t* v = ray_table_get_col_idx(sentinels,col); + TEST_ASSERT_TRUE(v->attrs & RAY_ATTR_HAS_NULLS); + for (int i = 0; i < 39; i++) TEST_ASSERT_EQ_I(ray_vec_is_null(v,i),i%(col ? 5 : 7) == 0); + } + ray_release(sentinels); + for (int workers = 1; workers <= 3; workers += 2) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(workers),RAY_OK); + ray_parquet_t* r = NULL; + TEST_ASSERT_NULL(ray_parquet_open(FIX "parallel.parquet",NULL,8192,&r)); + int64_t count = 0; ray_t* retained = NULL; + for (;;) { + ray_t* t = ray_parquet_next(r); if (!t) break; + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + ray_t* x = ray_table_get_col_idx(t,0); ray_t* y = ray_table_get_col_idx(t,1); + for (int64_t i = 0; i < x->len; i++,count++) { + TEST_ASSERT_EQ_I(((int32_t*)ray_data(x))[i],count); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(y))[i],count*INT64_C(10000000001)); + char expect[10]; int n = snprintf(expect,sizeof(expect),"s%lld",(long long)(count%11)); + size_t len; const char* p = ray_str_vec_get(ray_table_get_col_idx(t,2),i,&len); + TEST_ASSERT_EQ_I(len,n); TEST_ASSERT_TRUE(!memcmp(p,expect,len)); + } + if (!retained) retained = t; else ray_release(t); + } + TEST_ASSERT_EQ_I(count,70003); + if (workers > 1) TEST_ASSERT_TRUE(ray_parquet_parallel_batches(r) > 0); + else TEST_ASSERT_EQ_I(ray_parquet_parallel_batches(r),0); + ray_parquet_close(r); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(retained,0)))[100],100); + ray_release(retained); + ray_pool_destroy(); + } + PASS(); +} +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); } + rmdir(dir); +} +static test_result_t test_pq_group_native(void) { + const char* names[] = {"x","y","s"}; + int64_t tids[] = {ray_sym_intern("I32",3),ray_sym_intern("I64",3),ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM,tids,3); + for (int cores = 1; cores <= 8; cores *= 2) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(cores),RAY_OK); + for (int sym = 0; sym < 2; sym++) { + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-groups-%d-%d-%d",(int)getpid(),cores,sym); + ray_t* result = ray_parquet_splayed_typed(FIX "row-groups.parquet",dir,sym ? types : NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); TEST_ASSERT_EQ_I(result->i64,44009); ray_release(result); + char domain[200]; snprintf(domain,sizeof(domain),"%s/.sym",dir); + ray_t* table = ray_read_splayed(dir,sym ? domain : NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(table)); TEST_ASSERT_EQ_I(ray_table_nrows(table),44009); + ray_t* strings = ray_table_get_col_idx(table,2); + TEST_ASSERT_EQ_I(strings->type,sym ? RAY_SYM : RAY_STR); + for (int64_t i = 0; i < 44009; i++) { + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(table,0)))[i],i); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(table,1)))[i],i%13 ? i*3 : NULL_I64); + char expected[64]; int n = snprintf(expected,sizeof(expected),"long pooled string row %lld",(long long)i); + size_t len; const char* text; + if (sym) { ray_t* atom = ray_sym_vec_cell(strings,i); text = ray_str_ptr(atom); len = ray_str_len(atom); } + else text = ray_str_vec_get(strings,i,&len); + TEST_ASSERT_EQ_I(len,n); TEST_ASSERT_TRUE(!memcmp(text,expected,len)); + } + ray_release(table); pq_remove_native(dir,names,3); + } + ray_t* table = ray_parquet_read(FIX "row-groups.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(table)); TEST_ASSERT_EQ_I(ray_table_nrows(table),44009); + for (int64_t i = 0; i < 44009; i++) TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(table,0)))[i],i); + ray_release(table); + ray_pool_destroy(); + } + ray_release(types); + const char* unames[] = {"day","ts","s"}; + int64_t units[] = {ray_sym_intern("UNIX_DATE",9),ray_sym_intern("UNIX_SECONDS",12),ray_sym_intern("SYM",3)}; + types = ray_vec_from_raw(RAY_SYM,units,3); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-unix-%d",(int)getpid()); + ray_t* result = ray_parquet_splayed_typed(FIX "unix.parquet",dir,types); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); ray_release(result); ray_release(types); + char domain[200]; snprintf(domain,sizeof(domain),"%s/.sym",dir); + ray_t* table = ray_read_splayed(dir,domain); TEST_ASSERT_FALSE(RAY_IS_ERR(table)); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(table,0)->type,RAY_DATE); + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(table,0)))[1],1); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(table,1)->type,RAY_TIMESTAMP); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(table,1)))[1],1000000000); + ray_release(table); pq_remove_native(dir,unames,3); + PASS(); +} +static test_result_t test_pq_native_edges(void) { + int64_t ids[] = {ray_sym_intern("I32",3),ray_sym_intern("I64",3),ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM,ids,3); + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(4),RAY_OK); + ray_t* t = ray_parquet_read(FIX "rle-runs.parquet",NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_nrows(t),24597); + for (int i = 0; i < 24597; i++) { + bool first = i%8199 < 4099; + TEST_ASSERT_EQ_I(((int32_t*)ray_data(ray_table_get_col_idx(t,0)))[i],first ? 7 : 9); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ray_table_get_col_idx(t,1)))[i],first ? 11 : 13); + size_t len; const char* text = ray_str_vec_get(ray_table_get_col_idx(t,2),i,&len); + TEST_ASSERT_EQ_I(len,first ? 24 : 0); + if (first) TEST_ASSERT_TRUE(!memcmp(text,"a repeated pooled string",24)); + } + ray_release(t); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-rle-%d",(int)getpid()); + t = ray_parquet_splayed_typed(FIX "rle-runs.parquet",dir,types); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); ray_release(t); ray_release(types); + char sym[200]; snprintf(sym,sizeof(sym),"%s/.sym",dir); + t = ray_read_splayed(dir,sym); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + for (int i = 0; i < 24597; i++) { + ray_t* text = ray_sym_vec_cell(ray_table_get_col_idx(t,2),i); + TEST_ASSERT_EQ_I(ray_str_len(text),i%8199 < 4099 ? 24 : 0); + } + ray_release(t); + const char* names[] = {"x","y","s"}; pq_remove_native(dir,names,3); + int64_t empty_ids[] = {ray_sym_intern("I32",3),ray_sym_intern("SYM",3),ray_sym_intern("I16",3), + ray_sym_intern("I64",3),ray_sym_intern("DATE",4),ray_sym_intern("TIMESTAMP",9),ray_sym_intern("F64",3)}; + types = ray_vec_from_raw(RAY_SYM,empty_ids,7); + snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-empty-native-%d",(int)getpid()); + t = ray_parquet_splayed_typed(FIX "empty.parquet",dir,types); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(t->i64,0); ray_release(t); + snprintf(sym,sizeof(sym),"%s/.sym",dir); + t = ray_read_splayed(dir,sym); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(ray_table_nrows(t),0); ray_release(t); + const char* enames[] = {"x","name","flag","wide","day","ts","f"}; pq_remove_native(dir,enames,7); + /* A corrupt worker must join the others and leave the final name absent. */ + t = ray_parquet_splayed_typed(FIX "projection.parquet",dir,types); + TEST_ASSERT_TRUE(RAY_IS_ERR(t)); ray_release(t); TEST_ASSERT_TRUE(access(dir,F_OK) != 0); + char partial[200]; snprintf(partial,sizeof(partial),"%s.parquet-partial",dir); pq_remove_native(partial,enames,7); + /* Typed partition import uses the same native epoch/width contract. */ + snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-typed-parts-%d",(int)getpid()); + t = ray_parquet_parted_typed(FIX "flat-1-v2.parquet",dir,"hits",types); + TEST_ASSERT_FALSE(RAY_IS_ERR(t)); TEST_ASSERT_EQ_I(t->i64,18); ray_release(t); + t = ray_read_parted(dir,"hits"); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_nrows(t),18); ray_release(t); + snprintf(sym,sizeof(sym),"%s/.sym",dir); + for (int part = 0; part < 2; part++) { + char leaf[200]; snprintf(leaf,sizeof(leaf),"%s/%d/hits",dir,part); + t = ray_read_splayed(leaf,sym); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_get_col_idx(t,1)->type,RAY_SYM); + TEST_ASSERT_EQ_I(ray_str_len(ray_sym_vec_cell(ray_table_get_col_idx(t,1),1)),31); + ray_release(t); pq_remove_native(leaf,enames,7); + snprintf(leaf,sizeof(leaf),"%s/%d",dir,part); rmdir(leaf); + } + pq_remove_native(dir,NULL,0); + ray_release(types); ray_pool_destroy(); + PASS(); +} + +static test_result_t test_pq_parted_symbols(void) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(8),RAY_OK); + int64_t ids[] = {ray_sym_intern("I32",3),ray_sym_intern("I64",3),ray_sym_intern("SYM",3)}; + ray_t* types = ray_vec_from_raw(RAY_SYM,ids,3); + char root[160],sym[200],leaf[200]; + snprintf(root,sizeof(root),"/tmp/rayforce-pq-parted-symbols-%d",(int)getpid()); + ray_t* result = ray_parquet_parted_typed(FIX "row-groups.parquet",root,"hits",types); + ray_release(types); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); TEST_ASSERT_EQ_I(result->i64,44009); ray_release(result); + snprintf(sym,sizeof(sym),"%s/.sym",root); + const int starts[] = {0,5003,15004,22005,27006,33007,39008,44009}; + const char* names[] = {"x","y","s"}; + /* Each group adds unique symbols concurrently. Reopen every partition + * after the import domain was released, including late dictionary entries. */ + for (int p = 0; p < 7; p++) { + snprintf(leaf,sizeof(leaf),"%s/%d/hits",root,p); + ray_t* t = ray_read_splayed(leaf,sym); TEST_ASSERT_FALSE(RAY_IS_ERR(t)); + TEST_ASSERT_EQ_I(ray_table_nrows(t),starts[p+1]-starts[p]); + ray_t* col = ray_table_get_col_idx(t,2); + for (int i = starts[p]; i < starts[p+1]; i++) { + char expected[64]; snprintf(expected,sizeof(expected),"long pooled string row %d",i); + ray_t* s = ray_sym_vec_cell(col,i-starts[p]); TEST_ASSERT_TRUE(s != NULL); + TEST_ASSERT_TRUE(!strcmp(ray_str_ptr(s),expected)); + } + ray_release(t); pq_remove_native(leaf,names,3); + snprintf(leaf,sizeof(leaf),"%s/%d",root,p); rmdir(leaf); + } + pq_remove_native(root,NULL,0); ray_pool_destroy(); PASS(); +} +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) +static void* pq_small_stack_worker(void* result) { + pq_setup(); + int64_t ids[] = {ray_sym_intern("I32",3),ray_sym_intern("I64",3),ray_sym_intern("SYM",3)}; + int64_t key = ray_sym_intern("types",5); + ray_t* values = ray_list_new(1); + ((ray_t**)ray_data(values))[0] = ray_vec_from_raw(RAY_SYM,ids,3); values->len = 1; + ray_t* options = ray_dict_new(ray_vec_from_raw(RAY_SYM,&key,1),values); + const char* files[] = {FIX "unix.parquet",FIX "rle-runs.parquet",FIX "row-groups.parquet"}; + const int64_t counts[] = {2,24597,44009}; + bool ok = true; + /* No pool: every dictionary/PLAIN page and batch is decoded on this + * deliberately small thread stack, including the nested dictionary path. */ + for (int f = 0; f < 3 && ok; f++) { + ray_t* t = ray_parquet_read(files[f],options); + ok = t && !RAY_IS_ERR(t) && ray_table_nrows(t) == counts[f]; + if (ok) { + ray_t* col = ray_table_get_col_idx(t,2); + for (int64_t i = 0; i < counts[f] && ok; i++) { + char expected[64]; + if (f == 0) snprintf(expected,sizeof(expected),"pooled string number %s",i ? "two" : "one"); + else if (f == 1) snprintf(expected,sizeof(expected),"%s",i%8199 < 4099 ? "a repeated pooled string" : ""); + else snprintf(expected,sizeof(expected),"long pooled string row %lld",(long long)i); + ray_t* text = ray_sym_vec_cell(col,i); + ok = text && !strcmp(ray_str_ptr(text),expected); + } + } + if (t) ray_release(t); + } + ray_release(options); pq_teardown(); *(bool*)result = ok; + return NULL; +} +#endif +/* Direct path: 7 uneven row groups merge into the whole-column zone; the + * unclustered column with nulls gets a hash. */ +static test_result_t test_pq_splayed_inline_indexes(void) { + const char* names[] = {"x","y"}; + for (int cores = 1; cores <= 4; cores *= 4) { + ray_pool_destroy(); TEST_ASSERT_EQ_I(ray_pool_init_total(cores),RAY_OK); + char dir[160]; snprintf(dir,sizeof(dir),"/tmp/rayforce-pq-zones-%d-%d",(int)getpid(),cores); + ray_t* result = ray_parquet_splayed_typed(FIX "zones.parquet",dir,NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(result)); TEST_ASSERT_EQ_I(result->i64,200000); ray_release(result); + ray_t* table = ray_read_splayed(dir,NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(table)); + ray_t* x = ray_table_get_col_idx(table,0); + TEST_ASSERT_EQ_I(ray_index_kind(x),RAY_IDX_CHUNK_ZONE); + ray_t* plain = ray_vec_from_raw(RAY_I32,ray_data(x),x->len); + ray_t* want = ray_index_chunk_zone_compute(plain,16); + TEST_ASSERT_TRUE(want && !RAY_IS_ERR(want)); + const ray_index_t* g = ray_index_payload(x->index); + const ray_index_t* w = ray_index_payload(want); + TEST_ASSERT_EQ_I(g->u.chunk_zone.n_chunks,4); + TEST_ASSERT_EQ_I(memcmp(ray_data(g->u.chunk_zone.mins),ray_data(w->u.chunk_zone.mins),4*8),0); + TEST_ASSERT_EQ_I(memcmp(ray_data(g->u.chunk_zone.maxs),ray_data(w->u.chunk_zone.maxs),4*8),0); + TEST_ASSERT_EQ_I(memcmp(ray_data(g->u.chunk_zone.aggs),ray_data(w->u.chunk_zone.aggs),12*8),0); + TEST_ASSERT_TRUE((g->u.chunk_zone.null_bits != NULL) == (w->u.chunk_zone.null_bits != NULL)); + 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); + ray_release(table); pq_remove_native(dir,names,2); + ray_pool_destroy(); + } + PASS(); +} + +static test_result_t test_pq_small_stack(void) { +#if !defined(RAY_OS_WINDOWS) && !defined(RAY_OS_WASM) + ray_pool_destroy(); + pthread_attr_t attr; pthread_t worker; bool ok = false; + TEST_ASSERT_EQ_I(pthread_attr_init(&attr),0); + int rc = pthread_attr_setstacksize(&attr,256*1024); + if (!rc) rc = pthread_create(&worker,&attr,pq_small_stack_worker,&ok); + pthread_attr_destroy(&attr); + TEST_ASSERT_EQ_I(rc,0); + TEST_ASSERT_EQ_I(pthread_join(worker,NULL),0); + TEST_ASSERT_TRUE(ok); + PASS(); +#else + SKIP("requires POSIX thread stack attributes"); +#endif +} +const test_entry_t parquet_entries[] = { + {"parquet/small_stack",test_pq_small_stack,NULL,NULL}, + {"parquet/parted_symbols",test_pq_parted_symbols,pq_setup,pq_teardown}, + {"parquet/snappy",test_pq_snappy,pq_setup,pq_teardown}, + {"parquet/batch_matrix",test_pq_matrix,pq_setup,pq_teardown}, + {"parquet/read_metadata",test_pq_read_meta,pq_setup,pq_teardown}, + {"parquet/corrupt",test_pq_corrupt,pq_setup,pq_teardown}, + {"parquet/native",test_pq_native,pq_setup,pq_teardown}, + {"parquet/indexes",test_pq_indexes,pq_setup,pq_teardown}, + {"parquet/bloom",test_pq_bloom,pq_setup,pq_teardown}, + {"parquet/native_edges",test_pq_native_edges,pq_setup,pq_teardown}, + {"parquet/group_native",test_pq_group_native,pq_setup,pq_teardown}, + {"parquet/splayed_inline_indexes",test_pq_splayed_inline_indexes,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_partition_exec.c b/test/test_partition_exec.c index 20600f969..0e5f54cc6 100644 --- a/test/test_partition_exec.c +++ b/test/test_partition_exec.c @@ -1440,7 +1440,8 @@ static test_result_t test_filter_head_zero_limit(void) { /* -------------------------------------------------------------------------- * Test 22: exec_filter_head — non-table / non-BOOL inputs (early returns) * - * Targets filter.c L397 (input->type != RAY_TABLE || pred->type != RAY_BOOL). + * Targets the exec_filter_head early returns: a non-table input is passed + * through; a non-BOOL predicate over a table is a type error. * -------------------------------------------------------------------------- */ static test_result_t test_filter_head_non_table(void) { ray_heap_init(); @@ -1457,7 +1458,9 @@ static test_result_t test_filter_head_non_table(void) { TEST_ASSERT_NOT_NULL(r1); TEST_ASSERT_FALSE(RAY_IS_ERR(r1)); - /* Non-BOOL pred with a real table */ + /* Non-BOOL pred with a real table: no mask, a type error (#678). It + * used to pass the whole table through, so `where: x take: k` over an + * I64 column returned every row. */ ray_t* col = ray_vec_new(RAY_I64, 5); col->len = 5; int64_t sym_d = ray_sym_intern("d", 1); @@ -1468,10 +1471,10 @@ static test_result_t test_filter_head_non_table(void) { non_bool_pred->len = 5; ray_t* r2 = exec_filter_head(tbl, non_bool_pred, 3); TEST_ASSERT_NOT_NULL(r2); - TEST_ASSERT_FALSE(RAY_IS_ERR(r2)); + TEST_ASSERT_TRUE(RAY_IS_ERR(r2)); ray_release(r1); - ray_release(r2); + ray_error_free(r2); ray_release(pred); ray_release(non_bool_pred); ray_release(tbl); diff --git a/test/test_platform.c b/test/test_platform.c index be7be945b..4e0e0abed 100644 --- a/test/test_platform.c +++ b/test/test_platform.c @@ -94,6 +94,25 @@ static test_result_t test_thread_create_join(void) { PASS(); } +/* ---- test_cgroup_mem_limit --------------------------------------------- */ + +/* The probe must be defensive: never negative, and never larger than the + * host's physical RAM when a container limit is in force. Whether a limit + * IS in force depends on how the suite is launched (docker --memory, + * systemd MemoryMax), so only the invariants are asserted here; the + * limited case is verified by hand with `systemd-run --scope -p MemoryMax` + * (issue #688). */ +static test_result_t test_cgroup_mem_limit(void) { + int64_t cg = ray_os_cgroup_mem_limit(); + TEST_ASSERT(cg >= 0, "cgroup limit is never negative"); + /* A second probe reads the same files and must agree. */ + TEST_ASSERT_EQ_I(ray_os_cgroup_mem_limit(), cg); +#ifndef RAY_OS_LINUX + TEST_ASSERT_EQ_I(cg, 0); +#endif + PASS(); +} + /* ---- Suite definition -------------------------------------------------- */ const test_entry_t platform_entries[] = { @@ -101,6 +120,7 @@ const test_entry_t platform_entries[] = { { "platform/vm_alloc_aligned", test_vm_alloc_aligned, NULL, NULL }, { "platform/thread_count", test_thread_count, NULL, NULL }, { "platform/thread_create_join", test_thread_create_join, NULL, NULL }, + { "platform/cgroup_mem_limit", test_cgroup_mem_limit, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; diff --git a/test/test_pool.c b/test/test_pool.c index 6a3069f14..86472f36b 100644 --- a/test/test_pool.c +++ b/test/test_pool.c @@ -1131,6 +1131,198 @@ static test_result_t test_dispatch_n_exact_cap(void) { PASS(); } +/* ========================================================================== + * Claim-protocol tests: every ticket exactly once, under both claiming modes + * + * RAY_POOL_STEAL selects, at pool creation, the shared bounded-CAS cursor (0) + * or per-worker contiguous ranges with tail stealing (1). The pool has had + * cross-dispatch claim races before, so each mode is driven through thousands + * of back-to-back windows of every awkward shape — tiny n, n below / at / + * above the worker count, n far above it through both entry points, and a + * dispatch_n wider than the ring (several rounds) — with uneven per-ticket + * work so that owners and thieves really meet on the words. A ticket hit + * twice or never is the failure; a lost ticket would also hang the dispatch, + * which the harness watchdog reports as a hung test. + * ========================================================================== */ + +#if defined(__linux__) || defined(__APPLE__) + +/* Create a pool under a given RAY_POOL_STEAL value, restoring the variable + * afterwards (the switch is read once, at creation). */ +static ray_err_t pool_create_mode(ray_pool_t* pool, uint32_t n_workers, bool steal) { + const char* cur = getenv("RAY_POOL_STEAL"); + char* saved = cur ? strdup(cur) : NULL; + setenv("RAY_POOL_STEAL", steal ? "1" : "0", 1); + ray_err_t rc = ray_pool_create(pool, n_workers); + if (saved) { setenv("RAY_POOL_STEAL", saved, 1); free(saved); } + else unsetenv("RAY_POOL_STEAL"); + return rc; +} + +#define POOL_ONCE_MAX 70000u +#define POOL_ONCE_GRAIN ((int64_t)RAY_DISPATCH_MORSELS * RAY_MORSEL_ELEMS) /* = TASK_GRAIN */ + +static _Atomic(uint32_t) pool_once_hits[POOL_ONCE_MAX]; /* per-ticket hit count */ + +typedef struct { + int64_t grain; /* elements per ticket: 1 (dispatch_n) or TASK_GRAIN */ + 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 */ +} pool_once_ctx_t; + +static void pool_once_fn(void* ctx, uint32_t worker_id, int64_t start, int64_t end) { + (void)worker_id; + pool_once_ctx_t* c = (pool_once_ctx_t*)ctx; + uint32_t t = (uint32_t)(start / c->grain); + /* Uneven, deterministic per-ticket work (0..16k iterations) so claims + * and steals interleave instead of every ticket finishing at once. */ + volatile uint32_t sink = 0; + uint32_t spin = ((t * 2654435761u) >> 24) << 6; + for (uint32_t i = 0; i < spin; i++) sink += i; + (void)sink; + /* The blocking ticket finishes last: it waits on observable state (every + * 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) + 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) { + for (uint32_t t = 0; t < n; t++) + atomic_store_explicit(&pool_once_hits[t], 0, memory_order_relaxed); + c->grain = grain; + c->n = n; + atomic_store_explicit(&c->done, 0, memory_order_relaxed); +} + +/* First ticket in [0, n) whose hit count is not exactly one, or -1. */ +static int64_t pool_once_bad(uint32_t n) { + for (uint32_t t = 0; t < n; t++) + if (atomic_load_explicit(&pool_once_hits[t], memory_order_relaxed) != 1) return t; + return -1; +} + +/* One window through the chosen entry point, then the exactly-once check + * 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); + else ray_pool_dispatch_n(pool, pool_once_fn, c, n); + *tickets += n; + TEST_ASSERT_EQ_U(atomic_load(&c->done), n); + int64_t bad = pool_once_bad(n); + TEST_ASSERT_FMT(bad < 0, "ticket %lld of %u hit %u times (steal=%u, workers=%u, %s)", + (long long)bad, n, bad < 0 ? 0u : atomic_load(&pool_once_hits[bad]), + pool->steal, pool->n_workers, elem_form ? "dispatch" : "dispatch_n"); + TEST_ASSERT_EQ_U(atomic_load(&pool->task_claim), atomic_load(&pool->task_limit)); + PASS(); +} + +#define POOL_ONCE_RUN(pool, c, n, elem, tk) do { \ + test_result_t _r = pool_once_window((pool), (c), (n), (elem), (tk)); \ + if (_r.status != TEST_PASS) return _r; \ + } while (0) + +/* The window battery over one pool: every awkward shape, many times over. */ +static test_result_t pool_once_battery(ray_pool_t* pool) { + uint32_t W = ray_pool_total_workers(pool); + pool_once_ctx_t c = { .block = UINT32_MAX }; + uint64_t tickets = 0; + + /* thousands of back-to-back tiny windows: the cross-dispatch race bed */ + for (uint32_t i = 0; i < 3000; i++) + POOL_ONCE_RUN(pool, &c, 1 + i % 3, false, &tickets); + + /* n below, at and just above the worker count, and a few multiples */ + for (uint32_t i = 0; i < 300; i++) { + if (W > 1) POOL_ONCE_RUN(pool, &c, W - 1, false, &tickets); + POOL_ONCE_RUN(pool, &c, W, false, &tickets); + POOL_ONCE_RUN(pool, &c, W + 1, false, &tickets); + POOL_ONCE_RUN(pool, &c, 2 * W + 1, i & 1, &tickets); + } + + /* n far above the worker count, both entry points */ + for (uint32_t i = 0; i < 60; i++) { + POOL_ONCE_RUN(pool, &c, 1000, false, &tickets); + POOL_ONCE_RUN(pool, &c, 1000, true, &tickets); + } + + /* more tasks than the ring can ever hold: several dispatch_n rounds */ + POOL_ONCE_RUN(pool, &c, POOL_ONCE_MAX, false, &tickets); + + /* Accounting: in steal mode every ticket was claimed from an own range + * or stolen, nothing else; the cursor path never touches the counters. */ + uint64_t own = 0, stolen = 0; + for (uint32_t w = 0; w < W; w++) { own += pool->slots[w].own; stolen += pool->slots[w].stolen; } + if (pool->steal) TEST_ASSERT_EQ_U(own + stolen, tickets); + else TEST_ASSERT_EQ_U(own + stolen, 0u); + PASS(); +} + +static test_result_t pool_once_mode(bool steal) { + ray_heap_init(); + static const uint32_t workers[] = { 3, 0, 6 }; /* W = 4, 1 (main only), 7 */ + for (size_t i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { + ray_pool_t pool; + TEST_ASSERT_EQ_I(pool_create_mode(&pool, workers[i], steal), RAY_OK); + TEST_ASSERT_EQ_U(pool.steal, steal ? 1u : 0u); + test_result_t r = pool_once_battery(&pool); + ray_pool_free(&pool); + if (r.status != TEST_PASS) return r; + } + ray_heap_destroy(); + PASS(); +} + +static test_result_t test_claim_once_cursor(void) { return pool_once_mode(false); } +static test_result_t test_claim_once_steal(void) { return pool_once_mode(true); } + +/* -------------------------------------------------------------------------- + * Test: stealing is forced, not left to scheduling luck. + * + * Ticket 0 heads main's own range and waits until every other ticket is + * done. Main is stuck in it, so the rest of main's share can only run if + * the workers cut it from the tail — with ranges the window cannot complete + * otherwise (a hang the watchdog would report). Should a worker beat main + * to ticket 0 instead, it did so by stealing it, so `stolen` is positive + * either way. The cursor mode runs the same window as a control: there the + * remaining tickets are simply claimed from the shared cursor. + * -------------------------------------------------------------------------- */ +static test_result_t pool_steal_forced_mode(bool steal) { + ray_heap_init(); + ray_pool_t pool; + TEST_ASSERT_EQ_I(pool_create_mode(&pool, 3, steal), RAY_OK); + + pool_once_ctx_t c = { .block = 0 }; + uint64_t tickets = 0; + for (int rep = 0; rep < 8; rep++) + POOL_ONCE_RUN(&pool, &c, 4000, rep & 1, &tickets); + + uint64_t own = 0, stolen = 0, steals = 0; + for (uint32_t w = 0; w < ray_pool_total_workers(&pool); w++) { + own += pool.slots[w].own; stolen += pool.slots[w].stolen; steals += pool.slots[w].steals; + } + if (steal) { + TEST_ASSERT_EQ_U(own + stolen, tickets); + TEST_ASSERT_FMT(stolen > 0 && steals > 0, "no steal in %llu windows", (unsigned long long)8); + } else { + TEST_ASSERT_EQ_U(own + stolen + steals, 0u); + } + + ray_pool_free(&pool); + ray_heap_destroy(); + PASS(); +} + +static test_result_t test_steal_forced(void) { return pool_steal_forced_mode(true); } +static test_result_t test_steal_forced_cursor(void) { return pool_steal_forced_mode(false); } + +#endif /* __linux__ || __APPLE__ */ + /* ========================================================================== * Bounded poll-step tests * ========================================================================== */ @@ -1494,6 +1686,10 @@ const test_entry_t pool_entries[] = { { "pool/dispatch_n_multi_grow", test_dispatch_n_multi_grow, NULL, NULL }, { "pool/dispatch_n_exact_cap", test_dispatch_n_exact_cap, NULL, NULL }, #if defined(__linux__) || defined(__APPLE__) + { "pool/claim_once_cursor", test_claim_once_cursor, NULL, NULL }, + { "pool/claim_once_steal", test_claim_once_steal, NULL, NULL }, + { "pool/steal_forced", test_steal_forced, NULL, NULL }, + { "pool/steal_forced_cursor", test_steal_forced_cursor, NULL, NULL }, { "pool/poll_run_for_zero_drains_ready_event", test_poll_run_for_zero_drains_ready_event, NULL, NULL }, { "pool/poll_run_for_positive_timeout", test_poll_run_for_positive_timeout, NULL, NULL }, #endif diff --git a/test/test_runtime.c b/test/test_runtime.c index e6bb4f068..d100fdb0f 100644 --- a/test/test_runtime.c +++ b/test/test_runtime.c @@ -30,6 +30,8 @@ #include "core/sock.h" /* ray_sock_* */ #include "core/poll.h" /* ray_poll_t, ray_poll_create/destroy */ #include "core/timer.h" /* ray_timers_t, ray_timers_pump_for */ +#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 #include @@ -314,6 +316,29 @@ static test_result_t test_oom_sentinel_is_well_formed(void) { PASS(); } +/* The default anon watermark is the RAM this process may actually use: + * physical RAM, capped by a container / cgroup limit when one is set + * (#688). It must be positive and never above physical RAM, and the heap's + * default watermark must resolve to it. */ +static test_result_t test_ram_limit_caps_total_ram(void) { + ray_err_t err = RAY_OK; + ray_runtime_t* rt = ray_runtime_create_with_sym_err(NULL, &err); + TEST_ASSERT_NOT_NULL(rt); + int64_t phys = ray_sys_total_ram(); + int64_t limit = ray_sys_ram_limit(); + TEST_ASSERT(phys > 0, "physical RAM detected"); + TEST_ASSERT(limit > 0, "ram limit detected"); + TEST_ASSERT(limit <= phys, "ram limit never exceeds physical RAM"); + int64_t cg = ray_os_cgroup_mem_limit(); + TEST_ASSERT_EQ_I(limit, (cg > 0 && cg < phys) ? cg : phys); + int64_t previous = ray_heap_anon_watermark(); + ray_heap_set_anon_watermark(0); /* 0 = default */ + TEST_ASSERT_EQ_I(ray_heap_anon_watermark(), limit); + ray_heap_set_anon_watermark(previous == limit ? 0 : previous); + ray_runtime_destroy(rt); + PASS(); +} + /* ---- sock.c coverage helpers ---------------------------------------- */ /* ray_sock_close must silently ignore RAY_INVALID_SOCK without crashing. @@ -1239,6 +1264,30 @@ static test_result_t test_syscov_hclose_type_error(void) { PASS(); } +/* .csv.parted into a new root whose .csv-partial is left from an + * earlier failed import: the error names the directory to remove. */ +static test_result_t test_syscov_csv_parted_stale_staging(void) { + char root[128], staging[160], csv[160], src[512]; + snprintf(root, sizeof(root), "/tmp/rfcov-pstage-%d", (int)getpid()); + snprintf(staging, sizeof(staging), "%s.csv-partial", root); + snprintf(csv, sizeof(csv), "%s.csv", root); + FILE* f = fopen(csv, "wb"); + TEST_ASSERT_NOT_NULL(f); + fputs("a,b\n1,x\n", f); + fclose(f); + TEST_ASSERT_EQ_I(mkdir(staging, 0755), 0); + snprintf(src, sizeof(src), "(.csv.parted \"%s\" \"%s\" 'tbl)", csv, root); + ray_t* e = ray_eval_str(src); + TEST_ASSERT_TRUE(e && RAY_IS_ERR(e)); + TEST_ASSERT_STR_EQ(ray_err_code(e), "io"); + const char* msg = ray_error_msg(); + TEST_ASSERT_TRUE(msg && strstr(msg, staging) && strstr(msg, "remove it to retry")); + ray_error_free(e); + rmdir(staging); + unlink(csv); + PASS(); +} + /* hsend type errors (ray_hsend_fn) */ static test_result_t test_syscov_hsend_type_errors(void) { /* handle not integer */ @@ -1298,6 +1347,7 @@ const test_entry_t runtime_entries[] = { { "runtime/lambda_self_sym_per_runtime", test_lambda_self_sym_per_runtime, NULL, NULL }, { "runtime/create_with_sym_oversized_file", test_create_with_sym_oversized_file, NULL, NULL }, { "runtime/oom_sentinel_is_well_formed", test_oom_sentinel_is_well_formed, NULL, NULL }, + { "runtime/ram_limit_caps_total_ram", test_ram_limit_caps_total_ram, NULL, NULL }, { "runtime/sock_close_invalid", test_sock_close_invalid, NULL, NULL }, { "runtime/sock_listen_bind_fails_eaddrinuse", test_sock_listen_bind_fails_eaddrinuse, NULL, NULL }, { "runtime/sock_connect_bad_host", test_sock_connect_bad_host, NULL, NULL }, @@ -1334,6 +1384,7 @@ const test_entry_t runtime_entries[] = { { "runtime/syscov_hopen_with_credentials", test_syscov_hopen_with_credentials, sys_setup, sys_teardown }, { "runtime/syscov_hclose_type_error", test_syscov_hclose_type_error, sys_setup, sys_teardown }, { "runtime/syscov_hsend_type_errors", test_syscov_hsend_type_errors, sys_setup, sys_teardown }, + { "runtime/syscov_csv_parted_stale_staging", test_syscov_csv_parted_stale_staging, sys_setup, sys_teardown }, { "runtime/syscov_splayed_set_sym_path", test_syscov_splayed_set_with_sym_path, sys_setup, sys_teardown }, { "runtime/syscov_splayed_get_sym_path", test_syscov_splayed_get_with_sym_path, sys_setup, sys_teardown }, diff --git a/test/test_splay.c b/test/test_splay.c index d037cf5eb..346f3fd75 100644 --- a/test/test_splay.c +++ b/test/test_splay.c @@ -49,6 +49,7 @@ #include #include #include +#include #include /* ---- Setup / Teardown -------------------------------------------------- */ @@ -859,6 +860,35 @@ static test_result_t test_save_bulk_with_sym_path(void) { PASS(); } +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"; + rm_rf(dir); + unlink(sym_path); + + int64_t id_s = ray_sym_intern("wsym", 4); + int64_t sval = ray_sym_intern("wv1", 3); + ray_t* scol = ray_sym_vec_new(RAY_SYM_W8, 2); + TEST_ASSERT_FALSE(RAY_IS_ERR(scol)); + scol->len = 2; + ((uint8_t*)ray_data(scol))[0] = (uint8_t)sval; + ((uint8_t*)ray_data(scol))[1] = (uint8_t)sval; + + ray_t* tbl = ray_table_new(1); + tbl = ray_table_add_col(tbl, id_s, scol); + TEST_ASSERT_FALSE(RAY_IS_ERR(tbl)); + + ray_err_t err = ray_splay_save_staged_bulk(tbl, dir, sym_path); + TEST_ASSERT_EQ_I(err, RAY_OK); + TEST_ASSERT_EQ_I(access(sym_path, F_OK), -1); + + ray_release(scol); + ray_release(tbl); + rm_rf(dir); + unlink(sym_path); + PASS(); +} + /* ========================================================================= * 19. splay_save_impl: snprintf overflow for the column / ".d" paths. * Requires strlen(dir) >= 1021 so that strlen(dir)+3 >= 1024. @@ -1309,8 +1339,8 @@ static test_result_t test_selfdescribing_schema_fresh_process(void) { } /* ========================================================================= - * 29. Crash-safe save: (a) re-set with a NARROWER schema removes stale - * column files; (b) symbol-free tables write no symfile even when a + * 29. Crash-safe save: (a) re-set with a NARROWER schema retains old + * column files for readers; (b) symbol-free tables write no symfile even when a * sym_path is supplied; (c) .d is the commit marker — written last. * ========================================================================= */ static test_result_t test_save_sweeps_stale_and_skips_sym(void) { @@ -1343,10 +1373,10 @@ static test_result_t test_save_sweeps_stale_and_skips_sym(void) { TEST_ASSERT_FALSE(RAY_IS_ERR(narrow)); TEST_ASSERT_EQ_I(ray_splay_save(narrow, dir, NULL), RAY_OK); - /* (a) stale column file "b" must be gone; load sees 1 column */ + /* Old readers can still open b; the new generation has only a. */ char bpath[512]; snprintf(bpath, sizeof(bpath), "%s/b", dir); - TEST_ASSERT_EQ_I(access(bpath, F_OK), -1); + TEST_ASSERT_EQ_I(access(bpath, F_OK), 0); ray_t* loaded = ray_splay_load(dir, NULL); TEST_ASSERT_NOT_NULL(loaded); TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); @@ -2372,7 +2402,378 @@ static test_result_t test_splayed_has_nulls_roundtrip(void) { PASS(); } +/* A replacement must be published as one generation. The failed replacement + * 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"; + char manifest[512]; + int n = snprintf(manifest, sizeof(manifest), "%s/.current", dir); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(manifest)); + (void)ray_test_rm_rf(dir); + + int64_t x_id = ray_sym_intern("x", 1); + int64_t y_id = ray_sym_intern("y", 1); + int64_t old_x_raw[] = {1, 2}; + int64_t old_y_raw[] = {10, 20}; + ray_t* old_x = ray_vec_from_raw(RAY_I64, old_x_raw, 2); + ray_t* old_y = ray_vec_from_raw(RAY_I64, old_y_raw, 2); + ray_t* old = ray_table_new(2); + old = ray_table_add_col(old, x_id, old_x); + old = ray_table_add_col(old, y_id, old_y); + TEST_ASSERT_FALSE(RAY_IS_ERR(old)); + TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(access(manifest, F_OK), -1); + + int64_t new_x_raw[] = {3, 4}; + int64_t new_y_raw[] = {30, 40}; + ray_t* new_x = ray_vec_from_raw(RAY_I64, new_x_raw, 2); + ray_t* new_y = ray_vec_from_raw(RAY_I64, new_y_raw, 2); + ray_t* replacement = ray_table_new(2); + replacement = ray_table_add_col(replacement, x_id, new_x); + replacement = ray_table_add_col(replacement, y_id, new_y); + TEST_ASSERT_FALSE(RAY_IS_ERR(replacement)); + TEST_ASSERT_EQ_I(ray_splay_save(replacement, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(access(manifest, F_OK), 0); + char legacy_schema[512]; + n = snprintf(legacy_schema, sizeof(legacy_schema), "%s/.d", dir); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(legacy_schema)); + TEST_ASSERT_EQ_I(access(legacy_schema, F_OK), -1); + + ray_t* loaded = ray_splay_load(dir, NULL); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + ray_t* loaded_x = ray_table_get_col(loaded, x_id); + ray_t* loaded_y = ray_table_get_col(loaded, y_id); + TEST_ASSERT_NOT_NULL(loaded_x); + TEST_ASSERT_NOT_NULL(loaded_y); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(loaded_x))[0], 3); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(loaded_y))[0], 30); + ray_release(loaded); + + ray_t* bad_col = ray_dict_new(ray_vec_from_raw(RAY_I64, old_x_raw, 2), + ray_vec_from_raw(RAY_I64, old_y_raw, 2)); + ray_t* bad = ray_table_new(2); + bad = ray_table_add_col(bad, x_id, old_x); + bad = ray_table_add_col(bad, y_id, old_y); + ray_table_set_col_idx(bad, 1, bad_col); + TEST_ASSERT_FALSE(RAY_IS_ERR(bad)); + ray_err_t bad_err = ray_splay_save(bad, dir, NULL); + TEST_ASSERT_EQ_I(bad_err, RAY_ERR_NYI); + + loaded = ray_read_splayed(dir, NULL); + TEST_ASSERT_NOT_NULL(loaded); + TEST_ASSERT_FALSE(RAY_IS_ERR(loaded)); + loaded_x = ray_table_get_col(loaded, x_id); + loaded_y = ray_table_get_col(loaded, y_id); + TEST_ASSERT_NOT_NULL(loaded_x); + TEST_ASSERT_NOT_NULL(loaded_y); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(loaded_x))[0], 3); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(loaded_y))[0], 30); + ray_release(loaded); + + ray_release(bad); + ray_release(bad_col); + ray_release(replacement); + ray_release(new_x); + ray_release(new_y); + ray_release(old); + ray_release(old_x); + ray_release(old_y); + (void)ray_test_rm_rf(dir); + PASS(); +} + +static ray_t* generation_pair(int64_t value) { + int64_t x[] = {value, value + 1}; + int64_t y[] = {value * 10, (value + 1) * 10}; + ray_t* xc = ray_vec_from_raw(RAY_I64, x, 2); + ray_t* yc = ray_vec_from_raw(RAY_I64, y, 2); + ray_t* t = ray_table_new(2); + t = ray_table_add_col(t, ray_sym_intern("x", 1), xc); + t = ray_table_add_col(t, ray_sym_intern("y", 1), yc); + ray_release(xc); + ray_release(yc); + return t; +} + +static bool generation_matches(const char* dir, bool mmap, int64_t value) { + ray_t* t = mmap ? ray_read_splayed(dir, NULL) : ray_splay_load(dir, NULL); + if (!t || RAY_IS_ERR(t)) { if (t) ray_release(t); return false; } + ray_t* x = ray_table_get_col(t, ray_sym_intern("x", 1)); + ray_t* y = ray_table_get_col(t, ray_sym_intern("y", 1)); + bool ok = x && y && x->len == 2 && y->len == 2 && + x->type == RAY_I64 && y->type == RAY_I64; + if (ok) { + const int64_t* xd = ray_data(x); + const int64_t* yd = ray_data(y); + ok = xd[0] == value && xd[1] == value + 1 && + yd[0] == value * 10 && yd[1] == (value + 1) * 10; + } + ray_release(t); + return ok; +} + +static int generation_dir_count(const char* dir) { + char path[1024]; + int n = snprintf(path, sizeof(path), "%s/.generations", dir); + if (n < 0 || (size_t)n >= sizeof(path)) return -1; + DIR* d = opendir(path); + if (!d) return 0; + int count = 0; + struct dirent* entry; + while ((entry = readdir(d))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + char child[1024]; + n = snprintf(child, sizeof(child), "%s/%s", path, entry->d_name); + if (n < 0 || (size_t)n >= sizeof(child)) continue; + struct stat st; + if (stat(child, &st) == 0 && S_ISDIR(st.st_mode)) count++; + } + closedir(d); + return count; +} + +#ifndef _WIN32 +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"; + 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); + + char current[1024], generations[1024], prune_dir[1024]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, current, sizeof(current)), RAY_OK); + int n = snprintf(generations, sizeof(generations), "%s/.generations", dir); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(generations)); + DIR* d = opendir(generations); + TEST_ASSERT_NOT_NULL(d); + prune_dir[0] = '\0'; + struct dirent* entry; + while ((entry = readdir(d))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) + continue; + char full[1024]; + n = snprintf(full, sizeof(full), "%s/%s", generations, entry->d_name); + TEST_ASSERT_TRUE(n > 0 && (size_t)n < sizeof(full)); + if (strcmp(full, current) != 0) { + snprintf(prune_dir, sizeof(prune_dir), "%s", full); + break; + } + } + closedir(d); + TEST_ASSERT_TRUE(prune_dir[0] != '\0'); + + 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]; + n = snprintf(link_path, sizeof(link_path), "%s/outside", prune_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_save(four, dir, NULL), RAY_OK); + TEST_ASSERT_EQ_I(access(victim_file, F_OK), 0); + TEST_ASSERT_EQ_I(access(prune_dir, F_OK), -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"; + rm_rf(dir); + ray_t* old = generation_pair(1); + ray_t* next = generation_pair(9); + TEST_ASSERT_FALSE(RAY_IS_ERR(old)); + TEST_ASSERT_FALSE(RAY_IS_ERR(next)); + for (int era = 0; era < 2; era++) { + /* Exercise both legacy -> generation and generation -> generation. */ + TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); + char before[1024], after[1024], obstruction[1100], first_col[1100]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, before, sizeof(before)), RAY_OK); + ray_splay_write_t write; + TEST_ASSERT_EQ_I(ray_splay_write_begin(dir, &write), RAY_OK); + snprintf(obstruction, sizeof(obstruction), "%s/y", write.dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(obstruction), 0); + ray_err_t err = ray_splay_write_table(next, write.dir, NULL, true); + err = ray_splay_write_finish(&write, err, true); + TEST_ASSERT_EQ_I(err, RAY_ERR_IO); + snprintf(first_col, sizeof(first_col), "%s/x", write.dir); + TEST_ASSERT_EQ_I(access(first_col, F_OK), -1); + TEST_ASSERT_TRUE(generation_matches(dir, false, 1)); + TEST_ASSERT_TRUE(generation_matches(dir, true, 1)); + + TEST_ASSERT_EQ_I(ray_splay_write_begin(dir, &write), RAY_OK); + err = ray_splay_write_table(next, write.dir, NULL, true); + if (err != RAY_OK) (void)ray_splay_write_finish(&write, err, true); + TEST_ASSERT_EQ_I(err, RAY_OK); + /* A directory cannot be opened as the manifest's temporary file. */ + snprintf(obstruction, sizeof(obstruction), "%s/.current.tmp", write.dir); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(obstruction), 0); + TEST_ASSERT_EQ_I(ray_splay_write_finish(&write, RAY_OK, true), RAY_ERR_IO); + TEST_ASSERT_TRUE(generation_matches(dir, false, 1)); + TEST_ASSERT_TRUE(generation_matches(dir, true, 1)); + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, after, sizeof(after)), RAY_OK); + TEST_ASSERT_TRUE(strcmp(before, after) == 0); +#ifndef _WIN32 + if (geteuid() != 0) { + /* Temp creation succeeds inside the stage; publication itself + * fails when rename cannot modify the table root. */ + TEST_ASSERT_EQ_I(ray_splay_write_begin(dir, &write), RAY_OK); + err = ray_splay_write_table(next, write.dir, NULL, true); + if (err != RAY_OK) (void)ray_splay_write_finish(&write, err, true); + TEST_ASSERT_EQ_I(err, RAY_OK); + TEST_ASSERT_EQ_I(chmod(dir, 0555), 0); + err = ray_splay_write_finish(&write, RAY_OK, true); + int restored = chmod(dir, 0755); + TEST_ASSERT_EQ_I(restored, 0); + TEST_ASSERT_EQ_I(err, RAY_ERR_IO); + TEST_ASSERT_TRUE(generation_matches(dir, true, 1)); + } +#endif + } + /* Failure must also release the writer lock so a retry can commit. */ + TEST_ASSERT_EQ_I(ray_splay_save(next, dir, NULL), RAY_OK); + TEST_ASSERT_TRUE(generation_matches(dir, true, 9)); + TEST_ASSERT_TRUE(generation_dir_count(dir) <= 2); + ray_release(next); + ray_release(old); + rm_rf(dir); + PASS(); +} + +static test_result_t test_generation_retains_readers(void) { + const char* dir = TMP_SPLAY_BASE "/generation_readers"; + rm_rf(dir); + ray_t* old = generation_pair(1); + ray_t* next = generation_pair(9); + TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); + for (int era = 0; era < 2; era++) { + char resolved[1024], path[1100]; + TEST_ASSERT_EQ_I(ray_splay_resolve_dir(dir, resolved, sizeof(resolved)), RAY_OK); + ray_t* pinned = ray_read_splayed(dir, NULL); + TEST_ASSERT_FALSE(RAY_IS_ERR(pinned)); + TEST_ASSERT_EQ_I(ray_splay_save(next, dir, NULL), RAY_OK); + /* Reader resolved the old path before publication but opens a column + * afterwards. Both the on-disk file and an existing mmap must survive. */ + snprintf(path, sizeof(path), "%s/y", resolved); + ray_t* late = ray_col_load(path); + TEST_ASSERT_NOT_NULL(late); + TEST_ASSERT_FALSE(RAY_IS_ERR(late)); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(late))[0], 10); + ray_release(late); + ray_t* py = ray_table_get_col(pinned, ray_sym_intern("y", 1)); + TEST_ASSERT_NOT_NULL(py); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(py))[0], 10); + ray_release(pinned); + TEST_ASSERT_TRUE(generation_matches(dir, false, 9)); + TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); + } + TEST_ASSERT_TRUE(generation_dir_count(dir) <= 2); + ray_release(next); + ray_release(old); + rm_rf(dir); + PASS(); +} + +static test_result_t test_generation_invalid_manifest(void) { + const char* dir = 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"); + TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_TRUE(fputs(invalid[i], f) >= 0); + TEST_ASSERT_EQ_I(fclose(f), 0); + ray_t* loaded = ray_splay_load(dir, NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(loaded)); + TEST_ASSERT_STR_EQ(ray_err_code(loaded), "corrupt"); + ray_release(loaded); + loaded = ray_read_splayed_dom(dir, NULL); + TEST_ASSERT_TRUE(RAY_IS_ERR(loaded)); + TEST_ASSERT_STR_EQ(ray_err_code(loaded), "corrupt"); + ray_release(loaded); + } + ray_release(t); + rm_rf(dir); + PASS(); +} + +static test_result_t test_generation_writer_exit(void) { + const char* dir = TMP_SPLAY_BASE "/generation_exit"; + rm_rf(dir); + ray_t* old = generation_pair(1); + ray_t* next = generation_pair(9); + TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); + for (int complete = 0; complete < 2; complete++) { + ray_splay_write_t wr; + TEST_ASSERT_EQ_I(ray_splay_write_begin(dir, &wr), RAY_OK); + ray_err_t err; + if (complete) { + err = ray_splay_write_table(next, wr.dir, NULL, true); + } else { + char path[1100]; + snprintf(path, sizeof(path), "%s/x", wr.dir); + err = ray_col_save(ray_table_get_col_idx(next, 0), path); + } + TEST_ASSERT_EQ_I(err, RAY_OK); + /* Simulate an abrupt writer exit after staging but before finish(): + * the OS releases the writer lock, but no .current publication happens. + * Avoid fork() here; macOS sanitizer runtimes may terminate forked + * children before normal test-side status reporting runs. */ + TEST_ASSERT_EQ_I(ray_file_unlock(wr.lock), RAY_OK); + ray_file_close(wr.lock); + wr.lock = RAY_FD_INVALID; + TEST_ASSERT_TRUE(generation_matches(dir, false, 1)); + TEST_ASSERT_TRUE(generation_matches(dir, true, 1)); + TEST_ASSERT_EQ_I(ray_splay_save(old, dir, NULL), RAY_OK); + } + TEST_ASSERT_EQ_I(ray_splay_save(next, dir, NULL), RAY_OK); + TEST_ASSERT_TRUE(generation_matches(dir, true, 9)); + ray_release(next); + ray_release(old); + rm_rf(dir); + PASS(); +} + const test_entry_t splay_entries[] = { +#ifndef _WIN32 + { "splay/generation_prune_unlinks_symlink", test_generation_prune_unlinks_symlink, splay_setup, splay_teardown }, +#endif + { "splay/generation_io_failures", test_generation_io_failures, splay_setup, splay_teardown }, + { "splay/generation_retains_readers", test_generation_retains_readers, splay_setup, splay_teardown }, + { "splay/generation_invalid_manifest", test_generation_invalid_manifest, splay_setup, splay_teardown }, + { "splay/generation_writer_exit", test_generation_writer_exit, splay_setup, splay_teardown }, + { "splay/atomic_generation_publish", test_splay_atomic_generation_publish, splay_setup, splay_teardown }, { "splay/has_nulls_roundtrip", test_splayed_has_nulls_roundtrip, splay_setup, splay_teardown }, { "splay/save_null_dir", test_save_null_dir, splay_setup, splay_teardown }, { "splay/save_null_tbl", test_save_null_tbl, splay_setup, splay_teardown }, @@ -2393,6 +2794,7 @@ const test_entry_t splay_entries[] = { { "splay/load_dir_path_too_long", test_load_dir_path_too_long, splay_setup, splay_teardown }, { "splay/load_col_path_too_long", test_load_col_path_too_long, splay_setup, splay_teardown }, { "splay/save_bulk_with_sym_path", test_save_bulk_with_sym_path, splay_setup, splay_teardown }, + { "splay/save_staged_bulk_defers_sym_flush", test_save_staged_bulk_defers_sym_flush, splay_setup, splay_teardown }, { "splay/save_dir_path_too_long", test_save_dir_path_too_long, splay_setup, splay_teardown }, { "splay/save_col_path_too_long", test_save_col_path_too_long, splay_setup, splay_teardown }, { "splay/trace_valid_dir", test_trace_valid_dir, splay_setup, splay_teardown }, diff --git a/test/test_store.c b/test/test_store.c index 190a3eaef..f19448fb1 100644 --- a/test/test_store.c +++ b/test/test_store.c @@ -30,11 +30,14 @@ #include #include #include +#include #include "mem/heap.h" #include "ops/ops.h" #include "store/col.h" +#include "ops/idxop.h" #include "store/fileio.h" #include "store/splay.h" +#include "store/stream.h" #include "store/part.h" #include "store/serde.h" #include "core/ipc.h" @@ -58,6 +61,12 @@ #include #include #include +#include +#ifdef RAY_OS_LINUX +#include +#include +#include +#endif #define TMP_COL_PATH "/tmp/rayforce_test_col.dat" #define TMP_SPLAY_DIR "/tmp/rayforce_test_splay" @@ -1478,6 +1487,800 @@ static test_result_t test_file_rename_op(void) { PASS(); } +static test_result_t test_col_close_failure(void) { +#ifdef RAY_OS_LINUX + int64_t data[] = {1,2,3,4}; + ray_t* values[5]; + values[0] = ray_vec_from_raw(RAY_I64,data,4); + values[1] = ray_vec_new(RAY_STR,0); + values[1] = ray_str_vec_append(values[1],"a buffered string payload",25); + values[2] = ray_list_new(0); + ray_t* text = ray_str("a buffered string payload",25); + values[2] = ray_list_append(values[2],text); ray_release(text); + values[3] = ray_list_new(0); + values[3] = ray_list_append(values[3],values[0]); + values[4] = ray_table_new(0); + values[4] = ray_table_add_col(values[4],ray_sym_intern("v",1),values[0]); + char path[160], temp[180]; + snprintf(path,sizeof(path),"/tmp/rayforce-close-failure-%d",(int)getpid()); + snprintf(temp,sizeof(temp),"%s.tmp",path); + for (int type = 0; type < 5; type++) for (int durable = 0; durable < 2; durable++) { + TEST_ASSERT_NOT_NULL(values[type]); TEST_ASSERT_FALSE(RAY_IS_ERR(values[type])); + FILE* f = fopen(path,"wb"); TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(fwrite("original",1,8,f),8); TEST_ASSERT_EQ_I(fclose(f),0); + pid_t pid = fork(); TEST_ASSERT_TRUE(pid >= 0); + if (!pid) { + struct rlimit limit; + if (getrlimit(RLIMIT_FSIZE,&limit)) _exit(2); + limit.rlim_cur = 33; + if (signal(SIGXFSZ,SIG_IGN) == SIG_ERR || setrlimit(RLIMIT_FSIZE,&limit)) _exit(2); + ray_err_t err = durable ? ray_col_save(values[type],path) : ray_col_save_bulk(values[type],path); + _exit(err == 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); + f = fopen(path,"rb"); TEST_ASSERT_NOT_NULL(f); + char bytes[16]; size_t n = fread(bytes,1,sizeof(bytes),f); fclose(f); + TEST_ASSERT_EQ_I(n,8); TEST_ASSERT_TRUE(!memcmp(bytes,"original",8)); + TEST_ASSERT_TRUE(access(temp,F_OK) != 0); + } + unlink(path); + for (int i = 4; i >= 0; i--) ray_release(values[i]); + PASS(); +#else + SKIP("requires Linux RLIMIT_FSIZE fault injection"); +#endif +} + +/* A failed index append must leave the column loadable: without the index + * marker the loader requires the exact payload length, so a partial region + * would turn a best-effort accelerator into an unreadable column. */ +static test_result_t test_col_append_index_rollback(void) { +#ifdef RAY_OS_LINUX + int64_t n = 100000; + ray_t* v = ray_vec_new(RAY_I64, n); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + v->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(v))[i] = i * 3; + char path[160]; + snprintf(path, sizeof(path), "/tmp/rayforce-append-rollback-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_col_save(v, path), RAY_OK); + struct stat st; + TEST_ASSERT_EQ_I(stat(path, &st), 0); + off_t payload = st.st_size; + + ray_t* w = v; ray_retain(w); + ray_t* r = ray_index_attach_zone(&w); + TEST_ASSERT_TRUE(r && !RAY_IS_ERR(r)); + const ray_index_t* ix = ray_index_payload(w->index); + TEST_ASSERT_NOT_NULL(ix); + + pid_t pid = fork(); TEST_ASSERT_TRUE(pid >= 0); + if (!pid) { + struct rlimit limit; + if (getrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + limit.rlim_cur = (rlim_t)payload + 40; /* pad fits, region doesn't */ + if (signal(SIGXFSZ, SIG_IGN) == SIG_ERR || setrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + _exit(ray_col_append_index(path, ix, n, RAY_I64) != RAY_OK ? 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_EQ_I(stat(path, &st), 0); + TEST_ASSERT_EQ_I((int64_t)st.st_size, (int64_t)payload); + ray_t* back = ray_col_load(path); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_EQ_I(back->len, n); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(back))[n - 1], (n - 1) * 3); + ray_release(back); + + /* and the append still works once there is room */ + TEST_ASSERT_EQ_I(ray_col_append_index(path, ix, n, RAY_I64), RAY_OK); + TEST_ASSERT_EQ_I(stat(path, &st), 0); + TEST_ASSERT_TRUE(st.st_size > payload); + back = ray_col_load(path); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_EQ_I(back->len, n); + ray_release(back); + + ray_release(w); + ray_release(v); + unlink(path); + PASS(); +#else + SKIP("requires Linux RLIMIT_FSIZE fault injection"); +#endif +} + +/* Fill v with i*3, every 97th row null, rows [a, b) all null. */ +static ray_t* zone_test_col(int64_t n, int64_t null_from, int64_t null_to) { + ray_t* v = ray_vec_new(RAY_I64, n); + if (!v || RAY_IS_ERR(v)) return NULL; + v->len = n; + int64_t* d = (int64_t*)ray_data(v); + for (int64_t i = 0; i < n; i++) + d[i] = (i % 97 == 0 || (i >= null_from && i < null_to)) ? NULL_I64 : i * 3; + v->attrs |= 0x40; /* RAY_ATTR_HAS_NULLS */ + return v; +} + +static bool zone_equal(ray_t* a, ray_t* b) { + const ray_index_t* x = ray_index_payload(a); + const ray_index_t* y = ray_index_payload(b); + if (x->u.chunk_zone.n_chunks != y->u.chunk_zone.n_chunks) return false; + if (x->u.chunk_zone.is_f64 != y->u.chunk_zone.is_f64) return false; + size_t n = x->u.chunk_zone.n_chunks; + if (memcmp(ray_data(x->u.chunk_zone.mins), ray_data(y->u.chunk_zone.mins), n * 8)) return false; + if (memcmp(ray_data(x->u.chunk_zone.maxs), ray_data(y->u.chunk_zone.maxs), n * 8)) return false; + if (memcmp(ray_data(x->u.chunk_zone.null_bits), ray_data(y->u.chunk_zone.null_bits), (n + 7) / 8)) return false; + if ((x->u.chunk_zone.aggs == NULL) != (y->u.chunk_zone.aggs == NULL)) return false; + if (x->u.chunk_zone.aggs && + memcmp(ray_data(x->u.chunk_zone.aggs), ray_data(y->u.chunk_zone.aggs), n * 3 * 8)) return false; + return true; +} + +/* Uneven slices (70000 rows), an all-null chunk 2, equals the whole-column zone. */ +static test_result_t test_zone_acc_slices_equal_compute(void) { + int64_t n = 300000; + ray_t* v = zone_test_col(n, 131072, 196608); + TEST_ASSERT_NOT_NULL(v); + ray_zone_acc_t acc; + TEST_ASSERT_EQ_I(ray_zone_acc_init(&acc, RAY_I64, 0), RAY_OK); + for (int64_t off = 0; off < n; off += 70000) { + int64_t cnt = n - off < 70000 ? n - off : 70000; + ray_t* s = ray_vec_from_raw(RAY_I64, (int64_t*)ray_data(v) + off, cnt); + TEST_ASSERT_NOT_NULL(s); + TEST_ASSERT_EQ_I(ray_zone_acc_add(&acc, s), RAY_OK); + ray_release(s); + } + /* a zero-row append opens nothing */ + ray_t* empty = ray_vec_new(RAY_I64, 0); + TEST_ASSERT_EQ_I(ray_zone_acc_add(&acc, empty), RAY_OK); + ray_release(empty); + TEST_ASSERT_EQ_I(acc.n_chunks, 5); + ray_t* got = ray_zone_acc_finish(&acc, n); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got)); + ray_t* want = ray_index_chunk_zone_compute(v, 16); + TEST_ASSERT_TRUE(want && !RAY_IS_ERR(want)); + TEST_ASSERT_TRUE(zone_equal(got, want)); + const ray_index_t* ix = ray_index_payload(got); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ix->u.chunk_zone.mins))[2], INT64_MAX); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ix->u.chunk_zone.maxs))[2], INT64_MIN); + TEST_ASSERT_TRUE(((uint8_t*)ray_data(ix->u.chunk_zone.null_bits))[0] & (1u << 2)); + ray_release(got); ray_release(want); ray_release(v); + PASS(); +} + +/* Exactly one chunk; an append ending on the boundary opens no second chunk. */ +static test_result_t test_zone_acc_one_chunk(void) { + int64_t n = 65536; + ray_t* v = zone_test_col(n, 0, 0); + TEST_ASSERT_NOT_NULL(v); + ray_zone_acc_t acc; + TEST_ASSERT_EQ_I(ray_zone_acc_init(&acc, RAY_I64, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_zone_acc_add(&acc, v), RAY_OK); + TEST_ASSERT_EQ_I(acc.n_chunks, 1); + ray_t* got = ray_zone_acc_finish(&acc, n); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got)); + TEST_ASSERT_EQ_I(ray_index_payload(got)->u.chunk_zone.n_chunks, 1); + ray_release(got); + /* below the gate: nothing */ + ray_zone_acc_t small; + TEST_ASSERT_EQ_I(ray_zone_acc_init(&small, RAY_I64, 0), RAY_OK); + v->len = 65535; + TEST_ASSERT_EQ_I(ray_zone_acc_add(&small, v), RAY_OK); + TEST_ASSERT_NULL(ray_zone_acc_finish(&small, 65535)); + v->len = n; + ray_release(v); + PASS(); +} + +/* Two accumulators split mid-chunk (at row 100000) merge into the whole. */ +static test_result_t test_zone_acc_merge_mid_chunk(void) { + int64_t n = 200000, split = 100000; + ray_t* v = zone_test_col(n, 0, 0); + TEST_ASSERT_NOT_NULL(v); + ray_t* lo = ray_vec_from_raw(RAY_I64, ray_data(v), split); + ray_t* hi = ray_vec_from_raw(RAY_I64, (int64_t*)ray_data(v) + split, n - split); + TEST_ASSERT_TRUE(lo && hi); + ray_zone_acc_t a, b; + TEST_ASSERT_EQ_I(ray_zone_acc_init(&a, RAY_I64, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_zone_acc_init(&b, RAY_I64, split), RAY_OK); + TEST_ASSERT_EQ_I(ray_zone_acc_add(&b, hi), RAY_OK); /* later range first */ + TEST_ASSERT_EQ_I(ray_zone_acc_add(&a, lo), RAY_OK); + TEST_ASSERT_EQ_I(ray_zone_acc_merge(&a, &b), RAY_OK); + ray_zone_acc_free(&b); + ray_t* got = ray_zone_acc_finish(&a, n); + ray_t* want = ray_index_chunk_zone_compute(v, 16); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && want && !RAY_IS_ERR(want)); + TEST_ASSERT_TRUE(zone_equal(got, want)); + ray_release(got); ray_release(want); ray_release(lo); ray_release(hi); ray_release(v); + PASS(); +} + +/* F64 with NaN nulls: float arrays, no aggs. */ +static test_result_t test_zone_acc_float(void) { + int64_t n = 150000; + ray_t* v = ray_vec_new(RAY_F64, n); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + v->len = n; + double* d = (double*)ray_data(v); + for (int64_t i = 0; i < n; i++) d[i] = (i % 1000 == 7) ? NAN : (double)i * 0.5; + v->attrs |= 0x40; /* RAY_ATTR_HAS_NULLS */ + ray_zone_acc_t acc; + TEST_ASSERT_EQ_I(ray_zone_acc_init(&acc, RAY_F64, 0), RAY_OK); + for (int64_t off = 0; off < n; off += 40000) { + int64_t cnt = n - off < 40000 ? n - off : 40000; + ray_t* s = ray_vec_from_raw(RAY_F64, d + off, cnt); + TEST_ASSERT_EQ_I(ray_zone_acc_add(&acc, s), RAY_OK); + ray_release(s); + } + ray_t* got = ray_zone_acc_finish(&acc, n); + ray_t* want = ray_index_chunk_zone_compute(v, 16); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && want && !RAY_IS_ERR(want)); + TEST_ASSERT_TRUE(zone_equal(got, want)); + TEST_ASSERT_NULL(ray_index_payload(got)->u.chunk_zone.aggs); + ray_release(got); ray_release(want); ray_release(v); + PASS(); +} + +static ray_t* dict_test_col(int64_t n, int64_t distinct, bool unique) { + ray_t* v = ray_vec_new(RAY_STR, n); + if (!v || RAY_IS_ERR(v)) return NULL; + for (int64_t i = 0; i < n; i++) { + char buf[64]; + int len = unique ? snprintf(buf, sizeof(buf), "a long pooled unique string %lld", (long long)i) + : (i % 1009 == 0 ? 0 : snprintf(buf, sizeof(buf), "v%lld", (long long)(i % distinct))); + v = ray_str_vec_append(v, buf, (size_t)len); + if (!v || RAY_IS_ERR(v)) return NULL; + } + return v; +} + +/* Slices of 30000 rows, empty strings included, equals ray_index_dict_compute. */ +static test_result_t test_dict_acc_slices_equal_compute(void) { + int64_t n = 100000; + ray_t* v = dict_test_col(n, 3000, false); + TEST_ASSERT_NOT_NULL(v); + ray_dict_acc_t acc; + TEST_ASSERT_EQ_I(ray_dict_acc_init(&acc), RAY_OK); + for (int64_t off = 0; off < n; off += 30000) { + int64_t cnt = n - off < 30000 ? n - off : 30000; + ray_t* s = ray_vec_new(RAY_STR, cnt); + for (int64_t i = 0; i < cnt; i++) { + size_t len; const char* p = ray_str_vec_get(v, off + i, &len); + s = ray_str_vec_append(s, p, len); + } + TEST_ASSERT_EQ_I(ray_dict_acc_add(&acc, s), RAY_OK); + ray_release(s); + } + ray_t* got = ray_dict_acc_finish(&acc, n); + ray_t* want = ray_index_dict_compute(v); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && want && !RAY_IS_ERR(want)); + const ray_index_t* x = ray_index_payload(got); + const ray_index_t* y = ray_index_payload(want); + TEST_ASSERT_EQ_I(x->u.dict.n_distinct, y->u.dict.n_distinct); + TEST_ASSERT_EQ_I(x->u.dict.n_distinct, 3001); /* 3000 values plus "" */ + TEST_ASSERT_EQ_I(memcmp(ray_data(x->u.dict.codes), ray_data(y->u.dict.codes), (size_t)n * 4), 0); + TEST_ASSERT_EQ_I(memcmp(ray_data(x->u.dict.first_occ), ray_data(y->u.dict.first_occ), + (size_t)x->u.dict.n_distinct * 4), 0); + ray_release(got); ray_release(want); ray_release(v); + PASS(); +} + +/* Leading empty strings (NULL pool at the first distinct value), then + * 70000 rows over 100 values, in two slices: equals ray_index_dict_compute. */ +static test_result_t test_dict_acc_leading_empty(void) { + int64_t n = 70003; + ray_t* v = ray_vec_new(RAY_STR, n); + TEST_ASSERT_NOT_NULL(v); + v = ray_str_vec_append(v, "", 0); + v = ray_str_vec_append(v, "", 0); + v = ray_str_vec_append(v, "a", 1); + for (int64_t i = 0; i < 70000; i++) { + char buf[32]; int len = snprintf(buf, sizeof(buf), "v%lld", (long long)(i % 100)); + v = ray_str_vec_append(v, buf, (size_t)len); + } + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + ray_dict_acc_t acc; + TEST_ASSERT_EQ_I(ray_dict_acc_init(&acc), RAY_OK); + int64_t cuts[3] = {0, 35000, n}; + for (int k = 0; k < 2; k++) { + ray_t* s = ray_vec_new(RAY_STR, cuts[k + 1] - cuts[k]); + for (int64_t i = cuts[k]; i < cuts[k + 1]; i++) { + size_t len; const char* p = ray_str_vec_get(v, i, &len); + s = ray_str_vec_append(s, p, len); + } + TEST_ASSERT_EQ_I(ray_dict_acc_add(&acc, s), RAY_OK); + ray_release(s); + } + ray_t* got = ray_dict_acc_finish(&acc, n); + ray_t* want = ray_index_dict_compute(v); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got) && want && !RAY_IS_ERR(want)); + const ray_index_t* x = ray_index_payload(got); + const ray_index_t* y = ray_index_payload(want); + TEST_ASSERT_EQ_I(x->u.dict.n_distinct, y->u.dict.n_distinct); + TEST_ASSERT_EQ_I(x->u.dict.n_distinct, 102); /* "", "a", v0..v99 */ + TEST_ASSERT_EQ_I(memcmp(ray_data(x->u.dict.codes), ray_data(y->u.dict.codes), (size_t)n * 4), 0); + TEST_ASSERT_EQ_I(memcmp(ray_data(x->u.dict.first_occ), ray_data(y->u.dict.first_occ), + (size_t)x->u.dict.n_distinct * 4), 0); + ray_release(got); ray_release(want); ray_release(v); + PASS(); +} + +/* 70000 unique strings: no cap, the dictionary equals the whole-column one. */ +static test_result_t test_dict_acc_high_cardinality(void) { + int64_t n = 70000; + ray_t* v = dict_test_col(n, 0, true); + TEST_ASSERT_NOT_NULL(v); + ray_dict_acc_t acc; + TEST_ASSERT_EQ_I(ray_dict_acc_init(&acc), RAY_OK); + TEST_ASSERT_EQ_I(ray_dict_acc_add(&acc, v), RAY_OK); + TEST_ASSERT_FALSE(acc.dead); + ray_t* got = ray_dict_acc_finish(&acc, n); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got)); + ray_t* want = ray_index_dict_compute(v); + TEST_ASSERT_TRUE(want && !RAY_IS_ERR(want)); + const ray_index_t* g = ray_index_payload(got); + const ray_index_t* w = ray_index_payload(want); + TEST_ASSERT_EQ_I(g->u.dict.n_distinct, 70000); + TEST_ASSERT_EQ_I(g->u.dict.n_distinct, w->u.dict.n_distinct); + TEST_ASSERT_EQ_I(memcmp(ray_data(g->u.dict.codes), ray_data(w->u.dict.codes), (size_t)n * 4), 0); + TEST_ASSERT_EQ_I(memcmp(ray_data(g->u.dict.first_occ), ray_data(w->u.dict.first_occ), + (size_t)w->u.dict.n_distinct * 4), 0); + ray_release(got); ray_release(want); + /* below the gate: nothing */ + ray_dict_acc_t small; + TEST_ASSERT_EQ_I(ray_dict_acc_init(&small), RAY_OK); + v->len = 1000; + TEST_ASSERT_EQ_I(ray_dict_acc_add(&small, v), RAY_OK); + TEST_ASSERT_NULL(ray_dict_acc_finish(&small, 1000)); + v->len = n; + ray_release(v); + PASS(); +} + +/* Stream a 200000-row I64 column in 70000-row slices; the file carries the + * zone and loads with it. Values are clustered so no hash is wanted. */ +static test_result_t test_stream_inline_zone(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-zone-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + 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_index_begin(&w, 0), RAY_OK); + for (int64_t off = 0; off < n; off += 70000) { + int64_t cnt = n - off < 70000 ? n - off : 70000; + ray_t* s = ray_vec_from_raw(RAY_I64, (int64_t*)ray_data(v) + off, cnt); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w, s), RAY_OK); + 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)); + TEST_ASSERT_EQ_I(back->len, n); + TEST_ASSERT_TRUE(back->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_EQ_I(ray_index_kind(back), RAY_IDX_CHUNK_ZONE); + ray_t* want = ray_index_chunk_zone_compute(v, 16); + TEST_ASSERT_TRUE(zone_equal(back->index, want)); + /* the region is what ray_col_append_index would have written */ + ray_t* plain = zone_test_col(n, 0, 0); + char ref[200]; snprintf(ref, sizeof(ref), "%s/ref", dir); + TEST_ASSERT_EQ_I(ray_col_save_bulk(plain, ref), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_append_index(ref, ray_index_payload(want), n, RAY_I64), RAY_OK); + struct stat a, b; + TEST_ASSERT_EQ_I(stat(path, &a), 0); TEST_ASSERT_EQ_I(stat(ref, &b), 0); + TEST_ASSERT_EQ_I((int64_t)a.st_size, (int64_t)b.st_size); + { + size_t sz = (size_t)a.st_size; + uint8_t* ba = (uint8_t*)malloc(sz); uint8_t* bb = (uint8_t*)malloc(sz); + TEST_ASSERT_TRUE(ba && bb); + FILE* fa = fopen(path, "rb"); FILE* fb = fopen(ref, "rb"); + TEST_ASSERT_TRUE(fa && fb); + TEST_ASSERT_EQ_I((int64_t)fread(ba, 1, sz, fa), (int64_t)sz); + TEST_ASSERT_EQ_I((int64_t)fread(bb, 1, sz, fb), (int64_t)sz); + fclose(fa); fclose(fb); + TEST_ASSERT_EQ_I(memcmp(ba, bb, sz), 0); + free(ba); free(bb); + } + ray_release(want); ray_release(back); ray_release(plain); ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* A sentinel typed as a value in a slice WITHOUT HAS_NULLS is still a null: + * the accumulator decides by the sentinel value (col.c #495). */ +static test_result_t test_zone_acc_sentinel_without_flag(void) { + int64_t n = 70000; + ray_t* v = ray_vec_new(RAY_I64, n); + TEST_ASSERT_TRUE(v && !RAY_IS_ERR(v)); + v->len = n; + int64_t* d = (int64_t*)ray_data(v); + for (int64_t i = 0; i < n; i++) d[i] = i * 3 + 5; + d[7] = INT64_MIN; + TEST_ASSERT_FALSE(v->attrs & RAY_ATTR_HAS_NULLS); + ray_zone_acc_t acc; + TEST_ASSERT_EQ_I(ray_zone_acc_init(&acc, RAY_I64, 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_zone_acc_add(&acc, v), RAY_OK); + TEST_ASSERT_TRUE(acc.saw_null); + TEST_ASSERT_EQ_I(acc.nn[0], 65535); + ray_t* got = ray_zone_acc_finish(&acc, n); + TEST_ASSERT_TRUE(got && !RAY_IS_ERR(got)); + const ray_index_t* ix = ray_index_payload(got); + TEST_ASSERT_TRUE(((uint8_t*)ray_data(ix->u.chunk_zone.null_bits))[0] & 1u); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(ix->u.chunk_zone.mins))[0], 5); /* row 0 */ + v->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* want = ray_index_chunk_zone_compute(v, 16); + TEST_ASSERT_TRUE(want && !RAY_IS_ERR(want)); + TEST_ASSERT_TRUE(zone_equal(got, want)); + ray_release(got); ray_release(want); ray_release(v); + PASS(); +} + +/* Writer level: slice 1 carries a sentinel without the flag, slice 2 the + * flag; the file header must publish HAS_NULLS and the zone must agree with + * the loaded column. */ +static test_result_t test_stream_sentinel_publishes_has_nulls(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-sent-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + int64_t n = 70000; + ray_t* s1 = ray_vec_new(RAY_I64, n); s1->len = n; + ray_t* s2 = ray_vec_new(RAY_I64, n); s2->len = n; + for (int64_t i = 0; i < n; i++) { + ((int64_t*)ray_data(s1))[i] = i * 3; + ((int64_t*)ray_data(s2))[i] = (i % 50 == 0) ? NULL_I64 : (n + i) * 3; + } + ((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_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)); + TEST_ASSERT_EQ_I(back->len, 2 * n); + TEST_ASSERT_TRUE(back->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_TRUE(back->attrs & RAY_ATTR_HAS_INDEX); + ray_t* copy = ray_vec_from_raw(RAY_I64, ray_data(back), back->len); + TEST_ASSERT_TRUE(copy && !RAY_IS_ERR(copy)); + copy->attrs |= RAY_ATTR_HAS_NULLS; + ray_t* want = ray_index_chunk_zone_compute(copy, 16); + TEST_ASSERT_TRUE(want && !RAY_IS_ERR(want)); + TEST_ASSERT_TRUE(zone_equal(back->index, want)); + TEST_ASSERT_TRUE(((int64_t*)ray_data(ray_index_payload(back->index)->u.chunk_zone.mins))[0] != INT64_MIN); + ray_release(want); ray_release(copy); ray_release(back); + ray_release(s1); ray_release(s2); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* An index region that cannot be written (ENOSPC/EFBIG) is dropped: close + * cuts the file back to the payload and publishes the column without the + * index. Everything runs in the forked child so no FILE* state is shared + * with the parent; the child exits 0 only if close returned RAY_OK. */ +static test_result_t test_stream_index_write_failure_drops_index(void) { +#ifdef RAY_OS_LINUX + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-enospc-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + int64_t n = 70000; + ray_t* v = zone_test_col(n, 0, 0); + TEST_ASSERT_NOT_NULL(v); + int64_t* d = (int64_t*)ray_data(v); + for (int64_t i = 0; i < n; i++) d[i] = i * 3; /* clustered, no nulls */ + v->attrs &= (uint8_t)~RAY_ATTR_HAS_NULLS; + char path[200]; snprintf(path, sizeof(path), "%s/c", dir); + 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_index_begin(&w, 0) != RAY_OK) _exit(2); + if (ray_col_stream_append(&w, v) != RAY_OK) _exit(2); + struct rlimit limit; + if (getrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + limit.rlim_cur = (rlim_t)(32 + n * 8 + 40); + if (signal(SIGXFSZ, SIG_IGN) == SIG_ERR || setrlimit(RLIMIT_FSIZE, &limit)) _exit(2); + _exit(ray_col_stream_close(&w, false) == RAY_OK ? 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); + struct stat st; + TEST_ASSERT_EQ_I(stat(path, &st), 0); + TEST_ASSERT_EQ_I((int64_t)st.st_size, 32 + n * 8); + ray_t* back = ray_col_mmap(path); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_EQ_I(back->len, n); + TEST_ASSERT_FALSE(back->attrs & RAY_ATTR_HAS_INDEX); + TEST_ASSERT_EQ_I(((int64_t*)ray_data(back))[n - 1], (n - 1) * 3); + ray_release(back); ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +#else + SKIP("requires Linux RLIMIT_FSIZE fault injection"); +#endif +} + +/* Exactly 65536 rows: one chunk, a zone, never a hash candidate. */ +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); + int64_t n = 65536; + 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_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)); + TEST_ASSERT_EQ_I(ray_index_kind(back), RAY_IDX_CHUNK_ZONE); + ray_release(back); ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +/* 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); + 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); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_EQ_I(ray_index_kind(back), RAY_IDX_HASH); + ray_release(back); ray_release(v); + (void)ray_test_rm_rf(dir); + 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); + PASS(); +} + +/* The index region streamed to a file (block by block) is byte-identical to + * the one the buffered writer lays out in memory, for every public index kind. */ +static bool region_file_matches_buffer(ray_t* w) { + if (!w || RAY_IS_ERR(w) || !w->index) return false; + const ray_index_t* ix = ray_index_payload(w->index); + int64_t size = ray_index_inline_size(ix); + uint8_t* buf = (uint8_t*)ray_calloc_raw((size_t)size); + uint8_t* back = (uint8_t*)ray_calloc_raw((size_t)size + 1); + FILE* f = tmpfile(); + bool ok = buf && back && f; + if (ok) { + ray_index_inline_write(buf, ix); + ok = ray_index_inline_write_file(f, ix) && fflush(f) == 0 && + ftell(f) == (long)size && fseek(f, 0, SEEK_SET) == 0 && + fread(back, 1, (size_t)size + 1, f) == (size_t)size && /* nothing beyond size */ + memcmp(buf, back, (size_t)size) == 0; + } + if (f) fclose(f); + ray_free_raw(buf); ray_free_raw(back); + return ok; +} + +static test_result_t test_stream_region_bytes_match(void) { + int64_t n = 70001; /* child lengths are not multiples of 32: the pad path runs */ + ray_t* v = zone_test_col(n, 0, 0); + TEST_ASSERT_NOT_NULL(v); + ray_t* w = v; + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_chunk_zone(&w, 16))); + TEST_ASSERT_EQ_I(ray_index_kind(w), RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_NOT_NULL(ray_index_payload(w->index)->u.chunk_zone.aggs); + TEST_ASSERT_TRUE(region_file_matches_buffer(w)); + ray_release(w); + + ray_t* f64 = ray_vec_new(RAY_F64, n); f64->len = n; + for (int64_t i = 0; i < n; i++) ((double*)ray_data(f64))[i] = (double)(i % 1013) * 0.5; + w = f64; + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_chunk_zone(&w, 16))); + TEST_ASSERT_EQ_I(ray_index_kind(w), RAY_IDX_CHUNK_ZONE); + TEST_ASSERT_NULL(ray_index_payload(w->index)->u.chunk_zone.aggs); + TEST_ASSERT_TRUE(region_file_matches_buffer(w)); + ray_release(w); + + w = dict_test_col(n, 3000, false); + TEST_ASSERT_NOT_NULL(w); + TEST_ASSERT_FALSE(RAY_IS_ERR(ray_index_attach_dict(&w))); + TEST_ASSERT_EQ_I(ray_index_kind(w), RAY_IDX_DICT); + TEST_ASSERT_TRUE(region_file_matches_buffer(w)); + ray_release(w); + + ray_t* h = ray_vec_new(RAY_I64, n); h->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(h))[i] = (i * 7919) % 1009; + w = ray_idx_hash_fn(h); + TEST_ASSERT_TRUE(w && !RAY_IS_ERR(w)); + TEST_ASSERT_EQ_I(ray_index_kind(w), RAY_IDX_HASH); + TEST_ASSERT_TRUE(region_file_matches_buffer(w)); + ray_release(w); + + int kinds = 3; + for (int k = 0; k < kinds; k++) { + ray_t* z = ray_vec_new(RAY_I64, n); z->len = n; + for (int64_t i = 0; i < n; i++) ((int64_t*)ray_data(z))[i] = (i * 7919) % 100003; + w = z; + ray_t* r = k == 0 ? ray_index_attach_zone(&w) + : k == 1 ? ray_index_attach_sort(&w) : ray_index_attach_bloom(&w); + TEST_ASSERT_FALSE(RAY_IS_ERR(r)); + TEST_ASSERT_EQ_I(ray_index_kind(w), k == 0 ? RAY_IDX_ZONE : k == 1 ? RAY_IDX_SORT : RAY_IDX_BLOOM); + TEST_ASSERT_TRUE(region_file_matches_buffer(w)); + ray_release(w); + } + PASS(); +} + +static bool stream_dir_has_tmp(const char* dir) { + DIR* d = opendir(dir); + bool found = false; + struct dirent* e; + while (d && (e = readdir(d))) + if (!strncmp(e->d_name, ".stream-", 8)) found = true; + if (d) closedir(d); + return found; +} + +/* One writer's finish fails; close_all returns the error and nothing is + * published: no column file, no tmp or pool file, no retained index. + * Injection: the failing writer's FILE* is replaced by a read-only stream on + * its own tmp file, so every write the finish attempts (index region, header) + * fails with EBADF and the run needs neither timing nor an interrupt (which + * would also cancel the healthy columns nondeterministically). */ +static test_result_t test_stream_finish_failure_publishes_nothing(void) { + char dir[160]; snprintf(dir, sizeof(dir), "/tmp/rayforce-stream-fail-%d", (int)getpid()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + int64_t n = 300000; + ray_t* a = ray_vec_new(RAY_I64, n); a->len = n; + 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 */ + } + ray_t* s = dict_test_col(100000, 3000, false); + ray_t* cols[3] = { a, b, s }; + int8_t types[3] = { RAY_I64, RAY_I64, RAY_STR }; + 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_index_begin(&w[c], 0), RAY_OK); + TEST_ASSERT_EQ_I(ray_col_stream_append(&w[c], cols[c]), RAY_OK); + } + TEST_ASSERT_EQ_I(fclose(w[0].fp), 0); + w[0].fp = fopen(w[0].tmp_path, "rb"); + TEST_ASSERT_NOT_NULL(w[0].fp); + ray_err_t e = ray_col_stream_close_all(w, 3, false, NULL); + TEST_ASSERT_EQ_I(e, RAY_ERR_IO); + 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)); + ray_release(a); ray_release(b); ray_release(s); + (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()); + TEST_ASSERT_EQ_I(ray_test_mkdir_p(dir), 0); + 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_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); + char path[200]; snprintf(path, sizeof(path), "%s/s", dir); + ray_t* back = ray_col_mmap(path); + TEST_ASSERT_TRUE(back && !RAY_IS_ERR(back)); + TEST_ASSERT_TRUE(back->attrs & RAY_ATTR_HAS_NULLS); + TEST_ASSERT_EQ_I(ray_index_kind(back), RAY_IDX_DICT); + TEST_ASSERT_EQ_I(ray_index_payload(back->index)->u.dict.n_distinct, 3001); + ray_release(back); ray_release(v); + (void)ray_test_rm_rf(dir); + PASS(); +} + +static test_result_t test_file_rename_new(void) { +#ifdef RAY_OS_WASM + SKIP("exclusive rename is unavailable on this host"); +#else + char from[160], to[160], marker[180]; + snprintf(from,sizeof(from),"/tmp/rayforce-publish-from-%d",(int)getpid()); + snprintf(to,sizeof(to),"/tmp/rayforce-publish-to-%d",(int)getpid()); + TEST_ASSERT_EQ_I(ray_mkdir(from),RAY_OK); TEST_ASSERT_EQ_I(ray_mkdir(to),RAY_OK); + snprintf(marker,sizeof(marker),"%s/marker",from); + FILE* f = fopen(marker,"wb"); TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(fwrite("retained",1,8,f),8); TEST_ASSERT_EQ_I(fclose(f),0); + /* Ordinary POSIX rename would replace this empty directory. */ + TEST_ASSERT_EQ_I(ray_file_rename_new(from,to),RAY_ERR_IO); + TEST_ASSERT_TRUE(access(marker,F_OK) == 0); + TEST_ASSERT_EQ_I(rmdir(to),0); + TEST_ASSERT_EQ_I(ray_file_rename_new(from,to),RAY_OK); + TEST_ASSERT_TRUE(access(from,F_OK) != 0); + snprintf(marker,sizeof(marker),"%s/marker",to); + f = fopen(marker,"rb"); TEST_ASSERT_NOT_NULL(f); + char bytes[8]; TEST_ASSERT_EQ_I(fread(bytes,1,8,f),8); fclose(f); + TEST_ASSERT_TRUE(!memcmp(bytes,"retained",8)); + TEST_ASSERT_EQ_I(ray_file_rename_new(NULL,to),RAY_ERR_IO); + unlink(marker); rmdir(to); + PASS(); +#endif +} + +/* The portable fallback used where the host or filesystem has no + * no-replace rename: same contract as ray_file_rename_new. */ +static test_result_t test_file_rename_new_emulated(void) { +#if defined(RAY_OS_WASM) || defined(RAY_OS_WINDOWS) + SKIP("POSIX fallback"); +#else + char from[160], to[160], marker[180]; + snprintf(from,sizeof(from),"/tmp/rayforce-emu-from-%d",(int)getpid()); + snprintf(to,sizeof(to),"/tmp/rayforce-emu-to-%d",(int)getpid()); + TEST_ASSERT_EQ_I(ray_mkdir(from),RAY_OK); TEST_ASSERT_EQ_I(ray_mkdir(to),RAY_OK); + snprintf(marker,sizeof(marker),"%s/marker",from); + FILE* f = fopen(marker,"wb"); TEST_ASSERT_NOT_NULL(f); + TEST_ASSERT_EQ_I(fwrite("retained",1,8,f),8); TEST_ASSERT_EQ_I(fclose(f),0); + /* an existing (empty) directory is not replaced */ + TEST_ASSERT_EQ_I(ray_file_rename_new_emulated(from,to),RAY_ERR_IO); + TEST_ASSERT_TRUE(access(marker,F_OK) == 0); + TEST_ASSERT_EQ_I(rmdir(to),0); + TEST_ASSERT_EQ_I(ray_file_rename_new_emulated(from,to),RAY_OK); + TEST_ASSERT_TRUE(access(from,F_OK) != 0); + snprintf(marker,sizeof(marker),"%s/marker",to); + TEST_ASSERT_TRUE(access(marker,F_OK) == 0); + /* files: an existing destination is kept, a new one is published */ + char other[180]; + snprintf(other,sizeof(other),"%s/other",to); + f = fopen(other,"wb"); TEST_ASSERT_NOT_NULL(f); fputs("x",f); fclose(f); + TEST_ASSERT_EQ_I(ray_file_rename_new_emulated(other,marker),RAY_ERR_IO); + TEST_ASSERT_TRUE(access(other,F_OK) == 0); + unlink(marker); + TEST_ASSERT_EQ_I(ray_file_rename_new_emulated(other,marker),RAY_OK); + TEST_ASSERT_TRUE(access(other,F_OK) != 0 && access(marker,F_OK) == 0); + unlink(marker); rmdir(to); + PASS(); +#endif +} + /* ---- test_file_shared_lock_concurrent ---------------------------------- */ static test_result_t test_file_shared_lock_concurrent(void) { @@ -5447,6 +6250,27 @@ const test_entry_t store_entries[] = { { "store/file_lock_unlock", test_file_lock_unlock, store_setup, store_teardown }, { "store/file_sync", test_file_sync_op, store_setup, store_teardown }, { "store/file_rename", test_file_rename_op, store_setup, store_teardown }, + { "store/col_close_failure", test_col_close_failure, store_setup, store_teardown }, + { "store/col_append_index_rollback", test_col_append_index_rollback, store_setup, store_teardown }, + { "store/zone_acc_slices_equal_compute", test_zone_acc_slices_equal_compute, store_setup, store_teardown }, + { "store/zone_acc_one_chunk", test_zone_acc_one_chunk, store_setup, store_teardown }, + { "store/zone_acc_merge_mid_chunk", test_zone_acc_merge_mid_chunk, store_setup, store_teardown }, + { "store/zone_acc_float", test_zone_acc_float, store_setup, store_teardown }, + { "store/dict_acc_slices_equal_compute", test_dict_acc_slices_equal_compute, store_setup, store_teardown }, + { "store/dict_acc_leading_empty", test_dict_acc_leading_empty, store_setup, store_teardown }, + { "store/dict_acc_high_cardinality", test_dict_acc_high_cardinality, store_setup, store_teardown }, + { "store/stream_inline_zone", test_stream_inline_zone, store_setup, store_teardown }, + { "store/zone_acc_sentinel_without_flag", test_zone_acc_sentinel_without_flag, store_setup, store_teardown }, + { "store/stream_sentinel_has_nulls", test_stream_sentinel_publishes_has_nulls, 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/stream_inline_dict", test_stream_inline_dict, store_setup, store_teardown }, + { "store/stream_hash_wave", test_stream_hash_wave, store_setup, store_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/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 }, { "store/sym_col_bounds_reject", test_sym_col_bounds_reject, store_setup, store_teardown }, { "store/sym_col_count_mismatch", test_sym_col_count_mismatch, store_setup, store_teardown }, diff --git a/test/test_stress_matrix.c b/test/test_stress_matrix.c index a9d75dad2..45ca15fa2 100644 --- a/test/test_stress_matrix.c +++ b/test/test_stress_matrix.c @@ -348,7 +348,16 @@ static test_result_t test_matrix_shared_domain_layout(void) { * (bytes 0-15 aux, then mmod/order/type/attrs — store/col.c "Column file * format"). Returns RAY_SYM_W8/W16/W32/W64 or -1 on I/O failure. */ static int disk_sym_width(const char* col_path) { - FILE* f = fopen(col_path, "rb"); + /* Keep inspecting the raw header, but in the selected generation. */ + char dir[1024], resolved[1024], path[1200]; + const char* slash = strrchr(col_path, '/'); + if (!slash || (size_t)(slash - col_path) >= sizeof(dir)) return -1; + memcpy(dir, col_path, (size_t)(slash - col_path)); + dir[slash - col_path] = '\0'; + if (ray_splay_resolve_dir(dir, resolved, sizeof(resolved)) != RAY_OK) return -1; + int n = snprintf(path, sizeof(path), "%s/%s", resolved, slash + 1); + if (n < 0 || (size_t)n >= sizeof(path)) return -1; + FILE* f = fopen(path, "rb"); if (!f) return -1; if (fseek(f, (long)offsetof(ray_t, attrs), SEEK_SET) != 0) { fclose(f); diff --git a/test/test_types.c b/test/test_types.c index 3a17d5d8c..70893ab44 100644 --- a/test/test_types.c +++ b/test/test_types.c @@ -118,6 +118,21 @@ static test_result_t test_version_getters(void) { PASS(); } +/* ---- test_git_commit --------------------------------------------------- */ + +/* The exported commit is the one the build embedded, which the REPL and + * crash banners print too. */ +static test_result_t test_git_commit(void) { + const char* c = ray_git_commit(); + TEST_ASSERT_NOT_NULL(c); + TEST_ASSERT(c[0] != '\0', "commit string is empty"); +#ifdef RAYFORCE_GIT_COMMIT + TEST_ASSERT(strcmp(c, RAYFORCE_GIT_COMMIT) == 0, "commit differs from the build's"); +#endif + TEST_ASSERT(ray_git_commit() == c, "commit is a constant"); + PASS(); +} + /* ---- test_version_string ----------------------------------------------- */ static test_result_t test_version_string(void) { @@ -188,6 +203,7 @@ const test_entry_t types_entries[] = { { "types/sizes_pointer_types", test_type_sizes_pointer_types, NULL, NULL }, { "types/version_getters", test_version_getters, NULL, NULL }, { "types/version_string", test_version_string, NULL, NULL }, + { "types/git_commit", test_git_commit, NULL, NULL }, { "types/fn_name_builtin", test_fn_name_builtin, types_runtime_setup, types_runtime_teardown }, { NULL, NULL, NULL, NULL }, };